# reduce()--what is it good for? (was: Re: reduce() anomaly?)

Bob Gailer bgailer at alum.rpi.edu
Fri Nov 7 03:08:50 CET 2003

```At 03:41 PM 11/5/2003, Francis Avila wrote:

>"Alex Martelli" <aleax at aleax.it> wrote in message
>news:3fbqb.97878\$e5.3584611 at news1.tin.it...
> > Stephen C. Waterbury wrote:
> > If you want to abuse reduce at all costs for this purpose,
> > reduce(lambda x, y: x.update(y) or x, l) might work.
>
>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.

One's prior programming experience can affect one's view of reduce. My
favorite language, prior to Python, was APL. APL's native data container is
the array, and reduce is a native operator in APL. So we used reduce a lot,
sometimes to add things up, other times to check for all or any conditions,
other times for other at this moment forgotten purposes. A companion of
reduce in APL is scan, which did reduce but preserved all the intermediate
values (cumulative sum for example).

To expand your reduce horizons in Python, consider reduce as a way to
examine the relationship between successive pairs of a sequence. For
example one might wants the difference between successive elements: given
seq = [1,3,4,7] we'd like a differences == [2,1,3].

differences = []
def neighborDifference(left, right):
differences.append(right - left)
return right
reduce(neighborDifference, seq)

Bob Gailer
bgailer at alum.rpi.edu
303 442 2625
-------------- next part --------------

---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.532 / Virus Database: 326 - Release Date: 10/27/2003
```