问题
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)
whereas this is a tail recursion:
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?
回答1:
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.
Note this bug as well: Recursive calls to open tailrec functions are generated incorrectly
来源:https://stackoverflow.com/questions/60202108/why-it-is-not-a-tail-recursion