Last active
December 28, 2016 23:54
-
-
Save hanbzu/7194847 to your computer and use it in GitHub Desktop.
Scala: Occurrences with pairs, groupBy and map
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)] = { | |
val grouped = w.groupBy(x => x.toLower) // Group by element (all chars to lowercase) | |
grouped.map(x => (x._1, x._2.length)).toList // Create pair for each element | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment