实施可折叠[列表[A]]

时间:2013-10-29 03:35:53

标签: scala

我正在进行Functional Programming in Scala练习,以便在以下特征上实施List[A]

trait Foldable[F[_]] {
    def foldRight[A, B](as: F[A])(f: (A, B) => B): B
    def foldLeft[A, B](as: F[A])(f: (B, A) => B): B
    def foldMap[A, B](as: F[A])(f: A => B)(mb: Monoid[B]): B
    def concatenate[A](as: F[A])(m: Monoid[A]): A = foldLeft(as)(m.zero)(m.op)
}

在我尝试实施foldLeft时,如果签名中没有,我如何指定initial值?

trait Foldable[List[_]] {
    def foldLeft[A,B](as: List[A])(f: (A, B) => B): B = {
        go(bs: List[A], acc: B): B = bs match {
            case x :: xs => go(xs, f(x, acc))
            case Nil => acc
        }
    go(as, ???) // No start value in the signature? And no Monoid for m.zero
    }
}

1 个答案:

答案 0 :(得分:3)

这本书中的错误。看一下github上的源代码,你会看到一个零方法参数:

https://github.com/pchiusano/fpinscala/blob/master/exercises/src/main/scala/fpinscala/monoids/Monoid.scala#L84

trait Foldable[F[_]] {
  import Monoid._

  def foldRight[A, B](as: F[A])(z: B)(f: (A, B) => B): B =
    sys.error("todo")

  def foldLeft[A, B](as: F[A])(z: B)(f: (B, A) => B): B =
    sys.error("todo")

  def foldMap[A, B](as: F[A])(f: A => B)(mb: Monoid[B]): B =
    sys.error("todo")

  def concatenate[A](as: F[A])(m: Monoid[A]): A =
    sys.error("todo")

  def toList[A](as: F[A]): List[A] =
    sys.error("todo")
}