Whilst starting to learn lisp, I\'ve come across the term tail-recursive. What does it mean exactly?
The best way for me to understand tail call recursion
is a special case of recursion where the last call(or the tail call) is the function itself.
Comparing the examples provided in Python:
def recsum(x):
if x == 1:
return x
else:
return x + recsum(x - 1)
^RECURSION
def tailrecsum(x, running_total=0):
if x == 0:
return running_total
else:
return tailrecsum(x - 1, running_total + x)
^TAIL RECURSION
As you can see in the general recursive version, the final call in the code block is x + recsum(x - 1)
. So after calling the recsum
method, there is another operation which is x + ..
.
However, in the tail recursive version, the final call(or the tail call) in the code block is tailrecsum(x - 1, running_total + x)
which means the last call is made to the method itself and no operation after that.
This point is important because tail recursion as seen here is not making the memory grow because when the underlying VM sees a function calling itself in a tail position (the last expression to be evaluated in a function), it eliminates the current stack frame, which is known as Tail Call Optimization(TCO).
NB. Do bear in mind that the example above is written in Python whose runtime does not support TCO. This is just an example to explain the point. TCO is supported in languages like Scheme, Haskell etc