Skip to content

Instantly share code, notes, and snippets.

@nafg
Created June 3, 2015 18:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nafg/39adbf81a7e6392d24da to your computer and use it in GitHub Desktop.
Save nafg/39adbf81a7e6392d24da to your computer and use it in GitHub Desktop.
Immutable multimap via implicit class
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