Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding nested lambda function behaviour in python

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
like image 830
kmario23 Avatar asked Apr 03 '16 22:04

kmario23


2 Answers

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.

like image 127
Ignacio Vazquez-Abrams Avatar answered Sep 21 '22 07:09

Ignacio Vazquez-Abrams


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)
like image 35
hilberts_drinking_problem Avatar answered Sep 23 '22 07:09

hilberts_drinking_problem