What is tail-recursive

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/mybluesky1983/article/details/53575780

We used recursive programming, for example, 


def recsum(x):
  if x == 1:
    return x  else:    return x + recsum(x - 1)


But there is a problem recursion, recursive, computer used to store the stack, each recursive call once a layer stack, but the stack size is limited, multiple calls can lead to stack overflow

Here we need to use tail recursion

Tail recursion means that, when the function returns, calls itself itself, and, return statement can not contain expressions. In this way, the compiler or interpreter you can do to optimize tail recursion, the recursive call to itself, no matter how many times, only occupy a stack frame, stack overflow situation does not occur.


def tailrecsum(x, running_total=0):
  if x == 0:
    return running_total
  else:
    return tailrecsum(x - 1, running_total + x)


Although the example of using python write python interpretation but did not optimize tail recursion

Only C language


In the daily programming should try to avoid using recursion

Guess you like

Origin blog.csdn.net/mybluesky1983/article/details/53575780