summaryrefslogtreecommitdiffstats
path: root/Scala/sandbox
diff options
context:
space:
mode:
Diffstat (limited to 'Scala/sandbox')
-rw-r--r--Scala/sandbox/0-main.scala1
-rw-r--r--Scala/sandbox/13-polynomials.scala43
2 files changed, 44 insertions, 0 deletions
diff --git a/Scala/sandbox/0-main.scala b/Scala/sandbox/0-main.scala
index f6d6652..297fab9 100644
--- a/Scala/sandbox/0-main.scala
+++ b/Scala/sandbox/0-main.scala
@@ -15,5 +15,6 @@ object Main extends App {
MergeSort.run
Pack.run
NQueens.run
+ Polynomials.run
}
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)
+ }
+}