source
stringlengths
17
118
lean4
stringlengths
0
335k
.lake/packages/mathlib/Mathlib/Data/Int/Notation.lean
import Mathlib.Init /-! # Notation `β„€` for the integers. -/ @[inherit_doc] notation "β„€" => Int
.lake/packages/mathlib/Mathlib/Data/Int/CharZero.lean
import Mathlib.Algebra.Notation.Support import Mathlib.Data.Int.Cast.Field import Mathlib.Data.Int.Cast.Lemmas import Mathlib.Data.Int.Cast.Pi /-! # Injectivity of `Int.Cast` into characteristic zero rings and fields. -/ open Nat Set variable {Ξ± Ξ² : Type*} namespace Int @[simp, norm_cast] theorem cast_div_charZero {k : Type*} [DivisionRing k] [CharZero k] {m n : β„€} (n_dvd : n ∣ m) : ((m / n : β„€) : k) = m / n := by rcases eq_or_ne n 0 with (rfl | hn) Β· simp [Int.ediv_zero] Β· exact cast_div n_dvd (cast_ne_zero.mpr hn) -- Necessary for confluence with `ofNat_ediv` and `cast_div_charZero`. @[simp, norm_cast] theorem cast_div_ofNat_charZero {k : Type*} [DivisionRing k] [CharZero k] {m n : β„•} (n_dvd : n ∣ m) : (((m : β„€) / (n : β„€) : β„€) : k) = m / n := by rw [cast_div_charZero (Int.ofNat_dvd.mpr n_dvd), cast_natCast, cast_natCast] end Int theorem RingHom.injective_int {Ξ± : Type*} [NonAssocRing Ξ±] (f : β„€ β†’+* Ξ±) [CharZero Ξ±] : Function.Injective f := Subsingleton.elim (Int.castRingHom _) f β–Έ Int.cast_injective namespace Function variable [AddGroupWithOne Ξ²] [CharZero Ξ²] {n : β„€} lemma support_intCast (hn : n β‰  0) : support (n : Ξ± β†’ Ξ²) = univ := support_const <| Int.cast_ne_zero.2 hn lemma mulSupport_intCast (hn : n β‰  1) : mulSupport (n : Ξ± β†’ Ξ²) = univ := mulSupport_const <| Int.cast_ne_one.2 hn end Function
.lake/packages/mathlib/Mathlib/Data/Int/Range.lean
import Mathlib.Algebra.Group.Int.Defs import Mathlib.Algebra.Order.Group.Unbundled.Basic /-! # Intervals in β„€ This file defines integer ranges. `range m n` is the set of integers greater than `m` and strictly less than `n`. ## Note This could be unified with `Data.List.Intervals`. See the TODOs there. -/ namespace Int /-- List enumerating `[m, n)`. This is the β„€ variant of `List.Ico`. -/ def range (m n : β„€) : List β„€ := ((List.range (toNat (n - m))) : List β„•).map fun (r : β„•) => (m + r : β„€) theorem mem_range_iff {m n r : β„€} : r ∈ range m n ↔ m ≀ r ∧ r < n := by simp only [range, List.mem_map, List.mem_range, lt_toNat, lt_sub_iff_add_lt, add_comm] exact ⟨fun ⟨a, ha⟩ => ha.2 β–Έ ⟨le_add_of_nonneg_right (Int.natCast_nonneg _), ha.1⟩, fun h => ⟨toNat (r - m), by simp [toNat_of_nonneg (sub_nonneg.2 h.1), h.2] ⟩⟩ instance decidableLELT (P : Int β†’ Prop) [DecidablePred P] (m n : β„€) : Decidable (βˆ€ r, m ≀ r β†’ r < n β†’ P r) := decidable_of_iff (βˆ€ r ∈ range m n, P r) <| by simp only [mem_range_iff, and_imp] instance decidableLELE (P : Int β†’ Prop) [DecidablePred P] (m n : β„€) : Decidable (βˆ€ r, m ≀ r β†’ r ≀ n β†’ P r) := -- Add empty type ascription, otherwise it fails to find `Decidable` instance. decidable_of_iff (βˆ€ r ∈ range m (n + 1), P r :) <| by simp only [mem_range_iff, and_imp, lt_add_one_iff] instance decidableLTLT (P : Int β†’ Prop) [DecidablePred P] (m n : β„€) : Decidable (βˆ€ r, m < r β†’ r < n β†’ P r) := Int.decidableLELT P _ _ instance decidableLTLE (P : Int β†’ Prop) [DecidablePred P] (m n : β„€) : Decidable (βˆ€ r, m < r β†’ r ≀ n β†’ P r) := Int.decidableLELE P _ _ end Int
.lake/packages/mathlib/Mathlib/Data/Int/NatAbs.lean
import Mathlib.Algebra.GroupWithZero.Hom import Mathlib.Algebra.GroupWithZero.Nat import Mathlib.Algebra.Ring.Int.Defs /-! # Lemmas about `Int.natAbs` This file contains some results on `Int.natAbs`, the absolute value of an integer as a natural number. ## Main results * `Int.natAbsHom`: `Int.natAbs` bundled as a `MonoidWithZeroHom`. -/ namespace Int /-- `Int.natAbs` as a bundled `MonoidWithZeroHom`. -/ @[simps] def natAbsHom : β„€ β†’*β‚€ β„• where toFun := Int.natAbs map_mul' := Int.natAbs_mul map_one' := Int.natAbs_one map_zero' := Int.natAbs_zero lemma natAbs_natCast_sub_natCast_of_ge {a b : β„•} (h : b ≀ a) : Int.natAbs (↑a - ↑b) = a - b := by cutsat lemma natAbs_natCast_sub_natCast_of_le {a b : β„•} (h : a ≀ b) : Int.natAbs (↑a - ↑b) = b - a := by cutsat end Int
.lake/packages/mathlib/Mathlib/Data/Int/Log.lean
import Mathlib.Algebra.Field.Defs import Mathlib.Algebra.Order.Floor.Semiring import Mathlib.Data.Nat.Log /-! # Integer logarithms in a field with respect to a natural base This file defines two `β„€`-valued analogs of the logarithm of `r : R` with base `b : β„•`: * `Int.log b r`: Lower logarithm, or floor **log**. Greatest `k` such that `↑b^k ≀ r`. * `Int.clog b r`: Upper logarithm, or **c**eil **log**. Least `k` such that `r ≀ ↑b^k`. Note that `Int.log` gives the position of the left-most non-zero digit: ```lean #eval (Int.log 10 (0.09 : β„š), Int.log 10 (0.10 : β„š), Int.log 10 (0.11 : β„š)) -- (-2, -1, -1) #eval (Int.log 10 (9 : β„š), Int.log 10 (10 : β„š), Int.log 10 (11 : β„š)) -- (0, 1, 1) ``` which means it can be used for computing digit expansions ```lean import Data.Fin.VecNotation import Mathlib.Data.Rat.Floor def digits (b : β„•) (q : β„š) (n : β„•) : β„• := ⌊q * ((b : β„š) ^ (n - Int.log b q))βŒ‹β‚Š % b #eval digits 10 (1/7) ∘ ((↑) : Fin 8 β†’ β„•) -- ![1, 4, 2, 8, 5, 7, 1, 4] ``` ## Main results * For `Int.log`: * `Int.zpow_log_le_self`, `Int.lt_zpow_succ_log_self`: the bounds formed by `Int.log`, `(b : R) ^ log b r ≀ r < (b : R) ^ (log b r + 1)`. * `Int.zpow_log_gi`: the Galois coinsertion between `zpow` and `Int.log`. * For `Int.clog`: * `Int.zpow_pred_clog_lt_self`, `Int.self_le_zpow_clog`: the bounds formed by `Int.clog`, `(b : R) ^ (clog b r - 1) < r ≀ (b : R) ^ clog b r`. * `Int.clog_zpow_gi`: the Galois insertion between `Int.clog` and `zpow`. * `Int.neg_log_inv_eq_clog`, `Int.neg_clog_inv_eq_log`: the link between the two definitions. -/ assert_not_exists Finset variable {R : Type*} [Semifield R] [LinearOrder R] [IsStrictOrderedRing R] [FloorSemiring R] namespace Int /-- The greatest power of `b` such that `b ^ log b r ≀ r`. -/ def log (b : β„•) (r : R) : β„€ := if 1 ≀ r then Nat.log b ⌊rβŒ‹β‚Š else -Nat.clog b ⌈rβ»ΒΉβŒ‰β‚Š omit [IsStrictOrderedRing R] in theorem log_of_one_le_right (b : β„•) {r : R} (hr : 1 ≀ r) : log b r = Nat.log b ⌊rβŒ‹β‚Š := if_pos hr theorem log_of_right_le_one (b : β„•) {r : R} (hr : r ≀ 1) : log b r = -Nat.clog b ⌈rβ»ΒΉβŒ‰β‚Š := by obtain rfl | hr := hr.eq_or_lt Β· rw [log, if_pos hr, inv_one, Nat.ceil_one, Nat.floor_one, Nat.log_one_right, Nat.clog_one_right, Int.ofNat_zero, neg_zero] Β· exact if_neg hr.not_ge @[simp, norm_cast] theorem log_natCast (b : β„•) (n : β„•) : log b (n : R) = Nat.log b n := by cases n Β· simp [log_of_right_le_one] Β· rw [log_of_one_le_right, Nat.floor_natCast] simp @[simp] theorem log_ofNat (b : β„•) (n : β„•) [n.AtLeastTwo] : log b (ofNat(n) : R) = Nat.log b ofNat(n) := log_natCast b n theorem log_of_left_le_one {b : β„•} (hb : b ≀ 1) (r : R) : log b r = 0 := by rcases le_total 1 r with h | h Β· rw [log_of_one_le_right _ h, Nat.log_of_left_le_one hb, Int.ofNat_zero] Β· rw [log_of_right_le_one _ h, Nat.clog_of_left_le_one hb, Int.ofNat_zero, neg_zero] theorem log_of_right_le_zero (b : β„•) {r : R} (hr : r ≀ 0) : log b r = 0 := by rw [log_of_right_le_one _ (hr.trans zero_le_one), Nat.clog_of_right_le_one ((Nat.ceil_eq_zero.mpr <| inv_nonpos.2 hr).trans_le zero_le_one), Int.ofNat_zero, neg_zero] theorem zpow_log_le_self {b : β„•} {r : R} (hb : 1 < b) (hr : 0 < r) : (b : R) ^ log b r ≀ r := by rcases le_total 1 r with hr1 | hr1 Β· rw [log_of_one_le_right _ hr1] rw [zpow_natCast, ← Nat.cast_pow, ← Nat.le_floor_iff hr.le] exact Nat.pow_log_le_self b (Nat.floor_pos.mpr hr1).ne' Β· rw [log_of_right_le_one _ hr1, zpow_neg, zpow_natCast, ← Nat.cast_pow] exact inv_le_of_inv_leβ‚€ hr (Nat.ceil_le.1 <| Nat.le_pow_clog hb _) theorem lt_zpow_succ_log_self {b : β„•} (hb : 1 < b) (r : R) : r < (b : R) ^ (log b r + 1) := by rcases le_or_gt r 0 with hr | hr Β· rw [log_of_right_le_zero _ hr, zero_add, zpow_one] exact hr.trans_lt (zero_lt_one.trans_le <| mod_cast hb.le) rcases le_or_gt 1 r with hr1 | hr1 Β· rw [log_of_one_le_right _ hr1] rw [Int.ofNat_add_one_out, zpow_natCast, ← Nat.cast_pow] apply Nat.lt_of_floor_lt exact Nat.lt_pow_succ_log_self hb _ Β· rw [log_of_right_le_one _ hr1.le] have hcri : 1 < r⁻¹ := (one_lt_invβ‚€ hr).2 hr1 have : 1 ≀ Nat.clog b ⌈rβ»ΒΉβŒ‰β‚Š := Nat.succ_le_of_lt (Nat.clog_pos hb <| Nat.one_lt_cast.1 <| hcri.trans_le (Nat.le_ceil _)) rw [neg_add_eq_sub, ← neg_sub, ← Int.ofNat_one, ← Int.ofNat_sub this, zpow_neg, zpow_natCast, lt_inv_commβ‚€ hr (pow_pos (Nat.cast_pos.mpr <| zero_lt_one.trans hb) _), ← Nat.cast_pow] refine Nat.lt_ceil.1 ?_ exact Nat.pow_pred_clog_lt_self hb <| Nat.one_lt_cast.1 <| hcri.trans_le <| Nat.le_ceil _ @[simp] theorem log_zero_right (b : β„•) : log b (0 : R) = 0 := log_of_right_le_zero b le_rfl @[simp] theorem log_one_right (b : β„•) : log b (1 : R) = 0 := by rw [log_of_one_le_right _ le_rfl, Nat.floor_one, Nat.log_one_right, Int.ofNat_zero] omit [IsStrictOrderedRing R] in @[simp] theorem log_zero_left (r : R) : log 0 r = 0 := by simp only [log, Nat.log_zero_left, Nat.cast_zero, Nat.clog_zero_left, neg_zero, ite_self] omit [IsStrictOrderedRing R] in @[simp] theorem log_one_left (r : R) : log 1 r = 0 := by by_cases hr : 1 ≀ r Β· simp_all only [log, ↓reduceIte, Nat.log_one_left, Nat.cast_zero] Β· simp only [log, Nat.log_one_left, Nat.cast_zero, Nat.clog_one_left, neg_zero, ite_self] theorem log_zpow {b : β„•} (hb : 1 < b) (z : β„€) : log b (b ^ z : R) = z := by obtain ⟨n, rfl | rfl⟩ := Int.eq_nat_or_neg z Β· rw [log_of_one_le_right _ (one_le_zpowβ‚€ (mod_cast hb.le) <| Int.natCast_nonneg _), zpow_natCast, ← Nat.cast_pow, Nat.floor_natCast, Nat.log_pow hb] Β· rw [log_of_right_le_one _ (zpow_le_one_of_nonposβ‚€ (mod_cast hb.le) <| neg_nonpos.2 (Int.natCast_nonneg _)), zpow_neg, inv_inv, zpow_natCast, ← Nat.cast_pow, Nat.ceil_natCast, Nat.clog_pow _ _ hb] @[mono, gcongr] theorem log_mono_right {b : β„•} {r₁ rβ‚‚ : R} (hβ‚€ : 0 < r₁) (h : r₁ ≀ rβ‚‚) : log b r₁ ≀ log b rβ‚‚ := by rcases le_total r₁ 1 with h₁ | h₁ <;> rcases le_total rβ‚‚ 1 with hβ‚‚ | hβ‚‚ Β· have hβ‚€' : 0 < rβ‚‚ := lt_of_lt_of_le hβ‚€ h rw [log_of_right_le_one _ h₁, log_of_right_le_one _ hβ‚‚, neg_le_neg_iff, Nat.cast_le] exact Nat.clog_mono_right b <| Nat.ceil_mono <| (inv_le_invβ‚€ hβ‚€' hβ‚€).2 h Β· rw [log_of_right_le_one _ h₁, log_of_one_le_right _ hβ‚‚] exact (neg_nonpos.mpr (Int.natCast_nonneg _)).trans (Int.natCast_nonneg _) Β· obtain rfl := le_antisymm h (hβ‚‚.trans h₁) rfl Β· rw [log_of_one_le_right _ h₁, log_of_one_le_right _ hβ‚‚, Nat.cast_le] exact Nat.log_mono_right (Nat.floor_mono h) variable (R) in /-- Over suitable subtypes, `zpow` and `Int.log` form a Galois coinsertion -/ def zpowLogGi {b : β„•} (hb : 1 < b) : GaloisCoinsertion (fun z : β„€ => Subtype.mk ((b : R) ^ z) <| zpow_pos (mod_cast zero_lt_one.trans hb) z) fun r : Set.Ioi (0 : R) => Int.log b (r : R) := GaloisCoinsertion.monotoneIntro (fun r₁ _ => log_mono_right r₁.2) (fun _ _ hz => Subtype.coe_le_coe.mp <| (zpow_right_strictMonoβ‚€ <| mod_cast hb).monotone hz) (fun r => Subtype.coe_le_coe.mp <| zpow_log_le_self hb r.2) fun _ => log_zpow (R := R) hb _ /-- `zpow b` and `Int.log b` (almost) form a Galois connection. -/ theorem lt_zpow_iff_log_lt {b : β„•} (hb : 1 < b) {x : β„€} {r : R} (hr : 0 < r) : r < (b : R) ^ x ↔ log b r < x := @GaloisConnection.lt_iff_lt _ _ _ _ _ _ (zpowLogGi R hb).gc x ⟨r, hr⟩ /-- `zpow b` and `Int.log b` (almost) form a Galois connection. -/ theorem zpow_le_iff_le_log {b : β„•} (hb : 1 < b) {x : β„€} {r : R} (hr : 0 < r) : (b : R) ^ x ≀ r ↔ x ≀ log b r := @GaloisConnection.le_iff_le _ _ _ _ _ _ (zpowLogGi R hb).gc x ⟨r, hr⟩ /-- The least power of `b` such that `r ≀ b ^ log b r`. -/ def clog (b : β„•) (r : R) : β„€ := if 1 ≀ r then Nat.clog b ⌈rβŒ‰β‚Š else -Nat.log b ⌊rβ»ΒΉβŒ‹β‚Š omit [IsStrictOrderedRing R] in theorem clog_of_one_le_right (b : β„•) {r : R} (hr : 1 ≀ r) : clog b r = Nat.clog b ⌈rβŒ‰β‚Š := if_pos hr theorem clog_of_right_le_one (b : β„•) {r : R} (hr : r ≀ 1) : clog b r = -Nat.log b ⌊rβ»ΒΉβŒ‹β‚Š := by obtain rfl | hr := hr.eq_or_lt Β· rw [clog, if_pos hr, inv_one, Nat.ceil_one, Nat.floor_one, Nat.log_one_right, Nat.clog_one_right, Int.ofNat_zero, neg_zero] Β· exact if_neg hr.not_ge theorem clog_of_right_le_zero (b : β„•) {r : R} (hr : r ≀ 0) : clog b r = 0 := by rw [clog, if_neg (hr.trans_lt zero_lt_one).not_ge, neg_eq_zero, Int.natCast_eq_zero, Nat.log_eq_zero_iff] rcases le_or_gt b 1 with hb | hb Β· exact Or.inr hb Β· refine Or.inl (lt_of_le_of_lt ?_ hb) exact Nat.floor_le_one_of_le_one ((inv_nonpos.2 hr).trans zero_le_one) @[simp] theorem clog_inv (b : β„•) (r : R) : clog b r⁻¹ = -log b r := by rcases lt_or_ge 0 r with hrp | hrp Β· obtain hr | hr := le_total 1 r Β· rw [clog_of_right_le_one _ (inv_le_one_of_one_leβ‚€ hr), log_of_one_le_right _ hr, inv_inv] Β· rw [clog_of_one_le_right _ ((one_le_invβ‚€ hrp).2 hr), log_of_right_le_one _ hr, neg_neg] Β· rw [clog_of_right_le_zero _ (inv_nonpos.mpr hrp), log_of_right_le_zero _ hrp, neg_zero] @[simp] theorem log_inv (b : β„•) (r : R) : log b r⁻¹ = -clog b r := by rw [← inv_inv r, clog_inv, neg_neg, inv_inv] -- note this is useful for writing in reverse theorem neg_log_inv_eq_clog (b : β„•) (r : R) : -log b r⁻¹ = clog b r := by rw [log_inv, neg_neg] theorem neg_clog_inv_eq_log (b : β„•) (r : R) : -clog b r⁻¹ = log b r := by rw [clog_inv, neg_neg] @[simp, norm_cast] theorem clog_natCast (b : β„•) (n : β„•) : clog b (n : R) = Nat.clog b n := by rcases n with - | n Β· simp [clog_of_right_le_one] Β· rw [clog_of_one_le_right, (Nat.ceil_eq_iff (Nat.succ_ne_zero n)).mpr] <;> simp @[simp] theorem clog_ofNat (b : β„•) (n : β„•) [n.AtLeastTwo] : clog b (ofNat(n) : R) = Nat.clog b ofNat(n) := clog_natCast b n theorem clog_of_left_le_one {b : β„•} (hb : b ≀ 1) (r : R) : clog b r = 0 := by rw [← neg_log_inv_eq_clog, log_of_left_le_one hb, neg_zero] theorem self_le_zpow_clog {b : β„•} (hb : 1 < b) (r : R) : r ≀ (b : R) ^ clog b r := by rcases le_or_gt r 0 with hr | hr Β· rw [clog_of_right_le_zero _ hr, zpow_zero] exact hr.trans zero_le_one rw [← neg_log_inv_eq_clog, zpow_neg, le_inv_commβ‚€ hr (zpow_pos ..)] Β· exact zpow_log_le_self hb (inv_pos.mpr hr) Β· exact Nat.cast_pos.mpr (zero_le_one.trans_lt hb) theorem zpow_pred_clog_lt_self {b : β„•} {r : R} (hb : 1 < b) (hr : 0 < r) : (b : R) ^ (clog b r - 1) < r := by rw [← neg_log_inv_eq_clog, ← neg_add', zpow_neg, inv_lt_commβ‚€ _ hr] Β· exact lt_zpow_succ_log_self hb _ Β· exact zpow_pos (Nat.cast_pos.mpr <| zero_le_one.trans_lt hb) _ @[simp] theorem clog_zero_right (b : β„•) : clog b (0 : R) = 0 := clog_of_right_le_zero _ le_rfl @[simp] theorem clog_one_right (b : β„•) : clog b (1 : R) = 0 := by rw [clog_of_one_le_right _ le_rfl, Nat.ceil_one, Nat.clog_one_right, Int.ofNat_zero] omit [IsStrictOrderedRing R] in @[simp] theorem clog_zero_left (r : R) : clog 0 r = 0 := by by_cases hr : 1 ≀ r Β· simp only [clog, Nat.clog_zero_left, Nat.cast_zero, Nat.log_zero_left, neg_zero, ite_self] Β· simp only [clog, hr, ite_cond_eq_false, Nat.log_zero_left, Nat.cast_zero, neg_zero] omit [IsStrictOrderedRing R] in @[simp] theorem clog_one_left (r : R) : clog 1 r = 0 := by simp only [clog, Nat.log_one_left, Nat.cast_zero, Nat.clog_one_left, neg_zero, ite_self] theorem clog_zpow {b : β„•} (hb : 1 < b) (z : β„€) : clog b (b ^ z : R) = z := by rw [← neg_log_inv_eq_clog, ← zpow_neg, log_zpow hb, neg_neg] @[mono] theorem clog_mono_right {b : β„•} {r₁ rβ‚‚ : R} (hβ‚€ : 0 < r₁) (h : r₁ ≀ rβ‚‚) : clog b r₁ ≀ clog b rβ‚‚ := by have hβ‚€' : 0 < rβ‚‚ := lt_of_lt_of_le hβ‚€ h rw [← neg_log_inv_eq_clog, ← neg_log_inv_eq_clog, neg_le_neg_iff] exact log_mono_right (inv_pos_of_pos hβ‚€') <| (inv_le_invβ‚€ hβ‚€' hβ‚€).2 h variable (R) in /-- Over suitable subtypes, `Int.clog` and `zpow` form a Galois insertion -/ def clogZPowGi {b : β„•} (hb : 1 < b) : GaloisInsertion (fun r : Set.Ioi (0 : R) => Int.clog b (r : R)) fun z : β„€ => ⟨(b : R) ^ z, zpow_pos (mod_cast zero_lt_one.trans hb) z⟩ := GaloisInsertion.monotoneIntro (fun _ _ hz => Subtype.coe_le_coe.mp <| (zpow_right_strictMonoβ‚€ <| mod_cast hb).monotone hz) (fun r₁ _ => clog_mono_right r₁.2) (fun _ => Subtype.coe_le_coe.mp <| self_le_zpow_clog hb _) fun _ => clog_zpow (R := R) hb _ /-- `Int.clog b` and `zpow b` (almost) form a Galois connection. -/ theorem zpow_lt_iff_lt_clog {b : β„•} (hb : 1 < b) {x : β„€} {r : R} (hr : 0 < r) : (b : R) ^ x < r ↔ x < clog b r := (@GaloisConnection.lt_iff_lt _ _ _ _ _ _ (clogZPowGi R hb).gc ⟨r, hr⟩ x).symm /-- `Int.clog b` and `zpow b` (almost) form a Galois connection. -/ theorem le_zpow_iff_clog_le {b : β„•} (hb : 1 < b) {x : β„€} {r : R} (hr : 0 < r) : r ≀ (b : R) ^ x ↔ clog b r ≀ x := (@GaloisConnection.le_iff_le _ _ _ _ _ _ (clogZPowGi R hb).gc ⟨r, hr⟩ x).symm end Int
.lake/packages/mathlib/Mathlib/Data/Int/Associated.lean
import Mathlib.Algebra.GroupWithZero.Associated import Mathlib.Algebra.Ring.Int.Units /-! # Associated elements and the integers This file contains some results on equality up to units in the integers. ## Main results * `Int.natAbs_eq_iff_associated`: the absolute value is equal iff integers are associated -/ theorem Int.natAbs_eq_iff_associated {a b : β„€} : a.natAbs = b.natAbs ↔ Associated a b := by refine Int.natAbs_eq_natAbs_iff.trans ?_ constructor Β· rintro (rfl | rfl) Β· rfl Β· exact ⟨-1, by simp⟩ Β· rintro ⟨u, rfl⟩ obtain rfl | rfl := Int.units_eq_one_or u Β· exact Or.inl (by simp) Β· exact Or.inr (by simp)
.lake/packages/mathlib/Mathlib/Data/Int/AbsoluteValue.lean
import Mathlib.Algebra.Module.Basic import Mathlib.Algebra.Order.AbsoluteValue.Basic /-! # Absolute values and the integers This file contains some results on absolute values applied to integers. ## Main results * `AbsoluteValue.map_units_int`: an absolute value sends all units of `β„€` to `1` -/ variable {R S : Type*} [Ring R] [CommRing S] [LinearOrder S] [IsStrictOrderedRing S] @[simp] theorem AbsoluteValue.map_units_int (abv : AbsoluteValue β„€ S) (x : β„€Λ£) : abv x = 1 := by rcases Int.units_eq_one_or x with (rfl | rfl) <;> simp @[simp] theorem AbsoluteValue.map_units_intCast [Nontrivial R] (abv : AbsoluteValue R S) (x : β„€Λ£) : abv ((x : β„€) : R) = 1 := by rcases Int.units_eq_one_or x with (rfl | rfl) <;> simp @[simp] theorem AbsoluteValue.map_units_int_smul (abv : AbsoluteValue R S) (x : β„€Λ£) (y : R) : abv (x β€’ y) = abv y := by rcases Int.units_eq_one_or x with (rfl | rfl) <;> simp
.lake/packages/mathlib/Mathlib/Data/Int/Order/Lemmas.lean
import Mathlib.Algebra.Order.Ring.Abs /-! # Further lemmas about the integers The distinction between this file and `Data.Int.Order.Basic` is not particularly clear. They are separated by now to minimize the porting requirements for tactics during the transition to mathlib4. Please feel free to reorganize these two files. -/ open Function Nat namespace Int /-! ### nat abs -/ theorem natAbs_eq_iff_mul_self_eq {a b : β„€} : a.natAbs = b.natAbs ↔ a * a = b * b := by rw [← abs_eq_iff_mul_self_eq, abs_eq_natAbs, abs_eq_natAbs] exact Int.natCast_inj.symm theorem natAbs_lt_iff_mul_self_lt {a b : β„€} : a.natAbs < b.natAbs ↔ a * a < b * b := by rw [← abs_lt_iff_mul_self_lt, abs_eq_natAbs, abs_eq_natAbs] exact Int.ofNat_lt.symm theorem natAbs_le_iff_mul_self_le {a b : β„€} : a.natAbs ≀ b.natAbs ↔ a * a ≀ b * b := by rw [← abs_le_iff_mul_self_le, abs_eq_natAbs, abs_eq_natAbs] exact Int.ofNat_le.symm /-! ### Integer sqrt -/ theorem abs_le_sqrt {a b : β„€} (hn : 0 ≀ b) : |a| ≀ b.sqrt ↔ a * a ≀ b := by rw [← abs_mul_abs_self, eq_natCast_toNat.mpr hn, eq_natCast_toNat.mpr (abs_nonneg a), Int.sqrt_natCast, ← Int.natCast_mul, Nat.cast_le, Nat.cast_le, Nat.le_sqrt] theorem abs_le_sqrt_iff_sq_le {a b : β„€} (hn : 0 ≀ b) : |a| ≀ b.sqrt ↔ a ^ 2 ≀ b := pow_two a β–Έ abs_le_sqrt hn end Int
.lake/packages/mathlib/Mathlib/Data/Int/Order/Basic.lean
import Mathlib.Data.Int.Notation import Mathlib.Data.Nat.Notation import Mathlib.Order.Defs.LinearOrder import Mathlib.Tactic.ByCases /-! # The order relation on the integers -/ open Nat namespace Int theorem le.elim {a b : β„€} (h : a ≀ b) {P : Prop} (h' : βˆ€ n : β„•, a + ↑n = b β†’ P) : P := Exists.elim (le.dest h) h' alias ⟨le_of_ofNat_le_ofNat, ofNat_le_ofNat_of_le⟩ := ofNat_le theorem lt.elim {a b : β„€} (h : a < b) {P : Prop} (h' : βˆ€ n : β„•, a + ↑(Nat.succ n) = b β†’ P) : P := Exists.elim (lt.dest h) h' alias ⟨lt_of_ofNat_lt_ofNat, ofNat_lt_ofNat_of_lt⟩ := ofNat_lt instance instLinearOrder : LinearOrder β„€ where le_refl := Int.le_refl le_trans := @Int.le_trans le_antisymm := @Int.le_antisymm lt_iff_le_not_ge := @Int.lt_iff_le_not_le le_total := Int.le_total toDecidableEq := instDecidableEq toDecidableLE := decLe toDecidableLT := decLt protected theorem eq_zero_or_eq_zero_of_mul_eq_zero {a b : β„€} (h : a * b = 0) : a = 0 ∨ b = 0 := Int.mul_eq_zero.mp h theorem nonneg_or_nonpos_of_mul_nonneg {a b : β„€} : 0 ≀ a * b β†’ 0 ≀ a ∧ 0 ≀ b ∨ a ≀ 0 ∧ b ≀ 0 := by intro h by_cases! ha : 0 ≀ a <;> by_cases! hb : 0 ≀ b Β· exact .inl ⟨ha, hb⟩ Β· refine .inr ⟨?_, le_of_lt hb⟩ obtain _ | _ := Int.mul_eq_zero.mp <| Int.le_antisymm (Int.mul_nonpos_of_nonneg_of_nonpos ha <| le_of_lt hb) h all_goals cutsat Β· refine .inr ⟨le_of_lt ha, ?_⟩ obtain _ | _ := Int.mul_eq_zero.mp <| Int.le_antisymm (Int.mul_nonpos_of_nonpos_of_nonneg (le_of_lt ha) hb) h all_goals cutsat Β· exact .inr ⟨le_of_lt ha, le_of_lt hb⟩ theorem mul_nonneg_of_nonneg_or_nonpos {a b : β„€} : 0 ≀ a ∧ 0 ≀ b ∨ a ≀ 0 ∧ b ≀ 0 β†’ 0 ≀ a * b | .inl ⟨ha, hb⟩ => Int.mul_nonneg ha hb | .inr ⟨ha, hb⟩ => Int.mul_nonneg_of_nonpos_of_nonpos ha hb protected theorem mul_nonneg_iff {a b : β„€} : 0 ≀ a * b ↔ 0 ≀ a ∧ 0 ≀ b ∨ a ≀ 0 ∧ b ≀ 0 := ⟨nonneg_or_nonpos_of_mul_nonneg, mul_nonneg_of_nonneg_or_nonpos⟩ end Int
.lake/packages/mathlib/Mathlib/Data/Int/Order/Units.lean
import Mathlib.Algebra.Order.Ring.Abs /-! # Lemmas about units in `β„€`, which interact with the order structure. -/ namespace Int theorem isUnit_iff_abs_eq {x : β„€} : IsUnit x ↔ abs x = 1 := by rw [isUnit_iff_natAbs_eq, abs_eq_natAbs, ← Int.ofNat_one, natCast_inj] theorem isUnit_sq {a : β„€} (ha : IsUnit a) : a ^ 2 = 1 := by rw [sq, isUnit_mul_self ha] @[simp] theorem units_sq (u : β„€Λ£) : u ^ 2 = 1 := by rw [Units.ext_iff, Units.val_pow_eq_pow_val, Units.val_one, isUnit_sq u.isUnit] alias units_pow_two := units_sq @[simp] theorem units_mul_self (u : β„€Λ£) : u * u = 1 := by rw [← sq, units_sq] @[simp] theorem units_inv_eq_self (u : β„€Λ£) : u⁻¹ = u := by rw [inv_eq_iff_mul_eq_one, units_mul_self] theorem units_div_eq_mul (u₁ uβ‚‚ : β„€Λ£) : u₁ / uβ‚‚ = u₁ * uβ‚‚ := by rw [div_eq_mul_inv, units_inv_eq_self] -- `Units.val_mul` is a "wrong turn" for the simplifier, this undoes it and simplifies further @[simp] theorem units_coe_mul_self (u : β„€Λ£) : (u * u : β„€) = 1 := by rw [← Units.val_mul, units_mul_self, Units.val_one] theorem neg_one_pow_ne_zero {n : β„•} : (-1 : β„€) ^ n β‰  0 := by simp theorem sq_eq_one_of_sq_lt_four {x : β„€} (h1 : x ^ 2 < 4) (h2 : x β‰  0) : x ^ 2 = 1 := sq_eq_one_iff.mpr ((abs_eq (zero_le_one' β„€)).mp (le_antisymm (lt_add_one_iff.mp (abs_lt_of_sq_lt_sq h1 zero_le_two)) (sub_one_lt_iff.mp (abs_pos.mpr h2)))) theorem sq_eq_one_of_sq_le_three {x : β„€} (h1 : x ^ 2 ≀ 3) (h2 : x β‰  0) : x ^ 2 = 1 := sq_eq_one_of_sq_lt_four (lt_of_le_of_lt h1 (lt_add_one (3 : β„€))) h2 theorem units_pow_eq_pow_mod_two (u : β„€Λ£) (n : β„•) : u ^ n = u ^ (n % 2) := by conv => lhs rw [← Nat.mod_add_div n 2] rw [pow_add, pow_mul, units_sq, one_pow, mul_one] end Int
.lake/packages/mathlib/Mathlib/Data/Int/Cast/Lemmas.lean
import Mathlib.Algebra.Group.TypeTags.Hom import Mathlib.Algebra.Ring.Int.Defs import Mathlib.Algebra.Ring.Parity /-! # Cast of integers (additional theorems) This file proves additional properties about the *canonical* homomorphism from the integers into an additive group with a one (`Int.cast`), particularly results involving algebraic homomorphisms or the order structure on `β„€` which were not available in the import dependencies of `Data.Int.Cast.Basic`. ## Main declarations * `castAddHom`: `cast` bundled as an `AddMonoidHom`. * `castRingHom`: `cast` bundled as a `RingHom`. -/ assert_not_exists RelIso IsOrderedMonoid Field open Additive Function Multiplicative Nat variable {F ΞΉ Ξ± Ξ² : Type*} namespace Int /-- Coercion `β„• β†’ β„€` as a `RingHom`. -/ def ofNatHom : β„• β†’+* β„€ := Nat.castRingHom β„€ section cast @[simp, norm_cast] theorem cast_ite [IntCast Ξ±] (P : Prop) [Decidable P] (m n : β„€) : ((ite P m n : β„€) : Ξ±) = ite P (m : Ξ±) (n : Ξ±) := apply_ite _ _ _ _ /-- `coe : β„€ β†’ Ξ±` as an `AddMonoidHom`. -/ def castAddHom (Ξ± : Type*) [AddGroupWithOne Ξ±] : β„€ β†’+ Ξ± where toFun := Int.cast map_zero' := cast_zero map_add' := cast_add section AddGroupWithOne variable [AddGroupWithOne Ξ±] @[simp] lemma coe_castAddHom : ⇑(castAddHom Ξ±) = fun x : β„€ => (x : Ξ±) := rfl lemma _root_.Even.intCast {n : β„€} (h : Even n) : Even (n : Ξ±) := h.map (castAddHom Ξ±) variable [CharZero Ξ±] {m n : β„€} @[simp] lemma cast_eq_zero : (n : Ξ±) = 0 ↔ n = 0 where mp h := by cases n Β· rw [ofNat_eq_coe, Int.cast_natCast] at h exact congr_arg _ (Nat.cast_eq_zero.1 h) Β· rw [cast_negSucc, neg_eq_zero, Nat.cast_eq_zero] at h contradiction mpr h := by rw [h, cast_zero] @[simp, norm_cast] lemma cast_inj : (m : Ξ±) = n ↔ m = n := by rw [← sub_eq_zero, ← cast_sub, cast_eq_zero, sub_eq_zero] lemma cast_injective : Injective (Int.cast : β„€ β†’ Ξ±) := fun _ _ ↦ cast_inj.1 lemma cast_ne_zero : (n : Ξ±) β‰  0 ↔ n β‰  0 := not_congr cast_eq_zero @[simp] lemma cast_eq_one : (n : Ξ±) = 1 ↔ n = 1 := by rw [← cast_one, cast_inj] lemma cast_ne_one : (n : Ξ±) β‰  1 ↔ n β‰  1 := cast_eq_one.not end AddGroupWithOne section NonAssocRing variable [NonAssocRing Ξ±] variable (Ξ±) in /-- `coe : β„€ β†’ Ξ±` as a `RingHom`. -/ def castRingHom : β„€ β†’+* Ξ± where toFun := Int.cast map_zero' := cast_zero map_add' := cast_add map_one' := cast_one map_mul' := cast_mul @[simp] lemma coe_castRingHom : ⇑(castRingHom Ξ±) = fun x : β„€ ↦ (x : Ξ±) := rfl lemma cast_commute : βˆ€ (n : β„€) (a : Ξ±), Commute ↑n a | (n : β„•), x => by simpa using n.cast_commute x | -[n+1], x => by simpa only [cast_negSucc, Commute.neg_left_iff, Commute.neg_right_iff] using (n + 1).cast_commute (-x) lemma cast_comm (n : β„€) (x : Ξ±) : n * x = x * n := (cast_commute ..).eq lemma commute_cast (a : Ξ±) (n : β„€) : Commute a n := (cast_commute ..).symm @[simp] lemma _root_.zsmul_eq_mul (a : Ξ±) : βˆ€ n : β„€, n β€’ a = n * a | (n : β„•) => by rw [natCast_zsmul, nsmul_eq_mul, Int.cast_natCast] | -[n+1] => by simp [Nat.cast_succ, neg_add_rev, Int.cast_negSucc, add_mul] lemma _root_.zsmul_eq_mul' (a : Ξ±) (n : β„€) : n β€’ a = a * n := by rw [zsmul_eq_mul, (n.cast_commute a).eq] end NonAssocRing section Ring variable [Ring Ξ±] {n : β„€} lemma _root_.Odd.intCast (hn : Odd n) : Odd (n : Ξ±) := hn.map (castRingHom Ξ±) end Ring theorem cast_dvd_cast [Ring Ξ±] (m n : β„€) (h : m ∣ n) : (m : Ξ±) ∣ (n : Ξ±) := map_dvd (Int.castRingHom Ξ±) h end cast end Int open Int namespace SemiconjBy variable [Ring Ξ±] {a x y : Ξ±} @[simp] lemma intCast_mul_right (h : SemiconjBy a x y) (n : β„€) : SemiconjBy a (n * x) (n * y) := SemiconjBy.mul_right (Int.commute_cast _ _) h @[simp] lemma intCast_mul_left (h : SemiconjBy a x y) (n : β„€) : SemiconjBy (n * a) x y := SemiconjBy.mul_left (Int.cast_commute _ _) h lemma intCast_mul_intCast_mul (h : SemiconjBy a x y) (m n : β„€) : SemiconjBy (m * a) (n * x) (n * y) := by simp [h] end SemiconjBy namespace Commute section NonAssocRing variable [NonAssocRing Ξ±] {a : Ξ±} {n : β„€} @[simp] lemma intCast_left : Commute (n : Ξ±) a := Int.cast_commute _ _ @[simp] lemma intCast_right : Commute a n := Int.commute_cast _ _ end NonAssocRing section Ring variable [Ring Ξ±] {a b : Ξ±} lemma intCast_mul_right (h : Commute a b) (m : β„€) : Commute a (m * b) := by simp [h] lemma intCast_mul_left (h : Commute a b) (m : β„€) : Commute (m * a) b := by simp [h] lemma intCast_mul_intCast_mul (h : Commute a b) (m n : β„€) : Commute (m * a) (n * b) := SemiconjBy.intCast_mul_intCast_mul h m n variable (a) (m n : β„€) lemma self_intCast_mul : Commute a (n * a : Ξ±) := (Commute.refl a).intCast_mul_right n lemma intCast_mul_self : Commute ((n : Ξ±) * a) a := (Commute.refl a).intCast_mul_left n lemma self_intCast_mul_intCast_mul : Commute (m * a : Ξ±) (n * a : Ξ±) := (Commute.refl a).intCast_mul_intCast_mul m n end Ring end Commute namespace AddMonoidHom variable {A : Type*} /-- Two additive monoid homomorphisms `f`, `g` from `β„€` to an additive monoid are equal if `f 1 = g 1`. -/ @[ext high] theorem ext_int [AddMonoid A] {f g : β„€ β†’+ A} (h1 : f 1 = g 1) : f = g := have : f.comp (Int.ofNatHom : β„• β†’+ β„€) = g.comp (Int.ofNatHom : β„• β†’+ β„€) := ext_nat' _ _ h1 have this' : βˆ€ n : β„•, f n = g n := DFunLike.ext_iff.1 this ext fun n => match n with | (n : β„•) => this' n | .negSucc n => eq_on_neg _ _ (this' <| n + 1) variable [AddGroupWithOne A] theorem eq_intCastAddHom (f : β„€ β†’+ A) (h1 : f 1 = 1) : f = Int.castAddHom A := ext_int <| by simp [h1] end AddMonoidHom namespace AddEquiv variable {A : Type*} /-- Two additive monoid isomorphisms `f`, `g` from `β„€` to an additive monoid are equal if `f 1 = g 1`. -/ @[ext high] theorem ext_int [AddMonoid A] {f g : β„€ ≃+ A} (h1 : f 1 = g 1) : f = g := toAddMonoidHom_injective <| AddMonoidHom.ext_int h1 end AddEquiv theorem eq_intCast' [AddGroupWithOne Ξ±] [FunLike F β„€ Ξ±] [AddMonoidHomClass F β„€ Ξ±] (f : F) (h₁ : f 1 = 1) : βˆ€ n : β„€, f n = n := DFunLike.ext_iff.1 <| (f : β„€ β†’+ Ξ±).eq_intCastAddHom h₁ /-- This version is primed so that the `RingHomClass` versions aren't. -/ theorem map_intCast' [AddGroupWithOne Ξ±] [AddGroupWithOne Ξ²] [FunLike F Ξ± Ξ²] [AddMonoidHomClass F Ξ± Ξ²] (f : F) (h₁ : f 1 = 1) : βˆ€ n : β„€, f n = n := eq_intCast' ((f : Ξ± β†’+ Ξ²).comp <| Int.castAddHom _) (by simpa) @[simp] theorem Int.castAddHom_int : Int.castAddHom β„€ = AddMonoidHom.id β„€ := ((AddMonoidHom.id β„€).eq_intCastAddHom rfl).symm namespace MonoidHom variable {M : Type*} [Monoid M] @[ext] theorem ext_mint {f g : Multiplicative β„€ β†’* M} (h1 : f (ofAdd 1) = g (ofAdd 1)) : f = g := MonoidHom.toAdditiveRight.injective <| AddMonoidHom.ext_int <| Additive.toMul.injective h1 /-- If two `MonoidHom`s agree on `-1` and the naturals then they are equal. -/ @[ext] theorem ext_int {f g : β„€ β†’* M} (h_neg_one : f (-1) = g (-1)) (h_nat : f.comp Int.ofNatHom.toMonoidHom = g.comp Int.ofNatHom.toMonoidHom) : f = g := by ext (x | x) Β· exact (DFunLike.congr_fun h_nat x :) Β· rw [Int.negSucc_eq, ← neg_one_mul, f.map_mul, g.map_mul] congr 1 exact mod_cast (DFunLike.congr_fun h_nat (x + 1) :) end MonoidHom namespace MonoidWithZeroHom variable {M : Type*} [MonoidWithZero M] /-- If two `MonoidWithZeroHom`s agree on `-1` and the naturals then they are equal. -/ @[ext] theorem ext_int {f g : β„€ β†’*β‚€ M} (h_neg_one : f (-1) = g (-1)) (h_nat : f.comp Int.ofNatHom.toMonoidWithZeroHom = g.comp Int.ofNatHom.toMonoidWithZeroHom) : f = g := toMonoidHom_injective <| MonoidHom.ext_int h_neg_one <| MonoidHom.ext (DFunLike.congr_fun h_nat :) end MonoidWithZeroHom /-- If two `MonoidWithZeroHom`s agree on `-1` and the _positive_ naturals then they are equal. -/ theorem ext_int' [MonoidWithZero Ξ±] [FunLike F β„€ Ξ±] [MonoidWithZeroHomClass F β„€ Ξ±] {f g : F} (h_neg_one : f (-1) = g (-1)) (h_pos : βˆ€ n : β„•, 0 < n β†’ f n = g n) : f = g := (DFunLike.ext _ _) fun n => haveI := DFunLike.congr_fun (@MonoidWithZeroHom.ext_int _ _ (f : β„€ β†’*β‚€ Ξ±) (g : β„€ β†’*β‚€ Ξ±) h_neg_one <| MonoidWithZeroHom.ext_nat (h_pos _)) n this section Group variable (Ξ±) [Group Ξ±] (Ξ²) [AddGroup Ξ²] /-- Additive homomorphisms from `β„€` are defined by the image of `1`. -/ def zmultiplesHom : Ξ² ≃ (β„€ β†’+ Ξ²) where toFun x := { toFun := fun n => n β€’ x map_zero' := zero_zsmul x map_add' := fun _ _ => add_zsmul _ _ _ } invFun f := f 1 left_inv := one_zsmul right_inv f := AddMonoidHom.ext_int <| one_zsmul (f 1) /-- Monoid homomorphisms from `Multiplicative β„€` are defined by the image of `Multiplicative.ofAdd 1`. -/ def zpowersHom : Ξ± ≃ (Multiplicative β„€ β†’* Ξ±) := ofMul.trans <| (zmultiplesHom _).trans <| AddMonoidHom.toMultiplicativeLeft @[simp] lemma zmultiplesHom_apply (x : Ξ²) (n : β„€) : zmultiplesHom Ξ² x n = n β€’ x := rfl @[simp] lemma zmultiplesHom_symm_apply (f : β„€ β†’+ Ξ²) : (zmultiplesHom Ξ²).symm f = f 1 := rfl @[simp] lemma zpowersHom_apply (x : Ξ±) (n : Multiplicative β„€) : zpowersHom Ξ± x n = x ^ n.toAdd := rfl @[simp] lemma zpowersHom_symm_apply (f : Multiplicative β„€ β†’* Ξ±) : (zpowersHom Ξ±).symm f = f (ofAdd 1) := rfl lemma MonoidHom.apply_mint (f : Multiplicative β„€ β†’* Ξ±) (n : Multiplicative β„€) : f n = f (ofAdd 1) ^ n.toAdd := by rw [← zpowersHom_symm_apply, ← zpowersHom_apply, Equiv.apply_symm_apply] lemma AddMonoidHom.apply_int (f : β„€ β†’+ Ξ²) (n : β„€) : f n = n β€’ f 1 := by rw [← zmultiplesHom_symm_apply, ← zmultiplesHom_apply, Equiv.apply_symm_apply] end Group section CommGroup variable (Ξ±) [CommGroup Ξ±] (Ξ²) [AddCommGroup Ξ²] /-- If `Ξ±` is commutative, `zmultiplesHom` is an additive equivalence. -/ def zmultiplesAddHom : Ξ² ≃+ (β„€ β†’+ Ξ²) := { zmultiplesHom Ξ² with map_add' := fun a b => AddMonoidHom.ext fun n => by simp [zsmul_add] } /-- If `Ξ±` is commutative, `zpowersHom` is a multiplicative equivalence. -/ def zpowersMulHom : Ξ± ≃* (Multiplicative β„€ β†’* Ξ±) := { zpowersHom Ξ± with map_mul' := fun a b => MonoidHom.ext fun n => by simp [mul_zpow] } variable {Ξ±} @[simp] lemma zpowersMulHom_apply (x : Ξ±) (n : Multiplicative β„€) : zpowersMulHom Ξ± x n = x ^ n.toAdd := rfl @[simp] lemma zpowersMulHom_symm_apply (f : Multiplicative β„€ β†’* Ξ±) : (zpowersMulHom Ξ±).symm f = f (ofAdd 1) := rfl @[simp] lemma zmultiplesAddHom_apply (x : Ξ²) (n : β„€) : zmultiplesAddHom Ξ² x n = n β€’ x := rfl @[simp] lemma zmultiplesAddHom_symm_apply (f : β„€ β†’+ Ξ²) : (zmultiplesAddHom Ξ²).symm f = f 1 := rfl end CommGroup section NonAssocRing variable [NonAssocRing Ξ±] [NonAssocRing Ξ²] @[simp] theorem eq_intCast [FunLike F β„€ Ξ±] [RingHomClass F β„€ Ξ±] (f : F) (n : β„€) : f n = n := eq_intCast' f (map_one _) n @[simp] theorem map_intCast [FunLike F Ξ± Ξ²] [RingHomClass F Ξ± Ξ²] (f : F) (n : β„€) : f n = n := eq_intCast ((f : Ξ± β†’+* Ξ²).comp (Int.castRingHom Ξ±)) n namespace RingHom theorem eq_intCast' (f : β„€ β†’+* Ξ±) : f = Int.castRingHom Ξ± := RingHom.ext <| eq_intCast f theorem ext_int {R : Type*} [NonAssocSemiring R] (f g : β„€ β†’+* R) : f = g := coe_addMonoidHom_injective <| AddMonoidHom.ext_int <| f.map_one.trans g.map_one.symm instance Int.subsingleton_ringHom {R : Type*} [NonAssocSemiring R] : Subsingleton (β„€ β†’+* R) := ⟨RingHom.ext_int⟩ end RingHom end NonAssocRing @[simp] theorem Int.castRingHom_int : Int.castRingHom β„€ = RingHom.id β„€ := (RingHom.id β„€).eq_intCast'.symm
.lake/packages/mathlib/Mathlib/Data/Int/Cast/Prod.lean
import Mathlib.Data.Int.Cast.Basic import Mathlib.Data.Nat.Cast.Prod /-! # The product of two `AddGroupWithOne`s. -/ namespace Prod variable {Ξ± Ξ² : Type*} [AddGroupWithOne Ξ±] [AddGroupWithOne Ξ²] instance : AddGroupWithOne (Ξ± Γ— Ξ²) := { Prod.instAddMonoidWithOne, Prod.instAddGroup with intCast := fun n => (n, n) intCast_ofNat := fun _ => by ext <;> simp intCast_negSucc := fun _ => by ext <;> simp } @[simp] theorem fst_intCast (n : β„€) : (n : Ξ± Γ— Ξ²).fst = n := rfl @[simp] theorem snd_intCast (n : β„€) : (n : Ξ± Γ— Ξ²).snd = n := rfl end Prod
.lake/packages/mathlib/Mathlib/Data/Int/Cast/Pi.lean
import Batteries.Tactic.Alias import Mathlib.Data.Int.Notation import Mathlib.Tactic.TypeStar import Mathlib.Util.AssertExists import Mathlib.Tactic.Push.Attr /-! # Cast of integers to function types This file provides a (pointwise) cast from `β„€` to function types. ## Main declarations * `Pi.instIntCast`: map `n : β„€` to the constant function `n : βˆ€ i, Ο€ i` -/ assert_not_exists IsOrderedMonoid RingHom namespace Pi variable {ΞΉ : Type*} {Ο€ : ΞΉ β†’ Type*} [βˆ€ i, IntCast (Ο€ i)] instance instIntCast : IntCast (βˆ€ i, Ο€ i) where intCast n _ := n @[simp] theorem intCast_apply (n : β„€) (i : ΞΉ) : (n : βˆ€ i, Ο€ i) i = n := rfl @[push ←] theorem intCast_def (n : β„€) : (n : βˆ€ i, Ο€ i) = fun _ => ↑n := rfl end Pi @[simp] theorem Sum.elim_intCast_intCast {Ξ± Ξ² Ξ³ : Type*} [IntCast Ξ³] (n : β„€) : Sum.elim (n : Ξ± β†’ Ξ³) (n : Ξ² β†’ Ξ³) = n := Sum.elim_lam_const_lam_const (Ξ³ := Ξ³) n
.lake/packages/mathlib/Mathlib/Data/Int/Cast/Basic.lean
import Mathlib.Data.Int.Cast.Defs import Mathlib.Algebra.Group.Basic import Mathlib.Data.Nat.Basic /-! # Cast of integers (additional theorems) This file proves additional properties about the *canonical* homomorphism from the integers into an additive group with a one (`Int.cast`). There is also `Mathlib.Data.Int.Cast.Lemmas`, which includes lemmas stated in terms of algebraic homomorphisms, and results involving the order structure of `β„€`. By contrast, this file's only import beyond `Mathlib.Data.Int.Cast.Defs` is `Mathlib.Algebra.Group.Basic`. -/ universe u namespace Nat variable {R : Type u} [AddGroupWithOne R] @[simp, norm_cast] theorem cast_sub {m n} (h : m ≀ n) : ((n - m : β„•) : R) = n - m := eq_sub_of_add_eq <| by rw [← cast_add, Nat.sub_add_cancel h] @[simp, norm_cast] theorem cast_pred : βˆ€ {n}, 0 < n β†’ ((n - 1 : β„•) : R) = n - 1 | 0, h => by cases h | n + 1, _ => by rw [cast_succ, add_sub_cancel_right, Nat.add_sub_cancel_right] end Nat open Nat namespace Int variable {R : Type u} [AddGroupWithOne R] -- TODO: I don't like that `norm_cast` is used here, because it results in `norm_cast` -- introducing the "implementation detail" `Int.negSucc`. @[simp, norm_cast squash] theorem cast_negSucc (n : β„•) : (-[n+1] : R) = -(n + 1 : β„•) := AddGroupWithOne.intCast_negSucc n @[simp, norm_cast] theorem cast_zero : ((0 : β„€) : R) = 0 := (AddGroupWithOne.intCast_ofNat 0).trans Nat.cast_zero -- This lemma competes with `Int.ofNat_eq_natCast` to come later @[simp high, norm_cast] theorem cast_natCast (n : β„•) : ((n : β„€) : R) = n := AddGroupWithOne.intCast_ofNat _ @[simp, norm_cast] theorem cast_ofNat (n : β„•) [n.AtLeastTwo] : ((ofNat(n) : β„€) : R) = ofNat(n) := by simpa only [OfNat.ofNat] using AddGroupWithOne.intCast_ofNat (R := R) n @[simp, norm_cast] theorem cast_one : ((1 : β„€) : R) = 1 := by rw [← Int.natCast_one, cast_natCast, Nat.cast_one] @[simp, norm_cast] theorem cast_neg : βˆ€ n, ((-n : β„€) : R) = -n | (0 : β„•) => by simp | (n + 1 : β„•) => by rw [cast_natCast, neg_ofNat_succ]; simp | -[n+1] => by rw [Int.neg_negSucc, cast_natCast]; simp @[simp, norm_cast] theorem cast_subNatNat (m n) : ((Int.subNatNat m n : β„€) : R) = m - n := by unfold subNatNat cases e : n - m Β· simp [Nat.le_of_sub_eq_zero e] Β· rw [cast_negSucc, ← e, Nat.cast_sub <| _root_.le_of_lt <| Nat.lt_of_sub_eq_succ e, neg_sub] @[simp] theorem cast_negOfNat (n : β„•) : ((negOfNat n : β„€) : R) = -n := by simp [Int.cast_neg, negOfNat_eq] @[simp, norm_cast] theorem cast_add : βˆ€ m n, ((m + n : β„€) : R) = m + n | (m : β„•), (n : β„•) => by simp [← Int.natCast_add] | (m : β„•), -[n+1] => by rw [Int.ofNat_add_negSucc, cast_subNatNat, cast_natCast, cast_negSucc, sub_eq_add_neg] | -[m+1], (n : β„•) => by rw [Int.negSucc_add_ofNat, cast_subNatNat, cast_natCast, cast_negSucc, sub_eq_iff_eq_add, add_assoc, eq_neg_add_iff_add_eq, ← Nat.cast_add, ← Nat.cast_add, Nat.add_comm] | -[m+1], -[n+1] => by rw [Int.negSucc_add_negSucc, succ_eq_add_one, cast_negSucc, cast_negSucc, cast_negSucc, ← neg_add_rev, ← Nat.cast_add, Nat.add_right_comm m n 1, Nat.add_assoc, Nat.add_comm] @[simp, norm_cast] theorem cast_sub (m n) : ((m - n : β„€) : R) = m - n := by simp [Int.sub_eq_add_neg, sub_eq_add_neg, Int.cast_neg, Int.cast_add] theorem cast_two : ((2 : β„€) : R) = 2 := cast_ofNat _ theorem cast_three : ((3 : β„€) : R) = 3 := cast_ofNat _ theorem cast_four : ((4 : β„€) : R) = 4 := cast_ofNat _ end Int section zsmul variable {R : Type*} @[simp] lemma zsmul_one [AddGroupWithOne R] (n : β„€) : n β€’ (1 : R) = n := by cases n <;> simp end zsmul
.lake/packages/mathlib/Mathlib/Data/Int/Cast/Defs.lean
import Mathlib.Data.Nat.Cast.Defs /-! # Cast of integers This file defines the *canonical* homomorphism from the integers into an additive group with a one (typically a `Ring`). In additive groups with a one element, there exists a unique such homomorphism and we store it in the `intCast : β„€ β†’ R` field. Preferentially, the homomorphism is written as a coercion. ## Main declarations * `Int.cast`: Canonical homomorphism `β„€ β†’ R`. * `AddGroupWithOne`: Type class for `Int.cast`. -/ universe u /-- Default value for `IntCast.intCast` in an `AddGroupWithOne`. -/ protected def Int.castDef {R : Type u} [NatCast R] [Neg R] : β„€ β†’ R | (n : β„•) => n | Int.negSucc n => -(n + 1 : β„•) /-! ### Additive groups with one -/ /-- An `AddGroupWithOne` is an `AddGroup` with a 1. It also contains data for the unique homomorphisms `β„• β†’ R` and `β„€ β†’ R`. -/ class AddGroupWithOne (R : Type u) extends IntCast R, AddMonoidWithOne R, AddGroup R where /-- The canonical homomorphism `β„€ β†’ R`. -/ intCast := Int.castDef /-- The canonical homomorphism `β„€ β†’ R` agrees with the one from `β„• β†’ R` on `β„•`. -/ intCast_ofNat : βˆ€ n : β„•, intCast (n : β„•) = Nat.cast n := by intros; rfl /-- The canonical homomorphism `β„€ β†’ R` for negative values is just the negation of the values of the canonical homomorphism `β„• β†’ R`. -/ intCast_negSucc : βˆ€ n : β„•, intCast (Int.negSucc n) = -Nat.cast (n + 1) := by intros; rfl /-- An `AddCommGroupWithOne` is an `AddGroupWithOne` satisfying `a + b = b + a`. -/ class AddCommGroupWithOne (R : Type u) extends AddCommGroup R, AddGroupWithOne R, AddCommMonoidWithOne R
.lake/packages/mathlib/Mathlib/Data/Int/Cast/Field.lean
import Mathlib.Algebra.Field.Defs import Mathlib.Algebra.Ring.Int.Defs /-! # Cast of integers into fields This file concerns the canonical homomorphism `β„€ β†’ F`, where `F` is a field. ## Main results * `Int.cast_div`: if `n` divides `m`, then `↑(m / n) = ↑m / ↑n` -/ namespace Int open Nat variable {Ξ± : Type*} /-- Auxiliary lemma for norm_cast to move the cast `-↑n` upwards to `↑-↑n`. (The restriction to `DivisionRing` is necessary, otherwise this would also apply in the case where `R = β„€` and cause nontermination.) -/ @[norm_cast] theorem cast_neg_natCast {R} [DivisionRing R] (n : β„•) : ((-n : β„€) : R) = -n := by simp @[simp] theorem cast_div [DivisionRing Ξ±] {m n : β„€} (n_dvd : n ∣ m) (hn : (n : Ξ±) β‰  0) : ((m / n : β„€) : Ξ±) = m / n := by rcases n_dvd with ⟨k, rfl⟩ have : n β‰  0 := by rintro rfl; simp at hn rw [Int.mul_ediv_cancel_left _ this, mul_comm n, Int.cast_mul, mul_div_cancel_rightβ‚€ _ hn] end Int
.lake/packages/mathlib/Mathlib/Data/FinEnum/Option.lean
import Mathlib.Data.FinEnum import Mathlib.Logic.Equiv.Fin.Basic /-! # FinEnum instance for Option Provides a recursor for FinEnum types like `Fintype.truncRecEmptyOption`, but capable of producing non-truncated data. ## TODO * recreate rest of `Mathlib/Data/Fintype/Option.lean` -/ namespace FinEnum universe u v /-- Inserting an `Option.none` anywhere in an enumeration yields another enumeration. -/ def insertNone (Ξ± : Type u) [FinEnum Ξ±] (i : Fin (card Ξ± + 1)) : FinEnum (Option Ξ±) where card := card Ξ± + 1 equiv := equiv.optionCongr.trans <| finSuccEquiv' i |>.symm /-- This is an arbitrary choice of insertion rank for a default instance. It keeps the mapping of the existing `Ξ±`-inhabitants intact, modulo `Fin.castSucc`. -/ instance instFinEnumOptionLast (Ξ± : Type u) [FinEnum Ξ±] : FinEnum (Option Ξ±) := insertNone Ξ± (Fin.last _) open Fin.NatCast in -- TODO: refactor the proof to avoid needing this. /-- A recursor principle for finite-and-enumerable types, analogous to `Nat.rec`. It effectively says that every `FinEnum` is either `Empty` or `Option Ξ±`, up to an `Equiv` mediated by `Fin`s of equal cardinality. In contrast to the `Fintype` case, data can be transported along such an `Equiv`. Also, since order matters, the choice of element that gets replaced by `Option.none` has to be provided for every step. Since every `FinEnum` instance implies a `Fintype` instance and `Prop` is squashed already, `Fintype.induction_empty_option` can be used if a `Prop` needs to be constructed. Cf. `Data.Fintype.Option` -/ def recEmptyOption {P : Type u β†’ Sort v} (finChoice : (n : β„•) β†’ Fin (n + 1)) (congr : {Ξ± Ξ² : Type u} β†’ (_ : FinEnum Ξ±) β†’ (_ : FinEnum Ξ²) β†’ card Ξ² = card Ξ± β†’ P Ξ± β†’ P Ξ²) (empty : P PEmpty.{u + 1}) (option : {Ξ± : Type u} β†’ FinEnum Ξ± β†’ P Ξ± β†’ P (Option Ξ±)) (Ξ± : Type u) [FinEnum Ξ±] : P Ξ± := match cardeq : card Ξ± with | 0 => congr _ _ cardeq empty | n + 1 => let fN := ULift.instFinEnum (Ξ± := Fin n) have : card (ULift.{u} <| Fin n) = n := card_ulift.trans card_fin congr (insertNone _ <| finChoice n) _ (cardeq.trans <| congrArg Nat.succ this.symm) <| option fN (recEmptyOption finChoice congr empty option _) termination_by card Ξ± /-- For an empty type, the recursion principle evaluates to whatever `congr` makes of the base case. -/ theorem recEmptyOption_of_card_eq_zero {P : Type u β†’ Sort v} (finChoice : (n : β„•) β†’ Fin (n + 1)) (congr : {Ξ± Ξ² : Type u} β†’ (_ : FinEnum Ξ±) β†’ (_ : FinEnum Ξ²) β†’ card Ξ² = card Ξ± β†’ P Ξ± β†’ P Ξ²) (empty : P PEmpty.{u + 1}) (option : {Ξ± : Type u} β†’ FinEnum Ξ± β†’ P Ξ± β†’ P (Option Ξ±)) (Ξ± : Type u) [FinEnum Ξ±] (h : card Ξ± = 0) (_ : FinEnum PEmpty.{u + 1}) : recEmptyOption finChoice congr empty option Ξ± = congr _ _ (h.trans card_eq_zero.symm) empty := by unfold recEmptyOption split Β· congr 1; exact Subsingleton.allEq _ _ Β· exact Nat.noConfusion <| h.symm.trans β€Ή_β€Ί open Fin.NatCast in -- TODO: refactor the proof to avoid needing this. /-- For a type with positive `card`, the recursion principle evaluates to whatever `congr` makes of the step result, where `Option.none` has been inserted into the `(finChoice (card Ξ± - 1))`th rank of the enumeration. -/ theorem recEmptyOption_of_card_pos {P : Type u β†’ Sort v} (finChoice : (n : β„•) β†’ Fin (n + 1)) (congr : {Ξ± Ξ² : Type u} β†’ (_ : FinEnum Ξ±) β†’ (_ : FinEnum Ξ²) β†’ card Ξ² = card Ξ± β†’ P Ξ± β†’ P Ξ²) (empty : P PEmpty.{u + 1}) (option : {Ξ± : Type u} β†’ FinEnum Ξ± β†’ P Ξ± β†’ P (Option Ξ±)) (Ξ± : Type u) [FinEnum Ξ±] (h : 0 < card Ξ±) : recEmptyOption finChoice congr empty option Ξ± = congr (insertNone _ <| finChoice (card Ξ± - 1)) β€Ή_β€Ί (congrArg (Β· + 1) card_fin |>.trans <| (card Ξ±).succ_pred_eq_of_pos h).symm (option ULift.instFinEnum <| recEmptyOption finChoice congr empty option (ULift.{u} <| Fin (card Ξ± - 1))) := by conv => lhs; unfold recEmptyOption split Β· exact absurd (β€Ή_β€Ί β–Έ h) (card Ξ±).lt_irrefl Β· rcases Nat.succ.inj <| (card Ξ±).succ_pred_eq_of_pos h |>.trans β€Ή_β€Ί with rfl; rfl /-- A recursor principle for finite-and-enumerable types, analogous to `Nat.recOn`. It effectively says that every `FinEnum` is either `Empty` or `Option Ξ±`, up to an `Equiv` mediated by `Fin`s of equal cardinality. In contrast to the `Fintype` case, data can be transported along such an `Equiv`. Also, since order matters, the choice of element that gets replaced by `Option.none` has to be provided for every step. -/ abbrev recOnEmptyOption {P : Type u β†’ Sort v} {Ξ± : Type u} (aenum : FinEnum Ξ±) (finChoice : (n : β„•) β†’ Fin (n + 1)) (congr : {Ξ± Ξ² : Type u} β†’ (_ : FinEnum Ξ±) β†’ (_ : FinEnum Ξ²) β†’ card Ξ² = card Ξ± β†’ P Ξ± β†’ P Ξ²) (empty : P PEmpty.{u + 1}) (option : {Ξ± : Type u} β†’ FinEnum Ξ± β†’ P Ξ± β†’ P (Option Ξ±)) : P Ξ± := @recEmptyOption P finChoice congr empty option Ξ± aenum end FinEnum
.lake/packages/mathlib/Mathlib/Data/Rel/Separated.lean
import Mathlib.Data.Set.Pairwise.Basic import Mathlib.Data.Rel /-! # Uniform separation This file defines a notion of separation of a set relative to an relation. For a relation `R`, a `R`-separated set `s` is a set such that every pair of elements of `s` is `R`-unrelated. The concept of uniformly separated sets is used to define two further notions of separation: * Metric separation: `Metric.IsSeparated`, defined using the small distance relation. * Dynamical nets: `Dynamics.IsDynNetIn`, defined using the dynamical relation. ## TODO * Actually use `SetRel.IsSeparated` to define the above two notions. * Link to the notion of separation given by pairwise disjoint balls. -/ open Set namespace SetRel variable {X : Type*} {R S : SetRel X X} {s t : Set X} {x : X} /-- Given a relation `R`, a set `s` is `R`-separated if its elements are pairwise `R`-unrelated from each other. -/ def IsSeparated (R : SetRel X X) (s : Set X) : Prop := s.Pairwise fun x y ↦ Β¬ x ~[R] y protected lemma IsSeparated.empty : IsSeparated R (βˆ… : Set X) := pairwise_empty _ protected lemma IsSeparated.singleton : IsSeparated R {x} := pairwise_singleton .. @[simp] lemma IsSeparated.of_subsingleton (hs : s.Subsingleton) : IsSeparated R s := hs.pairwise _ alias _root_.Set.Subsingleton.relIsSeparated := IsSeparated.of_subsingleton nonrec lemma IsSeparated.mono_left (hUV : R βŠ† S) (hs : IsSeparated S s) : IsSeparated R s := hs.mono' fun _x _y hxy h ↦ hxy <| hUV h lemma IsSeparated.mono_right (hst : s βŠ† t) (ht : IsSeparated R t) : IsSeparated R s := ht.mono hst lemma isSeparated_insert' : IsSeparated R (insert x s) ↔ IsSeparated R s ∧ (βˆ€ y ∈ s, x ~[R] y β†’ x = y) ∧ βˆ€ y ∈ s, y ~[R] x β†’ x = y := by simp [IsSeparated, pairwise_insert, not_imp_comm (a := _ = _), -not_and, forall_and] lemma isSeparated_insert [R.IsSymm] : IsSeparated R (insert x s) ↔ IsSeparated R s ∧ βˆ€ y ∈ s, x ~[R] y β†’ x = y := by simpa [not_imp_not, IsSeparated] using pairwise_insert_of_symmetric fun _ _ ↦ mt R.symm lemma isSeparated_insert_of_notMem [R.IsSymm] (hx : x βˆ‰ s) : IsSeparated R (insert x s) ↔ IsSeparated R s ∧ βˆ€ y ∈ s, Β¬ x ~[R] y := pairwise_insert_of_symmetric_of_notMem (fun _ _ ↦ mt R.symm) hx protected lemma IsSeparated.insert [R.IsSymm] (hs : IsSeparated R s) (h : βˆ€ y ∈ s, x ~[R] y β†’ x = y) : IsSeparated R (insert x s) := isSeparated_insert.2 ⟨hs, h⟩ end SetRel
.lake/packages/mathlib/Mathlib/Data/Rel/Cover.lean
import Mathlib.Data.Rel.Separated /-! # Covers in a uniform space This file defines covers, aka nets, which are a quantitative notion of compactness given an entourage. A `U`-cover of a set `s` is a set `N` such that every element of `s` is `U`-close to some element of `N`. The concept of uniform covers can be used to define two further notions of covering: * Metric covers: `Metric.IsCover`, defined using the distance entourage. * Dynamical covers: `Dynamics.IsDynCoverOf`, defined using the dynamical entourage. ## References [R. Vershynin, *High Dimensional Probability*][vershynin2018high], Section 4.2. -/ open Set namespace SetRel variable {X : Type*} {U V : SetRel X X} {s t N N₁ Nβ‚‚ : Set X} {x : X} /-- For an entourage `U`, a set `N` is a *`U`-cover* of a set `s` if every point of `s` is `U`-close to some point of `N`. This is also called a *`U`-net* in the literature. [R. Vershynin, *High Dimensional Probability*][vershynin2018high], 4.2.1. -/ def IsCover (U : SetRel X X) (s N : Set X) : Prop := βˆ€ ⦃x⦄, x ∈ s β†’ βˆƒ y ∈ N, x ~[U] y @[simp] lemma IsCover.empty : IsCover U βˆ… N := by simp [IsCover] @[simp] lemma isCover_empty_right : IsCover U s βˆ… ↔ s = βˆ… := by simp [IsCover, eq_empty_iff_forall_notMem] protected nonrec lemma IsCover.nonempty (hsN : IsCover U s N) (hs : s.Nonempty) : N.Nonempty := let ⟨_x, hx⟩ := hs; let ⟨y, hy, _⟩ := hsN hx; ⟨y, hy⟩ @[simp] lemma IsCover.refl (U : SetRel X X) [U.IsRefl] (s : Set X) : IsCover U s s := fun a ha ↦ ⟨a, ha, U.rfl⟩ lemma IsCover.rfl {U : SetRel X X} [U.IsRefl] {s : Set X} : IsCover U s s := refl U s @[simp] protected lemma isCover_univ : IsCover univ s N ↔ (s.Nonempty β†’ N.Nonempty) := by simp [IsCover, Set.Nonempty] lemma IsCover.mono (hN : N₁ βŠ† Nβ‚‚) (h₁ : IsCover U s N₁) : IsCover U s Nβ‚‚ := fun _x hx ↦ let ⟨y, hy, hxy⟩ := h₁ hx; ⟨y, hN hy, hxy⟩ lemma IsCover.anti (hst : s βŠ† t) (ht : IsCover U t N) : IsCover U s N := fun _x hx ↦ ht <| hst hx lemma IsCover.mono_entourage (hUV : U βŠ† V) (hU : IsCover U s N) : IsCover V s N := fun _x hx ↦ let ⟨y, hy, hxy⟩ := hU hx; ⟨y, hy, hUV hxy⟩ /-- A maximal `U`-separated subset of a set `s` is a `U`-cover of `s`. [R. Vershynin, *High Dimensional Probability*][vershynin2018high], 4.2.6. -/ lemma IsCover.of_maximal_isSeparated [U.IsRefl] [U.IsSymm] (hN : Maximal (fun N ↦ N βŠ† s ∧ IsSeparated U N) N) : IsCover U s N := by rintro x hx by_contra! h simpa [U.rfl] using h _ <| hN.2 (y := insert x N) ⟨by simp [insert_subset_iff, hx, hN.1.1], hN.1.2.insert fun y hy hxy ↦ (h y hy hxy).elim⟩ (subset_insert _ _) (mem_insert _ _) @[simp] lemma isCover_relId : IsCover .id s N ↔ s βŠ† N := by simp [IsCover, subset_def] end SetRel
.lake/packages/mathlib/Mathlib/Data/Sum/Interval.lean
import Mathlib.Data.Finset.Sum import Mathlib.Data.Sum.Order import Mathlib.Order.Interval.Finset.Defs /-! # Finite intervals in a disjoint union This file provides the `LocallyFiniteOrder` instance for the disjoint sum and linear sum of two orders and calculates the cardinality of their finite intervals. -/ open Function Sum namespace Finset variable {α₁ Ξ±β‚‚ β₁ Ξ²β‚‚ γ₁ Ξ³β‚‚ : Type*} section SumLiftβ‚‚ variable (f f₁ g₁ : α₁ β†’ β₁ β†’ Finset γ₁) (g fβ‚‚ gβ‚‚ : Ξ±β‚‚ β†’ Ξ²β‚‚ β†’ Finset Ξ³β‚‚) /-- Lifts maps `α₁ β†’ β₁ β†’ Finset γ₁` and `Ξ±β‚‚ β†’ Ξ²β‚‚ β†’ Finset Ξ³β‚‚` to a map `α₁ βŠ• Ξ±β‚‚ β†’ β₁ βŠ• Ξ²β‚‚ β†’ Finset (γ₁ βŠ• Ξ³β‚‚)`. Could be generalized to `Alternative` functors if we can make sure to keep computability and universe polymorphism. -/ @[simp] def sumLiftβ‚‚ : βˆ€ (_ : α₁ βŠ• Ξ±β‚‚) (_ : β₁ βŠ• Ξ²β‚‚), Finset (γ₁ βŠ• Ξ³β‚‚) | inl a, inl b => (f a b).map Embedding.inl | inl _, inr _ => βˆ… | inr _, inl _ => βˆ… | inr a, inr b => (g a b).map Embedding.inr variable {f f₁ g₁ g fβ‚‚ gβ‚‚} {a : α₁ βŠ• Ξ±β‚‚} {b : β₁ βŠ• Ξ²β‚‚} {c : γ₁ βŠ• Ξ³β‚‚} theorem mem_sumLiftβ‚‚ : c ∈ sumLiftβ‚‚ f g a b ↔ (βˆƒ a₁ b₁ c₁, a = inl a₁ ∧ b = inl b₁ ∧ c = inl c₁ ∧ c₁ ∈ f a₁ b₁) ∨ βˆƒ aβ‚‚ bβ‚‚ cβ‚‚, a = inr aβ‚‚ ∧ b = inr bβ‚‚ ∧ c = inr cβ‚‚ ∧ cβ‚‚ ∈ g aβ‚‚ bβ‚‚ := by constructor Β· rcases a with a | a <;> rcases b with b | b Β· rw [sumLiftβ‚‚, mem_map] rintro ⟨c, hc, rfl⟩ exact Or.inl ⟨a, b, c, rfl, rfl, rfl, hc⟩ Β· refine fun h ↦ (notMem_empty _ h).elim Β· refine fun h ↦ (notMem_empty _ h).elim Β· rw [sumLiftβ‚‚, mem_map] rintro ⟨c, hc, rfl⟩ exact Or.inr ⟨a, b, c, rfl, rfl, rfl, hc⟩ Β· rintro (⟨a, b, c, rfl, rfl, rfl, h⟩ | ⟨a, b, c, rfl, rfl, rfl, h⟩) <;> exact mem_map_of_mem _ h theorem inl_mem_sumLiftβ‚‚ {c₁ : γ₁} : inl c₁ ∈ sumLiftβ‚‚ f g a b ↔ βˆƒ a₁ b₁, a = inl a₁ ∧ b = inl b₁ ∧ c₁ ∈ f a₁ b₁ := by rw [mem_sumLiftβ‚‚, or_iff_left] Β· simp only [inl.injEq, exists_and_left, exists_eq_left'] rintro ⟨_, _, cβ‚‚, _, _, h, _⟩ exact inl_ne_inr h theorem inr_mem_sumLiftβ‚‚ {cβ‚‚ : Ξ³β‚‚} : inr cβ‚‚ ∈ sumLiftβ‚‚ f g a b ↔ βˆƒ aβ‚‚ bβ‚‚, a = inr aβ‚‚ ∧ b = inr bβ‚‚ ∧ cβ‚‚ ∈ g aβ‚‚ bβ‚‚ := by rw [mem_sumLiftβ‚‚, or_iff_right] Β· simp only [inr.injEq, exists_and_left, exists_eq_left'] rintro ⟨_, _, cβ‚‚, _, _, h, _⟩ exact inr_ne_inl h theorem sumLiftβ‚‚_eq_empty : sumLiftβ‚‚ f g a b = βˆ… ↔ (βˆ€ a₁ b₁, a = inl a₁ β†’ b = inl b₁ β†’ f a₁ b₁ = βˆ…) ∧ βˆ€ aβ‚‚ bβ‚‚, a = inr aβ‚‚ β†’ b = inr bβ‚‚ β†’ g aβ‚‚ bβ‚‚ = βˆ… := by refine ⟨fun h ↦ ?_, fun h ↦ ?_⟩ Β· constructor <;> Β· rintro a b rfl rfl exact map_eq_empty.1 h cases a <;> cases b Β· exact map_eq_empty.2 (h.1 _ _ rfl rfl) Β· rfl Β· rfl Β· exact map_eq_empty.2 (h.2 _ _ rfl rfl) theorem sumLiftβ‚‚_nonempty : (sumLiftβ‚‚ f g a b).Nonempty ↔ (βˆƒ a₁ b₁, a = inl a₁ ∧ b = inl b₁ ∧ (f a₁ b₁).Nonempty) ∨ βˆƒ aβ‚‚ bβ‚‚, a = inr aβ‚‚ ∧ b = inr bβ‚‚ ∧ (g aβ‚‚ bβ‚‚).Nonempty := by simp only [nonempty_iff_ne_empty, Ne, sumLiftβ‚‚_eq_empty, not_and_or, not_forall, exists_prop] theorem sumLiftβ‚‚_mono (h₁ : βˆ€ a b, f₁ a b βŠ† g₁ a b) (hβ‚‚ : βˆ€ a b, fβ‚‚ a b βŠ† gβ‚‚ a b) : βˆ€ a b, sumLiftβ‚‚ f₁ fβ‚‚ a b βŠ† sumLiftβ‚‚ g₁ gβ‚‚ a b | inl _, inl _ => map_subset_map.2 (h₁ _ _) | inl _, inr _ => Subset.rfl | inr _, inl _ => Subset.rfl | inr _, inr _ => map_subset_map.2 (hβ‚‚ _ _) end SumLiftβ‚‚ section SumLexLift variable (f₁ f₁' : α₁ β†’ β₁ β†’ Finset γ₁) (fβ‚‚ fβ‚‚' : Ξ±β‚‚ β†’ Ξ²β‚‚ β†’ Finset Ξ³β‚‚) (g₁ g₁' : α₁ β†’ Ξ²β‚‚ β†’ Finset γ₁) (gβ‚‚ gβ‚‚' : α₁ β†’ Ξ²β‚‚ β†’ Finset Ξ³β‚‚) /-- Lifts maps `α₁ β†’ β₁ β†’ Finset γ₁`, `Ξ±β‚‚ β†’ Ξ²β‚‚ β†’ Finset Ξ³β‚‚`, `α₁ β†’ Ξ²β‚‚ β†’ Finset γ₁`, `Ξ±β‚‚ β†’ Ξ²β‚‚ β†’ Finset Ξ³β‚‚` to a map `α₁ βŠ• Ξ±β‚‚ β†’ β₁ βŠ• Ξ²β‚‚ β†’ Finset (γ₁ βŠ• Ξ³β‚‚)`. Could be generalized to alternative monads if we can make sure to keep computability and universe polymorphism. -/ def sumLexLift : α₁ βŠ• Ξ±β‚‚ β†’ β₁ βŠ• Ξ²β‚‚ β†’ Finset (γ₁ βŠ• Ξ³β‚‚) | inl a, inl b => (f₁ a b).map Embedding.inl | inl a, inr b => (g₁ a b).disjSum (gβ‚‚ a b) | inr _, inl _ => βˆ… | inr a, inr b => (fβ‚‚ a b).map ⟨_, inr_injective⟩ @[simp] lemma sumLexLift_inl_inl (a : α₁) (b : β₁) : sumLexLift f₁ fβ‚‚ g₁ gβ‚‚ (inl a) (inl b) = (f₁ a b).map Embedding.inl := rfl @[simp] lemma sumLexLift_inl_inr (a : α₁) (b : Ξ²β‚‚) : sumLexLift f₁ fβ‚‚ g₁ gβ‚‚ (inl a) (inr b) = (g₁ a b).disjSum (gβ‚‚ a b) := rfl @[simp] lemma sumLexLift_inr_inl (a : Ξ±β‚‚) (b : β₁) : sumLexLift f₁ fβ‚‚ g₁ gβ‚‚ (inr a) (inl b) = βˆ… := rfl @[simp] lemma sumLexLift_inr_inr (a : Ξ±β‚‚) (b : Ξ²β‚‚) : sumLexLift f₁ fβ‚‚ g₁ gβ‚‚ (inr a) (inr b) = (fβ‚‚ a b).map ⟨_, inr_injective⟩ := rfl variable {f₁ g₁ fβ‚‚ gβ‚‚ f₁' g₁' fβ‚‚' gβ‚‚'} {a : α₁ βŠ• Ξ±β‚‚} {b : β₁ βŠ• Ξ²β‚‚} {c : γ₁ βŠ• Ξ³β‚‚} lemma mem_sumLexLift : c ∈ sumLexLift f₁ fβ‚‚ g₁ gβ‚‚ a b ↔ (βˆƒ a₁ b₁ c₁, a = inl a₁ ∧ b = inl b₁ ∧ c = inl c₁ ∧ c₁ ∈ f₁ a₁ b₁) ∨ (βˆƒ a₁ bβ‚‚ c₁, a = inl a₁ ∧ b = inr bβ‚‚ ∧ c = inl c₁ ∧ c₁ ∈ g₁ a₁ bβ‚‚) ∨ (βˆƒ a₁ bβ‚‚ cβ‚‚, a = inl a₁ ∧ b = inr bβ‚‚ ∧ c = inr cβ‚‚ ∧ cβ‚‚ ∈ gβ‚‚ a₁ bβ‚‚) ∨ βˆƒ aβ‚‚ bβ‚‚ cβ‚‚, a = inr aβ‚‚ ∧ b = inr bβ‚‚ ∧ c = inr cβ‚‚ ∧ cβ‚‚ ∈ fβ‚‚ aβ‚‚ bβ‚‚ := by constructor Β· obtain a | a := a <;> obtain b | b := b Β· rw [sumLexLift, mem_map] rintro ⟨c, hc, rfl⟩ exact Or.inl ⟨a, b, c, rfl, rfl, rfl, hc⟩ Β· refine fun h ↦ (mem_disjSum.1 h).elim ?_ ?_ Β· rintro ⟨c, hc, rfl⟩ exact Or.inr (Or.inl ⟨a, b, c, rfl, rfl, rfl, hc⟩) Β· rintro ⟨c, hc, rfl⟩ exact Or.inr (Or.inr <| Or.inl ⟨a, b, c, rfl, rfl, rfl, hc⟩) Β· exact fun h ↦ (notMem_empty _ h).elim Β· rw [sumLexLift, mem_map] rintro ⟨c, hc, rfl⟩ exact Or.inr (Or.inr <| Or.inr <| ⟨a, b, c, rfl, rfl, rfl, hc⟩) Β· rintro (⟨a, b, c, rfl, rfl, rfl, hc⟩ | ⟨a, b, c, rfl, rfl, rfl, hc⟩ | ⟨a, b, c, rfl, rfl, rfl, hc⟩ | ⟨a, b, c, rfl, rfl, rfl, hc⟩) Β· exact mem_map_of_mem _ hc Β· exact inl_mem_disjSum.2 hc Β· exact inr_mem_disjSum.2 hc Β· exact mem_map_of_mem _ hc lemma inl_mem_sumLexLift {c₁ : γ₁} : inl c₁ ∈ sumLexLift f₁ fβ‚‚ g₁ gβ‚‚ a b ↔ (βˆƒ a₁ b₁, a = inl a₁ ∧ b = inl b₁ ∧ c₁ ∈ f₁ a₁ b₁) ∨ βˆƒ a₁ bβ‚‚, a = inl a₁ ∧ b = inr bβ‚‚ ∧ c₁ ∈ g₁ a₁ bβ‚‚ := by simp [mem_sumLexLift] lemma inr_mem_sumLexLift {cβ‚‚ : Ξ³β‚‚} : inr cβ‚‚ ∈ sumLexLift f₁ fβ‚‚ g₁ gβ‚‚ a b ↔ (βˆƒ a₁ bβ‚‚, a = inl a₁ ∧ b = inr bβ‚‚ ∧ cβ‚‚ ∈ gβ‚‚ a₁ bβ‚‚) ∨ βˆƒ aβ‚‚ bβ‚‚, a = inr aβ‚‚ ∧ b = inr bβ‚‚ ∧ cβ‚‚ ∈ fβ‚‚ aβ‚‚ bβ‚‚ := by simp [mem_sumLexLift] lemma sumLexLift_mono (hf₁ : βˆ€ a b, f₁ a b βŠ† f₁' a b) (hfβ‚‚ : βˆ€ a b, fβ‚‚ a b βŠ† fβ‚‚' a b) (hg₁ : βˆ€ a b, g₁ a b βŠ† g₁' a b) (hgβ‚‚ : βˆ€ a b, gβ‚‚ a b βŠ† gβ‚‚' a b) (a : α₁ βŠ• Ξ±β‚‚) (b : β₁ βŠ• Ξ²β‚‚) : sumLexLift f₁ fβ‚‚ g₁ gβ‚‚ a b βŠ† sumLexLift f₁' fβ‚‚' g₁' gβ‚‚' a b := by cases a <;> cases b exacts [map_subset_map.2 (hf₁ _ _), disjSum_mono (hg₁ _ _) (hgβ‚‚ _ _), Subset.rfl, map_subset_map.2 (hfβ‚‚ _ _)] lemma sumLexLift_eq_empty : sumLexLift f₁ fβ‚‚ g₁ gβ‚‚ a b = βˆ… ↔ (βˆ€ a₁ b₁, a = inl a₁ β†’ b = inl b₁ β†’ f₁ a₁ b₁ = βˆ…) ∧ (βˆ€ a₁ bβ‚‚, a = inl a₁ β†’ b = inr bβ‚‚ β†’ g₁ a₁ bβ‚‚ = βˆ… ∧ gβ‚‚ a₁ bβ‚‚ = βˆ…) ∧ βˆ€ aβ‚‚ bβ‚‚, a = inr aβ‚‚ β†’ b = inr bβ‚‚ β†’ fβ‚‚ aβ‚‚ bβ‚‚ = βˆ… := by refine ⟨fun h ↦ ⟨?_, ?_, ?_⟩, fun h ↦ ?_⟩ any_goals rintro a b rfl rfl; exact map_eq_empty.1 h Β· rintro a b rfl rfl; exact disjSum_eq_empty.1 h cases a <;> cases b Β· exact map_eq_empty.2 (h.1 _ _ rfl rfl) Β· simp [h.2.1 _ _ rfl rfl] Β· rfl Β· exact map_eq_empty.2 (h.2.2 _ _ rfl rfl) lemma sumLexLift_nonempty : (sumLexLift f₁ fβ‚‚ g₁ gβ‚‚ a b).Nonempty ↔ (βˆƒ a₁ b₁, a = inl a₁ ∧ b = inl b₁ ∧ (f₁ a₁ b₁).Nonempty) ∨ (βˆƒ a₁ bβ‚‚, a = inl a₁ ∧ b = inr bβ‚‚ ∧ ((g₁ a₁ bβ‚‚).Nonempty ∨ (gβ‚‚ a₁ bβ‚‚).Nonempty)) ∨ βˆƒ aβ‚‚ bβ‚‚, a = inr aβ‚‚ ∧ b = inr bβ‚‚ ∧ (fβ‚‚ aβ‚‚ bβ‚‚).Nonempty := by simp only [nonempty_iff_ne_empty, Ne, sumLexLift_eq_empty, not_and_or, exists_prop, not_forall] end SumLexLift end Finset open Finset namespace Sum variable {Ξ± Ξ² : Type*} /-! ### Disjoint sum of orders -/ section Disjoint section LocallyFiniteOrder variable [Preorder Ξ±] [Preorder Ξ²] [LocallyFiniteOrder Ξ±] [LocallyFiniteOrder Ξ²] instance instLocallyFiniteOrder : LocallyFiniteOrder (Ξ± βŠ• Ξ²) where finsetIcc := sumLiftβ‚‚ Icc Icc finsetIco := sumLiftβ‚‚ Ico Ico finsetIoc := sumLiftβ‚‚ Ioc Ioc finsetIoo := sumLiftβ‚‚ Ioo Ioo finset_mem_Icc := by simp finset_mem_Ico := by simp finset_mem_Ioc := by simp finset_mem_Ioo := by simp variable (a₁ aβ‚‚ : Ξ±) (b₁ bβ‚‚ : Ξ²) theorem Icc_inl_inl : Icc (inl a₁ : Ξ± βŠ• Ξ²) (inl aβ‚‚) = (Icc a₁ aβ‚‚).map Embedding.inl := rfl theorem Ico_inl_inl : Ico (inl a₁ : Ξ± βŠ• Ξ²) (inl aβ‚‚) = (Ico a₁ aβ‚‚).map Embedding.inl := rfl theorem Ioc_inl_inl : Ioc (inl a₁ : Ξ± βŠ• Ξ²) (inl aβ‚‚) = (Ioc a₁ aβ‚‚).map Embedding.inl := rfl theorem Ioo_inl_inl : Ioo (inl a₁ : Ξ± βŠ• Ξ²) (inl aβ‚‚) = (Ioo a₁ aβ‚‚).map Embedding.inl := rfl @[simp] theorem Icc_inl_inr : Icc (inl a₁) (inr bβ‚‚) = βˆ… := rfl @[simp] theorem Ico_inl_inr : Ico (inl a₁) (inr bβ‚‚) = βˆ… := rfl @[simp] theorem Ioc_inl_inr : Ioc (inl a₁) (inr bβ‚‚) = βˆ… := rfl @[simp] theorem Ioo_inl_inr : Ioo (inl a₁) (inr bβ‚‚) = βˆ… := rfl @[simp] theorem Icc_inr_inl : Icc (inr b₁) (inl aβ‚‚) = βˆ… := rfl @[simp] theorem Ico_inr_inl : Ico (inr b₁) (inl aβ‚‚) = βˆ… := rfl @[simp] theorem Ioc_inr_inl : Ioc (inr b₁) (inl aβ‚‚) = βˆ… := rfl @[simp] theorem Ioo_inr_inl : Ioo (inr b₁) (inl aβ‚‚) = βˆ… := rfl theorem Icc_inr_inr : Icc (inr b₁ : Ξ± βŠ• Ξ²) (inr bβ‚‚) = (Icc b₁ bβ‚‚).map Embedding.inr := rfl theorem Ico_inr_inr : Ico (inr b₁ : Ξ± βŠ• Ξ²) (inr bβ‚‚) = (Ico b₁ bβ‚‚).map Embedding.inr := rfl theorem Ioc_inr_inr : Ioc (inr b₁ : Ξ± βŠ• Ξ²) (inr bβ‚‚) = (Ioc b₁ bβ‚‚).map Embedding.inr := rfl theorem Ioo_inr_inr : Ioo (inr b₁ : Ξ± βŠ• Ξ²) (inr bβ‚‚) = (Ioo b₁ bβ‚‚).map Embedding.inr := rfl end LocallyFiniteOrder section LocallyFiniteOrderBot variable [Preorder Ξ±] [Preorder Ξ²] [LocallyFiniteOrderBot Ξ±] [LocallyFiniteOrderBot Ξ²] instance : LocallyFiniteOrderBot (Ξ± βŠ• Ξ²) where finsetIic := Sum.elim (Iic Β· |>.map .inl) (Iic Β· |>.map .inr) finsetIio := Sum.elim (Iio Β· |>.map .inl) (Iio Β· |>.map .inr) finset_mem_Iic := by simp finset_mem_Iio := by simp variable (a : Ξ±) (b : Ξ²) theorem Iic_inl : Iic (inl a : Ξ± βŠ• Ξ²) = (Iic a).map Embedding.inl := rfl theorem Iic_inr : Iic (inr b : Ξ± βŠ• Ξ²) = (Iic b).map Embedding.inr := rfl theorem Iio_inl : Iio (inl a : Ξ± βŠ• Ξ²) = (Iio a).map Embedding.inl := rfl theorem Iio_inr : Iio (inr b : Ξ± βŠ• Ξ²) = (Iio b).map Embedding.inr := rfl end LocallyFiniteOrderBot section LocallyFiniteOrderTop variable [Preorder Ξ±] [Preorder Ξ²] [LocallyFiniteOrderTop Ξ±] [LocallyFiniteOrderTop Ξ²] instance : LocallyFiniteOrderTop (Ξ± βŠ• Ξ²) where finsetIci := Sum.elim (Ici Β· |>.map .inl) (Ici Β· |>.map .inr) finsetIoi := Sum.elim (Ioi Β· |>.map .inl) (Ioi Β· |>.map .inr) finset_mem_Ici := by simp finset_mem_Ioi := by simp variable (a : Ξ±) (b : Ξ²) theorem Ici_inl : Ici (inl a : Ξ± βŠ• Ξ²) = (Ici a).map Embedding.inl := rfl theorem Ici_inr : Ici (inr b : Ξ± βŠ• Ξ²) = (Ici b).map Embedding.inr := rfl theorem Ioi_inl : Ioi (inl a : Ξ± βŠ• Ξ²) = (Ioi a).map Embedding.inl := rfl theorem Ioi_inr : Ioi (inr b : Ξ± βŠ• Ξ²) = (Ioi b).map Embedding.inr := rfl end LocallyFiniteOrderTop end Disjoint /-! ### Lexicographical sum of orders -/ namespace Lex section LocallyFiniteOrder variable [Preorder Ξ±] [Preorder Ξ²] [LocallyFiniteOrder Ξ±] [LocallyFiniteOrder Ξ²] variable [LocallyFiniteOrderTop Ξ±] [LocallyFiniteOrderBot Ξ²] instance locallyFiniteOrder : LocallyFiniteOrder (Ξ± βŠ•β‚— Ξ²) where finsetIcc a b := (sumLexLift Icc Icc (fun a _ => Ici a) (fun _ => Iic) (ofLex a) (ofLex b)).map toLex.toEmbedding finsetIco a b := (sumLexLift Ico Ico (fun a _ => Ici a) (fun _ => Iio) (ofLex a) (ofLex b)).map toLex.toEmbedding finsetIoc a b := (sumLexLift Ioc Ioc (fun a _ => Ioi a) (fun _ => Iic) (ofLex a) (ofLex b)).map toLex.toEmbedding finsetIoo a b := (sumLexLift Ioo Ioo (fun a _ => Ioi a) (fun _ => Iio) (ofLex a) (ofLex b)).map toLex.toEmbedding finset_mem_Icc := by simp finset_mem_Ico := by simp finset_mem_Ioc := by simp finset_mem_Ioo := by simp variable (a a₁ aβ‚‚ : Ξ±) (b b₁ bβ‚‚ : Ξ²) lemma Icc_inl_inl : Icc (inlβ‚— a₁ : Ξ± βŠ•β‚— Ξ²) (inlβ‚— aβ‚‚) = (Icc a₁ aβ‚‚).map (Embedding.inl.trans toLex.toEmbedding) := by rw [← Finset.map_map]; rfl lemma Ico_inl_inl : Ico (inlβ‚— a₁ : Ξ± βŠ•β‚— Ξ²) (inlβ‚— aβ‚‚) = (Ico a₁ aβ‚‚).map (Embedding.inl.trans toLex.toEmbedding) := by rw [← Finset.map_map]; rfl lemma Ioc_inl_inl : Ioc (inlβ‚— a₁ : Ξ± βŠ•β‚— Ξ²) (inlβ‚— aβ‚‚) = (Ioc a₁ aβ‚‚).map (Embedding.inl.trans toLex.toEmbedding) := by rw [← Finset.map_map]; rfl lemma Ioo_inl_inl : Ioo (inlβ‚— a₁ : Ξ± βŠ•β‚— Ξ²) (inlβ‚— aβ‚‚) = (Ioo a₁ aβ‚‚).map (Embedding.inl.trans toLex.toEmbedding) := by rw [← Finset.map_map]; rfl @[simp] lemma Icc_inl_inr : Icc (inlβ‚— a) (inrβ‚— b) = ((Ici a).disjSum (Iic b)).map toLex.toEmbedding := rfl @[simp] lemma Ico_inl_inr : Ico (inlβ‚— a) (inrβ‚— b) = ((Ici a).disjSum (Iio b)).map toLex.toEmbedding := rfl @[simp] lemma Ioc_inl_inr : Ioc (inlβ‚— a) (inrβ‚— b) = ((Ioi a).disjSum (Iic b)).map toLex.toEmbedding := rfl @[simp] lemma Ioo_inl_inr : Ioo (inlβ‚— a) (inrβ‚— b) = ((Ioi a).disjSum (Iio b)).map toLex.toEmbedding := rfl @[simp] lemma Icc_inr_inl : Icc (inrβ‚— b) (inlβ‚— a) = βˆ… := rfl @[simp] lemma Ico_inr_inl : Ico (inrβ‚— b) (inlβ‚— a) = βˆ… := rfl @[simp] lemma Ioc_inr_inl : Ioc (inrβ‚— b) (inlβ‚— a) = βˆ… := rfl @[simp] lemma Ioo_inr_inl : Ioo (inrβ‚— b) (inlβ‚— a) = βˆ… := rfl lemma Icc_inr_inr : Icc (inrβ‚— b₁ : Ξ± βŠ•β‚— Ξ²) (inrβ‚— bβ‚‚) = (Icc b₁ bβ‚‚).map (Embedding.inr.trans toLex.toEmbedding) := by rw [← Finset.map_map]; rfl lemma Ico_inr_inr : Ico (inrβ‚— b₁ : Ξ± βŠ•β‚— Ξ²) (inrβ‚— bβ‚‚) = (Ico b₁ bβ‚‚).map (Embedding.inr.trans toLex.toEmbedding) := by rw [← Finset.map_map]; rfl lemma Ioc_inr_inr : Ioc (inrβ‚— b₁ : Ξ± βŠ•β‚— Ξ²) (inrβ‚— bβ‚‚) = (Ioc b₁ bβ‚‚).map (Embedding.inr.trans toLex.toEmbedding) := by rw [← Finset.map_map]; rfl lemma Ioo_inr_inr : Ioo (inrβ‚— b₁ : Ξ± βŠ•β‚— Ξ²) (inrβ‚— bβ‚‚) = (Ioo b₁ bβ‚‚).map (Embedding.inr.trans toLex.toEmbedding) := by rw [← Finset.map_map]; rfl end LocallyFiniteOrder section LocallyFiniteOrderBot variable [Preorder Ξ±] [Preorder Ξ²] [Fintype Ξ±] [LocallyFiniteOrderBot Ξ±] [LocallyFiniteOrderBot Ξ²] instance instLocallyFiniteOrderBot : LocallyFiniteOrderBot (Ξ± βŠ•β‚— Ξ²) where finsetIic := Sum.elim (Iic Β· |>.map (.trans .inl toLex.toEmbedding)) (fun x => Finset.univ.disjSum (Iic x) |>.map toLex.toEmbedding) ∘ ofLex finsetIio := Sum.elim (Iio Β· |>.map (.trans .inl toLex.toEmbedding)) (fun x => Finset.univ.disjSum (Iio x) |>.map toLex.toEmbedding) ∘ ofLex finset_mem_Iic := by simp finset_mem_Iio := by simp variable (a : Ξ±) (b : Ξ²) lemma Iic_inl : Iic (inlβ‚— a : Ξ± βŠ•β‚— Ξ²) = (Iic a).map (Embedding.inl.trans toLex.toEmbedding) := rfl lemma Iic_inr : Iic (inrβ‚— b : Ξ± βŠ•β‚— Ξ²) = (Finset.univ.disjSum (Iic b)).map toLex.toEmbedding := rfl lemma Iio_inl : Iio (inlβ‚— a : Ξ± βŠ•β‚— Ξ²) = (Iio a).map (Embedding.inl.trans toLex.toEmbedding) := rfl lemma Iio_inr : Iio (inrβ‚— b : Ξ± βŠ•β‚— Ξ²) = (Finset.univ.disjSum (Iio b)).map toLex.toEmbedding := rfl end LocallyFiniteOrderBot /-- TODO: `LocallyFiniteOrder.toLocallyFiniteOrderBot` is probably a bad instance, as it forms a diamond with this instance, and constructs data from data. We should consider removing it. -/ example [Fintype Ξ±] [Preorder Ξ±] [Preorder Ξ²] [OrderBot Ξ±] [OrderBot Ξ²] [OrderTop Ξ±] [LocallyFiniteOrder Ξ±] [LocallyFiniteOrder Ξ²] : LocallyFiniteOrder.toLocallyFiniteOrderBot = instLocallyFiniteOrderBot (Ξ± := Ξ±) (Ξ² := Ξ²) := by try with_reducible_and_instances rfl -- fails try rfl -- fails exact Subsingleton.elim _ _ section LocallyFiniteOrderTop variable [Preorder Ξ±] [Preorder Ξ²] [LocallyFiniteOrderTop Ξ±] [Fintype Ξ²] [LocallyFiniteOrderTop Ξ²] instance instLocallyFiniteOrderTop : LocallyFiniteOrderTop (Ξ± βŠ•β‚— Ξ²) where finsetIci := Sum.elim (fun x => (Ici x).disjSum Finset.univ |>.map toLex.toEmbedding) (Ici Β· |>.map (.trans .inr toLex.toEmbedding)) ∘ ofLex finsetIoi := Sum.elim (fun x => (Ioi x).disjSum Finset.univ |>.map toLex.toEmbedding) (Ioi Β· |>.map (.trans .inr toLex.toEmbedding)) ∘ ofLex finset_mem_Ici := by simp finset_mem_Ioi := by simp variable (a : Ξ±) (b : Ξ²) lemma Ici_inl : Ici (inlβ‚— a : Ξ± βŠ•β‚— Ξ²) = ((Ici a).disjSum Finset.univ).map toLex.toEmbedding := rfl lemma Ici_inr : Ici (inrβ‚— b : Ξ± βŠ•β‚— Ξ²) = (Ici b).map (Embedding.inr.trans toLex.toEmbedding) := rfl lemma Ioi_inl : Ioi (inlβ‚— a : Ξ± βŠ•β‚— Ξ²) = ((Ioi a).disjSum Finset.univ).map toLex.toEmbedding := rfl lemma Ioi_inr : Ioi (inrβ‚— b : Ξ± βŠ•β‚— Ξ²) = (Ioi b).map (Embedding.inr.trans toLex.toEmbedding) := rfl end LocallyFiniteOrderTop end Lex end Sum
.lake/packages/mathlib/Mathlib/Data/Sum/Order.lean
import Mathlib.Order.Heyting.Basic import Mathlib.Order.Hom.Basic import Mathlib.Order.WithBot /-! # Orders on a sum type This file defines the disjoint sum and the linear (aka lexicographic) sum of two orders and provides relation instances for `Sum.LiftRel` and `Sum.Lex`. We declare the disjoint sum of orders as the default set of instances. The linear order goes on a type synonym. ## Main declarations * `Sum.LE`, `Sum.LT`: Disjoint sum of orders. * `Sum.Lex.LE`, `Sum.Lex.LT`: Lexicographic/linear sum of orders. ## Notation * `Ξ± βŠ•β‚— Ξ²`: The linear sum of `Ξ±` and `Ξ²`. -/ variable {Ξ± Ξ² Ξ³ : Type*} namespace Sum /-! ### Unbundled relation classes -/ section LiftRel variable (r : Ξ± β†’ Ξ± β†’ Prop) (s : Ξ² β†’ Ξ² β†’ Prop) @[refl] theorem LiftRel.refl [IsRefl Ξ± r] [IsRefl Ξ² s] : βˆ€ x, LiftRel r s x x | inl a => LiftRel.inl (_root_.refl a) | inr a => LiftRel.inr (_root_.refl a) instance [IsRefl Ξ± r] [IsRefl Ξ² s] : IsRefl (Ξ± βŠ• Ξ²) (LiftRel r s) := ⟨LiftRel.refl _ _⟩ instance [IsIrrefl Ξ± r] [IsIrrefl Ξ² s] : IsIrrefl (Ξ± βŠ• Ξ²) (LiftRel r s) := ⟨by rintro _ (⟨h⟩ | ⟨h⟩) <;> exact irrefl _ h⟩ @[trans] theorem LiftRel.trans [IsTrans Ξ± r] [IsTrans Ξ² s] : βˆ€ {a b c}, LiftRel r s a b β†’ LiftRel r s b c β†’ LiftRel r s a c | _, _, _, LiftRel.inl hab, LiftRel.inl hbc => LiftRel.inl <| _root_.trans hab hbc | _, _, _, LiftRel.inr hab, LiftRel.inr hbc => LiftRel.inr <| _root_.trans hab hbc instance [IsTrans Ξ± r] [IsTrans Ξ² s] : IsTrans (Ξ± βŠ• Ξ²) (LiftRel r s) := ⟨fun _ _ _ => LiftRel.trans _ _⟩ instance [IsAntisymm Ξ± r] [IsAntisymm Ξ² s] : IsAntisymm (Ξ± βŠ• Ξ²) (LiftRel r s) := ⟨by rintro _ _ (⟨hab⟩ | ⟨hab⟩) (⟨hba⟩ | ⟨hba⟩) <;> rw [antisymm hab hba]⟩ end LiftRel section Lex variable (r : Ξ± β†’ Ξ± β†’ Prop) (s : Ξ² β†’ Ξ² β†’ Prop) instance [IsRefl Ξ± r] [IsRefl Ξ² s] : IsRefl (Ξ± βŠ• Ξ²) (Lex r s) := ⟨by rintro (a | a) exacts [Lex.inl (refl _), Lex.inr (refl _)]⟩ instance [IsIrrefl Ξ± r] [IsIrrefl Ξ² s] : IsIrrefl (Ξ± βŠ• Ξ²) (Lex r s) := ⟨by rintro _ (⟨h⟩ | ⟨h⟩) <;> exact irrefl _ h⟩ instance [IsTrans Ξ± r] [IsTrans Ξ² s] : IsTrans (Ξ± βŠ• Ξ²) (Lex r s) := ⟨by rintro _ _ _ (⟨hab⟩ | ⟨hab⟩) (⟨hbc⟩ | ⟨hbc⟩) exacts [.inl (_root_.trans hab hbc), .sep _ _, .inr (_root_.trans hab hbc), .sep _ _]⟩ instance [IsAntisymm Ξ± r] [IsAntisymm Ξ² s] : IsAntisymm (Ξ± βŠ• Ξ²) (Lex r s) := ⟨by rintro _ _ (⟨hab⟩ | ⟨hab⟩) (⟨hba⟩ | ⟨hba⟩) <;> rw [antisymm hab hba]⟩ instance [IsTotal Ξ± r] [IsTotal Ξ² s] : IsTotal (Ξ± βŠ• Ξ²) (Lex r s) := ⟨fun a b => match a, b with | inl a, inl b => (total_of r a b).imp Lex.inl Lex.inl | inl _, inr _ => Or.inl (Lex.sep _ _) | inr _, inl _ => Or.inr (Lex.sep _ _) | inr a, inr b => (total_of s a b).imp Lex.inr Lex.inr⟩ instance [IsTrichotomous Ξ± r] [IsTrichotomous Ξ² s] : IsTrichotomous (Ξ± βŠ• Ξ²) (Lex r s) := ⟨fun a b => match a, b with | inl a, inl b => (trichotomous_of r a b).imp3 Lex.inl (congr_arg _) Lex.inl | inl _, inr _ => Or.inl (Lex.sep _ _) | inr _, inl _ => Or.inr (Or.inr <| Lex.sep _ _) | inr a, inr b => (trichotomous_of s a b).imp3 Lex.inr (congr_arg _) Lex.inr⟩ instance [IsWellOrder Ξ± r] [IsWellOrder Ξ² s] : IsWellOrder (Ξ± βŠ• Ξ²) (Sum.Lex r s) where wf := Sum.lex_wf IsWellFounded.wf IsWellFounded.wf end Lex /-! ### Disjoint sum of two orders -/ section Disjoint instance instLESum [LE Ξ±] [LE Ξ²] : LE (Ξ± βŠ• Ξ²) := ⟨LiftRel (Β· ≀ Β·) (Β· ≀ Β·)⟩ instance instLTSum [LT Ξ±] [LT Ξ²] : LT (Ξ± βŠ• Ξ²) := ⟨LiftRel (Β· < Β·) (Β· < Β·)⟩ theorem le_def [LE Ξ±] [LE Ξ²] {a b : Ξ± βŠ• Ξ²} : a ≀ b ↔ LiftRel (Β· ≀ Β·) (Β· ≀ Β·) a b := Iff.rfl theorem lt_def [LT Ξ±] [LT Ξ²] {a b : Ξ± βŠ• Ξ²} : a < b ↔ LiftRel (Β· < Β·) (Β· < Β·) a b := Iff.rfl @[simp] theorem inl_le_inl_iff [LE Ξ±] [LE Ξ²] {a b : Ξ±} : (inl a : Ξ± βŠ• Ξ²) ≀ inl b ↔ a ≀ b := liftRel_inl_inl @[simp] theorem inr_le_inr_iff [LE Ξ±] [LE Ξ²] {a b : Ξ²} : (inr a : Ξ± βŠ• Ξ²) ≀ inr b ↔ a ≀ b := liftRel_inr_inr @[simp] theorem inl_lt_inl_iff [LT Ξ±] [LT Ξ²] {a b : Ξ±} : (inl a : Ξ± βŠ• Ξ²) < inl b ↔ a < b := liftRel_inl_inl @[simp] theorem inr_lt_inr_iff [LT Ξ±] [LT Ξ²] {a b : Ξ²} : (inr a : Ξ± βŠ• Ξ²) < inr b ↔ a < b := liftRel_inr_inr @[simp] theorem not_inl_le_inr [LE Ξ±] [LE Ξ²] {a : Ξ±} {b : Ξ²} : Β¬inl b ≀ inr a := not_liftRel_inl_inr @[simp] theorem not_inl_lt_inr [LT Ξ±] [LT Ξ²] {a : Ξ±} {b : Ξ²} : Β¬inl b < inr a := not_liftRel_inl_inr @[simp] theorem not_inr_le_inl [LE Ξ±] [LE Ξ²] {a : Ξ±} {b : Ξ²} : Β¬inr b ≀ inl a := not_liftRel_inr_inl @[simp] theorem not_inr_lt_inl [LT Ξ±] [LT Ξ²] {a : Ξ±} {b : Ξ²} : Β¬inr b < inl a := not_liftRel_inr_inl section Preorder variable [Preorder Ξ±] [Preorder Ξ²] instance instPreorderSum : Preorder (Ξ± βŠ• Ξ²) := { instLESum, instLTSum with le_refl := fun _ => LiftRel.refl _ _ _, le_trans := fun _ _ _ => LiftRel.trans _ _, lt_iff_le_not_ge := fun a b => by refine ⟨fun hab => ⟨hab.mono (fun _ _ => le_of_lt) fun _ _ => le_of_lt, ?_⟩, ?_⟩ Β· rintro (⟨hba⟩ | ⟨hba⟩) Β· exact hba.not_gt (inl_lt_inl_iff.1 hab) Β· exact hba.not_gt (inr_lt_inr_iff.1 hab) Β· rintro ⟨⟨hab⟩ | ⟨hab⟩, hba⟩ Β· exact LiftRel.inl (hab.lt_of_not_ge fun h => hba <| LiftRel.inl h) Β· exact LiftRel.inr (hab.lt_of_not_ge fun h => hba <| LiftRel.inr h) } theorem inl_mono : Monotone (inl : Ξ± β†’ Ξ± βŠ• Ξ²) := fun _ _ => LiftRel.inl theorem inr_mono : Monotone (inr : Ξ² β†’ Ξ± βŠ• Ξ²) := fun _ _ => LiftRel.inr theorem inl_strictMono : StrictMono (inl : Ξ± β†’ Ξ± βŠ• Ξ²) := fun _ _ => LiftRel.inl theorem inr_strictMono : StrictMono (inr : Ξ² β†’ Ξ± βŠ• Ξ²) := fun _ _ => LiftRel.inr end Preorder instance [PartialOrder Ξ±] [PartialOrder Ξ²] : PartialOrder (Ξ± βŠ• Ξ²) := { instPreorderSum with le_antisymm := fun _ _ => show LiftRel _ _ _ _ β†’ _ from antisymm } instance noMinOrder [LT Ξ±] [LT Ξ²] [NoMinOrder Ξ±] [NoMinOrder Ξ²] : NoMinOrder (Ξ± βŠ• Ξ²) := ⟨fun a => match a with | inl a => let ⟨b, h⟩ := exists_lt a ⟨inl b, inl_lt_inl_iff.2 h⟩ | inr a => let ⟨b, h⟩ := exists_lt a ⟨inr b, inr_lt_inr_iff.2 h⟩⟩ instance noMaxOrder [LT Ξ±] [LT Ξ²] [NoMaxOrder Ξ±] [NoMaxOrder Ξ²] : NoMaxOrder (Ξ± βŠ• Ξ²) := ⟨fun a => match a with | inl a => let ⟨b, h⟩ := exists_gt a ⟨inl b, inl_lt_inl_iff.2 h⟩ | inr a => let ⟨b, h⟩ := exists_gt a ⟨inr b, inr_lt_inr_iff.2 h⟩⟩ @[simp] theorem noMinOrder_iff [LT Ξ±] [LT Ξ²] : NoMinOrder (Ξ± βŠ• Ξ²) ↔ NoMinOrder Ξ± ∧ NoMinOrder Ξ² := ⟨fun _ => ⟨⟨fun a => by obtain ⟨b | b, h⟩ := exists_lt (inl a : Ξ± βŠ• Ξ²) Β· exact ⟨b, inl_lt_inl_iff.1 h⟩ Β· exact (not_inr_lt_inl h).elim⟩, ⟨fun a => by obtain ⟨b | b, h⟩ := exists_lt (inr a : Ξ± βŠ• Ξ²) Β· exact (not_inl_lt_inr h).elim Β· exact ⟨b, inr_lt_inr_iff.1 h⟩⟩⟩, fun h => @Sum.noMinOrder _ _ _ _ h.1 h.2⟩ @[simp] theorem noMaxOrder_iff [LT Ξ±] [LT Ξ²] : NoMaxOrder (Ξ± βŠ• Ξ²) ↔ NoMaxOrder Ξ± ∧ NoMaxOrder Ξ² := ⟨fun _ => ⟨⟨fun a => by obtain ⟨b | b, h⟩ := exists_gt (inl a : Ξ± βŠ• Ξ²) Β· exact ⟨b, inl_lt_inl_iff.1 h⟩ Β· exact (not_inl_lt_inr h).elim⟩, ⟨fun a => by obtain ⟨b | b, h⟩ := exists_gt (inr a : Ξ± βŠ• Ξ²) Β· exact (not_inr_lt_inl h).elim Β· exact ⟨b, inr_lt_inr_iff.1 h⟩⟩⟩, fun h => @Sum.noMaxOrder _ _ _ _ h.1 h.2⟩ instance denselyOrdered [LT Ξ±] [LT Ξ²] [DenselyOrdered Ξ±] [DenselyOrdered Ξ²] : DenselyOrdered (Ξ± βŠ• Ξ²) := ⟨fun a b h => match a, b, h with | inl _, inl _, LiftRel.inl h => let ⟨c, ha, hb⟩ := exists_between h ⟨toLex (inl c), LiftRel.inl ha, LiftRel.inl hb⟩ | inr _, inr _, LiftRel.inr h => let ⟨c, ha, hb⟩ := exists_between h ⟨toLex (inr c), LiftRel.inr ha, LiftRel.inr hb⟩⟩ @[simp] theorem denselyOrdered_iff [LT Ξ±] [LT Ξ²] : DenselyOrdered (Ξ± βŠ• Ξ²) ↔ DenselyOrdered Ξ± ∧ DenselyOrdered Ξ² := ⟨fun _ => ⟨⟨fun a b h => by obtain ⟨c | c, ha, hb⟩ := @exists_between (Ξ± βŠ• Ξ²) _ _ _ _ (inl_lt_inl_iff.2 h) Β· exact ⟨c, inl_lt_inl_iff.1 ha, inl_lt_inl_iff.1 hb⟩ Β· exact (not_inl_lt_inr ha).elim⟩, ⟨fun a b h => by obtain ⟨c | c, ha, hb⟩ := @exists_between (Ξ± βŠ• Ξ²) _ _ _ _ (inr_lt_inr_iff.2 h) Β· exact (not_inl_lt_inr hb).elim Β· exact ⟨c, inr_lt_inr_iff.1 ha, inr_lt_inr_iff.1 hb⟩⟩⟩, fun h => @Sum.denselyOrdered _ _ _ _ h.1 h.2⟩ @[simp] theorem swap_le_swap_iff [LE Ξ±] [LE Ξ²] {a b : Ξ± βŠ• Ξ²} : a.swap ≀ b.swap ↔ a ≀ b := liftRel_swap_iff @[simp] theorem swap_lt_swap_iff [LT Ξ±] [LT Ξ²] {a b : Ξ± βŠ• Ξ²} : a.swap < b.swap ↔ a < b := liftRel_swap_iff end Disjoint /-! ### Linear sum of two orders -/ namespace Lex /-- The linear sum of two orders -/ notation:30 Ξ± " βŠ•β‚— " Ξ²:29 => _root_.Lex (Ξ± βŠ• Ξ²) --TODO: Can we make `inlβ‚—`, `inrβ‚—` `local notation`? /-- Lexicographical `Sum.inl`. Only used for pattern matching. -/ @[match_pattern] abbrev _root_.Sum.inlβ‚— (x : Ξ±) : Ξ± βŠ•β‚— Ξ² := toLex (Sum.inl x) /-- Lexicographical `Sum.inr`. Only used for pattern matching. -/ @[match_pattern] abbrev _root_.Sum.inrβ‚— (x : Ξ²) : Ξ± βŠ•β‚— Ξ² := toLex (Sum.inr x) /-- The linear/lexicographical `≀` on a sum. -/ protected instance LE [LE Ξ±] [LE Ξ²] : LE (Ξ± βŠ•β‚— Ξ²) := ⟨Lex (Β· ≀ Β·) (Β· ≀ Β·)⟩ /-- The linear/lexicographical `<` on a sum. -/ protected instance LT [LT Ξ±] [LT Ξ²] : LT (Ξ± βŠ•β‚— Ξ²) := ⟨Lex (Β· < Β·) (Β· < Β·)⟩ @[simp] theorem toLex_le_toLex [LE Ξ±] [LE Ξ²] {a b : Ξ± βŠ• Ξ²} : toLex a ≀ toLex b ↔ Lex (Β· ≀ Β·) (Β· ≀ Β·) a b := Iff.rfl @[simp] theorem toLex_lt_toLex [LT Ξ±] [LT Ξ²] {a b : Ξ± βŠ• Ξ²} : toLex a < toLex b ↔ Lex (Β· < Β·) (Β· < Β·) a b := Iff.rfl theorem le_def [LE Ξ±] [LE Ξ²] {a b : Ξ± βŠ•β‚— Ξ²} : a ≀ b ↔ Lex (Β· ≀ Β·) (Β· ≀ Β·) (ofLex a) (ofLex b) := Iff.rfl theorem lt_def [LT Ξ±] [LT Ξ²] {a b : Ξ± βŠ•β‚— Ξ²} : a < b ↔ Lex (Β· < Β·) (Β· < Β·) (ofLex a) (ofLex b) := Iff.rfl theorem inl_le_inl_iff [LE Ξ±] [LE Ξ²] {a b : Ξ±} : toLex (inl a : Ξ± βŠ• Ξ²) ≀ toLex (inl b) ↔ a ≀ b := lex_inl_inl theorem inr_le_inr_iff [LE Ξ±] [LE Ξ²] {a b : Ξ²} : toLex (inr a : Ξ± βŠ• Ξ²) ≀ toLex (inr b) ↔ a ≀ b := lex_inr_inr theorem inl_lt_inl_iff [LT Ξ±] [LT Ξ²] {a b : Ξ±} : toLex (inl a : Ξ± βŠ• Ξ²) < toLex (inl b) ↔ a < b := lex_inl_inl theorem inr_lt_inr_iff [LT Ξ±] [LT Ξ²] {a b : Ξ²} : toLex (inr a : Ξ± βŠ•β‚— Ξ²) < toLex (inr b) ↔ a < b := lex_inr_inr theorem inl_le_inr [LE Ξ±] [LE Ξ²] (a : Ξ±) (b : Ξ²) : toLex (inl a) ≀ toLex (inr b) := Lex.sep _ _ theorem inl_lt_inr [LT Ξ±] [LT Ξ²] (a : Ξ±) (b : Ξ²) : toLex (inl a) < toLex (inr b) := Lex.sep _ _ theorem not_inr_le_inl [LE Ξ±] [LE Ξ²] {a : Ξ±} {b : Ξ²} : Β¬toLex (inr b) ≀ toLex (inl a) := lex_inr_inl theorem not_inr_lt_inl [LT Ξ±] [LT Ξ²] {a : Ξ±} {b : Ξ²} : Β¬toLex (inr b) < toLex (inl a) := lex_inr_inl /-- `toLex` promoted to a `RelIso` between `<` relations. -/ def toLexRelIsoLT [LT Ξ±] [LT Ξ²] : Sum.Lex (Β· < Β· : Ξ± β†’ Ξ± β†’ Prop) (Β· < Β· : Ξ² β†’ Ξ² β†’ Prop) ≃r (Β· < Β· : Ξ± βŠ•β‚— Ξ² β†’ _ β†’ _) where toFun := toLex invFun := ofLex map_rel_iff' := .rfl @[simp] theorem toLexRelIsoLT_coe [LT Ξ±] [LT Ξ²] : ⇑(toLexRelIsoLT (Ξ± := Ξ±) (Ξ² := Ξ²)) = toLex := rfl @[simp] theorem toLexRelIsoLT_symm_coe [LT Ξ±] [LT Ξ²] : ⇑(toLexRelIsoLT (Ξ± := Ξ±) (Ξ² := Ξ²)).symm = ofLex := rfl /-- `toLex` promoted to a `RelIso` between `≀` relations. -/ def toLexRelIsoLE [LE Ξ±] [LE Ξ²] : Sum.Lex (Β· ≀ Β· : Ξ± β†’ Ξ± β†’ Prop) (Β· ≀ Β· : Ξ² β†’ Ξ² β†’ Prop) ≃r (Β· ≀ Β· : Ξ± βŠ•β‚— Ξ² β†’ _ β†’ _) where toFun := toLex invFun := ofLex map_rel_iff' := .rfl @[simp] theorem toLexRelIsoLE_coe [LE Ξ±] [LE Ξ²] : ⇑(toLexRelIsoLE (Ξ± := Ξ±) (Ξ² := Ξ²)) = toLex := rfl @[simp] theorem toLexRelIsoLE_symm_coe [LE Ξ±] [LE Ξ²] : ⇑(toLexRelIsoLE (Ξ± := Ξ±) (Ξ² := Ξ²)).symm = ofLex := rfl section Preorder variable [Preorder Ξ±] [Preorder Ξ²] instance preorder : Preorder (Ξ± βŠ•β‚— Ξ²) := { Lex.LE, Lex.LT with le_refl := refl_of (Lex (Β· ≀ Β·) (Β· ≀ Β·)), le_trans := fun _ _ _ => trans_of (Lex (Β· ≀ Β·) (Β· ≀ Β·)), lt_iff_le_not_ge := fun a b => by refine ⟨fun hab => ⟨hab.mono (fun _ _ => le_of_lt) fun _ _ => le_of_lt, ?_⟩, ?_⟩ Β· rintro (⟨hba⟩ | ⟨hba⟩ | ⟨b, a⟩) Β· exact hba.not_gt (inl_lt_inl_iff.1 hab) Β· exact hba.not_gt (inr_lt_inr_iff.1 hab) Β· exact not_inr_lt_inl hab Β· rintro ⟨⟨hab⟩ | ⟨hab⟩ | ⟨a, b⟩, hba⟩ Β· exact Lex.inl (hab.lt_of_not_ge fun h => hba <| Lex.inl h) Β· exact Lex.inr (hab.lt_of_not_ge fun h => hba <| Lex.inr h) Β· exact Lex.sep _ _ } theorem toLex_mono : Monotone (@toLex (Ξ± βŠ• Ξ²)) := fun _ _ h => h.lex theorem toLex_strictMono : StrictMono (@toLex (Ξ± βŠ• Ξ²)) := fun _ _ h => h.lex theorem inl_mono : Monotone (toLex ∘ inl : Ξ± β†’ Ξ± βŠ•β‚— Ξ²) := toLex_mono.comp Sum.inl_mono theorem inr_mono : Monotone (toLex ∘ inr : Ξ² β†’ Ξ± βŠ•β‚— Ξ²) := toLex_mono.comp Sum.inr_mono theorem inl_strictMono : StrictMono (toLex ∘ inl : Ξ± β†’ Ξ± βŠ•β‚— Ξ²) := toLex_strictMono.comp Sum.inl_strictMono theorem inr_strictMono : StrictMono (toLex ∘ inr : Ξ² β†’ Ξ± βŠ•β‚— Ξ²) := toLex_strictMono.comp Sum.inr_strictMono end Preorder instance partialOrder [PartialOrder Ξ±] [PartialOrder Ξ²] : PartialOrder (Ξ± βŠ•β‚— Ξ²) := { Lex.preorder with le_antisymm := fun _ _ => antisymm_of (Lex (Β· ≀ Β·) (Β· ≀ Β·)) } instance linearOrder [LinearOrder Ξ±] [LinearOrder Ξ²] : LinearOrder (Ξ± βŠ•β‚— Ξ²) := { Lex.partialOrder with le_total := total_of (Lex (Β· ≀ Β·) (Β· ≀ Β·)), toDecidableLE := instDecidableRelSumLex, toDecidableLT := instDecidableRelSumLex, toDecidableEq := instDecidableEqSum } /-- The lexicographical bottom of a sum is the bottom of the left component. -/ instance orderBot [LE Ξ±] [OrderBot Ξ±] [LE Ξ²] : OrderBot (Ξ± βŠ•β‚— Ξ²) where bot := inl βŠ₯ bot_le := by rintro (a | b) Β· exact Lex.inl bot_le Β· exact Lex.sep _ _ @[simp] theorem inl_bot [LE Ξ±] [OrderBot Ξ±] [LE Ξ²] : toLex (inl βŠ₯ : Ξ± βŠ• Ξ²) = βŠ₯ := rfl /-- The lexicographical top of a sum is the top of the right component. -/ instance orderTop [LE Ξ±] [LE Ξ²] [OrderTop Ξ²] : OrderTop (Ξ± βŠ•β‚— Ξ²) where top := inr ⊀ le_top := by rintro (a | b) Β· exact Lex.sep _ _ Β· exact Lex.inr le_top @[simp] theorem inr_top [LE Ξ±] [LE Ξ²] [OrderTop Ξ²] : toLex (inr ⊀ : Ξ± βŠ• Ξ²) = ⊀ := rfl instance boundedOrder [LE Ξ±] [LE Ξ²] [OrderBot Ξ±] [OrderTop Ξ²] : BoundedOrder (Ξ± βŠ•β‚— Ξ²) := { Lex.orderBot, Lex.orderTop with } instance noMinOrder [LT Ξ±] [LT Ξ²] [NoMinOrder Ξ±] [NoMinOrder Ξ²] : NoMinOrder (Ξ± βŠ•β‚— Ξ²) := ⟨fun a => match a with | inl a => let ⟨b, h⟩ := exists_lt a ⟨toLex (inl b), inl_lt_inl_iff.2 h⟩ | inr a => let ⟨b, h⟩ := exists_lt a ⟨toLex (inr b), inr_lt_inr_iff.2 h⟩⟩ instance noMaxOrder [LT Ξ±] [LT Ξ²] [NoMaxOrder Ξ±] [NoMaxOrder Ξ²] : NoMaxOrder (Ξ± βŠ•β‚— Ξ²) := ⟨fun a => match a with | inl a => let ⟨b, h⟩ := exists_gt a ⟨toLex (inl b), inl_lt_inl_iff.2 h⟩ | inr a => let ⟨b, h⟩ := exists_gt a ⟨toLex (inr b), inr_lt_inr_iff.2 h⟩⟩ instance noMinOrder_of_nonempty [LT Ξ±] [LT Ξ²] [NoMinOrder Ξ±] [Nonempty Ξ±] : NoMinOrder (Ξ± βŠ•β‚— Ξ²) := ⟨fun a => match a with | inl a => let ⟨b, h⟩ := exists_lt a ⟨toLex (inl b), inl_lt_inl_iff.2 h⟩ | inr _ => ⟨toLex (inl <| Classical.arbitrary Ξ±), inl_lt_inr _ _⟩⟩ instance noMaxOrder_of_nonempty [LT Ξ±] [LT Ξ²] [NoMaxOrder Ξ²] [Nonempty Ξ²] : NoMaxOrder (Ξ± βŠ•β‚— Ξ²) := ⟨fun a => match a with | inl _ => ⟨toLex (inr <| Classical.arbitrary Ξ²), inl_lt_inr _ _⟩ | inr a => let ⟨b, h⟩ := exists_gt a ⟨toLex (inr b), inr_lt_inr_iff.2 h⟩⟩ instance denselyOrdered_of_noMaxOrder [LT Ξ±] [LT Ξ²] [DenselyOrdered Ξ±] [DenselyOrdered Ξ²] [NoMaxOrder Ξ±] : DenselyOrdered (Ξ± βŠ•β‚— Ξ²) := ⟨fun a b h => match a, b, h with | inl _, inl _, Lex.inl h => let ⟨c, ha, hb⟩ := exists_between h ⟨toLex (inl c), inl_lt_inl_iff.2 ha, inl_lt_inl_iff.2 hb⟩ | inl a, inr _, Lex.sep _ _ => let ⟨c, h⟩ := exists_gt a ⟨toLex (inl c), inl_lt_inl_iff.2 h, inl_lt_inr _ _⟩ | inr _, inr _, Lex.inr h => let ⟨c, ha, hb⟩ := exists_between h ⟨toLex (inr c), inr_lt_inr_iff.2 ha, inr_lt_inr_iff.2 hb⟩⟩ instance denselyOrdered_of_noMinOrder [LT Ξ±] [LT Ξ²] [DenselyOrdered Ξ±] [DenselyOrdered Ξ²] [NoMinOrder Ξ²] : DenselyOrdered (Ξ± βŠ•β‚— Ξ²) := ⟨fun a b h => match a, b, h with | inl _, inl _, Lex.inl h => let ⟨c, ha, hb⟩ := exists_between h ⟨toLex (inl c), inl_lt_inl_iff.2 ha, inl_lt_inl_iff.2 hb⟩ | inl _, inr b, Lex.sep _ _ => let ⟨c, h⟩ := exists_lt b ⟨toLex (inr c), inl_lt_inr _ _, inr_lt_inr_iff.2 h⟩ | inr _, inr _, Lex.inr h => let ⟨c, ha, hb⟩ := exists_between h ⟨toLex (inr c), inr_lt_inr_iff.2 ha, inr_lt_inr_iff.2 hb⟩⟩ end Lex end Sum /-! ### Order isomorphisms -/ open OrderDual Sum namespace OrderIso variable {α₁ Ξ±β‚‚ β₁ Ξ²β‚‚ γ₁ Ξ³β‚‚ : Type*} [LE Ξ±] [LE Ξ²] [LE Ξ³] [LE α₁] [LE Ξ±β‚‚] [LE β₁] [LE Ξ²β‚‚] [LE γ₁] [LE Ξ³β‚‚] (a : Ξ±) (b : Ξ²) (c : Ξ³) /-- `Equiv.sumCongr` promoted to an order isomorphism. -/ @[simps! apply] def sumCongr (ea : α₁ ≃o Ξ±β‚‚) (eb : β₁ ≃o Ξ²β‚‚) : α₁ βŠ• β₁ ≃o Ξ±β‚‚ βŠ• Ξ²β‚‚ where toEquiv := .sumCongr ea eb map_rel_iff' := by aesop @[simp] theorem sumCongr_trans (e₁ : α₁ ≃o β₁) (eβ‚‚ : Ξ±β‚‚ ≃o Ξ²β‚‚) (f₁ : β₁ ≃o γ₁) (fβ‚‚ : Ξ²β‚‚ ≃o Ξ³β‚‚) : (e₁.sumCongr eβ‚‚).trans (f₁.sumCongr fβ‚‚) = (e₁.trans f₁).sumCongr (eβ‚‚.trans fβ‚‚) := by ext; simp @[simp] theorem sumCongr_symm (ea : α₁ ≃o Ξ±β‚‚) (eb : β₁ ≃o Ξ²β‚‚) : (ea.sumCongr eb).symm = ea.symm.sumCongr eb.symm := rfl @[simp] theorem sumCongr_refl : sumCongr (.refl Ξ±) (.refl Ξ²) = .refl _ := by ext; simp /-- `Equiv.sumComm` promoted to an order isomorphism. -/ @[simps! apply] def sumComm (Ξ± Ξ² : Type*) [LE Ξ±] [LE Ξ²] : Ξ± βŠ• Ξ² ≃o Ξ² βŠ• Ξ± := { Equiv.sumComm Ξ± Ξ² with map_rel_iff' := swap_le_swap_iff } @[simp] theorem sumComm_symm (Ξ± Ξ² : Type*) [LE Ξ±] [LE Ξ²] : (OrderIso.sumComm Ξ± Ξ²).symm = OrderIso.sumComm Ξ² Ξ± := rfl /-- `Equiv.sumAssoc` promoted to an order isomorphism. -/ def sumAssoc (Ξ± Ξ² Ξ³ : Type*) [LE Ξ±] [LE Ξ²] [LE Ξ³] : (Ξ± βŠ• Ξ²) βŠ• Ξ³ ≃o Ξ± βŠ• (Ξ² βŠ• Ξ³) := { Equiv.sumAssoc Ξ± Ξ² Ξ³ with map_rel_iff' := fun {a b} => by rcases a with ((_ | _) | _) <;> rcases b with ((_ | _) | _) <;> simp [Equiv.sumAssoc] } @[simp] theorem sumAssoc_apply_inl_inl : sumAssoc Ξ± Ξ² Ξ³ (inl (inl a)) = inl a := rfl @[simp] theorem sumAssoc_apply_inl_inr : sumAssoc Ξ± Ξ² Ξ³ (inl (inr b)) = inr (inl b) := rfl @[simp] theorem sumAssoc_apply_inr : sumAssoc Ξ± Ξ² Ξ³ (inr c) = inr (inr c) := rfl @[simp] theorem sumAssoc_symm_apply_inl : (sumAssoc Ξ± Ξ² Ξ³).symm (inl a) = inl (inl a) := rfl @[simp] theorem sumAssoc_symm_apply_inr_inl : (sumAssoc Ξ± Ξ² Ξ³).symm (inr (inl b)) = inl (inr b) := rfl @[simp] theorem sumAssoc_symm_apply_inr_inr : (sumAssoc Ξ± Ξ² Ξ³).symm (inr (inr c)) = inr c := rfl /-- `orderDual` is distributive over `βŠ•` up to an order isomorphism. -/ def sumDualDistrib (Ξ± Ξ² : Type*) [LE Ξ±] [LE Ξ²] : (Ξ± βŠ• Ξ²)α΅’α΅ˆ ≃o Ξ±α΅’α΅ˆ βŠ• Ξ²α΅’α΅ˆ := { Equiv.refl _ with map_rel_iff' := by rintro (a | a) (b | b) Β· change inl (toDual a) ≀ inl (toDual b) ↔ toDual (inl a) ≀ toDual (inl b) simp [toDual_le_toDual, inl_le_inl_iff] Β· exact iff_of_false (@not_inl_le_inr (OrderDual Ξ²) (OrderDual Ξ±) _ _ _ _) not_inr_le_inl Β· exact iff_of_false (@not_inr_le_inl (OrderDual Ξ±) (OrderDual Ξ²) _ _ _ _) not_inl_le_inr Β· change inr (toDual a) ≀ inr (toDual b) ↔ toDual (inr a) ≀ toDual (inr b) simp [toDual_le_toDual, inr_le_inr_iff] } @[simp] theorem sumDualDistrib_inl : sumDualDistrib Ξ± Ξ² (toDual (inl a)) = inl (toDual a) := rfl @[simp] theorem sumDualDistrib_inr : sumDualDistrib Ξ± Ξ² (toDual (inr b)) = inr (toDual b) := rfl @[simp] theorem sumDualDistrib_symm_inl : (sumDualDistrib Ξ± Ξ²).symm (inl (toDual a)) = toDual (inl a) := rfl @[simp] theorem sumDualDistrib_symm_inr : (sumDualDistrib Ξ± Ξ²).symm (inr (toDual b)) = toDual (inr b) := rfl /-- `Equiv.sumCongr` promoted to an order isomorphism between lexicographic sums. -/ @[simps! apply] def sumLexCongr (ea : α₁ ≃o Ξ±β‚‚) (eb : β₁ ≃o Ξ²β‚‚) : α₁ βŠ•β‚— β₁ ≃o Ξ±β‚‚ βŠ•β‚— Ξ²β‚‚ where toEquiv := ofLex.trans ((Equiv.sumCongr ea eb).trans toLex) map_rel_iff' := by simp_rw [Lex.forall]; rintro (a | a) (b | b) <;> simp @[simp] theorem sumLexCongr_trans (e₁ : α₁ ≃o β₁) (eβ‚‚ : Ξ±β‚‚ ≃o Ξ²β‚‚) (f₁ : β₁ ≃o γ₁) (fβ‚‚ : Ξ²β‚‚ ≃o Ξ³β‚‚) : (e₁.sumLexCongr eβ‚‚).trans (f₁.sumLexCongr fβ‚‚) = (e₁.trans f₁).sumLexCongr (eβ‚‚.trans fβ‚‚) := by ext; simp @[simp] theorem sumLexCongr_symm (ea : α₁ ≃o Ξ±β‚‚) (eb : β₁ ≃o Ξ²β‚‚) : (ea.sumLexCongr eb).symm = ea.symm.sumLexCongr eb.symm := rfl @[simp] theorem sumLexCongr_refl : sumLexCongr (.refl Ξ±) (.refl Ξ²) = .refl _ := by ext; simp /-- `Equiv.sumAssoc` promoted to an order isomorphism. -/ def sumLexAssoc (Ξ± Ξ² Ξ³ : Type*) [LE Ξ±] [LE Ξ²] [LE Ξ³] : (Ξ± βŠ•β‚— Ξ²) βŠ•β‚— Ξ³ ≃o Ξ± βŠ•β‚— Ξ² βŠ•β‚— Ξ³ := { Equiv.sumAssoc Ξ± Ξ² Ξ³ with map_rel_iff' := fun {a b} => ⟨fun h => match a, b, h with | inlβ‚— (inlβ‚— _), inlβ‚— (inlβ‚— _), Lex.inl h => Lex.inl <| Lex.inl h | inlβ‚— (inlβ‚— _), inlβ‚— (inrβ‚— _), Lex.sep _ _ => Lex.inl <| Lex.sep _ _ | inlβ‚— (inlβ‚— _), inrβ‚— _, Lex.sep _ _ => Lex.sep _ _ | inlβ‚— (inrβ‚— _), inlβ‚— (inrβ‚— _), Lex.inr (Lex.inl h) => Lex.inl <| Lex.inr h | inlβ‚— (inrβ‚— _), inrβ‚— _, Lex.inr (Lex.sep _ _) => Lex.sep _ _ | inrβ‚— _, inrβ‚— _, Lex.inr (Lex.inr h) => Lex.inr h, fun h => match a, b, h with | inlβ‚— (inlβ‚— _), inlβ‚— (inlβ‚— _), Lex.inl (Lex.inl h) => Lex.inl h | inlβ‚— (inlβ‚— _), inlβ‚— (inrβ‚— _), Lex.inl (Lex.sep _ _) => Lex.sep _ _ | inlβ‚— (inlβ‚— _), inrβ‚— _, Lex.sep _ _ => Lex.sep _ _ | inlβ‚— (inrβ‚— _), inlβ‚— (inrβ‚— _), Lex.inl (Lex.inr h) => Lex.inr <| Lex.inl h | inlβ‚— (inrβ‚— _), inrβ‚— _, Lex.sep _ _ => Lex.inr <| Lex.sep _ _ | inrβ‚— _, inrβ‚— _, Lex.inr h => Lex.inr <| Lex.inr h⟩ } @[simp] theorem sumLexAssoc_apply_inl_inl : sumLexAssoc Ξ± Ξ² Ξ³ (toLex <| inl <| toLex <| inl a) = toLex (inl a) := rfl @[simp] theorem sumLexAssoc_apply_inl_inr : sumLexAssoc Ξ± Ξ² Ξ³ (toLex <| inl <| toLex <| inr b) = toLex (inr <| toLex <| inl b) := rfl @[simp] theorem sumLexAssoc_apply_inr : sumLexAssoc Ξ± Ξ² Ξ³ (toLex <| inr c) = toLex (inr <| toLex <| inr c) := rfl @[simp] theorem sumLexAssoc_symm_apply_inl : (sumLexAssoc Ξ± Ξ² Ξ³).symm (inl a) = inl (inl a) := rfl @[simp] theorem sumLexAssoc_symm_apply_inr_inl : (sumLexAssoc Ξ± Ξ² Ξ³).symm (inr (inl b)) = inl (inr b) := rfl @[simp] theorem sumLexAssoc_symm_apply_inr_inr : (sumLexAssoc Ξ± Ξ² Ξ³).symm (inr (inr c)) = inr c := rfl /-- `OrderDual` is antidistributive over `βŠ•β‚—` up to an order isomorphism. -/ def sumLexDualAntidistrib (Ξ± Ξ² : Type*) [LE Ξ±] [LE Ξ²] : (Ξ± βŠ•β‚— Ξ²)α΅’α΅ˆ ≃o Ξ²α΅’α΅ˆ βŠ•β‚— Ξ±α΅’α΅ˆ := { Equiv.sumComm Ξ± Ξ² with map_rel_iff' := fun {a b} => by rcases a with (a | a) <;> rcases b with (b | b) Β· simp only [ge_iff_le] change toLex (inr <| toDual a) ≀ toLex (inr <| toDual b) ↔ toDual (toLex <| inl a) ≀ toDual (toLex <| inl b) simp [toDual_le_toDual] Β· exact iff_of_false (@Lex.not_inr_le_inl (OrderDual Ξ²) (OrderDual Ξ±) _ _ _ _) Lex.not_inr_le_inl Β· exact iff_of_true (@Lex.inl_le_inr (OrderDual Ξ²) (OrderDual Ξ±) _ _ _ _) (Lex.inl_le_inr _ _) Β· change toLex (inl <| toDual a) ≀ toLex (inl <| toDual b) ↔ toDual (toLex <| inr a) ≀ toDual (toLex <| inr b) simp [toDual_le_toDual] } @[simp] theorem sumLexDualAntidistrib_inl : sumLexDualAntidistrib Ξ± Ξ² (toDual (inl a)) = inr (toDual a) := rfl @[simp] theorem sumLexDualAntidistrib_inr : sumLexDualAntidistrib Ξ± Ξ² (toDual (inr b)) = inl (toDual b) := rfl @[simp] theorem sumLexDualAntidistrib_symm_inl : (sumLexDualAntidistrib Ξ± Ξ²).symm (inl (toDual b)) = toDual (inr b) := rfl @[simp] theorem sumLexDualAntidistrib_symm_inr : (sumLexDualAntidistrib Ξ± Ξ²).symm (inr (toDual a)) = toDual (inl a) := rfl end OrderIso variable [LE Ξ±] namespace WithBot /-- `WithBot Ξ±` is order-isomorphic to `PUnit βŠ•β‚— Ξ±`, by sending `βŠ₯` to `Unit` and `↑a` to `a`. -/ def orderIsoPUnitSumLex : WithBot Ξ± ≃o PUnit βŠ•β‚— Ξ± := ⟨(Equiv.optionEquivSumPUnit Ξ±).trans <| (Equiv.sumComm _ _).trans toLex, fun {a b} => by simp only [Equiv.optionEquivSumPUnit, Option.elim, Equiv.trans_apply, Equiv.coe_fn_mk, Equiv.sumComm_apply, swap, Lex.toLex_le_toLex, le_refl] cases a <;> cases b Β· simp only [elim_inr, lex_inl_inl, bot_le] Β· simp only [elim_inr, elim_inl, Lex.sep, bot_le] Β· simp only [elim_inl, elim_inr, lex_inr_inl, false_iff] exact not_coe_le_bot _ Β· simp only [elim_inl, lex_inr_inr, coe_le_coe] ⟩ @[simp] theorem orderIsoPUnitSumLex_bot : @orderIsoPUnitSumLex Ξ± _ βŠ₯ = toLex (inl PUnit.unit) := rfl @[simp] theorem orderIsoPUnitSumLex_toLex (a : Ξ±) : orderIsoPUnitSumLex ↑a = toLex (inr a) := rfl @[simp] theorem orderIsoPUnitSumLex_symm_inl (x : PUnit) : (@orderIsoPUnitSumLex Ξ± _).symm (toLex <| inl x) = βŠ₯ := rfl @[simp] theorem orderIsoPUnitSumLex_symm_inr (a : Ξ±) : orderIsoPUnitSumLex.symm (toLex <| inr a) = a := rfl end WithBot namespace WithTop /-- `WithTop Ξ±` is order-isomorphic to `Ξ± βŠ•β‚— PUnit`, by sending `⊀` to `Unit` and `↑a` to `a`. -/ def orderIsoSumLexPUnit : WithTop Ξ± ≃o Ξ± βŠ•β‚— PUnit := ⟨(Equiv.optionEquivSumPUnit Ξ±).trans toLex, fun {a b} => by simp only [Equiv.optionEquivSumPUnit, Option.elim, Equiv.trans_apply, Equiv.coe_fn_mk, Lex.toLex_le_toLex, le_refl] cases a <;> cases b Β· simp only [lex_inr_inr, le_top] Β· simp only [lex_inr_inl, false_iff] exact not_top_le_coe _ Β· simp only [Lex.sep, le_top] Β· simp only [lex_inl_inl, coe_le_coe]⟩ @[simp] theorem orderIsoSumLexPUnit_top : @orderIsoSumLexPUnit Ξ± _ ⊀ = toLex (inr PUnit.unit) := rfl @[simp] theorem orderIsoSumLexPUnit_toLex (a : Ξ±) : orderIsoSumLexPUnit ↑a = toLex (inl a) := rfl @[simp] theorem orderIsoSumLexPUnit_symm_inr (x : PUnit) : (@orderIsoSumLexPUnit Ξ± _).symm (toLex <| inr x) = ⊀ := rfl @[simp] theorem orderIsoSumLexPUnit_symm_inl (a : Ξ±) : orderIsoSumLexPUnit.symm (toLex <| inl a) = a := rfl end WithTop
.lake/packages/mathlib/Mathlib/Data/Sum/Basic.lean
import Mathlib.Logic.Function.Basic import Mathlib.Tactic.MkIffOfInductiveProp /-! # Additional lemmas about sum types Most of the former contents of this file have been moved to Batteries. -/ universe u v w x variable {Ξ± : Type u} {Ξ±' : Type w} {Ξ² : Type v} {Ξ²' : Type x} {Ξ³ Ξ΄ : Type*} lemma not_isLeft_and_isRight {x : Ξ± βŠ• Ξ²} : Β¬(x.isLeft ∧ x.isRight) := by simp namespace Sum @[simp] theorem elim_swap {Ξ± Ξ² Ξ³ : Type*} {f : Ξ± β†’ Ξ³} {g : Ξ² β†’ Ξ³} : Sum.elim f g ∘ Sum.swap = Sum.elim g f := by ext x cases x with | inl x => simp | inr x => simp -- Lean has removed the `@[simp]` attribute on these. For now Mathlib adds it back. attribute [simp] Sum.forall Sum.exists theorem exists_sum {Ξ³ : Ξ± βŠ• Ξ² β†’ Sort*} (p : (βˆ€ ab, Ξ³ ab) β†’ Prop) : (βˆƒ fab, p fab) ↔ (βˆƒ fa fb, p (Sum.rec fa fb)) := by rw [← not_forall_not, forall_sum] simp theorem inl_injective : Function.Injective (inl : Ξ± β†’ Ξ± βŠ• Ξ²) := fun _ _ ↦ inl.inj theorem inr_injective : Function.Injective (inr : Ξ² β†’ Ξ± βŠ• Ξ²) := fun _ _ ↦ inr.inj theorem sum_rec_congr (P : Ξ± βŠ• Ξ² β†’ Sort*) (f : βˆ€ i, P (inl i)) (g : βˆ€ i, P (inr i)) {x y : Ξ± βŠ• Ξ²} (h : x = y) : @Sum.rec _ _ _ f g x = cast (congr_arg P h.symm) (@Sum.rec _ _ _ f g y) := by cases h; rfl section get variable {x : Ξ± βŠ• Ξ²} theorem eq_left_iff_getLeft_eq {a : Ξ±} : x = inl a ↔ βˆƒ h, x.getLeft h = a := by cases x <;> simp theorem eq_right_iff_getRight_eq {b : Ξ²} : x = inr b ↔ βˆƒ h, x.getRight h = b := by cases x <;> simp theorem getLeft_eq_getLeft? (h₁ : x.isLeft) (hβ‚‚ : x.getLeft?.isSome) : x.getLeft h₁ = x.getLeft?.get hβ‚‚ := by simp [← getLeft?_eq_some_iff] theorem getRight_eq_getRight? (h₁ : x.isRight) (hβ‚‚ : x.getRight?.isSome) : x.getRight h₁ = x.getRight?.get hβ‚‚ := by simp [← getRight?_eq_some_iff] @[simp] theorem isSome_getLeft?_iff_isLeft : x.getLeft?.isSome ↔ x.isLeft := by rw [isLeft_iff, Option.isSome_iff_exists]; simp @[simp] theorem isSome_getRight?_iff_isRight : x.getRight?.isSome ↔ x.isRight := by rw [isRight_iff, Option.isSome_iff_exists]; simp end get open Function (update update_eq_iff update_comp_eq_of_injective update_comp_eq_of_forall_ne) @[simp] theorem update_elim_inl [DecidableEq Ξ±] [DecidableEq (Ξ± βŠ• Ξ²)] {f : Ξ± β†’ Ξ³} {g : Ξ² β†’ Ξ³} {i : Ξ±} {x : Ξ³} : update (Sum.elim f g) (inl i) x = Sum.elim (update f i x) g := update_eq_iff.2 ⟨by simp, by simp +contextual⟩ @[simp] theorem update_elim_inr [DecidableEq Ξ²] [DecidableEq (Ξ± βŠ• Ξ²)] {f : Ξ± β†’ Ξ³} {g : Ξ² β†’ Ξ³} {i : Ξ²} {x : Ξ³} : update (Sum.elim f g) (inr i) x = Sum.elim f (update g i x) := update_eq_iff.2 ⟨by simp, by simp +contextual⟩ @[simp] theorem update_inl_comp_inl [DecidableEq Ξ±] [DecidableEq (Ξ± βŠ• Ξ²)] {f : Ξ± βŠ• Ξ² β†’ Ξ³} {i : Ξ±} {x : Ξ³} : update f (inl i) x ∘ inl = update (f ∘ inl) i x := update_comp_eq_of_injective _ inl_injective _ _ @[simp] theorem update_inl_apply_inl [DecidableEq Ξ±] [DecidableEq (Ξ± βŠ• Ξ²)] {f : Ξ± βŠ• Ξ² β†’ Ξ³} {i j : Ξ±} {x : Ξ³} : update f (inl i) x (inl j) = update (f ∘ inl) i x j := by rw [← update_inl_comp_inl, Function.comp_apply] @[simp] theorem update_inl_comp_inr [DecidableEq (Ξ± βŠ• Ξ²)] {f : Ξ± βŠ• Ξ² β†’ Ξ³} {i : Ξ±} {x : Ξ³} : update f (inl i) x ∘ inr = f ∘ inr := (update_comp_eq_of_forall_ne _ _) fun _ ↦ inr_ne_inl theorem update_inl_apply_inr [DecidableEq (Ξ± βŠ• Ξ²)] {f : Ξ± βŠ• Ξ² β†’ Ξ³} {i : Ξ±} {j : Ξ²} {x : Ξ³} : update f (inl i) x (inr j) = f (inr j) := Function.update_of_ne inr_ne_inl .. @[simp] theorem update_inr_comp_inl [DecidableEq (Ξ± βŠ• Ξ²)] {f : Ξ± βŠ• Ξ² β†’ Ξ³} {i : Ξ²} {x : Ξ³} : update f (inr i) x ∘ inl = f ∘ inl := (update_comp_eq_of_forall_ne _ _) fun _ ↦ inl_ne_inr theorem update_inr_apply_inl [DecidableEq (Ξ± βŠ• Ξ²)] {f : Ξ± βŠ• Ξ² β†’ Ξ³} {i : Ξ±} {j : Ξ²} {x : Ξ³} : update f (inr j) x (inl i) = f (inl i) := Function.update_of_ne inl_ne_inr .. @[simp] theorem update_inr_comp_inr [DecidableEq Ξ²] [DecidableEq (Ξ± βŠ• Ξ²)] {f : Ξ± βŠ• Ξ² β†’ Ξ³} {i : Ξ²} {x : Ξ³} : update f (inr i) x ∘ inr = update (f ∘ inr) i x := update_comp_eq_of_injective _ inr_injective _ _ @[simp] theorem update_inr_apply_inr [DecidableEq Ξ²] [DecidableEq (Ξ± βŠ• Ξ²)] {f : Ξ± βŠ• Ξ² β†’ Ξ³} {i j : Ξ²} {x : Ξ³} : update f (inr i) x (inr j) = update (f ∘ inr) i x j := by rw [← update_inr_comp_inr, Function.comp_apply] @[simp] theorem update_inl_apply_inl' {Ξ³ : Ξ± βŠ• Ξ² β†’ Type*} [DecidableEq Ξ±] [DecidableEq (Ξ± βŠ• Ξ²)] {f : (i : Ξ± βŠ• Ξ²) β†’ Ξ³ i} {i : Ξ±} {x : Ξ³ (.inl i)} (j : Ξ±) : update f (.inl i) x (Sum.inl j) = update (fun j ↦ f (.inl j)) i x j := Function.update_apply_of_injective f Sum.inl_injective i x j @[simp] theorem update_inr_apply_inr' {Ξ³ : Ξ± βŠ• Ξ² β†’ Type*} [DecidableEq Ξ²] [DecidableEq (Ξ± βŠ• Ξ²)] {f : (i : Ξ± βŠ• Ξ²) β†’ Ξ³ i} {i : Ξ²} {x : Ξ³ (.inr i)} (j : Ξ²) : update f (.inr i) x (Sum.inr j) = update (fun j ↦ f (.inr j)) i x j := Function.update_apply_of_injective f Sum.inr_injective i x j @[simp] lemma rec_update_left {Ξ³ : Ξ± βŠ• Ξ² β†’ Sort*} [DecidableEq Ξ±] [DecidableEq Ξ²] (f : βˆ€ a, Ξ³ (.inl a)) (g : βˆ€ b, Ξ³ (.inr b)) (a : Ξ±) (x : Ξ³ (.inl a)) : Sum.rec (update f a x) g = update (Sum.rec f g) (.inl a) x := Function.rec_update Sum.inl_injective (Sum.rec Β· g) (fun _ _ => rfl) (fun | _, _, .inl _, h => (h _ rfl).elim | _, _, .inr _, _ => rfl) _ _ _ @[simp] lemma rec_update_right {Ξ³ : Ξ± βŠ• Ξ² β†’ Sort*} [DecidableEq Ξ±] [DecidableEq Ξ²] (f : βˆ€ a, Ξ³ (.inl a)) (g : βˆ€ b, Ξ³ (.inr b)) (b : Ξ²) (x : Ξ³ (.inr b)) : Sum.rec f (update g b x) = update (Sum.rec f g) (.inr b) x := Function.rec_update Sum.inr_injective (Sum.rec f) (fun _ _ => rfl) (fun | _, _, .inr _, h => (h _ rfl).elim | _, _, .inl _, _ => rfl) _ _ _ @[simp] lemma elim_update_left {Ξ³ : Sort*} [DecidableEq Ξ±] [DecidableEq Ξ²] (f : Ξ± β†’ Ξ³) (g : Ξ² β†’ Ξ³) (a : Ξ±) (x : Ξ³) : Sum.elim (update f a x) g = update (Sum.elim f g) (.inl a) x := rec_update_left _ _ _ _ @[simp] lemma elim_update_right {Ξ³ : Sort*} [DecidableEq Ξ±] [DecidableEq Ξ²] (f : Ξ± β†’ Ξ³) (g : Ξ² β†’ Ξ³) (b : Ξ²) (x : Ξ³) : Sum.elim f (update g b x) = update (Sum.elim f g) (.inr b) x := rec_update_right _ _ _ _ @[simp] theorem swap_leftInverse : Function.LeftInverse (@swap Ξ± Ξ²) swap := swap_swap @[simp] theorem swap_rightInverse : Function.RightInverse (@swap Ξ± Ξ²) swap := swap_swap mk_iff_of_inductive_prop Sum.LiftRel Sum.liftRel_iff namespace LiftRel variable {r : Ξ± β†’ Ξ³ β†’ Prop} {s : Ξ² β†’ Ξ΄ β†’ Prop} {x : Ξ± βŠ• Ξ²} {y : Ξ³ βŠ• Ξ΄} {a : Ξ±} {b : Ξ²} {c : Ξ³} {d : Ξ΄} theorem isLeft_congr (h : LiftRel r s x y) : x.isLeft ↔ y.isLeft := by cases h <;> rfl theorem isRight_congr (h : LiftRel r s x y) : x.isRight ↔ y.isRight := by cases h <;> rfl theorem isLeft_left (h : LiftRel r s x (inl c)) : x.isLeft := by cases h; rfl theorem isLeft_right (h : LiftRel r s (inl a) y) : y.isLeft := by cases h; rfl theorem isRight_left (h : LiftRel r s x (inr d)) : x.isRight := by cases h; rfl theorem isRight_right (h : LiftRel r s (inr b) y) : y.isRight := by cases h; rfl theorem exists_of_isLeft_left (h₁ : LiftRel r s x y) (hβ‚‚ : x.isLeft) : βˆƒ a c, r a c ∧ x = inl a ∧ y = inl c := by rcases isLeft_iff.mp hβ‚‚ with ⟨_, rfl⟩ simp only [liftRel_iff, false_and, and_false, exists_false, or_false, reduceCtorEq] at h₁ exact h₁ theorem exists_of_isLeft_right (h₁ : LiftRel r s x y) (hβ‚‚ : y.isLeft) : βˆƒ a c, r a c ∧ x = inl a ∧ y = inl c := exists_of_isLeft_left h₁ ((isLeft_congr h₁).mpr hβ‚‚) theorem exists_of_isRight_left (h₁ : LiftRel r s x y) (hβ‚‚ : x.isRight) : βˆƒ b d, s b d ∧ x = inr b ∧ y = inr d := by rcases isRight_iff.mp hβ‚‚ with ⟨_, rfl⟩ simp only [liftRel_iff, false_and, and_false, exists_false, false_or, reduceCtorEq] at h₁ exact h₁ theorem exists_of_isRight_right (h₁ : LiftRel r s x y) (hβ‚‚ : y.isRight) : βˆƒ b d, s b d ∧ x = inr b ∧ y = inr d := exists_of_isRight_left h₁ ((isRight_congr h₁).mpr hβ‚‚) end LiftRel end Sum open Sum namespace Function theorem Injective.sumElim {Ξ³ : Sort*} {f : Ξ± β†’ Ξ³} {g : Ξ² β†’ Ξ³} (hf : Injective f) (hg : Injective g) (hfg : βˆ€ a b, f a β‰  g b) : Injective (Sum.elim f g) | inl _, inl _, h => congr_arg inl <| hf h | inl _, inr _, h => (hfg _ _ h).elim | inr _, inl _, h => (hfg _ _ h.symm).elim | inr _, inr _, h => congr_arg inr <| hg h theorem Injective.sumMap {f : Ξ± β†’ Ξ²} {g : Ξ±' β†’ Ξ²'} (hf : Injective f) (hg : Injective g) : Injective (Sum.map f g) | inl _, inl _, h => congr_arg inl <| hf <| inl.inj h | inr _, inr _, h => congr_arg inr <| hg <| inr.inj h theorem Surjective.sumMap {f : Ξ± β†’ Ξ²} {g : Ξ±' β†’ Ξ²'} (hf : Surjective f) (hg : Surjective g) : Surjective (Sum.map f g) | inl y => let ⟨x, hx⟩ := hf y ⟨inl x, congr_arg inl hx⟩ | inr y => let ⟨x, hx⟩ := hg y ⟨inr x, congr_arg inr hx⟩ theorem Bijective.sumMap {f : Ξ± β†’ Ξ²} {g : Ξ±' β†’ Ξ²'} (hf : Bijective f) (hg : Bijective g) : Bijective (Sum.map f g) := ⟨hf.injective.sumMap hg.injective, hf.surjective.sumMap hg.surjective⟩ end Function namespace Sum open Function @[simp] theorem elim_injective {Ξ³ : Sort*} {f : Ξ± β†’ Ξ³} {g : Ξ² β†’ Ξ³} : Injective (Sum.elim f g) ↔ Injective f ∧ Injective g ∧ βˆ€ a b, f a β‰  g b where mp h := ⟨h.comp inl_injective, h.comp inr_injective, fun _ _ => h.ne inl_ne_inr⟩ mpr | ⟨hf, hg, hfg⟩ => hf.sumElim hg hfg @[simp] theorem map_injective {f : Ξ± β†’ Ξ³} {g : Ξ² β†’ Ξ΄} : Injective (Sum.map f g) ↔ Injective f ∧ Injective g where mp h := ⟨.of_comp <| h.comp inl_injective, .of_comp <| h.comp inr_injective⟩ mpr | ⟨hf, hg⟩ => hf.sumMap hg @[simp] theorem map_surjective {f : Ξ± β†’ Ξ³} {g : Ξ² β†’ Ξ΄} : Surjective (Sum.map f g) ↔ Surjective f ∧ Surjective g where mp h := ⟨ (fun c => by obtain ⟨a | b, h⟩ := h (inl c) Β· exact ⟨a, inl_injective h⟩ Β· cases h), (fun d => by obtain ⟨a | b, h⟩ := h (inr d) Β· cases h Β· exact ⟨b, inr_injective h⟩)⟩ mpr | ⟨hf, hg⟩ => hf.sumMap hg @[simp] theorem map_bijective {f : Ξ± β†’ Ξ³} {g : Ξ² β†’ Ξ΄} : Bijective (Sum.map f g) ↔ Bijective f ∧ Bijective g := (map_injective.and map_surjective).trans <| and_and_and_comm end Sum /-! ### Ternary sum Abbreviations for the maps from the summands to `Ξ± βŠ• Ξ² βŠ• Ξ³`. This is useful for pattern-matching. -/ namespace Sum3 /-- The map from the first summand into a ternary sum. -/ @[match_pattern, simp, reducible] def inβ‚€ (a : Ξ±) : Ξ± βŠ• (Ξ² βŠ• Ξ³) := inl a /-- The map from the second summand into a ternary sum. -/ @[match_pattern, simp, reducible] def in₁ (b : Ξ²) : Ξ± βŠ• (Ξ² βŠ• Ξ³) := inr <| inl b /-- The map from the third summand into a ternary sum. -/ @[match_pattern, simp, reducible] def inβ‚‚ (c : Ξ³) : Ξ± βŠ• (Ξ² βŠ• Ξ³) := inr <| inr c end Sum3 /-! ### PSum -/ namespace PSum variable {Ξ± Ξ² : Sort*} theorem inl_injective : Function.Injective (PSum.inl : Ξ± β†’ Ξ± βŠ•' Ξ²) := fun _ _ ↦ inl.inj theorem inr_injective : Function.Injective (PSum.inr : Ξ² β†’ Ξ± βŠ•' Ξ²) := fun _ _ ↦ inr.inj end PSum
.lake/packages/mathlib/Mathlib/Data/Sum/Lattice.lean
import Mathlib.Data.Sum.Order import Mathlib.Order.Hom.Lattice /-! # Lexicographic sum of lattices This file proves that we can combine two lattices `Ξ±` and `Ξ²` into a lattice `Ξ± βŠ•β‚— Ξ²` where everything in `Ξ±` is declared smaller than everything in `Ξ²`. -/ open OrderDual namespace Sum.Lex variable {Ξ± Ξ² : Type*} section SemilatticeSup variable [SemilatticeSup Ξ±] [SemilatticeSup Ξ²] -- The linter significantly hinders readability here. set_option linter.unusedVariables false in instance instSemilatticeSup : SemilatticeSup (Ξ± βŠ•β‚— Ξ²) where sup | inlβ‚— a₁, inlβ‚— aβ‚‚ => inl (a₁ βŠ” aβ‚‚) | inlβ‚— a₁, inrβ‚— bβ‚‚ => inr bβ‚‚ | inrβ‚— b₁, inlβ‚— aβ‚‚ => inr b₁ | inrβ‚— b₁, inrβ‚— bβ‚‚ => inr (b₁ βŠ” bβ‚‚) le_sup_left | inlβ‚— a₁, inlβ‚— aβ‚‚ => inl_le_inl_iff.2 le_sup_left | inlβ‚— a₁, inrβ‚— bβ‚‚ => inl_le_inr _ _ | inrβ‚— b₁, inlβ‚— aβ‚‚ => le_rfl | inrβ‚— b₁, inrβ‚— bβ‚‚ => inr_le_inr_iff.2 le_sup_left le_sup_right | inlβ‚— a₁, inlβ‚— aβ‚‚ => inl_le_inl_iff.2 le_sup_right | inlβ‚— a₁, inrβ‚— bβ‚‚ => le_rfl | inrβ‚— b₁, inlβ‚— aβ‚‚ => inl_le_inr _ _ | inrβ‚— b₁, inrβ‚— bβ‚‚ => inr_le_inr_iff.2 le_sup_right sup_le | inlβ‚— a₁, inlβ‚— aβ‚‚, inlβ‚— a₃, Lex.inl h₁₃, Lex.inl h₂₃ => inl_le_inl_iff.2 <| sup_le h₁₃ h₂₃ | inlβ‚— a₁, inlβ‚— aβ‚‚, inrβ‚— b₃, Lex.sep _ _, Lex.sep _ _ => Lex.sep _ _ | inlβ‚— a₁, inrβ‚— bβ‚‚, inrβ‚— b₃, Lex.sep _ _, Lex.inr h₂₃ => inr_le_inr_iff.2 h₂₃ | inrβ‚— b₁, inlβ‚— aβ‚‚, inrβ‚— b₃, Lex.inr h₁₃, Lex.sep _ _ => inr_le_inr_iff.2 h₁₃ | inrβ‚— b₁, inrβ‚— bβ‚‚, inrβ‚— b₃, Lex.inr h₁₃, Lex.inr h₂₃ => inr_le_inr_iff.2 <| sup_le h₁₃ h₂₃ @[simp] lemma inl_sup (a₁ aβ‚‚ : Ξ±) : (inlβ‚— (a₁ βŠ” aβ‚‚) : Ξ± βŠ• Ξ²) = inlβ‚— a₁ βŠ” inlβ‚— aβ‚‚ := rfl @[simp] lemma inr_sup (b₁ bβ‚‚ : Ξ²) : (inrβ‚— (b₁ βŠ” bβ‚‚) : Ξ± βŠ• Ξ²) = inrβ‚— b₁ βŠ” inrβ‚— bβ‚‚ := rfl end SemilatticeSup section SemilatticeInf variable [SemilatticeInf Ξ±] [SemilatticeInf Ξ²] -- The linter significantly hinders readability here. set_option linter.unusedVariables false in instance instSemilatticeInf : SemilatticeInf (Ξ± βŠ•β‚— Ξ²) where inf | inlβ‚— a₁, inlβ‚— aβ‚‚ => inl (a₁ βŠ“ aβ‚‚) | inlβ‚— a₁, inrβ‚— bβ‚‚ => inl a₁ | inrβ‚— b₁, inlβ‚— aβ‚‚ => inl aβ‚‚ | inrβ‚— b₁, inrβ‚— bβ‚‚ => inr (b₁ βŠ“ bβ‚‚) inf_le_left | inlβ‚— a₁, inlβ‚— aβ‚‚ => inl_le_inl_iff.2 inf_le_left | inlβ‚— a₁, inrβ‚— bβ‚‚ => le_rfl | inrβ‚— b₁, inlβ‚— aβ‚‚ => inl_le_inr _ _ | inrβ‚— b₁, inrβ‚— bβ‚‚ => inr_le_inr_iff.2 inf_le_left inf_le_right | inlβ‚— a₁, inlβ‚— aβ‚‚ => inl_le_inl_iff.2 inf_le_right | inlβ‚— a₁, inrβ‚— bβ‚‚ => inl_le_inr _ _ | inrβ‚— b₁, inlβ‚— aβ‚‚ => le_rfl | inrβ‚— b₁, inrβ‚— bβ‚‚ => inr_le_inr_iff.2 inf_le_right le_inf | inlβ‚— a₁, inlβ‚— aβ‚‚, inlβ‚— a₃, Lex.inl h₁₃, Lex.inl h₂₃ => inl_le_inl_iff.2 <| le_inf h₁₃ h₂₃ | inlβ‚— a₁, inlβ‚— aβ‚‚, inrβ‚— b₃, Lex.inl h₁₃, Lex.sep _ _ => inl_le_inl_iff.2 h₁₃ | inlβ‚— a₁, inrβ‚— bβ‚‚, inlβ‚— a₃, Lex.sep _ _, Lex.inl h₂₃ => inl_le_inl_iff.2 h₂₃ | inlβ‚— a₁, inrβ‚— bβ‚‚, inrβ‚— b₃, Lex.sep _ _, Lex.sep _ _ => Lex.sep _ _ | inrβ‚— b₁, inrβ‚— bβ‚‚, inrβ‚— b₃, Lex.inr h₁₃, Lex.inr h₂₃ => inr_le_inr_iff.2 <| le_inf h₁₃ h₂₃ @[simp] lemma inl_inf (a₁ aβ‚‚ : Ξ±) : (inlβ‚— (a₁ βŠ“ aβ‚‚) : Ξ± βŠ• Ξ²) = inlβ‚— a₁ βŠ“ inlβ‚— aβ‚‚ := rfl @[simp] lemma inr_inf (b₁ bβ‚‚ : Ξ²) : (inrβ‚— (b₁ βŠ“ bβ‚‚) : Ξ± βŠ• Ξ²) = inrβ‚— b₁ βŠ“ inrβ‚— bβ‚‚ := rfl end SemilatticeInf section Lattice variable [Lattice Ξ±] [Lattice Ξ²] instance instLattice : Lattice (Ξ± βŠ•β‚— Ξ²) := { instSemilatticeSup, instSemilatticeInf with } /-- `Sum.Lex.inlβ‚—` as a lattice homomorphism. -/ def inlLatticeHom : LatticeHom Ξ± (Ξ± βŠ•β‚— Ξ²) where toFun := inlβ‚— map_sup' _ _ := rfl map_inf' _ _ := rfl /-- `Sum.Lex.inrβ‚—` as a lattice homomorphism. -/ def inrLatticeHom : LatticeHom Ξ² (Ξ± βŠ•β‚— Ξ²) where toFun := inrβ‚— map_sup' _ _ := rfl map_inf' _ _ := rfl end Lattice instance instDistribLattice [DistribLattice Ξ±] [DistribLattice Ξ²] : DistribLattice (Ξ± βŠ•β‚— Ξ²) where le_sup_inf := by simp only [Lex.forall, Sum.forall, inr_le_inr_iff, le_sup_left, inl_le_inr, sup_of_le_right, and_self, inf_of_le_left, implies_true, inf_of_le_right, sup_of_le_left, ← inl_sup, ← inr_sup, ← inl_inf, ← inr_inf, sup_inf_left, le_rfl] end Sum.Lex
.lake/packages/mathlib/Mathlib/Data/Ordering/Lemmas.lean
import Mathlib.Data.Ordering.Basic import Mathlib.Order.Defs.Unbundled /-! # Some `Ordering` lemmas -/ universe u namespace Ordering @[simp] theorem ite_eq_lt_distrib (c : Prop) [Decidable c] (a b : Ordering) : ((if c then a else b) = Ordering.lt) = if c then a = Ordering.lt else b = Ordering.lt := by by_cases c <;> simp [*] @[simp] theorem ite_eq_eq_distrib (c : Prop) [Decidable c] (a b : Ordering) : ((if c then a else b) = Ordering.eq) = if c then a = Ordering.eq else b = Ordering.eq := by by_cases c <;> simp [*] @[simp] theorem ite_eq_gt_distrib (c : Prop) [Decidable c] (a b : Ordering) : ((if c then a else b) = Ordering.gt) = if c then a = Ordering.gt else b = Ordering.gt := by by_cases c <;> simp [*] @[simp] lemma dthen_eq_then (o₁ oβ‚‚ : Ordering) : o₁.dthen (fun _ => oβ‚‚) = o₁.then oβ‚‚ := by cases o₁ <;> rfl end Ordering section variable {Ξ± : Type u} {lt : Ξ± β†’ Ξ± β†’ Prop} [DecidableRel lt] attribute [local simp] cmpUsing @[simp] theorem cmpUsing_eq_lt (a b : Ξ±) : (cmpUsing lt a b = Ordering.lt) = lt a b := by simp only [cmpUsing, Ordering.ite_eq_lt_distrib, ite_self, if_false_right, and_true, reduceCtorEq] @[simp] theorem cmpUsing_eq_gt [IsStrictOrder Ξ± lt] (a b : Ξ±) : cmpUsing lt a b = Ordering.gt ↔ lt b a := by simp only [cmpUsing, Ordering.ite_eq_gt_distrib, if_false_right, and_true, if_false_left, and_iff_right_iff_imp, reduceCtorEq] exact fun hba hab ↦ (irrefl a) (_root_.trans hab hba) @[simp] theorem cmpUsing_eq_eq (a b : Ξ±) : cmpUsing lt a b = Ordering.eq ↔ Β¬lt a b ∧ Β¬lt b a := by simp end
.lake/packages/mathlib/Mathlib/Data/Ordering/Basic.lean
import Batteries.Tactic.Alias import Mathlib.Tactic.Lemma import Mathlib.Tactic.TypeStar /-! # Helper definitions and instances for `Ordering` -/ universe u namespace Ordering variable {Ξ± : Type*} /-- `Compares o a b` means that `a` and `b` have the ordering relation `o` between them, assuming that the relation `a < b` is defined. -/ def Compares [LT Ξ±] : Ordering β†’ Ξ± β†’ Ξ± β†’ Prop | lt, a, b => a < b | eq, a, b => a = b | gt, a, b => a > b @[simp] lemma compares_lt [LT Ξ±] (a b : Ξ±) : Compares lt a b = (a < b) := rfl @[simp] lemma compares_eq [LT Ξ±] (a b : Ξ±) : Compares eq a b = (a = b) := rfl @[simp] lemma compares_gt [LT Ξ±] (a b : Ξ±) : Compares gt a b = (a > b) := rfl /-- `o₁.dthen fun h => oβ‚‚(h)` is like `o₁.then oβ‚‚` but `oβ‚‚` is allowed to depend on `h : o₁ = .eq`. -/ @[macro_inline] def dthen : (o : Ordering) β†’ (o = .eq β†’ Ordering) β†’ Ordering | .eq, f => f rfl | o, _ => o end Ordering /-- Lift a decidable relation to an `Ordering`, assuming that incomparable terms are `Ordering.eq`. -/ def cmpUsing {Ξ± : Type u} (lt : Ξ± β†’ Ξ± β†’ Prop) [DecidableRel lt] (a b : Ξ±) : Ordering := if lt a b then Ordering.lt else if lt b a then Ordering.gt else Ordering.eq /-- Construct an `Ordering` from a type with a decidable `LT` instance, assuming that incomparable terms are `Ordering.eq`. -/ def cmp {Ξ± : Type u} [LT Ξ±] [DecidableLT Ξ±] (a b : Ξ±) : Ordering := cmpUsing (Β· < Β·) a b
.lake/packages/mathlib/Mathlib/Data/List/Nodup.lean
import Mathlib.Data.List.Forall2 import Mathlib.Data.Nat.Basic import Mathlib.Order.Basic /-! # Lists with no duplicates `List.Nodup` is defined in `Data/List/Basic`. In this file we prove various properties of this predicate. -/ universe u v open Function variable {Ξ± : Type u} {Ξ² : Type v} {l l₁ lβ‚‚ : List Ξ±} {r : Ξ± β†’ Ξ± β†’ Prop} {a : Ξ±} namespace List protected theorem Pairwise.nodup {l : List Ξ±} {r : Ξ± β†’ Ξ± β†’ Prop} [IsIrrefl Ξ± r] (h : Pairwise r l) : Nodup l := h.imp ne_of_irrefl open scoped Relator in theorem rel_nodup {r : Ξ± β†’ Ξ² β†’ Prop} (hr : Relator.BiUnique r) : (Forallβ‚‚ r β‡’ (Β· ↔ Β·)) Nodup Nodup | _, _, Forallβ‚‚.nil => by simp only [nodup_nil] | _, _, Forallβ‚‚.cons hab h => by simpa only [nodup_cons] using Relator.rel_and (Relator.rel_not (rel_mem hr hab h)) (rel_nodup hr h) protected theorem Nodup.cons (ha : a βˆ‰ l) (hl : Nodup l) : Nodup (a :: l) := nodup_cons.2 ⟨ha, hl⟩ theorem nodup_singleton (a : Ξ±) : Nodup [a] := pairwise_singleton _ _ theorem Nodup.of_cons (h : Nodup (a :: l)) : Nodup l := (nodup_cons.1 h).2 theorem Nodup.notMem (h : (a :: l).Nodup) : a βˆ‰ l := (nodup_cons.1 h).1 @[deprecated (since := "2025-05-23")] alias Nodup.not_mem := Nodup.notMem theorem not_nodup_cons_of_mem : a ∈ l β†’ Β¬Nodup (a :: l) := imp_not_comm.1 Nodup.notMem theorem not_nodup_pair (a : Ξ±) : Β¬Nodup [a, a] := not_nodup_cons_of_mem <| mem_singleton_self _ theorem nodup_iff_sublist {l : List Ξ±} : Nodup l ↔ βˆ€ a, Β¬[a, a] <+ l := ⟨fun d a h => not_nodup_pair a (d.sublist h), by induction l <;> intro h; Β· exact nodup_nil case cons a l IH => exact (IH fun a s => h a <| sublist_cons_of_sublist _ s).cons fun al => h a <| (singleton_sublist.2 al).cons_cons _⟩ @[simp] theorem nodup_mergeSort {l : List Ξ±} {le : Ξ± β†’ Ξ± β†’ Bool} : (l.mergeSort le).Nodup ↔ l.Nodup := (mergeSort_perm l le).nodup_iff protected alias ⟨_, Nodup.mergeSort⟩ := nodup_mergeSort theorem nodup_iff_injective_getElem {l : List Ξ±} : Nodup l ↔ Function.Injective (fun i : Fin l.length => l[i.1]) := pairwise_iff_getElem.trans ⟨fun h i j hg => by obtain ⟨i, hi⟩ := i; obtain ⟨j, hj⟩ := j rcases lt_trichotomy i j with (hij | rfl | hji) Β· exact (h i j hi hj hij hg).elim Β· rfl Β· exact (h j i hj hi hji hg.symm).elim, fun hinj i j hi hj hij h => Nat.ne_of_lt hij (Fin.val_eq_of_eq (@hinj ⟨i, hi⟩ ⟨j, hj⟩ h))⟩ theorem nodup_iff_injective_get {l : List Ξ±} : Nodup l ↔ Function.Injective l.get := nodup_iff_injective_getElem theorem Nodup.get_inj_iff {l : List Ξ±} (h : Nodup l) {i j : Fin l.length} : l.get i = l.get j ↔ i = j := (nodup_iff_injective_get.1 h).eq_iff theorem Nodup.getElem_inj_iff {l : List Ξ±} (h : Nodup l) {i : Nat} {hi : i < l.length} {j : Nat} {hj : j < l.length} : l[i] = l[j] ↔ i = j := by have := @Nodup.get_inj_iff _ _ h ⟨i, hi⟩ ⟨j, hj⟩ simpa theorem nodup_iff_getElem?_ne_getElem? {l : List Ξ±} : l.Nodup ↔ βˆ€ i j : β„•, i < j β†’ j < l.length β†’ l[i]? β‰  l[j]? := by grind [List.pairwise_iff_getElem] theorem Nodup.ne_singleton_iff {l : List Ξ±} (h : Nodup l) (x : Ξ±) : l β‰  [x] ↔ l = [] ∨ βˆƒ y ∈ l, y β‰  x := by induction l with | nil => simp | cons hd tl hl => specialize hl h.of_cons by_cases hx : tl = [x] Β· simpa [hx, and_comm, and_or_left] using h Β· rw [← Ne, hl] at hx rcases hx with (rfl | ⟨y, hy, hx⟩) Β· simp Β· suffices βˆƒ y ∈ hd :: tl, y β‰  x by simpa [ne_nil_of_mem hy] exact ⟨y, mem_cons_of_mem _ hy, hx⟩ theorem not_nodup_of_get_eq_of_ne (xs : List Ξ±) (n m : Fin xs.length) (h : xs.get n = xs.get m) (hne : n β‰  m) : Β¬Nodup xs := by rw [nodup_iff_injective_get] exact fun hinj => hne (hinj h) theorem idxOf_getElem [DecidableEq Ξ±] {l : List Ξ±} (H : Nodup l) (i : Nat) (h : i < l.length) : idxOf l[i] l = i := suffices (⟨idxOf l[i] l, idxOf_lt_length_iff.2 (getElem_mem _)⟩ : Fin l.length) = ⟨i, h⟩ from Fin.val_eq_of_eq this nodup_iff_injective_get.1 H (by simp) -- This is incorrectly named and should be `idxOf_get`; -- this already exists, so will require a deprecation dance. theorem get_idxOf [DecidableEq Ξ±] {l : List Ξ±} (H : Nodup l) (i : Fin l.length) : idxOf (get l i) l = i := by simp [idxOf_getElem, H] theorem nodup_iff_count_le_one [DecidableEq Ξ±] {l : List Ξ±} : Nodup l ↔ βˆ€ a, count a l ≀ 1 := nodup_iff_sublist.trans <| forall_congr' fun a => have : replicate 2 a <+ l ↔ 1 < count a l := replicate_sublist_iff .. (not_congr this).trans not_lt theorem nodup_iff_count_eq_one [DecidableEq Ξ±] : Nodup l ↔ βˆ€ a ∈ l, count a l = 1 := nodup_iff_count_le_one.trans <| forall_congr' fun _ => ⟨fun H h => H.antisymm (count_pos_iff.mpr h), fun H => if h : _ then (H h).le else (count_eq_zero.mpr h).trans_le (Nat.zero_le 1)⟩ theorem get_bijective_iff [DecidableEq Ξ±] : l.get.Bijective ↔ βˆ€ a, l.count a = 1 := ⟨fun h a ↦ (nodup_iff_count_eq_one.mp <| nodup_iff_injective_get.mpr h.injective) a <| mem_iff_get.mpr <| h.surjective a, fun h ↦ ⟨nodup_iff_injective_get.mp <| nodup_iff_count_eq_one.mpr fun a _ ↦ h a, fun a ↦ mem_iff_get.mp <| List.one_le_count_iff.mp <| by grind⟩⟩ theorem getElem_bijective_iff [DecidableEq Ξ±] : (fun (n : Fin l.length) ↦ l[n]).Bijective ↔ βˆ€ a, l.count a = 1 := get_bijective_iff @[simp] theorem count_eq_one_of_mem [DecidableEq Ξ±] {a : Ξ±} {l : List Ξ±} (d : Nodup l) (h : a ∈ l) : count a l = 1 := _root_.le_antisymm (nodup_iff_count_le_one.1 d a) (Nat.succ_le_of_lt (count_pos_iff.2 h)) @[deprecated (since := "2025-11-07")] alias count_eq_of_nodup := Nodup.count theorem Nodup.of_append_left : Nodup (l₁ ++ lβ‚‚) β†’ Nodup l₁ := Nodup.sublist (sublist_append_left l₁ lβ‚‚) theorem Nodup.of_append_right : Nodup (l₁ ++ lβ‚‚) β†’ Nodup lβ‚‚ := Nodup.sublist (sublist_append_right l₁ lβ‚‚) /-- This is a variant of the `nodup_append` from the standard library, which does not use `Disjoint`. -/ theorem nodup_append' {l₁ lβ‚‚ : List Ξ±} : Nodup (l₁ ++ lβ‚‚) ↔ Nodup l₁ ∧ Nodup lβ‚‚ ∧ Disjoint l₁ lβ‚‚ := by simp only [Nodup, pairwise_append, disjoint_iff_ne] theorem disjoint_of_nodup_append {l₁ lβ‚‚ : List Ξ±} (d : Nodup (l₁ ++ lβ‚‚)) : Disjoint l₁ lβ‚‚ := (nodup_append'.1 d).2.2 protected alias Nodup.disjoint := disjoint_of_nodup_append theorem Nodup.append (d₁ : Nodup l₁) (dβ‚‚ : Nodup lβ‚‚) (dj : Disjoint l₁ lβ‚‚) : Nodup (l₁ ++ lβ‚‚) := nodup_append'.2 ⟨d₁, dβ‚‚, dj⟩ theorem nodup_append_comm {l₁ lβ‚‚ : List Ξ±} : Nodup (l₁ ++ lβ‚‚) ↔ Nodup (lβ‚‚ ++ l₁) := by simp only [nodup_append', and_left_comm, disjoint_comm] theorem nodup_middle {a : Ξ±} {l₁ lβ‚‚ : List Ξ±} : Nodup (l₁ ++ a :: lβ‚‚) ↔ Nodup (a :: (l₁ ++ lβ‚‚)) := by simp only [nodup_append', not_or, and_left_comm, and_assoc, nodup_cons, mem_append, disjoint_cons_right] theorem Nodup.of_map (f : Ξ± β†’ Ξ²) {l : List Ξ±} : Nodup (map f l) β†’ Nodup l := (Pairwise.of_map f) fun _ _ => mt <| congr_arg f theorem Nodup.map_on {f : Ξ± β†’ Ξ²} (H : βˆ€ x ∈ l, βˆ€ y ∈ l, f x = f y β†’ x = y) (d : Nodup l) : (map f l).Nodup := Pairwise.map _ (fun a b ⟨ma, mb, n⟩ e => n (H a ma b mb e)) (Pairwise.and_mem.1 d) theorem inj_on_of_nodup_map {f : Ξ± β†’ Ξ²} {l : List Ξ±} (d : Nodup (map f l)) : βˆ€ ⦃x⦄, x ∈ l β†’ βˆ€ ⦃y⦄, y ∈ l β†’ f x = f y β†’ x = y := by induction l with | nil => simp | cons hd tl ih => simp only [map, nodup_cons, mem_map, not_exists, not_and, ← Ne.eq_def] at d simp only [mem_cons] rintro _ (rfl | h₁) _ (rfl | hβ‚‚) h₃ Β· rfl Β· apply (d.1 _ hβ‚‚ h₃.symm).elim Β· apply (d.1 _ h₁ h₃).elim Β· apply ih d.2 h₁ hβ‚‚ h₃ theorem nodup_map_iff_inj_on {f : Ξ± β†’ Ξ²} {l : List Ξ±} (d : Nodup l) : Nodup (map f l) ↔ βˆ€ x ∈ l, βˆ€ y ∈ l, f x = f y β†’ x = y := ⟨inj_on_of_nodup_map, fun h => d.map_on h⟩ protected theorem Nodup.map {f : Ξ± β†’ Ξ²} (hf : Injective f) : Nodup l β†’ Nodup (map f l) := Nodup.map_on fun _ _ _ _ h => hf h theorem nodup_map_iff {f : Ξ± β†’ Ξ²} {l : List Ξ±} (hf : Injective f) : Nodup (map f l) ↔ Nodup l := ⟨Nodup.of_map _, Nodup.map hf⟩ @[simp] theorem nodup_attach {l : List Ξ±} : Nodup (attach l) ↔ Nodup l := ⟨fun h => attach_map_subtype_val l β–Έ h.map fun _ _ => Subtype.eq, fun h => Nodup.of_map Subtype.val ((attach_map_subtype_val l).symm β–Έ h)⟩ protected alias ⟨Nodup.of_attach, Nodup.attach⟩ := nodup_attach theorem Nodup.pmap {p : Ξ± β†’ Prop} {f : βˆ€ a, p a β†’ Ξ²} {l : List Ξ±} {H} (hf : βˆ€ a ha b hb, f a ha = f b hb β†’ a = b) (h : Nodup l) : Nodup (pmap f l H) := by grind theorem Nodup.filter (p : Ξ± β†’ Bool) {l} : Nodup l β†’ Nodup (filter p l) := by simpa using Pairwise.filter p @[simp] theorem nodup_reverse {l : List Ξ±} : Nodup (reverse l) ↔ Nodup l := pairwise_reverse.trans <| by simp only [Nodup, Ne, eq_comm] theorem nodup_concat (l : List Ξ±) (u : Ξ±) : (l.concat u).Nodup ↔ u βˆ‰ l ∧ l.Nodup := by rw [← nodup_reverse] simp lemma nodup_tail_reverse (l : List Ξ±) (h : l[0]? = l.getLast?) : Nodup l.reverse.tail ↔ Nodup l.tail := by induction l with | nil => simp | cons a l ih => by_cases hl : l = [] Β· simp_all Β· simp_all only [List.tail_reverse, List.nodup_reverse, List.dropLast_cons_of_ne_nil hl, List.tail_cons] simp only [length_cons, Nat.zero_lt_succ, getElem?_eq_getElem, Nat.add_one_sub_one, Nat.lt_add_one, Option.some.injEq, List.getElem_cons, show l.length β‰  0 by aesop, ↓reduceDIte, getLast?_eq_getElem?] at h rw [h, show l.Nodup = (l.dropLast ++ [l.getLast hl]).Nodup by simp [List.dropLast_eq_take], List.nodup_append_comm] simp [List.getLast_eq_getElem] theorem Nodup.erase_getElem [DecidableEq Ξ±] {l : List Ξ±} (hl : l.Nodup) (i : Nat) (h : i < l.length) : l.erase l[i] = l.eraseIdx ↑i := by induction l generalizing i with | nil => simp | cons a l IH => cases i with | zero => simp | succ i => grind theorem Nodup.erase_get [DecidableEq Ξ±] {l : List Ξ±} (hl : l.Nodup) (i : Fin l.length) : l.erase (l.get i) = l.eraseIdx ↑i := by simp [erase_getElem, hl] theorem Nodup.diff [DecidableEq Ξ±] : l₁.Nodup β†’ (l₁.diff lβ‚‚).Nodup := Nodup.sublist <| diff_sublist _ _ theorem nodup_flatten {L : List (List Ξ±)} : Nodup (flatten L) ↔ (βˆ€ l ∈ L, Nodup l) ∧ Pairwise Disjoint L := by simp only [Nodup, pairwise_flatten, disjoint_left.symm, forall_mem_ne] theorem nodup_flatMap {l₁ : List Ξ±} {f : Ξ± β†’ List Ξ²} : Nodup (l₁.flatMap f) ↔ (βˆ€ x ∈ l₁, Nodup (f x)) ∧ Pairwise (Disjoint on f) l₁ := by simp only [List.flatMap, nodup_flatten, pairwise_map, and_comm, mem_map, exists_imp, and_imp] rw [show (βˆ€ (l : List Ξ²) (x : Ξ±), f x = l β†’ x ∈ l₁ β†’ Nodup l) ↔ βˆ€ x : Ξ±, x ∈ l₁ β†’ Nodup (f x) from forall_swap.trans <| forall_congr' fun _ => forall_eq'] protected theorem Nodup.product {lβ‚‚ : List Ξ²} (d₁ : l₁.Nodup) (dβ‚‚ : lβ‚‚.Nodup) : (l₁ Γ—Λ’ lβ‚‚).Nodup := nodup_flatMap.2 ⟨fun a _ => dβ‚‚.map <| LeftInverse.injective fun b => (rfl : (a, b).2 = b), d₁.imp fun {a₁ aβ‚‚} n x h₁ hβ‚‚ => by rcases mem_map.1 h₁ with ⟨b₁, _, rfl⟩ rcases mem_map.1 hβ‚‚ with ⟨bβ‚‚, mbβ‚‚, ⟨⟩⟩ exact n rfl⟩ theorem Nodup.sigma {Οƒ : Ξ± β†’ Type*} {lβ‚‚ : βˆ€ a, List (Οƒ a)} (d₁ : Nodup l₁) (dβ‚‚ : βˆ€ a, Nodup (lβ‚‚ a)) : (l₁.sigma lβ‚‚).Nodup := nodup_flatMap.2 ⟨fun a _ => (dβ‚‚ a).map fun b b' h => by injection h with _ h, d₁.imp fun {a₁ aβ‚‚} n x h₁ hβ‚‚ => by rcases mem_map.1 h₁ with ⟨b₁, _, rfl⟩ rcases mem_map.1 hβ‚‚ with ⟨bβ‚‚, mbβ‚‚, ⟨⟩⟩ exact n rfl⟩ protected theorem Nodup.filterMap {f : Ξ± β†’ Option Ξ²} (h : βˆ€ a a' b, b ∈ f a β†’ b ∈ f a' β†’ a = a') : Nodup l β†’ Nodup (filterMap f l) := (Pairwise.filterMap f) @fun a a' n b bm b' bm' e => n <| h a a' b' (by rw [← e]; exact bm) bm' protected theorem Nodup.concat (h : a βˆ‰ l) (h' : l.Nodup) : (l.concat a).Nodup := by rw [concat_eq_append]; exact h'.append (nodup_singleton _) (disjoint_singleton.2 h) protected theorem Nodup.insert [DecidableEq Ξ±] (h : l.Nodup) : (l.insert a).Nodup := if h' : a ∈ l then by rw [insert_of_mem h']; exact h else by rw [insert_of_not_mem h', nodup_cons]; constructor <;> assumption theorem Nodup.union [DecidableEq Ξ±] (l₁ : List Ξ±) (h : Nodup lβ‚‚) : (l₁ βˆͺ lβ‚‚).Nodup := by induction l₁ generalizing lβ‚‚ with | nil => exact h | cons a l₁ ih => exact (ih h).insert theorem Nodup.inter [DecidableEq Ξ±] (lβ‚‚ : List Ξ±) : Nodup l₁ β†’ Nodup (l₁ ∩ lβ‚‚) := Nodup.filter _ theorem Nodup.diff_eq_filter [BEq Ξ±] [LawfulBEq Ξ±] : βˆ€ {l₁ lβ‚‚ : List Ξ±} (_ : l₁.Nodup), l₁.diff lβ‚‚ = l₁.filter (Β· βˆ‰ lβ‚‚) | l₁, [], _ => by simp | l₁, a :: lβ‚‚, hl₁ => by rw [diff_cons, (hl₁.erase _).diff_eq_filter, hl₁.erase_eq_filter, filter_filter] simp only [decide_not, bne, Bool.and_comm, decide_mem_cons, Bool.not_or] theorem Nodup.mem_diff_iff [DecidableEq Ξ±] (hl₁ : l₁.Nodup) : a ∈ l₁.diff lβ‚‚ ↔ a ∈ l₁ ∧ a βˆ‰ lβ‚‚ := by rw [hl₁.diff_eq_filter, mem_filter, decide_eq_true_iff] protected theorem Nodup.set : βˆ€ {l : List Ξ±} {n : β„•} {a : Ξ±} (_ : l.Nodup) (_ : a βˆ‰ l), (l.set n a).Nodup | [], _, _, _, _ => nodup_nil | _ :: _, 0, _, hl, ha => nodup_cons.2 ⟨mt (mem_cons_of_mem _) ha, (nodup_cons.1 hl).2⟩ | _ :: _, _ + 1, _, hl, ha => nodup_cons.2 ⟨fun h => (mem_or_eq_of_mem_set h).elim (nodup_cons.1 hl).1 fun hba => ha (hba β–Έ mem_cons_self), hl.of_cons.set (mt (mem_cons_of_mem _) ha)⟩ theorem Nodup.map_update [DecidableEq Ξ±] {l : List Ξ±} (hl : l.Nodup) (f : Ξ± β†’ Ξ²) (x : Ξ±) (y : Ξ²) : l.map (Function.update f x y) = if x ∈ l then (l.map f).set (l.idxOf x) y else l.map f := by induction l with | nil => simp | cons hd tl ihl => ?_ rw [nodup_cons] at hl simp only [mem_cons, map, ihl hl.2] by_cases H : hd = x Β· subst hd simp [hl.1] Β· simp [Ne.symm H, H, ← apply_ite (cons (f hd))] theorem Nodup.pairwise_of_forall_ne {l : List Ξ±} {r : Ξ± β†’ Ξ± β†’ Prop} (hl : l.Nodup) (h : βˆ€ a ∈ l, βˆ€ b ∈ l, a β‰  b β†’ r a b) : l.Pairwise r := by grind [List.pairwise_iff_forall_sublist] theorem Nodup.take_eq_filter_mem [DecidableEq Ξ±] : βˆ€ {l : List Ξ±} {n : β„•} (_ : l.Nodup), l.take n = l.filter (l.take n).elem | [], n, _ => by simp | b::l, 0, _ => by simp | b::l, n + 1, hl => by rw [take_succ_cons, Nodup.take_eq_filter_mem (Nodup.of_cons hl), filter_cons_of_pos (by simp)] congr 1 refine List.filter_congr ?_ intro x hx have : x β‰  b := fun h => (nodup_cons.1 hl).1 (h β–Έ hx) simp +contextual [List.mem_filter, this, hx] end List theorem Option.toList_nodup : βˆ€ o : Option Ξ±, o.toList.Nodup | none => List.nodup_nil | some x => List.nodup_singleton x
.lake/packages/mathlib/Mathlib/Data/List/ReduceOption.lean
import Mathlib.Data.List.Basic /-! # Properties of `List.reduceOption` In this file we prove basic lemmas about `List.reduceOption`. -/ namespace List variable {Ξ± Ξ² : Type*} @[simp] theorem reduceOption_cons_of_some (x : Ξ±) (l : List (Option Ξ±)) : reduceOption (some x :: l) = x :: l.reduceOption := by simp only [reduceOption, filterMap, id] @[simp] theorem reduceOption_cons_of_none (l : List (Option Ξ±)) : reduceOption (none :: l) = l.reduceOption := by simp only [reduceOption, filterMap, id] @[simp] theorem reduceOption_nil : @reduceOption Ξ± [] = [] := rfl @[simp] theorem reduceOption_map {l : List (Option Ξ±)} {f : Ξ± β†’ Ξ²} : reduceOption (map (Option.map f) l) = map f (reduceOption l) := by induction l with | nil => simp only [reduceOption_nil, map_nil] | cons hd tl hl => cases hd <;> simpa [Option.map_some, map, eq_self_iff_true, reduceOption_cons_of_some] using hl theorem reduceOption_append (l l' : List (Option Ξ±)) : (l ++ l').reduceOption = l.reduceOption ++ l'.reduceOption := filterMap_append @[simp] theorem reduceOption_replicate_none {n : β„•} : (replicate n (@none Ξ±)).reduceOption = [] := by dsimp [reduceOption] rw [filterMap_replicate_of_none (id_def _)] theorem reduceOption_eq_nil_iff (l : List (Option Ξ±)) : l.reduceOption = [] ↔ βˆƒ n, l = replicate n none := by dsimp [reduceOption] rw [filterMap_eq_nil_iff] constructor Β· intro h exact ⟨l.length, eq_replicate_of_mem h⟩ Β· grind theorem reduceOption_eq_singleton_iff (l : List (Option Ξ±)) (a : Ξ±) : l.reduceOption = [a] ↔ βˆƒ m n, l = replicate m none ++ some a :: replicate n none := by dsimp [reduceOption] constructor Β· intro h rw [filterMap_eq_cons_iff] at h obtain ⟨l₁, _, lβ‚‚, h, hl₁, ⟨⟩, hlβ‚‚βŸ© := h rw [filterMap_eq_nil_iff] at hlβ‚‚ apply eq_replicate_of_mem at hl₁ apply eq_replicate_of_mem at hlβ‚‚ rw [h, hl₁, hlβ‚‚] use l₁.length, lβ‚‚.length Β· intro ⟨_, _, h⟩ simp only [h, filterMap_append, filterMap_cons_some, filterMap_replicate_of_none, id_eq, nil_append, Option.some.injEq] theorem reduceOption_eq_append_iff (l : List (Option Ξ±)) (l'₁ l'β‚‚ : List Ξ±) : l.reduceOption = l'₁ ++ l'β‚‚ ↔ βˆƒ l₁ lβ‚‚, l = l₁ ++ lβ‚‚ ∧ l₁.reduceOption = l'₁ ∧ lβ‚‚.reduceOption = l'β‚‚ := by dsimp [reduceOption] exact filterMap_eq_append_iff theorem reduceOption_eq_concat_iff (l : List (Option Ξ±)) (l' : List Ξ±) (a : Ξ±) : l.reduceOption = l'.concat a ↔ βˆƒ l₁ lβ‚‚, l = l₁ ++ some a :: lβ‚‚ ∧ l₁.reduceOption = l' ∧ lβ‚‚.reduceOption = [] := by rw [concat_eq_append] constructor Β· intro h rw [reduceOption_eq_append_iff] at h obtain ⟨l₁, _, h, hl₁, hlβ‚‚βŸ© := h rw [reduceOption_eq_singleton_iff] at hlβ‚‚ obtain ⟨m, n, hlβ‚‚βŸ© := hlβ‚‚ use l₁ ++ replicate m none, replicate n none simp_rw [h, reduceOption_append, reduceOption_replicate_none, append_assoc, append_nil, hl₁, hlβ‚‚, and_self] Β· intro ⟨_, _, h, hl₁, hlβ‚‚βŸ© rw [h, reduceOption_append, reduceOption_cons_of_some, hl₁, hlβ‚‚] theorem reduceOption_length_eq {l : List (Option Ξ±)} : l.reduceOption.length = (l.filter Option.isSome).length := by induction l with | nil => simp_rw [reduceOption_nil, filter_nil, length] | cons hd tl hl => cases hd <;> simp [hl] theorem length_eq_reduceOption_length_add_filter_none {l : List (Option Ξ±)} : l.length = l.reduceOption.length + (l.filter Option.isNone).length := by simp_rw [reduceOption_length_eq, l.length_eq_length_filter_add Option.isSome, Option.not_isSome] theorem reduceOption_length_le (l : List (Option Ξ±)) : l.reduceOption.length ≀ l.length := by rw [length_eq_reduceOption_length_add_filter_none] apply Nat.le_add_right theorem reduceOption_length_eq_iff {l : List (Option Ξ±)} : l.reduceOption.length = l.length ↔ βˆ€ x ∈ l, Option.isSome x := by rw [reduceOption_length_eq, List.length_filter_eq_length_iff] theorem reduceOption_length_lt_iff {l : List (Option Ξ±)} : l.reduceOption.length < l.length ↔ none ∈ l := by rw [Nat.lt_iff_le_and_ne, and_iff_right (reduceOption_length_le l), Ne, reduceOption_length_eq_iff] induction l Β· simp Β· grind [cases Option] theorem reduceOption_singleton (x : Option Ξ±) : [x].reduceOption = x.toList := by cases x <;> rfl theorem reduceOption_concat (l : List (Option Ξ±)) (x : Option Ξ±) : (l.concat x).reduceOption = l.reduceOption ++ x.toList := by induction l generalizing x with | nil => cases x <;> simp [Option.toList] | cons hd tl hl => simp only [concat_eq_append, reduceOption_append] at hl cases hd <;> simp [hl, reduceOption_append] theorem reduceOption_concat_of_some (l : List (Option Ξ±)) (x : Ξ±) : (l.concat (some x)).reduceOption = l.reduceOption.concat x := by simp only [reduceOption_nil, concat_eq_append, reduceOption_append, reduceOption_cons_of_some] theorem reduceOption_mem_iff {l : List (Option Ξ±)} {x : Ξ±} : x ∈ l.reduceOption ↔ some x ∈ l := by simp only [reduceOption, id, mem_filterMap, exists_eq_right] theorem reduceOption_getElem?_iff {l : List (Option Ξ±)} {x : Ξ±} : (βˆƒ i : β„•, l[i]? = some (some x)) ↔ βˆƒ i : β„•, l.reduceOption[i]? = some x := by rw [← mem_iff_getElem?, ← mem_iff_getElem?, reduceOption_mem_iff] end List
.lake/packages/mathlib/Mathlib/Data/List/Zip.lean
import Mathlib.Data.List.Forall2 import Mathlib.Data.Nat.Basic /-! # zip & unzip This file provides results about `List.zipWith`, `List.zip` and `List.unzip` (definitions are in core Lean). `zipWith f l₁ lβ‚‚` applies `f : Ξ± β†’ Ξ² β†’ Ξ³` pointwise to a list `l₁ : List Ξ±` and `lβ‚‚ : List Ξ²`. It applies, until one of the lists is exhausted. For example, `zipWith f [0, 1, 2] [6.28, 31] = [f 0 6.28, f 1 31]`. `zip` is `zipWith` applied to `Prod.mk`. For example, `zip [a₁, aβ‚‚] [b₁, bβ‚‚, b₃] = [(a₁, b₁), (aβ‚‚, bβ‚‚)]`. `unzip` undoes `zip`. For example, `unzip [(a₁, b₁), (aβ‚‚, bβ‚‚)] = ([a₁, aβ‚‚], [b₁, bβ‚‚])`. -/ -- Make sure we don't import algebra assert_not_exists Monoid universe u open Nat namespace List variable {Ξ± : Type u} {Ξ² Ξ³ Ξ΄ Ξ΅ : Type*} @[simp] theorem zip_swap : βˆ€ (l₁ : List Ξ±) (lβ‚‚ : List Ξ²), (zip l₁ lβ‚‚).map Prod.swap = zip lβ‚‚ l₁ | [], _ => zip_nil_right.symm | l₁, [] => by rw [zip_nil_right]; rfl | a :: l₁, b :: lβ‚‚ => by simp only [zip_cons_cons, map_cons, zip_swap l₁ lβ‚‚, Prod.swap_prod_mk] theorem forall_zipWith {f : Ξ± β†’ Ξ² β†’ Ξ³} {p : Ξ³ β†’ Prop} : βˆ€ {l₁ : List Ξ±} {lβ‚‚ : List Ξ²}, length l₁ = length lβ‚‚ β†’ (Forall p (zipWith f l₁ lβ‚‚) ↔ Forallβ‚‚ (fun x y => p (f x y)) l₁ lβ‚‚) | [], [], _ => by simp | a :: l₁, b :: lβ‚‚, h => by simp only [length_cons, succ_inj] at h simp [forall_zipWith h] theorem unzip_swap (l : List (Ξ± Γ— Ξ²)) : unzip (l.map Prod.swap) = (unzip l).swap := by simp only [unzip_eq_map, map_map] rfl @[congr] theorem zipWith_congr (f g : Ξ± β†’ Ξ² β†’ Ξ³) (la : List Ξ±) (lb : List Ξ²) (h : List.Forallβ‚‚ (fun a b => f a b = g a b) la lb) : zipWith f la lb = zipWith g la lb := by induction h with | nil => rfl | cons hfg _ ih => exact congr_argβ‚‚ _ hfg ih theorem zipWith_zipWith_left (f : Ξ΄ β†’ Ξ³ β†’ Ξ΅) (g : Ξ± β†’ Ξ² β†’ Ξ΄) : βˆ€ (la : List Ξ±) (lb : List Ξ²) (lc : List Ξ³), zipWith f (zipWith g la lb) lc = zipWith3 (fun a b c => f (g a b) c) la lb lc | [], _, _ => rfl | _ :: _, [], _ => rfl | _ :: _, _ :: _, [] => rfl | _ :: as, _ :: bs, _ :: cs => congr_arg (cons _) <| zipWith_zipWith_left f g as bs cs theorem zipWith_zipWith_right (f : Ξ± β†’ Ξ΄ β†’ Ξ΅) (g : Ξ² β†’ Ξ³ β†’ Ξ΄) : βˆ€ (la : List Ξ±) (lb : List Ξ²) (lc : List Ξ³), zipWith f la (zipWith g lb lc) = zipWith3 (fun a b c => f a (g b c)) la lb lc | [], _, _ => rfl | _ :: _, [], _ => rfl | _ :: _, _ :: _, [] => rfl | _ :: as, _ :: bs, _ :: cs => congr_arg (cons _) <| zipWith_zipWith_right f g as bs cs @[simp] theorem zipWith3_same_left (f : Ξ± β†’ Ξ± β†’ Ξ² β†’ Ξ³) : βˆ€ (la : List Ξ±) (lb : List Ξ²), zipWith3 f la la lb = zipWith (fun a b => f a a b) la lb | [], _ => rfl | _ :: _, [] => rfl | _ :: as, _ :: bs => congr_arg (cons _) <| zipWith3_same_left f as bs @[simp] theorem zipWith3_same_mid (f : Ξ± β†’ Ξ² β†’ Ξ± β†’ Ξ³) : βˆ€ (la : List Ξ±) (lb : List Ξ²), zipWith3 f la lb la = zipWith (fun a b => f a b a) la lb | [], _ => rfl | _ :: _, [] => rfl | _ :: as, _ :: bs => congr_arg (cons _) <| zipWith3_same_mid f as bs @[simp] theorem zipWith3_same_right (f : Ξ± β†’ Ξ² β†’ Ξ² β†’ Ξ³) : βˆ€ (la : List Ξ±) (lb : List Ξ²), zipWith3 f la lb lb = zipWith (fun a b => f a b b) la lb | [], _ => rfl | _ :: _, [] => rfl | _ :: as, _ :: bs => congr_arg (cons _) <| zipWith3_same_right f as bs instance (f : Ξ± β†’ Ξ± β†’ Ξ²) [IsSymmOp f] : IsSymmOp (zipWith f) := ⟨fun _ _ => zipWith_comm_of_comm IsSymmOp.symm_op⟩ @[simp] theorem length_revzip (l : List Ξ±) : length (revzip l) = length l := by simp only [revzip, length_zip, length_reverse, min_self] @[simp] theorem unzip_revzip (l : List Ξ±) : (revzip l).unzip = (l, l.reverse) := unzip_zip length_reverse.symm @[simp] theorem revzip_map_fst (l : List Ξ±) : (revzip l).map Prod.fst = l := by rw [← unzip_fst, unzip_revzip] @[simp] theorem revzip_map_snd (l : List Ξ±) : (revzip l).map Prod.snd = l.reverse := by rw [← unzip_snd, unzip_revzip] theorem reverse_revzip (l : List Ξ±) : reverse l.revzip = revzip l.reverse := by rw [← zip_unzip (revzip l).reverse] simp [unzip_eq_map, revzip, map_reverse, map_fst_zip, map_snd_zip] theorem revzip_swap (l : List Ξ±) : (revzip l).map Prod.swap = revzip l.reverse := by simp [revzip] theorem mem_zip_inits_tails {l : List Ξ±} {init tail : List Ξ±} : (init, tail) ∈ zip l.inits l.tails ↔ init ++ tail = l := by induction l generalizing init tail <;> simp_rw [tails, inits, zip_cons_cons] case nil => simp case cons hd tl ih => constructor <;> rw [mem_cons, zip_map_left, mem_map, Prod.exists] Β· rintro (⟨rfl, rfl⟩ | ⟨_, _, h, rfl, rfl⟩) Β· simp Β· simp [ih.mp h] Β· rcases init with - | ⟨hd', tl'⟩ Β· simp Β· intro h right use tl', tail simp_all end List
.lake/packages/mathlib/Mathlib/Data/List/SplitLengths.lean
import Mathlib.Algebra.Group.Nat.Defs import Mathlib.Order.MinMax /-! # Splitting a list to chunks of specified lengths This file defines splitting a list to chunks of given lengths, and some proofs about that. -/ variable {Ξ± : Type*} (l : List Ξ±) (sz : List β„•) namespace List /-- Split a list to chunks of given lengths. -/ def splitLengths : List β„• β†’ List Ξ± β†’ List (List Ξ±) | [], _ => [] | n::ns, x => let (x0, x1) := x.splitAt n x0 :: ns.splitLengths x1 @[simp] theorem length_splitLengths : (sz.splitLengths l).length = sz.length := by induction sz generalizing l <;> simp [splitLengths, *] @[simp] lemma splitLengths_nil : [].splitLengths l = [] := rfl @[simp] lemma splitLengths_cons (n : β„•) : (n :: sz).splitLengths l = l.take n :: sz.splitLengths (l.drop n) := by simp [splitLengths] theorem take_splitLength (i : β„•) : (sz.splitLengths l).take i = (sz.take i).splitLengths l := by induction i generalizing sz l case zero => simp case succ i hi => cases sz Β· simp Β· simp only [splitLengths_cons, take_succ_cons, hi] theorem length_splitLengths_getElem_le {i : β„•} {hi : i < (sz.splitLengths l).length} : (sz.splitLengths l)[i].length ≀ sz[i]'(by simpa using hi) := by induction sz generalizing l i Β· simp at hi case cons head tail tail_ih => simp only [splitLengths_cons] cases i Β· simp Β· simp only [getElem_cons_succ, tail_ih] theorem flatten_splitLengths (h : l.length ≀ sz.sum) : (sz.splitLengths l).flatten = l := by induction sz generalizing l Β· simp_all case cons head tail ih => simp only [splitLengths_cons, flatten_cons] rw [ih, take_append_drop] simpa [add_comm] using h theorem map_splitLengths_length (h : sz.sum ≀ l.length) : (sz.splitLengths l).map length = sz := by induction sz generalizing l Β· simp case cons head tail ih => simp only [sum_cons] at h simp only [splitLengths_cons, map_cons, length_take, cons.injEq, min_eq_left_iff] rw [ih] Β· simp [Nat.le_of_add_right_le h] Β· simp [Nat.le_sub_of_add_le' h] theorem length_splitLengths_getElem_eq {i : β„•} (hi : i < sz.length) (h : (sz.take (i + 1)).sum ≀ l.length) : ((sz.splitLengths l)[i]'(by simpa)).length = sz[i] := by rw [List.getElem_take' (hj := i.lt_add_one)] simp only [take_splitLength] conv_rhs => rw [List.getElem_take' (hj := i.lt_add_one)] simp +singlePass only [← map_splitLengths_length l _ h] rw [getElem_map] theorem splitLengths_length_getElem {Ξ± : Type*} (l : List Ξ±) (sz : List β„•) (h : sz.sum ≀ l.length) (i : β„•) (hi : i < (sz.splitLengths l).length) : (sz.splitLengths l)[i].length = sz[i]'(by simpa using hi) := by have := map_splitLengths_length l sz h rw [← List.getElem_map List.length] Β· simp [this] Β· simpa using hi theorem length_mem_splitLengths {Ξ± : Type*} (l : List Ξ±) (sz : List β„•) (b : β„•) (h : βˆ€ n ∈ sz, n ≀ b) : βˆ€ lβ‚‚ ∈ sz.splitLengths l, lβ‚‚.length ≀ b := by rw [← List.forall_getElem] intro i hi have := length_splitLengths_getElem_le l sz (hi := hi) have := h (sz[i]'(by simpa using hi)) (getElem_mem ..) cutsat end List
.lake/packages/mathlib/Mathlib/Data/List/Count.lean
import Batteries.Data.List.Perm import Mathlib.Tactic.Common /-! # Counting in lists This file proves basic properties of `List.countP` and `List.count`, which count the number of elements of a list satisfying a predicate and equal to a given element respectively. -/ assert_not_exists Monoid Set.range open Nat variable {Ξ± Ξ² : Type*} namespace List @[simp] theorem countP_lt_length_iff {l : List Ξ±} {p : Ξ± β†’ Bool} : l.countP p < l.length ↔ βˆƒ a ∈ l, p a = false := by simp [Nat.lt_iff_le_and_ne, countP_le_length] variable [DecidableEq Ξ±] {l l₁ lβ‚‚ : List Ξ±} @[simp] theorem count_lt_length_iff {a : Ξ±} : l.count a < l.length ↔ βˆƒ b ∈ l, b β‰  a := by simp [count] lemma countP_erase (p : Ξ± β†’ Bool) (l : List Ξ±) (a : Ξ±) : countP p (l.erase a) = countP p l - if a ∈ l ∧ p a then 1 else 0 := by rw [countP_eq_length_filter, countP_eq_length_filter, ← erase_filter, length_erase] aesop lemma count_diff (a : Ξ±) (l₁ : List Ξ±) : βˆ€ lβ‚‚, count a (l₁.diff lβ‚‚) = count a l₁ - count a lβ‚‚ | [] => rfl | b :: lβ‚‚ => by simp only [diff_cons, count_diff, count_erase, beq_iff_eq, Nat.sub_right_comm, count_cons, Nat.sub_add_eq] lemma countP_diff (hl : lβ‚‚ <+~ l₁) (p : Ξ± β†’ Bool) : countP p (l₁.diff lβ‚‚) = countP p l₁ - countP p lβ‚‚ := by refine (Nat.sub_eq_of_eq_add ?_).symm rw [← countP_append] exact ((subperm_append_diff_self_of_count_le <| subperm_ext_iff.1 hl).symm.trans perm_append_comm).countP_eq _ @[simp] theorem count_map_of_injective [DecidableEq Ξ²] (l : List Ξ±) (f : Ξ± β†’ Ξ²) (hf : Function.Injective f) (x : Ξ±) : count (f x) (map f l) = count x l := by simp only [count, countP_map] unfold Function.comp simp only [hf.beq_eq] end List
.lake/packages/mathlib/Mathlib/Data/List/Chain.lean
import Mathlib.Data.List.Forall2 import Mathlib.Data.List.Induction import Mathlib.Data.List.Lex import Mathlib.Logic.Function.Iterate import Mathlib.Logic.Relation /-! # Relation chain This file provides basic results about `List.IsChain` from betteries. A list `[a₁, aβ‚‚, ..., aβ‚™]` satifies `IsChain` with respect to the relation `r` if `r a₁ aβ‚‚` and `r aβ‚‚ a₃` and ... and `r aₙ₋₁ aβ‚™`. We write it `IsChain r [a₁, aβ‚‚, ..., aβ‚™]`. A graph-specialized version is in development and will hopefully be added under `combinatorics.` sometime soon. -/ assert_not_imported Mathlib.Algebra.Order.Group.Nat universe u v open Nat namespace List variable {Ξ± : Type u} {Ξ² : Type v} {R r : Ξ± β†’ Ξ± β†’ Prop} {l l₁ lβ‚‚ : List Ξ±} {a b : Ξ±} mk_iff_of_inductive_prop List.IsChain List.isChain_iff theorem isChain_nil : IsChain R [] := .nil theorem isChain_singleton (a : Ξ±) : IsChain R [a] := .singleton _ @[deprecated (since := "2025-09-24")] alias chain'_nil := isChain_nil @[deprecated (since := "2025-09-24")] alias chain'_singleton := isChain_singleton @[deprecated (since := "2025-09-24")] alias chain'_cons_cons := isChain_cons_cons @[deprecated (since := "2025-08-12")] alias chain'_cons := isChain_cons_cons @[deprecated (since := "2025-09-24"), nolint defLemma] alias Chain'.cons_cons := IsChain.cons_cons @[deprecated (since := "2025-09-24"), nolint defLemma] alias Chain'.cons := IsChain.cons_cons theorem isChain_cons_iff (R : Ξ± β†’ Ξ± β†’ Prop) (a : Ξ±) (l : List Ξ±) : IsChain R (a :: l) ↔ l = [] ∨ βˆƒ (b : Ξ±) (l' : List Ξ±), R a b ∧ IsChain R (b :: l') ∧ l = b :: l' := (isChain_iff _ _).trans <| by simp only [cons_ne_nil, List.cons_eq_cons, exists_and_right, exists_eq', true_and, exists_and_left, false_or] grind @[deprecated (since := "2025-09-24")] alias chain_iff := isChain_cons_iff theorem IsChain.imp_of_mem_tail_imp {S : Ξ± β†’ Ξ± β†’ Prop} {l : List Ξ±} (H : βˆ€ a b : Ξ±, a ∈ l β†’ b ∈ l.tail β†’ R a b β†’ S a b) (p : IsChain R l) : IsChain S l := by induction p with grind theorem IsChain.imp_of_mem_imp {S : Ξ± β†’ Ξ± β†’ Prop} {l : List Ξ±} (H : βˆ€ a b : Ξ±, a ∈ l β†’ b ∈ l β†’ R a b β†’ S a b) (p : IsChain R l) : IsChain S l := p.imp_of_mem_tail_imp (H Β· Β· Β· <| mem_of_mem_tail Β·) theorem IsChain.iff {S : Ξ± β†’ Ξ± β†’ Prop} (H : βˆ€ a b, R a b ↔ S a b) {l : List Ξ±} : IsChain R l ↔ IsChain S l := ⟨IsChain.imp fun a b => (H a b).1, IsChain.imp fun a b => (H a b).2⟩ @[deprecated (since := "2025-09-24")] alias Chain.iff := IsChain.iff @[deprecated (since := "2025-09-24")] alias Chain'.imp := IsChain.imp @[deprecated (since := "2025-09-24")] alias Chain'.iff := IsChain.iff theorem IsChain.iff_of_mem_imp {S : Ξ± β†’ Ξ± β†’ Prop} {l : List Ξ±} (H : βˆ€ a b : Ξ±, a ∈ l β†’ b ∈ l β†’ (R a b ↔ S a b)) : IsChain R l ↔ IsChain S l := ⟨IsChain.imp_of_mem_imp (Iff.mp <| H Β· Β· Β· Β·), IsChain.imp_of_mem_imp (Iff.mpr <| H Β· Β· Β· Β·)⟩ theorem IsChain.iff_of_mem_tail_imp {S : Ξ± β†’ Ξ± β†’ Prop} {l : List Ξ±} (H : βˆ€ a b : Ξ±, a ∈ l β†’ b ∈ l.tail β†’ (R a b ↔ S a b)) : IsChain R l ↔ IsChain S l := ⟨IsChain.imp_of_mem_tail_imp (Iff.mp <| H Β· Β· Β· Β·), IsChain.imp_of_mem_tail_imp (Iff.mpr <| H Β· Β· Β· Β·)⟩ theorem IsChain.iff_mem {l : List Ξ±} : IsChain R l ↔ IsChain (fun x y => x ∈ l ∧ y ∈ l ∧ R x y) l := IsChain.iff_of_mem_imp <| by grind theorem IsChain.iff_mem_mem_tail {l : List Ξ±} : IsChain R l ↔ IsChain (fun x y => x ∈ l ∧ y ∈ l.tail ∧ R x y) l := IsChain.iff_of_mem_tail_imp <| by grind @[deprecated (since := "2025-09-24")] alias Chain'.iff_mem := IsChain.iff_mem @[deprecated (since := "2025-09-24")] alias Chain.iff_mem := IsChain.iff_mem_mem_tail theorem isChain_pair {x y} : IsChain R [x, y] ↔ R x y := by simp only [IsChain.singleton, isChain_cons_cons, and_true] @[deprecated (since := "2025-09-24")] alias chain_singleton := isChain_pair @[deprecated (since := "2025-09-24")] alias chain'_pair := isChain_pair theorem isChain_isInfix : βˆ€ l : List Ξ±, IsChain (fun x y => [x, y] <:+: l) l | [] => .nil | [_] => .singleton _ | a :: b :: l => .cons_cons ⟨[], l, by simp⟩ ((isChain_isInfix (b :: l)).imp fun _ _ h => h.trans ⟨[a], [], by simp⟩) @[deprecated (since := "2025-09-24")] alias chain'_isInfix := isChain_isInfix theorem isChain_split {c : Ξ±} {l₁ lβ‚‚ : List Ξ±} : IsChain R (l₁ ++ c :: lβ‚‚) ↔ IsChain R (l₁ ++ [c]) ∧ IsChain R (c :: lβ‚‚) := by induction l₁ using twoStepInduction generalizing lβ‚‚ with grind @[deprecated (since := "2025-09-24")] alias chain'_split := isChain_split theorem isChain_cons_split {c : Ξ±} {l₁ lβ‚‚ : List Ξ±} : IsChain R (a :: (l₁ ++ c :: lβ‚‚)) ↔ IsChain R (a :: (l₁ ++ [c])) ∧ IsChain R (c :: lβ‚‚) := by simp_rw [← cons_append, isChain_split (lβ‚‚ := lβ‚‚)] @[deprecated (since := "2025-09-19")] alias chain_split := isChain_cons_split @[simp] theorem isChain_append_cons_cons {b c : Ξ±} {l₁ lβ‚‚ : List Ξ±} : IsChain R (l₁ ++ b :: c :: lβ‚‚) ↔ IsChain R (l₁ ++ [b]) ∧ R b c ∧ IsChain R (c :: lβ‚‚) := by rw [isChain_split, isChain_cons_cons] @[deprecated (since := "2025-09-24")] alias chain'_append_cons_cons := isChain_append_cons_cons @[simp] theorem isChain_cons_append_cons_cons {a b c : Ξ±} {l₁ lβ‚‚ : List Ξ±} : IsChain R (a :: (l₁ ++ b :: c :: lβ‚‚)) ↔ IsChain R (a :: (l₁ ++ [b])) ∧ R b c ∧ IsChain R (c :: lβ‚‚) := by rw [isChain_cons_split, isChain_cons_cons] @[deprecated (since := "2025-09-19")] alias chain_append_cons_cons := isChain_cons_append_cons_cons theorem isChain_iff_forall_rel_of_append_cons_cons {l : List Ξ±} : IsChain R l ↔ βˆ€ ⦃a b l₁ l₂⦄, l = l₁ ++ a :: b :: lβ‚‚ β†’ R a b := by refine ⟨fun h _ _ _ _ eq => (isChain_append_cons_cons.mp (eq β–Έ h)).2.1, ?_⟩ induction l using twoStepInduction with | nil | singleton => grind | cons_cons head head' tail _ ih => refine fun h ↦ isChain_cons_cons.mpr ⟨h (nil_append _).symm, ih _ fun ⦃a b l₁ l₂⦄ eq => ?_⟩ apply h rw [eq, cons_append] @[deprecated (since := "2025-09-24")] alias chain'_iff_forall_rel_of_append_cons_cons := isChain_append_cons_cons theorem isChain_iff_forallβ‚‚ {l : List Ξ±} : IsChain R l ↔ Forallβ‚‚ R l.dropLast l.tail := by induction l using twoStepInduction <;> simp_all theorem isChain_cons_iff_forallβ‚‚ : IsChain R (a :: l) ↔ l = [] ∨ Forallβ‚‚ R (a :: dropLast l) l := by cases l <;> simp [isChain_iff_forallβ‚‚] @[deprecated (since := "2025-09-24")] alias chain_iff_forallβ‚‚ := isChain_cons_iff_forallβ‚‚ theorem isChain_cons_append_singleton_iff_forallβ‚‚ : IsChain R (a :: l ++ [b]) ↔ Forallβ‚‚ R (a :: l) (l ++ [b]) := by simp_rw [isChain_iff_forallβ‚‚, dropLast_concat, cons_append, tail_cons] @[deprecated (since := "2025-09-24")] alias chain_append_singleton_iff_forallβ‚‚ := isChain_cons_append_singleton_iff_forallβ‚‚ theorem isChain_map (f : Ξ² β†’ Ξ±) {l : List Ξ²} : IsChain R (map f l) ↔ IsChain (fun a b : Ξ² => R (f a) (f b)) l := by induction l using twoStepInduction <;> grind @[deprecated (since := "2025-09-24")] alias chain'_map := isChain_map theorem isChain_of_isChain_map {S : Ξ² β†’ Ξ² β†’ Prop} (f : Ξ± β†’ Ξ²) (H : βˆ€ a b : Ξ±, S (f a) (f b) β†’ R a b) {l : List Ξ±} (p : IsChain S (map f l)) : IsChain R l := ((isChain_map f).1 p).imp H @[deprecated (since := "2025-09-24")] alias chain'_of_chain'_map := isChain_of_isChain_map theorem isChain_map_of_isChain {S : Ξ² β†’ Ξ² β†’ Prop} (f : Ξ± β†’ Ξ²) (H : βˆ€ a b : Ξ±, R a b β†’ S (f a) (f b)) {l : List Ξ±} (p : IsChain R l) : IsChain S (map f l) := (isChain_map f).2 <| p.imp H @[deprecated (since := "2025-09-24")] alias chain'_map_of_chain' := isChain_map_of_isChain theorem isChain_cons_map (f : Ξ² β†’ Ξ±) {l : List Ξ²} {b : Ξ²} : IsChain R (f b :: map f l) ↔ IsChain (fun a b : Ξ² => R (f a) (f b)) (b :: l) := isChain_map f (l := b :: l) theorem isChain_cons_of_isChain_cons_map {S : Ξ² β†’ Ξ² β†’ Prop} (f : Ξ± β†’ Ξ²) (H : βˆ€ a b : Ξ±, S (f a) (f b) β†’ R a b) {l : List Ξ±} (p : IsChain S (f a :: map f l)) : IsChain R (a :: l) := ((isChain_cons_map f).1 p).imp H theorem isChain_cons_map_of_isChain_cons {S : Ξ² β†’ Ξ² β†’ Prop} (f : Ξ± β†’ Ξ²) (H : βˆ€ a b : Ξ±, R a b β†’ S (f a) (f b)) {l : List Ξ±} (p : IsChain R (a :: l)) : IsChain S (f a :: map f l) := (isChain_cons_map f).2 <| p.imp H @[deprecated (since := "2025-09-19")] alias chain_map := isChain_cons_map @[deprecated (since := "2025-09-19")] alias chain_of_chain_map := isChain_cons_of_isChain_cons_map @[deprecated (since := "2025-09-19")] alias chain_map_of_chain := isChain_cons_map_of_isChain_cons theorem isChain_pmap {S : Ξ² β†’ Ξ² β†’ Prop} {p : Ξ± β†’ Prop} (f : βˆ€ a, p a β†’ Ξ²) {l : List Ξ±} (hl : βˆ€ a ∈ l, p a) : IsChain S (pmap f l hl) ↔ IsChain (fun a b => βˆƒ ha, βˆƒ hb, S (f a ha) (f b hb)) l := by induction l using twoStepInduction <;> grind theorem isChain_pmap_of_isChain {S : Ξ² β†’ Ξ² β†’ Prop} {p : Ξ± β†’ Prop} {f : βˆ€ a, p a β†’ Ξ²} (H : βˆ€ a b ha hb, R a b β†’ S (f a ha) (f b hb)) {l : List Ξ±} (hl₁ : IsChain R l) (hlβ‚‚ : βˆ€ a ∈ l, p a) : IsChain S (pmap f l hlβ‚‚) := (isChain_pmap f _).2 <| hl₁.imp_of_mem_imp (by grind) theorem isChain_of_isChain_pmap {S : Ξ² β†’ Ξ² β†’ Prop} {p : Ξ± β†’ Prop} (f : βˆ€ a, p a β†’ Ξ²) {l : List Ξ±} (hl₁ : βˆ€ a ∈ l, p a) (hlβ‚‚ : IsChain S (pmap f l hl₁)) (H : βˆ€ a b ha hb, S (f a ha) (f b hb) β†’ R a b) : IsChain R l := ((isChain_pmap f _).1 hlβ‚‚).imp (by grind) theorem isChain_cons_pmap {p : Ξ² β†’ Prop} (f : βˆ€ b, p b β†’ Ξ±) {l : List Ξ²} (hl : βˆ€ b ∈ l, p b) {a} (ha) : IsChain R (f a ha :: pmap f l hl) ↔ IsChain (fun a b => βˆƒ ha, βˆƒ hb, R (f a ha) (f b hb)) (a :: l) := isChain_pmap (l := a :: _) f (by grind) theorem isChain_cons_pmap_of_isChain_cons {S : Ξ² β†’ Ξ² β†’ Prop} {p : Ξ± β†’ Prop} {f : βˆ€ a, p a β†’ Ξ²} (H : βˆ€ a b ha hb, R a b β†’ S (f a ha) (f b hb)) {l : List Ξ±} {a} (ha) (hl₁ : IsChain R (a :: l)) (hlβ‚‚ : βˆ€ a ∈ l, p a) : IsChain S (f a ha :: pmap f l hlβ‚‚) := (isChain_cons_pmap f _ _).2 <| hl₁.imp_of_mem_imp (by grind) theorem isChain_cons_of_isChain_cons_pmap {S : Ξ² β†’ Ξ² β†’ Prop} {p : Ξ± β†’ Prop} (f : βˆ€ a, p a β†’ Ξ²) {l : List Ξ±} (hl₁ : βˆ€ a ∈ l, p a) {a} (ha) (hlβ‚‚ : IsChain S (f a ha :: pmap f l hl₁)) (H : βˆ€ a b ha hb, S (f a ha) (f b hb) β†’ R a b) : IsChain R (a :: l) := ((isChain_cons_pmap f _ _).1 hlβ‚‚).imp (by grind) @[deprecated (since := "2025-09-19")] alias chain_pmap_of_chain := isChain_cons_pmap_of_isChain_cons @[deprecated (since := "2025-09-19")] alias chain_of_chain_pmap := isChain_cons_of_isChain_cons_pmap @[deprecated (since := "2025-09-19")] alias Chain.pairwise := IsChain.pairwise @[deprecated (since := "2025-09-24")] alias Pairwise.chain' := Pairwise.isChain @[deprecated (since := "2025-09-19")] alias chain_iff_pairwise := isChain_iff_pairwise @[deprecated (since := "2025-09-24")] alias chain'_iff_pairwise := isChain_iff_pairwise protected theorem IsChain.sublist [Trans R R R] (hl : lβ‚‚.IsChain R) (h : l₁ <+ lβ‚‚) : l₁.IsChain R := by rw [isChain_iff_pairwise] at hl ⊒ exact hl.sublist h @[deprecated "Use `IsChain.sublist` combined with `Sublist.cons_cons`" (since := "2025-09-19")] alias Chain.sublist := IsChain.sublist @[deprecated (since := "2025-09-24")] alias Chain'.sublist := IsChain.sublist protected theorem IsChain.rel_cons [Trans R R R] (hl : (a :: l).IsChain R) (hb : b ∈ l) : R a b := by rw [isChain_iff_pairwise] at hl exact rel_of_pairwise_cons hl hb @[deprecated (since := "2025-09-19")] alias Chain.rel := IsChain.rel_cons theorem IsChain.of_cons {x} : βˆ€ {l : List Ξ±}, IsChain R (x :: l) β†’ IsChain R l | [] => fun _ => IsChain.nil | _ :: _ => fun | .cons_cons _ h => h theorem IsChain.tail {l : List Ξ±} (h : IsChain R l) : IsChain R l.tail := by cases l Β· exact IsChain.nil Β· exact h.of_cons @[deprecated (since := "2025-09-24")] alias Chain'.tail := IsChain.tail theorem IsChain.rel_head {x y l} (h : IsChain R (x :: y :: l)) : R x y := List.rel_of_isChain_cons_cons h @[deprecated (since := "2025-09-24")] alias Chain'.rel_head := IsChain.rel_head theorem IsChain.rel_head? {x l} (h : IsChain R (x :: l)) ⦃y⦄ (hy : y ∈ head? l) : R x y := by rw [← cons_head?_tail hy] at h exact h.rel_head @[deprecated (since := "2025-09-24")] alias Chain'.rel_head? := IsChain.rel_head? theorem IsChain.cons {x} : βˆ€ {l : List Ξ±}, IsChain R l β†’ (βˆ€ y ∈ l.head?, R x y) β†’ IsChain R (x :: l) | [], _, _ => .singleton x | _ :: _, hl, H => hl.cons_cons <| H _ rfl @[deprecated (since := "2025-10-16")] alias IsChain.cons' := IsChain.cons @[deprecated (since := "2025-09-24")] alias Chain'.cons' := IsChain.cons lemma IsChain.cons_of_ne_nil {x : Ξ±} {l : List Ξ±} (l_ne_nil : l β‰  []) (hl : IsChain R l) (h : R x (l.head l_ne_nil)) : IsChain R (x :: l) := by refine hl.cons fun y hy ↦ ?_ convert h simpa [l.head?_eq_head l_ne_nil] using hy.symm @[deprecated (since := "2025-09-24")] alias Chain'.cons_of_ne_nil := IsChain.cons_of_ne_nil theorem isChain_cons {x l} : IsChain R (x :: l) ↔ (βˆ€ y ∈ head? l, R x y) ∧ IsChain R l := ⟨fun h => ⟨h.rel_head?, h.tail⟩, fun ⟨h₁, hβ‚‚βŸ© => hβ‚‚.cons hβ‚βŸ© @[deprecated (since := "2025-10-16")] alias isChain_cons' := isChain_cons @[deprecated (since := "2025-09-24")] alias chain'_cons' := isChain_cons theorem isChain_append : βˆ€ {l₁ lβ‚‚ : List Ξ±}, IsChain R (l₁ ++ lβ‚‚) ↔ IsChain R l₁ ∧ IsChain R lβ‚‚ ∧ βˆ€ x ∈ l₁.getLast?, βˆ€ y ∈ lβ‚‚.head?, R x y | [], l => by simp | [a], l => by simp [isChain_cons, and_comm] | a :: b :: l₁, lβ‚‚ => by rw [cons_append, cons_append, isChain_cons_cons, isChain_cons_cons, ← cons_append, isChain_append, and_assoc] simp @[deprecated (since := "2025-09-24")] alias chain'_append := isChain_append theorem IsChain.append (h₁ : IsChain R l₁) (hβ‚‚ : IsChain R lβ‚‚) (h : βˆ€ x ∈ l₁.getLast?, βˆ€ y ∈ lβ‚‚.head?, R x y) : IsChain R (l₁ ++ lβ‚‚) := isChain_append.2 ⟨h₁, hβ‚‚, h⟩ theorem IsChain.left_of_append (h : IsChain R (l₁ ++ lβ‚‚)) : IsChain R l₁ := (isChain_append.1 h).1 theorem IsChain.right_of_append (h : IsChain R (l₁ ++ lβ‚‚)) : IsChain R lβ‚‚ := (isChain_append.1 h).2.1 @[deprecated (since := "2025-09-24")] alias Chain'.append := isChain_append @[deprecated (since := "2025-09-24")] alias Chain'.left_of_append := IsChain.left_of_append @[deprecated (since := "2025-09-24")] alias Chain'.right_of_append := IsChain.right_of_append theorem IsChain.infix (h : IsChain R l) (h' : l₁ <:+: l) : IsChain R l₁ := by rcases h' with ⟨lβ‚‚, l₃, rfl⟩ exact h.left_of_append.right_of_append @[deprecated (since := "2025-09-24")] alias Chain'.infix := IsChain.infix theorem IsChain.suffix (h : IsChain R l) (h' : l₁ <:+ l) : IsChain R l₁ := h.infix h'.isInfix @[deprecated (since := "2025-09-24")] alias Chain'.suffix := IsChain.suffix theorem IsChain.prefix (h : IsChain R l) (h' : l₁ <+: l) : IsChain R l₁ := h.infix h'.isInfix @[deprecated (since := "2025-09-24")] alias Chain'.prefix := IsChain.prefix theorem IsChain.drop (h : IsChain R l) (n : β„•) : IsChain R (drop n l) := h.suffix (drop_suffix _ _) @[deprecated (since := "2025-09-24")] alias Chain'.drop := IsChain.drop theorem IsChain.dropLast (h : IsChain R l) : IsChain R l.dropLast := h.prefix l.dropLast_prefix @[deprecated (since := "2025-09-24")] alias Chain'.init := IsChain.dropLast theorem IsChain.take (h : IsChain R l) (n : β„•) : IsChain R (take n l) := h.prefix (take_prefix _ _) @[deprecated (since := "2025-09-24")] alias Chain'.take := IsChain.take theorem IsChain.imp_head {x y} (h : βˆ€ {z}, R x z β†’ R y z) {l} (hl : IsChain R (x :: l)) : IsChain R (y :: l) := IsChain.cons_of_imp_of_cons @h hl @[deprecated (since := "2025-09-24")] alias Chain'.getElem := IsChain.getElem theorem isChain_iff_get {R} : βˆ€ {l : List Ξ±}, IsChain R l ↔ βˆ€ (i : β„•) (h : i + 1 < l.length), R (get l ⟨i, by cutsat⟩) (get l ⟨i + 1, h⟩) := by simp [isChain_iff_getElem] @[deprecated (since := "2025-09-24")] alias chain'_iff_forall_getElem := isChain_iff_getElem @[deprecated (since := "2025-09-24")] alias chain'_iff_get := isChain_iff_get theorem isChain_cons_iff_get {R} {a : Ξ±} {l : List Ξ±} : IsChain R (a :: l) ↔ (βˆ€ h : 0 < length l, R a (get l ⟨0, h⟩)) ∧ βˆ€ (i : β„•) (h : i < l.length - 1), R (get l ⟨i, by cutsat⟩) (get l ⟨i+1, by cutsat⟩) := by cases l <;> grind [isChain_iff_get] theorem exists_not_getElem_of_not_isChain (h : Β¬List.IsChain R l) : βˆƒ n : β„•, βˆƒ h : n + 1 < l.length, Β¬R l[n] l[n + 1] := by simp_all [isChain_iff_getElem] @[deprecated (since := "2025-09-19")] alias chain'_of_not := exists_not_getElem_of_not_isChain @[deprecated (since := "2025-09-19")] alias chain_iff_get := isChain_cons_iff_get theorem isChain_reverse {l : List Ξ±} : IsChain R (reverse l) ↔ IsChain (flip R) l := by induction l using twoStepInduction with | nil => grind | singleton a => grind | cons_cons a b l IH IH2 => rw [isChain_cons_cons, reverse_cons, reverse_cons, append_assoc, cons_append, nil_append, isChain_split, ← reverse_cons, IH2, and_comm, isChain_pair, flip] @[deprecated (since := "2025-09-24")] alias chain'_reverse := isChain_reverse /-- If `l₁ lβ‚‚` and `l₃` are lists and `l₁ ++ lβ‚‚` and `lβ‚‚ ++ l₃` both satisfy `IsChain R`, then so does `l₁ ++ lβ‚‚ ++ l₃` provided `lβ‚‚ β‰  []` -/ theorem IsChain.append_overlap {l₁ lβ‚‚ l₃ : List Ξ±} (h₁ : IsChain R (l₁ ++ lβ‚‚)) (hβ‚‚ : IsChain R (lβ‚‚ ++ l₃)) (hn : lβ‚‚ β‰  []) : IsChain R (l₁ ++ lβ‚‚ ++ l₃) := h₁.append hβ‚‚.right_of_append <| by simpa only [getLast?_append_of_ne_nil _ hn] using (isChain_append.1 hβ‚‚).2.2 @[deprecated (since := "2025-09-24")] alias Chain'.append_overlap := IsChain.append_overlap lemma isChain_flatten : βˆ€ {L : List (List Ξ±)}, [] βˆ‰ L β†’ (IsChain R L.flatten ↔ (βˆ€ l ∈ L, IsChain R l) ∧ L.IsChain (fun l₁ lβ‚‚ => βˆ€α΅‰ (x ∈ l₁.getLast?) (y ∈ lβ‚‚.head?), R x y)) | [], _ => by simp | [l], _ => by simp [flatten] | (l₁ :: lβ‚‚ :: L), hL => by rw [mem_cons, not_or, ← Ne] at hL rw [flatten_cons, isChain_append, isChain_flatten hL.2, forall_mem_cons, isChain_cons_cons] rw [mem_cons, not_or, ← Ne] at hL simp only [forall_mem_cons, and_assoc, flatten_cons, head?_append_of_ne_nil _ hL.2.1.symm] exact Iff.rfl.and (Iff.rfl.and <| Iff.rfl.and and_comm) @[deprecated (since := "2025-09-24")] alias chain'_flatten := isChain_flatten theorem isChain_attachWith {l : List Ξ±} {p : Ξ± β†’ Prop} (h : βˆ€ x ∈ l, p x) {r : {a // p a} β†’ {a // p a} β†’ Prop} : (l.attachWith p h).IsChain r ↔ l.IsChain fun a b ↦ βˆƒ ha hb, r ⟨a, ha⟩ ⟨b, hb⟩ := by induction l with | nil => grind | cons a l IH => rw [attachWith_cons, isChain_cons, isChain_cons, IH, and_congr_left] simp_rw [head?_attachWith] intros constructor <;> intro hc b (hb : _ = _) Β· simp_rw [hb, Option.pbind_some] at hc have hb' := h b (mem_cons_of_mem a (mem_of_mem_head? hb)) exact ⟨h a mem_cons_self, hb', hc ⟨b, hb'⟩ rfl⟩ Β· cases l <;> aesop @[deprecated (since := "2025-09-24")] alias chain'_attachWith := isChain_attachWith theorem isChain_attach {l : List Ξ±} {r : {a // a ∈ l} β†’ {a // a ∈ l} β†’ Prop} : l.attach.IsChain r ↔ l.IsChain fun a b ↦ βˆƒ ha hb, r ⟨a, ha⟩ ⟨b, hb⟩ := isChain_attachWith fun _ ↦ id @[deprecated (since := "2025-09-24")] alias chain'_attach := isChain_attach /-- If `a` and `b` are related by the reflexive transitive closure of `r`, then there is an `r`-chain starting from `a` and ending on `b`. -/ theorem exists_isChain_cons_of_relationReflTransGen (h : Relation.ReflTransGen r a b) : βˆƒ l, IsChain r (a :: l) ∧ getLast (a :: l) (cons_ne_nil _ _) = b := by refine Relation.ReflTransGen.head_induction_on h ?_ ?_ Β· exact ⟨[], .singleton _, rfl⟩ Β· intro c d e _ ih obtain ⟨l, hl₁, hlβ‚‚βŸ© := ih refine ⟨d :: l, .cons_cons e hl₁, ?_⟩ rwa [getLast_cons_cons] @[deprecated (since := "2025-09-22")] alias exists_chain_of_relationReflTransGen := exists_isChain_cons_of_relationReflTransGen /-- If `a` and `b` are related by the reflexive transitive closure of `r`, then there is an `r`-chain starting from `a` and ending on `b`. -/ theorem exists_isChain_ne_nil_of_relationReflTransGen (h : Relation.ReflTransGen r a b) : βˆƒ l, βˆƒ (hl : l β‰  []), IsChain r l ∧ l.head hl = a ∧ getLast l hl = b := by rcases exists_isChain_cons_of_relationReflTransGen h with ⟨l, _⟩; grind /-- Given a chain `l`, such that a predicate `p` holds for its head if it is nonempty, and if `r x y β†’ p x β†’ p y`, then the predicate is true everywhere in the chain. That is, we can propagate the predicate down the chain. -/ theorem IsChain.induction (p : Ξ± β†’ Prop) (l : List Ξ±) (h : IsChain r l) (carries : βˆ€ ⦃x y : α⦄, r x y β†’ p x β†’ p y) (initial : (lne : l β‰  []) β†’ p (l.head lne)) : βˆ€ i ∈ l, p i := by induction l using twoStepInduction with grind @[deprecated (since := "2025-09-24")] alias Chain'.induction := IsChain.induction /-- Given a chain from `a` to `b`, and a predicate true at `a`, if `r x y β†’ p x β†’ p y` then the predicate is true everywhere in the chain. That is, we can propagate the predicate down the chain. -/ theorem IsChain.cons_induction (p : Ξ± β†’ Prop) (l : List Ξ±) (h : IsChain r (a :: l)) (carries : βˆ€ ⦃x y : α⦄, r x y β†’ p x β†’ p y) (initial : p a) : βˆ€ i ∈ l, p i := fun _ hi => h.induction _ _ carries (fun _ => initial) _ (mem_cons_of_mem _ hi) @[deprecated (since := "2025-09-24")] alias Chain.induction := IsChain.cons_induction theorem IsChain.concat_induction (p : Ξ± β†’ Prop) (l : List Ξ±) (h : IsChain r (l ++ [b])) (hb : head (l ++ [b]) (concat_ne_nil _ _) = a) (carries : βˆ€ ⦃x y : α⦄, r x y β†’ p x β†’ p y) (initial : p a) : βˆ€ i ∈ l ++ [b], p i := h.induction _ _ carries (fun _ => hb β–Έ initial) @[elab_as_elim] theorem IsChain.concat_induction_head (p : Ξ± β†’ Prop) (l : List Ξ±) (h : IsChain r (l ++ [b])) (hb : head (l ++ [b]) (concat_ne_nil _ _) = a) (carries : βˆ€ ⦃x y : α⦄, r x y β†’ p x β†’ p y) (initial : p a) : p b := (IsChain.concat_induction p l h hb carries initial) _ mem_concat_self /-- Given a chain from `a` to `b`, and a predicate true at `b`, if `r x y β†’ p y β†’ p x` then the predicate is true everywhere in the chain and at `a`. That is, we can propagate the predicate up the chain. -/ theorem IsChain.backwards_induction (p : Ξ± β†’ Prop) (l : List Ξ±) (h : IsChain r l) (carries : βˆ€ ⦃x y : α⦄, r x y β†’ p y β†’ p x) (final : (lne : l β‰  []) β†’ p (getLast l lne)) : βˆ€ i ∈ l, p i := by have H : IsChain (flip (flip r)) l := h replace H := (isChain_reverse.mpr H).induction _ _ (fun _ _ h ↦ carries h) grind /-- Given a chain from `a` to `b`, and a predicate true at `b`, if `r x y β†’ p y β†’ p x` then the predicate is true everywhere in the chain and at `a`. That is, we can propagate the predicate up the chain. -/ theorem IsChain.backwards_concat_induction (p : Ξ± β†’ Prop) (l : List Ξ±) (h : IsChain r (l ++ [b])) (carries : βˆ€ ⦃x y : α⦄, r x y β†’ p y β†’ p x) (final : p b) : βˆ€ i ∈ l, p i := fun _ hi => h.backwards_induction _ _ carries (fun _ => getLast_concat β–Έ final) _ (mem_append_left _ hi) theorem IsChain.backwards_cons_induction (p : Ξ± β†’ Prop) (l : List Ξ±) (h : IsChain r (a :: l)) (hb : getLast (a :: l) (cons_ne_nil _ _) = b) (carries : βˆ€ ⦃x y : α⦄, r x y β†’ p y β†’ p x) (final : p b) : βˆ€ i ∈ a :: l, p i := h.backwards_induction _ _ carries (fun _ => hb β–Έ final) @[deprecated (since := "2025-09-24")] alias Chain.backwards_induction := IsChain.backwards_cons_induction /-- Given a chain from `a` to `b`, and a predicate true at `b`, if `r x y β†’ p y β†’ p x` then the predicate is true at `a`. That is, we can propagate the predicate all the way up the chain. -/ @[elab_as_elim] theorem IsChain.backwards_cons_induction_head (p : Ξ± β†’ Prop) (l : List Ξ±) (h : IsChain r (a :: l)) (hb : getLast (a :: l) (cons_ne_nil _ _) = b) (carries : βˆ€ ⦃x y : α⦄, r x y β†’ p y β†’ p x) (final : p b) : p a := (IsChain.backwards_cons_induction p l h hb carries final) _ mem_cons_self @[deprecated (since := "2025-09-24")] alias Chain.backwards_induction_head := IsChain.backwards_cons_induction_head /-- If there is an non-empty `r`-chain, its head and last element are related by the reflexive transitive closure of `r`. -/ theorem relationReflTransGen_of_exists_isChain (l : List Ξ±) (hl₁ : IsChain r l) (hne : l β‰  []) : Relation.ReflTransGen r (head l hne) (getLast l hne) := IsChain.induction (Relation.ReflTransGen r (head l hne) Β·) l hl₁ (fun _ _ h₁ hβ‚‚ => Trans.trans hβ‚‚ h₁) (fun _ => Relation.ReflTransGen.refl) _ (getLast_mem _) /-- If there is an `r`-chain starting from `a` and ending at `b`, then `a` and `b` are related by the reflexive transitive closure of `r`. -/ theorem relationReflTransGen_of_exists_isChain_cons (l : List Ξ±) (hl₁ : IsChain r (a :: l)) (hlβ‚‚ : getLast (a :: l) (cons_ne_nil _ _) = b) : Relation.ReflTransGen r a b := IsChain.backwards_cons_induction_head _ l hl₁ hlβ‚‚ (fun _ _ => Relation.ReflTransGen.head) Relation.ReflTransGen.refl @[deprecated (since := "2025-09-24")] alias relationReflTransGen_of_exists_chain_cons := relationReflTransGen_of_exists_isChain_cons theorem IsChain.cons_of_le [LinearOrder Ξ±] {a : Ξ±} {as m : List Ξ±} (ha : List.IsChain (Β· > Β·) (a :: as)) (hm : List.IsChain (Β· > Β·) m) (hmas : m ≀ as) : List.IsChain (Β· > Β·) (a :: m) := by cases m with | nil => grind | cons b bs => apply hm.cons_cons cases as with | nil => simp only [le_iff_lt_or_eq, reduceCtorEq, or_false] at hmas exact (List.not_lt_nil _ hmas).elim | cons a' as => rw [List.isChain_cons_cons] at ha refine lt_of_le_of_lt ?_ ha.1 rw [le_iff_lt_or_eq] at hmas rcases hmas with hmas | hmas Β· by_contra! hh rw [← not_le] at hmas apply hmas apply le_of_lt exact (List.lt_iff_lex_lt _ _).mp (List.Lex.rel hh) Β· simp_all only [List.cons.injEq, le_refl] @[deprecated (since := "2025-09-24")] alias Chain'.cons_of_le := IsChain.cons_of_le lemma IsChain.isChain_cons {Ξ± : Type*} {R : Ξ± β†’ Ξ± β†’ Prop} {l : List Ξ±} {v : Ξ±} (hl : l.IsChain R) (hv : (lne : l β‰  []) β†’ R v (l.head lne)) : (v :: l).IsChain R := by cases l <;> grind @[deprecated (since := "2025-09-24")] alias Chain'.chain := IsChain.isChain_cons lemma IsChain.iterate_eq_of_apply_eq {Ξ± : Type*} {f : Ξ± β†’ Ξ±} {l : List Ξ±} (hl : l.IsChain (fun x y ↦ f x = y)) (i : β„•) (hi : i < l.length) : f^[i] l[0] = l[i] := by induction i with | zero => rfl | succ i h => rw [Function.iterate_succ', Function.comp_apply, h (by cutsat)] rw [List.isChain_iff_get] at hl apply hl @[deprecated (since := "2025-09-24")] alias Chain'.iterate_eq_of_apply_eq := IsChain.iterate_eq_of_apply_eq theorem isChain_replicate_of_rel (n : β„•) {a : Ξ±} (h : r a a) : IsChain r (replicate n a) := by induction n using Nat.twoStepInduction <;> grind @[deprecated "Use `isChain_replicate_of_rel` with `n + 1` instead" (since := "2025-09-19")] alias chain_replicate_of_rel := isChain_replicate_of_rel theorem isChain_eq_iff_eq_replicate {l : List Ξ±} : IsChain (Β· = Β·) l ↔ βˆ€ a ∈ l.head?, l = replicate l.length a := by induction l using twoStepInduction with | nil | singleton => simp | cons_cons a b l IH IH2 => simp +contextual [isChain_cons_cons, eq_comm, IH2, replicate_succ] @[deprecated (since := "2025-09-19")] alias chain'_eq_iff_eq_replicate := isChain_eq_iff_eq_replicate theorem isChain_cons_eq_iff_eq_replicate {a : Ξ±} {l : List Ξ±} : IsChain (Β· = Β·) (a :: l) ↔ l = replicate l.length a := by simp [isChain_eq_iff_eq_replicate, replicate_succ] @[deprecated (since := "2025-09-19")] alias chain_eq_iff_eq_replicate := isChain_cons_eq_iff_eq_replicate end List /-! In this section, we consider the type of `r`-decreasing chains (`List.IsChain (flip r)`) equipped with lexicographic order `List.Lex r`. -/ variable {Ξ± : Type*} (r : Ξ± β†’ Ξ± β†’ Prop) /-- The type of `r`-decreasing chains -/ abbrev List.chains := { l : List Ξ± // l.IsChain (flip r) } /-- The lexicographic order on the `r`-decreasing chains -/ abbrev List.lex_chains (l m : List.chains r) : Prop := List.Lex r l.val m.val variable {r} /-- If an `r`-decreasing chain `l` is empty or its head is accessible by `r`, then `l` is accessible by the lexicographic order `List.Lex r`. -/ theorem Acc.list_chain' {l : List.chains r} (acc : βˆ€ a ∈ l.val.head?, Acc r a) : Acc (List.lex_chains r) l := by obtain ⟨_ | ⟨a, l⟩, hl⟩ := l Β· apply Acc.intro; rintro ⟨_⟩ ⟨_⟩ specialize acc a _ Β· rw [List.head?_cons, Option.mem_some_iff] /- For an r-decreasing chain of the form a :: l, apply induction on a -/ induction acc generalizing l with | intro a _ ih => /- Bundle l with a proof that it is r-decreasing to form l' -/ have hl' := (List.isChain_cons.1 hl).2 let l' : List.chains r := ⟨l, hl'⟩ have : Acc (List.lex_chains r) l' := by rcases l with - | ⟨b, l⟩ Β· apply Acc.intro; rintro ⟨_⟩ ⟨_⟩ /- l' is accessible by induction hypothesis -/ Β· apply ih b (List.isChain_cons_cons.1 hl).1 /- make l' a free variable and induct on l' -/ revert hl rw [(by rfl : l = l'.1)] clear_value l' induction this with | intro l _ ihl => intro hl apply Acc.intro rintro ⟨_ | ⟨b, m⟩, hm⟩ (_ | hr | hr) Β· apply Acc.intro; rintro ⟨_⟩ ⟨_⟩ Β· apply ih b hr Β· apply ihl ⟨m, (List.isChain_cons.1 hm).2⟩ hr /-- If `r` is well-founded, the lexicographic order on `r`-decreasing chains is also. -/ theorem WellFounded.list_chain' (hwf : WellFounded r) : WellFounded (List.lex_chains r) := ⟨fun _ ↦ Acc.list_chain' (fun _ _ => hwf.apply _)⟩ instance [hwf : IsWellFounded Ξ± r] : IsWellFounded (List.chains r) (List.lex_chains r) := ⟨hwf.wf.list_chain'⟩
.lake/packages/mathlib/Mathlib/Data/List/Iterate.lean
import Mathlib.Algebra.Order.Group.Nat import Mathlib.Data.List.Defs import Mathlib.Data.Set.Function /-! # iterate Proves various lemmas about `List.iterate`. -/ variable {Ξ± : Type*} namespace List @[simp] theorem length_iterate (f : Ξ± β†’ Ξ±) (a : Ξ±) (n : β„•) : length (iterate f a n) = n := by induction n generalizing a <;> simp [*] @[simp] theorem iterate_eq_nil {f : Ξ± β†’ Ξ±} {a : Ξ±} {n : β„•} : iterate f a n = [] ↔ n = 0 := by rw [← length_eq_zero_iff, length_iterate] theorem getElem?_iterate (f : Ξ± β†’ Ξ±) (a : Ξ±) : βˆ€ (n i : β„•), i < n β†’ (iterate f a n)[i]? = f^[i] a | n + 1, 0, _ => by simp | n + 1, i + 1, h => by simp [getElem?_iterate f (f a) n i (by simpa using h)] @[simp] theorem getElem_iterate (f : Ξ± β†’ Ξ±) (a : Ξ±) (n : β„•) (i : Nat) (h : i < (iterate f a n).length) : (iterate f a n)[i] = f^[i] a := (getElem_eq_iff _).2 <| getElem?_iterate _ _ _ _ <| by rwa [length_iterate] at h @[simp] theorem mem_iterate {f : Ξ± β†’ Ξ±} {a : Ξ±} {n : β„•} {b : Ξ±} : b ∈ iterate f a n ↔ βˆƒ m < n, b = f^[m] a := by simp [List.mem_iff_get, Fin.exists_iff, eq_comm (b := b)] @[simp] theorem range_map_iterate (n : β„•) (f : Ξ± β†’ Ξ±) (a : Ξ±) : (List.range n).map (f^[Β·] a) = List.iterate f a n := by apply List.ext_getElem <;> simp theorem iterate_add (f : Ξ± β†’ Ξ±) (a : Ξ±) (m n : β„•) : iterate f a (m + n) = iterate f a m ++ iterate f (f^[m] a) n := by induction m generalizing a with | zero => simp | succ n ih => rw [iterate, add_right_comm, iterate, ih, Nat.iterate, cons_append] theorem take_iterate (f : Ξ± β†’ Ξ±) (a : Ξ±) (m n : β„•) : take m (iterate f a n) = iterate f a (min m n) := by rw [← range_map_iterate, ← range_map_iterate, ← map_take, take_range] end List
.lake/packages/mathlib/Mathlib/Data/List/Sections.lean
import Mathlib.Data.List.Forall2 /-! # List sections This file proves some stuff about `List.sections` (definition in `Data.List.Defs`). A section of a list of lists `[l₁, ..., lβ‚™]` is a list whose `i`-th element comes from the `i`-th list. -/ open Nat Function namespace List variable {Ξ± Ξ² : Type*} theorem mem_sections {L : List (List Ξ±)} {f} : f ∈ sections L ↔ Forallβ‚‚ (Β· ∈ Β·) f L := by refine ⟨fun h => ?_, fun h => ?_⟩ Β· induction L generalizing f Β· cases mem_singleton.1 h exact Forallβ‚‚.nil simp only [sections, mem_flatMap, mem_map] at h rcases h with ⟨_, _, _, _, rfl⟩ simp only [*, forallβ‚‚_cons, true_and] Β· induction h with | nil => simp only [sections, mem_singleton] | @cons a l f L al fL fs => simp only [sections, mem_flatMap, mem_map] exact ⟨f, fs, a, al, rfl⟩ theorem mem_sections_length {L : List (List Ξ±)} {f} (h : f ∈ sections L) : length f = length L := (mem_sections.1 h).length_eq open scoped Relator in theorem rel_sections {r : Ξ± β†’ Ξ² β†’ Prop} : (Forallβ‚‚ (Forallβ‚‚ r) β‡’ Forallβ‚‚ (Forallβ‚‚ r)) sections sections | _, _, Forallβ‚‚.nil => Forallβ‚‚.cons Forallβ‚‚.nil Forallβ‚‚.nil | _, _, Forallβ‚‚.cons hβ‚€ h₁ => rel_flatMap (rel_sections h₁) fun _ _ hl => rel_map (fun _ _ ha => Forallβ‚‚.cons ha hl) hβ‚€ end List
.lake/packages/mathlib/Mathlib/Data/List/Flatten.lean
import Mathlib.Tactic.GCongr.Core import Mathlib.Util.AssertExists /-! # Join of a list of lists This file proves basic properties of `List.flatten`, which concatenates a list of lists. It is defined in `Init.Prelude`. -/ -- Make sure we don't import algebra assert_not_exists Monoid variable {Ξ± Ξ² : Type*} namespace List @[gcongr] protected theorem Sublist.flatten {l₁ lβ‚‚ : List (List Ξ±)} (h : l₁ <+ lβ‚‚) : l₁.flatten <+ lβ‚‚.flatten := by induction h with grind @[gcongr] protected theorem Sublist.flatMap {l₁ lβ‚‚ : List Ξ±} (h : l₁ <+ lβ‚‚) (f : Ξ± β†’ List Ξ²) : l₁.flatMap f <+ lβ‚‚.flatMap f := (h.map f).flatten /-- Taking only the first `i+1` elements in a list, and then dropping the first `i` ones, one is left with a list of length `1` made of the `i`-th element of the original list. -/ theorem drop_take_succ_eq_cons_getElem (L : List Ξ±) (i : Nat) (h : i < L.length) : (L.take (i + 1)).drop i = [L[i]] := by induction L generalizing i with grind /-- We can rebracket `x ++ (l₁ ++ x) ++ (lβ‚‚ ++ x) ++ ... ++ (lβ‚™ ++ x)` to `(x ++ l₁) ++ (x ++ lβ‚‚) ++ ... ++ (x ++ lβ‚™) ++ x` where `L = [l₁, lβ‚‚, ..., lβ‚™]`. -/ theorem append_flatten_map_append (L : List (List Ξ±)) (x : List Ξ±) : x ++ (L.map (Β· ++ x)).flatten = (L.map (x ++ Β·)).flatten ++ x := by induction L with grind end List
.lake/packages/mathlib/Mathlib/Data/List/Lemmas.lean
import Mathlib.Data.Set.Image import Mathlib.Data.List.InsertIdx /-! # Some lemmas about lists involving sets Split out from `Data.List.Basic` to reduce its dependencies. -/ variable {Ξ± Ξ² Ξ³ : Type*} namespace List @[simp] theorem setOf_mem_eq_empty_iff {l : List Ξ±} : { x | x ∈ l } = βˆ… ↔ l = [] := Set.eq_empty_iff_forall_notMem.trans eq_nil_iff_forall_not_mem.symm theorem injOn_insertIdx_index_of_notMem (l : List Ξ±) (x : Ξ±) (hx : x βˆ‰ l) : Set.InjOn (fun k => l.insertIdx k x) { n | n ≀ l.length } := by intro n hn m hm h induction l generalizing n m with | nil => simp_all [Set.mem_singleton_iff, Set.setOf_eq_eq_singleton, length] | cons hd tl IH => simp only [length, Set.mem_setOf_eq] at hn hm simp only [mem_cons, not_or] at hx cases n <;> cases m Β· rfl Β· simp [hx.left] at h Β· simp [Ne.symm hx.left] at h Β· simp only [insertIdx_succ_cons, cons.injEq, true_and] at h rw [Nat.succ_inj] refine IH hx.right ?_ ?_ h Β· simpa [Nat.succ_le_succ_iff] using hn Β· simpa [Nat.succ_le_succ_iff] using hm @[deprecated (since := "2025-05-23")] alias injOn_insertIdx_index_of_not_mem := injOn_insertIdx_index_of_notMem theorem foldr_range_subset_of_range_subset {f : Ξ² β†’ Ξ± β†’ Ξ±} {g : Ξ³ β†’ Ξ± β†’ Ξ±} (hfg : Set.range f βŠ† Set.range g) (a : Ξ±) : Set.range (foldr f a) βŠ† Set.range (foldr g a) := by rintro _ ⟨l, rfl⟩ induction l with | nil => exact ⟨[], rfl⟩ | cons b l H => obtain ⟨c, hgf⟩ := hfg (Set.mem_range_self b) obtain ⟨m, hgf'⟩ := H rw [foldr_cons, ← hgf, ← hgf'] exact ⟨c :: m, rfl⟩ theorem foldl_range_subset_of_range_subset {f : Ξ± β†’ Ξ² β†’ Ξ±} {g : Ξ± β†’ Ξ³ β†’ Ξ±} (hfg : (Set.range fun a c => f c a) βŠ† Set.range fun b c => g c b) (a : Ξ±) : Set.range (foldl f a) βŠ† Set.range (foldl g a) := by change (Set.range fun l => _) βŠ† Set.range fun l => _ -- Porting note: have to write `(foldr_reverse)` instead of `foldr_reverse`. simp_rw [← (foldr_reverse), Set.range_comp' _ reverse, reverse_involutive.bijective.surjective.range_eq, Set.image_univ] exact foldr_range_subset_of_range_subset hfg a theorem foldr_range_eq_of_range_eq {f : Ξ² β†’ Ξ± β†’ Ξ±} {g : Ξ³ β†’ Ξ± β†’ Ξ±} (hfg : Set.range f = Set.range g) (a : Ξ±) : Set.range (foldr f a) = Set.range (foldr g a) := (foldr_range_subset_of_range_subset hfg.le a).antisymm (foldr_range_subset_of_range_subset hfg.ge a) theorem foldl_range_eq_of_range_eq {f : Ξ± β†’ Ξ² β†’ Ξ±} {g : Ξ± β†’ Ξ³ β†’ Ξ±} (hfg : (Set.range fun a c => f c a) = Set.range fun b c => g c b) (a : Ξ±) : Set.range (foldl f a) = Set.range (foldl g a) := (foldl_range_subset_of_range_subset hfg.le a).antisymm (foldl_range_subset_of_range_subset hfg.ge a) /-! ### MapAccumr and Foldr Some lemmas relation `mapAccumr` and `foldr` -/ section MapAccumr theorem mapAccumr_eq_foldr {Οƒ : Type*} (f : Ξ± β†’ Οƒ β†’ Οƒ Γ— Ξ²) : βˆ€ (as : List Ξ±) (s : Οƒ), mapAccumr f as s = List.foldr (fun a s => let r := f a s.1 (r.1, r.2 :: s.2) ) (s, []) as | [], _ => rfl | a :: as, s => by simp only [mapAccumr, foldr, mapAccumr_eq_foldr f as] theorem mapAccumrβ‚‚_eq_foldr {Οƒ Ο† : Type*} (f : Ξ± β†’ Ξ² β†’ Οƒ β†’ Οƒ Γ— Ο†) : βˆ€ (as : List Ξ±) (bs : List Ξ²) (s : Οƒ), mapAccumrβ‚‚ f as bs s = foldr (fun ab s => let r := f ab.1 ab.2 s.1 (r.1, r.2 :: s.2) ) (s, []) (as.zip bs) | [], [], _ => rfl | _ :: _, [], _ => rfl | [], _ :: _, _ => rfl | a :: as, b :: bs, s => by simp only [mapAccumrβ‚‚, mapAccumrβ‚‚_eq_foldr f as] rfl end MapAccumr end List
.lake/packages/mathlib/Mathlib/Data/List/Pairwise.lean
import Batteries.Data.List.Pairwise import Mathlib.Logic.Pairwise import Mathlib.Logic.Relation /-! # Pairwise relations on a list This file provides basic results about `List.Pairwise` and `List.pwFilter` (definitions are in `Data.List.Defs`). `Pairwise r [a 0, ..., a (n - 1)]` means `βˆ€ i j, i < j β†’ r (a i) (a j)`. For example, `Pairwise (β‰ ) l` means that all elements of `l` are distinct, and `Pairwise (<) l` means that `l` is strictly increasing. `pwFilter r l` is the list obtained by iteratively adding each element of `l` that doesn't break the pairwiseness of the list we have so far. It thus yields `l'` a maximal sublist of `l` such that `Pairwise r l'`. ## Tags sorted, nodup -/ open Nat Function namespace List variable {Ξ± Ξ² : Type*} {R : Ξ± β†’ Ξ± β†’ Prop} {l : List Ξ±} {a : Ξ±} mk_iff_of_inductive_prop List.Pairwise List.pairwise_iff /-! ### Pairwise -/ theorem Pairwise.forall_of_forall (H : Symmetric R) (H₁ : βˆ€ x ∈ l, R x x) (Hβ‚‚ : l.Pairwise R) : βˆ€ ⦃x⦄, x ∈ l β†’ βˆ€ ⦃y⦄, y ∈ l β†’ R x y := Hβ‚‚.forall_of_forall_of_flip H₁ <| by rwa [H.flip_eq] theorem Pairwise.forall (hR : Symmetric R) (hl : l.Pairwise R) : βˆ€ ⦃a⦄, a ∈ l β†’ βˆ€ ⦃b⦄, b ∈ l β†’ a β‰  b β†’ R a b := by apply Pairwise.forall_of_forall Β· exact fun a b h hne => hR (h hne.symm) Β· exact fun _ _ hx => (hx rfl).elim Β· exact hl.imp (@fun a b h _ => by exact h) theorem Pairwise.set_pairwise (hl : Pairwise R l) (hr : Symmetric R) : { x | x ∈ l }.Pairwise R := hl.forall hr theorem pairwise_of_reflexive_of_forall_ne (hr : Reflexive R) (h : βˆ€ a ∈ l, βˆ€ b ∈ l, a β‰  b β†’ R a b) : l.Pairwise R := by rw [pairwise_iff_forall_sublist] intro a b hab if heq : a = b then cases heq; apply hr else apply h <;> try (apply hab.subset; simp) exact heq theorem Pairwise.rel_head_tail (h₁ : l.Pairwise R) (ha : a ∈ l.tail) : R (l.head <| ne_nil_of_mem <| mem_of_mem_tail ha) a := by cases l with | nil => simp at ha | cons b l => exact (pairwise_cons.1 h₁).1 a ha theorem Pairwise.rel_head_of_rel_head_head (h₁ : l.Pairwise R) (ha : a ∈ l) (hhead : R (l.head <| ne_nil_of_mem ha) (l.head <| ne_nil_of_mem ha)) : R (l.head <| ne_nil_of_mem ha) a := by cases l with | nil => simp at ha | cons b l => exact (mem_cons.mp ha).elim (Β· β–Έ hhead) ((pairwise_cons.1 h₁).1 _) theorem Pairwise.rel_head [IsRefl Ξ± R] (h₁ : l.Pairwise R) (ha : a ∈ l) : R (l.head <| ne_nil_of_mem ha) a := h₁.rel_head_of_rel_head_head ha (refl_of ..) theorem Pairwise.rel_dropLast_getLast (h : l.Pairwise R) (ha : a ∈ l.dropLast) : R a (l.getLast <| ne_nil_of_mem <| dropLast_subset _ ha) := by rw [← pairwise_reverse] at h rw [getLast_eq_head_reverse] exact h.rel_head_tail (by rwa [tail_reverse, mem_reverse]) theorem Pairwise.rel_getLast_of_rel_getLast_getLast (h₁ : l.Pairwise R) (ha : a ∈ l) (hlast : R (l.getLast <| ne_nil_of_mem ha) (l.getLast <| ne_nil_of_mem ha)) : R a (l.getLast <| ne_nil_of_mem ha) := by rw [← dropLast_concat_getLast (ne_nil_of_mem ha), mem_append, List.mem_singleton] at ha exact ha.elim h₁.rel_dropLast_getLast (Β· β–Έ hlast) theorem Pairwise.rel_getLast [IsRefl Ξ± R] (h₁ : l.Pairwise R) (ha : a ∈ l) : R a (l.getLast <| ne_nil_of_mem ha) := h₁.rel_getLast_of_rel_getLast_getLast ha (refl_of ..) protected alias ⟨Pairwise.of_reverse, Pairwise.reverse⟩ := pairwise_reverse /-! ### Pairwise filtering -/ protected alias ⟨_, Pairwise.pwFilter⟩ := pwFilter_eq_self end List
.lake/packages/mathlib/Mathlib/Data/List/MinMax.lean
import Mathlib.Data.List.Basic import Mathlib.Order.BoundedOrder.Lattice import Mathlib.Data.List.Induction import Mathlib.Order.MinMax import Mathlib.Order.WithBot /-! # Minimum and maximum of lists ## Main definitions The main definitions are `argmax`, `argmin`, `minimum` and `maximum` for lists. `argmax f l` returns `some a`, where `a` of `l` that maximises `f a`. If there are `a b` such that `f a = f b`, it returns whichever of `a` or `b` comes first in the list. `argmax f [] = none` `minimum l` returns a `WithTop Ξ±`, the smallest element of `l` for nonempty lists, and `⊀` for `[]` -/ namespace List variable {Ξ± Ξ² : Type*} section ArgAux variable (r : Ξ± β†’ Ξ± β†’ Prop) [DecidableRel r] {l : List Ξ±} {o : Option Ξ±} {a : Ξ±} /-- Auxiliary definition for `argmax` and `argmin`. -/ def argAux (a : Option Ξ±) (b : Ξ±) : Option Ξ± := Option.casesOn a (some b) fun c => if r b c then some b else some c @[simp] theorem foldl_argAux_eq_none : l.foldl (argAux r) o = none ↔ l = [] ∧ o = none := List.reverseRecOn l (by simp) fun tl hd => by simp only [foldl_append, foldl_cons, argAux, foldl_nil, append_eq_nil_iff] cases foldl (argAux r) o tl Β· simp Β· simp only split_ifs <;> simp private theorem foldl_argAux_mem (l) : βˆ€ a m : Ξ±, m ∈ foldl (argAux r) (some a) l β†’ m ∈ a :: l := List.reverseRecOn l (by simp [eq_comm]) (by intro tl hd ih a m simp only [foldl_append, foldl_cons, foldl_nil, argAux] cases hf : foldl (argAux r) (some a) tl Β· simp +contextual Β· dsimp only split_ifs Β· simp +contextual Β· -- `finish [ih _ _ hf]` closes this goal simp only [List.mem_cons] at ih rcases ih _ _ hf with rfl | H Β· simp +contextual only [Option.mem_def, Option.some.injEq, eq_comm, mem_cons, mem_append, true_or, implies_true] Β· simp +contextual [@eq_comm _ _ m, H]) @[simp] theorem argAux_self (hrβ‚€ : Irreflexive r) (a : Ξ±) : argAux r (some a) a = a := if_neg <| hrβ‚€ _ theorem not_of_mem_foldl_argAux (hrβ‚€ : Irreflexive r) (hr₁ : Transitive r) : βˆ€ {a m : Ξ±} {o : Option Ξ±}, a ∈ l β†’ m ∈ foldl (argAux r) o l β†’ Β¬r a m := by induction l using List.reverseRecOn with | nil => simp | append_singleton tl a ih => ?_ intro b m o hb ho rw [foldl_append, foldl_cons, foldl_nil, argAux] at ho rcases hf : foldl (argAux r) o tl with - | c Β· rw [hf] at ho rw [foldl_argAux_eq_none] at hf simp_all [hf.1, hf.2, hrβ‚€ _] rw [hf, Option.mem_def] at ho dsimp only at ho split_ifs at ho with hac <;> rcases mem_append.1 hb with h | h <;> injection ho with ho <;> subst ho Β· exact fun hba => ih h hf (hr₁ hba hac) Β· simp_all [hrβ‚€ _] Β· exact ih h hf Β· simp_all end ArgAux section Preorder variable [Preorder Ξ²] [DecidableLT Ξ²] {f : Ξ± β†’ Ξ²} {l : List Ξ±} {a m : Ξ±} /-- `argmax f l` returns `some a`, where `f a` is maximal among the elements of `l`, in the sense that there is no `b ∈ l` with `f a < f b`. If `a`, `b` are such that `f a = f b`, it returns whichever of `a` or `b` comes first in the list. `argmax f [] = none`. -/ def argmax (f : Ξ± β†’ Ξ²) (l : List Ξ±) : Option Ξ± := l.foldl (argAux fun b c => f c < f b) none /-- `argmin f l` returns `some a`, where `f a` is minimal among the elements of `l`, in the sense that there is no `b ∈ l` with `f b < f a`. If `a`, `b` are such that `f a = f b`, it returns whichever of `a` or `b` comes first in the list. `argmin f [] = none`. -/ def argmin (f : Ξ± β†’ Ξ²) (l : List Ξ±) := l.foldl (argAux fun b c => f b < f c) none @[simp] theorem argmax_nil (f : Ξ± β†’ Ξ²) : argmax f [] = none := rfl @[simp] theorem argmin_nil (f : Ξ± β†’ Ξ²) : argmin f [] = none := rfl @[simp] theorem argmax_singleton {f : Ξ± β†’ Ξ²} {a : Ξ±} : argmax f [a] = a := rfl @[simp] theorem argmin_singleton {f : Ξ± β†’ Ξ²} {a : Ξ±} : argmin f [a] = a := rfl theorem not_lt_of_mem_argmax : a ∈ l β†’ m ∈ argmax f l β†’ Β¬f m < f a := not_of_mem_foldl_argAux _ (fun x h => lt_irrefl (f x) h) (fun _ _ z hxy hyz => lt_trans (a := f z) hyz hxy) theorem not_lt_of_mem_argmin : a ∈ l β†’ m ∈ argmin f l β†’ Β¬f a < f m := not_of_mem_foldl_argAux _ (fun x h => lt_irrefl (f x) h) (fun x _ _ hxy hyz => lt_trans (a := f x) hxy hyz) theorem argmax_concat (f : Ξ± β†’ Ξ²) (a : Ξ±) (l : List Ξ±) : argmax f (l ++ [a]) = Option.casesOn (argmax f l) (some a) fun c => if f c < f a then some a else some c := by rw [argmax, argmax]; simp [argAux] theorem argmin_concat (f : Ξ± β†’ Ξ²) (a : Ξ±) (l : List Ξ±) : argmin f (l ++ [a]) = Option.casesOn (argmin f l) (some a) fun c => if f a < f c then some a else some c := @argmax_concat _ Ξ²α΅’α΅ˆ _ _ _ _ _ theorem argmax_mem : βˆ€ {l : List Ξ±} {m : Ξ±}, m ∈ argmax f l β†’ m ∈ l | [], m => by simp | hd :: tl, m => by simpa [argmax, argAux] using foldl_argAux_mem _ tl hd m theorem argmin_mem : βˆ€ {l : List Ξ±} {m : Ξ±}, m ∈ argmin f l β†’ m ∈ l := @argmax_mem _ Ξ²α΅’α΅ˆ _ _ _ @[simp] theorem argmax_eq_none : l.argmax f = none ↔ l = [] := by simp [argmax] @[simp] theorem argmin_eq_none : l.argmin f = none ↔ l = [] := @argmax_eq_none _ Ξ²α΅’α΅ˆ _ _ _ _ end Preorder section LinearOrder variable [LinearOrder Ξ²] {f : Ξ± β†’ Ξ²} {l : List Ξ±} {a m : Ξ±} theorem le_of_mem_argmax : a ∈ l β†’ m ∈ argmax f l β†’ f a ≀ f m := fun ha hm => le_of_not_gt <| not_lt_of_mem_argmax ha hm theorem le_of_mem_argmin : a ∈ l β†’ m ∈ argmin f l β†’ f m ≀ f a := @le_of_mem_argmax _ Ξ²α΅’α΅ˆ _ _ _ _ _ theorem argmax_cons (f : Ξ± β†’ Ξ²) (a : Ξ±) (l : List Ξ±) : argmax f (a :: l) = Option.casesOn (argmax f l) (some a) fun c => if f a < f c then some c else some a := List.reverseRecOn l rfl fun hd tl ih => by rw [← cons_append, argmax_concat, ih, argmax_concat] rcases h : argmax f hd with - | m Β· simp dsimp rw [← apply_ite, ← apply_ite] dsimp split_ifs <;> try rfl Β· exact absurd (lt_trans β€Ήf a < f mβ€Ί β€Ή_β€Ί) β€Ή_β€Ί Β· cases (β€Ήf a < f tlβ€Ί.gt_or_lt _).elim β€Ή_β€Ί β€Ή_β€Ί theorem argmin_cons (f : Ξ± β†’ Ξ²) (a : Ξ±) (l : List Ξ±) : argmin f (a :: l) = Option.casesOn (argmin f l) (some a) fun c => if f c < f a then some c else some a := @argmax_cons Ξ± Ξ²α΅’α΅ˆ _ _ _ _ variable [DecidableEq Ξ±] theorem index_of_argmax : βˆ€ {l : List Ξ±} {m : Ξ±}, m ∈ argmax f l β†’ βˆ€ {a}, a ∈ l β†’ f m ≀ f a β†’ l.idxOf m ≀ l.idxOf a | [], m, _, _, _, _ => by simp | hd :: tl, m, hm, a, ha, ham => by simp only [idxOf_cons, argmax_cons, Option.mem_def] at hm ⊒ cases h : argmax f tl Β· rw [h] at hm simp_all rw [h] at hm dsimp only at hm simp only [cond_eq_if, beq_iff_eq] obtain ha | ha := ha <;> split_ifs at hm <;> injection hm with hm <;> subst hm Β· cases not_le_of_gt β€Ή_β€Ί β€Ή_β€Ί Β· rw [if_pos rfl] Β· rw [if_neg, if_neg] Β· exact Nat.succ_le_succ (index_of_argmax h (by assumption) ham) Β· exact ne_of_apply_ne f (lt_of_lt_of_le β€Ή_β€Ί β€Ή_β€Ί).ne Β· exact ne_of_apply_ne _ β€Ήf hd < f _β€Ί.ne Β· rw [if_pos rfl] exact Nat.zero_le _ theorem index_of_argmin : βˆ€ {l : List Ξ±} {m : Ξ±}, m ∈ argmin f l β†’ βˆ€ {a}, a ∈ l β†’ f a ≀ f m β†’ l.idxOf m ≀ l.idxOf a := @index_of_argmax _ Ξ²α΅’α΅ˆ _ _ _ theorem mem_argmax_iff : m ∈ argmax f l ↔ m ∈ l ∧ (βˆ€ a ∈ l, f a ≀ f m) ∧ βˆ€ a ∈ l, f m ≀ f a β†’ l.idxOf m ≀ l.idxOf a := ⟨fun hm => ⟨argmax_mem hm, fun _ ha => le_of_mem_argmax ha hm, fun _ => index_of_argmax hm⟩, by rintro ⟨hml, ham, hma⟩ rcases harg : argmax f l with - | n Β· simp_all Β· have := _root_.le_antisymm (hma n (argmax_mem harg) (le_of_mem_argmax hml harg)) (index_of_argmax harg hml (ham _ (argmax_mem harg))) rw [(idxOf_inj hml (argmax_mem harg)).1 this, Option.mem_def]⟩ theorem argmax_eq_some_iff : argmax f l = some m ↔ m ∈ l ∧ (βˆ€ a ∈ l, f a ≀ f m) ∧ βˆ€ a ∈ l, f m ≀ f a β†’ l.idxOf m ≀ l.idxOf a := mem_argmax_iff theorem mem_argmin_iff : m ∈ argmin f l ↔ m ∈ l ∧ (βˆ€ a ∈ l, f m ≀ f a) ∧ βˆ€ a ∈ l, f a ≀ f m β†’ l.idxOf m ≀ l.idxOf a := @mem_argmax_iff _ Ξ²α΅’α΅ˆ _ _ _ _ _ theorem argmin_eq_some_iff : argmin f l = some m ↔ m ∈ l ∧ (βˆ€ a ∈ l, f m ≀ f a) ∧ βˆ€ a ∈ l, f a ≀ f m β†’ l.idxOf m ≀ l.idxOf a := mem_argmin_iff end LinearOrder section MaximumMinimum section Preorder variable [Preorder Ξ±] [DecidableLT Ξ±] {l : List Ξ±} {a m : Ξ±} /-- `maximum l` returns a `WithBot Ξ±`, the largest element of `l` for nonempty lists, and `βŠ₯` for `[]` -/ def maximum (l : List Ξ±) : WithBot Ξ± := argmax id l /-- `minimum l` returns a `WithTop Ξ±`, the smallest element of `l` for nonempty lists, and `⊀` for `[]` -/ def minimum (l : List Ξ±) : WithTop Ξ± := argmin id l @[simp] theorem maximum_nil : maximum ([] : List Ξ±) = βŠ₯ := rfl @[simp] theorem minimum_nil : minimum ([] : List Ξ±) = ⊀ := rfl @[simp] theorem maximum_singleton (a : Ξ±) : maximum [a] = a := rfl @[simp] theorem minimum_singleton (a : Ξ±) : minimum [a] = a := rfl theorem maximum_mem {l : List Ξ±} {m : Ξ±} : (maximum l : WithTop Ξ±) = m β†’ m ∈ l := argmax_mem theorem minimum_mem {l : List Ξ±} {m : Ξ±} : (minimum l : WithBot Ξ±) = m β†’ m ∈ l := argmin_mem @[simp] theorem maximum_eq_bot {l : List Ξ±} : l.maximum = βŠ₯ ↔ l = [] := argmax_eq_none @[simp] theorem minimum_eq_top {l : List Ξ±} : l.minimum = ⊀ ↔ l = [] := argmin_eq_none theorem not_maximum_lt_of_mem : a ∈ l β†’ (maximum l : WithBot Ξ±) = m β†’ Β¬m < a := not_lt_of_mem_argmax theorem not_lt_minimum_of_mem : a ∈ l β†’ (minimum l : WithTop Ξ±) = m β†’ Β¬a < m := not_lt_of_mem_argmin theorem not_maximum_lt_of_mem' (ha : a ∈ l) : Β¬maximum l < (a : WithBot Ξ±) := by cases h : l.maximum <;> simp_all [not_maximum_lt_of_mem ha] theorem not_lt_minimum_of_mem' (ha : a ∈ l) : Β¬(a : WithTop Ξ±) < minimum l := by cases h : l.minimum <;> simp_all [not_lt_minimum_of_mem ha] end Preorder section LinearOrder variable [LinearOrder Ξ±] {l : List Ξ±} {a m : Ξ±} theorem maximum_concat (a : Ξ±) (l : List Ξ±) : maximum (l ++ [a]) = max (maximum l) a := by simp only [maximum, argmax_concat, id] cases argmax id l Β· exact (max_eq_right bot_le).symm Β· simp [WithBot.some_eq_coe, max_def_lt, WithBot.coe_lt_coe] theorem le_maximum_of_mem : a ∈ l β†’ (maximum l : WithBot Ξ±) = m β†’ a ≀ m := le_of_mem_argmax theorem minimum_le_of_mem : a ∈ l β†’ (minimum l : WithTop Ξ±) = m β†’ m ≀ a := le_of_mem_argmin theorem le_maximum_of_mem' (ha : a ∈ l) : (a : WithBot Ξ±) ≀ maximum l := le_of_not_gt <| not_maximum_lt_of_mem' ha theorem minimum_le_of_mem' (ha : a ∈ l) : minimum l ≀ (a : WithTop Ξ±) := le_of_not_gt <| not_lt_minimum_of_mem' ha theorem minimum_concat (a : Ξ±) (l : List Ξ±) : minimum (l ++ [a]) = min (minimum l) a := @maximum_concat Ξ±α΅’α΅ˆ _ _ _ theorem maximum_cons (a : Ξ±) (l : List Ξ±) : maximum (a :: l) = max ↑a (maximum l) := List.reverseRecOn l (by simp) fun tl hd ih => by rw [← cons_append, maximum_concat, ih, maximum_concat, max_assoc] theorem minimum_cons (a : Ξ±) (l : List Ξ±) : minimum (a :: l) = min ↑a (minimum l) := @maximum_cons Ξ±α΅’α΅ˆ _ _ _ lemma maximum_append (l₁ lβ‚‚ : List Ξ±) : (l₁ ++ lβ‚‚).maximum = max l₁.maximum lβ‚‚.maximum := by induction l₁ with | nil => simp | cons _ _ ih => rw [maximum_cons, cons_append, maximum_cons, ih, ← max_assoc] lemma minimum_append (l₁ lβ‚‚ : List Ξ±) : (l₁ ++ lβ‚‚).minimum = min l₁.minimum lβ‚‚.minimum := @maximum_append Ξ±α΅’α΅ˆ _ _ _ theorem maximum_le_of_forall_le {b : WithBot Ξ±} (h : βˆ€ a ∈ l, a ≀ b) : l.maximum ≀ b := by induction l with | nil => simp | cons a l ih => simp only [maximum_cons, max_le_iff] exact ⟨h a (by simp), ih fun a w => h a (mem_cons.mpr (Or.inr w))⟩ theorem le_minimum_of_forall_le {b : WithTop Ξ±} (h : βˆ€ a ∈ l, b ≀ a) : b ≀ l.minimum := by induction l with | nil => simp | cons a l ih => simp only [minimum_cons, le_min_iff] exact ⟨h a (by simp), ih fun a w => h a (mem_cons.mpr (Or.inr w))⟩ theorem maximum_mono {l₁ lβ‚‚ : List Ξ±} (h : l₁ βŠ† lβ‚‚) : l₁.maximum ≀ lβ‚‚.maximum := maximum_le_of_forall_le fun _ ↦ (le_maximum_of_mem' <| h Β·) theorem minimum_anti {l₁ lβ‚‚ : List Ξ±} (h : l₁ βŠ† lβ‚‚) : lβ‚‚.minimum ≀ l₁.minimum := @maximum_mono Ξ±α΅’α΅ˆ _ _ _ h theorem maximum_eq_coe_iff : maximum l = m ↔ m ∈ l ∧ βˆ€ a ∈ l, a ≀ m := by rw [maximum, ← WithBot.some_eq_coe, argmax_eq_some_iff] simp only [id_eq, and_congr_right_iff, and_iff_left_iff_imp] intro _ h a hal hma rw [_root_.le_antisymm hma (h a hal)] theorem minimum_eq_coe_iff : minimum l = m ↔ m ∈ l ∧ βˆ€ a ∈ l, m ≀ a := @maximum_eq_coe_iff Ξ±α΅’α΅ˆ _ _ _ theorem coe_le_maximum_iff : a ≀ l.maximum ↔ βˆƒ b, b ∈ l ∧ a ≀ b := by induction l <;> simp [maximum_cons, *] theorem minimum_le_coe_iff : l.minimum ≀ a ↔ βˆƒ b, b ∈ l ∧ b ≀ a := by induction l <;> simp [minimum_cons, *] theorem maximum_ne_bot_of_ne_nil (h : l β‰  []) : l.maximum β‰  βŠ₯ := match l, h with | _ :: _, _ => by simp [maximum_cons] theorem minimum_ne_top_of_ne_nil (h : l β‰  []) : l.minimum β‰  ⊀ := @maximum_ne_bot_of_ne_nil Ξ±α΅’α΅ˆ _ _ h theorem maximum_ne_bot_of_length_pos (h : 0 < l.length) : l.maximum β‰  βŠ₯ := match l, h with | _ :: _, _ => by simp [maximum_cons] theorem minimum_ne_top_of_length_pos (h : 0 < l.length) : l.minimum β‰  ⊀ := maximum_ne_bot_of_length_pos (Ξ± := Ξ±α΅’α΅ˆ) h /-- The maximum value in a non-empty `List`. -/ def maximum_of_length_pos (h : 0 < l.length) : Ξ± := WithBot.unbot l.maximum (maximum_ne_bot_of_length_pos h) /-- The minimum value in a non-empty `List`. -/ def minimum_of_length_pos (h : 0 < l.length) : Ξ± := maximum_of_length_pos (Ξ± := Ξ±α΅’α΅ˆ) h @[simp] lemma coe_maximum_of_length_pos (h : 0 < l.length) : (l.maximum_of_length_pos h : Ξ±) = l.maximum := WithBot.coe_unbot _ _ @[simp] lemma coe_minimum_of_length_pos (h : 0 < l.length) : (l.minimum_of_length_pos h : Ξ±) = l.minimum := WithTop.coe_untop _ _ @[simp] theorem le_maximum_of_length_pos_iff {b : Ξ±} (h : 0 < l.length) : b ≀ maximum_of_length_pos h ↔ b ≀ l.maximum := WithBot.le_unbot_iff _ @[simp] theorem minimum_of_length_pos_le_iff {b : Ξ±} (h : 0 < l.length) : minimum_of_length_pos h ≀ b ↔ l.minimum ≀ b := WithTop.untop_le_iff _ theorem maximum_of_length_pos_mem (h : 0 < l.length) : maximum_of_length_pos h ∈ l := by apply maximum_mem simp only [coe_maximum_of_length_pos] theorem minimum_of_length_pos_mem (h : 0 < l.length) : minimum_of_length_pos h ∈ l := maximum_of_length_pos_mem (Ξ± := Ξ±α΅’α΅ˆ) h theorem le_maximum_of_length_pos_of_mem (h : a ∈ l) (w : 0 < l.length) : a ≀ l.maximum_of_length_pos w := by simp only [le_maximum_of_length_pos_iff] exact le_maximum_of_mem' h theorem minimum_of_length_pos_le_of_mem (h : a ∈ l) (w : 0 < l.length) : l.minimum_of_length_pos w ≀ a := le_maximum_of_length_pos_of_mem (Ξ± := Ξ±α΅’α΅ˆ) h w theorem getElem_le_maximum_of_length_pos {i : β„•} (w : i < l.length) (h := (Nat.zero_lt_of_lt w)) : l[i] ≀ l.maximum_of_length_pos h := by apply le_maximum_of_length_pos_of_mem exact getElem_mem _ theorem minimum_of_length_pos_le_getElem {i : β„•} (w : i < l.length) (h := (Nat.zero_lt_of_lt w)) : l.minimum_of_length_pos h ≀ l[i] := getElem_le_maximum_of_length_pos (Ξ± := Ξ±α΅’α΅ˆ) w #adaptation_note /-- 2025-08-14: We should stop using `max?_eq_some_iff_legacy` below, by connecting up Mathlib's order typeclasses with the new classes in Lean. -/ set_option linter.deprecated false in lemma getD_max?_eq_unbotD_maximum (l : List Ξ±) (d : Ξ±) : l.max?.getD d = l.maximum.unbotD d := by cases hy : l.maximum with | bot => simp [List.maximum_eq_bot.mp hy] | coe y => rw [List.maximum_eq_coe_iff] at hy simp only [WithBot.unbotD_coe] cases hz : l.max? with | none => simp [List.max?_eq_none_iff.mp hz] at hy | some z => have : Std.Antisymm (Ξ± := Ξ±) (Β· ≀ Β·) := ⟨fun _ _ => _root_.le_antisymm⟩ rw [List.max?_eq_some_iff_legacy] at hz Β· rw [Option.getD_some] exact _root_.le_antisymm (hy.right _ hz.left) (hz.right _ hy.left) all_goals simp [le_total] lemma getD_min?_eq_untopD_minimum (l : List Ξ±) (d : Ξ±) : l.min?.getD d = l.minimum.untopD d := getD_max?_eq_unbotD_maximum (Ξ± := Ξ±α΅’α΅ˆ) _ _ end LinearOrder end MaximumMinimum section Fold variable [LinearOrder Ξ±] section OrderBot variable [OrderBot Ξ±] {l : List Ξ±} @[simp] theorem foldr_max_of_ne_nil (h : l β‰  []) : ↑(l.foldr max βŠ₯) = l.maximum := by induction l with | nil => contradiction | cons hd tl IH => rw [maximum_cons, foldr, WithBot.coe_max] by_cases h : tl = [] Β· simp [h] Β· simp [IH h] theorem max_le_of_forall_le (l : List Ξ±) (a : Ξ±) (h : βˆ€ x ∈ l, x ≀ a) : l.foldr max βŠ₯ ≀ a := by induction l with | nil => simp | cons y l IH => simpa [h y mem_cons_self] using IH fun x hx => h x <| mem_cons_of_mem _ hx theorem le_max_of_le {l : List Ξ±} {a x : Ξ±} (hx : x ∈ l) (h : a ≀ x) : a ≀ l.foldr max βŠ₯ := by induction l with | nil => exact absurd hx not_mem_nil | cons y l IH => obtain hl | hl := hx Β· simp only [foldr] exact le_max_of_le_left h Β· exact le_max_of_le_right (IH (by assumption)) end OrderBot section OrderTop variable [OrderTop Ξ±] {l : List Ξ±} @[simp] theorem foldr_min_of_ne_nil (h : l β‰  []) : ↑(l.foldr min ⊀) = l.minimum := @foldr_max_of_ne_nil Ξ±α΅’α΅ˆ _ _ _ h theorem le_min_of_forall_le (l : List Ξ±) (a : Ξ±) (h : βˆ€ x ∈ l, a ≀ x) : a ≀ l.foldr min ⊀ := @max_le_of_forall_le Ξ±α΅’α΅ˆ _ _ _ _ h theorem min_le_of_le (l : List Ξ±) (a : Ξ±) {x : Ξ±} (hx : x ∈ l) (h : x ≀ a) : l.foldr min ⊀ ≀ a := @le_max_of_le Ξ±α΅’α΅ˆ _ _ _ _ _ hx h end OrderTop /-- If `a ≀ x` for some `x` in the list `l`, and `b : Ξ±`, then `a ≀ l.foldr max b`. -/ theorem le_max_of_le' {l : List Ξ±} {a x : Ξ±} (b : Ξ±) (hx : x ∈ l) (h : a ≀ x) : a ≀ l.foldr max b := by induction l with | nil => exact absurd hx List.not_mem_nil | cons y l IH => simp only [List.foldr] obtain rfl | hl := mem_cons.mp hx Β· exact le_max_of_le_left h Β· exact le_max_of_le_right (IH hl) theorem min_le_of_le' {l : List Ξ±} {a x : Ξ±} (b : Ξ±) (hx : x ∈ l) (h : x ≀ a) : l.foldr min b ≀ a := @le_max_of_le' Ξ±α΅’α΅ˆ _ _ _ _ _ hx h end Fold end List
.lake/packages/mathlib/Mathlib/Data/List/InsertIdx.lean
import Mathlib.Data.List.Basic import Mathlib.Data.Nat.Basic import Mathlib.Order.Basic /-! # insertIdx Proves various lemmas about `List.insertIdx`. -/ assert_not_exists Set.range open Function open Nat hiding one_pos namespace List universe u v variable {Ξ± : Type u} {Ξ² : Type v} section InsertIdx variable {a : Ξ±} @[simp] theorem sublist_insertIdx (l : List Ξ±) (n : β„•) (a : Ξ±) : l <+ (l.insertIdx n a) := by simpa only [eraseIdx_insertIdx_self] using eraseIdx_sublist (l.insertIdx n a) n @[simp] theorem subset_insertIdx (l : List Ξ±) (n : β„•) (a : Ξ±) : l βŠ† l.insertIdx n a := (sublist_insertIdx ..).subset /-- Erasing `n`th element of a list, then inserting `a` at the same place is the same as setting `n`th element to `a`. We assume that `n β‰  length l`, because otherwise LHS equals `l ++ [a]` while RHS equals `l`. -/ @[simp] theorem insertIdx_eraseIdx_self {l : List Ξ±} {n : β„•} (hn : n β‰  length l) (a : Ξ±) : (l.eraseIdx n).insertIdx n a = l.set n a := by induction n generalizing l <;> cases l <;> simp_all theorem insertIdx_eraseIdx_getElem {l : List Ξ±} {n : β„•} (hn : n < length l) : (l.eraseIdx n).insertIdx n l[n] = l := by simp [hn.ne] theorem eq_or_mem_of_mem_insertIdx {l : List Ξ±} {n : β„•} {a b : Ξ±} (h : a ∈ l.insertIdx n b) : a = b ∨ a ∈ l := by cases Nat.lt_or_ge (length l) n with | inl hn => rw [insertIdx_of_length_lt hn] at h exact .inr h | inr hn => rwa [mem_insertIdx hn] at h theorem insertIdx_subset_cons (n : β„•) (a : Ξ±) (l : List Ξ±) : l.insertIdx n a βŠ† a :: l := by intro b hb simpa using eq_or_mem_of_mem_insertIdx hb theorem insertIdx_pmap {p : Ξ± β†’ Prop} (f : βˆ€ a, p a β†’ Ξ²) {l : List Ξ±} {a : Ξ±} {n : β„•} (hl : βˆ€ x ∈ l, p x) (ha : p a) : (l.pmap f hl).insertIdx n (f a ha) = (l.insertIdx n a).pmap f (fun _ h ↦ (eq_or_mem_of_mem_insertIdx h).elim (fun heq ↦ heq β–Έ ha) (hl _)) := by induction n generalizing l with | zero => cases l <;> simp | succ n ihn => cases l <;> simp_all theorem map_insertIdx (f : Ξ± β†’ Ξ²) (l : List Ξ±) (n : β„•) (a : Ξ±) : (l.insertIdx n a).map f = (l.map f).insertIdx n (f a) := by simpa only [pmap_eq_map] using (insertIdx_pmap (fun a _ ↦ f a) (fun _ _ ↦ trivial) trivial).symm theorem eraseIdx_pmap {p : Ξ± β†’ Prop} (f : βˆ€ a, p a β†’ Ξ²) {l : List Ξ±} (hl : βˆ€ a ∈ l, p a) (n : β„•) : (pmap f l hl).eraseIdx n = (l.eraseIdx n).pmap f fun a ha ↦ hl a (eraseIdx_subset ha) := match l, hl, n with | [], _, _ => rfl | a :: _, _, 0 => rfl | a :: as, h, n + 1 => by rw [forall_mem_cons] at h; simp [eraseIdx_pmap f h.2 n] /-- Erasing an index commutes with `List.map`. -/ theorem eraseIdx_map (f : Ξ± β†’ Ξ²) (l : List Ξ±) (n : β„•) : (map f l).eraseIdx n = (l.eraseIdx n).map f := by simpa only [pmap_eq_map] using eraseIdx_pmap (fun a _ ↦ f a) (fun _ _ ↦ trivial) n theorem get_insertIdx_of_lt (l : List Ξ±) (x : Ξ±) (n k : β„•) (hn : k < n) (hk : k < l.length) (hk' : k < (l.insertIdx n x).length := hk.trans_le length_le_length_insertIdx) : (l.insertIdx n x).get ⟨k, hk'⟩ = l.get ⟨k, hk⟩ := by simp_all [getElem_insertIdx_of_lt] theorem get_insertIdx_self (l : List Ξ±) (x : Ξ±) (n : β„•) (hn : n ≀ l.length) (hn' : n < (l.insertIdx n x).length := (by rwa [length_insertIdx_of_le_length hn, Nat.lt_succ_iff])) : (l.insertIdx n x).get ⟨n, hn'⟩ = x := by simp theorem getElem_insertIdx_add_succ (l : List Ξ±) (x : Ξ±) (n k : β„•) (hk' : n + k < l.length) (hk : n + k + 1 < (l.insertIdx n x).length := (by rwa [length_insertIdx_of_le_length (by cutsat), Nat.succ_lt_succ_iff])) : (l.insertIdx n x)[n + k + 1] = l[n + k] := by grind theorem get_insertIdx_add_succ (l : List Ξ±) (x : Ξ±) (n k : β„•) (hk' : n + k < l.length) (hk : n + k + 1 < (l.insertIdx n x).length := (by rwa [length_insertIdx_of_le_length (by cutsat), Nat.succ_lt_succ_iff])) : (l.insertIdx n x).get ⟨n + k + 1, hk⟩ = get l ⟨n + k, hk'⟩ := by simp [getElem_insertIdx_add_succ, hk'] set_option linter.unnecessarySimpa false in theorem insertIdx_injective (n : β„•) (x : Ξ±) : Function.Injective (fun l : List Ξ± => l.insertIdx n x) := by induction n with | zero => simp | succ n IH => rintro (_ | ⟨a, as⟩) (_ | ⟨b, bs⟩) h <;> simpa [IH.eq_iff] using h end InsertIdx end List
.lake/packages/mathlib/Mathlib/Data/List/Lex.lean
import Mathlib.Data.List.Basic import Mathlib.Data.Nat.Basic import Mathlib.Order.RelClasses /-! # Lexicographic ordering of lists. The lexicographic order on `List Ξ±` is defined by `L < M` iff * `[] < (a :: L)` for any `a` and `L`, * `(a :: L) < (b :: M)` where `a < b`, or * `(a :: L) < (a :: M)` where `L < M`. ## See also Related files are: * `Mathlib/Data/Finset/Colex.lean`: Colexicographic order on finite sets. * `Mathlib/Data/PSigma/Order.lean`: Lexicographic order on `Ξ£' i, Ξ± i`. * `Mathlib/Data/Pi/Lex.lean`: Lexicographic order on `Ξ β‚— i, Ξ± i`. * `Mathlib/Data/Sigma/Order.lean`: Lexicographic order on `Ξ£ i, Ξ± i`. * `Mathlib/Data/Prod/Lex.lean`: Lexicographic order on `Ξ± Γ— Ξ²`. -/ namespace List open Nat universe u variable {Ξ± : Type u} /-! ### lexicographic ordering -/ theorem lex_cons_iff {r : Ξ± β†’ Ξ± β†’ Prop} [IsIrrefl Ξ± r] {a l₁ lβ‚‚} : Lex r (a :: l₁) (a :: lβ‚‚) ↔ Lex r l₁ lβ‚‚ := ⟨fun h => by obtain - | h | h := h; exacts [(irrefl_of r a h).elim, h], Lex.cons⟩ theorem lex_nil_or_eq_nil {r : Ξ± β†’ Ξ± β†’ Prop} (l : List Ξ±) : List.Lex r [] l ∨ l = [] := match l with | [] => Or.inr rfl | _ :: _ => .inl .nil @[simp] theorem lex_singleton_iff {r : Ξ± β†’ Ξ± β†’ Prop} (a b : Ξ±) : List.Lex r [a] [b] ↔ r a b := ⟨fun | .rel h => h, .rel⟩ namespace Lex instance isOrderConnected (r : Ξ± β†’ Ξ± β†’ Prop) [IsOrderConnected Ξ± r] [IsTrichotomous Ξ± r] : IsOrderConnected (List Ξ±) (Lex r) where conn := aux where aux | _, [], _ :: _, nil => Or.inr nil | _, [], _ :: _, rel _ => Or.inr nil | _, [], _ :: _, cons _ => Or.inr nil | _, _ :: _, _ :: _, nil => Or.inl nil | _ :: _, b :: _, _ :: _, rel h => (IsOrderConnected.conn _ b _ h).imp rel rel | a :: l₁, b :: lβ‚‚, _ :: l₃, cons h => by rcases trichotomous_of r a b with (ab | rfl | ab) Β· exact Or.inl (rel ab) Β· exact (aux _ lβ‚‚ _ h).imp cons cons Β· exact Or.inr (rel ab) instance isTrichotomous (r : Ξ± β†’ Ξ± β†’ Prop) [IsTrichotomous Ξ± r] : IsTrichotomous (List Ξ±) (Lex r) where trichotomous := aux where aux | [], [] => Or.inr (Or.inl rfl) | [], _ :: _ => Or.inl nil | _ :: _, [] => Or.inr (Or.inr nil) | a :: l₁, b :: lβ‚‚ => by rcases trichotomous_of r a b with (ab | rfl | ab) Β· exact Or.inl (rel ab) Β· exact (aux l₁ lβ‚‚).imp cons (Or.imp (congr_arg _) cons) Β· exact Or.inr (Or.inr (rel ab)) instance isAsymm (r : Ξ± β†’ Ξ± β†’ Prop) [IsAsymm Ξ± r] : IsAsymm (List Ξ±) (Lex r) where asymm := aux where aux | _, _, Lex.rel h₁, Lex.rel hβ‚‚ => asymm h₁ hβ‚‚ | _, _, Lex.rel h₁, Lex.cons _ => asymm h₁ h₁ | _, _, Lex.cons _, Lex.rel hβ‚‚ => asymm hβ‚‚ hβ‚‚ | _, _, Lex.cons h₁, Lex.cons hβ‚‚ => aux _ _ h₁ hβ‚‚ instance decidableRel [DecidableEq Ξ±] (r : Ξ± β†’ Ξ± β†’ Prop) [DecidableRel r] : DecidableRel (Lex r) | l₁, [] => isFalse fun h => by cases h | [], _ :: _ => isTrue Lex.nil | a :: l₁, b :: lβ‚‚ => by haveI := decidableRel r l₁ lβ‚‚ refine decidable_of_iff (r a b ∨ a = b ∧ Lex r l₁ lβ‚‚) ⟨fun h => ?_, fun h => ?_⟩ Β· rcases h with (h | ⟨rfl, h⟩) Β· exact Lex.rel h Β· exact Lex.cons h Β· rcases h with (_ | h | h) Β· exact Or.inl h Β· exact Or.inr ⟨rfl, h⟩ theorem append_right (r : Ξ± β†’ Ξ± β†’ Prop) : βˆ€ {s₁ sβ‚‚} (t), Lex r s₁ sβ‚‚ β†’ Lex r s₁ (sβ‚‚ ++ t) | _, _, _, nil => nil | _, _, _, cons h => cons (append_right r _ h) | _, _, _, rel r => rel r theorem append_left (R : Ξ± β†’ Ξ± β†’ Prop) {t₁ tβ‚‚} (h : Lex R t₁ tβ‚‚) : βˆ€ s, Lex R (s ++ t₁) (s ++ tβ‚‚) | [] => h | _ :: l => cons (append_left R h l) theorem imp {r s : Ξ± β†’ Ξ± β†’ Prop} (H : βˆ€ a b, r a b β†’ s a b) : βˆ€ l₁ lβ‚‚, Lex r l₁ lβ‚‚ β†’ Lex s l₁ lβ‚‚ | _, _, nil => nil | _, _, cons h => cons (imp H _ _ h) | _, _, rel r => rel (H _ _ r) theorem to_ne : βˆ€ {l₁ lβ‚‚ : List Ξ±}, Lex (Β· β‰  Β·) l₁ lβ‚‚ β†’ l₁ β‰  lβ‚‚ | _, _, cons h, e => to_ne h (List.cons.inj e).2 | _, _, rel r, e => r (List.cons.inj e).1 theorem _root_.Decidable.List.Lex.ne_iff [DecidableEq Ξ±] {l₁ lβ‚‚ : List Ξ±} (H : length l₁ ≀ length lβ‚‚) : Lex (Β· β‰  Β·) l₁ lβ‚‚ ↔ l₁ β‰  lβ‚‚ := ⟨to_ne, fun h => by induction l₁ generalizing lβ‚‚ <;> rcases lβ‚‚ with - | ⟨b, lβ‚‚βŸ© Β· contradiction Β· apply nil Β· exact (not_lt_of_ge H).elim (succ_pos _) case cons.cons a l₁ IH => by_cases ab : a = b Β· subst b exact .cons <| IH (le_of_succ_le_succ H) (mt (congr_arg _) h) Β· exact .rel ab ⟩ theorem ne_iff {l₁ lβ‚‚ : List Ξ±} (H : length l₁ ≀ length lβ‚‚) : Lex (Β· β‰  Β·) l₁ lβ‚‚ ↔ l₁ β‰  lβ‚‚ := by classical exact Decidable.List.Lex.ne_iff H end Lex instance [LinearOrder Ξ±] : LinearOrder (List Ξ±) := have : βˆ€ {r} [IsStrictTotalOrder Ξ± r], IsStrictTotalOrder (List Ξ±) (Lex r) := { isStrictWeakOrder_of_isOrderConnected with } linearOrderOfSTO (Lex (Β· < Β·)) --Note: this overrides an instance in core lean instance LE' [LinearOrder Ξ±] : LE (List Ξ±) := Preorder.toLE theorem lt_iff_lex_lt [LT Ξ±] (l l' : List Ξ±) : List.lt l l' ↔ Lex (Β· < Β·) l l' := by rw [List.lt] theorem head_le_of_lt [Preorder Ξ±] {a a' : Ξ±} {l l' : List Ξ±} (h : (a' :: l') < (a :: l)) : a' ≀ a := match h with | .cons _ => le_rfl | .rel h => h.le theorem head!_le_of_lt [Preorder Ξ±] [Inhabited Ξ±] (l l' : List Ξ±) (h : l' < l) (hl' : l' β‰  []) : l'.head! ≀ l.head! := by replace h : List.Lex (Β· < Β·) l' l := h by_cases hl : l = [] Β· simp [hl] at h Β· rw [← List.cons_head!_tail hl', ← List.cons_head!_tail hl] at h exact head_le_of_lt h theorem cons_le_cons [LinearOrder Ξ±] (a : Ξ±) {l l' : List Ξ±} (h : l' ≀ l) : a :: l' ≀ a :: l := by rw [le_iff_lt_or_eq] at h ⊒ exact h.imp .cons (congr_arg _) end List
.lake/packages/mathlib/Mathlib/Data/List/TFAE.lean
import Batteries.Tactic.Alias import Batteries.Data.List.Basic import Mathlib.Tactic.TypeStar /-! # The Following Are Equivalent This file allows to state that all propositions in a list are equivalent. It is used by `Mathlib/Tactic/Tfae.lean`. `TFAE l` means `βˆ€ x ∈ l, βˆ€ y ∈ l, x ↔ y`. This is equivalent to `Pairwise (↔) l`. -/ namespace List /-- TFAE: The Following (propositions) Are Equivalent. The `tfae_have` and `tfae_finish` tactics can be useful in proofs with `TFAE` goals. -/ def TFAE (l : List Prop) : Prop := βˆ€ x ∈ l, βˆ€ y ∈ l, x ↔ y theorem tfae_nil : TFAE [] := forall_mem_nil _ @[simp] theorem tfae_singleton (p) : TFAE [p] := by simp [TFAE, -eq_iff_iff] theorem tfae_cons_of_mem {a b} {l : List Prop} (h : b ∈ l) : TFAE (a :: l) ↔ (a ↔ b) ∧ TFAE l := ⟨fun H => ⟨H a (by simp) b (Mem.tail a h), fun _ hp _ hq => H _ (Mem.tail a hp) _ (Mem.tail a hq)⟩, by rintro ⟨ab, H⟩ p (_ | ⟨_, hp⟩) q (_ | ⟨_, hq⟩) Β· rfl Β· exact ab.trans (H _ h _ hq) Β· exact (ab.trans (H _ h _ hp)).symm Β· exact H _ hp _ hq⟩ theorem tfae_cons_cons {a b} {l : List Prop} : TFAE (a :: b :: l) ↔ (a ↔ b) ∧ TFAE (b :: l) := tfae_cons_of_mem (Mem.head _) @[simp] theorem tfae_cons_self {a} {l : List Prop} : TFAE (a :: a :: l) ↔ TFAE (a :: l) := by simp [tfae_cons_cons] theorem tfae_of_forall (b : Prop) (l : List Prop) (h : βˆ€ a ∈ l, a ↔ b) : TFAE l := fun _a₁ h₁ _aβ‚‚ hβ‚‚ => (h _ h₁).trans (h _ hβ‚‚).symm theorem tfae_of_cycle {a b} {l : List Prop} (h_chain : List.IsChain (Β· β†’ Β·) (a :: b :: l)) (h_last : getLastD l b β†’ a) : TFAE (a :: b :: l) := by induction l generalizing a b with | nil => simp_all [tfae_cons_cons, iff_def] | cons c l IH => simp only [tfae_cons_cons, getLastD_cons, isChain_cons_cons] at * rcases h_chain with ⟨ab, ⟨bc, ch⟩⟩ have := IH ⟨bc, ch⟩ (ab ∘ h_last) exact ⟨⟨ab, h_last ∘ (this.2 c (.head _) _ getLastD_mem_cons).1 ∘ bc⟩, this⟩ theorem TFAE.out {l} (h : TFAE l) (n₁ nβ‚‚ : Nat) {a b} (h₁ : l[n₁]? = some a := by rfl) (hβ‚‚ : l[nβ‚‚]? = some b := by rfl) : a ↔ b := h _ (List.mem_of_getElem? h₁) _ (List.mem_of_getElem? hβ‚‚) /-- If `P₁ x ↔ ... ↔ Pβ‚™ x` for all `x`, then `(βˆ€ x, P₁ x) ↔ ... ↔ (βˆ€ x, Pβ‚™ x)`. Note: in concrete cases, Lean has trouble finding the list `[P₁, ..., Pβ‚™]` from the list `[(βˆ€ x, P₁ x), ..., (βˆ€ x, Pβ‚™ x)]`, but simply providing a list of underscores with the right length makes it happier. Example: ```lean example (P₁ Pβ‚‚ P₃ : β„• β†’ Prop) (H : βˆ€ n, [P₁ n, Pβ‚‚ n, P₃ n].TFAE) : [βˆ€ n, P₁ n, βˆ€ n, Pβ‚‚ n, βˆ€ n, P₃ n].TFAE := forall_tfae [_, _, _] H ``` -/ theorem forall_tfae {Ξ± : Type*} (l : List (Ξ± β†’ Prop)) (H : βˆ€ a : Ξ±, (l.map (fun p ↦ p a)).TFAE) : (l.map (fun p ↦ βˆ€ a, p a)).TFAE := by simp only [TFAE, List.forall_mem_map] intro p₁ hp₁ pβ‚‚ hpβ‚‚ exact forall_congr' fun a ↦ H a (p₁ a) (mem_map_of_mem hp₁) (pβ‚‚ a) (mem_map_of_mem hpβ‚‚) /-- If `P₁ x ↔ ... ↔ Pβ‚™ x` for all `x`, then `(βˆƒ x, P₁ x) ↔ ... ↔ (βˆƒ x, Pβ‚™ x)`. Note: in concrete cases, Lean has trouble finding the list `[P₁, ..., Pβ‚™]` from the list `[(βˆƒ x, P₁ x), ..., (βˆƒ x, Pβ‚™ x)]`, but simply providing a list of underscores with the right length makes it happier. Example: ```lean example (P₁ Pβ‚‚ P₃ : β„• β†’ Prop) (H : βˆ€ n, [P₁ n, Pβ‚‚ n, P₃ n].TFAE) : [βˆƒ n, P₁ n, βˆƒ n, Pβ‚‚ n, βˆƒ n, P₃ n].TFAE := exists_tfae [_, _, _] H ``` -/ theorem exists_tfae {Ξ± : Type*} (l : List (Ξ± β†’ Prop)) (H : βˆ€ a : Ξ±, (l.map (fun p ↦ p a)).TFAE) : (l.map (fun p ↦ βˆƒ a, p a)).TFAE := by simp only [TFAE, List.forall_mem_map] intro p₁ hp₁ pβ‚‚ hpβ‚‚ exact exists_congr fun a ↦ H a (p₁ a) (mem_map_of_mem hp₁) (pβ‚‚ a) (mem_map_of_mem hpβ‚‚) theorem tfae_not_iff {l : List Prop} : TFAE (l.map Not) ↔ TFAE l := by classical simp only [TFAE, mem_map, forall_exists_index, and_imp, forall_apply_eq_imp_iffβ‚‚, Decidable.not_iff_not] alias ⟨_, TFAE.not⟩ := tfae_not_iff end List
.lake/packages/mathlib/Mathlib/Data/List/Permutation.lean
import Mathlib.Data.List.Lemmas import Mathlib.Data.Nat.Factorial.Basic import Mathlib.Data.List.Count import Mathlib.Data.List.Duplicate import Mathlib.Data.List.InsertIdx import Mathlib.Data.List.Induction import Batteries.Data.List.Perm import Mathlib.Data.List.Perm.Basic /-! # Permutations of a list In this file we prove properties about `List.Permutations`, a list of all permutations of a list. It is defined in `Data.List.Defs`. ## Order of the permutations Designed for performance, the order in which the permutations appear in `List.Permutations` is rather intricate and not very amenable to induction. That's why we also provide `List.Permutations'` as a less efficient but more straightforward way of listing permutations. ### `List.Permutations` TODO. In the meantime, you can try decrypting the docstrings. ### `List.Permutations'` The list of partitions is built by recursion. The permutations of `[]` are `[[]]`. Then, the permutations of `a :: l` are obtained by taking all permutations of `l` in order and adding `a` in all positions. Hence, to build `[0, 1, 2, 3].permutations'`, it does * `[[]]` * `[[3]]` * `[[2, 3], [3, 2]]]` * `[[1, 2, 3], [2, 1, 3], [2, 3, 1], [1, 3, 2], [3, 1, 2], [3, 2, 1]]` * `[[0, 1, 2, 3], [1, 0, 2, 3], [1, 2, 0, 3], [1, 2, 3, 0],` `[0, 2, 1, 3], [2, 0, 1, 3], [2, 1, 0, 3], [2, 1, 3, 0],` `[0, 2, 3, 1], [2, 0, 3, 1], [2, 3, 0, 1], [2, 3, 1, 0],` `[0, 1, 3, 2], [1, 0, 3, 2], [1, 3, 0, 2], [1, 3, 2, 0],` `[0, 3, 1, 2], [3, 0, 1, 2], [3, 1, 0, 2], [3, 1, 2, 0],` `[0, 3, 2, 1], [3, 0, 2, 1], [3, 2, 0, 1], [3, 2, 1, 0]]` -/ -- Make sure we don't import algebra assert_not_exists Monoid open Nat Function variable {Ξ± Ξ² : Type*} namespace List theorem permutationsAux2_fst (t : Ξ±) (ts : List Ξ±) (r : List Ξ²) : βˆ€ (ys : List Ξ±) (f : List Ξ± β†’ Ξ²), (permutationsAux2 t ts r ys f).1 = ys ++ ts | [], _ => rfl | y :: ys, f => by simp [permutationsAux2, permutationsAux2_fst t _ _ ys] @[simp] theorem permutationsAux2_snd_nil (t : Ξ±) (ts : List Ξ±) (r : List Ξ²) (f : List Ξ± β†’ Ξ²) : (permutationsAux2 t ts r [] f).2 = r := rfl @[simp] theorem permutationsAux2_snd_cons (t : Ξ±) (ts : List Ξ±) (r : List Ξ²) (y : Ξ±) (ys : List Ξ±) (f : List Ξ± β†’ Ξ²) : (permutationsAux2 t ts r (y :: ys) f).2 = f (t :: y :: ys ++ ts) :: (permutationsAux2 t ts r ys fun x : List Ξ± => f (y :: x)).2 := by simp [permutationsAux2, permutationsAux2_fst t _ _ ys] /-- The `r` argument to `permutationsAux2` is the same as appending. -/ theorem permutationsAux2_append (t : Ξ±) (ts : List Ξ±) (r : List Ξ²) (ys : List Ξ±) (f : List Ξ± β†’ Ξ²) : (permutationsAux2 t ts nil ys f).2 ++ r = (permutationsAux2 t ts r ys f).2 := by induction ys generalizing f <;> simp [*] /-- The `ts` argument to `permutationsAux2` can be folded into the `f` argument. -/ theorem permutationsAux2_comp_append {t : Ξ±} {ts ys : List Ξ±} {r : List Ξ²} (f : List Ξ± β†’ Ξ²) : ((permutationsAux2 t [] r ys) fun x => f (x ++ ts)).2 = (permutationsAux2 t ts r ys f).2 := by induction ys generalizing f with | nil => simp | cons ys_hd _ ys_ih => simp [ys_ih fun xs => f (ys_hd :: xs)] theorem map_permutationsAux2' {Ξ±' Ξ²'} (g : Ξ± β†’ Ξ±') (g' : Ξ² β†’ Ξ²') (t : Ξ±) (ts ys : List Ξ±) (r : List Ξ²) (f : List Ξ± β†’ Ξ²) (f' : List Ξ±' β†’ Ξ²') (H : βˆ€ a, g' (f a) = f' (map g a)) : map g' (permutationsAux2 t ts r ys f).2 = (permutationsAux2 (g t) (map g ts) (map g' r) (map g ys) f').2 := by induction ys generalizing f f' with | nil => simp | cons ys_hd _ ys_ih => simp only [map, permutationsAux2_snd_cons, cons_append, cons.injEq] rw [ys_ih] Β· refine ⟨?_, rfl⟩ simp only [← map_cons, ← map_append]; apply H Β· intro a; apply H /-- The `f` argument to `permutationsAux2` when `r = []` can be eliminated. -/ theorem map_permutationsAux2 (t : Ξ±) (ts : List Ξ±) (ys : List Ξ±) (f : List Ξ± β†’ Ξ²) : (permutationsAux2 t ts [] ys id).2.map f = (permutationsAux2 t ts [] ys f).2 := by rw [map_permutationsAux2' id, map_id, map_id] Β· rfl simp /-- An expository lemma to show how all of `ts`, `r`, and `f` can be eliminated from `permutationsAux2`. `(permutationsAux2 t [] [] ys id).2`, which appears on the RHS, is a list whose elements are produced by inserting `t` into every non-terminal position of `ys` in order. As an example: ```lean #eval permutationsAux2 1 [] [] [2, 3, 4] id -- [[1, 2, 3, 4], [2, 1, 3, 4], [2, 3, 1, 4]] ``` -/ theorem permutationsAux2_snd_eq (t : Ξ±) (ts : List Ξ±) (r : List Ξ²) (ys : List Ξ±) (f : List Ξ± β†’ Ξ²) : (permutationsAux2 t ts r ys f).2 = ((permutationsAux2 t [] [] ys id).2.map fun x => f (x ++ ts)) ++ r := by rw [← permutationsAux2_append, map_permutationsAux2, permutationsAux2_comp_append] theorem map_map_permutationsAux2 {Ξ±'} (g : Ξ± β†’ Ξ±') (t : Ξ±) (ts ys : List Ξ±) : map (map g) (permutationsAux2 t ts [] ys id).2 = (permutationsAux2 (g t) (map g ts) [] (map g ys) id).2 := map_permutationsAux2' _ _ _ _ _ _ _ _ fun _ => rfl theorem map_map_permutations'Aux (f : Ξ± β†’ Ξ²) (t : Ξ±) (ts : List Ξ±) : map (map f) (permutations'Aux t ts) = permutations'Aux (f t) (map f ts) := by induction ts with | nil => rfl | cons a ts ih => simp only [permutations'Aux, map_cons, map_map, ← ih, Function.comp_def] theorem permutations'Aux_eq_permutationsAux2 (t : Ξ±) (ts : List Ξ±) : permutations'Aux t ts = (permutationsAux2 t [] [ts ++ [t]] ts id).2 := by induction ts with | nil => rfl | cons a ts ih => ?_ simp only [permutations'Aux, ih, cons_append, permutationsAux2_snd_cons, append_nil, id_eq, cons.injEq, true_and] simp +singlePass only [← permutationsAux2_append] simp [map_permutationsAux2] theorem mem_permutationsAux2 {t : Ξ±} {ts : List Ξ±} {ys : List Ξ±} {l l' : List Ξ±} : l' ∈ (permutationsAux2 t ts [] ys (l ++ Β·)).2 ↔ βˆƒ l₁ lβ‚‚, lβ‚‚ β‰  [] ∧ ys = l₁ ++ lβ‚‚ ∧ l' = l ++ l₁ ++ t :: lβ‚‚ ++ ts := by induction ys generalizing l with | nil => simp +contextual | cons y ys ih => ?_ rw [permutationsAux2_snd_cons, show (fun x : List Ξ± => l ++ y :: x) = (l ++ [y] ++ Β·) by simp, mem_cons, ih] constructor Β· rintro (rfl | ⟨l₁, lβ‚‚, l0, rfl, rfl⟩) Β· exact ⟨[], y :: ys, by simp⟩ Β· exact ⟨y :: l₁, lβ‚‚, l0, by simp⟩ Β· rintro ⟨_ | ⟨y', lβ‚βŸ©, lβ‚‚, l0, ye, rfl⟩ Β· simp [ye] Β· simp only [cons_append] at ye rcases ye with ⟨rfl, rfl⟩ exact Or.inr ⟨l₁, lβ‚‚, l0, by simp⟩ theorem mem_permutationsAux2' {t : Ξ±} {ts : List Ξ±} {ys : List Ξ±} {l : List Ξ±} : l ∈ (permutationsAux2 t ts [] ys id).2 ↔ βˆƒ l₁ lβ‚‚, lβ‚‚ β‰  [] ∧ ys = l₁ ++ lβ‚‚ ∧ l = l₁ ++ t :: lβ‚‚ ++ ts := by rw [show @id (List Ξ±) = ([] ++ Β·) by funext _; rfl]; apply mem_permutationsAux2 theorem length_permutationsAux2 (t : Ξ±) (ts : List Ξ±) (ys : List Ξ±) (f : List Ξ± β†’ Ξ²) : length (permutationsAux2 t ts [] ys f).2 = length ys := by induction ys generalizing f <;> simp [*] theorem foldr_permutationsAux2 (t : Ξ±) (ts : List Ξ±) (r L : List (List Ξ±)) : foldr (fun y r => (permutationsAux2 t ts r y id).2) r L = (L.flatMap fun y => (permutationsAux2 t ts [] y id).2) ++ r := by induction L with | nil => rfl | cons l L ih => simp_rw [foldr_cons, ih, flatMap_cons, append_assoc, permutationsAux2_append] theorem mem_foldr_permutationsAux2 {t : Ξ±} {ts : List Ξ±} {r L : List (List Ξ±)} {l' : List Ξ±} : l' ∈ foldr (fun y r => (permutationsAux2 t ts r y id).2) r L ↔ l' ∈ r ∨ βˆƒ l₁ lβ‚‚, l₁ ++ lβ‚‚ ∈ L ∧ lβ‚‚ β‰  [] ∧ l' = l₁ ++ t :: lβ‚‚ ++ ts := by have : (βˆƒ a : List Ξ±, a ∈ L ∧ βˆƒ l₁ lβ‚‚ : List Ξ±, Β¬lβ‚‚ = nil ∧ a = l₁ ++ lβ‚‚ ∧ l' = l₁ ++ t :: (lβ‚‚ ++ ts)) ↔ βˆƒ l₁ lβ‚‚ : List Ξ±, Β¬lβ‚‚ = nil ∧ l₁ ++ lβ‚‚ ∈ L ∧ l' = l₁ ++ t :: (lβ‚‚ ++ ts) := ⟨fun ⟨_, aL, l₁, lβ‚‚, l0, e, h⟩ => ⟨l₁, lβ‚‚, l0, e β–Έ aL, h⟩, fun ⟨l₁, lβ‚‚, l0, aL, h⟩ => ⟨_, aL, l₁, lβ‚‚, l0, rfl, h⟩⟩ rw [foldr_permutationsAux2] simp only [mem_permutationsAux2', ← this, or_comm, and_left_comm, mem_append, mem_flatMap, append_assoc, cons_append] theorem length_foldr_permutationsAux2 (t : Ξ±) (ts : List Ξ±) (r L : List (List Ξ±)) : length (foldr (fun y r => (permutationsAux2 t ts r y id).2) r L) = (map length L).sum + length r := by simp [foldr_permutationsAux2, length_permutationsAux2, length_flatMap] theorem length_foldr_permutationsAux2' (t : Ξ±) (ts : List Ξ±) (r L : List (List Ξ±)) (n) (H : βˆ€ l ∈ L, length l = n) : length (foldr (fun y r => (permutationsAux2 t ts r y id).2) r L) = n * length L + length r := by rw [length_foldr_permutationsAux2, (_ : (map length L).sum = n * length L)] induction L with | nil => simp | cons l L ih => have sum_map : (map length L).sum = n * length L := ih fun l m => H l (mem_cons_of_mem _ m) have length_l : length l = n := H _ mem_cons_self simp [sum_map, length_l, Nat.add_comm, mul_succ] @[simp] theorem permutationsAux_nil (is : List Ξ±) : permutationsAux [] is = [] := by rw [permutationsAux, permutationsAux.rec] @[simp] theorem permutationsAux_cons (t : Ξ±) (ts is : List Ξ±) : permutationsAux (t :: ts) is = foldr (fun y r => (permutationsAux2 t ts r y id).2) (permutationsAux ts (t :: is)) (permutations is) := by rw [permutationsAux, permutationsAux.rec]; rfl @[simp] theorem permutations_nil : permutations ([] : List Ξ±) = [[]] := by rw [permutations, permutationsAux_nil] theorem map_permutationsAux (f : Ξ± β†’ Ξ²) : βˆ€ ts is : List Ξ±, map (map f) (permutationsAux ts is) = permutationsAux (map f ts) (map f is) := by refine permutationsAux.rec (by simp) ?_ introv IH1 IH2; rw [map] at IH2 simp only [foldr_permutationsAux2, map_append, map, map_map_permutationsAux2, permutations, flatMap_map, IH1, append_assoc, permutationsAux_cons, flatMap_cons, ← IH2, map_flatMap] theorem map_permutations (f : Ξ± β†’ Ξ²) (ts : List Ξ±) : map (map f) (permutations ts) = permutations (map f ts) := by rw [permutations, permutations, map, map_permutationsAux, map] theorem map_permutations' (f : Ξ± β†’ Ξ²) (ts : List Ξ±) : map (map f) (permutations' ts) = permutations' (map f ts) := by induction ts with | nil => rfl | cons t ts ih => simp [← ih, map_flatMap, ← map_map_permutations'Aux, flatMap_map] theorem permutationsAux_append (is is' ts : List Ξ±) : permutationsAux (is ++ ts) is' = (permutationsAux is is').map (Β· ++ ts) ++ permutationsAux ts (is.reverse ++ is') := by induction is generalizing is' with | nil => simp | cons t is ih => simp only [foldr_permutationsAux2, ih, map_flatMap, cons_append, permutationsAux_cons, map_append, reverse_cons, append_assoc] congr 2 funext _ rw [map_permutationsAux2] simp +singlePass only [← permutationsAux2_comp_append] simp only [id, append_assoc] theorem permutations_append (is ts : List Ξ±) : permutations (is ++ ts) = (permutations is).map (Β· ++ ts) ++ permutationsAux ts is.reverse := by simp [permutations, permutationsAux_append] theorem perm_of_mem_permutationsAux : βˆ€ {ts is l : List Ξ±}, l ∈ permutationsAux ts is β†’ l ~ ts ++ is := by show βˆ€ (ts is l : List Ξ±), l ∈ permutationsAux ts is β†’ l ~ ts ++ is refine permutationsAux.rec (by simp) ?_ introv IH1 IH2 m rw [permutationsAux_cons, permutations, mem_foldr_permutationsAux2] at m rcases m with (m | ⟨l₁, lβ‚‚, m, _, rfl⟩) Β· exact (IH1 _ m).trans perm_middle Β· have p : l₁ ++ lβ‚‚ ~ is := by simp only [mem_cons] at m rcases m with e | m Β· simp [e] exact is.append_nil β–Έ IH2 _ m exact ((perm_middle.trans (p.cons _)).append_right _).trans (perm_append_comm.cons _) theorem perm_of_mem_permutations {l₁ lβ‚‚ : List Ξ±} (h : l₁ ∈ permutations lβ‚‚) : l₁ ~ lβ‚‚ := (eq_or_mem_of_mem_cons h).elim (fun e => e β–Έ Perm.refl _) fun m => append_nil lβ‚‚ β–Έ perm_of_mem_permutationsAux m theorem length_permutationsAux : βˆ€ ts is : List Ξ±, length (permutationsAux ts is) + is.length ! = (length ts + length is)! := by refine permutationsAux.rec (by simp) ?_ intro t ts is IH1 IH2 have IH2 : length (permutationsAux is nil) + 1 = is.length ! := by simpa using IH2 simp only [length, factorial, Nat.mul_comm, add_eq] at IH1 rw [permutationsAux_cons, length_foldr_permutationsAux2' _ _ _ _ _ fun l m => (perm_of_mem_permutations m).length_eq, permutations, length, length, IH2, Nat.succ_add, Nat.factorial_succ, Nat.mul_comm (_ + 1), ← Nat.succ_eq_add_one, ← IH1, Nat.add_comm (_ * _), Nat.add_assoc, Nat.mul_succ, Nat.mul_comm] theorem length_permutations (l : List Ξ±) : length (permutations l) = (length l)! := length_permutationsAux l [] theorem mem_permutations_of_perm_lemma {is l : List Ξ±} (H : l ~ [] ++ is β†’ (βˆƒ (ts' : _) (_ : ts' ~ []), l = ts' ++ is) ∨ l ∈ permutationsAux is []) : l ~ is β†’ l ∈ permutations is := by simpa [permutations, perm_nil] using H theorem mem_permutationsAux_of_perm : βˆ€ {ts is l : List Ξ±}, l ~ is ++ ts β†’ (βˆƒ (is' : _) (_ : is' ~ is), l = is' ++ ts) ∨ l ∈ permutationsAux ts is := by show βˆ€ (ts is l : List Ξ±), l ~ is ++ ts β†’ (βˆƒ (is' : _) (_ : is' ~ is), l = is' ++ ts) ∨ l ∈ permutationsAux ts is refine permutationsAux.rec (by simp) ?_ intro t ts is IH1 IH2 l p rw [permutationsAux_cons, mem_foldr_permutationsAux2] rcases IH1 _ (p.trans perm_middle) with (⟨is', p', e⟩ | m) Β· clear p subst e rcases append_of_mem (p'.symm.subset mem_cons_self) with ⟨l₁, lβ‚‚, e⟩ subst is' have p := (perm_middle.symm.trans p').cons_inv rcases lβ‚‚ with - | ⟨a, lβ‚‚'⟩ Β· exact Or.inl ⟨l₁, by simpa using p⟩ Β· exact Or.inr (Or.inr ⟨l₁, a :: lβ‚‚', mem_permutations_of_perm_lemma (IH2 _) p, by simp⟩) Β· exact Or.inr (Or.inl m) @[simp] theorem mem_permutations {s t : List Ξ±} : s ∈ permutations t ↔ s ~ t := ⟨perm_of_mem_permutations, mem_permutations_of_perm_lemma mem_permutationsAux_of_perm⟩ theorem perm_permutations'Aux_comm (a b : Ξ±) (l : List Ξ±) : (permutations'Aux a l).flatMap (permutations'Aux b) ~ (permutations'Aux b l).flatMap (permutations'Aux a) := by induction l with | nil => exact Perm.swap [a, b] [b, a] [] | cons c l ih => ?_ simp only [permutations'Aux, flatMap_cons, map_cons, map_map, cons_append] apply Perm.swap' have : βˆ€ a b, (map (cons c) (permutations'Aux a l)).flatMap (permutations'Aux b) ~ map (cons b ∘ cons c) (permutations'Aux a l) ++ map (cons c) ((permutations'Aux a l).flatMap (permutations'Aux b)) := by intro a' b' simp only [flatMap_map, permutations'Aux] change (permutations'Aux _ l).flatMap (fun a => ([b' :: c :: a] ++ map (cons c) (permutations'Aux _ a))) ~ _ refine (flatMap_append_perm _ (fun x => [b' :: c :: x]) _).symm.trans ?_ rw [← map_eq_flatMap, ← map_flatMap] exact Perm.refl _ refine (((this _ _).append_left _).trans ?_).trans ((this _ _).append_left _).symm rw [← append_assoc, ← append_assoc] exact perm_append_comm.append (ih.map _) theorem Perm.permutations' {s t : List Ξ±} (p : s ~ t) : permutations' s ~ permutations' t := by induction p with | nil => simp | cons _ _ IH => exact IH.flatMap_right _ | swap => dsimp rw [flatMap_assoc, flatMap_assoc] apply Perm.flatMap_left intro l' _ apply perm_permutations'Aux_comm | trans _ _ IH₁ IHβ‚‚ => exact IH₁.trans IHβ‚‚ theorem permutations_perm_permutations' (ts : List Ξ±) : ts.permutations ~ ts.permutations' := by obtain ⟨n, h⟩ : βˆƒ n, length ts < n := ⟨_, Nat.lt_succ_self _⟩ induction n generalizing ts with | zero => cases h | succ n IH => ?_ refine List.reverseRecOn ts (fun _ => ?_) (fun ts t _ h => ?_) h; Β· simp [permutations] rw [← concat_eq_append, length_concat, Nat.succ_lt_succ_iff] at h have IHβ‚‚ := (IH ts.reverse (by rwa [length_reverse])).trans (reverse_perm _).permutations' simp only [permutations_append, foldr_permutationsAux2, permutationsAux_nil, permutationsAux_cons, append_nil] refine (perm_append_comm.trans ((IHβ‚‚.flatMap_right _).append ((IH _ h).map _))).trans (Perm.trans ?_ perm_append_comm.permutations') rw [map_eq_flatMap, singleton_append, permutations'] refine (flatMap_append_perm _ _ _).trans ?_ refine Perm.of_eq ?_ congr funext _ rw [permutations'Aux_eq_permutationsAux2, permutationsAux2_append] @[simp] theorem mem_permutations' {s t : List Ξ±} : s ∈ permutations' t ↔ s ~ t := (permutations_perm_permutations' _).symm.mem_iff.trans mem_permutations theorem Perm.permutations {s t : List Ξ±} (h : s ~ t) : permutations s ~ permutations t := (permutations_perm_permutations' _).trans <| h.permutations'.trans (permutations_perm_permutations' _).symm @[simp] theorem perm_permutations_iff {s t : List Ξ±} : permutations s ~ permutations t ↔ s ~ t := ⟨fun h => mem_permutations.1 <| h.mem_iff.1 <| mem_permutations.2 (Perm.refl _), Perm.permutations⟩ @[simp] theorem perm_permutations'_iff {s t : List Ξ±} : permutations' s ~ permutations' t ↔ s ~ t := ⟨fun h => mem_permutations'.1 <| h.mem_iff.1 <| mem_permutations'.2 (Perm.refl _), Perm.permutations'⟩ theorem getElem_permutations'Aux (s : List Ξ±) (x : Ξ±) (n : β„•) (hn : n < length (permutations'Aux x s)) : (permutations'Aux x s)[n] = s.insertIdx n x := by induction s generalizing n with | nil => simp only [permutations'Aux, length, Nat.zero_add, lt_one_iff] at hn simp [hn] | cons y s IH => cases n Β· simp Β· simpa [get] using IH _ _ theorem get_permutations'Aux (s : List Ξ±) (x : Ξ±) (n : β„•) (hn : n < length (permutations'Aux x s)) : (permutations'Aux x s).get ⟨n, hn⟩ = s.insertIdx n x := by simp [getElem_permutations'Aux] -- Porting note: temporary theorem to solve diamond issue private theorem DecEq_eq [DecidableEq Ξ±] : List.instBEq = @instBEqOfDecidableEq (List Ξ±) instDecidableEqList := congr_arg BEq.mk <| by funext l₁ lβ‚‚ change (l₁ == lβ‚‚) = _ rw [Bool.eq_iff_iff, @beq_iff_eq _ (_), decide_eq_true_iff] theorem count_permutations'Aux_self [DecidableEq Ξ±] (l : List Ξ±) (x : Ξ±) : count (x :: l) (permutations'Aux x l) = length (takeWhile (x = Β·) l) + 1 := by induction l generalizing x with | nil => simp [takeWhile, count] | cons y l IH => rw [permutations'Aux, count_cons_self] by_cases hx : x = y Β· subst hx simpa [takeWhile, Nat.succ_inj, DecEq_eq] using IH _ Β· rw [takeWhile] simp only [mem_map, cons.injEq, Ne.symm hx, false_and, and_false, exists_false, not_false_iff, count_eq_zero_of_not_mem, Nat.zero_add, hx, decide_false, length_nil] @[simp] theorem length_permutations'Aux (s : List Ξ±) (x : Ξ±) : length (permutations'Aux x s) = length s + 1 := by induction s with | nil => simp | cons y s IH => simpa using IH theorem injective_permutations'Aux (x : Ξ±) : Function.Injective (permutations'Aux x) := by intro s t h apply insertIdx_injective s.length x dsimp have hl : s.length = t.length := by simpa using congr_arg length h rw [← get_permutations'Aux s x s.length (by simp), ← get_permutations'Aux t x s.length (by simp [hl])] simp only [get_eq_getElem, h, hl] theorem nodup_permutations'Aux_of_notMem (s : List Ξ±) (x : Ξ±) (hx : x βˆ‰ s) : Nodup (permutations'Aux x s) := by induction s with | nil => simp | cons y s IH => simp only [not_or, mem_cons] at hx simp only [permutations'Aux, nodup_cons, mem_map, cons.injEq, exists_eq_right_right, not_and] refine ⟨fun _ => Ne.symm hx.left, ?_⟩ rw [nodup_map_iff] Β· exact IH hx.right Β· simp @[deprecated (since := "2025-05-23")] alias nodup_permutations'Aux_of_not_mem := nodup_permutations'Aux_of_notMem theorem nodup_permutations'Aux_iff {s : List Ξ±} {x : Ξ±} : Nodup (permutations'Aux x s) ↔ x βˆ‰ s := by refine ⟨fun h H ↦ ?_, nodup_permutations'Aux_of_notMem _ _⟩ obtain ⟨⟨k, hk⟩, hk'⟩ := get_of_mem H rw [nodup_iff_injective_get] at h apply k.succ_ne_self.symm have kl : k < (permutations'Aux x s).length := by simpa [Nat.lt_succ_iff] using hk.le have k1l : k + 1 < (permutations'Aux x s).length := by simpa using hk rw [← @Fin.mk.inj_iff _ _ _ kl k1l]; apply h rw [get_permutations'Aux, get_permutations'Aux] have hl : length (s.insertIdx k x) = length (s.insertIdx (k + 1) x) := by rw [length_insertIdx_of_le_length hk.le, length_insertIdx_of_le_length (Nat.succ_le_of_lt hk)] exact ext_get hl fun n hn hn' => by grind theorem nodup_permutations (s : List Ξ±) (hs : Nodup s) : Nodup s.permutations := by rw [(permutations_perm_permutations' s).nodup_iff] induction hs with | nil => simp | @cons x l h h' IH => rw [permutations'] rw [nodup_flatMap] constructor Β· intro ys hy rw [mem_permutations'] at hy rw [nodup_permutations'Aux_iff, hy.mem_iff] exact fun H => h x H rfl Β· refine IH.pairwise_of_forall_ne fun as ha bs hb H => ?_ rw [Function.onFun, disjoint_iff_ne] rintro a ha' b hb' rfl obtain ⟨⟨n, hn⟩, hn'⟩ := get_of_mem ha' obtain ⟨⟨m, hm⟩, hm'⟩ := get_of_mem hb' rw [mem_permutations'] at ha hb have hl : as.length = bs.length := (ha.trans hb.symm).length_eq simp only [Nat.lt_succ_iff, length_permutations'Aux] at hn hm rw [get_permutations'Aux] at hn' hm' have hx : (as.insertIdx n x)[m]'(by rwa [length_insertIdx_of_le_length hn, Nat.lt_succ_iff, hl]) = x := by simp [hn', ← hm'] have hx' : (bs.insertIdx m x)[n]'(by rwa [length_insertIdx_of_le_length hm, Nat.lt_succ_iff, ← hl]) = x := by simp [hm', ← hn'] rcases lt_trichotomy n m with (ht | ht | ht) Β· suffices x ∈ bs by exact h x (hb.subset this) rfl rw [← hx', getElem_insertIdx_of_lt ht] exact getElem_mem _ Β· simp only [ht] at hm' hn' rw [← hm'] at hn' exact H (insertIdx_injective _ _ hn') Β· suffices x ∈ as by exact h x (ha.subset this) rfl rw [← hx, getElem_insertIdx_of_lt ht] exact getElem_mem _ lemma permutations_take_two (x y : Ξ±) (s : List Ξ±) : (x :: y :: s).permutations.take 2 = [x :: y :: s, y :: x :: s] := by induction s <;> simp [permutations] @[simp] theorem nodup_permutations_iff {s : List Ξ±} : Nodup s.permutations ↔ Nodup s := by refine ⟨?_, nodup_permutations s⟩ contrapose rw [← exists_duplicate_iff_not_nodup] intro ⟨x, hs⟩ rw [duplicate_iff_sublist] at hs obtain ⟨l, ht⟩ := List.Sublist.exists_perm_append hs rw [List.Perm.nodup_iff (List.Perm.permutations ht), ← exists_duplicate_iff_not_nodup] use x :: x :: l rw [List.duplicate_iff_sublist, ← permutations_take_two] exact take_sublist 2 _ -- TODO: `count s s.permutations = (zipWith count s s.tails).prod` end List
.lake/packages/mathlib/Mathlib/Data/List/Sigma.lean
import Batteries.Data.List.Perm import Mathlib.Data.List.Pairwise import Mathlib.Data.List.Nodup import Mathlib.Data.List.Lookmap import Mathlib.Data.Sigma.Basic /-! # Utilities for lists of sigmas This file includes several ways of interacting with `List (Sigma Ξ²)`, treated as a key-value store. If `Ξ± : Type*` and `Ξ² : Ξ± β†’ Type*`, then we regard `s : Sigma Ξ²` as having key `s.1 : Ξ±` and value `s.2 : Ξ² s.1`. Hence, `List (Sigma Ξ²)` behaves like a key-value store. ## Main Definitions - `List.keys` extracts the list of keys. - `List.NodupKeys` determines if the store has duplicate keys. - `List.lookup`/`lookup_all` accesses the value(s) of a particular key. - `List.kreplace` replaces the first value with a given key by a given value. - `List.kerase` removes a value. - `List.kinsert` inserts a value. - `List.kunion` computes the union of two stores. - `List.kextract` returns a value with a given key and the rest of the values. -/ universe u u' v v' namespace List variable {Ξ± : Type u} {Ξ±' : Type u'} {Ξ² : Ξ± β†’ Type v} {Ξ²' : Ξ±' β†’ Type v'} {l l₁ lβ‚‚ : List (Sigma Ξ²)} /-! ### `keys` -/ /-- List of keys from a list of key-value pairs -/ def keys : List (Sigma Ξ²) β†’ List Ξ± := map Sigma.fst @[simp, grind =] theorem keys_nil : @keys Ξ± Ξ² [] = [] := rfl @[simp, grind =] theorem keys_cons {s} {l : List (Sigma Ξ²)} : (s :: l).keys = s.1 :: l.keys := rfl @[simp, grind =] theorem keys_append : (l₁ ++ lβ‚‚).keys = l₁.keys ++ lβ‚‚.keys := by simp [keys] theorem mem_keys_of_mem {s : Sigma Ξ²} {l : List (Sigma Ξ²)} : s ∈ l β†’ s.1 ∈ l.keys := mem_map_of_mem theorem exists_of_mem_keys {a} {l : List (Sigma Ξ²)} (h : a ∈ l.keys) : βˆƒ b : Ξ² a, Sigma.mk a b ∈ l := by have := exists_of_mem_map h grind @[grind =] theorem mem_keys {a} {l : List (Sigma Ξ²)} : a ∈ l.keys ↔ βˆƒ b : Ξ² a, Sigma.mk a b ∈ l := ⟨exists_of_mem_keys, fun ⟨_, h⟩ => mem_keys_of_mem h⟩ theorem notMem_keys {a} {l : List (Sigma Ξ²)} : a βˆ‰ l.keys ↔ βˆ€ b : Ξ² a, Sigma.mk a b βˆ‰ l := by grind @[deprecated (since := "2025-05-23")] alias not_mem_keys := notMem_keys theorem ne_key {a} {l : List (Sigma Ξ²)} : a βˆ‰ l.keys ↔ βˆ€ s : Sigma Ξ², s ∈ l β†’ a β‰  s.1 := by grind @[deprecated (since := "2025-04-27")] alias not_eq_key := ne_key /-! ### `NodupKeys` -/ /-- Determines whether the store uses a key several times. -/ @[grind] def NodupKeys (l : List (Sigma Ξ²)) : Prop := l.keys.Nodup theorem nodupKeys_iff_pairwise {l} : NodupKeys l ↔ Pairwise (fun s s' : Sigma Ξ² => s.1 β‰  s'.1) l := pairwise_map theorem NodupKeys.pairwise_ne {l} (h : NodupKeys l) : Pairwise (fun s s' : Sigma Ξ² => s.1 β‰  s'.1) l := nodupKeys_iff_pairwise.1 h @[simp] theorem nodupKeys_nil : @NodupKeys Ξ± Ξ² [] := Pairwise.nil @[simp] theorem nodupKeys_cons {s : Sigma Ξ²} {l : List (Sigma Ξ²)} : NodupKeys (s :: l) ↔ s.1 βˆ‰ l.keys ∧ NodupKeys l := by simp [keys, NodupKeys] theorem nodupKeys_middle {s : Sigma Ξ²} : (l₁ ++ s :: lβ‚‚).NodupKeys ↔ (s :: (l₁ ++ lβ‚‚)).NodupKeys := by simp_all [NodupKeys, keys, nodup_middle] theorem notMem_keys_of_nodupKeys_cons {s : Sigma Ξ²} {l : List (Sigma Ξ²)} (h : NodupKeys (s :: l)) : s.1 βˆ‰ l.keys := by grind @[deprecated (since := "2025-05-23")] alias not_mem_keys_of_nodupKeys_cons := notMem_keys_of_nodupKeys_cons theorem nodupKeys_of_nodupKeys_cons {s : Sigma Ξ²} {l : List (Sigma Ξ²)} (h : NodupKeys (s :: l)) : NodupKeys l := (nodupKeys_cons.1 h).2 theorem NodupKeys.eq_of_fst_eq {l : List (Sigma Ξ²)} (nd : NodupKeys l) {s s' : Sigma Ξ²} (h : s ∈ l) (h' : s' ∈ l) : s.1 = s'.1 β†’ s = s' := @Pairwise.forall_of_forall _ (fun s s' : Sigma Ξ² => s.1 = s'.1 β†’ s = s') _ (fun _ _ H h => (H h.symm).symm) (fun _ _ _ => rfl) ((nodupKeys_iff_pairwise.1 nd).imp fun h h' => (h h').elim) _ h _ h' theorem NodupKeys.eq_of_mk_mem {a : Ξ±} {b b' : Ξ² a} {l : List (Sigma Ξ²)} (nd : NodupKeys l) (h : Sigma.mk a b ∈ l) (h' : Sigma.mk a b' ∈ l) : b = b' := by grind [NodupKeys.eq_of_fst_eq] theorem nodupKeys_singleton (s : Sigma Ξ²) : NodupKeys [s] := nodup_singleton _ theorem NodupKeys.sublist {l₁ lβ‚‚ : List (Sigma Ξ²)} (h : l₁ <+ lβ‚‚) : NodupKeys lβ‚‚ β†’ NodupKeys l₁ := Nodup.sublist <| h.map _ @[grind β†’] protected theorem NodupKeys.nodup {l : List (Sigma Ξ²)} : NodupKeys l β†’ Nodup l := Nodup.of_map _ theorem perm_nodupKeys {l₁ lβ‚‚ : List (Sigma Ξ²)} (h : l₁ ~ lβ‚‚) : NodupKeys l₁ ↔ NodupKeys lβ‚‚ := (h.map _).nodup_iff theorem nodupKeys_flatten {L : List (List (Sigma Ξ²))} : NodupKeys (flatten L) ↔ (βˆ€ l ∈ L, NodupKeys l) ∧ Pairwise Disjoint (L.map keys) := by rw [nodupKeys_iff_pairwise, pairwise_flatten, pairwise_map] refine and_congr (forallβ‚‚_congr fun l _ => by simp [nodupKeys_iff_pairwise]) ?_ apply iff_of_eq; congr! with (l₁ lβ‚‚) simp [keys, disjoint_iff_ne, Sigma.forall] theorem nodup_zipIdx_map_snd (l : List Ξ±) : (l.zipIdx.map Prod.snd).Nodup := by simp [List.nodup_range'] theorem mem_ext {lβ‚€ l₁ : List (Sigma Ξ²)} (ndβ‚€ : lβ‚€.Nodup) (nd₁ : l₁.Nodup) (h : βˆ€ x, x ∈ lβ‚€ ↔ x ∈ l₁) : lβ‚€ ~ l₁ := by grind [perm_ext_iff_of_nodup] variable [DecidableEq Ξ±] [DecidableEq Ξ±'] /-! ### `dlookup` -/ /-- `dlookup a l` is the first value in `l` corresponding to the key `a`, or `none` if no such element exists. -/ def dlookup (a : Ξ±) : List (Sigma Ξ²) β†’ Option (Ξ² a) | [] => none | ⟨a', b⟩ :: l => if h : a' = a then some (Eq.recOn h b) else dlookup a l @[simp, grind =] theorem dlookup_nil (a : Ξ±) : dlookup a [] = @none (Ξ² a) := rfl @[simp, grind =] theorem dlookup_cons_eq (l) (a : Ξ±) (b : Ξ² a) : dlookup a (⟨a, b⟩ :: l) = some b := dif_pos rfl @[simp, grind =] theorem dlookup_cons_ne (l) {a} : βˆ€ s : Sigma Ξ², a β‰  s.1 β†’ dlookup a (s :: l) = dlookup a l | ⟨_, _⟩, h => dif_neg h.symm @[grind =] theorem dlookup_isSome {a : Ξ±} {l : List (Sigma Ξ²)} : (dlookup a l).isSome ↔ a ∈ l.keys := by induction l with | nil => simp | cons s _ _ => by_cases a = s.fst <;> grind theorem dlookup_eq_none {a : Ξ±} {l : List (Sigma Ξ²)} : dlookup a l = none ↔ a βˆ‰ l.keys := by simp [← dlookup_isSome, Option.isNone_iff_eq_none] theorem of_mem_dlookup {a : Ξ±} {b : Ξ² a} {l : List (Sigma Ξ²)} : b ∈ dlookup a l β†’ Sigma.mk a b ∈ l := by induction l with | nil => grind | cons s _ _ => by_cases a = s.fst <;> grind theorem mem_dlookup {a} {b : Ξ² a} {l : List (Sigma Ξ²)} (nd : l.NodupKeys) (h : Sigma.mk a b ∈ l) : b ∈ dlookup a l := by obtain ⟨b', h'⟩ := Option.isSome_iff_exists.mp (dlookup_isSome.mpr (mem_keys_of_mem h)) cases nd.eq_of_mk_mem h (of_mem_dlookup h') exact h' theorem map_dlookup_eq_find (a : Ξ±) (l : List (Sigma Ξ²)) : (dlookup a l).map (Sigma.mk a) = find? (fun s => a = s.1) l := by induction l with | nil => grind | cons s _ _ => by_cases s.fst = a <;> grind theorem mem_dlookup_iff {a : Ξ±} {b : Ξ² a} {l : List (Sigma Ξ²)} (nd : l.NodupKeys) : b ∈ dlookup a l ↔ Sigma.mk a b ∈ l := ⟨of_mem_dlookup, mem_dlookup nd⟩ theorem perm_dlookup (a : Ξ±) {l₁ lβ‚‚ : List (Sigma Ξ²)} (nd₁ : l₁.NodupKeys) (p : l₁ ~ lβ‚‚) : dlookup a l₁ = dlookup a lβ‚‚ := by have ndβ‚‚ := (perm_nodupKeys p).mp nd₁ ext b; simp only [← Option.mem_def, mem_dlookup_iff nd₁, mem_dlookup_iff ndβ‚‚, p.mem_iff] theorem lookup_ext {lβ‚€ l₁ : List (Sigma Ξ²)} (ndβ‚€ : lβ‚€.NodupKeys) (nd₁ : l₁.NodupKeys) (h : βˆ€ x y, y ∈ lβ‚€.dlookup x ↔ y ∈ l₁.dlookup x) : lβ‚€ ~ l₁ := by grind [_=_ mem_dlookup_iff, mem_ext] theorem dlookup_map (l : List (Sigma Ξ²)) {f : Ξ± β†’ Ξ±'} (hf : Function.Injective f) (g : βˆ€ a, Ξ² a β†’ Ξ²' (f a)) (a : Ξ±) : (l.map (.map f g)).dlookup (f a) = (l.dlookup a).map (g a) := by induction l with | nil => grind | cons s _ _ => have (h : a β‰  s.fst) : Β¬ f a = (⟨f s.fst, g s.fst s.snd⟩ : Sigma Ξ²').fst := fun he => h <| hf he by_cases a = s.fst <;> grind [Sigma.map] theorem dlookup_map₁ {Ξ² : Type v} (l : List (Ξ£ _ : Ξ±, Ξ²)) {f : Ξ± β†’ Ξ±'} (hf : Function.Injective f) (a : Ξ±) : (l.map (.map f fun _ => id) : List (Ξ£ _ : Ξ±', Ξ²)).dlookup (f a) = l.dlookup a := by have := dlookup_map (Ξ²' := fun _ => Ξ²) (f := f) (g := fun _ => id) grind [Option.map_id'] theorem dlookup_mapβ‚‚ {Ξ³ Ξ΄ : Ξ± β†’ Type*} {l : List (Ξ£ a, Ξ³ a)} {f : βˆ€ a, Ξ³ a β†’ Ξ΄ a} (a : Ξ±) : (l.map (.map id f) : List (Ξ£ a, Ξ΄ a)).dlookup a = (l.dlookup a).map (f a) := dlookup_map l Function.injective_id _ _ theorem NodupKeys.map₁ {Ξ² : Type v} (f : Ξ± β†’ Ξ±') (hf : Function.Injective f) {l : List (Ξ£ _ : Ξ±, Ξ²)} (nd : l.NodupKeys) : (l.map (.map f fun _ => id) : List (Ξ£ _ : Ξ±', Ξ²)).NodupKeys := by induction l with | nil => grind [nodupKeys_nil] | cons hd tl => have := dlookup_map₁ tl hf hd.fst grind [dlookup_isSome, β†’ notMem_keys_of_nodupKeys_cons, nodupKeys_of_nodupKeys_cons, nodupKeys_cons] omit [DecidableEq Ξ±] in theorem mapβ‚‚_keys {Ξ² Ξ²' : Ξ± β†’ Type*} (f : (a : Ξ±) β†’ Ξ² a β†’ Ξ²' a) (l : List (Ξ£ a, Ξ² a)) : (l.map (.map id f)).keys = l.keys := by induction l <;> grind [Sigma.map] omit [DecidableEq Ξ±] in theorem NodupKeys.mapβ‚‚ {Ξ² Ξ²' : Ξ± β†’ Type*} (f : (a : Ξ±) β†’ Ξ² a β†’ Ξ²' a) (l : List (Ξ£ a, Ξ² a)) (nd : l.NodupKeys) : (l.map (.map id f)).NodupKeys := by simp_all [NodupKeys, mapβ‚‚_keys] @[simp, grind =] theorem dlookup_append (l₁ lβ‚‚ : List (Sigma Ξ²)) (a : Ξ±) : (l₁ ++ lβ‚‚).dlookup a = (l₁.dlookup a).or (lβ‚‚.dlookup a) := by induction l₁ with | nil => rfl | cons s _ _ => by_cases a = s.fst <;> grind theorem sublist_dlookup {l₁ lβ‚‚ : List (Sigma Ξ²)} {a : Ξ±} {b : Ξ² a} (ndβ‚‚ : lβ‚‚.NodupKeys) (s : l₁ <+ lβ‚‚) (mem : b ∈ l₁.dlookup a) : b ∈ lβ‚‚.dlookup a := by grind [Option.mem_def, => perm_dlookup, β†’ Sublist.exists_perm_append] /-! ### `lookupAll` -/ /-- `lookup_all a l` is the list of all values in `l` corresponding to the key `a`. -/ def lookupAll (a : Ξ±) : List (Sigma Ξ²) β†’ List (Ξ² a) | [] => [] | ⟨a', b⟩ :: l => if h : a' = a then Eq.recOn h b :: lookupAll a l else lookupAll a l @[simp] theorem lookupAll_nil (a : Ξ±) : lookupAll a [] = @nil (Ξ² a) := rfl @[simp] theorem lookupAll_cons_eq (l) (a : Ξ±) (b : Ξ² a) : lookupAll a (⟨a, b⟩ :: l) = b :: lookupAll a l := dif_pos rfl @[simp] theorem lookupAll_cons_ne (l) {a} : βˆ€ s : Sigma Ξ², a β‰  s.1 β†’ lookupAll a (s :: l) = lookupAll a l | ⟨_, _⟩, h => dif_neg h.symm theorem lookupAll_eq_nil {a : Ξ±} : βˆ€ {l : List (Sigma Ξ²)}, lookupAll a l = [] ↔ βˆ€ b : Ξ² a, Sigma.mk a b βˆ‰ l | [] => by simp | ⟨a', b⟩ :: l => by by_cases h : a = a' Β· subst a' simp only [lookupAll_cons_eq, mem_cons, Sigma.mk.inj_iff, heq_eq_eq, true_and, not_or, false_iff, not_forall, not_and, not_not, reduceCtorEq] use b simp Β· simp [h, lookupAll_eq_nil] theorem head?_lookupAll (a : Ξ±) : βˆ€ l : List (Sigma Ξ²), head? (lookupAll a l) = dlookup a l | [] => by simp | ⟨a', b⟩ :: l => by by_cases h : a = a' Β· subst h; simp Β· rw [lookupAll_cons_ne, dlookup_cons_ne, head?_lookupAll a l] <;> assumption theorem mem_lookupAll {a : Ξ±} {b : Ξ² a} : βˆ€ {l : List (Sigma Ξ²)}, b ∈ lookupAll a l ↔ Sigma.mk a b ∈ l | [] => by simp | ⟨a', b'⟩ :: l => by by_cases h : a = a' Β· subst h simp [*, mem_lookupAll] Β· simp [*, mem_lookupAll] theorem lookupAll_sublist (a : Ξ±) : βˆ€ l : List (Sigma Ξ²), (lookupAll a l).map (Sigma.mk a) <+ l | [] => by simp | ⟨a', b'⟩ :: l => by by_cases h : a = a' Β· subst h simp only [lookupAll_cons_eq, List.map] exact (lookupAll_sublist a l).consβ‚‚ _ Β· simp only [ne_eq, h, not_false_iff, lookupAll_cons_ne] exact (lookupAll_sublist a l).cons _ theorem lookupAll_length_le_one (a : Ξ±) {l : List (Sigma Ξ²)} (h : l.NodupKeys) : length (lookupAll a l) ≀ 1 := by have := Nodup.sublist ((lookupAll_sublist a l).map _) h rw [map_map] at this rwa [← nodup_replicate, ← map_const] theorem lookupAll_eq_dlookup (a : Ξ±) {l : List (Sigma Ξ²)} (h : l.NodupKeys) : lookupAll a l = (dlookup a l).toList := by rw [← head?_lookupAll] have h1 := lookupAll_length_le_one a h; revert h1 rcases lookupAll a l with (_ | ⟨b, _ | ⟨c, l⟩⟩) <;> intro h1 <;> try rfl exact absurd h1 (by simp) theorem lookupAll_nodup (a : Ξ±) {l : List (Sigma Ξ²)} (h : l.NodupKeys) : (lookupAll a l).Nodup := by (rw [lookupAll_eq_dlookup a h]; apply Option.toList_nodup) theorem perm_lookupAll (a : Ξ±) {l₁ lβ‚‚ : List (Sigma Ξ²)} (nd₁ : l₁.NodupKeys) (p : l₁ ~ lβ‚‚) : lookupAll a l₁ = lookupAll a lβ‚‚ := by have ndβ‚‚ := (perm_nodupKeys p).mp nd₁ simp [lookupAll_eq_dlookup, nd₁, ndβ‚‚, perm_dlookup a nd₁ p] /-! ### `kreplace` -/ /-- Replaces the first value with key `a` by `b`. -/ def kreplace (a : Ξ±) (b : Ξ² a) : List (Sigma Ξ²) β†’ List (Sigma Ξ²) := lookmap fun s => if a = s.1 then some ⟨a, b⟩ else none theorem kreplace_of_forall_not (a : Ξ±) (b : Ξ² a) {l : List (Sigma Ξ²)} (H : βˆ€ b : Ξ² a, Sigma.mk a b βˆ‰ l) : kreplace a b l = l := lookmap_of_forall_not _ <| by grind theorem kreplace_self {a : Ξ±} {b : Ξ² a} {l : List (Sigma Ξ²)} (nd : NodupKeys l) (h : Sigma.mk a b ∈ l) : kreplace a b l = l := by refine (lookmap_congr ?_).trans (lookmap_id' (Option.guard fun (s : Sigma Ξ²) => a = s.1) ?_ _) Β· rintro ⟨a', b'⟩ h' dsimp [Option.guard] split_ifs Β· subst a' simp [nd.eq_of_mk_mem h h'] Β· simp_all Β· simp_all Β· rfl Β· simp theorem keys_kreplace (a : Ξ±) (b : Ξ² a) : βˆ€ l : List (Sigma Ξ²), (kreplace a b l).keys = l.keys := lookmap_map_eq _ _ <| by rintro ⟨a₁, bβ‚‚βŸ© ⟨aβ‚‚, bβ‚‚βŸ© dsimp split_ifs with h <;> simp +contextual [h] theorem kreplace_nodupKeys (a : Ξ±) (b : Ξ² a) {l : List (Sigma Ξ²)} : (kreplace a b l).NodupKeys ↔ l.NodupKeys := by simp [NodupKeys, keys_kreplace] theorem Perm.kreplace {a : Ξ±} {b : Ξ² a} {l₁ lβ‚‚ : List (Sigma Ξ²)} (nd : l₁.NodupKeys) : l₁ ~ lβ‚‚ β†’ kreplace a b l₁ ~ kreplace a b lβ‚‚ := perm_lookmap _ <| by refine nd.pairwise_ne.imp ?_ intro x y h z h₁ w hβ‚‚ split_ifs at h₁ hβ‚‚ with h_2 h_1 <;> cases h₁ <;> cases hβ‚‚ exact (h (h_2.symm.trans h_1)).elim /-! ### `kerase` -/ /-- Remove the first pair with the key `a`. -/ def kerase (a : Ξ±) : List (Sigma Ξ²) β†’ List (Sigma Ξ²) := eraseP fun s => a = s.1 @[simp] theorem kerase_nil {a} : @kerase _ Ξ² _ a [] = [] := rfl @[simp] theorem kerase_cons_eq {a} {s : Sigma Ξ²} {l : List (Sigma Ξ²)} (h : a = s.1) : kerase a (s :: l) = l := by simp [kerase, h] @[simp] theorem kerase_cons_ne {a} {s : Sigma Ξ²} {l : List (Sigma Ξ²)} (h : a β‰  s.1) : kerase a (s :: l) = s :: kerase a l := by simp [kerase, h] @[simp] theorem kerase_of_notMem_keys {a} {l : List (Sigma Ξ²)} (h : a βˆ‰ l.keys) : kerase a l = l := by induction l with | nil => rfl | cons _ _ ih => simp [not_or] at h; simp [h.1, ih h.2] @[deprecated (since := "2025-05-23")] alias kerase_of_not_mem_keys := kerase_of_notMem_keys theorem kerase_sublist (a : Ξ±) (l : List (Sigma Ξ²)) : kerase a l <+ l := eraseP_sublist theorem kerase_keys_subset (a) (l : List (Sigma Ξ²)) : (kerase a l).keys βŠ† l.keys := ((kerase_sublist a l).map _).subset theorem mem_keys_of_mem_keys_kerase {a₁ aβ‚‚} {l : List (Sigma Ξ²)} : a₁ ∈ (kerase aβ‚‚ l).keys β†’ a₁ ∈ l.keys := @kerase_keys_subset _ _ _ _ _ _ theorem exists_of_kerase {a : Ξ±} {l : List (Sigma Ξ²)} (h : a ∈ l.keys) : βˆƒ (b : Ξ² a) (l₁ lβ‚‚ : List (Sigma Ξ²)), a βˆ‰ l₁.keys ∧ l = l₁ ++ ⟨a, b⟩ :: lβ‚‚ ∧ kerase a l = l₁ ++ lβ‚‚ := by induction l with | nil => cases h | cons hd tl ih => by_cases e : a = hd.1 Β· subst e exact ⟨hd.2, [], tl, by simp, by cases hd; rfl, by simp⟩ Β· simp only [keys_cons, mem_cons] at h rcases h with h | h Β· exact absurd h e rcases ih h with ⟨b, tl₁, tlβ‚‚, h₁, hβ‚‚, hβ‚ƒβŸ© exact ⟨b, hd :: tl₁, tlβ‚‚, not_mem_cons_of_ne_of_not_mem e h₁, by (rw [hβ‚‚]; rfl), by simp [e, h₃]⟩ @[simp] theorem mem_keys_kerase_of_ne {a₁ aβ‚‚} {l : List (Sigma Ξ²)} (h : a₁ β‰  aβ‚‚) : a₁ ∈ (kerase aβ‚‚ l).keys ↔ a₁ ∈ l.keys := (Iff.intro mem_keys_of_mem_keys_kerase) fun p => if q : aβ‚‚ ∈ l.keys then match l, kerase aβ‚‚ l, exists_of_kerase q, p with | _, _, ⟨_, _, _, _, rfl, rfl⟩, p => by simpa [keys, h] using p else by simp [q, p] theorem keys_kerase {a} {l : List (Sigma Ξ²)} : (kerase a l).keys = l.keys.erase a := by rw [keys, kerase, erase_eq_eraseP, eraseP_map, Function.comp_def] congr theorem kerase_kerase {a a'} {l : List (Sigma Ξ²)} : (kerase a' l).kerase a = (kerase a l).kerase a' := by by_cases h : a = a' Β· subst a'; rfl induction l with | nil => rfl | cons x xs => by_cases a' = x.1 Β· subst a' simp [kerase_cons_ne h, kerase_cons_eq rfl] by_cases h' : a = x.1 Β· subst a simp [kerase_cons_eq rfl, kerase_cons_ne (Ne.symm h)] Β· simp [kerase_cons_ne, *] theorem NodupKeys.kerase (a : Ξ±) : NodupKeys l β†’ (kerase a l).NodupKeys := NodupKeys.sublist <| kerase_sublist _ _ theorem Perm.kerase {a : Ξ±} {l₁ lβ‚‚ : List (Sigma Ξ²)} (nd : l₁.NodupKeys) : l₁ ~ lβ‚‚ β†’ kerase a l₁ ~ kerase a lβ‚‚ := by apply Perm.eraseP apply (nodupKeys_iff_pairwise.1 nd).imp intros; simp_all @[simp] theorem notMem_keys_kerase (a) {l : List (Sigma Ξ²)} (nd : l.NodupKeys) : a βˆ‰ (kerase a l).keys := by induction l with | nil => simp | cons hd tl ih => simp only [nodupKeys_cons] at nd by_cases h : a = hd.1 Β· subst h simp [nd.1] Β· simp [h, ih nd.2] @[deprecated (since := "2025-05-23")] alias not_mem_keys_kerase := notMem_keys_kerase @[simp] theorem dlookup_kerase (a) {l : List (Sigma Ξ²)} (nd : l.NodupKeys) : dlookup a (kerase a l) = none := dlookup_eq_none.mpr (notMem_keys_kerase a nd) @[simp] theorem dlookup_kerase_ne {a a'} {l : List (Sigma Ξ²)} (h : a β‰  a') : dlookup a (kerase a' l) = dlookup a l := by induction l with | nil => rfl | cons hd tl ih => obtain ⟨ah, bh⟩ := hd by_cases h₁ : a = ah <;> by_cases hβ‚‚ : a' = ah Β· substs h₁ hβ‚‚ cases Ne.irrefl h Β· subst h₁ simp [hβ‚‚] Β· subst hβ‚‚ simp [h] Β· simp [h₁, hβ‚‚, ih] theorem kerase_append_left {a} : βˆ€ {l₁ lβ‚‚ : List (Sigma Ξ²)}, a ∈ l₁.keys β†’ kerase a (l₁ ++ lβ‚‚) = kerase a l₁ ++ lβ‚‚ | [], _, h => by cases h | s :: l₁, lβ‚‚, h₁ => by if hβ‚‚ : a = s.1 then simp [hβ‚‚] else simp_all [kerase_append_left] theorem kerase_append_right {a} : βˆ€ {l₁ lβ‚‚ : List (Sigma Ξ²)}, a βˆ‰ l₁.keys β†’ kerase a (l₁ ++ lβ‚‚) = l₁ ++ kerase a lβ‚‚ | [], _, _ => rfl | _ :: l₁, lβ‚‚, h => by simp only [keys_cons, mem_cons, not_or] at h simp [h.1, kerase_append_right h.2] theorem kerase_comm (a₁ aβ‚‚) (l : List (Sigma Ξ²)) : kerase aβ‚‚ (kerase a₁ l) = kerase a₁ (kerase aβ‚‚ l) := if h : a₁ = aβ‚‚ then by simp [h] else if ha₁ : a₁ ∈ l.keys then if haβ‚‚ : aβ‚‚ ∈ l.keys then match l, kerase a₁ l, exists_of_kerase ha₁, haβ‚‚ with | _, _, ⟨b₁, l₁, lβ‚‚, a₁_nin_l₁, rfl, rfl⟩, _ => if h' : aβ‚‚ ∈ l₁.keys then by simp [kerase_append_left h', kerase_append_right (mt (mem_keys_kerase_of_ne h).mp a₁_nin_l₁)] else by simp [kerase_append_right h', kerase_append_right a₁_nin_l₁, @kerase_cons_ne _ _ _ aβ‚‚ ⟨a₁, bβ‚βŸ© _ (Ne.symm h)] else by simp [haβ‚‚, mt mem_keys_of_mem_keys_kerase haβ‚‚] else by simp [ha₁, mt mem_keys_of_mem_keys_kerase ha₁] theorem sizeOf_kerase [SizeOf (Sigma Ξ²)] (x : Ξ±) (xs : List (Sigma Ξ²)) : SizeOf.sizeOf (List.kerase x xs) ≀ SizeOf.sizeOf xs := by simp only [SizeOf.sizeOf, _sizeOf_1] induction xs with | nil => simp | cons y ys => by_cases x = y.1 <;> simp [*] /-! ### `kinsert` -/ /-- Insert the pair `⟨a, b⟩` and erase the first pair with the key `a`. -/ def kinsert (a : Ξ±) (b : Ξ² a) (l : List (Sigma Ξ²)) : List (Sigma Ξ²) := ⟨a, b⟩ :: kerase a l @[simp] theorem kinsert_def {a} {b : Ξ² a} {l : List (Sigma Ξ²)} : kinsert a b l = ⟨a, b⟩ :: kerase a l := rfl theorem mem_keys_kinsert {a a'} {b' : Ξ² a'} {l : List (Sigma Ξ²)} : a ∈ (kinsert a' b' l).keys ↔ a = a' ∨ a ∈ l.keys := by by_cases h : a = a' <;> simp [h] theorem kinsert_nodupKeys (a) (b : Ξ² a) {l : List (Sigma Ξ²)} (nd : l.NodupKeys) : (kinsert a b l).NodupKeys := nodupKeys_cons.mpr ⟨notMem_keys_kerase a nd, nd.kerase a⟩ theorem Perm.kinsert {a} {b : Ξ² a} {l₁ lβ‚‚ : List (Sigma Ξ²)} (nd₁ : l₁.NodupKeys) (p : l₁ ~ lβ‚‚) : kinsert a b l₁ ~ kinsert a b lβ‚‚ := (p.kerase nd₁).cons _ theorem dlookup_kinsert {a} {b : Ξ² a} (l : List (Sigma Ξ²)) : dlookup a (kinsert a b l) = some b := by simp only [kinsert, dlookup_cons_eq] theorem dlookup_kinsert_ne {a a'} {b' : Ξ² a'} {l : List (Sigma Ξ²)} (h : a β‰  a') : dlookup a (kinsert a' b' l) = dlookup a l := by simp [h] /-! ### `kextract` -/ /-- Finds the first entry with a given key `a` and returns its value (as an `Option` because there might be no entry with key `a`) alongside with the rest of the entries. -/ def kextract (a : Ξ±) : List (Sigma Ξ²) β†’ Option (Ξ² a) Γ— List (Sigma Ξ²) | [] => (none, []) | s :: l => if h : s.1 = a then (some (Eq.recOn h s.2), l) else let (b', l') := kextract a l (b', s :: l') @[simp] theorem kextract_eq_dlookup_kerase (a : Ξ±) : βˆ€ l : List (Sigma Ξ²), kextract a l = (dlookup a l, kerase a l) | [] => rfl | ⟨a', b⟩ :: l => by simp only [kextract]; split_ifs with h Β· subst a' simp [kerase] Β· simp [Ne.symm h, kextract_eq_dlookup_kerase a l, kerase] /-! ### `dedupKeys` -/ /-- Remove entries with duplicate keys from `l : List (Sigma Ξ²)`. -/ def dedupKeys : List (Sigma Ξ²) β†’ List (Sigma Ξ²) := List.foldr (fun x => kinsert x.1 x.2) [] theorem dedupKeys_cons {x : Sigma Ξ²} (l : List (Sigma Ξ²)) : dedupKeys (x :: l) = kinsert x.1 x.2 (dedupKeys l) := rfl theorem nodupKeys_dedupKeys (l : List (Sigma Ξ²)) : NodupKeys (dedupKeys l) := by dsimp [dedupKeys] generalize hl : nil = l' have : NodupKeys l' := by rw [← hl] apply nodup_nil clear hl induction l with | nil => apply this | cons x xs l_ih => cases x simp only [foldr_cons, kinsert_def, nodupKeys_cons] constructor Β· simp only [keys_kerase] apply l_ih.not_mem_erase Β· exact l_ih.kerase _ theorem dlookup_dedupKeys (a : Ξ±) (l : List (Sigma Ξ²)) : dlookup a (dedupKeys l) = dlookup a l := by induction l with | nil => rfl | cons l_hd _ l_ih => obtain ⟨a', b⟩ := l_hd by_cases h : a = a' Β· subst a' rw [dedupKeys_cons, dlookup_kinsert, dlookup_cons_eq] Β· rw [dedupKeys_cons, dlookup_kinsert_ne h, l_ih, dlookup_cons_ne] exact h theorem sizeOf_dedupKeys [SizeOf (Sigma Ξ²)] (xs : List (Sigma Ξ²)) : SizeOf.sizeOf (dedupKeys xs) ≀ SizeOf.sizeOf xs := by simp only [SizeOf.sizeOf, _sizeOf_1] induction xs with | nil => simp [dedupKeys] | cons x xs => simp only [dedupKeys_cons, kinsert_def, Nat.add_le_add_iff_left, Sigma.eta] trans Β· apply sizeOf_kerase Β· assumption /-! ### `kunion` -/ /-- `kunion l₁ lβ‚‚` is the append to l₁ of lβ‚‚ after, for each key in l₁, the first matching pair in lβ‚‚ is erased. -/ def kunion : List (Sigma Ξ²) β†’ List (Sigma Ξ²) β†’ List (Sigma Ξ²) | [], lβ‚‚ => lβ‚‚ | s :: l₁, lβ‚‚ => s :: kunion l₁ (kerase s.1 lβ‚‚) @[simp] theorem nil_kunion {l : List (Sigma Ξ²)} : kunion [] l = l := rfl @[simp] theorem kunion_nil : βˆ€ {l : List (Sigma Ξ²)}, kunion l [] = l | [] => rfl | _ :: l => by rw [kunion, kerase_nil, kunion_nil] @[simp] theorem kunion_cons {s} {l₁ lβ‚‚ : List (Sigma Ξ²)} : kunion (s :: l₁) lβ‚‚ = s :: kunion l₁ (kerase s.1 lβ‚‚) := rfl @[simp] theorem mem_keys_kunion {a} {l₁ lβ‚‚ : List (Sigma Ξ²)} : a ∈ (kunion l₁ lβ‚‚).keys ↔ a ∈ l₁.keys ∨ a ∈ lβ‚‚.keys := by induction l₁ generalizing lβ‚‚ with | nil => simp | cons s l₁ ih => by_cases h : a = s.1 <;> [simp [h]; simp [h, ih]] @[simp] theorem kunion_kerase {a} : βˆ€ {l₁ lβ‚‚ : List (Sigma Ξ²)}, kunion (kerase a l₁) (kerase a lβ‚‚) = kerase a (kunion l₁ lβ‚‚) | [], _ => rfl | s :: _, l => by by_cases h : a = s.1 <;> simp [h, kerase_comm a s.1 l, kunion_kerase] theorem NodupKeys.kunion (nd₁ : l₁.NodupKeys) (ndβ‚‚ : lβ‚‚.NodupKeys) : (kunion l₁ lβ‚‚).NodupKeys := by induction l₁ generalizing lβ‚‚ with | nil => simp only [nil_kunion, ndβ‚‚] | cons s l₁ ih => simp only [nodupKeys_cons] at nd₁ simp [nd₁.1, ndβ‚‚, ih nd₁.2 (ndβ‚‚.kerase s.1)] theorem Perm.kunion_right {l₁ lβ‚‚ : List (Sigma Ξ²)} (p : l₁ ~ lβ‚‚) (l) : kunion l₁ l ~ kunion lβ‚‚ l := by induction p generalizing l with | nil => rfl | cons hd _ ih => simp [ih (List.kerase _ _)] | swap s₁ sβ‚‚ l => simp [kerase_comm, Perm.swap] | trans _ _ ih₁₂ ih₂₃ => exact Perm.trans (ih₁₂ l) (ih₂₃ l) theorem Perm.kunion_left : βˆ€ (l) {l₁ lβ‚‚ : List (Sigma Ξ²)}, l₁.NodupKeys β†’ l₁ ~ lβ‚‚ β†’ kunion l l₁ ~ kunion l lβ‚‚ | [], _, _, _, p => p | s :: l, _, _, nd₁, p => ((p.kerase nd₁).kunion_left l <| nd₁.kerase s.1).cons s theorem Perm.kunion {l₁ lβ‚‚ l₃ lβ‚„ : List (Sigma Ξ²)} (nd₃ : l₃.NodupKeys) (p₁₂ : l₁ ~ lβ‚‚) (p₃₄ : l₃ ~ lβ‚„) : kunion l₁ l₃ ~ kunion lβ‚‚ lβ‚„ := (p₁₂.kunion_right l₃).trans (p₃₄.kunion_left lβ‚‚ nd₃) @[simp] theorem dlookup_kunion_left {a} {l₁ lβ‚‚ : List (Sigma Ξ²)} (h : a ∈ l₁.keys) : dlookup a (kunion l₁ lβ‚‚) = dlookup a l₁ := by induction l₁ generalizing lβ‚‚ with | nil => simp at h | cons s _ ih => simp only [keys_cons, mem_cons] at h rcases h with rfl | h <;> obtain ⟨a'⟩ := s Β· simp Β· rw [kunion_cons] by_cases h' : a = a' Β· subst h' simp Β· simp [h', ih h] @[simp] theorem dlookup_kunion_right {a} {l₁ lβ‚‚ : List (Sigma Ξ²)} (h : a βˆ‰ l₁.keys) : dlookup a (kunion l₁ lβ‚‚) = dlookup a lβ‚‚ := by induction l₁ generalizing lβ‚‚ with | nil => simp | cons _ _ ih => simp_all [not_or] theorem mem_dlookup_kunion {a} {b : Ξ² a} {l₁ lβ‚‚ : List (Sigma Ξ²)} : b ∈ dlookup a (kunion l₁ lβ‚‚) ↔ b ∈ dlookup a l₁ ∨ a βˆ‰ l₁.keys ∧ b ∈ dlookup a lβ‚‚ := by induction l₁ generalizing lβ‚‚ with | nil => simp | cons s _ ih => obtain ⟨a'⟩ := s by_cases h₁ : a = a' Β· subst h₁ simp Β· simp [h₁, @ih (kerase a' lβ‚‚)] @[simp] theorem dlookup_kunion_eq_some {a} {b : Ξ² a} {l₁ lβ‚‚ : List (Sigma Ξ²)} : dlookup a (kunion l₁ lβ‚‚) = some b ↔ dlookup a l₁ = some b ∨ a βˆ‰ l₁.keys ∧ dlookup a lβ‚‚ = some b := mem_dlookup_kunion theorem mem_dlookup_kunion_middle {a} {b : Ξ² a} {l₁ lβ‚‚ l₃ : List (Sigma Ξ²)} (h₁ : b ∈ dlookup a (kunion l₁ l₃)) (hβ‚‚ : a βˆ‰ keys lβ‚‚) : b ∈ dlookup a (kunion (kunion l₁ lβ‚‚) l₃) := match mem_dlookup_kunion.mp h₁ with | Or.inl h => mem_dlookup_kunion.mpr (Or.inl (mem_dlookup_kunion.mpr (Or.inl h))) | Or.inr h => mem_dlookup_kunion.mpr <| Or.inr ⟨mt mem_keys_kunion.mp (not_or.mpr ⟨h.1, hβ‚‚βŸ©), h.2⟩ end List
.lake/packages/mathlib/Mathlib/Data/List/Dedup.lean
import Mathlib.Data.List.Nodup import Mathlib.Data.List.Lattice import Batteries.Data.List.Pairwise /-! # Erasure of duplicates in a list This file proves basic results about `List.dedup` (definition in `Data.List.Defs`). `dedup l` returns `l` without its duplicates. It keeps the earliest (that is, rightmost) occurrence of each. ## Tags duplicate, multiplicity, nodup, `nub` -/ universe u namespace List variable {Ξ± Ξ² : Type*} [DecidableEq Ξ±] @[simp] theorem dedup_nil : dedup [] = ([] : List Ξ±) := rfl theorem dedup_cons_of_mem' {a : Ξ±} {l : List Ξ±} (h : a ∈ dedup l) : dedup (a :: l) = dedup l := pwFilter_cons_of_neg <| by simpa only [forall_mem_ne, not_not] using h theorem dedup_cons_of_notMem' {a : Ξ±} {l : List Ξ±} (h : a βˆ‰ dedup l) : dedup (a :: l) = a :: dedup l := pwFilter_cons_of_pos <| by simpa only [forall_mem_ne] using h theorem dedup_cons' (a : Ξ±) (l : List Ξ±) : dedup (a :: l) = if a ∈ dedup l then dedup l else a :: dedup l := by split <;> simp [dedup_cons_of_mem', dedup_cons_of_notMem', *] @[deprecated (since := "2025-05-23")] alias dedup_cons_of_not_mem' := dedup_cons_of_notMem' @[simp] theorem mem_dedup {a : Ξ±} {l : List Ξ±} : a ∈ dedup l ↔ a ∈ l := by have := not_congr (@forall_mem_pwFilter Ξ± (Β· β‰  Β·) _ ?_ a l) Β· simpa only [dedup, forall_mem_ne, not_not] using this Β· intro x y z xz exact not_and_or.1 <| mt (fun h ↦ h.1.trans h.2) xz @[simp] theorem dedup_cons_of_mem {a : Ξ±} {l : List Ξ±} (h : a ∈ l) : dedup (a :: l) = dedup l := dedup_cons_of_mem' <| mem_dedup.2 h @[simp] theorem dedup_cons_of_notMem {a : Ξ±} {l : List Ξ±} (h : a βˆ‰ l) : dedup (a :: l) = a :: dedup l := dedup_cons_of_notMem' <| mt mem_dedup.1 h @[deprecated (since := "2025-05-23")] alias dedup_cons_of_not_mem := dedup_cons_of_notMem theorem dedup_cons (a : Ξ±) (l : List Ξ±) : dedup (a :: l) = if a ∈ l then dedup l else a :: dedup l := by simpa using dedup_cons' a l theorem dedup_sublist : βˆ€ l : List Ξ±, dedup l <+ l := pwFilter_sublist theorem dedup_subset : βˆ€ l : List Ξ±, dedup l βŠ† l := pwFilter_subset theorem subset_dedup (l : List Ξ±) : l βŠ† dedup l := fun _ => mem_dedup.2 theorem nodup_dedup : βˆ€ l : List Ξ±, Nodup (dedup l) := pairwise_pwFilter theorem headI_dedup [Inhabited Ξ±] (l : List Ξ±) : l.dedup.headI = if l.headI ∈ l.tail then l.tail.dedup.headI else l.headI := match l with | [] => rfl | a :: l => by by_cases ha : a ∈ l <;> simp [ha, List.dedup_cons_of_mem] theorem tail_dedup [Inhabited Ξ±] (l : List Ξ±) : l.dedup.tail = if l.headI ∈ l.tail then l.tail.dedup.tail else l.tail.dedup := match l with | [] => rfl | a :: l => by by_cases ha : a ∈ l <;> simp [ha, List.dedup_cons_of_mem] theorem dedup_eq_self {l : List Ξ±} : dedup l = l ↔ Nodup l := pwFilter_eq_self theorem dedup_eq_cons (l : List Ξ±) (a : Ξ±) (l' : List Ξ±) : l.dedup = a :: l' ↔ a ∈ l ∧ a βˆ‰ l' ∧ l.dedup.tail = l' := by refine ⟨fun h => ?_, fun h => ?_⟩ Β· refine ⟨mem_dedup.1 (h.symm β–Έ mem_cons_self), fun ha => ?_, by rw [h, tail_cons]⟩ have := count_pos_iff.2 ha have : count a l.dedup ≀ 1 := nodup_iff_count_le_one.1 (nodup_dedup l) a rw [h, count_cons_self] at this cutsat Β· have := @List.cons_head!_tail Ξ± ⟨a⟩ _ (ne_nil_of_mem (mem_dedup.2 h.1)) have hal : a ∈ l.dedup := mem_dedup.2 h.1 rw [← this, mem_cons, or_iff_not_imp_right] at hal exact this β–Έ h.2.2.symm β–Έ cons_eq_cons.2 ⟨(hal (h.2.2.symm β–Έ h.2.1)).symm, rfl⟩ @[simp] theorem dedup_eq_nil (l : List Ξ±) : l.dedup = [] ↔ l = [] := by induction l with | nil => exact Iff.rfl | cons a l hl => by_cases h : a ∈ l Β· simp only [List.dedup_cons_of_mem h, hl, List.ne_nil_of_mem h, reduceCtorEq] Β· simp only [List.dedup_cons_of_notMem h, List.cons_ne_nil] protected theorem Nodup.dedup {l : List Ξ±} (h : l.Nodup) : l.dedup = l := List.dedup_eq_self.2 h @[simp] theorem dedup_idem {l : List Ξ±} : dedup (dedup l) = dedup l := pwFilter_idem theorem dedup_append (l₁ lβ‚‚ : List Ξ±) : dedup (l₁ ++ lβ‚‚) = l₁ βˆͺ dedup lβ‚‚ := by induction l₁ with | nil => rfl | cons a l₁ IH => ?_ simp only [cons_union] at * rw [← IH, cons_append] by_cases h : a ∈ dedup (l₁ ++ lβ‚‚) Β· rw [dedup_cons_of_mem' h, insert_of_mem h] Β· rw [dedup_cons_of_notMem' h, insert_of_not_mem h] theorem dedup_map_of_injective [DecidableEq Ξ²] {f : Ξ± β†’ Ξ²} (hf : Function.Injective f) (xs : List Ξ±) : (xs.map f).dedup = xs.dedup.map f := by induction xs with | nil => simp | cons x xs ih => rw [map_cons] by_cases h : x ∈ xs Β· rw [dedup_cons_of_mem h, dedup_cons_of_mem (mem_map_of_mem h), ih] Β· rw [dedup_cons_of_notMem h, dedup_cons_of_notMem <| (mem_map_of_injective hf).not.mpr h, ih, map_cons] /-- Note that the weaker `List.Subset.dedup_append_left` is proved later. -/ theorem Subset.dedup_append_right {xs ys : List Ξ±} (h : xs βŠ† ys) : dedup (xs ++ ys) = dedup ys := by rw [List.dedup_append, Subset.union_eq_right (List.Subset.trans h <| subset_dedup _)] theorem Disjoint.union_eq {xs ys : List Ξ±} (h : Disjoint xs ys) : xs βˆͺ ys = xs.dedup ++ ys := by induction xs with | nil => simp | cons x xs ih => rw [cons_union] rw [disjoint_cons_left] at h by_cases hx : x ∈ xs Β· rw [dedup_cons_of_mem hx, insert_of_mem (mem_union_left hx _), ih h.2] Β· rw [dedup_cons_of_notMem hx, insert_of_not_mem, ih h.2, cons_append] rw [mem_union_iff, not_or] exact ⟨hx, h.1⟩ theorem Disjoint.dedup_append {xs ys : List Ξ±} (h : Disjoint xs ys) : dedup (xs ++ ys) = dedup xs ++ dedup ys := by rw [List.dedup_append, Disjoint.union_eq] intro a hx hy exact h hx (mem_dedup.mp hy) theorem replicate_dedup {x : Ξ±} : βˆ€ {k}, k β‰  0 β†’ (replicate k x).dedup = [x] | 0, h => (h rfl).elim | 1, _ => rfl | n + 2, _ => by rw [replicate_succ, dedup_cons_of_mem (mem_replicate.2 ⟨n.succ_ne_zero, rfl⟩), replicate_dedup n.succ_ne_zero] theorem count_dedup (l : List Ξ±) (a : Ξ±) : l.dedup.count a = if a ∈ l then 1 else 0 := by simp_rw [List.Nodup.count <| nodup_dedup l, mem_dedup] theorem Perm.dedup {l₁ lβ‚‚ : List Ξ±} (p : l₁ ~ lβ‚‚) : dedup l₁ ~ dedup lβ‚‚ := perm_iff_count.2 fun a => if h : a ∈ l₁ then by simp [h, nodup_dedup, p.subset h] else by simp [h, count_eq_zero_of_not_mem, mt p.mem_iff.2] end List
.lake/packages/mathlib/Mathlib/Data/List/FinRange.lean
import Mathlib.Data.List.OfFn import Batteries.Data.List.Perm import Mathlib.Data.List.Nodup /-! # Lists of elements of `Fin n` This file develops some results on `finRange n`. -/ assert_not_exists Monoid universe u namespace List variable {Ξ± : Type u} theorem finRange_eq_pmap_range (n : β„•) : finRange n = (range n).pmap Fin.mk (by simp) := by apply List.ext_getElem <;> simp [finRange] @[simp] theorem mem_finRange {n : β„•} (a : Fin n) : a ∈ finRange n := by rw [finRange_eq_pmap_range] exact mem_pmap.2 ⟨a.1, mem_range.2 a.2, by cases a rfl⟩ theorem nodup_finRange (n : β„•) : (finRange n).Nodup := by rw [finRange_eq_pmap_range] exact (Pairwise.pmap nodup_range _) fun _ _ _ _ => @Fin.ne_of_val_ne _ ⟨_, _⟩ ⟨_, _⟩ @[simp] theorem finRange_eq_nil {n : β„•} : finRange n = [] ↔ n = 0 := by rw [← length_eq_zero_iff, length_finRange] theorem pairwise_lt_finRange (n : β„•) : Pairwise (Β· < Β·) (finRange n) := by rw [finRange_eq_pmap_range] exact List.pairwise_lt_range.pmap (by simp) (by simp) theorem pairwise_le_finRange (n : β„•) : Pairwise (Β· ≀ Β·) (finRange n) := by rw [finRange_eq_pmap_range] exact List.pairwise_le_range.pmap (by simp) (by simp) @[simp] lemma count_finRange {n : β„•} (a : Fin n) : count a (finRange n) = 1 := by simp [List.Nodup.count (nodup_finRange n)] theorem get_finRange {n : β„•} {i : β„•} (h) : (finRange n).get ⟨i, h⟩ = ⟨i, length_finRange (n := n) β–Έ h⟩ := by simp @[simp] theorem finRange_map_get (l : List Ξ±) : (finRange l.length).map l.get = l := List.ext_get (by simp) (by simp) @[simp] theorem finRange_map_getElem (l : List Ξ±) : (finRange l.length).map (l[Β·.1]) = l := finRange_map_get l @[simp] theorem idxOf_finRange {k : β„•} (i : Fin k) : (finRange k).idxOf i = i := by simpa using idxOf_getElem (nodup_finRange k) i @[simp] theorem map_coe_finRange (n : β„•) : ((finRange n) : List (Fin n)).map (Fin.val) = List.range n := by apply List.ext_getElem <;> simp @[deprecated finRange_succ (since := "2025-10-10")] theorem finRange_succ_eq_map (n : β„•) : finRange n.succ = 0 :: (finRange n).map Fin.succ := finRange_succ theorem ofFn_eq_pmap {n} {f : Fin n β†’ Ξ±} : ofFn f = pmap (fun i hi => f ⟨i, hi⟩) (range n) fun _ => mem_range.1 := by ext grind theorem ofFn_id (n) : ofFn id = finRange n := rfl theorem ofFn_eq_map {n} {f : Fin n β†’ Ξ±} : ofFn f = (finRange n).map f := by rw [← ofFn_id, map_ofFn, Function.comp_id] theorem nodup_ofFn_ofInjective {n} {f : Fin n β†’ Ξ±} (hf : Function.Injective f) : Nodup (ofFn f) := by rw [ofFn_eq_pmap] exact nodup_range.pmap fun _ _ _ _ H => Fin.val_eq_of_eq <| hf H theorem nodup_ofFn {n} {f : Fin n β†’ Ξ±} : Nodup (ofFn f) ↔ Function.Injective f := by refine ⟨?_, nodup_ofFn_ofInjective⟩ refine Fin.consInduction ?_ (fun xβ‚€ xs ih => ?_) f Β· intro _ exact Function.injective_of_subsingleton _ Β· intro h rw [Fin.cons_injective_iff] simp_rw [ofFn_succ, Fin.cons_succ, nodup_cons, Fin.cons_zero, mem_ofFn] at h exact h.imp_right ih end List open List theorem Equiv.Perm.map_finRange_perm {n : β„•} (Οƒ : Equiv.Perm (Fin n)) : map Οƒ (finRange n) ~ finRange n := by rw [perm_ext_iff_of_nodup ((nodup_finRange n).map Οƒ.injective) <| nodup_finRange n] simpa [mem_map, mem_finRange] using Οƒ.surjective /-- The list obtained from a permutation of a tuple `f` is permutation equivalent to the list obtained from `f`. -/ theorem Equiv.Perm.ofFn_comp_perm {n : β„•} {Ξ± : Type u} (Οƒ : Equiv.Perm (Fin n)) (f : Fin n β†’ Ξ±) : ofFn (f ∘ Οƒ) ~ ofFn f := by rw [ofFn_eq_map, ofFn_eq_map, ← map_map] exact Οƒ.map_finRange_perm.map f
.lake/packages/mathlib/Mathlib/Data/List/Forall2.lean
import Mathlib.Data.List.Basic /-! # Double universal quantification on a list This file provides an API for `List.Forallβ‚‚` (definition in `Data.List.Defs`). `Forallβ‚‚ R l₁ lβ‚‚` means that `l₁` and `lβ‚‚` have the same length, and whenever `a` is the nth element of `l₁`, and `b` is the nth element of `lβ‚‚`, then `R a b` is satisfied. -/ open Nat Function namespace List variable {Ξ± Ξ² Ξ³ Ξ΄ : Type*} {R S : Ξ± β†’ Ξ² β†’ Prop} {P : Ξ³ β†’ Ξ΄ β†’ Prop} {Rₐ : Ξ± β†’ Ξ± β†’ Prop} open Relator mk_iff_of_inductive_prop List.Forallβ‚‚ List.forallβ‚‚_iff theorem Forallβ‚‚.imp (H : βˆ€ a b, R a b β†’ S a b) {l₁ lβ‚‚} (h : Forallβ‚‚ R l₁ lβ‚‚) : Forallβ‚‚ S l₁ lβ‚‚ := by induction h <;> constructor <;> solve_by_elim theorem Forallβ‚‚.mp {Q : Ξ± β†’ Ξ² β†’ Prop} (h : βˆ€ a b, Q a b β†’ R a b β†’ S a b) : βˆ€ {l₁ lβ‚‚}, Forallβ‚‚ Q l₁ lβ‚‚ β†’ Forallβ‚‚ R l₁ lβ‚‚ β†’ Forallβ‚‚ S l₁ lβ‚‚ | [], [], Forallβ‚‚.nil, Forallβ‚‚.nil => Forallβ‚‚.nil | a :: _, b :: _, Forallβ‚‚.cons hr hrs, Forallβ‚‚.cons hq hqs => Forallβ‚‚.cons (h a b hr hq) (Forallβ‚‚.mp h hrs hqs) theorem Forallβ‚‚.flip : βˆ€ {a b}, Forallβ‚‚ (flip R) b a β†’ Forallβ‚‚ R a b | _, _, Forallβ‚‚.nil => Forallβ‚‚.nil | _ :: _, _ :: _, Forallβ‚‚.cons h₁ hβ‚‚ => Forallβ‚‚.cons h₁ hβ‚‚.flip @[simp] theorem forallβ‚‚_same : βˆ€ {l : List Ξ±}, Forallβ‚‚ Rₐ l l ↔ βˆ€ x ∈ l, Rₐ x x | [] => by simp | a :: l => by simp [@forallβ‚‚_same l] theorem forallβ‚‚_refl [IsRefl Ξ± Rₐ] (l : List Ξ±) : Forallβ‚‚ Rₐ l l := forallβ‚‚_same.2 fun _ _ => refl _ @[simp] theorem forallβ‚‚_eq_eq_eq : Forallβ‚‚ ((Β· = Β·) : Ξ± β†’ Ξ± β†’ Prop) = Eq := by funext a b; apply propext constructor Β· intro h induction h Β· rfl simp only [*] Β· rintro rfl exact forallβ‚‚_refl _ @[simp] theorem forallβ‚‚_nil_left_iff {l} : Forallβ‚‚ R nil l ↔ l = nil := ⟨fun H => by cases H; rfl, by rintro rfl; exact Forallβ‚‚.nil⟩ @[simp] theorem forallβ‚‚_nil_right_iff {l} : Forallβ‚‚ R l nil ↔ l = nil := ⟨fun H => by cases H; rfl, by rintro rfl; exact Forallβ‚‚.nil⟩ theorem forallβ‚‚_cons_left_iff {a l u} : Forallβ‚‚ R (a :: l) u ↔ βˆƒ b u', R a b ∧ Forallβ‚‚ R l u' ∧ u = b :: u' := Iff.intro (fun h => match u, h with | b :: u', Forallβ‚‚.cons h₁ hβ‚‚ => ⟨b, u', h₁, hβ‚‚, rfl⟩) fun h => match u, h with | _, ⟨_, _, h₁, hβ‚‚, rfl⟩ => Forallβ‚‚.cons h₁ hβ‚‚ theorem forallβ‚‚_cons_right_iff {b l u} : Forallβ‚‚ R u (b :: l) ↔ βˆƒ a u', R a b ∧ Forallβ‚‚ R u' l ∧ u = a :: u' := Iff.intro (fun h => match u, h with | b :: u', Forallβ‚‚.cons h₁ hβ‚‚ => ⟨b, u', h₁, hβ‚‚, rfl⟩) fun h => match u, h with | _, ⟨_, _, h₁, hβ‚‚, rfl⟩ => Forallβ‚‚.cons h₁ hβ‚‚ theorem forallβ‚‚_and_left {p : Ξ± β†’ Prop} : βˆ€ l u, Forallβ‚‚ (fun a b => p a ∧ R a b) l u ↔ (βˆ€ a ∈ l, p a) ∧ Forallβ‚‚ R l u | [], u => by simp only [forallβ‚‚_nil_left_iff, forall_prop_of_false not_mem_nil, imp_true_iff, true_and] | a :: l, u => by simp only [forallβ‚‚_and_left l, forallβ‚‚_cons_left_iff, forall_mem_cons, and_assoc, exists_and_left] simp only [and_comm, and_assoc, ← exists_and_right] @[simp] theorem forallβ‚‚_map_left_iff {f : Ξ³ β†’ Ξ±} : βˆ€ {l u}, Forallβ‚‚ R (map f l) u ↔ Forallβ‚‚ (fun c b => R (f c) b) l u | [], _ => by simp only [map, forallβ‚‚_nil_left_iff] | a :: l, _ => by simp only [map, forallβ‚‚_cons_left_iff, forallβ‚‚_map_left_iff] @[simp] theorem forallβ‚‚_map_right_iff {f : Ξ³ β†’ Ξ²} : βˆ€ {l u}, Forallβ‚‚ R l (map f u) ↔ Forallβ‚‚ (fun a c => R a (f c)) l u | _, [] => by simp only [map, forallβ‚‚_nil_right_iff] | _, b :: u => by simp only [map, forallβ‚‚_cons_right_iff, forallβ‚‚_map_right_iff] theorem left_unique_forallβ‚‚' (hr : LeftUnique R) : βˆ€ {a b c}, Forallβ‚‚ R a c β†’ Forallβ‚‚ R b c β†’ a = b | _, _, _, Forallβ‚‚.nil, Forallβ‚‚.nil => rfl | _, _, _, Forallβ‚‚.cons haβ‚€ hβ‚€, Forallβ‚‚.cons ha₁ h₁ => hr haβ‚€ ha₁ β–Έ left_unique_forallβ‚‚' hr hβ‚€ h₁ β–Έ rfl theorem _root_.Relator.LeftUnique.forallβ‚‚ (hr : LeftUnique R) : LeftUnique (Forallβ‚‚ R) := @left_unique_forallβ‚‚' _ _ _ hr theorem right_unique_forallβ‚‚' (hr : RightUnique R) : βˆ€ {a b c}, Forallβ‚‚ R a b β†’ Forallβ‚‚ R a c β†’ b = c | _, _, _, Forallβ‚‚.nil, Forallβ‚‚.nil => rfl | _, _, _, Forallβ‚‚.cons haβ‚€ hβ‚€, Forallβ‚‚.cons ha₁ h₁ => hr haβ‚€ ha₁ β–Έ right_unique_forallβ‚‚' hr hβ‚€ h₁ β–Έ rfl theorem _root_.Relator.RightUnique.forallβ‚‚ (hr : RightUnique R) : RightUnique (Forallβ‚‚ R) := @right_unique_forallβ‚‚' _ _ _ hr theorem _root_.Relator.BiUnique.forallβ‚‚ (hr : BiUnique R) : BiUnique (Forallβ‚‚ R) := ⟨hr.left.forallβ‚‚, hr.right.forallβ‚‚βŸ© theorem Forallβ‚‚.length_eq : βˆ€ {l₁ lβ‚‚}, Forallβ‚‚ R l₁ lβ‚‚ β†’ length l₁ = length lβ‚‚ | _, _, Forallβ‚‚.nil => rfl | _, _, Forallβ‚‚.cons _ hβ‚‚ => congr_arg succ (Forallβ‚‚.length_eq hβ‚‚) theorem Forallβ‚‚.get : βˆ€ {x : List Ξ±} {y : List Ξ²}, Forallβ‚‚ R x y β†’ βˆ€ ⦃i : ℕ⦄ (hx : i < x.length) (hy : i < y.length), R (x.get ⟨i, hx⟩) (y.get ⟨i, hy⟩) | _, _, Forallβ‚‚.cons ha _, 0, _, _ => ha | _, _, Forallβ‚‚.cons _ hl, succ _, _, _ => hl.get _ _ theorem forallβ‚‚_of_length_eq_of_get : βˆ€ {x : List Ξ±} {y : List Ξ²}, x.length = y.length β†’ (βˆ€ i h₁ hβ‚‚, R (x.get ⟨i, hβ‚βŸ©) (y.get ⟨i, hβ‚‚βŸ©)) β†’ Forallβ‚‚ R x y | [], [], _, _ => Forallβ‚‚.nil | _ :: _, _ :: _, hl, h => Forallβ‚‚.cons (h 0 (Nat.zero_lt_succ _) (Nat.zero_lt_succ _)) (forallβ‚‚_of_length_eq_of_get (succ.inj hl) fun i h₁ hβ‚‚ => h i.succ (succ_lt_succ h₁) (succ_lt_succ hβ‚‚)) theorem forallβ‚‚_iff_get {l₁ : List Ξ±} {lβ‚‚ : List Ξ²} : Forallβ‚‚ R l₁ lβ‚‚ ↔ l₁.length = lβ‚‚.length ∧ βˆ€ i h₁ hβ‚‚, R (l₁.get ⟨i, hβ‚βŸ©) (lβ‚‚.get ⟨i, hβ‚‚βŸ©) := ⟨fun h => ⟨h.length_eq, h.get⟩, fun h => forallβ‚‚_of_length_eq_of_get h.1 h.2⟩ theorem forallβ‚‚_zip : βˆ€ {l₁ lβ‚‚}, Forallβ‚‚ R l₁ lβ‚‚ β†’ βˆ€ {a b}, (a, b) ∈ zip l₁ lβ‚‚ β†’ R a b | _, _, Forallβ‚‚.cons h₁ hβ‚‚, x, y, hx => by rw [zip, zipWith, mem_cons] at hx match hx with | Or.inl rfl => exact h₁ | Or.inr h₃ => exact forallβ‚‚_zip hβ‚‚ h₃ theorem forallβ‚‚_iff_zip {l₁ lβ‚‚} : Forallβ‚‚ R l₁ lβ‚‚ ↔ length l₁ = length lβ‚‚ ∧ βˆ€ {a b}, (a, b) ∈ zip l₁ lβ‚‚ β†’ R a b := ⟨fun h => ⟨Forallβ‚‚.length_eq h, @forallβ‚‚_zip _ _ _ _ _ h⟩, fun h => by obtain ⟨h₁, hβ‚‚βŸ© := h induction l₁ generalizing lβ‚‚ with | nil => cases length_eq_zero_iff.1 h₁.symm constructor | cons a l₁ IH => rcases lβ‚‚ with - | ⟨b, lβ‚‚βŸ© Β· simp at h₁ Β· simp only [length_cons, succ.injEq] at h₁ exact Forallβ‚‚.cons (hβ‚‚ <| by simp [zip]) (IH h₁ fun h => hβ‚‚ <| by simp only [zip, zipWith, mem_cons, Prod.mk.injEq]; right simpa [zip] using h)⟩ theorem forallβ‚‚_take : βˆ€ (n) {l₁ lβ‚‚}, Forallβ‚‚ R l₁ lβ‚‚ β†’ Forallβ‚‚ R (take n l₁) (take n lβ‚‚) | 0, _, _, _ => by simp only [Forallβ‚‚.nil, take] | _ + 1, _, _, Forallβ‚‚.nil => by simp only [Forallβ‚‚.nil, take] | n + 1, _, _, Forallβ‚‚.cons h₁ hβ‚‚ => by simp [And.intro h₁ hβ‚‚, forallβ‚‚_take n] theorem forallβ‚‚_drop : βˆ€ (n) {l₁ lβ‚‚}, Forallβ‚‚ R l₁ lβ‚‚ β†’ Forallβ‚‚ R (drop n l₁) (drop n lβ‚‚) | 0, _, _, h => by simp only [drop, h] | _ + 1, _, _, Forallβ‚‚.nil => by simp only [Forallβ‚‚.nil, drop] | n + 1, _, _, Forallβ‚‚.cons h₁ hβ‚‚ => by simp [And.intro h₁ hβ‚‚, forallβ‚‚_drop n] theorem forallβ‚‚_take_append (l : List Ξ±) (l₁ : List Ξ²) (lβ‚‚ : List Ξ²) (h : Forallβ‚‚ R l (l₁ ++ lβ‚‚)) : Forallβ‚‚ R (List.take (length l₁) l) l₁ := by have h' : Forallβ‚‚ R (take (length l₁) l) (take (length l₁) (l₁ ++ lβ‚‚)) := forallβ‚‚_take (length l₁) h rwa [take_left] at h' theorem forallβ‚‚_drop_append (l : List Ξ±) (l₁ : List Ξ²) (lβ‚‚ : List Ξ²) (h : Forallβ‚‚ R l (l₁ ++ lβ‚‚)) : Forallβ‚‚ R (List.drop (length l₁) l) lβ‚‚ := by have h' : Forallβ‚‚ R (drop (length l₁) l) (drop (length l₁) (l₁ ++ lβ‚‚)) := forallβ‚‚_drop (length l₁) h rwa [drop_left] at h' theorem rel_mem (hr : BiUnique R) : (R β‡’ Forallβ‚‚ R β‡’ Iff) (Β· ∈ Β·) (Β· ∈ Β·) | a, b, _, [], [], Forallβ‚‚.nil => by simp only [not_mem_nil] | a, b, h, a' :: as, b' :: bs, Forallβ‚‚.cons h₁ hβ‚‚ => by simp only [mem_cons] exact rel_or (rel_eq hr h h₁) (rel_mem hr h hβ‚‚) theorem rel_map : ((R β‡’ P) β‡’ Forallβ‚‚ R β‡’ Forallβ‚‚ P) map map | _, _, _, [], [], Forallβ‚‚.nil => Forallβ‚‚.nil | _, _, h, _ :: _, _ :: _, Forallβ‚‚.cons h₁ hβ‚‚ => Forallβ‚‚.cons (h h₁) (rel_map (@h) hβ‚‚) theorem rel_append : (Forallβ‚‚ R β‡’ Forallβ‚‚ R β‡’ Forallβ‚‚ R) (Β· ++ Β·) (Β· ++ Β·) | [], [], _, _, _, hl => hl | _, _, Forallβ‚‚.cons h₁ hβ‚‚, _, _, hl => Forallβ‚‚.cons h₁ (rel_append hβ‚‚ hl) theorem rel_reverse : (Forallβ‚‚ R β‡’ Forallβ‚‚ R) reverse reverse | [], [], Forallβ‚‚.nil => Forallβ‚‚.nil | _, _, Forallβ‚‚.cons h₁ hβ‚‚ => by simp only [reverse_cons] exact rel_append (rel_reverse hβ‚‚) (Forallβ‚‚.cons h₁ Forallβ‚‚.nil) @[simp] theorem forallβ‚‚_reverse_iff {l₁ lβ‚‚} : Forallβ‚‚ R (reverse l₁) (reverse lβ‚‚) ↔ Forallβ‚‚ R l₁ lβ‚‚ := Iff.intro (fun h => by rw [← reverse_reverse l₁, ← reverse_reverse lβ‚‚] exact rel_reverse h) fun h => rel_reverse h theorem rel_flatten : (Forallβ‚‚ (Forallβ‚‚ R) β‡’ Forallβ‚‚ R) flatten flatten | [], [], Forallβ‚‚.nil => Forallβ‚‚.nil | _, _, Forallβ‚‚.cons h₁ hβ‚‚ => rel_append h₁ (rel_flatten hβ‚‚) theorem rel_flatMap : (Forallβ‚‚ R β‡’ (R β‡’ Forallβ‚‚ P) β‡’ Forallβ‚‚ P) (Function.swap List.flatMap) (Function.swap List.flatMap) := fun _ _ h₁ _ _ hβ‚‚ => rel_flatten (rel_map (@hβ‚‚) h₁) theorem rel_foldl : ((P β‡’ R β‡’ P) β‡’ P β‡’ Forallβ‚‚ R β‡’ P) foldl foldl | _, _, _, _, _, h, _, _, Forallβ‚‚.nil => h | _, _, hfg, _, _, hxy, _, _, Forallβ‚‚.cons hab hs => rel_foldl (@hfg) (hfg hxy hab) hs theorem rel_foldr : ((R β‡’ P β‡’ P) β‡’ P β‡’ Forallβ‚‚ R β‡’ P) foldr foldr | _, _, _, _, _, h, _, _, Forallβ‚‚.nil => h | _, _, hfg, _, _, hxy, _, _, Forallβ‚‚.cons hab hs => hfg hab (rel_foldr (@hfg) hxy hs) theorem rel_filter {p : Ξ± β†’ Bool} {q : Ξ² β†’ Bool} (hpq : (R β‡’ (Β· ↔ Β·)) (fun x => p x) (fun x => q x)) : (Forallβ‚‚ R β‡’ Forallβ‚‚ R) (filter p) (filter q) | _, _, Forallβ‚‚.nil => Forallβ‚‚.nil | a :: as, b :: bs, Forallβ‚‚.cons h₁ hβ‚‚ => by dsimp [LiftFun] at hpq by_cases h : p a Β· have : q b := by rwa [← hpq h₁] simp only [filter_cons_of_pos h, filter_cons_of_pos this, forallβ‚‚_cons, h₁, true_and, rel_filter hpq hβ‚‚] Β· have : Β¬q b := by rwa [← hpq h₁] simp only [filter_cons_of_neg h, filter_cons_of_neg this, rel_filter hpq hβ‚‚] theorem rel_filterMap : ((R β‡’ Option.Rel P) β‡’ Forallβ‚‚ R β‡’ Forallβ‚‚ P) filterMap filterMap | _, _, _, _, _, Forallβ‚‚.nil => Forallβ‚‚.nil | f, g, hfg, a :: as, b :: bs, Forallβ‚‚.cons h₁ hβ‚‚ => by rw [filterMap_cons, filterMap_cons] exact match f a, g b, hfg h₁ with | _, _, Option.Rel.none => rel_filterMap (@hfg) hβ‚‚ | _, _, Option.Rel.some h => Forallβ‚‚.cons h (rel_filterMap (@hfg) hβ‚‚) /-- Given a relation `R`, `sublist_forallβ‚‚ r l₁ lβ‚‚` indicates that there is a sublist of `lβ‚‚` such that `forallβ‚‚ r l₁ lβ‚‚`. -/ inductive SublistForallβ‚‚ (R : Ξ± β†’ Ξ² β†’ Prop) : List Ξ± β†’ List Ξ² β†’ Prop | nil {l} : SublistForallβ‚‚ R [] l | cons {a₁ aβ‚‚ l₁ lβ‚‚} : R a₁ aβ‚‚ β†’ SublistForallβ‚‚ R l₁ lβ‚‚ β†’ SublistForallβ‚‚ R (a₁ :: l₁) (aβ‚‚ :: lβ‚‚) | cons_right {a l₁ lβ‚‚} : SublistForallβ‚‚ R l₁ lβ‚‚ β†’ SublistForallβ‚‚ R l₁ (a :: lβ‚‚) theorem sublistForallβ‚‚_iff {l₁ : List Ξ±} {lβ‚‚ : List Ξ²} : SublistForallβ‚‚ R l₁ lβ‚‚ ↔ βˆƒ l, Forallβ‚‚ R l₁ l ∧ l <+ lβ‚‚ := by constructor <;> intro h Β· induction h with | nil => exact ⟨nil, Forallβ‚‚.nil, nil_sublist _⟩ | @cons a b l1 l2 rab _ ih => obtain ⟨l, hl1, hl2⟩ := ih exact ⟨b :: l, Forallβ‚‚.cons rab hl1, hl2.cons_cons b⟩ | cons_right _ ih => obtain ⟨l, hl1, hl2⟩ := ih exact ⟨l, hl1, hl2.trans (Sublist.cons _ (Sublist.refl _))⟩ Β· obtain ⟨l, hl1, hl2⟩ := h revert l₁ induction hl2 with | slnil => intro l₁ hl1 rw [forallβ‚‚_nil_right_iff.1 hl1] exact SublistForallβ‚‚.nil | cons _ _ ih => intro l₁ hl1; exact SublistForallβ‚‚.cons_right (ih hl1) | consβ‚‚ _ _ ih => intro l₁ hl1 obtain - | ⟨hr, hl⟩ := hl1 exact SublistForallβ‚‚.cons hr (ih hl) instance SublistForallβ‚‚.is_refl [IsRefl Ξ± Rₐ] : IsRefl (List Ξ±) (SublistForallβ‚‚ Rₐ) := ⟨fun l => sublistForallβ‚‚_iff.2 ⟨l, forallβ‚‚_refl l, Sublist.refl l⟩⟩ instance SublistForallβ‚‚.is_trans [IsTrans Ξ± Rₐ] : IsTrans (List Ξ±) (SublistForallβ‚‚ Rₐ) := ⟨fun a b c => by revert a b induction c with | nil => rintro _ _ h1 h2 cases h2 exact h1 | cons _ _ ih => rintro a b h1 h2 obtain - | ⟨hbc, tbc⟩ | btc := h2 Β· cases h1 exact SublistForallβ‚‚.nil Β· obtain - | ⟨hab, tab⟩ | atb := h1 Β· exact SublistForallβ‚‚.nil Β· exact SublistForallβ‚‚.cons (_root_.trans hab hbc) (ih _ _ tab tbc) Β· exact SublistForallβ‚‚.cons_right (ih _ _ atb tbc) Β· exact SublistForallβ‚‚.cons_right (ih _ _ h1 btc)⟩ theorem Sublist.sublistForallβ‚‚ {l₁ lβ‚‚ : List Ξ±} (h : l₁ <+ lβ‚‚) [IsRefl Ξ± Rₐ] : SublistForallβ‚‚ Rₐ l₁ lβ‚‚ := sublistForallβ‚‚_iff.2 ⟨l₁, forallβ‚‚_refl l₁, h⟩ theorem tail_sublistForallβ‚‚_self [IsRefl Ξ± Rₐ] (l : List Ξ±) : SublistForallβ‚‚ Rₐ l.tail l := l.tail_sublist.sublistForallβ‚‚ @[simp] theorem sublistForallβ‚‚_map_left_iff {f : Ξ³ β†’ Ξ±} {l₁ : List Ξ³} {lβ‚‚ : List Ξ²} : SublistForallβ‚‚ R (map f l₁) lβ‚‚ ↔ SublistForallβ‚‚ (fun c b => R (f c) b) l₁ lβ‚‚ := by simp [sublistForallβ‚‚_iff] @[simp] theorem sublistForallβ‚‚_map_right_iff {f : Ξ³ β†’ Ξ²} {l₁ : List Ξ±} {lβ‚‚ : List Ξ³} : SublistForallβ‚‚ R l₁ (map f lβ‚‚) ↔ SublistForallβ‚‚ (fun a c => R a (f c)) l₁ lβ‚‚ := by simp only [sublistForallβ‚‚_iff] constructor Β· rintro ⟨l1, h1, h2⟩ obtain ⟨l', hl1, rfl⟩ := sublist_map_iff.mp h2 use l' simpa [hl1] using h1 Β· rintro ⟨l1, h1, h2⟩ use l1.map f simp [h1, h2.map] end List
.lake/packages/mathlib/Mathlib/Data/List/NodupEquivFin.lean
import Mathlib.Data.List.Duplicate import Mathlib.Data.List.Sort /-! # Equivalence between `Fin (length l)` and elements of a list Given a list `l`, * if `l` has no duplicates, then `List.Nodup.getEquiv` is the equivalence between `Fin (length l)` and `{x // x ∈ l}` sending `i` to `⟨get l i, _⟩` with the inverse sending `⟨x, hx⟩` to `⟨indexOf x l, _⟩`; * if `l` has no duplicates and contains every element of a type `Ξ±`, then `List.Nodup.getEquivOfForallMemList` defines an equivalence between `Fin (length l)` and `Ξ±`; if `Ξ±` does not have decidable equality, then there is a bijection `List.Nodup.getBijectionOfForallMemList`; * if `l` is sorted w.r.t. `(<)`, then `List.Sorted.getIso` is the same bijection reinterpreted as an `OrderIso`. -/ namespace List variable {Ξ± : Type*} namespace Nodup /-- If `l` lists all the elements of `Ξ±` without duplicates, then `List.get` defines a bijection `Fin l.length β†’ Ξ±`. See `List.Nodup.getEquivOfForallMemList` for a version giving an equivalence when there is decidable equality. -/ @[simps] def getBijectionOfForallMemList (l : List Ξ±) (nd : l.Nodup) (h : βˆ€ x : Ξ±, x ∈ l) : { f : Fin l.length β†’ Ξ± // Function.Bijective f } := ⟨fun i => l.get i, fun _ _ h => nd.get_inj_iff.1 h, fun x => let ⟨i, hl⟩ := List.mem_iff_get.1 (h x) ⟨i, hl⟩⟩ variable [DecidableEq Ξ±] /-- If `l` has no duplicates, then `List.get` defines an equivalence between `Fin (length l)` and the set of elements of `l`. -/ @[simps] def getEquiv (l : List Ξ±) (H : Nodup l) : Fin (length l) ≃ { x // x ∈ l } where toFun i := ⟨get l i, get_mem _ _⟩ invFun x := ⟨idxOf (↑x) l, idxOf_lt_length_iff.2 x.2⟩ left_inv i := by simp only [List.get_idxOf, Fin.eta, H] right_inv x := by simp /-- If `l` lists all the elements of `Ξ±` without duplicates, then `List.get` defines an equivalence between `Fin l.length` and `Ξ±`. See `List.Nodup.getBijectionOfForallMemList` for a version without decidable equality. -/ @[simps] def getEquivOfForallMemList (l : List Ξ±) (nd : l.Nodup) (h : βˆ€ x : Ξ±, x ∈ l) : Fin l.length ≃ Ξ± where toFun i := l.get i invFun a := ⟨_, idxOf_lt_length_iff.2 (h a)⟩ left_inv i := by simp [List.idxOf_getElem, nd] right_inv a := by simp end Nodup /-- Alternative phrasing of `List.Nodup.getEquivOfForallMemList` using `List.count`. -/ @[simps!] def getEquivOfForallCountEqOne [DecidableEq Ξ±] (l : List Ξ±) (h : βˆ€ x, l.count x = 1) : Fin l.length ≃ Ξ± := Nodup.getEquivOfForallMemList _ (List.nodup_iff_count_eq_one.mpr fun _ _ ↦ h _) fun _ ↦ List.count_pos_iff.mp <| h _ β–Έ Nat.one_pos namespace Sorted variable [Preorder Ξ±] {l : List Ξ±} theorem get_mono (h : l.Sorted (Β· ≀ Β·)) : Monotone l.get := fun _ _ => h.rel_get_of_le theorem get_strictMono (h : l.Sorted (Β· < Β·)) : StrictMono l.get := fun _ _ => h.rel_get_of_lt variable [DecidableEq Ξ±] /-- If `l` is a list sorted w.r.t. `(<)`, then `List.get` defines an order isomorphism between `Fin (length l)` and the set of elements of `l`. -/ def getIso (l : List Ξ±) (H : Sorted (Β· < Β·) l) : Fin (length l) ≃o { x // x ∈ l } where toEquiv := H.nodup.getEquiv l map_rel_iff' := H.get_strictMono.le_iff_le variable (H : Sorted (Β· < Β·) l) {x : { x // x ∈ l }} {i : Fin l.length} @[simp] theorem coe_getIso_apply : (H.getIso l i : Ξ±) = get l i := rfl @[simp] theorem coe_getIso_symm_apply : ((H.getIso l).symm x : β„•) = idxOf (↑x) l := rfl end Sorted section Sublist /-- If there is `f`, an order-preserving embedding of `β„•` into `β„•` such that any element of `l` found at index `ix` can be found at index `f ix` in `l'`, then `Sublist l l'`. -/ theorem sublist_of_orderEmbedding_getElem?_eq {l l' : List Ξ±} (f : β„• β†ͺo β„•) (hf : βˆ€ ix : β„•, l[ix]? = l'[f ix]?) : l <+ l' := by induction l generalizing l' f with | nil => simp | cons hd tl IH => ?_ have : some hd = l'[f 0]? := by simpa using hf 0 rw [eq_comm, List.getElem?_eq_some_iff] at this obtain ⟨w, h⟩ := this let f' : β„• β†ͺo β„• := OrderEmbedding.ofMapLEIff (fun i => f (i + 1) - (f 0 + 1)) fun a b => by dsimp only rw [Nat.sub_le_sub_iff_right, OrderEmbedding.le_iff_le, Nat.succ_le_succ_iff] rw [Nat.succ_le_iff, OrderEmbedding.lt_iff_lt] exact b.succ_pos have : βˆ€ ix, tl[ix]? = (l'.drop (f 0 + 1))[f' ix]? := by intro ix rw [List.getElem?_drop, OrderEmbedding.coe_ofMapLEIff, Nat.add_sub_cancel', ← hf] Β· simp only [getElem?_cons_succ] rw [Nat.succ_le_iff, OrderEmbedding.lt_iff_lt] exact ix.succ_pos rw [← List.take_append_drop (f 0 + 1) l', ← List.singleton_append] apply List.Sublist.append _ (IH _ this) rw [List.singleton_sublist, ← h, l'.getElem_take' _ (Nat.lt_succ_self _)] exact List.getElem_mem _ /-- A `l : List Ξ±` is `Sublist l l'` for `l' : List Ξ±` iff there is `f`, an order-preserving embedding of `β„•` into `β„•` such that any element of `l` found at index `ix` can be found at index `f ix` in `l'`. -/ theorem sublist_iff_exists_orderEmbedding_getElem?_eq {l l' : List Ξ±} : l <+ l' ↔ βˆƒ f : β„• β†ͺo β„•, βˆ€ ix : β„•, l[ix]? = l'[f ix]? := by constructor Β· intro H induction H with | slnil => simp | cons _ _ IH => obtain ⟨f, hf⟩ := IH refine ⟨f.trans (OrderEmbedding.ofStrictMono (Β· + 1) fun _ => by simp), ?_⟩ simpa using hf | consβ‚‚ _ _ IH => obtain ⟨f, hf⟩ := IH refine ⟨OrderEmbedding.ofMapLEIff (fun ix : β„• => if ix = 0 then 0 else (f ix.pred).succ) ?_, ?_⟩ Β· rintro ⟨_ | a⟩ ⟨_ | b⟩ <;> simp [Nat.succ_le_succ_iff] Β· rintro ⟨_ | i⟩ Β· simp Β· simpa using hf _ Β· rintro ⟨f, hf⟩ exact sublist_of_orderEmbedding_getElem?_eq f hf /-- A `l : List Ξ±` is `Sublist l l'` for `l' : List Ξ±` iff there is `f`, an order-preserving embedding of `Fin l.length` into `Fin l'.length` such that any element of `l` found at index `ix` can be found at index `f ix` in `l'`. -/ theorem sublist_iff_exists_fin_orderEmbedding_get_eq {l l' : List Ξ±} : l <+ l' ↔ βˆƒ f : Fin l.length β†ͺo Fin l'.length, βˆ€ ix : Fin l.length, l.get ix = l'.get (f ix) := by rw [sublist_iff_exists_orderEmbedding_getElem?_eq] constructor Β· rintro ⟨f, hf⟩ have h : βˆ€ {i : β„•}, i < l.length β†’ f i < l'.length := by intro i hi specialize hf i rw [getElem?_eq_getElem hi, eq_comm, getElem?_eq_some_iff] at hf obtain ⟨h, -⟩ := hf exact h refine ⟨OrderEmbedding.ofMapLEIff (fun ix => ⟨f ix, h ix.is_lt⟩) ?_, ?_⟩ Β· simp Β· intro i apply Option.some_injective simpa [getElem?_eq_getElem i.2, getElem?_eq_getElem (h i.2)] using hf i Β· rintro ⟨f, hf⟩ refine ⟨OrderEmbedding.ofStrictMono (fun i => if hi : i < l.length then f ⟨i, hi⟩ else i + l'.length) ?_, ?_⟩ Β· intro i j h dsimp only split_ifs with hi hj hj Β· rwa [Fin.val_fin_lt, f.lt_iff_lt] Β· cutsat Β· exact absurd (h.trans hj) hi Β· simpa using h Β· intro i simp only [OrderEmbedding.coe_ofStrictMono] split_ifs with hi Β· specialize hf ⟨i, hi⟩ simp_all Β· rw [getElem?_eq_none_iff.mpr, getElem?_eq_none_iff.mpr] Β· simp Β· simpa using hi /-- An element `x : Ξ±` of `l : List Ξ±` is a duplicate iff it can be found at two distinct indices `n m : β„•` inside the list `l`. -/ theorem duplicate_iff_exists_distinct_get {l : List Ξ±} {x : Ξ±} : l.Duplicate x ↔ βˆƒ (n m : Fin l.length) (_ : n < m), x = l.get n ∧ x = l.get m := by classical rw [duplicate_iff_two_le_count, ← replicate_sublist_iff, sublist_iff_exists_fin_orderEmbedding_get_eq] constructor Β· rintro ⟨f, hf⟩ refine ⟨f ⟨0, by simp⟩, f ⟨1, by simp⟩, f.lt_iff_lt.2 (Nat.zero_lt_one), ?_⟩ rw [← hf, ← hf]; simp Β· rintro ⟨n, m, hnm, h, h'⟩ refine ⟨OrderEmbedding.ofStrictMono (fun i => if (i : β„•) = 0 then n else m) ?_, ?_⟩ Β· rintro ⟨⟨_ | i⟩, hi⟩ ⟨⟨_ | j⟩, hj⟩ Β· simp Β· simp [hnm] Β· simp Β· simp only [Nat.lt_succ_iff, Nat.succ_le_succ_iff, replicate, length, Nat.le_zero] at hi hj simp [hi, hj] Β· rintro ⟨⟨_ | i⟩, hi⟩ Β· simpa using h Β· simpa using h' end Sublist end List
.lake/packages/mathlib/Mathlib/Data/List/Indexes.lean
import Mathlib.Util.AssertExists import Mathlib.Data.List.Defs /-! # Lemmas about List.*Idx functions. Some specification lemmas for `List.mapIdx`, `List.mapIdxM`, `List.foldlIdx` and `List.foldrIdx`. As of 2025-01-29, these are not used anywhere in Mathlib. Moreover, with `List.enum` and `List.enumFrom` being replaced by `List.zipIdx` in Lean's `nightly-2025-01-29` release, they now use deprecated functions and theorems. Rather than updating this unused material, we are deprecating it. Anyone wanting to restore this material is welcome to do so, but will need to update uses of `List.enum` and `List.enumFrom` to use `List.zipIdx` instead. However, note that this material will later be implemented in the Lean standard library. -/ assert_not_exists MonoidWithZero universe u v open Function namespace List variable {Ξ± : Type u} {Ξ² : Type v} section MapIdx theorem mapIdx_append_one : βˆ€ {f : β„• β†’ Ξ± β†’ Ξ²} {l : List Ξ±} {e : Ξ±}, mapIdx f (l ++ [e]) = mapIdx f l ++ [f l.length e] := mapIdx_concat theorem mapIdx_eq_ofFn (l : List Ξ±) (f : β„• β†’ Ξ± β†’ Ξ²) : l.mapIdx f = ofFn fun i : Fin l.length ↦ f (i : β„•) (l.get i) := by induction l generalizing f with | nil => simp | cons _ _ IH => simp [IH] end MapIdx section MapIdxM' variable {m : Type u β†’ Type v} [Monad m] [LawfulMonad m] theorem mapIdxMAux'_eq_mapIdxMGo {Ξ±} (f : β„• β†’ Ξ± β†’ m PUnit) (as : List Ξ±) (arr : Array PUnit) : mapIdxMAux' f arr.size as = mapIdxM.go f as arr *> pure PUnit.unit := by induction as generalizing arr with | nil => simp only [mapIdxMAux', mapIdxM.go, seqRight_eq, map_pure, seq_pure] | cons head tail ih => simp only [mapIdxMAux', seqRight_eq, map_eq_pure_bind, seq_eq_bind, bind_pure_unit, LawfulMonad.bind_assoc, pure_bind, mapIdxM.go] generalize (f (Array.size arr) head) = head have : (arr.push ⟨⟩).size = arr.size + 1 := Array.size_push _ rw [← this, ih] simp only [seqRight_eq, map_eq_pure_bind, seq_pure, LawfulMonad.bind_assoc, pure_bind] theorem mapIdxM'_eq_mapIdxM {Ξ±} (f : β„• β†’ Ξ± β†’ m PUnit) (as : List Ξ±) : mapIdxM' f as = mapIdxM f as *> pure PUnit.unit := mapIdxMAux'_eq_mapIdxMGo f as #[] end MapIdxM' end List
.lake/packages/mathlib/Mathlib/Data/List/Pi.lean
import Mathlib.Data.Multiset.Pi /-! # The Cartesian product of lists ## Main definitions * `List.pi`: Cartesian product of lists indexed by a list. -/ namespace List namespace Pi variable {ΞΉ : Type*} [DecidableEq ΞΉ] {Ξ± : ΞΉ β†’ Sort*} /-- Given `Ξ± : ΞΉ β†’ Sort*`, `Pi.nil Ξ±` is the trivial dependent function out of the empty list. -/ def nil (Ξ± : ΞΉ β†’ Sort*) : (βˆ€ i ∈ ([] : List ΞΉ), Ξ± i) := nofun variable {i : ΞΉ} {l : List ΞΉ} /-- Given `f` a function whose domain is `i :: l`, get its value at `i`. -/ def head (f : βˆ€ j ∈ i :: l, Ξ± j) : Ξ± i := f i mem_cons_self /-- Given `f` a function whose domain is `i :: l`, produce a function whose domain is restricted to `l`. -/ def tail (f : βˆ€ j ∈ i :: l, Ξ± j) : βˆ€ j ∈ l, Ξ± j := fun j hj ↦ f j (mem_cons_of_mem _ hj) variable (i l) /-- Given `Ξ± : ΞΉ β†’ Sort*`, a list `l` and a term `i`, as well as a term `a : Ξ± i` and a function `f` such that `f j : Ξ± j` for all `j` in `l`, `Pi.cons a f` is a function `g` such that `g k : Ξ± k` for all `k` in `i :: l`. -/ def cons (a : Ξ± i) (f : βˆ€ j ∈ l, Ξ± j) : βˆ€ j ∈ i :: l, Ξ± j := Multiset.Pi.cons (Ξ± := ΞΉ) l _ a f variable {i l} lemma cons_def (a : Ξ± i) (f : βˆ€ j ∈ l, Ξ± j) : cons _ _ a f = fun j hj ↦ if h : j = i then h.symm.rec a else f j <| (mem_cons.1 hj).resolve_left h := rfl @[simp] lemma _root_.Multiset.Pi.cons_coe {l : List ΞΉ} (a : Ξ± i) (f : βˆ€ j ∈ l, Ξ± j) : Multiset.Pi.cons l _ a f = cons _ _ a f := rfl @[simp] lemma cons_eta (f : βˆ€ j ∈ i :: l, Ξ± j) : cons _ _ (head f) (tail f) = f := Multiset.Pi.cons_eta (Ξ± := ΞΉ) (m := l) f lemma cons_map (a : Ξ± i) (f : βˆ€ j ∈ l, Ξ± j) {Ξ±' : ΞΉ β†’ Sort*} (Ο† : βˆ€ ⦃j⦄, Ξ± j β†’ Ξ±' j) : cons _ _ (Ο† a) (fun j hj ↦ Ο† (f j hj)) = (fun j hj ↦ Ο† ((cons _ _ a f) j hj)) := Multiset.Pi.cons_map _ _ _ lemma forall_rel_cons_ext {r : βˆ€ ⦃i⦄, Ξ± i β†’ Ξ± i β†’ Prop} {a₁ aβ‚‚ : Ξ± i} {f₁ fβ‚‚ : βˆ€ j ∈ l, Ξ± j} (ha : r a₁ aβ‚‚) (hf : βˆ€ (i : ΞΉ) (hi : i ∈ l), r (f₁ i hi) (fβ‚‚ i hi)) : βˆ€ j hj, r (cons _ _ a₁ f₁ j hj) (cons _ _ aβ‚‚ fβ‚‚ j hj) := Multiset.Pi.forall_rel_cons_ext (Ξ± := ΞΉ) (m := l) ha hf end Pi variable {ΞΉ : Type*} [DecidableEq ΞΉ] {Ξ± : ΞΉ β†’ Type*} /-- `pi xs f` creates the list of functions `g` such that, for `x ∈ xs`, `g x ∈ f x` -/ def pi : βˆ€ l : List ΞΉ, (βˆ€ i, List (Ξ± i)) β†’ List (βˆ€ i, i ∈ l β†’ Ξ± i) | [], _ => [List.Pi.nil Ξ±] | i :: l, fs => (fs i).flatMap (fun b ↦ (pi l fs).map (List.Pi.cons _ _ b)) @[simp] lemma pi_nil (t : βˆ€ i, List (Ξ± i)) : pi [] t = [Pi.nil Ξ±] := rfl @[simp] lemma pi_cons (i : ΞΉ) (l : List ΞΉ) (t : βˆ€ j, List (Ξ± j)) : pi (i :: l) t = ((t i).flatMap fun b ↦ (pi l t).map <| Pi.cons _ _ b) := rfl lemma _root_.Multiset.pi_coe (l : List ΞΉ) (fs : βˆ€ i, List (Ξ± i)) : (l : Multiset ΞΉ).pi (fs Β·) = (↑(pi l fs) : Multiset (βˆ€ i ∈ l, Ξ± i)) := by induction l with | nil => simp only [Multiset.coe_nil, Multiset.pi_zero, pi_nil, Multiset.coe_singleton, Multiset.singleton_inj] ext i hi simp at hi | cons i l ih => simp [ih, Multiset.coe_bind, ← Multiset.cons_coe] lemma mem_pi {l : List ΞΉ} (fs : βˆ€ i, List (Ξ± i)) (f : βˆ€ i ∈ l, Ξ± i) : (f ∈ pi l fs) ↔ (βˆ€ i (hi : i ∈ l), f i hi ∈ fs i) := by simpa [Multiset.pi_coe] using Multiset.mem_pi ↑l (fs Β·) f end List
.lake/packages/mathlib/Mathlib/Data/List/Monad.lean
import Mathlib.Init import Batteries.Control.AlternativeMonad /-! # Monad instances for `List` -/ universe u namespace List variable {Ξ± : Type u} instance instMonad : Monad List.{u} where pure x := [x] bind l f := l.flatMap f map f l := l.map f @[simp] theorem pure_def (a : Ξ±) : pure a = [a] := rfl instance instLawfulMonad : LawfulMonad List.{u} := LawfulMonad.mk' (id_map := map_id) (pure_bind := fun _ _ => List.append_nil _) (bind_assoc := fun _ _ _ => List.flatMap_assoc) (bind_pure_comp := fun _ _ => map_eq_flatMap.symm) instance : AlternativeMonad List.{u} where failure := @List.nil orElse l l' := List.append l (l' ()) instance : LawfulAlternative List where map_failure _ := List.map_nil failure_seq _ := List.flatMap_nil orElse_failure _ := List.append_nil _ failure_orElse _ := List.nil_append _ orElse_assoc _ _ _ := List.append_assoc _ _ _ |>.symm map_orElse _ _ _ := List.map_append end List
.lake/packages/mathlib/Mathlib/Data/List/Duplicate.lean
import Mathlib.Data.List.Nodup /-! # List duplicates ## Main definitions * `List.Duplicate x l : Prop` is an inductive property that holds when `x` is a duplicate in `l` ## Implementation details In this file, `x ∈+ l` notation is shorthand for `List.Duplicate x l`. -/ variable {Ξ± : Type*} namespace List /-- Property that an element `x : Ξ±` of `l : List Ξ±` can be found in the list more than once. -/ inductive Duplicate (x : Ξ±) : List Ξ± β†’ Prop | cons_mem {l : List Ξ±} : x ∈ l β†’ Duplicate x (x :: l) | cons_duplicate {y : Ξ±} {l : List Ξ±} : Duplicate x l β†’ Duplicate x (y :: l) local infixl:50 " ∈+ " => List.Duplicate variable {l : List Ξ±} {x : Ξ±} theorem Mem.duplicate_cons_self (h : x ∈ l) : x ∈+ x :: l := Duplicate.cons_mem h theorem Duplicate.duplicate_cons (h : x ∈+ l) (y : Ξ±) : x ∈+ y :: l := Duplicate.cons_duplicate h theorem Duplicate.mem (h : x ∈+ l) : x ∈ l := by induction h with | cons_mem => exact mem_cons_self | cons_duplicate _ hm => exact mem_cons_of_mem _ hm theorem Duplicate.mem_cons_self (h : x ∈+ x :: l) : x ∈ l := by obtain h | h := h Β· exact h Β· exact h.mem @[simp] theorem duplicate_cons_self_iff : x ∈+ x :: l ↔ x ∈ l := ⟨Duplicate.mem_cons_self, Mem.duplicate_cons_self⟩ theorem Duplicate.ne_nil (h : x ∈+ l) : l β‰  [] := fun H => (mem_nil_iff x).mp (H β–Έ h.mem) @[simp] theorem not_duplicate_nil (x : Ξ±) : Β¬x ∈+ [] := fun H => H.ne_nil rfl theorem Duplicate.ne_singleton (h : x ∈+ l) (y : Ξ±) : l β‰  [y] := by induction h with | cons_mem h => simp [ne_nil_of_mem h] | cons_duplicate h => simp [ne_nil_of_mem h.mem] @[simp] theorem not_duplicate_singleton (x y : Ξ±) : Β¬x ∈+ [y] := fun H => H.ne_singleton _ rfl theorem Duplicate.elim_nil (h : x ∈+ []) : False := not_duplicate_nil x h theorem Duplicate.elim_singleton {y : Ξ±} (h : x ∈+ [y]) : False := not_duplicate_singleton x y h theorem duplicate_cons_iff {y : Ξ±} : x ∈+ y :: l ↔ y = x ∧ x ∈ l ∨ x ∈+ l := by refine ⟨fun h => ?_, fun h => ?_⟩ Β· obtain hm | hm := h Β· exact Or.inl ⟨rfl, hm⟩ Β· exact Or.inr hm Β· rcases h with (⟨rfl | h⟩ | h) Β· simpa Β· exact h.cons_duplicate theorem Duplicate.of_duplicate_cons {y : Ξ±} (h : x ∈+ y :: l) (hx : x β‰  y) : x ∈+ l := by simpa [duplicate_cons_iff, hx.symm] using h theorem duplicate_cons_iff_of_ne {y : Ξ±} (hne : x β‰  y) : x ∈+ y :: l ↔ x ∈+ l := by simp [duplicate_cons_iff, hne.symm] theorem Duplicate.mono_sublist {l' : List Ξ±} (hx : x ∈+ l) (h : l <+ l') : x ∈+ l' := by induction h with | slnil => exact hx | cons y _ IH => exact (IH hx).duplicate_cons _ | consβ‚‚ y h IH => rw [duplicate_cons_iff] at hx ⊒ rcases hx with (⟨rfl, hx⟩ | hx) Β· simp [h.subset hx] Β· simp [IH hx] /-- The contrapositive of `List.nodup_iff_sublist`. -/ theorem duplicate_iff_sublist : x ∈+ l ↔ [x, x] <+ l := by induction l with | nil => simp | cons y l IH => by_cases hx : x = y Β· simp [hx, cons_sublist_cons, singleton_sublist] Β· rw [duplicate_cons_iff_of_ne hx, IH] refine ⟨sublist_cons_of_sublist y, fun h => ?_⟩ cases h Β· assumption Β· contradiction theorem nodup_iff_forall_not_duplicate : Nodup l ↔ βˆ€ x : Ξ±, Β¬x ∈+ l := by simp_rw [nodup_iff_sublist, duplicate_iff_sublist] theorem exists_duplicate_iff_not_nodup : (βˆƒ x : Ξ±, x ∈+ l) ↔ Β¬Nodup l := by simp [nodup_iff_forall_not_duplicate] theorem Duplicate.not_nodup (h : x ∈+ l) : Β¬Nodup l := fun H => nodup_iff_forall_not_duplicate.mp H _ h theorem duplicate_iff_two_le_count [DecidableEq Ξ±] : x ∈+ l ↔ 2 ≀ count x l := by simp [replicate_succ, duplicate_iff_sublist, ← replicate_sublist_iff] instance decidableDuplicate [DecidableEq Ξ±] (x : Ξ±) : βˆ€ l : List Ξ±, Decidable (x ∈+ l) | [] => isFalse (not_duplicate_nil x) | y :: l => match decidableDuplicate x l with | isTrue h => isTrue (h.duplicate_cons y) | isFalse h => if hx : y = x ∧ x ∈ l then isTrue (hx.left.symm β–Έ List.Mem.duplicate_cons_self hx.right) else isFalse (by simpa [duplicate_cons_iff, h] using hx) end List
.lake/packages/mathlib/Mathlib/Data/List/Basic.lean
import Mathlib.Control.Basic import Mathlib.Data.Option.Basic import Mathlib.Data.List.Defs import Mathlib.Data.List.Monad import Mathlib.Logic.OpClass import Mathlib.Logic.Unique import Mathlib.Tactic.Common /-! # Basic properties of lists -/ assert_not_exists Lattice assert_not_exists Monoid assert_not_exists Preorder assert_not_exists Prod.swap_eq_iff_eq_swap assert_not_exists Set.range open Function open Nat hiding one_pos namespace List universe u v w variable {ΞΉ : Type*} {Ξ± : Type u} {Ξ² : Type v} {Ξ³ : Type w} {l₁ lβ‚‚ : List Ξ±} /-- There is only one list of an empty type -/ instance uniqueOfIsEmpty [IsEmpty Ξ±] : Unique (List Ξ±) := { instInhabitedList with uniq := fun l => match l with | [] => rfl | a :: _ => isEmptyElim a } instance : Std.LawfulIdentity (Ξ± := List Ξ±) Append.append [] where left_id := nil_append right_id := append_nil instance : Std.Associative (Ξ± := List Ξ±) Append.append where assoc := append_assoc @[simp] theorem cons_injective {a : Ξ±} : Injective (cons a) := fun _ _ => tail_eq_of_cons_eq theorem singleton_injective : Injective fun a : Ξ± => [a] := fun _ _ h => (cons_eq_cons.1 h).1 theorem set_of_mem_cons (l : List Ξ±) (a : Ξ±) : { x | x ∈ a :: l } = insert a { x | x ∈ l } := Set.ext fun _ => mem_cons /-! ### mem -/ theorem _root_.Decidable.List.eq_or_ne_mem_of_mem [DecidableEq Ξ±] {a b : Ξ±} {l : List Ξ±} (h : a ∈ b :: l) : a = b ∨ a β‰  b ∧ a ∈ l := by by_cases hab : a = b Β· exact Or.inl hab Β· exact ((List.mem_cons.1 h).elim Or.inl (fun h => Or.inr ⟨hab, h⟩)) lemma mem_pair {a b c : Ξ±} : a ∈ [b, c] ↔ a = b ∨ a = c := by rw [mem_cons, mem_singleton] -- The simpNF linter says that the LHS can be simplified via `List.mem_map`. -- However this is a higher priority lemma. -- It seems the side condition `hf` is not applied by `simpNF`. -- https://github.com/leanprover/std4/issues/207 @[simp 1100, nolint simpNF] theorem mem_map_of_injective {f : Ξ± β†’ Ξ²} (H : Injective f) {a : Ξ±} {l : List Ξ±} : f a ∈ map f l ↔ a ∈ l := ⟨fun m => let ⟨_, m', e⟩ := exists_of_mem_map m; H e β–Έ m', mem_map_of_mem⟩ @[simp] theorem _root_.Function.Involutive.exists_mem_and_apply_eq_iff {f : Ξ± β†’ Ξ±} (hf : Function.Involutive f) (x : Ξ±) (l : List Ξ±) : (βˆƒ y : Ξ±, y ∈ l ∧ f y = x) ↔ f x ∈ l := ⟨by rintro ⟨y, h, rfl⟩; rwa [hf y], fun h => ⟨f x, h, hf _⟩⟩ theorem mem_map_of_involutive {f : Ξ± β†’ Ξ±} (hf : Involutive f) {a : Ξ±} {l : List Ξ±} : a ∈ map f l ↔ f a ∈ l := by rw [mem_map, hf.exists_mem_and_apply_eq_iff] /-! ### length -/ alias ⟨_, length_pos_of_ne_nil⟩ := length_pos_iff theorem length_pos_iff_ne_nil {l : List Ξ±} : 0 < length l ↔ l β‰  [] := ⟨ne_nil_of_length_pos, length_pos_of_ne_nil⟩ theorem exists_of_length_succ {n} : βˆ€ l : List Ξ±, l.length = n + 1 β†’ βˆƒ h t, l = h :: t | [], H => absurd H.symm <| succ_ne_zero n | h :: t, _ => ⟨h, t, rfl⟩ @[simp] lemma length_injective_iff : Injective (List.length : List Ξ± β†’ β„•) ↔ Subsingleton Ξ± := by constructor Β· intro h; refine ⟨fun x y => ?_⟩; (suffices [x] = [y] by simpa using this); apply h; rfl Β· intro hΞ± l1 l2 hl induction l1 generalizing l2 <;> cases l2 Β· rfl Β· cases hl Β· cases hl Β· next ih _ _ => congr Β· subsingleton Β· apply ih; simpa using hl @[simp default + 1] -- Raise priority above `length_injective_iff`. lemma length_injective [Subsingleton Ξ±] : Injective (length : List Ξ± β†’ β„•) := length_injective_iff.mpr inferInstance theorem length_eq_two {l : List Ξ±} : l.length = 2 ↔ βˆƒ a b, l = [a, b] := ⟨fun _ => let [a, b] := l; ⟨a, b, rfl⟩, fun ⟨_, _, e⟩ => e β–Έ rfl⟩ theorem length_eq_three {l : List Ξ±} : l.length = 3 ↔ βˆƒ a b c, l = [a, b, c] := ⟨fun _ => let [a, b, c] := l; ⟨a, b, c, rfl⟩, fun ⟨_, _, _, e⟩ => e β–Έ rfl⟩ theorem length_eq_four {l : List Ξ±} : l.length = 4 ↔ βˆƒ a b c d, l = [a, b, c, d] := ⟨fun _ => let [a, b, c, d] := l; ⟨a, b, c, d, rfl⟩, fun ⟨_, _, _, _, e⟩ => e β–Έ rfl⟩ /-! ### set-theoretic notation of lists -/ instance instSingletonList : Singleton Ξ± (List Ξ±) := ⟨fun x => [x]⟩ instance [DecidableEq Ξ±] : Insert Ξ± (List Ξ±) := ⟨List.insert⟩ instance [DecidableEq Ξ±] : LawfulSingleton Ξ± (List Ξ±) := { insert_empty_eq := fun x => show (if x ∈ ([] : List Ξ±) then [] else [x]) = [x] from if_neg not_mem_nil } theorem singleton_eq (x : Ξ±) : ({x} : List Ξ±) = [x] := rfl theorem insert_neg [DecidableEq Ξ±] {x : Ξ±} {l : List Ξ±} (h : x βˆ‰ l) : Insert.insert x l = x :: l := insert_of_not_mem h theorem insert_pos [DecidableEq Ξ±] {x : Ξ±} {l : List Ξ±} (h : x ∈ l) : Insert.insert x l = l := insert_of_mem h theorem doubleton_eq [DecidableEq Ξ±] {x y : Ξ±} (h : x β‰  y) : ({x, y} : List Ξ±) = [x, y] := by rw [insert_neg, singleton_eq] rwa [singleton_eq, mem_singleton] /-! ### bounded quantifiers over lists -/ theorem forall_mem_of_forall_mem_cons {p : Ξ± β†’ Prop} {a : Ξ±} {l : List Ξ±} (h : βˆ€ x ∈ a :: l, p x) : βˆ€ x ∈ l, p x := (forall_mem_cons.1 h).2 theorem exists_mem_cons_of {p : Ξ± β†’ Prop} {a : Ξ±} (l : List Ξ±) (h : p a) : βˆƒ x ∈ a :: l, p x := ⟨a, mem_cons_self, h⟩ theorem exists_mem_cons_of_exists {p : Ξ± β†’ Prop} {a : Ξ±} {l : List Ξ±} : (βˆƒ x ∈ l, p x) β†’ βˆƒ x ∈ a :: l, p x := fun ⟨x, xl, px⟩ => ⟨x, mem_cons_of_mem _ xl, px⟩ theorem or_exists_of_exists_mem_cons {p : Ξ± β†’ Prop} {a : Ξ±} {l : List Ξ±} : (βˆƒ x ∈ a :: l, p x) β†’ p a ∨ βˆƒ x ∈ l, p x := by grind theorem exists_mem_cons_iff (p : Ξ± β†’ Prop) (a : Ξ±) (l : List Ξ±) : (βˆƒ x ∈ a :: l, p x) ↔ p a ∨ βˆƒ x ∈ l, p x := by grind /-! ### list subset -/ theorem cons_subset_of_subset_of_mem {a : Ξ±} {l m : List Ξ±} (ainm : a ∈ m) (lsubm : l βŠ† m) : a::l βŠ† m := cons_subset.2 ⟨ainm, lsubm⟩ theorem append_subset_of_subset_of_subset {l₁ lβ‚‚ l : List Ξ±} (l₁subl : l₁ βŠ† l) (lβ‚‚subl : lβ‚‚ βŠ† l) : l₁ ++ lβ‚‚ βŠ† l := fun _ h ↦ (mem_append.1 h).elim (@l₁subl _) (@lβ‚‚subl _) theorem map_subset_iff {l₁ lβ‚‚ : List Ξ±} (f : Ξ± β†’ Ξ²) (h : Injective f) : map f l₁ βŠ† map f lβ‚‚ ↔ l₁ βŠ† lβ‚‚ := by refine ⟨?_, map_subset f⟩; intro h2 x hx rcases mem_map.1 (h2 (mem_map_of_mem hx)) with ⟨x', hx', hxx'⟩ cases h hxx'; exact hx' /-! ### append -/ theorem append_eq_has_append {L₁ Lβ‚‚ : List Ξ±} : List.append L₁ Lβ‚‚ = L₁ ++ Lβ‚‚ := rfl theorem append_right_injective (s : List Ξ±) : Injective fun t ↦ s ++ t := fun _ _ ↦ append_cancel_left theorem append_left_injective (t : List Ξ±) : Injective fun s ↦ s ++ t := fun _ _ ↦ append_cancel_right /-! ### replicate -/ theorem eq_replicate_length {a : Ξ±} : βˆ€ {l : List Ξ±}, l = replicate l.length a ↔ βˆ€ b ∈ l, b = a | [] => by simp | (b :: l) => by simp [eq_replicate_length, replicate_succ] theorem replicate_add (m n) (a : Ξ±) : replicate (m + n) a = replicate m a ++ replicate n a := by rw [replicate_append_replicate] theorem replicate_subset_singleton (n) (a : Ξ±) : replicate n a βŠ† [a] := fun _ h => mem_singleton.2 (eq_of_mem_replicate h) theorem subset_singleton_iff {a : Ξ±} {L : List Ξ±} : L βŠ† [a] ↔ βˆƒ n, L = replicate n a := by simp only [eq_replicate_iff, subset_def, mem_singleton, exists_eq_left'] theorem replicate_right_injective {n : β„•} (hn : n β‰  0) : Injective (@replicate Ξ± n) := fun _ _ h => (eq_replicate_iff.1 h).2 _ <| mem_replicate.2 ⟨hn, rfl⟩ theorem replicate_right_inj {a b : Ξ±} {n : β„•} (hn : n β‰  0) : replicate n a = replicate n b ↔ a = b := (replicate_right_injective hn).eq_iff theorem replicate_right_inj' {a b : Ξ±} : βˆ€ {n}, replicate n a = replicate n b ↔ n = 0 ∨ a = b | 0 => by simp | n + 1 => (replicate_right_inj n.succ_ne_zero).trans <| by simp only [n.succ_ne_zero, false_or] theorem replicate_left_injective (a : Ξ±) : Injective (replicate Β· a) := LeftInverse.injective (length_replicate (n := Β·)) theorem replicate_left_inj {a : Ξ±} {n m : β„•} : replicate n a = replicate m a ↔ n = m := (replicate_left_injective a).eq_iff @[simp] theorem head?_flatten_replicate {n : β„•} (h : n β‰  0) (l : List Ξ±) : (List.replicate n l).flatten.head? = l.head? := by obtain ⟨n, rfl⟩ := Nat.exists_eq_succ_of_ne_zero h induction l <;> simp [replicate] @[simp] theorem getLast?_flatten_replicate {n : β„•} (h : n β‰  0) (l : List Ξ±) : (List.replicate n l).flatten.getLast? = l.getLast? := by rw [← List.head?_reverse, ← List.head?_reverse, List.reverse_flatten, List.map_replicate, List.reverse_replicate, head?_flatten_replicate h] /-! ### pure -/ theorem mem_pure (x y : Ξ±) : x ∈ (pure y : List Ξ±) ↔ x = y := by simp /-! ### bind -/ @[simp] theorem bind_eq_flatMap {Ξ± Ξ²} (f : Ξ± β†’ List Ξ²) (l : List Ξ±) : l >>= f = l.flatMap f := rfl /-! ### concat -/ /-! ### reverse -/ theorem reverse_cons' (a : Ξ±) (l : List Ξ±) : reverse (a :: l) = concat (reverse l) a := by simp only [reverse_cons, concat_eq_append] theorem reverse_concat' (l : List Ξ±) (a : Ξ±) : (l ++ [a]).reverse = a :: l.reverse := by rw [reverse_append]; rfl @[simp] theorem reverse_singleton (a : Ξ±) : reverse [a] = [a] := rfl @[simp] theorem reverse_involutive : Involutive (@reverse Ξ±) := reverse_reverse @[simp] theorem reverse_injective : Injective (@reverse Ξ±) := reverse_involutive.injective theorem reverse_surjective : Surjective (@reverse Ξ±) := reverse_involutive.surjective theorem reverse_bijective : Bijective (@reverse Ξ±) := reverse_involutive.bijective theorem concat_eq_reverse_cons (a : Ξ±) (l : List Ξ±) : concat l a = reverse (a :: reverse l) := by simp only [concat_eq_append, reverse_cons, reverse_reverse] theorem map_reverseAux (f : Ξ± β†’ Ξ²) (l₁ lβ‚‚ : List Ξ±) : map f (reverseAux l₁ lβ‚‚) = reverseAux (map f l₁) (map f lβ‚‚) := by simp only [reverseAux_eq, map_append, map_reverse] -- TODO: Rename `List.reverse_perm` to `List.reverse_perm_self` @[simp] lemma reverse_perm' : l₁.reverse ~ lβ‚‚ ↔ l₁ ~ lβ‚‚ where mp := l₁.reverse_perm.symm.trans mpr := l₁.reverse_perm.trans @[simp] lemma perm_reverse : l₁ ~ lβ‚‚.reverse ↔ l₁ ~ lβ‚‚ where mp hl := hl.trans lβ‚‚.reverse_perm mpr hl := hl.trans lβ‚‚.reverse_perm.symm /-! ### getLast -/ attribute [simp] getLast_cons theorem getLast_append_singleton {a : Ξ±} (l : List Ξ±) : getLast (l ++ [a]) (append_ne_nil_of_right_ne_nil l (cons_ne_nil a _)) = a := by simp theorem getLast_append_of_right_ne_nil (l₁ lβ‚‚ : List Ξ±) (h : lβ‚‚ β‰  []) : getLast (l₁ ++ lβ‚‚) (append_ne_nil_of_right_ne_nil l₁ h) = getLast lβ‚‚ h := by induction l₁ with grind theorem getLast_concat' {a : Ξ±} (l : List Ξ±) : getLast (concat l a) (by simp) = a := by simp @[simp] theorem getLast_singleton' (a : Ξ±) : getLast [a] (cons_ne_nil a []) = a := rfl theorem dropLast_append_getLast : βˆ€ {l : List Ξ±} (h : l β‰  []), dropLast l ++ [getLast l h] = l | [], h => absurd rfl h | [_], _ => rfl | a :: b :: l, h => by rw [dropLast_consβ‚‚, cons_append, getLast_cons (cons_ne_nil _ _)] congr exact dropLast_append_getLast (cons_ne_nil b l) theorem getLast_congr {l₁ lβ‚‚ : List Ξ±} (h₁ : l₁ β‰  []) (hβ‚‚ : lβ‚‚ β‰  []) (h₃ : l₁ = lβ‚‚) : getLast l₁ h₁ = getLast lβ‚‚ hβ‚‚ := by subst l₁; rfl theorem getLast_replicate_succ (m : β„•) (a : Ξ±) : (replicate (m + 1) a).getLast (ne_nil_of_length_eq_add_one length_replicate) = a := by simp only [replicate_succ'] exact getLast_append_singleton _ /-! ### getLast? -/ theorem mem_getLast?_eq_getLast : βˆ€ {l : List Ξ±} {x : Ξ±}, x ∈ l.getLast? β†’ βˆƒ h, x = getLast l h | [], x, hx | [a], x, hx | a :: b :: l, x, hx => by grind theorem getLast?_eq_getLast_of_ne_nil : βˆ€ {l : List Ξ±} (h : l β‰  []), l.getLast? = some (l.getLast h) | [], h => (h rfl).elim | [_], _ => rfl | _ :: b :: l, _ => @getLast?_eq_getLast_of_ne_nil (b :: l) (cons_ne_nil _ _) theorem mem_getLast?_cons {x y : Ξ±} : βˆ€ {l : List Ξ±}, x ∈ l.getLast? β†’ x ∈ (y :: l).getLast? | [], _ => by contradiction | _ :: _, h => h theorem dropLast_append_getLast? : βˆ€ {l : List Ξ±}, βˆ€ a ∈ l.getLast?, dropLast l ++ [a] = l | [], a, ha => (Option.not_mem_none a ha).elim | [a], _, rfl => rfl | a :: b :: l, c, hc => by rw [getLast?_cons_cons] at hc rw [dropLast_consβ‚‚, cons_append, dropLast_append_getLast? _ hc] theorem getLastI_eq_getLast? [Inhabited Ξ±] : βˆ€ l : List Ξ±, l.getLastI = l.getLast?.iget | [] => by simp [getLastI] | [_] => rfl | [_, _] => rfl | [_, _, _] => rfl | _ :: _ :: c :: l => by simp [getLastI, getLastI_eq_getLast? (c :: l)] theorem getLast?_append_cons : βˆ€ (l₁ : List Ξ±) (a : Ξ±) (lβ‚‚ : List Ξ±), getLast? (l₁ ++ a :: lβ‚‚) = getLast? (a :: lβ‚‚) | [], _, _ => rfl | [_], _, _ => rfl | b :: c :: l₁, a, lβ‚‚ => by rw [cons_append, cons_append, getLast?_cons_cons, ← cons_append, getLast?_append_cons (c :: l₁)] theorem getLast?_append_of_ne_nil (l₁ : List Ξ±) : βˆ€ {lβ‚‚ : List Ξ±} (_ : lβ‚‚ β‰  []), getLast? (l₁ ++ lβ‚‚) = getLast? lβ‚‚ | [], hlβ‚‚ => by contradiction | b :: lβ‚‚, _ => getLast?_append_cons l₁ b lβ‚‚ theorem mem_getLast?_append_of_mem_getLast? {l₁ lβ‚‚ : List Ξ±} {x : Ξ±} (h : x ∈ lβ‚‚.getLast?) : x ∈ (l₁ ++ lβ‚‚).getLast? := by grind /-! ### head(!?) and tail -/ @[simp] theorem head!_nil [Inhabited Ξ±] : ([] : List Ξ±).head! = default := rfl @[deprecated cons_head_tail (since := "2025-08-15")] theorem head_cons_tail (x : List Ξ±) (h : x β‰  []) : x.head h :: x.tail = x := by simp theorem head_eq_getElem_zero {l : List Ξ±} (hl : l β‰  []) : l.head hl = l[0]'(length_pos_iff.2 hl) := (getElem_zero _).symm theorem head!_eq_head? [Inhabited Ξ±] (l : List Ξ±) : head! l = (head? l).iget := by cases l <;> rfl theorem surjective_head! [Inhabited Ξ±] : Surjective (@head! Ξ± _) := fun x => ⟨[x], rfl⟩ theorem surjective_head? : Surjective (@head? Ξ±) := Option.forall.2 ⟨⟨[], rfl⟩, fun x => ⟨[x], rfl⟩⟩ theorem surjective_tail : Surjective (@tail Ξ±) | [] => ⟨[], rfl⟩ | a :: l => ⟨a :: a :: l, rfl⟩ theorem eq_cons_of_mem_head? {x : Ξ±} : βˆ€ {l : List Ξ±}, x ∈ l.head? β†’ l = x :: tail l | [], h => (Option.not_mem_none _ h).elim | a :: l, h => by simp only [head?, Option.mem_def, Option.some_inj] at h exact h β–Έ rfl @[simp] theorem head!_cons [Inhabited Ξ±] (a : Ξ±) (l : List Ξ±) : head! (a :: l) = a := rfl @[simp] theorem head!_append [Inhabited Ξ±] (t : List Ξ±) {s : List Ξ±} (h : s β‰  []) : head! (s ++ t) = head! s := by induction s Β· contradiction Β· rfl theorem mem_head?_append_of_mem_head? {s t : List Ξ±} {x : Ξ±} (h : x ∈ s.head?) : x ∈ (s ++ t).head? := by grind [Option.mem_def] theorem head?_append_of_ne_nil : βˆ€ (l₁ : List Ξ±) {lβ‚‚ : List Ξ±} (_ : l₁ β‰  []), head? (l₁ ++ lβ‚‚) = head? l₁ | _ :: _, _, _ => rfl theorem tail_append_singleton_of_ne_nil {a : Ξ±} {l : List Ξ±} (h : l β‰  nil) : tail (l ++ [a]) = tail l ++ [a] := by grind theorem cons_head?_tail : βˆ€ {l : List Ξ±} {a : Ξ±}, a ∈ head? l β†’ a :: tail l = l | [], a, h => by contradiction | b :: l, a, h => by have : b = a := by simpa using h simp [this] theorem head!_mem_head? [Inhabited Ξ±] : βˆ€ {l : List Ξ±}, l β‰  [] β†’ head! l ∈ head? l | [], h => by contradiction | _ :: _, _ => rfl theorem cons_head!_tail [Inhabited Ξ±] {l : List Ξ±} (h : l β‰  []) : head! l :: tail l = l := cons_head?_tail (head!_mem_head? h) theorem head!_mem_self [Inhabited Ξ±] {l : List Ξ±} (h : l β‰  nil) : l.head! ∈ l := by have h' : l.head! ∈ l.head! :: l.tail := mem_cons_self rwa [cons_head!_tail h] at h' theorem get_eq_getElem? (l : List Ξ±) (i : Fin l.length) : l.get i = l[i]?.get (by simp) := by simp theorem exists_mem_iff_getElem {l : List Ξ±} {p : Ξ± β†’ Prop} : (βˆƒ x ∈ l, p x) ↔ βˆƒ (i : β„•) (_ : i < l.length), p l[i] := by simp only [mem_iff_getElem] exact ⟨fun ⟨_x, ⟨i, hi, hix⟩, hxp⟩ ↦ ⟨i, hi, hix β–Έ hxp⟩, fun ⟨i, hi, hp⟩ ↦ ⟨_, ⟨i, hi, rfl⟩, hp⟩⟩ theorem exists_mem_iff_get {l : List Ξ±} {p : Ξ± β†’ Prop} : (βˆƒ x ∈ l, p x) ↔ βˆƒ (i : Fin l.length), p (l.get i) := exists_mem_iff_getElem.trans ⟨fun ⟨i, hi, h⟩ ↦ ⟨⟨i, hi⟩, h⟩, fun ⟨i, h⟩ ↦ ⟨i, i.isLt, h⟩⟩ theorem forall_mem_iff_getElem {l : List Ξ±} {p : Ξ± β†’ Prop} : (βˆ€ x ∈ l, p x) ↔ βˆ€ (i : β„•) (_ : i < l.length), p l[i] := by simp [mem_iff_getElem, @forall_swap Ξ±] theorem forall_mem_iff_get {l : List Ξ±} {p : Ξ± β†’ Prop} : (βˆ€ x ∈ l, p x) ↔ βˆ€ (i : Fin l.length), p (l.get i) := forall_mem_iff_getElem.trans ⟨fun h i ↦ h i i.isLt, fun h i hi ↦ h ⟨i, hi⟩⟩ @[simp] theorem get_surjective_iff {l : List Ξ±} : l.get.Surjective ↔ (βˆ€ x, x ∈ l) := forall_congr' fun _ ↦ mem_iff_get.symm @[simp] theorem getElem_fin_surjective_iff {l : List Ξ±} : (fun (n : Fin l.length) ↦ l[n.val]).Surjective ↔ (βˆ€ x, x ∈ l) := get_surjective_iff @[simp] theorem getElem?_surjective_iff {l : List Ξ±} : (fun (n : β„•) ↦ l[n]?).Surjective ↔ (βˆ€ x, x ∈ l) := by refine ⟨fun h x ↦ mem_iff_getElem?.mpr <| h x, fun h x ↦ ?_⟩ cases x with | none => exact ⟨l.length, getElem?_eq_none <| Nat.le_refl _⟩ | some x => exact mem_iff_getElem?.mp <| h x theorem get_tail (l : List Ξ±) (i) (h : i < l.tail.length) (h' : i + 1 < l.length := (by simp only [length_tail] at h; cutsat)) : l.tail.get ⟨i, h⟩ = l.get ⟨i + 1, h'⟩ := by simp /-! ### sublists -/ attribute [refl] List.Sublist.refl theorem Sublist.cons_cons {l₁ lβ‚‚ : List Ξ±} (a : Ξ±) (s : l₁ <+ lβ‚‚) : a :: l₁ <+ a :: lβ‚‚ := Sublist.consβ‚‚ _ s lemma cons_sublist_cons' {a b : Ξ±} : a :: l₁ <+ b :: lβ‚‚ ↔ a :: l₁ <+ lβ‚‚ ∨ a = b ∧ l₁ <+ lβ‚‚ := by grind theorem sublist_cons_of_sublist (a : Ξ±) (h : l₁ <+ lβ‚‚) : l₁ <+ a :: lβ‚‚ := h.cons _ @[simp] lemma sublist_singleton {l : List Ξ±} {a : Ξ±} : l <+ [a] ↔ l = [] ∨ l = [a] := by constructor <;> rintro (_ | _) <;> aesop theorem Sublist.antisymm (s₁ : l₁ <+ lβ‚‚) (sβ‚‚ : lβ‚‚ <+ l₁) : l₁ = lβ‚‚ := s₁.eq_of_length_le sβ‚‚.length_le /-- If the first element of two lists are different, then a sublist relation can be reduced. -/ theorem Sublist.of_cons_of_ne {a b} (h₁ : a β‰  b) (hβ‚‚ : a :: l₁ <+ b :: lβ‚‚) : a :: l₁ <+ lβ‚‚ := match h₁, hβ‚‚ with | _, .cons _ h => h /-! ### indexOf -/ section IndexOf variable [DecidableEq Ξ±] theorem idxOf_cons_eq {a b : Ξ±} (l : List Ξ±) : b = a β†’ idxOf a (b :: l) = 0 | e => by rw [← e]; exact idxOf_cons_self @[simp] theorem idxOf_cons_ne {a b : Ξ±} (l : List Ξ±) : b β‰  a β†’ idxOf a (b :: l) = succ (idxOf a l) | h => by simp only [idxOf_cons, Bool.cond_eq_ite, beq_iff_eq, if_neg h] theorem idxOf_eq_length_iff {a : Ξ±} {l : List Ξ±} : idxOf a l = length l ↔ a βˆ‰ l := by grind @[simp] theorem idxOf_of_notMem {l : List Ξ±} {a : Ξ±} : a βˆ‰ l β†’ idxOf a l = length l := idxOf_eq_length_iff.2 @[deprecated (since := "2025-05-23")] alias idxOf_of_not_mem := idxOf_of_notMem theorem idxOf_append_of_mem {a : Ξ±} (h : a ∈ l₁) : idxOf a (l₁ ++ lβ‚‚) = idxOf a l₁ := by grind theorem idxOf_append_of_notMem {a : Ξ±} (h : a βˆ‰ l₁) : idxOf a (l₁ ++ lβ‚‚) = l₁.length + idxOf a lβ‚‚ := by grind @[deprecated (since := "2025-05-23")] alias idxOf_append_of_not_mem := idxOf_append_of_notMem end IndexOf /-! ### nth element -/ section deprecated theorem getElem?_length (l : List Ξ±) : l[l.length]? = none := getElem?_eq_none (Nat.le_refl _) /-- A version of `getElem_map` that can be used for rewriting. -/ theorem getElem_map_rev (f : Ξ± β†’ Ξ²) {l} {n : Nat} {h : n < l.length} : f l[n] = (map f l)[n]'((l.length_map f).symm β–Έ h) := Eq.symm (getElem_map _) theorem get_length_sub_one {l : List Ξ±} (h : l.length - 1 < l.length) : l.get ⟨l.length - 1, h⟩ = l.getLast (by rintro rfl; exact Nat.lt_irrefl 0 h) := (getLast_eq_getElem _).symm theorem take_one_drop_eq_of_lt_length {l : List Ξ±} {n : β„•} (h : n < l.length) : (l.drop n).take 1 = [l.get ⟨n, h⟩] := by rw [drop_eq_getElem_cons h, take, take] simp theorem ext_getElem?' {l₁ lβ‚‚ : List Ξ±} (h' : βˆ€ n < max l₁.length lβ‚‚.length, l₁[n]? = lβ‚‚[n]?) : l₁ = lβ‚‚ := by apply ext_getElem? grind theorem ext_get_iff {l₁ lβ‚‚ : List Ξ±} : l₁ = lβ‚‚ ↔ l₁.length = lβ‚‚.length ∧ βˆ€ n h₁ hβ‚‚, get l₁ ⟨n, hβ‚βŸ© = get lβ‚‚ ⟨n, hβ‚‚βŸ© := by constructor Β· rintro rfl exact ⟨rfl, fun _ _ _ ↦ rfl⟩ Β· intro ⟨h₁, hβ‚‚βŸ© exact ext_get h₁ hβ‚‚ theorem ext_getElem?_iff' {l₁ lβ‚‚ : List Ξ±} : l₁ = lβ‚‚ ↔ βˆ€ n < max l₁.length lβ‚‚.length, l₁[n]? = lβ‚‚[n]? := ⟨by rintro rfl _ _; rfl, ext_getElem?'⟩ /-- If two lists `l₁` and `lβ‚‚` are the same length and `l₁[n]! = lβ‚‚[n]!` for all `n`, then the lists are equal. -/ theorem ext_getElem! [Inhabited Ξ±] (hl : length l₁ = length lβ‚‚) (h : βˆ€ n : β„•, l₁[n]! = lβ‚‚[n]!) : l₁ = lβ‚‚ := ext_getElem hl fun n h₁ hβ‚‚ ↦ by simpa only [← getElem!_pos] using h n @[simp] theorem getElem_idxOf [DecidableEq Ξ±] {a : Ξ±} : βˆ€ {l : List Ξ±} (h : idxOf a l < l.length), l[idxOf a l] = a | b :: l, h => by by_cases h' : b = a <;> simp [h', getElem_idxOf] -- This is incorrectly named and should be `get_idxOf`; -- this already exists, so will require a deprecation dance. theorem idxOf_get [DecidableEq Ξ±] {a : Ξ±} {l : List Ξ±} (h) : get l ⟨idxOf a l, h⟩ = a := by simp @[simp] theorem getElem?_idxOf [DecidableEq Ξ±] {a : Ξ±} {l : List Ξ±} (h : a ∈ l) : l[idxOf a l]? = some a := by rw [getElem?_eq_getElem (idxOf_lt_length_iff.2 h), getElem_idxOf] theorem idxOf_inj [DecidableEq Ξ±] {l : List Ξ±} {x y : Ξ±} (hx : x ∈ l) (hy : y ∈ l) : idxOf x l = idxOf y l ↔ x = y := ⟨fun h => by have x_eq_y : get l ⟨idxOf x l, idxOf_lt_length_iff.2 hx⟩ = get l ⟨idxOf y l, idxOf_lt_length_iff.2 hy⟩ := by simp only [h] simp only [idxOf_get] at x_eq_y; exact x_eq_y, fun h => by subst h; rfl⟩ theorem get_reverse' (l : List Ξ±) (n) (hn') : l.reverse.get n = l.get ⟨l.length - 1 - n, hn'⟩ := by simp theorem eq_cons_of_length_one {l : List Ξ±} (h : l.length = 1) : l = [l.get ⟨0, by omega⟩] := by refine ext_get (by convert h) (by grind) end deprecated theorem getElem_set_of_ne {l : List Ξ±} {i j : β„•} (h : i β‰  j) (a : Ξ±) (hj : j < (l.set i a).length) : (l.set i a)[j] = l[j]'(by simpa using hj) := by simp [h] /-! ### map -/ -- `List.map_const` (the version with `Function.const` instead of a lambda) is already tagged -- `simp` in Core -- TODO: Upstream the tagging to Core? attribute [simp] map_const' theorem flatMap_pure_eq_map (f : Ξ± β†’ Ξ²) (l : List Ξ±) : l.flatMap (pure ∘ f) = map f l := .symm <| map_eq_flatMap .. theorem flatMap_congr {l : List Ξ±} {f g : Ξ± β†’ List Ξ²} (h : βˆ€ x ∈ l, f x = g x) : l.flatMap f = l.flatMap g := (congr_arg List.flatten <| map_congr_left h :) theorem infix_flatMap_of_mem {a : Ξ±} {as : List Ξ±} (h : a ∈ as) (f : Ξ± β†’ List Ξ±) : f a <:+: as.flatMap f := infix_of_mem_flatten (mem_map_of_mem h) @[simp] theorem map_eq_map {Ξ± Ξ²} (f : Ξ± β†’ Ξ²) (l : List Ξ±) : f <$> l = map f l := rfl /-- A single `List.map` of a composition of functions is equal to composing a `List.map` with another `List.map`, fully applied. This is the reverse direction of `List.map_map`. -/ theorem comp_map (h : Ξ² β†’ Ξ³) (g : Ξ± β†’ Ξ²) (l : List Ξ±) : map (h ∘ g) l = map h (map g l) := map_map.symm /-- Composing a `List.map` with another `List.map` is equal to a single `List.map` of composed functions. -/ @[simp] theorem map_comp_map (g : Ξ² β†’ Ξ³) (f : Ξ± β†’ Ξ²) : map g ∘ map f = map (g ∘ f) := by ext l; rw [comp_map, Function.comp_apply] section map_bijectivity theorem _root_.Function.LeftInverse.list_map {f : Ξ± β†’ Ξ²} {g : Ξ² β†’ Ξ±} (h : LeftInverse f g) : LeftInverse (map f) (map g) | [] => by simp_rw [map_nil] | x :: xs => by simp_rw [map_cons, h x, h.list_map xs] nonrec theorem _root_.Function.RightInverse.list_map {f : Ξ± β†’ Ξ²} {g : Ξ² β†’ Ξ±} (h : RightInverse f g) : RightInverse (map f) (map g) := h.list_map nonrec theorem _root_.Function.Involutive.list_map {f : Ξ± β†’ Ξ±} (h : Involutive f) : Involutive (map f) := Function.LeftInverse.list_map h @[simp] theorem map_leftInverse_iff {f : Ξ± β†’ Ξ²} {g : Ξ² β†’ Ξ±} : LeftInverse (map f) (map g) ↔ LeftInverse f g := ⟨fun h x => by injection h [x], (Β·.list_map)⟩ @[simp] theorem map_rightInverse_iff {f : Ξ± β†’ Ξ²} {g : Ξ² β†’ Ξ±} : RightInverse (map f) (map g) ↔ RightInverse f g := map_leftInverse_iff @[simp] theorem map_involutive_iff {f : Ξ± β†’ Ξ±} : Involutive (map f) ↔ Involutive f := map_leftInverse_iff theorem _root_.Function.Injective.list_map {f : Ξ± β†’ Ξ²} (h : Injective f) : Injective (map f) | [], [], _ => rfl | x :: xs, y :: ys, hxy => by injection hxy with hxy hxys rw [h hxy, h.list_map hxys] @[simp] theorem map_injective_iff {f : Ξ± β†’ Ξ²} : Injective (map f) ↔ Injective f := by refine ⟨fun h x y hxy => ?_, (Β·.list_map)⟩ suffices [x] = [y] by simpa using this apply h simp [hxy] theorem _root_.Function.Surjective.list_map {f : Ξ± β†’ Ξ²} (h : Surjective f) : Surjective (map f) := let ⟨_, h⟩ := h.hasRightInverse; h.list_map.surjective @[simp] theorem map_surjective_iff {f : Ξ± β†’ Ξ²} : Surjective (map f) ↔ Surjective f := by refine ⟨fun h x => ?_, (Β·.list_map)⟩ let ⟨[y], hxy⟩ := h [x] exact ⟨_, List.singleton_injective hxy⟩ theorem _root_.Function.Bijective.list_map {f : Ξ± β†’ Ξ²} (h : Bijective f) : Bijective (map f) := ⟨h.1.list_map, h.2.list_map⟩ @[simp] theorem map_bijective_iff {f : Ξ± β†’ Ξ²} : Bijective (map f) ↔ Bijective f := by simp_rw [Function.Bijective, map_injective_iff, map_surjective_iff] end map_bijectivity theorem eq_of_mem_map_const {b₁ bβ‚‚ : Ξ²} {l : List Ξ±} (h : b₁ ∈ map (const Ξ± bβ‚‚) l) : b₁ = bβ‚‚ := by rw [map_const] at h; exact eq_of_mem_replicate h /-- `eq_nil_or_concat` in simp normal form -/ lemma eq_nil_or_concat' (l : List Ξ±) : l = [] ∨ βˆƒ L b, l = L ++ [b] := by simpa using l.eq_nil_or_concat /-! ### foldl, foldr -/ theorem foldl_ext (f g : Ξ± β†’ Ξ² β†’ Ξ±) (a : Ξ±) {l : List Ξ²} (H : βˆ€ a : Ξ±, βˆ€ b ∈ l, f a b = g a b) : foldl f a l = foldl g a l := by induction l generalizing a with | nil => rfl | cons hd tl ih => unfold foldl rw [ih _ fun a b bin => H a b <| mem_cons_of_mem _ bin, H a hd mem_cons_self] theorem foldr_ext (f g : Ξ± β†’ Ξ² β†’ Ξ²) (b : Ξ²) {l : List Ξ±} (H : βˆ€ a ∈ l, βˆ€ b : Ξ², f a b = g a b) : foldr f b l = foldr g b l := by induction l with | nil => rfl | cons hd tl ih => ?_ simp only [mem_cons, or_imp, forall_and, forall_eq] at H simp only [foldr, ih H.2, H.1] theorem foldl_concat (f : Ξ² β†’ Ξ± β†’ Ξ²) (b : Ξ²) (x : Ξ±) (xs : List Ξ±) : List.foldl f b (xs ++ [x]) = f (List.foldl f b xs) x := by simp only [List.foldl_append, List.foldl] theorem foldr_concat (f : Ξ± β†’ Ξ² β†’ Ξ²) (b : Ξ²) (x : Ξ±) (xs : List Ξ±) : List.foldr f b (xs ++ [x]) = (List.foldr f (f x b) xs) := by simp only [List.foldr_append, List.foldr] theorem foldl_fixed' {f : Ξ± β†’ Ξ² β†’ Ξ±} {a : Ξ±} (hf : βˆ€ b, f a b = a) : βˆ€ l : List Ξ², foldl f a l = a | [] => rfl | b :: l => by rw [foldl_cons, hf b, foldl_fixed' hf l] theorem foldr_fixed' {f : Ξ± β†’ Ξ² β†’ Ξ²} {b : Ξ²} (hf : βˆ€ a, f a b = b) : βˆ€ l : List Ξ±, foldr f b l = b | [] => rfl | a :: l => by rw [foldr_cons, foldr_fixed' hf l, hf a] @[simp] theorem foldl_fixed {a : Ξ±} : βˆ€ l : List Ξ², foldl (fun a _ => a) a l = a := foldl_fixed' fun _ => rfl @[simp] theorem foldr_fixed {b : Ξ²} : βˆ€ l : List Ξ±, foldr (fun _ b => b) b l = b := foldr_fixed' fun _ => rfl theorem reverse_foldl {l : List Ξ±} : reverse (foldl (fun t h => h :: t) [] l) = l := by simp theorem foldl_homβ‚‚ (l : List ΞΉ) (f : Ξ± β†’ Ξ² β†’ Ξ³) (op₁ : Ξ± β†’ ΞΉ β†’ Ξ±) (opβ‚‚ : Ξ² β†’ ΞΉ β†’ Ξ²) (op₃ : Ξ³ β†’ ΞΉ β†’ Ξ³) (a : Ξ±) (b : Ξ²) (h : βˆ€ a b i, f (op₁ a i) (opβ‚‚ b i) = op₃ (f a b) i) : foldl op₃ (f a b) l = f (foldl op₁ a l) (foldl opβ‚‚ b l) := Eq.symm <| by revert a b induction l <;> intros <;> [rfl; simp only [*, foldl]] theorem foldr_homβ‚‚ (l : List ΞΉ) (f : Ξ± β†’ Ξ² β†’ Ξ³) (op₁ : ΞΉ β†’ Ξ± β†’ Ξ±) (opβ‚‚ : ΞΉ β†’ Ξ² β†’ Ξ²) (op₃ : ΞΉ β†’ Ξ³ β†’ Ξ³) (a : Ξ±) (b : Ξ²) (h : βˆ€ a b i, f (op₁ i a) (opβ‚‚ i b) = op₃ i (f a b)) : foldr op₃ (f a b) l = f (foldr op₁ a l) (foldr opβ‚‚ b l) := by revert a induction l <;> intros <;> [rfl; simp only [*, foldr]] theorem injective_foldl_comp {l : List (Ξ± β†’ Ξ±)} {f : Ξ± β†’ Ξ±} (hl : βˆ€ f ∈ l, Function.Injective f) (hf : Function.Injective f) : Function.Injective (@List.foldl (Ξ± β†’ Ξ±) (Ξ± β†’ Ξ±) Function.comp f l) := by induction l generalizing f with | nil => exact hf | cons lh lt l_ih => apply l_ih fun _ h => hl _ (List.mem_cons_of_mem _ h) apply Function.Injective.comp hf apply hl _ mem_cons_self /-- Consider two lists `l₁` and `lβ‚‚` with designated elements `a₁` and `aβ‚‚` somewhere in them: `l₁ = x₁ ++ [a₁] ++ z₁` and `lβ‚‚ = xβ‚‚ ++ [aβ‚‚] ++ zβ‚‚`. Assume the designated element `aβ‚‚` is present in neither `x₁` nor `z₁`. We conclude that the lists are equal (`l₁ = lβ‚‚`) if and only if their respective parts are equal (`x₁ = xβ‚‚ ∧ a₁ = aβ‚‚ ∧ z₁ = zβ‚‚`). -/ lemma append_cons_inj_of_notMem {x₁ xβ‚‚ z₁ zβ‚‚ : List Ξ±} {a₁ aβ‚‚ : Ξ±} (notin_x : aβ‚‚ βˆ‰ x₁) (notin_z : aβ‚‚ βˆ‰ z₁) : x₁ ++ a₁ :: z₁ = xβ‚‚ ++ aβ‚‚ :: zβ‚‚ ↔ x₁ = xβ‚‚ ∧ a₁ = aβ‚‚ ∧ z₁ = zβ‚‚ := by constructor Β· simp only [append_eq_append_iff, cons_eq_append_iff, cons_eq_cons] rintro (⟨c, rfl, ⟨rfl, rfl, rfl⟩ | ⟨d, rfl, rfl⟩⟩ | ⟨c, rfl, ⟨rfl, rfl, rfl⟩ | ⟨d, rfl, rfl⟩⟩) <;> simp_all Β· rintro ⟨rfl, rfl, rfl⟩ rfl @[deprecated (since := "2025-05-23")] alias append_cons_inj_of_not_mem := append_cons_inj_of_notMem section FoldlEqFoldr -- foldl and foldr coincide when f is commutative and associative variable {f : Ξ± β†’ Ξ± β†’ Ξ±} theorem foldl1_eq_foldr1 [hassoc : Std.Associative f] : βˆ€ a b l, foldl f a (l ++ [b]) = foldr f b (a :: l) | _, _, nil => rfl | a, b, c :: l => by simp only [cons_append, foldl_cons, foldr_cons, foldl1_eq_foldr1 _ _ l] rw [hassoc.assoc] theorem foldl_eq_of_comm_of_assoc [hcomm : Std.Commutative f] [hassoc : Std.Associative f] : βˆ€ a b l, foldl f a (b :: l) = f b (foldl f a l) | a, b, nil => hcomm.comm a b | a, b, c :: l => by simp only [foldl_cons] have : RightCommutative f := inferInstance rw [← foldl_eq_of_comm_of_assoc .., this.right_comm, foldl_cons] theorem foldl_eq_foldr [Std.Commutative f] [Std.Associative f] : βˆ€ a l, foldl f a l = foldr f a l | _, nil => rfl | a, b :: l => by simp only [foldr_cons, foldl_eq_of_comm_of_assoc] rw [foldl_eq_foldr a l] end FoldlEqFoldr section FoldlEqFoldr' variable {f : Ξ± β†’ Ξ² β†’ Ξ±} variable (hf : βˆ€ a b c, f (f a b) c = f (f a c) b) include hf theorem foldl_eq_of_comm' : βˆ€ a b l, foldl f a (b :: l) = f (foldl f a l) b | _, _, [] => rfl | a, b, c :: l => by rw [foldl, foldl, foldl, ← foldl_eq_of_comm' .., foldl, hf] theorem foldl_eq_foldr' : βˆ€ a l, foldl f a l = foldr (flip f) a l | _, [] => rfl | a, b :: l => by rw [foldl_eq_of_comm' hf, foldr, foldl_eq_foldr' ..]; rfl end FoldlEqFoldr' section FoldlEqFoldr' variable {f : Ξ± β†’ Ξ² β†’ Ξ²} theorem foldr_eq_of_comm' (hf : βˆ€ a b c, f a (f b c) = f b (f a c)) : βˆ€ a b l, foldr f a (b :: l) = foldr f (f b a) l | _, _, [] => rfl | a, b, c :: l => by rw [foldr, foldr, foldr, hf, ← foldr_eq_of_comm' hf ..]; rfl end FoldlEqFoldr' section variable {op : Ξ± β†’ Ξ± β†’ Ξ±} [ha : Std.Associative op] /-- Notation for `op a b`. -/ local notation a " ⋆ " b => op a b -- Setting `priority := high` means that Lean will prefer this notation to the identical one -- for `Seq.seq` /-- Notation for `foldl op a l`. -/ local notation l " <*> " a => foldl op a l theorem foldl_op_eq_op_foldr_assoc : βˆ€ {l : List Ξ±} {a₁ aβ‚‚}, ((l <*> a₁) ⋆ aβ‚‚) = a₁ ⋆ l.foldr (Β· ⋆ Β·) aβ‚‚ | [], _, _ => rfl | a :: l, a₁, aβ‚‚ => by simp only [foldl_cons, foldr_cons, foldl_assoc, ha.assoc]; rw [foldl_op_eq_op_foldr_assoc] variable [hc : Std.Commutative op] theorem foldl_assoc_comm_cons {l : List Ξ±} {a₁ aβ‚‚} : ((a₁ :: l) <*> aβ‚‚) = a₁ ⋆ l <*> aβ‚‚ := by rw [foldl_cons, hc.comm, foldl_assoc] end /-! ### foldlM, foldrM, mapM -/ section FoldlMFoldrM variable {m : Type v β†’ Type w} [Monad m] variable [LawfulMonad m] theorem foldrM_eq_foldr (f : Ξ± β†’ Ξ² β†’ m Ξ²) (b l) : foldrM f b l = foldr (fun a mb => mb >>= f a) (pure b) l := by induction l <;> simp [*] theorem foldlM_eq_foldl (f : Ξ² β†’ Ξ± β†’ m Ξ²) (b l) : List.foldlM f b l = foldl (fun mb a => mb >>= fun b => f b a) (pure b) l := by suffices h : βˆ€ mb : m Ξ², (mb >>= fun b => List.foldlM f b l) = foldl (fun mb a => mb >>= fun b => f b a) mb l by simp [← h (pure b)] induction l with | nil => simp | cons _ _ l_ih => intro; simp only [List.foldlM, foldl, ← l_ih, functor_norm] end FoldlMFoldrM /-! ### filter -/ theorem length_eq_length_filter_add {l : List (Ξ±)} (f : Ξ± β†’ Bool) : l.length = (l.filter f).length + (l.filter (!f Β·)).length := by simp_rw [← List.countP_eq_length_filter, l.length_eq_countP_add_countP f, Bool.not_eq_true, Bool.decide_eq_false] /-! ### filterMap -/ theorem filterMap_eq_flatMap_toList (f : Ξ± β†’ Option Ξ²) (l : List Ξ±) : l.filterMap f = l.flatMap fun a ↦ (f a).toList := by induction l with | nil => ?_ | cons a l ih => ?_ <;> simp [filterMap_cons] rcases f a <;> simp [ih] theorem filterMap_congr {f g : Ξ± β†’ Option Ξ²} {l : List Ξ±} (h : βˆ€ x ∈ l, f x = g x) : l.filterMap f = l.filterMap g := by induction l <;> simp_all [filterMap_cons] theorem filterMap_eq_map_iff_forall_eq_some {f : Ξ± β†’ Option Ξ²} {g : Ξ± β†’ Ξ²} {l : List Ξ±} : l.filterMap f = l.map g ↔ βˆ€ x ∈ l, f x = some (g x) where mp := by induction l with | nil => simp | cons a l ih => ?_ rcases ha : f a with - | b Β· intro h have : (filterMap f l).length = l.length + 1 := by grind grind Β· simp +contextual [ha, ih] mpr h := Eq.trans (filterMap_congr <| by simpa) (congr_fun filterMap_eq_map _) /-! ### filter -/ section Filter variable {p : Ξ± β†’ Bool} theorem filter_singleton {a : Ξ±} : [a].filter p = bif p a then [a] else [] := rfl theorem filter_eq_foldr (p : Ξ± β†’ Bool) (l : List Ξ±) : filter p l = foldr (fun a out => bif p a then a :: out else out) [] l := by induction l <;> simp [*, filter]; rfl #adaptation_note /-- nightly-2024-07-27 This has to be temporarily renamed to avoid an unintentional collision. The prime should be removed at nightly-2024-07-27. -/ @[simp] theorem filter_subset' (l : List Ξ±) : filter p l βŠ† l := filter_sublist.subset theorem of_mem_filter {a : Ξ±} {l} (h : a ∈ filter p l) : p a := (mem_filter.1 h).2 theorem mem_of_mem_filter {a : Ξ±} {l} (h : a ∈ filter p l) : a ∈ l := filter_subset' l h theorem mem_filter_of_mem {a : Ξ±} {l} (h₁ : a ∈ l) (hβ‚‚ : p a) : a ∈ filter p l := mem_filter.2 ⟨h₁, hβ‚‚βŸ© variable (p) theorem monotone_filter_right (l : List Ξ±) ⦃p q : Ξ± β†’ Bool⦄ (h : βˆ€ a, p a β†’ q a) : l.filter p <+ l.filter q := by induction l with grind lemma map_filter {f : Ξ± β†’ Ξ²} (hf : Injective f) (l : List Ξ±) [DecidablePred fun b => βˆƒ a, p a ∧ f a = b] : (l.filter p).map f = (l.map f).filter fun b => βˆƒ a, p a ∧ f a = b := by simp [comp_def, filter_map, hf.eq_iff] lemma filter_attach' (l : List Ξ±) (p : {a // a ∈ l} β†’ Bool) [DecidableEq Ξ±] : l.attach.filter p = (l.filter fun x => βˆƒ h, p ⟨x, h⟩).attach.map (Subtype.map id fun _ => mem_of_mem_filter) := by classical refine map_injective_iff.2 Subtype.coe_injective ?_ simp [comp_def, map_filter _ Subtype.coe_injective] lemma filter_attach (l : List Ξ±) (p : Ξ± β†’ Bool) : (l.attach.filter fun x => p x : List {x // x ∈ l}) = (l.filter p).attach.map (Subtype.map id fun _ => mem_of_mem_filter) := map_injective_iff.2 Subtype.coe_injective <| by simp_rw [map_map, comp_def, Subtype.map, id, ← Function.comp_apply (g := Subtype.val), ← filter_map, attach_map_subtype_val] lemma filter_comm (q) (l : List Ξ±) : filter p (filter q l) = filter q (filter p l) := by simp [Bool.and_comm] @[simp] theorem filter_true (l : List Ξ±) : filter (fun _ => true) l = l := by induction l <;> simp [*, filter] @[simp] theorem filter_false (l : List Ξ±) : filter (fun _ => false) l = [] := by induction l <;> simp [*, filter] end Filter /-! ### eraseP -/ section eraseP variable {p : Ξ± β†’ Bool} -- Cannot be @[simp] because `a` cannot be inferred by `simp`. theorem length_eraseP_add_one {l : List Ξ±} {a} (al : a ∈ l) (pa : p a) : (l.eraseP p).length + 1 = l.length := by grind end eraseP /-! ### erase -/ section Erase variable [DecidableEq Ξ±] -- @[simp] -- removed because LHS is not in simp normal form theorem length_erase_add_one {a : Ξ±} {l : List Ξ±} (h : a ∈ l) : (l.erase a).length + 1 = l.length := by rw [erase_eq_eraseP, length_eraseP_add_one h (decide_eq_true rfl)] theorem map_erase [DecidableEq Ξ²] {f : Ξ± β†’ Ξ²} (finj : Injective f) {a : Ξ±} (l : List Ξ±) : map f (l.erase a) = (map f l).erase (f a) := by have this : (a == Β·) = (f a == f Β·) := by ext b; simp [finj.eq_iff] rw [erase_eq_eraseP, erase_eq_eraseP, eraseP_map, this]; rfl theorem map_foldl_erase [DecidableEq Ξ²] {f : Ξ± β†’ Ξ²} (finj : Injective f) {l₁ lβ‚‚ : List Ξ±} : map f (foldl List.erase l₁ lβ‚‚) = foldl (fun l a => l.erase (f a)) (map f l₁) lβ‚‚ := by induction lβ‚‚ generalizing l₁ <;> [rfl; simp only [foldl_cons, map_erase finj, *]] theorem erase_getElem [DecidableEq ΞΉ] {l : List ΞΉ} {i : β„•} (hi : i < l.length) : Perm (l.erase l[i]) (l.eraseIdx i) := by induction l generalizing i with | nil => simp | cons a l IH => cases i with grind theorem length_eraseIdx_add_one {l : List ΞΉ} {i : β„•} (h : i < l.length) : (l.eraseIdx i).length + 1 = l.length := by grind end Erase /-! ### diff -/ section Diff variable [DecidableEq Ξ±] @[simp] theorem map_diff [DecidableEq Ξ²] {f : Ξ± β†’ Ξ²} (finj : Injective f) {l₁ lβ‚‚ : List Ξ±} : map f (l₁.diff lβ‚‚) = (map f l₁).diff (map f lβ‚‚) := by simp only [diff_eq_foldl, foldl_map, map_foldl_erase finj] end Diff section Choose variable (p : Ξ± β†’ Prop) [DecidablePred p] (l : List Ξ±) theorem choose_spec (hp : βˆƒ a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) := (chooseX p l hp).property theorem choose_mem (hp : βˆƒ a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1 theorem choose_property (hp : βˆƒ a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2 end Choose /-! ### Forall -/ section Forall variable {p q : Ξ± β†’ Prop} {l : List Ξ±} @[simp] theorem forall_cons (p : Ξ± β†’ Prop) (x : Ξ±) : βˆ€ l : List Ξ±, Forall p (x :: l) ↔ p x ∧ Forall p l | [] => (and_iff_left_of_imp fun _ ↦ trivial).symm | _ :: _ => Iff.rfl @[simp] theorem forall_append {p : Ξ± β†’ Prop} : βˆ€ {xs ys : List Ξ±}, Forall p (xs ++ ys) ↔ Forall p xs ∧ Forall p ys | [] => by simp | _ :: _ => by simp [forall_append, and_assoc] theorem forall_iff_forall_mem : βˆ€ {l : List Ξ±}, Forall p l ↔ βˆ€ x ∈ l, p x | [] => (iff_true_intro <| forall_mem_nil _).symm | x :: l => by rw [forall_mem_cons, forall_cons, forall_iff_forall_mem] theorem Forall.imp (h : βˆ€ x, p x β†’ q x) : βˆ€ {l : List Ξ±}, Forall p l β†’ Forall q l | [] => id | x :: l => by simp only [forall_cons, and_imp] rw [← and_imp] exact And.imp (h x) (Forall.imp h) @[simp] theorem forall_map_iff {p : Ξ² β†’ Prop} (f : Ξ± β†’ Ξ²) : Forall p (l.map f) ↔ Forall (p ∘ f) l := by induction l <;> simp [*] instance (p : Ξ± β†’ Prop) [DecidablePred p] : DecidablePred (Forall p) := fun _ => decidable_of_iff' _ forall_iff_forall_mem end Forall /-! ### Miscellaneous lemmas -/ theorem get_attach (l : List Ξ±) (i) : (l.attach.get i).1 = l.get ⟨i, length_attach (l := l) β–Έ i.2⟩ := by simp section Disjoint /-- The images of disjoint lists under a partially defined map are disjoint -/ theorem disjoint_pmap {p : Ξ± β†’ Prop} {f : βˆ€ a : Ξ±, p a β†’ Ξ²} {s t : List Ξ±} (hs : βˆ€ a ∈ s, p a) (ht : βˆ€ a ∈ t, p a) (hf : βˆ€ (a a' : Ξ±) (ha : p a) (ha' : p a'), f a ha = f a' ha' β†’ a = a') (h : Disjoint s t) : Disjoint (s.pmap f hs) (t.pmap f ht) := by simp only [Disjoint, mem_pmap] rintro b ⟨a, ha, rfl⟩ ⟨a', ha', ha''⟩ apply h ha rwa [hf a a' (hs a ha) (ht a' ha') ha''.symm] /-- The images of disjoint lists under an injective map are disjoint -/ theorem disjoint_map {f : Ξ± β†’ Ξ²} {s t : List Ξ±} (hf : Function.Injective f) (h : Disjoint s t) : Disjoint (s.map f) (t.map f) := by rw [← pmap_eq_map (fun _ _ ↦ trivial), ← pmap_eq_map (fun _ _ ↦ trivial)] exact disjoint_pmap _ _ (fun _ _ _ _ h' ↦ hf h') h alias Disjoint.map := disjoint_map theorem Disjoint.of_map {f : Ξ± β†’ Ξ²} {s t : List Ξ±} (h : Disjoint (s.map f) (t.map f)) : Disjoint s t := fun _a has hat ↦ h (mem_map_of_mem has) (mem_map_of_mem hat) theorem Disjoint.map_iff {f : Ξ± β†’ Ξ²} {s t : List Ξ±} (hf : Function.Injective f) : Disjoint (s.map f) (t.map f) ↔ Disjoint s t := ⟨fun h ↦ h.of_map, fun h ↦ h.map hf⟩ theorem Perm.disjoint_left {l₁ lβ‚‚ l : List Ξ±} (p : List.Perm l₁ lβ‚‚) : Disjoint l₁ l ↔ Disjoint lβ‚‚ l := by simp_rw [List.disjoint_left, p.mem_iff] theorem Perm.disjoint_right {l₁ lβ‚‚ l : List Ξ±} (p : List.Perm l₁ lβ‚‚) : Disjoint l l₁ ↔ Disjoint l lβ‚‚ := by simp_rw [List.disjoint_right, p.mem_iff] @[simp] theorem disjoint_reverse_left {l₁ lβ‚‚ : List Ξ±} : Disjoint l₁.reverse lβ‚‚ ↔ Disjoint l₁ lβ‚‚ := reverse_perm _ |>.disjoint_left @[simp] theorem disjoint_reverse_right {l₁ lβ‚‚ : List Ξ±} : Disjoint l₁ lβ‚‚.reverse ↔ Disjoint l₁ lβ‚‚ := reverse_perm _ |>.disjoint_right end Disjoint section lookup variable [BEq Ξ±] [LawfulBEq Ξ±] lemma lookup_graph (f : Ξ± β†’ Ξ²) {a : Ξ±} {as : List Ξ±} (h : a ∈ as) : lookup a (as.map fun x => (x, f x)) = some (f a) := by induction as with grind end lookup section range' @[simp] lemma range'_0 (a b : β„•) : range' a b 0 = replicate b a := by induction b with | zero => simp | succ b ih => simp [range'_succ, ih, replicate_succ] lemma left_le_of_mem_range' {a b s x : β„•} (hx : x ∈ List.range' a b s) : a ≀ x := by obtain ⟨i, _, rfl⟩ := List.mem_range'.mp hx exact le_add_right a (s * i) end range' end List
.lake/packages/mathlib/Mathlib/Data/List/Shortlex.lean
import Mathlib.Data.List.Lex import Mathlib.Tactic.Linarith import Mathlib.Order.RelClasses /-! # Shortlex ordering of lists. Given a relation `r` on `Ξ±`, the shortlex order on `List Ξ±` is defined by `L < M` iff * `L.length < M.length` * `L.length = M.length` and `L < M` under the lexicographic ordering over `r` on lists ## Main results We show that if `r` is well-founded, so too is the shortlex order over `r` ## See also Related files are: * `Mathlib/Data/List/Lex.lean`: Lexicographic order on `List Ξ±`. * `Mathlib/Data/DFinsupp/WellFounded.lean`: Well-foundedness of lexicographic orders on `DFinsupp` and `Pi`. -/ /-! ### shortlex ordering -/ namespace List /-- Given a relation `r` on `Ξ±`, the shortlex order on `List Ξ±`, for which `[a0, ..., an] < [b0, ..., b_k]` if `n < k` or `n = k` and `[a0, ..., an] < [b0, ..., bk]` under the lexicographic order induced by `r`. -/ def Shortlex {Ξ± : Type*} (r : Ξ± β†’ Ξ± β†’ Prop) : List Ξ± β†’ List Ξ± β†’ Prop := InvImage (Prod.Lex (Β· < Β·) (List.Lex r)) fun a ↦ (a.length, a) variable {Ξ± : Type*} {r : Ξ± β†’ Ξ± β†’ Prop} /-- If a list `s` is shorter than a list `t`, then `s` is smaller than `t` under any shortlex order. -/ theorem Shortlex.of_length_lt {s t : List Ξ±} (h : s.length < t.length) : Shortlex r s t := Prod.Lex.left _ _ h /-- If two lists `s` and `t` have the same length, `s` is smaller than `t` under the shortlex order over a relation `r` when `s` is smaller than `t` under the lexicographic order over `r` -/ theorem Shortlex.of_lex {s t : List Ξ±} (len_eq : s.length = t.length) (h_lex : List.Lex r s t) : Shortlex r s t := by apply Prod.lex_def.mpr right exact ⟨len_eq, h_lex⟩ theorem shortlex_def {s t : List Ξ±} : Shortlex r s t ↔ s.length < t.length ∨ s.length = t.length ∧ Lex r s t := Prod.lex_def /-- If two lists `s` and `t` have the same length, `s` is smaller than `t` under the shortlex order over a relation `r` exactly when `s` is smaller than `t` under the lexicographic order over `r`. -/ theorem shortlex_iff_lex {s t : List Ξ±} (h : s.length = t.length) : Shortlex r s t ↔ List.Lex r s t := by simp [shortlex_def, h] theorem shortlex_cons_iff [IsIrrefl Ξ± r] {a : Ξ±} {s t : List Ξ±} : Shortlex r (a :: s) (a :: t) ↔ Shortlex r s t := by simp only [shortlex_def, length_cons, add_lt_add_iff_right, add_left_inj, List.lex_cons_iff] alias ⟨Shortlex.of_cons, Shortlex.cons⟩ := shortlex_cons_iff @[simp] theorem not_shortlex_nil_right {s : List Ξ±} : Β¬ Shortlex r s [] := by rw [shortlex_def] rintro (h1 | h2) Β· simp only [List.length_nil, not_lt_zero'] at h1 Β· exact List.not_lex_nil h2.2 theorem shortlex_nil_or_eq_nil : βˆ€ s : List Ξ±, Shortlex r [] s ∨ s = [] | [] => .inr rfl | _ :: tail => .inl <| .of_length_lt tail.length.succ_pos @[simp] theorem shortlex_singleton_iff (a b : Ξ±) : Shortlex r [a] [b] ↔ r a b := by simp only [shortlex_def, length_singleton, lt_self_iff_false, lex_singleton_iff, true_and, false_or] namespace Shortlex instance isTrichotomous [IsTrichotomous Ξ± r] : IsTrichotomous (List Ξ±) (Shortlex r) := ⟨(InvImage.isTrichotomous (by simp [Function.Injective])).trichotomous⟩ instance isAsymm [IsAsymm Ξ± r] : IsAsymm (List Ξ±) (Shortlex r) := inferInstanceAs <| IsAsymm (List Ξ±) (InvImage _ _) theorem append_right {s₁ sβ‚‚ : List Ξ±} (t : List Ξ±) (h : Shortlex r s₁ sβ‚‚) : Shortlex r s₁ (sβ‚‚ ++ t) := by rcases shortlex_def.mp h with h1 | h2 Β· apply of_length_lt rw [List.length_append] cutsat cases t with | nil => rw [List.append_nil] exact h | cons head tail => apply of_length_lt rw [List.length_append, List.length_cons] cutsat theorem append_left {t₁ tβ‚‚ : List Ξ±} (h : Shortlex r t₁ tβ‚‚) (s : List Ξ±) : Shortlex r (s ++ t₁) (s ++ tβ‚‚) := by rcases shortlex_def.mp h with h1 | h2 Β· apply of_length_lt rw [List.length_append, List.length_append] cutsat cases s with | nil => rw [List.nil_append, List.nil_append] exact h | cons head tail => apply of_lex Β· simp only [List.cons_append, List.length_cons, List.length_append, add_left_inj, add_right_inj] exact h2.1 exact List.Lex.append_left r h2.2 (head :: tail) section WellFounded variable {h : WellFounded r} private theorem _root_.Acc.shortlex {a : Ξ±} {b : List Ξ±} (aca : Acc r a) (acb : Acc (Shortlex r) b) (ih : βˆ€ s : List Ξ±, s.length < (a :: b).length β†’ Acc (Shortlex r) s) : Acc (Shortlex r) (a :: b) := by induction aca generalizing b with | intro xa _ iha => induction acb with | intro xb _ ihb => refine Acc.intro (xa :: xb) fun p lt => ?_ rcases shortlex_def.mp lt with h1 | ⟨h2len, h2lex⟩ Β· exact ih _ h1 Β· cases h2lex with | nil => simp at h2len | @cons x xs _ h => simp only [length_cons, add_left_inj] at h2len refine ihb _ (of_lex h2len h) fun l hl => ?_ apply ih rw [List.length_cons, ← h2len] exact hl | @rel x xs _ _ h => simp only [List.length_cons, add_left_inj] at h2len refine iha _ h (ih xs (by rw [h2len]; simp)) fun l hl => ?_ apply ih rw [List.length_cons, ← h2len] exact hl theorem wf (h : WellFounded r) : WellFounded (Shortlex r) := .intro fun a => by induction len_a : a.length using Nat.caseStrongRecOn generalizing a with | zero => rw [List.length_eq_zero_iff] at len_a rw [len_a] exact Acc.intro _ <| fun _ ylt => (not_shortlex_nil_right ylt).elim | ind n ih => obtain ⟨head, tail, rfl⟩ := List.exists_of_length_succ a len_a rw [List.length_cons, add_left_inj] at len_a apply Acc.shortlex (WellFounded.apply h head) (ih n le_rfl tail len_a) intro l ll apply ih l.length _ _ rfl rw [← len_a] exact Nat.le_of_lt_succ ll end WellFounded end Shortlex end List
.lake/packages/mathlib/Mathlib/Data/List/Sort.lean
import Batteries.Data.List.Pairwise import Batteries.Data.List.Perm import Mathlib.Data.List.OfFn import Mathlib.Data.List.Nodup import Mathlib.Data.List.TakeWhile import Mathlib.Order.Fin.Basic /-! # Sorting algorithms on lists In this file we define `List.Sorted r l` to be an alias for `List.Pairwise r l`. This alias is preferred in the case that `r` is a `<` or `≀`-like relation. Then we define the sorting algorithm `List.insertionSort` and prove its correctness. -/ open List.Perm universe u v namespace List /-! ### The predicate `List.Sorted` -/ section Sorted variable {Ξ± : Type u} {r : Ξ± β†’ Ξ± β†’ Prop} {a : Ξ±} {l : List Ξ±} /-- `Sorted r l` is the same as `List.Pairwise r l`, preferred in the case that `r` is a `<` or `≀`-like relation (transitive and antisymmetric or asymmetric) -/ def Sorted := @Pairwise instance decidableSorted [DecidableRel r] (l : List Ξ±) : Decidable (Sorted r l) := List.instDecidablePairwise _ protected theorem Sorted.le_of_lt [Preorder Ξ±] {l : List Ξ±} (h : l.Sorted (Β· < Β·)) : l.Sorted (Β· ≀ Β·) := h.imp le_of_lt protected theorem Sorted.lt_of_le [PartialOrder Ξ±] {l : List Ξ±} (h₁ : l.Sorted (Β· ≀ Β·)) (hβ‚‚ : l.Nodup) : l.Sorted (Β· < Β·) := h₁.impβ‚‚ (fun _ _ => lt_of_le_of_ne) hβ‚‚ protected theorem Sorted.ge_of_gt [Preorder Ξ±] {l : List Ξ±} (h : l.Sorted (Β· > Β·)) : l.Sorted (Β· β‰₯ Β·) := h.imp le_of_lt protected theorem Sorted.gt_of_ge [PartialOrder Ξ±] {l : List Ξ±} (h₁ : l.Sorted (Β· β‰₯ Β·)) (hβ‚‚ : l.Nodup) : l.Sorted (Β· > Β·) := h₁.impβ‚‚ (fun _ _ => lt_of_le_of_ne) <| by simp_rw [ne_comm]; exact hβ‚‚ @[simp] theorem sorted_nil : Sorted r [] := Pairwise.nil theorem Sorted.of_cons : Sorted r (a :: l) β†’ Sorted r l := Pairwise.of_cons theorem Sorted.tail {r : Ξ± β†’ Ξ± β†’ Prop} {l : List Ξ±} (h : Sorted r l) : Sorted r l.tail := Pairwise.tail h theorem rel_of_sorted_cons {a : Ξ±} {l : List Ξ±} : Sorted r (a :: l) β†’ βˆ€ b ∈ l, r a b := rel_of_pairwise_cons nonrec theorem Sorted.cons {r : Ξ± β†’ Ξ± β†’ Prop} [IsTrans Ξ± r] {l : List Ξ±} {a b : Ξ±} (hab : r a b) (h : Sorted r (b :: l)) : Sorted r (a :: b :: l) := h.cons <| forall_mem_cons.2 ⟨hab, fun _ hx => _root_.trans hab <| rel_of_sorted_cons h _ hx⟩ theorem sorted_cons_cons {r : Ξ± β†’ Ξ± β†’ Prop} [IsTrans Ξ± r] {l : List Ξ±} {a b : Ξ±} : Sorted r (b :: a :: l) ↔ r b a ∧ Sorted r (a :: l) := by constructor Β· intro h exact ⟨rel_of_sorted_cons h _ mem_cons_self, h.of_cons⟩ Β· rintro ⟨h, ha⟩ exact ha.cons h theorem Sorted.head!_le [Inhabited Ξ±] [Preorder Ξ±] {a : Ξ±} {l : List Ξ±} (h : Sorted (Β· < Β·) l) (ha : a ∈ l) : l.head! ≀ a := by rw [← List.cons_head!_tail (List.ne_nil_of_mem ha)] at h ha cases ha Β· exact le_rfl Β· exact le_of_lt (rel_of_sorted_cons h a (by assumption)) theorem Sorted.le_head! [Inhabited Ξ±] [Preorder Ξ±] {a : Ξ±} {l : List Ξ±} (h : Sorted (Β· > Β·) l) (ha : a ∈ l) : a ≀ l.head! := by rw [← List.cons_head!_tail (List.ne_nil_of_mem ha)] at h ha cases ha Β· exact le_rfl Β· exact le_of_lt (rel_of_sorted_cons h a (by assumption)) @[simp] theorem sorted_cons {a : Ξ±} {l : List Ξ±} : Sorted r (a :: l) ↔ (βˆ€ b ∈ l, r a b) ∧ Sorted r l := pairwise_cons protected theorem Sorted.nodup {r : Ξ± β†’ Ξ± β†’ Prop} [IsIrrefl Ξ± r] {l : List Ξ±} (h : Sorted r l) : Nodup l := Pairwise.nodup h protected theorem Sorted.filter {l : List Ξ±} (f : Ξ± β†’ Bool) (h : Sorted r l) : Sorted r (filter f l) := h.sublist filter_sublist theorem eq_of_perm_of_sorted [IsAntisymm Ξ± r] {l₁ lβ‚‚ : List Ξ±} (hp : l₁ ~ lβ‚‚) (hs₁ : Sorted r l₁) (hsβ‚‚ : Sorted r lβ‚‚) : l₁ = lβ‚‚ := by induction hs₁ generalizing lβ‚‚ with | nil => exact hp.nil_eq | @cons a l₁ h₁ hs₁ IH => have : a ∈ lβ‚‚ := hp.subset mem_cons_self rcases append_of_mem this with ⟨uβ‚‚, vβ‚‚, rfl⟩ have hp' := (perm_cons a).1 (hp.trans perm_middle) obtain rfl := IH hp' (hsβ‚‚.sublist <| by simp) change a :: uβ‚‚ ++ vβ‚‚ = uβ‚‚ ++ ([a] ++ vβ‚‚) rw [← append_assoc] congr have : βˆ€ x ∈ uβ‚‚, x = a := fun x m => antisymm ((pairwise_append.1 hsβ‚‚).2.2 _ m a mem_cons_self) (h₁ _ (by simp [m])) rw [(@eq_replicate_iff _ a (length uβ‚‚ + 1) (a :: uβ‚‚)).2, (@eq_replicate_iff _ a (length uβ‚‚ + 1) (uβ‚‚ ++ [a])).2] <;> constructor <;> simp [iff_true_intro this, or_comm] theorem Sorted.eq_of_mem_iff [IsAntisymm Ξ± r] [IsIrrefl Ξ± r] {l₁ lβ‚‚ : List Ξ±} (h₁ : Sorted r l₁) (hβ‚‚ : Sorted r lβ‚‚) (h : βˆ€ a : Ξ±, a ∈ l₁ ↔ a ∈ lβ‚‚) : l₁ = lβ‚‚ := eq_of_perm_of_sorted ((perm_ext_iff_of_nodup h₁.nodup hβ‚‚.nodup).2 h) h₁ hβ‚‚ theorem sublist_of_subperm_of_sorted [IsAntisymm Ξ± r] {l₁ lβ‚‚ : List Ξ±} (hp : l₁ <+~ lβ‚‚) (hs₁ : l₁.Sorted r) (hsβ‚‚ : lβ‚‚.Sorted r) : l₁ <+ lβ‚‚ := by let ⟨_, h, h'⟩ := hp rwa [← eq_of_perm_of_sorted h (hsβ‚‚.sublist h') hs₁] @[simp 1100] -- Higher priority shortcut lemma. theorem sorted_singleton (a : Ξ±) : Sorted r [a] := by simp theorem sorted_lt_range (n : β„•) : Sorted (Β· < Β·) (range n) := by rw [Sorted, pairwise_iff_get] simp theorem sorted_replicate (n : β„•) (a : Ξ±) : Sorted r (replicate n a) ↔ n ≀ 1 ∨ r a a := pairwise_replicate theorem sorted_le_replicate (n : β„•) (a : Ξ±) [Preorder Ξ±] : Sorted (Β· ≀ Β·) (replicate n a) := by simp [sorted_replicate] theorem sorted_le_range (n : β„•) : Sorted (Β· ≀ Β·) (range n) := (sorted_lt_range n).le_of_lt lemma sorted_lt_range' (a b) {s} (hs : s β‰  0) : Sorted (Β· < Β·) (range' a b s) := by induction b generalizing a with | zero => simp | succ n ih => rw [List.range'_succ] refine List.sorted_cons.mpr ⟨fun b hb ↦ ?_, @ih (a + s)⟩ exact lt_of_lt_of_le (Nat.lt_add_of_pos_right (Nat.zero_lt_of_ne_zero hs)) (List.left_le_of_mem_range' hb) lemma sorted_le_range' (a b s) : Sorted (Β· ≀ Β·) (range' a b s) := by by_cases hs : s β‰  0 Β· exact (sorted_lt_range' a b hs).le_of_lt Β· rw [ne_eq, Decidable.not_not] at hs simpa [hs] using sorted_le_replicate b a theorem Sorted.rel_get_of_lt {l : List Ξ±} (h : l.Sorted r) {a b : Fin l.length} (hab : a < b) : r (l.get a) (l.get b) := List.pairwise_iff_get.1 h _ _ hab theorem Sorted.rel_get_of_le [IsRefl Ξ± r] {l : List Ξ±} (h : l.Sorted r) {a b : Fin l.length} (hab : a ≀ b) : r (l.get a) (l.get b) := by obtain rfl | hlt := Fin.eq_or_lt_of_le hab; exacts [refl _, h.rel_get_of_lt hlt] theorem Sorted.rel_of_mem_take_of_mem_drop {l : List Ξ±} (h : List.Sorted r l) {k : β„•} {x y : Ξ±} (hx : x ∈ List.take k l) (hy : y ∈ List.drop k l) : r x y := by obtain ⟨iy, hiy, rfl⟩ := getElem_of_mem hy obtain ⟨ix, hix, rfl⟩ := getElem_of_mem hx rw [getElem_take, getElem_drop] rw [length_take] at hix exact h.rel_get_of_lt (Nat.lt_add_right _ (Nat.lt_min.mp hix).left) /-- If a list is sorted with respect to a decidable relation, then it is sorted with respect to the corresponding Bool-valued relation. -/ theorem Sorted.decide [DecidableRel r] (l : List Ξ±) (h : Sorted r l) : Sorted (fun a b => decide (r a b) = true) l := by refine h.imp fun {a b} h => by simpa using h end Sorted section Monotone variable {n : β„•} {Ξ± : Type u} {f : Fin n β†’ Ξ±} open scoped Relator in theorem sorted_ofFn_iff {r : Ξ± β†’ Ξ± β†’ Prop} : (ofFn f).Sorted r ↔ ((Β· < Β·) β‡’ r) f f := by simp_rw [Sorted, pairwise_iff_get, get_ofFn, Relator.LiftFun] exact Iff.symm (Fin.rightInverse_cast _).surjective.forallβ‚‚ variable [Preorder Ξ±] /-- The list `List.ofFn f` is strictly sorted with respect to `(Β· ≀ Β·)` if and only if `f` is strictly monotone. -/ @[simp] theorem sorted_lt_ofFn_iff : (ofFn f).Sorted (Β· < Β·) ↔ StrictMono f := sorted_ofFn_iff /-- The list `List.ofFn f` is strictly sorted with respect to `(Β· β‰₯ Β·)` if and only if `f` is strictly antitone. -/ @[simp] theorem sorted_gt_ofFn_iff : (ofFn f).Sorted (Β· > Β·) ↔ StrictAnti f := sorted_ofFn_iff /-- The list `List.ofFn f` is sorted with respect to `(Β· ≀ Β·)` if and only if `f` is monotone. -/ @[simp] theorem sorted_le_ofFn_iff : (ofFn f).Sorted (Β· ≀ Β·) ↔ Monotone f := sorted_ofFn_iff.trans monotone_iff_forall_lt.symm /-- The list obtained from a monotone tuple is sorted. -/ alias ⟨_, _root_.Monotone.ofFn_sorted⟩ := sorted_le_ofFn_iff /-- The list `List.ofFn f` is sorted with respect to `(Β· β‰₯ Β·)` if and only if `f` is antitone. -/ @[simp] theorem sorted_ge_ofFn_iff : (ofFn f).Sorted (Β· β‰₯ Β·) ↔ Antitone f := sorted_ofFn_iff.trans antitone_iff_forall_lt.symm /-- The list obtained from an antitone tuple is sorted. -/ alias ⟨_, _root_.Antitone.ofFn_sorted⟩ := sorted_ge_ofFn_iff end Monotone lemma Sorted.filterMap {Ξ± Ξ² : Type*} {p : Ξ± β†’ Option Ξ²} {l : List Ξ±} {r : Ξ± β†’ Ξ± β†’ Prop} {r' : Ξ² β†’ Ξ² β†’ Prop} (hl : l.Sorted r) (hp : βˆ€ (a b : Ξ±) (c d : Ξ²), p a = some c β†’ p b = some d β†’ r a b β†’ r' c d) : (l.filterMap p).Sorted r' := by induction l with | nil => simp | cons a l ih => rw [List.filterMap_cons] cases ha : p a with | none => exact ih (List.sorted_cons.mp hl).right | some b => rw [List.sorted_cons] refine ⟨fun x hx ↦ ?_, ih (List.sorted_cons.mp hl).right⟩ obtain ⟨u, hu, hu'⟩ := List.mem_filterMap.mp hx exact hp a u b x ha hu' <| (List.sorted_cons.mp hl).left u hu end List open List namespace RelEmbedding variable {Ξ± Ξ² : Type*} {ra : Ξ± β†’ Ξ± β†’ Prop} {rb : Ξ² β†’ Ξ² β†’ Prop} @[simp] theorem sorted_listMap (e : ra β†ͺr rb) {l : List Ξ±} : (l.map e).Sorted rb ↔ l.Sorted ra := by simp [Sorted, pairwise_map, e.map_rel_iff] @[simp] theorem sorted_swap_listMap (e : ra β†ͺr rb) {l : List Ξ±} : (l.map e).Sorted (Function.swap rb) ↔ l.Sorted (Function.swap ra) := by simp [Sorted, pairwise_map, e.map_rel_iff] end RelEmbedding namespace OrderEmbedding variable {Ξ± Ξ² : Type*} [Preorder Ξ±] [Preorder Ξ²] @[simp] theorem sorted_lt_listMap (e : Ξ± β†ͺo Ξ²) {l : List Ξ±} : (l.map e).Sorted (Β· < Β·) ↔ l.Sorted (Β· < Β·) := e.ltEmbedding.sorted_listMap @[simp] theorem sorted_gt_listMap (e : Ξ± β†ͺo Ξ²) {l : List Ξ±} : (l.map e).Sorted (Β· > Β·) ↔ l.Sorted (Β· > Β·) := e.ltEmbedding.sorted_swap_listMap end OrderEmbedding namespace RelIso variable {Ξ± Ξ² : Type*} {ra : Ξ± β†’ Ξ± β†’ Prop} {rb : Ξ² β†’ Ξ² β†’ Prop} @[simp] theorem sorted_listMap (e : ra ≃r rb) {l : List Ξ±} : (l.map e).Sorted rb ↔ l.Sorted ra := e.toRelEmbedding.sorted_listMap @[simp] theorem sorted_swap_listMap (e : ra ≃r rb) {l : List Ξ±} : (l.map e).Sorted (Function.swap rb) ↔ l.Sorted (Function.swap ra) := e.toRelEmbedding.sorted_swap_listMap end RelIso namespace OrderIso variable {Ξ± Ξ² : Type*} [Preorder Ξ±] [Preorder Ξ²] @[simp] theorem sorted_lt_listMap (e : Ξ± ≃o Ξ²) {l : List Ξ±} : (l.map e).Sorted (Β· < Β·) ↔ l.Sorted (Β· < Β·) := e.toOrderEmbedding.sorted_lt_listMap @[simp] theorem sorted_gt_listMap (e : Ξ± ≃o Ξ²) {l : List Ξ±} : (l.map e).Sorted (Β· > Β·) ↔ l.Sorted (Β· > Β·) := e.toOrderEmbedding.sorted_gt_listMap end OrderIso namespace StrictMono variable {Ξ± Ξ² : Type*} [LinearOrder Ξ±] [Preorder Ξ²] {f : Ξ± β†’ Ξ²} {l : List Ξ±} theorem sorted_le_listMap (hf : StrictMono f) : (l.map f).Sorted (Β· ≀ Β·) ↔ l.Sorted (Β· ≀ Β·) := (OrderEmbedding.ofStrictMono f hf).sorted_listMap theorem sorted_ge_listMap (hf : StrictMono f) : (l.map f).Sorted (Β· β‰₯ Β·) ↔ l.Sorted (Β· β‰₯ Β·) := (OrderEmbedding.ofStrictMono f hf).sorted_swap_listMap theorem sorted_lt_listMap (hf : StrictMono f) : (l.map f).Sorted (Β· < Β·) ↔ l.Sorted (Β· < Β·) := (OrderEmbedding.ofStrictMono f hf).sorted_lt_listMap theorem sorted_gt_listMap (hf : StrictMono f) : (l.map f).Sorted (Β· > Β·) ↔ l.Sorted (Β· > Β·) := (OrderEmbedding.ofStrictMono f hf).sorted_gt_listMap end StrictMono namespace StrictAnti variable {Ξ± Ξ² : Type*} [LinearOrder Ξ±] [Preorder Ξ²] {f : Ξ± β†’ Ξ²} {l : List Ξ±} theorem sorted_le_listMap (hf : StrictAnti f) : (l.map f).Sorted (Β· ≀ Β·) ↔ l.Sorted (Β· β‰₯ Β·) := hf.dual_right.sorted_ge_listMap theorem sorted_ge_listMap (hf : StrictAnti f) : (l.map f).Sorted (Β· β‰₯ Β·) ↔ l.Sorted (Β· ≀ Β·) := hf.dual_right.sorted_le_listMap theorem sorted_lt_listMap (hf : StrictAnti f) : (l.map f).Sorted (Β· < Β·) ↔ l.Sorted (Β· > Β·) := hf.dual_right.sorted_gt_listMap theorem sorted_gt_listMap (hf : StrictAnti f) : (l.map f).Sorted (Β· > Β·) ↔ l.Sorted (Β· < Β·) := hf.dual_right.sorted_lt_listMap end StrictAnti namespace List section sort variable {Ξ± : Type u} {Ξ² : Type v} (r : Ξ± β†’ Ξ± β†’ Prop) (s : Ξ² β†’ Ξ² β†’ Prop) variable [DecidableRel r] [DecidableRel s] local infixl:50 " β‰Ό " => r local infixl:50 " β‰Ό " => s /-! ### Insertion sort -/ section InsertionSort /-- `orderedInsert a l` inserts `a` into `l` at such that `orderedInsert a l` is sorted if `l` is. -/ @[simp] def orderedInsert (a : Ξ±) : List Ξ± β†’ List Ξ± | [] => [a] | b :: l => if a β‰Ό b then a :: b :: l else b :: orderedInsert a l theorem orderedInsert_of_le {a b : Ξ±} (l : List Ξ±) (h : a β‰Ό b) : orderedInsert r a (b :: l) = a :: b :: l := dif_pos h /-- `insertionSort l` returns `l` sorted using the insertion sort algorithm. -/ @[simp] def insertionSort : List Ξ± β†’ List Ξ± | [] => [] | b :: l => orderedInsert r b (insertionSort l) -- A quick check that insertionSort is stable: example : insertionSort (fun m n => m / 10 ≀ n / 10) [5, 27, 221, 95, 17, 43, 7, 2, 98, 567, 23, 12] = [5, 7, 2, 17, 12, 27, 23, 43, 95, 98, 221, 567] := rfl @[simp] theorem orderedInsert_nil (a : Ξ±) : [].orderedInsert r a = [a] := rfl theorem orderedInsert_length : βˆ€ (L : List Ξ±) (a : Ξ±), (L.orderedInsert r a).length = L.length + 1 | [], _ => rfl | hd :: tl, a => by dsimp [orderedInsert] split_ifs <;> simp [orderedInsert_length tl] /-- An alternative definition of `orderedInsert` using `takeWhile` and `dropWhile`. -/ theorem orderedInsert_eq_take_drop (a : Ξ±) : βˆ€ l : List Ξ±, l.orderedInsert r a = (l.takeWhile fun b => Β¬a β‰Ό b) ++ a :: l.dropWhile fun b => Β¬a β‰Ό b | [] => rfl | b :: l => by dsimp only [orderedInsert] split_ifs with h <;> simp [takeWhile, dropWhile, *, orderedInsert_eq_take_drop a l] theorem insertionSort_cons_eq_take_drop (a : Ξ±) (l : List Ξ±) : insertionSort r (a :: l) = ((insertionSort r l).takeWhile fun b => Β¬a β‰Ό b) ++ a :: (insertionSort r l).dropWhile fun b => Β¬a β‰Ό b := orderedInsert_eq_take_drop r a _ @[simp] theorem mem_orderedInsert {a b : Ξ±} {l : List Ξ±} : a ∈ orderedInsert r b l ↔ a = b ∨ a ∈ l := match l with | [] => by simp [orderedInsert] | x :: xs => by rw [orderedInsert] split_ifs Β· simp Β· rw [mem_cons, mem_cons, mem_orderedInsert, or_left_comm] theorem map_orderedInsert (f : Ξ± β†’ Ξ²) (l : List Ξ±) (x : Ξ±) (hl₁ : βˆ€ a ∈ l, a β‰Ό x ↔ f a β‰Ό f x) (hlβ‚‚ : βˆ€ a ∈ l, x β‰Ό a ↔ f x β‰Ό f a) : (l.orderedInsert r x).map f = (l.map f).orderedInsert s (f x) := by induction l with | nil => simp | cons x xs ih => rw [List.forall_mem_cons] at hl₁ hlβ‚‚ simp only [List.map, List.orderedInsert, ← hlβ‚‚.1] split_ifs Β· rw [List.map, List.map] Β· rw [List.map, ih (fun _ ha => hl₁.2 _ ha) (fun _ ha => hlβ‚‚.2 _ ha)] section Correctness theorem perm_orderedInsert (a) : βˆ€ l : List Ξ±, orderedInsert r a l ~ a :: l | [] => Perm.refl _ | b :: l => by by_cases h : a β‰Ό b Β· simp [orderedInsert, h] Β· simpa [orderedInsert, h] using ((perm_orderedInsert a l).cons _).trans (Perm.swap _ _ _) theorem orderedInsert_count [DecidableEq Ξ±] (L : List Ξ±) (a b : Ξ±) : count a (L.orderedInsert r b) = count a L + if b = a then 1 else 0 := by rw [(L.perm_orderedInsert r b).count_eq, count_cons] simp theorem perm_insertionSort : βˆ€ l : List Ξ±, insertionSort r l ~ l | [] => Perm.nil | b :: l => by simpa [insertionSort] using (perm_orderedInsert _ _ _).trans ((perm_insertionSort l).cons b) @[simp] theorem mem_insertionSort {l : List Ξ±} {x : Ξ±} : x ∈ l.insertionSort r ↔ x ∈ l := (perm_insertionSort r l).mem_iff @[simp] theorem length_insertionSort (l : List Ξ±) : (insertionSort r l).length = l.length := (perm_insertionSort r _).length_eq theorem insertionSort_cons {a : Ξ±} {l : List Ξ±} (h : βˆ€ b ∈ l, r a b) : insertionSort r (a :: l) = a :: insertionSort r l := by rw [insertionSort] cases hi : insertionSort r l with | nil => rfl | cons b m => rw [orderedInsert_of_le] apply h b <| (mem_insertionSort r).1 _ rw [hi] exact mem_cons_self theorem map_insertionSort (f : Ξ± β†’ Ξ²) (l : List Ξ±) (hl : βˆ€ a ∈ l, βˆ€ b ∈ l, a β‰Ό b ↔ f a β‰Ό f b) : (l.insertionSort r).map f = (l.map f).insertionSort s := by induction l with | nil => simp | cons x xs ih => simp_rw [List.forall_mem_cons, forall_and] at hl simp_rw [List.map, List.insertionSort] rw [List.map_orderedInsert _ s, ih hl.2.2] Β· simpa only [mem_insertionSort] using hl.2.1 Β· simpa only [mem_insertionSort] using hl.1.2 variable {r} /-- If `l` is already `List.Sorted` with respect to `r`, then `insertionSort` does not change it. -/ theorem Sorted.insertionSort_eq : βˆ€ {l : List Ξ±}, Sorted r l β†’ insertionSort r l = l | [], _ => rfl | [_], _ => rfl | a :: b :: l, h => by rw [insertionSort, Sorted.insertionSort_eq, orderedInsert, if_pos] exacts [rel_of_sorted_cons h _ mem_cons_self, h.tail] /-- For a reflexive relation, insert then erasing is the identity. -/ theorem erase_orderedInsert [DecidableEq Ξ±] [IsRefl Ξ± r] (x : Ξ±) (xs : List Ξ±) : (xs.orderedInsert r x).erase x = xs := by rw [orderedInsert_eq_take_drop, erase_append_right, List.erase_cons_head, takeWhile_append_dropWhile] intro h replace h := mem_takeWhile_imp h simp [refl x] at h /-- Inserting then erasing an element that is absent is the identity. -/ theorem erase_orderedInsert_of_notMem [DecidableEq Ξ±] {x : Ξ±} {xs : List Ξ±} (hx : x βˆ‰ xs) : (xs.orderedInsert r x).erase x = xs := by rw [orderedInsert_eq_take_drop, erase_append_right, List.erase_cons_head, takeWhile_append_dropWhile] exact mt ((takeWhile_prefix _).sublist.subset Β·) hx @[deprecated (since := "2025-05-23")] alias erase_orderedInsert_of_not_mem := erase_orderedInsert_of_notMem /-- For an antisymmetric relation, erasing then inserting is the identity. -/ theorem orderedInsert_erase [DecidableEq Ξ±] [IsAntisymm Ξ± r] (x : Ξ±) (xs : List Ξ±) (hx : x ∈ xs) (hxs : Sorted r xs) : (xs.erase x).orderedInsert r x = xs := by induction xs generalizing x with | nil => cases hx | cons y ys ih => rw [sorted_cons] at hxs obtain rfl | hxy := Decidable.eq_or_ne x y Β· rw [erase_cons_head] cases ys with | nil => rfl | cons z zs => rw [orderedInsert, if_pos (hxs.1 _ (.head zs))] Β· rw [mem_cons] at hx replace hx := hx.resolve_left hxy rw [erase_cons_tail (not_beq_of_ne hxy.symm), orderedInsert, ih _ hx hxs.2, if_neg] refine mt (fun hrxy => ?_) hxy exact antisymm hrxy (hxs.1 _ hx) theorem sublist_orderedInsert (x : Ξ±) (xs : List Ξ±) : xs <+ xs.orderedInsert r x := by rw [orderedInsert_eq_take_drop] refine Sublist.trans ?_ (.append_left (.cons _ (.refl _)) _) rw [takeWhile_append_dropWhile] theorem cons_sublist_orderedInsert {l c : List Ξ±} {a : Ξ±} (hl : c <+ l) (ha : βˆ€ a' ∈ c, a β‰Ό a') : a :: c <+ orderedInsert r a l := by induction l with | nil => simp_all only [sublist_nil, orderedInsert, Sublist.refl] | cons _ _ ih => unfold orderedInsert split_ifs with hr Β· exact .consβ‚‚ _ hl Β· cases hl with | cons _ h => exact .cons _ <| ih h | consβ‚‚ => exact absurd (ha _ <| mem_cons_self ..) hr theorem Sublist.orderedInsert_sublist [IsTrans Ξ± r] {as bs} (x) (hs : as <+ bs) (hb : bs.Sorted r) : orderedInsert r x as <+ orderedInsert r x bs := by cases as with | nil => simp | cons a as => cases bs with | nil => contradiction | cons b bs => unfold orderedInsert cases hs <;> split_ifs with hr Β· exact .consβ‚‚ _ <| .cons _ β€Ήa :: as <+ bsβ€Ί Β· have ih := orderedInsert_sublist x β€Ήa :: as <+ bsβ€Ί hb.of_cons simp only [hr, orderedInsert, ite_true] at ih exact .trans ih <| .cons _ (.refl _) Β· have hba := pairwise_cons.mp hb |>.left _ (mem_of_cons_sublist β€Ήa :: as <+ bsβ€Ί) exact absurd (trans_of _ β€Ήr x bβ€Ί hba) hr Β· have ih := orderedInsert_sublist x β€Ήa :: as <+ bsβ€Ί hb.of_cons rw [orderedInsert, if_neg hr] at ih exact .cons _ ih Β· simp_all only [sorted_cons, cons_sublist_cons] Β· exact .consβ‚‚ _ <| orderedInsert_sublist x β€Ήas <+ bsβ€Ί hb.of_cons section TotalAndTransitive variable [IsTotal Ξ± r] [IsTrans Ξ± r] theorem Sorted.orderedInsert (a : Ξ±) : βˆ€ l, Sorted r l β†’ Sorted r (orderedInsert r a l) | [], _ => sorted_singleton a | b :: l, h => by by_cases h' : a β‰Ό b Β· simpa [orderedInsert, h', h] using fun b' bm => _root_.trans h' (rel_of_sorted_cons h _ bm) Β· suffices βˆ€ b' : Ξ±, b' ∈ List.orderedInsert r a l β†’ r b b' by simpa [orderedInsert, h', h.of_cons.orderedInsert a l] intro b' bm rcases (mem_orderedInsert r).mp bm with be | bm Β· subst b' exact (total_of r _ _).resolve_left h' Β· exact rel_of_sorted_cons h _ bm variable (r) /-- The list `List.insertionSort r l` is `List.Sorted` with respect to `r`. -/ theorem sorted_insertionSort : βˆ€ l, Sorted r (insertionSort r l) | [] => sorted_nil | a :: l => (sorted_insertionSort l).orderedInsert a _ end TotalAndTransitive /-- If `c` is a sorted sublist of `l`, then `c` is still a sublist of `insertionSort r l`. -/ theorem sublist_insertionSort {l c : List Ξ±} (hr : c.Pairwise r) (hc : c <+ l) : c <+ insertionSort r l := by induction l generalizing c with | nil => simp_all only [sublist_nil, insertionSort, Sublist.refl] | cons _ _ ih => cases hc with | cons _ h => exact ih hr h |>.trans (sublist_orderedInsert ..) | consβ‚‚ _ h => obtain ⟨hr, hp⟩ := pairwise_cons.mp hr exact cons_sublist_orderedInsert (ih hp h) hr /-- Another statement of stability of insertion sort. If a pair `[a, b]` is a sublist of `l` and `r a b`, then `[a, b]` is still a sublist of `insertionSort r l`. -/ theorem pair_sublist_insertionSort {a b : Ξ±} {l : List Ξ±} (hab : r a b) (h : [a, b] <+ l) : [a, b] <+ insertionSort r l := sublist_insertionSort (pairwise_pair.mpr hab) h variable [IsAntisymm Ξ± r] [IsTotal Ξ± r] [IsTrans Ξ± r] /-- A version of `insertionSort_stable` which only assumes `c <+~ l` (instead of `c <+ l`), but additionally requires `IsAntisymm Ξ± r`, `IsTotal Ξ± r` and `IsTrans Ξ± r`. -/ theorem sublist_insertionSort' {l c : List Ξ±} (hs : c.Sorted r) (hc : c <+~ l) : c <+ insertionSort r l := by classical obtain ⟨d, hc, hd⟩ := hc induction l generalizing c d with | nil => simp_all only [sublist_nil, insertionSort, nil_perm] | cons a _ ih => cases hd with | cons _ h => exact ih hs _ hc h |>.trans (sublist_orderedInsert ..) | consβ‚‚ _ h => specialize ih (hs.erase _) _ (erase_cons_head a β€ΉList _β€Ί β–Έ hc.erase a) h have hm := hc.mem_iff.mp <| mem_cons_self .. have he := orderedInsert_erase _ _ hm hs exact he β–Έ Sublist.orderedInsert_sublist _ ih (sorted_insertionSort ..) /-- Another statement of stability of insertion sort. If a pair `[a, b]` is a sublist of a permutation of `l` and `a β‰Ό b`, then `[a, b]` is still a sublist of `insertionSort r l`. -/ theorem pair_sublist_insertionSort' {a b : Ξ±} {l : List Ξ±} (hab : a β‰Ό b) (h : [a, b] <+~ l) : [a, b] <+ insertionSort r l := sublist_insertionSort' (pairwise_pair.mpr hab) h end Correctness end InsertionSort /-! ### Merge sort We provide some wrapper functions around the theorems for `mergeSort` provided in Lean, which rather than using explicit hypotheses for transitivity and totality, use Mathlib order typeclasses instead. -/ example : mergeSort [5, 27, 221, 95, 17, 43, 7, 2, 98, 567, 23, 12] (fun m n => m / 10 ≀ n / 10) = [5, 7, 2, 17, 12, 27, 23, 43, 95, 98, 221, 567] := by simp [mergeSort] section MergeSort section Correctness section TotalAndTransitive variable {r} [IsTotal Ξ± r] [IsTrans Ξ± r] theorem Sorted.merge {l l' : List Ξ±} (h : Sorted r l) (h' : Sorted r l') : Sorted r (merge l l' (r Β· Β·)) := by simpa using sorted_merge (le := (r Β· Β·)) (fun a b c h₁ hβ‚‚ => by simpa using _root_.trans (by simpa using h₁) (by simpa using hβ‚‚)) (fun a b => by simpa using IsTotal.total a b) l l' (by simpa using h) (by simpa using h') variable (r) /-- Variant of `sorted_mergeSort` using relation typeclasses. -/ theorem sorted_mergeSort' (l : List Ξ±) : Sorted r (mergeSort l (r Β· Β·)) := by simpa using sorted_mergeSort (le := (r Β· Β·)) (fun _ _ _ => by simpa using trans_of r) (by simpa using total_of r) l variable [IsAntisymm Ξ± r] theorem mergeSort_eq_self {l : List Ξ±} : Sorted r l β†’ mergeSort l (r Β· Β·) = l := eq_of_perm_of_sorted (mergeSort_perm _ _) (sorted_mergeSort' _ l) theorem mergeSort_eq_insertionSort (l : List Ξ±) : mergeSort l (r Β· Β·) = insertionSort r l := eq_of_perm_of_sorted ((mergeSort_perm l _).trans (perm_insertionSort r l).symm) (sorted_mergeSort' r l) (sorted_insertionSort r l) end TotalAndTransitive end Correctness end MergeSort end sort end List
.lake/packages/mathlib/Mathlib/Data/List/DropRight.lean
import Mathlib.Data.List.Induction import Mathlib.Data.List.TakeWhile /-! # Dropping or taking from lists on the right Taking or removing element from the tail end of a list ## Main definitions - `rdrop n`: drop `n : β„•` elements from the tail - `rtake n`: take `n : β„•` elements from the tail - `rdropWhile p`: remove all the elements from the tail of a list until it finds the first element for which `p : Ξ± β†’ Bool` returns false. This element and everything before is returned. - `rtakeWhile p`: Returns the longest terminal segment of a list for which `p : Ξ± β†’ Bool` returns true. ## Implementation detail The two predicate-based methods operate by performing the regular "from-left" operation on `List.reverse`, followed by another `List.reverse`, so they are not the most performant. The other two rely on `List.length l` so they still traverse the list twice. One could construct another function that takes a `L : β„•` and use `L - n`. Under a proof condition that `L = l.length`, the function would do the right thing. -/ -- Make sure we don't import algebra assert_not_exists Monoid variable {Ξ± : Type*} (p : Ξ± β†’ Bool) (l : List Ξ±) (n : β„•) namespace List /-- Drop `n` elements from the tail end of a list. -/ def rdrop : List Ξ± := l.take (l.length - n) @[simp] theorem rdrop_nil : rdrop ([] : List Ξ±) n = [] := by simp [rdrop] @[simp] theorem rdrop_zero : rdrop l 0 = l := by simp [rdrop] theorem rdrop_eq_reverse_drop_reverse : l.rdrop n = reverse (l.reverse.drop n) := by rw [rdrop] induction l using List.reverseRecOn generalizing n with | nil => simp | append_singleton xs x IH => cases n Β· simp [take_length_add_append] Β· simp [take_append, IH] @[simp] theorem rdrop_concat_succ (x : Ξ±) : rdrop (l ++ [x]) (n + 1) = rdrop l n := by simp [rdrop_eq_reverse_drop_reverse] /-- Take `n` elements from the tail end of a list. -/ def rtake : List Ξ± := l.drop (l.length - n) @[simp] theorem rtake_nil : rtake ([] : List Ξ±) n = [] := by simp [rtake] @[simp] theorem rtake_zero : rtake l 0 = [] := by simp [rtake] theorem rtake_eq_reverse_take_reverse : l.rtake n = reverse (l.reverse.take n) := by rw [rtake] induction l using List.reverseRecOn generalizing n with | nil => simp | append_singleton xs x IH => cases n Β· exact drop_length Β· simp [drop_append, IH] @[simp] theorem rtake_concat_succ (x : Ξ±) : rtake (l ++ [x]) (n + 1) = rtake l n ++ [x] := by simp [rtake_eq_reverse_take_reverse] /-- Drop elements from the tail end of a list that satisfy `p : Ξ± β†’ Bool`. Implemented naively via `List.reverse` -/ def rdropWhile : List Ξ± := reverse (l.reverse.dropWhile p) @[simp] theorem rdropWhile_nil : rdropWhile p ([] : List Ξ±) = [] := by simp [rdropWhile] theorem rdropWhile_concat (x : Ξ±) : rdropWhile p (l ++ [x]) = if p x then rdropWhile p l else l ++ [x] := by simp only [rdropWhile, dropWhile, reverse_append, reverse_singleton, singleton_append] split_ifs with h <;> simp [h] @[simp] theorem rdropWhile_concat_pos (x : Ξ±) (h : p x) : rdropWhile p (l ++ [x]) = rdropWhile p l := by rw [rdropWhile_concat, if_pos h] @[simp] theorem rdropWhile_concat_neg (x : Ξ±) (h : Β¬p x) : rdropWhile p (l ++ [x]) = l ++ [x] := by rw [rdropWhile_concat, if_neg h] theorem rdropWhile_singleton (x : Ξ±) : rdropWhile p [x] = if p x then [] else [x] := by rw [← nil_append [x], rdropWhile_concat, rdropWhile_nil] theorem rdropWhile_last_not (hl : l.rdropWhile p β‰  []) : Β¬p ((rdropWhile p l).getLast hl) := by simp_rw [rdropWhile] rw [getLast_reverse, head_dropWhile_not p] simp theorem rdropWhile_prefix : l.rdropWhile p <+: l := by rw [← reverse_suffix, rdropWhile, reverse_reverse] exact dropWhile_suffix _ variable {p} {l} @[simp] theorem rdropWhile_eq_nil_iff : rdropWhile p l = [] ↔ βˆ€ x ∈ l, p x := by simp [rdropWhile] @[simp] theorem rdropWhile_eq_self_iff : rdropWhile p l = l ↔ βˆ€ hl : l β‰  [], Β¬p (l.getLast hl) := by simp [rdropWhile, reverse_eq_iff, getLast_eq_getElem, Nat.pos_iff_ne_zero] variable (p) (l) theorem dropWhile_idempotent : dropWhile p (dropWhile p l) = dropWhile p l := by simp only [dropWhile_eq_self_iff] exact fun h => dropWhile_get_zero_not p l h theorem rdropWhile_idempotent : rdropWhile p (rdropWhile p l) = rdropWhile p l := rdropWhile_eq_self_iff.mpr (rdropWhile_last_not _ _) theorem rdropWhile_reverse : l.reverse.rdropWhile p = (l.dropWhile p).reverse := by simp_rw [rdropWhile, reverse_reverse] /-- Take elements from the tail end of a list that satisfy `p : Ξ± β†’ Bool`. Implemented naively via `List.reverse` -/ def rtakeWhile : List Ξ± := reverse (l.reverse.takeWhile p) @[simp] theorem rtakeWhile_nil : rtakeWhile p ([] : List Ξ±) = [] := by simp [rtakeWhile] theorem rtakeWhile_concat (x : Ξ±) : rtakeWhile p (l ++ [x]) = if p x then rtakeWhile p l ++ [x] else [] := by simp only [rtakeWhile, takeWhile, reverse_append, reverse_singleton, singleton_append] split_ifs with h <;> simp [h] @[simp] theorem rtakeWhile_concat_pos (x : Ξ±) (h : p x) : rtakeWhile p (l ++ [x]) = rtakeWhile p l ++ [x] := by rw [rtakeWhile_concat, if_pos h] @[simp] theorem rtakeWhile_concat_neg (x : Ξ±) (h : Β¬p x) : rtakeWhile p (l ++ [x]) = [] := by rw [rtakeWhile_concat, if_neg h] theorem rtakeWhile_suffix : l.rtakeWhile p <:+ l := by rw [← reverse_prefix, rtakeWhile, reverse_reverse] exact takeWhile_prefix _ variable {p} {l} @[simp] theorem rtakeWhile_eq_self_iff : rtakeWhile p l = l ↔ βˆ€ x ∈ l, p x := by simp [rtakeWhile, reverse_eq_iff] @[simp] theorem rtakeWhile_eq_nil_iff : rtakeWhile p l = [] ↔ βˆ€ hl : l β‰  [], Β¬p (l.getLast hl) := by induction l using List.reverseRecOn <;> simp [rtakeWhile] theorem mem_rtakeWhile_imp {x : Ξ±} (hx : x ∈ rtakeWhile p l) : p x := by rw [rtakeWhile, mem_reverse] at hx exact mem_takeWhile_imp hx theorem rtakeWhile_idempotent (p : Ξ± β†’ Bool) (l : List Ξ±) : rtakeWhile p (rtakeWhile p l) = rtakeWhile p l := rtakeWhile_eq_self_iff.mpr fun _ => mem_rtakeWhile_imp theorem rtakeWhile_reverse : l.reverse.rtakeWhile p = (l.takeWhile p).reverse := by simp_rw [rtakeWhile, reverse_reverse] @[simp] theorem rdropWhile_append_rtakeWhile : l.rdropWhile p ++ l.rtakeWhile p = l := by simp only [rdropWhile, rtakeWhile] rw [← List.reverse_append, takeWhile_append_dropWhile, reverse_reverse] lemma rdrop_add (i j : β„•) : (l.rdrop i).rdrop j = l.rdrop (i + j) := by simp_rw [rdrop_eq_reverse_drop_reverse, reverse_reverse, drop_drop] @[simp] lemma rdrop_append_length {l₁ lβ‚‚ : List Ξ±} : List.rdrop (l₁ ++ lβ‚‚) (List.length lβ‚‚) = l₁ := by rw [rdrop_eq_reverse_drop_reverse, ← length_reverse, reverse_append, drop_left, reverse_reverse] lemma rdrop_append_of_le_length {l₁ lβ‚‚ : List Ξ±} (k : β„•) : k ≀ length lβ‚‚ β†’ List.rdrop (l₁ ++ lβ‚‚) k = l₁ ++ List.rdrop lβ‚‚ k := by intro hk rw [← length_reverse] at hk rw [rdrop_eq_reverse_drop_reverse, reverse_append, drop_append_of_le_length hk, reverse_append, reverse_reverse, ← rdrop_eq_reverse_drop_reverse] @[simp] lemma rdrop_append_length_add {l₁ lβ‚‚ : List Ξ±} (k : β„•) : List.rdrop (l₁ ++ lβ‚‚) (length lβ‚‚ + k) = List.rdrop l₁ k := by rw [← rdrop_add, rdrop_append_length] end List
.lake/packages/mathlib/Mathlib/Data/List/Triplewise.lean
import Aesop import Mathlib.Tactic.Lemma import Mathlib.Tactic.MkIffOfInductiveProp /-! # Triplewise predicates on list. ## Main definitions * `List.Triplewise` says that a predicate applies to all ordered triples of elements of a list. -/ namespace List variable {Ξ± Ξ² : Type*} /-- Whether a predicate holds for all ordered triples of elements of a list. -/ @[mk_iff] inductive Triplewise (p : Ξ± β†’ Ξ± β†’ Ξ± β†’ Prop) : List Ξ± β†’ Prop | nil : [].Triplewise p | cons {a : Ξ±} {l : List Ξ±} : l.Pairwise (p a) β†’ l.Triplewise p β†’ (a :: l).Triplewise p attribute [simp, grind ←] Triplewise.nil variable {a b c : Ξ±} {l l₁ lβ‚‚ : List Ξ±} {p q : Ξ± β†’ Ξ± β†’ Ξ± β†’ Prop} {f : Ξ± β†’ Ξ²} {p' : Ξ² β†’ Ξ² β†’ Ξ² β†’ Prop} @[grind =] lemma triplewise_cons : (a :: l).Triplewise p ↔ l.Pairwise (p a) ∧ l.Triplewise p := by rw [triplewise_iff]; aesop variable (a b p) @[simp] lemma triplewise_singleton : [a].Triplewise p := by simp [triplewise_cons] @[simp] lemma triplewise_pair : [a, b].Triplewise p := by simp [triplewise_cons] variable {a b p} @[simp] lemma triplewise_triple : [a, b, c].Triplewise p ↔ p a b c := by simp [triplewise_cons] lemma Triplewise.imp (h : βˆ€ {a b c}, p a b c β†’ q a b c) (hl : l.Triplewise p) : l.Triplewise q := by induction hl with | nil => exact .nil | cons head tail ih => exact .cons (head.imp h) ih lemma triplewise_map : (l.map f).Triplewise p' ↔ l.Triplewise (fun a b c ↦ p' (f a) (f b) (f c)) := by induction l with | nil => simp | cons h t ih => simp [map, triplewise_cons, ih, pairwise_map] lemma Triplewise.of_map (h : βˆ€ {a b c}, p' (f a) (f b) (f c) β†’ p a b c) (hl : (l.map f).Triplewise p') : l.Triplewise p := by rw [triplewise_map] at hl exact hl.imp h lemma Triplewise.map (h : βˆ€ {a b c}, p a b c β†’ p' (f a) (f b) (f c)) (hl : l.Triplewise p) : (l.map f).Triplewise p' := triplewise_map.2 (hl.imp h) lemma triplewise_iff_getElem : l.Triplewise p ↔ βˆ€ i j k (hij : i < j) (hjk : j < k) (hk : k < l.length), p l[i] l[j] l[k] := by induction l with | nil => simp | cons head tail ih => simp only [triplewise_cons, length_cons, pairwise_iff_getElem, ih] refine ⟨fun ⟨hh, ht⟩ i j k hij hjk hk ↦ ?_, fun h ↦ ⟨fun i j hi hj hij ↦ ?_, fun i j k hij hjk hk ↦ ?_⟩⟩ Β· grind Β· simpa using h 0 (i + 1) (j + 1) (by cutsat) (by cutsat) (by cutsat) Β· simpa using h (i + 1) (j + 1) (k + 1) (by cutsat) (by cutsat) (by cutsat) lemma triplewise_append : (l₁ ++ lβ‚‚).Triplewise p ↔ l₁.Triplewise p ∧ lβ‚‚.Triplewise p ∧ (βˆ€ a ∈ l₁, lβ‚‚.Pairwise (p a)) ∧ βˆ€ a ∈ lβ‚‚, l₁.Pairwise fun x y ↦ p x y a := by induction l₁ with | nil => simp | cons h t ih => simp [triplewise_cons, ih, pairwise_append] aesop lemma triplewise_reverse : l.reverse.Triplewise p ↔ l.Triplewise fun a b c ↦ p c b a := by induction l with | nil => simp | cons h t ih => simp [triplewise_append, pairwise_reverse, triplewise_cons, ih, and_comm] end List
.lake/packages/mathlib/Mathlib/Data/List/Defs.lean
import Mathlib.Data.Nat.Notation import Mathlib.Control.Functor import Mathlib.Data.SProd import Mathlib.Util.CompileInductive import Batteries.Tactic.Lint.Basic import Batteries.Data.List.Basic import Batteries.Logic /-! ## Definitions on lists This file contains various definitions on lists. It does not contain proofs about these definitions, those are contained in other files in `Data.List` -/ namespace List open Function Nat universe u v w x variable {Ξ± Ξ² Ξ³ Ξ΄ Ξ΅ ΞΆ : Type*} instance [DecidableEq Ξ±] : SDiff (List Ξ±) := ⟨List.diff⟩ /-- "Inhabited" `get` function: returns `default` instead of `none` in the case that the index is out of bounds. -/ def getI [Inhabited Ξ±] (l : List Ξ±) (n : Nat) : Ξ± := getD l n default /-- The head of a list, or the default element of the type is the list is `nil`. -/ def headI [Inhabited Ξ±] : List Ξ± β†’ Ξ± | [] => default | (a :: _) => a @[simp] theorem headI_nil [Inhabited Ξ±] : ([] : List Ξ±).headI = default := rfl @[simp] theorem headI_cons [Inhabited Ξ±] {h : Ξ±} {t : List Ξ±} : (h :: t).headI = h := rfl /-- The last element of a list, with the default if list empty -/ def getLastI [Inhabited Ξ±] : List Ξ± β†’ Ξ± | [] => default | [a] => a | [_, b] => b | _ :: _ :: l => getLastI l /-- "Inhabited" `take` function: Take `n` elements from a list `l`. If `l` has less than `n` elements, append `n - length l` elements `default`. -/ def takeI [Inhabited Ξ±] (n : Nat) (l : List Ξ±) : List Ξ± := takeD n l default /-- `findM tac l` returns the first element of `l` on which `tac` succeeds, and fails otherwise. -/ def findM {Ξ±} {m : Type u β†’ Type v} [Alternative m] (tac : Ξ± β†’ m PUnit) : List Ξ± β†’ m Ξ± := List.firstM fun a => (tac a) $> a /-- `findM? p l` returns the first element `a` of `l` for which `p a` returns true. `findM?` short-circuits, so `p` is not necessarily run on every `a` in `l`. This is a monadic version of `List.find`. -/ def findM?' {m : Type u β†’ Type v} [Monad m] {Ξ± : Type u} (p : Ξ± β†’ m (ULift Bool)) : List Ξ± β†’ m (Option Ξ±) | [] => pure none | x :: xs => do let ⟨px⟩ ← p x if px then pure (some x) else findM?' p xs section variable {m : Type β†’ Type v} [Monad m] /-- `orM xs` runs the actions in `xs`, returning true if any of them returns true. `orM` short-circuits, so if an action returns true, later actions are not run. -/ def orM : List (m Bool) β†’ m Bool := anyM id /-- `andM xs` runs the actions in `xs`, returning true if all of them return true. `andM` short-circuits, so if an action returns false, later actions are not run. -/ def andM : List (m Bool) β†’ m Bool := allM id end section foldIdxM variable {m : Type v β†’ Type w} [Monad m] /-- Monadic variant of `foldlIdx`. -/ def foldlIdxM {Ξ± Ξ²} (f : β„• β†’ Ξ² β†’ Ξ± β†’ m Ξ²) (b : Ξ²) (as : List Ξ±) : m Ξ² := as.foldlIdx (fun i ma b => do let a ← ma f i a b) (pure b) /-- Monadic variant of `foldrIdx`. -/ def foldrIdxM {Ξ± Ξ²} (f : β„• β†’ Ξ± β†’ Ξ² β†’ m Ξ²) (b : Ξ²) (as : List Ξ±) : m Ξ² := as.foldrIdx (fun i a mb => do let b ← mb f i a b) (pure b) end foldIdxM section mapIdxM -- This could be relaxed to `Applicative` but is `Monad` to match `List.mapIdxM`. variable {m : Type v β†’ Type w} [Monad m] /-- Auxiliary definition for `mapIdxM'`. -/ def mapIdxMAux' {Ξ±} (f : β„• β†’ Ξ± β†’ m PUnit) : β„• β†’ List Ξ± β†’ m PUnit | _, [] => pure ⟨⟩ | i, a :: as => f i a *> mapIdxMAux' f (i + 1) as /-- A variant of `mapIdxM` specialised to applicative actions which return `Unit`. -/ def mapIdxM' {Ξ±} (f : β„• β†’ Ξ± β†’ m PUnit) (as : List Ξ±) : m PUnit := mapIdxMAux' f 0 as end mapIdxM /-- `l.Forall p` is equivalent to `βˆ€ a ∈ l, p a`, but unfolds directly to a conjunction, i.e. `List.Forall p [0, 1, 2] = p 0 ∧ p 1 ∧ p 2`. -/ @[simp] def Forall (p : Ξ± β†’ Prop) : List Ξ± β†’ Prop | [] => True | x :: [] => p x | x :: l => p x ∧ Forall p l section Permutations /-- An auxiliary function for defining `permutations`. `permutationsAux2 t ts r ys f` is equal to `(ys ++ ts, (insert_left ys t ts).map f ++ r)`, where `insert_left ys t ts` (not explicitly defined) is the list of lists of the form `insert_nth n t (ys ++ ts)` for `0 ≀ n < length ys`. permutations_aux2 10 [4, 5, 6] [] [1, 2, 3] id = ([1, 2, 3, 4, 5, 6], [[10, 1, 2, 3, 4, 5, 6], [1, 10, 2, 3, 4, 5, 6], [1, 2, 10, 3, 4, 5, 6]]) -/ def permutationsAux2 (t : Ξ±) (ts : List Ξ±) (r : List Ξ²) : List Ξ± β†’ (List Ξ± β†’ Ξ²) β†’ List Ξ± Γ— List Ξ² | [], _ => (ts, r) | y :: ys, f => let (us, zs) := permutationsAux2 t ts r ys (fun x : List Ξ± => f (y :: x)) (y :: us, f (t :: y :: us) :: zs) /-- A recursor for pairs of lists. To have `C l₁ lβ‚‚` for all `l₁`, `lβ‚‚`, it suffices to have it for `lβ‚‚ = []` and to be able to pour the elements of `l₁` into `lβ‚‚`. -/ @[elab_as_elim] def permutationsAux.rec {C : List Ξ± β†’ List Ξ± β†’ Sort v} (H0 : βˆ€ is, C [] is) (H1 : βˆ€ t ts is, C ts (t :: is) β†’ C is [] β†’ C (t :: ts) is) : βˆ€ l₁ lβ‚‚, C l₁ lβ‚‚ | [], is => H0 is | t :: ts, is => H1 t ts is (permutationsAux.rec H0 H1 ts (t :: is)) (permutationsAux.rec H0 H1 is []) termination_by ts is => (length ts + length is, length ts) decreasing_by all_goals (simp_wf; omega) /-- An auxiliary function for defining `permutations`. `permutationsAux ts is` is the set of all permutations of `is ++ ts` that do not fix `ts`. -/ def permutationsAux : List Ξ± β†’ List Ξ± β†’ List (List Ξ±) := permutationsAux.rec (fun _ => []) fun t ts is IH1 IH2 => foldr (fun y r => (permutationsAux2 t ts r y id).2) IH1 (is :: IH2) /-- List of all permutations of `l`. permutations [1, 2, 3] = [[1, 2, 3], [2, 1, 3], [3, 2, 1], [2, 3, 1], [3, 1, 2], [1, 3, 2]] -/ def permutations (l : List Ξ±) : List (List Ξ±) := l :: permutationsAux l [] /-- `permutations'Aux t ts` inserts `t` into every position in `ts`, including the last. This function is intended for use in specifications, so it is simpler than `permutationsAux2`, which plays roughly the same role in `permutations`. Note that `(permutationsAux2 t [] [] ts id).2` is similar to this function, but skips the last position: permutations'Aux 10 [1, 2, 3] = [[10, 1, 2, 3], [1, 10, 2, 3], [1, 2, 10, 3], [1, 2, 3, 10]] (permutationsAux2 10 [] [] [1, 2, 3] id).2 = [[10, 1, 2, 3], [1, 10, 2, 3], [1, 2, 10, 3]] -/ @[simp] def permutations'Aux (t : Ξ±) : List Ξ± β†’ List (List Ξ±) | [] => [[t]] | y :: ys => (t :: y :: ys) :: (permutations'Aux t ys).map (cons y) /-- List of all permutations of `l`. This version of `permutations` is less efficient but has simpler definitional equations. The permutations are in a different order, but are equal up to permutation, as shown by `List.permutations_perm_permutations'`. permutations [1, 2, 3] = [[1, 2, 3], [2, 1, 3], [2, 3, 1], [1, 3, 2], [3, 1, 2], [3, 2, 1]] -/ @[simp] def permutations' : List Ξ± β†’ List (List Ξ±) | [] => [[]] | t :: ts => (permutations' ts).flatMap <| permutations'Aux t end Permutations /-- `extractp p l` returns a pair of an element `a` of `l` satisfying the predicate `p`, and `l`, with `a` removed. If there is no such element `a` it returns `(none, l)`. -/ def extractp (p : Ξ± β†’ Prop) [DecidablePred p] : List Ξ± β†’ Option Ξ± Γ— List Ξ± | [] => (none, []) | a :: l => if p a then (some a, l) else let (a', l') := extractp p l (a', a :: l') /-- Notation for calculating the product of a `List` -/ instance instSProd : SProd (List Ξ±) (List Ξ²) (List (Ξ± Γ— Ξ²)) where sprod := List.product /-- `dedup l` removes duplicates from `l` (taking only the last occurrence). Defined as `pwFilter (β‰ )`. dedup [1, 0, 2, 2, 1] = [0, 2, 1] -/ def dedup [DecidableEq Ξ±] : List Ξ± β†’ List Ξ± := pwFilter (Β· β‰  Β·) /-- Greedily create a sublist of `a :: l` such that, for every two adjacent elements `a, b`, `R a b` holds. Mostly used with β‰ ; for example, `destutter' (β‰ ) 1 [2, 2, 1, 1] = [1, 2, 1]`, `destutter' (β‰ ) 1, [2, 3, 3] = [1, 2, 3]`, `destutter' (<) 1 [2, 5, 2, 3, 4, 9] = [1, 2, 5, 9]`. -/ def destutter' (R : Ξ± β†’ Ξ± β†’ Prop) [DecidableRel R] : Ξ± β†’ List Ξ± β†’ List Ξ± | a, [] => [a] | a, h :: l => if R a h then a :: destutter' R h l else destutter' R a l -- TODO: should below be "lazily"? -- TODO: Remove destutter' as we have removed chain' /-- Greedily create a sublist of `l` such that, for every two adjacent elements `a, b ∈ l`, `R a b` holds. Mostly used with β‰ ; for example, `destutter (β‰ ) [1, 2, 2, 1, 1] = [1, 2, 1]`, `destutter (β‰ ) [1, 2, 3, 3] = [1, 2, 3]`, `destutter (<) [1, 2, 5, 2, 3, 4, 9] = [1, 2, 5, 9]`. -/ def destutter (R : Ξ± β†’ Ξ± β†’ Prop) [DecidableRel R] : List Ξ± β†’ List Ξ± | h :: l => destutter' R h l | [] => [] section Choose variable (p : Ξ± β†’ Prop) [DecidablePred p] (l : List Ξ±) /-- Given a decidable predicate `p` and a proof of existence of `a ∈ l` such that `p a`, choose the first element with this property. This version returns both `a` and proofs of `a ∈ l` and `p a`. -/ def chooseX : βˆ€ l : List Ξ±, βˆ€ _ : βˆƒ a, a ∈ l ∧ p a, { a // a ∈ l ∧ p a } | [], hp => False.elim (Exists.elim hp fun _ h => not_mem_nil h.left) | l :: ls, hp => if pl : p l then ⟨l, ⟨mem_cons.mpr <| Or.inl rfl, pl⟩⟩ else -- pattern matching on `hx` too makes this not reducible! let ⟨a, ha⟩ := chooseX ls (hp.imp fun _ ⟨o, hβ‚‚βŸ© => ⟨(mem_cons.mp o).resolve_left fun e => pl <| e β–Έ hβ‚‚, hβ‚‚βŸ©) ⟨a, mem_cons.mpr <| Or.inr ha.1, ha.2⟩ /-- Given a decidable predicate `p` and a proof of existence of `a ∈ l` such that `p a`, choose the first element with this property. This version returns `a : Ξ±`, and properties are given by `choose_mem` and `choose_property`. -/ def choose (hp : βˆƒ a, a ∈ l ∧ p a) : Ξ± := chooseX p l hp end Choose /-- `mapDiagM' f l` calls `f` on all elements in the upper triangular part of `l Γ— l`. That is, for each `e ∈ l`, it will run `f e e` and then `f e e'` for each `e'` that appears after `e` in `l`. Example: suppose `l = [1, 2, 3]`. `mapDiagM' f l` will evaluate, in this order, `f 1 1`, `f 1 2`, `f 1 3`, `f 2 2`, `f 2 3`, `f 3 3`. -/ def mapDiagM' {m} [Monad m] {Ξ±} (f : Ξ± β†’ Ξ± β†’ m Unit) : List Ξ± β†’ m Unit | [] => return () | h :: t => do _ ← f h h _ ← t.mapM' (f h) t.mapDiagM' f -- as ported: -- | [] => return () -- | h :: t => (f h h >> t.mapM' (f h)) >> t.mapDiagM' /-- Left-biased version of `List.mapβ‚‚`. `mapβ‚‚Left' f as bs` applies `f` to each pair of elements `aα΅’ ∈ as` and `bα΅’ ∈ bs`. If `bs` is shorter than `as`, `f` is applied to `none` for the remaining `aα΅’`. Returns the results of the `f` applications and the remaining `bs`. ``` mapβ‚‚Left' prod.mk [1, 2] ['a'] = ([(1, some 'a'), (2, none)], []) mapβ‚‚Left' prod.mk [1] ['a', 'b'] = ([(1, some 'a')], ['b']) ``` -/ @[simp] def mapβ‚‚Left' (f : Ξ± β†’ Option Ξ² β†’ Ξ³) : List Ξ± β†’ List Ξ² β†’ List Ξ³ Γ— List Ξ² | [], bs => ([], bs) | a :: as, [] => ((a :: as).map fun a => f a none, []) | a :: as, b :: bs => let rec' := mapβ‚‚Left' f as bs (f a (some b) :: rec'.fst, rec'.snd) /-- Right-biased version of `List.mapβ‚‚`. `mapβ‚‚Right' f as bs` applies `f` to each pair of elements `aα΅’ ∈ as` and `bα΅’ ∈ bs`. If `as` is shorter than `bs`, `f` is applied to `none` for the remaining `bα΅’`. Returns the results of the `f` applications and the remaining `as`. ``` mapβ‚‚Right' prod.mk [1] ['a', 'b'] = ([(some 1, 'a'), (none, 'b')], []) mapβ‚‚Right' prod.mk [1, 2] ['a'] = ([(some 1, 'a')], [2]) ``` -/ def mapβ‚‚Right' (f : Option Ξ± β†’ Ξ² β†’ Ξ³) (as : List Ξ±) (bs : List Ξ²) : List Ξ³ Γ— List Ξ± := mapβ‚‚Left' (flip f) bs as /-- Left-biased version of `List.mapβ‚‚`. `mapβ‚‚Left f as bs` applies `f` to each pair `aα΅’ ∈ as` and `bα΅’ ∈ bs`. If `bs` is shorter than `as`, `f` is applied to `none` for the remaining `aα΅’`. ``` mapβ‚‚Left Prod.mk [1, 2] ['a'] = [(1, some 'a'), (2, none)] mapβ‚‚Left Prod.mk [1] ['a', 'b'] = [(1, some 'a')] mapβ‚‚Left f as bs = (mapβ‚‚Left' f as bs).fst ``` -/ @[simp] def mapβ‚‚Left (f : Ξ± β†’ Option Ξ² β†’ Ξ³) : List Ξ± β†’ List Ξ² β†’ List Ξ³ | [], _ => [] | a :: as, [] => (a :: as).map fun a => f a none | a :: as, b :: bs => f a (some b) :: mapβ‚‚Left f as bs /-- Right-biased version of `List.mapβ‚‚`. `mapβ‚‚Right f as bs` applies `f` to each pair `aα΅’ ∈ as` and `bα΅’ ∈ bs`. If `as` is shorter than `bs`, `f` is applied to `none` for the remaining `bα΅’`. ``` mapβ‚‚Right Prod.mk [1, 2] ['a'] = [(some 1, 'a')] mapβ‚‚Right Prod.mk [1] ['a', 'b'] = [(some 1, 'a'), (none, 'b')] mapβ‚‚Right f as bs = (mapβ‚‚Right' f as bs).fst ``` -/ def mapβ‚‚Right (f : Option Ξ± β†’ Ξ² β†’ Ξ³) (as : List Ξ±) (bs : List Ξ²) : List Ξ³ := mapβ‚‚Left (flip f) bs as -- TODO: naming is awkward... /-- Asynchronous version of `List.map`. -/ def mapAsyncChunked {Ξ± Ξ²} (f : Ξ± β†’ Ξ²) (xs : List Ξ±) (chunk_size := 1024) : List Ξ² := ((xs.toChunks chunk_size).map fun xs => Task.spawn fun _ => List.map f xs).flatMap Task.get /-! We add some n-ary versions of `List.zipWith` for functions with more than two arguments. These can also be written in terms of `List.zip` or `List.zipWith`. For example, `zipWith3 f xs ys zs` could also be written as `zipWith id (zipWith f xs ys) zs` or as `(zip xs <| zip ys zs).map <| fun ⟨x, y, z⟩ ↦ f x y z`. -/ /-- Ternary version of `List.zipWith`. -/ def zipWith3 (f : Ξ± β†’ Ξ² β†’ Ξ³ β†’ Ξ΄) : List Ξ± β†’ List Ξ² β†’ List Ξ³ β†’ List Ξ΄ | x :: xs, y :: ys, z :: zs => f x y z :: zipWith3 f xs ys zs | _, _, _ => [] /-- Quaternary version of `list.zipWith`. -/ def zipWith4 (f : Ξ± β†’ Ξ² β†’ Ξ³ β†’ Ξ΄ β†’ Ξ΅) : List Ξ± β†’ List Ξ² β†’ List Ξ³ β†’ List Ξ΄ β†’ List Ξ΅ | x :: xs, y :: ys, z :: zs, u :: us => f x y z u :: zipWith4 f xs ys zs us | _, _, _, _ => [] /-- Quinary version of `list.zipWith`. -/ def zipWith5 (f : Ξ± β†’ Ξ² β†’ Ξ³ β†’ Ξ΄ β†’ Ξ΅ β†’ ΞΆ) : List Ξ± β†’ List Ξ² β†’ List Ξ³ β†’ List Ξ΄ β†’ List Ξ΅ β†’ List ΞΆ | x :: xs, y :: ys, z :: zs, u :: us, v :: vs => f x y z u v :: zipWith5 f xs ys zs us vs | _, _, _, _, _ => [] /-- Given a starting list `old`, a list of Booleans and a replacement list `new`, read the items in `old` in succession and either replace them with the next element of `new` or not, according as to whether the corresponding Boolean is `true` or `false`. -/ def replaceIf : List Ξ± β†’ List Bool β†’ List Ξ± β†’ List Ξ± | l, _, [] => l | [], _, _ => [] | l, [], _ => l | n :: ns, tf :: bs, e@(c :: cs) => if tf then c :: ns.replaceIf bs cs else n :: ns.replaceIf bs e /-- `iterate f a n` is `[a, f a, ..., f^[n - 1] a]`. -/ @[simp] def iterate (f : Ξ± β†’ Ξ±) (a : Ξ±) : (n : β„•) β†’ List Ξ± | 0 => [] | n + 1 => a :: iterate f (f a) n /-- Tail-recursive version of `List.iterate`. -/ @[inline] def iterateTR (f : Ξ± β†’ Ξ±) (a : Ξ±) (n : β„•) : List Ξ± := loop a n [] where /-- `iterateTR.loop f a n l := iterate f a n ++ reverse l`. -/ @[simp, specialize] loop (a : Ξ±) (n : β„•) (l : List Ξ±) : List Ξ± := match n with | 0 => reverse l | n + 1 => loop (f a) n (a :: l) theorem iterateTR_loop_eq (f : Ξ± β†’ Ξ±) (a : Ξ±) (n : β„•) (l : List Ξ±) : iterateTR.loop f a n l = reverse l ++ iterate f a n := by induction n generalizing a l <;> simp [*] @[csimp] theorem iterate_eq_iterateTR : @iterate = @iterateTR := by funext Ξ± f a n exact Eq.symm <| iterateTR_loop_eq f a n [] section MapAccumr /-- Runs a function over a list returning the intermediate results and a final result. -/ def mapAccumr (f : Ξ± β†’ Ξ³ β†’ Ξ³ Γ— Ξ²) : List Ξ± β†’ Ξ³ β†’ Ξ³ Γ— List Ξ² | [], c => (c, []) | y :: yr, c => let r := mapAccumr f yr c let z := f y r.1 (z.1, z.2 :: r.2) /-- Length of the list obtained by `mapAccumr`. -/ @[simp] theorem length_mapAccumr : βˆ€ (f : Ξ± β†’ Ξ³ β†’ Ξ³ Γ— Ξ²) (x : List Ξ±) (s : Ξ³), length (mapAccumr f x s).2 = length x | f, _ :: x, s => congr_arg succ (length_mapAccumr f x s) | _, [], _ => rfl /-- Runs a function over two lists returning the intermediate results and a final result. -/ def mapAccumrβ‚‚ (f : Ξ± β†’ Ξ² β†’ Ξ³ β†’ Ξ³ Γ— Ξ΄) : List Ξ± β†’ List Ξ² β†’ Ξ³ β†’ Ξ³ Γ— List Ξ΄ | [], _, c => (c, []) | _, [], c => (c, []) | x :: xr, y :: yr, c => let r := mapAccumrβ‚‚ f xr yr c let q := f x y r.1 (q.1, q.2 :: r.2) /-- Length of a list obtained using `mapAccumrβ‚‚`. -/ @[simp] theorem length_mapAccumrβ‚‚ : βˆ€ (f : Ξ± β†’ Ξ² β†’ Ξ³ β†’ Ξ³ Γ— Ξ΄) (x y c), length (mapAccumrβ‚‚ f x y c).2 = min (length x) (length y) | f, _ :: x, _ :: y, c => calc succ (length (mapAccumrβ‚‚ f x y c).2) = succ (min (length x) (length y)) := congr_arg succ (length_mapAccumrβ‚‚ f x y c) _ = min (succ (length x)) (succ (length y)) := Eq.symm (succ_min_succ (length x) (length y)) | _, _ :: _, [], _ => rfl | _, [], _ :: _, _ => rfl | _, [], [], _ => rfl end MapAccumr end List
.lake/packages/mathlib/Mathlib/Data/List/GetD.lean
import Mathlib.Data.List.Defs import Mathlib.Data.Option.Basic import Mathlib.Util.AssertExists /-! # getD and getI This file provides theorems for working with the `getD` and `getI` functions. These are used to access an element of a list by numerical index, with a default value as a fallback when the index is out of range. -/ assert_not_imported Mathlib.Algebra.Order.Group.Nat namespace List universe u v variable {Ξ± : Type u} {Ξ² : Type v} (l : List Ξ±) (x : Ξ±) (xs : List Ξ±) (n : β„•) section getD variable (d : Ξ±) theorem getD_eq_getElem {n : β„•} (hn : n < l.length) : l.getD n d = l[n] := by grind theorem getD_map {n : β„•} (f : Ξ± β†’ Ξ²) : (map f l).getD n (f d) = f (l.getD n d) := by simp theorem getD_eq_default {n : β„•} (hn : l.length ≀ n) : l.getD n d = d := by grind theorem getD_reverse {l : List Ξ±} (i) (h : i < length l) : getD l.reverse i = getD l (l.length - 1 - i) := by funext a rwa [List.getD_eq_getElem?_getD, List.getElem?_reverse, ← List.getD_eq_getElem?_getD] /-- An empty list can always be decidably checked for the presence of an element. Not an instance because it would clash with `DecidableEq Ξ±`. -/ def decidableGetDNilNe (a : Ξ±) : DecidablePred fun i : β„• => getD ([] : List Ξ±) i a β‰  a := fun _ => isFalse fun H => H getD_nil @[simp] theorem getElem?_getD_singleton_default_eq (n : β„•) : [d][n]?.getD d = d := by cases n <;> simp @[simp] theorem getElem?_getD_replicate_default_eq (r n : β„•) : (replicate r d)[n]?.getD d = d := by grind theorem getD_replicate {y i n} (h : i < n) : getD (replicate n x) i y = x := by rw [getD_eq_getElem, getElem_replicate] rwa [length_replicate] theorem getD_append (l l' : List Ξ±) (d : Ξ±) (n : β„•) (h : n < l.length) : (l ++ l').getD n d = l.getD n d := by rw [getD_eq_getElem _ _ (Nat.lt_of_lt_of_le h (length_append β–Έ Nat.le_add_right _ _)), getElem_append_left h, getD_eq_getElem] theorem getD_append_right (l l' : List Ξ±) (d : Ξ±) (n : β„•) (h : l.length ≀ n) : (l ++ l').getD n d = l'.getD (n - l.length) d := by grind theorem getD_eq_getD_getElem? (n : β„•) : l.getD n d = l[n]?.getD d := by cases Nat.lt_or_ge n l.length with | inl h => rw [getD_eq_getElem _ _ h, getElem?_eq_getElem h, Option.getD_some] | inr h => rw [getD_eq_default _ _ h, getElem?_eq_none_iff.mpr h, Option.getD_none] theorem getD_surjective_iff {l : List Ξ±} {d : Ξ±} : (l.getD Β· d).Surjective ↔ (βˆ€ x, x = d ∨ x ∈ l) := by apply forall_congr' have : βˆƒ x, l.length ≀ x := ⟨_, Nat.le_refl _⟩ simp only [getD_eq_getElem?_getD, getD_getElem?, dite_eq_iff, Nat.not_lt, exists_prop, exists_or, exists_and_right, this, mem_iff_getElem?, getElem?_eq_some_iff] grind theorem getD_surjective {l : List Ξ±} (h : βˆ€ x, x ∈ l) (d : Ξ±) : (l.getD Β· d).Surjective := getD_surjective_iff.mpr fun _ ↦ .inr <| h _ end getD section getI variable [Inhabited Ξ±] @[simp] theorem getI_nil : getI ([] : List Ξ±) n = default := rfl @[simp] theorem getI_cons_zero : getI (x :: xs) 0 = x := rfl @[simp] theorem getI_cons_succ : getI (x :: xs) (n + 1) = getI xs n := rfl theorem getI_eq_getElem {n : β„•} (hn : n < l.length) : l.getI n = l[n] := getD_eq_getElem l default hn theorem getI_eq_default {n : β„•} (hn : l.length ≀ n) : l.getI n = default := getD_eq_default _ _ hn theorem getD_default_eq_getI {n : β„•} : l.getD n default = l.getI n := rfl theorem getI_append (l l' : List Ξ±) (n : β„•) (h : n < l.length) : (l ++ l').getI n = l.getI n := getD_append _ _ _ _ h theorem getI_append_right (l l' : List Ξ±) (n : β„•) (h : l.length ≀ n) : (l ++ l').getI n = l'.getI (n - l.length) := getD_append_right _ _ _ _ h theorem getI_eq_iget_getElem? (n : β„•) : l.getI n = l[n]?.iget := by rw [← getD_default_eq_getI, getD_eq_getD_getElem?, Option.getD_default_eq_iget] theorem getI_zero_eq_headI : l.getI 0 = l.headI := by cases l <;> rfl end getI end List
.lake/packages/mathlib/Mathlib/Data/List/Infix.lean
import Mathlib.Data.List.TakeDrop import Mathlib.Data.List.Induction import Mathlib.Data.Nat.Basic import Mathlib.Order.Basic /-! # Prefixes, suffixes, infixes This file proves properties about * `List.isPrefix`: `l₁` is a prefix of `lβ‚‚` if `lβ‚‚` starts with `l₁`. * `List.isSuffix`: `l₁` is a suffix of `lβ‚‚` if `lβ‚‚` ends with `l₁`. * `List.isInfix`: `l₁` is an infix of `lβ‚‚` if `l₁` is a prefix of some suffix of `lβ‚‚`. * `List.inits`: The list of prefixes of a list. * `List.tails`: The list of prefixes of a list. * `insert` on lists All those (except `insert`) are defined in `Mathlib/Data/List/Defs.lean`. ## Notation * `l₁ <+: lβ‚‚`: `l₁` is a prefix of `lβ‚‚`. * `l₁ <:+ lβ‚‚`: `l₁` is a suffix of `lβ‚‚`. * `l₁ <:+: lβ‚‚`: `l₁` is an infix of `lβ‚‚`. -/ variable {Ξ± Ξ² : Type*} namespace List variable {l l₁ lβ‚‚ l₃ : List Ξ±} {a b : Ξ±} /-! ### prefix, suffix, infix -/ section Fix @[gcongr] lemma IsPrefix.take (h : l₁ <+: lβ‚‚) (n : β„•) : l₁.take n <+: lβ‚‚.take n := by simpa [prefix_take_iff, Nat.min_le_left] using (take_prefix n l₁).trans h @[gcongr] lemma IsPrefix.drop (h : l₁ <+: lβ‚‚) (n : β„•) : l₁.drop n <+: lβ‚‚.drop n := by rw [prefix_iff_eq_take.mp h, drop_take]; apply take_prefix attribute [gcongr] take_prefix_take_left lemma isPrefix_append_of_length (h : l₁.length ≀ lβ‚‚.length) : l₁ <+: lβ‚‚ ++ l₃ ↔ l₁ <+: lβ‚‚ := ⟨fun h ↦ by rw [prefix_iff_eq_take] at *; nth_rw 1 [h, take_eq_left_iff]; tauto, fun h ↦ h.trans <| lβ‚‚.prefix_append lβ‚ƒβŸ© @[simp] lemma take_isPrefix_take {m n : β„•} : l.take m <+: l.take n ↔ m ≀ n ∨ l.length ≀ n := by simp [prefix_take_iff, take_prefix]; omega @[gcongr] protected theorem IsPrefix.flatten {l₁ lβ‚‚ : List (List Ξ±)} (h : l₁ <+: lβ‚‚) : l₁.flatten <+: lβ‚‚.flatten := by rcases h with ⟨l, rfl⟩ simp @[gcongr] protected theorem IsPrefix.flatMap (h : l₁ <+: lβ‚‚) (f : Ξ± β†’ List Ξ²) : l₁.flatMap f <+: lβ‚‚.flatMap f := (h.map _).flatten @[gcongr] protected theorem IsSuffix.flatten {l₁ lβ‚‚ : List (List Ξ±)} (h : l₁ <:+ lβ‚‚) : l₁.flatten <:+ lβ‚‚.flatten := by rcases h with ⟨l, rfl⟩ simp @[gcongr] protected theorem IsSuffix.flatMap (h : l₁ <:+ lβ‚‚) (f : Ξ± β†’ List Ξ²) : l₁.flatMap f <:+ lβ‚‚.flatMap f := (h.map _).flatten @[gcongr] protected theorem IsInfix.flatten {l₁ lβ‚‚ : List (List Ξ±)} (h : l₁ <:+: lβ‚‚) : l₁.flatten <:+: lβ‚‚.flatten := by rcases h with ⟨l, l', rfl⟩ simp @[gcongr] protected theorem IsInfix.flatMap (h : l₁ <:+: lβ‚‚) (f : Ξ± β†’ List Ξ²) : l₁.flatMap f <:+: lβ‚‚.flatMap f := (h.map _).flatten lemma dropSlice_sublist (n m : β„•) (l : List Ξ±) : l.dropSlice n m <+ l := calc l.dropSlice n m = take n l ++ drop m (drop n l) := by rw [dropSlice_eq, drop_drop, Nat.add_comm] _ <+ take n l ++ drop n l := (Sublist.refl _).append (drop_sublist _ _) _ = _ := take_append_drop _ _ lemma dropSlice_subset (n m : β„•) (l : List Ξ±) : l.dropSlice n m βŠ† l := (dropSlice_sublist n m l).subset lemma mem_of_mem_dropSlice {n m : β„•} {l : List Ξ±} {a : Ξ±} (h : a ∈ l.dropSlice n m) : a ∈ l := dropSlice_subset n m l h theorem tail_subset (l : List Ξ±) : tail l βŠ† l := (tail_sublist l).subset theorem mem_of_mem_dropLast (h : a ∈ l.dropLast) : a ∈ l := dropLast_subset l h attribute [gcongr] Sublist.drop attribute [refl] prefix_refl suffix_refl infix_refl theorem concat_get_prefix {x y : List Ξ±} (h : x <+: y) (hl : x.length < y.length) : x ++ [y.get ⟨x.length, hl⟩] <+: y := by use y.drop (x.length + 1) nth_rw 1 [List.prefix_iff_eq_take.mp h] convert List.take_append_drop (x.length + 1) y using 2 rw [← List.take_concat_get, List.concat_eq_append]; rfl theorem prefix_append_drop {l₁ lβ‚‚ : List Ξ±} (h : l₁ <+: lβ‚‚) : lβ‚‚ = l₁ ++ lβ‚‚.drop l₁.length := by induction lβ‚‚ generalizing l₁ with | nil => simp [List.prefix_nil.mp h] | cons _ _ ih => cases l₁ with | nil => rfl | cons => obtain ⟨rfl, h'⟩ := List.cons_prefix_cons.mp h simpa using ih h' instance decidableInfix [DecidableEq Ξ±] : βˆ€ l₁ lβ‚‚ : List Ξ±, Decidable (l₁ <:+: lβ‚‚) | [], lβ‚‚ => isTrue ⟨[], lβ‚‚, rfl⟩ | a :: l₁, [] => isFalse fun ⟨s, t, te⟩ => by simp at te | l₁, b :: lβ‚‚ => letI := l₁.decidableInfix lβ‚‚ @decidable_of_decidable_of_iff (l₁ <+: b :: lβ‚‚ ∨ l₁ <:+: lβ‚‚) _ _ infix_cons_iff.symm protected theorem IsPrefix.reduceOption {l₁ lβ‚‚ : List (Option Ξ±)} (h : l₁ <+: lβ‚‚) : l₁.reduceOption <+: lβ‚‚.reduceOption := h.filterMap id theorem singleton_infix_iff (x : Ξ±) (xs : List Ξ±) : [x] <:+: xs ↔ x ∈ xs := by rw [List.mem_iff_append, List.IsInfix] congr! 4 simp [eq_comm] @[simp] theorem singleton_infix_singleton_iff {x y : Ξ±} : [x] <:+: [y] ↔ x = y := by constructor Β· rintro ⟨_ | _, bs, h⟩ <;> simp_all Β· rintro rfl; rfl theorem infix_singleton_iff (xs : List Ξ±) (x : Ξ±) : xs <:+: [x] ↔ xs = [] ∨ xs = [x] := by match xs with | [] => simp | [_] => simp [List.singleton_infix_singleton_iff] | _ :: _ :: _ => constructor Β· rintro ⟨_ | _, _, h⟩ <;> simp at h Β· simp lemma infix_antisymm {l₁ lβ‚‚ : List Ξ±} (h₁ : l₁ <:+: lβ‚‚) (hβ‚‚ : lβ‚‚ <:+: l₁) : l₁ = lβ‚‚ := h₁.sublist.antisymm hβ‚‚.sublist instance : IsPartialOrder (List Ξ±) (Β· <+: Β·) where refl _ := prefix_rfl trans _ _ _ := IsPrefix.trans antisymm _ _ h₁ hβ‚‚ := h₁.eq_of_length <| h₁.length_le.antisymm hβ‚‚.length_le instance : IsPartialOrder (List Ξ±) (Β· <:+ Β·) where refl _ := suffix_rfl trans _ _ _ := IsSuffix.trans antisymm _ _ h₁ hβ‚‚ := h₁.eq_of_length <| h₁.length_le.antisymm hβ‚‚.length_le instance : IsPartialOrder (List Ξ±) (Β· <:+: Β·) where refl _ := infix_rfl trans _ _ _ := IsInfix.trans antisymm _ _ h₁ hβ‚‚ := h₁.eq_of_length <| h₁.length_le.antisymm hβ‚‚.length_le end Fix section InitsTails @[simp] theorem mem_inits : βˆ€ s t : List Ξ±, s ∈ inits t ↔ s <+: t | s, [] => suffices s = nil ↔ s <+: nil by simpa only [inits, mem_singleton] ⟨fun h => h.symm β–Έ prefix_rfl, eq_nil_of_prefix_nil⟩ | s, a :: t => suffices (s = nil ∨ βˆƒ l ∈ inits t, a :: l = s) ↔ s <+: a :: t by simpa ⟨fun o => match s, o with | _, Or.inl rfl => ⟨_, rfl⟩ | s, Or.inr ⟨r, hr, hs⟩ => by let ⟨s, ht⟩ := (mem_inits _ _).1 hr rw [← hs, ← ht]; exact ⟨s, rfl⟩, fun mi => match s, mi with | [], ⟨_, rfl⟩ => Or.inl rfl | b :: s, ⟨r, hr⟩ => (List.noConfusion hr) fun ba (st : s ++ r = t) => Or.inr <| by rw [ba]; exact ⟨_, (mem_inits _ _).2 ⟨_, st⟩, rfl⟩⟩ @[simp] theorem mem_tails : βˆ€ s t : List Ξ±, s ∈ tails t ↔ s <:+ t | s, [] => by simp only [tails, mem_singleton, suffix_nil] | s, a :: t => by simp only [tails, mem_cons, mem_tails s t] exact show s = a :: t ∨ s <:+ t ↔ s <:+ a :: t from ⟨fun o => match s, t, o with | _, t, Or.inl rfl => suffix_rfl | s, _, Or.inr ⟨l, rfl⟩ => ⟨a :: l, rfl⟩, fun e => match s, t, e with | _, t, ⟨[], rfl⟩ => Or.inl rfl | s, t, ⟨b :: l, he⟩ => List.noConfusion he fun _ lt => Or.inr ⟨l, lt⟩⟩ theorem inits_cons (a : Ξ±) (l : List Ξ±) : inits (a :: l) = [] :: l.inits.map fun t => a :: t := by simp theorem tails_cons (a : Ξ±) (l : List Ξ±) : tails (a :: l) = (a :: l) :: l.tails := by simp @[simp] theorem inits_append : βˆ€ s t : List Ξ±, inits (s ++ t) = s.inits ++ t.inits.tail.map fun l => s ++ l | [], [] => by simp | [], a :: t => by simp | a :: s, t => by simp [inits_append s t, Function.comp_def] @[simp] theorem tails_append : βˆ€ s t : List Ξ±, tails (s ++ t) = (s.tails.map fun l => l ++ t) ++ t.tails.tail | [], [] => by simp | [], a :: t => by simp | a :: s, t => by simp [tails_append s t] -- the lemma names `inits_eq_tails` and `tails_eq_inits` are like `sublists_eq_sublists'` theorem inits_eq_tails : βˆ€ l : List Ξ±, l.inits = (reverse <| map reverse <| tails <| reverse l) | [] => by simp | a :: l => by simp [inits_eq_tails l, map_inj_left, ← map_reverse] theorem tails_eq_inits : βˆ€ l : List Ξ±, l.tails = (reverse <| map reverse <| inits <| reverse l) | [] => by simp | a :: l => by simp [tails_eq_inits l] theorem inits_reverse (l : List Ξ±) : inits (reverse l) = reverse (map reverse l.tails) := by rw [tails_eq_inits l] simp [← map_reverse] theorem tails_reverse (l : List Ξ±) : tails (reverse l) = reverse (map reverse l.inits) := by rw [inits_eq_tails l] simp [← map_reverse] theorem map_reverse_inits (l : List Ξ±) : map reverse l.inits = (reverse <| tails <| reverse l) := by rw [inits_eq_tails l] simp [← map_reverse] theorem map_reverse_tails (l : List Ξ±) : map reverse l.tails = (reverse <| inits <| reverse l) := by rw [tails_eq_inits l] simp [← map_reverse] @[simp] theorem length_tails (l : List Ξ±) : length (tails l) = length l + 1 := by induction l with | nil => simp | cons x l IH => simpa using IH @[simp] theorem length_inits (l : List Ξ±) : length (inits l) = length l + 1 := by simp [inits_eq_tails] @[simp] theorem getElem_tails (l : List Ξ±) (n : Nat) (h : n < (tails l).length) : (tails l)[n] = l.drop n := by induction l generalizing n with | nil => simp | cons a l ihl => cases n with | zero => simp | succ n => simp [ihl] theorem get_tails (l : List Ξ±) (n : Fin (length (tails l))) : (tails l).get n = l.drop n := by simp @[simp] theorem getElem_inits (l : List Ξ±) (n : Nat) (h : n < length (inits l)) : (inits l)[n] = l.take n := by induction l generalizing n with | nil => simp | cons a l ihl => cases n with | zero => simp | succ n => simp [ihl] theorem get_inits (l : List Ξ±) (n : Fin (length (inits l))) : (inits l).get n = l.take n := by simp lemma map_inits {Ξ² : Type*} (g : Ξ± β†’ Ξ²) : (l.map g).inits = l.inits.map (map g) := by induction l using reverseRecOn <;> simp [*] lemma map_tails {Ξ² : Type*} (g : Ξ± β†’ Ξ²) : (l.map g).tails = l.tails.map (map g) := by induction l using reverseRecOn <;> simp [*] lemma take_inits {n} : (l.take n).inits = l.inits.take (n + 1) := by apply ext_getElem <;> (simp [take_take] <;> omega) end InitsTails /-! ### insert -/ section Insert variable [DecidableEq Ξ±] theorem insert_eq_ite (a : Ξ±) (l : List Ξ±) : insert a l = if a ∈ l then l else a :: l := by simp only [← elem_iff] rfl @[simp] theorem suffix_insert (a : Ξ±) (l : List Ξ±) : l <:+ l.insert a := by by_cases h : a ∈ l Β· simp only [insert_of_mem h, suffix_refl] Β· simp only [insert_of_not_mem h, suffix_cons] theorem infix_insert (a : Ξ±) (l : List Ξ±) : l <:+: l.insert a := (suffix_insert a l).isInfix theorem sublist_insert (a : Ξ±) (l : List Ξ±) : l <+ l.insert a := (suffix_insert a l).sublist theorem subset_insert (a : Ξ±) (l : List Ξ±) : l βŠ† l.insert a := (sublist_insert a l).subset end Insert end List
.lake/packages/mathlib/Mathlib/Data/List/ChainOfFn.lean
import Mathlib.Data.List.Chain import Mathlib.Data.List.OfFn /-! # Lemmas about `IsChain` and `ofFn` This file provides lemmas involving both `List.IsChain` and `List.ofFn`. -/ open Nat namespace List lemma isChain_ofFn {Ξ± : Type*} {n : β„•} {f : Fin n β†’ Ξ±} {r : Ξ± β†’ Ξ± β†’ Prop} : (ofFn f).IsChain r ↔ βˆ€ (i) (hi : i + 1 < n), r (f ⟨i, lt_of_succ_lt hi⟩) (f ⟨i + 1, hi⟩) := by simp_rw [isChain_iff_get, get_ofFn, length_ofFn] exact ⟨fun h i hi ↦ h i (by cutsat), fun h i hi ↦ h i (by cutsat)⟩ @[deprecated (since := "2025-09-24")] alias chain'_ofFn := isChain_ofFn end List
.lake/packages/mathlib/Mathlib/Data/List/ModifyLast.lean
import Batteries.Data.List.Basic import Batteries.Tactic.Alias import Mathlib.Tactic.TypeStar /-! ### List.modifyLast -/ variable {Ξ± : Type*} namespace List private theorem modifyLast.go_concat (f : Ξ± β†’ Ξ±) (a : Ξ±) (tl : List Ξ±) (r : Array Ξ±) : modifyLast.go f (tl ++ [a]) r = (r.toListAppend <| modifyLast.go f (tl ++ [a]) #[]) := by cases tl with | nil => simp only [nil_append, modifyLast.go]; rfl | cons hd tl => simp only [cons_append] rw [modifyLast.go, modifyLast.go] case x_3 | x_3 => exact append_ne_nil_of_right_ne_nil tl (cons_ne_nil a []) rw [modifyLast.go_concat _ _ tl _, modifyLast.go_concat _ _ tl (Array.push #[] hd)] simp only [Array.toListAppend_eq, Array.toList_push, nil_append, append_assoc] theorem modifyLast_concat (f : Ξ± β†’ Ξ±) (a : Ξ±) (l : List Ξ±) : modifyLast f (l ++ [a]) = l ++ [f a] := by cases l with | nil => simp only [nil_append, modifyLast, modifyLast.go, Array.toListAppend_eq] | cons _ tl => simp only [cons_append, modifyLast] rw [modifyLast.go] case x_3 => exact append_ne_nil_of_right_ne_nil tl (cons_ne_nil a []) rw [modifyLast.go_concat, Array.toListAppend_eq, Array.toList_push, List.toList_toArray, nil_append, cons_append, nil_append, cons_inj_right] exact modifyLast_concat _ _ tl theorem modifyLast_append_of_right_ne_nil (f : Ξ± β†’ Ξ±) (l₁ lβ‚‚ : List Ξ±) (_ : lβ‚‚ β‰  []) : modifyLast f (l₁ ++ lβ‚‚) = l₁ ++ modifyLast f lβ‚‚ := by cases lβ‚‚ with | nil => contradiction | cons hd tl => cases tl with | nil => exact modifyLast_concat _ hd _ | cons hd' tl' => rw [append_cons, ← nil_append (hd :: hd' :: tl'), append_cons [], nil_append, modifyLast_append_of_right_ne_nil _ (l₁ ++ [hd]) (hd' :: tl') _, modifyLast_append_of_right_ne_nil _ [hd] (hd' :: tl') _, append_assoc] all_goals { exact cons_ne_nil _ _ } end List
.lake/packages/mathlib/Mathlib/Data/List/Map2.lean
import Mathlib.Data.List.Defs import Mathlib.Tactic.Common /-! # Mapβ‚‚ Lemmas This file contains additional lemmas about a number of list functions related to combining zipping Lists together. In particular, we include lemmas about: * `mapβ‚‚Left'` * `mapβ‚‚Right'` * `zipWith` * `zipLeft'` * `zipRight'` -/ assert_not_exists GroupWithZero assert_not_exists Lattice assert_not_exists Prod.swap_eq_iff_eq_swap assert_not_exists Ring assert_not_exists Set.range open Function open Nat hiding one_pos namespace List universe u v w variable {ΞΉ : Type*} {Ξ± : Type u} {Ξ² : Type v} {Ξ³ : Type w} {l₁ lβ‚‚ : List Ξ±} /-! ### mapβ‚‚Left' -/ section Mapβ‚‚Left' -- The definitional equalities for `mapβ‚‚Left'` can already be used by the -- simplifier because `mapβ‚‚Left'` is marked `@[simp]`. @[simp] theorem mapβ‚‚Left'_nil_right (f : Ξ± β†’ Option Ξ² β†’ Ξ³) (as) : mapβ‚‚Left' f as [] = (as.map fun a => f a none, []) := by cases as <;> rfl end Mapβ‚‚Left' /-! ### mapβ‚‚Right' -/ section Mapβ‚‚Right' variable (f : Option Ξ± β†’ Ξ² β†’ Ξ³) (a : Ξ±) (as : List Ξ±) (b : Ξ²) (bs : List Ξ²) @[simp] theorem mapβ‚‚Right'_nil_left : mapβ‚‚Right' f [] bs = (bs.map (f none), []) := by cases bs <;> rfl @[simp] theorem mapβ‚‚Right'_nil_right : mapβ‚‚Right' f as [] = ([], as) := rfl @[simp] theorem mapβ‚‚Right'_nil_cons : mapβ‚‚Right' f [] (b :: bs) = (f none b :: bs.map (f none), []) := rfl @[simp] theorem mapβ‚‚Right'_cons_cons : mapβ‚‚Right' f (a :: as) (b :: bs) = let r := mapβ‚‚Right' f as bs (f (some a) b :: r.fst, r.snd) := rfl end Mapβ‚‚Right' /-! ### zipWith -/ theorem nil_zipWith (f : Ξ± β†’ Ξ² β†’ Ξ³) (l : List Ξ²) : zipWith f [] l = [] := by cases l <;> rfl theorem zipWith_nil (f : Ξ± β†’ Ξ² β†’ Ξ³) (l : List Ξ±) : zipWith f l [] = [] := by cases l <;> rfl @[simp] theorem zipWith_flip (f : Ξ± β†’ Ξ² β†’ Ξ³) : βˆ€ as bs, zipWith (flip f) bs as = zipWith f as bs | [], [] => rfl | [], _ :: _ => rfl | _ :: _, [] => rfl | a :: as, b :: bs => by simp! [zipWith_flip] rfl /-! ### zipLeft' -/ section ZipLeft' variable (a : Ξ±) (as : List Ξ±) (b : Ξ²) (bs : List Ξ²) @[simp] theorem zipLeft'_nil_right : zipLeft' as ([] : List Ξ²) = (as.map fun a => (a, none), []) := by cases as <;> rfl @[simp] theorem zipLeft'_nil_left : zipLeft' ([] : List Ξ±) bs = ([], bs) := rfl @[simp] theorem zipLeft'_cons_nil : zipLeft' (a :: as) ([] : List Ξ²) = ((a, none) :: as.map fun a => (a, none), []) := rfl @[simp] theorem zipLeft'_cons_cons : zipLeft' (a :: as) (b :: bs) = let r := zipLeft' as bs ((a, some b) :: r.fst, r.snd) := rfl end ZipLeft' /-! ### zipRight' -/ section ZipRight' variable (a : Ξ±) (as : List Ξ±) (b : Ξ²) (bs : List Ξ²) @[simp] theorem zipRight'_nil_left : zipRight' ([] : List Ξ±) bs = (bs.map fun b => (none, b), []) := by cases bs <;> rfl @[simp] theorem zipRight'_nil_right : zipRight' as ([] : List Ξ²) = ([], as) := rfl @[simp] theorem zipRight'_nil_cons : zipRight' ([] : List Ξ±) (b :: bs) = ((none, b) :: bs.map fun b => (none, b), []) := rfl @[simp] theorem zipRight'_cons_cons : zipRight' (a :: as) (b :: bs) = let r := zipRight' as bs ((some a, b) :: r.fst, r.snd) := rfl end ZipRight' /-! ### mapβ‚‚Left -/ section Mapβ‚‚Left variable (f : Ξ± β†’ Option Ξ² β†’ Ξ³) (as : List Ξ±) -- The definitional equalities for `mapβ‚‚Left` can already be used by the -- simplifier because `mapβ‚‚Left` is marked `@[simp]`. @[simp] theorem mapβ‚‚Left_nil_right : mapβ‚‚Left f as [] = as.map fun a => f a none := by cases as <;> rfl theorem mapβ‚‚Left_eq_mapβ‚‚Left' : βˆ€ as bs, mapβ‚‚Left f as bs = (mapβ‚‚Left' f as bs).fst | [], _ => by simp | a :: as, [] => by simp | a :: as, b :: bs => by simp [mapβ‚‚Left_eq_mapβ‚‚Left'] theorem mapβ‚‚Left_eq_zipWith : βˆ€ as bs, length as ≀ length bs β†’ mapβ‚‚Left f as bs = zipWith (fun a b => f a (some b)) as bs | [], [], _ => by simp | [], _ :: _, _ => by simp | a :: as, [], h => by simp at h | a :: as, b :: bs, h => by simp only [length_cons, succ_le_succ_iff] at h simp [h, mapβ‚‚Left_eq_zipWith] end Mapβ‚‚Left /-! ### mapβ‚‚Right -/ section Mapβ‚‚Right variable (f : Option Ξ± β†’ Ξ² β†’ Ξ³) (a : Ξ±) (as : List Ξ±) (b : Ξ²) (bs : List Ξ²) @[simp] theorem mapβ‚‚Right_nil_left : mapβ‚‚Right f [] bs = bs.map (f none) := by cases bs <;> rfl @[simp] theorem mapβ‚‚Right_nil_right : mapβ‚‚Right f as [] = [] := rfl @[simp] theorem mapβ‚‚Right_nil_cons : mapβ‚‚Right f [] (b :: bs) = f none b :: bs.map (f none) := rfl @[simp] theorem mapβ‚‚Right_cons_cons : mapβ‚‚Right f (a :: as) (b :: bs) = f (some a) b :: mapβ‚‚Right f as bs := rfl theorem mapβ‚‚Right_eq_mapβ‚‚Right' : mapβ‚‚Right f as bs = (mapβ‚‚Right' f as bs).fst := by simp only [mapβ‚‚Right, mapβ‚‚Right', mapβ‚‚Left_eq_mapβ‚‚Left'] theorem mapβ‚‚Right_eq_zipWith (h : length bs ≀ length as) : mapβ‚‚Right f as bs = zipWith (fun a b => f (some a) b) as bs := by have : (fun a b => flip f a (some b)) = flip fun a b => f (some a) b := rfl simp only [mapβ‚‚Right, mapβ‚‚Left_eq_zipWith, zipWith_flip, *] end Mapβ‚‚Right /-! ### zipLeft -/ section ZipLeft variable (a : Ξ±) (as : List Ξ±) (b : Ξ²) (bs : List Ξ²) @[simp] theorem zipLeft_nil_right : zipLeft as ([] : List Ξ²) = as.map fun a => (a, none) := by cases as <;> rfl @[simp] theorem zipLeft_nil_left : zipLeft ([] : List Ξ±) bs = [] := rfl @[simp] theorem zipLeft_cons_nil : zipLeft (a :: as) ([] : List Ξ²) = (a, none) :: as.map fun a => (a, none) := rfl @[simp] theorem zipLeft_cons_cons : zipLeft (a :: as) (b :: bs) = (a, some b) :: zipLeft as bs := rfl theorem zipLeft_eq_zipLeft' (as : List Ξ±) (bs : List Ξ²) : zipLeft as bs = (zipLeft' as bs).fst := by rw [zipLeft, zipLeft'] cases as with | nil => rfl | cons _ atl => cases bs with | nil => rfl | cons _ btl => rw [zipWithLeft, zipWithLeft', cons_inj_right] exact zipLeft_eq_zipLeft' atl btl end ZipLeft /-! ### zipRight -/ section ZipRight variable (a : Ξ±) (as : List Ξ±) (b : Ξ²) (bs : List Ξ²) @[simp] theorem zipRight_nil_left : zipRight ([] : List Ξ±) bs = bs.map fun b => (none, b) := by cases bs <;> rfl @[simp] theorem zipRight_nil_right : zipRight as ([] : List Ξ²) = [] := rfl @[simp] theorem zipRight_nil_cons : zipRight ([] : List Ξ±) (b :: bs) = (none, b) :: bs.map fun b => (none, b) := rfl @[simp] theorem zipRight_cons_cons : zipRight (a :: as) (b :: bs) = (some a, b) :: zipRight as bs := rfl theorem zipRight_eq_zipRight' : zipRight as bs = (zipRight' as bs).fst := by induction as generalizing bs <;> cases bs <;> simp [*] end ZipRight end List
.lake/packages/mathlib/Mathlib/Data/List/ToFinsupp.lean
import Mathlib.Algebra.Group.Embedding import Mathlib.Algebra.Group.Finsupp import Mathlib.Algebra.Group.Nat.Defs import Mathlib.Data.List.GetD /-! # Lists as finsupp ## Main definitions - `List.toFinsupp`: Interpret a list as a finitely supported function, where the indexing type is `β„•`, and the values are either the elements of the list (accessing by indexing) or `0` outside of the list. ## Main theorems - `List.toFinsupp_eq_sum_map_enum_single`: A `l : List M` over `M` an `AddMonoid`, when interpreted as a finitely supported function, is equal to the sum of `Finsupp.single` produced by mapping over `List.enum l`. ## Implementation details The functions defined here rely on a decidability predicate that each element in the list can be decidably determined to be not equal to zero or that one can decide one is out of the bounds of a list. For concretely defined lists that are made up of elements of decidable terms, this holds. More work will be needed to support lists over non-dec-eq types like `ℝ`, where the elements are beyond the dec-eq terms of casted values from `β„•, β„€, β„š`. -/ namespace List variable {M : Type*} [Zero M] (l : List M) [DecidablePred (getD l Β· 0 β‰  0)] (n : β„•) /-- Indexing into a `l : List M`, as a finitely-supported function, where the support are all the indices within the length of the list that index to a non-zero value. Indices beyond the end of the list are sent to 0. This is a computable version of the `Finsupp.onFinset` construction. -/ def toFinsupp : β„• β†’β‚€ M where toFun i := getD l i 0 support := {i ∈ Finset.range l.length | getD l i 0 β‰  0} mem_support_toFun n := by simp only [Ne, Finset.mem_filter, Finset.mem_range, and_iff_right_iff_imp] contrapose! exact getD_eq_default _ _ @[norm_cast] theorem coe_toFinsupp : (l.toFinsupp : β„• β†’ M) = (l.getD Β· 0) := rfl @[simp, norm_cast] theorem toFinsupp_apply (i : β„•) : (l.toFinsupp : β„• β†’ M) i = l.getD i 0 := rfl theorem toFinsupp_support : l.toFinsupp.support = {i ∈ Finset.range l.length | getD l i 0 β‰  0} := rfl theorem toFinsupp_apply_lt (hn : n < l.length) : l.toFinsupp n = l[n] := getD_eq_getElem _ _ hn theorem toFinsupp_apply_fin (n : Fin l.length) : l.toFinsupp n = l[n] := getD_eq_getElem _ _ n.isLt theorem toFinsupp_apply_le (hn : l.length ≀ n) : l.toFinsupp n = 0 := getD_eq_default _ _ hn @[simp] theorem toFinsupp_nil [DecidablePred fun i => getD ([] : List M) i 0 β‰  0] : toFinsupp ([] : List M) = 0 := by ext simp theorem toFinsupp_singleton (x : M) [DecidablePred (getD [x] Β· 0 β‰  0)] : toFinsupp [x] = Finsupp.single 0 x := by ext ⟨_ | i⟩ <;> simp theorem toFinsupp_append {R : Type*} [AddZeroClass R] (l₁ lβ‚‚ : List R) [DecidablePred (getD (l₁ ++ lβ‚‚) Β· 0 β‰  0)] [DecidablePred (getD l₁ Β· 0 β‰  0)] [DecidablePred (getD lβ‚‚ Β· 0 β‰  0)] : toFinsupp (l₁ ++ lβ‚‚) = toFinsupp l₁ + (toFinsupp lβ‚‚).embDomain (addLeftEmbedding l₁.length) := by ext n simp only [toFinsupp_apply, Finsupp.add_apply] cases lt_or_ge n l₁.length with | inl h => rw [getD_append _ _ _ _ h, Finsupp.embDomain_notin_range, add_zero] rintro ⟨k, rfl : length l₁ + k = n⟩ cutsat | inr h => rcases Nat.exists_eq_add_of_le h with ⟨k, rfl⟩ rw [getD_append_right _ _ _ _ h, Nat.add_sub_cancel_left, getD_eq_default _ _ h, zero_add] exact Eq.symm (Finsupp.embDomain_apply _ _ _) theorem toFinsupp_cons_eq_single_add_embDomain {R : Type*} [AddZeroClass R] (x : R) (xs : List R) [DecidablePred (getD (x::xs) Β· 0 β‰  0)] [DecidablePred (getD xs Β· 0 β‰  0)] : toFinsupp (x::xs) = Finsupp.single 0 x + (toFinsupp xs).embDomain ⟨Nat.succ, Nat.succ_injective⟩ := by classical convert toFinsupp_append [x] xs using 3 Β· exact (toFinsupp_singleton x).symm Β· ext n exact add_comm n 1 theorem toFinsupp_concat_eq_toFinsupp_add_single {R : Type*} [AddZeroClass R] (x : R) (xs : List R) [DecidablePred fun i => getD (xs ++ [x]) i 0 β‰  0] [DecidablePred fun i => getD xs i 0 β‰  0] : toFinsupp (xs ++ [x]) = toFinsupp xs + Finsupp.single xs.length x := by classical rw [toFinsupp_append, toFinsupp_singleton, Finsupp.embDomain_single, addLeftEmbedding_apply, add_zero] theorem toFinsupp_eq_sum_mapIdx_single {R : Type*} [AddMonoid R] (l : List R) [DecidablePred (getD l Β· 0 β‰  0)] : toFinsupp l = (l.mapIdx fun n r => Finsupp.single n r).sum := by /- Porting note: `induction` fails to substitute `l = []` in `[DecidablePred (getD l Β· 0 β‰  0)]`, so we manually do some `revert`/`intro` as a workaround -/ revert l; intro l induction l using List.reverseRecOn with | nil => exact toFinsupp_nil | append_singleton x xs ih => classical simp [toFinsupp_concat_eq_toFinsupp_add_single, sum_append, ih] end List
.lake/packages/mathlib/Mathlib/Data/List/SplitBy.lean
import Mathlib.Data.List.Chain /-! # Split a list into contiguous runs of elements which pairwise satisfy a relation. This file provides the basic API for `List.splitBy` which is defined in Core. The main results are the following: - `List.flatten_splitBy`: the lists in `List.splitBy` join to the original list. - `List.nil_notMem_splitBy`: the empty list is not contained in `List.splitBy`. - `List.isChain_of_mem_splitBy`: any two adjacent elements in a list in `List.splitBy` are related by the specified relation. - `List.isChain_getLast_head_splitBy`: the last element of each list in `List.splitBy` is not related to the first element of the next list. -/ namespace List variable {Ξ± : Type*} {m : List Ξ±} @[simp] theorem splitBy_nil (r : Ξ± β†’ Ξ± β†’ Bool) : splitBy r [] = [] := rfl private theorem splitByLoop_eq_append {r : Ξ± β†’ Ξ± β†’ Bool} {l : List Ξ±} {a : Ξ±} {g : List Ξ±} (gs : List (List Ξ±)) : splitBy.loop r l a g gs = gs.reverse ++ splitBy.loop r l a g [] := by induction l generalizing a g gs with | nil => simp [splitBy.loop] | cons b l IH => simp_rw [splitBy.loop] split <;> rw [IH] conv_rhs => rw [IH] simp private theorem flatten_splitByLoop {r : Ξ± β†’ Ξ± β†’ Bool} {l : List Ξ±} {a : Ξ±} {g : List Ξ±} : (splitBy.loop r l a g []).flatten = g.reverse ++ a :: l := by induction l generalizing a g with | nil => simp [splitBy.loop] | cons b l IH => rw [splitBy.loop, splitByLoop_eq_append [_]] split <;> simp [IH] @[simp] theorem flatten_splitBy (r : Ξ± β†’ Ξ± β†’ Bool) (l : List Ξ±) : (l.splitBy r).flatten = l := match l with | nil => rfl | cons _ _ => flatten_splitByLoop private theorem nil_notMem_splitByLoop {r : Ξ± β†’ Ξ± β†’ Bool} {l : List Ξ±} {a : Ξ±} {g : List Ξ±} : [] βˆ‰ splitBy.loop r l a g [] := by induction l generalizing a g with | nil => simp [splitBy.loop] | cons b l IH => rw [splitBy.loop] split Β· exact IH Β· rw [splitByLoop_eq_append, mem_append] simpa using IH @[deprecated (since := "2025-05-23")] alias nil_not_mem_splitByLoop := nil_notMem_splitByLoop @[simp] theorem nil_notMem_splitBy (r : Ξ± β†’ Ξ± β†’ Bool) (l : List Ξ±) : [] βˆ‰ l.splitBy r := match l with | nil => not_mem_nil | cons _ _ => nil_notMem_splitByLoop @[deprecated (since := "2025-05-23")] alias nil_not_mem_splitBy := nil_notMem_splitBy theorem ne_nil_of_mem_splitBy {r : Ξ± β†’ Ξ± β†’ Bool} {l : List Ξ±} (h : m ∈ l.splitBy r) : m β‰  [] := fun _ ↦ by simp_all private theorem isChain_of_mem_splitByLoop {r : Ξ± β†’ Ξ± β†’ Bool} {l : List Ξ±} {a : Ξ±} {g : List Ξ±} (hga : βˆ€ b ∈ g.head?, r b a) (hg : g.IsChain fun y x ↦ r x y) (h : m ∈ splitBy.loop r l a g []) : m.IsChain fun x y ↦ r x y := by induction l generalizing a g with | nil => rw [splitBy.loop, reverse_cons, mem_append, mem_reverse, mem_singleton] at h obtain hm | rfl := h Β· cases not_mem_nil hm Β· apply List.isChain_reverse.1 rw [reverse_reverse] exact isChain_cons.2 ⟨hga, hg⟩ | cons b l IH => simp only [splitBy.loop, reverse_cons] at h split at h Β· apply IH _ (isChain_cons.2 ⟨hga, hg⟩) h grind Β· rw [splitByLoop_eq_append, mem_append, reverse_singleton, mem_singleton] at h obtain rfl | hm := h Β· apply List.isChain_reverse.1 rw [reverse_append, reverse_cons, reverse_nil, nil_append, reverse_reverse] exact isChain_cons.2 ⟨hga, hg⟩ Β· grind theorem isChain_of_mem_splitBy {r : Ξ± β†’ Ξ± β†’ Bool} {l : List Ξ±} (h : m ∈ l.splitBy r) : m.IsChain fun x y ↦ r x y := by match l, h with | a::l, h => apply isChain_of_mem_splitByLoop _ _ h <;> simp @[deprecated (since := "2025-09-24")] alias chain'_of_mem_splitBy := isChain_of_mem_splitBy private theorem isChain_getLast_head_splitByLoop {r : Ξ± β†’ Ξ± β†’ Bool} (l : List Ξ±) {a : Ξ±} {g : List Ξ±} {gs : List (List Ξ±)} (hgs' : [] βˆ‰ gs) (hgs : gs.IsChain fun b a ↦ βˆƒ ha hb, r (a.getLast ha) (b.head hb) = false) (hga : βˆ€ m ∈ gs.head?, βˆƒ ha hb, r (m.getLast ha) ((g.reverse ++ [a]).head hb) = false) : (splitBy.loop r l a g gs).IsChain fun a b ↦ βˆƒ ha hb, r (a.getLast ha) (b.head hb) = false := by induction l generalizing a g gs with | nil => rw [splitBy.loop, reverse_cons] apply List.isChain_reverse.1 simpa using isChain_cons.2 ⟨hga, hgs⟩ | cons b l IH => rw [splitBy.loop] split Β· apply IH hgs' hgs intro m hm obtain ⟨ha, _, H⟩ := hga m hm refine ⟨ha, append_ne_nil_of_right_ne_nil _ (cons_ne_nil _ _), ?_⟩ rwa [reverse_cons, head_append_of_ne_nil] Β· apply IH Β· simpa using hgs' Β· rw [reverse_cons] apply isChain_cons.2 ⟨hga, hgs⟩ Β· simpa theorem isChain_getLast_head_splitBy (r : Ξ± β†’ Ξ± β†’ Bool) (l : List Ξ±) : (l.splitBy r).IsChain fun a b ↦ βˆƒ ha hb, r (a.getLast ha) (b.head hb) = false := by cases l with | nil => exact isChain_nil | cons _ _ => apply isChain_getLast_head_splitByLoop _ not_mem_nil isChain_nil rintro _ ⟨⟩ @[deprecated (since := "2025-09-24")] alias chain'_getLast_head_splitBy := isChain_getLast_head_splitBy end List
.lake/packages/mathlib/Mathlib/Data/List/AList.lean
import Mathlib.Data.List.Sigma /-! # Association Lists This file defines association lists. An association list is a list where every element consists of a key and a value, and no two entries have the same key. The type of the value is allowed to be dependent on the type of the key. This type dependence is implemented using `Sigma`: The elements of the list are of type `Sigma Ξ²`, for some type index `Ξ²`. ## Main definitions Association lists are represented by the `AList` structure. This file defines this structure and provides ways to access, modify, and combine `AList`s. * `AList.keys` returns a list of keys of the alist. * `AList.membership` returns membership in the set of keys. * `AList.erase` removes a certain key. * `AList.insert` adds a key-value mapping to the list. * `AList.union` combines two association lists. ## References * <https://en.wikipedia.org/wiki/Association_list> -/ universe u v w open List variable {Ξ± : Type u} {Ξ² : Ξ± β†’ Type v} /-- `AList Ξ²` is a key-value map stored as a `List` (i.e. a linked list). It is a wrapper around certain `List` functions with the added constraint that the list have unique keys. -/ structure AList (Ξ² : Ξ± β†’ Type v) : Type max u v where /-- The underlying `List` of an `AList` -/ entries : List (Sigma Ξ²) /-- There are no duplicate keys in `entries` -/ nodupKeys : entries.NodupKeys /-- Given `l : List (Sigma Ξ²)`, create a term of type `AList Ξ²` by removing entries with duplicate keys. -/ def List.toAList [DecidableEq Ξ±] {Ξ² : Ξ± β†’ Type v} (l : List (Sigma Ξ²)) : AList Ξ² where entries := _ nodupKeys := nodupKeys_dedupKeys l namespace AList @[ext] theorem ext : βˆ€ {s t : AList Ξ²}, s.entries = t.entries β†’ s = t | ⟨l₁, hβ‚βŸ©, ⟨lβ‚‚, _⟩, H => by congr instance [DecidableEq Ξ±] [βˆ€ a, DecidableEq (Ξ² a)] : DecidableEq (AList Ξ²) := fun xs ys => by rw [AList.ext_iff]; infer_instance /-! ### keys -/ /-- The list of keys of an association list. -/ def keys (s : AList Ξ²) : List Ξ± := s.entries.keys theorem keys_nodup (s : AList Ξ²) : s.keys.Nodup := s.nodupKeys @[simp] theorem keys_mk (l : List (Sigma Ξ²)) (h) : (AList.mk l h).keys = l.keys := rfl /-! ### mem -/ /-- The predicate `a ∈ s` means that `s` has a value associated to the key `a`. -/ instance : Membership Ξ± (AList Ξ²) := ⟨fun s a => a ∈ s.keys⟩ theorem mem_keys {a : Ξ±} {s : AList Ξ²} : a ∈ s ↔ a ∈ s.keys := Iff.rfl theorem mem_of_perm {a : Ξ±} {s₁ sβ‚‚ : AList Ξ²} (p : s₁.entries ~ sβ‚‚.entries) : a ∈ s₁ ↔ a ∈ sβ‚‚ := (p.map Sigma.fst).mem_iff @[simp] theorem mem_mk {l : List (Sigma Ξ²)} {h} {x : Ξ±} : x ∈ AList.mk l h ↔ x ∈ l.keys := .rfl /-! ### empty -/ /-- The empty association list. -/ instance : EmptyCollection (AList Ξ²) := ⟨⟨[], nodupKeys_nil⟩⟩ instance : Inhabited (AList Ξ²) := βŸ¨βˆ…βŸ© @[simp] theorem notMem_empty (a : Ξ±) : a βˆ‰ (βˆ… : AList Ξ²) := not_mem_nil @[deprecated (since := "2025-05-23")] alias not_mem_empty := notMem_empty @[simp] theorem empty_entries : (βˆ… : AList Ξ²).entries = [] := rfl @[simp] theorem keys_empty : (βˆ… : AList Ξ²).keys = [] := rfl /-! ### singleton -/ /-- The singleton association list. -/ def singleton (a : Ξ±) (b : Ξ² a) : AList Ξ² := ⟨[⟨a, b⟩], nodupKeys_singleton _⟩ @[simp] theorem singleton_entries (a : Ξ±) (b : Ξ² a) : (singleton a b).entries = [Sigma.mk a b] := rfl @[simp] theorem keys_singleton (a : Ξ±) (b : Ξ² a) : (singleton a b).keys = [a] := rfl /-! ### lookup -/ section variable [DecidableEq Ξ±] /-- Look up the value associated to a key in an association list. -/ def lookup (a : Ξ±) (s : AList Ξ²) : Option (Ξ² a) := s.entries.dlookup a @[simp] theorem lookup_empty (a) : lookup a (βˆ… : AList Ξ²) = none := rfl theorem lookup_isSome {a : Ξ±} {s : AList Ξ²} : (s.lookup a).isSome ↔ a ∈ s := dlookup_isSome theorem lookup_eq_none {a : Ξ±} {s : AList Ξ²} : lookup a s = none ↔ a βˆ‰ s := dlookup_eq_none theorem mem_lookup_iff {a : Ξ±} {b : Ξ² a} {s : AList Ξ²} : b ∈ lookup a s ↔ Sigma.mk a b ∈ s.entries := mem_dlookup_iff s.nodupKeys theorem perm_lookup {a : Ξ±} {s₁ sβ‚‚ : AList Ξ²} (p : s₁.entries ~ sβ‚‚.entries) : s₁.lookup a = sβ‚‚.lookup a := perm_dlookup _ s₁.nodupKeys p instance (a : Ξ±) (s : AList Ξ²) : Decidable (a ∈ s) := decidable_of_iff _ lookup_isSome end theorem keys_subset_keys_of_entries_subset_entries {s₁ sβ‚‚ : AList Ξ²} (h : s₁.entries βŠ† sβ‚‚.entries) : s₁.keys βŠ† sβ‚‚.keys := by intro k hk letI : DecidableEq Ξ± := Classical.decEq Ξ± have := h (mem_lookup_iff.1 (Option.get_mem (lookup_isSome.2 hk))) rw [← mem_lookup_iff, Option.mem_def] at this rw [← mem_keys, ← lookup_isSome, this] exact Option.isSome_some /-! ### replace -/ section variable [DecidableEq Ξ±] /-- Replace a key with a given value in an association list. If the key is not present it does nothing. -/ def replace (a : Ξ±) (b : Ξ² a) (s : AList Ξ²) : AList Ξ² := ⟨kreplace a b s.entries, (kreplace_nodupKeys a b).2 s.nodupKeys⟩ @[simp] theorem keys_replace (a : Ξ±) (b : Ξ² a) (s : AList Ξ²) : (replace a b s).keys = s.keys := keys_kreplace _ _ _ @[simp] theorem mem_replace {a a' : Ξ±} {b : Ξ² a} {s : AList Ξ²} : a' ∈ replace a b s ↔ a' ∈ s := by rw [mem_keys, keys_replace, ← mem_keys] theorem perm_replace {a : Ξ±} {b : Ξ² a} {s₁ sβ‚‚ : AList Ξ²} : s₁.entries ~ sβ‚‚.entries β†’ (replace a b s₁).entries ~ (replace a b sβ‚‚).entries := Perm.kreplace s₁.nodupKeys end /-- Fold a function over the key-value pairs in the map. -/ def foldl {Ξ΄ : Type w} (f : Ξ΄ β†’ βˆ€ a, Ξ² a β†’ Ξ΄) (d : Ξ΄) (m : AList Ξ²) : Ξ΄ := m.entries.foldl (fun r a => f r a.1 a.2) d /-! ### erase -/ section variable [DecidableEq Ξ±] /-- Erase a key from the map. If the key is not present, do nothing. -/ def erase (a : Ξ±) (s : AList Ξ²) : AList Ξ² := ⟨s.entries.kerase a, s.nodupKeys.kerase a⟩ @[simp] theorem keys_erase (a : Ξ±) (s : AList Ξ²) : (erase a s).keys = s.keys.erase a := keys_kerase @[simp] theorem mem_erase {a a' : Ξ±} {s : AList Ξ²} : a' ∈ erase a s ↔ a' β‰  a ∧ a' ∈ s := by rw [mem_keys, keys_erase, s.keys_nodup.mem_erase_iff, ← mem_keys] theorem perm_erase {a : Ξ±} {s₁ sβ‚‚ : AList Ξ²} : s₁.entries ~ sβ‚‚.entries β†’ (erase a s₁).entries ~ (erase a sβ‚‚).entries := Perm.kerase s₁.nodupKeys @[simp] theorem lookup_erase (a) (s : AList Ξ²) : lookup a (erase a s) = none := dlookup_kerase a s.nodupKeys @[simp] theorem lookup_erase_ne {a a'} {s : AList Ξ²} (h : a β‰  a') : lookup a (erase a' s) = lookup a s := dlookup_kerase_ne h theorem erase_erase (a a' : Ξ±) (s : AList Ξ²) : (s.erase a).erase a' = (s.erase a').erase a := ext <| kerase_kerase /-! ### insert -/ /-- Insert a key-value pair into an association list and erase any existing pair with the same key. -/ def insert (a : Ξ±) (b : Ξ² a) (s : AList Ξ²) : AList Ξ² := ⟨kinsert a b s.entries, kinsert_nodupKeys a b s.nodupKeys⟩ @[simp] theorem entries_insert {a} {b : Ξ² a} {s : AList Ξ²} : (insert a b s).entries = Sigma.mk a b :: kerase a s.entries := rfl theorem entries_insert_of_notMem {a} {b : Ξ² a} {s : AList Ξ²} (h : a βˆ‰ s) : (insert a b s).entries = ⟨a, b⟩ :: s.entries := by rw [entries_insert, kerase_of_notMem_keys h] @[deprecated (since := "2025-05-23")] alias entries_insert_of_not_mem := entries_insert_of_notMem theorem insert_of_notMem {a} {b : Ξ² a} {s : AList Ξ²} (h : a βˆ‰ s) : insert a b s = ⟨⟨a, b⟩ :: s.entries, nodupKeys_cons.2 ⟨h, s.2⟩⟩ := ext <| entries_insert_of_notMem h @[deprecated (since := "2025-05-23")] alias insert_of_not_mem := insert_of_notMem @[simp] theorem insert_empty (a) (b : Ξ² a) : insert a b βˆ… = singleton a b := rfl @[simp] theorem mem_insert {a a'} {b' : Ξ² a'} (s : AList Ξ²) : a ∈ insert a' b' s ↔ a = a' ∨ a ∈ s := mem_keys_kinsert @[simp] theorem keys_insert {a} {b : Ξ² a} (s : AList Ξ²) : (insert a b s).keys = a :: s.keys.erase a := by simp [insert, keys, keys_kerase] theorem perm_insert {a} {b : Ξ² a} {s₁ sβ‚‚ : AList Ξ²} (p : s₁.entries ~ sβ‚‚.entries) : (insert a b s₁).entries ~ (insert a b sβ‚‚).entries := by simp only [entries_insert]; exact p.kinsert s₁.nodupKeys @[simp] theorem lookup_insert {a} {b : Ξ² a} (s : AList Ξ²) : lookup a (insert a b s) = some b := by simp only [lookup, insert, dlookup_kinsert] @[simp] theorem lookup_insert_ne {a a'} {b' : Ξ² a'} {s : AList Ξ²} (h : a β‰  a') : lookup a (insert a' b' s) = lookup a s := dlookup_kinsert_ne h @[simp] theorem lookup_insert_eq_none {l : AList Ξ²} {k k' : Ξ±} {v : Ξ² k} : (l.insert k v).lookup k' = none ↔ (k' β‰  k) ∧ l.lookup k' = none := by by_cases h : k' = k Β· subst h; simp Β· simp_all [lookup_insert_ne h] @[simp] theorem lookup_to_alist {a} (s : List (Sigma Ξ²)) : lookup a s.toAList = s.dlookup a := by rw [List.toAList, lookup, dlookup_dedupKeys] @[simp] theorem insert_insert {a} {b b' : Ξ² a} (s : AList Ξ²) : (s.insert a b).insert a b' = s.insert a b' := by ext : 1; simp only [AList.entries_insert, List.kerase_cons_eq] theorem insert_insert_of_ne {a a'} {b : Ξ² a} {b' : Ξ² a'} (s : AList Ξ²) (h : a β‰  a') : ((s.insert a b).insert a' b').entries ~ ((s.insert a' b').insert a b).entries := by simp only [entries_insert]; rw [kerase_cons_ne, kerase_cons_ne, kerase_comm] <;> [apply Perm.swap; exact h; exact h.symm] @[simp] theorem insert_singleton_eq {a : Ξ±} {b b' : Ξ² a} : insert a b (singleton a b') = singleton a b := ext <| by simp only [AList.entries_insert, List.kerase_cons_eq, AList.singleton_entries] @[simp] theorem entries_toAList (xs : List (Sigma Ξ²)) : (List.toAList xs).entries = dedupKeys xs := rfl theorem toAList_cons (a : Ξ±) (b : Ξ² a) (xs : List (Sigma Ξ²)) : List.toAList (⟨a, b⟩ :: xs) = insert a b xs.toAList := rfl theorem mk_cons_eq_insert (c : Sigma Ξ²) (l : List (Sigma Ξ²)) (h : (c :: l).NodupKeys) : (⟨c :: l, h⟩ : AList Ξ²) = insert c.1 c.2 ⟨l, nodupKeys_of_nodupKeys_cons h⟩ := by simpa [insert] using (kerase_of_notMem_keys <| notMem_keys_of_nodupKeys_cons h).symm /-- Recursion on an `AList`, using `insert`. Use as `induction l`. -/ @[elab_as_elim, induction_eliminator] def insertRec {C : AList Ξ² β†’ Sort*} (H0 : C βˆ…) (IH : βˆ€ (a : Ξ±) (b : Ξ² a) (l : AList Ξ²), a βˆ‰ l β†’ C l β†’ C (l.insert a b)) : βˆ€ l : AList Ξ², C l | ⟨[], _⟩ => H0 | ⟨c :: l, h⟩ => by rw [mk_cons_eq_insert] refine IH _ _ _ ?_ (insertRec H0 IH _) exact notMem_keys_of_nodupKeys_cons h -- Test that the `induction` tactic works on `insertRec`. example (l : AList Ξ²) : True := by induction l <;> trivial @[simp] theorem insertRec_empty {C : AList Ξ² β†’ Sort*} (H0 : C βˆ…) (IH : βˆ€ (a : Ξ±) (b : Ξ² a) (l : AList Ξ²), a βˆ‰ l β†’ C l β†’ C (l.insert a b)) : @insertRec Ξ± Ξ² _ C H0 IH βˆ… = H0 := by change @insertRec Ξ± Ξ² _ C H0 IH ⟨[], _⟩ = H0 rw [insertRec] theorem insertRec_insert {C : AList Ξ² β†’ Sort*} (H0 : C βˆ…) (IH : βˆ€ (a : Ξ±) (b : Ξ² a) (l : AList Ξ²), a βˆ‰ l β†’ C l β†’ C (l.insert a b)) {c : Sigma Ξ²} {l : AList Ξ²} (h : c.1 βˆ‰ l) : @insertRec Ξ± Ξ² _ C H0 IH (l.insert c.1 c.2) = IH c.1 c.2 l h (@insertRec Ξ± Ξ² _ C H0 IH l) := by obtain ⟨l, hl⟩ := l suffices @insertRec Ξ± Ξ² _ C H0 IH ⟨c :: l, nodupKeys_cons.2 ⟨h, hl⟩⟩ ≍ IH c.1 c.2 ⟨l, hl⟩ h (@insertRec Ξ± Ξ² _ C H0 IH ⟨l, hl⟩) by cases c apply eq_of_heq convert this <;> rw [insert_of_notMem h] rw [insertRec] apply cast_heq theorem insertRec_insert_mk {C : AList Ξ² β†’ Sort*} (H0 : C βˆ…) (IH : βˆ€ (a : Ξ±) (b : Ξ² a) (l : AList Ξ²), a βˆ‰ l β†’ C l β†’ C (l.insert a b)) {a : Ξ±} (b : Ξ² a) {l : AList Ξ²} (h : a βˆ‰ l) : @insertRec Ξ± Ξ² _ C H0 IH (l.insert a b) = IH a b l h (@insertRec Ξ± Ξ² _ C H0 IH l) := @insertRec_insert Ξ± Ξ² _ C H0 IH ⟨a, b⟩ l h /-! ### extract -/ /-- Erase a key from the map, and return the corresponding value, if found. -/ def extract (a : Ξ±) (s : AList Ξ²) : Option (Ξ² a) Γ— AList Ξ² := have : (kextract a s.entries).2.NodupKeys := by rw [kextract_eq_dlookup_kerase]; exact s.nodupKeys.kerase _ match kextract a s.entries, this with | (b, l), h => (b, ⟨l, h⟩) @[simp] theorem extract_eq_lookup_erase (a : Ξ±) (s : AList Ξ²) : extract a s = (lookup a s, erase a s) := by simp [extract]; constructor <;> rfl /-! ### union -/ /-- `s₁ βˆͺ sβ‚‚` is the key-based union of two association lists. It is left-biased: if there exists an `a ∈ s₁`, `lookup a (s₁ βˆͺ sβ‚‚) = lookup a s₁`. -/ def union (s₁ sβ‚‚ : AList Ξ²) : AList Ξ² := ⟨s₁.entries.kunion sβ‚‚.entries, s₁.nodupKeys.kunion sβ‚‚.nodupKeys⟩ instance : Union (AList Ξ²) := ⟨union⟩ @[simp] theorem union_entries {s₁ sβ‚‚ : AList Ξ²} : (s₁ βˆͺ sβ‚‚).entries = kunion s₁.entries sβ‚‚.entries := rfl @[simp] theorem empty_union {s : AList Ξ²} : (βˆ… : AList Ξ²) βˆͺ s = s := ext rfl @[simp] theorem union_empty {s : AList Ξ²} : s βˆͺ (βˆ… : AList Ξ²) = s := ext <| by simp @[simp] theorem mem_union {a} {s₁ sβ‚‚ : AList Ξ²} : a ∈ s₁ βˆͺ sβ‚‚ ↔ a ∈ s₁ ∨ a ∈ sβ‚‚ := mem_keys_kunion theorem perm_union {s₁ sβ‚‚ s₃ sβ‚„ : AList Ξ²} (p₁₂ : s₁.entries ~ sβ‚‚.entries) (p₃₄ : s₃.entries ~ sβ‚„.entries) : (s₁ βˆͺ s₃).entries ~ (sβ‚‚ βˆͺ sβ‚„).entries := by simp [p₁₂.kunion s₃.nodupKeys p₃₄] theorem union_erase (a : Ξ±) (s₁ sβ‚‚ : AList Ξ²) : erase a (s₁ βˆͺ sβ‚‚) = erase a s₁ βˆͺ erase a sβ‚‚ := ext kunion_kerase.symm @[simp] theorem lookup_union_left {a} {s₁ sβ‚‚ : AList Ξ²} : a ∈ s₁ β†’ lookup a (s₁ βˆͺ sβ‚‚) = lookup a s₁ := dlookup_kunion_left @[simp] theorem lookup_union_right {a} {s₁ sβ‚‚ : AList Ξ²} : a βˆ‰ s₁ β†’ lookup a (s₁ βˆͺ sβ‚‚) = lookup a sβ‚‚ := dlookup_kunion_right -- The corresponding lemma in `simp`-normal form is `lookup_union_eq_some`. theorem mem_lookup_union {a} {b : Ξ² a} {s₁ sβ‚‚ : AList Ξ²} : b ∈ lookup a (s₁ βˆͺ sβ‚‚) ↔ b ∈ lookup a s₁ ∨ a βˆ‰ s₁ ∧ b ∈ lookup a sβ‚‚ := mem_dlookup_kunion @[simp] theorem lookup_union_eq_some {a} {b : Ξ² a} {s₁ sβ‚‚ : AList Ξ²} : lookup a (s₁ βˆͺ sβ‚‚) = some b ↔ lookup a s₁ = some b ∨ a βˆ‰ s₁ ∧ lookup a sβ‚‚ = some b := mem_dlookup_kunion theorem mem_lookup_union_middle {a} {b : Ξ² a} {s₁ sβ‚‚ s₃ : AList Ξ²} : b ∈ lookup a (s₁ βˆͺ s₃) β†’ a βˆ‰ sβ‚‚ β†’ b ∈ lookup a (s₁ βˆͺ sβ‚‚ βˆͺ s₃) := mem_dlookup_kunion_middle theorem insert_union {a} {b : Ξ² a} {s₁ sβ‚‚ : AList Ξ²} : insert a b (s₁ βˆͺ sβ‚‚) = insert a b s₁ βˆͺ sβ‚‚ := by ext; simp theorem union_assoc {s₁ sβ‚‚ s₃ : AList Ξ²} : (s₁ βˆͺ sβ‚‚ βˆͺ s₃).entries ~ (s₁ βˆͺ (sβ‚‚ βˆͺ s₃)).entries := lookup_ext (AList.nodupKeys _) (AList.nodupKeys _) (by simp [not_or, or_assoc, and_or_left, and_assoc]) end /-! ### disjoint -/ /-- Two associative lists are disjoint if they have no common keys. -/ def Disjoint (s₁ sβ‚‚ : AList Ξ²) : Prop := βˆ€ k ∈ s₁.keys, k βˆ‰ sβ‚‚.keys variable [DecidableEq Ξ±] theorem union_comm_of_disjoint {s₁ sβ‚‚ : AList Ξ²} (h : Disjoint s₁ sβ‚‚) : (s₁ βˆͺ sβ‚‚).entries ~ (sβ‚‚ βˆͺ s₁).entries := lookup_ext (AList.nodupKeys _) (AList.nodupKeys _) (by intros; simp only [union_entries, Option.mem_def, dlookup_kunion_eq_some] constructor <;> intro h' Β· rcases h' with h' | h' Β· right refine ⟨?_, h'⟩ apply h rw [keys, ← List.dlookup_isSome, h'] exact rfl Β· left rw [h'.2] Β· rcases h' with h' | h' Β· right refine ⟨?_, h'⟩ intro h'' apply h _ h'' rw [keys, ← List.dlookup_isSome, h'] exact rfl Β· left rw [h'.2]) end AList
.lake/packages/mathlib/Mathlib/Data/List/Destutter.lean
import Mathlib.Data.List.Chain import Mathlib.Data.List.Dedup /-! # Destuttering of Lists This file proves theorems about `List.destutter` (in `Data.List.Defs`), which greedily removes all non-related items that are adjacent in a list, e.g. `[2, 2, 3, 3, 2].destutter (β‰ ) = [2, 3, 2]`. Note that we make no guarantees of being the longest sublist with this property; e.g., `[123, 1, 2, 5, 543, 1000].destutter (<) = [123, 543, 1000]`, but a longer ascending chain could be `[1, 2, 5, 543, 1000]`. ## Main statements * `List.destutter_sublist`: `l.destutter` is a sublist of `l`. * `List.isChain_destutter'`: `l.destutter` satisfies `IsChain R`. * Analogies of these theorems for `List.destutter'`, which is the `destutter` equivalent of `Chain`. ## Tags adjacent, chain, duplicates, remove, list, stutter, destutter -/ open Function variable {Ξ± Ξ² : Type*} (l l₁ lβ‚‚ : List Ξ±) (R : Ξ± β†’ Ξ± β†’ Prop) [DecidableRel R] {a b : Ξ±} variable {Rβ‚‚ : Ξ² β†’ Ξ² β†’ Prop} [DecidableRel Rβ‚‚] namespace List @[simp] theorem destutter'_nil : destutter' R a [] = [a] := rfl theorem destutter'_cons : (b :: l).destutter' R a = if R a b then a :: destutter' R b l else destutter' R a l := rfl variable {R} @[simp] theorem destutter'_cons_pos (h : R b a) : (a :: l).destutter' R b = b :: l.destutter' R a := by rw [destutter', if_pos h] @[simp] theorem destutter'_cons_neg (h : Β¬R b a) : (a :: l).destutter' R b = l.destutter' R b := by rw [destutter', if_neg h] variable (R) @[simp] theorem destutter'_singleton : [b].destutter' R a = if R a b then [a, b] else [a] := by split_ifs with h <;> simp! [h] theorem destutter'_sublist (a) : l.destutter' R a <+ a :: l := by induction l generalizing a with | nil => simp | cons b l hl => rw [destutter'] split_ifs Β· exact Sublist.consβ‚‚ a (hl b) Β· exact (hl a).trans ((l.sublist_cons_self b).cons_cons a) theorem mem_destutter' (a) : a ∈ l.destutter' R a := by induction l with | nil => simp | cons b l hl => rw [destutter'] split_ifs Β· simp Β· assumption theorem isChain_destutter' (l : List Ξ±) (a : Ξ±) : (l.destutter' R a).IsChain R := by induction l using twoStepInduction generalizing a with | nil => simp | singleton => simp [apply_ite] | cons_cons b c l IH IH2 => simp_rw [destutter'_cons, apply_ite (IsChain R Β·), IH, if_true_right] at IH2 simp_rw [destutter'_cons, apply_ite (IsChain R Β·), apply_ite (IsChain R <| a :: Β·), IH, isChain_cons_cons, if_true_right, ite_prop_iff_and, imp_and] exact ⟨⟨⟨swap <| fun _ => id, fun _ => IH2 c b⟩, swap <| fun _ => IH2 b a⟩, fun _ => IH2 c a⟩ theorem isChain_cons_destutter'_of_rel (l : List Ξ±) {a b} (hab : R a b) : (a :: l.destutter' R b).IsChain R := by simpa [destutter'_cons, hab] using isChain_destutter' R (b :: l) a theorem destutter'_of_isChain_cons (h : (a :: l).IsChain R) : l.destutter' R a = a :: l := by induction l generalizing a with | nil => simp | cons b l hb => obtain ⟨h, hc⟩ := isChain_cons_cons.mp h rw [l.destutter'_cons_pos h, hb hc] @[deprecated (since := "2025-09-24")] alias destutter'_is_chain := isChain_cons_destutter'_of_rel @[deprecated (since := "2025-09-24")] alias destutter'_is_chain' := isChain_destutter' @[deprecated (since := "2025-09-24")] alias destutter'_of_chain := destutter'_of_isChain_cons @[simp] theorem destutter'_eq_self_iff (a) : l.destutter' R a = a :: l ↔ (a :: l).IsChain R := ⟨fun h => by suffices IsChain R (a::l) by assumption rw [← h] exact l.isChain_destutter' R a, destutter'_of_isChain_cons _ _⟩ theorem destutter'_ne_nil : l.destutter' R a β‰  [] := ne_nil_of_mem <| l.mem_destutter' R a @[simp] theorem destutter_nil : ([] : List Ξ±).destutter R = [] := rfl theorem destutter_cons' : (a :: l).destutter R = destutter' R a l := rfl theorem destutter_cons_cons : (a :: b :: l).destutter R = if R a b then a :: destutter' R b l else destutter' R a l := rfl @[simp] theorem destutter_singleton : destutter R [a] = [a] := rfl @[simp] theorem destutter_pair : destutter R [a, b] = if R a b then [a, b] else [a] := destutter_cons_cons _ R theorem destutter_sublist : βˆ€ l : List Ξ±, l.destutter R <+ l | [] => Sublist.slnil | h :: l => l.destutter'_sublist R h theorem isChain_destutter : βˆ€ l : List Ξ±, (l.destutter R).IsChain R | [] => .nil | h :: l => l.isChain_destutter' R h theorem destutter_of_isChain : βˆ€ l : List Ξ±, l.IsChain R β†’ l.destutter R = l | [], _ => rfl | _ :: l, h => l.destutter'_of_isChain_cons _ h @[deprecated (since := "2025-09-24")] alias destutter_is_chain' := isChain_destutter @[deprecated (since := "2025-09-24")] alias destutter_of_chain' := destutter_of_isChain @[simp] theorem destutter_eq_self_iff : βˆ€ l : List Ξ±, l.destutter R = l ↔ l.IsChain R | [] => by simp | a :: l => l.destutter'_eq_self_iff R a theorem destutter_idem : (l.destutter R).destutter R = l.destutter R := destutter_of_isChain R _ <| l.isChain_destutter R @[simp] theorem destutter_eq_nil : βˆ€ {l : List Ξ±}, destutter R l = [] ↔ l = [] | [] => Iff.rfl | _ :: l => ⟨fun h => absurd h <| l.destutter'_ne_nil R, fun h => nomatch h⟩ variable {R} /-- For a relation-preserving map, `destutter` commutes with `map`. -/ theorem map_destutter {f : Ξ± β†’ Ξ²} : βˆ€ {l : List Ξ±}, (βˆ€ a ∈ l, βˆ€ b ∈ l, R a b ↔ Rβ‚‚ (f a) (f b)) β†’ (l.destutter R).map f = (l.map f).destutter Rβ‚‚ | [], hl => by simp | [a], hl => by simp | a :: b :: l, hl => by have := hl a (by simp) b (by simp) simp_rw [map_cons, destutter_cons_cons, ← this] by_cases hr : R a b <;> simp [hr, ← destutter_cons', map_destutter fun c hc d hd ↦ hl _ (cons_subset_cons _ (subset_cons_self _ _) hc) _ (cons_subset_cons _ (subset_cons_self _ _) hd), map_destutter fun c hc d hd ↦ hl _ (subset_cons_self _ _ hc) _ (subset_cons_self _ _ hd)] /-- For a injective function `f`, `destutter' (Β·β‰ Β·)` commutes with `map f`. -/ theorem map_destutter_ne {f : Ξ± β†’ Ξ²} (h : Injective f) [DecidableEq Ξ±] [DecidableEq Ξ²] : (l.destutter (Β· β‰  Β·)).map f = (l.map f).destutter (Β· β‰  Β·) := map_destutter fun _ _ _ _ ↦ h.ne_iff.symm /-- `destutter'` on a relation like β‰  or <, whose negation is transitive, has length monotone under a `Β¬R` changing of the first element. -/ theorem length_destutter'_cotrans_ge [i : IsTrans Ξ± Rᢜ] : βˆ€ {a} {l : List Ξ±}, Β¬R b a β†’ (l.destutter' R b).length ≀ (l.destutter' R a).length | a, [], hba => by simp | a, c :: l, hba => by by_cases hbc : R b c case pos => have hac : Β¬Rᢜ a c := (mt (_root_.trans hba)) (not_not.2 hbc) simp_rw [destutter', if_pos (not_not.1 hac), if_pos hbc, length_cons, le_refl] case neg => simp only [destutter', if_neg hbc] by_cases hac : R a c case pos => simp only [if_pos hac, length_cons] exact Nat.le_succ_of_le (length_destutter'_cotrans_ge hbc) case neg => simp only [if_neg hac] exact length_destutter'_cotrans_ge hba /-- `List.destutter'` on a relation like `β‰ `, whose negation is an equivalence, gives the same length if the first elements are not related. -/ theorem length_destutter'_congr [IsEquiv Ξ± Rᢜ] (hab : Β¬R a b) : (l.destutter' R a).length = (l.destutter' R b).length := (length_destutter'_cotrans_ge hab).antisymm <| length_destutter'_cotrans_ge (symm hab : Rᢜ b a) /-- `List.destutter'` on a relation like β‰ , whose negation is an equivalence, has length monotonic under List.cons -/ /- TODO: Replace this lemma by the more general version: theorem Sublist.length_destutter'_mono [IsEquiv Ξ± Rᢜ] (h : a :: l₁ <+ b :: lβ‚‚) : (List.destutter' R a l₁).length ≀ (List.destutter' R b lβ‚‚).length -/ theorem le_length_destutter'_cons [IsEquiv Ξ± Rᢜ] : βˆ€ {l : List Ξ±}, (l.destutter' R b).length ≀ ((b :: l).destutter' R a).length | [] => by by_cases hab : (R a b) <;> simp_all [Nat.le_succ] | c :: cs => by by_cases hab : R a b case pos => simp [destutter', if_pos hab, Nat.le_succ] obtain hac | hac : R a c ∨ Rᢜ a c := em _ Β· have hbc : Β¬Rᢜ b c := mt (_root_.trans hab) (not_not.2 hac) simp [destutter', if_pos hac, if_pos (not_not.1 hbc), if_neg hab] Β· have hbc : Β¬R b c := trans (symm hab) hac simp only [destutter', if_neg hbc, if_neg hac, if_neg hab] exact (length_destutter'_congr cs hab).ge /-- `List.destutter` on a relation like β‰ , whose negation is an equivalence, has length monotone under List.cons -/ theorem length_destutter_le_length_destutter_cons [IsEquiv Ξ± Rᢜ] : βˆ€ {l : List Ξ±}, (l.destutter R).length ≀ ((a :: l).destutter R).length | [] => by simp [destutter] | b :: l => le_length_destutter'_cons variable {l l₁ lβ‚‚} /-- `destutter β‰ ` has length monotone under `List.cons`. -/ theorem length_destutter_ne_le_length_destutter_cons [DecidableEq Ξ±] : (l.destutter (Β· β‰  Β·)).length ≀ ((a :: l).destutter (Β· β‰  Β·)).length := length_destutter_le_length_destutter_cons /-- `destutter` of relations like `β‰ `, whose negation is an equivalence relation, gives a list of maximal length over any chain. In other words, `l.destutter R` is an `R`-chain sublist of `l`, and is at least as long as any other `R`-chain sublist. -/ lemma IsChain.length_le_length_destutter [IsEquiv Ξ± Rᢜ] : βˆ€ {l₁ lβ‚‚ : List Ξ±}, l₁ <+ lβ‚‚ β†’ l₁.IsChain R β†’ l₁.length ≀ (lβ‚‚.destutter R).length -- `l₁ := []`, `lβ‚‚ := []` | [], [], _, _ => by simp -- `l₁ := l₁`, `lβ‚‚ := a :: lβ‚‚` | l₁, _, .cons (lβ‚‚ := lβ‚‚) a hl, hl₁ => (hl₁.length_le_length_destutter hl).trans length_destutter_le_length_destutter_cons -- `l₁ := [a]`, `lβ‚‚ := a :: lβ‚‚` | _, _, .consβ‚‚ (l₁ := []) (lβ‚‚ := l₁) a hl, hl₁ => by simp [Nat.one_le_iff_ne_zero] -- `l₁ := a :: l₁`, `lβ‚‚ := a :: b :: lβ‚‚` | _, _, .consβ‚‚ a <| .cons (l₁ := l₁) (lβ‚‚ := lβ‚‚) b hl, hl₁ => by by_cases hab : R a b Β· simpa [destutter_cons_cons, hab] using hl₁.tail.length_le_length_destutter (hl.cons _) Β· simpa [destutter_cons_cons, hab] using hl₁.length_le_length_destutter (hl.consβ‚‚ _) -- `l₁ := a :: b :: l₁`, `lβ‚‚ := a :: b :: lβ‚‚` | _, _, .consβ‚‚ a <| .consβ‚‚ (l₁ := l₁) (lβ‚‚ := lβ‚‚) b hl, hl₁ => by simpa [destutter_cons_cons, rel_of_isChain_cons_cons hl₁] using hl₁.tail.length_le_length_destutter (hl.consβ‚‚ _) /-- `destutter` of `β‰ ` gives a list of maximal length over any chain. In other words, `l.destutter (Β· β‰  Β·)` is a `β‰ `-chain sublist of `l`, and is at least as long as any other `β‰ `-chain sublist. -/ lemma IsChain.length_le_length_destutter_ne [DecidableEq Ξ±] (hl : l₁ <+ lβ‚‚) (hl₁ : l₁.IsChain (Β· β‰  Β·)) : l₁.length ≀ (lβ‚‚.destutter (Β· β‰  Β·)).length := hl₁.length_le_length_destutter hl /-- If the elements of a list `l` are related pairwise by an antisymmetric relation `r`, then destuttering `l` by disequality produces the same result as deduplicating `l`. This is most useful when `r` is a strict or weak ordering. -/ lemma Pairwise.destutter_eq_dedup [DecidableEq Ξ±] {r : Ξ± β†’ Ξ± β†’ Prop} [IsAntisymm Ξ± r] : βˆ€ {l : List Ξ±}, l.Pairwise r β†’ l.destutter (Β· β‰  Β·) = l.dedup | [], h => by simp | [x], h => by simp | x :: y :: xs, h => by rw [pairwise_cons] at h rw [destutter_cons_cons, ← destutter_cons', ← destutter_cons', h.2.destutter_eq_dedup] obtain rfl | hxy := eq_or_ne x y Β· simpa using h.2.destutter_eq_dedup Β· simp only [mem_cons, forall_eq_or_imp, pairwise_cons] at h have : x βˆ‰ xs := fun hx ↦ hxy (antisymm h.1.1 (h.2.1 x hx)) rw [if_pos hxy, dedup_cons_of_notMem (a := x) (by simp [*])] end List
.lake/packages/mathlib/Mathlib/Data/List/TakeDrop.lean
import Mathlib.Data.List.Defs import Mathlib.Tactic.Common /-! # `Take` and `Drop` lemmas for lists This file provides lemmas about `List.take` and `List.drop` and related functions. -/ assert_not_exists GroupWithZero assert_not_exists Lattice assert_not_exists Prod.swap_eq_iff_eq_swap assert_not_exists Ring assert_not_exists Set.range open Function open Nat hiding one_pos namespace List universe u v w variable {ΞΉ : Type*} {Ξ± : Type u} {Ξ² : Type v} {Ξ³ : Type w} {l₁ lβ‚‚ : List Ξ±} /-! ### take, drop -/ theorem take_one_drop_eq_of_lt_length {l : List Ξ±} {n : β„•} (h : n < l.length) : (l.drop n).take 1 = [l.get ⟨n, h⟩] := by rw [drop_eq_getElem_cons h, take, take] simp @[simp] lemma take_eq_self_iff (x : List Ξ±) {n : β„•} : x.take n = x ↔ x.length ≀ n := ⟨by grind, take_of_length_le⟩ @[simp] lemma take_self_eq_iff (x : List Ξ±) {n : β„•} : x = x.take n ↔ x.length ≀ n := by rw [Eq.comm, take_eq_self_iff] @[simp] lemma take_eq_left_iff {x y : List Ξ±} {n : β„•} : (x ++ y).take n = x.take n ↔ y = [] ∨ n ≀ x.length := by simp [take_append, Nat.sub_eq_zero_iff_le, Or.comm] @[simp] lemma left_eq_take_iff {x y : List Ξ±} {n : β„•} : x.take n = (x ++ y).take n ↔ y = [] ∨ n ≀ x.length := by rw [Eq.comm]; apply take_eq_left_iff @[simp] lemma drop_take_append_drop (x : List Ξ±) (m n : β„•) : (x.drop m).take n ++ x.drop (m + n) = x.drop m := by rw [← drop_drop, take_append_drop] /-- Compared to `drop_take_append_drop`, the order of summands is swapped. -/ @[simp] lemma drop_take_append_drop' (x : List Ξ±) (m n : β„•) : (x.drop m).take n ++ x.drop (n + m) = x.drop m := by rw [Nat.add_comm, drop_take_append_drop] /-- `take_concat_get` in simp normal form -/ lemma take_concat_get' (l : List Ξ±) (i : β„•) (h : i < l.length) : l.take i ++ [l[i]] = l.take (i + 1) := by simp theorem cons_getElem_drop_succ {l : List Ξ±} {n : Nat} {h : n < l.length} : l[n] :: l.drop (n + 1) = l.drop n := (drop_eq_getElem_cons h).symm theorem cons_get_drop_succ {l : List Ξ±} {n} : l.get n :: l.drop (n.1 + 1) = l.drop n.1 := (drop_eq_getElem_cons n.2).symm lemma drop_length_sub_one {l : List Ξ±} (h : l β‰  []) : l.drop (l.length - 1) = [l.getLast h] := by induction l with | nil => aesop | cons a l ih => by_cases hl : l = [] Β· simp_all rw [length_cons, Nat.add_one_sub_one, List.drop_length_cons hl a] simp [getLast_cons, hl] section TakeI variable [Inhabited Ξ±] @[simp] theorem takeI_length : βˆ€ n l, length (@takeI Ξ± _ n l) = n | 0, _ => rfl | _ + 1, _ => congr_arg succ (takeI_length _ _) @[simp] theorem takeI_nil : βˆ€ n, takeI n (@nil Ξ±) = replicate n default | 0 => rfl | _ + 1 => congr_arg (cons _) (takeI_nil _) theorem takeI_eq_take : βˆ€ {n} {l : List Ξ±}, n ≀ length l β†’ takeI n l = take n l | 0, _, _ => rfl | _ + 1, _ :: _, h => congr_arg (cons _) <| takeI_eq_take <| le_of_succ_le_succ h @[simp] theorem takeI_left (l₁ lβ‚‚ : List Ξ±) : takeI (length l₁) (l₁ ++ lβ‚‚) = l₁ := (takeI_eq_take (by simp only [length_append, Nat.le_add_right])).trans take_left theorem takeI_left' {l₁ lβ‚‚ : List Ξ±} {n} (h : length l₁ = n) : takeI n (l₁ ++ lβ‚‚) = l₁ := by rw [← h]; apply takeI_left end TakeI /- The following section replicates the theorems above but for `takeD`. -/ section TakeD @[simp] theorem takeD_length : βˆ€ n l a, length (@takeD Ξ± n l a) = n | 0, _, _ => rfl | _ + 1, _, _ => congr_arg succ (takeD_length _ _ _) -- `takeD_nil` is already in batteries theorem takeD_eq_take : βˆ€ {n} {l : List Ξ±} a, n ≀ length l β†’ takeD n l a = take n l | 0, _, _, _ => rfl | _ + 1, _ :: _, a, h => congr_arg (cons _) <| takeD_eq_take a <| le_of_succ_le_succ h @[simp] theorem takeD_left (l₁ lβ‚‚ : List Ξ±) (a : Ξ±) : takeD (length l₁) (l₁ ++ lβ‚‚) a = l₁ := (takeD_eq_take a (by simp only [length_append, Nat.le_add_right])).trans take_left theorem takeD_left' {l₁ lβ‚‚ : List Ξ±} {n} {a} (h : length l₁ = n) : takeD n (l₁ ++ lβ‚‚) a = l₁ := by rw [← h]; apply takeD_left end TakeD /-! ### filter -/ section Filter variable (p) variable (p : Ξ± β†’ Bool) private theorem span.loop_eq_take_drop : βˆ€ l₁ lβ‚‚ : List Ξ±, span.loop p l₁ lβ‚‚ = (lβ‚‚.reverse ++ takeWhile p l₁, dropWhile p l₁) | [], lβ‚‚ => by simp [span.loop, takeWhile, dropWhile] | (a :: l), lβ‚‚ => by cases hp : p a <;> simp [hp, span.loop, span.loop_eq_take_drop, takeWhile, dropWhile] @[simp] theorem span_eq_takeWhile_dropWhile (l : List Ξ±) : span p l = (takeWhile p l, dropWhile p l) := by simpa using span.loop_eq_take_drop p l [] end Filter /-! ### Miscellaneous lemmas -/ theorem dropSlice_eq (xs : List Ξ±) (n m : β„•) : dropSlice n m xs = xs.take n ++ xs.drop (n + m) := by induction n generalizing xs with cases xs with grind [dropSlice] @[simp, grind =] theorem length_dropSlice (i j : β„•) (xs : List Ξ±) : (dropSlice i j xs).length = xs.length - min j (xs.length - i) := by induction xs generalizing i j with cases i with grind [dropSlice] theorem length_dropSlice_lt (i j : β„•) (hj : 0 < j) (xs : List Ξ±) (hi : i < xs.length) : (dropSlice i j xs).length < xs.length := by grind end List
.lake/packages/mathlib/Mathlib/Data/List/Prime.lean
import Mathlib.Algebra.BigOperators.Group.List.Lemmas import Mathlib.Algebra.GroupWithZero.Associated /-! # Products of lists of prime elements. This file contains some theorems relating `Prime` and products of `List`s. -/ open List section CommMonoidWithZero variable {M : Type*} [CommMonoidWithZero M] /-- Prime `p` divides the product of a list `L` iff it divides some `a ∈ L` -/ theorem Prime.dvd_prod_iff {p : M} {L : List M} (pp : Prime p) : p ∣ L.prod ↔ βˆƒ a ∈ L, p ∣ a := by constructor Β· intro h induction L with | nil => rw [prod_nil] at h exact absurd h pp.not_dvd_one | cons L_hd L_tl L_ih => rw [prod_cons] at h rcases pp.dvd_or_dvd h with hd | hd Β· exact ⟨L_hd, mem_cons_self, hd⟩ Β· obtain ⟨x, hx1, hx2⟩ := L_ih hd exact ⟨x, mem_cons_of_mem L_hd hx1, hx2⟩ Β· exact fun ⟨a, ha1, ha2⟩ => dvd_trans ha2 (dvd_prod ha1) theorem Prime.not_dvd_prod {p : M} {L : List M} (pp : Prime p) (hL : βˆ€ a ∈ L, Β¬p ∣ a) : Β¬p ∣ L.prod := mt (Prime.dvd_prod_iff pp).1 <| not_exists.2 fun a => not_and.2 (hL a) end CommMonoidWithZero section CancelCommMonoidWithZero variable {M : Type*} [CancelCommMonoidWithZero M] [Subsingleton MΛ£] theorem mem_list_primes_of_dvd_prod {p : M} (hp : Prime p) {L : List M} (hL : βˆ€ q ∈ L, Prime q) (hpL : p ∣ L.prod) : p ∈ L := by obtain ⟨x, hx1, hx2⟩ := hp.dvd_prod_iff.mp hpL rwa [(prime_dvd_prime_iff_eq hp (hL x hx1)).mp hx2] theorem perm_of_prod_eq_prod : βˆ€ {l₁ lβ‚‚ : List M}, l₁.prod = lβ‚‚.prod β†’ (βˆ€ p ∈ l₁, Prime p) β†’ (βˆ€ p ∈ lβ‚‚, Prime p) β†’ Perm l₁ lβ‚‚ | [], [], _, _, _ => Perm.nil | [], a :: l, h₁, _, h₃ => have ha : a ∣ 1 := prod_nil (Ξ± := M) β–Έ h₁.symm β–Έ (prod_cons (l := l)).symm β–Έ dvd_mul_right _ _ absurd ha (Prime.not_dvd_one (h₃ a mem_cons_self)) | a :: l, [], h₁, hβ‚‚, _ => have ha : a ∣ 1 := prod_nil (Ξ± := M) β–Έ h₁ β–Έ (prod_cons (l := l)).symm β–Έ dvd_mul_right _ _ absurd ha (Prime.not_dvd_one (hβ‚‚ a mem_cons_self)) | a :: l₁, b :: lβ‚‚, h, hl₁, hlβ‚‚ => by classical have hl₁' : βˆ€ p ∈ l₁, Prime p := fun p hp => hl₁ p (mem_cons_of_mem _ hp) have hlβ‚‚' : βˆ€ p ∈ (b :: lβ‚‚).erase a, Prime p := fun p hp => hlβ‚‚ p (mem_of_mem_erase hp) have ha : a ∈ b :: lβ‚‚ := mem_list_primes_of_dvd_prod (hl₁ a mem_cons_self) hlβ‚‚ (h β–Έ by rw [prod_cons]; exact dvd_mul_right _ _) have hb : b :: lβ‚‚ ~ a :: (b :: lβ‚‚).erase a := perm_cons_erase ha have hl : prod l₁ = prod ((b :: lβ‚‚).erase a) := (mul_right_inj' (hl₁ a mem_cons_self).ne_zero).1 <| by rwa [← prod_cons, ← prod_cons, ← hb.prod_eq] exact Perm.trans ((perm_of_prod_eq_prod hl hl₁' hlβ‚‚').cons _) hb.symm end CancelCommMonoidWithZero
.lake/packages/mathlib/Mathlib/Data/List/Range.lean
import Mathlib.Data.List.Chain /-! # Ranges of naturals as lists This file shows basic results about `List.iota`, `List.range`, `List.range'` and defines `List.finRange`. `finRange n` is the list of elements of `Fin n`. `iota n = [n, n - 1, ..., 1]` and `range n = [0, ..., n - 1]` are basic list constructions used for tactics. `range' a b = [a, ..., a + b - 1]` is there to help prove properties about them. Actual maths should use `List.Ico` instead. -/ universe u open Nat namespace List variable {Ξ± : Type u} theorem getElem_range'_1 {n m} (i) (H : i < (range' n m).length) : (range' n m)[i] = n + i := by simp theorem isChain_range (r : β„• β†’ β„• β†’ Prop) (n : β„•) : IsChain r (range n) ↔ βˆ€ m < n - 1, r m m.succ := by induction n with | zero => simp | succ n hn => simp only [range_succ, Nat.add_one_sub_one, Nat.lt_sub_iff_add_lt] at hn ⊒ cases n with | zero => simp | succ n => simp only [range_succ, Nat.add_lt_add_iff_right, succ_eq_add_one, append_assoc, cons_append, nil_append, isChain_append_cons_cons, IsChain.singleton, and_true] at hn ⊒ rw [hn, forall_lt_succ_right] theorem isChain_range_succ (r : β„• β†’ β„• β†’ Prop) (n : β„•) : IsChain r (range n.succ) ↔ βˆ€ m < n, r m m.succ := by rw [isChain_range, succ_eq_add_one, Nat.add_one_sub_one] theorem isChain_cons_range_succ (r : β„• β†’ β„• β†’ Prop) (n a : β„•) : IsChain r (a :: range n.succ) ↔ r a 0 ∧ βˆ€ m < n, r m m.succ := by rw [range_succ_eq_map, isChain_cons_cons, and_congr_right_iff, ← isChain_range_succ, range_succ_eq_map] exact fun _ => Iff.rfl @[deprecated (since := "2025-09-21")] alias chain_range_succ := isChain_cons_range_succ @[deprecated (since := "2025-09-24")] alias chain'_range_succ := isChain_range_succ section Ranges /-- From `l : List β„•`, construct `l.ranges : List (List β„•)` such that `l.ranges.map List.length = l` and `l.ranges.join = range l.sum` * Example: `[1,2,3].ranges = [[0],[1,2],[3,4,5]]` -/ def ranges : List β„• β†’ List (List β„•) | [] => nil | a::l => range a::(ranges l).map (map (a + Β·)) /-- The members of `l.ranges` are pairwise disjoint -/ theorem ranges_disjoint (l : List β„•) : Pairwise Disjoint (ranges l) := by induction l with | nil => exact Pairwise.nil | cons a l hl => simp only [ranges, pairwise_cons] constructor Β· intro s hs obtain ⟨s', _, rfl⟩ := mem_map.mp hs intro u hu rw [mem_map] rw [mem_range] at hu cutsat Β· rw [pairwise_map] apply Pairwise.imp _ hl intro u v apply disjoint_map exact fun u v => Nat.add_left_cancel /-- The lengths of the members of `l.ranges` are those given by `l` -/ theorem ranges_length (l : List β„•) : l.ranges.map length = l := by induction l with | nil => simp only [ranges, map_nil] | cons a l hl => -- (a :: l) simp only [ranges, map_cons, length_range, map_map, cons.injEq, true_and] conv_rhs => rw [← hl] apply map_congr_left intro s _ simp only [Function.comp_apply, length_map] end Ranges end List
.lake/packages/mathlib/Mathlib/Data/List/TakeWhile.lean
import Mathlib.Order.Basic import Mathlib.Data.Nat.Basic import Mathlib.Tactic.Set /-! ### List.takeWhile and List.dropWhile -/ namespace List variable {Ξ± : Type*} (p : Ξ± β†’ Bool) theorem dropWhile_get_zero_not (l : List Ξ±) (hl : 0 < (l.dropWhile p).length) : Β¬p ((l.dropWhile p).get ⟨0, hl⟩) := by induction l with | nil => cases hl | cons hd tl IH => simp only [dropWhile] by_cases hp : p hd Β· simp_all only [get_eq_getElem] apply IH simp_all only [dropWhile_cons_of_pos] Β· simp [hp] theorem length_dropWhile_le (l : List Ξ±) : (dropWhile p l).length ≀ l.length := by induction l with | nil => simp | cons head tail ih => simp only [dropWhile, length_cons] split Β· cutsat Β· simp variable {p} {l : List Ξ±} @[simp] theorem dropWhile_eq_nil_iff : dropWhile p l = [] ↔ βˆ€ x ∈ l, p x := by induction l with | nil => simp [dropWhile] | cons x xs IH => by_cases hp : p x <;> simp [hp, IH] @[simp] theorem dropWhile_eq_self_iff : dropWhile p l = l ↔ βˆ€ hl : 0 < l.length, Β¬p (l[0]'hl) := by rcases l with - | ⟨hd, tl⟩ Β· simp Β· rw [dropWhile] by_cases h_p_hd : p hd Β· simp only [h_p_hd, length_cons, Nat.zero_lt_succ, getElem_cons_zero, not_true_eq_false, imp_false, iff_false] intro h replace h := congrArg length h have := length_dropWhile_le p tl simp at h cutsat Β· simp [h_p_hd] @[simp] theorem takeWhile_eq_self_iff : takeWhile p l = l ↔ βˆ€ x ∈ l, p x := by induction l with | nil => simp | cons x xs IH => by_cases hp : p x <;> simp [hp, IH] @[simp] theorem takeWhile_eq_nil_iff : takeWhile p l = [] ↔ βˆ€ hl : 0 < l.length, Β¬p (l.get ⟨0, hl⟩) := by induction l with | nil => simp only [takeWhile_nil, Bool.not_eq_true, true_iff] intro h simp at h | cons x xs IH => by_cases hp : p x <;> simp [hp] theorem mem_takeWhile_imp {x : Ξ±} (hx : x ∈ takeWhile p l) : p x := by induction l with simp [takeWhile] at hx | cons hd tl IH => cases hp : p hd Β· simp [hp] at hx Β· rw [hp, mem_cons] at hx rcases hx with (rfl | hx) Β· exact hp Β· exact IH hx theorem takeWhile_takeWhile (p q : Ξ± β†’ Bool) (l : List Ξ±) : takeWhile p (takeWhile q l) = takeWhile (fun a => p a ∧ q a) l := by induction l with | nil => simp | cons hd tl IH => by_cases hp : p hd <;> by_cases hq : q hd <;> simp [takeWhile, hp, hq, IH] theorem takeWhile_idem : takeWhile p (takeWhile p l) = takeWhile p l := by simp_rw [takeWhile_takeWhile, and_self_iff, Bool.decide_coe] variable (p) (l) lemma find?_eq_head?_dropWhile_not : l.find? p = (l.dropWhile (fun x ↦ !(p x))).head? := by induction l case nil => simp case cons head tail hi => set ph := p head with phh rcases ph with rfl | rfl Β· have phh' : Β¬(p head = true) := by simp [phh.symm] rw [find?_cons_of_neg phh', dropWhile_cons_of_pos] Β· exact hi Β· simpa using phh Β· rw [find?_cons_of_pos phh.symm, dropWhile_cons_of_neg] Β· simp Β· simpa using phh lemma find?_not_eq_head?_dropWhile : l.find? (fun x ↦ !(p x)) = (l.dropWhile p).head? := by convert l.find?_eq_head?_dropWhile_not ?_ simp variable {p} {l} lemma find?_eq_head_dropWhile_not (h : βˆƒ x ∈ l, p x) : l.find? p = some ((l.dropWhile (fun x ↦ !(p x))).head (by simpa using h)) := by rw [l.find?_eq_head?_dropWhile_not p, ← head_eq_iff_head?_eq_some] lemma find?_not_eq_head_dropWhile (h : βˆƒ x ∈ l, Β¬p x) : l.find? (fun x ↦ !(p x)) = some ((l.dropWhile p).head (by simpa using h)) := by convert l.find?_eq_head_dropWhile_not ?_ Β· simp Β· simpa using h end List
.lake/packages/mathlib/Mathlib/Data/List/OfFn.lean
import Mathlib.Data.Fin.Tuple.Basic /-! # Lists from functions Theorems and lemmas for dealing with `List.ofFn`, which converts a function on `Fin n` to a list of length `n`. ## Main Statements The main statements pertain to lists generated using `List.ofFn` - `List.get?_ofFn`, which tells us the nth element of such a list - `List.equivSigmaTuple`, which is an `Equiv` between lists and the functions that generate them via `List.ofFn`. -/ assert_not_exists Monoid universe u variable {Ξ± : Type u} open Nat namespace List theorem get_ofFn {n} (f : Fin n β†’ Ξ±) (i) : get (ofFn f) i = f (Fin.cast (by simp) i) := by simp; congr @[simp] theorem map_ofFn {Ξ² : Type*} {n : β„•} (f : Fin n β†’ Ξ±) (g : Ξ± β†’ Ξ²) : map g (ofFn f) = ofFn (g ∘ f) := ext_get (by simp) fun i h h' => by simp /-- Useful if `rw [← map_ofFn]` complains that `g ∘ f` is not the same as `fun i => g (f i)`. -/ theorem ofFn_comp' {Ξ² : Type*} {n : β„•} (f : Fin n β†’ Ξ±) (g : Ξ± β†’ Ξ²) : ofFn (fun i => g (f i)) = map g (ofFn f) := (map_ofFn f g).symm @[congr] theorem ofFn_congr {m n : β„•} (h : m = n) (f : Fin m β†’ Ξ±) : ofFn f = ofFn fun i : Fin n => f (Fin.cast h.symm i) := by subst h simp_rw [Fin.cast_refl, id] theorem ofFn_succ' {n} (f : Fin (succ n) β†’ Ξ±) : ofFn f = (ofFn fun i => f (Fin.castSucc i)).concat (f (Fin.last _)) := by induction n with | zero => rw [ofFn_zero, concat_nil, ofFn_succ, ofFn_zero, Fin.last_zero] | succ n IH => rw [ofFn_succ, IH, ofFn_succ, concat_cons, Fin.castSucc_zero, Fin.succ_last] simp only [succ_eq_add_one, Fin.castSucc_succ] @[simp] theorem ofFn_fin_append {m n} (a : Fin m β†’ Ξ±) (b : Fin n β†’ Ξ±) : List.ofFn (Fin.append a b) = List.ofFn a ++ List.ofFn b := by simp_rw [ofFn_add] simp [Fin.append_left', Fin.append_right] /-- This breaks a list of `m*n` items into `m` groups each containing `n` elements. -/ theorem ofFn_mul {m n} (f : Fin (m * n) β†’ Ξ±) : List.ofFn f = List.flatten (List.ofFn fun i : Fin m => List.ofFn fun j : Fin n => f ⟨i * n + j, calc ↑i * n + j < (i + 1) * n := (Nat.add_lt_add_left j.prop _).trans_eq (by rw [Nat.add_mul, Nat.one_mul]) _ ≀ _ := Nat.mul_le_mul_right _ i.prop⟩) := by induction m with | zero => simp [ofFn_zero, Nat.zero_mul, ofFn_zero] | succ m IH => simp_rw [ofFn_succ', succ_mul] simp [ofFn_add, IH] rfl /-- This breaks a list of `m*n` items into `n` groups each containing `m` elements. -/ theorem ofFn_mul' {m n} (f : Fin (m * n) β†’ Ξ±) : List.ofFn f = List.flatten (List.ofFn fun i : Fin n => List.ofFn fun j : Fin m => f ⟨m * i + j, calc m * i + j < m * (i + 1) := (Nat.add_lt_add_left j.prop _).trans_eq (by rw [Nat.mul_add, Nat.mul_one]) _ ≀ _ := Nat.mul_le_mul_left _ i.prop⟩) := by simp_rw [m.mul_comm, ofFn_mul, Fin.cast_mk] @[simp] theorem ofFn_get : βˆ€ l : List Ξ±, (ofFn (get l)) = l | [] => by rw [ofFn_zero] | a :: l => by rw [ofFn_succ] congr exact ofFn_get l @[simp] theorem ofFn_getElem : βˆ€ l : List Ξ±, (ofFn (fun i : Fin l.length => l[(i : Nat)])) = l | [] => by rw [ofFn_zero] | a :: l => by rw [ofFn_succ] congr exact ofFn_get l @[simp] theorem ofFn_getElem_eq_map {Ξ² : Type*} (l : List Ξ±) (f : Ξ± β†’ Ξ²) : ofFn (fun i : Fin l.length => f <| l[(i : Nat)]) = l.map f := by rw [← Function.comp_def, ← map_ofFn, ofFn_getElem] -- Note there is a now another `mem_ofFn` defined in Lean, with an existential on the RHS, -- which is marked as a simp lemma. theorem mem_ofFn' {n} (f : Fin n β†’ Ξ±) (a : Ξ±) : a ∈ ofFn f ↔ a ∈ Set.range f := by grind theorem forall_mem_ofFn_iff {n : β„•} {f : Fin n β†’ Ξ±} {P : Ξ± β†’ Prop} : (βˆ€ i ∈ ofFn f, P i) ↔ βˆ€ j : Fin n, P (f j) := by simp @[simp] theorem ofFn_const : βˆ€ (n : β„•) (c : Ξ±), (ofFn fun _ : Fin n => c) = replicate n c | 0, c => by rw [ofFn_zero, replicate_zero] | n + 1, c => by rw [replicate, ← ofFn_const n]; simp @[simp] theorem ofFn_fin_repeat {m} (a : Fin m β†’ Ξ±) (n : β„•) : List.ofFn (Fin.repeat n a) = (List.replicate n (List.ofFn a)).flatten := by simp_rw [ofFn_mul, ← ofFn_const, Fin.repeat, Fin.modNat, Nat.add_comm, Nat.add_mul_mod_self_right, Nat.mod_eq_of_lt (Fin.is_lt _)] @[simp] theorem pairwise_ofFn {R : Ξ± β†’ Ξ± β†’ Prop} {n} {f : Fin n β†’ Ξ±} : (ofFn f).Pairwise R ↔ βˆ€ ⦃i j⦄, i < j β†’ R (f i) (f j) := by simp only [pairwise_iff_getElem, length_ofFn, List.getElem_ofFn, Fin.forall_iff, Fin.mk_lt_mk, forall_comm (Ξ± := (_ : Prop)) (Ξ² := β„•)] lemma getLast_ofFn_succ {n : β„•} (f : Fin n.succ β†’ Ξ±) : (ofFn f).getLast (mt ofFn_eq_nil_iff.1 (Nat.succ_ne_zero _)) = f (Fin.last _) := getLast_ofFn _ lemma ofFn_cons {n} (a : Ξ±) (f : Fin n β†’ Ξ±) : ofFn (Fin.cons a f) = a :: ofFn f := by rw [ofFn_succ] rfl lemma find?_ofFn_eq_some {n} {f : Fin n β†’ Ξ±} {p : Ξ± β†’ Bool} {b : Ξ±} : (ofFn f).find? p = some b ↔ p b = true ∧ βˆƒ i, f i = b ∧ βˆ€ j < i, Β¬(p (f j) = true) := by rw [find?_eq_some_iff_getElem] exact ⟨fun ⟨hpb, i, hi, hfb, h⟩ ↦ ⟨hpb, ⟨⟨i, length_ofFn (f := f) β–Έ hi⟩, by simpa using hfb, fun j hj ↦ by simpa using h j hj⟩⟩, fun ⟨hpb, i, hfb, h⟩ ↦ ⟨hpb, ⟨i, (length_ofFn (f := f)).symm β–Έ i.isLt, by simpa using hfb, fun j hj ↦ by simpa using h ⟨j, by cutsat⟩ (by simpa using hj)⟩⟩⟩ lemma find?_ofFn_eq_some_of_injective {n} {f : Fin n β†’ Ξ±} {p : Ξ± β†’ Bool} {i : Fin n} (h : Function.Injective f) : (ofFn f).find? p = some (f i) ↔ p (f i) = true ∧ βˆ€ j < i, Β¬(p (f j) = true) := by simp only [find?_ofFn_eq_some, h.eq_iff, Bool.not_eq_true, exists_eq_left] /-- Lists are equivalent to the sigma type of tuples of a given length. -/ @[simps] def equivSigmaTuple : List Ξ± ≃ Ξ£ n, Fin n β†’ Ξ± where toFun l := ⟨l.length, l.get⟩ invFun f := List.ofFn f.2 left_inv := List.ofFn_get right_inv := fun ⟨_, f⟩ => Fin.sigma_eq_of_eq_comp_cast length_ofFn <| funext fun i => get_ofFn f i /-- A recursor for lists that expands a list into a function mapping to its elements. This can be used with `induction l using List.ofFnRec`. -/ @[elab_as_elim] def ofFnRec {C : List Ξ± β†’ Sort*} (h : βˆ€ (n) (f : Fin n β†’ Ξ±), C (List.ofFn f)) (l : List Ξ±) : C l := cast (congr_arg C l.ofFn_get) <| h l.length l.get @[simp] theorem ofFnRec_ofFn {C : List Ξ± β†’ Sort*} (h : βˆ€ (n) (f : Fin n β†’ Ξ±), C (List.ofFn f)) {n : β„•} (f : Fin n β†’ Ξ±) : @ofFnRec _ C h (List.ofFn f) = h _ f := equivSigmaTuple.rightInverse_symm.cast_eq (fun s => h s.1 s.2) ⟨n, f⟩ theorem exists_iff_exists_tuple {P : List Ξ± β†’ Prop} : (βˆƒ l : List Ξ±, P l) ↔ βˆƒ (n : _) (f : Fin n β†’ Ξ±), P (List.ofFn f) := equivSigmaTuple.symm.surjective.exists.trans Sigma.exists theorem forall_iff_forall_tuple {P : List Ξ± β†’ Prop} : (βˆ€ l : List Ξ±, P l) ↔ βˆ€ (n) (f : Fin n β†’ Ξ±), P (List.ofFn f) := equivSigmaTuple.symm.surjective.forall.trans Sigma.forall /-- `Fin.sigma_eq_iff_eq_comp_cast` may be useful to work with the RHS of this expression. -/ theorem ofFn_inj' {m n : β„•} {f : Fin m β†’ Ξ±} {g : Fin n β†’ Ξ±} : ofFn f = ofFn g ↔ (⟨m, f⟩ : Ξ£ n, Fin n β†’ Ξ±) = ⟨n, g⟩ := Iff.symm <| equivSigmaTuple.symm.injective.eq_iff.symm /-- Note we can only state this when the two functions are indexed by defeq `n`. -/ theorem ofFn_injective {n : β„•} : Function.Injective (ofFn : (Fin n β†’ Ξ±) β†’ List Ξ±) := fun f g h => eq_of_heq <| by rw [ofFn_inj'] at h; cases h; rfl /-- A special case of `List.ofFn_inj` for when the two functions are indexed by defeq `n`. -/ @[simp] theorem ofFn_inj {n : β„•} {f g : Fin n β†’ Ξ±} : ofFn f = ofFn g ↔ f = g := ofFn_injective.eq_iff end List
.lake/packages/mathlib/Mathlib/Data/List/Palindrome.lean
import Mathlib.Data.List.Induction /-! # Palindromes This module defines *palindromes*, lists which are equal to their reverse. The main result is the `Palindrome` inductive type, and its associated `Palindrome.rec` induction principle. Also provided are conversions to and from other equivalent definitions. ## References * [Pierre CastΓ©ran, *On palindromes*][casteran] [casteran]: https://www.labri.fr/perso/casteran/CoqArt/inductive-prop-chap/palindrome.html ## Tags palindrome, reverse, induction -/ variable {Ξ± Ξ² : Type*} namespace List /-- `Palindrome l` asserts that `l` is a palindrome. This is defined inductively: * The empty list is a palindrome; * A list with one element is a palindrome; * Adding the same element to both ends of a palindrome results in a bigger palindrome. -/ inductive Palindrome : List Ξ± β†’ Prop | nil : Palindrome [] | singleton : βˆ€ x, Palindrome [x] | cons_concat : βˆ€ (x) {l}, Palindrome l β†’ Palindrome (x :: (l ++ [x])) namespace Palindrome variable {l : List Ξ±} theorem reverse_eq {l : List Ξ±} (p : Palindrome l) : reverse l = l := by induction p <;> try (exact rfl) simpa theorem of_reverse_eq {l : List Ξ±} : reverse l = l β†’ Palindrome l := by refine bidirectionalRecOn l (fun _ => Palindrome.nil) (fun a _ => Palindrome.singleton a) ?_ intro x l y hp hr rw [reverse_cons, reverse_append] at hr rw [head_eq_of_cons_eq hr] have : Palindrome l := hp (append_inj_left' (tail_eq_of_cons_eq hr) rfl) exact Palindrome.cons_concat x this theorem iff_reverse_eq {l : List Ξ±} : Palindrome l ↔ reverse l = l := Iff.intro reverse_eq of_reverse_eq theorem append_reverse (l : List Ξ±) : Palindrome (l ++ reverse l) := by apply of_reverse_eq rw [reverse_append, reverse_reverse] protected theorem map (f : Ξ± β†’ Ξ²) (p : Palindrome l) : Palindrome (map f l) := of_reverse_eq <| by rw [← map_reverse, p.reverse_eq] instance [DecidableEq Ξ±] (l : List Ξ±) : Decidable (Palindrome l) := decidable_of_iff' _ iff_reverse_eq end Palindrome end List
.lake/packages/mathlib/Mathlib/Data/List/Lookmap.lean
import Batteries.Logic import Batteries.Data.List.Basic import Mathlib.Tactic.TypeStar /-! ### lookmap -/ variable {Ξ± Ξ² : Type*} namespace List variable (f : Ξ± β†’ Option Ξ±) private theorem lookmap.go_append (l : List Ξ±) (acc : Array Ξ±) : lookmap.go f l acc = acc.toListAppend (lookmap f l) := by cases l with | nil => simp [go, lookmap] | cons hd tl => rw [lookmap, go, go] cases f hd with | none => simp only [go_append tl _, Array.toListAppend_eq, append_assoc, Array.toList_push] rfl | some a => rfl @[simp, grind =] theorem lookmap_nil : [].lookmap f = [] := rfl @[simp] theorem lookmap_cons_none {a : Ξ±} (l : List Ξ±) (h : f a = none) : (a :: l).lookmap f = a :: l.lookmap f := by simp only [lookmap, lookmap.go, Array.toListAppend_eq, nil_append] rw [lookmap.go_append, h]; rfl @[simp] theorem lookmap_cons_some {a b : Ξ±} (l : List Ξ±) (h : f a = some b) : (a :: l).lookmap f = b :: l := by simp only [lookmap, lookmap.go, Array.toListAppend_eq, nil_append] rw [h] @[grind =] theorem lookmap_cons {a : Ξ±} {l : List Ξ±} : (a :: l).lookmap f = match f a with | none => a :: l.lookmap f | some b => b :: l := by cases h : f a <;> simp_all theorem lookmap_some : βˆ€ l : List Ξ±, l.lookmap some = l | [] => rfl | _ :: _ => rfl theorem lookmap_none : βˆ€ l : List Ξ±, (l.lookmap fun _ => none) = l | [] => rfl | a :: l => (lookmap_cons_none _ l rfl).trans (congr_arg (cons a) (lookmap_none l)) theorem lookmap_congr {f g : Ξ± β†’ Option Ξ±} : βˆ€ {l : List Ξ±}, (βˆ€ a ∈ l, f a = g a) β†’ l.lookmap f = l.lookmap g | [], _ => rfl | a :: l, H => by obtain ⟨H₁, Hβ‚‚βŸ© := forall_mem_cons.1 H rcases h : g a with - | b Β· simp [h, H₁.trans h, lookmap_congr Hβ‚‚] Β· simp [lookmap_cons_some _ _ h, lookmap_cons_some _ _ (H₁.trans h)] theorem lookmap_of_forall_not {l : List Ξ±} (H : βˆ€ a ∈ l, f a = none) : l.lookmap f = l := (lookmap_congr H).trans (lookmap_none l) theorem lookmap_map_eq (g : Ξ± β†’ Ξ²) (h : βˆ€ (a), βˆ€ b ∈ f a, g a = g b) : βˆ€ l : List Ξ±, map g (l.lookmap f) = map g l | [] => rfl | a :: l => by rcases h' : f a with - | b Β· simpa [h'] using lookmap_map_eq _ h l Β· simp [lookmap_cons_some _ _ h', h _ _ h'] theorem lookmap_id' (h : βˆ€ (a), βˆ€ b ∈ f a, a = b) (l : List Ξ±) : l.lookmap f = l := by rw [← map_id (l.lookmap f), lookmap_map_eq, map_id]; exact h @[simp, grind =] theorem length_lookmap (l : List Ξ±) : length (l.lookmap f) = length l := by rw [← length_map, lookmap_map_eq _ fun _ => (), length_map]; simp open Perm in theorem perm_lookmap (f : Ξ± β†’ Option Ξ±) {l₁ lβ‚‚ : List Ξ±} (H : Pairwise (fun a b => βˆ€ c ∈ f a, βˆ€ d ∈ f b, a = b ∧ c = d) l₁) (p : l₁ ~ lβ‚‚) : lookmap f l₁ ~ lookmap f lβ‚‚ := by induction p with | nil => simp | cons a p IH => cases h : f a Β· simpa [h] using IH (pairwise_cons.1 H).2 Β· simp [lookmap_cons_some _ _ h, p] | swap a b l => rcases h₁ : f a with - | c <;> rcases hβ‚‚ : f b with - | d Β· simpa [h₁, hβ‚‚] using swap _ _ _ Β· simpa [h₁, lookmap_cons_some _ _ hβ‚‚] using swap _ _ _ Β· simpa [lookmap_cons_some _ _ h₁, hβ‚‚] using swap _ _ _ Β· rcases (pairwise_cons.1 H).1 _ (mem_cons.2 (Or.inl rfl)) _ hβ‚‚ _ h₁ with ⟨rfl, rfl⟩ exact Perm.refl _ | trans p₁ _ IH₁ IHβ‚‚ => refine (IH₁ H).trans (IHβ‚‚ ((p₁.pairwise_iff ?_).1 H)) grind end List
.lake/packages/mathlib/Mathlib/Data/List/Enum.lean
import Mathlib.Data.List.Basic /-! # Properties of `List.enum` -/ namespace List variable {Ξ± : Type*} theorem forall_mem_zipIdx {l : List Ξ±} {n : β„•} {p : Ξ± Γ— β„• β†’ Prop} : (βˆ€ x ∈ l.zipIdx n, p x) ↔ βˆ€ (i : β„•) (_ : i < length l), p (l[i], n + i) := by simp only [forall_mem_iff_getElem, getElem_zipIdx, length_zipIdx] /-- Variant of `forall_mem_zipIdx` with the `zipIdx` argument specialized to `0`. -/ theorem forall_mem_zipIdx' {l : List Ξ±} {p : Ξ± Γ— β„• β†’ Prop} : (βˆ€ x ∈ l.zipIdx, p x) ↔ βˆ€ (i : β„•) (_ : i < length l), p (l[i], i) := forall_mem_zipIdx.trans <| by simp theorem exists_mem_zipIdx {l : List Ξ±} {n : β„•} {p : Ξ± Γ— β„• β†’ Prop} : (βˆƒ x ∈ l.zipIdx n, p x) ↔ βˆƒ (i : β„•) (_ : i < length l), p (l[i], n + i) := by simp only [exists_mem_iff_getElem, getElem_zipIdx, length_zipIdx] /-- Variant of `exists_mem_zipIdx` with the `zipIdx` argument specialized to `0`. -/ theorem exists_mem_zipIdx' {l : List Ξ±} {p : Ξ± Γ— β„• β†’ Prop} : (βˆƒ x ∈ l.zipIdx, p x) ↔ βˆƒ (i : β„•) (_ : i < length l), p (l[i], i) := exists_mem_zipIdx.trans <| by simp end List
.lake/packages/mathlib/Mathlib/Data/List/Induction.lean
import Mathlib.Data.List.Basic /-! ### Induction principles for lists -/ variable {Ξ± : Type*} namespace List /-- Induction principle from the right for lists: if a property holds for the empty list, and for `l ++ [a]` if it holds for `l`, then it holds for all lists. The principle is given for a `Sort`-valued predicate, i.e., it can also be used to construct data. -/ @[elab_as_elim] def reverseRecOn {motive : List Ξ± β†’ Sort*} (l : List Ξ±) (nil : motive []) (append_singleton : βˆ€ (l : List Ξ±) (a : Ξ±), motive l β†’ motive (l ++ [a])) : motive l := match h : reverse l with | [] => cast (congr_arg motive <| by simpa using congr(reverse $h.symm)) <| nil | head :: tail => cast (congr_arg motive <| by simpa using congr(reverse $h.symm)) <| append_singleton _ head <| reverseRecOn (reverse tail) nil append_singleton termination_by l.length decreasing_by simp_wf rw [← length_reverse (as := l), h, length_cons] simp @[simp] theorem reverseRecOn_nil {motive : List Ξ± β†’ Sort*} (nil : motive []) (append_singleton : βˆ€ (l : List Ξ±) (a : Ξ±), motive l β†’ motive (l ++ [a])) : reverseRecOn [] nil append_singleton = nil := reverseRecOn.eq_1 .. -- `unusedHavesSuffices` is getting confused by the unfolding of `reverseRecOn` @[simp, nolint unusedHavesSuffices] theorem reverseRecOn_concat {motive : List Ξ± β†’ Sort*} (x : Ξ±) (xs : List Ξ±) (nil : motive []) (append_singleton : βˆ€ (l : List Ξ±) (a : Ξ±), motive l β†’ motive (l ++ [a])) : reverseRecOn (motive := motive) (xs ++ [x]) nil append_singleton = append_singleton _ _ (reverseRecOn (motive := motive) xs nil append_singleton) := by grind [reverseRecOn] /-- Bidirectional induction principle for lists: if a property holds for the empty list, the singleton list, and `a :: (l ++ [b])` from `l`, then it holds for all lists. This can be used to prove statements about palindromes. The principle is given for a `Sort`-valued predicate, i.e., it can also be used to construct data. -/ @[elab_as_elim] def bidirectionalRec {motive : List Ξ± β†’ Sort*} (nil : motive []) (singleton : βˆ€ a : Ξ±, motive [a]) (cons_append : βˆ€ (a : Ξ±) (l : List Ξ±) (b : Ξ±), motive l β†’ motive (a :: (l ++ [b]))) : βˆ€ l, motive l | [] => nil | [a] => singleton a | a :: b :: l => let l' := dropLast (b :: l) let b' := getLast (b :: l) (cons_ne_nil _ _) cast (by rw [← dropLast_append_getLast (cons_ne_nil b l)]) <| cons_append a l' b' (bidirectionalRec nil singleton cons_append l') termination_by l => l.length @[simp] theorem bidirectionalRec_nil {motive : List Ξ± β†’ Sort*} (nil : motive []) (singleton : βˆ€ a : Ξ±, motive [a]) (cons_append : βˆ€ (a : Ξ±) (l : List Ξ±) (b : Ξ±), motive l β†’ motive (a :: (l ++ [b]))) : bidirectionalRec nil singleton cons_append [] = nil := bidirectionalRec.eq_1 .. @[simp] theorem bidirectionalRec_singleton {motive : List Ξ± β†’ Sort*} (nil : motive []) (singleton : βˆ€ a : Ξ±, motive [a]) (cons_append : βˆ€ (a : Ξ±) (l : List Ξ±) (b : Ξ±), motive l β†’ motive (a :: (l ++ [b]))) (a : Ξ±) : bidirectionalRec nil singleton cons_append [a] = singleton a := by simp [bidirectionalRec] @[simp] theorem bidirectionalRec_cons_append {motive : List Ξ± β†’ Sort*} (nil : motive []) (singleton : βˆ€ a : Ξ±, motive [a]) (cons_append : βˆ€ (a : Ξ±) (l : List Ξ±) (b : Ξ±), motive l β†’ motive (a :: (l ++ [b]))) (a : Ξ±) (l : List Ξ±) (b : Ξ±) : bidirectionalRec nil singleton cons_append (a :: (l ++ [b])) = cons_append a l b (bidirectionalRec nil singleton cons_append l) := by conv_lhs => unfold bidirectionalRec cases l with grind /-- Like `bidirectionalRec`, but with the list parameter placed first. -/ @[elab_as_elim] abbrev bidirectionalRecOn {C : List Ξ± β†’ Sort*} (l : List Ξ±) (H0 : C []) (H1 : βˆ€ a : Ξ±, C [a]) (Hn : βˆ€ (a : Ξ±) (l : List Ξ±) (b : Ξ±), C l β†’ C (a :: (l ++ [b]))) : C l := bidirectionalRec H0 H1 Hn l /-- A dependent recursion principle for nonempty lists. Useful for dealing with operations like `List.head` which are not defined on the empty list. -/ @[elab_as_elim] def recNeNil {motive : (l : List Ξ±) β†’ l β‰  [] β†’ Sort*} (singleton : βˆ€ x, motive [x] (cons_ne_nil x [])) (cons : βˆ€ x xs h, motive xs h β†’ motive (x :: xs) (cons_ne_nil x xs)) (l : List Ξ±) (h : l β‰  []) : motive l h := match l with | [x] => singleton x | x :: y :: xs => cons x (y :: xs) (cons_ne_nil y xs) (recNeNil singleton cons (y :: xs) (cons_ne_nil y xs)) @[simp] theorem recNeNil_singleton {motive : (l : List Ξ±) β†’ l β‰  [] β†’ Sort*} (x : Ξ±) (singleton : βˆ€ x, motive [x] (cons_ne_nil x [])) (cons : βˆ€ x xs h, motive xs h β†’ motive (x :: xs) (cons_ne_nil x xs)) : recNeNil singleton cons [x] (cons_ne_nil x []) = singleton x := rfl @[simp] theorem recNeNil_cons {motive : (l : List Ξ±) β†’ l β‰  [] β†’ Sort*} (x : Ξ±) (xs : List Ξ±) (h : xs β‰  []) (singleton : βˆ€ x, motive [x] (cons_ne_nil x [])) (cons : βˆ€ x xs h, motive xs h β†’ motive (x :: xs) (cons_ne_nil x xs)) : recNeNil singleton cons (x :: xs) (cons_ne_nil x xs) = cons x xs h (recNeNil singleton cons xs h) := match xs with | _ :: _ => rfl /-- A dependent recursion principle for nonempty lists. Useful for dealing with operations like `List.head` which are not defined on the empty list. Same as `List.recNeNil`, with a more convenient argument order. -/ @[elab_as_elim, simp] abbrev recOnNeNil {motive : (l : List Ξ±) β†’ l β‰  [] β†’ Sort*} (l : List Ξ±) (h : l β‰  []) (singleton : βˆ€ x, motive [x] (cons_ne_nil x [])) (cons : βˆ€ x xs h, motive xs h β†’ motive (x :: xs) (cons_ne_nil x xs)) : motive l h := recNeNil singleton cons l h /-- A recursion principle for lists which separates the singleton case. -/ @[elab_as_elim] def twoStepInduction {motive : (l : List Ξ±) β†’ Sort*} (nil : motive []) (singleton : βˆ€ x, motive [x]) (cons_cons : βˆ€ x y xs, motive xs β†’ (βˆ€ y, motive (y :: xs)) β†’ motive (x :: y :: xs)) (l : List Ξ±) : motive l := match l with | [] => nil | [x] => singleton x | x :: y :: xs => cons_cons x y xs (twoStepInduction nil singleton cons_cons xs) (fun y => twoStepInduction nil singleton cons_cons (y :: xs)) @[simp] theorem twoStepInduction_nil {motive : (l : List Ξ±) β†’ Sort*} (nil : motive []) (singleton : βˆ€ x, motive [x]) (cons_cons : βˆ€ x y xs, motive xs β†’ (βˆ€ y, motive (y :: xs)) β†’ motive (x :: y :: xs)) : twoStepInduction nil singleton cons_cons [] = nil := twoStepInduction.eq_1 .. @[simp] theorem twoStepInduction_singleton {motive : (l : List Ξ±) β†’ Sort*} (x : Ξ±) (nil : motive []) (singleton : βˆ€ x, motive [x]) (cons_cons : βˆ€ x y xs, motive xs β†’ (βˆ€ y, motive (y :: xs)) β†’ motive (x :: y :: xs)) : twoStepInduction nil singleton cons_cons [x] = singleton x := twoStepInduction.eq_2 .. @[simp] theorem twoStepInduction_cons_cons {motive : (l : List Ξ±) β†’ Sort*} (x y : Ξ±) (xs : List Ξ±) (nil : motive []) (singleton : βˆ€ x, motive [x]) (cons_cons : βˆ€ x y xs, motive xs β†’ (βˆ€ y, motive (y :: xs)) β†’ motive (x :: y :: xs)) : twoStepInduction nil singleton cons_cons (x :: y :: xs) = cons_cons x y xs (twoStepInduction nil singleton cons_cons xs) (fun y => twoStepInduction nil singleton cons_cons (y :: xs)) := twoStepInduction.eq_3 .. end List
.lake/packages/mathlib/Mathlib/Data/List/SplitOn.lean
import Mathlib.Data.List.Basic /-! ### List.splitOn -/ namespace List variable {Ξ± : Type*} (p : Ξ± β†’ Bool) (xs : List Ξ±) (ls : List (List Ξ±)) attribute [simp] splitAt_eq @[simp] theorem splitOn_nil [DecidableEq Ξ±] (a : Ξ±) : [].splitOn a = [[]] := rfl @[simp] theorem splitOnP_nil : [].splitOnP p = [[]] := rfl theorem splitOnP.go_ne_nil (xs acc : List Ξ±) : splitOnP.go p xs acc β‰  [] := by induction xs generalizing acc <;> simp [go]; split <;> simp [*] theorem splitOnP.go_acc (xs acc : List Ξ±) : splitOnP.go p xs acc = modifyHead (acc.reverse ++ Β·) (splitOnP p xs) := by induction xs generalizing acc with | nil => simp only [go, modifyHead, splitOnP_nil, append_nil] | cons hd tl ih => simp only [splitOnP, go]; split Β· simp only [modifyHead, reverse_nil, append_nil] Β· rw [ih [hd], modifyHead_modifyHead, ih] congr; grind theorem splitOnP_ne_nil (xs : List Ξ±) : xs.splitOnP p β‰  [] := splitOnP.go_ne_nil _ _ _ @[simp] theorem splitOnP_cons (x : Ξ±) (xs : List Ξ±) : (x :: xs).splitOnP p = if p x then [] :: xs.splitOnP p else (xs.splitOnP p).modifyHead (cons x) := by rw [splitOnP, splitOnP.go]; split <;> [rfl; simp [splitOnP.go_acc]] /-- The original list `L` can be recovered by flattening the lists produced by `splitOnP p L`, interspersed with the elements `L.filter p`. -/ theorem splitOnP_spec (as : List Ξ±) : flatten (zipWith (Β· ++ Β·) (splitOnP p as) (((as.filter p).map fun x => [x]) ++ [[]])) = as := by induction as with | nil => rfl | cons a as' ih => rw [splitOnP_cons, filter] by_cases h : p a Β· rw [if_pos h, h, map, cons_append, zipWith, nil_append, flatten_cons, cons_append, cons_inj_right] exact ih Β· rw [if_neg h, eq_false_of_ne_true h, flatten_zipWith (splitOnP_ne_nil _ _) (append_ne_nil_of_right_ne_nil _ (cons_ne_nil [] [])), cons_inj_right] exact ih where flatten_zipWith {xs ys : List (List Ξ±)} {a : Ξ±} (hxs : xs β‰  []) (hys : ys β‰  []) : flatten (zipWith (fun x x_1 ↦ x ++ x_1) (modifyHead (cons a) xs) ys) = a :: flatten (zipWith (fun x x_1 ↦ x ++ x_1) xs ys) := by cases xs with | nil => contradiction | cons => cases ys with | nil => contradiction | cons => rfl /-- If no element satisfies `p` in the list `xs`, then `xs.splitOnP p = [xs]` -/ theorem splitOnP_eq_single (h : βˆ€ x ∈ xs, Β¬p x) : xs.splitOnP p = [xs] := by induction xs with | nil => simp only [splitOnP_nil] | cons hd tl ih => simp only [splitOnP_cons, h hd mem_cons_self, if_false, Bool.false_eq_true, modifyHead_cons, ih <| forall_mem_of_forall_mem_cons h] /-- When a list of the form `[...xs, sep, ...as]` is split on `p`, the first element is `xs`, assuming no element in `xs` satisfies `p` but `sep` does satisfy `p` -/ theorem splitOnP_first (h : βˆ€ x ∈ xs, Β¬p x) (sep : Ξ±) (hsep : p sep) (as : List Ξ±) : (xs ++ sep :: as).splitOnP p = xs :: as.splitOnP p := by induction xs with | nil => simp [hsep] | cons hd tl ih => simp [h hd _, ih <| forall_mem_of_forall_mem_cons h] /-- `intercalate [x]` is the left inverse of `splitOn x` -/ theorem intercalate_splitOn (x : Ξ±) [DecidableEq Ξ±] : [x].intercalate (xs.splitOn x) = xs := by simp only [intercalate, splitOn] induction xs with | nil => simp [flatten] | cons hd tl ih => ?_ rcases h' : splitOnP (Β· == x) tl with - | ⟨hd', tl'⟩; Β· exact (splitOnP_ne_nil _ tl h').elim rw [h'] at ih rw [splitOnP_cons] split_ifs with h Β· rw [beq_iff_eq] at h subst h simp [ih, flatten, h'] cases tl' <;> simpa [flatten, h'] using ih /-- `splitOn x` is the left inverse of `intercalate [x]`, on the domain consisting of each nonempty list of lists `ls` whose elements do not contain `x` -/ theorem splitOn_intercalate [DecidableEq Ξ±] (x : Ξ±) (hx : βˆ€ l ∈ ls, x βˆ‰ l) (hls : ls β‰  []) : ([x].intercalate ls).splitOn x = ls := by simp only [intercalate] induction ls with | nil => contradiction | cons hd tl ih => ?_ cases tl Β· suffices hd.splitOn x = [hd] by simpa [flatten] exact splitOnP_eq_single _ _ (by grind) Β· simp only [intersperse_consβ‚‚, singleton_append, flatten_cons] specialize ih _ _ Β· grind Β· grind simp only [splitOn] at ih ⊒ have := splitOnP_first (Β· == x) hd (by grind) x (beq_self_eq_true _) rw [this, ih] end List
.lake/packages/mathlib/Mathlib/Data/List/InsertNth.lean
import Mathlib.Data.List.InsertIdx /-! This is a stub file for importing `Mathlib/Data/List/InsertNth.lean`, which has been renamed to `Mathlib/Data/List/InsertIdx.lean`. This file can be removed once the deprecation for `List.insertNth` is removed. -/
.lake/packages/mathlib/Mathlib/Data/List/Lattice.lean
import Mathlib.Data.List.Basic /-! # Lattice structure of lists This file proves basic properties about `List.disjoint`, `List.union`, `List.inter` and `List.bagInter`, which are defined in core Lean and `Data.List.Defs`. `l₁ βˆͺ lβ‚‚` is the list where all elements of `l₁` have been inserted in `lβ‚‚` in order. For example, `[0, 0, 1, 2, 2, 3] βˆͺ [4, 3, 3, 0] = [1, 2, 4, 3, 3, 0]`. `l₁ ∩ lβ‚‚` is the list of elements of `l₁` in order which are in `lβ‚‚`. For example, `[0, 0, 1, 2, 2, 3] ∩ [4, 3, 3, 0] = [0, 0, 3]`. `List.bagInter l₁ lβ‚‚` is the list of elements that are in both `l₁` and `lβ‚‚`, counted with multiplicity and in the order they appear in `l₁`. As opposed to `List.inter`, `List.bagInter` copes well with multiplicity. For example, `bagInter [0, 1, 2, 3, 2, 1, 0] [1, 0, 1, 4, 3] = [0, 1, 3, 1]`. -/ open Nat namespace List variable {Ξ± : Type*} {l₁ lβ‚‚ : List Ξ±} {p : Ξ± β†’ Prop} {a : Ξ±} /-! ### `Disjoint` -/ section Disjoint @[symm] theorem Disjoint.symm (d : Disjoint l₁ lβ‚‚) : Disjoint lβ‚‚ l₁ := fun _ iβ‚‚ i₁ => d i₁ iβ‚‚ end Disjoint variable [DecidableEq Ξ±] /-! ### `union` -/ section Union theorem mem_union_left (h : a ∈ l₁) (lβ‚‚ : List Ξ±) : a ∈ l₁ βˆͺ lβ‚‚ := mem_union_iff.2 (Or.inl h) theorem mem_union_right (l₁ : List Ξ±) (h : a ∈ lβ‚‚) : a ∈ l₁ βˆͺ lβ‚‚ := mem_union_iff.2 (Or.inr h) theorem sublist_suffix_of_union : βˆ€ l₁ lβ‚‚ : List Ξ±, βˆƒ t, t <+ l₁ ∧ t ++ lβ‚‚ = l₁ βˆͺ lβ‚‚ | [], _ => ⟨[], by rfl, rfl⟩ | a :: l₁, lβ‚‚ => let ⟨t, s, e⟩ := sublist_suffix_of_union l₁ lβ‚‚ if h : a ∈ l₁ βˆͺ lβ‚‚ then ⟨t, sublist_cons_of_sublist _ s, by simp only [e, cons_union, insert_of_mem h]⟩ else ⟨a :: t, s.cons_cons _, by simp only [cons_append, cons_union, e, insert_of_not_mem h]⟩ theorem suffix_union_right (l₁ lβ‚‚ : List Ξ±) : lβ‚‚ <:+ l₁ βˆͺ lβ‚‚ := (sublist_suffix_of_union l₁ lβ‚‚).imp fun _ => And.right theorem union_sublist_append (l₁ lβ‚‚ : List Ξ±) : l₁ βˆͺ lβ‚‚ <+ l₁ ++ lβ‚‚ := let ⟨_, s, e⟩ := sublist_suffix_of_union l₁ lβ‚‚ e β–Έ (append_sublist_append_right _).2 s theorem forall_mem_union : (βˆ€ x ∈ l₁ βˆͺ lβ‚‚, p x) ↔ (βˆ€ x ∈ l₁, p x) ∧ βˆ€ x ∈ lβ‚‚, p x := by simp only [mem_union_iff, or_imp, forall_and] theorem forall_mem_of_forall_mem_union_left (h : βˆ€ x ∈ l₁ βˆͺ lβ‚‚, p x) : βˆ€ x ∈ l₁, p x := (forall_mem_union.1 h).1 theorem forall_mem_of_forall_mem_union_right (h : βˆ€ x ∈ l₁ βˆͺ lβ‚‚, p x) : βˆ€ x ∈ lβ‚‚, p x := (forall_mem_union.1 h).2 theorem Subset.union_eq_right {xs ys : List Ξ±} (h : xs βŠ† ys) : xs βˆͺ ys = ys := by induction xs with | nil => simp | cons x xs ih => rw [cons_union, insert_of_mem <| mem_union_right _ <| h mem_cons_self, ih <| subset_of_cons_subset h] end Union /-! ### `inter` -/ section Inter @[simp, grind =] theorem inter_nil (l : List Ξ±) : [] ∩ l = [] := rfl @[simp] theorem inter_cons_of_mem (l₁ : List Ξ±) (h : a ∈ lβ‚‚) : (a :: l₁) ∩ lβ‚‚ = a :: l₁ ∩ lβ‚‚ := by simp [Inter.inter, List.inter, h] @[simp] theorem inter_cons_of_notMem (l₁ : List Ξ±) (h : a βˆ‰ lβ‚‚) : (a :: l₁) ∩ lβ‚‚ = l₁ ∩ lβ‚‚ := by simp [Inter.inter, List.inter, h] @[grind =] theorem inter_cons (l₁ : List Ξ±) : (a :: l₁) ∩ lβ‚‚ = if a ∈ lβ‚‚ then a :: l₁ ∩ lβ‚‚ else l₁ ∩ lβ‚‚ := by split_ifs <;> simp_all @[deprecated (since := "2025-05-23")] alias inter_cons_of_not_mem := inter_cons_of_notMem @[simp, grind =] theorem inter_nil' (l : List Ξ±) : l ∩ [] = [] := by induction l with grind theorem mem_of_mem_inter_left : a ∈ l₁ ∩ lβ‚‚ β†’ a ∈ l₁ := mem_of_mem_filter theorem mem_of_mem_inter_right (h : a ∈ l₁ ∩ lβ‚‚) : a ∈ lβ‚‚ := by simpa using of_mem_filter h theorem mem_inter_of_mem_of_mem (h₁ : a ∈ l₁) (hβ‚‚ : a ∈ lβ‚‚) : a ∈ l₁ ∩ lβ‚‚ := mem_filter_of_mem h₁ <| by simpa using hβ‚‚ theorem inter_subset_left {l₁ lβ‚‚ : List Ξ±} : l₁ ∩ lβ‚‚ βŠ† l₁ := filter_subset' _ theorem inter_subset_right {l₁ lβ‚‚ : List Ξ±} : l₁ ∩ lβ‚‚ βŠ† lβ‚‚ := fun _ => mem_of_mem_inter_right theorem subset_inter {l l₁ lβ‚‚ : List Ξ±} (h₁ : l βŠ† l₁) (hβ‚‚ : l βŠ† lβ‚‚) : l βŠ† l₁ ∩ lβ‚‚ := fun _ h => mem_inter_iff.2 ⟨h₁ h, hβ‚‚ h⟩ theorem inter_eq_nil_iff_disjoint : l₁ ∩ lβ‚‚ = [] ↔ Disjoint l₁ lβ‚‚ := by simp only [eq_nil_iff_forall_not_mem, mem_inter_iff, not_and] rfl alias ⟨_, Disjoint.inter_eq_nil⟩ := inter_eq_nil_iff_disjoint theorem forall_mem_inter_of_forall_left (h : βˆ€ x ∈ l₁, p x) (lβ‚‚ : List Ξ±) : βˆ€ x, x ∈ l₁ ∩ lβ‚‚ β†’ p x := BAll.imp_left (fun _ => mem_of_mem_inter_left) h theorem forall_mem_inter_of_forall_right (l₁ : List Ξ±) (h : βˆ€ x ∈ lβ‚‚, p x) : βˆ€ x, x ∈ l₁ ∩ lβ‚‚ β†’ p x := BAll.imp_left (fun _ => mem_of_mem_inter_right) h @[simp] theorem inter_reverse {xs ys : List Ξ±} : xs.inter ys.reverse = xs.inter ys := by simp only [List.inter, elem_eq_mem, mem_reverse] theorem Subset.inter_eq_left {xs ys : List Ξ±} (h : xs βŠ† ys) : xs ∩ ys = xs := List.filter_eq_self.mpr fun _ ha => elem_eq_true_of_mem (h ha) end Inter /-! ### `bagInter` -/ section BagInter @[simp, grind =] theorem nil_bagInter (l : List Ξ±) : [].bagInter l = [] := by cases l <;> rfl @[simp, grind =] theorem bagInter_nil (l : List Ξ±) : l.bagInter [] = [] := by cases l <;> rfl @[simp] theorem cons_bagInter_of_pos (l₁ : List Ξ±) (h : a ∈ lβ‚‚) : (a :: l₁).bagInter lβ‚‚ = a :: l₁.bagInter (lβ‚‚.erase a) := by cases lβ‚‚ with grind [List.bagInter] @[simp] theorem cons_bagInter_of_neg (l₁ : List Ξ±) (h : a βˆ‰ lβ‚‚) : (a :: l₁).bagInter lβ‚‚ = l₁.bagInter lβ‚‚ := by cases lβ‚‚ with grind [List.bagInter] @[grind =] theorem cons_bagInteger : (a :: l₁).bagInter lβ‚‚ = if a ∈ lβ‚‚ then a :: l₁.bagInter (lβ‚‚.erase a) else l₁.bagInter lβ‚‚ := by split_ifs <;> simp_all @[simp] theorem mem_bagInter {a : Ξ±} {l₁ lβ‚‚ : List Ξ±} : a ∈ l₁.bagInter lβ‚‚ ↔ a ∈ l₁ ∧ a ∈ lβ‚‚ := by fun_induction List.bagInter with grind @[simp] theorem count_bagInter {a : Ξ±} {l₁ lβ‚‚ : List Ξ±} : count a (l₁.bagInter lβ‚‚) = min (count a l₁) (count a lβ‚‚) := by fun_induction List.bagInter with grind [count_pos_iff] theorem bagInter_sublist_left {l₁ lβ‚‚ : List Ξ±} : l₁.bagInter lβ‚‚ <+ l₁ := by fun_induction List.bagInter with grind theorem bagInter_nil_iff_inter_nil : βˆ€ l₁ lβ‚‚ : List Ξ±, l₁.bagInter lβ‚‚ = [] ↔ l₁ ∩ lβ‚‚ = [] | [], lβ‚‚ => by simp | b :: l₁, lβ‚‚ => by by_cases h : b ∈ lβ‚‚ Β· simp [h] Β· simpa [h] using bagInter_nil_iff_inter_nil l₁ lβ‚‚ end BagInter end List
.lake/packages/mathlib/Mathlib/Data/List/ProdSigma.lean
import Mathlib.Data.List.Basic /-! # Lists in product and sigma types This file proves basic properties of `List.product` and `List.sigma`, which are list constructions living in `Prod` and `Sigma` types respectively. Their definitions can be found in [`Data.List.Defs`](./defs). Beware, this is not about `List.prod`, the multiplicative product. -/ variable {Ξ± Ξ² : Type*} namespace List /-! ### product -/ @[simp] theorem nil_product (l : List Ξ²) : (@nil Ξ±) Γ—Λ’ l = [] := rfl @[simp] theorem product_cons (a : Ξ±) (l₁ : List Ξ±) (lβ‚‚ : List Ξ²) : (a :: l₁) Γ—Λ’ lβ‚‚ = map (fun b => (a, b)) lβ‚‚ ++ (l₁ Γ—Λ’ lβ‚‚) := rfl @[simp] theorem product_nil : βˆ€ l : List Ξ±, l Γ—Λ’ (@nil Ξ²) = [] | [] => rfl | _ :: l => by simp [product_cons, product_nil l] @[simp] theorem mem_product {l₁ : List Ξ±} {lβ‚‚ : List Ξ²} {a : Ξ±} {b : Ξ²} : (a, b) ∈ l₁ Γ—Λ’ lβ‚‚ ↔ a ∈ l₁ ∧ b ∈ lβ‚‚ := by simp_all [SProd.sprod, product, mem_flatMap, mem_map, Prod.ext_iff, and_left_comm] theorem length_product (l₁ : List Ξ±) (lβ‚‚ : List Ξ²) : length (l₁ Γ—Λ’ lβ‚‚) = length l₁ * length lβ‚‚ := by induction l₁ with | nil => exact (Nat.zero_mul _).symm | cons x l₁ IH => simp only [length, product_cons, length_append, IH, Nat.add_mul, Nat.one_mul, length_map, Nat.add_comm] /-! ### sigma -/ variable {Οƒ : Ξ± β†’ Type*} @[simp] theorem nil_sigma (l : βˆ€ a, List (Οƒ a)) : (@nil Ξ±).sigma l = [] := rfl @[simp] theorem sigma_cons (a : Ξ±) (l₁ : List Ξ±) (lβ‚‚ : βˆ€ a, List (Οƒ a)) : (a :: l₁).sigma lβ‚‚ = map (Sigma.mk a) (lβ‚‚ a) ++ l₁.sigma lβ‚‚ := rfl @[simp] theorem sigma_nil : βˆ€ l : List Ξ±, (l.sigma fun a => @nil (Οƒ a)) = [] | [] => rfl | _ :: l => by simp [sigma_cons, sigma_nil l] @[simp] theorem mem_sigma {l₁ : List Ξ±} {lβ‚‚ : βˆ€ a, List (Οƒ a)} {a : Ξ±} {b : Οƒ a} : Sigma.mk a b ∈ l₁.sigma lβ‚‚ ↔ a ∈ l₁ ∧ b ∈ lβ‚‚ a := by simp [List.sigma, mem_flatMap, mem_map, exists_and_left, and_left_comm, exists_eq_left, exists_eq_right] /-! ### Miscellaneous lemmas -/ @[simp 1100] theorem mem_map_swap (x : Ξ±) (y : Ξ²) (xs : List (Ξ± Γ— Ξ²)) : (y, x) ∈ map Prod.swap xs ↔ (x, y) ∈ xs := by simp end List
.lake/packages/mathlib/Mathlib/Data/List/NatAntidiagonal.lean
import Mathlib.Data.List.Nodup /-! # Antidiagonals in β„• Γ— β„• as lists This file defines the antidiagonals of β„• Γ— β„• as lists: the `n`-th antidiagonal is the list of pairs `(i, j)` such that `i + j = n`. This is useful for polynomial multiplication and more generally for sums going from `0` to `n`. ## Notes Files `Data.Multiset.NatAntidiagonal` and `Data.Finset.NatAntidiagonal` successively turn the `List` definition we have here into `Multiset` and `Finset`. -/ open Function namespace List namespace Nat /-- The antidiagonal of a natural number `n` is the list of pairs `(i, j)` such that `i + j = n`. -/ def antidiagonal (n : β„•) : List (β„• Γ— β„•) := (range (n + 1)).map fun i ↦ (i, n - i) /-- A pair (i, j) is contained in the antidiagonal of `n` if and only if `i + j = n`. -/ @[simp] theorem mem_antidiagonal {n : β„•} {x : β„• Γ— β„•} : x ∈ antidiagonal n ↔ x.1 + x.2 = n := by rw [antidiagonal, mem_map]; constructor Β· rintro ⟨i, hi, rfl⟩ rw [mem_range, Nat.lt_succ_iff] at hi exact Nat.add_sub_cancel' hi Β· rintro rfl refine ⟨x.fst, ?_, ?_⟩ Β· rw [mem_range] cutsat Β· exact Prod.ext rfl (by simp only [Nat.add_sub_cancel_left]) /-- The length of the antidiagonal of `n` is `n + 1`. -/ @[simp] theorem length_antidiagonal (n : β„•) : (antidiagonal n).length = n + 1 := by rw [antidiagonal, length_map, length_range] /-- The antidiagonal of `0` is the list `[(0, 0)]` -/ @[simp] theorem antidiagonal_zero : antidiagonal 0 = [(0, 0)] := rfl /-- The antidiagonal of `n` does not contain duplicate entries. -/ theorem nodup_antidiagonal (n : β„•) : Nodup (antidiagonal n) := nodup_range.map ((@LeftInverse.injective β„• (β„• Γ— β„•) Prod.fst fun i ↦ (i, n - i)) fun _ ↦ rfl) @[simp] theorem antidiagonal_succ {n : β„•} : antidiagonal (n + 1) = (0, n + 1) :: (antidiagonal n).map (Prod.map Nat.succ id) := by simp only [antidiagonal, range_succ_eq_map, map_cons, Nat.add_succ_sub_one, Nat.add_zero, id, Nat.sub_zero, map_map, Prod.map_apply] apply congr rfl (congr rfl _) ext; simp theorem antidiagonal_succ' {n : β„•} : antidiagonal (n + 1) = (antidiagonal n).map (Prod.map id Nat.succ) ++ [(n + 1, 0)] := by simp only [antidiagonal, range_succ, Nat.add_sub_cancel_left, map_append, append_assoc, Nat.sub_self, singleton_append, map_map, map] congr 1 apply map_congr_left simp +contextual [le_of_lt, Nat.sub_add_comm] theorem antidiagonal_succ_succ' {n : β„•} : antidiagonal (n + 2) = (0, n + 2) :: (antidiagonal n).map (Prod.map Nat.succ Nat.succ) ++ [(n + 2, 0)] := by rw [antidiagonal_succ'] simp only [antidiagonal_succ, map_cons, Prod.map_apply, id_eq, map_map, cons_append, cons.injEq, append_cancel_right_eq, true_and] ext simp theorem map_swap_antidiagonal {n : β„•} : (antidiagonal n).map Prod.swap = (antidiagonal n).reverse := by rw [antidiagonal, map_map, ← List.map_reverse, range_eq_range', reverse_range', ← range_eq_range', map_map] apply map_congr_left simp +contextual [Nat.sub_sub_self, Nat.lt_succ_iff] end Nat end List
.lake/packages/mathlib/Mathlib/Data/List/Sublists.lean
import Mathlib.Data.Nat.Choose.Basic import Mathlib.Data.List.FinRange import Mathlib.Data.List.Perm.Basic import Mathlib.Data.List.Lex import Mathlib.Data.List.Induction /-! # sublists `List.Sublists` gives a list of all (not necessarily contiguous) sublists of a list. This file contains basic results on this function. -/ universe u v w variable {Ξ± : Type u} {Ξ² : Type v} {Ξ³ : Type w} open Nat namespace List /-! ### sublists -/ @[simp] theorem sublists'_nil : sublists' (@nil Ξ±) = [[]] := rfl @[simp] theorem sublists'_singleton (a : Ξ±) : sublists' [a] = [[], [a]] := rfl /-- Auxiliary helper definition for `sublists'` -/ def sublists'Aux (a : Ξ±) (r₁ rβ‚‚ : List (List Ξ±)) : List (List Ξ±) := r₁.foldl (init := rβ‚‚) fun r l => r ++ [a :: l] theorem sublists'Aux_eq_array_foldl (a : Ξ±) : βˆ€ (r₁ rβ‚‚ : List (List Ξ±)), sublists'Aux a r₁ rβ‚‚ = ((r₁.toArray).foldl (init := rβ‚‚.toArray) (fun r l => r.push (a :: l))).toList := by intro r₁ rβ‚‚ rw [sublists'Aux, Array.foldl_toList] have := List.foldl_hom Array.toList (g₁ := fun r l => r.push (a :: l)) (gβ‚‚ := fun r l => r ++ [a :: l]) (l := r₁) (init := rβ‚‚.toArray) (by simp) simpa using this theorem sublists'_eq_sublists'Aux (l : List Ξ±) : sublists' l = l.foldr (fun a r => sublists'Aux a r r) [[]] := by simp only [sublists', sublists'Aux_eq_array_foldl] rw [← List.foldr_hom Array.toList] Β· intros; congr theorem sublists'Aux_eq_map (a : Ξ±) (r₁ : List (List Ξ±)) : βˆ€ (rβ‚‚ : List (List Ξ±)), sublists'Aux a r₁ rβ‚‚ = rβ‚‚ ++ map (cons a) r₁ := List.reverseRecOn r₁ (fun _ => by simp [sublists'Aux]) fun r₁ l ih rβ‚‚ => by rw [map_append, map_singleton, ← append_assoc, ← ih, sublists'Aux, foldl_append, foldl] simp [sublists'Aux] @[simp 900] theorem sublists'_cons (a : Ξ±) (l : List Ξ±) : sublists' (a :: l) = sublists' l ++ map (cons a) (sublists' l) := by simp [sublists'_eq_sublists'Aux, foldr_cons, sublists'Aux_eq_map] @[simp] theorem mem_sublists' {s t : List Ξ±} : s ∈ sublists' t ↔ s <+ t := by induction t generalizing s with | nil => simp only [sublists'_nil, mem_singleton] exact ⟨fun h => by rw [h], eq_nil_of_sublist_nil⟩ | cons a t IH => ?_ simp only [sublists'_cons, mem_append, IH, mem_map] constructor <;> intro h Β· rcases h with (h | ⟨s, h, rfl⟩) Β· exact sublist_cons_of_sublist _ h Β· exact h.cons_cons _ Β· obtain - | ⟨-, h⟩ | ⟨-, h⟩ := h Β· exact Or.inl h Β· exact Or.inr ⟨_, h, rfl⟩ @[simp] theorem length_sublists' : βˆ€ l : List Ξ±, length (sublists' l) = 2 ^ length l | [] => rfl | a :: l => by simp +arith only [sublists'_cons, length_append, length_sublists' l, length_map, length, Nat.pow_succ'] @[simp] theorem sublists_nil : sublists (@nil Ξ±) = [[]] := rfl @[simp] theorem sublists_singleton (a : Ξ±) : sublists [a] = [[], [a]] := rfl /-- Auxiliary helper function for `sublists` -/ def sublistsAux (a : Ξ±) (r : List (List Ξ±)) : List (List Ξ±) := r.foldl (init := []) fun r l => r ++ [l, a :: l] theorem sublistsAux_eq_array_foldl : sublistsAux = fun (a : Ξ±) (r : List (List Ξ±)) => (r.toArray.foldl (init := #[]) fun r l => (r.push l).push (a :: l)).toList := by funext a r simp only [sublistsAux] have := foldl_hom Array.toList (g₁ := fun r l => (r.push l).push (a :: l)) (gβ‚‚ := fun r l => r ++ [l, a :: l]) (l := r) (init := #[]) (by simp) simpa using this theorem sublistsAux_eq_flatMap : sublistsAux = fun (a : Ξ±) (r : List (List Ξ±)) => r.flatMap fun l => [l, a :: l] := funext fun a => funext fun r => List.reverseRecOn r (by simp [sublistsAux]) (fun r l ih => by rw [flatMap_append, ← ih, flatMap_singleton, sublistsAux, foldl_append] simp [sublistsAux]) theorem sublists_append (l₁ lβ‚‚ : List Ξ±) : sublists (l₁ ++ lβ‚‚) = (sublists lβ‚‚) >>= (fun x => (sublists l₁).map (Β· ++ x)) := by simp only [sublists, foldr_append] induction l₁ with | nil => simp | cons a l₁ ih => rw [foldr_cons, ih] simp [List.flatMap, flatten_flatten, Function.comp_def] theorem sublists_cons (a : Ξ±) (l : List Ξ±) : sublists (a :: l) = sublists l >>= (fun x => [x, a :: x]) := show sublists ([a] ++ l) = _ by rw [sublists_append] simp only [sublists_singleton, map_cons, bind_eq_flatMap, nil_append, cons_append, map_nil] @[simp] theorem sublists_concat (l : List Ξ±) (a : Ξ±) : sublists (l ++ [a]) = sublists l ++ map (fun x => x ++ [a]) (sublists l) := by rw [sublists_append, sublists_singleton, bind_eq_flatMap, flatMap_cons, flatMap_cons, flatMap_nil, map_id'' append_nil, append_nil] theorem sublists_reverse (l : List Ξ±) : sublists (reverse l) = map reverse (sublists' l) := by induction l with | nil => rfl | cons hd tl ih => simp only [reverse_cons, sublists_append, sublists'_cons, map_append, ih, sublists_singleton, bind_eq_flatMap, map_map, flatMap_cons, append_nil, flatMap_nil, Function.comp_def] theorem sublists_eq_sublists' (l : List Ξ±) : sublists l = map reverse (sublists' (reverse l)) := by rw [← sublists_reverse, reverse_reverse] theorem sublists'_reverse (l : List Ξ±) : sublists' (reverse l) = map reverse (sublists l) := by simp only [sublists_eq_sublists', map_map, map_id'' reverse_reverse, Function.comp_def] theorem sublists'_eq_sublists (l : List Ξ±) : sublists' l = map reverse (sublists (reverse l)) := by rw [← sublists'_reverse, reverse_reverse] @[simp] theorem mem_sublists {s t : List Ξ±} : s ∈ sublists t ↔ s <+ t := by rw [← reverse_sublist, ← mem_sublists', sublists'_reverse, mem_map_of_injective reverse_injective] @[simp] theorem length_sublists (l : List Ξ±) : length (sublists l) = 2 ^ length l := by simp only [sublists_eq_sublists', length_map, length_sublists', length_reverse] theorem map_pure_sublist_sublists (l : List Ξ±) : map pure l <+ sublists l := by induction l using reverseRecOn <;> simp only [map, map_append, sublists_concat] Β· simp only [sublists_nil, sublist_cons_self] case append_singleton l a ih => exact ((append_sublist_append_left _).2 <| singleton_sublist.2 <| mem_map.2 ⟨[], mem_sublists.2 (nil_sublist _), by rfl⟩).trans ((append_sublist_append_right _).2 ih) /-! ### sublistsLen -/ /-- Auxiliary function to construct the list of all sublists of a given length. Given an integer `n`, a list `l`, a function `f` and an auxiliary list `L`, it returns the list made of `f` applied to all sublists of `l` of length `n`, concatenated with `L`. -/ def sublistsLenAux : β„• β†’ List Ξ± β†’ (List Ξ± β†’ Ξ²) β†’ List Ξ² β†’ List Ξ² | 0, _, f, r => f [] :: r | _ + 1, [], _, r => r | n + 1, a :: l, f, r => sublistsLenAux (n + 1) l f (sublistsLenAux n l (f ∘ List.cons a) r) /-- The list of all sublists of a list `l` that are of length `n`. For instance, for `l = [0, 1, 2, 3]` and `n = 2`, one gets `[[2, 3], [1, 3], [1, 2], [0, 3], [0, 2], [0, 1]]`. -/ def sublistsLen (n : β„•) (l : List Ξ±) : List (List Ξ±) := sublistsLenAux n l id [] theorem sublistsLenAux_append : βˆ€ (n : β„•) (l : List Ξ±) (f : List Ξ± β†’ Ξ²) (g : Ξ² β†’ Ξ³) (r : List Ξ²) (s : List Ξ³), sublistsLenAux n l (g ∘ f) (r.map g ++ s) = (sublistsLenAux n l f r).map g ++ s | 0, l, f, g, r, s => by unfold sublistsLenAux; simp | _ + 1, [], _, _, _, _ => rfl | n + 1, a :: l, f, g, r, s => by unfold sublistsLenAux simp only [show (g ∘ f) ∘ List.cons a = g ∘ f ∘ List.cons a by rfl, sublistsLenAux_append] theorem sublistsLenAux_eq (l : List Ξ±) (n) (f : List Ξ± β†’ Ξ²) (r) : sublistsLenAux n l f r = (sublistsLen n l).map f ++ r := by rw [sublistsLen, ← sublistsLenAux_append]; rfl theorem sublistsLenAux_zero (l : List Ξ±) (f : List Ξ± β†’ Ξ²) (r) : sublistsLenAux 0 l f r = f [] :: r := by cases l <;> rfl @[simp] theorem sublistsLen_zero (l : List Ξ±) : sublistsLen 0 l = [[]] := sublistsLenAux_zero _ _ _ @[simp] theorem sublistsLen_succ_nil (n) : sublistsLen (n + 1) (@nil Ξ±) = [] := rfl @[simp] theorem sublistsLen_succ_cons (n) (a : Ξ±) (l) : sublistsLen (n + 1) (a :: l) = sublistsLen (n + 1) l ++ (sublistsLen n l).map (cons a) := by rw [sublistsLen, sublistsLenAux, sublistsLenAux_eq, sublistsLenAux_eq, map_id, append_nil]; rfl theorem sublistsLen_one (l : List Ξ±) : sublistsLen 1 l = l.reverse.map ([Β·]) := l.rec (by rw [sublistsLen_succ_nil, reverse_nil, map_nil]) fun a s ih ↦ by rw [sublistsLen_succ_cons, ih, reverse_cons, map_append, sublistsLen_zero]; rfl @[simp] theorem length_sublistsLen : βˆ€ (n) (l : List Ξ±), length (sublistsLen n l) = Nat.choose (length l) n | 0, l => by simp | _ + 1, [] => by simp | n + 1, a :: l => by rw [sublistsLen_succ_cons, length_append, length_sublistsLen (n + 1) l, length_map, length_sublistsLen n l, length_cons, Nat.choose_succ_succ, Nat.add_comm] theorem sublistsLen_sublist_sublists' : βˆ€ (n) (l : List Ξ±), sublistsLen n l <+ sublists' l | 0, l => by simp | _ + 1, [] => nil_sublist _ | n + 1, a :: l => by rw [sublistsLen_succ_cons, sublists'_cons] exact (sublistsLen_sublist_sublists' _ _).append ((sublistsLen_sublist_sublists' _ _).map _) theorem sublistsLen_sublist_of_sublist (n) {l₁ lβ‚‚ : List Ξ±} (h : l₁ <+ lβ‚‚) : sublistsLen n l₁ <+ sublistsLen n lβ‚‚ := by induction n generalizing l₁ lβ‚‚ with | zero => simp | succ n IHn => ?_ induction h with | slnil => rfl | cons a _ IH => refine IH.trans ?_ rw [sublistsLen_succ_cons] apply sublist_append_left | consβ‚‚ a s IH => simpa only [sublistsLen_succ_cons] using IH.append ((IHn s).map _) theorem length_of_sublistsLen : βˆ€ {n} {l l' : List Ξ±}, l' ∈ sublistsLen n l β†’ length l' = n | 0, l, l', h => by simp_all | n + 1, a :: l, l', h => by rw [sublistsLen_succ_cons, mem_append, mem_map] at h rcases h with (h | ⟨l', h, rfl⟩) Β· exact length_of_sublistsLen h Β· exact congr_arg (Β· + 1) (length_of_sublistsLen h) theorem mem_sublistsLen_self {l l' : List Ξ±} (h : l' <+ l) : l' ∈ sublistsLen (length l') l := by induction h with | slnil => simp | @cons l₁ lβ‚‚ a s IH => rcases l₁ with - | ⟨b, lβ‚βŸ© Β· simp Β· rw [length, sublistsLen_succ_cons] exact mem_append_left _ IH | consβ‚‚ a s IH => rw [length, sublistsLen_succ_cons] exact mem_append_right _ (mem_map.2 ⟨_, IH, rfl⟩) @[simp] theorem mem_sublistsLen {n} {l l' : List Ξ±} : l' ∈ sublistsLen n l ↔ l' <+ l ∧ length l' = n := ⟨fun h => ⟨mem_sublists'.1 ((sublistsLen_sublist_sublists' _ _).subset h), length_of_sublistsLen h⟩, fun ⟨h₁, hβ‚‚βŸ© => hβ‚‚ β–Έ mem_sublistsLen_self hβ‚βŸ© theorem sublistsLen_of_length_lt {n} {l : List Ξ±} (h : l.length < n) : sublistsLen n l = [] := eq_nil_iff_forall_not_mem.mpr fun _ => mem_sublistsLen.not.mpr fun ⟨hs, hl⟩ => (h.trans_eq hl.symm).not_ge (Sublist.length_le hs) @[simp] theorem sublistsLen_length : βˆ€ l : List Ξ±, sublistsLen l.length l = [l] | [] => rfl | a :: l => by simp only [length, sublistsLen_succ_cons, sublistsLen_length, map, sublistsLen_of_length_lt (lt_succ_self _), nil_append] open Function theorem Pairwise.sublists' {R} : βˆ€ {l : List Ξ±}, Pairwise R l β†’ Pairwise (Lex (swap R)) (sublists' l) | _, Pairwise.nil => pairwise_singleton _ _ | _, @Pairwise.cons _ _ a l H₁ Hβ‚‚ => by simp only [sublists'_cons, pairwise_append, pairwise_map, mem_sublists', mem_map, exists_imp, and_imp] refine ⟨Hβ‚‚.sublists', Hβ‚‚.sublists'.imp fun l₁ => Lex.cons l₁, ?_⟩ rintro l₁ sl₁ x lβ‚‚ _ rfl rcases l₁ with - | ⟨b, lβ‚βŸ©; Β· constructor exact Lex.rel (H₁ _ <| sl₁.subset mem_cons_self) theorem pairwise_sublists {R} {l : List Ξ±} (H : Pairwise R l) : Pairwise (Lex R on reverse) (sublists l) := by have := (pairwise_reverse.2 H).sublists' rwa [sublists'_reverse, pairwise_map] at this @[simp] theorem nodup_sublists {l : List Ξ±} : Nodup (sublists l) ↔ Nodup l := ⟨fun h => (h.sublist (map_pure_sublist_sublists _)).of_map _, fun h => (pairwise_sublists h).imp @fun l₁ lβ‚‚ h => by simpa using h.to_ne⟩ @[simp] theorem nodup_sublists' {l : List Ξ±} : Nodup (sublists' l) ↔ Nodup l := by rw [sublists'_eq_sublists, nodup_map_iff reverse_injective, nodup_sublists, nodup_reverse] protected alias ⟨Nodup.of_sublists, Nodup.sublists⟩ := nodup_sublists protected alias ⟨Nodup.of_sublists', _⟩ := nodup_sublists' theorem nodup_sublistsLen (n : β„•) {l : List Ξ±} (h : Nodup l) : (sublistsLen n l).Nodup := by have : Pairwise (Β· β‰  Β·) l.sublists' := Pairwise.imp (fun h => Lex.to_ne (by convert h using 3; simp [eq_comm])) h.sublists' exact this.sublist (sublistsLen_sublist_sublists' _ _) theorem sublists_map (f : Ξ± β†’ Ξ²) : βˆ€ (l : List Ξ±), sublists (map f l) = map (map f) (sublists l) | [] => by simp | a::l => by rw [map_cons, sublists_cons, bind_eq_flatMap, sublists_map f l, sublists_cons, bind_eq_flatMap, map_eq_flatMap, map_eq_flatMap] induction sublists l <;> simp [*] theorem sublists'_map (f : Ξ± β†’ Ξ²) : βˆ€ (l : List Ξ±), sublists' (map f l) = map (map f) (sublists' l) | [] => by simp | a::l => by simp [map_cons, sublists'_cons, sublists'_map f l, Function.comp] theorem sublists_perm_sublists' (l : List Ξ±) : sublists l ~ sublists' l := by rw [← finRange_map_get l, sublists_map, sublists'_map] apply Perm.map apply (perm_ext_iff_of_nodup _ _).mpr Β· simp Β· exact nodup_sublists.mpr (nodup_finRange _) Β· exact (nodup_sublists'.mpr (nodup_finRange _)) theorem sublists_cons_perm_append (a : Ξ±) (l : List Ξ±) : sublists (a :: l) ~ sublists l ++ map (cons a) (sublists l) := Perm.trans (sublists_perm_sublists' _) <| by rw [sublists'_cons] exact Perm.append (sublists_perm_sublists' _).symm (Perm.map _ (sublists_perm_sublists' _).symm) theorem revzip_sublists (l l₁ lβ‚‚ : List Ξ±) (h : (l₁, lβ‚‚) ∈ revzip l.sublists) : l₁ ++ lβ‚‚ ~ l := by rw [revzip] at h induction l using List.reverseRecOn generalizing l₁ lβ‚‚ with | nil => have : l₁ = [] ∧ lβ‚‚ = [] := by simpa using h simp [this] | append_singleton l' a ih => rw [sublists_concat, reverse_append, zip_append (by simp), ← map_reverse, zip_map_right, zip_map_left] at * simp only [Prod.mk_inj, mem_map, mem_append, Prod.map_apply, Prod.exists] at h rcases h with (⟨l₁, lβ‚‚', h, rfl, rfl⟩ | ⟨l₁', lβ‚‚, h, rfl, rfl⟩) Β· rw [← append_assoc] exact (ih _ _ h).append_right _ Β· rw [append_assoc] apply (perm_append_comm.append_left _).trans rw [← append_assoc] exact (ih _ _ h).append_right _ theorem revzip_sublists' (l l₁ lβ‚‚ : List Ξ±) (h : (l₁, lβ‚‚) ∈ revzip l.sublists') : l₁ ++ lβ‚‚ ~ l := by rw [revzip] at h induction l generalizing l₁ lβ‚‚ with | nil => simp_all only [sublists'_nil, reverse_cons, reverse_nil, nil_append, zip_cons_cons, zip_nil_right, mem_singleton, Prod.mk.injEq, append_nil, Perm.refl] | cons a l IH => rw [sublists'_cons, reverse_append, zip_append, ← map_reverse, zip_map_right, zip_map_left] at * <;> [simp only [mem_append, mem_map, Prod.map_apply, id_eq, Prod.mk.injEq, Prod.exists, exists_eq_right_right] at h; simp] rcases h with (⟨l₁, lβ‚‚', h, rfl, rfl⟩ | ⟨l₁', h, rfl⟩) Β· exact perm_middle.trans ((IH _ _ h).cons _) Β· exact (IH _ _ h).cons _ theorem range_bind_sublistsLen_perm (l : List Ξ±) : ((List.range (l.length + 1)).flatMap fun n => sublistsLen n l) ~ sublists' l := by induction l with | nil => simp [range_succ] | cons h tl l_ih => simp_rw [range_succ_eq_map, length, flatMap_cons, flatMap_map, sublistsLen_succ_cons, sublists'_cons, List.sublistsLen_zero, List.singleton_append] refine ((flatMap_append_perm (range (tl.length + 1)) _ _).symm.cons _).trans ?_ simp_rw [← List.map_flatMap, ← cons_append] rw [← List.singleton_append, ← List.sublistsLen_zero tl] refine Perm.append ?_ (l_ih.map _) rw [List.range_succ, flatMap_append, flatMap_singleton, sublistsLen_of_length_lt (Nat.lt_succ_self _), append_nil, ← List.flatMap_map Nat.succ fun n => sublistsLen n tl, ← flatMap_cons (f := fun n => sublistsLen n tl), ← range_succ_eq_map] exact l_ih end List
.lake/packages/mathlib/Mathlib/Data/List/Cycle.lean
import Mathlib.Data.Fintype.List import Mathlib.Data.Fintype.OfMap /-! # Cycles of a list Lists have an equivalence relation of whether they are rotational permutations of one another. This relation is defined as `IsRotated`. Based on this, we define the quotient of lists by the rotation relation, called `Cycle`. We also define a representation of concrete cycles, available when viewing them in a goal state or via `#eval`, when over representable types. For example, the cycle `(2 1 4 3)` will be shown as `c[2, 1, 4, 3]`. Two equal cycles may be printed differently if their internal representation is different. -/ assert_not_exists MonoidWithZero namespace List variable {Ξ± : Type*} [DecidableEq Ξ±] /-- Return the `z` such that `x :: z :: _` appears in `xs`, or `default` if there is no such `z`. -/ def nextOr : βˆ€ (_ : List Ξ±) (_ _ : Ξ±), Ξ± | [], _, default => default | [_], _, default => default -- Handles the not-found and the wraparound case | y :: z :: xs, x, default => if x = y then z else nextOr (z :: xs) x default @[simp] theorem nextOr_nil (x d : Ξ±) : nextOr [] x d = d := rfl @[simp] theorem nextOr_singleton (x y d : Ξ±) : nextOr [y] x d = d := rfl @[simp] theorem nextOr_self_cons_cons (xs : List Ξ±) (x y d : Ξ±) : nextOr (x :: y :: xs) x d = y := if_pos rfl theorem nextOr_cons_of_ne (xs : List Ξ±) (y x d : Ξ±) (h : x β‰  y) : nextOr (y :: xs) x d = nextOr xs x d := by rcases xs with - | ⟨z, zs⟩ Β· rfl Β· exact if_neg h /-- `nextOr` does not depend on the default value, if the next value appears. -/ theorem nextOr_eq_nextOr_of_mem_of_ne (xs : List Ξ±) (x d d' : Ξ±) (x_mem : x ∈ xs) (x_ne : x β‰  xs.getLast (ne_nil_of_mem x_mem)) : nextOr xs x d = nextOr xs x d' := by induction xs with | nil => cases x_mem | cons y ys IH => ?_ rcases ys with - | ⟨z, zs⟩ Β· simp at x_mem x_ne contradiction by_cases h : x = y Β· rw [h, nextOr_self_cons_cons, nextOr_self_cons_cons] Β· rw [nextOr, nextOr, IH] Β· simpa [h] using x_mem Β· simpa using x_ne theorem mem_of_nextOr_ne {xs : List Ξ±} {x d : Ξ±} (h : nextOr xs x d β‰  d) : x ∈ xs := by induction xs with | nil => simp at h | cons y ys IH => ?_ rcases ys with - | ⟨z, zs⟩ Β· simp at h Β· by_cases hx : x = y Β· simp [hx] Β· rw [nextOr_cons_of_ne _ _ _ _ hx] at h simpa [hx] using IH h theorem nextOr_concat {xs : List Ξ±} {x : Ξ±} (d : Ξ±) (h : x βˆ‰ xs) : nextOr (xs ++ [x]) x d = d := by induction xs with | nil => simp | cons z zs IH => obtain ⟨hz, hzs⟩ := not_or.mp (mt mem_cons.2 h) rw [cons_append, nextOr_cons_of_ne _ _ _ _ hz, IH hzs] theorem nextOr_mem {xs : List Ξ±} {x d : Ξ±} (hd : d ∈ xs) : nextOr xs x d ∈ xs := by revert hd suffices βˆ€ xs' : List Ξ±, (βˆ€ x ∈ xs, x ∈ xs') β†’ d ∈ xs' β†’ nextOr xs x d ∈ xs' by exact this xs fun _ => id intro xs' hxs' hd induction xs with | nil => exact hd | cons y ys ih => ?_ rcases ys with - | ⟨z, zs⟩ Β· exact hd rw [nextOr] split_ifs with h Β· exact hxs' _ (mem_cons_of_mem _ mem_cons_self) Β· exact ih fun _ h => hxs' _ (mem_cons_of_mem _ h) /-- Given an element `x : Ξ±` of `l : List Ξ±` such that `x ∈ l`, get the next element of `l`. This works from head to tail, (including a check for last element) so it will match on first hit, ignoring later duplicates. For example: * `next [1, 2, 3] 2 _ = 3` * `next [1, 2, 3] 3 _ = 1` * `next [1, 2, 3, 2, 4] 2 _ = 3` * `next [1, 2, 3, 2] 2 _ = 3` * `next [1, 1, 2, 3, 2] 1 _ = 1` -/ def next (l : List Ξ±) (x : Ξ±) (h : x ∈ l) : Ξ± := nextOr l x (l.get ⟨0, length_pos_of_mem h⟩) /-- Given an element `x : Ξ±` of `l : List Ξ±` such that `x ∈ l`, get the previous element of `l`. This works from head to tail, (including a check for last element) so it will match on first hit, ignoring later duplicates. * `prev [1, 2, 3] 2 _ = 1` * `prev [1, 2, 3] 1 _ = 3` * `prev [1, 2, 3, 2, 4] 2 _ = 1` * `prev [1, 2, 3, 4, 2] 2 _ = 1` * `prev [1, 1, 2] 1 _ = 2` -/ def prev : βˆ€ l : List Ξ±, βˆ€ x ∈ l, Ξ± | [], _, h => by simp at h | [y], _, _ => y | y :: z :: xs, x, h => if hx : x = y then getLast (z :: xs) (cons_ne_nil _ _) else if x = z then y else prev (z :: xs) x (by simpa [hx] using h) variable (l : List Ξ±) (x : Ξ±) @[simp] theorem next_singleton (x y : Ξ±) (h : x ∈ [y]) : next [y] x h = y := rfl @[simp] theorem prev_singleton (x y : Ξ±) (h : x ∈ [y]) : prev [y] x h = y := rfl theorem next_cons_cons_eq' (y z : Ξ±) (h : x ∈ y :: z :: l) (hx : x = y) : next (y :: z :: l) x h = z := by rw [next, nextOr, if_pos hx] @[simp] theorem next_cons_cons_eq (z : Ξ±) (h : x ∈ x :: z :: l) : next (x :: z :: l) x h = z := next_cons_cons_eq' l x x z h rfl theorem next_ne_head_ne_getLast (h : x ∈ l) (y : Ξ±) (h : x ∈ y :: l) (hy : x β‰  y) (hx : x β‰  getLast (y :: l) (cons_ne_nil _ _)) : next (y :: l) x h = next l x (by simpa [hy] using h) := by rw [next, next, nextOr_cons_of_ne _ _ _ _ hy, nextOr_eq_nextOr_of_mem_of_ne] Β· assumption Β· rwa [getLast_cons] at hx theorem next_cons_concat (y : Ξ±) (hy : x β‰  y) (hx : x βˆ‰ l) (h : x ∈ y :: l ++ [x] := mem_append_right _ (mem_singleton_self x)) : next (y :: l ++ [x]) x h = y := by rw [next, nextOr_concat] Β· simp Β· simp [hy, hx] theorem next_getLast_cons (h : x ∈ l) (y : Ξ±) (h : x ∈ y :: l) (hy : x β‰  y) (hx : x = getLast (y :: l) (cons_ne_nil _ _)) (hl : Nodup l) : next (y :: l) x h = y := by rw [next, get, ← dropLast_append_getLast (cons_ne_nil y l), hx, nextOr_concat] subst hx intro H obtain ⟨_ | k, hk, hk'⟩ := getElem_of_mem H Β· grind suffices k + 1 = l.length by simp [this] at hk rcases l with - | ⟨hd, tl⟩ Β· simp at hk Β· rw [nodup_iff_injective_get] at hl rw [length, Nat.succ_inj] refine Fin.val_eq_of_eq <| @hl ⟨k, Nat.lt_of_succ_lt <| by simpa using hk⟩ ⟨tl.length, by simp⟩ ?_ rw [← Option.some_inj] at hk' rw [← getElem?_eq_getElem, dropLast_eq_take, getElem?_take_of_lt, getElem?_cons_succ, getElem?_eq_getElem, Option.some_inj] at hk' Β· rw [get_eq_getElem, hk'] simp only [getLast_eq_getElem, length_cons, Nat.succ_sub_succ_eq_sub, Nat.sub_zero, get_eq_getElem, getElem_cons_succ] Β· simp only [dropLast_consβ‚‚, length_cons, length_dropLast, Nat.add_one_sub_one, Nat.add_lt_add_iff_right] at hk ⊒ cutsat simpa using hk theorem prev_getLast_cons' (y : Ξ±) (hxy : x ∈ y :: l) (hx : x = y) : prev (y :: l) x hxy = getLast (y :: l) (cons_ne_nil _ _) := by cases l <;> simp [prev, hx] @[simp] theorem prev_getLast_cons (h : x ∈ x :: l) : prev (x :: l) x h = getLast (x :: l) (cons_ne_nil _ _) := prev_getLast_cons' l x x h rfl theorem prev_cons_cons_eq' (y z : Ξ±) (h : x ∈ y :: z :: l) (hx : x = y) : prev (y :: z :: l) x h = getLast (z :: l) (cons_ne_nil _ _) := by rw [prev, dif_pos hx] theorem prev_cons_cons_eq (z : Ξ±) (h : x ∈ x :: z :: l) : prev (x :: z :: l) x h = getLast (z :: l) (cons_ne_nil _ _) := prev_cons_cons_eq' l x x z h rfl theorem prev_cons_cons_of_ne' (y z : Ξ±) (h : x ∈ y :: z :: l) (hy : x β‰  y) (hz : x = z) : prev (y :: z :: l) x h = y := by cases l Β· simp [prev, hz] Β· rw [prev, dif_neg hy, if_pos hz] theorem prev_cons_cons_of_ne (y : Ξ±) (h : x ∈ y :: x :: l) (hy : x β‰  y) : prev (y :: x :: l) x h = y := prev_cons_cons_of_ne' _ _ _ _ _ hy rfl theorem prev_ne_cons_cons (y z : Ξ±) (h : x ∈ y :: z :: l) (hy : x β‰  y) (hz : x β‰  z) : prev (y :: z :: l) x h = prev (z :: l) x (by simpa [hy] using h) := by cases l Β· simp [hy, hz] at h Β· rw [prev, dif_neg hy, if_neg hz] theorem next_mem (h : x ∈ l) : l.next x h ∈ l := nextOr_mem (get_mem _ _) theorem prev_mem (h : x ∈ l) : l.prev x h ∈ l := by rcases l with - | ⟨hd, tl⟩ Β· simp at h induction tl generalizing hd with | nil => simp | cons hd' tl hl => by_cases hx : x = hd Β· simp only [hx, prev_cons_cons_eq] exact mem_cons_of_mem _ (getLast_mem _) Β· rw [prev, dif_neg hx] split_ifs with hm Β· exact mem_cons_self Β· exact mem_cons_of_mem _ (hl _ _) theorem next_getElem (l : List Ξ±) (h : Nodup l) (i : Nat) (hi : i < l.length) : next l l[i] (get_mem _ _) = (l[(i + 1) % l.length]'(Nat.mod_lt _ (i.zero_le.trans_lt hi))) := match l, h, i, hi with | [], _, i, hi => by simp at hi | [_], _, _, _ => by simp | x::y::l, _h, 0, h0 => by have h₁ : (x :: y :: l)[0] = x := by simp rw [next_cons_cons_eq' _ _ _ _ _ h₁] simp | x::y::l, hn, i+1, hi => by have hx' : (x :: y :: l)[i+1] β‰  x := by intro H suffices (i + 1 : β„•) = 0 by simpa rw [nodup_iff_injective_get] at hn refine Fin.val_eq_of_eq (@hn ⟨i + 1, hi⟩ ⟨0, by simp⟩ ?_) simpa using H have hi' : i ≀ l.length := Nat.le_of_lt_succ (Nat.succ_lt_succ_iff.1 hi) rcases hi'.eq_or_lt with (hi' | hi') Β· subst hi' rw [next_getLast_cons] Β· simp Β· rw [getElem_cons_succ]; exact get_mem _ _ Β· exact hx' Β· simp [getLast_eq_getElem] Β· exact hn.of_cons Β· rw [next_ne_head_ne_getLast _ _ _ _ _ hx'] Β· simp only [getElem_cons_succ] rw [next_getElem (y::l), ← getElem_cons_succ (a := x)] Β· congr dsimp rw [Nat.mod_eq_of_lt (Nat.succ_lt_succ_iff.2 hi'), Nat.mod_eq_of_lt (Nat.succ_lt_succ_iff.2 (Nat.succ_lt_succ_iff.2 hi'))] Β· simp [Nat.mod_eq_of_lt (Nat.succ_lt_succ_iff.2 hi'), hi'] Β· exact hn.of_cons Β· rw [getLast_eq_getElem] intro h have := nodup_iff_injective_get.1 hn h simp at this; simp [this] at hi' Β· rw [getElem_cons_succ]; exact get_mem _ _ theorem prev_getElem (l : List Ξ±) (h : Nodup l) (i : Nat) (hi : i < l.length) : prev l l[i] (get_mem _ _) = (l[(i + (l.length - 1)) % l.length]'(Nat.mod_lt _ (by cutsat))) := match l with | [] => by simp at hi | x::l => by induction l generalizing i x with | nil => simp | cons y l hl => rcases i with (_ | _ | i) Β· simp [getLast_eq_getElem] Β· simp only [mem_cons, nodup_cons] at h push_neg at h simp only [zero_add, getElem_cons_succ, getElem_cons_zero, List.prev_cons_cons_of_ne _ _ _ _ h.left.left.symm, length, add_comm, Nat.add_sub_cancel_left, Nat.mod_self] Β· rw [prev_ne_cons_cons] Β· convert hl i.succ y h.of_cons (Nat.le_of_succ_le_succ hi) using 1 have : βˆ€ k hk, (y :: l)[k] = (x :: y :: l)[k + 1]'(Nat.succ_lt_succ hk) := by simp rw [this] congr simp only [Nat.add_succ_sub_one, add_zero, length] simp only [length, Nat.succ_lt_succ_iff] at hi set k := l.length rw [Nat.succ_add, ← Nat.add_succ, Nat.add_mod_right, Nat.succ_add, ← Nat.add_succ _ k, Nat.add_mod_right, Nat.mod_eq_of_lt, Nat.mod_eq_of_lt] Β· exact Nat.lt_succ_of_lt hi Β· exact Nat.succ_lt_succ (Nat.lt_succ_of_lt hi) Β· intro H suffices i.succ.succ = 0 by simpa suffices Fin.mk _ hi = ⟨0, by omega⟩ by rwa [Fin.mk.inj_iff] at this rw [nodup_iff_injective_get] at h apply h; rw [← H]; simp Β· intro H suffices i.succ.succ = 1 by simpa suffices Fin.mk _ hi = ⟨1, by omega⟩ by rwa [Fin.mk.inj_iff] at this rw [nodup_iff_injective_get] at h apply h; rw [← H]; simp @[simp] theorem next_getLast_eq_head (l : List Ξ±) (h : l β‰  []) (hn : l.Nodup) : l.next (l.getLast h) (getLast_mem h) = l.head h := by have h1 : l.length - 1 + 1 = l.length := by grind [length_pos_iff] simp [getLast_eq_getElem h, head_eq_getElem h, next_getElem l hn (l.length - 1) (by grind), h1] theorem pmap_next_eq_rotate_one (h : Nodup l) : (l.pmap l.next fun _ h => h) = l.rotate 1 := by apply List.ext_getElem Β· simp Β· intros rw [getElem_pmap, getElem_rotate, next_getElem _ h] theorem pmap_prev_eq_rotate_length_sub_one (h : Nodup l) : (l.pmap l.prev fun _ h => h) = l.rotate (l.length - 1) := by apply List.ext_getElem Β· simp Β· intro n hn hn' rw [getElem_rotate, getElem_pmap, prev_getElem _ h] theorem prev_next (l : List Ξ±) (h : Nodup l) (x : Ξ±) (hx : x ∈ l) : prev l (next l x hx) (next_mem _ _ _) = x := by obtain ⟨n, hn, rfl⟩ := getElem_of_mem hx simp only [next_getElem, prev_getElem, h, Nat.mod_add_mod] rcases l with - | ⟨hd, tl⟩ Β· simp at hn Β· have : (n + 1 + length tl) % (length tl + 1) = n := by rw [length_cons] at hn rw [add_assoc, add_comm 1, Nat.add_mod_right, Nat.mod_eq_of_lt hn] simp only [length_cons, Nat.succ_sub_succ_eq_sub, Nat.sub_zero, this] theorem next_prev (l : List Ξ±) (h : Nodup l) (x : Ξ±) (hx : x ∈ l) : next l (prev l x hx) (prev_mem _ _ _) = x := by obtain ⟨n, hn, rfl⟩ := getElem_of_mem hx simp only [next_getElem, prev_getElem, h, Nat.mod_add_mod] rcases l with - | ⟨hd, tl⟩ Β· simp at hn Β· have : (n + length tl + 1) % (length tl + 1) = n := by rw [length_cons] at hn rw [add_assoc, Nat.add_mod_right, Nat.mod_eq_of_lt hn] simp [this] theorem prev_reverse_eq_next (l : List Ξ±) (h : Nodup l) (x : Ξ±) (hx : x ∈ l) : prev l.reverse x (mem_reverse.mpr hx) = next l x hx := by obtain ⟨k, hk, rfl⟩ := getElem_of_mem hx have lpos : 0 < l.length := k.zero_le.trans_lt hk have key : l.length - 1 - k < l.length := by omega rw [← getElem_pmap l.next (fun _ h => h) (by simpa using hk)] simp_rw [getElem_eq_getElem_reverse (l := l), pmap_next_eq_rotate_one _ h] rw [← getElem_pmap l.reverse.prev fun _ h => h] Β· simp_rw [pmap_prev_eq_rotate_length_sub_one _ (nodup_reverse.mpr h), rotate_reverse, length_reverse, Nat.mod_eq_of_lt (Nat.sub_lt lpos Nat.succ_pos'), Nat.sub_sub_self (Nat.succ_le_of_lt lpos)] rw [getElem_eq_getElem_reverse] Β· simp [Nat.sub_sub_self (Nat.le_sub_one_of_lt hk)] Β· simpa theorem next_reverse_eq_prev (l : List Ξ±) (h : Nodup l) (x : Ξ±) (hx : x ∈ l) : next l.reverse x (mem_reverse.mpr hx) = prev l x hx := by convert (prev_reverse_eq_next l.reverse (nodup_reverse.mpr h) x (mem_reverse.mpr hx)).symm exact (reverse_reverse l).symm theorem isRotated_next_eq {l l' : List Ξ±} (h : l ~r l') (hn : Nodup l) {x : Ξ±} (hx : x ∈ l) : l.next x hx = l'.next x (h.mem_iff.mp hx) := by obtain ⟨k, hk, rfl⟩ := getElem_of_mem hx obtain ⟨n, rfl⟩ := id h rw [next_getElem _ hn] simp_rw [getElem_eq_getElem_rotate _ n k] rw [next_getElem _ (h.nodup_iff.mp hn), getElem_eq_getElem_rotate _ n] simp [add_assoc] theorem isRotated_prev_eq {l l' : List Ξ±} (h : l ~r l') (hn : Nodup l) {x : Ξ±} (hx : x ∈ l) : l.prev x hx = l'.prev x (h.mem_iff.mp hx) := by rw [← next_reverse_eq_prev _ hn, ← next_reverse_eq_prev _ (h.nodup_iff.mp hn)] exact isRotated_next_eq h.reverse (nodup_reverse.mpr hn) _ end List open List /-- `Cycle Ξ±` is the quotient of `List Ξ±` by cyclic permutation. Duplicates are allowed. -/ def Cycle (Ξ± : Type*) : Type _ := Quotient (IsRotated.setoid Ξ±) namespace Cycle variable {Ξ± : Type*} /-- The coercion from `List Ξ±` to `Cycle Ξ±` -/ @[coe] def ofList : List Ξ± β†’ Cycle Ξ± := Quot.mk _ instance : Coe (List Ξ±) (Cycle Ξ±) := ⟨ofList⟩ @[simp] theorem coe_eq_coe {l₁ lβ‚‚ : List Ξ±} : (l₁ : Cycle Ξ±) = (lβ‚‚ : Cycle Ξ±) ↔ l₁ ~r lβ‚‚ := @Quotient.eq _ (IsRotated.setoid _) _ _ @[simp] theorem mk_eq_coe (l : List Ξ±) : Quot.mk _ l = (l : Cycle Ξ±) := rfl @[simp] theorem mk''_eq_coe (l : List Ξ±) : Quotient.mk'' l = (l : Cycle Ξ±) := rfl theorem coe_cons_eq_coe_append (l : List Ξ±) (a : Ξ±) : (↑(a :: l) : Cycle Ξ±) = (↑(l ++ [a]) : Cycle Ξ±) := Quot.sound ⟨1, by rw [rotate_cons_succ, rotate_zero]⟩ /-- The unique empty cycle. -/ def nil : Cycle Ξ± := ([] : List Ξ±) @[simp] theorem coe_nil : ↑([] : List Ξ±) = @nil Ξ± := rfl @[simp] theorem coe_eq_nil (l : List Ξ±) : (l : Cycle Ξ±) = nil ↔ l = [] := coe_eq_coe.trans isRotated_nil_iff /-- For consistency with `EmptyCollection (List Ξ±)`. -/ instance : EmptyCollection (Cycle Ξ±) := ⟨nil⟩ @[simp] theorem empty_eq : βˆ… = @nil Ξ± := rfl instance : Inhabited (Cycle Ξ±) := ⟨nil⟩ /-- An induction principle for `Cycle`. Use as `induction s`. -/ @[elab_as_elim, induction_eliminator] theorem induction_on {motive : Cycle Ξ± β†’ Prop} (s : Cycle Ξ±) (nil : motive nil) (cons : βˆ€ (a) (l : List Ξ±), motive ↑l β†’ motive ↑(a :: l)) : motive s := Quotient.inductionOn' s fun l => by refine List.recOn l ?_ ?_ <;> simp only [mk''_eq_coe, coe_nil] assumption' /-- For `x : Ξ±`, `s : Cycle Ξ±`, `x ∈ s` indicates that `x` occurs at least once in `s`. -/ def Mem (s : Cycle Ξ±) (a : Ξ±) : Prop := Quot.liftOn s (fun l => a ∈ l) fun _ _ e => propext <| e.mem_iff instance : Membership Ξ± (Cycle Ξ±) := ⟨Mem⟩ @[simp] theorem mem_coe_iff {a : Ξ±} {l : List Ξ±} : a ∈ (↑l : Cycle Ξ±) ↔ a ∈ l := Iff.rfl @[simp] theorem notMem_nil (a : Ξ±) : a βˆ‰ nil := List.not_mem_nil @[deprecated (since := "2025-05-23")] alias not_mem_nil := notMem_nil instance [DecidableEq Ξ±] : DecidableEq (Cycle Ξ±) := fun s₁ sβ‚‚ => Quotient.recOnSubsingletonβ‚‚' s₁ sβ‚‚ fun _ _ => decidable_of_iff' _ Quotient.eq'' instance [DecidableEq Ξ±] (x : Ξ±) (s : Cycle Ξ±) : Decidable (x ∈ s) := Quotient.recOnSubsingleton' s fun l => show Decidable (x ∈ l) from inferInstance /-- Reverse a `s : Cycle Ξ±` by reversing the underlying `List`. -/ nonrec def reverse (s : Cycle Ξ±) : Cycle Ξ± := Quot.map reverse (fun _ _ => IsRotated.reverse) s @[simp] theorem reverse_coe (l : List Ξ±) : (l : Cycle Ξ±).reverse = l.reverse := rfl @[simp] theorem mem_reverse_iff {a : Ξ±} {s : Cycle Ξ±} : a ∈ s.reverse ↔ a ∈ s := Quot.inductionOn s fun _ => mem_reverse @[simp] theorem reverse_reverse (s : Cycle Ξ±) : s.reverse.reverse = s := Quot.inductionOn s fun _ => by simp @[simp] theorem reverse_nil : nil.reverse = @nil Ξ± := rfl /-- The length of the `s : Cycle Ξ±`, which is the number of elements, counting duplicates. -/ def length (s : Cycle Ξ±) : β„• := Quot.liftOn s List.length fun _ _ e => e.perm.length_eq @[simp] theorem length_coe (l : List Ξ±) : length (l : Cycle Ξ±) = l.length := rfl @[simp] theorem length_nil : length (@nil Ξ±) = 0 := rfl @[simp] theorem length_reverse (s : Cycle Ξ±) : s.reverse.length = s.length := Quot.inductionOn s fun _ => List.length_reverse /-- A `s : Cycle Ξ±` that is at most one element. -/ def Subsingleton (s : Cycle Ξ±) : Prop := s.length ≀ 1 theorem subsingleton_nil : Subsingleton (@nil Ξ±) := Nat.zero_le _ theorem length_subsingleton_iff {s : Cycle Ξ±} : Subsingleton s ↔ length s ≀ 1 := Iff.rfl @[simp] theorem subsingleton_reverse_iff {s : Cycle Ξ±} : s.reverse.Subsingleton ↔ s.Subsingleton := by simp [length_subsingleton_iff] theorem Subsingleton.congr {s : Cycle Ξ±} (h : Subsingleton s) : βˆ€ ⦃x⦄ (_hx : x ∈ s) ⦃y⦄ (_hy : y ∈ s), x = y := by induction s using Quot.inductionOn with | _ l simp only [length_subsingleton_iff, length_coe, mk_eq_coe, le_iff_lt_or_eq, Nat.lt_add_one_iff, length_eq_zero_iff, length_eq_one_iff, Nat.not_lt_zero, false_or] at h rcases h with (rfl | ⟨z, rfl⟩) <;> simp /-- A `s : Cycle Ξ±` that is made up of at least two unique elements. -/ def Nontrivial (s : Cycle Ξ±) : Prop := βˆƒ x y : Ξ±, x β‰  y ∧ x ∈ s ∧ y ∈ s @[simp] theorem nontrivial_coe_nodup_iff {l : List Ξ±} (hl : l.Nodup) : Nontrivial (l : Cycle Ξ±) ↔ 2 ≀ l.length := by rw [Nontrivial] rcases l with (_ | ⟨hd, _ | ⟨hd', tl⟩⟩) Β· simp Β· simp Β· simp only [mem_cons, mem_coe_iff, List.length, Ne, Nat.succ_le_succ_iff, Nat.zero_le, iff_true] refine ⟨hd, hd', ?_, by simp⟩ simp only [not_or, mem_cons, nodup_cons] at hl exact hl.left.left @[simp] theorem nontrivial_reverse_iff {s : Cycle Ξ±} : s.reverse.Nontrivial ↔ s.Nontrivial := by simp [Nontrivial] theorem length_nontrivial {s : Cycle Ξ±} (h : Nontrivial s) : 2 ≀ length s := by obtain ⟨x, y, hxy, hx, hy⟩ := h induction s using Quot.inductionOn with | _ l rcases l with (_ | ⟨hd, _ | ⟨hd', tl⟩⟩) Β· simp at hx Β· simp only [mem_coe_iff, mk_eq_coe, mem_singleton] at hx hy simp [hx, hy] at hxy Β· simp [Nat.succ_le_succ_iff] /-- The `s : Cycle Ξ±` contains no duplicates. -/ nonrec def Nodup (s : Cycle Ξ±) : Prop := Quot.liftOn s Nodup fun _l₁ _lβ‚‚ e => propext <| e.nodup_iff @[simp] nonrec theorem nodup_nil : Nodup (@nil Ξ±) := nodup_nil @[simp] theorem nodup_coe_iff {l : List Ξ±} : Nodup (l : Cycle Ξ±) ↔ l.Nodup := Iff.rfl @[simp] theorem nodup_reverse_iff {s : Cycle Ξ±} : s.reverse.Nodup ↔ s.Nodup := Quot.inductionOn s fun _ => nodup_reverse theorem Subsingleton.nodup {s : Cycle Ξ±} (h : Subsingleton s) : Nodup s := by induction s using Quot.inductionOn with | _ l obtain - | ⟨hd, tl⟩ := l Β· simp Β· have : tl = [] := by simpa [Subsingleton, length_eq_zero_iff, Nat.succ_le_succ_iff] using h simp [this] theorem Nodup.nontrivial_iff {s : Cycle Ξ±} (h : Nodup s) : Nontrivial s ↔ Β¬Subsingleton s := by rw [length_subsingleton_iff] induction s using Quotient.inductionOn' simp only [mk''_eq_coe, nodup_coe_iff] at h simp [h, Nat.succ_le_iff] /-- The `s : Cycle Ξ±` as a `Multiset Ξ±`. -/ def toMultiset (s : Cycle Ξ±) : Multiset Ξ± := Quotient.liftOn' s (↑) fun _ _ h => Multiset.coe_eq_coe.mpr h.perm @[simp] theorem coe_toMultiset (l : List Ξ±) : (l : Cycle Ξ±).toMultiset = l := rfl @[simp] theorem nil_toMultiset : nil.toMultiset = (0 : Multiset Ξ±) := rfl @[simp] theorem card_toMultiset (s : Cycle Ξ±) : Multiset.card s.toMultiset = s.length := Quotient.inductionOn' s (by simp) @[simp] theorem toMultiset_eq_nil {s : Cycle Ξ±} : s.toMultiset = 0 ↔ s = Cycle.nil := Quotient.inductionOn' s (by simp) /-- The lift of `list.map`. -/ def map {Ξ² : Type*} (f : Ξ± β†’ Ξ²) : Cycle Ξ± β†’ Cycle Ξ² := Quotient.map' (List.map f) fun _ _ h => h.map _ @[simp] theorem map_nil {Ξ² : Type*} (f : Ξ± β†’ Ξ²) : map f nil = nil := rfl @[simp] theorem map_coe {Ξ² : Type*} (f : Ξ± β†’ Ξ²) (l : List Ξ±) : map f ↑l = List.map f l := rfl @[simp] theorem map_eq_nil {Ξ² : Type*} (f : Ξ± β†’ Ξ²) (s : Cycle Ξ±) : map f s = nil ↔ s = nil := Quotient.inductionOn' s (by simp) @[simp] theorem mem_map {Ξ² : Type*} {f : Ξ± β†’ Ξ²} {b : Ξ²} {s : Cycle Ξ±} : b ∈ s.map f ↔ βˆƒ a, a ∈ s ∧ f a = b := Quotient.inductionOn' s (by simp) /-- The `Multiset` of lists that can make the cycle. -/ def lists (s : Cycle Ξ±) : Multiset (List Ξ±) := Quotient.liftOn' s (fun l => (l.cyclicPermutations : Multiset (List Ξ±))) fun l₁ lβ‚‚ h => by simpa using h.cyclicPermutations.perm @[simp] theorem lists_coe (l : List Ξ±) : lists (l : Cycle Ξ±) = ↑l.cyclicPermutations := rfl @[simp] theorem mem_lists_iff_coe_eq {s : Cycle Ξ±} {l : List Ξ±} : l ∈ s.lists ↔ (l : Cycle Ξ±) = s := Quotient.inductionOn' s fun l => by rw [lists, Quotient.liftOn'_mk''] simp @[simp] theorem lists_nil : lists (@nil Ξ±) = {([] : List Ξ±)} := by rw [nil, lists_coe, cyclicPermutations_nil, Multiset.coe_singleton] section Decidable variable [DecidableEq Ξ±] /-- Auxiliary decidability algorithm for lists that contain at least two unique elements. -/ def decidableNontrivialCoe : βˆ€ l : List Ξ±, Decidable (Nontrivial (l : Cycle Ξ±)) | [] => isFalse (by simp [Nontrivial]) | [x] => isFalse (by simp [Nontrivial]) | x :: y :: l => if h : x = y then @decidable_of_iff' _ (Nontrivial (x :: l : Cycle Ξ±)) (by simp [h, Nontrivial]) (decidableNontrivialCoe (x :: l)) else isTrue ⟨x, y, h, by simp, by simp⟩ instance {s : Cycle Ξ±} : Decidable (Nontrivial s) := Quot.recOnSubsingleton s decidableNontrivialCoe instance {s : Cycle Ξ±} : Decidable (Nodup s) := Quot.recOnSubsingleton s List.nodupDecidable instance fintypeNodupCycle [Fintype Ξ±] : Fintype { s : Cycle Ξ± // s.Nodup } := Fintype.ofSurjective (fun l : { l : List Ξ± // l.Nodup } => ⟨l.val, by simpa using l.prop⟩) fun ⟨s, hs⟩ => by induction s using Quotient.inductionOn' with | _ hs exact ⟨⟨_, hs⟩, by simp⟩ instance fintypeNodupNontrivialCycle [Fintype Ξ±] : Fintype { s : Cycle Ξ± // s.Nodup ∧ s.Nontrivial } := Fintype.subtype (((Finset.univ : Finset { s : Cycle Ξ± // s.Nodup }).map (Function.Embedding.subtype _)).filter Cycle.Nontrivial) (by simp) /-- The `s : Cycle Ξ±` as a `Finset Ξ±`. -/ def toFinset (s : Cycle Ξ±) : Finset Ξ± := s.toMultiset.toFinset @[simp] theorem toFinset_toMultiset (s : Cycle Ξ±) : s.toMultiset.toFinset = s.toFinset := rfl @[simp] theorem coe_toFinset (l : List Ξ±) : (l : Cycle Ξ±).toFinset = l.toFinset := rfl @[simp] theorem nil_toFinset : (@nil Ξ±).toFinset = βˆ… := rfl @[simp] theorem toFinset_eq_nil {s : Cycle Ξ±} : s.toFinset = βˆ… ↔ s = Cycle.nil := Quotient.inductionOn' s (by simp) /-- Given a `s : Cycle Ξ±` such that `Nodup s`, retrieve the next element after `x ∈ s`. -/ nonrec def next : βˆ€ (s : Cycle Ξ±) (_hs : Nodup s) (x : Ξ±) (_hx : x ∈ s), Ξ± := fun s => Quot.hrecOn (motive := fun (s : Cycle Ξ±) => βˆ€ (_hs : Cycle.Nodup s) (x : Ξ±) (_hx : x ∈ s), Ξ±) s (fun l _hn x hx => next l x hx) fun l₁ lβ‚‚ h => Function.hfunext (propext h.nodup_iff) fun h₁ hβ‚‚ _he => Function.hfunext rfl fun x y hxy => Function.hfunext (propext (by rw [eq_of_heq hxy]; simpa [eq_of_heq hxy] using h.mem_iff)) fun hm hm' he' => heq_of_eq (by rw [heq_iff_eq] at hxy; subst x; simpa using isRotated_next_eq h h₁ _) /-- Given a `s : Cycle Ξ±` such that `Nodup s`, retrieve the previous element before `x ∈ s`. -/ nonrec def prev : βˆ€ (s : Cycle Ξ±) (_hs : Nodup s) (x : Ξ±) (_hx : x ∈ s), Ξ± := fun s => Quot.hrecOn (motive := fun (s : Cycle Ξ±) => βˆ€ (_hs : Cycle.Nodup s) (x : Ξ±) (_hx : x ∈ s), Ξ±) s (fun l _hn x hx => prev l x hx) fun l₁ lβ‚‚ h => Function.hfunext (propext h.nodup_iff) fun h₁ hβ‚‚ _he => Function.hfunext rfl fun x y hxy => Function.hfunext (propext (by rw [eq_of_heq hxy]; simpa [eq_of_heq hxy] using h.mem_iff)) fun hm hm' he' => heq_of_eq (by rw [heq_iff_eq] at hxy; subst x; simpa using isRotated_prev_eq h h₁ _) -- `simp` cannot infer the proofs: see `prev_reverse_eq_next'` for `@[simp]` lemma. nonrec theorem prev_reverse_eq_next (s : Cycle Ξ±) : βˆ€ (hs : Nodup s) (x : Ξ±) (hx : x ∈ s), s.reverse.prev (nodup_reverse_iff.mpr hs) x (mem_reverse_iff.mpr hx) = s.next hs x hx := Quotient.inductionOn' s prev_reverse_eq_next @[simp] nonrec theorem prev_reverse_eq_next' (s : Cycle Ξ±) (hs : Nodup s.reverse) (x : Ξ±) (hx : x ∈ s.reverse) : s.reverse.prev hs x hx = s.next (nodup_reverse_iff.mp hs) x (mem_reverse_iff.mp hx) := prev_reverse_eq_next s (nodup_reverse_iff.mp hs) x (mem_reverse_iff.mp hx) -- `simp` cannot infer the proofs: see `next_reverse_eq_prev'` for `@[simp]` lemma. theorem next_reverse_eq_prev (s : Cycle Ξ±) (hs : Nodup s) (x : Ξ±) (hx : x ∈ s) : s.reverse.next (nodup_reverse_iff.mpr hs) x (mem_reverse_iff.mpr hx) = s.prev hs x hx := by simp [← prev_reverse_eq_next] @[simp] theorem next_reverse_eq_prev' (s : Cycle Ξ±) (hs : Nodup s.reverse) (x : Ξ±) (hx : x ∈ s.reverse) : s.reverse.next hs x hx = s.prev (nodup_reverse_iff.mp hs) x (mem_reverse_iff.mp hx) := by simp [← prev_reverse_eq_next] @[simp] nonrec theorem next_mem (s : Cycle Ξ±) (hs : Nodup s) (x : Ξ±) (hx : x ∈ s) : s.next hs x hx ∈ s := by induction s using Quot.inductionOn apply next_mem; assumption theorem prev_mem (s : Cycle Ξ±) (hs : Nodup s) (x : Ξ±) (hx : x ∈ s) : s.prev hs x hx ∈ s := by rw [← next_reverse_eq_prev, ← mem_reverse_iff] apply next_mem @[simp] nonrec theorem prev_next (s : Cycle Ξ±) : βˆ€ (hs : Nodup s) (x : Ξ±) (hx : x ∈ s), s.prev hs (s.next hs x hx) (next_mem s hs x hx) = x := Quotient.inductionOn' s prev_next @[simp] nonrec theorem next_prev (s : Cycle Ξ±) : βˆ€ (hs : Nodup s) (x : Ξ±) (hx : x ∈ s), s.next hs (s.prev hs x hx) (prev_mem s hs x hx) = x := Quotient.inductionOn' s next_prev end Decidable /-- We define a representation of concrete cycles, available when viewing them in a goal state or via `#eval`, when over representable types. For example, the cycle `(2 1 4 3)` will be shown as `c[2, 1, 4, 3]`. Two equal cycles may be printed differently if their internal representation is different. -/ unsafe instance [Repr Ξ±] : Repr (Cycle Ξ±) := ⟨fun s _ => "c[" ++ Std.Format.joinSep (s.map repr).lists.unquot.head! ", " ++ "]"⟩ /-- `chain R s` means that `R` holds between adjacent elements of `s`. `chain R ([a, b, c] : Cycle Ξ±) ↔ R a b ∧ R b c ∧ R c a` -/ nonrec def Chain (r : Ξ± β†’ Ξ± β†’ Prop) (c : Cycle Ξ±) : Prop := Quotient.liftOn' c (fun l => match l with | [] => True | a :: m => IsChain r (a :: m ++ [a])) fun a b hab => propext <| by rcases a with - | ⟨a, l⟩ <;> rcases b with - | ⟨b, m⟩ Β· rfl Β· have := isRotated_nil_iff'.1 hab contradiction Β· have := isRotated_nil_iff.1 hab contradiction Β· dsimp only obtain ⟨n, hn⟩ := hab induction n generalizing a b l m with | zero => simp only [rotate_zero, cons.injEq] at hn rw [hn.1, hn.2] | succ d hd => rcases l with - | ⟨c, s⟩ Β· simp only [rotate_cons_succ, nil_append, rotate_singleton, cons.injEq] at hn rw [hn.1, hn.2] Β· rw [Nat.add_comm, ← rotate_rotate, rotate_cons_succ, rotate_zero, cons_append] at hn rw [← hd c _ _ _ hn] simp [and_comm] @[simp] theorem Chain.nil (r : Ξ± β†’ Ξ± β†’ Prop) : Cycle.Chain r (@nil Ξ±) := by trivial @[simp] theorem chain_coe_cons (r : Ξ± β†’ Ξ± β†’ Prop) (a : Ξ±) (l : List Ξ±) : Chain r (a :: l) ↔ List.IsChain r (a :: (l ++ [a])) := Iff.rfl theorem chain_singleton (r : Ξ± β†’ Ξ± β†’ Prop) (a : Ξ±) : Chain r [a] ↔ r a a := by rw [chain_coe_cons, nil_append, List.isChain_pair] theorem chain_ne_nil (r : Ξ± β†’ Ξ± β†’ Prop) {l : List Ξ±} : βˆ€ hl : l β‰  [], Chain r l ↔ List.IsChain r (getLast l hl :: l) := l.reverseRecOn (fun hm => hm.irrefl.elim) (by intro m a _H _ rw [← coe_cons_eq_coe_append, chain_coe_cons, getLast_append_singleton]) theorem chain_map {Ξ² : Type*} {r : Ξ± β†’ Ξ± β†’ Prop} (f : Ξ² β†’ Ξ±) {s : Cycle Ξ²} : Chain r (s.map f) ↔ Chain (fun a b => r (f a) (f b)) s := Quotient.inductionOn s fun l => by rcases l with - | ⟨a, l⟩ Β· rfl Β· simp [← concat_eq_append, ← map_concat, List.isChain_cons_map f] theorem chain_range_succ (r : β„• β†’ β„• β†’ Prop) (n : β„•) : Chain r (List.range n.succ) ↔ r n 0 ∧ βˆ€ m < n, r m m.succ := by rw [range_succ, ← coe_cons_eq_coe_append, chain_coe_cons, ← range_succ, isChain_cons_range_succ] variable {r : Ξ± β†’ Ξ± β†’ Prop} {s : Cycle Ξ±} theorem Chain.imp {r₁ rβ‚‚ : Ξ± β†’ Ξ± β†’ Prop} (H : βˆ€ a b, r₁ a b β†’ rβ‚‚ a b) (p : Chain r₁ s) : Chain rβ‚‚ s := by induction s Β· trivial Β· rw [chain_coe_cons] at p ⊒ exact p.imp H /-- As a function from a relation to a predicate, `chain` is monotonic. -/ theorem chain_mono : Monotone (Chain : (Ξ± β†’ Ξ± β†’ Prop) β†’ Cycle Ξ± β†’ Prop) := fun _a _b hab _s => Chain.imp hab theorem chain_of_pairwise : (βˆ€ a ∈ s, βˆ€ b ∈ s, r a b) β†’ Chain r s := by induction s with | nil => exact fun _ ↦ Cycle.Chain.nil r | cons a l => ?_ intro hs have Ha : a ∈ (a :: l : Cycle Ξ±) := by simp have Hl : βˆ€ {b} (_hb : b ∈ l), b ∈ (a :: l : Cycle Ξ±) := @fun b hb => by simp [hb] rw [Cycle.chain_coe_cons] apply Pairwise.isChain rw [pairwise_cons] refine ⟨fun b hb => ?_, pairwise_append.2 ⟨pairwise_of_forall_mem_list fun b hb c hc => hs b (Hl hb) c (Hl hc), pairwise_singleton r a, fun b hb c hc => ?_⟩⟩ Β· rw [mem_append] at hb rcases hb with hb | hb Β· exact hs a Ha b (Hl hb) Β· rw [mem_singleton] at hb rw [hb] exact hs a Ha a Ha Β· rw [mem_singleton] at hc rw [hc] exact hs b (Hl hb) a Ha theorem chain_iff_pairwise [IsTrans Ξ± r] : Chain r s ↔ βˆ€ a ∈ s, βˆ€ b ∈ s, r a b := ⟨by induction s with | nil => exact fun _ b hb ↦ (notMem_nil _ hb).elim | cons a l => ?_ intro hs b hb c hc rw [Cycle.chain_coe_cons, List.isChain_iff_pairwise] at hs simp only [pairwise_append, pairwise_cons, mem_append, mem_singleton, List.not_mem_nil, IsEmpty.forall_iff, imp_true_iff, Pairwise.nil, forall_eq, true_and] at hs simp only [mem_coe_iff, mem_cons] at hb hc rcases hb with (rfl | hb) <;> rcases hc with (rfl | hc) Β· exact hs.1 c (Or.inr rfl) Β· exact hs.1 c (Or.inl hc) Β· exact hs.2.2 b hb Β· exact _root_.trans (hs.2.2 b hb) (hs.1 c (Or.inl hc)), Cycle.chain_of_pairwise⟩ theorem Chain.eq_nil_of_irrefl [IsTrans Ξ± r] [IsIrrefl Ξ± r] (h : Chain r s) : s = Cycle.nil := by induction s with | nil => rfl | cons a l h => have ha : a ∈ a :: l := mem_cons_self exact (irrefl_of r a <| chain_iff_pairwise.1 h a ha a ha).elim theorem Chain.eq_nil_of_well_founded [IsWellFounded Ξ± r] (h : Chain r s) : s = Cycle.nil := Chain.eq_nil_of_irrefl <| h.imp fun _ _ => Relation.TransGen.single theorem forall_eq_of_chain [IsTrans Ξ± r] [IsAntisymm Ξ± r] (hs : Chain r s) {a b : Ξ±} (ha : a ∈ s) (hb : b ∈ s) : a = b := by rw [chain_iff_pairwise] at hs exact antisymm (hs a ha b hb) (hs b hb a ha) end Cycle
.lake/packages/mathlib/Mathlib/Data/List/Intervals.lean
import Mathlib.Data.List.Lattice import Mathlib.Data.Bool.Basic import Mathlib.Order.Lattice /-! # Intervals in β„• This file defines intervals of naturals. `List.Ico m n` is the list of integers greater than `m` and strictly less than `n`. ## TODO - Define `Ioo` and `Icc`, state basic lemmas about them. - Also do the versions for integers? - One could generalise even further, defining 'locally finite partial orders', for which `Set.Ico a b` is `[Finite]`, and 'locally finite total orders', for which there is a list model. - Once the above is done, get rid of `Int.range` (and maybe `List.range'`?). -/ open Nat namespace List /-- `Ico n m` is the list of natural numbers `n ≀ x < m`. (Ico stands for "interval, closed-open".) See also `Mathlib/Order/Interval/Basic.lean` for modelling intervals in general preorders, as well as sibling definitions alongside it such as `Set.Ico`, `Multiset.Ico` and `Finset.Ico` for sets, multisets and finite sets respectively. -/ def Ico (n m : β„•) : List β„• := range' n (m - n) namespace Ico theorem zero_bot (n : β„•) : Ico 0 n = range n := by rw [Ico, Nat.sub_zero, range_eq_range'] @[simp] theorem length (n m : β„•) : length (Ico n m) = m - n := by dsimp [Ico] simp [length_range'] theorem pairwise_lt (n m : β„•) : Pairwise (Β· < Β·) (Ico n m) := by dsimp [Ico] simp [pairwise_lt_range'] theorem nodup (n m : β„•) : Nodup (Ico n m) := by dsimp [Ico] simp [nodup_range'] @[simp] theorem mem {n m l : β„•} : l ∈ Ico n m ↔ n ≀ l ∧ l < m := by suffices n ≀ l ∧ l < n + (m - n) ↔ n ≀ l ∧ l < m by simp [Ico, this] cutsat theorem eq_nil_of_le {n m : β„•} (h : m ≀ n) : Ico n m = [] := by simp [Ico, Nat.sub_eq_zero_iff_le.mpr h] theorem map_add (n m k : β„•) : (Ico n m).map (k + Β·) = Ico (n + k) (m + k) := by rw [Ico, Ico, map_add_range', Nat.add_sub_add_right m k, Nat.add_comm n k] theorem map_sub (n m k : β„•) (h₁ : k ≀ n) : ((Ico n m).map fun x => x - k) = Ico (n - k) (m - k) := by rw [Ico, Ico, Nat.sub_sub_sub_cancel_right h₁, map_sub_range' h₁] @[simp] theorem self_empty {n : β„•} : Ico n n = [] := eq_nil_of_le (le_refl n) @[simp] theorem eq_empty_iff {n m : β„•} : Ico n m = [] ↔ m ≀ n := Iff.intro (fun h => Nat.sub_eq_zero_iff_le.mp <| by rw [← length, h, List.length]) eq_nil_of_le theorem append_consecutive {n m l : β„•} (hnm : n ≀ m) (hml : m ≀ l) : Ico n m ++ Ico m l = Ico n l := by dsimp only [Ico] convert range'_append using 2 Β· rw [Nat.one_mul, Nat.add_sub_cancel' hnm] Β· cutsat @[simp] theorem inter_consecutive (n m l : β„•) : Ico n m ∩ Ico m l = [] := by apply eq_nil_iff_forall_not_mem.2 intro a simp only [and_imp, not_and, not_lt, List.mem_inter_iff, List.Ico.mem] intro _ hβ‚‚ h₃ exfalso exact not_lt_of_ge h₃ hβ‚‚ @[simp] theorem bagInter_consecutive (n m l : Nat) : @List.bagInter β„• instBEqOfDecidableEq (Ico n m) (Ico m l) = [] := (bagInter_nil_iff_inter_nil _ _).2 (by convert inter_consecutive n m l) @[simp] theorem succ_singleton {n : β„•} : Ico n (n + 1) = [n] := by dsimp [Ico] simp [Nat.add_sub_cancel_left] theorem succ_top {n m : β„•} (h : n ≀ m) : Ico n (m + 1) = Ico n m ++ [m] := by rwa [← succ_singleton, append_consecutive] exact Nat.le_succ _ theorem eq_cons {n m : β„•} (h : n < m) : Ico n m = n :: Ico (n + 1) m := by rw [← append_consecutive (Nat.le_succ n) h, succ_singleton] rfl @[simp] theorem pred_singleton {m : β„•} (h : 0 < m) : Ico (m - 1) m = [m - 1] := by simp [Ico, Nat.sub_sub_self (succ_le_of_lt h)] theorem isChain_succ (n m : β„•) : IsChain (fun a b => b = succ a) (Ico n m) := by by_cases! h : n < m Β· rw [eq_cons h] unfold List.Ico exact isChain_range' _ (_ + 1) 1 Β· rw [eq_nil_of_le h] exact .nil @[deprecated (since := "2025-09-19")] alias chain'_succ := isChain_succ theorem notMem_top {n m : β„•} : m βˆ‰ Ico n m := by simp @[deprecated (since := "2025-05-23")] alias not_mem_top := notMem_top theorem filter_lt_of_top_le {n m l : β„•} (hml : m ≀ l) : ((Ico n m).filter fun x => x < l) = Ico n m := filter_eq_self.2 fun k hk => by simp only [(lt_of_lt_of_le (mem.1 hk).2 hml), decide_true] theorem filter_lt_of_le_bot {n m l : β„•} (hln : l ≀ n) : ((Ico n m).filter fun x => x < l) = [] := filter_eq_nil_iff.2 fun k hk => by simp only [decide_eq_true_eq, not_lt] apply le_trans hln exact (mem.1 hk).1 theorem filter_lt_of_ge {n m l : β„•} (hlm : l ≀ m) : ((Ico n m).filter fun x => x < l) = Ico n l := by rcases le_total n l with hnl | hln Β· rw [← append_consecutive hnl hlm, filter_append, filter_lt_of_top_le (le_refl l), filter_lt_of_le_bot (le_refl l), append_nil] Β· rw [eq_nil_of_le hln, filter_lt_of_le_bot hln] @[simp] theorem filter_lt (n m l : β„•) : ((Ico n m).filter fun x => x < l) = Ico n (min m l) := by rcases le_total m l with hml | hlm Β· rw [min_eq_left hml, filter_lt_of_top_le hml] Β· rw [min_eq_right hlm, filter_lt_of_ge hlm] theorem filter_le_of_le_bot {n m l : β„•} (hln : l ≀ n) : ((Ico n m).filter fun x => l ≀ x) = Ico n m := filter_eq_self.2 fun k hk => by rw [decide_eq_true_eq] exact le_trans hln (mem.1 hk).1 theorem filter_le_of_top_le {n m l : β„•} (hml : m ≀ l) : ((Ico n m).filter fun x => l ≀ x) = [] := filter_eq_nil_iff.2 fun k hk => by rw [decide_eq_true_eq] exact not_le_of_gt (lt_of_lt_of_le (mem.1 hk).2 hml) theorem filter_le_of_le {n m l : β„•} (hnl : n ≀ l) : ((Ico n m).filter fun x => l ≀ x) = Ico l m := by rcases le_total l m with hlm | hml Β· rw [← append_consecutive hnl hlm, filter_append, filter_le_of_top_le (le_refl l), filter_le_of_le_bot (le_refl l), nil_append] Β· rw [eq_nil_of_le hml, filter_le_of_top_le hml] @[simp] theorem filter_le (n m l : β„•) : ((Ico n m).filter fun x => l ≀ x) = Ico (max n l) m := by rcases le_total n l with hnl | hln Β· rw [max_eq_right hnl, filter_le_of_le hnl] Β· rw [max_eq_left hln, filter_le_of_le_bot hln] theorem filter_lt_of_succ_bot {n m : β„•} (hnm : n < m) : ((Ico n m).filter fun x => x < n + 1) = [n] := by have r : min m (n + 1) = n + 1 := (@inf_eq_right _ _ m (n + 1)).mpr hnm simp [filter_lt n m (n + 1), r] @[simp] theorem filter_le_of_bot {n m : β„•} (hnm : n < m) : ((Ico n m).filter fun x => x ≀ n) = [n] := by rw [← filter_lt_of_succ_bot hnm] exact filter_congr fun _ _ => by simpa using Nat.lt_succ_iff.symm /-- For any natural numbers n, a, and b, one of the following holds: 1. n < a 2. n β‰₯ b 3. n ∈ Ico a b -/ theorem trichotomy (n a b : β„•) : n < a ∨ b ≀ n ∨ n ∈ Ico a b := by by_cases h₁ : n < a Β· left exact h₁ Β· right by_cases hβ‚‚ : n ∈ Ico a b Β· right exact hβ‚‚ Β· left simp only [Ico.mem, not_and, not_lt] at * exact hβ‚‚ h₁ end Ico end List
.lake/packages/mathlib/Mathlib/Data/List/Sym.lean
import Mathlib.Data.Nat.Choose.Basic import Mathlib.Data.Sym.Sym2 /-! # Unordered tuples of elements of a list Defines `List.sym` and the specialized `List.sym2` for computing lists of all unordered n-tuples from a given list. These are list versions of `Nat.multichoose`. ## Main declarations * `List.sym`: `xs.sym n` is a list of all unordered n-tuples of elements from `xs`, with multiplicity. The list's values are in `Sym Ξ± n`. * `List.sym2`: `xs.sym2` is a list of all unordered pairs of elements from `xs`, with multiplicity. The list's values are in `Sym2 Ξ±`. ## TODO * Prove `protected theorem Perm.sym (n : β„•) {xs ys : List Ξ±} (h : xs ~ ys) : xs.sym n ~ ys.sym n` and lift the result to `Multiset` and `Finset`. -/ namespace List variable {Ξ± Ξ² : Type*} section Sym2 /-- `xs.sym2` is a list of all unordered pairs of elements from `xs`. If `xs` has no duplicates then neither does `xs.sym2`. -/ protected def sym2 : List Ξ± β†’ List (Sym2 Ξ±) | [] => [] | x :: xs => (x :: xs).map (fun y => s(x, y)) ++ xs.sym2 theorem sym2_map (f : Ξ± β†’ Ξ²) (xs : List Ξ±) : (xs.map f).sym2 = xs.sym2.map (Sym2.map f) := by induction xs with | nil => simp [List.sym2] | cons x xs ih => simp [List.sym2, ih, Function.comp] theorem mem_sym2_cons_iff {x : Ξ±} {xs : List Ξ±} {z : Sym2 Ξ±} : z ∈ (x :: xs).sym2 ↔ z = s(x, x) ∨ (βˆƒ y, y ∈ xs ∧ z = s(x, y)) ∨ z ∈ xs.sym2 := by simp only [List.sym2, map_cons, cons_append, mem_cons, mem_append, mem_map] simp only [eq_comm] @[simp] theorem sym2_eq_nil_iff {xs : List Ξ±} : xs.sym2 = [] ↔ xs = [] := by cases xs <;> simp [List.sym2] theorem left_mem_of_mk_mem_sym2 {xs : List Ξ±} {a b : Ξ±} (h : s(a, b) ∈ xs.sym2) : a ∈ xs := by induction xs with | nil => exact (not_mem_nil h).elim | cons x xs ih => rw [mem_cons] rw [mem_sym2_cons_iff] at h obtain (h | ⟨c, hc, h⟩ | h) := h Β· rw [Sym2.eq_iff, ← and_or_left] at h exact .inl h.1 Β· rw [Sym2.eq_iff] at h obtain (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩) := h <;> simp [hc] Β· exact .inr <| ih h theorem right_mem_of_mk_mem_sym2 {xs : List Ξ±} {a b : Ξ±} (h : s(a, b) ∈ xs.sym2) : b ∈ xs := by rw [Sym2.eq_swap] at h exact left_mem_of_mk_mem_sym2 h theorem mk_mem_sym2 {xs : List Ξ±} {a b : Ξ±} (ha : a ∈ xs) (hb : b ∈ xs) : s(a, b) ∈ xs.sym2 := by induction xs with | nil => simp at ha | cons x xs ih => rw [mem_sym2_cons_iff] rw [mem_cons] at ha hb obtain (rfl | ha) := ha <;> obtain (rfl | hb) := hb Β· left; rfl Β· right; left; use b Β· right; left; rw [Sym2.eq_swap]; use a Β· right; right; exact ih ha hb theorem mk_mem_sym2_iff {xs : List Ξ±} {a b : Ξ±} : s(a, b) ∈ xs.sym2 ↔ a ∈ xs ∧ b ∈ xs := by constructor Β· intro h exact ⟨left_mem_of_mk_mem_sym2 h, right_mem_of_mk_mem_sym2 h⟩ Β· rintro ⟨ha, hb⟩ exact mk_mem_sym2 ha hb theorem mem_sym2_iff {xs : List Ξ±} {z : Sym2 Ξ±} : z ∈ xs.sym2 ↔ βˆ€ y ∈ z, y ∈ xs := by refine z.ind (fun a b => ?_) simp [mk_mem_sym2_iff] lemma setOf_mem_sym2 {xs : List Ξ±} : {z : Sym2 Ξ± | z ∈ xs.sym2} = {x : Ξ± | x ∈ xs}.sym2 := Set.ext fun z ↦ z.ind fun a b => by simp [mk_mem_sym2_iff] protected theorem Nodup.sym2 {xs : List Ξ±} (h : xs.Nodup) : xs.sym2.Nodup := by induction xs with | nil => simp only [List.sym2, nodup_nil] | cons x xs ih => rw [List.sym2] specialize ih h.of_cons rw [nodup_cons] at h refine Nodup.append (Nodup.cons ?notmem (h.2.map ?inj)) ih ?disj case disj => intro z hz hz' simp only [mem_cons, mem_map] at hz obtain ⟨_, (rfl | _), rfl⟩ := hz <;> simp [left_mem_of_mk_mem_sym2 hz'] at h case notmem => intro h' simp only [h.1, mem_map, Sym2.eq_iff, true_and, or_self, exists_eq_right] at h' case inj => intro a b simp only [Sym2.eq_iff, true_and] rintro (rfl | ⟨rfl, rfl⟩) <;> rfl theorem map_mk_sublist_sym2 (x : Ξ±) (xs : List Ξ±) (h : x ∈ xs) : map (fun y ↦ s(x, y)) xs <+ xs.sym2 := by induction xs with | nil => simp | cons x' xs ih => simp only [map_cons, List.sym2, cons_append] cases h with | head => exact (sublist_append_left _ _).consβ‚‚ _ | tail _ h => refine .cons _ ?_ rw [← singleton_append] refine .append ?_ (ih h) rw [singleton_sublist, mem_map] exact ⟨_, h, Sym2.eq_swap⟩ theorem map_mk_disjoint_sym2 (x : Ξ±) (xs : List Ξ±) (h : x βˆ‰ xs) : (map (fun y ↦ s(x, y)) xs).Disjoint xs.sym2 := by induction xs with | nil => simp | cons x' xs ih => simp only [mem_cons, not_or] at h rw [List.sym2, map_cons, map_cons, disjoint_cons_left, disjoint_append_right, disjoint_cons_right] refine ⟨?_, ⟨?_, ?_⟩, ?_⟩ Β· refine not_mem_cons_of_ne_of_not_mem ?_ (not_mem_append ?_ ?_) Β· simp [h.1] Β· simp_rw [mem_map, not_exists, not_and] intro x'' hx simp_rw [Sym2.mk_eq_mk_iff, Prod.swap_prod_mk, Prod.mk.injEq, true_and] rintro (⟨rfl, rfl⟩ | rfl) Β· exact h.2 hx Β· exact h.2 hx Β· simp [mk_mem_sym2_iff, h.2] Β· simp [h.1] Β· intro z hx hy rw [List.mem_map] at hx hy obtain ⟨a, hx, rfl⟩ := hx obtain ⟨b, hy, hx⟩ := hy simp only [Sym2.eq, Sym2.rel_iff', Prod.mk.injEq, Ne.symm h.1, false_and, Prod.swap_prod_mk, false_or] at hx obtain ⟨rfl, rfl⟩ := hx exact h.2 hy Β· exact ih h.2 theorem dedup_sym2 [DecidableEq Ξ±] (xs : List Ξ±) : xs.sym2.dedup = xs.dedup.sym2 := by induction xs with | nil => simp only [List.sym2, dedup_nil] | cons x xs ih => simp only [List.sym2, map_cons, cons_append] obtain hm | hm := Decidable.em (x ∈ xs) Β· rw [dedup_cons_of_mem hm, ← ih, dedup_cons_of_mem, List.Subset.dedup_append_right (map_mk_sublist_sym2 _ _ hm).subset] refine mem_append_left _ ?_ rw [mem_map] exact ⟨_, hm, Sym2.eq_swap⟩ Β· rw [dedup_cons_of_notMem hm, List.sym2, map_cons, ← ih, dedup_cons_of_notMem, cons_append, List.Disjoint.dedup_append, dedup_map_of_injective] Β· exact (Sym2.mkEmbedding _).injective Β· exact map_mk_disjoint_sym2 x xs hm Β· simp [hm, mem_sym2_iff] protected theorem Perm.sym2 {xs ys : List Ξ±} (h : xs ~ ys) : xs.sym2 ~ ys.sym2 := by induction h with | nil => rfl | cons x h ih => simp only [List.sym2, map_cons, cons_append, perm_cons] exact (h.map _).append ih | swap x y xs => simp only [List.sym2, map_cons, cons_append] conv => enter [1, 2, 1]; rw [Sym2.eq_swap] -- Explicit permutation to speed up simps that follow. refine Perm.trans (Perm.swap ..) (Perm.trans (Perm.cons _ ?_) (Perm.swap ..)) simp only [← Multiset.coe_eq_coe, ← Multiset.cons_coe, ← Multiset.coe_add, ← Multiset.singleton_add] simp only [add_left_comm] | trans _ _ ih1 ih2 => exact ih1.trans ih2 protected theorem Sublist.sym2 {xs ys : List Ξ±} (h : xs <+ ys) : xs.sym2 <+ ys.sym2 := by induction h with | slnil => apply slnil | cons a h ih => simp only [List.sym2] exact Sublist.append (nil_sublist _) ih | consβ‚‚ a h ih => simp only [List.sym2, map_cons, cons_append] exact consβ‚‚ _ (append (Sublist.map _ h) ih) protected theorem Subperm.sym2 {xs ys : List Ξ±} (h : xs <+~ ys) : xs.sym2 <+~ ys.sym2 := by obtain ⟨xs', hx, h⟩ := h exact hx.sym2.symm.subperm.trans h.sym2.subperm theorem length_sym2 {xs : List Ξ±} : xs.sym2.length = Nat.choose (xs.length + 1) 2 := by induction xs with | nil => rfl | cons x xs ih => rw [List.sym2, length_append, length_map, length_cons, Nat.choose_succ_succ, ← ih, Nat.choose_one_right] end Sym2 section Sym /-- `xs.sym n` is all unordered `n`-tuples from the list `xs` in some order. -/ protected def sym : (n : β„•) β†’ List Ξ± β†’ List (Sym Ξ± n) | 0, _ => [.nil] | _, [] => [] | n + 1, x :: xs => ((x :: xs).sym n |>.map fun p => x ::β‚› p) ++ xs.sym (n + 1) variable {xs ys : List Ξ±} {n : β„•} theorem sym_one_eq : xs.sym 1 = xs.map (Β· ::β‚› .nil) := by induction xs with | nil => simp only [List.sym, Nat.succ_eq_add_one, Nat.reduceAdd, map_nil] | cons x xs ih => rw [map_cons, ← ih, List.sym, List.sym, map_singleton, singleton_append] theorem sym2_eq_sym_two : xs.sym2.map (Sym2.equivSym Ξ±) = xs.sym 2 := by induction xs with | nil => simp only [List.sym, map_eq_nil_iff, sym2_eq_nil_iff] | cons x xs ih => rw [List.sym, ← ih, sym_one_eq, map_map, List.sym2, map_append, map_map] rfl theorem sym_map {Ξ² : Type*} (f : Ξ± β†’ Ξ²) (n : β„•) (xs : List Ξ±) : (xs.map f).sym n = (xs.sym n).map (Sym.map f) := match n, xs with | 0, _ => by simp only [List.sym]; rfl | n + 1, [] => by simp [List.sym] | n + 1, x :: xs => by rw [map_cons, List.sym, ← map_cons, sym_map f n (x :: xs), sym_map f (n + 1) xs] simp only [map_map, List.sym, map_append, append_cancel_right_eq] congr ext s simp only [Function.comp_apply, Sym.map_cons] protected theorem Sublist.sym (n : β„•) {xs ys : List Ξ±} (h : xs <+ ys) : xs.sym n <+ ys.sym n := match n, h with | 0, _ => by simp [List.sym] | n + 1, .slnil => by simp only [refl] | n + 1, .cons a h => by rw [List.sym, ← nil_append (List.sym (n + 1) xs)] apply Sublist.append (nil_sublist _) exact h.sym (n + 1) | n + 1, .consβ‚‚ a h => by rw [List.sym, List.sym] apply Sublist.append Β· exact ((consβ‚‚ a h).sym n).map _ Β· exact h.sym (n + 1) theorem sym_sublist_sym_cons {a : Ξ±} : xs.sym n <+ (a :: xs).sym n := (sublist_cons_self a xs).sym n theorem mem_of_mem_of_mem_sym {n : β„•} {xs : List Ξ±} {a : Ξ±} {z : Sym Ξ± n} (ha : a ∈ z) (hz : z ∈ xs.sym n) : a ∈ xs := match n, xs with | 0, xs => by cases Sym.eq_nil_of_card_zero z simp at ha | n + 1, [] => by simp [List.sym] at hz | n + 1, x :: xs => by rw [List.sym, mem_append, mem_map] at hz obtain ⟨z, hz, rfl⟩ | hz := hz Β· rw [Sym.mem_cons] at ha obtain rfl | ha := ha Β· simp Β· exact mem_of_mem_of_mem_sym ha hz Β· rw [mem_cons] right exact mem_of_mem_of_mem_sym ha hz theorem first_mem_of_cons_mem_sym {xs : List Ξ±} {n : β„•} {a : Ξ±} {z : Sym Ξ± n} (h : a ::β‚› z ∈ xs.sym (n + 1)) : a ∈ xs := mem_of_mem_of_mem_sym (Sym.mem_cons_self a z) h protected theorem Nodup.sym (n : β„•) {xs : List Ξ±} (h : xs.Nodup) : (xs.sym n).Nodup := match n, xs with | 0, _ => by simp [List.sym] | n + 1, [] => by simp [List.sym] | n + 1, x :: xs => by rw [List.sym] refine Nodup.append (Nodup.map ?inj (Nodup.sym n h)) (Nodup.sym (n + 1) h.of_cons) ?disj case inj => intro z z' simp case disj => intro z hz hz' rw [mem_map] at hz obtain ⟨z, _hz, rfl⟩ := hz have := first_mem_of_cons_mem_sym hz' simp only [nodup_cons, this, not_true_eq_false, false_and] at h theorem length_sym {n : β„•} {xs : List Ξ±} : (xs.sym n).length = Nat.multichoose xs.length n := match n, xs with | 0, _ => by rw [List.sym, Nat.multichoose]; rfl | n + 1, [] => by simp [List.sym] | n + 1, x :: xs => by rw [List.sym, length_append, length_map, length_cons] rw [@length_sym n (x :: xs), @length_sym (n + 1) xs] rw [Nat.multichoose_succ_succ, length_cons, add_comm] end Sym end List
.lake/packages/mathlib/Mathlib/Data/List/Rotate.lean
import Mathlib.Data.List.Nodup import Mathlib.Data.List.Infix import Mathlib.Data.Quot /-! # List rotation This file proves basic results about `List.rotate`, the list rotation. ## Main declarations * `List.IsRotated l₁ lβ‚‚`: States that `l₁` is a rotated version of `lβ‚‚`. * `List.cyclicPermutations l`: The list of all cyclic permutants of `l`, up to the length of `l`. ## Tags rotated, rotation, permutation, cycle -/ universe u variable {Ξ± : Type u} open Nat Function namespace List theorem rotate_mod (l : List Ξ±) (n : β„•) : l.rotate (n % l.length) = l.rotate n := by simp [rotate] @[simp] theorem rotate_nil (n : β„•) : ([] : List Ξ±).rotate n = [] := by simp [rotate] @[simp] theorem rotate_zero (l : List Ξ±) : l.rotate 0 = l := by simp [rotate] theorem rotate'_nil (n : β„•) : ([] : List Ξ±).rotate' n = [] := by simp @[simp] theorem rotate'_zero (l : List Ξ±) : l.rotate' 0 = l := by cases l <;> rfl theorem rotate'_cons_succ (l : List Ξ±) (a : Ξ±) (n : β„•) : (a :: l : List Ξ±).rotate' n.succ = (l ++ [a]).rotate' n := by simp [rotate'] @[simp] theorem length_rotate' : βˆ€ (l : List Ξ±) (n : β„•), (l.rotate' n).length = l.length | [], _ => by simp | _ :: _, 0 => rfl | a :: l, n + 1 => by rw [List.rotate', length_rotate' (l ++ [a]) n]; simp theorem rotate'_eq_drop_append_take : βˆ€ {l : List Ξ±} {n : β„•}, n ≀ l.length β†’ l.rotate' n = l.drop n ++ l.take n | [], n, h => by simp | l, 0, h => by simp | a :: l, n + 1, h => by have hnl : n ≀ l.length := le_of_succ_le_succ h have hnl' : n ≀ (l ++ [a]).length := by rw [length_append, length_cons, List.length]; exact le_of_succ_le h rw [rotate'_cons_succ, rotate'_eq_drop_append_take hnl', drop, take, drop_append_of_le_length hnl, take_append_of_le_length hnl]; simp theorem rotate'_rotate' : βˆ€ (l : List Ξ±) (n m : β„•), (l.rotate' n).rotate' m = l.rotate' (n + m) | a :: l, 0, m => by simp | [], n, m => by simp | a :: l, n + 1, m => by rw [rotate'_cons_succ, rotate'_rotate' _ n, Nat.add_right_comm, ← rotate'_cons_succ, Nat.succ_eq_add_one] @[simp] theorem rotate'_length (l : List Ξ±) : rotate' l l.length = l := by rw [rotate'_eq_drop_append_take le_rfl]; simp @[simp] theorem rotate'_length_mul (l : List Ξ±) : βˆ€ n : β„•, l.rotate' (l.length * n) = l | 0 => by simp | n + 1 => calc l.rotate' (l.length * (n + 1)) = (l.rotate' (l.length * n)).rotate' (l.rotate' (l.length * n)).length := by simp [-rotate'_length, Nat.mul_succ, rotate'_rotate'] _ = l := by rw [rotate'_length, rotate'_length_mul l n] theorem rotate'_mod (l : List Ξ±) (n : β„•) : l.rotate' (n % l.length) = l.rotate' n := calc l.rotate' (n % l.length) = (l.rotate' (n % l.length)).rotate' ((l.rotate' (n % l.length)).length * (n / l.length)) := by rw [rotate'_length_mul] _ = l.rotate' n := by rw [rotate'_rotate', length_rotate', Nat.mod_add_div] theorem rotate_eq_rotate' (l : List Ξ±) (n : β„•) : l.rotate n = l.rotate' n := if h : l.length = 0 then by simp_all [length_eq_zero_iff] else by rw [← rotate'_mod, rotate'_eq_drop_append_take (le_of_lt (Nat.mod_lt _ (Nat.pos_of_ne_zero h)))] simp [rotate] @[simp] theorem rotate_cons_succ (l : List Ξ±) (a : Ξ±) (n : β„•) : (a :: l : List Ξ±).rotate (n + 1) = (l ++ [a]).rotate n := by rw [rotate_eq_rotate', rotate_eq_rotate', rotate'_cons_succ] @[simp] theorem mem_rotate : βˆ€ {l : List Ξ±} {a : Ξ±} {n : β„•}, a ∈ l.rotate n ↔ a ∈ l | [], _, n => by simp | a :: l, _, 0 => by simp | a :: l, _, n + 1 => by simp [rotate_cons_succ, mem_rotate, or_comm] @[simp] theorem length_rotate (l : List Ξ±) (n : β„•) : (l.rotate n).length = l.length := by rw [rotate_eq_rotate', length_rotate'] @[simp] theorem rotate_replicate (a : Ξ±) (n : β„•) (k : β„•) : (replicate n a).rotate k = replicate n a := eq_replicate_iff.2 ⟨by rw [length_rotate, length_replicate], fun b hb => eq_of_mem_replicate <| mem_rotate.1 hb⟩ theorem rotate_eq_drop_append_take {l : List Ξ±} {n : β„•} : n ≀ l.length β†’ l.rotate n = l.drop n ++ l.take n := by rw [rotate_eq_rotate']; exact rotate'_eq_drop_append_take theorem rotate_eq_drop_append_take_mod {l : List Ξ±} {n : β„•} : l.rotate n = l.drop (n % l.length) ++ l.take (n % l.length) := by rcases l.length.zero_le.eq_or_lt with hl | hl Β· simp [eq_nil_of_length_eq_zero hl.symm] rw [← rotate_eq_drop_append_take (n.mod_lt hl).le, rotate_mod] @[simp] theorem rotate_append_length_eq (l l' : List Ξ±) : (l ++ l').rotate l.length = l' ++ l := by rw [rotate_eq_rotate'] induction l generalizing l' Β· simp Β· simp_all [rotate'] theorem rotate_rotate (l : List Ξ±) (n m : β„•) : (l.rotate n).rotate m = l.rotate (n + m) := by rw [rotate_eq_rotate', rotate_eq_rotate', rotate_eq_rotate', rotate'_rotate'] @[simp] theorem rotate_length (l : List Ξ±) : rotate l l.length = l := by rw [rotate_eq_rotate', rotate'_length] @[simp] theorem rotate_length_mul (l : List Ξ±) (n : β„•) : l.rotate (l.length * n) = l := by rw [rotate_eq_rotate', rotate'_length_mul] theorem rotate_perm (l : List Ξ±) (n : β„•) : l.rotate n ~ l := by rw [rotate_eq_rotate'] induction n generalizing l with | zero => simp | succ n hn => rcases l with - | ⟨hd, tl⟩ Β· simp Β· rw [rotate'_cons_succ] exact (hn _).trans (perm_append_singleton _ _) @[simp] theorem nodup_rotate {l : List Ξ±} {n : β„•} : Nodup (l.rotate n) ↔ Nodup l := (rotate_perm l n).nodup_iff @[simp] theorem rotate_eq_nil_iff {l : List Ξ±} {n : β„•} : l.rotate n = [] ↔ l = [] := by induction n generalizing l with | zero => simp | succ n hn => rcases l with - | ⟨hd, tl⟩ Β· simp Β· simp [rotate_cons_succ, hn] theorem nil_eq_rotate_iff {l : List Ξ±} {n : β„•} : [] = l.rotate n ↔ [] = l := by rw [eq_comm, rotate_eq_nil_iff, eq_comm] @[simp] theorem rotate_singleton (x : Ξ±) (n : β„•) : [x].rotate n = [x] := rotate_replicate x 1 n theorem zipWith_rotate_distrib {Ξ² Ξ³ : Type*} (f : Ξ± β†’ Ξ² β†’ Ξ³) (l : List Ξ±) (l' : List Ξ²) (n : β„•) (h : l.length = l'.length) : (zipWith f l l').rotate n = zipWith f (l.rotate n) (l'.rotate n) := by rw [rotate_eq_drop_append_take_mod, rotate_eq_drop_append_take_mod, rotate_eq_drop_append_take_mod, h, zipWith_append, ← drop_zipWith, ← take_zipWith, List.length_zipWith, h, min_self] rw [length_drop, length_drop, h] theorem zipWith_rotate_one {Ξ² : Type*} (f : Ξ± β†’ Ξ± β†’ Ξ²) (x y : Ξ±) (l : List Ξ±) : zipWith f (x :: y :: l) ((x :: y :: l).rotate 1) = f x y :: zipWith f (y :: l) (l ++ [x]) := by simp theorem getElem?_rotate {l : List Ξ±} {n m : β„•} (hml : m < l.length) : (l.rotate n)[m]? = l[(m + n) % l.length]? := by rw [rotate_eq_drop_append_take_mod] rcases lt_or_ge m (l.drop (n % l.length)).length with hm | hm Β· rw [getElem?_append_left hm, getElem?_drop, ← add_mod_mod] rw [length_drop, Nat.lt_sub_iff_add_lt] at hm rw [mod_eq_of_lt hm, Nat.add_comm] Β· have hlt : n % length l < length l := mod_lt _ (m.zero_le.trans_lt hml) rw [getElem?_append_right hm, getElem?_take_of_lt, length_drop] Β· congr 1 rw [length_drop] at hm have hm' := Nat.sub_le_iff_le_add'.1 hm have : n % length l + m - length l < length l := by rw [Nat.sub_lt_iff_lt_add hm'] exact Nat.add_lt_add hlt hml conv_rhs => rw [Nat.add_comm m, ← mod_add_mod, mod_eq_sub_mod hm', mod_eq_of_lt this] cutsat Β· rwa [Nat.sub_lt_iff_lt_add' hm, length_drop, Nat.sub_add_cancel hlt.le] theorem getElem_rotate (l : List Ξ±) (n : β„•) (k : Nat) (h : k < (l.rotate n).length) : (l.rotate n)[k] = l[(k + n) % l.length]'(mod_lt _ (length_rotate l n β–Έ k.zero_le.trans_lt h)) := by rw [← Option.some_inj, ← getElem?_eq_getElem, ← getElem?_eq_getElem, getElem?_rotate] exact h.trans_eq (length_rotate _ _) theorem get_rotate (l : List Ξ±) (n : β„•) (k : Fin (l.rotate n).length) : (l.rotate n).get k = l.get ⟨(k + n) % l.length, mod_lt _ (length_rotate l n β–Έ k.pos)⟩ := by simp [getElem_rotate] theorem head?_rotate {l : List Ξ±} {n : β„•} (h : n < l.length) : head? (l.rotate n) = l[n]? := by rw [head?_eq_getElem?, getElem?_rotate (n.zero_le.trans_lt h), Nat.zero_add, Nat.mod_eq_of_lt h] theorem get_rotate_one (l : List Ξ±) (k : Fin (l.rotate 1).length) : (l.rotate 1).get k = l.get ⟨(k + 1) % l.length, mod_lt _ (length_rotate l 1 β–Έ k.pos)⟩ := get_rotate l 1 k -- Allow `l[a]'b` to have a line break between `[a]'` and `b`. set_option linter.style.commandStart false in /-- A version of `List.getElem_rotate` that represents `l[k]` in terms of `(List.rotate l n)[β‹―]`, not vice versa. Can be used instead of rewriting `List.getElem_rotate` from right to left. -/ theorem getElem_eq_getElem_rotate (l : List Ξ±) (n : β„•) (k : Nat) (hk : k < l.length) : l[k] = ((l.rotate n)[(l.length - n % l.length + k) % l.length]' ((Nat.mod_lt _ (k.zero_le.trans_lt hk)).trans_eq (length_rotate _ _).symm)) := by rw [getElem_rotate] refine congr_arg l.get (Fin.eq_of_val_eq ?_) simp only [mod_add_mod] rw [← add_mod_mod, Nat.add_right_comm, Nat.sub_add_cancel, add_mod_left, mod_eq_of_lt] exacts [hk, (mod_lt _ (k.zero_le.trans_lt hk)).le] /-- A version of `List.get_rotate` that represents `List.get l` in terms of `List.get (List.rotate l n)`, not vice versa. Can be used instead of rewriting `List.get_rotate` from right to left. -/ theorem get_eq_get_rotate (l : List Ξ±) (n : β„•) (k : Fin l.length) : l.get k = (l.rotate n).get ⟨(l.length - n % l.length + k) % l.length, (Nat.mod_lt _ (k.1.zero_le.trans_lt k.2)).trans_eq (length_rotate _ _).symm⟩ := by rw [get_rotate] refine congr_arg l.get (Fin.eq_of_val_eq ?_) simp only [mod_add_mod] rw [← add_mod_mod, Nat.add_right_comm, Nat.sub_add_cancel, add_mod_left, mod_eq_of_lt] exacts [k.2, (mod_lt _ (k.1.zero_le.trans_lt k.2)).le] theorem rotate_eq_self_iff_eq_replicate [hΞ± : Nonempty Ξ±] : βˆ€ {l : List Ξ±}, (βˆ€ n, l.rotate n = l) ↔ βˆƒ a, l = replicate l.length a | [] => by simp | a :: l => ⟨fun h => ⟨a, ext_getElem length_replicate.symm fun n h₁ hβ‚‚ => by rw [getElem_replicate, ← Option.some_inj, ← getElem?_eq_getElem, ← head?_rotate h₁, h, head?_cons]⟩, fun ⟨b, hb⟩ n => by rw [hb, rotate_replicate]⟩ theorem rotate_one_eq_self_iff_eq_replicate [Nonempty Ξ±] {l : List Ξ±} : l.rotate 1 = l ↔ βˆƒ a : Ξ±, l = List.replicate l.length a := ⟨fun h => rotate_eq_self_iff_eq_replicate.mp fun n => Nat.rec l.rotate_zero (fun n hn => by rwa [Nat.succ_eq_add_one, ← l.rotate_rotate, hn]) n, fun h => rotate_eq_self_iff_eq_replicate.mpr h 1⟩ theorem rotate_injective (n : β„•) : Function.Injective fun l : List Ξ± => l.rotate n := by rintro l l' (h : l.rotate n = l'.rotate n) have hle : l.length = l'.length := (l.length_rotate n).symm.trans (h.symm β–Έ l'.length_rotate n) rw [rotate_eq_drop_append_take_mod, rotate_eq_drop_append_take_mod] at h obtain ⟨hd, ht⟩ := append_inj h (by simp_all) rw [← take_append_drop _ l, ht, hd, take_append_drop] @[simp] theorem rotate_eq_rotate {l l' : List Ξ±} {n : β„•} : l.rotate n = l'.rotate n ↔ l = l' := (rotate_injective n).eq_iff theorem rotate_eq_iff {l l' : List Ξ±} {n : β„•} : l.rotate n = l' ↔ l = l'.rotate (l'.length - n % l'.length) := by rw [← @rotate_eq_rotate _ l _ n, rotate_rotate, ← rotate_mod l', add_mod] rcases l'.length.zero_le.eq_or_lt with hl | hl Β· rw [eq_nil_of_length_eq_zero hl.symm, rotate_nil] Β· rcases (Nat.zero_le (n % l'.length)).eq_or_lt with hn | hn Β· simp [← hn] Β· rw [mod_eq_of_lt (Nat.sub_lt hl hn), Nat.sub_add_cancel, mod_self, rotate_zero] exact (Nat.mod_lt _ hl).le @[simp] theorem rotate_eq_singleton_iff {l : List Ξ±} {n : β„•} {x : Ξ±} : l.rotate n = [x] ↔ l = [x] := by rw [rotate_eq_iff, rotate_singleton] @[simp] theorem singleton_eq_rotate_iff {l : List Ξ±} {n : β„•} {x : Ξ±} : [x] = l.rotate n ↔ [x] = l := by rw [eq_comm, rotate_eq_singleton_iff, eq_comm] theorem reverse_rotate (l : List Ξ±) (n : β„•) : (l.rotate n).reverse = l.reverse.rotate (l.length - n % l.length) := by rw [← length_reverse, ← rotate_eq_iff] induction n generalizing l with | zero => simp | succ n hn => rcases l with - | ⟨hd, tl⟩ Β· simp Β· rw [rotate_cons_succ, ← rotate_rotate, hn] simp theorem rotate_reverse (l : List Ξ±) (n : β„•) : l.reverse.rotate n = (l.rotate (l.length - n % l.length)).reverse := by rw [← reverse_reverse l] simp_rw [reverse_rotate, reverse_reverse, rotate_eq_iff, rotate_rotate, length_rotate, length_reverse] rw [← length_reverse] let k := n % l.reverse.length rcases hk' : k with - | k' Β· simp_all! [k, length_reverse, ← rotate_rotate] Β· rcases l with - | ⟨x, l⟩ Β· simp Β· rw [Nat.mod_eq_of_lt, Nat.sub_add_cancel, rotate_length] Β· exact Nat.sub_le _ _ Β· exact Nat.sub_lt (by simp) (by simp_all! [k]) theorem map_rotate {Ξ² : Type*} (f : Ξ± β†’ Ξ²) (l : List Ξ±) (n : β„•) : map f (l.rotate n) = (map f l).rotate n := by induction n generalizing l with | zero => simp | succ n hn => rcases l with - | ⟨hd, tl⟩ Β· simp Β· simp [hn] theorem Nodup.rotate_congr {l : List Ξ±} (hl : l.Nodup) (hn : l β‰  []) (i j : β„•) (h : l.rotate i = l.rotate j) : i % l.length = j % l.length := by rw [← rotate_mod l i, ← rotate_mod l j] at h simpa only [head?_rotate, mod_lt, length_pos_of_ne_nil hn, getElem?_eq_getElem, Option.some_inj, hl.getElem_inj_iff, Fin.ext_iff] using congr_arg head? h theorem Nodup.rotate_congr_iff {l : List Ξ±} (hl : l.Nodup) {i j : β„•} : l.rotate i = l.rotate j ↔ i % l.length = j % l.length ∨ l = [] := by rcases eq_or_ne l [] with rfl | hn Β· simp Β· simp only [hn, or_false] refine ⟨hl.rotate_congr hn _ _, fun h ↦ ?_⟩ rw [← rotate_mod, h, rotate_mod] theorem Nodup.rotate_eq_self_iff {l : List Ξ±} (hl : l.Nodup) {n : β„•} : l.rotate n = l ↔ n % l.length = 0 ∨ l = [] := by rw [← zero_mod, ← hl.rotate_congr_iff, rotate_zero] section IsRotated variable (l l' : List Ξ±) /-- `IsRotated l₁ lβ‚‚` or `l₁ ~r lβ‚‚` asserts that `l₁` and `lβ‚‚` are cyclic permutations of each other. This is defined by claiming that `βˆƒ n, l.rotate n = l'`. -/ def IsRotated : Prop := βˆƒ n, l.rotate n = l' @[inherit_doc List.IsRotated] -- This matches the precedence of the infix `~` for `List.Perm`, and of other relation infixes infixr:50 " ~r " => IsRotated variable {l l'} @[refl] theorem IsRotated.refl (l : List Ξ±) : l ~r l := ⟨0, by simp⟩ @[symm] theorem IsRotated.symm (h : l ~r l') : l' ~r l := by obtain ⟨n, rfl⟩ := h rcases l with - | ⟨hd, tl⟩ Β· exists 0 Β· use (hd :: tl).length * n - n rw [rotate_rotate, Nat.add_sub_cancel', rotate_length_mul] exact Nat.le_mul_of_pos_left _ (by simp) theorem isRotated_comm : l ~r l' ↔ l' ~r l := ⟨IsRotated.symm, IsRotated.symm⟩ @[simp] protected theorem IsRotated.forall (l : List Ξ±) (n : β„•) : l.rotate n ~r l := IsRotated.symm ⟨n, rfl⟩ @[trans] theorem IsRotated.trans : βˆ€ {l l' l'' : List Ξ±}, l ~r l' β†’ l' ~r l'' β†’ l ~r l'' | _, _, _, ⟨n, rfl⟩, ⟨m, rfl⟩ => ⟨n + m, by rw [rotate_rotate]⟩ theorem IsRotated.eqv : Equivalence (@IsRotated Ξ±) := Equivalence.mk IsRotated.refl IsRotated.symm IsRotated.trans /-- The relation `List.IsRotated l l'` forms a `Setoid` of cycles. -/ def IsRotated.setoid (Ξ± : Type*) : Setoid (List Ξ±) where r := IsRotated iseqv := IsRotated.eqv theorem IsRotated.perm (h : l ~r l') : l ~ l' := Exists.elim h fun _ hl => hl β–Έ (rotate_perm _ _).symm theorem IsRotated.nodup_iff (h : l ~r l') : Nodup l ↔ Nodup l' := h.perm.nodup_iff theorem IsRotated.mem_iff (h : l ~r l') {a : Ξ±} : a ∈ l ↔ a ∈ l' := h.perm.mem_iff @[simp] theorem isRotated_nil_iff : l ~r [] ↔ l = [] := ⟨fun ⟨n, hn⟩ => by simpa using hn, fun h => h β–Έ by rfl⟩ @[simp] theorem isRotated_nil_iff' : [] ~r l ↔ [] = l := by rw [isRotated_comm, isRotated_nil_iff, eq_comm] @[simp] theorem isRotated_singleton_iff {x : Ξ±} : l ~r [x] ↔ l = [x] := ⟨fun ⟨n, hn⟩ => by simpa using hn, fun h => h β–Έ by rfl⟩ @[simp] theorem isRotated_singleton_iff' {x : Ξ±} : [x] ~r l ↔ [x] = l := by rw [isRotated_comm, isRotated_singleton_iff, eq_comm] theorem isRotated_concat (hd : Ξ±) (tl : List Ξ±) : (tl ++ [hd]) ~r (hd :: tl) := IsRotated.symm ⟨1, by simp⟩ theorem isRotated_append : (l ++ l') ~r (l' ++ l) := ⟨l.length, by simp⟩ theorem IsRotated.reverse (h : l ~r l') : l.reverse ~r l'.reverse := by obtain ⟨n, rfl⟩ := h exact ⟨_, (reverse_rotate _ _).symm⟩ theorem isRotated_reverse_comm_iff : l.reverse ~r l' ↔ l ~r l'.reverse := by constructor <;> Β· intro h simpa using h.reverse @[simp] theorem isRotated_reverse_iff : l.reverse ~r l'.reverse ↔ l ~r l' := by simp [isRotated_reverse_comm_iff] theorem isRotated_iff_mod : l ~r l' ↔ βˆƒ n ≀ l.length, l.rotate n = l' := by refine ⟨fun h => ?_, fun ⟨n, _, h⟩ => ⟨n, h⟩⟩ obtain ⟨n, rfl⟩ := h rcases l with - | ⟨hd, tl⟩ Β· simp Β· refine ⟨n % (hd :: tl).length, ?_, rotate_mod _ _⟩ refine (Nat.mod_lt _ ?_).le simp theorem isRotated_iff_mem_map_range : l ~r l' ↔ l' ∈ (List.range (l.length + 1)).map l.rotate := by simp_rw [mem_map, mem_range, isRotated_iff_mod] exact ⟨fun ⟨n, hn, h⟩ => ⟨n, Nat.lt_succ_of_le hn, h⟩, fun ⟨n, hn, h⟩ => ⟨n, Nat.le_of_lt_succ hn, h⟩⟩ theorem IsRotated.map {Ξ² : Type*} {l₁ lβ‚‚ : List Ξ±} (h : l₁ ~r lβ‚‚) (f : Ξ± β†’ Ξ²) : map f l₁ ~r map f lβ‚‚ := by obtain ⟨n, rfl⟩ := h rw [map_rotate] use n theorem IsRotated.cons_getLast_dropLast (L : List Ξ±) (hL : L β‰  []) : L.getLast hL :: L.dropLast ~r L := by induction L using List.reverseRecOn with | nil => simp at hL | append_singleton a L _ => simp only [getLast_append, dropLast_concat] apply IsRotated.symm apply isRotated_concat theorem IsRotated.dropLast_tail {Ξ±} {L : List Ξ±} (hL : L β‰  []) (hL' : L.head hL = L.getLast hL) : L.dropLast ~r L.tail := match L with | [] => by simp | [_] => by simp | a :: b :: L => by simp only [head_cons, ne_eq, reduceCtorEq, not_false_eq_true, getLast_cons] at hL' simp [hL', IsRotated.cons_getLast_dropLast] /-- List of all cyclic permutations of `l`. The `cyclicPermutations` of a nonempty list `l` will always contain `List.length l` elements. This implies that under certain conditions, there are duplicates in `List.cyclicPermutations l`. The `n`th entry is equal to `l.rotate n`, proven in `List.get_cyclicPermutations`. The proof that every cyclic permutant of `l` is in the list is `List.mem_cyclicPermutations_iff`. cyclicPermutations [1, 2, 3, 2, 4] = [[1, 2, 3, 2, 4], [2, 3, 2, 4, 1], [3, 2, 4, 1, 2], [2, 4, 1, 2, 3], [4, 1, 2, 3, 2]] -/ def cyclicPermutations : List Ξ± β†’ List (List Ξ±) | [] => [[]] | l@(_ :: _) => dropLast (zipWith (Β· ++ Β·) (tails l) (inits l)) @[simp] theorem cyclicPermutations_nil : cyclicPermutations ([] : List Ξ±) = [[]] := rfl theorem cyclicPermutations_cons (x : Ξ±) (l : List Ξ±) : cyclicPermutations (x :: l) = dropLast (zipWith (Β· ++ Β·) (tails (x :: l)) (inits (x :: l))) := rfl theorem cyclicPermutations_of_ne_nil (l : List Ξ±) (h : l β‰  []) : cyclicPermutations l = dropLast (zipWith (Β· ++ Β·) (tails l) (inits l)) := by obtain ⟨hd, tl, rfl⟩ := exists_cons_of_ne_nil h exact cyclicPermutations_cons _ _ theorem length_cyclicPermutations_cons (x : Ξ±) (l : List Ξ±) : length (cyclicPermutations (x :: l)) = length l + 1 := by simp [cyclicPermutations_cons] @[simp] theorem length_cyclicPermutations_of_ne_nil (l : List Ξ±) (h : l β‰  []) : length (cyclicPermutations l) = length l := by simp [cyclicPermutations_of_ne_nil _ h] @[simp] theorem cyclicPermutations_ne_nil : βˆ€ l : List Ξ±, cyclicPermutations l β‰  [] | a::l, h => by simpa using congr_arg length h @[simp] theorem getElem_cyclicPermutations (l : List Ξ±) (n : Nat) (h : n < length (cyclicPermutations l)) : (cyclicPermutations l)[n] = l.rotate n := by cases l with | nil => simp | cons a l => simp only [cyclicPermutations_cons, getElem_dropLast, getElem_zipWith, getElem_tails, getElem_inits] rw [rotate_eq_drop_append_take (by simpa using h.le)] theorem get_cyclicPermutations (l : List Ξ±) (n : Fin (length (cyclicPermutations l))) : (cyclicPermutations l).get n = l.rotate n := by simp @[simp] theorem head_cyclicPermutations (l : List Ξ±) : (cyclicPermutations l).head (cyclicPermutations_ne_nil l) = l := by have h : 0 < length (cyclicPermutations l) := length_pos_of_ne_nil (cyclicPermutations_ne_nil _) rw [← get_mk_zero h, get_cyclicPermutations, Fin.val_mk, rotate_zero] @[simp] theorem head?_cyclicPermutations (l : List Ξ±) : (cyclicPermutations l).head? = l := by rw [head?_eq_head (cyclicPermutations_ne_nil l), head_cyclicPermutations] theorem cyclicPermutations_injective : Function.Injective (@cyclicPermutations Ξ±) := fun l l' h ↦ by simpa using congr_arg head? h @[simp] theorem cyclicPermutations_inj {l l' : List Ξ±} : cyclicPermutations l = cyclicPermutations l' ↔ l = l' := cyclicPermutations_injective.eq_iff theorem length_mem_cyclicPermutations (l : List Ξ±) (h : l' ∈ cyclicPermutations l) : length l' = length l := by obtain ⟨k, hk, rfl⟩ := get_of_mem h simp theorem mem_cyclicPermutations_self (l : List Ξ±) : l ∈ cyclicPermutations l := by simpa using head_mem (cyclicPermutations_ne_nil l) @[simp] theorem cyclicPermutations_rotate (l : List Ξ±) (k : β„•) : (l.rotate k).cyclicPermutations = l.cyclicPermutations.rotate k := by have : (l.rotate k).cyclicPermutations.length = length (l.cyclicPermutations.rotate k) := by cases l Β· simp Β· rw [length_cyclicPermutations_of_ne_nil] <;> simp refine ext_get this fun n hn hn' => ?_ rw [get_rotate, get_cyclicPermutations, rotate_rotate, ← rotate_mod, Nat.add_comm] cases l <;> simp @[simp] theorem mem_cyclicPermutations_iff : l ∈ cyclicPermutations l' ↔ l ~r l' := by constructor Β· simp_rw [mem_iff_get, get_cyclicPermutations] rintro ⟨k, rfl⟩ exact .forall _ _ Β· rintro ⟨k, rfl⟩ rw [cyclicPermutations_rotate, mem_rotate] apply mem_cyclicPermutations_self @[simp] theorem cyclicPermutations_eq_nil_iff {l : List Ξ±} : cyclicPermutations l = [[]] ↔ l = [] := cyclicPermutations_injective.eq_iff' rfl @[simp] theorem cyclicPermutations_eq_singleton_iff {l : List Ξ±} {x : Ξ±} : cyclicPermutations l = [[x]] ↔ l = [x] := cyclicPermutations_injective.eq_iff' rfl /-- If a `l : List Ξ±` is `Nodup l`, then all of its cyclic permutants are distinct. -/ protected theorem Nodup.cyclicPermutations {l : List Ξ±} (hn : Nodup l) : Nodup (cyclicPermutations l) := by rcases eq_or_ne l [] with rfl | hl Β· simp Β· rw [nodup_iff_injective_get] rintro ⟨i, hi⟩ ⟨j, hj⟩ h simp only [length_cyclicPermutations_of_ne_nil l hl] at hi hj simpa [hn.rotate_congr_iff, mod_eq_of_lt, *] using h protected theorem IsRotated.cyclicPermutations {l l' : List Ξ±} (h : l ~r l') : l.cyclicPermutations ~r l'.cyclicPermutations := by obtain ⟨k, rfl⟩ := h exact ⟨k, by simp⟩ @[simp] theorem isRotated_cyclicPermutations_iff {l l' : List Ξ±} : l.cyclicPermutations ~r l'.cyclicPermutations ↔ l ~r l' := by simp only [IsRotated, ← cyclicPermutations_rotate, cyclicPermutations_inj] section Decidable variable [DecidableEq Ξ±] instance isRotatedDecidable (l l' : List Ξ±) : Decidable (l ~r l') := decidable_of_iff' _ isRotated_iff_mem_map_range instance {l l' : List Ξ±} : Decidable (IsRotated.setoid Ξ± l l') := List.isRotatedDecidable _ _ end Decidable end IsRotated end List
.lake/packages/mathlib/Mathlib/Data/List/Perm/Subperm.lean
import Batteries.Data.List.Perm import Mathlib.Data.List.Basic /-! # List Sub-permutations This file develops theory about the `List.Subperm` relation. ## Notation The notation `<+~` is used for sub-permutations. -/ open Nat namespace List variable {Ξ± : Type*} {l l₁ lβ‚‚ : List Ξ±} {a : Ξ±} open Perm section Subperm attribute [trans] Subperm.trans end Subperm /-- See also `List.subperm_ext_iff`. -/ lemma subperm_iff_count [DecidableEq Ξ±] : l₁ <+~ lβ‚‚ ↔ βˆ€ a, count a l₁ ≀ count a lβ‚‚ := subperm_ext_iff.trans <| forall_congr' fun a ↦ by by_cases ha : a ∈ l₁ <;> simp [ha, count_eq_zero_of_not_mem] lemma subperm_iff : l₁ <+~ lβ‚‚ ↔ βˆƒ l, l ~ lβ‚‚ ∧ l₁ <+ l := by refine ⟨?_, fun ⟨l, h₁, hβ‚‚βŸ© ↦ hβ‚‚.subperm.trans h₁.subperm⟩ rintro ⟨l, h₁, hβ‚‚βŸ© obtain ⟨l', hβ‚‚βŸ© := hβ‚‚.exists_perm_append exact ⟨l₁ ++ l', (hβ‚‚.trans (h₁.append_right _)).symm, (prefix_append _ _).sublist⟩ @[simp] lemma subperm_singleton_iff : l <+~ [a] ↔ l = [] ∨ l = [a] := by constructor Β· rw [subperm_iff] rintro ⟨s, hla, h⟩ rwa [perm_singleton.mp hla, sublist_singleton] at h Β· rintro (rfl | rfl) exacts [nil_subperm, Subperm.refl _] lemma subperm_cons_self : l <+~ a :: l := ⟨l, Perm.refl _, sublist_cons_self _ _⟩ protected alias ⟨subperm.of_cons, subperm.cons⟩ := subperm_cons protected theorem Nodup.subperm (d : Nodup l₁) (H : l₁ βŠ† lβ‚‚) : l₁ <+~ lβ‚‚ := subperm_of_subset d H end List
.lake/packages/mathlib/Mathlib/Data/List/Perm/Basic.lean
import Batteries.Data.List.Perm import Mathlib.Logic.Relation import Mathlib.Order.RelClasses import Mathlib.Data.List.Forall2 import Mathlib.Data.List.InsertIdx /-! # List Permutations This file develops theory about the `List.Perm` relation. ## Notation The notation `~` is used for permutation equivalence. -/ -- Make sure we don't import algebra assert_not_exists Monoid open Nat namespace List variable {Ξ± Ξ² : Type*} {l : List Ξ±} open Perm (swap) lemma perm_rfl : l ~ l := Perm.refl _ attribute [symm] Perm.symm attribute [trans] Perm.trans instance : IsSymm (List Ξ±) Perm := ⟨fun _ _ ↦ .symm⟩ theorem Perm.subset_congr_left {l₁ lβ‚‚ l₃ : List Ξ±} (h : l₁ ~ lβ‚‚) : l₁ βŠ† l₃ ↔ lβ‚‚ βŠ† l₃ := ⟨h.symm.subset.trans, h.subset.trans⟩ theorem Perm.subset_congr_right {l₁ lβ‚‚ l₃ : List Ξ±} (h : l₁ ~ lβ‚‚) : l₃ βŠ† l₁ ↔ l₃ βŠ† lβ‚‚ := ⟨fun h' => h'.trans h.subset, fun h' => h'.trans h.symm.subset⟩ theorem set_perm_cons_eraseIdx {n : β„•} (h : n < l.length) (a : Ξ±) : l.set n a ~ a :: l.eraseIdx n := by rw [← insertIdx_eraseIdx_self h.ne] apply perm_insertIdx rw [length_eraseIdx_of_lt h] exact Nat.le_sub_one_of_lt h theorem getElem_cons_eraseIdx_perm {n : β„•} (h : n < l.length) : l[n] :: l.eraseIdx n ~ l := by simpa [h] using (set_perm_cons_eraseIdx h l[n]).symm theorem perm_insertIdx_iff_of_le {l₁ lβ‚‚ : List Ξ±} {m n : β„•} (hm : m ≀ l₁.length) (hn : n ≀ lβ‚‚.length) (a : Ξ±) : l₁.insertIdx m a ~ lβ‚‚.insertIdx n a ↔ l₁ ~ lβ‚‚ := by rw [rel_congr_left (perm_insertIdx _ _ hm), rel_congr_right (perm_insertIdx _ _ hn), perm_cons] alias ⟨_, Perm.insertIdx_of_le⟩ := perm_insertIdx_iff_of_le @[simp] theorem perm_insertIdx_iff {l₁ lβ‚‚ : List Ξ±} {n : β„•} {a : Ξ±} : l₁.insertIdx n a ~ lβ‚‚.insertIdx n a ↔ l₁ ~ lβ‚‚ := by wlog hle : length l₁ ≀ length lβ‚‚ generalizing l₁ lβ‚‚ Β· rw [perm_comm, this (le_of_not_ge hle), perm_comm] cases Nat.lt_or_ge (length l₁) n with | inl hn₁ => rw [insertIdx_of_length_lt hn₁] cases Nat.lt_or_ge (length lβ‚‚) n with | inl hnβ‚‚ => rw [insertIdx_of_length_lt hnβ‚‚] | inr hnβ‚‚ => apply iff_of_false Β· intro h rw [h.length_eq] at hn₁ exact (hn₁.trans_le hnβ‚‚).not_ge (length_le_length_insertIdx ..) Β· exact fun h ↦ (hn₁.trans_le hnβ‚‚).not_ge h.length_eq.ge | inr hn₁ => exact perm_insertIdx_iff_of_le hn₁ (le_trans hn₁ hle) _ @[gcongr] protected theorem Perm.insertIdx {l₁ lβ‚‚ : List Ξ±} (h : l₁ ~ lβ‚‚) (n : β„•) (a : Ξ±) : l₁.insertIdx n a ~ lβ‚‚.insertIdx n a := perm_insertIdx_iff.mpr h theorem perm_eraseIdx_of_getElem?_eq {l₁ lβ‚‚ : List Ξ±} {m n : β„•} (h : l₁[m]? = lβ‚‚[n]?) : eraseIdx l₁ m ~ eraseIdx lβ‚‚ n ↔ l₁ ~ lβ‚‚ := by cases Nat.lt_or_ge m l₁.length with | inl hm => rw [getElem?_eq_getElem hm, eq_comm, getElem?_eq_some_iff] at h cases h with | intro hn hnm => rw [← perm_cons l₁[m], rel_congr_left (getElem_cons_eraseIdx_perm ..), ← hnm, rel_congr_right (getElem_cons_eraseIdx_perm ..)] | inr hm => rw [getElem?_eq_none hm, eq_comm, getElem?_eq_none_iff] at h rw [eraseIdx_of_length_le h, eraseIdx_of_length_le hm] alias ⟨_, Perm.eraseIdx_of_getElem?_eq⟩ := perm_eraseIdx_of_getElem?_eq section Rel open Relator variable {r : Ξ± β†’ Ξ² β†’ Prop} local infixr:80 " ∘r " => Relation.Comp theorem perm_comp_perm : (Perm ∘r Perm : List Ξ± β†’ List Ξ± β†’ Prop) = Perm := by funext a c; apply propext constructor Β· exact fun ⟨b, hab, hba⟩ => Perm.trans hab hba Β· exact fun h => ⟨a, Perm.refl a, h⟩ theorem perm_comp_forallβ‚‚ {l u v} (hlu : Perm l u) (huv : Forallβ‚‚ r u v) : (Forallβ‚‚ r ∘r Perm) l v := by induction hlu generalizing v with | nil => cases huv; exact ⟨[], Forallβ‚‚.nil, Perm.nil⟩ | cons u _hlu ih => obtain - | ⟨hab, huv'⟩ := huv rcases ih huv' with ⟨lβ‚‚, h₁₂, hβ‚‚β‚ƒβŸ© exact ⟨_ :: lβ‚‚, Forallβ‚‚.cons hab h₁₂, h₂₃.cons _⟩ | swap a₁ aβ‚‚ h₂₃ => obtain - | ⟨h₁, hrβ‚‚β‚ƒβŸ© := huv obtain - | ⟨hβ‚‚, hβ‚β‚‚βŸ© := hr₂₃ exact ⟨_, Forallβ‚‚.cons hβ‚‚ (Forallβ‚‚.cons h₁ h₁₂), Perm.swap _ _ _⟩ | trans _ _ ih₁ ihβ‚‚ => rcases ihβ‚‚ huv with ⟨lbβ‚‚, habβ‚‚, hβ‚‚β‚ƒβŸ© rcases ih₁ habβ‚‚ with ⟨lb₁, hab₁, hβ‚β‚‚βŸ© exact ⟨lb₁, hab₁, Perm.trans h₁₂ hβ‚‚β‚ƒβŸ© theorem forallβ‚‚_comp_perm_eq_perm_comp_forallβ‚‚ : Forallβ‚‚ r ∘r Perm = Perm ∘r Forallβ‚‚ r := by funext l₁ l₃; apply propext constructor Β· intro h rcases h with ⟨lβ‚‚, h₁₂, hβ‚‚β‚ƒβŸ© have : Forallβ‚‚ (flip r) lβ‚‚ l₁ := h₁₂.flip rcases perm_comp_forallβ‚‚ h₂₃.symm this with ⟨l', h₁, hβ‚‚βŸ© exact ⟨l', hβ‚‚.symm, h₁.flip⟩ Β· exact fun ⟨lβ‚‚, h₁₂, hβ‚‚β‚ƒβŸ© => perm_comp_forallβ‚‚ h₁₂ h₂₃ theorem eq_map_comp_perm (f : Ξ± β†’ Ξ²) : (Β· = map f Β·) ∘r (Β· ~ Β·) = (Β· ~ map f Β·) := by conv_rhs => rw [← Relation.comp_eq_fun (map f)] simp only [← forallβ‚‚_eq_eq_eq, forallβ‚‚_map_right_iff, forallβ‚‚_comp_perm_eq_perm_comp_forallβ‚‚] theorem rel_perm_imp (hr : RightUnique r) : (Forallβ‚‚ r β‡’ Forallβ‚‚ r β‡’ (Β· β†’ Β·)) Perm Perm := fun a b h₁ c d hβ‚‚ h => have : (flip (Forallβ‚‚ r) ∘r Perm ∘r Forallβ‚‚ r) b d := ⟨a, h₁, c, h, hβ‚‚βŸ© have : ((flip (Forallβ‚‚ r) ∘r Forallβ‚‚ r) ∘r Perm) b d := by rwa [← forallβ‚‚_comp_perm_eq_perm_comp_forallβ‚‚, ← Relation.comp_assoc] at this let ⟨b', ⟨_, hbc, hcb⟩, hbd⟩ := this have : b' = b := right_unique_forallβ‚‚' hr hcb hbc this β–Έ hbd theorem rel_perm (hr : BiUnique r) : (Forallβ‚‚ r β‡’ Forallβ‚‚ r β‡’ (Β· ↔ Β·)) Perm Perm := fun _a _b hab _c _d hcd => Iff.intro (rel_perm_imp hr.2 hab hcd) (rel_perm_imp hr.left.flip hab.flip hcd.flip) end Rel lemma count_eq_count_filter_add [DecidableEq Ξ±] (P : Ξ± β†’ Prop) [DecidablePred P] (l : List Ξ±) (a : Ξ±) : count a l = count a (l.filter P) + count a (l.filter (Β¬ P Β·)) := by convert countP_eq_countP_filter_add l _ P simp only [decide_not] theorem Perm.foldl_eq {f : Ξ² β†’ Ξ± β†’ Ξ²} {l₁ lβ‚‚ : List Ξ±} [rcomm : RightCommutative f] (p : l₁ ~ lβ‚‚) : βˆ€ b, foldl f b l₁ = foldl f b lβ‚‚ := p.foldl_eq' fun x _hx y _hy z => rcomm.right_comm z x y theorem Perm.foldr_eq {f : Ξ± β†’ Ξ² β†’ Ξ²} {l₁ lβ‚‚ : List Ξ±} [lcomm : LeftCommutative f] (p : l₁ ~ lβ‚‚) : βˆ€ b, foldr f b l₁ = foldr f b lβ‚‚ := by intro b induction p using Perm.recOnSwap' generalizing b with | nil => rfl | cons _ _ r => simp [r b] | swap' _ _ _ r => simp only [foldr_cons]; rw [lcomm.left_comm, r b] | trans _ _ r₁ rβ‚‚ => exact Eq.trans (r₁ b) (rβ‚‚ b) section variable {op : Ξ± β†’ Ξ± β†’ Ξ±} [IA : Std.Associative op] [IC : Std.Commutative op] local notation a " * " b => op a b local notation l " <*> " a => foldl op a l theorem Perm.foldl_op_eq {l₁ lβ‚‚ : List Ξ±} {a : Ξ±} (h : l₁ ~ lβ‚‚) : (l₁ <*> a) = lβ‚‚ <*> a := h.foldl_eq _ theorem Perm.foldr_op_eq {l₁ lβ‚‚ : List Ξ±} {a : Ξ±} (h : l₁ ~ lβ‚‚) : l₁.foldr op a = lβ‚‚.foldr op a := h.foldr_eq _ end theorem perm_option_toList {o₁ oβ‚‚ : Option Ξ±} : o₁.toList ~ oβ‚‚.toList ↔ o₁ = oβ‚‚ := by refine ⟨fun p => ?_, fun e => e β–Έ Perm.refl _⟩ rcases o₁ with - | a <;> rcases oβ‚‚ with - | b; Β· rfl Β· cases p.length_eq Β· cases p.length_eq Β· exact Option.mem_toList.1 (p.symm.subset <| by simp) theorem perm_replicate_append_replicate [DecidableEq Ξ±] {l : List Ξ±} {a b : Ξ±} {m n : β„•} (h : a β‰  b) : l ~ replicate m a ++ replicate n b ↔ count a l = m ∧ count b l = n ∧ l βŠ† [a, b] := by rw [perm_iff_count, ← Decidable.and_forall_ne a, ← Decidable.and_forall_ne b] suffices l βŠ† [a, b] ↔ βˆ€ c, c β‰  b β†’ c β‰  a β†’ c βˆ‰ l by simp +contextual [count_replicate, h, this, count_eq_zero, Ne.symm] trans βˆ€ c, c ∈ l β†’ c = b ∨ c = a Β· simp [subset_def, or_comm] Β· exact forall_congr' fun _ => by rw [← and_imp, ← not_or, not_imp_not] theorem map_perm_map_iff {l' : List Ξ±} {f : Ξ± β†’ Ξ²} (hf : f.Injective) : map f l ~ map f l' ↔ l ~ l' := calc map f l ~ map f l' ↔ Relation.Comp (Β· = map f Β·) (Β· ~ Β·) (map f l) l' := by rw [eq_map_comp_perm] _ ↔ l ~ l' := by simp [Relation.Comp, map_inj_right hf] theorem Perm.flatMap_left (l : List Ξ±) {f g : Ξ± β†’ List Ξ²} (h : βˆ€ a ∈ l, f a ~ g a) : l.flatMap f ~ l.flatMap g := Perm.flatten_congr <| by rwa [List.forallβ‚‚_map_right_iff, List.forallβ‚‚_map_left_iff, List.forallβ‚‚_same] @[gcongr] protected theorem Perm.flatMap {l₁ lβ‚‚ : List Ξ±} {f g : Ξ± β†’ List Ξ²} (h : l₁ ~ lβ‚‚) (hfg : βˆ€ a ∈ l₁, f a ~ g a) : l₁.flatMap f ~ lβ‚‚.flatMap g := .trans (.flatMap_left _ hfg) (h.flatMap_right _) theorem flatMap_append_perm (l : List Ξ±) (f g : Ξ± β†’ List Ξ²) : l.flatMap f ++ l.flatMap g ~ l.flatMap fun x => f x ++ g x := by induction l with | nil => simp | cons a l IH => ?_ simp only [flatMap_cons, append_assoc] refine (Perm.trans ?_ (IH.append_left _)).append_left _ rw [← append_assoc, ← append_assoc] exact perm_append_comm.append_right _ theorem map_append_flatMap_perm (l : List Ξ±) (f : Ξ± β†’ Ξ²) (g : Ξ± β†’ List Ξ²) : l.map f ++ l.flatMap g ~ l.flatMap fun x => f x :: g x := by simpa [← map_eq_flatMap] using flatMap_append_perm l (fun x => [f x]) g theorem Perm.product_right {l₁ lβ‚‚ : List Ξ±} (t₁ : List Ξ²) (p : l₁ ~ lβ‚‚) : product l₁ t₁ ~ product lβ‚‚ t₁ := p.flatMap_right _ theorem Perm.product_left (l : List Ξ±) {t₁ tβ‚‚ : List Ξ²} (p : t₁ ~ tβ‚‚) : product l t₁ ~ product l tβ‚‚ := (Perm.flatMap_left _) fun _ _ => p.map _ @[gcongr] theorem Perm.product {l₁ lβ‚‚ : List Ξ±} {t₁ tβ‚‚ : List Ξ²} (p₁ : l₁ ~ lβ‚‚) (pβ‚‚ : t₁ ~ tβ‚‚) : product l₁ t₁ ~ product lβ‚‚ tβ‚‚ := (p₁.product_right t₁).trans (pβ‚‚.product_left lβ‚‚) end List
.lake/packages/mathlib/Mathlib/Data/List/Perm/Lattice.lean
import Mathlib.Data.List.Forall2 import Mathlib.Data.List.TakeDrop import Mathlib.Data.List.Lattice import Mathlib.Data.List.Nodup /-! # List Permutations and list lattice operations. This file develops theory about the `List.Perm` relation and the lattice structure on lists. -/ -- Make sure we don't import algebra assert_not_exists Monoid open Nat namespace List variable {Ξ± : Type*} open Perm (swap) variable [DecidableEq Ξ±] theorem Perm.bagInter_right {l₁ lβ‚‚ : List Ξ±} (t : List Ξ±) (h : l₁ ~ lβ‚‚) : l₁.bagInter t ~ lβ‚‚.bagInter t := by induction h generalizing t with grind theorem Perm.bagInter_left (l : List Ξ±) {t₁ tβ‚‚ : List Ξ±} (p : t₁ ~ tβ‚‚) : l.bagInter t₁ = l.bagInter tβ‚‚ := by induction l generalizing t₁ tβ‚‚ p with | nil => simp | cons a l IH => ?_ by_cases h : a ∈ t₁ Β· simp [h, p.subset h, IH (p.erase _)] Β· simp [h, mt p.mem_iff.2 h, IH p] theorem Perm.bagInter {l₁ lβ‚‚ t₁ tβ‚‚ : List Ξ±} (hl : l₁ ~ lβ‚‚) (ht : t₁ ~ tβ‚‚) : l₁.bagInter t₁ ~ lβ‚‚.bagInter tβ‚‚ := ht.bagInter_left lβ‚‚ β–Έ hl.bagInter_right _ theorem Perm.inter_append {l t₁ tβ‚‚ : List Ξ±} (h : Disjoint t₁ tβ‚‚) : l ∩ (t₁ ++ tβ‚‚) ~ l ∩ t₁ ++ l ∩ tβ‚‚ := by induction l with | nil => simp | cons x xs l_ih => by_cases h₁ : x ∈ t₁ Β· have hβ‚‚ : x βˆ‰ tβ‚‚ := h h₁ simp [*] by_cases hβ‚‚ : x ∈ tβ‚‚ Β· simp only [*, inter_cons_of_notMem, false_or, mem_append, inter_cons_of_mem, not_false_iff] refine Perm.trans (Perm.cons _ l_ih) ?_ change [x] ++ xs ∩ t₁ ++ xs ∩ tβ‚‚ ~ xs ∩ t₁ ++ ([x] ++ xs ∩ tβ‚‚) rw [← List.append_assoc] solve_by_elim [Perm.append_right, perm_append_comm] Β· simp [*] theorem Perm.take_inter {xs ys : List Ξ±} (n : β„•) (h : xs ~ ys) (h' : ys.Nodup) : xs.take n ~ ys.inter (xs.take n) := by simp only [List.inter] exact Perm.trans (show xs.take n ~ xs.filter (xs.take n).elem by conv_lhs => rw [Nodup.take_eq_filter_mem ((Perm.nodup_iff h).2 h')]) (Perm.filter _ h) theorem Perm.drop_inter {xs ys : List Ξ±} (n : β„•) (h : xs ~ ys) (h' : ys.Nodup) : xs.drop n ~ ys.inter (xs.drop n) := by by_cases h'' : n ≀ xs.length Β· let n' := xs.length - n have hβ‚€ : n = xs.length - n' := by rwa [Nat.sub_sub_self] have h₁ : xs.drop n = (xs.reverse.take n').reverse := by rw [take_reverse, hβ‚€, reverse_reverse] rw [h₁] apply (reverse_perm _).trans rw [inter_reverse] apply Perm.take_inter _ _ h' apply (reverse_perm _).trans; assumption Β· have : xs.drop n = [] := by apply eq_nil_of_length_eq_zero rw [length_drop, Nat.sub_eq_zero_iff_le] apply le_of_not_ge h'' simp [this, List.inter] theorem Perm.dropSlice_inter {xs ys : List Ξ±} (n m : β„•) (h : xs ~ ys) (h' : ys.Nodup) : List.dropSlice n m xs ~ ys ∩ List.dropSlice n m xs := by simp only [dropSlice_eq] have : n ≀ n + m := Nat.le_add_right _ _ have hβ‚‚ := h.nodup_iff.2 h' apply Perm.trans _ (Perm.inter_append _).symm Β· exact Perm.append (Perm.take_inter _ h h') (Perm.drop_inter _ h h') Β· exact disjoint_take_drop hβ‚‚ this end List
.lake/packages/mathlib/Mathlib/Data/Bool/Count.lean
import Mathlib.Algebra.Order.Group.Nat import Mathlib.Algebra.Order.Monoid.NatCast import Mathlib.Algebra.Ring.Parity import Mathlib.Data.List.Chain /-! # List of Booleans In this file we prove lemmas about the number of `false`s and `true`s in a list of Booleans. First we prove that the number of `false`s plus the number of `true` equals the length of the list. Then we prove that in a list with alternating `true`s and `false`s, the number of `true`s differs from the number of `false`s by at most one. We provide several versions of these statements. -/ namespace List @[simp] theorem count_not_add_count (l : List Bool) (b : Bool) : count (!b) l + count b l = length l := by have := length_eq_countP_add_countP (l := l) (Β· == !b) aesop (add simp this) grind_pattern count_not_add_count => count (!b) l @[simp] theorem count_add_count_not (l : List Bool) (b : Bool) : count b l + count (!b) l = length l := by grind @[simp] theorem count_false_add_count_true (l : List Bool) : count false l + count true l = length l := count_not_add_count l true grind_pattern count_false_add_count_true => count false l grind_pattern count_false_add_count_true => count true l @[simp] theorem count_true_add_count_false (l : List Bool) : count true l + count false l = length l := count_not_add_count l false theorem IsChain.count_not_cons : βˆ€ {b : Bool} {l : List Bool}, IsChain (Β· β‰  Β·) (b :: l) β†’ count (!b) l = count b l + length l % 2 | _, [], _h => rfl | b, x :: l, h => by obtain rfl : b = !x := Bool.eq_not_iff.2 (rel_of_isChain_cons_cons h) rw [Bool.not_not, count_cons_self, count_cons_of_ne x.not_ne_self.symm, IsChain.count_not_cons (isChain_cons_of_isChain_cons_cons h), length, add_assoc, Nat.mod_two_add_succ_mod_two] @[deprecated (since := "2025-09-21")] alias Chain.count_not := IsChain.count_not_cons namespace IsChain variable {l : List Bool} theorem count_not_eq_count (hl : IsChain (Β· β‰  Β·) l) (h2 : Even (length l)) (b : Bool) : count (!b) l = count b l := by rcases l with - | ⟨x, l⟩ Β· rfl rw [length_cons, Nat.even_add_one, Nat.not_even_iff] at h2 suffices count (!x) (x :: l) = count x (x :: l) by grind rw [count_cons_of_ne x.not_ne_self.symm, hl.count_not_cons, h2, count_cons_self] theorem count_false_eq_count_true (hl : IsChain (Β· β‰  Β·) l) (h2 : Even (length l)) : count false l = count true l := hl.count_not_eq_count h2 true theorem count_not_le_count_add_one (hl : IsChain (Β· β‰  Β·) l) (b : Bool) : count (!b) l ≀ count b l + 1 := by rcases l with - | ⟨x, l⟩ Β· exact zero_le _ obtain rfl | rfl : b = x ∨ b = !x := by simp only [Bool.eq_not_iff, em] Β· rw [count_cons_of_ne b.not_ne_self.symm, count_cons_self, hl.count_not_cons, add_assoc] cutsat Β· rw [Bool.not_not, count_cons_self, count_cons_of_ne x.not_ne_self.symm, hl.count_not_cons] cutsat theorem count_false_le_count_true_add_one (hl : IsChain (Β· β‰  Β·) l) : count false l ≀ count true l + 1 := hl.count_not_le_count_add_one true theorem count_true_le_count_false_add_one (hl : IsChain (Β· β‰  Β·) l) : count true l ≀ count false l + 1 := hl.count_not_le_count_add_one false theorem two_mul_count_bool_of_even (hl : IsChain (Β· β‰  Β·) l) (h2 : Even (length l)) (b : Bool) : 2 * count b l = length l := by rw [← count_not_add_count l b, hl.count_not_eq_count h2, two_mul] theorem two_mul_count_bool_eq_ite (hl : IsChain (Β· β‰  Β·) l) (b : Bool) : 2 * count b l = if Even (length l) then length l else if Option.some b == l.head? then length l + 1 else length l - 1 := by by_cases h2 : Even (length l) Β· rw [if_pos h2, hl.two_mul_count_bool_of_even h2] Β· rcases l with - | ⟨x, l⟩ Β· exact (h2 .zero).elim simp only [if_neg h2, count_cons, mul_add, head?] rw [length_cons, Nat.even_add_one, not_not] at h2 replace hl : l.IsChain (Β· β‰  Β·) := hl.tail rw [hl.two_mul_count_bool_of_even h2] cases b <;> cases x <;> split_ifs <;> simp <;> contradiction theorem length_sub_one_le_two_mul_count_bool (hl : IsChain (Β· β‰  Β·) l) (b : Bool) : length l - 1 ≀ 2 * count b l := by rw [hl.two_mul_count_bool_eq_ite] split_ifs <;> simp [Nat.le_succ_of_le] theorem length_div_two_le_count_bool (hl : IsChain (Β· β‰  Β·) l) (b : Bool) : length l / 2 ≀ count b l := by rw [Nat.div_le_iff_le_mul_add_pred two_pos, ← tsub_le_iff_right] exact length_sub_one_le_two_mul_count_bool hl b theorem two_mul_count_bool_le_length_add_one (hl : IsChain (Β· β‰  Β·) l) (b : Bool) : 2 * count b l ≀ length l + 1 := by rw [hl.two_mul_count_bool_eq_ite] split_ifs <;> simp [Nat.le_succ_of_le] end IsChain end List
.lake/packages/mathlib/Mathlib/Data/Bool/AllAny.lean
import Batteries.Tactic.Alias import Mathlib.Tactic.TypeStar /-! # Boolean quantifiers This proves a few properties about `List.all` and `List.any`, which are the `Bool` universal and existential quantifiers. Their definitions are in core Lean. -/ variable {Ξ± : Type*} {p : Ξ± β†’ Prop} [DecidablePred p] {l : List Ξ±} {a : Ξ±} namespace List theorem all_iff_forall_prop : (all l fun a => p a) ↔ βˆ€ a ∈ l, p a := by simp theorem any_iff_exists_prop : (any l fun a => p a) ↔ βˆƒ a ∈ l, p a := by simp theorem any_of_mem {p : Ξ± β†’ Bool} (h₁ : a ∈ l) (hβ‚‚ : p a) : any l p := any_eq_true.2 ⟨_, h₁, hβ‚‚βŸ© end List
.lake/packages/mathlib/Mathlib/Data/Bool/Basic.lean
import Mathlib.Logic.Basic import Mathlib.Order.Defs.LinearOrder /-! # Booleans This file proves various trivial lemmas about Booleans and their relation to decidable propositions. ## Tags bool, boolean, Bool, De Morgan -/ namespace Bool section /-! This section contains lemmas about Booleans which were present in core Lean 3. The remainder of this file contains lemmas about Booleans from mathlib 3. -/ theorem true_eq_false_eq_False : Β¬(true = false) := by decide theorem false_eq_true_eq_False : Β¬(false = true) := by decide theorem eq_false_eq_not_eq_true (b : Bool) : (Β¬(b = true)) = (b = false) := by simp theorem eq_true_eq_not_eq_false (b : Bool) : (Β¬(b = false)) = (b = true) := by simp theorem eq_false_of_not_eq_true {b : Bool} : Β¬b = true β†’ b = false := Eq.mp (eq_false_eq_not_eq_true b) theorem eq_true_of_not_eq_false {b : Bool} : Β¬b = false β†’ b = true := Eq.mp (eq_true_eq_not_eq_false b) theorem and_eq_true_eq_eq_true_and_eq_true (a b : Bool) : ((a && b) = true) = (a = true ∧ b = true) := by simp theorem or_eq_true_eq_eq_true_or_eq_true (a b : Bool) : ((a || b) = true) = (a = true ∨ b = true) := by simp theorem not_eq_true_eq_eq_false (a : Bool) : (not a = true) = (a = false) := by grind theorem and_eq_false_eq_eq_false_or_eq_false (a b : Bool) : ((a && b) = false) = (a = false ∨ b = false) := by grind theorem or_eq_false_eq_eq_false_and_eq_false (a b : Bool) : ((a || b) = false) = (a = false ∧ b = false) := by grind theorem not_eq_false_eq_eq_true (a : Bool) : (not a = false) = (a = true) := by grind theorem coe_false : ↑false = False := by simp theorem coe_true : ↑true = True := by simp theorem coe_sort_false : (false : Prop) = False := by simp theorem coe_sort_true : (true : Prop) = True := by simp theorem decide_iff (p : Prop) [d : Decidable p] : decide p = true ↔ p := by simp theorem decide_true {p : Prop} [Decidable p] : p β†’ decide p := (decide_iff p).2 theorem of_decide_true {p : Prop} [Decidable p] : decide p β†’ p := (decide_iff p).1 theorem bool_iff_false {b : Bool} : Β¬b ↔ b = false := by grind theorem bool_eq_false {b : Bool} : Β¬b β†’ b = false := bool_iff_false.1 theorem decide_false_iff (p : Prop) {_ : Decidable p} : decide p = false ↔ Β¬p := bool_iff_false.symm.trans (not_congr (decide_iff _)) theorem decide_false {p : Prop} [Decidable p] : Β¬p β†’ decide p = false := (decide_false_iff p).2 theorem of_decide_false {p : Prop} [Decidable p] : decide p = false β†’ Β¬p := (decide_false_iff p).1 theorem decide_congr {p q : Prop} [Decidable p] [Decidable q] (h : p ↔ q) : decide p = decide q := decide_eq_decide.mpr h theorem coe_xor_iff (a b : Bool) : xor a b ↔ Xor' (a = true) (b = true) := by grind end theorem dichotomy (b : Bool) : b = false ∨ b = true := by grind theorem not_ne_id : not β‰  id := fun h ↦ false_ne_true <| congrFun h true theorem or_inl {a b : Bool} (H : a) : a || b := by simp [H] theorem or_inr {a b : Bool} (H : b) : a || b := by grind theorem and_elim_left : βˆ€ {a b : Bool}, a && b β†’ a := by decide theorem and_intro : βˆ€ {a b : Bool}, a β†’ b β†’ a && b := by decide theorem and_elim_right : βˆ€ {a b : Bool}, a && b β†’ b := by decide lemma eq_not_iff : βˆ€ {a b : Bool}, a = !b ↔ a β‰  b := by decide lemma not_eq_iff : βˆ€ {a b : Bool}, !a = b ↔ a β‰  b := by decide theorem ne_not {a b : Bool} : a β‰  !b ↔ a = b := not_eq_not lemma not_ne_self : βˆ€ b : Bool, (!b) β‰  b := by decide lemma self_ne_not : βˆ€ b : Bool, b β‰  !b := by decide lemma eq_or_eq_not : βˆ€ a b, a = b ∨ a = !b := by decide -- TODO naming issue: these two `not` are different. theorem not_iff_not : βˆ€ {b : Bool}, !b ↔ Β¬b := by simp theorem eq_true_of_not_eq_false' {a : Bool} : !a = false β†’ a = true := by grind theorem eq_false_of_not_eq_true' {a : Bool} : !a = true β†’ a = false := by grind theorem bne_eq_xor : bne = xor := by constructor attribute [simp] xor_assoc theorem xor_iff_ne : βˆ€ {x y : Bool}, xor x y = true ↔ x β‰  y := by decide /-! ### De Morgan's laws for Booleans -/ instance linearOrder : LinearOrder Bool where le_refl := by decide le_trans := by decide le_antisymm := by decide le_total := by decide toDecidableLE := inferInstance toDecidableEq := inferInstance toDecidableLT := inferInstance lt_iff_le_not_ge := by decide max_def := by decide min_def := by decide theorem lt_iff : βˆ€ {x y : Bool}, x < y ↔ x = false ∧ y = true := by decide @[simp] theorem false_lt_true : false < true := lt_iff.2 ⟨rfl, rfl⟩ theorem le_iff_imp : βˆ€ {x y : Bool}, x ≀ y ↔ x β†’ y := by decide theorem and_le_left : βˆ€ x y : Bool, (x && y) ≀ x := by decide theorem and_le_right : βˆ€ x y : Bool, (x && y) ≀ y := by decide theorem le_and : βˆ€ {x y z : Bool}, x ≀ y β†’ x ≀ z β†’ x ≀ (y && z) := by decide theorem left_le_or : βˆ€ x y : Bool, x ≀ (x || y) := by decide theorem right_le_or : βˆ€ x y : Bool, y ≀ (x || y) := by decide theorem or_le : βˆ€ {x y z}, x ≀ z β†’ y ≀ z β†’ (x || y) ≀ z := by decide /-- convert a `β„•` to a `Bool`, `0 -> false`, everything else -> `true` -/ def ofNat (n : Nat) : Bool := decide (n β‰  0) @[simp, grind =] theorem ofNat_zero : ofNat 0 = false := rfl @[simp, grind =] theorem ofNat_add_one {n : Nat} : ofNat (n + 1) = true := rfl @[simp] lemma toNat_beq_zero (b : Bool) : (b.toNat == 0) = !b := by grind @[simp] lemma toNat_bne_zero (b : Bool) : (b.toNat != 0) = b := by simp [bne] @[simp] lemma toNat_beq_one (b : Bool) : (b.toNat == 1) = b := by cases b <;> rfl @[simp] lemma toNat_bne_one (b : Bool) : (b.toNat != 1) = !b := by simp [bne] theorem ofNat_le_ofNat {n m : Nat} (h : n ≀ m) : ofNat n ≀ ofNat m := by simp only [ofNat, ne_eq, _root_.decide_not] cases Nat.decEq n 0 with | isTrue hn => grind [Bool.false_le] | isFalse hn => cases Nat.decEq m 0 with grind [Bool.le_true] theorem toNat_le_toNat {bβ‚€ b₁ : Bool} (h : bβ‚€ ≀ b₁) : toNat bβ‚€ ≀ toNat b₁ := by cases bβ‚€ <;> cases b₁ <;> simp_all +decide theorem ofNat_toNat (b : Bool) : ofNat (toNat b) = b := by grind [cases Bool] @[simp] theorem injective_iff {Ξ± : Sort*} {f : Bool β†’ Ξ±} : Function.Injective f ↔ f false β‰  f true := ⟨fun Hinj Heq ↦ false_ne_true (Hinj Heq), fun H x y ↦ by grind [cases Bool]⟩ /-- **Kaminski's Equation** -/ theorem apply_apply_apply (f : Bool β†’ Bool) (x : Bool) : f (f (f x)) = f x := by cases h₁ : f true <;> cases hβ‚‚ : f false <;> grind [cases Bool] /-- `xor3 x y c` is `((x XOR y) XOR c)`. -/ protected def xor3 (x y c : Bool) := xor (xor x y) c /-- `carry x y c` is `x && y || x && c || y && c`. -/ protected def carry (x y c : Bool) := x && y || x && c || y && c end Bool
.lake/packages/mathlib/Mathlib/Data/Bool/Set.lean
import Mathlib.Data.Set.Insert /-! # Booleans and set operations This file contains three trivial lemmas about `Bool`, `Set.univ`, and `Set.range`. -/ open Set namespace Bool @[simp] theorem univ_eq : (univ : Set Bool) = {false, true} := by grind @[simp, grind =] theorem range_eq {Ξ± : Type*} (f : Bool β†’ Ξ±) : range f = {f false, f true} := by grind [cases Bool] @[simp, grind =] theorem compl_singleton (b : Bool) : ({b}ᢜ : Set Bool) = {!b} := by grind [cases Bool] end Bool
.lake/packages/mathlib/Mathlib/Data/ENNReal/Lemmas.lean
import Mathlib.Algebra.Group.Indicator import Mathlib.Data.ENNReal.Basic import Mathlib.Data.Finset.Lattice.Fold /-! # Some lemmas on extended non-negative reals These are some lemmas split off from `ENNReal.Basic` because they need a lot more imports. They are probably good targets for further cleanup or moves. -/ open Function Set NNReal variable {Ξ± : Type*} namespace ENNReal @[simp, norm_cast] theorem coe_indicator {Ξ±} (s : Set Ξ±) (f : Ξ± β†’ ℝβ‰₯0) (a : Ξ±) : ((s.indicator f a : ℝβ‰₯0) : ℝβ‰₯0∞) = s.indicator (fun x => ↑(f x)) a := (ofNNRealHom : ℝβ‰₯0 β†’+ ℝβ‰₯0∞).map_indicator _ _ _ section Order @[simp, norm_cast] theorem coe_finset_sup {s : Finset Ξ±} {f : Ξ± β†’ ℝβ‰₯0} : ↑(s.sup f) = s.sup fun x => (f x : ℝβ‰₯0∞) := Finset.comp_sup_eq_sup_comp_of_is_total _ coe_mono rfl end Order end ENNReal
.lake/packages/mathlib/Mathlib/Data/ENNReal/Holder.lean
import Mathlib.Data.ENNReal.Inv /-! # HΓΆlder triples This file defines a new class: `ENNReal.HolderTriple` which takes arguments `p q r : ℝβ‰₯0∞`, with `r` marked as a `semiOutParam`, and states that `p⁻¹ + q⁻¹ = r⁻¹`. This is exactly the condition for which **HΓΆlder's inequality** is valid (see `MeasureTheory.MemLp.smul`). This allows us to declare a heterogeneous scalar multiplication (`HSMul`) instance on `MeasureTheory.Lp` spaces. In this file we provide many convenience lemmas in the presence of a `HolderTriple` instance. All these are easily provable from facts about `ℝβ‰₯0∞`, but it's convenient not to be forced to reprove them each time. For convenience we also define `ENNReal.HolderConjugate` (with arguments `p q`) as an abbreviation for `ENNReal.HolderTriple p q 1`. -/ namespace ENNReal /-- A class stating that `p q r : ℝβ‰₯0∞` satisfy `p⁻¹ + q⁻¹ = r⁻¹`. This is exactly the condition for which **HΓΆlder's inequality** is valid (see `MeasureTheory.MemLp.smul`). When `r := 1`, one generally says that `p q` are **HΓΆlder conjugate**. This class exists so that we can define a heterogeneous scalar multiplication on `MeasureTheory.Lp`, and this is why `r` must be marked as a `semiOutParam`. We don't mark it as an `outParam` because this would prevent Lean from using `HolderTriple p q r` and `HolderTriple p q r'` within a single proof, as may be occasionally convenient. -/ @[mk_iff] class HolderTriple (p q : ℝβ‰₯0∞) (r : semiOutParam ℝβ‰₯0∞) : Prop where inv_add_inv_eq_inv (p q r) : p⁻¹ + q⁻¹ = r⁻¹ /-- An abbreviation for `ENNReal.HolderTriple p q 1`, this class states `p⁻¹ + q⁻¹ = 1`. -/ abbrev HolderConjugate (p q : ℝβ‰₯0∞) := HolderTriple p q 1 lemma holderConjugate_iff {p q : ℝβ‰₯0∞} : HolderConjugate p q ↔ p⁻¹ + q⁻¹ = 1 := by simp [holderTriple_iff] /-! ### HΓΆlder triples -/ namespace HolderTriple /-- This is not marked as an instance so that Lean doesn't always find this one and a more canonical value of `r` can be used. -/ lemma of (p q : ℝβ‰₯0∞) : HolderTriple p q (p⁻¹ + q⁻¹)⁻¹ where inv_add_inv_eq_inv := inv_inv _ |>.symm /- This instance causes a trivial loop, but this is exactly the kind of loop that Lean should be able to detect and avoid. -/ instance symm {p q r : ℝβ‰₯0∞} [hpqr : HolderTriple p q r] : HolderTriple q p r where inv_add_inv_eq_inv := add_comm p⁻¹ q⁻¹ β–Έ hpqr.inv_add_inv_eq_inv instance instInfty (p : ℝβ‰₯0∞) : HolderTriple p ∞ p where inv_add_inv_eq_inv := by simp instance instZero (p : ℝβ‰₯0∞) : HolderTriple p 0 0 where inv_add_inv_eq_inv := by simp variable (p q r : ℝβ‰₯0∞) [HolderTriple p q r] lemma inv_eq : r⁻¹ = p⁻¹ + q⁻¹ := (inv_add_inv_eq_inv ..).symm lemma unique (r' : ℝβ‰₯0∞) [hr' : HolderTriple p q r'] : r = r' := by rw [← inv_inj, inv_eq p q r, inv_eq p q r'] lemma one_div_add_one_div : 1 / p + 1 / q = 1 / r := by simpa using inv_add_inv_eq_inv .. lemma one_div_eq : 1 / r = 1 / p + 1 / q := one_div_add_one_div p q r |>.symm lemma inv_inv_add_inv : (p⁻¹ + q⁻¹)⁻¹ = r := by simp [inv_add_inv_eq_inv p q r] include q in lemma le : r ≀ p := by simp [← ENNReal.inv_le_inv, ← @inv_inv_add_inv p q r, inv_inv] include q in protected lemma inv_le_inv : p⁻¹ ≀ r⁻¹ := by simp [ENNReal.inv_le_inv, le p q r] variable {r} in lemma inv_sub_inv_eq_inv (hr : r β‰  0) : r⁻¹ - q⁻¹ = p⁻¹ := by apply ENNReal.sub_eq_of_eq_add (ne_of_lt ?_) (inv_eq p q r) calc q⁻¹ ≀ r⁻¹ := HolderTriple.inv_le_inv q p r _ < ∞ := by simpa using pos_iff_ne_zero.mpr hr /-- assumes `q β‰  0` instead of `r β‰  0`. -/ lemma inv_sub_inv_eq_inv' (hq : q β‰  0) : r⁻¹ - q⁻¹ = p⁻¹ := by obtain (rfl | hr) := eq_zero_or_pos r Β· suffices p = 0 by simpa [this] by_contra! hp have := calc 0⁻¹ = p⁻¹ + q⁻¹ := inv_eq p q 0 _ < ⊀ + ⊀ := by simp [hp, hq, pos_iff_ne_zero] _ = ⊀ := by simp simp_all Β· exact inv_sub_inv_eq_inv p q hr.ne' variable {r} in lemma unique_of_ne_zero (q' : ℝβ‰₯0∞) (hr : r β‰  0) [HolderTriple p q' r] : q = q' := by rw [← inv_inj, ← inv_sub_inv_eq_inv q p hr, ← inv_sub_inv_eq_inv q' p hr] lemma holderConjugate_div_div (hrβ‚€ : r β‰  0) (hr : r β‰  ∞) : HolderConjugate (p / r) (q / r) where inv_add_inv_eq_inv := by rw [ENNReal.inv_div (.inl hr) (.inl hrβ‚€), ENNReal.inv_div (.inl hr) (.inl hrβ‚€), div_eq_mul_inv, div_eq_mul_inv, ← mul_add, inv_add_inv_eq_inv p q r, ENNReal.mul_inv_cancel hrβ‚€ hr, inv_one] end HolderTriple /-! ### HΓΆlder conjugates -/ namespace HolderConjugate /- This instance causes a trivial loop, but this is exactly the kind of loop that Lean should be able to detect and avoid. -/ instance symm {p q : ℝβ‰₯0∞} [hpq : HolderConjugate p q] : HolderConjugate q p := inferInstance instance instTwoTwo : HolderConjugate 2 2 where inv_add_inv_eq_inv := by rw [← two_mul, ENNReal.mul_inv_cancel] all_goals norm_num -- I'm not sure this is necessary, but maybe it's nice to have around given the `abbrev`. instance instOneInfty : HolderConjugate 1 ∞ := inferInstance variable (p q : ℝβ‰₯0∞) [HolderConjugate p q] include q in lemma one_le : 1 ≀ p := HolderTriple.le p q 1 include q in lemma pos : 0 < p := zero_lt_one.trans_le (one_le p q) include q in lemma ne_zero : p β‰  0 := pos p q |>.ne' lemma inv_add_inv_eq_one : p⁻¹ + q⁻¹ = 1 := @inv_one ℝβ‰₯0∞ _ β–Έ HolderTriple.inv_add_inv_eq_inv p q 1 lemma one_sub_inv : 1 - p⁻¹ = q⁻¹ := @inv_one ℝβ‰₯0∞ _ β–Έ HolderTriple.inv_sub_inv_eq_inv q p one_ne_zero lemma unique (q' : ℝβ‰₯0∞) [hq' : HolderConjugate p q'] : q = q' := HolderTriple.unique_of_ne_zero p q q' one_ne_zero lemma eq_top_iff_eq_one : p = ∞ ↔ q = 1 := by constructor Β· rintro rfl rw [← inv_inv q, ← one_sub_inv ∞ q] simp Β· rintro rfl rw [← inv_inv p, ← one_sub_inv 1 p] simp lemma ne_top_iff_ne_one : p β‰  ∞ ↔ q β‰  1 := by rw [not_iff_not, eq_top_iff_eq_one p q] lemma lt_top_iff_one_lt : p < ∞ ↔ 1 < q := by rw [lt_top_iff_ne_top, ne_top_iff_ne_one _ q, ne_comm, lt_iff_le_and_ne] simp [one_le q p] lemma sub_one_mul_inv (hp : p β‰  ⊀) : (p - 1) * p⁻¹ = q⁻¹ := by have := pos p q |>.ne' rw [ENNReal.sub_mul (by simp_all), ENNReal.mul_inv_cancel this (by cutsat)] simp [one_sub_inv p q] end HolderConjugate end ENNReal
.lake/packages/mathlib/Mathlib/Data/ENNReal/Order.lean
import Mathlib.Data.ENNReal.Operations deprecated_module (since := "2025-04-13")
.lake/packages/mathlib/Mathlib/Data/ENNReal/Basic.lean
import Mathlib.Algebra.Order.Ring.WithTop import Mathlib.Algebra.Order.Sub.WithTop import Mathlib.Data.NNReal.Defs import Mathlib.Order.Interval.Set.WithBotTop import Mathlib.Tactic.Finiteness /-! # Extended non-negative reals We define `ENNReal = ℝβ‰₯0∞ := WithTop ℝβ‰₯0` to be the type of extended nonnegative real numbers, i.e., the interval `[0, +∞]`. This type is used as the codomain of a `MeasureTheory.Measure`, and of the extended distance `edist` in an `EMetricSpace`. In this file we set up many of the instances on `ℝβ‰₯0∞`, and provide relationships between `ℝβ‰₯0∞` and `ℝβ‰₯0`, and between `ℝβ‰₯0∞` and `ℝ`. In particular, we provide a coercion from `ℝβ‰₯0` to `ℝβ‰₯0∞` as well as functions `ENNReal.toNNReal`, `ENNReal.ofReal` and `ENNReal.toReal`, all of which take the value zero wherever they cannot be the identity. Also included is the relationship between `ℝβ‰₯0∞` and `β„•`. The interaction of these functions, especially `ENNReal.ofReal` and `ENNReal.toReal`, with the algebraic and lattice structure can be found in `Data.ENNReal.Real`. This file proves many of the order properties of `ℝβ‰₯0∞`, with the exception of the ways those relate to the algebraic structure, which are included in `Data.ENNReal.Operations`. This file also defines inversion and division: this includes `Inv` and `Div` instances on `ℝβ‰₯0∞` making it into a `DivInvOneMonoid`. As a consequence of being a `DivInvOneMonoid`, `ℝβ‰₯0∞` inherits a power operation with integer exponent: this and other properties is shown in `Data.ENNReal.Inv`. ## Main definitions * `ℝβ‰₯0∞`: the extended nonnegative real numbers `[0, ∞]`; defined as `WithTop ℝβ‰₯0`; it is equipped with the following structures: - coercion from `ℝβ‰₯0` defined in the natural way; - the natural structure of a complete dense linear order: `↑p ≀ ↑q ↔ p ≀ q` and `βˆ€ a, a ≀ ∞`; - `a + b` is defined so that `↑p + ↑q = ↑(p + q)` for `(p q : ℝβ‰₯0)` and `a + ∞ = ∞ + a = ∞`; - `a * b` is defined so that `↑p * ↑q = ↑(p * q)` for `(p q : ℝβ‰₯0)`, `0 * ∞ = ∞ * 0 = 0`, and `a * ∞ = ∞ * a = ∞` for `a β‰  0`; - `a - b` is defined as the minimal `d` such that `a ≀ d + b`; this way we have `↑p - ↑q = ↑(p - q)`, `∞ - ↑p = ∞`, `↑p - ∞ = ∞ - ∞ = 0`; note that there is no negation, only subtraction; The addition and multiplication defined this way together with `0 = ↑0` and `1 = ↑1` turn `ℝβ‰₯0∞` into a canonically ordered commutative semiring of characteristic zero. - `a⁻¹` is defined as `Inf {b | 1 ≀ a * b}`. This way we have `(↑p)⁻¹ = ↑(p⁻¹)` for `p : ℝβ‰₯0`, `p β‰  0`, `0⁻¹ = ∞`, and `∞⁻¹ = 0`. - `a / b` is defined as `a * b⁻¹`. This inversion and division include `Inv` and `Div` instances on `ℝβ‰₯0∞`, making it into a `DivInvOneMonoid`. Further properties of these are shown in `Data.ENNReal.Inv`. * Coercions to/from other types: - coercion `ℝβ‰₯0 β†’ ℝβ‰₯0∞` is defined as `Coe`, so one can use `(p : ℝβ‰₯0)` in a context that expects `a : ℝβ‰₯0∞`, and Lean will apply `coe` automatically; - `ENNReal.toNNReal` sends `↑p` to `p` and `∞` to `0`; - `ENNReal.toReal := coe ∘ ENNReal.toNNReal` sends `↑p`, `p : ℝβ‰₯0` to `(↑p : ℝ)` and `∞` to `0`; - `ENNReal.ofReal := coe ∘ Real.toNNReal` sends `x : ℝ` to `β†‘βŸ¨max x 0, _⟩` - `ENNReal.neTopEquivNNReal` is an equivalence between `{a : ℝβ‰₯0∞ // a β‰  0}` and `ℝβ‰₯0`. ## Implementation notes We define a `CanLift ℝβ‰₯0∞ ℝβ‰₯0` instance, so one of the ways to prove theorems about an `ℝβ‰₯0∞` number `a` is to consider the cases `a = ∞` and `a β‰  ∞`, and use the tactic `lift a to ℝβ‰₯0 using ha` in the second case. This instance is even more useful if one already has `ha : a β‰  ∞` in the context, or if we have `(f : Ξ± β†’ ℝβ‰₯0∞) (hf : βˆ€ x, f x β‰  ∞)`. ## Notation * `ℝβ‰₯0∞`: the type of the extended nonnegative real numbers; * `ℝβ‰₯0`: the type of nonnegative real numbers `[0, ∞)`; defined in `Data.Real.NNReal`; * `∞`: a localized notation in `ENNReal` for `⊀ : ℝβ‰₯0∞`. -/ assert_not_exists Finset open Function Set NNReal variable {Ξ± : Type*} /-- The extended nonnegative real numbers. This is usually denoted [0, ∞], and is relevant as the codomain of a measure. -/ def ENNReal := WithTop ℝβ‰₯0 deriving Zero, Top, AddCommMonoidWithOne, SemilatticeSup, DistribLattice, Nontrivial @[inherit_doc] scoped[ENNReal] notation "ℝβ‰₯0∞" => ENNReal /-- Notation for infinity as an `ENNReal` number. -/ scoped[ENNReal] notation "∞" => (⊀ : ENNReal) namespace ENNReal instance : OrderBot ℝβ‰₯0∞ := inferInstanceAs (OrderBot (WithTop ℝβ‰₯0)) instance : OrderTop ℝβ‰₯0∞ := inferInstanceAs (OrderTop (WithTop ℝβ‰₯0)) instance : BoundedOrder ℝβ‰₯0∞ := inferInstanceAs (BoundedOrder (WithTop ℝβ‰₯0)) instance : CharZero ℝβ‰₯0∞ := inferInstanceAs (CharZero (WithTop ℝβ‰₯0)) instance : Min ℝβ‰₯0∞ := SemilatticeInf.toMin instance : Max ℝβ‰₯0∞ := SemilatticeSup.toMax noncomputable instance : CommSemiring ℝβ‰₯0∞ := inferInstanceAs (CommSemiring (WithTop ℝβ‰₯0)) instance : PartialOrder ℝβ‰₯0∞ := inferInstanceAs (PartialOrder (WithTop ℝβ‰₯0)) instance : IsOrderedRing ℝβ‰₯0∞ := inferInstanceAs (IsOrderedRing (WithTop ℝβ‰₯0)) instance : CanonicallyOrderedAdd ℝβ‰₯0∞ := inferInstanceAs (CanonicallyOrderedAdd (WithTop ℝβ‰₯0)) instance : NoZeroDivisors ℝβ‰₯0∞ := inferInstanceAs (NoZeroDivisors (WithTop ℝβ‰₯0)) noncomputable instance : CompleteLinearOrder ℝβ‰₯0∞ := inferInstanceAs (CompleteLinearOrder (WithTop ℝβ‰₯0)) instance : DenselyOrdered ℝβ‰₯0∞ := inferInstanceAs (DenselyOrdered (WithTop ℝβ‰₯0)) instance : AddCommMonoid ℝβ‰₯0∞ := inferInstanceAs (AddCommMonoid (WithTop ℝβ‰₯0)) noncomputable instance : LinearOrder ℝβ‰₯0∞ := inferInstanceAs (LinearOrder (WithTop ℝβ‰₯0)) instance : IsOrderedAddMonoid ℝβ‰₯0∞ := inferInstanceAs (IsOrderedAddMonoid (WithTop ℝβ‰₯0)) instance instSub : Sub ℝβ‰₯0∞ := inferInstanceAs (Sub (WithTop ℝβ‰₯0)) instance : OrderedSub ℝβ‰₯0∞ := inferInstanceAs (OrderedSub (WithTop ℝβ‰₯0)) noncomputable instance : LinearOrderedAddCommMonoidWithTop ℝβ‰₯0∞ := inferInstanceAs (LinearOrderedAddCommMonoidWithTop (WithTop ℝβ‰₯0)) -- RFC: redefine using pattern matching? noncomputable instance : Inv ℝβ‰₯0∞ := ⟨fun a => sInf { b | 1 ≀ a * b }⟩ noncomputable instance : DivInvMonoid ℝβ‰₯0∞ where variable {a b c d : ℝβ‰₯0∞} {r p q : ℝβ‰₯0} {n : β„•} -- TODO: add a `WithTop` instance and use it here noncomputable instance : LinearOrderedCommMonoidWithZero ℝβ‰₯0∞ := { inferInstanceAs (LinearOrderedAddCommMonoidWithTop ℝβ‰₯0∞), inferInstanceAs (CommSemiring ℝβ‰₯0∞) with bot_le _ := bot_le mul_le_mul_left := fun _ _ => mul_le_mul_left' zero_le_one := zero_le 1 } instance : Unique (AddUnits ℝβ‰₯0∞) where default := 0 uniq a := AddUnits.ext <| le_zero_iff.1 <| by rw [← a.add_neg]; exact le_self_add instance : Inhabited ℝβ‰₯0∞ := ⟨0⟩ /-- Coercion from `ℝβ‰₯0` to `ℝβ‰₯0∞`. -/ @[coe, match_pattern] def ofNNReal : ℝβ‰₯0 β†’ ℝβ‰₯0∞ := WithTop.some instance : Coe ℝβ‰₯0 ℝβ‰₯0∞ := ⟨ofNNReal⟩ /-- A version of `WithTop.recTopCoe` that uses `ENNReal.ofNNReal`. -/ @[elab_as_elim, induction_eliminator, cases_eliminator] def recTopCoe {C : ℝβ‰₯0∞ β†’ Sort*} (top : C ∞) (coe : βˆ€ x : ℝβ‰₯0, C x) (x : ℝβ‰₯0∞) : C x := WithTop.recTopCoe top coe x instance canLift : CanLift ℝβ‰₯0∞ ℝβ‰₯0 ofNNReal (Β· β‰  ∞) := WithTop.canLift @[simp] theorem none_eq_top : (none : ℝβ‰₯0∞) = ∞ := rfl @[simp] theorem some_eq_coe (a : ℝβ‰₯0) : (Option.some a : ℝβ‰₯0∞) = (↑a : ℝβ‰₯0∞) := rfl @[simp] theorem some_eq_coe' (a : ℝβ‰₯0) : (WithTop.some a : ℝβ‰₯0∞) = (↑a : ℝβ‰₯0∞) := rfl lemma coe_injective : Injective ((↑) : ℝβ‰₯0 β†’ ℝβ‰₯0∞) := WithTop.coe_injective @[simp, norm_cast] lemma coe_inj : (p : ℝβ‰₯0∞) = q ↔ p = q := coe_injective.eq_iff lemma coe_ne_coe : (p : ℝβ‰₯0∞) β‰  q ↔ p β‰  q := coe_inj.not theorem range_coe' : range ofNNReal = Iio ∞ := WithTop.range_coe theorem range_coe : range ofNNReal = {∞}ᢜ := (isCompl_range_some_none ℝβ‰₯0).symm.compl_eq.symm instance : NNRatCast ℝβ‰₯0∞ where nnratCast r := ofNNReal r @[norm_cast] theorem coe_nnratCast (q : β„šβ‰₯0) : ↑(q : ℝβ‰₯0) = (q : ℝβ‰₯0∞) := rfl /-- `toNNReal x` returns `x` if it is real, otherwise 0. -/ protected def toNNReal : ℝβ‰₯0∞ β†’ ℝβ‰₯0 := WithTop.untopD 0 /-- `toReal x` returns `x` if it is real, `0` otherwise. -/ protected def toReal (a : ℝβ‰₯0∞) : Real := a.toNNReal /-- `ofReal x` returns `x` if it is nonnegative, `0` otherwise. -/ protected def ofReal (r : Real) : ℝβ‰₯0∞ := r.toNNReal @[simp, norm_cast] lemma toNNReal_coe (r : ℝβ‰₯0) : (r : ℝβ‰₯0∞).toNNReal = r := rfl @[simp] theorem coe_toNNReal : βˆ€ {a : ℝβ‰₯0∞}, a β‰  ∞ β†’ ↑a.toNNReal = a | ofNNReal _, _ => rfl | ⊀, h => (h rfl).elim @[simp] theorem coe_comp_toNNReal_comp {ΞΉ : Type*} {f : ΞΉ β†’ ℝβ‰₯0∞} (hf : βˆ€ x, f x β‰  ∞) : (fun (x : ℝβ‰₯0) => (x : ℝβ‰₯0∞)) ∘ ENNReal.toNNReal ∘ f = f := by ext x simp [coe_toNNReal (hf x)] @[simp] theorem ofReal_toReal {a : ℝβ‰₯0∞} (h : a β‰  ∞) : ENNReal.ofReal a.toReal = a := by simp [ENNReal.toReal, ENNReal.ofReal, h] @[simp] theorem toReal_ofReal {r : ℝ} (h : 0 ≀ r) : (ENNReal.ofReal r).toReal = r := max_eq_left h theorem toReal_ofReal' {r : ℝ} : (ENNReal.ofReal r).toReal = max r 0 := rfl theorem coe_toNNReal_le_self : βˆ€ {a : ℝβ‰₯0∞}, ↑a.toNNReal ≀ a | ofNNReal r => by rw [toNNReal_coe] | ⊀ => le_top theorem coe_nnreal_eq (r : ℝβ‰₯0) : (r : ℝβ‰₯0∞) = ENNReal.ofReal r := by rw [ENNReal.ofReal, Real.toNNReal_coe] theorem ofReal_eq_coe_nnreal {x : ℝ} (h : 0 ≀ x) : ENNReal.ofReal x = ofNNReal ⟨x, h⟩ := (coe_nnreal_eq ⟨x, h⟩).symm theorem ofNNReal_toNNReal (x : ℝ) : (Real.toNNReal x : ℝβ‰₯0∞) = ENNReal.ofReal x := rfl @[simp] theorem ofReal_coe_nnreal : ENNReal.ofReal p = p := (coe_nnreal_eq p).symm @[simp, norm_cast] theorem coe_zero : ↑(0 : ℝβ‰₯0) = (0 : ℝβ‰₯0∞) := rfl @[simp, norm_cast] theorem coe_one : ↑(1 : ℝβ‰₯0) = (1 : ℝβ‰₯0∞) := rfl @[simp] theorem toReal_nonneg {a : ℝβ‰₯0∞} : 0 ≀ a.toReal := a.toNNReal.2 @[norm_cast] theorem coe_toNNReal_eq_toReal (z : ℝβ‰₯0∞) : (z.toNNReal : ℝ) = z.toReal := rfl @[simp] theorem toNNReal_toReal_eq (z : ℝβ‰₯0∞) : z.toReal.toNNReal = z.toNNReal := by ext; simp [coe_toNNReal_eq_toReal] @[simp] theorem toNNReal_top : ∞.toNNReal = 0 := rfl @[simp] theorem toReal_top : ∞.toReal = 0 := rfl @[simp] theorem toReal_one : (1 : ℝβ‰₯0∞).toReal = 1 := rfl @[simp] theorem toNNReal_one : (1 : ℝβ‰₯0∞).toNNReal = 1 := rfl @[simp] theorem coe_toReal (r : ℝβ‰₯0) : (r : ℝβ‰₯0∞).toReal = r := rfl @[simp] theorem toNNReal_zero : (0 : ℝβ‰₯0∞).toNNReal = 0 := rfl @[simp] theorem toReal_zero : (0 : ℝβ‰₯0∞).toReal = 0 := rfl @[simp] theorem ofReal_zero : ENNReal.ofReal (0 : ℝ) = 0 := by simp [ENNReal.ofReal] @[simp] theorem ofReal_one : ENNReal.ofReal (1 : ℝ) = (1 : ℝβ‰₯0∞) := by simp [ENNReal.ofReal] theorem ofReal_toReal_le {a : ℝβ‰₯0∞} : ENNReal.ofReal a.toReal ≀ a := if ha : a = ∞ then ha.symm β–Έ le_top else le_of_eq (ofReal_toReal ha) theorem forall_ennreal {p : ℝβ‰₯0∞ β†’ Prop} : (βˆ€ a, p a) ↔ (βˆ€ r : ℝβ‰₯0, p r) ∧ p ∞ := WithTop.forall.trans and_comm theorem forall_ne_top {p : ℝβ‰₯0∞ β†’ Prop} : (βˆ€ x β‰  ∞, p x) ↔ βˆ€ x : ℝβ‰₯0, p x := WithTop.forall_ne_top theorem exists_ne_top {p : ℝβ‰₯0∞ β†’ Prop} : (βˆƒ x β‰  ∞, p x) ↔ βˆƒ x : ℝβ‰₯0, p x := WithTop.exists_ne_top theorem toNNReal_eq_zero_iff (x : ℝβ‰₯0∞) : x.toNNReal = 0 ↔ x = 0 ∨ x = ∞ := WithTop.untopD_eq_self_iff theorem toReal_eq_zero_iff (x : ℝβ‰₯0∞) : x.toReal = 0 ↔ x = 0 ∨ x = ∞ := by simp [ENNReal.toReal, toNNReal_eq_zero_iff] theorem toNNReal_ne_zero : a.toNNReal β‰  0 ↔ a β‰  0 ∧ a β‰  ∞ := a.toNNReal_eq_zero_iff.not.trans not_or theorem toReal_ne_zero : a.toReal β‰  0 ↔ a β‰  0 ∧ a β‰  ∞ := a.toReal_eq_zero_iff.not.trans not_or theorem toNNReal_eq_one_iff (x : ℝβ‰₯0∞) : x.toNNReal = 1 ↔ x = 1 := WithTop.untopD_eq_iff.trans <| by simp theorem toReal_eq_one_iff (x : ℝβ‰₯0∞) : x.toReal = 1 ↔ x = 1 := by rw [ENNReal.toReal, NNReal.coe_eq_one, ENNReal.toNNReal_eq_one_iff] theorem toNNReal_ne_one : a.toNNReal β‰  1 ↔ a β‰  1 := a.toNNReal_eq_one_iff.not theorem toReal_ne_one : a.toReal β‰  1 ↔ a β‰  1 := a.toReal_eq_one_iff.not @[simp, aesop (rule_sets := [finiteness]) safe apply] theorem coe_ne_top : (r : ℝβ‰₯0∞) β‰  ∞ := WithTop.coe_ne_top @[simp] theorem top_ne_coe : ∞ β‰  (r : ℝβ‰₯0∞) := WithTop.top_ne_coe @[simp] theorem coe_lt_top : (r : ℝβ‰₯0∞) < ∞ := WithTop.coe_lt_top r @[simp, aesop (rule_sets := [finiteness]) safe apply] theorem ofReal_ne_top {r : ℝ} : ENNReal.ofReal r β‰  ∞ := coe_ne_top @[simp] theorem ofReal_lt_top {r : ℝ} : ENNReal.ofReal r < ∞ := coe_lt_top @[simp] theorem top_ne_ofReal {r : ℝ} : ∞ β‰  ENNReal.ofReal r := top_ne_coe @[simp] theorem ofReal_toReal_eq_iff : ENNReal.ofReal a.toReal = a ↔ a β‰  ⊀ := ⟨fun h => by rw [← h] exact ofReal_ne_top, ofReal_toReal⟩ @[simp] theorem toReal_ofReal_eq_iff {a : ℝ} : (ENNReal.ofReal a).toReal = a ↔ 0 ≀ a := ⟨fun h => by rw [← h] exact toReal_nonneg, toReal_ofReal⟩ @[simp, aesop (rule_sets := [finiteness]) safe apply] theorem zero_ne_top : 0 β‰  ∞ := coe_ne_top @[simp] theorem top_ne_zero : ∞ β‰  0 := top_ne_coe @[simp, aesop (rule_sets := [finiteness]) safe apply] theorem one_ne_top : 1 β‰  ∞ := coe_ne_top @[simp] theorem top_ne_one : ∞ β‰  1 := top_ne_coe @[simp] theorem zero_lt_top : 0 < ∞ := coe_lt_top @[simp, norm_cast] theorem coe_le_coe : (↑r : ℝβ‰₯0∞) ≀ ↑q ↔ r ≀ q := WithTop.coe_le_coe @[simp, norm_cast] theorem coe_lt_coe : (↑r : ℝβ‰₯0∞) < ↑q ↔ r < q := WithTop.coe_lt_coe -- Needed until `@[gcongr]` accepts iff statements alias ⟨_, coe_le_coe_of_le⟩ := coe_le_coe attribute [gcongr] ENNReal.coe_le_coe_of_le -- Needed until `@[gcongr]` accepts iff statements alias ⟨_, coe_lt_coe_of_lt⟩ := coe_lt_coe attribute [gcongr] ENNReal.coe_lt_coe_of_lt theorem coe_mono : Monotone ofNNReal := fun _ _ => coe_le_coe.2 theorem coe_strictMono : StrictMono ofNNReal := fun _ _ => coe_lt_coe.2 @[simp, norm_cast] theorem coe_eq_zero : (↑r : ℝβ‰₯0∞) = 0 ↔ r = 0 := coe_inj @[simp, norm_cast] theorem zero_eq_coe : 0 = (↑r : ℝβ‰₯0∞) ↔ 0 = r := coe_inj @[simp, norm_cast] theorem coe_eq_one : (↑r : ℝβ‰₯0∞) = 1 ↔ r = 1 := coe_inj @[simp, norm_cast] theorem one_eq_coe : 1 = (↑r : ℝβ‰₯0∞) ↔ 1 = r := coe_inj @[simp, norm_cast] theorem coe_pos : 0 < (r : ℝβ‰₯0∞) ↔ 0 < r := coe_lt_coe theorem coe_ne_zero : (r : ℝβ‰₯0∞) β‰  0 ↔ r β‰  0 := WithTop.coe_ne_zero lemma coe_ne_one : (r : ℝβ‰₯0∞) β‰  1 ↔ r β‰  1 := WithTop.coe_ne_one @[simp, norm_cast] lemma coe_add (x y : ℝβ‰₯0) : (↑(x + y) : ℝβ‰₯0∞) = x + y := rfl @[simp, norm_cast] lemma coe_mul (x y : ℝβ‰₯0) : (↑(x * y) : ℝβ‰₯0∞) = x * y := rfl @[norm_cast] lemma coe_nsmul (n : β„•) (x : ℝβ‰₯0) : (↑(n β€’ x) : ℝβ‰₯0∞) = n β€’ x := rfl @[simp, norm_cast] lemma coe_pow (x : ℝβ‰₯0) (n : β„•) : (↑(x ^ n) : ℝβ‰₯0∞) = x ^ n := rfl @[simp, norm_cast] theorem coe_ofNat (n : β„•) [n.AtLeastTwo] : ((ofNat(n) : ℝβ‰₯0) : ℝβ‰₯0∞) = ofNat(n) := rfl -- TODO: add lemmas about `OfNat.ofNat` and `<`/`≀` theorem coe_two : ((2 : ℝβ‰₯0) : ℝβ‰₯0∞) = 2 := rfl theorem toNNReal_eq_toNNReal_iff (x y : ℝβ‰₯0∞) : x.toNNReal = y.toNNReal ↔ x = y ∨ x = 0 ∧ y = ⊀ ∨ x = ⊀ ∧ y = 0 := WithTop.untopD_eq_untopD_iff theorem toReal_eq_toReal_iff (x y : ℝβ‰₯0∞) : x.toReal = y.toReal ↔ x = y ∨ x = 0 ∧ y = ⊀ ∨ x = ⊀ ∧ y = 0 := by simp only [ENNReal.toReal, NNReal.coe_inj, toNNReal_eq_toNNReal_iff] theorem toNNReal_eq_toNNReal_iff' {x y : ℝβ‰₯0∞} (hx : x β‰  ⊀) (hy : y β‰  ⊀) : x.toNNReal = y.toNNReal ↔ x = y := by simp only [ENNReal.toNNReal_eq_toNNReal_iff x y, hx, hy, and_false, false_and, or_false] theorem toReal_eq_toReal_iff' {x y : ℝβ‰₯0∞} (hx : x β‰  ⊀) (hy : y β‰  ⊀) : x.toReal = y.toReal ↔ x = y := by simp only [ENNReal.toReal, NNReal.coe_inj, toNNReal_eq_toNNReal_iff' hx hy] theorem one_lt_two : (1 : ℝβ‰₯0∞) < 2 := Nat.one_lt_ofNat /-- `(1 : ℝβ‰₯0∞) ≀ 1`, recorded as a `Fact` for use with `Lp` spaces. -/ instance _root_.fact_one_le_one_ennreal : Fact ((1 : ℝβ‰₯0∞) ≀ 1) := ⟨le_rfl⟩ /-- `(1 : ℝβ‰₯0∞) ≀ 2`, recorded as a `Fact` for use with `Lp` spaces. -/ instance _root_.fact_one_le_two_ennreal : Fact ((1 : ℝβ‰₯0∞) ≀ 2) := ⟨one_le_two⟩ /-- `(1 : ℝβ‰₯0∞) ≀ ∞`, recorded as a `Fact` for use with `Lp` spaces. -/ instance _root_.fact_one_le_top_ennreal : Fact ((1 : ℝβ‰₯0∞) ≀ ∞) := ⟨le_top⟩ /-- The set of numbers in `ℝβ‰₯0∞` that are not equal to `∞` is equivalent to `ℝβ‰₯0`. -/ def neTopEquivNNReal : { a | a β‰  ∞ } ≃ ℝβ‰₯0 where toFun x := ENNReal.toNNReal x invFun x := ⟨x, coe_ne_top⟩ left_inv := fun x => Subtype.eq <| coe_toNNReal x.2 right_inv := toNNReal_coe theorem cinfi_ne_top [InfSet Ξ±] (f : ℝβ‰₯0∞ β†’ Ξ±) : β¨… x : { x // x β‰  ∞ }, f x = β¨… x : ℝβ‰₯0, f x := Eq.symm <| neTopEquivNNReal.symm.surjective.iInf_congr _ fun _ => rfl theorem iInf_ne_top [CompleteLattice Ξ±] (f : ℝβ‰₯0∞ β†’ Ξ±) : β¨… (x) (_ : x β‰  ∞), f x = β¨… x : ℝβ‰₯0, f x := by rw [iInf_subtype', cinfi_ne_top] theorem csupr_ne_top [SupSet Ξ±] (f : ℝβ‰₯0∞ β†’ Ξ±) : ⨆ x : { x // x β‰  ∞ }, f x = ⨆ x : ℝβ‰₯0, f x := @cinfi_ne_top Ξ±α΅’α΅ˆ _ _ theorem iSup_ne_top [CompleteLattice Ξ±] (f : ℝβ‰₯0∞ β†’ Ξ±) : ⨆ (x) (_ : x β‰  ∞), f x = ⨆ x : ℝβ‰₯0, f x := @iInf_ne_top Ξ±α΅’α΅ˆ _ _ theorem iInf_ennreal {Ξ± : Type*} [CompleteLattice Ξ±] {f : ℝβ‰₯0∞ β†’ Ξ±} : β¨… n, f n = (β¨… n : ℝβ‰₯0, f n) βŠ“ f ∞ := (iInf_option f).trans (inf_comm _ _) theorem iSup_ennreal {Ξ± : Type*} [CompleteLattice Ξ±] {f : ℝβ‰₯0∞ β†’ Ξ±} : ⨆ n, f n = (⨆ n : ℝβ‰₯0, f n) βŠ” f ∞ := @iInf_ennreal Ξ±α΅’α΅ˆ _ _ /-- Coercion `ℝβ‰₯0 β†’ ℝβ‰₯0∞` as a `RingHom`. -/ def ofNNRealHom : ℝβ‰₯0 β†’+* ℝβ‰₯0∞ where toFun := WithTop.some map_one' := coe_one map_mul' _ _ := coe_mul _ _ map_zero' := coe_zero map_add' _ _ := coe_add _ _ @[simp] theorem coe_ofNNRealHom : ⇑ofNNRealHom = WithTop.some := rfl section Order theorem bot_eq_zero : (βŠ₯ : ℝβ‰₯0∞) = 0 := rfl -- `coe_lt_top` moved up theorem not_top_le_coe : ° ≀ ↑r := WithTop.not_top_le_coe r @[simp, norm_cast] theorem one_le_coe_iff : (1 : ℝβ‰₯0∞) ≀ ↑r ↔ 1 ≀ r := coe_le_coe @[simp, norm_cast] theorem coe_le_one_iff : ↑r ≀ (1 : ℝβ‰₯0∞) ↔ r ≀ 1 := coe_le_coe @[simp, norm_cast] theorem coe_lt_one_iff : (↑p : ℝβ‰₯0∞) < 1 ↔ p < 1 := coe_lt_coe @[simp, norm_cast] theorem one_lt_coe_iff : 1 < (↑p : ℝβ‰₯0∞) ↔ 1 < p := coe_lt_coe @[simp, norm_cast] theorem coe_natCast (n : β„•) : ((n : ℝβ‰₯0) : ℝβ‰₯0∞) = n := rfl @[simp, norm_cast] lemma ofReal_natCast (n : β„•) : ENNReal.ofReal n = n := by simp [ENNReal.ofReal] @[simp] theorem ofReal_ofNat (n : β„•) [n.AtLeastTwo] : ENNReal.ofReal ofNat(n) = ofNat(n) := ofReal_natCast n @[simp, aesop (rule_sets := [finiteness]) safe apply] theorem natCast_ne_top (n : β„•) : (n : ℝβ‰₯0∞) β‰  ∞ := WithTop.natCast_ne_top n @[simp] theorem natCast_lt_top (n : β„•) : (n : ℝβ‰₯0∞) < ∞ := WithTop.natCast_lt_top n @[simp, aesop (rule_sets := [finiteness]) safe apply] lemma ofNat_ne_top {n : β„•} [Nat.AtLeastTwo n] : ofNat(n) β‰  ∞ := natCast_ne_top n @[simp] lemma ofNat_lt_top {n : β„•} [Nat.AtLeastTwo n] : ofNat(n) < ∞ := natCast_lt_top n @[simp] theorem top_ne_natCast (n : β„•) : ∞ β‰  n := WithTop.top_ne_natCast n @[simp] theorem top_ne_ofNat {n : β„•} [n.AtLeastTwo] : ∞ β‰  ofNat(n) := ofNat_ne_top.symm @[simp, norm_cast] lemma natCast_le_ofNNReal : (n : ℝβ‰₯0∞) ≀ r ↔ n ≀ r := by simp [← coe_le_coe] @[simp, norm_cast] lemma ofNNReal_le_natCast : r ≀ (n : ℝβ‰₯0∞) ↔ r ≀ n := by simp [← coe_le_coe] @[simp, norm_cast] lemma ofNNReal_add_natCast (r : ℝβ‰₯0) (n : β„•) : ofNNReal (r + n) = r + n := rfl @[simp, norm_cast] lemma ofNNReal_natCast_add (n : β„•) (r : ℝβ‰₯0) : ofNNReal (n + r) = n + r := rfl @[simp, norm_cast] lemma ofNNReal_sub_natCast (r : ℝβ‰₯0) (n : β„•) : ofNNReal (r - n) = r - n := rfl @[simp, norm_cast] lemma ofNNReal_natCast_sub (n : β„•) (r : ℝβ‰₯0) : ofNNReal (n - r) = n - r := rfl @[simp] theorem one_lt_top : 1 < ∞ := coe_lt_top @[simp, norm_cast] theorem toNNReal_natCast (n : β„•) : (n : ℝβ‰₯0∞).toNNReal = n := by rw [← ENNReal.coe_natCast n, ENNReal.toNNReal_coe] theorem toNNReal_ofNat (n : β„•) [n.AtLeastTwo] : ENNReal.toNNReal ofNat(n) = ofNat(n) := toNNReal_natCast n @[simp, norm_cast] theorem toReal_natCast (n : β„•) : (n : ℝβ‰₯0∞).toReal = n := by rw [← ENNReal.ofReal_natCast n, ENNReal.toReal_ofReal (Nat.cast_nonneg _)] @[simp] theorem toReal_ofNat (n : β„•) [n.AtLeastTwo] : ENNReal.toReal ofNat(n) = ofNat(n) := toReal_natCast n lemma toNNReal_natCast_eq_toNNReal (n : β„•) : (n : ℝβ‰₯0∞).toNNReal = (n : ℝ).toNNReal := by rw [Real.toNNReal_of_nonneg (by positivity), ENNReal.toNNReal_natCast, mk_natCast] theorem le_coe_iff : a ≀ ↑r ↔ βˆƒ p : ℝβ‰₯0, a = p ∧ p ≀ r := WithTop.le_coe_iff theorem coe_le_iff : ↑r ≀ a ↔ βˆ€ p : ℝβ‰₯0, a = p β†’ r ≀ p := WithTop.coe_le_iff theorem lt_iff_exists_coe : a < b ↔ βˆƒ p : ℝβ‰₯0, a = p ∧ ↑p < b := WithTop.lt_iff_exists_coe theorem toReal_le_coe_of_le_coe {a : ℝβ‰₯0∞} {b : ℝβ‰₯0} (h : a ≀ b) : a.toReal ≀ b := by lift a to ℝβ‰₯0 using ne_top_of_le_ne_top coe_ne_top h simpa using h @[simp] theorem max_eq_zero_iff : max a b = 0 ↔ a = 0 ∧ b = 0 := max_eq_bot @[simp] theorem min_eq_zero_iff : min a b = 0 ↔ a = 0 ∨ b = 0 := min_eq_bot theorem max_zero_left : max 0 a = a := max_eq_right (zero_le a) theorem max_zero_right : max a 0 = a := max_eq_left (zero_le a) theorem lt_iff_exists_rat_btwn : a < b ↔ βˆƒ q : β„š, 0 ≀ q ∧ a < Real.toNNReal q ∧ (Real.toNNReal q : ℝβ‰₯0∞) < b := ⟨fun h => by rcases lt_iff_exists_coe.1 h with ⟨p, rfl, _⟩ rcases exists_between h with ⟨c, pc, cb⟩ rcases lt_iff_exists_coe.1 cb with ⟨r, rfl, _⟩ rcases (NNReal.lt_iff_exists_rat_btwn _ _).1 (coe_lt_coe.1 pc) with ⟨q, hq0, pq, qr⟩ exact ⟨q, hq0, coe_lt_coe.2 pq, lt_trans (coe_lt_coe.2 qr) cb⟩, fun ⟨_, _, qa, qb⟩ => lt_trans qa qb⟩ theorem lt_iff_exists_real_btwn : a < b ↔ βˆƒ r : ℝ, 0 ≀ r ∧ a < ENNReal.ofReal r ∧ (ENNReal.ofReal r : ℝβ‰₯0∞) < b := ⟨fun h => let ⟨q, q0, aq, qb⟩ := ENNReal.lt_iff_exists_rat_btwn.1 h ⟨q, Rat.cast_nonneg.2 q0, aq, qb⟩, fun ⟨_, _, qa, qb⟩ => lt_trans qa qb⟩ theorem lt_iff_exists_nnreal_btwn : a < b ↔ βˆƒ r : ℝβ‰₯0, a < r ∧ (r : ℝβ‰₯0∞) < b := WithTop.lt_iff_exists_coe_btwn theorem lt_iff_exists_add_pos_lt : a < b ↔ βˆƒ r : ℝβ‰₯0, 0 < r ∧ a + r < b := by refine ⟨fun hab => ?_, fun ⟨r, _, hr⟩ => lt_of_le_of_lt le_self_add hr⟩ rcases lt_iff_exists_nnreal_btwn.1 hab with ⟨c, ac, cb⟩ lift a to ℝβ‰₯0 using ac.ne_top rw [coe_lt_coe] at ac refine ⟨c - a, tsub_pos_iff_lt.2 ac, ?_⟩ rwa [← coe_add, add_tsub_cancel_of_le ac.le] theorem le_of_forall_pos_le_add (h : βˆ€ Ξ΅ : ℝβ‰₯0, 0 < Ξ΅ β†’ b < ∞ β†’ a ≀ b + Ξ΅) : a ≀ b := by contrapose! h rcases lt_iff_exists_add_pos_lt.1 h with ⟨r, hr0, hr⟩ exact ⟨r, hr0, h.trans_le le_top, hr⟩ theorem natCast_lt_coe {n : β„•} : n < (r : ℝβ‰₯0∞) ↔ n < r := ENNReal.coe_natCast n β–Έ coe_lt_coe theorem coe_lt_natCast {n : β„•} : (r : ℝβ‰₯0∞) < n ↔ r < n := ENNReal.coe_natCast n β–Έ coe_lt_coe protected theorem exists_nat_gt {r : ℝβ‰₯0∞} (h : r β‰  ∞) : βˆƒ n : β„•, r < n := by lift r to ℝβ‰₯0 using h rcases exists_nat_gt r with ⟨n, hn⟩ exact ⟨n, coe_lt_natCast.2 hn⟩ @[simp] theorem iUnion_Iio_coe_nat : ⋃ n : β„•, Iio (n : ℝβ‰₯0∞) = {∞}ᢜ := by ext x rw [mem_iUnion] exact ⟨fun ⟨n, hn⟩ => ne_top_of_lt hn, ENNReal.exists_nat_gt⟩ @[simp] theorem iUnion_Iic_coe_nat : ⋃ n : β„•, Iic (n : ℝβ‰₯0∞) = {∞}ᢜ := Subset.antisymm (iUnion_subset fun n _x hx => ne_top_of_le_ne_top (natCast_ne_top n) hx) <| iUnion_Iio_coe_nat β–Έ iUnion_mono fun _ => Iio_subset_Iic_self @[simp] theorem iUnion_Ioc_coe_nat : ⋃ n : β„•, Ioc a n = Ioi a \ {∞} := by simp only [← Ioi_inter_Iic, ← inter_iUnion, iUnion_Iic_coe_nat, diff_eq] @[simp] theorem iUnion_Ioo_coe_nat : ⋃ n : β„•, Ioo a n = Ioi a \ {∞} := by simp only [← Ioi_inter_Iio, ← inter_iUnion, iUnion_Iio_coe_nat, diff_eq] @[simp] theorem iUnion_Icc_coe_nat : ⋃ n : β„•, Icc a n = Ici a \ {∞} := by simp only [← Ici_inter_Iic, ← inter_iUnion, iUnion_Iic_coe_nat, diff_eq] @[simp] theorem iUnion_Ico_coe_nat : ⋃ n : β„•, Ico a n = Ici a \ {∞} := by simp only [← Ici_inter_Iio, ← inter_iUnion, iUnion_Iio_coe_nat, diff_eq] @[simp] theorem iInter_Ici_coe_nat : β‹‚ n : β„•, Ici (n : ℝβ‰₯0∞) = {∞} := by simp only [← compl_Iio, ← compl_iUnion, iUnion_Iio_coe_nat, compl_compl] @[simp] theorem iInter_Ioi_coe_nat : β‹‚ n : β„•, Ioi (n : ℝβ‰₯0∞) = {∞} := by simp only [← compl_Iic, ← compl_iUnion, iUnion_Iic_coe_nat, compl_compl] @[simp, norm_cast] theorem coe_min (r p : ℝβ‰₯0) : ((min r p : ℝβ‰₯0) : ℝβ‰₯0∞) = min (r : ℝβ‰₯0∞) p := rfl @[simp, norm_cast] theorem coe_max (r p : ℝβ‰₯0) : ((max r p : ℝβ‰₯0) : ℝβ‰₯0∞) = max (r : ℝβ‰₯0∞) p := rfl theorem le_of_top_imp_top_of_toNNReal_le {a b : ℝβ‰₯0∞} (h : a = ⊀ β†’ b = ⊀) (h_nnreal : a β‰  ⊀ β†’ b β‰  ⊀ β†’ a.toNNReal ≀ b.toNNReal) : a ≀ b := by by_contra! hlt lift b to ℝβ‰₯0 using hlt.ne_top lift a to ℝβ‰₯0 using mt h coe_ne_top refine hlt.not_ge ?_ simpa using h_nnreal @[simp] theorem abs_toReal {x : ℝβ‰₯0∞} : |x.toReal| = x.toReal := by cases x <;> simp end Order section CompleteLattice variable {ΞΉ : Sort*} {f : ΞΉ β†’ ℝβ‰₯0} theorem coe_sSup {s : Set ℝβ‰₯0} : BddAbove s β†’ (↑(sSup s) : ℝβ‰₯0∞) = ⨆ a ∈ s, ↑a := WithTop.coe_sSup theorem coe_sInf {s : Set ℝβ‰₯0} (hs : s.Nonempty) : (↑(sInf s) : ℝβ‰₯0∞) = β¨… a ∈ s, ↑a := WithTop.coe_sInf hs (OrderBot.bddBelow s) theorem coe_iSup {ΞΉ : Sort*} {f : ΞΉ β†’ ℝβ‰₯0} (hf : BddAbove (range f)) : (↑(iSup f) : ℝβ‰₯0∞) = ⨆ a, ↑(f a) := WithTop.coe_iSup _ hf @[norm_cast] theorem coe_iInf {ΞΉ : Sort*} [Nonempty ΞΉ] (f : ΞΉ β†’ ℝβ‰₯0) : (↑(iInf f) : ℝβ‰₯0∞) = β¨… a, ↑(f a) := WithTop.coe_iInf (OrderBot.bddBelow _) theorem coe_mem_upperBounds {s : Set ℝβ‰₯0} : ↑r ∈ upperBounds (ofNNReal '' s) ↔ r ∈ upperBounds s := by simp +contextual [upperBounds, forall_mem_image, -mem_image, *] lemma iSup_coe_eq_top : ⨆ i, (f i : ℝβ‰₯0∞) = ⊀ ↔ Β¬ BddAbove (range f) := WithTop.iSup_coe_eq_top lemma iSup_coe_lt_top : ⨆ i, (f i : ℝβ‰₯0∞) < ⊀ ↔ BddAbove (range f) := WithTop.iSup_coe_lt_top lemma iInf_coe_eq_top : β¨… i, (f i : ℝβ‰₯0∞) = ⊀ ↔ IsEmpty ΞΉ := WithTop.iInf_coe_eq_top lemma iInf_coe_lt_top : β¨… i, (f i : ℝβ‰₯0∞) < ⊀ ↔ Nonempty ΞΉ := WithTop.iInf_coe_lt_top end CompleteLattice section Bit -- TODO: add lemmas about `OfNat.ofNat` end Bit end ENNReal open ENNReal namespace Set namespace OrdConnected variable {s : Set ℝ} {t : Set ℝβ‰₯0} {u : Set ℝβ‰₯0∞} theorem preimage_coe_nnreal_ennreal (h : u.OrdConnected) : ((↑) ⁻¹' u : Set ℝβ‰₯0).OrdConnected := h.preimage_mono ENNReal.coe_mono -- TODO: generalize to `WithTop` theorem image_coe_nnreal_ennreal (h : t.OrdConnected) : ((↑) '' t : Set ℝβ‰₯0∞).OrdConnected := by refine ⟨forall_mem_image.2 fun x hx => forall_mem_image.2 fun y hy z hz => ?_⟩ rcases ENNReal.le_coe_iff.1 hz.2 with ⟨z, rfl, -⟩ exact mem_image_of_mem _ (h.out hx hy ⟨ENNReal.coe_le_coe.1 hz.1, ENNReal.coe_le_coe.1 hz.2⟩) theorem preimage_ennreal_ofReal (h : u.OrdConnected) : (ENNReal.ofReal ⁻¹' u).OrdConnected := h.preimage_coe_nnreal_ennreal.preimage_real_toNNReal theorem image_ennreal_ofReal (h : s.OrdConnected) : (ENNReal.ofReal '' s).OrdConnected := by simpa only [image_image] using h.image_real_toNNReal.image_coe_nnreal_ennreal end OrdConnected end Set /-- While not very useful, this instance uses the same representation as `Real.instRepr`. -/ unsafe instance : Repr ℝβ‰₯0∞ where reprPrec | (r : ℝβ‰₯0), p => Repr.addAppParen f!"ENNReal.ofReal ({repr r.val})" p | ∞, _ => "∞" namespace Mathlib.Meta.Positivity open Lean Meta Qq /-- Extension for the `positivity` tactic: `ENNReal.toReal`. -/ @[positivity ENNReal.toReal _] def evalENNRealtoReal : PositivityExt where eval {u Ξ±} _zΞ± _pΞ± e := do match u, Ξ±, e with | 0, ~q(ℝ), ~q(ENNReal.toReal $a) => assertInstancesCommute pure (.nonnegative q(ENNReal.toReal_nonneg)) | _, _, _ => throwError "not ENNReal.toReal" /-- Extension for the `positivity` tactic: `ENNReal.ofNNReal`. -/ @[positivity ENNReal.ofNNReal _] def evalENNRealOfNNReal : PositivityExt where eval {u Ξ±} _zΞ± _pΞ± e := do match u, Ξ±, e with | 0, ~q(ℝβ‰₯0∞), ~q(ENNReal.ofNNReal $a) => let ra ← core q(inferInstance) q(inferInstance) a assertInstancesCommute match ra with | .positive pa => pure <| .positive q(ENNReal.coe_pos.mpr $pa) | _ => pure .none | _, _, _ => throwError "not ENNReal.ofNNReal" end Mathlib.Meta.Positivity
.lake/packages/mathlib/Mathlib/Data/ENNReal/Operations.lean
import Mathlib.Data.ENNReal.Real /-! # Properties of addition, multiplication and subtraction on extended non-negative real numbers In this file we prove elementary properties of algebraic operations on `ℝβ‰₯0∞`, including addition, multiplication, natural powers and truncated subtraction, as well as how these interact with the order structure on `ℝβ‰₯0∞`. Notably excluded from this list are inversion and division, the definitions and properties of which can be found in `Mathlib/Data/ENNReal/Inv.lean`. Note: the definitions of the operations included in this file can be found in `Mathlib/Data/ENNReal/Basic.lean`. -/ assert_not_exists Finset open Set NNReal ENNReal namespace ENNReal variable {a b c d : ℝβ‰₯0∞} {r p q : ℝβ‰₯0} section Mul @[mono, gcongr] theorem mul_lt_mul (ac : a < c) (bd : b < d) : a * b < c * d := WithTop.mul_lt_mul ac bd protected lemma pow_right_strictMono {n : β„•} (hn : n β‰  0) : StrictMono fun a : ℝβ‰₯0∞ ↦ a ^ n := WithTop.pow_right_strictMono hn protected lemma pow_le_pow_left_iff {n : β„•} (hn : n β‰  0) : a ^ n ≀ b ^ n ↔ a ≀ b := (ENNReal.pow_right_strictMono hn).le_iff_le protected lemma pow_lt_pow_left_iff {n : β„•} (hn : n β‰  0) : a ^ n < b ^ n ↔ a < b := (ENNReal.pow_right_strictMono hn).lt_iff_lt @[mono, gcongr] protected lemma pow_le_pow_left {n : β„•} (h : a ≀ b) : a ^ n ≀ b ^ n := pow_le_pow_left' h n @[mono, gcongr] protected alias ⟨_, pow_lt_pow_left⟩ := ENNReal.pow_lt_pow_left_iff lemma mul_left_strictMono (hβ‚€ : a β‰  0) (hinf : a β‰  ∞) : StrictMono (Β· * a) := WithTop.mul_left_strictMono (pos_iff_ne_zero.2 hβ‚€) hinf lemma mul_right_strictMono (hβ‚€ : a β‰  0) (hinf : a β‰  ∞) : StrictMono (a * Β·) := WithTop.mul_right_strictMono (pos_iff_ne_zero.2 hβ‚€) hinf @[gcongr] protected theorem mul_lt_mul_left' (h0 : a β‰  0) (hinf : a β‰  ⊀) (bc : b < c) : a * b < a * c := ENNReal.mul_right_strictMono h0 hinf bc @[gcongr] protected theorem mul_lt_mul_right' (h0 : a β‰  0) (hinf : a β‰  ⊀) (bc : b < c) : b * a < c * a := mul_comm b a β–Έ mul_comm c a β–Έ ENNReal.mul_right_strictMono h0 hinf bc -- TODO: generalize to `WithTop` protected theorem mul_right_inj (h0 : a β‰  0) (hinf : a β‰  ∞) : a * b = a * c ↔ b = c := (mul_right_strictMono h0 hinf).injective.eq_iff -- TODO: generalize to `WithTop` protected theorem mul_left_inj (h0 : c β‰  0) (hinf : c β‰  ∞) : a * c = b * c ↔ a = b := mul_comm c a β–Έ mul_comm c b β–Έ ENNReal.mul_right_inj h0 hinf -- TODO: generalize to `WithTop` theorem mul_le_mul_left (h0 : a β‰  0) (hinf : a β‰  ∞) : a * b ≀ a * c ↔ b ≀ c := (mul_right_strictMono h0 hinf).le_iff_le -- TODO: generalize to `WithTop` theorem mul_le_mul_right : c β‰  0 β†’ c β‰  ∞ β†’ (a * c ≀ b * c ↔ a ≀ b) := mul_comm c a β–Έ mul_comm c b β–Έ mul_le_mul_left -- TODO: generalize to `WithTop` theorem mul_lt_mul_left (h0 : a β‰  0) (hinf : a β‰  ∞) : a * b < a * c ↔ b < c := (mul_right_strictMono h0 hinf).lt_iff_lt -- TODO: generalize to `WithTop` theorem mul_lt_mul_right : c β‰  0 β†’ c β‰  ∞ β†’ (a * c < b * c ↔ a < b) := mul_comm c a β–Έ mul_comm c b β–Έ mul_lt_mul_left protected lemma mul_eq_left (haβ‚€ : a β‰  0) (ha : a β‰  ∞) : a * b = a ↔ b = 1 := by simpa using ENNReal.mul_right_inj haβ‚€ ha (c := 1) protected lemma mul_eq_right (hbβ‚€ : b β‰  0) (hb : b β‰  ∞) : a * b = b ↔ a = 1 := by simpa using ENNReal.mul_left_inj hbβ‚€ hb (b := 1) end Mul section OperationsAndOrder protected theorem pow_pos : 0 < a β†’ βˆ€ n : β„•, 0 < a ^ n := CanonicallyOrderedAdd.pow_pos protected theorem pow_ne_zero : a β‰  0 β†’ βˆ€ n : β„•, a ^ n β‰  0 := by simpa only [pos_iff_ne_zero] using ENNReal.pow_pos theorem not_lt_zero : Β¬a < 0 := by simp protected theorem le_of_add_le_add_left : a β‰  ∞ β†’ a + b ≀ a + c β†’ b ≀ c := WithTop.le_of_add_le_add_left protected theorem le_of_add_le_add_right : a β‰  ∞ β†’ b + a ≀ c + a β†’ b ≀ c := WithTop.le_of_add_le_add_right @[gcongr] protected theorem add_lt_add_left : a β‰  ∞ β†’ b < c β†’ a + b < a + c := WithTop.add_lt_add_left @[gcongr] protected theorem add_lt_add_right : a β‰  ∞ β†’ b < c β†’ b + a < c + a := WithTop.add_lt_add_right protected theorem add_le_add_iff_left : a β‰  ∞ β†’ (a + b ≀ a + c ↔ b ≀ c) := WithTop.add_le_add_iff_left protected theorem add_le_add_iff_right : a β‰  ∞ β†’ (b + a ≀ c + a ↔ b ≀ c) := WithTop.add_le_add_iff_right protected theorem add_lt_add_iff_left : a β‰  ∞ β†’ (a + b < a + c ↔ b < c) := WithTop.add_lt_add_iff_left protected theorem add_lt_add_iff_right : a β‰  ∞ β†’ (b + a < c + a ↔ b < c) := WithTop.add_lt_add_iff_right protected theorem add_lt_add_of_le_of_lt : a β‰  ∞ β†’ a ≀ b β†’ c < d β†’ a + c < b + d := WithTop.add_lt_add_of_le_of_lt protected theorem add_lt_add_of_lt_of_le : c β‰  ∞ β†’ a < b β†’ c ≀ d β†’ a + c < b + d := WithTop.add_lt_add_of_lt_of_le instance addLeftReflectLT : AddLeftReflectLT ℝβ‰₯0∞ := WithTop.addLeftReflectLT theorem lt_add_right (ha : a β‰  ∞) (hb : b β‰  0) : a < a + b := by rwa [← pos_iff_ne_zero, ← ENNReal.add_lt_add_iff_left ha, add_zero] at hb end OperationsAndOrder section OperationsAndInfty variable {Ξ± : Type*} {n : β„•} @[simp] theorem add_eq_top : a + b = ∞ ↔ a = ∞ ∨ b = ∞ := WithTop.add_eq_top @[simp] theorem add_lt_top : a + b < ∞ ↔ a < ∞ ∧ b < ∞ := WithTop.add_lt_top theorem toNNReal_add {r₁ rβ‚‚ : ℝβ‰₯0∞} (h₁ : r₁ β‰  ∞) (hβ‚‚ : rβ‚‚ β‰  ∞) : (r₁ + rβ‚‚).toNNReal = r₁.toNNReal + rβ‚‚.toNNReal := by lift r₁ to ℝβ‰₯0 using h₁ lift rβ‚‚ to ℝβ‰₯0 using hβ‚‚ rfl /-- If `a ≀ b + c` and `a = ∞` whenever `b = ∞` or `c = ∞`, then `ENNReal.toReal a ≀ ENNReal.toReal b + ENNReal.toReal c`. This lemma is useful to transfer triangle-like inequalities from `ENNReal`s to `Real`s. -/ theorem toReal_le_add' (hle : a ≀ b + c) (hb : b = ∞ β†’ a = ∞) (hc : c = ∞ β†’ a = ∞) : a.toReal ≀ b.toReal + c.toReal := by refine le_trans (toReal_mono' hle ?_) toReal_add_le simpa only [add_eq_top, or_imp] using And.intro hb hc /-- If `a ≀ b + c`, `b β‰  ∞`, and `c β‰  ∞`, then `ENNReal.toReal a ≀ ENNReal.toReal b + ENNReal.toReal c`. This lemma is useful to transfer triangle-like inequalities from `ENNReal`s to `Real`s. -/ theorem toReal_le_add (hle : a ≀ b + c) (hb : b β‰  ∞) (hc : c β‰  ∞) : a.toReal ≀ b.toReal + c.toReal := toReal_le_add' hle (flip absurd hb) (flip absurd hc) theorem not_lt_top {x : ℝβ‰₯0∞} : Β¬x < ∞ ↔ x = ∞ := by rw [lt_top_iff_ne_top, Classical.not_not] theorem add_ne_top : a + b β‰  ∞ ↔ a β‰  ∞ ∧ b β‰  ∞ := by simpa only [lt_top_iff_ne_top] using add_lt_top @[aesop (rule_sets := [finiteness]) safe apply] protected lemma Finiteness.add_ne_top {a b : ℝβ‰₯0∞} (ha : a β‰  ∞) (hb : b β‰  ∞) : a + b β‰  ∞ := ENNReal.add_ne_top.2 ⟨ha, hb⟩ theorem mul_top' : a * ∞ = if a = 0 then 0 else ∞ := by convert WithTop.mul_top' a @[simp] theorem mul_top (h : a β‰  0) : a * ∞ = ∞ := WithTop.mul_top h theorem top_mul' : ∞ * a = if a = 0 then 0 else ∞ := by convert WithTop.top_mul' a @[simp] theorem top_mul (h : a β‰  0) : ∞ * a = ∞ := WithTop.top_mul h theorem top_mul_top : ∞ * ∞ = ∞ := WithTop.top_mul_top theorem mul_eq_top : a * b = ∞ ↔ a β‰  0 ∧ b = ∞ ∨ a = ∞ ∧ b β‰  0 := WithTop.mul_eq_top_iff theorem mul_lt_top : a < ∞ β†’ b < ∞ β†’ a * b < ∞ := WithTop.mul_lt_top -- This is unsafe because we could have `a = ∞` and `b = 0` or vice-versa @[aesop (rule_sets := [finiteness]) unsafe 75% apply] theorem mul_ne_top : a β‰  ∞ β†’ b β‰  ∞ β†’ a * b β‰  ∞ := WithTop.mul_ne_top theorem lt_top_of_mul_ne_top_left (h : a * b β‰  ∞) (hb : b β‰  0) : a < ∞ := lt_top_iff_ne_top.2 fun ha => h <| mul_eq_top.2 (Or.inr ⟨ha, hb⟩) theorem lt_top_of_mul_ne_top_right (h : a * b β‰  ∞) (ha : a β‰  0) : b < ∞ := lt_top_of_mul_ne_top_left (by rwa [mul_comm]) ha theorem mul_lt_top_iff {a b : ℝβ‰₯0∞} : a * b < ∞ ↔ a < ∞ ∧ b < ∞ ∨ a = 0 ∨ b = 0 := by constructor Β· intro h rw [← or_assoc, or_iff_not_imp_right, or_iff_not_imp_right] intro hb ha exact ⟨lt_top_of_mul_ne_top_left h.ne hb, lt_top_of_mul_ne_top_right h.ne ha⟩ Β· rintro (⟨ha, hb⟩ | rfl | rfl) <;> [exact mul_lt_top ha hb; simp; simp] theorem mul_self_lt_top_iff {a : ℝβ‰₯0∞} : a * a < ⊀ ↔ a < ⊀ := by rw [ENNReal.mul_lt_top_iff, and_self, or_self, or_iff_left_iff_imp] rintro rfl exact zero_lt_top theorem mul_pos_iff : 0 < a * b ↔ 0 < a ∧ 0 < b := CanonicallyOrderedAdd.mul_pos theorem mul_pos (ha : a β‰  0) (hb : b β‰  0) : 0 < a * b := mul_pos_iff.2 ⟨pos_iff_ne_zero.2 ha, pos_iff_ne_zero.2 hb⟩ @[simp] lemma top_pow {n : β„•} (hn : n β‰  0) : (∞ : ℝβ‰₯0∞) ^ n = ∞ := WithTop.top_pow hn @[simp] lemma pow_eq_top_iff : a ^ n = ∞ ↔ a = ∞ ∧ n β‰  0 := WithTop.pow_eq_top_iff lemma pow_ne_top_iff : a ^ n β‰  ∞ ↔ a β‰  ∞ ∨ n = 0 := WithTop.pow_ne_top_iff @[simp] lemma pow_lt_top_iff : a ^ n < ∞ ↔ a < ∞ ∨ n = 0 := WithTop.pow_lt_top_iff lemma eq_top_of_pow (n : β„•) (ha : a ^ n = ∞) : a = ∞ := WithTop.eq_top_of_pow n ha @[deprecated (since := "2025-04-24")] alias pow_eq_top := eq_top_of_pow @[aesop (rule_sets := [finiteness]) safe apply] lemma pow_ne_top (ha : a β‰  ∞) : a ^ n β‰  ∞ := WithTop.pow_ne_top ha lemma pow_lt_top (ha : a < ∞) : a ^ n < ∞ := WithTop.pow_lt_top ha end OperationsAndInfty -- TODO: generalize to `WithTop` @[gcongr] protected theorem add_lt_add (ac : a < c) (bd : b < d) : a + b < c + d := by lift a to ℝβ‰₯0 using ac.ne_top lift b to ℝβ‰₯0 using bd.ne_top cases c; Β· simp cases d; Β· simp simp only [← coe_add, coe_lt_coe] at * exact add_lt_add ac bd section Cancel -- TODO: generalize to `WithTop` /-- An element `a` is `AddLECancellable` if `a + b ≀ a + c` implies `b ≀ c` for all `b` and `c`. This is true in `ℝβ‰₯0∞` for all elements except `∞`. -/ @[simp] theorem addLECancellable_iff_ne {a : ℝβ‰₯0∞} : AddLECancellable a ↔ a β‰  ∞ := by constructor Β· rintro h rfl refine zero_lt_one.not_ge (h ?_) simp Β· rintro h b c hbc apply ENNReal.le_of_add_le_add_left h hbc /-- This lemma has an abbreviated name because it is used frequently. -/ theorem cancel_of_ne {a : ℝβ‰₯0∞} (h : a β‰  ∞) : AddLECancellable a := addLECancellable_iff_ne.mpr h /-- This lemma has an abbreviated name because it is used frequently. -/ theorem cancel_of_lt {a : ℝβ‰₯0∞} (h : a < ∞) : AddLECancellable a := cancel_of_ne h.ne /-- This lemma has an abbreviated name because it is used frequently. -/ theorem cancel_of_lt' {a b : ℝβ‰₯0∞} (h : a < b) : AddLECancellable a := cancel_of_ne h.ne_top /-- This lemma has an abbreviated name because it is used frequently. -/ theorem cancel_coe {a : ℝβ‰₯0} : AddLECancellable (a : ℝβ‰₯0∞) := cancel_of_ne coe_ne_top theorem add_right_inj (h : a β‰  ∞) : a + b = a + c ↔ b = c := (cancel_of_ne h).inj theorem add_left_inj (h : a β‰  ∞) : b + a = c + a ↔ b = c := (cancel_of_ne h).inj_left end Cancel section Sub theorem sub_eq_sInf {a b : ℝβ‰₯0∞} : a - b = sInf { d | a ≀ d + b } := le_antisymm (le_sInf fun _ h => tsub_le_iff_right.mpr h) <| sInf_le <| mem_setOf.2 le_tsub_add /-- This is a special case of `WithTop.coe_sub` in the `ENNReal` namespace -/ @[simp, norm_cast] theorem coe_sub : (↑(r - p) : ℝβ‰₯0∞) = ↑r - ↑p := WithTop.coe_sub /-- This is a special case of `WithTop.top_sub_coe` in the `ENNReal` namespace -/ @[simp] theorem top_sub_coe : ∞ - ↑r = ∞ := rfl @[simp] lemma top_sub (ha : a β‰  ∞) : ∞ - a = ∞ := by lift a to ℝβ‰₯0 using ha; exact top_sub_coe /-- This is a special case of `WithTop.sub_top` in the `ENNReal` namespace -/ @[simp] theorem sub_top : a - ∞ = 0 := WithTop.sub_top @[simp] theorem sub_eq_top_iff : a - b = ∞ ↔ a = ∞ ∧ b β‰  ∞ := WithTop.sub_eq_top_iff lemma sub_ne_top_iff : a - b β‰  ∞ ↔ a β‰  ∞ ∨ b = ∞ := WithTop.sub_ne_top_iff -- This is unsafe because we could have `a = b = ∞` @[aesop (rule_sets := [finiteness]) unsafe 75% apply] theorem sub_ne_top (ha : a β‰  ∞) : a - b β‰  ∞ := mt sub_eq_top_iff.mp <| mt And.left ha @[simp, norm_cast] theorem natCast_sub (m n : β„•) : ↑(m - n) = (m - n : ℝβ‰₯0∞) := by rw [← coe_natCast, Nat.cast_tsub, coe_sub, coe_natCast, coe_natCast] /-- See `ENNReal.sub_eq_of_eq_add'` for a version assuming that `a = c + b` itself is finite rather than `b`. -/ protected theorem sub_eq_of_eq_add (hb : b β‰  ∞) : a = c + b β†’ a - b = c := (cancel_of_ne hb).tsub_eq_of_eq_add /-- Weaker version of `ENNReal.sub_eq_of_eq_add` assuming that `a = c + b` itself is finite rather han `b`. -/ protected lemma sub_eq_of_eq_add' (ha : a β‰  ∞) : a = c + b β†’ a - b = c := (cancel_of_ne ha).tsub_eq_of_eq_add' /-- See `ENNReal.eq_sub_of_add_eq'` for a version assuming that `b = a + c` itself is finite rather than `c`. -/ protected theorem eq_sub_of_add_eq (hc : c β‰  ∞) : a + c = b β†’ a = b - c := (cancel_of_ne hc).eq_tsub_of_add_eq /-- Weaker version of `ENNReal.eq_sub_of_add_eq` assuming that `b = a + c` itself is finite rather than `c`. -/ protected lemma eq_sub_of_add_eq' (hb : b β‰  ∞) : a + c = b β†’ a = b - c := (cancel_of_ne hb).eq_tsub_of_add_eq' /-- See `ENNReal.sub_eq_of_eq_add_rev'` for a version assuming that `a = b + c` itself is finite rather than `b`. -/ protected theorem sub_eq_of_eq_add_rev (hb : b β‰  ∞) : a = b + c β†’ a - b = c := (cancel_of_ne hb).tsub_eq_of_eq_add_rev /-- Weaker version of `ENNReal.sub_eq_of_eq_add_rev` assuming that `a = b + c` itself is finite rather than `b`. -/ protected lemma sub_eq_of_eq_add_rev' (ha : a β‰  ∞) : a = b + c β†’ a - b = c := (cancel_of_ne ha).tsub_eq_of_eq_add_rev' protected theorem add_sub_cancel_left (ha : a β‰  ∞) : a + b - a = b := by simp [ha] protected theorem add_sub_cancel_right (hb : b β‰  ∞) : a + b - b = a := by simp [hb] protected theorem sub_add_eq_add_sub (hab : b ≀ a) (b_ne_top : b β‰  ∞) : a - b + c = a + c - b := by by_cases c_top : c = ∞ Β· simpa [c_top] using ENNReal.eq_sub_of_add_eq b_ne_top rfl refine ENNReal.eq_sub_of_add_eq b_ne_top ?_ simp only [add_assoc, add_comm c b] simpa only [← add_assoc] using (add_left_inj c_top).mpr <| tsub_add_cancel_of_le hab lemma add_sub_add_eq_sub_right (hc : c β‰  ∞ := by finiteness) : (a + c) - (b + c) = a - b := by lift c to ℝβ‰₯0 using hc cases a <;> cases b Β· simp Β· simp Β· simp Β· norm_cast rw [add_tsub_add_eq_tsub_right] lemma add_sub_add_eq_sub_left (hc : c β‰  ∞ := by finiteness) : (c + a) - (c + b) = a - b := by simp_rw [add_comm c] exact ENNReal.add_sub_add_eq_sub_right hc protected theorem lt_add_of_sub_lt_left (h : a β‰  ∞ ∨ b β‰  ∞) : a - b < c β†’ a < b + c := by obtain rfl | hb := eq_or_ne b ∞ Β· rw [top_add, lt_top_iff_ne_top] exact fun _ => h.resolve_right (Classical.not_not.2 rfl) Β· exact (cancel_of_ne hb).lt_add_of_tsub_lt_left protected theorem lt_add_of_sub_lt_right (h : a β‰  ∞ ∨ c β‰  ∞) : a - c < b β†’ a < b + c := add_comm c b β–Έ ENNReal.lt_add_of_sub_lt_left h theorem le_sub_of_add_le_left (ha : a β‰  ∞) : a + b ≀ c β†’ b ≀ c - a := (cancel_of_ne ha).le_tsub_of_add_le_left theorem le_sub_of_add_le_right (hb : b β‰  ∞) : a + b ≀ c β†’ a ≀ c - b := (cancel_of_ne hb).le_tsub_of_add_le_right protected theorem sub_lt_of_lt_add (hac : c ≀ a) (h : a < b + c) : a - c < b := ((cancel_of_lt' <| hac.trans_lt h).tsub_lt_iff_right hac).mpr h protected theorem sub_lt_iff_lt_right (hb : b β‰  ∞) (hab : b ≀ a) : a - b < c ↔ a < c + b := (cancel_of_ne hb).tsub_lt_iff_right hab protected theorem sub_lt_iff_lt_left (hb : b β‰  ∞) (hab : b ≀ a) : a - b < c ↔ a < b + c := (cancel_of_ne hb).tsub_lt_iff_left hab theorem le_sub_iff_add_le_left (hc : c β‰  ∞) (hcb : c ≀ b) : a ≀ b - c ↔ c + a ≀ b := ⟨fun h ↦ add_le_of_le_tsub_left_of_le hcb h, le_sub_of_add_le_left hc⟩ theorem le_sub_iff_add_le_right (hc : c β‰  ∞) (hcb : c ≀ b) : a ≀ b - c ↔ a + c ≀ b := ⟨fun h ↦ add_le_of_le_tsub_right_of_le hcb h, le_sub_of_add_le_right hc⟩ protected theorem sub_lt_self (ha : a β‰  ∞) (haβ‚€ : a β‰  0) (hb : b β‰  0) : a - b < a := (cancel_of_ne ha).tsub_lt_self (pos_iff_ne_zero.2 haβ‚€) (pos_iff_ne_zero.2 hb) protected theorem sub_lt_self_iff (ha : a β‰  ∞) : a - b < a ↔ 0 < a ∧ 0 < b := (cancel_of_ne ha).tsub_lt_self_iff theorem sub_lt_of_sub_lt (hβ‚‚ : c ≀ a) (h₃ : a β‰  ∞ ∨ b β‰  ∞) (h₁ : a - b < c) : a - c < b := ENNReal.sub_lt_of_lt_add hβ‚‚ (add_comm c b β–Έ ENNReal.lt_add_of_sub_lt_right h₃ h₁) theorem sub_sub_cancel (h : a β‰  ∞) (h2 : b ≀ a) : a - (a - b) = b := (cancel_of_ne <| sub_ne_top h).tsub_tsub_cancel_of_le h2 theorem sub_right_inj {a b c : ℝβ‰₯0∞} (ha : a β‰  ∞) (hb : b ≀ a) (hc : c ≀ a) : a - b = a - c ↔ b = c := (cancel_of_ne ha).tsub_right_inj (cancel_of_ne <| ne_top_of_le_ne_top ha hb) (cancel_of_ne <| ne_top_of_le_ne_top ha hc) hb hc protected theorem sub_mul (h : 0 < b β†’ b < a β†’ c β‰  ∞) : (a - b) * c = a * c - b * c := by rcases le_or_gt a b with hab | hab; Β· simp [hab, mul_left_mono hab, tsub_eq_zero_of_le] rcases eq_or_lt_of_le (zero_le b) with (rfl | hb); Β· simp exact (cancel_of_ne <| mul_ne_top hab.ne_top (h hb hab)).tsub_mul protected theorem mul_sub (h : 0 < c β†’ c < b β†’ a β‰  ∞) : a * (b - c) = a * b - a * c := by simp only [mul_comm a] exact ENNReal.sub_mul h theorem sub_le_sub_iff_left (h : c ≀ a) (h' : a β‰  ∞) : (a - b ≀ a - c) ↔ c ≀ b := (cancel_of_ne h').tsub_le_tsub_iff_left (cancel_of_ne (ne_top_of_le_ne_top h' h)) h theorem le_toReal_sub {a b : ℝβ‰₯0∞} (hb : b β‰  ∞) : a.toReal - b.toReal ≀ (a - b).toReal := by lift b to ℝβ‰₯0 using hb induction a Β· simp Β· simp only [← coe_sub, NNReal.sub_def, Real.coe_toNNReal', coe_toReal] exact le_max_left _ _ @[simp] lemma toNNReal_sub (hb : b β‰  ∞) : (a - b).toNNReal = a.toNNReal - b.toNNReal := by lift b to ℝβ‰₯0 using hb; induction a <;> simp [← coe_sub] @[simp] lemma toReal_sub_of_le (hba : b ≀ a) (ha : a β‰  ∞) : (a - b).toReal = a.toReal - b.toReal := by simp [ENNReal.toReal, ne_top_of_le_ne_top ha hba, toNNReal_mono ha hba] theorem ofReal_sub (p : ℝ) {q : ℝ} (hq : 0 ≀ q) : ENNReal.ofReal (p - q) = ENNReal.ofReal p - ENNReal.ofReal q := by obtain h | h := le_total p q Β· rw [ofReal_of_nonpos (sub_nonpos_of_le h), tsub_eq_zero_of_le (ofReal_le_ofReal h)] refine ENNReal.eq_sub_of_add_eq ofReal_ne_top ?_ rw [← ofReal_add (sub_nonneg_of_le h) hq, sub_add_cancel] lemma sub_sub_sub_cancel_left (ha : a β‰  ∞) (h : b ≀ a) : a - c - (a - b) = b - c := by have hb : b β‰  ∞ := ne_top_of_le_ne_top ha h lift a to ℝβ‰₯0 using ha lift b to ℝβ‰₯0 using hb cases c Β· simp Β· norm_cast rw [tsub_tsub_tsub_cancel_left] exact mod_cast h end Sub section Interval variable {x y z : ℝβ‰₯0∞} {Ξ΅ Ρ₁ Ξ΅β‚‚ : ℝβ‰₯0∞} {s : Set ℝβ‰₯0∞} protected theorem Ico_eq_Iio : Ico 0 y = Iio y := Ico_bot theorem mem_Iio_self_add : x β‰  ∞ β†’ Ξ΅ β‰  0 β†’ x ∈ Iio (x + Ξ΅) := fun xt Ξ΅0 => lt_add_right xt Ξ΅0 theorem mem_Ioo_self_sub_add : x β‰  ∞ β†’ x β‰  0 β†’ Ρ₁ β‰  0 β†’ Ξ΅β‚‚ β‰  0 β†’ x ∈ Ioo (x - Ρ₁) (x + Ξ΅β‚‚) := fun xt x0 Ξ΅0 Ξ΅0' => ⟨ENNReal.sub_lt_self xt x0 Ξ΅0, lt_add_right xt Ξ΅0'⟩ @[simp] theorem image_coe_Iic (x : ℝβ‰₯0) : (↑) '' Iic x = Iic (x : ℝβ‰₯0∞) := WithTop.image_coe_Iic @[simp] theorem image_coe_Ici (x : ℝβ‰₯0) : (↑) '' Ici x = Ico ↑x ∞ := WithTop.image_coe_Ici @[simp] theorem image_coe_Iio (x : ℝβ‰₯0) : (↑) '' Iio x = Iio (x : ℝβ‰₯0∞) := WithTop.image_coe_Iio @[simp] theorem image_coe_Ioi (x : ℝβ‰₯0) : (↑) '' Ioi x = Ioo ↑x ∞ := WithTop.image_coe_Ioi @[simp] theorem image_coe_Icc (x y : ℝβ‰₯0) : (↑) '' Icc x y = Icc (x : ℝβ‰₯0∞) y := WithTop.image_coe_Icc @[simp] theorem image_coe_Ico (x y : ℝβ‰₯0) : (↑) '' Ico x y = Ico (x : ℝβ‰₯0∞) y := WithTop.image_coe_Ico @[simp] theorem image_coe_Ioc (x y : ℝβ‰₯0) : (↑) '' Ioc x y = Ioc (x : ℝβ‰₯0∞) y := WithTop.image_coe_Ioc @[simp] theorem image_coe_Ioo (x y : ℝβ‰₯0) : (↑) '' Ioo x y = Ioo (x : ℝβ‰₯0∞) y := WithTop.image_coe_Ioo @[simp] theorem image_coe_uIcc (x y : ℝβ‰₯0) : (↑) '' uIcc x y = uIcc (x : ℝβ‰₯0∞) y := by simp [uIcc] @[simp] theorem image_coe_uIoc (x y : ℝβ‰₯0) : (↑) '' uIoc x y = uIoc (x : ℝβ‰₯0∞) y := by simp [uIoc] @[simp] theorem image_coe_uIoo (x y : ℝβ‰₯0) : (↑) '' uIoo x y = uIoo (x : ℝβ‰₯0∞) y := by simp [uIoo] end Interval section iInf variable {ΞΉ : Sort*} {f g : ΞΉ β†’ ℝβ‰₯0∞} variable {a b c d : ℝβ‰₯0∞} {r p q : ℝβ‰₯0} theorem toNNReal_iInf (hf : βˆ€ i, f i β‰  ∞) : (iInf f).toNNReal = β¨… i, (f i).toNNReal := by cases isEmpty_or_nonempty ΞΉ Β· rw [iInf_of_empty, toNNReal_top, NNReal.iInf_empty] Β· lift f to ΞΉ β†’ ℝβ‰₯0 using hf simp_rw [← coe_iInf, toNNReal_coe] theorem toNNReal_sInf (s : Set ℝβ‰₯0∞) (hs : βˆ€ r ∈ s, r β‰  ∞) : (sInf s).toNNReal = sInf (ENNReal.toNNReal '' s) := by have hf : βˆ€ i, ((↑) : s β†’ ℝβ‰₯0∞) i β‰  ∞ := fun ⟨r, rs⟩ => hs r rs simpa only [← sInf_range, ← image_eq_range, Subtype.range_coe_subtype] using (toNNReal_iInf hf) theorem toReal_iInf (hf : βˆ€ i, f i β‰  ∞) : (iInf f).toReal = β¨… i, (f i).toReal := by simp only [ENNReal.toReal, toNNReal_iInf hf, NNReal.coe_iInf] theorem toReal_sInf (s : Set ℝβ‰₯0∞) (hf : βˆ€ r ∈ s, r β‰  ∞) : (sInf s).toReal = sInf (ENNReal.toReal '' s) := by simp only [ENNReal.toReal, toNNReal_sInf s hf, NNReal.coe_sInf, Set.image_image] @[simp] lemma ofReal_iInf [Nonempty ΞΉ] (f : ΞΉ β†’ ℝ) : ENNReal.ofReal (β¨… i, f i) = β¨… i, ENNReal.ofReal (f i) := by obtain ⟨i, hi⟩ | h := em (βˆƒ i, f i ≀ 0) Β· rw [(iInf_eq_bot _).2 fun _ _ ↦ ⟨i, by simpa [ofReal_of_nonpos hi]⟩] simp [Real.iInf_nonpos' ⟨i, hi⟩] replace h i : 0 ≀ f i := le_of_not_ge fun hi ↦ h ⟨i, hi⟩ refine eq_of_forall_le_iff fun a ↦ ?_ obtain rfl | ha := eq_or_ne a ∞ Β· simp rw [le_iInf_iff, le_ofReal_iff_toReal_le ha, le_ciInf_iff ⟨0, by simpa [mem_lowerBounds]⟩] Β· exact forall_congr' fun i ↦ (le_ofReal_iff_toReal_le ha (h _)).symm Β· exact Real.iInf_nonneg h theorem iInf_add : iInf f + a = β¨… i, f i + a := le_antisymm (le_iInf fun _ => add_le_add (iInf_le _ _) <| le_rfl) (tsub_le_iff_right.1 <| le_iInf fun _ => tsub_le_iff_right.2 <| iInf_le _ _) theorem sub_iInf : (a - β¨… i, f i) = ⨆ i, a - f i := by refine eq_of_forall_ge_iff fun c => ?_ rw [tsub_le_iff_right, add_comm, iInf_add] simp [tsub_le_iff_right, add_comm] theorem sInf_add {s : Set ℝβ‰₯0∞} : sInf s + a = β¨… b ∈ s, b + a := by simp [sInf_eq_iInf, iInf_add] theorem add_iInf {a : ℝβ‰₯0∞} : a + iInf f = β¨… b, a + f b := by rw [add_comm, iInf_add]; simp [add_comm] theorem iInf_add_iInf (h : βˆ€ i j, βˆƒ k, f k + g k ≀ f i + g j) : iInf f + iInf g = β¨… a, f a + g a := suffices β¨… a, f a + g a ≀ iInf f + iInf g from le_antisymm (le_iInf fun _ => add_le_add (iInf_le _ _) (iInf_le _ _)) this calc β¨… a, f a + g a ≀ β¨… (a) (a'), f a + g a' := le_iInfβ‚‚ fun a a' => let ⟨k, h⟩ := h a a'; iInf_le_of_le k h _ = iInf f + iInf g := by simp_rw [iInf_add, add_iInf] lemma iInf_add_iInf_of_monotone {ΞΉ : Type*} [Preorder ΞΉ] [IsDirected ΞΉ (Β· β‰₯ Β·)] {f g : ΞΉ β†’ ℝβ‰₯0∞} (hf : Monotone f) (hg : Monotone g) : iInf f + iInf g = β¨… a, f a + g a := iInf_add_iInf fun i j ↦ (exists_le_le i j).imp fun _k ⟨hi, hj⟩ ↦ by gcongr <;> apply_rules lemma add_iInfβ‚‚ {ΞΊ : ΞΉ β†’ Sort*} (f : (i : ΞΉ) β†’ ΞΊ i β†’ ℝβ‰₯0∞) : a + β¨… (i) (j), f i j = β¨… (i) (j), a + f i j := by simp [add_iInf] lemma iInfβ‚‚_add {ΞΊ : ΞΉ β†’ Sort*} (f : (i : ΞΉ) β†’ ΞΊ i β†’ ℝβ‰₯0∞) : (β¨… (i) (j), f i j) + a = β¨… (i) (j), f i j + a := by simp only [add_comm, add_iInfβ‚‚] lemma add_sInf {s : Set ℝβ‰₯0∞} : a + sInf s = β¨… b ∈ s, a + b := by rw [sInf_eq_iInf, add_iInfβ‚‚] variable {ΞΊ : Sort*} lemma le_iInf_add_iInf {g : ΞΊ β†’ ℝβ‰₯0∞} (h : βˆ€ i j, a ≀ f i + g j) : a ≀ iInf f + iInf g := by simp_rw [iInf_add, add_iInf]; exact le_iInfβ‚‚ h lemma le_iInfβ‚‚_add_iInfβ‚‚ {q₁ : ΞΉ β†’ Sort*} {qβ‚‚ : ΞΊ β†’ Sort*} {f : (i : ΞΉ) β†’ q₁ i β†’ ℝβ‰₯0∞} {g : (k : ΞΊ) β†’ qβ‚‚ k β†’ ℝβ‰₯0∞} (h : βˆ€ i pi k qk, a ≀ f i pi + g k qk) : a ≀ (β¨… (i) (qi), f i qi) + β¨… (k) (qk), g k qk := by simp_rw [iInfβ‚‚_add, add_iInfβ‚‚] exact le_iInfβ‚‚ fun i hi => le_iInfβ‚‚ (h i hi) @[simp] lemma iInf_gt_eq_self (a : ℝβ‰₯0∞) : β¨… b, β¨… _ : a < b, b = a := by refine le_antisymm ?_ (le_iInfβ‚‚ fun b hb ↦ hb.le) refine le_of_forall_gt fun c hac ↦ ?_ obtain ⟨d, had, hdc⟩ := exists_between hac exact (iInfβ‚‚_le_of_le d had le_rfl).trans_lt hdc lemma exists_add_lt_of_add_lt {x y z : ℝβ‰₯0∞} (h : y + z < x) : βˆƒ y' > y, βˆƒ z' > z, y' + z' < x := by contrapose! h simpa using le_iInfβ‚‚_add_iInfβ‚‚ h end iInf section iSup variable {ΞΉ ΞΊ : Sort*} {f g : ΞΉ β†’ ℝβ‰₯0∞} {s : Set ℝβ‰₯0∞} {a : ℝβ‰₯0∞} theorem toNNReal_iSup (hf : βˆ€ i, f i β‰  ∞) : (iSup f).toNNReal = ⨆ i, (f i).toNNReal := by lift f to ΞΉ β†’ ℝβ‰₯0 using hf simp_rw [toNNReal_coe] by_cases h : BddAbove (range f) Β· rw [← coe_iSup h, toNNReal_coe] Β· rw [NNReal.iSup_of_not_bddAbove h, iSup_coe_eq_top.2 h, toNNReal_top] theorem toNNReal_sSup (s : Set ℝβ‰₯0∞) (hs : βˆ€ r ∈ s, r β‰  ∞) : (sSup s).toNNReal = sSup (ENNReal.toNNReal '' s) := by have hf : βˆ€ i, ((↑) : s β†’ ℝβ‰₯0∞) i β‰  ∞ := fun ⟨r, rs⟩ => hs r rs simpa only [← sSup_range, ← image_eq_range, Subtype.range_coe_subtype] using (toNNReal_iSup hf) theorem toReal_iSup (hf : βˆ€ i, f i β‰  ∞) : (iSup f).toReal = ⨆ i, (f i).toReal := by simp only [ENNReal.toReal, toNNReal_iSup hf, NNReal.coe_iSup] theorem toReal_sSup (s : Set ℝβ‰₯0∞) (hf : βˆ€ r ∈ s, r β‰  ∞) : (sSup s).toReal = sSup (ENNReal.toReal '' s) := by simp only [ENNReal.toReal, toNNReal_sSup s hf, NNReal.coe_sSup, Set.image_image] theorem iSup_sub : (⨆ i, f i) - a = ⨆ i, f i - a := le_antisymm (tsub_le_iff_right.2 <| iSup_le fun i => tsub_le_iff_right.1 <| le_iSup (f Β· - a) i) (iSup_le fun _ => tsub_le_tsub (le_iSup _ _) (le_refl a)) @[simp] lemma iSup_eq_zero : ⨆ i, f i = 0 ↔ βˆ€ i, f i = 0 := iSup_eq_bot @[simp] lemma iSup_zero : ⨆ _ : ΞΉ, (0 : ℝβ‰₯0∞) = 0 := by simp lemma iSup_natCast : ⨆ n : β„•, (n : ℝβ‰₯0∞) = ∞ := (iSup_eq_top _).2 fun _b hb => ENNReal.exists_nat_gt (lt_top_iff_ne_top.1 hb) lemma add_iSup [Nonempty ΞΉ] (f : ΞΉ β†’ ℝβ‰₯0∞) : a + ⨆ i, f i = ⨆ i, a + f i := by obtain rfl | ha := eq_or_ne a ∞ Β· simp refine le_antisymm ?_ <| iSup_le fun i ↦ by grw [← le_iSup] refine add_le_of_le_tsub_left_of_le (le_iSup_of_le (Classical.arbitrary _) le_self_add) ?_ exact iSup_le fun i ↦ ENNReal.le_sub_of_add_le_left ha <| le_iSup (a + f Β·) i lemma iSup_add [Nonempty ΞΉ] (f : ΞΉ β†’ ℝβ‰₯0∞) : (⨆ i, f i) + a = ⨆ i, f i + a := by simp [add_comm, add_iSup] lemma add_biSup' {p : ΞΉ β†’ Prop} (h : βˆƒ i, p i) (f : ΞΉ β†’ ℝβ‰₯0∞) : a + ⨆ i, ⨆ _ : p i, f i = ⨆ i, ⨆ _ : p i, a + f i := by haveI : Nonempty {i // p i} := nonempty_subtype.2 h simp only [iSup_subtype', add_iSup] lemma biSup_add' {p : ΞΉ β†’ Prop} (h : βˆƒ i, p i) (f : ΞΉ β†’ ℝβ‰₯0∞) : (⨆ i, ⨆ _ : p i, f i) + a = ⨆ i, ⨆ _ : p i, f i + a := by simp only [add_comm, add_biSup' h] lemma add_biSup {ΞΉ : Type*} {s : Set ΞΉ} (hs : s.Nonempty) (f : ΞΉ β†’ ℝβ‰₯0∞) : a + ⨆ i ∈ s, f i = ⨆ i ∈ s, a + f i := add_biSup' hs _ lemma biSup_add {ΞΉ : Type*} {s : Set ΞΉ} (hs : s.Nonempty) (f : ΞΉ β†’ ℝβ‰₯0∞) : (⨆ i ∈ s, f i) + a = ⨆ i ∈ s, f i + a := biSup_add' hs _ lemma add_sSup (hs : s.Nonempty) : a + sSup s = ⨆ b ∈ s, a + b := by rw [sSup_eq_iSup, add_biSup hs] lemma sSup_add (hs : s.Nonempty) : sSup s + a = ⨆ b ∈ s, b + a := by rw [sSup_eq_iSup, biSup_add hs] lemma iSup_add_iSup_le [Nonempty ΞΉ] [Nonempty ΞΊ] {g : ΞΊ β†’ ℝβ‰₯0∞} (h : βˆ€ i j, f i + g j ≀ a) : iSup f + iSup g ≀ a := by simp_rw [iSup_add, add_iSup]; exact iSupβ‚‚_le h lemma biSup_add_biSup_le' {p : ΞΉ β†’ Prop} {q : ΞΊ β†’ Prop} (hp : βˆƒ i, p i) (hq : βˆƒ j, q j) {g : ΞΊ β†’ ℝβ‰₯0∞} (h : βˆ€ i, p i β†’ βˆ€ j, q j β†’ f i + g j ≀ a) : (⨆ i, ⨆ _ : p i, f i) + ⨆ j, ⨆ _ : q j, g j ≀ a := by simp_rw [biSup_add' hp, add_biSup' hq] exact iSupβ‚‚_le fun i hi => iSupβ‚‚_le (h i hi) lemma biSup_add_biSup_le {ΞΉ ΞΊ : Type*} {s : Set ΞΉ} {t : Set ΞΊ} (hs : s.Nonempty) (ht : t.Nonempty) {f : ΞΉ β†’ ℝβ‰₯0∞} {g : ΞΊ β†’ ℝβ‰₯0∞} {a : ℝβ‰₯0∞} (h : βˆ€ i ∈ s, βˆ€ j ∈ t, f i + g j ≀ a) : (⨆ i ∈ s, f i) + ⨆ j ∈ t, g j ≀ a := biSup_add_biSup_le' hs ht h lemma iSup_add_iSup (h : βˆ€ i j, βˆƒ k, f i + g j ≀ f k + g k) : iSup f + iSup g = ⨆ i, f i + g i := by cases isEmpty_or_nonempty ΞΉ Β· simp only [iSup_of_empty, bot_eq_zero, zero_add] Β· refine le_antisymm ?_ (iSup_le fun a => add_le_add (le_iSup _ _) (le_iSup _ _)) refine iSup_add_iSup_le fun i j => ?_ rcases h i j with ⟨k, hk⟩ exact le_iSup_of_le k hk lemma iSup_add_iSup_of_monotone {ΞΉ : Type*} [Preorder ΞΉ] [IsDirected ΞΉ (Β· ≀ Β·)] {f g : ΞΉ β†’ ℝβ‰₯0∞} (hf : Monotone f) (hg : Monotone g) : iSup f + iSup g = ⨆ a, f a + g a := iSup_add_iSup fun i j ↦ (exists_ge_ge i j).imp fun _k ⟨hi, hj⟩ ↦ by gcongr <;> apply_rules lemma sub_iSup [Nonempty ΞΉ] (ha : a β‰  ∞) : a - ⨆ i, f i = β¨… i, a - f i := by obtain ⟨i, hi⟩ | h := em (βˆƒ i, a < f i) Β· rw [tsub_eq_zero_iff_le.2 <| le_iSup_of_le _ hi.le, (iInf_eq_bot _).2, bot_eq_zero] exact fun x hx ↦ ⟨i, by simpa [hi.le, tsub_eq_zero_of_le]⟩ simp_rw [not_exists, not_lt] at h refine le_antisymm (le_iInf fun i ↦ tsub_le_tsub_left (le_iSup ..) _) <| ENNReal.le_sub_of_add_le_left (ne_top_of_le_ne_top ha <| iSup_le h) <| add_le_of_le_tsub_right_of_le (iInf_le_of_le (Classical.arbitrary _) tsub_le_self) <| iSup_le fun i ↦ ?_ rw [← sub_sub_cancel ha (h _)] exact tsub_le_tsub_left (iInf_le (a - f Β·) i) _ @[simp] lemma iSup_lt_eq_self (a : ℝβ‰₯0∞) : ⨆ b, ⨆ _ : b < a, b = a := by refine le_antisymm (iSupβ‚‚_le fun b hb ↦ hb.le) ?_ refine le_of_forall_lt fun c hca ↦ ?_ obtain ⟨d, hcd, hdb⟩ := exists_between hca exact hcd.trans_le <| le_iSupβ‚‚_of_le d hdb le_rfl -- TODO: Prove the two one-side versions lemma exists_lt_add_of_lt_add {x y z : ℝβ‰₯0∞} (h : x < y + z) (hy : y β‰  0) (hz : z β‰  0) : βˆƒ y' < y, βˆƒ z' < z, x < y' + z' := by contrapose! h simpa using biSup_add_biSup_le' (by exact ⟨0, hy.bot_lt⟩) (by exact ⟨0, hz.bot_lt⟩) h end iSup end ENNReal
.lake/packages/mathlib/Mathlib/Data/ENNReal/Action.lean
import Mathlib.Data.ENNReal.Operations /-! # Scalar multiplication on `ℝβ‰₯0∞`. This file defines basic scalar actions on extended nonnegative reals, showing that `MulAction`s, `DistribMulAction`s, `Module`s and `Algebra`s restrict from `ℝβ‰₯0∞` to `ℝβ‰₯0`. -/ open Set NNReal ENNReal namespace ENNReal variable {a b c d : ℝβ‰₯0∞} {r p q : ℝβ‰₯0} -- TODO: generalize some of these to `WithTop Ξ±` section Actions /-- A `MulAction` over `ℝβ‰₯0∞` restricts to a `MulAction` over `ℝβ‰₯0`. -/ noncomputable instance {M : Type*} [MulAction ℝβ‰₯0∞ M] : MulAction ℝβ‰₯0 M := MulAction.compHom M ofNNRealHom.toMonoidHom theorem smul_def {M : Type*} [MulAction ℝβ‰₯0∞ M] (c : ℝβ‰₯0) (x : M) : c β€’ x = (c : ℝβ‰₯0∞) β€’ x := rfl instance {M N : Type*} [MulAction ℝβ‰₯0∞ M] [MulAction ℝβ‰₯0∞ N] [SMul M N] [IsScalarTower ℝβ‰₯0∞ M N] : IsScalarTower ℝβ‰₯0 M N where smul_assoc r := smul_assoc (r : ℝβ‰₯0∞) instance smulCommClass_left {M N : Type*} [MulAction ℝβ‰₯0∞ N] [SMul M N] [SMulCommClass ℝβ‰₯0∞ M N] : SMulCommClass ℝβ‰₯0 M N where smul_comm r := smul_comm (r : ℝβ‰₯0∞) instance smulCommClass_right {M N : Type*} [MulAction ℝβ‰₯0∞ N] [SMul M N] [SMulCommClass M ℝβ‰₯0∞ N] : SMulCommClass M ℝβ‰₯0 N where smul_comm m r := smul_comm m (r : ℝβ‰₯0∞) /-- A `DistribMulAction` over `ℝβ‰₯0∞` restricts to a `DistribMulAction` over `ℝβ‰₯0`. -/ noncomputable instance {M : Type*} [AddMonoid M] [DistribMulAction ℝβ‰₯0∞ M] : DistribMulAction ℝβ‰₯0 M := DistribMulAction.compHom M ofNNRealHom.toMonoidHom /-- A `Module` over `ℝβ‰₯0∞` restricts to a `Module` over `ℝβ‰₯0`. -/ noncomputable instance {M : Type*} [AddCommMonoid M] [Module ℝβ‰₯0∞ M] : Module ℝβ‰₯0 M := Module.compHom M ofNNRealHom /-- An `Algebra` over `ℝβ‰₯0∞` restricts to an `Algebra` over `ℝβ‰₯0`. -/ noncomputable instance {A : Type*} [Semiring A] [Algebra ℝβ‰₯0∞ A] : Algebra ℝβ‰₯0 A where commutes' r x := by simp [Algebra.commutes] smul_def' r x := by simp [← Algebra.smul_def (r : ℝβ‰₯0∞) x, smul_def] algebraMap := (algebraMap ℝβ‰₯0∞ A).comp (ofNNRealHom : ℝβ‰₯0 β†’+* ℝβ‰₯0∞) -- verify that the above produces instances we might care about noncomputable example : Algebra ℝβ‰₯0 ℝβ‰₯0∞ := inferInstance noncomputable example : DistribMulAction ℝβ‰₯0Λ£ ℝβ‰₯0∞ := inferInstance theorem coe_smul {R} (r : R) (s : ℝβ‰₯0) [SMul R ℝβ‰₯0] [SMul R ℝβ‰₯0∞] [IsScalarTower R ℝβ‰₯0 ℝβ‰₯0] [IsScalarTower R ℝβ‰₯0 ℝβ‰₯0∞] : (↑(r β€’ s) : ℝβ‰₯0∞) = (r : R) β€’ (s : ℝβ‰₯0∞) := by rw [← smul_one_smul ℝβ‰₯0 r (s : ℝβ‰₯0∞), smul_def, smul_eq_mul, ← ENNReal.coe_mul, smul_mul_assoc, one_mul] theorem smul_top {R} [Zero R] [SMulWithZero R ℝβ‰₯0∞] [IsScalarTower R ℝβ‰₯0∞ ℝβ‰₯0∞] [NoZeroSMulDivisors R ℝβ‰₯0∞] [DecidableEq R] (c : R) : c β€’ ∞ = if c = 0 then 0 else ∞ := by rw [← smul_one_mul, mul_top'] simp_rw [smul_eq_zero, or_iff_left one_ne_zero] lemma nnreal_smul_lt_top {x : ℝβ‰₯0} {y : ℝβ‰₯0∞} (hy : y < ⊀) : x β€’ y < ⊀ := mul_lt_top (by simp) hy lemma nnreal_smul_ne_top {x : ℝβ‰₯0} {y : ℝβ‰₯0∞} (hy : y β‰  ⊀) : x β€’ y β‰  ⊀ := mul_ne_top (by simp) hy lemma nnreal_smul_ne_top_iff {x : ℝβ‰₯0} {y : ℝβ‰₯0∞} (hx : x β‰  0) : x β€’ y β‰  ⊀ ↔ y β‰  ⊀ := ⟨by rintro h rfl; simp [smul_top, hx] at h, nnreal_smul_ne_top⟩ lemma nnreal_smul_lt_top_iff {x : ℝβ‰₯0} {y : ℝβ‰₯0∞} (hx : x β‰  0) : x β€’ y < ⊀ ↔ y < ⊀ := by rw [lt_top_iff_ne_top, lt_top_iff_ne_top, nnreal_smul_ne_top_iff hx] @[simp] theorem smul_toNNReal (a : ℝβ‰₯0) (b : ℝβ‰₯0∞) : (a β€’ b).toNNReal = a * b.toNNReal := by change ((a : ℝβ‰₯0∞) * b).toNNReal = a * b.toNNReal simp only [ENNReal.toNNReal_mul, ENNReal.toNNReal_coe] theorem toReal_smul (r : ℝβ‰₯0) (s : ℝβ‰₯0∞) : (r β€’ s).toReal = r β€’ s.toReal := by rw [ENNReal.smul_def, smul_eq_mul, toReal_mul, coe_toReal] rfl instance : PosSMulStrictMono ℝβ‰₯0 ℝβ‰₯0∞ where smul_lt_smul_of_pos_left _r hr _a _b hab := ENNReal.mul_lt_mul_left' (coe_pos.2 hr).ne' coe_ne_top hab instance : SMulPosMono ℝβ‰₯0 ℝβ‰₯0∞ where smul_le_smul_of_nonneg_right _r _ _a _b hab := mul_le_mul_right' (coe_le_coe.2 hab) _ end Actions end ENNReal
.lake/packages/mathlib/Mathlib/Data/ENNReal/BigOperators.lean
import Mathlib.Algebra.BigOperators.WithTop import Mathlib.Data.NNReal.Basic import Mathlib.Data.ENNReal.Inv /-! # Properties of big operators extended non-negative real numbers In this file we prove elementary properties of sums and products on `ℝβ‰₯0∞`, as well as how these interact with the order structure on `ℝβ‰₯0∞`. -/ open Set NNReal ENNReal namespace ENNReal variable {a b c d : ℝβ‰₯0∞} {r p q : ℝβ‰₯0} section OperationsAndInfty variable {Ξ± : Type*} @[simp, norm_cast] theorem coe_finset_sum {s : Finset Ξ±} {f : Ξ± β†’ ℝβ‰₯0} : ↑(βˆ‘ a ∈ s, f a) = βˆ‘ a ∈ s, (f a : ℝβ‰₯0∞) := map_sum ofNNRealHom f s @[simp, norm_cast] theorem coe_finset_prod {s : Finset Ξ±} {f : Ξ± β†’ ℝβ‰₯0} : ↑(∏ a ∈ s, f a) = ∏ a ∈ s, (f a : ℝβ‰₯0∞) := map_prod ofNNRealHom f s @[simp] theorem toNNReal_prod {ΞΉ : Type*} {s : Finset ΞΉ} {f : ΞΉ β†’ ℝβ‰₯0∞} : (∏ i ∈ s, f i).toNNReal = ∏ i ∈ s, (f i).toNNReal := map_prod toNNRealHom _ _ @[simp] theorem toReal_prod {ΞΉ : Type*} {s : Finset ΞΉ} {f : ΞΉ β†’ ℝβ‰₯0∞} : (∏ i ∈ s, f i).toReal = ∏ i ∈ s, (f i).toReal := map_prod toRealHom _ _ theorem ofReal_prod_of_nonneg {Ξ± : Type*} {s : Finset Ξ±} {f : Ξ± β†’ ℝ} (hf : βˆ€ i, i ∈ s β†’ 0 ≀ f i) : ENNReal.ofReal (∏ i ∈ s, f i) = ∏ i ∈ s, ENNReal.ofReal (f i) := by simp_rw [ENNReal.ofReal, ← coe_finset_prod, coe_inj] exact Real.toNNReal_prod_of_nonneg hf theorem iInf_sum {ΞΉ Ξ± : Type*} {f : ΞΉ β†’ Ξ± β†’ ℝβ‰₯0∞} {s : Finset Ξ±} [Nonempty ΞΉ] (h : βˆ€ (t : Finset Ξ±) (i j : ΞΉ), βˆƒ k, βˆ€ a ∈ t, f k a ≀ f i a ∧ f k a ≀ f j a) : β¨… i, βˆ‘ a ∈ s, f i a = βˆ‘ a ∈ s, β¨… i, f i a := by induction s using Finset.cons_induction_on with | empty => simp only [Finset.sum_empty, ciInf_const] | cons a s ha ih => simp only [Finset.sum_cons, ← ih] refine (iInf_add_iInf fun i j => ?_).symm refine (h (Finset.cons a s ha) i j).imp fun k hk => ?_ rw [Finset.forall_mem_cons] at hk exact add_le_add hk.1.1 (Finset.sum_le_sum fun a ha => (hk.2 a ha).2) end OperationsAndInfty section Sum open Finset variable {Ξ± : Type*} {s : Finset Ξ±} {f : Ξ± β†’ ℝβ‰₯0∞} /-- A product of finite numbers is still finite. -/ lemma prod_ne_top (h : βˆ€ a ∈ s, f a β‰  ∞) : ∏ a ∈ s, f a β‰  ∞ := WithTop.prod_ne_top h /-- A product of finite numbers is still finite. -/ lemma prod_lt_top (h : βˆ€ a ∈ s, f a < ∞) : ∏ a ∈ s, f a < ∞ := WithTop.prod_lt_top h /-- A sum is infinite iff one of the summands is infinite. -/ @[simp] lemma sum_eq_top : βˆ‘ x ∈ s, f x = ∞ ↔ βˆƒ a ∈ s, f a = ∞ := WithTop.sum_eq_top /-- A sum is finite iff all summands are finite. -/ lemma sum_ne_top : βˆ‘ a ∈ s, f a β‰  ∞ ↔ βˆ€ a ∈ s, f a β‰  ∞ := WithTop.sum_ne_top /-- A sum is finite iff all summands are finite. -/ @[simp] lemma sum_lt_top : βˆ‘ a ∈ s, f a < ∞ ↔ βˆ€ a ∈ s, f a < ∞ := WithTop.sum_lt_top theorem lt_top_of_sum_ne_top {s : Finset Ξ±} {f : Ξ± β†’ ℝβ‰₯0∞} (h : βˆ‘ x ∈ s, f x β‰  ∞) {a : Ξ±} (ha : a ∈ s) : f a < ∞ := sum_lt_top.1 h.lt_top a ha /-- Seeing `ℝβ‰₯0∞` as `ℝβ‰₯0` does not change their sum, unless one of the `ℝβ‰₯0∞` is infinity -/ theorem toNNReal_sum {s : Finset Ξ±} {f : Ξ± β†’ ℝβ‰₯0∞} (hf : βˆ€ a ∈ s, f a β‰  ∞) : ENNReal.toNNReal (βˆ‘ a ∈ s, f a) = βˆ‘ a ∈ s, ENNReal.toNNReal (f a) := by rw [← coe_inj, coe_toNNReal, coe_finset_sum, sum_congr rfl] Β· intro x hx exact (coe_toNNReal (hf x hx)).symm Β· exact sum_ne_top.2 hf /-- seeing `ℝβ‰₯0∞` as `Real` does not change their sum, unless one of the `ℝβ‰₯0∞` is infinity -/ theorem toReal_sum {s : Finset Ξ±} {f : Ξ± β†’ ℝβ‰₯0∞} (hf : βˆ€ a ∈ s, f a β‰  ∞) : ENNReal.toReal (βˆ‘ a ∈ s, f a) = βˆ‘ a ∈ s, ENNReal.toReal (f a) := by rw [ENNReal.toReal, toNNReal_sum hf, NNReal.coe_sum] rfl theorem ofReal_sum_of_nonneg {s : Finset Ξ±} {f : Ξ± β†’ ℝ} (hf : βˆ€ i, i ∈ s β†’ 0 ≀ f i) : ENNReal.ofReal (βˆ‘ i ∈ s, f i) = βˆ‘ i ∈ s, ENNReal.ofReal (f i) := by simp_rw [ENNReal.ofReal, ← coe_finset_sum, coe_inj] exact Real.toNNReal_sum_of_nonneg hf theorem sum_lt_sum_of_nonempty {s : Finset Ξ±} (hs : s.Nonempty) {f g : Ξ± β†’ ℝβ‰₯0∞} (Hlt : βˆ€ i ∈ s, f i < g i) : βˆ‘ i ∈ s, f i < βˆ‘ i ∈ s, g i := by induction hs using Finset.Nonempty.cons_induction with | singleton => simp [Hlt _ (Finset.mem_singleton_self _)] | cons _ _ _ _ ih => simp only [Finset.sum_cons, forall_mem_cons] at Hlt ⊒ exact ENNReal.add_lt_add Hlt.1 (ih Hlt.2) theorem exists_le_of_sum_le {s : Finset Ξ±} (hs : s.Nonempty) {f g : Ξ± β†’ ℝβ‰₯0∞} (Hle : βˆ‘ i ∈ s, f i ≀ βˆ‘ i ∈ s, g i) : βˆƒ i ∈ s, f i ≀ g i := by contrapose! Hle apply ENNReal.sum_lt_sum_of_nonempty hs Hle end Sum section Inv lemma prod_inv_distrib {ΞΉ : Type*} {f : ΞΉ β†’ ℝβ‰₯0∞} {s : Finset ΞΉ} (hf : (s : Set ΞΉ).Pairwise fun i j ↦ f i β‰  0 ∨ f j β‰  ∞) : (∏ i ∈ s, f i)⁻¹ = ∏ i ∈ s, (f i)⁻¹ := by induction s using Finset.cons_induction with | empty => simp | cons i s hi ih => ?_ simp only [Finset.prod_cons, ← ih (hf.mono <| by simp)] refine ENNReal.mul_inv (not_or_of_imp fun hiβ‚€ ↦ prod_ne_top fun j hj ↦ ?_) (not_or_of_imp fun hiβ‚€ ↦ Finset.prod_ne_zero_iff.2 fun j hj ↦ ?_) Β· exact imp_iff_not_or.2 (hf (by simp) (by simp [hj]) <| .symm <| ne_of_mem_of_not_mem hj hi) hiβ‚€ Β· exact imp_iff_not_or.2 (hf (by simp [hj]) (by simp) <| ne_of_mem_of_not_mem hj hi).symm hiβ‚€ lemma finsetSum_iSup {Ξ± ΞΉ : Type*} {s : Finset Ξ±} {f : Ξ± β†’ ΞΉ β†’ ℝβ‰₯0∞} (hf : βˆ€ i j, βˆƒ k, βˆ€ a, f a i ≀ f a k ∧ f a j ≀ f a k) : βˆ‘ a ∈ s, ⨆ i, f a i = ⨆ i, βˆ‘ a ∈ s, f a i := by induction s using Finset.cons_induction with | empty => simp | cons a s ha ihs => simp_rw [Finset.sum_cons, ihs] refine iSup_add_iSup fun i j ↦ (hf i j).imp fun k hk ↦ ?_ gcongr exacts [(hk a).1, (hk _).2] lemma finsetSum_iSup_of_monotone {Ξ± ΞΉ : Type*} [Preorder ΞΉ] [IsDirected ΞΉ (Β· ≀ Β·)] {s : Finset Ξ±} {f : Ξ± β†’ ΞΉ β†’ ℝβ‰₯0∞} (hf : βˆ€ a, Monotone (f a)) : (βˆ‘ a ∈ s, iSup (f a)) = ⨆ n, βˆ‘ a ∈ s, f a n := finsetSum_iSup fun i j ↦ (exists_ge_ge i j).imp fun _k ⟨hi, hj⟩ a ↦ ⟨hf a hi, hf a hj⟩ end Inv end ENNReal
.lake/packages/mathlib/Mathlib/Data/ENNReal/Inv.lean
import Mathlib.Data.ENNReal.Operations /-! # Results about division in extended non-negative reals This file establishes basic properties related to the inversion and division operations on `ℝβ‰₯0∞`. For instance, as a consequence of being a `DivInvOneMonoid`, `ℝβ‰₯0∞` inherits a power operation with integer exponent. ## Main results A few order isomorphisms are worthy of mention: - `OrderIso.invENNReal : ℝβ‰₯0∞ ≃o ℝβ‰₯0βˆžα΅’α΅ˆ`: The map `x ↦ x⁻¹` as an order isomorphism to the dual. - `orderIsoIicOneBirational : ℝβ‰₯0∞ ≃o Iic (1 : ℝβ‰₯0∞)`: The birational order isomorphism between `ℝβ‰₯0∞` and the unit interval `Set.Iic (1 : ℝβ‰₯0∞)` given by `x ↦ (x⁻¹ + 1)⁻¹` with inverse `x ↦ (x⁻¹ - 1)⁻¹` - `orderIsoIicCoe (a : ℝβ‰₯0) : Iic (a : ℝβ‰₯0∞) ≃o Iic a`: Order isomorphism between an initial interval in `ℝβ‰₯0∞` and an initial interval in `ℝβ‰₯0` given by the identity map. - `orderIsoUnitIntervalBirational : ℝβ‰₯0∞ ≃o Icc (0 : ℝ) 1`: An order isomorphism between the extended nonnegative real numbers and the unit interval. This is `orderIsoIicOneBirational` composed with the identity order isomorphism between `Iic (1 : ℝβ‰₯0∞)` and `Icc (0 : ℝ) 1`. -/ assert_not_exists Finset open Set NNReal namespace ENNReal noncomputable section Inv variable {a b c d : ℝβ‰₯0∞} {r p q : ℝβ‰₯0} protected theorem div_eq_inv_mul : a / b = b⁻¹ * a := by rw [div_eq_mul_inv, mul_comm] @[simp] theorem inv_zero : (0 : ℝβ‰₯0∞)⁻¹ = ∞ := show sInf { b : ℝβ‰₯0∞ | 1 ≀ 0 * b } = ∞ by simp @[simp] theorem inv_top : ∞⁻¹ = 0 := bot_unique <| le_of_forall_gt_imp_ge_of_dense fun a (h : 0 < a) => sInf_le <| by simp [*, h.ne', top_mul] theorem coe_inv_le : (↑r⁻¹ : ℝβ‰₯0∞) ≀ (↑r)⁻¹ := le_sInf fun b (hb : 1 ≀ ↑r * b) => coe_le_iff.2 <| by rintro b rfl apply NNReal.inv_le_of_le_mul rwa [← coe_mul, ← coe_one, coe_le_coe] at hb @[simp, norm_cast] theorem coe_inv (hr : r β‰  0) : (↑r⁻¹ : ℝβ‰₯0∞) = (↑r)⁻¹ := coe_inv_le.antisymm <| sInf_le <| mem_setOf.2 <| by rw [← coe_mul, mul_inv_cancelβ‚€ hr, coe_one] @[norm_cast] theorem coe_inv_two : ((2⁻¹ : ℝβ‰₯0) : ℝβ‰₯0∞) = 2⁻¹ := by rw [coe_inv _root_.two_ne_zero, coe_two] @[simp, norm_cast] theorem coe_div (hr : r β‰  0) : (↑(p / r) : ℝβ‰₯0∞) = p / r := by rw [div_eq_mul_inv, div_eq_mul_inv, coe_mul, coe_inv hr] lemma coe_div_le : ↑(p / r) ≀ (p / r : ℝβ‰₯0∞) := by simpa only [div_eq_mul_inv, coe_mul] using mul_le_mul_left' coe_inv_le _ theorem div_zero (h : a β‰  0) : a / 0 = ∞ := by simp [div_eq_mul_inv, h] instance : DivInvOneMonoid ℝβ‰₯0∞ := { inferInstanceAs (DivInvMonoid ℝβ‰₯0∞) with inv_one := by simpa only [coe_inv one_ne_zero, coe_one] using coe_inj.2 inv_one } protected theorem inv_pow : βˆ€ {a : ℝβ‰₯0∞} {n : β„•}, (a ^ n)⁻¹ = a⁻¹ ^ n | _, 0 => by simp only [pow_zero, inv_one] | ⊀, n + 1 => by simp [top_pow] | (a : ℝβ‰₯0), n + 1 => by rcases eq_or_ne a 0 with (rfl | ha) Β· simp [top_pow] Β· have := pow_ne_zero (n + 1) ha norm_cast rw [inv_pow] protected theorem mul_inv_cancel (h0 : a β‰  0) (ht : a β‰  ∞) : a * a⁻¹ = 1 := by lift a to ℝβ‰₯0 using ht norm_cast at h0; norm_cast exact mul_inv_cancelβ‚€ h0 protected theorem inv_mul_cancel (h0 : a β‰  0) (ht : a β‰  ∞) : a⁻¹ * a = 1 := mul_comm a a⁻¹ β–Έ ENNReal.mul_inv_cancel h0 ht /-- See `ENNReal.inv_mul_cancel_left` for a simpler version assuming `a β‰  0`, `a β‰  ∞`. -/ protected lemma inv_mul_cancel_left' (haβ‚€ : a = 0 β†’ b = 0) (ha : a = ∞ β†’ b = 0) : a⁻¹ * (a * b) = b := by obtain rfl | haβ‚€ := eq_or_ne a 0 Β· simp_all obtain rfl | ha := eq_or_ne a ⊀ Β· simp_all Β· simp [← mul_assoc, ENNReal.inv_mul_cancel, *] /-- See `ENNReal.inv_mul_cancel_left'` for a stronger version. -/ protected lemma inv_mul_cancel_left (haβ‚€ : a β‰  0) (ha : a β‰  ∞) : a⁻¹ * (a * b) = b := ENNReal.inv_mul_cancel_left' (by simp [haβ‚€]) (by simp [ha]) /-- See `ENNReal.mul_inv_cancel_left` for a simpler version assuming `a β‰  0`, `a β‰  ∞`. -/ protected lemma mul_inv_cancel_left' (haβ‚€ : a = 0 β†’ b = 0) (ha : a = ∞ β†’ b = 0) : a * (a⁻¹ * b) = b := by obtain rfl | haβ‚€ := eq_or_ne a 0 Β· simp_all obtain rfl | ha := eq_or_ne a ⊀ Β· simp_all Β· simp [← mul_assoc, ENNReal.mul_inv_cancel, *] /-- See `ENNReal.mul_inv_cancel_left'` for a stronger version. -/ protected lemma mul_inv_cancel_left (haβ‚€ : a β‰  0) (ha : a β‰  ∞) : a * (a⁻¹ * b) = b := ENNReal.mul_inv_cancel_left' (by simp [haβ‚€]) (by simp [ha]) /-- See `ENNReal.mul_inv_cancel_right` for a simpler version assuming `b β‰  0`, `b β‰  ∞`. -/ protected lemma mul_inv_cancel_right' (hbβ‚€ : b = 0 β†’ a = 0) (hb : b = ∞ β†’ a = 0) : a * b * b⁻¹ = a := by obtain rfl | hbβ‚€ := eq_or_ne b 0 Β· simp_all obtain rfl | hb := eq_or_ne b ⊀ Β· simp_all Β· simp [mul_assoc, ENNReal.mul_inv_cancel, *] /-- See `ENNReal.mul_inv_cancel_right'` for a stronger version. -/ protected lemma mul_inv_cancel_right (hbβ‚€ : b β‰  0) (hb : b β‰  ∞) : a * b * b⁻¹ = a := ENNReal.mul_inv_cancel_right' (by simp [hbβ‚€]) (by simp [hb]) /-- See `ENNReal.inv_mul_cancel_right` for a simpler version assuming `b β‰  0`, `b β‰  ∞`. -/ protected lemma inv_mul_cancel_right' (hbβ‚€ : b = 0 β†’ a = 0) (hb : b = ∞ β†’ a = 0) : a * b⁻¹ * b = a := by obtain rfl | hbβ‚€ := eq_or_ne b 0 Β· simp_all obtain rfl | hb := eq_or_ne b ⊀ Β· simp_all Β· simp [mul_assoc, ENNReal.inv_mul_cancel, *] /-- See `ENNReal.inv_mul_cancel_right'` for a stronger version. -/ protected lemma inv_mul_cancel_right (hbβ‚€ : b β‰  0) (hb : b β‰  ∞) : a * b⁻¹ * b = a := ENNReal.inv_mul_cancel_right' (by simp [hbβ‚€]) (by simp [hb]) /-- See `ENNReal.mul_div_cancel_right` for a simpler version assuming `b β‰  0`, `b β‰  ∞`. -/ protected lemma mul_div_cancel_right' (hbβ‚€ : b = 0 β†’ a = 0) (hb : b = ∞ β†’ a = 0) : a * b / b = a := ENNReal.mul_inv_cancel_right' hbβ‚€ hb /-- See `ENNReal.mul_div_cancel_right'` for a stronger version. -/ protected lemma mul_div_cancel_right (hbβ‚€ : b β‰  0) (hb : b β‰  ∞) : a * b / b = a := ENNReal.mul_div_cancel_right' (by simp [hbβ‚€]) (by simp [hb]) /-- See `ENNReal.div_mul_cancel` for a simpler version assuming `a β‰  0`, `a β‰  ∞`. -/ protected lemma div_mul_cancel' (haβ‚€ : a = 0 β†’ b = 0) (ha : a = ∞ β†’ b = 0) : b / a * a = b := ENNReal.inv_mul_cancel_right' haβ‚€ ha /-- See `ENNReal.div_mul_cancel'` for a stronger version. -/ protected lemma div_mul_cancel (haβ‚€ : a β‰  0) (ha : a β‰  ∞) : b / a * a = b := ENNReal.div_mul_cancel' (by simp [haβ‚€]) (by simp [ha]) /-- See `ENNReal.mul_div_cancel` for a simpler version assuming `a β‰  0`, `a β‰  ∞`. -/ protected lemma mul_div_cancel' (haβ‚€ : a = 0 β†’ b = 0) (ha : a = ∞ β†’ b = 0) : a * (b / a) = b := by rw [mul_comm, ENNReal.div_mul_cancel' haβ‚€ ha] /-- See `ENNReal.mul_div_cancel'` for a stronger version. -/ protected lemma mul_div_cancel (haβ‚€ : a β‰  0) (ha : a β‰  ∞) : a * (b / a) = b := ENNReal.mul_div_cancel' (by simp [haβ‚€]) (by simp [ha]) protected theorem mul_comm_div : a / b * c = a * (c / b) := by simp only [div_eq_mul_inv, mul_left_comm, mul_comm] protected theorem mul_div_right_comm : a * b / c = a / c * b := by simp only [div_eq_mul_inv, mul_right_comm] instance : InvolutiveInv ℝβ‰₯0∞ where inv_inv a := by by_cases a = 0 <;> cases a <;> simp_all [-coe_inv, (coe_inv _).symm] @[simp] protected lemma inv_eq_one : a⁻¹ = 1 ↔ a = 1 := by rw [← inv_inj, inv_inv, inv_one] @[simp] theorem inv_eq_top : a⁻¹ = ∞ ↔ a = 0 := inv_zero β–Έ inv_inj theorem inv_ne_top : a⁻¹ β‰  ∞ ↔ a β‰  0 := by simp @[aesop (rule_sets := [finiteness]) safe apply] protected alias ⟨_, Finiteness.inv_ne_top⟩ := ENNReal.inv_ne_top @[simp] theorem inv_lt_top {x : ℝβ‰₯0∞} : x⁻¹ < ∞ ↔ 0 < x := by simp only [lt_top_iff_ne_top, inv_ne_top, pos_iff_ne_zero] theorem div_lt_top {x y : ℝβ‰₯0∞} (h1 : x β‰  ∞) (h2 : y β‰  0) : x / y < ∞ := mul_lt_top h1.lt_top (inv_ne_top.mpr h2).lt_top @[aesop (rule_sets := [finiteness]) safe apply] theorem div_ne_top {x y : ℝβ‰₯0∞} (h1 : x β‰  ∞) (h2 : y β‰  0) : x / y β‰  ∞ := (div_lt_top h1 h2).ne @[simp] protected theorem inv_eq_zero : a⁻¹ = 0 ↔ a = ∞ := inv_top β–Έ inv_inj protected theorem inv_ne_zero : a⁻¹ β‰  0 ↔ a β‰  ∞ := by simp protected theorem div_pos (ha : a β‰  0) (hb : b β‰  ∞) : 0 < a / b := ENNReal.mul_pos ha <| ENNReal.inv_ne_zero.2 hb protected theorem inv_mul_le_iff {x y z : ℝβ‰₯0∞} (h1 : x β‰  0) (h2 : x β‰  ∞) : x⁻¹ * y ≀ z ↔ y ≀ x * z := by rw [← mul_le_mul_left h1 h2, ← mul_assoc, ENNReal.mul_inv_cancel h1 h2, one_mul] protected theorem mul_inv_le_iff {x y z : ℝβ‰₯0∞} (h1 : y β‰  0) (h2 : y β‰  ∞) : x * y⁻¹ ≀ z ↔ x ≀ z * y := by rw [mul_comm, ENNReal.inv_mul_le_iff h1 h2, mul_comm] protected theorem div_le_iff {x y z : ℝβ‰₯0∞} (h1 : y β‰  0) (h2 : y β‰  ∞) : x / y ≀ z ↔ x ≀ z * y := by rw [div_eq_mul_inv, ENNReal.mul_inv_le_iff h1 h2] protected theorem div_le_iff' {x y z : ℝβ‰₯0∞} (h1 : y β‰  0) (h2 : y β‰  ∞) : x / y ≀ z ↔ x ≀ y * z := by rw [mul_comm, ENNReal.div_le_iff h1 h2] protected theorem mul_inv {a b : ℝβ‰₯0∞} (ha : a β‰  0 ∨ b β‰  ∞) (hb : a β‰  ∞ ∨ b β‰  0) : (a * b)⁻¹ = a⁻¹ * b⁻¹ := by cases b case top => grind [mul_top, mul_zero, inv_top, ENNReal.inv_eq_zero] cases a case top => grind [top_mul, zero_mul, inv_top, ENNReal.inv_eq_zero] grind [_=_ coe_mul, coe_zero, inv_zero, = mul_inv, coe_ne_top, ENNReal.inv_eq_zero, =_ coe_inv, zero_mul, = mul_eq_zero, mul_top, mul_zero, top_mul] protected theorem inv_div {a b : ℝβ‰₯0∞} (htop : b β‰  ∞ ∨ a β‰  ∞) (hzero : b β‰  0 ∨ a β‰  0) : (a / b)⁻¹ = b / a := by rw [← ENNReal.inv_ne_zero] at htop rw [← ENNReal.inv_ne_top] at hzero rw [ENNReal.div_eq_inv_mul, ENNReal.div_eq_inv_mul, ENNReal.mul_inv htop hzero, mul_comm, inv_inv] protected theorem mul_div_mul_left (a b : ℝβ‰₯0∞) (hc : c β‰  0) (hc' : c β‰  ⊀) : c * a / (c * b) = a / b := by rw [div_eq_mul_inv, div_eq_mul_inv, ENNReal.mul_inv (Or.inl hc) (Or.inl hc'), mul_mul_mul_comm, ENNReal.mul_inv_cancel hc hc', one_mul] protected theorem mul_div_mul_right (a b : ℝβ‰₯0∞) (hc : c β‰  0) (hc' : c β‰  ⊀) : a * c / (b * c) = a / b := by rw [div_eq_mul_inv, div_eq_mul_inv, ENNReal.mul_inv (Or.inr hc') (Or.inr hc), mul_mul_mul_comm, ENNReal.mul_inv_cancel hc hc', mul_one] protected theorem sub_div (h : 0 < b β†’ b < a β†’ c β‰  0) : (a - b) / c = a / c - b / c := by simp_rw [div_eq_mul_inv] exact ENNReal.sub_mul (by simpa using h) @[simp] protected theorem inv_pos : 0 < a⁻¹ ↔ a β‰  ∞ := pos_iff_ne_zero.trans ENNReal.inv_ne_zero theorem inv_strictAnti : StrictAnti (Inv.inv : ℝβ‰₯0∞ β†’ ℝβ‰₯0∞) := by intro a b h lift a to ℝβ‰₯0 using h.ne_top cases b; Β· simp rw [coe_lt_coe] at h rcases eq_or_ne a 0 with (rfl | ha); Β· simp [h] rw [← coe_inv h.ne_bot, ← coe_inv ha, coe_lt_coe] exact NNReal.inv_lt_inv ha h @[simp] protected theorem inv_lt_inv : a⁻¹ < b⁻¹ ↔ b < a := inv_strictAnti.lt_iff_gt theorem inv_lt_iff_inv_lt : a⁻¹ < b ↔ b⁻¹ < a := by simpa only [inv_inv] using @ENNReal.inv_lt_inv a b⁻¹ theorem lt_inv_iff_lt_inv : a < b⁻¹ ↔ b < a⁻¹ := by simpa only [inv_inv] using @ENNReal.inv_lt_inv a⁻¹ b @[simp] protected theorem inv_le_inv : a⁻¹ ≀ b⁻¹ ↔ b ≀ a := inv_strictAnti.le_iff_ge theorem inv_le_iff_inv_le : a⁻¹ ≀ b ↔ b⁻¹ ≀ a := by simpa only [inv_inv] using @ENNReal.inv_le_inv a b⁻¹ theorem le_inv_iff_le_inv : a ≀ b⁻¹ ↔ b ≀ a⁻¹ := by simpa only [inv_inv] using @ENNReal.inv_le_inv a⁻¹ b @[gcongr] protected theorem inv_le_inv' (h : a ≀ b) : b⁻¹ ≀ a⁻¹ := ENNReal.inv_strictAnti.antitone h @[gcongr] protected theorem inv_lt_inv' (h : a < b) : b⁻¹ < a⁻¹ := ENNReal.inv_strictAnti h @[simp] protected theorem inv_le_one : a⁻¹ ≀ 1 ↔ 1 ≀ a := by rw [inv_le_iff_inv_le, inv_one] protected theorem one_le_inv : 1 ≀ a⁻¹ ↔ a ≀ 1 := by rw [le_inv_iff_le_inv, inv_one] @[simp] protected theorem inv_lt_one : a⁻¹ < 1 ↔ 1 < a := by rw [inv_lt_iff_inv_lt, inv_one] @[simp] protected theorem one_lt_inv : 1 < a⁻¹ ↔ a < 1 := by rw [lt_inv_iff_lt_inv, inv_one] /-- The inverse map `fun x ↦ x⁻¹` is an order isomorphism between `ℝβ‰₯0∞` and its `OrderDual` -/ @[simps! apply] def _root_.OrderIso.invENNReal : ℝβ‰₯0∞ ≃o ℝβ‰₯0βˆžα΅’α΅ˆ where map_rel_iff' := ENNReal.inv_le_inv toEquiv := (Equiv.inv ℝβ‰₯0∞).trans OrderDual.toDual @[simp] theorem _root_.OrderIso.invENNReal_symm_apply (a : ℝβ‰₯0βˆžα΅’α΅ˆ) : OrderIso.invENNReal.symm a = (OrderDual.ofDual a)⁻¹ := rfl @[simp] theorem div_top : a / ∞ = 0 := by rw [div_eq_mul_inv, inv_top, mul_zero] theorem top_div : ∞ / a = if a = ∞ then 0 else ∞ := by simp [div_eq_mul_inv, top_mul'] theorem top_div_of_ne_top (h : a β‰  ∞) : ∞ / a = ∞ := by simp [top_div, h] @[simp] theorem top_div_coe : ∞ / p = ∞ := top_div_of_ne_top coe_ne_top theorem top_div_of_lt_top (h : a < ∞) : ∞ / a = ∞ := top_div_of_ne_top h.ne @[simp] protected theorem zero_div : 0 / a = 0 := zero_mul a⁻¹ theorem div_eq_top : a / b = ∞ ↔ a β‰  0 ∧ b = 0 ∨ a = ∞ ∧ b β‰  ∞ := by simp [div_eq_mul_inv, ENNReal.mul_eq_top] /-- See `ENNReal.div_div_cancel` for a simpler version assuming `a β‰  0`, `a β‰  ∞`. -/ protected lemma div_div_cancel' (hβ‚€ : a = 0 β†’ b = 0) (h₁ : a = ∞ β†’ b = 0) : a / (a / b) = b := by obtain rfl | ha := eq_or_ne a 0 Β· simp [hβ‚€] obtain rfl | ha' := eq_or_ne a ∞ Β· simp [h₁, top_div_of_lt_top] rw [ENNReal.div_eq_inv_mul, ENNReal.inv_div (Or.inr ha') (Or.inr ha), ENNReal.div_mul_cancel ha ha'] /-- See `ENNReal.div_div_cancel'` for a stronger version. -/ protected lemma div_div_cancel {a b : ℝβ‰₯0∞} (hβ‚€ : a β‰  0) (h₁ : a β‰  ∞) : a / (a / b) = b := ENNReal.div_div_cancel' (by simp [hβ‚€]) (by simp [h₁]) protected theorem le_div_iff_mul_le (h0 : b β‰  0 ∨ c β‰  0) (ht : b β‰  ∞ ∨ c β‰  ∞) : a ≀ c / b ↔ a * b ≀ c := by cases b with | top => lift c to ℝβ‰₯0 using ht.neg_resolve_left rfl rw [div_top, nonpos_iff_eq_zero] rcases eq_or_ne a 0 with (rfl | ha) <;> simp [*] | coe b => ?_ rcases eq_or_ne b 0 with (rfl | hb) Β· have hc : c β‰  0 := h0.neg_resolve_left rfl simp [div_zero hc] Β· rw [← coe_ne_zero] at hb rw [← ENNReal.mul_le_mul_right hb coe_ne_top, ENNReal.div_mul_cancel hb coe_ne_top] protected theorem div_le_iff_le_mul (hb0 : b β‰  0 ∨ c β‰  ∞) (hbt : b β‰  ∞ ∨ c β‰  0) : a / b ≀ c ↔ a ≀ c * b := by suffices a * b⁻¹ ≀ c ↔ a ≀ c / b⁻¹ by simpa [div_eq_mul_inv] refine (ENNReal.le_div_iff_mul_le ?_ ?_).symm <;> simpa protected theorem lt_div_iff_mul_lt (hb0 : b β‰  0 ∨ c β‰  ∞) (hbt : b β‰  ∞ ∨ c β‰  0) : c < a / b ↔ c * b < a := lt_iff_lt_of_le_iff_le (ENNReal.div_le_iff_le_mul hb0 hbt) theorem div_le_of_le_mul (h : a ≀ b * c) : a / c ≀ b := by by_cases h0 : c = 0 Β· have : a = 0 := by simpa [h0] using h simp [*] by_cases hinf : c = ∞; Β· simp [hinf] exact (ENNReal.div_le_iff_le_mul (Or.inl h0) (Or.inl hinf)).2 h theorem div_le_of_le_mul' (h : a ≀ b * c) : a / b ≀ c := div_le_of_le_mul <| mul_comm b c β–Έ h @[simp] protected theorem div_self_le_one : a / a ≀ 1 := div_le_of_le_mul <| by rw [one_mul] @[simp] protected lemma mul_inv_le_one (a : ℝβ‰₯0∞) : a * a⁻¹ ≀ 1 := ENNReal.div_self_le_one @[simp] protected lemma inv_mul_le_one (a : ℝβ‰₯0∞) : a⁻¹ * a ≀ 1 := by simp [mul_comm] @[aesop (rule_sets := [finiteness]) safe apply, simp] lemma mul_inv_ne_top (a : ℝβ‰₯0∞) : a * a⁻¹ β‰  ⊀ := ne_top_of_le_ne_top one_ne_top a.mul_inv_le_one @[aesop (rule_sets := [finiteness]) safe apply, simp] lemma inv_mul_ne_top (a : ℝβ‰₯0∞) : a⁻¹ * a β‰  ⊀ := by simp [mul_comm] theorem mul_le_of_le_div (h : a ≀ b / c) : a * c ≀ b := by rw [← inv_inv c] exact div_le_of_le_mul h theorem mul_le_of_le_div' (h : a ≀ b / c) : c * a ≀ b := mul_comm a c β–Έ mul_le_of_le_div h protected theorem div_lt_iff (h0 : b β‰  0 ∨ c β‰  0) (ht : b β‰  ∞ ∨ c β‰  ∞) : c / b < a ↔ c < a * b := lt_iff_lt_of_le_iff_le <| ENNReal.le_div_iff_mul_le h0 ht theorem mul_lt_of_lt_div (h : a < b / c) : a * c < b := by contrapose! h exact ENNReal.div_le_of_le_mul h theorem mul_lt_of_lt_div' (h : a < b / c) : c * a < b := mul_comm a c β–Έ mul_lt_of_lt_div h theorem div_lt_of_lt_mul (h : a < b * c) : a / c < b := mul_lt_of_lt_div <| by rwa [div_eq_mul_inv, inv_inv] theorem div_lt_of_lt_mul' (h : a < b * c) : a / b < c := div_lt_of_lt_mul <| by rwa [mul_comm] protected lemma div_lt_div_iff_left (hcβ‚€ : c β‰  0) (hc : c β‰  ∞) : a / c < b / c ↔ a < b := ENNReal.mul_lt_mul_right (by simpa) (by simpa) protected lemma div_lt_div_iff_right (haβ‚€ : a β‰  0) (ha : a β‰  ∞) : a / b < a / c ↔ c < b := (ENNReal.mul_lt_mul_left haβ‚€ ha).trans (by simp) @[gcongr] protected lemma div_lt_div_right (hcβ‚€ : c β‰  0) (hc : c β‰  ∞) (hab : a < b) : a / c < b / c := (ENNReal.div_lt_div_iff_left hcβ‚€ hc).2 hab @[gcongr] protected lemma div_lt_div_left (haβ‚€ : a β‰  0) (ha : a β‰  ∞) (hcb : c < b) : a / b < a / c := (ENNReal.div_lt_div_iff_right haβ‚€ ha).2 hcb protected lemma exists_pos_mul_lt (ha : a β‰  ∞) (hbβ‚€ : b β‰  0) : βˆƒ c, 0 < c ∧ c * a < b := by obtain rfl | hb := eq_or_ne b ∞ Β· exact ⟨1, by simpa [lt_top_iff_ne_top]⟩ refine ⟨b / (a + 1), ENNReal.div_pos hbβ‚€ (by finiteness), ENNReal.mul_lt_of_lt_div ?_⟩ gcongr exacts [hb, ENNReal.lt_add_right ha one_ne_zero] theorem inv_le_iff_le_mul (h₁ : b = ∞ β†’ a β‰  0) (hβ‚‚ : a = ∞ β†’ b β‰  0) : a⁻¹ ≀ b ↔ 1 ≀ a * b := by rw [← one_div, ENNReal.div_le_iff_le_mul, mul_comm] exacts [or_not_of_imp h₁, not_or_of_imp hβ‚‚] @[simp 900] theorem le_inv_iff_mul_le : a ≀ b⁻¹ ↔ a * b ≀ 1 := by rw [← one_div, ENNReal.le_div_iff_mul_le] <;> Β· right simp @[gcongr] protected theorem div_le_div (hab : a ≀ b) (hdc : d ≀ c) : a / c ≀ b / d := div_eq_mul_inv b d β–Έ div_eq_mul_inv a c β–Έ mul_le_mul' hab (ENNReal.inv_le_inv.mpr hdc) protected theorem div_le_div_left (h : a ≀ b) (c : ℝβ‰₯0∞) : c / b ≀ c / a := ENNReal.div_le_div le_rfl h protected theorem div_le_div_right (h : a ≀ b) (c : ℝβ‰₯0∞) : a / c ≀ b / c := ENNReal.div_le_div h le_rfl protected theorem eq_inv_of_mul_eq_one_left (h : a * b = 1) : a = b⁻¹ := by rw [← mul_one a, ← ENNReal.mul_inv_cancel (right_ne_zero_of_mul_eq_one h), ← mul_assoc, h, one_mul] rintro rfl simp [left_ne_zero_of_mul_eq_one h] at h theorem mul_le_iff_le_inv {a b r : ℝβ‰₯0∞} (hrβ‚€ : r β‰  0) (hr₁ : r β‰  ∞) : r * a ≀ b ↔ a ≀ r⁻¹ * b := by rw [← @ENNReal.mul_le_mul_left _ a _ hrβ‚€ hr₁, ← mul_assoc, ENNReal.mul_inv_cancel hrβ‚€ hr₁, one_mul] theorem le_of_forall_nnreal_lt {x y : ℝβ‰₯0∞} (h : βˆ€ r : ℝβ‰₯0, ↑r < x β†’ ↑r ≀ y) : x ≀ y := by refine le_of_forall_lt_imp_le_of_dense fun r hr => ?_ lift r to ℝβ‰₯0 using ne_top_of_lt hr exact h r hr lemma eq_of_forall_nnreal_le_iff {x y : ℝβ‰₯0∞} : (βˆ€ r : ℝβ‰₯0, ↑r ≀ x ↔ ↑r ≀ y) β†’ x = y := WithTop.eq_of_forall_coe_le_iff @[deprecated (since := "2025-10-20")] alias eq_of_forall_nnreal_iff := eq_of_forall_nnreal_le_iff lemma eq_of_forall_le_nnreal_iff {x y : ℝβ‰₯0∞} : (βˆ€ r : ℝβ‰₯0, x ≀ r ↔ y ≀ r) β†’ x = y := WithTop.eq_of_forall_le_coe_iff theorem le_of_forall_pos_nnreal_lt {x y : ℝβ‰₯0∞} (h : βˆ€ r : ℝβ‰₯0, 0 < r β†’ ↑r < x β†’ ↑r ≀ y) : x ≀ y := le_of_forall_nnreal_lt fun r hr => (zero_le r).eq_or_lt.elim (fun h => h β–Έ zero_le _) fun h0 => h r h0 hr theorem eq_top_of_forall_nnreal_le {x : ℝβ‰₯0∞} (h : βˆ€ r : ℝβ‰₯0, ↑r ≀ x) : x = ∞ := top_unique <| le_of_forall_nnreal_lt fun r _ => h r protected theorem add_div : (a + b) / c = a / c + b / c := right_distrib a b c⁻¹ protected theorem div_add_div_same {a b c : ℝβ‰₯0∞} : a / c + b / c = (a + b) / c := ENNReal.add_div.symm protected theorem div_self (h0 : a β‰  0) (hI : a β‰  ∞) : a / a = 1 := ENNReal.mul_inv_cancel h0 hI theorem mul_div_le : a * (b / a) ≀ b := mul_le_of_le_div' le_rfl theorem eq_div_iff (ha : a β‰  0) (ha' : a β‰  ∞) : b = c / a ↔ a * b = c := ⟨fun h => by rw [h, ENNReal.mul_div_cancel ha ha'], fun h => by rw [← h, mul_div_assoc, ENNReal.mul_div_cancel ha ha']⟩ protected theorem div_eq_div_iff (ha : a β‰  0) (ha' : a β‰  ∞) (hb : b β‰  0) (hb' : b β‰  ∞) : c / b = d / a ↔ a * c = b * d := by rw [eq_div_iff ha ha'] conv_rhs => rw [eq_comm] rw [← eq_div_iff hb hb', mul_div_assoc, eq_comm] theorem div_eq_one_iff {a b : ℝβ‰₯0∞} (hbβ‚€ : b β‰  0) (hb₁ : b β‰  ∞) : a / b = 1 ↔ a = b := ⟨fun h => by rw [← (eq_div_iff hbβ‚€ hb₁).mp h.symm, mul_one], fun h => h.symm β–Έ ENNReal.div_self hbβ‚€ hbβ‚βŸ© theorem inv_two_add_inv_two : (2 : ℝβ‰₯0∞)⁻¹ + 2⁻¹ = 1 := by rw [← two_mul, ← div_eq_mul_inv, ENNReal.div_self two_ne_zero ofNat_ne_top] theorem inv_three_add_inv_three : (3 : ℝβ‰₯0∞)⁻¹ + 3⁻¹ + 3⁻¹ = 1 := by rw [← ENNReal.mul_inv_cancel three_ne_zero ofNat_ne_top] ring @[simp] protected theorem add_halves (a : ℝβ‰₯0∞) : a / 2 + a / 2 = a := by rw [div_eq_mul_inv, ← mul_add, inv_two_add_inv_two, mul_one] @[simp] theorem add_thirds (a : ℝβ‰₯0∞) : a / 3 + a / 3 + a / 3 = a := by rw [div_eq_mul_inv, ← mul_add, ← mul_add, inv_three_add_inv_three, mul_one] @[simp] theorem div_eq_zero_iff : a / b = 0 ↔ a = 0 ∨ b = ∞ := by simp [div_eq_mul_inv] @[simp] theorem div_pos_iff : 0 < a / b ↔ a β‰  0 ∧ b β‰  ∞ := by simp [pos_iff_ne_zero, not_or] protected lemma div_ne_zero : a / b β‰  0 ↔ a β‰  0 ∧ b β‰  ∞ := by rw [← pos_iff_ne_zero, div_pos_iff] protected lemma div_mul (a : ℝβ‰₯0∞) (h0 : b β‰  0 ∨ c β‰  0) (htop : b β‰  ∞ ∨ c β‰  ∞) : a / b * c = a / (b / c) := by simp only [div_eq_mul_inv] rw [ENNReal.mul_inv, inv_inv] Β· ring Β· simpa Β· simpa protected lemma mul_div_mul_comm (hc : c β‰  0 ∨ d β‰  ∞) (hd : c β‰  ∞ ∨ d β‰  0) : a * b / (c * d) = a / c * (b / d) := by simp only [div_eq_mul_inv, ENNReal.mul_inv hc hd] ring protected theorem half_pos (h : a β‰  0) : 0 < a / 2 := ENNReal.div_pos h ofNat_ne_top protected theorem one_half_lt_one : (2⁻¹ : ℝβ‰₯0∞) < 1 := ENNReal.inv_lt_one.2 <| one_lt_two protected theorem half_lt_self (hz : a β‰  0) (ht : a β‰  ∞) : a / 2 < a := by lift a to ℝβ‰₯0 using ht rw [coe_ne_zero] at hz rw [← coe_two, ← coe_div, coe_lt_coe] exacts [NNReal.half_lt_self hz, two_ne_zero' _] protected theorem half_le_self : a / 2 ≀ a := le_add_self.trans_eq <| ENNReal.add_halves _ theorem sub_half (h : a β‰  ∞) : a - a / 2 = a / 2 := ENNReal.sub_eq_of_eq_add' h a.add_halves.symm @[simp] theorem one_sub_inv_two : (1 : ℝβ‰₯0∞) - 2⁻¹ = 2⁻¹ := by rw [← one_div, sub_half one_ne_top] private lemma exists_lt_mul_left {a b c : ℝβ‰₯0∞} (hc : c < a * b) : βˆƒ a' < a, c < a' * b := by obtain ⟨a', hc, ha'⟩ := exists_between (ENNReal.div_lt_of_lt_mul hc) exact ⟨_, ha', (ENNReal.div_lt_iff (.inl <| by rintro rfl; simp at *) (.inr <| by rintro rfl; simp at *)).1 hc⟩ private lemma exists_lt_mul_right {a b c : ℝβ‰₯0∞} (hc : c < a * b) : βˆƒ b' < b, c < a * b' := by simp_rw [mul_comm a] at hc ⊒; exact exists_lt_mul_left hc lemma mul_le_of_forall_lt {a b c : ℝβ‰₯0∞} (h : βˆ€ a' < a, βˆ€ b' < b, a' * b' ≀ c) : a * b ≀ c := by refine le_of_forall_lt_imp_le_of_dense fun d hd ↦ ?_ obtain ⟨a', ha', hd⟩ := exists_lt_mul_left hd obtain ⟨b', hb', hd⟩ := exists_lt_mul_right hd exact le_trans hd.le <| h _ ha' _ hb' lemma le_mul_of_forall_lt {a b c : ℝβ‰₯0∞} (h₁ : a β‰  0 ∨ b β‰  ∞) (hβ‚‚ : a β‰  ∞ ∨ b β‰  0) (h : βˆ€ a' > a, βˆ€ b' > b, c ≀ a' * b') : c ≀ a * b := by rw [← ENNReal.inv_le_inv, ENNReal.mul_inv h₁ hβ‚‚] exact mul_le_of_forall_lt fun a' ha' b' hb' ↦ ENNReal.le_inv_iff_le_inv.1 <| (h _ (ENNReal.lt_inv_iff_lt_inv.1 ha') _ (ENNReal.lt_inv_iff_lt_inv.1 hb')).trans_eq (ENNReal.mul_inv (Or.inr hb'.ne_top) (Or.inl ha'.ne_top)).symm /-- The birational order isomorphism between `ℝβ‰₯0∞` and the unit interval `Set.Iic (1 : ℝβ‰₯0∞)`. -/ @[simps! apply_coe] def orderIsoIicOneBirational : ℝβ‰₯0∞ ≃o Iic (1 : ℝβ‰₯0∞) := by refine StrictMono.orderIsoOfRightInverse (fun x => ⟨(x⁻¹ + 1)⁻¹, ENNReal.inv_le_one.2 <| le_add_self⟩) (fun x y hxy => ?_) (fun x => (x.1⁻¹ - 1)⁻¹) fun x => Subtype.ext ?_ Β· simpa only [Subtype.mk_lt_mk, ENNReal.inv_lt_inv, ENNReal.add_lt_add_iff_right one_ne_top] Β· have : (1 : ℝβ‰₯0∞) ≀ x.1⁻¹ := ENNReal.one_le_inv.2 x.2 simp only [inv_inv, tsub_add_cancel_of_le this] @[simp] theorem orderIsoIicOneBirational_symm_apply (x : Iic (1 : ℝβ‰₯0∞)) : orderIsoIicOneBirational.symm x = (x.1⁻¹ - 1)⁻¹ := rfl /-- Order isomorphism between an initial interval in `ℝβ‰₯0∞` and an initial interval in `ℝβ‰₯0`. -/ @[simps! apply_coe] def orderIsoIicCoe (a : ℝβ‰₯0) : Iic (a : ℝβ‰₯0∞) ≃o Iic a := OrderIso.symm { toFun := fun x => ⟨x, coe_le_coe.2 x.2⟩ invFun := fun x => ⟨ENNReal.toNNReal x, coe_le_coe.1 <| coe_toNNReal_le_self.trans x.2⟩ left_inv := fun _ => Subtype.ext <| toNNReal_coe _ right_inv := fun x => Subtype.ext <| coe_toNNReal (ne_top_of_le_ne_top coe_ne_top x.2) map_rel_iff' := fun {_ _} => by simp only [Equiv.coe_fn_mk, Subtype.mk_le_mk, coe_le_coe, Subtype.coe_le_coe] } @[simp] theorem orderIsoIicCoe_symm_apply_coe (a : ℝβ‰₯0) (b : Iic a) : ((orderIsoIicCoe a).symm b : ℝβ‰₯0∞) = b := rfl /-- An order isomorphism between the extended nonnegative real numbers and the unit interval. -/ def orderIsoUnitIntervalBirational : ℝβ‰₯0∞ ≃o Icc (0 : ℝ) 1 := orderIsoIicOneBirational.trans <| (orderIsoIicCoe 1).trans <| (NNReal.orderIsoIccZeroCoe 1).symm @[simp] theorem orderIsoUnitIntervalBirational_apply_coe (x : ℝβ‰₯0∞) : (orderIsoUnitIntervalBirational x : ℝ) = (x⁻¹ + 1)⁻¹.toReal := rfl theorem exists_inv_nat_lt {a : ℝβ‰₯0∞} (h : a β‰  0) : βˆƒ n : β„•, (n : ℝβ‰₯0∞)⁻¹ < a := inv_inv a β–Έ by simp only [ENNReal.inv_lt_inv, ENNReal.exists_nat_gt (inv_ne_top.2 h)] theorem exists_nat_pos_mul_gt (ha : a β‰  0) (hb : b β‰  ∞) : βˆƒ n > 0, b < (n : β„•) * a := let ⟨n, hn⟩ := ENNReal.exists_nat_gt (div_lt_top hb ha).ne ⟨n, Nat.cast_pos.1 ((zero_le _).trans_lt hn), by rwa [← ENNReal.div_lt_iff (Or.inl ha) (Or.inr hb)]⟩ theorem exists_nat_mul_gt (ha : a β‰  0) (hb : b β‰  ∞) : βˆƒ n : β„•, b < n * a := (exists_nat_pos_mul_gt ha hb).imp fun _ => And.right theorem exists_nat_pos_inv_mul_lt (ha : a β‰  ∞) (hb : b β‰  0) : βˆƒ n > 0, ((n : β„•) : ℝβ‰₯0∞)⁻¹ * a < b := by rcases exists_nat_pos_mul_gt hb ha with ⟨n, npos, hn⟩ use n, npos rw [← ENNReal.div_eq_inv_mul] exact div_lt_of_lt_mul' hn theorem exists_nnreal_pos_mul_lt (ha : a β‰  ∞) (hb : b β‰  0) : βˆƒ n > 0, ↑(n : ℝβ‰₯0) * a < b := by rcases exists_nat_pos_inv_mul_lt ha hb with ⟨n, npos : 0 < n, hn⟩ use (n : ℝβ‰₯0)⁻¹ simp [*, npos.ne'] theorem exists_inv_two_pow_lt (ha : a β‰  0) : βˆƒ n : β„•, 2⁻¹ ^ n < a := by rcases exists_inv_nat_lt ha with ⟨n, hn⟩ refine ⟨n, lt_trans ?_ hn⟩ rw [← ENNReal.inv_pow, ENNReal.inv_lt_inv] norm_cast exact n.lt_two_pow_self @[simp, norm_cast] theorem coe_zpow (hr : r β‰  0) (n : β„€) : (↑(r ^ n) : ℝβ‰₯0∞) = (r : ℝβ‰₯0∞) ^ n := by rcases n with n | n Β· simp only [Int.ofNat_eq_coe, coe_pow, zpow_natCast] Β· have : r ^ n.succ β‰  0 := pow_ne_zero (n + 1) hr simp only [zpow_negSucc, coe_inv this, coe_pow] lemma zero_zpow_def (n : β„€) : (0 : ℝβ‰₯0∞) ^ n = if n = 0 then 1 else if 0 < n then 0 else ⊀ := by obtain ((_ | n) | n) := n <;> simp [-Nat.cast_add, -Int.natCast_add] lemma top_zpow_def (n : β„€) : (⊀ : ℝβ‰₯0∞) ^ n = if n = 0 then 1 else if 0 < n then ⊀ else 0 := by obtain ((_ | n) | n) := n <;> simp [-Nat.cast_add, -Int.natCast_add] theorem zpow_pos (ha : a β‰  0) (h'a : a β‰  ∞) (n : β„€) : 0 < a ^ n := by cases n Β· simpa using ENNReal.pow_pos ha.bot_lt _ Β· simp only [h'a, pow_eq_top_iff, zpow_negSucc, Ne, ENNReal.inv_pos, false_and, not_false_eq_true] theorem zpow_lt_top (ha : a β‰  0) (h'a : a β‰  ∞) (n : β„€) : a ^ n < ∞ := by cases n Β· simpa using ENNReal.pow_lt_top h'a.lt_top Β· simp only [ENNReal.pow_pos ha.bot_lt, zpow_negSucc, inv_lt_top] @[aesop (rule_sets := [finiteness]) unsafe apply] lemma zpow_ne_top {a : ℝβ‰₯0∞} (ha : a β‰  0) (h'a : a β‰  ∞) (n : β„€) : a ^ n β‰  ∞ := (ENNReal.zpow_lt_top ha h'a n).ne theorem exists_mem_Ico_zpow {x y : ℝβ‰₯0∞} (hx : x β‰  0) (h'x : x β‰  ∞) (hy : 1 < y) (h'y : y β‰  ⊀) : βˆƒ n : β„€, x ∈ Ico (y ^ n) (y ^ (n + 1)) := by lift x to ℝβ‰₯0 using h'x lift y to ℝβ‰₯0 using h'y have A : y β‰  0 := by simpa only [Ne, coe_eq_zero] using (zero_lt_one.trans hy).ne' obtain ⟨n, hn, h'n⟩ : βˆƒ n : β„€, y ^ n ≀ x ∧ x < y ^ (n + 1) := by refine NNReal.exists_mem_Ico_zpow ?_ (one_lt_coe_iff.1 hy) simpa only [Ne, coe_eq_zero] using hx refine ⟨n, ?_, ?_⟩ Β· rwa [← ENNReal.coe_zpow A, ENNReal.coe_le_coe] Β· rwa [← ENNReal.coe_zpow A, ENNReal.coe_lt_coe] theorem exists_mem_Ioc_zpow {x y : ℝβ‰₯0∞} (hx : x β‰  0) (h'x : x β‰  ∞) (hy : 1 < y) (h'y : y β‰  ⊀) : βˆƒ n : β„€, x ∈ Ioc (y ^ n) (y ^ (n + 1)) := by lift x to ℝβ‰₯0 using h'x lift y to ℝβ‰₯0 using h'y have A : y β‰  0 := by simpa only [Ne, coe_eq_zero] using (zero_lt_one.trans hy).ne' obtain ⟨n, hn, h'n⟩ : βˆƒ n : β„€, y ^ n < x ∧ x ≀ y ^ (n + 1) := by refine NNReal.exists_mem_Ioc_zpow ?_ (one_lt_coe_iff.1 hy) simpa only [Ne, coe_eq_zero] using hx refine ⟨n, ?_, ?_⟩ Β· rwa [← ENNReal.coe_zpow A, ENNReal.coe_lt_coe] Β· rwa [← ENNReal.coe_zpow A, ENNReal.coe_le_coe] theorem Ioo_zero_top_eq_iUnion_Ico_zpow {y : ℝβ‰₯0∞} (hy : 1 < y) (h'y : y β‰  ⊀) : Ioo (0 : ℝβ‰₯0∞) (∞ : ℝβ‰₯0∞) = ⋃ n : β„€, Ico (y ^ n) (y ^ (n + 1)) := by ext x simp only [mem_iUnion, mem_Ioo, mem_Ico] constructor Β· rintro ⟨hx, h'x⟩ exact exists_mem_Ico_zpow hx.ne' h'x.ne hy h'y Β· rintro ⟨n, hn, h'n⟩ constructor Β· apply lt_of_lt_of_le _ hn exact ENNReal.zpow_pos (zero_lt_one.trans hy).ne' h'y _ Β· apply lt_trans h'n _ exact ENNReal.zpow_lt_top (zero_lt_one.trans hy).ne' h'y _ @[gcongr] theorem zpow_le_of_le {x : ℝβ‰₯0∞} (hx : 1 ≀ x) {a b : β„€} (h : a ≀ b) : x ^ a ≀ x ^ b := by obtain a | a := a <;> obtain b | b := b Β· simp only [Int.ofNat_eq_coe, zpow_natCast] exact pow_right_monoβ‚€ hx (Int.le_of_ofNat_le_ofNat h) Β· apply absurd h (not_le_of_gt _) exact lt_of_lt_of_le (Int.negSucc_lt_zero _) (Int.natCast_nonneg _) Β· simp only [zpow_negSucc, Int.ofNat_eq_coe, zpow_natCast] refine (ENNReal.inv_le_one.2 ?_).trans ?_ <;> exact one_le_pow_of_one_le' hx _ Β· simp only [zpow_negSucc, ENNReal.inv_le_inv] apply pow_right_monoβ‚€ hx simpa only [← Int.ofNat_le, neg_le_neg_iff, Int.natCast_add, Int.ofNat_one] using h theorem monotone_zpow {x : ℝβ‰₯0∞} (hx : 1 ≀ x) : Monotone ((x ^ Β·) : β„€ β†’ ℝβ‰₯0∞) := fun _ _ h => zpow_le_of_le hx h protected theorem zpow_add {x : ℝβ‰₯0∞} (hx : x β‰  0) (h'x : x β‰  ∞) (m n : β„€) : x ^ (m + n) = x ^ m * x ^ n := by lift x to ℝβ‰₯0 using h'x replace hx : x β‰  0 := by simpa only [Ne, coe_eq_zero] using hx simp only [← coe_zpow hx, zpow_addβ‚€ hx, coe_mul] protected theorem zpow_neg (x : ℝβ‰₯0∞) (m : β„€) : x ^ (-m) = (x ^ m)⁻¹ := by obtain hxβ‚€ | hxβ‚€ := eq_or_ne x 0 Β· obtain hm | hm | hm := lt_trichotomy m 0 <;> simp_all [zero_zpow_def, ne_of_lt, ne_of_gt, lt_asymm] obtain hx | hx := eq_or_ne x ⊀ Β· obtain hm | hm | hm := lt_trichotomy m 0 <;> simp_all [top_zpow_def, ne_of_lt, ne_of_gt, lt_asymm] exact ENNReal.eq_inv_of_mul_eq_one_left (by simp [← ENNReal.zpow_add hxβ‚€ hx]) protected theorem zpow_sub {x : ℝβ‰₯0∞} (x_ne_zero : x β‰  0) (x_ne_top : x β‰  ⊀) (m n : β„€) : x ^ (m - n) = (x ^ m) * (x ^ n)⁻¹ := by rw [sub_eq_add_neg, ENNReal.zpow_add x_ne_zero x_ne_top, ENNReal.zpow_neg] protected lemma inv_zpow (x : ℝβ‰₯0∞) (n : β„€) : x⁻¹ ^ n = (x ^ n)⁻¹ := by cases n <;> simp [ENNReal.inv_pow] protected lemma inv_zpow' (x : ℝβ‰₯0∞) (n : β„€) : x⁻¹ ^ n = x ^ (-n) := by rw [ENNReal.zpow_neg, ENNReal.inv_zpow] lemma zpow_le_one_of_nonpos {n : β„€} (hn : n ≀ 0) {x : ℝβ‰₯0∞} (hx : 1 ≀ x) : x ^ n ≀ 1 := by obtain ⟨m, rfl⟩ := neg_surjective n lift m to β„• using by simpa using hn rw [← ENNReal.inv_zpow', ENNReal.inv_zpow, ENNReal.inv_le_one] exact mod_cast one_le_powβ‚€ hx lemma isUnit_iff : IsUnit a ↔ a β‰  0 ∧ a β‰  ∞ := by refine ⟨fun ha ↦ ⟨ha.ne_zero, ?_⟩, fun ha ↦ ⟨⟨a, a⁻¹, ENNReal.mul_inv_cancel ha.1 ha.2, ENNReal.inv_mul_cancel ha.1 ha.2⟩, rfl⟩⟩ obtain ⟨u, rfl⟩ := ha rintro hu have := congr($hu * u⁻¹) norm_cast at this simp [mul_inv_cancel] at this /-- Left multiplication by a nonzero finite `a` as an order isomorphism. -/ @[simps! toEquiv apply symm_apply] def mulLeftOrderIso (a : ℝβ‰₯0∞) (ha : IsUnit a) : ℝβ‰₯0∞ ≃o ℝβ‰₯0∞ where toEquiv := ha.unit.mulLeft map_rel_iff' := by simp [ENNReal.mul_le_mul_left, ha.ne_zero, (isUnit_iff.1 ha).2] /-- Right multiplication by a nonzero finite `a` as an order isomorphism. -/ @[simps! toEquiv apply symm_apply] def mulRightOrderIso (a : ℝβ‰₯0∞) (ha : IsUnit a) : ℝβ‰₯0∞ ≃o ℝβ‰₯0∞ where toEquiv := ha.unit.mulRight map_rel_iff' := by simp [ENNReal.mul_le_mul_right, ha.ne_zero, (isUnit_iff.1 ha).2] variable {ΞΉ ΞΊ : Sort*} {f g : ΞΉ β†’ ℝβ‰₯0∞} {s : Set ℝβ‰₯0∞} {a : ℝβ‰₯0∞} lemma mul_iSup (a : ℝβ‰₯0∞) (f : ΞΉ β†’ ℝβ‰₯0∞) : a * ⨆ i, f i = ⨆ i, a * f i := by by_cases hf : βˆ€ i, f i = 0 Β· simp [hf] obtain rfl | haβ‚€ := eq_or_ne a 0 Β· simp obtain rfl | ha := eq_or_ne a ∞ Β· obtain ⟨i, hi⟩ := not_forall.1 hf simpa [iSup_eq_zero.not.2 hf, eq_comm (a := ⊀)] using le_iSup_of_le (f := fun i => ⊀ * f i) i (top_mul hi).ge Β· exact (mulLeftOrderIso _ <| isUnit_iff.2 ⟨haβ‚€, ha⟩).map_iSup _ lemma iSup_mul (f : ΞΉ β†’ ℝβ‰₯0∞) (a : ℝβ‰₯0∞) : (⨆ i, f i) * a = ⨆ i, f i * a := by simp [mul_comm, mul_iSup] lemma mul_sSup {a : ℝβ‰₯0∞} : a * sSup s = ⨆ b ∈ s, a * b := by simp only [sSup_eq_iSup, mul_iSup] lemma sSup_mul {a : ℝβ‰₯0∞} : sSup s * a = ⨆ b ∈ s, b * a := by simp only [sSup_eq_iSup, iSup_mul] lemma iSup_div (f : ΞΉ β†’ ℝβ‰₯0∞) (a : ℝβ‰₯0∞) : iSup f / a = ⨆ i, f i / a := iSup_mul .. lemma sSup_div (s : Set ℝβ‰₯0∞) (a : ℝβ‰₯0∞) : sSup s / a = ⨆ b ∈ s, b / a := sSup_mul .. /-- Very general version for distributivity of multiplication over an infimum. See `ENNReal.mul_iInf_of_ne` for the special case assuming `a β‰  0` and `a β‰  ∞`, and `ENNReal.mul_iInf` for the special case assuming `Nonempty ΞΉ`. -/ lemma mul_iInf' (hinfty : a = ∞ β†’ β¨… i, f i = 0 β†’ βˆƒ i, f i = 0) (hβ‚€ : a = 0 β†’ Nonempty ΞΉ) : a * β¨… i, f i = β¨… i, a * f i := by obtain rfl | haβ‚€ := eq_or_ne a 0 Β· simp [hβ‚€ rfl] obtain rfl | ha := eq_or_ne a ∞ Β· obtain ⟨i, hi⟩ | hf := em (βˆƒ i, f i = 0) Β· rw [(iInf_eq_bot _).2, (iInf_eq_bot _).2, bot_eq_zero, mul_zero] <;> exact fun _ _↦ ⟨i, by simpa [hi]⟩ Β· rw [top_mul (mt (hinfty rfl) hf), eq_comm, iInf_eq_top] exact fun i ↦ top_mul fun hi ↦ hf ⟨i, hi⟩ Β· exact (mulLeftOrderIso _ <| isUnit_iff.2 ⟨haβ‚€, ha⟩).map_iInf _ /-- Very general version for distributivity of multiplication over an infimum. See `ENNReal.iInf_mul_of_ne` for the special case assuming `a β‰  0` and `a β‰  ∞`, and `ENNReal.iInf_mul` for the special case assuming `Nonempty ΞΉ`. -/ lemma iInf_mul' (hinfty : a = ∞ β†’ β¨… i, f i = 0 β†’ βˆƒ i, f i = 0) (hβ‚€ : a = 0 β†’ Nonempty ΞΉ) : (β¨… i, f i) * a = β¨… i, f i * a := by simpa only [mul_comm a] using mul_iInf' hinfty hβ‚€ /-- If `a β‰  0` and `a β‰  ∞`, then right multiplication by `a` maps infimum to infimum. See `ENNReal.mul_iInf'` for the general case, and `ENNReal.iInf_mul` for another special case that assumes `Nonempty ΞΉ` but does not require `a β‰  0`, and `ENNReal`. -/ lemma mul_iInf_of_ne (haβ‚€ : a β‰  0) (ha : a β‰  ∞) : a * β¨… i, f i = β¨… i, a * f i := mul_iInf' (by simp [ha]) (by simp [haβ‚€]) /-- If `a β‰  0` and `a β‰  ∞`, then right multiplication by `a` maps infimum to infimum. See `ENNReal.iInf_mul'` for the general case, and `ENNReal.iInf_mul` for another special case that assumes `Nonempty ΞΉ` but does not require `a β‰  0`. -/ lemma iInf_mul_of_ne (haβ‚€ : a β‰  0) (ha : a β‰  ∞) : (β¨… i, f i) * a = β¨… i, f i * a := iInf_mul' (by simp [ha]) (by simp [haβ‚€]) /-- See `ENNReal.mul_iInf'` for the general case, and `ENNReal.mul_iInf_of_ne` for another special case that assumes `a β‰  0` but does not require `Nonempty ΞΉ`. -/ lemma mul_iInf [Nonempty ΞΉ] (hinfty : a = ∞ β†’ β¨… i, f i = 0 β†’ βˆƒ i, f i = 0) : a * β¨… i, f i = β¨… i, a * f i := mul_iInf' hinfty fun _ ↦ β€ΉNonempty ΞΉβ€Ί /-- See `ENNReal.iInf_mul'` for the general case, and `ENNReal.iInf_mul_of_ne` for another special case that assumes `a β‰  0` but does not require `Nonempty ΞΉ`. -/ lemma iInf_mul [Nonempty ΞΉ] (hinfty : a = ∞ β†’ β¨… i, f i = 0 β†’ βˆƒ i, f i = 0) : (β¨… i, f i) * a = β¨… i, f i * a := iInf_mul' hinfty fun _ ↦ β€ΉNonempty ΞΉβ€Ί /-- Very general version for distributivity of division over an infimum. See `ENNReal.iInf_div_of_ne` for the special case assuming `a β‰  0` and `a β‰  ∞`, and `ENNReal.iInf_div` for the special case assuming `Nonempty ΞΉ`. -/ lemma iInf_div' (hinfty : a = 0 β†’ β¨… i, f i = 0 β†’ βˆƒ i, f i = 0) (hβ‚€ : a = ∞ β†’ Nonempty ΞΉ) : (β¨… i, f i) / a = β¨… i, f i / a := iInf_mul' (by simpa) (by simpa) /-- If `a β‰  0` and `a β‰  ∞`, then division by `a` maps infimum to infimum. See `ENNReal.iInf_div'` for the general case, and `ENNReal.iInf_div` for another special case that assumes `Nonempty ΞΉ` but does not require `a β‰  ∞`. -/ lemma iInf_div_of_ne (haβ‚€ : a β‰  0) (ha : a β‰  ∞) : (β¨… i, f i) / a = β¨… i, f i / a := iInf_div' (by simp [haβ‚€]) (by simp [ha]) /-- See `ENNReal.iInf_div'` for the general case, and `ENNReal.iInf_div_of_ne` for another special case that assumes `a β‰  ∞` but does not require `Nonempty ΞΉ`. -/ lemma iInf_div [Nonempty ΞΉ] (hinfty : a = 0 β†’ β¨… i, f i = 0 β†’ βˆƒ i, f i = 0) : (β¨… i, f i) / a = β¨… i, f i / a := iInf_div' hinfty fun _ ↦ β€ΉNonempty ΞΉβ€Ί lemma inv_iInf (f : ΞΉ β†’ ℝβ‰₯0∞) : (β¨… i, f i)⁻¹ = ⨆ i, (f i)⁻¹ := OrderIso.invENNReal.map_iInf _ lemma inv_iSup (f : ΞΉ β†’ ℝβ‰₯0∞) : (⨆ i, f i)⁻¹ = β¨… i, (f i)⁻¹ := OrderIso.invENNReal.map_iSup _ lemma inv_sInf (s : Set ℝβ‰₯0∞) : (sInf s)⁻¹ = ⨆ a ∈ s, a⁻¹ := by simp [sInf_eq_iInf, inv_iInf] lemma inv_sSup (s : Set ℝβ‰₯0∞) : (sSup s)⁻¹ = β¨… a ∈ s, a⁻¹ := by simp [sSup_eq_iSup, inv_iSup] lemma le_iInf_mul {ΞΉ : Type*} (u v : ΞΉ β†’ ℝβ‰₯0∞) : (β¨… i, u i) * β¨… i, v i ≀ β¨… i, u i * v i := le_iInf fun i ↦ mul_le_mul' (iInf_le u i) (iInf_le v i) lemma iSup_mul_le {ΞΉ : Type*} {u v : ΞΉ β†’ ℝβ‰₯0∞} : ⨆ i, u i * v i ≀ (⨆ i, u i) * ⨆ i, v i := iSup_le fun i ↦ mul_le_mul' (le_iSup u i) (le_iSup v i) lemma le_iInf_mul_iInf {g : ΞΊ β†’ ℝβ‰₯0∞} (hf : βˆƒ i, f i β‰  ∞) (hg : βˆƒ j, g j β‰  ∞) (ha : βˆ€ i j, a ≀ f i * g j) : a ≀ (β¨… i, f i) * β¨… j, g j := by rw [← iInf_ne_top_subtype] have := nonempty_subtype.2 hf have := hg.nonempty replace hg : β¨… j, g j β‰  ∞ := by simpa using hg rw [iInf_mul fun h ↦ (hg h).elim, le_iInf_iff] rintro ⟨i, hi⟩ simpa [mul_iInf fun h ↦ (hi h).elim] using ha i lemma iInf_mul_iInf {f g : ΞΉ β†’ ℝβ‰₯0∞} (hf : βˆƒ i, f i β‰  ∞) (hg : βˆƒ j, g j β‰  ∞) (h : βˆ€ i j, βˆƒ k, f k * g k ≀ f i * g j) : (β¨… i, f i) * β¨… i, g i = β¨… i, f i * g i := by refine le_antisymm (le_iInf fun i ↦ mul_le_mul' (iInf_le ..) (iInf_le ..)) (le_iInf_mul_iInf hf hg fun i j ↦ ?_) obtain ⟨k, hk⟩ := h i j exact iInf_le_of_le k hk lemma smul_iSup {R} [SMul R ℝβ‰₯0∞] [IsScalarTower R ℝβ‰₯0∞ ℝβ‰₯0∞] (f : ΞΉ β†’ ℝβ‰₯0∞) (c : R) : c β€’ ⨆ i, f i = ⨆ i, c β€’ f i := by simp only [← smul_one_mul c (f _), ← smul_one_mul c (iSup _), ENNReal.mul_iSup] lemma smul_sSup {R} [SMul R ℝβ‰₯0∞] [IsScalarTower R ℝβ‰₯0∞ ℝβ‰₯0∞] (s : Set ℝβ‰₯0∞) (c : R) : c β€’ sSup s = ⨆ a ∈ s, c β€’ a := by simp_rw [← smul_one_mul c (sSup s), ENNReal.mul_sSup, smul_one_mul] @[simp] theorem ofReal_inv_of_pos {x : ℝ} (hx : 0 < x) : ENNReal.ofReal x⁻¹ = (ENNReal.ofReal x)⁻¹ := by rw [ENNReal.ofReal, ENNReal.ofReal, ← @coe_inv (Real.toNNReal x) (by simp [hx]), coe_inj, ← Real.toNNReal_inv] theorem ofReal_div_of_pos {x y : ℝ} (hy : 0 < y) : ENNReal.ofReal (x / y) = ENNReal.ofReal x / ENNReal.ofReal y := by rw [div_eq_mul_inv, div_eq_mul_inv, ofReal_mul' (inv_nonneg.2 hy.le), ofReal_inv_of_pos hy] @[simp] theorem toNNReal_inv (a : ℝβ‰₯0∞) : a⁻¹.toNNReal = a.toNNReal⁻¹ := by cases a with | top => simp | coe a => rcases eq_or_ne a 0 with (rfl | ha); Β· simp rw [← coe_inv ha, toNNReal_coe, toNNReal_coe] @[simp] theorem toNNReal_div (a b : ℝβ‰₯0∞) : (a / b).toNNReal = a.toNNReal / b.toNNReal := by rw [div_eq_mul_inv, toNNReal_mul, toNNReal_inv, div_eq_mul_inv] @[simp] theorem toReal_inv (a : ℝβ‰₯0∞) : a⁻¹.toReal = a.toReal⁻¹ := by simp only [ENNReal.toReal, toNNReal_inv, NNReal.coe_inv] @[simp] theorem toReal_div (a b : ℝβ‰₯0∞) : (a / b).toReal = a.toReal / b.toReal := by rw [div_eq_mul_inv, toReal_mul, toReal_inv, div_eq_mul_inv] end Inv end ENNReal
.lake/packages/mathlib/Mathlib/Data/ENNReal/Real.lean
import Mathlib.Data.ENNReal.Basic /-! # Maps between real and extended non-negative real numbers This file focuses on the functions `ENNReal.toReal : ℝβ‰₯0∞ β†’ ℝ` and `ENNReal.ofReal : ℝ β†’ ℝβ‰₯0∞` which were defined in `Data.ENNReal.Basic`. It collects all the basic results of the interactions between these functions and the algebraic and lattice operations, although a few may appear in earlier files. This file provides a `positivity` extension for `ENNReal.ofReal`. ## Main statements - `trichotomy (p : ℝβ‰₯0∞) : p = 0 ∨ p = ∞ ∨ 0 < p.toReal`: often used for `WithLp` and `lp` - `dichotomy (p : ℝβ‰₯0∞) [Fact (1 ≀ p)] : p = ∞ ∨ 1 ≀ p.toReal`: often used for `WithLp` and `lp` - `toNNReal_iInf` through `toReal_sSup`: these declarations allow for easy conversions between indexed or set infima and suprema in `ℝ`, `ℝβ‰₯0` and `ℝβ‰₯0∞`. This is especially useful because `ℝβ‰₯0∞` is a complete lattice. -/ assert_not_exists Finset open Set NNReal ENNReal namespace ENNReal section Real variable {a b c d : ℝβ‰₯0∞} {r p q : ℝβ‰₯0} theorem toReal_add (ha : a β‰  ∞) (hb : b β‰  ∞) : (a + b).toReal = a.toReal + b.toReal := by lift a to ℝβ‰₯0 using ha lift b to ℝβ‰₯0 using hb rfl theorem toReal_add_le : (a + b).toReal ≀ a.toReal + b.toReal := if ha : a = ∞ then by simp only [ha, top_add, toReal_top, zero_add, toReal_nonneg] else if hb : b = ∞ then by simp only [hb, add_top, toReal_top, add_zero, toReal_nonneg] else le_of_eq (toReal_add ha hb) theorem ofReal_add {p q : ℝ} (hp : 0 ≀ p) (hq : 0 ≀ q) : ENNReal.ofReal (p + q) = ENNReal.ofReal p + ENNReal.ofReal q := by rw [ENNReal.ofReal, ENNReal.ofReal, ENNReal.ofReal, ← coe_add, coe_inj, Real.toNNReal_add hp hq] theorem ofReal_add_le {p q : ℝ} : ENNReal.ofReal (p + q) ≀ ENNReal.ofReal p + ENNReal.ofReal q := coe_le_coe.2 Real.toNNReal_add_le @[simp] theorem toReal_le_toReal (ha : a β‰  ∞) (hb : b β‰  ∞) : a.toReal ≀ b.toReal ↔ a ≀ b := by lift a to ℝβ‰₯0 using ha lift b to ℝβ‰₯0 using hb norm_cast @[gcongr] theorem toReal_mono (hb : b β‰  ∞) (h : a ≀ b) : a.toReal ≀ b.toReal := (toReal_le_toReal (ne_top_of_le_ne_top hb h) hb).2 h theorem toReal_mono' (h : a ≀ b) (ht : b = ∞ β†’ a = ∞) : a.toReal ≀ b.toReal := by rcases eq_or_ne a ∞ with rfl | ha Β· exact toReal_nonneg Β· exact toReal_mono (mt ht ha) h @[simp] theorem toReal_lt_toReal (ha : a β‰  ∞) (hb : b β‰  ∞) : a.toReal < b.toReal ↔ a < b := by lift a to ℝβ‰₯0 using ha lift b to ℝβ‰₯0 using hb norm_cast @[gcongr] theorem toReal_strict_mono (hb : b β‰  ∞) (h : a < b) : a.toReal < b.toReal := (toReal_lt_toReal h.ne_top hb).2 h @[gcongr] theorem toNNReal_mono (hb : b β‰  ∞) (h : a ≀ b) : a.toNNReal ≀ b.toNNReal := toReal_mono hb h theorem le_toNNReal_of_coe_le (h : p ≀ a) (ha : a β‰  ∞) : p ≀ a.toNNReal := @toNNReal_coe p β–Έ toNNReal_mono ha h @[simp] theorem toNNReal_le_toNNReal (ha : a β‰  ∞) (hb : b β‰  ∞) : a.toNNReal ≀ b.toNNReal ↔ a ≀ b := ⟨fun h => by rwa [← coe_toNNReal ha, ← coe_toNNReal hb, coe_le_coe], toNNReal_mono hb⟩ @[gcongr] theorem toNNReal_strict_mono (hb : b β‰  ∞) (h : a < b) : a.toNNReal < b.toNNReal := by simpa [← ENNReal.coe_lt_coe, hb, h.ne_top] @[simp] theorem toNNReal_lt_toNNReal (ha : a β‰  ∞) (hb : b β‰  ∞) : a.toNNReal < b.toNNReal ↔ a < b := ⟨fun h => by rwa [← coe_toNNReal ha, ← coe_toNNReal hb, coe_lt_coe], toNNReal_strict_mono hb⟩ theorem toNNReal_lt_of_lt_coe (h : a < p) : a.toNNReal < p := @toNNReal_coe p β–Έ toNNReal_strict_mono coe_ne_top h theorem toReal_max (hr : a β‰  ∞) (hp : b β‰  ∞) : ENNReal.toReal (max a b) = max (ENNReal.toReal a) (ENNReal.toReal b) := (le_total a b).elim (fun h => by simp only [h, ENNReal.toReal_mono hp h, max_eq_right]) fun h => by simp only [h, ENNReal.toReal_mono hr h, max_eq_left] theorem toReal_min {a b : ℝβ‰₯0∞} (hr : a β‰  ∞) (hp : b β‰  ∞) : ENNReal.toReal (min a b) = min (ENNReal.toReal a) (ENNReal.toReal b) := (le_total a b).elim (fun h => by simp only [h, ENNReal.toReal_mono hp h, min_eq_left]) fun h => by simp only [h, ENNReal.toReal_mono hr h, min_eq_right] theorem toReal_sup {a b : ℝβ‰₯0∞} : a β‰  ∞ β†’ b β‰  ∞ β†’ (a βŠ” b).toReal = a.toReal βŠ” b.toReal := toReal_max theorem toReal_inf {a b : ℝβ‰₯0∞} : a β‰  ∞ β†’ b β‰  ∞ β†’ (a βŠ“ b).toReal = a.toReal βŠ“ b.toReal := toReal_min theorem toNNReal_pos_iff : 0 < a.toNNReal ↔ 0 < a ∧ a < ∞ := by induction a <;> simp theorem toNNReal_pos {a : ℝβ‰₯0∞} (haβ‚€ : a β‰  0) (ha_top : a β‰  ∞) : 0 < a.toNNReal := toNNReal_pos_iff.mpr ⟨bot_lt_iff_ne_bot.mpr haβ‚€, lt_top_iff_ne_top.mpr ha_top⟩ theorem toReal_pos_iff : 0 < a.toReal ↔ 0 < a ∧ a < ∞ := NNReal.coe_pos.trans toNNReal_pos_iff theorem toReal_pos {a : ℝβ‰₯0∞} (haβ‚€ : a β‰  0) (ha_top : a β‰  ∞) : 0 < a.toReal := toReal_pos_iff.mpr ⟨bot_lt_iff_ne_bot.mpr haβ‚€, lt_top_iff_ne_top.mpr ha_top⟩ @[gcongr, bound] theorem ofReal_le_ofReal {p q : ℝ} (h : p ≀ q) : ENNReal.ofReal p ≀ ENNReal.ofReal q := by simp [ENNReal.ofReal, Real.toNNReal_le_toNNReal h] lemma ofReal_mono : Monotone ENNReal.ofReal := fun _ _ ↦ ENNReal.ofReal_le_ofReal theorem ofReal_le_of_le_toReal {a : ℝ} {b : ℝβ‰₯0∞} (h : a ≀ ENNReal.toReal b) : ENNReal.ofReal a ≀ b := (ofReal_le_ofReal h).trans ofReal_toReal_le @[simp] theorem ofReal_le_ofReal_iff {p q : ℝ} (h : 0 ≀ q) : ENNReal.ofReal p ≀ ENNReal.ofReal q ↔ p ≀ q := by rw [ENNReal.ofReal, ENNReal.ofReal, coe_le_coe, Real.toNNReal_le_toNNReal_iff h] lemma ofReal_le_ofReal_iff' {p q : ℝ} : ENNReal.ofReal p ≀ .ofReal q ↔ p ≀ q ∨ p ≀ 0 := coe_le_coe.trans Real.toNNReal_le_toNNReal_iff' @[simp, norm_cast] lemma ofReal_le_coe {a : ℝ} {b : ℝβ‰₯0} : ENNReal.ofReal a ≀ b ↔ a ≀ b := by simp [← ofReal_le_ofReal_iff] lemma ofReal_lt_ofReal_iff' {p q : ℝ} : ENNReal.ofReal p < .ofReal q ↔ p < q ∧ 0 < q := coe_lt_coe.trans Real.toNNReal_lt_toNNReal_iff' @[simp] theorem ofReal_eq_ofReal_iff {p q : ℝ} (hp : 0 ≀ p) (hq : 0 ≀ q) : ENNReal.ofReal p = ENNReal.ofReal q ↔ p = q := by rw [ENNReal.ofReal, ENNReal.ofReal, coe_inj, Real.toNNReal_eq_toNNReal_iff hp hq] @[simp] theorem ofReal_lt_ofReal_iff {p q : ℝ} (h : 0 < q) : ENNReal.ofReal p < ENNReal.ofReal q ↔ p < q := by rw [ENNReal.ofReal, ENNReal.ofReal, coe_lt_coe, Real.toNNReal_lt_toNNReal_iff h] theorem ofReal_lt_ofReal_iff_of_nonneg {p q : ℝ} (hp : 0 ≀ p) : ENNReal.ofReal p < ENNReal.ofReal q ↔ p < q := by rw [ENNReal.ofReal, ENNReal.ofReal, coe_lt_coe, Real.toNNReal_lt_toNNReal_iff_of_nonneg hp] @[simp] theorem ofReal_pos {p : ℝ} : 0 < ENNReal.ofReal p ↔ 0 < p := by simp [ENNReal.ofReal] @[bound] private alias ⟨_, Bound.ofReal_pos_of_pos⟩ := ofReal_pos @[simp] theorem ofReal_eq_zero {p : ℝ} : ENNReal.ofReal p = 0 ↔ p ≀ 0 := by simp [ENNReal.ofReal] @[simp] lemma ofReal_min (x y : ℝ) : ENNReal.ofReal (min x y) = min (.ofReal x) (.ofReal y) := ofReal_mono.map_min @[simp] lemma ofReal_max (x y : ℝ) : ENNReal.ofReal (max x y) = max (.ofReal x) (.ofReal y) := ofReal_mono.map_max theorem ofReal_ne_zero_iff {r : ℝ} : ENNReal.ofReal r β‰  0 ↔ 0 < r := by rw [← zero_lt_iff, ENNReal.ofReal_pos] @[simp] theorem zero_eq_ofReal {p : ℝ} : 0 = ENNReal.ofReal p ↔ p ≀ 0 := eq_comm.trans ofReal_eq_zero alias ⟨_, ofReal_of_nonpos⟩ := ofReal_eq_zero @[simp] lemma ofReal_lt_natCast {p : ℝ} {n : β„•} (hn : n β‰  0) : ENNReal.ofReal p < n ↔ p < n := by exact mod_cast ofReal_lt_ofReal_iff (Nat.cast_pos.2 hn.bot_lt) @[simp] lemma ofReal_lt_one {p : ℝ} : ENNReal.ofReal p < 1 ↔ p < 1 := by exact mod_cast ofReal_lt_natCast one_ne_zero @[simp] lemma ofReal_lt_ofNat {p : ℝ} {n : β„•} [n.AtLeastTwo] : ENNReal.ofReal p < ofNat(n) ↔ p < OfNat.ofNat n := ofReal_lt_natCast (NeZero.ne n) @[simp] lemma natCast_le_ofReal {n : β„•} {p : ℝ} (hn : n β‰  0) : n ≀ ENNReal.ofReal p ↔ n ≀ p := by simp only [← not_lt, ofReal_lt_natCast hn] @[simp] lemma one_le_ofReal {p : ℝ} : 1 ≀ ENNReal.ofReal p ↔ 1 ≀ p := by exact mod_cast natCast_le_ofReal one_ne_zero @[simp] lemma ofNat_le_ofReal {n : β„•} [n.AtLeastTwo] {p : ℝ} : ofNat(n) ≀ ENNReal.ofReal p ↔ OfNat.ofNat n ≀ p := natCast_le_ofReal (NeZero.ne n) @[simp, norm_cast] lemma ofReal_le_natCast {r : ℝ} {n : β„•} : ENNReal.ofReal r ≀ n ↔ r ≀ n := coe_le_coe.trans Real.toNNReal_le_natCast @[simp] lemma ofReal_le_one {r : ℝ} : ENNReal.ofReal r ≀ 1 ↔ r ≀ 1 := coe_le_coe.trans Real.toNNReal_le_one @[simp] lemma ofReal_le_ofNat {r : ℝ} {n : β„•} [n.AtLeastTwo] : ENNReal.ofReal r ≀ ofNat(n) ↔ r ≀ OfNat.ofNat n := ofReal_le_natCast @[simp] lemma natCast_lt_ofReal {n : β„•} {r : ℝ} : n < ENNReal.ofReal r ↔ n < r := coe_lt_coe.trans Real.natCast_lt_toNNReal @[simp] lemma one_lt_ofReal {r : ℝ} : 1 < ENNReal.ofReal r ↔ 1 < r := coe_lt_coe.trans Real.one_lt_toNNReal @[simp] lemma ofNat_lt_ofReal {n : β„•} [n.AtLeastTwo] {r : ℝ} : ofNat(n) < ENNReal.ofReal r ↔ OfNat.ofNat n < r := natCast_lt_ofReal @[simp] lemma ofReal_eq_natCast {r : ℝ} {n : β„•} (h : n β‰  0) : ENNReal.ofReal r = n ↔ r = n := ENNReal.coe_inj.trans <| Real.toNNReal_eq_natCast h @[simp] lemma ofReal_eq_one {r : ℝ} : ENNReal.ofReal r = 1 ↔ r = 1 := ENNReal.coe_inj.trans Real.toNNReal_eq_one @[simp] lemma ofReal_eq_ofNat {r : ℝ} {n : β„•} [n.AtLeastTwo] : ENNReal.ofReal r = ofNat(n) ↔ r = OfNat.ofNat n := ofReal_eq_natCast (NeZero.ne n) theorem ofReal_le_iff_le_toReal {a : ℝ} {b : ℝβ‰₯0∞} (hb : b β‰  ∞) : ENNReal.ofReal a ≀ b ↔ a ≀ ENNReal.toReal b := by lift b to ℝβ‰₯0 using hb simpa [ENNReal.ofReal, ENNReal.toReal] using Real.toNNReal_le_iff_le_coe theorem ofReal_lt_iff_lt_toReal {a : ℝ} {b : ℝβ‰₯0∞} (ha : 0 ≀ a) (hb : b β‰  ∞) : ENNReal.ofReal a < b ↔ a < ENNReal.toReal b := by lift b to ℝβ‰₯0 using hb simpa [ENNReal.ofReal, ENNReal.toReal] using Real.toNNReal_lt_iff_lt_coe ha theorem ofReal_lt_coe_iff {a : ℝ} {b : ℝβ‰₯0} (ha : 0 ≀ a) : ENNReal.ofReal a < b ↔ a < b := (ofReal_lt_iff_lt_toReal ha coe_ne_top).trans <| by rw [coe_toReal] theorem le_ofReal_iff_toReal_le {a : ℝβ‰₯0∞} {b : ℝ} (ha : a β‰  ∞) (hb : 0 ≀ b) : a ≀ ENNReal.ofReal b ↔ ENNReal.toReal a ≀ b := by lift a to ℝβ‰₯0 using ha simpa [ENNReal.ofReal, ENNReal.toReal] using Real.le_toNNReal_iff_coe_le hb theorem toReal_le_of_le_ofReal {a : ℝβ‰₯0∞} {b : ℝ} (hb : 0 ≀ b) (h : a ≀ ENNReal.ofReal b) : ENNReal.toReal a ≀ b := have ha : a β‰  ∞ := ne_top_of_le_ne_top ofReal_ne_top h (le_ofReal_iff_toReal_le ha hb).1 h theorem lt_ofReal_iff_toReal_lt {a : ℝβ‰₯0∞} {b : ℝ} (ha : a β‰  ∞) : a < ENNReal.ofReal b ↔ ENNReal.toReal a < b := by lift a to ℝβ‰₯0 using ha simpa [ENNReal.ofReal, ENNReal.toReal] using Real.lt_toNNReal_iff_coe_lt theorem toReal_lt_of_lt_ofReal {b : ℝ} (h : a < ENNReal.ofReal b) : ENNReal.toReal a < b := (lt_ofReal_iff_toReal_lt h.ne_top).1 h @[simp] theorem ofReal_mul {p q : ℝ} (hp : 0 ≀ p) : ENNReal.ofReal (p * q) = ENNReal.ofReal p * ENNReal.ofReal q := by simp only [ENNReal.ofReal, ← coe_mul, Real.toNNReal_mul hp] theorem ofReal_mul' {p q : ℝ} (hq : 0 ≀ q) : ENNReal.ofReal (p * q) = ENNReal.ofReal p * ENNReal.ofReal q := by rw [mul_comm, ofReal_mul hq, mul_comm] @[simp] theorem ofReal_pow {p : ℝ} (hp : 0 ≀ p) (n : β„•) : ENNReal.ofReal (p ^ n) = ENNReal.ofReal p ^ n := by rw [ofReal_eq_coe_nnreal hp, ← coe_pow, ← ofReal_coe_nnreal, NNReal.coe_pow, NNReal.coe_mk] theorem ofReal_nsmul {x : ℝ} {n : β„•} : ENNReal.ofReal (n β€’ x) = n β€’ ENNReal.ofReal x := by simp only [nsmul_eq_mul, ← ofReal_natCast n, ← ofReal_mul n.cast_nonneg] @[simp] theorem toNNReal_mul {a b : ℝβ‰₯0∞} : (a * b).toNNReal = a.toNNReal * b.toNNReal := WithTop.untopD_zero_mul a b theorem toNNReal_mul_top (a : ℝβ‰₯0∞) : ENNReal.toNNReal (a * ∞) = 0 := by simp theorem toNNReal_top_mul (a : ℝβ‰₯0∞) : ENNReal.toNNReal (∞ * a) = 0 := by simp /-- `ENNReal.toNNReal` as a `MonoidHom`. -/ def toNNRealHom : ℝβ‰₯0∞ β†’*β‚€ ℝβ‰₯0 where toFun := ENNReal.toNNReal map_one' := toNNReal_coe _ map_mul' _ _ := toNNReal_mul map_zero' := toNNReal_zero @[simp] theorem toNNReal_pow (a : ℝβ‰₯0∞) (n : β„•) : (a ^ n).toNNReal = a.toNNReal ^ n := toNNRealHom.map_pow a n /-- `ENNReal.toReal` as a `MonoidHom`. -/ def toRealHom : ℝβ‰₯0∞ β†’*β‚€ ℝ := (NNReal.toRealHom : ℝβ‰₯0 β†’*β‚€ ℝ).comp toNNRealHom @[simp] theorem toReal_mul : (a * b).toReal = a.toReal * b.toReal := toRealHom.map_mul a b theorem toReal_nsmul (a : ℝβ‰₯0∞) (n : β„•) : (n β€’ a).toReal = n β€’ a.toReal := by simp @[simp] theorem toReal_pow (a : ℝβ‰₯0∞) (n : β„•) : (a ^ n).toReal = a.toReal ^ n := toRealHom.map_pow a n theorem toReal_ofReal_mul (c : ℝ) (a : ℝβ‰₯0∞) (h : 0 ≀ c) : ENNReal.toReal (ENNReal.ofReal c * a) = c * ENNReal.toReal a := by rw [ENNReal.toReal_mul, ENNReal.toReal_ofReal h] theorem toReal_mul_top (a : ℝβ‰₯0∞) : ENNReal.toReal (a * ∞) = 0 := by rw [toReal_mul, toReal_top, mul_zero] theorem toReal_top_mul (a : ℝβ‰₯0∞) : ENNReal.toReal (∞ * a) = 0 := by rw [mul_comm] exact toReal_mul_top _ @[deprecated (since := "2025-11-07")] alias toReal_eq_toReal := toReal_eq_toReal_iff' protected theorem trichotomy (p : ℝβ‰₯0∞) : p = 0 ∨ p = ∞ ∨ 0 < p.toReal := by simpa only [or_iff_not_imp_left] using toReal_pos protected theorem trichotomyβ‚‚ {p q : ℝβ‰₯0∞} (hpq : p ≀ q) : p = 0 ∧ q = 0 ∨ p = 0 ∧ q = ∞ ∨ p = 0 ∧ 0 < q.toReal ∨ p = ∞ ∧ q = ∞ ∨ 0 < p.toReal ∧ q = ∞ ∨ 0 < p.toReal ∧ 0 < q.toReal ∧ p.toReal ≀ q.toReal := by rcases eq_or_lt_of_le (bot_le : 0 ≀ p) with ((rfl : 0 = p) | (hp : 0 < p)) Β· simpa using q.trichotomy rcases eq_or_lt_of_le (le_top : q ≀ ∞) with (rfl | hq) Β· simpa using p.trichotomy have hq' : 0 < q := lt_of_lt_of_le hp hpq have hp' : p < ∞ := lt_of_le_of_lt hpq hq simp [ENNReal.toReal_mono hq.ne hpq, ENNReal.toReal_pos_iff, hp, hp', hq', hq] protected theorem dichotomy (p : ℝβ‰₯0∞) [Fact (1 ≀ p)] : p = ∞ ∨ 1 ≀ p.toReal := haveI : p = ⊀ ∨ 0 < p.toReal ∧ 1 ≀ p.toReal := by simpa using ENNReal.trichotomyβ‚‚ (Fact.out : 1 ≀ p) this.imp_right fun h => h.2 theorem toReal_pos_iff_ne_top (p : ℝβ‰₯0∞) [Fact (1 ≀ p)] : 0 < p.toReal ↔ p β‰  ∞ := ⟨fun h hp => have : (0 : ℝ) β‰  0 := toReal_top β–Έ (hp β–Έ h.ne : 0 β‰  ∞.toReal) this rfl, fun h => zero_lt_one.trans_le (p.dichotomy.resolve_left h)⟩ end Real @[deprecated max_eq_zero_iff (since := "2025-10-25")] theorem sup_eq_zero {a b : ℝβ‰₯0∞} : a βŠ” b = 0 ↔ a = 0 ∧ b = 0 := sup_eq_bot_iff end ENNReal namespace Mathlib.Meta.Positivity open Lean Meta Qq /-- Extension for the `positivity` tactic: `ENNReal.ofReal`. -/ @[positivity ENNReal.ofReal _] def evalENNRealOfReal : PositivityExt where eval {u Ξ±} _zΞ± _pΞ± e := do match u, Ξ±, e with | 0, ~q(ℝβ‰₯0∞), ~q(ENNReal.ofReal $a) => let ra ← core q(inferInstance) q(inferInstance) a assertInstancesCommute match ra with | .positive pa => pure (.positive q(Iff.mpr (@ENNReal.ofReal_pos $a) $pa)) | _ => pure .none | _, _, _ => throwError "not ENNReal.ofReal" end Mathlib.Meta.Positivity