Andrew.Butterfield@cs.tcd.ie Room F.13, OReilly Institute 3BA31 - - PDF document

andrew butterfield cs tcd ie
SMART_READER_LITE
LIVE PREVIEW

Andrew.Butterfield@cs.tcd.ie Room F.13, OReilly Institute 3BA31 - - PDF document

3BA31 Formal Methods 1 3BA31: Formal Methods Andrew Butterfield Foundations & Methods Group, Software Systems Laboratory Andrew.Butterfield@cs.tcd.ie Room F.13, OReilly Institute 3BA31 Formal Methods 2 Remember This? A Stock


slide-1
SLIDE 1

3BA31 Formal Methods 1

3BA31: Formal Methods

Andrew Butterfield Foundations & Methods Group, Software Systems Laboratory

Andrew.Butterfield@cs.tcd.ie

Room F.13, O’Reilly Institute

3BA31 Formal Methods 2

Remember This?

“A Stock Exchange is a collection of companies, where each company has a collection of shares; moreover these collections of shares are mutually disjoint. Each company has an associated share price. Furthermore, investors own shares in several companies; the collections of shares held by investors are mutually disjoint. Additionally, there is one dealer, who acts as an intermediary for the buying and selling of shares.”

slide-2
SLIDE 2

3BA31 Formal Methods 3

3BA21 Mathematics — Sample Paper, Q1

Why revisit this? What can formal methods do for us here?

3BA31 Formal Methods 4

3BA21 Sample Q1—Basic Domain Shr =d

f

domain of shares

Cmp =d

f

domain of company

Inv =d

f

domain of investors

data Shr = S Nat data Cmp = C1 | C2 | C3 | C4 data Inv = I1 | I2 | I3 | I4

slide-3
SLIDE 3

3BA31 Formal Methods 5

3BA21 Sample Q1—State ς : Shr → Cmp ̟ : Cmp → N ψ : Shr → Inv

d : Inv

type CmpShr = Map Shr Cmp type ShrPri = Map Cmp Nat type InvShr = Map Shr Inv type SEState = (CmpShr,ShrPri,InvShr,Inv)

3BA31 Formal Methods 6

3BA21 Sample Q1—Constraint StcExcCns(ς, ̟, ψ, d) =d

f

( rng ς = dom ̟ ) ∧ ( dom ς = dom ψ ) stcExcCns(cmpshr,shrpri,invshr,dlr) = rng cmpshr == dom shrpri && dom cmpshr == dom invshr

slide-4
SLIDE 4

3BA31 Formal Methods 7

3BA21 Sample Q1—Change Share Price pre-ChgPri[c, p](ς, ̟, ψ, d) =d

f

c ∈ dom ̟

ChgPri[c, p](ς, ̟, ψ, d) =d

f

(ς, ̟ † [c → p], ψ, d) preChgPri (c,p) (cmpshr,shrpri,invshr,dlr) = c ‘mOf‘ dom shrpri chgPri (c,p) (cmpshr,shrpri,invshr,dlr) = (cmpshr,shrpri ‘override‘ (iMap c p),invshr,dlr)

3BA31 Formal Methods 8

3BA21 Sample Q1—Sell Share pre-SellShr[i, S](ς, ̟, ψ, d) =d

f

( S ⊆ ψ−1{i} ) ∧ ( i = d ) SellShr[i, S](ς, ̟, ψ, d) =d

f

(ς, ̟, ψ † [s → d | s ∈ S], d) preSellShr (i,ss) (cmpshr,shrpri,invshr,dlr) = ss ‘subSet‘ invImg invshr (iSet i) && i /= dlr sellShr (i,ss) (cmpshr,shrpri,invshr,dlr) = (cmpshr,shrpri,invshr ‘override‘ imapset ss dlr,dlr)

slide-5
SLIDE 5

3BA31 Formal Methods 9

3BA21 Sample Q1—New Company pre-NewCmp[c, S, p](ς, ̟, ψ, d) =d

f

( c ∈ rng ς ) ∧ ( S ∩ dom ς = ∅ ) ∧ ( S = ∅ ) NewCmp[c, S, p](ς, ̟, ψ, d) =d

f

(ς ⊔ [s → c | s ∈ S], ̟ ⊔ [c → p] , ψ ⊔ [s → d | s ∈ S], d) preNewCmp(c,ss,p)(cmpshr,shrpri,invshr,dlr) = not (c ‘mOf‘ rng cmpshr) && ss ‘intersect‘ dom cmpshr == nullSet && not(isNullSet ss) newCmp(c,ss,p)(cmpshr,shrpri,invshr,dlr) = ( cmpshr ‘mextend‘ imapset ss c , shrpri ‘mextend‘ iMap c p , invshr ‘mextend‘imapset ss dlr , dlr )

3BA31 Formal Methods 10

3BA21 Sample Q1—Share Price pre-CmpShrPri[s](ς, ̟, ψ, d) =d

f

s ∈ dom ς

CmpShrPri[s](ς, ̟, ψ, d) =d

f

(̟ ◦ ς)(s) preCmpShrPri s (cmpshr,shrpri,invshr,dlr) = s ‘mOf‘ dom cmpshr cmpShrPri s (cmpshr,shrpri,invshr,dlr) = (mApp shrpri . mApp cmpshr) s

slide-6
SLIDE 6

3BA31 Formal Methods 11

3BA21 Sample Q1—Investor Holding pre-CmpInvIn[i](ς, ̟, ψ, d) =d

f

i ∈ rng ψ

CmpInvIn[i](ς, ̟, ψ, d) =d

f

rng ⊳[ψ−1{i}]ς

preCmpInvIn i (cmpshr,shrpri,invshr,dlr) = i ‘mOf‘ rng invshr cmpInvIn i (cmpshr,shrpri,invshr,dlr) = rng (mrestrict (invImg invshr (iSet i)) cmpshr)

3BA31 Formal Methods 12

3BA21 Sample Q1—Portfolio Value pre-PrtV al[i](ς, ̟, ψ, d) =d

f

i ∈ rng ψ

PrtV al[i](ς, ̟, ψ, d) =d

f

  • s∈ψ−1{i}

(̟ ◦ ς)(s) prePrtVal i (cmpshr,shrpri,invshr,dlr) = i ‘mOf‘ rng invshr prtVal i (cmpshr,shrpri,invshr,dlr) = sum [ (mApp shrpri . mApp cmpshr)s | s <- ssort (invImg invshr (iSet i)) ]

slide-7
SLIDE 7

3BA31 Formal Methods 13

3BA21 Sample Q1—Remove Company pre-RmvCmp[c](ς, ̟, ψ, d) =d

f

c ∈ rng ς

RmvCmp[c](ς, ̟, ψ, d) =d

f

(⊳ −[ς−1{c}]ς, ⊳ −[{c}]̟, ⊳ −[ς−1{c}]ψ, d) preRmvCmp c (cmpshr,shrpri,invshr,dlr) = c ‘mOf‘ rng cmpshr rmvCmp c (cmpshr,shrpri,invshr,dlr) = ( mremove remSS cmpshr , mremove cc shrpri , mremove remSS invshr , dlr ) where cc = iSet c remSS = invImg cmpshr cc

3BA31 Formal Methods 14

3BA21 Sample Q1—Constraint Preservation StcExcCns ◦ RmvCmp[c] ⇐ pre-RmvCmp[c] ∧ StcExcCns

slide-8
SLIDE 8

3BA31 Formal Methods 15

3BA21 Sample Q1— Constraint Preservation (rework)     StcExcCns(ς, ̟, ψ, d) ∧ pre-RmvCmp[c](ς, ̟, ψ, d)     ⇒ StcExcCns(RmvCmp[c](ς, ̟, ψ, d)) rmvCmp_preserves_StcExcCns (c::Cmp) (se::SEState) = stcExcCns se && preRmvCmp c se ==> stcExcCns(rmvCmp c se)

3BA31 Formal Methods 16

What’s the Point?

Haskell/QuickCheck Demo

slide-9
SLIDE 9

3BA31 Formal Methods 17

What are “Formal” Systems?

3BA31 Formal Methods 18

Formal Systems: Rules of the Game

  • Specified collection of Symbols
  • Specified ways or putting them together (well-formedness)
  • Specific ways of manipulating symbol-sequences
slide-10
SLIDE 10

3BA31 Formal Methods 19

Example: System ℑ

  • Symbols:
  • Well-Formed Sequences:

Flijet Zero or more Blirgle A followed by a Flijet Xixos ℑ followed by two Blirgles

  • Manipulations (let f1 and f2 stand for arbitrary Flijets).

– ℑf1 becomes f1 – ℑf1f2 becomes ℑf1f2

  • Goal: convert a Xixos into a Blirgle

3BA31 Formal Methods 20

Interpretation

  • +1

ℑ + ℑ + 0 + 1 + 1 0 + 1 + 1 + 1 ℑ + 0 + 1 0 + 1 + 1 + 1 + 1 ℑ + 0 + 1 + 1 + 1 + 1 + 1

  • 0 + 1 + 1 + 1 + 1 + 1
slide-11
SLIDE 11

3BA31 Formal Methods 21

What’s the point?

  • We give meanings to the symbols
  • The symbols could be manipulated without our having to understand them

– which is exactly how a computer does it ! Formal Methods allow us to limit the scope for human error and to exploit the use of machines to help

  • ur analysis

3BA31 Formal Methods 22

Another System

  • Symbols:

– infinite supply of variables u, v, x, y, z, . . . , x1, x2, . . . – punctuation: λ, •, (, )

  • Well-Formed Sequences (M, N):

– x – (λ x • M) – M N

  • Manipulations

– (λ x • M) N becomes M[N/x] (M where N replaces all (free) occurrences of x) A variable x is free if not inside an enclosing (λ x • . . .)

  • Goal: eliminate as many λs as possible.
slide-12
SLIDE 12

3BA31 Formal Methods 23

The Lambda Calculus

  • The system just introduced is the Lambda Calculus
  • It is Turing-Complete — anything a Turing machining or general-purpose computer can do, it can

do.

  • You have already seen it in action (with lots of syntactic sugar) ???

3BA31 Formal Methods 24

Remember these poor folks?

slide-13
SLIDE 13

3BA31 Formal Methods 25

And the relevance to 3BA31 is . . . ?

  • That 747 was not “fly-by-wire” — the pilot landed it, not a computer!
  • Pilots as professionals train so they can take care to get it right
  • Formal Methods are the Programmers’ way of taking care to get it rightr

3BA31 Formal Methods 26

Scribbles 1 : An example of Xixos conversion ℑ →

2nd rule

ℑ →

2nd rule

ℑ →

2nd rule

ℑ →

1st rule

slide-14
SLIDE 14

3BA31 Formal Methods 27

Scribbles 1 : Examples of λ-calculus Expressions

x a variable is a λ-calculus expr. v so is this one

λ x • x

an abstraction built on x

λ x • v

an abstraction built on v

λ x • (λ x • v)

another abstraction

λ v • (λ x • v)

yet another

λ y • (λ x • v)

using a new variable to abstract x (λ v • v) an application

3BA31 Formal Methods 28

Scribbles 1 : λ-Elimination (λ x • x) (λ x • v) → λ x • v (λ x • v) (λ x • x) →

v

(λ x • x x) (λ x • x x) → (λ x • x x) (λ x • x x)

slide-15
SLIDE 15

3BA31 Formal Methods 29

3BA31: Approach

Monday 12noon Lb01 Theory and small exercise to be handed up at start of . . . Thursday 12noon Lb04 Practice Friday 11am Lb01 Tools Hilary Term Focus on formalism and method Trinity Term Focus on scale, real-world, and some backing theory Webpage: www.cs.tcd.ie/Andrew.Butterfield/Teaching/3BA31/

3BA31 Formal Methods 30

The λ-Calculus

  • Invented by Alonzo Church in 1930s
  • Intended as a form of logic
  • Turned into a model of computation
  • Not shown completely sound until early 70s !

We shall now revisit it in a little more detail, and a little more formally.

slide-16
SLIDE 16

3BA31 Formal Methods 31

λ-Calculus: Syntax

We have an infinite set Vars, of variables: u, v, x, y, z, . . . , x1, x2, . . .

Vars We define the set of well-formed λ-calculus expressions LExpr as the smallest set of strings matching the following syntax: M, N, . . . ∈ LExpr

::=

v

| (λ x • M) | (M N)

Read: a λ-calculus expression is either (i) a variable (v); (ii) an abstraction of a variable from an expression (λ x • M); or (iii) an application of one expression to another ((M N)).

3BA31 Formal Methods 32

λ-Calculus: Free/Bound Variables

  • A variable occurrence is free in an expression if it is not mentioned in an enclosing abstraction.
  • A variable occurrence is bound in an expression if is mentioned in an enclosing abstraction.
  • A variable occurrence is binding in an expression if is the variable immediately after a λ.
  • A variable is free in an expression if it occurs free in that expression.
  • A variable is bound in an expression if it occurs bound in that expression.

A variable can be both free and bound in the same expression (how?)

slide-17
SLIDE 17

3BA31 Formal Methods 33

λ-Calculus: Computing Free/Bound Vards

We can define functions that return the sets of free and bound variables:

FV :

LExpr → P Var

FV(x)

  • =

{ x } FV(λ x • M)

  • =

FV(M) \ { x } FV(M N)

  • =

FV(M) ∪ FV(N) BV :

LExpr → P Var

BV(x)

  • =

∅ BV(λ x • M)

  • =

BV(M) ∪ { x } BV(M N)

  • =

BV(M) ∪ BV(N)

3BA31 Formal Methods 34

λ-Calculus: α-Renaming

We can change a binding variable and its bound instances provided we are careful not to make other free variables become bound.

(λ x • (λ y • (x y)))

α

→ (λ u • λ v • (u v))) (λ x • (x y))

  • α

→ (λ y • (y y))

formerly free y has been “captured” ! This process is called α-Renaming or α-Substitution, and leaves the meaning of a term unchanged.

slide-18
SLIDE 18

3BA31 Formal Methods 35

λ-Calculus: Substitution

We define the notion of substituting an expression N for all free occurrences of x, in another expression M, written: M[N/x]

(x (λ y • (z y)))[(λ u • u)/z]

subs

→ (x (λ y • ((λ u • u) y))) (x (λ y • (z y)))[(λ u • u)/y]

subs

→ (x (λ y • (z y)))

y was not free anywhere

3BA31 Formal Methods 36

λ-Calculus: Careful Substitution!

When doing (general) substitution M[N/x], we need to avoid variable “capture” of free variables in N, by bindings in M:

(x (λ y • (z y)))[(y x)/z]

  • subs

→ (x (λ y • ((y x) y)))

If N has free variables which are going to be inside an abstraction on those variables in M, the we need to α-Rename the abstractions to something else first, and the substitute:

(x (λ y • (z y)))[(y x)/z]

α

→ (x (λ w • (z w)))[(y x)/z]

subs

→ (x (λ w • ((y x) w)))

The Golden Rule: A substitution should never make a free occurrence of a variable become bound,

  • r vice-versa.
slide-19
SLIDE 19

3BA31 Formal Methods 37

λ-Calculus: β-Reduction

We can now define the most important “move” in the λ-calculus, known as β-Reduction:

(λ x • M) N

β

M[N/x] We define an expression of the form (λ x • M) N as a “(β−)redex” (reducible expression).

3BA31 Formal Methods 38

λ-Calculus: Normal Form

An expression is in “Normal-Form” if it contains no redexes. The object of the exercise is to reduce an expression to its normal-form (if it exists).

(((λ x • (λ y • (y x))) u) v)

β

→ (λ y • (y u)) v)

β

→ (v u)

Not all expressions have a normal form — e.g.: ((λ x • (x x)) (λ x • (x x))) What about:

( ( (λ x • (λ y • y))) ((λ x • (x x)) (λ x • (x x)) ) w ) ?

slide-20
SLIDE 20

3BA31 Formal Methods 39

λ-Calculus: Reduction Order

The question is, if we have a choice of redexes, which should we reduce first. Answer: always the leftmost-outermost one (Normal Order Reduction). If an expression has a normal form, then normal order reduction is guaranteed to find it.

3BA31 Formal Methods 40

Scribbles 2 : Binding, Bound and Free!

bnd

  • f

x

bnd

  • f

y

bnd x

bnd y

free x

bnd

  • f

z

bnd z

free y

(λ x • (λ y • x y)) ( x (λ z • z y))

slide-21
SLIDE 21

3BA31 Formal Methods 41

Scribbles 2 : Binding, Bound and Free!

bnd

  • f

y

free x

bnd y

(λ y • x y)

3BA31 Formal Methods 42

Scribbles 2 : α-Renaming

Consistent changing of bound variables leaves meaning unchanged:

(λ x • xx) (u) = (u u) (λ y • yy) (u) = (u u)

Analagous to the following definitions of f being equivalent: f(x)

= 1 + x2

f(y)

= 1 + y2

slide-22
SLIDE 22

3BA31 Formal Methods 43

Scribbles 2 : β-Reduction ((λ x •

M

  • (λ y • y))

N

u) v

↓β (λ y • y) v ↓β

v

3BA31 Formal Methods 44

Scribbles 2 : Monster

monster

= (λ x • x x) (λ x • x x)

monster

= (λ x • x x) (λ x • x x) ↓β (monster

β

→ monster) (λ x • x x) (λ x • x x) =

monster

slide-23
SLIDE 23

3BA31 Formal Methods 45

Scribbles 2 : Reducing Big Expression (1) ((λ x λ y • y) monster) w ↓β ((λ x λ y • y) monster) w ↓β ((λ x λ y • y) monster) w ↓β

. . .

3BA31 Formal Methods 46

Scribbles 2 : Reducing Big Expression (2) ((λ x λ y • y) monster) w ↓β (λ y • y) w ↓β

w

slide-24
SLIDE 24

3BA31 Formal Methods 47

Scribbles 2 : Reduction Order Example (1)

f(x) = x2 f(3 + 7)

= (3 + 7)2 = 102 = 100

f(3 + 7)

= f(10) = 102 = 100

3BA31 Formal Methods 48

Scribbles 2 : Reduction Order Example (2)

f = λ x • x2

(λ x • x2)((+3)7)

β

  • β
  • ((+3)7)2

β

  • (λ x • x2)10

β

  • 102

102

slide-25
SLIDE 25

3BA31 Formal Methods 49

Sugaring The Pill

The lambda calculus rapidly gets unwieldy.

( ( (λ x • (λ y • y))) ((λ x • (x x)) (λ x • (x x)) ) w ) !!

It’s worth adding a little syntactic sugar to make it easier to use.

3BA31 Formal Methods 50

Too Many Brackets, etc.

  • 1. We don’t bracket every abstraction or application:

we assume the scope of an abstraction goes as far to the right as possible.

  • 2. We change (M N) P to M N P, but leave M (N P) as is.
  • 3. We drop intermediate λ and dots in nested abstractions

(((λ x • ( λ y • y))((λ x • (x x))(λ x • (x x))))w) 1 ((λ x • λ y • y)((λ x • x x)(λ x • x x)))w 2 (λ x• λy • y) ((λ x • x x)(λ x • x x)) w 3 (λ x y • y) ((λ x • x x)(λ x • x x)) w

These conventions support concise multiple abstraction/application:

(λ x y • M) N

β

→ λ y • M[N/x] (λ x y • M) N P

β

→ (M[N/x])[P/y]

  • r

M[N/x][P/y]

slide-26
SLIDE 26

3BA31 Formal Methods 51

Definitions

It is convenient to be able to give names to expressions, using a definition notation (Symbol

= means

“is defined equal to”):

  • =

(λ x • x x)(λ x • x x)

Z

  • =

λ z s • z

S

  • =

λ n z s • s(n z s)

We sometimes like to to do the following transformation: N

= λ x • M ↔

N x

= M

Z s z

  • =

z S n s z

  • =

s (n s z) You can use brackets if it makes you feel more comfortable: Z(s)(z) = z S(n)(s)(z) = s(n(s)(z))

3BA31 Formal Methods 52

Computable ? Show me Numbers !

Ok. We think of a number as a function of two arguments, the first a function that adds one (successor), the second representing zero:

= λ s z • z 0 s z = z 1 = λ s z • s z 1 s z = s z 2 = λ s z • s(s z) 2 s z = s(s z) 3 = λ s z • s(s(s z)) 3 s z = s(s(s z))

. . . These are the so-called “Church Numerals”

slide-27
SLIDE 27

3BA31 Formal Methods 53

Count the ss, Duh ! What about addition, etc?

No problem. SUCC

  • =

λ n s z • s(n s z)

PLUS

  • =

λ m n s z • m s (n s z)

TIMES

  • =

λ m n s • n (m s)

EXP

  • =

λ m n • n m

We can encode booleans, if-then-else and propositional logic operators (and,or,not) as well.

3BA31 Formal Methods 54

Serious Sugar: infix notation

We can now consider adding in some operator symbols written in infix form: M + N

  • =

PLUS M N M · N

  • =

TIMES M N M ˆ N

  • =

EXP M N We will have to adopt some suitable convention regarding operator precedence and bracketing. So now we can write things like: F x y

= x ˆ2 + x · (x + y)

slide-28
SLIDE 28

3BA31 Formal Methods 55

Mini-Exercise 1

Show that

2 + 2

β

→ 4

Hints:

  • 1. Use rightmost-innermost reduction order here.
  • 2. You might want to pull an inner redex out, do the reduction separately, and then plug the result

back in.

  • 3. Try 1 + 1

β

→ 2 as a warm-up!

Due: at start of 12noon Lecture, Thursday, February 15th, 2007.

3BA31 Formal Methods 56

Motivating Types

All the syntactic sugar to date has in principle been convertible back to original λ-calculus expressions. So,

(λ m n s • n (m s)) (λ s z • s(s(s z))) (λ t f • t)

looks innocent enough. But if we interpret λ t f • t as True (“Church Booleans”), then the above, if sugared, is 3 · True The (untype) λ-calculus expression will reduce, but not to a normal form that is a sensible number or boolean. Wouldn’t it be nice to have types?

slide-29
SLIDE 29

3BA31 Formal Methods 57

Typed λ-Calculus

We define types (Type) to be either basic-types (BType or function types: s, t, . . .

BType

σ, τ ∈ Type ::=

s

| σ → τ

We can add type annotations to the variables in the lambda calculus: x : τ We can then give typing rules:

  • If M : σ, then (λ x : τ • M) : τ → σ.
  • If M : σ → τ and N : σ, then (M N) : τ.

Typed λ-calculus is different from the un-typed variety — they cannot be inter-converted.

3BA31 Formal Methods 58

Sugared Typed-λ-calculus

We can then add in a range of syntactic sugar for types, basic and compound:

N, Z, Q, ×, ∗

and extend the expression notation:

37, −35, 46.13, (13, 23), 1, 2, 3

We can now write definitions like: length

: Q∗ → N

length seq

  • =

if null seq then 0 else 1 + (length(tail seq)) Look vaguely familiar? !?!?!! Recursion ! How did that get there ? (Later)

slide-30
SLIDE 30

3BA31 Formal Methods 59

Haskell

  • Pure, lazy functional language i.e. well-sugared typed λ-calculus.
  • Named for logician Haskell B. Curry
  • Many multiple-platform implementations:

– compilers — GHC, yhc, nbc, . . . – interpreters — Hugs, WinHugs.

  • www.haskell.org

3BA31 Formal Methods 60

Haskell: Basic Types, Constants and Operators

As expected, Haskell supports all the usual basic types: Format Type, Values, Operators, Example Expression. Boolean Bool, True, False, not, &&, ||,

not False && (True || b)

Integers Int, 0, 10, -34, +, -, *, /,

3 * (23 - 16 * i)

Floating-Point Float,Double, 0.0, 1.23E+5, +, -, *, /,

3.14159 * (23E-3 - 1.6 * r)

Characters Char, ’a’,’B’,’\n’,’\xd’, ord, chr, isAlpha,

  • rd c - ord ’0’
slide-31
SLIDE 31

3BA31 Formal Methods 61

Haskell: Composite Types

Assume s, t and u are pre-existing types. Function Types s -> t, f x = x * x, \ y -> y+3, ., map, foldl,

(f . g) 3

Tuples (s,t),(s,t,u), (1,True), (’a’,42), fst, snd,

(fst(True,999),snd(False,42))

Lists [t], [],[1,1,2,3,5,8], :, length, head, tail, ++,

tail ([1,2,3]++[4,5,6])

Strings String is synonym for [Char],

"" is really [],

while "abc" is syntactic sugar for [’a’,’b’,’c’].

3BA31 Formal Methods 62

Haskell: Scripts

A Haskell programme (or script) has the following general format:

module ModuleName where import Import1

. . . list of definitions A definition is typically of a function, of the form: fname arg1 . . . argn = expression defining function

slide-32
SLIDE 32

3BA31 Formal Methods 63

Haskell: Demo

3BA31 Formal Methods 64

Scribbles 3 : Reducing SUCC 2

SUCC 2

= (λ n s z • s(n s z)) (λ s z • s(s z))

β

→ λ s z • s((λ s z • s(s z)) s z)

β

→ λ s z • s((λ z • s(s z)) z)

β

→ λ s z • s(s(s z)) = 3

slide-33
SLIDE 33

3BA31 Formal Methods 65

Scribbles 3 : SUCC 2, one step in detail (λ s z • s(s z)) s

β

“using law (λ x • M)N

β

→ M[N/x], where x is s, M is λ z • s(s z) and N is s” (λ z • s(s z))[s/s] =

“by definition of substitution”

λ z • s(s z)

3BA31 Formal Methods 66

VDM♣

“VDM” stands for the Vienna Development Method — Result of work the in the Vienna Research Laboratory of IBM (1960s). VDM is now a standardised formal-method (VDM-SL — Specification Language):

  • reasoning based on the Logic of Partial Functions (LPF)
  • based on the notion of specifiying programs via pre- and post-condition predicates.
  • http://en.wikipedia.org/wiki/Vienna Development Method

VDM♣ is a non-standard dialect of VDM:

  • based on equational reasoning, rather than LPF.
  • uses pre-condition predicates, but most specifications give an abstract definition of the computed

result (called explicit post-conditions in VDM-SL)

  • http://www.cs.tcd.ie/Andrew.Butterfield/IrishVDM/

The way in which the mathematics is used to reason about systems is very similar in both VDM-SL and VDM♣.

slide-34
SLIDE 34

3BA31 Formal Methods 67

The “Method” in VDM♣: Requirements

  • capture the “users” expectations of the behaviour of the system to be built.
  • model of the environment, or the “World”.
  • model of the desired interactions between system and environment
  • This process requires building a model of the problem domain, and is often referred to as Domain

Modelling or Domain Capture.

3BA31 Formal Methods 68

The “Method” in VDM♣: Specifications

  • a description of the behaviour the system must have in order to satisfy the requirements.
  • a model of the system to be built
  • the process of ensuring that a specification is consistent w.r.t the requirements is called Validation

The VDM method says relatively little about validation, as this is very probelm-specific. VDM methodology does ensure that the specification makes sense, (even it if not what the users wanted !). VDM/VDM♣ uses its mathematics to model the pertinent parts of the system and environment (as state) and then specifies the safety conditions and operations that the system must maintain and provide. System = State + Operations

slide-35
SLIDE 35

3BA31 Formal Methods 69

The “Method” in VDM♣

In order to produce a formal model according to the Vienna Development Method, we need to:

  • Determine the System State

– State Type – State Invariant – Initial State

  • Describe the Operations

– Operation Pre-Condition – Operation Post-Condition

  • Discharge all Proof Obligations

3BA31 Formal Methods 70

The “Method” in VDM♣: Proof Obligations

  • Proof obligation is a required property of a VDM model.
  • Typically capture idea that model “makes sense”.
  • Method compliance the successful proof of every Proof Obligation.
  • They don’t guarantee that what a model is realistic, or what the “customer” wanted.

Note: In addition to the method proof obligations, we may want to prove that other properties hold, related to our particular application.

slide-36
SLIDE 36

3BA31 Formal Methods 71

The “Method” in VDM♣: System State

System state contains all the relevant values and conditions of the system. We define it by first declaring its components and their structure, using the types and type constructors of VDM♣:

Σ ∈ State = (expression using N, B, . . . , ×, P, → , →,

m

→ , . . . , ADTs)

Relationships and conditions of the state that always hold true (often called safety properties) are captured by an invariant: inv-State

: State → B

inv-State Σ

  • =

. . .

Proof Obligation: State Invariant Satisfiability: We must prove that the invariant is satisfiable, i.e there is at least one instance of the state datatype that satisfies it.

∃ Σ : State • inv-State Σ

3BA31 Formal Methods 72

The “Method” in VDM♣: Initial State

We generally need to introduce the notion of an initial or starting state, at least of any system we are proposing to build:

Σ0 : State Σ0

  • =

. . .

Proof Obligation: Initial-State Invariant: We must prove that the initial state satisfies the invariant: inv-State Σ0 = TRUE Note that a proof of this obligation is also a proof of the Invariant Satisfiability obligation (why?)

slide-37
SLIDE 37

3BA31 Formal Methods 73

The “Method” in VDM♣: Operations

  • Capture events that change or observe the system state

– initiated by the system, or – by the environment.

  • Have inputs and outputs
  • cause state changes
  • Two main classes of operations:

– state change: no outputs, but state changes – state enquiry: outputs, but state is unchanged An operation with outputs that changes state as well, can be decomposed into two operations, on of each of the above classes. We shall assume all operators have been so decomposed.

3BA31 Formal Methods 74

The “Method” in VDM♣: State Change

State change operations take input or control parameters of some type (c ∈ Control) and produce a change in state. When specifying such (called StChg, say), we need to identify the circumstances under which we consider the operator to be well-defined — the precondition of the operation. We capture this by a declaration with the following signatures and forms: StChg

: Control → State → State

StChg[c]Σ

  • =

expression defining after-State pre-StChg

: Control → State → B

pre-StChg[c]Σ

  • =

predicate describing pre-condition Proof Obligation: State Change Invariant We must prove that if the state before change satisfies the invariant, and the pre-condition of the

  • perator holds, that then the invariant holds after the operation has run:

inv-State Σ ∧ pre-StChg[c]Σ ⇒ inv-State(StChg[c]Σ)

slide-38
SLIDE 38

3BA31 Formal Methods 75

The “Method” in VDM♣: State Query

State query operations take input or query parameters of some type (q ∈ Query), look at the state, and return an appropriate result value (r ∈ Result) . When specifying such (called StQry, say), we need to identify the circumstances under which we consider the operator to be well-defined — the precondition of the operation. We capture this by a declaration with the following signatures and forms: StQry

: Query → State → Result

StQry[q]Σ

  • =

expression defining query-result pre-StQry

: Query → State → B

pre-StQry[q]Σ

  • =

predicate describing pre-condition There is no specific proof obligation associated with queries, other than the general observation that a query’s result need not be defined or make sense if the pre-condition does not hold.

3BA31 Formal Methods 76

Scribbles 4 : Example Model — Orienteering Event

We construct a model of an orienteering event, for competitors using the SportIdent (SI) System. We first introduce the Types: s ∈ SI

= N

SI (Competitor) Numbers c ∈ Control

= N

Control Numbers r ∈ Course given set of course identifiers A course has a non-empty list of controls:

κ ∈ Courses =

Course

m

→ CONTROL+

A competitor enters a course:

ω ∈ Entries =

SI

m

→ Course

A competitor runs and collects controls in order (hopefully):

ω ∈ Runs =

SI

m

→ Control∗

slide-39
SLIDE 39

3BA31 Formal Methods 77

Scribbles 4 : Orienteering State and Invariant

System state is comprised of Courses, Entries and Runs:

(κ, ω, ρ) ∈ OState

  • =

Courses × Entries × Runs Competitors can only enter courses that are offered (1), and when running must be entered (2), and can only find controls that are out there (3): inv-OState(κ, ω, ρ)

  • =

rng ω ⊆ dom κ

(1)

∧ dom ρ ⊆ dom ω

(2)

∧ controlsof(ρ) ⊆ controlsof(κ)

(3) controlsof

: (A

m

→ P B) → P B

controlsof(α)

  • =

∪/(Pelems(rng α))

controlsof

=

∪/ ◦ Pelems ◦ rng

3BA31 Formal Methods 78

Scribbles 4 : Orienteering Initial State

Initially everything is empty: O0

:

OState O0

  • =

(θ, θ, θ)

This satisfies the invariant, and so we discharge two proof obligations: inv-OState(θ, θ, θ)

= rng θ ⊆ dom θ ∧ dom θ ⊆ dom θ ∧ controlsof(θ) ⊆ controlsof(θ) = ∅ ⊆ ∅ ∧ ∅ ⊆ ∅ ∧ ∅ ⊆ ∅ =

TRUE controlsof(θ)

=

∪/(Pelems(rng θ))

=

∪/(Pelems(∅)

=

∪/(∅)

= ∅

slide-40
SLIDE 40

3BA31 Formal Methods 79

Scribbles 4 : Planning An Event

We now introduce an operation to allow the planner to add a course, and we decide to impose no pre-condition, to allow the planner flexibility to change things: Plan

: (Course × Controls+) → OState → OState

Plan(r, σ)(κ, ω, ρ)

  • =

(κ † {r → σ}, ω, ρ)

pre-Plan

: (Course × Controls+) → OState → B

pre-Plan(r, σ)(κ, ω, ρ)

  • =

TRUE

3BA31 Formal Methods 80

Scribbles 4 : Plan Proof Obligation

We have to show that operation Plan preserves the invariant, when its pre-condition holds: inv-OState(κ, ω, ρ) ∧ pre-Plan(r, σ)(κ, ω, ρ) ⇒ inv-OState(Plan(r, σ)(κ, ω, ρ)) As the pre-condition is vacuously true, we can drop it: inv-OState(κ, ω, ρ) ⇒ inv-OState(Plan(r, σ)(κ, ω, ρ))

slide-41
SLIDE 41

3BA31 Formal Methods 81

Mini-Exercise 2

Does Plan preserve the invariant ? inv-OState(κ, ω, ρ) ⇒ inv-OState(Plan(r, σ)(κ, ω, ρ)) If you think so, give an informal argument as to why. If you think not, give a counter-example showing what goes wrong Due: at start of 12noon Lecture, Thursday, February 15th, 2007.

3BA31 Formal Methods 82

Mini-Exercise 1

Show that

2 + 2

β

→ 4

Hints:

  • 1. Use rightmost-innermost reduction order here.
  • 2. You might want to pull an inner redex out, do the reduction separately, and then plug the result

back in.

  • 3. Try 1 + 1

β

→ 2 as a warm-up!

Due: at start of 12noon Lecture, Thursday, February 15th, 2007.

slide-42
SLIDE 42

3BA31 Formal Methods 83

Mini-Solution 1 2 + 2 =

PLUS 2 2

= (λ m n s z • m s (n s z)) (λ s z • s(s z)) (λ s z • s(s z))

β

→ (λ n s z • (λ s z • s(s z)) s (n s z)) (λ s z • s(s z))

β

→ λ s z • (λ s z • s(s z)) s ((λ s z • s(s z)) s z)

β

→ λ s z • (λ s z • s(s z)) s ((λ z • s(s z)) z)

β

→ λ s z • (λ s z • s(s z)) s (s(s z))

β

→ λ s z • (λ z • s(s z)) (s(s z))

β

→ λ s z • s(s(s(s z))) = 4

3BA31 Formal Methods 84

Mini-Exercise 2

Does Plan preserve the invariant ? inv-OState(κ, ω, ρ) ⇒ inv-OState(Plan(r, σ)(κ, ω, ρ)) If you think so, give an informal argument as to why. If you think not, give a counter-example showing what goes wrong Due: at start of 12noon Lecture, Thursday, February 15th, 2007.

slide-43
SLIDE 43

3BA31 Formal Methods 85

Mini-Solution 2

We’ll do this backwards:

  • 1. Attempt a Proof
  • 2. Test it using QuickCheck
  • 3. Think about the Issue

We should really approach this the other way around!

3BA31 Formal Methods 86

Mini-Solution 2: Proof Attempt (I)

To Prove: inv-OState(κ, ω, ρ) ⇒ inv-OState(Plan(r, σ)(κ, ω, ρ)) Strategy: we assume the antecedent: inv-OState(κ, ω, ρ) in order to show the truth of the consequent: inv-OState(Plan(r, σ)(κ, ω, ρ))

slide-44
SLIDE 44

3BA31 Formal Methods 87

Mini-Solution 2: Proof Attempt (II)

We assume (A1)–(A3′), expanding definitions of inv-OState and controlsof:

(A1) rng ω ⊆

dom κ

(A2)

dom ρ

dom ω

(A3)

controlsof(ρ)

controlsof(κ)

(A3′)

∪/(Pelems(rng ρ)

∪/(Pelems(rng κ)

to show inv-OState(Plan(r, σ)(κ, ω, ρ))

3BA31 Formal Methods 88

Mini-Solution 2: Proof Attempt (III)

inv-OState(Plan(r, σ)(κ, ω, ρ))

“ definition of Plan ” inv-OState(κ † {r → σ}, ω, ρ)

“ definition of inv-OState ”

rng ω ⊆ dom (κ † {r → σ}) ∧ dom ρ ⊆ dom ω ∧ controlsof(ρ) ⊆ controlsof(κ † {r → σ}) ≡

“ property of dom and † ”

rng ω ⊆ dom κ ∪ { r } ∧ dom ρ ⊆ dom ω ∧ controlsof(ρ) ⊆ controlsof(κ † {r → σ})

slide-45
SLIDE 45

3BA31 Formal Methods 89

Mini-Solution 2: Proof Attempt (IV) rng ω ⊆ dom κ ∪ { r } ∧ dom ρ ⊆ dom ω ∧ controlsof(ρ) ⊆ controlsof(κ † {r → σ}) ≡

“ Assumption A1 and S ⊆ T ⇒ S ⊆ T ∪ U, Assumption A2 ” TRUE ∧ TRUE

∧ controlsof(ρ) ⊆ controlsof(κ † {r → σ}) ≡

“ prop. calc., definition of controlsof ”

∪/(Pelems(rng ρ)) ⊆ ∪/(Pelems(rng(κ † {r → σ})))

“ alternative form of override: µ †{a → b} = ⊳

−[a] µ ⊔{a → b} ”

∪/(Pelems(rng ρ)) ⊆ ∪/(Pelems(rng(⊳

−[r]κ ⊔ {r → σ})))

3BA31 Formal Methods 90

Mini-Solution 2: Proof Attempt (V)

∪/(Pelems(rng ρ)) ⊆ ∪/(Pelems(rng(⊳

−[r]κ ⊔ {r → σ}))) ≡

“ property of rng ”

∪/(Pelems(rng ρ)) ⊆ ∪/(Pelems(rng(⊳

−[r]κ) ∪ { σ }))) ≡

“ property/definition of Pf ”

∪/(Pelems(rng ρ)) ⊆ ∪/(Pelems(rng(⊳

−[r]κ)) ∪ { elems σ }) ≡

“ property/definition of ∪/ ”

∪/(Pelems(rng ρ)) ⊆ ∪/(Pelems(rng(⊳

−[r]κ))) ∪ { elems σ }

slide-46
SLIDE 46

3BA31 Formal Methods 91

Mini-Solution 2: Proof Attempt (VI)

∪/(Pelems(rng ρ)) ⊆ ∪/(Pelems(rng(⊳

−[r]κ))) ∪ { elems σ }

Uh-Oh ! From (A3’) we can assume

∪/(Pelems(rng ρ)

∪/(Pelems(rng κ)

But while we are adding in elems σ, we are also potentially taking away whatever controls were mapped to beforehand by r (in term ⊳

−[r]κ).

3BA31 Formal Methods 92

Mini-Solution 2: QuickCheck Test (I)

We can encode the model in QuickCheck and test the property [Show Script]

slide-47
SLIDE 47

3BA31 Formal Methods 93

Mini-Solution 2: QuickCheck Test (II)

The test fails!

Scribbles04> test planInvTest Falsifiable, after 1 tests: G [1] ({G|->[0]},{0|->G},{0|->[0]})

3BA31 Formal Methods 94

Mini-Solution 2: QuickCheck Test (III)

The invariant holds to start: inv-OState({G → 0}, {0 → G}, {0 → 0})

= rng {0 → G} ⊆ dom {G → 0} ∧ dom {0 → 0} ⊆ dom {0 → G} ∧ controlsof({0 → 0}) ⊆ controlsof({G → 0}) = { G } ⊆ { G } ∧ { 0 } ⊆ { 0 } ∧ { 0 } ⊆ { 0 } =

TRUE But not when we are done: inv-OState(Plan(G, 1)({G → 0}, {0 → G}, {0 → 0}))

=

inv-OState({G → 1}, {0 → G}, {0 → 0})

= rng {0 → G} ⊆ dom {G → 1} ∧ dom {0 → 0} ⊆ dom {0 → G} ∧ controlsof({0 → 0}) ⊆ controlsof({G → 1}) = { G } ⊆ { G } ∧ { 0 } ⊆ { 0 } ∧ { 0 } ⊆ { 1 } =

TRUE ∧ TRUE ∧ FALSE

slide-48
SLIDE 48

3BA31 Formal Methods 95

Mini-Solution 2: Think About It

A little thought should lead to the following conclusion: The planner might change a course mid-event, removing some controls, at a point when a runner has already visited them. Nothing in the model said that the planning had to be complete when the event began running. How might we enforce this ?

3BA31 Formal Methods 96

Scribbles 5 : Properties of Maps µ †ν

  • =

⊳ −[dom ν] µ ⊔ν

dom(µ †nu)

= (dom µ) ∪ (dom ν) rng(µ †nu) = (rng µ) ∪ (rng ν)

Counter-example:

µ = {a → 1} rng µ = { 1 } ν = {a → 2} rng ν = { 2 } µ †ν = {a → 2} rng(µ †ν) = { 2 } rng µ ∪rng ν = { 1, 2 } { 2 } = { 1, 2 }

slide-49
SLIDE 49

3BA31 Formal Methods 97

Scribbles 5 : Fixing Plan

The solution is a pre-condition that says that planning can go on as long as no-one has entered: pre-Plan(r, σ)(κ, ω, ρ)

  • =

ω = θ ∧ ρ = θ

Does this preserve the invariant? inv-OState(Σ) ∧ pre-Plan(r, σ)(Σ)

inv-OState(Plan(r, σ)(Σ)) Will controlsof(ρ) remain a subset of controlsof(κ)?

3BA31 Formal Methods 98

Scribbles 5 : Plan Invariant (Thinking)

As the entries and runs maps are empty, by the pre-condition, and planning never adds to them, the stay empty once planning has just finished. So controlsof(ρ) is always empty and hence a subset of controlsof(κ), no matter how often the planner comes back and changes his mind. It looks good.

slide-50
SLIDE 50

3BA31 Formal Methods 99

Scribbles 5 : Plan Invariant (Testing)

We should run this through QuickCheck again [Script]:

Scribbles05> test planInvTest OK, passed 100 tests.

It passes (eventually).

3BA31 Formal Methods 100

Scribbles 5 : Plan Invariant (Proving–I)

We assume (A1)–(A4), expanding definitions of inv-OState and controlsof:

(A1) rng ω ⊆

dom κ

(A2)

dom ρ

dom ω

(A3)

controlsof(ρ)

controlsof(κ)

(A3′)

∪/(Pelems(rng ρ)

∪/(Pelems(rng κ)

(A4) ω = θ ∧ ρ = θ

to show inv-OState(Plan(r, σ)(κ, ω, ρ)) which by (A4) is the same as: inv-OState(Plan(r, σ)(κ, θ, θ))

slide-51
SLIDE 51

3BA31 Formal Methods 101

Scribbles 5 : Plan Invariant (Proving–II)

inv-OState(Plan(r, σ)(κ, θ, θ))

“ definition of Plan ” inv-OState(κ † {r → σ}, θ, θ)

“ definition of inv-OState ”

rng θ ⊆ dom (κ † {r → σ}) ∧ dom θ ⊆ dom θ ∧ controlsof(θ) ⊆ controlsof(κ † {r → σ}) ≡

“ A null map has empty domain and range: dom θ = ∅ = rng θ ”

∅ ⊆ dom (κ † {r → σ}) ∧ ∅ ⊆ ∅ ∧ controlsof(θ) ⊆ controlsof(κ † {r → σ})

3BA31 Formal Methods 102

Scribbles 5 : Plan Invariant (Proving–III) ∅ ⊆ dom (κ † {r → σ}) ∧ ∅ ⊆ ∅ ∧ controlsof(θ) ⊆ controlsof(κ † {r → σ}) ≡

“ ∅ ⊆ S, any S, definitions of controlsof ” TRUE ∧ TRUE ∧ ∪/(Pelems(rng θ) ⊆ controlsof(κ † {r → σ})

“ prop. calc., rngθ = ∅ ”

∪/(Pelems(∅) ⊆ controlsof(κ † {r → σ})

“ prop. calc., Pf∅ = ∅ ”

∪/(∅) ⊆ controlsof(κ † {r → σ})

“ ∪/∅ = ∅ ”

∅ ⊆ controlsof(κ † {r → σ}) ≡

“ ∅ ⊆ S, any S ” TRUE

slide-52
SLIDE 52

3BA31 Formal Methods 103

Scribbles 5 : Other Operations

Orienteers can enter for an offered course, and change their mind when not already out running: Register

:

SI × Course → OState → OState pre-Register(s, c)(κ, ω, ρ)

  • =

c ∈ dom κ ∧ s /

∈ dom ρ

Register(s, c)(κ, ω, ρ)

  • =

(κ, ω † {s → c}, ρ)

An orienteer can run once, once entered: Run

:

SI × Control∗ → OState → OState pre-Run(s, σ)(κ, ω, ρ)

  • =

s ∈ dom ω ∧ s /

∈ dom ρ

Run(s, σ)(κ, ω, ρ)

  • =

(κ, ω, ρ † {s → σ})

A competitor is complete if they got precisely the controls on their course: Complete

:

SI → OState → B Complete(s)(κ, ω, ρ)

  • =

κ(ω(s)) = ρ(s)

3BA31 Formal Methods 104

Haskell Features

We take a brief look at some important Haskell features:

  • Lists
  • Type Polymorphism
  • ADTs (Abstract Data Types)
  • Namespaces
  • Function and Operator Fixity
slide-53
SLIDE 53

3BA31 Formal Methods 105

Lists (I)

Lists are a major datatype in Haskell: Type We use the notation [t] to denote a list whose elements are of type t. Constructing Values There are two basic ways to define a list:

  • We write the empty list as []. It has type [t] for any type t.
  • Given an element x of type t and a list xs of type [t], we can stick the element on the front

(“cons-ing”), written x:xs — the infix colon : is the list constructor. Accessing Values There are two ways to get at the components of a list:

  • Using functions null, head and tail
  • Pattern matching on the two ways to build a list.

3BA31 Formal Methods 106

Lists (II)

Functions null, head and tail can be defined by pattern matching:

null [] = True null (x:xs) = False head (x:xs) = x tail (x:xs) = xs

Note that head and tail are partial, being undefined for the empty-list. The list enumeration notation [x1, x2, . . . , xn] is syntactic sugar for x1 : (x2 : (. . . (xn : []) . . .)) There are a long list of functions available for list manipulation —see the Haskell “Prelude”

http://haskell.org/onlinereport/standard-prelude.html.

slide-54
SLIDE 54

3BA31 Formal Methods 107

Type Polymorphism (I)

Consider the list length function:

length [] = 0 length (x:xs) = 1 + length xs

What type does it have? [ DEMO: Taking List Lengths ]

3BA31 Formal Methods 108

Type Polymorphism (II)

The function length works with lists of any type, and returns an Integer:

length :: [t] -> Int.

This works because it does not manipulate the elements in any way, but simply counts them. Polymorphic (“many-shaped”) types are simply types with parts, represented by type variables, that can take on any type (Haskell uses letters a, b, c,. . . for these). E.g. function reverse ::

[t] -> [t] takes a list of any type and reverses it to give a list

  • f the same type.
slide-55
SLIDE 55

3BA31 Formal Methods 109

Abstract Data Types (I)

We can build our own datatypes by describing them as a collection of Constructors that build a value

  • f the type from other types.

General framework:

data MyType =

C1 t11 t12 · · · t1k1

|

C2 t21 t22 · · · t2k2 . . .

|

Cn tn1 tn2 · · · tnkn Here all the ki, for i ∈ 1 . . . n can be zero or more. This is read as declaring MyType to be either a C1 built from t11 through to t1k1, or a C2 built . . . The names MyType can appear as one of more of the tij (Recursive types allowed).

3BA31 Formal Methods 110

Abstract Data Types (II)

We can define functions on these by pattern-matching: f

::

MyType− > AnotherType f (C1 p11 p12 · · · p1k1)

=

what to do with C1 variant f (C2 p21 p22 · · · p2k2)

=

what to do with C2 variant . . . f (Cn pn1 pn2 · · · pnkn)

=

what to do with Cn variant Here pij is a pattern matching a value of type tij.

slide-56
SLIDE 56

3BA31 Formal Methods 111

Abstract Data Types (III)

Example 1 - Days of the Week. All the ki can be zero:

data Day = Mon | Tue | Wed | Thu | Fri | Sat | Sun isWeekDay :: Day -> Bool isWeekDay Sat = False isWeekDay Sun = False isWeekDay _ = True

The pattern is a wildcard and matches anything. Patterns are tried in the order listed.

3BA31 Formal Methods 112

Abstract Data Types (IV)

Example 2 - Binary Tree of Integers

data BinTreeInt = LeafI Int | BranchI BinTreeInt Int BinTreeInt btiSize (LeafI _) = 1 btiSize (BranchI left _ right) = 1 + btiSize left + btiSize right

So the following is a value of type BinTreeInt

BranchI (LeafI 1) 2 (LeafI 3)

slide-57
SLIDE 57

3BA31 Formal Methods 113

Abstract Data Types (V)

Example 2 - Binary Tree of anything We can put a type parameter (type variable) immediately after the name of our type, which can then be used as on of the tij.

data BinTree t = Leaf t | Branch (BinTree t) t (BinTree t) btSize (Leaf _) = 1 btSize (Branch left _ right) = 1 + btSize left + btSize right

So the following is a value of type BinTree Char

Branch (Leaf ’a’) ’b’ (Leaf ’c’)

3BA31 Formal Methods 114

Namespaces

In Haskell we can classify identifier tokens into two types:

  • Those starting with lowercase alpha followed by alphanum:

a, b1, idWithCapSepWords, identifier with underscores.

These are used for names of functions and variables/values

  • Those starting with uppercase alpha followed by alphanum:

A, B1, True, Leaf, Branch

These are used as names of Types and Type-/Data-Constructors

slide-58
SLIDE 58

3BA31 Formal Methods 115

Function and Operator Fixity

In Haskell we write function/operators in two ways:

  • conventional identifiers (lowercase alpha followed by alphanum:

a, b1, idWithCapSepWords, identifier with underscores.

These are prefix function names by default.

  • Symbols (“funny” characters)

++, <=, :, $!$, $, =:::=.

These are infix operator names by default. Prefix function names (of arity 2) and infix operators can be converted into each other as follows: Normal Use Converted Use

f a b a ‘f‘ b a + b (+) a b

3BA31 Formal Methods 116

Type Classes in Haskell

Haskell allows us to define the notion of type classes:

  • A class defines a number of functions/values over types of that class
  • A type is an instance of a class if instances of those functions and values are defined for that type
  • Type-classes support ad-hoc overloading — the use of a single symbol to represent a number of

different but related functions.

slide-59
SLIDE 59

3BA31 Formal Methods 117

Class Example: Equality

Assume we have builtin functions defining equality for various basic types:

primitive primEqChar :: Char -> Char -> Bool primitive primEqInt :: Int -> Int -> Bool primitive primEqFloat :: Float -> Float -> Bool

We define a class Eq (equality) which requires a symbol == to be defined:

class Eq a where (==), (/=) :: a -> a -> Bool

  • - Minimal complete definition: (==) or (/=)

x == y = not (x/=y) x /= y = not (x==y)

We can now define instances of == for Char, Int and Float:

instance Eq Char where (==) = primEqChar instance Eq Int where (==) = primEqInt instance Eq Float where (==) = primEqFLoat

We can now use == to denote equality between these different types.

3BA31 Formal Methods 118

More Equality

We can define class instances which depend on others. For example, given any type of class Eq (i.e. for which == is defined), we can define equality over lists of that type:

instance Eq a => Eq [a] where [] == [] = True (x:xs) == (y:ys) = x==y && xs==ys _ == _ = False

Given previous definitions, this now means == can be used with arguments of type [Char],

[Int], [Float].

Indeed we can nest such instances, so equality is now also defined for [[Char]], [[[Int]]], etc. In Haskell, == is predefined for all its builtin-types, (except for functions).

slide-60
SLIDE 60

3BA31 Formal Methods 119

Class Example: Ordering

A class definition can depend on another — consider the ordering class Ord which defines <=, >=, among others. We have an ordering result type Ordering, and again some builtin comparison operators:

data Ordering = LT | EQ | GT primitive primCmpChar :: Char -> Char -> Ordering primitive primCmpInt :: Int -> Int -> Ordering primitive primCmpFloat :: Float -> Float -> Ordering

We define the class Ord as follows:

class (Eq a) => Ord a where compare :: a -> a -> Ordering (<), (<=), (>=), (>) :: a -> a -> Bool max, min :: a -> a -> a .... details omitted ....

The complete definition allows us to define everything in terms of either compare or <.

3BA31 Formal Methods 120

Class Example: Show

There is a class Show concerned with converting a value into a printable string:

class Show a where showsPrec :: Int -> a -> ShowS show :: a -> String showList :: [a] -> ShowS

  • - Mimimal complete definition:
  • show or showsPrec

showsPrec _ x s = show x ++ s

A value needs to be of class Show in order for Hugs to show it.

slide-61
SLIDE 61

3BA31 Formal Methods 121

Deriving Instances

For certain builtin classes (Eq, Ord, Show) we can ask the compiler to automatically generate instances for out ADTs:

data BinTreeInt = LeafI Int | BranchI BinTreeInt Int BinTreeInt deriving (Eq,Ord,Show)

Haskell will define equality in the “obvious” way, and come up with an ordering where a Leaf is less than a Branch. Values of type BinTreeInt will print as we would write them in Haskell.

3BA31 Formal Methods 122

Class Example: Numbers

There are a range of classes defining different aspects of numbers. The most prevalent is Num:

class (Eq a, Show a) => Num a where (+), (-), (*) :: a -> a -> a negate :: a -> a abs, signum :: a -> a fromInteger :: Integer -> a

  • - Minimal complete definition:
  • All, except negate or (-)

x - y = x + negate y negate x = 0 - x

slide-62
SLIDE 62

3BA31 Formal Methods 123

VDM♣ in Haskell

We can encode VDM♣ expressions (Sets, Maps, etc) in Haskell

  • IVDM Haskell Module, importing:

– IVDM Set, defining (finite) sets in Haskell; – IVDM Map, defining (finite) maps in Haskell; – IVDM Rel, defining (finite) relations in Haskell. We can use Haskell to evaluate such expressions Haskell acts as an VDM♣ “Calculator”. We cannot use Haskell to prove properties, but we will be able to use it to test them (using a package called QuickCheck). The Haskell implementation makes use of the class system, in particular requiring set and map elements to belong to the Eq and Ord classes.

3BA31 Formal Methods 124

VDM♣ Types in Haskell

Let A, B and C denote VDM♣ types, and a, b and c be the corresponding Haskell types. The following VDM♣ types have the following direct counterparts in Haskell: Type VDM♣ Haskell Boolean

B Bool

Naturals

N Integer, Int (non-negative)

Integers

Z Integer, Int

Rationals

Q Float, Double

Reals

R Float, Double (finite approximations)

Characters

A Char

Sequences A

[a]

Pairs A × B

(a,b)

Tuples A × · · · × C

(a,..,c)

Functions A → B

a -> b

slide-63
SLIDE 63

3BA31 Formal Methods 125

Sets in Haskell

Module: IVDM Set Defines sets and operations for any Haskell instances of the Ord class. VDM♣ type PA represented by Haskell type Set a. The resulting sets are themselves instances of Ord, so we can define sets of sets, etc. Many set operators have Haskell counterparts: VDM♣ Haskell VDM♣ Haskell VDM♣ Haskell

∅ nullSet { x } iSet x ∈ mOf ∪ union ∩ intersect △ symdiff # card

  • p/

sreduce (op,id) Pf smap f

3BA31 Formal Methods 126

Set Examples

Let S1, S2, . . . denote VDM♣ sets while s1, s2, . . . denote their Haskell counterparts. VDM♣ Haskell S1 ∪ S2 ∩ S3

s1 ‘union‘ s2 ‘intersect‘ s3

x ∈ S1

x ‘mOf‘ s1 ⊳ −[S1]S2 sremove s1 s2 (+/ ◦ P#)S1 (sreduce ((+),0) . smap card) s1 { 1, 3, 5 } iSet 1 ‘union‘ iSet 3 ‘union‘ iSet 5 elems [1,3,5]

Functional composition (◦) is denoted in Haskell by . [ DEMO: Sets in Haskell ]

slide-64
SLIDE 64

3BA31 Formal Methods 127

Maps in Haskell

Module: IVDM Map Defines maps and operations for any Haskell instances of the Ord class. VDM♣ type A

m

→ B represented by Haskell type Map a b.

The resulting maps are themselves instances of Ord, so we can define maps of maps, etc. Many map operators have Haskell counterparts: VDM♣ Haskell VDM♣ Haskell VDM♣ Haskell

θ nullMap {x → y} iMap x y ⊔ mextend †

  • verride

⊳ −[S] mremove s ⊳[S] mrestrict

dom

dom rng rng

f

m

→ g mmap f g

3BA31 Formal Methods 128

Map Examples

Let µ1, µ2, . . . denote VDM♣ maps while m1, m2, . . . denote their Haskell counterparts. VDM♣ Haskell

µ1 † µ2 ⊔ µ3 m1 ‘override‘ m2 ‘mextend‘ m3

x ∈ dom µ1

x ‘mOf‘ (dom m1) ⊳ −[S1] µ2 mremove s1 m2 (f

m

→ g) µ1 mmap f g m1 {1 → ‘a’, 5 → ‘e’} iMap 1 ’a’ ‘mextend‘ iMap 5 ’e’ mkMap [(1,’a’),(5,’e’)]

Functional composition (◦) is denoted in Haskell by . [ DEMO: Maps in Haskell ]

slide-65
SLIDE 65

3BA31 Formal Methods 129

Modelling Example (1)

Consider a simple model of a spell-checking Dictionary: D ∈ Dict

= PWord

D0

:

Dict D0

  • =

We can model this in Haskell as

type Wrd = String type Dict = Set Wrd d0 :: Dict d0 = nullSet

3BA31 Formal Methods 130

Modelling Example (2)

We define an operation to insert a word into the dictionary as: Ins

:

Word → Dict → Dict Ins(w)D

  • =

D ∪ { w } The Haskell version:

ins :: Wrd -> Dict -> Dict ins w d = d ‘union‘ iSet w

slide-66
SLIDE 66

3BA31 Formal Methods 131

Modelling Example (3)

We can define word lookup: Lkp

:

Word → Dict → B Lkp(w)D

  • =

w ∈ D and the Haskell equivalent:

lkp :: Wrd -> Dict -> Bool lkp w d = w ‘mOf‘ d

3BA31 Formal Methods 132

Scribbles 6 : A Binary Tree

The binary tree BranchI (LeafI 1) 2 (LeafI 3) can be viewed as BranchI

2

  • 1

3

Leaf Leaf

slide-67
SLIDE 67

3BA31 Formal Methods 133

How To Build (VDM♣) Models

We are now going to explore how to go about building good formal models of systems of interest. The key notions are: Entities things, concepts, individuals, . . . Collections groups, birds of a feather, . . . Relationships connections, interactions, constraints, “knock-on effects” . . . Adequacy Have we captured all relevant aspects of problem ?

3BA31 Formal Methods 134

Entities

  • Basic elements of model
  • What are key attributes: equality ? ordering ? numeric, or identifiers ?
slide-68
SLIDE 68

3BA31 Formal Methods 135

Collections

  • What’s in a collection?
  • Does order or multiplicity matter ?

– Membership ? – Ordering, Priority, Queueing ? – Counting ? Measuring ?

  • Collections of collections ?

3BA31 Formal Methods 136

Relationships

  • Multiplicity again — many/one-to-many/one ?
  • Uniqueness ?
  • “Intentional” vs “Inherent” !
  • Experiment
slide-69
SLIDE 69

3BA31 Formal Methods 137

Scribbles 7 : Entity Examples

Consider a Birthday Book Example: entities are Persons and Birthdays A Person simply needs a unique identifier, for which the only operation need be an equality check: p ∈ Person

  • =

Id The basic type Id is simply an unbounded set of values to be used as identifiers. For a Birthday, we could give it structure (Day/Month/Year), or simply record the day number (1 . . . 366): b ∈ Birthday

  • =

N

Ordering might be useful, to establish which birthday is next. etc.

3BA31 Formal Methods 138

Scribbles 7 : Collection Examples

Ordering Multiplicity Example Math.

X X

Class Attendance Set (PA)

X

  • Balls on Pool Table

Bag/Multiset (A

→ N1)

  • X

Queue Unique Sequences (A∗

! )

  • Text String

Sequences (A∗)

slide-70
SLIDE 70

3BA31 Formal Methods 139

Scribbles 7 : Relationship Examples

Multiplicity Examples Math. Many-to-Many Persons to Holiday Dest. P1...m ↔ 1...nH

P(P × H),

P → PH H → PP relation inverse switches between these two many-to-one Person to Birthday P1...n ↔ 1B P → B One-to-One Student to Id-No S1 ↔ 1N S ֌ N (here ֌ denotes injective fn.) N ֌ S An injective function maps different inputs to different outputs: f : A ֌ B ∧ f(a1) = f(a2)

a1 = a2

3BA31 Formal Methods 140

Mini-Solution 3

Some samples of actual answers will be put here at some point.

slide-71
SLIDE 71

3BA31 Formal Methods 141

Formal Model: Reminder of Goals

State Type Invariant Initial-State Operations State-Change Build vs. Run State-Query

3BA31 Formal Methods 142

Developing/Determining Relationships

  • “Intentional” vs “Inherent” !

Intentional: Relationships we want as modellers Inherent: Relationships we obtain from the mathematics

  • Experiment
slide-72
SLIDE 72

3BA31 Formal Methods 143

Experimentation

  • Pick a structure
  • Write down examples
  • Ask — does it make sense ?
  • If not, figure out how to “stop it happening”

Key idea here: “Initialise & Build”.

3BA31 Formal Methods 144

Operations

  • How does system change?
  • How do users interact with system?
  • What do we want to observe about the system?
  • Under what conditions do certain actions make sense?
slide-73
SLIDE 73

3BA31 Formal Methods 145

Adequacy

  • Have we covered the problem space?
  • Can we represent all relevant entities?
  • Can we describe the key collections ?
  • Have we captured all relationships ?
  • Do we have descriptions (as Operations) of everything relevant that can happen ?

3BA31 Formal Methods 146

State Construction

What do we do if it is not possible to build a safe (invariant preserving) state bit-by-bit ? Issue: can we start with a blank-slate or does the initial system have to be fully formed ?

slide-74
SLIDE 74

3BA31 Formal Methods 147

Real Life: BASE Trusted Gateway

Goal — Trusted Gateway for transferring messages between different security levels, for British Aerospace Systems & Equipment. Approach — Two teams, one conventional, the other using formal methods. Method — Formal team employed VDM-SL, using IFAD Toolkit. Who — T.M.Brookes, J.S.Fitzgerald & P .G.Larsen, “Formal and Informal Specifications of a Secure System Component” in FME’96: Industrial Benefit and Advances in Formal Methods, Springer-Verlag, LNCS 1051, pp214–227, 1996.

3BA31 Formal Methods 148

BASE: Key Results (1)

  • Formal approach spent more time up front in System Design (43% as against 34%).
  • Formal approach uncovered an implicit special condition from requirements.

Informal code had to be re-written at late stage to cope.

  • Formal code was less complex (“McCabe Complexity”)
  • Formal code one-fifth the size of informal code.
slide-75
SLIDE 75

3BA31 Formal Methods 149

BASE: Key Results (2) Formal system started up slower (4 times)

  • 1. Formal System Invariant better understood, so more care was taken by resulting initialisation

code.

  • 2. Not a big issue as the system is meant to stay up and running.

3BA31 Formal Methods 150

BASE: Key Results (3) Formal system throughput higher (almost 14 times !)

  • 1. The informal system had to have a last-minute fix, so the code speed got worse.
  • 2. If code is formally verified, then you don’t need so many run-time checks (array bounds, etc.)
slide-76
SLIDE 76

3BA31 Formal Methods 151

Scribbles 8 : Modelling the “World Cup”

Initial Q&A:

  • Which countries ? Only those in tournament
  • Whole tournament,or just knock-out phase? Stick with knock-out phase

These choices all impact on initial state and invariant

3BA31 Formal Methods 152

Scribbles 8 : Main Concepts

Entities Countries Events Playing a Match Relationships Contest Draw A first stab: c ∈ Country

=

Id State

  • =

PCountry × . . .

The state mentions only those countries still in the contest.

slide-77
SLIDE 77

3BA31 Formal Methods 153

Scribbles 8 : Modelling the Draw

A draw looks like: Ireland

  • Brazil
  • England
  • Samoa
  • Ireland
  • England
  • ?

The green entries shows how the contest might evolve ! We see we have a binary tree of slots, where a slot can be empty or contain a country.

3BA31 Formal Methods 154

Scribbles 8 : Badly Drawn

An invalid draw might be Ireland

  • Brazil
  • England
  • Brazil
  • Japan
  • The picture above violates a number of well-formedness conditions:
  • the winner of a match must be one or other contestant (i.e. not Japan)
  • a country can only occur once in the draw at a level (Brazil can’t occur twice).

We need to find a way to capture this mathematically as an invariant.

slide-78
SLIDE 78

3BA31 Formal Methods 155

Scribbles 8 : Attempt 1 — A Binary Tree

  • The leaf slots (1st round) have countries, while intermediate nodes in the tree may be empty.
  • We use a tree built from leaf-nodes with a country, and match-nodes with left and right sub-trees,

and a slot.

  • A leaf node is either empty, or identifies the Winning country

Draw

  • =

LEAF Country | MATCH Draw Slot Draw Slot

  • =

EMPTY | WINNER Country

3BA31 Formal Methods 156

Scribbles 8 : Attempt 1 Example

Ireland

  • Brazil
  • MATCH(LEAF Ireland) EMPTY (LEAF Brazil)

Ireland

  • Brazil
  • Ireland

MATCH(LEAF Ireland) (WINNER Ireland) (LEAF Brazil) . . . which might then be reduced to . . . Ireland LEAF Ireland

slide-79
SLIDE 79

3BA31 Formal Methods 157

Scribbles 8 : Attempt 1 Invariant

We need to define an invariant that looks (semi-formally) like: invariant(LEAF )

=

TRUE invariant(MATCH d1 slot d2)

=

invariant d1 ∧ invariant d2

∧    

slot = EMPTY

slot = WINNER p where p won d1 ∨ p won d2

    ∧ countriesof d1 ∩ countriesof d2 = ∅

This is a complex invariant. Can it be simplified? One idea is that once a match is decided, we simply replace it by a leaf with the winner, so no slots are required.

3BA31 Formal Methods 158

Scribbles 8 : Attempt 2 — A different Binary Tree

  • The leaf slots have countries.
  • We use a tree built from leaf-nodes with a country, and match-nodes with left and right sub-trees.

Draw

  • =

LEAF Country | MATCH Draw Draw

slide-80
SLIDE 80

3BA31 Formal Methods 159

Scribbles 8 : Attempt 2 Example

Ireland

  • Brazil
  • MATCH(LEAF Ireland) (LEAF Brazil)

. . . which then reduces to . . . Ireland LEAF Ireland

3BA31 Formal Methods 160

Scribbles 8 : Attempt 2 Invariant

We need to define an invariant that looks (semi-formally) like: invariant(LEAF )

=

TRUE invariant(MATCH d1 d2)

=

invariant d1 ∧ invariant d2

∧ countriesof d1 ∩ countriesof d2 = ∅

This is a much less complex invariant. The red stuff about slots has disappeared.

slide-81
SLIDE 81

3BA31 Formal Methods 161

Scribbles 8 : Countries in Tournament

We can easily define the countries involved: countriesof

:

Draw → PCountry countriesof(LEAF c)

  • =

{ c }

countriesof(MATCH d1 d2)

  • =

(countriesof d1) ∪ (countriesof d2)

We now have to consider the initial state, which should be a tree of uniform depth with distinct countries at leaves. We need to consider a partial operation Play : Draw

→ Draw.

We can say what it does when a Match has two leaves: Play(MATCH(LEAF c1) (LEAF c2))

  • =

winner(c1, c2) Here winner is a function that determines the victor (somehow) ! The trick now is to determine which match gets played when.

3BA31 Formal Methods 162

QuickCheck

Haskell module for testing properties of Haskell Programs Properties are defined as functions of one or more variables, returning a value of type Bool

QuickCheck tests a property (using function test !) by generating random test values for each

  • f its arguments, and then evaluating the property.

It repeats this 100 times, or until a False result is returned. In the event of a False result, it prints out the test values that caused the test to fail,

  • therwise it states that the test was Ok.

See http://www.cs.chalmers.se/∼rjmh/QuickCheck/ Simply import QuickCheck to use it.

slide-82
SLIDE 82

3BA31 Formal Methods 163

Monomorphism Type Restriction QuickCheck cannot work with functions of polymorphic type (e.g. [a]), but instead must have a

fully specified type (monomorphic), (e.g. [Int]). This is required because QuickCheck needs to know how to generate and print test values, so it needs a concrete type to work with.

3BA31 Formal Methods 164

Example: Testing List reversal

The function reverse ::

[a] -> [a] reverses its list argument.

If we reverse the list twice, we should get the original back:

reverse (reverse xs) == xs

We can define such a property for lists as:

prop RevRev xs = reverse (reverse xs) == xs

This is just a standard Haskell function definition, so it has type

prop RevRev :: [a] -> Bool.

This is polymorphic, so when we test it we need to give it a concrete type:

test (prop RevRev :: [Int] -> Bool)

[ DEMO: Testing the Double Reverse Property ]

slide-83
SLIDE 83

3BA31 Formal Methods 165

List Reversal, continued

If we reverse a list once, we do not get the original back. Let’s test this:

prop Rev xs = reverse xs == xs test (prop Rev :: [Int] -> Bool)

[ DEMO: Testing the Single Reverse Property ] We see that the failure is indicated by an example of a list which is not equal to its reverse. Properties with a name beginning prop... can be checked automatically by a script called

quickCheck (on Unix systems).

3BA31 Formal Methods 166

Generic Properties (I)

Sometimes we want a property that we can use with a variety of operators. Consider the property of commutativity - an operator ∗ is commutative if x∗y

=

y∗x We can define the property as a function of the operator:

pOpComm op x y = x ‘op‘ y == y ‘op‘ x

To test it we need to supply the operator, and type information:

test (pOpComm (+) :: Int -> Int -> Bool)

[ DEMO: Testing commutativity of + ]

slide-84
SLIDE 84

3BA31 Formal Methods 167

Generic Properties (II)

Consider operator associativity: pOpAssoc op x y z = x ‘op‘ (y ‘op‘ z) ==

(x ‘op‘ y) ‘op‘ z

To test if list concatention is associative ((++) ::

[a] -> [a] -> [a])

we need to type the following:

test (pOpAssoc (++) :: [Int] -> [Int] -> [Int] -> Bool)

It is useful to have shorthands defined commonly used property signatures, e.g. type LC3B = [Char] -> [Char] -> [Char] -> Bool Then our test could use character sequences instead:

test (pOpAssoc (++) :: LC3B)

[ DEMO: Testing associativity of ++ ]

3BA31 Formal Methods 168

Commonly used test types

We use the following shorthands:

B Bool C Char I Int F Float Lx [x] Sx Set x Mxy Map x y

A function Bool->Char->Char->Bool is then given by BCCB. A function with repeated list, set or map types uses a digit to indicate how many, so [Char]->[Char]->[Char]->Bool is denoted by LC3B See IVDM Check for list of types so defined.

slide-85
SLIDE 85

3BA31 Formal Methods 169

Using QuickCheck with VDM♣

Two modules have been defined to integrate QuickCheck with IVDM:

  • IVDM Check

This module describes – how to generate test sets and maps – useful shorthands for commonly used test types – useful generic properties

  • IVDM Test

Use this module to import both QuickCheck and IVDM — it resolves a name-clash (forAll) between the modules, by renaming the IVDM version to be for all

3BA31 Formal Methods 170

Common Generic Properties

The following generic properties have been defined Name Property

pOpComm

x∗y = y∗x

pOpAssoc

x∗(y∗z) = (x∗y)∗z

pOpIdem

x∗x = x

pOpId

i∗x = x = x∗i

pOpZero

x∗z = z = z∗x See IVDM Check for a complete list. [ DEMO: Testing properties using IVDM Test ]

slide-86
SLIDE 86

3BA31 Formal Methods 171

QuickCheck: Class Arbitrary

QuickCheck defines a class called Arbitrary that defines two operators for generating random values of a type:

class Arbitrary a where arbitrary :: Gen a coarbitrary :: a -> Gen b -> Gen b

The type Gen a denotes something capable of generating random values of a given type — by a mechanism we shall ignore for now. We shall also ignore the coarbitrary function, whose role is quite technical.

3BA31 Formal Methods 172

Type Constructor Gen

While the details of how a generator works are complex, there are functions supplied to build generators:

choose :: Random a => (a,a) -> Gen a

Given type a an instance of the standard Random class, return a random value within bound of first argument

elements :: [a] -> Gen a

Pick a value at random from a list

vector :: Arbitrary a => Int -> Gen [a]

Generate a list of arbitrary elements of given length

  • neof ::

[Gen a] -> Gen a

Pick a generator at random from a list, and use that

sized :: (Int -> Gen a) -> Gen a

Takes a generator depending on an integer and generates that integer internally (starts small and gets larger over time).

slide-87
SLIDE 87

3BA31 Formal Methods 173

Some Arbitrary Instances

We can now show some simple instances of Arbitrary:

instance Arbitrary Bool where arbitrary = elements [True, False] instance Arbitrary Int where arbitrary = sized $ \n -> choose (-n,n) instance Arbitrary a => Arbitrary [a] where arbitrary = sized (\n -> choose (0,n) >>= vector)

3BA31 Formal Methods 174

Function test

Function test ::

Testable a => a -> IO() allow us to run tests on any type

belonging to the Testable class.

class Testable a where property :: a -> Property

We have instances of Testable for Bool, Property, and for a -> b where b is an instance of Testable, and a is an instance of Arbitrary and Show. This latter case means we automatically get testable instances of functions of type a1 -> a2 ->

....

  • > ab -> Bool, as long as the ai can be generated arbitrarily.
slide-88
SLIDE 88

3BA31 Formal Methods 175

What is type Property ?

A problem arises when testing implications: P ⇒ Q This is always true when P is false, so benefit arises from test-cases where P does not hold. We have a variation of implication that does not count case where antecedent fails:

(==>) :: Testable a => Bool -> a -> Property

The Property type is best viewed as a special form of Bool. QuickCheck testing of Property looks for 100 cases where antecedent is true, but gives up after 10,000 attempts. [ DEMO: Testing n = m2 ⇒ n · m = m3 ]

3BA31 Formal Methods 176

Exercise (Optional)

Read

http://www.cs.chalmers.se/∼rjmh/QuickCheck/manual.html

slide-89
SLIDE 89

3BA31 Formal Methods 177

Scribbles 9 : Generator Examples choose (1,10) :: Gen Int

generate a random integer between 1 and 10

elements [1..10] :: Gen Int

as above

vector 5 :: Gen [a]

generate list of length 5 of arbitrary elements

sized vector :: Gen [a]

generate list of arbitrary elements of some length, the length chosen starts small and gets larger as this generator is repeatedly used.

3BA31 Formal Methods 178

Scribbles 9 : What is $ for ?

The infix operator $ has a simple definition:

($) :: (a -> b) -> a -> b f $ x = f x

Its main use is to reduce the need for brackets:

sized $ \ n -> choose (-n,n) = sized ( \ n -> choose (-n,n) ) = sized nchoose where nchoose n = choose (-n,n)

slide-90
SLIDE 90

3BA31 Formal Methods 179

Scribbles 9 : Testable Instances

  • Bool is an instance of Testable,
  • Int is an instance of Arbitrary and Show,
  • . . . so Int -> Bool is an instance of Testable.
  • Char is an instance of Arbitrary and Show,
  • . . . so Char -> Int -> Bool is an instance of Testable.
  • Also Char -> Char -> Int -> Bool is an instance of Testable,
  • and Int -> Char -> Char -> Int -> Bool,
  • and . . .

3BA31 Formal Methods 180

Formal Logic

We are now going to present Logic as a Formal System: Symbols Those used for expressions and logic, including ∃, ∀. Well-Formedness Well structured expressions whose type is Boolean. Manipulation Rules Known in formal systems for logic as Axioms and Inference Rules.

slide-91
SLIDE 91

3BA31 Formal Methods 181

Types

We make use of a rich variety of given types and type constructors: S, T ∈ Type

::=

1 | B | A | N | Z | Q | R | C |

PT | T1 × · · · × Tn | T

∗ | S → T | . . .

  • Basic Types:

– “Unit” or “Void” type: 1 = { ∗ } – Booleans: B = { FALSE, TRUE } – Number Types naturals, integers, rationals, real and complex: N, Z, Q, R, C – Characters: A

  • Type Constructors:

– Set of T: PT – Tuples over T1 . . . Tn: T1 × · · · × Tn – Sequence of T: T

– Function from S to T: S → T

3BA31 Formal Methods 182

Expressions

We build expressions denoting values of given type, out of constants of appropriate types (k ∈ Const), variables, (v ∈ Var), tuples, functions and operators applied in various ways: prefix, infix, post-fix, as well as lambda abstractions: e ∈ Expr

::=

k | v | (e1 . . . , en) | e1 e2 . . . en | e1 ⊕ e2 | λ v · e

⊕ ∈ { ∧, ∨, ≡, ⇒, +, −, ∗, /, =, <, >, ≤, ≥, . . . }

We often write function application without brackets, so f(x) and f x are equivalent. Applying a function to many argument brackets to the left, so f x y z should be interpreted as ((f x) y) z. Usually we let expression types be determined from context, but if necessary we can annotate (sub-)expressions with types, i.e.

(x : Q)2 = 2

instead of x2 = 2

slide-92
SLIDE 92

3BA31 Formal Methods 183

Value of Expressions

The value of an expression is determined by the values we associate with its free variables. We call the association of values with variables an Interpretation or Environment, and is usually modelled as a finite map (Env) from variables to values:

ρ ∈ Env =

Var → Value Here the ‘type’ Value should considered as the union of all possible types. Given an environment, it is possible to determine the value for an expression in a systematic way. This is captured by a “meaning function” (E [

[−] ]) which describes how an expression should be

evaluated given an environment:

E [ [−] ] :

Env → Expr → Value Another way of thinking about this is to consider an expression (with free variables) as a function from an environment to a value.

3BA31 Formal Methods 184

Expression Meaning Example

Consider the expression: (x < 3 ∨ y2 > z) : B. Its value depends on the values of x, y and z (which is why it makes sense to think of the expression as having type Env → Value). Assume the environment is ρ = {x → 4, y → −3, z → 100}. We can evaluate the expression in a number of ways: by applying E [

[−] ] (left), or by using ρ as a

substitution (right):

Eρ[ [x < 3 ∨ y2 > z] ] (x < 3 ∨ y2 > z)ρ Eρ[ [x < 3] ] ∨ Eρ[ [y2 > z] ] (x < 3 ∨ y2 > z)[4/x, −3/y, 100/z] Eρ[ [x] ] < Eρ[ [3] ] ∨ Eρ[ [y2] ] > Eρ[ [z] ] (4 < 3 ∨ (−3)2 > 100) ρ(x) < 3 ∨ Eρ[ [y] ]Eρ[

[2] ] > ρ(z)

(FALSE ∨ 9 > 100) 4 < 3 ∨ ρ(y)2 > 100 (FALSE ∨ FALSE)

FALSE ∨ (−3)2 > 100 FALSE FALSE

slide-93
SLIDE 93

3BA31 Formal Methods 185

Atomic Predicates

An Atomic Predicate is simply an expression whose overall type is Boolean. P ∈ Pred

::=

e : B | . . . As such, a predicate can be viewed as a function from an environment to the the values true or false. Pred

:

Env → B The previous expression example was in fact that of a predicate. We have two special predicates: true and false which always return TRUE and FALSE respectively, regardless of the environment. So, while the expression TRUE, can be interpreted as the predicate true, but we do need to remember the type-distinction between TRUE : B and true : Env → B

3BA31 Formal Methods 186

Identities

Predicate Expressions of the form: e1

=

e2 where e1 and e2 have the same type, are known as Identities. Identities play a major role in what is to come.

slide-94
SLIDE 94

3BA31 Formal Methods 187

Predicate Logic Syntax

Given atomic predicates we can build a richer language of predicates: Well-founded formulas (P) of predicate calculus: P ∈ Pred

::=

true | false

|

e : B — the atomic predicates

| ¬ P |

P1 op P2,

  • p ∈ { ∨, ∧, ⇒, ≡ }

| Q x : T • P, Q ∈ { ∀, ∃, ∃! }

We can give a meaning to predicates in much the same way as we did for expressions.

3BA31 Formal Methods 188

Predicate Meanings

The predicate meaning function, given an environment, maps a predicate to true or false:

P [ [−] ] :

Env → Pred → B For everything except the quantifiers, its definition is straightforward:

Pρ[ [true] ]

  • =

TRUE

Pρ[ [false] ]

  • =

FALSE

Pρ[ [e] ]

  • =

Eρ[ [e] ] Pρ[ [¬ P] ]

  • =

not Pρ[

[P] ] Pρ[ [P1 ∧ P2] ]

  • =

Pρ[ [P1] ] and Pρ[ [P2] ] Pρ[ [P1 ∨ P2] ]

  • =

Pρ[ [P1] ] or Pρ[ [P2] ] Pρ[ [P1 ⇒ P2] ]

  • =

Pρ[ [P1] ] implies Pρ[ [P2] ] Pρ[ [P1 ≡ P2] ]

  • =

Pρ[ [P1] ] equivales Pρ[ [P2] ]

slide-95
SLIDE 95

3BA31 Formal Methods 189

Manipulating Environments

We define the domain of an environment (dom ρ) as the set of all variables mentioned in ρ. We can use one environment (ρ′) to override part or all of another (ρ), indicating this by ρ † ρ′. The bindings in the second map, extend and take precedence of those in the first map — e.g.:

{a → 1, b → 2, c → 3} † {c → 33, d → 44} = {a → 1, b → 2, c → 33, d → 44}

3BA31 Formal Methods 190

Meaning for Quantifiers

We can now give the meaning for the quantifiers as:

Pρ[ [∀ x : T • P] ]

  • =

for all ρ′ such that dom ρ′ = { x } we have Pρ†ρ′[

[P] ] = TRUE Pρ[ [∃ x : T • P] ]

  • =

for at least one ρ′ such that dom ρ′ = { x } we have Pρ†ρ′[

[P] ] = TRUE Pρ[ [∃!x : T • P] ]

  • =

for exactly one ρ′ such that dom ρ′ = { x } we have Pρ†ρ′[

[P] ] = TRUE

To evaluate a quantifier, we need to generate all possible environments ρ′ involving the bound variable. Note that if T is infinite, then the first and last cases above cannot be computed at all, and we would

  • nly get an answer to the middle case if the answer was actually true.

In general, in order to reason about quantifiers we need to use Axioms and Inference Rules.

slide-96
SLIDE 96

3BA31 Formal Methods 191

Inference Rules

Inference rules describe how we may deduce the truth of one or more predicates (the consequents) from the truth of a collection of other predicates (the antecedents): antecedent 1

. . .

antecedent n

[ side condition ]

consequent 1

. . .

consequent m

3BA31 Formal Methods 192

Inference Examples

The modus ponens law: p p ⇒ q q The ∧-introduction law: p q p ∧ q

slide-97
SLIDE 97

3BA31 Formal Methods 193

Inference Examples (revisited)

Sometimes the antecedents are listed on one line, with a large gap inbetween The modus ponens law revisited: p p ⇒ q q The ∧-introduction law revisited: p q p ∧ q

3BA31 Formal Methods 194

Axioms

Axioms are predicates which are true in their own right, and are simply shown by inference rules with no antecedents: axiom For example. the law of the excluded middle: p ∨ ¬ p Often axioms are simply written without any line: p ∨ ¬ p

slide-98
SLIDE 98

3BA31 Formal Methods 195

Reading Inference Rules

One way to read a rule like A1 A2 C is as saying that in order to prove C we must prove both A1 and A2. Another way is to read it as stating that A1 and A2 imply the truth of C.

3BA31 Formal Methods 196

Using Inference Rules with Predicates

There are a number of different ways in which inference rules can be used to define laws of reasoning for predicates. We shall adopt a particular form that is suitable for us, based on the notion of Sequents. A Sequent has the syntax: P1, P2, . . . Pn

Q and is interpreted as asserting that from predicates P1, P2, through Pn that we can deduce Q. Sequents can be thought of as an inference rules themselves, but we are instead going to treat them as meta-predicates which our inference rules allow us to manipulate. A meta-predicate is a predicate about predicates — they are not a part of our predicate language, but stand apart, as a means of talking about our predicates. In general we use Γ to denote lists of predicates, so shorthand for a sequent is Γ ⊢ Q

slide-99
SLIDE 99

3BA31 Formal Methods 197

Hypotheses

The predicates to the left of ⊢ are called the hypotheses, and sometimes we give the numbers of the form Hn where n ranges from 1 upwards. A sequent with the nth hypothesis A singled out will be written as

Γ, Hn:A ⊢ B

A sequent may have no hypotheses, in which case we write it simply as

⊢ Q

3BA31 Formal Methods 198

Where do hypotheses come from?

Typically the hypotheses at the start of a proof are based on the definitions of the entities referred to in the consequent: If we define f(n + 1)

= (n + 1) ∗ f(n) (say), then we can start any proof using this definition with

the hypothesis f(n + 1) = (n + 1) ∗ f(n)

⊢ . . .

Note that in principle there could be very many of these, as there may well be definitions and laws associated with every mathematical operator mentioned.

slide-100
SLIDE 100

3BA31 Formal Methods 199

Goals

The predicate to the right of ⊢ is called the goal. The proof process will usually result in the proof of a goal turning into one or more proofs of sub-goals. The exception is when an axiom is found that immediately proves the goal.

3BA31 Formal Methods 200

Scribbles 10 : Truth Depends on Types

Can x2 = 2 be true for some value of x ? It depends on its type.

(x : Q)2 = 2 is always false as there is no rational square-root of 2. (x : R)2 = 2 evaluates to true if x = √ 2.

slide-101
SLIDE 101

3BA31 Formal Methods 201

Scribbles 10 : Evaluating (x : Q)2 = 2

Consider environment ρ = {a → 17, b → −99, x → 5} We evaluate (x : Q)2 = 2 with respect to ρ above by substituting 5 for x where it is free in the expression, so we get 52 = 2, which we can then reduce down to FALSE. A different environment, a different calculation, possibly a different answer: If ρ = {x → 2} then (x : Q)2 = 2 becomes 22 = 2, i.e. also FALSE. If the type differs, yet another answer is possible: Evaluating (x : R)2 = 2 w.r.t. ρ = {x →

√ 2}

gives (

√ 2)2 = 2 which is TRUE.

3BA31 Formal Methods 202

Scribbles 10 : Evaluating a Quantifier

Consider ∀x : Nat • x > 5. We need an environment ρ′ whose domain is { x }, i.e of the form {x → . . .}. Then x > 5 must evaluate to TRUE in any environment of the form ρ † {x → . . .}. This fails for values of . . . less than 6. If we have ∃x : Nat • x > 5, then the body need only be true for one choice of . . ., so for example, take ρ′ = {x → 6}.

slide-102
SLIDE 102

3BA31 Formal Methods 203

Mini-Exercise 4

Evaluate the expression

(x ≤ 3 ∧ x = 100) ⇒ (x ≤ x2)

where x : N, in an environment of your choice. Does your choice of environment matter ? Due: at start of 12noon Lecture, Thursday, March 1st, 2007.

3BA31 Formal Methods 204

3BA31 Project

This is project work to be done as part of 3BA31. The project is split into a number of phases, each phase containing a number of deliverables. The phase is the unit of submission. The phases currently specified and their deadlines are: ATC Specification Thursday 5th April 2007, 3pm.

slide-103
SLIDE 103

3BA31 Formal Methods 205

Submission Procedure

  • 1. A hardcopy of all the deliverables (including Haskell code), clearly identified with Name and

Student-Id, must be left into the Computer Science Office in the O’Reilly Institute by the deadline.

  • 2. All the Haskell code associated with a phase must also be emailed to

Andrew.Butterfield@cs.tcd.ie,

with a Subject: line of “3BA31: phase-name”

  • 3. The files emailed must be identical to the hard copies submitted.
  • 4. A valid submission consists of both the hardcopy and the email. The hardcopy is the formal

record of submission.

  • 5. Emails will not be acknowledged. However, after the deadline has passed, in the event of any

problem, you may be asked to re-send the e-mail.

3BA31 Formal Methods 206

Overview

We want to model an aspect of an air-traffic control (ATC) system, namely the link between aircraft and their controllers. Basically an aircraft must have exactly one assigned on-duty controller at all times while it is airborne. Conversely however, a controller on duty can have more than one aircraft assigned to them. We wish to model a situation were aircraft can plan and execute flights, meeting the safety requirement above, while also allowing controllers to come on and off duty, while some planes are airborne.

slide-104
SLIDE 104

3BA31 Formal Methods 207

Actions

The key actions that can occur are:

  • nduty A controller can come on duty
  • ffduty A controller can go off duty

contact An aircraft can request a controller takeoff An aircraft can take-off handover An aircraft can be transferred from one controller to another land An aircraft can land signoff An aircraft can release its assignment to a controller.

3BA31 Formal Methods 208

Observations

It should also be possible to determine the following information about the state: controllers the controllers currently on duty airborne the aircraft currently airborne handler for a given aircraft, the controller currently responsible of that aircraft.

slide-105
SLIDE 105

3BA31 Formal Methods 209

Deliverables

The ATC Specification deliverables are the following: VDM♣ Model a handwritten (or LaTeX’d) version of the model in mathematical (VDM♣) notation.

IVDM Model the previous model implemented in Haskell/IVDM.

QuickCheck Test tests of all the proof obligations using QuickCheck. Proofs Formal Proofs of the proof obligations for the initial state and the takeoff, handover and signoff operations, done according to the format specified in class.

3BA31 Formal Methods 210

Mini-Solution 4

Lets take ρ = {x → 99}.

Eρ[ [(x ≤ 3 ∧ x = 100) ⇒ (x ≤ x2)] ] = Eρ[ [x ≤ 3 ∧ x = 100] ] ⇒ Eρ[ [x ≤ x2] ] = Eρ[ [x ≤ 3] ] ∧ Eρ[ [x = 100] ] ⇒ Eρ[ [x] ] ≤ Eρ[ [x2] ] = Eρ[ [x] ] ≤ Eρ[ [3] ] ∧ Eρ[ [x] ] = Eρ[ [100] ] ⇒ 99 ≤ Eρ[ [x] ]Eρ[

[2] ]

= 99 ≤ 3 ∧ 99 = 100 ⇒ 99 ≤ 992 =

FALSE ∧ FALSE ⇒ 99 ≤ 9801

=

FALSE ⇒ TRUE

=

TRUE The same answer is obtained, no matter what value x takes. The lhs of the implication is always false, so the whole implication is always true.

slide-106
SLIDE 106

3BA31 Formal Methods 211

Sequents are proof objects

We are trying to prove sequents of the form: H1, H2, . . . Hn ⊢ G

  • r

Γ ⊢ G

  • The lefthand predicates Γ = H1, H2, . . . Hn make up the hypotheses.
  • The righthand predicate G is the goal.

In general we have a starting set of hypotheses and a desired goal, and we apply inference rules moving from bottom upwards, to get a proof. We want a proof style that allows us to concentrate on the goal, while keeping the hypotheses in the background.

3BA31 Formal Methods 212

Introducing the Inference Rules

The axioms and inference rules of logic come in a wide range of flavours and styles. E.g. lots of axioms and a few inference rules vs few axioms and many inference rules. We shall present the rules associated with the theorem prover Sparkle that comes bundled with the functional programming language Clean. This is a logic and prover tailored for reasoning about functional programs.

slide-107
SLIDE 107

3BA31 Formal Methods 213

Classifying Inference Rules

It is worthwhile distinguishing inference rules as either axioms, or else according to what changes — hypotheses, goals or both: Axioms Exact; Trivial; ExFalso; Absurd. Reduce; Reflexive; Hypothesis Only Rewrite ↔ Hn in Hm; Symmetric Hn; Discard; Split Deep Hn; Case Deep Hn; Apply Hn to Hm; SplitIff Hn; Specialize; Witness for Hn. Goal Only Extensionality; Rewrite ↔ Hn; Symmetric; Transitive; Split Deep; Left; Right; Cut; Apply Hn; SplitIff; Introduce x; Generalise; MoveQuantors; Witness. Both Assume; Contradiction; Introduce Hn. The highlighted rules manipulating only the hypotheses are mirror images of corresponding rules (also highlighted) which only change the goal. The last three rules involve interactions between hypotheses and conclusions - worth looking at closely

3BA31 Formal Methods 214

The Axioms (I)

The first two axioms deal with really easy cases where the goal is actually one of the hypotheses, or is the always true predicate itself:

Exact Hn Γ, Hn:A ⊢ A Trivial Γ ⊢ true

slide-108
SLIDE 108

3BA31 Formal Methods 215

The Axioms (II)

The next set of axioms deal with the outcome of reducing redexes and the fact that expressions and predicates are equal to themselves:

Reduce Γ ⊢ (λ v · e1)e2 = e1[e2/v] Reduce Γ ⊢ (λ v · e v) = e Reflexive Γ ⊢ A = A Reflexive Γ ⊢ A ≡ A

3BA31 Formal Methods 216

Axioms (III) — Arithmetic/Prop. Calc

If we can prove e1 = e2 using the laws of arithmetic, then we get the following axiom:

Arithmetic Γ ⊢ e1 = e2

If T is a propositional tautology (always true), we can deduce:

Tautology Γ ⊢ T

All tautologies can be proved within our system of inference rules, but it is simpler to simply pull them in as axioms in our scheme.

slide-109
SLIDE 109

3BA31 Formal Methods 217

The Axioms (IV)

The following axioms seem paradoxical, as they basically capture the notion that if our hypotheses are contradictory, then we can prove anything.

ExFalso Γ, false ⊢ B Absurd Hn Hm Γ, Hn:A, Hm:¬A ⊢ B

This is a fundamental feature of any logic. Surprisingly, these axioms can actually help prove something useful.

3BA31 Formal Methods 218

Inference Rules (Both)

We now describe the inference rules that change both hypotheses and goals.

slide-110
SLIDE 110

3BA31 Formal Methods 219

Introduce Hn

Introduce Hn Γ, Hn:A ⊢ B Γ ⊢ A ⇒ B

This rule is a key one when manipulating hypotheses: when trying to prove A ⇒ B, often the best way is to add A to the hypotheses, and then use it (as well as the other hypotheses) to prove B. We will make much use of this rule, often at the very start of a proof to separate out antecedents as hypotheses, in order to have as simple a conclusion as possible.

3BA31 Formal Methods 220

Assume A

Assume A Γ, A ⊢ B Γ ⊢ A Γ ⊢ B

This rule allows us to introduce an assumption A to help prove B, provided we also get around to proving A true in its own right.

slide-111
SLIDE 111

3BA31 Formal Methods 221

Contradiction

Contradiction Γ, A ⊢ false Γ ⊢ ¬A Contradiction Hn Γ, ¬A ⊢ A Γ, Hn:¬A ⊢ B

To prove ¬ A, simply introduce A as a hypothesis, and see if you can prove false. The second rule has a sinister aspect, if it is read top-down: If given a bunch of hypotheses Γ and

¬ A, we can prove A, then we can use those hypotheses to prove anything (arbitrary B).

3BA31 Formal Methods 222

Inference Rules (One-Sided)

We now describe the inference rules that only change the goals or hypotheses.

slide-112
SLIDE 112

3BA31 Formal Methods 223

Propositional Inference (I) Contradiction Γ, A ⊢ false Γ ⊢ ¬A Contradiction Hn Γ, ¬A ⊢ A Γ, Hn:¬A ⊢ B Split Deep Hn Γ, A, B ⊢ C Γ, Hn:A ∧ B ⊢ C Split Deep Γ ⊢ A Γ ⊢ B Γ ⊢ A ∧ B

3BA31 Formal Methods 224

Propositional Inference (II) Case Deep Hn Γ, A ⊢ C Γ, B ⊢ C Γ, Hn:A ∨ B ⊢ C Left Γ ⊢ A Γ ⊢ A ∨ B Right Γ ⊢ B Γ ⊢ A ∨ B

slide-113
SLIDE 113

3BA31 Formal Methods 225

Predicate Inference (I) Introduce x Γ ⊢ A Γ ⊢ ∀ x.A

(x not free in Γ)

Generalize x Γ ⊢ ∀ x.B Γ ⊢ B (x free in B) Specialize Hn with t Γ, A[t/x] ⊢ B Γ, Hn: ∀ x.A ⊢ B

3BA31 Formal Methods 226

Predicate Inference (II) MoveQuantors In Γ ⊢ A ⇒ ∀ x.B Γ ⊢ ∀ x.A ⇒ B

(x not free in A)

MoveQuantors Out Γ ⊢ ∀ x.A ⇒ B Γ ⊢ A ⇒ ∀ x.B

(x not free in A)

Witness t Γ ⊢ A[t/x] Γ ⊢ ∃ x.A Witness for Hn Γ, A ⊢ B Γ, Hn: ∃ x.A ⊢ B

(x not free in Γ, B)

slide-114
SLIDE 114

3BA31 Formal Methods 227

Induction Induction n Γ ⊢ P(0) Γ ⊢ P(n) ⇒ P(n + 1) Γ ⊢ ∀ n : N • P(n) Induction xs Γ ⊢ P() Γ ⊢ P(xs) ⇒ P(x : xs) Γ ⊢ ∀ xs : A∗ • P(xs)

(x new)

Induction S Γ ⊢ P(∅) Γ ⊢ P(S) ⇒ P({ x } ⊔ S) Γ ⊢ ∀ S : PA • P(S)

(x new)

Induction m Γ ⊢ P(θ) Γ ⊢ P(µ) ⇒ P({a → b} ⊔ µ) Γ ⊢ ∀ µ : A

m

→ B • P(µ)

(a, b new) Note: ⊔ is set-union defined only for disjoint arguments, or map extension, defined only for maps with disjoint domains.

3BA31 Formal Methods 228

Concentrating on the Goal

We shall simply record hypotheses as they arise, noting if they are only associated with a subproof Only one rule shrinks the hypothesis set (Discard), and this rule only leads to a successful proof if that hypothesis was not required. In general we can ignore this inference rule. We shall work mainly by transforming goals step-by-step, and will write proofs of the form: goal rel “ reason why rel holds ” intermediate-goal-1 rel′ “ reason why rel′ holds ” intermediate-goal-2 The relationships between goals will usually be either =, ≡, ⇒or ⇐.

slide-115
SLIDE 115

3BA31 Formal Methods 229

Inference and Implication

The inference rule

RuleName Γ ⊢ B Γ ⊢ A

states that if we can show B is a consequence of Γ, then we can conclude that A is also a consequence, i.e., that B implies A (given Γ). This is written as follows in our proof style: Assuming Γ, A

“ RuleName ” B

3BA31 Formal Methods 230

Axioms and Implication

The axiom

RuleName Γ ⊢ A

states that we always assert A (given Γ). This is written as follows in our proof style: Assuming Γ, A

“ RuleName ” true We exploit the fact that in propositional calculus (TRUE ⇒ A) ≡ A

slide-116
SLIDE 116

3BA31 Formal Methods 231

Branching in Proofs

Some inference rules require us to prove more than one sequent in order to establish some goal (e.g.) Case Deep Hn or Split Deep. When can build proof-trees up using the inference rule notation, but this rapidly gets very clumsy: . . .

Γ ⊢ A

. . .

Γ ⊢ B

. . .

Γ ⊢ C Γ ⊢ B ∧ C [Split Deep] Γ ⊢ A ∧ (B ∧ C) [Split Deep]

The vertical dots show further proof steps rising above, with possibly even more branching. We prefer a linear way of writing such proof — best done by “section numbering”

3BA31 Formal Methods 232

Section Numbering

We give a proof a short name, number or letter to refer to it (e.g. P). If a proof requires a number of cases, each case gets a “sub-name”, which we append after the main proof name, separated by a dot. For further sub-proofs we add extra sub-names as required. P :Assume Γ to prove A ∧ (B ∧ C): A ∧ (B ∧ C)

“ Split Deep ” P.1 and P.2 where P .1 assumes Γ to show A, and P .2 assumes Γ to show B ∧ C For P .2 we would proceed: B ∧ C

“ Split Deep ” P.2.1 and P.2.2 and so on . . .

slide-117
SLIDE 117

3BA31 Formal Methods 233

Identities

Many properties we shall want to prove, will be identities (A = B or C ≡ D). A proof of an arbitrary predicate P can often be turned into an identity, by simply choosing to prove P ≡ TRUE instead. The axioms involving identities are: Reduce, Reflexive. The inference rules regarding identities are: Extensionality, Symmetric, SplitIff, Transitive, Rewrite Consider a proof of id(id(y)) = y, given the definition id

= λ x · x

The sequent we want to prove is: id = λ x · x ⊢ id(id(y)) = y

3BA31 Formal Methods 234

Full Blown Tree Proof

We write Γ as shorthand for H1 : id = λ x · x

Γ ⊢ (λ x·x)((λ x·x)(y))=(λ x·x)(y) [Reduce] Γ ⊢ (λ x·x)(y)=y [Reduce] Γ ⊢ (λ x·x)((λ x·x)(y))=y [Transitive] Γ ⊢ id(id(y))=y [Rewrite→H1]

The proof is complicated to read, and to write down. It definitely looks like using a pile-driver to crack a peanut !

slide-118
SLIDE 118

3BA31 Formal Methods 235

Linear Proof (1st attempt)

We assume H1

:

id = λ x · x to prove P :id(id(y)) = y id(id(y)) = y

“ [Rewrite→H1] ”

(λ x · x)((λ x · x)y) = y ⇐

“ [Transitive] ” P.1 and P.2 We now need separate proofs of P.1 :(λ x · x)((λ x · x)(y)) = (λ x · x)y and P.2 :(λ x · x)y = y.

3BA31 Formal Methods 236

Linear Proof (1st attempt, cont)

Just for completeness, we complete P .1 and P .2 We assume H1 : id = λ x · x to prove P.1 :(λ x · x)((λ x · x)y) = (λ x · x)y

(λ x · x)((λ x · x)y) = (λ x · x)y ⇐

“ [Reduce] ” TRUE We assume H1 : id = λ x · x to prove P.2 :(λ x · x)(y) = y

(λ x · x)(y) = y ⇐

“ [Reduce] ” TRUE

slide-119
SLIDE 119

3BA31 Formal Methods 237

Implicit use of Identity-related Rules

When we reason about identities, we can safely make implicit use of the rules of Reflexivity, Symmetry, and Transitivity. Most lines in our proofs are then uses of Reduce or Rewrite. A proof in our style can be transformed into a fully formal proof using inference rules.

3BA31 Formal Methods 238

Identity-centric Proof

We assume H1

:

id = λ x · x to prove id(id(y) = y id(id(y))

=

“ defn. id (or [Rewrite→H1]) ”

(λ x · x)((λ x · x)(y)) =

“ β-reduction (or [Reduce]) ”

(λ x · x)(y) =

“ β-reduction (or [Reduce]) ” y This proof looks good, but how does it relate to our inference rules ?

slide-120
SLIDE 120

3BA31 Formal Methods 239

Relating Equality Axioms and Identities

An axiom like

Γ ⊢ A = B [RuleName]

becomes a proof segment like: A

=

“ [RuleName] ” B

3BA31 Formal Methods 240

Relating Transitivity and Identities

The transitive rule

Γ ⊢ A = B Γ ⊢ B = C Γ ⊢ A = C [Transitive B]

becomes a proof segment like A

=

“ proof segment for Γ ⊢ A = B ” B

=

“ proof segment for Γ ⊢ B = C ” C

slide-121
SLIDE 121

3BA31 Formal Methods 241

Proof Re-Use

Assume that we have managed to prove Γ1 ⊢ G1. We can use G1 as a hypotheses in another proof provided the other hypotheses cover Γ1:

Γ1 ⊆ Γ2 Γ2, G1 ⊢ G2 Γ2 ⊢ G2 [proof reuse]

In fact this is simply an instance of inference rule [Assume G1] when Γ1 = Γ2:

Γ1 ⊢ G1 Γ1, G1 ⊢ G2 Γ1 ⊢ G2 [Assume G1]

3BA31 Formal Methods 242

Induction

We can perform induction over natural numbers, for which the inference rule is

Γ ⊢ P(0) Γ ⊢ P(n) ⇒ P(n + 1) Γ ⊢ ∀ n : N • P(n) [Induction n]

We see that we generate two sub-proofs, usually named “base” and “step” respectively, so a proof P by induction will involve sub-proofs of P .base and P .step. We can also do induction over other structures, such as sequences and ADTs, as will be explained later.

slide-122
SLIDE 122

3BA31 Formal Methods 243

Proving with ADTs

We have seen ADTs in Haskell:

data MyType =

C1 t11 t12 · · · t1k1

|

C2 t21 t22 · · · t2k2 . . .

|

Cn tn1 tn2 · · · tnkn and we can use these type definitions in VDM♣: MyType

  • =

C1 t11 t12 · · · t1k1

|

C2 t21 t22 · · · t2k2 . . .

|

Cn tn1 tn2 · · · tnkn We need to be able reason about these.

3BA31 Formal Methods 244

ADT Semantics

Let us consider a simple ADT, for a binary tree of integers: BinTree

  • =

LEAF Z

|

BRANCH BinTree Z BinTree This is syntactic sugar for the following recursive type definition: BinTree

  • =

Z + (BinTree × Z × BinTree)

LEAF

  • =

1

BRANCH

  • =

2

The + symbol here denotes disjoint union or sum, pronounced “or” when used as above to define a type. We are saying that a BinTree is either an integer, or a triple composed of an integer sandwiched between two BinTrees. The two variants are distinguished by tags which denote numbers, and the constructor names are mapped to the corresponding numbers.

slide-123
SLIDE 123

3BA31 Formal Methods 245

Disjoint Sum

The disjoint union of two sets is a way of combining sets so we can always tell which set an element came from, even if the sets have elements in common. This is achieved by tagging elements in the disjoint union to indicate their origin: A1 + A2 + · · · + An

  • =

({ 1 } × A1) ∪ ({ 2 } × A2) ∪ . . . ∪ ({ n } × An)

(Some definitions of disjoint union use tags from { 0 . . . n − 1 } Example:

{ a, b } + { b, c } = { (1, a), (1, b), (2, b), (2, c) }

Even though b occurs in both sets, we can still distinguish the two occurrences.

3BA31 Formal Methods 246

Enumerations as ADTS

How do we handle ADTS or where there are constructors with no associated data, e.g. Day

  • =

MON | TUE | . . . | SUN List

  • =

NIL | CONS Z List ? We assume a “unit” datatype called 1 with one element ∗, which we use in the disjoint sum: 1

  • = { ∗ }

In Haskell both 1 and ∗ are written as (). Our definitions become: Day

  • =

1 + 1 + 1 + 1 + 1 + 1 + 1 MON = 1, TUE = 2, . . . List

  • =

1 + (Z × List) NIL = 1, CONS = 2.

slide-124
SLIDE 124

3BA31 Formal Methods 247

A Notational Subtlety (i)

We could have defined the binary tree slightly differently: BinTree

  • =

LEAF Z | BRANCH BinTree Z BinTree

  • r

BinTree

  • =

LEAF Z | BRANCH (BinTree × Z × BinTree) Both translate to the same disjoint union. So what is the difference, if any?

3BA31 Formal Methods 248

Constructors as Functions

Haskell and VDM♣ view data constructors as functions, taking arguments of the type specified in the type definition, and returning a result of the type being defined. If we define: MyType

  • =

. . . | Ci ti1 ti2 · · · tiki | . . .

Then Ci is a function of type: Ci

:

ti1 → ti2 → · · · → tiki → MyType We have two views of a data constructor Ci: Tag the underlying semantics views a constructor as a tag number in a disjoint union, as does the Haskell implementation of that type Function the mathematical/Haskell programmer view is of a constructor as a function that builds a value of the type from appropriate arguments. We want to use the logic at the mathematical/programmer level.

slide-125
SLIDE 125

3BA31 Formal Methods 249

A Notational Subtlety (i)

We could have defined the binary tree slightly differently: BinTree

  • =

LEAF Z | BRANCH BinTree Z BinTree

  • r

BinTree

  • =

LEAF Z | BRANCH (BinTree × Z × BinTree) Both translate to the same disjoint union. So what is the difference, if any?

3BA31 Formal Methods 250

A Notational Subtlety (ii)

Now our alternive type definition are different: BinTree

  • =

LEAF Z | BRANCH BinTree Z BinTree LEAF

: Z → BinTree

BRANCH

:

BinTree → Z → BinTree → BinTree BinTree

  • =

LEAF Z | BRANCH (BinTree × Z × BinTree) LEAF

: Z → BinTree

BRANCH

: (BinTree × Z × BinTree) → BinTree

The BRANCH constructor in the first definition can be applied one argument at a time.

slide-126
SLIDE 126

3BA31 Formal Methods 251

Constructor Disjointness & Injectivity

In terms of the logic we note that type constructors satisfy the following laws: Disjoint Different constructors produce different values from the type, so if i = j: Ci di1 di2 · · · diki

=

Cj dj1 dj2 · · · djkj Injective The same constructor gives different arguments if applied to different values, i.e. it is an injective function:

( Ci di1 di2 · · · diki =

Ci ei1 ei2 · · · eiki )

⇔ ( di1 = ei1 ∧ . . . ∧ diki = eiki )

This is captured in the logic by an [Injective] inference rule.

3BA31 Formal Methods 252

Scribbles 12 : Linearising Example

Consider goal x ≤ 3 ∨ x > 3 and inference rule:

Left

Γ ⊢ A Γ ⊢ A∨B

This is instantiated (no hypotheses) as:

Left

⊢ x≤3 ⊢ x≤3∨x>3

And written in linear form as: x ≤ 3 ∨ x > 3

“ Left ” x ≤ 3

slide-127
SLIDE 127

3BA31 Formal Methods 253

Scribbles 12 : Need for Disjoint Sum

You have already seen the operation “extend” that connects disjoint parts: S1 ⊔ S2

µ ⊔{a → b}

The sets involved (set itself or map domain) must be disjoint, or the extension is undefined. We want to join (+) overlapping sets (e.g. { a, b } and { b, c } so that we can always tell from which set any element of the result actually came. So if R = { a, b } + { b, c }, I can look at a b in R, and say which set ( { a, b } or { b, c }) if came from. If we use bags, we can merge and record that there were 2 bs, but not were they came from: R

= {a → 1, b → 2, c → 1} = {a → 1, b → 1} ⊕ {b → 1, c → 1} = {a → 1, b → 2} ⊕ {c → 1}

We need to tag the elements in R to indicate their origin

3BA31 Formal Methods 254

Scribbles 12 : Tagging to identify Origin

To compute R = { a, b } + { b, c } we tag the elements from the first set with 1, and those of the second with 2, and the collect them together: R

= { a, b } + { b, c } = { (1, a), (1, b) } ∪ { (2, b), (2, c) } = { (1, a), (1, b), (2, b), (2, c) }

We can now tell, for instance, that (2, b) ∈ R cane from the second set.

slide-128
SLIDE 128

3BA31 Formal Methods 255

Scribbles 12 : Proving id(id(y)) = y

The proof of this property should look something like: id(id(y))

=

“ defn. id ” id(y)

=

“ defn. id ” y

3BA31 Formal Methods 256

Scribbles 12 : Constructors as Functions

We can partially apply Branch:

Branch (Leaf 3) :: Int -> BinTree -> BinTree Branch (Leaf 3) 5 :: BinTree -> BinTree

We can use constructors where functions are expected:

map Leaf [1..3] = [Leaf 1, Leaf 2, Leaf 3]

slide-129
SLIDE 129

3BA31 Formal Methods 257

3BA31 Project

The phases currently specified and their deadlines are: ATC Specification Thursday 5th April 2007, 3pm (revised).

3BA31 Formal Methods 258

Doing Proofs

We are now going to look at the process of doing proofs, building on the models we have already seen: e.g. Orienteering Event, World Cup. The key idea is that a proof obligation P say, will become a sequent

Γ ⊢ P

. Here Γ includes:

  • all the definitions in our model,
  • any previous properties we’ve proved,
  • definitions and laws associated with the mathematical operators we are using,
  • and any hypotheses that result from pre-processing property P.
slide-130
SLIDE 130

3BA31 Formal Methods 259

Pre-processing a property

We are planning to prove Γ ⊢ P, as just discussed. If P has the form Q ⇒ R, then we can add Q to the hypotheses, so we are now proving Γ, Q ⊢ R (implicity using rule [Introduction]). If Q has the form Q1 ∧ Q2 ∧ . . . ∧ Qn, then we can split these conjuncts into separate hypotheses to get Γ, Q1, Q2, . . . , Qn ⊢ R (use of [Split Deep]). Note that we might expand some definitions used by Q if they themselves turn into the logical-and of simpler stuff. If R has the form S ⇒ T, then we repeat the two steps above. The final outcome of this pre-processing is a large number of hypotheses, and a small goal, which is always the easiest form of proof to discharge. Note that: A ⇒ (B ⇒ C)

≡ (A ∧ B) ⇒ C ≡

B ⇒ (A ⇒ C) as pre-processing each will show.

3BA31 Formal Methods 260

Proof Format

A proof always starts on a new page and has the following format:

  • State clearly what has to be proved.
  • Pre-process it to collect hypotheses, write these down and label them.
  • State clearly the resulting initial goal.
  • For this goal, identify a proof strategy, and state it clearly.
  • Perform proof steps line by line starting with the initial goal and following with the alternation of

justification lines describing a step and line giving the outcome goal of that step.

  • Explanatory text should refer to hypotheses by label where possible.
  • If forced to split a proof into parts (induction or case-analysis), clearly mark the start and end of

each sub-part See examples in class/on slides for guidance

slide-131
SLIDE 131

3BA31 Formal Methods 261

O-Model: Types

We construct a model of an orienteering event, for competitors using the SportIdent (SI) System. We first introduce the Types:

[SI:def]

s ∈ SI

= N [Cntl:def]

c ∈ Control

= N [Crs:def]

r ∈ Course

=

Id

[Crss:def] κ ∈ Courses =

Course

m

→ CONTROL+ [Ntries:def] ω ∈ Entries =

SI

m

→ Course [Runs:def] ω ∈ Runs =

SI

m

→ Control∗

The notation [xxx] on the left of each definition is simply a handy label used to refer to the definitions. We shall use these in proofs.

3BA31 Formal Methods 262

O-Model: State and Invariant

System state is comprised of Courses, Entries and Runs:

[OState:def] (κ, ω, ρ) ∈ OState

  • =

Courses × Entries × Runs Competitors can only enter courses that are offered, and when running must be entered, and can

  • nly find controls that are out there:

[inv-OState:def]

inv-OState(κ, ω, ρ)

  • =

rng ω ⊆ dom κ ∧ dom ρ ⊆ dom ω ∧ controlsof(ρ) ⊆ controlsof(κ) [controlsof:sig]

controlsof

: (A

m

→ P B) → P B [controlsof:def]

controlsof(α)

  • =

∪/(Pelems(rng α))

slide-132
SLIDE 132

3BA31 Formal Methods 263

O-Model: State and Invariant

Proof obligation: Invariant Satisfiability:

∃ Σ ∈ OState • inv-OState(Σ)

3BA31 Formal Methods 264

O-Model: State and Invariant

The proof of this follows from that for the initial state, as follows:

Γ ⊢ A[t/x] Γ ⊢ ∃ x • A[Witness t] Γ ⊢ inv-OState(O0) Γ ⊢ ∃ Σ • inv-OState(Σ)[Witness O0]

The general inference rule is on the left, and its application to this obligation is on the right.

slide-133
SLIDE 133

3BA31 Formal Methods 265

O-Model: Initial State

Initially everything is empty:

[OState:init:sig]

O0

:

OState

[OState:init:def]

O0

  • =

(θ, θ, θ)

The initial state must satisfy the invariant: inv-OState(O0)

3BA31 Formal Methods 266

O-Model: Initial State Proof

To prove: inv-OState(O0) Extracted hypotheses: none. Initial Goal: inv-OState(O0) Proof strategy: reduce initial goal to TRUE. Proof: inv-OState(θ, θ, θ)

“ defn. inv-Ostate, [inv-OState:def]:slide262 ”

rng θ ⊆ dom θ ∧ dom θ ⊆ dom θ ∧ controlsof(θ) ⊆ controlsof(θ) ≡

“ defn. of rng, dom, [Lemma:controlsof-null]:slide267 ”

∅ ⊆ ∅ ∧ ∅ ⊆ ∅ ∧ ∅ ⊆ ∅ ≡

“ defn. of ⊆, propositional calculus ” TRUE

slide-134
SLIDE 134

3BA31 Formal Methods 267

O-Model: Initial State Proof (Lemma)

We made use of a Lemma (subsidiary property to assist a proof):

[Lemma:controlsof-null]

controlsof(θ) = ∅ Reduce lhs to rhs: controlsof(θ)

=

“ defn. of controlsof ”

∪/(Pelems(rng θ))

=

“ defn. rng ”

∪/(Pelems(∅)

=

“ defn. Pf ”

∪/(∅)

=

“ defn. ∪/ ”

3BA31 Formal Methods 268

O-Model Operation : Planning An Event

We now introduce an operation to allow the planner to add a course, so long as the event has not started (runners registered for and/or out on a course):

[Plan:sig]

Plan

: (Course × Controls+) → OState → OState [Plan:def]

Plan(r, σ)(κ, ω, ρ)

  • =

(κ † {r → σ}, ω, ρ) [pre-Plan:def]

pre-Plan

  • =

ω = θ ∧ ρ = θ

Proof obligation: invariant preservation inv-OState(κ, ω, ρ) ∧ pre-Plan(r, σ)(κ, ω, ρ) ⇒ inv-OState(Plan(r, σ)(κ, ω, ρ)) We have already seen a proof of this.

slide-135
SLIDE 135

3BA31 Formal Methods 269

O-Model Operation : Register

Orienteers can enter for an offered course, and change their mind when not already out running:

[Register:sig]

Register

:

SI × Course → OState → OState

[pre-Register:def]

pre-Register(s, c)(κ, ω, ρ)

  • =

c ∈ dom κ ∧ s /

∈ dom ρ [Register:def]

Register(s, c)(κ, ω, ρ)

  • =

(κ, ω † {s → c}, ρ)

Proof obligation: invariant preservation inv-OState(κ, ω, ρ) ∧ pre-Register(s, c)(κ, ω, ρ) ⇒ inv-OState(Register(s, c)(κ, ω, ρ))

3BA31 Formal Methods 270

O-Model Operation : Run

An orienteer can run once, once entered: Run

:

SI × Control∗ → OState → OState pre-Run(s, σ)(κ, ω, ρ)

  • =

s ∈ dom ω ∧ s /

∈ dom ρ

Run(s, σ)(κ, ω, ρ)

  • =

(κ, ω, ρ † {s → σ})

Proof obligation: invariant preservation inv-OState(κ, ω, ρ) ∧ pre-Run(s, σ)(κ, ω, ρ) ⇒ inv-OState(Run(s, σ)(κ, ω, ρ))

slide-136
SLIDE 136

3BA31 Formal Methods 271

O-Model Operation : Complete

A competitor is complete if they got precisely the controls on their course: Complete

:

SI → OState → B Complete(s)(κ, ω, ρ)

  • =

κ(ω(s)) = ρ(s)

There is no proof obligation here.

3BA31 Formal Methods 272

Scribbles 13 : Split Deep

The [Split Deep] inference rule for hypotheses is as follows:

Split Deep Hn Γ, A, B ⊢ C Γ, Hn:A ∧ B ⊢ C

This allows us to split the logical-and of hypotheses into separate hypotheses, which can be used individually.

slide-137
SLIDE 137

3BA31 Formal Methods 273

Scribbles 13 : Register Proof (pre-processing)

We are going to prove the Register operation’s proof obligation (see slide 269 for statement). First we take the following as (separate) hypotheses: inv-OState(κ, ω, ρ) pre-Register(s, c)(κ, ω, ρ) We then expand the definitions to obtain:

[Reg:PO:H1] rng ω ⊆ dom κ [Reg:PO:H2]

dom ρ ⊆ dom ω

[Reg:PO:H3]

controlsof(ρ) ⊆ controlsof(κ)

[Reg:PO:H4]

c ∈ dom κ

[Reg:PO:H5]

s /

∈ dom ρ

Should we expand the definition of controlsof further? The best bet is to leave it for now—we can always expand it later,

3BA31 Formal Methods 274

Scribbles 13 : Register Proof (goal)

Given the hypotheses on the previous slide, we now want to prove the goal: inv-OState(Register(s, c)(κ, ω, ρ)) The strategy we are going to adopt is to reduce this whole goal to true. We start by expanding the definitions: inv-OState(Register(s, c)(κ, ω, ρ))

“ defn. of Register ” inv-OState((κ, ω † {s → c}, ρ))

“ defn. of inv-OState ”

rng (ω † {s → c}) ⊆ dom κ ∧ dom ρ ⊆ dom (ω † {s → c}) ∧ controlsof(ρ) ⊆ controlsof(κ)

Note that at the start, we can only expand the definition of Register, because the argument of inv-OState has the wrong form at that point.

slide-138
SLIDE 138

3BA31 Formal Methods 275

Scribbles 13 : Register Proof (hypotheses)

We now look at our hypotheses and use these to reduce as much of the goal to true as possible:

rng (ω † {s → c}) ⊆ dom κ ∧ dom ρ ⊆ dom (ω † {s → c}) ∧ controlsof(ρ) ⊆ controlsof(κ) ≡

“ [Reg:PO:H3]:slide273 ”

rng (ω † {s → c}) ⊆ dom κ ∧ dom ρ ⊆ dom (ω † {s → c}) ∧ true

Now we see that is was not necessary to expand the definition of controlsof. Further progress now requires us to make use of some properties of maps and sets.

3BA31 Formal Methods 276

Scribbles 13 : Relevant Set and Map Laws [union:prsrv:subset]

S ⊆ T

S ⊆ T ∪ U

[subset:def.1] { x } ⊆ U ≡

x ∈ U

[subset:def.2]

S ∪ T ⊆ U

S ⊂ U ∧ T ⊆ U

[override:def]

dom(µ †ν)

  • =

⊳ −[dom ν] µ ⊔ν [dom:def.1]

dom({a → b})

  • =

{ a } [dom:def.2]

dom(µ †ν)

  • =

dom µ ∪ dom ν

[rng:def.1] rng({a → b})

  • =

{ b } [rng:def.2] rng(µ ⊔ν)

  • =

rng µ ∪rng ν [remove:rng:subset] rng(⊳ −[S] µ) ⊆ rng(µ)

slide-139
SLIDE 139

3BA31 Formal Methods 277

Scribbles 13 : Register Proof (laws — I)

We apply the laws (dropping the ∧ true along the way):

rng (ω † {s → c}) ⊆ dom κ ∧ dom ρ ⊆ dom (ω † {s → c}) ≡

“ [dom:def.2]:slide276 ”

rng (ω † {s → c}) ⊆ dom κ ∧ dom ρ ⊆ dom ω ∪ dom{s → c} ≡

“ [union:prsrv:subset]:slide276, using [Reg:PO:H2]:slide273, ” “ with dom ρ as S, dom ω as T and dom{s → c} as U. ”

rng (ω † {s → c}) ⊆ dom κ ∧ true ≡

“ [override:def]:slide276, drop ∧ true. ”

rng (⊳ −[dom{s → c}]ω ⊔ {s → c}) ⊆ dom κ

(continued on next slide)

3BA31 Formal Methods 278

Scribbles 13 : Register Proof (laws — II) rng (⊳ −[dom{s → c}]ω ⊔ {s → c}) ⊆ dom κ ≡

“ [dom:def.1]:slide276 ”

rng (⊳ −[{ s }]ω ⊔ {s → c}) ⊆ dom κ ≡

“ [rng:def.2]:slide276 ”

rng (⊳ −[{ s }]ω) ∪ { c } ⊆ dom κ ≡

“ [subset:def.2]:slide276 ”

rng (⊳ −[{ s }]ω) ⊆ dom κ ∧ { c } ⊆ dom κ ≡

“ [subset:def.1]:slide276, followed by [Reg:PO:H4]:slide273 ”

rng (⊳ −[{ s }]ω) ⊆ dom κ ∧ true ≡

“ [remove:rng:subset]:slide276, [Reg:PO:H1]:slide273, transitivity of ⊆ ” true ∧ true

slide-140
SLIDE 140

3BA31 Formal Methods 279

Induction on Natural Numbers

The idea of Induction on Natural Numbers is very straightforward: In order to show a property P holds for all n ∈ N, it suffices to show:

  • 1. the property holds for 0
  • 2. if the property holds for x then also holds for x + 1

(a) it holds for 0, so we can conclude it holds for 1 (b) it now holds for 1, so we can conclude it holds for 2 (c) it now holds for 2, so we can conclude it holds for 3 . . . In logical notation: P(0) P(x) ⇒ P(x + 1)

∀ n ∈ N • P(n)

3BA31 Formal Methods 280

Natural Induction Example

Prove: S(n)

= n

i=1 i = n2+n

2

S(0)

“ defn S ”

i=1 i = 02+0

2

“ defn , arithmetic ”

0 = 0 ≡

“ reflexivity ” true

slide-141
SLIDE 141

3BA31 Formal Methods 281

Natural Induction Example (Step)

Assume S(n), and show: S(n + 1)

“ defn. S(n) ”

n+1

i=1 i = (n+1)2+(n+1)

2

“ law of , arithmetic ”

(n

i=1 i) + (n + 1) = n2+n

2

+ (n + 1) ≡

“ arithmetic ”

n

i=1 i = n2+n

2

∧ (n + 1) = (n + 1) ≡

“ hypothesis, S(n) ” TRUE ∧ TRUE

3BA31 Formal Methods 282

Natural Induction — Another View

We can define natural numbers as an ADT: NatNum

  • =

ZERO | SUCC natNum (A natural number is either zero or the successor of a natural number) We can then formulate our induction as: P(ZERO) P(x) ⇒ P(SUCC x)

∀ n ∈ NatNum • P(n)

In effect, this is just a change of notation. We can extend this idea to all ADTs

slide-142
SLIDE 142

3BA31 Formal Methods 283

List Induction

A List of t is either empty, or an element of type t stuck on the front of a List of t: List t

  • =

NIL | CONS t (List t) To show a property holds of all lists:

  • 1. show it holds for the empty list.
  • 2. show that if it holds for a list, it holds when we add an arbitrary element to the front

P(NIL)

∀ e • P(ℓ) ⇒ P(CONS e ℓ) ∀ ℓ ∈ List t • P(ℓ)

3BA31 Formal Methods 284

Induction on Trees ?

Tree

  • =

LEAF N | BRANCH Tree N Tree We want to prove for all τ ∈ Tree that P(τ) holds. Clearly, P(LEAF n) must hold, for all n ∈ N. What else ?

slide-143
SLIDE 143

3BA31 Formal Methods 285

Induction on Trees

Tree

  • =

LEAF N | BRANCH Tree N Tree We want to prove for all τ ∈ Tree that P(τ) holds. We show:

  • 1. that P(LEAF n) holds, for all n ∈ N.
  • 2. that if P(τ1) holds,

and P(τ2) holds, that we can show that P(BRANCH τ1 n τ2) holds, for all n ∈ N.

3BA31 Formal Methods 286

Induction for ADTS (I)

Consider the following general ADT definition: MyType

  • =

C1 t11 t12 · · · t1k1

|

C2 t21 t22 · · · t2k2 . . .

|

Cn tn1 tn2 · · · tnkn We can split the constructors C1, . . . Cn into two groups: Base Constructors Constructors Cb where none of the associated types tbi are MyType. Recursive Constructors Constructors Cm

r where exactly m, m > 0 of the associated types tri are MyType.

slide-144
SLIDE 144

3BA31 Formal Methods 287

Induction for ADTS (II)

The induction principle for ADTS is as follows, In order to show ∀ a ∈ MyType • P(a):

  • 1. For each base constructor Cb tb1 · · · tbkb, prove

∀ xb1, . . . , xbkb : tb1 · · · tbkb • P(Cb xb1 · · · xbkb)

  • 2. For each recursive constructor Cm

r tr1 · · · trkr−m MyType1 ··· MyTypem

assume P(ai) for i ∈ 1 . . . m, and from this infer the truth of ∀ xr1, . . . , xrkr−m : tb1 · · · tbkb • Cm

r tr1 · · · trkr−m a1 ··· am

where the trj are the non-MyType type parameters.

3BA31 Formal Methods 288

WC-Model: Types

We have countries, modelled as Strings: c ∈ Country

  • =

A∗

We model the draw as a Binary Tree: Draw

  • =

TEAM C | MATCH Draw Draw

slide-145
SLIDE 145

3BA31 Formal Methods 289

WC-Model: State and Invariant

The state of the system is just a draw:

ω ∈ WCState

  • =

Draw The invariant states that each country occurs at most once in the draw: inv-WCState(TEAM c)

  • =

TRUE inv-WCState(MATCH d1 d2)

  • =

inv-WCState(d1) ∧ vWCState(d2)

cof(d1) ∩ cof(d2) = ∅ Proof obligation: Invariant Satisfiability:

∃ ω ∈ WCState • inv-WCState(ω)

3BA31 Formal Methods 290

WC-Model Operation : Playing a Match

We define playing a match as follows, with a trivial pre-condition: play

: (Country × Country) → WCState → WCState

play(c1, c2)(TEAM c)

  • =

TEAM c play(c1, c2)(MATCH(TEAM c1) (TEAM c2))

  • =

(TEAM winner(c1, c2))

play(c1, c2)(MATCH(TEAM c2) (TEAM c1))

  • =

(TEAM winner(c2, c1))

play(c1, c2)(MATCH d1 d2)

  • =

(MATCH play(c1, c2)(d1) play(c1, c2)(d2))

Proof obligation: invariant preservation inv-WCState(ω) ⇒ inv-WCState(play(c1, c2)(ω))

slide-146
SLIDE 146

3BA31 Formal Methods 291

Scribbles 14 : List Definitions

Some Useful List definitions, of the list length operation (len) and list concatenation ():

[len:def.0] len

  • =

[len:def.1] len (e:ℓ)

  • =

1 + len ℓ [cat:def.0] ℓ

  • =

ℓ [cat:def.1] (e : ℓ) ℓ′

  • =

e : (ℓ ℓ′)

3BA31 Formal Methods 292

Scribbles 14 : Length/Concat Property Proof

We want to prove that

len(ℓ1 ℓ2) = (len ℓ1) + (len ℓ2)

There is no pre-processing to be done. The strategy is to do induction on ℓ1, so we re-state the property explicitly as a function of that variable: P(ℓ1)

  • =

len(ℓ1 ℓ2) = (len ℓ1) + (len ℓ2)

slide-147
SLIDE 147

3BA31 Formal Methods 293

Scribbles 14 : Proof (base Case)

P()

= len( ℓ2) = (len ) + (len ℓ2)

Strategy: We reduce both the lhs and rhs to the same thing:

len( ℓ2) =

“ [cat:def.0]:slide291 ”

len ℓ2 (len ) + (len ℓ2) =

“ [len:def.0]:slide291 ”

0 + (len ℓ2) =

“ arithmetic ”

len ℓ2

The base case holds.

3BA31 Formal Methods 294

Scribbles 14 : Proof (inductive step)

We assume P(ℓ1) in order to show P(e : ℓ1), for arbitrary e.

[P:step:H1] len(ℓ1 ℓ2) = (len ℓ1) + (len ℓ2)

Goal:

len((e : ℓ1) ℓ2) = (len (e : ℓ1)) + (len ℓ2)

Strategy: We reduce both the lhs and rhs to the same thing:

len((e : ℓ1) ℓ2) =

“ [cat:def.1]:slide291 ”

len(e : (ℓ1 ℓ2)) =

“ [len:def.1]:slide291 ”

1 + len(ℓ1 ℓ2) (len (e : ℓ1)) + (len ℓ2) =

“ [len:def.1]:slide291 ”

(1 + (len ℓ1)) + (len ℓ2) =

“ [P .step.H1]:slide??, right-to-left ”

(1 + len(ℓ1 ℓ2)

The step-case holds, and so does the overall property.

slide-148
SLIDE 148

3BA31 Formal Methods 295

Scribbles 14 : The Idea behind Induction

Induction is a general way of showing how to build a proof for any number, list, tree etc, from proofs of smaller instances of same:

  • To show P(5), say, show P(4), P(3), P(2), P(1) and P(0).
  • To show Q(a : b : c : ), show Q(b : c : ), Q(c : and Q().
  • To show R(BRANCH(LEAF 1)3(LEAF 2)), show R(LEAF 1) and R(LEAF 2).

For binary tree, if we have shown R(LEAF n) for any n, and R(τ1) and R(τ2) implies R(BRANCH τ1 m τ2) for any m, we can deduce that

  • 1. R holds for LEAF 1 and LEAF 2, so it holds for BRANCH(LEAF 1)5(LEAF 2);
  • 2. R holds for LEAF 3 and LEAF 4, so it holds for BRANCH(LEAF 3)6(LEAF 4);
  • 3. R holds for BRANCH(LEAF 1)5(LEAF 2) and BRANCH(LEAF 3)6(LEAF 4), so it holds for

BRANCH(BRANCH(LEAF 1)5(LEAF 2))7(BRANCH(LEAF 3)6(LEAF 4)); This works for any (finite) tree build this way, no matter how large.

3BA31 Formal Methods 296

Scribbles 14 : Expression ADT and Induction Principle

Consider the following ADT for Expressions in some language: Expr

  • =

INT Z | BOOL B | VAR String

|

SUM Expr Expr | PROD Expr Expr | IF Expr Expr Expr We have the following induction principle, to allow us to prove that ∀ e ∈ Expr • P(e), for some property P of interest: Base Cases Prove ∀ z ∈ Z • P(INT z), ∀ b ∈ B • P(BOOL b), and ∀ s ∈ String • P(VAR s) Inductive Step Assume P(e1),P(e2) and P(e1), and show P(SUM e1 e2) P(PROD e1 e2) P(ID e1 e2 e3)

slide-149
SLIDE 149

3BA31 Formal Methods 297

Scribbles 14 : Play Proof Obligation

We want to prove the proof obligation for Play, reproduced here: inv-WCState(ω) ⇒ inv-WCState(play(c1, c2)(ω)) We don’t pre-process this as normal, because there is nothing we can do with inv-WCState(ω) (we can’t expand the definition, unless we know what form ωhas). Instead we announce a strategy to prove the above by induction on ω. P(ω)

  • =

inv-WCState(ω) ⇒ inv-WCState(play(c1, c2)(ω)) The base case is P(TEAM c). The inductive step assumes P(ω1) and P(ω2) to show P(MATCH ω1 ω2).

3BA31 Formal Methods 298

Scribbles 14 : Proof (base case)

P(TEAM c)

  • =

inv-WCState(TEAM c) ⇒ inv-WCState(play(c1, c2)(TEAM c)) This we can pre-process. We assume inv-WCState(TEAM c) which reduces to true. We have as goal: inv-WCState(play(c1, c2)(TEAM c)) Strategy: We reduce the goal to true: inv-WCState(play(c1, c2)(TEAM c))

“ defn. play ” inv-WCState(TEAM c)

“ defn. inv-WCState ” true

slide-150
SLIDE 150

3BA31 Formal Methods 299

Scribbles 14 : Proof (inductive step)

We shall assume P(ω1)

  • =

inv-WCState(ω1) ⇒ inv-WCState(play(c1, c2)(ω1)) P(ω2)

  • =

inv-WCState(ω2) ⇒ inv-WCState(play(c1, c2)(ω2)) to prove P(MATCH ω1 ω2)

  • =

inv-WCState(MATCH ω1 ω2) ⇒ inv-WCState(play(c1, c2)(MATCH ω1 ω2)) Initial pre-processing suggests we assume inv-WCState(MATCH ω1 ω2) and take inv-WCState(play(c1, c2)(MATCH ω1 ω2)) as goal. So we are assuming:

[play:PO:H1]

inv-WCState(ω1)

inv-WCState(play(c1, c2)(ω1))

[play:PO:H2]

inv-WCState(ω2)

inv-WCState(play(c1, c2)(ω2))

[play:PO:H3]

inv-WCState(MATCH ω1 ω2)

3BA31 Formal Methods 300

Scribbles 14 : Proof (assumptions)

If we expand [play:PO:H3]:slide??, using the invariant definition and split, we get:

[play:PO:H1]

inv-WCState(ω1)

inv-WCState(play(c1, c2)(ω1))

[play:PO:H2]

inv-WCState(ω2)

inv-WCState(play(c1, c2)(ω2))

[play:PO:H3.1]

inv-WCState(ω1)

[play:PO:H3.2]

inv-WCState(ω2)

[play:PO:H3.3]

cof(ω1) ∩ cof(ω2) = ∅ At this point we note that H3.1 and H3.2 correspond to the antecedents of H1 and H2 respectively. Can we exploit this in any way ?

slide-151
SLIDE 151

3BA31 Formal Methods 301

Scribbles 14 : Proof ([Apply])

The inference rule [Apply] is:

Γ, A, B ⊢ C Γ, Hm : A, Hn : A ⇒ B ⊢ C [Apply Hn to Hm]

This allows us to simplify H1 and H2 (playing the role of B above) using H3.1 and H3.2 (acting like A).

[play:PO:H1]

inv-WCState(play(c1, c2)(ω1))

[play:PO:H2]

inv-WCState(play(c1, c2)(ω2))

[play:PO:H3.1]

inv-WCState(ω1)

[play:PO:H3.2]

inv-WCState(ω2)

[play:PO:H3.3]

cof(ω1) ∩ cof(ω2) = ∅ We can now address our goal.

3BA31 Formal Methods 302

Scribbles 14 : Proof (goal)

Our Goal inv-WCState(play(c1, c2)(MATCH ω1 ω2)) Strategy: reduce to true: inv-WCState(play(c1, c2)(MATCH ω1 ω2))

[ Rest of Proof to Follow ]