Modula-2 hash tables
last modified November 27, 2026 Modula-2
A hash table stores values under keys and finds a key in a few steps, no matter how many keys it holds. A hash function turns the key into the index of a slot in an array, and the value is stored in that slot. When two keys get the same slot, the table needs a rule to place the second one elsewhere.
This article uses open addressing with linear
probing: every entry lives in the array itself, and a key whose slot
is taken goes to the next free one. All examples are compiled with
-fiso.
Slots and a hash function
A hash function for strings combines the codes of all characters, so that similar keys land far apart. The result is reduced modulo the number of slots.
MODULE hash;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteCard;
CONST
Size = 11;
PROCEDURE Hash(key: ARRAY OF CHAR; size: CARDINAL): CARDINAL;
VAR
h, i: CARDINAL;
BEGIN
h := 0;
i := 0;
WHILE (i <= HIGH(key)) AND (key[i] # 0C) DO
h := (h * 31 + ORD(key[i])) MOD size;
INC(i)
END;
RETURN h
END Hash;
PROCEDURE Show(key: ARRAY OF CHAR);
BEGIN
WriteString(key);
WriteString(" -> slot ");
WriteCard(Hash(key, Size), 0);
WriteLn
END Show;
BEGIN
Show("apple");
Show("banana");
Show("cherry");
Show("plum");
Show("pear");
Show("fig");
Show("lime");
Show("kiwi")
END hash.
For each character, Hash multiplies the result so far by 31
and adds the character code. Taking MOD size at each step keeps
the value small, so the CARDINAL never overflows, and the
result is always a valid slot from 0 to size - 1. The same key
always gives the same slot. Eight keys in eleven slots already collide:
pear and lime both hash to slot 0.
$ gm2 -fiso hash.mod -o hash $ ./hash apple -> slot 10 banana -> slot 1 cherry -> slot 6 plum -> slot 5 pear -> slot 0 fig -> slot 4 lime -> slot 0 kiwi -> slot 3
Insert and find
The table is an array of entries. Each entry holds a key, a value and a flag that tells whether the slot is in use. Insertion and lookup follow the same path, so they share one procedure.
MODULE probing;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteCard;
FROM Strings IMPORT Assign, Equal;
CONST
Size = 11;
TYPE
Key = ARRAY [0..15] OF CHAR;
Entry = RECORD
used: BOOLEAN;
key: Key;
value: CARDINAL
END;
VAR
table: ARRAY [0..Size - 1] OF Entry;
PROCEDURE Hash(key: ARRAY OF CHAR; size: CARDINAL): CARDINAL;
VAR
h, i: CARDINAL;
BEGIN
h := 0;
i := 0;
WHILE (i <= HIGH(key)) AND (key[i] # 0C) DO
h := (h * 31 + ORD(key[i])) MOD size;
INC(i)
END;
RETURN h
END Hash;
PROCEDURE Slot(key: ARRAY OF CHAR): CARDINAL;
VAR
i: CARDINAL;
BEGIN
i := Hash(key, Size);
WHILE table[i].used AND NOT Equal(table[i].key, key) DO
i := (i + 1) MOD Size
END;
RETURN i
END Slot;
PROCEDURE Put(key: ARRAY OF CHAR; value: CARDINAL);
VAR
i: CARDINAL;
BEGIN
i := Slot(key);
table[i].used := TRUE;
Assign(key, table[i].key);
table[i].value := value
END Put;
PROCEDURE Show(key: ARRAY OF CHAR);
VAR
i: CARDINAL;
BEGIN
i := Slot(key);
WriteString(key);
IF table[i].used THEN
WriteString(": "); WriteCard(table[i].value, 0);
WriteString(" in slot "); WriteCard(i, 0)
ELSE
WriteString(": not found, stopped at slot "); WriteCard(i, 0)
END;
WriteLn
END Show;
VAR
k: CARDINAL;
BEGIN
FOR k := 0 TO Size - 1 DO
table[k].used := FALSE
END;
Put("apple", 12); Put("pear", 7); Put("lime", 30);
Put("fig", 4); Put("apple", 15);
Show("apple"); Show("pear"); Show("lime");
Show("fig"); Show("kiwi")
END probing.
Slot starts at the hash of the key and moves to the next slot,
wrapping round at the end, until it finds the key or an unused slot.
Put stores the key and the value there; when the key already
exists, it only replaces the value, so the second apple
updates the first one. lime found slot 0 taken by
pear and went to slot 1. A lookup of a missing key stops at
the first unused slot. A table that is completely full would make
Slot loop forever; the next sections keep it from filling up.
$ gm2 -fiso probing.mod -o probing $ ./probing apple: 15 in slot 10 pear: 7 in slot 0 lime: 30 in slot 1 fig: 4 in slot 4 kiwi: not found, stopped at slot 3
Removing entries
An entry cannot simply be marked unused when it is removed: a lookup would stop at the hole and miss the keys that were placed after it. The slot gets a third state instead, a tombstone.
MODULE removal;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteCard;
FROM Strings IMPORT Assign, Equal;
CONST
Size = 11;
TYPE
State = (Empty, Used, Removed);
Key = ARRAY [0..15] OF CHAR;
Entry = RECORD
state: State;
key: Key
END;
VAR
table: ARRAY [0..Size - 1] OF Entry;
PROCEDURE Hash(key: ARRAY OF CHAR; size: CARDINAL): CARDINAL;
VAR
h, i: CARDINAL;
BEGIN
h := 0;
i := 0;
WHILE (i <= HIGH(key)) AND (key[i] # 0C) DO
h := (h * 31 + ORD(key[i])) MOD size;
INC(i)
END;
RETURN h
END Hash;
PROCEDURE Slot(key: ARRAY OF CHAR): CARDINAL;
VAR
i: CARDINAL;
BEGIN
i := Hash(key, Size);
WHILE (table[i].state = Removed) OR
(table[i].state = Used) AND NOT Equal(table[i].key, key) DO
i := (i + 1) MOD Size
END;
RETURN i
END Slot;
PROCEDURE Put(key: ARRAY OF CHAR);
VAR
i: CARDINAL;
BEGIN
i := Slot(key);
table[i].state := Used;
Assign(key, table[i].key)
END Put;
PROCEDURE Remove(key: ARRAY OF CHAR);
VAR
i: CARDINAL;
BEGIN
i := Slot(key);
IF table[i].state = Used THEN
table[i].state := Removed
END
END Remove;
PROCEDURE Dump;
VAR
i: CARDINAL;
BEGIN
FOR i := 0 TO Size - 1 DO
CASE table[i].state OF
Empty: WriteString(" .")
| Used: WriteString(" "); WriteString(table[i].key)
| Removed: WriteString(" x")
END
END;
WriteLn
END Dump;
VAR
k: CARDINAL;
BEGIN
FOR k := 0 TO Size - 1 DO
table[k].state := Empty
END;
Put("pear"); Put("lime"); Put("apple");
Dump;
Remove("pear");
Dump;
WriteString("lime is in slot "); WriteCard(Slot("lime"), 0); WriteLn;
Put("pear");
Dump
END removal.
The flag becomes an enumeration with three states. Slot walks
past removed slots as if they were in use, and stops only at an empty slot
or at the key. In its condition AND binds tighter than
OR, so the second line is one test. Dump shows a
dot for an empty slot and x for a tombstone. After
pear is removed, lime is still found in slot 1,
because the search does not stop at slot 0. Inserting pear
again puts it after lime: this Put never reuses a
tombstone, so tombstones accumulate until the table is rebuilt. A better
Put remembers the first tombstone on its path and stores the
key there.
$ gm2 -fiso removal.mod -o removal $ ./removal pear lime . . . . . . . . apple x lime . . . . . . . . apple lime is in slot 1 x lime pear . . . . . . . apple
The cost of a full table
The fuller the table, the longer the runs of occupied slots, and the more probes a search needs. The program fills a table of 1000 slots to various levels with random six-letter keys and measures the average number of probes.
MODULE load;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteCard;
FROM SRealIO IMPORT WriteFixed;
FROM Strings IMPORT Assign, Equal;
CONST
Size = 1000;
TYPE
Key = ARRAY [0..15] OF CHAR;
VAR
keys: ARRAY [0..Size - 1] OF Key;
seed: CARDINAL;
PROCEDURE Hash(key: ARRAY OF CHAR; size: CARDINAL): CARDINAL;
VAR
h, i: CARDINAL;
BEGIN
h := 0;
i := 0;
WHILE (i <= HIGH(key)) AND (key[i] # 0C) DO
h := (h * 31 + ORD(key[i])) MOD size;
INC(i)
END;
RETURN h
END Hash;
PROCEDURE Probes(key: ARRAY OF CHAR; add: BOOLEAN): CARDINAL;
VAR
i, n: CARDINAL;
BEGIN
i := Hash(key, Size);
n := 1;
WHILE (keys[i][0] # 0C) AND NOT Equal(keys[i], key) DO
i := (i + 1) MOD Size;
INC(n)
END;
IF add THEN
Assign(key, keys[i])
END;
RETURN n
END Probes;
PROCEDURE RandomKey(VAR key: Key);
VAR
i: CARDINAL;
BEGIN
FOR i := 0 TO 5 DO
seed := (seed * 75 + 74) MOD 65537;
key[i] := CHR(ORD('a') + seed MOD 26)
END;
key[6] := 0C
END RandomKey;
PROCEDURE Measure(percent: CARDINAL);
VAR
i, n, hit, miss: CARDINAL;
key: Key;
BEGIN
FOR i := 0 TO Size - 1 DO
keys[i] := ""
END;
n := Size * percent DIV 100;
seed := 1;
hit := 0;
miss := 0;
FOR i := 1 TO n DO
RandomKey(key);
INC(hit, Probes(key, TRUE))
END;
FOR i := 1 TO n DO
RandomKey(key);
INC(miss, Probes(key, FALSE))
END;
WriteCard(percent, 3); WriteString("%");
WriteFixed(FLOAT(hit) / FLOAT(n), 2, 8);
WriteFixed(FLOAT(miss) / FLOAT(n), 2, 9);
WriteLn
END Measure;
BEGIN
WriteString("load found missing"); WriteLn;
Measure(25); Measure(50); Measure(75);
Measure(90); Measure(99)
END load.
This table has no flags: an empty key marks a free slot. Without removal, a key is later found along the same path on which it was inserted, so the probes counted during insertion are the probes of a successful search. The missing keys are the next random keys, which are not in the table. Up to three quarters full, a search costs a few probes; beyond that, the runs of taken slots merge into long clusters, and a search for a missing key at 99% walks through hundreds of slots. The ratio of keys to slots is the load factor, and tables grow before it gets high.
$ gm2 -fiso load.mod -o load $ ./load load found missing 25% 1.19 1.58 50% 1.68 2.84 75% 2.50 7.14 90% 5.15 35.95 99% 11.47 240.25
A table module
The table moves into a module with an opaque type. A program may need several tables of different sizes, so the slots are allocated on the heap when the table is created.
DEFINITION MODULE Tables; TYPE Table; PROCEDURE Create(size: CARDINAL): Table; PROCEDURE Put(t: Table; key: ARRAY OF CHAR; value: CARDINAL); PROCEDURE Get(t: Table; key: ARRAY OF CHAR; VAR value: CARDINAL): BOOLEAN; PROCEDURE Count(t: Table): CARDINAL; PROCEDURE Size(t: Table): CARDINAL; PROCEDURE Destroy(VAR t: Table); END Tables.
Create takes the number of slots. Get returns
FALSE when the key is missing and the value otherwise.
IMPLEMENTATION MODULE Tables;
FROM Storage IMPORT ALLOCATE, DEALLOCATE;
FROM SYSTEM IMPORT TSIZE;
FROM Strings IMPORT Assign, Equal;
TYPE
Entry = RECORD
key: ARRAY [0..31] OF CHAR;
value: CARDINAL
END;
Slots = POINTER TO ARRAY [0..999999] OF Entry;
Table = POINTER TO RECORD
slots: Slots;
size, count: CARDINAL
END;
PROCEDURE Create(size: CARDINAL): Table;
VAR
t: Table;
i: CARDINAL;
BEGIN
NEW(t);
ALLOCATE(t^.slots, size * TSIZE(Entry));
FOR i := 0 TO size - 1 DO
t^.slots^[i].key := ""
END;
t^.size := size;
t^.count := 0;
RETURN t
END Create;
PROCEDURE Find(t: Table; key: ARRAY OF CHAR): CARDINAL;
VAR
h, i: CARDINAL;
BEGIN
h := 0;
i := 0;
WHILE (i <= HIGH(key)) AND (key[i] # 0C) DO
h := (h * 31 + ORD(key[i])) MOD t^.size;
INC(i)
END;
WHILE (t^.slots^[h].key[0] # 0C) AND NOT Equal(t^.slots^[h].key, key) DO
h := (h + 1) MOD t^.size
END;
RETURN h
END Find;
PROCEDURE Put(t: Table; key: ARRAY OF CHAR; value: CARDINAL);
VAR
i: CARDINAL;
BEGIN
i := Find(t, key);
IF t^.slots^[i].key[0] = 0C THEN
Assign(key, t^.slots^[i].key);
INC(t^.count)
END;
t^.slots^[i].value := value
END Put;
PROCEDURE Get(t: Table; key: ARRAY OF CHAR; VAR value: CARDINAL): BOOLEAN;
VAR
i: CARDINAL;
BEGIN
i := Find(t, key);
value := t^.slots^[i].value;
RETURN t^.slots^[i].key[0] # 0C
END Get;
PROCEDURE Count(t: Table): CARDINAL;
BEGIN
RETURN t^.count
END Count;
PROCEDURE Size(t: Table): CARDINAL;
BEGIN
RETURN t^.size
END Size;
PROCEDURE Destroy(VAR t: Table);
BEGIN
DEALLOCATE(t^.slots, t^.size * TSIZE(Entry));
DISPOSE(t)
END Destroy;
END Tables.
ISO Modula-2 has no array whose length is chosen at run time. The module
declares Slots as a pointer to a very large array type and
allocates only the first size elements with
ALLOCATE and TSIZE, as shown in the
pointers article; it never indexes past
size - 1. DEALLOCATE gets the same byte count.
Find combines the hash with the probing loop; an empty key
marks a free slot.
MODULE stock;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteCard;
FROM Tables IMPORT Table, Create, Put, Get, Count, Size, Destroy;
VAR
fruit: Table;
PROCEDURE Show(key: ARRAY OF CHAR);
VAR
n: CARDINAL;
BEGIN
WriteString(key);
IF Get(fruit, key, n) THEN
WriteString(": "); WriteCard(n, 0)
ELSE
WriteString(": none")
END;
WriteLn
END Show;
BEGIN
fruit := Create(11);
Put(fruit, "apple", 12); Put(fruit, "pear", 7);
Put(fruit, "lime", 30); Put(fruit, "apple", 15);
Show("apple"); Show("lime"); Show("kiwi");
WriteCard(Count(fruit), 0); WriteString(" keys in ");
WriteCard(Size(fruit), 0); WriteString(" slots");
WriteLn;
Destroy(fruit)
END stock.
The client does not see entries or slots, only keys and values. This
version still has a fixed number of slots, given to Create.
$ gm2 -fiso -c Tables.mod $ gm2 -fiso stock.mod Tables.o -o stock $ ./stock apple: 15 lime: 30 kiwi: none 3 keys in 11 slots
Growing the table
When the table gets three quarters full, it allocates twice as many slots
and moves every entry over. The definition module stays the same; only
Put changes and a new Grow procedure appears in
the implementation module.
PROCEDURE Grow(t: Table);
VAR
old: Slots;
oldSize, i, j: CARDINAL;
BEGIN
old := t^.slots;
oldSize := t^.size;
t^.size := 2 * oldSize;
ALLOCATE(t^.slots, t^.size * TSIZE(Entry));
FOR i := 0 TO t^.size - 1 DO
t^.slots^[i].key := ""
END;
FOR i := 0 TO oldSize - 1 DO
IF old^[i].key[0] # 0C THEN
j := Find(t, old^[i].key);
t^.slots^[j] := old^[i]
END
END;
DEALLOCATE(old, oldSize * TSIZE(Entry))
END Grow;
PROCEDURE Put(t: Table; key: ARRAY OF CHAR; value: CARDINAL);
VAR
i: CARDINAL;
BEGIN
IF 4 * (t^.count + 1) > 3 * t^.size THEN
Grow(t)
END;
i := Find(t, key);
IF t^.slots^[i].key[0] = 0C THEN
Assign(key, t^.slots^[i].key);
INC(t^.count)
END;
t^.slots^[i].value := value
END Put;
The listing shows only the two procedures; the rest of
Tables.mod is unchanged. Put checks the load
factor before it inserts, in integers: 4 × (count + 1) > 3
× size. Grow keeps the old slots, allocates the
new ones and inserts every used entry again. The entries cannot be copied
to the same index, because Find reduces the hash by the new
size and most keys get a different slot; this is called
rehashing. Rehashing also drops tombstones, if the table has
them.
MODULE growth;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteCard;
FROM WholeStr IMPORT CardToStr;
FROM Tables IMPORT Table, Create, Put, Get, Count, Size, Destroy;
VAR
squares: Table;
key: ARRAY [0..15] OF CHAR;
i, size, value: CARDINAL;
BEGIN
squares := Create(4);
size := Size(squares);
FOR i := 1 TO 1000 DO
CardToStr(i, key);
Put(squares, key, i * i);
IF Size(squares) # size THEN
size := Size(squares);
WriteCard(Count(squares), 5); WriteString(" keys, ");
WriteCard(size, 0); WriteString(" slots");
WriteLn
END
END;
IF Get(squares, "999", value) THEN
WriteString("999 -> "); WriteCard(value, 0); WriteLn
END;
Destroy(squares)
END growth.
The client puts a thousand keys, the numbers converted to strings with
WholeStr.CardToStr, into a table that starts with four slots,
and prints a line whenever the number of slots changes. Each growth costs
one pass over all entries, but it happens after the number of keys doubles,
so on average every Put pays only a small constant share of
it.
$ gm2 -fiso -c Tables.mod
$ gm2 -fiso growth.mod Tables.o -o growth
$ ./growth
4 keys, 8 slots
7 keys, 16 slots
13 keys, 32 slots
25 keys, 64 slots
49 keys, 128 slots
97 keys, 256 slots
193 keys, 512 slots
385 keys, 1024 slots
769 keys, 2048 slots
999 -> 998001
Counting words
A classic use of a hash table is counting how often each word occurs in a text. The word is the key, and the count is the value.
MODULE frequency;
FROM STextIO IMPORT WriteString, WriteLn, ReadToken, SkipLine;
FROM SWholeIO IMPORT WriteCard;
FROM SIOResult IMPORT ReadResult, ReadResults;
FROM Tables IMPORT Table, Create, Put, Get, Count, Destroy;
TYPE
Word = ARRAY [0..31] OF CHAR;
PROCEDURE Clean(VAR s: Word);
VAR
i, j: CARDINAL;
ch: CHAR;
BEGIN
i := 0;
j := 0;
WHILE (i <= HIGH(s)) AND (s[i] # 0C) DO
ch := s[i];
IF (ch >= 'A') AND (ch <= 'Z') THEN
ch := CHR(ORD(ch) - ORD('A') + ORD('a'))
END;
IF (ch >= 'a') AND (ch <= 'z') THEN
s[j] := ch;
INC(j)
END;
INC(i)
END;
IF j <= HIGH(s) THEN
s[j] := 0C
END
END Clean;
VAR
words: Table;
word: Word;
res: ReadResults;
n, total: CARDINAL;
PROCEDURE Show(key: ARRAY OF CHAR);
BEGIN
IF NOT Get(words, key, n) THEN
n := 0
END;
WriteString(key); WriteString(": "); WriteCard(n, 0); WriteLn
END Show;
BEGIN
words := Create(8);
total := 0;
LOOP
ReadToken(word);
res := ReadResult();
Clean(word);
IF word[0] # 0C THEN
IF NOT Get(words, word, n) THEN
n := 0
END;
Put(words, word, n + 1);
INC(total)
END;
IF res = endOfInput THEN
EXIT
ELSIF res = endOfLine THEN
SkipLine
END
END;
WriteCard(total, 0); WriteString(" words, ");
WriteCard(Count(words), 0); WriteString(" different");
WriteLn;
Show("the"); Show("module"); Show("language"); Show("pascal");
Show("c");
Destroy(words)
END frequency.
The program reads whitespace-separated tokens as in the
reading input article.
Clean lower-cases each token and drops everything that is not
a letter, so The, the and module:
become the, the and module. For each
word the program gets the old count, 0 for a new word, and puts back the
count plus one. The table starts with eight slots and grows as the words
arrive. The text is a short paragraph about the history of Modula-2.
$ gm2 -fiso frequency.mod Tables.o -o frequency $ ./frequency < wirth.txt 108 words, 68 different the: 14 module: 4 language: 4 pascal: 1 c: 0
Choosing a structure
A hash table finds, inserts and updates a key in a constant number of probes on average, which beats both binary search in a sorted array and a search tree. In return it keeps the keys in no useful order, needs a good hash function, and wastes some of its slots to keep the load factor low. When the keys must come out sorted, or when the largest and smallest key matter, a tree or a sorted array is the better choice. Another common design, separate chaining, keeps a linked list of entries in each slot instead of probing; it tolerates a higher load factor and makes removal simple.
Source
Niklaus Wirth: Algorithms and Data Structures
In this article we have hashed strings into slots, inserted and found keys with linear probing, removed entries with tombstones, measured the cost of a full table, wrapped the table in a module with an opaque type and heap slots, grown it by rehashing, and counted the words of a text. The searching article covers linear and binary search, and the stacks, queues and trees article builds a binary search tree.
Author
List all Modula-2 tutorials.