Skip to content

Instantly share code, notes, and snippets.

@hanbzu
Last active December 28, 2016 23:54
Show Gist options
  • Save hanbzu/7194847 to your computer and use it in GitHub Desktop.
Save hanbzu/7194847 to your computer and use it in GitHub Desktop.
Scala: Occurrences with pairs, groupBy and map
/**
* 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