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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.