Possible Duplicate:
function making
>>> g=lambda x:x+1
>>> composition=lambda f,g:(lambda x:f(g(x)))
>>> f=g
>>> f=composition(f,g)
>>> f(9)
11
>>> f=composition(f,g)
>>> f=composition(f,g)
>>> f=composition(f,g)
>>> f(9)
14
Instead of using function composition(f,g) ,i did the following
>>> f=g
>>> f=lambda x:f(g(x))
>>> f(8)
RuntimeError: maximum recursion depth exceeded
I just aimed substituting function composition with corresponding lambda expression. I am confused about why f=composition(f,g) is not producing recursion but f=lambda x:f(g(x)) does.
For the first one:
When you call
composition(f, g), you are creating a closure around the contents of those variables. The lambda being returned is looking for the variable namesfandgin its local scope – they’ll both be references to theglambda created on the first line.For the second one:
In the second one, when
fis called, it looks forfin its “local” scope, which is actually the global scope – and finds itself, hence creating infinite recursion.The key here is that the lookup of
fhappens at execution, not when the lambda is defined.