Search code examples
scalafoldleft

foldLeft on Map - Why does that work?


This is from a Coursera course, until now no one could help me. The following works, taken from a lecture.

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)

}

Considering that the signature of foldLeft in Map is as follows,

def foldLeft[B](z: B)(op: (B, (A, B)) => B): B

I try to understand the signature and map it to the usage in above example.

The zero element z corresponds to terms so the type would be Map[Int, Double].
The operator op corresponds to addTerm which has the signature ( Map[Int, Double], (Int, Double) ) => Map[Int, Double].

To me this does not look consistent. What am I doing wrong?


Solution

  • Yes, this is the issue SI-6974 related to Scaladoc, which seems to be fixed in Scala 2.12-RC1. You can check nightly Scala 2.12.x API docs, it shows correct signature.

    Explanation:

    The signature of foldLeft defined in TraversableOnce is

    def foldLeft[B](z: B)(op: (B, A) ⇒ B): B
    

    where A is a type of collection and comes from Traversable[A].

    Map[A, B] <: Traversable[(A, B)], then in the definition of foldLeft scaladoc just substitutes type A of collection with (A, B), which brings confusion:

    def foldLeft[B](z: B)(op: (B, (A, B)) ⇒ B): B
    

    If you rename parameters of the map to Map[K, V], then foldLeft becomes:

     def foldLeft[B](z: B)(op: (B, (K, V)) ⇒ B): B