I'm trying to learn pure functional programming. But this code is puzzling me particularly the second line. I do not understand how the value 2
is passed to the variable x
. Can somebody explain this nested lambda
behaviour?
>>> square_func = lambda x: x**2
>>> function_product = lambda F, m: lambda x: F(x)*m
>>> square_func(2)
4
>>> function_product(square_func, 3)(2)
12
The inner lambda creates a function when the outer lambda is called. The outer lambda returns this function. This function is then called with the argument 2
.
A good place to start would be to apply type
to your definitions and see if it clarifies things. Also, I can't help but remark that something like Haskell would be a nicer place to start if you are interested in functional programming, even if you do not plan on using the language. That being said, here is what you get:
In [13]: type(square_func)
Out[13]: function
In [14]: type(function_product)
Out[14]: function
In [15]: type(square_func(2))
Out[15]: int
In [16]: type(function_product(square_func, 3))
Out[16]: function
In [17]: type(function_product(square_func, 3)(2))
Out[17]: int
So the puzzling part is the return type of function_product(square_func, 3)
, which is a function itself, one that is presumably intended to take a single number and return a single number. You could write it as:
f = function_product(square_func, 3)
f(2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With