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

Re: Accumulator

At 04:43 PM 5/23/2002, Paul Prescod wrote:
>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.

There may be several reasons for this.  Here's some suspects:
1.  Why are we picking on reduce?  There are lots of constructs that aren't 
used often.
2.  Reduce makes sense if you're operating on a list of unknown length.
3.  If you know the length, or are interested in performance in a language 
that doesn't optimize reduce, you might pick something else.
4.  I agree the Common Lisp has lots of other loop idioms.

>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

Although, you had a nice example that saved a variable.
Java programmers do that to, why?  Is it because they learn that idiom form 
the language, or reading other peoples code?

I find it particularly annoying to use a variable in Java, because i have 
to declare the type on both sides of the =.  In Python, it must be more