dileep nandanam
dileep nandanam

Reputation: 2895

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?

Upvotes: 4

Views: 192

Answers (3)

Eric
Eric

Reputation: 97571

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)

Upvotes: 6

nevsan
nevsan

Reputation: 1445

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.

Upvotes: 4

Marcin
Marcin

Reputation: 49826

This

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 whatever f happens to be defined in the global (or enclosing) scope.

what you're expecting is something like:

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

That captures the value of f in the outer scope at the time the lambda expression is evaluated.

Upvotes: 2

Related Questions