Using the solution here, I’m adding two maps together and treating them as if they were sparse vectors. So
def addTwoVectors(map1: Map[Int, Double], map2: Map[Int, Double]) = {
map1 ++ map2.map{ case (k,v) => k -> (v + map1.getOrElse(k,0)) }
}
Now I’d like to make this generic so that
def addTwoMaps[I, D <% Numeric[D]](m1: Map[I, D], m2: Map[I, D]) = {
m1 ++ m2.map{ case (k,v) => k -> (v + m1.getOrElse(k, 0.asInstanceOf[D])) }
}
Unfortunately, it doesn’t seem to work:
error: type mismatch;
found : D
required: String
So how do I make this function generic?
How about this one?
Cause I don’t know which one Numeric I have, I’m taking this info implicitly, and then importing zero method, which is specific for every Numeric type.
Actually, I do believe, that scalaz solution will be much more cleaner and hope that somebody will post it.