Unit 3.2 Deriving a loop from its loop invariant
In the spirit of the quote from Dijkstra in Unit 3.1, given the precondition, postcondition, and loop invariant, it is the proof outline that these create that should guide the development of the program. Let us illustrate this for \({\bf Algorithm~1}\text{.}\) (In Unit 3.3, we will go a step further and systematically derive the loop invariant.)
Let us pretend that we don't know about \({\bf Algorithm~1} \) but we do have some means for determining the loop invariant that allows it to be proven correct, together with the precondition and the postcondition. We can place this information into our outline for a proof of correctness, which we will refer to as the worksheet since we will systematically fill it with assertions and commands.
The condition under which the \({\bf while} \) loop continues to execute, \(G \text{,}\) is called the loop guard. If the loop correctly maintains the loop invariant and the execution exits the loop, then after that loop the condition
is true. We must choose \(G \) so that (3.1) implies the postcondition
Clearly, choosing \(G \) equal to \(k \neq n \) meets the desired criteria. This can then be substituted for \(G \) in the worksheet, which yields
Next, we need to initialize variables \(y \) and \(k\) so that the loop invariant is true before the loop:
Initializing \(y := 0 \) and \(k := 0 \) has the desired effect, since the Hoare triple
evaluates to true. This initializiation is added to the worksheet:
This leaves us to determine the commands that make the body of the loop correct. In other words, commands such that the loop invariant is maintained. Notice that performing no computation in the body of the loop has the desired result. However, that would mean that \(k \) is never incremented and hence the loop never completes for \(k \neq 0 \text{.}\) This leads us to increment (rather than decrement) \(k \text{:}\)
We can now reason about what the state of the variables must be before \(k \) is incremented: If \(k:=k+1 \) leaves us in a state where
is true, then before incrementing \(k \) the variables must be in a state where
is true. This yields
Finally, we must determine how \(y \) must be updated in order to make the Hoare triple
true. We can manipulate the postcondition for this Haore triple to find it is equivalent to
which then suggests the update
with which we complete the worksheet:
It is important to note that at every step the proof of correctness of the program guided the insertion of assertions (in form of predicates) and commands in the worksheet. Thus, we have (almost) achieved what Dijkstra advocated: We have let correctness proof and program grow hand in hand.