[Tutor] fancy list things

Lloyd Kvam pythontutor at venix.com
Fri Feb 6 08:17:46 EST 2004


Marilyn Davis wrote:
> On Fri, 6 Feb 2004, Karl Pflästerer wrote:
> (SNIPPED)
> 
> Is it only useful in map() and filter() and reduce()?  And other
> places where you want to hand a little function to a function?  comp()
> for example.  Is there another class of examples?
> 
> I'm teaching python for the first time and want to be as solid as
> possible on this stuff.

You probably do NOT want to inflict this on your class, But David Mertz made
heavy use of lambda's in building a set of functions for combining functions:
(from "Text Processing in Python")

       #------------------- combinatorial.py -------------------#
       from operator import mul, add, truth
       apply_each = lambda fns, args=[]: map(apply, fns, [args]*len(fns))
       bools = lambda lst: map(truth, lst)
       bool_each = lambda fns, args=[]: bools(apply_each(fns, args))
       conjoin = lambda fns, args=[]: reduce(mul, bool_each(fns, args))
       all = lambda fns: lambda arg, fns=fns: conjoin(fns, (arg,))
       both = lambda f,g: all((f,g))
       all3 = lambda f,g,h: all((f,g,h))
       and_ = lambda f,g: lambda x, f=f, g=g: f(x) and g(x)
       disjoin = lambda fns, args=[]: reduce(add, bool_each(fns, args))
       some = lambda fns: lambda arg, fns=fns: disjoin(fns, (arg,))
       either = lambda f,g: some((f,g))
       anyof3 = lambda f,g,h: some((f,g,h))
       compose = lambda f,g: lambda x, f=f, g=g: f(g(x))
       compose3 = lambda f,g,h: lambda x, f=f, g=g, h=h: f(g(h(x)))
       ident = lambda x: x

It was done for the same reason lambda is used with map, etc.,  creating named
versions of the expressions is more confusing than simply showing the expression.

the first function could have been written:

def apply_each( fns, args=[]):
     return map(apply, fns, [args]*len(fns))

Written either way, you will probably need to expend some thought before you really
understand how to use a function like this.  The book does include explanations and
examples.

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582




More information about the Tutor mailing list