Variadic Functions in Pascal

Here’s the translation of the provided code example suitable for the Pascal language:

Variadic Functions

Variadic functions can be called with any number of trailing arguments. For example, WriteLn is a common variadic function in Pascal.

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

program VariadicFunctions;

uses
  SysUtils;

procedure Sum(const nums: array of Integer);
var
  total, i: Integer;
begin
  for i := Low(nums) to High(nums) do
  begin
    total := total + nums[i];
  end;
  WriteLn(total);
end;

begin
  Sum([1, 2]);
  Sum([1, 2, 3]);

  var
    nums: array of Integer;
  begin
    nums := [1, 2, 3, 4];
    Sum(nums);
  end;
end.

Within the function, the type of nums is equivalent to an array of Integer. We can call Length(nums), iterate over it with a for loop, etc.

Variadic functions can be called in the usual way with individual arguments.

Sum([1, 2]);
Sum([1, 2, 3]);

If you already have multiple args in an array, apply them to a variadic function using array like this.

var
  nums: array of Integer;
begin
  nums := [1, 2, 3, 4];
  Sum(nums);
end.

Output

$ fpc VariadicFunctions.pas
$ ./VariadicFunctions
3
6
10

Another key aspect of functions is their ability to form closures, which we’ll look at next.

Next example: Closures.