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>0){ sum += n; n--;}
Old buggy version (and assuming that is not because of such bugs are easier to spot)
sum = 0;
while(n--) sum += n
sum1(n-1), where I writesum1for your first function which you also namedsum. the hand-rolled iteration is so very often much more prone to such errors than its equivalent syntactically recursive formulation. specifically,while(n--)decrementsnbefore it is added to the accumulator, so the very firstnvalue is missed.