I couldn't find articles describing why tail recursive functions should be preferred over iterative algorithms.
I'm not asking why tail recursive is better than simple recursive which I think is clearly explained everywhere.
So why
sum(n) = {
def sumImpl(n, acc) = if(n <= 0) acc else sumImpl(n - 1 , n + accumulator)
sumImpl(n, 0)
}
is preferable to
sum = 0;
while(n--) sum += n
Recursion is when a function calls itself within its code, thus repeatedly executing the instructions present inside it. Iteration is when a loop repeatedly executes the set of instructions like "for" loops and "while" loops.
The tail recursion is better than non-tail recursion. As there is no task left after the recursive call, it will be easier for the compiler to optimize the code. When one function is called, its address is stored inside the stack. So if it is tail recursion, then storing addresses into stack is not needed.
(algorithmic technique) Definition: 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.
In simple, the main difference between the traditional recursion and tail recursion is when the actual calculation takes place. In traditional recursion, calculation will happen after the recursion call while the calculation will occur before the recursion call in tail recursion.
Recursion makes a program more readable, but it gives poor performance. Iterative procedures give good performance but are not that readable and may require a local variable to store an intermediate value (mutability). Using tail recursion you will get the best of both worlds and no "sum" variable is needed (immutability). This is very useful in calculating large number sums or factorials, because you will never get a stackoverflow exception as you just forward the result to the next recursive function call.
In a parallel environment immutability is very important. Try to edit your code and pass very large numbers to the function to see the difference.
Further reading here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With