gpt4 book ai didi

scala - Scala 中是否需要@tailrec 注释?

转载 作者:行者123 更新时间:2023-12-05 00:57:06 26 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





What is the Scala annotation to ensure a tail recursive function is optimized?

(3 个回答)


5年前关闭。




我了解递归函数的问题和堆栈溢出问题的风险。

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

最佳答案

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



这是。

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

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



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

您没有注释可以优化的方法。您注释必须优化的方法,以便在无法优化时出现编译错误。

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 仅优化直接尾递归),但很清楚注释的目的。

这个注释的原因是有时人们对什么是直接尾递归和什么不是直接尾递归的直觉可能是错误的。这里有很多关于“为什么 Scala 不优化我的尾递归方法”形式的问题,其答案是“因为它不是尾递归”。 ( Here is an example of a method where the fact that it can't be optimized is non-obvious. ) 因此,通过对方法进行注释,您可以向编译器和其他开发人员发出信号,表明必须优化此方法。

关于scala - Scala 中是否需要@tailrec 注释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35010965/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com