Skip to content

Instantly share code, notes, and snippets.

@hanbzu
Last active May 8, 2016 10:08
Show Gist options
  • Save hanbzu/7194083 to your computer and use it in GitHub Desktop.
Save hanbzu/7194083 to your computer and use it in GitHub Desktop.
Scala: Occurrences with pairs, Map and foldLeft
/**
* This function computes for each unique character in the list `chars` the number of
* times it occurs. times(List('a', 'b', 'a')) should return List(('a', 2), ('b', 1))
*/
def howManyTimes(chars: List[Char]): List[(Char, Int)] = {
def incr(acc:Map[Char, Int], c:Char) = {
val count = (acc get c).getOrElse(0) + 1 // If acc get c is none getOrElse makes it 0
// To add values to the Map we use operator +
// If key does not exist, a new (key, value) is inserted, otherwise substitution occurs
acc + ((c, count)) // I Double brakets tell scala we're dealing with a pair
}
// Initially we have an empty map and with that initial value we perform the operation
// starting from the right. The resulting element is an updated map (my brain hurts)
(chars foldLeft Map[Char,Int]())(incr).iterator.toList
// (1) foldLeft has an alternate syntax. These two are equivalent
// xs foldLeft z
// z /: xs
// We could have written:
// (Map[Char, Int]() /: chars)(incr)
// (2)To convert a map to a list I need to use .iterator.toList
}
@noloman
Copy link

noloman commented May 8, 2016

Great explanation, it took me a while to figure it out after my brain melted too! Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment