views:

388

answers:

3

So apparently, there's been a big brouhaha over whether or not Python needs tail call optimization. This came to a head when someone shipped Guido a copy of SICP because he didn't "get it." I'm in the same boat as Guido. I understand the concept of tail call optimization. I just can't think of any reason why Python really needs it.

To make this easier for me to understand, could someone give me a snippet of code that would be greatly simplified using TCO?

+4  A: 

Tail call optimization makes it easier to write recursive functions without worrying about a stack overflow:

def fac(n, result=1):
        if n > 1:
                return fac(n - 1, n * result)
        return result

Without tail call optimization, calling this with a big number could overflow the stack.

Zifre
Standard academic example. Any example with real world usage?
ebo
in fact, this isn't tail recursive. the multiplication is in the tail, not the recursion.
Javier
def fac(n): return reduce(operator.mul, range(1, n+1))
John Fouhy
@Javier, the multiplication is in the tail, and there is no "pending" operation to perform, once the recursive call returns. Hence, that makes it tail recursive. Please correct me if I am wrong.
Amit
@Amit: He was correct originally, I changed the example. But even with the original, a smart compiler could have optimized it.
Zifre
@Zifre: right, the new form is so widely recognized as efficient, that Scheme purists refer to this as 'iteration, not recursion', since the TCO produces the same code as a while(){...} loop
Javier
+8  A: 

Personally, i put great value on tail call optimization; but mainly because it makes recursion as efficient as iteration (or makes iteration a subset of recursion). On minimalistic languages you get huge expressive power without sacrificing performance.

On a 'practical' language (like Python), OTOH, you usually have a lot of other constructions for almost every situation imaginable, so it's less critical. Always a good thing to have, to allow for unforeseen situations, of course

Javier
That's about what I suspected, but I figured there must be a bigger reason for it. I suppose I was wrong.
Jason Baker
but remember that those 'minimalistic languages' that i mention (Lua and Scheme, for example) are usually both nicer and much faster than Python. in part because having reliable tail call optimization frees your mind and makes programs clearer. unfortunately, i don't know any one as practical as Python.
Javier
+4  A: 

If you intensely want to use recursion for things that might alternatively be expressed as loops, then "tail call optimization" is really a must. However, Guido, Python's Benevolent Dictator For Life (BDFL), strongly believes in loops being expressed as loops -- so he's not going to special-case tail calls (sacrificing stack-trace dumps and debugging regularity).

Alex Martelli