首页 > 解决方案 > 使用 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>)

我无法找出问题所在!有任何想法吗?

标签: scalatail-recursion

解决方案


它在这里工作:

  @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)))

推荐阅读