Dmitri Dmitri - 2 months ago 19
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)

Answer

You have an error in:

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

instead you should do:

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

or

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