7. Arrays - JulTob/Ada GitHub Wiki

Un array es un objeto compuesto formado por un conjunto de elementos del mismo tipo. Cada componente se identifica mediante uno o más índices discretos.

✋🏼 In Ada, Arrays are first-class objects.

☝️ They are not pointers to something.

👌🏼 Every time we make a new array we are creating a type.

🤲🏼 Arrays can be used in different manners.

Vector: array (1 .. 10) of Integer;  -- Note it goes 1 to 10
...
Vector:=(1,2,3,4,5,6,7,8,9,10); 
Vector(1) := 10; --  Se asigna el valor 10 al primer elemento del array
Vector(2) := 20; --  Se asigna el valor 20 al segundo elemento del array

☝🏼 Ada lets you set your indexes as you like. You are not bounded to starting from 0. It can start at 0, 1, 42, or whatever.

Matrix : array (1 .. 20, 1..20) of Float;
Page: array (5 .. 30, 1 .. 25) of Character;  
Workspace: array (1 .. 1024) of Character;
type weekday is (sn,mn,tu,we,th,fr,st);
Work_Hours : array (weekday) of Natural;
...
Work_Hours:=(0,8,8,8,8,0);
Work_Hours(Mn) := 5;
hours_Monday := Work_Hours(Mn); 
Type Buffer_Type is array (0..1023) of Character;
A: Buffer_Type;
B: array (0..1023) of Character;
...
A = B; --ERROR!! Doesn’t match

Array's proper index

✌️ The best way of indexing is making a proper type

Type Height is new integer range 0..250; -- [cm]
Type Age is new integer range 0..150;    -- [years]

type People is array (Height, Age) of Integers;
Stats: People := (others => 0);

Arrays as functions

--Array as function
 Probability: array(-10..10) of float;
 ...
 Probability( 
    1 => 0.5,
    2 => 0.3,
    3 => 0.2,
    4 => 0.1,
    others => 0.0)
...
  Probability(-3); 
  -- Functionally identical to a function. THIS IS BY DESIGN (and awesome)
...
for x in Probability'Range loop

   Ada.Text_IO.Put(" | ");
   Ada.Float_Text_IO.Put(Probability(x), Aft => 2, Exp => 0);
end loop; Ada.Text_IO.New_Line(3);

Indexing is on purpose similar to a function call. It allows hiding implementation, so you don’t have to know about inferior layers. You can change it for a function later on, and no one will know.

Probability'Range is equivalent to Probability'First..Probability'Last

example of declaring an array of 26 characters, initializing the values from ‘a’ to ‘z’:

declare
  type Arr_Type is array (Integer range <>) of Character;
  Arr : Arr_Type (1 .. 26);
  C : Character := ’a’;
  begin
    for I in Arr’Range loop
      Arr (I) := C;
      C := Character’Succ (C);
      end loop;
  end;
declare 
   type Arr_Type is array (Integer range <>) of Integer
   A1: Arr_type (1..3);
   A2: arr_Type (1 .. 3);
   A3: arr_Type (3 .. 5);
   A4: arr_Type (1 .. 5) := (others := 0);
   A5: arr_Type := (1,2,3,4,5,6);
   begin
     -- Elemental Assignation
     A1(1) := 0;
     A1(2) := 1;
     A1(3) := 1;

     -- Builds a copy of the array object with the same values
     ---- It does NOT point to the same place -- <3
     A2:= A1; 
     A3 (3 .. 4) = A2 (2 .. 3);

     -- Comparing by content, all equal?
     if A2 = A1 then 
        null; end if;
      
      -- Default values
      A5:= (1, 2, others => 10);
      -- Slice assignment
      A4(1..3) := (others => 11);
   end

Signal

	type signal is array (Integer range <>) of Integer;

Length variable arrays

	long	: Integer:= x  --x declared somewhere else
	ArrUnb	: array (1..x) of Integer;

Anonymous Arrays

Built at runtime


	AuxArr	: array (1..6) 
		  of Integer	:=(others=>0);


	AuxStr	: String(1..12)	:=(others=>' ');


	AuxWord	: ASU.Unbounded_String;

Access

Arr(index)		-- Element from array at the index's position
			-- Looks like a function call ...hmmm
	Arr'first 	-- First Element, at first index
	Arr'last  	-- Last Element,  at last index
	
	Arr'lenght	-- Length in Integer type
	
	Arr'range	-- Range from first to last index; in Index type set

	Bool:= index in Arr'range; -- Is index valid ?

	Arr(index) := value ;

Compare arrays

Element to element.

Arr1 = Arr2

Concatenate arrays

Arr1 & Arr2

Aggregates

Un agregado de record especifica los valores de los componentes de un record, bien asociándolos por posición, bien asociándolos por nombre. Cuando se usa un agregado nominal los campos se pueden enumerar en cualquier orden, pero siempre hay que enumerarlos todos.

Son agregados de valores del tipo de los elementos del array que se pueden utilizar para inicializar variables o constantes de tipo array, asignarlos a variables de tipo array o emplearlos en otras operaciones que involucren arrays. Un agregado posicional se forma enumerando los valores según su posición. También se pueden definir agregados por asociación nominal, indicando para cada valor la posición a que corresponde, en cuyo caso se pueden enumerar salteados y desordenados. La palabra others sirve para indicar el valor de los elementos no mencionados de forma explícita. El símbolo <> significa que se dará el valor por omisión que esté previsto para el tipo, si lo hay.

--  Array monodimensional
V: array (1 .. 5) of Integer := (12, 3, 45, 6, 8);
V := (12, 3, 45, others => 0);
V := (others => 0);
V := (4, 3 => 15, 5 => 8, others => 0);
V := (4, 3 => 15, 5 => 8, others => <>);

--  Array multidiemensional (se anidan las dimensiones)
M: array (1..3, 1..2) of Character := (('a','b'),('c','d'),('e','f'));
M := (('a', 'b'),('c', others => 'd'), others => ('e','f'));
M := (3 => ('e','f'), 1 => ('a','b'), others => ('c','d'));

Arr := (Val1, Val2 ... ValN );
Arr := ( index1 => Val1,
         index3 => Val3,
         indexN => ValN, ...
         others => defaultVal);
Arr := ArrType'(Val1, Val2, others => defaultVal);

type Complejo is record
    Real, Imag: Float := 0.0;
end record;

X : Complejo;
X := (3.5, 7.1);                 --  Asociación posicional
X := (Real => 3.5, Imag => 7.1); --  Asociación nominal
X := (others => 0.0);
X := (others => <>);             --  Valor por omisión

Slices

type Vector_1 is array (1 .. 20) of Integer;
subtype Diez is Integer range 1 .. 10;
V0, V1 : Vector_1;
...
V0 (5 .. 15);
V0 (Diez);
V1 (1 .. 15) := V0 (1 .. 15);
V1 (Diez) := V0 (1 .. 10);