[英]foldLeft on Map - Why does that work?
這是一個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)
}
考慮到Map
中foldLeft
的簽名如下,
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]
。
對我而言,這看起來並不一致。 我究竟做錯了什么?
是的,這是與Scaladoc相關的問題SI-6974 ,似乎在Scala 2.12-RC1中得到修復。 您可以每晚檢查Scala 2.12.x API文檔,它顯示正確的簽名。
TraversableOnce中定義的foldLeft
簽名是
def foldLeft[B](z: B)(op: (B, A) ⇒ B): B
其中A
是一種集合,來自Traversable[A]
。
Map[A, B] <: Traversable[(A, B)]
,然后在定義foldLeft
scaladoc只是替代型A
與采集的(A, B)
這帶來混亂:
def foldLeft[B](z: B)(op: (B, (A, B)) ⇒ B): B
如果將地圖的參數重命名為Map[K, V]
,則foldLeft
將變為:
def foldLeft[B](z: B)(op: (B, (K, V)) ⇒ B): B
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.