Functions in Chapel

Functions are central in Chapel. We’ll learn about functions with a few different examples.

use IO;

// Here's a function that takes two integers and returns
// their sum as an integer.
proc plus(a: int, b: int): int {
    // Chapel doesn't require explicit returns, but we'll
    // include it for clarity.
    return a + b;
}

// In Chapel, we can define default values for parameters,
// which is a bit different from Go's approach of omitting types.
proc plusPlus(a: int, b: int, c: int): int {
    return a + b + c;
}

// The main procedure in Chapel
proc main() {
    // Call a function just as you'd expect, with
    // name(args).
    var res = plus(1, 2);
    writeln("1+2 = ", res);

    res = plusPlus(1, 2, 3);
    writeln("1+2+3 = ", res);
}

To run the program, save it as functions.chpl and use the Chapel compiler:

$ chpl functions.chpl -o functions
$ ./functions
1+2 = 3
1+2+3 = 6

In Chapel, functions are called procedures and are defined using the proc keyword. The syntax is slightly different from other languages, but the concept is similar. Chapel uses type inference, but we’ve explicitly declared types here for clarity.

Chapel doesn’t have a built-in fmt module like in the original example, so we use the IO module and its writeln function for output.

There are several other features to Chapel functions. One is multiple return values, which we’ll look at next.