Created
June 3, 2015 18:11
-
-
Save nafg/39adbf81a7e6392d24da to your computer and use it in GitHub Desktop.
Immutable multimap via implicit class
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
implicit class MultiMap[K, V](map: Map[K, Set[V]]) { | |
def addBinding(k: K, v: V) = addBindings(k, Set(v)) | |
def addBindings(k: K, vs: Set[V]) = map.get(k) match { | |
case None => map + (k -> vs) | |
case Some(xs) => map + (k -> (vs ++ xs)) | |
} | |
def removeBinding(k: K, v: V) = map.get(k) match { | |
case None => map | |
case Some(vs) => | |
val vs2 = vs - v | |
if (vs2.isEmpty) | |
map - k | |
else | |
map + (k -> vs2) | |
} | |
def removeAll(v: V) = map.keys.foldLeft(map)((m, k) => m.removeBinding(k, v)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment