了解更高级的类型 - 实现特征功能

时间:2014-02-06 14:11:26

标签: scala

尝试按照此示例(取自scala in action)为所有集合创建通用求和函数

trait Summable[A] {
  def plus(a1: A, a2: A): A
  def init: A
}
object IntSummable extends Summable[Int] {
  def plus(a1: Int, a2: Int): Int = a1 + a2
  def init: Int = 0
}
trait Foldable[F[_]] {
  def foldLeft[A](xs: F[A], m: Summable[A]) : A
}

像这样实现foldLeft工作正常:

  object ListFoldLeft extends Foldable[List] {
    def foldLeft[A](xs:List[A],m:Summable[A]) =
    xs.foldLeft(m.init)(m.plus)
  }
然而,

然而,尽管foldLeft函数接受两个参数(xs:List [A],m:Summable [A]),我们将它们分开发送 xs.foldLeft(m.init)(m.plus),它工作正常

但如果我尝试像这样发送它们:

      object ListFoldLeft extends Foldable[List] {
        def foldLeft[A](xs:List[A],m:Summable[A]) =
            xs.foldLeft(m.init,m.plus)
       }

我得到了

<console>:18: error: too many arguments for method foldLeft: (z: B)(op: (B, A) => B)B
       xs.foldLeft(m.init,m.plus)

为什么?

1 个答案:

答案 0 :(得分:2)

也许我错了,但看起来你试着打电话 List . foldLeft[B](z: B)(f: (B, A) ⇒ B): B curried函数只有一个参数列表,并且该定义的参数列表中的参数数量无效。

List.foldLeft是一个curried函数

更多关于curried函数的信息:

http://www.codecommit.com/blog/scala/function-currying-in-scala

相关问题