Skip to content
LumenaryAcademy
Practice 55 min

Records, arrays and strings

Modelling data with records and discriminants, arrays indexed by anything discrete, slices, and Ada's three kinds of string.

Code tested · 5AI-draftedAwaiting review by a computer scientist

Your guides: Chloe · The Designer, Margaret · The Profiler, Gideon · The Language Lawyer

MotivationH

Data with a shape

Real programs juggle structured data: a weather station's reading has a temperature, a humidity and a flag for rain; a week of step counts is seven numbers; a passenger's name is a sequence of characters. Ada models these with records (components of different types, each with a name), arrays (components of one type, each with an index) and strings (arrays of characters with a little extra help).

What makes Ada's versions worth a lesson of their own is how much of your intent they let you write down. An array can be indexed by an enumeration, so Rainfall (March) replaces rainfall[2] and its comment. A record can have a discriminant that decides which components exist, so a search result that found nothing simply has no index to misuse. An array type can leave its bounds open, so one function handles arrays of any length without passing the length separately. And every array knows its own bounds, so loops can never run off the end without the run-time check noticing.

DefinitionsH

Records, arrays and aggregates

Definition— Record

A record type groups named components, possibly of different types, into one value. Components may have default values, used whenever an object is created without an explicit value. A component is selected with a dot: R.Humidity.

Definition— Array

An array type maps every value of an index type (any discrete type: an integer range, an enumeration, Character, Boolean) to a component. A constrained array type fixes its bounds, array (1 .. 12) of Float; an unconstrained one, array (Positive range <>) of Float, leaves them to each object, which fixes them when it is created.

Definition— Aggregate

An aggregate is a literal for a whole record or array: positional (31.0, 77, False), named (Temperature => 31.0, Humidity => 77, Raining => False), or a mix. others => covers every component not yet mentioned, and <> means "the default value". Ada 2022 adds square brackets for array aggregates, [1, 4, 9], iterated aggregates, [for I in 1 .. 5 => I * I], and delta aggregates, (R with delta Humidity => 70), which copy a value with some components changed.

The compiler checks aggregates thoroughly: every component must be given exactly once, by position, by name or through others. Add a component to a record and every aggregate that forgot it stops compiling, the same safety net that case gives for enumerations. Records and arrays also get the equality operator = automatically, comparing component by component.

An array's bounds are always available through attributes: A'First, A'Last, A'Length and A'Range. Loops written for I in A'Range cannot go out of bounds; loops written for X of A (Ada 2012) visit the elements directly, and inside them X is a name for the element itself, so assigning to X updates the array if the array is a variable.

Worked examplesH

Records and arrays at work

A network of weather stations

ada
pragma Ada_2022;
with Ada.Text_IO; use Ada.Text_IO;

procedure Main is
   type Station is (Nairobi, Quito, Hanoi, Oslo);
   type Celsius is delta 0.1 digits 4;          -- decimal fixed point: exact tenths
   type Percent is range 0 .. 100;

   type Reading is record
      Temperature : Celsius := 0.0;
      Humidity    : Percent := 50;
      Raining     : Boolean := False;
   end record;

   --  An array indexed by an enumeration: one reading per station.
   type Network is array (Station) of Reading;

   Today : Network :=
     (Nairobi => (Temperature => 24.5, Humidity => 60, Raining => False),
      Quito   => (Temperature => 14.2, Humidity => 81, Raining => True),
      Hanoi   => (31.0, 77, False),                  -- positional aggregate
      Oslo    => (Temperature => -3.5, others => <>)); -- defaults for the rest

   Warmest : Station := Station'First;
begin
   for S in Station loop
      if Today (S).Temperature > Today (Warmest).Temperature then
         Warmest := S;
      end if;
   end loop;
   Put_Line ("Warmest: " & Warmest'Image & Today (Warmest).Temperature'Image);

   --  Ada 2022 delta aggregate: a copy with some components changed.
   Today (Quito) := (Today (Quito) with delta Raining => False, Humidity => 70);
   Put_Line ("Quito now raining? " & Today (Quito).Raining'Image
             & ", humidity" & Today (Quito).Humidity'Image);

   Put_Line ("Oslo humidity (default):" & Today (Oslo).Humidity'Image);

   --  Records and arrays get "=" for free.
   if Today (Hanoi) = (31.0, 77, False) then
      Put_Line ("Hanoi unchanged");
   end if;

   --  A quantified expression asks a question about every element.
   if (for all S in Station => Today (S).Humidity >= 50) then
      Put_Line ("Every station reports at least 50% humidity");
   end if;
end Main;

It prints:

text
Warmest: HANOI 31.0
Quito now raining? FALSE, humidity 70
Oslo humidity (default): 50
Hanoi unchanged
Every station reports at least 50% humidity

Network is indexed by Station, so the array has exactly one reading per station, and the aggregate for Today must mention all four. Celsius is a decimal fixed-point type, so 24.5 and -3.5 are stored exactly and print as written. Oslo's aggregate gives a temperature and uses others => <> to take the defaults for the rest, which is why its humidity is 50. The delta aggregate rebuilds Quito's reading with two components changed. And the quantified expression (for all S in Station => …) is true when its condition holds for every station; its partner for some is true when it holds for at least one.

Arrays of any length

ada
pragma Ada_2022;
with Ada.Text_IO; use Ada.Text_IO;

procedure Main is
   --  An unconstrained array type: each object chooses its own bounds.
   type Sample_Array is array (Positive range <>) of Integer;

   function Sum (A : Sample_Array) return Integer is
      Total : Integer := 0;
   begin
      for X of A loop               -- iterate over the elements
         Total := Total + X;
      end loop;
      return Total;
   end Sum;

   procedure Show (Label : String; A : Sample_Array) is
   begin
      Put (Label & " (" & A'First'Image & " .." & A'Last'Image & "):");
      for I in A'Range loop         -- iterate over the indices
         Put (A (I)'Image);
      end loop;
      New_Line;
   end Show;

   Steps : constant Sample_Array := [4_200, 8_150, 6_900, 12_030, 7_400, 9_800, 3_100];
   Squares : constant Sample_Array (1 .. 5) := [for I in 1 .. 5 => I * I];

   type Grid is array (1 .. 3, 1 .. 4) of Character;
   Seats : Grid := [others => [others => '.']];
begin
   Show ("Steps", Steps);
   Put_Line ("Total steps:" & Sum (Steps)'Image
             & ", days:" & Steps'Length'Image);

   Show ("Weekend", Steps (6 .. 7));           -- a slice keeps its bounds
   Put_Line ("Weekend total:" & Sum (Steps (6 .. 7))'Image);

   Show ("Squares", Squares);
   Put_Line ("Any square above 20? "
             & Boolean'Image (for some S of Squares => S > 20));

   Seats (2, 3) := 'X';
   Seats (1, 1) := 'X';
   for Row in Seats'Range (1) loop
      for Col in Seats'Range (2) loop
         Put (Seats (Row, Col));
      end loop;
      New_Line;
   end loop;
end Main;

It prints:

text
Steps ( 1 .. 7): 4200 8150 6900 12030 7400 9800 3100
Total steps: 51580, days: 7
Weekend ( 6 .. 7): 9800 3100
Weekend total: 12900
Squares ( 1 .. 5): 1 4 9 16 25
Any square above 20? TRUE
X...
..X.
....

Sample_Array is unconstrained, so Sum and Show accept arrays of any length, and they ask the array for its bounds instead of taking a length parameter. The constant Steps gets its bounds, 1 .. 7, from its initial value. Steps (6 .. 7) is a slice: a view of part of the array, which can be passed, compared and assigned like an array. Notice that the slice keeps its original indices, 6 and 7. Code that assumes every array starts at 1 breaks on slices, which is why professional Ada code always writes A'First, A'Range and A'Length instead of 1 and a length.

Grid is two-dimensional. Its bounds are queried per dimension, Seats'Range (1) for rows and Seats'Range (2) for columns, and the nested aggregate [others => [others => '.']] fills every seat.

Indexing outside the bounds raises Constraint_Error, as you would expect by now. In a loop over A'Range the compiler can see that the index is always in bounds and leave the check out, so idiomatic code pays little or nothing for this safety.

Records whose shape depends on a value

Lesson 3 promised a better way than exceptions to say "not found". A record can have a discriminant, a special component that is fixed when the object is created and that a variant part can depend on:

ada
pragma Ada_2022;
with Ada.Text_IO; use Ada.Text_IO;

procedure Main is
   type Code_List is array (Positive range <>) of Natural;

   --  A record with a discriminant: the Index component exists only when Found.
   type Search_Result (Found : Boolean := False) is record
      case Found is
         when True  => Index : Positive;
         when False => null;
      end case;
   end record;

   function Find (Codes : Code_List; Wanted : Natural) return Search_Result is
   begin
      for I in Codes'Range loop
         if Codes (I) = Wanted then
            return (Found => True, Index => I);
         end if;
      end loop;
      return (Found => False);
   end Find;

   Dialling_Codes : constant Code_List := [254, 593, 84, 47, 233];
   R : Search_Result;
begin
   for Wanted of Code_List'[84, 81] loop
      R := Find (Dialling_Codes, Wanted);
      if R.Found then
         Put_Line (Wanted'Image & " found at position" & R.Index'Image);
      else
         Put_Line (Wanted'Image & " not found");
      end if;
   end loop;

   R := Find (Dialling_Codes, 81);
   Put_Line ("Reading R.Index anyway...");
   Put_Line (R.Index'Image);
exception
   when Constraint_Error =>
      Put_Line ("Constraint_Error: R has no Index when Found is False");
end Main;

It prints:

text
 84 found at position 3
 81 not found
Reading R.Index anyway...
Constraint_Error: R has no Index when Found is False

When Found is False, the record has no Index component at all, and reading R.Index raises Constraint_Error (a discriminant check) instead of handing back a meaningless number. Because Found has a default, R can be declared without one and then hold either variant over its life. Code_List'[84, 81] is a qualified expression: it tells the compiler the type of the aggregate, which it could not otherwise know. Discriminated records serve the same purpose as Rust's Option, Haskell's Maybe or a tagged union in C, with the check made by the language.

ComputationC

Strings

In Ada, String is simply a predefined unconstrained array type:

ada
type String is array (Positive range <>) of Character;

So everything you just learnt about arrays applies: a String object has fixed bounds once created, slices keep their indices, = compares lengths and characters, and & concatenates (producing a new string). That makes String excellent for text whose length is known when it is created, such as constants, parameters and function results, and awkward for text that grows, because a String variable can never change its length.

Ada therefore offers three kinds of string, each with its own package:

KindPackageLengthUse it for
StringAda.Strings.Fixed for operationsfixed when createdparameters, results, constants; the default
Unbounded_StringAda.Strings.Unboundedgrows and shrinks freely (heap allocated)building text, record components of varying length
Bounded_StringAda.Strings.Bounded (a generic)varies up to a fixed maximum (no heap)embedded and real-time code that avoids the heap

Character is Latin-1. For full Unicode, Ada has Wide_Wide_String and the packages Ada.Strings.UTF_Encoding, and many programs simply keep UTF-8 in String and treat it as bytes.

ada
pragma Ada_2022;
with Ada.Text_IO;             use Ada.Text_IO;
with Ada.Strings;             use Ada.Strings;
with Ada.Strings.Fixed;       use Ada.Strings.Fixed;
with Ada.Strings.Unbounded;   use Ada.Strings.Unbounded;
with Ada.Characters.Handling; use Ada.Characters.Handling;

procedure Main is
   Line : constant String := "  Amara Okafor, Lagos  ";
   Name  : constant String  := Trim (Line, Both);  -- spaces removed at both ends
   Comma : constant Natural := Index (Name, ",");  -- position of the first comma
   City  : String renames Name (Comma + 2 .. Name'Last);

   function Initials (Full : String) return String is
      Result : Unbounded_String;
      Start_Of_Word : Boolean := True;
   begin
      for C of Full loop
         if C = ' ' then
            Start_Of_Word := True;
         elsif Start_Of_Word then
            Append (Result, To_Upper (C));
            Start_Of_Word := False;
         end if;
      end loop;
      return To_String (Result);
   end Initials;
begin
   Put_Line ("[" & Name & "]");
   Put_Line ("Bounds:" & Name'First'Image & " .." & Name'Last'Image
             & ", length" & Name'Length'Image);
   Put_Line ("Person: " & Name (Name'First .. Comma - 1));
   Put_Line ("City:   " & City & ", bounds" & City'First'Image & " .." & City'Last'Image);
   Put_Line ("Upper:  " & To_Upper (Name));
   Put_Line ("Initials of 'nguyen thi lan': " & Initials ("nguyen thi lan"));

   declare
      Log : Unbounded_String := To_Unbounded_String ("Log:");
   begin
      for Day in 1 .. 3 loop
         Append (Log, " day" & Day'Image & ";");
      end loop;
      Put_Line (To_String (Log) & " length" & Length (Log)'Image);
   end;

   Put_Line ("Same text? " & Boolean'Image (Name = "Amara Okafor, Lagos"));
   Put_Line (5 * "ab" & "!");
end Main;

It prints:

text
[Amara Okafor, Lagos]
Bounds: 1 .. 19, length 19
Person: Amara Okafor
City:   Lagos, bounds 15 .. 19
Upper:  AMARA OKAFOR, LAGOS
Initials of 'nguyen thi lan': NTL
Log: day 1; day 2; day 3; length 25
Same text? TRUE
ababababab!

Each line shows a common task:

  • Trim (Line, Both) from Ada.Strings.Fixed removes spaces at both ends; Index (Name, ",") finds the first comma, returning 0 if there is none (a check worth adding in real code).
  • City : String renames Name (…) gives a slice a name without copying it. Its bounds are 15 .. 19, the positions in Name, not 1 .. 5.
  • To_Upper from Ada.Characters.Handling works on characters and on whole strings; the same package has tests such as Is_Digit and Is_Letter.
  • Initials builds its result in an Unbounded_String with Append, then converts with To_String. This is the idiom for text whose final length you do not know in advance.
  • 5 * "ab" uses the * operator from Ada.Strings.Fixed, which repeats a string.

A practical rule from experienced Ada programmers: use String everywhere you can, declared at the point where its value is known (in a declare block if need be), and reach for Unbounded_String for record components and accumulating text. Many apparent needs for a growing string disappear once you write constant String := … at the right place.

ExplanationH

Data layout under your control

So far the compiler has chosen how records and arrays are laid out in memory, which is what you want almost all the time. But Ada was designed for embedded systems, where a record may have to match a hardware register, a network packet or a file format bit for bit. For those cases Ada lets you state the layout exactly, with representation clauses and aspects, and the compiler either obeys or refuses to compile. Nothing is left to compiler-specific packing rules, as it often is with C's bit-fields.

ada
pragma Ada_2022;
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Unchecked_Conversion;
with System;

procedure Main is
   type Mode is (Off, Heat, Cool, Fan) with Size => 2;
   for Mode use (Off => 0, Heat => 1, Cool => 2, Fan => 3);

   type Level is range 0 .. 15 with Size => 4;

   --  A one-byte hardware control register, laid out bit by bit.
   type Control_Register is record
      Enabled : Boolean;
      Alarm   : Boolean;
      Current : Mode;
      Setting : Level;
   end record
     with Size => 8, Bit_Order => System.Low_Order_First;

   for Control_Register use record
      Enabled at 0 range 0 .. 0;
      Alarm   at 0 range 1 .. 1;
      Current at 0 range 2 .. 3;
      Setting at 0 range 4 .. 7;
   end record;

   type Flags is array (1 .. 16) of Boolean with Pack;

   type Byte is mod 256 with Size => 8;
   function To_Byte is new Ada.Unchecked_Conversion (Control_Register, Byte);

   R : constant Control_Register :=
     (Enabled => True, Alarm => False, Current => Cool, Setting => 9);
begin
   Put_Line ("Control_Register'Size =" & Control_Register'Size'Image & " bits");
   Put_Line ("Flags'Size            =" & Flags'Size'Image & " bits");
   Put_Line ("Register value        =" & To_Byte (R)'Image);
end Main;

It prints:

text
Control_Register'Size = 8 bits
Flags'Size            = 16 bits
Register value        = 153

The enumeration representation clause fixes the codes of Mode, and Size => 2 fits it in two bits. The record representation clause places each component: Setting at 0 range 4 .. 7 means byte 0, bits 4 to 7, with bit 0 the least significant because of Bit_Order => System.Low_Order_First. The packed Flags array uses one bit per Boolean. Ada.Unchecked_Conversion reinterprets the record's bits as a Byte: Setting 9 in the top four bits gives 144, Cool (code 2) in bits 2 and 3 gives 8, and Enabled gives 1, so 153. Its name is a warning: it is the one place where the type system steps aside, and professional code keeps such conversions few, small and reviewed.

On real hardware the same record would be placed at the register's address with the aspects Address and Volatile, and the rest of the program would read and write named, typed fields instead of shifting and masking bits. Driver code written this way reads almost like the chip's data sheet.

Common misconceptionsH

Common misunderstandings

Misconception

"Arrays start at 1 (or 0)." Ada arrays start wherever their index type or bounds say: at Mon, at -10, at 15 for a slice. Write A'First, A'Last and A'Range, never literal bounds, unless the type itself fixes them.

Misconception

"I can assign a longer string to a String variable." A String object's length is fixed when it is declared. S : String (1 .. 5); … S := "Hello, world"; raises Constraint_Error at run time (and GNAT warns at compile time). Use a new constant String declaration, or an Unbounded_String.

Misconception

"A discriminated record is just a struct with a flag." In C, nothing stops you reading the index field of a "not found" result. In Ada the variant's components do not exist unless the discriminant selects them, and every access is checked. With SPARK, the check can be proved never to fail.

Misconception

"Unbounded_String is the normal string type, like in Java." It is a convenience with a cost (heap allocation and copying). Idiomatic Ada uses plain String for most text and keeps Unbounded_String for the places that genuinely need to grow.

Exercises

Exercises

All outputs below were checked by compiling and running the code with GNAT 14.

1. Records, arrays and strings

Warm-upComputational

In the arrays program, what does Sum (Steps (2 .. 4)) return? (Steps is [4_200, 8_150, 6_900, 12_030, 7_400, 9_800, 3_100].)

2. Records, arrays and strings

CoreComputational

What line does Show ("Mid", Steps (3 .. 4)); print?

3. Records, arrays and strings

CoreComputational

In the strings program, Line is changed to "Ngozi Adeyemi, Abuja ". What is City'First now?

4. Records, arrays and strings

Warm-upComputational

What does Initials ("ana maria de souza") return?

6. Records, arrays and strings

CoreComputational

With Squares equal to [1, 4, 9, 16, 25], what does Put_Line (Boolean'Image (for all S of Squares => S mod 2 = 1)); print?

7. Records, arrays and strings

CoreHuman

R is a Search_Result whose Found discriminant is False. What happens when the program evaluates R.Index?

Choose one

8. Records, arrays and strings

StretchHuman

Firmware for a medical pump must not use the heap. It stores a patient label of up to 40 characters in a record. Which string type fits best?

Choose one

Further reading and resources