Python is not bad ;-)

Chris Angelico rosuav at gmail.com
Sat May 2 07:21:44 EDT 2015


On Sat, May 2, 2015 at 9:07 PM, Christian Gollwitzer <auriocus at gmx.de> wrote:
> I need to add, I grew up with imperative programming, and as such got
> recursion as the solution to problems that are too complex for iteration,
> i.e. tree traversal and such, and exactly these are never tail-recursive.

Tree traversal can be forking-recursive:

def walk(func):
    if self.left and self.left.walk(func): return 1
    if func(self.payload): return 1
    if self.right: return self.right.walk(func)

The left walk is non-tail-recursive, but the right walk is. This
particular style looks rather less clean with iteration:

def walk(func):
    while True:
        if self.left and self.left.walk(func): return 1
        if func(self.payload): return 1
        if not self.right: break
        self = self.right

I'd call this an example of fairly natural tail recursion.

ChrisA



More information about the Python-list mailing list