πŸ“₯ Download raw
open import Padova2025.ProgrammingBasics.Lists
open import Padova2025.ProvingBasics.Connectives.Disjunction

module Padova2025.VerifiedAlgorithms.InsertionSort.PostHoc
  (A : Set) (_≀_ : A β†’ A β†’ Set) (cmp? : (x y : A) β†’ x ≀ y ⊎ y ≀ x) where

Post-hoc verification

open import Padova2025.VerifiedAlgorithms.InsertionSort.Implementation A _≀_ cmp?

Output lists are ordered

As a first step, let us prove that the lists produced by the sort function are always ascendingly ordered. To express such an assertion, we need to introduce a type IsOrdered xs of witnesses that a given list xs is ordered.

data IsOrdered : List A β†’ Set where
  empty     : IsOrdered []
  singleton : {x : A} β†’ IsOrdered (x ∷ [])
  cons      : {x y : A} {ys : List A} β†’ x ≀ y β†’ IsOrdered (y ∷ ys) β†’ IsOrdered (x ∷ (y ∷ ys))
lemmaβ‚€ : (x y : A) (ys : List A) β†’ y ≀ x β†’ IsOrdered (y ∷ ys) β†’ IsOrdered (y ∷ insert x ys)
lemmaβ‚€ = {!!}
lemma : (x : A) (ys : List A) β†’ IsOrdered ys β†’ IsOrdered (insert x ys)
lemma = {!!}
theorem : (xs : List A) β†’ IsOrdered (sort xs)
theorem = {!!}

Output lists are permutations of the input lists

It is nice that a full proof of theorem : (xs : List A) β†’ IsOrdered (sort xs), developed above, is just one screenful of code. However, this theorem does not yet express all aspects of the sorting function working correctly:

cheatsort : List A β†’ List A
cheatsort xs = []
cheattheorem : (xs : List A) β†’ IsOrdered (cheatsort xs)
cheattheorem xs = empty

We need to verify that sort xs is a permutation of the input list xs. To express such an assertion, we first set up a type x β—‚ ys ↝ xys of witnesses that inserting x into ys somewhere yields the list xys.

data _β—‚_↝_ : A β†’ List A β†’ List A β†’ Set where
  here  : {x : A} {xs : List A} β†’ x β—‚ xs ↝ (x ∷ xs)
  there : {x y : A} {ys xys : List A} β†’ x β—‚ ys ↝ xys β†’ x β—‚ (y ∷ ys) ↝ (y ∷ xys)

We then set up a type xs β‰ˆ ys of witnesses that the two lists xs and ys are permutations of each other, that is, contain exactly the same elements just perhaps in different order.

infix 4 _β‰ˆ_
data _β‰ˆ_ : List A β†’ List A β†’ Set where
  empty : [] β‰ˆ []
  cons  : {x : A} {xs ys xys : List A} β†’ (x β—‚ ys ↝ xys) β†’ xs β‰ˆ ys β†’ (x ∷ xs) β‰ˆ xys

Here is an example for such a permutation witness:

example : (x y z : A) β†’ (x ∷ y ∷ z ∷ []) β‰ˆ (z ∷ x ∷ y ∷ [])
example = {!!}

We can then state and prove the fundamental lemma about the inserting behavior of insert.

lemma' : (x : A) (ys : List A) β†’ x β—‚ ys ↝ insert x ys
lemma' = {!!}

The desired result about the sort function is then a quick corollary.

theorem' : (xs : List A) β†’ xs β‰ˆ sort xs
theorem' = {!!}