我正在尝试学习函数式编程和Scala,所以我正在阅读Chiusano和Bjarnason的《Scala函数式编程》。在处理列表时,我不太理解fold left和fold right方法的作用。我在这里找了一下,但没有找到适合初学者的内容。因此,书中提供的代码如下:
def foldRight[A,B](as: List[A], z: B)(f: (A, B) => B): B = as match {
case Nil => z
case Cons(h, t) => f(h, foldRight(t, z)(f))
}
def foldLeft[A,B](l: List[A], z: B)(f: (B, A) => B): B = l match {
case Nil => z
case Cons(h,t) => foldLeft(t, f(z,h))(f)
}
Cons 和 Nil 分别代表:
case class Cons[+A](head: A, tail: List[A]) extends List[A]
case object Nil extends List[Nothing]
那么,“fold left”和“fold right”到底是做什么的?为什么它们被称为“实用”方法?许多其他方法都使用它们,但我也很难理解它们,因为我不太懂这两个方法。