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.
This program demonstrates the use of closures in Pascal. Here’s how it works:
We define a function type
TIntFunc
that represents a function that takes no parameters and returns an integer.The
IntSeq
function returns another function of typeTIntFunc
. This returned function is defined anonymously withinIntSeq
and forms a closure over the variablei
.In the
begin
section (equivalent tomain
in other languages), we callIntSeq
and assign the result tonextInt
. This function value captures its owni
value.We call
nextInt
multiple times to see the effect of the closure. Each call increments and returns the capturedi
value.To demonstrate that each closure has its own state, we create a new function
newInts
usingIntSeq
and call it once.
When you run this program, you should see output similar to:
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.