Dmitri Dmitri - 9 months ago 84
Scala Question

List counter with foldLeft

I'm trying to do a simple counter of list elements and get something like List((a, 1), (b, 2)). But he compiler produces cryptic error messages about "following methods with _". I don't understands what's the problem...

def counter(acc: List[(Char, Int)], c: Char): List[(Char, Int)] =
acc match {
case Nil => List((c, 1))
case (x, n) :: xs => if (c == x) (x, n+1) :: xs else (c, 1) :: (x, n) :: xs

chars.sorted.foldLeft(List[(Char, Int)])(counter)


You have an error in:

chars.sorted.foldLeft(List[(Char, Int)])(counter) 

instead you should do:

chars.sorted.foldLeft(List[(Char, Int)]())(counter)


chars.sorted.foldLeft(List.empty[(Char, Int)])(counter)