diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 58ca29d3d1..15d72c6876 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -18,10 +18,9 @@ jobs: - id: lean-action name: build, test, and lint batteries - uses: leanprover/lean-action@v1-beta + uses: leanprover/lean-action@v1 with: build-args: '-Kwerror' - lint-module: 'Batteries' - name: Check that all files are imported run: lake env lean scripts/check_imports.lean diff --git a/Batteries.lean b/Batteries.lean index f56659960b..8e1e6f1828 100644 --- a/Batteries.lean +++ b/Batteries.lean @@ -1,4 +1,3 @@ -import Batteries.Classes.BEq import Batteries.Classes.Cast import Batteries.Classes.Order import Batteries.Classes.RatCast @@ -15,6 +14,7 @@ import Batteries.Control.Lemmas import Batteries.Control.Nondet.Basic import Batteries.Data.Array import Batteries.Data.AssocList +import Batteries.Data.BinaryHeap import Batteries.Data.BinomialHeap import Batteries.Data.BitVec import Batteries.Data.Bool @@ -35,6 +35,7 @@ import Batteries.Data.Range import Batteries.Data.Rat import Batteries.Data.String import Batteries.Data.Sum +import Batteries.Data.Thunk import Batteries.Data.UInt import Batteries.Data.UnionFind import Batteries.Lean.AttributeExtra @@ -57,18 +58,15 @@ import Batteries.Lean.Meta.SavedState import Batteries.Lean.Meta.Simp import Batteries.Lean.Meta.UnusedNames import Batteries.Lean.MonadBacktrack -import Batteries.Lean.Name import Batteries.Lean.NameMap import Batteries.Lean.NameMapAttribute import Batteries.Lean.PersistentHashMap import Batteries.Lean.PersistentHashSet import Batteries.Lean.Position -import Batteries.Lean.SMap import Batteries.Lean.Syntax import Batteries.Lean.System.IO import Batteries.Lean.TagAttribute import Batteries.Lean.Util.EnvSearch -import Batteries.Lean.Util.Path import Batteries.Linter import Batteries.Linter.UnnecessarySeqFocus import Batteries.Linter.UnreachableTactic @@ -100,7 +98,6 @@ import Batteries.Tactic.Unreachable import Batteries.Tactic.Where import Batteries.Test.Internal.DummyLabelAttr import Batteries.Util.Cache -import Batteries.Util.CheckTactic import Batteries.Util.ExtendedBinder import Batteries.Util.LibraryNote import Batteries.Util.Pickle diff --git a/Batteries/Classes/BEq.lean b/Batteries/Classes/BEq.lean deleted file mode 100644 index 98318f97c9..0000000000 --- a/Batteries/Classes/BEq.lean +++ /dev/null @@ -1,18 +0,0 @@ -/- -Copyright (c) 2022 Mario Carneiro. All rights reserved. -Released under Apache 2.0 license as described in the file LICENSE. -Authors: Mario Carneiro --/ - -/-! ## Boolean equality -/ - -/-- `PartialEquivBEq α` says that the `BEq` implementation is a -partial equivalence relation, that is: -* it is symmetric: `a == b → b == a` -* it is transitive: `a == b → b == c → a == c`. --/ -class PartialEquivBEq (α) [BEq α] : Prop where - /-- Symmetry for `BEq`. If `a == b` then `b == a`. -/ - symm : (a : α) == b → b == a - /-- Transitivity for `BEq`. If `a == b` and `b == c` then `a == c`. -/ - trans : (a : α) == b → b == c → a == c diff --git a/Batteries/Classes/Order.lean b/Batteries/Classes/Order.lean index f54f82eb24..8cbfae25b0 100644 --- a/Batteries/Classes/Order.lean +++ b/Batteries/Classes/Order.lean @@ -102,7 +102,7 @@ theorem cmp_congr_left (xy : cmp x y = .eq) : cmp x z = cmp y z := theorem cmp_congr_left' (xy : cmp x y = .eq) : cmp x = cmp y := funext fun _ => cmp_congr_left xy -theorem cmp_congr_right [TransCmp cmp] (yz : cmp y z = .eq) : cmp x y = cmp x z := by +theorem cmp_congr_right (yz : cmp y z = .eq) : cmp x y = cmp x z := by rw [← Ordering.swap_inj, symm, symm, cmp_congr_left yz] end TransCmp diff --git a/Batteries/CodeAction/Deprecated.lean b/Batteries/CodeAction/Deprecated.lean index f308992885..ec6a2f11c2 100644 --- a/Batteries/CodeAction/Deprecated.lean +++ b/Batteries/CodeAction/Deprecated.lean @@ -32,7 +32,7 @@ def deprecatedCodeActionProvider : CodeActionProvider := fun params snap => do for m in snap.msgLog.toList do if m.data.isDeprecationWarning then if h : _ then - msgs := msgs.push (snap.cmdState.messages.toList[i]) + msgs := msgs.push (snap.cmdState.messages.toList[i]'h) i := i + 1 if msgs.isEmpty then return #[] let start := doc.meta.text.lspPosToUtf8Pos params.range.start diff --git a/Batteries/CodeAction/Misc.lean b/Batteries/CodeAction/Misc.lean index 1b5be55ce6..0bea77ff55 100644 --- a/Batteries/CodeAction/Misc.lean +++ b/Batteries/CodeAction/Misc.lean @@ -5,7 +5,6 @@ Authors: Mario Carneiro -/ import Lean.Elab.BuiltinTerm import Lean.Elab.BuiltinNotation -import Batteries.Lean.Name import Batteries.Lean.Position import Batteries.CodeAction.Attr import Lean.Meta.Tactic.TryThis diff --git a/Batteries/Data/Array/Basic.lean b/Batteries/Data/Array/Basic.lean index 1dddea3c14..ad6b8129e6 100644 --- a/Batteries/Data/Array/Basic.lean +++ b/Batteries/Data/Array/Basic.lean @@ -3,7 +3,6 @@ Copyright (c) 2021 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Arthur Paulino, Floris van Doorn, Jannis Limperg -/ -import Batteries.Data.List.Init.Attach import Batteries.Data.Array.Init.Lemmas /-! @@ -130,23 +129,6 @@ protected def maxI [ord : Ord α] [Inhabited α] (xs : Array α) (start := 0) (stop := xs.size) : α := xs.minI (ord := ord.opposite) start stop -/-- -Unsafe implementation of `attachWith`, taking advantage of the fact that the representation of -`Array {x // P x}` is the same as the input `Array α`. --/ -@[inline] private unsafe def attachWithImpl - (xs : Array α) (P : α → Prop) (_ : ∀ x ∈ xs, P x) : Array {x // P x} := unsafeCast xs - -/-- `O(1)`. "Attach" a proof `P x` that holds for all the elements of `xs` to produce a new array - with the same elements but in the type `{x // P x}`. -/ -@[implemented_by attachWithImpl] def attachWith - (xs : Array α) (P : α → Prop) (H : ∀ x ∈ xs, P x) : Array {x // P x} := - ⟨xs.data.attachWith P fun x h => H x (Array.Mem.mk h)⟩ - -/-- `O(1)`. "Attach" the proof that the elements of `xs` are in `xs` to produce a new array - with the same elements but in the type `{x // x ∈ xs}`. -/ -@[inline] def attach (xs : Array α) : Array {x // x ∈ xs} := xs.attachWith _ fun _ => id - /-- `O(|join L|)`. `join L` concatenates all the arrays in `L` into one array. * `join #[#[a], #[], #[b, c], #[d, e, f]] = #[a, b, c, d, e, f]` diff --git a/Batteries/Data/Array/Lemmas.lean b/Batteries/Data/Array/Lemmas.lean index 303acd40d9..bc401c197b 100644 --- a/Batteries/Data/Array/Lemmas.lean +++ b/Batteries/Data/Array/Lemmas.lean @@ -22,7 +22,7 @@ theorem forIn_eq_data_forIn [Monad m] have j_eq : j = size as - 1 - i := by simp [← ij, ← Nat.add_assoc] have : as.size - 1 - i < as.size := j_eq ▸ ij ▸ Nat.lt_succ_of_le (Nat.le_add_right ..) have : as[size as - 1 - i] :: as.data.drop (j + 1) = as.data.drop j := by - rw [j_eq]; exact List.get_cons_drop _ ⟨_, this⟩ + rw [j_eq]; exact List.getElem_cons_drop _ _ this simp only [← this, List.forIn_cons]; congr; funext x; congr; funext b rw [loop (i := i)]; rw [← ij, Nat.succ_add]; rfl conv => lhs; simp only [forIn, Array.forIn] @@ -64,12 +64,11 @@ theorem zipWith_eq_zipWith_data (f : α → β → γ) (as : Array α) (bs : Arr let i_bs : Fin bs.data.length := ⟨i, hbs⟩ rw [h₁, List.append_assoc] congr - rw [← List.zipWith_append (h := by simp), getElem_eq_data_get, getElem_eq_data_get] - show List.zipWith f ((List.get as.data i_as) :: List.drop (i_as + 1) as.data) + rw [← List.zipWith_append (h := by simp), getElem_eq_data_getElem, getElem_eq_data_getElem] + show List.zipWith f (as.data[i_as] :: List.drop (i_as + 1) as.data) ((List.get bs.data i_bs) :: List.drop (i_bs + 1) bs.data) = List.zipWith f (List.drop i as.data) (List.drop i bs.data) - simp only [List.get_cons_drop] - termination_by as.size - i + simp only [data_length, Fin.getElem_fin, List.getElem_cons_drop, List.get_eq_getElem] simp [zipWith, loop 0 #[] (by simp) (by simp)] theorem size_zipWith (as : Array α) (bs : Array β) (f : α → β → γ) : @@ -182,3 +181,22 @@ theorem size_shrink_loop (a : Array α) (n) : (shrink.loop n a).size = a.size - theorem size_shrink (a : Array α) (n) : (a.shrink n).size = min a.size n := by simp [shrink, size_shrink_loop] omega + +/-! ### map -/ + +theorem mapM_empty [Monad m] (f : α → m β) : mapM f #[] = pure #[] := by + rw [mapM, mapM.map]; rfl + +@[simp] theorem map_empty (f : α → β) : map f #[] = #[] := mapM_empty .. + +/-! ### mem -/ + +alias not_mem_empty := not_mem_nil + +theorem mem_singleton : a ∈ #[b] ↔ a = b := by simp + +/-! ### append -/ + +alias append_empty := append_nil + +alias empty_append := nil_append diff --git a/Batteries/Data/Array/Merge.lean b/Batteries/Data/Array/Merge.lean index 1486520565..aa83e0200b 100644 --- a/Batteries/Data/Array/Merge.lean +++ b/Batteries/Data/Array/Merge.lean @@ -27,7 +27,7 @@ where termination_by xs.size + ys.size - (i + j) set_option linter.unusedVariables false in -@[deprecated merge, inherit_doc merge] +@[deprecated merge (since := "2024-04-24"), inherit_doc merge] def mergeSortedPreservingDuplicates [ord : Ord α] (xs ys : Array α) : Array α := merge (compare · · |>.isLT) xs ys @@ -55,7 +55,7 @@ where | .eq => go (acc.push (merge x y)) (i + 1) (j + 1) termination_by xs.size + ys.size - (i + j) -@[deprecated] alias mergeSortedMergingDuplicates := mergeDedupWith +@[deprecated (since := "2024-04-24")] alias mergeSortedMergingDuplicates := mergeDedupWith /-- `O(|xs| + |ys|)`. Merge arrays `xs` and `ys`, which must be sorted according to `compare` and must @@ -64,7 +64,7 @@ not contain duplicates. If an element appears in both `xs` and `ys`, only one co @[inline] def mergeDedup [ord : Ord α] (xs ys : Array α) : Array α := mergeDedupWith (ord := ord) xs ys fun x _ => x -@[deprecated] alias mergeSortedDeduplicating := mergeDedup +@[deprecated (since := "2024-04-24")] alias mergeSortedDeduplicating := mergeDedup set_option linter.unusedVariables false in /-- @@ -83,7 +83,7 @@ where ys.foldl (init := xs) fun xs y => if xs.any (· == y) (stop := xsSize) then xs else xs.push y -@[deprecated] alias mergeUnsortedDeduplicating := mergeUnsortedDedup +@[deprecated (since := "2024-04-24")] alias mergeUnsortedDeduplicating := mergeUnsortedDedup /-- `O(|xs|)`. Replace each run `[x₁, ⋯, xₙ]` of equal elements in `xs` with @@ -101,7 +101,7 @@ where acc.push hd termination_by xs.size - i -@[deprecated] alias mergeAdjacentDuplicates := mergeAdjacentDups +@[deprecated (since := "2024-04-24")] alias mergeAdjacentDuplicates := mergeAdjacentDups /-- `O(|xs|)`. Deduplicate a sorted array. The array must be sorted with to an order which agrees with @@ -110,13 +110,13 @@ where def dedupSorted [eq : BEq α] (xs : Array α) : Array α := xs.mergeAdjacentDups (eq := eq) fun x _ => x -@[deprecated] alias deduplicateSorted := dedupSorted +@[deprecated (since := "2024-04-24")] alias deduplicateSorted := dedupSorted /-- `O(|xs| log |xs|)`. Sort and deduplicate an array. -/ def sortDedup [ord : Ord α] (xs : Array α) : Array α := have := ord.toBEq dedupSorted <| xs.qsort (compare · · |>.isLT) -@[deprecated] alias sortAndDeduplicate := sortDedup +@[deprecated (since := "2024-04-24")] alias sortAndDeduplicate := sortDedup end Array diff --git a/Batteries/Data/BinaryHeap.lean b/Batteries/Data/BinaryHeap.lean new file mode 100644 index 0000000000..b36ed97fd3 --- /dev/null +++ b/Batteries/Data/BinaryHeap.lean @@ -0,0 +1,176 @@ +/- +Copyright (c) 2021 Mario Carneiro. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE. +Authors: Mario Carneiro +-/ + +namespace Batteries + +/-- A max-heap data structure. -/ +structure BinaryHeap (α) (lt : α → α → Bool) where + /-- Backing array for `BinaryHeap`. -/ + arr : Array α + +namespace BinaryHeap + +/-- 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 : Array α) (i : Fin a.size) : + {a' : Array α // a'.size = a.size} := + let left := 2 * i.1 + 1 + let right := left + 1 + have left_le : i ≤ left := Nat.le_trans + (by rw [Nat.succ_mul, Nat.one_mul]; exact Nat.le_add_left i i) + (Nat.le_add_right ..) + have right_le : i ≤ right := Nat.le_trans left_le (Nat.le_add_right ..) + have i_le : i ≤ i := Nat.le_refl _ + have j : {j : Fin a.size // i ≤ j} := if h : left < a.size then + if lt (a.get i) (a.get ⟨left, h⟩) then ⟨⟨left, h⟩, left_le⟩ else ⟨i, i_le⟩ else ⟨i, i_le⟩ + have j := if h : right < a.size then + if lt (a.get j) (a.get ⟨right, h⟩) then ⟨⟨right, h⟩, right_le⟩ else j else j + if h : i.1 = j then ⟨a, rfl⟩ else + let a' := a.swap i j + let j' := ⟨j, by rw [a.size_swap i j]; exact j.1.2⟩ + have : a'.size - j < a.size - i := by + rw [a.size_swap i j]; exact Nat.sub_lt_sub_left i.2 <| Nat.lt_of_le_of_ne j.2 h + let ⟨a₂, h₂⟩ := heapifyDown lt a' j' + ⟨a₂, h₂.trans (a.size_swap i j)⟩ +termination_by a.size - i + +@[simp] theorem size_heapifyDown (lt : α → α → Bool) (a : Array α) (i : Fin a.size) : + (heapifyDown lt a i).1.size = a.size := (heapifyDown lt a i).2 + +/-- 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 : Array α) : {a' : Array α // a'.size = a.size} := + loop (a.size / 2) a (Nat.div_le_self ..) +where + /-- Inner loop for `mkHeap`. -/ + loop : (i : Nat) → (a : Array α) → i ≤ a.size → {a' : Array α // a'.size = a.size} + | 0, a, _ => ⟨a, rfl⟩ + | i+1, a, h => + let h := Nat.lt_of_succ_le h + let a' := heapifyDown lt a ⟨i, h⟩ + let ⟨a₂, h₂⟩ := loop i a' ((heapifyDown ..).2.symm ▸ Nat.le_of_lt h) + ⟨a₂, h₂.trans a'.2⟩ + +@[simp] theorem size_mkHeap (lt : α → α → Bool) (a : Array α) : + (mkHeap lt a).1.size = a.size := (mkHeap lt a).2 + +/-- 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 : Array α) (i : Fin a.size) : + {a' : Array α // a'.size = a.size} := + if i0 : i.1 = 0 then ⟨a, rfl⟩ else + have : (i.1 - 1) / 2 < i := Nat.lt_of_le_of_lt (Nat.div_le_self ..) <| + Nat.sub_lt (Nat.pos_of_ne_zero i0) Nat.zero_lt_one + let j := ⟨(i.1 - 1) / 2, Nat.lt_trans this i.2⟩ + if lt (a.get j) (a.get i) then + let a' := a.swap i j + let ⟨a₂, h₂⟩ := heapifyUp lt a' ⟨j.1, by rw [a.size_swap i j]; exact j.2⟩ + ⟨a₂, h₂.trans (a.size_swap i j)⟩ + else ⟨a, rfl⟩ + +@[simp] theorem size_heapifyUp (lt : α → α → Bool) (a : Array α) (i : Fin a.size) : + (heapifyUp lt a i).1.size = a.size := (heapifyUp lt a i).2 + +/-- `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 an element in the heap by index. -/ +def get (self : BinaryHeap α lt) (i : Fin self.size) : α := self.1.get i + +/-- `O(log n)`. Insert an element into a `BinaryHeap`, preserving the max-heap property. -/ +def insert (self : BinaryHeap α lt) (x : α) : BinaryHeap α lt where + arr := let n := self.size; + heapifyUp lt (self.1.push x) ⟨n, by rw [Array.size_push]; apply Nat.lt_succ_self⟩ + +@[simp] theorem size_insert (self : BinaryHeap α lt) (x : α) : + (self.insert x).size = self.size + 1 := by + simp [insert, size, size_heapifyUp] + +/-- `O(1)`. Get the maximum element in a `BinaryHeap`. -/ +def max (self : BinaryHeap α lt) : Option α := self.1.get? 0 + +/-- Auxiliary for `popMax`. -/ +def popMaxAux (self : BinaryHeap α lt) : {a' : BinaryHeap α lt // a'.size = self.size - 1} := + match e: self.1.size with + | 0 => ⟨self, by simp [size, e]⟩ + | n+1 => + have h0 := by rw [e]; apply Nat.succ_pos + have hn := by rw [e]; apply Nat.lt_succ_self + if hn0 : 0 < n then + let a := self.1.swap ⟨0, h0⟩ ⟨n, hn⟩ |>.pop + ⟨⟨heapifyDown lt a ⟨0, by rwa [Array.size_pop, Array.size_swap, e]⟩⟩, + by simp [size, a]⟩ + else + ⟨⟨self.1.pop⟩, by simp [size]⟩ + +/-- `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 := self.popMaxAux + +@[simp] theorem size_popMax (self : BinaryHeap α lt) : + self.popMax.size = self.size - 1 := self.popMaxAux.2 + +/-- `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} (e : self.max = some x) : 0 < self.size := + Decidable.of_not_not fun h : ¬ 0 < self.1.size => by simp [BinaryHeap.max, Array.get?, h] at e + +/-- `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 a := self.1.set ⟨0, size_pos_of_max e⟩ x + (m, ⟨heapifyDown lt a ⟨0, by simp only [Array.size_set, a]; exact size_pos_of_max e⟩⟩) + 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.1.push x⟩) + | some m => + let a := self.1.set ⟨0, size_pos_of_max e⟩ x + (some m, ⟨heapifyDown lt a ⟨0, by simp only [Array.size_set, a]; exact size_pos_of_max e⟩⟩) + +/-- `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.1.set i x) ⟨i, by rw [self.1.size_set]; exact i.2⟩ + +/-- `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.1.set i x) ⟨i, by rw [self.1.size_set]; exact i.2⟩ + +end Batteries.BinaryHeap + +/-- `O(n)`. Convert an unsorted array to a `BinaryHeap`. -/ +def Array.toBinaryHeap (lt : α → α → Bool) (a : Array α) : Batteries.BinaryHeap α lt where + arr := Batteries.BinaryHeap.mkHeap lt a + +/-- `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 diff --git a/Batteries/Data/BitVec/Lemmas.lean b/Batteries/Data/BitVec/Lemmas.lean index e0e45b8cb0..2bcd3ce4aa 100644 --- a/Batteries/Data/BitVec/Lemmas.lean +++ b/Batteries/Data/BitVec/Lemmas.lean @@ -7,13 +7,10 @@ import Batteries.Tactic.Alias namespace BitVec -/-- Replaced 2024-02-07. -/ -@[deprecated] alias zero_is_unique := eq_nil +@[deprecated (since := "2024-02-07")] alias zero_is_unique := eq_nil /-! ### sub/neg -/ -/-- Replaced 2024-02-06. -/ -@[deprecated] alias sub_toNat := toNat_sub +@[deprecated (since := "2024-02-07")] alias sub_toNat := toNat_sub -/-- Replaced 2024-02-06. -/ -@[deprecated] alias neg_toNat := toNat_neg +@[deprecated (since := "2024-02-07")] alias neg_toNat := toNat_neg diff --git a/Batteries/Data/Bool.lean b/Batteries/Data/Bool.lean index ab48cbc578..b6c0c9b4e7 100644 --- a/Batteries/Data/Bool.lean +++ b/Batteries/Data/Bool.lean @@ -10,10 +10,10 @@ namespace Bool /-! ### injectivity lemmas -/ -@[deprecated] alias not_inj' := not_inj_iff +@[deprecated (since := "2023-10-27")] alias not_inj' := not_inj_iff -@[deprecated] alias and_or_inj_right' := and_or_inj_right_iff +@[deprecated (since := "2023-10-27")] alias and_or_inj_right' := and_or_inj_right_iff -@[deprecated] alias and_or_inj_left' := and_or_inj_left_iff +@[deprecated (since := "2023-10-27")] alias and_or_inj_left' := and_or_inj_left_iff end Bool diff --git a/Batteries/Data/Char.lean b/Batteries/Data/Char.lean index c94b35ac44..4f3c59ef0b 100644 --- a/Batteries/Data/Char.lean +++ b/Batteries/Data/Char.lean @@ -4,11 +4,7 @@ Released under Apache 2.0 license as described in the file LICENSE. Authors: Jannis Limperg -/ import Batteries.Data.UInt - -@[ext] theorem Char.ext : {a b : Char} → a.val = b.val → a = b - | ⟨_,_⟩, ⟨_,_⟩, rfl => rfl - -theorem Char.ext_iff {x y : Char} : x = y ↔ x.val = y.val := ⟨congrArg _, Char.ext⟩ +import Batteries.Tactic.Alias theorem Char.le_antisymm_iff {x y : Char} : x = y ↔ x ≤ y ∧ y ≤ x := Char.ext_iff.trans UInt32.le_antisymm_iff @@ -21,16 +17,7 @@ instance : Batteries.LawfulOrd Char := .compareOfLessAndEq namespace String -private theorem csize_eq (c) : - csize c = 1 ∨ csize c = 2 ∨ csize c = 3 ∨ - csize c = 4 := by - simp only [csize, Char.utf8Size] - repeat (first | split | (solve | simp (config := {decide := true}))) - -theorem csize_pos (c) : 0 < csize c := by - rcases csize_eq c with _|_|_|_ <;> simp_all (config := {decide := true}) - -theorem csize_le_4 (c) : csize c ≤ 4 := by - rcases csize_eq c with _|_|_|_ <;> simp_all (config := {decide := true}) +@[deprecated (since := "2024-06-11")] alias csize_pos := Char.utf8Size_pos +@[deprecated (since := "2024-06-11")] alias csize_le_4 := Char.utf8Size_le_four end String diff --git a/Batteries/Data/Fin/Lemmas.lean b/Batteries/Data/Fin/Lemmas.lean index a310aa6f93..4d4eb59a1a 100644 --- a/Batteries/Data/Fin/Lemmas.lean +++ b/Batteries/Data/Fin/Lemmas.lean @@ -30,8 +30,13 @@ protected theorem le_antisymm {x y : Fin n} (h1 : x ≤ y) (h2 : y ≤ x) : x = @[simp] theorem length_list (n) : (list n).length = n := by simp [list] -@[simp] theorem get_list (i : Fin (list n).length) : (list n).get i = i.cast (length_list n) := by - cases i; simp only [list]; rw [← Array.getElem_eq_data_get, getElem_enum, cast_mk] +@[simp] theorem getElem_list (i : Nat) (h : i < (list n).length) : + (list n)[i] = cast (length_list n) ⟨i, h⟩ := by + simp only [list]; rw [← Array.getElem_eq_data_getElem, getElem_enum, cast_mk] + +@[deprecated getElem_list (since := "2024-06-12")] +theorem get_list (i : Fin (list n).length) : (list n).get i = i.cast (length_list n) := by + simp [getElem_list] @[simp] theorem list_zero : list 0 = [] := by simp [list] @@ -52,7 +57,7 @@ theorem list_reverse (n) : (list n).reverse = (list n).map rev := by | succ n ih => conv => lhs; rw [list_succ_last] conv => rhs; rw [list_succ] - simp [List.reverse_map, ih, Function.comp_def, rev_succ] + simp [← List.map_reverse, ih, Function.comp_def, rev_succ] /-! ### foldl -/ diff --git a/Batteries/Data/HashMap/Basic.lean b/Batteries/Data/HashMap/Basic.lean index 106fea1e4d..3419ba35ab 100644 --- a/Batteries/Data/HashMap/Basic.lean +++ b/Batteries/Data/HashMap/Basic.lean @@ -6,7 +6,6 @@ Authors: Leonardo de Moura, Mario Carneiro import Batteries.Data.AssocList import Batteries.Data.Nat.Basic import Batteries.Data.Array.Monadic -import Batteries.Classes.BEq namespace Batteries.HashMap diff --git a/Batteries/Data/HashMap/Lemmas.lean b/Batteries/Data/HashMap/Lemmas.lean index 50efb40455..290f4c0cff 100644 --- a/Batteries/Data/HashMap/Lemmas.lean +++ b/Batteries/Data/HashMap/Lemmas.lean @@ -5,7 +5,13 @@ Authors: Scott Morrison -/ import Batteries.Data.HashMap.Basic import Batteries.Data.Array.Lemmas -import Batteries.Util.ProofWanted + +/-! +# Lemmas for `Batteries.HashMap` + +Note that Lean core provides an alternative hash map implementation, `Std.HashMap`, which comes with +more lemmas. See the module `Std.Data.HashMap.Lemmas`. +-/ namespace Batteries.HashMap @@ -21,5 +27,7 @@ end Imp @[simp] theorem empty_find? [BEq α] [Hashable α] {a : α} : (∅ : HashMap α β).find? a = none := by simp [find?, Imp.find?] -proof_wanted insert_find? [BEq α] [Hashable α] (m : HashMap α β) (a a' : α) (b : β) : - (m.insert a b).find? a' = if a' == a then some b else m.find? a' +-- `Std.HashMap` has this lemma (as `getElem?_insert`) and many more, so working on this +-- `proof_wanted` is likely not a good use of your time. +-- proof_wanted insert_find? [BEq α] [Hashable α] (m : HashMap α β) (a a' : α) (b : β) : +-- (m.insert a b).find? a' = if a' == a then some b else m.find? a' diff --git a/Batteries/Data/HashMap/WF.lean b/Batteries/Data/HashMap/WF.lean index d535685691..e83e32e567 100644 --- a/Batteries/Data/HashMap/WF.lean +++ b/Batteries/Data/HashMap/WF.lean @@ -23,24 +23,27 @@ theorem update_data (self : Buckets α β) (i d h) : theorem exists_of_update (self : Buckets α β) (i d h) : ∃ l₁ l₂, self.1.data = l₁ ++ self.1[i] :: l₂ ∧ List.length l₁ = i.toNat ∧ (self.update i d h).1.data = l₁ ++ d :: l₂ := by - simp [Array.getElem_eq_data_get]; exact List.exists_of_set' h + simp only [Array.data_length, Array.ugetElem_eq_getElem, Array.getElem_eq_data_getElem] + exact List.exists_of_set h theorem update_update (self : Buckets α β) (i d d' h h') : (self.update i d h).update i d' h' = self.update i d' h := by - simp [update]; congr 1; rw [Array.set_set] + simp only [update, Array.uset, Array.data_length] + congr 1 + rw [Array.set_set] theorem size_eq (data : Buckets α β) : size data = .sum (data.1.data.map (·.toList.length)) := rfl theorem mk_size (h) : (mk n h : Buckets α β).size = 0 := by - simp [Buckets.size_eq, Buckets.mk, mkArray]; clear h - induction n <;> simp [*] + simp only [mk, mkArray, size_eq]; clear h + induction n <;> simp_all [List.replicate_succ] theorem WF.mk' [BEq α] [Hashable α] (h) : (Buckets.mk n h : Buckets α β).WF := by refine ⟨fun _ h => ?_, fun i h => ?_⟩ - · simp [Buckets.mk, empty', mkArray, List.mem_replicate] at h + · simp only [Buckets.mk, mkArray, List.mem_replicate, ne_eq] at h simp [h, List.Pairwise.nil] - · simp [Buckets.mk, empty', mkArray, Array.getElem_eq_data_get, AssocList.All] + · simp [Buckets.mk, empty', mkArray, Array.getElem_eq_data_getElem, AssocList.All] theorem WF.update [BEq α] [Hashable α] {buckets : Buckets α β} {i d h} (H : buckets.WF) (h₁ : ∀ [PartialEquivBEq α] [LawfulHashable α], @@ -53,16 +56,20 @@ theorem WF.update [BEq α] [Hashable α] {buckets : Buckets α β} {i d h} (H : · exact match List.mem_or_eq_of_mem_set hl with | .inl hl => H.1 _ hl | .inr rfl => h₁ (H.1 _ (Array.getElem_mem_data ..)) - · revert hp; simp [update_data, Array.getElem_eq_data_get, List.get_set] + · revert hp + simp only [Array.getElem_eq_data_getElem, update_data, List.getElem_set, Array.data_length, + update_size] split <;> intro hp · next eq => exact eq ▸ h₂ (H.2 _ _) _ hp - · simp at hi; exact H.2 i hi _ hp + · simp only [update_size, Array.data_length] at hi + exact H.2 i hi _ hp end Buckets theorem reinsertAux_size [Hashable α] (data : Buckets α β) (a : α) (b : β) : (reinsertAux data a b).size = data.size.succ := by - simp [Buckets.size_eq, reinsertAux] + simp only [reinsertAux, Array.data_length, Array.ugetElem_eq_getElem, Buckets.size_eq, + Nat.succ_eq_add_one] refine have ⟨l₁, l₂, h₁, _, eq⟩ := Buckets.exists_of_update ..; eq ▸ ?_ simp [h₁, Nat.succ_add]; rfl @@ -81,32 +88,35 @@ theorem expand_size [Hashable α] {buckets : Buckets α β} : · rw [Buckets.mk_size]; simp [Buckets.size] · nofun where - go (i source) (target : Buckets α β) (hs : ∀ j < i, source.data.getD j .nil = .nil) : + go (i source) (target : Buckets α β) (hs : ∀ j < i, source.data[j]?.getD .nil = .nil) : (expand.go i source target).size = .sum (source.data.map (·.toList.length)) + target.size := by unfold expand.go; split · next H => refine (go (i+1) _ _ fun j hj => ?a).trans ?b <;> simp · case a => - simp [List.getD_eq_get?, List.get?_set]; split - · cases List.get? .. <;> rfl + simp [List.getD_eq_getElem?_getD, List.getElem?_set, Option.map_eq_map]; split + · cases source.data[j]? <;> rfl · next H => exact hs _ (Nat.lt_of_le_of_ne (Nat.le_of_lt_succ hj) (Ne.symm H)) · case b => - refine have ⟨l₁, l₂, h₁, _, eq⟩ := List.exists_of_set' H; eq ▸ ?_ - simp [h₁, Buckets.size_eq] + refine have ⟨l₁, l₂, h₁, _, eq⟩ := List.exists_of_set H; eq ▸ ?_ + rw [h₁] + simp only [Buckets.size_eq, List.map_append, List.map_cons, AssocList.toList, + List.length_nil, Nat.sum_append, Nat.sum_cons, Nat.zero_add, Array.data_length] rw [Nat.add_assoc, Nat.add_assoc, Nat.add_assoc]; congr 1 (conv => rhs; rw [Nat.add_left_comm]); congr 1 - rw [← Array.getElem_eq_data_get] + rw [← Array.getElem_eq_data_getElem] have := @reinsertAux_size α β _; simp [Buckets.size] at this induction source[i].toList generalizing target <;> simp [*, Nat.succ_add]; rfl · next H => rw [(_ : Nat.sum _ = 0), Nat.zero_add] rw [← (_ : source.data.map (fun _ => .nil) = source.data)] - · simp; induction source.data <;> simp [*] - refine List.ext_get (by simp) fun j h₁ h₂ => ?_ - simp + · simp only [List.map_map] + induction source.data <;> simp [*] + refine List.ext_getElem (by simp) fun j h₁ h₂ => ?_ + simp only [List.getElem_map, Array.data_length] have := (hs j (Nat.lt_of_lt_of_le h₂ (Nat.not_lt.1 H))).symm - rwa [List.getD_eq_get?, List.get?_eq_get, Option.getD_some] at this + rwa [List.getElem?_eq_getElem] at this termination_by source.size - i theorem expand_WF.foldl [BEq α] [Hashable α] (rank : α → Nat) {l : List (α × β)} {i : Nat} @@ -126,7 +136,8 @@ theorem expand_WF.foldl [BEq α] [Hashable α] (rank : α → Nat) {l : List (α refine ih hl₁.2 hl₂.2 (reinsertAux_WF ht₁ fun _ h => (ht₂ _ (Array.getElem_mem_data ..) _ h).2.1) (fun _ h => ?_) - simp [reinsertAux, Buckets.update] at h + simp only [reinsertAux, Buckets.update, Array.uset, Array.data_length, + Array.ugetElem_eq_getElem, Array.data_set] at h match List.mem_or_eq_of_mem_set h with | .inl h => intro _ hf @@ -157,7 +168,9 @@ where · match List.mem_or_eq_of_mem_set hl with | .inl hl => exact hs₁ _ hl | .inr e => exact e ▸ .nil - · simp [Array.getElem_eq_data_get, List.get_set]; split + · simp only [Array.data_length, Array.size_set, Array.getElem_eq_data_getElem, Array.data_set, + List.getElem_set] + split · nofun · exact hs₂ _ (by simp_all) · let rank (k : α) := ((hash k).toUSize % source.size).toNat @@ -182,7 +195,7 @@ theorem insert_size [BEq α] [Hashable α] {m : Imp α β} {k v} · unfold Buckets.size refine have ⟨_, _, h₁, _, eq⟩ := Buckets.exists_of_update ..; eq ▸ ?_ simp [h, h₁, Buckets.size_eq, Nat.succ_add]; rfl - · rw [expand_size]; simp [h, expand, Buckets.size] + · rw [expand_size]; simp only [expand, h, Buckets.size, Array.data_length, Buckets.update_size] refine have ⟨_, _, h₁, _, eq⟩ := Buckets.exists_of_update ..; eq ▸ ?_ simp [h₁, Buckets.size_eq, Nat.succ_add]; rfl @@ -191,7 +204,8 @@ private theorem mem_replaceF {l : List (α × β)} {x : α × β} {p : α × β induction l with | nil => exact .inr | cons a l ih => - simp; generalize e : cond .. = z; revert e + simp only [List.replaceF, List.mem_cons] + generalize e : cond .. = z; revert e unfold cond; split <;> (intro h; subst h; simp) · intro | .inl eq => exact eq ▸ .inl rfl @@ -208,7 +222,7 @@ private theorem pairwise_replaceF [BEq α] [PartialEquivBEq α] induction l with | nil => simp [H] | cons a l ih => - simp at H ⊢ + simp only [List.pairwise_cons, List.replaceF] at H ⊢ generalize e : cond .. = z; unfold cond at e; revert e split <;> (intro h; subst h; simp) · next e => exact ⟨(H.1 · · ∘ PartialEquivBEq.trans e), H.2⟩ @@ -222,15 +236,17 @@ theorem insert_WF [BEq α] [Hashable α] {m : Imp α β} {k v} (h : m.buckets.WF) : (insert m k v).buckets.WF := by dsimp [insert, cond]; split · next h₁ => - simp at h₁; have ⟨x, hx₁, hx₂⟩ := h₁ + simp only [AssocList.contains_eq, List.any_eq_true] at h₁; have ⟨x, hx₁, hx₂⟩ := h₁ refine h.update (fun H => ?_) (fun H a h => ?_) - · simp; exact pairwise_replaceF H - · simp [AssocList.All] at H h ⊢ + · simp only [AssocList.toList_replace] + exact pairwise_replaceF H + · simp only [AssocList.All, Array.ugetElem_eq_getElem, AssocList.toList_replace] at H h ⊢ match mem_replaceF h with | .inl rfl => rfl | .inr h => exact H _ h · next h₁ => - rw [Bool.eq_false_iff] at h₁; simp at h₁ + rw [Bool.eq_false_iff] at h₁ + simp only [AssocList.contains_eq, ne_eq, List.any_eq_true, not_exists, not_and] at h₁ suffices _ by split <;> [exact this; refine expand_WF this] refine h.update (.cons ?_) (fun H a h => ?_) · exact fun a h h' => h₁ a h (PartialEquivBEq.symm h') @@ -243,12 +259,13 @@ theorem erase_size [BEq α] [Hashable α] {m : Imp α β} {k} (erase m k).size = (erase m k).buckets.size := by dsimp [erase, cond]; split · next H => - simp [h, Buckets.size] + simp only [h, Buckets.size] refine have ⟨_, _, h₁, _, eq⟩ := Buckets.exists_of_update ..; eq ▸ ?_ - simp [h, h₁, Buckets.size_eq] + simp only [h₁, Array.data_length, Array.ugetElem_eq_getElem, List.map_append, List.map_cons, + Nat.sum_append, Nat.sum_cons, AssocList.toList_erase] rw [(_ : List.length _ = _ + 1), Nat.add_right_comm]; {rfl} clear h₁ eq - simp [AssocList.contains_eq] at H + simp only [AssocList.contains_eq, List.any_eq_true] at H have ⟨a, h₁, h₂⟩ := H refine have ⟨_, _, _, _, _, h, eq⟩ := List.exists_of_eraseP h₁ h₂; eq ▸ ?_ simp [h]; rfl @@ -257,7 +274,7 @@ theorem erase_size [BEq α] [Hashable α] {m : Imp α β} {k} theorem erase_WF [BEq α] [Hashable α] {m : Imp α β} {k} (h : m.buckets.WF) : (erase m k).buckets.WF := by dsimp [erase, cond]; split - · refine h.update (fun H => ?_) (fun H a h => ?_) <;> simp at h ⊢ + · refine h.update (fun H => ?_) (fun H a h => ?_) <;> simp only [AssocList.toList_erase] at h ⊢ · exact H.sublist (List.eraseP_sublist _) · exact H _ (List.mem_of_mem_eraseP h) · exact h @@ -266,7 +283,7 @@ theorem modify_size [BEq α] [Hashable α] {m : Imp α β} {k} (h : m.size = m.buckets.size) : (modify m k f).size = (modify m k f).buckets.size := by dsimp [modify, cond]; rw [Buckets.update_update] - simp [h, Buckets.size] + simp only [h, Buckets.size] refine have ⟨_, _, h₁, _, eq⟩ := Buckets.exists_of_update ..; eq ▸ ?_ simp [h, h₁, Buckets.size_eq] @@ -275,7 +292,7 @@ theorem modify_WF [BEq α] [Hashable α] {m : Imp α β} {k} dsimp [modify, cond]; rw [Buckets.update_update] refine h.update (fun H => ?_) (fun H a h => ?_) <;> simp at h ⊢ · exact pairwise_replaceF H - · simp [AssocList.All] at H h ⊢ + · simp only [AssocList.All, Array.ugetElem_eq_getElem] at H h ⊢ match mem_replaceF h with | .inl rfl => rfl | .inr h => exact H _ h @@ -296,12 +313,13 @@ theorem WF_iff [BEq α] [Hashable α] {m : Imp α β} : theorem WF.mapVal {α β γ} {f : α → β → γ} [BEq α] [Hashable α] {m : Imp α β} (H : WF m) : WF (mapVal f m) := by have ⟨h₁, h₂⟩ := H.out - simp [Imp.mapVal, Buckets.mapVal, WF_iff, h₁]; refine ⟨?_, ?_, fun i h => ?_⟩ - · simp [Buckets.size]; congr; funext l; simp - · simp only [Array.map_data, List.forall_mem_map_iff] + simp only [Imp.mapVal, h₁, Buckets.mapVal, WF_iff]; refine ⟨?_, ?_, fun i h => ?_⟩ + · simp only [Buckets.size, Array.map_data, List.map_map]; congr; funext l; simp + · simp only [Array.map_data, List.forall_mem_map] simp only [AssocList.toList_mapVal, List.pairwise_map] exact fun _ => h₂.1 _ - · simp [AssocList.All] at h ⊢ + · simp only [Array.size_map, AssocList.All, Array.getElem_map, AssocList.toList_mapVal, + List.mem_map, forall_exists_index, and_imp, forall_apply_eq_imp_iff₂] at h ⊢ intro a m apply h₂.2 _ _ _ m @@ -310,10 +328,16 @@ theorem WF.filterMap {α β γ} {f : α → β → Option γ} [BEq α] [Hashable let g₁ (l : AssocList α β) := l.toList.filterMap (fun x => (f x.1 x.2).map (x.1, ·)) have H1 (l n acc) : filterMap.go f acc l n = (((g₁ l).reverse ++ acc.toList).toAssocList, ⟨n.1 + (g₁ l).length⟩) := by - induction l generalizing n acc with simp [filterMap.go, g₁, *] + induction l generalizing n acc with simp only [filterMap.go, AssocList.toList, + List.filterMap_nil, List.reverse_nil, List.nil_append, AssocList.toList_toAssocList, + List.length_nil, Nat.add_zero, List.filterMap_cons, g₁, *] | cons a b l => match f a b with | none => rfl - | some c => simp; rw [Nat.add_right_comm]; rfl + | some c => + simp only [Option.map_some', List.reverse_cons, List.append_assoc, List.singleton_append, + List.length_cons, Nat.succ_eq_add_one, Prod.mk.injEq, true_and] + rw [Nat.add_right_comm] + rfl let g l := (g₁ l).reverse.toAssocList let M := StateT (ULift Nat) Id have H2 (l : List (AssocList α β)) n : @@ -328,24 +352,25 @@ theorem WF.filterMap {α β γ} {f : α → β → Option γ} [BEq α] [Hashable induction l with | nil => exact .slnil | cons a l ih => - simp; exact match f a.1 a.2 with + simp only [List.filterMap_cons, List.map_cons]; exact match f a.1 a.2 with | none => .cons _ ih | some b => .cons₂ _ ih suffices ∀ bk sz (h : 0 < bk.length), m.buckets.val.mapM (m := M) (filterMap.go f .nil) ⟨0⟩ = (⟨bk⟩, ⟨sz⟩) → WF ⟨sz, ⟨bk⟩, h⟩ from this _ _ _ rfl - simp [Array.mapM_eq_mapM_data, bind, StateT.bind, H2, g] + simp only [Array.mapM_eq_mapM_data, bind, StateT.bind, H2, List.map_map, Nat.zero_add, g] intro bk sz h e'; cases e' refine .mk (by simp [Buckets.size]) ⟨?_, fun i h => ?_⟩ - · simp only [List.forall_mem_map_iff, List.toList_toAssocList] + · simp only [List.forall_mem_map, List.toList_toAssocList] refine fun l h => (List.pairwise_reverse.2 ?_).imp (mt PartialEquivBEq.symm) have := H.out.2.1 _ h rw [← List.pairwise_map (R := (¬ · == ·))] at this ⊢ exact this.sublist (H3 l.toList) - · simp only [Array.size_mk, List.length_map, Array.data_length, Array.getElem_eq_data_get, - List.get_map] at h ⊢ + · simp only [Array.size_mk, List.length_map, Array.data_length, Array.getElem_eq_data_getElem, + List.getElem_map] at h ⊢ have := H.out.2.2 _ h - simp [AssocList.All, g₁] at this ⊢ + simp only [AssocList.All, List.toList_toAssocList, List.mem_reverse, List.mem_filterMap, + Option.map_eq_some', forall_exists_index, and_imp, g₁] at this ⊢ rintro _ _ h' _ _ rfl exact this _ h' diff --git a/Batteries/Data/Int/Order.lean b/Batteries/Data/Int/Order.lean index 3855f19885..daab75c612 100644 --- a/Batteries/Data/Int/Order.lean +++ b/Batteries/Data/Int/Order.lean @@ -7,4 +7,4 @@ import Batteries.Tactic.Alias namespace Int -@[deprecated] alias ofNat_natAbs_eq_of_nonneg := natAbs_of_nonneg +@[deprecated (since := "2024-01-24")] alias ofNat_natAbs_eq_of_nonneg := natAbs_of_nonneg diff --git a/Batteries/Data/LazyList.lean b/Batteries/Data/LazyList.lean index 9deb41e77b..426cdd2248 100644 --- a/Batteries/Data/LazyList.lean +++ b/Batteries/Data/LazyList.lean @@ -1,12 +1,17 @@ /- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. -Authors: Leonardo de Moura +Authors: Leonardo de Moura, Simon Hudon -/ - +import Batteries.Data.Thunk /-! # Lazy lists +Deprecated. This module is deprecated and will be removed in the future. +Most use cases can use `MLList`. Without custom support from the kernel +(previously provided in Lean 3) this type is not very useful, +but was ported from Lean 3 anyway. + The type `LazyList α` is a lazy list with elements of type `α`. In the VM, these are potentially infinite lists where all elements after the first are computed on-demand. @@ -17,6 +22,7 @@ logically we can prove that `LazyList α` is isomorphic to `List α`.) /-- Lazy list. All elements (except the first) are computed lazily. -/ +@[deprecated "Consider using `MLList`." (since := "2024-07-15")] inductive LazyList (α : Type u) : Type u /-- The empty lazy list. -/ | nil : LazyList α @@ -24,6 +30,7 @@ inductive LazyList (α : Type u) : Type u | cons (hd : α) (tl : Thunk <| LazyList α) : LazyList α +set_option linter.deprecated false namespace LazyList @@ -117,4 +124,160 @@ partial def iterates (f : α → α) : α → LazyList α partial def iota (i : Nat) : LazyList Nat := iterates Nat.succ i + +instance decidableEq {α : Type u} [DecidableEq α] : DecidableEq (LazyList α) + | nil, nil => isTrue rfl + | cons x xs, cons y ys => + if h : x = y then + match decidableEq xs.get ys.get with + | isFalse h2 => by + apply isFalse; simp only [cons.injEq, not_and]; intro _ xs_ys; apply h2; rw [xs_ys] + | isTrue h2 => by apply isTrue; congr; ext; exact h2 + else by apply isFalse; simp only [cons.injEq, not_and]; intro; contradiction + | nil, cons _ _ => by apply isFalse; simp + | cons _ _, nil => by apply isFalse; simp + +/-- Traversal of lazy lists using an applicative effect. -/ +protected def traverse {m : Type u → Type u} [Applicative m] {α β : Type u} (f : α → m β) : + LazyList α → m (LazyList β) + | LazyList.nil => pure LazyList.nil + | LazyList.cons x xs => LazyList.cons <$> f x <*> Thunk.pure <$> xs.get.traverse f + +/-- `init xs`, if `xs` non-empty, drops the last element of the list. +Otherwise, return the empty list. -/ +def init {α} : LazyList α → LazyList α + | LazyList.nil => LazyList.nil + | LazyList.cons x xs => + let xs' := xs.get + match xs' with + | LazyList.nil => LazyList.nil + | LazyList.cons _ _ => LazyList.cons x (init xs') + +/-- Return the first object contained in the list that satisfies +predicate `p` -/ +def find {α} (p : α → Prop) [DecidablePred p] : LazyList α → Option α + | nil => none + | cons h t => if p h then some h else t.get.find p + +/-- `interleave xs ys` creates a list where elements of `xs` and `ys` alternate. -/ +def interleave {α} : LazyList α → LazyList α → LazyList α + | LazyList.nil, xs => xs + | a@(LazyList.cons _ _), LazyList.nil => a + | LazyList.cons x xs, LazyList.cons y ys => + LazyList.cons x (LazyList.cons y (interleave xs.get ys.get)) + +/-- `interleaveAll (xs::ys::zs::xss)` creates a list where elements of `xs`, `ys` +and `zs` and the rest alternate. Every other element of the resulting list is taken from +`xs`, every fourth is taken from `ys`, every eighth is taken from `zs` and so on. -/ +def interleaveAll {α} : List (LazyList α) → LazyList α + | [] => LazyList.nil + | x :: xs => interleave x (interleaveAll xs) + +/-- Monadic bind operation for `LazyList`. -/ +protected def bind {α β} : LazyList α → (α → LazyList β) → LazyList β + | LazyList.nil, _ => LazyList.nil + | LazyList.cons x xs, f => (f x).append (xs.get.bind f) + +/-- Reverse the order of a `LazyList`. +It is done by converting to a `List` first because reversal involves evaluating all +the list and if the list is all evaluated, `List` is a better representation for +it than a series of thunks. -/ +def reverse {α} (xs : LazyList α) : LazyList α := + ofList xs.toList.reverse + +instance : Monad LazyList where + pure := @LazyList.singleton + bind := @LazyList.bind + +-- Porting note: Added `Thunk.pure` to definition. +theorem append_nil {α} (xs : LazyList α) : xs.append (Thunk.pure LazyList.nil) = xs := by + induction xs using LazyList.rec with + | nil => simp only [Thunk.pure, append, Thunk.get] + | cons _ _ => simpa only [append, cons.injEq, true_and] + | mk _ ih => ext; apply ih + +theorem append_assoc {α} (xs ys zs : LazyList α) : + (xs.append ys).append zs = xs.append (ys.append zs) := by + induction xs using LazyList.rec with + | nil => simp only [append, Thunk.get] + | cons _ _ => simpa only [append, cons.injEq, true_and] + | mk _ ih => ext; apply ih + +-- Porting note: Rewrote proof of `append_bind`. +theorem append_bind {α β} (xs : LazyList α) (ys : Thunk (LazyList α)) (f : α → LazyList β) : + (xs.append ys).bind f = (xs.bind f).append (ys.get.bind f) := by + match xs with + | LazyList.nil => + simp only [append, Thunk.get, LazyList.bind] + | LazyList.cons x xs => + simp only [append, Thunk.get, LazyList.bind] + have := append_bind xs.get ys f + simp only [Thunk.get] at this + rw [this, append_assoc] + +-- TODO: upstream from mathlib +-- instance : LawfulMonad LazyList.{u} + +/-- Try applying function `f` to every element of a `LazyList` and +return the result of the first attempt that succeeds. -/ +def mfirst {m} [Alternative m] {α β} (f : α → m β) : LazyList α → m β + | nil => failure + | cons x xs => f x <|> xs.get.mfirst f + +/-- Membership in lazy lists -/ +protected def Mem {α} (x : α) : LazyList α → Prop + | nil => False + | cons y ys => x = y ∨ ys.get.Mem x + +instance {α} : Membership α (LazyList α) := + ⟨LazyList.Mem⟩ + +instance Mem.decidable {α} [DecidableEq α] (x : α) : ∀ xs : LazyList α, Decidable (x ∈ xs) + | LazyList.nil => by + apply Decidable.isFalse + simp [Membership.mem, LazyList.Mem] + | LazyList.cons y ys => + if h : x = y then by + apply Decidable.isTrue + simp only [Membership.mem, LazyList.Mem] + exact Or.inl h + else by + have := Mem.decidable x ys.get + have : (x ∈ ys.get) ↔ (x ∈ cons y ys) := by simp [(· ∈ ·), LazyList.Mem, h] + exact decidable_of_decidable_of_iff this + +@[simp] +theorem mem_nil {α} (x : α) : x ∈ @LazyList.nil α ↔ False := by + simp [Membership.mem, LazyList.Mem] + +@[simp] +theorem mem_cons {α} (x y : α) (ys : Thunk (LazyList α)) : + x ∈ @LazyList.cons α y ys ↔ x = y ∨ x ∈ ys.get := by + simp [Membership.mem, LazyList.Mem] + +theorem forall_mem_cons {α} {p : α → Prop} {a : α} {l : Thunk (LazyList α)} : + (∀ x ∈ @LazyList.cons _ a l, p x) ↔ p a ∧ ∀ x ∈ l.get, p x := by + simp only [Membership.mem, LazyList.Mem, or_imp, forall_and, forall_eq] + +/-! ### map for partial functions -/ + + +/-- Partial map. If `f : ∀ a, p a → β` is a partial function defined on + `a : α` satisfying `p`, then `pmap f l h` is essentially the same as `map f l` + but is defined only when all members of `l` satisfy `p`, using the proof + to apply `f`. -/ +@[simp] +def pmap {α β} {p : α → Prop} (f : ∀ a, p a → β) : ∀ l : LazyList α, (∀ a ∈ l, p a) → LazyList β + | LazyList.nil, _ => LazyList.nil + | LazyList.cons x xs, H => + LazyList.cons (f x (forall_mem_cons.1 H).1) (xs.get.pmap f (forall_mem_cons.1 H).2) + +/-- "Attach" the proof that the elements of `l` are in `l` to produce a new `LazyList` + with the same elements but in the type `{x // x ∈ l}`. -/ +def attach {α} (l : LazyList α) : LazyList { x // x ∈ l } := + pmap Subtype.mk l fun _ => id + +instance {α} [Repr α] : Repr (LazyList α) := + ⟨fun xs _ => repr xs.toList⟩ + end LazyList diff --git a/Batteries/Data/List.lean b/Batteries/Data/List.lean index d060ba89c8..998160b904 100644 --- a/Batteries/Data/List.lean +++ b/Batteries/Data/List.lean @@ -1,7 +1,6 @@ import Batteries.Data.List.Basic import Batteries.Data.List.Count import Batteries.Data.List.EraseIdx -import Batteries.Data.List.Init.Attach import Batteries.Data.List.Init.Lemmas import Batteries.Data.List.Lemmas import Batteries.Data.List.Pairwise diff --git a/Batteries/Data/List/Basic.lean b/Batteries/Data/List/Basic.lean index aacd1c9f2c..43915cd733 100644 --- a/Batteries/Data/List/Basic.lean +++ b/Batteries/Data/List/Basic.lean @@ -10,16 +10,6 @@ namespace List /-! ## New definitions -/ -/-- -`l₁ ⊆ l₂` means that every element of `l₁` is also an element of `l₂`, ignoring multiplicity. --/ -protected def Subset (l₁ l₂ : List α) := ∀ ⦃a : α⦄, a ∈ l₁ → a ∈ l₂ - -instance : HasSubset (List α) := ⟨List.Subset⟩ - -instance [DecidableEq α] : DecidableRel (Subset : List α → List α → Prop) := - fun _ _ => decidableBAll _ _ - /-- Computes the "bag intersection" of `l₁` and `l₂`, that is, the collection of elements of `l₁` which are also in `l₂`. As each element @@ -37,15 +27,6 @@ protected def diff {α} [BEq α] : List α → List α → List α open Option Nat -/-- Get the tail of a nonempty list, or return `[]` for `[]`. -/ -def tail : List α → List α - | [] => [] - | _::as => as - --- FIXME: `@[simp]` on the definition simplifies even `tail l` -@[simp] theorem tail_nil : @tail α [] = [] := rfl -@[simp] theorem tail_cons : @tail α (a::as) = as := rfl - /-- Get the head and tail of a list, if it is nonempty. -/ @[inline] def next? : List α → Option (α × List α) | [] => none @@ -83,19 +64,9 @@ drop_while (· != 1) [0, 1, 2, 3] = [1, 2, 3] | [] => [] | x :: xs => bif p x then xs else after p xs -/-- Returns the index of the first element satisfying `p`, or the length of the list otherwise. -/ -@[inline] def findIdx (p : α → Bool) (l : List α) : Nat := go l 0 where - /-- Auxiliary for `findIdx`: `findIdx.go p l n = findIdx p l + n` -/ - @[specialize] go : List α → Nat → Nat - | [], n => n - | a :: l, n => bif p a then n else go l (n + 1) - -/-- Returns the index of the first element equal to `a`, or the length of the list otherwise. -/ -def indexOf [BEq α] (a : α) : List α → Nat := findIdx (· == a) - -@[deprecated] alias removeNth := eraseIdx -@[deprecated] alias removeNthTR := eraseIdxTR -@[deprecated] alias removeNth_eq_removeNthTR := eraseIdx_eq_eraseIdxTR +@[deprecated (since := "2024-05-06")] alias removeNth := eraseIdx +@[deprecated (since := "2024-05-06")] alias removeNthTR := eraseIdxTR +@[deprecated (since := "2024-05-06")] alias removeNth_eq_removeNthTR := eraseIdx_eq_eraseIdxTR /-- Replaces the first element of the list for which `f` returns `some` with the returned value. -/ @[simp] def replaceF (f : α → Option α) : List α → List α @@ -139,26 +110,6 @@ Unlike `bagInter` this does not preserve multiplicity: `[1, 1].inter [1]` is `[1 instance [BEq α] : Inter (List α) := ⟨List.inter⟩ -/-- `l₁ <+ l₂`, or `Sublist l₁ l₂`, says that `l₁` is a (non-contiguous) subsequence of `l₂`. -/ -inductive Sublist {α} : List α → List α → Prop - /-- the base case: `[]` is a sublist of `[]` -/ - | slnil : Sublist [] [] - /-- If `l₁` is a subsequence of `l₂`, then it is also a subsequence of `a :: l₂`. -/ - | cons a : Sublist l₁ l₂ → Sublist l₁ (a :: l₂) - /-- If `l₁` is a subsequence of `l₂`, then `a :: l₁` is a subsequence of `a :: l₂`. -/ - | cons₂ a : Sublist l₁ l₂ → Sublist (a :: l₁) (a :: l₂) - -@[inherit_doc] scoped infixl:50 " <+ " => Sublist - -/-- True if the first list is a potentially non-contiguous sub-sequence of the second list. -/ -def isSublist [BEq α] : List α → List α → Bool - | [], _ => true - | _, [] => false - | l₁@(hd₁::tl₁), hd₂::tl₂ => - if hd₁ == hd₂ - then tl₁.isSublist tl₂ - else l₁.isSublist tl₂ - /-- Split a list at an index. ``` @@ -299,7 +250,7 @@ theorem insertNthTR_go_eq : ∀ n l, insertNthTR.go a n l acc = acc.data ++ inse @[csimp] theorem insertNth_eq_insertNthTR : @insertNth = @insertNthTR := by funext α f n l; simp [insertNthTR, insertNthTR_go_eq] -@[simp] theorem headD_eq_head? (l) (a : α) : headD l a = (head? l).getD a := by cases l <;> rfl +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` @@ -313,7 +264,8 @@ def takeD : Nat → List α → α → List α @[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 [*] +@[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 @@ -325,25 +277,12 @@ def takeDTR (n : Nat) (l : List α) (dflt : α) : List α := go n l #[] where theorem takeDTR_go_eq : ∀ n l, takeDTR.go dflt n l acc = acc.data ++ takeD n l dflt | 0, _ => by simp [takeDTR.go] - | _+1, [] => 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] -/-- -Pads `l : List α` with repeated occurrences of `a : α` until it is of length `n`. -If `l` is initially larger than `n`, just return `l`. --/ -def leftpad (n : Nat) (a : α) (l : List α) : List α := replicate (n - length l) a ++ l - -/-- Optimized version of `leftpad`. -/ -@[inline] def leftpadTR (n : Nat) (a : α) (l : List α) : List α := - replicateTR.loop a (n - length l) l - -@[csimp] theorem leftpad_eq_leftpadTR : @leftpad = @leftpadTR := by - funext α n a l; simp [leftpad, leftpadTR, replicateTR_loop_eq] - /-- Fold a function `f` over the list from the left, returning the list of partial results. ``` @@ -415,14 +354,6 @@ indexesOf a [a, b, a, a] = [0, 2, 3] -/ @[inline] def indexesOf [BEq α] (a : α) : List α → List Nat := findIdxs (· == a) -/-- Return the index of the first occurrence of an element satisfying `p`. -/ -def findIdx? (p : α → Bool) : List α → (start : Nat := 0) → Option Nat -| [], _ => none -| a :: l, i => if p a then some i else findIdx? p l (i + 1) - -/-- Return the index of the first occurrence of `a` in the list. -/ -@[inline] def indexOf? [BEq α] (a : α) : List α → Option Nat := findIdx? (· == a) - /-- `lookmap` is a combination of `lookup` and `filterMap`. `lookmap f l` will apply `f : α → Option α` to each element of the list, @@ -436,40 +367,6 @@ replacing `a → b` at the first value `a` in the list such that `f a = some b`. | some b => acc.toListAppend (b :: l) | none => go l (acc.push a) -/-- `countP p l` is the number of elements of `l` that satisfy `p`. -/ -@[inline] def countP (p : α → Bool) (l : List α) : Nat := go l 0 where - /-- Auxiliary for `countP`: `countP.go p l acc = countP p l + acc`. -/ - @[specialize] go : List α → Nat → Nat - | [], acc => acc - | x :: xs, acc => bif p x then go xs (acc + 1) else go xs acc - -/-- `count a l` is the number of occurrences of `a` in `l`. -/ -@[inline] def count [BEq α] (a : α) : List α → Nat := countP (· == a) - -/-- -`IsPrefix l₁ l₂`, or `l₁ <+: l₂`, means that `l₁` is a prefix of `l₂`, -that is, `l₂` has the form `l₁ ++ t` for some `t`. --/ -def IsPrefix (l₁ : List α) (l₂ : List α) : Prop := ∃ t, l₁ ++ t = l₂ - -/-- -`IsSuffix l₁ l₂`, or `l₁ <:+ l₂`, means that `l₁` is a suffix of `l₂`, -that is, `l₂` has the form `t ++ l₁` for some `t`. --/ -def IsSuffix (l₁ : List α) (l₂ : List α) : Prop := ∃ t, t ++ l₁ = l₂ - -/-- -`IsInfix l₁ l₂`, or `l₁ <:+: l₂`, means that `l₁` is a contiguous -substring of `l₂`, that is, `l₂` has the form `s ++ l₁ ++ t` for some `s, t`. --/ -def IsInfix (l₁ : List α) (l₂ : List α) : Prop := ∃ s t, s ++ l₁ ++ t = l₂ - -@[inherit_doc] infixl:50 " <+: " => IsPrefix - -@[inherit_doc] infixl:50 " <:+ " => IsSuffix - -@[inherit_doc] infixl:50 " <:+: " => IsInfix - /-- `inits l` is the list of initial segments of `l`. ``` @@ -485,7 +382,7 @@ 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 [*, reverse_map] + funext α l; simp [initsTR]; induction l <;> simp [*, map_reverse] /-- `tails l` is the list of terminal segments of `l`. @@ -658,29 +555,6 @@ theorem sections_eq_nil_of_isEmpty : ∀ {L}, L.any isEmpty → @sections α L = rw [Array.foldl_eq_foldl_data, Array.foldl_data_eq_bind]; rfl intros; apply Array.foldl_data_eq_map -/-- `eraseP p l` removes the first element of `l` satisfying the predicate `p`. -/ -def eraseP (p : α → Bool) : List α → List α - | [] => [] - | a :: l => bif p a then l else a :: eraseP p l - -/-- Tail-recursive version of `eraseP`. -/ -@[inline] def erasePTR (p : α → Bool) (l : List α) : List α := go l #[] where - /-- Auxiliary for `erasePTR`: `erasePTR.go p l xs acc = acc.toList ++ eraseP p xs`, - unless `xs` does not contain any elements satisfying `p`, where it returns `l`. -/ - @[specialize] go : List α → Array α → List α - | [], _ => l - | a :: l, acc => bif p a then acc.toListAppend l else go l (acc.push a) - -@[csimp] theorem eraseP_eq_erasePTR : @eraseP = @erasePTR := by - funext α p l; simp [erasePTR] - let rec go (acc) : ∀ xs, l = acc.data ++ xs → - erasePTR.go p l xs acc = acc.data ++ xs.eraseP p - | [] => fun h => by simp [erasePTR.go, eraseP, h] - | x::xs => by - simp [erasePTR.go, eraseP]; cases p x <;> simp - · intro h; rw [go _ xs]; {simp}; simp [h] - exact (go #[] _ rfl).symm - /-- `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)`. @@ -805,46 +679,6 @@ where rename_i a as b bs; unfold cond; cases R a b <;> simp [go as bs] exact (go as bs [] []).symm -section Pairwise - -variable (R : α → α → Prop) - -/-- -`Pairwise R l` means that all the elements with earlier indexes are -`R`-related to all the elements with later indexes. -``` -Pairwise R [1, 2, 3] ↔ R 1 2 ∧ R 1 3 ∧ R 2 3 -``` -For example if `R = (·≠·)` then it asserts `l` has no duplicates, -and if `R = (·<·)` then it asserts that `l` is (strictly) sorted. --/ -inductive Pairwise : List α → Prop - /-- All elements of the empty list are vacuously pairwise related. -/ - | nil : Pairwise [] - /-- `a :: l` is `Pairwise R` if `a` `R`-relates to every element of `l`, - and `l` is `Pairwise R`. -/ - | cons : ∀ {a : α} {l : List α}, (∀ a' ∈ l, R a a') → Pairwise l → Pairwise (a :: l) - -attribute [simp] Pairwise.nil - -variable {R} - -@[simp] theorem pairwise_cons : Pairwise R (a::l) ↔ (∀ a' ∈ l, R a a') ∧ Pairwise R l := - ⟨fun | .cons h₁ h₂ => ⟨h₁, h₂⟩, fun ⟨h₁, h₂⟩ => h₂.cons h₁⟩ - -instance instDecidablePairwise [DecidableRel R] : - (l : List α) → Decidable (Pairwise R l) - | [] => isTrue .nil - | hd :: tl => - match instDecidablePairwise tl with - | isTrue ht => - match decidableBAll (R hd) tl with - | isFalse hf => isFalse fun hf' => hf (pairwise_cons.1 hf').1 - | isTrue ht' => isTrue <| pairwise_cons.mpr (And.intro ht' ht) - | isFalse hf => isFalse fun | .cons _ ih => hf ih - -end Pairwise - /-- `pwFilter R l` is a maximal sublist of `l` which is `Pairwise R`. `pwFilter (·≠·)` is the erase duplicates function (cf. `eraseDup`), and `pwFilter (·<·)` finds @@ -880,52 +714,17 @@ def Chain' : List α → Prop end Chain -/-- `Nodup l` means that `l` has no duplicates, that is, any element appears at most - once in the List. It is defined as `Pairwise (≠)`. -/ -def Nodup : List α → Prop := Pairwise (· ≠ ·) - -instance nodupDecidable [DecidableEq α] : ∀ l : List α, Decidable (Nodup l) := - instDecidablePairwise - /-- `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 (· != ·) -/-- `range' start len step` is the list of numbers `[start, start+step, ..., start+(len-1)*step]`. - It is intended mainly for proving properties of `range` and `iota`. -/ -def range' : (start len : Nat) → (step : Nat := 1) → List Nat - | _, 0, _ => [] - | s, n+1, step => s :: range' (s+step) n step - -/-- Optimized version of `range'`. -/ -@[inline] def range'TR (s n : Nat) (step : Nat := 1) : List Nat := go n (s + step * n) [] where - /-- Auxiliary for `range'TR`: `range'TR.go n e = [e-n, ..., e-1] ++ acc`. -/ - go : Nat → Nat → List Nat → List Nat - | 0, _, acc => acc - | n+1, e, acc => go n (e-step) ((e-step) :: acc) - -@[csimp] theorem range'_eq_range'TR : @range' = @range'TR := by - funext s n step - let rec go (s) : ∀ n m, - range'TR.go step n (s + step * n) (range' (s + step * n) m step) = range' s (n + m) step - | 0, m => by simp [range'TR.go] - | n+1, m => by - simp [range'TR.go] - rw [Nat.mul_succ, ← Nat.add_assoc, Nat.add_sub_cancel, Nat.add_right_comm n] - exact go s n (m + 1) - exact (go s n 0).symm - -/-- Drop `none`s from a list, and replace each remaining `some a` with `a`. -/ -@[inline] def reduceOption {α} : List (Option α) → List α := - List.filterMap id - /-- `ilast' x xs` returns the last element of `xs` if `xs` is non-empty; it returns `x` otherwise. Use `List.getLastD` instead. -/ -@[simp, deprecated getLastD] def ilast' {α} : α → List α → α +@[simp, deprecated getLastD (since := "2024-01-09")] def ilast' {α} : α → List α → α | a, [] => a | _, b :: l => ilast' b l @@ -933,7 +732,7 @@ Use `List.getLastD` instead. `last' xs` returns the last element of `xs` if `xs` is non-empty; it returns `none` otherwise. Use `List.getLast?` instead -/ -@[simp, deprecated getLast?] def last' {α} : List α → Option α +@[simp, deprecated getLast? (since := "2024-01-09")] def last' {α} : List α → Option α | [] => none | [a] => some a | _ :: l => last' l diff --git a/Batteries/Data/List/Count.lean b/Batteries/Data/List/Count.lean index 81548ff437..036a76b4b8 100644 --- a/Batteries/Data/List/Count.lean +++ b/Batteries/Data/List/Count.lean @@ -19,111 +19,6 @@ open Nat namespace List -section countP - -variable (p q : α → Bool) - -@[simp] theorem countP_nil : countP p [] = 0 := rfl - -protected theorem countP_go_eq_add (l) : countP.go p l n = n + countP.go p l 0 := by - induction l generalizing n with - | nil => rfl - | cons head tail ih => - unfold countP.go - rw [ih (n := n + 1), ih (n := n), ih (n := 1)] - if h : p head then simp [h, Nat.add_assoc] else simp [h] - -@[simp] theorem countP_cons_of_pos (l) (pa : p a) : countP p (a :: l) = countP p l + 1 := by - have : countP.go p (a :: l) 0 = countP.go p l 1 := show cond .. = _ by rw [pa]; rfl - unfold countP - rw [this, Nat.add_comm, List.countP_go_eq_add] - -@[simp] theorem countP_cons_of_neg (l) (pa : ¬p a) : countP p (a :: l) = countP p l := by - simp [countP, countP.go, pa] - -theorem countP_cons (a : α) (l) : countP p (a :: l) = countP p l + if p a then 1 else 0 := by - by_cases h : p a <;> simp [h] - -theorem length_eq_countP_add_countP (l) : length l = countP p l + countP (fun a => ¬p a) l := by - induction l with - | nil => rfl - | cons x h ih => - if h : p x then - rw [countP_cons_of_pos _ _ h, countP_cons_of_neg _ _ _, length, ih] - · rw [Nat.add_assoc, Nat.add_comm _ 1, Nat.add_assoc] - · simp only [h, not_true_eq_false, decide_False, not_false_eq_true] - else - rw [countP_cons_of_pos (fun a => ¬p a) _ _, countP_cons_of_neg _ _ h, length, ih] - · rfl - · simp only [h, not_false_eq_true, decide_True] - -theorem countP_eq_length_filter (l) : countP p l = length (filter p l) := by - induction l with - | nil => rfl - | cons x l ih => - if h : p x - then rw [countP_cons_of_pos p l h, ih, filter_cons_of_pos l h, length] - else rw [countP_cons_of_neg p l h, ih, filter_cons_of_neg l h] - -theorem countP_le_length : countP p l ≤ l.length := by - simp only [countP_eq_length_filter] - apply length_filter_le - -@[simp] theorem countP_append (l₁ l₂) : countP p (l₁ ++ l₂) = countP p l₁ + countP p l₂ := by - simp only [countP_eq_length_filter, filter_append, length_append] - -theorem countP_pos : 0 < countP p l ↔ ∃ a ∈ l, p a := by - simp only [countP_eq_length_filter, length_pos_iff_exists_mem, mem_filter, exists_prop] - -theorem countP_eq_zero : countP p l = 0 ↔ ∀ a ∈ l, ¬p a := by - simp only [countP_eq_length_filter, length_eq_zero, filter_eq_nil] - -theorem countP_eq_length : countP p l = l.length ↔ ∀ a ∈ l, p a := by - rw [countP_eq_length_filter, filter_length_eq_length] - -theorem Sublist.countP_le (s : l₁ <+ l₂) : countP p l₁ ≤ countP p l₂ := by - simp only [countP_eq_length_filter] - apply s.filter _ |>.length_le - -theorem countP_filter (l : List α) : - countP p (filter q l) = countP (fun a => p a ∧ q a) l := by - simp only [countP_eq_length_filter, filter_filter] - -@[simp] theorem countP_true {l : List α} : (l.countP fun _ => true) = l.length := by - rw [countP_eq_length] - simp - -@[simp] theorem countP_false {l : List α} : (l.countP fun _ => false) = 0 := by - rw [countP_eq_zero] - simp - -@[simp] theorem countP_map (p : β → Bool) (f : α → β) : - ∀ l, countP p (map f l) = countP (p ∘ f) l - | [] => rfl - | a :: l => by rw [map_cons, countP_cons, countP_cons, countP_map p f l]; rfl - -variable {p q} - -theorem countP_mono_left (h : ∀ x ∈ l, p x → q x) : countP p l ≤ countP q l := by - induction l with - | nil => apply Nat.le_refl - | cons a l ihl => - rw [forall_mem_cons] at h - have ⟨ha, hl⟩ := h - simp [countP_cons] - cases h : p a - . simp - apply Nat.le_trans ?_ (Nat.le_add_right _ _) - apply ihl hl - . simp [ha h] - apply ihl hl - -theorem countP_congr (h : ∀ x ∈ l, p x ↔ q x) : countP p l = countP q l := - Nat.le_antisymm - (countP_mono_left fun x hx => (h x hx).1) - (countP_mono_left fun x hx => (h x hx).2) - -end countP /-! ### count -/ @@ -131,118 +26,14 @@ section count variable [DecidableEq α] -@[simp] theorem count_nil (a : α) : count a [] = 0 := rfl - -theorem count_cons (a b : α) (l : List α) : - count a (b :: l) = count a l + if a = b then 1 else 0 := by - simp [count, countP_cons, eq_comm (a := a)] - -@[simp] theorem count_cons_self (a : α) (l : List α) : count a (a :: l) = count a l + 1 := by - simp [count_cons] - -@[simp] theorem count_cons_of_ne (h : a ≠ b) (l : List α) : count a (b :: l) = count a l := by - simp [count_cons, h] - -theorem count_tail : ∀ (l : List α) (a : α) (h : l ≠ []), - l.tail.count a = l.count a - if a = l.head h then 1 else 0 - | head :: tail, a, h => by simp [count_cons] - -theorem count_le_length (a : α) (l : List α) : count a l ≤ l.length := countP_le_length _ - -theorem Sublist.count_le (h : l₁ <+ l₂) (a : α) : count a l₁ ≤ count a l₂ := h.countP_le _ - -theorem count_le_count_cons (a b : α) (l : List α) : count a l ≤ count a (b :: l) := - (sublist_cons _ _).count_le _ - -theorem count_singleton (a : α) : count a [a] = 1 := by simp - -theorem count_singleton' (a b : α) : count a [b] = if a = b then 1 else 0 := by simp [count_cons] - -@[simp] theorem count_append (a : α) : ∀ l₁ l₂, count a (l₁ ++ l₂) = count a l₁ + count a l₂ := - countP_append _ +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 -@[simp] -theorem count_pos_iff_mem {a : α} {l : List α} : 0 < count a l ↔ a ∈ l := by - simp only [count, countP_pos, beq_iff_eq, exists_eq_right] - -@[simp 900] theorem count_eq_zero_of_not_mem {a : α} {l : List α} (h : a ∉ l) : count a l = 0 := - Decidable.byContradiction fun h' => h <| count_pos_iff_mem.1 (Nat.pos_of_ne_zero h') - -theorem not_mem_of_count_eq_zero {a : α} {l : List α} (h : count a l = 0) : a ∉ l := - fun h' => Nat.ne_of_lt (count_pos_iff_mem.2 h') h.symm - -theorem count_eq_zero {l : List α} : count a l = 0 ↔ a ∉ l := - ⟨not_mem_of_count_eq_zero, count_eq_zero_of_not_mem⟩ - -theorem count_eq_length {l : List α} : count a l = l.length ↔ ∀ b ∈ l, a = b := by - rw [count, countP_eq_length] - refine ⟨fun h b hb => Eq.symm ?_, fun h b hb => ?_⟩ - · simpa using h b hb - · rw [h b hb, beq_self_eq_true] - -@[simp] theorem count_replicate_self (a : α) (n : Nat) : count a (replicate n a) = n := - (count_eq_length.2 <| fun _ h => (eq_of_mem_replicate h).symm).trans (length_replicate ..) - -theorem count_replicate (a b : α) (n : Nat) : count a (replicate n b) = if a = b then n else 0 := by - split - exacts [‹a = b› ▸ count_replicate_self .., count_eq_zero.2 <| mt eq_of_mem_replicate ‹a ≠ b›] - -theorem filter_beq (l : List α) (a : α) : l.filter (· == a) = replicate (count a l) a := by - simp only [count, countP_eq_length_filter, eq_replicate, mem_filter, beq_iff_eq] - exact ⟨trivial, fun _ h => h.2⟩ - -theorem filter_eq (l : List α) (a : α) : l.filter (· = a) = replicate (count a l) a := - filter_beq l a - -@[deprecated filter_eq] +@[deprecated filter_eq (since := "2023-12-14")] theorem filter_eq' (l : List α) (a : α) : l.filter (a = ·) = replicate (count a l) a := by simpa only [eq_comm] using filter_eq l a -@[deprecated filter_beq] +@[deprecated filter_beq (since := "2023-12-14")] theorem filter_beq' (l : List α) (a : α) : l.filter (a == ·) = replicate (count a l) a := by simpa only [eq_comm (b := a)] using filter_eq l a - -theorem le_count_iff_replicate_sublist {l : List α} : n ≤ count a l ↔ replicate n a <+ l := by - refine ⟨fun h => ?_, fun h => ?_⟩ - · exact ((replicate_sublist_replicate a).2 h).trans <| filter_eq l a ▸ filter_sublist _ - · simpa only [count_replicate_self] using h.count_le a - -theorem replicate_count_eq_of_count_eq_length {l : List α} (h : count a l = length l) : - replicate (count a l) a = l := - (le_count_iff_replicate_sublist.mp (Nat.le_refl _)).eq_of_length <| - (length_replicate (count a l) a).trans h - -@[simp] theorem count_filter {l : List α} (h : p a) : count a (filter p l) = count a l := by - rw [count, countP_filter]; congr; funext b - rw [(by rfl : (b == a) = decide (b = a)), decide_eq_decide] - simp; rintro rfl; exact h - -theorem count_le_count_map [DecidableEq β] (l : List α) (f : α → β) (x : α) : - count x l ≤ count (f x) (map f l) := by - rw [count, count, countP_map] - apply countP_mono_left; simp (config := { contextual := true }) - -theorem count_erase (a b : α) : - ∀ l : List α, count a (l.erase b) = count a l - if a = b then 1 else 0 - | [] => by simp - | c :: l => by - rw [erase_cons] - if hc : c = b then - have hc_beq := (beq_iff_eq _ _).mpr hc - rw [if_pos hc_beq, hc, count_cons, Nat.add_sub_cancel] - else - have hc_beq := beq_false_of_ne hc - simp only [hc_beq, if_false, count_cons, count_cons, count_erase a b l] - if ha : a = b then - rw [← ha, eq_comm] at hc - rw [if_pos ha, if_neg hc, Nat.add_zero, Nat.add_zero] - else - rw [if_neg ha, Nat.sub_zero, Nat.sub_zero] - -@[simp] theorem count_erase_self (a : α) (l : List α) : - count a (List.erase l a) = count a l - 1 := by rw [count_erase, if_pos rfl] - -@[simp] theorem count_erase_of_ne (ab : a ≠ b) (l : List α) : count a (l.erase b) = count a l := by - rw [count_erase, if_neg ab, Nat.sub_zero] diff --git a/Batteries/Data/List/EraseIdx.lean b/Batteries/Data/List/EraseIdx.lean index 31a595be57..42b4bfacd1 100644 --- a/Batteries/Data/List/EraseIdx.lean +++ b/Batteries/Data/List/EraseIdx.lean @@ -17,66 +17,18 @@ namespace List universe u v variable {α : Type u} {β : Type v} -@[simp] theorem eraseIdx_zero (l : List α) : eraseIdx l 0 = tail l := by cases l <;> rfl - -theorem eraseIdx_eq_take_drop_succ : - ∀ (l : List α) (i : Nat), l.eraseIdx i = l.take i ++ l.drop (i + 1) - | nil, _ => by simp - | a::l, 0 => by simp - | a::l, i + 1 => by simp [eraseIdx_eq_take_drop_succ l i] - -theorem eraseIdx_sublist : ∀ (l : List α) (k : Nat), eraseIdx l k <+ l - | [], _ => by simp - | a::l, 0 => by simp - | a::l, k + 1 => by simp [eraseIdx_sublist l k] - -theorem eraseIdx_subset (l : List α) (k : Nat) : eraseIdx l k ⊆ l := (eraseIdx_sublist l k).subset - -@[simp] -theorem eraseIdx_eq_self : ∀ {l : List α} {k : Nat}, eraseIdx l k = l ↔ length l ≤ k - | [], _ => by simp - | a::l, 0 => by simp [(cons_ne_self _ _).symm] - | a::l, k + 1 => by simp [eraseIdx_eq_self] - -alias ⟨_, eraseIdx_of_length_le⟩ := eraseIdx_eq_self - -theorem eraseIdx_append_of_lt_length {l : List α} {k : Nat} (hk : k < length l) (l' : List α) : - eraseIdx (l ++ l') k = eraseIdx l k ++ l' := by - rw [eraseIdx_eq_take_drop_succ, take_append_of_le_length, drop_append_of_le_length, - eraseIdx_eq_take_drop_succ, append_assoc] - all_goals omega - -theorem eraseIdx_append_of_length_le {l : List α} {k : Nat} (hk : length l ≤ k) (l' : List α) : - eraseIdx (l ++ l') k = l ++ eraseIdx l' (k - length l) := by - rw [eraseIdx_eq_take_drop_succ, eraseIdx_eq_take_drop_succ, - take_append_eq_append_take, drop_append_eq_append_drop, - take_all_of_le hk, drop_eq_nil_of_le (by omega), nil_append, append_assoc] - congr - omega - -protected theorem IsPrefix.eraseIdx {l l' : List α} (h : l <+: l') (k : Nat) : - eraseIdx l k <+: eraseIdx l' k := by - rcases h with ⟨t, rfl⟩ - if hkl : k < length l then - simp [eraseIdx_append_of_lt_length hkl] - else - rw [Nat.not_lt] at hkl - simp [eraseIdx_append_of_length_le hkl, eraseIdx_of_length_le hkl] - -theorem mem_eraseIdx_iff_get {x : α} : - ∀ {l} {k}, x ∈ eraseIdx l k ↔ ∃ i : Fin l.length, ↑i ≠ k ∧ l.get i = x - | [], _ => by - simp only [eraseIdx, Fin.exists_iff, not_mem_nil, false_iff] - rintro ⟨i, h, -⟩ - exact Nat.not_lt_zero _ h - | a::l, 0 => by simp [Fin.exists_fin_succ, mem_iff_get] - | a::l, k+1 => by - simp [Fin.exists_fin_succ, mem_eraseIdx_iff_get, @eq_comm _ a, k.succ_ne_zero.symm] - +@[deprecated mem_eraseIdx_iff_getElem (since := "2024-06-12")] +theorem mem_eraseIdx_iff_get {x : α} {l} {k} : + x ∈ eraseIdx l k ↔ ∃ i : Fin l.length, ↑i ≠ k ∧ l.get i = x := by + simp only [mem_eraseIdx_iff_getElem, ne_eq, exists_and_left, get_eq_getElem] + constructor + · rintro ⟨i, h, w, rfl⟩ + exact ⟨⟨i, w⟩, h, rfl⟩ + · rintro ⟨i, h, rfl⟩ + exact ⟨i.1, h, i.2, rfl⟩ + +@[deprecated mem_eraseIdx_iff_getElem? (since := "2024-06-12")] theorem mem_eraseIdx_iff_get? {x : α} {l} {k} : x ∈ eraseIdx l k ↔ ∃ i ≠ k, l.get? i = x := by - simp only [mem_eraseIdx_iff_get, Fin.exists_iff, exists_and_left, get_eq_iff, exists_prop] - refine exists_congr fun i => and_congr_right' <| and_iff_right_of_imp fun h => ?_ - obtain ⟨h, -⟩ := get?_eq_some.1 h - exact h + simp [mem_eraseIdx_iff_getElem?] end List diff --git a/Batteries/Data/List/Init/Attach.lean b/Batteries/Data/List/Init/Attach.lean deleted file mode 100644 index d2b2bf0990..0000000000 --- a/Batteries/Data/List/Init/Attach.lean +++ /dev/null @@ -1,44 +0,0 @@ -/- -Copyright (c) 2023 Mario Carneiro. All rights reserved. -Released under Apache 2.0 license as described in the file LICENSE. -Authors: Mario Carneiro --/ - -namespace List - -/-- `O(n)`. Partial map. If `f : Π a, P a → β` is a partial function defined on - `a : α` satisfying `P`, then `pmap f l h` is essentially the same as `map f l` - but is defined only when all members of `l` satisfy `P`, using the proof - to apply `f`. -/ -@[simp] def pmap {P : α → Prop} (f : ∀ a, P a → β) : ∀ l : List α, (H : ∀ a ∈ l, P a) → List β - | [], _ => [] - | a :: l, H => f a (forall_mem_cons.1 H).1 :: pmap f l (forall_mem_cons.1 H).2 - -/-- -Unsafe implementation of `attachWith`, taking advantage of the fact that the representation of -`List {x // P x}` is the same as the input `List α`. -(Someday, the compiler might do this optimization automatically, but until then...) --/ -@[inline] private unsafe def attachWithImpl - (l : List α) (P : α → Prop) (_ : ∀ x ∈ l, P x) : List {x // P x} := unsafeCast l - -/-- `O(1)`. "Attach" a proof `P x` that holds for all the elements of `l` to produce a new list - with the same elements but in the type `{x // P x}`. -/ -@[implemented_by attachWithImpl] def attachWith - (l : List α) (P : α → Prop) (H : ∀ x ∈ l, P x) : List {x // P x} := pmap Subtype.mk l H - -/-- `O(1)`. "Attach" the proof that the elements of `l` are in `l` to produce a new list - with the same elements but in the type `{x // x ∈ l}`. -/ -@[inline] def attach (l : List α) : List {x // x ∈ l} := attachWith l _ fun _ => id - -/-- Implementation of `pmap` using the zero-copy version of `attach`. -/ -@[inline] private def pmapImpl {P : α → Prop} (f : ∀ a, P a → β) (l : List α) (H : ∀ a ∈ l, P a) : - List β := (l.attachWith _ H).map fun ⟨x, h'⟩ => f x h' - -@[csimp] private theorem pmap_eq_pmapImpl : @pmap = @pmapImpl := by - funext α β p f L h' - let rec go : ∀ L' (hL' : ∀ ⦃x⦄, x ∈ L' → p x), - pmap f L' hL' = map (fun ⟨x, hx⟩ => f x hx) (pmap Subtype.mk L' hL') - | nil, hL' => rfl - | cons _ L', hL' => congrArg _ <| go L' fun _ hx => hL' (.tail _ hx) - exact go L h' diff --git a/Batteries/Data/List/Lemmas.lean b/Batteries/Data/List/Lemmas.lean index 32a4ab6ccc..829674c771 100644 --- a/Batteries/Data/List/Lemmas.lean +++ b/Batteries/Data/List/Lemmas.lean @@ -17,225 +17,6 @@ open Nat @[simp] theorem mem_toArray {a : α} {l : List α} : a ∈ l.toArray ↔ a ∈ l := by simp [Array.mem_def] -/-! ### drop -/ - -@[simp] -theorem drop_one : ∀ l : List α, drop 1 l = tail l - | [] | _ :: _ => rfl - -/-! ### zipWith -/ - -theorem zipWith_distrib_tail : (zipWith f l l').tail = zipWith f l.tail l'.tail := by - rw [← drop_one]; simp [zipWith_distrib_drop] - -/-! ### List subset -/ - -theorem subset_def {l₁ l₂ : List α} : l₁ ⊆ l₂ ↔ ∀ {a : α}, a ∈ l₁ → a ∈ l₂ := .rfl - -@[simp] theorem nil_subset (l : List α) : [] ⊆ l := nofun - -@[simp] theorem Subset.refl (l : List α) : l ⊆ l := fun _ i => i - -theorem Subset.trans {l₁ l₂ l₃ : List α} (h₁ : l₁ ⊆ l₂) (h₂ : l₂ ⊆ l₃) : l₁ ⊆ l₃ := - fun _ i => h₂ (h₁ i) - -instance : Trans (Membership.mem : α → List α → Prop) Subset Membership.mem := - ⟨fun h₁ h₂ => h₂ h₁⟩ - -instance : Trans (Subset : List α → List α → Prop) Subset Subset := - ⟨Subset.trans⟩ - -@[simp] theorem subset_cons (a : α) (l : List α) : l ⊆ a :: l := fun _ => Mem.tail _ - -theorem subset_of_cons_subset {a : α} {l₁ l₂ : List α} : a :: l₁ ⊆ l₂ → l₁ ⊆ l₂ := - fun s _ i => s (mem_cons_of_mem _ i) - -theorem subset_cons_of_subset (a : α) {l₁ l₂ : List α} : l₁ ⊆ l₂ → l₁ ⊆ a :: l₂ := - fun s _ i => .tail _ (s i) - -theorem cons_subset_cons {l₁ l₂ : List α} (a : α) (s : l₁ ⊆ l₂) : a :: l₁ ⊆ a :: l₂ := - fun _ => by simp only [mem_cons]; exact Or.imp_right (@s _) - -@[simp] theorem subset_append_left (l₁ l₂ : List α) : l₁ ⊆ l₁ ++ l₂ := fun _ => mem_append_left _ - -@[simp] theorem subset_append_right (l₁ l₂ : List α) : l₂ ⊆ l₁ ++ l₂ := fun _ => mem_append_right _ - -theorem subset_append_of_subset_left (l₂ : List α) : l ⊆ l₁ → l ⊆ l₁ ++ l₂ := -fun s => Subset.trans s <| subset_append_left _ _ - -theorem subset_append_of_subset_right (l₁ : List α) : l ⊆ l₂ → l ⊆ l₁ ++ l₂ := -fun s => Subset.trans s <| subset_append_right _ _ - -@[simp] theorem cons_subset : a :: l ⊆ m ↔ a ∈ m ∧ l ⊆ m := by - simp only [subset_def, mem_cons, or_imp, forall_and, forall_eq] - -@[simp] theorem append_subset {l₁ l₂ l : List α} : - l₁ ++ l₂ ⊆ l ↔ l₁ ⊆ l ∧ l₂ ⊆ l := by simp [subset_def, or_imp, forall_and] - -theorem subset_nil {l : List α} : l ⊆ [] ↔ l = [] := - ⟨fun h => match l with | [] => rfl | _::_ => (nomatch h (.head ..)), fun | rfl => Subset.refl _⟩ - -theorem map_subset {l₁ l₂ : List α} (f : α → β) (H : l₁ ⊆ l₂) : map f l₁ ⊆ map f l₂ := - fun x => by simp only [mem_map]; exact .imp fun a => .imp_left (@H _) - -/-! ### sublists -/ - -@[simp] theorem nil_sublist : ∀ l : List α, [] <+ l - | [] => .slnil - | a :: l => (nil_sublist l).cons a - -@[simp] theorem Sublist.refl : ∀ l : List α, l <+ l - | [] => .slnil - | a :: l => (Sublist.refl l).cons₂ a - -theorem Sublist.trans {l₁ l₂ l₃ : List α} (h₁ : l₁ <+ l₂) (h₂ : l₂ <+ l₃) : l₁ <+ l₃ := by - induction h₂ generalizing l₁ with - | slnil => exact h₁ - | cons _ _ IH => exact (IH h₁).cons _ - | @cons₂ l₂ _ a _ IH => - generalize e : a :: l₂ = l₂' - match e ▸ h₁ with - | .slnil => apply nil_sublist - | .cons a' h₁' => cases e; apply (IH h₁').cons - | .cons₂ a' h₁' => cases e; apply (IH h₁').cons₂ - -instance : Trans (@Sublist α) Sublist Sublist := ⟨Sublist.trans⟩ - -@[simp] theorem sublist_cons (a : α) (l : List α) : l <+ a :: l := (Sublist.refl l).cons _ - -theorem sublist_of_cons_sublist : a :: l₁ <+ l₂ → l₁ <+ l₂ := - (sublist_cons a l₁).trans - -@[simp] theorem sublist_append_left : ∀ l₁ l₂ : List α, l₁ <+ l₁ ++ l₂ - | [], _ => nil_sublist _ - | _ :: l₁, l₂ => (sublist_append_left l₁ l₂).cons₂ _ - -@[simp] theorem sublist_append_right : ∀ l₁ l₂ : List α, l₂ <+ l₁ ++ l₂ - | [], _ => Sublist.refl _ - | _ :: l₁, l₂ => (sublist_append_right l₁ l₂).cons _ - -theorem sublist_append_of_sublist_left (s : l <+ l₁) : l <+ l₁ ++ l₂ := - s.trans <| sublist_append_left .. - -theorem sublist_append_of_sublist_right (s : l <+ l₂) : l <+ l₁ ++ l₂ := - s.trans <| sublist_append_right .. - -@[simp] -theorem cons_sublist_cons : a :: l₁ <+ a :: l₂ ↔ l₁ <+ l₂ := - ⟨fun | .cons _ s => sublist_of_cons_sublist s | .cons₂ _ s => s, .cons₂ _⟩ - -@[simp] theorem append_sublist_append_left : ∀ l, l ++ l₁ <+ l ++ l₂ ↔ l₁ <+ l₂ - | [] => Iff.rfl - | _ :: l => cons_sublist_cons.trans (append_sublist_append_left l) - -theorem Sublist.append_left : l₁ <+ l₂ → ∀ l, l ++ l₁ <+ l ++ l₂ := - fun h l => (append_sublist_append_left l).mpr h - -theorem Sublist.append_right : l₁ <+ l₂ → ∀ l, l₁ ++ l <+ l₂ ++ l - | .slnil, _ => Sublist.refl _ - | .cons _ h, _ => (h.append_right _).cons _ - | .cons₂ _ h, _ => (h.append_right _).cons₂ _ - -theorem sublist_or_mem_of_sublist (h : l <+ l₁ ++ a :: l₂) : l <+ l₁ ++ l₂ ∨ a ∈ l := by - induction l₁ generalizing l with - | nil => match h with - | .cons _ h => exact .inl h - | .cons₂ _ h => exact .inr (.head ..) - | cons b l₁ IH => - match h with - | .cons _ h => exact (IH h).imp_left (Sublist.cons _) - | .cons₂ _ h => exact (IH h).imp (Sublist.cons₂ _) (.tail _) - -theorem Sublist.reverse : l₁ <+ l₂ → l₁.reverse <+ l₂.reverse - | .slnil => Sublist.refl _ - | .cons _ h => by rw [reverse_cons]; exact sublist_append_of_sublist_left h.reverse - | .cons₂ _ h => by rw [reverse_cons, reverse_cons]; exact h.reverse.append_right _ - -@[simp] theorem reverse_sublist : l₁.reverse <+ l₂.reverse ↔ l₁ <+ l₂ := - ⟨fun h => l₁.reverse_reverse ▸ l₂.reverse_reverse ▸ h.reverse, Sublist.reverse⟩ - -@[simp] theorem append_sublist_append_right (l) : l₁ ++ l <+ l₂ ++ l ↔ l₁ <+ l₂ := - ⟨fun h => by - have := h.reverse - simp only [reverse_append, append_sublist_append_left, reverse_sublist] at this - exact this, - fun h => h.append_right l⟩ - -theorem Sublist.append (hl : l₁ <+ l₂) (hr : r₁ <+ r₂) : l₁ ++ r₁ <+ l₂ ++ r₂ := - (hl.append_right _).trans ((append_sublist_append_left _).2 hr) - -theorem Sublist.subset : l₁ <+ l₂ → l₁ ⊆ l₂ - | .slnil, _, h => h - | .cons _ s, _, h => .tail _ (s.subset h) - | .cons₂ .., _, .head .. => .head .. - | .cons₂ _ s, _, .tail _ h => .tail _ (s.subset h) - -instance : Trans (@Sublist α) Subset Subset := - ⟨fun h₁ h₂ => trans h₁.subset h₂⟩ - -instance : Trans Subset (@Sublist α) Subset := - ⟨fun h₁ h₂ => trans h₁ h₂.subset⟩ - -instance : Trans (Membership.mem : α → List α → Prop) Sublist Membership.mem := - ⟨fun h₁ h₂ => h₂.subset h₁⟩ - -theorem Sublist.length_le : l₁ <+ l₂ → length l₁ ≤ length l₂ - | .slnil => Nat.le_refl 0 - | .cons _l s => le_succ_of_le (length_le s) - | .cons₂ _ s => succ_le_succ (length_le s) - -@[simp] theorem sublist_nil {l : List α} : l <+ [] ↔ l = [] := - ⟨fun s => subset_nil.1 s.subset, fun H => H ▸ Sublist.refl _⟩ - -theorem Sublist.eq_of_length : l₁ <+ l₂ → length l₁ = length l₂ → l₁ = l₂ - | .slnil, _ => rfl - | .cons a s, h => nomatch Nat.not_lt.2 s.length_le (h ▸ lt_succ_self _) - | .cons₂ a s, h => by rw [s.eq_of_length (succ.inj h)] - -theorem Sublist.eq_of_length_le (s : l₁ <+ l₂) (h : length l₂ ≤ length l₁) : l₁ = l₂ := - s.eq_of_length <| Nat.le_antisymm s.length_le h - -@[simp] theorem singleton_sublist {a : α} {l} : [a] <+ l ↔ a ∈ l := by - refine ⟨fun h => h.subset (mem_singleton_self _), fun h => ?_⟩ - obtain ⟨_, _, rfl⟩ := append_of_mem h - exact ((nil_sublist _).cons₂ _).trans (sublist_append_right ..) - -@[simp] theorem replicate_sublist_replicate {m n} (a : α) : - replicate m a <+ replicate n a ↔ m ≤ n := by - refine ⟨fun h => ?_, fun h => ?_⟩ - · have := h.length_le; simp only [length_replicate] at this ⊢; exact this - · induction h with - | refl => apply Sublist.refl - | step => simp [*, replicate, Sublist.cons] - -theorem isSublist_iff_sublist [BEq α] [LawfulBEq α] {l₁ l₂ : List α} : - l₁.isSublist l₂ ↔ l₁ <+ l₂ := by - cases l₁ <;> cases l₂ <;> simp [isSublist] - case cons.cons hd₁ tl₁ hd₂ tl₂ => - if h_eq : hd₁ = hd₂ then - simp [h_eq, cons_sublist_cons, isSublist_iff_sublist] - else - simp only [beq_iff_eq, h_eq] - constructor - · intro h_sub - apply Sublist.cons - exact isSublist_iff_sublist.mp h_sub - · intro h_sub - cases h_sub - case cons h_sub => - exact isSublist_iff_sublist.mpr h_sub - case cons₂ => - contradiction - -instance [DecidableEq α] (l₁ l₂ : List α) : Decidable (l₁ <+ l₂) := - decidable_of_iff (l₁.isSublist l₂) isSublist_iff_sublist - -/-! ### tail -/ - -theorem tail_eq_tailD (l) : @tail α l = tailD l [] := by cases l <;> rfl - -theorem tail_eq_tail? (l) : @tail α l = (tail? l).getD [] := by simp [tail_eq_tailD] - /-! ### next? -/ @[simp] theorem next?_nil : @next? α [] = none := rfl @@ -259,34 +40,15 @@ theorem dropLast_eq_eraseIdx {xs : List α} {i : Nat} (last_idx : i + 1 = xs.len /-! ### get? -/ -theorem get_eq_iff : List.get l n = x ↔ l.get? n.1 = some x := by simp [get?_eq_some] +@[deprecated getElem_eq_iff (since := "2024-06-12")] +theorem get_eq_iff : List.get l n = x ↔ l.get? n.1 = some x := by + simp +@[deprecated getElem?_inj (since := "2024-06-12")] theorem get?_inj (h₀ : i < xs.length) (h₁ : Nodup xs) (h₂ : xs.get? i = xs.get? j) : i = j := by - induction xs generalizing i j with - | nil => cases h₀ - | cons x xs ih => - match i, j with - | 0, 0 => rfl - | i+1, j+1 => simp; cases h₁ with - | cons ha h₁ => exact ih (Nat.lt_of_succ_lt_succ h₀) h₁ h₂ - | i+1, 0 => ?_ | 0, j+1 => ?_ - all_goals - simp at h₂ - cases h₁; rename_i h' h - have := h x ?_ rfl; cases this - rw [mem_iff_get?] - exact ⟨_, h₂⟩; exact ⟨_ , h₂.symm⟩ - -/-! ### drop -/ - -theorem tail_drop (l : List α) (n : Nat) : (l.drop n).tail = l.drop (n + 1) := by - induction l generalizing n with - | nil => simp - | cons hd tl hl => - cases n - · simp - · simp [hl] + apply getElem?_inj h₀ h₁ + simp_all /-! ### modifyNth -/ @@ -308,17 +70,23 @@ theorem eraseIdx_eq_modifyNthTail : ∀ n (l : List α), eraseIdx l n = modifyNt | n+1, [] => rfl | n+1, a :: l => congrArg (cons _) (eraseIdx_eq_modifyNthTail _ _) -@[deprecated] alias removeNth_eq_nth_tail := eraseIdx_eq_modifyNthTail +@[deprecated (since := "2024-05-06")] alias removeNth_eq_nth_tail := eraseIdx_eq_modifyNthTail -theorem get?_modifyNth (f : α → α) : - ∀ n (l : List α) m, (modifyNth f n l).get? m = (fun a => if n = m then f a else a) <$> l.get? m - | n, l, 0 => by cases l <;> cases n <;> rfl +theorem getElem?_modifyNth (f : α → α) : + ∀ n (l : List α) m, (modifyNth f n l)[m]? = (fun a => if n = m then f a else a) <$> l[m]? + | n, l, 0 => by cases l <;> cases n <;> simp | n, [], _+1 => by cases n <;> rfl - | 0, _ :: l, m+1 => by cases h : l.get? m <;> simp [h, modifyNth, m.succ_ne_zero.symm] - | n+1, a :: l, m+1 => - (get?_modifyNth f n l m).trans <| by - cases h' : l.get? m <;> by_cases h : n = m <;> - simp [h, if_pos, if_neg, Option.map, mt Nat.succ.inj, not_false_iff, h'] + | 0, _ :: l, m+1 => by cases h : l[m]? <;> simp [h, modifyNth, m.succ_ne_zero.symm] + | n+1, a :: l, m+1 => by + simp only [modifyNth_succ_cons, getElem?_cons_succ, Nat.reduceEqDiff, Option.map_eq_map] + refine (getElem?_modifyNth f n l m).trans ?_ + cases h' : l[m]? <;> by_cases h : n = m <;> + simp [h, if_pos, if_neg, Option.map, mt Nat.succ.inj, not_false_iff, h'] + +@[deprecated getElem?_modifyNth (since := "2024-06-12")] +theorem get?_modifyNth (f : α → α) (n) (l : List α) (m) : + (modifyNth f n l).get? m = (fun a => if n = m then f a else a) <$> l.get? m := by + simp [getElem?_modifyNth] theorem modifyNthTail_length (f : List α → List α) (H : ∀ l, length (f l) = length l) : ∀ n l, length (modifyNthTail f n l) = length l @@ -339,13 +107,23 @@ theorem exists_of_modifyNthTail (f : List α → List α) {n} {l : List α} (h : @[simp] theorem modify_get?_length (f : α → α) : ∀ n l, length (modifyNth f n l) = length l := modifyNthTail_length _ fun l => by cases l <;> rfl -@[simp] theorem get?_modifyNth_eq (f : α → α) (n) (l : List α) : - (modifyNth f n l).get? n = f <$> l.get? n := by - simp only [get?_modifyNth, if_pos] +@[simp] theorem getElem?_modifyNth_eq (f : α → α) (n) (l : List α) : + (modifyNth f n l)[n]? = f <$> l[n]? := by + simp only [getElem?_modifyNth, if_pos] + +@[deprecated getElem?_modifyNth_eq (since := "2024-06-12")] +theorem get?_modifyNth_eq (f : α → α) (n) (l : List α) : + (modifyNth f n l).get? n = f <$> l.get? n := by + simp [getElem?_modifyNth_eq] -@[simp] theorem get?_modifyNth_ne (f : α → α) {m n} (l : List α) (h : m ≠ n) : +@[simp] theorem getElem?_modifyNth_ne (f : α → α) {m n} (l : List α) (h : m ≠ n) : + (modifyNth f m l)[n]? = l[n]? := by + simp only [getElem?_modifyNth, if_neg h, id_map'] + +@[deprecated getElem?_modifyNth_ne (since := "2024-06-12")] +theorem get?_modifyNth_ne (f : α → α) {m n} (l : List α) (h : m ≠ n) : (modifyNth f m l).get? n = l.get? n := by - simp only [get?_modifyNth, if_neg h, id_map'] + simp [h] theorem exists_of_modifyNth (f : α → α) {n} {l : List α} (h : n < l.length) : ∃ l₁ a l₂, l = l₁ ++ a :: l₂ ∧ l₁.length = n ∧ modifyNth f n l = l₁ ++ f a :: l₂ := @@ -363,9 +141,9 @@ theorem modifyNth_eq_take_drop (f : α → α) : ∀ n l, modifyNth f n l = take n l ++ modifyHead f (drop n l) := modifyNthTail_eq_take_drop _ rfl -theorem modifyNth_eq_take_cons_drop (f : α → α) {n l} (h) : - modifyNth f n l = take n l ++ f (get l ⟨n, h⟩) :: drop (n + 1) l := by - rw [modifyNth_eq_take_drop, drop_eq_get_cons h]; rfl +theorem modifyNth_eq_take_cons_drop (f : α → α) {n l} (h : n < length l) : + modifyNth f n l = take n l ++ f l[n] :: drop (n + 1) l := by + rw [modifyNth_eq_take_drop, drop_eq_getElem_cons h]; rfl /-! ### set -/ @@ -383,160 +161,52 @@ theorem modifyNth_eq_set_get? (f : α → α) : | 0, l => by cases l <;> rfl | n+1, [] => rfl | n+1, b :: l => - (congrArg (cons _) (modifyNth_eq_set_get? ..)).trans <| by cases h : l.get? n <;> simp [h] + (congrArg (cons _) (modifyNth_eq_set_get? ..)).trans <| by cases h : l[n]? <;> simp [h] theorem modifyNth_eq_set_get (f : α → α) {n} {l : List α} (h) : l.modifyNth f n = l.set n (f (l.get ⟨n, h⟩)) := by rw [modifyNth_eq_set_get?, get?_eq_get h]; rfl -theorem exists_of_set {l : List α} (h : n < l.length) : +-- The naming of `exists_of_set'` and `exists_of_set` have been swapped. +-- If no one complains, we will remove this version later. +@[deprecated exists_of_set (since := "2024-07-04")] +theorem exists_of_set' {l : List α} (h : n < l.length) : ∃ l₁ a l₂, l = l₁ ++ a :: l₂ ∧ l₁.length = n ∧ l.set n a' = l₁ ++ a' :: l₂ := by rw [set_eq_modifyNth]; exact exists_of_modifyNth _ h -theorem exists_of_set' {l : List α} (h : n < l.length) : - ∃ l₁ l₂, l = l₁ ++ l.get ⟨n, h⟩ :: l₂ ∧ l₁.length = n ∧ l.set n a' = l₁ ++ a' :: l₂ := - have ⟨_, _, _, h₁, h₂, h₃⟩ := exists_of_set h; ⟨_, _, get_of_append h₁ h₂ ▸ h₁, h₂, h₃⟩ - -@[simp] +@[deprecated getElem?_set_eq' (since := "2024-06-12")] theorem get?_set_eq (a : α) (n) (l : List α) : (set l n a).get? n = (fun _ => a) <$> l.get? n := by - simp only [set_eq_modifyNth, get?_modifyNth_eq] + simp +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_eq', getElem?_eq_getElem h]; rfl + +@[deprecated getElem?_set_eq_of_lt (since := "2024-06-12")] theorem get?_set_eq_of_lt (a : α) {n} {l : List α} (h : n < length l) : - (set l n a).get? n = some a := by rw [get?_set_eq, get?_eq_get h]; rfl + (set l n a).get? n = some a := by + rw [get?_eq_getElem?, getElem?_set_eq', getElem?_eq_getElem h]; rfl -@[simp] +@[deprecated getElem?_set_ne (since := "2024-06-12")] theorem get?_set_ne (a : α) {m n} (l : List α) (h : m ≠ n) : (set l m a).get? n = l.get? n := by - simp only [set_eq_modifyNth, get?_modifyNth_ne _ _ h] + simp [h] +@[deprecated getElem?_set (since := "2024-06-12")] theorem get?_set (a : α) {m n} (l : List α) : (set l m a).get? n = if m = n then (fun _ => a) <$> l.get? n else l.get? n := by - by_cases m = n <;> simp [*, get?_set_eq, get?_set_ne] + simp [getElem?_set'] theorem get?_set_of_lt (a : α) {m n} (l : List α) (h : n < length l) : (set l m a).get? n = if m = n then some a else l.get? n := by - simp [get?_set, get?_eq_get h] + simp [getElem?_set', getElem?_eq_getElem h] theorem get?_set_of_lt' (a : α) {m n} (l : List α) (h : m < length l) : (set l m a).get? n = if m = n then some a else l.get? n := by - simp [get?_set]; split <;> subst_vars <;> simp [*, get?_eq_get h] - -theorem drop_set_of_lt (a : α) {n m : Nat} (l : List α) (h : n < m) : - (l.set n a).drop m = l.drop m := - List.ext fun i => by rw [get?_drop, get?_drop, get?_set_ne _ _ (by omega)] - -theorem take_set_of_lt (a : α) {n m : Nat} (l : List α) (h : m < n) : - (l.set n a).take m = l.take m := - List.ext fun i => by - rw [get?_take_eq_if, get?_take_eq_if] - split - · next h' => rw [get?_set_ne _ _ (by omega)] - · rfl - -/-! ### removeNth -/ + simp [getElem?_set]; split <;> subst_vars <;> simp [*, getElem?_eq_getElem h] -theorem length_eraseIdx : ∀ {l i}, i < length l → length (@eraseIdx α l i) = length l - 1 - | [], _, _ => rfl - | _::_, 0, _ => by simp [eraseIdx] - | x::xs, i+1, h => by - have : i < length xs := Nat.lt_of_succ_lt_succ h - simp [eraseIdx, ← Nat.add_one] - rw [length_eraseIdx this, Nat.sub_add_cancel (Nat.lt_of_le_of_lt (Nat.zero_le _) this)] - -@[deprecated] alias length_removeNth := length_eraseIdx - -/-! ### tail -/ - -@[simp] theorem length_tail (l : List α) : length (tail l) = length l - 1 := by cases l <;> rfl +@[deprecated (since := "2024-05-06")] alias length_removeNth := length_eraseIdx /-! ### eraseP -/ -@[simp] theorem eraseP_nil : [].eraseP p = [] := rfl - -theorem eraseP_cons (a : α) (l : List α) : - (a :: l).eraseP p = bif p a then l else a :: l.eraseP p := rfl - -@[simp] theorem eraseP_cons_of_pos {l : List α} (p) (h : p a) : (a :: l).eraseP p = l := by - simp [eraseP_cons, h] - -@[simp] theorem eraseP_cons_of_neg {l : List α} (p) (h : ¬p a) : - (a :: l).eraseP p = a :: l.eraseP p := by simp [eraseP_cons, h] - -theorem eraseP_of_forall_not {l : List α} (h : ∀ a, a ∈ l → ¬p a) : l.eraseP p = l := by - induction l with - | nil => rfl - | cons _ _ ih => simp [h _ (.head ..), ih (forall_mem_cons.1 h).2] - -theorem exists_of_eraseP : ∀ {l : List α} {a} (al : a ∈ l) (pa : p a), - ∃ a l₁ l₂, (∀ b ∈ l₁, ¬p b) ∧ p a ∧ l = l₁ ++ a :: l₂ ∧ l.eraseP p = l₁ ++ l₂ - | b :: l, a, al, pa => - if pb : p b then - ⟨b, [], l, forall_mem_nil _, pb, by simp [pb]⟩ - else - match al with - | .head .. => nomatch pb pa - | .tail _ al => - let ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩ := exists_of_eraseP al pa - ⟨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_eraseP (p) (l : List α) : - l.eraseP p = l ∨ - ∃ a l₁ l₂, (∀ b ∈ l₁, ¬p b) ∧ p a ∧ l = l₁ ++ a :: l₂ ∧ l.eraseP p = l₁ ++ l₂ := - if h : ∃ a ∈ l, p a then - let ⟨_, ha, pa⟩ := h - .inr (exists_of_eraseP ha pa) - else - .inl (eraseP_of_forall_not (h ⟨·, ·, ·⟩)) - -@[simp] theorem length_eraseP_of_mem (al : a ∈ l) (pa : p a) : - length (l.eraseP p) = Nat.pred (length l) := by - let ⟨_, l₁, l₂, _, _, e₁, e₂⟩ := exists_of_eraseP al pa - rw [e₂]; simp [length_append, e₁]; rfl - -theorem eraseP_append_left {a : α} (pa : p a) : - ∀ {l₁ : List α} l₂, a ∈ l₁ → (l₁++l₂).eraseP p = l₁.eraseP p ++ l₂ - | x :: xs, l₂, h => by - by_cases h' : p x <;> simp [h'] - rw [eraseP_append_left pa l₂ ((mem_cons.1 h).resolve_left (mt _ h'))] - intro | rfl => exact pa - -theorem eraseP_append_right : - ∀ {l₁ : List α} l₂, (∀ b ∈ l₁, ¬p b) → eraseP p (l₁++l₂) = l₁ ++ l₂.eraseP p - | [], l₂, _ => rfl - | x :: xs, l₂, h => by - simp [(forall_mem_cons.1 h).1, eraseP_append_right _ (forall_mem_cons.1 h).2] - -theorem eraseP_sublist (l : List α) : l.eraseP p <+ l := by - match exists_or_eq_self_of_eraseP p l with - | .inl h => rw [h]; apply Sublist.refl - | .inr ⟨c, l₁, l₂, _, _, h₃, h₄⟩ => rw [h₄, h₃]; simp - -theorem eraseP_subset (l : List α) : l.eraseP p ⊆ l := (eraseP_sublist l).subset - -protected theorem Sublist.eraseP : l₁ <+ l₂ → l₁.eraseP p <+ l₂.eraseP p - | .slnil => Sublist.refl _ - | .cons a s => by - by_cases h : p a <;> simp [h] - exacts [s.eraseP.trans (eraseP_sublist _), s.eraseP.cons _] - | .cons₂ a s => by - by_cases h : p a <;> simp [h] - exacts [s, s.eraseP] - -theorem mem_of_mem_eraseP {l : List α} : a ∈ l.eraseP p → a ∈ l := (eraseP_subset _ ·) - -@[simp] theorem mem_eraseP_of_neg {l : List α} (pa : ¬p a) : a ∈ l.eraseP p ↔ a ∈ l := by - refine ⟨mem_of_mem_eraseP, fun al => ?_⟩ - match exists_or_eq_self_of_eraseP p l with - | .inl h => rw [h]; assumption - | .inr ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩ => - rw [h₄]; rw [h₃] at al - have : a ≠ c := fun h => (h ▸ pa).elim h₂ - simp [this] at al; simp [al] - -theorem eraseP_map (f : β → α) : ∀ (l : List β), (map f l).eraseP p = map f (l.eraseP (p ∘ f)) - | [] => rfl - | b::l => by by_cases h : p (f b) <;> simp [h, eraseP_map f l, eraseP_cons_of_pos] - @[simp] theorem extractP_eq_find?_eraseP (l : List α) : extractP p l = (find? p l, eraseP p l) := by let rec go (acc) : ∀ xs, l = acc.data ++ xs → @@ -549,6 +219,8 @@ theorem eraseP_map (f : β → α) : ∀ (l : List β), (map f l).eraseP p = map /-! ### erase -/ +@[deprecated (since := "2024-04-22")] alias sublist.erase := Sublist.erase + section erase variable [BEq α] @@ -870,10 +542,10 @@ theorem disjoint_of_subset_right (ss : l₂ ⊆ l) (d : Disjoint l₁ l) : Disjo 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 _ _) + 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 _ _) + disjoint_of_subset_right (subset_cons_self _ _) @[simp] theorem disjoint_nil_left (l : List α) : Disjoint [] l := fun a => (not_mem_nil a).elim @@ -909,23 +581,13 @@ theorem disjoint_of_disjoint_append_right_left (d : Disjoint l (l₁ ++ l₂)) : theorem disjoint_of_disjoint_append_right_right (d : Disjoint l (l₁ ++ l₂)) : Disjoint l l₂ := (disjoint_append_right.1 d).2 -/-! ### foldl / foldr -/ - -theorem foldl_hom (f : α₁ → α₂) (g₁ : α₁ → β → α₁) (g₂ : α₂ → β → α₂) (l : List β) (init : α₁) - (H : ∀ x y, g₂ (f x) y = f (g₁ x y)) : l.foldl g₂ (f init) = f (l.foldl g₁ init) := by - induction l generalizing init <;> simp [*, H] - -theorem foldr_hom (f : β₁ → β₂) (g₁ : α → β₁ → β₁) (g₂ : α → β₂ → β₂) (l : List α) (init : β₁) - (H : ∀ x y, g₂ x (f y) = f (g₁ x y)) : l.foldr g₂ (f init) = f (l.foldr g₁ init) := by - induction l <;> simp [*, H] - /-! ### union -/ section union variable [BEq α] -theorem union_def [BEq α] (l₁ l₂ : List α) : l₁ ∪ l₂ = foldr .insert l₂ l₁ := rfl +theorem union_def (l₁ l₂ : List α) : l₁ ∪ l₂ = foldr .insert l₂ l₁ := rfl @[simp] theorem nil_union (l : List α) : nil ∪ l = l := by simp [List.union_def, foldr] @@ -954,46 +616,23 @@ theorem pair_mem_product {xs : List α} {ys : List β} {x : α} {y : β} : simp only [product, and_imp, mem_map, Prod.mk.injEq, exists_eq_right_right, mem_bind, iff_self] -/-! ### leftpad -/ - -/-- The length of the List returned by `List.leftpad n a l` is equal - to the larger of `n` and `l.length` -/ -@[simp] -theorem leftpad_length (n : Nat) (a : α) (l : List α) : - (leftpad n a l).length = max n l.length := by - simp only [leftpad, length_append, length_replicate, Nat.sub_add_eq_max] - -theorem leftpad_prefix (n : Nat) (a : α) (l : List α) : - replicate (n - length l) a <+: leftpad n a l := by - simp only [IsPrefix, leftpad] - exact Exists.intro l rfl - -theorem leftpad_suffix (n : Nat) (a : α) (l : List α) : l <:+ (leftpad n a l) := by - simp only [IsSuffix, leftpad] - exact Exists.intro (replicate (n - length l) a) rfl - /-! ### monadic operations -/ --- we use ForIn.forIn as the simp normal form -@[simp] theorem forIn_eq_forIn [Monad m] : @List.forIn α β m _ = forIn := rfl - 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 [*, map_eq_pure_bind] congr; ext (b | b) <;> simp -@[simp] theorem forM_append [Monad m] [LawfulMonad m] (l₁ l₂ : List α) (f : α → m PUnit) : - (l₁ ++ l₂).forM f = (do l₁.forM f; l₂.forM f) := by induction l₁ <;> simp [*] - /-! ### diff -/ section Diff variable [BEq α] -variable [LawfulBEq α] @[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] @@ -1062,205 +701,8 @@ theorem Sublist.erase_diff_erase_sublist {a : α} : end Diff -/-! ### prefix, suffix, infix -/ - -@[simp] theorem prefix_append (l₁ l₂ : List α) : l₁ <+: l₁ ++ l₂ := ⟨l₂, rfl⟩ - -@[simp] theorem suffix_append (l₁ l₂ : List α) : l₂ <:+ l₁ ++ l₂ := ⟨l₁, rfl⟩ - -theorem infix_append (l₁ l₂ l₃ : List α) : l₂ <:+: l₁ ++ l₂ ++ l₃ := ⟨l₁, l₃, rfl⟩ - -@[simp] theorem infix_append' (l₁ l₂ l₃ : List α) : l₂ <:+: l₁ ++ (l₂ ++ l₃) := by - rw [← List.append_assoc]; apply infix_append - -theorem IsPrefix.isInfix : l₁ <+: l₂ → l₁ <:+: l₂ := fun ⟨t, h⟩ => ⟨[], t, h⟩ - -theorem IsSuffix.isInfix : l₁ <:+ l₂ → l₁ <:+: l₂ := fun ⟨t, h⟩ => ⟨t, [], by rw [h, append_nil]⟩ - -theorem nil_prefix (l : List α) : [] <+: l := ⟨l, rfl⟩ - -theorem nil_suffix (l : List α) : [] <:+ l := ⟨l, append_nil _⟩ - -theorem nil_infix (l : List α) : [] <:+: l := (nil_prefix _).isInfix - -theorem prefix_refl (l : List α) : l <+: l := ⟨[], append_nil _⟩ - -theorem suffix_refl (l : List α) : l <:+ l := ⟨[], rfl⟩ - -theorem infix_refl (l : List α) : l <:+: l := (prefix_refl l).isInfix - -@[simp] theorem suffix_cons (a : α) : ∀ l, l <:+ a :: l := suffix_append [a] - -theorem infix_cons : l₁ <:+: l₂ → l₁ <:+: a :: l₂ := fun ⟨L₁, L₂, h⟩ => ⟨a :: L₁, L₂, h ▸ rfl⟩ - -theorem infix_concat : l₁ <:+: l₂ → l₁ <:+: concat l₂ a := fun ⟨L₁, L₂, h⟩ => - ⟨L₁, concat L₂ a, by simp [← h, concat_eq_append, append_assoc]⟩ - -theorem IsPrefix.trans : ∀ {l₁ l₂ l₃ : List α}, l₁ <+: l₂ → l₂ <+: l₃ → l₁ <+: l₃ - | _, _, _, ⟨r₁, rfl⟩, ⟨r₂, rfl⟩ => ⟨r₁ ++ r₂, (append_assoc _ _ _).symm⟩ - -theorem IsSuffix.trans : ∀ {l₁ l₂ l₃ : List α}, l₁ <:+ l₂ → l₂ <:+ l₃ → l₁ <:+ l₃ - | _, _, _, ⟨l₁, rfl⟩, ⟨l₂, rfl⟩ => ⟨l₂ ++ l₁, append_assoc _ _ _⟩ - -theorem IsInfix.trans : ∀ {l₁ l₂ l₃ : List α}, l₁ <:+: l₂ → l₂ <:+: l₃ → l₁ <:+: l₃ - | l, _, _, ⟨l₁, r₁, rfl⟩, ⟨l₂, r₂, rfl⟩ => ⟨l₂ ++ l₁, r₁ ++ r₂, by simp only [append_assoc]⟩ - -protected theorem IsInfix.sublist : l₁ <:+: l₂ → l₁ <+ l₂ - | ⟨_, _, h⟩ => h ▸ (sublist_append_right ..).trans (sublist_append_left ..) - -protected theorem IsInfix.subset (hl : l₁ <:+: l₂) : l₁ ⊆ l₂ := - hl.sublist.subset - -protected theorem IsPrefix.sublist (h : l₁ <+: l₂) : l₁ <+ l₂ := - h.isInfix.sublist - -protected theorem IsPrefix.subset (hl : l₁ <+: l₂) : l₁ ⊆ l₂ := - hl.sublist.subset - -protected theorem IsSuffix.sublist (h : l₁ <:+ l₂) : l₁ <+ l₂ := - h.isInfix.sublist - -protected theorem IsSuffix.subset (hl : l₁ <:+ l₂) : l₁ ⊆ l₂ := - hl.sublist.subset - -@[simp] theorem reverse_suffix : reverse l₁ <:+ reverse l₂ ↔ l₁ <+: l₂ := - ⟨fun ⟨r, e⟩ => ⟨reverse r, by rw [← reverse_reverse l₁, ← reverse_append, e, reverse_reverse]⟩, - fun ⟨r, e⟩ => ⟨reverse r, by rw [← reverse_append, e]⟩⟩ - -@[simp] theorem reverse_prefix : reverse l₁ <+: reverse l₂ ↔ l₁ <:+ l₂ := by - rw [← reverse_suffix]; simp only [reverse_reverse] - -@[simp] theorem reverse_infix : reverse l₁ <:+: reverse l₂ ↔ l₁ <:+: l₂ := by - refine ⟨fun ⟨s, t, e⟩ => ⟨reverse t, reverse s, ?_⟩, fun ⟨s, t, e⟩ => ⟨reverse t, reverse s, ?_⟩⟩ - · rw [← reverse_reverse l₁, append_assoc, ← reverse_append, ← reverse_append, e, - reverse_reverse] - · rw [append_assoc, ← reverse_append, ← reverse_append, e] - -theorem IsInfix.length_le (h : l₁ <:+: l₂) : l₁.length ≤ l₂.length := - h.sublist.length_le - -theorem IsPrefix.length_le (h : l₁ <+: l₂) : l₁.length ≤ l₂.length := - h.sublist.length_le - -theorem IsSuffix.length_le (h : l₁ <:+ l₂) : l₁.length ≤ l₂.length := - h.sublist.length_le - -@[simp] theorem infix_nil : l <:+: [] ↔ l = [] := ⟨(sublist_nil.1 ·.sublist), (· ▸ infix_refl _)⟩ - -@[simp] theorem prefix_nil : l <+: [] ↔ l = [] := ⟨(sublist_nil.1 ·.sublist), (· ▸ prefix_refl _)⟩ - -@[simp] theorem suffix_nil : l <:+ [] ↔ l = [] := ⟨(sublist_nil.1 ·.sublist), (· ▸ suffix_refl _)⟩ - -theorem infix_iff_prefix_suffix (l₁ l₂ : List α) : l₁ <:+: l₂ ↔ ∃ t, l₁ <+: t ∧ t <:+ l₂ := - ⟨fun ⟨_, t, e⟩ => ⟨l₁ ++ t, ⟨_, rfl⟩, e ▸ append_assoc .. ▸ ⟨_, rfl⟩⟩, - fun ⟨_, ⟨t, rfl⟩, s, e⟩ => ⟨s, t, append_assoc .. ▸ e⟩⟩ - -theorem IsInfix.eq_of_length (h : l₁ <:+: l₂) : l₁.length = l₂.length → l₁ = l₂ := - h.sublist.eq_of_length - -theorem IsPrefix.eq_of_length (h : l₁ <+: l₂) : l₁.length = l₂.length → l₁ = l₂ := - h.sublist.eq_of_length - -theorem IsSuffix.eq_of_length (h : l₁ <:+ l₂) : l₁.length = l₂.length → l₁ = l₂ := - h.sublist.eq_of_length - -theorem prefix_of_prefix_length_le : - ∀ {l₁ l₂ l₃ : List α}, l₁ <+: l₃ → l₂ <+: l₃ → length l₁ ≤ length l₂ → l₁ <+: l₂ - | [], l₂, _, _, _, _ => nil_prefix _ - | a :: l₁, b :: l₂, _, ⟨r₁, rfl⟩, ⟨r₂, e⟩, ll => by - injection e with _ e'; subst b - rcases prefix_of_prefix_length_le ⟨_, rfl⟩ ⟨_, e'⟩ (le_of_succ_le_succ ll) with ⟨r₃, rfl⟩ - exact ⟨r₃, rfl⟩ - -theorem prefix_or_prefix_of_prefix (h₁ : l₁ <+: l₃) (h₂ : l₂ <+: l₃) : l₁ <+: l₂ ∨ l₂ <+: l₁ := - (Nat.le_total (length l₁) (length l₂)).imp (prefix_of_prefix_length_le h₁ h₂) - (prefix_of_prefix_length_le h₂ h₁) - -theorem suffix_of_suffix_length_le - (h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) (ll : length l₁ ≤ length l₂) : l₁ <:+ l₂ := - reverse_prefix.1 <| - prefix_of_prefix_length_le (reverse_prefix.2 h₁) (reverse_prefix.2 h₂) (by simp [ll]) - -theorem suffix_or_suffix_of_suffix (h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) : l₁ <:+ l₂ ∨ l₂ <:+ l₁ := - (prefix_or_prefix_of_prefix (reverse_prefix.2 h₁) (reverse_prefix.2 h₂)).imp reverse_prefix.1 - reverse_prefix.1 - -theorem suffix_cons_iff : l₁ <:+ a :: l₂ ↔ l₁ = a :: l₂ ∨ l₁ <:+ l₂ := by - constructor - · rintro ⟨⟨hd, tl⟩, hl₃⟩ - · exact Or.inl hl₃ - · simp only [cons_append] at hl₃ - injection hl₃ with _ hl₄ - exact Or.inr ⟨_, hl₄⟩ - · rintro (rfl | hl₁) - · exact (a :: l₂).suffix_refl - · exact hl₁.trans (l₂.suffix_cons _) - -theorem infix_cons_iff : l₁ <:+: a :: l₂ ↔ l₁ <+: a :: l₂ ∨ l₁ <:+: l₂ := by - constructor - · rintro ⟨⟨hd, tl⟩, t, hl₃⟩ - · exact Or.inl ⟨t, hl₃⟩ - · simp only [cons_append] at hl₃ - injection hl₃ with _ hl₄ - exact Or.inr ⟨_, t, hl₄⟩ - · rintro (h | hl₁) - · exact h.isInfix - · exact infix_cons hl₁ - -theorem infix_of_mem_join : ∀ {L : List (List α)}, l ∈ L → l <:+: join L - | l' :: _, h => - match h with - | List.Mem.head .. => infix_append [] _ _ - | List.Mem.tail _ hlMemL => - IsInfix.trans (infix_of_mem_join hlMemL) <| (suffix_append _ _).isInfix - -theorem prefix_append_right_inj (l) : l ++ l₁ <+: l ++ l₂ ↔ l₁ <+: l₂ := - exists_congr fun r => by rw [append_assoc, append_right_inj] - -@[simp] -theorem prefix_cons_inj (a) : a :: l₁ <+: a :: l₂ ↔ l₁ <+: l₂ := - prefix_append_right_inj [a] - -theorem take_prefix (n) (l : List α) : take n l <+: l := - ⟨_, take_append_drop _ _⟩ - -theorem drop_suffix (n) (l : List α) : drop n l <:+ l := - ⟨_, take_append_drop _ _⟩ - -theorem take_sublist (n) (l : List α) : take n l <+ l := - (take_prefix n l).sublist - -theorem drop_sublist (n) (l : List α) : drop n l <+ l := - (drop_suffix n l).sublist - -theorem take_subset (n) (l : List α) : take n l ⊆ l := - (take_sublist n l).subset - -theorem drop_subset (n) (l : List α) : drop n l ⊆ l := - (drop_sublist n l).subset - -theorem mem_of_mem_take {l : List α} (h : a ∈ l.take n) : a ∈ l := - take_subset n l h - -theorem IsPrefix.filter (p : α → Bool) ⦃l₁ l₂ : List α⦄ (h : l₁ <+: l₂) : - l₁.filter p <+: l₂.filter p := by - obtain ⟨xs, rfl⟩ := h - rw [filter_append]; apply prefix_append - -theorem IsSuffix.filter (p : α → Bool) ⦃l₁ l₂ : List α⦄ (h : l₁ <:+ l₂) : - l₁.filter p <:+ l₂.filter p := by - obtain ⟨xs, rfl⟩ := h - rw [filter_append]; apply suffix_append - -theorem IsInfix.filter (p : α → Bool) ⦃l₁ l₂ : List α⦄ (h : l₁ <:+: l₂) : - l₁.filter p <:+: l₂.filter p := by - obtain ⟨xs, ys, rfl⟩ := h - rw [filter_append, filter_append]; apply infix_append _ - /-! ### drop -/ -theorem mem_of_mem_drop {n} {l : List α} (h : a ∈ l.drop n) : a ∈ l := drop_subset _ _ h - theorem disjoint_take_drop : ∀ {l : List α}, l.Nodup → m ≤ n → Disjoint (l.take m) (l.drop n) | [], _, _ => by simp | x :: xs, hl, h => by @@ -1309,36 +751,6 @@ protected theorem Pairwise.chain (p : Pairwise R (a :: l)) : Chain R a l := by /-! ### range', range -/ -@[simp] theorem length_range' (s step) : ∀ n : Nat, length (range' s n step) = n - | 0 => rfl - | _ + 1 => congrArg succ (length_range' _ _ _) - -@[simp] theorem range'_eq_nil : range' s n step = [] ↔ n = 0 := by - rw [← length_eq_zero, length_range'] - -theorem mem_range' : ∀{n}, m ∈ range' s n step ↔ ∃ i < n, m = s + step * i - | 0 => by simp [range', Nat.not_lt_zero] - | n + 1 => by - have h (i) : i ≤ n ↔ i = 0 ∨ ∃ j, i = succ j ∧ j < n := by cases i <;> simp [Nat.succ_le] - simp [range', mem_range', Nat.lt_succ, h]; simp only [← exists_and_right, and_assoc] - rw [exists_comm]; simp [Nat.mul_succ, Nat.add_assoc, Nat.add_comm] - -@[simp] theorem mem_range'_1 : m ∈ range' s n ↔ s ≤ m ∧ m < s + n := by - simp [mem_range']; exact ⟨ - fun ⟨i, h, e⟩ => e ▸ ⟨Nat.le_add_right .., Nat.add_lt_add_left h _⟩, - fun ⟨h₁, h₂⟩ => ⟨m - s, Nat.sub_lt_left_of_lt_add h₁ h₂, (Nat.add_sub_cancel' h₁).symm⟩⟩ - -@[simp] -theorem map_add_range' (a) : ∀ s n step, map (a + ·) (range' s n step) = range' (a + s) n step - | _, 0, _ => rfl - | s, n + 1, step => by simp [range', map_add_range' _ (s + step) n step, Nat.add_assoc] - -theorem map_sub_range' (a s n : Nat) (h : a ≤ s) : - map (· - a) (range' s n step) = range' (s - a) n step := by - conv => lhs; rw [← Nat.add_sub_cancel' h] - rw [← map_add_range', map_map, (?_ : _∘_ = _), map_id] - funext x; apply Nat.add_sub_cancel_left - theorem chain_succ_range' : ∀ s n step : Nat, Chain (fun a b => b = a + step) s (range' (s + step) n step) | _, 0, _ => Chain.nil @@ -1348,132 +760,23 @@ theorem chain_lt_range' (s n : Nat) {step} (h : 0 < step) : Chain (· < ·) s (range' (s + step) n step) := (chain_succ_range' s n step).imp fun _ _ e => e.symm ▸ Nat.lt_add_of_pos_right h -theorem range'_append : ∀ s m n step : Nat, - range' s m step ++ range' (s + step * m) n step = range' s (n + m) step - | s, 0, n, step => rfl - | s, m + 1, n, step => by - simpa [range', Nat.mul_succ, Nat.add_assoc, Nat.add_comm] - using range'_append (s + step) m n step - -@[simp] theorem range'_append_1 (s m n : Nat) : - range' s m ++ range' (s + m) n = range' s (n + m) := by simpa using range'_append s m n 1 - -theorem range'_sublist_right {s m n : Nat} : range' s m step <+ range' s n step ↔ m ≤ n := - ⟨fun h => by simpa only [length_range'] using h.length_le, - fun h => by rw [← Nat.sub_add_cancel h, ← range'_append]; apply sublist_append_left⟩ - -theorem range'_subset_right {s m n : Nat} (step0 : 0 < step) : - range' s m step ⊆ range' s n step ↔ m ≤ n := by - refine ⟨fun h => Nat.le_of_not_lt fun hn => ?_, fun h => (range'_sublist_right.2 h).subset⟩ - have ⟨i, h', e⟩ := mem_range'.1 <| h <| mem_range'.2 ⟨_, hn, rfl⟩ - exact Nat.ne_of_gt h' (Nat.eq_of_mul_eq_mul_left step0 (Nat.add_left_cancel e)) - -theorem range'_subset_right_1 {s m n : Nat} : range' s m ⊆ range' s n ↔ m ≤ n := - range'_subset_right (by decide) - -theorem get?_range' (s step) : ∀ {m n : Nat}, m < n → get? (range' s n step) m = some (s + step * m) - | 0, n + 1, _ => rfl - | m + 1, n + 1, h => - (get?_range' (s + step) step (Nat.lt_of_add_lt_add_right h)).trans <| by - simp [Nat.mul_succ, Nat.add_assoc, Nat.add_comm] - -@[simp] theorem get_range' {n m step} (i) (H : i < (range' n m step).length) : - get (range' n m step) ⟨i, H⟩ = n + step * i := - (get?_eq_some.1 <| get?_range' n step (by simpa using H)).2 - -theorem range'_concat (s n : Nat) : range' s (n + 1) step = range' s n step ++ [s + step * n] := by - rw [Nat.add_comm n 1]; exact (range'_append s n 1 step).symm - -theorem range'_1_concat (s n : Nat) : range' s (n + 1) = range' s n ++ [s + n] := by - simp [range'_concat] - -theorem range_loop_range' : ∀ s n : Nat, range.loop s (range' s n) = range' 0 (n + s) - | 0, n => rfl - | s + 1, n => by rw [← Nat.add_assoc, Nat.add_right_comm n s 1]; exact range_loop_range' s (n + 1) - -theorem range_eq_range' (n : Nat) : range n = range' 0 n := - (range_loop_range' n 0).trans <| by rw [Nat.zero_add] - -theorem range_succ_eq_map (n : Nat) : range (n + 1) = 0 :: map succ (range n) := by - rw [range_eq_range', range_eq_range', range', Nat.add_comm, ← map_add_range'] - congr; exact funext one_add +@[deprecated getElem?_range' (since := "2024-06-12")] +theorem get?_range' (s step) {m n : Nat} (h : m < n) : + get? (range' s n step) m = some (s + step * m) := by + simp [h] -theorem range'_eq_map_range (s n : Nat) : range' s n = map (s + ·) (range n) := by - rw [range_eq_range', map_add_range']; rfl - -@[simp] theorem length_range (n : Nat) : length (range n) = n := by - simp only [range_eq_range', length_range'] - -@[simp] theorem range_eq_nil {n : Nat} : range n = [] ↔ n = 0 := by - rw [← length_eq_zero, length_range] - -@[simp] -theorem range_sublist {m n : Nat} : range m <+ range n ↔ m ≤ n := by - simp only [range_eq_range', range'_sublist_right] - -@[simp] -theorem range_subset {m n : Nat} : range m ⊆ range n ↔ m ≤ n := by - simp only [range_eq_range', range'_subset_right, lt_succ_self] - -@[simp] -theorem mem_range {m n : Nat} : m ∈ range n ↔ m < n := by - simp only [range_eq_range', mem_range'_1, Nat.zero_le, true_and, Nat.zero_add] - -theorem not_mem_range_self {n : Nat} : n ∉ range n := by simp - -theorem self_mem_range_succ (n : Nat) : n ∈ range (n + 1) := by simp +@[deprecated getElem_range' (since := "2024-06-12")] +theorem get_range' {n m step} (i) (H : i < (range' n m step).length) : + get (range' n m step) ⟨i, H⟩ = n + step * i := by + simp +@[deprecated getElem?_range (since := "2024-06-12")] theorem get?_range {m n : Nat} (h : m < n) : get? (range n) m = some m := by - simp [range_eq_range', get?_range' _ _ h] - -theorem range_succ (n : Nat) : range (succ n) = range n ++ [n] := by - simp only [range_eq_range', range'_1_concat, Nat.zero_add] - -@[simp] theorem range_zero : range 0 = [] := rfl - -theorem range_add (a b : Nat) : range (a + b) = range a ++ (range b).map (a + ·) := by - rw [← range'_eq_map_range] - simpa [range_eq_range', Nat.add_comm] using (range'_append_1 0 a b).symm - -theorem iota_eq_reverse_range' : ∀ n : Nat, iota n = reverse (range' 1 n) - | 0 => rfl - | n + 1 => by simp [iota, range'_concat, iota_eq_reverse_range' n, reverse_append, Nat.add_comm] - -@[simp] theorem length_iota (n : Nat) : length (iota n) = n := by simp [iota_eq_reverse_range'] - -@[simp] -theorem mem_iota {m n : Nat} : m ∈ iota n ↔ 1 ≤ m ∧ m ≤ n := by - simp [iota_eq_reverse_range', Nat.add_comm, Nat.lt_succ] - -theorem reverse_range' : ∀ s n : Nat, reverse (range' s n) = map (s + n - 1 - ·) (range n) - | s, 0 => rfl - | s, n + 1 => by - rw [range'_1_concat, reverse_append, range_succ_eq_map, - show s + (n + 1) - 1 = s + n from rfl, map, map_map] - simp [reverse_range', Nat.sub_right_comm]; rfl - -@[simp] theorem get_range {n} (i) (H : i < (range n).length) : get (range n) ⟨i, H⟩ = i := - Option.some.inj <| by rw [← get?_eq_get _, get?_range (by simpa using H)] - -/-! ### enum, enumFrom -/ - -@[simp] theorem enumFrom_map_fst (n) : - ∀ (l : List α), map Prod.fst (enumFrom n l) = range' n l.length - | [] => rfl - | _ :: _ => congrArg (cons _) (enumFrom_map_fst _ _) - -@[simp] theorem enum_map_fst (l : List α) : map Prod.fst (enum l) = range l.length := by - simp only [enum, enumFrom_map_fst, range_eq_range'] - -/-! ### maximum? -/ + simp [getElem?_range, h] --- A specialization of `maximum?_eq_some_iff` to Nat. -theorem maximum?_eq_some_iff' {xs : List Nat} : - xs.maximum? = some a ↔ (a ∈ xs ∧ ∀ b ∈ xs, b ≤ a) := - maximum?_eq_some_iff - (le_refl := Nat.le_refl) - (max_eq_or := fun _ _ => Nat.max_def .. ▸ by split <;> simp) - (max_le_iff := fun _ _ _ => Nat.max_le) +@[deprecated getElem_range (since := "2024-06-12")] +theorem get_range {n} (i) (H : i < (range n).length) : get (range n) ⟨i, H⟩ = i := by + simp /-! ### indexOf and indexesOf -/ diff --git a/Batteries/Data/List/Pairwise.lean b/Batteries/Data/List/Pairwise.lean index 392f261bf2..dd94875ca9 100644 --- a/Batteries/Data/List/Pairwise.lean +++ b/Batteries/Data/List/Pairwise.lean @@ -30,165 +30,7 @@ namespace List /-! ### Pairwise -/ -theorem rel_of_pairwise_cons (p : (a :: l).Pairwise R) : ∀ {a'}, a' ∈ l → R a a' := - (pairwise_cons.1 p).1 _ - -theorem Pairwise.of_cons (p : (a :: l).Pairwise R) : Pairwise R l := - (pairwise_cons.1 p).2 - -theorem Pairwise.tail : ∀ {l : List α} (_p : Pairwise R l), Pairwise R l.tail - | [], h => h - | _ :: _, h => h.of_cons - -theorem Pairwise.drop : ∀ {l : List α} {n : Nat}, List.Pairwise R l → List.Pairwise R (l.drop n) - | _, 0, h => h - | [], _ + 1, _ => List.Pairwise.nil - | _ :: _, n + 1, h => Pairwise.drop (n := n) (pairwise_cons.mp h).right - -theorem Pairwise.imp_of_mem {S : α → α → Prop} - (H : ∀ {a b}, a ∈ l → b ∈ l → R a b → S a b) (p : Pairwise R l) : Pairwise S l := by - induction p with - | nil => constructor - | @cons a l r _ ih => - constructor - · exact fun x h => H (mem_cons_self ..) (mem_cons_of_mem _ h) <| r x h - · exact ih fun m m' => H (mem_cons_of_mem _ m) (mem_cons_of_mem _ m') - -theorem Pairwise.and (hR : Pairwise R l) (hS : Pairwise S l) : - l.Pairwise fun a b => R a b ∧ S a b := by - induction hR with - | nil => simp only [Pairwise.nil] - | cons R1 _ IH => - simp only [Pairwise.nil, pairwise_cons] at hS ⊢ - exact ⟨fun b bl => ⟨R1 b bl, hS.1 b bl⟩, IH hS.2⟩ - -theorem pairwise_and_iff : l.Pairwise (fun a b => R a b ∧ S a b) ↔ Pairwise R l ∧ Pairwise S l := - ⟨fun h => ⟨h.imp fun h => h.1, h.imp fun h => h.2⟩, fun ⟨hR, hS⟩ => hR.and hS⟩ - -theorem Pairwise.imp₂ (H : ∀ a b, R a b → S a b → T a b) - (hR : Pairwise R l) (hS : l.Pairwise S) : l.Pairwise T := - (hR.and hS).imp fun ⟨h₁, h₂⟩ => H _ _ h₁ h₂ - -theorem Pairwise.iff_of_mem {S : α → α → Prop} {l : List α} - (H : ∀ {a b}, a ∈ l → b ∈ l → (R a b ↔ S a b)) : Pairwise R l ↔ Pairwise S l := - ⟨Pairwise.imp_of_mem fun m m' => (H m m').1, Pairwise.imp_of_mem fun m m' => (H m m').2⟩ - -theorem Pairwise.iff {S : α → α → Prop} (H : ∀ a b, R a b ↔ S a b) {l : List α} : - Pairwise R l ↔ Pairwise S l := - Pairwise.iff_of_mem fun _ _ => H .. - -theorem pairwise_of_forall {l : List α} (H : ∀ x y, R x y) : Pairwise R l := by - induction l <;> simp [*] - -theorem Pairwise.and_mem {l : List α} : - Pairwise R l ↔ Pairwise (fun x y => x ∈ l ∧ y ∈ l ∧ R x y) l := - Pairwise.iff_of_mem <| by simp (config := { contextual := true }) - -theorem Pairwise.imp_mem {l : List α} : - Pairwise R l ↔ Pairwise (fun x y => x ∈ l → y ∈ l → R x y) l := - Pairwise.iff_of_mem <| by simp (config := { contextual := true }) - -theorem Pairwise.forall_of_forall_of_flip (h₁ : ∀ x ∈ l, R x x) (h₂ : Pairwise R l) - (h₃ : l.Pairwise (flip R)) : ∀ ⦃x⦄, x ∈ l → ∀ ⦃y⦄, y ∈ l → R x y := by - induction l with - | nil => exact forall_mem_nil _ - | cons a l ih => - rw [pairwise_cons] at h₂ h₃ - simp only [mem_cons] - rintro x (rfl | hx) y (rfl | hy) - · exact h₁ _ (l.mem_cons_self _) - · exact h₂.1 _ hy - · exact h₃.1 _ hx - · exact ih (fun x hx => h₁ _ <| mem_cons_of_mem _ hx) h₂.2 h₃.2 hx hy - -theorem pairwise_singleton (R) (a : α) : Pairwise R [a] := by simp - -theorem pairwise_pair {a b : α} : Pairwise R [a, b] ↔ R a b := by simp - -theorem pairwise_append_comm {R : α → α → Prop} (s : ∀ {x y}, R x y → R y x) {l₁ l₂ : List α} : - Pairwise R (l₁ ++ l₂) ↔ Pairwise R (l₂ ++ l₁) := by - have (l₁ l₂ : List α) (H : ∀ x : α, x ∈ l₁ → ∀ y : α, y ∈ l₂ → R x y) - (x : α) (xm : x ∈ l₂) (y : α) (ym : y ∈ l₁) : R x y := s (H y ym x xm) - simp only [pairwise_append, and_left_comm]; rw [Iff.intro (this l₁ l₂) (this l₂ l₁)] - -theorem pairwise_middle {R : α → α → Prop} (s : ∀ {x y}, R x y → R y x) {a : α} {l₁ l₂ : List α} : - Pairwise R (l₁ ++ a :: l₂) ↔ Pairwise R (a :: (l₁ ++ l₂)) := by - show Pairwise R (l₁ ++ ([a] ++ l₂)) ↔ Pairwise R ([a] ++ l₁ ++ l₂) - rw [← append_assoc, pairwise_append, @pairwise_append _ _ ([a] ++ l₁), pairwise_append_comm s] - simp only [mem_append, or_comm] - -theorem Pairwise.of_map {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, S (f a) (f b) → R a b) - (p : Pairwise S (map f l)) : Pairwise R l := - (pairwise_map.1 p).imp (H _ _) - -theorem Pairwise.map {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, R a b → S (f a) (f b)) - (p : Pairwise R l) : Pairwise S (map f l) := - pairwise_map.2 <| p.imp (H _ _) - -theorem pairwise_filterMap (f : β → Option α) {l : List β} : - Pairwise R (filterMap f l) ↔ Pairwise (fun a a' : β => ∀ b ∈ f a, ∀ b' ∈ f a', R b b') l := by - let _S (a a' : β) := ∀ b ∈ f a, ∀ b' ∈ f a', R b b' - simp only [Option.mem_def] - induction l with - | nil => simp only [filterMap, Pairwise.nil] - | cons a l IH => ?_ - match e : f a with - | none => - rw [filterMap_cons_none _ _ e, pairwise_cons] - simp only [e, false_implies, implies_true, true_and, IH] - | some b => - rw [filterMap_cons_some _ _ _ e] - simpa [IH, e] using fun _ => - ⟨fun h a ha b hab => h _ _ ha hab, fun h a b ha hab => h _ ha _ hab⟩ - -theorem Pairwise.filter_map {S : β → β → Prop} (f : α → Option β) - (H : ∀ a a' : α, R a a' → ∀ b ∈ f a, ∀ b' ∈ f a', S b b') {l : List α} (p : Pairwise R l) : - Pairwise S (filterMap f l) := - (pairwise_filterMap _).2 <| p.imp (H _ _) - -theorem pairwise_filter (p : α → Prop) [DecidablePred p] {l : List α} : - Pairwise R (filter p l) ↔ Pairwise (fun x y => p x → p y → R x y) l := by - rw [← filterMap_eq_filter, pairwise_filterMap] - simp - -theorem Pairwise.filter (p : α → Bool) : Pairwise R l → Pairwise R (filter p l) := - Pairwise.sublist (filter_sublist _) - -theorem pairwise_join {L : List (List α)} : - Pairwise R (join L) ↔ - (∀ l ∈ L, Pairwise R l) ∧ Pairwise (fun l₁ l₂ => ∀ x ∈ l₁, ∀ y ∈ l₂, R x y) L := by - induction L with - | nil => simp - | cons l L IH => - simp only [join, pairwise_append, IH, mem_join, exists_imp, and_imp, forall_mem_cons, - pairwise_cons, and_assoc, and_congr_right_iff] - rw [and_comm, and_congr_left_iff] - intros; exact ⟨fun h a b c d e => h c d e a b, fun h c d e a b => h a b c d e⟩ - -theorem pairwise_bind {R : β → β → Prop} {l : List α} {f : α → List β} : - List.Pairwise R (l.bind f) ↔ - (∀ a ∈ l, Pairwise R (f a)) ∧ Pairwise (fun a₁ a₂ => ∀ x ∈ f a₁, ∀ y ∈ f a₂, R x y) l := by - simp [List.bind, pairwise_join, pairwise_map] - -theorem pairwise_iff_forall_sublist : l.Pairwise R ↔ (∀ {a b}, [a,b] <+ l → R a b) := by - induction l with - | nil => simp - | cons hd tl IH => - rw [List.pairwise_cons] - constructor <;> intro h - · intro - | a, b, .cons _ hab => exact IH.mp h.2 hab - | _, b, .cons₂ _ hab => refine h.1 _ (hab.subset ?_); simp - · constructor - · intro x hx - apply h - rw [List.cons_sublist_cons, List.singleton_sublist] - exact hx - · apply IH.mpr - intro a b hab - apply h; exact hab.cons _ - -@[deprecated pairwise_iff_forall_sublist] +@[deprecated pairwise_iff_forall_sublist (since := "2023-09-18")] theorem pairwise_of_reflexive_on_dupl_of_forall_ne [DecidableEq α] {l : List α} {r : α → α → Prop} (hr : ∀ a, 1 < count a l → r a a) (h : ∀ a ∈ l, ∀ b ∈ l, a ≠ b → r a b) : l.Pairwise r := by apply pairwise_iff_forall_sublist.mpr @@ -200,57 +42,13 @@ theorem pairwise_of_reflexive_on_dupl_of_forall_ne [DecidableEq α] {l : List α apply h <;> try (apply hab.subset; simp) exact heq -/-- given a list `is` of monotonically increasing indices into `l`, getting each index - produces a sublist of `l`. -/ -theorem map_get_sublist {l : List α} {is : List (Fin l.length)} (h : is.Pairwise (·.val < ·.val)) : - is.map (get l) <+ l := by - suffices ∀ n l', l' = l.drop n → (∀ i ∈ is, n ≤ i) → map (get l) is <+ l' - from this 0 l (by simp) (by simp) - intro n l' hl' his - induction is generalizing n l' with - | nil => simp - | cons hd tl IH => - simp; cases hl' - have := IH h.of_cons (hd+1) _ rfl (pairwise_cons.mp h).1 - specialize his hd (.head _) - have := (drop_eq_get_cons ..).symm ▸ this.cons₂ (get l hd) - have := Sublist.append (nil_sublist (take hd l |>.drop n)) this - rwa [nil_append, ← (drop_append_of_le_length ?_), take_append_drop] at this - simp [Nat.min_eq_left (Nat.le_of_lt hd.isLt), his] - -/-- given a sublist `l' <+ l`, there exists a list of indices `is` such that - `l' = map (get l) is`. -/ -theorem sublist_eq_map_get (h : l' <+ l) : ∃ is : List (Fin l.length), - l' = map (get l) is ∧ is.Pairwise (· < ·) := by - induction h with - | slnil => exact ⟨[], by simp⟩ - | cons _ _ IH => - let ⟨is, IH⟩ := IH - refine ⟨is.map (·.succ), ?_⟩ - simp [comp, pairwise_map] - exact IH - | cons₂ _ _ IH => - rcases IH with ⟨is,IH⟩ - refine ⟨⟨0, by simp [Nat.zero_lt_succ]⟩ :: is.map (·.succ), ?_⟩ - simp [comp_def, pairwise_map, IH] - theorem pairwise_iff_get : Pairwise R l ↔ ∀ (i j) (_hij : i < j), R (get l i) (get l j) := by - rw [pairwise_iff_forall_sublist] + rw [pairwise_iff_getElem] constructor <;> intro h · intros i j h' - apply h - apply map_get_sublist (is := [i, j]) - rw [Fin.lt_def] at h'; simp [h'] - · intros a b h' - have ⟨is, h', hij⟩ := sublist_eq_map_get h' - rcases is with ⟨⟩ | ⟨a', ⟨⟩ | ⟨b', ⟨⟩⟩⟩ <;> simp at h' - rcases h' with ⟨rfl, rfl⟩ - apply h; simpa using hij - -theorem pairwise_replicate {α : Type _} {r : α → α → Prop} {x : α} (hx : r x x) : - ∀ n : Nat, Pairwise r (List.replicate n x) - | 0 => by simp - | n + 1 => by simp [mem_replicate, hx, pairwise_replicate hx n] + exact h _ _ _ _ h' + · intros i j hi hj h' + exact h ⟨i, hi⟩ ⟨j, hj⟩ h' /-! ### Pairwise filtering -/ diff --git a/Batteries/Data/List/Perm.lean b/Batteries/Data/List/Perm.lean index 49299089a5..5c31720c7c 100644 --- a/Batteries/Data/List/Perm.lean +++ b/Batteries/Data/List/Perm.lean @@ -4,10 +4,7 @@ Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad, Mario Carneiro -/ import Batteries.Tactic.Alias -import Batteries.Data.List.Init.Attach import Batteries.Data.List.Pairwise --- Adaptation note: nightly-2024-03-18. We should be able to remove this after nightly-2024-03-19. -import Lean.Elab.Tactic.Rfl /-! # List Permutations @@ -155,8 +152,8 @@ theorem Perm.filterMap (f : α → Option β) {l₁ l₂ : List α} (p : l₁ ~ filterMap f l₁ ~ filterMap f l₂ := by induction p with | nil => simp - | cons x _p IH => cases h : f x <;> simp [h, filterMap, IH, Perm.cons] - | swap x y l₂ => cases hx : f x <;> cases hy : f y <;> simp [hx, hy, filterMap, swap] + | cons x _p IH => cases h : f x <;> simp [h, filterMap_cons, IH, Perm.cons] + | swap x y l₂ => cases hx : f x <;> cases hy : f y <;> simp [hx, hy, filterMap_cons, swap] | trans _p₁ _p₂ IH₁ IH₂ => exact IH₁.trans IH₂ theorem Perm.map (f : α → β) {l₁ l₂ : List α} (p : l₁ ~ l₂) : map f l₁ ~ map f l₂ := @@ -234,7 +231,7 @@ theorem Subperm.trans {l₁ l₂ l₃ : List α} (s₁₂ : l₁ <+~ l₂) (s₂ ⟨l₁', p₁, s₁.trans s₂⟩ theorem Subperm.cons_right {α : Type _} {l l' : List α} (x : α) (h : l <+~ l') : l <+~ x :: l' := - h.trans (sublist_cons x l').subperm + 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 @@ -371,7 +368,7 @@ theorem perm_append_right_iff {l₁ l₂ : List α} (l) : l₁ ++ l ~ l₂ ++ l 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 _ _).subperm).trans s'.subperm + | .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` -/ @@ -412,7 +409,7 @@ theorem Subperm.exists_of_length_lt {l₁ l₂ : List α} (s : l₁ <+~ l₂) (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 _ _).subperm + | .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 => @@ -440,12 +437,12 @@ theorem Nodup.perm_iff_eq_of_sublist {l₁ l₂ l : List α} (d : Nodup l) | .cons _ s₁ => exact IH d.2 s₁ h | .cons₂ _ s₁ => have := Subperm.subset ⟨_, h.symm, s₂⟩ (.head _) - exact (d.1 _ this rfl).elim + exact (d.1 this).elim | cons₂ a _ IH => match s₁ with | .cons _ s₁ => have := Subperm.subset ⟨_, h, s₁⟩ (.head _) - exact (d.1 _ this rfl).elim + exact (d.1 this).elim | .cons₂ _ s₁ => rw [IH d.2 s₁ h.cons_inv] section DecidableEq @@ -464,7 +461,7 @@ theorem subperm_cons_erase (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 _ _).subperm + (erase_of_not_mem h).symm ▸ (sublist_cons_self _ _).subperm theorem erase_subperm (a : α) (l : List α) : l.erase a <+~ l := (erase_sublist _ _).subperm @@ -513,7 +510,7 @@ theorem erase_cons_subperm_cons_erase (a b : α) (l : List α) : 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] - rw [erase_cons_tail _ this] + rw [erase_cons_tail this] theorem subperm_cons_diff {a : α} {l₁ l₂ : List α} : (a :: l₁).diff l₂ <+~ a :: l₁.diff l₂ := by induction l₂ with @@ -643,7 +640,7 @@ theorem Perm.union {l₁ l₂ t₁ t₂ : List α} (p₁ : l₁ ~ l₂) (p₂ : theorem Perm.inter_right {l₁ l₂ : List α} (t₁ : List α) : l₁ ~ l₂ → l₁ ∩ t₁ ~ l₂ ∩ t₁ := .filter _ theorem Perm.inter_left (l : List α) {t₁ t₂ : List α} (p : t₁ ~ t₂) : l ∩ t₁ = l ∩ t₂ := - filter_congr' fun a _ => by simpa using p.mem_iff (a := a) + filter_congr fun a _ => by simpa using p.mem_iff (a := a) theorem Perm.inter {l₁ l₂ t₁ t₂ : List α} (p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : l₁ ∩ t₁ ~ l₂ ∩ t₂ := p₂.inter_left l₂ ▸ p₁.inter_right t₁ diff --git a/Batteries/Data/Nat/Basic.lean b/Batteries/Data/Nat/Basic.lean index 9f7c7d8f36..1d9658f49e 100644 --- a/Batteries/Data/Nat/Basic.lean +++ b/Batteries/Data/Nat/Basic.lean @@ -28,6 +28,15 @@ protected def strongRec {motive : Nat → Sort _} (ind : ∀ n, (∀ m, m < n protected def strongRecOn (t : Nat) {motive : Nat → Sort _} (ind : ∀ n, (∀ m, m < n → motive m) → motive n) : motive t := Nat.strongRec ind t +/-- + 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` -/ @@ -85,9 +94,6 @@ protected def casesDiagOn {motive : Nat → Nat → Sort _} (m n : Nat) Nat.recDiag zero_zero (fun _ _ => zero_succ _) (fun _ _ => succ_zero _) (fun _ _ _ => succ_succ _ _) m n -/-- Sum of a list of natural numbers. -/ -protected def sum (l : List Nat) : Nat := l.foldr (·+·) 0 - /-- Integer square root function. Implemented via Newton's method. -/ diff --git a/Batteries/Data/Nat/Lemmas.lean b/Batteries/Data/Nat/Lemmas.lean index 951f330e51..1c3edddeaf 100644 --- a/Batteries/Data/Nat/Lemmas.lean +++ b/Batteries/Data/Nat/Lemmas.lean @@ -151,19 +151,21 @@ protected def sum_trichotomy (a b : Nat) : a < b ⊕' a = b ⊕' b < a := /-! ## add -/ -@[deprecated] alias succ_add_eq_succ_add := Nat.succ_add_eq_add_succ +@[deprecated (since := "2023-11-25")] alias succ_add_eq_succ_add := Nat.succ_add_eq_add_succ /-! ## sub -/ -@[deprecated] protected alias le_of_le_of_sub_le_sub_right := Nat.le_of_sub_le_sub_right +@[deprecated (since := "2023-11-25")] +protected alias le_of_le_of_sub_le_sub_right := Nat.le_of_sub_le_sub_right -@[deprecated] protected alias le_of_le_of_sub_le_sub_left := Nat.le_of_sub_le_sub_left +@[deprecated (since := "2023-11-25")] +protected alias le_of_le_of_sub_le_sub_left := Nat.le_of_sub_le_sub_left /-! ### mul -/ -@[deprecated] protected alias mul_lt_mul := Nat.mul_lt_mul_of_lt_of_le' +@[deprecated (since := "2024-01-11")] protected alias mul_lt_mul := Nat.mul_lt_mul_of_lt_of_le' -@[deprecated] protected alias mul_lt_mul' := Nat.mul_lt_mul_of_le_of_lt +@[deprecated (since := "2024-01-11")] protected alias mul_lt_mul' := Nat.mul_lt_mul_of_le_of_lt /-! ### div/mod -/ @@ -175,12 +177,8 @@ protected def sum_trichotomy (a b : Nat) : a < b ⊕' a = b ⊕' b < a := /-! ### sum -/ -@[simp] theorem sum_nil : Nat.sum [] = 0 := rfl - -@[simp] theorem sum_cons : Nat.sum (a :: l) = a + Nat.sum l := rfl - @[simp] theorem sum_append : Nat.sum (l₁ ++ l₂) = Nat.sum l₁ + Nat.sum l₂ := by induction l₁ <;> simp [*, Nat.add_assoc] -@[deprecated] protected alias lt_connex := Nat.lt_or_gt_of_ne -@[deprecated] alias pow_two_pos := Nat.two_pow_pos -- deprecated 2024-02-09 +@[deprecated (since := "2024-03-05")] protected alias lt_connex := Nat.lt_or_gt_of_ne +@[deprecated (since := "2024-02-09")] alias pow_two_pos := Nat.two_pow_pos diff --git a/Batteries/Data/Option/Lemmas.lean b/Batteries/Data/Option/Lemmas.lean index a768a776ce..05a38b25a7 100644 --- a/Batteries/Data/Option/Lemmas.lean +++ b/Batteries/Data/Option/Lemmas.lean @@ -7,7 +7,7 @@ import Batteries.Tactic.Alias namespace Option -@[deprecated] alias to_list_some := toList_some -@[deprecated] alias to_list_none := toList_none +@[deprecated (since := "2024-03-05")] alias to_list_some := toList_some +@[deprecated (since := "2024-03-05")] alias to_list_none := toList_none end Option diff --git a/Batteries/Data/RBMap/Basic.lean b/Batteries/Data/RBMap/Basic.lean index ae60899f26..d1aff2dc3b 100644 --- a/Batteries/Data/RBMap/Basic.lean +++ b/Batteries/Data/RBMap/Basic.lean @@ -67,8 +67,8 @@ protected def max? : RBNode α → Option α | node _ _ v nil => some v | node _ _ _ r => r.max? -@[deprecated] protected alias min := RBNode.min? -@[deprecated] protected alias max := RBNode.max? +@[deprecated (since := "2024-04-17")] protected alias min := RBNode.min? +@[deprecated (since := "2024-04-17")] protected alias max := RBNode.max? /-- Fold a function in tree order along the nodes. `v₀` is used at `nil` nodes and @@ -669,8 +669,8 @@ instance : ToStream (RBSet α cmp) (RBNode.Stream α) := ⟨fun x => x.1.toStrea /-- `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? -@[deprecated] protected alias min := RBSet.min? -@[deprecated] protected alias max := RBSet.max? +@[deprecated (since := "2024-04-17")] protected alias min := RBSet.min? +@[deprecated (since := "2024-04-17")] protected alias max := RBSet.max? instance [Repr α] : Repr (RBSet α cmp) where reprPrec m prec := Repr.addAppParen ("RBSet.ofList " ++ repr m.toList) prec @@ -678,6 +678,16 @@ instance [Repr α] : Repr (RBSet α cmp) where /-- `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: @@ -1043,8 +1053,8 @@ instance : Stream (Values.Stream α β) β := ⟨Values.Stream.next?⟩ /-- `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? -@[deprecated] protected alias min := RBMap.min? -@[deprecated] protected alias max := RBMap.max? +@[deprecated (since := "2024-04-17")] protected alias min := RBMap.min? +@[deprecated (since := "2024-04-17")] protected alias max := RBMap.max? instance [Repr α] [Repr β] : Repr (RBMap α β cmp) where reprPrec m prec := Repr.addAppParen ("RBMap.ofList " ++ repr m.toList) prec diff --git a/Batteries/Data/RBMap/Lemmas.lean b/Batteries/Data/RBMap/Lemmas.lean index 37f24ebea9..5577b3a1a7 100644 --- a/Batteries/Data/RBMap/Lemmas.lean +++ b/Batteries/Data/RBMap/Lemmas.lean @@ -152,7 +152,6 @@ theorem min?_eq_toList_head? {t : RBNode α} : t.min? = t.toList.head? := by | nil => rfl | node _ l _ _ ih => cases l <;> simp [RBNode.min?, ih] - next ll _ _ => cases toList ll <;> rfl theorem max?_eq_toList_getLast? {t : RBNode α} : t.max? = t.toList.getLast? := by rw [← min?_reverse, min?_eq_toList_head?]; simp diff --git a/Batteries/Data/Range/Lemmas.lean b/Batteries/Data/Range/Lemmas.lean index 586f32a7e8..d71082848f 100644 --- a/Batteries/Data/Range/Lemmas.lean +++ b/Batteries/Data/Range/Lemmas.lean @@ -5,7 +5,6 @@ Authors: Mario Carneiro -/ import Batteries.Tactic.SeqFocus import Batteries.Data.List.Lemmas -import Batteries.Data.List.Init.Attach namespace Std.Range diff --git a/Batteries/Data/String/Lemmas.lean b/Batteries/Data/String/Lemmas.lean index 8a9376fe05..9984d0fb52 100644 --- a/Batteries/Data/String/Lemmas.lean +++ b/Batteries/Data/String/Lemmas.lean @@ -8,10 +8,12 @@ import Batteries.Data.List.Lemmas import Batteries.Data.String.Basic import Batteries.Tactic.Lint.Misc import Batteries.Tactic.SeqFocus +import Batteries.Tactic.SqueezeScope namespace String -attribute [ext] ext +-- TODO(kmill): add `@[ext]` attribute to `String.ext` in core. +attribute [ext (iff := false)] ext theorem lt_trans {s₁ s₂ s₃ : String} : s₁ < s₂ → s₂ < s₃ → s₁ < s₃ := List.lt_trans' (α := Char) Nat.lt_trans @@ -33,14 +35,14 @@ instance : Batteries.BEqOrd String := .compareOfLessAndEq String.lt_irrefl attribute [simp] toList -- prefer `String.data` over `String.toList` in lemmas -private theorem add_csize_pos : 0 < i + csize c := - Nat.add_pos_right _ (csize_pos c) +private theorem add_utf8Size_pos : 0 < i + Char.utf8Size c := + Nat.add_pos_right _ (Char.utf8Size_pos c) -private theorem ne_add_csize_add_self : i ≠ n + csize c + i := - Nat.ne_of_lt (Nat.lt_add_of_pos_left add_csize_pos) +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_csize : i ≠ i + (n + csize c) := - Nat.ne_of_lt (Nat.lt_add_of_pos_right add_csize_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 := utf8ByteSize.go @@ -51,7 +53,7 @@ private theorem ne_self_add_add_csize : i ≠ i + (n + csize c) := @[simp] theorem utf8Len_nil : utf8Len [] = 0 := rfl -@[simp] theorem utf8Len_cons (c cs) : utf8Len (c :: cs) = utf8Len cs + csize c := 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] @@ -63,7 +65,7 @@ private theorem ne_self_add_add_csize : i ≠ i + (n + csize c) := @[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_of_gt add_csize_pos] + cases l <;> simp [Nat.ne_of_gt add_utf8Size_pos] section open List @@ -86,12 +88,13 @@ end namespace Pos -attribute [ext] ext +-- TODO(kmill): add `@[ext]` attribute to `String.Pos.ext` in core. +attribute [ext (iff := false)] ext -theorem lt_addChar (p : Pos) (c : Char) : p < p + c := Nat.lt_add_of_pos_right (csize_pos _) +theorem lt_addChar (p : Pos) (c : Char) : p < p + c := Nat.lt_add_of_pos_right (Char.utf8Size_pos _) private theorem zero_ne_addChar {i : Pos} {c : Char} : 0 ≠ i + c := - ne_of_lt add_csize_pos + 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`. -/ def Valid (s : String) (p : Pos) : Prop := @@ -135,10 +138,10 @@ theorem utf8GetAux_add_right_cancel (s : List Char) (i p n : Nat) : utf8GetAux s ⟨i + n⟩ ⟨p + n⟩ = utf8GetAux s ⟨i⟩ ⟨p⟩ := by apply utf8InductionOn s ⟨i⟩ ⟨p⟩ (motive := fun s i => utf8GetAux s ⟨i.byteIdx + n⟩ ⟨p + n⟩ = utf8GetAux s i ⟨p⟩) <;> - simp [utf8GetAux] + simp only [utf8GetAux, Char.reduceDefault, implies_true, ↓reduceIte, ne_eq, pos_add_char] intro c cs ⟨i⟩ h ih - simp [Pos.ext_iff, Pos.addChar_eq] at h ⊢ - simp [Nat.add_right_cancel_iff, h] + simp only [Pos.ext_iff, Pos.addChar_eq] at h ⊢ + simp only [Nat.add_right_cancel_iff, h, ↓reduceIte] rw [Nat.add_right_comm] exact ih @@ -151,8 +154,9 @@ theorem utf8GetAux_of_valid (cs cs' : List Char) {i p : Nat} (hp : i + utf8Len c | [], [] => rfl | [], c::cs' => simp [← hp, utf8GetAux] | c::cs, cs' => - simp [utf8GetAux, -List.headD_eq_head?]; rw [if_neg] - case hnc => simp [← hp, Pos.ext_iff]; exact ne_self_add_add_csize + simp only [utf8GetAux, List.append_eq, Char.reduceDefault, ↓Char.isValue] + rw [if_neg] + case hnc => simp only [← hp, utf8Len_cons, Pos.ext_iff]; exact ne_self_add_add_utf8Size refine utf8GetAux_of_valid cs cs' ?_ simpa [Nat.add_assoc, Nat.add_comm] using hp @@ -169,8 +173,9 @@ theorem utf8GetAux?_of_valid (cs cs' : List Char) {i p : Nat} (hp : i + utf8Len | [], [] => rfl | [], c::cs' => simp [← hp, utf8GetAux?] | c::cs, cs' => - simp [utf8GetAux?]; rw [if_neg] - case hnc => simp [← hp, Pos.ext_iff]; exact ne_self_add_add_csize + simp only [utf8GetAux?, List.append_eq] + rw [if_neg] + case hnc => simp [← hp, Pos.ext_iff]; exact ne_self_add_add_utf8Size refine utf8GetAux?_of_valid cs cs' ?_ simpa [Nat.add_assoc, Nat.add_comm] using hp @@ -183,8 +188,9 @@ theorem utf8SetAux_of_valid (c' : Char) (cs cs' : List Char) {i p : Nat} (hp : i | [], [] => rfl | [], c::cs' => simp [← hp, utf8SetAux] | c::cs, cs' => - simp [utf8SetAux]; rw [if_neg] - case hnc => simp [← hp, Pos.ext_iff]; exact ne_self_add_add_csize + simp only [utf8SetAux, List.append_eq, List.cons_append] + rw [if_neg] + case hnc => simp [← hp, Pos.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 @@ -197,11 +203,11 @@ theorem modify_of_valid (cs cs' : List Char) : rw [modify, set_of_valid, get_of_valid]; cases cs' <;> rfl theorem next_of_valid' (cs cs' : List Char) : - next ⟨cs ++ cs'⟩ ⟨utf8Len cs⟩ = ⟨utf8Len cs + csize (cs'.headD default)⟩ := by + next ⟨cs ++ cs'⟩ ⟨utf8Len cs⟩ = ⟨utf8Len cs + (cs'.headD default).utf8Size⟩ := by simp only [next, get_of_valid]; rfl theorem next_of_valid (cs : List Char) (c : Char) (cs' : List Char) : - next ⟨cs ++ c :: cs'⟩ ⟨utf8Len cs⟩ = ⟨utf8Len cs + csize c⟩ := next_of_valid' .. + next ⟨cs ++ c :: cs'⟩ ⟨utf8Len cs⟩ = ⟨utf8Len cs + c.utf8Size⟩ := next_of_valid' .. @[simp] theorem atEnd_iff (s : String) (p : Pos) : atEnd s p ↔ s.endPos ≤ p := decide_eq_true_iff _ @@ -214,20 +220,24 @@ theorem valid_next {p : Pos} (h : p.Valid s) (h₂ : p < s.endPos) : (next s p). simpa using Pos.Valid.mk (cs ++ [c]) cs' theorem utf8PrevAux_of_valid {cs cs' : List Char} {c : Char} {i p : Nat} - (hp : i + (utf8Len cs + csize c) = p) : + (hp : i + (utf8Len cs + c.utf8Size) = p) : utf8PrevAux (cs ++ c :: cs') ⟨i⟩ ⟨p⟩ = ⟨i + utf8Len cs⟩ := by match cs with | [] => simp [utf8PrevAux, ← hp, Pos.addChar_eq] | c'::cs => - simp [utf8PrevAux, Pos.addChar_eq, ← hp]; rw [if_neg] + simp only [utf8PrevAux, Pos.addChar_eq, ← hp, utf8Len_cons, List.append_eq] + rw [if_neg] case hnc => - simp [Pos.ext_iff]; rw [Nat.add_right_comm, Nat.add_left_comm]; apply ne_add_csize_add_self + simp only [Pos.ext_iff] + rw [Nat.add_right_comm, Nat.add_left_comm] + apply ne_add_utf8Size_add_self 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) : - prev ⟨cs ++ c :: cs'⟩ ⟨utf8Len cs + csize c⟩ = ⟨utf8Len cs⟩ := by - simp [prev]; refine (if_neg (Pos.ne_of_gt add_csize_pos)).trans ?_ + prev ⟨cs ++ c :: cs'⟩ ⟨utf8Len cs + c.utf8Size⟩ = ⟨utf8Len cs⟩ := by + simp only [prev] + refine (if_neg (Pos.ne_of_gt add_utf8Size_pos)).trans ?_ rw [utf8PrevAux_of_valid] <;> simp theorem prev_of_valid' (cs cs' : List Char) : @@ -247,7 +257,7 @@ theorem back_eq (s : String) : back s = s.1.getLastD default := by theorem atEnd_of_valid (cs : List Char) (cs' : List Char) : atEnd ⟨cs ++ cs'⟩ ⟨utf8Len cs⟩ ↔ cs' = [] := by rw [atEnd_iff] - cases cs' <;> simp [Nat.lt_add_of_pos_right add_csize_pos] + cases cs' <;> simp [Nat.lt_add_of_pos_right add_utf8Size_pos] unseal posOfAux findAux in theorem posOfAux_eq (s c) : posOfAux s c = findAux s (· == c) := rfl @@ -268,13 +278,18 @@ theorem findAux_of_valid (p) : ∀ l m r, | 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_csize_pos)] + 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 at h1 h2; simp [h1, h2] - cases p c <;> simp - have foo := findAux_of_valid p (l++[c]) m r; simp at foo - rw [Nat.add_right_comm, Nat.add_assoc] at foo - rw [foo, Nat.add_right_comm, Nat.add_assoc] + 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.singleton_append, 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.1.takeWhile (!p ·))⟩ := by simpa using findAux_of_valid p [] s.1 [] @@ -285,10 +300,12 @@ theorem revFindAux_of_valid (p) : ∀ l r, | [], r => by unfold revFindAux List.dropWhile; simp | c::l, r => by unfold revFindAux List.dropWhile - rw [dif_neg (by exact Pos.ne_of_gt add_csize_pos)] + rw [dif_neg (by exact Pos.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 at h1 h2; simp [h1, h2] - cases p c <;> simp + 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) : @@ -305,19 +322,22 @@ theorem firstDiffPos_loop_eq (l₁ l₂ r₁ r₂ stop p) rw [ dif_pos <| by rw [hstop, ← hl₁, ← hl₂] - refine Nat.lt_min.2 ⟨?_, ?_⟩ <;> exact Nat.lt_add_of_pos_right add_csize_pos, + refine Nat.lt_min.2 ⟨?_, ?_⟩ <;> exact Nat.lt_add_of_pos_right add_utf8Size_pos, show get ⟨l₁ ++ a :: r₁⟩ ⟨p⟩ = a by simp [hl₁, get_of_valid], show get ⟨l₂ ++ b :: r₂⟩ ⟨p⟩ = b by simp [hl₂, get_of_valid]] - simp; split <;> simp - subst b - rw [show next ⟨l₁ ++ a :: r₁⟩ ⟨p⟩ = ⟨utf8Len l₁ + csize a⟩ by simp [hl₁, next_of_valid]] - simpa [← hl₁, ← Nat.add_assoc, Nat.add_right_comm] using - firstDiffPos_loop_eq (l₁ ++ [a]) (l₂ ++ [a]) r₁ r₂ stop (p + csize a) - (by simp [hl₁]) (by simp [hl₂]) (by simp [hstop, ← Nat.add_assoc, Nat.add_right_comm]) + simp only [bne_iff_ne, ne_eq, ite_not, decide_eq_true_eq] + split + · simp only [utf8Len_cons] + subst b + rw [show next ⟨l₁ ++ a :: r₁⟩ ⟨p⟩ = ⟨utf8Len l₁ + a.utf8Size⟩ by simp [hl₁, 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}, p < p + utf8Len cs → cs ≠ [] := by rintro _ h rfl; simp at 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₂ @@ -330,10 +350,11 @@ theorem firstDiffPos_eq (a b : String) : theorem 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 [go₂] + go₂ s ⟨i.byteIdx + n⟩ ⟨e + n⟩ = go₂ s i ⟨e⟩) + <;> simp only [ne_eq, go₂, pos_add_char, implies_true, ↓reduceIte] intro c cs ⟨i⟩ h ih - simp [Pos.ext_iff, Pos.addChar_eq] at h ⊢ - simp [Nat.add_right_cancel_iff, h] + simp only [Pos.ext_iff, Pos.addChar_eq] at h ⊢ + simp only [Nat.add_right_cancel_iff, h, ↓reduceIte, List.cons.injEq, true_and] rw [Nat.add_right_comm] exact ih @@ -341,32 +362,35 @@ theorem 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 [go₂, Pos.ext_iff, ne_add_csize_add_self, Pos.addChar_eq] + simp only [go₂, utf8Len_cons, Pos.ext_iff, ne_add_utf8Size_add_self, ↓reduceIte, List.append_eq, + Pos.addChar_eq, List.cons.injEq, true_and] apply go₂_append_left; rw [Nat.add_right_comm, Nat.add_assoc] theorem 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 [go₁] + go₁ s ⟨i.byteIdx + n⟩ ⟨b + n⟩ ⟨e + n⟩ = go₁ s i ⟨b⟩ ⟨e⟩) + <;> simp only [ne_eq, go₁, pos_add_char, implies_true, ↓reduceIte] · intro c cs apply go₂_add_right_cancel · intro c cs ⟨i⟩ h ih - simp [Pos.ext_iff, Pos.addChar_eq] at h ih ⊢ - simp [Nat.add_right_cancel_iff, h] + simp only [Pos.ext_iff, Pos.addChar_eq] at h ih ⊢ + simp only [Nat.add_right_cancel_iff, h, ↓reduceIte] rw [Nat.add_right_comm] exact ih theorem extract.go₁_cons_addChar (c : Char) (cs : List Char) (b e : Pos) : go₁ (c :: cs) 0 (b + c) (e + c) = go₁ cs 0 b e := by - simp [go₁, Pos.ext_iff, Nat.ne_of_lt add_csize_pos] + simp only [go₁, Pos.ext_iff, Pos.byteIdx_zero, pos_add_char, Nat.ne_of_lt add_utf8Size_pos, + ↓reduceIte] apply go₁_add_right_cancel theorem extract.go₁_append_right : ∀ (s t : List Char) (i b : Nat) (e : Pos), 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 [go₁, Pos.ext_iff, ne_add_csize_add_self, Pos.addChar_eq] + simp only [go₁, utf8Len_cons, Pos.ext_iff, ne_add_utf8Size_add_self, ↓reduceIte, List.append_eq, + Pos.addChar_eq] apply go₁_append_right; rw [Nat.add_right_comm, Nat.add_assoc] theorem extract.go₁_zero_utf8Len (s : List Char) : go₁ s 0 0 ⟨utf8Len s⟩ = s := @@ -375,13 +399,15 @@ theorem extract.go₁_zero_utf8Len (s : List Char) : go₁ s 0 0 ⟨utf8Len s⟩ theorem extract_cons_addChar (c : Char) (cs : List Char) (b e : Pos) : extract ⟨c :: cs⟩ (b + c) (e + c) = extract ⟨cs⟩ b e := by - simp [extract, Nat.add_le_add_iff_right] + simp only [extract, pos_add_char, ge_iff_le, Nat.add_le_add_iff_right] split <;> [rfl; rw [extract.go₁_cons_addChar]] theorem extract_zero_endPos : ∀ (s : String), s.extract 0 (endPos s) = s | ⟨[]⟩ => rfl | ⟨c :: cs⟩ => by - simp [extract, Nat.ne_of_gt add_csize_pos]; congr + simp only [extract, Pos.byteIdx_zero, endPos_eq, utf8Len_cons, ge_iff_le, Nat.le_zero_eq, + Nat.ne_of_gt add_utf8Size_pos, ↓reduceIte] + congr apply extract.go₁_zero_utf8Len theorem extract_of_valid (l m r : List Char) : @@ -396,11 +422,18 @@ theorem splitAux_of_valid (p l m r acc) : splitAux ⟨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 [by simpa using atEnd_of_valid (l ++ m) r]; split + simp only [List.append_assoc, atEnd_iff, endPos_eq, utf8Len_append, Pos.mk_le_mk, + Nat.add_le_add_iff_left, by simpa using atEnd_of_valid (l ++ m) r, 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 [by simpa 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] + simp only [by + simpa 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 · simpa [Nat.add_assoc] using splitAux_of_valid p (l++m++[c]) [] r (⟨m⟩::acc) · simpa [Nat.add_assoc] using splitAux_of_valid p l (m++[c]) r acc @@ -478,7 +511,7 @@ theorem pos_eq_zero {l r it} (h : ValidFor l r it) : it.2 = 0 ↔ l = [] := by simp [h.pos, Pos.ext_iff] theorem pos_eq_endPos {l r it} (h : ValidFor l r it) : it.2 = it.1.endPos ↔ r = [] := by - simp [h.pos, h.toString, Pos.ext_iff] + simp only [h.pos, h.toString, endPos_eq, utf8Len_reverseAux, Pos.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 @@ -494,15 +527,21 @@ 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 at this; simp [Iterator.prev, this] + 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 [Iterator.prev, h.toString, h.pos]; constructor + | it, h => by + simp only [Iterator.prev, h.toString, List.reverseAux_nil, h.pos, utf8Len_nil, + Pos.mk_zero, prev_zero] + constructor theorem atEnd : ∀ {it}, ValidFor l r it → (it.atEnd ↔ r = []) | it, h => by - simp [Iterator.atEnd, h.pos, h.toString] + simp only [Iterator.atEnd, h.pos, h.toString, endPos_eq, 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 ≠ []) @@ -515,26 +554,29 @@ theorem setCurr' : ∀ {it}, ValidFor l r it → ValidFor l (r.modifyHead fun _ => c) (it.setCurr c) | it, h => by cases h.out' - simp [Iterator.setCurr] + simp only [setCurr, utf8Len_reverse] refine .of_eq _ ?_ (by simp) have := set_of_valid l.reverse r c - simp at this; simp [List.reverseAux_eq, this] + simp only [utf8Len_reverse] at this; simp [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 [Iterator.toEnd, h.toString] + simp only [Iterator.toEnd, h.toString, endPos_eq, utf8Len_reverseAux] exact .of_eq _ (by simp [List.reverseAux_eq]) (by simp [Nat.add_comm]) theorem toEnd' (it : Iterator) : ValidFor it.s.1.reverse [] it.toEnd := by - simp [Iterator.toEnd] + simp only [Iterator.toEnd] exact .of_eq _ (by simp [List.reverseAux_eq]) (by simp [endPos, utf8ByteSize]) theorem extract (h₁ : ValidFor l (m ++ r) it₁) (h₂ : ValidFor (m.reverse ++ l) r it₂) : it₁.extract it₂ = ⟨m⟩ := by cases h₁.out; cases h₂.out - simp [Iterator.extract, List.reverseAux_eq, Nat.not_lt.2 (Nat.le_add_left ..)] + 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_lt_eq, 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 = ⟨r⟩ := by @@ -545,7 +587,7 @@ 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 [h, Iterator.nextn] + simp only [Iterator.nextn] have a::r := r simpa using h.next.nextn _ (Nat.le_of_succ_le_succ hn) @@ -553,7 +595,7 @@ 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 [h, Iterator.prevn] + simp only [Iterator.prevn] have a::l := l simpa using h.prev.prevn _ (Nat.le_of_succ_le_succ hn) @@ -606,10 +648,10 @@ theorem offsetOfPosAux_of_valid : ∀ l m r n, | 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_csize_pos))] + 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 [next_of_valid l c (m++r)] - simpa [← Nat.add_assoc, Nat.add_right_comm, Nat.succ_eq_add_one] using + 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 ⟨l ++ r⟩ ⟨utf8Len l⟩ = l.length := by @@ -621,8 +663,9 @@ theorem foldlAux_of_valid (f : α → Char → α) : ∀ l m r 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_csize_pos)] - simp [get_of_valid l (c::(m++r)), next_of_valid l c (m++r)] + 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.1.foldl f a := by @@ -634,9 +677,9 @@ theorem foldrAux_of_valid (f : Char → α → α) (l m r a) : rw [← m.reverse_reverse] induction m.reverse generalizing r a with (unfold foldrAux; simp) | cons c m IH => - rw [if_pos (by exact Nat.lt_add_of_pos_right add_csize_pos)] - simp [← Nat.add_assoc, by simpa using prev_of_valid (l++m.reverse) c r] - simp [by simpa using get_of_valid (l++m.reverse) (c::r)] + 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.1.foldr f a := by @@ -648,8 +691,10 @@ theorem anyAux_of_valid (p : Char → Bool) : ∀ l m r, | 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_csize_pos)] - simp [get_of_valid l (c::(m++r)), next_of_valid l c (m++r)] + 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 @@ -672,7 +717,8 @@ theorem mapAux_of_valid (f : Char → Char) : ∀ l r, mapAux f ⟨utf8Len l⟩ | l, c::r => by unfold mapAux rw [dif_neg (by rw [atEnd_of_valid]; simp)] - simp [set_of_valid l (c::r), get_of_valid l (c::r), next_of_valid l (f c) r] + simp only [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 = ⟨s.1.map f⟩ := by @@ -689,8 +735,9 @@ theorem takeWhileAux_of_valid (p : Char → Bool) : ∀ l m r, | 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_csize_pos)] - simp [get_of_valid l (c::(m++r)), next_of_valid l c (m++r)] + 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 @@ -752,33 +799,35 @@ theorem toString : ∀ {s}, ValidFor l m r s → s.toString = ⟨m⟩ theorem toIterator : ∀ {s}, ValidFor l m r s → s.toIterator.ValidFor l.reverse (m ++ r) | _, h => by - simp [Substring.toIterator] + 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₁ + csize c⟩ +theorem next : ∀ {s}, ValidFor l (m₁ ++ c :: m₂) r s → + s.next ⟨utf8Len m₁⟩ = ⟨utf8Len m₁ + c.utf8Size⟩ | _, ⟨⟩ => by - simp [Substring.next] + simp only [Substring.next, utf8Len_append, utf8Len_cons, List.append_assoc, List.cons_append] rw [if_neg (mt Pos.ext_iff.1 ?a)] case a => simpa [Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using - @ne_add_csize_add_self (utf8Len l + utf8Len m₁) (utf8Len m₂) c + @ne_add_utf8Size_add_self (utf8Len l + utf8Len m₁) (utf8Len m₂) c have := next_of_valid (l ++ m₁) c (m₂ ++ r) - simp [Pos.add_eq] at this ⊢; rw [this] + simp only [List.append_assoc, utf8Len_append, Pos.add_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.add_eq] -theorem prev : ∀ {s}, ValidFor l (m₁ ++ c :: m₂) r s → s.prev ⟨utf8Len m₁ + csize c⟩ = ⟨utf8Len m₁⟩ +theorem prev : ∀ {s}, ValidFor l (m₁ ++ c :: m₂) r s → + s.prev ⟨utf8Len m₁ + c.utf8Size⟩ = ⟨utf8Len m₁⟩ | _, ⟨⟩ => by - simp [Substring.prev] + simp only [Substring.prev, List.append_assoc, List.cons_append] rw [if_neg (mt Pos.ext_iff.1 <| Ne.symm ?a)] - case a => simpa [Nat.add_comm] using @ne_add_csize_add_self (utf8Len l) (utf8Len m₁) c + 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 [Pos.add_eq, Nat.add_assoc] at this ⊢; rw [this] + simp only [List.append_assoc, utf8Len_append, Nat.add_assoc, Pos.add_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⟩ @@ -789,7 +838,7 @@ 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 [Substring.nextn] + simp only [Substring.nextn] match m₂ with | [] => simp at h; simp [h.next_stop, h.nextn_stop] | c::m₂ => @@ -801,7 +850,7 @@ 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 [Substring.prevn] + simp only [Substring.prevn] match m₁ with | [] => simp | c::m₁ => @@ -814,8 +863,9 @@ theorem front : ∀ {s}, ValidFor l (c :: m) r s → s.front = c 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 at this; simp [Substring.drop, this] - simp [h.str, h.startPos, h.stopPos] + simp only [utf8Len_nil, Pos.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] @@ -824,8 +874,9 @@ theorem drop : ∀ {s}, ValidFor l m r s → ∀ n, ValidFor (l ++ m.take n) (m. 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 [Substring.take, this] - simp [h.str, h.startPos, h.stopPos] + 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] @@ -839,14 +890,16 @@ theorem atEnd : ∀ {s}, ValidFor l m r s → (s.atEnd ⟨p⟩ ↔ p = utf8Len m theorem extract : ∀ {s}, ValidFor l m r s → ValidFor ml mm mr ⟨⟨m⟩, b, e⟩ → ∃ l' r', ValidFor l' mm r' (s.extract b e) | _, ⟨⟩, ⟨⟩ => by - simp [Substring.extract]; split + simp only [Substring.extract, ge_iff_le, Pos.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 [Nat.min_eq_min] <;> rw [Nat.min_eq_right] <;> - try simp [Nat.add_le_add_iff_left, Nat.le_add_right] + simp only [Pos.add_byteIdx, 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] -- TODO: splitOn @@ -888,11 +941,11 @@ namespace Valid theorem validFor : ∀ {s}, Valid s → ∃ l m r, ValidFor l m r s | ⟨⟨_⟩, ⟨_⟩, ⟨_⟩⟩, ⟨⟨l, mr, rfl, rfl⟩, ⟨lm, r, e, rfl⟩, h⟩ => by - simp at * + simp only [utf8ByteSize.go_eq, Pos.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 at h + 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 @@ -913,22 +966,22 @@ theorem isEmpty : ∀ {s}, Valid s → (s.isEmpty ↔ s.toString = "") theorem get : ∀ {s}, Valid s → s.toString.1 = m₁ ++ c :: m₂ → s.get ⟨utf8Len m₁⟩ = c | _, h, e => by let ⟨l, m, r, h⟩ := h.validFor - simp [h.toString] at e; subst e; simp [h.get] + simp only [h.toString] at e; subst e; simp [h.get] theorem next : ∀ {s}, Valid s → s.toString.1 = m₁ ++ c :: m₂ → - s.next ⟨utf8Len m₁⟩ = ⟨utf8Len m₁ + csize c⟩ + s.next ⟨utf8Len m₁⟩ = ⟨utf8Len m₁ + c.utf8Size⟩ | _, h, e => by let ⟨l, m, r, h⟩ := h.validFor - simp [h.toString] at e; subst e; simp [h.next] + simp only [h.toString] 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.1 = m₁ ++ c :: m₂ → - s.prev ⟨utf8Len m₁ + csize c⟩ = ⟨utf8Len m₁⟩ + s.prev ⟨utf8Len m₁ + c.utf8Size⟩ = ⟨utf8Len m₁⟩ | _, h, e => by let ⟨l, m, r, h⟩ := h.validFor - simp [h.toString] at e; subst e; simp [h.prev] + simp only [h.toString] 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] @@ -937,13 +990,13 @@ theorem nextn : ∀ {s}, Valid s → s.toString.1 = 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 [h.toString] at e; subst e; simp [h.nextn] + simp only [h.toString] at e; subst e; simp [h.nextn] theorem prevn : ∀ {s}, Valid s → s.toString.1 = m₁.reverse ++ m₂ → ∀ n, s.prevn n ⟨utf8Len m₁⟩ = ⟨utf8Len (m₁.drop n)⟩ | _, h, e => by let ⟨l, m, r, h⟩ := h.validFor - simp [h.toString] at e; subst e; simp [h.prevn] + simp only [h.toString] at e; subst e; simp [h.prevn] theorem front : ∀ {s}, Valid s → s.toString.1 = c :: m → s.front = c | _, h => h.get (m₁ := []) diff --git a/Batteries/Data/Thunk.lean b/Batteries/Data/Thunk.lean new file mode 100644 index 0000000000..88c92c3784 --- /dev/null +++ b/Batteries/Data/Thunk.lean @@ -0,0 +1,10 @@ +/- +Copyright (c) 2024 François G. Dorais. All rights reserved. +Released under Apache 2.0 license as described in the file LICENSE +Authors: François G. Dorais, et al. +-/ + +namespace Thunk + +@[ext] protected theorem ext : {a b : Thunk α} → a.get = b.get → a = b + | {..}, {..}, heq => congrArg _ <| funext fun _ => heq diff --git a/Batteries/Data/UInt.lean b/Batteries/Data/UInt.lean index 3151a25852..44ebfd9b80 100644 --- a/Batteries/Data/UInt.lean +++ b/Batteries/Data/UInt.lean @@ -10,10 +10,14 @@ import Batteries.Classes.Order @[ext] theorem UInt8.ext : {x y : UInt8} → x.toNat = y.toNat → x = y | ⟨⟨_,_⟩⟩, ⟨⟨_,_⟩⟩, rfl => rfl -theorem UInt8.ext_iff {x y : UInt8} : x = y ↔ x.toNat = y.toNat := ⟨congrArg _, UInt8.ext⟩ - @[simp] theorem UInt8.val_val_eq_toNat (x : UInt8) : x.val.val = x.toNat := rfl +@[simp] theorem UInt8.val_ofNat (n) : + (no_index (OfNat.ofNat n) : UInt8).val = OfNat.ofNat n := rfl + +@[simp] theorem UInt8.toNat_ofNat (n) : + (no_index (OfNat.ofNat n) : UInt8).toNat = n % UInt8.size := rfl + theorem UInt8.toNat_lt (x : UInt8) : x.toNat < 2 ^ 8 := x.val.isLt @[simp] theorem UInt8.toUInt16_toNat (x : UInt8) : x.toUInt16.toNat = x.toNat := rfl @@ -22,6 +26,21 @@ theorem UInt8.toNat_lt (x : UInt8) : x.toNat < 2 ^ 8 := x.val.isLt @[simp] theorem UInt8.toUInt64_toNat (x : UInt8) : x.toUInt64.toNat = x.toNat := rfl +theorem UInt8.toNat_zero : (0 : UInt8).toNat = 0 := rfl + +theorem UInt8.toNat_add (x y : UInt8) : (x + y).toNat = (x.toNat + y.toNat) % UInt8.size := rfl + +theorem UInt8.toNat_sub (x y : UInt8) : + (x - y).toNat = (UInt8.size - y.toNat + x.toNat) % UInt8.size := rfl + +theorem UInt8.toNat_mul (x y : UInt8) : (x * y).toNat = (x.toNat * y.toNat) % UInt8.size := rfl + +theorem UInt8.toNat_div (x y : UInt8) : (x / y).toNat = x.toNat / y.toNat := rfl + +theorem UInt8.toNat_mod (x y : UInt8) : (x % y).toNat = x.toNat % y.toNat := rfl + +theorem UInt8.toNat_modn (x : UInt8) (n) : (x.modn n).toNat = x.toNat % n := rfl + theorem UInt8.le_antisymm_iff {x y : UInt8} : x = y ↔ x ≤ y ∧ y ≤ x := UInt8.ext_iff.trans Nat.le_antisymm_iff @@ -36,11 +55,15 @@ instance : Batteries.LawfulOrd UInt8 := .compareOfLessAndEq @[ext] theorem UInt16.ext : {x y : UInt16} → x.toNat = y.toNat → x = y | ⟨⟨_,_⟩⟩, ⟨⟨_,_⟩⟩, rfl => rfl -theorem UInt16.ext_iff {x y : UInt16} : x = y ↔ x.toNat = y.toNat := ⟨congrArg _, UInt16.ext⟩ +@[simp] theorem UInt16.val_val_eq_toNat (x : UInt16) : x.val.val = x.toNat := rfl -theorem UInt16.toNat_lt (x : UInt16) : x.toNat < 2 ^ 16 := x.val.isLt +@[simp] theorem UInt16.val_ofNat (n) : + (no_index (OfNat.ofNat n) : UInt16).val = OfNat.ofNat n := rfl -@[simp] theorem UInt16.val_val_eq_toNat (x : UInt16) : x.val.val = x.toNat := rfl +@[simp] theorem UInt16.toNat_ofNat (n) : + (no_index (OfNat.ofNat n) : UInt16).toNat = n % UInt16.size := rfl + +theorem UInt16.toNat_lt (x : UInt16) : x.toNat < 2 ^ 16 := x.val.isLt @[simp] theorem UInt16.toUInt8_toNat (x : UInt16) : x.toUInt8.toNat = x.toNat % 2 ^ 8 := rfl @@ -48,6 +71,21 @@ theorem UInt16.toNat_lt (x : UInt16) : x.toNat < 2 ^ 16 := x.val.isLt @[simp] theorem UInt16.toUInt64_toNat (x : UInt16) : x.toUInt64.toNat = x.toNat := rfl +theorem UInt16.toNat_zero : (0 : UInt16).toNat = 0 := rfl + +theorem UInt16.toNat_add (x y : UInt16) : (x + y).toNat = (x.toNat + y.toNat) % UInt16.size := rfl + +theorem UInt16.toNat_sub (x y : UInt16) : + (x - y).toNat = (UInt16.size - y.toNat + x.toNat) % UInt16.size := rfl + +theorem UInt16.toNat_mul (x y : UInt16) : (x * y).toNat = (x.toNat * y.toNat) % UInt16.size := rfl + +theorem UInt16.toNat_div (x y : UInt16) : (x / y).toNat = x.toNat / y.toNat := rfl + +theorem UInt16.toNat_mod (x y : UInt16) : (x % y).toNat = x.toNat % y.toNat := rfl + +theorem UInt16.toNat_modn (x : UInt16) (n) : (x.modn n).toNat = x.toNat % n := rfl + theorem UInt16.le_antisymm_iff {x y : UInt16} : x = y ↔ x ≤ y ∧ y ≤ x := UInt16.ext_iff.trans Nat.le_antisymm_iff @@ -62,10 +100,14 @@ instance : Batteries.LawfulOrd UInt16 := .compareOfLessAndEq @[ext] theorem UInt32.ext : {x y : UInt32} → x.toNat = y.toNat → x = y | ⟨⟨_,_⟩⟩, ⟨⟨_,_⟩⟩, rfl => rfl -theorem UInt32.ext_iff {x y : UInt32} : x = y ↔ x.toNat = y.toNat := ⟨congrArg _, UInt32.ext⟩ - @[simp] theorem UInt32.val_val_eq_toNat (x : UInt32) : x.val.val = x.toNat := rfl +@[simp] theorem UInt32.val_ofNat (n) : + (no_index (OfNat.ofNat n) : UInt32).val = OfNat.ofNat n := rfl + +@[simp] theorem UInt32.toNat_ofNat (n) : + (no_index (OfNat.ofNat n) : UInt32).toNat = n % UInt32.size := rfl + theorem UInt32.toNat_lt (x : UInt32) : x.toNat < 2 ^ 32 := x.val.isLt @[simp] theorem UInt32.toUInt8_toNat (x : UInt32) : x.toUInt8.toNat = x.toNat % 2 ^ 8 := rfl @@ -74,6 +116,21 @@ theorem UInt32.toNat_lt (x : UInt32) : x.toNat < 2 ^ 32 := x.val.isLt @[simp] theorem UInt32.toUInt64_toNat (x : UInt32) : x.toUInt64.toNat = x.toNat := rfl +theorem UInt32.toNat_zero : (0 : UInt32).toNat = 0 := rfl + +theorem UInt32.toNat_add (x y : UInt32) : (x + y).toNat = (x.toNat + y.toNat) % UInt32.size := rfl + +theorem UInt32.toNat_sub (x y : UInt32) : + (x - y).toNat = (UInt32.size - y.toNat + x.toNat) % UInt32.size := rfl + +theorem UInt32.toNat_mul (x y : UInt32) : (x * y).toNat = (x.toNat * y.toNat) % UInt32.size := rfl + +theorem UInt32.toNat_div (x y : UInt32) : (x / y).toNat = x.toNat / y.toNat := rfl + +theorem UInt32.toNat_mod (x y : UInt32) : (x % y).toNat = x.toNat % y.toNat := rfl + +theorem UInt32.toNat_modn (x : UInt32) (n) : (x.modn n).toNat = x.toNat % n := rfl + theorem UInt32.le_antisymm_iff {x y : UInt32} : x = y ↔ x ≤ y ∧ y ≤ x := UInt32.ext_iff.trans Nat.le_antisymm_iff @@ -88,10 +145,14 @@ instance : Batteries.LawfulOrd UInt32 := .compareOfLessAndEq @[ext] theorem UInt64.ext : {x y : UInt64} → x.toNat = y.toNat → x = y | ⟨⟨_,_⟩⟩, ⟨⟨_,_⟩⟩, rfl => rfl -theorem UInt64.ext_iff {x y : UInt64} : x = y ↔ x.toNat = y.toNat := ⟨congrArg _, UInt64.ext⟩ - @[simp] theorem UInt64.val_val_eq_toNat (x : UInt64) : x.val.val = x.toNat := rfl +@[simp] theorem UInt64.val_ofNat (n) : + (no_index (OfNat.ofNat n) : UInt64).val = OfNat.ofNat n := rfl + +@[simp] theorem UInt64.toNat_ofNat (n) : + (no_index (OfNat.ofNat n) : UInt64).toNat = n % UInt64.size := rfl + theorem UInt64.toNat_lt (x : UInt64) : x.toNat < 2 ^ 64 := x.val.isLt @[simp] theorem UInt64.toUInt8_toNat (x : UInt64) : x.toUInt8.toNat = x.toNat % 2 ^ 8 := rfl @@ -100,6 +161,21 @@ theorem UInt64.toNat_lt (x : UInt64) : x.toNat < 2 ^ 64 := x.val.isLt @[simp] theorem UInt64.toUInt32_toNat (x : UInt64) : x.toUInt32.toNat = x.toNat % 2 ^ 32 := rfl +theorem UInt64.toNat_zero : (0 : UInt64).toNat = 0 := rfl + +theorem UInt64.toNat_add (x y : UInt64) : (x + y).toNat = (x.toNat + y.toNat) % UInt64.size := rfl + +theorem UInt64.toNat_sub (x y : UInt64) : + (x - y).toNat = (UInt64.size - y.toNat + x.toNat) % UInt64.size := rfl + +theorem UInt64.toNat_mul (x y : UInt64) : (x * y).toNat = (x.toNat * y.toNat) % UInt64.size := rfl + +theorem UInt64.toNat_div (x y : UInt64) : (x / y).toNat = x.toNat / y.toNat := rfl + +theorem UInt64.toNat_mod (x y : UInt64) : (x % y).toNat = x.toNat % y.toNat := rfl + +theorem UInt64.toNat_modn (x : UInt64) (n) : (x.modn n).toNat = x.toNat % n := rfl + theorem UInt64.le_antisymm_iff {x y : UInt64} : x = y ↔ x ≤ y ∧ y ≤ x := UInt64.ext_iff.trans Nat.le_antisymm_iff @@ -114,10 +190,14 @@ instance : Batteries.LawfulOrd UInt64 := .compareOfLessAndEq @[ext] theorem USize.ext : {x y : USize} → x.toNat = y.toNat → x = y | ⟨⟨_,_⟩⟩, ⟨⟨_,_⟩⟩, rfl => rfl -theorem USize.ext_iff {x y : USize} : x = y ↔ x.toNat = y.toNat := ⟨congrArg _, USize.ext⟩ - @[simp] theorem USize.val_val_eq_toNat (x : USize) : x.val.val = x.toNat := rfl +@[simp] theorem USize.val_ofNat (n) : + (no_index (OfNat.ofNat n) : USize).val = OfNat.ofNat n := rfl + +@[simp] theorem USize.toNat_ofNat (n) : + (no_index (OfNat.ofNat n) : USize).toNat = n % USize.size := rfl + theorem USize.size_eq : USize.size = 2 ^ System.Platform.numBits := by have : 1 ≤ 2 ^ System.Platform.numBits := Nat.succ_le_of_lt (Nat.two_pow_pos _) rw [USize.size, Nat.sub_add_cancel this] @@ -140,6 +220,21 @@ theorem USize.toNat_lt (x : USize) : x.toNat < 2 ^ System.Platform.numBits := by @[simp] theorem UInt32.toUSize_toNat (x : UInt32) : x.toUSize.toNat = x.toNat := rfl +theorem USize.toNat_zero : (0 : USize).toNat = 0 := rfl + +theorem USize.toNat_add (x y : USize) : (x + y).toNat = (x.toNat + y.toNat) % USize.size := rfl + +theorem USize.toNat_sub (x y : USize) : + (x - y).toNat = (USize.size - y.toNat + x.toNat) % USize.size := rfl + +theorem USize.toNat_mul (x y : USize) : (x * y).toNat = (x.toNat * y.toNat) % USize.size := rfl + +theorem USize.toNat_div (x y : USize) : (x / y).toNat = x.toNat / y.toNat := rfl + +theorem USize.toNat_mod (x y : USize) : (x % y).toNat = x.toNat % y.toNat := rfl + +theorem USize.toNat_modn (x : USize) (n) : (x.modn n).toNat = x.toNat % n := rfl + theorem USize.le_antisymm_iff {x y : USize} : x = y ↔ x ≤ y ∧ y ≤ x := USize.ext_iff.trans Nat.le_antisymm_iff diff --git a/Batteries/Data/UnionFind/Basic.lean b/Batteries/Data/UnionFind/Basic.lean index 24966452c2..292f4285eb 100644 --- a/Batteries/Data/UnionFind/Basic.lean +++ b/Batteries/Data/UnionFind/Basic.lean @@ -46,13 +46,17 @@ theorem lt_of_parentD : parentD arr i ≠ i → i < arr.size := theorem parentD_set {arr : Array UFNode} {x v i} : parentD (arr.set x v) i = if x.1 = i then v.parent else parentD arr i := by - rw [parentD]; simp [Array.get_eq_getElem, parentD] - split <;> [split <;> simp [Array.get_set, *]; split <;> [(subst i; cases ‹¬_› x.2); rfl]] + rw [parentD]; simp only [Array.size_set, Array.get_eq_getElem, parentD] + split + · split <;> simp_all + · split <;> [(subst i; cases ‹¬_› x.2); rfl] theorem rankD_set {arr : Array UFNode} {x v i} : rankD (arr.set x v) i = if x.1 = i then v.rank else rankD arr i := by - rw [rankD]; simp [Array.get_eq_getElem, rankD] - split <;> [split <;> simp [Array.get_set, *]; split <;> [(subst i; cases ‹¬_› x.2); rfl]] + rw [rankD]; simp only [Array.size_set, Array.get_eq_getElem, rankD] + split + · split <;> simp_all + · split <;> [(subst i; cases ‹¬_› x.2); rfl] end UnionFind @@ -146,7 +150,7 @@ theorem rank'_lt_rankMax (self : UnionFind) (i : Fin self.size) : 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 [rankMax, Array.foldr_eq_foldr_data] + simp only [Array.get_eq_getElem, rankMax, Array.foldr_eq_foldr_data] exact Nat.lt_succ.2 <| go (self.arr.data.get_mem i.1 i.2) theorem rankD_lt_rankMax (self : UnionFind) (i : Nat) : @@ -156,11 +160,11 @@ theorem rankD_lt_rankMax (self : UnionFind) (i : Nat) : 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 [rankD, Array.get_eq_getElem, Array.get_push] + simp only [rankD, Array.size_push, Array.get_eq_getElem, Array.get_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 [parentD, Array.get_eq_getElem, Array.get_push] + simp only [parentD, Array.size_push, Array.get_eq_getElem, Array.get_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 ‹_›) @@ -169,9 +173,9 @@ theorem push_parentD (arr : Array UFNode) : parentD (arr.push ⟨arr.size, 0⟩) def push (self : UnionFind) : UnionFind where arr := self.arr.push ⟨self.arr.size, 0⟩ parentD_lt {i} := by - simp [push_parentD]; simp [parentD] + simp only [Array.size_push, push_parentD]; simp only [parentD, Array.get_eq_getElem] split <;> [exact fun _ => Nat.lt_succ_of_lt (self.parent'_lt _); exact id] - rankD_lt := by simp [push_parentD, push_rankD]; exact self.rank_lt + 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 := @@ -205,18 +209,23 @@ 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, -Array.get_eq_getElem]; simp [parentD_of_not_lt, *]] + rw [rootD] + split + · simp [parentD, parent_root, -Array.get_eq_getElem] + · simp [parentD_of_not_lt, *] @[nolint unusedHavesSuffices] theorem rootD_parent (self : UnionFind) (x : Nat) : self.rootD (self.parent x) = self.rootD x := by - simp [rootD, parent_lt]; split <;> simp [parentD, parentD_of_not_lt, *, -Array.get_eq_getElem] - (conv => rhs; rw [root]); split - · rw [root, dif_pos] <;> simp [*, -Array.get_eq_getElem] - · simp + simp only [rootD, Array.data_length, 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 [rootD]; split <;> simp [*] + simp only [rootD, Array.data_length]; split <;> simp [*] @[nolint unusedHavesSuffices] theorem rootD_eq_self {self : UnionFind} {x : Nat} : self.rootD x = x ↔ self.parent x = x := by @@ -273,7 +282,9 @@ 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; split <;> simp + rw [findAux, root] + simp only [Array.data_length, Array.get_eq_getElem, 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 @@ -286,7 +297,7 @@ theorem findAux_s {self : UnionFind} {x : Fin self.size} : rw [show self.rootD _ = (self.findAux ⟨_, self.parent'_lt x⟩).root from _] · rw [findAux]; split <;> rfl · rw [← rootD_parent, parent, parentD_eq] - simp [findAux_root, rootD] + simp only [rootD, Array.get_eq_getElem, Array.data_length, findAux_root] apply dif_pos exact parent'_lt .. @@ -299,7 +310,8 @@ theorem rankD_findAux {self : UnionFind} {x : Fin self.size} : rw [rankD_eq' (by simp [FindAux.size_eq, h]), Array.get_modify (by rwa [FindAux.size_eq])] split <;> simp [← rankD_eq, rankD_findAux (x := ⟨_, self.parent'_lt x⟩), -Array.get_eq_getElem] else - simp [rank, rankD]; rw [dif_neg (by rwa [FindAux.size_eq]), dif_neg h] + simp only [rankD, Array.data_length, Array.get_eq_getElem, 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} : @@ -311,7 +323,7 @@ theorem parentD_findAux {self : UnionFind} {x : Fin self.size} : · next h => rw [parentD]; split <;> rename_i h' · rw [Array.get_modify (by simpa using h')] - simp [@eq_comm _ i, -Array.get_eq_getElem] + simp only [Array.data_length, @eq_comm _ i] split <;> simp [← parentD_eq, -Array.get_eq_getElem] · rw [if_neg (mt (by rintro rfl; simp [FindAux.size_eq]) h')] rw [parentD, dif_neg]; simpa using h' @@ -330,9 +342,11 @@ theorem parentD_findAux_lt {self : UnionFind} {x : Fin self.size} (h : i < self. if h' : (self.arr.get x).parent = x then rw [findAux_s, if_pos h']; apply self.parentD_lt h else - rw [parentD_findAux]; split <;> [simp [rootD_lt]; skip] - have := Nat.sub_lt_sub_left (self.lt_rankMax x) (self.rank'_lt _ ‹_›) - apply parentD_findAux_lt h + 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) : @@ -341,10 +355,12 @@ theorem parentD_findAux_or (self : UnionFind) (x : Fin self.size) (i) : if h' : (self.arr.get x).parent = x then rw [findAux_s, if_pos h']; exact .inr rfl else - rw [parentD_findAux]; split <;> [simp [*]; skip] - have := Nat.sub_lt_sub_left (self.lt_rankMax x) (self.rank'_lt _ ‹_›) - exact (parentD_findAux_or self ⟨_, self.parent'_lt x⟩ i).imp_left <| .imp_right fun h => by - simp only [h, ← parentD_eq, rootD_parent, Array.data_length] + rw [parentD_findAux] + split + · simp [*] + · have := Nat.sub_lt_sub_left (self.lt_rankMax x) (self.rank'_lt _ ‹_›) + exact (parentD_findAux_or self ⟨_, self.parent'_lt x⟩ i).imp_left <| .imp_right fun h => by + simp only [h, ← parentD_eq, rootD_parent, Array.data_length] termination_by self.rankMax - self.rank x theorem lt_rankD_findAux {self : UnionFind} {x : Fin self.size} : @@ -365,7 +381,9 @@ def find (self : UnionFind) (x : Fin self.size) : let r := self.findAux x { 1.arr := r.s 2.1.val := r.root - 1.parentD_lt := fun h => by simp [FindAux.size_eq] at *; exact parentD_findAux_lt h + 1.parentD_lt := fun h => by + simp only [Array.data_length, 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] } @@ -398,7 +416,8 @@ def findD (self : UnionFind) (x : Nat) : UnionFind × Nat := @[simp] theorem find_parent_1 (self : UnionFind) (x : Fin self.size) : (self.find x).1.parent x = self.rootD x := by - simp [find, parent]; rw [parentD_findAux, if_pos rfl] + simp only [parent, Array.data_length, 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 ∨ @@ -449,7 +468,8 @@ theorem setParentBump_rankD_lt {arr : Array UFNode} {x y : Fin arr.size} simp [hP, hR, -Array.get_eq_getElem] at *; split <;> rename_i h₁ <;> [simp [← h₁]; skip] <;> split <;> rename_i h₂ <;> intro h · simp [h₂] at h - · simp [rankD_eq]; split <;> rename_i h₃ + · simp only [rankD_eq, Array.get_eq_getElem] + split <;> rename_i h₃ · rw [← h₃]; apply Nat.lt_succ_self · exact Nat.lt_of_le_of_ne H h₃ · cases h₂.1 @@ -469,13 +489,16 @@ theorem setParent_rankD_lt {arr : Array UFNode} {x y : Fin arr.size} (by simp [rankD_set, Nat.ne_of_lt h, rankD_eq, -Array.get_eq_getElem]) @[simp] theorem linkAux_size : (linkAux self x y).size = self.size := by - simp [linkAux]; split <;> [rfl; split] <;> [skip; split] <;> simp + simp only [linkAux, Array.get_eq_getElem] + 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 at *; simp [linkAux]; split <;> [skip; split <;> [skip; split]] + simp only [Array.data_length, linkAux_size] at * + simp only [linkAux, Array.get_eq_getElem] + 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 @@ -484,12 +507,21 @@ def link (self : UnionFind) (x y : Fin self.size) (yroot : self.parent y = y) : · rw [parentD_set]; split <;> [exact y.2; exact self.parentD_lt h] rankD_lt := by rw [parent, parentD_eq] at yroot - simp [linkAux]; split <;> [skip; split <;> [skip; split]] + simp only [linkAux, Array.get_eq_getElem, 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 [parentD_set]; rintro rfl; simp [*, parentD_eq]) fun {i} => ?_ - simp [rankD_set]; split <;> simp [*]; rintro rfl; simp [rankD_eq, *] + · 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, Fin.eta, Array.get_eq_getElem] + split + · simp_all + · simp_all only [Array.get_eq_getElem, Array.data_length, 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] diff --git a/Batteries/Lean/AttributeExtra.lean b/Batteries/Lean/AttributeExtra.lean index 7b8c92af3f..aeac0267c5 100644 --- a/Batteries/Lean/AttributeExtra.lean +++ b/Batteries/Lean/AttributeExtra.lean @@ -81,7 +81,7 @@ Registers a new parametric attribute. The `extra` field is a list of definitions which will be "pre-tagged" and are not subject to the usual restriction on tagging in the same file as the declaration. -/ -def registerParametricAttributeExtra [Inhabited α] (impl : ParametricAttributeImpl α) +def registerParametricAttributeExtra (impl : ParametricAttributeImpl α) (extra : List (Name × α)) : IO (ParametricAttributeExtra α) := do let attr ← registerParametricAttribute impl pure { attr, base := extra.foldl (fun s (a, b) => s.insert a b) {} } diff --git a/Batteries/Lean/Delaborator.lean b/Batteries/Lean/Delaborator.lean index d722eef9d8..e09f2198de 100644 --- a/Batteries/Lean/Delaborator.lean +++ b/Batteries/Lean/Delaborator.lean @@ -8,6 +8,6 @@ import Lean.PrettyPrinter open Lean PrettyPrinter Delaborator SubExpr /-- Abbreviation for `Lean.MessageData.ofConst`. -/ -@[deprecated Lean.MessageData.ofConst] +@[deprecated Lean.MessageData.ofConst (since := "2024-05-18")] def Lean.ppConst (e : Expr) : MessageData := Lean.MessageData.ofConst e diff --git a/Batteries/Lean/Name.lean b/Batteries/Lean/Name.lean deleted file mode 100644 index b5530e49d1..0000000000 --- a/Batteries/Lean/Name.lean +++ /dev/null @@ -1,28 +0,0 @@ -/- -Copyright (c) 2023 Mario Carneiro. All rights reserved. -Released under Apache 2.0 license as described in the file LICENSE. -Authors: Mario Carneiro --/ -import Lean.Data.Name - -namespace Lean.Name - -/-- -Returns true if this a part of name that is internal or dynamically -generated so that it may easily be changed. - -Generally, user code should not explicitly use internal names. --/ -def isInternalDetail : Name → Bool - | .str p s => - s.startsWith "_" - || matchPrefix s "eq_" - || matchPrefix s "match_" - || matchPrefix s "proof_" - || p.isInternalOrNum - | .num _ _ => true - | p => p.isInternalOrNum -where - /-- Check that a string begins with the given prefix, and then is only digit characters. -/ - matchPrefix (s : String) (pre : String) := - s.startsWith pre && (s |>.drop pre.length |>.all Char.isDigit) diff --git a/Batteries/Lean/PersistentHashMap.lean b/Batteries/Lean/PersistentHashMap.lean index 5054e15758..b297f2fa52 100644 --- a/Batteries/Lean/PersistentHashMap.lean +++ b/Batteries/Lean/PersistentHashMap.lean @@ -10,15 +10,6 @@ namespace Lean.PersistentHashMap variable [BEq α] [Hashable α] -/-- -Similar to `insert`, but also returns a Boolean flag indicating whether an -existing entry has been replaced with `a => b`. --/ -def insert' (m : PersistentHashMap α β) (a : α) (b : β) : PersistentHashMap α β × Bool := - let oldSize := m.size - let m := m.insert a b - (m, m.size == oldSize) - /-- Builds a `PersistentHashMap` from a list of key-value pairs. Values of duplicated keys are replaced by their respective last occurrences. diff --git a/Batteries/Lean/PersistentHashSet.lean b/Batteries/Lean/PersistentHashSet.lean index 51e33e8487..0a8231d723 100644 --- a/Batteries/Lean/PersistentHashSet.lean +++ b/Batteries/Lean/PersistentHashSet.lean @@ -56,16 +56,6 @@ def all (s : PersistentHashSet α) (f : α → Bool) : Bool := instance : BEq (PersistentHashSet α) where beq s t := s.all (t.contains ·) && t.all (s.contains ·) -/-- -Similar to `insert`, but also returns a Boolean flag indicating whether an -existing entry has been replaced with `a => b`. --/ -@[inline] -def insert' (s : PersistentHashSet α) (a : α) : PersistentHashSet α × Bool := - let oldSize := s.size - let s := s.insert a - (s, s.size == oldSize) - /-- Insert all elements from a collection into a `PersistentHashSet`. -/ diff --git a/Batteries/Lean/SMap.lean b/Batteries/Lean/SMap.lean deleted file mode 100644 index 44a660e2e0..0000000000 --- a/Batteries/Lean/SMap.lean +++ /dev/null @@ -1,17 +0,0 @@ -/- -Copyright (c) 2023 Scott Morrison. All rights reserved. -Released under Apache 2.0 license as described in the file LICENSE. -Authors: Scott Morrison --/ -import Lean.Data.SMap - -/-! -# Extra functions on Lean.SMap --/ - -set_option autoImplicit true - -/-- Monadic fold over a staged map. -/ -def Lean.SMap.foldM {m : Type w → Type w} [Monad m] [BEq α] [Hashable α] - (f : σ → α → β → m σ) (init : σ) (map : SMap α β) : m σ := do - map.map₂.foldlM f (← map.map₁.foldM f init) diff --git a/Batteries/Lean/Util/EnvSearch.lean b/Batteries/Lean/Util/EnvSearch.lean index 9143c89511..d9419b8cbf 100644 --- a/Batteries/Lean/Util/EnvSearch.lean +++ b/Batteries/Lean/Util/EnvSearch.lean @@ -24,8 +24,7 @@ where /-- Check constant should be returned -/ @[nolint unusedArguments] check matches_ (_name : Name) cinfo := do - let include ← p cinfo - if include then + if ← p cinfo then pure $ matches_.push cinfo else pure matches_ diff --git a/Batteries/Lean/Util/Path.lean b/Batteries/Lean/Util/Path.lean deleted file mode 100644 index d9488c0dc8..0000000000 --- a/Batteries/Lean/Util/Path.lean +++ /dev/null @@ -1,34 +0,0 @@ -/- -Copyright (c) 2022 Gabriel Ebner. All rights reserved. -Released under Apache 2.0 license as described in the file LICENSE. -Authors: Gabriel Ebner --/ -import Lean.Elab.Term - -/-! -# `compile_time_search_path%` term elaborator. - -Use this as `searchPathRef.set compile_time_search_path%`. --/ - -open Lean System - --- Ideally this instance would be constructed simply by `deriving instance ToExpr for FilePath` --- but for now we have decided not to upstream the `ToExpr` derive handler from `Mathlib`. --- https://leanprover.zulipchat.com/#narrow/stream/348111-std4/topic/ToExpr.20derive.20handler/near/386476438 -instance : ToExpr FilePath where - toTypeExpr := mkConst ``FilePath - toExpr path := mkApp (mkConst ``FilePath.mk) (toExpr path.1) - -/-- -Term elaborator that retrieves the current `SearchPath`. - -Typical usage is `searchPathRef.set compile_time_search_path%`. - -This must not be used in files that are potentially compiled on another machine and then -imported. -(That is, if used in an imported file it will embed the search path from whichever machine -compiled the `.olean`.) --/ -elab "compile_time_search_path%" : term => - return toExpr (← searchPathRef.get) diff --git a/Batteries/Linter/UnnecessarySeqFocus.lean b/Batteries/Linter/UnnecessarySeqFocus.lean index 3ebe54dcb4..566da1d490 100644 --- a/Batteries/Linter/UnnecessarySeqFocus.lean +++ b/Batteries/Linter/UnnecessarySeqFocus.lean @@ -7,7 +7,7 @@ import Lean.Elab.Command import Lean.Linter.Util import Batteries.Lean.AttributeExtra -namespace Std.Linter +namespace Batteries.Linter open Lean Elab Command Linter /-- @@ -147,7 +147,7 @@ partial def markUsedTactics : InfoTree → M ω Unit end -/-- The main entry point to the unused tactic linter. -/ +@[inherit_doc Batteries.Linter.linter.unnecessarySeqFocus] def unnecessarySeqFocusLinter : Linter where run := withSetOptionIn fun stx => do unless getLinterUnnecessarySeqFocus (← getOptions) && (← getInfoState).enabled do return diff --git a/Batteries/Linter/UnreachableTactic.lean b/Batteries/Linter/UnreachableTactic.lean index c4ea4dd10c..a4bedbe10c 100644 --- a/Batteries/Linter/UnreachableTactic.lean +++ b/Batteries/Linter/UnreachableTactic.lean @@ -7,7 +7,7 @@ import Lean.Elab.Command import Lean.Linter.Util import Batteries.Tactic.Unreachable -namespace Std.Linter +namespace Batteries.Linter open Lean Elab Command Linter /-- @@ -86,7 +86,7 @@ partial def eraseUsedTactics : InfoTree → M Unit end -/-- The main entry point to the unreachable tactic linter. -/ +@[inherit_doc Batteries.Linter.linter.unreachableTactic] def unreachableTacticLinter : Linter where run := withSetOptionIn fun stx => do unless getLinterUnreachableTactic (← getOptions) && (← getInfoState).enabled do return diff --git a/Batteries/Logic.lean b/Batteries/Logic.lean index 10b5bd2fcb..5c6efe108a 100644 --- a/Batteries/Logic.lean +++ b/Batteries/Logic.lean @@ -10,16 +10,12 @@ import Batteries.Tactic.Lint.Misc instance {f : α → β} [DecidablePred p] : DecidablePred (p ∘ f) := inferInstanceAs <| DecidablePred fun x => p (f x) -@[deprecated] alias proofIrrel := proof_irrel +@[deprecated (since := "2024-03-15")] alias proofIrrel := proof_irrel /-! ## id -/ theorem Function.id_def : @id α = fun x => x := rfl -/-! ## exists and forall -/ - -alias ⟨forall_not_of_not_exists, not_exists_of_forall_not⟩ := not_exists - /-! ## decidable -/ protected alias ⟨Decidable.exists_not_of_not_forall, _⟩ := Decidable.not_forall @@ -60,8 +56,7 @@ theorem funext₃ {β : α → Sort _} {γ : ∀ a, β a → Sort _} {δ : ∀ a {f g : ∀ a b c, δ a b c} (h : ∀ a b c, f a b c = g a b c) : f = g := funext fun _ => funext₂ <| h _ -theorem Function.funext_iff {β : α → Sort u} {f₁ f₂ : ∀ x : α, β x} : f₁ = f₂ ↔ ∀ a, f₁ a = f₂ a := - ⟨congrFun, funext⟩ +protected alias Function.funext_iff := funext_iff theorem ne_of_apply_ne {α β : Sort _} (f : α → β) {x y : α} : f x ≠ f y → x ≠ y := mt <| congrArg _ @@ -128,9 +123,7 @@ end Mem -- instance (priority := 10) {α} [Subsingleton α] : DecidableEq α -- | a, b => isTrue (Subsingleton.elim a b) --- @[simp] -- TODO(Mario): profile -theorem eq_iff_true_of_subsingleton [Subsingleton α] (x y : α) : x = y ↔ True := - iff_true_intro (Subsingleton.elim ..) +-- TODO(Mario): profile adding `@[simp]` to `eq_iff_true_of_subsingleton` /-- If all points are equal to a given point `x`, then `α` is a subsingleton. -/ theorem subsingleton_of_forall_eq (x : α) (h : ∀ y, y = x) : Subsingleton α := diff --git a/Batteries/StdDeprecations.lean b/Batteries/StdDeprecations.lean index 49357a0573..f82b1739a7 100644 --- a/Batteries/StdDeprecations.lean +++ b/Batteries/StdDeprecations.lean @@ -21,35 +21,35 @@ but it would be much harder to generate the deprecations. Let's hope that people using the tactic implementations can work this out themselves. -/ -@[deprecated] alias Std.AssocList := Batteries.AssocList -@[deprecated] alias Std.HashMap := Batteries.HashMap -@[deprecated] alias Std.mkHashMap := Batteries.mkHashMap -@[deprecated] alias Std.DList := Batteries.DList -@[deprecated] alias Std.PairingHeapImp.Heap := Batteries.PairingHeapImp.Heap -@[deprecated] alias Std.TotalBLE := Batteries.TotalBLE -@[deprecated] alias Std.OrientedCmp := Batteries.OrientedCmp -@[deprecated] alias Std.TransCmp := Batteries.TransCmp -@[deprecated] alias Std.BEqCmp := Batteries.BEqCmp -@[deprecated] alias Std.LTCmp := Batteries.LTCmp -@[deprecated] alias Std.LECmp := Batteries.LECmp -@[deprecated] alias Std.LawfulCmp := Batteries.LawfulCmp -@[deprecated] alias Std.OrientedOrd := Batteries.OrientedOrd -@[deprecated] alias Std.TransOrd := Batteries.TransOrd -@[deprecated] alias Std.BEqOrd := Batteries.BEqOrd -@[deprecated] alias Std.LTOrd := Batteries.LTOrd -@[deprecated] alias Std.LEOrd := Batteries.LEOrd -@[deprecated] alias Std.LawfulOrd := Batteries.LawfulOrd -@[deprecated] alias Std.compareOfLessAndEq_eq_lt := Batteries.compareOfLessAndEq_eq_lt -@[deprecated] alias Std.RBColor := Batteries.RBColor -@[deprecated] alias Std.RBNode := Batteries.RBNode -@[deprecated] alias Std.RBSet := Batteries.RBSet -@[deprecated] alias Std.mkRBSet := Batteries.mkRBSet -@[deprecated] alias Std.RBMap := Batteries.RBMap -@[deprecated] alias Std.mkRBMap := Batteries.mkRBMap -@[deprecated] alias Std.BinomialHeap := Batteries.BinomialHeap -@[deprecated] alias Std.mkBinomialHeap := Batteries.mkBinomialHeap -@[deprecated] alias Std.UFNode := Batteries.UFNode -@[deprecated] alias Std.UnionFind := Batteries.UnionFind +@[deprecated (since := "2024-05-07")] alias Std.AssocList := Batteries.AssocList +@[deprecated (since := "2024-05-07")] alias Std.mkHashMap := Batteries.mkHashMap +@[deprecated (since := "2024-05-07")] alias Std.DList := Batteries.DList +@[deprecated (since := "2024-05-07")] alias Std.PairingHeapImp.Heap := Batteries.PairingHeapImp.Heap +@[deprecated (since := "2024-05-07")] alias Std.TotalBLE := Batteries.TotalBLE +@[deprecated (since := "2024-05-07")] alias Std.OrientedCmp := Batteries.OrientedCmp +@[deprecated (since := "2024-05-07")] alias Std.TransCmp := Batteries.TransCmp +@[deprecated (since := "2024-05-07")] alias Std.BEqCmp := Batteries.BEqCmp +@[deprecated (since := "2024-05-07")] alias Std.LTCmp := Batteries.LTCmp +@[deprecated (since := "2024-05-07")] alias Std.LECmp := Batteries.LECmp +@[deprecated (since := "2024-05-07")] alias Std.LawfulCmp := Batteries.LawfulCmp +@[deprecated (since := "2024-05-07")] alias Std.OrientedOrd := Batteries.OrientedOrd +@[deprecated (since := "2024-05-07")] alias Std.TransOrd := Batteries.TransOrd +@[deprecated (since := "2024-05-07")] alias Std.BEqOrd := Batteries.BEqOrd +@[deprecated (since := "2024-05-07")] alias Std.LTOrd := Batteries.LTOrd +@[deprecated (since := "2024-05-07")] alias Std.LEOrd := Batteries.LEOrd +@[deprecated (since := "2024-05-07")] alias Std.LawfulOrd := Batteries.LawfulOrd +@[deprecated (since := "2024-05-07")] +alias Std.compareOfLessAndEq_eq_lt := Batteries.compareOfLessAndEq_eq_lt +@[deprecated (since := "2024-05-07")] alias Std.RBColor := Batteries.RBColor +@[deprecated (since := "2024-05-07")] alias Std.RBNode := Batteries.RBNode +@[deprecated (since := "2024-05-07")] alias Std.RBSet := Batteries.RBSet +@[deprecated (since := "2024-05-07")] alias Std.mkRBSet := Batteries.mkRBSet +@[deprecated (since := "2024-05-07")] alias Std.RBMap := Batteries.RBMap +@[deprecated (since := "2024-05-07")] alias Std.mkRBMap := Batteries.mkRBMap +@[deprecated (since := "2024-05-07")] alias Std.BinomialHeap := Batteries.BinomialHeap +@[deprecated (since := "2024-05-07")] alias Std.mkBinomialHeap := Batteries.mkBinomialHeap +@[deprecated (since := "2024-05-07")] alias Std.UFNode := Batteries.UFNode +@[deprecated (since := "2024-05-07")] alias Std.UnionFind := Batteries.UnionFind -- Check that these generate usable deprecated hints -- when referring to names inside these namespaces. diff --git a/Batteries/Tactic/Alias.lean b/Batteries/Tactic/Alias.lean index b7eaeaf713..07b91dc76e 100644 --- a/Batteries/Tactic/Alias.lean +++ b/Batteries/Tactic/Alias.lean @@ -6,6 +6,7 @@ Authors: Mario Carneiro, David Renshaw, François G. Dorais import Lean.Elab.Command import Lean.Elab.DeclarationRange import Lean.Compiler.NoncomputableAttr +import Lean.DocString import Batteries.CodeAction.Deprecated /-! diff --git a/Batteries/Tactic/Lint/Basic.lean b/Batteries/Tactic/Lint/Basic.lean index 87cc925a06..948bab5456 100644 --- a/Batteries/Tactic/Lint/Basic.lean +++ b/Batteries/Tactic/Lint/Basic.lean @@ -42,6 +42,8 @@ def isAutoDecl (decl : Name) : CoreM Bool := do if env.isConstructor n && ["injEq", "inj", "sizeOf_spec"].any (· == s) then return true if let ConstantInfo.inductInfo _ := (← getEnv).find? n then + if s.startsWith "brecOn_" || s.startsWith "below_" || s.startsWith "binductionOn_" + || s.startsWith "ibelow_" then return true if [casesOnSuffix, recOnSuffix, brecOnSuffix, binductionOnSuffix, belowSuffix, "ibelow", "ndrec", "ndrecOn", "noConfusionType", "noConfusion", "ofNat", "toCtorIdx" ].any (· == s) then diff --git a/Batteries/Tactic/Lint/Frontend.lean b/Batteries/Tactic/Lint/Frontend.lean index 4eff8b1450..841c696af8 100644 --- a/Batteries/Tactic/Lint/Frontend.lean +++ b/Batteries/Tactic/Lint/Frontend.lean @@ -65,20 +65,28 @@ inductive LintVerbosity | high deriving Inhabited, DecidableEq, Repr -/-- `getChecks slow extra use_only` produces a list of linters. -`extras` is a list of names that should resolve to declarations with type `linter`. -If `useOnly` is true, it only uses the linters in `extra`. -Otherwise, it uses all linters in the environment tagged with `@[env_linter]`. +/-- `getChecks slow runOnly runAlways` produces a list of linters. +`runOnly` is an optional list of names that should resolve to declarations with type `NamedLinter`. +If populated, only these linters are run (regardless of the default configuration). +`runAlways` is an optional list of names that should resolve to declarations with type +`NamedLinter`. If populated, these linters are always run (regardless of their configuration). +Specifying a linter in `runAlways` but not `runOnly` is an error. +Otherwise, it uses all enabled linters in the environment tagged with `@[env_linter]`. If `slow` is false, it only uses the fast default tests. -/ -def getChecks (slow : Bool) (useOnly : Bool) : CoreM (Array NamedLinter) := do +def getChecks (slow : Bool) (runOnly : Option (List Name)) (runAlways : Option (List Name)) : + CoreM (Array NamedLinter) := do let mut result := #[] - unless useOnly do - for (name, declName, dflt) in batteriesLinterExt.getState (← getEnv) do - if dflt then - let linter ← getLinter name declName - if slow || linter.isFast then - let _ := Inhabited.mk linter - result := result.binInsert (·.name.lt ·.name) linter + for (name, declName, default) in batteriesLinterExt.getState (← getEnv) do + let shouldRun := match (runOnly, runAlways) with + | (some only, some always) => only.contains name && (always.contains name || default) + | (some only, none) => only.contains name + | (none, some always) => default || always.contains name + | _ => default + if shouldRun then + let linter ← getLinter name declName + if slow || linter.isFast then + let _ := Inhabited.mk linter + result := result.binInsert (·.name.lt ·.name) linter pure result -- Note: we have to use the same context as `runTermElabM` here so that the `simpNF` @@ -125,9 +133,11 @@ def printWarning (declName : Name) (warning : MessageData) (useErrorFormat : Boo (filePath : System.FilePath := default) : CoreM MessageData := do if useErrorFormat then if let some range ← findDeclarationRanges? declName then - return m!"{filePath}:{range.range.pos.line}:{range.range.pos.column + 1}: error: { + let msg ← addMessageContextPartial + m!"{filePath}:{range.range.pos.line}:{range.range.pos.column + 1}: error: { ← mkConstWithLevelParams declName} {warning}" - pure m!"#check {← mkConstWithLevelParams declName} /- {warning} -/" + return msg + addMessageContextPartial m!"#check {← mkConstWithLevelParams declName} /- {warning} -/" /-- Formats a map of linter warnings using `print_warning`, sorted by line number. -/ def printWarnings (results : HashMap Name MessageData) (filePath : System.FilePath := default) @@ -236,9 +246,11 @@ elab tk:"#lint" verbosity:("+" <|> "-")? fast:"*"? only:(&" only")? | some ⟨.node _ `token.«-» _⟩ => pure .low | _ => throwUnsupportedSyntax let fast := fast.isSome - let only := only.isSome + let onlyNames : Option (List Name) := match only.isSome with + | true => some (linters.map fun l => l.getId).toList + | false => none let linters ← liftCoreM do - let mut result ← getChecks (slow := !fast) only + let mut result ← getChecks (slow := !fast) (runOnly := onlyNames) none let linterState := batteriesLinterExt.getState (← getEnv) for id in linters do let name := id.getId.eraseMacroScopes diff --git a/Batteries/Tactic/Lint/Misc.lean b/Batteries/Tactic/Lint/Misc.lean index 4bb3f2125b..3f0e69f648 100644 --- a/Batteries/Tactic/Lint/Misc.lean +++ b/Batteries/Tactic/Lint/Misc.lean @@ -239,9 +239,7 @@ def findUnusedHaves (e : Expr) : MetaM (Array MessageData) := do | _ => return res.get -/-- A linter for checking that declarations don't have unused term mode have statements. We do not -tag this as `@[env_linter]` so that it is not in the default linter set as it is slow and an -uncommon problem. -/ +/-- A linter for checking that declarations don't have unused term mode have statements. -/ @[env_linter] def unusedHavesSuffices : Linter where noErrorsFound := "No declarations have unused term mode have statements." errorsFound := "THE FOLLOWING DECLARATIONS HAVE INEFFECTUAL TERM MODE HAVE/SUFFICES BLOCKS. \ diff --git a/Batteries/Tactic/Lint/Simp.lean b/Batteries/Tactic/Lint/Simp.lean index 44a858b340..9196e4ab74 100644 --- a/Batteries/Tactic/Lint/Simp.lean +++ b/Batteries/Tactic/Lint/Simp.lean @@ -93,14 +93,14 @@ def decorateError (msg : MessageData) (k : MetaM α) : MetaM α := do try k catch e => throw (.error e.getRef m!"{msg}\n{e.toMessageData}") /-- Render the list of simp lemmas. -/ -def formatLemmas (usedSimps : Simp.UsedSimps) : MetaM MessageData := do +def formatLemmas (usedSimps : Simp.UsedSimps) (simpName : String) : MetaM MessageData := do let mut args := #[] let env ← getEnv - for (thm, _) in usedSimps.toArray.qsort (·.2 < ·.2) do + for (thm, _) in usedSimps.map.toArray.qsort (·.2 < ·.2) do if let .decl declName := thm then if env.contains declName && declName != ``eq_self then args := args.push (← mkConstWithFreshMVarLevels declName) - return m!"simp only {args.toList}" + return m!"{simpName} only {args.toList}" /-- A linter for simp lemmas whose lhs is not in simp-normal form, and which hence never fire. -/ @[env_linter] def simpNF : Linter where @@ -112,17 +112,29 @@ https://leanprover-community.github.io/mathlib_docs/notes.html#simp-normal%20for unless ← isSimpTheorem declName do return none let ctx := { ← Simp.Context.mkDefault with config.decide := false } checkAllSimpTheoremInfos (← getConstInfo declName).type fun {lhs, rhs, isConditional, ..} => do + let isRfl ← isRflTheorem declName let ({ expr := lhs', proof? := prf1, .. }, prf1Stats) ← - decorateError "simplify fails on left-hand side:" <| simp lhs ctx - if prf1Stats.usedTheorems.contains (.decl declName) then return none + decorateError "simplify fails on left-hand side:" <| + if !isRfl then + simp lhs ctx + else do + let (e, s) ← dsimp lhs ctx + return (Simp.Result.mk e .none .true, s) + if prf1Stats.usedTheorems.map.contains (.decl declName) then return none let ({ expr := rhs', .. }, stats) ← - decorateError "simplify fails on right-hand side:" <| simp rhs ctx (stats := prf1Stats) + decorateError "simplify fails on right-hand side:" <| + if !isRfl then + simp rhs ctx (stats := prf1Stats) + else do + let (e, s) ← dsimp rhs ctx (stats := prf1Stats) + return (Simp.Result.mk e .none .true, s) let lhs'EqRhs' ← isSimpEq lhs' rhs' (whnfFirst := false) let lhsInNF ← isSimpEq lhs' lhs + let simpName := if !isRfl then "simp" else "dsimp" if lhs'EqRhs' then if prf1.isNone then return none -- TODO: FP rewriting foo.eq_2 using `simp only [foo]` - return m!"simp can prove this: - by {← formatLemmas stats.usedTheorems} + return m!"{simpName} can prove this: + by {← formatLemmas stats.usedTheorems simpName} One of the lemmas above could be a duplicate. If that's not the case try reordering lemmas or adding @[priority]. " @@ -132,7 +144,7 @@ If that's not the case try reordering lemmas or adding @[priority]. to {lhs'} using - {← formatLemmas prf1Stats.usedTheorems} + {← formatLemmas prf1Stats.usedTheorems simpName} Try to change the left-hand side to the simplified term! " else if !isConditional && lhs == lhs' then diff --git a/Batteries/Tactic/NoMatch.lean b/Batteries/Tactic/NoMatch.lean index 9dc517b33f..7efe68e7d2 100644 --- a/Batteries/Tactic/NoMatch.lean +++ b/Batteries/Tactic/NoMatch.lean @@ -4,6 +4,7 @@ Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Lean.Elab.ElabRules +import Lean.DocString /-! Deprecation warnings for `match ⋯ with.`, `fun.`, `λ.`, and `intro.`. diff --git a/Batteries/Tactic/PrintPrefix.lean b/Batteries/Tactic/PrintPrefix.lean index 0046f0a4d7..63d2c3bbf5 100644 --- a/Batteries/Tactic/PrintPrefix.lean +++ b/Batteries/Tactic/PrintPrefix.lean @@ -3,7 +3,6 @@ Copyright (c) 2021 Shing Tak Lam. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Shing Tak Lam, Daniel Selsam, Mario Carneiro -/ -import Batteries.Lean.Name import Batteries.Lean.Util.EnvSearch import Batteries.Lean.Delaborator import Lean.Elab.Tactic.Config diff --git a/Batteries/Tactic/SqueezeScope.lean b/Batteries/Tactic/SqueezeScope.lean index 78a1d2a540..df289dc982 100644 --- a/Batteries/Tactic/SqueezeScope.lean +++ b/Batteries/Tactic/SqueezeScope.lean @@ -85,7 +85,8 @@ elab_rules : tactic throw e if let some new := new then for (_, stx, usedSimps) in new do - let usedSimps := usedSimps.foldl (fun s usedSimps => usedSimps.foldl .insert s) {} + let usedSimps := usedSimps.reverse.foldl + (fun s usedSimps => usedSimps.toArray.foldl .insert s) {} let stx' ← mkSimpCallStx stx usedSimps TryThis.addSuggestion stx[0] stx' (origSpan? := stx) diff --git a/Batteries/Util/CheckTactic.lean b/Batteries/Util/CheckTactic.lean deleted file mode 100644 index bc97e681cc..0000000000 --- a/Batteries/Util/CheckTactic.lean +++ /dev/null @@ -1,124 +0,0 @@ -/- -Copyright (c) 2024 Lean FRO. All rights reserved. -Released under Apache 2.0 license as described in the file LICENSE. -Authors: Joe Hendrix --/ -import Lean.Elab.Tactic.ElabTerm -import Lean.Elab.Term - -/- -This file is the home for commands to tactics behave as expected. - -It currently includes two tactics: - -#check_tactic t ~> res - - -only a #check_simp command that applies simp -IT --/ - -namespace Batteries.Tactic - -open Lean Elab Tactic -open Meta - -/-- -Type used to lift an arbitrary value into a type parameter so it can -appear in a proof goal. - -It is used by the #check_tactic command. --/ -private inductive CheckGoalType {α : Sort u} : (val : α) → Prop where -| intro : (val : α) → CheckGoalType val - -private def matchCheckGoalType (stx : Syntax) (goalType : Expr) : MetaM (Expr × Expr × Level) := do - let u ← mkFreshLevelMVar - let type ← mkFreshExprMVar (some (.sort u)) - let val ← mkFreshExprMVar (some type) - let extType := mkAppN (.const ``CheckGoalType [u]) #[type, val] - if !(← isDefEq goalType extType) then - throwErrorAt stx "Goal{indentExpr goalType}\nis expected to match {indentExpr extType}" - pure (val, type, u) - -/-- -`check_tactic_goal t` verifies that the goal has is equal to -`CheckGoalType t` with reducible transparency. It closes the goal if so -and otherwise reports an error. - -It is used by #check_tactic. --/ -local syntax (name := check_tactic_goal) "check_tactic_goal " term : tactic - -/-- -Implementation of `check_tactic_goal` --/ -@[tactic check_tactic_goal] private def evalCheckTacticGoal : Tactic := fun stx => - match stx with - | `(tactic| check_tactic_goal $exp) => - closeMainGoalUsing (checkUnassigned := false) fun goalType => do - let (val, type, u) ← matchCheckGoalType stx goalType - let expTerm ← elabTermEnsuringType exp type - if !(← Meta.withReducible <| isDefEq val expTerm) then - throwErrorAt stx - m!"Term reduces to{indentExpr val}\nbut is expected to reduce to {indentExpr expTerm}" - return mkAppN (.const ``CheckGoalType.intro [u]) #[type, val] - | _ => throwErrorAt stx "check_goal syntax error" - -/-- -`check_tactic_goal t` verifies that the goal has is equal to -`CheckGoalType t` with reducible transparency. It closes the goal if so -and otherwise reports an error. - -It is used by #check_tactic. --/ -local syntax (name := check_tactic_fails) "check_tactic_fails " tactic : tactic - -@[tactic check_tactic_fails] private def evalCheckTacticFails : Tactic := fun stx => do - let `(tactic| check_tactic_fails $tactic) := stx - | throwUnsupportedSyntax - closeMainGoalUsing (checkUnassigned := false) fun goalType => do - let (val, type, u) ← matchCheckGoalType stx goalType - Term.withoutErrToSorry <| withoutRecover do - match (← try (some <$> evalTactic tactic) catch _ => pure none) with - | none => - return mkAppN (.const ``CheckGoalType.intro [u]) #[type, val] - | some () => - let gls ← getGoals - let ppGoal (g : MVarId) := do - let (val, _type, _u) ← matchCheckGoalType stx (← g.getType) - pure m!"{indentExpr val}" - let msg ← - match gls with - | [] => pure m!"{tactic} expected to fail on {val}, but closed goal." - | [g] => - pure <| m!"{tactic} expected to fail on {val}, but returned: {←ppGoal g}" - | gls => - let app m g := do pure <| m ++ (←ppGoal g) - let init := m!"{tactic} expected to fail on {val}, but returned goals:" - gls.foldlM (init := init) app - throwErrorAt stx msg - -/-- -`#check_tactic t ~> r by commands` runs the tactic sequence `commands` -on a goal with t in the type and sees if the resulting expression has -reduced it to `r`. --/ -macro "#check_tactic " t:term "~>" result:term "by" tac:tactic : command => - `(command|example : CheckGoalType $t := by $tac; check_tactic_goal $result) - -/-- -`#check_simp t ~> r` checks `simp` reduces `t` to `r`. --/ -macro "#check_simp " t:term "~>" exp:term : command => - `(command|#check_tactic $t ~> $exp by simp) - -example (x : Nat) : CheckGoalType ((x + z) = x) := by - fail_if_success simp [] - exact (CheckGoalType.intro ((x + z) = x)) - -/-- -`#check_simp t !~>` checks `simp` fails to reduce `t`. --/ -macro "#check_simp " t:term "!~>" : command => - `(command|example : CheckGoalType $t := by check_tactic_fails simp) diff --git a/lake-manifest.json b/lake-manifest.json index e33f34b1fa..68d5a83837 100644 --- a/lake-manifest.json +++ b/lake-manifest.json @@ -1,50 +1,5 @@ -{"version": 7, +{"version": "1.0.0", "packagesDir": ".lake/packages", - "packages": - [{"url": "https://github.com/xubaiw/CMark.lean", - "type": "git", - "subDir": null, - "rev": "0077cbbaa92abf855fc1c0413e158ffd8195ec77", - "name": "CMark", - "manifestFile": "lake-manifest.json", - "inputRev": "main", - "inherited": true, - "configFile": "lakefile.lean"}, - {"url": "https://github.com/fgdorais/lean4-unicode-basic", - "type": "git", - "subDir": null, - "rev": "280d75fdfe7be8eb337be7f1bf8479b4aac09f71", - "name": "UnicodeBasic", - "manifestFile": "lake-manifest.json", - "inputRev": "main", - "inherited": true, - "configFile": "lakefile.lean"}, - {"url": "https://github.com/mhuisi/lean4-cli", - "type": "git", - "subDir": null, - "rev": "39229f3630d734af7d9cfb5937ddc6b41d3aa6aa", - "name": "Cli", - "manifestFile": "lake-manifest.json", - "inputRev": "nightly", - "inherited": true, - "configFile": "lakefile.lean"}, - {"url": "https://github.com/hargonix/LeanInk", - "type": "git", - "subDir": null, - "rev": "2447df5cc6e48eb965c3c3fba87e46d353b5e9f1", - "name": "leanInk", - "manifestFile": "lake-manifest.json", - "inputRev": "doc-gen", - "inherited": true, - "configFile": "lakefile.lean"}, - {"url": "https://github.com/leanprover/doc-gen4", - "type": "git", - "subDir": null, - "rev": "b7fad51b87a5f8fb3a238dc820ec40ebfa2a636e", - "name": "«doc-gen4»", - "manifestFile": "lake-manifest.json", - "inputRev": "main", - "inherited": false, - "configFile": "lakefile.lean"}], + "packages": [], "name": "batteries", "lakeDir": ".lake"} diff --git a/lakefile.lean b/lakefile.lean index a59342f68c..e55e8b2639 100644 --- a/lakefile.lean +++ b/lakefile.lean @@ -13,14 +13,11 @@ package batteries where @[default_target] lean_lib Batteries -@[default_target] +@[default_target, lint_driver] lean_exe runLinter where srcDir := "scripts" supportInterpreter := true -meta if get_config? doc |>.isSome then -require «doc-gen4» from git "https://github.com/leanprover/doc-gen4" @ "main" - @[test_driver] lean_exe test where srcDir := "scripts" diff --git a/lean-toolchain b/lean-toolchain index 0ba3faf807..64981ae5f5 100644 --- a/lean-toolchain +++ b/lean-toolchain @@ -1 +1 @@ -leanprover/lean4:v4.9.0-rc1 +leanprover/lean4:v4.11.0-rc1 diff --git a/scripts/runLinter.lean b/scripts/runLinter.lean index 87d8774ce9..4f18be6b50 100644 --- a/scripts/runLinter.lean +++ b/scripts/runLinter.lean @@ -1,6 +1,6 @@ +import Lean.Util.SearchPath import Batteries.Tactic.Lint import Batteries.Data.Array.Basic -import Batteries.Lean.Util.Path open Lean Core Elab Command Std.Tactic.Lint open System (FilePath) @@ -57,7 +57,7 @@ unsafe def main (args : List String) : IO Unit := do let state := { env } Prod.fst <$> (CoreM.toIO · ctx state) do let decls ← getDeclsInPackage module.getRoot - let linters ← getChecks (slow := true) (useOnly := false) + let linters ← getChecks (slow := true) (runAlways := none) (runOnly := none) let results ← lintCore decls linters if update then writeJsonFile (α := NoLints) nolintsFile <| diff --git a/test/absurd.lean b/test/absurd.lean index 4974467e5a..1817c0e715 100644 --- a/test/absurd.lean +++ b/test/absurd.lean @@ -43,5 +43,5 @@ h : p → False ⊢ p -/ #guard_msgs in -example (h : p → False) : 0 = 3 := by +example {p : Prop} (h : p → False) : 0 = 3 := by absurd h diff --git a/test/array.lean b/test/array.lean index 41338a8bd4..2ba3a29577 100644 --- a/test/array.lean +++ b/test/array.lean @@ -1,4 +1,3 @@ -import Batteries.Util.CheckTactic import Batteries.Data.Array section diff --git a/test/congr.lean b/test/congr.lean index 5303fbd74b..065a899f99 100644 --- a/test/congr.lean +++ b/test/congr.lean @@ -19,8 +19,6 @@ example {α β γ δ} {F : ∀ {α β}, (α → β) → γ → δ} {f g : α → -- apply_assumption -- FIXME apply h -attribute [ext] Subtype.eq - example {α β : Type _} {f : _ → β} {x y : { x : { x : α // x = x } // x = x }} (h : x.1 = y.1) : f x = f y := by congr with : 1 @@ -38,7 +36,7 @@ section -- Adaptation note: the next two examples have always failed if `List.ext` was in scope, -- but until nightly-2024-04-24 (when `List.ext` was upstreamed), it wasn't in scope. -- In order to preserve the test behaviour we locally remove the `ext` attribute. -attribute [-ext] List.ext +attribute [-ext] List.ext_getElem? private opaque List.sum : List Nat → Nat diff --git a/test/lint_lean.lean b/test/lint_lean.lean new file mode 100644 index 0000000000..2b2f8b89e1 --- /dev/null +++ b/test/lint_lean.lean @@ -0,0 +1,47 @@ +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 + +/-! Failing lints that need work. -/ + +-- #lint only explicitVarsOfIff in all -- Found 109 errors + +-- Many fixed in https://github.com/leanprover/lean4/pull/4620 +-- and should be checked again. +-- #lint only simpNF in all -- Found 34 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 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 diff --git a/test/lint_simpNF.lean b/test/lint_simpNF.lean index 8587e464bb..e06e067d18 100644 --- a/test/lint_simpNF.lean +++ b/test/lint_simpNF.lean @@ -27,4 +27,18 @@ theorem sumCompl_apply_symm_of_pos (p : α → Prop) [DecidablePred p] (a : α) (sumCompl p).symm a = Sum.inl ⟨a, h⟩ := dif_pos h +def foo (n : Nat) : Nat := if n = n then n else 0 + +@[simp] +theorem foo_eq_id : foo = id := by + funext n + simp [foo] + +-- The following `dsimp`-lemma is (correctly) not flagged by the linter +@[simp] +theorem foo_eq_ite (n : Nat) : foo n = if n = n then n else 0 := by + rfl + +end Equiv + #lint- only simpNF