Tail recursive versus iterative algorithms

I could not find articles describing why tail recursive functions should be preferable to iterative algorithms.

I am not asking why a tail recursive is better than a simple recursive one, which, it seems to me, 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) } 

preferable

 sum = 0; while(n--) sum += n 
+4
source share
1 answer

Recursion makes the program more readable, but it gives poor performance. Iterative procedures give good performance, but are not as readable and may require a local variable to retain an intermediate value (variability). Using tail recursion, you get the best of both worlds, and no "sum" variable is needed (immutability). This is very useful when calculating large sums or factorials, because you will never get a stackoverflow exception, because you simply forward the result to the next call to the recursive function.

In a parallel environment, immutability is very important. Try editing the code and passing very large numbers to functions to see the difference.

Further reading here

+5
source

Source: https://habr.com/ru/post/1439779/


All Articles