How explain why Python is easier/nicer than Lisp which has a simpler grammar/syntax?

Richard Damon Richard at Damon-Family.org
Sat Aug 15 10:55:28 EDT 2020


A few comments come to mind about this discussion about TCO.

First, TCO, Tail Call Optimization, is talking about something that is
an optimization.

Optimizations, are generally some OPTIONAL improvement in the method of
executing the code that doesn't alter its DEFINED meaning.

First big point, they are optional. Yes, some languages may define
certain circumstances where where there is a promise that a given
optimization will be done, but this is unusual. Some things that might
seem like optimizations, really aren't but are defined behaviors, like
the short cutting operators 'and' and 'or' where the fact that the
second operand isn't always evaluated could be though of as an optimization.

Second, optimizations are generally only allow to be performed if it
doesn't change any defined behavior of the program. I am not so sure
that is possible for TCO to be done in python based on that.

for example, given:

def foo(x):

    if x == 0: return 1

    else return foo(x-1)

def bar(x)

    if x == 0: return 2

    else return bar(x-1)

t = foo

foo = bar

bar = t

foo(1)


By the twiddling done at the end, we have changed the self
tail-recursive functions into mutually tail-recursive functions. The
fact we can do this says that when compiling foo and bar into byte-code,
the recursive call to foo can't just automatically go to the beginning
of the current function, but needs to look up the name and enter with a
possibly need operation, something like a tail-call which becomes more
of a jump as it doesn't create a new stack frame but somehow replaces
the current frame with what will be the new frame while binding the 'new
x' with the old 'x-1'

Second, because Python has defined things like traceback, the presence
of TCO is observable, and thus violates one of the basic guidelines of
an optimization, that it shouldn't change defined behavior.

In my mid, this says that for Python to proper support TCO, it may need
to do something to make it an explicit request, or at least defined
specifically when it will do it and when not.

Perhaps it could be defined that a return statement whose top level of
the expression is a function call, becomes an optimized tail call,
ALWAYS (at least with that version of Python), or maybe some sort of
flag needs to also be on the statement to avoid making it a backwards
breaking change.



More information about the Python-list mailing list