Scala Map collection and map method

Viewed 45

I don't understand why def + and def adjust of the following Scala code can be correct. 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. But what I dont' understand is that: 1) This should be taken care of by code "other.terms map adjust)" under def + ; 2) and if 1)is correct, “terms ++ " in the same def will add p1's coefficient one more time, which should be wrong.

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
1 Answers

Quick answers:

  1. other.terms map adjust only includes terms from other, but there may be terms in this that are not in 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. So the terms from other.terms map adjust will replace those in this.terms not modify them.

Related