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

时间:2015-12-10 07:27:20

标签: 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))
    }
  }
}

1 个答案:

答案 0 :(得分:7)

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

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