What is tail recursion?

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

    It is a special form of recursion where the last operation of a function is a recursive call. The recursion may be optimized away by executing the call in the current stack frame and returning its result rather than creating a new stack frame.

    A recursive function is tail recursive when recursive call is the last thing executed by the function. For example the following C++ function print() is tail recursive.

    An example of tail recursive function

        void print(int n) 
    { 
    if (n < 0)  return; 
    cout << " " << n; 
    print(n-1);} 
    
    
    
    // The last executed statement is recursive call 
    

    The tail recursive functions considered better than non tail recursive functions as tail-recursion can be optimized by compiler. The idea used by compilers to optimize tail-recursive functions is simple, since the recursive call is the last statement, there is nothing left to do in the current function, so saving the current function’s stack frame is of no use.

提交回复
热议问题