Is this a good use for lambda

Nick Coghlan ncoghlan at iinet.net.au
Tue Dec 21 06:36:19 EST 2004


Steven Bethard wrote:
> Nick Coghlan wrote:
> 
>> def compose(list_of_functions):
>>   application_order = reversed(list_of_functions)
>>   def composed(x):
>>     for f in application_order:
>>       x = f(x)
>>     return x
>>   return composed

> so you either need to call reversed each time in 'composed' or copy the 
> list and call reverse.

These iterator thingies sure are handy most of the time, but occasionally. . . I 
suspect the iterator (e.g. reversed()) vs list (e.g. sorted()) distinction is 
going to end up on a few of those 'Python Gotchas' pages.

Ah well, at least I caught the 'return x' that was missing from my first draft 
version  :)

Corrected version:

def compose(functions):
   application_order = list(functions)
   application_order.reverse()
   def composed(x)
     for f in application_order:
       x = f(x)
     return x
   return composed

Cheers,
Nick.

P.S. For the curious:

C:\>python -m timeit -s "x = range(10000)" "y = x[:]; y.reverse()"
10000 loops, best of 3: 102 usec per loop

C:\>python -m timeit -s "x = range(10000)" "y = list(x); y.reverse()"
10000 loops, best of 3: 100 usec per loop

C:\>python -m timeit -s "x = range(10000)" "y = list(reversed(x))"
10000 loops, best of 3: 166 usec per loop

-- 
Nick Coghlan   |   ncoghlan at email.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://boredomandlaziness.skystorm.net



More information about the Python-list mailing list