Skip to content

Instantly share code, notes, and snippets.

@raboof
Last active February 23, 2016 21:03
Show Gist options
  • Save raboof/6a3a0ef7d798c175ff2d to your computer and use it in GitHub Desktop.
Save raboof/6a3a0ef7d798c175ff2d to your computer and use it in GitHub Desktop.
MultiMap
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