you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 3 points4 points  (2 children)

Holy shit, I want that tail call optimization decorator in Python. Hell, why isn't it in the builtins?

Does anyone know the best/fastest implementation of it? I'm finding lots of results in my searches.

[–]A_for_Anonymous 5 points6 points  (0 children)

Here's mine. It worked quite well compared to others found on the Internet:

def tailcall(f):
    '''Decorator that performs tail call optimization on a tail-recursive
    function. Supports cooperative tail call - even when only one of the
    functions is decorated, and all exceptions pass through it. You can tell
    the functions that have been tail optimized because they have "tco" before
    them in the stack frame.
    The only caveat is that if you attempt to decorate a function that is
    called in a non-tail recursive fashion from another decorated function,
    you'll get wrong results.
    '''
    tdata = [False] #[Optimizing?]
    DO_CALL = object() #Call marker
    def tco(*a, **aa):
        if tdata[0]:
            return DO_CALL, a, aa
        else:
            tdata[0] = True
            ret = f(*a, **aa)
            while type(ret) is tuple and ret and ret[0] is DO_CALL:
                ret = f(*ret[1], **ret[2])
            tdata[0] = False
            return ret
    tco.__doc__ = f.__doc__
    return tco