On Tuesday, 13 February 2024 at 00:59:36 UTC, Richard (Rikki) Andrew Cattermole wrote:
> On 13/02/2024 6:52 AM, H. S. Teoh wrote:
> One example of the usefulness of a loop construct that supports the above construct in full generality is the outputing of list delimiters. If we postulate a syntax construct like:
|loop { loopBodyBeforeCondition(); } while(cond) { loopBodyAfterCondition(); } |
then, given some range r of items, we can output it with delimiters like this:
|loop { writef("%s", r.front); r.popFront; } while(!r.empty) { write(", "); } |
Oh I quite like this.
Me, too. I love this:
do
{
…
}
while (cond)
{
…
}
It’s a lot more structured than:
for (;;)
{
…
if (!cond) break;
…
}
The only issue I see is it would probably be useful to have the variables declared in the top part be in scope in the lower part, however that is counterintuitive because of separated blocks. The less structured construct solves this.
In my 4-statement for
loop, it’s not surprising that a variable declared in the prepare step is present in the loop body.
Alternatively, one can double-down on D’s for loop weirdness and allow this:
for ({int i = 1; int n = 10;} i < n; ++i) { } // already possible
for (int i = 0; {int n = 10 - i; i < n;} ++i) { } // new!
Thinking about it, I actually like that more. The small semicolon could really easily be missed, while the braces are striking.
I know I’ve seen this in some diagrams at university. Probably some form of Nassi–Shneiderman diagram. The University of Darmstadt has one here: https://www.iim.maschinenbau.tu-darmstadt.de/kursunterlagen_archiv/pst_ws1314/04-Methoden-3/Theorie/nassishneidermann.html (German) Image only:https://www.iim.maschinenbau.tu-darmstadt.de/kursunterlagen_archiv/pst_ws1314/04-Methoden-3/Theorie/endlosschleife.png
On the other hand, this is rather obscure and I don’t intuit how it’ll work:
foreach(x; xs)
{
…
}
while
{
…
}
This is my attempt to express it in terms of a while
loop and range primitives:
for (;;)
{
…
if (!xs.empty) break;
auto x = xs.front;
…
xs.popFront;
}
It’s weird to do stuff before you check a range for empty. It’s fine explicitly, but it would be weird to have x
not be there in the first block after foreach
.
Correct me if I got the lowering wrong.