Reputation: 13
Playing around with implementation of list function
sealed trait List[+A]
case object Nil extends List[Nothing]
case class Cons[+A] (head:A, tail:List[A]) extends List[A]
object List {
@tailrec
def foldLeft[A,B] (list: List[A], z:B)(f:(A,B) => B) : B = {
list match {
case Nil => z
case Cons(h,t) => foldLeft(t,f(h,z))(f)
}
}
def reverse[A] (list: List[A]) = {
foldLeft(list,Nil)(Cons(_,_))
}
}
getting "Type mismatch, expected (A,Nil.Type) => Nil.Type, actual: (A, Nil.Type) => Cons[A]" from the Cons(,) in the reverse method.
What am I doing wrong ?
Upvotes: 1
Views: 223
Reputation: 7476
This is a very common error when using Nil
. Nil
extends List[Nothing]
so you need to help the compiler a little bit to properly infer the actual type of B
:
def reverse[A] (list: List[A]) = {
foldLeft(list,Nil:List[A])(Cons(_,_))
}
Upvotes: 6