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?