Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function making

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, it is not creating g as a nonterminating recursive function - g(x) is transformed to a new function which gives the result g(g(x)).

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

I expected g to be transformed into a function which gives the result g(g(g(x))), according to the first definition of g(x). Why does it not? Is it possible to make a new function which results in g(g(g(...(g(x))....))) for a certain number of iterations in this way?

like image 574
dileep nandanam Avatar asked Dec 15 '22 19:12

dileep nandanam


2 Answers

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


This becomes easy with a helper 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)
like image 154
Eric Avatar answered Jan 06 '23 19:01

Eric


In python, variables are names mapped to values, not values themselves (everything is a reference). Also, you can think of lambda as storing text that can be evaluated. The following will illustrate

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

This should clear up why you are getting infinite recursion.

In answer to your question about recursing, here is a little hack that might do

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

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

like image 29
nevsan Avatar answered Jan 06 '23 21:01

nevsan