foreach
H. S. Teoh via Digitalmars-d
digitalmars-d at puremagic.com
Fri Jun 13 15:41:04 PDT 2014
On Fri, Jun 13, 2014 at 10:15:59PM +0000, monarch_dodra via Digitalmars-d wrote:
> On Friday, 13 June 2014 at 22:07:53 UTC, H. S. Teoh via Digitalmars-d wrote:
> >>The very idea of a loop without a condition seems very, very wrong
> >>to me.
> >
> >Why would it be "very, very wrong"? Perpetual cycles are ubiquitous
> >in nature
>
> Hum... you guys seem to be forgetting about break statements.
>
> You know when you want to do something, and also do something
> *between* each iteration, but don't want to check your end condition
> twice per loop? It usually ends up looking something like this:
>
> T[] arr = ... ;
> auto len = arr.length;
> write("[");
> if ( len != 0 ) {
> size_t i = 0
> for ( ; ; ) {
> write(arr[i]);
> if (++i == len) break;
> write(", ");
> }
> }
> write("]");
I'm of the opinion that today's ubiquitous for/while/do loops are all
defective caricatures of the "true" looping construct:
loop {
// body1
} while (condition) {
// body2
}
where body1 runs first, then the condition is checked, then body2 runs
followed immediately by body1 again, etc.. Either body1 or body2 can be
elided as needed, of course:
// do-loop
loop {
// body1
} while(condition);
// while-loop
loop while(condition) {
// body2
}
// the real infinite loop ;-)
loop {
// body1
}
// busy wait loop
loop while (!externallySetFlag);
And here's an example the full loop in action:
write("[");
if (!range.empty) {
loop {
writef("%s", range.front);
range.popFront();
} while (!range.empty) {
writef(", ");
}
}
writeln("]");
The fact that this is the One True Loop is backed up by the necessity of
%| in order to complete the functionality of %( and %) in std.format. %(
and %) wouldn't be halfway as cool as they are, if %| didn't exist.
T
--
Questions are the beginning of intelligence, but the fear of God is the beginning of wisdom.
More information about the Digitalmars-d
mailing list