Scala 第一个程序问题

Scala first program issue

在使用其他语言进行函数式编程后,我才刚刚开始学习 Scala。

def freq(c:Char, y:String, list:List[(Char,Int)]): List[(Char,Int)] = list match{
  case _ =>  freq(c, y.filter(_ == c), list :: List((count(c,y),c))) 
  case nil => list
} 

在上面的代码中,我在尝试递归连接列表时遇到错误。错误发生在 list::List((count(c,y),c))。 count 方法根据 char 出现的次数接受一个 char 和一个 string 以及 returns 一个 int。

如有任何帮助,我们将不胜感激。我得到的错误状态是 [(Char,Int)] required (Char,Int).

您还需要切换 2 个匹配案例,因为永远不会以这种方式评估 nil。 _ 也会捕获 nil 并且永远不会继续达到第二种情况。

Cons operator (::) 是一个中缀运算符,所以如果你想获得 List[T] 而不是 List[List[T]] 的类型,那么你应该写

freq(c, y.filter(_ == c),(count(c,y),c)) :: list)