我正在进行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
}
}
答案 0 :(得分:3)
这本书中的错误。看一下github上的源代码,你会看到一个零方法参数:
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")
}