A new module for performing tail-call elimination

Marko Rauhamaa marko at pacujo.net
Thu Jul 16 15:45:09 EDT 2015


Nobody seemed to notice that I just posted a fairly typical tail call
function:

========================================================================
    def setvalue(self, keyseq, value, offset=0):
        try:
            next = keyseq[offset]
        except IndexError:
            self.value = value
            return
        if next is Node.ANY:
            raise KeyError()
        try:
            child = self.children[next]
        except KeyError:
            self.children[next] = child = Node()
        child.setvalue(keyseq, value, offset + 1)
========================================================================

In the context, the tail call is at least as clear as the corresponding
while/for loop.

In the case of this function, tail call elimination is hardly needed
because the key sequence is probably not all that long (and if it were,
the accompanying lookup function would overflow the stack anyway). At
any rate, it demonstrates how the idiom has its place in Python.


Marko



More information about the Python-list mailing list