为什么不是尾递归? [英] Why it is not a tail recursion?

查看:67
本文介绍了为什么不是尾递归?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,我不明白,为什么它不是尾递归:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆