diff options
author | Jérémy Zurcher <jeremy@asynk.ch> | 2013-05-17 17:17:29 +0200 |
---|---|---|
committer | Jérémy Zurcher <jeremy@asynk.ch> | 2016-11-10 18:03:25 +0100 |
commit | b95dd68188634f826bbbab79d47c65f39ee5a06e (patch) | |
tree | c9d9ff33742d2c01b74781c036e9e39cfaddd242 /Scala/sandbox/13-polynomials.scala | |
parent | d8d74ed55984d2ae39cbdb965dd42bba984735a9 (diff) | |
download | coursera-b95dd68188634f826bbbab79d47c65f39ee5a06e.zip coursera-b95dd68188634f826bbbab79d47c65f39ee5a06e.tar.gz |
Scala : add 13-polynomials to sandbox
Diffstat (limited to 'Scala/sandbox/13-polynomials.scala')
-rw-r--r-- | Scala/sandbox/13-polynomials.scala | 43 |
1 files changed, 43 insertions, 0 deletions
diff --git a/Scala/sandbox/13-polynomials.scala b/Scala/sandbox/13-polynomials.scala new file mode 100644 index 0000000..ebf3818 --- /dev/null +++ b/Scala/sandbox/13-polynomials.scala @@ -0,0 +1,43 @@ +object Polynomials +{ + + class Poly(terms0: Map[Int, Double]) { + def this(bindings: (Int, Double)*) = this(bindings.toMap) + val terms = terms0 withDefaultValue 0.0 + + def add (other: Poly) = new Poly(terms ++ (other.terms map adjust)) + + def adjust(term: (Int, Double)): (Int, Double) = { + val (exp, coeff) = term + exp -> (coeff + terms(exp)) + // before adding defauld value + /* terms get exp match { */ + /* case Some(coeff1) => exp -> (coeff + coeff1) */ + /* case None => exp -> coeff */ + /* } */ + } + + def + (other: Poly) = new Poly((other.terms foldLeft terms)(addTerm)) + + def addTerm(terms: Map[Int, Double], term: (Int, Double)) = { + val (exp, coeff) = term + terms + (exp -> (coeff + terms(exp))) + } + + override def toString = + (for ((exp, coeff) <- terms.toList.sorted.reverse) yield coeff+"^"+exp) mkString " + " + } + + def run = { + println("Polynomials") + /* 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)) */ + val p1 = new Poly(1 -> 2.0, 3 -> 4.0, 5 -> 6.2) + val p2 = new Poly(0 -> 3.0, 3 -> 7.0) + println(p1.terms(7)) + println(p1) + println(p2) + println(p1 add p2) + println(p1 + p2) + } +} |