什么是 Scala 注释以确保优化尾递归函数? [英] What is the Scala annotation to ensure a tail recursive function is optimized?

查看:55
本文介绍了什么是 Scala 注释以确保优化尾递归函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I think there is @tailrec annotation to ensure the compiler will optimize a tail recursive function. Do you just put it in front of the declaration? Does it also work if Scala is used in scripting mode (for instance using :load <file> under REPL)?

推荐答案

来自尾调用、@tailrec 和蹦床" 博客文章:

  • 在 Scala 2.8 中,您还可以使用新的 @tailrec 注释来获取有关优化了哪些方法的信息.
    此注释可让您标记希望编译器优化的特定方法.
    如果编译器未优化它们,您将收到警告.
  • 在 Scala 2.7 或更早版本中,您需要依靠手动测试或字节码检查来确定方法是否已优化.
  • 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.
  • In Scala 2.7 or earlier, you will need to rely on manual testing, or inspection of the bytecode, to work out whether a method has been optimised.

示例:

您可以添加一个 @tailrec 注释,以确保您的更改有效.

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 提示和技巧):

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 注释以确保优化尾递归函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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