I hope it will be relatively easy to follow.
two_to_one = lambda g: (lambda y: g(y,y))
two_to_one
is a function, with an input of a function (g
: a function with an input of two parameters (as seen in g(y,y)
), and output of a function (with 1 input y
, and output of g(y,y)
). Meaning it is a function of functions. So when giving two_to_one
a two parameter function g
, you get back a function, that takes 1 number and outputs g(y,y)
.
e.g:
two_to_one(lambda x,y:x+y)(3)
6
We gave two_to_one
a function that gets two numbers and output their sum, lambda x,y:x+y
, and we got back a function that takes 1 number and output its sum with itself two_to_one(lambda x,y:x+y)
. So with an input of 3
it outputs 6
.
Second line is similiar:
one_to_two = lambda f: (lambda x, y: f(x) + f(y))
Take a function f
(of 1 parameter - due to f(x)
), and give back a function, that gets two parameters (numbers probably) x,y
and outputs f(x) + f(y)
.
Now, for the 13 output - working from inner to outer:
h = one_to_two(two_to_one(lambda x, y: x*y))
lambda x, y: x*y
two parameter input - output of multiplication. This is the input of two_to_one
so (remember what was written earlier) two_to_one(lambda x, y: x*y)
is a function that gets 1 number, and returns it squared. And finally, feeding this function to one_to_two
gives a function that gets two numbers (those x,y
frim before) and returns their sum of squares.
In total h(3,2)
gives 3**2+2**2=13
.