source
stringlengths
17
118
lean4
stringlengths
0
335k
.lake/packages/batteries/Batteries/CodeAction/Match.lean
module public meta import Batteries.CodeAction.Misc public meta import Batteries.Data.List @[expose] public meta section namespace Batteries.CodeAction open Lean Meta Elab Server RequestM CodeAction /-- Filter for the info-nodes to find the match-nodes. -/ def isMatchTerm : Info → Bool | .ofTermInfo i => i.stx.isOfKind ``Lean.Parser.Term.match | _ => false /-- Returns the String.range that encompasses `match e (with)`. -/ def getMatchHeaderRange? (matchStx : Syntax) : Option String.Range := do match matchStx with | `(term| match $[(generalizing := $generalizingVal)]? $[(motive := $motiveVal)]? $[$discrs:matchDiscr],* with $_) => --Here the $alts would go, if they were already typed. Else $_ will match "missing" -- Isolate the syntax of only the "match" atom to get the starting position: let mStx ← matchStx.getArgs.find? (fun s => s.isAtom && s.getAtomVal == "match") let startPos ← mStx.getPos? -- begin of 'match' keyword -- Depending on the existence of 'with', return the correct range: if let some withStx := (matchStx.getArgs.find? (fun s => s.isAtom && s.getAtomVal == "with")) then return ⟨startPos, ←withStx.getTailPos?⟩ else let lastMatchDiscr ← discrs.back? return ⟨startPos, ←lastMatchDiscr.raw.getTailPos?⟩ | _ => none /-- Flattens an Infotree into an array of Info-nodes that fulfill p. -/ partial def findAllInfos (p : Info → Bool) (t : InfoTree) : Array Info := loop t #[] where /-- Inner loop for `findAllInfos`. -/ loop (t : InfoTree) (acc : Array Info) : Array Info := match t with | .context _ childTree => loop childTree acc | .node info children => let acc' := if p info then acc.push info else acc children.foldl (fun currentAcc child => loop child currentAcc) acc' | .hole _ => acc /-- From a constructor-name e.g. 'Option.some' construct the corresponding match pattern, e.g. '.some val'. We implement special cases for Nat and List, Option and Bool to e.g. produce 'n + 1' instead of 'Nat.succ n'. -/ def pattern_from_constructor (ctor : Name) (env : Environment) (suffix : String) : Option String := do let some (.ctorInfo ci) := env.find? ctor | panic! "bad inductive" let ctor_short := toString (ctor.updatePrefix .anonymous) let mut str := "" let explicit_args := getExplicitArgs ci.type #[] match ctor with | (.str (.str .anonymous "Nat") "zero") => "0" /- At the moment this evaluates to "n + 1": -/ | (.str (.str .anonymous "Nat") "succ") => s!"{explicit_args[0]!}{suffix} + 1" -- | (.str (.str .anonymous "List") "nil") => "[]" /- At the moment this evaluates to "head :: tail": -/ | (.str (.str .anonymous "List") "cons") => s!"{explicit_args[0]!}{suffix} :: {explicit_args[1]!}{suffix}" | (.str (.str .anonymous "Option") "some") => s!"some {explicit_args[0]!}{suffix}" | (.str (.str .anonymous "Option") "none") => "none" | (.str (.str .anonymous "Bool") "true") => "true" | (.str (.str .anonymous "Bool") "false") => "false" /- Default case: -/ | _ => str := str ++ s!".{ctor_short}" for arg in explicit_args do /- This takes the variable names `arg` which were used in the inductive type specification. When using this action with multiple (same-type) arguments these might clash, so we fix it by appending a suffix like `_2` - you will probably want to rename these suffixed names yourself. -/ str := str ++ if arg.hasNum || arg.isInternal then " _" else s!" {arg}{suffix}" return str /-- Invoking tactic code action "Generate a list of alternatives for this match." in the following: ```lean def myfun2 (n : Nat) : Nat := match n ``` produces: ```lean def myfun2 (n : Nat) : Nat := match n with | 0 => _ | n + 1 => _ ``` Also has support for multiple discriminants, e.g. ``` def myfun3 (o : Option Bool) (m : Nat) : Nat := match o, m with ``` can be expanded into ``` def myfun3 (o : Option Bool) (m : Nat) : Nat := match o, m with | none, 0 => _ | none, n_2 + 1 => _ | some val_1, 0 => _ | some val_1, n_2 + 1 => _ ``` -/ @[command_code_action] def matchExpand : CommandCodeAction := fun CodeActionParams snap ctx node => do /- Since `match` is a term (not a command) `@[command_code_action Parser.Term.match]` will not fire. So we filter `command_code_action` ourselves in Step 1 for now. -/ /- 1. Find ALL ofTermInfo Info nodes that are of kind `Term.match` -/ let allMatchInfos := findAllInfos isMatchTerm node /- 2. Filter these candidates within the `RequestM` monad based on the cursor being in the header lines of these matches. -/ let doc ← readDoc let relevantMatchInfos ← allMatchInfos.filterM fun matchInfo => do let some headerRangeRaw := getMatchHeaderRange? matchInfo.stx | return false let headerRangeLsp := doc.meta.text.utf8RangeToLspRange headerRangeRaw let cursorRangeLsp := CodeActionParams.range -- check if the cursor range is contained in the header range return (cursorRangeLsp.start ≥ headerRangeLsp.start && cursorRangeLsp.end ≤ headerRangeLsp.end) /- 3. Pick the first (and mostly only) candidate. There might sometimes be more, since some things are just contained multiple times in 'node'. -/ let some matchInfo := relevantMatchInfos[0]? | return #[] let some headerRangeRaw := getMatchHeaderRange? matchInfo.stx | return #[] /- Isolate the array of match-discriminants -/ let discrs ← match matchInfo.stx with | `(term| match $[(generalizing := $generalizingVal)]? $[(motive := $motiveVal)]? $[$discrs:matchDiscr],* with $_) => pure discrs | _ => return #[] /- Reduce discrs to the array of match-discriminants-terms (i.e. "[n1, n2]" in "match n2,n2"). -/ let some discrTerms := discrs.mapM (fun discr => match discr with | `(matchDiscr| $t: term) => some t | `(matchDiscr| $_:ident : $t: term) => some t | _ => none ) | return #[] -- Get a Bool, that tells us if "with" is already typed in: let withPresent := (matchInfo.stx.getArgs.find? (fun s => s.isAtom && s.getAtomVal == "with")).isSome /- Construct a list containing for each discriminant its list of constructor names. The list contains the first discriminant constructors last, since we are prepending in the loop.-/ let mut constructors_rev : List (List Name) := [] for discrTerm in discrTerms do let some (info : TermInfo) := findTermInfo? node discrTerm | return #[] let ty ← info.runMetaM ctx (Lean.Meta.inferType info.expr) let .const name _ := (← info.runMetaM ctx (whnf ty)).getAppFn | return #[] -- Find the inductive constructors of e: let some (.inductInfo val) := snap.env.find? name | return #[] constructors_rev := val.ctors :: constructors_rev let eager : Lsp.CodeAction := { title := "Generate a list of equations for this match." kind? := "quickfix" } return #[{ --rest is lightly adapted from eqnStub: eager lazy? := some do let holePos := headerRangeRaw.stop --where we start inserting let (indent, _) := findIndentAndIsStart doc.meta.text.source headerRangeRaw.start let mut str := if withPresent then "" else " with" let indent := "\n".pushn ' ' (indent) --use the same indent as the 'match' line. let constructor_combinations := constructors_rev.sections.map List.reverse for l in constructor_combinations do str := str ++ indent ++ "| " for ctor_idx in [:l.length] do let ctor := l[ctor_idx]! let suffix := if constructors_rev.length ≥ 2 then s!"_{ctor_idx + 1}" else "" let some pat := pattern_from_constructor ctor snap.env suffix | panic! "bad inductive" str := str ++ pat if ctor_idx < l.length - 1 then str := str ++ ", " str := str ++ s!" => _" pure { eager with edit? := some <|.ofTextEdit doc.versionedIdentifier { range := doc.meta.text.utf8RangeToLspRange ⟨holePos, holePos⟩-- adapted to insert-only newText := str } } }]
.lake/packages/batteries/Batteries/Data/String.lean
module public import Batteries.Data.String.AsciiCasing public import Batteries.Data.String.Basic public import Batteries.Data.String.Lemmas public import Batteries.Data.String.Matcher
.lake/packages/batteries/Batteries/Data/RBMap.lean
module public import Batteries.Data.RBMap.Alter public import Batteries.Data.RBMap.Basic public import Batteries.Data.RBMap.Depth public import Batteries.Data.RBMap.Lemmas public import Batteries.Data.RBMap.WF
.lake/packages/batteries/Batteries/Data/Fin.lean
module public import Batteries.Data.Fin.Basic public import Batteries.Data.Fin.Fold public import Batteries.Data.Fin.Lemmas public import Batteries.Data.Fin.OfBits
.lake/packages/batteries/Batteries/Data/Int.lean
module public import Batteries.Data.Nat.Lemmas @[expose] public section namespace Int /-- `testBit m n` returns whether the `(n+1)` least significant bit is `1` or `0`, using the two's complement convention for negative `m`. -/ def testBit : Int → Nat → Bool | ofNat m, n => Nat.testBit m n | negSucc m, n => !(Nat.testBit m n) /-- Construct an integer from a sequence of bits using little endian convention. The sign is determined using the two's complement convention: the result is negative if and only if `n > 0` and `f (n-1) = true`. -/ def ofBits (f : Fin n → Bool) := if 2 * Nat.ofBits f < 2 ^ n then ofNat (Nat.ofBits f) else subNatNat (Nat.ofBits f) (2 ^ n) @[simp] theorem ofBits_zero (f : Fin 0 → Bool) : ofBits f = 0 := by simp [ofBits] @[simp] theorem testBit_ofBits_lt {f : Fin n → Bool} (h : i < n) : (ofBits f).testBit i = f ⟨i, h⟩ := by simp only [ofBits] split · simp only [testBit, Nat.testBit_ofBits_lt, h] · have hlt := Nat.ofBits_lt_two_pow f simp [subNatNat_of_lt hlt, testBit, Nat.sub_sub, Nat.testBit_two_pow_sub_succ hlt, h] @[simp] theorem testBit_ofBits_ge {f : Fin n → Bool} (h : i ≥ n) : (ofBits f).testBit i = decide (ofBits f < 0) := by simp only [ofBits] split · have hge : ¬ ofNat (Nat.ofBits f) < 0 := by rw [Int.not_lt]; exact natCast_nonneg .. simp only [testBit, Nat.testBit_ofBits_ge _ _ h, hge, decide_false] · have hlt := Nat.ofBits_lt_two_pow f have h : 2 ^ n - Nat.ofBits f - 1 < 2 ^ i := Nat.lt_of_lt_of_le (by omega) (Nat.pow_le_pow_right Nat.zero_lt_two h) simp [testBit, subNatNat_of_lt hlt, Nat.testBit_lt_two_pow h, negSucc_lt_zero] theorem testBit_ofBits (f : Fin n → Bool) : (ofBits f).testBit i = if h : i < n then f ⟨i, h⟩ else decide (ofBits f < 0) := by split <;> simp_all -- Forward port of lean4#10739 instance {n : Int} : NeZero (n^0) := ⟨Int.one_ne_zero⟩
.lake/packages/batteries/Batteries/Data/Rat.lean
module public import Batteries.Data.Rat.Float
.lake/packages/batteries/Batteries/Data/FloatArray.lean
module @[expose] public section namespace FloatArray attribute [ext] FloatArray /-- Unsafe optimized implementation of `mapM`. This function is unsafe because it relies on the implementation limit that the size of an array is always less than `USize.size`. -/ @[inline] unsafe def mapMUnsafe [Monad m] (a : FloatArray) (f : Float → m Float) : m FloatArray := loop a 0 a.usize where /-- Inner loop for `mapMUnsafe`. -/ @[specialize] loop (a : FloatArray) (k s : USize) := do if k < s then let x := a.uget k lcProof let y ← f x let a := a.uset k y lcProof loop a (k+1) s else pure a /-- `mapM f a` applies the monadic function `f` to each element of the array. -/ @[implemented_by mapMUnsafe] def mapM [Monad m] (a : FloatArray) (f : Float → m Float) : m FloatArray := do let mut r := a for i in [0:r.size] do r := r.set! i (← f r[i]!) return r /-- `map f a` applies the function `f` to each element of the array. -/ @[inline] def map (a : FloatArray) (f : Float → Float) : FloatArray := mapM (m:=Id) a f
.lake/packages/batteries/Batteries/Data/List.lean
module public import Batteries.Data.List.ArrayMap public import Batteries.Data.List.Basic public import Batteries.Data.List.Count public import Batteries.Data.List.Init.Lemmas public import Batteries.Data.List.Lemmas public import Batteries.Data.List.Matcher public import Batteries.Data.List.Monadic public import Batteries.Data.List.Pairwise public import Batteries.Data.List.Perm public import Batteries.Data.List.Scan
.lake/packages/batteries/Batteries/Data/HashMap.lean
module public import Batteries.Data.HashMap.Basic
.lake/packages/batteries/Batteries/Data/Nat.lean
module public import Batteries.Data.Nat.Basic public import Batteries.Data.Nat.Bisect public import Batteries.Data.Nat.Bitwise public import Batteries.Data.Nat.Digits public import Batteries.Data.Nat.Gcd public import Batteries.Data.Nat.Lemmas
.lake/packages/batteries/Batteries/Data/BitVec.lean
module public import Batteries.Data.BitVec.Basic public import Batteries.Data.BitVec.Lemmas
.lake/packages/batteries/Batteries/Data/DList.lean
module public import Batteries.Data.DList.Basic public import Batteries.Data.DList.Lemmas
.lake/packages/batteries/Batteries/Data/MLList.lean
module public import Batteries.Data.MLList.Basic public import Batteries.Data.MLList.Heartbeats public import Batteries.Data.MLList.IO
.lake/packages/batteries/Batteries/Data/UnionFind.lean
module public import Batteries.Data.UnionFind.Basic public import Batteries.Data.UnionFind.Lemmas
.lake/packages/batteries/Batteries/Data/Vector.lean
module public import Batteries.Data.Vector.Basic public import Batteries.Data.Vector.Lemmas public import Batteries.Data.Vector.Monadic
.lake/packages/batteries/Batteries/Data/NameSet.lean
module public import Lean.Data.NameMap.Basic @[expose] public section namespace Lean.NameSet instance : Singleton Name NameSet where singleton := fun n => (∅ : NameSet).insert n instance : Union NameSet where union := fun s t => s.foldl (fun t n => t.insert n) t instance : Inter NameSet where inter := fun s t => s.foldl (fun r n => if t.contains n then r.insert n else r) {} instance : SDiff NameSet where sdiff := fun s t => t.foldl (fun s n => s.erase n) s end Lean.NameSet
.lake/packages/batteries/Batteries/Data/ByteSlice.lean
module public import Std.Data.ByteSlice import all Std.Data.ByteSlice -- for unfolding `ByteSlice.size` @[expose] public section namespace ByteSlice /-- Test whether a byte slice is empty. -/ protected abbrev isEmpty (s : ByteSlice) := s.start == s.stop theorem stop_eq_start_add_size (s : ByteSlice) : s.stop = s.start + s.size := by rw [ByteSlice.size, Nat.add_sub_cancel' s.start_le_stop] /-- Returns the subslice obtained by removing the last element. -/ abbrev pop (s : ByteSlice) : ByteSlice := s.slice 0 (s.size - 1) /-- Returns the subslice obtained by removing the first element. -/ abbrev popFront (s : ByteSlice) : ByteSlice := s.slice 1 s.size /-- Folds a monadic function over a `ByteSubarray` from left to right. -/ @[inline] def foldlM [Monad m] (s : ByteSlice) (f : β → UInt8 → m β) (init : β) : m β := s.toByteArray.foldlM f init s.start s.stop /-- Folds a function over a `ByteSubarray` from left to right. -/ @[inline] def foldl (s : ByteSlice) (f : β → UInt8 → β) (init : β) : β := s.foldlM (m:=Id) f init /-- Implementation of `forIn` for a `ByteSlice`. -/ @[specialize] protected def forIn [Monad m] (s : ByteSlice) (init : β) (f : UInt8 → β → m (ForInStep β)) : m β := loop s.size (Nat.le_refl _) init where /-- Inner loop of the `forIn` implementation for `ByteSlice`. -/ loop (i : Nat) (h : i ≤ s.size) (b : β) : m β := do match i, h with | 0, _ => pure b | i+1, h => match (← f s[s.size - 1 - i] b) with | ForInStep.done b => pure b | ForInStep.yield b => loop i (Nat.le_of_succ_le h) b instance : ForIn m ByteSlice UInt8 where forIn := ByteSlice.forIn instance : Std.Stream ByteSlice UInt8 where next? s := s[0]? >>= (·, s.popFront) instance : Coe ByteArray ByteSlice where coe := ByteArray.toByteSlice end ByteSlice namespace Batteries /-- A subarray of a `ByteArray`. -/ @[deprecated ByteSlice (since := "2025-10-04")] structure ByteSubarray where /-- `O(1)`. Get data array of a `ByteSubarray`. -/ array : ByteArray /-- `O(1)`. Get start index of a `ByteSubarray`. -/ start : Nat /-- `O(1)`. Get stop index of a `ByteSubarray`. -/ stop : Nat /-- Start index is before stop index. -/ start_le_stop : start ≤ stop /-- Stop index is before end of data array. -/ stop_le_array_size : stop ≤ array.size namespace ByteSubarray set_option linter.deprecated false attribute [deprecated ByteSlice.byteArray (since := "2025-10-04")] ByteSubarray.array attribute [deprecated ByteSlice.start (since := "2025-10-04")] ByteSubarray.start attribute [deprecated ByteSlice.stop (since := "2025-10-04")] ByteSubarray.stop attribute [deprecated ByteSlice.start_le_stop (since := "2025-10-04")] ByteSubarray.start_le_stop attribute [deprecated ByteSlice.stop_le_size_byteArray (since := "2025-10-04")] ByteSubarray.stop_le_array_size /-- `O(1)`. Get the size of a `ByteSubarray`. -/ @[deprecated ByteSlice.size (since := "2025-10-04")] protected def size (self : ByteSubarray) := self.stop - self.start /-- `O(1)`. Test if a `ByteSubarray` is empty. -/ @[deprecated ByteSlice.isEmpty (since := "2025-10-04")] protected def isEmpty (self : ByteSubarray) := self.start == self.stop @[deprecated ByteSlice.stop_eq_start_add_size (since := "2025-10-04")] theorem stop_eq_start_add_size (self : ByteSubarray) : self.stop = self.start + self.size := by rw [ByteSubarray.size, Nat.add_sub_cancel' self.start_le_stop] /-- `O(n)`. Extract a `ByteSubarray` to a `ByteArray`. -/ @[deprecated ByteSlice.toByteArray (since := "2025-10-04")] def toByteArray (self : ByteSubarray) : ByteArray := self.array.extract self.start self.stop /-- `O(1)`. Get the element at index `i` from the start of a `ByteSubarray`. -/ @[deprecated ByteSlice.get (since := "2025-10-04"), inline] def get (self : ByteSubarray) (i : Fin self.size) : UInt8 := have : self.start + i.1 < self.array.size := by apply Nat.lt_of_lt_of_le _ self.stop_le_array_size rw [stop_eq_start_add_size] apply Nat.add_lt_add_left i.is_lt self.start self.array[self.start + i.1] instance : GetElem ByteSubarray Nat UInt8 fun self i => i < self.size where getElem self i h := self.get ⟨i, h⟩ /-- `O(1)`. Pop the last element of a `ByteSubarray`. -/ @[deprecated ByteSlice.pop (since := "2025-10-04"), inline] def pop (self : ByteSubarray) : ByteSubarray := if h : self.start = self.stop then self else {self with stop := self.stop - 1 start_le_stop := Nat.le_pred_of_lt (Nat.lt_of_le_of_ne self.start_le_stop h) stop_le_array_size := Nat.le_trans (Nat.pred_le _) self.stop_le_array_size } /-- `O(1)`. Pop the first element of a `ByteSubarray`. -/ @[deprecated ByteSlice.popFront (since := "2025-10-04"), inline] def popFront (self : ByteSubarray) : ByteSubarray := if h : self.start = self.stop then self else {self with start := self.start + 1 start_le_stop := Nat.succ_le_of_lt (Nat.lt_of_le_of_ne self.start_le_stop h) } /-- Folds a monadic function over a `ByteSubarray` from left to right. -/ @[deprecated ByteSlice.foldlM (since := "2025-10-04"), inline] def foldlM [Monad m] (self : ByteSubarray) (f : β → UInt8 → m β) (init : β) : m β := self.array.foldlM f init self.start self.stop /-- Folds a function over a `ByteSubarray` from left to right. -/ @[deprecated ByteSlice.foldl (since := "2025-10-04"), inline] def foldl (self : ByteSubarray) (f : β → UInt8 → β) (init : β) : β := self.foldlM (m:=Id) f init /-- Implementation of `forIn` for a `ByteSubarray`. -/ @[specialize] --@[deprecated ByteSlice.forIn (since := "2025-10-04"), specialize] protected def forIn [Monad m] (self : ByteSubarray) (init : β) (f : UInt8 → β → m (ForInStep β)) : m β := loop self.size (Nat.le_refl _) init where /-- Inner loop of the `forIn` implementation for `ByteSubarray`. -/ loop (i : Nat) (h : i ≤ self.size) (b : β) : m β := do match i, h with | 0, _ => pure b | i+1, h => match (← f self[self.size - 1 - i] b) with | ForInStep.done b => pure b | ForInStep.yield b => loop i (Nat.le_of_succ_le h) b instance : ForIn m ByteSubarray UInt8 where forIn := ByteSubarray.forIn instance : Std.Stream ByteSubarray UInt8 where next? s := s[0]? >>= fun x => (x, s.popFront) end Batteries.ByteSubarray set_option linter.deprecated false in /-- `O(1)`. Coerce a byte array into a byte slice. -/ @[deprecated ByteArray.toByteSlice (since := "2025-10-04")] def ByteArray.toByteSubarray (array : ByteArray) : Batteries.ByteSubarray where array := array start := 0 stop := array.size start_le_stop := Nat.zero_le _ stop_le_array_size := Nat.le_refl _ set_option linter.deprecated false in instance : Coe ByteArray Batteries.ByteSubarray where coe := ByteArray.toByteSubarray
.lake/packages/batteries/Batteries/Data/ByteArray.lean
module @[expose] public section namespace ByteArray attribute [ext] ByteArray instance : DecidableEq ByteArray := fun _ _ => decidable_of_decidable_of_iff ByteArray.ext_iff.symm theorem getElem_eq_data_getElem (a : ByteArray) (h : i < a.size) : a[i] = a.data[i] := rfl /-! ### uget/uset -/ @[simp] theorem uset_eq_set (a : ByteArray) {i : USize} (h : i.toNat < a.size) (v : UInt8) : a.uset i v h = a.set i.toNat v := rfl /-! ### empty -/ @[simp] theorem data_mkEmpty (cap) : (emptyWithCapacity cap).data = #[] := rfl /-! ### push -/ @[simp] theorem size_push (a : ByteArray) (b : UInt8) : (a.push b).size = a.size + 1 := Array.size_push .. @[simp] theorem get_push_eq (a : ByteArray) (x : UInt8) : (a.push x)[a.size] = x := Array.getElem_push_eq .. theorem get_push_lt (a : ByteArray) (x : UInt8) (i : Nat) (h : i < a.size) : (a.push x)[i]'(size_push .. ▸ Nat.lt_succ_of_lt h) = a[i] := Array.getElem_push_lt .. /-! ### set -/ @[simp] theorem size_set (a : ByteArray) (i : Fin a.size) (v : UInt8) : (a.set i v).size = a.size := Array.size_set .. @[simp] theorem get_set_eq (a : ByteArray) (i : Fin a.size) (v : UInt8) : (a.set i v)[i.val] = v := Array.getElem_set_self _ theorem get_set_ne (a : ByteArray) (i : Fin a.size) (v : UInt8) (hj : j < a.size) (h : i.val ≠ j) : (a.set i v)[j]'(a.size_set .. ▸ hj) = a[j] := Array.getElem_set_ne (h := h) .. theorem set_set (a : ByteArray) (i : Fin a.size) (v v' : UInt8) : (a.set i v).set i v' = a.set i v' := ByteArray.ext <| Array.set_set .. /-! ### copySlice -/ @[simp] theorem data_copySlice (a i b j len exact) : (copySlice a i b j len exact).data = b.data.extract 0 j ++ a.data.extract i (i + len) ++ b.data.extract (j + min len (a.data.size - i)) b.data.size := rfl /-! ### append -/ theorem get_append_left {a b : ByteArray} (hlt : i < a.size) (h : i < (a ++ b).size := size_append .. ▸ Nat.lt_of_lt_of_le hlt (Nat.le_add_right ..)) : (a ++ b)[i] = a[i] := by simp [getElem_eq_data_getElem]; exact Array.getElem_append_left hlt theorem get_append_right {a b : ByteArray} (hle : a.size ≤ i) (h : i < (a ++ b).size) (h' : i - a.size < b.size := Nat.sub_lt_left_of_lt_add hle (size_append .. ▸ h)) : (a ++ b)[i] = b[i - a.size] := by simp [getElem_eq_data_getElem]; exact Array.getElem_append_right hle /-! ### extract -/ theorem get_extract_aux {a : ByteArray} {start stop} (h : i < (a.extract start stop).size) : start + i < a.size := by apply Nat.add_lt_of_lt_sub'; apply Nat.lt_of_lt_of_le h rw [size_extract, ← Nat.sub_min_sub_right]; exact Nat.min_le_right .. @[simp] theorem get_extract {a : ByteArray} {start stop} (h : i < (a.extract start stop).size) : (a.extract start stop)[i] = a[start+i]'(get_extract_aux h) := by simp [getElem_eq_data_getElem] /-! ### ofFn -/ /--- `ofFn f` with `f : Fin n → UInt8` returns the byte array whose `i`th element is `f i`. --/ @[inline] def ofFn (f : Fin n → UInt8) : ByteArray := Fin.foldl n (fun acc i => acc.push (f i)) (emptyWithCapacity n) @[simp] theorem ofFn_zero (f : Fin 0 → UInt8) : ofFn f = empty := by simp [ofFn] theorem ofFn_succ (f : Fin (n+1) → UInt8) : ofFn f = (ofFn fun i => f i.castSucc).push (f (Fin.last n)) := by simp [ofFn, Fin.foldl_succ_last, emptyWithCapacity] @[simp] theorem data_ofFn (f : Fin n → UInt8) : (ofFn f).data = .ofFn f := by induction n with | zero => simp | succ n ih => simp [ofFn_succ, Array.ofFn_succ, ih, Fin.last] @[simp] theorem size_ofFn (f : Fin n → UInt8) : (ofFn f).size = n := by simp [size] @[simp] theorem get_ofFn (f : Fin n → UInt8) (i : Fin (ofFn f).size) : (ofFn f).get i = f (i.cast (size_ofFn f)) := by simp [get, Fin.cast] @[simp] theorem getElem_ofFn (f : Fin n → UInt8) (i) (h : i < (ofFn f).size) : (ofFn f)[i] = f ⟨i, size_ofFn f ▸ h⟩ := get_ofFn f ⟨i, h⟩ /-! ### map/mapM -/ /-- Unsafe optimized implementation of `mapM`. This function is unsafe because it relies on the implementation limit that the size of an array is always less than `USize.size`. -/ @[inline] unsafe def mapMUnsafe [Monad m] (a : ByteArray) (f : UInt8 → m UInt8) : m ByteArray := loop a 0 a.usize where /-- Inner loop for `mapMUnsafe`. -/ @[specialize] loop (a : ByteArray) (k s : USize) := do if k < a.usize then let x := a.uget k lcProof let y ← f x let a := a.uset k y lcProof loop a (k+1) s else pure a /-- `mapM f a` applies the monadic function `f` to each element of the array. -/ @[implemented_by mapMUnsafe] def mapM [Monad m] (a : ByteArray) (f : UInt8 → m UInt8) : m ByteArray := do let mut r := a for i in [0:r.size] do r := r.set! i (← f r[i]!) return r /-- `map f a` applies the function `f` to each element of the array. -/ @[inline] def map (a : ByteArray) (f : UInt8 → UInt8) : ByteArray := mapM (m:=Id) a f
.lake/packages/batteries/Batteries/Data/BinomialHeap.lean
module public import Batteries.Data.BinomialHeap.Basic public import Batteries.Data.BinomialHeap.Lemmas
.lake/packages/batteries/Batteries/Data/PairingHeap.lean
module public import Batteries.Classes.Order @[expose] public section namespace Batteries.PairingHeapImp /-- A `Heap` is the nodes of the pairing heap. Each node have two pointers: `child` going to the first child of this node, and `sibling` goes to the next sibling of this tree. So it actually encodes a forest where each node has children `node.child`, `node.child.sibling`, `node.child.sibling.sibling`, etc. Each edge in this forest denotes a `le a b` relation that has been checked, so the root is smaller than everything else under it. -/ inductive Heap (α : Type u) where /-- An empty forest, which has depth `0`. -/ | nil : Heap α /-- A forest consists of a root `a`, a forest `child` elements greater than `a`, and another forest `sibling`. -/ | node (a : α) (child sibling : Heap α) : Heap α deriving Repr /-- `O(n)`. The number of elements in the heap. -/ def Heap.size : Heap α → Nat | .nil => 0 | .node _ c s => c.size + 1 + s.size /-- A node containing a single element `a`. -/ def Heap.singleton (a : α) : Heap α := .node a .nil .nil /-- `O(1)`. Is the heap empty? -/ def Heap.isEmpty : Heap α → Bool | .nil => true | _ => false /-- `O(1)`. Merge two heaps. Ignore siblings. -/ @[specialize] def Heap.merge (le : α → α → Bool) : Heap α → Heap α → Heap α | .nil, .nil => .nil | .nil, .node a₂ c₂ _ => .node a₂ c₂ .nil | .node a₁ c₁ _, .nil => .node a₁ c₁ .nil | .node a₁ c₁ _, .node a₂ c₂ _ => if le a₁ a₂ then .node a₁ (.node a₂ c₂ c₁) .nil else .node a₂ (.node a₁ c₁ c₂) .nil /-- Auxiliary for `Heap.deleteMin`: merge the forest in pairs. -/ @[specialize] def Heap.combine (le : α → α → Bool) : Heap α → Heap α | h₁@(.node _ _ h₂@(.node _ _ s)) => merge le (merge le h₁ h₂) (s.combine le) | h => h /-- `O(1)`. Get the smallest element in the heap, including the passed in value `a`. -/ @[inline] def Heap.headD (a : α) : Heap α → α | .nil => a | .node a _ _ => a /-- `O(1)`. Get the smallest element in the heap, if it has an element. -/ @[inline] def Heap.head? : Heap α → Option α | .nil => none | .node a _ _ => some a /-- Amortized `O(log n)`. Find and remove the the minimum element from the heap. -/ @[inline] def Heap.deleteMin (le : α → α → Bool) : Heap α → Option (α × Heap α) | .nil => none | .node a c _ => (a, combine le c) /-- Amortized `O(log n)`. Get the tail of the pairing heap after removing the minimum element. -/ @[inline] def Heap.tail? (le : α → α → Bool) (h : Heap α) : Option (Heap α) := deleteMin le h |>.map (·.snd) /-- Amortized `O(log n)`. Remove the minimum element of the heap. -/ @[inline] def Heap.tail (le : α → α → Bool) (h : Heap α) : Heap α := tail? le h |>.getD .nil /-- A predicate says there is no more than one tree. -/ inductive Heap.NoSibling : Heap α → Prop /-- An empty heap is no more than one tree. -/ | nil : NoSibling .nil /-- Or there is exactly one tree. -/ | node (a c) : NoSibling (.node a c .nil) instance : Decidable (Heap.NoSibling s) := match s with | .nil => isTrue .nil | .node a c .nil => isTrue (.node a c) | .node _ _ (.node _ _ _) => isFalse nofun theorem Heap.noSibling_merge (le) (s₁ s₂ : Heap α) : (s₁.merge le s₂).NoSibling := by unfold merge (split <;> try split) <;> constructor theorem Heap.noSibling_combine (le) (s : Heap α) : (s.combine le).NoSibling := by unfold combine; split · exact noSibling_merge _ _ _ · match s with | nil | node _ _ nil => constructor | node _ _ (node _ _ s) => rename_i h; exact (h _ _ _ _ _ rfl).elim theorem Heap.noSibling_deleteMin {s : Heap α} (eq : s.deleteMin le = some (a, s')) : s'.NoSibling := by cases s with cases eq | node a c => exact noSibling_combine _ _ theorem Heap.noSibling_tail? {s : Heap α} : s.tail? le = some s' → s'.NoSibling := by simp only [Heap.tail?]; intro eq match eq₂ : s.deleteMin le, eq with | some (a, tl), rfl => exact noSibling_deleteMin eq₂ theorem Heap.noSibling_tail (le) (s : Heap α) : (s.tail le).NoSibling := by simp only [Heap.tail] match eq : s.tail? le with | none => cases s with cases eq | nil => constructor | some tl => exact Heap.noSibling_tail? eq theorem Heap.size_merge_node (le) (a₁ : α) (c₁ s₁ : Heap α) (a₂ : α) (c₂ s₂ : Heap α) : (merge le (.node a₁ c₁ s₁) (.node a₂ c₂ s₂)).size = c₁.size + c₂.size + 2 := by unfold merge; dsimp; split <;> simp +arith [size] theorem Heap.size_merge (le) {s₁ s₂ : Heap α} (h₁ : s₁.NoSibling) (h₂ : s₂.NoSibling) : (merge le s₁ s₂).size = s₁.size + s₂.size := by match h₁, h₂ with | .nil, .nil | .nil, .node _ _ | .node _ _, .nil => simp [merge, size] | .node _ _, .node _ _ => unfold merge; dsimp; split <;> simp +arith [size] theorem Heap.size_combine (le) (s : Heap α) : (s.combine le).size = s.size := by unfold combine; split · rename_i a₁ c₁ a₂ c₂ s rw [size_merge le (noSibling_merge _ _ _) (noSibling_combine _ _), size_merge_node, size_combine le s] simp +arith [size] · rfl theorem Heap.size_deleteMin {s : Heap α} (h : s.NoSibling) (eq : s.deleteMin le = some (a, s')) : s.size = s'.size + 1 := by cases h with cases eq | node a c => rw [size_combine, size, size] theorem Heap.size_tail? {s : Heap α} (h : s.NoSibling) : s.tail? le = some s' → s.size = s'.size + 1 := by simp only [Heap.tail?]; intro eq match eq₂ : s.deleteMin le, eq with | some (a, tl), rfl => exact size_deleteMin h eq₂ theorem Heap.size_tail (le) {s : Heap α} (h : s.NoSibling) : (s.tail le).size = s.size - 1 := by simp only [Heap.tail] match eq : s.tail? le with | none => cases s with cases eq | nil => rfl | some tl => simp [Heap.size_tail? h eq] theorem Heap.size_deleteMin_lt {s : Heap α} (eq : s.deleteMin le = some (a, s')) : s'.size < s.size := by cases s with cases eq | node a c => simp +arith [size_combine, size] theorem Heap.size_tail?_lt {s : Heap α} : s.tail? le = some s' → s'.size < s.size := by simp only [Heap.tail?]; intro eq match eq₂ : s.deleteMin le, eq with | some (a, tl), rfl => exact size_deleteMin_lt eq₂ /-- `O(n log n)`. Monadic fold over the elements of a heap in increasing order, by repeatedly pulling the minimum element out of the heap. -/ @[specialize] def Heap.foldM [Monad m] (le : α → α → Bool) (s : Heap α) (init : β) (f : β → α → m β) : m β := match eq : s.deleteMin le with | none => pure init | some (hd, tl) => have : tl.size < s.size := by simp +arith [Heap.size_deleteMin_lt eq] do foldM le tl (← f init hd) f termination_by s.size /-- `O(n log n)`. Fold over the elements of a heap in increasing order, by repeatedly pulling the minimum element out of the heap. -/ @[inline] def Heap.fold (le : α → α → Bool) (s : Heap α) (init : β) (f : β → α → β) : β := Id.run <| s.foldM le init f /-- `O(n log n)`. Convert the heap to an array in increasing order. -/ @[inline] def Heap.toArray (le : α → α → Bool) (s : Heap α) : Array α := fold le s #[] Array.push /-- `O(n log n)`. Convert the heap to a list in increasing order. -/ @[inline] def Heap.toList (le : α → α → Bool) (s : Heap α) : List α := (s.toArray le).toList /-- `O(n)`. Fold a monadic function over the tree structure to accumulate a value. -/ @[specialize] def Heap.foldTreeM [Monad m] (nil : β) (join : α → β → β → m β) : Heap α → m β | .nil => pure nil | .node a c s => do join a (← c.foldTreeM nil join) (← s.foldTreeM nil join) /-- `O(n)`. Fold a function over the tree structure to accumulate a value. -/ @[inline] def Heap.foldTree (nil : β) (join : α → β → β → β) (s : Heap α) : β := Id.run <| s.foldTreeM nil join /-- `O(n)`. Convert the heap to a list in arbitrary order. -/ def Heap.toListUnordered (s : Heap α) : List α := s.foldTree id (fun a c s l => a :: c (s l)) [] /-- `O(n)`. Convert the heap to an array in arbitrary order. -/ def Heap.toArrayUnordered (s : Heap α) : Array α := s.foldTree id (fun a c s r => s (c (r.push a))) #[] /-- The well formedness predicate for a heap node. It asserts that: * If `a` is added at the top to make the forest into a tree, the resulting tree is a `le`-min-heap (if `le` is well-behaved) -/ def Heap.NodeWF (le : α → α → Bool) (a : α) : Heap α → Prop | .nil => True | .node b c s => (∀ [TotalBLE le], le a b) ∧ c.NodeWF le b ∧ s.NodeWF le a /-- The well formedness predicate for a pairing heap. It asserts that: * There is no more than one tree. * It is a `le`-min-heap (if `le` is well-behaved) -/ inductive Heap.WF (le : α → α → Bool) : Heap α → Prop /-- It is an empty heap. -/ | nil : WF le .nil /-- There is exactly one tree and it is a `le`-min-heap. -/ | node (h : c.NodeWF le a) : WF le (.node a c .nil) theorem Heap.WF.singleton : (Heap.singleton a).WF le := node trivial theorem Heap.WF.merge_node (h₁ : NodeWF le a₁ c₁) (h₂ : NodeWF le a₂ c₂) : (merge le (.node a₁ c₁ s₁) (.node a₂ c₂ s₂)).WF le := by unfold merge; dsimp split <;> rename_i h · exact node ⟨fun [_] => h, h₂, h₁⟩ · exact node ⟨fun [_] => TotalBLE.total.resolve_left h, h₁, h₂⟩ theorem Heap.WF.merge (h₁ : s₁.WF le) (h₂ : s₂.WF le) : (merge le s₁ s₂).WF le := match h₁, h₂ with | .nil, .nil => nil | .nil, .node h₂ => node h₂ | .node h₁, .nil => node h₁ | .node h₁, .node h₂ => merge_node h₁ h₂ theorem Heap.WF.combine (h : s.NodeWF le a) : (combine le s).WF le := match s with | .nil => nil | .node _b _c .nil => node h.2.1 | .node _b₁ _c₁ (.node _b₂ _c₂ _s) => merge (merge_node h.2.1 h.2.2.2.1) (combine h.2.2.2.2) theorem Heap.WF.deleteMin {s : Heap α} (h : s.WF le) (eq : s.deleteMin le = some (a, s')) : s'.WF le := by cases h with cases eq | node h => exact Heap.WF.combine h theorem Heap.WF.tail? (hwf : (s : Heap α).WF le) : s.tail? le = some tl → tl.WF le := by simp only [Heap.tail?]; intro eq match eq₂ : s.deleteMin le, eq with | some (a, tl), rfl => exact hwf.deleteMin eq₂ theorem Heap.WF.tail (hwf : (s : Heap α).WF le) : (s.tail le).WF le := by simp only [Heap.tail] match eq : s.tail? le with | none => exact Heap.WF.nil | some tl => exact hwf.tail? eq theorem Heap.deleteMin_fst : ((s : Heap α).deleteMin le).map (·.1) = s.head? := match s with | .nil => rfl | .node _ _ _ => rfl end PairingHeapImp open PairingHeapImp /-- A [pairing heap](https://en.wikipedia.org/wiki/Pairing_heap) is a data structure which supports the following primary operations: * `insert : α → PairingHeap α → PairingHeap α`: add an element to the heap * `deleteMin : PairingHeap α → Option (α × PairingHeap α)`: remove the minimum element from the heap * `merge : PairingHeap α → PairingHeap α → PairingHeap α`: combine two heaps The first two operations are known as a "priority queue", so this could be called a "mergeable priority queue". The standard choice for a priority queue is a binary heap, which supports `insert` and `deleteMin` in `O(log n)`, but `merge` is `O(n)`. With a `PairingHeap`, `insert` and `merge` are `O(1)`, `deleteMin` is amortized `O(log n)`. Note that `deleteMin` may be `O(n)` in a single operation. So if you need an efficient persistent priority queue, you should use other data structures with better worst-case time. -/ def PairingHeap (α : Type u) (le : α → α → Bool) := { h : Heap α // h.WF le } /-- `O(1)`. Make a new empty pairing heap. -/ @[inline] def mkPairingHeap (α : Type u) (le : α → α → Bool) : PairingHeap α le := ⟨.nil, Heap.WF.nil⟩ namespace PairingHeap variable {α : Type u} {le : α → α → Bool} /-- `O(1)`. Make a new empty pairing heap. -/ @[inline] def empty : PairingHeap α le := mkPairingHeap α le instance : Inhabited (PairingHeap α le) := ⟨.empty⟩ /-- `O(1)`. Is the heap empty? -/ @[inline] def isEmpty (b : PairingHeap α le) : Bool := b.1.isEmpty /-- `O(n)`. The number of elements in the heap. -/ @[inline] def size (b : PairingHeap α le) : Nat := b.1.size /-- `O(1)`. Make a new heap containing `a`. -/ @[inline] def singleton (a : α) : PairingHeap α le := ⟨Heap.singleton a, Heap.WF.singleton⟩ /-- `O(1)`. Merge the contents of two heaps. -/ @[inline] def merge : PairingHeap α le → PairingHeap α le → PairingHeap α le | ⟨b₁, h₁⟩, ⟨b₂, h₂⟩ => ⟨b₁.merge le b₂, h₁.merge h₂⟩ /-- `O(1)`. Add element `a` to the given heap `h`. -/ @[inline] def insert (a : α) (h : PairingHeap α le) : PairingHeap α le := merge (singleton a) h /-- `O(n log n)`. Construct a heap from a list by inserting all the elements. -/ def ofList (le : α → α → Bool) (as : List α) : PairingHeap α le := as.foldl (flip insert) empty /-- `O(n log n)`. Construct a heap from a list by inserting all the elements. -/ def ofArray (le : α → α → Bool) (as : Array α) : PairingHeap α le := as.foldl (flip insert) empty /-- Amortized `O(log n)`. Remove and return the minimum element from the heap. -/ @[inline] def deleteMin (b : PairingHeap α le) : Option (α × PairingHeap α le) := match eq : b.1.deleteMin le with | none => none | some (a, tl) => some (a, ⟨tl, b.2.deleteMin eq⟩) /-- `O(1)`. Returns the smallest element in the heap, or `none` if the heap is empty. -/ @[inline] def head? (b : PairingHeap α le) : Option α := b.1.head? /-- `O(1)`. Returns the smallest element in the heap, or panics if the heap is empty. -/ @[inline] def head! [Inhabited α] (b : PairingHeap α le) : α := b.head?.get! /-- `O(1)`. Returns the smallest element in the heap, or `default` if the heap is empty. -/ @[inline] def headI [Inhabited α] (b : PairingHeap α le) : α := b.head?.getD default /-- Amortized `O(log n)`. Removes the smallest element from the heap, or `none` if the heap is empty. -/ @[inline] def tail? (b : PairingHeap α le) : Option (PairingHeap α le) := match eq : b.1.tail? le with | none => none | some tl => some ⟨tl, b.2.tail? eq⟩ /-- Amortized `O(log n)`. Removes the smallest element from the heap, if possible. -/ @[inline] def tail (b : PairingHeap α le) : PairingHeap α le := ⟨b.1.tail le, b.2.tail⟩ /-- `O(n log n)`. Convert the heap to a list in increasing order. -/ @[inline] def toList (b : PairingHeap α le) : List α := b.1.toList le /-- `O(n log n)`. Convert the heap to an array in increasing order. -/ @[inline] def toArray (b : PairingHeap α le) : Array α := b.1.toArray le /-- `O(n)`. Convert the heap to a list in arbitrary order. -/ @[inline] def toListUnordered (b : PairingHeap α le) : List α := b.1.toListUnordered /-- `O(n)`. Convert the heap to an array in arbitrary order. -/ @[inline] def toArrayUnordered (b : PairingHeap α le) : Array α := b.1.toArrayUnordered
.lake/packages/batteries/Batteries/Data/BinaryHeap.lean
module public section namespace Batteries /-- A max-heap data structure. -/ structure BinaryHeap (α) (lt : α → α → Bool) where /-- `O(1)`. Get data array for a `BinaryHeap`. -/ arr : Array α namespace BinaryHeap private def maxChild (lt : α → α → Bool) (a : Vector α sz) (i : Fin sz) : Option (Fin sz) := let left := 2 * i.1 + 1 let right := left + 1 if hleft : left < sz then if hright : right < sz then if lt a[left] a[right] then some ⟨right, hright⟩ else some ⟨left, hleft⟩ else some ⟨left, hleft⟩ else none /-- Core operation for binary heaps, expressed directly on arrays. Given an array which is a max-heap, push item `i` down to restore the max-heap property. -/ def heapifyDown (lt : α → α → Bool) (a : Vector α sz) (i : Fin sz) : Vector α sz := match h : maxChild lt a i with | none => a | some j => have : i < j := by cases i; cases j simp only [maxChild] at h split at h · split at h · split at h <;> (cases h; simp +arith) · cases h; simp +arith · contradiction if lt a[i] a[j] then heapifyDown lt (a.swap i j) j else a termination_by sz - i /-- Core operation for binary heaps, expressed directly on arrays. Construct a heap from an unsorted array, by heapifying all the elements. -/ def mkHeap (lt : α → α → Bool) (a : Vector α sz) : Vector α sz := loop (sz / 2) a (Nat.div_le_self ..) where /-- Inner loop for `mkHeap`. -/ loop : (i : Nat) → (a : Vector α sz) → i ≤ sz → Vector α sz | 0, a, _ => a | i+1, a, h => let a' := heapifyDown lt a ⟨i, Nat.lt_of_succ_le h⟩ loop i a' (Nat.le_trans (Nat.le_succ _) h) /-- Core operation for binary heaps, expressed directly on arrays. Given an array which is a max-heap, push item `i` up to restore the max-heap property. -/ def heapifyUp (lt : α → α → Bool) (a : Vector α sz) (i : Fin sz) : Vector α sz := match i with | ⟨0, _⟩ => a | ⟨i'+1, hi⟩ => let j := i'/2 if lt a[j] a[i] then heapifyUp lt (a.swap i j) ⟨j, by get_elem_tactic⟩ else a /-- `O(1)`. Build a new empty heap. -/ def empty (lt) : BinaryHeap α lt := ⟨#[]⟩ instance (lt) : Inhabited (BinaryHeap α lt) := ⟨empty _⟩ instance (lt) : EmptyCollection (BinaryHeap α lt) := ⟨empty _⟩ /-- `O(1)`. Build a one-element heap. -/ def singleton (lt) (x : α) : BinaryHeap α lt := ⟨#[x]⟩ /-- `O(1)`. Get the number of elements in a `BinaryHeap`. -/ def size (self : BinaryHeap α lt) : Nat := self.1.size /-- `O(1)`. Get data vector of a `BinaryHeap`. -/ def vector (self : BinaryHeap α lt) : Vector α self.size := ⟨self.1, rfl⟩ /-- `O(1)`. Get an element in the heap by index. -/ def get (self : BinaryHeap α lt) (i : Fin self.size) : α := self.1[i]'(i.2) /-- `O(log n)`. Insert an element into a `BinaryHeap`, preserving the max-heap property. -/ def insert (self : BinaryHeap α lt) (x : α) : BinaryHeap α lt where arr := heapifyUp lt (self.vector.push x) ⟨_, Nat.lt_succ_self _⟩ |>.toArray @[simp] theorem size_insert (self : BinaryHeap α lt) (x : α) : (self.insert x).size = self.size + 1 := by simp [size, insert] /-- `O(1)`. Get the maximum element in a `BinaryHeap`. -/ def max (self : BinaryHeap α lt) : Option α := self.1[0]? /-- `O(log n)`. Remove the maximum element from a `BinaryHeap`. Call `max` first to actually retrieve the maximum element. -/ def popMax (self : BinaryHeap α lt) : BinaryHeap α lt := if h0 : self.size = 0 then self else have hs : self.size - 1 < self.size := Nat.pred_lt h0 have h0 : 0 < self.size := Nat.zero_lt_of_ne_zero h0 let v := self.vector.swap _ _ h0 hs |>.pop if h : 0 < self.size - 1 then ⟨heapifyDown lt v ⟨0, h⟩ |>.toArray⟩ else ⟨v.toArray⟩ @[simp] theorem size_popMax (self : BinaryHeap α lt) : self.popMax.size = self.size - 1 := by simp only [popMax, size] split · simp +arith [*] · split <;> simp +arith /-- `O(log n)`. Return and remove the maximum element from a `BinaryHeap`. -/ def extractMax (self : BinaryHeap α lt) : Option α × BinaryHeap α lt := (self.max, self.popMax) theorem size_pos_of_max {self : BinaryHeap α lt} (h : self.max = some x) : 0 < self.size := by simp only [max, getElem?_def] at h split at h · assumption · contradiction /-- `O(log n)`. Equivalent to `extractMax (self.insert x)`, except that extraction cannot fail. -/ def insertExtractMax (self : BinaryHeap α lt) (x : α) : α × BinaryHeap α lt := match e : self.max with | none => (x, self) | some m => if lt x m then let v := self.vector.set 0 x (size_pos_of_max e) (m, ⟨heapifyDown lt v ⟨0, size_pos_of_max e⟩ |>.toArray⟩) else (x, self) /-- `O(log n)`. Equivalent to `(self.max, self.popMax.insert x)`. -/ def replaceMax (self : BinaryHeap α lt) (x : α) : Option α × BinaryHeap α lt := match e : self.max with | none => (none, ⟨self.vector.push x |>.toArray⟩) | some m => let v := self.vector.set 0 x (size_pos_of_max e) (some m, ⟨heapifyDown lt v ⟨0, size_pos_of_max e⟩ |>.toArray⟩) /-- `O(log n)`. Replace the value at index `i` by `x`. Assumes that `x ≤ self.get i`. -/ def decreaseKey (self : BinaryHeap α lt) (i : Fin self.size) (x : α) : BinaryHeap α lt where arr := heapifyDown lt (self.vector.set i x) i |>.toArray /-- `O(log n)`. Replace the value at index `i` by `x`. Assumes that `self.get i ≤ x`. -/ def increaseKey (self : BinaryHeap α lt) (i : Fin self.size) (x : α) : BinaryHeap α lt where arr := heapifyUp lt (self.vector.set i x) i |>.toArray end Batteries.BinaryHeap /-- `O(n)`. Convert an unsorted vector to a `BinaryHeap`. -/ def Batteries.Vector.toBinaryHeap (lt : α → α → Bool) (v : Vector α n) : Batteries.BinaryHeap α lt where arr := BinaryHeap.mkHeap lt v |>.toArray open Batteries in /-- `O(n)`. Convert an unsorted array to a `BinaryHeap`. -/ def Array.toBinaryHeap (lt : α → α → Bool) (a : Array α) : Batteries.BinaryHeap α lt where arr := BinaryHeap.mkHeap lt ⟨a, rfl⟩ |>.toArray open Batteries in /-- `O(n log n)`. Sort an array using a `BinaryHeap`. -/ @[specialize] def Array.heapSort (a : Array α) (lt : α → α → Bool) : Array α := loop (a.toBinaryHeap (flip lt)) #[] where /-- Inner loop for `heapSort`. -/ loop (a : Batteries.BinaryHeap α (flip lt)) (out : Array α) : Array α := match e: a.max with | none => out | some x => have : a.popMax.size < a.size := by simp; exact Nat.sub_lt (Batteries.BinaryHeap.size_pos_of_max e) Nat.zero_lt_one loop a.popMax (out.push x) termination_by a.size
.lake/packages/batteries/Batteries/Data/Range.lean
module public import Batteries.Data.Range.Lemmas
.lake/packages/batteries/Batteries/Data/AssocList.lean
module public import Batteries.Data.List.Basic @[expose] public section namespace Batteries /-- `AssocList α β` is "the same as" `List (α × β)`, but flattening the structure leads to one fewer pointer indirection (in the current code generator). It is mainly intended as a component of `HashMap`, but it can also be used as a plain key-value map. -/ inductive AssocList (α : Type u) (β : Type v) where /-- An empty list -/ | nil /-- Add a `key, value` pair to the list -/ | cons (key : α) (value : β) (tail : AssocList α β) deriving Inhabited namespace AssocList /-- `O(n)`. Convert an `AssocList α β` into the equivalent `List (α × β)`. This is used to give specifications for all the `AssocList` functions in terms of corresponding list functions. -/ @[simp] def toList : AssocList α β → List (α × β) | nil => [] | cons a b es => (a, b) :: es.toList instance : EmptyCollection (AssocList α β) := ⟨nil⟩ @[simp] theorem empty_eq : (∅ : AssocList α β) = nil := rfl /-- `O(1)`. Is the list empty? -/ def isEmpty : AssocList α β → Bool | nil => true | _ => false @[simp] theorem isEmpty_eq (l : AssocList α β) : isEmpty l = l.toList.isEmpty := by cases l <;> simp [*, isEmpty, List.isEmpty] /-- The number of entries in an `AssocList`. -/ def length (L : AssocList α β) : Nat := match L with | .nil => 0 | .cons _ _ t => t.length + 1 @[simp] theorem length_nil : length (nil : AssocList α β) = 0 := rfl @[simp] theorem length_cons : length (cons a b t) = length t + 1 := rfl theorem length_toList (l : AssocList α β) : l.toList.length = l.length := by induction l <;> simp_all /-- `O(n)`. Fold a monadic function over the list, from head to tail. -/ @[specialize] def foldlM [Monad m] (f : δ → α → β → m δ) : (init : δ) → AssocList α β → m δ | d, nil => pure d | d, cons a b es => do foldlM f (← f d a b) es @[simp] theorem foldlM_eq [Monad m] (f : δ → α → β → m δ) (init l) : foldlM f init l = l.toList.foldlM (fun d (a, b) => f d a b) init := by induction l generalizing init <;> simp [*, foldlM] /-- `O(n)`. Fold a function over the list, from head to tail. -/ @[inline] def foldl (f : δ → α → β → δ) (init : δ) (as : AssocList α β) : δ := Id.run (foldlM (fun d a b => pure (f d a b)) init as) @[simp] theorem foldl_eq (f : δ → α → β → δ) (init l) : foldl f init l = l.toList.foldl (fun d (a, b) => f d a b) init := by simp [foldl, foldlM_eq] /-- Optimized version of `toList`. -/ def toListTR (as : AssocList α β) : List (α × β) := as.foldl (init := #[]) (fun r a b => r.push (a, b)) |>.toList @[csimp] theorem toList_eq_toListTR : @toList = @toListTR := by funext α β as; simp [toListTR] /-- `O(n)`. Run monadic function `f` on all elements in the list, from head to tail. -/ @[specialize] def forM [Monad m] (f : α → β → m PUnit) : AssocList α β → m PUnit | nil => pure ⟨⟩ | cons a b es => do f a b; forM f es @[simp] theorem forM_eq [Monad m] (f : α → β → m PUnit) (l) : forM f l = l.toList.forM (fun (a, b) => f a b) := by induction l <;> simp [*, forM] /-- `O(n)`. Map a function `f` over the keys of the list. -/ @[simp] def mapKey (f : α → δ) : AssocList α β → AssocList δ β | nil => nil | cons k v t => cons (f k) v (mapKey f t) @[simp] theorem toList_mapKey (f : α → δ) (l : AssocList α β) : (mapKey f l).toList = l.toList.map (fun (a, b) => (f a, b)) := by induction l <;> simp [*] @[simp] theorem length_mapKey : (mapKey f l).length = l.length := by induction l <;> simp_all /-- `O(n)`. Map a function `f` over the values of the list. -/ @[simp] def mapVal (f : α → β → δ) : AssocList α β → AssocList α δ | nil => nil | cons k v t => cons k (f k v) (mapVal f t) @[simp] theorem toList_mapVal (f : α → β → δ) (l : AssocList α β) : (mapVal f l).toList = l.toList.map (fun (a, b) => (a, f a b)) := by induction l <;> simp [*] @[simp] theorem length_mapVal : (mapVal f l).length = l.length := by induction l <;> simp_all /-- `O(n)`. Returns the first entry in the list whose entry satisfies `p`. -/ @[specialize] def findEntryP? (p : α → β → Bool) : AssocList α β → Option (α × β) | nil => none | cons k v es => bif p k v then some (k, v) else findEntryP? p es @[simp] theorem findEntryP?_eq (p : α → β → Bool) (l : AssocList α β) : findEntryP? p l = l.toList.find? fun (a, b) => p a b := by induction l <;> simp [findEntryP?, List.find?_cons]; split <;> simp [*] /-- `O(n)`. Returns the first entry in the list whose key is equal to `a`. -/ @[inline] def findEntry? [BEq α] (a : α) (l : AssocList α β) : Option (α × β) := findEntryP? (fun k _ => k == a) l @[simp] theorem findEntry?_eq [BEq α] (a : α) (l : AssocList α β) : findEntry? a l = l.toList.find? (·.1 == a) := findEntryP?_eq .. /-- `O(n)`. Returns the first value in the list whose key is equal to `a`. -/ def find? [BEq α] (a : α) : AssocList α β → Option β | nil => none | cons k v es => match k == a with | true => some v | false => find? a es theorem find?_eq_findEntry? [BEq α] (a : α) (l : AssocList α β) : find? a l = (l.findEntry? a).map (·.2) := by induction l <;> simp [find?, List.find?_cons]; split <;> simp [*] @[simp] theorem find?_eq [BEq α] (a : α) (l : AssocList α β) : find? a l = (l.toList.find? (·.1 == a)).map (·.2) := by simp [find?_eq_findEntry?] /-- `O(n)`. Returns true if any entry in the list satisfies `p`. -/ @[specialize] def any (p : α → β → Bool) : AssocList α β → Bool | nil => false | cons k v es => p k v || any p es @[simp] theorem any_eq (p : α → β → Bool) (l : AssocList α β) : any p l = l.toList.any fun (a, b) => p a b := by induction l <;> simp [any, *] /-- `O(n)`. Returns true if every entry in the list satisfies `p`. -/ @[specialize] def all (p : α → β → Bool) : AssocList α β → Bool | nil => true | cons k v es => p k v && all p es @[simp] theorem all_eq (p : α → β → Bool) (l : AssocList α β) : all p l = l.toList.all fun (a, b) => p a b := by induction l <;> simp [all, *] /-- Returns true if every entry in the list satisfies `p`. -/ def All (p : α → β → Prop) (l : AssocList α β) : Prop := ∀ a ∈ l.toList, p a.1 a.2 /-- `O(n)`. Returns true if there is an element in the list whose key is equal to `a`. -/ @[inline] def contains [BEq α] (a : α) (l : AssocList α β) : Bool := any (fun k _ => k == a) l @[simp] theorem contains_eq [BEq α] (a : α) (l : AssocList α β) : contains a l = l.toList.any (·.1 == a) := by induction l <;> simp [*, contains] /-- `O(n)`. Replace the first entry in the list with key equal to `a` to have key `a` and value `b`. -/ @[simp] def replace [BEq α] (a : α) (b : β) : AssocList α β → AssocList α β | nil => nil | cons k v es => match k == a with | true => cons a b es | false => cons k v (replace a b es) @[simp] theorem toList_replace [BEq α] (a : α) (b : β) (l : AssocList α β) : (replace a b l).toList = l.toList.replaceF (bif ·.1 == a then some (a, b) else none) := by induction l <;> simp [replace]; split <;> simp [*] @[simp] theorem length_replace [BEq α] {a : α} : (replace a b l).length = l.length := by induction l · rfl · simp only [replace, length_cons] split <;> simp_all /-- `O(n)`. Remove the first entry in the list with key equal to `a`. -/ @[specialize, simp] def eraseP (p : α → β → Bool) : AssocList α β → AssocList α β | nil => nil | cons k v es => bif p k v then es else cons k v (eraseP p es) @[simp] theorem toList_eraseP (p) (l : AssocList α β) : (eraseP p l).toList = l.toList.eraseP fun (a, b) => p a b := by induction l <;> simp [List.eraseP, cond]; split <;> simp [*] /-- `O(n)`. Remove the first entry in the list with key equal to `a`. -/ @[inline] def erase [BEq α] (a : α) (l : AssocList α β) : AssocList α β := eraseP (fun k _ => k == a) l @[simp] theorem toList_erase [BEq α] (a : α) (l : AssocList α β) : (erase a l).toList = l.toList.eraseP (·.1 == a) := toList_eraseP .. /-- `O(n)`. Replace the first entry `a', b` in the list with key equal to `a` to have key `a` and value `f a' b`. -/ @[simp] def modify [BEq α] (a : α) (f : α → β → β) : AssocList α β → AssocList α β | nil => nil | cons k v es => match k == a with | true => cons a (f k v) es | false => cons k v (modify a f es) @[simp] theorem toList_modify [BEq α] (a : α) (l : AssocList α β) : (modify a f l).toList = l.toList.replaceF fun (k, v) => bif k == a then some (a, f k v) else none := by simp [cond] induction l with simp [List.replaceF] | cons k v es ih => cases k == a <;> simp [ih] @[simp] theorem length_modify [BEq α] {a : α} : (modify a f l).length = l.length := by induction l · rfl · simp only [modify, length_cons] split <;> simp_all /-- The implementation of `ForIn`, which enables `for (k, v) in aList do ...` notation. -/ @[specialize] protected def forIn [Monad m] (as : AssocList α β) (init : δ) (f : (α × β) → δ → m (ForInStep δ)) : m δ := match as with | nil => pure init | cons k v es => do match (← f (k, v) init) with | ForInStep.done d => pure d | ForInStep.yield d => es.forIn d f instance : ForIn m (AssocList α β) (α × β) where forIn := AssocList.forIn @[simp] theorem forIn_eq [Monad m] (l : AssocList α β) (init : δ) (f : (α × β) → δ → m (ForInStep δ)) : forIn l init f = forIn l.toList init f := by simp only [forIn] induction l generalizing init <;> simp [AssocList.forIn] congr; funext a; split <;> simp [*] /-- Split the list into head and tail, if possible. -/ def pop? : AssocList α β → Option ((α × β) × AssocList α β) | nil => none | cons a b l => some ((a, b), l) instance : Std.ToStream (AssocList α β) (AssocList α β) := ⟨fun x => x⟩ instance : Std.Stream (AssocList α β) (α × β) := ⟨pop?⟩ /-- Converts a list into an `AssocList`. This is the inverse function to `AssocList.toList`. -/ @[simp] def _root_.List.toAssocList : List (α × β) → AssocList α β | [] => nil | (a,b) :: es => cons a b (toAssocList es) @[simp] theorem _root_.List.toList_toAssocList (l : List (α × β)) : l.toAssocList.toList = l := by induction l <;> simp [*] @[simp] theorem toList_toAssocList (l : AssocList α β) : l.toList.toAssocList = l := by induction l <;> simp [*] @[simp] theorem _root_.List.length_toAssocList (l : List (α × β)) : l.toAssocList.length = l.length := by induction l <;> simp [*] /-- Implementation of `==` on `AssocList`. -/ protected def beq [BEq α] [BEq β] : AssocList α β → AssocList α β → Bool | .nil, .nil => true | .cons _ _ _, .nil => false | .nil, .cons _ _ _ => false | .cons a b t, .cons a' b' t' => a == a' && b == b' && AssocList.beq t t' /-- Boolean equality for `AssocList`. (This relation cares about the ordering of the key-value pairs.) -/ instance [BEq α] [BEq β] : BEq (AssocList α β) where beq := AssocList.beq @[simp] theorem beq_nil₂ [BEq α] [BEq β] : ((.nil : AssocList α β) == .nil) = true := rfl @[simp] theorem beq_nil_cons [BEq α] [BEq β] : ((.nil : AssocList α β) == .cons a b t) = false := rfl @[simp] theorem beq_cons_nil [BEq α] [BEq β] : ((.cons a b t : AssocList α β) == .nil) = false := rfl @[simp] theorem beq_cons₂ [BEq α] [BEq β] : ((.cons a b t : AssocList α β) == .cons a' b' t') = (a == a' && b == b' && t == t') := rfl instance [BEq α] [LawfulBEq α] [BEq β] [LawfulBEq β] : LawfulBEq (AssocList α β) where rfl {L} := by induction L <;> simp_all eq_of_beq {L M} := by induction L generalizing M with | nil => cases M <;> simp_all | cons a b L ih => cases M with | nil => simp_all | cons a' b' M => simp_all only [beq_cons₂, Bool.and_eq_true, beq_iff_eq, cons.injEq, true_and, and_imp] exact fun _ _ => ih protected theorem beq_eq [BEq α] [BEq β] {l m : AssocList α β} : (l == m) = (l.toList == m.toList) := by simp [(· == ·)] induction l generalizing m <;> cases m <;> simp [*, (· == ·), AssocList.beq, List.beq]
.lake/packages/batteries/Batteries/Data/Char.lean
module public import Batteries.Data.Char.AsciiCasing public import Batteries.Data.Char.Basic
.lake/packages/batteries/Batteries/Data/Array.lean
module public import Batteries.Data.Array.Basic public import Batteries.Data.Array.Init.Lemmas public import Batteries.Data.Array.Lemmas public import Batteries.Data.Array.Match public import Batteries.Data.Array.Merge public import Batteries.Data.Array.Monadic public import Batteries.Data.Array.Pairwise
.lake/packages/batteries/Batteries/Data/UInt.lean
module public import Batteries.Classes.Order @[expose] public section /-! ### UInt8 -/ @[ext] theorem UInt8.ext : {x y : UInt8} → x.toNat = y.toNat → x = y | ⟨⟨_,_⟩⟩, ⟨⟨_,_⟩⟩, rfl => rfl @[simp] theorem UInt8.toUInt16_toNat (x : UInt8) : x.toUInt16.toNat = x.toNat := rfl @[simp] theorem UInt8.toUInt32_toNat (x : UInt8) : x.toUInt32.toNat = x.toNat := rfl @[simp] theorem UInt8.toUInt64_toNat (x : UInt8) : x.toUInt64.toNat = x.toNat := rfl instance : Std.LawfulOrd UInt8 := Std.LawfulCmp.compareOfLessAndEq_of_irrefl_of_trans_of_not_lt_of_antisymm (fun _ => Nat.lt_irrefl _) Nat.lt_trans Nat.not_lt UInt8.le_antisymm /-! ### UInt16 -/ @[ext] theorem UInt16.ext : {x y : UInt16} → x.toNat = y.toNat → x = y | ⟨⟨_,_⟩⟩, ⟨⟨_,_⟩⟩, rfl => rfl @[simp] theorem UInt16.toUInt8_toNat (x : UInt16) : x.toUInt8.toNat = x.toNat % 2 ^ 8 := rfl @[simp] theorem UInt16.toUInt32_toNat (x : UInt16) : x.toUInt32.toNat = x.toNat := rfl @[simp] theorem UInt16.toUInt64_toNat (x : UInt16) : x.toUInt64.toNat = x.toNat := rfl instance : Std.LawfulOrd UInt16 := Std.LawfulCmp.compareOfLessAndEq_of_irrefl_of_trans_of_not_lt_of_antisymm (fun _ => Nat.lt_irrefl _) Nat.lt_trans Nat.not_lt UInt16.le_antisymm /-! ### UInt32 -/ @[ext] theorem UInt32.ext : {x y : UInt32} → x.toNat = y.toNat → x = y | ⟨⟨_,_⟩⟩, ⟨⟨_,_⟩⟩, rfl => rfl @[simp] theorem UInt32.toUInt8_toNat (x : UInt32) : x.toUInt8.toNat = x.toNat % 2 ^ 8 := rfl @[simp] theorem UInt32.toUInt16_toNat (x : UInt32) : x.toUInt16.toNat = x.toNat % 2 ^ 16 := rfl @[simp] theorem UInt32.toUInt64_toNat (x : UInt32) : x.toUInt64.toNat = x.toNat := rfl instance : Std.LawfulOrd UInt32 := Std.LawfulCmp.compareOfLessAndEq_of_irrefl_of_trans_of_not_lt_of_antisymm (fun _ => Nat.lt_irrefl _) Nat.lt_trans Nat.not_lt UInt32.le_antisymm /-! ### UInt64 -/ @[ext] theorem UInt64.ext : {x y : UInt64} → x.toNat = y.toNat → x = y | ⟨⟨_,_⟩⟩, ⟨⟨_,_⟩⟩, rfl => rfl @[simp] theorem UInt64.toUInt8_toNat (x : UInt64) : x.toUInt8.toNat = x.toNat % 2 ^ 8 := rfl @[simp] theorem UInt64.toUInt16_toNat (x : UInt64) : x.toUInt16.toNat = x.toNat % 2 ^ 16 := rfl @[simp] theorem UInt64.toUInt32_toNat (x : UInt64) : x.toUInt32.toNat = x.toNat % 2 ^ 32 := rfl instance : Std.LawfulOrd UInt64 := Std.LawfulCmp.compareOfLessAndEq_of_irrefl_of_trans_of_not_lt_of_antisymm (fun _ => Nat.lt_irrefl _) Nat.lt_trans Nat.not_lt UInt64.le_antisymm /-! ### USize -/ @[ext] theorem USize.ext : {x y : USize} → x.toNat = y.toNat → x = y | ⟨⟨_,_⟩⟩, ⟨⟨_,_⟩⟩, rfl => rfl theorem USize.toUInt64_toNat (x : USize) : x.toUInt64.toNat = x.toNat := by simp @[simp] theorem UInt32.toUSize_toNat (x : UInt32) : x.toUSize.toNat = x.toNat := rfl instance : Std.LawfulOrd USize := Std.LawfulCmp.compareOfLessAndEq_of_irrefl_of_trans_of_not_lt_of_antisymm (fun _ => Nat.lt_irrefl _) Nat.lt_trans Nat.not_lt USize.le_antisymm
.lake/packages/batteries/Batteries/Data/Stream.lean
module @[expose] public section namespace Std.Stream /-- Drop up to `n` values from the stream `s`. -/ def drop [Stream σ α] (s : σ) : Nat → σ | 0 => s | n+1 => match next? s with | none => s | some (_, s) => drop s n /-- Read up to `n` values from the stream `s` as a list from first to last. -/ def take [Stream σ α] (s : σ) : Nat → List α × σ | 0 => ([], s) | n+1 => match next? s with | none => ([], s) | some (a, s) => match take s n with | (as, s) => (a :: as, s) @[simp] theorem fst_take_zero [Stream σ α] (s : σ) : (take s 0).fst = [] := rfl theorem fst_take_succ [Stream σ α] (s : σ) : (take s (n+1)).fst = match next? s with | none => [] | some (a, s) => a :: (take s n).fst := by simp only [take]; split <;> rfl @[simp] theorem snd_take_eq_drop [Stream σ α] (s : σ) (n : Nat) : (take s n).snd = drop s n := by induction n generalizing s with | zero => rfl | succ n ih => simp only [take, drop] split <;> simp [ih] /-- Tail recursive version of `Stream.take`. -/ def takeTR [Stream σ α] (s : σ) (n : Nat) : List α × σ := loop s [] n where /-- Inner loop for `Stream.takeTR`. -/ loop (s : σ) (acc : List α) | 0 => (acc.reverse, s) | n+1 => match next? s with | none => (acc.reverse, s) | some (a, s) => loop s (a :: acc) n theorem fst_takeTR_loop [Stream σ α] (s : σ) (acc : List α) (n : Nat) : (takeTR.loop s acc n).fst = acc.reverseAux (take s n).fst := by induction n generalizing acc s with | zero => rfl | succ n ih => simp only [take, takeTR.loop]; split; rfl; simp [ih] theorem fst_takeTR [Stream σ α] (s : σ) (n : Nat) : (takeTR s n).fst = (take s n).fst := fst_takeTR_loop .. theorem snd_takeTR_loop [Stream σ α] (s : σ) (acc : List α) (n : Nat) : (takeTR.loop s acc n).snd = drop s n := by induction n generalizing acc s with | zero => rfl | succ n ih => simp only [takeTR.loop, drop]; split; rfl; simp [ih] theorem snd_takeTR [Stream σ α] (s : σ) (n : Nat) : (takeTR s n).snd = drop s n := snd_takeTR_loop .. @[csimp] theorem take_eq_takeTR : @take = @takeTR := by funext; ext : 1; rw [fst_takeTR]; rw [snd_takeTR, snd_take_eq_drop] end Stream @[simp] theorem List.stream_drop_eq_drop (l : List α) : Stream.drop l n = l.drop n := by induction n generalizing l with | zero => rfl | succ n ih => match l with | [] => rfl | _::_ => simp [Stream.drop, List.drop_succ_cons, ih] @[simp] theorem List.stream_take_eq_take_drop (l : List α) : Stream.take l n = (l.take n, l.drop n) := by induction n generalizing l with | zero => rfl | succ n ih => match l with | [] => rfl | _::_ => simp [Stream.take, ih]
.lake/packages/batteries/Batteries/Data/Random.lean
module public import Batteries.Data.Random.MersenneTwister
.lake/packages/batteries/Batteries/Data/BinomialHeap/Lemmas.lean
module public import Batteries.Data.BinomialHeap.Basic @[expose] public section namespace Batteries.BinomialHeap namespace Imp theorem Heap.findMin_val : ((s : Heap α).findMin le k res).val = s.headD le res.val := match s with | .nil => rfl | .cons r a c s => by rw [findMin, headD]; split <;> apply findMin_val theorem Heap.deleteMin_fst : ((s : Heap α).deleteMin le).map (·.1) = s.head? le := match s with | .nil => rfl | .cons r a c s => by simp only [deleteMin, findMin_val, Option.map, head?] theorem HeapNode.WF.realSize_eq : ∀ {n} {s : HeapNode α}, s.WF le a n → s.realSize + 1 = 2 ^ n | _, .nil, rfl => rfl | _, .node .., ⟨_, rfl, _, c, s⟩ => by rw [realSize, realSize_eq c, Nat.pow_succ, Nat.mul_succ] simp [Nat.add_assoc, realSize_eq s] theorem Heap.WF.size_eq : ∀ {s : Heap α}, s.WF le n → s.size = s.realSize | .nil, _ => rfl | .cons .., ⟨_, h₁, h₂⟩ => by simp [size, size_eq h₂] simp [Nat.one_shiftLeft, h₁.realSize_eq] end Imp
.lake/packages/batteries/Batteries/Data/BinomialHeap/Basic.lean
module public import Batteries.Classes.Order public import Batteries.Control.ForInStep.Basic @[expose] public section namespace Batteries namespace BinomialHeap namespace Imp /-- A `HeapNode` is one of the internal nodes of the binomial heap. It is always a perfect binary tree, with the depth of the tree stored in the `Heap`. However the interpretation of the two pointers is different: we view the `child` as going to the first child of this node, and `sibling` goes to the next sibling of this tree. So it actually encodes a forest where each node has children `node.child`, `node.child.sibling`, `node.child.sibling.sibling`, etc. Each edge in this forest denotes a `le a b` relation that has been checked, so the root is smaller than everything else under it. -/ inductive HeapNode (α : Type u) where /-- An empty forest, which has depth `0`. -/ | nil : HeapNode α /-- A forest of rank `r + 1` consists of a root `a`, a forest `child` of rank `r` elements greater than `a`, and another forest `sibling` of rank `r`. -/ | node (a : α) (child sibling : HeapNode α) : HeapNode α deriving Repr /-- The "real size" of the node, counting up how many values of type `α` are stored. This is `O(n)` and is intended mainly for specification purposes. For a well formed `HeapNode` the size is always `2^n - 1` where `n` is the depth. -/ @[simp] def HeapNode.realSize : HeapNode α → Nat | .nil => 0 | .node _ c s => c.realSize + 1 + s.realSize /-- A node containing a single element `a`. -/ def HeapNode.singleton (a : α) : HeapNode α := .node a .nil .nil /-- `O(log n)`. The rank, or the number of trees in the forest. It is also the depth of the forest. -/ def HeapNode.rank : HeapNode α → Nat | .nil => 0 | .node _ _ s => s.rank + 1 /-- Tail-recursive version of `HeapNode.rank`. -/ @[inline] def HeapNode.rankTR (s : HeapNode α) : Nat := go s 0 where /-- Computes `s.rank + r` -/ go : HeapNode α → Nat → Nat | .nil, r => r | .node _ _ s, r => go s (r + 1) @[csimp] theorem HeapNode.rankTR_eq : @rankTR = @rank := by funext α s; exact go s 0 where go {α} : ∀ s n, @rankTR.go α s n = rank s + n | .nil, _ => (Nat.zero_add ..).symm | .node .., _ => by simp +arith only [rankTR.go, go, rank] /-- A `Heap` is the top level structure in a binomial heap. It consists of a forest of `HeapNode`s with strictly increasing ranks. -/ inductive Heap (α : Type u) where /-- An empty heap. -/ | nil : Heap α /-- A cons node contains a tree of root `val`, children `node` and rank `rank`, and then `next` which is the rest of the forest. -/ | cons (rank : Nat) (val : α) (node : HeapNode α) (next : Heap α) : Heap α deriving Repr /-- `O(n)`. The "real size" of the heap, counting up how many values of type `α` are stored. This is intended mainly for specification purposes. Prefer `Heap.size`, which is the same for well formed heaps. -/ @[simp] def Heap.realSize : Heap α → Nat | .nil => 0 | .cons _ _ c s => c.realSize + 1 + s.realSize /-- `O(log n)`. The number of elements in the heap. -/ def Heap.size : Heap α → Nat | .nil => 0 | .cons r _ _ s => 1 <<< r + s.size /-- `O(1)`. Is the heap empty? -/ @[inline] def Heap.isEmpty : Heap α → Bool | .nil => true | _ => false /-- `O(1)`. The heap containing a single value `a`. -/ @[inline] def Heap.singleton (a : α) : Heap α := .cons 0 a .nil .nil /-- `O(1)`. Auxiliary for `Heap.merge`: Is the minimum rank in `Heap` strictly larger than `n`? -/ def Heap.rankGT : Heap α → Nat → Prop | .nil, _ => True | .cons r .., n => n < r instance : Decidable (Heap.rankGT s n) := match s with | .nil => inferInstanceAs (Decidable True) | .cons .. => inferInstanceAs (Decidable (_ < _)) /-- `O(log n)`. The number of trees in the forest. -/ @[simp] def Heap.length : Heap α → Nat | .nil => 0 | .cons _ _ _ r => r.length + 1 /-- `O(1)`. Auxiliary for `Heap.merge`: combines two heap nodes of the same rank into one with the next larger rank. -/ @[inline] def combine (le : α → α → Bool) (a₁ a₂ : α) (n₁ n₂ : HeapNode α) : α × HeapNode α := if le a₁ a₂ then (a₁, .node a₂ n₂ n₁) else (a₂, .node a₁ n₁ n₂) /-- Merge two forests of binomial trees. The forests are assumed to be ordered by rank and `merge` maintains this invariant. -/ @[specialize] def Heap.merge (le : α → α → Bool) : Heap α → Heap α → Heap α | .nil, h => h | h, .nil => h | s₁@(.cons r₁ a₁ n₁ t₁), s₂@(.cons r₂ a₂ n₂ t₂) => if r₁ < r₂ then .cons r₁ a₁ n₁ (merge le t₁ s₂) else if r₂ < r₁ then .cons r₂ a₂ n₂ (merge le s₁ t₂) else let (a, n) := combine le a₁ a₂ n₁ n₂ let r := r₁ + 1 if t₁.rankGT r then if t₂.rankGT r then .cons r a n (merge le t₁ t₂) else merge le (.cons r a n t₁) t₂ else if t₂.rankGT r then merge le t₁ (.cons r a n t₂) else .cons r a n (merge le t₁ t₂) termination_by s₁ s₂ => s₁.length + s₂.length /-- `O(log n)`. Convert a `HeapNode` to a `Heap` by reversing the order of the nodes along the `sibling` spine. -/ def HeapNode.toHeap (s : HeapNode α) : Heap α := go s s.rank .nil where /-- Computes `s.toHeap ++ res` tail-recursively, assuming `n = s.rank`. -/ go : HeapNode α → Nat → Heap α → Heap α | .nil, _, res => res | .node a c s, n, res => go s (n - 1) (.cons (n - 1) a c res) /-- `O(log n)`. Get the smallest element in the heap, including the passed in value `a`. -/ @[specialize] def Heap.headD (le : α → α → Bool) (a : α) : Heap α → α | .nil => a | .cons _ b _ hs => headD le (if le a b then a else b) hs /-- `O(log n)`. Get the smallest element in the heap, if it has an element. -/ @[inline] def Heap.head? (le : α → α → Bool) : Heap α → Option α | .nil => none | .cons _ h _ hs => some <| headD le h hs /-- The return type of `FindMin`, which encodes various quantities needed to reconstruct the tree in `deleteMin`. -/ structure FindMin (α) where /-- The list of elements prior to the minimum element, encoded as a "difference list". -/ before : Heap α → Heap α := id /-- The minimum element. -/ val : α /-- The children of the minimum element. -/ node : HeapNode α /-- The forest after the minimum element. -/ next : Heap α /-- `O(log n)`. Find the minimum element, and return a data structure `FindMin` with information needed to reconstruct the rest of the binomial heap. -/ @[specialize] def Heap.findMin (le : α → α → Bool) (k : Heap α → Heap α) : Heap α → FindMin α → FindMin α | .nil, res => res | .cons r a c s, res => -- It is important that we check `le res.val a` here, not the other way -- around. This ensures that head? and findMin find the same element even -- when we have `le res.val a` and `le a res.val` (i.e. le is not antisymmetric). findMin le (k ∘ .cons r a c) s <| if le res.val a then res else ⟨k, a, c, s⟩ /-- `O(log n)`. Find and remove the the minimum element from the binomial heap. -/ def Heap.deleteMin (le : α → α → Bool) : Heap α → Option (α × Heap α) | .nil => none | .cons r a c s => let { before, val, node, next } := findMin le (.cons r a c) s ⟨id, a, c, s⟩ some (val, node.toHeap.merge le (before next)) /-- `O(log n)`. Get the tail of the binomial heap after removing the minimum element. -/ @[inline] def Heap.tail? (le : α → α → Bool) (h : Heap α) : Option (Heap α) := deleteMin le h |>.map (·.snd) /-- `O(log n)`. Remove the minimum element of the heap. -/ @[inline] def Heap.tail (le : α → α → Bool) (h : Heap α) : Heap α := tail? le h |>.getD .nil theorem Heap.realSize_merge (le) (s₁ s₂ : Heap α) : (s₁.merge le s₂).realSize = s₁.realSize + s₂.realSize := by unfold merge; split · simp · simp · next r₁ a₁ n₁ t₁ r₂ a₂ n₂ t₂ => have IH₁ r a n := realSize_merge le t₁ (cons r a n t₂) have IH₂ r a n := realSize_merge le (cons r a n t₁) t₂ have IH₃ := realSize_merge le t₁ t₂ split; · simp [IH₁, Nat.add_assoc] split; · simp [IH₂, Nat.add_assoc, Nat.add_left_comm] split; simp only; rename_i a n eq have : n.realSize = n₁.realSize + 1 + n₂.realSize := by rw [combine] at eq; split at eq <;> cases eq <;> simp [Nat.add_assoc, Nat.add_left_comm, Nat.add_comm] split <;> split <;> simp [IH₁, IH₂, IH₃, this, Nat.add_assoc, Nat.add_left_comm] termination_by s₁.length + s₂.length private def FindMin.HasSize (res : FindMin α) (n : Nat) : Prop := ∃ m, (∀ s, (res.before s).realSize = m + s.realSize) ∧ n = m + res.node.realSize + res.next.realSize + 1 private theorem Heap.realSize_findMin {s : Heap α} (m) (hk : ∀ s, (k s).realSize = m + s.realSize) (eq : n = m + s.realSize) (hres : res.HasSize n) : (s.findMin le k res).HasSize n := match s with | .nil => hres | .cons r a c s => by simp [findMin] refine realSize_findMin (m + c.realSize + 1) (by simp [hk, Nat.add_assoc]) (by simp [eq, Nat.add_assoc]) ?_ split · exact hres · exact ⟨m, hk, by simp [eq, Nat.add_comm, Nat.add_left_comm]⟩ theorem HeapNode.realSize_toHeap (s : HeapNode α) : s.toHeap.realSize = s.realSize := go s where go {n res} : ∀ s : HeapNode α, (toHeap.go s n res).realSize = s.realSize + res.realSize | .nil => (Nat.zero_add _).symm | .node a c s => by simp [toHeap.go, go, Nat.add_assoc, Nat.add_left_comm] theorem Heap.realSize_deleteMin {s : Heap α} (eq : s.deleteMin le = some (a, s')) : s.realSize = s'.realSize + 1 := by cases s with cases eq | cons r a c s => ?_ have : (s.findMin le (cons r a c) ⟨id, a, c, s⟩).HasSize (c.realSize + s.realSize + 1) := Heap.realSize_findMin (c.realSize + 1) (by simp) (Nat.add_right_comm ..) ⟨0, by simp⟩ revert this match s.findMin le (cons r a c) ⟨id, a, c, s⟩ with | { before, val, node, next } => intro ⟨m, ih₁, ih₂⟩; dsimp only at ih₁ ih₂ rw [realSize, Nat.add_right_comm, ih₂] simp only [realSize_merge, HeapNode.realSize_toHeap, ih₁, Nat.add_assoc, Nat.add_left_comm] theorem Heap.realSize_tail? {s : Heap α} : s.tail? le = some s' → s.realSize = s'.realSize + 1 := by simp only [Heap.tail?]; intro eq match eq₂ : s.deleteMin le, eq with | some (a, tl), rfl => exact realSize_deleteMin eq₂ theorem Heap.realSize_tail (le) (s : Heap α) : (s.tail le).realSize = s.realSize - 1 := by simp only [Heap.tail] match eq : s.tail? le with | none => cases s with cases eq | nil => rfl | some tl => simp [Heap.realSize_tail? eq] /-- `O(n log n)`. Monadic fold over the elements of a heap in increasing order, by repeatedly pulling the minimum element out of the heap. -/ @[specialize] def Heap.foldM [Monad m] (le : α → α → Bool) (s : Heap α) (init : β) (f : β → α → m β) : m β := match eq : s.deleteMin le with | none => pure init | some (hd, tl) => do have : tl.realSize < s.realSize := by simp +arith [Heap.realSize_deleteMin eq] foldM le tl (← f init hd) f termination_by s.realSize /-- `O(n log n)`. Fold over the elements of a heap in increasing order, by repeatedly pulling the minimum element out of the heap. -/ @[inline] def Heap.fold (le : α → α → Bool) (s : Heap α) (init : β) (f : β → α → β) : β := Id.run <| s.foldM le init f /-- `O(n log n)`. Convert the heap to an array in increasing order. -/ @[inline] def Heap.toArray (le : α → α → Bool) (s : Heap α) : Array α := fold le s #[] Array.push /-- `O(n log n)`. Convert the heap to a list in increasing order. -/ @[inline] def Heap.toList (le : α → α → Bool) (s : Heap α) : List α := (s.toArray le).toList section variable [Monad m] (nil : β) (join : α → β → β → m β) /-- `O(n)`. Fold a monadic function over the tree structure to accumulate a value. -/ @[specialize] def HeapNode.foldTreeM : HeapNode α → m β | .nil => pure nil | .node a c s => do join a (← c.foldTreeM) (← s.foldTreeM) /-- `O(n)`. Fold a monadic function over the tree structure to accumulate a value. -/ @[specialize] def Heap.foldTreeM : Heap α → m β | .nil => pure nil | .cons _ a c s => do join a (← c.foldTreeM nil join) (← s.foldTreeM) end /-- `O(n)`. Fold a function over the tree structure to accumulate a value. -/ @[inline] def Heap.foldTree (nil : β) (join : α → β → β → β) (s : Heap α) : β := Id.run <| s.foldTreeM nil join /-- `O(n)`. Convert the heap to a list in arbitrary order. -/ def Heap.toListUnordered (s : Heap α) : List α := s.foldTree id (fun a c s l => a :: c (s l)) [] /-- `O(n)`. Convert the heap to an array in arbitrary order. -/ def Heap.toArrayUnordered (s : Heap α) : Array α := s.foldTree id (fun a c s r => s (c (r.push a))) #[] /-- The well formedness predicate for a heap node. It asserts that: * If `a` is added at the top to make the forest into a tree, the resulting tree is a `le`-min-heap (if `le` is well-behaved) * When interpreting `child` and `sibling` as left and right children of a binary tree, it is a perfect binary tree with depth `r` -/ def HeapNode.WF (le : α → α → Bool) (a : α) : HeapNode α → Nat → Prop | .nil, r => r = 0 | .node b c s, r => ∃ r', r = r' + 1 ∧ (∀ [TotalBLE le], le a b) ∧ c.WF le b r' ∧ s.WF le a r' /-- The well formedness predicate for a binomial heap. It asserts that: * It consists of a list of well formed trees with the specified ranks * The ranks are in strictly increasing order, and all are at least `n` -/ def Heap.WF (le : α → α → Bool) (n : Nat) : Heap α → Prop | .nil => True | .cons r a c s => n ≤ r ∧ c.WF le a r ∧ s.WF le (r+1) theorem Heap.WF.nil : Heap.nil.WF le n := trivial theorem Heap.WF.singleton : (Heap.singleton a).WF le 0 := ⟨by decide, rfl, ⟨⟩⟩ theorem Heap.WF.of_rankGT (hlt : s.rankGT n) (h : Heap.WF le n' s) : s.WF le (n+1) := match s with | .nil => trivial | .cons .. => let ⟨_, h₂, h₃⟩ := h; ⟨hlt, h₂, h₃⟩ theorem Heap.WF.of_le (hle : n ≤ n') (h : Heap.WF le n' s) : s.WF le n := match s with | .nil => trivial | .cons .. => let ⟨h₁, h₂, h₃⟩ := h; ⟨Nat.le_trans hle h₁, h₂, h₃⟩ theorem Heap.rankGT.of_le (h : Heap.rankGT s n) (h' : n' ≤ n) : s.rankGT n' := match s with | .nil => trivial | .cons .. => Nat.lt_of_le_of_lt h' h theorem Heap.WF.rankGT (h : Heap.WF lt (n+1) s) : s.rankGT n := match s with | .nil => trivial | .cons .. => Nat.lt_of_succ_le h.1 theorem Heap.WF.merge' (h₁ : s₁.WF le n) (h₂ : s₂.WF le n) : (merge le s₁ s₂).WF le n ∧ ((s₁.rankGT n ↔ s₂.rankGT n) → (merge le s₁ s₂).rankGT n) := by unfold merge; split · exact ⟨h₂, fun h => h.1 h₁⟩ · exact ⟨h₁, fun h => h.2 h₂⟩ · rename_i r₁ a₁ n₁ t₁ r₂ a₂ n₂ t₂ let ⟨hr₁, hn₁, ht₁⟩ := h₁ let ⟨hr₂, hn₂, ht₂⟩ := h₂ split <;> rename_i lt₁ · refine ⟨⟨hr₁, hn₁, And.left (merge' ht₁ ⟨lt₁, hn₂, ht₂⟩)⟩, fun h => ?_⟩ exact h.2 <| Nat.lt_of_le_of_lt hr₁ lt₁ split <;> rename_i lt₂ · refine ⟨⟨hr₂, hn₂, And.left (merge' ⟨lt₂, hn₁, ht₁⟩ ht₂)⟩, fun h => ?_⟩ exact h.1 <| Nat.lt_of_le_of_lt hr₂ lt₂ cases Nat.le_antisymm (Nat.ge_of_not_lt lt₂) (Nat.ge_of_not_lt lt₁) split; rename_i a n eq have : n.WF le a (r₁+1) := by unfold combine at eq; split at eq <;> cases eq <;> rename_i h · exact ⟨r₁, rfl, h, hn₂, hn₁⟩ · exact ⟨r₁, rfl, TotalBLE.total.resolve_left h, hn₁, hn₂⟩ simp only; split <;> split <;> rename_i hl₁ hl₂ · exact ⟨⟨Nat.le_succ_of_le hr₁, this, (merge' (ht₁.of_rankGT hl₁) (ht₂.of_rankGT hl₂)).1⟩, fun _ => Nat.lt_succ_of_le hr₁⟩ · let ⟨ih₁, ih₂⟩ := merge' (s₁ := .cons ..) ⟨Nat.le_succ_of_le hr₁, this, ht₁.of_rankGT hl₁⟩ (ht₂.of_le (Nat.le_succ_of_le hr₁)) exact ⟨ih₁, fun _ => ih₂ ⟨fun _ => ht₂.rankGT.of_le hr₁, fun _ => Nat.lt_succ_of_le hr₁⟩⟩ · let ⟨ih₁, ih₂⟩ := merge' (s₂ := .cons ..) (ht₁.of_le (Nat.le_succ_of_le hr₁)) ⟨Nat.le_succ_of_le hr₁, this, ht₂.of_rankGT hl₂⟩ exact ⟨ih₁, fun _ => ih₂ ⟨fun _ => Nat.lt_succ_of_le hr₁, fun _ => ht₁.rankGT.of_le hr₁⟩⟩ · let ⟨ih₁, ih₂⟩ := merge' ht₁ ht₂ exact ⟨⟨Nat.le_succ_of_le hr₁, this, ih₁.of_rankGT (ih₂ (iff_of_false hl₁ hl₂))⟩, fun _ => Nat.lt_succ_of_le hr₁⟩ termination_by s₁.length + s₂.length theorem Heap.WF.merge (h₁ : s₁.WF le n) (h₂ : s₂.WF le n) : (merge le s₁ s₂).WF le n := (merge' h₁ h₂).1 theorem HeapNode.WF.rank_eq : ∀ {n} {s : HeapNode α}, s.WF le a n → s.rank = n | _, .nil, h => h.symm | _, .node .., ⟨_, rfl, _, _, h⟩ => congrArg Nat.succ (rank_eq h) theorem HeapNode.WF.toHeap {s : HeapNode α} (h : s.WF le a n) : s.toHeap.WF le 0 := go h trivial where go {res} : ∀ {n s}, s.WF le a n → res.WF le s.rank → (HeapNode.toHeap.go s s.rank res).WF le 0 | _, .nil, _, hr => hr | _, .node a c s, ⟨n, rfl, _, h, h'⟩, hr => go (s := s) h' ⟨Nat.le_refl _, by rw [← h'.rank_eq] at h; exact h, hr⟩ /-- The well formedness predicate for a `FindMin` value. This is not actually a predicate, as it contains an additional data value `rank` corresponding to the rank of the returned node, which is omitted from `findMin`. -/ structure FindMin.WF (le : α → α → Bool) (res : FindMin α) where /-- The rank of the minimum element -/ rank : Nat /-- `before` is a difference list which can be appended to a binomial heap with ranks at least `rank` to produce another well formed heap. -/ before : ∀ {s}, s.WF le rank → (res.before s).WF le 0 /-- `node` is a well formed forest of rank `rank` with `val` at the root. -/ node : res.node.WF le res.val rank /-- `next` is a binomial heap with ranks above `rank + 1`. -/ next : res.next.WF le (rank + 1) /-- The conditions under which `findMin` is well-formed. -/ def Heap.WF.findMin {s : Heap α} (h : s.WF le n) (hr : res.WF le) (hk : ∀ {s}, s.WF le n → (k s).WF le 0) : ((s : Heap α).findMin le k res).WF le := match s with | .nil => hr | .cons r a c s => by let ⟨h₁, h₂, h₃⟩ := h simp [Heap.findMin] cases le res.val a with | true => exact findMin h₃ hr (fun h => hk ⟨h₁, h₂, h⟩) | false => exact findMin h₃ ⟨_, fun h => hk (h.of_le h₁), h₂, h₃⟩ (fun h => hk ⟨h₁, h₂, h⟩) theorem Heap.WF.deleteMin {s : Heap α} (h : s.WF le n) (eq : s.deleteMin le = some (a, s')) : s'.WF le 0 := by cases s with cases eq | cons r a c s => ?_ have : (s.findMin le (cons r a c) ⟨id, a, c, s⟩).WF le := let ⟨_, h₂, h₃⟩ := h h₃.findMin ⟨_, fun h => h.of_le (Nat.zero_le _), h₂, h₃⟩ fun h => ⟨Nat.zero_le _, h₂, h⟩ revert this let { before, val, node, next } := s.findMin le (cons r a c) ⟨id, a, c, s⟩ intro ⟨_, hk, ih₁, ih₂⟩ exact ih₁.toHeap.merge <| hk (ih₂.of_le (Nat.le_succ _)) theorem Heap.WF.tail? (hwf : (s : Heap α).WF le n) : s.tail? le = some tl → tl.WF le 0 := by simp only [Heap.tail?]; intro eq match eq₂ : s.deleteMin le, eq with | some (a, tl), rfl => exact hwf.deleteMin eq₂ theorem Heap.WF.tail (hwf : (s : Heap α).WF le n) : (s.tail le).WF le 0 := by simp only [Heap.tail] match eq : s.tail? le with | none => exact Heap.WF.nil | some tl => exact hwf.tail? eq end Imp end BinomialHeap open BinomialHeap.Imp /-- A [binomial heap](https://en.wikipedia.org/wiki/Binomial_heap) is a data structure which supports the following primary operations: * `insert : α → BinomialHeap α → BinomialHeap α`: add an element to the heap * `deleteMin : BinomialHeap α → Option (α × BinomialHeap α)`: remove the minimum element from the heap * `merge : BinomialHeap α → BinomialHeap α → BinomialHeap α`: combine two heaps The first two operations are known as a "priority queue", so this could be called a "mergeable priority queue". The standard choice for a priority queue is a binary heap, which supports `insert` and `deleteMin` in `O(log n)`, but `merge` is `O(n)`. With a `BinomialHeap`, all three operations are `O(log n)`. -/ def BinomialHeap (α : Type u) (le : α → α → Bool) := { h : Heap α // h.WF le 0 } /-- `O(1)`. Make a new empty binomial heap. -/ @[inline] def mkBinomialHeap (α : Type u) (le : α → α → Bool) : BinomialHeap α le := ⟨.nil, Heap.WF.nil⟩ namespace BinomialHeap variable {α : Type u} {le : α → α → Bool} /-- `O(1)`. Make a new empty binomial heap. -/ @[inline] def empty : BinomialHeap α le := mkBinomialHeap α le instance : EmptyCollection (BinomialHeap α le) := ⟨.empty⟩ instance : Inhabited (BinomialHeap α le) := ⟨.empty⟩ /-- `O(1)`. Is the heap empty? -/ @[inline] def isEmpty (b : BinomialHeap α le) : Bool := b.1.isEmpty /-- `O(log n)`. The number of elements in the heap. -/ @[inline] def size (b : BinomialHeap α le) : Nat := b.1.size /-- `O(1)`. Make a new heap containing `a`. -/ @[inline] def singleton (a : α) : BinomialHeap α le := ⟨Heap.singleton a, Heap.WF.singleton⟩ /-- `O(log n)`. Merge the contents of two heaps. -/ @[inline] def merge : BinomialHeap α le → BinomialHeap α le → BinomialHeap α le | ⟨b₁, h₁⟩, ⟨b₂, h₂⟩ => ⟨b₁.merge le b₂, h₁.merge h₂⟩ /-- `O(log n)`. Add element `a` to the given heap `h`. -/ @[inline] def insert (a : α) (h : BinomialHeap α le) : BinomialHeap α le := merge (singleton a) h /-- `O(n log n)`. Construct a heap from a list by inserting all the elements. -/ def ofList (le : α → α → Bool) (as : List α) : BinomialHeap α le := as.foldl (flip insert) empty /-- `O(n log n)`. Construct a heap from a list by inserting all the elements. -/ def ofArray (le : α → α → Bool) (as : Array α) : BinomialHeap α le := as.foldl (flip insert) empty /-- `O(log n)`. Remove and return the minimum element from the heap. -/ @[inline] def deleteMin (b : BinomialHeap α le) : Option (α × BinomialHeap α le) := match eq : b.1.deleteMin le with | none => none | some (a, tl) => some (a, ⟨tl, b.2.deleteMin eq⟩) instance : Std.Stream (BinomialHeap α le) α := ⟨deleteMin⟩ /-- `O(n log n)`. Implementation of `for x in (b : BinomialHeap α le) ...` notation, which iterates over the elements in the heap in increasing order. -/ protected def forIn [Monad m] (b : BinomialHeap α le) (x : β) (f : α → β → m (ForInStep β)) : m β := ForInStep.run <$> b.1.foldM le (.yield x) fun x a => x.bind (f a) instance : ForIn m (BinomialHeap α le) α := ⟨BinomialHeap.forIn⟩ /-- `O(log n)`. Returns the smallest element in the heap, or `none` if the heap is empty. -/ @[inline] def head? (b : BinomialHeap α le) : Option α := b.1.head? le /-- `O(log n)`. Returns the smallest element in the heap, or panics if the heap is empty. -/ @[inline] def head! [Inhabited α] (b : BinomialHeap α le) : α := b.head?.get! /-- `O(log n)`. Returns the smallest element in the heap, or `default` if the heap is empty. -/ @[inline] def headI [Inhabited α] (b : BinomialHeap α le) : α := b.head?.getD default /-- `O(log n)`. Removes the smallest element from the heap, or `none` if the heap is empty. -/ @[inline] def tail? (b : BinomialHeap α le) : Option (BinomialHeap α le) := match eq : b.1.tail? le with | none => none | some tl => some ⟨tl, b.2.tail? eq⟩ /-- `O(log n)`. Removes the smallest element from the heap, if possible. -/ @[inline] def tail (b : BinomialHeap α le) : BinomialHeap α le := ⟨b.1.tail le, b.2.tail⟩ /-- `O(n log n)`. Monadic fold over the elements of a heap in increasing order, by repeatedly pulling the minimum element out of the heap. -/ @[inline] def foldM [Monad m] (b : BinomialHeap α le) (init : β) (f : β → α → m β) : m β := b.1.foldM le init f /-- `O(n log n)`. Fold over the elements of a heap in increasing order, by repeatedly pulling the minimum element out of the heap. -/ @[inline] def fold (b : BinomialHeap α le) (init : β) (f : β → α → β) : β := b.1.fold le init f /-- `O(n log n)`. Convert the heap to a list in increasing order. -/ @[inline] def toList (b : BinomialHeap α le) : List α := b.1.toList le /-- `O(n log n)`. Convert the heap to an array in increasing order. -/ @[inline] def toArray (b : BinomialHeap α le) : Array α := b.1.toArray le /-- `O(n)`. Convert the heap to a list in arbitrary order. -/ @[inline] def toListUnordered (b : BinomialHeap α le) : List α := b.1.toListUnordered /-- `O(n)`. Convert the heap to an array in arbitrary order. -/ @[inline] def toArrayUnordered (b : BinomialHeap α le) : Array α := b.1.toArrayUnordered
.lake/packages/batteries/Batteries/Data/DList/Lemmas.lean
module public import Batteries.Data.DList.Basic @[expose] public section /-! # Difference list This file provides a few results about `DList`. A difference list is a function that, given a list, returns the original content of the difference list prepended to the given list. It is useful to represent elements of a given type as `a₁ + ... + aₙ` where `+ : α → α → α` is any operation, without actually computing. This structure supports `O(1)` `append` and `push` operations on lists, making it useful for append-heavy uses such as logging and pretty printing. -/ namespace Batteries.DList open Function theorem toList_ofList (l : List α) : DList.toList (DList.ofList l) = l := by cases l; rfl; simp [ofList] theorem ofList_toList (l : DList α) : DList.ofList (DList.toList l) = l := by obtain ⟨app, inv⟩ := l simp only [ofList, toList, mk.injEq] funext x rw [(inv x)] theorem toList_empty : toList (@empty α) = [] := by simp [empty] theorem toList_singleton (x : α) : toList (singleton x) = [x] := by simp [singleton] theorem toList_append (l₁ l₂ : DList α) : toList (l₁ ++ l₂) = toList l₁ ++ toList l₂ := by simp only [toList, append, Function.comp]; rw [invariant] theorem toList_cons (x : α) (l : DList α) : toList (cons x l) = x :: toList l := by cases l; simp [cons] theorem toList_push (x : α) (l : DList α) : toList (push l x) = toList l ++ [x] := by simp only [toList, push]; rw [invariant] @[simp] theorem singleton_eq_ofThunk {α : Type _} {a : α} : singleton a = ofThunk [a] := rfl @[simp] theorem ofThunk_coe {α : Type _} {l : List α} : ofThunk l = ofList l := rfl end Batteries.DList
.lake/packages/batteries/Batteries/Data/DList/Basic.lean
module @[expose] public section namespace Batteries /-- A difference List is a Function that, given a List, returns the original contents of the difference List prepended to the given List. This structure supports `O(1)` `append` and `push` operations on lists, making it useful for append-heavy uses such as logging and pretty printing. -/ structure DList (α : Type u) where /-- "Run" a `DList` by appending it on the right by a `List α` to get another `List α`. -/ apply : List α → List α /-- The `apply` function of a `DList` is completely determined by the list `apply []`. -/ invariant : ∀ l, apply l = apply [] ++ l attribute [simp] DList.apply namespace DList variable {α : Type u} open List /-- `O(1)` (`apply` is `O(|l|)`). Convert a `List α` into a `DList α`. -/ def ofList (l : List α) : DList α := ⟨(l ++ ·), fun t => by simp⟩ /-- `O(1)` (`apply` is `O(1)`). Return an empty `DList α`. -/ def empty : DList α := ⟨id, fun _ => rfl⟩ instance : EmptyCollection (DList α) := ⟨DList.empty⟩ instance : Inhabited (DList α) := ⟨DList.empty⟩ /-- `O(apply())`. Convert a `DList α` into a `List α` by running the `apply` function. -/ @[simp] def toList : DList α → List α | ⟨f, _⟩ => f [] /-- `O(1)` (`apply` is `O(1)`). A `DList α` corresponding to the list `[a]`. -/ def singleton (a : α) : DList α where apply := fun t => a :: t invariant := fun _ => rfl /-- `O(1)` (`apply` is `O(1)`). Prepend `a` on a `DList α`. -/ def cons : α → DList α → DList α | a, ⟨f, h⟩ => { apply := fun t => a :: f t invariant := by intro t; simp; rw [h] } /-- `O(1)` (`apply` is `O(1)`). Append two `DList α`. -/ def append : DList α → DList α → DList α | ⟨f, h₁⟩, ⟨g, h₂⟩ => { apply := f ∘ g invariant := by intro t show f (g t) = (f (g [])) ++ t rw [h₁ (g t), h₂ t, ← append_assoc (f []) (g []) t, ← h₁ (g [])] } /-- `O(1)` (`apply` is `O(1)`). Append an element at the end of a `DList α`. -/ def push : DList α → α → DList α | ⟨f, h⟩, a => { apply := fun t => f (a :: t) invariant := by intro t show f (a :: t) = f (a :: nil) ++ t rw [h [a], h (a::t), append_assoc (f []) [a] t] rfl } instance : Append (DList α) := ⟨DList.append⟩ /-- Convert a lazily-evaluated `List` to a `DList` -/ def ofThunk (l : Thunk (List α)) : DList α := ⟨fun xs => l.get ++ xs, fun t => by simp⟩ /-- Concatenates a list of difference lists to form a single difference list. Similar to `List.join`. -/ def join {α : Type _} : List (DList α) → DList α | [] => DList.empty | x :: xs => x ++ DList.join xs
.lake/packages/batteries/Batteries/Data/Char/AsciiCasing.lean
module public import Batteries.Data.Char.Basic public import Batteries.Tactic.Basic @[expose] public section /-! # Lemmas for ASCII-casing These facts apply for ASCII characters only. Recall that `isAlpha`, `isLower`, `isUpper`, `toLower`, `toUpper` do not consider characters outside the ASCII character range (code points less than 128). -/ namespace Char theorem not_isLower_of_isUpper {c : Char} : c.isUpper → ¬ c.isLower := by simp only [isUpper, ge_iff_le, UInt32.le_iff_toNat_le, UInt32.reduceToNat, toNat_val, Bool.and_eq_true, decide_eq_true_eq, isLower, not_and, Nat.not_le, and_imp] omega theorem not_isUpper_of_isLower {c : Char} : c.isLower → ¬ c.isUpper := by simp only [isUpper, ge_iff_le, UInt32.le_iff_toNat_le, UInt32.reduceToNat, toNat_val, Bool.and_eq_true, decide_eq_true_eq, isLower, not_and, Nat.not_le, and_imp] omega theorem toLower_eq_of_not_isUpper {c : Char} (h : ¬ c.isUpper) : c.toLower = c := by simp only [isUpper, ge_iff_le, Bool.and_eq_true, decide_eq_true_eq, not_and] at h simp only [toLower, ge_iff_le, ite_eq_right_iff, and_imp] intro h65 h90 absurd h h65 exact h90 theorem toLower_eq_of_isUpper {c : Char} (h : c.isUpper) : c.toLower = ofNat (c.toNat + 32) := by simp only [isUpper, ge_iff_le, Bool.and_eq_true, decide_eq_true_eq] at h simp only [toLower, ge_iff_le, ite_eq_left_iff] intro; contradiction theorem toUpper_eq_of_not_isLower {c : Char} (h : ¬ c.isLower) : c.toUpper = c := by simp only [isLower, ge_iff_le, Bool.and_eq_true, decide_eq_true_eq, not_and] at h simp only [toUpper, ge_iff_le, ite_eq_right_iff, and_imp] intro h97 h122 absurd h h97 exact h122 theorem toUpper_eq_of_isLower {c : Char} (h : c.isLower) : c.toUpper = ofNat (c.toNat - 32) := by simp only [isLower, ge_iff_le, Bool.and_eq_true, decide_eq_true_eq] at h simp only [toUpper, ge_iff_le, ite_eq_left_iff] intro; contradiction @[simp] theorem isUpper_toLower_eq_false (c : Char) : c.toLower.isUpper = false := by simp only [isUpper, toLower, ge_iff_le, UInt32.le_iff_toNat_le, UInt32.reduceToNat, toNat_val, Bool.and_eq_false_imp, decide_eq_true_eq, decide_eq_false_iff_not, Nat.not_le] intro h split at h · next h' => rw [if_pos h'] have : (c.toNat + 32).isValidChar := by omega simp only [toNat_ofNat, ↓reduceIte, gt_iff_lt, *] omega · next h' => rw [if_neg h'] omega @[simp] theorem isLower_toUpper_eq_false (c : Char) : c.toUpper.isLower = false := by simp only [isLower, toUpper, ge_iff_le, UInt32.le_iff_toNat_le, UInt32.reduceToNat, toNat_val, Bool.and_eq_false_imp, decide_eq_true_eq, decide_eq_false_iff_not, Nat.not_le] intro h split at h · next h' => rw [if_pos h'] have : (c.toNat - 32).isValidChar := by omega simp [toNat_ofNat, *] at h ⊢ omega · next h' => rw [if_neg h'] omega @[simp] theorem isLower_toLower_eq_isAlpha (c : Char) : c.toLower.isLower = c.isAlpha := by rw [Bool.eq_iff_iff] by_cases h : c.isUpper · simp only [isLower, h, toLower_eq_of_isUpper, ge_iff_le, UInt32.le_iff_toNat_le, UInt32.reduceToNat, toNat_val, Bool.and_eq_true, decide_eq_true_eq, isAlpha, Bool.true_or, iff_true] simp only [isUpper, ge_iff_le, UInt32.le_iff_toNat_le, UInt32.reduceToNat, toNat_val, Bool.and_eq_true, decide_eq_true_eq] at h have : (c.toNat + 32).isValidChar := by omega simp [toNat_ofNat, *] · simp [toLower_eq_of_not_isUpper, isAlpha, h] @[simp] theorem isUpper_toUpper_eq_isAlpha (c : Char) : c.toUpper.isUpper = c.isAlpha := by rw [Bool.eq_iff_iff] by_cases h : c.isLower · simp only [isUpper, h, toUpper_eq_of_isLower, ge_iff_le, UInt32.le_iff_toNat_le, UInt32.reduceToNat, toNat_val, Bool.and_eq_true, decide_eq_true_eq, isAlpha, Bool.or_true, iff_true] simp only [isLower, ge_iff_le, UInt32.le_iff_toNat_le, UInt32.reduceToNat, toNat_val, Bool.and_eq_true, decide_eq_true_eq] at h have : (c.toNat - 32).isValidChar := by omega have : 32 ≤ c.toNat := by omega simp [toNat_ofNat, Nat.le_sub_iff_add_le, *] · simp [toUpper_eq_of_not_isLower, isAlpha, h] @[simp] theorem isAlpha_toLower_eq_isAlpha (c : Char) : c.toLower.isAlpha = c.isAlpha := by simp [isAlpha] @[simp] theorem isAlpha_toUpper_eq_isAlpha (c : Char) : c.toUpper.isAlpha = c.isAlpha := by simp [isAlpha] @[simp] theorem toLower_toLower_eq_toLower (c : Char) : c.toLower.toLower = c.toLower := by simp [toLower_eq_of_not_isUpper] @[simp] theorem toLower_toUpper_eq_toLower (c : Char) : c.toUpper.toLower = c.toLower := by by_cases hl : c.isLower · have hu : ¬ c.isUpper := not_isUpper_of_isLower hl have hu' : c.toUpper.isUpper := by simp [isAlpha, hl] have hv : (c.toNat - 32).isValidChar := by simp only [isLower, ge_iff_le, UInt32.le_iff_toNat_le, UInt32.reduceToNat, toNat_val, Bool.and_eq_true, decide_eq_true_eq, isUpper, not_and, Nat.not_le] at hl hu omega have h : 32 ≤ c.toNat := by simp only [isLower, ge_iff_le, UInt32.le_iff_toNat_le, UInt32.reduceToNat, toNat_val, Bool.and_eq_true, decide_eq_true_eq, isUpper, not_and, Nat.not_le] at hl hu omega rw [toLower_eq_of_isUpper hu', toUpper_eq_of_isLower hl, toLower_eq_of_not_isUpper hu, toNat_ofNat, if_pos hv, Nat.sub_add_cancel h, ofNat_toNat] · rw [toUpper_eq_of_not_isLower hl] @[simp] theorem toUpper_toUpper_eq_toUpper (c : Char) : c.toUpper.toUpper = c.toUpper := by simp [toUpper_eq_of_not_isLower] @[simp] theorem toUpper_toLower_eq_toUpper (c : Char) : c.toLower.toUpper = c.toUpper := by by_cases hu : c.isUpper · have hl : ¬ c.isLower := not_isLower_of_isUpper hu have hl' : c.toLower.isLower := by simp [isAlpha, hu] have hv : (c.toNat + 32).isValidChar := by simp only [isUpper, ge_iff_le, UInt32.le_iff_toNat_le, UInt32.reduceToNat, toNat_val, Bool.and_eq_true, decide_eq_true_eq, isLower, not_and, Nat.not_le] at hu hl omega rw [toUpper_eq_of_isLower hl', toLower_eq_of_isUpper hu, toUpper_eq_of_not_isLower hl, toNat_ofNat, if_pos hv, Nat.add_sub_cancel, ofNat_toNat] · rw [toLower_eq_of_not_isUpper hu] /-- Case folding for ASCII characters only. Alphabetic ASCII characters are mapped to their lowercase form, all other characters are left unchanged. This agrees with the Unicode case folding algorithm for ASCII characters. ``` #eval caseFoldAsciiOnly 'A' == 'a' #eval caseFoldAsciiOnly 'a' == 'a' #eval caseFoldAsciiOnly 'À' == 'À' #eval caseFoldAsciiOnly 'à' == 'à' #eval caseFoldAsciiOnly '$' == '$' ``` -/ abbrev caseFoldAsciiOnly := Char.toLower /-- Bool-valued comparison of two `Char`s for *ASCII*-case insensitive equality. ``` #eval beqCaseInsensitiveAsciiOnly 'a' 'A' -- true #eval beqCaseInsensitiveAsciiOnly 'a' 'a' -- true #eval beqCaseInsensitiveAsciiOnly '$' '$' -- true #eval beqCaseInsensitiveAsciiOnly 'a' 'b' -- false #eval beqCaseInsensitiveAsciiOnly 'γ' 'Γ' -- false #eval beqCaseInsensitiveAsciiOnly 'ä' 'Ä' -- false ``` -/ def beqCaseInsensitiveAsciiOnly (c₁ c₂ : Char) : Bool := c₁.caseFoldAsciiOnly == c₂.caseFoldAsciiOnly theorem beqCaseInsensitiveAsciiOnly.eqv : Equivalence (beqCaseInsensitiveAsciiOnly · ·) := { refl _ := BEq.rfl trans _ _ := by simp_all [beqCaseInsensitiveAsciiOnly] symm := by simp_all [beqCaseInsensitiveAsciiOnly]} /-- Setoid structure on `Char` using `beqCaseInsensitiveAsciiOnly` -/ def beqCaseInsensitiveAsciiOnly.isSetoid : Setoid Char:= ⟨(beqCaseInsensitiveAsciiOnly · ·), beqCaseInsensitiveAsciiOnly.eqv⟩ /-- ASCII-case insensitive implementation comparison returning an `Ordering`. Useful for sorting. ``` #eval cmpCaseInsensitiveAsciiOnly 'a' 'A' -- eq #eval cmpCaseInsensitiveAsciiOnly 'a' 'a' -- eq #eval cmpCaseInsensitiveAsciiOnly '$' '$' -- eq #eval cmpCaseInsensitiveAsciiOnly 'a' 'b' -- lt #eval cmpCaseInsensitiveAsciiOnly 'γ' 'Γ' -- gt #eval cmpCaseInsensitiveAsciiOnly 'ä' 'Ä' -- gt ``` -/ def cmpCaseInsensitiveAsciiOnly (c₁ c₂ : Char) : Ordering := compare c₁.caseFoldAsciiOnly c₂.caseFoldAsciiOnly
.lake/packages/batteries/Batteries/Data/Char/Basic.lean
module public import Batteries.Classes.Order @[expose] public section -- Forward port of https://github.com/leanprover/lean4/pull/9515 @[simp, grind ←] theorem List.mem_finRange (x : Fin n) : x ∈ finRange n := by simp [finRange] namespace Char theorem le_antisymm_iff {x y : Char} : x = y ↔ x ≤ y ∧ y ≤ x := Char.ext_iff.trans UInt32.le_antisymm_iff instance : Std.LawfulOrd Char := .compareOfLessAndEq_of_irrefl_of_trans_of_not_lt_of_antisymm (fun _ => Nat.lt_irrefl _) Nat.lt_trans Nat.not_lt Char.le_antisymm @[simp] theorem toNat_val (c : Char) : c.val.toNat = c.toNat := rfl @[simp] theorem toNat_ofNatAux {n : Nat} (h : n.isValidChar) : toNat (ofNatAux n h) = n := by simp [ofNatAux, toNat] theorem toNat_ofNat (n : Nat) : toNat (ofNat n) = if n.isValidChar then n else 0 := by split · simp [ofNat, *] · simp [ofNat, toNat, *] /-- Maximum character code point. (See [unicode scalar value](https://www.unicode.org/glossary/#unicode_scalar_value).) -/ protected abbrev max := 0x10FFFF /-- Maximum surrogate code point. (See [unicode scalar value](https://www.unicode.org/glossary/#unicode_scalar_value).) -/ protected abbrev maxSurrogate := 0xDFFF /-- Minimum surrogate code point. (See [unicode scalar value](https://www.unicode.org/glossary/#unicode_scalar_value).) -/ protected abbrev minSurrogate := 0xD800 /-- Number of valid character code points. (See [unicode scalar value](https://www.unicode.org/glossary/#unicode_scalar_value).) -/ protected abbrev count := Char.max - Char.maxSurrogate + Char.minSurrogate @[grind .] theorem toNat_le_max (c : Char) : c.toNat ≤ Char.max := by match c.valid with | .inl h => simp only [toNat_val] at h; grind | .inr ⟨_, h⟩ => simp only [toNat_val] at h; grind @[grind .] theorem toNat_not_surrogate (c : Char) : ¬(Char.minSurrogate ≤ c.toNat ∧ c.toNat ≤ Char.maxSurrogate) := by match c.valid with | .inl h => simp only [toNat_val] at h; grind | .inr ⟨h, _⟩ => simp only [toNat_val] at h; grind /-- Returns `true` if `p` returns true for every `Char`. -/ protected def all (p : Char → Bool) : Bool := Nat.all Char.minSurrogate (fun c h₁ => p <| Char.ofNatAux c <| .inl h₁) && Nat.all (Char.max - Char.maxSurrogate) fun c h₂ => p <| Char.ofNatAux (c + (Char.maxSurrogate + 1)) <| .inr (by grind) private theorem of_all_eq_true_aux (h : Char.all p) (n : Nat) (hn : n.isValidChar) : p (.ofNatAux n hn) := by simp only [Char.all, Nat.all_eq_finRange_all, List.all_eq_true, Bool.and_eq_true] at h match hn with | .inl hn => have := h.1 ⟨n, by grind⟩ grind | .inr ⟨hn, hn'⟩ => have := h.2 ⟨n - (Char.maxSurrogate + 1), by grind⟩ grind theorem eq_true_of_all_eq_true (h : Char.all p) (c : Char) : p c := by have : c.toNat.isValidChar := c.valid rw [← c.ofNat_toNat, ofNat, dif_pos this] exact of_all_eq_true_aux h c.toNat this theorem exists_eq_false_of_all_eq_false (h : Char.all p = false) : ∃ c, p c = false := by simp only [Char.all, Nat.all_eq_finRange_all, List.all_eq_false, Bool.and_eq_false_iff] at h simp only [Bool.eq_false_iff] match h with | .inl ⟨⟨n, hn⟩, _, h⟩ => exact ⟨Char.ofNatAux n (.inl hn), h⟩ | .inr ⟨⟨n, _⟩, _, h⟩ => exact ⟨Char.ofNatAux (n + (Char.maxSurrogate + 1)) (.inr (by grind)), h⟩ theorem all_eq_true_iff_forall_eq_true : Char.all p = true ↔ ∀ c, p c = true := by constructor · exact eq_true_of_all_eq_true · intro h cases heq : Char.all p · obtain ⟨c, hc⟩ := exists_eq_false_of_all_eq_false heq simp [h c] at hc · trivial /-- Returns `true` if `p` returns true for some `Char`. -/ protected def any (p : Char → Bool) : Bool := Nat.any Char.minSurrogate (fun c h₁ => p <| Char.ofNatAux c <| .inl h₁) || Nat.any (Char.max - Char.maxSurrogate) fun c h₂ => p <| Char.ofNatAux (c + Char.maxSurrogate + 1) <| .inr (by grind) theorem exists_eq_true_of_any_eq_true (h : Char.any p = true) : ∃ c, p c = true := by simp only [Char.any, Nat.any_eq_finRange_any, List.any_eq_true, Bool.or_eq_true] at h match h with | .inl ⟨⟨n, hn⟩, _, h⟩ => exact ⟨Char.ofNatAux n (.inl hn), h⟩ | .inr ⟨⟨n, _⟩, _, h⟩ => exact ⟨Char.ofNatAux (n + Char.maxSurrogate + 1) (.inr (by grind)), h⟩ private theorem of_any_eq_false_aux (h : Char.any p = false) (n : Nat) (hn : n.isValidChar) : p (.ofNatAux n hn) = false := by simp only [Char.any, Nat.any_eq_finRange_any, List.any_eq_false, Bool.or_eq_false_iff] at h match hn with | .inl hn => have := h.1 ⟨n, hn⟩ (List.mem_finRange _) grind | .inr ⟨hn, hn'⟩ => have := h.2 ⟨n - (Char.maxSurrogate + 1), by grind⟩ (List.mem_finRange _) grind theorem eq_false_of_any_eq_false (h : Char.any p = false) (c : Char) : p c = false := by have : c.toNat.isValidChar := c.valid rw [← c.ofNat_toNat, ofNat, dif_pos this] exact of_any_eq_false_aux h c.toNat this theorem any_eq_true_iff_exists_eq_true : Char.any p = true ↔ ∃ c, p c = true := by constructor · exact exists_eq_true_of_any_eq_true · intro h cases heq : Char.any p · obtain ⟨c, hc⟩ := h simp [eq_false_of_any_eq_false heq] at hc · trivial instance (P : Char → Prop) [DecidablePred P] : Decidable (∀ c, P c) := match h : Char.all (P ·) with | true => isTrue <| fun c => of_decide_eq_true <| eq_true_of_all_eq_true h c | false => isFalse <| not_forall_of_exists_not <| match exists_eq_false_of_all_eq_false h with | ⟨c, hc⟩ => ⟨c, of_decide_eq_false hc⟩ instance (P : Char → Prop) [DecidablePred P] : Decidable (∃ c, P c) := match h : Char.any (P ·) with | false => isFalse <| not_exists_of_forall_not <| fun c => of_decide_eq_false <| eq_false_of_any_eq_false h c | true => isTrue <| match exists_eq_true_of_any_eq_true h with | ⟨c, hc⟩ => ⟨c, of_decide_eq_true hc⟩
.lake/packages/batteries/Batteries/Data/Fin/Lemmas.lean
module public import Batteries.Data.Fin.Basic public import Batteries.Data.Nat.Lemmas public import Batteries.Util.ProofWanted public import Batteries.Tactic.Alias @[expose] public section namespace Fin attribute [norm_cast] val_last /-! ### rev -/ -- Forward port of lean4#11065 attribute [grind =] rev_lt_rev rev_le_rev rev_rev /-! ### foldl/foldr -/ theorem foldl_assoc {op : α → α → α} [ha : Std.Associative op] {f : Fin n → α} {a₁ a₂} : foldl n (fun x i => op x (f i)) (op a₁ a₂) = op a₁ (foldl n (fun x i => op x (f i)) a₂) := by induction n generalizing a₂ with | zero => simp | succ n ih => simp only [foldl_succ, ha.assoc, ih] theorem foldr_assoc {op : α → α → α} [ha : Std.Associative op] {f : Fin n → α} {a₁ a₂} : foldr n (fun i x => op (f i) x) (op a₁ a₂) = op (foldr n (fun i x => op (f i) x) a₁) a₂ := by simp only [← Fin.foldl_rev] haveI : Std.Associative (flip op) := ⟨fun a b c => (ha.assoc c b a).symm⟩ exact foldl_assoc (op := flip op) /-! ### clamp -/ @[simp] theorem coe_clamp (n m : Nat) : (clamp n m : Nat) = min n m := rfl /-! ### findSome? -/ @[simp] theorem findSome?_zero {f : Fin 0 → Option α} : findSome? f = none := by simp [findSome?] @[simp] theorem findSome?_one {f : Fin 1 → Option α} : findSome? f = f 0 := by simp [findSome?, foldl_succ] theorem findSome?_succ {f : Fin (n+1) → Option α} : findSome? f = (f 0).or (findSome? (f ·.succ)) := by simp only [findSome?, foldl_succ, Option.orElse_eq_orElse, Option.orElse_eq_or] exact Eq.trans (by cases (f 0) <;> rfl) foldl_assoc theorem findSome?_succ_of_some {f : Fin (n+1) → Option α} (h : f 0 = some x) : findSome? f = some x := findSome?_succ.trans (h ▸ Option.some_or) theorem findSome?_succ_of_isSome {f : Fin (n+1) → Option α} (h : (f 0).isSome) : findSome? f = f 0 := findSome?_succ.trans (Option.or_of_isSome h) theorem findSome?_succ_of_none {f : Fin (n+1) → Option α} (h : f 0 = none) : findSome? f = findSome? (f ·.succ) := findSome?_succ.trans (Option.or_eq_right_of_none h) theorem findSome?_succ_of_isNone {f : Fin (n+1) → Option α} (h : (f 0).isNone) : findSome? f = findSome? (f ·.succ) := findSome?_succ.trans (Option.or_of_isNone h) @[simp, grind =] theorem findSome?_eq_some_iff {f : Fin n → Option α} : findSome? f = some a ↔ ∃ i, f i = some a ∧ ∀ j < i, f j = none := by induction n with | zero => simp only [findSome?_zero, reduceCtorEq, forall_fin_zero, and_true, exists_fin_zero] | succ n ih => simp only [findSome?_succ, Option.or_eq_some_iff, exists_fin_succ, forall_fin_succ, succ_lt_succ_iff, succ_pos, not_lt_zero, ih] grind @[simp, grind =] theorem findSome?_eq_none_iff {f : Fin n → Option α} : findSome? f = none ↔ ∀ i, f i = none := by induction n with | zero => simp only [findSome?_zero, forall_fin_zero] | succ n ih => simp only [findSome?_succ, Option.or_eq_none_iff, ih, forall_fin_succ] theorem isNone_findSome?_iff {f : Fin n → Option α} : (findSome? f).isNone ↔ ∀ i, (f i).isNone := by simp @[deprecated (since := "2025-09-28")] alias findSome?_isNone_iff := isNone_findSome?_iff @[simp] theorem isSome_findSome?_iff {f : Fin n → Option α} : (findSome? f).isSome ↔ ∃ i, (f i).isSome := by cases h : findSome? f <;> grind @[deprecated (since := "2025-09-28")] alias findSome?_isSome_iff := isSome_findSome?_iff theorem exists_minimal_of_findSome?_eq_some {f : Fin n → Option α} (h : findSome? f = some x) : ∃ i, f i = some x ∧ ∀ j < i, f j = none := findSome?_eq_some_iff.1 h theorem exists_eq_some_of_findSome?_eq_some {f : Fin n → Option α} (h : findSome? f = some x) : ∃ i, f i = some x := by grind @[deprecated (since := "2025-09-28")] alias exists_of_findSome?_eq_some := exists_eq_some_of_findSome?_eq_some theorem eq_none_of_findSome?_eq_none {f : Fin n → Option α} (h : findSome? f = none) (i) : f i = none := findSome?_eq_none_iff.1 h i theorem exists_isSome_of_isSome_findSome? {f : Fin n → Option α} (h : (findSome? f).isSome) : ∃ i, (f i).isSome := isSome_findSome?_iff.1 h theorem isNone_of_isNone_findSome? {f : Fin n → Option α} (h : (findSome? f).isNone) : (f i).isNone := isNone_findSome?_iff.1 h i theorem isSome_findSome?_of_isSome {f : Fin n → Option α} (h : (f i).isSome) : (findSome? f).isSome := isSome_findSome?_iff.2 ⟨_, h⟩ theorem map_findSome? (f : Fin n → Option α) (g : α → β) : (findSome? f).map g = findSome? (Option.map g <| f ·) := by induction n with | zero => simp | succ n ih => simp [findSome?_succ, Option.map_or, ih] theorem findSome?_guard {p : Fin n → Bool} : findSome? (Option.guard p) = find? p := rfl theorem bind_findSome?_guard_isSome {f : Fin n → Option α} : (findSome? (Option.guard fun i => (f i).isSome)).bind f = findSome? f := by cases hf : findSome? f with | none => grind | some x => simp only [Option.bind_eq_some_iff, findSome?_eq_some_iff, Option.guard_eq_some_iff] grind theorem findSome?_eq_findSome?_finRange (f : Fin n → Option α) : findSome? f = (List.finRange n).findSome? f := by induction n with | zero => simp | succ n ih => rw [findSome?_succ, List.finRange_succ, List.findSome?_cons] cases f 0 <;> simp [ih, List.findSome?_map, Function.comp_def] /-! ### findSomeRev? -/ @[simp] theorem findSome?_rev {f : Fin n → Option α} : findSome? (f ·.rev) = findSomeRev? f := rfl @[simp] theorem findSomeRev?_rev {f : Fin n → Option α} : findSomeRev? (f ·.rev) = findSome? f := by simp only [findSomeRev?, rev_rev] @[simp] theorem findSomeRev?_zero {f : Fin 0 → Option α} : findSomeRev? f = none := by simp [findSomeRev?] @[simp] theorem findSomeRev?_one {f : Fin 1 → Option α} : findSomeRev? f = f 0 := by simp [findSomeRev?] theorem findSomeRev?_succ {f : Fin (n+1) → Option α} : findSomeRev? f = (f (last n)).or (findSomeRev? fun i => f i.castSucc) := by unfold findSomeRev? simp only [findSome?_succ, rev_succ, rev_zero] @[simp, grind =] theorem findSomeRev?_eq_some_iff {f : Fin n → Option α} : findSomeRev? f = some a ↔ ∃ i, f i = some a ∧ ∀ j, i < j → f j = none := findSome?_eq_some_iff.trans <| ⟨fun ⟨i, h⟩ => ⟨i.rev, by grind, fun j hj => have := h.2 j.rev; by grind⟩, fun ⟨i, _⟩ => ⟨i.rev, by grind⟩⟩ @[simp, grind =] theorem findSomeRev?_eq_none_iff {f : Fin n → Option α} : findSomeRev? f = none ↔ ∀ i, f i = none := findSome?_eq_none_iff.trans <| ⟨fun h i => have := h i.rev; by grind, by grind⟩ theorem isNone_findSomeRev?_iff {f : Fin n → Option α} : (findSomeRev? f).isNone ↔ ∀ i, (f i).isNone := by simp @[simp] theorem isSome_findSomeRev?_iff {f : Fin n → Option α} : (findSomeRev? f).isSome ↔ ∃ i, (f i).isSome := by cases h : findSomeRev? f <;> grind theorem exists_minimal_of_findSomeRev?_eq_some {f : Fin n → Option α} (h : findSomeRev? f = some x) : ∃ i, f i = some x ∧ ∀ j, i < j → f j = none := findSomeRev?_eq_some_iff.1 h theorem exists_eq_some_of_findSomeRev?_eq_some {f : Fin n → Option α} (h : findSomeRev? f = some x) : ∃ i, f i = some x := by grind theorem eq_none_of_findSomeRev?_eq_none {f : Fin n → Option α} (h : findSomeRev? f = none) (i) : f i = none := findSomeRev?_eq_none_iff.1 h i theorem exists_isSome_of_isSome_findSomeRev? {f : Fin n → Option α} (h : (findSomeRev? f).isSome) : ∃ i, (f i).isSome := isSome_findSomeRev?_iff.1 h theorem isNone_of_isNone_findSomeRev? {f : Fin n → Option α} (h : (findSomeRev? f).isNone) : (f i).isNone := isNone_findSomeRev?_iff.1 h i theorem isSome_findSomeRev?_of_isSome {f : Fin n → Option α} (h : (f i).isSome) : (findSomeRev? f).isSome := isSome_findSomeRev?_iff.2 ⟨_, h⟩ theorem map_findSomeRev? (f : Fin n → Option α) (g : α → β) : (findSomeRev? f).map g = findSomeRev? (Option.map g <| f ·) := by induction n with | zero => grind [findSomeRev?_zero] | succ n ih => grind [findSomeRev?_succ] @[grind =_] theorem findSomeRev?_guard {p : Fin n → Bool} : findSomeRev? (Option.guard p) = findRev? p := rfl theorem bind_findSomeRev?_guard_isSome {f : Fin n → Option α} : (findSomeRev? (Option.guard fun i => (f i).isSome)).bind f = findSomeRev? f := by cases hf : findSomeRev? f with | none => grind | some x => simp only [Option.bind_eq_some_iff, findSomeRev?_eq_some_iff, Option.guard_eq_some_iff] grind /-! ### find? -/ theorem find?_zero {p : Fin 0 → Bool} : find? p = none := by simp theorem find?_one {p : Fin 1 → Bool} : find? p = if p 0 then some 0 else none := by simp [Option.guard] theorem find?_succ {p : Fin (n+1) → Bool} : find? p = if p 0 then some 0 else (find? (p ·.succ)).map Fin.succ := by simp only [findSome?_succ, Option.guard, fun a => apply_ite (Option.or · a), Option.some_or, Option.none_or, map_findSome?, Option.map_if] @[grind =] theorem find?_eq_some_iff {p : Fin n → Bool} : find? p = some i ↔ p i ∧ ∀ j, j < i → p j = false := by simp [and_assoc] theorem isSome_find?_iff {p : Fin n → Bool} : (find? p).isSome ↔ ∃ i, p i := by simp @[deprecated (since := "2025-09-28")] alias find?_isSome_iff := isSome_find?_iff @[grind =] theorem find?_eq_none_iff {p : Fin n → Bool} : find? p = none ↔ ∀ i, p i = false := by simp theorem isNone_find?_iff {p : Fin n → Bool} : (find? p).isNone ↔ ∀ i, p i = false := by simp @[deprecated (since := "2025-09-28")] alias find?_isNone_iff := isNone_find?_iff theorem eq_true_of_find?_eq_some {p : Fin n → Bool} (h : find? p = some i) : p i := (find?_eq_some_iff.mp h).1 theorem eq_false_of_find?_eq_some_of_lt {p : Fin n → Bool} (h : find? p = some i) : ∀ j < i, p j = false := (find?_eq_some_iff.mp h).2 theorem eq_false_of_find?_eq_none {p : Fin n → Bool} (h : find? p = none) (i) : p i = false := find?_eq_none_iff.1 h i theorem exists_eq_true_of_isSome_find? {p : Fin n → Bool} (h : (find? p).isSome) : ∃ i, p i := isSome_find?_iff.1 h theorem eq_false_of_isNone_find? {p : Fin n → Bool} (h : (find? p).isNone) : p i = false := isNone_find?_iff.1 h i theorem isSome_find?_of_eq_true {p : Fin n → Bool} (h : p i) : (find? p).isSome := isSome_find?_iff.2 ⟨_, h⟩ theorem get_find?_eq_true {p : Fin n → Bool} (h : (find? p).isSome) : p ((find? p).get h) := eq_true_of_find?_eq_some (Option.some_get _).symm theorem get_find?_minimal {p : Fin n → Bool} (h : (find? p).isSome) : ∀ j, j < (find? p).get h → p j = false := eq_false_of_find?_eq_some_of_lt (Option.some_get _).symm theorem bind_find?_isSome {f : Fin n → Option α} : (find? (fun i => (f i).isSome)).bind f = findSome? f := bind_findSome?_guard_isSome theorem find?_eq_find?_finRange {p : Fin n → Bool} : find? p = (List.finRange n).find? p := (findSome?_eq_findSome?_finRange _).trans (List.findSome?_guard) theorem exists_eq_true_iff_exists_minimal_eq_true (p : Fin n → Bool): (∃ i, p i) ↔ ∃ i, p i ∧ ∀ j < i, p j = false := by cases h : find? p <;> grind theorem exists_iff_exists_minimal (p : Fin n → Prop) [DecidablePred p] : (∃ i, p i) ↔ ∃ i, p i ∧ ∀ j < i, ¬ p j := by cases h : find? (p ·) <;> grind theorem find?_rev {p : Fin n → Bool} : find? (p ·.rev) = (findRev? p).map rev := by simp [← findSomeRev?_rev, map_findSomeRev?, Option.guard_eq_ite] theorem map_rev_findRev? {p : Fin n → Bool} : (findRev? (p ·.rev)).map rev = find? p := by simp only [← find?_rev, rev_rev] /-! ### findRev? -/ theorem findRev?_zero {p : Fin 0 → Bool} : findRev? p = none := by grind theorem findRev?_succ {p : Fin (n+1) → Bool} : findRev? p = if p (last n) then some (last n) else (findRev? fun i => p i.castSucc).map Fin.castSucc := by simp only [findSomeRev?_succ, Option.guard, fun a => apply_ite (Option.or · a), Option.some_or, Option.none_or, map_findSomeRev?, Option.map_if] theorem findRev?_one {p : Fin 1 → Bool} : findRev? p = if p 0 then some 0 else none := by grind [findRev?_succ] @[grind =] theorem findRev?_eq_some_iff {p : Fin n → Bool} : findRev? p = some i ↔ p i ∧ ∀ j, i < j → p j = false := by simp [and_assoc] @[grind =] theorem findRev?_eq_none_iff {p : Fin n → Bool} : findRev? p = none ↔ ∀ i, p i = false := by simp theorem isSome_findRev?_iff {p : Fin n → Bool} : (findRev? p).isSome ↔ ∃ i, p i := by simp theorem isNone_findRev?_iff {p : Fin n → Bool} : (findRev? p).isNone ↔ ∀ i, p i = false := by simp theorem eq_true_of_findRev?_eq_some {p : Fin n → Bool} (h : findRev? p = some i) : p i := (findRev?_eq_some_iff.mp h).1 theorem eq_false_of_findRev?_eq_some_of_lt {p : Fin n → Bool} (h : findRev? p = some i) : ∀ j, i < j → p j = false := (findRev?_eq_some_iff.mp h).2 theorem eq_false_of_findRev?_eq_none {p : Fin n → Bool} (h : findRev? p = none) (i) : p i = false := findRev?_eq_none_iff.1 h i theorem exists_eq_true_of_isSome_findRev? {p : Fin n → Bool} (h : (findRev? p).isSome) : ∃ i, p i := isSome_findRev?_iff.1 h theorem eq_false_of_isNone_findRev? {p : Fin n → Bool} (h : (findRev? p).isNone) : p i = false := isNone_findRev?_iff.1 h i theorem isSome_findRev?_of_eq_true {p : Fin n → Bool} (h : p i) : (findRev? p).isSome := isSome_findRev?_iff.2 ⟨_, h⟩ theorem get_findRev?_eq_true {p : Fin n → Bool} (h : (findRev? p).isSome) : p ((findRev? p).get h) := eq_true_of_findRev?_eq_some (Option.some_get _).symm theorem get_findRev?_maximal {p : Fin n → Bool} (h : (findRev? p).isSome) : ∀ j, (findRev? p).get h < j → p j = false := eq_false_of_findRev?_eq_some_of_lt (Option.some_get _).symm theorem exists_eq_true_iff_exists_maximal_eq_true (p : Fin n → Bool): (∃ i, p i) ↔ ∃ i, p i ∧ ∀ j , i < j → p j = false := by cases h : findRev? p <;> grind theorem exists_iff_exists_maximal (p : Fin n → Prop) [DecidablePred p] : (∃ i, p i) ↔ ∃ i, p i ∧ ∀ j, i < j → ¬ p j := by cases h : findRev? (p ·) <;> grind theorem bind_findRev?_isSome {f : Fin n → Option α} : (findRev? (fun i => (f i).isSome)).bind f = findSomeRev? f := bind_findSomeRev?_guard_isSome theorem findRev?_rev {p : Fin n → Bool} : findRev? (p ·.rev) = (find? p).map rev := by simp [← findSome?_rev, map_findSome?, Option.guard_eq_ite] theorem map_rev_find? {p : Fin n → Bool} : (find? (p ·.rev)).map rev = findRev? p := by simp only [← findRev?_rev, rev_rev] theorem find?_le_findRev? {p : Fin n → Bool} : find? p ≤ findRev? p := by cases hl : find? p <;> cases hu : findRev? p <;> grind theorem find?_eq_findRev?_iff {p : Fin n → Bool} : find? p = findRev? p ↔ ∀ i j, p i = true → p j = true → i = j := by cases h : findRev? p <;> grind /-! ### divNat / modNat / mkDivMod -/ @[simp] theorem coe_divNat (i : Fin (m * n)) : (i.divNat : Nat) = i / n := rfl @[simp] theorem coe_modNat (i : Fin (m * n)) : (i.modNat : Nat) = i % n := rfl @[simp] theorem coe_mkDivMod (i : Fin m) (j : Fin n) : (mkDivMod i j : Nat) = n * i + j := rfl @[simp] theorem divNat_mkDivMod (i : Fin m) (j : Fin n) : (mkDivMod i j).divNat = i := by ext; simp [Nat.mul_add_div (Nat.zero_lt_of_lt j.is_lt)] @[simp] theorem modNat_mkDivMod (i : Fin m) (j : Fin n) : (mkDivMod i j).modNat = j := by ext; simp [Nat.mod_eq_of_lt] @[simp] theorem divNat_mkDivMod_modNat (k : Fin (m * n)) : mkDivMod k.divNat k.modNat = k := by ext; simp [Nat.div_add_mod]
.lake/packages/batteries/Batteries/Data/Fin/OfBits.lean
module public import Batteries.Data.Nat.Lemmas @[expose] public section namespace Fin /-- Construct an element of `Fin (2 ^ n)` from a sequence of bits (little endian). -/ abbrev ofBits (f : Fin n → Bool) : Fin (2 ^ n) := ⟨Nat.ofBits f, Nat.ofBits_lt_two_pow f⟩ @[simp] theorem val_ofBits (f : Fin n → Bool) : (ofBits f).val = Nat.ofBits f := rfl
.lake/packages/batteries/Batteries/Data/Fin/Basic.lean
module public import Batteries.Data.Nat.Lemmas @[expose] public section namespace Fin /-- `min n m` as an element of `Fin (m + 1)` -/ def clamp (n m : Nat) : Fin (m + 1) := ⟨min n m, Nat.lt_succ_of_le (Nat.min_le_right ..)⟩ /-- Heterogeneous monadic fold over `Fin n` from right to left: ``` Fin.foldrM n f xₙ = do let xₙ₋₁ : α (n-1) ← f (n-1) xₙ let xₙ₋₂ : α (n-2) ← f (n-2) xₙ₋₁ ... let x₀ : α 0 ← f 0 x₁ pure x₀ ``` This is the dependent version of `Fin.foldrM`. -/ @[inline] def dfoldrM [Monad m] (n : Nat) (α : Fin (n + 1) → Type _) (f : ∀ (i : Fin n), α i.succ → m (α i.castSucc)) (init : α (last n)) : m (α 0) := loop n (Nat.lt_succ_self n) init where /-- Inner loop for `Fin.dfoldrM`. ``` Fin.dfoldrM.loop n f i h xᵢ = do let xᵢ₋₁ ← f (i-1) xᵢ ... let x₁ ← f 1 x₂ let x₀ ← f 0 x₁ pure x₀ ``` -/ @[specialize] loop (i : Nat) (h : i < n + 1) (x : α ⟨i, h⟩) : m (α 0) := match i with | i + 1 => (f ⟨i, Nat.lt_of_succ_lt_succ h⟩ x) >>= loop i (Nat.lt_of_succ_lt h) | 0 => pure x /-- Heterogeneous fold over `Fin n` from the right: `foldr 3 f x = f 0 (f 1 (f 2 x))`, where `f 2 : α 3 → α 2`, `f 1 : α 2 → α 1`, etc. This is the dependent version of `Fin.foldr`. -/ @[inline] def dfoldr (n : Nat) (α : Fin (n + 1) → Type _) (f : ∀ (i : Fin n), α i.succ → α i.castSucc) (init : α (last n)) : α 0 := dfoldrM (m := Id) n α f init /-- Heterogeneous monadic fold over `Fin n` from left to right: ``` Fin.foldlM n f x₀ = do let x₁ : α 1 ← f 0 x₀ let x₂ : α 2 ← f 1 x₁ ... let xₙ : α n ← f (n-1) xₙ₋₁ pure xₙ ``` This is the dependent version of `Fin.foldlM`. -/ @[inline] def dfoldlM [Monad m] (n : Nat) (α : Fin (n + 1) → Type _) (f : ∀ (i : Fin n), α i.castSucc → m (α i.succ)) (init : α 0) : m (α (last n)) := loop 0 (Nat.zero_lt_succ n) init where /-- Inner loop for `Fin.dfoldlM`. ``` Fin.foldM.loop n α f i h xᵢ = do let xᵢ₊₁ : α (i+1) ← f i xᵢ ... let xₙ : α n ← f (n-1) xₙ₋₁ pure xₙ ``` -/ @[specialize] loop (i : Nat) (h : i < n + 1) (x : α ⟨i, h⟩) : m (α (last n)) := if h' : i < n then (f ⟨i, h'⟩ x) >>= loop (i + 1) (Nat.succ_lt_succ h') else haveI : ⟨i, h⟩ = last n := by ext; simp; omega _root_.cast (congrArg (fun i => m (α i)) this) (pure x) /-- Heterogeneous fold over `Fin n` from the left: `foldl 3 f x = f 0 (f 1 (f 2 x))`, where `f 0 : α 0 → α 1`, `f 1 : α 1 → α 2`, etc. This is the dependent version of `Fin.foldl`. -/ @[inline] def dfoldl (n : Nat) (α : Fin (n + 1) → Type _) (f : ∀ (i : Fin n), α i.castSucc → α i.succ) (init : α 0) : α (last n) := dfoldlM (m := Id) n α f init /-- `findSome? f` returns `f i` for the first `i` for which `f i` is `some _`, or `none` if no such element is found. The function `f` is not evaluated on further inputs after the first `i` is found. -/ @[inline] def findSome? (f : Fin n → Option α) : Option α := foldl n (fun r i => r <|> f i) none /-- `findSomeRev? f` returns `f i` for the last `i` for which `f i` is `some _`, or `none` if no such element is found. The function `f` is not evaluated on further inputs after the first `i` is found. -/ @[inline] def findSomeRev? (f : Fin n → Option α) : Option α := findSome? (f ·.rev) /-- `find? p` returns the first `i` for which `p i = true`, or `none` if no such element is found. The function `p` is not evaluated on further inputs after the first `i` is found. -/ @[inline] abbrev find? (p : Fin n → Bool) : Option (Fin n) := findSome? <| Option.guard p /-- `find? p` returns the first `i` for which `p i = true`, or `none` if no such element is found. The function `p` is not evaluated on further inputs after the first `i` is found. -/ @[inline] abbrev findRev? (p : Fin n → Bool) : Option (Fin n) := findSomeRev? <| Option.guard p /-- Compute `i / n`, where `n` is a `Nat` and inferred the type of `i`. -/ def divNat (i : Fin (m * n)) : Fin m := ⟨i / n, Nat.div_lt_of_lt_mul <| Nat.mul_comm m n ▸ i.is_lt⟩ /-- Compute `i % n`, where `n` is a `Nat` and inferred the type of `i`. -/ def modNat (i : Fin (m * n)) : Fin n := ⟨i % n, Nat.mod_lt _ <| Nat.pos_of_mul_pos_left i.pos⟩ /-- Compute the element of `Fin (m * n)` with quotient `i : Fin m` and remainder `j : Fin n` when divided by `n`. -/ def mkDivMod (i : Fin m) (j : Fin n) : Fin (m * n) := ⟨n * i + j, Nat.mul_add_lt_mul_of_lt_of_lt i.is_lt j.is_lt⟩
.lake/packages/batteries/Batteries/Data/Fin/Fold.lean
module public import Batteries.Tactic.Alias public import Batteries.Data.Fin.Basic @[expose] public section namespace Fin /-! ### dfoldrM -/ theorem dfoldrM_loop_zero [Monad m] (f : (i : Fin n) → α i.succ → m (α i.castSucc)) (x) : dfoldrM.loop n α f 0 h x = pure x := rfl theorem dfoldrM_loop_succ [Monad m] (f : (i : Fin n) → α i.succ → m (α i.castSucc)) (x) : dfoldrM.loop n α f (i+1) h x = f ⟨i, by omega⟩ x >>= dfoldrM.loop n α f i (by omega) := rfl theorem dfoldrM_loop [Monad m] [LawfulMonad m] (f : (i : Fin (n+1)) → α i.succ → m (α i.castSucc)) (x) : dfoldrM.loop (n+1) α f (i+1) h x = dfoldrM.loop n (α ∘ succ) (f ·.succ) i (by omega) x >>= f 0 := by induction i with | zero => rw [dfoldrM_loop_zero, dfoldrM_loop_succ, pure_bind] conv => rhs; rw [← bind_pure (f 0 x)] rfl | succ i ih => rw [dfoldrM_loop_succ, dfoldrM_loop_succ, bind_assoc] congr; funext; exact ih .. @[simp] theorem dfoldrM_zero [Monad m] (f : (i : Fin 0) → α i.succ → m (α i.castSucc)) (x) : dfoldrM 0 α f x = pure x := rfl theorem dfoldrM_succ [Monad m] [LawfulMonad m] (f : (i : Fin (n+1)) → α i.succ → m (α i.castSucc)) (x) : dfoldrM (n+1) α f x = dfoldrM n (α ∘ succ) (f ·.succ) x >>= f 0 := dfoldrM_loop .. theorem dfoldrM_eq_foldrM [Monad m] [LawfulMonad m] (f : (i : Fin n) → α → m α) (x) : dfoldrM n (fun _ => α) f x = foldrM n f x := by induction n with | zero => simp only [dfoldrM_zero, foldrM_zero] | succ n ih => simp only [dfoldrM_succ, foldrM_succ, Function.comp_def, ih] theorem dfoldr_eq_dfoldrM (f : (i : Fin n) → α i.succ → α i.castSucc) (x) : dfoldr n α f x = dfoldrM (m:=Id) n α f x := rfl /-! ### dfoldr -/ @[simp] theorem dfoldr_zero (f : (i : Fin 0) → α i.succ → α i.castSucc) (x) : dfoldr 0 α f x = x := rfl theorem dfoldr_succ (f : (i : Fin (n+1)) → α i.succ → α i.castSucc) (x) : dfoldr (n+1) α f x = f 0 (dfoldr n (α ∘ succ) (f ·.succ) x) := dfoldrM_succ .. theorem dfoldr_succ_last {n : Nat} {α : Fin (n+2) → Sort _} (f : (i : Fin (n+1)) → α i.succ → α i.castSucc) (x : α (last (n+1))) : dfoldr (n+1) α f x = dfoldr n (α ∘ castSucc) (f ·.castSucc) (f (last n) x) := by induction n with | zero => simp only [dfoldr_succ, dfoldr_zero, last, zero_eta] | succ n ih => rw [dfoldr_succ, ih (α := α ∘ succ) (f ·.succ), dfoldr_succ]; congr theorem dfoldr_eq_foldr (f : (i : Fin n) → α → α) (x) : dfoldr n (fun _ => α) f x = foldr n f x := by induction n with | zero => simp only [dfoldr_zero, foldr_zero] | succ n ih => simp only [dfoldr_succ, foldr_succ, Function.comp_def, ih] /-! ### dfoldlM -/ theorem dfoldlM_loop_lt [Monad m] (f : ∀ (i : Fin n), α i.castSucc → m (α i.succ)) (h : i < n) (x) : dfoldlM.loop n α f i (Nat.lt_add_right 1 h) x = (f ⟨i, h⟩ x) >>= (dfoldlM.loop n α f (i+1) (Nat.add_lt_add_right h 1)) := by rw [dfoldlM.loop, dif_pos h] theorem dfoldlM_loop_eq [Monad m] (f : ∀ (i : Fin n), α i.castSucc → m (α i.succ)) (x) : dfoldlM.loop n α f n (Nat.le_refl _) x = pure x := by rw [dfoldlM.loop, dif_neg (Nat.lt_irrefl _), cast_eq] @[simp] theorem dfoldlM_zero [Monad m] (f : (i : Fin 0) → α i.castSucc → m (α i.succ)) (x) : dfoldlM 0 α f x = pure x := by simp [dfoldlM, dfoldlM.loop] theorem dfoldlM_loop [Monad m] (f : (i : Fin (n+1)) → α i.castSucc → m (α i.succ)) (h : i < n+1) (x) : dfoldlM.loop (n+1) α f i (Nat.lt_add_right 1 h) x = f ⟨i, h⟩ x >>= (dfoldlM.loop n (α ∘ succ) (f ·.succ ·) i h .) := by if h' : i < n then rw [dfoldlM_loop_lt _ h _] congr; funext rw [dfoldlM_loop_lt _ h' _, dfoldlM_loop]; rfl else cases Nat.le_antisymm (Nat.le_of_lt_succ h) (Nat.not_lt.1 h') rw [dfoldlM_loop_lt _ h] congr; funext rw [dfoldlM_loop_eq, dfoldlM_loop_eq] theorem dfoldlM_succ [Monad m] (f : (i : Fin (n+1)) → α i.castSucc → m (α i.succ)) (x) : dfoldlM (n+1) α f x = f 0 x >>= (dfoldlM n (α ∘ succ) (f ·.succ ·) .) := dfoldlM_loop .. theorem dfoldlM_eq_foldlM [Monad m] (f : (i : Fin n) → α → m α) (x : α) : dfoldlM n (fun _ => α) f x = foldlM n (fun x i => f i x) x := by induction n generalizing x with | zero => simp only [dfoldlM_zero, foldlM_zero] | succ n ih => simp only [dfoldlM_succ, foldlM_succ, Function.comp_apply, Function.comp_def] congr; ext; simp only [ih] /-! ### dfoldl -/ @[simp] theorem dfoldl_zero (f : (i : Fin 0) → α i.castSucc → α i.succ) (x) : dfoldl 0 α f x = x := by simp [dfoldl, pure] theorem dfoldl_succ (f : (i : Fin (n+1)) → α i.castSucc → α i.succ) (x) : dfoldl (n+1) α f x = dfoldl n (α ∘ succ) (f ·.succ ·) (f 0 x) := dfoldlM_succ .. theorem dfoldl_succ_last (f : (i : Fin (n+1)) → α i.castSucc → α i.succ) (x) : dfoldl (n+1) α f x = f (last n) (dfoldl n (α ∘ castSucc) (f ·.castSucc ·) x) := by rw [dfoldl_succ] induction n with | zero => simp [last] | succ n ih => rw [dfoldl_succ, @ih (α ∘ succ) (f ·.succ ·), dfoldl_succ]; congr theorem dfoldl_eq_dfoldlM (f : (i : Fin n) → α i.castSucc → α i.succ) (x) : dfoldl n α f x = dfoldlM (m := Id) n α f x := rfl theorem dfoldl_eq_foldl (f : Fin n → α → α) (x : α) : dfoldl n (fun _ => α) f x = foldl n (fun x i => f i x) x := by induction n generalizing x with | zero => simp only [dfoldl_zero, foldl_zero] | succ n ih => simp only [dfoldl_succ, foldl_succ, Function.comp_apply, Function.comp_def] congr; simp only [ih] /-! ### `Fin.fold{l/r}{M}` equals `List.fold{l/r}{M}` -/ theorem foldl_eq_foldl_finRange (f : α → Fin n → α) (x) : foldl n f x = (List.finRange n).foldl f x := by induction n generalizing x with | zero => rw [foldl_zero, List.finRange_zero, List.foldl_nil] | succ n ih => rw [foldl_succ, ih, List.finRange_succ, List.foldl_cons, List.foldl_map] theorem foldr_eq_foldr_finRange (f : Fin n → α → α) (x) : foldr n f x = (List.finRange n).foldr f x := by induction n with | zero => rw [foldr_zero, List.finRange_zero, List.foldr_nil] | succ n ih => rw [foldr_succ, ih, List.finRange_succ, List.foldr_cons, List.foldr_map]
.lake/packages/batteries/Batteries/Data/MLList/IO.lean
module public import Batteries.Lean.System.IO public import Batteries.Data.MLList.Basic @[expose] public section /-! # IO operations using monadic lazy lists. -/ namespace MLList /-- Give a list of tasks, return the monadic lazy list which returns the values as they become available. -/ def ofTaskList (tasks : List (Task α)) : MLList BaseIO α := fix?' (init := tasks) fun t => do if h : 0 < t.length then some <$> IO.waitAny' t h else pure none
.lake/packages/batteries/Batteries/Data/MLList/Basic.lean
module public import Batteries.Control.AlternativeMonad public section /-! # Monadic lazy lists. Lazy lists with "laziness" controlled by an arbitrary monad. -/ /-! In an initial section we describe the specification of `MLList`, and provide a private unsafe implementation, and then a public `opaque` wrapper of this implementation, satisfying the specification. -/ namespace MLList private structure Spec (m : Type u → Type u) where listM : Type u → Type u nil : listM α cons : α → listM α → listM α thunk : (Unit → listM α) → listM α squash : (Unit → m (listM α)) → listM α uncons : [Monad m] → listM α → m (Option (α × listM α)) uncons? : listM α → Option (Option (α × listM α)) private instance : Nonempty (Spec m) := .intro { listM := fun _ => PUnit nil := ⟨⟩ cons := fun _ _ => ⟨⟩ thunk := fun _ => ⟨⟩ squash := fun _ => ⟨⟩ uncons := fun _ => pure none uncons? := fun _ => none } private unsafe inductive MLListImpl (m : Type u → Type u) (α : Type u) : Type u | nil : MLListImpl m α | cons : α → MLListImpl m α → MLListImpl m α | thunk : Thunk (MLListImpl m α) → MLListImpl m α | squash : (Unit → m (MLListImpl m α)) → MLListImpl m α private unsafe def unconsImpl {m : Type u → Type u} [Monad m] : MLListImpl m α → m (Option (α × MLListImpl m α)) | .nil => pure none | .thunk t => unconsImpl t.get | .squash t => t () >>= unconsImpl | .cons x xs => return (x, xs) private unsafe def uncons?Impl : MLListImpl m α → Option (Option (α × MLListImpl m α)) | .nil => pure none | .cons x xs => pure (x, xs) | _ => none @[inline] private unsafe def specImpl (m) : Spec m where listM := MLListImpl m nil := .nil cons := .cons thunk f := .thunk (.mk f) squash := .squash uncons := unconsImpl uncons? := uncons?Impl @[implemented_by specImpl] private opaque spec (m) : MLList.Spec m end MLList /-- A monadic lazy list, controlled by an arbitrary monad. -/ def MLList (m : Type u → Type u) (α : Type u) : Type u := (MLList.spec m).listM α namespace MLList /-- The empty `MLList`. -/ @[inline] def nil : MLList m α := (MLList.spec m).nil /-- Constructs a `MLList` from head and tail. -/ @[inline] def cons : α → MLList m α → MLList m α := (MLList.spec m).cons /-- Embed a non-monadic thunk as a lazy list. -/ @[inline] def thunk : (Unit → MLList m α) → MLList m α := (MLList.spec m).thunk /-- Lift a monadic lazy list inside the monad to a monadic lazy list. -/ def squash : (Unit → m (MLList m α)) → MLList m α := (MLList.spec m).squash /-- Deconstruct a `MLList`, returning inside the monad an optional pair `α × MLList m α` representing the head and tail of the list. -/ @[inline] def uncons [Monad m] : MLList.{u} m α → m (Option (α × MLList m α)) := (MLList.spec m).uncons /-- Try to deconstruct a `MLList`, returning an optional pair `α × MLList m α` representing the head and tail of the list if it is already evaluated, and `none` otherwise. -/ @[inline] def uncons? : MLList.{u} m α → Option (Option (α × MLList m α)) := (MLList.spec m).uncons? instance : EmptyCollection (MLList m α) := ⟨nil⟩ instance : Inhabited (MLList m α) := ⟨nil⟩ private local instance [Monad n] : Inhabited (δ → (α → δ → n (ForInStep δ)) → n δ) where default d _ := pure d in /-- The implementation of `ForIn`, which enables `for a in L do ...` notation. -/ @[specialize] protected partial def forIn [Monad m] [Monad n] [MonadLiftT m n] (as : MLList m α) (init : δ) (f : α → δ → n (ForInStep δ)) : n δ := do match ← as.uncons with | none => pure init | some (a, t) => match (← f a init) with | ForInStep.done d => pure d | ForInStep.yield d => t.forIn d f instance [Monad m] [MonadLiftT m n] : ForIn n (MLList m α) α where forIn := MLList.forIn /-- Construct a singleton monadic lazy list from a single monadic value. -/ def singletonM [Monad m] (x : m α) : MLList m α := .squash fun _ => do return .cons (← x) .nil /-- Construct a singleton monadic lazy list from a single value. -/ def singleton [Monad m] (x : α) : MLList m α := .singletonM (pure x) /-- Construct a `MLList` recursively. Failures from `f` will result in `uncons` failing. -/ partial def fix [Monad m] (f : α → m α) (x : α) : MLList m α := cons x <| squash fun _ => fix f <$> f x /-- Constructs an `MLList` recursively, with state in `α`, recording terms from `β`. If `f` returns `none` the list will terminate. Variant of `MLList.fix?` that allows returning values of a different type. -/ partial def fix?' [Monad m] (f : α → m (Option (β × α))) (init : α) : MLList m β := squash fun _ => do match ← f init with | none => pure .nil | some (b, a) => pure (.cons b (fix?' f a)) /-- Constructs an `MLList` recursively. If `f` returns `none` the list will terminate. Returns the initial value as the first element. -/ partial def fix? [Monad m] (f : α → m (Option α)) (x : α) : MLList m α := cons x <| squash fun _ => do match ← f x with | none => return nil | some x' => return fix? f x' /-- Construct a `MLList` by iteration. (`m` must be a stateful monad for this to be useful.) -/ partial def iterate [Monad m] (f : m α) : MLList m α := squash fun _ => return cons (← f) (iterate f) /-- Repeatedly apply a function `f : α → m (α × List β)` to an initial `a : α`, accumulating the elements of the resulting `List β` as a single monadic lazy list. (This variant allows starting with a specified `List β` of elements, as well. )-/ partial def fixlWith [Monad m] {α β : Type u} (f : α → m (α × List β)) (s : α) (l : List β) : MLList m β := thunk fun _ => match l with | b :: rest => cons b (fixlWith f s rest) | [] => squash fun _ => do let (s', l) ← f s match l with | b :: rest => pure <| cons b (fixlWith f s' rest) | [] => pure <| fixlWith f s' [] /-- Repeatedly apply a function `f : α → m (α × List β)` to an initial `a : α`, accumulating the elements of the resulting `List β` as a single monadic lazy list. -/ def fixl [Monad m] {α β : Type u} (f : α → m (α × List β)) (s : α) : MLList m β := fixlWith f s [] /-- Compute, inside the monad, whether a `MLList` is empty. -/ def isEmpty [Monad m] (xs : MLList m α) : m (ULift Bool) := (ULift.up ∘ Option.isNone) <$> uncons xs /-- Convert a `List` to a `MLList`. -/ def ofList : List α → MLList m α | [] => nil | h :: t => cons h (thunk fun _ => ofList t) /-- Convert a `List` of values inside the monad into a `MLList`. -/ def ofListM [Monad m] : List (m α) → MLList m α | [] => nil | h :: t => squash fun _ => return cons (← h) (ofListM t) /-- Extract a list inside the monad from a `MLList`. -/ partial def force [Monad m] (L : MLList m α) : m (List α) := do match ← L.uncons with | none => pure [] | some (x, xs) => return x :: (← xs.force) /-- Extract an array inside the monad from a `MLList`. -/ def asArray [Monad m] (L : MLList m α) : m (Array α) := do let mut r := #[] for a in L do r := r.push a return r /-- Performs a monadic case distinction on a `MLList` when the motive is a `MLList` as well. -/ @[specialize] def casesM [Monad m] (xs : MLList m α) (hnil : Unit → m (MLList m β)) (hcons : α → MLList m α → m (MLList m β)) : MLList m β := squash fun _ => do match ← xs.uncons with | none => hnil () | some (x, xs) => hcons x xs /-- Performs a case distinction on a `MLList` when the motive is a `MLList` as well. (We need to be in a monadic context to distinguish a nil from a cons.) -/ @[specialize] def cases [Monad m] (xs : MLList m α) (hnil : Unit → MLList m β) (hcons : α → MLList m α → MLList m β) : MLList m β := match xs.uncons? with | none => xs.casesM (fun _ => return hnil ()) (fun x xs => return hcons x xs) | some none => thunk hnil | some (some (x, xs)) => thunk fun _ => hcons x xs /-- Gives the monadic lazy list consisting all of folds of a function on a given initial element. Thus `[a₀, a₁, ...].foldsM f b` will give `[b, ← f b a₀, ← f (← f b a₀) a₁, ...]`. -/ partial def foldsM [Monad m] (f : β → α → m β) (init : β) (L : MLList m α) : MLList m β := cons init <| squash fun _ => do match ← L.uncons with | none => return nil | some (x, xs) => return foldsM f (← f init x) xs /-- Gives the monadic lazy list consisting all of folds of a function on a given initial element. Thus `[a₀, a₁, ...].foldsM f b` will give `[b, f b a₀, f (f b a₀) a₁, ...]`. -/ def folds [Monad m] (f : β → α → β) (init : β) (L : MLList m α) : MLList m β := L.foldsM (fun b a => pure (f b a)) init /-- Take the first `n` elements, as a list inside the monad. -/ partial def takeAsList [Monad m] (xs : MLList m α) (n : Nat) : m (List α) := go n [] xs where /-- Implementation of `MLList.takeAsList`. -/ go (r : Nat) (acc : List α) (xs : MLList m α) : m (List α) := match r with | 0 => pure acc.reverse | r+1 => do match ← xs.uncons with | none => pure acc.reverse | some (x, xs) => go r (x :: acc) xs /-- Take the first `n` elements, as an array inside the monad. -/ partial def takeAsArray [Monad m] (xs : MLList m α) (n : Nat) : m (Array α) := go n #[] xs where /-- Implementation of `MLList.takeAsArray`. -/ go (r : Nat) (acc : Array α) (xs : MLList m α) : m (Array α) := match r with | 0 => pure acc | r+1 => do match ← xs.uncons with | none => pure acc | some (x, xs) => go r (acc.push x) xs /-- Take the first `n` elements. -/ partial def take [Monad m] (xs : MLList m α) : Nat → MLList m α | 0 => nil | n+1 => xs.cases (fun _ => nil) fun h l => cons h (l.take n) /-- Drop the first `n` elements. -/ def drop [Monad m] (xs : MLList m α) : Nat → MLList m α | 0 => xs | n+1 => xs.cases (fun _ => nil) fun _ l => l.drop n /-- Apply a function which returns values in the monad to every element of a `MLList`. -/ partial def mapM [Monad m] (f : α → m β) (xs : MLList m α) : MLList m β := xs.cases (fun _ => nil) fun x xs => squash fun _ => return cons (← f x) (xs.mapM f) /-- Apply a function to every element of a `MLList`. -/ def map [Monad m] (f : α → β) (L : MLList m α) : MLList m β := L.mapM fun a => pure (f a) /-- Filter a `MLList` using a monadic function. -/ partial def filterM [Monad m] (p : α → m (ULift Bool)) (L : MLList m α) : MLList m α := L.casesM (fun _ => pure nil) fun x xs => return if (← p x).down then cons x (filterM p xs) else filterM p xs /-- Filter a `MLList`. -/ def filter [Monad m] (p : α → Bool) (L : MLList m α) : MLList m α := L.filterM fun a => pure <| .up (p a) /-- Filter and transform a `MLList` using a function that returns values inside the monad. -/ -- Note that the type signature has changed since Lean 3, when we allowed `f` to fail. -- Use `try?` from `Mathlib.Control.Basic` to lift a possibly failing function to `Option`. partial def filterMapM [Monad m] (f : α → m (Option β)) (xs : MLList m α) : MLList m β := xs.casesM (fun _ => pure nil) fun x xs => do match ← f x with | none => return xs.filterMapM f | some a => return cons a (xs.filterMapM f) /-- Filter and transform a `MLList` using an `Option` valued function. -/ def filterMap [Monad m] (f : α → Option β) : MLList m α → MLList m β := filterMapM fun a => do pure (f a) /-- Take the initial segment of the lazy list, until the function `f` first returns `false`. -/ partial def takeWhileM [Monad m] (f : α → m (ULift Bool)) (L : MLList m α) : MLList m α := L.casesM (fun _ => pure nil) fun x xs => return if !(← f x).down then nil else cons x (xs.takeWhileM f) /-- Take the initial segment of the lazy list, until the function `f` first returns `false`. -/ def takeWhile [Monad m] (f : α → Bool) : MLList m α → MLList m α := takeWhileM fun a => pure (.up (f a)) /-- Concatenate two monadic lazy lists. -/ partial def append [Monad m] (xs : MLList m α) (ys : Unit → MLList m α) : MLList m α := xs.cases ys fun x xs => cons x (append xs ys) /-- Join a monadic lazy list of monadic lazy lists into a single monadic lazy list. -/ partial def join [Monad m] (xs : MLList m (MLList m α)) : MLList m α := xs.cases (fun _ => nil) fun x xs => append x (fun _ => join xs) /-- Enumerate the elements of a monadic lazy list, starting at a specified offset. -/ partial def enumFrom [Monad m] (n : Nat) (xs : MLList m α) : MLList m (Nat × α) := xs.cases (fun _ => nil) fun x xs => cons (n, x) (xs.enumFrom (n+1)) /-- Enumerate the elements of a monadic lazy list. -/ def enum [Monad m] : MLList m α → MLList m (Nat × α) := enumFrom 0 /-- The infinite monadic lazy list of natural numbers.-/ def range [Monad m] : MLList m Nat := MLList.fix (fun n => pure (n + 1)) 0 /-- Iterate through the elements of `Fin n`. -/ partial def fin (n : Nat) : MLList m (Fin n) := go 0 where /-- Implementation of `MLList.fin`. -/ go (i : Nat) : MLList m (Fin n) := if h : i < n then cons ⟨i, h⟩ (thunk fun _ => go (i+1)) else nil /-- Convert an array to a monadic lazy list. -/ partial def ofArray {α : Type} (L : Array α) : MLList m α := go 0 where /-- Implementation of `MLList.ofArray`. -/ go (i : Nat) : MLList m α := if h : i < L.size then cons L[i] (thunk fun _ => go (i+1)) else nil /-- Group the elements of a lazy list into chunks of a given size. If the lazy list is finite, the last chunk may be smaller (possibly even length 0). -/ partial def chunk [Monad m] (L : MLList m α) (n : Nat) : MLList m (Array α) := go n #[] L where /-- Implementation of `MLList.chunk`. -/ go (r : Nat) (acc : Array α) (M : MLList m α) : MLList m (Array α) := match r with | 0 => cons acc (thunk fun _ => go n #[] M) | r+1 => squash fun _ => do match ← M.uncons with | none => return cons acc nil | some (a, M') => return go r (acc.push a) M' /-- Add one element to the end of a monadic lazy list. -/ def concat [Monad m] (L : MLList m α) (a : α) : MLList m α := L.append (fun _ => cons a nil) /-- Take the product of two monadic lazy lists. -/ partial def zip [Monad m] (L : MLList m α) (M : MLList m β) : MLList.{u} m (α × β) := L.cases (fun _ => nil) fun a L => M.cases (fun _ => nil) fun b M => cons (a, b) (L.zip M) /-- Apply a function returning a monadic lazy list to each element of a monadic lazy list, joining the results. -/ partial def bind [Monad m] (xs : MLList m α) (f : α → MLList m β) : MLList m β := xs.cases (fun _ => nil) fun x xs => match xs.uncons? with | some none => f x | _ => append (f x) (fun _ => bind xs f) /-- Convert any value in the monad to the singleton monadic lazy list. -/ def monadLift [Monad m] (x : m α) : MLList m α := squash fun _ => return cons (← x) nil /-- Lift the monad of a lazy list. -/ partial def liftM [Monad m] [Monad n] [MonadLiftT m n] (L : MLList m α) : MLList n α := squash fun _ => return match ← (uncons L : m _) with | none => nil | some (a, L') => cons a L'.liftM /-- Given a lazy list in a state monad, run it on some initial state, recording the states. -/ partial def runState [Monad m] (L : MLList (StateT.{u} σ m) α) (s : σ) : MLList m (α × σ) := squash fun _ => return match ← (uncons L).run s with | (none, _) => nil | (some (a, L'), s') => cons (a, s') (L'.runState s') /-- Given a lazy list in a state monad, run it on some initial state. -/ def runState' [Monad m] (L : MLList (StateT.{u} σ m) α) (s : σ) : MLList m α := L.runState s |>.map (·.1) /-- Run a lazy list in a `ReaderT` monad on some fixed state. -/ partial def runReader [Monad m] (L : MLList (ReaderT.{u, u} ρ m) α) (r : ρ) : MLList m α := squash fun _ => return match ← (uncons L).run r with | none => nil | some (a, L') => cons a (L'.runReader r) /-- Run a lazy list in a `StateRefT'` monad on some initial state. -/ partial def runStateRef [Monad m] [MonadLiftT (ST ω) m] (L : MLList (StateRefT' ω σ m) α) (s : σ) : MLList m α := squash fun _ => return match ← (uncons L).run s with | (none, _) => nil | (some (a, L'), s') => cons a (L'.runStateRef s') /-- Return the head of a monadic lazy list if it exists, as an `Option` in the monad. -/ def head? [Monad m] (L : MLList m α) : m (Option α) := return (← L.uncons).map (·.1) /-- Take the initial segment of the lazy list, up to and including the first place where `f` gives `true`. -/ partial def takeUpToFirstM [Monad m] (L : MLList m α) (f : α → m (ULift Bool)) : MLList m α := L.casesM (fun _ => pure nil) fun x xs => return cons x <| if (← (f x)).down then nil else xs.takeUpToFirstM f /-- Take the initial segment of the lazy list, up to and including the first place where `f` gives `true`. -/ def takeUpToFirst [Monad m] (L : MLList m α) (f : α → Bool) : MLList m α := L.takeUpToFirstM fun a => pure (.up (f a)) /-- Gets the last element of a monadic lazy list, as an option in the monad. This will run forever if the list is infinite. -/ partial def getLast? [Monad m] (L : MLList m α) : m (Option α) := do match ← uncons L with | none => return none | some (x, xs) => aux x xs where /-- Implementation of `MLList.aux`. -/ aux (x : α) (L : MLList m α) : m (Option α) := do match ← uncons L with | none => return some x | some (y, ys) => aux y ys /-- Gets the last element of a monadic lazy list, or the default value if the list is empty. This will run forever if the list is infinite. -/ partial def getLast! [Monad m] [Inhabited α] (L : MLList m α) : m α := Option.get! <$> L.getLast? /-- Folds a binary function across a monadic lazy list, from an initial starting value. This will run forever if the list is infinite. -/ partial def foldM [Monad m] (f : β → α → m β) (init : β) (L : MLList m α) : m β := return (← L.foldsM f init |>.getLast?).getD init -- `foldsM` is always non-empty, anyway. /-- Folds a binary function across a monadic lazy list, from an initial starting value. This will run forever if the list is infinite. -/ partial def fold [Monad m] (f : β → α → β) (init : β) (L : MLList m α) : m β := L.foldM (fun b a => pure (f b a)) init /-- Return the head of a monadic lazy list, as a value in the monad. Fails if the list is empty. -/ def head [AlternativeMonad m] (L : MLList m α) : m α := do let some (r, _) ← L.uncons | failure return r /-- Apply a function returning values inside the monad to a monadic lazy list, returning only the first successful result. -/ def firstM [AlternativeMonad m] (L : MLList m α) (f : α → m (Option β)) : m β := (L.filterMapM f).head /-- Return the first value on which a predicate returns true. -/ def first [AlternativeMonad m] (L : MLList m α) (p : α → Bool) : m α := (L.filter p).head instance [Monad m] : AlternativeMonad (MLList m) where pure a := cons a nil map := map bind := bind failure := nil orElse := MLList.append instance [Monad m] : MonadLift m (MLList m) where monadLift := monadLift
.lake/packages/batteries/Batteries/Data/MLList/Heartbeats.lean
module public import Batteries.Data.MLList.Basic public import Lean.Util.Heartbeats @[expose] public section /-! # Truncate a `MLList` when running out of available heartbeats. -/ open Lean open Lean.Core (CoreM) /-- Take an initial segment of a monadic lazy list, stopping when there is less than `percent` of the remaining allowed heartbeats. If `getMaxHeartbeats` returns `0`, then this passes through the original list unmodified. The `initial` heartbeat counter is recorded when the first element of the list is requested. Then each time an element is requested from the wrapped list the heartbeat counter is checked, and if `current * 100 / initial < percent` then that element is returned, but no further elements. -/ def MLList.whileAtLeastHeartbeatsPercent [Monad m] [MonadLiftT CoreM m] (L : MLList m α) (percent : Nat := 10) : MLList m α := MLList.squash fun _ => do if (← getMaxHeartbeats) = 0 then do return L let initialHeartbeats ← getRemainingHeartbeats return L.takeUpToFirstM fun _ => do pure <| .up <| (← getRemainingHeartbeats) * 100 / initialHeartbeats < percent
.lake/packages/batteries/Batteries/Data/Array/Lemmas.lean
module public import Batteries.Data.List.Lemmas @[expose] public section namespace Array @[deprecated forIn_toList (since := "2025-07-01")] theorem forIn_eq_forIn_toList [Monad m] (as : Array α) (b : β) (f : α → β → m (ForInStep β)) : forIn as b f = forIn as.toList b f := by cases as simp /-! ### idxOf? -/ open List @[grind =] theorem idxOf?_toList [BEq α] {a : α} {l : Array α} : l.toList.idxOf? a = l.idxOf? a := by rcases l with ⟨l⟩ simp /-! ### erase -/ @[deprecated (since := "2025-02-06")] alias eraseP_toArray := List.eraseP_toArray @[deprecated (since := "2025-02-06")] alias erase_toArray := List.erase_toArray @[simp, grind =] theorem toList_erase [BEq α] (l : Array α) (a : α) : (l.erase a).toList = l.toList.erase a := by rcases l with ⟨l⟩ simp @[simp] theorem size_eraseIdxIfInBounds (a : Array α) (i : Nat) : (a.eraseIdxIfInBounds i).size = if i < a.size then a.size-1 else a.size := by grind /-! ### set -/ theorem size_set! (a : Array α) (i v) : (a.set! i v).size = a.size := by simp /-! ### map -/ /-! ### mem -/ /-! ### insertAt -/ @[deprecated (since := "2025-02-06")] alias getElem_insertIdx_lt := getElem_insertIdx_of_lt @[deprecated (since := "2025-02-06")] alias getElem_insertIdx_eq := getElem_insertIdx_self @[deprecated (since := "2025-02-06")] alias getElem_insertIdx_gt := getElem_insertIdx_of_gt
.lake/packages/batteries/Batteries/Data/Array/Pairwise.lean
module public import Batteries.Tactic.Alias @[expose] public section namespace Array /-- `Pairwise R as` means that all the elements of the array `as` are `R`-related to all elements with larger indices. `Pairwise R #[1, 2, 3] ↔ R 1 2 ∧ R 1 3 ∧ R 2 3` For example `as.Pairwise (· ≠ ·)` asserts that `as` has no duplicates, `as.Pairwise (· < ·)` asserts that `as` is strictly sorted and `as.Pairwise (· ≤ ·)` asserts that `as` is weakly sorted. -/ def Pairwise (R : α → α → Prop) (as : Array α) : Prop := as.toList.Pairwise R theorem pairwise_iff_getElem {as : Array α} : as.Pairwise R ↔ ∀ (i j : Nat) (_ : i < as.size) (_ : j < as.size), i < j → R as[i] as[j] := by unfold Pairwise; simp [List.pairwise_iff_getElem, length_toList] @[deprecated (since := "2025-02-19")] alias pairwise_iff_get := pairwise_iff_getElem instance (R : α → α → Prop) [DecidableRel R] (as) : Decidable (Pairwise R as) := have : (∀ (j : Fin as.size) (i : Fin j.val), R as[i.val] (as[j.val])) ↔ Pairwise R as := by rw [pairwise_iff_getElem] constructor · intro h i j _ hj hlt; exact h ⟨j, hj⟩ ⟨i, hlt⟩ · intro h ⟨j, hj⟩ ⟨i, hlt⟩; exact h i j (Nat.lt_trans hlt hj) hj hlt decidable_of_iff _ this @[grind ←] theorem pairwise_empty : #[].Pairwise R := by unfold Pairwise; exact List.Pairwise.nil @[grind ←] theorem pairwise_singleton (R : α → α → Prop) (a) : #[a].Pairwise R := by unfold Pairwise; exact List.pairwise_singleton .. @[grind =] theorem pairwise_pair : #[a, b].Pairwise R ↔ R a b := by unfold Pairwise; exact List.pairwise_pair @[grind =] theorem pairwise_append {as bs : Array α} : (as ++ bs).Pairwise R ↔ as.Pairwise R ∧ bs.Pairwise R ∧ (∀ x ∈ as, ∀ y ∈ bs, R x y) := by unfold Pairwise; simp [← mem_toList_iff, toList_append, ← List.pairwise_append] @[grind =] theorem pairwise_push {as : Array α} : (as.push a).Pairwise R ↔ as.Pairwise R ∧ (∀ x ∈ as, R x a) := by unfold Pairwise simp [← mem_toList_iff, toList_push, List.pairwise_append] @[grind ←] theorem pairwise_extract {as : Array α} (h : as.Pairwise R) (start stop) : (as.extract start stop).Pairwise R := by simp only [pairwise_iff_getElem, getElem_extract, size_extract] at h ⊢ intro _ _ _ _ hlt apply h exact Nat.add_lt_add_left hlt start
.lake/packages/batteries/Batteries/Data/Array/Merge.lean
module @[expose] public section namespace Array /-- `O(|xs| + |ys|)`. Merge arrays `xs` and `ys`. If the arrays are sorted according to `lt`, then the result is sorted as well. If two (or more) elements are equal according to `lt`, they are preserved. -/ def merge (lt : α → α → Bool) (xs ys : Array α) : Array α := go (Array.mkEmpty (xs.size + ys.size)) 0 0 where /-- Auxiliary definition for `merge`. -/ go (acc : Array α) (i j : Nat) : Array α := if hi : i ≥ xs.size then acc ++ ys[j:] else if hj : j ≥ ys.size then acc ++ xs[i:] else let x := xs[i] let y := ys[j] if lt x y then go (acc.push x) (i + 1) j else go (acc.push y) i (j + 1) termination_by xs.size + ys.size - (i + j) -- We name `ord` so it can be provided as a named argument. set_option linter.unusedVariables.funArgs false in /-- `O(|xs| + |ys|)`. Merge arrays `xs` and `ys`, which must be sorted according to `compare` and must not contain duplicates. Equal elements are merged using `merge`. If `merge` respects the order (i.e. for all `x`, `y`, `y'`, `z`, if `x < y < z` and `x < y' < z` then `x < merge y y' < z`) then the resulting array is again sorted. -/ def mergeDedupWith [ord : Ord α] (xs ys : Array α) (merge : α → α → α) : Array α := go (Array.mkEmpty (xs.size + ys.size)) 0 0 where /-- Auxiliary definition for `mergeDedupWith`. -/ go (acc : Array α) (i j : Nat) : Array α := if hi : i ≥ xs.size then acc ++ ys[j:] else if hj : j ≥ ys.size then acc ++ xs[i:] else let x := xs[i] let y := ys[j] match compare x y with | .lt => go (acc.push x) (i + 1) j | .gt => go (acc.push y) i (j + 1) | .eq => go (acc.push (merge x y)) (i + 1) (j + 1) termination_by xs.size + ys.size - (i + j) /-- `O(|xs| + |ys|)`. Merge arrays `xs` and `ys`, which must be sorted according to `compare` and must not contain duplicates. If an element appears in both `xs` and `ys`, only one copy is kept. -/ @[inline] def mergeDedup [ord : Ord α] (xs ys : Array α) : Array α := mergeDedupWith (ord := ord) xs ys fun x _ => x set_option linter.unusedVariables false in /-- `O(|xs| * |ys|)`. Merge `xs` and `ys`, which do not need to be sorted. Elements which occur in both `xs` and `ys` are only added once. If `xs` and `ys` do not contain duplicates, then neither does the result. -/ def mergeUnsortedDedup [eq : BEq α] (xs ys : Array α) : Array α := -- Ideally we would check whether `xs` or `ys` have spare capacity, to prevent -- copying if possible. But Lean arrays don't expose their capacity. if xs.size < ys.size then go ys xs else go xs ys where /-- Auxiliary definition for `mergeUnsortedDedup`. -/ @[inline] go (xs ys : Array α) := let xsSize := xs.size ys.foldl (init := xs) fun xs y => if xs.any (· == y) (stop := xsSize) then xs else xs.push y -- We name `eq` so it can be provided as a named argument. set_option linter.unusedVariables.funArgs false in /-- `O(|xs|)`. Replace each run `[x₁, ⋯, xₙ]` of equal elements in `xs` with `f ⋯ (f (f x₁ x₂) x₃) ⋯ xₙ`. -/ def mergeAdjacentDups [eq : BEq α] (f : α → α → α) (xs : Array α) : Array α := if h : 0 < xs.size then go (mkEmpty xs.size) 1 xs[0] else xs where /-- Auxiliary definition for `mergeAdjacentDups`. -/ go (acc : Array α) (i : Nat) (hd : α) := if h : i < xs.size then let x := xs[i] if x == hd then go acc (i + 1) (f hd x) else go (acc.push hd) (i + 1) x else acc.push hd termination_by xs.size - i /-- `O(|xs|)`. Deduplicate a sorted array. The array must be sorted with to an order which agrees with `==`, i.e. whenever `x == y` then `compare x y == .eq`. -/ def dedupSorted [eq : BEq α] (xs : Array α) : Array α := xs.mergeAdjacentDups (eq := eq) fun x _ => x /-- `O(|xs| log |xs|)`. Sort and deduplicate an array. -/ def sortDedup [ord : Ord α] (xs : Array α) : Array α := have := ord.toBEq dedupSorted <| xs.qsort (compare · · |>.isLT) end Array
.lake/packages/batteries/Batteries/Data/Array/Monadic.lean
module public import Batteries.Classes.SatisfiesM public import Batteries.Util.ProofWanted import all Init.Data.Array.Basic -- for unfolding `modifyM` @[expose] public section /-! # Results about monadic operations on `Array`, in terms of `SatisfiesM`. The pure versions of these theorems are proved in `Batteries.Data.Array.Lemmas` directly, in order to minimize dependence on `SatisfiesM`. -/ namespace Array theorem SatisfiesM_foldlM [Monad m] [LawfulMonad m] {as : Array α} {init : β} {motive : Nat → β → Prop} {f : β → α → m β} (h0 : motive 0 init) (hf : ∀ i : Fin as.size, ∀ b, motive i.1 b → SatisfiesM (motive (i.1 + 1)) (f b as[i])) : SatisfiesM (motive as.size) (as.foldlM f init) := by let rec go {i j b} (h₁ : j ≤ as.size) (h₂ : as.size ≤ i + j) (H : motive j b) : SatisfiesM (motive as.size) (foldlM.loop f as as.size (Nat.le_refl _) i j b) := by unfold foldlM.loop; split · next hj => split · cases Nat.not_le_of_gt (by simp [hj]) h₂ · exact (hf ⟨j, hj⟩ b H).bind fun _ => go hj (by rwa [Nat.succ_add] at h₂) · next hj => exact Nat.le_antisymm h₁ (Nat.ge_of_not_lt hj) ▸ .pure H simp [foldlM]; exact go (Nat.zero_le _) (Nat.le_refl _) h0 theorem SatisfiesM_mapM [Monad m] [LawfulMonad m] {as : Array α} {f : α → m β} {motive : Nat → Prop} {p : Fin as.size → β → Prop} (h0 : motive 0) (hs : ∀ i, motive i.1 → SatisfiesM (p i · ∧ motive (i + 1)) (f as[i])) : SatisfiesM (fun arr => motive as.size ∧ ∃ eq : arr.size = as.size, ∀ i h, p ⟨i, h⟩ arr[i]) (Array.mapM f as) := by rw [mapM_eq_foldlM] refine SatisfiesM_foldlM (m := m) (β := Array β) (motive := fun i arr => motive i ∧ arr.size = i ∧ ∀ i h2, p i (arr[i.1]'h2)) ?z ?s |>.imp fun ⟨h₁, eq, h₂⟩ => ⟨h₁, eq, fun _ _ => h₂ ..⟩ · case z => exact ⟨h0, rfl, nofun⟩ · case s => intro ⟨i, hi⟩ arr ⟨ih₁, eq, ih₂⟩ refine (hs _ ih₁).map fun ⟨h₁, h₂⟩ => ⟨h₂, by simp [eq], fun j hj => ?_⟩ simp [getElem_push] at hj ⊢; split; {apply ih₂} cases j; cases (Nat.le_or_eq_of_le_succ hj).resolve_left ‹_›; cases eq; exact h₁ theorem SatisfiesM_mapM' [Monad m] [LawfulMonad m] {as : Array α} {f : α → m β} {p : Fin as.size → β → Prop} (hs : ∀ i, SatisfiesM (p i) (f as[i])) : SatisfiesM (fun arr => ∃ eq : arr.size = as.size, ∀ i h, p ⟨i, h⟩ arr[i]) (Array.mapM f as) := (SatisfiesM_mapM (motive := fun _ => True) trivial (fun _ h => (hs _).imp (⟨·, h⟩))).imp (·.2) theorem size_mapM [Monad m] [LawfulMonad m] (f : α → m β) (as : Array α) : SatisfiesM (fun arr => arr.size = as.size) (Array.mapM f as) := (SatisfiesM_mapM' (fun _ => .trivial)).imp (·.1) theorem SatisfiesM_anyM [Monad m] [LawfulMonad m] {p : α → m Bool} {as : Array α} (hstart : start ≤ min stop as.size) (tru : Prop) (fal : Nat → Prop) (h0 : fal start) (hp : ∀ i : Fin as.size, i.1 < stop → fal i.1 → SatisfiesM (bif · then tru else fal (i + 1)) (p as[i])) : SatisfiesM (fun res => bif res then tru else fal (min stop as.size)) (anyM p as start stop) := by let rec go {stop j} (hj' : j ≤ stop) (hstop : stop ≤ as.size) (h0 : fal j) (hp : ∀ i : Fin as.size, i.1 < stop → fal i.1 → SatisfiesM (bif · then tru else fal (i + 1)) (p as[i])) : SatisfiesM (fun res => bif res then tru else fal stop) (anyM.loop p as stop hstop j) := by unfold anyM.loop; split · next hj => exact (hp ⟨j, Nat.lt_of_lt_of_le hj hstop⟩ hj h0).bind fun | true, h => .pure h | false, h => go hj hstop h hp · next hj => exact .pure <| Nat.le_antisymm hj' (Nat.ge_of_not_lt hj) ▸ h0 termination_by stop - j simp only [Array.anyM_eq_anyM_loop] exact go hstart _ h0 fun i hi => hp i <| Nat.lt_of_lt_of_le hi <| Nat.min_le_left .. theorem SatisfiesM_anyM_iff_exists [Monad m] [LawfulMonad m] {p : α → m Bool} {as : Array α} {q : Fin as.size → Prop} (hp : ∀ i : Fin as.size, start ≤ i.1 → i.1 < stop → SatisfiesM (· = true ↔ q i) (p as[i])) : SatisfiesM (fun res => res = true ↔ ∃ i : Fin as.size, start ≤ i.1 ∧ i.1 < stop ∧ q i) (anyM p as start stop) := by cases Nat.le_total start (min stop as.size) with | inl hstart => refine (SatisfiesM_anyM hstart (fal := fun j => start ≤ j ∧ ¬ ∃ i : Fin as.size, start ≤ i.1 ∧ i.1 < j ∧ q i) (tru := ∃ i : Fin as.size, start ≤ i.1 ∧ i.1 < stop ∧ q i) ?_ ?_).imp ?_ · exact ⟨Nat.le_refl _, fun ⟨i, h₁, h₂, _⟩ => (Nat.not_le_of_gt h₂ h₁).elim⟩ · refine fun i h₂ ⟨h₁, h₃⟩ => (hp _ h₁ h₂).imp fun hq => ?_ unfold cond; split <;> simp at hq · exact ⟨_, h₁, h₂, hq⟩ · refine ⟨Nat.le_succ_of_le h₁, h₃.imp fun ⟨j, h₃, h₄, h₅⟩ => ⟨j, h₃, ?_, h₅⟩⟩ refine Nat.lt_of_le_of_ne (Nat.le_of_lt_succ h₄) fun e => hq (Fin.eq_of_val_eq e ▸ h₅) · intro | true, h => simp only [true_iff]; exact h | false, h => simp only [false_iff, reduceCtorEq] exact h.2.imp fun ⟨j, h₁, h₂, hq⟩ => ⟨j, h₁, Nat.lt_min.2 ⟨h₂, j.2⟩, hq⟩ | inr hstart => rw [anyM_stop_le_start (h := hstart)] refine .pure ?_; simp; intro j h₁ h₂ cases Nat.not_lt.2 (Nat.le_trans hstart h₁) (Nat.lt_min.2 ⟨h₂, j.2⟩) theorem SatisfiesM_foldrM [Monad m] [LawfulMonad m] {as : Array α} {init : β} {motive : Nat → β → Prop} {f : α → β → m β} (h0 : motive as.size init) (hf : ∀ i : Fin as.size, ∀ b, motive (i.1 + 1) b → SatisfiesM (motive i.1) (f as[i] b)) : SatisfiesM (motive 0) (as.foldrM f init) := by let rec go {i b} (hi : i ≤ as.size) (H : motive i b) : SatisfiesM (motive 0) (foldrM.fold f as 0 i hi b) := by unfold foldrM.fold; simp; split · next hi => exact .pure (hi ▸ H) · next hi => split; {simp at hi} · next i hi' => exact (hf ⟨i, hi'⟩ b H).bind fun _ => go _ simp [foldrM]; split; {exact go _ h0} · next h => exact .pure (Nat.eq_zero_of_not_pos h ▸ h0) theorem SatisfiesM_mapFinIdxM [Monad m] [LawfulMonad m] {as : Array α} {f : (i : Nat) → α → i < as.size → m β} {motive : Nat → Prop} {p : (i : Nat) → β → i < as.size → Prop} (h0 : motive 0) (hs : ∀ i h, motive i → SatisfiesM (p i · h ∧ motive (i + 1)) (f i as[i] h)) : SatisfiesM (fun arr => motive as.size ∧ ∃ eq : arr.size = as.size, ∀ i h, p i arr[i] h) (Array.mapFinIdxM as f) := by let rec go {bs i j h} (h₁ : j = bs.size) (h₂ : ∀ i h h', p i bs[i] h) (hm : motive j) : SatisfiesM (fun arr => motive as.size ∧ ∃ eq : arr.size = as.size, ∀ i h, p i arr[i] h) (Array.mapFinIdxM.map as f i j h bs) := by induction i generalizing j bs with simp [mapFinIdxM.map] | zero => have := (Nat.zero_add _).symm.trans h exact .pure ⟨this ▸ hm, h₁ ▸ this, fun _ _ => h₂ ..⟩ | succ i ih => refine (hs _ _ (by exact hm)).bind fun b hb => ih (by simp [h₁]) (fun i hi hi' => ?_) hb.2 simp at hi'; simp [getElem_push]; split · next h => exact h₂ _ _ h · next h => cases h₁.symm ▸ (Nat.le_or_eq_of_le_succ hi').resolve_left h; exact hb.1 simp [mapFinIdxM]; exact go rfl nofun h0 theorem SatisfiesM_mapIdxM [Monad m] [LawfulMonad m] {as : Array α} {f : Nat → α → m β} {p : (i : Nat) → β → i < as.size → Prop} {motive : Nat → Prop} (h0 : motive 0) (hs : ∀ i h, motive i → SatisfiesM (p i · h ∧ motive (i + 1)) (f i as[i])) : SatisfiesM (fun arr => motive as.size ∧ ∃ eq : arr.size = as.size, ∀ i h, p i arr[i] h) (as.mapIdxM f) := SatisfiesM_mapFinIdxM h0 hs theorem size_mapFinIdxM [Monad m] [LawfulMonad m] (as : Array α) (f : (i : Nat) → α → i < as.size → m β) : SatisfiesM (fun arr => arr.size = as.size) (Array.mapFinIdxM as f) := (SatisfiesM_mapFinIdxM (motive := fun _ => True) trivial (fun _ _ _ => .of_true fun _ => ⟨trivial, trivial⟩)).imp (·.2.1) theorem size_mapIdxM [Monad m] [LawfulMonad m] (as : Array α) (f : Nat → α → m β) : SatisfiesM (fun arr => arr.size = as.size) (Array.mapIdxM f as) := size_mapFinIdxM _ _ theorem size_modifyM [Monad m] [LawfulMonad m] (as : Array α) (i : Nat) (f : α → m α) : SatisfiesM (·.size = as.size) (as.modifyM i f) := by unfold modifyM; split · exact .bind_pre <| .of_true fun _ => .pure <| by simp only [size_set] · exact .pure rfl end Array
.lake/packages/batteries/Batteries/Data/Array/Basic.lean
module @[expose] public section /-! ## Definitions on Arrays This file contains various definitions on `Array`. It does not contain proofs about these definitions, those are contained in other files in `Batteries.Data.Array`. -/ namespace Array /-- Check whether `xs` and `ys` are equal as sets, i.e. they contain the same elements when disregarding order and duplicates. `O(n*m)`! If your element type has an `Ord` instance, it is asymptotically more efficient to sort the two arrays, remove duplicates and then compare them elementwise. -/ def equalSet [BEq α] (xs ys : Array α) : Bool := xs.all (ys.contains ·) && ys.all (xs.contains ·) set_option linter.unusedVariables.funArgs false in /-- Returns the first minimal element among `d` and elements of the array. If `start` and `stop` are given, only the subarray `xs[start:stop]` is considered (in addition to `d`). -/ @[inline] protected def minWith [ord : Ord α] (xs : Array α) (d : α) (start := 0) (stop := xs.size) : α := xs.foldl (init := d) (start := start) (stop := stop) fun min x => if compare x min |>.isLT then x else min set_option linter.unusedVariables.funArgs false in /-- Find the first minimal element of an array. If the array is empty, `d` is returned. If `start` and `stop` are given, only the subarray `xs[start:stop]` is considered. -/ @[inline] protected def minD [ord : Ord α] (xs : Array α) (d : α) (start := 0) (stop := xs.size) : α := if h: start < xs.size ∧ start < stop then xs.minWith xs[start] (start + 1) stop else d set_option linter.unusedVariables.funArgs false in /-- Find the first minimal element of an array. If the array is empty, `none` is returned. If `start` and `stop` are given, only the subarray `xs[start:stop]` is considered. -/ @[inline] protected def min? [ord : Ord α] (xs : Array α) (start := 0) (stop := xs.size) : Option α := if h : start < xs.size ∧ start < stop then some $ xs.minD xs[start] start stop else none set_option linter.unusedVariables.funArgs false in /-- Find the first minimal element of an array. If the array is empty, `default` is returned. If `start` and `stop` are given, only the subarray `xs[start:stop]` is considered. -/ @[inline] protected def minI [ord : Ord α] [Inhabited α] (xs : Array α) (start := 0) (stop := xs.size) : α := xs.minD default start stop set_option linter.unusedVariables.funArgs false in /-- Returns the first maximal element among `d` and elements of the array. If `start` and `stop` are given, only the subarray `xs[start:stop]` is considered (in addition to `d`). -/ @[inline] protected def maxWith [ord : Ord α] (xs : Array α) (d : α) (start := 0) (stop := xs.size) : α := xs.minWith (ord := ord.opposite) d start stop set_option linter.unusedVariables.funArgs false in /-- Find the first maximal element of an array. If the array is empty, `d` is returned. If `start` and `stop` are given, only the subarray `xs[start:stop]` is considered. -/ @[inline] protected def maxD [ord : Ord α] (xs : Array α) (d : α) (start := 0) (stop := xs.size) : α := xs.minD (ord := ord.opposite) d start stop set_option linter.unusedVariables.funArgs false in /-- Find the first maximal element of an array. If the array is empty, `none` is returned. If `start` and `stop` are given, only the subarray `xs[start:stop]` is considered. -/ @[inline] protected def max? [ord : Ord α] (xs : Array α) (start := 0) (stop := xs.size) : Option α := xs.min? (ord := ord.opposite) start stop set_option linter.unusedVariables.funArgs false in /-- Find the first maximal element of an array. If the array is empty, `default` is returned. If `start` and `stop` are given, only the subarray `xs[start:stop]` is considered. -/ @[inline] protected def maxI [ord : Ord α] [Inhabited α] (xs : Array α) (start := 0) (stop := xs.size) : α := xs.minI (ord := ord.opposite) start stop /-! ### Safe Nat Indexed Array functions The functions in this section offer variants of Array functions which use `Nat` indices instead of `Fin` indices. All these functions have as parameter a proof that the index is valid for the array. But this parameter has a default argument `by get_elem_tactic` which should prove the index bound. -/ /-- `setN a i h x` sets an element in a vector using a Nat index which is provably valid. A proof by `get_elem_tactic` is provided as a default argument for `h`. This will perform the update destructively provided that `a` has a reference count of 1 when called. -/ abbrev setN (a : Array α) (i : Nat) (x : α) (h : i < a.size := by get_elem_tactic) : Array α := a.set i x end Array namespace Subarray /-- Check whether a subarray is empty. -/ @[inline] def isEmpty (as : Subarray α) : Bool := as.start == as.stop /-- Check whether a subarray contains an element. -/ @[inline] def contains [BEq α] (as : Subarray α) (a : α) : Bool := as.any (· == a) /-- Remove the first element of a subarray. Returns the element and the remaining subarray, or `none` if the subarray is empty. -/ def popHead? (as : Subarray α) : Option (α × Subarray α) := if h : as.start < as.stop then let head := as.array[as.start]'(Nat.lt_of_lt_of_le h as.stop_le_array_size) let tail := ⟨{ as.internalRepresentation with start := as.start + 1 start_le_stop := Nat.le_of_lt_succ $ Nat.succ_lt_succ h }⟩ some (head, tail) else none end Subarray
.lake/packages/batteries/Batteries/Data/Array/Match.lean
module @[expose] public section namespace Array /-- Prefix table for the Knuth-Morris-Pratt matching algorithm This is an array of the form `t = [(x₀,n₀), (x₁,n₁), (x₂, n₂), ...]` where for each `i`, `nᵢ` is the length of the longest proper prefix of `xs = [x₀,x₁,...,xᵢ]` which is also a suffix of `xs`. -/ structure PrefixTable (α : Type _) extends Array (α × Nat) where /-- Validity condition to help with termination proofs -/ valid : (h : i < toArray.size) → toArray[i].2 ≤ i instance : Inhabited (PrefixTable α) where default := ⟨#[], nofun⟩ /-- Returns the size of the prefix table -/ abbrev PrefixTable.size (t : PrefixTable α) := t.toArray.size /-- Transition function for the KMP matcher Assuming we have an input `xs` with a suffix that matches the pattern prefix `t.pattern[:len]` where `len : Fin (t.size+1)`. Then `xs.push x` has a suffix that matches the pattern prefix `t.pattern[:t.step x len]`. If `len` is as large as possible then `t.step x len` will also be as large as possible. -/ def PrefixTable.step [BEq α] (t : PrefixTable α) (x : α) : Fin (t.size+1) → Fin (t.size+1) | ⟨k, hk⟩ => let cont := fun () => match k with | 0 => ⟨0, Nat.zero_lt_succ _⟩ | k + 1 => have h2 : k < t.size := Nat.lt_of_succ_lt_succ hk let k' := t.toArray[k].2 have hk' : k' < k + 1 := Nat.lt_succ_of_le (t.valid h2) step t x ⟨k', Nat.lt_trans hk' hk⟩ if hsz : k < t.size then if x == t.toArray[k].1 then ⟨k+1, Nat.succ_lt_succ hsz⟩ else cont () else cont () termination_by k => k.val /-- Extend a prefix table by one element If `t` is the prefix table for `xs` then `t.extend x` is the prefix table for `xs.push x`. -/ def PrefixTable.extend [BEq α] (t : PrefixTable α) (x : α) : PrefixTable α where toArray := t.toArray.push (x, t.step x ⟨t.size, Nat.lt_succ_self _⟩) valid _ := by rw [Array.getElem_push] split · exact t.valid .. · next h => exact Nat.le_trans (Nat.lt_succ.1 <| Fin.isLt ..) (Nat.not_lt.1 h) /-- Make prefix table from a pattern array -/ def mkPrefixTable [BEq α] (xs : Array α) : PrefixTable α := xs.foldl (·.extend) default /-- Make prefix table from a pattern stream -/ partial def mkPrefixTableOfStream [BEq α] [Std.Stream σ α] (stream : σ) : PrefixTable α := loop default stream where /-- Inner loop for `mkPrefixTableOfStream` -/ loop (t : PrefixTable α) (stream : σ) := match Stream.next? stream with | none => t | some (x, stream) => loop (t.extend x) stream /-- KMP matcher structure -/ structure Matcher (α) where /-- Prefix table for the pattern -/ table : PrefixTable α /-- Current longest matching prefix -/ state : Fin (table.size + 1) := 0 /-- Make a KMP matcher for a given pattern array -/ def Matcher.ofArray [BEq α] (pat : Array α) : Matcher α where table := mkPrefixTable pat /-- Make a KMP matcher for a given a pattern stream -/ def Matcher.ofStream [BEq α] [Std.Stream σ α] (pat : σ) : Matcher α where table := mkPrefixTableOfStream pat /-- Find next match from a given stream Runs the stream until it reads a sequence that matches the sought pattern, then returns the stream state at that point and an updated matcher state. -/ partial def Matcher.next? [BEq α] [Std.Stream σ α] (m : Matcher α) (stream : σ) : Option (σ × Matcher α) := match Stream.next? stream with | none => none | some (x, stream) => let state := m.table.step x m.state if state = m.table.size then some (stream, { m with state }) else next? { m with state } stream namespace Matcher open Std.Iterators /-- Iterator transformer for KMP matcher. -/ protected structure Iterator (σ n α) [BEq α] (m : Matcher α) [Iterator σ n α] where /-- Inner iterator. -/ inner : IterM (α := σ) n α /-- Matcher state. -/ state : Fin (m.table.size + 1) := 0 /-- Implementation datail for `Matcher.Iterator`. -/ def modifyStep [BEq α] (m : Matcher α) [Iterator σ n α] (it : IterM (α := m.Iterator σ n α) n σ) : it.internalState.inner.Step (α := σ) → IterStep (IterM (α := m.Iterator σ n α) n σ) σ | .done _ => .done | .skip it' _ => .skip ⟨{it.internalState with inner := it'}⟩ | .yield it' x _ => let state := m.table.step x m.state if state = m.table.size then .yield ⟨{inner := it', state := state}⟩ it'.internalState else .skip ⟨{inner := it', state := state}⟩ instance [Monad n] [BEq α] (m : Matcher α) [Iterator σ n α] : Iterator (m.Iterator σ n α) n σ where IsPlausibleStep it step := ∃ step', m.modifyStep it step' = step step it := it.internalState.inner.step >>= fun step => pure (.deflate ⟨m.modifyStep _ _, step.inflate, rfl⟩) private def finitenessRelation [Monad n] [BEq α] (m : Matcher α) [Iterator σ n α] [Finite σ n] : FinitenessRelation (m.Iterator σ n α) n where rel := InvImage IterM.IsPlausibleSuccessorOf fun it => it.internalState.inner wf := InvImage.wf _ Finite.wf subrelation {it it'} h := by obtain ⟨_, hsucc, step, rfl⟩ := h simp only [IterM.Step] at step cases step with simp only [IterStep.successor, modifyStep, reduceCtorEq] at hsucc | skip => cases hsucc apply IterM.isPlausibleSuccessorOf_of_skip assumption | yield => split at hsucc · next heq => cases hsucc split at heq · cases heq apply IterM.isPlausibleSuccessorOf_of_yield assumption · contradiction · next heq => cases hsucc split at heq · contradiction · cases heq apply IterM.isPlausibleSuccessorOf_of_yield assumption · contradiction instance [Monad n] [BEq α] (m : Matcher α) [Iterator σ n α] [inst : Finite σ n] : Finite (m.Iterator σ n α) n (β := σ) := .of_finitenessRelation m.finitenessRelation end Matcher end Array
.lake/packages/batteries/Batteries/Data/Array/Init/Lemmas.lean
module @[expose] public section /-! While this file is currently empty, it is intended as a home for any lemmas which are required for definitions in `Batteries.Data.Array.Basic`, but which are not provided by Lean. -/
.lake/packages/batteries/Batteries/Data/BitVec/Lemmas.lean
module public import Batteries.Tactic.Alias public import Batteries.Data.BitVec.Basic public import Batteries.Data.Fin.OfBits public import Batteries.Data.Nat.Lemmas public import Batteries.Data.Int @[expose] public section namespace BitVec @[simp] theorem toNat_ofFnLEAux (m : Nat) (f : Fin n → Bool) : (ofFnLEAux m f).toNat = Nat.ofBits f % 2 ^ m := by simp only [ofFnLEAux] induction n with | zero => rfl | succ n ih => rw [Fin.foldr_succ, toNat_shiftConcat, Nat.shiftLeft_eq, Nat.pow_one, Nat.ofBits_succ, ih, ← Nat.mod_add_div (Nat.ofBits (f ∘ Fin.succ)) (2 ^ m), Nat.mul_add 2, Nat.add_right_comm, Nat.mul_left_comm, Nat.add_mul_mod_self_left, Nat.mul_comm 2] rfl @[simp] theorem toFin_ofFnLEAux (m : Nat) (f : Fin n → Bool) : (ofFnLEAux m f).toFin = Fin.ofNat (2 ^ m) (Nat.ofBits f) := by ext; simp @[simp, grind =] theorem toNat_ofFnLE (f : Fin n → Bool) : (ofFnLE f).toNat = Nat.ofBits f := by rw [ofFnLE, toNat_ofFnLEAux, Nat.mod_eq_of_lt (Nat.ofBits_lt_two_pow f)] @[simp, grind =] theorem toFin_ofFnLE (f : Fin n → Bool) : (ofFnLE f).toFin = Fin.ofBits f := by ext; simp @[simp, grind =] theorem toInt_ofFnLE (f : Fin n → Bool) : (ofFnLE f).toInt = Int.ofBits f := by simp only [BitVec.toInt, Int.ofBits, toNat_ofFnLE, Int.subNatNat_eq_coe]; rfl -- TODO: consider these for global `grind` attributes. attribute [local grind =] Fin.succ Fin.rev Fin.last Fin.zero_eta theorem getElem_ofFnLEAux (f : Fin n → Bool) (i) (h : i < n) (h' : i < m) : (ofFnLEAux m f)[i] = f ⟨i, h⟩ := by simp only [ofFnLEAux] induction n generalizing i m with | zero => contradiction | succ n ih => simp only [Fin.foldr_succ, getElem_shiftConcat] cases i with | zero => grind | succ i => rw [ih] <;> grind @[simp, grind =] theorem getElem_ofFnLE (f : Fin n → Bool) (i) (h : i < n) : (ofFnLE f)[i] = f ⟨i, h⟩ := getElem_ofFnLEAux .. @[grind =] theorem getLsb_ofFnLE (f : Fin n → Bool) (i) : (ofFnLE f).getLsb i = f i := by simp @[deprecated (since := "2025-06-17")] alias getLsb'_ofFnLE := getLsb_ofFnLE theorem getLsbD_ofFnLE (f : Fin n → Bool) (i) : (ofFnLE f).getLsbD i = if h : i < n then f ⟨i, h⟩ else false := by grind @[simp, grind =] theorem getMsb_ofFnLE (f : Fin n → Bool) (i) : (ofFnLE f).getMsb i = f i.rev := by grind @[deprecated (since := "2025-06-17")] alias getMsb'_ofFnLE := getMsb_ofFnLE @[grind =] theorem getMsbD_ofFnLE (f : Fin n → Bool) (i) : (ofFnLE f).getMsbD i = if h : i < n then f (Fin.rev ⟨i, h⟩) else false := by grind theorem msb_ofFnLE (f : Fin n → Bool) : (ofFnLE f).msb = if h : n ≠ 0 then f ⟨n-1, Nat.sub_one_lt h⟩ else false := by grind @[simp, grind =] theorem toNat_ofFnBE (f : Fin n → Bool) : (ofFnBE f).toNat = Nat.ofBits (f ∘ Fin.rev) := by simp [ofFnBE]; rfl @[simp, grind =] theorem toFin_ofFnBE (f : Fin n → Bool) : (ofFnBE f).toFin = Fin.ofBits (f ∘ Fin.rev) := by ext; simp @[simp, grind =] theorem toInt_ofFnBE (f : Fin n → Bool) : (ofFnBE f).toInt = Int.ofBits (f ∘ Fin.rev) := by simp [ofFnBE]; rfl @[simp, grind =] theorem getElem_ofFnBE (f : Fin n → Bool) (i) (h : i < n) : (ofFnBE f)[i] = f (Fin.rev ⟨i, h⟩) := by simp [ofFnBE] @[grind =] theorem getLsb_ofFnBE (f : Fin n → Bool) (i) : (ofFnBE f).getLsb i = f i.rev := by simp @[deprecated (since := "2025-06-17")] alias getLsb'_ofFnBE := getLsb_ofFnBE theorem getLsbD_ofFnBE (f : Fin n → Bool) (i) : (ofFnBE f).getLsbD i = if h : i < n then f (Fin.rev ⟨i, h⟩) else false := by grind @[simp, grind =] theorem getMsb_ofFnBE (f : Fin n → Bool) (i) : (ofFnBE f).getMsb i = f i := by simp [ofFnBE] @[deprecated (since := "2025-06-17")] alias getMsb'_ofFnBE := getMsb_ofFnBE @[grind =] theorem getMsbD_ofFnBE (f : Fin n → Bool) (i) : (ofFnBE f).getMsbD i = if h : i < n then f ⟨i, h⟩ else false := by grind @[grind =] theorem msb_ofFnBE (f : Fin n → Bool) : (ofFnBE f).msb = if h : n ≠ 0 then f ⟨0, Nat.zero_lt_of_ne_zero h⟩ else false := by grind
.lake/packages/batteries/Batteries/Data/BitVec/Basic.lean
module @[expose] public section namespace BitVec /-- `ofFnLEAux f` returns the `BitVec m` whose `i`th bit is `f i` when `i < m`, little endian. -/ @[inline] def ofFnLEAux (m : Nat) (f : Fin n → Bool) : BitVec m := Fin.foldr n (fun i v => v.shiftConcat (f i)) 0 /-- `ofFnLE f` returns the `BitVec n` whose `i`th bit is `f i` with little endian ordering. -/ @[inline] def ofFnLE (f : Fin n → Bool) : BitVec n := ofFnLEAux n f /-- `ofFnBE f` returns the `BitVec n` whose `i`th bit is `f i` with big endian ordering. -/ @[inline] def ofFnBE (f : Fin n → Bool) : BitVec n := ofFnLE fun i => f i.rev
.lake/packages/batteries/Batteries/Data/UnionFind/Lemmas.lean
module public import Batteries.Data.UnionFind.Basic @[expose] public section namespace Batteries.UnionFind @[simp] theorem arr_empty : empty.arr = #[] := rfl @[simp] theorem parent_empty : empty.parent a = a := rfl @[simp] theorem rank_empty : empty.rank a = 0 := rfl @[simp] theorem rootD_empty : empty.rootD a = a := rfl @[simp] theorem arr_push {m : UnionFind} : m.push.arr = m.arr.push ⟨m.arr.size, 0⟩ := rfl @[simp] theorem parentD_push {arr : Array UFNode} : parentD (arr.push ⟨arr.size, 0⟩) a = parentD arr a := by simp [parentD]; split <;> split <;> try simp [Array.getElem_push, *] · next h1 h2 => simp [Nat.lt_succ] at h1 h2 exact Nat.le_antisymm h2 h1 · next h1 h2 => cases h1 (Nat.lt_succ_of_lt h2) @[simp] theorem parent_push {m : UnionFind} : m.push.parent a = m.parent a := by simp [parent] @[simp] theorem rankD_push {arr : Array UFNode} : rankD (arr.push ⟨arr.size, 0⟩) a = rankD arr a := by simp [rankD]; split <;> split <;> try simp [Array.getElem_push, *] next h1 h2 => cases h1 (Nat.lt_succ_of_lt h2) @[simp] theorem rank_push {m : UnionFind} : m.push.rank a = m.rank a := by simp [rank] @[simp] theorem rankMax_push {m : UnionFind} : m.push.rankMax = m.rankMax := by simp [rankMax] @[simp] theorem root_push {self : UnionFind} : self.push.rootD x = self.rootD x := rootD_ext fun _ => parent_push @[simp] theorem arr_link : (link self x y yroot).arr = linkAux self.arr x y := rfl theorem parentD_linkAux {self} {x y : Fin self.size} : parentD (linkAux self x y) i = if x.1 = y then parentD self i else if self[y.1].rank < self[x.1].rank then if y = i then x else parentD self i else if x = i then y else parentD self i := by dsimp only [linkAux]; split <;> [rfl; split] <;> [rw [parentD_set]; split] <;> rw [parentD_set] split <;> [(subst i; rwa [if_neg, parentD_eq]); rw [parentD_set]] theorem parent_link {self} {x y : Fin self.size} (yroot) {i} : (link self x y yroot).parent i = if x.1 = y then self.parent i else if self.rank y < self.rank x then if y = i then x else self.parent i else if x = i then y else self.parent i := by simp [rankD_eq]; exact parentD_linkAux theorem root_link {self : UnionFind} {x y : Fin self.size} (xroot : self.parent x = x) (yroot : self.parent y = y) : ∃ r, (r = x ∨ r = y) ∧ ∀ i, (link self x y yroot).rootD i = if self.rootD i = x ∨ self.rootD i = y then r.1 else self.rootD i := by if h : x.1 = y then refine ⟨x, .inl rfl, fun i => ?_⟩ rw [rootD_ext (m2 := self) (fun _ => by rw [parent_link, if_pos h])] split <;> [obtain _ | _ := ‹_› <;> simp [*]; rfl] else have {x y : Fin self.size} (xroot : self.parent x = x) (yroot : self.parent y = y) {m : UnionFind} (hm : ∀ i, m.parent i = if y = i then x.1 else self.parent i) : ∃ r, (r = x ∨ r = y) ∧ ∀ i, m.rootD i = if self.rootD i = x ∨ self.rootD i = y then r.1 else self.rootD i := by let rec go (i) : m.rootD i = if self.rootD i = x ∨ self.rootD i = y then x.1 else self.rootD i := by if h : m.parent i = i then rw [rootD_eq_self.2 h]; rw [hm i] at h; split at h · rw [if_pos, h]; simp [← h, rootD_eq_self, xroot] · rw [rootD_eq_self.2 ‹_›]; split <;> [skip; rfl] next h' => exact h'.resolve_right (Ne.symm ‹_›) else have _ := Nat.sub_lt_sub_left (m.lt_rankMax i) (m.rank_lt h) rw [← rootD_parent, go (m.parent i)] rw [hm i]; split <;> [subst i; rw [rootD_parent]] simp [rootD_eq_self.2 xroot, rootD_eq_self.2 yroot] termination_by m.rankMax - m.rank i exact ⟨x, .inl rfl, go⟩ if hr : self.rank y < self.rank x then exact this xroot yroot fun i => by simp [parent_link, h, hr] else simpa (config := {singlePass := true}) [or_comm] using this yroot xroot fun i => by simp [parent_link, h, hr] nonrec theorem Equiv.rfl : Equiv self a a := rfl nonrec theorem Equiv.symm : Equiv self a b → Equiv self b a := .symm nonrec theorem Equiv.trans : Equiv self a b → Equiv self b c → Equiv self a c := .trans @[simp] theorem equiv_empty : Equiv empty a b ↔ a = b := by simp [Equiv] @[simp] theorem equiv_push : Equiv self.push a b ↔ Equiv self a b := by simp [Equiv] @[simp] theorem equiv_rootD : Equiv self (self.rootD a) a := by simp [Equiv, rootD_rootD] @[simp] theorem equiv_rootD_l : Equiv self (self.rootD a) b ↔ Equiv self a b := by simp [Equiv, rootD_rootD] @[simp] theorem equiv_rootD_r : Equiv self a (self.rootD b) ↔ Equiv self a b := by simp [Equiv, rootD_rootD] theorem equiv_find : Equiv (self.find x).1 a b ↔ Equiv self a b := by simp [Equiv, find_root_1] theorem equiv_link {self : UnionFind} {x y : Fin self.size} (xroot : self.parent x = x) (yroot : self.parent y = y) : Equiv (link self x y yroot) a b ↔ Equiv self a b ∨ Equiv self a x ∧ Equiv self y b ∨ Equiv self a y ∧ Equiv self x b := by have {m : UnionFind} {x y : Fin self.size} (xroot : self.rootD x = x) (yroot : self.rootD y = y) (hm : ∀ i, m.rootD i = if self.rootD i = x ∨ self.rootD i = y then x.1 else self.rootD i) : Equiv m a b ↔ Equiv self a b ∨ Equiv self a x ∧ Equiv self y b ∨ Equiv self a y ∧ Equiv self x b := by simp [Equiv, hm, xroot, yroot] by_cases h1 : rootD self a = x <;> by_cases h2 : rootD self b = x <;> simp [h1, h2, imp_false, Decidable.not_not, -left_eq_ite_iff] · simp [Ne.symm h2, -left_eq_ite_iff]; split <;> simp [@eq_comm _ _ (rootD self b), *] · by_cases h1 : rootD self a = y <;> by_cases h2 : rootD self b = y <;> simp [@eq_comm _ _ (rootD self b), *] obtain ⟨r, ha, hr⟩ := root_link xroot yroot; revert hr rw [← rootD_eq_self] at xroot yroot obtain rfl | rfl := ha · exact this xroot yroot · simpa [or_comm, and_comm] using this yroot xroot theorem equiv_union {self : UnionFind} {x y : Fin self.size} : Equiv (union self x y) a b ↔ Equiv self a b ∨ Equiv self a x ∧ Equiv self y b ∨ Equiv self a y ∧ Equiv self x b := by simp [union]; rw [equiv_link (by simp [← rootD_eq_self, rootD_rootD])]; simp [equiv_find]
.lake/packages/batteries/Batteries/Data/UnionFind/Basic.lean
module public import Batteries.Tactic.Lint.Misc public import Batteries.Tactic.SeqFocus public import Batteries.Util.Panic @[expose] public section namespace Batteries /-- Union-find node type -/ structure UFNode where /-- Parent of node -/ parent : Nat /-- Rank of node -/ rank : Nat namespace UnionFind /-- Parent of a union-find node, defaults to self when the node is a root -/ def parentD (arr : Array UFNode) (i : Nat) : Nat := if h : i < arr.size then arr[i].parent else i /-- Rank of a union-find node, defaults to 0 when the node is a root -/ def rankD (arr : Array UFNode) (i : Nat) : Nat := if h : i < arr.size then arr[i].rank else 0 theorem parentD_eq {arr : Array UFNode} {i} (h) : parentD arr i = arr[i].parent := dif_pos _ theorem rankD_eq {arr : Array UFNode} {i} (h) : rankD arr i = arr[i].rank := dif_pos _ theorem parentD_of_not_lt : ¬i < arr.size → parentD arr i = i := (dif_neg ·) theorem lt_of_parentD : parentD arr i ≠ i → i < arr.size := Decidable.not_imp_comm.1 parentD_of_not_lt theorem parentD_set {arr : Array UFNode} {x v i h} : parentD (arr.set x v h) i = if x = i then v.parent else parentD arr i := by rw [parentD]; simp only [Array.size_set, parentD] split · split <;> simp_all · split <;> [(subst i; cases ‹¬_› h); rfl] theorem rankD_set {arr : Array UFNode} {x v i h} : rankD (arr.set x v h) i = if x = i then v.rank else rankD arr i := by rw [rankD]; simp only [Array.size_set, rankD] split · split <;> simp_all · split <;> [(subst i; cases ‹¬_› h); rfl] end UnionFind open UnionFind /-- ### Union-find data structure The `UnionFind` structure is an implementation of disjoint-set data structure that uses path compression to make the primary operations run in amortized nearly linear time. The nodes of a `UnionFind` structure `s` are natural numbers smaller than `s.size`. The structure associates with a canonical representative from its equivalence class. The structure can be extended using the `push` operation and equivalence classes can be updated using the `union` operation. The main operations for `UnionFind` are: * `empty`/`mkEmpty` are used to create a new empty structure. * `size` returns the size of the data structure. * `push` adds a new node to a structure, unlinked to any other node. * `union` links two nodes of the data structure, joining their equivalence classes, and performs path compression. * `find` returns the canonical representative of a node and updates the data structure using path compression. * `root` returns the canonical representative of a node without altering the data structure. * `checkEquiv` checks whether two nodes have the same canonical representative and updates the structure using path compression. Most use cases should prefer `find` over `root` to benefit from the speedup from path-compression. The main operations use `Fin s.size` to represent nodes of the union-find structure. Some alternatives are provided: * `unionN`, `findN`, `rootN`, `checkEquivN` use `Fin n` with a proof that `n = s.size`. * `union!`, `find!`, `root!`, `checkEquiv!` use `Nat` and panic when the indices are out of bounds. * `findD`, `rootD`, `checkEquivD` use `Nat` and treat out of bound indices as isolated nodes. The noncomputable relation `UnionFind.Equiv` is provided to use the equivalence relation from a `UnionFind` structure in the context of proofs. -/ structure UnionFind where /-- Array of union-find nodes -/ arr : Array UFNode /-- Validity for parent nodes -/ parentD_lt : ∀ {i}, i < arr.size → parentD arr i < arr.size /-- Validity for rank -/ rankD_lt : ∀ {i}, parentD arr i ≠ i → rankD arr i < rankD arr (parentD arr i) namespace UnionFind /-- Size of union-find structure. -/ @[inline] abbrev size (self : UnionFind) := self.arr.size /-- Create an empty union-find structure with specific capacity -/ def mkEmpty (c : Nat) : UnionFind where arr := Array.mkEmpty c parentD_lt := nofun rankD_lt := nofun /-- Empty union-find structure -/ def empty := mkEmpty 0 instance : EmptyCollection UnionFind := ⟨.empty⟩ /-- Parent of union-find node -/ abbrev parent (self : UnionFind) (i : Nat) : Nat := parentD self.arr i theorem parent'_lt (self : UnionFind) (i : Nat) (h) : self.arr[i].parent < self.size := by simp [← parentD_eq, parentD_lt, h] theorem parent_lt (self : UnionFind) (i : Nat) : self.parent i < self.size ↔ i < self.size := by simp only [parentD]; split <;> simp only [*, parent'_lt] /-- Rank of union-find node -/ abbrev rank (self : UnionFind) (i : Nat) : Nat := rankD self.arr i theorem rank_lt {self : UnionFind} {i : Nat} : self.parent i ≠ i → self.rank i < self.rank (self.parent i) := by simpa only [rank] using self.rankD_lt theorem rank'_lt (self : UnionFind) (i h) : self.arr[i].parent ≠ i → self.rank i < self.rank (self.arr[i]).parent := by simpa only [← parentD_eq] using self.rankD_lt /-- Maximum rank of nodes in a union-find structure -/ noncomputable def rankMax (self : UnionFind) := self.arr.foldr (max ·.rank) 0 + 1 theorem rank'_lt_rankMax (self : UnionFind) (i : Nat) (h) : (self.arr[i]).rank < self.rankMax := by let rec go : ∀ {l} {x : UFNode}, x ∈ l → x.rank ≤ List.foldr (max ·.rank) 0 l | a::l, _, List.Mem.head _ => by dsimp; apply Nat.le_max_left | a::l, _, .tail _ h => by dsimp; exact Nat.le_trans (go h) (Nat.le_max_right ..) simp only [rankMax, ← Array.foldr_toList] exact Nat.lt_succ.2 <| go (self.arr.toList.getElem_mem _) theorem rankD_lt_rankMax (self : UnionFind) (i : Nat) : rankD self.arr i < self.rankMax := by simp [rankD]; split <;> [apply rank'_lt_rankMax; apply Nat.succ_pos] theorem lt_rankMax (self : UnionFind) (i : Nat) : self.rank i < self.rankMax := rankD_lt_rankMax .. theorem push_rankD (arr : Array UFNode) : rankD (arr.push ⟨arr.size, 0⟩) i = rankD arr i := by simp only [rankD, Array.size_push, Array.getElem_push, dite_eq_ite] split <;> split <;> first | simp | cases ‹¬_› (Nat.lt_succ_of_lt ‹_›) theorem push_parentD (arr : Array UFNode) : parentD (arr.push ⟨arr.size, 0⟩) i = parentD arr i := by simp only [parentD, Array.size_push, Array.getElem_push, dite_eq_ite] split <;> split <;> try simp · exact Nat.le_antisymm (Nat.ge_of_not_lt ‹_›) (Nat.le_of_lt_succ ‹_›) · cases ‹¬_› (Nat.lt_succ_of_lt ‹_›) /-- Add a new node to a union-find structure, unlinked with any other nodes -/ def push (self : UnionFind) : UnionFind where arr := self.arr.push ⟨self.arr.size, 0⟩ parentD_lt {i} := by simp only [Array.size_push, push_parentD]; simp only [parentD] split <;> [exact fun _ => Nat.lt_succ_of_lt (self.parent'_lt ..); exact id] rankD_lt := by simp only [push_parentD, ne_eq, push_rankD]; exact self.rank_lt /-- Root of a union-find node. -/ def root (self : UnionFind) (x : Fin self.size) : Fin self.size := let y := self.arr[x.1].parent if h : y = x then x else have := Nat.sub_lt_sub_left (self.lt_rankMax x) (self.rank'_lt _ _ h) self.root ⟨y, self.parent'_lt x _⟩ termination_by self.rankMax - self.rank x @[inherit_doc root] def rootN (self : UnionFind) (x : Fin n) (h : n = self.size) : Fin n := match n, h with | _, rfl => self.root x /-- Root of a union-find node. Panics if index is out of bounds. -/ def root! (self : UnionFind) (x : Nat) : Nat := if h : x < self.size then self.root ⟨x, h⟩ else panicWith x "index out of bounds" /-- Root of a union-find node. Returns input if index is out of bounds. -/ def rootD (self : UnionFind) (x : Nat) : Nat := if h : x < self.size then self.root ⟨x, h⟩ else x set_option backward.proofsInPublic true in -- for `rw [root]` @[nolint unusedHavesSuffices] theorem parent_root (self : UnionFind) (x : Fin self.size) : (self.arr[(self.root x).1]).parent = self.root x := by rw [root]; split <;> [assumption; skip] have := Nat.sub_lt_sub_left (self.lt_rankMax x) (self.rank'_lt _ _ ‹_›) apply parent_root termination_by self.rankMax - self.rank x theorem parent_rootD (self : UnionFind) (x : Nat) : self.parent (self.rootD x) = self.rootD x := by rw [rootD] split · simp [parentD, parent_root] · simp [parentD_of_not_lt, *] @[nolint unusedHavesSuffices] theorem rootD_parent (self : UnionFind) (x : Nat) : self.rootD (self.parent x) = self.rootD x := by simp only [rootD, parent_lt] split · simp only [parentD, ↓reduceDIte, *] (conv => rhs; rw [root]); split · rw [root, dif_pos] <;> simp_all · simp · simp only [not_false_eq_true, parentD_of_not_lt, *] theorem rootD_lt {self : UnionFind} {x : Nat} : self.rootD x < self.size ↔ x < self.size := by simp only [rootD]; split <;> simp [*] @[nolint unusedHavesSuffices] theorem rootD_eq_self {self : UnionFind} {x : Nat} : self.rootD x = x ↔ self.parent x = x := by refine ⟨fun h => by rw [← h, parent_rootD], fun h => ?_⟩ rw [rootD]; split <;> [rw [root, dif_pos (by rwa [parent, parentD_eq ‹_›] at h)]; rfl] theorem rootD_rootD {self : UnionFind} {x : Nat} : self.rootD (self.rootD x) = self.rootD x := rootD_eq_self.2 (parent_rootD ..) theorem rootD_ext {m1 m2 : UnionFind} (H : ∀ x, m1.parent x = m2.parent x) {x} : m1.rootD x = m2.rootD x := by if h : m2.parent x = x then rw [rootD_eq_self.2 h, rootD_eq_self.2 ((H _).trans h)] else have := Nat.sub_lt_sub_left (m2.lt_rankMax x) (m2.rank_lt h) rw [← rootD_parent, H, rootD_ext H, rootD_parent] termination_by m2.rankMax - m2.rank x theorem le_rank_root {self : UnionFind} {x : Nat} : self.rank x ≤ self.rank (self.rootD x) := by if h : self.parent x = x then rw [rootD_eq_self.2 h]; exact Nat.le_refl .. else have := Nat.sub_lt_sub_left (self.lt_rankMax x) (self.rank_lt h) rw [← rootD_parent] exact Nat.le_trans (Nat.le_of_lt (self.rank_lt h)) le_rank_root termination_by self.rankMax - self.rank x theorem lt_rank_root {self : UnionFind} {x : Nat} : self.rank x < self.rank (self.rootD x) ↔ self.parent x ≠ x := by refine ⟨fun h h' => Nat.ne_of_lt h (by rw [rootD_eq_self.2 h']), fun h => ?_⟩ rw [← rootD_parent] exact Nat.lt_of_lt_of_le (self.rank_lt h) le_rank_root /-- Auxiliary data structure for find operation -/ structure FindAux (n : Nat) where /-- Array of nodes -/ s : Array UFNode /-- Index of root node -/ root : Fin n /-- Size requirement -/ size_eq : s.size = n /-- Auxiliary function for find operation -/ def findAux (self : UnionFind) (x : Fin self.size) : FindAux self.size := let y := self.arr[x.1].parent if h : y = x then ⟨self.arr, x, rfl⟩ else have := Nat.sub_lt_sub_left (self.lt_rankMax x) (self.rank'_lt _ _ h) let ⟨arr₁, root, H⟩ := self.findAux ⟨y, self.parent'_lt _ x.2⟩ ⟨arr₁.modify x fun s => { s with parent := root }, root, by simp [H]⟩ termination_by self.rankMax - self.rank x @[nolint unusedHavesSuffices] theorem findAux_root {self : UnionFind} {x : Fin self.size} : (findAux self x).root = self.root x := by rw [findAux, root] simp only [dite_eq_ite] split <;> simp only have := Nat.sub_lt_sub_left (self.lt_rankMax x) (self.rank'_lt _ _ ‹_›) exact findAux_root termination_by self.rankMax - self.rank x @[nolint unusedHavesSuffices] theorem findAux_s {self : UnionFind} {x : Fin self.size} : (findAux self x).s = if self.arr[x.1].parent = x then self.arr else (self.findAux ⟨_, self.parent'_lt x x.2⟩).s.modify x fun s => { s with parent := self.rootD x } := by rw [show self.rootD _ = (self.findAux ⟨_, self.parent'_lt x x.2⟩).root from _] · rw [findAux]; split <;> rfl · rw [← rootD_parent, parent, parentD_eq (Fin.is_lt _)] simp only [rootD, findAux_root] apply dif_pos theorem rankD_findAux {self : UnionFind} {x : Fin self.size} : rankD (findAux self x).s i = self.rank i := by if h : i < self.size then rw [findAux_s]; split <;> [rfl; skip] have := Nat.sub_lt_sub_left (self.lt_rankMax x) (self.rank'_lt _ _ ‹_›) have := lt_of_parentD (by rwa [parentD_eq]) rw [rankD_eq (by simp [FindAux.size_eq, h]), Array.getElem_modify] split <;> simp [← rankD_eq, rankD_findAux (x := ⟨_, self.parent'_lt _ x.2⟩)] else simp only [rankD, rank] rw [dif_neg (by rwa [FindAux.size_eq]), dif_neg h] termination_by self.rankMax - self.rank x theorem parentD_findAux {self : UnionFind} {x : Fin self.size} : parentD (findAux self x).s i = if i = x then self.rootD x else parentD (self.findAux ⟨_, self.parent'_lt _ x.2⟩).s i := by rw [findAux_s]; split <;> [split; skip] · subst i; rw [rootD_eq_self.2 _] <;> simp [parentD_eq, *] · rw [findAux_s]; simp [*] · next h => rw [parentD]; split <;> rename_i h' · rw [Array.getElem_modify (by simpa using h')] simp only [@eq_comm _ i] split <;> simp [← parentD_eq] · rw [if_neg (mt (by rintro rfl; simp [FindAux.size_eq]) h')] rw [parentD, dif_neg]; simpa using h' theorem parentD_findAux_rootD {self : UnionFind} {x : Fin self.size} : parentD (findAux self x).s (self.rootD x) = self.rootD x := by rw [parentD_findAux]; split <;> [rfl; rename_i h] rw [rootD_eq_self, parent, parentD_eq x.2] at h have := Nat.sub_lt_sub_left (self.lt_rankMax x) (self.rank'_lt _ _ ‹_›) rw [← rootD_parent, parent, parentD_eq x.2] exact parentD_findAux_rootD (x := ⟨_, self.parent'_lt _ x.2⟩) termination_by self.rankMax - self.rank x theorem parentD_findAux_lt {self : UnionFind} {x : Fin self.size} (h : i < self.size) : parentD (findAux self x).s i < self.size := by if h' : self.arr[x.1].parent = x then rw [findAux_s, if_pos h']; apply self.parentD_lt h else rw [parentD_findAux] split · simp [rootD_lt] · have := Nat.sub_lt_sub_left (self.lt_rankMax x) (self.rank'_lt _ _ ‹_›) apply parentD_findAux_lt h termination_by self.rankMax - self.rank x theorem parentD_findAux_or (self : UnionFind) (x : Fin self.size) (i) : parentD (findAux self x).s i = self.rootD i ∧ self.rootD i = self.rootD x ∨ parentD (findAux self x).s i = self.parent i := by if h' : self.arr[x.1].parent = x then rw [findAux_s, if_pos h']; exact .inr rfl else rw [parentD_findAux] split · simp [*] · have := Nat.sub_lt_sub_left (self.lt_rankMax x) (self.rank'_lt _ _ ‹_›) refine (parentD_findAux_or self ⟨_, self.parent'_lt _ x.2⟩ i) |>.imp_left (.imp_right fun h => ?_) simp only [h, ← parentD_eq, rootD_parent] termination_by self.rankMax - self.rank x theorem lt_rankD_findAux {self : UnionFind} {x : Fin self.size} : parentD (findAux self x).s i ≠ i → self.rank i < self.rank (parentD (findAux self x).s i) := by if h' : self.arr[x.1].parent = x then rw [findAux_s, if_pos h']; apply self.rank_lt else rw [parentD_findAux]; split <;> rename_i h <;> intro h' · subst i; rwa [lt_rank_root, Ne, ← rootD_eq_self] · have := Nat.sub_lt_sub_left (self.lt_rankMax x) (self.rank'_lt _ _ ‹_›) apply lt_rankD_findAux h' termination_by self.rankMax - self.rank x /-- Find root of a union-find node, updating the structure using path compression. -/ def find (self : UnionFind) (x : Fin self.size) : (s : UnionFind) × {_root : Fin s.size // s.size = self.size} := let r := self.findAux x { 1.arr := r.s 2.1.val := r.root 1.parentD_lt := fun h => by simp only [FindAux.size_eq] at * exact parentD_findAux_lt h 1.rankD_lt := fun h => by rw [rankD_findAux, rankD_findAux]; exact lt_rankD_findAux h 2.1.isLt := show _ < r.s.size by rw [r.size_eq]; exact r.root.2 2.2 := by simp [size, r.size_eq] } @[inherit_doc find] def findN (self : UnionFind) (x : Fin n) (h : n = self.size) : UnionFind × Fin n := match n, h with | _, rfl => match self.find x with | ⟨s, r, h⟩ => (s, Fin.cast h r) /-- Find root of a union-find node, updating the structure using path compression. Panics if index is out of bounds. -/ def find! (self : UnionFind) (x : Nat) : UnionFind × Nat := if h : x < self.size then match self.find ⟨x, h⟩ with | ⟨s, r, _⟩ => (s, r) else panicWith (self, x) "index out of bounds" /-- Find root of a union-find node, updating the structure using path compression. Returns inputs unchanged when index is out of bounds. -/ def findD (self : UnionFind) (x : Nat) : UnionFind × Nat := if h : x < self.size then match self.find ⟨x, h⟩ with | ⟨s, r, _⟩ => (s, r) else (self, x) @[simp] theorem find_size (self : UnionFind) (x : Fin self.size) : (self.find x).1.size = self.size := by simp [find, size, FindAux.size_eq] @[simp] theorem find_root_2 (self : UnionFind) (x : Fin self.size) : (self.find x).2.1.1 = self.rootD x := by simp [find, findAux_root, rootD] @[simp] theorem find_parent_1 (self : UnionFind) (x : Fin self.size) : (self.find x).1.parent x = self.rootD x := by simp only [parent, find] rw [parentD_findAux, if_pos rfl] theorem find_parent_or (self : UnionFind) (x : Fin self.size) (i) : (self.find x).1.parent i = self.rootD i ∧ self.rootD i = self.rootD x ∨ (self.find x).1.parent i = self.parent i := parentD_findAux_or .. @[simp] theorem find_root_1 (self : UnionFind) (x : Fin self.size) (i : Nat) : (self.find x).1.rootD i = self.rootD i := by if h : (self.find x).1.parent i = i then rw [rootD_eq_self.2 h] obtain ⟨h1, _⟩ | h1 := find_parent_or self x i <;> rw [h1] at h · rw [h] · rw [rootD_eq_self.2 h] else have := Nat.sub_lt_sub_left ((self.find x).1.lt_rankMax _) ((self.find x).1.rank_lt h) rw [← rootD_parent, find_root_1 self x ((self.find x).1.parent i)] obtain ⟨h1, _⟩ | h1 := find_parent_or self x i · rw [h1, rootD_rootD] · rw [h1, rootD_parent] termination_by (self.find x).1.rankMax - (self.find x).1.rank i decreasing_by exact this -- why is this needed? It is way slower without it /-- Link two union-find nodes -/ def linkAux (self : Array UFNode) (x y : Fin self.size) : Array UFNode := if x.1 = y then self else let nx := self[x.1] let ny := self[y.1] if ny.rank < nx.rank then self.set y {ny with parent := x} else let arr₁ := self.set x {nx with parent := y} if nx.rank = ny.rank then arr₁.set y {ny with rank := ny.rank + 1} (by simp [arr₁]) else arr₁ theorem setParentBump_rankD_lt {arr : Array UFNode} {x y : Fin arr.size} (hroot : arr[x.1].rank < arr[y.1].rank ∨ arr[y.1].parent = y) (H : arr[x.1].rank ≤ arr[y.1].rank) {i : Nat} (rankD_lt : parentD arr i ≠ i → rankD arr i < rankD arr (parentD arr i)) (hP : parentD arr' i = if x.1 = i then y.1 else parentD arr i) (hR : ∀ {i}, rankD arr' i = if y.1 = i ∧ arr[x.1].rank = arr[y.1].rank then arr[y.1].rank + 1 else rankD arr i) : ¬parentD arr' i = i → rankD arr' i < rankD arr' (parentD arr' i) := by simp only [ne_eq, hP, hR, implies_true] at *; split <;> rename_i h₁ <;> [simp [← h₁]; skip] <;> split <;> rename_i h₂ <;> intro h · simp [h₂] at h · simp only [rankD_eq, x.2, y.2] split <;> rename_i h₃ · rw [← h₃]; apply Nat.lt_succ_self · exact Nat.lt_of_le_of_ne H h₃ · cases h₂.1 simp only [h₂.2, false_or, Nat.lt_irrefl] at hroot simp only [hroot, parentD_eq y.2, not_true_eq_false] at h · have := rankD_lt h split <;> rename_i h₃ · rw [← rankD_eq, h₃.1]; exact Nat.lt_succ_of_lt this · exact this theorem setParent_rankD_lt {arr : Array UFNode} {x y : Fin arr.size} (h : arr[x.1].rank < arr[y.1].rank) {i : Nat} (rankD_lt : parentD arr i ≠ i → rankD arr i < rankD arr (parentD arr i)) : let arr' := arr.set x ⟨y, arr[x].rank⟩ parentD arr' i ≠ i → rankD arr' i < rankD arr' (parentD arr' i) := setParentBump_rankD_lt (.inl h) (Nat.le_of_lt h) rankD_lt parentD_set (by simp [rankD_set, Nat.ne_of_lt h, rankD_eq]) @[simp] theorem linkAux_size : (linkAux self x y).size = self.size := by simp only [linkAux] split <;> [rfl; split] <;> [skip; split] <;> simp /-- Link a union-find node to a root node. -/ def link (self : UnionFind) (x y : Fin self.size) (yroot : self.parent y = y) : UnionFind where arr := linkAux self.arr x y parentD_lt h := by simp only [linkAux_size] at * simp only [linkAux] split <;> [skip; split <;> [skip; split]] · exact self.parentD_lt h · rw [parentD_set]; split <;> [exact x.2; exact self.parentD_lt h] · rw [parentD_set]; split · exact self.parent'_lt .. · rw [parentD_set]; split <;> [exact y.2; exact self.parentD_lt h] · rw [parentD_set]; split <;> [exact y.2; exact self.parentD_lt h] rankD_lt := by rw [parent, parentD_eq (Fin.is_lt _)] at yroot simp only [linkAux, ne_eq] split <;> [skip; split <;> [skip; split]] · exact self.rankD_lt · exact setParent_rankD_lt ‹_› self.rankD_lt · refine setParentBump_rankD_lt (.inr yroot) (Nat.le_of_eq ‹_›) self.rankD_lt (by simp only [parentD_set, ite_eq_right_iff] rintro rfl simp [*, parentD_eq]) fun {i} => ?_ simp only [rankD_set] split · simp_all · simp_all only [Nat.lt_irrefl, not_false_eq_true, and_true, ite_false, ite_eq_right_iff] rintro rfl simp [rankD_eq, *] · exact setParent_rankD_lt (Nat.lt_of_le_of_ne (Nat.not_lt.1 ‹_›) ‹_›) self.rankD_lt @[inherit_doc link] def linkN (self : UnionFind) (x y : Fin n) (yroot : self.parent y = y) (h : n = self.size) : UnionFind := match n, h with | _, rfl => self.link x y yroot /-- Link a union-find node to a root node. Panics if either index is out of bounds. -/ def link! (self : UnionFind) (x y : Nat) (yroot : self.parent y = y) : UnionFind := if h : x < self.size ∧ y < self.size then self.link ⟨x, h.1⟩ ⟨y, h.2⟩ yroot else panicWith self "index out of bounds" /-- Link two union-find nodes, uniting their respective classes. -/ def union (self : UnionFind) (x y : Fin self.size) : UnionFind := let ⟨self₁, rx, ex⟩ := self.find x have hy := by rw [ex]; exact y.2 match eq : self₁.find ⟨y, hy⟩ with | ⟨self₂, ry, ey⟩ => self₂.link ⟨rx, by rw [ey]; exact rx.2⟩ ry <| by have := find_root_1 self₁ ⟨y, hy⟩ (⟨y, hy⟩ : Fin _) rw [← find_root_2, eq] at this; simp at this rw [← this, parent_rootD] @[inherit_doc union] def unionN (self : UnionFind) (x y : Fin n) (h : n = self.size) : UnionFind := match n, h with | _, rfl => self.union x y /-- Link two union-find nodes, uniting their respective classes. Panics if either index is out of bounds. -/ def union! (self : UnionFind) (x y : Nat) : UnionFind := if h : x < self.size ∧ y < self.size then self.union ⟨x, h.1⟩ ⟨y, h.2⟩ else panicWith self "index out of bounds" /-- Check whether two union-find nodes are equivalent, updating structure using path compression. -/ def checkEquiv (self : UnionFind) (x y : Fin self.size) : UnionFind × Bool := let ⟨s, ⟨r₁, _⟩, h⟩ := self.find x let ⟨s, ⟨r₂, _⟩, _⟩ := s.find (h ▸ y) (s, r₁ == r₂) @[inherit_doc checkEquiv] def checkEquivN (self : UnionFind) (x y : Fin n) (h : n = self.size) : UnionFind × Bool := match n, h with | _, rfl => self.checkEquiv x y /-- Check whether two union-find nodes are equivalent, updating structure using path compression. Panics if either index is out of bounds. -/ def checkEquiv! (self : UnionFind) (x y : Nat) : UnionFind × Bool := if h : x < self.size ∧ y < self.size then self.checkEquiv ⟨x, h.1⟩ ⟨y, h.2⟩ else panicWith (self, false) "index out of bounds" /-- Check whether two union-find nodes are equivalent with path compression, returns `x == y` if either index is out of bounds -/ def checkEquivD (self : UnionFind) (x y : Nat) : UnionFind × Bool := let (s, x) := self.findD x let (s, y) := s.findD y (s, x == y) /-- Equivalence relation from a `UnionFind` structure -/ def Equiv (self : UnionFind) (a b : Nat) : Prop := self.rootD a = self.rootD b
.lake/packages/batteries/Batteries/Data/Nat/Bitwise.lean
module @[expose] public section /-! # Bitwise Lemmas This module defines properties of the bitwise operations on natural numbers. This file is complements `Init.Data.Nat.Bitwise.Lemmas` with properties that are not necessary for the bitvector library. -/ namespace Nat /-! ### and -/ @[simp] theorem and_self_left (a b : Nat) : a &&& (a &&& b) = a &&& b := by apply Nat.eq_of_testBit_eq; simp @[simp] theorem and_self_right (a b : Nat) : ((a &&& b) &&& b) = (a &&& b) := by apply Nat.eq_of_testBit_eq; simp theorem and_left_comm (x y z : Nat) : x &&& (y &&& z) = y &&& (x &&& z) := by apply Nat.eq_of_testBit_eq; simp [Bool.and_left_comm] theorem and_right_comm (x y z : Nat) : (x &&& y) &&& z = (x &&& z) &&& y := by apply Nat.eq_of_testBit_eq; simp [Bool.and_right_comm] /-! ### or -/ @[simp] theorem or_self_left (a b : Nat) : a ||| (a ||| b) = a ||| b := by apply Nat.eq_of_testBit_eq; simp @[simp] theorem or_self_right (a b : Nat) : (a ||| b) ||| b = a ||| b := by apply Nat.eq_of_testBit_eq; simp theorem or_left_comm (x y z : Nat) : x ||| (y ||| z) = y ||| (x ||| z) := by apply Nat.eq_of_testBit_eq; simp [Bool.or_left_comm] theorem or_right_comm (x y z : Nat) : (x ||| y) ||| z = (x ||| z) ||| y := by apply Nat.eq_of_testBit_eq; simp [Bool.or_right_comm] /-! ### xor -/ theorem xor_left_comm (x y z : Nat) : x ^^^ (y ^^^ z) = y ^^^ (x ^^^ z) := by apply Nat.eq_of_testBit_eq; simp only [testBit_xor, Bool.xor_left_comm, implies_true] theorem xor_right_comm (x y z : Nat) : (x ^^^ y) ^^^ z = (x ^^^ z) ^^^ y := by apply Nat.eq_of_testBit_eq; simp only [testBit_xor, Bool.xor_right_comm, implies_true] @[simp] theorem xor_xor_cancel_left (x y : Nat) : x ^^^ (x ^^^ y) = y := by apply Nat.eq_of_testBit_eq; simp @[simp] theorem xor_xor_cancel_right (x y : Nat) : (x ^^^ y) ^^^ y = x := by apply Nat.eq_of_testBit_eq; simp theorem eq_of_xor_eq_zero {x y : Nat} : x ^^^ y = 0 → x = y := by intro h; rw [← xor_xor_cancel_left x y, h, xor_zero] @[simp] theorem xor_eq_zero_iff {x y : Nat} : x ^^^ y = 0 ↔ x = y := ⟨eq_of_xor_eq_zero, fun | rfl => Nat.xor_self _⟩ theorem xor_ne_zero_iff {x y : Nat} : x ^^^ y ≠ 0 ↔ x ≠ y := by simp /-! ### injectivity lemmas -/ theorem xor_right_injective {x : Nat} : Function.Injective (x ^^^ ·) := by intro y z h; rw [← xor_xor_cancel_left x y, ← xor_xor_cancel_left x z]; simp only [h] theorem xor_left_injective {x : Nat} : Function.Injective (· ^^^ x) := by intro y z h; rw [← xor_xor_cancel_right y x, ← xor_xor_cancel_right z x]; simp only [h] @[simp] theorem xor_right_inj {x y z : Nat} : x ^^^ y = x ^^^ z ↔ y = z := ⟨(xor_right_injective ·), fun | rfl => rfl⟩ @[simp] theorem xor_left_inj {x y z : Nat} : x ^^^ z = y ^^^ z ↔ x = y := ⟨(xor_left_injective ·), fun | rfl => rfl⟩ theorem and_or_right_injective {m x y : Nat} : x &&& m = y &&& m → x ||| m = y ||| m → x = y := by intro ha ho apply Nat.eq_of_testBit_eq intro i rw [← Bool.and_or_inj_right_iff (m := m.testBit i)] simp [← testBit_and, ← testBit_or, ha, ho] theorem and_or_right_inj {m x y : Nat} : x &&& m = y &&& m ∧ x ||| m = y ||| m ↔ x = y := ⟨fun ⟨ha, ho⟩ => and_or_right_injective ha ho, fun | rfl => ⟨rfl, rfl⟩⟩ theorem and_or_left_injective {m x y : Nat} : m &&& x = m &&& y → m ||| x = m ||| y → x = y := by intro ha ho apply Nat.eq_of_testBit_eq intro i rw [← Bool.and_or_inj_left_iff (m := m.testBit i)] simp [← testBit_and, ← testBit_or, ha, ho] theorem and_or_left_inj {m x y : Nat} : m &&& x = m &&& y ∧ m ||| x = m ||| y ↔ x = y := ⟨fun ⟨ha, ho⟩ => and_or_left_injective ha ho, fun | rfl => ⟨rfl, rfl⟩⟩
.lake/packages/batteries/Batteries/Data/Nat/Gcd.lean
module public import Batteries.Tactic.Alias @[expose] public section /-! # Definitions and properties of `coprime` -/ namespace Nat @[deprecated (since := "2025-08-04")] alias Coprime.mul := Coprime.mul_left
.lake/packages/batteries/Batteries/Data/Nat/Lemmas.lean
module public import Batteries.Tactic.Alias public import Batteries.Data.Nat.Basic @[expose] public section /-! # Basic lemmas about natural numbers The primary purpose of the lemmas in this file is to assist with reasoning about sizes of objects, array indices and such. For a more thorough development of the theory of natural numbers, we recommend using Mathlib. -/ namespace Nat /-! ### rec/cases -/ @[simp] theorem recAux_zero {motive : Nat → Sort _} (zero : motive 0) (succ : ∀ n, motive n → motive (n+1)) : Nat.recAux zero succ 0 = zero := rfl theorem recAux_succ {motive : Nat → Sort _} (zero : motive 0) (succ : ∀ n, motive n → motive (n+1)) (n) : Nat.recAux zero succ (n+1) = succ n (Nat.recAux zero succ n) := rfl @[simp] theorem recAuxOn_zero {motive : Nat → Sort _} (zero : motive 0) (succ : ∀ n, motive n → motive (n+1)) : Nat.recAuxOn 0 zero succ = zero := rfl theorem recAuxOn_succ {motive : Nat → Sort _} (zero : motive 0) (succ : ∀ n, motive n → motive (n+1)) (n) : Nat.recAuxOn (n+1) zero succ = succ n (Nat.recAuxOn n zero succ) := rfl @[simp] theorem casesAuxOn_zero {motive : Nat → Sort _} (zero : motive 0) (succ : ∀ n, motive (n+1)) : Nat.casesAuxOn 0 zero succ = zero := rfl theorem casesAuxOn_succ {motive : Nat → Sort _} (zero : motive 0) (succ : ∀ n, motive (n+1)) (n) : Nat.casesAuxOn (n+1) zero succ = succ n := rfl theorem strongRec_eq {motive : Nat → Sort _} (ind : ∀ n, (∀ m, m < n → motive m) → motive n) (t : Nat) : Nat.strongRec ind t = ind t fun m _ => Nat.strongRec ind m := by conv => lhs; unfold Nat.strongRec theorem strongRecOn_eq {motive : Nat → Sort _} (ind : ∀ n, (∀ m, m < n → motive m) → motive n) (t : Nat) : Nat.strongRecOn t ind = ind t fun m _ => Nat.strongRecOn m ind := WellFounded.fix_eq WellFoundedRelation.wf ind t @[simp] theorem recDiagAux_zero_left {motive : Nat → Nat → Sort _} (zero_left : ∀ n, motive 0 n) (zero_right : ∀ m, motive m 0) (succ_succ : ∀ m n, motive m n → motive (m+1) (n+1)) (n) : Nat.recDiagAux zero_left zero_right succ_succ 0 n = zero_left n := by cases n <;> rfl @[simp] theorem recDiagAux_zero_right {motive : Nat → Nat → Sort _} (zero_left : ∀ n, motive 0 n) (zero_right : ∀ m, motive m 0) (succ_succ : ∀ m n, motive m n → motive (m+1) (n+1)) (m) (h : zero_left 0 = zero_right 0 := by first | assumption | trivial) : Nat.recDiagAux zero_left zero_right succ_succ m 0 = zero_right m := by cases m; exact h; rfl theorem recDiagAux_succ_succ {motive : Nat → Nat → Sort _} (zero_left : ∀ n, motive 0 n) (zero_right : ∀ m, motive m 0) (succ_succ : ∀ m n, motive m n → motive (m+1) (n+1)) (m n) : Nat.recDiagAux zero_left zero_right succ_succ (m+1) (n+1) = succ_succ m n (Nat.recDiagAux zero_left zero_right succ_succ m n) := rfl @[simp] theorem recDiag_zero_zero {motive : Nat → Nat → Sort _} (zero_zero : motive 0 0) (zero_succ : ∀ n, motive 0 n → motive 0 (n+1)) (succ_zero : ∀ m, motive m 0 → motive (m+1) 0) (succ_succ : ∀ m n, motive m n → motive (m+1) (n+1)) : Nat.recDiag (motive:=motive) zero_zero zero_succ succ_zero succ_succ 0 0 = zero_zero := rfl theorem recDiag_zero_succ {motive : Nat → Nat → Sort _} (zero_zero : motive 0 0) (zero_succ : ∀ n, motive 0 n → motive 0 (n+1)) (succ_zero : ∀ m, motive m 0 → motive (m+1) 0) (succ_succ : ∀ m n, motive m n → motive (m+1) (n+1)) (n) : Nat.recDiag zero_zero zero_succ succ_zero succ_succ 0 (n+1) = zero_succ n (Nat.recDiag zero_zero zero_succ succ_zero succ_succ 0 n) := by simp [Nat.recDiag]; rfl theorem recDiag_succ_zero {motive : Nat → Nat → Sort _} (zero_zero : motive 0 0) (zero_succ : ∀ n, motive 0 n → motive 0 (n+1)) (succ_zero : ∀ m, motive m 0 → motive (m+1) 0) (succ_succ : ∀ m n, motive m n → motive (m+1) (n+1)) (m) : Nat.recDiag zero_zero zero_succ succ_zero succ_succ (m+1) 0 = succ_zero m (Nat.recDiag zero_zero zero_succ succ_zero succ_succ m 0) := by simp [Nat.recDiag]; cases m <;> rfl theorem recDiag_succ_succ {motive : Nat → Nat → Sort _} (zero_zero : motive 0 0) (zero_succ : ∀ n, motive 0 n → motive 0 (n+1)) (succ_zero : ∀ m, motive m 0 → motive (m+1) 0) (succ_succ : ∀ m n, motive m n → motive (m+1) (n+1)) (m n) : Nat.recDiag zero_zero zero_succ succ_zero succ_succ (m+1) (n+1) = succ_succ m n (Nat.recDiag zero_zero zero_succ succ_zero succ_succ m n) := rfl @[simp] theorem recDiagOn_zero_zero {motive : Nat → Nat → Sort _} (zero_zero : motive 0 0) (zero_succ : ∀ n, motive 0 n → motive 0 (n+1)) (succ_zero : ∀ m, motive m 0 → motive (m+1) 0) (succ_succ : ∀ m n, motive m n → motive (m+1) (n+1)) : Nat.recDiagOn (motive:=motive) 0 0 zero_zero zero_succ succ_zero succ_succ = zero_zero := rfl theorem recDiagOn_zero_succ {motive : Nat → Nat → Sort _} (zero_zero : motive 0 0) (zero_succ : ∀ n, motive 0 n → motive 0 (n+1)) (succ_zero : ∀ m, motive m 0 → motive (m+1) 0) (succ_succ : ∀ m n, motive m n → motive (m+1) (n+1)) (n) : Nat.recDiagOn 0 (n+1) zero_zero zero_succ succ_zero succ_succ = zero_succ n (Nat.recDiagOn 0 n zero_zero zero_succ succ_zero succ_succ) := Nat.recDiag_zero_succ .. theorem recDiagOn_succ_zero {motive : Nat → Nat → Sort _} (zero_zero : motive 0 0) (zero_succ : ∀ n, motive 0 n → motive 0 (n+1)) (succ_zero : ∀ m, motive m 0 → motive (m+1) 0) (succ_succ : ∀ m n, motive m n → motive (m+1) (n+1)) (m) : Nat.recDiagOn (m+1) 0 zero_zero zero_succ succ_zero succ_succ = succ_zero m (Nat.recDiagOn m 0 zero_zero zero_succ succ_zero succ_succ) := Nat.recDiag_succ_zero .. theorem recDiagOn_succ_succ {motive : Nat → Nat → Sort _} (zero_zero : motive 0 0) (zero_succ : ∀ n, motive 0 n → motive 0 (n+1)) (succ_zero : ∀ m, motive m 0 → motive (m+1) 0) (succ_succ : ∀ m n, motive m n → motive (m+1) (n+1)) (m n) : Nat.recDiagOn (m+1) (n+1) zero_zero zero_succ succ_zero succ_succ = succ_succ m n (Nat.recDiagOn m n zero_zero zero_succ succ_zero succ_succ) := rfl @[simp] theorem casesDiagOn_zero_zero {motive : Nat → Nat → Sort _} (zero_zero : motive 0 0) (zero_succ : ∀ n, motive 0 (n+1)) (succ_zero : ∀ m, motive (m+1) 0) (succ_succ : ∀ m n, motive (m+1) (n+1)) : Nat.casesDiagOn 0 0 (motive:=motive) zero_zero zero_succ succ_zero succ_succ = zero_zero := rfl @[simp] theorem casesDiagOn_zero_succ {motive : Nat → Nat → Sort _} (zero_zero : motive 0 0) (zero_succ : ∀ n, motive 0 (n+1)) (succ_zero : ∀ m, motive (m+1) 0) (succ_succ : ∀ m n, motive (m+1) (n+1)) (n) : Nat.casesDiagOn 0 (n+1) zero_zero zero_succ succ_zero succ_succ = zero_succ n := rfl @[simp] theorem casesDiagOn_succ_zero {motive : Nat → Nat → Sort _} (zero_zero : motive 0 0) (zero_succ : ∀ n, motive 0 (n+1)) (succ_zero : ∀ m, motive (m+1) 0) (succ_succ : ∀ m n, motive (m+1) (n+1)) (m) : Nat.casesDiagOn (m+1) 0 zero_zero zero_succ succ_zero succ_succ = succ_zero m := rfl @[simp] theorem casesDiagOn_succ_succ {motive : Nat → Nat → Sort _} (zero_zero : motive 0 0) (zero_succ : ∀ n, motive 0 (n+1)) (succ_zero : ∀ m, motive (m+1) 0) (succ_succ : ∀ m n, motive (m+1) (n+1)) (m n) : Nat.casesDiagOn (m+1) (n+1) zero_zero zero_succ succ_zero succ_succ = succ_succ m n := rfl /-! ## strong case -/ /-- Strong case analysis on `a < b ∨ b ≤ a` -/ protected def lt_sum_ge (a b : Nat) : a < b ⊕' b ≤ a := if h : a < b then .inl h else .inr (Nat.not_lt.1 h) /-- Strong case analysis on `a < b ∨ a = b ∨ b < a` -/ protected def sum_trichotomy (a b : Nat) : a < b ⊕' a = b ⊕' b < a := match h : compare a b with | .lt => .inl (Nat.compare_eq_lt.1 h) | .eq => .inr (.inl (Nat.compare_eq_eq.1 h)) | .gt => .inr (.inr (Nat.compare_eq_gt.1 h)) /-! ### div/mod -/ -- TODO mod_core_congr, mod_def -- TODO div_core_congr, div_def -- TODO cont_to_bool_mod_two /-! ### sum -/ @[deprecated (since := "2025-07-31")] alias sum_append := List.sum_append_nat /-! ### ofBits -/ @[simp] theorem ofBits_zero (f : Fin 0 → Bool) : ofBits f = 0 := rfl theorem ofBits_succ (f : Fin (n+1) → Bool) : ofBits f = 2 * ofBits (f ∘ Fin.succ) + (f 0).toNat := Fin.foldr_succ .. theorem ofBits_lt_two_pow (f : Fin n → Bool) : ofBits f < 2 ^ n := by induction n with | zero => simp | succ n ih => calc ofBits f = 2 * ofBits (f ∘ Fin.succ) + (f 0).toNat := ofBits_succ .. _ < 2 * (ofBits (f ∘ Fin.succ) + 1) := Nat.add_lt_add_left (Bool.toNat_lt _) .. _ ≤ 2 * 2 ^ n := Nat.mul_le_mul_left 2 (ih ..) _ = 2 ^ (n + 1) := Nat.pow_add_one' .. |>.symm @[simp] theorem testBit_ofBits_lt (f : Fin n → Bool) (i : Nat) (h : i < n) : (ofBits f).testBit i = f ⟨i, h⟩ := by induction n generalizing i with | zero => contradiction | succ n ih => simp only [ofBits_succ] match i with | 0 => simp [mod_eq_of_lt (Bool.toNat_lt _)] | i+1 => rw [testBit_add_one, mul_add_div Nat.zero_lt_two, Nat.div_eq_of_lt (Bool.toNat_lt _)] exact ih (f ∘ Fin.succ) i (Nat.lt_of_succ_lt_succ h) @[simp] theorem testBit_ofBits_ge (f : Fin n → Bool) (i : Nat) (h : n ≤ i) : (ofBits f).testBit i = false := by apply testBit_lt_two_pow apply Nat.lt_of_lt_of_le · exact ofBits_lt_two_pow f · exact Nat.pow_le_pow_right Nat.zero_lt_two h theorem testBit_ofBits (f : Fin n → Bool) : (ofBits f).testBit i = if h : i < n then f ⟨i, h⟩ else false := by cases Nat.lt_or_ge i n with | inl h => simp [h] | inr h => simp [h, Nat.not_lt_of_ge h] theorem ofBits_testBit (x n) : ofBits (fun i : Fin n => x.testBit i) = x % 2 ^ n := by apply eq_of_testBit_eq; simp [testBit_ofBits] /-! ### Misc -/ theorem mul_add_lt_mul_of_lt_of_lt {m n x y : Nat} (hx : x < m) (hy : y < n) : n * x + y < m * n := calc _ < n * x + n := Nat.add_lt_add_left hy _ _ = n * (x + 1) := Nat.mul_add_one .. |>.symm _ ≤ n * m := Nat.mul_le_mul_left _ hx _ = m * n := Nat.mul_comm .. theorem add_mul_lt_mul_of_lt_of_lt {m n x y : Nat} (hx : x < m) (hy : y < n) : x + m * y < m * n := by rw [Nat.add_comm, Nat.mul_comm _ n] exact mul_add_lt_mul_of_lt_of_lt hy hx
.lake/packages/batteries/Batteries/Data/Nat/Digits.lean
module import all Init.Data.Repr -- for unfolding... everything @[expose] public section namespace Nat @[simp] theorem isDigit_digitChar : n.digitChar.isDigit = decide (n < 10) := match n with | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 => by simp [digitChar] | _ + 10 => by simp only [digitChar, ↓reduceIte, Nat.reduceEqDiff] (repeat' split) <;> simp private theorem isDigit_of_mem_toDigitsCore (hc : c ∈ cs → c.isDigit) (hb₁ : 0 < b) (hb₂ : b ≤ 10) (h : c ∈ toDigitsCore b fuel n cs) : c.isDigit := by induction fuel generalizing n cs with rw [toDigitsCore] at h | zero => exact hc h | succ _ ih => split at h case' isFalse => apply ih (fun h => ?_) h all_goals cases h with | head => simp [Nat.lt_of_lt_of_le (mod_lt _ hb₁) hb₂] | tail _ hm => exact hc hm theorem isDigit_of_mem_toDigits (hb₁ : 0 < b) (hb₂ : b ≤ 10) (hc : c ∈ toDigits b n) : c.isDigit := isDigit_of_mem_toDigitsCore (fun _ => by contradiction) hb₁ hb₂ hc private theorem toDigitsCore_of_lt_base (hb : n < b) (hf : n < fuel) : toDigitsCore b fuel n cs = n.digitChar :: cs := by unfold toDigitsCore split <;> simp_all [mod_eq_of_lt] theorem toDigits_of_lt_base (h : n < b) : toDigits b n = [n.digitChar] := toDigitsCore_of_lt_base h (lt_succ_self _) theorem toDigits_zero : (b : Nat) → toDigits b 0 = ['0'] | 0 => rfl | _ + 1 => toDigits_of_lt_base (zero_lt_succ _) private theorem toDigitsCore_append : toDigitsCore b fuel n cs₁ ++ cs₂ = toDigitsCore b fuel n (cs₁ ++ cs₂) := by induction fuel generalizing n cs₁ with simp only [toDigitsCore] | succ => split <;> simp_all private theorem toDigitsCore_eq_of_lt_fuel (hb : 1 < b) (h₁ : n < fuel₁) (h₂ : n < fuel₂) : toDigitsCore b fuel₁ n cs = toDigitsCore b fuel₂ n cs := by cases fuel₁ <;> cases fuel₂ <;> try contradiction simp only [toDigitsCore, Nat.div_eq_zero_iff] split · simp · have := Nat.div_lt_self (by omega : 0 < n) hb exact toDigitsCore_eq_of_lt_fuel hb (by omega) (by omega) private theorem toDigitsCore_toDigitsCore (hb : 1 < b) (hn : 0 < n) (hd : d < b) (hf : b * n + d < fuel) (hnf : n < nf) (hdf : d < df) : toDigitsCore b nf n (toDigitsCore b df d cs) = toDigitsCore b fuel (b * n + d) cs := by cases fuel with | zero => contradiction | succ fuel => rw [toDigitsCore] split case isTrue h => have : b ≤ b * n + d := Nat.le_trans (Nat.le_mul_of_pos_right _ hn) (le_add_right _ _) cases Nat.div_eq_zero_iff.mp h <;> omega case isFalse => have h : (b * n + d) / b = n := by rw [mul_add_div (by omega), Nat.div_eq_zero_iff.mpr (.inr hd), Nat.add_zero] have := (Nat.lt_mul_iff_one_lt_left hn).mpr hb simp only [toDigitsCore_of_lt_base hd hdf, mul_add_mod_self_left, mod_eq_of_lt hd, h] apply toDigitsCore_eq_of_lt_fuel hb hnf (by omega) theorem toDigits_append_toDigits (hb : 1 < b) (hn : 0 < n) (hd : d < b) : (toDigits b n) ++ (toDigits b d) = toDigits b (b * n + d) := by rw [toDigits, toDigitsCore_append] exact toDigitsCore_toDigitsCore hb hn hd (lt_succ_self _) (lt_succ_self _) (lt_succ_self _)
.lake/packages/batteries/Batteries/Data/Nat/Basic.lean
module @[expose] public section namespace Nat /-- Recursor identical to `Nat.recOn` but uses notations `0` for `Nat.zero` and `·+1` for `Nat.succ` -/ @[elab_as_elim] protected def recAuxOn {motive : Nat → Sort _} (t : Nat) (zero : motive 0) (succ : ∀ n, motive n → motive (n+1)) : motive t := Nat.recAux zero succ t /-- Strong recursor for `Nat` -/ @[elab_as_elim] protected def strongRec {motive : Nat → Sort _} (ind : ∀ n, (∀ m, m < n → motive m) → motive n) (t : Nat) : motive t := ind t fun m _ => Nat.strongRec ind m /-- Strong recursor via a `Nat`-valued measure -/ @[elab_as_elim] def strongRecMeasure (f : α → Nat) {motive : α → Sort _} (ind : ∀ x, (∀ y, f y < f x → motive y) → motive x) (x : α) : motive x := ind x fun y _ => strongRecMeasure f ind y termination_by f x /-- Simple diagonal recursor for `Nat` -/ @[elab_as_elim] protected def recDiagAux {motive : Nat → Nat → Sort _} (zero_left : ∀ n, motive 0 n) (zero_right : ∀ m, motive m 0) (succ_succ : ∀ m n, motive m n → motive (m+1) (n+1)) : (m n : Nat) → motive m n | 0, _ => zero_left _ | _, 0 => zero_right _ | _+1, _+1 => succ_succ _ _ (Nat.recDiagAux zero_left zero_right succ_succ _ _) /-- Diagonal recursor for `Nat` -/ @[elab_as_elim] protected def recDiag {motive : Nat → Nat → Sort _} (zero_zero : motive 0 0) (zero_succ : ∀ n, motive 0 n → motive 0 (n+1)) (succ_zero : ∀ m, motive m 0 → motive (m+1) 0) (succ_succ : ∀ m n, motive m n → motive (m+1) (n+1)) : (m n : Nat) → motive m n := Nat.recDiagAux left right succ_succ where /-- Left leg for `Nat.recDiag` -/ left : ∀ n, motive 0 n | 0 => zero_zero | _+1 => zero_succ _ (left _) /-- Right leg for `Nat.recDiag` -/ right : ∀ m, motive m 0 | 0 => zero_zero | _+1 => succ_zero _ (right _) /-- Diagonal recursor for `Nat` -/ @[elab_as_elim] protected def recDiagOn {motive : Nat → Nat → Sort _} (m n : Nat) (zero_zero : motive 0 0) (zero_succ : ∀ n, motive 0 n → motive 0 (n+1)) (succ_zero : ∀ m, motive m 0 → motive (m+1) 0) (succ_succ : ∀ m n, motive m n → motive (m+1) (n+1)) : motive m n := Nat.recDiag zero_zero zero_succ succ_zero succ_succ m n /-- Diagonal recursor for `Nat` -/ @[elab_as_elim] protected def casesDiagOn {motive : Nat → Nat → Sort _} (m n : Nat) (zero_zero : motive 0 0) (zero_succ : ∀ n, motive 0 (n+1)) (succ_zero : ∀ m, motive (m+1) 0) (succ_succ : ∀ m n, motive (m+1) (n+1)) : motive m n := Nat.recDiag zero_zero (fun _ _ => zero_succ _) (fun _ _ => succ_zero _) (fun _ _ _ => succ_succ _ _) m n /-- Integer square root function. Implemented via Newton's method. -/ def sqrt (n : Nat) : Nat := if n ≤ 1 then n else iter n (1 <<< ((n.log2 / 2) + 1)) where /-- Auxiliary for `sqrt`. If `guess` is greater than the integer square root of `n`, returns the integer square root of `n`. -/ iter (n guess : Nat) : Nat := let next := (guess + n / guess) / 2 if _h : next < guess then iter n next else guess termination_by guess /-- Construct a natural number from a sequence of bits using little endian convention. -/ @[inline] def ofBits (f : Fin n → Bool) : Nat := Fin.foldr n (fun i v => 2 * v + (f i).toNat) 0 -- Forward port of lean4#10739 instance {n : Nat} : NeZero (n^0) := ⟨Nat.one_ne_zero⟩
.lake/packages/batteries/Batteries/Data/Nat/Bisect.lean
module public import Batteries.Tactic.Basic @[expose] public section namespace Nat /-- Average of two natural numbers rounded toward zero. -/ abbrev avg (a b : Nat) := (a + b) / 2 theorem avg_comm (a b : Nat) : avg a b = avg b a := by rw [avg, Nat.add_comm] theorem avg_le_left (h : b ≤ a) : avg a b ≤ a := by apply Nat.div_le_of_le_mul; simp +arith [*] theorem avg_le_right (h : a ≤ b) : avg a b ≤ b := by apply Nat.div_le_of_le_mul; simp +arith [*] theorem avg_lt_left (h : b < a) : avg a b < a := by apply Nat.div_lt_of_lt_mul; omega theorem avg_lt_right (h : a < b) : avg a b < b := by apply Nat.div_lt_of_lt_mul; omega theorem le_avg_left (h : a ≤ b) : a ≤ avg a b := by apply (Nat.le_div_iff_mul_le Nat.zero_lt_two).mpr; simp +arith [*] theorem le_avg_right (h : b ≤ a) : b ≤ avg a b := by apply (Nat.le_div_iff_mul_le Nat.zero_lt_two).mpr; simp +arith [*] theorem le_add_one_of_avg_eq_left (h : avg a b = a) : b ≤ a + 1 := by cases Nat.lt_or_ge b (a+2) with | inl hlt => exact Nat.le_of_lt_add_one hlt | inr hge => absurd Nat.lt_irrefl a conv => rhs; rw [← h] rw [← Nat.add_one_le_iff, Nat.le_div_iff_mul_le Nat.zero_lt_two] omega theorem le_add_one_of_avg_eq_right (h : avg a b = b) : a ≤ b + 1 := by cases Nat.lt_or_ge a (b+2) with | inl hlt => exact Nat.le_of_lt_add_one hlt | inr hge => absurd Nat.lt_irrefl b conv => rhs; rw [← h] rw [← Nat.add_one_le_iff, Nat.le_div_iff_mul_le Nat.zero_lt_two] omega /-- Given natural numbers `a < b` such that `p a = true` and `p b = false`, `bisect` finds a natural number `a ≤ c < b` such that `p c = true` and `p (c+1) = false`. -/ def bisect {p : Nat → Bool} (h : start < stop) (hstart : p start = true) (hstop : p stop = false) := let mid := avg start stop have hmidstop : mid < stop := by apply Nat.div_lt_of_lt_mul; omega if hstartmid : start < mid then match hmid : p mid with | false => bisect hstartmid hstart hmid | true => bisect hmidstop hmid hstop else mid termination_by stop - start theorem bisect_lt_stop {p : Nat → Bool} (h : start < stop) (hstart : p start = true) (hstop : p stop = false) : bisect h hstart hstop < stop := by unfold bisect simp only; split · split · next h' _ => have : avg start stop - start < stop - start := by apply Nat.sub_lt_sub_right · exact Nat.le_of_lt h' · exact Nat.avg_lt_right h apply Nat.lt_trans · exact bisect_lt_stop .. · exact avg_lt_right h · exact bisect_lt_stop .. · exact avg_lt_right h theorem start_le_bisect {p : Nat → Bool} (h : start < stop) (hstart : p start = true) (hstop : p stop = false) : start ≤ bisect h hstart hstop := by unfold bisect simp only; split · split · next h' _ => have : avg start stop - start < stop - start := by apply Nat.sub_lt_sub_right · exact Nat.le_of_lt h' · exact avg_lt_right h exact start_le_bisect .. · next h' _ => apply Nat.le_trans · exact Nat.le_of_lt h' · exact start_le_bisect .. · exact le_avg_left (Nat.le_of_lt h) theorem bisect_true {p : Nat → Bool} (h : start < stop) (hstart : p start = true) (hstop : p stop = false) : p (bisect h hstart hstop) = true := by unfold bisect simp only; split · split · have : avg start stop - start < stop - start := by apply Nat.sub_lt_sub_right · exact Nat.le_avg_left (Nat.le_of_lt h) · exact Nat.avg_lt_right h exact bisect_true .. · exact bisect_true .. · next h' => rw [← hstart]; congr apply Nat.le_antisymm · exact Nat.le_of_not_gt h' · exact Nat.le_avg_left (Nat.le_of_lt h) theorem bisect_add_one_false {p : Nat → Bool} (h : start < stop) (hstart : p start = true) (hstop : p stop = false) : p (bisect h hstart hstop + 1) = false := by unfold bisect simp only; split · split · have : avg start stop - start < stop - start := by apply Nat.sub_lt_sub_right · exact Nat.le_avg_left (Nat.le_of_lt h) · exact Nat.avg_lt_right h exact bisect_add_one_false .. · exact bisect_add_one_false .. · next h' => have heq : avg start stop = start := by apply Nat.le_antisymm · exact Nat.le_of_not_gt h' · exact Nat.le_avg_left (Nat.le_of_lt h) rw [← hstop, heq]; congr apply Nat.le_antisymm · exact Nat.succ_le_of_lt h · exact Nat.le_add_one_of_avg_eq_left heq
.lake/packages/batteries/Batteries/Data/Rat/Float.lean
module public import Batteries.Lean.Float @[expose] public section /-! # Rational Numbers and Float -/ namespace Rat /-- Convert this rational number to a `Float` value. -/ protected def toFloat (a : Rat) : Float := a.num.divFloat a.den /-- Convert this floating point number to a rational value. -/ protected def _root_.Float.toRat? (a : Float) : Option Rat := a.toRatParts.map fun (v, exp) => mkRat (v.sign * v.natAbs <<< exp.toNat) (1 <<< (-exp).toNat) /-- Convert this floating point number to a rational value, mapping non-finite values (`inf`, `-inf`, `nan`) to 0. -/ protected def _root_.Float.toRat0 (a : Float) : Rat := a.toRat?.getD 0 instance : Coe Rat Float := ⟨Rat.toFloat⟩ end Rat
.lake/packages/batteries/Batteries/Data/HashMap/Basic.lean
module public import Batteries.Lean.HashMap public import Batteries.Tactic.Alias @[expose] public section namespace Std.HashMap variable [BEq α] [Hashable α] /-- Given a key `a`, returns a key-value pair in the map whose key compares equal to `a`. Note that the returned key may not be identical to the input, if `==` ignores some part of the value. ``` def hashMap := ofList [("one", 1), ("two", 2)] hashMap.findEntry? "one" = some ("one", 1) hashMap.findEntry? "three" = none ``` -/ -- This could be given a more efficient low level implementation. @[inline] def findEntry? [BEq α] [Hashable α] (m : Std.HashMap α β) (k : α) : Option (α × β) := if h : k ∈ m then some (m.getKey k h, m.get k h) else none /-- Variant of `ofList` which accepts a function that combines values of duplicated keys. ``` ofListWith [("one", 1), ("one", 2)] (fun v₁ v₂ => v₁ + v₂) = {"one" => 3} ``` -/ def ofListWith [BEq α] [Hashable α] (l : List (α × β)) (f : β → β → β) : HashMap α β := l.foldl (init := ∅) fun m p => match m[p.1]? with | none => m.insert p.1 p.2 | some v => m.insert p.1 <| f v p.2 end Std.HashMap namespace Batteries.HashMap @[reducible, deprecated (since := "2025-05-31")] alias LawfulHashable := LawfulHashable /-- `HashMap α β` is a key-value map which stores elements in an array using a hash function to find the values. This allows it to have very good performance for lookups (average `O(1)` for a perfectly random hash function), but it is not a persistent data structure, meaning that one should take care to use the map linearly when performing updates. Copies are `O(n)`. -/ @[deprecated Std.HashMap (since := "2025-04-09")] structure _root_.Batteries.HashMap (α : Type u) (β : Type v) [BEq α] [Hashable α] where /-- The inner `Std.HashMap` powering the `Batteries.HashMap`. -/ inner : Std.HashMap α β set_option linter.deprecated false /-- Make a new hash map with the specified capacity. -/ @[inline] def _root_.Batteries.mkHashMap [BEq α] [Hashable α] (capacity := 0) : HashMap α β := ⟨.emptyWithCapacity capacity, .emptyWithCapacity⟩ instance [BEq α] [Hashable α] : Inhabited (HashMap α β) where default := mkHashMap instance [BEq α] [Hashable α] : EmptyCollection (HashMap α β) := ⟨mkHashMap⟩ /-- Make a new empty hash map. ``` (empty : Batteries.HashMap Int Int).toList = [] ``` -/ @[inline] def empty [BEq α] [Hashable α] : HashMap α β := mkHashMap variable {_ : BEq α} {_ : Hashable α} /-- The number of elements in the hash map. ``` (ofList [("one", 1), ("two", 2)]).size = 2 ``` -/ @[inline] def size (self : HashMap α β) : Nat := self.inner.size /-- Is the map empty? ``` (empty : Batteries.HashMap Int Int).isEmpty = true (ofList [("one", 1), ("two", 2)]).isEmpty = false ``` -/ @[inline] def isEmpty (self : HashMap α β) : Bool := self.inner.isEmpty /-- Inserts key-value pair `a, b` into the map. If an element equal to `a` is already in the map, it is replaced by `b`. ``` def hashMap := ofList [("one", 1), ("two", 2)] hashMap.insert "three" 3 = {"one" => 1, "two" => 2, "three" => 3} hashMap.insert "two" 0 = {"one" => 1, "two" => 0} ``` -/ @[inline] def insert (self : HashMap α β) (a : α) (b : β) : HashMap α β := ⟨Std.HashMap.insert self.inner a b⟩ /-- Similar to `insert`, but also returns a boolean flag indicating whether an existing entry has been replaced with `a => b`. ``` def hashMap := ofList [("one", 1), ("two", 2)] hashMap.insert' "three" 3 = ({"one" => 1, "two" => 2, "three" => 3}, false) hashMap.insert' "two" 0 = ({"one" => 1, "two" => 0}, true) ``` -/ @[inline] def insert' (m : HashMap α β) (a : α) (b : β) : HashMap α β × Bool := let ⟨contains, insert⟩ := m.inner.containsThenInsert a b ⟨⟨insert⟩, contains⟩ /-- Removes key `a` from the map. If it does not exist in the map, the map is returned unchanged. ``` def hashMap := ofList [("one", 1), ("two", 2)] hashMap.erase "one" = {"two" => 2} hashMap.erase "three" = {"one" => 1, "two" => 2} ``` -/ @[inline] def erase (self : HashMap α β) (a : α) : HashMap α β := ⟨self.inner.erase a⟩ /-- Performs an in-place edit of the value, ensuring that the value is used linearly. The function `f` is passed the original key of the entry, along with the value in the map. ``` (ofList [("one", 1), ("two", 2)]).modify "one" (fun _ v => v + 1) = {"one" => 2, "two" => 2} (ofList [("one", 1), ("two", 2)]).modify "three" (fun _ v => v + 1) = {"one" => 1, "two" => 2} ``` -/ @[inline] def modify (self : HashMap α β) (a : α) (f : α → β → β) : HashMap α β := ⟨self.inner.modify a (f a)⟩ /-- Looks up an element in the map with key `a`. ``` def hashMap := ofList [("one", 1), ("two", 2)] hashMap.find? "one" = some 1 hashMap.find? "three" = none ``` -/ @[inline] def find? (self : HashMap α β) (a : α) : Option β := self.inner[a]? /-- Looks up an element in the map with key `a`. Returns `b₀` if the element is not found. ``` def hashMap := ofList [("one", 1), ("two", 2)] hashMap.findD "one" 0 = 1 hashMap.findD "three" 0 = 0 ``` -/ @[inline] def findD (self : HashMap α β) (a : α) (b₀ : β) : β := self.inner.getD a b₀ /-- Looks up an element in the map with key `a`. Panics if the element is not found. ``` def hashMap := ofList [("one", 1), ("two", 2)] hashMap.find! "one" = 1 hashMap.find! "three" => panic! ``` -/ @[inline] def find! [Inhabited β] (self : HashMap α β) (a : α) : β := self.inner.getD a (panic! "key is not in the map") instance : GetElem (HashMap α β) α (Option β) fun _ _ => True where getElem m k _ := m.inner[k]? /-- Given a key `a`, returns a key-value pair in the map whose key compares equal to `a`. Note that the returned key may not be identical to the input, if `==` ignores some part of the value. ``` def hashMap := ofList [("one", 1), ("two", 2)] hashMap.findEntry? "one" = some ("one", 1) hashMap.findEntry? "three" = none ``` -/ -- This could be given a more efficient low level implementation. @[inline] def findEntry? [BEq α] [Hashable α] (m : HashMap α β) (k : α) : Option (α × β) := m.inner.findEntry? k /-- Returns true if the element `a` is in the map. ``` def hashMap := ofList [("one", 1), ("two", 2)] hashMap.contains "one" = true hashMap.contains "three" = false ``` -/ @[inline] def contains (self : HashMap α β) (a : α) : Bool := self.inner.contains a /-- Folds a monadic function over the elements in the map (in arbitrary order). ``` def sumEven (sum: Nat) (k : String) (v : Nat) : Except String Nat := if v % 2 == 0 then pure (sum + v) else throw s!"value {v} at key {k} is not even" foldM sumEven 0 (ofList [("one", 1), ("three", 3)]) = Except.error "value 3 at key three is not even" foldM sumEven 0 (ofList [("two", 2), ("four", 4)]) = Except.ok 6 ``` -/ @[inline] def foldM [Monad m] (f : δ → α → β → m δ) (init : δ) (self : HashMap α β) : m δ := Std.HashMap.foldM f init self.inner /-- Folds a function over the elements in the map (in arbitrary order). ``` fold (fun sum _ v => sum + v) 0 (ofList [("one", 1), ("two", 2)]) = 3 ``` -/ @[inline] def fold (f : δ → α → β → δ) (init : δ) (self : HashMap α β) : δ := Std.HashMap.fold f init self.inner /-- Combines two hashmaps using a monadic function `f` to combine two values at a key. ``` def map1 := ofList [("one", 1), ("two", 2)] def map2 := ofList [("two", 2), ("three", 3)] def map3 := ofList [("two", 3), ("three", 3)] def mergeIfNoConflict? (_ : String) (v₁ v₂ : Nat) : Option Nat := if v₁ != v₂ then none else some v₁ mergeWithM mergeIfNoConflict? map1 map2 = some {"one" => 1, "two" => 2, "three" => 3} mergeWithM mergeIfNoConflict? map1 map3 = none ``` -/ @[specialize] def mergeWithM [Monad m] (f : α → β → β → m β) (self other : HashMap α β) : m (HashMap α β) := HashMap.mk <$> self.inner.mergeWithM f other.inner /-- Combines two hashmaps using function `f` to combine two values at a key. ``` mergeWith (fun _ v₁ v₂ => v₁ + v₂ ) (ofList [("one", 1), ("two", 2)]) (ofList [("two", 2), ("three", 3)]) = {"one" => 1, "two" => 4, "three" => 3} ``` -/ @[inline] def mergeWith (f : α → β → β → β) (self other : HashMap α β) : HashMap α β := ⟨self.inner.mergeWith f other.inner⟩ /-- Runs a monadic function over the elements in the map (in arbitrary order). ``` def checkEven (k : String) (v : Nat) : Except String Unit := if v % 2 == 0 then pure () else throw s!"value {v} at key {k} is not even" forM checkEven (ofList [("one", 1), ("three", 3)]) = Except.error "value 3 at key three is not even" forM checkEven (ofList [("two", 2), ("four", 4)]) = Except.ok () ``` -/ @[inline] def forM [Monad m] (f : α → β → m PUnit) (self : HashMap α β) : m PUnit := Std.HashMap.forM f self.inner /-- Converts the map into a list of key-value pairs. ``` open List (ofList [("one", 1), ("two", 2)]).toList ~ [("one", 1), ("two", 2)] ``` -/ def toList (self : HashMap α β) : List (α × β) := self.inner.toList /-- Converts the map into an array of key-value pairs. ``` open List (ofList [("one", 1), ("two", 2)]).toArray.data ~ #[("one", 1), ("two", 2)].data ``` -/ def toArray (self : HashMap α β) : Array (α × β) := self.inner.toArray /-- The number of buckets in the hash map. -/ def numBuckets (self : HashMap α β) : Nat := Std.HashMap.Internal.numBuckets self.inner /-- Builds a `HashMap` from a list of key-value pairs. Values of duplicated keys are replaced by their respective last occurrences. ``` ofList [("one", 1), ("one", 2)] = {"one" => 2} ``` -/ def ofList [BEq α] [Hashable α] (l : List (α × β)) : HashMap α β := ⟨Std.HashMap.ofList l⟩ /-- Variant of `ofList` which accepts a function that combines values of duplicated keys. ``` ofListWith [("one", 1), ("one", 2)] (fun v₁ v₂ => v₁ + v₂) = {"one" => 3} ``` -/ def ofListWith [BEq α] [Hashable α] (l : List (α × β)) (f : β → β → β) : HashMap α β := ⟨Std.HashMap.ofListWith l f⟩
.lake/packages/batteries/Batteries/Data/List/Count.lean
module @[expose] public section /-! # Counting in lists This file proves basic properties of `List.countP` and `List.count`, which count the number of elements of a list satisfying a predicate and equal to a given element respectively. Their definitions can be found in `Batteries.Data.List.Basic`. -/ open Nat namespace List /-! ### count -/ section count variable [DecidableEq α] theorem count_singleton' (a b : α) : count a [b] = if b = a then 1 else 0 := by simp [count_cons] theorem count_concat (a : α) (l : List α) : count a (concat l a) = succ (count a l) := by simp
.lake/packages/batteries/Batteries/Data/List/Lemmas.lean
module public import Batteries.Control.ForInStep.Lemmas public import Batteries.Data.List.Basic public import Batteries.Tactic.Alias @[expose] public section namespace List /-! ### toArray-/ @[deprecated List.getElem_toArray (since := "2025-09-11")] theorem getElem_mk {xs : List α} {i : Nat} (h : i < xs.length) : (Array.mk xs)[i] = xs[i] := List.getElem_toArray h /-! ### next? -/ @[simp, grind =] theorem next?_nil : @next? α [] = none := rfl @[simp, grind =] theorem next?_cons (a l) : @next? α (a :: l) = some (a, l) := rfl /-! ### dropLast -/ theorem dropLast_eq_eraseIdx {xs : List α} {i : Nat} (last_idx : i + 1 = xs.length) : xs.dropLast = List.eraseIdx xs i := by ext grind /-! ### set -/ theorem set_eq_modify (a : α) : ∀ n (l : List α), l.set n a = l.modify n (fun _ => a) | 0, l => by cases l <;> rfl | _+1, [] => rfl | _+1, _ :: _ => congrArg (cons _) (set_eq_modify _ _ _) theorem set_eq_take_cons_drop (a : α) {n l} (h : n < length l) : set l n a = take n l ++ a :: drop (n + 1) l := by rw [set_eq_modify, modify_eq_take_cons_drop h] theorem modify_eq_set_getElem? (f : α → α) : ∀ n (l : List α), l.modify n f = ((fun a => l.set n (f a)) <$> l[n]?).getD l | 0, l => by cases l <;> simp | _+1, [] => rfl | n+1, b :: l => (congrArg (cons _) (modify_eq_set_getElem? ..)).trans <| by cases h : l[n]? <;> simp [h] @[deprecated (since := "2025-02-15")] alias modify_eq_set_get? := modify_eq_set_getElem? theorem modify_eq_set_get (f : α → α) {n} {l : List α} (h) : l.modify n f = l.set n (f (l.get ⟨n, h⟩)) := by rw [modify_eq_set_getElem?, getElem?_eq_getElem h]; rfl theorem getElem?_set_eq_of_lt (a : α) {n} {l : List α} (h : n < length l) : (set l n a)[n]? = some a := by rw [getElem?_set_self', getElem?_eq_getElem h]; rfl theorem getElem?_set_of_lt (a : α) {m n} (l : List α) (h : n < length l) : (set l m a)[n]? = if m = n then some a else l[n]? := by simp [getElem?_set', getElem?_eq_getElem h] @[deprecated (since := "2025-02-15")] alias get?_set_of_lt := getElem?_set_of_lt theorem getElem?_set_of_lt' (a : α) {m n} (l : List α) (h : m < length l) : (set l m a)[n]? = if m = n then some a else l[n]? := by simp [getElem?_set]; split <;> subst_vars <;> simp [*] @[deprecated (since := "2025-02-15")] alias get?_set_of_lt' := getElem?_set_of_lt' /-! ### tail -/ theorem length_tail_add_one (l : List α) (h : 0 < length l) : (length (tail l)) + 1 = length l := by grind /-! ### eraseP -/ @[simp] theorem extractP_eq_find?_eraseP (l : List α) : extractP p l = (find? p l, eraseP p l) := by suffices ∀ (acc) (xs) (h : l = acc.toList ++ xs), extractP.go p l xs acc = (xs.find? p, acc.toList ++ xs.eraseP p) from this #[] _ rfl intros fun_induction extractP.go with grind /-! ### erase -/ theorem erase_eq_self_iff_forall_bne [BEq α] (a : α) (xs : List α) : xs.erase a = xs ↔ ∀ (x : α), x ∈ xs → ¬x == a := by rw [erase_eq_eraseP', eraseP_eq_self_iff] /-! ### findIdx? -/ theorem findIdx_eq_findIdx? (p : α → Bool) (l : List α) : l.findIdx p = (match l.findIdx? p with | some i => i | none => l.length) := by grind /-! ### replaceF -/ theorem replaceF_nil : [].replaceF p = [] := rfl theorem replaceF_cons (a : α) (l : List α) : (a :: l).replaceF p = match p a with | none => a :: replaceF p l | some a' => a' :: l := rfl theorem replaceF_cons_of_some {l : List α} (p) (h : p a = some a') : (a :: l).replaceF p = a' :: l := by simp [h] theorem replaceF_cons_of_none {l : List α} (p) (h : p a = none) : (a :: l).replaceF p = a :: l.replaceF p := by simp [h] theorem replaceF_of_forall_none {l : List α} (h : ∀ a, a ∈ l → p a = none) : l.replaceF p = l := by induction l with | nil => rfl | cons _ _ ih => simp [h _ (.head ..), ih (forall_mem_cons.1 h).2] theorem exists_of_replaceF : ∀ {l : List α} {a a'} (_ : a ∈ l) (_ : p a = some a'), ∃ a a' l₁ l₂, (∀ b ∈ l₁, p b = none) ∧ p a = some a' ∧ l = l₁ ++ a :: l₂ ∧ l.replaceF p = l₁ ++ a' :: l₂ | b :: l, _, _, al, pa => match pb : p b with | some b' => ⟨b, b', [], l, forall_mem_nil _, pb, by simp [pb]⟩ | none => match al with | .head .. => nomatch pb.symm.trans pa | .tail _ al => let ⟨c, c', l₁, l₂, h₁, h₂, h₃, h₄⟩ := exists_of_replaceF al pa ⟨c, c', b::l₁, l₂, (forall_mem_cons ..).2 ⟨pb, h₁⟩, h₂, by rw [h₃, cons_append], by simp [pb, h₄]⟩ theorem exists_or_eq_self_of_replaceF (p) (l : List α) : l.replaceF p = l ∨ ∃ a a' l₁ l₂, (∀ b ∈ l₁, p b = none) ∧ p a = some a' ∧ l = l₁ ++ a :: l₂ ∧ l.replaceF p = l₁ ++ a' :: l₂ := if h : ∃ a ∈ l, (p a).isSome then let ⟨_, ha, pa⟩ := h .inr (exists_of_replaceF ha (Option.get_mem pa)) else .inl <| replaceF_of_forall_none fun a ha => Option.not_isSome_iff_eq_none.1 fun h' => h ⟨a, ha, h'⟩ @[simp] theorem length_replaceF : length (replaceF f l) = length l := by induction l <;> simp [replaceF]; split <;> simp [*] /-! ### disjoint -/ theorem disjoint_symm (d : Disjoint l₁ l₂) : Disjoint l₂ l₁ := fun _ i₂ i₁ => d i₁ i₂ theorem disjoint_comm : Disjoint l₁ l₂ ↔ Disjoint l₂ l₁ := ⟨disjoint_symm, disjoint_symm⟩ theorem disjoint_left : Disjoint l₁ l₂ ↔ ∀ ⦃a⦄, a ∈ l₁ → a ∉ l₂ := by simp [Disjoint] theorem disjoint_right : Disjoint l₁ l₂ ↔ ∀ ⦃a⦄, a ∈ l₂ → a ∉ l₁ := disjoint_comm theorem disjoint_iff_ne : Disjoint l₁ l₂ ↔ ∀ a ∈ l₁, ∀ b ∈ l₂, a ≠ b := ⟨fun h _ al1 _ bl2 ab => h al1 (ab ▸ bl2), fun h _ al1 al2 => h _ al1 _ al2 rfl⟩ theorem disjoint_of_subset_left (ss : l₁ ⊆ l) (d : Disjoint l l₂) : Disjoint l₁ l₂ := fun _ m => d (ss m) theorem disjoint_of_subset_right (ss : l₂ ⊆ l) (d : Disjoint l₁ l) : Disjoint l₁ l₂ := fun _ m m₁ => d m (ss m₁) theorem disjoint_of_disjoint_cons_left {l₁ l₂} : Disjoint (a :: l₁) l₂ → Disjoint l₁ l₂ := disjoint_of_subset_left (subset_cons_self _ _) theorem disjoint_of_disjoint_cons_right {l₁ l₂} : Disjoint l₁ (a :: l₂) → Disjoint l₁ l₂ := disjoint_of_subset_right (subset_cons_self _ _) @[simp] theorem disjoint_nil_left (l : List α) : Disjoint [] l := fun _ => not_mem_nil.elim @[simp] theorem disjoint_nil_right (l : List α) : Disjoint l [] := by rw [disjoint_comm]; exact disjoint_nil_left _ @[simp 1100] theorem singleton_disjoint : Disjoint [a] l ↔ a ∉ l := by simp [Disjoint] @[simp 1100] theorem disjoint_singleton : Disjoint l [a] ↔ a ∉ l := by rw [disjoint_comm, singleton_disjoint] @[simp] theorem disjoint_append_left : Disjoint (l₁ ++ l₂) l ↔ Disjoint l₁ l ∧ Disjoint l₂ l := by simp [Disjoint, or_imp, forall_and] @[simp] theorem disjoint_append_right : Disjoint l (l₁ ++ l₂) ↔ Disjoint l l₁ ∧ Disjoint l l₂ := disjoint_comm.trans <| by rw [disjoint_append_left]; simp [disjoint_comm] @[simp] theorem disjoint_cons_left : Disjoint (a::l₁) l₂ ↔ (a ∉ l₂) ∧ Disjoint l₁ l₂ := (disjoint_append_left (l₁ := [a])).trans <| by simp [singleton_disjoint] @[simp] theorem disjoint_cons_right : Disjoint l₁ (a :: l₂) ↔ (a ∉ l₁) ∧ Disjoint l₁ l₂ := disjoint_comm.trans <| by rw [disjoint_cons_left]; simp [disjoint_comm] theorem disjoint_of_disjoint_append_left_left (d : Disjoint (l₁ ++ l₂) l) : Disjoint l₁ l := (disjoint_append_left.1 d).1 theorem disjoint_of_disjoint_append_left_right (d : Disjoint (l₁ ++ l₂) l) : Disjoint l₂ l := (disjoint_append_left.1 d).2 theorem disjoint_of_disjoint_append_right_left (d : Disjoint l (l₁ ++ l₂)) : Disjoint l l₁ := (disjoint_append_right.1 d).1 theorem disjoint_of_disjoint_append_right_right (d : Disjoint l (l₁ ++ l₂)) : Disjoint l l₂ := (disjoint_append_right.1 d).2 /-! ### union -/ section union variable [BEq α] theorem union_def (l₁ l₂ : List α) : l₁ ∪ l₂ = foldr .insert l₂ l₁ := rfl @[simp, grind =] theorem nil_union (l : List α) : nil ∪ l = l := by simp [List.union_def, foldr] @[simp, grind =] theorem cons_union (a : α) (l₁ l₂ : List α) : (a :: l₁) ∪ l₂ = (l₁ ∪ l₂).insert a := by simp [List.union_def, foldr] @[simp, grind =] theorem mem_union_iff [LawfulBEq α] {x : α} {l₁ l₂ : List α} : x ∈ l₁ ∪ l₂ ↔ x ∈ l₁ ∨ x ∈ l₂ := by induction l₁ <;> simp [*, or_assoc] end union /-! ### inter -/ theorem inter_def [BEq α] (l₁ l₂ : List α) : l₁ ∩ l₂ = filter (elem · l₂) l₁ := rfl @[simp, grind =] theorem mem_inter_iff [BEq α] [LawfulBEq α] {x : α} {l₁ l₂ : List α} : x ∈ l₁ ∩ l₂ ↔ x ∈ l₁ ∧ x ∈ l₂ := by cases l₁ <;> simp [List.inter_def, mem_filter] /-! ### product -/ /-- List.prod satisfies a specification of cartesian product on lists. -/ @[simp] theorem pair_mem_product {xs : List α} {ys : List β} {x : α} {y : β} : (x, y) ∈ product xs ys ↔ x ∈ xs ∧ y ∈ ys := by simp only [product, mem_map, Prod.mk.injEq, exists_eq_right_right, mem_flatMap, iff_self] /-! ### monadic operations -/ theorem forIn_eq_bindList [Monad m] [LawfulMonad m] (f : α → β → m (ForInStep β)) (l : List α) (init : β) : forIn l init f = ForInStep.run <$> (ForInStep.yield init).bindList f l := by induction l generalizing init <;> simp [*] congr; ext (b | b) <;> simp /-! ### diff -/ section Diff variable [BEq α] @[simp] theorem diff_nil (l : List α) : l.diff [] = l := rfl variable [LawfulBEq α] @[simp] theorem diff_cons (l₁ l₂ : List α) (a : α) : l₁.diff (a :: l₂) = (l₁.erase a).diff l₂ := by simp_all [List.diff, erase_of_not_mem] theorem diff_cons_right (l₁ l₂ : List α) (a : α) : l₁.diff (a :: l₂) = (l₁.diff l₂).erase a := by apply Eq.symm; induction l₂ generalizing l₁ <;> simp [erase_comm, *] theorem diff_erase (l₁ l₂ : List α) (a : α) : (l₁.diff l₂).erase a = (l₁.erase a).diff l₂ := by rw [← diff_cons_right, diff_cons] @[simp] theorem nil_diff (l : List α) : [].diff l = [] := by induction l <;> simp [*, erase_of_not_mem] theorem cons_diff (a : α) (l₁ l₂ : List α) : (a :: l₁).diff l₂ = if a ∈ l₂ then l₁.diff (l₂.erase a) else a :: l₁.diff l₂ := by induction l₂ generalizing l₁ with | nil => rfl | cons b l₂ ih => by_cases h : a = b next => simp [*] next => have := Ne.symm h simp[*] theorem cons_diff_of_mem {a : α} {l₂ : List α} (h : a ∈ l₂) (l₁ : List α) : (a :: l₁).diff l₂ = l₁.diff (l₂.erase a) := by rw [cons_diff, if_pos h] theorem cons_diff_of_not_mem {a : α} {l₂ : List α} (h : a ∉ l₂) (l₁ : List α) : (a :: l₁).diff l₂ = a :: l₁.diff l₂ := by rw [cons_diff, if_neg h] theorem diff_eq_foldl : ∀ l₁ l₂ : List α, l₁.diff l₂ = foldl List.erase l₁ l₂ | _, [] => rfl | l₁, a :: l₂ => (diff_cons l₁ l₂ a).trans (diff_eq_foldl _ _) @[simp] theorem diff_append (l₁ l₂ l₃ : List α) : l₁.diff (l₂ ++ l₃) = (l₁.diff l₂).diff l₃ := by simp only [diff_eq_foldl, foldl_append] theorem diff_sublist : ∀ l₁ l₂ : List α, l₁.diff l₂ <+ l₁ | _, [] => .refl _ | l₁, a :: l₂ => calc l₁.diff (a :: l₂) = (l₁.erase a).diff l₂ := diff_cons .. _ <+ l₁.erase a := diff_sublist .. _ <+ l₁ := erase_sublist .. theorem diff_subset (l₁ l₂ : List α) : l₁.diff l₂ ⊆ l₁ := (diff_sublist ..).subset theorem mem_diff_of_mem {a : α} : ∀ {l₁ l₂ : List α}, a ∈ l₁ → a ∉ l₂ → a ∈ l₁.diff l₂ | _, [], h₁, _ => h₁ | l₁, b :: l₂, h₁, h₂ => by rw [diff_cons] exact mem_diff_of_mem ((mem_erase_of_ne <| ne_of_not_mem_cons h₂).2 h₁) (mt (.tail _) h₂) theorem Sublist.diff_right : ∀ {l₁ l₂ l₃ : List α}, l₁ <+ l₂ → l₁.diff l₃ <+ l₂.diff l₃ | _, _, [], h => h | l₁, l₂, a :: l₃, h => by simp only [diff_cons, (h.erase _).diff_right] theorem Sublist.erase_diff_erase_sublist {a : α} : ∀ {l₁ l₂ : List α}, l₁ <+ l₂ → (l₂.erase a).diff (l₁.erase a) <+ l₂.diff l₁ | [], _, _ => erase_sublist | b :: l₁, l₂, h => by if heq : b = a then simp [heq] else simp [heq, erase_comm a] exact (erase_cons_head b _ ▸ h.erase b).erase_diff_erase_sublist end Diff /-! ### drop -/ theorem disjoint_take_drop : ∀ {l : List α}, l.Nodup → m ≤ n → Disjoint (l.take m) (l.drop n) | [], _, _ => by simp | x :: xs, hl, h => by cases m <;> cases n <;> simp only [disjoint_cons_left, drop, disjoint_nil_left, take] · case succ.zero => cases h · cases hl with | cons h₀ h₁ => refine ⟨fun h => h₀ _ (mem_of_mem_drop h) rfl, ?_⟩ exact disjoint_take_drop h₁ (Nat.le_of_succ_le_succ h) /-! ### Pairwise -/ attribute [simp, grind ←] Pairwise.nil @[grind →] protected theorem Pairwise.isChain (p : Pairwise R l) : IsChain R l := by induction p with | nil => grind | cons _ l => cases l with grind @[grind =] theorem pairwise_cons_cons : Pairwise R (a :: b :: l) ↔ R a b ∧ Pairwise R (a :: l) ∧ Pairwise R (b :: l) := by grind [pairwise_cons] /-! ### IsChain -/ @[deprecated (since := "2025-09-19")] alias chain_cons := isChain_cons_cons theorem rel_of_isChain_cons_cons (p : IsChain R (a :: b :: l)) : R a b := (isChain_cons_cons.1 p).1 @[deprecated (since := "2025-09-19")] alias rel_of_chain_cons := rel_of_isChain_cons_cons theorem isChain_cons_of_isChain_cons_cons (p : IsChain R (a :: b :: l)) : IsChain R (b :: l) := (isChain_cons_cons.1 p).2 @[deprecated (since := "2025-09-19")] alias chain_of_chain_cons := isChain_cons_of_isChain_cons_cons theorem isChain_of_isChain_cons (p : IsChain R (b :: l)) : IsChain R l := by cases l · exact .nil · exact isChain_cons_of_isChain_cons_cons p theorem isChain_of_isChain_cons_cons (p : IsChain R (a :: b :: l)) : IsChain R l := isChain_of_isChain_cons (isChain_of_isChain_cons p) theorem IsChain.imp (H : ∀ ⦃a b : α⦄, R a b → S a b) (p : IsChain R l) : IsChain S l := by induction p with grind @[deprecated (since := "2025-09-19")] alias Chain.imp := IsChain.imp theorem IsChain.cons_of_imp_of_cons (h : ∀ c, R a c → R b c) : IsChain R (a :: l) → IsChain R (b :: l) := by cases l <;> grind @[deprecated "Use IsChain.imp and IsChain.change_head" (since := "2025-09-19")] theorem Chain.imp' (HRS : ∀ ⦃a b : α⦄, R a b → S a b) (Hab : ∀ ⦃c⦄, R a c → S b c) : IsChain R (a :: l) → IsChain S (b :: l) := by cases l with grind [IsChain.imp] @[deprecated (since := "2025-09-19")] protected alias Pairwise.chain := Pairwise.isChain @[grind →] protected theorem IsChain.pairwise [Trans R R R] (c : IsChain R l) : Pairwise R l := by induction c with | nil | singleton => grind | cons_cons hr h p => simp only [pairwise_cons, mem_cons, forall_eq_or_imp] at p ⊢ exact ⟨⟨hr, fun _ ha => Trans.trans hr <| p.1 _ ha⟩, p⟩ theorem isChain_iff_pairwise [Trans R R R] : IsChain R l ↔ Pairwise R l := by grind theorem isChain_iff_getElem {l : List α} : IsChain R l ↔ ∀ (i : Nat) (_hi : i + 1 < l.length), R l[i] l[i + 1] := by induction l with | nil => grind | cons a l IH => cases l with | nil => grind | cons b l => simp [IH, Nat.forall_lt_succ_left'] theorem IsChain.getElem {l : List α} (c : IsChain R l) (i : Nat) (hi : i + 1 < l.length) : R l[i] l[i + 1] := isChain_iff_getElem.mp c _ _ /-! ### range', range -/ theorem isChain_range' (s : Nat) : ∀ n step : Nat, IsChain (fun a b => b = a + step) (range' s n step) | 0, _ => .nil | 1, _ => .singleton _ | n + 2, step => (isChain_range' (s + step) (n + 1) step).cons_cons rfl @[deprecated isChain_range' (since := "2025-09-19")] theorem chain_succ_range' (s n step : Nat) : IsChain (fun a b => b = a + step) (s :: range' (s + step) n step) := isChain_range' _ (n + 1) _ theorem isChain_lt_range' (s n : Nat) (h : 0 < step) : IsChain (· < ·) (range' s n step) := (isChain_range' s n step).imp fun | _, _, rfl => Nat.lt_add_of_pos_right h @[deprecated isChain_lt_range' (since := "2025-09-19")] theorem chain_lt_range' (s n : Nat) (h : 0 < step) : IsChain (· < ·) (s :: range' (s + step) n step) := isChain_lt_range' _ (n + 1) h /-! ### idxOf and idxsOf -/ theorem foldrIdx_start : (xs : List α).foldrIdx f i s = (xs : List α).foldrIdx (fun i => f (i + s)) i := by induction xs generalizing f i s with grind [foldrIdx] @[simp] theorem foldrIdx_cons : (x :: xs : List α).foldrIdx f i s = f s x (foldrIdx f i xs (s + 1)) := rfl theorem findIdxs_cons_aux (p : α → Bool) : foldrIdx (fun i a is => if p a = true then (i + 1) :: is else is) [] xs s = map (· + 1) (foldrIdx (fun i a is => if p a = true then i :: is else is) [] xs s) := by induction xs generalizing s with grind [foldrIdx] theorem findIdxs_cons : (x :: xs : List α).findIdxs p = bif p x then 0 :: (xs.findIdxs p).map (· + 1) else (xs.findIdxs p).map (· + 1) := by dsimp [findIdxs] rw [cond_eq_if] split <;> · simp [foldrIdx_start, Nat.add_zero, true_and] apply findIdxs_cons_aux @[simp, grind =] theorem idxsOf_nil [BEq α] : ([] : List α).idxsOf x = [] := rfl @[grind =] theorem idxsOf_cons [BEq α] : (x :: xs : List α).idxsOf y = bif x == y then 0 :: (xs.idxsOf y).map (· + 1) else (xs.idxsOf y).map (· + 1) := by simp [idxsOf, findIdxs_cons] @[simp] theorem eraseIdx_idxOf_eq_erase [BEq α] (a : α) (l : List α) : l.eraseIdx (l.idxOf a) = l.erase a := by induction l with grind theorem idxOf_mem_idxsOf [BEq α] [LawfulBEq α] {xs : List α} (m : x ∈ xs) : xs.idxOf x ∈ xs.idxsOf x := by induction xs with grind theorem idxOf_eq_idxOf? [BEq α] (a : α) (l : List α) : l.idxOf a = (match l.idxOf? a with | some i => i | none => l.length) := by simp [idxOf, idxOf?, findIdx_eq_findIdx?] /-! ### insertP -/ theorem insertP_loop (a : α) (l r : List α) : insertP.loop p a l r = reverseAux r (insertP p a l) := by induction l generalizing r with simp [insertP, insertP.loop, cond] | cons b l ih => rw [ih (b :: r), ih [b]]; split <;> simp @[simp] theorem insertP_nil (p : α → Bool) (a) : insertP p a [] = [a] := rfl @[simp] theorem insertP_cons_pos (p : α → Bool) (a b l) (h : p b) : insertP p a (b :: l) = a :: b :: l := by simp only [insertP, insertP.loop, cond, h]; rfl @[simp] theorem insertP_cons_neg (p : α → Bool) (a b l) (h : ¬ p b) : insertP p a (b :: l) = b :: insertP p a l := by simp only [insertP, insertP.loop, cond, h]; exact insertP_loop .. @[simp] theorem length_insertP (p : α → Bool) (a l) : (insertP p a l).length = l.length + 1 := by induction l with simp [insertP, insertP.loop, cond] | cons _ _ ih => split <;> simp [insertP_loop, ih] @[simp] theorem mem_insertP (p : α → Bool) (a l) : a ∈ insertP p a l := by induction l with simp [insertP, insertP.loop, cond] | cons _ _ ih => split <;> simp [insertP_loop, ih] /-! ### dropPrefix?, dropSuffix?, dropInfix?-/ open Option @[simp] theorem dropPrefix?_nil [BEq α] {p : List α} : dropPrefix? p [] = some p := by simp [dropPrefix?] theorem dropPrefix?_eq_some_iff [BEq α] {l p s : List α} : dropPrefix? l p = some s ↔ ∃ p', l = p' ++ s ∧ p' == p := by unfold dropPrefix? split · simp · simp · rename_i a as b bs simp only [ite_none_right_eq_some] constructor · rw [dropPrefix?_eq_some_iff] rintro ⟨w, p', rfl, h⟩ refine ⟨a :: p', by simp_all⟩ · rw [dropPrefix?_eq_some_iff] rintro ⟨p, h, w⟩ rw [cons_eq_append_iff] at h obtain (⟨rfl, rfl⟩ | ⟨a', rfl, rfl⟩) := h · simp at w · simp only [cons_beq_cons, Bool.and_eq_true] at w refine ⟨w.1, a', rfl, w.2⟩ theorem dropPrefix?_append_of_beq [BEq α] {l₁ l₂ : List α} (p : List α) (h : l₁ == l₂) : dropPrefix? (l₁ ++ p) l₂ = some p := by simp [dropPrefix?_eq_some_iff, h] theorem dropSuffix?_eq_some_iff [BEq α] {l p s : List α} : dropSuffix? l s = some p ↔ ∃ s', l = p ++ s' ∧ s' == s := by unfold dropSuffix? rw [splitAt_eq] simp only [ite_none_right_eq_some, some.injEq] constructor · rintro ⟨w, rfl⟩ refine ⟨_, by simp, w⟩ · rintro ⟨s', rfl, w⟩ simp [length_eq_of_beq w, w] @[simp] theorem dropSuffix?_nil [BEq α] {s : List α} : dropSuffix? s [] = some s := by simp [dropSuffix?_eq_some_iff] theorem dropInfix?_go_eq_some_iff [BEq α] {i l acc p s : List α} : dropInfix?.go i l acc = some (p, s) ↔ ∃ p', p = acc.reverse ++ p' ∧ -- `i` is an infix up to `==` (∃ i', l = p' ++ i' ++ s ∧ i' == i) ∧ -- and there is no shorter prefix for which that is the case (∀ p'' i'' s'', l = p'' ++ i'' ++ s'' → i'' == i → p''.length ≥ p'.length) := by unfold dropInfix?.go split · simp only [isEmpty_iff, ite_none_right_eq_some, some.injEq, Prod.mk.injEq, nil_eq, append_assoc, append_eq_nil_iff, ge_iff_le, and_imp] constructor · rintro ⟨rfl, rfl, rfl⟩ simp · rintro ⟨p', rfl, ⟨_, ⟨rfl, rfl, rfl⟩, h⟩, w⟩ simp_all · rename_i a t split <;> rename_i h · rw [dropInfix?_go_eq_some_iff] constructor · rintro ⟨p', rfl, ⟨i', rfl, h₂⟩, w⟩ refine ⟨a :: p', ?_⟩ simp [h₂] intro p'' i'' s'' h₁ h₂ rw [cons_eq_append_iff] at h₁ obtain (⟨rfl, h₁⟩ | ⟨p'', rfl, h₁⟩) := h₁ · rw [append_assoc, ← h₁] at h have := dropPrefix?_append_of_beq s'' h₂ simp_all · simpa using w p'' i'' s'' (by simpa using h₁) h₂ · rintro ⟨p', rfl, ⟨i', h₁, h₂⟩, w⟩ rw [cons_eq_append_iff] at h₁ simp at h₁ obtain (⟨⟨rfl, rfl⟩, rfl⟩ | ⟨a', h₁, rfl⟩) := h₁ · simp only [nil_beq_eq, isEmpty_iff] at h₂ simp only [h₂] at h simp at h · rw [append_eq_cons_iff] at h₁ obtain (⟨rfl, rfl⟩ | ⟨p', rfl, rfl⟩) := h₁ · rw [← cons_append] at h have := dropPrefix?_append_of_beq s h₂ simp_all · refine ⟨p', ?_⟩ simp only [reverse_cons, append_assoc, singleton_append, append_cancel_left_eq, append_cancel_right_eq, exists_eq_left', ge_iff_le, true_and] refine ⟨h₂, ?_⟩ intro p'' i'' s'' h₃ h₄ rw [← append_assoc] at h₃ rw [h₃] at w simpa using w (a :: p'') i'' s'' (by simp) h₄ · rename_i s' simp only [some.injEq, Prod.mk.injEq, append_assoc, ge_iff_le] rw [dropPrefix?_eq_some_iff] at h obtain ⟨p', h, w⟩ := h constructor · rintro ⟨rfl, rfl⟩ simpa using ⟨p', by simp_all⟩ · rintro ⟨p'', rfl, ⟨i', h₁, h₂⟩, w'⟩ specialize w' [] p' s' (by simpa using h) w simp at w' simp [w'] at h₁ ⊢ rw [h] at h₁ apply append_inj_right h₁ replace w := length_eq_of_beq w replace h₂ := length_eq_of_beq h₂ simp_all theorem dropInfix?_eq_some_iff [BEq α] {l i p s : List α} : dropInfix? l i = some (p, s) ↔ -- `i` is an infix up to `==` (∃ i', l = p ++ i' ++ s ∧ i' == i) ∧ -- and there is no shorter prefix for which that is the case (∀ p' i' s', l = p' ++ i' ++ s' → i' == i → p'.length ≥ p.length) := by unfold dropInfix? rw [dropInfix?_go_eq_some_iff] simp @[simp] theorem dropInfix?_nil [BEq α] {s : List α} : dropInfix? s [] = some ([], s) := by simp [dropInfix?_eq_some_iff] /-! ### IsPrefixOf?, IsSuffixOf? -/ @[simp] theorem isSome_isPrefixOf?_eq_isPrefixOf [BEq α] (xs ys : List α) : (xs.isPrefixOf? ys).isSome = xs.isPrefixOf ys := by match xs, ys with | [], _ => simp [List.isPrefixOf?] | _::_, [] => rfl | _::_, _::_ => simp only [List.isPrefixOf?, List.isPrefixOf] split <;> simp [*, isSome_isPrefixOf?_eq_isPrefixOf] @[simp] theorem isPrefixOf?_eq_some_iff_append_eq [BEq α] [LawfulBEq α] {xs ys zs : List α} : xs.isPrefixOf? ys = some zs ↔ xs ++ zs = ys := by induction xs generalizing ys with | nil => simp [isPrefixOf?, Eq.comm] | cons => cases ys <;> simp [isPrefixOf?, *] theorem append_eq_of_isPrefixOf?_eq_some [BEq α] [LawfulBEq α] {xs ys zs : List α} (h : xs.isPrefixOf? ys = some zs) : xs ++ zs = ys := by simp_all @[simp] theorem isSome_isSuffixOf?_eq_isSuffixOf [BEq α] (xs ys : List α) : (xs.isSuffixOf? ys).isSome = xs.isSuffixOf ys := by simp [List.isSuffixOf?, isSuffixOf] @[simp] theorem isSuffixOf?_eq_some_iff_append_eq [BEq α] [LawfulBEq α] {xs ys zs : List α} : xs.isSuffixOf? ys = some zs ↔ zs ++ xs = ys := by simp only [isSuffixOf?, map_eq_some_iff, isPrefixOf?_eq_some_iff_append_eq] constructor · intro | ⟨_, h, heq⟩ => rw [List.reverse_eq_iff] at heq rw [heq] at h rw [← reverse_inj, reverse_append, h] · intro h exists zs.reverse simp [← h] theorem append_eq_of_isSuffixOf?_eq_some [BEq α] [LawfulBEq α] {xs ys zs : List α} (h : xs.isSuffixOf? ys = some zs) : zs ++ xs = ys := by simp_all /-! ### sum/prod -/ private theorem foldr_eq_foldl_aux (f : α → α → α) (init : α) [Std.Associative f] [Std.LawfulIdentity f init] {l : List α} : l.foldl f a = f a (l.foldl f init) := by induction l generalizing a with | nil => simp [Std.LawfulRightIdentity.right_id] | cons b l ih => simp [Std.LawfulLeftIdentity.left_id, ih (a := f a b), ih (a := b), Std.Associative.assoc] theorem foldr_eq_foldl (f : α → α → α) (init : α) [Std.Associative f] [Std.LawfulIdentity f init] {l : List α} : l.foldr f init = l.foldl f init := by induction l with | nil => rfl | cons a l ih => simp [ih, Std.LawfulLeftIdentity.left_id, foldr_eq_foldl_aux (a := a)] @[simp, grind =] theorem prod_nil [Mul α] [One α] : ([] : List α).prod = 1 := rfl @[simp, grind =] theorem prod_cons [Mul α] [One α] {a : α} {l : List α} : (a :: l).prod = a * l.prod := rfl theorem prod_one_cons [Mul α] [One α] [Std.LawfulLeftIdentity (α := α) (· * ·) 1] {l : List α} : (1 :: l).prod = l.prod := by simp [Std.LawfulLeftIdentity.left_id] theorem prod_singleton [Mul α] [One α] [Std.LawfulRightIdentity (α := α) (· * ·) 1] {a : α} : [a].prod = a := by simp [Std.LawfulRightIdentity.right_id] theorem prod_pair [Mul α] [One α] [Std.LawfulRightIdentity (α := α) (· * ·) 1] {a b : α} : [a, b].prod = a * b := by simp [Std.LawfulRightIdentity.right_id] @[simp, grind =] theorem prod_append [Mul α] [One α] [Std.LawfulLeftIdentity (α := α) (· * ·) 1] [Std.Associative (α := α) (· * ·)] {l₁ l₂ : List α} : (l₁ ++ l₂).prod = l₁.prod * l₂.prod := by induction l₁ with simp [Std.LawfulLeftIdentity.left_id, Std.Associative.assoc, *] theorem prod_concat [Mul α] [One α] [Std.LawfulIdentity (α := α) (· * ·) 1] [Std.Associative (α := α) (· * ·)] {l : List α} {a : α} : (l.concat a).prod = l.prod * a := by simp [Std.LawfulRightIdentity.right_id] @[simp, grind =] theorem prod_flatten [Mul α] [One α] [Std.LawfulIdentity (α := α) (· * ·) 1] [Std.Associative (α := α) (· * ·)] {l : List (List α)} : l.flatten.prod = (l.map prod).prod := by induction l with simp [*] theorem prod_eq_foldr [Mul α] [One α] {l : List α} : l.prod = l.foldr (· * ·) 1 := rfl theorem prod_eq_foldl [Mul α] [One α] [Std.Associative (α := α) (· * ·)] [Std.LawfulIdentity (α := α) (· * ·) 1] {l : List α} : l.prod = l.foldl (· * ·) 1 := foldr_eq_foldl .. theorem sum_zero_cons [Add α] [Zero α] [Std.LawfulLeftIdentity (α := α) (· + ·) 0] {l : List α} : (0 :: l).sum = l.sum := by simp [Std.LawfulLeftIdentity.left_id] theorem sum_singleton [Add α] [Zero α] [Std.LawfulRightIdentity (α := α) (· + ·) 0] {a : α} : [a].sum = a := by simp [Std.LawfulRightIdentity.right_id] theorem sum_pair [Add α] [Zero α] [Std.LawfulRightIdentity (α := α) (· + ·) 0] {a b : α} : [a, b].sum = a + b := by simp [Std.LawfulRightIdentity.right_id] @[simp, grind =] theorem sum_append [Add α] [Zero α] [Std.LawfulLeftIdentity (α := α) (· + ·) 0] [Std.Associative (α := α) (· + ·)] {l₁ l₂ : List α} : (l₁ ++ l₂).sum = l₁.sum + l₂.sum := by induction l₁ with simp [Std.LawfulLeftIdentity.left_id, Std.Associative.assoc, *] theorem sum_concat [Add α] [Zero α] [Std.LawfulIdentity (α := α) (· + ·) 0] [Std.Associative (α := α) (· + ·)] {l : List α} {a : α} : (l.concat a).sum = l.sum + a := by simp [Std.LawfulRightIdentity.right_id] @[simp, grind =] theorem sum_flatten [Add α] [Zero α] [Std.LawfulIdentity (α := α) (· + ·) 0] [Std.Associative (α := α) (· + ·)] {l : List (List α)} : l.flatten.sum = (l.map sum).sum := by induction l with simp [*] theorem sum_eq_foldr [Add α] [Zero α] {l : List α} : l.sum = l.foldr (· + ·) 0 := rfl theorem sum_eq_foldl [Add α] [Zero α] [Std.Associative (α := α) (· + ·)] [Std.LawfulIdentity (α := α) (· + ·) 0] {l : List α} : l.sum = l.foldl (· + ·) 0 := foldr_eq_foldl ..
.lake/packages/batteries/Batteries/Data/List/Pairwise.lean
module public import Batteries.Data.List.Basic @[expose] public section /-! # Pairwise relations on a list This file provides basic results about `List.Pairwise` and `List.pwFilter` (definitions are in `Batteries.Data.List.Basic`). `Pairwise r [a 0, ..., a (n - 1)]` means `∀ i j, i < j → r (a i) (a j)`. For example, `Pairwise (≠) l` means that all elements of `l` are distinct, and `Pairwise (<) l` means that `l` is strictly increasing. `pwFilter r l` is the list obtained by iteratively adding each element of `l` that doesn't break the pairwiseness of the list we have so far. It thus yields `l'` a maximal sublist of `l` such that `Pairwise r l'`. ## Tags sorted, nodup -/ open Nat Function namespace List /-! ### Pairwise -/ theorem pairwise_iff_get : Pairwise R l ↔ ∀ (i j) (_hij : i < j), R (get l i) (get l j) := by rw [pairwise_iff_getElem] constructor <;> intro h · intros i j h' exact h _ _ _ _ h' · intros i j hi hj h' exact h ⟨i, hi⟩ ⟨j, hj⟩ h' /-! ### Pairwise filtering -/ @[simp] theorem pwFilter_nil [DecidableRel R] : pwFilter R [] = [] := rfl @[simp] theorem pwFilter_cons_of_pos [DecidableRel (α := α) R] {a : α} {l : List α} (h : ∀ b ∈ pwFilter R l, R a b) : pwFilter R (a :: l) = a :: pwFilter R l := if_pos h @[simp] theorem pwFilter_cons_of_neg [DecidableRel (α := α) R] {a : α} {l : List α} (h : ¬∀ b ∈ pwFilter R l, R a b) : pwFilter R (a :: l) = pwFilter R l := if_neg h theorem pwFilter_map [DecidableRel (α := α) R] (f : β → α) : ∀ l : List β, pwFilter R (map f l) = map f (pwFilter (fun x y => R (f x) (f y)) l) | [] => rfl | x :: xs => by if h : ∀ b ∈ pwFilter R (map f xs), R (f x) b then have h' : ∀ b : β, b ∈ pwFilter (fun x y : β => R (f x) (f y)) xs → R (f x) (f b) := fun b hb => h _ (by rw [pwFilter_map f xs]; apply mem_map_of_mem hb) rw [map, pwFilter_cons_of_pos h, pwFilter_cons_of_pos h', pwFilter_map f xs, map] else rw [map, pwFilter_cons_of_neg h, pwFilter_cons_of_neg ?_, pwFilter_map f xs] refine fun hh => h fun a ha => ?_ rw [pwFilter_map f xs, mem_map] at ha let ⟨b, hb₀, hb₁⟩ := ha; exact hb₁ ▸ hh _ hb₀ theorem pwFilter_sublist [DecidableRel (α := α) R] : ∀ l : List α, pwFilter R l <+ l | [] => nil_sublist _ | x :: l => if h : ∀ y ∈ pwFilter R l, R x y then pwFilter_cons_of_pos h ▸ (pwFilter_sublist l).cons₂ _ else pwFilter_cons_of_neg h ▸ Sublist.cons _ (pwFilter_sublist l) theorem pwFilter_subset [DecidableRel (α := α) R] (l : List α) : pwFilter R l ⊆ l := (pwFilter_sublist _).subset theorem pairwise_pwFilter [DecidableRel (α := α) R] : ∀ l : List α, Pairwise R (pwFilter R l) | [] => Pairwise.nil | x :: l => if h : ∀ y ∈ pwFilter R l, R x y then pwFilter_cons_of_pos h ▸ pairwise_cons.2 ⟨h, pairwise_pwFilter l⟩ else pwFilter_cons_of_neg h ▸ pairwise_pwFilter l theorem pwFilter_eq_self [DecidableRel (α := α) R] {l : List α} : pwFilter R l = l ↔ Pairwise R l := by refine ⟨fun e => e ▸ pairwise_pwFilter l, fun p => ?_⟩ induction l with | nil => rfl | cons x l IH => let ⟨al, p⟩ := pairwise_cons.1 p rw [pwFilter_cons_of_pos fun b hb => ?_, IH p] rw [IH p] at hb exact al _ hb @[simp] theorem pwFilter_idem [DecidableRel (α := α) R] : pwFilter R (pwFilter R l) = pwFilter R l := pwFilter_eq_self.2 (pairwise_pwFilter ..) theorem forall_mem_pwFilter [DecidableRel (α := α) R] (neg_trans : ∀ {x y z}, R x z → R x y ∨ R y z) (a : α) (l : List α) : (∀ b ∈ pwFilter R l, R a b) ↔ ∀ b ∈ l, R a b := by refine ⟨?_, fun h b hb => h _ <| pwFilter_subset (R := R) _ hb⟩ induction l with | nil => exact fun _ _ h => (not_mem_nil h).elim | cons x l IH => simp only [forall_mem_cons] if h : ∀ y ∈ pwFilter R l, R x y then simpa [pwFilter_cons_of_pos h] using fun r H => ⟨r, IH H⟩ else refine pwFilter_cons_of_neg h ▸ fun H => ⟨?_, IH H⟩ match e : find? (fun y => ¬R x y) (pwFilter R l) with | none => exact h.elim fun y hy => by simpa using find?_eq_none.1 e y hy | some k => have := find?_some e apply (neg_trans (H k (mem_of_find?_eq_some e))).resolve_right rw [decide_eq_true_iff] at this; exact this
.lake/packages/batteries/Batteries/Data/List/ArrayMap.lean
module @[expose] public section universe u v w variable {α : Type u} {β : Type v} namespace List /-- This function is provided as a more efficient runtime alternative to `(l.map f).toArray`. (It avoids the intermediate memory allocation of creating an intermediate list first.) For verification purposes, we immediately simplify it to that form. -/ def toArrayMap (l : List α) (f : α → β) : Array β := l.foldl (init := #[]) fun acc x => acc.push (f x) -- Future: a toArrayMapM version could be useful (e.g. in mathlib's DeriveToExpr) -- def toArrayMapM {m : Type v → Type w} [Monad m] (l : List α) (f : α → m β) : m (Array β) := -- l.foldlM (init := #[]) fun acc x => acc.push (f x) theorem toArrayMap_toList (l : List α) (f : α → β ) : (l.toArrayMap f).toList = l.map f := by suffices ∀ arr : Array β, (l.foldl (init := arr) fun acc x => acc.push (f x)).toList = arr.toList ++ l.map f from this #[] induction l with | nil => simp | cons head tail tail_ih => intro arr have : arr.toList ++ f head :: map f tail = (arr.push (f head)).toList ++ map f tail := by simp rw [List.foldl_cons, List.map_cons, this, ← tail_ih] @[simp, grind =] theorem toArrayMap_eq_toArray_map (l : List α) (f : α → β) : l.toArrayMap f = (l.map f).toArray := Array.ext' (by simpa using toArrayMap_toList l f) end List
.lake/packages/batteries/Batteries/Data/List/Scan.lean
module public import Batteries.Data.List.Basic @[expose] public section /-! # List scan Prove basic results about `List.scanl` and `List.scanr`. -/ namespace List /-! ### List.scanl -/ @[simp, grind =] theorem length_scanl {f : β → α → β} (b : β) (l : List α) : length (scanl f b l) = l.length + 1 := by induction l generalizing b <;> simp_all @[simp, grind =] theorem scanl_nil {f : β → α → β} (b : β) : scanl f b [] = [b] := rfl @[simp, grind =] theorem scanl_cons {f : β → α → β} : scanl f b (a :: l) = b :: scanl f (f b a) l := by simp only [scanl] theorem scanl_singleton {f : β → α → β} : scanl f b [a] = [b, f b a] := by simp @[simp] theorem scanl_ne_nil {f : β → α → β} : scanl f b l ≠ [] := by cases l <;> simp @[simp] theorem scanl_iff_nil {f : β → α → β} (c : β) : scanl f b l = [c] ↔ c = b ∧ l = [] := by constructor <;> cases l <;> simp_all @[simp, grind =] theorem getElem_scanl {f : α → β → α} (h : i < (scanl f a l).length) : (scanl f a l)[i] = foldl f a (l.take i) := by induction l generalizing a i with | nil => simp | cons _ _ ih => cases i <;> simp [ih] @[grind =] theorem getElem?_scanl {f : α → β → α} : (scanl f a l)[i]? = if i ≤ l.length then some (foldl f a (l.take i)) else none := by grind @[grind _=_] theorem take_scanl {f : α → β → α} (a : α) (l : List β) (i : Nat) : (scanl f a l).take (i + 1) = scanl f a (l.take i) := by induction l generalizing a i with | nil => simp | cons _ _ ih => cases i <;> simp [ih] theorem getElem?_scanl_zero {f : β → α → β} : (scanl f b l)[0]? = some b := by simp theorem getElem_scanl_zero {f : β → α → β} : (scanl f b l)[0] = b := by simp @[simp] theorem head_scanl {f : β → α → β} (h : scanl f b l ≠ []) : (scanl f b l).head h = b := by grind theorem getLast_scanl {f : β → α → β} (h : scanl f b l ≠ []) : (scanl f b l).getLast h = foldl f b l := by induction l generalizing b case nil => simp case cons head tail ih => simp [getLast_cons, scanl_ne_nil, ih] theorem getLast?_scanl {f : β → α → β} : (scanl f b l).getLast? = some (foldl f b l) := by simp [getLast?] split · exact absurd ‹_› scanl_ne_nil · simp [←‹_›, getLast_scanl] theorem getElem?_succ_scanl {f : β → α → β} : (scanl f b l)[i + 1]? = (scanl f b l)[i]?.bind fun x => l[i]?.map fun y => f x y := by induction l generalizing b i with | nil => simp | cons _ _ ih => cases i <;> simp [ih] theorem getElem_succ_scanl {f : β → α → β} (h : i + 1 < (scanl f b l).length) : (scanl f b l)[i + 1] = f (l.scanl f b)[i] (l[i]'(by grind)) := by induction i generalizing b l with | zero => cases l <;> simp at h ⊢ | succ _ ih => cases l <;> simp [ih] at h ⊢ theorem scanl_append {f : β → α → β} (l₁ l₂ : List α) : scanl f b (l₁ ++ l₂) = scanl f b l₁ ++ (scanl f (foldl f b l₁) l₂).tail := by induction l₁ generalizing b case nil => cases l₂ <;> simp case cons head tail ih => simp [ih] theorem scanl_map {f : β → γ → β} {g : α → γ} (b : β) (l : List α) : scanl f b (l.map g) = scanl (fun acc x => f acc (g x)) b l := by induction l generalizing b case nil => simp case cons head tail ih => simp [ih] /-! ### List.scanr -/ @[simp, grind =] theorem scanr_nil {f : α → β → β} (b : β) : scanr f b [] = [b] := rfl @[simp] theorem scanr_ne_nil {f : α → β → β} : scanr f b l ≠ [] := by simp [scanr] @[simp, grind =] theorem scanr_cons {f : α → β → β} : scanr f b (a :: l) = foldr f b (a :: l) :: scanr f b l := by simp only [scanr, foldr, cons.injEq, and_true] induction l generalizing a with | nil => rfl | cons _ _ ih => simp only [foldr, ih] theorem scanr_singleton {f : α → β → β} : scanr f b [a] = [f a b, b] := by simp @[simp] theorem scanr_iff_nil {f : α → β → β} (c : β) : scanr f b l = [c] ↔ c = b ∧ l = [] := by constructor <;> cases l <;> simp_all @[simp, grind =] theorem length_scanr {f : α → β → β} (b : β) (l : List α) : length (scanr f b l) = l.length + 1 := by induction l <;> simp_all theorem scanr_append {f : α → β → β} (l₁ l₂ : List α) : scanr f b (l₁ ++ l₂) = (scanr f (foldr f b l₂) l₁) ++ (scanr f b l₂).tail := by induction l₁ <;> induction l₂ <;> simp [*] @[simp] theorem head_scanr {f : α → β → β} (h : scanr f b l ≠ []) : (scanr f b l).head h = foldr f b l := by cases l <;> simp theorem getLast_scanr {f : α → β → β} (h : scanr f b l ≠ []) : (scanr f b l).getLast h = b := by induction l case nil => simp case cons head tail ih => simp [getLast_cons, scanr_ne_nil, ih] theorem getLast?_scanr {f : α → β → β} : (scanr f b l).getLast? = some b := by simp [getLast?] split · exact absurd ‹_› scanr_ne_nil · simp [←‹_›, getLast_scanr] theorem tail_scanr {f : α → β → β} (h : 0 < l.length) : (scanr f b l).tail = scanr f b l.tail := by induction l <;> simp_all @[grind _=_] theorem drop_scanr {f : α → β → β} (h : i ≤ l.length) : (scanr f b l).drop i = scanr f b (l.drop i) := by induction i generalizing l with | zero => simp | succ => cases l <;> simp_all @[simp, grind =] theorem getElem_scanr {f : α → β → β} (h : i < (scanr f b l).length) : (scanr f b l)[i] = foldr f b (l.drop i) := by induction l generalizing i with | nil => simp | cons _ _ ih => cases i <;> simp [ih] at h ⊢ @[grind =] theorem getElem?_scanr {f : α → β → β} (h : i < l.length + 1) : (scanr f b l)[i]? = if i < l.length + 1 then some (foldr f b (l.drop i)) else none := by grind theorem getElem_scanr_zero {f : α → β → β} : (scanr f b l)[0] = foldr f b l := by simp theorem getElem?_scanr_zero {f : α → β → β} : (scanr f b l)[0]? = some (foldr f b l) := by simp theorem getElem?_scanr_of_lt {f : α → β → β} (h : i < l.length + 1) : (scanr f b l)[i]? = some (foldr f b (l.drop i)) := by simp [h] theorem scanr_map {f : α → β → β} {g : γ → α} (b : β) (l : List γ) : scanr f b (l.map g) = scanr (fun x acc => f (g x) acc) b l := by suffices ∀ l, foldr f b (l.map g) = foldr (fun x acc => f (g x) acc) b l from by induction l generalizing b <;> simp [*] intro l induction l <;> simp [*] @[simp, grind =] theorem scanl_reverse {f : β → α → β} (b : β) (l : List α) : scanl f b l.reverse = reverse (scanr (flip f) b l) := by induction l generalizing b case nil => rfl case cons head tail ih => simp [scanl_append, ih]; rfl @[simp, grind =] theorem scanr_reverse {f : α → β → β} (b : β) (l : List α) : scanr f b l.reverse = reverse (scanl (flip f) b l) := by induction l generalizing b case nil => rfl case cons head tail ih => simp [scanr_append, ih]; rfl
.lake/packages/batteries/Batteries/Data/List/Monadic.lean
module public import Batteries.Classes.SatisfiesM @[expose] public section /-! # Results about monadic operations on `List`, in terms of `SatisfiesM`. -/ namespace List theorem satisfiesM_foldlM [Monad m] [LawfulMonad m] {f : β → α → m β} (h₀ : motive b) (h₁ : ∀ (b) (_ : motive b) (a : α) (_ : a ∈ l), SatisfiesM motive (f b a)) : SatisfiesM motive (List.foldlM f b l) := by induction l generalizing b with | nil => exact SatisfiesM.pure h₀ | cons hd tl ih => simp only [foldlM_cons] apply SatisfiesM.bind_pre let ⟨q, qh⟩ := h₁ b h₀ hd mem_cons_self exact ⟨(fun ⟨b, bh⟩ => ⟨b, ih bh (fun b bh a am => h₁ b bh a (mem_cons_of_mem hd am))⟩) <$> q, by simpa using qh⟩ theorem satisfiesM_foldrM [Monad m] [LawfulMonad m] {f : α → β → m β} (h₀ : motive b) (h₁ : ∀ (a : α) (_ : a ∈ l) (b) (_ : motive b), SatisfiesM motive (f a b)) : SatisfiesM motive (List.foldrM f b l) := by induction l with | nil => exact SatisfiesM.pure h₀ | cons hd tl ih => simp only [foldrM_cons] apply SatisfiesM.bind_pre let ⟨q, qh⟩ := ih (fun a am b hb => h₁ a (mem_cons_of_mem hd am) b hb) exact ⟨(fun ⟨b, bh⟩ => ⟨b, h₁ hd mem_cons_self b bh⟩) <$> q, by simpa using qh⟩ end List
.lake/packages/batteries/Batteries/Data/List/Perm.lean
module public import Batteries.Tactic.Alias public import Batteries.Data.List.Lemmas @[expose] public section /-! # List Permutations This file introduces the `List.Perm` relation, which is true if two lists are permutations of one another. ## Notation The notation `~` is used for permutation equivalence. -/ open Nat namespace List open Perm (swap) @[simp] theorem nil_subperm {l : List α} : [] <+~ l := ⟨[], Perm.nil, by simp⟩ theorem Perm.subperm_left {l l₁ l₂ : List α} (p : l₁ ~ l₂) : l <+~ l₁ ↔ l <+~ l₂ := suffices ∀ {l₁ l₂ : List α}, l₁ ~ l₂ → l <+~ l₁ → l <+~ l₂ from ⟨this p, this p.symm⟩ fun p ⟨_u, pu, su⟩ => let ⟨v, pv, sv⟩ := exists_perm_sublist su p ⟨v, pv.trans pu, sv⟩ theorem Perm.subperm_right {l₁ l₂ l : List α} (p : l₁ ~ l₂) : l₁ <+~ l ↔ l₂ <+~ l := ⟨fun ⟨u, pu, su⟩ => ⟨u, pu.trans p, su⟩, fun ⟨u, pu, su⟩ => ⟨u, pu.trans p.symm, su⟩⟩ theorem Sublist.subperm {l₁ l₂ : List α} (s : l₁ <+ l₂) : l₁ <+~ l₂ := ⟨l₁, .rfl, s⟩ theorem Perm.subperm {l₁ l₂ : List α} (p : l₁ ~ l₂) : l₁ <+~ l₂ := ⟨l₂, p.symm, Sublist.refl _⟩ @[refl] theorem Subperm.refl (l : List α) : l <+~ l := Perm.rfl.subperm theorem Subperm.trans {l₁ l₂ l₃ : List α} (s₁₂ : l₁ <+~ l₂) (s₂₃ : l₂ <+~ l₃) : l₁ <+~ l₃ := let ⟨_l₂', p₂, s₂⟩ := s₂₃ let ⟨l₁', p₁, s₁⟩ := p₂.subperm_left.2 s₁₂ ⟨l₁', p₁, s₁.trans s₂⟩ theorem Subperm.cons_self : l <+~ a :: l := ⟨l, .refl _, sublist_cons_self ..⟩ theorem Subperm.cons_right {α : Type _} {l l' : List α} (x : α) (h : l <+~ l') : l <+~ x :: l' := h.trans (sublist_cons_self x l').subperm theorem Subperm.length_le {l₁ l₂ : List α} : l₁ <+~ l₂ → length l₁ ≤ length l₂ | ⟨_l, p, s⟩ => p.length_eq ▸ s.length_le theorem Subperm.perm_of_length_le {l₁ l₂ : List α} : l₁ <+~ l₂ → length l₂ ≤ length l₁ → l₁ ~ l₂ | ⟨_l, p, s⟩, h => (s.eq_of_length_le <| p.symm.length_eq ▸ h) ▸ p.symm theorem Subperm.antisymm {l₁ l₂ : List α} (h₁ : l₁ <+~ l₂) (h₂ : l₂ <+~ l₁) : l₁ ~ l₂ := h₁.perm_of_length_le h₂.length_le theorem Subperm.subset {l₁ l₂ : List α} : l₁ <+~ l₂ → l₁ ⊆ l₂ | ⟨_l, p, s⟩ => Subset.trans p.symm.subset s.subset theorem Subperm.filter (p : α → Bool) ⦃l l' : List α⦄ (h : l <+~ l') : filter p l <+~ filter p l' := by let ⟨xs, hp, h⟩ := h exact ⟨_, hp.filter p, h.filter p⟩ @[simp] theorem subperm_nil : l <+~ [] ↔ l = [] := ⟨fun h => length_eq_zero_iff.1 $ Nat.le_zero.1 h.length_le, by rintro rfl; rfl⟩ @[simp] theorem singleton_subperm_iff {α} {l : List α} {a : α} : [a] <+~ l ↔ a ∈ l := by refine ⟨fun ⟨s, hla, h⟩ => ?_, fun h => ⟨[a], .rfl, singleton_sublist.mpr h⟩⟩ rwa [perm_singleton.mp hla, singleton_sublist] at h theorem Subperm.countP_le (p : α → Bool) {l₁ l₂ : List α} : l₁ <+~ l₂ → countP p l₁ ≤ countP p l₂ | ⟨_l, p', s⟩ => p'.countP_eq p ▸ s.countP_le theorem Subperm.count_le [BEq α] {l₁ l₂ : List α} (s : l₁ <+~ l₂) (a) : count a l₁ ≤ count a l₂ := s.countP_le _ theorem subperm_cons (a : α) {l₁ l₂ : List α} : a :: l₁ <+~ a :: l₂ ↔ l₁ <+~ l₂ := by refine ⟨fun ⟨l, p, s⟩ => ?_, fun ⟨l, p, s⟩ => ⟨a :: l, p.cons a, s.cons₂ _⟩⟩ match s with | .cons _ s' => exact (p.subperm_left.2 <| (sublist_cons_self _ _).subperm).trans s'.subperm | .cons₂ _ s' => exact ⟨_, p.cons_inv, s'⟩ /-- Weaker version of `Subperm.cons_left` -/ theorem cons_subperm_of_not_mem_of_mem {a : α} {l₁ l₂ : List α} (h₁ : a ∉ l₁) (h₂ : a ∈ l₂) (s : l₁ <+~ l₂) : a :: l₁ <+~ l₂ := by obtain ⟨l, p, s⟩ := s induction s generalizing l₁ with | slnil => cases h₂ | @cons r₁ _ b s' ih => simp at h₂ match h₂ with | .inl e => subst_vars; exact ⟨_ :: r₁, p.cons _, s'.cons₂ _⟩ | .inr m => let ⟨t, p', s'⟩ := ih h₁ m p; exact ⟨t, p', s'.cons _⟩ | @cons₂ _ r₂ b _ ih => have bm : b ∈ l₁ := p.subset mem_cons_self have am : a ∈ r₂ := by simp only [mem_cons] at h₂ exact h₂.resolve_left fun e => h₁ <| e.symm ▸ bm obtain ⟨t₁, t₂, rfl⟩ := append_of_mem bm have st : t₁ ++ t₂ <+ t₁ ++ b :: t₂ := by simp obtain ⟨t, p', s'⟩ := ih (mt (st.subset ·) h₁) am (.cons_inv <| p.trans perm_middle) exact ⟨b :: t, (p'.cons b).trans <| (swap ..).trans (perm_middle.symm.cons a), s'.cons₂ _⟩ theorem subperm_append_left {l₁ l₂ : List α} : ∀ l, l ++ l₁ <+~ l ++ l₂ ↔ l₁ <+~ l₂ | [] => .rfl | a :: l => (subperm_cons a).trans (subperm_append_left l) theorem subperm_append_right {l₁ l₂ : List α} (l) : l₁ ++ l <+~ l₂ ++ l ↔ l₁ <+~ l₂ := (perm_append_comm.subperm_left.trans perm_append_comm.subperm_right).trans (subperm_append_left l) theorem Subperm.exists_of_length_lt {l₁ l₂ : List α} (s : l₁ <+~ l₂) (h : length l₁ < length l₂) : ∃ a, a :: l₁ <+~ l₂ := by obtain ⟨l, p, s⟩ := s suffices length l < length l₂ → ∃ a : α, a :: l <+~ l₂ from (this <| p.symm.length_eq ▸ h).imp fun a => (p.cons a).subperm_right.1 clear h p l₁ induction s with intro h | slnil => cases h | cons a s IH => match Nat.lt_or_eq_of_le (Nat.le_of_lt_succ h) with | .inl h => exact (IH h).imp fun a s => s.trans (sublist_cons_self _ _).subperm | .inr h => exact ⟨a, s.eq_of_length h ▸ .refl _⟩ | cons₂ b _ IH => exact (IH <| Nat.lt_of_succ_lt_succ h).imp fun a s => (swap ..).subperm_right.1 <| (subperm_cons _).2 s theorem subperm_of_subset (d : Nodup l₁) (H : l₁ ⊆ l₂) : l₁ <+~ l₂ := by induction d with | nil => exact ⟨nil, .nil, nil_sublist _⟩ | cons h _ IH => have ⟨H₁, H₂⟩ := forall_mem_cons.1 H exact cons_subperm_of_not_mem_of_mem (h _ · rfl) H₁ (IH H₂) theorem perm_ext_iff_of_nodup {l₁ l₂ : List α} (d₁ : Nodup l₁) (d₂ : Nodup l₂) : l₁ ~ l₂ ↔ ∀ a, a ∈ l₁ ↔ a ∈ l₂ := by refine ⟨fun p _ => p.mem_iff, fun H => ?_⟩ exact (subperm_of_subset d₁ fun a => (H a).1).antisymm <| subperm_of_subset d₂ fun a => (H a).2 theorem Nodup.perm_iff_eq_of_sublist {l₁ l₂ l : List α} (d : Nodup l) (s₁ : l₁ <+ l) (s₂ : l₂ <+ l) : l₁ ~ l₂ ↔ l₁ = l₂ := by refine ⟨fun h => ?_, fun h => by rw [h]⟩ induction s₂ generalizing l₁ with simp [Nodup, List.forall_mem_ne] at d | slnil => exact h.eq_nil | cons a s₂ IH => match s₁ with | .cons _ s₁ => exact IH d.2 s₁ h | .cons₂ _ s₁ => have := Subperm.subset ⟨_, h.symm, s₂⟩ (.head _) exact (d.1 this).elim | cons₂ a _ IH => match s₁ with | .cons _ s₁ => have := Subperm.subset ⟨_, h, s₁⟩ (.head _) exact (d.1 this).elim | .cons₂ _ s₁ => rw [IH d.2 s₁ h.cons_inv] theorem subperm_cons_erase [BEq α] [LawfulBEq α] (a : α) (l : List α) : l <+~ a :: l.erase a := if h : a ∈ l then (perm_cons_erase h).subperm else (erase_of_not_mem h).symm ▸ (sublist_cons_self _ _).subperm theorem erase_subperm [BEq α] (a : α) (l : List α) : l.erase a <+~ l := erase_sublist.subperm theorem Subperm.erase [BEq α] [LawfulBEq α] (a : α) (h : l₁ <+~ l₂) : l₁.erase a <+~ l₂.erase a := let ⟨l, hp, hs⟩ := h ⟨l.erase a, hp.erase _, hs.erase _⟩ theorem Perm.diff_right [BEq α] [LawfulBEq α] (t : List α) (h : l₁ ~ l₂) : l₁.diff t ~ l₂.diff t := by induction t generalizing l₁ l₂ h with simp only [List.diff] | nil => exact h | cons x t ih => simp only [elem_eq_mem, decide_eq_true_eq, Perm.mem_iff h] split · exact ih (h.erase _) · exact ih h theorem Perm.diff_left [BEq α] [LawfulBEq α] (l : List α) (h : t₁ ~ t₂) : l.diff t₁ = l.diff t₂ := by induction h generalizing l with try simp [List.diff] | cons x _ ih => apply ite_congr rfl <;> (intro; apply ih) | swap x y => if h : x = y then simp [h] else simp [mem_erase_of_ne h, mem_erase_of_ne (Ne.symm h), erase_comm x y] split <;> simp | trans => simp only [*] theorem Perm.diff [BEq α] [LawfulBEq α] {l₁ l₂ t₁ t₂ : List α} (hl : l₁ ~ l₂) (ht : t₁ ~ t₂) : l₁.diff t₁ ~ l₂.diff t₂ := ht.diff_left l₂ ▸ hl.diff_right _ theorem Subperm.diff_right [BEq α] [LawfulBEq α] (h : l₁ <+~ l₂) (t : List α) : l₁.diff t <+~ l₂.diff t := by induction t generalizing l₁ l₂ h with simp [List.diff, *] | cons x t ih => split <;> rename_i hx1 · simp [h.subset hx1] exact ih (h.erase _) · split · rw [← erase_of_not_mem hx1] exact ih (h.erase _) · exact ih h theorem erase_cons_subperm_cons_erase [BEq α] [LawfulBEq α] (a b : α) (l : List α) : (a :: l).erase b <+~ a :: l.erase b := by if h : a = b then rw [h, erase_cons_head]; apply subperm_cons_erase else have : ¬(a == b) = true := by simp only [beq_false_of_ne h, not_false_eq_true, reduceCtorEq] rw [erase_cons_tail this] theorem subperm_cons_diff [BEq α] [LawfulBEq α] {a : α} {l₁ l₂ : List α} : (a :: l₁).diff l₂ <+~ a :: l₁.diff l₂ := by induction l₂ with | nil => exact ⟨a :: l₁, by simp [List.diff]⟩ | cons b l₂ ih => rw [diff_cons, diff_cons, ← diff_erase, ← diff_erase] exact Subperm.trans (.erase _ ih) (erase_cons_subperm_cons_erase ..) theorem subset_cons_diff [BEq α] [LawfulBEq α] {a : α} {l₁ l₂ : List α} : (a :: l₁).diff l₂ ⊆ a :: l₁.diff l₂ := subperm_cons_diff.subset /-- The list version of `add_tsub_cancel_of_le` for multisets. -/ theorem subperm_append_diff_self_of_count_le [BEq α] [LawfulBEq α] {l₁ l₂ : List α} (h : ∀ x ∈ l₁, count x l₁ ≤ count x l₂) : l₁ ++ l₂.diff l₁ ~ l₂ := by induction l₁ generalizing l₂ with | nil => simp | cons hd tl IH => have : hd ∈ l₂ := by rw [← count_pos_iff] exact Nat.lt_of_lt_of_le (count_pos_iff.mpr (.head _)) (h hd (.head _)) have := perm_cons_erase this refine Perm.trans ?_ this.symm rw [cons_append, diff_cons, perm_cons] refine IH fun x hx => ?_ specialize h x (.tail _ hx) rw [perm_iff_count.mp this] at h if hx : hd = x then subst hd; simpa [Nat.succ_le_succ_iff] using h else simpa [hx] using h /-- The list version of `Multiset.le_iff_count`. -/ theorem subperm_ext_iff [BEq α] [LawfulBEq α] {l₁ l₂ : List α} : l₁ <+~ l₂ ↔ ∀ x ∈ l₁, count x l₁ ≤ count x l₂ := by refine ⟨fun h x _ => h.count_le x, fun h => ?_⟩ have : l₁ <+~ l₂.diff l₁ ++ l₁ := (subperm_append_right l₁).mpr nil_subperm refine this.trans (Perm.subperm ?_) exact perm_append_comm.trans (subperm_append_diff_self_of_count_le h) theorem isSubperm_iff [BEq α] [LawfulBEq α] {l₁ l₂ : List α} : l₁.isSubperm l₂ ↔ l₁ <+~ l₂ := by simp [isSubperm, subperm_ext_iff] instance decidableSubperm [BEq α] [LawfulBEq α] : DecidableRel ((· <+~ ·) : List α → List α → Prop) := fun _ _ => decidable_of_iff _ isSubperm_iff theorem Subperm.cons_left [BEq α] [LawfulBEq α] (h : l₁ <+~ l₂) (x : α) (hx : count x l₁ < count x l₂) : x :: l₁ <+~ l₂ := by rw [subperm_ext_iff] at h ⊢ intro y hy if hy' : y = x then subst x; simpa using Nat.succ_le_of_lt hx else rw [count_cons_of_ne (Ne.symm hy')] refine h y ?_ simpa [hy'] using hy theorem Perm.union_right [BEq α] [LawfulBEq α] (t₁ : List α) (h : l₁ ~ l₂) : l₁ ∪ t₁ ~ l₂ ∪ t₁ := by induction h with | nil => rfl | cons a _ ih => exact ih.insert a | swap => apply perm_insert_swap | trans _ _ ih_1 ih_2 => exact ih_1.trans ih_2 theorem Perm.union_left [BEq α] [LawfulBEq α] (l : List α) (h : t₁ ~ t₂) : l ∪ t₁ ~ l ∪ t₂ := by induction l with | nil => simp only [nil_union, h] | cons _ _ ih => simp only [cons_union, Perm.insert _ ih] theorem Perm.union [BEq α] [LawfulBEq α] {l₁ l₂ t₁ t₂ : List α} (p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : l₁ ∪ t₁ ~ l₂ ∪ t₂ := (p₁.union_right t₁).trans (p₂.union_left l₂) theorem Perm.inter_right [BEq α] (t₁ : List α) : l₁ ~ l₂ → l₁ ∩ t₁ ~ l₂ ∩ t₁ := .filter _ theorem Perm.inter_left [BEq α] [LawfulBEq α] (l : List α) (p : t₁ ~ t₂) : l ∩ t₁ = l ∩ t₂ := filter_congr fun a _ => by simpa using p.mem_iff (a := a) theorem Perm.inter [BEq α] [LawfulBEq α] {l₁ l₂ t₁ t₂ : List α} (p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : l₁ ∩ t₁ ~ l₂ ∩ t₂ := p₂.inter_left l₂ ▸ p₁.inter_right t₁ theorem Perm.flatten_congr : ∀ {l₁ l₂ : List (List α)} (_ : List.Forall₂ (· ~ ·) l₁ l₂), l₁.flatten ~ l₂.flatten | _, _, .nil => .rfl | _ :: _, _ :: _, .cons h₁ h₂ => h₁.append (Perm.flatten_congr h₂) theorem perm_insertP (p : α → Bool) (a l) : insertP p a l ~ a :: l := by induction l with simp [insertP, insertP.loop, cond] | cons _ _ ih => split · exact Perm.refl .. · rw [insertP_loop, reverseAux, reverseAux] exact Perm.trans (Perm.cons _ ih) (Perm.swap ..) theorem Perm.insertP (p : α → Bool) (a) (h : l₁ ~ l₂) : insertP p a l₁ ~ insertP p a l₂ := Perm.trans (perm_insertP ..) <| Perm.trans (Perm.cons _ h) <| Perm.symm (perm_insertP ..)
.lake/packages/batteries/Batteries/Data/List/Matcher.lean
module public import Batteries.Data.Array.Match @[expose] public section namespace List /-- Knuth-Morris-Pratt matcher type This type is used to keep data for running the Knuth-Morris-Pratt (KMP) list matching algorithm. KMP is a linear time algorithm to locate all contiguous sublists of a list that match a given pattern. Generating the algorithm data is also linear in the length of the pattern but the data can be re-used to match the same pattern over multiple lists. The KMP data for a pattern can be generated using `Matcher.ofList`. Then `Matcher.find?` and `Matcher.findAll` can be used to run the algorithm on an input list. ``` def m := Matcher.ofList [0,1,1,0] #eval Option.isSome <| m.find? [2,1,1,0,1,1,2] -- false #eval Option.isSome <| m.find? [0,0,1,1,0,0] -- true #eval Array.size <| m.findAll [0,1,1,0,1,1,0] -- 2 #eval Array.size <| m.findAll [0,1,1,0,1,1,0,1,1,0] -- 3 ``` -/ structure Matcher (α : Type _) extends Array.Matcher α where /-- The pattern for the matcher -/ pattern : List α /-- Make KMP matcher from list pattern. -/ @[inline] def Matcher.ofList [BEq α] (pattern : List α) : Matcher α where toMatcher := Array.Matcher.ofStream pattern pattern := pattern /-- List stream that keeps count of items read. -/ local instance (α) : Std.Stream (List α × Nat) α where next? | ([], _) => none | (x::xs, n) => (x, xs, n+1) /-- Find all start and end positions of all infix sublists of `l` matching `m.pattern`. The sublists may be overlapping. -/ partial def Matcher.findAll [BEq α] (m : Matcher α) (l : List α) : Array (Nat × Nat) := loop (l, 0) m.toMatcher #[] where /-- Accumulator loop for `List.Matcher.findAll` -/ loop (l : List α × Nat) (am : Array.Matcher α) (occs : Array (Nat × Nat)) : Array (Nat × Nat) := match am.next? l with | none => occs | some (l, am) => loop l am (occs.push (l.snd - m.table.size, l.snd)) /-- Find the start and end positions of the first infix sublist of `l` matching `m.pattern`, or `none` if there is no such sublist. -/ def Matcher.find? [BEq α] (m : Matcher α) (l : List α) : Option (Nat × Nat) := match m.next? (l, 0) with | none => none | some (l, _) => some (l.snd - m.table.size, l.snd) /-- Returns all the start and end positions of all infix sublists of of `l` that match `pattern`. The sublists may be overlapping. -/ @[inline] def findAllInfix [BEq α] (l pattern : List α) : Array (Nat × Nat) := (Matcher.ofList pattern).findAll l /-- Returns the start and end positions of the first infix sublist of `l` that matches `pattern`, or `none` if there is no such sublist. -/ @[inline] def findInfix? [BEq α] (l pattern : List α) : Option (Nat × Nat) := (Matcher.ofList pattern).find? l /-- Returns true iff `pattern` occurs as an infix sublist of `l`. -/ @[inline] def containsInfix [BEq α] (l pattern : List α) : Bool := findInfix? l pattern |>.isSome
.lake/packages/batteries/Batteries/Data/List/Basic.lean
module import Batteries.Tactic.Alias @[expose] public section namespace List /-! ## New definitions -/ /-- Computes the "bag intersection" of `l₁` and `l₂`, that is, the collection of elements of `l₁` which are also in `l₂`. As each element is identified, it is removed from `l₂`, so elements are counted with multiplicity. -/ protected def bagInter {α} [BEq α] : List α → List α → List α | [], _ => [] | _, [] => [] | a :: l₁, l₂ => if l₂.elem a then a :: List.bagInter l₁ (l₂.erase a) else List.bagInter l₁ l₂ /-- Computes the difference of `l₁` and `l₂`, by removing each element in `l₂` from `l₁`. -/ protected def diff {α} [BEq α] : List α → List α → List α | l, [] => l | l₁, a :: l₂ => if l₁.elem a then List.diff (l₁.erase a) l₂ else List.diff l₁ l₂ open Option Nat /-- Get the head and tail of a list, if it is nonempty. -/ @[inline] def next? : List α → Option (α × List α) | [] => none | a :: l => some (a, l) /-- `after p xs` is the suffix of `xs` after the first element that satisfies `p`, not including that element. ```lean after (· == 1) [0, 1, 2, 3] = [2, 3] drop_while (· != 1) [0, 1, 2, 3] = [1, 2, 3] ``` -/ @[specialize] def after (p : α → Bool) : List α → List α | [] => [] | x :: xs => bif p x then xs else after p xs /-- Replaces the first element of the list for which `f` returns `some` with the returned value. -/ @[simp] def replaceF (f : α → Option α) : List α → List α | [] => [] | x :: xs => match f x with | none => x :: replaceF f xs | some a => a :: xs /-- Tail-recursive version of `replaceF`. -/ @[inline] def replaceFTR (f : α → Option α) (l : List α) : List α := go l #[] where /-- Auxiliary for `replaceFTR`: `replaceFTR.go f xs acc = acc.toList ++ replaceF f xs`. -/ @[specialize] go : List α → Array α → List α | [], acc => acc.toList | x :: xs, acc => match f x with | none => go xs (acc.push x) | some a' => acc.toListAppend (a' :: xs) @[csimp] theorem replaceF_eq_replaceFTR : @replaceF = @replaceFTR := by funext α p l; simp [replaceFTR] let rec go (acc) : ∀ xs, replaceFTR.go p xs acc = acc.toList ++ xs.replaceF p | [] => by simp [replaceFTR.go, replaceF] | x::xs => by simp [replaceFTR.go, replaceF]; cases p x <;> simp · rw [go _ xs]; simp exact (go #[] _).symm /-- Constructs the union of two lists, by inserting the elements of `l₁` in reverse order to `l₂`. As a result, `l₂` will always be a suffix, but only the last occurrence of each element in `l₁` will be retained (but order will otherwise be preserved). -/ @[inline] protected def union [BEq α] (l₁ l₂ : List α) : List α := foldr .insert l₂ l₁ instance [BEq α] : Union (List α) := ⟨List.union⟩ /-- Constructs the intersection of two lists, by filtering the elements of `l₁` that are in `l₂`. Unlike `bagInter` this does not preserve multiplicity: `[1, 1].inter [1]` is `[1, 1]`. -/ @[inline] protected def inter [BEq α] (l₁ l₂ : List α) : List α := filter (elem · l₂) l₁ instance [BEq α] : Inter (List α) := ⟨List.inter⟩ /-- Split a list at an index. Ensures the left list always has the specified length by right padding with the provided default element. ``` splitAtD 2 [a, b, c] x = ([a, b], [c]) splitAtD 4 [a, b, c] x = ([a, b, c, x], []) ``` -/ def splitAtD (n : Nat) (l : List α) (dflt : α) : List α × List α := go n l [] where /-- Auxiliary for `splitAtD`: `splitAtD.go dflt n l acc = (acc.reverse ++ left, right)` if `splitAtD n l dflt = (left, right)`. -/ go : Nat → List α → List α → List α × List α | n+1, x :: xs, acc => go n xs (x :: acc) | 0, xs, acc => (acc.reverse, xs) | n, [], acc => (acc.reverseAux (replicate n dflt), []) /-- Split a list at every element satisfying a predicate. The separators are not in the result. ``` [1, 1, 2, 3, 2, 4, 4].splitOnP (· == 2) = [[1, 1], [3], [4, 4]] ``` -/ def splitOnP (P : α → Bool) (l : List α) : List (List α) := go l [] where /-- Auxiliary for `splitOnP`: `splitOnP.go xs acc = res'` where `res'` is obtained from `splitOnP P xs` by prepending `acc.reverse` to the first element. -/ go : List α → List α → List (List α) | [], acc => [acc.reverse] | a :: t, acc => if P a then acc.reverse :: go t [] else go t (a::acc) /-- Tail recursive version of `splitOnP`. -/ @[inline] def splitOnPTR (P : α → Bool) (l : List α) : List (List α) := go l #[] #[] where /-- Auxiliary for `splitOnP`: `splitOnP.go xs acc r = r.toList ++ res'` where `res'` is obtained from `splitOnP P xs` by prepending `acc.toList` to the first element. -/ @[specialize] go : List α → Array α → Array (List α) → List (List α) | [], acc, r => r.toListAppend [acc.toList] | a :: t, acc, r => bif P a then go t #[] (r.push acc.toList) else go t (acc.push a) r @[csimp] theorem splitOnP_eq_splitOnPTR : @splitOnP = @splitOnPTR := by funext α P l; simp [splitOnPTR] suffices ∀ xs acc r, splitOnPTR.go P xs acc r = r.toList ++ splitOnP.go P xs acc.toList.reverse from (this l #[] #[]).symm intro xs acc r; induction xs generalizing acc r with simp [splitOnP.go, splitOnPTR.go] | cons x xs IH => cases P x <;> simp [*] /-- Split a list at every occurrence of a separator element. The separators are not in the result. ``` [1, 1, 2, 3, 2, 4, 4].splitOn 2 = [[1, 1], [3], [4, 4]] ``` -/ @[inline] def splitOn [BEq α] (a : α) (as : List α) : List (List α) := as.splitOnP (· == a) /-- Apply `f` to the last element of `l`, if it exists. -/ @[inline] def modifyLast (f : α → α) (l : List α) : List α := go l #[] where /-- Auxiliary for `modifyLast`: `modifyLast.go f l acc = acc.toList ++ modifyLast f l`. -/ @[specialize] go : List α → Array α → List α | [], _ => [] | [x], acc => acc.toListAppend [f x] | x :: xs, acc => go xs (acc.push x) theorem headD_eq_head? (l) (a : α) : headD l a = (head? l).getD a := by cases l <;> rfl /-- Take `n` elements from a list `l`. If `l` has less than `n` elements, append `n - length l` elements `x`. -/ def takeD : Nat → List α → α → List α | 0, _, _ => [] | n+1, l, x => l.headD x :: takeD n l.tail x @[simp] theorem takeD_zero (l) (a : α) : takeD 0 l a = [] := rfl @[simp] theorem takeD_succ (l) (a : α) : takeD (n+1) l a = l.head?.getD a :: takeD n l.tail a := by simp [takeD] @[simp] theorem takeD_nil (n) (a : α) : takeD n [] a = replicate n a := by induction n <;> simp [*, replicate_succ] /-- Tail-recursive version of `takeD`. -/ def takeDTR (n : Nat) (l : List α) (dflt : α) : List α := go n l #[] where /-- Auxiliary for `takeDTR`: `takeDTR.go dflt n l acc = acc.toList ++ takeD n l dflt`. -/ go : Nat → List α → Array α → List α | n+1, x :: xs, acc => go n xs (acc.push x) | 0, _, acc => acc.toList | n, [], acc => acc.toListAppend (replicate n dflt) theorem takeDTR_go_eq : ∀ n l, takeDTR.go dflt n l acc = acc.toList ++ takeD n l dflt | 0, _ => by simp [takeDTR.go] | _+1, [] => by simp [takeDTR.go, replicate_succ] | _+1, _::l => by simp [takeDTR.go, takeDTR_go_eq _ l] @[csimp] theorem takeD_eq_takeDTR : @takeD = @takeDTR := by funext α f n l; simp [takeDTR, takeDTR_go_eq] /-- Fold a function `f` over the list from the left, returning the list of partial results. ``` scanl (+) 0 [1, 2, 3] = [0, 1, 3, 6] ``` -/ @[simp] def scanl (f : α → β → α) (a : α) : List β → List α | [] => [a] | b :: l => a :: scanl f (f a b) l /-- Tail-recursive version of `scanl`. -/ @[inline] def scanlTR (f : α → β → α) (a : α) (l : List β) : List α := go l a #[] where /-- Auxiliary for `scanlTR`: `scanlTR.go f l a acc = acc.toList ++ scanl f a l`. -/ @[specialize] go : List β → α → Array α → List α | [], a, acc => acc.toListAppend [a] | b :: l, a, acc => go l (f a b) (acc.push a) theorem scanlTR_go_eq : ∀ l, scanlTR.go f l a acc = acc.toList ++ scanl f a l | [] => by simp [scanlTR.go, scanl] | a :: l => by simp [scanlTR.go, scanl, scanlTR_go_eq l] @[csimp] theorem scanl_eq_scanlTR : @scanl = @scanlTR := by funext α f n l; simp (config := { unfoldPartialApp := true }) [scanlTR, scanlTR_go_eq] /-- Fold a function `f` over the list from the right, returning the list of partial results. ``` scanr (+) 0 [1, 2, 3] = [6, 5, 3, 0] ``` -/ def scanr (f : α → β → β) (b : β) (l : List α) : List β := let (b', l') := l.foldr (fun a (b', l') => (f a b', b' :: l')) (b, []) b' :: l' /-- Fold a list from left to right as with `foldl`, but the combining function also receives each element's index. -/ @[simp, specialize] def foldlIdx (f : Nat → α → β → α) (init : α) : List β → (start : _ := 0) → α | [], _ => init | b :: l, i => foldlIdx f (f i init b) l (i+1) /-- Fold a list from right to left as with `foldr`, but the combining function also receives each element's index. -/ -- TODO(Mario): tail recursive / array-based implementation @[simp, specialize] def foldrIdx (f : Nat → α → β → β) (init : β) : (l : List α) → (start : _ := 0) → β | [], _ => init | a :: l, i => f i a (foldrIdx f init l (i+1)) /-- `findIdxs p l` is the list of indexes of elements of `l` that satisfy `p`. -/ @[inline] def findIdxs (p : α → Bool) (l : List α) : List Nat := foldrIdx (fun i a is => if p a then i :: is else is) [] l /-- Returns the elements of `l` that satisfy `p` together with their indexes in `l`. The returned list is ordered by index. -/ @[inline] def findIdxsValues (p : α → Bool) (l : List α) : List (Nat × α) := foldrIdx (fun i a l => if p a then (i, a) :: l else l) [] l @[deprecated (since := "2025-11-06")] alias indexsValues := findIdxsValues /-- `idxsOf a l` is the list of all indexes of `a` in `l`. For example: ``` idxsOf a [a, b, a, a] = [0, 2, 3] ``` -/ @[inline] def idxsOf [BEq α] (a : α) : List α → List Nat := findIdxs (· == a) @[deprecated (since := "2025-11-06")] alias indexesOf := idxsOf /-- `lookmap` is a combination of `lookup` and `filterMap`. `lookmap f l` will apply `f : α → Option α` to each element of the list, replacing `a → b` at the first value `a` in the list such that `f a = some b`. -/ @[inline] def lookmap (f : α → Option α) (l : List α) : List α := go l #[] where /-- Auxiliary for `lookmap`: `lookmap.go f l acc = acc.toList ++ lookmap f l`. -/ @[specialize] go : List α → Array α → List α | [], acc => acc.toList | a :: l, acc => match f a with | some b => acc.toListAppend (b :: l) | none => go l (acc.push a) /-- `inits l` is the list of initial segments of `l`. ``` inits [1, 2, 3] = [[], [1], [1, 2], [1, 2, 3]] ``` -/ @[simp] def inits : List α → List (List α) | [] => [[]] | a :: l => [] :: map (fun t => a :: t) (inits l) /-- Tail-recursive version of `inits`. -/ def initsTR (l : List α) : List (List α) := l.foldr (fun a arrs => (arrs.map fun t => a :: t).push []) #[[]] |>.toListRev @[csimp] theorem inits_eq_initsTR : @inits = @initsTR := by funext α l; simp [initsTR]; induction l <;> simp [*, map_reverse] /-- `tails l` is the list of terminal segments of `l`. ``` tails [1, 2, 3] = [[1, 2, 3], [2, 3], [3], []] ``` -/ @[simp] def tails : List α → List (List α) | [] => [[]] | a :: l => (a :: l) :: tails l /-- Tail-recursive version of `tails`. -/ def tailsTR (l : List α) : List (List α) := go l #[] where /-- Auxiliary for `tailsTR`: `tailsTR.go l acc = acc.toList ++ tails l`. -/ go (l : List α) (acc : Array (List α)) : List (List α) := match l with | [] => acc.toListAppend [[]] | _::xs => go xs (acc.push l) @[csimp] theorem tails_eq_tailsTR : @tails = @tailsTR := by funext α have H (l : List α) : ∀ acc, tailsTR.go l acc = acc.toList ++ tails l := by induction l <;> simp [*, tailsTR.go] simp (config := { unfoldPartialApp := true }) [tailsTR, H] /-- `sublists' l` is the list of all (non-contiguous) sublists of `l`. It differs from `sublists` only in the order of appearance of the sublists; `sublists'` uses the first element of the list as the MSB, `sublists` uses the first element of the list as the LSB. ``` sublists' [1, 2, 3] = [[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]] ``` -/ def sublists' (l : List α) : List (List α) := let f a arr := arr.foldl (init := arr) fun r l => r.push (a :: l) (l.foldr f #[[]]).toList /-- `sublists l` is the list of all (non-contiguous) sublists of `l`; cf. `sublists'` for a different ordering. ``` sublists [1, 2, 3] = [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]] ``` -/ def sublists (l : List α) : List (List α) := l.foldr (fun a acc => acc.flatMap fun x => [x, a :: x]) [[]] /-- A version of `List.sublists` that has faster runtime performance but worse kernel performance -/ def sublistsFast (l : List α) : List (List α) := let f a arr := arr.foldl (init := Array.mkEmpty (arr.size * 2)) fun r l => (r.push l).push (a :: l) (l.foldr f #[[]]).toList @[csimp] theorem sublists_eq_sublistsFast : @sublists = @sublistsFast := funext <| fun _ => funext fun _ => foldr_hom Array.toList fun _ r => flatMap_eq_foldl.trans <| (foldl_toArray _ _ _).symm.trans <| r.foldl_hom Array.toList <| fun r _ => r.toList_append.symm section Forall₂ variable {r : α → β → Prop} {p : γ → δ → Prop} /-- `Forall₂ R l₁ l₂` means that `l₁` and `l₂` have the same length, and whenever `a` is the nth element of `l₁`, and `b` is the nth element of `l₂`, then `R a b` is satisfied. -/ inductive Forall₂ (R : α → β → Prop) : List α → List β → Prop /-- Two nil lists are `Forall₂`-related -/ | nil : Forall₂ R [] [] /-- Two cons lists are related by `Forall₂ R` if the heads are related by `R` and the tails are related by `Forall₂ R` -/ | cons {a b l₁ l₂} : R a b → Forall₂ R l₁ l₂ → Forall₂ R (a :: l₁) (b :: l₂) attribute [simp] Forall₂.nil @[simp] theorem forall₂_cons {R : α → β → Prop} {a b l₁ l₂} : Forall₂ R (a :: l₁) (b :: l₂) ↔ R a b ∧ Forall₂ R l₁ l₂ := ⟨fun | .cons h tail => ⟨h, tail⟩, fun ⟨head, tail⟩ => .cons head tail⟩ /-- Check for all elements `a`, `b`, where `a` and `b` are the nth element of the first and second List respectively, that `r a b = true`. -/ def all₂ (r : α → β → Bool) : List α → List β → Bool | [], [] => true | a::as, b::bs => if r a b then all₂ r as bs else false | _, _ => false @[simp] theorem all₂_eq_true {r : α → β → Bool} : ∀ l₁ l₂, all₂ r l₁ l₂ ↔ Forall₂ (r · ·) l₁ l₂ | [], [] => by simp [all₂] | a::as, b::bs => by by_cases h : r a b <;> simp [all₂, h, all₂_eq_true, forall₂_cons] | _::_, [] | [], _::_ => by simp [all₂] exact nofun instance {R : α → β → Prop} [∀ a b, Decidable (R a b)] : ∀ l₁ l₂, Decidable (Forall₂ R l₁ l₂) := fun l₁ l₂ => decidable_of_iff (all₂ (R · ·) l₁ l₂) (by simp [all₂_eq_true]) end Forall₂ /-- Transpose of a list of lists, treated as a matrix. ``` transpose [[1, 2], [3, 4], [5, 6]] = [[1, 3, 5], [2, 4, 6]] ``` -/ def transpose (l : List (List α)) : List (List α) := (l.foldr go #[]).toList where /-- `pop : List α → StateM (List α) (List α)` transforms the input list `old` by taking the head of the current state and pushing it on the head of `old`. If the state list is empty, then `old` is left unchanged. -/ pop (old : List α) : StateM (List α) (List α) | [] => (old, []) | a :: l => (a :: old, l) /-- `go : List α → Array (List α) → Array (List α)` handles the insertion of a new list into all the lists in the array: `go [a, b, c] #[l₁, l₂, l₃] = #[a::l₁, b::l₂, c::l₃]`. If the new list is too short, the later lists are unchanged, and if it is too long the array is extended: ``` go [a] #[l₁, l₂, l₃] = #[a::l₁, l₂, l₃] go [a, b, c, d] #[l₁, l₂, l₃] = #[a::l₁, b::l₂, c::l₃, [d]] ``` -/ go (l : List α) (acc : Array (List α)) : Array (List α) := let (acc, l) := acc.mapM pop l l.foldl (init := acc) fun arr a => arr.push [a] /-- List of all sections through a list of lists. A section of `[L₁, L₂, ..., Lₙ]` is a list whose first element comes from `L₁`, whose second element comes from `L₂`, and so on. -/ @[simp] def sections : List (List α) → List (List α) | [] => [[]] | l :: L => (sections L).flatMap fun s => l.map fun a => a :: s /-- Optimized version of `sections`. -/ def sectionsTR (L : List (List α)) : List (List α) := bif L.any isEmpty then [] else (L.foldr go #[[]]).toList where /-- `go : List α → Array (List α) → Array (List α)` inserts one list into the accumulated list of sections `acc`: `go [a, b] #[l₁, l₂] = [a::l₁, b::l₁, a::l₂, b::l₂]`. -/ go (l : List α) (acc : Array (List α)) : Array (List α) := acc.foldl (init := #[]) fun acc' l' => l.foldl (init := acc') fun acc' a => acc'.push (a :: l') theorem sections_eq_nil_of_isEmpty : ∀ {L}, L.any isEmpty → @sections α L = [] | l :: L, h => by simp only [any, Bool.or_eq_true] at h match l, h with | [], .inl rfl => simp | l, .inr h => simp [sections, sections_eq_nil_of_isEmpty h] @[csimp] theorem sections_eq_sectionsTR : @sections = @sectionsTR := by funext α L; simp [sectionsTR] cases e : L.any isEmpty <;> simp [sections_eq_nil_of_isEmpty, *] clear e; induction L with | nil => rfl | cons l L IH => ?_ simp [IH, sectionsTR.go] rfl /-- `extractP p l` returns a pair of an element `a` of `l` satisfying the predicate `p`, and `l`, with `a` removed. If there is no such element `a` it returns `(none, l)`. -/ def extractP (p : α → Bool) (l : List α) : Option α × List α := go l #[] where /-- Auxiliary for `extractP`: `extractP.go p l xs acc = (some a, acc.toList ++ out)` if `extractP p xs = (some a, out)`, and `extractP.go p l xs acc = (none, l)` if `extractP p xs = (none, _)`. -/ go : List α → Array α → Option α × List α | [], _ => (none, l) | a :: l, acc => bif p a then (some a, acc.toListAppend l) else go l (acc.push a) /-- `revzip l` returns a list of pairs of the elements of `l` paired with the elements of `l` in reverse order. ``` revzip [1, 2, 3, 4, 5] = [(1, 5), (2, 4), (3, 3), (4, 2), (5, 1)] ``` -/ def revzip (l : List α) : List (α × α) := zip l l.reverse /-- `product l₁ l₂` is the list of pairs `(a, b)` where `a ∈ l₁` and `b ∈ l₂`. ``` product [1, 2] [5, 6] = [(1, 5), (1, 6), (2, 5), (2, 6)] ``` -/ def product (l₁ : List α) (l₂ : List β) : List (α × β) := l₁.flatMap fun a => l₂.map (Prod.mk a) /-- Optimized version of `product`. -/ def productTR (l₁ : List α) (l₂ : List β) : List (α × β) := l₁.foldl (fun acc a => l₂.foldl (fun acc b => acc.push (a, b)) acc) #[] |>.toList @[csimp] theorem product_eq_productTR : @product = @productTR := by funext α β l₁ l₂; simp only [product, productTR] rw [Array.foldl_toList_eq_flatMap]; rfl simp /-- `sigma l₁ l₂` is the list of dependent pairs `(a, b)` where `a ∈ l₁` and `b ∈ l₂ a`. ``` sigma [1, 2] (λ_, [(5 : Nat), 6]) = [(1, 5), (1, 6), (2, 5), (2, 6)] ``` -/ protected def sigma {σ : α → Type _} (l₁ : List α) (l₂ : ∀ a, List (σ a)) : List (Σ a, σ a) := l₁.flatMap fun a => (l₂ a).map (Sigma.mk a) /-- Optimized version of `sigma`. -/ def sigmaTR {σ : α → Type _} (l₁ : List α) (l₂ : ∀ a, List (σ a)) : List (Σ a, σ a) := l₁.foldl (fun acc a => (l₂ a).foldl (fun acc b => acc.push ⟨a, b⟩) acc) #[] |>.toList @[csimp] theorem sigma_eq_sigmaTR : @List.sigma = @sigmaTR := by funext α β l₁ l₂; simp only [List.sigma, sigmaTR] rw [Array.foldl_toList_eq_flatMap]; rfl simp /-- `ofFnNthVal f i` returns `some (f i)` if `i < n` and `none` otherwise. -/ def ofFnNthVal {n} (f : Fin n → α) (i : Nat) : Option α := if h : i < n then some (f ⟨i, h⟩) else none /-- `Disjoint l₁ l₂` means that `l₁` and `l₂` have no elements in common. -/ def Disjoint (l₁ l₂ : List α) : Prop := ∀ ⦃a⦄, a ∈ l₁ → a ∈ l₂ → False /-- Returns the longest initial prefix of two lists such that they are pairwise related by `R`. ``` takeWhile₂ (· < ·) [1, 2, 4, 5] [5, 4, 3, 6] = ([1, 2], [5, 4]) ``` -/ def takeWhile₂ (R : α → β → Bool) : List α → List β → List α × List β | a::as, b::bs => if R a b then let (as', bs') := takeWhile₂ R as bs (a::as', b::bs') else ([], []) | _, _ => ([], []) /-- Tail-recursive version of `takeWhile₂`. -/ @[inline] def takeWhile₂TR (R : α → β → Bool) (as : List α) (bs : List β) : List α × List β := go as bs [] [] where /-- Auxiliary for `takeWhile₂TR`: `takeWhile₂TR.go R as bs acca accb = (acca.reverse ++ as', acca.reverse ++ bs')` if `takeWhile₂ R as bs = (as', bs')`. -/ @[specialize] go : List α → List β → List α → List β → List α × List β | a::as, b::bs, acca, accb => bif R a b then go as bs (a::acca) (b::accb) else (acca.reverse, accb.reverse) | _, _, acca, accb => (acca.reverse, accb.reverse) @[csimp] theorem takeWhile₂_eq_takeWhile₂TR : @takeWhile₂ = @takeWhile₂TR := by funext α β R as bs; simp [takeWhile₂TR] let rec go (as bs acca accb) : takeWhile₂TR.go R as bs acca accb = (acca.reverse ++ (as.takeWhile₂ R bs).1, accb.reverse ++ (as.takeWhile₂ R bs).2) := by unfold takeWhile₂TR.go takeWhile₂; split <;> simp rename_i a as b bs; unfold cond; cases R a b <;> simp [go as bs] exact (go as bs [] []).symm /-- `pwFilter R l` is a maximal sublist of `l` which is `Pairwise R`. `pwFilter (·≠·)` is the erase duplicates function (cf. `eraseDup`), and `pwFilter (·<·)` finds a maximal increasing subsequence in `l`. For example, ``` pwFilter (·<·) [0, 1, 5, 2, 6, 3, 4] = [0, 1, 2, 3, 4] ``` -/ def pwFilter (R : α → α → Prop) [DecidableRel R] (l : List α) : List α := l.foldr (fun x IH => if ∀ y ∈ IH, R x y then x :: IH else IH) [] /-- `IsChain R l` means that `R` holds between adjacent elements of `l`. ``` IsChain R [a, b, c, d] ↔ R a b ∧ R b c ∧ R c d ``` -/ inductive IsChain (R : α → α → Prop) : List α → Prop where /-- A list of length 0 is a chain. -/ | nil : IsChain R [] /-- A list of length 1 is a chain. -/ | singleton (a : α) : IsChain R [a] /-- If `a` relates to `b` and `b::l` is a chain, then `a :: b :: l` is also a chain. -/ | cons_cons (hr : R a b) (h : IsChain R (b :: l)) : IsChain R (a :: b :: l) attribute [simp, grind ←] IsChain.nil attribute [simp, grind ←] IsChain.singleton @[simp, grind =] theorem isChain_cons_cons : IsChain R (a :: b :: l) ↔ R a b ∧ IsChain R (b :: l) := ⟨fun | .cons_cons hr h => ⟨hr, h⟩, fun ⟨hr, h⟩ => .cons_cons hr h⟩ instance instDecidableIsChain {R : α → α → Prop} [h : DecidableRel R] (l : List α) : Decidable (l.IsChain R) := match l with | [] => isTrue .nil | a :: l => go a l where go (a : α) (l : List α) : Decidable ((a :: l).IsChain R) := match l with | [] => isTrue <| .singleton a | b :: l => haveI := (go b l); decidable_of_iff' _ isChain_cons_cons /-- `Chain R a l` means that `R` holds between adjacent elements of `a::l`. ``` Chain R a [b, c, d] ↔ R a b ∧ R b c ∧ R c d ``` -/ @[deprecated IsChain (since := "2025-09-19")] def Chain : (α → α → Prop) → α → List α → Prop := (IsChain · <| · :: ·) set_option linter.deprecated false in /-- A list of length 1 is a chain. -/ @[deprecated IsChain.singleton (since := "2025-09-19")] theorem Chain.nil {a : α} : Chain R a [] := IsChain.singleton a set_option linter.deprecated false in /-- If `a` relates to `b` and `b::l` is a chain, then `a :: b :: l` is also a chain. -/ @[deprecated IsChain.cons_cons (since := "2025-09-19")] theorem Chain.cons : R a b → Chain R b l → Chain R a (b :: l) := IsChain.cons_cons /-- `Chain' R l` means that `R` holds between adjacent elements of `l`. ``` Chain' R [a, b, c, d] ↔ R a b ∧ R b c ∧ R c d ``` -/ @[deprecated IsChain (since := "2025-09-19")] def Chain' : (α → α → Prop) → List α → Prop := (IsChain · ·) /-- `eraseDup l` removes duplicates from `l` (taking only the first occurrence). Defined as `pwFilter (≠)`. eraseDup [1, 0, 2, 2, 1] = [0, 2, 1] -/ @[inline] def eraseDup [BEq α] : List α → List α := pwFilter (· != ·) /-- `rotate l n` rotates the elements of `l` to the left by `n` ``` rotate [0, 1, 2, 3, 4, 5] 2 = [2, 3, 4, 5, 0, 1] ``` -/ @[inline] def rotate (l : List α) (n : Nat) : List α := let (l₁, l₂) := List.splitAt (n % l.length) l l₂ ++ l₁ /-- `rotate'` is the same as `rotate`, but slower. Used for proofs about `rotate` -/ @[simp] def rotate' : List α → Nat → List α | [], _ => [] | l, 0 => l | a :: l, n+1 => rotate' (l ++ [a]) n /-- `mapDiagM f l` calls `f` on all elements in the upper triangular part of `l × l`. That is, for each `e ∈ l`, it will run `f e e` and then `f e e'` for each `e'` that appears after `e` in `l`. ``` mapDiagM f [1, 2, 3] = return [← f 1 1, ← f 1 2, ← f 1 3, ← f 2 2, ← f 2 3, ← f 3 3] ``` -/ def mapDiagM [Monad m] (f : α → α → m β) (l : List α) : m (List β) := go l #[] where /-- Auxiliary for `mapDiagM`: `mapDiagM.go as f acc = (acc.toList ++ ·) <$> mapDiagM f as` -/ go : List α → Array β → m (List β) | [], acc => pure acc.toList | x::xs, acc => do let b ← f x x let acc ← xs.foldlM (·.push <$> f x ·) (acc.push b) go xs acc /-- `forDiagM f l` calls `f` on all elements in the upper triangular part of `l × l`. That is, for each `e ∈ l`, it will run `f e e` and then `f e e'` for each `e'` that appears after `e` in `l`. ``` forDiagM f [1, 2, 3] = do f 1 1; f 1 2; f 1 3; f 2 2; f 2 3; f 3 3 ``` -/ @[simp] def forDiagM [Monad m] (f : α → α → m PUnit) : List α → m PUnit | [] => pure ⟨⟩ | x :: xs => do f x x; xs.forM (f x); xs.forDiagM f /-- `getRest l l₁` returns `some l₂` if `l = l₁ ++ l₂`. If `l₁` is not a prefix of `l`, returns `none` -/ def getRest [DecidableEq α] : List α → List α → Option (List α) | l, [] => some l | [], _ => none | x :: l, y :: l₁ => if x = y then getRest l l₁ else none /-- `List.dropSlice n m xs` removes a slice of length `m` at index `n` in list `xs`. -/ @[simp] def dropSlice : Nat → Nat → List α → List α | _, _, [] => [] | 0, m, xs => xs.drop m | n+1, m, x :: xs => x :: dropSlice n m xs /-- Optimized version of `dropSlice`. -/ @[inline] def dropSliceTR (n m : Nat) (l : List α) : List α := match m with | 0 => l | m+1 => go m l n #[] where /-- Auxiliary for `dropSliceTR`: `dropSliceTR.go l m xs n acc = acc.toList ++ dropSlice n m xs` unless `n ≥ length xs`, in which case it is `l`. -/ go (m : Nat) : List α → Nat → Array α → List α | [], _, _ => l | _::xs, 0, acc => acc.toListAppend (xs.drop m) | x::xs, n+1, acc => go m xs n (acc.push x) theorem dropSlice_zero₂ : ∀ n l, @dropSlice α n 0 l = l | 0, [] | 0, _::_ | _+1, [] => rfl | n+1, x::xs => by simp [dropSlice, dropSlice_zero₂] @[csimp] theorem dropSlice_eq_dropSliceTR : @dropSlice = @dropSliceTR := by funext α n m l; simp [dropSliceTR] split; { rw [dropSlice_zero₂] } rename_i m let rec go (acc) : ∀ xs n, l = acc.toList ++ xs → dropSliceTR.go l m xs n acc = acc.toList ++ xs.dropSlice n (m+1) | [], n | _::xs, 0 => fun h => by simp [dropSliceTR.go, dropSlice, h] | x::xs, n+1 => by simp [dropSliceTR.go, dropSlice]; intro h; rw [go _ xs]; {simp}; simp [h] exact (go #[] _ _ rfl).symm /-- Left-biased version of `List.zipWith`. `zipWithLeft' f as bs` applies `f` to each pair of elements `aᵢ ∈ as` and `bᵢ ∈ bs`. If `bs` is shorter than `as`, `f` is applied to `none` for the remaining `aᵢ`. Returns the results of the `f` applications and the remaining `bs`. ``` zipWithLeft' prod.mk [1, 2] ['a'] = ([(1, some 'a'), (2, none)], []) zipWithLeft' prod.mk [1] ['a', 'b'] = ([(1, some 'a')], ['b']) ``` -/ @[simp] def zipWithLeft' (f : α → Option β → γ) : List α → List β → List γ × List β | [], bs => ([], bs) | a :: as, [] => ((a :: as).map fun a => f a none, []) | a :: as, b :: bs => let r := zipWithLeft' f as bs; (f a (some b) :: r.1, r.2) /-- Tail-recursive version of `zipWithLeft'`. -/ @[inline] def zipWithLeft'TR (f : α → Option β → γ) (as : List α) (bs : List β) : List γ × List β := go as bs #[] where /-- Auxiliary for `zipWithLeft'TR`: `zipWithLeft'TR.go l acc = acc.toList ++ zipWithLeft' l`. -/ go : List α → List β → Array γ → List γ × List β | [], bs, acc => (acc.toList, bs) | as, [], acc => (as.foldl (fun acc a => acc.push (f a none)) acc |>.toList, []) | a :: as, b :: bs, acc => go as bs (acc.push (f a (some b))) @[csimp] theorem zipWithLeft'_eq_zipWithLeft'TR : @zipWithLeft' = @zipWithLeft'TR := by funext α β γ f as bs; simp [zipWithLeft'TR] let rec go (acc) : ∀ as bs, zipWithLeft'TR.go f as bs acc = let (l, r) := as.zipWithLeft' f bs; (acc.toList ++ l, r) | [], bs => by simp [zipWithLeft'TR.go] | _::_, [] => by simp [zipWithLeft'TR.go] | a::as, b::bs => by simp [zipWithLeft'TR.go, go _ as bs] simp [go] /-- Right-biased version of `List.zipWith`. `zipWithRight' f as bs` applies `f` to each pair of elements `aᵢ ∈ as` and `bᵢ ∈ bs`. If `as` is shorter than `bs`, `f` is applied to `none` for the remaining `bᵢ`. Returns the results of the `f` applications and the remaining `as`. ``` zipWithRight' prod.mk [1] ['a', 'b'] = ([(some 1, 'a'), (none, 'b')], []) zipWithRight' prod.mk [1, 2] ['a'] = ([(some 1, 'a')], [2]) ``` -/ @[inline] def zipWithRight' (f : Option α → β → γ) (as : List α) (bs : List β) : List γ × List α := zipWithLeft' (flip f) bs as /-- Left-biased version of `List.zip`. `zipLeft' as bs` returns the list of pairs `(aᵢ, bᵢ)` for `aᵢ ∈ as` and `bᵢ ∈ bs`. If `bs` is shorter than `as`, the remaining `aᵢ` are paired with `none`. Also returns the remaining `bs`. ``` zipLeft' [1, 2] ['a'] = ([(1, some 'a'), (2, none)], []) zipLeft' [1] ['a', 'b'] = ([(1, some 'a')], ['b']) zipLeft' = zipWithLeft' prod.mk ``` -/ @[inline] def zipLeft' : List α → List β → List (α × Option β) × List β := zipWithLeft' Prod.mk /-- Right-biased version of `List.zip`. `zipRight' as bs` returns the list of pairs `(aᵢ, bᵢ)` for `aᵢ ∈ as` and `bᵢ ∈ bs`. If `as` is shorter than `bs`, the remaining `bᵢ` are paired with `none`. Also returns the remaining `as`. ``` zipRight' [1] ['a', 'b'] = ([(some 1, 'a'), (none, 'b')], []) zipRight' [1, 2] ['a'] = ([(some 1, 'a')], [2]) zipRight' = zipWithRight' prod.mk ``` -/ @[inline] def zipRight' : List α → List β → List (Option α × β) × List α := zipWithRight' Prod.mk /-- Left-biased version of `List.zipWith`. `zipWithLeft f as bs` applies `f` to each pair `aᵢ ∈ as` and `bᵢ ‌∈ bs`. If `bs` is shorter than `as`, `f` is applied to `none` for the remaining `aᵢ`. ``` zipWithLeft prod.mk [1, 2] ['a'] = [(1, some 'a'), (2, none)] zipWithLeft prod.mk [1] ['a', 'b'] = [(1, some 'a')] zipWithLeft f as bs = (zipWithLeft' f as bs).fst ``` -/ @[simp] def zipWithLeft (f : α → Option β → γ) : List α → List β → List γ | [], _ => [] | a :: as, [] => (a :: as).map fun a => f a none | a :: as, b :: bs => f a (some b) :: zipWithLeft f as bs /-- Tail-recursive version of `zipWithLeft`. -/ @[inline] def zipWithLeftTR (f : α → Option β → γ) (as : List α) (bs : List β) : List γ := go as bs #[] where /-- Auxiliary for `zipWithLeftTR`: `zipWithLeftTR.go l acc = acc.toList ++ zipWithLeft l`. -/ go : List α → List β → Array γ → List γ | [], _, acc => acc.toList | as, [], acc => as.foldl (fun acc a => acc.push (f a none)) acc |>.toList | a :: as, b :: bs, acc => go as bs (acc.push (f a (some b))) @[csimp] theorem zipWithLeft_eq_zipWithLeftTR : @zipWithLeft = @zipWithLeftTR := by funext α β γ f as bs; simp [zipWithLeftTR] let rec go (acc) : ∀ as bs, zipWithLeftTR.go f as bs acc = acc.toList ++ as.zipWithLeft f bs | [], bs => by simp [zipWithLeftTR.go] | _::_, [] => by simp [zipWithLeftTR.go] | a::as, b::bs => by simp [zipWithLeftTR.go, go _ as bs] simp [go] /-- Right-biased version of `List.zipWith`. `zipWithRight f as bs` applies `f` to each pair `aᵢ ∈ as` and `bᵢ ‌∈ bs`. If `as` is shorter than `bs`, `f` is applied to `none` for the remaining `bᵢ`. ``` zipWithRight prod.mk [1, 2] ['a'] = [(some 1, 'a')] zipWithRight prod.mk [1] ['a', 'b'] = [(some 1, 'a'), (none, 'b')] zipWithRight f as bs = (zipWithRight' f as bs).fst ``` -/ @[inline] def zipWithRight (f : Option α → β → γ) (as : List α) (bs : List β) : List γ := zipWithLeft (flip f) bs as /-- Left-biased version of `List.zip`. `zipLeft as bs` returns the list of pairs `(aᵢ, bᵢ)` for `aᵢ ∈ as` and `bᵢ ∈ bs`. If `bs` is shorter than `as`, the remaining `aᵢ` are paired with `none`. ``` zipLeft [1, 2] ['a'] = [(1, some 'a'), (2, none)] zipLeft [1] ['a', 'b'] = [(1, some 'a')] zipLeft = zipWithLeft prod.mk ``` -/ @[inline] def zipLeft : List α → List β → List (α × Option β) := zipWithLeft Prod.mk /-- Right-biased version of `List.zip`. `zipRight as bs` returns the list of pairs `(aᵢ, bᵢ)` for `aᵢ ∈ as` and `bᵢ ∈ bs`. If `as` is shorter than `bs`, the remaining `bᵢ` are paired with `none`. ``` zipRight [1, 2] ['a'] = [(some 1, 'a')] zipRight [1] ['a', 'b'] = [(some 1, 'a'), (none, 'b')] zipRight = zipWithRight prod.mk ``` -/ @[inline] def zipRight : List α → List β → List (Option α × β) := zipWithRight Prod.mk /-- If all elements of `xs` are `some xᵢ`, `allSome xs` returns the `xᵢ`. Otherwise it returns `none`. ``` allSome [some 1, some 2] = some [1, 2] allSome [some 1, none ] = none ``` -/ @[inline] def allSome (l : List (Option α)) : Option (List α) := l.mapM id /-- `fillNones xs ys` replaces the `none`s in `xs` with elements of `ys`. If there are not enough `ys` to replace all the `none`s, the remaining `none`s are dropped from `xs`. ``` fillNones [none, some 1, none, none] [2, 3] = [2, 1, 3] ``` -/ @[simp, deprecated "Deprecated without replacement." (since := "2025-08-07")] def fillNones {α} : List (Option α) → List α → List α | [], _ => [] | some a :: as, as' => a :: fillNones as as' | none :: as, [] => as.reduceOption | none :: as, a :: as' => a :: fillNones as as' /-- `takeList as ns` extracts successive sublists from `as`. For `ns = n₁ ... nₘ`, it first takes the `n₁` initial elements from `as`, then the next `n₂` ones, etc. It returns the sublists of `as` -- one for each `nᵢ` -- and the remaining elements of `as`. If `as` does not have at least as many elements as the sum of the `nᵢ`, the corresponding sublists will have less than `nᵢ` elements. ``` takeList ['a', 'b', 'c', 'd', 'e'] [2, 1, 1] = ([['a', 'b'], ['c'], ['d']], ['e']) takeList ['a', 'b'] [3, 1] = ([['a', 'b'], []], []) ``` -/ def takeList {α} : List α → List Nat → List (List α) × List α | xs, [] => ([], xs) | xs, n :: ns => let (xs₁, xs₂) := xs.splitAt n let (xss, rest) := takeList xs₂ ns (xs₁ :: xss, rest) /-- Tail-recursive version of `takeList`. -/ @[inline] def takeListTR (xs : List α) (ns : List Nat) : List (List α) × List α := go ns xs #[] where /-- Auxiliary for `takeListTR`: `takeListTR.go as as' acc = acc.toList ++ takeList as as'`. -/ go : List Nat → List α → Array (List α) → List (List α) × List α | [], xs, acc => (acc.toList, xs) | n :: ns, xs, acc => let (xs₁, xs₂) := xs.splitAt n go ns xs₂ (acc.push xs₁) @[csimp] theorem takeList_eq_takeListTR : @takeList = @takeListTR := by funext α xs ns; simp [takeListTR] let rec go (acc) : ∀ ns xs, @takeListTR.go α ns xs acc = let (l, r) := xs.takeList ns; (acc.toList ++ l, r) | [], xs => by simp [takeListTR.go, takeList] | n::ns, xs => by simp [takeListTR.go, takeList, go _ ns] simp [go] /-- Auxliary definition used to define `toChunks`. `toChunksAux n xs i` returns `(xs.take i, (xs.drop i).toChunks (n+1))`, that is, the first `i` elements of `xs`, and the remaining elements chunked into sublists of length `n+1`. -/ def toChunksAux {α} (n : Nat) : List α → Nat → List α × List (List α) | [], _ => ([], []) | x :: xs, 0 => let (l, L) := toChunksAux n xs n ([], (x :: l) :: L) | x :: xs, i+1 => let (l, L) := toChunksAux n xs i (x :: l, L) /-- `xs.toChunks n` splits the list into sublists of size at most `n`, such that `(xs.toChunks n).join = xs`. ``` [1, 2, 3, 4, 5, 6, 7, 8].toChunks 10 = [[1, 2, 3, 4, 5, 6, 7, 8]] [1, 2, 3, 4, 5, 6, 7, 8].toChunks 3 = [[1, 2, 3], [4, 5, 6], [7, 8]] [1, 2, 3, 4, 5, 6, 7, 8].toChunks 2 = [[1, 2], [3, 4], [5, 6], [7, 8]] [1, 2, 3, 4, 5, 6, 7, 8].toChunks 0 = [[1, 2, 3, 4, 5, 6, 7, 8]] ``` -/ def toChunks {α} : Nat → List α → List (List α) | _, [] => [] | 0, xs => [xs] | n, x :: xs => let rec /-- Auxliary definition used to define `toChunks`. `toChunks.go xs acc₁ acc₂` pushes elements into `acc₁` until it reaches size `n`, then it pushes the resulting list to `acc₂` and continues until `xs` is exhausted. -/ go : List α → Array α → Array (List α) → List (List α) | [], acc₁, acc₂ => acc₂.push acc₁.toList |>.toList | x :: xs, acc₁, acc₂ => if acc₁.size == n then go xs ((Array.mkEmpty n).push x) (acc₂.push acc₁.toList) else go xs (acc₁.push x) acc₂ go xs #[x] #[] /-! We add some n-ary versions of `List.zipWith` for functions with more than two arguments. These can also be written in terms of `List.zip` or `List.zipWith`. For example, `zipWith₃ f xs ys zs` could also be written as `zipWith id (zipWith f xs ys) zs` or as `(zip xs <| zip ys zs).map fun ⟨x, y, z⟩ => f x y z`. -/ -- TODO(Mario): tail recursive /-- Ternary version of `List.zipWith`. -/ def zipWith₃ (f : α → β → γ → δ) : List α → List β → List γ → List δ | x :: xs, y :: ys, z :: zs => f x y z :: zipWith₃ f xs ys zs | _, _, _ => [] /-- Quaternary version of `List.zipWith`. -/ def zipWith₄ (f : α → β → γ → δ → ε) : List α → List β → List γ → List δ → List ε | x :: xs, y :: ys, z :: zs, u :: us => f x y z u :: zipWith₄ f xs ys zs us | _, _, _, _ => [] /-- Quinary version of `List.zipWith`. -/ def zipWith₅ (f : α → β → γ → δ → ε → ζ) : List α → List β → List γ → List δ → List ε → List ζ | x :: xs, y :: ys, z :: zs, u :: us, v :: vs => f x y z u v :: zipWith₅ f xs ys zs us vs | _, _, _, _, _ => [] /-- An auxiliary function for `List.mapWithPrefixSuffix`. -/ -- TODO(Mario): tail recursive def mapWithPrefixSuffixAux {α β} (f : List α → α → List α → β) : List α → List α → List β | _, [] => [] | prev, h :: t => f prev h t :: mapWithPrefixSuffixAux f (prev.concat h) t /-- `List.mapWithPrefixSuffix f l` maps `f` across a list `l`. For each `a ∈ l` with `l = pref ++ [a] ++ suff`, `a` is mapped to `f pref a suff`. Example: if `f : list Nat → Nat → list Nat → β`, `List.mapWithPrefixSuffix f [1, 2, 3]` will produce the list `[f [] 1 [2, 3], f [1] 2 [3], f [1, 2] 3 []]`. -/ def mapWithPrefixSuffix {α β} (f : List α → α → List α → β) (l : List α) : List β := mapWithPrefixSuffixAux f [] l /-- `List.mapWithComplement f l` is a variant of `List.mapWithPrefixSuffix` that maps `f` across a list `l`. For each `a ∈ l` with `l = pref ++ [a] ++ suff`, `a` is mapped to `f a (pref ++ suff)`, i.e., the list input to `f` is `l` with `a` removed. Example: if `f : Nat → list Nat → β`, `List.mapWithComplement f [1, 2, 3]` will produce the list `[f 1 [2, 3], f 2 [1, 3], f 3 [1, 2]]`. -/ def mapWithComplement {α β} (f : α → List α → β) : List α → List β := mapWithPrefixSuffix fun pref a suff => f a (pref ++ suff) /-- Map each element of a `List` to an action, evaluate these actions in order, and collect the results. -/ protected def traverse [Applicative F] (f : α → F β) : List α → F (List β) | [] => pure [] | x :: xs => List.cons <$> f x <*> List.traverse f xs /-- `Subperm l₁ l₂`, denoted `l₁ <+~ l₂`, means that `l₁` is a sublist of a permutation of `l₂`. This is an analogue of `l₁ ⊆ l₂` which respects multiplicities of elements, and is used for the `≤` relation on multisets. -/ def Subperm (l₁ l₂ : List α) : Prop := ∃ l, l ~ l₁ ∧ l <+ l₂ @[inherit_doc] scoped infixl:50 " <+~ " => Subperm /-- `O(|l₁| * (|l₁| + |l₂|))`. Computes whether `l₁` is a sublist of a permutation of `l₂`. See `isSubperm_iff` for a characterization in terms of `List.Subperm`. -/ def isSubperm [BEq α] (l₁ l₂ : List α) : Bool := ∀ x ∈ l₁, count x l₁ ≤ count x l₂ /-- `O(|l|)`. Inserts `a` in `l` right before the first element such that `p` is true, or at the end of the list if `p` always false on `l`. -/ def insertP (p : α → Bool) (a : α) (l : List α) : List α := loop l [] where /-- Inner loop for `insertP`. Tail recursive. -/ loop : List α → List α → List α | [], r => reverseAux (a :: r) [] -- Note: `reverseAux` is tail recursive. | b :: l, r => bif p b then reverseAux (a :: r) (b :: l) else loop l (b :: r) /-- `dropPrefix? l p` returns `some r` if `l = p' ++ r` for some `p'` which is paiwise `==` to `p`, and `none` otherwise. -/ def dropPrefix? [BEq α] : List α → List α → Option (List α) | list, [] => some list | [], _ :: _ => none | a :: as, b :: bs => if a == b then dropPrefix? as bs else none /-- `dropSuffix? l s` returns `some r` if `l = r ++ s'` for some `s'` which is paiwise `==` to `s`, and `none` otherwise. -/ def dropSuffix? [BEq α] (l s : List α) : Option (List α) := let (r, s') := l.splitAt (l.length - s.length) if s' == s then some r else none /-- `dropInfix? l i` returns `some (p, s)` if `l = p ++ i' ++ s` for some `i'` which is paiwise `==` to `i`, and `none` otherwise. Note that this is an inefficient implementation, and if computation time is a concern you should be using the Knuth-Morris-Pratt algorithm as implemented in `Batteries.Data.List.Matcher`. -/ def dropInfix? [BEq α] (l i : List α) : Option (List α × List α) := go l [] where /-- Inner loop for `dropInfix?`. -/ go : List α → List α → Option (List α × List α) | [], acc => if i.isEmpty then some (acc.reverse, []) else none | a :: as, acc => match (a :: as).dropPrefix? i with | none => go as (a :: acc) | some s => (acc.reverse, s) /-- Computes the product of the elements of a list. Examples: [a, b, c].prod = a * (b * (c * 1)) [2, 3, 5].prod = 30 -/ @[expose] def prod [Mul α] [One α] (xs : List α) : α := xs.foldr (· * ·) 1
.lake/packages/batteries/Batteries/Data/List/Init/Lemmas.lean
module @[expose] public section /-! While this file is currently empty, it is intended as a home for any lemmas which are required for definitions in `Batteries.Data.List.Basic`, but which are not provided by Lean. -/
.lake/packages/batteries/Batteries/Data/String/Lemmas.lean
module public import Batteries.Data.String.Basic public import Batteries.Tactic.Lint.Misc public import Batteries.Tactic.SeqFocus public import Batteries.Classes.Order public import Batteries.Data.List.Basic import all Init.Data.String.Basic -- for unfolding `isEmpty` @[expose] public section namespace String -- TODO(kmill): add `@[ext]` attribute to `String.ext` in core. attribute [ext (iff := false)] ext theorem lt_antisymm {s₁ s₂ : String} (h₁ : ¬s₁ < s₂) (h₂ : ¬s₂ < s₁) : s₁ = s₂ := by simp at h₁ h₂ exact String.le_antisymm h₂ h₁ instance : Std.LawfulLTOrd String := .compareOfLessAndEq_of_irrefl_of_trans_of_antisymm String.lt_irrefl String.lt_trans String.lt_antisymm theorem mk_length (s : List Char) : (String.mk s).length = s.length := by simp attribute [simp] toList -- prefer `String.data` over `String.toList` in lemmas theorem Pos.Raw.offsetBy_eq {p q : Pos.Raw} : p.offsetBy q = ⟨q.byteIdx + p.byteIdx⟩ := by ext simp private theorem add_utf8Size_pos : 0 < i + Char.utf8Size c := Nat.add_pos_right _ (Char.utf8Size_pos c) private theorem ne_add_utf8Size_add_self : i ≠ n + Char.utf8Size c + i := Nat.ne_of_lt (Nat.lt_add_of_pos_left add_utf8Size_pos) private theorem ne_self_add_add_utf8Size : i ≠ i + (n + Char.utf8Size c) := Nat.ne_of_lt (Nat.lt_add_of_pos_right add_utf8Size_pos) /-- The UTF-8 byte length of a list of characters. (This is intended for specification purposes.) -/ @[inline] def utf8Len : List Char → Nat | [] => 0 | c::cs => utf8Len cs + c.utf8Size theorem utf8ByteSize_mk (cs) : utf8ByteSize (String.mk cs) = utf8Len cs := by induction cs with | nil => simp [utf8Len] | cons c cs ih => rw [String.mk_eq_asString, utf8Len, ← ih, ← List.singleton_append, List.asString_append, utf8ByteSize_append, Nat.add_comm] congr rw [← size_bytes, List.bytes_asString, List.utf8Encode_singleton, List.size_toByteArray, length_utf8EncodeChar] @[simp] theorem utf8Len_nil : utf8Len [] = 0 := rfl @[simp] theorem utf8Len_cons (c cs) : utf8Len (c :: cs) = utf8Len cs + c.utf8Size := rfl @[simp] theorem utf8Len_append (cs₁ cs₂) : utf8Len (cs₁ ++ cs₂) = utf8Len cs₁ + utf8Len cs₂ := by induction cs₁ <;> simp [*, Nat.add_right_comm] theorem utf8Len_reverseAux (cs₁ cs₂) : utf8Len (cs₁.reverseAux cs₂) = utf8Len cs₁ + utf8Len cs₂ := by induction cs₁ generalizing cs₂ <;> simp_all [← Nat.add_assoc, Nat.add_right_comm] @[simp] theorem utf8Len_reverse (cs) : utf8Len cs.reverse = utf8Len cs := utf8Len_reverseAux .. @[simp] theorem utf8Len_eq_zero : utf8Len l = 0 ↔ l = [] := by cases l <;> simp [Nat.ne_zero_iff_zero_lt.mpr (Char.utf8Size_pos _)] section open List theorem utf8Len_le_of_sublist : ∀ {cs₁ cs₂}, cs₁ <+ cs₂ → utf8Len cs₁ ≤ utf8Len cs₂ | _, _, .slnil => Nat.le_refl _ | _, _, .cons _ h => Nat.le_trans (utf8Len_le_of_sublist h) (Nat.le_add_right ..) | _, _, .cons₂ _ h => Nat.add_le_add_right (utf8Len_le_of_sublist h) _ theorem utf8Len_le_of_infix (h : cs₁ <:+: cs₂) : utf8Len cs₁ ≤ utf8Len cs₂ := utf8Len_le_of_sublist h.sublist theorem utf8Len_le_of_suffix (h : cs₁ <:+ cs₂) : utf8Len cs₁ ≤ utf8Len cs₂ := utf8Len_le_of_sublist h.sublist theorem utf8Len_le_of_prefix (h : cs₁ <+: cs₂) : utf8Len cs₁ ≤ utf8Len cs₂ := utf8Len_le_of_sublist h.sublist end @[simp] theorem endPos_asString (cs : List Char) : endPos cs.asString = ⟨utf8Len cs⟩ := by apply Pos.Raw.ext simp [String.endPos, ← String.mk_eq_asString, utf8ByteSize_mk] theorem endPos_mk (cs : List Char) : endPos (mk cs) = ⟨utf8Len cs⟩ := by simp @[simp] theorem utf8Len_data (s : String) : utf8Len s.data = s.utf8ByteSize := by rw [← utf8ByteSize_mk, String.mk_eq_asString, asString_data] namespace Pos.Raw -- TODO(kmill): add `@[ext]` attribute to `String.Pos.ext` in core. attribute [ext (iff := false)] ext theorem lt_addChar (p : Pos.Raw) (c : Char) : p < p + c := Nat.lt_add_of_pos_right (Char.utf8Size_pos _) private theorem zero_ne_addChar {i : Pos.Raw} {c : Char} : 0 ≠ i + c := ne_of_lt add_utf8Size_pos /-- A string position is valid if it is equal to the UTF-8 length of an initial substring of `s`. -/ inductive Valid : String → Pos.Raw → Prop where /-- A string position is valid if it is equal to the UTF-8 length of an initial substring of `s`. -/ | mk (cs cs' : List Char) {p} (hp : p.1 = utf8Len cs) : Valid (String.mk (cs ++ cs')) p theorem Valid.intro {s : String} {p : Pos.Raw} (h : ∃ cs cs', cs ++ cs' = s.data ∧ p.1 = utf8Len cs) : Valid s p := by obtain ⟨cs, cs', h₁, h₂⟩ := h rw [← String.asString_data (b := s), ← h₁] exact .mk cs cs' h₂ theorem Valid.exists : {s : String} → {p : Pos.Raw} → Valid s p → ∃ cs cs', String.mk (cs ++ cs') = s ∧ p = ⟨utf8Len cs⟩ | _, _, .mk cs cs' rfl => ⟨cs, cs', rfl, rfl⟩ @[simp] theorem valid_zero : Valid s 0 := .intro ⟨[], s.data, rfl, rfl⟩ @[simp] theorem valid_endPos : Valid s (endPos s) := .intro ⟨s.data, [], by simp, by simp [endPos]⟩ theorem Valid.le_endPos : ∀ {s p}, Valid s p → p ≤ endPos s | _, ⟨_⟩, .mk cs cs' rfl => by simp [endPos, le_iff, -String.mk_eq_asString, utf8ByteSize_mk] end Pos.Raw theorem endPos_eq_zero (s : String) : endPos s = 0 ↔ s = "" := by simp [Pos.Raw.ext_iff, endPos] theorem isEmpty_iff (s : String) : isEmpty s ↔ s = "" := (beq_iff_eq ..).trans (endPos_eq_zero _) /-- Induction along the valid positions in a list of characters. (This definition is intended only for specification purposes.) -/ def utf8InductionOn {motive : List Char → Pos.Raw → Sort u} (s : List Char) (i p : Pos.Raw) (nil : ∀ i, motive [] i) (eq : ∀ c cs, motive (c :: cs) p) (ind : ∀ (c : Char) cs i, i ≠ p → motive cs (i + c) → motive (c :: cs) i) : motive s i := match s with | [] => nil i | c::cs => if h : i = p then h ▸ eq c cs else ind c cs i h (utf8InductionOn cs (i + c) p nil eq ind) theorem utf8GetAux_add_right_cancel (s : List Char) (i p n : Nat) : Pos.Raw.utf8GetAux s ⟨i + n⟩ ⟨p + n⟩ = Pos.Raw.utf8GetAux s ⟨i⟩ ⟨p⟩ := by apply utf8InductionOn s ⟨i⟩ ⟨p⟩ (motive := fun s i => Pos.Raw.utf8GetAux s ⟨i.byteIdx + n⟩ ⟨p + n⟩ = Pos.Raw.utf8GetAux s i ⟨p⟩) <;> simp only [Pos.Raw.utf8GetAux, Char.reduceDefault, implies_true, ↓reduceIte, ne_eq, Pos.Raw.byteIdx_add_char] intro c cs ⟨i⟩ h ih simp only [Pos.Raw.ext_iff, Pos.Raw.add_char_eq] at h ⊢ simp only [Nat.add_right_cancel_iff, h, ↓reduceIte] rw [Nat.add_right_comm] exact ih theorem utf8GetAux_addChar_right_cancel (s : List Char) (i p : Pos.Raw) (c : Char) : Pos.Raw.utf8GetAux s (i + c) (p + c) = Pos.Raw.utf8GetAux s i p := utf8GetAux_add_right_cancel .. theorem utf8GetAux_of_valid (cs cs' : List Char) {i p : Nat} (hp : i + utf8Len cs = p) : Pos.Raw.utf8GetAux (cs ++ cs') ⟨i⟩ ⟨p⟩ = cs'.headD default := by match cs, cs' with | [], [] => rfl | [], c::cs' => simp [← hp, Pos.Raw.utf8GetAux] | c::cs, cs' => simp only [List.cons_append, Pos.Raw.utf8GetAux, Char.reduceDefault] rw [if_neg] case hnc => simp only [← hp, utf8Len_cons, Pos.Raw.ext_iff]; exact ne_self_add_add_utf8Size refine utf8GetAux_of_valid cs cs' ?_ simpa [Nat.add_assoc, Nat.add_comm] using hp theorem get_of_valid (cs cs' : List Char) : Pos.Raw.get (mk (cs ++ cs')) ⟨utf8Len cs⟩ = cs'.headD default := by rw [Pos.Raw.get, String.mk_eq_asString, List.data_asString] exact utf8GetAux_of_valid _ _ (Nat.zero_add _) theorem get_cons_addChar (c : Char) (cs : List Char) (i : Pos.Raw) : (i + c).get (c :: cs).asString = i.get cs.asString := by simp [Pos.Raw.get, Pos.Raw.utf8GetAux, Pos.Raw.zero_ne_addChar, utf8GetAux_addChar_right_cancel] theorem utf8GetAux?_of_valid (cs cs' : List Char) {i p : Nat} (hp : i + utf8Len cs = p) : Pos.Raw.utf8GetAux? (cs ++ cs') ⟨i⟩ ⟨p⟩ = cs'.head? := by match cs, cs' with | [], [] => rfl | [], c::cs' => simp [← hp, Pos.Raw.utf8GetAux?] | c::cs, cs' => simp only [List.cons_append, Pos.Raw.utf8GetAux?] rw [if_neg] case hnc => simp only [← hp, Pos.Raw.ext_iff]; exact ne_self_add_add_utf8Size refine utf8GetAux?_of_valid cs cs' ?_ simpa [Nat.add_assoc, Nat.add_comm] using hp theorem get?_of_valid (cs cs' : List Char) : Pos.Raw.get? (cs ++ cs').asString ⟨utf8Len cs⟩ = cs'.head? := by rw [Pos.Raw.get?, List.data_asString] exact utf8GetAux?_of_valid _ _ (Nat.zero_add _) theorem utf8SetAux_of_valid (c' : Char) (cs cs' : List Char) {i p : Nat} (hp : i + utf8Len cs = p) : Pos.Raw.utf8SetAux c' (cs ++ cs') ⟨i⟩ ⟨p⟩ = cs ++ cs'.modifyHead fun _ => c' := by match cs, cs' with | [], [] => rfl | [], c::cs' => simp [← hp, Pos.Raw.utf8SetAux] | c::cs, cs' => simp only [Pos.Raw.utf8SetAux, List.cons_append] rw [if_neg] case hnc => simp only [← hp, Pos.Raw.ext_iff]; exact ne_self_add_add_utf8Size refine congrArg (c::·) (utf8SetAux_of_valid c' cs cs' ?_) simpa [Nat.add_assoc, Nat.add_comm] using hp theorem set_of_valid (cs cs' : List Char) (c' : Char) : Pos.Raw.set (mk (cs ++ cs')) ⟨utf8Len cs⟩ c' = (cs ++ cs'.modifyHead fun _ => c').asString := by ext rw [Pos.Raw.set, List.data_asString, List.data_asString, String.mk_eq_asString, List.data_asString, utf8SetAux_of_valid _ _ _] exact Nat.zero_add _ theorem modify_of_valid (cs cs' : List Char) : Pos.Raw.modify (mk (cs ++ cs')) ⟨utf8Len cs⟩ f = (cs ++ cs'.modifyHead f).asString := by rw [Pos.Raw.modify, set_of_valid, get_of_valid]; cases cs' <;> rfl theorem next_of_valid' (cs cs' : List Char) : Pos.Raw.next (mk (cs ++ cs')) ⟨utf8Len cs⟩ = ⟨utf8Len cs + (cs'.headD default).utf8Size⟩ := by simp only [Pos.Raw.next, get_of_valid]; rfl theorem next_of_valid (cs : List Char) (c : Char) (cs' : List Char) : Pos.Raw.next (mk (cs ++ c :: cs')) ⟨utf8Len cs⟩ = ⟨utf8Len cs + c.utf8Size⟩ := next_of_valid' .. @[simp] theorem atEnd_iff (s : String) (p : Pos.Raw) : p.atEnd s ↔ s.endPos ≤ p := decide_eq_true_iff theorem valid_next {p : Pos.Raw} (h : p.Valid s) (h₂ : p < s.endPos) : (Pos.Raw.next s p).Valid s := by match s, p, h with | _, ⟨_⟩, .mk cs [] rfl => simp at h₂ | _, ⟨_⟩, .mk cs (c::cs') rfl => rw [next_of_valid] simpa using Pos.Raw.Valid.mk (cs ++ [c]) cs' rfl theorem utf8PrevAux_of_valid {cs cs' : List Char} {c : Char} {i p : Nat} (hp : i + (utf8Len cs + c.utf8Size) = p) : Pos.Raw.utf8PrevAux (cs ++ c :: cs') ⟨i⟩ ⟨p⟩ = ⟨i + utf8Len cs⟩ := by match cs with | [] => simp [Pos.Raw.utf8PrevAux, ← hp, Pos.Raw.add_char_eq] | c'::cs => simp only [Pos.Raw.utf8PrevAux, List.cons_append, utf8Len_cons, ← hp] rw [if_neg] case hnc => simp only [Pos.Raw.le_iff, Pos.Raw.byteIdx_add_char] grind [!Char.utf8Size_pos] refine (utf8PrevAux_of_valid (by simp [Nat.add_assoc, Nat.add_left_comm])).trans ?_ simp [Nat.add_assoc, Nat.add_comm] theorem prev_of_valid (cs : List Char) (c : Char) (cs' : List Char) : Pos.Raw.prev (mk (cs ++ c :: cs')) ⟨utf8Len cs + c.utf8Size⟩ = ⟨utf8Len cs⟩ := by simp only [Pos.Raw.prev, String.mk_eq_asString, List.data_asString] rw [utf8PrevAux_of_valid] <;> simp theorem prev_of_valid' (cs cs' : List Char) : Pos.Raw.prev (mk (cs ++ cs')) ⟨utf8Len cs⟩ = ⟨utf8Len cs.dropLast⟩ := by match cs, cs.eq_nil_or_concat with | _, .inl rfl => apply Pos.Raw.prev_zero | _, .inr ⟨cs, c, rfl⟩ => simp [-String.mk_eq_asString, prev_of_valid] theorem front_eq (s : String) : front s = s.data.headD default := by unfold front; simpa using get_of_valid [] s.data theorem back_eq (s : String) : back s = s.data.getLastD default := by conv => lhs; rw [← s.asString_data] match s.data.eq_nil_or_concat with | .inl h => simp [h]; rfl | .inr ⟨cs, c, h⟩ => simp only [h, back_eq_get_prev_endPos] have : (mk (cs ++ [c])).endPos = ⟨utf8Len cs + c.utf8Size⟩ := by simp [-String.mk_eq_asString, endPos, utf8ByteSize_mk] simp [← String.mk_eq_asString, this, prev_of_valid, get_of_valid] theorem atEnd_of_valid (cs : List Char) (cs' : List Char) : String.Pos.Raw.atEnd (mk (cs ++ cs')) ⟨utf8Len cs⟩ ↔ cs' = [] := by rw [atEnd_iff] cases cs' <;> simp [-String.mk_eq_asString, add_utf8Size_pos, endPos, utf8ByteSize_mk] unseal posOfAux findAux in theorem posOfAux_eq (s c) : posOfAux s c = findAux s (· == c) := (rfl) unseal posOfAux findAux in theorem posOf_eq (s c) : posOf s c = find s (· == c) := (rfl) unseal revPosOfAux revFindAux in theorem revPosOfAux_eq (s c) : revPosOfAux s c = revFindAux s (· == c) := (rfl) unseal revPosOfAux revFindAux in theorem revPosOf_eq (s c) : revPosOf s c = revFind s (· == c) := (rfl) @[nolint unusedHavesSuffices] -- false positive from unfolding String.findAux theorem findAux_of_valid (p) : ∀ l m r, findAux (mk (l ++ m ++ r)) p ⟨utf8Len l + utf8Len m⟩ ⟨utf8Len l⟩ = ⟨utf8Len l + utf8Len (m.takeWhile (!p ·))⟩ | l, [], r => by unfold findAux List.takeWhile; simp | l, c::m, r => by unfold findAux List.takeWhile rw [dif_pos (by exact Nat.lt_add_of_pos_right add_utf8Size_pos)] have h1 := get_of_valid l (c::m++r); have h2 := next_of_valid l c (m++r) simp only [List.cons_append, Char.reduceDefault, List.headD_cons] at h1 h2 simp only [List.append_assoc, List.cons_append, h1, utf8Len_cons, h2] cases p c · simp only [Bool.false_eq_true, ↓reduceIte, Bool.not_false, utf8Len_cons] have foo := findAux_of_valid p (l++[c]) m r simp only [List.append_assoc, List.cons_append, utf8Len_append, utf8Len_cons, utf8Len_nil, Nat.zero_add, List.nil_append] at foo rw [Nat.add_right_comm, Nat.add_assoc] at foo rw [foo, Nat.add_right_comm, Nat.add_assoc] · simp theorem find_of_valid (p s) : find s p = ⟨utf8Len (s.data.takeWhile (!p ·))⟩ := by simpa using findAux_of_valid p [] s.data [] @[nolint unusedHavesSuffices] -- false positive from unfolding String.revFindAux theorem revFindAux_of_valid (p) : ∀ l r, revFindAux (mk (l.reverse ++ r)) p ⟨utf8Len l⟩ = (l.dropWhile (!p ·)).tail?.map (⟨utf8Len ·⟩) | [], r => by unfold revFindAux List.dropWhile; simp | c::l, r => by unfold revFindAux List.dropWhile rw [dif_neg (by exact Pos.Raw.ne_of_gt add_utf8Size_pos)] have h1 := get_of_valid l.reverse (c::r); have h2 := prev_of_valid l.reverse c r simp only [utf8Len_reverse, Char.reduceDefault, List.headD_cons] at h1 h2 simp only [List.reverse_cons, List.append_assoc, List.singleton_append, utf8Len_cons, h2, h1] cases p c <;> simp only [Bool.false_eq_true, ↓reduceIte, Bool.not_false, Bool.not_true, List.tail?_cons, Option.map_some] exact revFindAux_of_valid p l (c::r) theorem revFind_of_valid (p s) : revFind s p = (s.data.reverse.dropWhile (!p ·)).tail?.map (⟨utf8Len ·⟩) := by simpa using revFindAux_of_valid p s.data.reverse [] theorem firstDiffPos_loop_eq (l₁ l₂ r₁ r₂ stop p) (hl₁ : p = utf8Len l₁) (hl₂ : p = utf8Len l₂) (hstop : stop = min (utf8Len l₁ + utf8Len r₁) (utf8Len l₂ + utf8Len r₂)) : firstDiffPos.loop (mk (l₁ ++ r₁)) (mk (l₂ ++ r₂)) ⟨stop⟩ ⟨p⟩ = ⟨p + utf8Len (List.takeWhile₂ (· = ·) r₁ r₂).1⟩ := by unfold List.takeWhile₂; split <;> unfold firstDiffPos.loop · next a r₁ b r₂ => rw [ dif_pos <| by rw [hstop, ← hl₁, ← hl₂] refine Nat.lt_min.2 ⟨?_, ?_⟩ <;> exact Nat.lt_add_of_pos_right add_utf8Size_pos, show Pos.Raw.get (mk (l₁ ++ a :: r₁)) ⟨p⟩ = a by simp [hl₁, -String.mk_eq_asString, get_of_valid], show Pos.Raw.get (mk (l₂ ++ b :: r₂)) ⟨p⟩ = b by simp [hl₂, -String.mk_eq_asString, get_of_valid]] simp only [bne_iff_ne, ne_eq, ite_not, decide_eq_true_eq] split · simp only [utf8Len_cons] subst b rw [show Pos.Raw.next (mk (l₁ ++ a :: r₁)) ⟨p⟩ = ⟨utf8Len l₁ + a.utf8Size⟩ by simp [hl₁, -String.mk_eq_asString, next_of_valid]] simpa [← hl₁, ← Nat.add_assoc, Nat.add_right_comm] using firstDiffPos_loop_eq (l₁ ++ [a]) (l₂ ++ [a]) r₁ r₂ stop (p + a.utf8Size) (by simp [hl₁]) (by simp [hl₂]) (by simp [hstop, ← Nat.add_assoc, Nat.add_right_comm]) · simp · next h => rw [dif_neg] <;> simp [hstop, ← hl₁, ← hl₂, -Nat.not_lt, Nat.lt_min] intro h₁ h₂ have : ∀ {cs}, 0 < utf8Len cs → cs ≠ [] := by rintro _ h rfl; simp at h obtain ⟨a, as, e₁⟩ := List.exists_cons_of_ne_nil (this h₁) obtain ⟨b, bs, e₂⟩ := List.exists_cons_of_ne_nil (this h₂) exact h _ _ _ _ e₁ e₂ theorem firstDiffPos_eq (a b : String) : firstDiffPos a b = ⟨utf8Len (List.takeWhile₂ (· = ·) a.data b.data).1⟩ := by simpa [firstDiffPos] using firstDiffPos_loop_eq [] [] a.data b.data ((utf8Len a.data).min (utf8Len b.data)) 0 rfl rfl (by simp) theorem Pos.Raw.extract.go₂_add_right_cancel (s : List Char) (i e n : Nat) : go₂ s ⟨i + n⟩ ⟨e + n⟩ = go₂ s ⟨i⟩ ⟨e⟩ := by apply utf8InductionOn s ⟨i⟩ ⟨e⟩ (motive := fun s i => go₂ s ⟨i.byteIdx + n⟩ ⟨e + n⟩ = go₂ s i ⟨e⟩) <;> simp only [ne_eq, go₂, Pos.Raw.byteIdx_add_char, implies_true, ↓reduceIte] intro c cs ⟨i⟩ h ih simp only [Pos.Raw.ext_iff, Pos.Raw.add_char_eq] at h ⊢ simp only [Nat.add_right_cancel_iff, h, ↓reduceIte, List.cons.injEq, true_and] rw [Nat.add_right_comm] exact ih theorem Pos.Raw.extract.go₂_append_left : ∀ (s t : List Char) (i e : Nat), e = utf8Len s + i → go₂ (s ++ t) ⟨i⟩ ⟨e⟩ = s | [], t, i, _, rfl => by cases t <;> simp [go₂] | c :: cs, t, i, _, rfl => by simp only [List.cons_append, utf8Len_cons, go₂, Pos.Raw.ext_iff, ne_add_utf8Size_add_self, ↓reduceIte, Pos.Raw.add_char_eq, List.cons.injEq, true_and] apply go₂_append_left; rw [Nat.add_right_comm, Nat.add_assoc] theorem Pos.Raw.extract.go₁_add_right_cancel (s : List Char) (i b e n : Nat) : go₁ s ⟨i + n⟩ ⟨b + n⟩ ⟨e + n⟩ = go₁ s ⟨i⟩ ⟨b⟩ ⟨e⟩ := by apply utf8InductionOn s ⟨i⟩ ⟨b⟩ (motive := fun s i => go₁ s ⟨i.byteIdx + n⟩ ⟨b + n⟩ ⟨e + n⟩ = go₁ s i ⟨b⟩ ⟨e⟩) <;> simp only [ne_eq, go₁, Pos.Raw.byteIdx_add_char, implies_true, ↓reduceIte] · intro c cs apply go₂_add_right_cancel · intro c cs ⟨i⟩ h ih simp only [Pos.Raw.ext_iff, Pos.Raw.add_char_eq] at h ih ⊢ simp only [Nat.add_right_cancel_iff, h, ↓reduceIte] rw [Nat.add_right_comm] exact ih theorem Pos.Raw.extract.go₁_cons_addChar (c : Char) (cs : List Char) (b e : Pos.Raw) : go₁ (c :: cs) 0 (b + c) (e + c) = go₁ cs 0 b e := by simp only [go₁, Pos.Raw.ext_iff, Pos.Raw.byteIdx_zero, byteIdx_add_char, Nat.ne_of_lt add_utf8Size_pos, ↓reduceIte] apply go₁_add_right_cancel theorem Pos.Raw.extract.go₁_append_right : ∀ (s t : List Char) (i b : Nat) (e : Pos.Raw), b = utf8Len s + i → go₁ (s ++ t) ⟨i⟩ ⟨b⟩ e = go₂ t ⟨b⟩ e | [], t, i, _, e, rfl => by cases t <;> simp [go₁, go₂] | c :: cs, t, i, _, e, rfl => by simp only [go₁, utf8Len_cons, Pos.Raw.ext_iff, ne_add_utf8Size_add_self, ↓reduceIte, List.cons_append, Pos.Raw.add_char_eq] apply go₁_append_right; rw [Nat.add_right_comm, Nat.add_assoc] theorem Pos.Raw.extract.go₁_zero_utf8Len (s : List Char) : go₁ s 0 0 ⟨utf8Len s⟩ = s := (go₁_append_right [] s 0 0 ⟨utf8Len s⟩ rfl).trans <| by simpa using go₂_append_left s [] 0 (utf8Len s) rfl theorem extract_cons_addChar (c : Char) (cs : List Char) (b e : Pos.Raw) : Pos.Raw.extract (mk (c :: cs)) (b + c) (e + c) = Pos.Raw.extract (mk cs) b e := by simp only [Pos.Raw.extract, Pos.Raw.byteIdx_add_char, ge_iff_le, Nat.add_le_add_iff_right] split <;> [rfl; simp [Pos.Raw.extract.go₁_cons_addChar]] theorem extract_zero_endPos (s : String) : Pos.Raw.extract s 0 (endPos s) = s := by obtain ⟨l, rfl⟩ := s.exists_eq_asString match l with | [] => rfl | c :: cs => simp only [Pos.Raw.extract, Pos.Raw.byteIdx_zero, endPos_asString, utf8Len_cons, ge_iff_le, Nat.le_zero_eq, Nat.ne_of_gt add_utf8Size_pos, ↓reduceIte, List.data_asString] congr apply Pos.Raw.extract.go₁_zero_utf8Len theorem extract_of_valid (l m r : List Char) : Pos.Raw.extract (mk (l ++ m ++ r)) ⟨utf8Len l⟩ ⟨utf8Len l + utf8Len m⟩ = mk m := by simp only [Pos.Raw.extract] split · next h => rw [utf8Len_eq_zero.1 <| Nat.le_zero.1 <| Nat.add_le_add_iff_left.1 h] · congr rw [List.append_assoc, String.mk_eq_asString, List.data_asString, Pos.Raw.extract.go₁_append_right _ _ _ _ _ (by rfl)] apply Pos.Raw.extract.go₂_append_left; apply Nat.add_comm theorem splitAux_of_valid (p l m r acc) : splitAux (mk (l ++ m ++ r)) p ⟨utf8Len l⟩ ⟨utf8Len l + utf8Len m⟩ acc = acc.reverse ++ (List.splitOnP.go p r m.reverse).map mk := by unfold splitAux simp only [List.append_assoc, atEnd_iff, endPos_mk, utf8Len_append, Pos.Raw.mk_le_mk, Nat.add_le_add_iff_left, (by omega : utf8Len m + utf8Len r ≤ utf8Len m ↔ utf8Len r = 0), utf8Len_eq_zero, List.reverse_cons, dite_eq_ite] split · subst r; simpa [List.splitOnP.go] using extract_of_valid l m [] · obtain ⟨c, r, rfl⟩ := r.exists_cons_of_ne_nil ‹_› simp only [by simpa [-String.mk_eq_asString] using (⟨get_of_valid (l ++ m) (c :: r), next_of_valid (l ++ m) c r, extract_of_valid l m (c :: r)⟩ : _ ∧ _ ∧ _), List.splitOnP.go, List.reverse_reverse] split <;> rename_i h · simpa [-String.mk_eq_asString, Nat.add_assoc] using splitAux_of_valid p (l++m++[c]) [] r ((mk m)::acc) · simpa [-String.mk_eq_asString, Nat.add_assoc] using splitAux_of_valid p l (m++[c]) r acc theorem splitToList_of_valid (s p) : splitToList s p = (List.splitOnP p s.data).map mk := by simpa [splitToList] using splitAux_of_valid p [] [] s.data [] @[deprecated splitToList_of_valid (since := "2025-10-18")] theorem split_of_valid (s p) : splitToList s p = (List.splitOnP p s.data).map mk := splitToList_of_valid s p -- TODO: splitOn @[simp] theorem toString_toSubstring (s : String) : s.toSubstring.toString = s := extract_zero_endPos _ attribute [simp] toSubstring' theorem join_eq (ss : List String) : join ss = mk (ss.map data).flatten := by suffices ∀ (ss : List String) t, ss.foldl (· ++ ·) t = mk (t.data ++ (ss.map data).flatten) by simpa [join] using this ss "" intro ss t induction ss generalizing t with | nil => simp | cons s ss ih => simp [ih] @[simp] theorem data_join (ss : List String) : (join ss).data = (ss.map data).flatten := by simp [join_eq] namespace Iterator @[simp] theorem forward_eq_nextn : forward = nextn := by funext it n; induction n generalizing it <;> simp [forward, nextn, *] theorem hasNext_cons_addChar (c : Char) (cs : List Char) (i : Pos.Raw) : hasNext ⟨String.mk (c :: cs), i + c⟩ = hasNext ⟨String.mk cs, i⟩ := by simp [hasNext, Nat.add_lt_add_iff_right] /-- Validity for a string iterator. -/ def Valid (it : Iterator) : Prop := it.pos.Valid it.s /-- `it.ValidFor l r` means that `it` is a string iterator whose underlying string is `l.reverse ++ r`, and where the cursor is pointing at the end of `l.reverse`. -/ inductive ValidFor (l r : List Char) : Iterator → Prop /-- The canonical constructor for `ValidFor`. -/ | mk : ValidFor l r ⟨String.mk (l.reverseAux r), ⟨utf8Len l⟩⟩ attribute [simp] toString pos namespace ValidFor theorem valid : ∀ {it}, ValidFor l r it → Valid it | _, ⟨⟩ => by simpa [List.reverseAux_eq] using Pos.Raw.Valid.mk l.reverse r rfl theorem out : ∀ {it}, ValidFor l r it → it = ⟨String.mk (l.reverseAux r), ⟨utf8Len l⟩⟩ | _, ⟨⟩ => rfl theorem out' : ∀ {it}, ValidFor l r it → it = ⟨String.mk (l.reverse ++ r), ⟨utf8Len l.reverse⟩⟩ | _, ⟨⟩ => by simp [List.reverseAux_eq] theorem mk' : ValidFor l r ⟨String.mk (l.reverse ++ r), ⟨utf8Len l.reverse⟩⟩ := by simpa [List.reverseAux_eq] using mk theorem of_eq : ∀ it, it.1.data = l.reverseAux r → it.2.1 = utf8Len l → ValidFor l r it | ⟨s, ⟨_⟩⟩, h, rfl => by rw [← s.asString_data, ← String.mk_eq_asString, h] exact ⟨⟩ theorem _root_.String.validFor_mkIterator (s) : (mkIterator s).ValidFor [] s.data := .of_eq _ (by simp [mkIterator]) (by simp [mkIterator]) theorem remainingBytes : ∀ {it}, ValidFor l r it → it.remainingBytes = utf8Len r | _, ⟨⟩ => by simp [-String.mk_eq_asString, Iterator.remainingBytes, Nat.add_sub_cancel_left, endPos_mk] theorem toString : ∀ {it}, ValidFor l r it → it.1 = String.mk (l.reverseAux r) | _, ⟨⟩ => rfl theorem pos : ∀ {it}, ValidFor l r it → it.2 = ⟨utf8Len l⟩ | _, ⟨⟩ => rfl theorem pos_eq_zero {l r it} (h : ValidFor l r it) : it.2 = 0 ↔ l = [] := by simp [h.pos, Pos.Raw.ext_iff] theorem pos_eq_endPos {l r it} (h : ValidFor l r it) : it.2 = it.1.endPos ↔ r = [] := by simp only [h.pos, h.toString, endPos_mk, utf8Len_reverseAux, Pos.Raw.ext_iff] exact (Nat.add_left_cancel_iff (m := 0)).trans <| eq_comm.trans utf8Len_eq_zero theorem curr : ∀ {it}, ValidFor l r it → it.curr = r.headD default | it, h => by cases h.out'; apply get_of_valid theorem next : ∀ {it}, ValidFor l (c :: r) it → ValidFor (c :: l) r it.next | it, h => by cases h.out' simp only [Iterator.next, next_of_valid l.reverse c r] rw [← List.reverseAux_eq, utf8Len_reverse]; constructor theorem prev : ∀ {it}, ValidFor (c :: l) r it → ValidFor l (c :: r) it.prev | it, h => by cases h.out' have := prev_of_valid l.reverse c r simp only [utf8Len_reverse] at this simp only [Iterator.prev, List.reverse_cons, List.append_assoc, List.singleton_append, utf8Len_append, utf8Len_reverse, utf8Len_cons, utf8Len_nil, Nat.zero_add, this] exact .of_eq _ (by simp [List.reverseAux_eq]) (by simp) theorem prev_nil : ∀ {it}, ValidFor [] r it → ValidFor [] r it.prev | it, h => by simp only [Iterator.prev, h.toString, List.reverseAux_nil, h.pos, utf8Len_nil, Pos.Raw.mk_zero, Pos.Raw.prev_zero] constructor theorem atEnd : ∀ {it}, ValidFor l r it → (it.atEnd ↔ r = []) | it, h => by simp only [Iterator.atEnd, h.pos, h.toString, endPos_mk, utf8Len_reverseAux, ge_iff_le, decide_eq_true_eq] exact Nat.add_le_add_iff_left.trans <| Nat.le_zero.trans utf8Len_eq_zero theorem hasNext : ∀ {it}, ValidFor l r it → (it.hasNext ↔ r ≠ []) | it, h => by simp [Iterator.hasNext, ← h.atEnd, Iterator.atEnd] theorem hasPrev : ∀ {it}, ValidFor l r it → (it.hasPrev ↔ l ≠ []) | it, h => by simp [Iterator.hasPrev, h.pos, Nat.pos_iff_ne_zero] theorem setCurr' : ∀ {it}, ValidFor l r it → ValidFor l (r.modifyHead fun _ => c) (it.setCurr c) | it, h => by cases h.out' simp only [setCurr, utf8Len_reverse] refine .of_eq _ ?_ (by simp) have := set_of_valid l.reverse r c simp only [utf8Len_reverse] at this; simp [-String.mk_eq_asString, List.reverseAux_eq, this] theorem setCurr (h : ValidFor l (c :: r) it) : ValidFor l (c :: r) (it.setCurr c) := h.setCurr' theorem toEnd (h : ValidFor l r it) : ValidFor (r.reverse ++ l) [] it.toEnd := by simp only [Iterator.toEnd, h.toString, endPos_mk, utf8Len_reverseAux] exact .of_eq _ (by simp [List.reverseAux_eq]) (by simp [Nat.add_comm]) theorem toEnd' (it : Iterator) : ValidFor it.s.data.reverse [] it.toEnd := by simp only [Iterator.toEnd] exact .of_eq _ (by simp [List.reverseAux_eq]) (by simp [-size_bytes, -String.mk_eq_asString, endPos, utf8ByteSize]) theorem extract (h₁ : ValidFor l (m ++ r) it₁) (h₂ : ValidFor (m.reverse ++ l) r it₂) : it₁.extract it₂ = String.mk m := by cases h₁.out; cases h₂.out simp only [Iterator.extract, List.reverseAux_eq, List.reverse_append, List.reverse_reverse, List.append_assoc, ne_eq, not_true_eq_false, decide_false, utf8Len_append, utf8Len_reverse, gt_iff_lt, Pos.Raw.lt_iff, Nat.not_lt.2 (Nat.le_add_left ..), Bool.or_self, Bool.false_eq_true, ↓reduceIte] simpa [Nat.add_comm] using extract_of_valid l.reverse m r theorem remainingToString {it} (h : ValidFor l r it) : it.remainingToString = String.mk r := by cases h.out simpa [-String.mk_eq_asString, endPos_mk, Iterator.remainingToString, List.reverseAux_eq] using extract_of_valid l.reverse r [] theorem nextn : ∀ {it}, ValidFor l r it → ∀ n, n ≤ r.length → ValidFor ((r.take n).reverse ++ l) (r.drop n) (it.nextn n) | it, h, 0, _ => by simp [h, Iterator.nextn] | it, h, n+1, hn => by simp only [Iterator.nextn] have a::r := r simpa using h.next.nextn _ (Nat.le_of_succ_le_succ hn) theorem prevn : ∀ {it}, ValidFor l r it → ∀ n, n ≤ l.length → ValidFor (l.drop n) ((l.take n).reverse ++ r) (it.prevn n) | it, h, 0, _ => by simp [h, Iterator.prevn] | it, h, n+1, hn => by simp only [Iterator.prevn] have a::l := l simpa using h.prev.prevn _ (Nat.le_of_succ_le_succ hn) end ValidFor namespace Valid theorem validFor : ∀ {it}, Valid it → ∃ l r, ValidFor l r it | ⟨_, ⟨_⟩⟩, .mk l r rfl => ⟨l.reverse, r, by simpa [List.reverseAux_eq] using @ValidFor.mk l.reverse r⟩ theorem _root_.String.valid_mkIterator (s) : (mkIterator s).Valid := s.validFor_mkIterator.valid theorem remainingBytes_le : ∀ {it}, Valid it → it.remainingBytes ≤ utf8ByteSize it.s | _, h => let ⟨l, r, h⟩ := h.validFor by simp [-String.mk_eq_asString, utf8ByteSize_mk, h.remainingBytes, h.toString, Nat.le_add_left] theorem next : ∀ {it}, Valid it → it.hasNext → Valid it.next | _, h, hn => by let ⟨l, r, h⟩ := h.validFor obtain ⟨c, r, rfl⟩ := List.exists_cons_of_ne_nil (h.hasNext.1 hn) exact h.next.valid theorem prev : ∀ {it}, Valid it → Valid it.prev | _, h => match h.validFor with | ⟨[], _, h⟩ => h.prev_nil.valid | ⟨_::_, _, h⟩ => h.prev.valid theorem setCurr : ∀ {it}, Valid it → Valid (it.setCurr c) | it, h => by let ⟨l, r, h⟩ := h.validFor exact h.setCurr'.valid theorem toEnd (it : String.Iterator) : Valid it.toEnd := (ValidFor.toEnd' _).valid theorem remainingToString {it} (h : ValidFor l r it) : it.remainingToString = String.mk r := by cases h.out simpa [-String.mk_eq_asString, endPos_mk, Iterator.remainingToString, List.reverseAux_eq] using extract_of_valid l.reverse r [] theorem prevn (h : Valid it) : ∀ n, Valid (it.prevn n) | 0 => h | n+1 => h.prev.prevn n end Valid end Iterator @[nolint unusedHavesSuffices] -- false positive from unfolding String.offsetOfPosAux theorem offsetOfPosAux_of_valid : ∀ l m r n, offsetOfPosAux (mk (l ++ m ++ r)) ⟨utf8Len l + utf8Len m⟩ ⟨utf8Len l⟩ n = n + m.length | l, [], r, n => by unfold offsetOfPosAux; simp | l, c::m, r, n => by unfold offsetOfPosAux rw [if_neg (by exact Nat.not_le.2 (Nat.lt_add_of_pos_right add_utf8Size_pos))] simp only [List.append_assoc, atEnd_of_valid l (c::m++r)] simp only [List.cons_append, utf8Len_cons, next_of_valid l c (m ++ r)] simpa [← Nat.add_assoc, Nat.add_right_comm] using offsetOfPosAux_of_valid (l++[c]) m r (n + 1) theorem offsetOfPos_of_valid (l r) : offsetOfPos (mk (l ++ r)) ⟨utf8Len l⟩ = l.length := by simpa using offsetOfPosAux_of_valid [] l r 0 @[nolint unusedHavesSuffices] -- false positive from unfolding String.foldlAux theorem foldlAux_of_valid (f : α → Char → α) : ∀ l m r a, foldlAux f (mk (l ++ m ++ r)) ⟨utf8Len l + utf8Len m⟩ ⟨utf8Len l⟩ a = m.foldl f a | l, [], r, a => by unfold foldlAux; simp | l, c::m, r, a => by unfold foldlAux rw [dif_pos (by exact Nat.lt_add_of_pos_right add_utf8Size_pos)] simp only [List.append_assoc, List.cons_append, utf8Len_cons, next_of_valid l c (m ++ r), get_of_valid l (c :: (m ++ r)), Char.reduceDefault, List.headD_cons, List.foldl_cons] simpa [← Nat.add_assoc, Nat.add_right_comm] using foldlAux_of_valid f (l++[c]) m r (f a c) theorem foldl_eq (f : α → Char → α) (s a) : foldl f a s = s.data.foldl f a := by simpa using foldlAux_of_valid f [] s.data [] a @[nolint unusedHavesSuffices] -- false positive from unfolding String.foldrAux theorem foldrAux_of_valid (f : Char → α → α) (l m r a) : foldrAux f a (mk (l ++ m ++ r)) ⟨utf8Len l + utf8Len m⟩ ⟨utf8Len l⟩ = m.foldr f a := by rw [← m.reverse_reverse] induction m.reverse generalizing r a with (unfold foldrAux; simp) | cons c m IH => rw [if_pos add_utf8Size_pos] simp only [← Nat.add_assoc, by simpa using prev_of_valid (l ++ m.reverse) c r] simp only [by simpa using get_of_valid (l ++ m.reverse) (c :: r)] simpa using IH (c::r) (f c a) theorem foldr_eq (f : Char → α → α) (s a) : foldr f a s = s.data.foldr f a := by simpa using foldrAux_of_valid f [] s.data [] a @[nolint unusedHavesSuffices] -- false positive from unfolding String.anyAux theorem anyAux_of_valid (p : Char → Bool) : ∀ l m r, anyAux (mk (l ++ m ++ r)) ⟨utf8Len l + utf8Len m⟩ p ⟨utf8Len l⟩ = m.any p | l, [], r => by unfold anyAux; simp | l, c::m, r => by unfold anyAux rw [dif_pos (by exact Nat.lt_add_of_pos_right add_utf8Size_pos)] simp only [List.append_assoc, List.cons_append, get_of_valid l (c :: (m ++ r)), Char.reduceDefault, List.headD_cons, utf8Len_cons, next_of_valid l c (m ++ r), Bool.if_true_left, Bool.decide_eq_true, List.any_cons] cases p c <;> simp simpa [← Nat.add_assoc, Nat.add_right_comm] using anyAux_of_valid p (l++[c]) m r theorem any_eq (s : String) (p : Char → Bool) : any s p = s.data.any p := by simpa using anyAux_of_valid p [] s.data [] theorem any_iff (s : String) (p : Char → Bool) : any s p ↔ ∃ c ∈ s.data, p c := by simp [any_eq] theorem all_eq (s : String) (p : Char → Bool) : all s p = s.data.all p := by rw [all, any_eq, List.all_eq_not_any_not] theorem all_iff (s : String) (p : Char → Bool) : all s p ↔ ∀ c ∈ s.data, p c := by simp [all_eq] theorem contains_iff (s : String) (c : Char) : contains s c ↔ c ∈ s.data := by simp [contains, any_iff] @[nolint unusedHavesSuffices] -- false positive from unfolding String.mapAux theorem mapAux_of_valid (f : Char → Char) : ∀ l r, mapAux f ⟨utf8Len l⟩ (mk (l ++ r)) = mk (l ++ r.map f) | l, [] => by unfold mapAux; simp | l, c::r => by unfold mapAux rw [dif_neg (by rw [atEnd_of_valid]; simp)] simp only [← String.mk_eq_asString, get_of_valid l (c :: r), Char.reduceDefault, List.headD_cons, set_of_valid l (c :: r), List.modifyHead_cons, next_of_valid l (f c) r, List.map_cons] simpa using mapAux_of_valid f (l++[f c]) r theorem map_eq (f : Char → Char) (s) : map f s = mk (s.data.map f) := by simpa using mapAux_of_valid f [] s.data -- TODO: substrEq -- TODO: isPrefixOf -- TODO: replace @[nolint unusedHavesSuffices] -- false positive from unfolding String.takeWhileAux theorem takeWhileAux_of_valid (p : Char → Bool) : ∀ l m r, Substring.takeWhileAux (mk (l ++ m ++ r)) ⟨utf8Len l + utf8Len m⟩ p ⟨utf8Len l⟩ = ⟨utf8Len l + utf8Len (m.takeWhile p)⟩ | l, [], r => by unfold Substring.takeWhileAux List.takeWhile; simp | l, c::m, r => by unfold Substring.takeWhileAux List.takeWhile rw [dif_pos (by exact Nat.lt_add_of_pos_right add_utf8Size_pos)] simp only [List.append_assoc, List.cons_append, get_of_valid l (c :: (m ++ r)), Char.reduceDefault, List.headD_cons, utf8Len_cons, next_of_valid l c (m ++ r)] cases p c <;> simp simpa [← Nat.add_assoc, Nat.add_right_comm] using takeWhileAux_of_valid p (l++[c]) m r @[simp] theorem map_eq_empty_iff (s : String) (f : Char → Char) : (s.map f) = "" ↔ s = "" := by simp only [map_eq, ← data_eq_nil_iff, String.mk_eq_asString, List.data_asString, List.map_eq_nil_iff] @[simp] theorem map_isEmpty_eq_isEmpty (s : String) (f : Char → Char) : (s.map f).isEmpty = s.isEmpty := by rw [Bool.eq_iff_iff]; simp [isEmpty_iff, map_eq_empty_iff] @[simp] theorem length_map (s : String) (f : Char → Char) : (s.map f).length = s.length := by simp only [← length_data, map_eq, String.mk_eq_asString, List.data_asString, List.length_map] theorem length_eq_of_map_eq {a b : String} {f g : Char → Char} : a.map f = b.map g → a.length = b.length := by intro h; rw [← length_map a f, ← length_map b g, h] end String open String namespace Substring /-- Validity for a substring. -/ structure Valid (s : Substring) : Prop where /-- The start position of a valid substring is valid. -/ startValid : s.startPos.Valid s.str /-- The stop position of a valid substring is valid. -/ stopValid : s.stopPos.Valid s.str /-- The stop position of a substring is at least the start. -/ le : s.startPos ≤ s.stopPos theorem Valid_default : Valid default := ⟨Pos.Raw.valid_zero, Pos.Raw.valid_zero, Nat.le_refl _⟩ /-- A substring is represented by three lists `l m r`, where `m` is the middle section (the actual substring) and `l ++ m ++ r` is the underlying string. -/ inductive ValidFor (l m r : List Char) : Substring → Prop /-- The constructor for `ValidFor`. -/ | mk : ValidFor l m r ⟨String.mk (l ++ m ++ r), ⟨utf8Len l⟩, ⟨utf8Len l + utf8Len m⟩⟩ namespace ValidFor theorem valid : ∀ {s}, ValidFor l m r s → Valid s | _, ⟨⟩ => ⟨.intro ⟨l, m ++ r, by simp⟩, .intro ⟨l ++ m, r, by simp⟩, Nat.le_add_right ..⟩ theorem of_eq : ∀ s, s.str.data = l ++ m ++ r → s.startPos.1 = utf8Len l → s.stopPos.1 = utf8Len l + utf8Len m → ValidFor l m r s | ⟨s, ⟨_⟩, ⟨_⟩⟩, h, rfl, rfl => by rw [← s.asString_data, h] exact ⟨⟩ theorem _root_.String.validFor_toSubstring (s : String) : ValidFor [] s.data [] s := .of_eq _ (by simp [toSubstring]) rfl (by simp [toSubstring, endPos]) theorem str : ∀ {s}, ValidFor l m r s → s.str = String.mk (l ++ m ++ r) | _, ⟨⟩ => rfl theorem startPos : ∀ {s}, ValidFor l m r s → s.startPos = ⟨utf8Len l⟩ | _, ⟨⟩ => rfl theorem stopPos : ∀ {s}, ValidFor l m r s → s.stopPos = ⟨utf8Len l + utf8Len m⟩ | _, ⟨⟩ => rfl theorem bsize : ∀ {s}, ValidFor l m r s → s.bsize = utf8Len m | _, ⟨⟩ => by simp [Substring.bsize, Nat.add_sub_cancel_left] theorem isEmpty : ∀ {s}, ValidFor l m r s → (s.isEmpty ↔ m = []) | _, h => by simp [Substring.isEmpty, h.bsize] theorem toString : ∀ {s}, ValidFor l m r s → s.toString = String.mk m | _, ⟨⟩ => extract_of_valid l m r theorem toIterator : ∀ {s}, ValidFor l m r s → s.toIterator.ValidFor l.reverse (m ++ r) | _, h => by simp only [Substring.toIterator] exact .of_eq _ (by simp [h.str, List.reverseAux_eq]) (by simp [h.startPos]) theorem get : ∀ {s}, ValidFor l (m₁ ++ c :: m₂) r s → s.get ⟨utf8Len m₁⟩ = c | _, ⟨⟩ => by simpa using get_of_valid (l ++ m₁) (c :: m₂ ++ r) theorem next : ∀ {s}, ValidFor l (m₁ ++ c :: m₂) r s → s.next ⟨utf8Len m₁⟩ = ⟨utf8Len m₁ + c.utf8Size⟩ | _, ⟨⟩ => by simp only [Substring.next, utf8Len_append, utf8Len_cons, List.append_assoc, List.cons_append] rw [if_neg (mt Pos.Raw.ext_iff.1 ?a)] case a => simpa [Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using @ne_add_utf8Size_add_self (utf8Len l + utf8Len m₁) (utf8Len m₂) c have := next_of_valid (l ++ m₁) c (m₂ ++ r) simp only [List.append_assoc, utf8Len_append, Pos.Raw.offsetBy_eq] at this ⊢; rw [this] simp [Nat.add_assoc, Nat.add_sub_cancel_left] theorem next_stop : ∀ {s}, ValidFor l m r s → s.next ⟨utf8Len m⟩ = ⟨utf8Len m⟩ | _, ⟨⟩ => by simp [Substring.next, Pos.Raw.offsetBy_eq] theorem prev : ∀ {s}, ValidFor l (m₁ ++ c :: m₂) r s → s.prev ⟨utf8Len m₁ + c.utf8Size⟩ = ⟨utf8Len m₁⟩ | _, ⟨⟩ => by simp only [Substring.prev, List.append_assoc, List.cons_append] rw [if_neg (mt Pos.Raw.ext_iff.1 <| Ne.symm ?a)] case a => simpa [Nat.add_comm] using @ne_add_utf8Size_add_self (utf8Len l) (utf8Len m₁) c have := prev_of_valid (l ++ m₁) c (m₂ ++ r) simp only [List.append_assoc, utf8Len_append, Nat.add_assoc, Pos.Raw.offsetBy_eq] at this ⊢; rw [this] simp [Nat.add_sub_cancel_left] theorem nextn_stop : ∀ {s}, ValidFor l m r s → ∀ n, s.nextn n ⟨utf8Len m⟩ = ⟨utf8Len m⟩ | _, _, 0 => rfl | _, h, n+1 => by simp [Substring.nextn, h.next_stop, h.nextn_stop n] theorem nextn : ∀ {s}, ValidFor l (m₁ ++ m₂) r s → ∀ n, s.nextn n ⟨utf8Len m₁⟩ = ⟨utf8Len m₁ + utf8Len (m₂.take n)⟩ | _, _, 0 => by simp [Substring.nextn] | s, h, n+1 => by simp only [Substring.nextn] match m₂ with | [] => simp at h; simp [h.next_stop, h.nextn_stop] | c::m₂ => rw [h.next] have := @nextn l (m₁ ++ [c]) m₂ r s (by simp [h]) n simp at this; rw [this]; simp [Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] theorem prevn : ∀ {s}, ValidFor l (m₁.reverse ++ m₂) r s → ∀ n, s.prevn n ⟨utf8Len m₁⟩ = ⟨utf8Len (m₁.drop n)⟩ | _, _, 0 => by simp [Substring.prevn] | s, h, n+1 => by simp only [Substring.prevn] match m₁ with | [] => simp | c::m₁ => rw [List.reverse_cons, List.append_assoc] at h have := h.prev; simp at this; simp [this, h.prevn n] theorem front : ∀ {s}, ValidFor l (c :: m) r s → s.front = c | _, h => h.get (m₁ := []) theorem drop : ∀ {s}, ValidFor l m r s → ∀ n, ValidFor (l ++ m.take n) (m.drop n) r (s.drop n) | s, h, n => by have : Substring.nextn {..} .. = _ := h.nextn (m₁ := []) n simp only [utf8Len_nil, Pos.Raw.mk_zero, Nat.zero_add] at this simp only [Substring.drop, this] simp only [h.str, List.append_assoc, h.startPos, h.stopPos] rw [← List.take_append_drop n m] at h refine .of_eq _ (by simp) (by simp) ?_ conv => lhs; rw [← List.take_append_drop n m] simp [-List.take_append_drop, Nat.add_assoc] theorem take : ∀ {s}, ValidFor l m r s → ∀ n, ValidFor l (m.take n) (m.drop n ++ r) (s.take n) | s, h, n => by have : Substring.nextn {..} .. = _ := h.nextn (m₁ := []) n simp at this simp only [Substring.take, this] simp only [h.str, List.append_assoc, h.startPos] rw [← List.take_append_drop n m] at h refine .of_eq _ ?_ (by simp) (by simp) conv => lhs; rw [← List.take_append_drop n m] simp [-List.take_append_drop] -- TODO: takeRight, dropRight theorem atEnd : ∀ {s}, ValidFor l m r s → (s.atEnd ⟨p⟩ ↔ p = utf8Len m) | _, ⟨⟩ => by simp [Substring.atEnd, Pos.Raw.ext_iff, Nat.add_left_cancel_iff] theorem extract' : ∀ {s}, ValidFor l (ml ++ mm ++ mr) r s → ValidFor ml mm mr ⟨String.mk (ml ++ mm ++ mr), b, e⟩ → ∃ l' r', ValidFor l' mm r' (s.extract b e) | _, ⟨⟩, ⟨⟩ => by simp only [Substring.extract, ge_iff_le, Pos.Raw.mk_le_mk, List.append_assoc, utf8Len_append] split · next h => rw [utf8Len_eq_zero.1 <| Nat.le_zero.1 <| Nat.add_le_add_iff_left.1 h] exact ⟨[], [], ⟨⟩⟩ · next h => refine ⟨l ++ ml, mr ++ r, .of_eq _ (by simp) ?_ ?_⟩ <;> simp only [Pos.Raw.byteIdx_offsetBy, Nat.min_eq_min, utf8Len_append] <;> rw [Nat.min_eq_right] <;> try simp [Nat.add_le_add_iff_left, Nat.le_add_right] rw [Nat.add_assoc] theorem extract : ∀ {s}, ValidFor l m r s → ValidFor ml mm mr ⟨String.mk m, b, e⟩ → ∃ l' r', ValidFor l' mm r' (s.extract b e) := by intro s h₁ h₂ obtain rfl : m = ml ++ mm ++ mr := by simpa using congrArg String.data h₂.str exact extract' h₁ h₂ -- TODO: splitOn theorem foldl (f) (init : α) : ∀ {s}, ValidFor l m r s → s.foldl f init = m.foldl f init | _, ⟨⟩ => by simp [-String.mk_eq_asString, -List.append_assoc, Substring.foldl, foldlAux_of_valid] theorem foldr (f) (init : α) : ∀ {s}, ValidFor l m r s → s.foldr f init = m.foldr f init | _, ⟨⟩ => by simp [-String.mk_eq_asString, -List.append_assoc, Substring.foldr, foldrAux_of_valid] theorem any (f) : ∀ {s}, ValidFor l m r s → s.any f = m.any f | _, ⟨⟩ => by simp [-String.mk_eq_asString, -List.append_assoc, Substring.any, anyAux_of_valid] theorem all (f) : ∀ {s}, ValidFor l m r s → s.all f = m.all f | _, h => by simp [Substring.all, h.any, List.all_eq_not_any_not] theorem contains (c) : ∀ {s}, ValidFor l m r s → (s.contains c ↔ c ∈ m) | _, h => by simp [Substring.contains, h.any] theorem takeWhile (p : Char → Bool) : ∀ {s}, ValidFor l m r s → ValidFor l (m.takeWhile p) (m.dropWhile p ++ r) (s.takeWhile p) | _, ⟨⟩ => by simp only [Substring.takeWhile, takeWhileAux_of_valid] apply ValidFor.of_eq <;> simp rw [← List.append_assoc, List.takeWhile_append_dropWhile] theorem dropWhile (p : Char → Bool) : ∀ {s}, ValidFor l m r s → ValidFor (l ++ m.takeWhile p) (m.dropWhile p) r (s.dropWhile p) | _, ⟨⟩ => by simp only [Substring.dropWhile, takeWhileAux_of_valid] apply ValidFor.of_eq <;> simp rw [Nat.add_assoc, ← utf8Len_append (m.takeWhile p), List.takeWhile_append_dropWhile] -- TODO: takeRightWhile end ValidFor namespace Valid theorem validFor : ∀ {s}, Valid s → ∃ l m r, ValidFor l m r s | ⟨_, ⟨_⟩, ⟨_⟩⟩, ⟨.mk l mr rfl, t, h⟩ => by obtain ⟨lm, r, h₁, h₂⟩ := t.exists have e : lm ++ r = l ++ mr := by simpa [← List.asString_inj, ← String.bytes_inj] using h₁ obtain rfl := Pos.Raw.ext_iff.1 h₂ simp only [Pos.Raw.mk_le_mk] at * have := (or_iff_right_iff_imp.2 fun h => ?x).1 (List.append_eq_append_iff.1 e) case x => match l, r, h with | _, _, ⟨m, rfl, rfl⟩ => ?_ simp only [utf8Len_append] at h cases utf8Len_eq_zero.1 <| Nat.le_zero.1 (Nat.le_of_add_le_add_left (c := 0) h) exact ⟨[], by simp⟩ match lm, mr, this with | _, _, ⟨m, rfl, rfl⟩ => exact ⟨l, m, r, by simpa using ValidFor.mk⟩ theorem valid : ∀ {s}, ValidFor l m r s → Valid s | _, ⟨⟩ => ⟨.intro ⟨l, m ++ r, by simp, by simp⟩, .intro ⟨l ++ m, r, by simp, by simp⟩, Nat.le_add_right ..⟩ theorem _root_.String.valid_toSubstring (s : String) : Valid s := s.validFor_toSubstring.valid theorem bsize : ∀ {s}, Valid s → s.bsize = utf8Len s.toString.data | _, h => let ⟨l, m, r, h⟩ := h.validFor; by simp [h.bsize, h.toString] theorem isEmpty : ∀ {s}, Valid s → (s.isEmpty ↔ s.toString = "") | _, h => let ⟨l, m, r, h⟩ := h.validFor; by simp [h.isEmpty, h.toString, String.ext_iff] theorem get : ∀ {s}, Valid s → s.toString.data = m₁ ++ c :: m₂ → s.get ⟨utf8Len m₁⟩ = c | _, h, e => by let ⟨l, m, r, h⟩ := h.validFor simp only [h.toString, String.mk_eq_asString, List.data_asString] at e; subst e; simp [h.get] theorem next : ∀ {s}, Valid s → s.toString.data = m₁ ++ c :: m₂ → s.next ⟨utf8Len m₁⟩ = ⟨utf8Len m₁ + c.utf8Size⟩ | _, h, e => by let ⟨l, m, r, h⟩ := h.validFor simp only [h.toString, String.mk_eq_asString, List.data_asString] at e; subst e; simp [h.next] theorem next_stop : ∀ {s}, Valid s → s.next ⟨s.bsize⟩ = ⟨s.bsize⟩ | _, h => let ⟨l, m, r, h⟩ := h.validFor; by simp [h.bsize, h.next_stop] theorem prev : ∀ {s}, Valid s → s.toString.data = m₁ ++ c :: m₂ → s.prev ⟨utf8Len m₁ + c.utf8Size⟩ = ⟨utf8Len m₁⟩ | _, h, e => by let ⟨l, m, r, h⟩ := h.validFor simp only [h.toString, String.mk_eq_asString, List.data_asString] at e; subst e; simp [h.prev] theorem nextn_stop : ∀ {s}, Valid s → ∀ n, s.nextn n ⟨s.bsize⟩ = ⟨s.bsize⟩ | _, h, n => let ⟨l, m, r, h⟩ := h.validFor; by simp [h.bsize, h.nextn_stop] theorem nextn : ∀ {s}, Valid s → s.toString.data = m₁ ++ m₂ → ∀ n, s.nextn n ⟨utf8Len m₁⟩ = ⟨utf8Len m₁ + utf8Len (m₂.take n)⟩ | _, h, e => by let ⟨l, m, r, h⟩ := h.validFor simp only [h.toString, String.mk_eq_asString, List.data_asString] at e; subst e; simp [h.nextn] theorem prevn : ∀ {s}, Valid s → s.toString.data = m₁.reverse ++ m₂ → ∀ n, s.prevn n ⟨utf8Len m₁⟩ = ⟨utf8Len (m₁.drop n)⟩ | _, h, e => by let ⟨l, m, r, h⟩ := h.validFor simp only [h.toString, String.mk_eq_asString, List.data_asString] at e; subst e; simp [h.prevn] theorem front : ∀ {s}, Valid s → s.toString.data = c :: m → s.front = c | _, h => h.get (m₁ := []) theorem drop : ∀ {s}, Valid s → ∀ n, Valid (s.drop n) | _, h, _ => let ⟨_, _, _, h⟩ := h.validFor; (h.drop _).valid theorem data_drop : ∀ {s}, Valid s → ∀ n, (s.drop n).toString.data = s.toString.data.drop n | _, h, _ => let ⟨_, _, _, h⟩ := h.validFor; by simp [(h.drop _).toString, h.toString] theorem take : ∀ {s}, Valid s → ∀ n, Valid (s.take n) | _, h, _ => let ⟨_, _, _, h⟩ := h.validFor; (h.take _).valid theorem data_take : ∀ {s}, Valid s → ∀ n, (s.take n).toString.data = s.toString.data.take n | _, h, _ => let ⟨_, _, _, h⟩ := h.validFor; by simp [(h.take _).toString, h.toString] -- TODO: takeRight, dropRight theorem atEnd : ∀ {s}, Valid s → (s.atEnd ⟨p⟩ ↔ p = utf8ByteSize s.toString) | _, h => let ⟨_, _, _, h⟩ := h.validFor; by simp [-String.mk_eq_asString, utf8ByteSize_mk, h.atEnd, h.toString] theorem extract : ∀ {s}, Valid s → Valid ⟨s.toString, b, e⟩ → Valid (s.extract b e) | _, h₁, h₂ => by let ⟨l, m, r, h₁⟩ := h₁.validFor rw [h₁.toString] at h₂ let ⟨ml, mm, mr, h₂⟩ := h₂.validFor have ⟨l', r', h₃⟩ := h₁.extract h₂ exact h₃.valid theorem toString_extract : ∀ {s}, Valid s → Valid ⟨s.toString, b, e⟩ → (s.extract b e).toString = String.Pos.Raw.extract s.toString b e | _, h₁, h₂ => by let ⟨l, m, r, h₁⟩ := h₁.validFor rw [h₁.toString] at h₂ let ⟨ml, mm, mr, h₂⟩ := h₂.validFor have ⟨l', r', h₃⟩ := h₁.extract h₂ rw [h₃.toString, h₁.toString, ← h₂.toString, toString] theorem foldl (f) (init : α) : ∀ {s}, Valid s → s.foldl f init = s.toString.data.foldl f init | _, h => let ⟨_, _, _, h⟩ := h.validFor; by simp [h.foldl, h.toString] theorem foldr (f) (init : α) : ∀ {s}, Valid s → s.foldr f init = s.toString.data.foldr f init | _, h => let ⟨_, _, _, h⟩ := h.validFor; by simp [h.foldr, h.toString] theorem any (f) : ∀ {s}, Valid s → s.any f = s.toString.data.any f | _, h => let ⟨_, _, _, h⟩ := h.validFor; by simp [h.any, h.toString] theorem all (f) : ∀ {s}, Valid s → s.all f = s.toString.data.all f | _, h => let ⟨_, _, _, h⟩ := h.validFor; by simp [h.all, h.toString] theorem contains (c) : ∀ {s}, Valid s → (s.contains c ↔ c ∈ s.toString.data) | _, h => let ⟨_, _, _, h⟩ := h.validFor; by simp [h.contains, h.toString] theorem takeWhile (p : Char → Bool) : ∀ {s}, Valid s → Valid (s.takeWhile p) | _, h => let ⟨_, _, _, h⟩ := h.validFor; (h.takeWhile _).valid theorem data_takeWhile (p) : ∀ {s}, Valid s → (s.takeWhile p).toString.data = s.toString.data.takeWhile p | _, h => let ⟨_, _, _, h⟩ := h.validFor; by simp [(h.takeWhile _).toString, h.toString] theorem dropWhile (p : Char → Bool) : ∀ {s}, Valid s → Valid (s.dropWhile p) | _, h => let ⟨_, _, _, h⟩ := h.validFor; (h.dropWhile _).valid theorem data_dropWhile (p) : ∀ {s}, Valid s → (s.dropWhile p).toString.data = s.toString.data.dropWhile p | _, h => let ⟨_, _, _, h⟩ := h.validFor; by simp [(h.dropWhile _).toString, h.toString] -- TODO: takeRightWhile end Valid end Substring namespace String theorem drop_eq (s : String) (n : Nat) : s.drop n = mk (s.data.drop n) := (s.validFor_toSubstring.drop n).toString @[simp] theorem data_drop (s : String) (n : Nat) : (s.drop n).data = s.data.drop n := by simp [drop_eq] @[simp] theorem drop_empty {n : Nat} : "".drop n = "" := by simp [drop_eq, List.drop_nil] theorem take_eq (s : String) (n : Nat) : s.take n = mk (s.data.take n) := (s.validFor_toSubstring.take n).toString @[simp] theorem data_take (s : String) (n : Nat) : (s.take n).data = s.data.take n := by simp [take_eq] theorem takeWhile_eq (p : Char → Bool) (s : String) : s.takeWhile p = mk (s.data.takeWhile p) := (s.validFor_toSubstring.takeWhile p).toString @[simp] theorem data_takeWhile (p : Char → Bool) (s : String) : (s.takeWhile p).data = s.data.takeWhile p := by simp [takeWhile_eq] theorem dropWhile_eq (p : Char → Bool) (s : String) : s.dropWhile p = mk (s.data.dropWhile p) := (s.validFor_toSubstring.dropWhile p).toString @[simp] theorem data_dropWhile (p : Char → Bool) (s : String) : (s.dropWhile p).data = s.data.dropWhile p := by simp [dropWhile_eq] end String
.lake/packages/batteries/Batteries/Data/String/AsciiCasing.lean
module public import Batteries.Data.Char public import Batteries.Data.Char.AsciiCasing @[expose] public section namespace String /-- Case folding for ASCII characters only. Alphabetic ASCII characters are mapped to their lowercase form, all other characters are left unchanged. This agrees with the Unicode case folding algorithm for ASCII characters. ``` #eval "ABC".caseFoldAsciiOnly == "abc" -- true #eval "x".caseFoldAsciiOnly == "y" -- false #eval "Àà".caseFoldAsciiOnly == "Àà" -- true #eval "1$#!".caseFoldAsciiOnly == "1$#!" -- true ``` -/ abbrev caseFoldAsciiOnly (s : String) := s.map Char.caseFoldAsciiOnly -- TODO: Reimplement with finite iterators/streams when available for `String`. private partial def beqCaseInsensitiveAsciiOnlyImpl (s₁ s₂ : String) : Bool := s₁.length == s₂.length && loop (ToStream.toStream s₁) (ToStream.toStream s₂) where loop i₁ i₂ := match Stream.next? i₁, Stream.next? i₂ with | some (c₁, i₁), some (c₂, i₂) => c₁.beqCaseInsensitiveAsciiOnly c₂ && loop i₁ i₂ | none, none => true | _, _ => false /-- Bool-valued comparison of two `String`s for *ASCII*-case insensitive equality. #eval "abc".beqCaseInsensitiveAsciiOnly "ABC" -- true #eval "cba".beqCaseInsensitiveAsciiOnly "ABC" -- false #eval "$".beqCaseInsensitiveAsciiOnly "$" -- true #eval "a".beqCaseInsensitiveAsciiOnly "b" -- false #eval "γ".beqCaseInsensitiveAsciiOnly "Γ" -- false -/ @[implemented_by beqCaseInsensitiveAsciiOnlyImpl] def beqCaseInsensitiveAsciiOnly (s₁ s₂ : String) : Bool := s₁.caseFoldAsciiOnly == s₂.caseFoldAsciiOnly theorem beqCaseInsensitiveAsciiOnly.eqv : Equivalence (beqCaseInsensitiveAsciiOnly · ·) := { refl _ := BEq.rfl trans _ _ := by simp_all [beqCaseInsensitiveAsciiOnly] symm := by simp_all [beqCaseInsensitiveAsciiOnly] } /-- Setoid structure on `String` usig `beqCaseInsensitiveAsciiOnly` -/ def beqCaseInsensitiveAsciiOnly.isSetoid : Setoid String := ⟨(beqCaseInsensitiveAsciiOnly · ·), beqCaseInsensitiveAsciiOnly.eqv⟩ -- TODO: Reimplement with finite iterators/streams when available for `String`. private partial def cmpCaseInsensitiveAsciiOnlyImpl (s₁ s₂ : String) : Ordering := loop (ToStream.toStream s₁) (ToStream.toStream s₂) where loop i₁ i₂ := match Stream.next? i₁, Stream.next? i₂ with | some (c₁, i₁), some (c₂, i₂) => c₁.cmpCaseInsensitiveAsciiOnly c₂ |>.then (loop i₁ i₂) | some _, none => .gt | none, some _ => .lt | none, none => .eq /-- ASCII-case insensitive implementation comparison returning an `Ordering`. Useful for sorting. ``` #eval cmpCaseInsensitiveAsciiOnly "a" "A" -- eq #eval cmpCaseInsensitiveAsciiOnly "a" "a" -- eq #eval cmpCaseInsensitiveAsciiOnly "$" "$" -- eq #eval cmpCaseInsensitiveAsciiOnly "a" "b" -- lt #eval cmpCaseInsensitiveAsciiOnly "γ" "Γ" -- gt ``` -/ @[implemented_by cmpCaseInsensitiveAsciiOnlyImpl] def cmpCaseInsensitiveAsciiOnly (s₁ s₂ : String) : Ordering := compare s₁.caseFoldAsciiOnly s₂.caseFoldAsciiOnly
.lake/packages/batteries/Batteries/Data/String/Matcher.lean
module public import Batteries.Data.Array.Match public import Batteries.Data.String.Basic @[expose] public section namespace String /-- Knuth-Morris-Pratt matcher type This type is used to keep data for running the Knuth-Morris-Pratt (KMP) string matching algorithm. KMP is a linear time algorithm to locate all substrings of a string that match a given pattern. Generating the algorithm data is also linear in the length of the pattern but the data can be re-used to match the same pattern over different strings. The KMP data for a pattern string can be generated using `Matcher.ofString`. Then `Matcher.find?` and `Matcher.findAll` can be used to run the algorithm on an input string. ``` def m := Matcher.ofString "abba" #eval Option.isSome <| m.find? "AbbabbA" -- false #eval Option.isSome <| m.find? "aabbaa" -- true #eval Array.size <| m.findAll "abbabba" -- 2 #eval Array.size <| m.findAll "abbabbabba" -- 3 ``` -/ structure Matcher extends Array.Matcher Char where /-- The pattern for the matcher -/ pattern : Substring /-- Make KMP matcher from pattern substring -/ @[inline] def Matcher.ofSubstring (pattern : Substring) : Matcher where toMatcher := Array.Matcher.ofStream pattern pattern := pattern /-- Make KMP matcher from pattern string -/ @[inline] def Matcher.ofString (pattern : String) : Matcher := Matcher.ofSubstring pattern /-- The byte size of the string pattern for the matcher -/ abbrev Matcher.patternSize (m : Matcher) : Nat := m.pattern.bsize /-- Find all substrings of `s` matching `m.pattern`. -/ partial def Matcher.findAll (m : Matcher) (s : Substring) : Array Substring := loop s m.toMatcher #[] where /-- Accumulator loop for `String.Matcher.findAll` -/ loop (s : Substring) (am : Array.Matcher Char) (occs : Array Substring) : Array Substring := match am.next? s with | none => occs | some (s, am) => loop s am <| occs.push { s with startPos := ⟨s.startPos.byteIdx - m.patternSize⟩ stopPos := s.startPos } /-- Find the first substring of `s` matching `m.pattern`, or `none` if no such substring exists. -/ def Matcher.find? (m : Matcher) (s : Substring) : Option Substring := match m.next? s with | none => none | some (s, _) => some { s with startPos := ⟨s.startPos.byteIdx - m.patternSize⟩ stopPos := s.startPos } end String namespace Substring /-- Returns all the substrings of `s` that match `pattern`. -/ @[inline] def findAllSubstr (s pattern : Substring) : Array Substring := (String.Matcher.ofSubstring pattern).findAll s /-- Returns the first substring of `s` that matches `pattern`, or `none` if there is no such substring. -/ @[inline] def findSubstr? (s pattern : Substring) : Option Substring := (String.Matcher.ofSubstring pattern).find? s /-- Returns true iff `pattern` occurs as a substring of `s`. -/ @[inline] def containsSubstr (s pattern : Substring) : Bool := s.findSubstr? pattern |>.isSome end Substring namespace String @[inherit_doc Substring.findAllSubstr] abbrev findAllSubstr (s : String) (pattern : Substring) : Array Substring := (String.Matcher.ofSubstring pattern).findAll s @[inherit_doc Substring.findSubstr?] abbrev findSubstr? (s : String) (pattern : Substring) : Option Substring := s.toSubstring.findSubstr? pattern @[inherit_doc Substring.containsSubstr] abbrev containsSubstr (s : String) (pattern : Substring) : Bool := s.toSubstring.containsSubstr pattern end String
.lake/packages/batteries/Batteries/Data/String/Basic.lean
module @[expose] public section instance : Coe String Substring := ⟨String.toSubstring⟩ namespace String /-- Count the occurrences of a character in a string. -/ def count (s : String) (c : Char) : Nat := s.foldl (fun n d => if d = c then n + 1 else n) 0 /-- Convert a string of assumed-ASCII characters into a byte array. (If any characters are non-ASCII they will be reduced modulo 256.) Note: if you just need the underlying `ByteArray` of a non-ASCII string, use `String.toUTF8`. -/ def toAsciiByteArray (s : String) : ByteArray := let rec /-- Internal implementation of `toAsciiByteArray`. `loop p out = out ++ toAsciiByteArray ({ s with startPos := p } : Substring)` -/ loop (p : Pos.Raw) (out : ByteArray) : ByteArray := if h : p.atEnd s then out else let c := p.get s have : utf8ByteSize s - (Pos.Raw.next s p).byteIdx < utf8ByteSize s - p.byteIdx := Nat.sub_lt_sub_left (Nat.lt_of_not_le <| mt decide_eq_true h) (Nat.lt_add_of_pos_right (Char.utf8Size_pos _)) loop (p.next s) (out.push c.toUInt8) termination_by utf8ByteSize s - p.byteIdx loop 0 ByteArray.empty
.lake/packages/batteries/Batteries/Data/Random/MersenneTwister.lean
module public section /-! # Mersenne Twister Generic implementation for the Mersenne Twister pseudorandom number generator. All choices of parameters from Matsumoto and Nishimura (1998) are supported, along with later refinements. Parameters for the standard 32-bit MT19937 and 64-bit MT19937-64 algorithms are provided. Both `RandomGen` and `Stream` interfaces are provided. Use `mt19937.init seed` to create a MT19937 PRNG with a 32 bit seed value; use `mt19937_64.init seed` to create a MT19937-64 PRNG with a 64 bit seed value. If omitted, default seed choices will be used. Sample usage: ``` import Batteries.Data.Random.MersenneTwister open Batteries.Random.MersenneTwister def mtgen := mt19937.init -- default seed 4357 #eval (Stream.take mtgen 5).fst -- [874448474, 2424656266, 2174085406, 1265871120, 3155244894] ``` ### References: - Matsumoto, Makoto and Nishimura, Takuji (1998), [**Mersenne twister: A 623-dimensionally equidistributed uniform pseudo-random number generator**](https://doi.org/10.1145/272991.272995), ACM Trans. Model. Comput. Simul. 8, No. 1, 3-30. [ZBL0917.65005](https://zbmath.org/?q=an:0917.65005). - Nishimura, Takuji (2000), [**Tables of 64-bit Mersenne twisters**](https://doi.org/10.1145/369534.369540), ACM Trans. Model. Comput. Simul. 10, No. 4, 348-357. [ZBL1390.65014](https://zbmath.org/?q=an:1390.65014). -/ namespace Batteries.Random.MersenneTwister /-- Mersenne Twister configuration. Letters in parentheses correspond to variable names used by Matsumoto and Nishimura (1998) and Nishimura (2000). -/ structure Config where /-- Word size (`w`). -/ wordSize : Nat /-- Degree of recurrence (`n`). -/ stateSize : Nat /-- Middle word (`m`). -/ shiftSize : Fin stateSize /-- Twist value (`r`). -/ maskBits : Fin wordSize /-- Coefficients of the twist matrix (`a`). -/ xorMask : BitVec wordSize /-- Tempering shift parameters (`u`, `s`, `t`, `l`). -/ temperingShifts : Nat × Nat × Nat × Nat /-- Tempering mask parameters (`d`, `b`, `c`). -/ temperingMasks : BitVec wordSize × BitVec wordSize × BitVec wordSize /-- Initialization multiplier (`f`). -/ initMult : BitVec wordSize /-- Default initialization seed value. -/ initSeed : BitVec wordSize private abbrev Config.uMask (cfg : Config) : BitVec cfg.wordSize := BitVec.allOnes cfg.wordSize <<< cfg.maskBits.val private abbrev Config.lMask (cfg : Config) : BitVec cfg.wordSize := BitVec.allOnes cfg.wordSize >>> (cfg.wordSize - cfg.maskBits.val) @[simp] theorem Config.zero_lt_wordSize (cfg : Config) : 0 < cfg.wordSize := Nat.zero_lt_of_lt cfg.maskBits.is_lt @[simp] theorem Config.zero_lt_stateSize (cfg : Config) : 0 < cfg.stateSize := Nat.zero_lt_of_lt cfg.shiftSize.is_lt /-- Mersenne Twister State. -/ structure State (cfg : Config) where /-- Data for current state. -/ data : Vector (BitVec cfg.wordSize) cfg.stateSize /-- Current data index. -/ index : Fin cfg.stateSize /-- Mersenne Twister initialization given an optional seed. -/ @[specialize cfg] protected def Config.init (cfg : MersenneTwister.Config) (seed : BitVec cfg.wordSize := cfg.initSeed) : State cfg := ⟨loop seed (.mkEmpty cfg.stateSize) (Nat.zero_le _), 0, cfg.zero_lt_stateSize⟩ where /-- Inner loop for Mersenne Twister initalization. -/ loop (w : BitVec cfg.wordSize) (v : Array (BitVec cfg.wordSize)) (h : v.size ≤ cfg.stateSize) := if heq : v.size = cfg.stateSize then ⟨v, heq⟩ else let v := v.push w let w := cfg.initMult * (w ^^^ (w >>> cfg.wordSize - 2)) + v.size loop w v (by simp only [v, Array.size_push]; omega) /-- Apply the twisting transformation to the given state. -/ @[specialize cfg] protected def State.twist (state : State cfg) : State cfg := let i := state.index let i' : Fin cfg.stateSize := if h : i.val+1 < cfg.stateSize then ⟨i.val+1, h⟩ else ⟨0, cfg.zero_lt_stateSize⟩ let y := state.data[i] &&& cfg.uMask ||| state.data[i'] &&& cfg.lMask let x := state.data[i+cfg.shiftSize] ^^^ bif y[0] then y >>> 1 ^^^ cfg.xorMask else y >>> 1 ⟨state.data.set i x, i'⟩ /-- Update the state by a number of generation steps (default 1). -/ -- TODO: optimize to `O(log(steps))` using the minimal polynomial protected def State.update (state : State cfg) : (steps : Nat := 1) → State cfg | 0 => state | steps+1 => state.twist.update steps /-- Mersenne Twister iteration. -/ @[specialize cfg] protected def State.next (state : State cfg) : BitVec cfg.wordSize × State cfg := let i := state.index let s := state.twist (temper s.data[i], s) where /-- Tempering step for Mersenne Twister. -/ @[inline] temper (x : BitVec cfg.wordSize) := match cfg.temperingShifts, cfg.temperingMasks with | (u, s, t, l), (d, b, c) => let x := x ^^^ x >>> u &&& d let x := x ^^^ x <<< s &&& b let x := x ^^^ x <<< t &&& c x ^^^ x >>> l instance (cfg) : Std.Stream (State cfg) (BitVec cfg.wordSize) where next? s := s.next /-- 32 bit Mersenne Twister (MT19937) configuration. -/ def mt19937 : Config where wordSize := 32 stateSize := 624 shiftSize := 397 maskBits := 31 xorMask := 0x9908b0df temperingShifts := (11, 7, 15, 18) temperingMasks := (0xffffffff, 0x9d2c5680, 0xefc60000) initMult := 1812433253 initSeed := 4357 /-- 64 bit Mersenne Twister (MT19937-64) configuration. -/ def mt19937_64 : Config where wordSize := 64 stateSize := 312 shiftSize := 156 maskBits := 31 xorMask := 0xb5026f5aa96619e9 temperingShifts := (29, 17, 37, 43) temperingMasks := (0x5555555555555555, 0x71d67fffeda60000, 0xfff7eee000000000) initMult := 6364136223846793005 initSeed := 19650218
.lake/packages/batteries/Batteries/Data/Range/Lemmas.lean
module public import Batteries.Tactic.SeqFocus public import Batteries.Tactic.Alias @[expose] public section namespace Std.Range theorem size_stop_le_start : ∀ r : Range, r.stop ≤ r.start → r.size = 0 | ⟨start, stop, step, _⟩, h => by simp_all [size] omega theorem size_step_1 (start stop) : size ⟨start, stop, 1, by decide⟩ = stop - start := by simp [size]
.lake/packages/batteries/Batteries/Data/Vector/Lemmas.lean
module @[expose] public section namespace Vector theorem toArray_injective : ∀ {v w : Vector α n}, v.toArray = w.toArray → v = w | {..}, {..}, rfl => rfl /-! ### mk lemmas -/ @[simp] theorem get_mk (a : Array α) (h : a.size = n) (i) : (Vector.mk a h).get i = a[i] := rfl @[simp] theorem getD_mk (a : Array α) (h : a.size = n) (i x) : (Vector.mk a h).getD i x = a.getD i x := rfl @[simp] theorem uget_mk (a : Array α) (h : a.size = n) (i) (hi : i.toNat < n) : (Vector.mk a h).uget i hi = a.uget i (by simp [h, hi]) := rfl /-! ### tail lemmas -/ theorem tail_eq_of_zero {v : Vector α 0} : v.tail = #v[] := Vector.eq_empty theorem tail_eq_of_ne_zero [NeZero n] {v : Vector α n} : v.tail = v.eraseIdx 0 n.pos_of_neZero := by simp only [tail_eq_cast_extract] ext simp only [getElem_cast, getElem_extract, getElem_eraseIdx, Nat.not_lt_zero, ↓reduceDIte] congr 1 omega -- This is not a `@[simp]` lemma because the LHS simplifies to `Vector.extract`. theorem toList_tail {v : Vector α n} : v.tail.toList = v.toList.tail := match n with | 0 => by simp [Vector.eq_empty] | _ + 1 => by apply List.ext_getElem · simp · intro i h₁ h₂ simp only [Nat.add_one_sub_one, tail_eq_cast_extract, getElem_toList, getElem_cast, getElem_extract, List.getElem_tail] congr 1 omega /-! ### getElem lemmas -/ theorem getElem_tail {v : Vector α n} {i : Nat} (hi : i < n - 1) : v.tail[i] = v[i + 1] := match n with | _ + 1 => getElem_congr_coll tail_eq_of_ne_zero |>.trans <| getElem_eraseIdx (Nat.zero_lt_succ _) hi /-! ### get lemmas -/ theorem get_eq_getElem (v : Vector α n) (i : Fin n) : v.get i = v[(i : Nat)] := rfl @[simp] theorem get_push_last (v : Vector α n) (a : α) : (v.push a).get (Fin.last n) = a := getElem_push_last @[simp] theorem get_push_castSucc (v : Vector α n) (a : α) (i : Fin n) : (v.push a).get (Fin.castSucc i) = v.get i := getElem_push_lt _ @[simp] theorem get_map (v : Vector α n) (f : α → β) (i : Fin n) : (v.map f).get i = f (v.get i) := getElem_map _ _ @[simp] theorem get_reverse (v : Vector α n) (i : Fin n) : v.reverse.get i = v.get (i.rev) := getElem_reverse _ |>.trans <| congrArg v.get <| Fin.ext <| by simp; omega @[simp] theorem get_replicate (n : Nat) (a : α) (i : Fin n) : (replicate n a).get i = a := getElem_replicate _ @[simp] theorem get_range (n : Nat) (i : Fin n) : (range n).get i = i := getElem_range _ @[simp] theorem get_ofFn (f : Fin n → α) (i : Fin n) : (ofFn f).get i = f i := getElem_ofFn _ @[simp] theorem get_cast (v : Vector α m) (h : m = n) (i : Fin n) : (v.cast h).get i = v.get (i.cast h.symm) := getElem_cast _ -- This is not a `@[simp]` lemma because the LHS simplifies to `Vector.extract`. theorem get_tail (v : Vector α (n + 1)) (i : Fin n) : v.tail.get i = v.get i.succ := getElem_tail _ /-! ### finIdxOf? lemmas -/ @[simp] theorem finIdxOf?_empty [BEq α] (v : Vector α 0) : v.finIdxOf? a = none := by simp [v.eq_empty] @[simp] theorem finIdxOf?_eq_none_iff [BEq α] [LawfulBEq α] {v : Vector α n} {a : α} : v.finIdxOf? a = none ↔ a ∉ v := by obtain ⟨xs, rfl⟩ := v simp @[simp] theorem finIdxOf?_eq_some_iff [BEq α] [LawfulBEq α] {v : Vector α n} {a : α} {i : Fin n} : v.finIdxOf? a = some i ↔ v.get i = a ∧ ∀ j < i, ¬v.get j = a := by obtain ⟨xs, rfl⟩ := v simp @[simp] theorem isSome_finIdxOf? [BEq α] [PartialEquivBEq α] {v : Vector α n} {a : α} : (v.finIdxOf? a).isSome = v.contains a := by obtain ⟨v, rfl⟩ := v simp @[simp] theorem isNone_finIdxOf? [BEq α] [PartialEquivBEq α] {v : Vector α n} {a : α} : (v.finIdxOf? a).isNone = !v.contains a := by obtain ⟨v, rfl⟩ := v simp
.lake/packages/batteries/Batteries/Data/Vector/Monadic.lean
module public import Batteries.Classes.SatisfiesM public import Batteries.Data.Array.Monadic @[expose] public section namespace Vector theorem mapM_mk [Monad m] [LawfulMonad m] [MonadSatisfying m] (a : Array α) (h : a.size = n) (f : α → m β) : (Vector.mk a h).mapM f = (fun ⟨a, h'⟩ => Vector.mk a (h'.trans h)) <$> satisfying (Array.size_mapM f a) := by rw [← _root_.map_inj_right Vector.toArray_inj.mp] simp only [Functor.map_map, MonadSatisfying.val_eq, toArray_mapM] theorem mapIdxM_mk [Monad m] [LawfulMonad m] [MonadSatisfying m] (a : Array α) (h : a.size = n) (f : Nat → α → m β) : (Vector.mk a h).mapIdxM f = (fun ⟨a, h'⟩ => Vector.mk a (h'.trans h)) <$> satisfying (Array.size_mapIdxM a f) := by rw [← _root_.map_inj_right Vector.toArray_inj.mp] simp only [Functor.map_map, MonadSatisfying.val_eq, toArray_mapIdxM] theorem mapFinIdxM_mk [Monad m] [LawfulMonad m] [MonadSatisfying m] (a : Array α) (h : a.size = n) (f : (i : Nat) → α → (h : i < n) → m β) : (Vector.mk a h).mapFinIdxM f = (fun ⟨a, h'⟩ => Vector.mk a (h'.trans h)) <$> satisfying (Array.size_mapFinIdxM a (fun i a h' => f i a (h ▸ h'))) := by rw [← _root_.map_inj_right Vector.toArray_inj.mp] simp only [Functor.map_map, MonadSatisfying.val_eq, toArray_mapFinIdxM]
.lake/packages/batteries/Batteries/Data/Vector/Basic.lean
module @[expose] public section /-! # Vectors `Vector α n` is a thin wrapper around `Array α` for arrays of fixed size `n`. -/ namespace Vector /-- Returns `true` when all elements of the vector are pairwise distinct using `==` for comparison. -/ @[inline] def allDiff [BEq α] (as : Vector α n) : Bool := as.toArray.allDiff
.lake/packages/batteries/Batteries/Data/RBMap/Depth.lean
module public import Batteries.Data.RBMap.WF @[expose] public section /-! # RBNode depth bounds -/ namespace Batteries.RBNode open RBColor /-- `O(n)`. `depth t` is the maximum number of nodes on any path to a leaf. It is an upper bound on most tree operations. -/ def depth : RBNode α → Nat | nil => 0 | node _ a _ b => max a.depth b.depth + 1 theorem size_lt_depth : ∀ t : RBNode α, t.size < 2 ^ t.depth | .nil => (by decide : 0 < 1) | .node _ a _ b => by rw [size, depth, Nat.add_right_comm, Nat.pow_succ, Nat.mul_two] refine Nat.add_le_add (Nat.lt_of_lt_of_le a.size_lt_depth ?_) (Nat.lt_of_lt_of_le b.size_lt_depth ?_) · exact Nat.pow_le_pow_right (by decide) (Nat.le_max_left ..) · exact Nat.pow_le_pow_right (by decide) (Nat.le_max_right ..) /-- `depthLB c n` is the best upper bound on the depth of any balanced red-black tree with root colored `c` and black-height `n`. -/ def depthLB : RBColor → Nat → Nat | red, n => n + 1 | black, n => n theorem depthLB_le : ∀ c n, n ≤ depthLB c n | red, _ => Nat.le_succ _ | black, _ => Nat.le_refl _ /-- `depthUB c n` is the best upper bound on the depth of any balanced red-black tree with root colored `c` and black-height `n`. -/ def depthUB : RBColor → Nat → Nat | red, n => 2 * n + 1 | black, n => 2 * n theorem depthUB_le : ∀ c n, depthUB c n ≤ 2 * n + 1 | red, _ => Nat.le_refl _ | black, _ => Nat.le_succ _ theorem depthUB_le_two_depthLB : ∀ c n, depthUB c n ≤ 2 * depthLB c n | red, _ => Nat.le_succ _ | black, _ => Nat.le_refl _ theorem Balanced.depth_le : @Balanced α t c n → t.depth ≤ depthUB c n | .nil => Nat.le_refl _ | .red hl hr => Nat.succ_le_succ <| Nat.max_le.2 ⟨hl.depth_le, hr.depth_le⟩ | .black hl hr => Nat.succ_le_succ <| Nat.max_le.2 ⟨Nat.le_trans hl.depth_le (depthUB_le ..), Nat.le_trans hr.depth_le (depthUB_le ..)⟩ theorem Balanced.le_size : @Balanced α t c n → 2 ^ depthLB c n ≤ t.size + 1 | .nil => Nat.le_refl _ | .red hl hr => by rw [size, Nat.add_right_comm (size _), Nat.add_assoc, depthLB, Nat.pow_succ, Nat.mul_two] exact Nat.add_le_add hl.le_size hr.le_size | .black hl hr => by rw [size, Nat.add_right_comm (size _), Nat.add_assoc, depthLB, Nat.pow_succ, Nat.mul_two] refine Nat.add_le_add (Nat.le_trans ?_ hl.le_size) (Nat.le_trans ?_ hr.le_size) <;> exact Nat.pow_le_pow_right (by decide) (depthLB_le ..) theorem Balanced.depth_bound (h : @Balanced α t c n) : t.depth ≤ 2 * (t.size + 1).log2 := Nat.le_trans h.depth_le <| Nat.le_trans (depthUB_le_two_depthLB ..) <| Nat.mul_le_mul_left _ <| (Nat.le_log2 (Nat.succ_ne_zero _)).2 h.le_size /-- A well formed tree has `t.depth ∈ O(log t.size)`, that is, it is well balanced. This justifies the `O(log n)` bounds on most searching operations of `RBSet`. -/ theorem WF.depth_bound {t : RBNode α} (h : t.WF cmp) : t.depth ≤ 2 * (t.size + 1).log2 := let ⟨_, _, h⟩ := h.out.2; h.depth_bound
.lake/packages/batteries/Batteries/Data/RBMap/Lemmas.lean
module public import Batteries.Tactic.Basic public import Batteries.Data.RBMap.Alter public import Batteries.Data.List.Lemmas @[expose] public section /-! # Additional lemmas for Red-black trees -/ namespace Batteries namespace RBNode open RBColor attribute [simp] fold foldl foldr Any forM foldlM Ordered @[simp] theorem min?_reverse (t : RBNode α) : t.reverse.min? = t.max? := by unfold RBNode.max?; split <;> simp [RBNode.min?] unfold RBNode.min?; rw [min?.match_1.eq_3] · apply min?_reverse · simpa [reverse_eq_iff] @[simp] theorem max?_reverse (t : RBNode α) : t.reverse.max? = t.min? := by rw [← min?_reverse, reverse_reverse] @[simp] theorem mem_nil {x} : ¬x ∈ (.nil : RBNode α) := by simp [Membership.mem, EMem] @[simp] theorem mem_node {y c a x b} : y ∈ (.node c a x b : RBNode α) ↔ y = x ∨ y ∈ a ∨ y ∈ b := by simp [Membership.mem, EMem] theorem All_def {t : RBNode α} : t.All p ↔ ∀ x ∈ t, p x := by induction t <;> simp [or_imp, forall_and, *] theorem Any_def {t : RBNode α} : t.Any p ↔ ∃ x ∈ t, p x := by induction t <;> simp [or_and_right, exists_or, *] theorem memP_def : MemP cut t ↔ ∃ x ∈ t, cut x = .eq := Any_def theorem mem_def : Mem cmp x t ↔ ∃ y ∈ t, cmp x y = .eq := Any_def theorem mem_congr [Std.TransCmp (α := α) cmp] {t : RBNode α} (h : cmp x y = .eq) : Mem cmp x t ↔ Mem cmp y t := by rw [Mem, Mem, iff_iff_eq]; congr 1; funext; rw [Std.TransCmp.congr_left h] theorem isOrdered_iff' [Std.TransCmp (α := α) cmp] {t : RBNode α} : isOrdered cmp t L R ↔ (∀ a ∈ L, t.All (cmpLT cmp a ·)) ∧ (∀ a ∈ R, t.All (cmpLT cmp · a)) ∧ (∀ a ∈ L, ∀ b ∈ R, cmpLT cmp a b) ∧ Ordered cmp t := by induction t generalizing L R with | nil => simp [isOrdered]; split <;> simp [cmpLT_iff] next h => intro _ ha _ hb; cases h _ _ ha hb | node _ l v r => simp [isOrdered, *] exact ⟨ fun ⟨⟨Ll, lv, Lv, ol⟩, ⟨vr, rR, vR, or⟩⟩ => ⟨ fun _ h => ⟨Lv _ h, Ll _ h, (Lv _ h).trans_l vr⟩, fun _ h => ⟨vR _ h, (vR _ h).trans_r lv, rR _ h⟩, fun _ hL _ hR => (Lv _ hL).trans (vR _ hR), lv, vr, ol, or⟩, fun ⟨hL, hR, _, lv, vr, ol, or⟩ => ⟨ ⟨fun _ h => (hL _ h).2.1, lv, fun _ h => (hL _ h).1, ol⟩, ⟨vr, fun _ h => (hR _ h).2.2, fun _ h => (hR _ h).1, or⟩⟩⟩ theorem isOrdered_iff [Std.TransCmp (α := α) cmp] {t : RBNode α} : isOrdered cmp t ↔ Ordered cmp t := by simp [isOrdered_iff'] instance (cmp) [Std.TransCmp (α := α) cmp] (t) : Decidable (Ordered cmp t) := decidable_of_iff _ isOrdered_iff /-- A cut is like a homomorphism of orderings: it is a monotonic predicate with respect to `cmp`, but it can make things that are distinguished by `cmp` equal. This is sufficient for `find?` to locate an element on which `cut` returns `.eq`, but there may be other elements, not returned by `find?`, on which `cut` also returns `.eq`. -/ class IsCut (cmp : α → α → Ordering) (cut : α → Ordering) : Prop where /-- The set `{x | cut x = .lt}` is downward-closed. -/ le_lt_trans [Std.TransCmp cmp] : cmp x y ≠ .gt → cut x = .lt → cut y = .lt /-- The set `{x | cut x = .gt}` is upward-closed. -/ le_gt_trans [Std.TransCmp cmp] : cmp x y ≠ .gt → cut y = .gt → cut x = .gt theorem IsCut.lt_trans [IsCut cmp cut] [Std.TransCmp cmp] (H : cmp x y = .lt) : cut x = .lt → cut y = .lt := IsCut.le_lt_trans <| Std.OrientedCmp.not_gt_of_gt <| Std.OrientedCmp.gt_iff_lt.2 H theorem IsCut.gt_trans [IsCut cmp cut] [Std.TransCmp cmp] (H : cmp x y = .lt) : cut y = .gt → cut x = .gt := IsCut.le_gt_trans <| Std.OrientedCmp.not_gt_of_gt <| Std.OrientedCmp.gt_iff_lt.2 H theorem IsCut.congr [IsCut cmp cut] [Std.TransCmp cmp] (H : cmp x y = .eq) : cut x = cut y := by cases ey : cut y · exact IsCut.le_lt_trans (fun h => nomatch H.symm.trans <| Std.OrientedCmp.gt_iff_lt.1 h) ey · cases ex : cut x · exact IsCut.le_lt_trans (fun h => nomatch H.symm.trans h) ex |>.symm.trans ey · rfl · refine IsCut.le_gt_trans (cmp := cmp) (fun h => ?_) ex |>.symm.trans ey cases H.symm.trans <| Std.OrientedCmp.gt_iff_lt.1 h · exact IsCut.le_gt_trans (fun h => nomatch H.symm.trans h) ey instance (cmp cut) [@IsCut α cmp cut] : IsCut (flip cmp) (cut · |>.swap) where le_lt_trans h₁ h₂ := by have : Std.TransCmp cmp := inferInstanceAs (Std.TransCmp (flip (flip cmp))) rw [IsCut.le_gt_trans (cmp := cmp) h₁ (Ordering.swap_inj.1 h₂)]; rfl le_gt_trans h₁ h₂ := by have : Std.TransCmp cmp := inferInstanceAs (Std.TransCmp (flip (flip cmp))) rw [IsCut.le_lt_trans (cmp := cmp) h₁ (Ordering.swap_inj.1 h₂)]; rfl /-- `IsStrictCut` upgrades the `IsCut` property to ensure that at most one element of the tree can match the cut, and hence `find?` will return the unique such element if one exists. -/ class IsStrictCut (cmp : α → α → Ordering) (cut : α → Ordering) : Prop extends IsCut cmp cut where /-- If `cut = x`, then `cut` and `x` have compare the same with respect to other elements. -/ exact [Std.TransCmp cmp] : cut x = .eq → cmp x y = cut y /-- A "representable cut" is one generated by `cmp a` for some `a`. This is always a valid cut. -/ instance (cmp) (a : α) : IsStrictCut cmp (cmp a) where le_lt_trans h₁ h₂ := Std.TransCmp.lt_of_lt_of_le h₂ h₁ le_gt_trans h₁ := Decidable.not_imp_not.1 (Std.TransCmp.le_trans · h₁) exact h := (Std.TransCmp.congr_left h).symm instance (cmp cut) [@IsStrictCut α cmp cut] : IsStrictCut (flip cmp) (cut · |>.swap) where exact h := by have : Std.TransCmp cmp := inferInstanceAs (Std.TransCmp (flip (flip cmp))) rw [← IsStrictCut.exact (cmp := cmp) (Ordering.swap_inj.1 h), ← Std.OrientedCmp.eq_swap]; rfl section fold theorem foldr_cons (t : RBNode α) (l) : t.foldr (·::·) l = t.toList ++ l := by unfold toList induction t generalizing l with | nil => rfl | node _ a _ b iha ihb => rw [foldr, foldr, iha, iha (_::_), ihb]; simp @[simp] theorem toList_nil : (.nil : RBNode α).toList = [] := rfl @[simp] theorem toList_node : (.node c a x b : RBNode α).toList = a.toList ++ x :: b.toList := by rw [toList, foldr, foldr_cons]; rfl @[simp] theorem toList_reverse (t : RBNode α) : t.reverse.toList = t.toList.reverse := by induction t <;> simp [*] @[simp] theorem mem_toList {t : RBNode α} : x ∈ t.toList ↔ x ∈ t := by induction t <;> simp [*, or_left_comm] @[simp] theorem mem_reverse {t : RBNode α} : a ∈ t.reverse ↔ a ∈ t := by rw [← mem_toList]; simp theorem min?_eq_toList_head? {t : RBNode α} : t.min? = t.toList.head? := by induction t with | nil => rfl | node _ l _ _ ih => cases l <;> simp [RBNode.min?, ih] theorem max?_eq_toList_getLast? {t : RBNode α} : t.max? = t.toList.getLast? := by rw [← min?_reverse, min?_eq_toList_head?]; simp theorem foldr_eq_foldr_toList {t : RBNode α} : t.foldr f init = t.toList.foldr f init := by induction t generalizing init <;> simp [*] theorem foldl_eq_foldl_toList {t : RBNode α} : t.foldl f init = t.toList.foldl f init := by induction t generalizing init <;> simp [*] theorem foldl_reverse {α β : Type _} {t : RBNode α} {f : β → α → β} {init : β} : t.reverse.foldl f init = t.foldr (flip f) init := by simp (config := {unfoldPartialApp := true}) [foldr_eq_foldr_toList, foldl_eq_foldl_toList, flip] theorem foldr_reverse {α β : Type _} {t : RBNode α} {f : α → β → β} {init : β} : t.reverse.foldr f init = t.foldl (flip f) init := foldl_reverse.symm.trans (by simp; rfl) theorem forM_eq_forM_toList [Monad m] [LawfulMonad m] {t : RBNode α} : t.forM (m := m) f = t.toList.forM f := by induction t <;> simp [*] theorem foldlM_eq_foldlM_toList [Monad m] [LawfulMonad m] {t : RBNode α} : t.foldlM (m := m) f init = t.toList.foldlM f init := by induction t generalizing init <;> simp [*] theorem forIn_visit_eq_bindList [Monad m] [LawfulMonad m] {t : RBNode α} : forIn.visit (m := m) f t init = (ForInStep.yield init).bindList f t.toList := by induction t generalizing init <;> simp [*, forIn.visit] theorem forIn_eq_forIn_toList [Monad m] [LawfulMonad m] {t : RBNode α} : forIn (m := m) t init f = forIn t.toList init f := by conv => lhs; simp only [forIn, RBNode.forIn] rw [List.forIn_eq_bindList, forIn_visit_eq_bindList] end fold namespace Stream attribute [simp] foldl foldr theorem foldr_cons (t : RBNode.Stream α) (l) : t.foldr (·::·) l = t.toList ++ l := by unfold toList; apply Eq.symm; induction t <;> simp [*, foldr, RBNode.foldr_cons] @[simp] theorem toList_nil : (.nil : RBNode.Stream α).toList = [] := rfl @[simp] theorem toList_cons : (.cons x r s : RBNode.Stream α).toList = x :: r.toList ++ s.toList := by rw [toList, toList, foldr, RBNode.foldr_cons]; rfl theorem foldr_eq_foldr_toList {s : RBNode.Stream α} : s.foldr f init = s.toList.foldr f init := by induction s <;> simp [*, RBNode.foldr_eq_foldr_toList] theorem foldl_eq_foldl_toList {t : RBNode.Stream α} : t.foldl f init = t.toList.foldl f init := by induction t generalizing init <;> simp [*, RBNode.foldl_eq_foldl_toList] theorem forIn_eq_forIn_toList [Monad m] [LawfulMonad m] {t : RBNode α} : forIn (m := m) t init f = forIn t.toList init f := by conv => lhs; simp only [forIn, RBNode.forIn] rw [List.forIn_eq_bindList, forIn_visit_eq_bindList] end Stream theorem toStream_toList' {t : RBNode α} {s} : (t.toStream s).toList = t.toList ++ s.toList := by induction t generalizing s <;> simp [*, toStream] @[simp] theorem toStream_toList {t : RBNode α} : t.toStream.toList = t.toList := by simp [toStream_toList'] theorem Stream.next?_toList {s : RBNode.Stream α} : (s.next?.map fun (a, b) => (a, b.toList)) = s.toList.next? := by cases s <;> simp [next?, toStream_toList'] theorem ordered_iff {t : RBNode α} : t.Ordered cmp ↔ t.toList.Pairwise (cmpLT cmp) := by induction t with | nil => simp | node c l v r ihl ihr => simp [*, List.pairwise_append, Ordered, All_def, and_assoc, and_left_comm, and_comm, imp_and, forall_and] exact fun _ _ hl hr a ha b hb => (hl _ ha).trans (hr _ hb) theorem Ordered.toList_sorted {t : RBNode α} : t.Ordered cmp → t.toList.Pairwise (cmpLT cmp) := ordered_iff.1 theorem min?_mem {t : RBNode α} (h : t.min? = some a) : a ∈ t := by rw [min?_eq_toList_head?] at h rw [← mem_toList] revert h; cases toList t <;> rintro ⟨⟩; constructor theorem Ordered.min?_le {t : RBNode α} [Std.TransCmp cmp] (ht : t.Ordered cmp) (h : t.min? = some a) (x) (hx : x ∈ t) : cmp a x ≠ .gt := by rw [min?_eq_toList_head?] at h rw [← mem_toList] at hx have := ht.toList_sorted revert h hx this; cases toList t <;> rintro ⟨⟩ (_ | ⟨_, hx⟩) (_ | ⟨h1,h2⟩) · rw [Std.ReflCmp.compare_self (cmp := cmp)]; decide · rw [(h1 _ hx).1]; decide theorem max?_mem {t : RBNode α} (h : t.max? = some a) : a ∈ t := by simpa using min?_mem ((min?_reverse _).trans h) theorem Ordered.le_max? {t : RBNode α} [Std.TransCmp cmp] (ht : t.Ordered cmp) (h : t.max? = some a) (x) (hx : x ∈ t) : cmp x a ≠ .gt := ht.reverse.min?_le ((min?_reverse _).trans h) _ (by simpa using hx) @[simp] theorem setBlack_toList {t : RBNode α} : t.setBlack.toList = t.toList := by cases t <;> simp [setBlack] @[simp] theorem setRed_toList {t : RBNode α} : t.setRed.toList = t.toList := by cases t <;> simp [setRed] @[simp] theorem balance1_toList {l : RBNode α} {v r} : (l.balance1 v r).toList = l.toList ++ v :: r.toList := by unfold balance1; split <;> simp @[simp] theorem balance2_toList {l : RBNode α} {v r} : (l.balance2 v r).toList = l.toList ++ v :: r.toList := by unfold balance2; split <;> simp @[simp] theorem balLeft_toList {l : RBNode α} {v r} : (l.balLeft v r).toList = l.toList ++ v :: r.toList := by unfold balLeft; split <;> (try simp); split <;> simp @[simp] theorem balRight_toList {l : RBNode α} {v r} : (l.balRight v r).toList = l.toList ++ v :: r.toList := by unfold balRight; split <;> (try simp); split <;> simp theorem size_eq {t : RBNode α} : t.size = t.toList.length := by induction t <;> simp [*, size]; rfl @[simp] theorem reverse_size (t : RBNode α) : t.reverse.size = t.size := by simp [size_eq] @[simp] theorem Any_reverse {t : RBNode α} : t.reverse.Any p ↔ t.Any p := by simp [Any_def] @[simp] theorem memP_reverse {t : RBNode α} : MemP cut t.reverse ↔ MemP (cut · |>.swap) t := by simp [MemP] theorem Mem_reverse [Std.OrientedCmp (α := α) cmp] {t : RBNode α} : Mem cmp x t.reverse ↔ Mem (flip cmp) x t := by simp [Mem]; apply Iff.of_eq; congr; funext x; rw [← Std.OrientedCmp.eq_swap]; rfl section find? theorem find?_some_eq_eq {t : RBNode α} : x ∈ t.find? cut → cut x = .eq := by induction t <;> simp [find?]; split <;> try assumption intro | rfl => assumption theorem find?_some_mem {t : RBNode α} : x ∈ t.find? cut → x ∈ t := by induction t <;> simp [find?]; split <;> simp (config := {contextual := true}) [*] theorem find?_some_memP {t : RBNode α} (h : x ∈ t.find? cut) : MemP cut t := memP_def.2 ⟨_, find?_some_mem h, find?_some_eq_eq h⟩ theorem Ordered.memP_iff_find? [Std.TransCmp (α := α) cmp] [IsCut cmp cut] (ht : Ordered cmp t) : MemP cut t ↔ ∃ x, t.find? cut = some x := by refine ⟨fun H => ?_, fun ⟨x, h⟩ => find?_some_memP h⟩ induction t with simp [find?] at H ⊢ | nil => cases H | node _ l _ r ihl ihr => let ⟨lx, xr, hl, hr⟩ := ht split · next ev => refine ihl hl ?_ rcases H with ev' | hx | hx · cases ev.symm.trans ev' · exact hx · have ⟨z, hz, ez⟩ := Any_def.1 hx cases ez.symm.trans <| IsCut.lt_trans (All_def.1 xr _ hz).1 ev · next ev => refine ihr hr ?_ rcases H with ev' | hx | hx · cases ev.symm.trans ev' · have ⟨z, hz, ez⟩ := Any_def.1 hx cases ez.symm.trans <| IsCut.gt_trans (All_def.1 lx _ hz).1 ev · exact hx · exact ⟨_, rfl⟩ theorem Ordered.unique [Std.TransCmp (α := α) cmp] (ht : Ordered cmp t) (hx : x ∈ t) (hy : y ∈ t) (e : cmp x y = .eq) : x = y := by induction t with | nil => cases hx | node _ l _ r ihl ihr => let ⟨lx, xr, hl, hr⟩ := ht rcases hx, hy with ⟨rfl | hx | hx, rfl | hy | hy⟩ · rfl · cases e.symm.trans <| Std.OrientedCmp.gt_iff_lt.2 (All_def.1 lx _ hy).1 · cases e.symm.trans (All_def.1 xr _ hy).1 · cases e.symm.trans (All_def.1 lx _ hx).1 · exact ihl hl hx hy · cases e.symm.trans ((All_def.1 lx _ hx).trans (All_def.1 xr _ hy)).1 · cases e.symm.trans <| Std.OrientedCmp.gt_iff_lt.2 (All_def.1 xr _ hx).1 · cases e.symm.trans <| Std.OrientedCmp.gt_iff_lt.2 ((All_def.1 lx _ hy).trans (All_def.1 xr _ hx)).1 · exact ihr hr hx hy theorem Ordered.find?_some [Std.TransCmp (α := α) cmp] [IsStrictCut cmp cut] (ht : Ordered cmp t) : t.find? cut = some x ↔ x ∈ t ∧ cut x = .eq := by refine ⟨fun h => ⟨find?_some_mem h, find?_some_eq_eq h⟩, fun ⟨hx, e⟩ => ?_⟩ have ⟨y, hy⟩ := ht.memP_iff_find?.1 (memP_def.2 ⟨_, hx, e⟩) exact ht.unique hx (find?_some_mem hy) ((IsStrictCut.exact e).trans (find?_some_eq_eq hy)) ▸ hy @[simp] theorem find?_reverse (t : RBNode α) (cut : α → Ordering) : t.reverse.find? cut = t.find? (cut · |>.swap) := by induction t <;> simp [*, find?] cases cut _ <;> simp [Ordering.swap] /-- Auxiliary definition for `zoom_ins`: set the root of the tree to `v`, creating a node if necessary. -/ def setRoot (v : α) : RBNode α → RBNode α | nil => node red nil v nil | node c a _ b => node c a v b /-- Auxiliary definition for `zoom_ins`: set the root of the tree to `v`, creating a node if necessary. -/ def delRoot : RBNode α → RBNode α | nil => nil | node _ a _ b => a.append b end find? section «upperBound? and lowerBound?» @[simp] theorem upperBound?_reverse (t : RBNode α) (cut ub) : t.reverse.upperBound? cut ub = t.lowerBound? (cut · |>.swap) ub := by induction t generalizing ub <;> simp [lowerBound?, upperBound?] split <;> simp [*, Ordering.swap] @[simp] theorem lowerBound?_reverse (t : RBNode α) (cut lb) : t.reverse.lowerBound? cut lb = t.upperBound? (cut · |>.swap) lb := by simpa using (upperBound?_reverse t.reverse (cut · |>.swap) lb).symm theorem upperBound?_eq_find? {t : RBNode α} {cut} (ub) (H : t.find? cut = some x) : t.upperBound? cut ub = some x := by induction t generalizing ub with simp [find?] at H | node c a y b iha ihb => simp [upperBound?]; split at H · apply iha _ H · apply ihb _ H · exact H theorem lowerBound?_eq_find? {t : RBNode α} {cut} (lb) (H : t.find? cut = some x) : t.lowerBound? cut lb = some x := by rw [← reverse_reverse t] at H ⊢; rw [lowerBound?_reverse]; rw [find?_reverse] at H exact upperBound?_eq_find? _ H /-- The value `x` returned by `upperBound?` is greater or equal to the `cut`. -/ theorem upperBound?_ge' {t : RBNode α} (H : ∀ {x}, x ∈ ub → cut x ≠ .gt) : t.upperBound? cut ub = some x → cut x ≠ .gt := by induction t generalizing ub with | nil => exact H | node _ _ _ _ ihl ihr => simp [upperBound?]; split · next hv => exact ihl fun | rfl, e => nomatch hv.symm.trans e · exact ihr H · next hv => intro | rfl, e => cases hv.symm.trans e /-- The value `x` returned by `upperBound?` is greater or equal to the `cut`. -/ theorem upperBound?_ge {t : RBNode α} : t.upperBound? cut = some x → cut x ≠ .gt := upperBound?_ge' nofun /-- The value `x` returned by `lowerBound?` is less or equal to the `cut`. -/ theorem lowerBound?_le' {t : RBNode α} (H : ∀ {x}, x ∈ lb → cut x ≠ .lt) : t.lowerBound? cut lb = some x → cut x ≠ .lt := by rw [← reverse_reverse t, lowerBound?_reverse, Ne, ← Ordering.swap_inj] exact upperBound?_ge' fun h => by specialize H h; rwa [Ne, ← Ordering.swap_inj] at H /-- The value `x` returned by `lowerBound?` is less or equal to the `cut`. -/ theorem lowerBound?_le {t : RBNode α} : t.lowerBound? cut = some x → cut x ≠ .lt := lowerBound?_le' nofun theorem All.upperBound?_ub {t : RBNode α} (hp : t.All p) (H : ∀ {x}, ub = some x → p x) : t.upperBound? cut ub = some x → p x := by induction t generalizing ub with | nil => exact H | node _ _ _ _ ihl ihr => simp [upperBound?]; split · exact ihl hp.2.1 fun | rfl => hp.1 · exact ihr hp.2.2 H · exact fun | rfl => hp.1 theorem All.upperBound? {t : RBNode α} (hp : t.All p) : t.upperBound? cut = some x → p x := hp.upperBound?_ub nofun theorem All.lowerBound?_lb {t : RBNode α} (hp : t.All p) (H : ∀ {x}, lb = some x → p x) : t.lowerBound? cut lb = some x → p x := by rw [← reverse_reverse t, lowerBound?_reverse] exact All.upperBound?_ub (All.reverse.2 hp) H theorem All.lowerBound? {t : RBNode α} (hp : t.All p) : t.lowerBound? cut = some x → p x := hp.lowerBound?_lb nofun theorem upperBound?_mem_ub {t : RBNode α} (h : t.upperBound? cut ub = some x) : x ∈ t ∨ ub = some x := All.upperBound?_ub (p := fun x => x ∈ t ∨ ub = some x) (All_def.2 fun _ => .inl) Or.inr h theorem upperBound?_mem {t : RBNode α} (h : t.upperBound? cut = some x) : x ∈ t := (upperBound?_mem_ub h).resolve_right nofun theorem lowerBound?_mem_lb {t : RBNode α} (h : t.lowerBound? cut lb = some x) : x ∈ t ∨ lb = some x := All.lowerBound?_lb (p := fun x => x ∈ t ∨ lb = some x) (All_def.2 fun _ => .inl) Or.inr h theorem lowerBound?_mem {t : RBNode α} (h : t.lowerBound? cut = some x) : x ∈ t := (lowerBound?_mem_lb h).resolve_right nofun theorem upperBound?_of_some {t : RBNode α} : ∃ x, t.upperBound? cut (some y) = some x := by induction t generalizing y <;> simp [upperBound?]; split <;> simp [*] theorem lowerBound?_of_some {t : RBNode α} : ∃ x, t.lowerBound? cut (some y) = some x := by rw [← reverse_reverse t, lowerBound?_reverse]; exact upperBound?_of_some theorem Ordered.upperBound?_exists [Std.TransCmp (α := α) cmp] [IsCut cmp cut] (h : Ordered cmp t) : (∃ x, t.upperBound? cut = some x) ↔ ∃ x ∈ t, cut x ≠ .gt := by refine ⟨fun ⟨x, hx⟩ => ⟨_, upperBound?_mem hx, upperBound?_ge hx⟩, fun H => ?_⟩ obtain ⟨x, hx, e⟩ := H induction t generalizing x with | nil => cases hx | node _ _ _ _ _ ihr => simp [upperBound?]; split · exact upperBound?_of_some · rcases hx with rfl | hx | hx · contradiction · next hv => cases e <| IsCut.gt_trans (All_def.1 h.1 _ hx).1 hv · exact ihr h.2.2.2 _ hx e · exact ⟨_, rfl⟩ theorem Ordered.lowerBound?_exists [Std.TransCmp (α := α) cmp] [IsCut cmp cut] (h : Ordered cmp t) : (∃ x, t.lowerBound? cut = some x) ↔ ∃ x ∈ t, cut x ≠ .lt := by conv => enter [2, 1, x]; rw [Ne, ← Ordering.swap_inj] rw [← reverse_reverse t, lowerBound?_reverse] simpa [-Ordering.swap_inj] using h.reverse.upperBound?_exists (cut := (cut · |>.swap)) theorem Ordered.upperBound?_least_ub [Std.TransCmp (α := α) cmp] [IsCut cmp cut] (h : Ordered cmp t) (hub : ∀ {x}, ub = some x → t.All (cmpLT cmp · x)) : t.upperBound? cut ub = some x → y ∈ t → cut x = .lt → cmp y x = .lt → cut y = .gt := by induction t generalizing ub with | nil => nofun | node _ _ _ _ ihl ihr => simp [upperBound?]; split <;> rename_i hv <;> rintro h₁ (rfl | hy' | hy') hx h₂ · rcases upperBound?_mem_ub h₁ with h₁ | ⟨⟨⟩⟩ · cases Std.OrientedCmp.not_lt_of_lt h₂ (All_def.1 h.1 _ h₁).1 · cases Std.OrientedCmp.not_lt_of_lt h₂ h₂ · exact ihl h.2.2.1 (by rintro _ ⟨⟨⟩⟩; exact h.1) h₁ hy' hx h₂ · refine (Std.OrientedCmp.not_lt_of_lt h₂ ?_).elim; have := (All_def.1 h.2.1 _ hy').1 rcases upperBound?_mem_ub h₁ with h₁ | ⟨⟨⟩⟩ · exact Std.TransCmp.lt_trans (All_def.1 h.1 _ h₁).1 this · exact this · exact hv · exact IsCut.gt_trans (cut := cut) (cmp := cmp) (All_def.1 h.1 _ hy').1 hv · exact ihr h.2.2.2 (fun h => (hub h).2.2) h₁ hy' hx h₂ · cases h₁; cases Std.OrientedCmp.not_lt_of_lt h₂ h₂ · cases h₁; cases hx.symm.trans hv · cases h₁; cases hx.symm.trans hv theorem Ordered.lowerBound?_greatest_lb [Std.TransCmp (α := α) cmp] [IsCut cmp cut] (h : Ordered cmp t) (hlb : ∀ {x}, lb = some x → t.All (cmpLT cmp x ·)) : t.lowerBound? cut lb = some x → y ∈ t → cut x = .gt → cmp x y = .lt → cut y = .lt := by intro h1 h2 h3 h4 rw [← reverse_reverse t, lowerBound?_reverse] at h1 rw [← Ordering.swap_inj] at h3 ⊢ revert h2 h3 h4 simpa [-Ordering.swap_inj] using h.reverse.upperBound?_least_ub (fun h => All.reverse.2 <| (hlb h).imp .flip) h1 /-- A statement of the least-ness of the result of `upperBound?`. If `x` is the return value of `upperBound?` and it is strictly greater than the cut, then any other `y < x` in the tree is in fact strictly less than the cut (so there is no exact match, and nothing closer to the cut). -/ theorem Ordered.upperBound?_least [Std.TransCmp (α := α) cmp] [IsCut cmp cut] (ht : Ordered cmp t) (H : t.upperBound? cut = some x) (hy : y ∈ t) (xy : cmp y x = .lt) (hx : cut x = .lt) : cut y = .gt := ht.upperBound?_least_ub (by nofun) H hy hx xy /-- A statement of the greatest-ness of the result of `lowerBound?`. If `x` is the return value of `lowerBound?` and it is strictly less than the cut, then any other `y > x` in the tree is in fact strictly greater than the cut (so there is no exact match, and nothing closer to the cut). -/ theorem Ordered.lowerBound?_greatest [Std.TransCmp (α := α) cmp] [IsCut cmp cut] (ht : Ordered cmp t) (H : t.lowerBound? cut none = some x) (hy : y ∈ t) (xy : cmp x y = .lt) (hx : cut x = .gt) : cut y = .lt := ht.lowerBound?_greatest_lb (by nofun) H hy hx xy theorem Ordered.memP_iff_upperBound? [Std.TransCmp (α := α) cmp] [IsCut cmp cut] (ht : Ordered cmp t) : t.MemP cut ↔ ∃ x, t.upperBound? cut = some x ∧ cut x = .eq := by refine memP_def.trans ⟨fun ⟨y, hy, ey⟩ => ?_, fun ⟨x, hx, e⟩ => ⟨_, upperBound?_mem hx, e⟩⟩ have ⟨x, hx⟩ := ht.upperBound?_exists.2 ⟨_, hy, fun h => nomatch ey.symm.trans h⟩ refine ⟨x, hx, ?_⟩; cases ex : cut x · cases e : cmp x y · cases ey.symm.trans <| IsCut.lt_trans e ex · cases ey.symm.trans <| IsCut.congr e |>.symm.trans ex · cases ey.symm.trans <| ht.upperBound?_least hx hy (Std.OrientedCmp.gt_iff_lt.1 e) ex · rfl · cases upperBound?_ge hx ex theorem Ordered.memP_iff_lowerBound? [Std.TransCmp (α := α) cmp] [IsCut cmp cut] (ht : Ordered cmp t) : t.MemP cut ↔ ∃ x, t.lowerBound? cut = some x ∧ cut x = .eq := by refine memP_def.trans ⟨fun ⟨y, hy, ey⟩ => ?_, fun ⟨x, hx, e⟩ => ⟨_, lowerBound?_mem hx, e⟩⟩ have ⟨x, hx⟩ := ht.lowerBound?_exists.2 ⟨_, hy, fun h => nomatch ey.symm.trans h⟩ refine ⟨x, hx, ?_⟩; cases ex : cut x · cases lowerBound?_le hx ex · rfl · cases e : cmp x y · cases ey.symm.trans <| ht.lowerBound?_greatest hx hy e ex · cases ey.symm.trans <| IsCut.congr e |>.symm.trans ex · cases ey.symm.trans <| IsCut.gt_trans (Std.OrientedCmp.gt_iff_lt.1 e) ex /-- A stronger version of `lowerBound?_greatest` that holds when the cut is strict. -/ theorem Ordered.lowerBound?_lt [Std.TransCmp (α := α) cmp] [IsStrictCut cmp cut] (ht : Ordered cmp t) (H : t.lowerBound? cut = some x) (hy : y ∈ t) : cmp x y = .lt ↔ cut y = .lt := by refine ⟨fun h => ?_, fun h => Std.OrientedCmp.gt_iff_lt.1 ?_⟩ · cases e : cut x · cases lowerBound?_le H e · exact IsStrictCut.exact e |>.symm.trans h · exact ht.lowerBound?_greatest H hy h e · by_contra h'; exact lowerBound?_le H <| IsCut.le_lt_trans (cmp := cmp) (cut := cut) h' h /-- A stronger version of `upperBound?_least` that holds when the cut is strict. -/ theorem Ordered.lt_upperBound? [Std.TransCmp (α := α) cmp] [IsStrictCut cmp cut] (ht : Ordered cmp t) (H : t.upperBound? cut = some x) (hy : y ∈ t) : cmp y x = .lt ↔ cut y = .gt := by rw [← reverse_reverse t, upperBound?_reverse] at H rw [← Ordering.swap_inj (o₂ := .gt)] revert hy; simpa [-Ordering.swap_inj] using ht.reverse.lowerBound?_lt H end «upperBound? and lowerBound?» namespace Path attribute [simp] RootOrdered Ordered /-- The list of elements to the left of the hole. (This function is intended for specification purposes only.) -/ @[simp] def listL : Path α → List α | .root => [] | .left _ parent _ _ => parent.listL | .right _ l v parent => parent.listL ++ (l.toList ++ [v]) /-- The list of elements to the right of the hole. (This function is intended for specification purposes only.) -/ @[simp] def listR : Path α → List α | .root => [] | .left _ parent v r => v :: r.toList ++ parent.listR | .right _ _ _ parent => parent.listR /-- Wraps a list of elements with the left and right elements of the path. -/ abbrev withList (p : Path α) (l : List α) : List α := p.listL ++ l ++ p.listR theorem rootOrdered_iff {p : Path α} (hp : p.Ordered cmp) : p.RootOrdered cmp v ↔ (∀ a ∈ p.listL, cmpLT cmp a v) ∧ (∀ a ∈ p.listR, cmpLT cmp v a) := by induction p with (simp [All_def] at hp; simp [*, and_assoc, and_left_comm, and_comm, or_imp, forall_and]) | left _ _ x _ ih => exact fun vx _ _ _ ha => vx.trans (hp.2.1 _ ha) | right _ _ x _ ih => exact fun xv _ _ _ ha => (hp.2.1 _ ha).trans xv theorem ordered_iff {p : Path α} : p.Ordered cmp ↔ p.listL.Pairwise (cmpLT cmp) ∧ p.listR.Pairwise (cmpLT cmp) ∧ ∀ x ∈ p.listL, ∀ y ∈ p.listR, cmpLT cmp x y := by induction p with | root => simp | left _ _ x _ ih | right _ _ x _ ih => ?_ all_goals rw [Ordered, and_congr_right_eq fun h => by simp [All_def, rootOrdered_iff h]; rfl] simp [List.pairwise_append, or_imp, forall_and, ih, RBNode.ordered_iff] -- FIXME: simp [and_assoc, and_left_comm, and_comm] is really slow here · exact ⟨ fun ⟨⟨hL, hR, LR⟩, xr, ⟨Lx, xR⟩, ⟨rL, rR⟩, hr⟩ => ⟨hL, ⟨⟨xr, xR⟩, hr, hR, rR⟩, Lx, fun _ ha _ hb => rL _ hb _ ha, LR⟩, fun ⟨hL, ⟨⟨xr, xR⟩, hr, hR, rR⟩, Lx, Lr, LR⟩ => ⟨⟨hL, hR, LR⟩, xr, ⟨Lx, xR⟩, ⟨fun _ ha _ hb => Lr _ hb _ ha, rR⟩, hr⟩⟩ · exact ⟨ fun ⟨⟨hL, hR, LR⟩, lx, ⟨Lx, xR⟩, ⟨lL, lR⟩, hl⟩ => ⟨⟨hL, ⟨hl, lx⟩, fun _ ha _ hb => lL _ hb _ ha, Lx⟩, hR, LR, lR, xR⟩, fun ⟨⟨hL, ⟨hl, lx⟩, Ll, Lx⟩, hR, LR, lR, xR⟩ => ⟨⟨hL, hR, LR⟩, lx, ⟨Lx, xR⟩, ⟨fun _ ha _ hb => Ll _ hb _ ha, lR⟩, hl⟩⟩ theorem zoom_zoomed₁ (e : zoom cut t path = (t', path')) : t'.OnRoot (cut · = .eq) := match t, e with | nil, rfl => trivial | node .., e => by revert e; unfold zoom; split · exact zoom_zoomed₁ · exact zoom_zoomed₁ · next H => intro e; cases e; exact H @[simp] theorem fill_toList {p : Path α} : (p.fill t).toList = p.withList t.toList := by induction p generalizing t <;> simp [*] theorem _root_.Batteries.RBNode.zoom_toList {t : RBNode α} (eq : t.zoom cut = (t', p')) : p'.withList t'.toList = t.toList := by rw [← fill_toList, ← zoom_fill eq]; rfl @[simp] theorem ins_toList {p : Path α} : (p.ins t).toList = p.withList t.toList := by match p with | .root | .left red .. | .right red .. | .left black .. | .right black .. => simp [ins, ins_toList] @[simp] theorem insertNew_toList {p : Path α} : (p.insertNew v).toList = p.withList [v] := by simp [insertNew] theorem insert_toList {p : Path α} : (p.insert t v).toList = p.withList (t.setRoot v).toList := by simp [insert]; split <;> simp [setRoot] protected theorem Balanced.insert {path : Path α} (hp : path.Balanced c₀ n₀ c n) : t.Balanced c n → ∃ c n, (path.insert t v).Balanced c n | .nil => ⟨_, hp.insertNew⟩ | .red ha hb => ⟨_, _, hp.fill (.red ha hb)⟩ | .black ha hb => ⟨_, _, hp.fill (.black ha hb)⟩ theorem Ordered.insert : ∀ {path : Path α} {t : RBNode α}, path.Ordered cmp → t.Ordered cmp → t.All (path.RootOrdered cmp) → path.RootOrdered cmp v → t.OnRoot (cmpEq cmp v) → (path.insert t v).Ordered cmp | _, nil, hp, _, _, vp, _ => hp.insertNew vp | _, node .., hp, ⟨ax, xb, ha, hb⟩, ⟨_, ap, bp⟩, vp, xv => Ordered.fill.2 ⟨hp, ⟨ax.imp xv.lt_congr_right.2, xb.imp xv.lt_congr_left.2, ha, hb⟩, vp, ap, bp⟩ theorem Ordered.erase : ∀ {path : Path α} {t : RBNode α}, path.Ordered cmp → t.Ordered cmp → t.All (path.RootOrdered cmp) → (path.erase t).Ordered cmp | _, nil, hp, ht, tp => Ordered.fill.2 ⟨hp, ht, tp⟩ | _, node .., hp, ⟨ax, xb, ha, hb⟩, ⟨_, ap, bp⟩ => hp.del (ha.append ax xb hb) (ap.append bp) theorem zoom_ins {t : RBNode α} {cmp : α → α → Ordering} : t.zoom (cmp v) path = (t', path') → path.ins (t.ins cmp v) = path'.ins (t'.setRoot v) := by unfold RBNode.ins; split <;> simp [zoom] · intro | rfl, rfl => rfl all_goals · split · exact zoom_ins · exact zoom_ins · intro | rfl => rfl theorem insertNew_eq_insert (h : zoom (cmp v) t = (nil, path)) : path.insertNew v = (t.insert cmp v).setBlack := insert_setBlack .. ▸ (zoom_ins h).symm theorem ins_eq_fill {path : Path α} {t : RBNode α} : path.Balanced c₀ n₀ c n → t.Balanced c n → path.ins t = (path.fill t).setBlack | .root, h => rfl | .redL hb H, ha | .redR ha H, hb => by unfold ins; exact ins_eq_fill H (.red ha hb) | .blackL hb H, ha => by rw [ins, fill, ← ins_eq_fill H (.black ha hb), balance1_eq ha] | .blackR ha H, hb => by rw [ins, fill, ← ins_eq_fill H (.black ha hb), balance2_eq hb] theorem zoom_insert {path : Path α} {t : RBNode α} (ht : t.Balanced c n) (H : zoom (cmp v) t = (t', path)) : (path.insert t' v).setBlack = (t.insert cmp v).setBlack := by have ⟨_, _, ht', hp'⟩ := ht.zoom .root H cases ht' with simp [insert] | nil => simp [insertNew_eq_insert H, setBlack_idem] | red hl hr => rw [← ins_eq_fill hp' (.red hl hr), insert_setBlack]; exact (zoom_ins H).symm | black hl hr => rw [← ins_eq_fill hp' (.black hl hr), insert_setBlack]; exact (zoom_ins H).symm theorem zoom_del {t : RBNode α} : t.zoom cut path = (t', path') → path.del (t.del cut) (match t with | node c .. => c | _ => red) = path'.del t'.delRoot (match t' with | node c .. => c | _ => red) := by rw [RBNode.del.eq_def]; split <;> simp [zoom] · intro | rfl, rfl => rfl · next c a y b => split · have IH := @zoom_del (t := a) match a with | nil => intro | rfl => rfl | node black .. | node red .. => apply IH · have IH := @zoom_del (t := b) match b with | nil => intro | rfl => rfl | node black .. | node red .. => apply IH · intro | rfl => rfl /-- Asserts that `p` holds on all elements to the left of the hole. -/ def AllL (p : α → Prop) : Path α → Prop | .root => True | .left _ parent _ _ => parent.AllL p | .right _ a x parent => a.All p ∧ p x ∧ parent.AllL p /-- Asserts that `p` holds on all elements to the right of the hole. -/ def AllR (p : α → Prop) : Path α → Prop | .root => True | .left _ parent x b => parent.AllR p ∧ p x ∧ b.All p | .right _ _ _ parent => parent.AllR p end Path theorem insert_toList_zoom {t : RBNode α} (ht : Balanced t c n) (e : zoom (cmp v) t = (t', p)) : (t.insert cmp v).toList = p.withList (t'.setRoot v).toList := by rw [← setBlack_toList, ← Path.zoom_insert ht e, setBlack_toList, Path.insert_toList] theorem insert_toList_zoom_nil {t : RBNode α} (ht : Balanced t c n) (e : zoom (cmp v) t = (nil, p)) : (t.insert cmp v).toList = p.withList [v] := insert_toList_zoom ht e theorem exists_insert_toList_zoom_nil {t : RBNode α} (ht : Balanced t c n) (e : zoom (cmp v) t = (nil, p)) : ∃ L R, t.toList = L ++ R ∧ (t.insert cmp v).toList = L ++ v :: R := ⟨p.listL, p.listR, by simp [← zoom_toList e, insert_toList_zoom_nil ht e]⟩ theorem insert_toList_zoom_node {t : RBNode α} (ht : Balanced t c n) (e : zoom (cmp v) t = (node c' l v' r, p)) : (t.insert cmp v).toList = p.withList (node c l v r).toList := insert_toList_zoom ht e theorem exists_insert_toList_zoom_node {t : RBNode α} (ht : Balanced t c n) (e : zoom (cmp v) t = (node c' l v' r, p)) : ∃ L R, t.toList = L ++ v' :: R ∧ (t.insert cmp v).toList = L ++ v :: R := by refine ⟨p.listL ++ l.toList, r.toList ++ p.listR, ?_⟩ simp [← zoom_toList e, insert_toList_zoom_node ht e] theorem mem_insert_self {t : RBNode α} (ht : Balanced t c n) : v ∈ t.insert cmp v := by rw [← mem_toList, List.mem_iff_append] exact match e : zoom (cmp v) t with | (nil, p) => let ⟨_, _, _, h⟩ := exists_insert_toList_zoom_nil ht e; ⟨_, _, h⟩ | (node .., p) => let ⟨_, _, _, h⟩ := exists_insert_toList_zoom_node ht e; ⟨_, _, h⟩ theorem mem_insert_of_mem {t : RBNode α} (ht : Balanced t c n) (h : v' ∈ t) : v' ∈ t.insert cmp v ∨ cmp v v' = .eq := by match e : zoom (cmp v) t with | (nil, p) => let ⟨_, _, h₁, h₂⟩ := exists_insert_toList_zoom_nil ht e simp [← mem_toList, h₁] at h simp [← mem_toList, h₂]; cases h <;> simp [*] | (node .., p) => let ⟨_, _, h₁, h₂⟩ := exists_insert_toList_zoom_node ht e simp [← mem_toList, h₁] at h simp [← mem_toList, h₂]; rcases h with h|h|h <;> simp [*] exact .inr (Path.zoom_zoomed₁ e) theorem exists_find?_insert_self [Std.TransCmp (α := α) cmp] [IsCut cmp cut] {t : RBNode α} (ht : Balanced t c n) (ht₂ : Ordered cmp t) (hv : cut v = .eq) : ∃ x, (t.insert cmp v).find? cut = some x := ht₂.insert.memP_iff_find?.1 <| memP_def.2 ⟨_, mem_insert_self ht, hv⟩ theorem find?_insert_self [Std.TransCmp (α := α) cmp] [IsStrictCut cmp cut] {t : RBNode α} (ht : Balanced t c n) (ht₂ : Ordered cmp t) (hv : cut v = .eq) : (t.insert cmp v).find? cut = some v := ht₂.insert.find?_some.2 ⟨mem_insert_self ht, hv⟩ theorem mem_insert [Std.TransCmp (α := α) cmp] {t : RBNode α} (ht : Balanced t c n) (ht₂ : Ordered cmp t) : v' ∈ t.insert cmp v ↔ (v' ∈ t ∧ t.find? (cmp v) ≠ some v') ∨ v' = v := by refine ⟨fun h => ?_, fun | .inl ⟨h₁, h₂⟩ => ?_ | .inr h => ?_⟩ · match e : zoom (cmp v) t with | (nil, p) => let ⟨_, _, h₁, h₂⟩ := exists_insert_toList_zoom_nil ht e simp [← mem_toList, h₂] at h; rw [← or_assoc, or_right_comm] at h refine h.imp_left fun h => ?_ simp [← mem_toList, h₁, h] rw [find?_eq_zoom, e]; nofun | (node .., p) => let ⟨_, _, h₁, h₂⟩ := exists_insert_toList_zoom_node ht e simp [← mem_toList, h₂] at h; simp [← mem_toList, h₁]; rw [or_left_comm] at h ⊢ rcases h with _|h <;> simp [*] refine .inl fun h => ?_ rw [find?_eq_zoom, e] at h; cases h suffices cmpLT cmp v' v' by cases Std.ReflCmp.compare_self.symm.trans this.1 have := ht₂.toList_sorted; simp [h₁, List.pairwise_append] at this exact h.elim (this.2.2 _ · |>.1) (this.2.1.1 _) · exact (mem_insert_of_mem ht h₁).resolve_right fun h' => h₂ <| ht₂.find?_some.2 ⟨h₁, h'⟩ · exact h ▸ mem_insert_self ht end RBNode open RBNode (IsCut IsStrictCut) namespace RBSet @[simp] theorem val_toList {t : RBSet α cmp} : t.1.toList = t.toList := rfl @[simp] theorem mkRBSet_eq : mkRBSet α cmp = ∅ := rfl @[simp] theorem empty_eq : @RBSet.empty α cmp = ∅ := rfl @[simp] theorem default_eq : (default : RBSet α cmp) = ∅ := rfl @[simp] theorem empty_toList : toList (∅ : RBSet α cmp) = [] := rfl @[simp] theorem single_toList : toList (single a : RBSet α cmp) = [a] := rfl theorem mem_toList {t : RBSet α cmp} : x ∈ toList t ↔ x ∈ t.1 := RBNode.mem_toList theorem mem_congr [Std.TransCmp (α := α) cmp] {t : RBSet α cmp} (h : cmp x y = .eq) : x ∈ t ↔ y ∈ t := RBNode.mem_congr h theorem mem_iff_mem_toList {t : RBSet α cmp} : x ∈ t ↔ ∃ y ∈ toList t, cmp x y = .eq := RBNode.mem_def.trans <| by simp [mem_toList] theorem mem_of_mem_toList [Std.OrientedCmp (α := α) cmp] {t : RBSet α cmp} (h : x ∈ toList t) : x ∈ t := mem_iff_mem_toList.2 ⟨_, h, Std.ReflCmp.compare_self⟩ theorem foldl_eq_foldl_toList {t : RBSet α cmp} : t.foldl f init = t.toList.foldl f init := RBNode.foldl_eq_foldl_toList theorem foldr_eq_foldr_toList {t : RBSet α cmp} : t.foldr f init = t.toList.foldr f init := RBNode.foldr_eq_foldr_toList theorem foldlM_eq_foldlM_toList [Monad m] [LawfulMonad m] {t : RBSet α cmp} : t.foldlM (m := m) f init = t.toList.foldlM f init := RBNode.foldlM_eq_foldlM_toList theorem forM_eq_forM_toList [Monad m] [LawfulMonad m] {t : RBSet α cmp} : t.forM (m := m) f = t.toList.forM f := RBNode.forM_eq_forM_toList theorem forIn_eq_forIn_toList [Monad m] [LawfulMonad m] {t : RBSet α cmp} : forIn (m := m) t init f = forIn t.toList init f := RBNode.forIn_eq_forIn_toList theorem toStream_eq {t : RBSet α cmp} : Std.toStream t = t.1.toStream .nil := rfl @[simp] theorem toStream_toList {t : RBSet α cmp} : (Std.toStream t).toList = t.toList := by simp [toStream_eq] theorem isEmpty_iff_toList_eq_nil {t : RBSet α cmp} : t.isEmpty ↔ t.toList = [] := by obtain ⟨⟨⟩, _⟩ := t <;> simp [toList, isEmpty] theorem toList_sorted {t : RBSet α cmp} : t.toList.Pairwise (RBNode.cmpLT cmp) := t.2.out.1.toList_sorted theorem findP?_some_eq_eq {t : RBSet α cmp} : t.findP? cut = some y → cut y = .eq := RBNode.find?_some_eq_eq theorem find?_some_eq_eq {t : RBSet α cmp} : t.find? x = some y → cmp x y = .eq := findP?_some_eq_eq theorem findP?_some_mem_toList {t : RBSet α cmp} (h : t.findP? cut = some y) : y ∈ toList t := mem_toList.2 <| RBNode.find?_some_mem h theorem find?_some_mem_toList {t : RBSet α cmp} (h : t.find? x = some y) : y ∈ toList t := findP?_some_mem_toList h theorem findP?_some_memP {t : RBSet α cmp} (h : t.findP? cut = some y) : t.MemP cut := RBNode.find?_some_memP h theorem find?_some_mem {t : RBSet α cmp} (h : t.find? x = some y) : x ∈ t := findP?_some_memP h theorem mem_toList_unique [Std.TransCmp (α := α) cmp] {t : RBSet α cmp} (hx : x ∈ toList t) (hy : y ∈ toList t) (e : cmp x y = .eq) : x = y := t.2.out.1.unique (mem_toList.1 hx) (mem_toList.1 hy) e theorem findP?_some [Std.TransCmp (α := α) cmp] [IsStrictCut cmp cut] {t : RBSet α cmp} : t.findP? cut = some y ↔ y ∈ toList t ∧ cut y = .eq := t.2.out.1.find?_some.trans <| by simp [mem_toList] theorem find?_some [Std.TransCmp (α := α) cmp] {t : RBSet α cmp} : t.find? x = some y ↔ y ∈ toList t ∧ cmp x y = .eq := findP?_some theorem memP_iff_findP? [Std.TransCmp (α := α) cmp] [IsCut cmp cut] {t : RBSet α cmp} : MemP cut t ↔ ∃ y, t.findP? cut = some y := t.2.out.1.memP_iff_find? theorem mem_iff_find? [Std.TransCmp (α := α) cmp] {t : RBSet α cmp} : x ∈ t ↔ ∃ y, t.find? x = some y := memP_iff_findP? @[simp] theorem contains_iff [Std.TransCmp (α := α) cmp] {t : RBSet α cmp} : t.contains x ↔ x ∈ t := Option.isSome_iff_exists.trans mem_iff_find?.symm instance [Std.TransCmp (α := α) cmp] {t : RBSet α cmp} : Decidable (x ∈ t) := decidable_of_iff _ contains_iff theorem size_eq (t : RBSet α cmp) : t.size = t.toList.length := RBNode.size_eq theorem mem_toList_insert_self (v) (t : RBSet α cmp) : v ∈ toList (t.insert v) := let ⟨_, _, h⟩ := t.2.out.2; mem_toList.2 (RBNode.mem_insert_self h) theorem mem_insert_self [Std.OrientedCmp (α := α) cmp] (v) (t : RBSet α cmp) : v ∈ t.insert v := mem_of_mem_toList <| mem_toList_insert_self v t theorem mem_insert_of_eq [Std.TransCmp (α := α) cmp] (t : RBSet α cmp) (h : cmp v v' = .eq) : v' ∈ t.insert v := (mem_congr h).1 (mem_insert_self ..) theorem mem_toList_insert_of_mem (v) {t : RBSet α cmp} (h : v' ∈ toList t) : v' ∈ toList (t.insert v) ∨ cmp v v' = .eq := let ⟨_, _, ht⟩ := t.2.out.2 .imp_left mem_toList.2 <| RBNode.mem_insert_of_mem ht <| mem_toList.1 h theorem mem_insert_of_mem_toList [Std.OrientedCmp (α := α) cmp] (v) {t : RBSet α cmp} (h : v' ∈ toList t) : v' ∈ t.insert v := match mem_toList_insert_of_mem v h with | .inl h' => mem_of_mem_toList h' | .inr h' => mem_iff_mem_toList.2 ⟨_, mem_toList_insert_self .., Std.OrientedCmp.eq_comm.1 h'⟩ theorem mem_insert_of_mem [Std.TransCmp (α := α) cmp] (v) {t : RBSet α cmp} (h : v' ∈ t) : v' ∈ t.insert v := let ⟨_, h₁, h₂⟩ := mem_iff_mem_toList.1 h (mem_congr h₂).2 (mem_insert_of_mem_toList v h₁) theorem mem_toList_insert [Std.TransCmp (α := α) cmp] {t : RBSet α cmp} : v' ∈ toList (t.insert v) ↔ (v' ∈ toList t ∧ t.find? v ≠ some v') ∨ v' = v := by let ⟨ht₁, _, _, ht₂⟩ := t.2.out simpa [mem_toList] using RBNode.mem_insert ht₂ ht₁ theorem mem_insert [Std.TransCmp (α := α) cmp] {t : RBSet α cmp} : v' ∈ t.insert v ↔ v' ∈ t ∨ cmp v v' = .eq := by refine ⟨fun h => ?_, fun | .inl h => mem_insert_of_mem _ h | .inr h => mem_insert_of_eq _ h⟩ let ⟨_, h₁, h₂⟩ := mem_iff_mem_toList.1 h match mem_toList_insert.1 h₁ with | .inl ⟨h₃, _⟩ => exact .inl <| mem_iff_mem_toList.2 ⟨_, h₃, h₂⟩ | .inr rfl => exact .inr <| Std.OrientedCmp.eq_comm.1 h₂ theorem find?_congr [Std.TransCmp (α := α) cmp] (t : RBSet α cmp) (h : cmp v₁ v₂ = .eq) : t.find? v₁ = t.find? v₂ := by simp only [find?]; congr 1; funext; rw [Std.TransCmp.congr_left h] theorem findP?_insert_of_eq [Std.TransCmp (α := α) cmp] [IsStrictCut cmp cut] (t : RBSet α cmp) (h : cut v = .eq) : (t.insert v).findP? cut = some v := findP?_some.2 ⟨mem_toList_insert_self .., h⟩ theorem find?_insert_of_eq [Std.TransCmp (α := α) cmp] (t : RBSet α cmp) (h : cmp v' v = .eq) : (t.insert v).find? v' = some v := findP?_insert_of_eq t h theorem findP?_insert_of_ne [Std.TransCmp (α := α) cmp] [IsStrictCut cmp cut] (t : RBSet α cmp) (h : cut v ≠ .eq) : (t.insert v).findP? cut = t.findP? cut := by refine Option.ext fun u => findP?_some.trans <| .trans (and_congr_left fun h' => ?_) findP?_some.symm rw [mem_toList_insert, or_iff_left, and_iff_left] · exact mt (fun h => by rwa [IsCut.congr (cut := cut) (find?_some_eq_eq h)]) h · rintro rfl; contradiction theorem find?_insert_of_ne [Std.TransCmp (α := α) cmp] (t : RBSet α cmp) (h : cmp v' v ≠ .eq) : (t.insert v).find? v' = t.find? v' := findP?_insert_of_ne t h theorem findP?_insert [Std.TransCmp (α := α) cmp] (t : RBSet α cmp) (v cut) [IsStrictCut cmp cut] : (t.insert v).findP? cut = if cut v = .eq then some v else t.findP? cut := by split <;> [exact findP?_insert_of_eq t ‹_›; exact findP?_insert_of_ne t ‹_›] theorem find?_insert [Std.TransCmp (α := α) cmp] (t : RBSet α cmp) (v v') : (t.insert v).find? v' = if cmp v' v = .eq then some v else t.find? v' := findP?_insert .. theorem upperBoundP?_eq_findP? {t : RBSet α cmp} {cut} (H : t.findP? cut = some x) : t.upperBoundP? cut = some x := RBNode.upperBound?_eq_find? _ H theorem lowerBoundP?_eq_findP? {t : RBSet α cmp} {cut} (H : t.findP? cut = some x) : t.lowerBoundP? cut = some x := RBNode.lowerBound?_eq_find? _ H theorem upperBound?_eq_find? {t : RBSet α cmp} (H : t.find? x = some y) : t.upperBound? x = some y := upperBoundP?_eq_findP? H theorem lowerBound?_eq_find? {t : RBSet α cmp} (H : t.find? x = some y) : t.lowerBound? x = some y := lowerBoundP?_eq_findP? H /-- The value `x` returned by `upperBoundP?` is greater or equal to the `cut`. -/ theorem upperBoundP?_ge {t : RBSet α cmp} : t.upperBoundP? cut = some x → cut x ≠ .gt := RBNode.upperBound?_ge /-- The value `y` returned by `upperBound? x` is greater or equal to `x`. -/ theorem upperBound?_ge {t : RBSet α cmp} : t.upperBound? x = some y → cmp x y ≠ .gt := upperBoundP?_ge /-- The value `x` returned by `lowerBoundP?` is less or equal to the `cut`. -/ theorem lowerBoundP?_le {t : RBSet α cmp} : t.lowerBoundP? cut = some x → cut x ≠ .lt := RBNode.lowerBound?_le /-- The value `y` returned by `lowerBound? x` is less or equal to `x`. -/ theorem lowerBound?_le {t : RBSet α cmp} : t.lowerBound? x = some y → cmp x y ≠ .lt := lowerBoundP?_le theorem upperBoundP?_mem_toList {t : RBSet α cmp} (h : t.upperBoundP? cut = some x) : x ∈ t.toList := mem_toList.2 (RBNode.upperBound?_mem h) theorem upperBound?_mem_toList {t : RBSet α cmp} (h : t.upperBound? x = some y) : y ∈ t.toList := upperBoundP?_mem_toList h theorem lowerBoundP?_mem_toList {t : RBSet α cmp} (h : t.lowerBoundP? cut = some x) : x ∈ t.toList := mem_toList.2 (RBNode.lowerBound?_mem h) theorem lowerBound?_mem_toList {t : RBSet α cmp} (h : t.lowerBound? x = some y) : y ∈ t.toList := lowerBoundP?_mem_toList h theorem upperBoundP?_mem [Std.OrientedCmp (α := α) cmp] {t : RBSet α cmp} (h : t.upperBoundP? cut = some x) : x ∈ t := mem_of_mem_toList (upperBoundP?_mem_toList h) theorem lowerBoundP?_mem [Std.OrientedCmp (α := α) cmp] {t : RBSet α cmp} (h : t.lowerBoundP? cut = some x) : x ∈ t := mem_of_mem_toList (lowerBoundP?_mem_toList h) theorem upperBound?_mem [Std.OrientedCmp (α := α) cmp] {t : RBSet α cmp} (h : t.upperBound? x = some y) : y ∈ t := upperBoundP?_mem h theorem lowerBound?_mem [Std.OrientedCmp (α := α) cmp] {t : RBSet α cmp} (h : t.lowerBound? x = some y) : y ∈ t := lowerBoundP?_mem h theorem upperBoundP?_exists {t : RBSet α cmp} [Std.TransCmp cmp] [IsCut cmp cut] : (∃ x, t.upperBoundP? cut = some x) ↔ ∃ x ∈ t, cut x ≠ .gt := by simp [upperBoundP?, t.2.out.1.upperBound?_exists, mem_toList, mem_iff_mem_toList] exact ⟨ fun ⟨x, h1, h2⟩ => ⟨x, ⟨x, h1, Std.ReflCmp.compare_self⟩, h2⟩, fun ⟨x, ⟨y, h1, h2⟩, eq⟩ => ⟨y, h1, IsCut.congr (cut := cut) h2 ▸ eq⟩⟩ theorem lowerBoundP?_exists {t : RBSet α cmp} [Std.TransCmp cmp] [IsCut cmp cut] : (∃ x, t.lowerBoundP? cut = some x) ↔ ∃ x ∈ t, cut x ≠ .lt := by simp [lowerBoundP?, t.2.out.1.lowerBound?_exists, mem_toList, mem_iff_mem_toList] exact ⟨ fun ⟨x, h1, h2⟩ => ⟨x, ⟨x, h1, Std.ReflCmp.compare_self⟩, h2⟩, fun ⟨x, ⟨y, h1, h2⟩, eq⟩ => ⟨y, h1, IsCut.congr (cut := cut) h2 ▸ eq⟩⟩ theorem upperBound?_exists {t : RBSet α cmp} [Std.TransCmp cmp] : (∃ y, t.upperBound? x = some y) ↔ ∃ y ∈ t, cmp x y ≠ .gt := upperBoundP?_exists theorem lowerBound?_exists {t : RBSet α cmp} [Std.TransCmp cmp] : (∃ y, t.lowerBound? x = some y) ↔ ∃ y ∈ t, cmp x y ≠ .lt := lowerBoundP?_exists /-- A statement of the least-ness of the result of `upperBoundP?`. If `x` is the return value of `upperBoundP?` and it is strictly greater than the cut, then any other `y < x` in the tree is in fact strictly less than the cut (so there is no exact match, and nothing closer to the cut). -/ theorem upperBoundP?_least {t : RBSet α cmp} [Std.TransCmp cmp] [IsCut cmp cut] (H : t.upperBoundP? cut = some x) (hy : y ∈ t) (xy : cmp y x = .lt) (hx : cut x = .lt) : cut y = .gt := let ⟨_, h1, h2⟩ := mem_iff_mem_toList.1 hy IsCut.congr (cut := cut) h2 ▸ t.2.out.1.upperBound?_least H (mem_toList.1 h1) (Std.TransCmp.congr_left h2 ▸ xy) hx /-- A statement of the greatest-ness of the result of `lowerBoundP?`. If `x` is the return value of `lowerBoundP?` and it is strictly less than the cut, then any other `y > x` in the tree is in fact strictly greater than the cut (so there is no exact match, and nothing closer to the cut). -/ theorem lowerBoundP?_greatest {t : RBSet α cmp} [Std.TransCmp cmp] [IsCut cmp cut] (H : t.lowerBoundP? cut = some x) (hy : y ∈ t) (xy : cmp x y = .lt) (hx : cut x = .gt) : cut y = .lt := let ⟨_, h1, h2⟩ := mem_iff_mem_toList.1 hy IsCut.congr (cut := cut) h2 ▸ t.2.out.1.lowerBound?_greatest H (mem_toList.1 h1) (Std.TransCmp.congr_right h2 ▸ xy) hx theorem memP_iff_upperBoundP? {t : RBSet α cmp} [Std.TransCmp cmp] [IsCut cmp cut] : t.MemP cut ↔ ∃ x, t.upperBoundP? cut = some x ∧ cut x = .eq := t.2.out.1.memP_iff_upperBound? theorem memP_iff_lowerBoundP? {t : RBSet α cmp} [Std.TransCmp cmp] [IsCut cmp cut] : t.MemP cut ↔ ∃ x, t.lowerBoundP? cut = some x ∧ cut x = .eq := t.2.out.1.memP_iff_lowerBound? theorem mem_iff_upperBound? {t : RBSet α cmp} [Std.TransCmp cmp] : x ∈ t ↔ ∃ y, t.upperBound? x = some y ∧ cmp x y = .eq := memP_iff_upperBoundP? theorem mem_iff_lowerBound? {t : RBSet α cmp} [Std.TransCmp cmp] : x ∈ t ↔ ∃ y, t.lowerBound? x = some y ∧ cmp x y = .eq := memP_iff_lowerBoundP? /-- A stronger version of `upperBoundP?_least` that holds when the cut is strict. -/ theorem lt_upperBoundP? {t : RBSet α cmp} [Std.TransCmp cmp] [IsStrictCut cmp cut] (H : t.upperBoundP? cut = some x) (hy : y ∈ t) : cmp y x = .lt ↔ cut y = .gt := let ⟨_, h1, h2⟩ := mem_iff_mem_toList.1 hy IsCut.congr (cut := cut) h2 ▸ Std.TransCmp.congr_left h2 ▸ t.2.out.1.lt_upperBound? H (mem_toList.1 h1) /-- A stronger version of `lowerBoundP?_greatest` that holds when the cut is strict. -/ theorem lowerBoundP?_lt {t : RBSet α cmp} [Std.TransCmp cmp] [IsStrictCut cmp cut] (H : t.lowerBoundP? cut = some x) (hy : y ∈ t) : cmp x y = .lt ↔ cut y = .lt := let ⟨_, h1, h2⟩ := mem_iff_mem_toList.1 hy IsCut.congr (cut := cut) h2 ▸ Std.TransCmp.congr_right h2 ▸ t.2.out.1.lowerBound?_lt H (mem_toList.1 h1) theorem lt_upperBound? {t : RBSet α cmp} [Std.TransCmp cmp] (H : t.upperBound? x = some y) (hz : z ∈ t) : cmp z y = .lt ↔ cmp z x = .lt := (lt_upperBoundP? H hz).trans Std.OrientedCmp.gt_iff_lt theorem lowerBound?_lt {t : RBSet α cmp} [Std.TransCmp cmp] (H : t.lowerBound? x = some y) (hz : z ∈ t) : cmp y z = .lt ↔ cmp x z = .lt := lowerBoundP?_lt H hz end RBSet namespace RBMap -- @[simp] -- FIXME: RBSet.val_toList already triggers here, seems bad? theorem val_toList {t : RBMap α β cmp} : t.1.toList = t.toList := rfl @[simp] theorem mkRBSet_eq : mkRBMap α β cmp = ∅ := rfl @[simp] theorem empty_eq : @RBMap.empty α β cmp = ∅ := rfl @[simp] theorem default_eq : (default : RBMap α β cmp) = ∅ := rfl @[simp] theorem empty_toList : toList (∅ : RBMap α β cmp) = [] := rfl @[simp] theorem single_toList : toList (single a b : RBMap α β cmp) = [(a, b)] := rfl theorem mem_toList {t : RBMap α β cmp} : x ∈ toList t ↔ x ∈ t.1 := RBNode.mem_toList theorem foldl_eq_foldl_toList {t : RBMap α β cmp} : t.foldl f init = t.toList.foldl (fun r p => f r p.1 p.2) init := RBNode.foldl_eq_foldl_toList theorem foldr_eq_foldr_toList {t : RBMap α β cmp} : t.foldr f init = t.toList.foldr (fun p r => f p.1 p.2 r) init := RBNode.foldr_eq_foldr_toList theorem foldlM_eq_foldlM_toList [Monad m] [LawfulMonad m] {t : RBMap α β cmp} : t.foldlM (m := m) f init = t.toList.foldlM (fun r p => f r p.1 p.2) init := RBNode.foldlM_eq_foldlM_toList theorem forM_eq_forM_toList [Monad m] [LawfulMonad m] {t : RBMap α β cmp} : t.forM (m := m) f = t.toList.forM (fun p => f p.1 p.2) := RBNode.forM_eq_forM_toList theorem forIn_eq_forIn_toList [Monad m] [LawfulMonad m] {t : RBMap α β cmp} : forIn (m := m) t init f = forIn t.toList init f := RBNode.forIn_eq_forIn_toList theorem toStream_eq {t : RBMap α β cmp} : Std.toStream t = t.1.toStream .nil := rfl @[simp] theorem toStream_toList {t : RBMap α β cmp} : (Std.toStream t).toList = t.toList := RBSet.toStream_toList theorem toList_sorted {t : RBMap α β cmp} : t.toList.Pairwise (RBNode.cmpLT (cmp ·.1 ·.1)) := RBSet.toList_sorted theorem findEntry?_some_eq_eq {t : RBMap α β cmp} : t.findEntry? x = some (y, v) → cmp x y = .eq := RBSet.findP?_some_eq_eq theorem findEntry?_some_mem_toList {t : RBMap α β cmp} (h : t.findEntry? x = some y) : y ∈ toList t := RBSet.findP?_some_mem_toList h theorem find?_some_mem_toList {t : RBMap α β cmp} (h : t.find? x = some v) : ∃ y, (y, v) ∈ toList t ∧ cmp x y = .eq := by obtain ⟨⟨y, v⟩, h', rfl⟩ := Option.map_eq_some_iff.1 h exact ⟨_, findEntry?_some_mem_toList h', findEntry?_some_eq_eq h'⟩ theorem mem_toList_unique [Std.TransCmp (α := α) cmp] {t : RBMap α β cmp} (hx : x ∈ toList t) (hy : y ∈ toList t) (e : cmp x.1 y.1 = .eq) : x = y := RBSet.mem_toList_unique hx hy e /-- A "representable cut" is one generated by `cmp a` for some `a`. This is always a valid cut. -/ instance (cmp) (a : α) : IsStrictCut cmp (cmp a) where le_lt_trans h₁ h₂ := Std.TransCmp.lt_of_lt_of_le h₂ h₁ le_gt_trans h₁ := Decidable.not_imp_not.1 (Std.TransCmp.le_trans · h₁) exact h := (Std.TransCmp.congr_left h).symm instance (f : α → β) (cmp) [Std.TransCmp (α := β) cmp] (x : β) : IsStrictCut (Ordering.byKey f cmp) (fun y => cmp x (f y)) where le_lt_trans h₁ h₂ := Std.TransCmp.lt_of_lt_of_le h₂ h₁ le_gt_trans h₁ := Decidable.not_imp_not.1 (Std.TransCmp.le_trans · h₁) exact h := (Std.TransCmp.congr_left h).symm theorem findEntry?_some [Std.TransCmp (α := α) cmp] {t : RBMap α β cmp} : t.findEntry? x = some y ↔ y ∈ toList t ∧ cmp x y.1 = .eq := RBSet.findP?_some theorem find?_some [Std.TransCmp (α := α) cmp] {t : RBMap α β cmp} : t.find? x = some v ↔ ∃ y, (y, v) ∈ toList t ∧ cmp x y = .eq := by simp only [find?, findEntry?_some, Option.map_eq_some_iff]; constructor · rintro ⟨_, h, rfl⟩; exact ⟨_, h⟩ · rintro ⟨b, h⟩; exact ⟨_, h, rfl⟩ theorem contains_iff_findEntry? {t : RBMap α β cmp} : t.contains x ↔ ∃ v, t.findEntry? x = some v := Option.isSome_iff_exists theorem contains_iff_find? {t : RBMap α β cmp} : t.contains x ↔ ∃ v, t.find? x = some v := by simp only [contains_iff_findEntry?, Prod.exists, find?, Option.map_eq_some_iff, and_comm, exists_eq_left] rw [exists_comm] theorem size_eq (t : RBMap α β cmp) : t.size = t.toList.length := RBNode.size_eq theorem mem_toList_insert_self (v) (t : RBMap α β cmp) : (k, v) ∈ toList (t.insert k v) := RBSet.mem_toList_insert_self .. theorem mem_toList_insert_of_mem (v) {t : RBMap α β cmp} (h : y ∈ toList t) : y ∈ toList (t.insert k v) ∨ cmp k y.1 = .eq := RBSet.mem_toList_insert_of_mem _ h theorem mem_toList_insert [Std.TransCmp (α := α) cmp] {t : RBMap α β cmp} : y ∈ toList (t.insert k v) ↔ (y ∈ toList t ∧ t.findEntry? k ≠ some y) ∨ y = (k, v) := RBSet.mem_toList_insert theorem findEntry?_congr [Std.TransCmp (α := α) cmp] (t : RBMap α β cmp) (h : cmp k₁ k₂ = .eq) : t.findEntry? k₁ = t.findEntry? k₂ := by simp only [findEntry?]; congr; funext; rw [Std.TransCmp.congr_left h] theorem find?_congr [Std.TransCmp (α := α) cmp] (t : RBMap α β cmp) (h : cmp k₁ k₂ = .eq) : t.find? k₁ = t.find? k₂ := by simp [find?, findEntry?_congr _ h] theorem findEntry?_insert_of_eq [Std.TransCmp (α := α) cmp] (t : RBMap α β cmp) (h : cmp k' k = .eq) : (t.insert k v).findEntry? k' = some (k, v) := RBSet.findP?_insert_of_eq _ h theorem find?_insert_of_eq [Std.TransCmp (α := α) cmp] (t : RBMap α β cmp) (h : cmp k' k = .eq) : (t.insert k v).find? k' = some v := by rw [find?, findEntry?_insert_of_eq _ h]; rfl theorem findEntry?_insert_of_ne [Std.TransCmp (α := α) cmp] (t : RBMap α β cmp) (h : cmp k' k ≠ .eq) : (t.insert k v).findEntry? k' = t.findEntry? k' := RBSet.findP?_insert_of_ne _ h theorem find?_insert_of_ne [Std.TransCmp (α := α) cmp] (t : RBMap α β cmp) (h : cmp k' k ≠ .eq) : (t.insert k v).find? k' = t.find? k' := by simp [find?, findEntry?_insert_of_ne _ h] theorem findEntry?_insert [Std.TransCmp (α := α) cmp] (t : RBMap α β cmp) (k v k') : (t.insert k v).findEntry? k' = if cmp k' k = .eq then some (k, v) else t.findEntry? k' := RBSet.findP?_insert .. theorem find?_insert [Std.TransCmp (α := α) cmp] (t : RBMap α β cmp) (k v k') : (t.insert k v).find? k' = if cmp k' k = .eq then some v else t.find? k' := by split <;> [exact find?_insert_of_eq t ‹_›; exact find?_insert_of_ne t ‹_›] end RBMap
.lake/packages/batteries/Batteries/Data/RBMap/Basic.lean
module public import Batteries.Classes.Order public import Batteries.Control.ForInStep.Basic public import Batteries.Tactic.Lint.Misc @[expose] public section /-! # Red-black trees Note: users are recommended to use `Std.TreeMap` instead of `Batteries.RBMap`. `Std.TreeMap` is a mostly drop-in replacement (notably, there is no `ToStream` instance yet), and has more complete and consistent API. This implementation will eventually be deprecated. This module implements a type `RBMap α β cmp` which is a functional data structure for storing a key-value store in a binary search tree. It is built on the simpler `RBSet α cmp` type, which stores a set of values of type `α` using the function `cmp : α → α → Ordering` for determining the ordering relation. The tree will never store two elements that compare `.eq` under the `cmp` function, but the function does not have to satisfy `cmp x y = .eq → x = y`, and in the map case `α` is a key-value pair and the `cmp` function only compares the keys. -/ namespace Batteries /-- In a red-black tree, every node has a color which is either "red" or "black" (this particular choice of colors is conventional). A nil node is considered black. -/ inductive RBColor where /-- A red node is required to have black children. -/ | red /-- Every path from the root to a leaf must pass through the same number of black nodes. -/ | black deriving Repr /-- A red-black tree. (This is an internal implementation detail of the `RBSet` type, which includes the invariants of the tree.) This is a binary search tree augmented with a "color" field which is either red or black for each node and used to implement the re-balancing operations. See: [Red–black tree](https://en.wikipedia.org/wiki/Red%E2%80%93black_tree) -/ inductive RBNode (α : Type u) where /-- An empty tree. -/ | nil /-- A node consists of a value `v`, a subtree `l` of smaller items, and a subtree `r` of larger items. The color `c` is either `red` or `black` and participates in the red-black balance invariant (see `Balanced`). -/ | node (c : RBColor) (l : RBNode α) (v : α) (r : RBNode α) deriving Repr namespace RBNode open RBColor instance : EmptyCollection (RBNode α) := ⟨nil⟩ /-- The minimum element of a tree is the left-most value. -/ protected def min? : RBNode α → Option α | nil => none | node _ nil v _ => some v | node _ l _ _ => l.min? /-- The maximum element of a tree is the right-most value. -/ protected def max? : RBNode α → Option α | nil => none | node _ _ v nil => some v | node _ _ _ r => r.max? /-- Fold a function in tree order along the nodes. `v₀` is used at `nil` nodes and `f` is used to combine results at branching nodes. -/ @[specialize] def fold (v₀ : σ) (f : σ → α → σ → σ) : RBNode α → σ | nil => v₀ | node _ l v r => f (l.fold v₀ f) v (r.fold v₀ f) /-- Fold a function on the values from left to right (in increasing order). -/ @[specialize] def foldl (f : σ → α → σ) : (init : σ) → RBNode α → σ | b, nil => b | b, node _ l v r => foldl f (f (foldl f b l) v) r /-- Fold a function on the values from right to left (in decreasing order). -/ @[specialize] def foldr (f : α → σ → σ) : RBNode α → (init : σ) → σ | nil, b => b | node _ l v r, b => l.foldr f <| f v <| r.foldr f b /-- `O(n)`. Convert the tree to a list in ascending order. -/ def toList (t : RBNode α) : List α := t.foldr (·::·) [] /-- Run monadic function `f` on each element of the tree (in increasing order). -/ @[specialize] def forM [Monad m] (f : α → m PUnit) : RBNode α → m PUnit | nil => pure ⟨⟩ | node _ l v r => do forM f l; f v; forM f r /-- Fold a monadic function on the values from left to right (in increasing order). -/ @[specialize] def foldlM [Monad m] (f : σ → α → m σ) : (init : σ) → RBNode α → m σ | b, nil => pure b | b, node _ l v r => do foldlM f (← f (← foldlM f b l) v) r /-- Implementation of `for x in t` loops over a `RBNode` (in increasing order). -/ @[inline] protected def forIn [Monad m] (as : RBNode α) (init : σ) (f : α → σ → m (ForInStep σ)) : m σ := do ForInStep.run <$> visit as init where /-- Inner loop of `forIn`. -/ @[specialize] visit : RBNode α → σ → m (ForInStep σ) | nil, b => return ForInStep.yield b | node _ l v r, b => ForInStep.bindM (visit l b) fun b => ForInStep.bindM (f v b) (visit r ·) instance : ForIn m (RBNode α) α where forIn := RBNode.forIn /-- An auxiliary data structure (an iterator) over an `RBNode` which lazily pulls elements from the left. -/ protected inductive Stream (α : Type _) /-- The stream is empty. -/ | nil /-- We are ready to deliver element `v` with right child `r`, and where `tail` represents all the subtrees we have yet to destructure. -/ | cons (v : α) (r : RBNode α) (tail : RBNode.Stream α) /-- `O(log n)`. Turn a node into a stream, by descending along the left spine. -/ def toStream : RBNode α → (_ : RBNode.Stream α := .nil) → RBNode.Stream α | nil, acc => acc | node _ l v r, acc => toStream l (.cons v r acc) namespace Stream /-- `O(1)` amortized, `O(log n)` worst case: Get the next element from the stream. -/ def next? : RBNode.Stream α → Option (α × RBNode.Stream α) | nil => none | cons v r tail => some (v, toStream r tail) /-- Fold a function on the values from left to right (in increasing order). -/ @[specialize] def foldl (f : σ → α → σ) : (init : σ) → RBNode.Stream α → σ | b, nil => b | b, cons v r tail => foldl f (r.foldl f (f b v)) tail /-- Fold a function on the values from right to left (in decreasing order). -/ @[specialize] def foldr (f : α → σ → σ) : RBNode.Stream α → (init : σ) → σ | nil, b => b | cons v r tail, b => f v <| r.foldr f <| tail.foldr f b /-- `O(n)`. Convert the stream to a list in ascending order. -/ def toList (t : RBNode.Stream α) : List α := t.foldr (·::·) [] end Stream instance : Std.ToStream (RBNode α) (RBNode.Stream α) := ⟨(·.toStream)⟩ instance : Std.Stream (RBNode.Stream α) α := ⟨Stream.next?⟩ /-- Returns `true` iff every element of the tree satisfies `p`. -/ @[specialize] def all (p : α → Bool) : RBNode α → Bool | nil => true | node _ l v r => p v && all p l && all p r /-- Returns `true` iff any element of the tree satisfies `p`. -/ @[specialize] def any (p : α → Bool) : RBNode α → Bool | nil => false | node _ l v r => p v || any p l || any p r /-- Asserts that `p` holds on every element of the tree. -/ def All (p : α → Prop) : RBNode α → Prop | nil => True | node _ l v r => p v ∧ All p l ∧ All p r theorem All.imp (H : ∀ {x : α}, p x → q x) : ∀ {t : RBNode α}, t.All p → t.All q | nil => id | node .. => fun ⟨h, hl, hr⟩ => ⟨H h, hl.imp H, hr.imp H⟩ theorem all_iff {t : RBNode α} : t.all p ↔ t.All (p ·) := by induction t <;> simp [*, all, All, and_assoc] instance {t : RBNode α} [DecidablePred p] : Decidable (t.All p) := decidable_of_iff (t.all p) (by simp [all_iff]) /-- Asserts that `p` holds on some element of the tree. -/ def Any (p : α → Prop) : RBNode α → Prop | nil => False | node _ l v r => p v ∨ Any p l ∨ Any p r theorem any_iff {t : RBNode α} : t.any p ↔ t.Any (p ·) := by induction t <;> simp [*, any, Any, or_assoc] instance {t : RBNode α} [DecidablePred p] : Decidable (t.Any p) := decidable_of_iff (t.any p) (by simp [any_iff]) /-- True if `x` is an element of `t` "exactly", i.e. up to equality, not the `cmp` relation. -/ def EMem (x : α) (t : RBNode α) : Prop := t.Any (x = ·) instance : Membership α (RBNode α) where mem t x := EMem x t /-- True if the specified `cut` matches at least one element of of `t`. -/ def MemP (cut : α → Ordering) (t : RBNode α) : Prop := t.Any (cut · = .eq) /-- True if `x` is equivalent to an element of `t`. -/ @[reducible] def Mem (cmp : α → α → Ordering) (x : α) (t : RBNode α) : Prop := MemP (cmp x) t -- These instances are put in a special namespace because they are usually not what users want -- when deciding membership in a RBSet, since this does a naive linear search through the tree. -- The real `O(log n)` instances are defined in `Data.RBMap.Lemmas`. @[nolint docBlame] scoped instance Slow.instDecidableEMem [DecidableEq α] {t : RBNode α} : Decidable (EMem x t) := inferInstanceAs (Decidable (Any ..)) @[nolint docBlame] scoped instance Slow.instDecidableMemP {t : RBNode α} : Decidable (MemP cut t) := inferInstanceAs (Decidable (Any ..)) @[nolint docBlame] scoped instance Slow.instDecidableMem {t : RBNode α} : Decidable (Mem cmp x t) := inferInstanceAs (Decidable (Any ..)) /-- Asserts that `t₁` and `t₂` have the same number of elements in the same order, and `R` holds pairwise between them. The tree structure is ignored. -/ @[specialize] def all₂ (R : α → β → Bool) (t₁ : RBNode α) (t₂ : RBNode β) : Bool := let result := StateT.run (s := t₂.toStream) <| t₁.forM fun a s => do let (b, s) ← s.next? bif R a b then pure (⟨⟩, s) else none result matches some (_, .nil) instance [BEq α] : BEq (RBNode α) where beq a b := a.all₂ (· == ·) b /-- We say that `x < y` under the comparator `cmp` if `cmp x y = .lt`. * In order to avoid assuming the comparator is always lawful, we use a local `∀ [Std.TransCmp cmp]` binder in the relation so that the ordering properties of the tree only need to hold if the comparator is lawful. * The `Nonempty` wrapper is a no-op because this is already a proposition, but it prevents the `[Std.TransCmp cmp]` binder from being introduced when we don't want it. -/ def cmpLT (cmp : α → α → Ordering) (x y : α) : Prop := Nonempty (∀ [Std.TransCmp cmp], cmp x y = .lt) theorem cmpLT_iff [Std.TransCmp cmp] : cmpLT cmp x y ↔ cmp x y = .lt := ⟨fun ⟨h⟩ => h, (⟨·⟩)⟩ instance (cmp) [Std.TransCmp cmp] : Decidable (cmpLT cmp x y) := decidable_of_iff' _ cmpLT_iff /-- We say that `x ≈ y` under the comparator `cmp` if `cmp x y = .eq`. See also `cmpLT`. -/ def cmpEq (cmp : α → α → Ordering) (x y : α) : Prop := Nonempty (∀ [Std.TransCmp cmp], cmp x y = .eq) theorem cmpEq_iff [Std.TransCmp cmp] : cmpEq cmp x y ↔ cmp x y = .eq := ⟨fun ⟨h⟩ => h, (⟨·⟩)⟩ instance (cmp) [Std.TransCmp cmp] : Decidable (cmpEq cmp x y) := decidable_of_iff' _ cmpEq_iff /-- `O(n)`. Verifies an ordering relation on the nodes of the tree. -/ def isOrdered (cmp : α → α → Ordering) (t : RBNode α) (l : Option α := none) (r : Option α := none) : Bool := match t with | nil => match l, r with | some l, some r => cmp l r = .lt | _, _ => true | node _ a v b => isOrdered cmp a l v && isOrdered cmp b v r /-- The first half of Okasaki's `balance`, concerning red-red sequences in the left child. -/ @[inline] def balance1 : RBNode α → α → RBNode α → RBNode α | node red (node red a x b) y c, z, d | node red a x (node red b y c), z, d => node red (node black a x b) y (node black c z d) | a, x, b => node black a x b /-- The second half of Okasaki's `balance`, concerning red-red sequences in the right child. -/ @[inline] def balance2 : RBNode α → α → RBNode α → RBNode α | a, x, node red b y (node red c z d) | a, x, node red (node red b y c) z d => node red (node black a x b) y (node black c z d) | a, x, b => node black a x b /-- Returns `red` if the node is red, otherwise `black`. (Nil nodes are treated as `black`.) -/ @[inline] def isRed : RBNode α → RBColor | node c .. => c | _ => black /-- Returns `black` if the node is black, otherwise `red`. (Nil nodes are treated as `red`, which is not the usual convention but useful for deletion.) -/ @[inline] def isBlack : RBNode α → RBColor | node c .. => c | _ => red /-- Changes the color of the root to `black`. -/ def setBlack : RBNode α → RBNode α | nil => nil | node _ l v r => node black l v r /-- `O(n)`. Reverses the ordering of the tree without any rebalancing. -/ @[simp] def reverse : RBNode α → RBNode α | nil => nil | node c l v r => node c r.reverse v l.reverse section Insert /-- The core of the `insert` function. This adds an element `x` to a balanced red-black tree. Importantly, the result of calling `ins` is not a proper red-black tree, because it has a broken balance invariant. (See `Balanced.ins` for the balance invariant of `ins`.) The `insert` function does the final fixup needed to restore the invariant. -/ @[specialize] def ins (cmp : α → α → Ordering) (x : α) : RBNode α → RBNode α | nil => node red nil x nil | node red a y b => match cmp x y with | Ordering.lt => node red (ins cmp x a) y b | Ordering.gt => node red a y (ins cmp x b) | Ordering.eq => node red a x b | node black a y b => match cmp x y with | Ordering.lt => balance1 (ins cmp x a) y b | Ordering.gt => balance2 a y (ins cmp x b) | Ordering.eq => node black a x b /-- `insert cmp t v` inserts element `v` into the tree, using the provided comparator `cmp` to put it in the right place and automatically rebalancing the tree as necessary. -/ @[specialize] def insert (cmp : α → α → Ordering) (t : RBNode α) (v : α) : RBNode α := match isRed t with | red => (ins cmp v t).setBlack | black => ins cmp v t end Insert /-- Recolor the root of the tree to `red` if possible. -/ def setRed : RBNode α → RBNode α | node _ a v b => node red a v b | nil => nil /-- Rebalancing a tree which has shrunk on the left. -/ def balLeft (l : RBNode α) (v : α) (r : RBNode α) : RBNode α := match l with | node red a x b => node red (node black a x b) v r | l => match r with | node black a y b => balance2 l v (node red a y b) | node red (node black a y b) z c => node red (node black l v a) y (balance2 b z (setRed c)) | r => node red l v r -- unreachable /-- Rebalancing a tree which has shrunk on the right. -/ def balRight (l : RBNode α) (v : α) (r : RBNode α) : RBNode α := match r with | node red b y c => node red l v (node black b y c) | r => match l with | node black a x b => balance1 (node red a x b) v r | node red a x (node black b y c) => node red (balance1 (setRed a) x b) y (node black c v r) | l => node red l v r -- unreachable /-- The number of nodes in the tree. -/ @[simp] def size : RBNode α → Nat | nil => 0 | node _ x _ y => x.size + y.size + 1 /-- Concatenate two trees with the same black-height. -/ def append : RBNode α → RBNode α → RBNode α | nil, x | x, nil => x | node red a x b, node red c y d => match append b c with | node red b' z c' => node red (node red a x b') z (node red c' y d) | bc => node red a x (node red bc y d) | node black a x b, node black c y d => match append b c with | node red b' z c' => node red (node black a x b') z (node black c' y d) | bc => balLeft a x (node black bc y d) | a@(node black ..), node red b x c => node red (append a b) x c | node red a x b, c@(node black ..) => node red a x (append b c) termination_by x y => x.size + y.size /-! ## erase -/ /-- The core of the `erase` function. The tree returned from this function has a broken invariant, which is restored in `erase`. -/ @[specialize] def del (cut : α → Ordering) : RBNode α → RBNode α | nil => nil | node _ a y b => match cut y with | .lt => match a.isBlack with | black => balLeft (del cut a) y b | red => node red (del cut a) y b | .gt => match b.isBlack with | black => balRight a y (del cut b) | red => node red a y (del cut b) | .eq => append a b /-- The `erase cut t` function removes an element from the tree `t`. The `cut` function is used to locate an element in the tree: it returns `.gt` if we go too high and `.lt` if we go too low; if it returns `.eq` we will remove the element. (The function `cmp k` for some key `k` is a valid cut function, but we can also use cuts that are not of this form as long as they are suitably monotonic.) -/ @[specialize] def erase (cut : α → Ordering) (t : RBNode α) : RBNode α := (del cut t).setBlack /-- Finds an element in the tree satisfying the `cut` function. -/ @[specialize] def find? (cut : α → Ordering) : RBNode α → Option α | nil => none | node _ a y b => match cut y with | .lt => find? cut a | .gt => find? cut b | .eq => some y /-- `upperBound? cut` retrieves the smallest entry larger than or equal to `cut`, if it exists. -/ @[specialize] def upperBound? (cut : α → Ordering) : RBNode α → (ub : Option α := .none) → Option α | nil, ub => ub | node _ a y b, ub => match cut y with | .lt => upperBound? cut a (some y) | .gt => upperBound? cut b ub | .eq => some y /-- `lowerBound? cut` retrieves the largest entry smaller than or equal to `cut`, if it exists. -/ @[specialize] def lowerBound? (cut : α → Ordering) : RBNode α → (lb : Option α := .none) → Option α | nil, lb => lb | node _ a y b, lb => match cut y with | .lt => lowerBound? cut a lb | .gt => lowerBound? cut b (some y) | .eq => some y /-- Returns the root of the tree, if any. -/ def root? : RBNode α → Option α | nil => none | node _ _ v _ => some v /-- `O(n)`. Map a function on every value in the tree. This requires `IsMonotone` on the function in order to preserve the order invariant. -/ @[specialize] def map (f : α → β) : RBNode α → RBNode β | nil => nil | node c l v r => node c (l.map f) (f v) (r.map f) /-- Converts the tree into an array in increasing sorted order. -/ def toArray (n : RBNode α) : Array α := n.foldl (init := #[]) (·.push ·) /-- A `RBNode.Path α` is a "cursor" into an `RBNode` which represents the path from the root to a subtree. Note that the path goes from the target subtree up to the root, which is reversed from the normal way data is stored in the tree. See [Zipper](https://en.wikipedia.org/wiki/Zipper_(data_structure)) for more information. -/ inductive Path (α : Type u) where /-- The root of the tree, which is the end of the path of parents. -/ | root /-- A path that goes down the left subtree. -/ | left (c : RBColor) (parent : Path α) (v : α) (r : RBNode α) /-- A path that goes down the right subtree. -/ | right (c : RBColor) (l : RBNode α) (v : α) (parent : Path α) /-- Fills the `Path` with a subtree. -/ def Path.fill : Path α → RBNode α → RBNode α | .root, t => t | .left c parent y b, a | .right c a y parent, b => parent.fill (node c a y b) /-- Like `find?`, but instead of just returning the element, it returns the entire subtree at the element and a path back to the root for reconstructing the tree. -/ @[specialize] def zoom (cut : α → Ordering) : RBNode α → (e : Path α := .root) → RBNode α × Path α | nil, path => (nil, path) | n@(node c a y b), path => match cut y with | .lt => zoom cut a (.left c path y b) | .gt => zoom cut b (.right c a y path) | .eq => (n, path) /-- This function does the second part of `RBNode.ins`, which unwinds the stack and rebuilds the tree. -/ def Path.ins : Path α → RBNode α → RBNode α | .root, t => t.setBlack | .left red parent y b, a | .right red a y parent, b => parent.ins (node red a y b) | .left black parent y b, a => parent.ins (balance1 a y b) | .right black a y parent, b => parent.ins (balance2 a y b) /-- `path.insertNew v` inserts element `v` into the tree, assuming that `path` is zoomed in on a `nil` node such that inserting a new element at this position is valid. -/ @[inline] def Path.insertNew (path : Path α) (v : α) : RBNode α := path.ins (node red nil v nil) /-- `path.insert t v` inserts element `v` into the tree, assuming that `(t, path)` was the result of a previous `zoom` operation (so either the root of `t` is equivalent to `v` or it is empty). -/ def Path.insert (path : Path α) (t : RBNode α) (v : α) : RBNode α := match t with | nil => path.insertNew v | node c a _ b => path.fill (node c a v b) /-- `path.del t c` does the second part of `RBNode.del`, which unwinds the stack and rebuilds the tree. The `c` argument is the color of the node before the deletion (we used `t₀.isBlack` for this in `RBNode.del` but the original tree is no longer available in this formulation). -/ def Path.del : Path α → RBNode α → RBColor → RBNode α | .root, t, _ => t.setBlack | .left c parent y b, a, red | .right c a y parent, b, red => parent.del (node red a y b) c | .left c parent y b, a, black => parent.del (balLeft a y b) c | .right c a y parent, b, black => parent.del (balRight a y b) c /-- `path.erase t v` removes the root element of `t` from the tree, assuming that `(t, path)` was the result of a previous `zoom` operation. -/ def Path.erase (path : Path α) (t : RBNode α) : RBNode α := match t with | nil => path.fill nil | node c a _ b => path.del (a.append b) c /-- `modify cut f t` uses `cut` to find an element, then modifies the element using `f` and reinserts it into the tree. Because the tree structure is not modified, `f` must not modify the ordering properties of the element. The element in `t` is used linearly if `t` is unshared. -/ @[specialize] def modify (cut : α → Ordering) (f : α → α) (t : RBNode α) : RBNode α := match zoom cut t with | (nil, _) => t -- TODO: profile whether it would be better to use `path.fill nil` here | (node c a x b, path) => path.fill (node c a (f x) b) /-- `alter cut f t` simultaneously handles inserting, erasing and replacing an element using a function `f : Option α → Option α`. It is passed the result of `t.find? cut` and can either return `none` to remove the element or `some a` to replace/insert the element with `a` (which must have the same ordering properties as the original element). The element is used linearly if `t` is unshared. -/ @[specialize] def alter (cut : α → Ordering) (f : Option α → Option α) (t : RBNode α) : RBNode α := match zoom cut t with | (nil, path) => match f none with | none => t -- TODO: profile whether it would be better to use `path.fill nil` here | some y => path.insertNew y | (node c a x b, path) => match f (some x) with | none => path.del (a.append b) c | some y => path.fill (node c a y b) /-- The ordering invariant of a red-black tree, which is a binary search tree. This says that every element of a left subtree is less than the root, and every element in the right subtree is greater than the root, where the less than relation `x < y` is understood to mean `cmp x y = .lt`. Because we do not assume that `cmp` is lawful when stating this property, we write it in such a way that if `cmp` is not lawful then the condition holds trivially. That way we can prove the ordering invariants without assuming `cmp` is lawful. -/ def Ordered (cmp : α → α → Ordering) : RBNode α → Prop | nil => True | node _ a x b => a.All (cmpLT cmp · x) ∧ b.All (cmpLT cmp x ·) ∧ a.Ordered cmp ∧ b.Ordered cmp -- This is in the Slow namespace because it is `O(n^2)` where a `O(n)` algorithm exists -- (see `isOrdered_iff` in `Data.RBMap.Lemmas`). Prefer `isOrdered` or the other instance. @[nolint docBlame] scoped instance Slow.instDecidableOrdered (cmp) [Std.TransCmp cmp] : ∀ t : RBNode α, Decidable (Ordered cmp t) | nil => inferInstanceAs (Decidable True) | node _ a _ b => haveI := instDecidableOrdered cmp a haveI := instDecidableOrdered cmp b inferInstanceAs (Decidable (And ..)) /-- The red-black balance invariant. `Balanced t c n` says that the color of the root node is `c`, and the black-height (the number of black nodes on any path from the root) of the tree is `n`. Additionally, every red node must have black children. -/ inductive Balanced : RBNode α → RBColor → Nat → Prop where /-- A nil node is balanced with black-height 0, and it is considered black. -/ | protected nil : Balanced nil black 0 /-- A red node is balanced with black-height `n` if its children are both black with with black-height `n`. -/ | protected red : Balanced x black n → Balanced y black n → Balanced (node red x v y) red n /-- A black node is balanced with black-height `n + 1` if its children both have black-height `n`. -/ | protected black : Balanced x c₁ n → Balanced y c₂ n → Balanced (node black x v y) black (n + 1) /-- The well-formedness invariant for a red-black tree. The first constructor is the real invariant, and the others allow us to "cheat" in this file and define `insert` and `erase`, which have more complex proofs that are delayed to `Batteries.Data.RBMap.Lemmas`. -/ inductive WF (cmp : α → α → Ordering) : RBNode α → Prop /-- The actual well-formedness invariant: a red-black tree has the ordering and balance invariants. -/ | mk : t.Ordered cmp → t.Balanced c n → WF cmp t /-- Inserting into a well-formed tree yields another well-formed tree. (See `Ordered.insert` and `Balanced.insert` for the actual proofs.) -/ | insert : WF cmp t → WF cmp (t.insert cmp a) /-- Erasing from a well-formed tree yields another well-formed tree. (See `Ordered.erase` and `Balanced.erase` for the actual proofs.) -/ | erase : WF cmp t → WF cmp (t.erase cut) end RBNode open RBNode /-- An `RBSet` is a self-balancing binary search tree. The `cmp` function is the comparator that will be used for performing searches; it should satisfy the requirements of `TransCmp` for it to have sensible behavior. -/ def RBSet (α : Type u) (cmp : α → α → Ordering) : Type u := {t : RBNode α // t.WF cmp} /-- `O(1)`. Construct a new empty tree. -/ @[inline] def mkRBSet (α : Type u) (cmp : α → α → Ordering) : RBSet α cmp := ⟨.nil, .mk ⟨⟩ .nil⟩ namespace RBSet /-- `O(1)`. Construct a new empty tree. -/ @[inline] def empty : RBSet α cmp := mkRBSet .. instance (α : Type u) (cmp : α → α → Ordering) : EmptyCollection (RBSet α cmp) := ⟨empty⟩ instance (α : Type u) (cmp : α → α → Ordering) : Inhabited (RBSet α cmp) := ⟨∅⟩ /-- `O(1)`. Construct a new tree with one element `v`. -/ @[inline] def single (v : α) : RBSet α cmp := ⟨.node .red .nil v .nil, .mk ⟨⟨⟩, ⟨⟩, ⟨⟩, ⟨⟩⟩ (.red .nil .nil)⟩ /-- `O(n)`. Fold a function on the values from left to right (in increasing order). -/ @[inline] def foldl (f : σ → α → σ) (init : σ) (t : RBSet α cmp) : σ := t.1.foldl f init /-- `O(n)`. Fold a function on the values from right to left (in decreasing order). -/ @[inline] def foldr (f : α → σ → σ) (init : σ) (t : RBSet α cmp) : σ := t.1.foldr f init /-- `O(n)`. Fold a monadic function on the values from left to right (in increasing order). -/ @[inline] def foldlM [Monad m] (f : σ → α → m σ) (init : σ) (t : RBSet α cmp) : m σ := t.1.foldlM f init /-- `O(n)`. Run monadic function `f` on each element of the tree (in increasing order). -/ @[inline] def forM [Monad m] (f : α → m PUnit) (t : RBSet α cmp) : m PUnit := t.1.forM f instance : ForIn m (RBSet α cmp) α where forIn t := t.1.forIn instance : Std.ToStream (RBSet α cmp) (RBNode.Stream α) := ⟨fun x => x.1.toStream .nil⟩ /-- `O(1)`. Is the tree empty? -/ @[inline] def isEmpty : RBSet α cmp → Bool | ⟨nil, _⟩ => true | _ => false /-- `O(n)`. Convert the tree to a list in ascending order. -/ @[inline] def toList (t : RBSet α cmp) : List α := t.1.toList /-- `O(log n)`. Returns the entry `a` such that `a ≤ k` for all keys in the RBSet. -/ @[inline] protected def min? (t : RBSet α cmp) : Option α := t.1.min? /-- `O(log n)`. Returns the entry `a` such that `a ≥ k` for all keys in the RBSet. -/ @[inline] protected def max? (t : RBSet α cmp) : Option α := t.1.max? instance [Repr α] : Repr (RBSet α cmp) where reprPrec m prec := Repr.addAppParen ("RBSet.ofList " ++ repr m.toList) prec /-- `O(log n)`. Insert element `v` into the tree. -/ @[inline] def insert (t : RBSet α cmp) (v : α) : RBSet α cmp := ⟨t.1.insert cmp v, t.2.insert⟩ /-- Insert all elements from a collection into a `RBSet α cmp`. -/ def insertMany [ForIn Id ρ α] (s : RBSet α cmp) (as : ρ) : RBSet α cmp := Id.run do let mut s := s for a in as do s := s.insert a return s /-- `O(log n)`. Remove an element from the tree using a cut function. The `cut` function is used to locate an element in the tree: it returns `.gt` if we go too high and `.lt` if we go too low; if it returns `.eq` we will remove the element. (The function `cmp k` for some key `k` is a valid cut function, but we can also use cuts that are not of this form as long as they are suitably monotonic.) -/ @[inline] def erase (t : RBSet α cmp) (cut : α → Ordering) : RBSet α cmp := ⟨t.1.erase cut, t.2.erase⟩ /-- `O(log n)`. Find an element in the tree using a cut function. -/ @[inline] def findP? (t : RBSet α cmp) (cut : α → Ordering) : Option α := t.1.find? cut /-- `O(log n)`. Returns an element in the tree equivalent to `x` if one exists. -/ @[inline] def find? (t : RBSet α cmp) (x : α) : Option α := t.1.find? (cmp x) /-- `O(log n)`. Find an element in the tree, or return a default value `v₀`. -/ @[inline] def findPD (t : RBSet α cmp) (cut : α → Ordering) (v₀ : α) : α := (t.findP? cut).getD v₀ /-- `O(log n)`. `upperBoundP cut` retrieves the smallest entry comparing `gt` or `eq` under `cut`, if it exists. If multiple keys in the map return `eq` under `cut`, any of them may be returned. -/ @[inline] def upperBoundP? (t : RBSet α cmp) (cut : α → Ordering) : Option α := t.1.upperBound? cut /-- `O(log n)`. `upperBound? k` retrieves the largest entry smaller than or equal to `k`, if it exists. -/ @[inline] def upperBound? (t : RBSet α cmp) (k : α) : Option α := t.upperBoundP? (cmp k) /-- `O(log n)`. `lowerBoundP cut` retrieves the largest entry comparing `lt` or `eq` under `cut`, if it exists. If multiple keys in the map return `eq` under `cut`, any of them may be returned. -/ @[inline] def lowerBoundP? (t : RBSet α cmp) (cut : α → Ordering) : Option α := t.1.lowerBound? cut /-- `O(log n)`. `lowerBound? k` retrieves the largest entry smaller than or equal to `k`, if it exists. -/ @[inline] def lowerBound? (t : RBSet α cmp) (k : α) : Option α := t.lowerBoundP? (cmp k) /-- `O(log n)`. Returns true if the given cut returns `eq` for something in the RBSet. -/ @[inline] def containsP (t : RBSet α cmp) (cut : α → Ordering) : Bool := (t.findP? cut).isSome /-- `O(log n)`. Returns true if the given key `a` is in the RBSet. -/ @[inline] def contains (t : RBSet α cmp) (a : α) : Bool := (t.find? a).isSome /-- `O(n log n)`. Build a tree from an unsorted list by inserting them one at a time. -/ @[inline] def ofList (l : List α) (cmp : α → α → Ordering) : RBSet α cmp := l.foldl (fun r p => r.insert p) (mkRBSet α cmp) /-- `O(n log n)`. Build a tree from an unsorted array by inserting them one at a time. -/ @[inline] def ofArray (l : Array α) (cmp : α → α → Ordering) : RBSet α cmp := l.foldl (fun r p => r.insert p) (mkRBSet α cmp) /-- `O(n)`. Returns true if the given predicate is true for all items in the RBSet. -/ @[inline] def all (t : RBSet α cmp) (p : α → Bool) : Bool := t.1.all p /-- `O(n)`. Returns true if the given predicate is true for any item in the RBSet. -/ @[inline] def any (t : RBSet α cmp) (p : α → Bool) : Bool := t.1.any p /-- Asserts that `t₁` and `t₂` have the same number of elements in the same order, and `R` holds pairwise between them. The tree structure is ignored. -/ @[inline] def all₂ (R : α → β → Bool) (t₁ : RBSet α cmpα) (t₂ : RBSet β cmpβ) : Bool := t₁.1.all₂ R t₂.1 /-- True if `x` is an element of `t` "exactly", i.e. up to equality, not the `cmp` relation. -/ def EMem (x : α) (t : RBSet α cmp) : Prop := t.1.EMem x /-- True if the specified `cut` matches at least one element of of `t`. -/ def MemP (cut : α → Ordering) (t : RBSet α cmp) : Prop := t.1.MemP cut /-- True if `x` is equivalent to an element of `t`. -/ def Mem (x : α) (t : RBSet α cmp) : Prop := MemP (cmp x) t instance : Membership α (RBSet α cmp) where mem t x := Mem x t -- These instances are put in a special namespace because they are usually not what users want -- when deciding membership in a RBSet, since this does a naive linear search through the tree. -- The real `O(log n)` instances are defined in `Data.RBMap.Lemmas`. @[nolint docBlame] scoped instance Slow.instDecidableEMem [DecidableEq α] {t : RBSet α cmp} : Decidable (EMem x t) := inferInstanceAs (Decidable (Any ..)) @[nolint docBlame] scoped instance Slow.instDecidableMemP {t : RBSet α cmp} : Decidable (MemP cut t) := inferInstanceAs (Decidable (Any ..)) @[nolint docBlame] scoped instance Slow.instDecidableMem {t : RBSet α cmp} : Decidable (Mem x t) := inferInstanceAs (Decidable (Any ..)) /-- Returns true if `t₁` and `t₂` are equal as sets (assuming `cmp` and `==` are compatible), ignoring the internal tree structure. -/ instance [BEq α] : BEq (RBSet α cmp) where beq a b := a.all₂ (· == ·) b /-- `O(n)`. The number of items in the RBSet. -/ def size (m : RBSet α cmp) : Nat := m.1.size /-- `O(log n)`. Returns the minimum element of the tree, or panics if the tree is empty. -/ @[inline] def min! [Inhabited α] (t : RBSet α cmp) : α := t.min?.getD (panic! "tree is empty") /-- `O(log n)`. Returns the maximum element of the tree, or panics if the tree is empty. -/ @[inline] def max! [Inhabited α] (t : RBSet α cmp) : α := t.max?.getD (panic! "tree is empty") /-- `O(log n)`. Attempts to find the value with key `k : α` in `t` and panics if there is no such key. -/ @[inline] def findP! [Inhabited α] (t : RBSet α cmp) (cut : α → Ordering) : α := (t.findP? cut).getD (panic! "key is not in the tree") /-- `O(log n)`. Attempts to find the value with key `k : α` in `t` and panics if there is no such key. -/ @[inline] def find! [Inhabited α] (t : RBSet α cmp) (k : α) : α := (t.find? k).getD (panic! "key is not in the tree") /-- The predicate asserting that the result of `modifyP` is safe to construct. -/ class ModifyWF (t : RBSet α cmp) (cut : α → Ordering) (f : α → α) : Prop where /-- The resulting tree is well formed. -/ wf : (t.1.modify cut f).WF cmp /-- `O(log n)`. In-place replace an element found by `cut`. This takes the element out of the tree while `f` runs, so it uses the element linearly if `t` is unshared. The `ModifyWF` assumption is required because `f` may change the ordering properties of the element, which would break the invariants. -/ def modifyP (t : RBSet α cmp) (cut : α → Ordering) (f : α → α) [wf : ModifyWF t cut f] : RBSet α cmp := ⟨t.1.modify cut f, wf.wf⟩ /-- The predicate asserting that the result of `alterP` is safe to construct. -/ class AlterWF (t : RBSet α cmp) (cut : α → Ordering) (f : Option α → Option α) : Prop where /-- The resulting tree is well formed. -/ wf : (t.1.alter cut f).WF cmp /-- `O(log n)`. `alterP cut f t` simultaneously handles inserting, erasing and replacing an element using a function `f : Option α → Option α`. It is passed the result of `t.findP? cut` and can either return `none` to remove the element or `some a` to replace/insert the element with `a` (which must have the same ordering properties as the original element). The element is used linearly if `t` is unshared. The `AlterWF` assumption is required because `f` may change the ordering properties of the element, which would break the invariants. -/ def alterP (t : RBSet α cmp) (cut : α → Ordering) (f : Option α → Option α) [wf : AlterWF t cut f] : RBSet α cmp := ⟨t.1.alter cut f, wf.wf⟩ /-- `O(n₂ * log (n₁ + n₂))`. Merges the maps `t₁` and `t₂`. If equal keys exist in both, the key from `t₂` is preferred. -/ def union (t₁ t₂ : RBSet α cmp) : RBSet α cmp := t₂.foldl .insert t₁ instance : Union (RBSet α cmp) := ⟨RBSet.union⟩ /-- `O(n₂ * log (n₁ + n₂))`. Merges the maps `t₁` and `t₂`. If equal keys exist in both, then use `mergeFn a₁ a₂` to produce the new merged value. -/ def mergeWith (mergeFn : α → α → α) (t₁ t₂ : RBSet α cmp) : RBSet α cmp := t₂.foldl (init := t₁) fun t₁ a₂ => t₁.insert <| match t₁.find? a₂ with | some a₁ => mergeFn a₁ a₂ | none => a₂ /-- `O(n₁ * log (n₁ + n₂))`. Intersects the maps `t₁` and `t₂` using `mergeFn a b` to produce the new value. -/ def intersectWith (cmp : α → β → Ordering) (mergeFn : α → β → γ) (t₁ : RBSet α cmpα) (t₂ : RBSet β cmpβ) : RBSet γ cmpγ := t₁.foldl (init := ∅) fun acc a => match t₂.findP? (cmp a) with | some b => acc.insert <| mergeFn a b | none => acc /-- `O(n * log n)`. Constructs the set of all elements satisfying `p`. -/ def filter (t : RBSet α cmp) (p : α → Bool) : RBSet α cmp := t.foldl (init := ∅) fun acc a => bif p a then acc.insert a else acc /-- `O(n * log n)`. Map a function on every value in the set. If the function is monotone, consider using the more efficient `RBSet.mapMonotone` instead. -/ def map (t : RBSet α cmpα) (f : α → β) : RBSet β cmpβ := t.foldl (init := ∅) fun acc a => acc.insert <| f a /-- `O(n₁ * (log n₁ + log n₂))`. Constructs the set of all elements of `t₁` that are not in `t₂`. -/ def sdiff (t₁ t₂ : RBSet α cmp) : RBSet α cmp := t₁.filter (!t₂.contains ·) instance : SDiff (Batteries.RBSet α cmp) := ⟨RBSet.sdiff⟩ end RBSet /- TODO(Leo): define dRBMap -/ /-- An `RBMap` is a self-balancing binary search tree, used to store a key-value map. The `cmp` function is the comparator that will be used for performing searches; it should satisfy the requirements of `TransCmp` for it to have sensible behavior. -/ def RBMap (α : Type u) (β : Type v) (cmp : α → α → Ordering) : Type (max u v) := RBSet (α × β) (Ordering.byKey Prod.fst cmp) /-- `O(1)`. Construct a new empty map. -/ @[inline] def mkRBMap (α : Type u) (β : Type v) (cmp : α → α → Ordering) : RBMap α β cmp := mkRBSet .. /-- `O(1)`. Construct a new empty map. -/ @[inline] def RBMap.empty {α : Type u} {β : Type v} {cmp : α → α → Ordering} : RBMap α β cmp := mkRBMap .. instance (α : Type u) (β : Type v) (cmp : α → α → Ordering) : EmptyCollection (RBMap α β cmp) := ⟨RBMap.empty⟩ instance (α : Type u) (β : Type v) (cmp : α → α → Ordering) : Inhabited (RBMap α β cmp) := ⟨∅⟩ /-- `O(1)`. Construct a new tree with one key-value pair `k, v`. -/ @[inline] def RBMap.single (k : α) (v : β) : RBMap α β cmp := RBSet.single (k, v) namespace RBMap variable {α : Type u} {β : Type v} {σ : Type w} {cmp : α → α → Ordering} /-- `O(n)`. Fold a function on the values from left to right (in increasing order). -/ @[inline] def foldl (f : σ → α → β → σ) : (init : σ) → RBMap α β cmp → σ | b, ⟨t, _⟩ => t.foldl (fun s (a, b) => f s a b) b /-- `O(n)`. Fold a function on the values from right to left (in decreasing order). -/ @[inline] def foldr (f : α → β → σ → σ) : (init : σ) → RBMap α β cmp → σ | b, ⟨t, _⟩ => t.foldr (fun (a, b) s => f a b s) b /-- `O(n)`. Fold a monadic function on the values from left to right (in increasing order). -/ @[inline] def foldlM [Monad m] (f : σ → α → β → m σ) : (init : σ) → RBMap α β cmp → m σ | b, ⟨t, _⟩ => t.foldlM (fun s (a, b) => f s a b) b /-- `O(n)`. Run monadic function `f` on each element of the tree (in increasing order). -/ @[inline] def forM [Monad m] (f : α → β → m PUnit) (t : RBMap α β cmp) : m PUnit := t.1.forM (fun (a, b) => f a b) instance : ForIn m (RBMap α β cmp) (α × β) := inferInstanceAs (ForIn _ (RBSet ..) _) instance : Std.ToStream (RBMap α β cmp) (RBNode.Stream (α × β)) := inferInstanceAs (Std.ToStream (RBSet ..) _) /-- `O(n)`. Constructs the array of keys of the map. -/ @[inline] def keysArray (t : RBMap α β cmp) : Array α := t.1.foldl (init := #[]) (·.push ·.1) /-- `O(n)`. Constructs the list of keys of the map. -/ @[inline] def keysList (t : RBMap α β cmp) : List α := t.1.foldr (init := []) (·.1 :: ·) /-- An "iterator" over the keys of the map. This is a trivial wrapper over the underlying map, but it comes with a small API to use it in a `for` loop or convert it to an array or list. -/ def Keys (α β cmp) := RBMap α β cmp /-- The keys of the map. This is an `O(1)` wrapper operation, which can be used in `for` loops or converted to an array or list. -/ @[inline] def keys (t : RBMap α β cmp) : Keys α β cmp := t @[inline, inherit_doc keysArray] def Keys.toArray := @keysArray @[inline, inherit_doc keysList] def Keys.toList := @keysList instance : CoeHead (Keys α β cmp) (Array α) := ⟨keysArray⟩ instance : CoeHead (Keys α β cmp) (List α) := ⟨keysList⟩ instance : ForIn m (Keys α β cmp) α where forIn t init f := t.val.forIn init (f ·.1) instance : ForM m (Keys α β cmp) α where forM t f := t.val.forM (f ·.1) /-- The result of `toStream` on a `Keys`. -/ def Keys.Stream (α β) := RBNode.Stream (α × β) /-- A stream over the iterator. -/ def Keys.toStream (t : Keys α β cmp) : Keys.Stream α β := t.1.toStream /-- `O(1)` amortized, `O(log n)` worst case: Get the next element from the stream. -/ def Keys.Stream.next? (t : Stream α β) : Option (α × Stream α β) := match inline (RBNode.Stream.next? t) with | none => none | some ((a, _), t) => some (a, t) instance : Std.ToStream (Keys α β cmp) (Keys.Stream α β) := ⟨Keys.toStream⟩ instance : Std.Stream (Keys.Stream α β) α := ⟨Keys.Stream.next?⟩ /-- `O(n)`. Constructs the array of values of the map. -/ @[inline] def valuesArray (t : RBMap α β cmp) : Array β := t.1.foldl (init := #[]) (·.push ·.2) /-- `O(n)`. Constructs the list of values of the map. -/ @[inline] def valuesList (t : RBMap α β cmp) : List β := t.1.foldr (init := []) (·.2 :: ·) /-- An "iterator" over the values of the map. This is a trivial wrapper over the underlying map, but it comes with a small API to use it in a `for` loop or convert it to an array or list. -/ def Values (α β cmp) := RBMap α β cmp /-- The "keys" of the map. This is an `O(1)` wrapper operation, which can be used in `for` loops or converted to an array or list. -/ @[inline] def values (t : RBMap α β cmp) : Values α β cmp := t @[inline, inherit_doc valuesArray] def Values.toArray := @valuesArray @[inline, inherit_doc valuesList] def Values.toList := @valuesList instance : CoeHead (Values α β cmp) (Array β) := ⟨valuesArray⟩ instance : CoeHead (Values α β cmp) (List β) := ⟨valuesList⟩ instance : ForIn m (Values α β cmp) β where forIn t init f := t.val.forIn init (f ·.2) instance : ForM m (Values α β cmp) β where forM t f := t.val.forM (f ·.2) /-- The result of `toStream` on a `Values`. -/ def Values.Stream (α β) := RBNode.Stream (α × β) /-- A stream over the iterator. -/ def Values.toStream (t : Values α β cmp) : Values.Stream α β := t.1.toStream /-- `O(1)` amortized, `O(log n)` worst case: Get the next element from the stream. -/ def Values.Stream.next? (t : Stream α β) : Option (β × Stream α β) := match inline (RBNode.Stream.next? t) with | none => none | some ((_, b), t) => some (b, t) instance : Std.ToStream (Values α β cmp) (Values.Stream α β) := ⟨Values.toStream⟩ instance : Std.Stream (Values.Stream α β) β := ⟨Values.Stream.next?⟩ /-- `O(1)`. Is the tree empty? -/ @[inline] def isEmpty : RBMap α β cmp → Bool := RBSet.isEmpty /-- `O(n)`. Convert the tree to a list in ascending order. -/ @[inline] def toList : RBMap α β cmp → List (α × β) := RBSet.toList /-- `O(log n)`. Returns the key-value pair `(a, b)` such that `a ≤ k` for all keys in the RBMap. -/ @[inline] protected def min? : RBMap α β cmp → Option (α × β) := RBSet.min? /-- `O(log n)`. Returns the key-value pair `(a, b)` such that `a ≥ k` for all keys in the RBMap. -/ @[inline] protected def max? : RBMap α β cmp → Option (α × β) := RBSet.max? instance [Repr α] [Repr β] : Repr (RBMap α β cmp) where reprPrec m prec := Repr.addAppParen ("RBMap.ofList " ++ repr m.toList) prec /-- `O(log n)`. Insert key-value pair `(k, v)` into the tree. -/ @[inline] def insert (t : RBMap α β cmp) (k : α) (v : β) : RBMap α β cmp := RBSet.insert t (k, v) /-- `O(log n)`. Remove an element `k` from the map. -/ @[inline] def erase (t : RBMap α β cmp) (k : α) : RBMap α β cmp := RBSet.erase t (cmp k ·.1) /-- `O(n log n)`. Build a tree from an unsorted list by inserting them one at a time. -/ @[inline] def ofList (l : List (α × β)) (cmp : α → α → Ordering) : RBMap α β cmp := RBSet.ofList l _ /-- `O(n log n)`. Build a tree from an unsorted array by inserting them one at a time. -/ @[inline] def ofArray (l : Array (α × β)) (cmp : α → α → Ordering) : RBMap α β cmp := RBSet.ofArray l _ /-- `O(log n)`. Find an entry in the tree with key equal to `k`. -/ @[inline] def findEntry? (t : RBMap α β cmp) (k : α) : Option (α × β) := t.findP? (cmp k ·.1) /-- `O(log n)`. Find the value corresponding to key `k`. -/ @[inline] def find? (t : RBMap α β cmp) (k : α) : Option β := t.findEntry? k |>.map (·.2) /-- `O(log n)`. Find the value corresponding to key `k`, or return `v₀` if it is not in the map. -/ @[inline] def findD (t : RBMap α β cmp) (k : α) (v₀ : β) : β := (t.find? k).getD v₀ /-- `O(log n)`. `lowerBound? k` retrieves the key-value pair of the largest key smaller than or equal to `k`, if it exists. -/ @[inline] def lowerBound? (t : RBMap α β cmp) (k : α) : Option (α × β) := RBSet.lowerBoundP? t (cmp k ·.1) /-- `O(log n)`. Returns true if the given key `a` is in the RBMap. -/ @[inline] def contains (t : RBMap α β cmp) (a : α) : Bool := (t.findEntry? a).isSome /-- `O(n)`. Returns true if the given predicate is true for all items in the RBMap. -/ @[inline] def all (t : RBMap α β cmp) (p : α → β → Bool) : Bool := RBSet.all t fun (a, b) => p a b /-- `O(n)`. Returns true if the given predicate is true for any item in the RBMap. -/ @[inline] def any (t : RBMap α β cmp) (p : α → β → Bool) : Bool := RBSet.any t fun (a, b) => p a b /-- Asserts that `t₁` and `t₂` have the same number of elements in the same order, and `R` holds pairwise between them. The tree structure is ignored. -/ @[inline] def all₂ (R : α × β → γ × δ → Bool) (t₁ : RBMap α β cmpα) (t₂ : RBMap γ δ cmpγ) : Bool := RBSet.all₂ R t₁ t₂ /-- Asserts that `t₁` and `t₂` have the same set of keys (up to equality). -/ @[inline] def eqKeys (t₁ : RBMap α β cmp) (t₂ : RBMap α γ cmp) : Bool := t₁.all₂ (cmp ·.1 ·.1 = .eq) t₂ /-- Returns true if `t₁` and `t₂` have the same keys and values (assuming `cmp` and `==` are compatible), ignoring the internal tree structure. -/ instance [BEq α] [BEq β] : BEq (RBMap α β cmp) := inferInstanceAs (BEq (RBSet ..)) /-- `O(n)`. The number of items in the RBMap. -/ def size : RBMap α β cmp → Nat := RBSet.size /-- `O(log n)`. Returns the minimum element of the map, or panics if the map is empty. -/ @[inline] def min! [Inhabited α] [Inhabited β] : RBMap α β cmp → α × β := RBSet.min! /-- `O(log n)`. Returns the maximum element of the map, or panics if the map is empty. -/ @[inline] def max! [Inhabited α] [Inhabited β] : RBMap α β cmp → α × β := RBSet.max! /-- Attempts to find the value with key `k : α` in `t` and panics if there is no such key. -/ @[inline] def find! [Inhabited β] (t : RBMap α β cmp) (k : α) : β := (t.find? k).getD (panic! "key is not in the map") /-- `O(n₂ * log (n₁ + n₂))`. Merges the maps `t₁` and `t₂`, if a key `a : α` exists in both, then use `mergeFn a b₁ b₂` to produce the new merged value. -/ def mergeWith (mergeFn : α → β → β → β) (t₁ t₂ : RBMap α β cmp) : RBMap α β cmp := RBSet.mergeWith (fun (_, b₁) (a, b₂) => (a, mergeFn a b₁ b₂)) t₁ t₂ /-- `O(n₁ * log (n₁ + n₂))`. Intersects the maps `t₁` and `t₂` using `mergeFn a b` to produce the new value. -/ def intersectWith (mergeFn : α → β → γ → δ) (t₁ : RBMap α β cmp) (t₂ : RBMap α γ cmp) : RBMap α δ cmp := RBSet.intersectWith (cmp ·.1 ·.1) (fun (a, b₁) (_, b₂) => (a, mergeFn a b₁ b₂)) t₁ t₂ /-- `O(n * log n)`. Constructs the set of all elements satisfying `p`. -/ def filter (t : RBMap α β cmp) (p : α → β → Bool) : RBMap α β cmp := RBSet.filter t fun (a, b) => p a b /-- `O(n₁ * (log n₁ + log n₂))`. Constructs the set of all elements of `t₁` that are not in `t₂`. -/ def sdiff (t₁ t₂ : RBMap α β cmp) : RBMap α β cmp := t₁.filter fun a _ => !t₂.contains a end RBMap end Batteries open Batteries @[inherit_doc RBMap.ofList] abbrev List.toRBMap (l : List (α × β)) (cmp : α → α → Ordering) : RBMap α β cmp := RBMap.ofList l cmp
.lake/packages/batteries/Batteries/Data/RBMap/Alter.lean
module public import Batteries.Data.RBMap.WF @[expose] public section /-! # Path operations; `modify` and `alter` This develops the necessary theorems to construct the `modify` and `alter` functions on `RBSet` using path operations for in-place modification of an `RBTree`. -/ namespace Batteries namespace RBNode open RBColor attribute [simp] Path.fill /-! ## path balance -/ /-- Asserts that property `p` holds on the root of the tree, if any. -/ def OnRoot (p : α → Prop) : RBNode α → Prop | nil => True | node _ _ x _ => p x namespace Path /-- Same as `fill` but taking its arguments in a pair for easier composition with `zoom`. -/ @[inline] def fill' : RBNode α × Path α → RBNode α := fun (t, path) => path.fill t theorem zoom_fill' (cut : α → Ordering) (t : RBNode α) (path : Path α) : fill' (zoom cut t path) = path.fill t := by induction t generalizing path with | nil => rfl | node _ _ _ _ iha ihb => unfold zoom; split <;> [apply iha; apply ihb; rfl] theorem zoom_fill (H : zoom cut t path = (t', path')) : path.fill t = path'.fill t' := (H ▸ zoom_fill' cut t path).symm variable (c₀ : RBColor) (n₀ : Nat) in /-- The balance invariant for a path. `path.Balanced c₀ n₀ c n` means that `path` is a red-black tree with balance invariant `c₀, n₀`, but it has a "hole" where a tree with balance invariant `c, n` has been removed. The defining property is `Balanced.fill`: if `path.Balanced c₀ n₀ c n` and you fill the hole with a tree satisfying `t.Balanced c n`, then `(path.fill t).Balanced c₀ n₀` . -/ protected inductive Balanced : Path α → RBColor → Nat → Prop where /-- The root of the tree is `c₀, n₀`-balanced by assumption. -/ | protected root : Path.root.Balanced c₀ n₀ /-- Descend into the left subtree of a red node. -/ | redL : Balanced y black n → parent.Balanced red n → (Path.left red parent v y).Balanced black n /-- Descend into the right subtree of a red node. -/ | redR : Balanced x black n → parent.Balanced red n → (Path.right red x v parent).Balanced black n /-- Descend into the left subtree of a black node. -/ | blackL : Balanced y c₂ n → parent.Balanced black (n + 1) → (Path.left black parent v y).Balanced c₁ n /-- Descend into the right subtree of a black node. -/ | blackR : Balanced x c₁ n → parent.Balanced black (n + 1) → (Path.right black x v parent).Balanced c₂ n /-- The defining property of a balanced path: If `path` is a `c₀,n₀` tree with a `c,n` hole, then filling the hole with a `c,n` tree yields a `c₀,n₀` tree. -/ protected theorem Balanced.fill {path : Path α} {t} : path.Balanced c₀ n₀ c n → t.Balanced c n → (path.fill t).Balanced c₀ n₀ | .root, h => h | .redL hb H, ha | .redR ha H, hb => H.fill (.red ha hb) | .blackL hb H, ha | .blackR ha H, hb => H.fill (.black ha hb) protected theorem _root_.Batteries.RBNode.Balanced.zoom : t.Balanced c n → path.Balanced c₀ n₀ c n → zoom cut t path = (t', path') → ∃ c n, t'.Balanced c n ∧ path'.Balanced c₀ n₀ c n | .nil, hp => fun e => by cases e; exact ⟨_, _, .nil, hp⟩ | .red ha hb, hp => by unfold zoom; split · exact ha.zoom (.redL hb hp) · exact hb.zoom (.redR ha hp) · intro e; cases e; exact ⟨_, _, .red ha hb, hp⟩ | .black ha hb, hp => by unfold zoom; split · exact ha.zoom (.blackL hb hp) · exact hb.zoom (.blackR ha hp) · intro e; cases e; exact ⟨_, _, .black ha hb, hp⟩ protected theorem Balanced.ins {path : Path α} (hp : path.Balanced c₀ n₀ c n) (ht : t.RedRed (c = red) n) : ∃ n, (path.ins t).Balanced black n := by induction hp generalizing t with | root => exact ht.setBlack | redL hr hp ih => match ht with | .balanced .nil => exact ih (.balanced (.red .nil hr)) | .balanced (.red ha hb) => exact ih (.redred rfl (.red ha hb) hr) | .balanced (.black ha hb) => exact ih (.balanced (.red (.black ha hb) hr)) | redR hl hp ih => match ht with | .balanced .nil => exact ih (.balanced (.red hl .nil)) | .balanced (.red ha hb) => exact ih (.redred rfl hl (.red ha hb)) | .balanced (.black ha hb) => exact ih (.balanced (.red hl (.black ha hb))) | blackL hr _hp ih => exact have ⟨c, h⟩ := ht.balance1 hr; ih (.balanced h) | blackR hl _hp ih => exact have ⟨c, h⟩ := ht.balance2 hl; ih (.balanced h) protected theorem Balanced.insertNew {path : Path α} (H : path.Balanced c n black 0) : ∃ n, (path.insertNew v).Balanced black n := H.ins (.balanced (.red .nil .nil)) protected theorem Balanced.del {path : Path α} (hp : path.Balanced c₀ n₀ c n) (ht : t.DelProp c' n) (hc : c = black → c' ≠ red) : ∃ n, (path.del t c').Balanced black n := by induction hp generalizing t c' with | root => match c', ht with | red, ⟨_, h⟩ | black, ⟨_, _, h⟩ => exact h.setBlack | @redL _ n _ _ hb hp ih => match c', n, ht with | red, _, _ => cases hc rfl rfl | black, _, ⟨_, rfl, ha⟩ => exact ih ((hb.balLeft ha).of_false nofun) nofun | @redR _ n _ _ ha hp ih => match c', n, ht with | red, _, _ => cases hc rfl rfl | black, _, ⟨_, rfl, hb⟩ => exact ih ((ha.balRight hb).of_false nofun) nofun | @blackL _ _ n _ _ _ hb hp ih => match c', n, ht with | red, _, ⟨_, ha⟩ => exact ih ⟨_, rfl, .redred ⟨⟩ ha hb⟩ nofun | black, _, ⟨_, rfl, ha⟩ => exact ih ⟨_, rfl, (hb.balLeft ha).imp fun _ => ⟨⟩⟩ nofun | @blackR _ _ n _ _ _ ha hp ih => match c', n, ht with | red, _, ⟨_, hb⟩ => exact ih ⟨_, rfl, .redred ⟨⟩ ha hb⟩ nofun | black, _, ⟨_, rfl, hb⟩ => exact ih ⟨_, rfl, (ha.balRight hb).imp fun _ => ⟨⟩⟩ nofun /-- The property of a path returned by `t.zoom cut`. Each of the parents visited along the path have the appropriate ordering relation to the cut. -/ def Zoomed (cut : α → Ordering) : Path α → Prop | .root => True | .left _ parent x _ => cut x = .lt ∧ parent.Zoomed cut | .right _ _ x parent => cut x = .gt ∧ parent.Zoomed cut theorem zoom_zoomed₂ (e : zoom cut t path = (t', path')) (hp : path.Zoomed cut) : path'.Zoomed cut := match t, e with | nil, rfl => hp | node .., e => by revert e; unfold zoom; split · next h => exact fun e => zoom_zoomed₂ e ⟨h, hp⟩ · next h => exact fun e => zoom_zoomed₂ e ⟨h, hp⟩ · intro e; cases e; exact hp /-- `path.RootOrdered cmp v` is true if `v` would be able to fit into the hole without violating the ordering invariant. -/ def RootOrdered (cmp : α → α → Ordering) : Path α → α → Prop | .root, _ => True | .left _ parent x _, v => cmpLT cmp v x ∧ parent.RootOrdered cmp v | .right _ _ x parent, v => cmpLT cmp x v ∧ parent.RootOrdered cmp v theorem _root_.Batteries.RBNode.cmpEq.RootOrdered_congr {cmp : α → α → Ordering} (h : cmpEq cmp a b) : ∀ {t : Path α}, t.RootOrdered cmp a ↔ t.RootOrdered cmp b | .root => .rfl | .left .. => and_congr h.lt_congr_left h.RootOrdered_congr | .right .. => and_congr h.lt_congr_right h.RootOrdered_congr theorem Zoomed.toRootOrdered {cmp} : ∀ {path : Path α}, path.Zoomed (cmp v) → path.RootOrdered cmp v | .root, h => h | .left .., ⟨h, hp⟩ => ⟨⟨h⟩, hp.toRootOrdered⟩ | .right .., ⟨h, hp⟩ => ⟨⟨Std.OrientedCmp.gt_iff_lt.1 h⟩, hp.toRootOrdered⟩ /-- The ordering invariant for a `Path`. -/ def Ordered (cmp : α → α → Ordering) : Path α → Prop | .root => True | .left _ parent x b => parent.Ordered cmp ∧ b.All (cmpLT cmp x ·) ∧ parent.RootOrdered cmp x ∧ b.All (parent.RootOrdered cmp) ∧ b.Ordered cmp | .right _ a x parent => parent.Ordered cmp ∧ a.All (cmpLT cmp · x) ∧ parent.RootOrdered cmp x ∧ a.All (parent.RootOrdered cmp) ∧ a.Ordered cmp protected theorem Ordered.fill : ∀ {path : Path α} {t}, (path.fill t).Ordered cmp ↔ path.Ordered cmp ∧ t.Ordered cmp ∧ t.All (path.RootOrdered cmp) | .root, _ => ⟨fun H => ⟨⟨⟩, H, .trivial ⟨⟩⟩, (·.2.1)⟩ | .left .., _ => by simp [Ordered.fill, RBNode.Ordered, Ordered, RootOrdered, All_and] exact ⟨ fun ⟨hp, ⟨ax, xb, ha, hb⟩, ⟨xp, ap, bp⟩⟩ => ⟨⟨hp, xb, xp, bp, hb⟩, ha, ⟨ax, ap⟩⟩, fun ⟨⟨hp, xb, xp, bp, hb⟩, ha, ⟨ax, ap⟩⟩ => ⟨hp, ⟨ax, xb, ha, hb⟩, ⟨xp, ap, bp⟩⟩⟩ | .right .., _ => by simp [Ordered.fill, RBNode.Ordered, Ordered, RootOrdered, All_and] exact ⟨ fun ⟨hp, ⟨ax, xb, ha, hb⟩, ⟨xp, ap, bp⟩⟩ => ⟨⟨hp, ax, xp, ap, ha⟩, hb, ⟨xb, bp⟩⟩, fun ⟨⟨hp, ax, xp, ap, ha⟩, hb, ⟨xb, bp⟩⟩ => ⟨hp, ⟨ax, xb, ha, hb⟩, ⟨xp, ap, bp⟩⟩⟩ theorem _root_.Batteries.RBNode.Ordered.zoom' {t : RBNode α} {path : Path α} (ht : t.Ordered cmp) (hp : path.Ordered cmp) (tp : t.All (path.RootOrdered cmp)) (pz : path.Zoomed cut) (eq : t.zoom cut path = (t', path')) : t'.Ordered cmp ∧ path'.Ordered cmp ∧ t'.All (path'.RootOrdered cmp) ∧ path'.Zoomed cut := have ⟨hp', ht', tp'⟩ := Ordered.fill.1 <| zoom_fill eq ▸ Ordered.fill.2 ⟨hp, ht, tp⟩ ⟨ht', hp', tp', zoom_zoomed₂ eq pz⟩ theorem _root_.Batteries.RBNode.Ordered.zoom {t : RBNode α} (ht : t.Ordered cmp) (eq : t.zoom cut = (t', path')) : t'.Ordered cmp ∧ path'.Ordered cmp ∧ t'.All (path'.RootOrdered cmp) ∧ path'.Zoomed cut := ht.zoom' (path := .root) ⟨⟩ (.trivial ⟨⟩) ⟨⟩ eq theorem Ordered.ins : ∀ {path : Path α} {t : RBNode α}, t.Ordered cmp → path.Ordered cmp → t.All (path.RootOrdered cmp) → (path.ins t).Ordered cmp | .root, _, ht, _, _ => Ordered.setBlack.2 ht | .left red parent x b, a, ha, ⟨hp, xb, xp, bp, hb⟩, H => by unfold Path.ins have ⟨ax, ap⟩ := All_and.1 H exact hp.ins ⟨ax, xb, ha, hb⟩ ⟨xp, ap, bp⟩ | .right red a x parent, b, hb, ⟨hp, ax, xp, ap, ha⟩, H => by unfold Path.ins have ⟨xb, bp⟩ := All_and.1 H exact hp.ins ⟨ax, xb, ha, hb⟩ ⟨xp, ap, bp⟩ | .left black parent x b, a, ha, ⟨hp, xb, xp, bp, hb⟩, H => by unfold Path.ins have ⟨ax, ap⟩ := All_and.1 H exact hp.ins (ha.balance1 ax xb hb) (balance1_All.2 ⟨xp, ap, bp⟩) | .right black a x parent, b, hb, ⟨hp, ax, xp, ap, ha⟩, H => by unfold Path.ins have ⟨xb, bp⟩ := All_and.1 H exact hp.ins (ha.balance2 ax xb hb) (balance2_All.2 ⟨xp, ap, bp⟩) theorem Ordered.insertNew {path : Path α} (hp : path.Ordered cmp) (vp : path.RootOrdered cmp v) : (path.insertNew v).Ordered cmp := hp.ins ⟨⟨⟩, ⟨⟩, ⟨⟩, ⟨⟩⟩ ⟨vp, ⟨⟩, ⟨⟩⟩ theorem Ordered.del : ∀ {path : Path α} {t : RBNode α} {c}, t.Ordered cmp → path.Ordered cmp → t.All (path.RootOrdered cmp) → (path.del t c).Ordered cmp | .root, _, _, ht, _, _ => Ordered.setBlack.2 ht | .left _ parent x b, a, red, ha, ⟨hp, xb, xp, bp, hb⟩, H => by unfold Path.del have ⟨ax, ap⟩ := All_and.1 H exact hp.del ⟨ax, xb, ha, hb⟩ ⟨xp, ap, bp⟩ | .right _ a x parent, b, red, hb, ⟨hp, ax, xp, ap, ha⟩, H => by unfold Path.del have ⟨xb, bp⟩ := All_and.1 H exact hp.del ⟨ax, xb, ha, hb⟩ ⟨xp, ap, bp⟩ | .left _ parent x b, a, black, ha, ⟨hp, xb, xp, bp, hb⟩, H => by unfold Path.del have ⟨ax, ap⟩ := All_and.1 H exact hp.del (ha.balLeft ax xb hb) (ap.balLeft xp bp) | .right _ a x parent, b, black, hb, ⟨hp, ax, xp, ap, ha⟩, H => by unfold Path.del have ⟨xb, bp⟩ := All_and.1 H exact hp.del (ha.balRight ax xb hb) (ap.balRight xp bp) end Path /-! ## alter -/ /-- The `alter` function preserves the ordering invariants. -/ protected theorem Ordered.alter {t : RBNode α} (H : ∀ {x t' p}, t.zoom cut = (t', p) → f t'.root? = some x → p.RootOrdered cmp x ∧ t'.OnRoot (cmpEq cmp x)) (h : t.Ordered cmp) : (alter cut f t).Ordered cmp := by simp [alter]; split · next path eq => have ⟨_, hp, _, _⟩ := h.zoom eq; split · exact h · next hf => exact hp.insertNew (H eq hf).1 · next path eq => have ⟨⟨ax, xb, ha, hb⟩, hp, ⟨_, ap, bp⟩, _⟩ := h.zoom eq; split · exact hp.del (ha.append ax xb hb) (ap.append bp) · next hf => have ⟨yp, xy⟩ := H eq hf apply Path.Ordered.fill.2 exact ⟨hp, ⟨ax.imp xy.lt_congr_right.2, xb.imp xy.lt_congr_left.2, ha, hb⟩, yp, ap, bp⟩ /-- The `alter` function preserves the balance invariants. -/ protected theorem Balanced.alter {t : RBNode α} (h : t.Balanced c n) : ∃ c n, (t.alter cut f).Balanced c n := by simp [alter]; split · next path eq => split · exact ⟨_, _, h⟩ · have ⟨_, _, .nil, h⟩ := h.zoom .root eq exact ⟨_, h.insertNew⟩ · next path eq => have ⟨_, _, h, hp⟩ := h.zoom .root eq split · match h with | .red ha hb => exact ⟨_, hp.del ((ha.append hb).of_false (· rfl rfl)) nofun⟩ | .black ha hb => exact ⟨_, hp.del ⟨_, rfl, (ha.append hb).imp fun _ => ⟨⟩⟩ nofun⟩ · match h with | .red ha hb => exact ⟨_, _, hp.fill (.red ha hb)⟩ | .black ha hb => exact ⟨_, _, hp.fill (.black ha hb)⟩ theorem modify_eq_alter (t : RBNode α) : t.modify cut f = t.alter cut (.map f) := by simp [modify, alter] /-- The `modify` function preserves the ordering invariants. -/ protected theorem Ordered.modify {t : RBNode α} (H : (t.zoom cut).1.OnRoot fun x => cmpEq cmp (f x) x) (h : t.Ordered cmp) : (modify cut f t).Ordered cmp := modify_eq_alter _ ▸ h.alter @fun | _, .node .., _, eq, rfl => by rw [eq] at H; exact ⟨H.RootOrdered_congr.2 (h.zoom eq).2.2.1.1, H⟩ /-- The `modify` function preserves the balance invariants. -/ protected theorem Balanced.modify {t : RBNode α} (h : t.Balanced c n) : ∃ c n, (t.modify cut f).Balanced c n := modify_eq_alter _ ▸ h.alter theorem WF.alter {t : RBNode α} (H : ∀ {x t' p}, t.zoom cut = (t', p) → f t'.root? = some x → p.RootOrdered cmp x ∧ t'.OnRoot (cmpEq cmp x)) (h : WF cmp t) : WF cmp (alter cut f t) := let ⟨h₁, _, _, h₂⟩ := h.out; WF_iff.2 ⟨h₁.alter H, h₂.alter⟩ theorem WF.modify {t : RBNode α} (H : (t.zoom cut).1.OnRoot fun x => cmpEq cmp (f x) x) (h : WF cmp t) : WF cmp (t.modify cut f) := let ⟨h₁, _, _, h₂⟩ := h.out; WF_iff.2 ⟨h₁.modify H, h₂.modify⟩ theorem find?_eq_zoom : ∀ {t : RBNode α} (p := .root), t.find? cut = (t.zoom cut p).1.root? | .nil, _ => rfl | .node .., _ => by unfold find? zoom; split <;> [apply find?_eq_zoom; apply find?_eq_zoom; rfl] end RBNode namespace RBSet open RBNode /-- A sufficient condition for `ModifyWF` is that the new element compares equal to the original. -/ theorem ModifyWF.of_eq {t : RBSet α cmp} (H : ∀ {x}, RBNode.find? cut t.val = some x → cmpEq cmp (f x) x) : ModifyWF t cut f := by refine ⟨.modify ?_ t.2⟩ revert H; rw [find?_eq_zoom] cases (t.1.zoom cut).1 <;> intro H <;> [trivial; exact H rfl] end RBSet namespace RBMap /-- `O(log n)`. In-place replace the corresponding to key `k`. This takes the element out of the tree while `f` runs, so it uses the element linearly if `t` is unshared. -/ def modify (t : RBMap α β cmp) (k : α) (f : β → β) : RBMap α β cmp := @RBSet.modifyP _ _ t (cmp k ·.1) (fun (a, b) => (a, f b)) (.of_eq fun _ => ⟨Std.ReflCmp.compare_self (cmp := Ordering.byKey Prod.fst cmp)⟩) /-- Auxiliary definition for `alter`. -/ def alter.adapt (k : α) (f : Option β → Option β) : Option (α × β) → Option (α × β) | none => match f none with | none => none | some v => some (k, v) | some (k', v') => match f (some v') with | none => none | some v => some (k', v) /-- `O(log n)`. `alterP cut f t` simultaneously handles inserting, erasing and replacing an element using a function `f : Option α → Option α`. It is passed the result of `t.findP? cut` and can either return `none` to remove the element or `some a` to replace/insert the element with `a` (which must have the same ordering properties as the original element). The element is used linearly if `t` is unshared. The `AlterWF` assumption is required because `f` may change the ordering properties of the element, which would break the invariants. -/ @[specialize] def alter (t : RBMap α β cmp) (k : α) (f : Option β → Option β) : RBMap α β cmp := by refine @RBSet.alterP _ _ t (cmp k ·.1) (alter.adapt k f) ⟨.alter (@fun _ t' p eq => ?_) t.2⟩ cases t' <;> simp [alter.adapt, RBNode.root?] <;> split <;> intro h <;> cases h · exact ⟨(t.2.out.1.zoom eq).2.2.2.toRootOrdered, ⟨⟩⟩ · refine ⟨(?a).RootOrdered_congr.2 (t.2.out.1.zoom eq).2.2.1.1, ?a⟩ exact ⟨Std.ReflCmp.compare_self (cmp := Ordering.byKey Prod.fst cmp)⟩ end RBMap
.lake/packages/batteries/Batteries/Data/RBMap/WF.lean
module public import Batteries.Data.RBMap.Basic public import Batteries.Tactic.SeqFocus @[expose] public section /-! # Lemmas for Red-black trees The main theorem in this file is `WF_def`, which shows that the `RBNode.WF.mk` constructor subsumes the others, by showing that `insert` and `erase` satisfy the red-black invariants. -/ namespace Batteries namespace RBNode open RBColor attribute [simp] All theorem All.trivial (H : ∀ {x : α}, p x) : ∀ {t : RBNode α}, t.All p | nil => _root_.trivial | node .. => ⟨H, All.trivial H, All.trivial H⟩ theorem All_and {t : RBNode α} : t.All (fun a => p a ∧ q a) ↔ t.All p ∧ t.All q := by induction t <;> simp [*, and_assoc, and_left_comm] protected theorem cmpLT.flip (h₁ : cmpLT cmp x y) : cmpLT (flip cmp) y x := ⟨have : Std.TransCmp cmp := inferInstanceAs (Std.TransCmp (flip (flip cmp))); h₁.1⟩ theorem cmpLT.trans (h₁ : cmpLT cmp x y) (h₂ : cmpLT cmp y z) : cmpLT cmp x z := ⟨Std.TransCmp.lt_trans h₁.1 h₂.1⟩ theorem cmpLT.trans_l {cmp x y} (H : cmpLT cmp x y) {t : RBNode α} (h : t.All (cmpLT cmp y ·)) : t.All (cmpLT cmp x ·) := h.imp fun h => H.trans h theorem cmpLT.trans_r {cmp x y} (H : cmpLT cmp x y) {a : RBNode α} (h : a.All (cmpLT cmp · x)) : a.All (cmpLT cmp · y) := h.imp fun h => h.trans H theorem cmpEq.lt_congr_left (H : cmpEq cmp x y) : cmpLT cmp x z ↔ cmpLT cmp y z := ⟨fun ⟨h⟩ => ⟨Std.TransCmp.congr_left H.1 ▸ h⟩, fun ⟨h⟩ => ⟨Std.TransCmp.congr_left H.1 ▸ h⟩⟩ theorem cmpEq.lt_congr_right (H : cmpEq cmp y z) : cmpLT cmp x y ↔ cmpLT cmp x z := ⟨fun ⟨h⟩ => ⟨Std.TransCmp.congr_right H.1 ▸ h⟩, fun ⟨h⟩ => ⟨Std.TransCmp.congr_right H.1 ▸ h⟩⟩ @[simp] theorem reverse_reverse (t : RBNode α) : t.reverse.reverse = t := by induction t <;> simp [*] theorem reverse_eq_iff {t t' : RBNode α} : t.reverse = t' ↔ t = t'.reverse := by constructor <;> rintro rfl <;> simp @[simp] theorem reverse_balance1 (l : RBNode α) (v : α) (r : RBNode α) : (balance1 l v r).reverse = balance2 r.reverse v l.reverse := by unfold balance1 balance2; split <;> simp · rw [balance2.match_1.eq_2]; simp [reverse_eq_iff]; intros; solve_by_elim · rw [balance2.match_1.eq_3] <;> (simp [reverse_eq_iff]; intros; solve_by_elim) @[simp] theorem reverse_balance2 (l : RBNode α) (v : α) (r : RBNode α) : (balance2 l v r).reverse = balance1 r.reverse v l.reverse := by refine Eq.trans ?_ (reverse_reverse _); rw [reverse_balance1]; simp @[simp] theorem All.reverse {t : RBNode α} : t.reverse.All p ↔ t.All p := by induction t <;> simp [*, and_comm] /-- The `reverse` function reverses the ordering invariants. -/ protected theorem Ordered.reverse : ∀ {t : RBNode α}, t.Ordered cmp → t.reverse.Ordered (flip cmp) | .nil, _ => ⟨⟩ | .node .., ⟨lv, vr, hl, hr⟩ => ⟨(All.reverse.2 vr).imp cmpLT.flip, (All.reverse.2 lv).imp cmpLT.flip, hr.reverse, hl.reverse⟩ protected theorem Balanced.reverse {t : RBNode α} : t.Balanced c n → t.reverse.Balanced c n | .nil => .nil | .black hl hr => .black hr.reverse hl.reverse | .red hl hr => .red hr.reverse hl.reverse /-- The `balance1` function preserves the ordering invariants. -/ protected theorem Ordered.balance1 {l : RBNode α} {v : α} {r : RBNode α} (lv : l.All (cmpLT cmp · v)) (vr : r.All (cmpLT cmp v ·)) (hl : l.Ordered cmp) (hr : r.Ordered cmp) : (balance1 l v r).Ordered cmp := by unfold balance1; split · next a x b y c => have ⟨yv, _, cv⟩ := lv; have ⟨xy, yc, hx, hc⟩ := hl exact ⟨xy, ⟨yv, yc, yv.trans_l vr⟩, hx, cv, vr, hc, hr⟩ · next a x b y c _ => have ⟨_, _, yv, _, cv⟩ := lv; have ⟨ax, ⟨xy, xb, _⟩, ha, by_, yc, hb, hc⟩ := hl exact ⟨⟨xy, xy.trans_r ax, by_⟩, ⟨yv, yc, yv.trans_l vr⟩, ⟨ax, xb, ha, hb⟩, cv, vr, hc, hr⟩ · exact ⟨lv, vr, hl, hr⟩ @[simp] theorem balance1_All {l : RBNode α} {v : α} {r : RBNode α} : (balance1 l v r).All p ↔ p v ∧ l.All p ∧ r.All p := by unfold balance1; split <;> simp [and_assoc, and_left_comm] /-- The `balance2` function preserves the ordering invariants. -/ protected theorem Ordered.balance2 {l : RBNode α} {v : α} {r : RBNode α} (lv : l.All (cmpLT cmp · v)) (vr : r.All (cmpLT cmp v ·)) (hl : l.Ordered cmp) (hr : r.Ordered cmp) : (balance2 l v r).Ordered cmp := by rw [← reverse_reverse (balance2 ..), reverse_balance2] exact .reverse <| hr.reverse.balance1 ((All.reverse.2 vr).imp cmpLT.flip) ((All.reverse.2 lv).imp cmpLT.flip) hl.reverse @[simp] theorem balance2_All {l : RBNode α} {v : α} {r : RBNode α} : (balance2 l v r).All p ↔ p v ∧ l.All p ∧ r.All p := by unfold balance2; split <;> simp [and_assoc, and_left_comm] @[simp] theorem reverse_setBlack {t : RBNode α} : (setBlack t).reverse = setBlack t.reverse := by unfold setBlack; split <;> simp protected theorem Ordered.setBlack {t : RBNode α} : (setBlack t).Ordered cmp ↔ t.Ordered cmp := by unfold setBlack; split <;> simp [Ordered] protected theorem Balanced.setBlack : t.Balanced c n → ∃ n', (setBlack t).Balanced black n' | .nil => ⟨_, .nil⟩ | .black hl hr | .red hl hr => ⟨_, hl.black hr⟩ theorem setBlack_idem {t : RBNode α} : t.setBlack.setBlack = t.setBlack := by cases t <;> rfl @[simp] theorem reverse_ins [inst : Std.OrientedCmp (α := α) cmp] {t : RBNode α} : (ins cmp x t).reverse = ins (flip cmp) x t.reverse := by induction t with | nil => simp [ins] | node c a y b iha ihb => cases c <;> (simp only [ins, Std.OrientedCmp.eq_swap (cmp := cmp) (a := x) (b := y)]; split) <;> simp_all [ins, reverse, flip] protected theorem All.ins {x : α} {t : RBNode α} (h₁ : p x) (h₂ : t.All p) : (ins cmp x t).All p := by induction t <;> unfold ins <;> try simp [*] split <;> cases ‹_=_› <;> split <;> simp at h₂ <;> simp [*] /-- The `ins` function preserves the ordering invariants. -/ protected theorem Ordered.ins : ∀ {t : RBNode α}, t.Ordered cmp → (ins cmp x t).Ordered cmp | nil, _ => ⟨⟨⟩, ⟨⟩, ⟨⟩, ⟨⟩⟩ | node red a y b, ⟨ay, yb, ha, hb⟩ => by unfold ins; split · next h => exact ⟨ay.ins ⟨h⟩, yb, ha.ins, hb⟩ · next h => exact ⟨ay, yb.ins ⟨Std.OrientedCmp.gt_iff_lt.1 h⟩, ha, hb.ins⟩ · next h => exact (⟨ ay.imp fun ⟨h'⟩ => ⟨(Std.TransCmp.congr_right h).trans h'⟩, yb.imp fun ⟨h'⟩ => ⟨(Std.TransCmp.congr_left h).trans h'⟩, ha, hb⟩) | node black a y b, ⟨ay, yb, ha, hb⟩ => by unfold ins; split · next h => exact ha.ins.balance1 (ay.ins ⟨h⟩) yb hb · next h => exact ha.balance2 ay (yb.ins ⟨Std.OrientedCmp.gt_iff_lt.1 h⟩) hb.ins · next h => exact (⟨ ay.imp fun ⟨h'⟩ => ⟨(Std.TransCmp.congr_right h).trans h'⟩, yb.imp fun ⟨h'⟩ => ⟨(Std.TransCmp.congr_left h).trans h'⟩, ha, hb⟩) @[simp] theorem isRed_reverse {t : RBNode α} : t.reverse.isRed = t.isRed := by cases t <;> simp [isRed] @[simp] theorem reverse_insert [inst : Std.OrientedCmp (α := α) cmp] {t : RBNode α} : (insert cmp t x).reverse = insert (flip cmp) t.reverse x := by simp [insert]; split <;> simp theorem insert_setBlack {t : RBNode α} : (t.insert cmp v).setBlack = (t.ins cmp v).setBlack := by unfold insert; split <;> simp [setBlack_idem] /-- The `insert` function preserves the ordering invariants. -/ protected theorem Ordered.insert (h : t.Ordered cmp) : (insert cmp t v).Ordered cmp := by unfold RBNode.insert; split <;> simp [Ordered.setBlack, h.ins (x := v)] /-- The red-red invariant is a weakening of the red-black balance invariant which allows the root to be red with red children, but does not allow any other violations. It occurs as a temporary condition in the `insert` and `erase` functions. The `p` parameter allows the `.redred` case to be dependent on an additional condition. If it is false, then this is equivalent to the usual red-black invariant. -/ inductive RedRed (p : Prop) : RBNode α → Nat → Prop where /-- A balanced tree has the red-red invariant. -/ | balanced : Balanced t c n → RedRed p t n /-- A red node with balanced red children has the red-red invariant (if `p` is true). -/ | redred : p → Balanced a c₁ n → Balanced b c₂ n → RedRed p (node red a x b) n /-- When `p` is false, the red-red case is impossible so the tree is balanced. -/ protected theorem RedRed.of_false (h : ¬p) : RedRed p t n → ∃ c, Balanced t c n | .balanced h => ⟨_, h⟩ | .redred hp .. => nomatch h hp /-- A `red` node with the red-red invariant has balanced children. -/ protected theorem RedRed.of_red : RedRed p (node red a x b) n → ∃ c₁ c₂, Balanced a c₁ n ∧ Balanced b c₂ n | .balanced (.red ha hb) | .redred _ ha hb => ⟨_, _, ha, hb⟩ /-- The red-red invariant is monotonic in `p`. -/ protected theorem RedRed.imp (h : p → q) : RedRed p t n → RedRed q t n | .balanced h => .balanced h | .redred hp ha hb => .redred (h hp) ha hb protected theorem RedRed.reverse : RedRed p t n → RedRed p t.reverse n | .balanced h => .balanced h.reverse | .redred hp ha hb => .redred hp hb.reverse ha.reverse /-- If `t` has the red-red invariant, then setting the root to black yields a balanced tree. -/ protected theorem RedRed.setBlack : t.RedRed p n → ∃ n', (setBlack t).Balanced black n' | .balanced h => h.setBlack | .redred _ hl hr => ⟨_, hl.black hr⟩ /-- The `balance1` function repairs the balance invariant when the first argument is red-red. -/ protected theorem RedRed.balance1 {l : RBNode α} {v : α} {r : RBNode α} (hl : l.RedRed p n) (hr : r.Balanced c n) : ∃ c, (balance1 l v r).Balanced c (n + 1) := by unfold balance1; split · have .redred _ (.red ha hb) hc := hl; exact ⟨_, .red (.black ha hb) (.black hc hr)⟩ · have .redred _ ha (.red hb hc) := hl; exact ⟨_, .red (.black ha hb) (.black hc hr)⟩ · next H1 H2 => match hl with | .balanced hl => exact ⟨_, .black hl hr⟩ | .redred _ (c₁ := black) (c₂ := black) ha hb => exact ⟨_, .black (.red ha hb) hr⟩ | .redred _ (c₁ := red) (.red ..) _ => cases H1 _ _ _ _ _ rfl | .redred _ (c₂ := red) _ (.red ..) => cases H2 _ _ _ _ _ rfl /-- The `balance2` function repairs the balance invariant when the second argument is red-red. -/ protected theorem RedRed.balance2 {l : RBNode α} {v : α} {r : RBNode α} (hl : l.Balanced c n) (hr : r.RedRed p n) : ∃ c, (balance2 l v r).Balanced c (n + 1) := (hr.reverse.balance1 hl.reverse (v := v)).imp fun _ h => by simpa using h.reverse /-- The `balance1` function does nothing if the first argument is already balanced. -/ theorem balance1_eq {l : RBNode α} {v : α} {r : RBNode α} (hl : l.Balanced c n) : balance1 l v r = node black l v r := by unfold balance1; split <;> first | rfl | nomatch hl /-- The `balance2` function does nothing if the second argument is already balanced. -/ theorem balance2_eq {l : RBNode α} {v : α} {r : RBNode α} (hr : r.Balanced c n) : balance2 l v r = node black l v r := (reverse_reverse _).symm.trans <| by simp [balance1_eq hr.reverse] /-! ## insert -/ /-- The balance invariant of the `ins` function. The result of inserting into the tree either yields a balanced tree, or a tree which is almost balanced except that it has a red-red violation at the root. -/ protected theorem Balanced.ins (cmp v) {t : RBNode α} (h : t.Balanced c n) : (ins cmp v t).RedRed (t.isRed = red) n := by induction h with | nil => exact .balanced (.red .nil .nil) | @red a n b x hl hr ihl ihr => unfold ins; split · match ins cmp v a, ihl with | _, .balanced .nil => exact .balanced (.red .nil hr) | _, .balanced (.red ha hb) => exact .redred rfl (.red ha hb) hr | _, .balanced (.black ha hb) => exact .balanced (.red (.black ha hb) hr) | _, .redred h .. => cases hl <;> cases h · match ins cmp v b, ihr with | _, .balanced .nil => exact .balanced (.red hl .nil) | _, .balanced (.red ha hb) => exact .redred rfl hl (.red ha hb) | _, .balanced (.black ha hb) => exact .balanced (.red hl (.black ha hb)) | _, .redred h .. => cases hr <;> cases h · exact .balanced (.red hl hr) | @black a ca n b cb x hl hr ihl ihr => unfold ins; split · exact have ⟨c, h⟩ := ihl.balance1 hr; .balanced h · exact have ⟨c, h⟩ := ihr.balance2 hl; .balanced h · exact .balanced (.black hl hr) /-- The `insert` function is balanced if the input is balanced. (We lose track of both the color and the black-height of the result, so this is only suitable for use on the root of the tree.) -/ theorem Balanced.insert {t : RBNode α} (h : t.Balanced c n) : ∃ c' n', (insert cmp t v).Balanced c' n' := by unfold RBNode.insert match ins cmp v t, h.ins cmp v with | _, .balanced h => split <;> [exact ⟨_, h.setBlack⟩; exact ⟨_, _, h⟩] | _, .redred _ ha hb => have .node red .. := t; exact ⟨_, _, .black ha hb⟩ @[simp] theorem reverse_setRed {t : RBNode α} : (setRed t).reverse = setRed t.reverse := by unfold setRed; split <;> simp protected theorem All.setRed {t : RBNode α} (h : t.All p) : (setRed t).All p := by unfold setRed; split <;> simp_all /-- The `setRed` function preserves the ordering invariants. -/ protected theorem Ordered.setRed {t : RBNode α} : (setRed t).Ordered cmp ↔ t.Ordered cmp := by unfold setRed; split <;> simp [Ordered] @[simp] theorem reverse_balLeft (l : RBNode α) (v : α) (r : RBNode α) : (balLeft l v r).reverse = balRight r.reverse v l.reverse := by suffices ∀ r' l', r' = r.reverse → l' = l.reverse → (balLeft l v r).reverse = balRight r' v l' from this _ _ rfl rfl intros r' l' hr hl fun_cases balLeft l v r <;> fun_cases balRight r' v l' <;> grind [reverse, reverse_reverse, reverse_balance2, reverse_setRed] @[simp] theorem reverse_balRight (l : RBNode α) (v : α) (r : RBNode α) : (balRight l v r).reverse = balLeft r.reverse v l.reverse := by rw [← reverse_reverse (balLeft ..)]; simp protected theorem All.balLeft (hl : l.All p) (hv : p v) (hr : r.All p) : (balLeft l v r).All p := by unfold balLeft; split <;> (try simp_all); split <;> simp_all [All.setRed] /-- The `balLeft` function preserves the ordering invariants. -/ protected theorem Ordered.balLeft {l : RBNode α} {v : α} {r : RBNode α} (lv : l.All (cmpLT cmp · v)) (vr : r.All (cmpLT cmp v ·)) (hl : l.Ordered cmp) (hr : r.Ordered cmp) : (balLeft l v r).Ordered cmp := by unfold balLeft; split · exact ⟨lv, vr, hl, hr⟩ split · exact hl.balance2 lv vr hr · have ⟨vy, va, _⟩ := vr.2.1; have ⟨⟨yz, _, bz⟩, zc, ⟨ay, yb, ha, hb⟩, hc⟩ := hr exact ⟨⟨vy, vy.trans_r lv, ay⟩, balance2_All.2 ⟨yz, yb, (yz.trans_l zc).setRed⟩, ⟨lv, va, hl, ha⟩, hb.balance2 bz zc.setRed (Ordered.setRed.2 hc)⟩ · exact ⟨lv, vr, hl, hr⟩ /-- The balancing properties of the `balLeft` function. -/ protected theorem Balanced.balLeft (hl : l.RedRed True n) (hr : r.Balanced cr (n + 1)) : (balLeft l v r).RedRed (cr = red) (n + 1) := by unfold balLeft; split · next a x b => exact let ⟨ca, cb, ha, hb⟩ := hl.of_red match cr with | red => .redred rfl (.black ha hb) hr | black => .balanced (.red (.black ha hb) hr) · next H => exact match hl with | .redred .. => nomatch H _ _ _ rfl | .balanced hl => match hr with | .black ha hb => let ⟨c, h⟩ := RedRed.balance2 hl (.redred trivial ha hb); .balanced h | .red (.black ha hb) (.black hc hd) => let ⟨c, h⟩ := RedRed.balance2 hb (.redred trivial hc hd); .redred rfl (.black hl ha) h protected theorem All.balRight (hl : l.All p) (hv : p v) (hr : r.All p) : (balRight l v r).All p := All.reverse.1 <| reverse_balRight .. ▸ (All.reverse.2 hr).balLeft hv (All.reverse.2 hl) /-- The `balRight` function preserves the ordering invariants. -/ protected theorem Ordered.balRight {l : RBNode α} {v : α} {r : RBNode α} (lv : l.All (cmpLT cmp · v)) (vr : r.All (cmpLT cmp v ·)) (hl : l.Ordered cmp) (hr : r.Ordered cmp) : (balRight l v r).Ordered cmp := by rw [← reverse_reverse (balRight ..), reverse_balRight] exact .reverse <| hr.reverse.balLeft ((All.reverse.2 vr).imp cmpLT.flip) ((All.reverse.2 lv).imp cmpLT.flip) hl.reverse /-- The balancing properties of the `balRight` function. -/ protected theorem Balanced.balRight (hl : l.Balanced cl (n + 1)) (hr : r.RedRed True n) : (balRight l v r).RedRed (cl = red) (n + 1) := by rw [← reverse_reverse (balRight ..), reverse_balRight] exact .reverse <| hl.reverse.balLeft hr.reverse -- note: reverse_append is false! protected theorem All.append (hl : l.All p) (hr : r.All p) : (append l r).All p := by unfold append; split <;> try simp [*] · have ⟨hx, ha, hb⟩ := hl; have ⟨hy, hc, hd⟩ := hr have := hb.append hc; split <;> simp_all · have ⟨hx, ha, hb⟩ := hl; have ⟨hy, hc, hd⟩ := hr have := hb.append hc; split <;> simp_all [All.balLeft] · simp_all [hl.append hr.2.1] · simp_all [hl.2.2.append hr] termination_by l.size + r.size /-- The `append` function preserves the ordering invariants. -/ protected theorem Ordered.append {l : RBNode α} {v : α} {r : RBNode α} (lv : l.All (cmpLT cmp · v)) (vr : r.All (cmpLT cmp v ·)) (hl : l.Ordered cmp) (hr : r.Ordered cmp) : (append l r).Ordered cmp := by unfold append; split · exact hr · exact hl · have ⟨xv, _, bv⟩ := lv; have ⟨ax, xb, ha, hb⟩ := hl have ⟨vy, vc, _⟩ := vr; have ⟨cy, yd, hc, hd⟩ := hr have : _ ∧ _ ∧ _ := ⟨hb.append bv vc hc, xb.append (xv.trans_l vc), (vy.trans_r bv).append cy⟩ split · next H => have ⟨⟨b'z, c'z, hb', hc'⟩, ⟨xz, xb', _⟩, zy, _, c'y⟩ := H ▸ this have az := xz.trans_r ax; have zd := zy.trans_l yd exact ⟨⟨xz, az, b'z⟩, ⟨zy, c'z, zd⟩, ⟨ax, xb', ha, hb'⟩, c'y, yd, hc', hd⟩ · have ⟨hbc, xbc, bcy⟩ := this; have xy := xv.trans vy exact ⟨ax, ⟨xy, xbc, xy.trans_l yd⟩, ha, bcy, yd, hbc, hd⟩ · have ⟨xv, _, bv⟩ := lv; have ⟨ax, xb, ha, hb⟩ := hl have ⟨vy, vc, _⟩ := vr; have ⟨cy, yd, hc, hd⟩ := hr have : _ ∧ _ ∧ _ := ⟨hb.append bv vc hc, xb.append (xv.trans_l vc), (vy.trans_r bv).append cy⟩ split · next H => have ⟨⟨b'z, c'z, hb', hc'⟩, ⟨xz, xb', _⟩, zy, _, c'y⟩ := H ▸ this have az := xz.trans_r ax; have zd := zy.trans_l yd exact ⟨⟨xz, az, b'z⟩, ⟨zy, c'z, zd⟩, ⟨ax, xb', ha, hb'⟩, c'y, yd, hc', hd⟩ · have ⟨hbc, xbc, bcy⟩ := this; have xy := xv.trans vy exact ha.balLeft ax ⟨xy, xbc, xy.trans_l yd⟩ ⟨bcy, yd, hbc, hd⟩ · have ⟨vx, vb, _⟩ := vr; have ⟨bx, yc, hb, hc⟩ := hr exact ⟨(vx.trans_r lv).append bx, yc, hl.append lv vb hb, hc⟩ · have ⟨xv, _, bv⟩ := lv; have ⟨ax, xb, ha, hb⟩ := hl exact ⟨ax, xb.append (xv.trans_l vr), ha, hb.append bv vr hr⟩ termination_by l.size + r.size /-- The balance properties of the `append` function. -/ protected theorem Balanced.append {l r : RBNode α} (hl : l.Balanced c₁ n) (hr : r.Balanced c₂ n) : (l.append r).RedRed (c₁ = black → c₂ ≠ black) n := by unfold append; split · exact .balanced hr · exact .balanced hl · next b c _ _ => have .red ha hb := hl; have .red hc hd := hr have ⟨_, IH⟩ := (hb.append hc).of_false (· rfl rfl); split · next e => have .red hb' hc' := e ▸ IH exact .redred nofun (.red ha hb') (.red hc' hd) · next bcc _ H => match bcc, append b c, IH, H with | black, _, IH, _ => exact .redred nofun ha (.red IH hd) | red, _, .red .., H => cases H _ _ _ rfl · next b c _ _ => have .black ha hb := hl; have .black hc hd := hr have IH := hb.append hc; split · next e => match e ▸ IH with | .balanced (.red hb' hc') | .redred _ hb' hc' => exact .balanced (.red (.black ha hb') (.black hc' hd)) · next H => match append b c, IH, H with | bc, .balanced hbc, _ => unfold balLeft; split · have .red ha' hb' := ha exact .balanced (.red (.black ha' hb') (.black hbc hd)) · exact have ⟨c, h⟩ := RedRed.balance2 ha (.redred trivial hbc hd); .balanced h | _, .redred .., H => cases H _ _ _ rfl · have .red hc hd := hr; have IH := hl.append hc have .black ha hb := hl; have ⟨c, IH⟩ := IH.of_false (· rfl rfl) exact .redred nofun IH hd · have .red ha hb := hl; have IH := hb.append hr have .black hc hd := hr; have ⟨c, IH⟩ := IH.of_false (· rfl rfl) exact .redred nofun ha IH termination_by l.size + r.size /-! ## erase -/ /-- The invariant of the `del` function. * If the input tree is black, then the result of deletion is a red-red tree with black-height lowered by 1. * If the input tree is red or nil, then the result of deletion is a balanced tree with some color and the same black-height. -/ def DelProp (p : RBColor) (t : RBNode α) (n : Nat) : Prop := match p with | black => ∃ n', n = n' + 1 ∧ RedRed True t n' | red => ∃ c, Balanced t c n /-- The `DelProp` property is a strengthened version of the red-red invariant. -/ theorem DelProp.redred (h : DelProp c t n) : ∃ n', RedRed (c = black) t n' := by unfold DelProp at h exact match c, h with | red, ⟨_, h⟩ => ⟨_, .balanced h⟩ | black, ⟨_, _, h⟩ => ⟨_, h.imp fun _ => rfl⟩ protected theorem All.del : ∀ {t : RBNode α}, t.All p → (del cut t).All p | .nil, h => h | .node .., ⟨hy, ha, hb⟩ => by unfold del; split · split · exact ha.del.balLeft hy hb · exact ⟨hy, ha.del, hb⟩ · split · exact ha.balRight hy hb.del · exact ⟨hy, ha, hb.del⟩ · exact ha.append hb /-- The `del` function preserves the ordering invariants. -/ protected theorem Ordered.del : ∀ {t : RBNode α}, t.Ordered cmp → (del cut t).Ordered cmp | .nil, _ => ⟨⟩ | .node _ a y b, ⟨ay, yb, ha, hb⟩ => by unfold del; split · split · exact ha.del.balLeft ay.del yb hb · exact ⟨ay.del, yb, ha.del, hb⟩ · split · exact ha.balRight ay yb.del hb.del · exact ⟨ay, yb.del, ha, hb.del⟩ · exact ha.append ay yb hb /-- The `del` function has the `DelProp` property. -/ protected theorem Balanced.del {t : RBNode α} (h : t.Balanced c n) : (t.del cut).DelProp t.isBlack n := by induction h with | nil => exact ⟨_, .nil⟩ | @black a _ n b _ _ ha hb iha ihb => refine ⟨_, rfl, ?_⟩ unfold del; split · exact match a, n, iha with | .nil, _, ⟨c, ha⟩ | .node red .., _, ⟨c, ha⟩ => .redred ⟨⟩ ha hb | .node black .., _, ⟨n, rfl, ha⟩ => (hb.balLeft ha).imp fun _ => ⟨⟩ · exact match b, n, ihb with | .nil, _, ⟨c, hb⟩ | .node .red .., _, ⟨c, hb⟩ => .redred ⟨⟩ ha hb | .node black .., _, ⟨n, rfl, hb⟩ => (ha.balRight hb).imp fun _ => ⟨⟩ · exact (ha.append hb).imp fun _ => ⟨⟩ | @red a n b _ ha hb iha ihb => unfold del; split · exact match a, n, iha with | .nil, _, _ => ⟨_, .red ha hb⟩ | .node black .., _, ⟨n, rfl, ha⟩ => (hb.balLeft ha).of_false nofun · exact match b, n, ihb with | .nil, _, _ => ⟨_, .red ha hb⟩ | .node black .., _, ⟨n, rfl, hb⟩ => (ha.balRight hb).of_false nofun · exact (ha.append hb).of_false (· rfl rfl) /-- The `erase` function preserves the ordering invariants. -/ protected theorem Ordered.erase {t : RBNode α} (h : t.Ordered cmp) : (erase cut t).Ordered cmp := Ordered.setBlack.2 h.del /-- The `erase` function preserves the balance invariants. -/ protected theorem Balanced.erase {t : RBNode α} (h : t.Balanced c n) : ∃ n, (t.erase cut).Balanced black n := have ⟨_, h⟩ := h.del.redred; h.setBlack /-- The well-formedness invariant implies the ordering and balance properties. -/ theorem WF.out {t : RBNode α} (h : t.WF cmp) : t.Ordered cmp ∧ ∃ c n, t.Balanced c n := by induction h with | mk o h => exact ⟨o, _, _, h⟩ | insert _ ih => have ⟨o, _, _, h⟩ := ih; exact ⟨o.insert, h.insert⟩ | erase _ ih => have ⟨o, _, _, h⟩ := ih; exact ⟨o.erase, _, h.erase⟩ /-- The well-formedness invariant for a red-black tree is exactly the `mk` constructor, because the other constructors of `WF` are redundant. -/ @[simp] theorem WF_iff {t : RBNode α} : t.WF cmp ↔ t.Ordered cmp ∧ ∃ c n, t.Balanced c n := ⟨fun h => h.out, fun ⟨o, _, _, h⟩ => .mk o h⟩ /-- The `map` function preserves the balance invariants. -/ protected theorem Balanced.map {t : RBNode α} : t.Balanced c n → (t.map f).Balanced c n | .nil => .nil | .red hl hr => .red hl.map hr.map | .black hl hr => .black hl.map hr.map /-- The property of a map function `f` which ensures the `map` operation is valid. -/ class IsMonotone (cmpα cmpβ) (f : α → β) : Prop where /-- If `x < y` then `f x < f y`. -/ lt_mono : cmpLT cmpα x y → cmpLT cmpβ (f x) (f y) /-- Sufficient condition for `map` to preserve an `All` quantifier. -/ protected theorem All.map {f : α → β} (H : ∀ {x}, p x → q (f x)) : ∀ {t : RBNode α}, t.All p → (t.map f).All q | nil, _ => ⟨⟩ | node .., ⟨hx, ha, hb⟩ => ⟨H hx, ha.map H, hb.map H⟩ /-- The `map` function preserves the order invariants if `f` is monotone. -/ protected theorem Ordered.map (f : α → β) [IsMonotone cmpα cmpβ f] : ∀ {t : RBNode α}, t.Ordered cmpα → (t.map f).Ordered cmpβ | nil, _ => ⟨⟩ | node _ a x b, ⟨ax, xb, ha, hb⟩ => by refine ⟨ax.map ?_, xb.map ?_, ha.map f, hb.map f⟩ <;> exact IsMonotone.lt_mono end RBNode namespace RBSet export RBNode (IsMonotone) /-- `O(n)`. Map a function on every value in the set. This requires `IsMonotone` on the function in order to preserve the order invariant. If the function is not monotone, use `RBSet.map` instead. -/ @[inline] def mapMonotone (f : α → β) [IsMonotone cmpα cmpβ f] (t : RBSet α cmpα) : RBSet β cmpβ := ⟨t.1.map f, have ⟨h₁, _, _, h₂⟩ := t.2.out; .mk (h₁.map _) h₂.map⟩ end RBSet namespace RBMap export RBNode (IsMonotone) namespace Imp /-- Applies `f` to the second component. We extract this as a function so that `IsMonotone (mapSnd f)` can be an instance. -/ @[inline] def mapSnd (f : α → β → γ) := fun (a, b) => (a, f a b) open Ordering (byKey) instance (cmp : α → α → Ordering) (f : α → β → γ) : IsMonotone (byKey Prod.fst cmp) (byKey Prod.fst cmp) (mapSnd f) where lt_mono | ⟨h⟩ => ⟨@fun _ => @h { eq_swap := @fun (a₁, b₁) (a₂, b₂) => Std.OrientedCmp.eq_swap (cmp := byKey Prod.fst cmp) (a := (a₁, f a₁ b₁)) (b := (a₂, f a₂ b₂)) isLE_trans := @fun (a₁, b₁) (a₂, b₂) (a₃, b₃) => Std.TransCmp.isLE_trans (cmp := byKey Prod.fst cmp) (a := (a₁, f a₁ b₁)) (b := (a₂, f a₂ b₂)) (c := (a₃, f a₃ b₃)) }⟩ end Imp /-- `O(n)`. Map a function on the values in the map. -/ def mapVal (f : α → β → γ) (t : RBMap α β cmp) : RBMap α γ cmp := t.mapMonotone (Imp.mapSnd f) end RBMap
.lake/packages/batteries/Batteries/Control/Lemmas.lean
module import all Init.Control.Reader import all Init.Control.State @[expose] public section namespace ReaderT attribute [ext] ReaderT.ext @[simp] theorem run_failure [Monad m] [Alternative m] (ctx : ρ) : (failure : ReaderT ρ m α).run ctx = failure := (rfl) @[simp] theorem run_orElse [Monad m] [Alternative m] (x y : ReaderT ρ m α) (ctx : ρ) : (x <|> y).run ctx = (x.run ctx <|> y.run ctx) := (rfl) @[simp] theorem run_throw [MonadExceptOf ε m] (e : ε) (ctx : ρ) : (throw e : ReaderT ρ m α).run ctx = throw e := rfl @[simp] theorem run_throwThe [MonadExceptOf ε m] (e : ε) (ctx : ρ) : (throwThe ε e : ReaderT ρ m α).run ctx = throwThe ε e := rfl @[simp] theorem run_tryCatch [MonadExceptOf ε m] (body : ReaderT ρ m α) (handler : ε → ReaderT ρ m α) (ctx : ρ) : (tryCatch body handler).run ctx = tryCatch (body.run ctx) (handler · |>.run ctx) := rfl @[simp] theorem run_tryCatchThe [MonadExceptOf ε m] (body : ReaderT ρ m α) (handler : ε → ReaderT ρ m α) (ctx : ρ) : (tryCatchThe ε body handler).run ctx = tryCatchThe ε (body.run ctx) (handler · |>.run ctx) := rfl end ReaderT namespace StateT attribute [ext] StateT.ext @[simp] theorem run_failure {α σ} [Monad m] [Alternative m] (s : σ) : (failure : StateT σ m α).run s = failure := (rfl) @[simp] theorem run_orElse {α σ} [Monad m] [Alternative m] (x y : StateT σ m α) (s : σ) : (x <|> y).run s = (x.run s <|> y.run s) := (rfl) @[simp] theorem run_throw [Monad m] [MonadExceptOf ε m] (e : ε) (s : σ) : (throw e : StateT σ m α).run s = (do let a ← throw e; pure (a, s)) := rfl @[simp] theorem run_throwThe [Monad m] [MonadExceptOf ε m] (e : ε) (s : σ) : (throwThe ε e : StateT σ m α).run s = (do let a ← throwThe ε e; pure (a, s)) := rfl @[simp] theorem run_tryCatch [Monad m] [MonadExceptOf ε m] (body : StateT σ m α) (handler : ε → StateT σ m α) (s : σ) : (tryCatch body handler).run s = tryCatch (body.run s) (handler · |>.run s) := rfl @[simp] theorem run_tryCatchThe [Monad m] [MonadExceptOf ε m] (body : StateT σ m α) (handler : ε → StateT σ m α) (s : σ) : (tryCatchThe ε body handler).run s = tryCatchThe ε (body.run s) (handler · |>.run s) := rfl end StateT
.lake/packages/batteries/Batteries/Control/Monad.lean
module public import Batteries.Tactic.Alias @[expose] public section @[deprecated (since := "2025-02-09")] alias LawfulFunctor.map_inj_right_of_nonempty := map_inj_right_of_nonempty @[deprecated (since := "2025-02-09")] alias LawfulMonad.map_inj_right := map_inj_right
.lake/packages/batteries/Batteries/Control/AlternativeMonad.lean
module public import Batteries.Control.Lemmas public import Batteries.Control.OptionT import all Init.Control.Option import all Init.Control.State import all Init.Control.Reader import all Init.Control.StateRef @[expose] public section /-! # Laws for Monads with Failure Definitions for monads that also have an `Alternative` instance while sharing the underlying `Applicative` instance, and a class `LawfulAlternative` for types where the `failure` and `orElse` operations behave in a natural way. More specifically they satisfy: * `f <$> failure = failure` * `failure <*> x = failure` * `x <|> failure = x` * `failure <|> y = y` * `x <|> y <|> z = (x <|> y) <|> z` * `f <$> (x <|> y) = (f <$> x <|> f <$> y)` `Option`/`OptionT` are the most basic examples, but transformers like `StateT` also preserve the lawfulness of this on the underlying monad. The law `x *> failure = failure` is true for monads like `Option` and `List` that don't have any "side effects" to execution, but not for something like `OptionT` on some monads, so we don't include this condition. We also define a class `LawfulAlternativeLift` similar to `LawfulMonadLift` that states that a lifting between monads preserves `failure` and `orElse`. ## Tags monad, alternative, failure -/ /-- `AlternativeMonad m` means that `m` has both a `Monad` and `Alternative` instance, which both share the same underlying `Applicative` instance. The main example is `Option`, but many monad transformers also preserve or add this structure. -/ class AlternativeMonad (m : Type _ → Type _) extends Alternative m, Monad m section LawfulAlternative /-- `LawfulAlternative m` means that the `failure` operation on `m` behaves naturally with respect to `map`, `seq`, and `orElse` operators. -/ class LawfulAlternative (m : Type _ → Type _) [Alternative m] : Prop extends LawfulApplicative m where /-- Mapping the result of a failure is still a failure -/ map_failure (f : α → β) : f <$> (failure : m α) = failure /-- Sequencing a `failure` call results in failure -/ failure_seq (x : m α) : (failure : m (α → β)) <*> x = failure /-- `failure` is a right identity for `orElse`. -/ orElse_failure (x : m α) : (x <|> failure) = x /-- `failure` is a left identity for `orElse`. -/ failure_orElse (y : m α) : (failure <|> y) = y /-- `orElse` is associative. -/ orElse_assoc (x y z : m α) : (x <|> y <|> z) = ((x <|> y) <|> z) /-- `map` commutes with `orElse`. The stronger statement with `bind` generally isn't true -/ map_orElse (x y : m α) (f : α → β) : f <$> (x <|> y) = (f <$> x <|> f <$> y) export LawfulAlternative (map_failure failure_seq orElse_failure failure_orElse orElse_assoc map_orElse) attribute [simp] map_failure failure_seq orElse_failure failure_orElse map_orElse section Alternative @[simp] theorem mapConst_failure [Alternative m] [LawfulAlternative m] (y : β) : Functor.mapConst y (failure : m α) = failure := by rw [LawfulFunctor.map_const, Function.comp_apply, map_failure] @[simp] theorem mapConst_orElse [Alternative m] [LawfulAlternative m] (x x' : m α) (y : β) : Functor.mapConst y (x <|> x') = (Functor.mapConst y x <|> Functor.mapConst y x') := by simp only [map_const, Function.comp_apply, map_orElse] @[simp] theorem failure_seqLeft [Alternative m] [LawfulAlternative m] (x : m α) : (failure : m β) <* x = failure := by simp only [seqLeft_eq, map_failure, failure_seq] @[simp] theorem failure_seqRight [Alternative m] [LawfulAlternative m] (x : m α) : (failure : m β) *> x = failure := by simp only [seqRight_eq, map_failure, failure_seq] end Alternative section AlternativeMonad @[simp] theorem failure_bind [AlternativeMonad m] [LawfulAlternative m] [LawfulMonad m] (x : α → m β) : failure >>= x = failure := by calc failure >>= x = (PEmpty.elim <$> failure) >>= x := by rw [map_failure] _ = failure >>= (x ∘ PEmpty.elim) := by rw [bind_map_left, Function.comp_def] _ = failure >>= (pure ∘ PEmpty.elim) := bind_congr fun a => a.elim _ = (PEmpty.elim <$> failure) >>= pure := by rw [bind_map_left, Function.comp_def] _ = failure := by rw [map_failure, bind_pure] @[simp] theorem seq_failure [AlternativeMonad m] [LawfulAlternative m] [LawfulMonad m] (x : m (α → β)) : x <*> failure = x *> failure := by simp only [seq_eq_bind, map_failure, seqRight_eq, bind_map_left] end AlternativeMonad end LawfulAlternative /-- Type-class for monad lifts that preserve the `Alternative` operations. -/ class LawfulAlternativeLift (m : semiOutParam (Type u → Type v)) (n : Type u → Type w) [Alternative m] [Alternative n] [MonadLift m n] : Prop where /-- Lifting preserves `failure`. -/ monadLift_failure : monadLift (failure : m α) = (failure : n α) /-- Lifting preserves `orElse`. -/ monadLift_orElse (x y : m α) : monadLift (x <|> y) = (monadLift x <|> monadLift y : n α) export LawfulAlternativeLift (monadLift_failure monadLift_orElse) attribute [simp] monadLift_failure monadLift_orElse namespace Option instance : AlternativeMonad Option.{u} where instance : LawfulAlternative Option.{u} where map_failure _ := rfl failure_seq _ := rfl orElse_failure x := by cases x <;> rfl failure_orElse := by simp [failure] orElse_assoc | some _, _, _ => rfl | none, _, _ => rfl map_orElse | some _ => by simp | none => by simp end Option namespace OptionT instance (m) [Monad m] : AlternativeMonad (OptionT m) where instance (m) [Monad m] [LawfulMonad m] : LawfulAlternative (OptionT m) where map_failure _ := pure_bind _ _ failure_seq _ := pure_bind _ _ orElse_failure x := (bind_congr (fun | some _ => rfl | none => rfl)).trans (bind_pure x) failure_orElse _ := pure_bind _ _ orElse_assoc _ _ _ := by simp only [OptionT.ext_iff, run_orElse, Option.elimM, bind_assoc] refine bind_congr fun | some _ => by simp | none => rfl map_orElse x y f := by simp only [OptionT.ext_iff, run_map, run_orElse, map_bind, bind_map_left, Option.elimM] refine bind_congr fun | some _ => by simp | none => rfl end OptionT namespace StateT instance (m) [AlternativeMonad m] : AlternativeMonad (StateT σ m) where instance (m) [AlternativeMonad m] [LawfulAlternative m] [LawfulMonad m] : LawfulAlternative (StateT σ m) where map_failure _ := StateT.ext fun _ => by simp only [run_map, run_failure, map_failure] failure_seq _ := StateT.ext fun _ => by simp only [run_seq, run_failure, failure_bind] orElse_failure _ := StateT.ext fun _ => orElse_failure _ failure_orElse _ := StateT.ext fun _ => failure_orElse _ orElse_assoc _ _ _ := StateT.ext fun _ => orElse_assoc _ _ _ map_orElse _ _ _ := StateT.ext fun _ => by simp only [run_map, run_orElse, map_orElse] instance (m) [AlternativeMonad m] [LawfulAlternative m] [LawfulMonad m] : LawfulAlternativeLift m (StateT σ m) where monadLift_failure {α} := StateT.ext fun s => by simp monadLift_orElse {α} x y := StateT.ext fun s => by simp end StateT namespace ReaderT instance [AlternativeMonad m] : AlternativeMonad (ReaderT ρ m) where instance [AlternativeMonad m] [LawfulAlternative m] : LawfulAlternative (ReaderT ρ m) where map_failure _ := ReaderT.ext fun _ => map_failure _ failure_seq _ := ReaderT.ext fun _ => failure_seq _ orElse_failure _ := ReaderT.ext fun _ => orElse_failure _ failure_orElse _ := ReaderT.ext fun _ => failure_orElse _ orElse_assoc _ _ _ := ReaderT.ext fun _ => orElse_assoc _ _ _ map_orElse _ _ _ := ReaderT.ext fun _ => by simp only [run_map, run_orElse, map_orElse] instance [AlternativeMonad m] : LawfulAlternativeLift m (ReaderT ρ m) where monadLift_failure {α} := ReaderT.ext fun s => by simp monadLift_orElse {α} x y := ReaderT.ext fun s => by simp end ReaderT namespace StateRefT' instance [AlternativeMonad m] : AlternativeMonad (StateRefT' ω σ m) where instance [AlternativeMonad m] [LawfulAlternative m] : LawfulAlternative (StateRefT' ω σ m) := inferInstanceAs (LawfulAlternative (ReaderT _ _)) instance [AlternativeMonad m] : LawfulAlternativeLift m (StateRefT' ω σ m) := inferInstanceAs (LawfulAlternativeLift m (ReaderT _ _)) end StateRefT'
.lake/packages/batteries/Batteries/Control/LawfulMonadState.lean
module import all Init.Control.StateRef @[expose] public section /-! # Laws for Monads with State This file defines a typeclass for `MonadStateOf` with compatible `get` and `set` operations. Note that we use `MonadStateOf` over `MonadState` as the first induces the second, but we phrase things using `MonadStateOf.set` and `MonadState.get` as those are the versions that are available at the top level namespace. -/ /-- The namespaced `MonadStateOf.get` is equal to the `MonadState` provided `get`. -/ @[simp] theorem monadStateOf_get_eq_get [MonadStateOf σ m] : (MonadStateOf.get : m σ) = get := rfl /-- The namespaced `MonadStateOf.modifyGet` is equal to the `MonadState` provided `modifyGet`. -/ @[simp] theorem monadStateOf_modifyGet_eq_modifyGet [MonadStateOf σ m] (f : σ → α × σ) : (MonadStateOf.modifyGet f : m α) = modifyGet f := rfl @[simp] theorem liftM_get {m n} [MonadStateOf σ m] [MonadLift m n] : (liftM (get (m := m)) : n _) = get := rfl @[simp] theorem liftM_set {m n} [MonadStateOf σ m] [MonadLift m n] (s : σ) : (liftM (set (m := m) s) : n _) = set s := rfl @[simp] theorem liftM_modify {m n} [MonadStateOf σ m] [MonadLift m n] (f : σ → σ) : (liftM (modify (m := m) f) : n _) = modify f := rfl @[simp] theorem liftM_modifyGet {m n} [MonadStateOf σ m] [MonadLift m n] (f : σ → α × σ) : (liftM (modifyGet (m := m) f) : n _) = modifyGet f := rfl @[simp] theorem liftM_getModify {m n} [MonadStateOf σ m] [MonadLift m n] (f : σ → σ) : (liftM (getModify (m := m) f) : n _) = getModify f := rfl /-- Class for well behaved state monads, extending the base `MonadState` type. Requires that `modifyGet` is equal to the same definition with only `get` and `set`, that `get` is idempotent if the result isn't used, and that `get` after `set` returns exactly the value that was previously `set`. -/ class LawfulMonadStateOf (σ : semiOutParam (Type _)) (m : Type _ → Type _) [Monad m] [MonadStateOf σ m] extends LawfulMonad m where /-- `modifyGet f` is equal to getting the state, modifying it, and returning a result. -/ modifyGet_eq {α} (f : σ → α × σ) : modifyGet (m := m) f = do let z ← f <$> get; set z.2; return z.1 /-- Discarding the result of `get` is the same as never getting the state. -/ get_bind_const {α} (mx : m α) : (do let _ ← get; mx) = mx /-- Calling `get` twice is the same as just using the first retreived state value. -/ get_bind_get_bind {α} (mx : σ → σ → m α) : (do let s ← get; let s' ← get; mx s s') = (do let s ← get; mx s s) /-- Setting the monad state to its current value has no effect. -/ get_bind_set_bind {α} (mx : σ → PUnit → m α) : (do let s ← get; let u ← set s; mx s u) = (do let s ← get; mx s PUnit.unit) /-- Setting and then returning the monad state is the same as returning the set value. -/ set_bind_get (s : σ) : (do set (m := m) s; get) = (do set s; return s) /-- Setting the monad twice is the same as just setting to the final state. -/ set_bind_set (s s' : σ) : (do set (m := m) s; set s') = set s' namespace LawfulMonadStateOf variable {σ : Type _} {m : Type _ → Type _} [Monad m] [MonadStateOf σ m] [LawfulMonadStateOf σ m] attribute [simp] get_bind_const get_bind_get_bind get_bind_set_bind set_bind_get set_bind_set @[simp] theorem get_seqRight (mx : m α) : get *> mx = mx := by rw [seqRight_eq_bind, get_bind_const] @[simp] theorem seqLeft_get (mx : m α) : mx <* get = mx := by simp only [seqLeft_eq_bind, get_bind_const, bind_pure] @[simp] theorem get_map_const (x : α) : (fun _ => x) <$> get (m := m) = pure x := by rw [map_eq_pure_bind, get_bind_const] theorem get_bind_get : (do let _ ← get (m := m); get) = get := get_bind_const get @[simp] theorem get_bind_set : (do let s ← get (m := m); set s) = return PUnit.unit := by simpa only [bind_pure_comp, id_map', get_map_const] using get_bind_set_bind (σ := σ) (m := m) (fun _ _ => return PUnit.unit) @[simp] theorem get_bind_map_set (f : σ → PUnit → α) : (do let s ← get (m := m); f s <$> set s) = (do return f (← get) PUnit.unit) := by simp [map_eq_pure_bind, -bind_pure_comp] @[simp] theorem set_bind_get_bind (s : σ) (f : σ → m α) : (do set s; let s' ← get; f s') = (do set s; f s) := by rw [← bind_assoc, set_bind_get, bind_assoc, pure_bind] @[simp] theorem set_bind_map_get (f : σ → α) (s : σ) : (do set (m := m) s; f <$> get) = (do set (m := m) s; pure (f s)) := by simp [map_eq_pure_bind, -bind_pure_comp] @[simp] theorem set_bind_set_bind (s s' : σ) (mx : m α) : (do set s; set s'; mx) = (do set s'; mx) := by rw [← bind_assoc, set_bind_set] @[simp] theorem set_bind_map_set (s s' : σ) (f : PUnit → α) : (do set (m := m) s; f <$> set s') = (do f <$> set s') := by simp [map_eq_pure_bind, ← bind_assoc, -bind_pure_comp] section modify theorem modifyGetThe_eq (f : σ → α × σ) : modifyGetThe σ (m := m) f = do let z ← f <$> get; set z.2; return z.1 := modifyGet_eq f theorem modify_eq (f : σ → σ) : modify (m := m) f = (do set (f (← get))) := by simp [modify, modifyGet_eq] theorem modifyThe_eq (f : σ → σ) : modifyThe σ (m := m) f = (do set (f (← get))) := modify_eq f theorem getModify_eq (f : σ → σ) : getModify (m := m) f = do let s ← get; set (f s); return s := by rw [getModify, modifyGet_eq, bind_map_left] /-- Version of `modifyGet_eq` that preserves an call to `modify`. -/ theorem modifyGet_eq' (f : σ → α × σ) : modifyGet (m := m) f = do let s ← get; modify (Prod.snd ∘ f); return (f s).fst := by simp [modify_eq, modifyGet_eq] @[simp] theorem modify_id : modify (m := m) id = pure PUnit.unit := by simp [modify_eq] @[simp] theorem getModify_id : getModify (m := m) id = get := by simp [getModify_eq] @[simp] theorem set_bind_modify (s : σ) (f : σ → σ) : (do set (m := m) s; modify f) = set (f s) := by simp [modify_eq] @[simp] theorem set_bind_modify_bind (s : σ) (f : σ → σ) (mx : PUnit → m α) : (do set s; let u ← modify f; mx u) = (do set (f s); mx PUnit.unit) := by simp [modify_eq, ← bind_assoc] @[simp] theorem set_bind_modifyGet (s : σ) (f : σ → α × σ) : (do set (m := m) s; modifyGet f) = (do set (f s).2; return (f s).1) := by simp [modifyGet_eq] @[simp] theorem set_bind_modifyGet_bind (s : σ) (f : σ → α × σ) (mx : α → m β) : (do set s; let x ← modifyGet f; mx x) = (do set (f s).2; mx (f s).1) := by simp [modifyGet_eq] @[simp] theorem set_bind_getModify (s : σ) (f : σ → σ) : (do set (m := m) s; getModify f) = (do set (f s); return s) := by simp [getModify_eq] @[simp] theorem set_bind_getModify_bind (s : σ) (f : σ → σ) (mx : σ → m α) : (do set s; let x ← getModify f; mx x) = (do set (f s); mx s) := by simp [getModify_eq, ← bind_assoc] @[simp] theorem modify_bind_modify (f g : σ → σ) : (do modify (m := m) f; modify g) = modify (g ∘ f) := by simp [modify_eq] @[simp] theorem modify_bind_modifyGet (f : σ → σ) (g : σ → α × σ) : (do modify (m := m) f; modifyGet g) = modifyGet (g ∘ f) := by simp [modify_eq, modifyGet_eq] @[simp] theorem getModify_bind_modify (f : σ → σ) (g : σ → σ → σ) : (do let s ← getModify (m := m) f; modify (g s)) = (do let s ← get; modify (g s ∘ f)) := by simp [modify_eq, getModify_eq] theorem modify_comm_of_comp_comm {f g : σ → σ} (h : f ∘ g = g ∘ f) : (do modify (m := m) f; modify g) = (do modify (m := m) g; modify f) := by simp [modify_bind_modify, h] theorem modify_bind_get (f : σ → σ) : (do modify (m := m) f; get) = (do let s ← get; modify f; return (f s)) := by simp [modify_eq] end modify /-- `StateT` has lawful state operations if the underlying monad is lawful. This is applied for `StateM` as well due to the reducibility of that definition. -/ instance {m σ} [Monad m] [LawfulMonad m] : LawfulMonadStateOf σ (StateT σ m) where modifyGet_eq f := StateT.ext fun s => by simp get_bind_const mx := StateT.ext fun s => by simp get_bind_get_bind mx := StateT.ext fun s => by simp get_bind_set_bind mx := StateT.ext fun s => by simp set_bind_get s := StateT.ext fun s => by simp set_bind_set s s' := StateT.ext fun s => by simp /-- The continuation passing state monad variant `StateCpsT` always has lawful state instance. -/ instance {σ m} : LawfulMonadStateOf σ (StateCpsT σ m) where modifyGet_eq _ := rfl get_bind_const _ := rfl get_bind_get_bind _ := rfl get_bind_set_bind _ := rfl set_bind_get _ := rfl set_bind_set _ _ := rfl /-- The `EStateM` monad always has a lawful state instance. -/ instance {σ ε} : LawfulMonadStateOf σ (EStateM ε σ) where modifyGet_eq _ := rfl get_bind_const _ := rfl get_bind_get_bind _ := rfl get_bind_set_bind _ := rfl set_bind_get _ := rfl set_bind_set _ _ := rfl /-- If the underlying monad `m` has a lawful state instance, then the induced state instance on `ReaderT ρ m` will also be lawful. -/ instance {m σ ρ} [Monad m] [LawfulMonad m] [MonadStateOf σ m] [LawfulMonadStateOf σ m] : LawfulMonadStateOf σ (ReaderT ρ m) where modifyGet_eq f := ReaderT.ext fun ctx => by simp [← liftM_modifyGet, LawfulMonadStateOf.modifyGet_eq, ← liftM_get] get_bind_const mx := ReaderT.ext fun ctx => by simp [← liftM_get] get_bind_get_bind mx := ReaderT.ext fun ctx => by simp [← liftM_get] get_bind_set_bind mx := ReaderT.ext fun ctx => by simp [← liftM_get, ← liftM_set] set_bind_get s := ReaderT.ext fun ctx => by simp [← liftM_get, ← liftM_set] set_bind_set s s' := ReaderT.ext fun ctx => by simp [← liftM_set] instance {m ω σ} [Monad m] [LawfulMonad m] [MonadStateOf σ m] [LawfulMonadStateOf σ m] : LawfulMonadStateOf σ (StateRefT' ω σ m) := inferInstanceAs (LawfulMonadStateOf σ (ReaderT _ _))
.lake/packages/batteries/Batteries/Control/OptionT.lean
module public import Batteries.Control.LawfulMonadState import all Init.Control.Option @[expose] public section /-! # Lemmas About Option Monad Transformer This file contains lemmas about the behavior of `OptionT` and `OptionT.run`. -/ namespace OptionT @[simp] theorem run_monadLift [Monad m] [LawfulMonad m] [MonadLiftT n m] (x : n α) : (monadLift x : OptionT m α).run = some <$> (monadLift x : m α) := (map_eq_pure_bind _ _).symm @[simp] theorem run_mapConst [Monad m] [LawfulMonad m] (x : OptionT m α) (y : β) : (Functor.mapConst y x).run = Option.map (Function.const α y) <$> x.run := run_map _ _ @[simp] theorem run_monadMap {n} [MonadFunctorT n m] (f : ∀ {α}, n α → n α) : (monadMap (@f) x : OptionT m α).run = monadMap (@f) x.run := (rfl) instance [Monad m] [LawfulMonad m] [MonadStateOf σ m] [LawfulMonadStateOf σ m] : LawfulMonadStateOf σ (OptionT m) where modifyGet_eq f := by simp [← liftM_modifyGet, ← liftM_get, LawfulMonadStateOf.modifyGet_eq] get_bind_const mx := OptionT.ext (by simp [← liftM_get]) get_bind_get_bind mx := OptionT.ext (by simp [← liftM_get]) get_bind_set_bind mx := OptionT.ext (by simp [← liftM_get, ← liftM_set]) set_bind_get s := OptionT.ext (by simp [← liftM_get, ← liftM_set]) set_bind_set s s' := OptionT.ext (by simp [← liftM_set]) end OptionT
.lake/packages/batteries/Batteries/Control/ForInStep.lean
module public import Batteries.Control.ForInStep.Basic public import Batteries.Control.ForInStep.Lemmas
.lake/packages/batteries/Batteries/Control/Nondet/Basic.lean
module public import Batteries.Tactic.Lint.Misc public import Batteries.Data.MLList.Basic import Lean.Util.MonadBacktrack @[expose] public section /-! # A nondeterminism monad. We represent nondeterministic values in a type `α` as a single field structure containing an `MLList m (σ × α)`, i.e. as a monadic lazy list of possible values, each equipped with the backtrackable state required to run further computations in the ambient monad. We provide an `Alternative` `Monad` instance, as well as functions `bind`, `mapM`, and `filterMapM`, and functions `singletonM`, `ofListM`, `ofOptionM`, and `firstM` for entering and leaving the nondeterministic world. Operations on the nondeterministic value via `bind`, `mapM`, and `filterMapM` run with the appropriate backtrackable state, and are responsible for updating the state themselves (typically this doesn't need to be done explicitly, but just happens as a side effect in the monad `m`). -/ open Lean (MonadBacktrack) open Lean.MonadBacktrack /-- `Nondet m α` is variation on `MLList m α` suitable for use with backtrackable monads `m`. We think of `Nondet m α` as a nondeterministic value in `α`, with the possible alternatives stored in a monadic lazy list. Along with each `a : α` we store the backtrackable state, and ensure that monadic operations on alternatives run with the appropriate state. Operations on the nondeterministic value via `bind`, `mapM`, and `filterMapM` run with the appropriate backtrackable state, and are responsible for updating the state themselves (typically this doesn't need to be done explicitly, but just happens as a side effect in the monad `m`). -/ @[nolint unusedArguments] structure Nondet (m : Type → Type) [MonadBacktrack σ m] (α : Type) : Type where /-- Convert a non-deterministic value into a lazy list, keeping the backtrackable state. Be careful that monadic operations on the `MLList` will not respect this state! -/ toMLList : MLList m (α × σ) namespace Nondet variable {m : Type → Type} section Monad variable [Monad m] [MonadBacktrack σ m] /-- The empty nondeterministic value. -/ def nil : Nondet m α := .mk .nil instance : Inhabited (Nondet m α) := ⟨.nil⟩ /-- Squash a monadic nondeterministic value to a nondeterministic value. -/ def squash (L : Unit → m (Nondet m α)) : Nondet m α := .mk <| MLList.squash fun _ => return (← L ()).toMLList /-- Bind a nondeterministic function over a nondeterministic value, ensuring the function is run with the relevant backtrackable state at each value. -/ partial def bind (L : Nondet m α) (f : α → Nondet m β) : Nondet m β := .squash fun _ => do match ← L.toMLList.uncons with | none => pure .nil | some (⟨x, s⟩, xs) => do let r := (Nondet.mk xs).bind f restoreState s match ← (f x).toMLList.uncons with | none => return r | some (y, ys) => return .mk <| .cons y (ys.append (fun _ => r.toMLList)) /-- Convert any value in the monad to the singleton nondeterministic value. -/ def singletonM (x : m α) : Nondet m α := .mk <| .singletonM do let a ← x return (a, ← saveState) /-- Convert a value to the singleton nondeterministic value. -/ def singleton (x : α) : Nondet m α := singletonM (pure x) /-- `Nondet m` is an alternative monad. -/ instance : AlternativeMonad (Nondet m) where pure a := singletonM (pure a) bind := bind failure := .nil orElse x y := .mk <| x.toMLList.append fun _ => (y ()).toMLList instance : MonadLift m (Nondet m) where monadLift := singletonM /-- Lift a list of monadic values to a nondeterministic value. We ensure that each monadic value is evaluated with the same backtrackable state. -/ def ofListM (L : List (m α)) : Nondet m α := .squash fun _ => do let s ← saveState return .mk <| MLList.ofListM <| L.map fun x => do restoreState s let a ← x pure (a, ← saveState) /-- Lift a list of values to a nondeterministic value. (The backtrackable state in each will be identical: whatever the state was when we first read from the result.) -/ def ofList (L : List α) : Nondet m α := ofListM (L.map pure) /-- Apply a function which returns values in the monad to every alternative of a `Nondet m α`. -/ def mapM (f : α → m β) (L : Nondet m α) : Nondet m β := L.bind fun a => singletonM (f a) /-- Apply a function to each alternative in a `Nondet m α` . -/ def map (f : α → β) (L : Nondet m α) : Nondet m β := L.mapM fun a => pure (f a) /-- Convert a monadic optional value to a nondeterministic value. -/ def ofOptionM (x : m (Option α)) : Nondet m α := .squash fun _ => do match ← x with | none => return .nil | some a => return singleton a /-- Convert an optional value to a nondeterministic value. -/ def ofOption (x : Option α) : Nondet m α := ofOptionM (pure x) /-- Filter and map a nondeterministic value using a monadic function which may return `none`. -/ def filterMapM (f : α → m (Option β)) (L : Nondet m α) : Nondet m β := L.bind fun a => ofOptionM (f a) /-- Filter and map a nondeterministic value. -/ def filterMap (f : α → Option β) (L : Nondet m α) : Nondet m β := L.filterMapM fun a => pure (f a) /-- Filter a nondeterministic value using a monadic predicate. -/ def filterM (p : α → m (ULift Bool)) (L : Nondet m α) : Nondet m α := L.filterMapM fun a => do if (← p a).down then pure (some a) else pure none /-- Filter a nondeterministic value. -/ def filter (p : α → Bool) (L : Nondet m α) : Nondet m α := L.filterM fun a => pure <| .up (p a) /-- All iterations of a non-deterministic function on an initial value. (That is, depth first search.) -/ partial def iterate (f : α → Nondet m α) (a : α) : Nondet m α := singleton a <|> (f a).bind (iterate f) /-- Convert a non-deterministic value into a lazy list, by discarding the backtrackable state. -/ def toMLList' (L : Nondet m α) : MLList m α := L.toMLList.map (·.1) /-- Convert a non-deterministic value into a list in the monad, retaining the backtrackable state. -/ def toList (L : Nondet m α) : m (List (α × σ)) := L.toMLList.force /-- Convert a non-deterministic value into a list in the monad, by discarding the backtrackable state. -/ def toList' (L : Nondet m α) : m (List α) := L.toMLList.map (·.1) |>.force end Monad section AlternativeMonad variable [AlternativeMonad m] [MonadBacktrack σ m] /-- Find the first alternative in a nondeterministic value, as a monadic value. -/ def head (L : Nondet m α) : m α := do let (x, s) ← L.toMLList.head restoreState s return x /-- Find the value of a monadic function on the first alternative in a nondeterministic value where the function succeeds. -/ def firstM (L : Nondet m α) (f : α → m (Option β)) : m β := L.filterMapM f |>.head end AlternativeMonad end Nondet /-- The `Id` monad is trivially backtrackable, with state `Unit`. -/ -- This is useful so we can use `Nondet Id α` instead of `List α` -- as the basic non-determinism monad. instance : MonadBacktrack Unit Id where saveState := pure () restoreState _ := pure ()
.lake/packages/batteries/Batteries/Control/ForInStep/Lemmas.lean
module public import Batteries.Control.ForInStep.Basic @[expose] public section /-! # Additional theorems on `ForInStep` -/ @[simp] theorem ForInStep.bind_done [Monad m] (a : α) (f : α → m (ForInStep α)) : (ForInStep.done a).bind (m := m) f = pure (.done a) := rfl @[simp] theorem ForInStep.bind_yield [Monad m] (a : α) (f : α → m (ForInStep α)) : (ForInStep.yield a).bind (m := m) f = f a := rfl attribute [simp] ForInStep.bindM @[simp] theorem ForInStep.run_done : (ForInStep.done a).run = a := rfl @[simp] theorem ForInStep.run_yield : (ForInStep.yield a).run = a := rfl @[simp] theorem ForInStep.bindList_nil [Monad m] (f : α → β → m (ForInStep β)) (s : ForInStep β) : s.bindList f [] = pure s := rfl @[simp] theorem ForInStep.bindList_cons [Monad m] (f : α → β → m (ForInStep β)) (s : ForInStep β) (a l) : s.bindList f (a::l) = s.bind fun b => f a b >>= (·.bindList f l) := rfl @[simp] theorem ForInStep.done_bindList [Monad m] (f : α → β → m (ForInStep β)) (a l) : (ForInStep.done a).bindList f l = pure (.done a) := by cases l <;> simp @[simp] theorem ForInStep.bind_yield_bindList [Monad m] (f : α → β → m (ForInStep β)) (s : ForInStep β) (l) : (s.bind fun a => (yield a).bindList f l) = s.bindList f l := by cases s <;> simp @[simp] theorem ForInStep.bind_bindList_assoc [Monad m] [LawfulMonad m] (f : β → m (ForInStep β)) (g : α → β → m (ForInStep β)) (s : ForInStep β) (l) : s.bind f >>= (·.bindList g l) = s.bind fun b => f b >>= (·.bindList g l) := by cases s <;> simp theorem ForInStep.bindList_cons' [Monad m] [LawfulMonad m] (f : α → β → m (ForInStep β)) (s : ForInStep β) (a l) : s.bindList f (a::l) = s.bind (f a) >>= (·.bindList f l) := by simp @[simp] theorem ForInStep.bindList_append [Monad m] [LawfulMonad m] (f : α → β → m (ForInStep β)) (s : ForInStep β) (l₁ l₂) : s.bindList f (l₁ ++ l₂) = s.bindList f l₁ >>= (·.bindList f l₂) := by induction l₁ generalizing s <;> simp [*]
.lake/packages/batteries/Batteries/Control/ForInStep/Basic.lean
module @[expose] public section /-! # Additional definitions on `ForInStep` -/ /-- This is similar to a monadic `bind` operator, except that the two type parameters have to be the same, which prevents putting a monad instance on `ForInStepT m α := m (ForInStep α)`. -/ @[inline] protected def ForInStep.bind [Monad m] (a : ForInStep α) (f : α → m (ForInStep α)) : m (ForInStep α) := match a with | .done a => return .done a | .yield a => f a @[inherit_doc ForInStep.bind] protected abbrev ForInStep.bindM [Monad m] (a : m (ForInStep α)) (f : α → m (ForInStep α)) : m (ForInStep α) := a >>= (·.bind f) /-- Get the value out of a `ForInStep`. This is usually done at the end of a `forIn` loop to scope the early exit to the loop body. -/ @[inline] def ForInStep.run : ForInStep α → α | .done a | .yield a => a /-- Applies function `f` to each element of a list to accumulate a `ForInStep` value. -/ def ForInStep.bindList [Monad m] (f : α → β → m (ForInStep β)) : List α → ForInStep β → m (ForInStep β) | [], s => pure s | a::l, s => s.bind fun b => f a b >>= (·.bindList f l)
.lake/packages/batteries/docs/README.md
# Batteries The "batteries included" extended library for Lean 4. This is a collection of data structures and tactics intended for use by both computer-science applications and mathematics applications of Lean 4. # Using `batteries` To use `batteries` in your project, add the following to your `lakefile.lean`: ```lean require "leanprover-community" / "batteries" @ git "main" ``` Or add the following to your `lakefile.toml`: ```toml [[require]] name = "batteries" scope = "leanprover-community" rev = "main" ``` Additionally, please make sure that you're using the version of Lean that the current version of `batteries` expects. The easiest way to do this is to copy the [`lean-toolchain`](./lean-toolchain) file from this repository to your project. Once you've added the dependency declaration, the command `lake update` checks out the current version of `batteries` and writes it the Lake manifest file. Don't run this command again unless you're prepared to potentially also update your Lean compiler version, as it will retrieve the latest version of dependencies and add them to the manifest. # Build instructions * Get the newest version of `elan`. If you already have installed a version of Lean, you can run ```sh elan self update ``` If the above command fails, or if you need to install `elan`, run ```sh curl https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh -sSf | sh ``` If this also fails, follow the instructions under `Regular install` [here](https://leanprover-community.github.io/get_started.html). * To build `batteries` run `lake build`. * To build and run all tests, run `lake test`. * To run the environment linter, run `lake lint`. * If you added a new file, run the command `scripts/updateBatteries.sh` to update the imports. # Documentation You can generate `batteries` documentation with ```sh cd docs lake build Batteries:docs ``` The top-level HTML file will be located at `docs/doc/index.html`, though to actually expose the documentation you need to run an HTTP server (e.g. `python3 -m http.server`) in the `docs/doc` directory. Note that documentation for the latest nightly of `batteries` is also available as part of [the Mathlib 4 documentation][mathlib4 docs]. [mathlib4 docs]: https://leanprover-community.github.io/mathlib4_docs/Batteries.html # Contributing The first step to contribute is to create a fork of Batteries. Then add your contributions to a branch of your fork and make a PR to Batteries. Do not make your changes to the main branch of your fork, that may lead to complications on your end. Every pull request should have exactly one of the status labels `awaiting-review`, `awaiting-author` or `WIP` (in progress). To change the status label of a pull request, add a comment containing one of these options and _nothing else_. This will remove the previous label and replace it by the requested status label. These labels are used for triage. One of the easiest ways to contribute is to find a missing proof and complete it. The [`proof_wanted`](https://github.com/search?q=repo%3Aleanprover-community%2Fbatteries+language%3ALean+%2F^proof_wanted%2F&type=code) declaration documents statements that have been identified as being useful, but that have not yet been proven. ### Mathlib Adaptations Batteries PRs often affect Mathlib, a key component of the Lean ecosystem. When Batteries changes in a significant way, Mathlib must adapt promptly. When necessary, Batteries contributors are expected to either create an adaptation PR on Mathlib, or ask for assistance for and to collaborate with this necessary process. Every Batteries PR has an automatically created [Mathlib Nightly Testing](https://github.com/leanprover-community/mathlib4-nightly-testing/) branch called `batteries-pr-testing-N` where `N` is the number of the Batteries PR. This is a clone of Mathlib where the Batteries requirement points to the Batteries PR branch instead of the main branch. Batteries uses this branch to check whether the Batteries PR needs Mathlib adaptations. A tag `builds-mathlib` will be issued when this branch needs no adaptation; a tag `breaks-mathlib` will be issued when the branch does need an adaptation. The first step in creating an adaptation PR is to switch to the `batteries-pr-testing-N` branch and push changes to that branch until the Mathlib CI process works. You may need to ask for write access to [Mathlib Nightly Testing](https://github.com/leanprover-community/mathlib4-nightly-testing/) to do that. Changes to the Batteries PR will be integrated automatically as you work on this process. Do not redirect the Batteries requirement to main until the Batteries PR is merged. Please ask questions to Batteries and Mathlib maintainers if you run into issues with this process. When everything works, create an adaptation PR on Mathlib from the `batteries-pr-testing-N` branch. You may need to ping a Mathlib maintainer to review the PR, ask if you don't know who to ping. Once the Mathlib adaptation PR and the original Batteries PR have been reviewed and accepted, the Batteries PR will be merged first. Then, the Mathlib PR's lakefile needs to be repointed to the Batteries main branch: change the Batteries line to ```lean require "leanprover-community" / "batteries" @ git "main" ``` Once CI once again checks out on Mathlib, the adaptation PR can be merged using the regular Mathlib process.
.lake/packages/batteries/scripts/check_imports.lean
import Batteries /-! This test checks that all directories in `Batteries/Data/` have corresponding `Batteries.Data.<dir>` modules imported by `Batteries` that import all of the submodules under that directory. It will also check that `Batteries` imports all the expected modules. It has a flag (`autofix` below) to automatically fix the errors found. This command may need to be rerun to fix all errors; it tries to avoid overwriting existing files. -/ open Lean System /-- Monad to log errors to stderr while record error count. -/ abbrev LogIO := StateRefT (Bool × Bool) IO def runLogIO (act : LogIO Unit) : MetaM Unit := do let ((), (warnings, _)) ← act.run (false, false) if warnings then throwError "Fatal error" def warn (fixable : Bool) (msg : String) : LogIO Unit := do modify (fun (_, u) => (true, u || not fixable)) liftM (IO.eprintln msg) -- | Predicate indicates if warnings are present and if they fixable. def getWarningInfo : LogIO (Bool × Bool) := get def createModuleHashmap (env : Environment) : Std.HashMap Name ModuleData := Id.run do let mut nameMap := {} for i in [0:env.header.moduleNames.size] do let nm := env.header.moduleNames[i]! let md := env.header.moduleData[i]! nameMap := nameMap.insert nm md pure nameMap /-- Get the imports we expect in a directory of `Batteries.Data`. -/ partial def addModulesIn (recurse : Bool) (prev : Array Name) (root : Name := .anonymous) (path : FilePath) : IO (Array Name) := do let mut r := prev for entry in ← path.readDir do if ← entry.path.isDir then if recurse then r ← addModulesIn recurse r (root.mkStr entry.fileName) entry.path else let .some mod := FilePath.fileStem entry.fileName | continue r := r.push (root.mkStr mod) pure r def modulePath (name : Name) : FilePath := let path := name.toString.replace "." FilePath.pathSeparator.toString s!"{path}.lean" def writeImportModule (path : FilePath) (imports : Array Name) : IO Unit := do let imports := imports.qsort (·.toString < ·.toString) let lines := imports.map (s!"public import {·}\n") let contents := String.join ("module\n" :: "\n" :: lines.toList) IO.println s!"Generating {path}" IO.FS.writeFile path contents /-- Check for imports and return true if warnings issued. -/ def checkMissingImports (modName : Name) (modData : ModuleData) (reqImports : Array Name) : LogIO Bool := do let names : Std.HashSet Name := Std.HashSet.ofArray (modData.imports.map (·.module)) let mut warned := false for req in reqImports do if !names.contains req then warn true s!"Missing import {req} in {modName}" warned := true pure warned /-- Check directory entry in `Batteries/Data/` -/ def checkBatteriesDataDir (modMap : Std.HashMap Name ModuleData) (entry : IO.FS.DirEntry) (autofix : Bool := false) : LogIO Unit := do let moduleName := `Batteries.Data ++ .mkSimple entry.fileName let requiredImports ← addModulesIn (recurse := true) #[] (root := moduleName) entry.path let .some module := modMap[moduleName]? | warn true s!"Could not find {moduleName}; Not imported into Batteries." let path := modulePath moduleName -- We refuse to generate imported modules whose path doesn't exist. -- The import failure will be fixed later and the file rerun if autofix then if ← path.pathExists then warn false s!"Skipping writing of {moduleName}: rerun after {moduleName} imported." else writeImportModule path requiredImports return let hasDecls : Bool := module.constants.size > 0 if hasDecls then warn false s!"Expected {moduleName} to not contain additional declarations.\n\ Declarations should be moved out.\n\ This error cannot be automatically fixed." let warned ← checkMissingImports moduleName module requiredImports if autofix && warned && !hasDecls then writeImportModule (modulePath moduleName) requiredImports /-- Compute imports expected by `Batteries.lean` -/ def expectedBatteriesImports : IO (Array Name) := do let mut needed := #[] for top in ← FilePath.readDir "Batteries" do if top.fileName == "Data" then needed ← addModulesIn (recurse := false) needed `Batteries.Data top.path else let nm := `Batteries let rootname := FilePath.withExtension top.fileName "" let root := nm.mkStr rootname.toString if ← top.path.isDir then needed ← addModulesIn (recurse := true) needed (root := root) top.path else needed := needed.push root pure needed def checkBatteriesDataImports : MetaM Unit := do -- N.B. This can be used to automatically fix Batteries.lean as well as -- other import files. -- It uses an environment variable to do that. -- The easiest way to use this is run `./scripts/updateBatteries.sh.` let autofix := (← IO.getEnv "__LEAN_BATTERIES_AUTOFIX_IMPORTS").isSome let env ← getEnv let modMap := createModuleHashmap env runLogIO do for entry in ← FilePath.readDir ("Batteries" / "Data") do if ← entry.path.isDir then checkBatteriesDataDir (autofix := autofix) modMap entry let batteriesImports ← expectedBatteriesImports let .some batteriesMod := modMap[`Batteries]? | warn false "Missing Batteries module!; Run `lake build`." let warned ← checkMissingImports `Batteries batteriesMod batteriesImports if autofix && warned then writeImportModule "Batteries.lean" batteriesImports match ← getWarningInfo with | (false, _) => pure () | (_, true) => IO.eprintln s!"Found errors that cannot be automatically fixed.\n\ Address unfixable issues and rerun lake build && ./scripts/updateBatteries.sh." | _ => if autofix then IO.eprintln s!"Found missing imports and attempted fixes.\n\ Run lake build && ./scripts/updateBatteries.sh to verify.\n\ Multiple runs may be needed." else IO.eprintln s!"Found missing imports.\n\ Run lake build && ./scripts/updateBatteries.sh to attempt automatic fixes." run_meta checkBatteriesDataImports
.lake/packages/batteries/scripts/runLinter.lean
import Batteries.Tactic.Lint import Batteries.Data.Array.Basic import Lake.CLI.Main open Lean Core Elab Command Batteries.Tactic.Lint open System (FilePath) /-- The list of `nolints` pulled from the `nolints.json` file -/ abbrev NoLints := Array (Name × Name) /-- Read the given file path and deserialize it as JSON. -/ def readJsonFile (α) [FromJson α] (path : System.FilePath) : IO α := do let _ : MonadExceptOf String IO := ⟨throw ∘ IO.userError, fun x _ => x⟩ liftExcept <| fromJson? <|← liftExcept <| Json.parse <|← IO.FS.readFile path /-- Serialize the given value `a : α` to the file as JSON. -/ def writeJsonFile [ToJson α] (path : System.FilePath) (a : α) : IO Unit := IO.FS.writeFile path <| toJson a |>.pretty.push '\n' open Lake /-- Returns the root modules of `lean_exe` or `lean_lib` default targets in the Lake workspace. -/ def resolveDefaultRootModules : IO (Array Name) := do -- load the Lake workspace let (elanInstall?, leanInstall?, lakeInstall?) ← findInstall? let config ← MonadError.runEIO <| mkLoadConfig { elanInstall?, leanInstall?, lakeInstall? } let some workspace ← loadWorkspace config |>.toBaseIO | throw <| IO.userError "failed to load Lake workspace" -- build an array of all root modules of `lean_exe` and `lean_lib` default targets let defaultTargetModules := workspace.root.defaultTargets.flatMap fun target => if let some lib := workspace.root.findLeanLib? target then lib.roots else if let some exe := workspace.root.findLeanExe? target then #[exe.config.root] else #[] return defaultTargetModules /-- Parse args list for `runLinter` and return a pair of the update and specified module arguments. Throws an exception if unable to parse the arguments. Returns `none` for the specified module if no module is specified.-/ def parseLinterArgs (args: List String) : Except String (Bool × Option Name) := let (update, moreArgs) := match args with | "--update" :: args => (true, args) | _ => (false, args) match moreArgs with | [] => Except.ok (update, none) | [mod] => match mod.toName with | .anonymous => Except.error "cannot convert module to Name" | name => Except.ok (update, some name) | _ => Except.error "cannot parse arguments" /-- Return an array of the modules to lint. If `specifiedModule` is not `none` return an array containing only `specifiedModule`. Otherwise, resolve the default root modules from the Lake workspace. -/ def determineModulesToLint (specifiedModule : Option Name) : IO (Array Name) := do match specifiedModule with | some module => println!"Running linter on specified module: {module}" return #[module] | none => println!"Automatically detecting modules to lint" let defaultModules ← resolveDefaultRootModules println!"Default modules: {defaultModules}" return defaultModules /-- Run the Batteries linter on a given module and update the linter if `update` is `true`. -/ unsafe def runLinterOnModule (update : Bool) (module : Name): IO Unit := do initSearchPath (← findSysroot) let mFile ← findOLean module unless (← mFile.pathExists) do -- run `lake build module` (and ignore result) if the file hasn't been built yet let child ← IO.Process.spawn { cmd := (← IO.getEnv "LAKE").getD "lake" args := #["build", s!"+{module}"] stdin := .null } _ ← child.wait -- If the linter is being run on a target that doesn't import `Batteries.Tactic.List`, -- the linters are ineffective. So we import it here. let lintModule := `Batteries.Tactic.Lint let lintFile ← findOLean lintModule unless (← lintFile.pathExists) do -- run `lake build +Batteries.Tactic.Lint` (and ignore result) if the file hasn't been built yet let child ← IO.Process.spawn { cmd := (← IO.getEnv "LAKE").getD "lake" args := #["build", s!"+{lintModule}"] stdin := .null } _ ← child.wait let nolintsFile : FilePath := "scripts/nolints.json" let nolints ← if ← nolintsFile.pathExists then readJsonFile NoLints nolintsFile else pure #[] unsafe Lean.enableInitializersExecution let env ← importModules #[module, lintModule] {} (trustLevel := 1024) (loadExts := true) let ctx := { fileName := "", fileMap := default } let state := { env } Prod.fst <$> (CoreM.toIO · ctx state) do let decls ← getDeclsInPackage module.getRoot let linters ← getChecks (slow := true) (runAlways := none) (runOnly := none) let results ← lintCore decls linters if update then writeJsonFile (α := NoLints) nolintsFile <| .qsort (lt := fun (a, b) (c, d) => a.lt c || (a == c && b.lt d)) <| .flatten <| results.map fun (linter, decls) => decls.fold (fun res decl _ => res.push (linter.name, decl)) #[] let results := results.map fun (linter, decls) => .mk linter <| nolints.foldl (init := decls) fun decls (linter', decl') => if linter.name == linter' then decls.erase decl' else decls let failed := results.any (!·.2.isEmpty) if failed then let fmtResults ← formatLinterResults results decls (groupByFilename := true) (useErrorFormat := true) s!"in {module}" (runSlowLinters := true) .medium linters.size IO.print (← fmtResults.toString) IO.Process.exit 1 else IO.println s!"-- Linting passed for {module}." /-- Usage: `runLinter [--update] [Batteries.Data.Nat.Basic]` Runs the linters on all declarations in the given module (or all root modules of Lake `lean_lib` and `lean_exe` default targets if no module is specified). If `--update` is set, the `nolints` file is updated to remove any declarations that no longer need to be nolinted. -/ unsafe def main (args : List String) : IO Unit := do let linterArgs := parseLinterArgs args let (update, specifiedModule) ← match linterArgs with | Except.ok args => pure args | Except.error msg => do IO.eprintln s!"Error parsing args: {msg}" IO.eprintln "Usage: runLinter [--update] [Batteries.Data.Nat.Basic]" IO.Process.exit 1 let modulesToLint ← determineModulesToLint specifiedModule modulesToLint.forM <| runLinterOnModule update
.lake/packages/batteries/BatteriesTest/String.lean
import Batteries.Data.String.AsciiCasing #guard "ABC".caseFoldAsciiOnly == "abc" #guard "x".caseFoldAsciiOnly != "y" #guard "Àà".caseFoldAsciiOnly == "Àà" #guard "1$#!".caseFoldAsciiOnly == "1$#!" #guard "abc".beqCaseInsensitiveAsciiOnly "ABC" == true #guard "cba".beqCaseInsensitiveAsciiOnly "ABC" == false #guard "a".beqCaseInsensitiveAsciiOnly "a" == true #guard "$".beqCaseInsensitiveAsciiOnly "$" == true #guard "a".beqCaseInsensitiveAsciiOnly "b" == false #guard "γ".beqCaseInsensitiveAsciiOnly "Γ" == false #guard "ä".beqCaseInsensitiveAsciiOnly "Ä" == false #guard "abc".cmpCaseInsensitiveAsciiOnly "ABC" == .eq #guard "abc".cmpCaseInsensitiveAsciiOnly "xyz" == .lt #guard "a".cmpCaseInsensitiveAsciiOnly "a" == .eq #guard "$".cmpCaseInsensitiveAsciiOnly "$" == .eq #guard "a__".cmpCaseInsensitiveAsciiOnly "b__" == .lt #guard "γ".cmpCaseInsensitiveAsciiOnly "Γ" == .gt #guard "ä".cmpCaseInsensitiveAsciiOnly "Ä" == .gt #guard [ ("", ""), (" ", " "), ("a", "A"), ("abc", "ABC"), ("aBc", "AbC"), ("123", "123"), ("国际化与本地化", "国际化与本地化"), ("ABC😂🔰🍑xyz", "abc😂🔰🍑XYZ") ].all (fun (a, b) => a.beqCaseInsensitiveAsciiOnly b && a.cmpCaseInsensitiveAsciiOnly b = .eq) #guard [ ("国际化", "国际化与本地化"), ("", " "), ("a", "b"), ("ab", "ba"), ("123", "124"), ("😂", "🍑"), ("🔰🍑", "😂🔰🍑aaa") ] |>.all fun (a, b) => a ≠ b && !(a.beqCaseInsensitiveAsciiOnly b) && a.cmpCaseInsensitiveAsciiOnly b != .eq
.lake/packages/batteries/BatteriesTest/norm_cast.lean
/-! # Tests for norm_cast involving `Rat`. -/ set_option linter.missingDocs false -- set_option trace.Meta.Tactic.simp true variable (aq bq cq dq : Rat) example : az = bz ↔ (az : Rat) = bz := by norm_cast -- zero and one cause special problems example : aq < (1 : Nat) ↔ (aq : Rat) < (1 : Int) := by norm_cast --testing numerals example : ((42 : Nat) : Rat) = 42 := by norm_cast example : ((42 : Int) : Rat) = 42 := by norm_cast -- We don't yet have `{n m : Int} : (↑n : Rat) ≤ ↑m ↔ n ≤ m` in Batteries -- example (n : Int) (h : n + 1 > 0) : ((n + 1 : Int) : Rat) > 0 := by exact_mod_cast h
.lake/packages/batteries/BatteriesTest/lint_lean.lean
import Batteries.Tactic.Lint /-! This test file runs the environment linters set up in Batteries on the core Lean4 repository. Everything is commented out as it is too slow to run in regular Batteries CI (and in any case there are many failures still), but it is useful to run locally to see what the linters would catch. -/ -- We can't apply `nolint` attributes to imported declarations, -- but if we move the environment linters up to Lean, -- these nolints should be installed there. -- (And in the meantime you can "manually" ignore them!) -- attribute [nolint dupNamespace] Lean.Elab.Tactic.Tactic -- attribute [nolint dupNamespace] Lean.Parser.Parser Lean.Parser.Parser.rec Lean.Parser.Parser.mk -- Lean.Parser.Parser.info Lean.Parser.Parser.fn -- attribute [nolint explicitVarsOfIff] Iff.refl /-! Failing lints that need work. -/ -- Many fixed in https://github.com/leanprover/lean4/pull/4620 and subsequent PRs -- and should be checked again. -- #lint only simpNF in all -- Found 22 errors /-! Lints that fail, but that we're not intending to do anything about. -/ -- Mostly fixed in https://github.com/leanprover/lean4/pull/4621 -- There are many false positives here. -- To run this properly we would need to ignore all declarations with `@[extern]`. -- #lint only unusedArguments in all -- Found 89 errors -- After https://github.com/leanprover/lean4/pull/4616, these are all intentional and have -- `nolint` attributes above. -- #lint only dupNamespace in all -- Found 6 errors -- After https://github.com/leanprover/lean4/pull/4619 all of these should be caused by `abbrev`. -- Unless we decide to upstream something like `alias`, we're not planning on fixing these. -- #lint only defLemma in all -- Found 31 errors /-! Lints that have succeeded in the past, and hopefully still do! -/ -- #lint only explicitVarsOfIff in all -- Found 1 errors, `Iff.refl`, which could be nolinted. -- #lint only impossibleInstance in all -- Found 0 errors -- #lint only simpVarHead in all -- Found 0 error -- #lint only unusedHavesSuffices in all -- Found 0 errors -- #lint only checkUnivs in all -- Found 0 errors
.lake/packages/batteries/BatteriesTest/instances.lean
import Batteries.Tactic.Instances set_option linter.missingDocs false /-- error: type class instance expected Fin 1 -/ #guard_msgs in #instances Fin 1 /-- info: 3 instances: instAddNat : Add Nat (prio 100) Lean.Grind.Semiring.toAdd.{u} {α : Type u} [self : Lean.Grind.Semiring α] : Add α (prio 100) Lean.Grind.AddCommMonoid.toAdd.{u} {M : Type u} [self : Lean.Grind.AddCommMonoid M] : Add M -/ #guard_msgs in #instances Add Nat namespace Testing class A (α : Type) /-- info: No instances -/ #guard_msgs in #instances A instance (priority := high) : A Nat := ⟨⟩ instance : A Int := ⟨⟩ instance : A Bool := ⟨⟩ /-- info: 3 instances: (prio 10000) Testing.instANat : A Nat Testing.instABool : A Bool Testing.instAInt : A Int -/ #guard_msgs in #instances A _ /-- info: 3 instances: (prio 10000) Testing.instANat : A Nat Testing.instABool : A Bool Testing.instAInt : A Int -/ #guard_msgs in #instances A /-- info: No instances -/ #guard_msgs in #instances (α : Type) → A α instance : A α := ⟨⟩ /-- info: 5 instances: (local) inst✝ : A β (prio 10000) Testing.instANat : A Nat Testing.instABool : A Bool Testing.instAInt : A Int Testing.instA {α : Type} : A α -/ #guard_msgs in #instances [A β] : A /-- info: 1 instance: Testing.instA {α : Type} : A α -/ #guard_msgs in #instances (α : Type) → A α end Testing