Ministry of silly loops

Stay a while and listen:

var i: u32 = 0;
while (i < 10) {
    defer i += 1;
    print("{d}\n", .{i})
}

Tricked you, this one is a serious loop, not a silly loop!

I think while (condition) : (increment) loops are redundant and should be removed from the language.

while (condition) : (increment) {
    body;
}

is, as far as I can tell at 3AM, fully equivalent to

while (condition) {
    defer increment;

    body;
}

But the latter is so much more readable! You don’t need to guess semantics of ) : ( and how it interacts with continue and what not. And you know why is that hard to intuit? Because it’s the single violation of “no control flow without keyword” principle! : is control flow, and a particularly tricky one! Execution goes from the condition, past the increment, to the loop body, and then back to the increment again.

while (condition) : (increment) loops are a bit more concise than while-defer loops, and that was important when a counting for loop was written as a while. But, since we have explicit counting for(0..10) loops, I’d say, down with the while with increment! Даёшь while defer!

13 Likes

one difference is whether break runs the increment expression. it could be important if doing iterator.next() one more time would crash or have other side effects

–

In my opinion the true sillyness of this loops is that it's not just a for(0..10) |i: u32|

–

I'd never even thought of using defer increment, gonna steal that for myself. I have seen but never used while (condition) : (increment) loops because I agree, they feel a bit redundant and weirdly out of place in the language.

–

another difference: you can't break or try inside a defer expression. but I generally agree, I use defer i += 1 whenever possible. it's particularly nice when writing the internals of an iterator (because of the difference andrew described!) to make sure that iterator state is always advanced

–

what about adding a new keyword 'continuedefer' (or maybe 'loopdefer', ...) that defers a statement in a loop IFF the loop continues (explicitly with 'continue' or implicitly by reaching end of loop body). I think this would solve the issue above and would allow to replacing the while () : ([continue expression]) syntax with a keyboard based explicit controlflow. Also this concept of a conditional defer already existst in the language: 'errdefer'.

–