What is tail recursion?

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

    Tail recursion refers to the recursive call being last in the last logic instruction in the recursive algorithm.

    Typically in recursion, you have a base-case which is what stops the recursive calls and begins popping the call stack. To use a classic example, though more C-ish than Lisp, the factorial function illustrates tail recursion. The recursive call occurs after checking the base-case condition.

    factorial(x, fac=1) {
      if (x == 1)
         return fac;
       else
         return factorial(x-1, x*fac);
    }
    

    The initial call to factorial would be factorial(n) where fac=1 (default value) and n is the number for which the factorial is to be calculated.

提交回复
热议问题