Documentation

CslibFrontier.Foundations.Data.List.Sort

Insertion, erasure, and rank in sorted lists #

In a list l sorted by (· ≤ ·) over a linear order, the rank l.countP (· < a) of a gives the exact split position at which List.orderedInsert (· ≤ ·) a l inserts a and at which l.erase a removes a when a ∈ l, and characterizes the indices i whose entry satisfies l[i] < a.

List.insertSortedUnique inserts into a strictly increasing list, skipping an equal entry.

Main results #

def List.insertSortedUnique {α : Type u_1} [LinearOrder α] (x : α) :
List α → List α

Insert x before the first larger entry, or keep the list if the first entry at least x equals x. On a strictly increasing list, this inserts without repetition.

theorem List.mem_insertSortedUnique {α : Type u_1} [LinearOrder α] (x z : α) (l : List α) :

The result contains the inserted element and every original entry.

theorem List.length_insertSortedUnique_le {α : Type u_1} [LinearOrder α] (x : α) (l : List α) :

This insertion adds at most one list entry.

theorem List.Pairwise.insertSortedUnique {α : Type u_1} [LinearOrder α] {l : List α} (hl : Pairwise (fun (x1 x2 : α) => x1 < x2) l) (x : α) :
Pairwise (fun (x1 x2 : α) => x1 < x2) (List.insertSortedUnique x l)

Inserting without repetition into a strictly increasing list preserves strict order.

theorem List.Pairwise.orderedInsert_eq_take_append_drop {α : Type u_1} [LinearOrder α] {l : List α} (hl : Pairwise (fun (x1 x2 : α) => x1 ≤ x2) l) (a : α) :
List.orderedInsert (fun (x1 x2 : α) => x1 ≤ x2) a l = List.take (countP (fun (x : α) => decide (x < a)) l) l ++ a :: List.drop (countP (fun (x : α) => decide (x < a)) l) l

In a list sorted by (· ≤ ·), orderedInsert (· ≤ ·) a l inserts a immediately after the prefix of length l.countP (· < a) consisting of elements strictly smaller than a.

theorem List.Pairwise.erase_eq_take_append_drop {α : Type u_1} [LinearOrder α] {l : List α} (hl : Pairwise (fun (x1 x2 : α) => x1 ≤ x2) l) {a : α} (ha : a ∈ l) :
l.erase a = List.take (countP (fun (x : α) => decide (x < a)) l) l ++ List.drop (countP (fun (x : α) => decide (x < a)) l + 1) l

In a list sorted by (· ≤ ·), erasing a present element a ∈ l removes the entry at index k = l.countP (· < a) (the first occurrence of a), splitting l into l.take k ++ l.drop (k + 1).

theorem List.Pairwise.getElem_lt_iff_lt_countP {α : Type u_1} [LinearOrder α] {l : List α} (hl : Pairwise (fun (x1 x2 : α) => x1 ≤ x2) l) {i : ℕ} (hi : i < l.length) {a : α} :
l[i] < a ↔ i < countP (fun (x : α) => decide (x < a)) l

In a list sorted by (· ≤ ·), the i-th entry is strictly below a if and only if i lies below the rank l.countP (· < a) of a.