0

Consider the following code (details below):

def add(a):
    def f(x):
        return x+a
    return f

def times(a,b):
    return a*b

def adlist(A,B):
    add_a = map(add,A)
    add_b = map(add,B)

    return [ lambda x : times(f(x),g(x)) for (f,g) in zip(add_a,add_b)]

(f,g) = adlist([0,1],[0,1])

I would expect that f(x) = x*x and g(x) = (x+1)*(x+1) at this point but

print f(0) # 1
print g(0) # 1 

And in fact, f(x) = g(x) = (x+1)*(x+1).

Question: Why does this happen? How to fix it? (Given that I cannot modify the functions add and times.)


Details : Consider functions of the sort f(x) = (x+a)*(x+b). In python it is easy to write a function that takes a and b as input and returns the function f.

However, what I need is a bit more complicated, I need something that takes lists A = [a1,...] and B = [b1, ...] and returns a corresponding list of functions [f1, ...] where f1(x) = (x+a1)*(x+a2). And the actual functions are more complicated than just addition and multiplication. My attempt above doesn't seem to work.

Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186
Lambda Mu
  • 293
  • 1
  • 3
  • This is the classical lexical-scoping problem in python – shx2 Jul 25 '14 at 11:54
  • Ok thank you, it appears my question was answered in the duplicate question. I didn't know what to search for. So please close/delete. – Lambda Mu Jul 25 '14 at 11:58

0 Answers0