I am new to Ada, and I changed from java to Ada. I know how to create an indefinite array. But I would like to create an array like [[],[3],[3,5],[2,3,5]. And I would like to return an Array like this. I cannot find the answer on the Internet.
2 Answers
You could make an array of pointers to indefinite arrays:
type A is array (Natural range <>) of Integer;
type A_Access is access A;
type AA is array (Natural range <>) of A_Access;
but then you have to deallocate the A_Accesses (if you care, e.g. if the data is set up at the start of the program and doesn’t change).
Or, you could use Vectors:
package V is new Ada.Containers.Vectors
(Index_Type => Natural,
Element_Type => Integer);
subtype A is V.Vector;
type AA is array (Natural range <>) of A;
2 Comments
Expanding Simon answer, and assuming you do not want to manually play with pointers, you have three options with standard containers:
- An array of vectors (Simon's answer)
- A Vector of indefinite arrays.
- A vector of vectors.
Arrays are immutable in size. You can concatenate them and extract slices to another array or as arguments, but they cannot grow or shrink, which makes them a complicated choice for record members depending on what you want them for. There are ways around it if you're set on using arrays, but I wouldn't recommend going that route for a newcomer.
With options 2 and 3, you don't have that constraint as Vectors can be resized freely.
For 2:
type A is array (Natural range <>) of Integer;
package V is new Ada.Containers.Indefinite_Vectors (Natural, A);
Now V.Vector variables can grow, and their elements replaced (but not grown in place).
For 3:
package V is new Ada.Containers.Vectors (Natural, Integer);
package VV is new Ada.Containers.Vectors (Natural, V.Vector);
I hope you get the idea.
As for the difference between Vectors and Indefinite_Vectors, the former means that the elements cannot have unknown constraints at compile time (like an array length). This difference is one of the central concepts in Ada so I'd advice to read about it or you'll suffer with arrays/strings. E.g., here: https://en.wikibooks.org/wiki/Ada_Programming/Type_System#Indefinite_subtype