使用foldLeft列出计数器

时间:2016-09-06 03:41:38

标签: scala

我试图做一个简单的列表元素计数器,得到类似List((a,1),(b,2))的东西。但是他编译器使用_"生成关于"以下方法的神秘错误消息。我不明白这个问题是什么......

  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)

1 个答案:

答案 0 :(得分:1)

您输入错误:

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

你应该这样做:

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

chars.sorted.foldLeft(List.empty[(Char, Int)])(counter)
相关问题