我正在进行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
}
}