Chapter 7The pointer machine
The root-access model of Chapter 3 lets an access rotate anywhere in the tree and charges only for rotations. The standard BST model of the literature (Wilber 1989; Demaine et al. 2009) is more operational. A single pointer starts at the root for each request. It moves along edges and rotates the node it points to over its parent. Every move and every rotation costs one unit, and the pointer must visit the requested key. This chapter defines that machine in Lean and proves that the two models agree up to constant factors in total cost, offline for executions and online for algorithms.
Total cost means requests plus rotations () in the rotation model, and requests plus pointer instructions () on the pointer machine. Let be a sequence of requests and a tree.
- Pointers to rotations. If the pointer machine serves from at total cost , ending in tree , then some root-access execution serves from with rotations and ends rotations away from , where .
- Rotations to pointers. If a root-access execution serves from with rotations, ending in tree , then the pointer machine serves from at total cost , ending rotations away from , where .
The constants do not depend on the size of the tree. In both directions the final trees may differ, by a number of rotations that the bound pays for.
In Lean, rotation-model executions are Execution, pointer executions are Pointer.Execution, and Rotations u t q says that q rotations turn u into t.
The Lean statements
/-- Conventional searches become root accesses with at most factor three intotal cost. Final pending rotations are retained and charged explicitly. -/theorem to_rotations (h : Pointer.Execution s xs t k) : ∃ u r q, RotationBST.Execution s xs u r ∧ Rotations u t q ∧ xs.length + r + q ≤ 3 * k := … Pointer.execution_to_rotations h/-- Lazy simulation has constant overhead, independent of tree size. Its finalpending rotations are explicitly retained and charged. -/theorem to_pointer_lazy (h : RotationBST.Execution s xs t k) : ∃ u c d, Pointer.Execution s xs u c ∧ Rotations u t d ∧ c + 32 * d ≤ 32 * k + 17 * xs.length := … Lazy.execution_to_pointer hThe definitions are in Models/Pointer/Machine/Abstract.lean and the simulation theorems in Models/Pointer/Abstract.lean. The later sections walk through the readable interface of the constant-factor (“lazy”) simulation, and then run it online. The last section collects facts about cursors and regions that later chapters use.
7.1 Configurations
The machine state is a zipper: the subtree under the cursor, plus the path back to the root. Each step of that path is recorded by a frame.
/-- The other child of an ancestor, together with the side containing the cursor. -/inductive Frame where | left (right : Tree) | right (left : Tree) deriving DecidableEq, ReprA frame describes one ancestor of the cursor. left right means the cursor is in the left subtree of this ancestor, whose other child is right. right left is the mirror case. The ancestor itself stores nothing more, because shapes have no keys. The constructor name says which side the cursor is on, and its argument is the sibling subtree. So Frame.left stores a right subtree, which is easy to misread.
/-- Reassemble the whole tree from a focused subtree and its ancestors. -/def plug : List Frame → Tree → Tree | [], t => t | .left r :: cs, t => plug cs (.node t r) | .right l :: cs, t => plug cs (.node l t)/-- Number of keys before the focused subtree in the whole inorder traversal. -/def offset : List Frame → Nat | [] => 0 | .left _ :: cs => offset cs | .right l :: cs => offset cs + l.size + 1plug cs t rebuilds the whole tree from the focused subtree t and the frames cs, nearest ancestor first, wrapping t one ancestor at a time. offset cs counts the keys that precede the focused subtree in inorder. A left frame adds nothing, since the cursor is to the left of everything in that ancestor’s other subtree. A right l frame adds the l.size keys of the left sibling plus 1 for the ancestor itself.
structure Config where focus : Tree context : List Frame deriving DecidableEq, Reprdef Config.tree (c : Config) : Tree := plug c.context c.focusdef Config.key? (c : Config) : Option Nat := match c.focus with | .nil => none | .node l _ => some (offset c.context + l.size)A configuration pairs the focus with its context. Config.tree is the whole tree it represents. Config.key? is the rank of the node under the cursor: offset plus the size of the focus’s left subtree, which is the same offset arithmetic as in Chapter 1. It is none when the focus is empty. The initial configuration for a request on tree s is ⟨s, []⟩: the cursor is on the root and the context is empty.
7.2 Instructions
/-- Move to a neighboring node, or rotate the pointed node over its parent.A rotation keeps the cursor on that same node. -/inductive Step : Config → Config → Prop where | downLeft {a b r : Tree} {cs : List Frame} : Step ⟨.node (.node a b) r, cs⟩ ⟨.node a b, .left r :: cs⟩ | downRight {l a b : Tree} {cs : List Frame} : Step ⟨.node l (.node a b), cs⟩ ⟨.node a b, .right l :: cs⟩ | upLeft {a b r : Tree} {cs : List Frame} : Step ⟨.node a b, .left r :: cs⟩ ⟨.node (.node a b) r, cs⟩ | upRight {a b l : Tree} {cs : List Frame} : Step ⟨.node a b, .right l :: cs⟩ ⟨.node l (.node a b), cs⟩ | rotateLeftChild {a b r : Tree} {cs : List Frame} : Step ⟨.node a b, .left r :: cs⟩ ⟨.node a (.node b r), cs⟩ | rotateRightChild {a b l : Tree} {cs : List Frame} : Step ⟨.node a b, .right l :: cs⟩ ⟨.node (.node l a) b, cs⟩The six instructions, each matched on the shape of the configuration:
downLeft,downRightmove to a child. The pattern.node (.node a b) rrequires the left child to be a real node, so the cursor never moves ontonil. This is the docstring’s promise that the cursor always points to an actual node when an instruction is taken.upLeft,upRightmove to the parent, popping one frame and rebuilding the parent around the focus.rotateLeftChildapplies when the cursor is a left child (top frame.left r). It rotates the cursor’s node over its parent, soxwith childrena, bunder a parent whose right subtree isrbecomesxwith childrenaand(b r). The cursor stays onx, which is now one level higher, so one frame is consumed. On the whole tree this is aRotate.rightinside the context.rotateRightChildis the mirror image and corresponds toRotate.left.
There is no instruction that rotates a node the cursor is not on, and there is no “jump”. Each instruction costs one unit, and traces record the exact count:
/-- Exactly `k` charged instructions. -/inductive Trace : Config → Config → Nat → Prop where | refl {c : Config} : Trace c c 0 | step {a b c : Config} {k : Nat} : Step a b → Trace b c k → Trace a c (k + 1)A computation inside a subtree can be replayed from higher up. Config.under adds extra frames below the context, so the same focus sits deeper in a larger tree:
/-- The same configuration below extra context frames: a computation inside asubtree, viewed from an ancestor. -/def Config.under (c : Config) (ds : List Frame) : Config := ⟨c.focus, c.context ++ ds⟩Every instruction only looks at the focus and the nearest frame, so a trace in a subtree is also a trace, with the same count, under any extra context. The library proves this as Trace.under; the lazy simulations below use it to run a request inside a region and lift the cost unchanged.
7.3 Serving a request
/-- A search visits `x`, possibly continues working, and finishes with tree `t`.The extra unit accounts for the request itself. The final cursor is unrestricted;the next request starts again at the root. -/def Serves (s t : Tree) (x cost : Nat) : Prop := ∃ visited finish before after, Trace ⟨s, []⟩ visited before ∧ visited.key? = some x ∧ Trace visited finish after ∧ finish.tree = t ∧ cost = 1 + before + afterServes s t x cost says that a search for x on tree s can end with tree t at the given cost. Concretely, there are configurations visited and finish and step counts before and after such that:
- a trace of
beforeinstructions goes from the root configuration⟨s, []⟩tovisited, - the cursor of
visitedis on rankx(visited.key? = some x), - a further trace of
afterinstructions goes fromvisitedtofinish, finishrepresentst, wherever its cursor is, andcost = 1 + before + after: one unit for the request plus every instruction.
The search may restructure both before and after reaching x, and need not end at x or at the root. Returning the cursor to the root is free, since the next request starts again at ⟨t, []⟩; this is the usual convention. The extra unit means that a request for the root, served with no instructions, still costs .
/-- A sequence of conventional searches with total instruction-and-request cost. -/inductive Execution : Tree → List Nat → Tree → Nat → Prop where | nil {t : Tree} : Execution t [] t 0 | cons {s t : Tree} {x k : Nat} {xs : List Nat} {u : Tree} {m : Nat} : Serves s t x k → Execution t xs u m → Execution s (x :: xs) u (k + m)A pointer execution serves the requests in order, each starting from the previous search’s final tree, and adds up the costs. Its structure is the same as Execution, with Serves in place of Access.
Each button is one Pointer.Step constructor, enabled exactly when its pattern matches. Walk to the orange key; the panel reports when the visit condition holds and computes 1 + before + after. You may keep rotating afterwards; “Finish request” then plugs the configuration back into a tree and starts the next search at its root.
Servesexistentially quantifies the visit, so it describes all legal searches. An algorithm in this model is any way of choosing them.- In the classical model the pointer may also be “reset” between accesses at no cost. Here the reset is implicit, because each
Servesstarts at⟨s, []⟩. - The cost of moving and the cost of rotating are the same. Rotation-only costs, as in Chapter 3, are not this model.
7.4 The two models agree
The comparison uses total cost on both sides: requests plus rotations () in the rotation model, and requests plus instructions in the pointer model. Executions are related directly, and each direction keeps an explicit, charged suffix of rotations at the end.
7.4.1 From pointers to rotations
Theorem (pointers to rotations). A pointer execution of total cost from s to t gives a root-access execution from s to some u with rotations, plus further rotations from u to t, with .
/-- Conventional searches become root accesses with at most factor three intotal cost. Final pending rotations are retained and charged explicitly. -/theorem to_rotations (h : Pointer.Execution s xs t k) : ∃ u r q, RotationBST.Execution s xs u r ∧ Rotations u t q ∧ xs.length + r + q ≤ 3 * k := Pointer.execution_to_rotations hThe proof treats each search separately. Moves cost nothing in the rotation model, and the rotations performed before the visit are kept. At the visit, the cursor is at some depth before, since each instruction changes the depth by at most one. Rotating x over its ancestors puts it at the root, which completes a root access. Undoing those rotations and then replaying the search’s remaining rotations yields t. These (rotations after the visit) form the suffix, which is prepended to the next access, so the rotation execution can continue from the pointer execution’s tree. Per search, the rotation cost is at most , which with the request unit is at most . Only the last search’s suffix remains pending at the end. That is the Rotations u t q conjunct, and its cost is included in the bound.
7.4.2 From rotations to pointers, exactly
Theorem (exact simulation). Every root-access execution from s with rotations has a pointer execution from s with the same final tree and total cost at most , where = s.size.
/-- Eager simulation preserves the exact final shape. Navigating to arbitrarydeep rotations incurs the displayed tree-size factor. -/theorem to_pointer (h : RotationBST.Execution s xs t k) : ∃ m, m ≤ xs.length + 2 * s.size * k ∧ Pointer.Execution s xs t m := Pointer.execution_to_pointer hEach rotation is simulated separately: walk from the root to the rotated node’s parent, step to the child, rotate, and walk back. A rotation at depth costs instructions. After all of an access’s rotations the requested key is at the root, where the cursor already is, so the visit is free. The factor is necessary for this naive simulation, because the rotation model charges a deep rotation the same as a shallow one. This is why the following theorem is needed.
7.4.3 From rotations to pointers, lazily
Theorem (lazy simulation). A root-access execution from s to t with rotations and requests has a pointer execution from s of total cost ending at some u, and deferred rotations take u to t, with
$$
/-- Lazy simulation has constant overhead, independent of tree size. Its finalpending rotations are explicitly retained and charged. -/theorem to_pointer_lazy (h : RotationBST.Execution s xs t k) : ∃ u c d, Pointer.Execution s xs u c ∧ Rotations u t d ∧ c + 32 * d ≤ 32 * k + 17 * xs.length := Lazy.execution_to_pointer hThe bound does not depend on tree size. Since , the pointer cost satisfies . Together with to_rotations, this makes the total costs of the two models equivalent within constant factors, for every execution and every tree.
The lazy simulation does not end in the same tree. Rotations that the rotation model performs far from the current request are postponed until a later request needs them. Those still pending after the last request form the suffix Rotations u t d. They are not dropped: they are paid for in the bound with weight , the same as executed rotations. They are simply not executed by the pointer machine. If you need the exact final tree, use to_pointer, which pays the factor . The README states the same trade-off.
7.5 Inside the lazy simulation
The proof of to_pointer_lazy is too long to explain here, but its components are exposed through readable statements in Models/Pointer/Lazy/Abstract.lean and the definition files under Models/Pointer/Lazy/. Those statements are not used by the headline theorem’s statement. They are shown so that a reader can follow the argument and check its key lemmas.
7.5.1 Rotations with named endpoints
To reason about which rotations interact, the proof works on labelled trees and records each rotation by the keys of its two endpoints.
/-- `RotateAt x y` promotes key `x` over its parent `y`. -/inductive RotateAt {α : Type} : α → α → LabelledTree α → LabelledTree α → Prop where | right {a b c : LabelledTree α} {x y : α} : RotateAt x y (.node (.node a x b) y c) (.node a x (.node b y c)) | left {a b c : LabelledTree α} {x y : α} : RotateAt x y (.node a y (.node b x c)) (.node (.node a y b) x c) | inLeft {a b c : LabelledTree α} {x y z : α} : RotateAt x y a b → RotateAt x y (.node a z c) (.node b z c) | inRight {a b c : LabelledTree α} {x y z : α} : RotateAt x y a b → RotateAt x y (.node c z a) (.node c z b)RotateAt x y s t is a labelled rotation that promotes key x over its parent y. In right, x is the left child of y; in left, it is the right child. inLeft and inRight place the rotation inside a subtree whose root key z is arbitrary. Forgetting the endpoint labels gives back LabelledTree.Rotate.
/-- A rotation program records the two endpoint keys of every instruction. -/inductive Trace {α : Type} : LabelledTree α → List (α × α) → LabelledTree α → Prop where | nil {t : LabelledTree α} : Trace t [] t | cons {x y : α} {s t u : LabelledTree α} {ops : List (α × α)} : RotateAt x y s t → Trace t ops u → Trace s ((x, y) :: ops) u/-- The explicit key at a labelled tree's root. -/def rootKey? {α : Type} : LabelledTree α → Option α | .nil => none | .node _ x _ => some xA Trace is a rotation sequence together with its program: the list of endpoint pairs (x, y), in order. rootKey? reads the root label.
Theorem (exchange). If a rotation of x over y turns s into t, and a rotation of u over v turns t into z, and the four endpoints are distinct, then the two rotations can be performed in the opposite order: rotating u over v and then x over y also turns s into z.
theorem commute (first : RotateAt x y s t) (second : RotateAt u v t z) (disjoint : DisjointPairs x y u v) : ∃ q, RotateAt u v s q ∧ RotateAt x y q z := Lazy.commute first second disjointModels.Rotation, Models.Pointer.Machine, Models.Pointer.Lazy.Rotations, Models.Pointer.Lazy.SkeletonThis holds even when one rotation is inside a subtree moved by the other: rotations are identified by their endpoint keys, not by tree positions, so they still make sense after the exchange. The hypothesis says that no endpoint of the first rotation is an endpoint of the second:
/-- The two rotations have no endpoint key in common. -/def DisjointPairs {α : Type} (x y u v : α) : Prop := x ≠ u ∧ x ≠ v ∧ y ≠ u ∧ y ≠ v7.5.2 Postponing independent rotations
Repeated exchanges sort a program by any colouring of keys in which every rotation has both endpoints of the same colour.
Theorem (postponing). Colour the keys so that both endpoints of every rotation of a program have the same colour, and suppose the program ends with a selected key x at the root. Then the selected rotations alone, in their original order, form an access to x, and the unselected rotations, run afterwards, reach the same final tree.
/-- Independent rotations outside the requested key's color can be postponed.The prefix still serves the request; the suffix restores the exact final tree. -/theorem postpone_access (color : α → Bool) (ops : List (α × α)) (program : Trace s ops t) (uniform : ∀ e ∈ ops, color e.1 = color e.2) (root : rootKey? t = some x) (selected : color x = true) : ∃ q, LabelledTree.Access s q x (ops.filter fun e => color e.1).length ∧ Trace q (ops.filter fun e => !(color e.1)) t ∧ (ops.filter fun e => color e.1).length + (ops.filter fun e => !(color e.1)).length = ops.length := Lazy.postpone_access color program uniform root selectedModels.Rotation, Models.Pointer.Machine, Models.Pointer.Lazy.Rotations, Models.Pointer.Lazy.SkeletonIn Lean: colour the keys with color : α → Bool so that every rotation of the program ops has equally coloured endpoints (uniform). Suppose the program ends with x at the root and x is selected (color x = true). Then the selected rotations alone, in their original order, already form a labelled access to x, and the unselected ones, run afterwards, reach the same final tree. The two counts add up to ops.length, so nothing is added or lost. Unselected rotations never touch the selected root’s key, so they can be postponed past the access.
The proof uses a particular colouring, the connected component of the initial root in the rotation graph, whose edges are the endpoint pairs of the program:
/-- Connectivity in the graph whose edges are the endpoint pairs of a program. -/inductive Connected {α : Type} (ops : List (α × α)) : α → α → Prop where | refl {x : α} : Connected ops x x | edge {x y : α} : (x, y) ∈ ops → Connected ops x y | symm {x y : α} : Connected ops x y → Connected ops y x | trans {x y z : α} : Connected ops x y → Connected ops y z → Connected ops x z/-- Endpoint occurrences, retaining duplicates so its length is exactly twice the program length. -/def endpointSupport {α : Type} (ops : List (α × α)) : List α := ops.flatMap fun e => [e.1, e.2]/-- Keys in the monochromatic component touching the root, in inorder.A root of the other color gives the empty component. -/def componentKeys {α : Type} (color : α → Bool) (wanted : Bool) : LabelledTree α → List α | .nil => [] | .node l x r => if color x = wanted then componentKeys color wanted l ++ x :: componentKeys color wanted r else []Connected ops is the equivalence relation generated by the pairs in ops: reflexive, symmetric and transitive closure of the edges. endpointSupport ops lists both endpoints of every rotation, keeping duplicates, so its length is exactly 2 * ops.length. componentKeys color wanted t lists, in inorder, the keys of the maximal region of colour wanted that contains the root of t and is connected in the tree. If the root has the other colour, the region is empty.
Colouring keys by “connected to the initial root in the rotation graph” makes every rotation uniform, because both endpoints of a rotation are connected to each other. In the proof (Models/Pointer/Lazy/RootComponent.lean), distinctness of keys then gives two facts. First, the selected keys form a connected region at the top of the initial tree. Second, that region contains at most keys, where is the number of selected rotations: the root, plus at most two endpoints per rotation. This is where endpointSupport comes in.
7.5.3 Reshaping a connected region
The selected rotations only rearrange this top region. Every subtree hanging off it is moved as a block and never entered. The proof captures such a region as a skeleton:
/-- A connected region of a tree. A hole holds an entire untouched fringe subtree;only `node` constructors count toward the size of the region. -/inductive Skeleton where | hole (tree : Tree) | node (left right : Skeleton)def tree : Skeleton → Tree | .hole t => t | .node l r => .node l.tree r.treedef size : Skeleton → Nat | .hole _ => 0 | .node l r => l.size + 1 + r.sizedef fringe : Skeleton → List Tree | .hole t => [t] | .node l r => l.fringe ++ r.fringe/-- The canonical right vine with these fringe subtrees in inorder. -/def vine : List Tree → Tree | [] => .nil | [t] => t | t :: u :: ts => .node t (vine (u :: ts))A skeleton is a tree whose leaves are holes, each holding an entire untouched Tree. The same type reappears in Chapter 8 as the rooted region touched by one request, the unit of cost in the region model. tree fills the holes in. size counts only the region’s own nodes, so a hole contributes however large its subtree is. fringe lists the hole subtrees in inorder; a region with nodes has of them. vine builds the canonical right spine whose left children are the fringe subtrees, in order, with the last one at the bottom on the right.
Theorem (reshaping). Two regions with the same fringe, in the same order, can be transformed into one another by a pointer trace from root to root with at most instructions, where is the number of nodes in the first region.
/-- Reshape a connected active region without entering its fringe subtrees. -/theorem reshape (s t : Skeleton) (same : s.fringe = t.fringe) : ∃ k, k ≤ 16 * s.size ∧ Pointer.Trace ⟨s.tree, []⟩ ⟨t.tree, []⟩ k := Skeleton.reshape s t sameModels.Rotation, Models.Pointer.Machine, Models.Pointer.Lazy.Rotations, Models.Pointer.Lazy.SkeletonThe bound does not depend on the sizes of the fringe subtrees. The proof flattens both regions into the common vine, using at most instructions each, and runs the second flattening backwards. Reversing a pointer trace costs at most three instructions per instruction, since undoing a rotation requires stepping to the demoted node. In total this is .
A whole tree is a region whose holes are all empty, so any two shapes of the same size are a cheap pointer trace apart.
Theorem (reshaping a whole tree). If s and t have the same size, a pointer trace of at most instructions turns s into t, from root to root.
/-- Changing the initial shape costs at most sixteen physical instructionsper key and leaves the pointer at the root. -/theorem reshape (s t : Tree) (same : s.size = t.size) : ∃ k, k ≤ 16 * s.size ∧ Trace ⟨s, []⟩ ⟨t, []⟩ k := Pointer.reshape s t sameThis is the startup term of several later comparisons. A dynamic BST that wants to imitate a static tree t, but starts from an arbitrary tree s, first rebuilds s into t at this cost, as in Results.reference of Chapter 16.
7.5.4 Putting it together
For one access with selected rotations, the region has at most nodes. Reshaping it costs at most instructions, and the request unit gives . The requested key ends at the root, where the cursor is, so the visit is free. The unselected rotations become pending. They are prepended to the next access, where they are selected or postponed again, and each rotation is charged once, when it is finally executed or left in the final suffix. Summing over the execution gives . The README describes the same argument in prose. The next section shows how the library turns this into an online transformer that uses only the past and the current request.
7.6 Running an online algorithm on the pointer machine
The lazy simulation above reorders rotations and postpones those that the current request does not need. As stated, it is an offline construction: it takes a whole execution as input. This section shows that it can also be run online, for the online algorithms of Chapter 5: each pointer step depends only on the past, the current request and a simulation state. Every online rotation-model algorithm therefore yields an online pointer algorithm with constant overhead.
The simulator maintains two trees:
/-- The real pointer tree and the virtual rotation-model tree, related by therotations postponed so far. This state contains no future requests. -/structure State where current : Tree virtual : Tree pending : Nat certificate : Rotations current virtual pendingdef initial (t : Tree) : State := ⟨t, t, 0, .refl⟩virtual is the tree that the rotation-model algorithm believes it has. current is the tree actually present in the pointer machine. The pending rotations that the pointer machine has not yet performed separate them, and certificate proves this (Rotations current virtual pending). Initially both trees are the input tree and nothing is pending. The state contains no future requests.
One step of the simulation is specified as a relation:
/-- One causal simulation step, with pending work carried as a potential. -/def Transition (a : Algorithm) (past : List Nat) (s : State) (x : Nat) (result : State × Nat) : Prop := Pointer.Serves s.current result.1.current x result.2 ∧ result.1.virtual = (a.step past s.virtual x).1 ∧ result.2 + 32 * result.1.pending ≤ 32 * (s.pending + (a.step past s.virtual x).2) + 17Given state s and request x, a result (s', c) is a valid transition when:
- the pointer machine serves
xfroms.current, ending ats'.currentand payingc(Pointer.Serves, which includes the unit request charge); - the new virtual tree is exactly what the algorithm’s own step produces from the old virtual tree, so the algorithm runs unmodified on its own view; and
- an amortized bound holds with potential
pending: the actual cost plus the new potential is at most times the old pending work plus the algorithm’s rotations, plus .
Theorem (a transition exists). For every algorithm, history and simulation state, and every request x that is a key of the virtual tree, there is a valid transition. This is the per-request form of the lazy simulation above.
/-- Every valid current request has a certified simulation step. -/theorem advance_exists (a : Algorithm) (past : List Nat) (s : State) (x : Nat) (valid : x < s.virtual.size) : ∃ result, Transition a past s x result := transition_exists a past s x validModels/Pointer/Lazy/Online/Algorithm/Abstract.lean and its importsThe simulator chooses one transition:
/-- Choose a certified implementation using only the current request, past andsimulation state. Classical choice fixes this rule once, independently of futurerequests. Planning is uncharged, as in the underlying abstract BST models. -/noncomputable def advance (a : Algorithm) (past : List Nat) (s : State) (x : Nat) : State × Nat := if valid : x < s.virtual.size then Classical.choose (advance_exists a past s x valid) else (s, 0)noncomputable def run (a : Algorithm) (past : List Nat) (s : State) : List Nat → State × Nat | [] => (s, 0) | x :: xs => let next := advance a past s x let rest := run a (past ++ [x]) next.1 xs (rest.1, next.2 + rest.2)advance picks a transition with Classical.choose, so it is noncomputable. It is a mathematical function of (a, past, s, x), not an executable program. An invalid request leaves the state unchanged at cost ; it is never reached by the theorems below, which assume validity. run threads the state through the sequence and appends each request to the history, exactly like Algorithm.runFrom.
Choosing the pointer instructions requires knowing a valid transition, and finding one involves the lazy-simulation construction on the current pending rotations. As in the rotation model, this planning is not charged. The cost bound counts pointer instructions and requests only. The library’s README states this explicitly.
The main theorem runs the simulator from the initial state.
Theorem (online simulation). Let a be an online rotation-model algorithm, t a tree and xs a sequence of keys of t, served with rotations by a. Running the simulator on xs from t produces a pointer execution of total cost whose final tree is pending rotations away from the algorithm’s final tree, and .
/-- The chosen pointer strategy serves every valid request, retains an explicitfinal deferred suffix, and has a uniform constant-factor cost bound. -/theorem simulation (a : RotationBST.Algorithm) (past : List Nat) (t : Tree) (xs : List Nat) (valid : ∀ x ∈ xs, x < t.size) : Pointer.Execution t xs (run a past (initial t) xs).1.current (run a past (initial t) xs).2 ∧ Rotations (run a past (initial t) xs).1.current (a.runFrom past t xs).1 (run a past (initial t) xs).1.pending ∧ (run a past (initial t) xs).2 + 32 * (run a past (initial t) xs).1.pending ≤ 32 * (a.runFrom past t xs).2 + 17 * xs.length := from_initial a past t xs validThe three conjuncts say:
- Legality. The chosen instructions form a pointer execution serving
xsfromt, with final pointer tree(run …).1.currentand cost(run …).2. - Agreement up to the deferred suffix. The final pointer tree reaches the final tree of the rotation-model algorithm by exactly
pendingrotations. The two executions end in the same place, except for work that has been postponed and not yet paid for. - Cost. Pointer cost plus times the pending suffix is at most , where is the algorithm’s rotation count. In particular the pointer cost alone is , with constants independent of .
Causality is visible in the types (advance never receives the future), and the library also states it as a theorem.
Theorem (no lookahead). Running the simulator on xs ++ ys gives the same result as running it on xs, then continuing from the resulting state, with history past ++ xs, on ys. The costs add.
/-- Appending requests leaves the prefix computation unchanged. -/theorem prefix_composition (a : RotationBST.Algorithm) (past : List Nat) (s : State) (xs ys : List Nat) : run a past s (xs ++ ys) = let first := run a past s xs let rest := run a (past ++ xs) first.1 ys (rest.1, first.2 + rest.2) := run_append a past s xs ysThe state and cost after the prefix xs are therefore the same for every continuation ys. Nothing computed for the first requests can depend on later ones, so there is no lookahead.
Finally, the property this transfer was built for.
Theorem (dynamic optimality transfers). If an online algorithm is dynamically optimal in the rotation model, with total cost as the measure, then there are constants and such that its pointer-machine simulation, on every tree t and every sequence xs, costs at most for every offline pointer execution of cost serving xs from t, where = t.size.
/-- Dynamic optimality, if established in the normalized rotation model,transfers to comparison with every offline pointer execution. -/theorem dynamicOptimality (a : RotationBST.Algorithm) (optimal : TotallyDynamicallyOptimal a) : ∃ C D : Nat, ∀ t xs u k, Pointer.Execution t xs u k → (run a [] (initial t) xs).2 ≤ C * k + D * t.size := dynamic_transfer a optimalThe comparison is against every offline pointer execution Pointer.Execution t xs u k. Both sides of this comparison are in the pointer model. The proof composes three bounds: an offline pointer execution of cost yields a rotation execution of total cost at most (Results.to_rotations); total dynamic optimality bounds the algorithm by that execution; and simulation bounds the pointer cost by the algorithm’s rotation-model cost. The resulting constants are .
Conventional dynamic optimality is a statement about pointer-model algorithms competing with pointer-model optima. This theorem says that a proof of TotallyDynamicallyOptimal for any rotation-model algorithm would give exactly that: an online pointer algorithm that is dynamically optimal in the conventional sense. The hypothesis is the total-cost notion. The rotation-only DynamicallyOptimal is stronger, and is never needed.
The working-set transfer Results.workingSet has the same shape. It is stated in Chapter 14, after the working-set bound is defined.
7.7 Cursors and regions for later chapters
The definitions and theorems of this section are not needed for the simulations above. Later chapters use the pointer machine in ways that the root-restarting searches of Serves do not cover: with cursors that persist between requests, with navigation on a fixed tree, and with regions assembled from smaller pieces. They are collected here, next to the machine.
7.7.1 Cursors on a fixed tree
A configuration stores the focused subtree and the whole path to the root. All of it is determined by the tree and the rank under the cursor.
Theorem (a rank determines the cursor). Two configurations of the same tree whose cursors are on the same rank are equal.
/-- A reference tree and an existing key uniquely determine the completecursor, including its focused subtree and enclosing zipper. -/theorem cursor_unique {a b : Config} {x : Nat} (tree : a.tree = b.tree) (left : a.key? = some x) (right : b.key? = some x) : a = b := Config.ext_key tree left rightSo a cursor can be stored as a rank. The multi-finger model of Chapter 10 does exactly that: its state is a tree and one rank per finger, and this theorem makes each finger’s configuration, and hence the effect of each instruction, well defined.
Some arguments only walk, without rotating. The library separates the four moves from the rotations:
/-- Navigation only, distinguished from rotations so a walk has a fixed tree. -/inductive Move : Config → Config → Prop where | downLeft {a b r : Tree} {cs : List Frame} : Move ⟨.node (.node a b) r, cs⟩ ⟨.node a b, .left r :: cs⟩ | downRight {l a b : Tree} {cs : List Frame} : Move ⟨.node l (.node a b), cs⟩ ⟨.node a b, .right l :: cs⟩ | upLeft {a b r : Tree} {cs : List Frame} : Move ⟨.node a b, .left r :: cs⟩ ⟨.node (.node a b) r, cs⟩ | upRight {a b l : Tree} {cs : List Frame} : Move ⟨.node a b, .right l :: cs⟩ ⟨.node l (.node a b), cs⟩inductive Walk : Config → Config → Nat → Prop where | refl {c : Config} : Walk c c 0 | step {a b c : Config} {k : Nat} : Move a b → Walk b c k → Walk a c (k + 1)A Move is one of the instructions downLeft, downRight, upLeft, upRight of Pointer.Step, with the same patterns, and Walk a b k is a sequence of k moves. Since no rotation occurs, a walk stays in one tree, and every walk is a Pointer.Trace with the same count. Walks are what a static tree with a lazy finger performs. In Chapter 16, Results.readonly realizes the lazy-finger distance between two ranks by a walk of exactly that length, Results.shortest shows that no walk is shorter, and Results.toward takes one Move along a shortest route.
A cursor cannot get far in few instructions, even when it may rotate.
Theorem (few reachable keys). From a fixed configuration, at most distinct ranks can be under the cursor after at most instructions.
/-- A fixed cursor can reach at most exponentially many different keys with abounded number of physical instructions, even when rotations are permitted. -/theorem reachable_keys (a : Config) (r : Nat) (keys : Finset Nat) (reachable : ∀ x ∈ keys, ∃ b k, Trace a b k ∧ k ≤ r ∧ b.key? = some x) : keys.card ≤ 7 ^ r := reachable_keys_card a r keys reachableThe proof is a counting argument. Write each trace as a word over seven symbols, one per instruction and a padding symbol, padded to length exactly . The decoder runs the word from the fixed configuration with Multifinger.perform (Chapter 10), so the word determines the endpoint, and different endpoint ranks need different words. The configuration must be fixed before the ranks are chosen; the bound is uniform in the tree. Chapter 16 uses it to bound the number of keys within lazy-finger distance of a key by , the counting step of the separation between lazy finger and dynamic BSTs.
7.7.2 Assembling regions
The structures of Section 35.1, BST deques and tendons, describe the part of a tree they occupy as a Lazy.Skeleton and change it with the reshaping theorem above. They build these skeletons from smaller ones with three operations.
/-- Substitute a connected region for the first or last inorder hole. -/def fillMin : Skeleton → Skeleton → Skeleton | .hole _, t => t | .node l r, t => .node (l.fillMin t) rdef fillMax : Skeleton → Skeleton → Skeleton | .hole _, t => t | .node l r, t => .node l (r.fillMax t)s.fillMin t replaces the first hole of s, in inorder, by the whole skeleton t, and s.fillMax t replaces the last hole. The subtree that the replaced hole held is discarded, so the operation is meant for a hole whose content t takes over. The active nodes of both skeletons stay active, so the sizes add, and the fringe of the result is the fringe of t followed by the rest of s’s fringe, or the mirror image for fillMax. A tendon’s region is built this way: the region of one deque, with its last hole filled by the region of another deque, whose first hole holds the subtree at the tendon’s bottom endpoint.
/-- A zipper path as an active skeleton, keeping each off-path subtree opaque. -/def under : Skeleton → List Pointer.Frame → Skeleton | s, [] => s | s, .left r :: cs => (Skeleton.node s (.hole r)).under cs | s, .right l :: cs => (Skeleton.node (.hole l) s).under css.under cs places the skeleton s at the position described by the context cs, nearest ancestor first as in Pointer.plug. Every ancestor on the path becomes an active node, and every subtree hanging off the path becomes a hole. It is the skeleton analogue of Config.under: its tree is plug cs s.tree, and its size is the size of s plus the length of the path. A short path from the root, together with a few nodes below it, thus becomes a small region, and the reshaping theorem rearranges it at a cost proportional to the path length, independent of the subtrees hanging off it. Tendons use this to move one subtree across the short boundary path of a deque with a constant number of instructions.