Feature Creation

Hi, I am new to functional programming. What i did is

>>> g=lambda x:x*2 >>> f=g >>> g=lambda x:f(f(x)) >>> g(9) 36 

Now he does not create g as an irregular recursive function - g(x) converted to a new function that gives the result g(g(x)) .

 >>> f=g >>> g=lambda x:f(f(x)) >>> f(8) RuntimeError: maximum recursion depth exceeded 

I expected g convert to a function that gives the result g(g(g(x))) , according to the first definition of g (x). Why is this not so? Is it possible to create a new function that leads to g(g(g(...(g(x))....))) for a certain number of iterations in this way?

+4
source share
3 answers

When you execute f = g a second time, f becomes lambda x: f(x) . Closures are created by name, not by value.


This is facilitated by an auxiliary function:

 def compose(f, g): return lambda x: f(g(x)) square = lambda x:x*2 g = square for i in xrange(4): g = compose(g, square) 
+6
source

In python, variables are names mapped to values, not the values ​​themselves (everything is a reference). In addition, you can think of lambda as storing text that can be appreciated. Below is illustrated

 a = 2 f = lambda x: a*x f(2) # This gives 4 a = 3 f(2) # This gives 6 

This should clarify why you are getting infinite recursion.

In answer to your question about recursion, here is a small hack that could do

 g = lambda x, n: n > 0 and g(x, n-1)**2 or x 

Then g(2,3) will be (((2)^2)^2)^2 = 256 .

+4
source

it

 g=lambda x:x*2 f=g g=lambda x:f(x) 

is equivalent to:

 f=lambda x:x*2 g=lambda x:f(x) 

When you call g , you get the value of f , which must be defined in the global (or encompassing) area.

what you expect is something like:

 f=lambda x:x*2 g=lambda x, f=f:f(x) 

This captures the value of f in the outer region at the time the lambda expression is evaluated.

+2
source

Source: https://habr.com/ru/post/1434254/


All Articles