From: Charles Comstock Date: 2004-04-05T23:34:21+09:00 Subject: Re: deciding between ruby and python David A. Black wrote: > Hi -- > > On Mon, 5 Apr 2004, Charles Comstock wrote: > > >>>Perhaps some of us like to do our iteration explicitly. I don't think >>>there is any syntactic overhead, and the for loop reads >>>better. Counterexamples welcome. >>> >>>Obviously we can do #each too: >>> >>>def L(x): >>> print x >>> return x*2 >>> >>>map(L, [1,2,3]) >>> >> >>(reverse (map (lambda (x) (begin (display x) (* x 2))) >> (map (lambda (x) (+ x 2)) (list 1 2 3)))) >> >>[1,2,3].each {|x| x+2}.each {|x| print x;return x*2}.reverse > > > I think you want #map there. With each, the first block is > essentially a no-op. Also, return will break through all levels > (including method call): Whoops, just goes to show what happens when I forget to test the code before posting. I'd forgotten that caveat about each, the commentary on map remains true, I find it much easier to read in this order then the above functional style. [1,2,3].map {|x| x+2}.map {|x| print x;x*2}.reverse [...] > > for doesn't generate a result list though. What you've got here will > return [3,2,1], and all the x+2 calculations will be discarded (like > #each). > > > David > Hmm I had misunderstood that about each, I encountered it once, but promptly forgot about it. Do we do this to increase efficiency? Otherwise I can't see a situation where you wouldn't want to return the results of each for iteration. Charles Comstock