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.