这是来自 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)
}
考虑到foldLeft
in的签名Map
如下,
def foldLeft[B](z: B)(op: (B, (A, B)) => B): B
我尝试理解签名并将其映射到上面示例中的用法。
零元素z
对应于terms
所以类型将是Map[Int, Double]
。
操作员op
对应addTerm
哪个有签名( Map[Int, Double], (Int, Double) ) => Map[Int, Double]
。
对我来说,这看起来并不一致。我究竟做错了什么?