lambda

Alexis Roda arv.nntp at gmail.com
Fri Apr 21 15:41:34 EDT 2006


rubbishemail at web.de escribió:
> Hello,
> 
> # the idea is now to give the definition of the multiplication of
> functions and integers
> # (f * c)(xx) := f(x)*c
> [lambda xx: f(xx)*y for y in range(1,5)][0](1)
> # returns 4

here lambda uses a variable defined outside of the lambda (y). Any 
change made to y will be visible within the lambda. In your example the 
last value for y is 4, so:

[...][0](1) = f(1) * 4 = 4

> # I would expect 1*x*x = 1

you should use a local variable to "protect" y:

[ lambda xx, y=y : f(xx) * y for y in range(1, 5) ]

> # Where is my mistake and what would be the correct way to do this
> without lambdas?

You can emulate callables http://docs.python.org/ref/callable-types.html

class Callable:
   def __init__(self, f, y) :
     self.y = y
     self.f = f
   def __call__(self, x) :
     return self.f(x) * self.y

f = lambda x : x * x

[ Callable(f, y) for y in range(1, 5) ]

if you *absolutely* don't want lambdas you can hard code the x*x in 
__call__ and get rid of self._f, or you can define:

class Monomial:
   def __init__(self, exp, coef) :
     self.exp = exp
     self.coef = coef
   def __call__(self, x) :
     return x ** self.exp * self.coef

[ Monomial(2, y) for y in range(1, 5) ]

Another way, somewhat convoluted, using closures:

def make_list() :
   def make_function(y) :
     def function(x) :
       return x * x * y
     return function
   return [ make_function(y) for i in range(1, 5) ]

is essentially the same as lambda. Mostly didactic.



HTH



More information about the Python-list mailing list