pythonrecursionchurch-encoding

unfolding recursive expressions


I've been recently working with recursive expressions in Python. An example of such expression is given as:

['+', [['*', ['i0','i1']], ['*', ['i2','i3']]]]

I'm attempting to transform expressions like these into something I can directly compute, e.g.,

(i0*i1) + (i2*i3)

Intuitively, it seems some form of recursion is needed, however, I cannot wrap my head around this problem for some reason.

Thanks!


Solution

  • A way that can also handle more than two operands:

    def transform(e):
        if isinstance(e, str):
            return e
        return '(' + e[0].join(map(transform, e[1])) + ')'
    

    Demo:

    >>> transform(['+', [['*', ['i0', 'i1']], ['*', ['i2', 'i3', 'i4']]]])
    '((i0*i1)+(i2*i3*i4))'