これは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)
}
foldLeftinの署名が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]
私には、これは一貫していないように見えます。私は何を間違っていますか?