Proofs: Persistent stack
These are the human proofs of Persistent stack, at full length.
The persistent stack meets the stack laws and never changes an old version full
This proof shows: correctness.
Write for the sequence of items of the stack , from the top down: , and for a node . Write for the length of .
Lemma 1 (the invariant holds). At each moment, every node satisfies (I1) its fields have not changed since it was made, (I2) where , and (I3) the chain reaches nil.
Proof. By induction on the number of operations done. Before the first operation there is no node. POP, TOP, IS-EMPTY and SIZE write no field and make no node, so they keep all three statements. PUSH at line L1 makes one node with , and , and writes no other field, so (I1) holds for the old nodes. The chain from is followed by the chain from , which reaches nil by the hypothesis, so (I3) holds for . SIZE returns , which is by (I2) and (I3) for (induction along the finite chain), or 0 for nil. So , which is (I2) for .
By (I3), is a finite sequence for each stack , and by (I1), depends only on fields that never change.
Lemma 2 (old versions are unchanged). If a stack value exists at some moment, then is the same at every later moment.
Proof. is determined by the fields and of the nodes on the chain from , and by Lemma 1 no field of an existing node changes. A node made later is not on this chain, because the chain consists of nodes that existed when existed, and fields do not change.
Theorem (the stack laws). For each stack and item :
- PUSH returns a stack with , and is unchanged.
- If and , then POP returns with , and TOP returns .
- If , POP and TOP report underflow.
- IS-EMPTY is true exactly when , and SIZE.
Proof. (1) Line L1 makes with and , so by the definition of seq. Lemma 2 gives that is unchanged. (2) If , line L2 does not stop, and line L3 returns and , with by the definition of seq. Lines L4 and L5 return in the same way. (3) Lines L2 and L4 test exactly . (4) exactly when , because a node contributes its item. SIZE returns by (I2) and (I3), as in the proof of Lemma 1.
Corollary (full persistence). Let be the versions made by any sequence of operations, where each update takes any earlier version as input. Then at the end, is the sequence that the stack laws give for the chain of updates that made from the empty stack.
Proof. By induction on . The version is nil. The version was made by PUSH or POP from some with . At that moment, was, by the hypothesis, the right sequence, so by the theorem was the right sequence for . By Lemma 2 it is still the same at the end.
Append. Lines A1 to A4 push the items of onto from the bottom item of up to the top item. By part 1 of the theorem and induction on the number of pushes, after the pushes of the bottom items of the sequence of is those items, in the order they have in , followed by . With this is . Each push makes one node, so APPEND makes nodes.