为什么下面的函数不是尾递归的?
Why the following function is not tail recursive?
下面的函数在我看来是尾递归的
但是如果我在它上面放一个 @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))
}
}
}
如 thefourtheye 所述,您的函数 returns 是 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))
}
}
}
下面的函数在我看来是尾递归的
但是如果我在它上面放一个 @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))
}
}
}
如 thefourtheye 所述,您的函数 returns 是 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))
}
}
}