Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tail recursive vs iterative algorithms

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
like image 418
raisercostin Avatar asked Oct 15 '12 09:10

raisercostin


People also ask

What is the difference between recursive and iterative algorithms?

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.

Why is tail-recursive function better?

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.

What is a tail-recursive algorithm?

(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.

What is the difference between tail recursion and recursion?

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.


1 Answers

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

like image 81
sgud Avatar answered Oct 02 '22 14:10

sgud