Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package week6
- object poly {
- class Poly(terms0: Map[Int, Double]) {
- val terms = terms0 withDefaultValue (0.0)
- def this(bindings: (Int,Double)*)= this(bindings.toMap)
- //def +(other: Poly): Poly = new Poly(terms ++ (other.terms map adjust))
- def +(other: Poly): Poly = new Poly((other.terms foldLeft (terms))(addTerm))
- def addTerm(terms: Map[Int,Double], term: (Int, Double)): Map[Int, Double] = {
- val (exp, coef) = term
- terms + (exp-> (terms(exp) + coef))
- }
- def adjust(term: (Int, Double)): (Int, Double) = {
- val (exp, coef) = term
- exp -> (terms(exp) + coef) // possible with maos that have default value no more test necessary
- //terms get exp match {
- //case Some(coef1) => exp -> (coef + coef1)
- //case None => exp -> coef
- //}
- }
- override def toString = (for ((exp, coef) <- terms.toList.sorted.reverse) yield coef + "x^" + exp) mkString " + "
- }
- val p1 = new Poly((1 -> 2.0), (3 -> 4.0), (5 -> 6.5))
- //> p1 : week6.poly.Poly = 6.5x^5 + 4.0x^3 + 2.0x^1
- val p2 = new Poly((0 -> 5), (2 -> 8), (5 -> 8)) //> p2 : week6.poly.Poly = 8.0x^5 + 8.0x^2 + 5.0x^0
- p1 + p2
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement