functional programming with map()

Michael Hudson mwh at python.net
Mon Feb 25 04:45:55 EST 2002


Paul Rubin <phr-n2002a at nightsong.com> writes:

> David Eppstein <eppstein at ics.uci.edu> writes:
> > > : But what is the functional equvalent of:
> > > 
> > > : for x in items:
> > > :     x.f()
> > > 
> > > 
> > > 
> > > Here's one way to do it:
> > > 
> > > ###
> > > map(lambda x: x.f(), items)
> > > ###
> > 
> > I'd prefer
> > [x.f() for x in items]
> > 
> > It's not functional syntax, but so what?
> 
> Both of those build up a new list of the results, instead of
> discarding the values.  If the f function takes an integer and
> computes a 20-megabyte structure, you've got a problem.  This really
> calls for a generator comprehension as discussed a few weeks back.
> 
>    reduce(lambda x,y:(y.f(),0)[1], items, 0)
> 
> almost works, but invokes f an extra time at the end.
> 
> Someone see how to fix it?

for x in items:
    x.f()

?

Cheers,
M.

-- 
  Premature optimization is the root of all evil.
       -- Donald E. Knuth, Structured Programming with goto Statements



More information about the Python-list mailing list