Variadic Functions in Modelica

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

function sum
  input Real nums[:] = {};
  output Real total;
algorithm 
  total := sum(nums);
end sum;

Within the function, the type of nums is equivalent to Real[:]. We can call size(nums, 1), iterate over it with a for loop, etc.

model VariadicFunctions
  Real total;
equation
  total = sum({1.0, 2.0});
  total = sum({1.0, 2.0, 3.0});
end VariadicFunctions;

If you already have multiple arguments in an array, apply them to a variadic function using the array directly.

model VariadicFunctions
  Real total;
  Real nums[4] = {1.0, 2.0, 3.0, 4.0};
equation
  total = sum(nums);
end VariadicFunctions;

To run the program, load it in a Modelica environment such as OpenModelica or Dymola and simulate the VariadicFunctions model. The output will display the sum of the numbers passed to the sum function.