Variadic Functions in Chapel

Here’s a function that will take an arbitrary number of int arguments.

proc sum(nums: int...) {
    writeln(nums, " ");
    var total = 0;
    
    for num in nums {
        total += num;
    }
    
    writeln(total);
}

proc main() {
    sum(1, 2);
    sum(1, 2, 3);
    
    var nums = [1, 2, 3, 4];
    sum(nums...);
}

In Chapel, you can define variadic functions using ... after the parameter type. The nums parameter here is essentially an array of integers. Within the function, you can work with nums as you would with any array, such as using for loops.

Variadic functions can be called in the usual way with individual arguments. Also, if you have multiple arguments in an array, you can apply them to a variadic function using func(array...).

To run the program, put the code in a file, for example, variadic-functions.chpl, and use chpl to compile and run it.

$ chpl variadic-functions.chpl -o variadic-functions
$ ./variadic-functions
[1, 2] 
3
[1, 2, 3] 
6
[1, 2, 3, 4] 
10

Another key aspect of functions in Chapel is their ability to support first-class functions, which we’ll look at next.