Skip to content

Instantly share code, notes, and snippets.

@robhinds
Created May 30, 2017 08:26
Show Gist options
  • Save robhinds/d56e6d61c860af510c5a27c7ad22f361 to your computer and use it in GitHub Desktop.
Save robhinds/d56e6d61c860af510c5a27c7ad22f361 to your computer and use it in GitHub Desktop.
def mergeMap[A, B](ms: List[Map[A, B]])(f: (B, B) => B): Map[A, B] =
(Map[A, B]() /: (for (m <- ms; kv <- m) yield kv)) { (a, kv) =>
a + (if (a.contains(kv._1)) kv._1 -> f(a(kv._1), kv._2) else kv)
}
val ms = List(Map("hello" -> 1.1, "world" -> 2.2), Map("goodbye" -> 3.3, "hello" -> 4.4))
val mm = mergeMap(ms)((v1, v2) => v1 + v2)
println(mm) // prints Map(hello -> 5.5, world -> 2.2, goodbye -> 3.3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment