具有Tailrec功能的Scala模式匹配

时间:2019-05-02 18:24:15

标签: scala tail-recursion

我有以下函数,可以执行Tailrec并尝试在给定的String中进行字符计数:

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

我无法找出问题所在!有什么想法吗?

2 个答案:

答案 0 :(得分:1)

在这里有效:

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

答案 1 :(得分:1)

如评论中所述,Seq不是ListSeq没有Nil元素,也没有::方法。

如果您想保留Seq[Char],可以这样做。

@scala.annotation.tailrec
def letterCount(remaining: Seq[Char], acc: Map[Char, Int]): Map[Char, Int] = remaining match {
  case Seq() => acc
  case x +: xs =>
    letterCount(xs.filter(_ != x), acc ++ Map(x -> (xs.count(_ == x)+1)))
}

letterCount("aabbccd", Map.empty)

请注意,您不必.toSeq String。它会自动解释为Seq[Char]

相关问题