[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Accumulator

Guy Steele - Sun Microsystems Labs wrote:
> This is interesting data, and an interesting follow-up
> questions would be:  Are there any places in that 50,000
> lines of code where reduce *could* have been used but some
> other programming idiom was used instead?  

A little hard to check with a grep but it sort of stands to reason. I
would never think to use reduce in my code.

> ... And, if so, what
> are the reasons that other idioms were used instead of reduce?

You learn the for-loop in programming 101. You can't, in general, avoid
using it in Python for very long. You can get away without using reduce.
IMHO, you can increase code consistency (and thus readability) by using
for-loops instead of reduce.

Pattern 1:

>>> x = reduce(lambda y,z:y+z, range(2,20))

Pattern 2:

>>> x=0
>>> for i in range(2,20): x+=i

Three statements rather than one, but two variables rather than three,
and 0 functions. And dumping a lambda is almost always a good idea.

> I ask this question because I have seen a fair amount of
> Lisp code where REDUCE could have been used but the programmer,
> more comfortable with another idiom, chose to use LOOP or to
> write his own recursive or iterative procedure.

That is also an interesting data point. Is it your sense that these are
people still thinking in another language or are they experienced

map and filter were more popular, but hopefully will disappear now that
we have list comprehensions.

One central difference between the Python style (and this goes for most
OO languages) and the Lisp style is that Python programmers are
discouraged from building up large anonymous expressions. Reduce would
be really useful if I had a reason to want large anonymous expressions.
Instead, Python programmers collect values a little bit at a time in

 Paul Prescod