假设我有以下代码在Scala中可以保证尾递归优化吗?
def foo(x:Int):Unit = {
if (x == 1) println ("done")
else foo(scala.util.Random.nextInt(10))
}
能够保证所有的编译器做尾递归优化?
假设我有以下代码在Scala中可以保证尾递归优化吗?
def foo(x:Int):Unit = {
if (x == 1) println ("done")
else foo(scala.util.Random.nextInt(10))
}
能够保证所有的编译器做尾递归优化?
没有,则Unit
返回类型是无关紧要的。
scala> @tailrec def f(i: Int) { if (i >= 0) { println(i); f(i - 1) } }
f: (i: Int)Unit
但是:
scala> @tailrec def f(i: Int) { if (i >= 0) { f(i - 1); println(".") } }
<console>:11: error: could not optimize @tailrec annotated method f:
it contains a recursive call not in tail position
你需要有递归调用的最后一次通话,返回类型并不重要。
你在问题中的代码是好的,但问题的标题会误导。
同意。我编辑了标题。感谢您的反例。 – Jus12
我不知道Scala保证你什么,但是在JVM的一般情况下并不实现尾递归。 (对于tailrec调用没有JVM字节码) –
@Basile Starynkevitch:Scala可以编译简单的尾循环递归循环。一些JVM支持“自动”尾部递归,但不幸的是Oracle不支持。 – Landei