Title here
Summary here
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.
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.
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;
This Ada code defines a procedure Main
where:
Int_Seq
function returns an access to another inner function Next_Int
, effectively creating a closure.I
is encapsulated within the scope of Int_Seq
and is modified by Next_Int
.Next_Int
function is called multiple times to demonstrate the state preservation and increment behavior.New_Ints
is created to confirm that the state variable I
is unique to each function closure.To compile and run the Ada program, follow these commands:
$ gnatmake main.adb
$ ./main
1
2
3
1
In 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.