Variadic Function
A variadic function is a special function that can accecpt an arbitrary number of arguments. To write such a function, we need help from function overloading and compile-time annotation.
Example: We're going to create a function called simple_prinln that accepts a number of variables and print each one followed by a \n.
@compile-time
void simple_println(type... args[]){
for(int8 i = 0; i < len(args), i++){
print("{}\n", args[i]);
}
}
Similar to generic function, this compile-time simple_prinln is like a blueprint used to dynamically, at compile time, create concrete versions of function overloadings.
This syntax type... args[] only works with compile-time function, and it tells the compiler, when simple_println is called, to put all the arguments into an array-like named args, so you can process the arguments with the following properties:
len(args)return the number of arguments passed in the functionargs[i]return the argument at index itype(args[i])return the type of the argument at index i
Next we're going to call this function and see what happens!
@compile-time
void simple_println(type... args[]){
for(int8 i = 0; i < len(args), i++){
print("{}\n", args[i]);
}
}
int main(string args[]){
simple_println("hello, world");
simple_println("hello", 12, 3.14);
return 0;
}
Since we call it twice with different arguments, the compiler will create two overloading versions of simple_println:
simple_println(string)simple_println(string, int, float)
And the compiler will process the function and generate that two concrete versions of simple_println and below is the code to illustrate this:
void simple_println(string arg0){
print("{}\n", arg0);
}
void simple_println(string arg0, int8 arg1, float16 arg2){
print("{}\n", arg0);
print("{}\n", arg1);
print("{}\n", arg2);
}
int main(string args[]){
simple_println("hello, world");
simple_println("hello", 12, 3.14);
return 0;
}
Example 2: In the 2nd example, we're going to explore more about this feature by