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:
We define a function type
TIntFuncthat represents a function that takes no parameters and returns an integer.The
IntSeqfunction returns another function of typeTIntFunc. This returned function is defined anonymously withinIntSeqand forms a closure over the variablei.In the
beginsection (equivalent tomainin other languages), we callIntSeqand assign the result tonextInt. This function value captures its ownivalue.We call
nextIntmultiple times to see the effect of the closure. Each call increments and returns the capturedivalue.To demonstrate that each closure has its own state, we create a new function
newIntsusingIntSeqand call it once.
When you run this program, you should see output similar to:
1
2
3
1This 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.