Created
February 21, 2011 23:41
-
-
Save hallettj/837927 to your computer and use it in GitHub Desktop.
how to use Set#groupBy in Scala 2.7
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
/* | |
* 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