Scala 中是否需要@tailrec 注释? [英] The need for the @tailrec annotation in Scala?

查看:68
本文介绍了Scala 中是否需要@tailrec 注释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解递归函数的问题以及堆栈溢出问题的风险.

I understand the problem with recursive functions and the risk of stack overflow issues.

然而,如果一个函数能够针对尾递归进行优化,那么为什么不自动应用这种优化,即.为什么我需要标记一个可以用 @tailrec 优化的函数?

However, if a function is able to be optimized for tail recursion then why isn't this optimization automatically applied ie. why do I need to mark a function that can be optimized with @tailrec?

推荐答案

如果一个函数能够针对尾递归进行优化,那么为什么不自动应用这种优化

if a function is able to be optimized for tail recursion then why isn't this optimization automatically applied

.

不幸的是,我没有从 SLS 中找到可以保证这一点的引用.

Unfortunately, I haven't found a quote from the SLS which would guarantee this, though.

为什么我需要标记一个可以用@tailrec优化的函数?

why do I need to mark a function that can be optimized with @tailrec?

注意:Scala 不保证函数的正确尾递归,只保证方法

Note: Scala doesn't guarantee proper tail recursion for functions, only for methods!

您不注释可以优化的方法.您注释了必须优化的方法,这样当它们不能被优化时,您会得到一个编译错误.

You don't annotate methods that can be optimized. You annotate methods that must be optimized, so that you will get a compile error, when they can't be optimized.

参见 scala.annotation.tailrec 的文档:

See the documentation for scala.annotation.tailrec:

一个方法注解,用于验证该方法将使用尾调用优化进行编译.

A method annotation which verifies that the method will be compiled with tail call optimization.

如果存在,如果该方法无法优化为循环,编译器将发出错误.

If it is present, the compiler will issue an error if the method cannot be optimized into a loop.

文档在优化什么方面具有误导性(尾调用优化",实际上 Scala 仅优化直接尾递归),但它em> 清楚注释的目的.

The documentation is misleading in exactly what is optimized ("tail call optimization", when really Scala only optimizes direct tail recursion) but it is clear about the purpose of the annotation.

这个注解的原因是有时人们对什么是直接尾递归和什么不是直接尾递归的直觉可能是错误的.这里有很多关于为什么 Scala 不优化我的尾递归方法"形式的问题,其答案是因为它不是尾递归".(以下是一个方法示例,其中无法优化的事实并不明显.)因此,通过对方法进行注释,您可以向编译器和其他开发人员发出信号,表明该方法必须优化.

The reason for this annotation is that sometimes people's intuition about what is and isn't direct tail recursion may be wrong. There are plenty of questions here on SO of the form "why doesn't Scala optimize my tail-recursive method" whose answer is "because it isn't tail-recursive". (Here is an example of a method where the fact that it can't be optimized is non-obvious.) So, by annotating a method, you signal both to the compiler and your fellow developers that this method must be optimized.

这篇关于Scala 中是否需要@tailrec 注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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