I am learning recursion and was reading about head
and tail
recursion. It is told that head recursion does recursive call first and then does the calculation on the result. The tail recursion on the other hand does all the processing before doing the recursive call first.
The head recursion can reduce the data passed to the recursive calls, while the tail recursion can result in passing additional data to the recursive calls.
So, basically I want to know is there any benefit I get by using one over another? and how to get to know which one is used in a given function.
AFAIK the below power function (defined for whole numbers) is using head recursion
:
def power(num, exponent):
if exponent <= 1:
return num
else:
return num * power(num, exponent-1)
Note:
The real reason we would use recursion is for a simple way of storing values on a 'path' for future use. Recursion store's the state of the algorithm at each level and allows the user to come back to that exact state later on. We will see this in use when using the tree traversal routines.
It will be good if someone can shed some light on the above statement as I perceive it as a very important for getting a deeper insight.