简体   繁体   English

Scala Map 收集和 map 方法

[英]Scala Map collection and map method

I don't understand why def + and def adjust of the following Scala code can be correct.我不明白为什么以下 Scala 代码的 def + 和 def 调整可以正确。 I understand def adjust is used to adjust coefficients because when p1 and p2 have same exponents, their respective coefficients need to be summed up together when summing p1 and p2.我理解 def adjust 用于调整系数,因为当 p1 和 p2 具有相同的指数时,在求和 p1 和 p2 时需要将它们各自的系数相加。 But what I dont' understand is that: 1) This should be taken care of by code "other.terms map adjust)" under def +;但我不明白的是:1)这应该通过def +下的代码“other.terms map调整)”来处理; 2) and if 1)is correct, “terms ++ " in the same def will add p1's coefficient one more time, which should be wrong. 2)如果1)正确,则同一个def中的“terms ++”将p1的系数加一次,应该是错误的。

I'm confused as this code works well.我很困惑,因为这段代码运行良好。 Can someone please help me?有人可以帮帮我吗? Thanks a lot!非常感谢!

object polynomials { 
  class Poly(terms0: Map[Int, Double]) {
    val terms = terms0 withDefaultValue 0.0

    def +(other: Poly) = new Poly(terms ++ (other.terms map adjust))

    def adjust(term: (Int, Double)): (Int, Double) = {
        val (exp, coeff) = term
        exp -> (coeff + terms(exp))
    }

   override def toString = 
 (for ((exp, coeff) <- terms.tolist.sorted.reverse) yield coeff + ”x^” + exp) mkString “+” 
}

val p1 = new Poly(Map(1 -> 2.0, 3 -> 4.0, 5 -> 6,2))
val p2 = new Poly(Map(0 -> 3.0, 3 -> 7.0)

p1 + p2

Quick answers:快速回答:

  1. other.terms map adjust only includes terms from other , but there may be terms in this that are not in other . other.terms map adjust仅包括来自other的术语,但在this中可能有在other中没有的术语。 In order to retain those terms, the adjusted terms are added to the existing ones.为了保留这些条款,将调整后的条款添加到现有条款中。

  2. ++ on two maps does not merge values with the same key, it replaces any values from the left-hand Map with those from the right-hand Map with the same key.两个地图上的++不会合并具有相同键的值,它将左侧Map中的任何值替换为具有相同键的右侧Map中的任何值。 So the terms from other.terms map adjust will replace those in this.terms not modify them.因此other.terms map adjust中的条款将替换this.terms中的条款,而不是修改它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM