Sets
Specifications talk about collections all the time: the users who may read a file, the states a system can reach, the messages in transit. Mathematics has one notion for all of them, the set, and many specification languages are built on it: Z and B on set theory, Alloy on relations, TLA+ on sets and functions. This module builds the vocabulary in layers: sets, then relations, which connect elements, then functions, and finally the sizes of sets. Everything rests on the logic of Modules 2 and 3; you will see that the laws of sets are laws of logic in disguise. For more practice with the mathematics, see “Sets, relations, and discrete structures” in Mathematical Foundations.
Elements and set-builder notation
A set is a collection of things, called its elements, determined entirely by which things belong to it. reads “x is an element of A”, or “x is in A”; reads “x is not in A” and abbreviates .
There are two ways to describe a set. A listing names its elements between braces: . Set-builder notation describes them by a property: reads “the set of all x such that P x”. The primes below 10 form the set , which is again. Many books write ; this series writes , as Isabelle does. A common variant takes the elements from a given set: means .
Set-builder notation connects sets with the predicates of Module 3. Something belongs to exactly when it has the property :
So a set and a predicate carry the same information. In Isabelle/HOL, a set of elements of some type is, in effect, a predicate on that type.
A set is a collection of elements; means that is an element of . A set can be
given by a listing such as , or by set-builder notation , the set
of all for which holds. In Isabelle/HOL every set has an element type: a set of natural
numbers has type nat set, and all its elements are natural numbers.
When are two sets equal? When they have the same elements. Nothing else counts: not the order in which you list them, not how you describe them.
Two sets are equal when they have the same elements:
So , and .
is a subset of , written , when every element of is an element of :
. It is a proper subset, , when also .
The empty set has no elements; Isabelle writes it {}. The universe contains every
element of the type; Isabelle calls it UNIV.
For all sets and :
- and .
- .
For the first, is false for every , so is vacuously true (Module 2); vacuous truth will come back in this module. And holds whatever is. The second combines extensionality with the law . It is also how you usually prove two sets equal: show that each is a subset of the other.
Because HOL is typed (Module 3), a universe is always the universe of one type: UNIV :: bool set is
, and UNIV :: nat set contains all natural numbers. There is no set
of absolutely everything, and Section 4.7 shows why that is a good thing.
A file server has the users alice, bob, carol and dave. Those who may read a certain file form the set , those who may write it , and the administrators . Then holds: every administrator may write. The policy “writers must be able to read” is the statement , and it is violated, with dave as the witness: but .
Keep and apart. is about an element, about a set, and both are true. In HOL, is not even false: it is a type error, because the elements of are numbers and is a set. In the same way, and differ: the first has no elements, the second has one.
Operations on sets
Each operation on sets is a logical connective applied to membership.
and are disjoint when . Isabelle writes A ∪ B, A ∩ B, A - B
and - A.
Read them as “A union B”, “A intersect B”, “A minus B” and “the complement of A”. The complement contains everything of the type that is not in . Figure 4.1 draws the four operations.
The four operations as Venn diagrams. The rectangle is the universe, each circle a set, and the shaded region the result. Under each diagram is the condition on that the region stands for.
On the file server, may read and write, (alice and carol) may only read, and is the user who violates the policy.
The power set of a set is the set of all its subsets:
. Isabelle writes Pow A.
has eight elements: , , , , , , and . Choosing a subset means deciding for each element whether it is in or out, so a set of elements has subsets. Power sets grow fast: a program with forty on-off feature flags has configurations, more than a million million, one for each subset of the flags.
Set laws are logic in disguise
Since every operation is defined by a connective, every law of the connectives (Module 2) gives a law of sets. Each law in the table also has a dual, with and swapped (and and ), that holds as well.
| Name | Law of sets | Law of logic behind it |
|---|---|---|
| Commutativity | ||
| Associativity | ||
| Distributivity | ||
| De Morgan | ||
| Identity | ||
| Complement | ||
| Double complement | ||
| Absorption |
Translate an equation between sets built with , , and complement into propositional logic: replace each set by a proposition that stands for “”, by , by , by , complement by , by and by . The equation holds for all sets exactly when the two formulas are equivalent, that is, when their biconditional is a tautology.
If the formulas are equivalent, every is in the left set exactly when it is in the right one, and extensionality makes the sets equal. If they are not, the truth table has a row where they differ: put a single element into exactly those sets whose propositions are true in that row, and is in one side but not the other. So a falsifying row is a counterexample with one element.
To prove , take any and rewrite its membership:
This holds for every , so the sets are equal by extensionality. The middle step is the only real work, and it is propositional. Write , and for “”, “” and “”, and the build checks it with a truth table:
| A | B | C | A ∧ (B ∨ C) | A ∧ B ∨ A ∧ C | A ∧ (B ∨ C) ⟷ A ∧ B ∨ A ∧ C |
|---|---|---|---|---|---|
| T | T | T | T | T | T |
| T | T | F | T | T | T |
| T | F | T | T | T | T |
| T | F | F | F | F | T |
| F | T | T | F | F | T |
| F | T | F | F | F | T |
| F | F | T | F | F | T |
| F | F | F | F | F | T |
Tautology: true in every row.
Each row is one region of a Venn diagram with three circles: the row where and are true and is false is the region of the elements in and but not in . A tautology says that the two sides agree on every region.
Is ? Translate both sides:
| A | B | C | A ∧ ¬(B ∧ ¬C) | A ∧ ¬B ∧ ¬C | A ∧ ¬(B ∧ ¬C) ⟷ A ∧ ¬B ∧ ¬C |
|---|---|---|---|---|---|
| T | T | T | T | F | F |
| T | T | F | F | F | T |
| T | F | T | T | F | F |
| T | F | F | T | T | T |
| F | T | T | F | F | T |
| F | T | F | F | F | T |
| F | F | T | F | F | T |
| F | F | F | F | F | T |
Satisfiable but not valid: true in 6 rows.
The formulas differ in the two rows where and are true. Take the one with false: an element in and but not in . With , and , the left side is and the right side is . Set difference, like the subtraction of numbers, is not associative.
Sets in Isabelle
Type the new symbols with their names after a backslash, or with the abbreviations in the table.
Difference and complement use the ordinary minus sign -.
| Symbol | Type | Meaning |
|---|---|---|
| ∈ | \in or : |
is an element of |
| ∉ | \notin or ~: |
is not an element of |
| ⊆ | \subseteq or (= |
is a subset of |
| ∪ | \union or Un |
union |
| ∩ | \inter or Int |
intersection |
value computes with finite sets, as in Module 1:
value "{1, 2, 3} ∪ {3, 4 :: nat}""{2, 1, 3, 4}"
:: "nat set"One annotation, :: nat, fixes the element type of the whole expression. Isabelle lists the elements
in whatever order its computation produced them; by extensionality the order does not matter.
Set-builder notation works when the elements come from a finite set. {0..10} is the set of numbers
from 0 to 10, and mod gives the remainder:
value "{x ∈ {0..10}. x mod 3 = (0::nat)}""{0, 3, 6, 9}"
:: "nat set"The power set of a set of numbers is a set of sets of numbers, a nat set set:
value "Pow {1, 2, 3 :: nat}""{{2, 3}, {2}, {}, {3}, {1, 3}, {1}, {1, 2}, {1, 2, 3}}"
:: "nat set set"Mixing up and is a type error, as the pitfall above said:
value "{1} ∈ {1, 2 :: nat}"Type unification failed: Clash of types "nat" and "_ set"
Type error in application: incompatible operand type
Operator: (∈) {1} :: ??'a set set ⇒ bool
Operand: {1, 2} :: nat set
The operator (∈) {1} (“is {1} an element of …”) needs a set of sets, a ??'a set set; the operand is
a set of numbers. Write {1} ⊆ {1, 2} or 1 ∈ {1, 2}, depending on what you mean.
Now prove a law. State it:
lemma "A ∩ (B ∪ C) = A ∩ B ∪ A ∩ C"proof (prove)
goal (1 subgoal):
1. A ∩ (B ∪ C) = A ∩ B ∪ A ∩ CIsabelle prints A ∩ B ∪ A ∩ C without brackets because binds more tightly than , as
binds more tightly than . A, B and C are free, so the lemma claims the law for all
sets (Module 3). Prove it:
by autoauto does what the paper proof did: it applies extensionality, replaces each membership by its
definition and finishes with propositional reasoning. blast works as well; on sets these two are the
usual tools.
lemma "- (A ∪ B) = - A ∩ - B"
by auto
lemma "x ∈ {y. P y} ⟷ P x"
by simpA false law cannot be proved, but Nitpick (Module 2) finds a counterexample. The option
card 'a = 1 makes it search a universe with one element, which is enough, as you saw above:
lemma "A - (B - C) = (A - B) - (C :: 'a set)"
nitpick [card 'a = 1]
oopsNitpicking formula...
Nitpick found a counterexample for card 'a = 1:
Free variables:
A = {a1}
B = {}
C = {a1}The counterexample is the row of the truth table found above: a₁ is in A and C but not in B.
Isabelle/jEdit’s automatic Quickcheck may flag the lemma as soon as you type it.
The annotation (C :: 'a set) matters. Of the operations above, only - also exists for other types,
so without it Isabelle reads the lemma as a claim about subtraction in general. Nitpick then finds a
counterexample in which A, B and C are not sets at all, and suspects the problem:
lemma "A - (B - C) = A - B - C"
nitpick [card 'a = 2]
oopsNitpicking formula...
Nitpick found a counterexample for card 'a = 2:
Free variables:
A = a1
B = a1
C = a1
Hint: Maybe you forgot a type constraint?∪, ∩, ⊆ and ∈ exist only for sets, so a lemma that uses one of them needs no annotation.
If something went wrong
-
Clash of types "nat" and "bool"in set-builder notation. In Isabelle,|is a way to type , so the book notation does not work:value "{x | x < (5::nat)}"Type unification failed: Clash of types "nat" and "bool" Type error in application: incompatible operand type Operator: (<) x :: bool ⇒ bool Operand: 5 :: natIsabelle read the set with the single element
x ∨ x < 5, soxwould have to be both a truth value and a number. Write{x. x < 5}, with a dot. -
Wellsortedness error…not of sort enumfromvalue.valuecannot compute{x. x < (5::nat)}with this representation: the evaluator has no finite list over which to search. Take the elements from a finite set, as in{x ∈ {0..10}. x < 5}. The issue is executable representation and code equations, rather than a prohibition on reasoning about infinite sets. For example, membership in some infinite sets is computable even though listing every element is not.
Relations
A set says which things there are. A relation says how they are connected: which user has which role, which function calls which, which state of a system can follow which.
Pairs and products
An ordered pair has a first component and a second component . Unlike a set, a pair
has an order: , although . Two pairs are equal when their
components are: . In Isabelle a pair (a, b) has a type such
as nat × string, read “nat times string”.
The Cartesian product of and is the set of all pairs whose first component is in and whose second component is in :
For example, . A product of finite sets has elements, where is the number of elements of . A database table with the columns name and age is a subset of .
Relations as sets of pairs
A (binary) relation from to is a subset ; a relation on is
a subset of . Instead of one also writes , “x is related to
y by R”. In Isabelle a relation on a type 'a has the type 'a rel, short for ('a × 'a) set.
A relation is nothing but the set of the pairs that are related. The order on is the set . Equality on is the identity relation . “function calls function ” is the call graph of a program, and “the system can move from state to state in one step” is its transition relation (Section 4.5).
A relation on a small finite set can be drawn as a directed graph, with an arrow from to for each pair and a loop at for , or as a matrix, with a mark in row and column for each pair. The widget below shows both.
Properties of relations
Six properties come up again and again. They use the bounded quantifier , “for all x in A, P x”, which means .
A relation on is
In the graph, each property has a shape you can check by eye:
| Property | In the graph |
|---|---|
| Reflexive | a loop at every node |
| Irreflexive | no loops at all |
| Symmetric | every arrow has a partner going back |
| Antisymmetric | no pair of arrows going both ways between different nodes |
| Transitive | every path of two arrows has a shortcut |
| Total | any two different nodes are joined by an arrow, in at least one direction |
Some books ask totality also for ; this series follows Isabelle and asks it only for different elements, so that counts as total. To show that a property holds you check every case; to show that it fails, one witness is enough. Each property is a -statement, and by the law of Module 3 it fails exactly when some instance fails. A witness against transitivity is a triple with and in but not.
- , that is , is reflexive, antisymmetric, transitive and total. It is not symmetric: is in it and is not.
- “one less than”, , is irreflexive and antisymmetric. It is not transitive: and are in it but is not. Nor is it total: neither nor is in it.
- “has the same parity as”, , is reflexive, symmetric and transitive. It is not antisymmetric: and are in it, but .
- Antisymmetric is not “not symmetric”. Equality is both symmetric and antisymmetric; is neither. Likewise, on is neither reflexive nor irreflexive.
- Vacuous truth. The empty relation is symmetric, antisymmetric and transitive: these properties are implications whose premises never hold.
- Transitivity includes the case . is not transitive: and demand .
Composition and converse
The converse (or inverse) of reverses every pair: . The composition of and takes an -step followed by an -step:
The image of a set under is the set of everything related to an element of :
. Isabelle writes r¯ (type ^-1), r O s, and
for the image r `` X, with two backquotes.
The converse of is , and the converse of “is a parent of” is “is a child of”; in the graph, it turns every arrow round. Composing “is a parent of” with itself gives “is a grandparent of”. Books also write composition as , or as by analogy with functions (Section 4.6), which reverses the order; Isabelle’s reads from left to right.
Many systems assign users roles and assign permissions to those roles; this is role-based access control. With
the permissions of the users are the composition , which relates alice to read and write, and bob to read.
For relations , and :
- and .
- is symmetric exactly when .
- is transitive exactly when .
- is reflexive on exactly when .
Take the third. says that whenever some has and , then . That is transitivity, with the moved out of the premise by the law of Module 3.
A string in Isabelle is written between two pairs of single quotes, ''alice''; its type prints as
char list, a list of characters. Products need × (type \times or <*>):
value "{1, 2 :: nat} × {''x'', ''y''}""{(1, ''x''), (1, ''y''), (2, ''x''), (2, ''y'')}"
:: "(nat × char list) set"Isabelle names the six properties refl_on A r, irrefl_on A r, sym_on A r, antisym_on A r,
trans_on A r and total_on A r, where A is the set the relation is on. Without _on and the set,
as in refl r, sym r and trans r, they speak about the whole type. For finite relations, value
decides them:
value "refl_on {1, 2, 3} {(1::nat, 1), (2, 2), (1, 2)}"
value "trans_on {1, 2, 3} {(1::nat, 2), (2, 3)}"
value "trans_on {1, 2, 3} {(1::nat, 2), (2, 3), (1, 3)}""False"
:: "bool"
"False"
:: "bool"
"True"
:: "bool"The first relation lacks (3, 3); the second lacks the shortcut (1, 3), which the third has.
Composition computes too, and a line break inside the quotes is allowed:
value "{(''alice'', ''admin''), (''bob'', ''guest'')}
O {(''admin'', ''read''), (''admin'', ''write''), (''guest'', ''read'')}""{(''alice'', ''read''), (''alice'', ''write''), (''bob'', ''read'')}"
:: "(char list × char list) set"To prove the facts above for all relations, auto must see the definitions of trans and sym: by
itself, it does not replace trans r by what it means. The library states the definitions as
theorems, trans_def and sym_def, and auto simp: trans_def hands one of them to auto, which then
rewrites trans r into the ∀-formula of the definition and proves the rest as before. Module 9
explains this mechanism in depth.
lemma "trans r ⟷ r O r ⊆ r"
by (auto simp: trans_def)
lemma "sym r ⟷ r¯ = r"
by (auto simp: sym_def)
lemma "(r O s)¯ = s¯ O r¯"
by autoEquivalence relations and partitions
Specifications often care about things only up to some detail: two account numbers may belong to the same customer, two inputs may have to be treated alike, two times may show the same position on a clock. “Has the same … as” relations share three properties.
An equivalence relation on is a relation on that is reflexive on , symmetric and transitive. The equivalence class of is the set of the elements related to it, the image of :
On , let when : and leave the same remainder on division by 3. Every number has the same remainder as itself, “the same” does not depend on the order, and two equalities chain, so this is an equivalence relation. Its classes are
A class has many names, : any element of a class can represent it.
The classes do not overlap, and together they cover the set. This is no accident.
A partition of is a set of non-empty subsets of , its blocks, such that every element of is in exactly one block: the blocks are pairwise disjoint and their union is .
The equivalence classes of an equivalence relation on form a partition of . Conversely, every partition of defines an equivalence relation, “is in the same block as”, whose classes are the blocks.
Here is the proof of the first half. The classes are subsets of , because is a relation on . Reflexivity puts every into its own class, so the classes are non-empty and cover . It remains to show that two classes that meet are equal. Suppose is in and in , so and . By symmetry , and by transitivity . Now for any , transitivity turns and into , so . Hence ; the same argument with and swapped gives , and Fact 4.1 gives . For the second half: every element is in some block (reflexive), the wording is symmetric, and two blocks that share an element are the same block (transitive).
Equivalence relations appear wherever software ignores a detail. Equivalence partitioning, a standard way of designing tests, splits the inputs into classes that the program should treat alike (parcels up to 1 kg, up to 5 kg, heavier) and tests one representative of each, plus the boundaries. And for any function , “has the same value under ” is an equivalence relation. In Module 12, is an abstraction function, which maps each data structure to the abstract value it represents: two structures that represent the same value are equivalent in this sense.
Isabelle writes equiv A r for “r is an equivalence relation on A”, r `` {x} for the class of
x, and A // r (“A modulo r”) for the set of all classes, the partition. Here they are for the
example, with the relation built by set-builder notation over a product:
value "{(x, y) ∈ {0..8::nat} × {0..8}. x mod 3 = y mod 3} `` {4}""{1, 4, 7}"
:: "nat set"value "{0..8::nat} // {(x, y) ∈ {0..8} × {0..8}. x mod 3 = y mod 3}""{{2, 5, 8}, {1, 4, 7}, {0, 3, 6}}"
:: "nat set set"For all natural numbers the relation is an equivalence; the proof unfolds the definitions:
lemma "equiv UNIV {(x, y). x mod 3 = (y::nat) mod 3}"
by (auto simp: equiv_def refl_on_def sym_def trans_def)The library proves the main fact of this section once and for all, as quotient_disj: two classes are
equal or disjoint. With simp add: you hand a theorem to the simplifier:
lemma "equiv A r ⟶ X ∈ A // r ⟶ Y ∈ A // r ⟶ X = Y ∨ X ∩ Y = {}"
by (simp add: quotient_disj)Orders and well-foundedness
Orders compare things: version numbers, priorities, deadlines, “must happen before” in a schedule. Some compare any two elements; many do not.
Partial and total orders
A partial order on is a relation on that is reflexive on , antisymmetric and transitive. A total order (or linear order) is a partial order that is also total on . A strict order is a relation that is irreflexive and transitive.
Partial orders are usually written and strict orders , and each gives the other: , and . A strict order is asymmetric: and would give by transitivity, which irreflexivity forbids.
- on numbers is a total order.
- on is a partial order. If contains two different elements, it is not total: for example, when , and are incomparable, as neither is a subset of the other. If has at most one element, its subsets do form a total order.
- Divisibility on the positive integers, when for some integer , is a partial order, and 2 and 3 are incomparable.
Hasse diagrams
The graph of a partial order has many arrows: a loop at every node, and a shortcut for every path. A Hasse diagram of a partial order on a finite set leaves out what the properties imply. It puts smaller elements lower, draws no loops and no arrowheads, and draws a line from up to only when covers : with nothing strictly between them. Then exactly when an upward path leads from to , allowing a path of zero edges when .
Two Hasse diagrams. Left: the subsets of , ordered by . Right: the divisors of 12, ordered by divisibility. Each line goes up from an element to an element that covers it.
In a partial order, is minimal when no element is strictly below it, and least when it is below every element; maximal and greatest are the same notions upside down. In Figure 4.2, and 1 are least, and 12 greatest. A partial order can have several minimal elements and no least one: in ordered by divisibility, 2 and 3 are minimal, 4 and 6 maximal. In a project plan with no cyclic dependencies, “is a prerequisite of” is a strict order; adding equality gives a partial order. Its minimal tasks have no unfinished prerequisites. Listing tasks in an order that respects the dependencies, a topological sort, gives a valid dependency order; durations and resource constraints are further scheduling questions.
Well-founded relations
On the natural numbers, every descending chain stops after at most steps. On the integers, never stops. This difference is what makes induction and termination proofs work.
Read as “ is smaller than ”. is well-founded when there is no infinite descending chain: no infinite sequence with for every .
Equivalently, a fact this series uses without proof, every non-empty set has an -minimal element: some such that no has .
- on is well-founded. on is not, nor is on the non-negative fractions: never stops.
- A well-founded relation is irreflexive, since gives the chain . So on is well-founded and is not.
- A relation on a finite set is well-founded exactly when it has no cycle. (The library proves this as
wf_iff_acyclic_if_finite.)
Well-founded relations are why programs terminate and why induction is sound.
- Termination. If each iteration of a loop, or each recursive call, moves to a smaller value in a
well-founded relation, the computation stops: an infinite computation would be an infinite descending
chain, provided the work between decreases also terminates. Euclid’s algorithm returns when
; otherwise it makes the recursive call
gcd n (m mod n). Its second argument decreases because whenever . When you define a function withfun, Isabelle looks for such a relation; that is the “termination order” it reported in Module 1. - Induction. To prove for all , it suffices to prove assuming that holds for everything smaller than (this proof is the induction step). If failed somewhere, the counterexamples would have a minimal element ; holds below , so the induction step proves , a contradiction.
Module 5 builds both ideas on this foundation.
Isabelle writes wf r for “r is well-founded”, with the same reading: (y, x) ∈ r means that y is
smaller. The library proves that < on the natural numbers is well-founded, as wf_less:
lemma "wf {(x, y). x < (y::nat)}"
by (simp add: wf_less)The command thm displays a theorem of the library by its name. This one says that well-founded means
“no infinite descending chain”:
thm wf_iff_no_infinite_down_chainwf ?r = (∄f. ∀i. (f (Suc i), f i) ∈ ?r)The chain is a function f on the natural numbers, f 0, f 1, f 2, … , and Suc i is i + 1.
∄ reads “there is no”, and = between two truth values is (Module 3). The question mark in
?r marks a variable of the theorem, which can be any relation; Module 7 says more. Finally, two
incomparable sets show that is not total:
value "{1::nat} ⊆ {2} ∨ {2} ⊆ {1::nat}""False"
:: "bool"Closures and reachability
A relation often lacks a property you need. “calls” is not transitive, but “can call, directly or indirectly” is; “can move in one step” is not, but “can reach” is. A closure adds the pairs that are missing, and nothing else.
Closures
The reflexive, symmetric or transitive closure of is the smallest relation that contains and has the property; “smallest” means that it is contained in every other such relation. For the paper definitions, take and keep closures on the chosen carrier .
- Reflexive closure on : . Symmetric closure: .
- Transitive closure: , so when a path of one or more -steps leads from to .
- Reflexive-transitive closure on : , paths of zero or more steps.
Isabelle writes r⇧+ and r⇧* (type r^+ and r^*), and calls them trancl and rtrancl.
Isabelle’s r⇧* uses the whole element type as its carrier, so it includes (x, x) even for values
outside a finite set being drawn. To restrict it to , take its intersection with .
For reachability from initial states in , a relation contained in cannot leave ,
so this distinction does not change the reachable states.
For , paths of two steps give , paths of three steps give , and there are none longer. So
which is on ; adds the pairs and gives . Figure 4.3, left, draws with the pairs that adds.
On a set with elements, every reachable pair has a path of at most steps. For different endpoints, remove repeated loops to get a path of at most steps. For equal endpoints in , keep a shortest non-empty cycle, which has at most steps; a zero-step path would not suffice for . So you can compute by adding the pairs of , then of , and so on, until nothing changes. The Transitive closure button of the widget in Section 4.2 computes the same relation.
- Zero steps count in . for every , even when has no loop at ; contains only when a cycle passes through .
- The order of closures matters. The smallest equivalence relation containing is : symmetric first, then reflexive and transitive. For it relates 1 and 2, through , but does not.
Reachability in a state machine
Module 1 described model checkers, which explore every reachable state of a system. Reachability is the reflexive-transitive closure.
A state machine consists of a set of states, a set of initial states, and a transition relation : when the system can move from to in one step. The reachable states are those with for some , that is, the image . A safety property says that no reachable state is bad.
A door is open or closed, and its bolt locked or unlocked: four states, CL (closed and locked), CU (closed, unlocked), OU (open, unlocked) and OL (open and locked). OL is bad: the bolt sticks out of an open door and will damage the frame. The transitions are unlock (CL to CU), lock (CU to CL), open (CU to OU) and close (OU to CU), and the door starts in CL.
From CL the door can only go to CU, from CU to CL or OU, and from OU back to CU. So the reachable states are CL, CU and OU, and the safety property “the door is never open and locked” holds. Now suppose a designer makes the lock button work in every state. That adds a transition from OU to OL, and OL becomes reachable along CL, CU, OU, OL: a counterexample trace, the kind of answer a model checker gives when a property fails.
Left: the relation (solid) and the pairs its transitive closure adds (dashed). Right: the door as a state machine. The green states are reachable from CL; the red dashed transition is the one the designer added, which makes the bad state OL reachable.
Real systems have billions of states, or infinitely many, which is why model checkers compute reachability by machine and why Module 13 proves safety properties with invariants instead.
To give the door’s transition relation a name, use definition. Like fun in Module 1, it introduces
a new constant with its type and a defining equation, but it allows no recursion, and a set written out
pair by pair needs none (Module 8 says more about both commands):
definition door :: "(string × string) set" where
"door = {(''CL'', ''CU''), (''CU'', ''CL''), (''CU'', ''OU''), (''OU'', ''CU'')}"consts
door :: "(char list × char list) set"The reachable states are the image of the initial state under the reflexive-transitive closure:
value "door* `` {''CL''}""{''OU'', ''CU'', ''CL''}"
:: "char list set"The bad state is not reachable, until the extra transition is added:
value "''OL'' ∈ door* `` {''CL''}"
value "''OL'' ∈ (door ∪ {(''OU'', ''OL'')})* `` {''CL''}""False"
:: "bool"
"True"
:: "bool"The transitive closure of the chain:
value "{(1::nat, 2), (2, 3), (3, 4)}+""{(1, 2), (2, 3), (3, 4), (2, 4), (1, 3), (1, 4)}"
:: "(nat × nat) set"And for all relations, contains and is transitive, and taking the reflexive-transitive closure twice adds nothing:
lemma "r ⊆ r+"
by auto
lemma "trans (r+)"
by simp
lemma "(r*)* = r*"
by simpFunctions
Mathematically, a function is a relation in which every input has exactly one output.
Functions as relations
A function from to , written , is a relation in which every is related to exactly one , written . is the domain of and its codomain. The image of a set is , and the image of the whole domain is the range of .
The codomain says where the values may lie, the range where they do lie: for squaring on , the codomain is and the range is .
In HOL, functions are not sets of pairs: nat ⇒ nat is a type of its own (Module 1), and its elements
are written with . λn. 2 * n is the function that takes n to 2 * n, written
in mathematics (type \lambda or %). Every HOL function is total: it has a value for every
element of its argument type. (This sense of “total” has nothing to do with the total relations of
Section 4.2.) A relation in which every input has at most one output is a partial function, such
as the input-output relation of a deterministic program that may not return a result. A mathematical
partial function can be represented in HOL by a total function returning the type option of Module 8:
either a value or None. This representation records undefinedness; it does not make a potentially
non-terminating program executable as a terminating HOL function. Isabelle writes the image of
a set as f ` A (one backquote) and the range as range f.
Injective, surjective, bijective
A function is
- injective (one-to-one) when different inputs give different outputs: ;
- surjective (onto ) when every element of is an output: , that is, ;
- bijective when it is both: it pairs the elements of and one to one.
- on is injective, since implies , but not surjective: 1 is not an output.
- on (division rounding down) is surjective but not injective: 0 and 1 both give 0.
- on is injective but not surjective: 0 is not an output.
- on is bijective: every integer is the output for exactly one input, .
The last two have the same formula and different properties: surjectivity depends on the domain and codomain. In software, injectivity means “no collisions”. For example, for a fixed key, deterministic encryption with exact decryption must map different plaintexts to different ciphertexts; otherwise decryption could not recover both messages correctly.
Inverses and composition
The composition of and is , with : first , then , read “g after f”. A function is an inverse of when for all and for all .
- If and are injective, so is ; if they are surjective, so is . So the composition of two bijections is a bijection.
- A function has an inverse exactly when it is bijective. The inverse is then unique, written , and its graph is the converse of the graph of .
- For bijections, .
For injectivity in the first part: if , then because is injective, and because is. The third part is the socks-and-shoes rule: socks go on first and come off last. A message that was compressed and then encrypted is decrypted first.
Isabelle’s names are inj f, surj f and bij f for functions on whole types, inj_on f A and
bij_betw f A B for functions on sets, inv f for the inverse and g ∘ f for composition (type
\circ). State that doubling is injective:
lemma "inj (λn::nat. 2 * n)"proof (prove)
goal (1 subgoal):
1. inj ((*) 2)Isabelle prints λn. 2 * n in a shorter form, (*) 2: multiplication with its first argument fixed
to 2. As in Section 4.2, the proof needs the definition, here inj_def:
by (auto simp: inj_def)More of the examples, and the first part of the fact:
lemma "¬ surj (λn::nat. n + 1)"
by (auto simp: surj_def)
lemma "bij (λn::int. n + 1)"
by (auto simp: bij_def inj_def surj_def)
lemma "inj f ⟶ inj g ⟶ inj (g ∘ f)"
by (auto simp: inj_def)inv f is defined for every HOL function. Injectivity guarantees that it undoes f on every input:
lemma "inj f ⟶ inv f (f x) = x"
by simpOn finite sets value decides these properties. Adding 1 and taking the remainder by 3 rotates
, a bijection of the set onto itself:
value "bij_betw (λx::nat. (x + 1) mod 3) {0, 1, 2} {0, 1, 2}""True"
:: "bool"When f is not surjective, inv f y still has a value for a y outside the range, because every HOL
function is total, but no inverse law is guaranteed there. Injectivity gives the left-inverse law
inv f (f x) = x; surjectivity gives the right-inverse law f (inv f y) = y. Bijectivity gives both.
Counting: cardinality and Cantor’s theorem
For finite sets you count. For infinite sets you cannot, but you can still compare sizes with functions, and the comparison holds a surprise.
Finite sets
The cardinality of a finite set is its number of elements. Isabelle writes card A, and
finite A for “A is finite”.
For finite sets and :
- , so when and are disjoint.
- and .
- If there is an injective function from to , then ; if there is a bijection, then .
The first rule is inclusion–exclusion: counts the elements of twice. On the file server, . The third rule compares sizes without counting, by pairing off elements, and that idea still works for infinite sets.
The pigeonhole principle
If and are finite and , then no function is injective: two different elements of have the same image. When is non-empty, every function maps at least elements of to some one element of . If is empty and is not, there is no function at all.
If more pigeons than holes fly into the holes, some hole holds two pigeons. Among any 13 people, two were born in the same month. A hash table with 1000 keys and 256 buckets has a bucket with at least keys, whatever the hash function. And no lossless compression program makes every file shorter: there are files of bits but only shorter ones, so two files would get the same compressed form.
card counts, and repeated elements count once:
value "card {1, 2, 3, 2, 1 :: nat}"
value "card (Pow {1, 2, 3 :: nat})""3"
:: "nat"
"8"
:: "nat"Thirteen numbers have only twelve possible remainders by 12, so the remainder is not injective on them:
value "inj_on (λn::nat. n mod 12) {0..12}""False"
:: "bool"The library proves the counting rules for all finite sets. The rule for power sets is card_Pow:
lemma "finite A ⟶ card (Pow A) = 2 ^ card A"
by (simp add: card_Pow)The pigeonhole principle is pigeonhole. It speaks about the image f ` A of Section 4.6: if the
image has fewer elements than A, two elements of A share an image, so f is not injective on A.
lemma "card (f ` A) < card A ⟶ ¬ inj_on f A"
by (simp add: pigeonhole)In Isabelle, card of an infinite set is 0. That keeps card a total function, but statements about
card usually need the assumption finite A, as in the lemma about power sets above.
lemma "card (UNIV :: nat set) = 0"
by simpCountable sets
For infinite sets, take the third counting rule as the definition: two sets have the same cardinality when there is a bijection between them. Strange things happen at once: is a bijection from to the even numbers, so a proper subset of is as large as itself.
A set is countable when there is an injective function from to . Equivalently, is finite or its elements can be listed as , each appearing somewhere in the list.
The integers are countable: list them as . So are the pairs of natural numbers, listed diagonal by diagonal: , , , , , , … . So are the finite strings over a finite alphabet, listed by length and then alphabetically; in particular, the programs of any programming language form a countable set. Is every set countable, then? No, and the proof is one of the most famous in mathematics.
Cantor’s theorem
For every set , no function is surjective.
Since is injective, is at least as large as ; Cantor’s theorem says it is strictly larger. Georg Cantor published the proof, the diagonal argument, in 1891.
Take any . Each is a set that may or may not contain itself. Collect the elements that are not in their own set:
, so . Suppose were surjective. Then for some . Is in ? The first step below is the definition of (it applies because ); the second replaces by , which is equal to it:
So , and a proposition equivalent to its own negation is impossible:
| P | P ⟷ ¬P |
|---|---|
| T | F |
| F | F |
Contradiction: false in every row.
The assumption that is surjective has led to a contradiction, so it is false: no has , and is not surjective. Figure 4.4 shows where the name comes from.
The diagonal argument for . Row shows which numbers are in the set (1 for “in”, 0 for “not in”). flips the diagonal, so it differs from the set at position , for every : is in no row.
A subset of describes a decision problem, such as “is this number prime?”. A program decides such a set only if it halts with the correct yes-or-no answer on every input. There are countably many programs, so at most countably many decidable sets, while is uncountable. Thus undecidable problems must exist. This is a counting argument: it does not give an algorithm that lists exactly the programs which halt on every input. Turing’s proof that the halting problem is undecidable (Module 1) is a diagonal argument too.
Bertrand Russell found in 1901 that the same trick breaks naive set theory, which lets every property
define a set: then , the set of all sets that are not elements of themselves,
would be a set, and . HOL avoids the paradox with types: x ∈ x is a type
error, because a set and its elements have different types, and for the same reason there is no set of
everything (Section 4.1).
The heart of the proof is that the diagonal set is not a value of f. range f is the set of all
values of f:
lemma diagonal: "{x. x ∉ f x} ∉ range f"
by autoCantor’s theorem for every type follows: a surjective f would have every set in its range, the
diagonal set included. auto does not find this proof, but force does. force is a relative of
auto that searches harder, and more slowly, and either proves the goal completely or fails; Module 9
introduces it properly. Here it even finds the diagonal set by itself:
lemma cantor: "¬ surj (f :: 'a ⇒ 'a set)"
by forceSo no sequence f 0, f 1, f 2, … of sets of natural numbers contains them all; the name cantor
lets a later proof use the lemma:
lemma "¬ surj (f :: nat ⇒ nat set)"
by (simp add: cantor)The library has the theorem for every set A, as Cantors_theorem:
thm Cantors_theorem∄f. f ` ?A = Pow ?AWhat you learned
- A set is determined by its elements (extensionality), and . In HOL every set has an element type.
- Union, intersection, difference and complement are , , “and not” and
applied to membership, so set laws are propositional laws, which Isabelle proves with
auto. - A relation is a set of pairs. It can be reflexive, irreflexive, symmetric, antisymmetric, transitive or total; a property fails exactly when a witness exists. Converse and composition build new relations.
- Equivalence relations correspond to partitions. Partial orders are drawn as Hasse diagrams. Well-founded relations have no infinite descending chains, which is why programs terminate and induction works.
- The closures and (
r⇧+,r⇧*) add the pairs joined by paths, and the reachable states of a state machine are the image of its initial states under . - A function can be injective, surjective, both (bijective), or neither. It has a
two-sided inverse exactly when it is bijective. Isabelle’s
invis defined more generally; inverse laws require the appropriate assumptions (inj,surj,bij). - Cardinality counts finite sets (
card,finite). The pigeonhole principle forbids injections into smaller sets, and Cantor’s diagonal argument shows that no set can be mapped onto its power set: some sets are uncountable, and some problems have no program.
Exercises
Let , and .
- Compute , , , and , and check your answers
with
value. - Which of these are true: , , ?
Show solution
- , , , and . In Isabelle:
value "{1, 2, 3, 4} - {3, 4, 5 :: nat}"
value "{3, 4, 5} - {1, 2, 3, 4 :: nat}"
value "{1, 2, 3, 4} ∩ {3, 4, 5} ∩ {1, 5 :: nat}"
value "{1, 5 :: nat} × {0, 1 :: nat}"
value "Pow {1, 5 :: nat}""{1, 2}"
:: "nat set"
"{5}"
:: "nat set"
"{}"
:: "nat set"
"{(1, 0), (1, 1), (5, 0), (5, 1)}"
:: "(nat × nat) set"
"{{5}, {}, {1}, {1, 5}}"
:: "nat set set"- All three are true. , and and are subsets of , so they are elements of .
Which of the six properties of Section 4.2 do these relations on have? For every property that fails, give a witness, and check your answers with the widget.
Show solution
- is reflexive, symmetric and transitive: an equivalence relation with the classes , and . It is not irreflexive (witness ), not antisymmetric ( and , but ) and not total (neither nor ).
- , a cycle, is irreflexive and antisymmetric. It is not reflexive (no ), not symmetric ( without ), not transitive ( and without ) and not total (neither nor ).
- is irreflexive, antisymmetric and transitive; transitivity holds vacuously, as no path has two steps. It is not reflexive (no ), not symmetric ( without ) and not total (neither nor ). It is a strict order.
- Prove on paper by translating it into propositional logic, and then in Isabelle.
- Someone claims . Find a counterexample with the method of Section 4.1, then let Nitpick find one, and compare.
Show solution
-
translates to , which De Morgan’s law turns into . The right side translates to , the same formula, because . In Isabelle, no type annotation is needed, since
∪and∩exist only for sets:lemma "A - (B ∪ C) = (A - B) ∩ (A - C)" by auto -
and differ exactly when and are true: then the left side is false and the right side true. With and , the left side is and the right side . Nitpick:
lemma "(A ∪ B) - C = A ∪ (B - C)" nitpick [card 'a = 1] oopsNitpicking formula... Nitpick found a counterexample for card 'a = 1: Free variables: A = {a1} B = {} C = {a1}It is the same counterexample, with a₁ for .
A program has the functions main, parse, lex, eval and apply. main calls parse and eval, parse calls lex, eval calls apply, and apply calls eval.
- Which functions can main call, directly or indirectly?
- A function is recursive when it can call itself, directly or indirectly. Express this with the transitive closure, and find the recursive functions.
- Check both answers in Isabelle.
Show solution
- parse, lex, eval and apply: the image of under .
- is recursive when . eval and apply are, through the cycle eval, apply, eval; main, parse and lex are not.
- With a definition for the call graph:
definition calls :: "(string × string) set" where
"calls = {(''main'', ''parse''), (''main'', ''eval''), (''parse'', ''lex''),
(''eval'', ''apply''), (''apply'', ''eval'')}"
value "calls+ `` {''main''}"
value "(''apply'', ''apply'') ∈ calls+"
value "(''main'', ''main'') ∈ calls+"consts
calls :: "(char list × char list) set"
"{''parse'', ''lex'', ''apply'', ''eval''}"
:: "char list set"
"True"
:: "bool"
"False"
:: "bool"Classify each function as injective, surjective, both or neither, and give the inverse of each
bijection. Check the fourth with value.
- ,
- ,
- ,
- ,
Show solution
- Injective, not surjective: 0, 1 and 2 are not outputs.
- Bijective, and its own inverse: .
- Surjective, since ; not injective, since .
- Bijective: maps 0, 1, 2, 3 to 0, 3, 2, 1. It is its own inverse, because .
value "bij_betw (λn::nat. 3 * n mod 4) {0, 1, 2, 3} {0, 1, 2, 3}""True"
:: "bool"Let and be equivalence relations on .
- Prove that is an equivalence relation on , on paper and in Isabelle.
- Show with an example on that need not be one, and check it with
value. - What is the smallest equivalence relation on that contains ?
Show solution
-
Reflexive: for , is in and in . Symmetric: if is in both, so is , because both are symmetric. Transitive: if and are in both, so is , because both are transitive. In Isabelle,
sym_Intandtrans_Intare the library’s versions of the last two steps:lemma "equiv A R ⟶ equiv A S ⟶ equiv A (R ∩ S)" by (auto simp: equiv_def refl_on_def sym_Int trans_Int) -
Let relate 1 and 2, and relate 2 and 3, each with all pairs . Then contains and but not :
value "trans_on {1, 2, 3} ({(1::nat, 1), (2, 2), (3, 3), (1, 2), (2, 1)} ∪ {(1, 1), (2, 2), (3, 3), (2, 3), (3, 2)})""False" :: "bool" -
. It is reflexive on because it contains , symmetric because a path read backwards is again a path of , and transitive. An equivalence relation that contains is transitive, so it contains every path, that is, all of .
An infinite bit sequence is a function from to , in HOL a function of type
nat ⇒ bool. Adapt Cantor’s diagonal argument to show that no list of such
sequences contains them all: give the missing sequence and explain why it is missing. Then prove in
Isabelle that it is not in the range of f. (Hint: two functions are equal when they agree on every
argument; the library calls this fun_eq_iff.)
Show solution
Let be the sequence whose -th bit is the opposite of the -th bit of : . If for some , the two functions agree at : , which is impossible. So is not in the list, and the set of infinite bit sequences is uncountable. This is Figure 4.4 again: a set of natural numbers and the bit sequence “1 at when is in the set” describe the same thing. (A similar argument shows that the real numbers are uncountable.)
lemma "(λn. ¬ f n n) ∉ range (f :: nat ⇒ nat ⇒ bool)"
by (auto simp: fun_eq_iff)fun_eq_iff turns the equation between functions into one about all arguments, and auto then finds
the argument on its own.