[Python-Dev] Proper tail recursion

Andrew Koenig ark-mlist at att.net
Fri Jul 16 16:11:52 CEST 2004


> I think it's pretty hard to come up with a problem where the natural
> solution is tail recursive.

I might agree with you that it isn't easy to come up with a problem where
the natural problem is *entirely* tail recursive -- but my original
tree-traversal example is tail-recursive and I think it's more natural to
write it that way than it is to eliminate the tail recursion (leaving the
other recursion) by hand.

I've also seen examples of functions that begin like this:

	def foo(x, y):
		if x < 0:
			return foo(-x, -y)
		...

which I think is clearer than

	def foo(x, y)
		if x < 0:
			x = -x
			y = -y
		...

especially if there are several such cases to consider.  Of course there
isn't much to gain by removing this particular tail recursion, but
nevertheless it is a tail recursion that I think is more natural to leave in
place.



More information about the Python-Dev mailing list