A new module for performing tail-call elimination
steve+comp.lang.python at pearwood.info
Thu Jul 16 10:07:03 CEST 2015
On Wednesday 15 July 2015 19:29, Antoon Pardon wrote:
> Suppose I start with the following:
> def even(n):
> True if n == 0 else odd(n - 1)
> def odd(n):
> False if n == 0 else even(n - 1)
Well, both of those always return None, so can be optimized to:
even = odd = lambda x: None
Fixing the obvious mistake (failing to return anything) leads to the next
mistake. When all you have is a hammer, everything looks like a nail.
return n%2 == 0
return n%2 != 0
are faster, easier to understand, and don't turn into an infinite loop if
you pass a negative integer.
The point is, people keep insisting that there are a vast number of
algorithms which are best expressed using recursion and which require TCO to
be practical, and yet when asked for examples they either can't give any
examples at all, or they give examples that are not well-suited to
recursion. Or, at best, examples which are equally good when written either
using recursion or iteration.
I do believe that such examples surely must exist. But I'm yet to see one.
More information about the Python-list