Skip to content
Part IA Michaelmas Term

Dictionaries and Association Lists

Dictionary operations

A dictionary (or map) associates keys with values. The core operations are:

OperationDescription
lookupFind the value associated with a key
updateInsert or replace a key-value pair
deleteRemove a key-value pair
emptyThe dictionary containing no entries
MissingException raised when a key is not found

An abstract type would hide the internal representation behind these operations. This course does not cover OCaml’s module system, so operations are declared individually.

Association list

The simplest representation is an association list: a list of (key, value) pairs.

lookup

Linear search through the list:

exception Missing

let rec lookup a = function
  | [] -> raise Missing
  | (x, y) :: pairs ->
      if a = x then y
      else lookup a pairs

O(n) time, where n is the number of entries.

update

Simply cons the new pair onto the front:

let update (l, b, y) = (b, y) :: l

O(1) time, which is optimal.

Limitations

AspectBehaviour
Lookup speedO(n) — slow for large dictionaries
Update speedO(1) — fast
Space usageGrows with number of updates, not number of distinct keys
Ordering required?No — only equality on keys

The space problem is significant: obsolete entries accumulate and are never removed. Deleting an entry would require finding it first, which would increase update from O(1) to O(n). Association lists are acceptable only when there are few keys in use, or when fast updates matter more than fast lookups.