Multiple Return Values in Chapel

Chapel supports multiple return values, which can be used to return both result and error values from a function.

use IO;

// The (int, int) in this function signature shows that
// the function returns 2 ints.
proc vals(): (int, int) {
    return (3, 7);
}

proc main() {
    // Here we use the 2 different return values from the
    // call with multiple assignment.
    var (a, b) = vals();
    writeln(a);
    writeln(b);

    // If you only want a subset of the returned values,
    // use an underscore '_' as a placeholder.
    var (_, c) = vals();
    writeln(c);
}

To run the program:

$ chpl multiple-return-values.chpl -o multiple-return-values
$ ./multiple-return-values
3
7
7

In Chapel, multiple return values are handled using tuples. The vals() function returns a tuple of two integers. When calling the function, we can use tuple destructuring to assign the returned values to individual variables.

The var (a, b) = vals(); line demonstrates how to capture both return values. If you only need one of the values, you can use an underscore _ as a placeholder for the value you don’t need, as shown in var (_, c) = vals();.

Chapel’s syntax for multiple return values is similar to other modern programming languages, making it easy to write clean and expressive code when dealing with functions that need to return multiple values.

Next, we’ll explore how Chapel handles functions with a variable number of arguments.