So I've got my version of List class in scala:
sealed trait List[+A] {
(...)
}
case object Nil extends List[Nothing]
case class Cons[+A](_head: A, _tail: List[A]) extends List[A]
now I'm trying to write reverse
in terms of my foldLeft
which is the following:
@annotation.tailrec
def foldLeft[A,B](l: List[A], z: B)(f: (B, A) => B): B = l match {
case Nil => z
case Cons(x,xs) => foldLeft(xs,f(z,x))(f)
}
here is the problematic part:
def revers[A](l:List[A]) : List[A] = foldLeft(l,Nil)((b,a) => Cons(a,b))
that gives me type errors:
[error] found : datastructures.Cons[A]
[error] required: datastructures.Nil.type
[error] foldLeft(l,Nil)((b,a) => Cons(a,b))
I've could solve this by not using Nil at all like this:
def revers[A](l:List[A]) : List[A] = l match {
case Nil => Nil
case Cons(x,xs) => foldLeft(xs,Cons(x,Nil))((b,a) => Cons(a,b))
}
but still I would like to know how can I pass this?