首页 > 其他 > 详细

About Tail Recursion(关于尾递归)

时间:2014-12-02 02:16:18      阅读:319      评论:0      收藏:0      [点我收藏+]

为了锻炼英语水平,为以后出国工作提前准备,我就用英文写了,也没查字典,可能有语法错误,欢迎大家指正。。

When we have to recursion we always prefer to use loop rather than recursion.?

Because when the recursion goes deep the stack will always overflow. Its like a nightmare to us. Why stack always overflow? Look at the code below.

?

```erlang

normal(N) when N > 0 -> N + normal(N - 1);

normal(0) -> 0.

```

Every time before the recursion goes to the next level, the stack always have to save N and the ‘normal‘ function’s status. So if the recursion goes deeper it ?will cost out the stack’s space.

?

But if we use tail recursion it will not happen again. Look at the code below.

?

```erlang

tail(N) -> tail(N, 0).

?

tail(N, Result) when N > 0 -> tail(N - 1, N + Result);

tail(0, Result) -> Result.

```

?

In tail recursion we don’t need to save any status in stack. Because all result is in the parameters of next recursion. So the stack can fix the size.

About Tail Recursion(关于尾递归)

原文:http://wudixiaotie.iteye.com/blog/2162057

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!