Advertisement
jules0707

polynomial

Feb 27th, 2017
199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.23 KB | None | 0 0
  1. package week6
  2.  
  3. object poly {
  4.  
  5.   class Poly(terms0: Map[Int, Double]) {
  6.     val terms = terms0 withDefaultValue (0.0)
  7.     def this(bindings: (Int,Double)*)= this(bindings.toMap)
  8.     //def +(other: Poly): Poly = new Poly(terms ++ (other.terms map adjust))
  9.     def +(other: Poly): Poly = new Poly((other.terms foldLeft (terms))(addTerm))
  10.    
  11.     def addTerm(terms: Map[Int,Double], term: (Int, Double)): Map[Int, Double] = {
  12.      val (exp, coef) = term
  13.      terms + (exp-> (terms(exp) + coef))
  14.     }
  15.    
  16.     def adjust(term: (Int, Double)): (Int, Double) = {
  17.       val (exp, coef) = term
  18.       exp -> (terms(exp) + coef) // possible with maos that have default value no more test necessary
  19.       //terms get exp match {
  20.       //case Some(coef1) => exp -> (coef + coef1)
  21.       //case None        => exp -> coef
  22.       //}
  23.     }
  24.     override def toString = (for ((exp, coef) <- terms.toList.sorted.reverse) yield coef + "x^" + exp) mkString " + "
  25.   }
  26.  
  27.   val p1 = new Poly((1 -> 2.0), (3 -> 4.0), (5 -> 6.5))
  28.                                                   //> p1  : week6.poly.Poly = 6.5x^5 + 4.0x^3 + 2.0x^1
  29.   val p2 = new Poly((0 -> 5), (2 -> 8), (5 -> 8)) //> p2  : week6.poly.Poly = 8.0x^5 + 8.0x^2 + 5.0x^0
  30.   p1 + p2
  31.  
  32.  
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement