Task

Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index    i     (you may choose to start     i     from either    0    or    1),    when run, should return the square of the index,   that is,     i  2.

Display the result of running any but the last function, to demonstrate that the function indeed remembers its value.



Goal

Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over.

In imperative languages, one would generally use a loop with a mutable counter variable.

For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.

See also: Multiple distinct objects

with Ada.Text_IO;
 
procedure Value_Capture is
 
   protected type Fun is -- declaration of the type of a protected object
      entry Init(Index: Natural);
      function Result return Natural;
   private
      N: Natural := 0;
   end Fun;
 
   protected body Fun is -- the implementation of a protected object
      entry Init(Index: Natural) when N=0 is
      begin -- after N has been set to a nonzero value, it cannot be changed any more
         N := Index;
      end Init;
      function Result return Natural is (N*N);
   end Fun;
 
   A: array (1 .. 10) of Fun; -- an array holding 10 protected objects
 
begin
   for I in A'Range loop -- initialize the protected objects
      A(I).Init(I);
   end loop;
 
   for I in A'First .. A'Last-1 loop -- evaluate the functions, except for the last
      Ada.Text_IO.Put(Integer'Image(A(I).Result));
   end loop;
end Value_Capture;