Scala 函数–尾递归

2018-09-28 18:25 更新

函数–尾递归

``````def approximate(guess: Double) : Double =
if (isGoodEnough(guess)) guess
else approximate(improve(guess))``````

``````def approximateLoop(initialGuess: Double) : Double = {
var guess = initialGuess
while(!isGoodEnough(guess))
guess=improve(guess)
guess
} ``````

跟踪尾递归函数

``````scala> def boom(x:Int):Int=
|   if(x==0) throw new Exception("boom!") else boom(x-1) + 1
boom: (x: Int)Int``````
``````scala> boom(5)
java.lang.Exception: boom!
at .boom(<console>:8)
at .boom(<console>:8)
at .boom(<console>:8)
at .boom(<console>:8)
at .boom(<console>:8)
at .boom(<console>:8)
... 32 elided``````

boom 不是一个尾递归，因为最后一行为一个递归加一操作，可以看到调用 boom(5)的调用栈，为多层。

``````scala> def bang(x:Int):Int=
|        if(x==0) throw new Exception("boom!") else bang(x-1)
bang: (x: Int)Int``````
``````scala> bang(5)
java.lang.Exception: boom!
at .bang(<console>:8)
... 32 elided``````

尾递归的一些局限性

``````def isEven(x:Int): Boolean =
if(x==0) true else isOdd(x-1)
def isOdd(x:Int): Boolean=
if(x==0) false else isEven(x-1)``````

isEven 和 isOdd 事件也是为递归，但不是直接定义的尾递归，scala 编译器无法对这种递归进行优化。

App下载