Skip to content

Instantly share code, notes, and snippets.

@hallettj
Created February 21, 2011 23:41
Show Gist options
  • Save hallettj/837927 to your computer and use it in GitHub Desktop.
Save hallettj/837927 to your computer and use it in GitHub Desktop.
how to use Set#groupBy in Scala 2.7
/*
* Set#groupBy() is not defined in Scala 2.7.
*/
class GroupableSet[A](val set: Set[A]) {
def groupBy[K](grouping: A => K): Map[K, Set[A]] = {
val init: Map[K, Set[A]] = Map()
set.foldLeft(init) { (map, e) =>
val key = grouping(e)
val group = map.getOrElse(key, Set())
map + (key -> (group + e))
}
}
}
implicit def set2GroupableSet[A](set: Set[A]): GroupableSet[A] = new GroupableSet(set)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment