Functional Programming and python

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Sep 30 20:41:18 EDT 2013


On Mon, 30 Sep 2013 19:04:32 +0200, Franck Ditter wrote:

> Good approach of FP in Python, but two points make me crazy : 1. Tail
> recursion is not optimized. We are in 2013, why ? This is known
> technology (since 1960). And don't answer with "good programmers don't
> use recursion", this is bullshit.

Tail recursion optimization isn't really that useful. There is a HUGE 
universe of recursive problems which are not tail-recursive, and so 
cannot be optimized at all, or at least not automatically. Instead of 
encouraging people to rewrite such code using tail-recursion, which 
usually ends up obfuscating the code and introducing subtle bugs, it is 
better to encourage them to rewrite it to be iterative instead of 
recursive. Or just use recursion -- in many cases (although not all), if 
you have to recurse so many times that you pass the limit, your code is 
probably doing something wrong.

So tail-recursion optimization only helps in a tiny subset of recursive 
problems. Usually it doesn't help at all. And one cost is that you lose 
debugging information. Don't think of a single recursive function, where 
the traceback is extremely boring:

py> f()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in f
  File "<stdin>", line 2, in f
  [...]
  File "<stdin>", line 2, in f
  File "<stdin>", line 2, in f
  File "<stdin>", line 2, in f
RuntimeError: maximum recursion depth exceeded


Think of mutually recursive functions, where f calls g which calls h 
which sometimes calls f and sometimes calls g...

Personally, I'm not 100% convinced by these arguments. I think having a 
runtime option to enable or disable tail recursive optimizations would 
make Python a better language. Not by a lot, but by a tiny bit. But the 
people who would actually do the work don't care enough to do it, and the 
people who say they care don't bother doing the work.


> 2. Lambda-expression body is limited
> to one expression. Why ?

Nobody has come up with syntax that is unambiguous, would allow multiple 
statements in an expression, doesn't break backwards compatibility, and 
isn't ugly.

Since lambda is just a convenience, not a necessity -- it almost got 
dropped from Python 3 -- it is not worth compromising on those design 
requirements just for multiple-statement lambdas. It simply isn't 
important enough.



-- 
Steven



More information about the Python-list mailing list