-
1
-
2
-
3
-
4
-
5
-
6
-
7
-
8
-
9
-
10
-
11
-
12
-
13
-
14
-
15
-
16
-
17
-
18
-
19
-
20
-
21
-
22
-
23
-
24
-
25
-
26
-
27
-
28
-
29
-
30
-
31
-
32
-
33
-
34
-
35
-
36
-
37
-
38
-
39
-
40
-
41
-
42
-
43
-
44
-
45
-
46
-
47
-
48
-
49
-
50
-
51
-
52
-
53
-
54
-
55
-
56
-
57
-
58
-
59
-- Simplified version of https://jamesoswald.dev/posts/lean4-insertion-sort/
-- Also inspired by https://gist.github.com/Kha/96d67c8b947b48f8786aea90857fbb5c
variable [LE α] [DecidableLE α]
/-- Inserts an element n into a sorted list. -/
@[grind]
def sInsert (n : α) : List α → List α
| [] => [n]
| h :: t =>
if n ≤ h then
n :: h :: t
else
h :: sInsert n t
/-- Insertion sort -/
@[grind]
def sort : List α → List α
| [] => []
| h :: t => sInsert h (sort t)
/-- Predicate for a list being sorted -/
@[grind]
def sorted : List α → Prop
-- An empty list is sorted
| [] => True
-- A list containing a single element is sorted
| [_] => True
-- A list with 2 or more elements is only sorted if all elements are ordered.
| h :: h' :: t => h ≤ h' ∧ sorted (h' :: t)
/- This also works:
inductive sorted : List α → Prop where
| nil : sorted []
| single x : sorted [x]
| cons_cons x x' xs : x ≤ x' → sorted (x' :: xs) → sorted (x :: x' :: xs)
-/
variable (l : List α)
/-- If a sorted list is passed to `sInsert`,
it will return a sorted list after inserting a new element. -/
theorem sInsert_sorted [Std.IsLinearOrder α] : sorted l → sorted (sInsert n l) := by
induction l with
| nil => grind
| cons _ t => cases t <;> grind
theorem sort_sorted [Std.IsLinearOrder α] : sorted (sort l) := by
induction l <;> grind [sInsert_sorted]
/-- A list l with n is a permutation of a list the list with n inserted into it.
We need `LawfulBEq` because grind uses it via `List.perm_iff_count`. -/
theorem sInsert_perm [BEq α] [LawfulBEq α] : (n :: l).Perm (sInsert n l) := by
induction l <;> grind
/-- `sort` returns a permutation of the input list. -/
theorem sort_perm [BEq α] [LawfulBEq α] : l.Perm (sort l) := by
induction l with
| nil => grind
| cons h t => grind [sInsert_perm (sort t) (n := h)]