[Python-ideas] Tail recursion elimination
spir
denis.spir at gmail.com
Sun Jan 19 15:03:05 CET 2014
On 01/19/2014 12:09 AM, Terry Reedy wrote:
I share all your views except for the following, which in my view is incomplete:
> 1) A tail call is a 'top level' call in a return statement.
> return f(*args, **kwds)
> A directly recursive call, where f refers to the function with the return
> statement, is a special case.
This is also true for "actions" (rather than proper functions, which purpose is
to compute a new piece of data). It's actually rather common (also in C ;-).
There is no data procuct. (see PS)
Denis
PS: An example may be an "action" writing out list items which calls, or rather
delegates to, another action that writes additional items preceded by a separator.
def write_items (stream, l):
n = len(l)
if n == 0:
stream.write('\n')
return
stream.write(str(l[0]))
if n == 1 : return
write_other_items(stream, l, n) # tail call
def write_other_items (stream, l, n):
for i in range(1,n):
stream.write(" ")
stream.write(str(l[i]))
stream.write('\n')
from sys import stdout
l = []
write_items(stdout, l)
l = [1]
write_items(stdout, l)
l = [1,2,3]
write_items(stdout, l)
More information about the Python-ideas
mailing list