For in Chapel

Chapel provides several ways to create loops. Here are some basic types of loops.

use IO;

proc main() {
    // The most basic type, with a single condition.
    var i = 1;
    while i <= 3 {
        writeln(i);
        i += 1;
    }

    // A classic initial/condition/after loop.
    for j in 0..#3 {
        writeln(j);
    }

    // Another way of accomplishing the basic "do this
    // N times" iteration is to use a range.
    for i in 0..#3 {
        writeln("range ", i);
    }

    // A loop without a condition will run indefinitely
    // until you break out of the loop or return from
    // the enclosing function.
    while true {
        writeln("loop");
        break;
    }

    // You can also continue to the next iteration of
    // the loop.
    for n in 0..#6 {
        if n % 2 == 0 {
            continue;
        }
        writeln(n);
    }
}

When you run this program, you’ll see:

$ ./for
1
2
3
0
1
2
range 0
range 1
range 2
loop
1
3
5

In Chapel, the for loop is more versatile than in many other languages. It can iterate over ranges, arrays, and other iterable objects. The while loop is used for condition-based looping.

The ..# syntax in Chapel creates a range from 0 to n-1, which is similar to the range-based for loops in the original example.

Chapel doesn’t have a direct equivalent to Go’s for range over an integer, but using a range with ..# achieves the same result.

We’ll see other forms of loops later when we look at iterating over arrays, domains, and other data structures.