天天看點

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.