[Ada] How do I work with arrays or lists in Ada?

In Ada, arrays and lists are called arrays and access types, respectively. Here's how you can work with arrays and lists in Ada:

  1. Arrays:

    • Declare an array type: Define the type of the elements and the index range.
    1type MyArray is array (Integer range <>) of Element_Type;
    • Declare an array variable: Instantiate the array type with a specific size.
    1MyArray : MyArray(1..10);
    • Accessing array elements: Use the array variable name with the appropriate index.
    1MyArray(3) := 42; -- Assigning a value to the third element
    2X := MyArray(5); -- Retrieving the value of the fifth element
    • Iterate over an array: Use a loop construct, such as a for loop or a while loop.
    1for I in MyArray'Range loop
    2   -- Access MyArray(I)
    3end loop;
  2. Lists using access types:

    • Declare a list type: Define a record type containing the element and a pointer to the next node.
    1type Node;
    2type Node_Ptr is access Node;
    3type Node is record
    4   Data : Element_Type;
    5   Next : Node_Ptr := null;
    6end record;
    • Declare a list variable: Instantiate the list type.
    1MyList : Node_Ptr := null;
    • Adding elements to the list: Allocate a new node and link it to the previous node.
    1New_Node : Node_Ptr := new Node;
    2New_Node.Data := Element_Value;
    3New_Node.Next := MyList;
    4MyList := New_Node;
    • Accessing list elements: Traverse the list using the Next pointer.
    1Current := MyList;
    2while Current /= null loop
    3   -- Access Current.Data
    4   Current := Current.Next;
    5end loop;

Remember to handle memory deallocation in the case of lists created using access types to avoid memory leaks.