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

Re: Accumulator

   Date: Thu, 23 May 2002 13:43:28 -0700
   From: Paul Prescod <paul@prescod.net>
   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.

Whereas you can write entire applications in Lisp and never
use a for-loop (or its analogues) even once.
   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.

Whereas in Lisp "+" is already a function, rather than a
special-case piece of infix syntax as it is in Python,
so the analogous code in Lisp would not need a lambda
(I use Common Lisp syntax for these examples; Scheme
would not need the "#'" marker):

Pattern 1:
(setq x (reduce #'+ (range 2 20)))

This compares favorably with the use of iteration constructs:

Pattern 2a:
(let ((x 0))
  (dotimes (i 19) (setq x (+ i 2)))
Pattern 2b:
(do ((i 2 (+ i 1))
     (x 0 (+ x i)))
    ((> i 20)

Pattern 2c:
(setq x (loop for i from 2 to 20 sum i))

I conjecture that if Python allowed you to write

>>> x = reduce(+, range(2,20))

then this idiom would be somewhat more attractive.

--Guy Steele