尾递归
- Lua尾递归的实现
爆栈问题
基于栈实现函数调用的语言都有栈空间的上限,这里拿几个语言举例
#include <stdio.h>
int foo(int n){
printf("%d\n", n);
return foo(n+1);
}
int main()
{
foo(1);
return 0;
}
运行到258914次的时候出现segmentation fault
258911
258912
258913
258914
[1] 25175 segmentation fault ./trait
def foo(n):
print(n)
return foo(n+1)
foo(1)
运行到992次就爆栈了
993
994
995
996
Traceback (most recent call last):
File "trait.py", line 5, in <module>
foo(1)
File "trait.py", line 3, in foo
return foo(n+1)
File "trait.py", line 3, in foo
return foo(n+1)
File "trait.py", line 3, in foo
return foo(n+1)
[Previous line repeated 992 more times]
File "trait.py", line 2, in foo
print(n)
RecursionError: maximum recursion depth exceeded while calling a Python object
如何解决
解决爆栈的方式无非就两种
- 尾递归(Goto实现的状态机)
- 不解决
Go和lua的实现
function foo(n)
print(n)
return foo(n+1)
end
foo(1)
package main
import "fmt"
func foo(n int) int {
fmt.Println(n)
return foo(n+1)
}
func main() {
foo(1)
}
网友评论