scala - 使用 Tailrec 函数的 Scala 模式匹配
问题描述
我有以下函数执行 Tailrec 并尝试在给定的字符串中进行字符计数:
@scala.annotation.tailrec
def letterCount(remaining: Seq[Char], acc: Map[Char, Int]): Map[Char, Int] = remaining match {
case Nil => acc
case x :: Nil => acc ++ Map(x -> 1)
case x :: xs =>
letterCount(xs.filter(_ == x), acc ++ Map(x -> xs.count(_ == x)))
}
letterCount("aabbccd".toSeq, Map.empty)
由于某种奇怪的原因,它失败并出现匹配错误:
scala.MatchError: aabbccd (of class scala.collection.immutable.WrappedString)
at $line87.$read$$iw$$iw$.letterCount(<pastie>:14)
at $line87.$read$$iw$$iw$.liftedTree1$1(<pastie>:23)
at $line87.$read$$iw$$iw$.<init>(<pastie>:22)
at $line87.$read$$iw$$iw$.<clinit>(<pastie>)
at $line87.$eval$.$print$lzycompute(<pastie>:7)
at $line87.$eval$.$print(<pastie>:6)
at $line87.$eval.$print(<pastie>)
我无法找出问题所在!有任何想法吗?
解决方案
它在这里工作:
@scala.annotation.tailrec
def letterCount(original: List[Char], remaining: List[Char], acc: Map[Char, Int]): Map[Char, Int] = remaining match {
case Nil => acc
case x :: Nil => acc ++ Map(x -> 1)
case x :: xs =>
letterCount(original, xs.filter(_ != x), acc ++ Map(x -> original.count(_ == x)))
}
letterCount("aabbccd".toList, "aabbccd".toList, Map.empty)
或者, foldLeft 也可以这样工作:
"aabbccd".foldLeft[Map[Char,Int]](Map.empty)((map, c) => map + (c -> (map.getOrElse(c, 0) + 1)))
推荐阅读
- docker - Gitlab docker 备份和恢复
- javascript - 需要帮助我对 discord.js 的取消静音命令
- vault - 使用 Vault.service 文件以开发模式启动 Vault Server
- python - 对 Dask 与 Pandas 进行基准测试时出现关键错误“负面评论”
- c# - 如何使用 Visual Studio 2019 中的控制台项目测试 .net 5 WPF 项目?
- javascript - 如何在 React 中动态映射另一个数组中的数组?
- python - 如何在不中断 python 中其他代码的情况下运行代码?
- regex - 正则表达式仅在单词不跟随另一个单词时才匹配单词
- apache-flink - flink 广播流和广播状态
- cython - ImportError:无法导入 Cython 模块