Possible Duplicate:
Best way to merge two maps and sum the values of same key?
I have a bunch of maps of the type Map[String, Int]
. I would like to be able to merge them taking the sum of the values when the keys correspond. For instance, the standard ++
method on maps gives
Map("a" -> 1, "b" -> 2) ++ Map("a" -> 3, "c" -> 5)
// Map[String,Int] = Map(a -> 3, b -> 2, c -> 5)
I would like to define an operation that as a result would give
Map("a" -> 1, "b" -> 2) ?? Map("a" -> 3, "c" -> 5)
// Map[String,Int] = Map(a -> 4, b -> 2, c -> 5)
In fancy wording, Map[A, B]
always has a natural structure of monoid, but there is a different one when B
is itself a monoid.
Now, it would not be difficult to write, say, a recursive implementation for LinkedHashMap
, but I think there must be some trivial and more general way to write this, possibly using scalaz. Any ideas?