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_Seq function returns an access to another inner function Next_Int, effectively creating a closure.
  • The variable I is encapsulated within the scope of Int_Seq and is modified by Next_Int.
  • The Next_Int function is called multiple times to demonstrate the state preservation and increment behavior.
  • A new instance New_Ints is created to confirm that the state variable I is 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
 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.