Why it is not a tail recursion?

China☆狼群 提交于 2021-02-07 20:11:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!