Last active
May 8, 2016 10:08
-
-
Save hanbzu/7194083 to your computer and use it in GitHub Desktop.
Scala: Occurrences with pairs, Map and foldLeft
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
/** | |
* 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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great explanation, it took me a while to figure it out after my brain melted too! Thanks!