Last active
February 23, 2016 21:03
-
-
Save raboof/6a3a0ef7d798c175ff2d to your computer and use it in GitHub Desktop.
MultiMap
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
type ListMultiMap[A, B] = Map[A, List[B]] | |
implicit class ListMultiMapOps[A, B](val map: ListMultiMap[A, B]) extends AnyVal { | |
/** May be overridden */ | |
def makeList: List[B] = Nil | |
def addBinding(key: A, value: B): ListMultiMap[A, B] = map + (key -> { value :: map.getOrElse(key, makeList) }) | |
def removeBinding(key: A, value: B): ListMultiMap[A, B] = map.get(key) match { | |
case None => map | |
case Some(List(value)) => map - key | |
case Some(list) => map + (key -> list.diff(List(value))) | |
} | |
} | |
def toListMultiMap[A,B](seq: Seq[(A, B)]) = seq.foldLeft(Map[A, List[B]]())((acc, t) => acc.addBinding(t._1, t._2)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment