Ada hash tables
last modified November 23, 2026
A hash table stores key-value pairs in an array and uses a hash function to
jump close to the right slot instead of walking through every element. When
two keys land in the same slot, a collision policy decides what happens next.
This article hashes integer and string keys, resolves collisions with linear
probing, grows the table by rehashing, counts word frequencies, and compares
the hand-written table with Ada.Containers.Hashed_Maps.
Hashing a key
The hash function turns a key into an index in the table. For an integer key
and a table of ten buckets, Key mod Buckets is enough: the result
is always in the range 0 .. 9, because mod takes the
sign of the divisor, which is positive here. The first program distributes
twenty-five keys over ten buckets and counts how many keys each bucket
receives.
with Ada.Text_IO; use Ada.Text_IO;
procedure Hash_Demo is
Buckets : constant := 10;
function Hash (Key : Integer) return Natural is
begin
return Key mod Buckets;
end Hash;
Counts : array (0 .. Buckets - 1) of Natural := [others => 0];
begin
for Key in 1 .. 25 loop
Counts (Hash (Key)) := Counts (Hash (Key)) + 1;
end loop;
for B in Counts'Range loop
Put_Line ("bucket" & Natural'Image (B) & ":" & Natural'Image (Counts (B)));
end loop;
end Hash_Demo;
The keys are spread fairly evenly, but not perfectly: buckets 1 to 5 receive three keys each and the remaining buckets two. A bucket that receives more than one key produces a collision. Even this small example collides, because there are more keys than buckets, and no hash function can avoid that once the number of keys exceeds the table size.
$ gnatmake -gnat2022 -gnatwa hash_demo.adb $ ./hash_demo bucket 0: 2 bucket 1: 3 bucket 2: 3 bucket 3: 3 bucket 4: 3 bucket 5: 3 bucket 6: 2 bucket 7: 2 bucket 8: 2 bucket 9: 2
Placing keys with linear probing
Open addressing keeps every entry inside the array and resolves a collision by
probing the next slot. With linear probing the probe sequence is
Index + 1, Index + 2, and so on, wrapping around at
the end. The table has eleven slots, and the keys 3, 14, 25, and 36 all hash
to slot 3: each one probes past the occupied slots that the previous keys left
behind until it finds a free one.
with Ada.Text_IO; use Ada.Text_IO;
procedure Linear_Probing is
Size : constant := 11;
type Slot is record
Used : Boolean := False;
Key : Integer := 0;
end record;
Table : array (0 .. Size - 1) of Slot := [others => (False, 0)];
function Hash (Key : Integer) return Natural is
begin
return Key mod Size;
end Hash;
procedure Insert (Key : Integer) is
Index : Natural := Hash (Key);
begin
while Table (Index).Used loop
Index := (Index + 1) mod Size;
end loop;
Table (Index) := (True, Key);
end Insert;
Keys : constant array (1 .. 8) of Integer :=
[3, 14, 25, 36, 7, 18, 29, 40];
begin
for K of Keys loop
Insert (K);
end loop;
for I in Table'Range loop
if Table (I).Used then
Put_Line ("slot" & Natural'Image (I) & ":" & Integer'Image (Table (I).Key));
end if;
end loop;
end Linear_Probing;
The first four keys form a single run in slots 3 through 6. The next key, 7, hashes to slot 7, which is free, and 18, 29, and 40 follow in slots 8 to 10. The cluster is exactly what linear probing produces: once a key has been displaced from its hash slot, every later key that hashes into the same slot must walk to the end of the run. The table now contains one long cluster, so a lookup for a missing key that hashes into it walks the whole run.
$ gnatmake -gnat2022 -gnatwa linear_probing.adb $ ./linear_probing slot 3: 3 slot 4: 14 slot 5: 25 slot 6: 36 slot 7: 7 slot 8: 18 slot 9: 29 slot 10: 40
Searching with a probe
A lookup follows the same path as an insertion. It starts at the hash slot and moves forward until it finds the key or an empty slot. An empty slot proves that the key is absent, because any key that hashed there would have been placed at or before that position. The next program inserts the same eight keys and checks 36, which is present, and 50 and 11, which are not.
with Ada.Text_IO; use Ada.Text_IO;
procedure Open_Addressing is
Size : constant := 11;
type Slot_State is (Empty, Occupied);
type Slot is record
State : Slot_State := Empty;
Key : Integer := 0;
end record;
Table : array (0 .. Size - 1) of Slot := [others => (Empty, 0)];
function Hash (Key : Integer) return Natural is
begin
return Key mod Size;
end Hash;
procedure Insert (Key : Integer) is
Index : Natural := Hash (Key);
begin
while Table (Index).State = Occupied loop
Index := (Index + 1) mod Size;
end loop;
Table (Index) := (Occupied, Key);
end Insert;
function Contains (Key : Integer) return Boolean is
Index : Natural := Hash (Key);
Steps : Natural := 0;
begin
while Steps < Size loop
if Table (Index).State = Empty then
return False;
elsif Table (Index).Key = Key then
return True;
end if;
Index := (Index + 1) mod Size;
Steps := Steps + 1;
end loop;
return False;
end Contains;
Keys : constant array (1 .. 8) of Integer :=
[3, 14, 25, 36, 7, 18, 29, 40];
Checks : constant array (1 .. 3) of Integer := [36, 50, 11];
begin
for K of Keys loop
Insert (K);
end loop;
for K of Checks loop
Put_Line (Integer'Image (K) & " ->" & Boolean'Image (Contains (K)));
end loop;
end Open_Addressing;
36 hashes to slot 3 and is found after the three keys already in the cluster.
50 hashes to slot 6, which holds 36, and the search walks through 7, 8, 9, and
10 before reaching the empty slot 0, so it reports false. 11 hashes to slot 0,
finds it empty, and returns false at once. The Steps counter
stops the loop after a full circle; without it a search for a missing key in a
full table would never see an empty slot and would not terminate. This version
has no deletion. Removing an entry cannot simply mark the slot empty, because
that would cut the probe chain of a later key; a real implementation uses a
third Deleted state or rehashes the table.
$ gnatmake -gnat2022 -gnatwa open_addressing.adb $ ./open_addressing 36 ->TRUE 50 ->FALSE 11 ->FALSE
Growing the table
A table that stays nearly full makes probing slow, so it is kept below a load factor, the ratio of stored entries to slots. The next program starts with eight slots, inserts ten keys, and grows to sixteen slots as soon as the count reaches seventy percent of the capacity. Growing means allocating a larger table and reinserting every live key, because the index of a key depends on the table size.
with Ada.Text_IO; use Ada.Text_IO;
procedure Growth is
Max_Size : constant := 32;
type Slot is record
Used : Boolean := False;
Key : Integer := 0;
end record;
type Table_Type is array (0 .. Max_Size - 1) of Slot;
Table : Table_Type := [others => (False, 0)];
Size : Natural := 8;
Count : Natural := 0;
function Hash (Key : Integer; Modulus : Natural) return Natural is
begin
return Key mod Modulus;
end Hash;
procedure Place (Key : Integer) is
Index : Natural := Hash (Key, Size);
begin
while Table (Index).Used and then Table (Index).Key /= Key loop
Index := (Index + 1) mod Size;
end loop;
if not Table (Index).Used then
Table (Index) := (True, Key);
Count := Count + 1;
end if;
end Place;
procedure Grow is
Old : constant Table_Type := Table;
begin
Table := [others => (False, 0)];
Size := Size * 2;
Count := 0;
for I in Old'Range loop
if Old (I).Used then
Place (Old (I).Key);
end if;
end loop;
end Grow;
procedure Insert (Key : Integer) is
begin
Place (Key);
if Count * 10 >= Size * 7 then
Grow;
end if;
end Insert;
begin
for K in 1 .. 10 loop
Insert (K * 10);
Put_Line ("insert" & Integer'Image (K * 10) &
": size =" & Natural'Image (Size) &
", count =" & Natural'Image (Count));
end loop;
end Growth;
The sixth insertion takes the count to six of eight slots, so
Grow copies the old array into Old, clears the
table, doubles Size,
and places each live key again with the new modulus. After that the same ten
keys occupy a table of sixteen slots, and every later lookup hashes with the
new size and follows the shorter clusters. The array is declared with the
maximum size the program will ever need,
because an ordinary Ada array cannot change its bounds; a production table
would allocate the array dynamically or use a vector of slots.
$ gnatmake -gnat2022 -gnatwa growth.adb $ ./growth insert 10: size = 8, count = 1 insert 20: size = 8, count = 2 insert 30: size = 8, count = 3 insert 40: size = 8, count = 4 insert 50: size = 8, count = 5 insert 60: size = 16, count = 6 insert 70: size = 16, count = 7 insert 80: size = 16, count = 8 insert 90: size = 16, count = 9 insert 100: size = 16, count = 10
Hashing strings
A string needs a hash function that mixes all of its characters into one
number. A common choice processes the characters from left to right and keeps
H * 31 + Character'Pos (C), reduced modulo the table size after
every step so that the intermediate value stays small. The multiplier 31
spreads similar words apart: fox and fog end in
different buckets even though most of their characters are equal. The next
program stores the words in Unbounded_String keys, because the
words have different lengths.
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
procedure Word_Frequency is
Size : constant := 101;
type Word_Entry is record
Used : Boolean := False;
Word : Unbounded_String;
Count : Natural := 0;
end record;
Table : array (0 .. Size - 1) of Word_Entry :=
[others => (False, Null_Unbounded_String, 0)];
Text : constant String :=
"the quick brown fox jumps over the lazy dog the fox sleeps";
function Hash (Word : String) return Natural is
H : Natural := 0;
begin
for C of Word loop
H := (H * 31 + Character'Pos (C)) mod Size;
end loop;
return H;
end Hash;
procedure Add (Word : String) is
Index : Natural := Hash (Word);
begin
loop
if not Table (Index).Used then
Table (Index) := (True, To_Unbounded_String (Word), 1);
return;
elsif To_String (Table (Index).Word) = Word then
Table (Index).Count := Table (Index).Count + 1;
return;
end if;
Index := (Index + 1) mod Size;
end loop;
end Add;
Start : Positive := Text'First;
begin
for I in Text'Range loop
if Text (I) = ' ' then
Add (Text (Start .. I - 1));
Start := I + 1;
end if;
end loop;
Add (Text (Start .. Text'Last));
for I in Table'Range loop
if Table (I).Used then
Put_Line (To_String (Table (I).Word) & ":" &
Natural'Image (Table (I).Count));
end if;
end loop;
end Word_Frequency;
Add probes until it finds either the word or an unused slot. An
existing word increments its counter; a new word is stored with a count of
one. The table has 101 slots for nine distinct words, so collisions are
unlikely, and even with a collision the linear probe finds the key or a free
slot. Printing walks the array from index zero, which is why the output is in
hash order rather than alphabetical order: the and
fox appear before brown because their hashes are
smaller.
$ gnatmake -gnat2022 -gnatwa word_frequency.adb $ ./word_frequency sleeps: 1 quick: 1 lazy: 1 over: 1 dog: 1 the: 3 fox: 2 jumps: 1 brown: 1
The standard hashed map
The standard library provides the same idea as a generic package.
Ada.Containers.Hashed_Maps takes the key type, the element type,
a hash function, and an equivalence function for keys. For
Unbounded_String keys the child unit
Ada.Strings.Unbounded.Hash supplies the hash function, and the
equality operator supplies Equivalent_Keys. The map takes care
of the table, collisions, and growth.
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Containers.Hashed_Maps;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Strings.Unbounded.Hash;
procedure Map_Frequency is
package Word_Maps is new Ada.Containers.Hashed_Maps
(Key_Type => Unbounded_String,
Element_Type => Natural,
Hash => Ada.Strings.Unbounded.Hash,
Equivalent_Keys => Ada.Strings.Unbounded."=");
Text : constant String :=
"the quick brown fox jumps over the lazy dog the fox sleeps";
Map : Word_Maps.Map;
procedure Add (Word : String) is
Key : constant Unbounded_String := To_Unbounded_String (Word);
Pos : constant Word_Maps.Cursor := Map.Find (Key);
begin
if Word_Maps.Has_Element (Pos) then
Map.Replace_Element (Pos, Word_Maps.Element (Pos) + 1);
else
Map.Insert (Key, 1);
end if;
end Add;
Start : Positive := Text'First;
begin
for I in Text'Range loop
if Text (I) = ' ' then
Add (Text (Start .. I - 1));
Start := I + 1;
end if;
end loop;
Add (Text (Start .. Text'Last));
for Pos in Map.Iterate loop
Put_Line (To_String (Word_Maps.Key (Pos)) & ":" &
Natural'Image (Word_Maps.Element (Pos)));
end loop;
end Map_Frequency;
Find returns a cursor, and Has_Element says whether
the key was present. An existing entry is updated through
Replace_Element; a new one is added with Insert.
The counts match the hand-written table, but the iteration order differs,
because the standard map uses its own hash function and its own table size.
That order is an implementation detail and should never be relied upon when
the output must be sorted.
$ gnatmake -gnat2022 -gnatwa map_frequency.adb $ ./map_frequency the: 3 fox: 2 brown: 1 quick: 1 lazy: 1 sleeps: 1 dog: 1 over: 1 jumps: 1
Next steps
The next article stays with text and processes it without a table: it counts words, splits CSV lines, trims headers, classifies characters, and checks palindromes. The containers article describes the standard maps and sets in more detail, and the arrays article explains the aggregates and index ranges used by the bucket array.
Source
Ada Reference Manual: Hashed Maps
In this article we have hashed integer and string keys, resolved collisions
with linear probing, grown a table by rehashing, counted word frequencies with
a hand-written table, and repeated the count with
Ada.Containers.Hashed_Maps. The
stacks, queues and trees article shows
the node-based structures that a hash table replaces when a key is available.
Author
List all Ada tutorials.