Skip to content

Instantly share code, notes, and snippets.

@hanbzu
Created October 29, 2013 07:49
Show Gist options
  • Save hanbzu/7210555 to your computer and use it in GitHub Desktop.
Save hanbzu/7210555 to your computer and use it in GitHub Desktop.
Scala: Occurrences with pairs, groupBy and mapValues
/**
* 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