Home > Mobile >  python lambda evaluate expression
python lambda evaluate expression

Time:09-26

I am trying out lambda in python and came across this question:

def foo(y):
    return lambda x: x(x(y))
def bar(x):
    return lambda y: x(y)
print((bar)(bar)(foo)(2)(lambda x:x 1))

can someone explain/breakdown how this code works? I am having problems trying to figure out what is x and y.

CodePudding user response:

Lambda (in python) is just syntatic sugar. You can think of this structure:

anony_mouse = lambda x: x # don't actually assign lambdas

as equivalent to this structure:

def anony_mouse(x):
    return x

Thus let's write out the top example using standard function notation:

def foo(y):
    # note that y exists here
    def baz(x):
        return x(x(y))

    return baz

So we have a factory function, which generates a function which... expects to be called with a function (x), and returns x(x(arg_to_factory_function)). Consider:

>>> def add_six(x):
        return x   6
>>> bazzer = foo(3)
>>> bazzer(add_six) # add_six(add_six(3)) = 6 (6 3)

I could go on, but does that make it clearer?

Incidentally that code is horrible, and almost makes me agree with Guido that lambdas are bad.

CodePudding user response:

The 1st ‘(bar)’ is equal to just ‘bar’ so it is an ordinary function call, the 2nd — argument to that call, i.e. bar(bar) — substitute ‘x’ to ‘bar’ there any you will get what is result of bar(bar); the’(foo)’ argument passing to the result of bar(bar) it will be a lambda-function with some arg. — substitute it to ‘foo’ and get result and so on until you reach the end of expression

  • Related