I'm trying to implement dropWhile in Scala but I get a type mismatch, on the invocation of "f(h)" error that says it actually found the type it was expecting:
def dropWhile[A](l: XList[A])(f: A => Boolean): XList[A] = {
def dropWhile[A](toCheck: XList[A], toKeep: XList[A]) : XList[A] = toCheck match {
case XNil => toKeep
case Cons(h, t) if **f(h)** == false => dropWhile(tail(toCheck), Cons(h, toKeep))
case Cons(_, Cons(t1, t2)) => dropWhile(Cons(t1, t2), toKeep)
}
dropWhile(l, XList[A]())
}
error message:
found : h.type (with underlying type A)
[error] required: A
relevant code:
sealed trait XList[+A] {}
case object XNil extends XList[Nothing]
case class Cons[+A](head: A, tail: XList[A]) extends XList[A]
EDIT:
Here's a way to make it compile - but the winning answer is better and explains why as well.
def dropWhile[A](l: XList[A])(f: A => Boolean): XList[A] = {
@tailrec
def dropWhile[A](toCheck: XList[A], toKeep: XList[A], dropItem: A => Boolean): XList[A] = toCheck match {
case Cons(h, XNil) if !dropItem(h) => Cons(h, toKeep)
case Cons(h, XNil) if dropItem(h) => toKeep
case Cons(h, t) if !dropItem(h) => dropWhile(t, Cons(h, toKeep), dropItem)
case Cons(h, t) if dropItem(h) => dropWhile(t, toKeep, dropItem)
}
dropWhile(l, XList[A](), f)
}