Scala: Frequency of characters in a list
Scala: Frequency of characters in a list I am a novice programmer from a python/java background, who is trying to get to grips with functional programming in scala. I am trying to write a function that will take a list of characters and return a list of their frequencies. For example, List('a','b','a') should return List(('a', 2), ('b', 1)). I am new to scala and tail recursion, so please don't presume much prior knowledge :) Here is what I have: def times(chars: List[Char]): List[(Char, Int)] = { def loop(chars: List[Char], list: List[(Char, Int)]): List[(Char, Int)] = { if (chars.isEmpty) list else { val head = chars.head val freq = chars.count(x=> x == head) (head,freq) :: list loop(chars.tail.filterNot(x=> x == head),list) } } loop(chars,List()) } If I run times(List('a','b','a')) I just get an empty list. Any help would be greatly appreciated! ...
