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

Re: Accumulator

Guy Steele - Sun Microsystems Labs wrote:
> Pattern 2c:
> (setq x (loop for i from 2 to 20 sum i))

I like that one. I don't quite understand how it works but it is pretty
succinct and readable. But then if you've got a sum primitive why don't
you just feed it the list of numbers from 2 to 20?


> I conjecture that if Python allowed you to write
> >>> x = reduce(+, range(2,20))
> then this idiom would be somewhat more attractive.

Python has an equivalent.

>>> from operator import add
<built-in function add>
>>> x = reduce(add, range(2,20))

Arguably it is the extra import statement that is turning people off. If
so, I'm happy to see the use of reduce discouraged.

There are only a few binary infix operators (compared to the number of
things in the universe that are already functions). So you can't get by
without the for-loop (or recursion or similar alternatives).

Also, it is quite common in Python to make a function which accepts a
list or n-ary parameters to start with, so the user doesn't have to do
the loop. Come to think of it, operator.add COULD be implemented that
way but isn't. It is strictly boolean.

 Paul Prescod