Last active
December 16, 2015 09:29
-
-
Save davidandrzej/5413350 to your computer and use it in GitHub Desktop.
Combining two Map[String,Int] with key-wise addition.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object CombineMaps { | |
type Counts = Map[String,Int] | |
def combine(x: Counts, y: Counts): Counts = { | |
val x0 = x.withDefaultValue(0) | |
val y0 = y.withDefaultValue(0) | |
val keys = x.keys.toSet.union(y.keys.toSet) | |
keys.map{ k => (k -> (x0(k) + y0(k))) }.toMap | |
} | |
} | |
val counts1 = Map("boats" -> 1, "against" -> 2, | |
"the" -> 10, "current" -> 1) | |
val counts2 = Map("burned" -> 1, "the" -> 5, "boats" -> 1) | |
println(CombineMaps.combine(counts1,counts2)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment