One way to look at foreach as not so bad
Bill Baxter
dnewsgroup at billbaxter.com
Thu Oct 19 18:48:43 PDT 2006
One of the things I've said recently I find distasteful about foreach
(not even foreach_reverse, just plain foreach) is that in the statement
foreach(i; &obj.foreach){} 'foreach' doesn't really 'foreach' anything.
The method obj.foreach is the one that really contains the "for each"
loop, and obj.foreach is the one that really decides if it will even be
"for each item" or only "for some items".
In short 'foreach' only means 'foreach' if you use it in a particular way.
It occurred to me, though, that a similar argument applies to good old
'for'.
for(i=0; i<3; i++) {}
C's 'for' is really totally cryptic if you think about it. And can do
just about anything you want it to, including things having nothing to
do with 'for'-ing.
for(do_laundry(); wash_car() ; clean_room()) {
take_out_the_trash();
}
That's legal, but whatever it's doing sure is not 'for'-ing anything.
I kind of stopped seeing that years ago though. Thinking back, however,
I can remember the very early days staring at the first few 'for'
statements I ever saw in K&R, trying to figure out what the heck all
those semicolons were doing, and why good old "for i=1 to 10" wasn't
good enough, and later flipping back and forth in K&R to figure out
for-loop code later in the book.
foreach is pretty similar. It may have many uses that have nothing to
do with 'foreach'-ing, and the meaning of the semicolon is meaningless
and unclear at first, but I'll probably get used to it.
That doesn't mean it's an optimal design, though. ;-P
Nor does it mean that I wouldn't like trailing delegates to work also:
obj.each() (int i) {
writefln(i);
}
Maybe I can get used to this version that works now:
obj.each( (int i) {
wrietfln(i);
})
But it just looks weird to have my loop body inside the parens, and will
look even weirder if nested
obj.each( (Obj c) {
c.each( (int i) {
writefln(i);
})
})
It sort of looks like nested loops, but I just can't get excited about
all those })'s screaming out "I'm a not a loop! I'm a function call!".
All that's just about plain 'foreach'. I still can't see a good
justification for foreach_reverse. Reverse iteration just isn't common
enough to justify a special case like that.
--bb
More information about the Digitalmars-d-announce
mailing list