Scala 地图上的foldLeft-为什么会这样?
这是一门Coursera课程,直到现在没有人能帮我。 以下作品摘自一次讲座Scala 地图上的foldLeft-为什么会这样?,scala,foldleft,Scala,Foldleft,这是一门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
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)
}
我试图理解签名并将其映射到上面示例中的用法
零元素z
对应于术语
,因此类型为Map[Int,Double]
运算符
op
对应于签名为(Map[Int,Double],(Int,Double))=>Map[Int,Double]
的addTerm
在我看来,这并不一致。我做错了什么?是的,这是与Scaladoc相关的问题,Scala2.12-RC1中似乎解决了这个问题。您可以检查每晚的API文档,它显示正确的签名
说明:
中定义的foldLeft
的签名为
其中A
是一种集合类型,来自Traversable[A]
Map[A,B]在REPL中,自动完成Map(1->“one”)。foldLeft
生成def foldLeft[B](z:B)(op:(B,(Int,String))=>B):B
,这可能有助于诊断它。
def foldLeft[B](z: B)(op: (B, (A, B)) => B): B
def foldLeft[B](z: B)(op: (B, A) ⇒ B): B
def foldLeft[B](z: B)(op: (B, (A, B)) ⇒ B): B
def foldLeft[B](z: B)(op: (B, (K, V)) ⇒ B): B