-
Notifications
You must be signed in to change notification settings - Fork 3
NEP6 Variable Argument List Functions
Sometimes it is useful to declare a function that can be called with an arbitrarily variable number of arguments. This proposal describes a syntax and mechanism for such functions.
Variable argument lists can be implemented such that the caller lists function arguments in the usual way, and the function being called receives them in an array. Fundamentally, it is exactly as if the caller constructed an array with the variable arguments, and passed that array to the function.
Each function can have at most one variable argument list, and that must be the last declared parameter of the function.
FUNCTION f(a: Number...): Number
VAR r: Number := 0
FOREACH x IN a DO
r := r + x
END FOREACH
RETURN r
END FUNCTION
ASSERT f(1, 2, 3) = 6
ASSERT f() = 0
LET values: Array<Number> := [1, 2, 3, 4]
ASSERT f(values...) = 10
The ...
in the function declaration indicates that the argument a
accepts a variable number of arguments as an array.
Inside the function, a
has type Array<Number>
and is accessed exactly as if it were an array.
The ...
in the function call allows a caller to pass an already-constructed array of parameters.
Given the above concept, the implementation is reasonably straightforward. The analyzer will construct the AST to build an array out of the variable argument list parameters, and pass that as the last argument to the function. The function implementation analyzer need only ensure that the variable argument list parameter is an array.