MyList - step 1
MyList
We will create a MyList similar to the List in the standard libraries
We start with a trait
trait MyList[A]:
def isEmpty: Boolean
def head: A
def tail: MyList[A]
Exercise
Implement the trait in a Cons node and an Empty node And then create a MyList with them.
case class Empty[A]() extends MyList[A]
case class Cons[A]() extends MyList[A]
Cons
We put the head and tail in the constructor
case class Cons[A](override val head: A, override val tail: MyList[A]) extends MyList[A]:
override def isEmpty: Boolean = false
main
@main
def main(): Unit =
val myList: MyList[Int] = Cons(1, Cons(2, Cons(3, Empty())))
println(myList)
// Cons(1,Cons(2,Cons(3,Empty())))