"Updating" lambda functions

Oliver Fromme olli at haluter.fromme.com
Thu Sep 16 16:07:20 CEST 2004


I'm trying to write a Python function that parses
an expression and builds a function tree from it

During parsing, lambda functions for the the terms
and sub-expressions are constructed on the fly.
Now my problem is lazy evaluation.  Or at least I
think it is.  :-)

I need to "update" a lambda function, like this:

        fu = lambda x: x
        fu = lambda x: fu(x) + 17
        fu = lambda x: fu(x) * 3

Of course that doesn't work, because fu is resolved
when the lambda is called, not when it's defined, so
I'll run into an endless recursion.

My current solution is to define a helper function
which passes the lambda through its argument:

        def add_17 (fu):
                return lambda x: fu(x) + 17

        def mul_3 (fu):
                return lambda x: fu(x) * 3

        fu = lambda x: x
        fu = add_17(fu)
        fu = mul_3(fu)

That works, but it strikes me as unclean and ugly.
Is there a better way to do it?

Best regards

Oliver Fromme, Konrad-Celtis-Str. 72, 81369 Munich, Germany

``All that we see or seem is just a dream within a dream.''
(E. A. Poe)

More information about the Python-list mailing list