我正在尝试在 Scala 中实现 dropWhile,但在调用“f(h)”错误时出现类型不匹配,该错误表示它实际上找到了它所期望的类型:
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]())
}
错误信息:
found : h.type (with underlying type A)
[error] required: A
相关代码:
sealed trait XList[+A] {}
case object XNil extends XList[Nothing]
case class Cons[+A](head: A, tail: XList[A]) extends XList[A]
编辑:
这是一种使其编译的方法-但获胜的答案更好,并解释了原因。
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)
}