Lectures onType Theory
ch:dijkstra-monads: Dijkstra monads
appendix sectionsolutions

ch:dijkstra-monads: Dijkstra monads

Exercise 104.1.

Let P be the successful postcondition on (unit,s1) and Q the exceptional postcondition on (negative,s1). The program reads s0; if s0<0 it raises, and otherwise it writes s0+1. Expanding get, bind, raise, and put gives w(P)(Q)(s0)={Q(negative,s0),s0<0,P(unit,s0+1),s00. Thus the negative branch requires exactly Q(negative,s0), retaining the failing state, while the nonnegative branch requires exactly P(unit,s0+1).

Exercise 104.2.

Let incr2 sequence incr twice. Two applications of WP-Bind, followed by the get and put clauses, calculate w2(p)(s0)=WPBindwi(λ(unit,s1).wi(p)(s1))(s0)=first incrementwi(p)(s0+1)=second incrementp(unit,s0+2). Advertise wa(p)(s0)=s2.s2=s0+2p(unit,s2). Rule WP-Sub asks for p,s0.wa(p)(s0)w2(p)(s0). Given its antecedent, instantiate s2 with s0+2, use reflexivity of equality, and obtain p(unit,s0+2), which is the calculated consequent.

Exercise 104.3.

Fix a result type A, a state s0:S, and a postcondition p:A×SU. For a state transformer w, right identity is bindStwp(w,λa.returnStwpa)(p)(s0)=WPBindw(λ(a,s1).returnStwpa(p)(s1))(s0)=WPReturnw(λ(a,s1).p(a,s1))(s0)=w(p)(s0). For w:WPSt(A), k:AWPSt(B), and h:BWPSt(C), fix q:C×SU. Then bindStwp(bindStwp(w,k),h)(q)(s0)=WPBindw(λ(a,s1).k(a)(λ(b,s2).h(b)(q)(s2))(s1))(s0)=WPBindbindStwp(w,λa.bindStwp(k(a),h))(q)(s0). Extensionality in q and s0 yields the two transformer equations.

Exercise 104.4.

In the state-preserving semantics, raise(e)(p)(q)(s1)=q(e,s1). In the rollback semantics a computation also receives its entry state s0, and failure uses q(e,s0), discarding the state at the point of failure. Start at zero and run put(1);raise(e). The preserving transformer produces q(e,1), while the rollback transformer produces q(e,0). Choose q(e,s):=(e=es=1). The preserving precondition is true and the rollback precondition is false. Therefore the transformers are not extensionally equal, and the generated bind/catch laws of one semantics cannot be transferred without replacing the failure rule.

Search the book

Type to search the local edition.