reduce()--what is it good for?

anton muhin antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru
Thu Nov 6 17:26:01 CET 2003


> Just out of curiosity, for what kind of problems do we find reduce to just
> be the Right Way?  I mean, summing a big list of numbers is fun and all, but
> I never find any use for it otherwise.  I *often* try to think if reduce
> would be useful when I come across some collection-of-values manipulation
> task, but usually one wants to repeat an operation on a whole set of values,
> not reduce the set to one value.
> 
> So, are there any *non-trivial* and *unabusive* uses of reduce, where any
> other way would be tedious, repetitive, slow, unclear, etc.?  I'm very
> curious to see them.
> 
> reduce--the black sheep of the functional-Python herd?
> --

IMHO, not. Once I read an article that explains that foldr and 
foldl---almost Python's reduce---are most important HOFs. Actually, 
functions like map can be easily defined with reduce:

def my_map(func, seq):
     return reduce(lambda seq, el: seq + [func(el)], seq, [])

print my_map(lambda x: 2*x, [1, 2, 3, 4, 5])

regards,
anton.





More information about the Python-list mailing list