在我看来,以下功能为尾递归
但是编译器仍然抱怨如果我在上面放一个@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))
    }
  }
}

最佳答案

如fourtheye所述,您的函数返回fold的结果。尾部递归版本(具有模式匹配)如下所示:

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

10-08 19:47