2.7. Type Classes and Property-Based Testing
Proving a program correct takes work. Before investing that effort, it is prudent to gain some confidence that the specification is right and that the program satisfies it — after all, trying to prove a false theorem is the most frustrating way to waste time. An effective technique for this is property-based testing: we state the desired property as a formula and let a tool automatically generate hundreds of random inputs, looking for a counterexample.
In Lean, this technique is implemented by the Plausible library, inspired by Haskell's QuickCheck. To generate random values of a type, Plausible needs to know how to generate them and how to simplify them; this information is supplied through type classes. That is why we begin the chapter by studying type classes in more depth than in the chapter on functional programming. We then present Plausible and, finally, apply both techniques — testing and proving — to a complete example: insertion sort.
namespace Ch14
2.7.1. Type classes
A type class describes an interface: a set of operations (and possibly of
properties) that a type may offer. An instance of the class for a concrete
type supplies the implementations. When a function requires an instance
argument [C α], Lean finds the appropriate instance automatically, based on
the type α. The mechanism lets us write generic code without giving up type
checking — it is what is known as ad hoc polymorphism.
2.7.1.1. A simple class
As a first example, we define a class for types whose values can be displayed as strings:
class Display (α : Type) where
display : α → String
Instances for concrete types provide the display function:
instance : Display Nat where
display n := s!"Nat({n})"
instance : Display Bool where
display b := if b then "yes" else "no"
More interesting are parametric instances, which build an instance for a compound type from instances for its components. A pair can be displayed if both of its components can; a list can be displayed if its elements can:
instance {α β : Type} [Display α] [Display β] :
Display (α × β) where
display p :=
s!"({Display.display p.1}, {Display.display p.2})"
instance {α : Type} [Display α] : Display (List α) where
display xs :=
"[" ++ String.intercalate ", "
(xs.map Display.display) ++ "]"
When evaluating Display.display on a list of pairs, Lean composes the
instances automatically:
#eval Display.display
([(1, true), (2, false)] : List (Nat × Bool))
Generic functions can require the constraint [Display α] and use display
without knowing what the concrete type is:
def displayAll {α : Type} [Display α] (xs : List α) :
List String :=
xs.map Display.display
2.7.1.2. Standard library classes
Lean's library uses type classes extensively. Some of the most common ones are
BEq (Boolean equality, the == operator), Ord (three-way comparison,
compare), ToString (conversion to text, used in s!"…" interpolations),
Repr (the representation used by #eval) and the arithmetic classes Add,
Mul, Zero and One, which give meaning to the symbols +, *, 0 and
1.
#eval compare (2 : Nat) 5
To illustrate the arithmetic classes, we define the type of integers modulo 2, the field with two elements, together with its addition and multiplication:
inductive Mod2 : Type where
| zero : Mod2
| one : Mod2
deriving Repr, DecidableEq
def Mod2.add : Mod2 → Mod2 → Mod2
| .zero, x => x
| x, .zero => x
| .one, .one => .zero
def Mod2.mul : Mod2 → Mod2 → Mod2
| .one, .one => .one
| _, _ => .zero
By registering instances of the arithmetic classes, we can use the usual notation:
instance : Add Mod2 where add := Mod2.add
instance : Mul Mod2 where mul := Mod2.mul
instance : Zero Mod2 where zero := .zero
instance : One Mod2 where one := .one
#eval (1 : Mod2) + 1
2.7.1.3. Classes with properties
Type classes in Lean can contain not only operations but also properties that these operations must satisfy. An instance can only be declared if we supply proofs of these properties. The class below describes a monoid: a type with an associative operation and a neutral element.
class MyMonoid (α : Type) where
neutral : α
op : α → α → α
neutral_op : ∀ a : α, op neutral a = a
op_neutral : ∀ a : α, op a neutral = a
op_assoc : ∀ a b c : α, op a (op b c) = op (op a b) c
The natural numbers with addition, Mod2 with its addition and lists with
concatenation are monoids. In each case, the proofs are short: for the
naturals, simp and omega suffice; for Mod2, since the type is finite, it
is enough to analyze all cases (cases a <;> rfl applies rfl to each
generated case); for lists, we use the associativity of concatenation.
instance : MyMonoid Nat where
neutral := 0
op := (· + ·)
neutral_op := ⊢ ∀ (a : ℕ), 0 + a = a a:ℕ⊢ 0 + a = a; All goals completed! 🐙
op_neutral := ⊢ ∀ (a : ℕ), a + 0 = a a:ℕ⊢ a + 0 = a; All goals completed! 🐙
op_assoc := ⊢ ∀ (a b c : ℕ), a + (b + c) = a + b + c a:ℕb:ℕc:ℕ⊢ a + (b + c) = a + b + c; All goals completed! 🐙
instance : MyMonoid Mod2 where
neutral := .zero
op := Mod2.add
neutral_op := ⊢ ∀ (a : Mod2), Mod2.zero.add a = a a:Mod2⊢ Mod2.zero.add a = a; ⊢ Mod2.zero.add Mod2.zero = Mod2.zero⊢ Mod2.zero.add Mod2.one = Mod2.one ⊢ Mod2.zero.add Mod2.zero = Mod2.zero⊢ Mod2.zero.add Mod2.one = Mod2.one All goals completed! 🐙
op_neutral := ⊢ ∀ (a : Mod2), a.add Mod2.zero = a a:Mod2⊢ a.add Mod2.zero = a; ⊢ Mod2.zero.add Mod2.zero = Mod2.zero⊢ Mod2.one.add Mod2.zero = Mod2.one ⊢ Mod2.zero.add Mod2.zero = Mod2.zero⊢ Mod2.one.add Mod2.zero = Mod2.one All goals completed! 🐙
op_assoc := ⊢ ∀ (a b c : Mod2), a.add (b.add c) = (a.add b).add c
intro a a:Mod2b:Mod2⊢ ∀ (c : Mod2), a.add (b.add c) = (a.add b).add c a:Mod2b:Mod2c:Mod2⊢ a.add (b.add c) = (a.add b).add c
b:Mod2c:Mod2⊢ Mod2.zero.add (b.add c) = (Mod2.zero.add b).add cb:Mod2c:Mod2⊢ Mod2.one.add (b.add c) = (Mod2.one.add b).add c b:Mod2c:Mod2⊢ Mod2.zero.add (b.add c) = (Mod2.zero.add b).add cb:Mod2c:Mod2⊢ Mod2.one.add (b.add c) = (Mod2.one.add b).add c c:Mod2⊢ Mod2.one.add (Mod2.zero.add c) = (Mod2.one.add Mod2.zero).add cc:Mod2⊢ Mod2.one.add (Mod2.one.add c) = (Mod2.one.add Mod2.one).add c c:Mod2⊢ Mod2.zero.add (Mod2.zero.add c) = (Mod2.zero.add Mod2.zero).add cc:Mod2⊢ Mod2.zero.add (Mod2.one.add c) = (Mod2.zero.add Mod2.one).add cc:Mod2⊢ Mod2.one.add (Mod2.zero.add c) = (Mod2.one.add Mod2.zero).add cc:Mod2⊢ Mod2.one.add (Mod2.one.add c) = (Mod2.one.add Mod2.one).add c ⊢ Mod2.one.add (Mod2.one.add Mod2.zero) = (Mod2.one.add Mod2.one).add Mod2.zero⊢ Mod2.one.add (Mod2.one.add Mod2.one) = (Mod2.one.add Mod2.one).add Mod2.one ⊢ Mod2.zero.add (Mod2.zero.add Mod2.zero) = (Mod2.zero.add Mod2.zero).add Mod2.zero⊢ Mod2.zero.add (Mod2.zero.add Mod2.one) = (Mod2.zero.add Mod2.zero).add Mod2.one⊢ Mod2.zero.add (Mod2.one.add Mod2.zero) = (Mod2.zero.add Mod2.one).add Mod2.zero⊢ Mod2.zero.add (Mod2.one.add Mod2.one) = (Mod2.zero.add Mod2.one).add Mod2.one⊢ Mod2.one.add (Mod2.zero.add Mod2.zero) = (Mod2.one.add Mod2.zero).add Mod2.zero⊢ Mod2.one.add (Mod2.zero.add Mod2.one) = (Mod2.one.add Mod2.zero).add Mod2.one⊢ Mod2.one.add (Mod2.one.add Mod2.zero) = (Mod2.one.add Mod2.one).add Mod2.zero⊢ Mod2.one.add (Mod2.one.add Mod2.one) = (Mod2.one.add Mod2.one).add Mod2.one All goals completed! 🐙
instance {α : Type} : MyMonoid (List α) where
neutral := []
op := (· ++ ·)
neutral_op := α:Type⊢ ∀ (a : List α), [] ++ a = a α:Typea:List α⊢ [] ++ a = a; All goals completed! 🐙
op_neutral := α:Type⊢ ∀ (a : List α), a ++ [] = a α:Typea:List α⊢ a ++ [] = a; All goals completed! 🐙
op_assoc := α:Type⊢ ∀ (a b c : List α), a ++ (b ++ c) = a ++ b ++ c α:Typea:List αb:List αc:List α⊢ a ++ (b ++ c) = a ++ b ++ c; All goals completed! 🐙
The advantage of including the laws in the class is that we can prove generic theorems, valid for every monoid, using only the laws. For example, the neutral element is unique:
theorem neutral_unique {α : Type} [MyMonoid α] (e : α)
(h : ∀ a : α, MyMonoid.op e a = a) :
e = MyMonoid.neutral := α:Typeinst✝:MyMonoid αe:αh:∀ (a : α), MyMonoid.op e a = a⊢ e = MyMonoid.neutral
α:Typeinst✝:MyMonoid αe:αh:∀ (a : α), MyMonoid.op e a = ah1:MyMonoid.op e MyMonoid.neutral = MyMonoid.neutral⊢ e = MyMonoid.neutral
α:Typeinst✝:MyMonoid αe:αh:∀ (a : α), MyMonoid.op e a = ah1:e = MyMonoid.neutral⊢ e = MyMonoid.neutral
All goals completed! 🐙
The proof instantiates the hypothesis with a := neutral, obtaining
op e neutral = neutral; by the op_neutral law, the left-hand side is e.
2.7.1.4. Derived instances
For many classes, the instance is so mechanical that Lean can generate it on
its own. The deriving clause requests this automatic generation:
structure Point where
x : Int
y : Int
deriving Repr, BEq, DecidableEq
inductive Color where
| red
| green
| blue
deriving Repr, BEq, DecidableEq, Inhabited
#eval Point.mk 1 2 == Point.mk 1 2
The default value (default) derived for an enumerated type is its first
constructor:
#eval (default : Color)
2.7.1.5. Functor, Applicative and Monad
The classes Functor, Applicative and Monad generalize the idea of
"computation in a context". A Functor lets us apply a pure function to a
value inside the context (f <$> x); an Applicative lets us combine
independent contexts; and a Monad lets us chain computations in which the
second depends on the result of the first. We illustrate with a type analogous
to Option, which represents a possibly missing value:
inductive Maybe (α : Type) : Type where
| nothing : Maybe α
| just : α → Maybe α
deriving Repr
instance : Functor Maybe where
map f
| .nothing => .nothing
| .just x => .just (f x)
instance : Applicative Maybe where
pure := .just
seq mf mx :=
match mf with
| .nothing => .nothing
| .just f => f <$> mx ()
instance : Monad Maybe where
bind mx f :=
match mx with
| .nothing => .nothing
| .just x => f x
With the Monad instance, we can use do notation, in which each ←
corresponds to a bind. The function below chains two safe divisions; if any
divisor is zero, the result is nothing, without our having to test each step
explicitly:
def safeDiv (n d : Nat) : Maybe Nat :=
if d == 0 then .nothing else .just (n / d)
def compute (a b c : Nat) : Maybe Nat := do
let x ← safeDiv a b
let y ← safeDiv x c
return y
#eval compute 100 5 4
#eval compute 100 0 4
2.7.2. Property-based testing with Plausible
The Plausible library tests a proposition by generating random values for its universally quantified variables and evaluating the proposition for each choice. For this, the proposition must be decidable once the values are fixed, and the types of the variables must be sampleable.
There are two ways to use Plausible. The first is the function
Plausible.Testable.check, which can be called with #eval:
open Plausible in
#eval Testable.check
(∀ a b : Nat, Nat.gcd a b = Nat.gcd b a)
The second is the plausible tactic, which tests the current goal. If it
finds a counterexample, the tactic fails and displays it; otherwise, it emits
the message "Unable to find a counter-example" and closes the goal without
proving it, by means of a sorry. It is important to understand this
behavior: Plausible proves nothing, it only increases our confidence that the
property is true. That is why Lean warns that the declaration uses sorry:
example (xs : List Nat) : xs.reverse.reverse = xs := xs:List ℕ⊢ xs.reverse.reverse = xs
All goals completed! 🐙
When the property is false, Plausible finds a counterexample and then shrinks it: it tries simpler values that still violate the property, until it reaches a minimal counterexample. Below, we test the (false) commutativity of list concatenation; we fix the seed of the random generator so that the result is reproducible:
example (xs ys : List Nat) : xs ++ ys = ys ++ xs := xs:List ℕys:List ℕ⊢ xs ++ ys = ys ++ xs
All goals completed! 🐙
2.7.2.1. Generators for new types
To test properties of a user-defined type, such as Mod2, we need to teach
Plausible two things, again by means of type classes. The Shrinkable class
says how to simplify a value (returning a list of "smaller" candidates); the
Arbitrary class provides a random generator, written in the Gen monad:
instance : Plausible.Shrinkable Mod2 where
shrink
| .zero => []
| .one => [.zero]
open Plausible Gen in
instance : Arbitrary Mod2 where
arbitrary := do
let b ← chooseAny Bool
return if b then .one else .zero
With these instances (and the derived Repr instance, used to display
counterexamples), Plausible can already test algebraic properties of Mod2:
open Plausible in
#eval Testable.check
(∀ a b c : Mod2, a * (b + c) = a * b + a * c)
Since Mod2 is finite, this property can also be proved by exhaustive case
analysis — which gives a definitive guarantee, unlike testing:
theorem mod2_distrib (a b c : Mod2) :
a * (b + c) = a * b + a * c := a:Mod2b:Mod2c:Mod2⊢ a * (b + c) = a * b + a * c
b:Mod2c:Mod2⊢ Mod2.zero * (b + c) = Mod2.zero * b + Mod2.zero * cb:Mod2c:Mod2⊢ Mod2.one * (b + c) = Mod2.one * b + Mod2.one * c b:Mod2c:Mod2⊢ Mod2.zero * (b + c) = Mod2.zero * b + Mod2.zero * cb:Mod2c:Mod2⊢ Mod2.one * (b + c) = Mod2.one * b + Mod2.one * c c:Mod2⊢ Mod2.one * (Mod2.zero + c) = Mod2.one * Mod2.zero + Mod2.one * cc:Mod2⊢ Mod2.one * (Mod2.one + c) = Mod2.one * Mod2.one + Mod2.one * c c:Mod2⊢ Mod2.zero * (Mod2.zero + c) = Mod2.zero * Mod2.zero + Mod2.zero * cc:Mod2⊢ Mod2.zero * (Mod2.one + c) = Mod2.zero * Mod2.one + Mod2.zero * cc:Mod2⊢ Mod2.one * (Mod2.zero + c) = Mod2.one * Mod2.zero + Mod2.one * cc:Mod2⊢ Mod2.one * (Mod2.one + c) = Mod2.one * Mod2.one + Mod2.one * c ⊢ Mod2.one * (Mod2.one + Mod2.zero) = Mod2.one * Mod2.one + Mod2.one * Mod2.zero⊢ Mod2.one * (Mod2.one + Mod2.one) = Mod2.one * Mod2.one + Mod2.one * Mod2.one ⊢ Mod2.zero * (Mod2.zero + Mod2.zero) = Mod2.zero * Mod2.zero + Mod2.zero * Mod2.zero⊢ Mod2.zero * (Mod2.zero + Mod2.one) = Mod2.zero * Mod2.zero + Mod2.zero * Mod2.one⊢ Mod2.zero * (Mod2.one + Mod2.zero) = Mod2.zero * Mod2.one + Mod2.zero * Mod2.zero⊢ Mod2.zero * (Mod2.one + Mod2.one) = Mod2.zero * Mod2.one + Mod2.zero * Mod2.one⊢ Mod2.one * (Mod2.zero + Mod2.zero) = Mod2.one * Mod2.zero + Mod2.one * Mod2.zero⊢ Mod2.one * (Mod2.zero + Mod2.one) = Mod2.one * Mod2.zero + Mod2.one * Mod2.one⊢ Mod2.one * (Mod2.one + Mod2.zero) = Mod2.one * Mod2.one + Mod2.one * Mod2.zero⊢ Mod2.one * (Mod2.one + Mod2.one) = Mod2.one * Mod2.one + Mod2.one * Mod2.one All goals completed! 🐙
2.7.3. Case study: insertion sort
We now combine testing and proving in a complete example. Insertion sort is
based on the function ins, which inserts an element into an already sorted
list, at the right position:
def ins (x : ℕ) : List ℕ → List ℕ
| [] => [x]
| y :: ys =>
if x ≤ y then x :: y :: ys
else y :: ins x ys
def isort : List ℕ → List ℕ
| [] => []
| x :: xs => ins x (isort xs)
#eval isort [5, 3, 8, 1, 3]
What does it mean to say that isort is correct? Two things: the result is
sorted, and the result is a permutation of the input (that is, it contains the
same elements, with the same multiplicities). Without the second condition,
the constant function returning [] would be a correct "sort"!
2.7.3.1. Testing the specification
To test, we need executable versions of the two properties. The function
isSorted checks sortedness by comparing consecutive elements; isPermOf
checks whether each element occurs the same number of times in both lists:
def isSorted : List ℕ → Bool
| [] => true
| [_] => true
| x :: y :: t => x ≤ y && isSorted (y :: t)
def isPermOf (xs ys : List ℕ) : Bool :=
(xs ++ ys).all (fun n => xs.count n == ys.count n)
We first test the properties of ins and then those of isort:
open Plausible in
#eval Testable.check (∀ (x : ℕ) (xs : List ℕ),
isSorted xs = true → isSorted (ins x xs) = true)
open Plausible in
#eval Testable.check (∀ (x : ℕ) (xs : List ℕ),
isPermOf (x :: xs) (ins x xs) = true)
open Plausible in
#eval Testable.check (∀ xs : List ℕ,
isSorted (isort xs) = true ∧
isPermOf xs (isort xs) = true)
One detail: in the first test, the hypothesis isSorted xs = true is rarely
satisfied by long random lists. Plausible discards the cases in which the
hypothesis is false, so the property is effectively tested on only a few
lists, usually short ones. This is a well-known limitation of property-based
testing with preconditions.
2.7.3.2. Logical specification
The tests passed; on to the proofs. For these we use logical specifications,
given by inductive predicates. The predicate Sorted is the same as in the
previous chapter:
inductive Sorted : List ℕ → Prop where
| nil : Sorted []
| single (x : ℕ) : Sorted [x]
| two_or_more (x y : ℕ) {zs : List ℕ} (hle : x ≤ y)
(hsorted : Sorted (y :: zs)) : Sorted (x :: y :: zs)
Permutations are defined by four rules: the empty list is a permutation of
itself; we can add the same element in front of two permuted lists (skip);
swapping the first two elements gives a permutation (swap); and permutations
compose (trans).
inductive Perm {α : Type} : List α → List α → Prop where
| nil : Perm [] []
| skip (x : α) {xs ys : List α} :
Perm xs ys → Perm (x :: xs) (x :: ys)
| swap (x y : α) (xs : List α) :
Perm (x :: y :: xs) (y :: x :: xs)
| trans {xs ys zs : List α} :
Perm xs ys → Perm ys zs → Perm xs zs
local infix:50 " ~ " => Perm
The relation ~ is reflexive, by induction on the list (using skip), and
symmetric, by induction on the permutation proof (in the trans case, the
induction hypotheses are combined in reverse order):
theorem Perm_refl {α : Type} : ∀ xs : List α, xs ~ xs := α:Type⊢ ∀ (xs : List α), xs ~ xs
α:Typexs:List α⊢ xs ~ xs
induction xs with
α:Type⊢ [] ~ [] All goals completed! 🐙
α:Typex:αxs:List αih:xs ~ xs⊢ x :: xs ~ x :: xs All goals completed! 🐙
theorem Perm_sym {α : Type} :
∀ xs ys : List α, xs ~ ys → ys ~ xs := α:Type⊢ ∀ (xs ys : List α), xs ~ ys → ys ~ xs
intro xs α:Typexs:List αys:List α⊢ xs ~ ys → ys ~ xs α:Typexs:List αys:List αh:xs ~ ys⊢ ys ~ xs
induction h with
α:Typexs:List αys:List α⊢ [] ~ [] All goals completed! 🐙
α:Typexs:List αys:List αx:αxs_1:List αys_1:List αa:xs_1 ~ ys_1ih:ys_1 ~ xs_1⊢ x :: ys_1 ~ x :: xs_1 All goals completed! 🐙
α:Typexs:List αys:List αx:αy:αzs:List α⊢ y :: x :: zs ~ x :: y :: zs All goals completed! 🐙
α:Typexs:List αys:List αxs_1:List αys_1:List αzs:List αa:xs_1 ~ ys_1a_1:ys_1 ~ zsih1:ys_1 ~ xs_1ih2:zs ~ ys_1⊢ zs ~ xs_1 All goals completed! 🐙
2.7.3.3. Equations for ins
The function ins is defined with an if. To reason about it, it is
convenient to have lemmas giving its value when the condition is true or
false. The change tactic replaces the goal by a definitionally equal one —
here, the unfolded body of ins —, and then if_pos/if_neg resolve the
if:
theorem ins_pos {x y : ℕ} (ys : List ℕ) (h : x ≤ y) :
ins x (y :: ys) = x :: y :: ys := x:ℕy:ℕys:List ℕh:x ≤ y⊢ ins x (y :: ys) = x :: y :: ys
x:ℕy:ℕys:List ℕh:x ≤ y⊢ (if x ≤ y then x :: y :: ys else y :: ins x ys) = x :: y :: ys
All goals completed! 🐙
theorem ins_neg {x y : ℕ} (ys : List ℕ) (h : ¬ x ≤ y) :
ins x (y :: ys) = y :: ins x ys := x:ℕy:ℕys:List ℕh:¬x ≤ y⊢ ins x (y :: ys) = y :: ins x ys
x:ℕy:ℕys:List ℕh:¬x ≤ y⊢ (if x ≤ y then x :: y :: ys else y :: ins x ys) = y :: ins x ys
All goals completed! 🐙
2.7.3.4. ins preserves sortedness
The delicate part of the proof that ins preserves Sorted is the case in
which x does not end up at the head: we know that y :: z :: zs is sorted,
that y < x and (by the induction hypothesis) that ins x (z :: zs) is
sorted, and we need to conclude that y :: ins x (z :: zs) is sorted. To
apply the two_or_more rule, we need to know that y is less than or equal
to the head of ins x (z :: zs). That head is either x or z, and in
both cases the result holds. We isolate this reasoning in an auxiliary lemma:
theorem ins_sorted_aux (y x : ℕ) (xs : List ℕ)
(hyx : y ≤ x) (hys : Sorted (y :: xs))
(hins : Sorted (ins x xs)) :
Sorted (y :: ins x xs) := y:ℕx:ℕxs:List ℕhyx:y ≤ xhys:Sorted (y :: xs)hins:Sorted (ins x xs)⊢ Sorted (y :: ins x xs)
cases xs with
y:ℕx:ℕhyx:y ≤ xhys:Sorted [y]hins:Sorted (ins x [])⊢ Sorted (y :: ins x [])
All goals completed! 🐙
y:ℕx:ℕhyx:y ≤ xz:ℕzs:List ℕhys:Sorted (y :: z :: zs)hins:Sorted (ins x (z :: zs))⊢ Sorted (y :: ins x (z :: zs))
have hyz : y ≤ z := y:ℕx:ℕxs:List ℕhyx:y ≤ xhys:Sorted (y :: xs)hins:Sorted (ins x xs)⊢ Sorted (y :: ins x xs)
cases hys with
y:ℕx:ℕhyx:y ≤ xz:ℕzs:List ℕhins:Sorted (ins x (z :: zs))h:y ≤ zhsorted:Sorted (z :: zs)⊢ y ≤ z All goals completed! 🐙
y:ℕx:ℕhyx:y ≤ xz:ℕzs:List ℕhys:Sorted (y :: z :: zs)hins:Sorted (ins x (z :: zs))hyz:y ≤ zhxz:x ≤ z⊢ Sorted (y :: ins x (z :: zs))y:ℕx:ℕhyx:y ≤ xz:ℕzs:List ℕhys:Sorted (y :: z :: zs)hins:Sorted (ins x (z :: zs))hyz:y ≤ zhxz:¬x ≤ z⊢ Sorted (y :: ins x (z :: zs))
y:ℕx:ℕhyx:y ≤ xz:ℕzs:List ℕhys:Sorted (y :: z :: zs)hins:Sorted (ins x (z :: zs))hyz:y ≤ zhxz:x ≤ z⊢ Sorted (y :: ins x (z :: zs)) y:ℕx:ℕhyx:y ≤ xz:ℕzs:List ℕhys:Sorted (y :: z :: zs)hins:Sorted (x :: z :: zs)hyz:y ≤ zhxz:x ≤ z⊢ Sorted (y :: x :: z :: zs)
All goals completed! 🐙
y:ℕx:ℕhyx:y ≤ xz:ℕzs:List ℕhys:Sorted (y :: z :: zs)hins:Sorted (ins x (z :: zs))hyz:y ≤ zhxz:¬x ≤ z⊢ Sorted (y :: ins x (z :: zs)) y:ℕx:ℕhyx:y ≤ xz:ℕzs:List ℕhys:Sorted (y :: z :: zs)hins:Sorted (z :: ins x zs)hyz:y ≤ zhxz:¬x ≤ z⊢ Sorted (y :: z :: ins x zs)
All goals completed! 🐙
In the case xs = [], we have ins x [] = [x] and y ≤ x suffices. In the
case xs = z :: zs, we extract y ≤ z from the sortedness hypothesis (by
inversion with cases) and distinguish the cases x ≤ z (head x) and
¬ x ≤ z (head z).
The main theorem is proved by induction on the proof of Sorted xs. In the
nil and single cases, the result is computed directly. In the
two_or_more case, if x ≤ y, the result is x :: y :: z :: zs, which is
sorted; otherwise, it is y :: ins x (z :: zs), and we apply the auxiliary
lemma with the induction hypothesis.
theorem ins_sorted (x : ℕ) :
∀ xs, Sorted xs → Sorted (ins x xs) := x:ℕ⊢ ∀ (xs : List ℕ), Sorted xs → Sorted (ins x xs)
intro xs x:ℕxs:List ℕhxs:Sorted xs⊢ Sorted (ins x xs)
induction hxs with
x:ℕxs:List ℕ⊢ Sorted (ins x []) All goals completed! 🐙
x:ℕxs:List ℕy:ℕ⊢ Sorted (ins x [y])
x:ℕxs:List ℕy:ℕh:x ≤ y⊢ Sorted (ins x [y])x:ℕxs:List ℕy:ℕh:¬x ≤ y⊢ Sorted (ins x [y])
x:ℕxs:List ℕy:ℕh:x ≤ y⊢ Sorted (ins x [y]) x:ℕxs:List ℕy:ℕh:x ≤ y⊢ Sorted [x, y]
All goals completed! 🐙
x:ℕxs:List ℕy:ℕh:¬x ≤ y⊢ Sorted (ins x [y]) x:ℕxs:List ℕy:ℕh:¬x ≤ y⊢ Sorted (y :: ins x [])
exact Sorted.two_or_more y x (x:ℕxs:List ℕy:ℕh:¬x ≤ y⊢ y ≤ x All goals completed! 🐙)
(Sorted.single x)
x:ℕxs:List ℕy:ℕz:ℕzs:List ℕhyz:y ≤ zhsorted:Sorted (z :: zs)ih:Sorted (ins x (z :: zs))⊢ Sorted (ins x (y :: z :: zs))
x:ℕxs:List ℕy:ℕz:ℕzs:List ℕhyz:y ≤ zhsorted:Sorted (z :: zs)ih:Sorted (ins x (z :: zs))hxy:x ≤ y⊢ Sorted (ins x (y :: z :: zs))x:ℕxs:List ℕy:ℕz:ℕzs:List ℕhyz:y ≤ zhsorted:Sorted (z :: zs)ih:Sorted (ins x (z :: zs))hxy:¬x ≤ y⊢ Sorted (ins x (y :: z :: zs))
x:ℕxs:List ℕy:ℕz:ℕzs:List ℕhyz:y ≤ zhsorted:Sorted (z :: zs)ih:Sorted (ins x (z :: zs))hxy:x ≤ y⊢ Sorted (ins x (y :: z :: zs)) x:ℕxs:List ℕy:ℕz:ℕzs:List ℕhyz:y ≤ zhsorted:Sorted (z :: zs)ih:Sorted (ins x (z :: zs))hxy:x ≤ y⊢ Sorted (x :: y :: z :: zs)
All goals completed! 🐙
x:ℕxs:List ℕy:ℕz:ℕzs:List ℕhyz:y ≤ zhsorted:Sorted (z :: zs)ih:Sorted (ins x (z :: zs))hxy:¬x ≤ y⊢ Sorted (ins x (y :: z :: zs)) x:ℕxs:List ℕy:ℕz:ℕzs:List ℕhyz:y ≤ zhsorted:Sorted (z :: zs)ih:Sorted (ins x (z :: zs))hxy:¬x ≤ y⊢ Sorted (y :: ins x (z :: zs))
x:ℕxs:List ℕy:ℕz:ℕzs:List ℕhyz:y ≤ zhsorted:Sorted (z :: zs)ih:Sorted (ins x (z :: zs))hxy:¬x ≤ y⊢ y ≤ xx:ℕxs:List ℕy:ℕz:ℕzs:List ℕhyz:y ≤ zhsorted:Sorted (z :: zs)ih:Sorted (ins x (z :: zs))hxy:¬x ≤ y⊢ Sorted (y :: z :: zs)x:ℕxs:List ℕy:ℕz:ℕzs:List ℕhyz:y ≤ zhsorted:Sorted (z :: zs)ih:Sorted (ins x (z :: zs))hxy:¬x ≤ y⊢ Sorted (ins x (z :: zs))
x:ℕxs:List ℕy:ℕz:ℕzs:List ℕhyz:y ≤ zhsorted:Sorted (z :: zs)ih:Sorted (ins x (z :: zs))hxy:¬x ≤ y⊢ y ≤ x All goals completed! 🐙
x:ℕxs:List ℕy:ℕz:ℕzs:List ℕhyz:y ≤ zhsorted:Sorted (z :: zs)ih:Sorted (ins x (z :: zs))hxy:¬x ≤ y⊢ Sorted (y :: z :: zs) All goals completed! 🐙
x:ℕxs:List ℕy:ℕz:ℕzs:List ℕhyz:y ≤ zhsorted:Sorted (z :: zs)ih:Sorted (ins x (z :: zs))hxy:¬x ≤ y⊢ Sorted (ins x (z :: zs)) All goals completed! 🐙
2.7.3.5. ins produces a permutation
Now we show that x :: xs ~ ins x xs, by induction on xs. If x ≤ y, the
two lists are equal. Otherwise, we chain two permutations:
x :: y :: ys \;\sim\; y :: x :: ys \;\sim\; y :: \mathsf{ins}\ x\ ys
the first by the swap rule and the second by skip applied to the induction
hypothesis.
theorem ins_perm (x : ℕ) :
∀ xs, (x :: xs) ~ (ins x xs) := x:ℕ⊢ ∀ (xs : List ℕ), x :: xs ~ ins x xs
x:ℕxs:List ℕ⊢ x :: xs ~ ins x xs
induction xs with
x:ℕ⊢ [x] ~ ins x [] All goals completed! 🐙
x:ℕy:ℕys:List ℕih:x :: ys ~ ins x ys⊢ x :: y :: ys ~ ins x (y :: ys)
x:ℕy:ℕys:List ℕih:x :: ys ~ ins x ysh:x ≤ y⊢ x :: y :: ys ~ ins x (y :: ys)x:ℕy:ℕys:List ℕih:x :: ys ~ ins x ysh:¬x ≤ y⊢ x :: y :: ys ~ ins x (y :: ys)
x:ℕy:ℕys:List ℕih:x :: ys ~ ins x ysh:x ≤ y⊢ x :: y :: ys ~ ins x (y :: ys) x:ℕy:ℕys:List ℕih:x :: ys ~ ins x ysh:x ≤ y⊢ x :: y :: ys ~ x :: y :: ys
All goals completed! 🐙
x:ℕy:ℕys:List ℕih:x :: ys ~ ins x ysh:¬x ≤ y⊢ x :: y :: ys ~ ins x (y :: ys) x:ℕy:ℕys:List ℕih:x :: ys ~ ins x ysh:¬x ≤ y⊢ x :: y :: ys ~ y :: ins x ys
All goals completed! 🐙
2.7.3.6. Correctness of isort
With the two lemmas about ins, the correctness of isort follows by simple
induction on the input list. Sortedness is immediate. For the permutation, we
use the chain
x :: xs \;\sim\; x :: \mathsf{isort}\ xs \;\sim\; \mathsf{ins}\ x\ (\mathsf{isort}\ xs)
in which the first step comes from the induction hypothesis (with skip) and
the second from ins_perm.
theorem isort_sorted : ∀ xs, Sorted (isort xs) := ⊢ ∀ (xs : List ℕ), Sorted (isort xs)
xs:List ℕ⊢ Sorted (isort xs)
induction xs with
⊢ Sorted (isort []) All goals completed! 🐙
x:ℕxs:List ℕih:Sorted (isort xs)⊢ Sorted (isort (x :: xs)) All goals completed! 🐙
theorem isort_perm : ∀ xs, xs ~ isort xs := ⊢ ∀ (xs : List ℕ), xs ~ isort xs
xs:List ℕ⊢ xs ~ isort xs
induction xs with
⊢ [] ~ isort [] All goals completed! 🐙
x:ℕxs:List ℕih:xs ~ isort xs⊢ x :: xs ~ isort (x :: xs)
All goals completed! 🐙
Note the division of labor: the tests quickly gave us confidence that the specification and the implementation were correct; the proofs gave us the definitive guarantee. In practice, testing before proving avoids spending hours trying to prove a false statement because of some overlooked detail.
end Ch14
2.7.4. Exercises
-
Define a class
Semigroup(an associative operation, without a neutral element) and makeMyMonoidextend it usingextends. Declare instances forNatwith multiplication and forBoolwith conjunction. -
Prove, for an arbitrary monoid, that if
op a b = neutralandop b c = neutral, thena = c. -
Write
ShrinkableandArbitraryinstances for the typeColorand use Plausible to test that the derived equality==is symmetric. -
Use Plausible to test the (false) claim that
isort (xs ++ ys) = isort xs ++ isort ys. Which counterexample is found? -
Prove that
Permpreserves length:theorem Perm_length {α : Type} (xs ys : List α) : xs ~ ys → xs.length = ys.length -
Prove that
isortis idempotent on sorted lists:theorem isort_of_sorted (xs : List ℕ) : Sorted xs → isort xs = xs -
Prove the correctness of
isSortedwith respect toSorted:isSorted xs = true ↔ Sorted xs.