[Edu-sig] Re: [Tutor] Thoughts on little lambda

Burley, Brent Burley, Brent" <Brent.Burley@disney.com
Tue, 12 Mar 2002 11:42:26 -0800


Kirby wrote:
> Just to review the construct, I was suggesting a way to
> make "function factories" (functions that build other
> functions) which have internal complexity beyond lambda's
> ability by itself, is to use an internal function called
> with lambda.
> 
> E.g. the example below includes a print statement --
> something lambda can't, by itself, invoke:
> 
>   >>> def makeadder(n):
>           def main(x):
>              print "Adding %s" % n
>              return x + n
>           return main

In "functional language" language, binding a function with a partial
argument list is called "currying".  Here's a nice description:
http://foldoc.doc.ic.ac.uk/foldoc/foldoc.cgi?curried+function

Here's the same thing, but in an explicitly curried form:

def adder(x, n):
   print "Adding %s" % n
   return x + n

def makeadder(n):
   return lambda x: adder(x, n)

The main difference is that it wraps the adder function rather than
redefining it each time.

There's also a recipe for a general currying class here:
http://aspn.ActiveState.com/ASPN/Cookbook/Python/Recipe/52549
You use it directly like this:
   add2 = curry(adder, 2)

The curry class supports currying of arbitrary arguments (including
keyword args!) and has the added benefit that it doesn't require nested
scopes and thus works on older versions of python.

	Brent