为什么以下函数不是尾递归?

Eli*_*lin 2 scala tail-recursion

以下函数在我看来是尾递归
但是编译器仍然抱怨如果我把@tailrec它放在上面:

def loop(newInterests: Set[Interest], oldInterests: Set[Interest]): Set[Interest] = {
  newInterests.headOption.fold(oldInterests){ ni =>
    val withSameKeyWord = oldInterests.find(oi => oi.keyword == ni.keyword)

    withSameKeyWord.fold(loop(newInterests.tail, oldInterests + ni)){ k => 
      loop(newInterests.tail,
      oldInterests - k + k.copy(count = k.count + 1))
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

iru*_*aia 7

如thefourtheye所述,您的函数返回folds 的结果.尾递归版(带模式匹配)看起来像:

@tailrec
def loop(newInterests: Set[Interest], oldInterests: Set[Interest]): Set[Interest] = {
  newInterests.headOption match {
    case None => oldInterests
    case Some(ni) =>
      oldInterests.find(oi => oi.keyword == ni.keyword) match {
        case None => loop(newInterests.tail, oldInterests + ni)
        case Some(k) => loop(newInterests.tail, oldInterests - k + k.copy(count = k.count + 1))
      }
  }
}
Run Code Online (Sandbox Code Playgroud)