The Hoare Triple law for sequential composition says
Note that here S1 and S2 represent programs that may themselves be sequential compositions (i.e., they need not be individual commands).
Example 1: Prove {P & k≥0} sum := sum + k; k := k+1 {P}, where P: sum = (+i | 0≤i<k : i).
The rule suggests that we find a prediate R such that both
Utilizing the Hoare Triple rule for assignment, we have that
Hence, we choose as a candidate for R the predicate P(k:=k+1). It remains only to show that
By the Hoare Triple rule for assignment, this is equivalent to
Here is a proof:
Assume P and k≥0.
R(sum := sum + k)
= < defn of R >
P(k:=k+1)(sum := sum + k)
= < defn of P >
(sum = (+i | 0≤i<k : i))(k:=k+1)(sum := sum + k)
= < textual substitution >
(sum = (+i | 0≤i<k+1 : i)(sum := sum + k)
= < textual substitution >
sum + k = (+i | 0≤i<k+1 : i)
= < assumption k≥ allows us to split off term (Gries 8.23) >
sum + k = (+i | 0≤i<k : i) + k
= < algebra: subtract k from both sides >
sum = (+i | 0≤i<k : i)
= < assumption P >
true
Now suppose that we use the wp-approach instead of the Hoare Triple approach. The relationship between wp and Hoare Triples is
Because our program is a sequential composition of commands, in order to compute its weakest precondition we will make use of the wp sequential composition rule, which is
Here is a proof of [P & k≥0 ⇒ wp.(sum := sum+k; k:=k+1).P]:
Assume P and k≥0
wp.(sum := sum+k; k:=k+1).P
= < wp sequential composition rule >
wp.(sum:=sum+k).(wp.(k:=k+1).P)
= < wp assignment rule >
wp.(sum:=sum+k).(P(k:=k+1))
= < wp assignment rule >
P(k:=k+1)(sum:=sum+k)
As this is the second line in the proof above, we simply continue as in that proof.
Assume x=X and y=Y
wp.(temp:=x; x:=y; y:=temp).(x=Y & y=X}
= < wp seq. comp. law, with S1 := "temp:=x" and S2 := "x:=y; y:=temp" >
wp.(temp:=x).(wp.(x:=y; y:=temp).(x=Y & y=X))
= < wp seq. comp. law, with S1 := "x:=y" and S2:= "y:=temp" >
wp.(temp:=x).(wp.(x:=y).(wp.(y:=temp).(x=Y & y=X)))
= < wp assignment law >
wp.(temp:=x).(wp.(x:=y).((x=Y & y=X)(y:=temp)))
= < textual substitution >
wp.(temp:=x).(wp.(x:=y).(x=Y & temp=X))
= < wp assignment law >
wp.(temp:=x).((x=Y & temp=X)(x:=y))
= < textual substitution >
wp.(temp:=x).(y=Y & temp=X)
= < wp assignment law >
(y=Y & temp=X)(temp:=x)
= < textual substitution >
y=Y & x=X
= < assumptions y=Y and x=X >
true & true
= < (Gries 3.29) >
true
Sequential composition is associative; that is, the program
can be viewed as being either
In the proof above, we used the latter interpretation. (Notice the instantiations of S1 and S2 in the first step of the proof.) As an exercise, the reader should do the proof using the former interpretation.