Proofs: Sparse vector
These are the human proofs of Sparse vector, at full length.
The sparse vector operations return the vector values and keep the invariant full
This proof shows: correctness.
Statement. Let each sparse vector satisfy (I1) to (I3) of the page, and let denote the entry that (I3) assigns. Assume the table behaves as a map: after T-PUT the key maps to , after DELETE the key is absent, the other keys keep their values, and iteration visits each pair of once. Then, for indices and vectors of equal dimension:
- after PUT, the vector satisfies (I1) to (I3) with and every other entry unchanged;
- GET returns ;
- DOT returns , and DOT-DENSE returns ;
- PLUS returns a vector that satisfies (I1) to (I3) with for every , and leaves and unchanged.
Proof.
Part 1. If , line L1 deletes , so is not a key and (I3) gives . If , line L2 maps to , so (I3) gives , and the new value is nonzero. In both cases the other keys and their values are unchanged, so the other entries are unchanged and still satisfy (I2) and (I3). The only key that may be added is , and , so (I1) holds.
Part 2. Line L3 returns if is a key and 0 otherwise, which is by (I3).
Part 3. Exchanging and on line L4 does not change the sum, since . Let be the set of keys of after line L4. We show the loop invariant: after the loop has visited a set of pairs, . It holds with and by line L5. A round visits a new pair with by (I3), and adds by part 2, so the invariant holds for . The loop visits each pair once, so at line L8 and . For an index , (I3) gives , so , and . The proof for DOT-DENSE is the same with in place of GET.
Part 4. Line A1 makes a copy of , so satisfies (I1) to (I3) with , and later changes to do not touch . The loop reads and never writes it. Let be the set of keys of visited so far. The loop invariant is: satisfies (I1) to (I3), and for , and for . It holds at the start with . A round visits a new pair with . Before the round, since , and GET returns it by part 2. Line A3 calls PUT, which by part 1 keeps (I1) to (I3), sets , and changes no other entry. So the invariant holds for . At line A4 every key of is in . For , (I3) for gives , so . Hence for every . When , part 1 shows that index is not stored, so (I2) holds for .
Each loop visits a finite table once and each round takes finitely many steps, so every operation stops.