CS 641 meeting -*- Outline -*- * developing loops (Cohen's chapters 9-10) Remark: these examples are simple, but same principles guide the development of more complex programs, where the aid is needed Recall: Basic problem (in developing a loop) is how to choose invariant and guard i.e. given postcondition R for a loop, need to choose invariant P, guard B, such that P /\ ~B ==> R ** deleting a conjunct (9) this heuristic applies when the postcondition is a conjunction If R has form X /\ Y, choose P as one, and B as negation of other ------------- HEURISTICS FOR CHOOSING INVARIANT (deleting a conjunct): if postcondition R is a conjunction, then delete the most difficult to truthify. (what's most difficult?): conjunct that gives enough info for solution (i.e, part of answer) -------------- *** integer division example (9.1) suppose we want to program integer division without using it as a primitive ---------------- EXAMPLE (INTEGER DIVISION) var x,y: int {Q: 0<=x /\ 0=y, ------------------ **** establish invariant an assignment will do that ---------------- 1. establish invariant {Q: 0<=x /\ 00 below to ensure progress --------------- 3. develop loop body solve for K>0 and E in {P /\ (r>=y)} r,q := r-K,E {P} --------------- we solve by assuming the precondition and working as follows wp(r,q := r-K,E).P equiv wp(r,q := r-K,E).(0<=r /\ q*y+r = x) equiv 0<=r-K /\ E*y+(r-K) = x equiv r>=K /\ (E*y + r-K = x) equiv r>=K /\ (E*y + r-K = q*y+r) equiv r>=K /\ E = q + K/y equiv r>=y /\ E = q + 1 equiv =y> E = q +1 so the body of the loop will be r,q := r-y,q+1 Q: why does boundness hold? in general have to check that at this point so annotated solution {Q: 0 <= x /\ 0= y -> r,q := r-y,q+1 od {P /\ r < y, hence R: 0<=r /\ r X := true [] x := false fi use functions that already do case analysis (max) *** postpone design decisions (9.4) (omit) heuristic: don't make a design decision until absolutely necessary. ** replacing constants by fresh variables (10) what if the postcondition is not a conjuction? ------------------- HEURISTICS FOR CHOOSING INVARIANT (replace constants by fresh variables): If the postcondition has the form x = f.N, then rewrite it as x = f.n /\ n = N and choose invariant: x = f.n guard: ~(n = N) (constrain fresh vars to ensure defined): If f is partial, and defined on (i:0<=i 0} ; var x: int ; x : (R: x = (MIN i : 0 <= i /\ i < #b : b.i)) where MIN is not allowed in the program. Q: what constant can you eliminate? see Cohen's book for other examples.