I'm using maps to represent a polynomial.
The key is the exponent and the value is the coefficient : Map(exp -> coef)
e.g. 2.5*x^5 + 3.0 is represented by : Map(5 -> 2.5, 0 -> 3.0)
I wrote 3 functions (in Scala) to add such polynomials. Which one is the most elegant ? Do you have another version that is preferable/better ? (Implementations in another language such as Haskell are welcome)
Here is a sample testcase :
val polynom1 = Map(0 -> 1.0, 1 -> 2.0, 2 -> 1.0)
val polynom2 = Map(0 -> 1.0, 1 -> (-2.0), 2 -> 1.0)
val expectedSum = Map(0 -> 2.0, 1 -> 0.0, 2 -> 2.0)
Here are the implementations :
def addMap1(lhs: Map[Int, Double], rhs: Map[Int, Double]) =
((lhs.keys ++ rhs.keys) map { k =>
(k, lhs.getOrElse(k, 0.0) + rhs.getOrElse(k, 0.0))
}).toMap
def addMap2(lhs: Map[Int, Double], rhs: Map[Int, Double]) = {
def adjust(kv: (Int, Double)) = {
val (exp, coef) = kv
(exp, coef + lhs.getOrElse(exp, 0.0))
}
lhs ++ (rhs map adjust)
}
def addMap3(lhs: Map[Int, Double], rhs: Map[Int, Double]) = {
def addTerms(acc: Map[Int, Double], x: (Int, Double)) = {
val (exp, coef) = x
acc + (exp -> (coef + rhs.getOrElse(exp, 0.0)))
}
(lhs foldLeft rhs)(addTerms)
}