What is tail recursion?

前端 未结 28 3571
一个人的身影
一个人的身影 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:11

    A tail recursion is a recursive function where the function calls itself at the end ("tail") of the function in which no computation is done after the return of recursive call. Many compilers optimize to change a recursive call to a tail recursive or an iterative call.

    Consider the problem of computing factorial of a number.

    A straightforward approach would be:

      factorial(n):
    
        if n==0 then 1
    
        else n*factorial(n-1)
    

    Suppose you call factorial(4). The recursion tree would be:

           factorial(4)
           /        \
          4      factorial(3)
         /             \
        3          factorial(2)
       /                  \
      2                factorial(1)
     /                       \
    1                       factorial(0)
                                \
                                 1    
    

    The maximum recursion depth in the above case is O(n).

    However, consider the following example:

    factAux(m,n):
    if n==0  then m;
    else     factAux(m*n,n-1);
    
    factTail(n):
       return factAux(1,n);
    

    Recursion tree for factTail(4) would be:

    factTail(4)
       |
    factAux(1,4)
       |
    factAux(4,3)
       |
    factAux(12,2)
       |
    factAux(24,1)
       |
    factAux(24,0)
       |
      24
    

    Here also, maximum recursion depth is O(n) but none of the calls adds any extra variable to the stack. Hence the compiler can do away with a stack.

提交回复
热议问题