Arrays in Chapel

In Chapel, an array is a collection of elements of a specific type. Arrays in Chapel are more flexible than in some other languages, as they can be resizable and distributed across multiple locales.

use IO;

proc main() {
    // Here we create an array 'a' that will hold exactly 5 integers.
    // By default, an array is initialized with the default value of its type,
    // which for integers is 0.
    var a: [1..5] int;
    writeln("emp: ", a);

    // We can set a value at an index using the array[index] = value syntax,
    // and get a value with array[index].
    a[5] = 100;
    writeln("set: ", a);
    writeln("get: ", a[5]);

    // The '.size' property returns the length of an array.
    writeln("len: ", a.size);

    // Use this syntax to declare and initialize an array in one line.
    var b = [1, 2, 3, 4, 5];
    writeln("dcl: ", b);

    // Chapel allows you to create arrays with arbitrary index ranges
    var c: [0..4] int = [1, 2, 3, 4, 5];
    writeln("range: ", c);

    // You can also create sparse arrays where only certain indices are populated
    var d: [1..5] int;
    d[1] = 100;
    d[4] = 400;
    d[5] = 500;
    writeln("sparse: ", d);

    // Chapel supports multidimensional arrays
    var twoD: [1..2, 1..3] int;
    for i in 1..2 {
        for j in 1..3 {
            twoD[i,j] = i + j - 1;
        }
    }
    writeln("2d: ", twoD);

    // You can create and initialize multi-dimensional arrays at once too.
    var twoD2 = [
        [1, 2, 3],
        [1, 2, 3]
    ];
    writeln("2d: ", twoD2);
}

When you run this program, you’ll see output similar to the following:

emp: 0 0 0 0 0
set: 0 0 0 0 100
get: 100
len: 5
dcl: 1 2 3 4 5
range: 1 2 3 4 5
sparse: 100 0 0 400 500
2d: 1 2 3
   2 3 4
2d: 1 2 3
   1 2 3

Note that arrays in Chapel are printed in a format similar to other languages when using the writeln function.

Chapel’s arrays are more flexible than those in some other languages. They can have arbitrary index ranges, be resizable, and even be distributed across multiple locales in parallel computing environments. This example demonstrates some basic array operations, but Chapel’s capabilities with arrays extend far beyond these basics, especially in the realm of parallel and distributed computing.