Closures in Ada
Ada Example: Closures
Ada does support concepts similar to closures, although its syntax and structure are quite different from other languages. Here’s how the given Go code example can be translated to Ada.
Explanation:
Ada supports nested subprograms, which can be used to simulate closures. The nested subprogram (inner function) can access and modify variables from the enclosing scope.
Full Source Code
with Ada.Text_IO; use Ada.Text_IO;
procedure Main is
function Int_Seq return access function return Integer is
I : Integer := 0;
function Next_Int return Integer is
begin
I := I + 1;
return I;
end Next_Int;
begin
return Next_Int'Access;
end Int_Seq;
begin
-- Call Int_Seq, assigning the result to Next_Int
Next_Int : access function return Integer := Int_Seq;
-- The function value captures its own I value
-- and updates it each time we call Next_Int
Put_Line(Integer'Image(Next_Int.all));
Put_Line(Integer'Image(Next_Int.all));
Put_Line(Integer'Image(Next_Int.all));
-- Confirming that the state is unique to that
-- particular function, create and test a new one
New_Ints : access function return Integer := Int_Seq;
Put_Line(Integer'Image(New_Ints.all));
end Main;Explanation and Usage
This Ada code defines a procedure Main where:
- The
Int_Seqfunction returns an access to another inner functionNext_Int, effectively creating a closure. - The variable
Iis encapsulated within the scope ofInt_Seqand is modified byNext_Int. - The
Next_Intfunction is called multiple times to demonstrate the state preservation and increment behavior. - A new instance
New_Intsis created to confirm that the state variableIis unique to each function closure.
Running the Code
To compile and run the Ada program, follow these commands:
$ gnatmake main.adb
$ ./main
1
2
3
1In this example, the output shows that the first sequence increments the value from 1 to 3, and the new sequence starts again from 1, confirming the independent state of each closure.
Comments powered by Disqus