gpt4 book ai didi

scala - 在对象而非类上定义时,方法是尾部递归

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

在对象上定义递归方法:

object Recursive {
def recurse(maxDepth: Int = 10): Unit = {
if (maxDepth == 0) throw new Exception
recurse(maxDepth - 1)
}
}

给出:
scala> Recursive.recurse(10)
java.lang.Exception
at Recursive$.recurse(<console>:7)
at .<init>(<console>:7)
at .<clinit>(<console>)
at RequestResult$.<init>(<console>:9)
at RequestResult$.<clinit>(<console>)
at RequestResult$scala_repl_result(<console>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at scala.tools.nsc.Interpreter$Request$$anonfun$loadAndRun$1$$anonfun$apply$17.apply(Interpreter.scala:988)
at scala.tools.nsc.Interpreter$Request$$anonfun$loadAndRun$1$$anonfun$apply$17.apply(Interpreter.scala:988)
at scala.util.control.Exception$Catch.apply(Exception.scal...

但是在一个类上定义它:
class Recursive {
def recurse(maxDepth: Int = 10): Unit = {
if (maxDepth == 0) throw new Exception
recurse(maxDepth - 1)
}
}

给出:
scala> new Recursive recurse(10)
java.lang.Exception
at Recursive.recurse(<console>:7)
at Recursive.recurse(<console>:8)
at Recursive.recurse(<console>:8)
at Recursive.recurse(<console>:8)
at Recursive.recurse(<console>:8)
at Recursive.recurse(<console>:8)
at Recursive.recurse(<console>:8)
at Recursive.recurse(<console>:8)
at Recursive.recurse(<console>:8)
at Recursive.recurse(<console>:8)
at Recursive.recurse(<console>:8)
at .<init>(<console>:7)
at .<clinit>(<console>)
at RequestResult$.<init>(<console>:9)
at RequestResult$.<clinit>(<console>)
at RequestResult$scala_repl_result(<console>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcc..

方法是相同的。为什么在类上定义时不尾部递归?

最佳答案

如果要执行尾递归,则recurse不可覆盖。如果recurse是可重写的(如class声明中所述),则其中的任何递归都必须使用动态方法调用(因为它可能是多态的),无法将其优化为goto样式的语句。
object单例声明静态地确保了对递归的明确调用,并允许编译器进行尾递归优化。

关于scala - 在对象而非类上定义时,方法是尾部递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4698827/

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