lean4-htt/tests/lean/run/mergeSortCPDT.lean
Kim Morrison 4aa74d9c0b
feat: List.mergeSort (#5092)
Defines `mergeSort`, a naive stable merge sort algorithm, replaces it
via a `@[csimp]` lemma with something faster at runtime, and proves the
following results:

* `mergeSort_sorted`: `mergeSort` produces a sorted list.
* `mergeSort_perm`: `mergeSort` is a permutation of the input list.
* `mergeSort_of_sorted`: `mergeSort` does not change a sorted list.
* `mergeSort_cons`: proves `mergeSort le (x :: xs) = l₁ ++ x :: l₂` for
some `l₁, l₂`
so that `mergeSort le xs = l₁ ++ l₂`, and no `a ∈ l₁` satisfies `le a
x`.
* `mergeSort_stable`: if `c` is a sorted sublist of `l`, then `c` is
still a sublist of `mergeSort le l`.
2024-08-20 06:32:52 +00:00

50 lines
1.7 KiB
Text
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

def List.insert' (p : αα → Bool) (a : α) (bs : List α) : List α :=
match bs with
| [] => [a]
| b :: bs' => if p a b then a :: bs else b :: bs'.insert' p a
def List.merge' (p : αα → Bool) (as bs : List α) : List α :=
match as with
| [] => bs
| a :: as' => insert' p a (merge p as' bs)
def List.split (as : List α) : List α × List α :=
match as with
| [] => ([], [])
| [a] => ([a], [])
| a :: b :: as =>
let (as, bs) := split as
(a :: as, b :: bs)
@[simp] def List.atLeast2 (as : List α) : Bool :=
match as with
| [] => false
| [_] => false
| _::_::_ => true
theorem List.length_split_of_atLeast2 {as : List α} (h : as.atLeast2) : as.split.1.length < as.length ∧ as.split.2.length < as.length := by
match as with
| [] => simp at h
| [_] => simp at h
| [_, _] => simp (config := { decide := true }) [split]
| [_, _, _] => simp (config := { decide := true }) [split]
| a::b::c::d::as =>
-- TODO: simplify using linear arith and more automation
have : (c::d::as).atLeast2 := by simp_arith
have ih := length_split_of_atLeast2 this
simp_arith [split] at ih |-
have ⟨ih₁, ih₂⟩ := ih
exact ⟨Nat.le_trans ih₁ (by simp_arith), Nat.le_trans ih₂ (by simp_arith)⟩
def List.mergeSort' (p : αα → Bool) (as : List α) : List α :=
if h : as.atLeast2 then
match he:as.split with
| (as', bs') =>
-- TODO: simplify using more automation
have ⟨h₁, h₂⟩ := length_split_of_atLeast2 h
have : as'.length < as.length := by simp [he] at h₁; assumption
have : bs'.length < as.length := by simp [he] at h₂; assumption
merge' p (mergeSort' p as') (mergeSort' p bs')
else
as
termination_by as.length