Proofs: Postfix expression evaluation
These are the human proofs of Postfix expression evaluation, at full length.
Postfix evaluation returns the value of a postfix expression and rejects every other string full
This proof shows: correctness, termination.
Claim. Let be a token string. If , POSTFIX-EVAL returns . If , it reports an error. In both cases it stops after at most rounds of the loop.
Setup. We use the definitions of the reverse Polish notation page: the weight of a token ( for an operand, for an operator), the prefix sums with , and its theorem: exactly when for and , and each element of splits by rule 2 in exactly one way, so is well defined.
We prove this invariant for the loop of line L2. It holds before round , for , provided that rounds reported no error:
(E) for . The prefix is a concatenation with and each , and the stack holds from the bottom to the top. In particular .
Step 1: initialization. Before round 1, , the prefix is empty, , and the stack is empty. (E) holds.
Step 2: maintenance. Assume (E) for , and consider round with token .
- Operand. Line L3 pushes . Set , which is in by rule 1, with . Now , and (E) holds for .
- Operator of arity with . Line L5 does not report an error, since . Line L6 pops the top values, which are : the first pop is the top, , and it goes to , so for . Let . By rule 2, , and by the definition of , , which line L7 pushes. So the prefix is , a concatenation of postfix expressions, and the stack holds their values in order. Since , (E) holds for .
- Operator of arity with . Line L5 reports an error. In this case , so the condition of the theorem fails at , and . The error is correct.
Step 3: termination. Each round increases by exactly 1, and the loop has rounds, so it stops after at most rounds, either at an error of line L5 or after round . Lines L6 and L7 run a bounded number of steps for each round, pops and one push.
Step 4: the result. Suppose that no round reported an error. Then (E) holds for : for all , and the stack holds values.
- If , then satisfies the condition of the theorem, so . By (E), and the stack holds only . Line L8 finds , and line L9 returns .
- If , then by the theorem, and line L8 finds and reports an error.
Suppose now that a round reported an error. By Step 2 this happens only in the third case, where .
So for no error occurs (each error case implies ), and the algorithm returns . For it cannot return a value, because a return at line L9 needs no error in the loop and , which with (E) means . So it reports an error.