Sub topic 7
Persistent vectors with wide tries
This chapter assumes you know path copying, from the persistent binary search tree chapter, and Big-O notation. You should also be comfortable with bitwise shifts and masks in Python.
The problem with a tree of two
A persistent binary tree can serve as an array, but a balanced one with a million elements is about 20 levels deep. Each update copies about 20 nodes, and each lookup follows 20 pointers. A persistent vector keeps path copying and makes the tree much shallower by making it much wider.
A trie keyed by index bits
A vector's keys are the integers 0 to n-1. Instead of comparing keys, the structure reads the index in 5-bit slices. Each slice picks one of 32 children. Elements live only in the leaves, and each leaf holds up to 32 of them.
To find index 35, take the top slice, (35 >> 5) & 31 = 1. That selects the second leaf. Then take the low slice, 35 & 31 = 3, which selects the fourth slot of that leaf.
BITS = 5
MASK = 0b11111 # 32-way branching
def lookup(root, shift, i):
node = root
while shift > 0:
node = node[(i >> shift) & MASK]
shift -= BITS
return node[i & MASK]
leaf0 = list(range(0, 32))
leaf1 = list(range(32, 40))
root = [leaf0, leaf1] # one internal level above the leaves
assert lookup(root, BITS, 35) == 35
assert lookup(root, BITS, 7) == 7The shift value records how many bits remain to consume at the current level. It starts at BITS * (levels - 1) and drops by 5 on each step.
Why this is shallow
Each level multiplies capacity by 32. Depth is ceil(log32 n):
| Elements | Levels |
|---|---|
| 32 | 1 |
| 1,024 | 2 |
| 32,768 | 3 |
| about 1 million | 4 |
| about 1 billion | 6 |
Lookups and updates are O(log32 n). That is formally logarithmic, but for any realistic size it behaves like a small constant, so documentation often calls it "effectively O(1)".
Updating by path copying
An update copies one node per level, which is at most 6 nodes of 32 slots each. Every other subtree is shared with the old version.
def assoc(node, shift, i, value):
copy = list(node) # copy this node only
if shift == 0:
copy[i & MASK] = value
else:
idx = (i >> shift) & MASK
copy[idx] = assoc(node[idx], shift - BITS, i, value)
return copy
new_root = assoc(root, BITS, 35, -1)
assert lookup(new_root, BITS, 35) == -1
assert lookup(root, BITS, 35) == 35 # old version unchanged
assert new_root[0] is root[0] # untouched leaf is shared
assert new_root[1] is not root[1] # leaf on the path is copiedThe old and new roots are two versions of the same vector, and they share leaf 0.
Appending and the tail
Real implementations also support append and pop at the end in near-constant time. Appending fills the next free leaf slot. If the leaf is full, the vector allocates a new leaf. If the root is full, it adds a new level above it.
Clojure and similar libraries keep the last partial leaf outside the trie, in a separate array called the tail. Most appends then copy only a small array and do not walk the tree at all. The tree is touched only once every 32 appends.
Common errors
- Mutating a shared node. If
assocwrote intonodeinstead ofcopy, the old version would change too. Every node on the update path must be copied. - Forgetting the shift. After a root split, the root's
shiftgrows by 5. A lookup that uses the old shift reads the wrong slots. - Expecting cheap inserts in the middle. Inserting at index k shifts every later element, which breaks the index-to-path mapping. Persistent vectors give fast read, update, append and pop, but not arbitrary insertion. Relaxed radix balanced trees (RRB trees) address that, at extra cost.
Exercise
A persistent vector with 32-way nodes holds 100,000 elements. How many levels does it need, and roughly how many nodes does one assoc copy?
Show answer
32^3 = 32,768 is too small and 32^4 = 1,048,576 is enough, so it needs 4 levels. One update copies one node per level, so about 4 nodes of 32 slots each. The rest of the tree is shared with the old version.