【发布时间】:2021-08-22 02:48:03
【问题描述】:
我正在为一门在线课程做作业。它是 Scala 中的函数式编程。我正在研究一个函数,该函数返回一个对列表,其中包含第一个索引中的字符和第二个索引中的出现次数。不幸的是,我遇到了一个错误。由于某种原因,我的模式匹配案例没有捕获 Nil 列表的案例。我收到没有这样的元素错误。谢谢!
这是我的代码
def times(chars: List[Char]): List[(Char, Int)] = {
// Need to recurse through list
// Needs to be tail recursive
def timesAcc(charList: List[Char], acc: List[(Char, Int)]): List[(Char, Int)] = {
charList match {
case Nil => acc
case _ =>
}
if(!acc.exists(elem => elem._1 == charList.head)) {
val count = charList.count(c => c == charList.head)
timesAcc(charList.tail,(charList.head, count) :: acc)
}else{
timesAcc(charList.tail, acc)
}
}
timesAcc(chars, List())
}
【问题讨论】:
-
您的括号不匹配(您过早关闭模式匹配)。模式匹配是无用的。您需要将所有逻辑移动到第二个
case
标签: scala functional-programming