foldLeft在地图上 - 为什么这样做?

Ely*_*Ely 3 scala foldleft

这是一个Coursera课程,直到现在没有人可以帮助我.以下作品取自演讲.

object polynomials {

  class Poly(terms0: Map[Int, Double]) {

    def this(bindings: (Int, Double)*) = this(bindings.toMap)

    val terms = terms0 withDefaultValue 0.0

    def +(other: Poly) = new Poly((other.terms foldLeft terms)(addTerm))

    def addTerm(terms: Map[Int, Double], term: (Int, Double)) : Map[Int, Double]= {
      val (exp, coeff) = term
      terms + (exp -> (coeff + terms(exp)))
    }

    override def toString =
      (for ((exp, coeff) <- terms.toList.sorted.reverse)
        yield coeff+"x^"+exp) mkString " + "
  }

  val p1 = new Poly(1 -> 2.0, 3 -> 4.0, 5 -> 6.2)
  val p2 = new Poly(0 -> 3.0, 3 -> 7.0)
  p1 + p2

  p1.terms(7)

}
Run Code Online (Sandbox Code Playgroud)

考虑到foldLeftin 的签名Map如下,

def foldLeft[B](z: B)(op: (B, (A, B)) => B): B
Run Code Online (Sandbox Code Playgroud)

我尝试理解签名并将其映射到上面示例中的用法.

零元素z对应于terms类型Map[Int, Double].
操作员op对应于addTerm具有签名的操作员( Map[Int, Double], (Int, Double) ) => Map[Int, Double].

对我而言,这看起来并不一致.我究竟做错了什么?

4e6*_*4e6 5

是的,这是与Scaladoc相关的问题SI-6974,似乎在Scala 2.12-RC1中得到修复.您可以每晚检查Scala 2.12.x API文档,它显示正确的签名.

说明:

TraversableOnce中foldLeft定义的签名是

def foldLeft[B](z: B)(op: (B, A) ? B): B
Run Code Online (Sandbox Code Playgroud)

哪里A是一种集合,来自Traversable[A].

Map[A, B] <: Traversable[(A, B)],那么在foldLeftscaladoc 的定义中只是替换A了集合的类型(A, B),这带来了混乱:

def foldLeft[B](z: B)(op: (B, (A, B)) ? B): B
Run Code Online (Sandbox Code Playgroud)

如果将地图的参数重命名为Map[K, V],则foldLeft变为:

 def foldLeft[B](z: B)(op: (B, (K, V)) ? B): B
Run Code Online (Sandbox Code Playgroud)