Loops
This post is focused on basic loop syntax. There is some features that I would like to add in the future that are not considered here.
For (each) loop
array : []int = {1, 2, 3, 4, 5}
for i : in array {
// i ...
}
or more idiomatic:
for each : in array {
// each ...
}
: )
For loop with ranges
Note how
each
is not a keyword, but an identifier. Also, there is a parallelism between thein
keyword and the assignment operator (=
).
// Full verbosity.
for each : i32 in 0 <= .. < 256 {
// each ...
}
// With type inference.
for each : in 0 <= .. < 256 {
// each ...
}
// Playing with the inclusion of the ends.
for each : in -1 < .. <= 255 {
// each ...
}
// Reversed range.
for each : in 256 > .. => 0 {
// each ...
}
For loop with implicit iterator
array : []int = {1, 2, 3, 4, 5}
for in array {
// ...
}
(I hate this form, I may remove it later).
While loop
a = 0
while a < 256 {
a += 1
}
Repeat-while loop
a = 0
repeat while a < 256 {
a += 1
}
Pros:
- This loop can be quickly turned into a
while
loop and vice versa. - The condition works consistently with
if
,for
andwhile
(like in C). - The braces could be removed in the future easier than in other versions.
- Only one additional keyword (like in C).
- It can be less confusing and prevent errors related with copy-and-paste and dangling empty
while
s (like Pascal achieves).
Cons:
- It also can be more confusing, because the condition is before the block (‘Repeat? Oh, yes, now I remember…’).
- Slightly more verbose (I considered
repeat if
, but semantically it would be more trouble than it is worth).