Sub topic 4
A persistent linked list
This chapter assumes you can read basic Python, know how a singly linked list works, and understand the difference between two names pointing at one object and two separate copies. It builds on the previous chapter's idea of structural sharing and applies it to the simplest structure that supports it.
Why a linked list works so well
A singly linked list is a chain of nodes. Each node holds a value (the head) and a reference to the rest of the chain (the tail). The key property is that a node never needs to know who points at it. If nodes are immutable, many lists can point into the same chain.
Prepending to such a list does not touch any existing node. You allocate one new node whose tail is the old list. The old list is still valid, and the new list reuses all of it.
from typing import NamedTuple, Optional
class Node(NamedTuple):
head: int
tail: Optional["Node"]
xs = Node(2, Node(3, None))
ys = Node(1, xs) # new version: prepend 1
zs = Node(0, xs) # another version: prepend 0
assert ys.tail is xs
assert zs.tail is xs
assert ys.tail is zs.tail # both versions share the same tail nodesNamedTuple instances are immutable, so no code can change xs after the fact. That guarantee is what makes sharing safe.
The diagram shows three lists stored in four nodes. Copying each list would need seven nodes.
Costs of the basic operations
| Operation | Time | New nodes |
|---|---|---|
| Prepend | O(1) | 1 |
| Read the head | O(1) | 0 |
| Take the tail (remove the first item) | O(1) | 0 |
| Read item at index i | O(i) | 0 |
| Replace item at index i | O(i) | i + 1 |
| Append to the end | O(n) | n + 1 |
Taking the tail is free because the tail already exists as a node. Operations at the front are cheap, while operations deep in the list or at the far end are not.
Changing something in the middle
To change item i, you must rebuild every node before it, because each of those nodes has to point at a new tail. Nodes after position i stay shared. This is the first appearance of path copying, which the next chapter develops: copy the route to the change and reuse everything else.
from typing import NamedTuple, Optional
class Node(NamedTuple):
head: int
tail: Optional["Node"]
def from_iter(items):
result = None
for x in reversed(list(items)):
result = Node(x, result)
return result
def to_list(node):
out = []
while node is not None:
out.append(node.head)
node = node.tail
return out
def set_at(node, i, value):
if node is None:
raise IndexError(i)
if i == 0:
return Node(value, node.tail)
return Node(node.head, set_at(node.tail, i - 1, value))
xs = from_iter([1, 2, 3, 4])
ys = set_at(xs, 2, 99)
assert to_list(xs) == [1, 2, 3, 4] # old version unchanged
assert to_list(ys) == [1, 2, 99, 4]
assert ys.tail.tail.tail is xs.tail.tail.tail # the suffix after index 2 is shared
assert ys.tail is not xs.tail # the prefix was copiedThe function is recursive, so a very long list can hit Python's recursion limit. A loop that collects the prefix and rebuilds it avoids that.
Common errors
- Appending in a loop. Each append copies the whole list, so building a list of n items this way costs O(n²). Prepend while looping, then reverse once.
- Assuming indexing is cheap. A linked list gives O(i) access, unlike an array. Persistent vectors, covered later, fix this.
- Testing sharing with
==. Equality compares contents. Useisto check that two versions really reuse the same node. - Expecting memory to be freed immediately. An old version's nodes stay alive while any other version still references them.
Exercise
Given xs = fromiter([1, 2, 3, 4]) and ys = setat(xs, 1, 50), how many new nodes does set_at allocate, and which nodes of xs does ys reuse?
Show answer
It allocates 2 new nodes: one for the copied prefix item 1 and one for the replacement value 50. The suffix starting at the node holding 3 is reused, so ys shares nodes 3 and 4 with xs. The first two nodes of xs are not reused.