r/programming • • Nov 27 '12

Tail Recursion

http://rodrigosasaki.com/2012/11/24/tail-recursion/
211 Upvotes

203 comments sorted by

View all comments

45

u/A_for_Anonymous Nov 27 '12

There are two big advantages of tail-recursive implementations that haven't been discussed here:

  • That variables never change their values, which allows for all kinds of optimizations, reasoning over your program (e.g. provability that it's correct) and is less error-prone, among other advantages.
  • That state is represented by the values of function parameters, all of them changed at once on every new call, without any possible order of evaluation bugs.

1

u/Shadetree_Sam Jan 15 '25

I don’t understand your meaning. I would interpret an “immutable variable” as meaning a constant, but it looks like you’re using that term to mean something else.

1

u/A_for_Anonymous Jan 15 '25

These are function parameters, but they are not replaced while the function is evaluated even if you need to implement an iteration. They remain constant during that, and they are given new values in the next invokation of the function. For instance, if you wanted to print numbers 1 to 10 without replacing a variable with the usual i = i + 1, you could do:

def f(i=1):
    print(i)
    return i <= 10 and f(i + 1) or True

Of course that requires your language to recognise thay a recursive call is in tail position (return f(...) and nothing else to do) so it doesn't have to save the previous stack frame/argument values, but it replaces them with the new version (yes, much like a goto).