Reputation: 25
I don't understand how this lambda function knows x is equal to 1?
def one(f = None): return 1 if not f else f(1)
def two(f = None): return 2 if not f else f(2)
def plus(y): return lambda x: x+y
one(plus(two()))
3
I know that the inner function two() returns 2 because f is defaulted to None. Thus y= 2. But how does the lambda function know to look to the outmost function for the x value?
Upvotes: 0
Views: 161
Reputation: 71570
Let's run through the steps first:
one
gets a value, f
, as plus(two())
.
plus
gets a value as two
, two
is gonna be 2
since no f
.
Okay, so since one
gets the value of that, it gonna condition and see that it shouldn't return 1
, so does f(1)
the f
is the unfinished lambda
process, the lambda
needs one parameter more to add up, so it got 1
, so 2 + 1
is 3
.
That is the whole process really.
Upvotes: 0
Reputation: 174
If you look at one()
it passes "1" into a function which you pass in the arguments (if a function is passed. otherwise 1 is returned). Thus, it evaluates to f(1)
(see in the else of one). The function you pass to one()
is lambda x: x + 2
(since y=2
). Thus, this evaluates to lambda 1: 1 + 2
If you call one(lambda x: 50)
, it returns 50
.
Upvotes: 2
Reputation: 19352
plus
returns a (lambda) function. That function is passed to one
. Within the scope of one
, it is called f
.
Then f
(which is actually the lambda from returned from plus
) is called in f(1)
.
In other words, the code one(plus(two()))
does this:
number2 = two()
lambda_function = plus(number2)
result = one(lambda_function)
Upvotes: 2