gpt4 book ai didi

scala - 确保尾递归函数得到优化的 Scala 注释是什么?

转载 作者:行者123 更新时间:2023-12-03 04:59:40 24 4
gpt4 key购买 nike

我认为有@tailrec注解以确保编译器将优化尾递归函数。你只是把它放在声明前面吗?如果 Scala 在脚本模式下使用(例如在 REPL 下使用 :load <file>),它也可以工作吗?

最佳答案

来自“Tail calls, @tailrec and trampolines”博客文章:

  • In Scala 2.8, you will also be able to use the new @tailrec annotation to get information about which methods are optimised.
    This annotation lets you mark specific methods that you hope the compiler will optimise.
    You will then get a warning if they are not optimised by the compiler.
  • 在 Scala 2.7 或更早版本中,您需要依靠手动测试或字节码检查来确定方法是否已优化。

示例:

you could add a @tailrec annotation so that you can be sure that your changes have worked.

import scala.annotation.tailrec

class Factorial2 {
def factorial(n: Int): Int = {
@tailrec def factorialAcc(acc: Int, n: Int): Int = {
if (n <= 1) acc
else factorialAcc(n * acc, n - 1)
}
factorialAcc(1, n)
}
}
<小时/>

它在 REPL 中工作(来自 Scala REPL tips and tricks 的示例):

C:\Prog\Scala\tests>scala
Welcome to Scala version 2.8.0.RC5 (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_18).
Type in expressions to have them evaluated.
Type :help for more information.

scala> import scala.annotation.tailrec
import scala.annotation.tailrec

scala> class Tails {
| @tailrec def boom(x: Int): Int = {
| if (x == 0) throw new Exception("boom!")
| else boom(x-1)+ 1
| }
| @tailrec def bang(x: Int): Int = {
| if (x == 0) throw new Exception("bang!")
| else bang(x-1)
| }
| }
<console>:9: error: could not optimize @tailrec annotated method: it contains a recursive call not in tail position
@tailrec def boom(x: Int): Int = {
^
<console>:13: error: could not optimize @tailrec annotated method: it is neither private nor final so can be overridden
@tailrec def bang(x: Int): Int = {
^

关于scala - 确保尾递归函数得到优化的 Scala 注释是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3114142/

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