为什么不是尾递归? [英] Why it is not a tail recursion?
问题描述
我有以下代码,我不明白,为什么它不是尾递归:
I have the following code, that I do not understand, why it is not a tail recursion:
override fun drop(n: Int): List<A> = if (n == 0) this else tail.drop(n - 1)
这是一个尾递归:
fun drop(n: Int): List<A> {
tailrec fun drop(n: Int, list: List<A>): List<A> =
if (n <= 0) list else when (list) {
is Cons -> drop(n - 1, list.tail)
is Nil -> list
}
return drop(n, this)
}
为什么第一个示例不是尾部递归?
Why is the first example not a tail recursion?
推荐答案
这不是尾递归,因为Kotlin会检查递归调用在同一接收者上.就您而言,这是正确的; drop
是一个虚函数(因为您使用了override
),因此tail.drop
可能具有不同的实现.对于非open
函数,存在问题 Tailrec优化未应用于不是此接收器,但似乎并未对其进行积极的处理.
It isn't tail recursion because Kotlin checks the recursive call is on the same receiver. In your case it's correct; drop
is a virtual function (since you use override
), so tail.drop
could have a different implementation. For non-open
functions there is the issue Tailrec optimization not being applied to tail recursive calls on a non-this receiver, but it doesn't seem to be actively worked on.
也请注意以下错误:打开endrec函数的递归调用生成不正确
这篇关于为什么不是尾递归?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!