【发布时间】:2014-11-26 01:32:21
【问题描述】:
所以我在 scala 中得到了我的 List 类版本:
sealed trait List[+A] {
(...)
}
case object Nil extends List[Nothing]
case class Cons[+A](_head: A, _tail: List[A]) extends List[A]
现在我正在尝试用我的foldLeft 来写reverse,如下所示:
@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)
}
这是有问题的部分:
def revers[A](l:List[A]) : List[A] = foldLeft(l,Nil)((b,a) => Cons(a,b))
这给了我类型错误:
[error] found : datastructures.Cons[A]
[error] required: datastructures.Nil.type
[error] foldLeft(l,Nil)((b,a) => Cons(a,b))
我可以通过完全不使用 Nil 来解决这个问题:
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))
}
但我还是想知道如何通过这个?
【问题讨论】:
标签: scala types functional-programming