What is the logic used to break down multiple lambda variables in python?
Question:
I am trying to reason through why the result of the following would be 8 but I’m a little stuck.
f = lambda x,y: lambda z: (x)(y)(z)
print((f)(lambda x: lambda y: x, lambda z: z*2)(3)(4))
I know that the next step would be to substitute f into the line as shown below, but this is where I get lost.
ans = (lambda x,y: lambda z: (x)(y)(z))(lambda x: lambda y: x, lambda z: z*2)(3)(4)
From my understanding, f requires three arguments in total, one in this (x,y) format and another one like (z).
(lambda x: lambda y: x, lambda z: z*2)(3)(4)
I think 3 should be the argument for lambda x and nothing should be inputted for lambda y. I think 4 would then be the argument for lambda z.
This leads me to think (3,8) is what is returned for (lambda x: lambda y: x, lambda z: z*2), but then I don’t have an input for lambda z in the original f.
I could use explanation of how this is processed to give a final answer of 8. Apologies for any formatting errors.
Answers:
Let’s give a name to some of those lambdas:
const = lambda x: (lambda y: x)
double = lambda z: (z*2)
And eta-reduct the lambda z:...
inside f
(that is lambda z: ( x(y) )(z) -> x(y)
):
f = lambda x, y: x(y)
We can now rewrite that expression as ( ( f(const, double) )(3) )(4)
.
Reducing, we get:
f(const, double) -> const(double) -> lambda y: double
(lambda y: double)(3) -> double
double(4) -> 8
I am trying to reason through why the result of the following would be 8 but I’m a little stuck.
f = lambda x,y: lambda z: (x)(y)(z)
print((f)(lambda x: lambda y: x, lambda z: z*2)(3)(4))
I know that the next step would be to substitute f into the line as shown below, but this is where I get lost.
ans = (lambda x,y: lambda z: (x)(y)(z))(lambda x: lambda y: x, lambda z: z*2)(3)(4)
From my understanding, f requires three arguments in total, one in this (x,y) format and another one like (z).
(lambda x: lambda y: x, lambda z: z*2)(3)(4)
I think 3 should be the argument for lambda x and nothing should be inputted for lambda y. I think 4 would then be the argument for lambda z.
This leads me to think (3,8) is what is returned for (lambda x: lambda y: x, lambda z: z*2), but then I don’t have an input for lambda z in the original f.
I could use explanation of how this is processed to give a final answer of 8. Apologies for any formatting errors.
Let’s give a name to some of those lambdas:
const = lambda x: (lambda y: x)
double = lambda z: (z*2)
And eta-reduct the lambda z:...
inside f
(that is lambda z: ( x(y) )(z) -> x(y)
):
f = lambda x, y: x(y)
We can now rewrite that expression as ( ( f(const, double) )(3) )(4)
.
Reducing, we get:
f(const, double) -> const(double) -> lambda y: double
(lambda y: double)(3) -> double
double(4) -> 8