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