Created
May 30, 2017 08:26
-
-
Save robhinds/d56e6d61c860af510c5a27c7ad22f361 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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