What is tail recursion?

前端 未结 28 3567
一个人的身影
一个人的身影 2020-11-21 05:03

Whilst starting to learn lisp, I\'ve come across the term tail-recursive. What does it mean exactly?

28条回答
  •  感情败类
    2020-11-21 05:21

    In short, a tail recursion has the recursive call as the last statement in the function so that it doesn't have to wait for the recursive call.

    So this is a tail recursion i.e. N(x - 1, p * x) is the last statement in the function where the compiler is clever to figure out that it can be optimised to a for-loop (factorial). The second parameter p carries the intermediate product value.

    function N(x, p) {
       return x == 1 ? p : N(x - 1, p * x);
    }
    

    This is the non-tail-recursive way of writing the above factorial function (although some C++ compilers may be able to optimise it anyway).

    function N(x) {
       return x == 1 ? 1 : x * N(x - 1);
    }
    

    but this is not:

    function F(x) {
      if (x == 1) return 0;
      if (x == 2) return 1;
      return F(x - 1) + F(x - 2);
    }
    

    I did write a long post titled "Understanding Tail Recursion – Visual Studio C++ – Assembly View"

提交回复
热议问题