Skip to content
Snippets Groups Projects
Commit 8a9bca1f authored by Alexander Gehrke's avatar Alexander Gehrke
Browse files

[lec02] Scala 3 migration

parent 2ab69e12
Branches readerwriter
No related tags found
No related merge requests found
package datastructures
sealed trait List[+A]:
def head = this match
enum List[+A]:
case Nil
case Cons(_head: A, _tail: List[A])
def head: A = this match
case Nil => sys.error("head of empty list")
case Cons(a, _) => a
/** removes the first element of a list and returns the rest */
def tail: List[A] = ???
/** returns all but the last element of a list */
def init: List[A] = ???
/** replaces the first element of a list */
def setHead[AA >: A](head: AA): List[AA] = ???
/** recurses through the list, combining elements with the given function
* Uncomment the annotation to enable checking for tail-recursiveness */
//@annotation.tailrec
def foldLeft[B](z: B)(f: (B, A) => B): B = ???
case object Nil extends List[Nothing]
case class Cons[+A](elem: A, rest: List[A]) extends List[A]
object List:
/** construct a list by passing elements
*
* Remember: `apply` makes the object behave like a function,
* you can call it as `List(elem1, elem2,...)`
**/
def apply[A](as: A*): List[A] =
if as.isEmpty then Nil
else Cons(as.head, apply(as.tail: _*))
......@@ -12,13 +12,13 @@ class ListSpec extends AnyFlatSpec with Matchers with AppendedClues with Pending
"A list" should "have a tail function that removes the first element" in {
numbers.tail shouldBe List(2, 3, 4, 5)
single.tail shouldBe Nil
single.tail shouldBe List.Nil
a[RuntimeException] should be thrownBy List().tail
}
it should "have a init function that removes the last element" in {
numbers.init shouldBe List(1, 2, 3, 4)
single.init shouldBe Nil
single.init shouldBe List.Nil
a[RuntimeException] should be thrownBy List().init
}
......@@ -31,4 +31,4 @@ class ListSpec extends AnyFlatSpec with Matchers with AppendedClues with Pending
strings.foldLeft("X")(_ + _) should not be "Xcba" withClue ", this looks like a right fold with flipped args"
strings.foldLeft("X")(_ + _) shouldBe "Xabc"
}
}
\ No newline at end of file
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment