递归调用不在尾部位置 [英] Recursive call not in tail position

查看:55
本文介绍了递归调用不在尾部位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我定义了以下函数:

Say I define the following function:

final def myFunc[T](list: List[T]): List[T] = list match {
        case h :: t =>
            h :: myFunc(t)
        case _ =>
            Nil
    } 

当我添加一个 tailrec 注释时,编译器给了我以下错误:

When I add a tailrec annotation the compiler gives me the following error:

无法优化@tailrec 注释的方法 myFunc:它包含一个递归调用不在尾部位置:^Nil.

could not optimize @tailrec annotated method myFunc: it contains a recursive call not in tail position: ^Nil.

我对 Nil 的声明如何成为递归调用感到困惑?

I am confused as to how the declaration of Nil can be a recursive call?

推荐答案

问题不在于 Nil 而在于 h :: myFunc(t) 因为 myFunc(t) 不是最后一次调用.最后一次调用是对 myFunc(t) 的结果的运算符 ::.这就是函数不是尾递归的原因.

The problem is not with the Nil but with h :: myFunc(t) because myFunc(t) is not the last call. The last call is to the operator :: on the result of myFunc(t). That is why the function is not tail recursive.

这篇关于递归调用不在尾部位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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