Created
October 29, 2013 07:49
-
-
Save hanbzu/7210555 to your computer and use it in GitHub Desktop.
Scala: Occurrences with pairs, groupBy and mapValues
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
/** | |
* For each unique character in the list `chars`, it calculates the number of | |
* times it occurs. times(List('a', 'b', 'a')) should return List(('a', 2), ('b', 1)) | |
*/ | |
def howManyTimes(w: String): List[(Char, Int)] = { // w = "Wooord" | |
val grouped = w.groupBy(x => x.toLower) // Map(d -> d, w -> W, r -> r, o -> ooo) | |
val occ = grouped.mapValues(_.length) // Map(d -> 1, w -> 1, r -> 1, o -> 3) | |
occ.toList // List((d,1), (w,1), (r,1), (o,3)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment