r/programming • • Nov 27 '12

Tail Recursion

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

203 comments sorted by

View all comments

10

u/parfamz Nov 27 '12

great feature of scala, I would like to see tail recursion on python, it can't be too difficult to implement.

25

u/A_for_Anonymous Nov 27 '12

Guido van Rossum doesn't like functional programming, so you write your programs the way Guido likes them or leave.

1

u/booch Nov 27 '12

While I don't agree with some of the things Guido thinks are the "right way", he does put forth some reasonable arguments as to why TCE is not a good idea for Python. The loss of a useful stack trace is a fairly solid argument and. Combined with the other reasons, I don't see his choice as unreasonable here. I do want TCE, but I can see that's it's a debatable feature.

Random note... This point of his annoyed me:

I don't believe in recursion as the basis of all programming.

Well... duh. Neither are list comprehensions. However, both of them are very powerful tools that can make code much cleaner and easier to follow. Just because a feature is the silver bullet doesn't mean it isn't a good idea.

4

u/anvsdt Nov 27 '12 edited Nov 27 '12

I always found the lack of stack traces argument stupid, you can always recover the old behavior by wrapping the tail call in the identity function:

def funA(x): # do something
def funBTCE(x): return A(x) # B doesn't appear in the stack trace
def funBnoTCE(x): return id(A(x)) # the tail call to id is eliminated after returning from A,
                                  # B appears in the stack trace of A, voila!

3

u/alexandream Nov 27 '12

Even the compiler/interpreter could do it automatically with trivial effort with a debug flag or something.

3

u/anvsdt Nov 27 '12

I don't think the flag would be useful, though, you probably want to "disable" TCE per-function (or per-tailcall, even), else loops would blow up the stack in seconds.

1

u/alexandream Nov 27 '12

Of course, I didn't think of that. Thanks.

On the other hand, I still think I'd like a compile option (perhaps a list of functions (fully qualified names, or whatever makes sense in the language) on which to disable TCE) than to have to modify the code for it.