Closures in Pascal

Pascal supports anonymous functions, which can form closures. Anonymous functions are useful when you want to define a function inline without having to name it.

program Closures;

uses
  SysUtils;

type
  TIntFunc = function: Integer;

function IntSeq: TIntFunc;
var
  i: Integer;
begin
  i := 0;
  Result := function: Integer
  begin
    Inc(i);
    Result := i;
  end;
end;

var
  nextInt, newInts: TIntFunc;
  
begin
  // We call IntSeq, assigning the result (a function)
  // to nextInt. This function value captures its
  // own i value, which will be updated each time
  // we call nextInt.
  nextInt := IntSeq;

  // See the effect of the closure by calling nextInt
  // a few times.
  WriteLn(nextInt());
  WriteLn(nextInt());
  WriteLn(nextInt());

  // To confirm that the state is unique to that
  // particular function, create and test a new one.
  newInts := IntSeq;
  WriteLn(newInts());
end.

This program demonstrates the use of closures in Pascal. Here’s how it works:

  1. We define a function type TIntFunc that represents a function that takes no parameters and returns an integer.

  2. The IntSeq function returns another function of type TIntFunc. This returned function is defined anonymously within IntSeq and forms a closure over the variable i.

  3. In the begin section (equivalent to main in other languages), we call IntSeq and assign the result to nextInt. This function value captures its own i value.

  4. We call nextInt multiple times to see the effect of the closure. Each call increments and returns the captured i value.

  5. To demonstrate that each closure has its own state, we create a new function newInts using IntSeq and call it once.

When you run this program, you should see output similar to:

1
2
3
1

This output shows that nextInt maintains its own state across calls, while newInts starts with a fresh state.

The last concept we’ll look at for now is recursion, which is also supported in Pascal.