About Tail Recursion(关于尾递归)

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

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.

你可能感兴趣的:(tail)