Recursion 为什么它不是尾部递归?

Recursion 为什么它不是尾部递归?,recursion,kotlin,functional-programming,Recursion,Kotlin,Functional Programming,我不理解下面的代码,为什么它不是尾部递归: 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) {

我不理解下面的代码,为什么它不是尾部递归:

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)
}
override-fun-drop(n:Int):List=if(n==0)这个else-tail.drop(n-1)
而这是一个尾部递归:

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)
}
fundrop(n:Int):列表{
tailrec趣味下拉列表(n:Int,list:list):list=
if(n drop(n-1,list.tail)
是Nil->list
}
返回下降(n,本)
}

为什么第一个示例不是尾部递归?

它不是尾部递归,因为Kotlin检查递归调用是否在同一个接收器上。在您的情况下,它是正确的;
drop
是一个虚拟函数(因为您使用了
override
),因此,
tail.drop
可能有不同的实现。对于非
open
函数,存在问题,但它似乎没有得到积极的解决


请注意这个错误:

我不是100%确定,但我认为尾部调用必须在同一个对象上。因此
tail.drop(n-1)
不是尾部调用,因为它是在
tail
上调用的,而不是
this