path
stringlengths
11
71
content
stringlengths
75
124k
Data\PNat\Find.lean
/- Copyright (c) 2022 Yakov Pechersky. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yakov Pechersky, Floris van Doorn -/ import Mathlib.Data.Nat.Find import Mathlib.Data.PNat.Basic /-! # Explicit least witnesses to existentials on positive natural numbers Implemented via calling out to `Nat.find`. -/ namespace PNat variable {p q : ℕ+ → Prop} [DecidablePred p] [DecidablePred q] (h : ∃ n, p n) instance decidablePredExistsNat : DecidablePred fun n' : ℕ => ∃ (n : ℕ+) (_ : n' = n), p n := fun n' => decidable_of_iff' (∃ h : 0 < n', p ⟨n', h⟩) <| Subtype.exists.trans <| by simp_rw [mk_coe, @exists_comm (_ < _) (_ = _), exists_prop, exists_eq_left'] /-- The `PNat` version of `Nat.findX` -/ protected def findX : { n // p n ∧ ∀ m : ℕ+, m < n → ¬p m } := by have : ∃ (n' : ℕ) (n : ℕ+) (_ : n' = n), p n := Exists.elim h fun n hn => ⟨n, n, rfl, hn⟩ have n := Nat.findX this refine ⟨⟨n, ?_⟩, ?_, fun m hm pm => ?_⟩ · obtain ⟨n', hn', -⟩ := n.prop.1 rw [hn'] exact n'.prop · obtain ⟨n', hn', pn'⟩ := n.prop.1 simpa [hn', Subtype.coe_eta] using pn' · exact n.prop.2 m hm ⟨m, rfl, pm⟩ /-- If `p` is a (decidable) predicate on `ℕ+` and `hp : ∃ (n : ℕ+), p n` is a proof that there exists some positive natural number satisfying `p`, then `PNat.find hp` is the smallest positive natural number satisfying `p`. Note that `PNat.find` is protected, meaning that you can't just write `find`, even if the `PNat` namespace is open. The API for `PNat.find` is: * `PNat.find_spec` is the proof that `PNat.find hp` satisfies `p`. * `PNat.find_min` is the proof that if `m < PNat.find hp` then `m` does not satisfy `p`. * `PNat.find_min'` is the proof that if `m` does satisfy `p` then `PNat.find hp ≤ m`. -/ protected def find : ℕ+ := PNat.findX h protected theorem find_spec : p (PNat.find h) := (PNat.findX h).prop.left protected theorem find_min : ∀ {m : ℕ+}, m < PNat.find h → ¬p m := @(PNat.findX h).prop.right protected theorem find_min' {m : ℕ+} (hm : p m) : PNat.find h ≤ m := le_of_not_lt fun l => PNat.find_min h l hm variable {n m : ℕ+} theorem find_eq_iff : PNat.find h = m ↔ p m ∧ ∀ n < m, ¬p n := by constructor · rintro rfl exact ⟨PNat.find_spec h, fun _ => PNat.find_min h⟩ · rintro ⟨hm, hlt⟩ exact le_antisymm (PNat.find_min' h hm) (not_lt.1 <| imp_not_comm.1 (hlt _) <| PNat.find_spec h) @[simp] theorem find_lt_iff (n : ℕ+) : PNat.find h < n ↔ ∃ m < n, p m := ⟨fun h2 => ⟨PNat.find h, h2, PNat.find_spec h⟩, fun ⟨_, hmn, hm⟩ => (PNat.find_min' h hm).trans_lt hmn⟩ @[simp] theorem find_le_iff (n : ℕ+) : PNat.find h ≤ n ↔ ∃ m ≤ n, p m := by simp only [exists_prop, ← lt_add_one_iff, find_lt_iff] @[simp] theorem le_find_iff (n : ℕ+) : n ≤ PNat.find h ↔ ∀ m < n, ¬p m := by simp only [← not_lt, find_lt_iff, not_exists, not_and] @[simp] theorem lt_find_iff (n : ℕ+) : n < PNat.find h ↔ ∀ m ≤ n, ¬p m := by simp only [← add_one_le_iff, le_find_iff, add_le_add_iff_right] @[simp] theorem find_eq_one : PNat.find h = 1 ↔ p 1 := by simp [find_eq_iff] -- Porting note: deleted `@[simp]` to satisfy the linter because `le_find_iff` is more general theorem one_le_find : 1 < PNat.find h ↔ ¬p 1 := not_iff_not.mp <| by simp theorem find_mono (h : ∀ n, q n → p n) {hp : ∃ n, p n} {hq : ∃ n, q n} : PNat.find hp ≤ PNat.find hq := PNat.find_min' _ (h _ (PNat.find_spec hq)) theorem find_le {h : ∃ n, p n} (hn : p n) : PNat.find h ≤ n := (PNat.find_le_iff _ _).2 ⟨n, le_rfl, hn⟩ theorem find_comp_succ (h : ∃ n, p n) (h₂ : ∃ n, p (n + 1)) (h1 : ¬p 1) : PNat.find h = PNat.find h₂ + 1 := by refine (find_eq_iff _).2 ⟨PNat.find_spec h₂, fun n => PNat.recOn n ?_ ?_⟩ · simp [h1] intro m _ hm simp only [add_lt_add_iff_right, lt_find_iff] at hm exact hm _ le_rfl end PNat
Data\PNat\Interval.lean
/- Copyright (c) 2021 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import Mathlib.Order.Interval.Finset.Nat import Mathlib.Data.PNat.Defs /-! # Finite intervals of positive naturals This file proves that `ℕ+` is a `LocallyFiniteOrder` and calculates the cardinality of its intervals as finsets and fintypes. -/ open Finset Function PNat namespace PNat variable (a b : ℕ+) instance instLocallyFiniteOrder : LocallyFiniteOrder ℕ+ := Subtype.instLocallyFiniteOrder _ theorem Icc_eq_finset_subtype : Icc a b = (Icc (a : ℕ) b).subtype fun n : ℕ => 0 < n := rfl theorem Ico_eq_finset_subtype : Ico a b = (Ico (a : ℕ) b).subtype fun n : ℕ => 0 < n := rfl theorem Ioc_eq_finset_subtype : Ioc a b = (Ioc (a : ℕ) b).subtype fun n : ℕ => 0 < n := rfl theorem Ioo_eq_finset_subtype : Ioo a b = (Ioo (a : ℕ) b).subtype fun n : ℕ => 0 < n := rfl theorem uIcc_eq_finset_subtype : uIcc a b = (uIcc (a : ℕ) b).subtype fun n : ℕ => 0 < n := rfl theorem map_subtype_embedding_Icc : (Icc a b).map (Embedding.subtype _) = Icc ↑a ↑b := Finset.map_subtype_embedding_Icc _ _ _ fun _c _ _x hx _ hc _ => hc.trans_le hx theorem map_subtype_embedding_Ico : (Ico a b).map (Embedding.subtype _) = Ico ↑a ↑b := Finset.map_subtype_embedding_Ico _ _ _ fun _c _ _x hx _ hc _ => hc.trans_le hx theorem map_subtype_embedding_Ioc : (Ioc a b).map (Embedding.subtype _) = Ioc ↑a ↑b := Finset.map_subtype_embedding_Ioc _ _ _ fun _c _ _x hx _ hc _ => hc.trans_le hx theorem map_subtype_embedding_Ioo : (Ioo a b).map (Embedding.subtype _) = Ioo ↑a ↑b := Finset.map_subtype_embedding_Ioo _ _ _ fun _c _ _x hx _ hc _ => hc.trans_le hx theorem map_subtype_embedding_uIcc : (uIcc a b).map (Embedding.subtype _) = uIcc ↑a ↑b := map_subtype_embedding_Icc _ _ @[simp] theorem card_Icc : (Icc a b).card = b + 1 - a := by rw [← Nat.card_Icc] -- Porting note: I had to change this to `erw` *and* provide the proof, yuck. -- https://github.com/leanprover-community/mathlib4/issues/5164 erw [← Finset.map_subtype_embedding_Icc _ a b (fun c x _ hx _ hc _ => hc.trans_le hx)] rw [card_map] @[simp] theorem card_Ico : (Ico a b).card = b - a := by rw [← Nat.card_Ico] -- Porting note: I had to change this to `erw` *and* provide the proof, yuck. -- https://github.com/leanprover-community/mathlib4/issues/5164 erw [← Finset.map_subtype_embedding_Ico _ a b (fun c x _ hx _ hc _ => hc.trans_le hx)] rw [card_map] @[simp] theorem card_Ioc : (Ioc a b).card = b - a := by rw [← Nat.card_Ioc] -- Porting note: I had to change this to `erw` *and* provide the proof, yuck. -- https://github.com/leanprover-community/mathlib4/issues/5164 erw [← Finset.map_subtype_embedding_Ioc _ a b (fun c x _ hx _ hc _ => hc.trans_le hx)] rw [card_map] @[simp] theorem card_Ioo : (Ioo a b).card = b - a - 1 := by rw [← Nat.card_Ioo] -- Porting note: I had to change this to `erw` *and* provide the proof, yuck. -- https://github.com/leanprover-community/mathlib4/issues/5164 erw [← Finset.map_subtype_embedding_Ioo _ a b (fun c x _ hx _ hc _ => hc.trans_le hx)] rw [card_map] @[simp] theorem card_uIcc : (uIcc a b).card = (b - a : ℤ).natAbs + 1 := by rw [← Nat.card_uIcc, ← map_subtype_embedding_uIcc, card_map] -- Porting note: `simpNF` says `simp` can prove this theorem card_fintype_Icc : Fintype.card (Set.Icc a b) = b + 1 - a := by rw [← card_Icc, Fintype.card_ofFinset] -- Porting note: `simpNF` says `simp` can prove this theorem card_fintype_Ico : Fintype.card (Set.Ico a b) = b - a := by rw [← card_Ico, Fintype.card_ofFinset] -- Porting note: `simpNF` says `simp` can prove this theorem card_fintype_Ioc : Fintype.card (Set.Ioc a b) = b - a := by rw [← card_Ioc, Fintype.card_ofFinset] -- Porting note: `simpNF` says `simp` can prove this theorem card_fintype_Ioo : Fintype.card (Set.Ioo a b) = b - a - 1 := by rw [← card_Ioo, Fintype.card_ofFinset] -- Porting note: `simpNF` says `simp` can prove this theorem card_fintype_uIcc : Fintype.card (Set.uIcc a b) = (b - a : ℤ).natAbs + 1 := by rw [← card_uIcc, Fintype.card_ofFinset] end PNat
Data\PNat\Prime.lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Neil Strickland -/ import Mathlib.Data.Nat.Prime.Defs import Mathlib.Data.PNat.Basic /-! # Primality and GCD on pnat This file extends the theory of `ℕ+` with `gcd`, `lcm` and `Prime` functions, analogous to those on `Nat`. -/ namespace Nat.Primes -- Porting note (#11445): new definition /-- The canonical map from `Nat.Primes` to `ℕ+` -/ @[coe] def toPNat : Nat.Primes → ℕ+ := fun p => ⟨(p : ℕ), p.property.pos⟩ instance coePNat : Coe Nat.Primes ℕ+ := ⟨toPNat⟩ @[norm_cast] theorem coe_pnat_nat (p : Nat.Primes) : ((p : ℕ+) : ℕ) = p := rfl theorem coe_pnat_injective : Function.Injective ((↑) : Nat.Primes → ℕ+) := fun p q h => Subtype.ext (by injection h) @[norm_cast] theorem coe_pnat_inj (p q : Nat.Primes) : (p : ℕ+) = (q : ℕ+) ↔ p = q := coe_pnat_injective.eq_iff end Nat.Primes namespace PNat open Nat /-- The greatest common divisor (gcd) of two positive natural numbers, viewed as positive natural number. -/ def gcd (n m : ℕ+) : ℕ+ := ⟨Nat.gcd (n : ℕ) (m : ℕ), Nat.gcd_pos_of_pos_left (m : ℕ) n.pos⟩ /-- The least common multiple (lcm) of two positive natural numbers, viewed as positive natural number. -/ def lcm (n m : ℕ+) : ℕ+ := ⟨Nat.lcm (n : ℕ) (m : ℕ), by let h := mul_pos n.pos m.pos rw [← gcd_mul_lcm (n : ℕ) (m : ℕ), mul_comm] at h exact pos_of_dvd_of_pos (Dvd.intro (Nat.gcd (n : ℕ) (m : ℕ)) rfl) h⟩ @[simp, norm_cast] theorem gcd_coe (n m : ℕ+) : (gcd n m : ℕ) = Nat.gcd n m := rfl @[simp, norm_cast] theorem lcm_coe (n m : ℕ+) : (lcm n m : ℕ) = Nat.lcm n m := rfl theorem gcd_dvd_left (n m : ℕ+) : gcd n m ∣ n := dvd_iff.2 (Nat.gcd_dvd_left (n : ℕ) (m : ℕ)) theorem gcd_dvd_right (n m : ℕ+) : gcd n m ∣ m := dvd_iff.2 (Nat.gcd_dvd_right (n : ℕ) (m : ℕ)) theorem dvd_gcd {m n k : ℕ+} (hm : k ∣ m) (hn : k ∣ n) : k ∣ gcd m n := dvd_iff.2 (Nat.dvd_gcd (dvd_iff.1 hm) (dvd_iff.1 hn)) theorem dvd_lcm_left (n m : ℕ+) : n ∣ lcm n m := dvd_iff.2 (Nat.dvd_lcm_left (n : ℕ) (m : ℕ)) theorem dvd_lcm_right (n m : ℕ+) : m ∣ lcm n m := dvd_iff.2 (Nat.dvd_lcm_right (n : ℕ) (m : ℕ)) theorem lcm_dvd {m n k : ℕ+} (hm : m ∣ k) (hn : n ∣ k) : lcm m n ∣ k := dvd_iff.2 (@Nat.lcm_dvd (m : ℕ) (n : ℕ) (k : ℕ) (dvd_iff.1 hm) (dvd_iff.1 hn)) theorem gcd_mul_lcm (n m : ℕ+) : gcd n m * lcm n m = n * m := Subtype.eq (Nat.gcd_mul_lcm (n : ℕ) (m : ℕ)) theorem eq_one_of_lt_two {n : ℕ+} : n < 2 → n = 1 := by intro h; apply le_antisymm; swap · apply PNat.one_le · exact PNat.lt_add_one_iff.1 h section Prime /-! ### Prime numbers -/ /-- Primality predicate for `ℕ+`, defined in terms of `Nat.Prime`. -/ def Prime (p : ℕ+) : Prop := (p : ℕ).Prime theorem Prime.one_lt {p : ℕ+} : p.Prime → 1 < p := Nat.Prime.one_lt theorem prime_two : (2 : ℕ+).Prime := Nat.prime_two instance {p : ℕ+} [h : Fact p.Prime] : Fact (p : ℕ).Prime := h instance fact_prime_two : Fact (2 : ℕ+).Prime := ⟨prime_two⟩ theorem prime_three : (3 : ℕ+).Prime := Nat.prime_three instance fact_prime_three : Fact (3 : ℕ+).Prime := ⟨prime_three⟩ theorem prime_five : (5 : ℕ+).Prime := Nat.prime_five instance fact_prime_five : Fact (5 : ℕ+).Prime := ⟨prime_five⟩ theorem dvd_prime {p m : ℕ+} (pp : p.Prime) : m ∣ p ↔ m = 1 ∨ m = p := by rw [PNat.dvd_iff] rw [Nat.dvd_prime pp] simp theorem Prime.ne_one {p : ℕ+} : p.Prime → p ≠ 1 := by intro pp intro contra apply Nat.Prime.ne_one pp rw [PNat.coe_eq_one_iff] apply contra @[simp] theorem not_prime_one : ¬(1 : ℕ+).Prime := Nat.not_prime_one theorem Prime.not_dvd_one {p : ℕ+} : p.Prime → ¬p ∣ 1 := fun pp : p.Prime => by rw [dvd_iff] apply Nat.Prime.not_dvd_one pp theorem exists_prime_and_dvd {n : ℕ+} (hn : n ≠ 1) : ∃ p : ℕ+, p.Prime ∧ p ∣ n := by obtain ⟨p, hp⟩ := Nat.exists_prime_and_dvd (mt coe_eq_one_iff.mp hn) exists (⟨p, Nat.Prime.pos hp.left⟩ : ℕ+); rw [dvd_iff]; apply hp end Prime section Coprime /-! ### Coprime numbers and gcd -/ /-- Two pnats are coprime if their gcd is 1. -/ def Coprime (m n : ℕ+) : Prop := m.gcd n = 1 @[simp, norm_cast] theorem coprime_coe {m n : ℕ+} : Nat.Coprime ↑m ↑n ↔ m.Coprime n := by unfold Nat.Coprime Coprime rw [← coe_inj] simp theorem Coprime.mul {k m n : ℕ+} : m.Coprime k → n.Coprime k → (m * n).Coprime k := by repeat rw [← coprime_coe] rw [mul_coe] apply Nat.Coprime.mul theorem Coprime.mul_right {k m n : ℕ+} : k.Coprime m → k.Coprime n → k.Coprime (m * n) := by repeat rw [← coprime_coe] rw [mul_coe] apply Nat.Coprime.mul_right theorem gcd_comm {m n : ℕ+} : m.gcd n = n.gcd m := by apply eq simp only [gcd_coe] apply Nat.gcd_comm theorem gcd_eq_left_iff_dvd {m n : ℕ+} : m ∣ n ↔ m.gcd n = m := by rw [dvd_iff] rw [Nat.gcd_eq_left_iff_dvd] rw [← coe_inj] simp theorem gcd_eq_right_iff_dvd {m n : ℕ+} : m ∣ n ↔ n.gcd m = m := by rw [gcd_comm] apply gcd_eq_left_iff_dvd theorem Coprime.gcd_mul_left_cancel (m : ℕ+) {n k : ℕ+} : k.Coprime n → (k * m).gcd n = m.gcd n := by intro h; apply eq; simp only [gcd_coe, mul_coe] apply Nat.Coprime.gcd_mul_left_cancel; simpa theorem Coprime.gcd_mul_right_cancel (m : ℕ+) {n k : ℕ+} : k.Coprime n → (m * k).gcd n = m.gcd n := by rw [mul_comm]; apply Coprime.gcd_mul_left_cancel theorem Coprime.gcd_mul_left_cancel_right (m : ℕ+) {n k : ℕ+} : k.Coprime m → m.gcd (k * n) = m.gcd n := by intro h; iterate 2 rw [gcd_comm]; symm apply Coprime.gcd_mul_left_cancel _ h theorem Coprime.gcd_mul_right_cancel_right (m : ℕ+) {n k : ℕ+} : k.Coprime m → m.gcd (n * k) = m.gcd n := by rw [mul_comm] apply Coprime.gcd_mul_left_cancel_right @[simp] theorem one_gcd {n : ℕ+} : gcd 1 n = 1 := by rw [← gcd_eq_left_iff_dvd] apply one_dvd @[simp] theorem gcd_one {n : ℕ+} : gcd n 1 = 1 := by rw [gcd_comm] apply one_gcd @[symm] theorem Coprime.symm {m n : ℕ+} : m.Coprime n → n.Coprime m := by unfold Coprime rw [gcd_comm] simp @[simp] theorem one_coprime {n : ℕ+} : (1 : ℕ+).Coprime n := one_gcd @[simp] theorem coprime_one {n : ℕ+} : n.Coprime 1 := Coprime.symm one_coprime theorem Coprime.coprime_dvd_left {m k n : ℕ+} : m ∣ k → k.Coprime n → m.Coprime n := by rw [dvd_iff] repeat rw [← coprime_coe] apply Nat.Coprime.coprime_dvd_left theorem Coprime.factor_eq_gcd_left {a b m n : ℕ+} (cop : m.Coprime n) (am : a ∣ m) (bn : b ∣ n) : a = (a * b).gcd m := by rw [gcd_eq_left_iff_dvd] at am conv_lhs => rw [← am] rw [eq_comm] apply Coprime.gcd_mul_right_cancel a apply Coprime.coprime_dvd_left bn cop.symm theorem Coprime.factor_eq_gcd_right {a b m n : ℕ+} (cop : m.Coprime n) (am : a ∣ m) (bn : b ∣ n) : a = (b * a).gcd m := by rw [mul_comm]; apply Coprime.factor_eq_gcd_left cop am bn theorem Coprime.factor_eq_gcd_left_right {a b m n : ℕ+} (cop : m.Coprime n) (am : a ∣ m) (bn : b ∣ n) : a = m.gcd (a * b) := by rw [gcd_comm]; apply Coprime.factor_eq_gcd_left cop am bn theorem Coprime.factor_eq_gcd_right_right {a b m n : ℕ+} (cop : m.Coprime n) (am : a ∣ m) (bn : b ∣ n) : a = m.gcd (b * a) := by rw [gcd_comm] apply Coprime.factor_eq_gcd_right cop am bn theorem Coprime.gcd_mul (k : ℕ+) {m n : ℕ+} (h : m.Coprime n) : k.gcd (m * n) = k.gcd m * k.gcd n := by rw [← coprime_coe] at h; apply eq simp only [gcd_coe, mul_coe]; apply Nat.Coprime.gcd_mul k h theorem gcd_eq_left {m n : ℕ+} : m ∣ n → m.gcd n = m := by rw [dvd_iff] intro h apply eq simp only [gcd_coe] apply Nat.gcd_eq_left h theorem Coprime.pow {m n : ℕ+} (k l : ℕ) (h : m.Coprime n) : (m ^ k : ℕ).Coprime (n ^ l) := by rw [← coprime_coe] at *; apply Nat.Coprime.pow; apply h end Coprime end PNat
Data\PNat\Xgcd.lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Neil Strickland -/ import Mathlib.Tactic.Ring import Mathlib.Data.PNat.Prime /-! # Euclidean algorithm for ℕ This file sets up a version of the Euclidean algorithm that only works with natural numbers. Given `0 < a, b`, it computes the unique `(w, x, y, z, d)` such that the following identities hold: * `a = (w + x) d` * `b = (y + z) d` * `w * z = x * y + 1` `d` is then the gcd of `a` and `b`, and `a' := a / d = w + x` and `b' := b / d = y + z` are coprime. This story is closely related to the structure of SL₂(ℕ) (as a free monoid on two generators) and the theory of continued fractions. ## Main declarations * `XgcdType`: Helper type in defining the gcd. Encapsulates `(wp, x, y, zp, ap, bp)`. where `wp` `zp`, `ap`, `bp` are the variables getting changed through the algorithm. * `IsSpecial`: States `wp * zp = x * y + 1` * `IsReduced`: States `ap = a ∧ bp = b` ## Notes See `Nat.Xgcd` for a very similar algorithm allowing values in `ℤ`. -/ open Nat namespace PNat /-- A term of `XgcdType` is a system of six naturals. They should be thought of as representing the matrix [[w, x], [y, z]] = [[wp + 1, x], [y, zp + 1]] together with the vector [a, b] = [ap + 1, bp + 1]. -/ structure XgcdType where /-- `wp` is a variable which changes through the algorithm. -/ wp : ℕ /-- `x` satisfies `a / d = w + x` at the final step. -/ x : ℕ /-- `y` satisfies `b / d = z + y` at the final step. -/ y : ℕ /-- `zp` is a variable which changes through the algorithm. -/ zp : ℕ /-- `ap` is a variable which changes through the algorithm. -/ ap : ℕ /-- `bp` is a variable which changes through the algorithm. -/ bp : ℕ deriving Inhabited namespace XgcdType variable (u : XgcdType) instance : SizeOf XgcdType := ⟨fun u => u.bp⟩ /-- The `Repr` instance converts terms to strings in a way that reflects the matrix/vector interpretation as above. -/ instance : Repr XgcdType where reprPrec | g, _ => s!"[[[{repr (g.wp + 1)}, {repr g.x}], \ [{repr g.y}, {repr (g.zp + 1)}]], \ [{repr (g.ap + 1)}, {repr (g.bp + 1)}]]" /-- Another `mk` using ℕ and ℕ+ -/ def mk' (w : ℕ+) (x : ℕ) (y : ℕ) (z : ℕ+) (a : ℕ+) (b : ℕ+) : XgcdType := mk w.val.pred x y z.val.pred a.val.pred b.val.pred /-- `w = wp + 1` -/ def w : ℕ+ := succPNat u.wp /-- `z = zp + 1` -/ def z : ℕ+ := succPNat u.zp /-- `a = ap + 1` -/ def a : ℕ+ := succPNat u.ap /-- `b = bp + 1` -/ def b : ℕ+ := succPNat u.bp /-- `r = a % b`: remainder -/ def r : ℕ := (u.ap + 1) % (u.bp + 1) /-- `q = ap / bp`: quotient -/ def q : ℕ := (u.ap + 1) / (u.bp + 1) /-- `qp = q - 1` -/ def qp : ℕ := u.q - 1 /-- The map `v` gives the product of the matrix [[w, x], [y, z]] = [[wp + 1, x], [y, zp + 1]] and the vector [a, b] = [ap + 1, bp + 1]. The map `vp` gives [sp, tp] such that v = [sp + 1, tp + 1]. -/ def vp : ℕ × ℕ := ⟨u.wp + u.x + u.ap + u.wp * u.ap + u.x * u.bp, u.y + u.zp + u.bp + u.y * u.ap + u.zp * u.bp⟩ /-- `v = [sp + 1, tp + 1]`, check `vp` -/ def v : ℕ × ℕ := ⟨u.w * u.a + u.x * u.b, u.y * u.a + u.z * u.b⟩ /-- `succ₂ [t.1, t.2] = [t.1.succ, t.2.succ]` -/ def succ₂ (t : ℕ × ℕ) : ℕ × ℕ := ⟨t.1.succ, t.2.succ⟩ theorem v_eq_succ_vp : u.v = succ₂ u.vp := by ext <;> dsimp [v, vp, w, z, a, b, succ₂] <;> ring_nf /-- `IsSpecial` holds if the matrix has determinant one. -/ def IsSpecial : Prop := u.wp + u.zp + u.wp * u.zp = u.x * u.y /-- `IsSpecial'` is an alternative of `IsSpecial`. -/ def IsSpecial' : Prop := u.w * u.z = succPNat (u.x * u.y) theorem isSpecial_iff : u.IsSpecial ↔ u.IsSpecial' := by dsimp [IsSpecial, IsSpecial'] let ⟨wp, x, y, zp, ap, bp⟩ := u constructor <;> intro h <;> simp [w, z, succPNat] at * <;> simp only [← coe_inj, mul_coe, mk_coe] at * · simp_all [← h]; ring · simp [Nat.mul_add, Nat.add_mul, ← Nat.add_assoc] at h; rw [← h]; ring -- Porting note: Old code has been removed as it was much more longer. /-- `IsReduced` holds if the two entries in the vector are the same. The reduction algorithm will produce a system with this property, whose product vector is the same as for the original system. -/ def IsReduced : Prop := u.ap = u.bp /-- `IsReduced'` is an alternative of `IsReduced`. -/ def IsReduced' : Prop := u.a = u.b theorem isReduced_iff : u.IsReduced ↔ u.IsReduced' := succPNat_inj.symm /-- `flip` flips the placement of variables during the algorithm. -/ def flip : XgcdType where wp := u.zp x := u.y y := u.x zp := u.wp ap := u.bp bp := u.ap @[simp] theorem flip_w : (flip u).w = u.z := rfl @[simp] theorem flip_x : (flip u).x = u.y := rfl @[simp] theorem flip_y : (flip u).y = u.x := rfl @[simp] theorem flip_z : (flip u).z = u.w := rfl @[simp] theorem flip_a : (flip u).a = u.b := rfl @[simp] theorem flip_b : (flip u).b = u.a := rfl theorem flip_isReduced : (flip u).IsReduced ↔ u.IsReduced := by dsimp [IsReduced, flip] constructor <;> intro h <;> exact h.symm theorem flip_isSpecial : (flip u).IsSpecial ↔ u.IsSpecial := by dsimp [IsSpecial, flip] rw [mul_comm u.x, mul_comm u.zp, add_comm u.zp] theorem flip_v : (flip u).v = u.v.swap := by dsimp [v] ext · simp only ring · simp only ring /-- Properties of division with remainder for a / b. -/ theorem rq_eq : u.r + (u.bp + 1) * u.q = u.ap + 1 := Nat.mod_add_div (u.ap + 1) (u.bp + 1) theorem qp_eq (hr : u.r = 0) : u.q = u.qp + 1 := by by_cases hq : u.q = 0 · let h := u.rq_eq rw [hr, hq, mul_zero, add_zero] at h cases h · exact (Nat.succ_pred_eq_of_pos (Nat.pos_of_ne_zero hq)).symm /-- The following function provides the starting point for our algorithm. We will apply an iterative reduction process to it, which will produce a system satisfying IsReduced. The gcd can be read off from this final system. -/ def start (a b : ℕ+) : XgcdType := ⟨0, 0, 0, 0, a - 1, b - 1⟩ theorem start_isSpecial (a b : ℕ+) : (start a b).IsSpecial := by dsimp [start, IsSpecial] theorem start_v (a b : ℕ+) : (start a b).v = ⟨a, b⟩ := by dsimp [start, v, XgcdType.a, XgcdType.b, w, z] rw [one_mul, one_mul, zero_mul, zero_mul] have := a.pos have := b.pos congr <;> omega /-- `finish` happens when the reducing process ends. -/ def finish : XgcdType := XgcdType.mk u.wp ((u.wp + 1) * u.qp + u.x) u.y (u.y * u.qp + u.zp) u.bp u.bp theorem finish_isReduced : u.finish.IsReduced := by dsimp [IsReduced] rfl theorem finish_isSpecial (hs : u.IsSpecial) : u.finish.IsSpecial := by dsimp [IsSpecial, finish] at hs ⊢ rw [add_mul _ _ u.y, add_comm _ (u.x * u.y), ← hs] ring theorem finish_v (hr : u.r = 0) : u.finish.v = u.v := by let ha : u.r + u.b * u.q = u.a := u.rq_eq rw [hr, zero_add] at ha ext · change (u.wp + 1) * u.b + ((u.wp + 1) * u.qp + u.x) * u.b = u.w * u.a + u.x * u.b have : u.wp + 1 = u.w := rfl rw [this, ← ha, u.qp_eq hr] ring · change u.y * u.b + (u.y * u.qp + u.z) * u.b = u.y * u.a + u.z * u.b rw [← ha, u.qp_eq hr] ring /-- This is the main reduction step, which is used when u.r ≠ 0, or equivalently b does not divide a. -/ def step : XgcdType := XgcdType.mk (u.y * u.q + u.zp) u.y ((u.wp + 1) * u.q + u.x) u.wp u.bp (u.r - 1) /-- We will apply the above step recursively. The following result is used to ensure that the process terminates. -/ theorem step_wf (hr : u.r ≠ 0) : SizeOf.sizeOf u.step < SizeOf.sizeOf u := by change u.r - 1 < u.bp have h₀ : u.r - 1 + 1 = u.r := Nat.succ_pred_eq_of_pos (Nat.pos_of_ne_zero hr) have h₁ : u.r < u.bp + 1 := Nat.mod_lt (u.ap + 1) u.bp.succ_pos rw [← h₀] at h₁ exact lt_of_succ_lt_succ h₁ theorem step_isSpecial (hs : u.IsSpecial) : u.step.IsSpecial := by dsimp [IsSpecial, step] at hs ⊢ rw [mul_add, mul_comm u.y u.x, ← hs] ring /-- The reduction step does not change the product vector. -/ theorem step_v (hr : u.r ≠ 0) : u.step.v = u.v.swap := by let ha : u.r + u.b * u.q = u.a := u.rq_eq let hr : u.r - 1 + 1 = u.r := (add_comm _ 1).trans (add_tsub_cancel_of_le (Nat.pos_of_ne_zero hr)) ext · change ((u.y * u.q + u.z) * u.b + u.y * (u.r - 1 + 1) : ℕ) = u.y * u.a + u.z * u.b rw [← ha, hr] ring · change ((u.w * u.q + u.x) * u.b + u.w * (u.r - 1 + 1) : ℕ) = u.w * u.a + u.x * u.b rw [← ha, hr] ring -- Porting note: removed 'have' and added decreasing_by to avoid lint errors /-- We can now define the full reduction function, which applies step as long as possible, and then applies finish. Note that the "have" statement puts a fact in the local context, and the equation compiler uses this fact to help construct the full definition in terms of well-founded recursion. The same fact needs to be introduced in all the inductive proofs of properties given below. -/ def reduce (u : XgcdType) : XgcdType := dite (u.r = 0) (fun _ => u.finish) fun _h => flip (reduce u.step) decreasing_by apply u.step_wf _h theorem reduce_a {u : XgcdType} (h : u.r = 0) : u.reduce = u.finish := by rw [reduce] exact if_pos h theorem reduce_b {u : XgcdType} (h : u.r ≠ 0) : u.reduce = u.step.reduce.flip := by rw [reduce] exact if_neg h theorem reduce_isReduced : ∀ u : XgcdType, u.reduce.IsReduced | u => dite (u.r = 0) (fun h => by rw [reduce_a h] exact u.finish_isReduced) fun h => by have : SizeOf.sizeOf u.step < SizeOf.sizeOf u := u.step_wf h rw [reduce_b h, flip_isReduced] apply reduce_isReduced theorem reduce_isReduced' (u : XgcdType) : u.reduce.IsReduced' := (isReduced_iff _).mp u.reduce_isReduced theorem reduce_isSpecial : ∀ u : XgcdType, u.IsSpecial → u.reduce.IsSpecial | u => dite (u.r = 0) (fun h hs => by rw [reduce_a h] exact u.finish_isSpecial hs) fun h hs => by have : SizeOf.sizeOf u.step < SizeOf.sizeOf u := u.step_wf h rw [reduce_b h] exact (flip_isSpecial _).mpr (reduce_isSpecial _ (u.step_isSpecial hs)) theorem reduce_isSpecial' (u : XgcdType) (hs : u.IsSpecial) : u.reduce.IsSpecial' := (isSpecial_iff _).mp (u.reduce_isSpecial hs) theorem reduce_v : ∀ u : XgcdType, u.reduce.v = u.v | u => dite (u.r = 0) (fun h => by rw [reduce_a h, finish_v u h]) fun h => by have : SizeOf.sizeOf u.step < SizeOf.sizeOf u := u.step_wf h rw [reduce_b h, flip_v, reduce_v (step u), step_v u h, Prod.swap_swap] end XgcdType section gcd variable (a b : ℕ+) /-- Extended Euclidean algorithm -/ def xgcd : XgcdType := (XgcdType.start a b).reduce /-- `gcdD a b = gcd a b` -/ def gcdD : ℕ+ := (xgcd a b).a /-- Final value of `w` -/ def gcdW : ℕ+ := (xgcd a b).w /-- Final value of `x` -/ def gcdX : ℕ := (xgcd a b).x /-- Final value of `y` -/ def gcdY : ℕ := (xgcd a b).y /-- Final value of `z` -/ def gcdZ : ℕ+ := (xgcd a b).z /-- Final value of `a / d` -/ def gcdA' : ℕ+ := succPNat ((xgcd a b).wp + (xgcd a b).x) /-- Final value of `b / d` -/ def gcdB' : ℕ+ := succPNat ((xgcd a b).y + (xgcd a b).zp) theorem gcdA'_coe : (gcdA' a b : ℕ) = gcdW a b + gcdX a b := by dsimp [gcdA', gcdX, gcdW, XgcdType.w] rw [add_right_comm] theorem gcdB'_coe : (gcdB' a b : ℕ) = gcdY a b + gcdZ a b := by dsimp [gcdB', gcdY, gcdZ, XgcdType.z] rw [add_assoc] theorem gcd_props : let d := gcdD a b let w := gcdW a b let x := gcdX a b let y := gcdY a b let z := gcdZ a b let a' := gcdA' a b let b' := gcdB' a b w * z = succPNat (x * y) ∧ a = a' * d ∧ b = b' * d ∧ z * a' = succPNat (x * b') ∧ w * b' = succPNat (y * a') ∧ (z * a : ℕ) = x * b + d ∧ (w * b : ℕ) = y * a + d := by intros d w x y z a' b' let u := XgcdType.start a b let ur := u.reduce have _ : d = ur.a := rfl have hb : d = ur.b := u.reduce_isReduced' have ha' : (a' : ℕ) = w + x := gcdA'_coe a b have hb' : (b' : ℕ) = y + z := gcdB'_coe a b have hdet : w * z = succPNat (x * y) := u.reduce_isSpecial' rfl constructor · exact hdet have hdet' : (w * z : ℕ) = x * y + 1 := by rw [← mul_coe, hdet, succPNat_coe] have _ : u.v = ⟨a, b⟩ := XgcdType.start_v a b let hv : Prod.mk (w * d + x * ur.b : ℕ) (y * d + z * ur.b : ℕ) = ⟨a, b⟩ := u.reduce_v.trans (XgcdType.start_v a b) rw [← hb, ← add_mul, ← add_mul, ← ha', ← hb'] at hv have ha'' : (a : ℕ) = a' * d := (congr_arg Prod.fst hv).symm have hb'' : (b : ℕ) = b' * d := (congr_arg Prod.snd hv).symm constructor · exact eq ha'' constructor · exact eq hb'' have hza' : (z * a' : ℕ) = x * b' + 1 := by rw [ha', hb', mul_add, mul_add, mul_comm (z : ℕ), hdet'] ring have hwb' : (w * b' : ℕ) = y * a' + 1 := by rw [ha', hb', mul_add, mul_add, hdet'] ring constructor · apply eq rw [succPNat_coe, Nat.succ_eq_add_one, mul_coe, hza'] constructor · apply eq rw [succPNat_coe, Nat.succ_eq_add_one, mul_coe, hwb'] rw [ha'', hb''] repeat rw [← @mul_assoc] rw [hza', hwb'] constructor <;> ring theorem gcd_eq : gcdD a b = gcd a b := by rcases gcd_props a b with ⟨_, h₁, h₂, _, _, h₅, _⟩ apply dvd_antisymm · apply dvd_gcd · exact Dvd.intro (gcdA' a b) (h₁.trans (mul_comm _ _)).symm · exact Dvd.intro (gcdB' a b) (h₂.trans (mul_comm _ _)).symm · have h₇ : (gcd a b : ℕ) ∣ gcdZ a b * a := (Nat.gcd_dvd_left a b).trans (dvd_mul_left _ _) have h₈ : (gcd a b : ℕ) ∣ gcdX a b * b := (Nat.gcd_dvd_right a b).trans (dvd_mul_left _ _) rw [h₅] at h₇ rw [dvd_iff] exact (Nat.dvd_add_iff_right h₈).mpr h₇ theorem gcd_det_eq : gcdW a b * gcdZ a b = succPNat (gcdX a b * gcdY a b) := (gcd_props a b).1 theorem gcd_a_eq : a = gcdA' a b * gcd a b := gcd_eq a b ▸ (gcd_props a b).2.1 theorem gcd_b_eq : b = gcdB' a b * gcd a b := gcd_eq a b ▸ (gcd_props a b).2.2.1 theorem gcd_rel_left' : gcdZ a b * gcdA' a b = succPNat (gcdX a b * gcdB' a b) := (gcd_props a b).2.2.2.1 theorem gcd_rel_right' : gcdW a b * gcdB' a b = succPNat (gcdY a b * gcdA' a b) := (gcd_props a b).2.2.2.2.1 theorem gcd_rel_left : (gcdZ a b * a : ℕ) = gcdX a b * b + gcd a b := gcd_eq a b ▸ (gcd_props a b).2.2.2.2.2.1 theorem gcd_rel_right : (gcdW a b * b : ℕ) = gcdY a b * a + gcd a b := gcd_eq a b ▸ (gcd_props a b).2.2.2.2.2.2 end gcd end PNat
Data\Prod\Basic.lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import Mathlib.Logic.Function.Defs import Mathlib.Logic.Function.Iterate import Mathlib.Tactic.Inhabit /-! # Extra facts about `Prod` This file defines `Prod.swap : α × β → β × α` and proves various simple lemmas about `Prod`. It also defines better delaborators for product projections. -/ variable {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} @[deprecated (since := "2024-05-08")] alias Prod_map := Prod.map_apply namespace Prod @[simp] theorem mk.eta : ∀ {p : α × β}, (p.1, p.2) = p | (_, _) => rfl @[simp] theorem «forall» {p : α × β → Prop} : (∀ x, p x) ↔ ∀ a b, p (a, b) := ⟨fun h a b ↦ h (a, b), fun h ⟨a, b⟩ ↦ h a b⟩ @[simp] theorem «exists» {p : α × β → Prop} : (∃ x, p x) ↔ ∃ a b, p (a, b) := ⟨fun ⟨⟨a, b⟩, h⟩ ↦ ⟨a, b, h⟩, fun ⟨a, b, h⟩ ↦ ⟨⟨a, b⟩, h⟩⟩ theorem forall' {p : α → β → Prop} : (∀ x : α × β, p x.1 x.2) ↔ ∀ a b, p a b := Prod.forall theorem exists' {p : α → β → Prop} : (∃ x : α × β, p x.1 x.2) ↔ ∃ a b, p a b := Prod.exists @[simp] theorem snd_comp_mk (x : α) : Prod.snd ∘ (Prod.mk x : β → α × β) = id := rfl @[simp] theorem fst_comp_mk (x : α) : Prod.fst ∘ (Prod.mk x : β → α × β) = Function.const β x := rfl @[simp, mfld_simps] theorem map_mk (f : α → γ) (g : β → δ) (a : α) (b : β) : map f g (a, b) = (f a, g b) := rfl -- This was previously a `simp` lemma, but no longer is on the basis that it destructures the pair. -- See `map_apply`, `map_fst`, and `map_snd` for slightly weaker lemmas in the `simp` set. theorem map_apply' (f : α → γ) (g : β → δ) (p : α × β) : map f g p = (f p.1, g p.2) := rfl #adaptation_note /-- After `nightly-2024-06-23`, the explicitness of `map_fst` and `map_snd` will be fixed and we can change this back to `funext <| map_fst f g`. Also in `map_snd'` below. -/ theorem map_fst' (f : α → γ) (g : β → δ) : Prod.fst ∘ map f g = f ∘ Prod.fst := funext <| @map_fst (f := f) (g := g) theorem map_snd' (f : α → γ) (g : β → δ) : Prod.snd ∘ map f g = g ∘ Prod.snd := funext <| @map_snd (f := f) (g := g) /-- Composing a `Prod.map` with another `Prod.map` is equal to a single `Prod.map` of composed functions. -/ theorem map_comp_map {ε ζ : Type*} (f : α → β) (f' : γ → δ) (g : β → ε) (g' : δ → ζ) : Prod.map g g' ∘ Prod.map f f' = Prod.map (g ∘ f) (g' ∘ f') := rfl /-- Composing a `Prod.map` with another `Prod.map` is equal to a single `Prod.map` of composed functions, fully applied. -/ theorem map_map {ε ζ : Type*} (f : α → β) (f' : γ → δ) (g : β → ε) (g' : δ → ζ) (x : α × γ) : Prod.map g g' (Prod.map f f' x) = Prod.map (g ∘ f) (g' ∘ f') x := rfl -- Porting note: `@[simp]` tag removed because auto-generated `mk.injEq` simplifies LHS -- @[simp] theorem mk.inj_iff {a₁ a₂ : α} {b₁ b₂ : β} : (a₁, b₁) = (a₂, b₂) ↔ a₁ = a₂ ∧ b₁ = b₂ := Iff.of_eq (mk.injEq _ _ _ _) theorem mk.inj_left {α β : Type*} (a : α) : Function.Injective (Prod.mk a : β → α × β) := by intro b₁ b₂ h simpa only [true_and, Prod.mk.inj_iff, eq_self_iff_true] using h theorem mk.inj_right {α β : Type*} (b : β) : Function.Injective (fun a ↦ Prod.mk a b : α → α × β) := by intro b₁ b₂ h simpa only [and_true, eq_self_iff_true, mk.inj_iff] using h lemma mk_inj_left {a : α} {b₁ b₂ : β} : (a, b₁) = (a, b₂) ↔ b₁ = b₂ := (mk.inj_left _).eq_iff lemma mk_inj_right {a₁ a₂ : α} {b : β} : (a₁, b) = (a₂, b) ↔ a₁ = a₂ := (mk.inj_right _).eq_iff theorem map_def {f : α → γ} {g : β → δ} : Prod.map f g = fun p : α × β ↦ (f p.1, g p.2) := funext fun p ↦ Prod.ext (map_fst f g p) (map_snd f g p) theorem id_prod : (fun p : α × β ↦ (p.1, p.2)) = id := rfl @[simp] lemma map_id : Prod.map (@id α) (@id β) = id := rfl @[simp] lemma map_id' : Prod.map (fun a : α ↦ a) (fun b : β ↦ b) = fun x ↦ x := rfl @[simp] theorem map_iterate (f : α → α) (g : β → β) (n : ℕ) : (Prod.map f g)^[n] = Prod.map f^[n] g^[n] := by induction n <;> simp [*, Prod.map_comp_map] @[deprecated (since := "2024-07-03")] alias iterate_prod_map := Prod.map_iterate theorem fst_surjective [h : Nonempty β] : Function.Surjective (@fst α β) := fun x ↦ h.elim fun y ↦ ⟨⟨x, y⟩, rfl⟩ theorem snd_surjective [h : Nonempty α] : Function.Surjective (@snd α β) := fun y ↦ h.elim fun x ↦ ⟨⟨x, y⟩, rfl⟩ theorem fst_injective [Subsingleton β] : Function.Injective (@fst α β) := fun _ _ h ↦ Prod.ext h (Subsingleton.elim _ _) theorem snd_injective [Subsingleton α] : Function.Injective (@snd α β) := fun _ _ h ↦ Prod.ext (Subsingleton.elim _ _) h /-- Swap the factors of a product. `swap (a, b) = (b, a)` -/ def swap : α × β → β × α := fun p ↦ (p.2, p.1) @[simp] theorem swap_swap : ∀ x : α × β, swap (swap x) = x | ⟨_, _⟩ => rfl @[simp] theorem fst_swap {p : α × β} : (swap p).1 = p.2 := rfl @[simp] theorem snd_swap {p : α × β} : (swap p).2 = p.1 := rfl @[simp] theorem swap_prod_mk {a : α} {b : β} : swap (a, b) = (b, a) := rfl @[simp] theorem swap_swap_eq : swap ∘ swap = @id (α × β) := funext swap_swap @[simp] theorem swap_leftInverse : Function.LeftInverse (@swap α β) swap := swap_swap @[simp] theorem swap_rightInverse : Function.RightInverse (@swap α β) swap := swap_swap theorem swap_injective : Function.Injective (@swap α β) := swap_leftInverse.injective theorem swap_surjective : Function.Surjective (@swap α β) := swap_leftInverse.surjective theorem swap_bijective : Function.Bijective (@swap α β) := ⟨swap_injective, swap_surjective⟩ @[simp] theorem swap_inj {p q : α × β} : swap p = swap q ↔ p = q := swap_injective.eq_iff /--For two functions `f` and `g`, the composition of `Prod.map f g` with `Prod.swap` is equal to the composition of `Prod.swap` with `Prod.map g f`.-/ theorem map_comp_swap (f : α → β) (g : γ → δ) : Prod.map f g ∘ Prod.swap = Prod.swap ∘ Prod.map g f := rfl theorem eq_iff_fst_eq_snd_eq : ∀ {p q : α × β}, p = q ↔ p.1 = q.1 ∧ p.2 = q.2 | ⟨p₁, p₂⟩, ⟨q₁, q₂⟩ => by simp theorem fst_eq_iff : ∀ {p : α × β} {x : α}, p.1 = x ↔ p = (x, p.2) | ⟨a, b⟩, x => by simp theorem snd_eq_iff : ∀ {p : α × β} {x : β}, p.2 = x ↔ p = (p.1, x) | ⟨a, b⟩, x => by simp variable {r : α → α → Prop} {s : β → β → Prop} {x y : α × β} lemma lex_iff : Prod.Lex r s x y ↔ r x.1 y.1 ∨ x.1 = y.1 ∧ s x.2 y.2 := lex_def _ _ instance Lex.decidable [DecidableEq α] (r : α → α → Prop) (s : β → β → Prop) [DecidableRel r] [DecidableRel s] : DecidableRel (Prod.Lex r s) := fun _ _ ↦ decidable_of_decidable_of_iff (lex_def r s).symm @[refl] theorem Lex.refl_left (r : α → α → Prop) (s : β → β → Prop) [IsRefl α r] : ∀ x, Prod.Lex r s x x | (_, _) => Lex.left _ _ (refl _) instance {r : α → α → Prop} {s : β → β → Prop} [IsRefl α r] : IsRefl (α × β) (Prod.Lex r s) := ⟨Lex.refl_left _ _⟩ @[refl] theorem Lex.refl_right (r : α → α → Prop) (s : β → β → Prop) [IsRefl β s] : ∀ x, Prod.Lex r s x x | (_, _) => Lex.right _ (refl _) instance {r : α → α → Prop} {s : β → β → Prop} [IsRefl β s] : IsRefl (α × β) (Prod.Lex r s) := ⟨Lex.refl_right _ _⟩ instance isIrrefl [IsIrrefl α r] [IsIrrefl β s] : IsIrrefl (α × β) (Prod.Lex r s) := ⟨by rintro ⟨i, a⟩ (⟨_, _, h⟩ | ⟨_, h⟩) <;> exact irrefl _ h⟩ @[trans] theorem Lex.trans {r : α → α → Prop} {s : β → β → Prop} [IsTrans α r] [IsTrans β s] : ∀ {x y z : α × β}, Prod.Lex r s x y → Prod.Lex r s y z → Prod.Lex r s x z | (_, _), (_, _), (_, _), left _ _ hxy₁, left _ _ hyz₁ => left _ _ (_root_.trans hxy₁ hyz₁) | (_, _), (_, _), (_, _), left _ _ hxy₁, right _ _ => left _ _ hxy₁ | (_, _), (_, _), (_, _), right _ _, left _ _ hyz₁ => left _ _ hyz₁ | (_, _), (_, _), (_, _), right _ hxy₂, right _ hyz₂ => right _ (_root_.trans hxy₂ hyz₂) instance {r : α → α → Prop} {s : β → β → Prop} [IsTrans α r] [IsTrans β s] : IsTrans (α × β) (Prod.Lex r s) := ⟨fun _ _ _ ↦ Lex.trans⟩ instance {r : α → α → Prop} {s : β → β → Prop} [IsStrictOrder α r] [IsAntisymm β s] : IsAntisymm (α × β) (Prod.Lex r s) := ⟨fun x₁ x₂ h₁₂ h₂₁ ↦ match x₁, x₂, h₁₂, h₂₁ with | (a, _), (_, _), .left _ _ hr₁, .left _ _ hr₂ => (irrefl a (_root_.trans hr₁ hr₂)).elim | (_, _), (_, _), .left _ _ hr₁, .right _ _ => (irrefl _ hr₁).elim | (_, _), (_, _), .right _ _, .left _ _ hr₂ => (irrefl _ hr₂).elim | (_, _), (_, _), .right _ hs₁, .right _ hs₂ => antisymm hs₁ hs₂ ▸ rfl⟩ instance isTotal_left {r : α → α → Prop} {s : β → β → Prop} [IsTotal α r] : IsTotal (α × β) (Prod.Lex r s) := ⟨fun ⟨a₁, _⟩ ⟨a₂, _⟩ ↦ (IsTotal.total a₁ a₂).imp (Lex.left _ _) (Lex.left _ _)⟩ instance isTotal_right {r : α → α → Prop} {s : β → β → Prop} [IsTrichotomous α r] [IsTotal β s] : IsTotal (α × β) (Prod.Lex r s) := ⟨fun ⟨i, a⟩ ⟨j, b⟩ ↦ by obtain hij | rfl | hji := trichotomous_of r i j · exact Or.inl (.left _ _ hij) · exact (total_of s a b).imp (.right _) (.right _) · exact Or.inr (.left _ _ hji) ⟩ instance IsTrichotomous [IsTrichotomous α r] [IsTrichotomous β s] : IsTrichotomous (α × β) (Prod.Lex r s) := ⟨fun ⟨i, a⟩ ⟨j, b⟩ ↦ by obtain hij | rfl | hji := trichotomous_of r i j { exact Or.inl (Lex.left _ _ hij) } { exact (trichotomous_of (s) a b).imp3 (Lex.right _) (congr_arg _) (Lex.right _) } { exact Or.inr (Or.inr <| Lex.left _ _ hji) }⟩ end Prod open Prod namespace Function variable {f : α → γ} {g : β → δ} {f₁ : α → β} {g₁ : γ → δ} {f₂ : β → α} {g₂ : δ → γ} theorem Injective.prodMap (hf : Injective f) (hg : Injective g) : Injective (map f g) := fun _ _ h ↦ Prod.ext (hf <| congr_arg Prod.fst h) (hg <| congr_arg Prod.snd h) theorem Surjective.prodMap (hf : Surjective f) (hg : Surjective g) : Surjective (map f g) := fun p ↦ let ⟨x, hx⟩ := hf p.1 let ⟨y, hy⟩ := hg p.2 ⟨(x, y), Prod.ext hx hy⟩ theorem Bijective.prodMap (hf : Bijective f) (hg : Bijective g) : Bijective (map f g) := ⟨hf.1.prodMap hg.1, hf.2.prodMap hg.2⟩ theorem LeftInverse.prodMap (hf : LeftInverse f₁ f₂) (hg : LeftInverse g₁ g₂) : LeftInverse (map f₁ g₁) (map f₂ g₂) := fun a ↦ by rw [Prod.map_map, hf.comp_eq_id, hg.comp_eq_id, map_id, id] theorem RightInverse.prodMap : RightInverse f₁ f₂ → RightInverse g₁ g₂ → RightInverse (map f₁ g₁) (map f₂ g₂) := LeftInverse.prodMap theorem Involutive.prodMap {f : α → α} {g : β → β} : Involutive f → Involutive g → Involutive (map f g) := LeftInverse.prodMap @[deprecated (since := "2024-05-08")] alias Injective.Prod_map := Injective.prodMap @[deprecated (since := "2024-05-08")] alias Surjective.Prod_map := Surjective.prodMap @[deprecated (since := "2024-05-08")] alias Bijective.Prod_map := Bijective.prodMap @[deprecated (since := "2024-05-08")] alias LeftInverse.Prod_map := LeftInverse.prodMap @[deprecated (since := "2024-05-08")] alias RightInverse.Prod_map := RightInverse.prodMap @[deprecated (since := "2024-05-08")] alias Involutive.Prod_map := Involutive.prodMap end Function namespace Prod open Function @[simp] theorem map_injective [Nonempty α] [Nonempty β] {f : α → γ} {g : β → δ} : Injective (map f g) ↔ Injective f ∧ Injective g := ⟨fun h => ⟨fun a₁ a₂ ha => by inhabit β injection @h (a₁, default) (a₂, default) (congr_arg (fun c : γ => Prod.mk c (g default)) ha : _), fun b₁ b₂ hb => by inhabit α injection @h (default, b₁) (default, b₂) (congr_arg (Prod.mk (f default)) hb : _)⟩, fun h => h.1.prodMap h.2⟩ @[simp] theorem map_surjective [Nonempty γ] [Nonempty δ] {f : α → γ} {g : β → δ} : Surjective (map f g) ↔ Surjective f ∧ Surjective g := ⟨fun h => ⟨fun c => by inhabit δ obtain ⟨⟨a, b⟩, h⟩ := h (c, default) exact ⟨a, congr_arg Prod.fst h⟩, fun d => by inhabit γ obtain ⟨⟨a, b⟩, h⟩ := h (default, d) exact ⟨b, congr_arg Prod.snd h⟩⟩, fun h => h.1.prodMap h.2⟩ @[simp] theorem map_bijective [Nonempty α] [Nonempty β] {f : α → γ} {g : β → δ} : Bijective (map f g) ↔ Bijective f ∧ Bijective g := by haveI := Nonempty.map f ‹_› haveI := Nonempty.map g ‹_› exact (map_injective.and map_surjective).trans and_and_and_comm @[simp] theorem map_leftInverse [Nonempty β] [Nonempty δ] {f₁ : α → β} {g₁ : γ → δ} {f₂ : β → α} {g₂ : δ → γ} : LeftInverse (map f₁ g₁) (map f₂ g₂) ↔ LeftInverse f₁ f₂ ∧ LeftInverse g₁ g₂ := ⟨fun h => ⟨fun b => by inhabit δ exact congr_arg Prod.fst (h (b, default)), fun d => by inhabit β exact congr_arg Prod.snd (h (default, d))⟩, fun h => h.1.prodMap h.2 ⟩ @[simp] theorem map_rightInverse [Nonempty α] [Nonempty γ] {f₁ : α → β} {g₁ : γ → δ} {f₂ : β → α} {g₂ : δ → γ} : RightInverse (map f₁ g₁) (map f₂ g₂) ↔ RightInverse f₁ f₂ ∧ RightInverse g₁ g₂ := map_leftInverse @[simp] theorem map_involutive [Nonempty α] [Nonempty β] {f : α → α} {g : β → β} : Involutive (map f g) ↔ Involutive f ∧ Involutive g := map_leftInverse section delaborators open Lean PrettyPrinter Delaborator /-- Delaborator for `Prod.fst x` as `x.1`. -/ @[delab app.Prod.fst] def delabProdFst : Delab := withOverApp 3 do let x ← SubExpr.withAppArg delab `($(x).1) /-- Delaborator for `Prod.snd x` as `x.2`. -/ @[delab app.Prod.snd] def delabProdSnd : Delab := withOverApp 3 do let x ← SubExpr.withAppArg delab `($(x).2) end delaborators end Prod
Data\Prod\Lex.lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Minchao Wu -/ import Mathlib.Order.BoundedOrder /-! # Lexicographic order This file defines the lexicographic relation for pairs of orders, partial orders and linear orders. ## Main declarations * `Prod.Lex.<pre/partial/linear>Order`: Instances lifting the orders on `α` and `β` to `α ×ₗ β`. ## Notation * `α ×ₗ β`: `α × β` equipped with the lexicographic order ## See also Related files are: * `Data.Finset.CoLex`: Colexicographic order on finite sets. * `Data.List.Lex`: Lexicographic order on lists. * `Data.Pi.Lex`: Lexicographic order on `Πₗ i, α i`. * `Data.PSigma.Order`: Lexicographic order on `Σ' i, α i`. * `Data.Sigma.Order`: Lexicographic order on `Σ i, α i`. -/ variable {α β γ : Type*} namespace Prod.Lex @[inherit_doc] notation:35 α " ×ₗ " β:34 => Lex (Prod α β) instance decidableEq (α β : Type*) [DecidableEq α] [DecidableEq β] : DecidableEq (α ×ₗ β) := instDecidableEqProd instance inhabited (α β : Type*) [Inhabited α] [Inhabited β] : Inhabited (α ×ₗ β) := instInhabitedProd /-- Dictionary / lexicographic ordering on pairs. -/ instance instLE (α β : Type*) [LT α] [LE β] : LE (α ×ₗ β) where le := Prod.Lex (· < ·) (· ≤ ·) instance instLT (α β : Type*) [LT α] [LT β] : LT (α ×ₗ β) where lt := Prod.Lex (· < ·) (· < ·) theorem le_iff [LT α] [LE β] (a b : α × β) : toLex a ≤ toLex b ↔ a.1 < b.1 ∨ a.1 = b.1 ∧ a.2 ≤ b.2 := Prod.lex_def (· < ·) (· ≤ ·) theorem lt_iff [LT α] [LT β] (a b : α × β) : toLex a < toLex b ↔ a.1 < b.1 ∨ a.1 = b.1 ∧ a.2 < b.2 := Prod.lex_def (· < ·) (· < ·) example (x : α) (y : β) : toLex (x, y) = toLex (x, y) := rfl /-- Dictionary / lexicographic preorder for pairs. -/ instance preorder (α β : Type*) [Preorder α] [Preorder β] : Preorder (α ×ₗ β) := { Prod.Lex.instLE α β, Prod.Lex.instLT α β with le_refl := refl_of <| Prod.Lex _ _, le_trans := fun _ _ _ => trans_of <| Prod.Lex _ _, lt_iff_le_not_le := fun x₁ x₂ => match x₁, x₂ with | (a₁, b₁), (a₂, b₂) => by constructor · rintro (⟨_, _, hlt⟩ | ⟨_, hlt⟩) · constructor · exact left _ _ hlt · rintro ⟨⟩ · apply lt_asymm hlt; assumption · exact lt_irrefl _ hlt · constructor · right rw [lt_iff_le_not_le] at hlt exact hlt.1 · rintro ⟨⟩ · apply lt_irrefl a₁ assumption · rw [lt_iff_le_not_le] at hlt apply hlt.2 assumption · rintro ⟨⟨⟩, h₂r⟩ · left assumption · right rw [lt_iff_le_not_le] constructor · assumption · intro h apply h₂r right exact h } theorem monotone_fst [Preorder α] [LE β] (t c : α ×ₗ β) (h : t ≤ c) : (ofLex t).1 ≤ (ofLex c).1 := by cases (Prod.Lex.le_iff t c).mp h with | inl h' => exact h'.le | inr h' => exact h'.1.le section Preorder variable [PartialOrder α] [Preorder β] theorem toLex_mono : Monotone (toLex : α × β → α ×ₗ β) := by rintro ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ ⟨ha, hb⟩ obtain rfl | ha : a₁ = a₂ ∨ _ := ha.eq_or_lt · exact right _ hb · exact left _ _ ha theorem toLex_strictMono : StrictMono (toLex : α × β → α ×ₗ β) := by rintro ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ h obtain rfl | ha : a₁ = a₂ ∨ _ := h.le.1.eq_or_lt · exact right _ (Prod.mk_lt_mk_iff_right.1 h) · exact left _ _ ha end Preorder /-- Dictionary / lexicographic partial order for pairs. -/ instance partialOrder (α β : Type*) [PartialOrder α] [PartialOrder β] : PartialOrder (α ×ₗ β) := { Prod.Lex.preorder α β with le_antisymm := by haveI : IsStrictOrder α (· < ·) := { irrefl := lt_irrefl, trans := fun _ _ _ => lt_trans } haveI : IsAntisymm β (· ≤ ·) := ⟨fun _ _ => le_antisymm⟩ exact @antisymm _ (Prod.Lex _ _) _ } /-- Dictionary / lexicographic linear order for pairs. -/ instance linearOrder (α β : Type*) [LinearOrder α] [LinearOrder β] : LinearOrder (α ×ₗ β) := { Prod.Lex.partialOrder α β with le_total := total_of (Prod.Lex _ _), decidableLE := Prod.Lex.decidable _ _, decidableLT := Prod.Lex.decidable _ _, decidableEq := Lex.decidableEq _ _, } instance [Ord α] [Ord β] : Ord (α ×ₗ β) where compare := compareLex (compareOn (·.1)) (compareOn (·.2)) instance orderBot [PartialOrder α] [Preorder β] [OrderBot α] [OrderBot β] : OrderBot (α ×ₗ β) where bot := toLex ⊥ bot_le _ := toLex_mono bot_le instance orderTop [PartialOrder α] [Preorder β] [OrderTop α] [OrderTop β] : OrderTop (α ×ₗ β) where top := toLex ⊤ le_top _ := toLex_mono le_top instance boundedOrder [PartialOrder α] [Preorder β] [BoundedOrder α] [BoundedOrder β] : BoundedOrder (α ×ₗ β) := { Lex.orderBot, Lex.orderTop with } instance [Preorder α] [Preorder β] [DenselyOrdered α] [DenselyOrdered β] : DenselyOrdered (α ×ₗ β) where dense := by rintro _ _ (@⟨a₁, b₁, a₂, b₂, h⟩ | @⟨a, b₁, b₂, h⟩) · obtain ⟨c, h₁, h₂⟩ := exists_between h exact ⟨(c, b₁), left _ _ h₁, left _ _ h₂⟩ · obtain ⟨c, h₁, h₂⟩ := exists_between h exact ⟨(a, c), right _ h₁, right _ h₂⟩ instance noMaxOrder_of_left [Preorder α] [Preorder β] [NoMaxOrder α] : NoMaxOrder (α ×ₗ β) where exists_gt := by rintro ⟨a, b⟩ obtain ⟨c, h⟩ := exists_gt a exact ⟨⟨c, b⟩, left _ _ h⟩ instance noMinOrder_of_left [Preorder α] [Preorder β] [NoMinOrder α] : NoMinOrder (α ×ₗ β) where exists_lt := by rintro ⟨a, b⟩ obtain ⟨c, h⟩ := exists_lt a exact ⟨⟨c, b⟩, left _ _ h⟩ instance noMaxOrder_of_right [Preorder α] [Preorder β] [NoMaxOrder β] : NoMaxOrder (α ×ₗ β) where exists_gt := by rintro ⟨a, b⟩ obtain ⟨c, h⟩ := exists_gt b exact ⟨⟨a, c⟩, right _ h⟩ instance noMinOrder_of_right [Preorder α] [Preorder β] [NoMinOrder β] : NoMinOrder (α ×ₗ β) where exists_lt := by rintro ⟨a, b⟩ obtain ⟨c, h⟩ := exists_lt b exact ⟨⟨a, c⟩, right _ h⟩ end Prod.Lex
Data\Prod\PProd.lean
/- Copyright (c) 2020 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import Mathlib.Logic.Function.Defs /-! # Extra facts about `PProd` -/ open Function variable {α β γ δ : Sort*} namespace PProd @[simp] theorem mk.eta {p : PProd α β} : PProd.mk p.1 p.2 = p := rfl @[simp] theorem «forall» {p : PProd α β → Prop} : (∀ x, p x) ↔ ∀ a b, p ⟨a, b⟩ := ⟨fun h a b ↦ h ⟨a, b⟩, fun h ⟨a, b⟩ ↦ h a b⟩ @[simp] theorem «exists» {p : PProd α β → Prop} : (∃ x, p x) ↔ ∃ a b, p ⟨a, b⟩ := ⟨fun ⟨⟨a, b⟩, h⟩ ↦ ⟨a, b, h⟩, fun ⟨a, b, h⟩ ↦ ⟨⟨a, b⟩, h⟩⟩ theorem forall' {p : α → β → Prop} : (∀ x : PProd α β, p x.1 x.2) ↔ ∀ a b, p a b := PProd.forall theorem exists' {p : α → β → Prop} : (∃ x : PProd α β, p x.1 x.2) ↔ ∃ a b, p a b := PProd.exists end PProd theorem Function.Injective.pprod_map {f : α → β} {g : γ → δ} (hf : Injective f) (hg : Injective g) : Injective (fun x ↦ ⟨f x.1, g x.2⟩ : PProd α γ → PProd β δ) := fun _ _ h ↦ have A := congr_arg PProd.fst h have B := congr_arg PProd.snd h congr_arg₂ PProd.mk (hf A) (hg B)
Data\Prod\TProd.lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import Mathlib.Data.List.Nodup /-! # Finite products of types This file defines the product of types over a list. For `l : List ι` and `α : ι → Type v` we define `List.TProd α l = l.foldr (fun i β ↦ α i × β) PUnit`. This type should not be used if `∀ i, α i` or `∀ i ∈ l, α i` can be used instead (in the last expression, we could also replace the list `l` by a set or a finset). This type is used as an intermediary between binary products and finitary products. The application of this type is finitary product measures, but it could be used in any construction/theorem that is easier to define/prove on binary products than on finitary products. * Once we have the construction on binary products (like binary product measures in `MeasureTheory.prod`), we can easily define a finitary version on the type `TProd l α` by iterating. Properties can also be easily extended from the binary case to the finitary case by iterating. * Then we can use the equivalence `List.TProd.piEquivTProd` below (or enhanced versions of it, like a `MeasurableEquiv` for product measures) to get the construction on `∀ i : ι, α i`, at least when assuming `[Fintype ι] [Encodable ι]` (using `Encodable.sortedUniv`). Using `attribute [local instance] Fintype.toEncodable` we can get rid of the argument `[Encodable ι]`. ## Main definitions * We have the equivalence `TProd.piEquivTProd : (∀ i, α i) ≃ TProd α l` if `l` contains every element of `ι` exactly once. * The product of sets is `Set.tprod : (∀ i, Set (α i)) → Set (TProd α l)`. -/ open List Function universe u v variable {ι : Type u} {α : ι → Type v} {i j : ι} {l : List ι} {f : ∀ i, α i} namespace List variable (α) /-- The product of a family of types over a list. -/ abbrev TProd (l : List ι) : Type v := l.foldr (fun i β => α i × β) PUnit variable {α} namespace TProd open List /-- Turning a function `f : ∀ i, α i` into an element of the iterated product `TProd α l`. -/ protected def mk : ∀ (l : List ι) (_f : ∀ i, α i), TProd α l | [] => fun _ => PUnit.unit | i :: is => fun f => (f i, TProd.mk is f) instance [∀ i, Inhabited (α i)] : Inhabited (TProd α l) := ⟨TProd.mk l default⟩ @[simp] theorem fst_mk (i : ι) (l : List ι) (f : ∀ i, α i) : (TProd.mk (i :: l) f).1 = f i := rfl @[simp] theorem snd_mk (i : ι) (l : List ι) (f : ∀ i, α i) : (TProd.mk.{u,v} (i :: l) f).2 = TProd.mk.{u,v} l f := rfl variable [DecidableEq ι] /-- Given an element of the iterated product `l.Prod α`, take a projection into direction `i`. If `i` appears multiple times in `l`, this chooses the first component in direction `i`. -/ protected def elim : ∀ {l : List ι} (_ : TProd α l) {i : ι} (_ : i ∈ l), α i | i :: is, v, j, hj => if hji : j = i then by subst hji exact v.1 else TProd.elim v.2 ((List.mem_cons.mp hj).resolve_left hji) @[simp] theorem elim_self (v : TProd α (i :: l)) : v.elim (l.mem_cons_self i) = v.1 := by simp [TProd.elim] @[simp] theorem elim_of_ne (hj : j ∈ i :: l) (hji : j ≠ i) (v : TProd α (i :: l)) : v.elim hj = TProd.elim v.2 ((List.mem_cons.mp hj).resolve_left hji) := by simp [TProd.elim, hji] @[simp] theorem elim_of_mem (hl : (i :: l).Nodup) (hj : j ∈ l) (v : TProd α (i :: l)) : v.elim (mem_cons_of_mem _ hj) = TProd.elim v.2 hj := by apply elim_of_ne rintro rfl exact hl.not_mem hj theorem elim_mk : ∀ (l : List ι) (f : ∀ i, α i) {i : ι} (hi : i ∈ l), (TProd.mk l f).elim hi = f i | i :: is, f, j, hj => by by_cases hji : j = i · subst hji simp · rw [TProd.elim_of_ne _ hji, snd_mk, elim_mk is] @[ext] theorem ext : ∀ {l : List ι} (_ : l.Nodup) {v w : TProd α l} (_ : ∀ (i) (hi : i ∈ l), v.elim hi = w.elim hi), v = w | [], _, v, w, _ => PUnit.ext v w | i :: is, hl, v, w, hvw => by apply Prod.ext · rw [← elim_self v, hvw, elim_self] refine ext (nodup_cons.mp hl).2 fun j hj => ?_ rw [← elim_of_mem hl, hvw, elim_of_mem hl] /-- A version of `TProd.elim` when `l` contains all elements. In this case we get a function into `Π i, α i`. -/ @[simp] protected def elim' (h : ∀ i, i ∈ l) (v : TProd α l) (i : ι) : α i := v.elim (h i) theorem mk_elim (hnd : l.Nodup) (h : ∀ i, i ∈ l) (v : TProd α l) : TProd.mk l (v.elim' h) = v := TProd.ext hnd fun i hi => by simp [elim_mk] /-- Pi-types are equivalent to iterated products. -/ def piEquivTProd (hnd : l.Nodup) (h : ∀ i, i ∈ l) : (∀ i, α i) ≃ TProd α l := ⟨TProd.mk l, TProd.elim' h, fun f => funext fun i => elim_mk l f (h i), mk_elim hnd h⟩ end TProd end List namespace Set open List /-- A product of sets in `TProd α l`. -/ @[simp] protected def tprod : ∀ (l : List ι) (_t : ∀ i, Set (α i)), Set (TProd α l) | [], _ => univ | i :: is, t => t i ×ˢ Set.tprod is t theorem mk_preimage_tprod : ∀ (l : List ι) (t : ∀ i, Set (α i)), TProd.mk l ⁻¹' Set.tprod l t = { i | i ∈ l }.pi t | [], t => by simp [Set.tprod] | i :: l, t => by ext f have h : TProd.mk l f ∈ Set.tprod l t ↔ ∀ i : ι, i ∈ l → f i ∈ t i := by change f ∈ TProd.mk l ⁻¹' Set.tprod l t ↔ f ∈ { x | x ∈ l }.pi t rw [mk_preimage_tprod l t] -- `simp [Set.TProd, TProd.mk, this]` can close this goal but is slow. rw [Set.tprod, TProd.mk, mem_preimage, mem_pi, prod_mk_mem_set_prod_eq] simp_rw [mem_setOf_eq, mem_cons] rw [forall_eq_or_imp, and_congr_right_iff] exact fun _ => h theorem elim_preimage_pi [DecidableEq ι] {l : List ι} (hnd : l.Nodup) (h : ∀ i, i ∈ l) (t : ∀ i, Set (α i)) : TProd.elim' h ⁻¹' pi univ t = Set.tprod l t := by have h2 : { i | i ∈ l } = univ := by ext i simp [h] rw [← h2, ← mk_preimage_tprod, preimage_preimage] simp only [TProd.mk_elim hnd h] dsimp end Set
Data\PSigma\Order.lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Minchao Wu -/ import Mathlib.Data.Sigma.Lex import Mathlib.Order.BoundedOrder import Mathlib.Mathport.Notation import Init.NotationExtra import Mathlib.Data.Sigma.Basic /-! # Lexicographic order on a sigma type This file defines the lexicographic order on `Σₗ' i, α i`. `a` is less than `b` if its summand is strictly less than the summand of `b` or they are in the same summand and `a` is less than `b` there. ## Notation * `Σₗ' i, α i`: Sigma type equipped with the lexicographic order. A type synonym of `Σ' i, α i`. ## See also Related files are: * `Data.Finset.Colex`: Colexicographic order on finite sets. * `Data.List.Lex`: Lexicographic order on lists. * `Data.Pi.Lex`: Lexicographic order on `Πₗ i, α i`. * `Data.Sigma.Order`: Lexicographic order on `Σₗ i, α i`. Basically a twin of this file. * `Data.Prod.Lex`: Lexicographic order on `α × β`. ## TODO Define the disjoint order on `Σ' i, α i`, where `x ≤ y` only if `x.fst = y.fst`. Prove that a sigma type is a `NoMaxOrder`, `NoMinOrder`, `DenselyOrdered` when its summands are. -/ variable {ι : Type*} {α : ι → Type*} namespace PSigma /-- The notation `Σₗ' i, α i` refers to a sigma type which is locally equipped with the lexicographic order. -/ -- TODO: make `Lex` be `Sort u -> Sort u` so we can remove `.{_+1, _+1}` notation3 "Σₗ' "(...)", "r:(scoped p => _root_.Lex (PSigma.{_+1, _+1} p)) => r namespace Lex /-- The lexicographical `≤` on a sigma type. -/ instance le [LT ι] [∀ i, LE (α i)] : LE (Σₗ' i, α i) := ⟨Lex (· < ·) fun _ => (· ≤ ·)⟩ /-- The lexicographical `<` on a sigma type. -/ instance lt [LT ι] [∀ i, LT (α i)] : LT (Σₗ' i, α i) := ⟨Lex (· < ·) fun _ => (· < ·)⟩ instance preorder [Preorder ι] [∀ i, Preorder (α i)] : Preorder (Σₗ' i, α i) := { Lex.le, Lex.lt with le_refl := fun ⟨i, a⟩ => Lex.right _ le_rfl, le_trans := by rintro ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ ⟨a₃, b₃⟩ ⟨h₁r⟩ ⟨h₂r⟩ · left apply lt_trans repeat' assumption · left assumption · left assumption · right apply le_trans repeat' assumption, lt_iff_le_not_le := by refine fun a b => ⟨fun hab => ⟨hab.mono_right fun i a b => le_of_lt, ?_⟩, ?_⟩ · rintro (⟨i, a, hji⟩ | ⟨i, hba⟩) <;> obtain ⟨_, _, hij⟩ | ⟨_, hab⟩ := hab · exact hij.not_lt hji · exact lt_irrefl _ hji · exact lt_irrefl _ hij · exact hab.not_le hba · rintro ⟨⟨j, b, hij⟩ | ⟨i, hab⟩, hba⟩ · exact Lex.left _ _ hij · exact Lex.right _ (hab.lt_of_not_le fun h => hba <| Lex.right _ h) } /-- Dictionary / lexicographic partial_order for dependent pairs. -/ instance partialOrder [PartialOrder ι] [∀ i, PartialOrder (α i)] : PartialOrder (Σₗ' i, α i) := { Lex.preorder with le_antisymm := by rintro ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ (⟨_, _, hlt₁⟩ | ⟨_, hlt₁⟩) (⟨_, _, hlt₂⟩ | ⟨_, hlt₂⟩) · exact (lt_irrefl a₁ <| hlt₁.trans hlt₂).elim · exact (lt_irrefl a₁ hlt₁).elim · exact (lt_irrefl a₁ hlt₂).elim · rw [hlt₁.antisymm hlt₂] } /-- Dictionary / lexicographic linear_order for pairs. -/ instance linearOrder [LinearOrder ι] [∀ i, LinearOrder (α i)] : LinearOrder (Σₗ' i, α i) := { Lex.partialOrder with le_total := by rintro ⟨i, a⟩ ⟨j, b⟩ obtain hij | rfl | hji := lt_trichotomy i j · exact Or.inl (Lex.left _ _ hij) · obtain hab | hba := le_total a b · exact Or.inl (Lex.right _ hab) · exact Or.inr (Lex.right _ hba) · exact Or.inr (Lex.left _ _ hji), decidableEq := PSigma.decidableEq, decidableLE := Lex.decidable _ _, decidableLT := Lex.decidable _ _ } /-- The lexicographical linear order on a sigma type. -/ instance orderBot [PartialOrder ι] [OrderBot ι] [∀ i, Preorder (α i)] [OrderBot (α ⊥)] : OrderBot (Σₗ' i, α i) where bot := ⟨⊥, ⊥⟩ bot_le := fun ⟨a, b⟩ => by obtain rfl | ha := eq_bot_or_bot_lt a · exact Lex.right _ bot_le · exact Lex.left _ _ ha /-- The lexicographical linear order on a sigma type. -/ instance orderTop [PartialOrder ι] [OrderTop ι] [∀ i, Preorder (α i)] [OrderTop (α ⊤)] : OrderTop (Σₗ' i, α i) where top := ⟨⊤, ⊤⟩ le_top := fun ⟨a, b⟩ => by obtain rfl | ha := eq_top_or_lt_top a · exact Lex.right _ le_top · exact Lex.left _ _ ha /-- The lexicographical linear order on a sigma type. -/ instance boundedOrder [PartialOrder ι] [BoundedOrder ι] [∀ i, Preorder (α i)] [OrderBot (α ⊥)] [OrderTop (α ⊤)] : BoundedOrder (Σₗ' i, α i) := { Lex.orderBot, Lex.orderTop with } instance denselyOrdered [Preorder ι] [DenselyOrdered ι] [∀ i, Nonempty (α i)] [∀ i, Preorder (α i)] [∀ i, DenselyOrdered (α i)] : DenselyOrdered (Σₗ' i, α i) := ⟨by rintro ⟨i, a⟩ ⟨j, b⟩ (⟨_, _, h⟩ | @⟨_, _, b, h⟩) · obtain ⟨k, hi, hj⟩ := exists_between h obtain ⟨c⟩ : Nonempty (α k) := inferInstance exact ⟨⟨k, c⟩, left _ _ hi, left _ _ hj⟩ · obtain ⟨c, ha, hb⟩ := exists_between h exact ⟨⟨i, c⟩, right _ ha, right _ hb⟩⟩ instance denselyOrdered_of_noMaxOrder [Preorder ι] [∀ i, Preorder (α i)] [∀ i, DenselyOrdered (α i)] [∀ i, NoMaxOrder (α i)] : DenselyOrdered (Σₗ' i, α i) := ⟨by rintro ⟨i, a⟩ ⟨j, b⟩ (⟨_, _, h⟩ | @⟨_, _, b, h⟩) · obtain ⟨c, ha⟩ := exists_gt a exact ⟨⟨i, c⟩, right _ ha, left _ _ h⟩ · obtain ⟨c, ha, hb⟩ := exists_between h exact ⟨⟨i, c⟩, right _ ha, right _ hb⟩⟩ instance denselyOrdered_of_noMinOrder [Preorder ι] [∀ i, Preorder (α i)] [∀ i, DenselyOrdered (α i)] [∀ i, NoMinOrder (α i)] : DenselyOrdered (Σₗ' i, α i) := ⟨by rintro ⟨i, a⟩ ⟨j, b⟩ (⟨_, _, h⟩ | @⟨_, _, b, h⟩) · obtain ⟨c, hb⟩ := exists_lt b exact ⟨⟨j, c⟩, left _ _ h, right _ hb⟩ · obtain ⟨c, ha, hb⟩ := exists_between h exact ⟨⟨i, c⟩, right _ ha, right _ hb⟩⟩ instance noMaxOrder_of_nonempty [Preorder ι] [∀ i, Preorder (α i)] [NoMaxOrder ι] [∀ i, Nonempty (α i)] : NoMaxOrder (Σₗ' i, α i) := ⟨by rintro ⟨i, a⟩ obtain ⟨j, h⟩ := exists_gt i obtain ⟨b⟩ : Nonempty (α j) := inferInstance exact ⟨⟨j, b⟩, left _ _ h⟩⟩ instance noMinOrder_of_nonempty [Preorder ι] [∀ i, Preorder (α i)] [NoMinOrder ι] [∀ i, Nonempty (α i)] : NoMinOrder (Σₗ' i, α i) := ⟨by rintro ⟨i, a⟩ obtain ⟨j, h⟩ := exists_lt i obtain ⟨b⟩ : Nonempty (α j) := inferInstance exact ⟨⟨j, b⟩, left _ _ h⟩⟩ instance noMaxOrder [Preorder ι] [∀ i, Preorder (α i)] [∀ i, NoMaxOrder (α i)] : NoMaxOrder (Σₗ' i, α i) := ⟨by rintro ⟨i, a⟩ obtain ⟨b, h⟩ := exists_gt a exact ⟨⟨i, b⟩, right _ h⟩⟩ instance noMinOrder [Preorder ι] [∀ i, Preorder (α i)] [∀ i, NoMinOrder (α i)] : NoMinOrder (Σₗ' i, α i) := ⟨by rintro ⟨i, a⟩ obtain ⟨b, h⟩ := exists_lt a exact ⟨⟨i, b⟩, right _ h⟩⟩ end Lex end PSigma
Data\QPF\Multivariate\Basic.lean
/- Copyright (c) 2018 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Simon Hudon -/ import Mathlib.Data.PFunctor.Multivariate.Basic /-! # Multivariate quotients of polynomial functors. Basic definition of multivariate QPF. QPFs form a compositional framework for defining inductive and coinductive types, their quotients and nesting. The idea is based on building ever larger functors. For instance, we can define a list using a shape functor: ```lean inductive ListShape (a b : Type) | nil : ListShape | cons : a -> b -> ListShape ``` This shape can itself be decomposed as a sum of product which are themselves QPFs. It follows that the shape is a QPF and we can take its fixed point and create the list itself: ```lean def List (a : Type) := fix ListShape a -- not the actual notation ``` We can continue and define the quotient on permutation of lists and create the multiset type: ```lean def Multiset (a : Type) := QPF.quot List.perm List a -- not the actual notion ``` And `Multiset` is also a QPF. We can then create a novel data type (for Lean): ```lean inductive Tree (a : Type) | node : a -> Multiset Tree -> Tree ``` An unordered tree. This is currently not supported by Lean because it nests an inductive type inside of a quotient. We can go further and define unordered, possibly infinite trees: ```lean coinductive Tree' (a : Type) | node : a -> Multiset Tree' -> Tree' ``` by using the `cofix` construct. Those options can all be mixed and matched because they preserve the properties of QPF. The latter example, `Tree'`, combines fixed point, co-fixed point and quotients. ## Related modules * constructions * Fix * Cofix * Quot * Comp * Sigma / Pi * Prj * Const each proves that some operations on functors preserves the QPF structure -/ set_option linter.longLine false in /-! ## Reference [Jeremy Avigad, Mario M. Carneiro and Simon Hudon, *Data Types as Quotients of Polynomial Functors*][avigad-carneiro-hudon2019] -/ universe u open MvFunctor /-- Multivariate quotients of polynomial functors. -/ class MvQPF {n : ℕ} (F : TypeVec.{u} n → Type*) extends MvFunctor F where P : MvPFunctor.{u} n abs : ∀ {α}, P α → F α repr : ∀ {α}, F α → P α abs_repr : ∀ {α} (x : F α), abs (repr x) = x abs_map : ∀ {α β} (f : α ⟹ β) (p : P α), abs (f <$$> p) = f <$$> abs p namespace MvQPF variable {n : ℕ} {F : TypeVec.{u} n → Type*} [q : MvQPF F] open MvFunctor (LiftP LiftR) /-! ### Show that every MvQPF is a lawful MvFunctor. -/ protected theorem id_map {α : TypeVec n} (x : F α) : TypeVec.id <$$> x = x := by rw [← abs_repr x, ← abs_map] rfl @[simp] theorem comp_map {α β γ : TypeVec n} (f : α ⟹ β) (g : β ⟹ γ) (x : F α) : (g ⊚ f) <$$> x = g <$$> f <$$> x := by rw [← abs_repr x, ← abs_map, ← abs_map, ← abs_map] rfl instance (priority := 100) lawfulMvFunctor : LawfulMvFunctor F where id_map := @MvQPF.id_map n F _ comp_map := @comp_map n F _ -- Lifting predicates and relations theorem liftP_iff {α : TypeVec n} (p : ∀ ⦃i⦄, α i → Prop) (x : F α) : LiftP p x ↔ ∃ a f, x = abs ⟨a, f⟩ ∧ ∀ i j, p (f i j) := by constructor · rintro ⟨y, hy⟩ cases' h : repr y with a f use a, fun i j => (f i j).val constructor · rw [← hy, ← abs_repr y, h, ← abs_map]; rfl intro i j apply (f i j).property rintro ⟨a, f, h₀, h₁⟩ use abs ⟨a, fun i j => ⟨f i j, h₁ i j⟩⟩ rw [← abs_map, h₀]; rfl theorem liftR_iff {α : TypeVec n} (r : ∀ /- ⦃i⦄ -/ {i}, α i → α i → Prop) (x y : F α) : LiftR r x y ↔ ∃ a f₀ f₁, x = abs ⟨a, f₀⟩ ∧ y = abs ⟨a, f₁⟩ ∧ ∀ i j, r (f₀ i j) (f₁ i j) := by constructor · rintro ⟨u, xeq, yeq⟩ cases' h : repr u with a f use a, fun i j => (f i j).val.fst, fun i j => (f i j).val.snd constructor · rw [← xeq, ← abs_repr u, h, ← abs_map]; rfl constructor · rw [← yeq, ← abs_repr u, h, ← abs_map]; rfl intro i j exact (f i j).property rintro ⟨a, f₀, f₁, xeq, yeq, h⟩ use abs ⟨a, fun i j => ⟨(f₀ i j, f₁ i j), h i j⟩⟩ dsimp; constructor · rw [xeq, ← abs_map]; rfl rw [yeq, ← abs_map]; rfl open Set open MvFunctor (LiftP LiftR) theorem mem_supp {α : TypeVec n} (x : F α) (i) (u : α i) : u ∈ supp x i ↔ ∀ a f, abs ⟨a, f⟩ = x → u ∈ f i '' univ := by rw [supp]; dsimp; constructor · intro h a f haf have : LiftP (fun i u => u ∈ f i '' univ) x := by rw [liftP_iff] refine ⟨a, f, haf.symm, ?_⟩ intro i u exact mem_image_of_mem _ (mem_univ _) exact h this intro h p; rw [liftP_iff] rintro ⟨a, f, xeq, h'⟩ rcases h a f xeq.symm with ⟨i, _, hi⟩ rw [← hi]; apply h' theorem supp_eq {α : TypeVec n} {i} (x : F α) : supp x i = { u | ∀ a f, abs ⟨a, f⟩ = x → u ∈ f i '' univ } := by ext; apply mem_supp theorem has_good_supp_iff {α : TypeVec n} (x : F α) : (∀ p, LiftP p x ↔ ∀ (i), ∀ u ∈ supp x i, p i u) ↔ ∃ a f, abs ⟨a, f⟩ = x ∧ ∀ i a' f', abs ⟨a', f'⟩ = x → f i '' univ ⊆ f' i '' univ := by constructor · intro h have : LiftP (supp x) x := by rw [h]; introv; exact id rw [liftP_iff] at this rcases this with ⟨a, f, xeq, h'⟩ refine ⟨a, f, xeq.symm, ?_⟩ intro a' f' h'' rintro hu u ⟨j, _h₂, hfi⟩ have hh : u ∈ supp x a' := by rw [← hfi]; apply h' exact (mem_supp x _ u).mp hh _ _ hu rintro ⟨a, f, xeq, h⟩ p; rw [liftP_iff]; constructor · rintro ⟨a', f', xeq', h'⟩ i u usuppx rcases (mem_supp x _ u).mp (@usuppx) a' f' xeq'.symm with ⟨i, _, f'ieq⟩ rw [← f'ieq] apply h' intro h' refine ⟨a, f, xeq.symm, ?_⟩; intro j y apply h'; rw [mem_supp] intro a' f' xeq' apply h _ a' f' xeq' apply mem_image_of_mem _ (mem_univ _) /-- A qpf is said to be uniform if every polynomial functor representing a single value all have the same range. -/ def IsUniform : Prop := ∀ ⦃α : TypeVec n⦄ (a a' : q.P.A) (f : q.P.B a ⟹ α) (f' : q.P.B a' ⟹ α), abs ⟨a, f⟩ = abs ⟨a', f'⟩ → ∀ i, f i '' univ = f' i '' univ /-- does `abs` preserve `liftp`? -/ def LiftPPreservation : Prop := ∀ ⦃α : TypeVec n⦄ (p : ∀ ⦃i⦄, α i → Prop) (x : q.P α), LiftP p (abs x) ↔ LiftP p x /-- does `abs` preserve `supp`? -/ def SuppPreservation : Prop := ∀ ⦃α⦄ (x : q.P α), supp (abs x) = supp x theorem supp_eq_of_isUniform (h : q.IsUniform) {α : TypeVec n} (a : q.P.A) (f : q.P.B a ⟹ α) : ∀ i, supp (abs ⟨a, f⟩) i = f i '' univ := by intro; ext u; rw [mem_supp]; constructor · intro h' apply h' _ _ rfl intro h' a' f' e rw [← h _ _ _ _ e.symm]; apply h' theorem liftP_iff_of_isUniform (h : q.IsUniform) {α : TypeVec n} (x : F α) (p : ∀ i, α i → Prop) : LiftP p x ↔ ∀ (i), ∀ u ∈ supp x i, p i u := by rw [liftP_iff, ← abs_repr x] cases' repr x with a f; constructor · rintro ⟨a', f', abseq, hf⟩ u rw [supp_eq_of_isUniform h, h _ _ _ _ abseq] rintro b ⟨i, _, hi⟩ rw [← hi] apply hf intro h' refine ⟨a, f, rfl, fun _ i => h' _ _ ?_⟩ rw [supp_eq_of_isUniform h] exact ⟨i, mem_univ i, rfl⟩ theorem supp_map (h : q.IsUniform) {α β : TypeVec n} (g : α ⟹ β) (x : F α) (i) : supp (g <$$> x) i = g i '' supp x i := by rw [← abs_repr x]; cases' repr x with a f; rw [← abs_map, MvPFunctor.map_eq] rw [supp_eq_of_isUniform h, supp_eq_of_isUniform h, ← image_comp] rfl theorem suppPreservation_iff_isUniform : q.SuppPreservation ↔ q.IsUniform := by constructor · intro h α a a' f f' h' i rw [← MvPFunctor.supp_eq, ← MvPFunctor.supp_eq, ← h, h', h] · rintro h α ⟨a, f⟩ ext rwa [supp_eq_of_isUniform, MvPFunctor.supp_eq] theorem suppPreservation_iff_liftpPreservation : q.SuppPreservation ↔ q.LiftPPreservation := by constructor <;> intro h · rintro α p ⟨a, f⟩ have h' := h rw [suppPreservation_iff_isUniform] at h' dsimp only [SuppPreservation, supp] at h simp only [liftP_iff_of_isUniform, supp_eq_of_isUniform, MvPFunctor.liftP_iff', h', image_univ, mem_range, exists_imp] constructor <;> intros <;> subst_vars <;> solve_by_elim · rintro α ⟨a, f⟩ simp only [LiftPPreservation] at h ext simp only [supp, h, mem_setOf_eq] theorem liftpPreservation_iff_uniform : q.LiftPPreservation ↔ q.IsUniform := by rw [← suppPreservation_iff_liftpPreservation, suppPreservation_iff_isUniform] /-- Any type function `F` that is (extensionally) equivalent to a QPF, is itself a QPF, assuming that the functorial map of `F` behaves similar to `MvFunctor.ofEquiv eqv` -/ def ofEquiv {F F' : TypeVec.{u} n → Type*} [q : MvQPF F'] [MvFunctor F] (eqv : ∀ α, F α ≃ F' α) (map_eq : ∀ (α β : TypeVec n) (f : α ⟹ β) (a : F α), f <$$> a = ((eqv _).symm <| f <$$> eqv _ a) := by intros; rfl) : MvQPF F where P := q.P abs α := (eqv _).symm <| q.abs α repr α := q.repr <| eqv _ α abs_repr := by simp [q.abs_repr] abs_map := by simp [q.abs_map, map_eq] end MvQPF /-- Every polynomial functor is a (trivial) QPF -/ instance MvPFunctor.instMvQPFObj {n} (P : MvPFunctor n) : MvQPF P where P := P abs := id repr := id abs_repr := by intros; rfl abs_map := by intros; rfl
Data\QPF\Multivariate\Constructions\Cofix.lean
/- Copyright (c) 2018 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Simon Hudon -/ import Mathlib.Control.Functor.Multivariate import Mathlib.Data.PFunctor.Multivariate.Basic import Mathlib.Data.PFunctor.Multivariate.M import Mathlib.Data.QPF.Multivariate.Basic /-! # The final co-algebra of a multivariate qpf is again a qpf. For a `(n+1)`-ary QPF `F (α₀,..,αₙ)`, we take the least fixed point of `F` with regards to its last argument `αₙ`. The result is an `n`-ary functor: `Fix F (α₀,..,αₙ₋₁)`. Making `Fix F` into a functor allows us to take the fixed point, compose with other functors and take a fixed point again. ## Main definitions * `Cofix.mk` - constructor * `Cofix.dest` - destructor * `Cofix.corec` - corecursor: useful for formulating infinite, productive computations * `Cofix.bisim` - bisimulation: proof technique to show the equality of possibly infinite values of `Cofix F α` ## Implementation notes For `F` a QPF, we define `Cofix F α` in terms of the M-type of the polynomial functor `P` of `F`. We define the relation `Mcongr` and take its quotient as the definition of `Cofix F α`. `Mcongr` is taken as the weakest bisimulation on M-type. See [avigad-carneiro-hudon2019] for more details. ## Reference * Jeremy Avigad, Mario M. Carneiro and Simon Hudon. [*Data Types as Quotients of Polynomial Functors*][avigad-carneiro-hudon2019] -/ universe u open MvFunctor namespace MvQPF open TypeVec MvPFunctor open MvFunctor (LiftP LiftR) variable {n : ℕ} {F : TypeVec.{u} (n + 1) → Type u} [q : MvQPF F] /-- `corecF` is used as a basis for defining the corecursor of `Cofix F α`. `corecF` uses corecursion to construct the M-type generated by `q.P` and uses function on `F` as a corecursive step -/ def corecF {α : TypeVec n} {β : Type u} (g : β → F (α.append1 β)) : β → q.P.M α := M.corec _ fun x => repr (g x) theorem corecF_eq {α : TypeVec n} {β : Type u} (g : β → F (α.append1 β)) (x : β) : M.dest q.P (corecF g x) = appendFun id (corecF g) <$$> repr (g x) := by rw [corecF, M.dest_corec] /-- Characterization of desirable equivalence relations on M-types -/ def IsPrecongr {α : TypeVec n} (r : q.P.M α → q.P.M α → Prop) : Prop := ∀ ⦃x y⦄, r x y → abs (appendFun id (Quot.mk r) <$$> M.dest q.P x) = abs (appendFun id (Quot.mk r) <$$> M.dest q.P y) /-- Equivalence relation on M-types representing a value of type `Cofix F` -/ def Mcongr {α : TypeVec n} (x y : q.P.M α) : Prop := ∃ r, IsPrecongr r ∧ r x y /-- Greatest fixed point of functor F. The result is a functor with one fewer parameters than the input. For `F a b c` a ternary functor, fix F is a binary functor such that ```lean Cofix F a b = F a b (Cofix F a b) ``` -/ def Cofix (F : TypeVec (n + 1) → Type u) [MvQPF F] (α : TypeVec n) := Quot (@Mcongr _ F _ α) instance {α : TypeVec n} [Inhabited q.P.A] [∀ i : Fin2 n, Inhabited (α i)] : Inhabited (Cofix F α) := ⟨Quot.mk _ default⟩ /-- maps every element of the W type to a canonical representative -/ def mRepr {α : TypeVec n} : q.P.M α → q.P.M α := corecF (abs ∘ M.dest q.P) /-- the map function for the functor `Cofix F` -/ def Cofix.map {α β : TypeVec n} (g : α ⟹ β) : Cofix F α → Cofix F β := Quot.lift (fun x : q.P.M α => Quot.mk Mcongr (g <$$> x)) (by rintro aa₁ aa₂ ⟨r, pr, ra₁a₂⟩; apply Quot.sound let r' b₁ b₂ := ∃ a₁ a₂ : q.P.M α, r a₁ a₂ ∧ b₁ = g <$$> a₁ ∧ b₂ = g <$$> a₂ use r'; constructor · show IsPrecongr r' rintro b₁ b₂ ⟨a₁, a₂, ra₁a₂, b₁eq, b₂eq⟩ let u : Quot r → Quot r' := Quot.lift (fun x : q.P.M α => Quot.mk r' (g <$$> x)) (by intro a₁ a₂ ra₁a₂ apply Quot.sound exact ⟨a₁, a₂, ra₁a₂, rfl, rfl⟩) have hu : (Quot.mk r' ∘ fun x : q.P.M α => g <$$> x) = u ∘ Quot.mk r := by ext x rfl rw [b₁eq, b₂eq, M.dest_map, M.dest_map, ← q.P.comp_map, ← q.P.comp_map] rw [← appendFun_comp, id_comp, hu, ← comp_id g, appendFun_comp] rw [q.P.comp_map, q.P.comp_map, abs_map, pr ra₁a₂, ← abs_map] show r' (g <$$> aa₁) (g <$$> aa₂); exact ⟨aa₁, aa₂, ra₁a₂, rfl, rfl⟩) instance Cofix.mvfunctor : MvFunctor (Cofix F) where map := @Cofix.map _ _ _ /-- Corecursor for `Cofix F` -/ def Cofix.corec {α : TypeVec n} {β : Type u} (g : β → F (α.append1 β)) : β → Cofix F α := fun x => Quot.mk _ (corecF g x) /-- Destructor for `Cofix F` -/ def Cofix.dest {α : TypeVec n} : Cofix F α → F (α.append1 (Cofix F α)) := Quot.lift (fun x => appendFun id (Quot.mk Mcongr) <$$> abs (M.dest q.P x)) (by rintro x y ⟨r, pr, rxy⟩ dsimp have : ∀ x y, r x y → Mcongr x y := by intro x y h exact ⟨r, pr, h⟩ rw [← Quot.factor_mk_eq _ _ this] conv => lhs rw [appendFun_comp_id, comp_map, ← abs_map, pr rxy, abs_map, ← comp_map, ← appendFun_comp_id]) /-- Abstraction function for `cofix F α` -/ def Cofix.abs {α} : q.P.M α → Cofix F α := Quot.mk _ /-- Representation function for `Cofix F α` -/ def Cofix.repr {α} : Cofix F α → q.P.M α := M.corec _ <| q.repr ∘ Cofix.dest /-- Corecursor for `Cofix F` -/ def Cofix.corec'₁ {α : TypeVec n} {β : Type u} (g : ∀ {X}, (β → X) → F (α.append1 X)) (x : β) : Cofix F α := Cofix.corec (fun _ => g id) x /-- More flexible corecursor for `Cofix F`. Allows the return of a fully formed value instead of making a recursive call -/ def Cofix.corec' {α : TypeVec n} {β : Type u} (g : β → F (α.append1 (Cofix F α ⊕ β))) (x : β) : Cofix F α := let f : (α ::: Cofix F α) ⟹ (α ::: (Cofix F α ⊕ β)) := id ::: Sum.inl Cofix.corec (Sum.elim (MvFunctor.map f ∘ Cofix.dest) g) (Sum.inr x : Cofix F α ⊕ β) /-- Corecursor for `Cofix F`. The shape allows recursive calls to look like recursive calls. -/ def Cofix.corec₁ {α : TypeVec n} {β : Type u} (g : ∀ {X}, (Cofix F α → X) → (β → X) → β → F (α ::: X)) (x : β) : Cofix F α := Cofix.corec' (fun x => g Sum.inl Sum.inr x) x theorem Cofix.dest_corec {α : TypeVec n} {β : Type u} (g : β → F (α.append1 β)) (x : β) : Cofix.dest (Cofix.corec g x) = appendFun id (Cofix.corec g) <$$> g x := by conv => lhs rw [Cofix.dest, Cofix.corec] dsimp rw [corecF_eq, abs_map, abs_repr, ← comp_map, ← appendFun_comp]; rfl /-- constructor for `Cofix F` -/ def Cofix.mk {α : TypeVec n} : F (α.append1 <| Cofix F α) → Cofix F α := Cofix.corec fun x => (appendFun id fun i : Cofix F α => Cofix.dest.{u} i) <$$> x /-! ## Bisimulation principles for `Cofix F` The following theorems are bisimulation principles. The general idea is to use a bisimulation relation to prove the equality between specific values of type `Cofix F α`. A bisimulation relation `R` for values `x y : Cofix F α`: * holds for `x y`: `R x y` * for any values `x y` that satisfy `R`, their root has the same shape and their children can be paired in such a way that they satisfy `R`. -/ private theorem Cofix.bisim_aux {α : TypeVec n} (r : Cofix F α → Cofix F α → Prop) (h' : ∀ x, r x x) (h : ∀ x y, r x y → appendFun id (Quot.mk r) <$$> Cofix.dest x = appendFun id (Quot.mk r) <$$> Cofix.dest y) : ∀ x y, r x y → x = y := by intro x rcases x; clear x; rename M (P F) α => x intro y rcases y; clear y; rename M (P F) α => y intro rxy apply Quot.sound let r' := fun x y => r (Quot.mk _ x) (Quot.mk _ y) have hr' : r' = fun x y => r (Quot.mk _ x) (Quot.mk _ y) := rfl have : IsPrecongr r' := by intro a b r'ab have h₀ : appendFun id (Quot.mk r ∘ Quot.mk Mcongr) <$$> MvQPF.abs (M.dest q.P a) = appendFun id (Quot.mk r ∘ Quot.mk Mcongr) <$$> MvQPF.abs (M.dest q.P b) := by rw [appendFun_comp_id, comp_map, comp_map]; exact h _ _ r'ab have h₁ : ∀ u v : q.P.M α, Mcongr u v → Quot.mk r' u = Quot.mk r' v := by intro u v cuv apply Quot.sound dsimp [r', hr'] rw [Quot.sound cuv] apply h' let f : Quot r → Quot r' := Quot.lift (Quot.lift (Quot.mk r') h₁) (by intro c apply Quot.inductionOn (motive := fun c => ∀b, r c b → Quot.lift (Quot.mk r') h₁ c = Quot.lift (Quot.mk r') h₁ b) c clear c intro c d apply Quot.inductionOn (motive := fun d => r (Quot.mk Mcongr c) d → Quot.lift (Quot.mk r') h₁ (Quot.mk Mcongr c) = Quot.lift (Quot.mk r') h₁ d) d clear d intro d rcd; apply Quot.sound; apply rcd) have : f ∘ Quot.mk r ∘ Quot.mk Mcongr = Quot.mk r' := rfl rw [← this, appendFun_comp_id, q.P.comp_map, q.P.comp_map, abs_map, abs_map, abs_map, abs_map, h₀] exact ⟨r', this, rxy⟩ /-- Bisimulation principle using `map` and `Quot.mk` to match and relate children of two trees. -/ theorem Cofix.bisim_rel {α : TypeVec n} (r : Cofix F α → Cofix F α → Prop) (h : ∀ x y, r x y → appendFun id (Quot.mk r) <$$> Cofix.dest x = appendFun id (Quot.mk r) <$$> Cofix.dest y) : ∀ x y, r x y → x = y := by let r' (x y) := x = y ∨ r x y intro x y rxy apply Cofix.bisim_aux r' · intro x left rfl · intro x y r'xy cases r'xy with | inl h => rw [h] | inr r'xy => have : ∀ x y, r x y → r' x y := fun x y h => Or.inr h rw [← Quot.factor_mk_eq _ _ this] dsimp [r'] rw [appendFun_comp_id] rw [@comp_map _ _ q _ _ _ (appendFun id (Quot.mk r)), @comp_map _ _ q _ _ _ (appendFun id (Quot.mk r))] rw [h _ _ r'xy] right; exact rxy /-- Bisimulation principle using `LiftR` to match and relate children of two trees. -/ theorem Cofix.bisim {α : TypeVec n} (r : Cofix F α → Cofix F α → Prop) (h : ∀ x y, r x y → LiftR (RelLast α r (i := _)) (Cofix.dest x) (Cofix.dest y)) : ∀ x y, r x y → x = y := by apply Cofix.bisim_rel intro x y rxy rcases (liftR_iff (fun a b => RelLast α r a b) (dest x) (dest y)).mp (h x y rxy) with ⟨a, f₀, f₁, dxeq, dyeq, h'⟩ rw [dxeq, dyeq, ← abs_map, ← abs_map, MvPFunctor.map_eq, MvPFunctor.map_eq] rw [← split_dropFun_lastFun f₀, ← split_dropFun_lastFun f₁] rw [appendFun_comp_splitFun, appendFun_comp_splitFun] rw [id_comp, id_comp] congr 2 with (i j); cases' i with _ i · apply Quot.sound apply h' _ j · change f₀ _ j = f₁ _ j apply h' _ j open MvFunctor /-- Bisimulation principle using `LiftR'` to match and relate children of two trees. -/ theorem Cofix.bisim₂ {α : TypeVec n} (r : Cofix F α → Cofix F α → Prop) (h : ∀ x y, r x y → LiftR' (RelLast' α r) (Cofix.dest x) (Cofix.dest y)) : ∀ x y, r x y → x = y := Cofix.bisim r <| by intros; rw [← LiftR_RelLast_iff]; apply h; assumption /-- Bisimulation principle the values `⟨a,f⟩` of the polynomial functor representing `Cofix F α` as well as an invariant `Q : β → Prop` and a state `β` generating the left-hand side and right-hand side of the equality through functions `u v : β → Cofix F α` -/ theorem Cofix.bisim' {α : TypeVec n} {β : Type*} (Q : β → Prop) (u v : β → Cofix F α) (h : ∀ x, Q x → ∃ a f' f₀ f₁, Cofix.dest (u x) = q.abs ⟨a, q.P.appendContents f' f₀⟩ ∧ Cofix.dest (v x) = q.abs ⟨a, q.P.appendContents f' f₁⟩ ∧ ∀ i, ∃ x', Q x' ∧ f₀ i = u x' ∧ f₁ i = v x') : ∀ x, Q x → u x = v x := fun x Qx => let R := fun w z : Cofix F α => ∃ x', Q x' ∧ w = u x' ∧ z = v x' Cofix.bisim R (fun x y ⟨x', Qx', xeq, yeq⟩ => by rcases h x' Qx' with ⟨a, f', f₀, f₁, ux'eq, vx'eq, h'⟩ rw [liftR_iff] refine ⟨a, q.P.appendContents f' f₀, q.P.appendContents f' f₁, xeq.symm ▸ ux'eq, yeq.symm ▸ vx'eq, ?_⟩ intro i; cases i · apply h' · intro j apply Eq.refl) _ _ ⟨x, Qx, rfl, rfl⟩ theorem Cofix.mk_dest {α : TypeVec n} (x : Cofix F α) : Cofix.mk (Cofix.dest x) = x := by apply Cofix.bisim_rel (fun x y : Cofix F α => x = Cofix.mk (Cofix.dest y)) _ _ _ rfl dsimp intro x y h rw [h] conv => lhs congr rfl rw [Cofix.mk] rw [Cofix.dest_corec] rw [← comp_map, ← appendFun_comp, id_comp] rw [← comp_map, ← appendFun_comp, id_comp, ← Cofix.mk] congr apply congrArg funext x apply Quot.sound rfl theorem Cofix.dest_mk {α : TypeVec n} (x : F (α.append1 <| Cofix F α)) : Cofix.dest (Cofix.mk x) = x := by have : Cofix.mk ∘ Cofix.dest = @_root_.id (Cofix F α) := funext Cofix.mk_dest rw [Cofix.mk, Cofix.dest_corec, ← comp_map, ← Cofix.mk, ← appendFun_comp, this, id_comp, appendFun_id_id, MvFunctor.id_map] theorem Cofix.ext {α : TypeVec n} (x y : Cofix F α) (h : x.dest = y.dest) : x = y := by rw [← Cofix.mk_dest x, h, Cofix.mk_dest] theorem Cofix.ext_mk {α : TypeVec n} (x y : F (α ::: Cofix F α)) (h : Cofix.mk x = Cofix.mk y) : x = y := by rw [← Cofix.dest_mk x, h, Cofix.dest_mk] /-! `liftR_map`, `liftR_map_last` and `liftR_map_last'` are useful for reasoning about the induction step in bisimulation proofs. -/ section LiftRMap theorem liftR_map {α β : TypeVec n} {F' : TypeVec n → Type u} [MvFunctor F'] [LawfulMvFunctor F'] (R : β ⊗ β ⟹ «repeat» n Prop) (x : F' α) (f g : α ⟹ β) (h : α ⟹ Subtype_ R) (hh : subtypeVal _ ⊚ h = (f ⊗' g) ⊚ prod.diag) : LiftR' R (f <$$> x) (g <$$> x) := by rw [LiftR_def] exists h <$$> x rw [MvFunctor.map_map, comp_assoc, hh, ← comp_assoc, fst_prod_mk, comp_assoc, fst_diag] rw [MvFunctor.map_map, comp_assoc, hh, ← comp_assoc, snd_prod_mk, comp_assoc, snd_diag] dsimp [LiftR']; constructor <;> rfl open Function theorem liftR_map_last [lawful : LawfulMvFunctor F] {α : TypeVec n} {ι ι'} (R : ι' → ι' → Prop) (x : F (α ::: ι)) (f g : ι → ι') (hh : ∀ x : ι, R (f x) (g x)) : LiftR' (RelLast' _ R) ((id ::: f) <$$> x) ((id ::: g) <$$> x) := let h : ι → { x : ι' × ι' // uncurry R x } := fun x => ⟨(f x, g x), hh x⟩ let b : (α ::: ι) ⟹ _ := @diagSub n α ::: h let c : (Subtype_ α.repeatEq ::: { x // uncurry R x }) ⟹ ((fun i : Fin2 n => { x // ofRepeat (α.RelLast' R i.fs x) }) ::: Subtype (uncurry R)) := ofSubtype _ ::: id have hh : subtypeVal _ ⊚ toSubtype _ ⊚ fromAppend1DropLast ⊚ c ⊚ b = ((id ::: f) ⊗' (id ::: g)) ⊚ prod.diag := by dsimp [b] apply eq_of_drop_last_eq · dsimp simp only [prod_map_id, dropFun_prod, dropFun_appendFun, dropFun_diag, TypeVec.id_comp, dropFun_toSubtype] erw [toSubtype_of_subtype_assoc, TypeVec.id_comp] clear liftR_map_last q lawful F x R f g hh h b c ext (i x) : 2 induction i with | fz => rfl | fs _ ih => apply ih simp only [lastFun_from_append1_drop_last, lastFun_toSubtype, lastFun_appendFun, lastFun_subtypeVal, Function.id_comp, lastFun_comp, lastFun_prod] ext1 rfl liftR_map _ _ _ _ (toSubtype _ ⊚ fromAppend1DropLast ⊚ c ⊚ b) hh theorem liftR_map_last' [LawfulMvFunctor F] {α : TypeVec n} {ι} (R : ι → ι → Prop) (x : F (α ::: ι)) (f : ι → ι) (hh : ∀ x : ι, R (f x) x) : LiftR' (RelLast' _ R) ((id ::: f) <$$> x) x := by have := liftR_map_last R x f id hh rwa [appendFun_id_id, MvFunctor.id_map] at this end LiftRMap variable {F : TypeVec (n + 1) → Type u} [q : MvQPF F] theorem Cofix.abs_repr {α} (x : Cofix F α) : Quot.mk _ (Cofix.repr x) = x := by let R := fun x y : Cofix F α => abs (repr y) = x refine Cofix.bisim₂ R ?_ _ _ rfl clear x rintro x y h subst h dsimp [Cofix.dest, Cofix.abs] induction y using Quot.ind simp only [Cofix.repr, M.dest_corec, abs_map, MvQPF.abs_repr, Function.comp] conv => congr; rfl; rw [Cofix.dest] rw [MvFunctor.map_map, MvFunctor.map_map, ← appendFun_comp_id, ← appendFun_comp_id] apply liftR_map_last intros rfl end MvQPF namespace Mathlib.Tactic.MvBisim open Lean Expr Elab Term Tactic Meta Qq /-- tactic for proof by bisimulation -/ syntax "mv_bisim" (ppSpace colGt term) (" with" (ppSpace colGt binderIdent)+)? : tactic elab_rules : tactic | `(tactic| mv_bisim $e $[ with $ids:binderIdent*]?) => do let ids : TSyntaxArray `Lean.binderIdent := ids.getD #[] let idsn (n : ℕ) : Name := match ids[n]? with | some s => match s with | `(binderIdent| $n:ident) => n.getId | `(binderIdent| _) => `_ | _ => unreachable! | none => `_ let idss (n : ℕ) : TacticM (TSyntax `rcasesPat) := do match ids[n]? with | some s => match s with | `(binderIdent| $n:ident) => `(rcasesPat| $n) | `(binderIdent| _%$b) => `(rcasesPat| _%$b) | _ => unreachable! | none => `(rcasesPat| _) withMainContext do let e ← Tactic.elabTerm e none let f ← liftMetaTacticAux fun g => do let (#[fv], g) ← g.generalize #[{ expr := e }] | unreachable! return (mkFVar fv, [g]) withMainContext do let some (t, l, r) ← matchEq? (← getMainTarget) | throwError "goal is not an equality" let ex ← withLocalDecl (idsn 1) .default t fun v₀ => withLocalDecl (idsn 2) .default t fun v₁ => do let x₀ ← mkEq v₀ l let x₁ ← mkEq v₁ r let xx ← mkAppM ``And #[x₀, x₁] let ex₁ ← mkLambdaFVars #[f] xx let ex₂ ← mkAppM ``Exists #[ex₁] mkLambdaFVars #[v₀, v₁] ex₂ let R ← liftMetaTacticAux fun g => do let g₁ ← g.define (idsn 0) (← mkArrow t (← mkArrow t (mkSort .zero))) ex let (Rv, g₂) ← g₁.intro1P return (mkFVar Rv, [g₂]) withMainContext do ids[0]?.forM fun s => addLocalVarInfoForBinderIdent R s let sR ← exprToSyntax R evalTactic <| ← `(tactic| refine MvQPF.Cofix.bisim₂ $sR ?_ _ _ ⟨_, rfl, rfl⟩; rintro $(← idss 1) $(← idss 2) ⟨$(← idss 3), $(← idss 4), $(← idss 5)⟩) liftMetaTactic fun g => return [← g.clear f.fvarId!] for n in [6 : ids.size] do let name := ids[n]! logWarningAt name m!"unused name: {name}" end Mathlib.Tactic.MvBisim namespace MvQPF open TypeVec MvPFunctor open MvFunctor (LiftP LiftR) variable {n : ℕ} {F : TypeVec.{u} (n + 1) → Type u} [q : MvQPF F] theorem corec_roll {α : TypeVec n} {X Y} {x₀ : X} (f : X → Y) (g : Y → F (α ::: X)) : Cofix.corec (g ∘ f) x₀ = Cofix.corec (MvFunctor.map (id ::: f) ∘ g) (f x₀) := by mv_bisim x₀ with R a b x Ha Hb rw [Ha, Hb, Cofix.dest_corec, Cofix.dest_corec, Function.comp_apply, Function.comp_apply] rw [MvFunctor.map_map, ← appendFun_comp_id] refine liftR_map_last _ _ _ _ ?_ intro a; refine ⟨a, rfl, rfl⟩ theorem Cofix.dest_corec' {α : TypeVec.{u} n} {β : Type u} (g : β → F (α.append1 (Cofix F α ⊕ β))) (x : β) : Cofix.dest (Cofix.corec' g x) = appendFun id (Sum.elim _root_.id (Cofix.corec' g)) <$$> g x := by rw [Cofix.corec', Cofix.dest_corec]; dsimp congr!; ext (i | i) <;> erw [corec_roll] <;> dsimp [Cofix.corec'] · mv_bisim i with R a b x Ha Hb rw [Ha, Hb, Cofix.dest_corec] dsimp [Function.comp_def] repeat rw [MvFunctor.map_map, ← appendFun_comp_id] apply liftR_map_last' dsimp [Function.comp_def] intros exact ⟨_, rfl, rfl⟩ · congr with y erw [appendFun_id_id] simp [MvFunctor.id_map, Sum.elim] theorem Cofix.dest_corec₁ {α : TypeVec n} {β : Type u} (g : ∀ {X}, (Cofix F α → X) → (β → X) → β → F (α.append1 X)) (x : β) (h : ∀ (X Y) (f : Cofix F α → X) (f' : β → X) (k : X → Y), g (k ∘ f) (k ∘ f') x = (id ::: k) <$$> g f f' x) : Cofix.dest (Cofix.corec₁ (@g) x) = g id (Cofix.corec₁ @g) x := by rw [Cofix.corec₁, Cofix.dest_corec', ← h]; rfl instance mvqpfCofix : MvQPF (Cofix F) where P := q.P.mp abs := Quot.mk Mcongr repr := Cofix.repr abs_repr := Cofix.abs_repr abs_map := by intros; rfl end MvQPF
Data\QPF\Multivariate\Constructions\Comp.lean
/- Copyright (c) 2018 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Simon Hudon -/ import Mathlib.Data.PFunctor.Multivariate.Basic import Mathlib.Data.QPF.Multivariate.Basic /-! # The composition of QPFs is itself a QPF We define composition between one `n`-ary functor and `n` `m`-ary functors and show that it preserves the QPF structure -/ universe u namespace MvQPF open MvFunctor variable {n m : ℕ} (F : TypeVec.{u} n → Type*) (G : Fin2 n → TypeVec.{u} m → Type u) /-- Composition of an `n`-ary functor with `n` `m`-ary functors gives us one `m`-ary functor -/ def Comp (v : TypeVec.{u} m) : Type _ := F fun i : Fin2 n ↦ G i v namespace Comp open MvFunctor MvPFunctor variable {F G} {α β : TypeVec.{u} m} (f : α ⟹ β) instance [I : Inhabited (F fun i : Fin2 n ↦ G i α)] : Inhabited (Comp F G α) := I /-- Constructor for functor composition -/ protected def mk (x : F fun i ↦ G i α) : Comp F G α := x /-- Destructor for functor composition -/ protected def get (x : Comp F G α) : F fun i ↦ G i α := x @[simp] protected theorem mk_get (x : Comp F G α) : Comp.mk (Comp.get x) = x := rfl @[simp] protected theorem get_mk (x : F fun i ↦ G i α) : Comp.get (Comp.mk x) = x := rfl section variable [MvFunctor F] [∀ i, MvFunctor <| G i] /-- map operation defined on a vector of functors -/ protected def map' : (fun i : Fin2 n ↦ G i α) ⟹ fun i : Fin2 n ↦ G i β := fun _i ↦ map f /-- The composition of functors is itself functorial -/ protected def map : (Comp F G) α → (Comp F G) β := (map fun _i ↦ map f : (F fun i ↦ G i α) → F fun i ↦ G i β) instance : MvFunctor (Comp F G) where map f := Comp.map f theorem map_mk (x : F fun i ↦ G i α) : f <$$> Comp.mk x = Comp.mk ((fun i (x : G i α) ↦ f <$$> x) <$$> x) := rfl theorem get_map (x : Comp F G α) : Comp.get (f <$$> x) = (fun i (x : G i α) ↦ f <$$> x) <$$> Comp.get x := rfl end instance [MvQPF F] [∀ i, MvQPF <| G i] : MvQPF (Comp F G) where P := MvPFunctor.comp (P F) fun i ↦ P <| G i abs := Comp.mk ∘ (map fun i ↦ abs) ∘ abs ∘ MvPFunctor.comp.get repr {α} := MvPFunctor.comp.mk ∘ repr ∘ (map fun i ↦ (repr : G i α → (fun i : Fin2 n ↦ Obj (P (G i)) α) i)) ∘ Comp.get abs_repr := by intros simp (config := { unfoldPartialApp := true }) only [Function.comp_def, comp.get_mk, abs_repr, map_map, TypeVec.comp, MvFunctor.id_map', Comp.mk_get] abs_map := by intros simp only [(· ∘ ·)] rw [← abs_map] simp (config := { unfoldPartialApp := true }) only [comp.get_map, map_map, TypeVec.comp, abs_map, map_mk] end Comp end MvQPF
Data\QPF\Multivariate\Constructions\Const.lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import Mathlib.Control.Functor.Multivariate import Mathlib.Data.QPF.Multivariate.Basic /-! # Constant functors are QPFs Constant functors map every type vectors to the same target type. This is a useful device for constructing data types from more basic types that are not actually functorial. For instance `Const n Nat` makes `Nat` into a functor that can be used in a functor-based data type specification. -/ universe u namespace MvQPF open MvFunctor variable (n : ℕ) /-- Constant multivariate functor -/ @[nolint unusedArguments] def Const (A : Type*) (_v : TypeVec.{u} n) : Type _ := A instance Const.inhabited {A α} [Inhabited A] : Inhabited (Const n A α) := ⟨(default : A)⟩ namespace Const open MvFunctor MvPFunctor variable {n} {A : Type u} {α β : TypeVec.{u} n} (f : α ⟹ β) /-- Constructor for constant functor -/ protected def mk (x : A) : Const n A α := x /-- Destructor for constant functor -/ protected def get (x : Const n A α) : A := x @[simp] protected theorem mk_get (x : Const n A α) : Const.mk (Const.get x) = x := rfl @[simp] protected theorem get_mk (x : A) : Const.get (Const.mk x : Const n A α) = x := rfl /-- `map` for constant functor -/ protected def map : Const n A α → Const n A β := fun x => x instance MvFunctor : MvFunctor (Const n A) where map _f := Const.map theorem map_mk (x : A) : f <$$> Const.mk x = Const.mk x := rfl theorem get_map (x : (Const n A) α) : Const.get (f <$$> x) = Const.get x := rfl instance mvqpf : @MvQPF _ (Const n A) where P := MvPFunctor.const n A abs x := MvPFunctor.const.get x repr x := MvPFunctor.const.mk n x abs_repr := fun _ => const.get_mk _ abs_map := fun _ => const.get_map _ end Const end MvQPF
Data\QPF\Multivariate\Constructions\Fix.lean
/- Copyright (c) 2018 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Simon Hudon -/ import Mathlib.Data.PFunctor.Multivariate.W import Mathlib.Data.QPF.Multivariate.Basic /-! # The initial algebra of a multivariate qpf is again a qpf. For an `(n+1)`-ary QPF `F (α₀,..,αₙ)`, we take the least fixed point of `F` with regards to its last argument `αₙ`. The result is an `n`-ary functor: `Fix F (α₀,..,αₙ₋₁)`. Making `Fix F` into a functor allows us to take the fixed point, compose with other functors and take a fixed point again. ## Main definitions * `Fix.mk` - constructor * `Fix.dest` - destructor * `Fix.rec` - recursor: basis for defining functions by structural recursion on `Fix F α` * `Fix.drec` - dependent recursor: generalization of `Fix.rec` where the result type of the function is allowed to depend on the `Fix F α` value * `Fix.rec_eq` - defining equation for `recursor` * `Fix.ind` - induction principle for `Fix F α` ## Implementation notes For `F` a `QPF`, we define `Fix F α` in terms of the W-type of the polynomial functor `P` of `F`. We define the relation `WEquiv` and take its quotient as the definition of `Fix F α`. See [avigad-carneiro-hudon2019] for more details. ## Reference * Jeremy Avigad, Mario M. Carneiro and Simon Hudon. [*Data Types as Quotients of Polynomial Functors*][avigad-carneiro-hudon2019] -/ universe u v namespace MvQPF open TypeVec open MvFunctor (LiftP LiftR) open MvFunctor variable {n : ℕ} {F : TypeVec.{u} (n + 1) → Type u} [q : MvQPF F] /-- `recF` is used as a basis for defining the recursor on `Fix F α`. `recF` traverses recursively the W-type generated by `q.P` using a function on `F` as a recursive step -/ def recF {α : TypeVec n} {β : Type u} (g : F (α.append1 β) → β) : q.P.W α → β := q.P.wRec fun a f' _f rec => g (abs ⟨a, splitFun f' rec⟩) theorem recF_eq {α : TypeVec n} {β : Type u} (g : F (α.append1 β) → β) (a : q.P.A) (f' : q.P.drop.B a ⟹ α) (f : q.P.last.B a → q.P.W α) : recF g (q.P.wMk a f' f) = g (abs ⟨a, splitFun f' (recF g ∘ f)⟩) := by rw [recF, MvPFunctor.wRec_eq]; rfl theorem recF_eq' {α : TypeVec n} {β : Type u} (g : F (α.append1 β) → β) (x : q.P.W α) : recF g x = g (abs (appendFun id (recF g) <$$> q.P.wDest' x)) := by apply q.P.w_cases _ x intro a f' f rw [recF_eq, q.P.wDest'_wMk, MvPFunctor.map_eq, appendFun_comp_splitFun, TypeVec.id_comp] /-- Equivalence relation on W-types that represent the same `Fix F` value -/ inductive WEquiv {α : TypeVec n} : q.P.W α → q.P.W α → Prop | ind (a : q.P.A) (f' : q.P.drop.B a ⟹ α) (f₀ f₁ : q.P.last.B a → q.P.W α) : (∀ x, WEquiv (f₀ x) (f₁ x)) → WEquiv (q.P.wMk a f' f₀) (q.P.wMk a f' f₁) | abs (a₀ : q.P.A) (f'₀ : q.P.drop.B a₀ ⟹ α) (f₀ : q.P.last.B a₀ → q.P.W α) (a₁ : q.P.A) (f'₁ : q.P.drop.B a₁ ⟹ α) (f₁ : q.P.last.B a₁ → q.P.W α) : abs ⟨a₀, q.P.appendContents f'₀ f₀⟩ = abs ⟨a₁, q.P.appendContents f'₁ f₁⟩ → WEquiv (q.P.wMk a₀ f'₀ f₀) (q.P.wMk a₁ f'₁ f₁) | trans (u v w : q.P.W α) : WEquiv u v → WEquiv v w → WEquiv u w theorem recF_eq_of_wEquiv (α : TypeVec n) {β : Type u} (u : F (α.append1 β) → β) (x y : q.P.W α) : WEquiv x y → recF u x = recF u y := by apply q.P.w_cases _ x intro a₀ f'₀ f₀ apply q.P.w_cases _ y intro a₁ f'₁ f₁ intro h -- Porting note: induction on h doesn't work. refine @WEquiv.recOn _ _ _ _ (fun a a' _ ↦ recF u a = recF u a') _ _ h ?_ ?_ ?_ · intros a f' f₀ f₁ _h ih; simp only [recF_eq, Function.comp] congr; funext; congr; funext; apply ih · intros a₀ f'₀ f₀ a₁ f'₁ f₁ h; simp only [recF_eq', abs_map, MvPFunctor.wDest'_wMk, h] · intros x y z _e₁ _e₂ ih₁ ih₂; exact Eq.trans ih₁ ih₂ theorem wEquiv.abs' {α : TypeVec n} (x y : q.P.W α) (h : MvQPF.abs (q.P.wDest' x) = MvQPF.abs (q.P.wDest' y)) : WEquiv x y := by revert h apply q.P.w_cases _ x intro a₀ f'₀ f₀ apply q.P.w_cases _ y intro a₁ f'₁ f₁ apply WEquiv.abs theorem wEquiv.refl {α : TypeVec n} (x : q.P.W α) : WEquiv x x := by apply q.P.w_cases _ x; intro a f' f; exact WEquiv.abs a f' f a f' f rfl theorem wEquiv.symm {α : TypeVec n} (x y : q.P.W α) : WEquiv x y → WEquiv y x := by intro h; induction h with | ind a f' f₀ f₁ _h ih => exact WEquiv.ind _ _ _ _ ih | abs a₀ f'₀ f₀ a₁ f'₁ f₁ h => exact WEquiv.abs _ _ _ _ _ _ h.symm | trans x y z _e₁ _e₂ ih₁ ih₂ => exact MvQPF.WEquiv.trans _ _ _ ih₂ ih₁ /-- maps every element of the W type to a canonical representative -/ def wrepr {α : TypeVec n} : q.P.W α → q.P.W α := recF (q.P.wMk' ∘ repr) theorem wrepr_wMk {α : TypeVec n} (a : q.P.A) (f' : q.P.drop.B a ⟹ α) (f : q.P.last.B a → q.P.W α) : wrepr (q.P.wMk a f' f) = q.P.wMk' (repr (abs (appendFun id wrepr <$$> ⟨a, q.P.appendContents f' f⟩))) := by rw [wrepr, recF_eq', q.P.wDest'_wMk]; rfl theorem wrepr_equiv {α : TypeVec n} (x : q.P.W α) : WEquiv (wrepr x) x := by apply q.P.w_ind _ x; intro a f' f ih apply WEquiv.trans _ (q.P.wMk' (appendFun id wrepr <$$> ⟨a, q.P.appendContents f' f⟩)) · apply wEquiv.abs' rw [wrepr_wMk, q.P.wDest'_wMk', q.P.wDest'_wMk', abs_repr] rw [q.P.map_eq, MvPFunctor.wMk', appendFun_comp_splitFun, id_comp] apply WEquiv.ind; exact ih theorem wEquiv_map {α β : TypeVec n} (g : α ⟹ β) (x y : q.P.W α) : WEquiv x y → WEquiv (g <$$> x) (g <$$> y) := by intro h; induction h with | ind a f' f₀ f₁ h ih => rw [q.P.w_map_wMk, q.P.w_map_wMk]; apply WEquiv.ind; exact ih | abs a₀ f'₀ f₀ a₁ f'₁ f₁ h => rw [q.P.w_map_wMk, q.P.w_map_wMk]; apply WEquiv.abs show abs (q.P.objAppend1 a₀ (g ⊚ f'₀) fun x => q.P.wMap g (f₀ x)) = abs (q.P.objAppend1 a₁ (g ⊚ f'₁) fun x => q.P.wMap g (f₁ x)) rw [← q.P.map_objAppend1, ← q.P.map_objAppend1, abs_map, abs_map, h] | trans x y z _ _ ih₁ ih₂ => apply MvQPF.WEquiv.trans · apply ih₁ · apply ih₂ /-- Define the fixed point as the quotient of trees under the equivalence relation. -/ def wSetoid (α : TypeVec n) : Setoid (q.P.W α) := ⟨WEquiv, wEquiv.refl, wEquiv.symm _ _, WEquiv.trans _ _ _⟩ attribute [local instance] wSetoid /-- Least fixed point of functor F. The result is a functor with one fewer parameters than the input. For `F a b c` a ternary functor, `Fix F` is a binary functor such that ```lean Fix F a b = F a b (Fix F a b) ``` -/ def Fix {n : ℕ} (F : TypeVec (n + 1) → Type*) [q : MvQPF F] (α : TypeVec n) := Quotient (wSetoid α : Setoid (q.P.W α)) /-- `Fix F` is a functor -/ def Fix.map {α β : TypeVec n} (g : α ⟹ β) : Fix F α → Fix F β := Quotient.lift (fun x : q.P.W α => ⟦q.P.wMap g x⟧) fun _a _b h => Quot.sound (wEquiv_map _ _ _ h) instance Fix.mvfunctor : MvFunctor (Fix F) where map := Fix.map variable {α : TypeVec.{u} n} /-- Recursor for `Fix F` -/ def Fix.rec {β : Type u} (g : F (α ::: β) → β) : Fix F α → β := Quot.lift (recF g) (recF_eq_of_wEquiv α g) /-- Access W-type underlying `Fix F` -/ def fixToW : Fix F α → q.P.W α := Quotient.lift wrepr (recF_eq_of_wEquiv α fun x => q.P.wMk' (repr x)) /-- Constructor for `Fix F` -/ def Fix.mk (x : F (append1 α (Fix F α))) : Fix F α := Quot.mk _ (q.P.wMk' (appendFun id fixToW <$$> repr x)) /-- Destructor for `Fix F` -/ def Fix.dest : Fix F α → F (append1 α (Fix F α)) := Fix.rec (MvFunctor.map (appendFun id Fix.mk)) theorem Fix.rec_eq {β : Type u} (g : F (append1 α β) → β) (x : F (append1 α (Fix F α))) : Fix.rec g (Fix.mk x) = g (appendFun id (Fix.rec g) <$$> x) := by have : recF g ∘ fixToW = Fix.rec g := by apply funext apply Quotient.ind intro x apply recF_eq_of_wEquiv apply wrepr_equiv conv => lhs rw [Fix.rec, Fix.mk] dsimp cases' h : repr x with a f rw [MvPFunctor.map_eq, recF_eq', ← MvPFunctor.map_eq, MvPFunctor.wDest'_wMk'] rw [← MvPFunctor.comp_map, abs_map, ← h, abs_repr, ← appendFun_comp, id_comp, this] theorem Fix.ind_aux (a : q.P.A) (f' : q.P.drop.B a ⟹ α) (f : q.P.last.B a → q.P.W α) : Fix.mk (abs ⟨a, q.P.appendContents f' fun x => ⟦f x⟧⟩) = ⟦q.P.wMk a f' f⟧ := by have : Fix.mk (abs ⟨a, q.P.appendContents f' fun x => ⟦f x⟧⟩) = ⟦wrepr (q.P.wMk a f' f)⟧ := by apply Quot.sound; apply wEquiv.abs' rw [MvPFunctor.wDest'_wMk', abs_map, abs_repr, ← abs_map, MvPFunctor.map_eq] conv => rhs rw [wrepr_wMk, q.P.wDest'_wMk', abs_repr, MvPFunctor.map_eq] congr 2; rw [MvPFunctor.appendContents, MvPFunctor.appendContents] rw [appendFun, appendFun, ← splitFun_comp, ← splitFun_comp] rfl rw [this] apply Quot.sound apply wrepr_equiv theorem Fix.ind_rec {β : Type u} (g₁ g₂ : Fix F α → β) (h : ∀ x : F (append1 α (Fix F α)), appendFun id g₁ <$$> x = appendFun id g₂ <$$> x → g₁ (Fix.mk x) = g₂ (Fix.mk x)) : ∀ x, g₁ x = g₂ x := by apply Quot.ind intro x apply q.P.w_ind _ x intro a f' f ih show g₁ ⟦q.P.wMk a f' f⟧ = g₂ ⟦q.P.wMk a f' f⟧ rw [← Fix.ind_aux a f' f] apply h rw [← abs_map, ← abs_map, MvPFunctor.map_eq, MvPFunctor.map_eq] congr 2 rw [MvPFunctor.appendContents, appendFun, appendFun, ← splitFun_comp, ← splitFun_comp] have : (g₁ ∘ fun x => ⟦f x⟧) = g₂ ∘ fun x => ⟦f x⟧ := by ext x exact ih x rw [this] theorem Fix.rec_unique {β : Type u} (g : F (append1 α β) → β) (h : Fix F α → β) (hyp : ∀ x, h (Fix.mk x) = g (appendFun id h <$$> x)) : Fix.rec g = h := by ext x apply Fix.ind_rec intro x hyp' rw [hyp, ← hyp', Fix.rec_eq] theorem Fix.mk_dest (x : Fix F α) : Fix.mk (Fix.dest x) = x := by change (Fix.mk ∘ Fix.dest) x = x apply Fix.ind_rec intro x; dsimp rw [Fix.dest, Fix.rec_eq, ← comp_map, ← appendFun_comp, id_comp] intro h; rw [h] show Fix.mk (appendFun id id <$$> x) = Fix.mk x rw [appendFun_id_id, MvFunctor.id_map] theorem Fix.dest_mk (x : F (append1 α (Fix F α))) : Fix.dest (Fix.mk x) = x := by unfold Fix.dest rw [Fix.rec_eq, ← Fix.dest, ← comp_map] conv => rhs rw [← MvFunctor.id_map x] rw [← appendFun_comp, id_comp] have : Fix.mk ∘ Fix.dest (F := F) (α := α) = _root_.id := by ext (x : Fix F α) apply Fix.mk_dest rw [this, appendFun_id_id] theorem Fix.ind {α : TypeVec n} (p : Fix F α → Prop) (h : ∀ x : F (α.append1 (Fix F α)), LiftP (PredLast α p) x → p (Fix.mk x)) : ∀ x, p x := by apply Quot.ind intro x apply q.P.w_ind _ x; intro a f' f ih change p ⟦q.P.wMk a f' f⟧ rw [← Fix.ind_aux a f' f] apply h rw [MvQPF.liftP_iff] refine ⟨_, _, rfl, ?_⟩ intro i j cases i · apply ih · trivial instance mvqpfFix : MvQPF (Fix F) where P := q.P.wp abs α := Quot.mk WEquiv α repr α := fixToW α abs_repr := by intro α apply Quot.ind intro a apply Quot.sound apply wrepr_equiv abs_map := by intro α β g x conv => rhs dsimp [MvFunctor.map] rfl /-- Dependent recursor for `fix F` -/ def Fix.drec {β : Fix F α → Type u} (g : ∀ x : F (α ::: Sigma β), β (Fix.mk <| (id ::: Sigma.fst) <$$> x)) (x : Fix F α) : β x := let y := @Fix.rec _ F _ α (Sigma β) (fun i => ⟨_, g i⟩) x have : x = y.1 := by symm dsimp [y] apply Fix.ind_rec _ id _ x intro x' ih rw [Fix.rec_eq] dsimp simp? [appendFun_id_id] at ih says simp only [appendFun_id_id, MvFunctor.id_map] at ih congr conv => rhs rw [← ih] rw [MvFunctor.map_map, ← appendFun_comp, id_comp] simp only [Function.comp] cast (by rw [this]) y.2 end MvQPF
Data\QPF\Multivariate\Constructions\Prj.lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import Mathlib.Control.Functor.Multivariate import Mathlib.Data.QPF.Multivariate.Basic /-! Projection functors are QPFs. The `n`-ary projection functors on `i` is an `n`-ary functor `F` such that `F (α₀..αᵢ₋₁, αᵢ, αᵢ₊₁..αₙ₋₁) = αᵢ` -/ universe u v namespace MvQPF open MvFunctor variable {n : ℕ} (i : Fin2 n) /-- The projection `i` functor -/ def Prj (v : TypeVec.{u} n) : Type u := v i instance Prj.inhabited {v : TypeVec.{u} n} [Inhabited (v i)] : Inhabited (Prj i v) := ⟨(default : v i)⟩ /-- `map` on functor `Prj i` -/ def Prj.map ⦃α β : TypeVec n⦄ (f : α ⟹ β) : Prj i α → Prj i β := f _ instance Prj.mvfunctor : MvFunctor (Prj i) where map := @Prj.map _ i /-- Polynomial representation of the projection functor -/ def Prj.P : MvPFunctor.{u} n where A := PUnit B _ j := ULift <| PLift <| i = j /-- Abstraction function of the `QPF` instance -/ def Prj.abs ⦃α : TypeVec n⦄ : Prj.P i α → Prj i α | ⟨_x, f⟩ => f _ ⟨⟨rfl⟩⟩ /-- Representation function of the `QPF` instance -/ def Prj.repr ⦃α : TypeVec n⦄ : Prj i α → Prj.P i α := fun x : α i => ⟨⟨⟩, fun j ⟨⟨h⟩⟩ => (h.rec x : α j)⟩ instance Prj.mvqpf : MvQPF (Prj i) where P := Prj.P i abs := @Prj.abs _ i repr := @Prj.repr _ i abs_repr := by intros; rfl abs_map := by intros α β f P; cases P; rfl end MvQPF
Data\QPF\Multivariate\Constructions\Quot.lean
/- Copyright (c) 2018 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Simon Hudon -/ import Mathlib.Data.QPF.Multivariate.Basic /-! # The quotient of QPF is itself a QPF The quotients are here defined using a surjective function and its right inverse. They are very similar to the `abs` and `repr` functions found in the definition of `MvQPF` -/ universe u open MvFunctor namespace MvQPF variable {n : ℕ} variable {F : TypeVec.{u} n → Type u} section repr variable [q : MvQPF F] variable {G : TypeVec.{u} n → Type u} [MvFunctor G] variable {FG_abs : ∀ {α}, F α → G α} variable {FG_repr : ∀ {α}, G α → F α} /-- If `F` is a QPF then `G` is a QPF as well. Can be used to construct `MvQPF` instances by transporting them across surjective functions -/ def quotientQPF (FG_abs_repr : ∀ {α} (x : G α), FG_abs (FG_repr x) = x) (FG_abs_map : ∀ {α β} (f : α ⟹ β) (x : F α), FG_abs (f <$$> x) = f <$$> FG_abs x) : MvQPF G where P := q.P abs p := FG_abs (abs p) repr x := repr (FG_repr x) abs_repr x := by dsimp; rw [abs_repr, FG_abs_repr] abs_map f p := by dsimp; rw [abs_map, FG_abs_map] end repr section Rel variable (R : ∀ ⦃α⦄, F α → F α → Prop) /-- Functorial quotient type -/ def Quot1 (α : TypeVec n) := Quot (@R α) instance Quot1.inhabited {α : TypeVec n} [Inhabited <| F α] : Inhabited (Quot1 R α) := ⟨Quot.mk _ default⟩ section variable [MvFunctor F] (Hfunc : ∀ ⦃α β⦄ (a b : F α) (f : α ⟹ β), R a b → R (f <$$> a) (f <$$> b)) /-- `map` of the `Quot1` functor -/ def Quot1.map ⦃α β⦄ (f : α ⟹ β) : Quot1.{u} R α → Quot1.{u} R β := Quot.lift (fun x : F α => Quot.mk _ (f <$$> x : F β)) fun a b h => Quot.sound <| Hfunc a b _ h /-- `mvFunctor` instance for `Quot1` with well-behaved `R` -/ def Quot1.mvFunctor : MvFunctor (Quot1 R) where map := @Quot1.map _ _ R _ Hfunc end section variable [q : MvQPF F] (Hfunc : ∀ ⦃α β⦄ (a b : F α) (f : α ⟹ β), R a b → R (f <$$> a) (f <$$> b)) /-- `Quot1` is a QPF -/ noncomputable def relQuot : @MvQPF _ (Quot1 R) := @quotientQPF n F q _ (MvQPF.Quot1.mvFunctor R Hfunc) (fun x => Quot.mk _ x) Quot.out (fun _x => Quot.out_eq _) fun _f _x => rfl end end Rel end MvQPF
Data\QPF\Multivariate\Constructions\Sigma.lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import Mathlib.Data.PFunctor.Multivariate.Basic import Mathlib.Data.QPF.Multivariate.Basic /-! # Dependent product and sum of QPFs are QPFs -/ universe u namespace MvQPF open MvFunctor variable {n : ℕ} {A : Type u} variable (F : A → TypeVec.{u} n → Type u) /-- Dependent sum of an `n`-ary functor. The sum can range over data types like `ℕ` or over `Type.{u-1}` -/ def Sigma (v : TypeVec.{u} n) : Type u := Σ α : A, F α v /-- Dependent product of an `n`-ary functor. The sum can range over data types like `ℕ` or over `Type.{u-1}` -/ def Pi (v : TypeVec.{u} n) : Type u := ∀ α : A, F α v instance Sigma.inhabited {α} [Inhabited A] [Inhabited (F default α)] : Inhabited (Sigma F α) := ⟨⟨default, default⟩⟩ instance Pi.inhabited {α} [∀ a, Inhabited (F a α)] : Inhabited (Pi F α) := ⟨fun _a => default⟩ namespace Sigma instance [∀ α, MvFunctor <| F α] : MvFunctor (Sigma F) where map := fun f ⟨a, x⟩ => ⟨a, f <$$> x⟩ variable [∀ α, MvQPF <| F α] /-- polynomial functor representation of a dependent sum -/ protected def P : MvPFunctor n := ⟨Σ a, (P (F a)).A, fun x => (P (F x.1)).B x.2⟩ /-- abstraction function for dependent sums -/ protected def abs ⦃α⦄ : Sigma.P F α → Sigma F α | ⟨a, f⟩ => ⟨a.1, MvQPF.abs ⟨a.2, f⟩⟩ /-- representation function for dependent sums -/ protected def repr ⦃α⦄ : Sigma F α → Sigma.P F α | ⟨a, f⟩ => let x := MvQPF.repr f ⟨⟨a, x.1⟩, x.2⟩ instance : MvQPF (Sigma F) where P := Sigma.P F abs {α} := @Sigma.abs _ _ F _ α repr {α} := @Sigma.repr _ _ F _ α abs_repr := by rintro α ⟨x, f⟩; simp only [Sigma.abs, Sigma.repr, Sigma.eta, abs_repr] abs_map := by rintro α β f ⟨x, g⟩; simp only [Sigma.abs, MvPFunctor.map_eq] simp only [(· <$$> ·), ← abs_map, ← MvPFunctor.map_eq] end Sigma namespace Pi instance [∀ α, MvFunctor <| F α] : MvFunctor (Pi F) where map f x a := f <$$> x a variable [∀ α, MvQPF <| F α] /-- polynomial functor representation of a dependent product -/ protected def P : MvPFunctor n := ⟨∀ a, (P (F a)).A, fun x i => Σ a, (P (F a)).B (x a) i⟩ /-- abstraction function for dependent products -/ protected def abs ⦃α⦄ : Pi.P F α → Pi F α | ⟨a, f⟩ => fun x => MvQPF.abs ⟨a x, fun i y => f i ⟨_, y⟩⟩ /-- representation function for dependent products -/ protected def repr ⦃α⦄ : Pi F α → Pi.P F α | f => ⟨fun a => (MvQPF.repr (f a)).1, fun _i a => (MvQPF.repr (f _)).2 _ a.2⟩ instance : MvQPF (Pi F) where P := Pi.P F abs := @Pi.abs _ _ F _ repr := @Pi.repr _ _ F _ abs_repr := by rintro α f; simp only [Pi.abs, Pi.repr, Sigma.eta, abs_repr] abs_map := by rintro α β f ⟨x, g⟩; simp only [Pi.abs, (· <$$> ·), ← abs_map]; rfl end Pi end MvQPF
Data\QPF\Univariate\Basic.lean
/- Copyright (c) 2018 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad -/ import Mathlib.Data.PFunctor.Univariate.M /-! # Quotients of Polynomial Functors We assume the following: * `P`: a polynomial functor * `W`: its W-type * `M`: its M-type * `F`: a functor We define: * `q`: `QPF` data, representing `F` as a quotient of `P` The main goal is to construct: * `Fix`: the initial algebra with structure map `F Fix → Fix`. * `Cofix`: the final coalgebra with structure map `Cofix → F Cofix` We also show that the composition of qpfs is a qpf, and that the quotient of a qpf is a qpf. The present theory focuses on the univariate case for qpfs ## References * [Jeremy Avigad, Mario M. Carneiro and Simon Hudon, *Data Types as Quotients of Polynomial Functors*][avigad-carneiro-hudon2019] -/ universe u /-- Quotients of polynomial functors. Roughly speaking, saying that `F` is a quotient of a polynomial functor means that for each `α`, elements of `F α` are represented by pairs `⟨a, f⟩`, where `a` is the shape of the object and `f` indexes the relevant elements of `α`, in a suitably natural manner. -/ class QPF (F : Type u → Type u) extends Functor F where P : PFunctor.{u} abs : ∀ {α}, P α → F α repr : ∀ {α}, F α → P α abs_repr : ∀ {α} (x : F α), abs (repr x) = x abs_map : ∀ {α β} (f : α → β) (p : P α), abs (P.map f p) = f <$> abs p namespace QPF variable {F : Type u → Type u} [q : QPF F] open Functor (Liftp Liftr) /- Show that every qpf is a lawful functor. Note: every functor has a field, `map_const`, and `lawfulFunctor` has the defining characterization. We can only propagate the assumption. -/ theorem id_map {α : Type _} (x : F α) : id <$> x = x := by rw [← abs_repr x] cases' repr x with a f rw [← abs_map] rfl theorem comp_map {α β γ : Type _} (f : α → β) (g : β → γ) (x : F α) : (g ∘ f) <$> x = g <$> f <$> x := by rw [← abs_repr x] cases' repr x with a f rw [← abs_map, ← abs_map, ← abs_map] rfl theorem lawfulFunctor (h : ∀ α β : Type u, @Functor.mapConst F _ α _ = Functor.map ∘ Function.const β) : LawfulFunctor F := { map_const := @h id_map := @id_map F _ comp_map := @comp_map F _ } /- Lifting predicates and relations -/ section open Functor theorem liftp_iff {α : Type u} (p : α → Prop) (x : F α) : Liftp p x ↔ ∃ a f, x = abs ⟨a, f⟩ ∧ ∀ i, p (f i) := by constructor · rintro ⟨y, hy⟩ cases' h : repr y with a f use a, fun i => (f i).val constructor · rw [← hy, ← abs_repr y, h, ← abs_map] rfl intro i apply (f i).property rintro ⟨a, f, h₀, h₁⟩ use abs ⟨a, fun i => ⟨f i, h₁ i⟩⟩ rw [← abs_map, h₀]; rfl theorem liftp_iff' {α : Type u} (p : α → Prop) (x : F α) : Liftp p x ↔ ∃ u : q.P α, abs u = x ∧ ∀ i, p (u.snd i) := by constructor · rintro ⟨y, hy⟩ cases' h : repr y with a f use ⟨a, fun i => (f i).val⟩ dsimp constructor · rw [← hy, ← abs_repr y, h, ← abs_map] rfl intro i apply (f i).property rintro ⟨⟨a, f⟩, h₀, h₁⟩; dsimp at * use abs ⟨a, fun i => ⟨f i, h₁ i⟩⟩ rw [← abs_map, ← h₀]; rfl theorem liftr_iff {α : Type u} (r : α → α → Prop) (x y : F α) : Liftr r x y ↔ ∃ a f₀ f₁, x = abs ⟨a, f₀⟩ ∧ y = abs ⟨a, f₁⟩ ∧ ∀ i, r (f₀ i) (f₁ i) := by constructor · rintro ⟨u, xeq, yeq⟩ cases' h : repr u with a f use a, fun i => (f i).val.fst, fun i => (f i).val.snd constructor · rw [← xeq, ← abs_repr u, h, ← abs_map] rfl constructor · rw [← yeq, ← abs_repr u, h, ← abs_map] rfl intro i exact (f i).property rintro ⟨a, f₀, f₁, xeq, yeq, h⟩ use abs ⟨a, fun i => ⟨(f₀ i, f₁ i), h i⟩⟩ constructor · rw [xeq, ← abs_map] rfl rw [yeq, ← abs_map]; rfl end /- Think of trees in the `W` type corresponding to `P` as representatives of elements of the least fixed point of `F`, and assign a canonical representative to each equivalence class of trees. -/ /-- does recursion on `q.P.W` using `g : F α → α` rather than `g : P α → α` -/ def recF {α : Type _} (g : F α → α) : q.P.W → α | ⟨a, f⟩ => g (abs ⟨a, fun x => recF g (f x)⟩) theorem recF_eq {α : Type _} (g : F α → α) (x : q.P.W) : recF g x = g (abs (q.P.map (recF g) x.dest)) := by cases x rfl theorem recF_eq' {α : Type _} (g : F α → α) (a : q.P.A) (f : q.P.B a → q.P.W) : recF g ⟨a, f⟩ = g (abs (q.P.map (recF g) ⟨a, f⟩)) := rfl /-- two trees are equivalent if their F-abstractions are -/ inductive Wequiv : q.P.W → q.P.W → Prop | ind (a : q.P.A) (f f' : q.P.B a → q.P.W) : (∀ x, Wequiv (f x) (f' x)) → Wequiv ⟨a, f⟩ ⟨a, f'⟩ | abs (a : q.P.A) (f : q.P.B a → q.P.W) (a' : q.P.A) (f' : q.P.B a' → q.P.W) : abs ⟨a, f⟩ = abs ⟨a', f'⟩ → Wequiv ⟨a, f⟩ ⟨a', f'⟩ | trans (u v w : q.P.W) : Wequiv u v → Wequiv v w → Wequiv u w /-- `recF` is insensitive to the representation -/ theorem recF_eq_of_Wequiv {α : Type u} (u : F α → α) (x y : q.P.W) : Wequiv x y → recF u x = recF u y := by intro h induction h with | ind a f f' _ ih => simp only [recF_eq', PFunctor.map_eq, Function.comp, ih] | abs a f a' f' h => simp only [recF_eq', abs_map, h] | trans x y z _ _ ih₁ ih₂ => exact Eq.trans ih₁ ih₂ theorem Wequiv.abs' (x y : q.P.W) (h : QPF.abs x.dest = QPF.abs y.dest) : Wequiv x y := by cases x cases y apply Wequiv.abs apply h theorem Wequiv.refl (x : q.P.W) : Wequiv x x := by cases' x with a f exact Wequiv.abs a f a f rfl theorem Wequiv.symm (x y : q.P.W) : Wequiv x y → Wequiv y x := by intro h induction h with | ind a f f' _ ih => exact Wequiv.ind _ _ _ ih | abs a f a' f' h => exact Wequiv.abs _ _ _ _ h.symm | trans x y z _ _ ih₁ ih₂ => exact QPF.Wequiv.trans _ _ _ ih₂ ih₁ /-- maps every element of the W type to a canonical representative -/ def Wrepr : q.P.W → q.P.W := recF (PFunctor.W.mk ∘ repr) theorem Wrepr_equiv (x : q.P.W) : Wequiv (Wrepr x) x := by induction' x with a f ih apply Wequiv.trans · change Wequiv (Wrepr ⟨a, f⟩) (PFunctor.W.mk (q.P.map Wrepr ⟨a, f⟩)) apply Wequiv.abs' have : Wrepr ⟨a, f⟩ = PFunctor.W.mk (repr (abs (q.P.map Wrepr ⟨a, f⟩))) := rfl rw [this, PFunctor.W.dest_mk, abs_repr] rfl apply Wequiv.ind; exact ih /-- Define the fixed point as the quotient of trees under the equivalence relation `Wequiv`. -/ def Wsetoid : Setoid q.P.W := ⟨Wequiv, @Wequiv.refl _ _, @Wequiv.symm _ _, @Wequiv.trans _ _⟩ attribute [local instance] Wsetoid /-- inductive type defined as initial algebra of a Quotient of Polynomial Functor -/ -- Porting note(#5171): this linter isn't ported yet. -- @[nolint has_nonempty_instance] def Fix (F : Type u → Type u) [q : QPF F] := Quotient (Wsetoid : Setoid q.P.W) /-- recursor of a type defined by a qpf -/ def Fix.rec {α : Type _} (g : F α → α) : Fix F → α := Quot.lift (recF g) (recF_eq_of_Wequiv g) /-- access the underlying W-type of a fixpoint data type -/ def fixToW : Fix F → q.P.W := Quotient.lift Wrepr (recF_eq_of_Wequiv fun x => @PFunctor.W.mk q.P (repr x)) /-- constructor of a type defined by a qpf -/ def Fix.mk (x : F (Fix F)) : Fix F := Quot.mk _ (PFunctor.W.mk (q.P.map fixToW (repr x))) /-- destructor of a type defined by a qpf -/ def Fix.dest : Fix F → F (Fix F) := Fix.rec (Functor.map Fix.mk) theorem Fix.rec_eq {α : Type _} (g : F α → α) (x : F (Fix F)) : Fix.rec g (Fix.mk x) = g (Fix.rec g <$> x) := by have : recF g ∘ fixToW = Fix.rec g := by ext ⟨x⟩ apply recF_eq_of_Wequiv rw [fixToW] apply Wrepr_equiv conv => lhs rw [Fix.rec, Fix.mk] dsimp cases' h : repr x with a f rw [PFunctor.map_eq, recF_eq, ← PFunctor.map_eq, PFunctor.W.dest_mk, PFunctor.map_map, abs_map, ← h, abs_repr, this] theorem Fix.ind_aux (a : q.P.A) (f : q.P.B a → q.P.W) : Fix.mk (abs ⟨a, fun x => ⟦f x⟧⟩) = ⟦⟨a, f⟩⟧ := by have : Fix.mk (abs ⟨a, fun x => ⟦f x⟧⟩) = ⟦Wrepr ⟨a, f⟩⟧ := by apply Quot.sound; apply Wequiv.abs' rw [PFunctor.W.dest_mk, abs_map, abs_repr, ← abs_map, PFunctor.map_eq] simp only [Wrepr, recF_eq, PFunctor.W.dest_mk, abs_repr, Function.comp] rfl rw [this] apply Quot.sound apply Wrepr_equiv theorem Fix.ind_rec {α : Type u} (g₁ g₂ : Fix F → α) (h : ∀ x : F (Fix F), g₁ <$> x = g₂ <$> x → g₁ (Fix.mk x) = g₂ (Fix.mk x)) : ∀ x, g₁ x = g₂ x := by rintro ⟨x⟩ induction' x with a f ih change g₁ ⟦⟨a, f⟩⟧ = g₂ ⟦⟨a, f⟩⟧ rw [← Fix.ind_aux a f]; apply h rw [← abs_map, ← abs_map, PFunctor.map_eq, PFunctor.map_eq] congr with x apply ih theorem Fix.rec_unique {α : Type u} (g : F α → α) (h : Fix F → α) (hyp : ∀ x, h (Fix.mk x) = g (h <$> x)) : Fix.rec g = h := by ext x apply Fix.ind_rec intro x hyp' rw [hyp, ← hyp', Fix.rec_eq] theorem Fix.mk_dest (x : Fix F) : Fix.mk (Fix.dest x) = x := by change (Fix.mk ∘ Fix.dest) x = id x apply Fix.ind_rec (mk ∘ dest) id intro x rw [Function.comp_apply, id_eq, Fix.dest, Fix.rec_eq, id_map, comp_map] intro h rw [h] theorem Fix.dest_mk (x : F (Fix F)) : Fix.dest (Fix.mk x) = x := by unfold Fix.dest; rw [Fix.rec_eq, ← Fix.dest, ← comp_map] conv => rhs rw [← id_map x] congr with x apply Fix.mk_dest theorem Fix.ind (p : Fix F → Prop) (h : ∀ x : F (Fix F), Liftp p x → p (Fix.mk x)) : ∀ x, p x := by rintro ⟨x⟩ induction' x with a f ih change p ⟦⟨a, f⟩⟧ rw [← Fix.ind_aux a f] apply h rw [liftp_iff] refine ⟨_, _, rfl, ?_⟩ convert ih end QPF /- Construct the final coalgebra to a qpf. -/ namespace QPF variable {F : Type u → Type u} [q : QPF F] open Functor (Liftp Liftr) /-- does recursion on `q.P.M` using `g : α → F α` rather than `g : α → P α` -/ def corecF {α : Type _} (g : α → F α) : α → q.P.M := PFunctor.M.corec fun x => repr (g x) theorem corecF_eq {α : Type _} (g : α → F α) (x : α) : PFunctor.M.dest (corecF g x) = q.P.map (corecF g) (repr (g x)) := by rw [corecF, PFunctor.M.dest_corec] -- Equivalence /-- A pre-congruence on `q.P.M` *viewed as an F-coalgebra*. Not necessarily symmetric. -/ def IsPrecongr (r : q.P.M → q.P.M → Prop) : Prop := ∀ ⦃x y⦄, r x y → abs (q.P.map (Quot.mk r) (PFunctor.M.dest x)) = abs (q.P.map (Quot.mk r) (PFunctor.M.dest y)) /-- The maximal congruence on `q.P.M`. -/ def Mcongr : q.P.M → q.P.M → Prop := fun x y => ∃ r, IsPrecongr r ∧ r x y /-- coinductive type defined as the final coalgebra of a qpf -/ def Cofix (F : Type u → Type u) [q : QPF F] := Quot (@Mcongr F q) instance [Inhabited q.P.A] : Inhabited (Cofix F) := ⟨Quot.mk _ default⟩ /-- corecursor for type defined by `Cofix` -/ def Cofix.corec {α : Type _} (g : α → F α) (x : α) : Cofix F := Quot.mk _ (corecF g x) /-- destructor for type defined by `Cofix` -/ def Cofix.dest : Cofix F → F (Cofix F) := Quot.lift (fun x => Quot.mk Mcongr <$> abs (PFunctor.M.dest x)) (by rintro x y ⟨r, pr, rxy⟩ dsimp have : ∀ x y, r x y → Mcongr x y := by intro x y h exact ⟨r, pr, h⟩ rw [← Quot.factor_mk_eq _ _ this] conv => lhs rw [comp_map, ← abs_map, pr rxy, abs_map, ← comp_map]) theorem Cofix.dest_corec {α : Type u} (g : α → F α) (x : α) : Cofix.dest (Cofix.corec g x) = Cofix.corec g <$> g x := by conv => lhs rw [Cofix.dest, Cofix.corec] dsimp rw [corecF_eq, abs_map, abs_repr, ← comp_map]; rfl private theorem Cofix.bisim_aux (r : Cofix F → Cofix F → Prop) (h' : ∀ x, r x x) (h : ∀ x y, r x y → Quot.mk r <$> Cofix.dest x = Quot.mk r <$> Cofix.dest y) : ∀ x y, r x y → x = y := by rintro ⟨x⟩ ⟨y⟩ rxy apply Quot.sound let r' x y := r (Quot.mk _ x) (Quot.mk _ y) have : IsPrecongr r' := by intro a b r'ab have h₀ : Quot.mk r <$> Quot.mk Mcongr <$> abs (PFunctor.M.dest a) = Quot.mk r <$> Quot.mk Mcongr <$> abs (PFunctor.M.dest b) := h _ _ r'ab have h₁ : ∀ u v : q.P.M, Mcongr u v → Quot.mk r' u = Quot.mk r' v := by intro u v cuv apply Quot.sound simp only [r'] rw [Quot.sound cuv] apply h' let f : Quot r → Quot r' := Quot.lift (Quot.lift (Quot.mk r') h₁) <| by rintro ⟨c⟩ ⟨d⟩ rcd exact Quot.sound rcd have : f ∘ Quot.mk r ∘ Quot.mk Mcongr = Quot.mk r' := rfl rw [← this, ← PFunctor.map_map _ _ f, ← PFunctor.map_map _ _ (Quot.mk r), abs_map, abs_map, abs_map, h₀] rw [← PFunctor.map_map _ _ f, ← PFunctor.map_map _ _ (Quot.mk r), abs_map, abs_map, abs_map] exact ⟨r', this, rxy⟩ theorem Cofix.bisim_rel (r : Cofix F → Cofix F → Prop) (h : ∀ x y, r x y → Quot.mk r <$> Cofix.dest x = Quot.mk r <$> Cofix.dest y) : ∀ x y, r x y → x = y := by let r' (x y) := x = y ∨ r x y intro x y rxy apply Cofix.bisim_aux r' · intro x left rfl · intro x y r'xy cases' r'xy with r'xy r'xy · rw [r'xy] have : ∀ x y, r x y → r' x y := fun x y h => Or.inr h rw [← Quot.factor_mk_eq _ _ this] dsimp [r'] rw [@comp_map _ q _ _ _ (Quot.mk r), @comp_map _ q _ _ _ (Quot.mk r)] rw [h _ _ r'xy] right; exact rxy theorem Cofix.bisim (r : Cofix F → Cofix F → Prop) (h : ∀ x y, r x y → Liftr r (Cofix.dest x) (Cofix.dest y)) : ∀ x y, r x y → x = y := by apply Cofix.bisim_rel intro x y rxy rcases (liftr_iff r _ _).mp (h x y rxy) with ⟨a, f₀, f₁, dxeq, dyeq, h'⟩ rw [dxeq, dyeq, ← abs_map, ← abs_map, PFunctor.map_eq, PFunctor.map_eq] congr 2 with i apply Quot.sound apply h' theorem Cofix.bisim' {α : Type*} (Q : α → Prop) (u v : α → Cofix F) (h : ∀ x, Q x → ∃ a f f', Cofix.dest (u x) = abs ⟨a, f⟩ ∧ Cofix.dest (v x) = abs ⟨a, f'⟩ ∧ ∀ i, ∃ x', Q x' ∧ f i = u x' ∧ f' i = v x') : ∀ x, Q x → u x = v x := fun x Qx => let R := fun w z : Cofix F => ∃ x', Q x' ∧ w = u x' ∧ z = v x' Cofix.bisim R (fun x y ⟨x', Qx', xeq, yeq⟩ => by rcases h x' Qx' with ⟨a, f, f', ux'eq, vx'eq, h'⟩ rw [liftr_iff] exact ⟨a, f, f', xeq.symm ▸ ux'eq, yeq.symm ▸ vx'eq, h'⟩) _ _ ⟨x, Qx, rfl, rfl⟩ end QPF /- Composition of qpfs. -/ namespace QPF variable {F₂ : Type u → Type u} [q₂ : QPF F₂] variable {F₁ : Type u → Type u} [q₁ : QPF F₁] /-- composition of qpfs gives another qpf -/ def comp : QPF (Functor.Comp F₂ F₁) where P := PFunctor.comp q₂.P q₁.P abs {α} := by dsimp [Functor.Comp] intro p exact abs ⟨p.1.1, fun x => abs ⟨p.1.2 x, fun y => p.2 ⟨x, y⟩⟩⟩ repr {α} := by dsimp [Functor.Comp] intro y refine ⟨⟨(repr y).1, fun u => (repr ((repr y).2 u)).1⟩, ?_⟩ dsimp [PFunctor.comp] intro x exact (repr ((repr y).2 x.1)).snd x.2 abs_repr {α} := by dsimp [Functor.Comp] intro x conv => rhs rw [← abs_repr x] cases' repr x with a f dsimp congr with x cases' h' : repr (f x) with b g dsimp; rw [← h', abs_repr] abs_map {α β} f := by dsimp (config := { unfoldPartialApp := true }) [Functor.Comp, PFunctor.comp] intro p cases' p with a g; dsimp cases' a with b h; dsimp symm trans · symm apply abs_map congr rw [PFunctor.map_eq] dsimp [Function.comp_def] congr ext x rw [← abs_map] rfl end QPF /- Quotients. We show that if `F` is a qpf and `G` is a suitable quotient of `F`, then `G` is a qpf. -/ namespace QPF variable {F : Type u → Type u} [q : QPF F] variable {G : Type u → Type u} [Functor G] variable {FG_abs : ∀ {α}, F α → G α} variable {FG_repr : ∀ {α}, G α → F α} /-- Given a qpf `F` and a well-behaved surjection `FG_abs` from `F α` to functor `G α`, `G` is a qpf. We can consider `G` a quotient on `F` where elements `x y : F α` are in the same equivalence class if `FG_abs x = FG_abs y`. -/ def quotientQPF (FG_abs_repr : ∀ {α} (x : G α), FG_abs (FG_repr x) = x) (FG_abs_map : ∀ {α β} (f : α → β) (x : F α), FG_abs (f <$> x) = f <$> FG_abs x) : QPF G where P := q.P abs {α} p := FG_abs (abs p) repr {α} x := repr (FG_repr x) abs_repr {α} x := by simp only; rw [abs_repr, FG_abs_repr] abs_map {α β} f x := by simp only; rw [abs_map, FG_abs_map] end QPF /- Support. -/ namespace QPF variable {F : Type u → Type u} [q : QPF F] open Functor (Liftp Liftr supp) open Set theorem mem_supp {α : Type u} (x : F α) (u : α) : u ∈ supp x ↔ ∀ a f, abs ⟨a, f⟩ = x → u ∈ f '' univ := by rw [supp]; dsimp; constructor · intro h a f haf have : Liftp (fun u => u ∈ f '' univ) x := by rw [liftp_iff] exact ⟨a, f, haf.symm, fun i => mem_image_of_mem _ (mem_univ _)⟩ exact h this intro h p; rw [liftp_iff] rintro ⟨a, f, xeq, h'⟩ rcases h a f xeq.symm with ⟨i, _, hi⟩ rw [← hi]; apply h' theorem supp_eq {α : Type u} (x : F α) : supp x = { u | ∀ a f, abs ⟨a, f⟩ = x → u ∈ f '' univ } := by ext apply mem_supp theorem has_good_supp_iff {α : Type u} (x : F α) : (∀ p, Liftp p x ↔ ∀ u ∈ supp x, p u) ↔ ∃ a f, abs ⟨a, f⟩ = x ∧ ∀ a' f', abs ⟨a', f'⟩ = x → f '' univ ⊆ f' '' univ := by constructor · intro h have : Liftp (supp x) x := by rw [h]; intro u; exact id rw [liftp_iff] at this rcases this with ⟨a, f, xeq, h'⟩ refine ⟨a, f, xeq.symm, ?_⟩ intro a' f' h'' rintro u ⟨i, _, hfi⟩ have : u ∈ supp x := by rw [← hfi]; apply h' exact (mem_supp x u).mp this _ _ h'' rintro ⟨a, f, xeq, h⟩ p; rw [liftp_iff]; constructor · rintro ⟨a', f', xeq', h'⟩ u usuppx rcases (mem_supp x u).mp usuppx a' f' xeq'.symm with ⟨i, _, f'ieq⟩ rw [← f'ieq] apply h' intro h' refine ⟨a, f, xeq.symm, ?_⟩; intro i apply h'; rw [mem_supp] intro a' f' xeq' apply h a' f' xeq' apply mem_image_of_mem _ (mem_univ _) /-- A qpf is said to be uniform if every polynomial functor representing a single value all have the same range. -/ def IsUniform : Prop := ∀ ⦃α : Type u⦄ (a a' : q.P.A) (f : q.P.B a → α) (f' : q.P.B a' → α), abs ⟨a, f⟩ = abs ⟨a', f'⟩ → f '' univ = f' '' univ /-- does `abs` preserve `Liftp`? -/ def LiftpPreservation : Prop := ∀ ⦃α⦄ (p : α → Prop) (x : q.P α), Liftp p (abs x) ↔ Liftp p x /-- does `abs` preserve `supp`? -/ def SuppPreservation : Prop := ∀ ⦃α⦄ (x : q.P α), supp (abs x) = supp x theorem supp_eq_of_isUniform (h : q.IsUniform) {α : Type u} (a : q.P.A) (f : q.P.B a → α) : supp (abs ⟨a, f⟩) = f '' univ := by ext u; rw [mem_supp]; constructor · intro h' apply h' _ _ rfl intro h' a' f' e rw [← h _ _ _ _ e.symm]; apply h' theorem liftp_iff_of_isUniform (h : q.IsUniform) {α : Type u} (x : F α) (p : α → Prop) : Liftp p x ↔ ∀ u ∈ supp x, p u := by rw [liftp_iff, ← abs_repr x] cases' repr x with a f; constructor · rintro ⟨a', f', abseq, hf⟩ u rw [supp_eq_of_isUniform h, h _ _ _ _ abseq] rintro ⟨i, _, hi⟩ rw [← hi] apply hf intro h' refine ⟨a, f, rfl, fun i => h' _ ?_⟩ rw [supp_eq_of_isUniform h] exact ⟨i, mem_univ i, rfl⟩ theorem supp_map (h : q.IsUniform) {α β : Type u} (g : α → β) (x : F α) : supp (g <$> x) = g '' supp x := by rw [← abs_repr x]; cases' repr x with a f; rw [← abs_map, PFunctor.map_eq] rw [supp_eq_of_isUniform h, supp_eq_of_isUniform h, image_comp] theorem suppPreservation_iff_uniform : q.SuppPreservation ↔ q.IsUniform := by constructor · intro h α a a' f f' h' rw [← PFunctor.supp_eq, ← PFunctor.supp_eq, ← h, h', h] · rintro h α ⟨a, f⟩ rwa [supp_eq_of_isUniform, PFunctor.supp_eq] theorem suppPreservation_iff_liftpPreservation : q.SuppPreservation ↔ q.LiftpPreservation := by constructor <;> intro h · rintro α p ⟨a, f⟩ have h' := h rw [suppPreservation_iff_uniform] at h' dsimp only [SuppPreservation, supp] at h rw [liftp_iff_of_isUniform h', supp_eq_of_isUniform h', PFunctor.liftp_iff'] simp only [image_univ, mem_range, exists_imp] constructor <;> intros <;> subst_vars <;> solve_by_elim · rintro α ⟨a, f⟩ simp only [LiftpPreservation] at h simp only [supp, h] theorem liftpPreservation_iff_uniform : q.LiftpPreservation ↔ q.IsUniform := by rw [← suppPreservation_iff_liftpPreservation, suppPreservation_iff_uniform] end QPF
Data\Rat\BigOperators.lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import Mathlib.Algebra.BigOperators.Group.Finset import Mathlib.Data.Rat.Cast.CharZero /-! # Casting lemmas for rational numbers involving sums and products -/ variable {ι α : Type*} namespace Rat section WithDivRing variable [DivisionRing α] [CharZero α] @[simp, norm_cast] theorem cast_list_sum (s : List ℚ) : (↑s.sum : α) = (s.map (↑)).sum := map_list_sum (Rat.castHom α) _ @[simp, norm_cast] theorem cast_multiset_sum (s : Multiset ℚ) : (↑s.sum : α) = (s.map (↑)).sum := map_multiset_sum (Rat.castHom α) _ @[simp, norm_cast] theorem cast_sum (s : Finset ι) (f : ι → ℚ) : ∑ i ∈ s, f i = ∑ i ∈ s, (f i : α) := map_sum (Rat.castHom α) _ s @[simp, norm_cast] theorem cast_list_prod (s : List ℚ) : (↑s.prod : α) = (s.map (↑)).prod := map_list_prod (Rat.castHom α) _ end WithDivRing section Field variable [Field α] [CharZero α] @[simp, norm_cast] theorem cast_multiset_prod (s : Multiset ℚ) : (↑s.prod : α) = (s.map (↑)).prod := map_multiset_prod (Rat.castHom α) _ @[simp, norm_cast] theorem cast_prod (s : Finset ι) (f : ι → ℚ) : ∏ i ∈ s, f i = ∏ i ∈ s, (f i : α) := map_prod (Rat.castHom α) _ _ end Field end Rat
Data\Rat\Defs.lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import Mathlib.Algebra.Group.Defs import Mathlib.Data.Int.Defs import Mathlib.Data.Rat.Init import Mathlib.Order.Basic import Mathlib.Tactic.Common import Batteries.Data.Rat.Lemmas /-! # Basics for the Rational Numbers ## Summary We define the integral domain structure on `ℚ` and prove basic lemmas about it. The definition of the field structure on `ℚ` will be done in `Mathlib.Data.Rat.Basic` once the `Field` class has been defined. ## Main Definitions - `Rat.divInt n d` constructs a rational number `q = n / d` from `n d : ℤ`. ## Notations - `/.` is infix notation for `Rat.divInt`. -/ -- TODO: If `Inv` was defined earlier than `Algebra.Group.Defs`, we could have -- assert_not_exists Monoid assert_not_exists MonoidWithZero assert_not_exists Lattice assert_not_exists PNat assert_not_exists Nat.dvd_mul open Function namespace Rat variable {q : ℚ} -- Porting note: the definition of `ℚ` has changed; in mathlib3 this was a field. theorem pos (a : ℚ) : 0 < a.den := Nat.pos_of_ne_zero a.den_nz lemma mk'_num_den (q : ℚ) : mk' q.num q.den q.den_nz q.reduced = q := rfl @[simp] theorem ofInt_eq_cast (n : ℤ) : ofInt n = Int.cast n := rfl -- TODO: Replace `Rat.ofNat_num`/`Rat.ofNat_den` in Batteries -- See note [no_index around OfNat.ofNat] @[simp] lemma num_ofNat (n : ℕ) : num (no_index (OfNat.ofNat n)) = OfNat.ofNat n := rfl @[simp] lemma den_ofNat (n : ℕ) : den (no_index (OfNat.ofNat n)) = 1 := rfl @[simp, norm_cast] lemma num_natCast (n : ℕ) : num n = n := rfl @[simp, norm_cast] lemma den_natCast (n : ℕ) : den n = 1 := rfl -- TODO: Replace `intCast_num`/`intCast_den` the names in Batteries @[simp, norm_cast] lemma num_intCast (n : ℤ) : (n : ℚ).num = n := rfl @[simp, norm_cast] lemma den_intCast (n : ℤ) : (n : ℚ).den = 1 := rfl @[deprecated (since := "2024-04-29")] alias coe_int_num := num_intCast @[deprecated (since := "2024-04-29")] alias coe_int_den := den_intCast lemma intCast_injective : Injective (Int.cast : ℤ → ℚ) := fun _ _ ↦ congr_arg num lemma natCast_injective : Injective (Nat.cast : ℕ → ℚ) := intCast_injective.comp fun _ _ ↦ Int.natCast_inj.1 -- We want to use these lemmas earlier than the lemmas simp can prove them with @[simp, nolint simpNF, norm_cast] lemma natCast_inj {m n : ℕ} : (m : ℚ) = n ↔ m = n := natCast_injective.eq_iff @[simp, nolint simpNF, norm_cast] lemma intCast_eq_zero {n : ℤ} : (n : ℚ) = 0 ↔ n = 0 := intCast_inj @[simp, nolint simpNF, norm_cast] lemma natCast_eq_zero {n : ℕ} : (n : ℚ) = 0 ↔ n = 0 := natCast_inj @[simp, nolint simpNF, norm_cast] lemma intCast_eq_one {n : ℤ} : (n : ℚ) = 1 ↔ n = 1 := intCast_inj @[simp, nolint simpNF, norm_cast] lemma natCast_eq_one {n : ℕ} : (n : ℚ) = 1 ↔ n = 1 := natCast_inj -- Porting note (#11215): TODO Should this be namespaced? lemma mkRat_eq_divInt (n d) : mkRat n d = n /. d := rfl @[simp] lemma mk'_zero (d) (h : d ≠ 0) (w) : mk' 0 d h w = 0 := by congr; simp_all @[simp] lemma num_eq_zero {q : ℚ} : q.num = 0 ↔ q = 0 := by induction q constructor · rintro rfl exact mk'_zero _ _ _ · exact congr_arg num lemma num_ne_zero {q : ℚ} : q.num ≠ 0 ↔ q ≠ 0 := num_eq_zero.not @[simp] lemma den_ne_zero (q : ℚ) : q.den ≠ 0 := q.den_pos.ne' @[simp] lemma num_nonneg : 0 ≤ q.num ↔ 0 ≤ q := by simp [Int.le_iff_lt_or_eq, instLE, Rat.blt, Int.not_lt]; tauto @[simp] theorem divInt_eq_zero {a b : ℤ} (b0 : b ≠ 0) : a /. b = 0 ↔ a = 0 := by rw [← zero_divInt b, divInt_eq_iff b0 b0, Int.zero_mul, Int.mul_eq_zero, or_iff_left b0] theorem divInt_ne_zero {a b : ℤ} (b0 : b ≠ 0) : a /. b ≠ 0 ↔ a ≠ 0 := (divInt_eq_zero b0).not -- Porting note: this can move to Batteries theorem normalize_eq_mk' (n : Int) (d : Nat) (h : d ≠ 0) (c : Nat.gcd (Int.natAbs n) d = 1) : normalize n d h = mk' n d h c := (mk_eq_normalize ..).symm -- TODO: Rename `mkRat_num_den` in Batteries @[simp] alias mkRat_num_den' := mkRat_self -- TODO: Rename `Rat.divInt_self` to `Rat.num_divInt_den` in Batteries lemma num_divInt_den (q : ℚ) : q.num /. q.den = q := divInt_self _ lemma mk'_eq_divInt {n d h c} : (⟨n, d, h, c⟩ : ℚ) = n /. d := (num_divInt_den _).symm theorem intCast_eq_divInt (z : ℤ) : (z : ℚ) = z /. 1 := mk'_eq_divInt -- TODO: Rename `divInt_self` in Batteries to `num_divInt_den` @[simp] lemma divInt_self' {n : ℤ} (hn : n ≠ 0) : n /. n = 1 := by simpa using divInt_mul_right (n := 1) (d := 1) hn /-- Define a (dependent) function or prove `∀ r : ℚ, p r` by dealing with rational numbers of the form `n /. d` with `0 < d` and coprime `n`, `d`. -/ @[elab_as_elim] def numDenCasesOn.{u} {C : ℚ → Sort u} : ∀ (a : ℚ) (_ : ∀ n d, 0 < d → (Int.natAbs n).Coprime d → C (n /. d)), C a | ⟨n, d, h, c⟩, H => by rw [mk'_eq_divInt]; exact H n d (Nat.pos_of_ne_zero h) c /-- Define a (dependent) function or prove `∀ r : ℚ, p r` by dealing with rational numbers of the form `n /. d` with `d ≠ 0`. -/ @[elab_as_elim] def numDenCasesOn'.{u} {C : ℚ → Sort u} (a : ℚ) (H : ∀ (n : ℤ) (d : ℕ), d ≠ 0 → C (n /. d)) : C a := numDenCasesOn a fun n d h _ => H n d h.ne' /-- Define a (dependent) function or prove `∀ r : ℚ, p r` by dealing with rational numbers of the form `mk' n d` with `d ≠ 0`. -/ @[elab_as_elim] def numDenCasesOn''.{u} {C : ℚ → Sort u} (a : ℚ) (H : ∀ (n : ℤ) (d : ℕ) (nz red), C (mk' n d nz red)) : C a := numDenCasesOn a fun n d h h' ↦ by rw [← mk_eq_divInt _ _ h.ne' h']; exact H n d h.ne' _ -- Porting note: there's already an instance for `Add ℚ` is in Batteries. theorem lift_binop_eq (f : ℚ → ℚ → ℚ) (f₁ : ℤ → ℤ → ℤ → ℤ → ℤ) (f₂ : ℤ → ℤ → ℤ → ℤ → ℤ) (fv : ∀ {n₁ d₁ h₁ c₁ n₂ d₂ h₂ c₂}, f ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ = f₁ n₁ d₁ n₂ d₂ /. f₂ n₁ d₁ n₂ d₂) (f0 : ∀ {n₁ d₁ n₂ d₂}, d₁ ≠ 0 → d₂ ≠ 0 → f₂ n₁ d₁ n₂ d₂ ≠ 0) (a b c d : ℤ) (b0 : b ≠ 0) (d0 : d ≠ 0) (H : ∀ {n₁ d₁ n₂ d₂}, a * d₁ = n₁ * b → c * d₂ = n₂ * d → f₁ n₁ d₁ n₂ d₂ * f₂ a b c d = f₁ a b c d * f₂ n₁ d₁ n₂ d₂) : f (a /. b) (c /. d) = f₁ a b c d /. f₂ a b c d := by generalize ha : a /. b = x; cases' x with n₁ d₁ h₁ c₁; rw [mk'_eq_divInt] at ha generalize hc : c /. d = x; cases' x with n₂ d₂ h₂ c₂; rw [mk'_eq_divInt] at hc rw [fv] have d₁0 := Int.ofNat_ne_zero.2 h₁ have d₂0 := Int.ofNat_ne_zero.2 h₂ exact (divInt_eq_iff (f0 d₁0 d₂0) (f0 b0 d0)).2 (H ((divInt_eq_iff b0 d₁0).1 ha) ((divInt_eq_iff d0 d₂0).1 hc)) attribute [simp] divInt_add_divInt @[deprecated divInt_add_divInt (since := "2024-03-18")] theorem add_def'' {a b c d : ℤ} (b0 : b ≠ 0) (d0 : d ≠ 0) : a /. b + c /. d = (a * d + c * b) /. (b * d) := divInt_add_divInt _ _ b0 d0 attribute [simp] neg_divInt lemma neg_def (q : ℚ) : -q = -q.num /. q.den := by rw [← neg_divInt, num_divInt_den] @[simp] lemma divInt_neg (n d : ℤ) : n /. -d = -n /. d := divInt_neg' .. @[deprecated (since := "2024-03-18")] alias divInt_neg_den := divInt_neg attribute [simp] divInt_sub_divInt @[deprecated divInt_sub_divInt (since := "2024-03-18")] lemma sub_def'' {a b c d : ℤ} (b0 : b ≠ 0) (d0 : d ≠ 0) : a /. b - c /. d = (a * d - c * b) /. (b * d) := divInt_sub_divInt _ _ b0 d0 @[simp] lemma divInt_mul_divInt' (n₁ d₁ n₂ d₂ : ℤ) : (n₁ /. d₁) * (n₂ /. d₂) = (n₁ * n₂) /. (d₁ * d₂) := by obtain rfl | h₁ := eq_or_ne d₁ 0 · simp obtain rfl | h₂ := eq_or_ne d₂ 0 · simp exact divInt_mul_divInt _ _ h₁ h₂ attribute [simp] mkRat_mul_mkRat lemma mk'_mul_mk' (n₁ n₂ : ℤ) (d₁ d₂ : ℕ) (hd₁ hd₂ hnd₁ hnd₂) (h₁₂ : n₁.natAbs.Coprime d₂) (h₂₁ : n₂.natAbs.Coprime d₁) : mk' n₁ d₁ hd₁ hnd₁ * mk' n₂ d₂ hd₂ hnd₂ = mk' (n₁ * n₂) (d₁ * d₂) (Nat.mul_ne_zero hd₁ hd₂) (by rw [Int.natAbs_mul]; exact (hnd₁.mul h₂₁).mul_right (h₁₂.mul hnd₂)) := by rw [mul_def]; dsimp; simp [mk_eq_normalize] lemma mul_eq_mkRat (q r : ℚ) : q * r = mkRat (q.num * r.num) (q.den * r.den) := by rw [mul_def, normalize_eq_mkRat] -- TODO: Rename `divInt_eq_iff` in Batteries to `divInt_eq_divInt` alias divInt_eq_divInt := divInt_eq_iff @[deprecated (since := "2024-04-29")] alias mul_num_den := mul_eq_mkRat instance instPowNat : Pow ℚ ℕ where pow q n := ⟨q.num ^ n, q.den ^ n, by simp [Nat.pow_eq_zero], by rw [Int.natAbs_pow]; exact q.reduced.pow _ _⟩ lemma pow_def (q : ℚ) (n : ℕ) : q ^ n = ⟨q.num ^ n, q.den ^ n, by simp [Nat.pow_eq_zero], by rw [Int.natAbs_pow]; exact q.reduced.pow _ _⟩ := rfl lemma pow_eq_mkRat (q : ℚ) (n : ℕ) : q ^ n = mkRat (q.num ^ n) (q.den ^ n) := by rw [pow_def, mk_eq_mkRat] lemma pow_eq_divInt (q : ℚ) (n : ℕ) : q ^ n = q.num ^ n /. q.den ^ n := by rw [pow_def, mk_eq_divInt, Int.natCast_pow] @[simp] lemma num_pow (q : ℚ) (n : ℕ) : (q ^ n).num = q.num ^ n := rfl @[simp] lemma den_pow (q : ℚ) (n : ℕ) : (q ^ n).den = q.den ^ n := rfl @[simp] lemma mk'_pow (num : ℤ) (den : ℕ) (hd hdn) (n : ℕ) : mk' num den hd hdn ^ n = mk' (num ^ n) (den ^ n) (by simp [Nat.pow_eq_zero, hd]) (by rw [Int.natAbs_pow]; exact hdn.pow _ _) := rfl instance : Inv ℚ := ⟨Rat.inv⟩ @[simp] lemma inv_divInt' (a b : ℤ) : (a /. b)⁻¹ = b /. a := inv_divInt .. @[simp] lemma inv_mkRat (a : ℤ) (b : ℕ) : (mkRat a b)⁻¹ = b /. a := by rw [mkRat_eq_divInt, inv_divInt'] lemma inv_def' (q : ℚ) : q⁻¹ = q.den /. q.num := by rw [← inv_divInt', num_divInt_den] @[simp] lemma divInt_div_divInt (n₁ d₁ n₂ d₂) : (n₁ /. d₁) / (n₂ /. d₂) = (n₁ * d₂) /. (d₁ * n₂) := by rw [div_def, inv_divInt, divInt_mul_divInt'] lemma div_def' (q r : ℚ) : q / r = (q.num * r.den) /. (q.den * r.num) := by rw [← divInt_div_divInt, num_divInt_den, num_divInt_den] @[deprecated (since := "2024-04-15")] alias div_num_den := div_def' variable (a b c : ℚ) protected lemma add_zero : a + 0 = a := by simp [add_def, normalize_eq_mkRat] protected lemma zero_add : 0 + a = a := by simp [add_def, normalize_eq_mkRat] protected lemma add_comm : a + b = b + a := by simp [add_def, Int.add_comm, Int.mul_comm, Nat.mul_comm] protected theorem add_assoc : a + b + c = a + (b + c) := numDenCasesOn' a fun n₁ d₁ h₁ ↦ numDenCasesOn' b fun n₂ d₂ h₂ ↦ numDenCasesOn' c fun n₃ d₃ h₃ ↦ by simp only [ne_eq, Int.natCast_eq_zero, h₁, not_false_eq_true, h₂, divInt_add_divInt, Int.mul_eq_zero, or_self, h₃] rw [Int.mul_assoc, Int.add_mul, Int.add_mul, Int.mul_assoc, Int.add_assoc] congr 2 ac_rfl protected lemma add_left_neg : -a + a = 0 := by simp [add_def, normalize_eq_mkRat, Int.neg_mul, Int.add_comm, ← Int.sub_eq_add_neg] @[deprecated zero_divInt (since := "2024-03-18")] lemma divInt_zero_one : 0 /. 1 = 0 := zero_divInt _ @[simp] lemma divInt_one (n : ℤ) : n /. 1 = n := by simp [divInt, mkRat, normalize] @[simp] lemma mkRat_one (n : ℤ) : mkRat n 1 = n := by simp [mkRat_eq_divInt] lemma divInt_one_one : 1 /. 1 = 1 := by rw [divInt_one, intCast_one] @[deprecated divInt_one (since := "2024-03-18")] lemma divInt_neg_one_one : -1 /. 1 = -1 := by rw [divInt_one, intCast_neg, intCast_one] protected theorem mul_assoc : a * b * c = a * (b * c) := numDenCasesOn' a fun n₁ d₁ h₁ => numDenCasesOn' b fun n₂ d₂ h₂ => numDenCasesOn' c fun n₃ d₃ h₃ => by simp [h₁, h₂, h₃, Int.mul_comm, Nat.mul_assoc, Int.mul_left_comm] protected theorem add_mul : (a + b) * c = a * c + b * c := numDenCasesOn' a fun n₁ d₁ h₁ ↦ numDenCasesOn' b fun n₂ d₂ h₂ ↦ numDenCasesOn' c fun n₃ d₃ h₃ ↦ by simp only [ne_eq, Int.natCast_eq_zero, h₁, not_false_eq_true, h₂, divInt_add_divInt, Int.mul_eq_zero, or_self, h₃, divInt_mul_divInt] rw [← divInt_mul_right (Int.natCast_ne_zero.2 h₃), Int.add_mul, Int.add_mul] ac_rfl protected theorem mul_add : a * (b + c) = a * b + a * c := by rw [Rat.mul_comm, Rat.add_mul, Rat.mul_comm, Rat.mul_comm c a] protected theorem zero_ne_one : 0 ≠ (1 : ℚ) := by rw [ne_comm, ← divInt_one_one, divInt_ne_zero] <;> omega attribute [simp] mkRat_eq_zero protected theorem mul_inv_cancel : a ≠ 0 → a * a⁻¹ = 1 := numDenCasesOn' a fun n d hd hn ↦ by simp only [divInt_ofNat, ne_eq, hd, not_false_eq_true, mkRat_eq_zero] at hn simp [-divInt_ofNat, mkRat_eq_divInt, Int.mul_comm, Int.mul_ne_zero hn (Int.ofNat_ne_zero.2 hd)] protected theorem inv_mul_cancel (h : a ≠ 0) : a⁻¹ * a = 1 := Eq.trans (Rat.mul_comm _ _) (Rat.mul_inv_cancel _ h) -- Porting note: we already have a `DecidableEq ℚ`. -- Extra instances to short-circuit type class resolution -- TODO(Mario): this instance slows down Mathlib.Data.Real.Basic instance nontrivial : Nontrivial ℚ where exists_pair_ne := ⟨1, 0, by decide⟩ /-! ### The rational numbers are a group -/ instance addCommGroup : AddCommGroup ℚ where zero := 0 add := (· + ·) neg := Neg.neg zero_add := Rat.zero_add add_zero := Rat.add_zero add_comm := Rat.add_comm add_assoc := Rat.add_assoc add_left_neg := Rat.add_left_neg sub_eq_add_neg := Rat.sub_eq_add_neg nsmul := nsmulRec zsmul := zsmulRec instance addGroup : AddGroup ℚ := by infer_instance instance addCommMonoid : AddCommMonoid ℚ := by infer_instance instance addMonoid : AddMonoid ℚ := by infer_instance instance addLeftCancelSemigroup : AddLeftCancelSemigroup ℚ := by infer_instance instance addRightCancelSemigroup : AddRightCancelSemigroup ℚ := by infer_instance instance addCommSemigroup : AddCommSemigroup ℚ := by infer_instance instance addSemigroup : AddSemigroup ℚ := by infer_instance instance commMonoid : CommMonoid ℚ where one := 1 mul := (· * ·) mul_one := Rat.mul_one one_mul := Rat.one_mul mul_comm := Rat.mul_comm mul_assoc := Rat.mul_assoc npow n q := q ^ n npow_zero := by intros; apply Rat.ext <;> simp [Int.pow_zero] npow_succ n q := by dsimp rw [← q.mk'_num_den, mk'_pow, mk'_mul_mk'] · congr · rw [mk'_pow, Int.natAbs_pow] exact q.reduced.pow_left _ · rw [mk'_pow] exact q.reduced.pow_right _ instance monoid : Monoid ℚ := by infer_instance instance commSemigroup : CommSemigroup ℚ := by infer_instance instance semigroup : Semigroup ℚ := by infer_instance theorem eq_iff_mul_eq_mul {p q : ℚ} : p = q ↔ p.num * q.den = q.num * p.den := by conv => lhs rw [← num_divInt_den p, ← num_divInt_den q] apply Rat.divInt_eq_iff <;> · rw [← Int.natCast_zero, Ne, Int.ofNat_inj] apply den_nz @[simp] theorem den_neg_eq_den (q : ℚ) : (-q).den = q.den := rfl @[simp] theorem num_neg_eq_neg_num (q : ℚ) : (-q).num = -q.num := rfl @[simp] theorem num_zero : Rat.num 0 = 0 := rfl @[simp] theorem den_zero : Rat.den 0 = 1 := rfl lemma zero_of_num_zero {q : ℚ} (hq : q.num = 0) : q = 0 := by simpa [hq] using q.num_divInt_den.symm theorem zero_iff_num_zero {q : ℚ} : q = 0 ↔ q.num = 0 := ⟨fun _ => by simp [*], zero_of_num_zero⟩ @[simp] theorem num_one : (1 : ℚ).num = 1 := rfl @[simp] theorem den_one : (1 : ℚ).den = 1 := rfl theorem mk_num_ne_zero_of_ne_zero {q : ℚ} {n d : ℤ} (hq : q ≠ 0) (hqnd : q = n /. d) : n ≠ 0 := fun this => hq <| by simpa [this] using hqnd theorem mk_denom_ne_zero_of_ne_zero {q : ℚ} {n d : ℤ} (hq : q ≠ 0) (hqnd : q = n /. d) : d ≠ 0 := fun this => hq <| by simpa [this] using hqnd theorem divInt_ne_zero_of_ne_zero {n d : ℤ} (h : n ≠ 0) (hd : d ≠ 0) : n /. d ≠ 0 := (divInt_ne_zero hd).mpr h protected lemma nonneg_antisymm : 0 ≤ q → 0 ≤ -q → q = 0 := by simp_rw [← num_eq_zero, Int.le_antisymm_iff, ← num_nonneg, num_neg_eq_neg_num, Int.neg_nonneg] tauto protected lemma nonneg_total (a : ℚ) : 0 ≤ a ∨ 0 ≤ -a := by simp_rw [← num_nonneg, num_neg_eq_neg_num, Int.neg_nonneg]; exact Int.le_total _ _ section Casts protected theorem add_divInt (a b c : ℤ) : (a + b) /. c = a /. c + b /. c := if h : c = 0 then by simp [h] else by rw [divInt_add_divInt _ _ h h, divInt_eq_iff h (Int.mul_ne_zero h h)] simp [Int.add_mul, Int.mul_assoc] theorem divInt_eq_div (n d : ℤ) : n /. d = (n : ℚ) / d := by simp [div_def'] lemma intCast_div_eq_divInt (n d : ℤ) : (n : ℚ) / (d) = n /. d := by rw [divInt_eq_div] theorem natCast_div_eq_divInt (n d : ℕ) : (n : ℚ) / d = n /. d := Rat.intCast_div_eq_divInt n d theorem divInt_mul_divInt_cancel {x : ℤ} (hx : x ≠ 0) (n d : ℤ) : n /. x * (x /. d) = n /. d := by by_cases hd : d = 0 · rw [hd] simp rw [divInt_mul_divInt _ _ hx hd, x.mul_comm, divInt_mul_right hx] theorem coe_int_num_of_den_eq_one {q : ℚ} (hq : q.den = 1) : (q.num : ℚ) = q := by conv_rhs => rw [← num_divInt_den q, hq] rw [intCast_eq_divInt] rfl lemma eq_num_of_isInt {q : ℚ} (h : q.isInt) : q = q.num := by rw [Rat.isInt, Nat.beq_eq_true_eq] at h exact (Rat.coe_int_num_of_den_eq_one h).symm theorem den_eq_one_iff (r : ℚ) : r.den = 1 ↔ ↑r.num = r := ⟨Rat.coe_int_num_of_den_eq_one, fun h => h ▸ Rat.den_intCast r.num⟩ instance canLift : CanLift ℚ ℤ (↑) fun q => q.den = 1 := ⟨fun q hq => ⟨q.num, coe_int_num_of_den_eq_one hq⟩⟩ @[deprecated (since := "2024-04-05")] alias coe_int_eq_divInt := intCast_eq_divInt @[deprecated (since := "2024-04-05")] alias coe_int_div_eq_divInt := intCast_div_eq_divInt -- Will be subsumed by `Int.coe_inj` after we have defined -- `LinearOrderedField ℚ` (which implies characteristic zero). theorem coe_int_inj (m n : ℤ) : (m : ℚ) = n ↔ m = n := ⟨congr_arg num, congr_arg _⟩ end Casts end Rat
Data\Rat\Denumerable.lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import Mathlib.Algebra.Order.Ring.Rat import Mathlib.SetTheory.Cardinal.Basic /-! # Denumerability of ℚ This file proves that ℚ is infinite, denumerable, and deduces that it has cardinality `omega`. -/ assert_not_exists Module assert_not_exists Field namespace Rat open Denumerable instance : Infinite ℚ := Infinite.of_injective ((↑) : ℕ → ℚ) Nat.cast_injective private def denumerable_aux : ℚ ≃ { x : ℤ × ℕ // 0 < x.2 ∧ x.1.natAbs.Coprime x.2 } where toFun x := ⟨⟨x.1, x.2⟩, Nat.pos_of_ne_zero x.3, x.4⟩ invFun x := ⟨x.1.1, x.1.2, ne_zero_of_lt x.2.1, x.2.2⟩ left_inv := fun ⟨_, _, _, _⟩ => rfl right_inv := fun ⟨⟨_, _⟩, _, _⟩ => rfl /-- **Denumerability of the Rational Numbers** -/ instance instDenumerable : Denumerable ℚ := by let T := { x : ℤ × ℕ // 0 < x.2 ∧ x.1.natAbs.Coprime x.2 } letI : Infinite T := Infinite.of_injective _ denumerable_aux.injective letI : Encodable T := Subtype.encodable letI : Denumerable T := ofEncodableOfInfinite T exact Denumerable.ofEquiv T denumerable_aux end Rat open Cardinal theorem Cardinal.mkRat : #ℚ = ℵ₀ := by simp only [mk_eq_aleph0]
Data\Rat\Encodable.lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import Mathlib.Logic.Encodable.Basic import Mathlib.Data.Nat.GCD.Basic import Mathlib.Data.Rat.Init /-! # The rationals are `Encodable`. As a consequence we also get the instance `Countable ℚ`. This is kept separate from `Data.Rat.Defs` in order to minimize imports. -/ namespace Rat instance : Encodable ℚ := Encodable.ofEquiv (Σn : ℤ, { d : ℕ // 0 < d ∧ n.natAbs.Coprime d }) ⟨fun ⟨a, b, c, d⟩ => ⟨a, b, Nat.pos_of_ne_zero c, d⟩, fun ⟨a, b, c, d⟩ => ⟨a, b, Nat.pos_iff_ne_zero.mp c, d⟩, fun _ => rfl, fun ⟨_, _, _, _⟩ => rfl⟩ end Rat
Data\Rat\Floor.lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Kevin Kappelmann -/ import Mathlib.Algebra.Order.Floor import Mathlib.Data.Rat.Cast.Order import Mathlib.Tactic.FieldSimp import Mathlib.Tactic.Ring /-! # Floor Function for Rational Numbers ## Summary We define the `FloorRing` instance on `ℚ`. Some technical lemmas relating `floor` to integer division and modulo arithmetic are derived as well as some simple inequalities. ## Tags rat, rationals, ℚ, floor -/ open Int namespace Rat variable {α : Type*} [LinearOrderedField α] [FloorRing α] protected theorem floor_def' (a : ℚ) : a.floor = a.num / a.den := by rw [Rat.floor] split · next h => simp [h] · next => rfl protected theorem le_floor {z : ℤ} : ∀ {r : ℚ}, z ≤ Rat.floor r ↔ (z : ℚ) ≤ r | ⟨n, d, h, c⟩ => by simp only [Rat.floor_def'] rw [mk'_eq_divInt] have h' := Int.ofNat_lt.2 (Nat.pos_of_ne_zero h) conv => rhs rw [intCast_eq_divInt, Rat.divInt_le_divInt zero_lt_one h', mul_one] exact Int.le_ediv_iff_mul_le h' instance : FloorRing ℚ := (FloorRing.ofFloor ℚ Rat.floor) fun _ _ => Rat.le_floor.symm protected theorem floor_def {q : ℚ} : ⌊q⌋ = q.num / q.den := Rat.floor_def' q theorem floor_int_div_nat_eq_div (n : ℤ) (d : ℕ) : ⌊(↑n : ℚ) / (↑d : ℚ)⌋ = n / (↑d : ℤ) := by rw [Rat.floor_def] obtain rfl | hd := @eq_zero_or_pos _ _ d · simp set q := (n : ℚ) / d with q_eq obtain ⟨c, n_eq_c_mul_num, d_eq_c_mul_denom⟩ : ∃ c, n = c * q.num ∧ (d : ℤ) = c * q.den := by rw [q_eq] exact mod_cast @Rat.exists_eq_mul_div_num_and_eq_mul_div_den n d (mod_cast hd.ne') rw [n_eq_c_mul_num, d_eq_c_mul_denom] refine (Int.mul_ediv_mul_of_pos _ _ <| pos_of_mul_pos_left ?_ <| Int.natCast_nonneg q.den).symm rwa [← d_eq_c_mul_denom, Int.natCast_pos] @[simp, norm_cast] theorem floor_cast (x : ℚ) : ⌊(x : α)⌋ = ⌊x⌋ := floor_eq_iff.2 (mod_cast floor_eq_iff.1 (Eq.refl ⌊x⌋)) @[simp, norm_cast] theorem ceil_cast (x : ℚ) : ⌈(x : α)⌉ = ⌈x⌉ := by rw [← neg_inj, ← floor_neg, ← floor_neg, ← Rat.cast_neg, Rat.floor_cast] @[simp, norm_cast] theorem round_cast (x : ℚ) : round (x : α) = round x := by have : ((x + 1 / 2 : ℚ) : α) = x + 1 / 2 := by simp rw [round_eq, round_eq, ← this, floor_cast] @[simp, norm_cast] theorem cast_fract (x : ℚ) : (↑(fract x) : α) = fract (x : α) := by simp only [fract, cast_sub, cast_intCast, floor_cast] section NormNum open Mathlib.Meta.NormNum Qq theorem isNat_intFloor {R} [LinearOrderedRing R] [FloorRing R] (r : R) (m : ℕ) : IsNat r m → IsNat ⌊r⌋ m := by rintro ⟨⟨⟩⟩; exact ⟨by simp⟩ theorem isInt_intFloor {R} [LinearOrderedRing R] [FloorRing R] (r : R) (m : ℤ) : IsInt r m → IsInt ⌊r⌋ m := by rintro ⟨⟨⟩⟩; exact ⟨by simp⟩ theorem isInt_intFloor_ofIsRat (r : α) (n : ℤ) (d : ℕ) : IsRat r n d → IsInt ⌊r⌋ (n / d) := by rintro ⟨inv, rfl⟩ constructor simp only [invOf_eq_inv, ← div_eq_mul_inv, Int.cast_id] rw [← floor_int_div_nat_eq_div n d, ← floor_cast (α := α), Rat.cast_div, cast_intCast, cast_natCast] /-- `norm_num` extension for `Int.floor` -/ @[norm_num ⌊_⌋] def evalIntFloor : NormNumExt where eval {u αZ} e := do match u, αZ, e with | 0, ~q(ℤ), ~q(@Int.floor $α $instR $instF $x) => match ← derive x with | .isBool .. => failure | .isNat sα nb pb => do assertInstancesCommute return .isNat q(inferInstance) _ q(isNat_intFloor $x _ $pb) | .isNegNat sα nb pb => do assertInstancesCommute -- floor always keeps naturals negative, so we can shortcut `.isInt` return .isNegNat q(inferInstance) _ q(isInt_intFloor _ _ $pb) | .isRat dα q n d h => do let _i ← synthInstanceQ q(LinearOrderedField $α) assertInstancesCommute have z : Q(ℤ) := mkRawIntLit ⌊q⌋ letI : $z =Q ⌊$n / $d⌋ := ⟨⟩ return .isInt q(inferInstance) z ⌊q⌋ q(isInt_intFloor_ofIsRat _ $n $d $h) | _, _, _ => failure end NormNum end Rat theorem Int.mod_nat_eq_sub_mul_floor_rat_div {n : ℤ} {d : ℕ} : n % d = n - d * ⌊(n : ℚ) / d⌋ := by rw [eq_sub_of_add_eq <| Int.emod_add_ediv n d, Rat.floor_int_div_nat_eq_div] theorem Nat.coprime_sub_mul_floor_rat_div_of_coprime {n d : ℕ} (n_coprime_d : n.Coprime d) : ((n : ℤ) - d * ⌊(n : ℚ) / d⌋).natAbs.Coprime d := by have : (n : ℤ) % d = n - d * ⌊(n : ℚ) / d⌋ := Int.mod_nat_eq_sub_mul_floor_rat_div rw [← this] have : d.Coprime n := n_coprime_d.symm rwa [Nat.Coprime, Nat.gcd_rec] at this namespace Rat theorem num_lt_succ_floor_mul_den (q : ℚ) : q.num < (⌊q⌋ + 1) * q.den := by suffices (q.num : ℚ) < (⌊q⌋ + 1) * q.den from mod_cast this suffices (q.num : ℚ) < (q - fract q + 1) * q.den by have : (⌊q⌋ : ℚ) = q - fract q := eq_sub_of_add_eq <| floor_add_fract q rwa [this] suffices (q.num : ℚ) < q.num + (1 - fract q) * q.den by have : (q - fract q + 1) * q.den = q.num + (1 - fract q) * q.den := by calc (q - fract q + 1) * q.den = (q + (1 - fract q)) * q.den := by ring _ = q * q.den + (1 - fract q) * q.den := by rw [add_mul] _ = q.num + (1 - fract q) * q.den := by simp rwa [this] suffices 0 < (1 - fract q) * q.den by rw [← sub_lt_iff_lt_add'] simpa have : 0 < 1 - fract q := by have : fract q < 1 := fract_lt_one q have : 0 + fract q < 1 := by simp [this] rwa [lt_sub_iff_add_lt] exact mul_pos this (by exact mod_cast q.pos) theorem fract_inv_num_lt_num_of_pos {q : ℚ} (q_pos : 0 < q) : (fract q⁻¹).num < q.num := by -- we know that the numerator must be positive have q_num_pos : 0 < q.num := Rat.num_pos.mpr q_pos -- we will work with the absolute value of the numerator, which is equal to the numerator have q_num_abs_eq_q_num : (q.num.natAbs : ℤ) = q.num := Int.natAbs_of_nonneg q_num_pos.le set q_inv : ℚ := q.den / q.num with q_inv_def have q_inv_eq : q⁻¹ = q_inv := by rw [q_inv_def, inv_def', divInt_eq_div, Int.cast_natCast] suffices (q_inv - ⌊q_inv⌋).num < q.num by rwa [q_inv_eq] suffices ((q.den - q.num * ⌊q_inv⌋ : ℚ) / q.num).num < q.num by field_simp [q_inv, this, ne_of_gt q_num_pos] suffices (q.den : ℤ) - q.num * ⌊q_inv⌋ < q.num by -- use that `q.num` and `q.den` are coprime to show that the numerator stays unreduced have : ((q.den - q.num * ⌊q_inv⌋ : ℚ) / q.num).num = q.den - q.num * ⌊q_inv⌋ := by suffices ((q.den : ℤ) - q.num * ⌊q_inv⌋).natAbs.Coprime q.num.natAbs from mod_cast Rat.num_div_eq_of_coprime q_num_pos this have tmp := Nat.coprime_sub_mul_floor_rat_div_of_coprime q.reduced.symm simpa only [Nat.cast_natAbs, abs_of_nonneg q_num_pos.le] using tmp rwa [this] -- to show the claim, start with the following inequality have q_inv_num_denom_ineq : q⁻¹.num - ⌊q⁻¹⌋ * q⁻¹.den < q⁻¹.den := by have : q⁻¹.num < (⌊q⁻¹⌋ + 1) * q⁻¹.den := Rat.num_lt_succ_floor_mul_den q⁻¹ have : q⁻¹.num < ⌊q⁻¹⌋ * q⁻¹.den + q⁻¹.den := by rwa [right_distrib, one_mul] at this rwa [← sub_lt_iff_lt_add'] at this -- use that `q.num` and `q.den` are coprime to show that q_inv is the unreduced reciprocal -- of `q` have : q_inv.num = q.den ∧ q_inv.den = q.num.natAbs := by have coprime_q_denom_q_num : q.den.Coprime q.num.natAbs := q.reduced.symm have : Int.natAbs q.den = q.den := by simp rw [← this] at coprime_q_denom_q_num rw [q_inv_def] constructor · exact mod_cast Rat.num_div_eq_of_coprime q_num_pos coprime_q_denom_q_num · suffices (((q.den : ℚ) / q.num).den : ℤ) = q.num.natAbs by exact mod_cast this rw [q_num_abs_eq_q_num] exact mod_cast Rat.den_div_eq_of_coprime q_num_pos coprime_q_denom_q_num rwa [q_inv_eq, this.left, this.right, q_num_abs_eq_q_num, mul_comm] at q_inv_num_denom_ineq end Rat
Data\Rat\Init.lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Yaël Dillies -/ import Mathlib.Data.Nat.Notation import Mathlib.Tactic.Lemma import Mathlib.Tactic.ProjectionNotation import Mathlib.Tactic.TypeStar import Batteries.Classes.RatCast /-! # Basic definitions around the rational numbers This file declares `ℚ` notation for the rationals and defines the nonnegative rationals `ℚ≥0`. This file is eligible to upstreaming to Batteries. -/ @[inherit_doc] notation "ℚ" => Rat /-- Nonnegative rational numbers. -/ def NNRat := {q : ℚ // 0 ≤ q} @[inherit_doc] notation "ℚ≥0" => NNRat /-! ### Cast from `NNRat` This section sets up the typeclasses necessary to declare the canonical embedding `ℚ≥0` to any semifield. -/ /-- Typeclass for the canonical homomorphism `ℚ≥0 → K`. This should be considered as a notation typeclass. The sole purpose of this typeclass is to be extended by `DivisionSemiring`. -/ class NNRatCast (K : Type*) where /-- The canonical homomorphism `ℚ≥0 → K`. Do not use directly. Use the coercion instead. -/ protected nnratCast : ℚ≥0 → K instance NNRat.instNNRatCast : NNRatCast ℚ≥0 where nnratCast q := q variable {K : Type*} [NNRatCast K] /-- Canonical homomorphism from `ℚ≥0` to a division semiring `K`. This is just the bare function in order to aid in creating instances of `DivisionSemiring`. -/ @[coe, reducible, match_pattern] protected def NNRat.cast : ℚ≥0 → K := NNRatCast.nnratCast -- See note [coercion into rings] instance NNRatCast.toCoeTail [NNRatCast K] : CoeTail ℚ≥0 K where coe := NNRat.cast -- See note [coercion into rings] instance NNRatCast.toCoeHTCT [NNRatCast K] : CoeHTCT ℚ≥0 K where coe := NNRat.cast instance Rat.instNNRatCast : NNRatCast ℚ := ⟨Subtype.val⟩ /-! ### Numerator and denominator of a nonnegative rational -/ namespace NNRat /-- The numerator of a nonnegative rational. -/ def num (q : ℚ≥0) : ℕ := (q : ℚ).num.natAbs /-- The denominator of a nonnegative rational. -/ def den (q : ℚ≥0) : ℕ := (q : ℚ).den @[simp] lemma num_mk (q : ℚ) (hq : 0 ≤ q) : num ⟨q, hq⟩ = q.num.natAbs := rfl @[simp] lemma den_mk (q : ℚ) (hq : 0 ≤ q) : den ⟨q, hq⟩ = q.den := rfl @[norm_cast] lemma cast_id (n : ℚ≥0) : NNRat.cast n = n := rfl @[simp] lemma cast_eq_id : NNRat.cast = id := rfl end NNRat namespace Rat @[norm_cast] lemma cast_id (n : ℚ) : Rat.cast n = n := rfl @[simp] lemma cast_eq_id : Rat.cast = id := rfl end Rat
Data\Rat\Lemmas.lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import Mathlib.Algebra.GroupWithZero.Divisibility import Mathlib.Algebra.Ring.Rat import Mathlib.Data.PNat.Defs /-! # Further lemmas for the Rational Numbers -/ namespace Rat open Rat theorem num_dvd (a) {b : ℤ} (b0 : b ≠ 0) : (a /. b).num ∣ a := by cases' e : a /. b with n d h c rw [Rat.mk'_eq_divInt, divInt_eq_iff b0 (mod_cast h)] at e refine Int.natAbs_dvd.1 <| Int.dvd_natAbs.1 <| Int.natCast_dvd_natCast.2 <| c.dvd_of_dvd_mul_right ?_ have := congr_arg Int.natAbs e simp only [Int.natAbs_mul, Int.natAbs_ofNat] at this; simp [this] theorem den_dvd (a b : ℤ) : ((a /. b).den : ℤ) ∣ b := by by_cases b0 : b = 0; · simp [b0] cases' e : a /. b with n d h c rw [mk'_eq_divInt, divInt_eq_iff b0 (ne_of_gt (Int.natCast_pos.2 (Nat.pos_of_ne_zero h)))] at e refine Int.dvd_natAbs.1 <| Int.natCast_dvd_natCast.2 <| c.symm.dvd_of_dvd_mul_left ?_ rw [← Int.natAbs_mul, ← Int.natCast_dvd_natCast, Int.dvd_natAbs, ← e]; simp theorem num_den_mk {q : ℚ} {n d : ℤ} (hd : d ≠ 0) (qdf : q = n /. d) : ∃ c : ℤ, n = c * q.num ∧ d = c * q.den := by obtain rfl | hn := eq_or_ne n 0 · simp [qdf] have : q.num * d = n * ↑q.den := by refine (divInt_eq_iff ?_ hd).mp ?_ · exact Int.natCast_ne_zero.mpr (Rat.den_nz _) · rwa [num_divInt_den] have hqdn : q.num ∣ n := by rw [qdf] exact Rat.num_dvd _ hd refine ⟨n / q.num, ?_, ?_⟩ · rw [Int.ediv_mul_cancel hqdn] · refine Int.eq_mul_div_of_mul_eq_mul_of_dvd_left ?_ hqdn this rw [qdf] exact Rat.num_ne_zero.2 ((divInt_ne_zero hd).mpr hn) theorem num_mk (n d : ℤ) : (n /. d).num = d.sign * n / n.gcd d := by have (m : ℕ) : Int.natAbs (m + 1) = m + 1 := by rw [← Nat.cast_one, ← Nat.cast_add, Int.natAbs_cast] rcases d with ((_ | _) | _) <;> rw [← Int.div_eq_ediv_of_dvd] <;> simp [divInt, mkRat, Rat.normalize, Nat.succPNat, Int.sign, Int.gcd, Int.zero_ediv, Int.ofNat_dvd_left, Nat.gcd_dvd_left, this] theorem den_mk (n d : ℤ) : (n /. d).den = if d = 0 then 1 else d.natAbs / n.gcd d := by have (m : ℕ) : Int.natAbs (m + 1) = m + 1 := by rw [← Nat.cast_one, ← Nat.cast_add, Int.natAbs_cast] rcases d with ((_ | _) | _) <;> simp [divInt, mkRat, Rat.normalize, Nat.succPNat, Int.sign, Int.gcd, if_neg (Nat.cast_add_one_ne_zero _), this] theorem add_den_dvd (q₁ q₂ : ℚ) : (q₁ + q₂).den ∣ q₁.den * q₂.den := by rw [add_def, normalize_eq] apply Nat.div_dvd_of_dvd apply Nat.gcd_dvd_right theorem mul_den_dvd (q₁ q₂ : ℚ) : (q₁ * q₂).den ∣ q₁.den * q₂.den := by rw [mul_def, normalize_eq] apply Nat.div_dvd_of_dvd apply Nat.gcd_dvd_right theorem mul_num (q₁ q₂ : ℚ) : (q₁ * q₂).num = q₁.num * q₂.num / Nat.gcd (q₁.num * q₂.num).natAbs (q₁.den * q₂.den) := by rw [mul_def, normalize_eq] theorem mul_den (q₁ q₂ : ℚ) : (q₁ * q₂).den = q₁.den * q₂.den / Nat.gcd (q₁.num * q₂.num).natAbs (q₁.den * q₂.den) := by rw [mul_def, normalize_eq] theorem mul_self_num (q : ℚ) : (q * q).num = q.num * q.num := by rw [mul_num, Int.natAbs_mul, Nat.Coprime.gcd_eq_one, Int.ofNat_one, Int.ediv_one] exact (q.reduced.mul_right q.reduced).mul (q.reduced.mul_right q.reduced) theorem mul_self_den (q : ℚ) : (q * q).den = q.den * q.den := by rw [Rat.mul_den, Int.natAbs_mul, Nat.Coprime.gcd_eq_one, Nat.div_one] exact (q.reduced.mul_right q.reduced).mul (q.reduced.mul_right q.reduced) theorem add_num_den (q r : ℚ) : q + r = (q.num * r.den + q.den * r.num : ℤ) /. (↑q.den * ↑r.den : ℤ) := by have hqd : (q.den : ℤ) ≠ 0 := Int.natCast_ne_zero_iff_pos.2 q.den_pos have hrd : (r.den : ℤ) ≠ 0 := Int.natCast_ne_zero_iff_pos.2 r.den_pos conv_lhs => rw [← num_divInt_den q, ← num_divInt_den r, divInt_add_divInt _ _ hqd hrd] rw [mul_comm r.num q.den] theorem isSquare_iff {q : ℚ} : IsSquare q ↔ IsSquare q.num ∧ IsSquare q.den := by constructor · rintro ⟨qr, rfl⟩ rw [Rat.mul_self_num, mul_self_den] simp only [isSquare_mul_self, and_self] · rintro ⟨⟨nr, hnr⟩, ⟨dr, hdr⟩⟩ refine ⟨nr / dr, ?_⟩ rw [div_mul_div_comm, ← Int.cast_mul, ← Nat.cast_mul, ← hnr, ← hdr, num_div_den] @[norm_cast, simp] theorem isSquare_natCast_iff {n : ℕ} : IsSquare (n : ℚ) ↔ IsSquare n := by simp_rw [isSquare_iff, num_natCast, den_natCast, isSquare_one, and_true, Int.isSquare_natCast_iff] @[norm_cast, simp] theorem isSquare_intCast_iff {z : ℤ} : IsSquare (z : ℚ) ↔ IsSquare z := by simp_rw [isSquare_iff, intCast_num, intCast_den, isSquare_one, and_true] -- See note [no_index around OfNat.ofNat] @[simp] theorem isSquare_ofNat_iff {n : ℕ} : IsSquare (no_index (OfNat.ofNat n) : ℚ) ↔ IsSquare (OfNat.ofNat n : ℕ) := isSquare_natCast_iff section Casts theorem exists_eq_mul_div_num_and_eq_mul_div_den (n : ℤ) {d : ℤ} (d_ne_zero : d ≠ 0) : ∃ c : ℤ, n = c * ((n : ℚ) / d).num ∧ (d : ℤ) = c * ((n : ℚ) / d).den := haveI : (n : ℚ) / d = Rat.divInt n d := by rw [← Rat.divInt_eq_div] Rat.num_den_mk d_ne_zero this theorem mul_num_den' (q r : ℚ) : (q * r).num * q.den * r.den = q.num * r.num * (q * r).den := by let s := q.num * r.num /. (q.den * r.den : ℤ) have hs : (q.den * r.den : ℤ) ≠ 0 := Int.natCast_ne_zero_iff_pos.mpr (Nat.mul_pos q.pos r.pos) obtain ⟨c, ⟨c_mul_num, c_mul_den⟩⟩ := exists_eq_mul_div_num_and_eq_mul_div_den (q.num * r.num) hs rw [c_mul_num, mul_assoc, mul_comm] nth_rw 1 [c_mul_den] rw [Int.mul_assoc, Int.mul_assoc, mul_eq_mul_left_iff, or_iff_not_imp_right] intro have h : _ = s := divInt_mul_divInt q.num r.num (mod_cast q.den_ne_zero) (mod_cast r.den_ne_zero) rw [num_divInt_den, num_divInt_den] at h rw [h, mul_comm, ← Rat.eq_iff_mul_eq_mul, ← divInt_eq_div] theorem add_num_den' (q r : ℚ) : (q + r).num * q.den * r.den = (q.num * r.den + r.num * q.den) * (q + r).den := by let s := divInt (q.num * r.den + r.num * q.den) (q.den * r.den : ℤ) have hs : (q.den * r.den : ℤ) ≠ 0 := Int.natCast_ne_zero_iff_pos.mpr (Nat.mul_pos q.pos r.pos) obtain ⟨c, ⟨c_mul_num, c_mul_den⟩⟩ := exists_eq_mul_div_num_and_eq_mul_div_den (q.num * r.den + r.num * q.den) hs rw [c_mul_num, mul_assoc, mul_comm] nth_rw 1 [c_mul_den] repeat rw [Int.mul_assoc] apply mul_eq_mul_left_iff.2 rw [or_iff_not_imp_right] intro have h : _ = s := divInt_add_divInt q.num r.num (mod_cast q.den_ne_zero) (mod_cast r.den_ne_zero) rw [num_divInt_den, num_divInt_den] at h rw [h] rw [mul_comm] apply Rat.eq_iff_mul_eq_mul.mp rw [← divInt_eq_div] theorem substr_num_den' (q r : ℚ) : (q - r).num * q.den * r.den = (q.num * r.den - r.num * q.den) * (q - r).den := by rw [sub_eq_add_neg, sub_eq_add_neg, ← neg_mul, ← num_neg_eq_neg_num, ← den_neg_eq_den r, add_num_den' q (-r)] end Casts protected theorem inv_neg (q : ℚ) : (-q)⁻¹ = -q⁻¹ := by rw [← num_divInt_den q] simp only [Rat.neg_divInt, Rat.inv_divInt', eq_self_iff_true, Rat.divInt_neg] theorem num_div_eq_of_coprime {a b : ℤ} (hb0 : 0 < b) (h : Nat.Coprime a.natAbs b.natAbs) : (a / b : ℚ).num = a := by -- Porting note: was `lift b to ℕ using le_of_lt hb0` rw [← Int.natAbs_of_nonneg hb0.le, ← Rat.divInt_eq_div, ← mk_eq_divInt _ _ (Int.natAbs_ne_zero.mpr hb0.ne') h] theorem den_div_eq_of_coprime {a b : ℤ} (hb0 : 0 < b) (h : Nat.Coprime a.natAbs b.natAbs) : ((a / b : ℚ).den : ℤ) = b := by -- Porting note: was `lift b to ℕ using le_of_lt hb0` rw [← Int.natAbs_of_nonneg hb0.le, ← Rat.divInt_eq_div, ← mk_eq_divInt _ _ (Int.natAbs_ne_zero.mpr hb0.ne') h] theorem div_int_inj {a b c d : ℤ} (hb0 : 0 < b) (hd0 : 0 < d) (h1 : Nat.Coprime a.natAbs b.natAbs) (h2 : Nat.Coprime c.natAbs d.natAbs) (h : (a : ℚ) / b = (c : ℚ) / d) : a = c ∧ b = d := by apply And.intro · rw [← num_div_eq_of_coprime hb0 h1, h, num_div_eq_of_coprime hd0 h2] · rw [← den_div_eq_of_coprime hb0 h1, h, den_div_eq_of_coprime hd0 h2] @[norm_cast] theorem intCast_div_self (n : ℤ) : ((n / n : ℤ) : ℚ) = n / n := by by_cases hn : n = 0 · subst hn simp only [Int.cast_zero, Int.zero_div, zero_div, Int.ediv_zero] · have : (n : ℚ) ≠ 0 := by rwa [← coe_int_inj] at hn simp only [Int.ediv_self hn, Int.cast_one, Ne, not_false_iff, div_self this] @[norm_cast] theorem natCast_div_self (n : ℕ) : ((n / n : ℕ) : ℚ) = n / n := intCast_div_self n theorem intCast_div (a b : ℤ) (h : b ∣ a) : ((a / b : ℤ) : ℚ) = a / b := by rcases h with ⟨c, rfl⟩ rw [mul_comm b, Int.mul_ediv_assoc c (dvd_refl b), Int.cast_mul, intCast_div_self, Int.cast_mul, mul_div_assoc] theorem natCast_div (a b : ℕ) (h : b ∣ a) : ((a / b : ℕ) : ℚ) = a / b := intCast_div a b (Int.ofNat_dvd.mpr h) theorem den_div_intCast_eq_one_iff (m n : ℤ) (hn : n ≠ 0) : ((m : ℚ) / n).den = 1 ↔ n ∣ m := by replace hn : (n : ℚ) ≠ 0 := num_ne_zero.mp hn constructor · rw [Rat.den_eq_one_iff, eq_div_iff hn] exact mod_cast (Dvd.intro_left _) · exact (intCast_div _ _ · ▸ rfl) theorem den_div_natCast_eq_one_iff (m n : ℕ) (hn : n ≠ 0) : ((m : ℚ) / n).den = 1 ↔ n ∣ m := (den_div_intCast_eq_one_iff m n (Int.ofNat_ne_zero.mpr hn)).trans Int.ofNat_dvd @[deprecated (since := "2024-05-11")] alias den_div_cast_eq_one_iff := den_div_intCast_eq_one_iff theorem inv_intCast_num_of_pos {a : ℤ} (ha0 : 0 < a) : (a : ℚ)⁻¹.num = 1 := by rw [← ofInt_eq_cast, ofInt, mk_eq_divInt, Rat.inv_divInt', divInt_eq_div, Nat.cast_one] apply num_div_eq_of_coprime ha0 rw [Int.natAbs_one] exact Nat.coprime_one_left _ theorem inv_natCast_num_of_pos {a : ℕ} (ha0 : 0 < a) : (a : ℚ)⁻¹.num = 1 := inv_intCast_num_of_pos (mod_cast ha0 : 0 < (a : ℤ)) theorem inv_intCast_den_of_pos {a : ℤ} (ha0 : 0 < a) : ((a : ℚ)⁻¹.den : ℤ) = a := by rw [← ofInt_eq_cast, ofInt, mk_eq_divInt, Rat.inv_divInt', divInt_eq_div, Nat.cast_one] apply den_div_eq_of_coprime ha0 rw [Int.natAbs_one] exact Nat.coprime_one_left _ theorem inv_natCast_den_of_pos {a : ℕ} (ha0 : 0 < a) : (a : ℚ)⁻¹.den = a := by rw [← Int.ofNat_inj, ← Int.cast_natCast a, inv_intCast_den_of_pos] rwa [Int.natCast_pos] @[simp] theorem inv_intCast_num (a : ℤ) : (a : ℚ)⁻¹.num = Int.sign a := by rcases lt_trichotomy a 0 with lt | rfl | gt · obtain ⟨a, rfl⟩ : ∃ b, -b = a := ⟨-a, a.neg_neg⟩ simp at lt simp [Rat.inv_neg, inv_intCast_num_of_pos lt, (Int.sign_eq_one_iff_pos _).mpr lt] · rfl · simp [inv_intCast_num_of_pos gt, (Int.sign_eq_one_iff_pos _).mpr gt] @[simp] theorem inv_natCast_num (a : ℕ) : (a : ℚ)⁻¹.num = Int.sign a := inv_intCast_num a @[simp] theorem inv_ofNat_num (a : ℕ) [a.AtLeastTwo] : (no_index (OfNat.ofNat a : ℚ))⁻¹.num = 1 := inv_natCast_num_of_pos (Nat.pos_of_neZero a) @[simp] theorem inv_intCast_den (a : ℤ) : (a : ℚ)⁻¹.den = if a = 0 then 1 else a.natAbs := by rw [← Int.ofNat_inj] rcases lt_trichotomy a 0 with lt | rfl | gt · obtain ⟨a, rfl⟩ : ∃ b, -b = a := ⟨-a, a.neg_neg⟩ simp at lt rw [if_neg (by omega)] simp only [Int.cast_neg, Rat.inv_neg, neg_den, inv_intCast_den_of_pos lt, Int.natAbs_neg] exact Int.eq_natAbs_of_zero_le (by omega) · rfl · rw [if_neg (by omega)] simp only [inv_intCast_den_of_pos gt] exact Int.eq_natAbs_of_zero_le (by omega) @[simp] theorem inv_natCast_den (a : ℕ) : (a : ℚ)⁻¹.den = if a = 0 then 1 else a := by simpa [-inv_intCast_den, ofInt_eq_cast] using inv_intCast_den a @[deprecated (since := "2024-04-05")] alias coe_int_div_self := intCast_div_self @[deprecated (since := "2024-04-05")] alias coe_nat_div_self := natCast_div_self @[deprecated (since := "2024-04-05")] alias coe_int_div := intCast_div @[deprecated (since := "2024-04-05")] alias coe_nat_div := natCast_div @[deprecated (since := "2024-04-05")] alias inv_coe_int_num_of_pos := inv_intCast_num_of_pos @[deprecated (since := "2024-04-05")] alias inv_coe_nat_num_of_pos := inv_natCast_num_of_pos @[deprecated (since := "2024-04-05")] alias inv_coe_int_den_of_pos := inv_intCast_den_of_pos @[deprecated (since := "2024-04-05")] alias inv_coe_nat_den_of_pos := inv_natCast_den_of_pos @[deprecated (since := "2024-04-05")] alias inv_coe_int_num := inv_intCast_num @[deprecated (since := "2024-04-05")] alias inv_coe_nat_num := inv_natCast_num @[deprecated (since := "2024-04-05")] alias inv_coe_int_den := inv_intCast_den @[deprecated (since := "2024-04-05")] alias inv_coe_nat_den := inv_natCast_den @[simp] theorem inv_ofNat_den (a : ℕ) [a.AtLeastTwo] : (no_index (OfNat.ofNat a : ℚ))⁻¹.den = OfNat.ofNat a := inv_natCast_den_of_pos (Nat.pos_of_neZero a) protected theorem «forall» {p : ℚ → Prop} : (∀ r, p r) ↔ ∀ a b : ℤ, p (a / b) := ⟨fun h _ _ => h _, fun h q => by have := h q.num q.den rwa [Int.cast_natCast, num_div_den q] at this⟩ protected theorem «exists» {p : ℚ → Prop} : (∃ r, p r) ↔ ∃ a b : ℤ, p (a / b) := ⟨fun ⟨r, hr⟩ => ⟨r.num, r.den, by convert hr; convert num_div_den r⟩, fun ⟨a, b, h⟩ => ⟨_, h⟩⟩ /-! ### Denominator as `ℕ+` -/ section PNatDen /-- Denominator as `ℕ+`. -/ def pnatDen (x : ℚ) : ℕ+ := ⟨x.den, x.pos⟩ @[simp] theorem coe_pnatDen (x : ℚ) : (x.pnatDen : ℕ) = x.den := rfl theorem pnatDen_eq_iff_den_eq {x : ℚ} {n : ℕ+} : x.pnatDen = n ↔ x.den = ↑n := Subtype.ext_iff @[simp] theorem pnatDen_one : (1 : ℚ).pnatDen = 1 := rfl @[simp] theorem pnatDen_zero : (0 : ℚ).pnatDen = 1 := rfl end PNatDen end Rat
Data\Rat\Sqrt.lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import Mathlib.Algebra.Order.Ring.Abs import Mathlib.Algebra.Order.Ring.Rat import Mathlib.Data.Rat.Lemmas import Mathlib.Data.Int.Sqrt /-! # Square root on rational numbers This file defines the square root function on rational numbers `Rat.sqrt` and proves several theorems about it. -/ namespace Rat /-- Square root function on rational numbers, defined by taking the (integer) square root of the numerator and the square root (on natural numbers) of the denominator. -/ @[pp_nodot] def sqrt (q : ℚ) : ℚ := mkRat (Int.sqrt q.num) (Nat.sqrt q.den) theorem sqrt_eq (q : ℚ) : Rat.sqrt (q * q) = |q| := by rw [sqrt, mul_self_num, mul_self_den, Int.sqrt_eq, Nat.sqrt_eq, abs_def, divInt_ofNat] theorem exists_mul_self (x : ℚ) : (∃ q, q * q = x) ↔ Rat.sqrt x * Rat.sqrt x = x := ⟨fun ⟨n, hn⟩ => by rw [← hn, sqrt_eq, abs_mul_abs_self], fun h => ⟨Rat.sqrt x, h⟩⟩ lemma sqrt_nonneg (q : ℚ) : 0 ≤ Rat.sqrt q := mkRat_nonneg (Int.sqrt_nonneg _) _ /-- `IsSquare` can be decided on `ℚ` by checking against the square root. -/ instance : DecidablePred (IsSquare : ℚ → Prop) := fun m => decidable_of_iff' (sqrt m * sqrt m = m) <| by simp_rw [← exists_mul_self m, IsSquare, eq_comm] @[simp, norm_cast] theorem sqrt_intCast (z : ℤ) : Rat.sqrt (z : ℚ) = Int.sqrt z := by simp only [sqrt, num_intCast, den_intCast, Nat.sqrt_one, mkRat_one] @[simp, norm_cast] theorem sqrt_natCast (n : ℕ) : Rat.sqrt (n : ℚ) = Nat.sqrt n := by rw [← Int.cast_natCast, sqrt_intCast, Int.sqrt_natCast, Int.cast_natCast] -- See note [no_index around OfNat.ofNat] @[simp] theorem sqrt_ofNat (n : ℕ) : Rat.sqrt (no_index (OfNat.ofNat n) : ℚ) = Nat.sqrt (OfNat.ofNat n) := sqrt_natCast _ end Rat
Data\Rat\Star.lean
/- Copyright (c) 2023 Jireh Loreaux. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jireh Loreaux, Yaël Dillies -/ import Mathlib.Algebra.GroupWithZero.Commute import Mathlib.Algebra.Order.Ring.Abs import Mathlib.Algebra.Star.Order import Mathlib.Data.NNRat.Lemmas import Mathlib.Algebra.Order.Monoid.Submonoid import Mathlib.Tactic.FieldSimp /-! # Star ordered ring structures on `ℚ` and `ℚ≥0` This file shows that `ℚ` and `ℚ≥0` are `StarOrderedRing`s. In particular, this means that every nonnegative rational number is a sum of squares. -/ open AddSubmonoid Set open scoped NNRat namespace NNRat @[simp] lemma addSubmonoid_closure_range_pow {n : ℕ} (hn₀ : n ≠ 0) : closure (range fun x : ℚ≥0 ↦ x ^ n) = ⊤ := by refine (eq_top_iff' _).2 fun x ↦ ?_ suffices x = (x.num * x.den ^ (n - 1)) • (x.den : ℚ≥0)⁻¹ ^ n by rw [this] exact nsmul_mem (subset_closure <| mem_range_self _) _ rw [nsmul_eq_mul] push_cast rw [mul_assoc, pow_sub₀, pow_one, mul_right_comm, ← mul_pow, mul_inv_cancel, one_pow, one_mul, ← div_eq_mul_inv, num_div_den] all_goals simp [x.den_pos.ne', Nat.one_le_iff_ne_zero, *] @[simp] lemma addSubmonoid_closure_range_mul_self : closure (range fun x : ℚ≥0 ↦ x * x) = ⊤ := by simpa only [sq] using addSubmonoid_closure_range_pow two_ne_zero instance instStarOrderedRing : StarOrderedRing ℚ≥0 where le_iff a b := by simp [le_iff_exists_nonneg_add a b] end NNRat namespace Rat @[simp] lemma addSubmonoid_closure_range_pow {n : ℕ} (hn₀ : n ≠ 0) (hn : Even n) : closure (range fun x : ℚ ↦ x ^ n) = nonneg _ := by convert (AddMonoidHom.map_mclosure NNRat.coeHom <| range fun x ↦ x ^ n).symm · have (x : ℚ) : ∃ y : ℚ≥0, y ^ n = x ^ n := ⟨x.nnabs, by simp [hn.pow_abs]⟩ simp [subset_antisymm_iff, range_subset_iff, this] · ext simp [NNRat.addSubmonoid_closure_range_pow hn₀, NNRat.exists] @[simp] lemma addSubmonoid_closure_range_mul_self : closure (range fun x : ℚ ↦ x * x) = nonneg _ := by simpa only [sq] using addSubmonoid_closure_range_pow two_ne_zero even_two instance instStarOrderedRing : StarOrderedRing ℚ where le_iff a b := by simp [le_iff_exists_nonneg_add a b] end Rat
Data\Rat\Cast\CharZero.lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import Mathlib.Algebra.GroupWithZero.Units.Lemmas import Mathlib.Data.Rat.Cast.Defs /-! # Casts of rational numbers into characteristic zero fields (or division rings). -/ variable {F ι α β : Type*} namespace Rat open Rat section WithDivRing variable [DivisionRing α] @[simp, norm_cast] theorem cast_inj [CharZero α] : ∀ {m n : ℚ}, (m : α) = n ↔ m = n | ⟨n₁, d₁, d₁0, c₁⟩, ⟨n₂, d₂, d₂0, c₂⟩ => by refine ⟨fun h => ?_, congr_arg _⟩ have d₁a : (d₁ : α) ≠ 0 := Nat.cast_ne_zero.2 d₁0 have d₂a : (d₂ : α) ≠ 0 := Nat.cast_ne_zero.2 d₂0 rw [mk'_eq_divInt, mk'_eq_divInt] at h ⊢ rw [cast_divInt_of_ne_zero, cast_divInt_of_ne_zero] at h <;> simp [d₁0, d₂0] at h ⊢ rwa [eq_div_iff_mul_eq d₂a, division_def, mul_assoc, (d₁.cast_commute (d₂ : α)).inv_left₀.eq, ← mul_assoc, ← division_def, eq_comm, eq_div_iff_mul_eq d₁a, eq_comm, ← Int.cast_natCast d₁, ← Int.cast_mul, ← Int.cast_natCast d₂, ← Int.cast_mul, Int.cast_inj, ← mkRat_eq_iff d₁0 d₂0] at h theorem cast_injective [CharZero α] : Function.Injective ((↑) : ℚ → α) | _, _ => cast_inj.1 @[simp] theorem cast_eq_zero [CharZero α] {n : ℚ} : (n : α) = 0 ↔ n = 0 := by rw [← cast_zero, cast_inj] theorem cast_ne_zero [CharZero α] {n : ℚ} : (n : α) ≠ 0 ↔ n ≠ 0 := not_congr cast_eq_zero @[simp, norm_cast] theorem cast_add [CharZero α] (m n) : ((m + n : ℚ) : α) = m + n := cast_add_of_ne_zero (Nat.cast_ne_zero.2 <| ne_of_gt m.pos) (Nat.cast_ne_zero.2 <| ne_of_gt n.pos) @[simp, norm_cast] theorem cast_sub [CharZero α] (m n) : ((m - n : ℚ) : α) = m - n := cast_sub_of_ne_zero (Nat.cast_ne_zero.2 <| ne_of_gt m.pos) (Nat.cast_ne_zero.2 <| ne_of_gt n.pos) @[simp, norm_cast] theorem cast_mul [CharZero α] (m n) : ((m * n : ℚ) : α) = m * n := cast_mul_of_ne_zero (Nat.cast_ne_zero.2 <| ne_of_gt m.pos) (Nat.cast_ne_zero.2 <| ne_of_gt n.pos) variable (α) variable [CharZero α] /-- Coercion `ℚ → α` as a `RingHom`. -/ def castHom : ℚ →+* α where toFun := (↑) map_one' := cast_one map_mul' := cast_mul map_zero' := cast_zero map_add' := cast_add variable {α} @[simp] theorem coe_cast_hom : ⇑(castHom α) = ((↑) : ℚ → α) := rfl @[simp, norm_cast] theorem cast_inv (n) : ((n⁻¹ : ℚ) : α) = (n : α)⁻¹ := map_inv₀ (castHom α) _ @[simp, norm_cast] theorem cast_div (m n) : ((m / n : ℚ) : α) = m / n := map_div₀ (castHom α) _ _ @[simp, norm_cast] theorem cast_zpow (q : ℚ) (n : ℤ) : ((q ^ n : ℚ) : α) = (q : α) ^ n := map_zpow₀ (castHom α) q n @[norm_cast] theorem cast_mk (a b : ℤ) : (a /. b : α) = a / b := by simp only [divInt_eq_div, cast_div, cast_intCast] @[simp, norm_cast] theorem cast_pow (q : ℚ) (k : ℕ) : ↑(q ^ k) = (q : α) ^ k := (castHom α).map_pow q k end WithDivRing end Rat
Data\Rat\Cast\Defs.lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import Mathlib.Algebra.Field.Rat import Mathlib.Algebra.Group.Commute.Basic import Mathlib.Algebra.GroupWithZero.Units.Lemmas import Mathlib.Algebra.Order.Field.Rat import Mathlib.Data.Int.Cast.Lemmas import Mathlib.Data.Rat.Lemmas /-! # Casts for Rational Numbers ## Summary We define the canonical injection from ℚ into an arbitrary division ring and prove various casting lemmas showing the well-behavedness of this injection. ## Notations - `/.` is infix notation for `Rat.divInt`. ## Tags rat, rationals, field, ℚ, numerator, denominator, num, denom, cast, coercion, casting -/ variable {F ι α β : Type*} namespace NNRat variable [DivisionSemiring α] {q r : ℚ≥0} @[simp, norm_cast] lemma cast_natCast (n : ℕ) : ((n : ℚ≥0) : α) = n := by simp [cast_def] -- See note [no_index around OfNat.ofNat] @[simp, norm_cast] lemma cast_ofNat (n : ℕ) [n.AtLeastTwo] : no_index (OfNat.ofNat n : ℚ≥0) = (OfNat.ofNat n : α) := cast_natCast _ @[simp, norm_cast] lemma cast_zero : ((0 : ℚ≥0) : α) = 0 := (cast_natCast _).trans Nat.cast_zero @[simp, norm_cast] lemma cast_one : ((1 : ℚ≥0) : α) = 1 := (cast_natCast _).trans Nat.cast_one lemma cast_commute (q : ℚ≥0) (a : α) : Commute (↑q) a := by simpa only [cast_def] using (q.num.cast_commute a).div_left (q.den.cast_commute a) lemma commute_cast (a : α) (q : ℚ≥0) : Commute a q := (cast_commute ..).symm lemma cast_comm (q : ℚ≥0) (a : α) : q * a = a * q := cast_commute _ _ @[norm_cast] lemma cast_divNat_of_ne_zero (a : ℕ) {b : ℕ} (hb : (b : α) ≠ 0) : divNat a b = (a / b : α) := by rcases e : divNat a b with ⟨⟨n, d, h, c⟩, hn⟩ rw [← Rat.num_nonneg] at hn lift n to ℕ using hn have hd : (d : α) ≠ 0 := by refine fun hd ↦ hb ?_ have : Rat.divInt a b = _ := congr_arg NNRat.cast e obtain ⟨k, rfl⟩ : d ∣ b := by simpa [Int.natCast_dvd_natCast, this] using Rat.den_dvd a b simp [*] have hb' : b ≠ 0 := by rintro rfl; exact hb Nat.cast_zero have hd' : d ≠ 0 := by rintro rfl; exact hd Nat.cast_zero simp_rw [Rat.mk'_eq_divInt, mk_divInt, divNat_inj hb' hd'] at e rw [cast_def] dsimp rw [Commute.div_eq_div_iff _ hd hb] · norm_cast rw [e] exact b.commute_cast _ @[norm_cast] lemma cast_add_of_ne_zero (hq : (q.den : α) ≠ 0) (hr : (r.den : α) ≠ 0) : ↑(q + r) = (q + r : α) := by rw [add_def, cast_divNat_of_ne_zero, cast_def, cast_def, mul_comm _ q.den, (Nat.commute_cast _ _).div_add_div (Nat.commute_cast _ _) hq hr] · push_cast rfl · push_cast exact mul_ne_zero hq hr @[norm_cast] lemma cast_mul_of_ne_zero (hq : (q.den : α) ≠ 0) (hr : (r.den : α) ≠ 0) : ↑(q * r) = (q * r : α) := by rw [mul_def, cast_divNat_of_ne_zero, cast_def, cast_def, (Nat.commute_cast _ _).div_mul_div_comm (Nat.commute_cast _ _)] · push_cast rfl · push_cast exact mul_ne_zero hq hr @[norm_cast] lemma cast_inv_of_ne_zero (hq : (q.num : α) ≠ 0) : (q⁻¹ : ℚ≥0) = (q⁻¹ : α) := by rw [inv_def, cast_divNat_of_ne_zero _ hq, cast_def, inv_div] @[norm_cast] lemma cast_div_of_ne_zero (hq : (q.den : α) ≠ 0) (hr : (r.num : α) ≠ 0) : ↑(q / r) = (q / r : α) := by rw [div_def, cast_divNat_of_ne_zero, cast_def, cast_def, div_eq_mul_inv (_ / _), inv_div, (Nat.commute_cast _ _).div_mul_div_comm (Nat.commute_cast _ _)] · push_cast rfl · push_cast exact mul_ne_zero hq hr end NNRat namespace Rat variable [DivisionRing α] {p q : ℚ} @[simp, norm_cast] theorem cast_intCast (n : ℤ) : ((n : ℚ) : α) = n := (cast_def _).trans <| show (n / (1 : ℕ) : α) = n by rw [Nat.cast_one, div_one] @[simp, norm_cast] theorem cast_natCast (n : ℕ) : ((n : ℚ) : α) = n := by rw [← Int.cast_natCast, cast_intCast, Int.cast_natCast] @[deprecated (since := "2024-03-21")] alias cast_coe_int := cast_intCast @[deprecated (since := "2024-03-21")] alias cast_coe_nat := cast_natCast -- See note [no_index around OfNat.ofNat] @[simp, norm_cast] lemma cast_ofNat (n : ℕ) [n.AtLeastTwo] : ((no_index (OfNat.ofNat n : ℚ)) : α) = (OfNat.ofNat n : α) := by simp [cast_def] @[simp, norm_cast] theorem cast_zero : ((0 : ℚ) : α) = 0 := (cast_intCast _).trans Int.cast_zero @[simp, norm_cast] theorem cast_one : ((1 : ℚ) : α) = 1 := (cast_intCast _).trans Int.cast_one theorem cast_commute (r : ℚ) (a : α) : Commute (↑r) a := by simpa only [cast_def] using (r.1.cast_commute a).div_left (r.2.cast_commute a) theorem cast_comm (r : ℚ) (a : α) : (r : α) * a = a * r := (cast_commute r a).eq theorem commute_cast (a : α) (r : ℚ) : Commute a r := (r.cast_commute a).symm @[norm_cast] lemma cast_divInt_of_ne_zero (a : ℤ) {b : ℤ} (b0 : (b : α) ≠ 0) : (a /. b : α) = a / b := by have b0' : b ≠ 0 := by refine mt ?_ b0 simp (config := { contextual := true }) cases' e : a /. b with n d h c have d0 : (d : α) ≠ 0 := by intro d0 have dd := den_dvd a b cases' show (d : ℤ) ∣ b by rwa [e] at dd with k ke have : (b : α) = (d : α) * (k : α) := by rw [ke, Int.cast_mul, Int.cast_natCast] rw [d0, zero_mul] at this contradiction rw [mk'_eq_divInt] at e have := congr_arg ((↑) : ℤ → α) ((divInt_eq_iff b0' <| ne_of_gt <| Int.natCast_pos.2 h.bot_lt).1 e) rw [Int.cast_mul, Int.cast_mul, Int.cast_natCast] at this rw [eq_comm, cast_def, div_eq_mul_inv, eq_div_iff_mul_eq d0, mul_assoc, (d.commute_cast _).eq, ← mul_assoc, this, mul_assoc, mul_inv_cancel b0, mul_one] @[norm_cast] lemma cast_mkRat_of_ne_zero (a : ℤ) {b : ℕ} (hb : (b : α) ≠ 0) : (mkRat a b : α) = a / b := by rw [Rat.mkRat_eq_divInt, cast_divInt_of_ne_zero, Int.cast_natCast]; rwa [Int.cast_natCast] @[norm_cast] lemma cast_add_of_ne_zero {q r : ℚ} (hq : (q.den : α) ≠ 0) (hr : (r.den : α) ≠ 0) : (q + r : ℚ) = (q + r : α) := by rw [add_def', cast_mkRat_of_ne_zero, cast_def, cast_def, mul_comm r.num, (Nat.cast_commute _ _).div_add_div (Nat.commute_cast _ _) hq hr] · push_cast rfl · push_cast exact mul_ne_zero hq hr @[simp, norm_cast] lemma cast_neg (q : ℚ) : ↑(-q) = (-q : α) := by simp [cast_def, neg_div] @[norm_cast] lemma cast_sub_of_ne_zero (hp : (p.den : α) ≠ 0) (hq : (q.den : α) ≠ 0) : ↑(p - q) = (p - q : α) := by simp [sub_eq_add_neg, cast_add_of_ne_zero, hp, hq] @[norm_cast] lemma cast_mul_of_ne_zero (hp : (p.den : α) ≠ 0) (hq : (q.den : α) ≠ 0) : ↑(p * q) = (p * q : α) := by rw [mul_eq_mkRat, cast_mkRat_of_ne_zero, cast_def, cast_def, (Nat.commute_cast _ _).div_mul_div_comm (Int.commute_cast _ _)] · push_cast rfl · push_cast exact mul_ne_zero hp hq @[norm_cast] lemma cast_inv_of_ne_zero (hq : (q.num : α) ≠ 0) : ↑(q⁻¹) = (q⁻¹ : α) := by rw [inv_def', cast_divInt_of_ne_zero _ hq, cast_def, inv_div, Int.cast_natCast] @[norm_cast] lemma cast_div_of_ne_zero (hp : (p.den : α) ≠ 0) (hq : (q.num : α) ≠ 0) : ↑(p / q) = (p / q : α) := by rw [div_def', cast_divInt_of_ne_zero, cast_def, cast_def, div_eq_mul_inv (_ / _), inv_div, (Int.commute_cast _ _).div_mul_div_comm (Nat.commute_cast _ _)] · push_cast rfl · push_cast exact mul_ne_zero hp hq end Rat open Rat variable [FunLike F α β] @[simp] lemma map_nnratCast [DivisionSemiring α] [DivisionSemiring β] [RingHomClass F α β] (f : F) (q : ℚ≥0) : f q = q := by simp_rw [NNRat.cast_def, map_div₀, map_natCast] @[simp] lemma eq_nnratCast [DivisionSemiring α] [FunLike F ℚ≥0 α] [RingHomClass F ℚ≥0 α] (f : F) (q : ℚ≥0) : f q = q := by rw [← map_nnratCast f, NNRat.cast_id] @[simp] theorem map_ratCast [DivisionRing α] [DivisionRing β] [RingHomClass F α β] (f : F) (q : ℚ) : f q = q := by rw [cast_def, map_div₀, map_intCast, map_natCast, cast_def] @[simp] lemma eq_ratCast [DivisionRing α] [FunLike F ℚ α] [RingHomClass F ℚ α] (f : F) (q : ℚ) : f q = q := by rw [← map_ratCast f, Rat.cast_id] namespace MonoidWithZeroHom variable {M₀ : Type*} [MonoidWithZero M₀] [FunLike F ℚ M₀] [MonoidWithZeroHomClass F ℚ M₀] variable {f g : F} /-- If `f` and `g` agree on the integers then they are equal `φ`. -/ theorem ext_rat' (h : ∀ m : ℤ, f m = g m) : f = g := (DFunLike.ext f g) fun r => by rw [← r.num_div_den, div_eq_mul_inv, map_mul, map_mul, h, ← Int.cast_natCast, eq_on_inv₀ f g] apply h /-- If `f` and `g` agree on the integers then they are equal `φ`. See note [partially-applied ext lemmas] for why `comp` is used here. -/ @[ext] theorem ext_rat {f g : ℚ →*₀ M₀} (h : f.comp (Int.castRingHom ℚ : ℤ →*₀ ℚ) = g.comp (Int.castRingHom ℚ)) : f = g := ext_rat' <| DFunLike.congr_fun h /-- Positive integer values of a morphism `φ` and its value on `-1` completely determine `φ`. -/ theorem ext_rat_on_pnat (same_on_neg_one : f (-1) = g (-1)) (same_on_pnat : ∀ n : ℕ, 0 < n → f n = g n) : f = g := ext_rat' <| DFunLike.congr_fun <| show (f : ℚ →*₀ M₀).comp (Int.castRingHom ℚ : ℤ →*₀ ℚ) = (g : ℚ →*₀ M₀).comp (Int.castRingHom ℚ : ℤ →*₀ ℚ) from ext_int' (by simpa) (by simpa) end MonoidWithZeroHom /-- Any two ring homomorphisms from `ℚ` to a semiring are equal. If the codomain is a division ring, then this lemma follows from `eq_ratCast`. -/ theorem RingHom.ext_rat {R : Type*} [Semiring R] [FunLike F ℚ R] [RingHomClass F ℚ R] (f g : F) : f = g := MonoidWithZeroHom.ext_rat' <| RingHom.congr_fun <| ((f : ℚ →+* R).comp (Int.castRingHom ℚ)).ext_int ((g : ℚ →+* R).comp (Int.castRingHom ℚ)) instance Rat.subsingleton_ringHom {R : Type*} [Semiring R] : Subsingleton (ℚ →+* R) := ⟨RingHom.ext_rat⟩ /-! ### Scalar multiplication -/ namespace NNRat variable [DivisionSemiring α] instance (priority := 100) instDistribSMul : DistribSMul ℚ≥0 α where smul_zero a := by rw [smul_def, mul_zero] smul_add a x y := by rw [smul_def, smul_def, smul_def, mul_add] instance instIsScalarTowerRight : IsScalarTower ℚ≥0 α α where smul_assoc a x y := by simp only [smul_def, smul_eq_mul, mul_assoc] end NNRat namespace Rat variable [DivisionRing α] instance (priority := 100) instDistribSMul : DistribSMul ℚ α where smul_zero a := by rw [smul_def, mul_zero] smul_add a x y := by rw [smul_def, smul_def, smul_def, mul_add] instance instIsScalarTowerRight : IsScalarTower ℚ α α where smul_assoc a x y := by simp only [smul_def, smul_eq_mul, mul_assoc] end Rat
Data\Rat\Cast\Lemmas.lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import Mathlib.Data.Rat.Cast.Defs import Mathlib.Algebra.Field.Basic /-! # Some exiled lemmas about casting These lemmas have been removed from `Mathlib.Data.Rat.Cast.Defs` to avoiding needing to import `Mathlib.Algebra.Field.Basic` there. In fact, these lemmas don't appear to be used anywhere in Mathlib, so perhaps this file can simply be deleted. -/ namespace Rat variable {α : Type*} [DivisionRing α] -- Porting note: rewrote proof @[simp] theorem cast_inv_nat (n : ℕ) : ((n⁻¹ : ℚ) : α) = (n : α)⁻¹ := by cases' n with n · simp rw [cast_def, inv_natCast_num, inv_natCast_den, if_neg n.succ_ne_zero, Int.sign_eq_one_of_pos (Nat.cast_pos.mpr n.succ_pos), Int.cast_one, one_div] -- Porting note: proof got a lot easier - is this still the intended statement? @[simp] theorem cast_inv_int (n : ℤ) : ((n⁻¹ : ℚ) : α) = (n : α)⁻¹ := by cases' n with n n · simp [ofInt_eq_cast, cast_inv_nat] · simp only [ofInt_eq_cast, Int.cast_negSucc, ← Nat.cast_succ, cast_neg, inv_neg, cast_inv_nat] @[simp, norm_cast] theorem cast_nnratCast {K} [DivisionRing K] (q : ℚ≥0) : ((q : ℚ) : K) = (q : K) := by rw [Rat.cast_def, NNRat.cast_def, NNRat.cast_def] have hn := @num_div_eq_of_coprime q.num q.den ?hdp q.coprime_num_den on_goal 1 => have hd := @den_div_eq_of_coprime q.num q.den ?hdp q.coprime_num_den case hdp => simpa only [Nat.cast_pos] using q.den_pos simp only [Int.cast_natCast, Nat.cast_inj] at hn hd rw [hn, hd, Int.cast_natCast] /-- Casting a scientific literal via `ℚ` is the same as casting directly. -/ @[simp, norm_cast] theorem cast_ofScientific {K} [DivisionRing K] (m : ℕ) (s : Bool) (e : ℕ) : (OfScientific.ofScientific m s e : ℚ) = (OfScientific.ofScientific m s e : K) := by rw [← NNRat.cast_ofScientific (K := K), ← NNRat.cast_ofScientific, cast_nnratCast] end Rat namespace NNRat @[simp, norm_cast] theorem cast_pow {K} [DivisionSemiring K] (q : ℚ≥0) (n : ℕ) : NNRat.cast (q ^ n) = (NNRat.cast q : K) ^ n := by rw [cast_def, cast_def, den_pow, num_pow, Nat.cast_pow, Nat.cast_pow, div_eq_mul_inv, ← inv_pow, ← (Nat.cast_commute _ _).mul_pow, ← div_eq_mul_inv] theorem cast_zpow_of_ne_zero {K} [DivisionSemiring K] (q : ℚ≥0) (z : ℤ) (hq : (q.num : K) ≠ 0) : NNRat.cast (q ^ z) = (NNRat.cast q : K) ^ z := by obtain ⟨n, rfl | rfl⟩ := z.eq_nat_or_neg · simp · simp_rw [zpow_neg, zpow_natCast, ← inv_pow, NNRat.cast_pow] congr rw [cast_inv_of_ne_zero hq] open OfScientific in theorem Nonneg.coe_ofScientific {K} [LinearOrderedField K] (m : ℕ) (s : Bool) (e : ℕ) : (ofScientific m s e : {x : K // 0 ≤ x}).val = ofScientific m s e := rfl end NNRat
Data\Rat\Cast\Order.lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import Mathlib.Algebra.Order.Ring.Rat import Mathlib.Data.Rat.Cast.CharZero import Mathlib.Tactic.Positivity.Core import Mathlib.Algebra.Order.Field.Basic /-! # Casts of rational numbers into linear ordered fields. -/ variable {F ι α β : Type*} namespace Rat variable {p q : ℚ} @[simp] theorem castHom_rat : castHom ℚ = RingHom.id ℚ := RingHom.ext cast_id section LinearOrderedField variable {K : Type*} [LinearOrderedField K] theorem cast_pos_of_pos (hq : 0 < q) : (0 : K) < q := by rw [Rat.cast_def] exact div_pos (Int.cast_pos.2 <| num_pos.2 hq) (Nat.cast_pos.2 q.pos) @[mono] theorem cast_strictMono : StrictMono ((↑) : ℚ → K) := fun p q => by simpa only [sub_pos, cast_sub] using cast_pos_of_pos (K := K) (q := q - p) @[mono] theorem cast_mono : Monotone ((↑) : ℚ → K) := cast_strictMono.monotone /-- Coercion from `ℚ` as an order embedding. -/ @[simps!] def castOrderEmbedding : ℚ ↪o K := OrderEmbedding.ofStrictMono (↑) cast_strictMono @[simp, norm_cast] lemma cast_le : (p : K) ≤ q ↔ p ≤ q := castOrderEmbedding.le_iff_le @[simp, norm_cast] lemma cast_lt : (p : K) < q ↔ p < q := cast_strictMono.lt_iff_lt @[simp] lemma cast_nonneg : 0 ≤ (q : K) ↔ 0 ≤ q := by norm_cast @[simp] lemma cast_nonpos : (q : K) ≤ 0 ↔ q ≤ 0 := by norm_cast @[simp] lemma cast_pos : (0 : K) < q ↔ 0 < q := by norm_cast @[simp] lemma cast_lt_zero : (q : K) < 0 ↔ q < 0 := by norm_cast @[simp, norm_cast] lemma cast_min (p q : ℚ) : (↑(min p q) : K) = min (p : K) (q : K) := (@cast_mono K _).map_min @[simp, norm_cast] lemma cast_max (p q : ℚ) : (↑(max p q) : K) = max (p : K) (q : K) := (@cast_mono K _).map_max @[simp, norm_cast] lemma cast_abs (q : ℚ) : ((|q| : ℚ) : K) = |(q : K)| := by simp [abs_eq_max_neg] open Set @[simp] theorem preimage_cast_Icc (p q : ℚ) : (↑) ⁻¹' Icc (p : K) q = Icc p q := castOrderEmbedding.preimage_Icc .. @[simp] theorem preimage_cast_Ico (p q : ℚ) : (↑) ⁻¹' Ico (p : K) q = Ico p q := castOrderEmbedding.preimage_Ico .. @[simp] theorem preimage_cast_Ioc (p q : ℚ) : (↑) ⁻¹' Ioc (p : K) q = Ioc p q := castOrderEmbedding.preimage_Ioc p q @[simp] theorem preimage_cast_Ioo (p q : ℚ) : (↑) ⁻¹' Ioo (p : K) q = Ioo p q := castOrderEmbedding.preimage_Ioo p q @[simp] theorem preimage_cast_Ici (q : ℚ) : (↑) ⁻¹' Ici (q : K) = Ici q := castOrderEmbedding.preimage_Ici q @[simp] theorem preimage_cast_Iic (q : ℚ) : (↑) ⁻¹' Iic (q : K) = Iic q := castOrderEmbedding.preimage_Iic q @[simp] theorem preimage_cast_Ioi (q : ℚ) : (↑) ⁻¹' Ioi (q : K) = Ioi q := castOrderEmbedding.preimage_Ioi q @[simp] theorem preimage_cast_Iio (q : ℚ) : (↑) ⁻¹' Iio (q : K) = Iio q := castOrderEmbedding.preimage_Iio q @[simp] theorem preimage_cast_uIcc (p q : ℚ) : (↑) ⁻¹' uIcc (p : K) q = uIcc p q := (castOrderEmbedding (K := K)).preimage_uIcc p q @[simp] theorem preimage_cast_uIoc (p q : ℚ) : (↑) ⁻¹' uIoc (p : K) q = uIoc p q := (castOrderEmbedding (K := K)).preimage_uIoc p q end LinearOrderedField end Rat namespace NNRat variable {K} [LinearOrderedSemifield K] {p q : ℚ≥0} theorem cast_strictMono : StrictMono ((↑) : ℚ≥0 → K) := fun p q h => by rwa [NNRat.cast_def, NNRat.cast_def, div_lt_div_iff, ← Nat.cast_mul, ← Nat.cast_mul, Nat.cast_lt (α := K), ← NNRat.lt_def] · simp · simp @[mono] theorem cast_mono : Monotone ((↑) : ℚ≥0 → K) := cast_strictMono.monotone /-- Coercion from `ℚ` as an order embedding. -/ @[simps!] def castOrderEmbedding : ℚ≥0 ↪o K := OrderEmbedding.ofStrictMono (↑) cast_strictMono @[simp, norm_cast] lemma cast_le : (p : K) ≤ q ↔ p ≤ q := castOrderEmbedding.le_iff_le @[simp, norm_cast] lemma cast_lt : (p : K) < q ↔ p < q := cast_strictMono.lt_iff_lt @[simp] lemma cast_nonpos : (q : K) ≤ 0 ↔ q ≤ 0 := by norm_cast @[simp] lemma cast_pos : (0 : K) < q ↔ 0 < q := by norm_cast @[norm_cast] lemma cast_lt_zero : (q : K) < 0 ↔ q < 0 := by norm_cast @[simp] lemma not_cast_lt_zero : ¬(q : K) < 0 := mod_cast not_lt_zero' @[simp, norm_cast] lemma cast_min (p q : ℚ≥0) : (↑(min p q) : K) = min (p : K) (q : K) := (@cast_mono K _).map_min @[simp, norm_cast] lemma cast_max (p q : ℚ≥0) : (↑(max p q) : K) = max (p : K) (q : K) := (@cast_mono K _).map_max open Set @[simp] theorem preimage_cast_Icc (p q : ℚ≥0) : (↑) ⁻¹' Icc (p : K) q = Icc p q := castOrderEmbedding.preimage_Icc .. @[simp] theorem preimage_cast_Ico (p q : ℚ≥0) : (↑) ⁻¹' Ico (p : K) q = Ico p q := castOrderEmbedding.preimage_Ico .. @[simp] theorem preimage_cast_Ioc (p q : ℚ≥0) : (↑) ⁻¹' Ioc (p : K) q = Ioc p q := castOrderEmbedding.preimage_Ioc p q @[simp] theorem preimage_cast_Ioo (p q : ℚ≥0) : (↑) ⁻¹' Ioo (p : K) q = Ioo p q := castOrderEmbedding.preimage_Ioo p q @[simp] theorem preimage_cast_Ici (p : ℚ≥0) : (↑) ⁻¹' Ici (p : K) = Ici p := castOrderEmbedding.preimage_Ici p @[simp] theorem preimage_cast_Iic (p : ℚ≥0) : (↑) ⁻¹' Iic (p : K) = Iic p := castOrderEmbedding.preimage_Iic p @[simp] theorem preimage_cast_Ioi (p : ℚ≥0) : (↑) ⁻¹' Ioi (p : K) = Ioi p := castOrderEmbedding.preimage_Ioi p @[simp] theorem preimage_cast_Iio (p : ℚ≥0) : (↑) ⁻¹' Iio (p : K) = Iio p := castOrderEmbedding.preimage_Iio p @[simp] theorem preimage_cast_uIcc (p q : ℚ≥0) : (↑) ⁻¹' uIcc (p : K) q = uIcc p q := (castOrderEmbedding (K := K)).preimage_uIcc p q @[simp] theorem preimage_cast_uIoc (p q : ℚ≥0) : (↑) ⁻¹' uIoc (p : K) q = uIoc p q := (castOrderEmbedding (K := K)).preimage_uIoc p q end NNRat namespace Mathlib.Meta.Positivity open Lean Meta Qq Function /-- Extension for Rat.cast. -/ @[positivity Rat.cast _] def evalRatCast : PositivityExt where eval {u α} _zα _pα e := do let ~q(@Rat.cast _ (_) ($a : ℚ)) := e | throwError "not Rat.cast" match ← core q(inferInstance) q(inferInstance) a with | .positive pa => let _oα ← synthInstanceQ q(LinearOrderedField $α) assumeInstancesCommute return .positive q((Rat.cast_pos (K := $α)).mpr $pa) | .nonnegative pa => let _oα ← synthInstanceQ q(LinearOrderedField $α) assumeInstancesCommute return .nonnegative q((Rat.cast_nonneg (K := $α)).mpr $pa) | .nonzero pa => let _oα ← synthInstanceQ q(DivisionRing $α) let _cα ← synthInstanceQ q(CharZero $α) assumeInstancesCommute return .nonzero q((Rat.cast_ne_zero (α := $α)).mpr $pa) | .none => pure .none /-- Extension for NNRat.cast. -/ @[positivity NNRat.cast _] def evalNNRatCast : PositivityExt where eval {u α} _zα _pα e := do let ~q(@NNRat.cast _ (_) ($a : ℚ≥0)) := e | throwError "not NNRat.cast" match ← core q(inferInstance) q(inferInstance) a with | .positive pa => let _oα ← synthInstanceQ q(LinearOrderedSemifield $α) assumeInstancesCommute return .positive q((NNRat.cast_pos (K := $α)).mpr $pa) | _ => let _oα ← synthInstanceQ q(LinearOrderedSemifield $α) assumeInstancesCommute return .nonnegative q(NNRat.cast_nonneg _) end Mathlib.Meta.Positivity
Data\Real\Archimedean.lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Floris van Doorn -/ import Mathlib.Algebra.Bounds import Mathlib.Algebra.Order.Archimedean.Basic import Mathlib.Data.Real.Basic import Mathlib.Order.Interval.Set.Disjoint /-! # The real numbers are an Archimedean floor ring, and a conditionally complete linear order. -/ open scoped Classical open Pointwise CauSeq namespace Real instance instArchimedean : Archimedean ℝ := archimedean_iff_rat_le.2 fun x => Real.ind_mk x fun f => let ⟨M, _, H⟩ := f.bounded' 0 ⟨M, mk_le_of_forall_le ⟨0, fun i _ => Rat.cast_le.2 <| le_of_lt (abs_lt.1 (H i)).2⟩⟩ noncomputable instance : FloorRing ℝ := Archimedean.floorRing _ theorem isCauSeq_iff_lift {f : ℕ → ℚ} : IsCauSeq abs f ↔ IsCauSeq abs fun i => (f i : ℝ) where mp H ε ε0 := let ⟨δ, δ0, δε⟩ := exists_pos_rat_lt ε0 (H _ δ0).imp fun i hi j ij => by dsimp; exact lt_trans (mod_cast hi _ ij) δε mpr H ε ε0 := (H _ (Rat.cast_pos.2 ε0)).imp fun i hi j ij => by dsimp at hi; exact mod_cast hi _ ij theorem of_near (f : ℕ → ℚ) (x : ℝ) (h : ∀ ε > 0, ∃ i, ∀ j ≥ i, |(f j : ℝ) - x| < ε) : ∃ h', Real.mk ⟨f, h'⟩ = x := ⟨isCauSeq_iff_lift.2 (CauSeq.of_near _ (const abs x) h), sub_eq_zero.1 <| abs_eq_zero.1 <| (eq_of_le_of_forall_le_of_dense (abs_nonneg _)) fun _ε ε0 => mk_near_of_forall_near <| (h _ ε0).imp fun _i h j ij => le_of_lt (h j ij)⟩ theorem exists_floor (x : ℝ) : ∃ ub : ℤ, (ub : ℝ) ≤ x ∧ ∀ z : ℤ, (z : ℝ) ≤ x → z ≤ ub := Int.exists_greatest_of_bdd (let ⟨n, hn⟩ := exists_int_gt x ⟨n, fun _ h' => Int.cast_le.1 <| le_trans h' <| le_of_lt hn⟩) (let ⟨n, hn⟩ := exists_int_lt x ⟨n, le_of_lt hn⟩) theorem exists_isLUB {S : Set ℝ} (hne : S.Nonempty) (hbdd : BddAbove S) : ∃ x, IsLUB S x := by rcases hne, hbdd with ⟨⟨L, hL⟩, ⟨U, hU⟩⟩ have : ∀ d : ℕ, BddAbove { m : ℤ | ∃ y ∈ S, (m : ℝ) ≤ y * d } := by cases' exists_int_gt U with k hk refine fun d => ⟨k * d, fun z h => ?_⟩ rcases h with ⟨y, yS, hy⟩ refine Int.cast_le.1 (hy.trans ?_) push_cast exact mul_le_mul_of_nonneg_right ((hU yS).trans hk.le) d.cast_nonneg choose f hf using fun d : ℕ => Int.exists_greatest_of_bdd (this d) ⟨⌊L * d⌋, L, hL, Int.floor_le _⟩ have hf₁ : ∀ n > 0, ∃ y ∈ S, ((f n / n : ℚ) : ℝ) ≤ y := fun n n0 => let ⟨y, yS, hy⟩ := (hf n).1 ⟨y, yS, by simpa using (div_le_iff (Nat.cast_pos.2 n0 : (_ : ℝ) < _)).2 hy⟩ have hf₂ : ∀ n > 0, ∀ y ∈ S, (y - ((n : ℕ) : ℝ)⁻¹) < (f n / n : ℚ) := by intro n n0 y yS have := (Int.sub_one_lt_floor _).trans_le (Int.cast_le.2 <| (hf n).2 _ ⟨y, yS, Int.floor_le _⟩) simp only [Rat.cast_div, Rat.cast_intCast, Rat.cast_natCast, gt_iff_lt] rwa [lt_div_iff (Nat.cast_pos.2 n0 : (_ : ℝ) < _), sub_mul, _root_.inv_mul_cancel] exact ne_of_gt (Nat.cast_pos.2 n0) have hg : IsCauSeq abs (fun n => f n / n : ℕ → ℚ) := by intro ε ε0 suffices ∀ j ≥ ⌈ε⁻¹⌉₊, ∀ k ≥ ⌈ε⁻¹⌉₊, (f j / j - f k / k : ℚ) < ε by refine ⟨_, fun j ij => abs_lt.2 ⟨?_, this _ ij _ le_rfl⟩⟩ rw [neg_lt, neg_sub] exact this _ le_rfl _ ij intro j ij k ik replace ij := le_trans (Nat.le_ceil _) (Nat.cast_le.2 ij) replace ik := le_trans (Nat.le_ceil _) (Nat.cast_le.2 ik) have j0 := Nat.cast_pos.1 ((inv_pos.2 ε0).trans_le ij) have k0 := Nat.cast_pos.1 ((inv_pos.2 ε0).trans_le ik) rcases hf₁ _ j0 with ⟨y, yS, hy⟩ refine lt_of_lt_of_le ((Rat.cast_lt (K := ℝ)).1 ?_) ((inv_le ε0 (Nat.cast_pos.2 k0)).1 ik) simpa using sub_lt_iff_lt_add'.2 (lt_of_le_of_lt hy <| sub_lt_iff_lt_add.1 <| hf₂ _ k0 _ yS) let g : CauSeq ℚ abs := ⟨fun n => f n / n, hg⟩ refine ⟨mk g, ⟨fun x xS => ?_, fun y h => ?_⟩⟩ · refine le_of_forall_ge_of_dense fun z xz => ?_ cases' exists_nat_gt (x - z)⁻¹ with K hK refine le_mk_of_forall_le ⟨K, fun n nK => ?_⟩ replace xz := sub_pos.2 xz replace hK := hK.le.trans (Nat.cast_le.2 nK) have n0 : 0 < n := Nat.cast_pos.1 ((inv_pos.2 xz).trans_le hK) refine le_trans ?_ (hf₂ _ n0 _ xS).le rwa [le_sub_comm, inv_le (Nat.cast_pos.2 n0 : (_ : ℝ) < _) xz] · exact mk_le_of_forall_le ⟨1, fun n n1 => let ⟨x, xS, hx⟩ := hf₁ _ n1 le_trans hx (h xS)⟩ /-- A nonempty, bounded below set of real numbers has a greatest lower bound. -/ theorem exists_isGLB {S : Set ℝ} (hne : S.Nonempty) (hbdd : BddBelow S) : ∃ x, IsGLB S x := by have hne' : (-S).Nonempty := Set.nonempty_neg.mpr hne have hbdd' : BddAbove (-S) := bddAbove_neg.mpr hbdd use -Classical.choose (Real.exists_isLUB hne' hbdd') rw [← isLUB_neg] exact Classical.choose_spec (Real.exists_isLUB hne' hbdd') noncomputable instance : SupSet ℝ := ⟨fun S => if h : S.Nonempty ∧ BddAbove S then Classical.choose (exists_isLUB h.1 h.2) else 0⟩ theorem sSup_def (S : Set ℝ) : sSup S = if h : S.Nonempty ∧ BddAbove S then Classical.choose (exists_isLUB h.1 h.2) else 0 := rfl protected theorem isLUB_sSup (S : Set ℝ) (h₁ : S.Nonempty) (h₂ : BddAbove S) : IsLUB S (sSup S) := by simp only [sSup_def, dif_pos (And.intro h₁ h₂)] apply Classical.choose_spec noncomputable instance : InfSet ℝ := ⟨fun S => -sSup (-S)⟩ theorem sInf_def (S : Set ℝ) : sInf S = -sSup (-S) := rfl protected theorem is_glb_sInf (S : Set ℝ) (h₁ : S.Nonempty) (h₂ : BddBelow S) : IsGLB S (sInf S) := by rw [sInf_def, ← isLUB_neg', neg_neg] exact Real.isLUB_sSup _ h₁.neg h₂.neg noncomputable instance : ConditionallyCompleteLinearOrder ℝ := { Real.linearOrder, Real.lattice with sSup := SupSet.sSup sInf := InfSet.sInf le_csSup := fun s a hs ha => (Real.isLUB_sSup s ⟨a, ha⟩ hs).1 ha csSup_le := fun s a hs ha => (Real.isLUB_sSup s hs ⟨a, ha⟩).2 ha csInf_le := fun s a hs ha => (Real.is_glb_sInf s ⟨a, ha⟩ hs).1 ha le_csInf := fun s a hs ha => (Real.is_glb_sInf s hs ⟨a, ha⟩).2 ha csSup_of_not_bddAbove := fun s hs ↦ by simp [hs, sSup_def] csInf_of_not_bddBelow := fun s hs ↦ by simp [hs, sInf_def, sSup_def] } theorem lt_sInf_add_pos {s : Set ℝ} (h : s.Nonempty) {ε : ℝ} (hε : 0 < ε) : ∃ a ∈ s, a < sInf s + ε := exists_lt_of_csInf_lt h <| lt_add_of_pos_right _ hε theorem add_neg_lt_sSup {s : Set ℝ} (h : s.Nonempty) {ε : ℝ} (hε : ε < 0) : ∃ a ∈ s, sSup s + ε < a := exists_lt_of_lt_csSup h <| add_lt_iff_neg_left.2 hε theorem sInf_le_iff {s : Set ℝ} (h : BddBelow s) (h' : s.Nonempty) {a : ℝ} : sInf s ≤ a ↔ ∀ ε, 0 < ε → ∃ x ∈ s, x < a + ε := by rw [le_iff_forall_pos_lt_add] constructor <;> intro H ε ε_pos · exact exists_lt_of_csInf_lt h' (H ε ε_pos) · rcases H ε ε_pos with ⟨x, x_in, hx⟩ exact csInf_lt_of_lt h x_in hx theorem le_sSup_iff {s : Set ℝ} (h : BddAbove s) (h' : s.Nonempty) {a : ℝ} : a ≤ sSup s ↔ ∀ ε, ε < 0 → ∃ x ∈ s, a + ε < x := by rw [le_iff_forall_pos_lt_add] refine ⟨fun H ε ε_neg => ?_, fun H ε ε_pos => ?_⟩ · exact exists_lt_of_lt_csSup h' (lt_sub_iff_add_lt.mp (H _ (neg_pos.mpr ε_neg))) · rcases H _ (neg_lt_zero.mpr ε_pos) with ⟨x, x_in, hx⟩ exact sub_lt_iff_lt_add.mp (lt_csSup_of_lt h x_in hx) @[simp] theorem sSup_empty : sSup (∅ : Set ℝ) = 0 := dif_neg <| by simp @[simp] lemma iSup_of_isEmpty {α : Sort*} [IsEmpty α] (f : α → ℝ) : ⨆ i, f i = 0 := by dsimp [iSup] convert Real.sSup_empty rw [Set.range_eq_empty_iff] infer_instance @[simp] theorem ciSup_const_zero {α : Sort*} : ⨆ _ : α, (0 : ℝ) = 0 := by cases isEmpty_or_nonempty α · exact Real.iSup_of_isEmpty _ · exact ciSup_const theorem sSup_of_not_bddAbove {s : Set ℝ} (hs : ¬BddAbove s) : sSup s = 0 := dif_neg fun h => hs h.2 theorem iSup_of_not_bddAbove {α : Sort*} {f : α → ℝ} (hf : ¬BddAbove (Set.range f)) : ⨆ i, f i = 0 := sSup_of_not_bddAbove hf theorem sSup_univ : sSup (@Set.univ ℝ) = 0 := Real.sSup_of_not_bddAbove not_bddAbove_univ @[simp] theorem sInf_empty : sInf (∅ : Set ℝ) = 0 := by simp [sInf_def, sSup_empty] @[simp] nonrec lemma iInf_of_isEmpty {α : Sort*} [IsEmpty α] (f : α → ℝ) : ⨅ i, f i = 0 := by rw [iInf_of_isEmpty, sInf_empty] @[simp] theorem ciInf_const_zero {α : Sort*} : ⨅ _ : α, (0 : ℝ) = 0 := by cases isEmpty_or_nonempty α · exact Real.iInf_of_isEmpty _ · exact ciInf_const theorem sInf_of_not_bddBelow {s : Set ℝ} (hs : ¬BddBelow s) : sInf s = 0 := neg_eq_zero.2 <| sSup_of_not_bddAbove <| mt bddAbove_neg.1 hs theorem iInf_of_not_bddBelow {α : Sort*} {f : α → ℝ} (hf : ¬BddBelow (Set.range f)) : ⨅ i, f i = 0 := sInf_of_not_bddBelow hf /-- As `0` is the default value for `Real.sSup` of the empty set or sets which are not bounded above, it suffices to show that `S` is bounded below by `0` to show that `0 ≤ sSup S`. -/ theorem sSup_nonneg (S : Set ℝ) (hS : ∀ x ∈ S, (0 : ℝ) ≤ x) : 0 ≤ sSup S := by rcases S.eq_empty_or_nonempty with (rfl | ⟨y, hy⟩) · exact sSup_empty.ge · apply dite _ (fun h => le_csSup_of_le h hy <| hS y hy) fun h => (sSup_of_not_bddAbove h).ge /-- As `0` is the default value for `Real.sSup` of the empty set or sets which are not bounded above, it suffices to show that `f i` is nonnegative to show that `0 ≤ ⨆ i, f i`. -/ protected theorem iSup_nonneg {ι : Sort*} {f : ι → ℝ} (hf : ∀ i, 0 ≤ f i) : 0 ≤ ⨆ i, f i := sSup_nonneg _ <| Set.forall_mem_range.2 hf /-- As `0` is the default value for `Real.sSup` of the empty set or sets which are not bounded above, it suffices to show that all elements of `S` are bounded by a nonnegative number to show that `sSup S` is bounded by this number. -/ protected theorem sSup_le {S : Set ℝ} {a : ℝ} (hS : ∀ x ∈ S, x ≤ a) (ha : 0 ≤ a) : sSup S ≤ a := by rcases S.eq_empty_or_nonempty with (rfl | hS₂) exacts [sSup_empty.trans_le ha, csSup_le hS₂ hS] protected theorem iSup_le {ι : Sort*} {f : ι → ℝ} {a : ℝ} (hS : ∀ i, f i ≤ a) (ha : 0 ≤ a) : ⨆ i, f i ≤ a := Real.sSup_le (Set.forall_mem_range.2 hS) ha /-- As `0` is the default value for `Real.sSup` of the empty set, it suffices to show that `S` is bounded above by `0` to show that `sSup S ≤ 0`. -/ theorem sSup_nonpos (S : Set ℝ) (hS : ∀ x ∈ S, x ≤ (0 : ℝ)) : sSup S ≤ 0 := Real.sSup_le hS le_rfl /-- As `0` is the default value for `Real.sInf` of the empty set, it suffices to show that `S` is bounded below by `0` to show that `0 ≤ sInf S`. -/ theorem sInf_nonneg (S : Set ℝ) (hS : ∀ x ∈ S, (0 : ℝ) ≤ x) : 0 ≤ sInf S := by rcases S.eq_empty_or_nonempty with (rfl | hS₂) exacts [sInf_empty.ge, le_csInf hS₂ hS] /-- As `0` is the default value for `Real.sInf` of the empty set, it suffices to show that `f i` is bounded below by `0` to show that `0 ≤ iInf f`. -/ theorem iInf_nonneg {ι} {f : ι → ℝ} (hf : ∀ i, 0 ≤ f i) : 0 ≤ iInf f := sInf_nonneg _ <| Set.forall_mem_range.2 hf /-- As `0` is the default value for `Real.sInf` of the empty set or sets which are not bounded below, it suffices to show that `S` is bounded above by `0` to show that `sInf S ≤ 0`. -/ theorem sInf_nonpos (S : Set ℝ) (hS : ∀ x ∈ S, x ≤ (0 : ℝ)) : sInf S ≤ 0 := by rcases S.eq_empty_or_nonempty with (rfl | ⟨y, hy⟩) · exact sInf_empty.le · apply dite _ (fun h => csInf_le_of_le h hy <| hS y hy) fun h => (sInf_of_not_bddBelow h).le theorem sInf_le_sSup (s : Set ℝ) (h₁ : BddBelow s) (h₂ : BddAbove s) : sInf s ≤ sSup s := by rcases s.eq_empty_or_nonempty with (rfl | hne) · rw [sInf_empty, sSup_empty] · exact csInf_le_csSup h₁ h₂ hne theorem cauSeq_converges (f : CauSeq ℝ abs) : ∃ x, f ≈ const abs x := by let S := { x : ℝ | const abs x < f } have lb : ∃ x, x ∈ S := exists_lt f have ub' : ∀ x, f < const abs x → ∀ y ∈ S, y ≤ x := fun x h y yS => le_of_lt <| const_lt.1 <| CauSeq.lt_trans yS h have ub : ∃ x, ∀ y ∈ S, y ≤ x := (exists_gt f).imp ub' refine ⟨sSup S, ((lt_total _ _).resolve_left fun h => ?_).resolve_right fun h => ?_⟩ · rcases h with ⟨ε, ε0, i, ih⟩ refine (csSup_le lb (ub' _ ?_)).not_lt (sub_lt_self _ (half_pos ε0)) refine ⟨_, half_pos ε0, i, fun j ij => ?_⟩ rw [sub_apply, const_apply, sub_right_comm, le_sub_iff_add_le, add_halves] exact ih _ ij · rcases h with ⟨ε, ε0, i, ih⟩ refine (le_csSup ub ?_).not_lt ((lt_add_iff_pos_left _).2 (half_pos ε0)) refine ⟨_, half_pos ε0, i, fun j ij => ?_⟩ rw [sub_apply, const_apply, add_comm, ← sub_sub, le_sub_iff_add_le, add_halves] exact ih _ ij instance : CauSeq.IsComplete ℝ abs := ⟨cauSeq_converges⟩ open Set theorem iInf_Ioi_eq_iInf_rat_gt {f : ℝ → ℝ} (x : ℝ) (hf : BddBelow (f '' Ioi x)) (hf_mono : Monotone f) : ⨅ r : Ioi x, f r = ⨅ q : { q' : ℚ // x < q' }, f q := by refine le_antisymm ?_ ?_ · have : Nonempty { r' : ℚ // x < ↑r' } := by obtain ⟨r, hrx⟩ := exists_rat_gt x exact ⟨⟨r, hrx⟩⟩ refine le_ciInf fun r => ?_ obtain ⟨y, hxy, hyr⟩ := exists_rat_btwn r.prop refine ciInf_set_le hf (hxy.trans ?_) exact_mod_cast hyr · refine le_ciInf fun q => ?_ have hq := q.prop rw [mem_Ioi] at hq obtain ⟨y, hxy, hyq⟩ := exists_rat_btwn hq refine (ciInf_le ?_ ?_).trans ?_ · refine ⟨hf.some, fun z => ?_⟩ rintro ⟨u, rfl⟩ suffices hfu : f u ∈ f '' Ioi x from hf.choose_spec hfu exact ⟨u, u.prop, rfl⟩ · exact ⟨y, hxy⟩ · refine hf_mono (le_trans ?_ hyq.le) norm_cast theorem not_bddAbove_coe : ¬ (BddAbove <| range (fun (x : ℚ) ↦ (x : ℝ))) := by dsimp only [BddAbove, upperBounds] rw [Set.not_nonempty_iff_eq_empty] ext simpa using exists_rat_gt _ theorem not_bddBelow_coe : ¬ (BddBelow <| range (fun (x : ℚ) ↦ (x : ℝ))) := by dsimp only [BddBelow, lowerBounds] rw [Set.not_nonempty_iff_eq_empty] ext simpa using exists_rat_lt _ theorem iUnion_Iic_rat : ⋃ r : ℚ, Iic (r : ℝ) = univ := by exact iUnion_Iic_of_not_bddAbove_range not_bddAbove_coe theorem iInter_Iic_rat : ⋂ r : ℚ, Iic (r : ℝ) = ∅ := by exact iInter_Iic_eq_empty_iff.mpr not_bddBelow_coe /-- Exponentiation is eventually larger than linear growth. -/ lemma exists_natCast_add_one_lt_pow_of_one_lt {a : ℝ} (ha : 1 < a) : ∃ m : ℕ, (m + 1 : ℝ) < a ^ m := by obtain ⟨k, posk, hk⟩ : ∃ k : ℕ, 0 < k ∧ 1 / k + 1 < a := by contrapose! ha refine le_of_forall_lt_rat_imp_le ?_ intro q hq refine (ha q.den (by positivity)).trans ?_ rw [← le_sub_iff_add_le, div_le_iff (by positivity), sub_mul, one_mul] norm_cast at hq ⊢ rw [← q.num_div_den, one_lt_div (by positivity)] at hq rw [q.mul_den_eq_num] norm_cast at hq ⊢ rw [le_tsub_iff_left hq.le] exact hq use 2 * k ^ 2 refine (pow_lt_pow_left hk (by positivity) (by simp [posk.ne'])).trans_le' ?_ rcases k.zero_le.eq_or_lt with rfl|kpos · simp rw [pow_two, mul_left_comm, pow_mul] have := mul_add_one_le_add_one_pow (a := 1 / k) (by simp) k rw [div_mul_cancel₀ _ (by simp [kpos.ne'])] at this refine (pow_le_pow_left (by positivity) this _).trans' ?_ rw [mul_left_comm, ← pow_two] exact_mod_cast Nat.two_mul_sq_add_one_le_two_pow_two_mul _ end Real
Data\Real\Basic.lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Floris van Doorn -/ import Mathlib.Algebra.Order.CauSeq.Completion /-! # Real numbers from Cauchy sequences This file defines `ℝ` as the type of equivalence classes of Cauchy sequences of rational numbers. This choice is motivated by how easy it is to prove that `ℝ` is a commutative ring, by simply lifting everything to `ℚ`. The facts that the real numbers are an Archimedean floor ring, and a conditionally complete linear order, have been deferred to the file `Mathlib/Data/Real/Archimedean.lean`, in order to keep the imports here simple. The fact that the real numbers are a (trivial) *-ring has similarly been deferred to `Mathlib/Data/Real/Star.lean`. -/ assert_not_exists Finset assert_not_exists Module assert_not_exists Submonoid assert_not_exists FloorRing /-- The type `ℝ` of real numbers constructed as equivalence classes of Cauchy sequences of rational numbers. -/ structure Real where ofCauchy :: /-- The underlying Cauchy completion -/ cauchy : CauSeq.Completion.Cauchy (abs : ℚ → ℚ) @[inherit_doc] notation "ℝ" => Real -- Porting note: unknown attribute -- attribute [pp_using_anonymous_constructor] Real namespace CauSeq.Completion -- this can't go in `Data.Real.CauSeqCompletion` as the structure on `ℚ` isn't available @[simp] theorem ofRat_rat {abv : ℚ → ℚ} [IsAbsoluteValue abv] (q : ℚ) : ofRat (q : ℚ) = (q : Cauchy abv) := rfl end CauSeq.Completion namespace Real open CauSeq CauSeq.Completion variable {x y : ℝ} theorem ext_cauchy_iff : ∀ {x y : Real}, x = y ↔ x.cauchy = y.cauchy | ⟨a⟩, ⟨b⟩ => by rw [ofCauchy.injEq] theorem ext_cauchy {x y : Real} : x.cauchy = y.cauchy → x = y := ext_cauchy_iff.2 /-- The real numbers are isomorphic to the quotient of Cauchy sequences on the rationals. -/ def equivCauchy : ℝ ≃ CauSeq.Completion.Cauchy (abs : ℚ → ℚ) := ⟨Real.cauchy, Real.ofCauchy, fun ⟨_⟩ => rfl, fun _ => rfl⟩ -- irreducible doesn't work for instances: https://github.com/leanprover-community/lean/issues/511 private irreducible_def zero : ℝ := ⟨0⟩ private irreducible_def one : ℝ := ⟨1⟩ private irreducible_def add : ℝ → ℝ → ℝ | ⟨a⟩, ⟨b⟩ => ⟨a + b⟩ private irreducible_def neg : ℝ → ℝ | ⟨a⟩ => ⟨-a⟩ private irreducible_def mul : ℝ → ℝ → ℝ | ⟨a⟩, ⟨b⟩ => ⟨a * b⟩ private noncomputable irreducible_def inv' : ℝ → ℝ | ⟨a⟩ => ⟨a⁻¹⟩ instance : Zero ℝ := ⟨zero⟩ instance : One ℝ := ⟨one⟩ instance : Add ℝ := ⟨add⟩ instance : Neg ℝ := ⟨neg⟩ instance : Mul ℝ := ⟨mul⟩ instance : Sub ℝ := ⟨fun a b => a + -b⟩ noncomputable instance : Inv ℝ := ⟨inv'⟩ theorem ofCauchy_zero : (⟨0⟩ : ℝ) = 0 := zero_def.symm theorem ofCauchy_one : (⟨1⟩ : ℝ) = 1 := one_def.symm theorem ofCauchy_add (a b) : (⟨a + b⟩ : ℝ) = ⟨a⟩ + ⟨b⟩ := (add_def _ _).symm theorem ofCauchy_neg (a) : (⟨-a⟩ : ℝ) = -⟨a⟩ := (neg_def _).symm theorem ofCauchy_sub (a b) : (⟨a - b⟩ : ℝ) = ⟨a⟩ - ⟨b⟩ := by rw [sub_eq_add_neg, ofCauchy_add, ofCauchy_neg] rfl theorem ofCauchy_mul (a b) : (⟨a * b⟩ : ℝ) = ⟨a⟩ * ⟨b⟩ := (mul_def _ _).symm theorem ofCauchy_inv {f} : (⟨f⁻¹⟩ : ℝ) = ⟨f⟩⁻¹ := show _ = inv' _ by rw [inv'] theorem cauchy_zero : (0 : ℝ).cauchy = 0 := show zero.cauchy = 0 by rw [zero_def] theorem cauchy_one : (1 : ℝ).cauchy = 1 := show one.cauchy = 1 by rw [one_def] theorem cauchy_add : ∀ a b, (a + b : ℝ).cauchy = a.cauchy + b.cauchy | ⟨a⟩, ⟨b⟩ => show (add _ _).cauchy = _ by rw [add_def] theorem cauchy_neg : ∀ a, (-a : ℝ).cauchy = -a.cauchy | ⟨a⟩ => show (neg _).cauchy = _ by rw [neg_def] theorem cauchy_mul : ∀ a b, (a * b : ℝ).cauchy = a.cauchy * b.cauchy | ⟨a⟩, ⟨b⟩ => show (mul _ _).cauchy = _ by rw [mul_def] theorem cauchy_sub : ∀ a b, (a - b : ℝ).cauchy = a.cauchy - b.cauchy | ⟨a⟩, ⟨b⟩ => by rw [sub_eq_add_neg, ← cauchy_neg, ← cauchy_add] rfl theorem cauchy_inv : ∀ f, (f⁻¹ : ℝ).cauchy = f.cauchy⁻¹ | ⟨f⟩ => show (inv' _).cauchy = _ by rw [inv'] instance instNatCast : NatCast ℝ where natCast n := ⟨n⟩ instance instIntCast : IntCast ℝ where intCast z := ⟨z⟩ instance instNNRatCast : NNRatCast ℝ where nnratCast q := ⟨q⟩ instance instRatCast : RatCast ℝ where ratCast q := ⟨q⟩ lemma ofCauchy_natCast (n : ℕ) : (⟨n⟩ : ℝ) = n := rfl lemma ofCauchy_intCast (z : ℤ) : (⟨z⟩ : ℝ) = z := rfl lemma ofCauchy_nnratCast (q : ℚ≥0) : (⟨q⟩ : ℝ) = q := rfl lemma ofCauchy_ratCast (q : ℚ) : (⟨q⟩ : ℝ) = q := rfl lemma cauchy_natCast (n : ℕ) : (n : ℝ).cauchy = n := rfl lemma cauchy_intCast (z : ℤ) : (z : ℝ).cauchy = z := rfl lemma cauchy_nnratCast (q : ℚ≥0) : (q : ℝ).cauchy = q := rfl lemma cauchy_ratCast (q : ℚ) : (q : ℝ).cauchy = q := rfl instance commRing : CommRing ℝ where natCast n := ⟨n⟩ intCast z := ⟨z⟩ zero := (0 : ℝ) one := (1 : ℝ) mul := (· * ·) add := (· + ·) neg := @Neg.neg ℝ _ sub := @Sub.sub ℝ _ npow := @npowRec ℝ ⟨1⟩ ⟨(· * ·)⟩ nsmul := @nsmulRec ℝ ⟨0⟩ ⟨(· + ·)⟩ zsmul := @zsmulRec ℝ ⟨0⟩ ⟨(· + ·)⟩ ⟨@Neg.neg ℝ _⟩ (@nsmulRec ℝ ⟨0⟩ ⟨(· + ·)⟩) add_zero a := by apply ext_cauchy; simp [cauchy_add, cauchy_zero] zero_add a := by apply ext_cauchy; simp [cauchy_add, cauchy_zero] add_comm a b := by apply ext_cauchy; simp only [cauchy_add, add_comm] add_assoc a b c := by apply ext_cauchy; simp only [cauchy_add, add_assoc] mul_zero a := by apply ext_cauchy; simp [cauchy_mul, cauchy_zero] zero_mul a := by apply ext_cauchy; simp [cauchy_mul, cauchy_zero] mul_one a := by apply ext_cauchy; simp [cauchy_mul, cauchy_one] one_mul a := by apply ext_cauchy; simp [cauchy_mul, cauchy_one] mul_comm a b := by apply ext_cauchy; simp only [cauchy_mul, mul_comm] mul_assoc a b c := by apply ext_cauchy; simp only [cauchy_mul, mul_assoc] left_distrib a b c := by apply ext_cauchy; simp only [cauchy_add, cauchy_mul, mul_add] right_distrib a b c := by apply ext_cauchy; simp only [cauchy_add, cauchy_mul, add_mul] add_left_neg a := by apply ext_cauchy; simp [cauchy_add, cauchy_neg, cauchy_zero] natCast_zero := by apply ext_cauchy; simp [cauchy_zero] natCast_succ n := by apply ext_cauchy; simp [cauchy_one, cauchy_add] intCast_negSucc z := by apply ext_cauchy; simp [cauchy_neg, cauchy_natCast] /-- `Real.equivCauchy` as a ring equivalence. -/ @[simps] def ringEquivCauchy : ℝ ≃+* CauSeq.Completion.Cauchy (abs : ℚ → ℚ) := { equivCauchy with toFun := cauchy invFun := ofCauchy map_add' := cauchy_add map_mul' := cauchy_mul } /-! Extra instances to short-circuit type class resolution. These short-circuits have an additional property of ensuring that a computable path is found; if `Field ℝ` is found first, then decaying it to these typeclasses would result in a `noncomputable` version of them. -/ instance instRing : Ring ℝ := by infer_instance instance : CommSemiring ℝ := by infer_instance instance semiring : Semiring ℝ := by infer_instance instance : CommMonoidWithZero ℝ := by infer_instance instance : MonoidWithZero ℝ := by infer_instance instance : AddCommGroup ℝ := by infer_instance instance : AddGroup ℝ := by infer_instance instance : AddCommMonoid ℝ := by infer_instance instance : AddMonoid ℝ := by infer_instance instance : AddLeftCancelSemigroup ℝ := by infer_instance instance : AddRightCancelSemigroup ℝ := by infer_instance instance : AddCommSemigroup ℝ := by infer_instance instance : AddSemigroup ℝ := by infer_instance instance : CommMonoid ℝ := by infer_instance instance : Monoid ℝ := by infer_instance instance : CommSemigroup ℝ := by infer_instance instance : Semigroup ℝ := by infer_instance instance : Inhabited ℝ := ⟨0⟩ /-- Make a real number from a Cauchy sequence of rationals (by taking the equivalence class). -/ def mk (x : CauSeq ℚ abs) : ℝ := ⟨CauSeq.Completion.mk x⟩ theorem mk_eq {f g : CauSeq ℚ abs} : mk f = mk g ↔ f ≈ g := ext_cauchy_iff.trans CauSeq.Completion.mk_eq private irreducible_def lt : ℝ → ℝ → Prop | ⟨x⟩, ⟨y⟩ => (Quotient.liftOn₂ x y (· < ·)) fun _ _ _ _ hf hg => propext <| ⟨fun h => lt_of_eq_of_lt (Setoid.symm hf) (lt_of_lt_of_eq h hg), fun h => lt_of_eq_of_lt hf (lt_of_lt_of_eq h (Setoid.symm hg))⟩ instance : LT ℝ := ⟨lt⟩ theorem lt_cauchy {f g} : (⟨⟦f⟧⟩ : ℝ) < ⟨⟦g⟧⟩ ↔ f < g := show lt _ _ ↔ _ by rw [lt_def]; rfl @[simp] theorem mk_lt {f g : CauSeq ℚ abs} : mk f < mk g ↔ f < g := lt_cauchy theorem mk_zero : mk 0 = 0 := by rw [← ofCauchy_zero]; rfl theorem mk_one : mk 1 = 1 := by rw [← ofCauchy_one]; rfl theorem mk_add {f g : CauSeq ℚ abs} : mk (f + g) = mk f + mk g := by simp [mk, ← ofCauchy_add] theorem mk_mul {f g : CauSeq ℚ abs} : mk (f * g) = mk f * mk g := by simp [mk, ← ofCauchy_mul] theorem mk_neg {f : CauSeq ℚ abs} : mk (-f) = -mk f := by simp [mk, ← ofCauchy_neg] @[simp] theorem mk_pos {f : CauSeq ℚ abs} : 0 < mk f ↔ Pos f := by rw [← mk_zero, mk_lt] exact iff_of_eq (congr_arg Pos (sub_zero f)) private irreducible_def le (x y : ℝ) : Prop := x < y ∨ x = y instance : LE ℝ := ⟨le⟩ private theorem le_def' {x y : ℝ} : x ≤ y ↔ x < y ∨ x = y := iff_of_eq <| le_def _ _ @[simp] theorem mk_le {f g : CauSeq ℚ abs} : mk f ≤ mk g ↔ f ≤ g := by simp only [le_def', mk_lt, mk_eq]; rfl @[elab_as_elim] protected theorem ind_mk {C : Real → Prop} (x : Real) (h : ∀ y, C (mk y)) : C x := by cases' x with x induction' x using Quot.induction_on with x exact h x theorem add_lt_add_iff_left {a b : ℝ} (c : ℝ) : c + a < c + b ↔ a < b := by induction a using Real.ind_mk induction b using Real.ind_mk induction c using Real.ind_mk simp only [mk_lt, ← mk_add] show Pos _ ↔ Pos _; rw [add_sub_add_left_eq_sub] instance partialOrder : PartialOrder ℝ where le := (· ≤ ·) lt := (· < ·) lt_iff_le_not_le a b := by induction' a using Real.ind_mk with a induction' b using Real.ind_mk with b simpa using lt_iff_le_not_le le_refl a := by induction' a using Real.ind_mk with a rw [mk_le] le_trans a b c := by induction' a using Real.ind_mk with a induction' b using Real.ind_mk with b induction' c using Real.ind_mk with c simpa using le_trans le_antisymm a b := by induction' a using Real.ind_mk with a induction' b using Real.ind_mk with b simpa [mk_eq] using @CauSeq.le_antisymm _ _ a b instance : Preorder ℝ := by infer_instance theorem ratCast_lt {x y : ℚ} : (x : ℝ) < (y : ℝ) ↔ x < y := by erw [mk_lt] exact const_lt protected theorem zero_lt_one : (0 : ℝ) < 1 := by convert ratCast_lt.2 zero_lt_one <;> simp [← ofCauchy_ratCast, ofCauchy_one, ofCauchy_zero] protected theorem fact_zero_lt_one : Fact ((0 : ℝ) < 1) := ⟨Real.zero_lt_one⟩ protected theorem mul_pos {a b : ℝ} : 0 < a → 0 < b → 0 < a * b := by induction' a using Real.ind_mk with a induction' b using Real.ind_mk with b simpa only [mk_lt, mk_pos, ← mk_mul] using CauSeq.mul_pos instance : StrictOrderedCommRing ℝ := { Real.commRing, Real.partialOrder, Real.semiring with exists_pair_ne := ⟨0, 1, Real.zero_lt_one.ne⟩ add_le_add_left := by simp only [le_iff_eq_or_lt] rintro a b ⟨rfl, h⟩ · simp only [lt_self_iff_false, or_false, forall_const] · exact fun c => Or.inr ((add_lt_add_iff_left c).2 ‹_›) zero_le_one := le_of_lt Real.zero_lt_one mul_pos := @Real.mul_pos } instance strictOrderedRing : StrictOrderedRing ℝ := inferInstance instance strictOrderedCommSemiring : StrictOrderedCommSemiring ℝ := inferInstance instance strictOrderedSemiring : StrictOrderedSemiring ℝ := inferInstance instance orderedRing : OrderedRing ℝ := inferInstance instance orderedSemiring : OrderedSemiring ℝ := inferInstance instance orderedAddCommGroup : OrderedAddCommGroup ℝ := inferInstance instance orderedCancelAddCommMonoid : OrderedCancelAddCommMonoid ℝ := inferInstance instance orderedAddCommMonoid : OrderedAddCommMonoid ℝ := inferInstance instance nontrivial : Nontrivial ℝ := inferInstance private irreducible_def sup : ℝ → ℝ → ℝ | ⟨x⟩, ⟨y⟩ => ⟨Quotient.map₂ (· ⊔ ·) (fun _ _ hx _ _ hy => sup_equiv_sup hx hy) x y⟩ instance : Sup ℝ := ⟨sup⟩ theorem ofCauchy_sup (a b) : (⟨⟦a ⊔ b⟧⟩ : ℝ) = ⟨⟦a⟧⟩ ⊔ ⟨⟦b⟧⟩ := show _ = sup _ _ by rw [sup_def] rfl @[simp] theorem mk_sup (a b) : (mk (a ⊔ b) : ℝ) = mk a ⊔ mk b := ofCauchy_sup _ _ private irreducible_def inf : ℝ → ℝ → ℝ | ⟨x⟩, ⟨y⟩ => ⟨Quotient.map₂ (· ⊓ ·) (fun _ _ hx _ _ hy => inf_equiv_inf hx hy) x y⟩ instance : Inf ℝ := ⟨inf⟩ theorem ofCauchy_inf (a b) : (⟨⟦a ⊓ b⟧⟩ : ℝ) = ⟨⟦a⟧⟩ ⊓ ⟨⟦b⟧⟩ := show _ = inf _ _ by rw [inf_def] rfl @[simp] theorem mk_inf (a b) : (mk (a ⊓ b) : ℝ) = mk a ⊓ mk b := ofCauchy_inf _ _ instance : DistribLattice ℝ := { Real.partialOrder with sup := (· ⊔ ·) le := (· ≤ ·) le_sup_left := by intros a b induction' a using Real.ind_mk with a induction' b using Real.ind_mk with b rw [← mk_sup, mk_le] exact CauSeq.le_sup_left le_sup_right := by intros a b induction' a using Real.ind_mk with a induction' b using Real.ind_mk with b rw [← mk_sup, mk_le] exact CauSeq.le_sup_right sup_le := by intros a b c induction' a using Real.ind_mk with a induction' b using Real.ind_mk with b induction' c using Real.ind_mk with c simp_rw [← mk_sup, mk_le] exact CauSeq.sup_le inf := (· ⊓ ·) inf_le_left := by intros a b induction' a using Real.ind_mk with a induction' b using Real.ind_mk with b rw [← mk_inf, mk_le] exact CauSeq.inf_le_left inf_le_right := by intros a b induction' a using Real.ind_mk with a induction' b using Real.ind_mk with b rw [← mk_inf, mk_le] exact CauSeq.inf_le_right le_inf := by intros a b c induction' a using Real.ind_mk with a induction' b using Real.ind_mk with b induction' c using Real.ind_mk with c simp_rw [← mk_inf, mk_le] exact CauSeq.le_inf le_sup_inf := by intros a b c induction' a using Real.ind_mk with a induction' b using Real.ind_mk with b induction' c using Real.ind_mk with c apply Eq.le simp only [← mk_sup, ← mk_inf] exact congr_arg mk (CauSeq.sup_inf_distrib_left _ _ _).symm } -- Extra instances to short-circuit type class resolution instance lattice : Lattice ℝ := inferInstance instance : SemilatticeInf ℝ := inferInstance instance : SemilatticeSup ℝ := inferInstance open scoped Classical instance : IsTotal ℝ (· ≤ ·) := ⟨by intros a b induction' a using Real.ind_mk with a induction' b using Real.ind_mk with b simpa using le_total a b⟩ noncomputable instance linearOrder : LinearOrder ℝ := Lattice.toLinearOrder _ noncomputable instance linearOrderedCommRing : LinearOrderedCommRing ℝ := { Real.nontrivial, Real.strictOrderedRing, Real.commRing, Real.linearOrder with } -- Extra instances to short-circuit type class resolution noncomputable instance : LinearOrderedRing ℝ := by infer_instance noncomputable instance : LinearOrderedSemiring ℝ := by infer_instance instance : IsDomain ℝ := { Real.nontrivial, Real.commRing, LinearOrderedRing.isDomain with } noncomputable instance instDivInvMonoid : DivInvMonoid ℝ where lemma ofCauchy_div (f g) : (⟨f / g⟩ : ℝ) = (⟨f⟩ : ℝ) / (⟨g⟩ : ℝ) := by simp_rw [div_eq_mul_inv, ofCauchy_mul, ofCauchy_inv] noncomputable instance instLinearOrderedField : LinearOrderedField ℝ where toLinearOrderedCommRing := linearOrderedCommRing mul_inv_cancel := by rintro ⟨a⟩ h rw [mul_comm] simp only [← ofCauchy_inv, ← ofCauchy_mul, ← ofCauchy_one, ← ofCauchy_zero, Ne, ofCauchy.injEq] at * exact CauSeq.Completion.inv_mul_cancel h inv_zero := by simp [← ofCauchy_zero, ← ofCauchy_inv] nnqsmul := _ nnqsmul_def := fun q a => rfl qsmul := _ qsmul_def := fun q a => rfl nnratCast_def q := by rw [← ofCauchy_nnratCast, NNRat.cast_def, ofCauchy_div, ofCauchy_natCast, ofCauchy_natCast] ratCast_def q := by rw [← ofCauchy_ratCast, Rat.cast_def, ofCauchy_div, ofCauchy_natCast, ofCauchy_intCast] -- Extra instances to short-circuit type class resolution noncomputable instance : LinearOrderedAddCommGroup ℝ := by infer_instance noncomputable instance field : Field ℝ := by infer_instance noncomputable instance : DivisionRing ℝ := by infer_instance noncomputable instance decidableLT (a b : ℝ) : Decidable (a < b) := by infer_instance noncomputable instance decidableLE (a b : ℝ) : Decidable (a ≤ b) := by infer_instance noncomputable instance decidableEq (a b : ℝ) : Decidable (a = b) := by infer_instance /-- Show an underlying cauchy sequence for real numbers. The representative chosen is the one passed in the VM to `Quot.mk`, so two cauchy sequences converging to the same number may be printed differently. -/ unsafe instance : Repr ℝ where reprPrec r _ := "Real.ofCauchy " ++ repr r.cauchy theorem le_mk_of_forall_le {f : CauSeq ℚ abs} : (∃ i, ∀ j ≥ i, x ≤ f j) → x ≤ mk f := by intro h induction' x using Real.ind_mk with x apply le_of_not_lt rw [mk_lt] rintro ⟨K, K0, hK⟩ obtain ⟨i, H⟩ := exists_forall_ge_and h (exists_forall_ge_and hK (f.cauchy₃ <| half_pos K0)) apply not_lt_of_le (H _ le_rfl).1 erw [mk_lt] refine ⟨_, half_pos K0, i, fun j ij => ?_⟩ have := add_le_add (H _ ij).2.1 (le_of_lt (abs_lt.1 <| (H _ le_rfl).2.2 _ ij).1) rwa [← sub_eq_add_neg, sub_self_div_two, sub_apply, sub_add_sub_cancel] at this theorem mk_le_of_forall_le {f : CauSeq ℚ abs} {x : ℝ} (h : ∃ i, ∀ j ≥ i, (f j : ℝ) ≤ x) : mk f ≤ x := by cases' h with i H rw [← neg_le_neg_iff, ← mk_neg] exact le_mk_of_forall_le ⟨i, fun j ij => by simp [H _ ij]⟩ theorem mk_near_of_forall_near {f : CauSeq ℚ abs} {x : ℝ} {ε : ℝ} (H : ∃ i, ∀ j ≥ i, |(f j : ℝ) - x| ≤ ε) : |mk f - x| ≤ ε := abs_sub_le_iff.2 ⟨sub_le_iff_le_add'.2 <| mk_le_of_forall_le <| H.imp fun _ h j ij => sub_le_iff_le_add'.1 (abs_sub_le_iff.1 <| h j ij).1, sub_le_comm.1 <| le_mk_of_forall_le <| H.imp fun _ h j ij => sub_le_comm.1 (abs_sub_le_iff.1 <| h j ij).2⟩ lemma mul_add_one_le_add_one_pow {a : ℝ} (ha : 0 ≤ a) (b : ℕ) : a * b + 1 ≤ (a + 1) ^ b := by rcases ha.eq_or_lt with rfl|ha' · simp clear ha induction b generalizing a with | zero => simp | succ b hb => rw [Nat.cast_add_one, mul_add, mul_one, add_right_comm, pow_succ, mul_add, mul_one, add_comm] gcongr · rw [le_mul_iff_one_le_left ha'] exact (pow_le_pow_left zero_le_one (by simpa using ha'.le) b).trans' (by simp) · exact hb ha' end Real /-- A function `f : R → ℝ≥0` is nonarchimedean if it satisfies the strong triangle inequality `f (r + s) ≤ max (f r) (f s)` for all `r s : R`. -/ def IsNonarchimedean {A : Type*} [Add A] (f : A → ℝ) : Prop := ∀ r s, f (r + s) ≤ max (f r) (f s) /-- A function `f : R → ℝ` is power-multiplicative if for all `r ∈ R` and all positive `n ∈ ℕ`, `f (r ^ n) = (f r) ^ n`. -/ def IsPowMul {R : Type*} [Pow R ℕ] (f : R → ℝ) := ∀ (a : R) {n : ℕ}, 1 ≤ n → f (a ^ n) = f a ^ n
Data\Real\Cardinality.lean
/- Copyright (c) 2019 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import Mathlib.Analysis.SpecificLimits.Basic import Mathlib.Data.Rat.Denumerable import Mathlib.Data.Set.Pointwise.Interval import Mathlib.SetTheory.Cardinal.Continuum /-! # The cardinality of the reals This file shows that the real numbers have cardinality continuum, i.e. `#ℝ = 𝔠`. We show that `#ℝ ≤ 𝔠` by noting that every real number is determined by a Cauchy-sequence of the form `ℕ → ℚ`, which has cardinality `𝔠`. To show that `#ℝ ≥ 𝔠` we define an injection from `{0, 1} ^ ℕ` to `ℝ` with `f ↦ Σ n, f n * (1 / 3) ^ n`. We conclude that all intervals with distinct endpoints have cardinality continuum. ## Main definitions * `Cardinal.cantorFunction` is the function that sends `f` in `{0, 1} ^ ℕ` to `ℝ` by `f ↦ Σ' n, f n * (1 / 3) ^ n` ## Main statements * `Cardinal.mk_real : #ℝ = 𝔠`: the reals have cardinality continuum. * `Cardinal.not_countable_real`: the universal set of real numbers is not countable. We can use this same proof to show that all the other sets in this file are not countable. * 8 lemmas of the form `mk_Ixy_real` for `x,y ∈ {i,o,c}` state that intervals on the reals have cardinality continuum. ## Notation * `𝔠` : notation for `Cardinal.Continuum` in locale `Cardinal`, defined in `SetTheory.Continuum`. ## Tags continuum, cardinality, reals, cardinality of the reals -/ open Nat Set open Cardinal noncomputable section namespace Cardinal variable {c : ℝ} {f g : ℕ → Bool} {n : ℕ} /-- The body of the sum in `cantorFunction`. `cantorFunctionAux c f n = c ^ n` if `f n = true`; `cantorFunctionAux c f n = 0` if `f n = false`. -/ def cantorFunctionAux (c : ℝ) (f : ℕ → Bool) (n : ℕ) : ℝ := cond (f n) (c ^ n) 0 @[simp] theorem cantorFunctionAux_true (h : f n = true) : cantorFunctionAux c f n = c ^ n := by simp [cantorFunctionAux, h] @[simp] theorem cantorFunctionAux_false (h : f n = false) : cantorFunctionAux c f n = 0 := by simp [cantorFunctionAux, h] theorem cantorFunctionAux_nonneg (h : 0 ≤ c) : 0 ≤ cantorFunctionAux c f n := by cases h' : f n · simp [h'] · simpa [h'] using pow_nonneg h _ theorem cantorFunctionAux_eq (h : f n = g n) : cantorFunctionAux c f n = cantorFunctionAux c g n := by simp [cantorFunctionAux, h] theorem cantorFunctionAux_zero (f : ℕ → Bool) : cantorFunctionAux c f 0 = cond (f 0) 1 0 := by cases h : f 0 <;> simp [h] theorem cantorFunctionAux_succ (f : ℕ → Bool) : (fun n => cantorFunctionAux c f (n + 1)) = fun n => c * cantorFunctionAux c (fun n => f (n + 1)) n := by ext n cases h : f (n + 1) <;> simp [h, _root_.pow_succ'] theorem summable_cantor_function (f : ℕ → Bool) (h1 : 0 ≤ c) (h2 : c < 1) : Summable (cantorFunctionAux c f) := by apply (summable_geometric_of_lt_one h1 h2).summable_of_eq_zero_or_self intro n; cases h : f n <;> simp [h] /-- `cantorFunction c (f : ℕ → Bool)` is `Σ n, f n * c ^ n`, where `true` is interpreted as `1` and `false` is interpreted as `0`. It is implemented using `cantorFunctionAux`. -/ def cantorFunction (c : ℝ) (f : ℕ → Bool) : ℝ := ∑' n, cantorFunctionAux c f n theorem cantorFunction_le (h1 : 0 ≤ c) (h2 : c < 1) (h3 : ∀ n, f n → g n) : cantorFunction c f ≤ cantorFunction c g := by apply tsum_le_tsum _ (summable_cantor_function f h1 h2) (summable_cantor_function g h1 h2) intro n; cases h : f n · simp [h, cantorFunctionAux_nonneg h1] replace h3 : g n = true := h3 n h; simp [h, h3] theorem cantorFunction_succ (f : ℕ → Bool) (h1 : 0 ≤ c) (h2 : c < 1) : cantorFunction c f = cond (f 0) 1 0 + c * cantorFunction c fun n => f (n + 1) := by rw [cantorFunction, tsum_eq_zero_add (summable_cantor_function f h1 h2)] rw [cantorFunctionAux_succ, tsum_mul_left, cantorFunctionAux, _root_.pow_zero] rfl /-- `cantorFunction c` is strictly increasing with if `0 < c < 1/2`, if we endow `ℕ → Bool` with a lexicographic order. The lexicographic order doesn't exist for these infinitary products, so we explicitly write out what it means. -/ theorem increasing_cantorFunction (h1 : 0 < c) (h2 : c < 1 / 2) {n : ℕ} {f g : ℕ → Bool} (hn : ∀ k < n, f k = g k) (fn : f n = false) (gn : g n = true) : cantorFunction c f < cantorFunction c g := by have h3 : c < 1 := by apply h2.trans norm_num induction' n with n ih generalizing f g · let f_max : ℕ → Bool := fun n => Nat.rec false (fun _ _ => true) n have hf_max : ∀ n, f n → f_max n := by intro n hn cases n · rw [fn] at hn contradiction apply rfl let g_min : ℕ → Bool := fun n => Nat.rec true (fun _ _ => false) n have hg_min : ∀ n, g_min n → g n := by intro n hn cases n · rw [gn] simp at hn apply (cantorFunction_le (le_of_lt h1) h3 hf_max).trans_lt refine lt_of_lt_of_le ?_ (cantorFunction_le (le_of_lt h1) h3 hg_min) have : c / (1 - c) < 1 := by rw [div_lt_one, lt_sub_iff_add_lt] · convert _root_.add_lt_add h2 h2 norm_num rwa [sub_pos] convert this · rw [cantorFunction_succ _ (le_of_lt h1) h3, div_eq_mul_inv, ← tsum_geometric_of_lt_one (le_of_lt h1) h3] apply zero_add · refine (tsum_eq_single 0 ?_).trans ?_ · intro n hn cases n · contradiction rfl · exact cantorFunctionAux_zero _ rw [cantorFunction_succ f (le_of_lt h1) h3, cantorFunction_succ g (le_of_lt h1) h3] rw [hn 0 <| zero_lt_succ n] apply add_lt_add_left rw [mul_lt_mul_left h1] exact ih (fun k hk => hn _ <| Nat.succ_lt_succ hk) fn gn /-- `cantorFunction c` is injective if `0 < c < 1/2`. -/ theorem cantorFunction_injective (h1 : 0 < c) (h2 : c < 1 / 2) : Function.Injective (cantorFunction c) := by intro f g hfg classical by_contra h revert hfg have : ∃ n, f n ≠ g n := by rw [← not_forall] intro h' apply h ext apply h' let n := Nat.find this have hn : ∀ k : ℕ, k < n → f k = g k := by intro k hk apply of_not_not exact Nat.find_min this hk cases fn : f n · apply _root_.ne_of_lt refine increasing_cantorFunction h1 h2 hn fn ?_ apply Bool.eq_true_of_not_eq_false rw [← fn] apply Ne.symm exact Nat.find_spec this · apply _root_.ne_of_gt refine increasing_cantorFunction h1 h2 (fun k hk => (hn k hk).symm) ?_ fn apply Bool.eq_false_of_not_eq_true rw [← fn] apply Ne.symm exact Nat.find_spec this /-- The cardinality of the reals, as a type. -/ theorem mk_real : #ℝ = 𝔠 := by apply le_antisymm · rw [Real.equivCauchy.cardinal_eq] apply mk_quotient_le.trans apply (mk_subtype_le _).trans_eq rw [← power_def, mk_nat, mkRat, aleph0_power_aleph0] · convert mk_le_of_injective (cantorFunction_injective _ _) · rw [← power_def, mk_bool, mk_nat, two_power_aleph0] · exact 1 / 3 · norm_num · norm_num /-- The cardinality of the reals, as a set. -/ theorem mk_univ_real : #(Set.univ : Set ℝ) = 𝔠 := by rw [mk_univ, mk_real] /-- **Non-Denumerability of the Continuum**: The reals are not countable. -/ theorem not_countable_real : ¬(Set.univ : Set ℝ).Countable := by rw [← le_aleph0_iff_set_countable, not_le, mk_univ_real] apply cantor /-- The cardinality of the interval (a, ∞). -/ theorem mk_Ioi_real (a : ℝ) : #(Ioi a) = 𝔠 := by refine le_antisymm (mk_real ▸ mk_set_le _) ?_ rw [← not_lt] intro h refine _root_.ne_of_lt ?_ mk_univ_real have hu : Iio a ∪ {a} ∪ Ioi a = Set.univ := by convert @Iic_union_Ioi ℝ _ _ exact Iio_union_right rw [← hu] refine lt_of_le_of_lt (mk_union_le _ _) ?_ refine lt_of_le_of_lt (add_le_add_right (mk_union_le _ _) _) ?_ have h2 : (fun x => a + a - x) '' Ioi a = Iio a := by convert @image_const_sub_Ioi ℝ _ _ _ simp rw [← h2] refine add_lt_of_lt (cantor _).le ?_ h refine add_lt_of_lt (cantor _).le (mk_image_le.trans_lt h) ?_ rw [mk_singleton] exact one_lt_aleph0.trans (cantor _) /-- The cardinality of the interval [a, ∞). -/ theorem mk_Ici_real (a : ℝ) : #(Ici a) = 𝔠 := le_antisymm (mk_real ▸ mk_set_le _) (mk_Ioi_real a ▸ mk_le_mk_of_subset Ioi_subset_Ici_self) /-- The cardinality of the interval (-∞, a). -/ theorem mk_Iio_real (a : ℝ) : #(Iio a) = 𝔠 := by refine le_antisymm (mk_real ▸ mk_set_le _) ?_ have h2 : (fun x => a + a - x) '' Iio a = Ioi a := by simp only [image_const_sub_Iio, add_sub_cancel_right] exact mk_Ioi_real a ▸ h2 ▸ mk_image_le /-- The cardinality of the interval (-∞, a]. -/ theorem mk_Iic_real (a : ℝ) : #(Iic a) = 𝔠 := le_antisymm (mk_real ▸ mk_set_le _) (mk_Iio_real a ▸ mk_le_mk_of_subset Iio_subset_Iic_self) /-- The cardinality of the interval (a, b). -/ theorem mk_Ioo_real {a b : ℝ} (h : a < b) : #(Ioo a b) = 𝔠 := by refine le_antisymm (mk_real ▸ mk_set_le _) ?_ have h1 : #((fun x => x - a) '' Ioo a b) ≤ #(Ioo a b) := mk_image_le refine le_trans ?_ h1 rw [image_sub_const_Ioo, sub_self] replace h := sub_pos_of_lt h have h2 : #(Inv.inv '' Ioo 0 (b - a)) ≤ #(Ioo 0 (b - a)) := mk_image_le refine le_trans ?_ h2 rw [image_inv, inv_Ioo_0_left h, mk_Ioi_real] /-- The cardinality of the interval [a, b). -/ theorem mk_Ico_real {a b : ℝ} (h : a < b) : #(Ico a b) = 𝔠 := le_antisymm (mk_real ▸ mk_set_le _) (mk_Ioo_real h ▸ mk_le_mk_of_subset Ioo_subset_Ico_self) /-- The cardinality of the interval [a, b]. -/ theorem mk_Icc_real {a b : ℝ} (h : a < b) : #(Icc a b) = 𝔠 := le_antisymm (mk_real ▸ mk_set_le _) (mk_Ioo_real h ▸ mk_le_mk_of_subset Ioo_subset_Icc_self) /-- The cardinality of the interval (a, b]. -/ theorem mk_Ioc_real {a b : ℝ} (h : a < b) : #(Ioc a b) = 𝔠 := le_antisymm (mk_real ▸ mk_set_le _) (mk_Ioo_real h ▸ mk_le_mk_of_subset Ioo_subset_Ioc_self) end Cardinal
Data\Real\ConjExponents.lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel, Yury Kudryashov -/ import Mathlib.Data.ENNReal.Real /-! # Real conjugate exponents This file defines conjugate exponents in `ℝ` and `ℝ≥0`. Real numbers `p` and `q` are *conjugate* if they are both greater than `1` and satisfy `p⁻¹ + q⁻¹ = 1`. This property shows up often in analysis, especially when dealing with `L^p` spaces. ## Main declarations * `Real.IsConjExponent`: Predicate for two real numbers to be conjugate. * `Real.conjExponent`: Conjugate exponent of a real number. * `NNReal.IsConjExponent`: Predicate for two nonnegative real numbers to be conjugate. * `NNReal.conjExponent`: Conjugate exponent of a nonnegative real number. ## TODO * Eradicate the `1 / p` spelling in lemmas. * Do we want an `ℝ≥0∞` version? -/ noncomputable section open scoped ENNReal namespace Real /-- Two real exponents `p, q` are conjugate if they are `> 1` and satisfy the equality `1/p + 1/q = 1`. This condition shows up in many theorems in analysis, notably related to `L^p` norms. -/ @[mk_iff] structure IsConjExponent (p q : ℝ) : Prop where one_lt : 1 < p inv_add_inv_conj : p⁻¹ + q⁻¹ = 1 /-- The conjugate exponent of `p` is `q = p/(p-1)`, so that `1/p + 1/q = 1`. -/ def conjExponent (p : ℝ) : ℝ := p / (p - 1) variable {a b p q : ℝ} (h : p.IsConjExponent q) namespace IsConjExponent /- Register several non-vanishing results following from the fact that `p` has a conjugate exponent `q`: many computations using these exponents require clearing out denominators, which can be done with `field_simp` given a proof that these denominators are non-zero, so we record the most usual ones. -/ theorem pos : 0 < p := lt_trans zero_lt_one h.one_lt theorem nonneg : 0 ≤ p := le_of_lt h.pos theorem ne_zero : p ≠ 0 := ne_of_gt h.pos theorem sub_one_pos : 0 < p - 1 := sub_pos.2 h.one_lt theorem sub_one_ne_zero : p - 1 ≠ 0 := ne_of_gt h.sub_one_pos protected lemma inv_pos : 0 < p⁻¹ := inv_pos.2 h.pos protected lemma inv_nonneg : 0 ≤ p⁻¹ := h.inv_pos.le protected lemma inv_ne_zero : p⁻¹ ≠ 0 := h.inv_pos.ne' theorem one_div_pos : 0 < 1 / p := _root_.one_div_pos.2 h.pos theorem one_div_nonneg : 0 ≤ 1 / p := le_of_lt h.one_div_pos theorem one_div_ne_zero : 1 / p ≠ 0 := ne_of_gt h.one_div_pos theorem conj_eq (h : p.IsConjExponent q) : q = p / (p - 1) := by have := h.inv_add_inv_conj rw [← eq_sub_iff_add_eq', inv_eq_iff_eq_inv] at this field_simp [this, h.ne_zero] lemma conjExponent_eq : conjExponent p = q := h.conj_eq.symm lemma one_sub_inv : 1 - p⁻¹ = q⁻¹ := sub_eq_of_eq_add' h.inv_add_inv_conj.symm lemma inv_sub_one : p⁻¹ - 1 = -q⁻¹ := by rw [← h.inv_add_inv_conj, sub_add_cancel_left] theorem sub_one_mul_conj : (p - 1) * q = p := mul_comm q (p - 1) ▸ (eq_div_iff h.sub_one_ne_zero).1 h.conj_eq theorem mul_eq_add : p * q = p + q := by simpa only [sub_mul, sub_eq_iff_eq_add, one_mul] using h.sub_one_mul_conj @[symm] protected lemma symm (h : p.IsConjExponent q) : q.IsConjExponent p where one_lt := by simpa only [h.conj_eq] using (one_lt_div h.sub_one_pos).mpr (sub_one_lt p) inv_add_inv_conj := by simpa [add_comm] using h.inv_add_inv_conj theorem div_conj_eq_sub_one : p / q = p - 1 := by field_simp [h.symm.ne_zero] rw [h.sub_one_mul_conj] theorem inv_add_inv_conj_ennreal : (ENNReal.ofReal p)⁻¹ + (ENNReal.ofReal q)⁻¹ = 1 := by rw [← ENNReal.ofReal_one, ← ENNReal.ofReal_inv_of_pos h.pos, ← ENNReal.ofReal_inv_of_pos h.symm.pos, ← ENNReal.ofReal_add h.inv_nonneg h.symm.inv_nonneg, h.inv_add_inv_conj] protected lemma inv_inv (ha : 0 < a) (hb : 0 < b) (hab : a + b = 1) : a⁻¹.IsConjExponent b⁻¹ := ⟨one_lt_inv ha $ by linarith, by simpa only [inv_inv]⟩ lemma inv_one_sub_inv (ha₀ : 0 < a) (ha₁ : a < 1) : a⁻¹.IsConjExponent (1 - a)⁻¹ := .inv_inv ha₀ (sub_pos_of_lt ha₁) $ add_tsub_cancel_of_le ha₁.le lemma one_sub_inv_inv (ha₀ : 0 < a) (ha₁ : a < 1) : (1 - a)⁻¹.IsConjExponent a⁻¹ := (inv_one_sub_inv ha₀ ha₁).symm end IsConjExponent lemma isConjExponent_iff_eq_conjExponent (hp : 1 < p) : p.IsConjExponent q ↔ q = p / (p - 1) := ⟨IsConjExponent.conj_eq, fun h ↦ ⟨hp, by field_simp [h]⟩⟩ lemma IsConjExponent.conjExponent (h : 1 < p) : p.IsConjExponent (conjExponent p) := (isConjExponent_iff_eq_conjExponent h).2 rfl lemma isConjExponent_one_div (ha : 0 < a) (hb : 0 < b) (hab : a + b = 1) : (1 / a).IsConjExponent (1 / b) := by simpa using IsConjExponent.inv_inv ha hb hab end Real namespace NNReal /-- Two nonnegative real exponents `p, q` are conjugate if they are `> 1` and satisfy the equality `1/p + 1/q = 1`. This condition shows up in many theorems in analysis, notably related to `L^p` norms. -/ @[mk_iff] structure IsConjExponent (p q : ℝ≥0) : Prop where one_lt : 1 < p inv_add_inv_conj : p⁻¹ + q⁻¹ = 1 /-- The conjugate exponent of `p` is `q = p/(p-1)`, so that `1/p + 1/q = 1`. -/ noncomputable def conjExponent (p : ℝ≥0) : ℝ≥0 := p / (p - 1) variable {a b p q : ℝ≥0} (h : p.IsConjExponent q) @[simp, norm_cast] lemma isConjExponent_coe : (p : ℝ).IsConjExponent q ↔ p.IsConjExponent q := by simp [Real.isConjExponent_iff, isConjExponent_iff]; norm_cast; simp alias ⟨_, IsConjExponent.coe⟩ := isConjExponent_coe namespace IsConjExponent /- Register several non-vanishing results following from the fact that `p` has a conjugate exponent `q`: many computations using these exponents require clearing out denominators, which can be done with `field_simp` given a proof that these denominators are non-zero, so we record the most usual ones. -/ lemma one_le : 1 ≤ p := h.one_lt.le lemma pos : 0 < p := zero_lt_one.trans h.one_lt lemma ne_zero : p ≠ 0 := h.pos.ne' lemma sub_one_pos : 0 < p - 1 := tsub_pos_of_lt h.one_lt lemma sub_one_ne_zero : p - 1 ≠ 0 := h.sub_one_pos.ne' lemma inv_pos : 0 < p⁻¹ := _root_.inv_pos.2 h.pos lemma inv_ne_zero : p⁻¹ ≠ 0 := h.inv_pos.ne' lemma one_sub_inv : 1 - p⁻¹ = q⁻¹ := tsub_eq_of_eq_add_rev h.inv_add_inv_conj.symm lemma conj_eq (h : p.IsConjExponent q) : q = p / (p - 1) := by simpa only [← coe_one, ← NNReal.coe_sub h.one_le, ← NNReal.coe_div, coe_inj] using h.coe.conj_eq lemma conjExponent_eq : conjExponent p = q := h.conj_eq.symm lemma sub_one_mul_conj : (p - 1) * q = p := mul_comm q (p - 1) ▸ (eq_div_iff h.sub_one_ne_zero).1 h.conj_eq lemma mul_eq_add : p * q = p + q := by simpa only [← NNReal.coe_mul, ← NNReal.coe_add, NNReal.coe_inj] using h.coe.mul_eq_add @[symm] protected lemma symm (h : p.IsConjExponent q) : q.IsConjExponent p where one_lt := by rw [h.conj_eq] exact (one_lt_div h.sub_one_pos).mpr (tsub_lt_self h.pos zero_lt_one) inv_add_inv_conj := by simpa [add_comm] using h.inv_add_inv_conj lemma div_conj_eq_sub_one : p / q = p - 1 := by field_simp [h.symm.ne_zero]; rw [h.sub_one_mul_conj] lemma inv_add_inv_conj_ennreal : (p⁻¹ + q⁻¹ : ℝ≥0∞) = 1 := by norm_cast; exact h.inv_add_inv_conj protected lemma inv_inv (ha : a ≠ 0) (hb : b ≠ 0) (hab : a + b = 1) : a⁻¹.IsConjExponent b⁻¹ := ⟨one_lt_inv ha.bot_lt $ by rw [← hab]; exact lt_add_of_pos_right _ hb.bot_lt, by simpa only [inv_inv] using hab⟩ lemma inv_one_sub_inv (ha₀ : a ≠ 0) (ha₁ : a < 1) : a⁻¹.IsConjExponent (1 - a)⁻¹ := .inv_inv ha₀ (tsub_pos_of_lt ha₁).ne' $ add_tsub_cancel_of_le ha₁.le lemma one_sub_inv_inv (ha₀ : a ≠ 0) (ha₁ : a < 1) : (1 - a)⁻¹.IsConjExponent a⁻¹ := (inv_one_sub_inv ha₀ ha₁).symm end IsConjExponent lemma isConjExponent_iff_eq_conjExponent (h : 1 < p) : p.IsConjExponent q ↔ q = p / (p - 1) := by rw [← isConjExponent_coe, Real.isConjExponent_iff_eq_conjExponent (mod_cast h), ← coe_inj, NNReal.coe_div, NNReal.coe_sub h.le, coe_one] protected lemma IsConjExponent.conjExponent (h : 1 < p) : p.IsConjExponent (conjExponent p) := (isConjExponent_iff_eq_conjExponent h).2 rfl end NNReal protected lemma Real.IsConjExponent.toNNReal {p q : ℝ} (hpq : p.IsConjExponent q) : p.toNNReal.IsConjExponent q.toNNReal where one_lt := by simpa using hpq.one_lt inv_add_inv_conj := by rw [← toNNReal_inv, ← toNNReal_inv, ← toNNReal_add hpq.inv_nonneg hpq.symm.inv_nonneg, hpq.inv_add_inv_conj, toNNReal_one]
Data\Real\ENatENNReal.lean
/- Copyright (c) 2022 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import Mathlib.Data.ENat.Basic import Mathlib.Data.ENNReal.Basic /-! # Coercion from `ℕ∞` to `ℝ≥0∞` In this file we define a coercion from `ℕ∞` to `ℝ≥0∞` and prove some basic lemmas about this map. -/ open scoped Classical open NNReal ENNReal noncomputable section namespace ENat variable {m n : ℕ∞} /-- Coercion from `ℕ∞` to `ℝ≥0∞`. -/ @[coe] def toENNReal : ℕ∞ → ℝ≥0∞ := WithTop.map Nat.cast instance hasCoeENNReal : CoeTC ℕ∞ ℝ≥0∞ := ⟨toENNReal⟩ @[simp] theorem map_coe_nnreal : WithTop.map ((↑) : ℕ → ℝ≥0) = ((↑) : ℕ∞ → ℝ≥0∞) := rfl /-- Coercion `ℕ∞ → ℝ≥0∞` as an `OrderEmbedding`. -/ @[simps! (config := .asFn)] def toENNRealOrderEmbedding : ℕ∞ ↪o ℝ≥0∞ := Nat.castOrderEmbedding.withTopMap /-- Coercion `ℕ∞ → ℝ≥0∞` as a ring homomorphism. -/ @[simps! (config := .asFn)] def toENNRealRingHom : ℕ∞ →+* ℝ≥0∞ := .withTopMap (Nat.castRingHom ℝ≥0) Nat.cast_injective @[simp, norm_cast] theorem toENNReal_top : ((⊤ : ℕ∞) : ℝ≥0∞) = ⊤ := rfl @[simp, norm_cast] theorem toENNReal_coe (n : ℕ) : ((n : ℕ∞) : ℝ≥0∞) = n := rfl -- See note [no_index around OfNat.ofNat] @[simp, norm_cast] theorem toENNReal_ofNat (n : ℕ) [n.AtLeastTwo] : ((no_index (OfNat.ofNat n : ℕ∞)) : ℝ≥0∞) = OfNat.ofNat n := rfl @[simp, norm_cast] theorem toENNReal_coe_eq_iff : (m : ℝ≥0∞) = (n : ℝ≥0∞) ↔ m = n := toENNRealOrderEmbedding.eq_iff_eq @[simp, norm_cast] theorem toENNReal_le : (m : ℝ≥0∞) ≤ n ↔ m ≤ n := toENNRealOrderEmbedding.le_iff_le @[simp, norm_cast] theorem toENNReal_lt : (m : ℝ≥0∞) < n ↔ m < n := toENNRealOrderEmbedding.lt_iff_lt @[mono] theorem toENNReal_mono : Monotone ((↑) : ℕ∞ → ℝ≥0∞) := toENNRealOrderEmbedding.monotone @[mono] theorem toENNReal_strictMono : StrictMono ((↑) : ℕ∞ → ℝ≥0∞) := toENNRealOrderEmbedding.strictMono @[simp, norm_cast] theorem toENNReal_zero : ((0 : ℕ∞) : ℝ≥0∞) = 0 := map_zero toENNRealRingHom @[simp, norm_cast] theorem toENNReal_add (m n : ℕ∞) : ↑(m + n) = (m + n : ℝ≥0∞) := map_add toENNRealRingHom m n @[simp, norm_cast] theorem toENNReal_one : ((1 : ℕ∞) : ℝ≥0∞) = 1 := map_one toENNRealRingHom @[simp, norm_cast] theorem toENNReal_mul (m n : ℕ∞) : ↑(m * n) = (m * n : ℝ≥0∞) := map_mul toENNRealRingHom m n @[simp, norm_cast] theorem toENNReal_pow (x : ℕ∞) (n : ℕ) : (x ^ n : ℕ∞) = (x : ℝ≥0∞) ^ n := RingHom.map_pow toENNRealRingHom x n @[simp, norm_cast] theorem toENNReal_min (m n : ℕ∞) : ↑(min m n) = (min m n : ℝ≥0∞) := toENNReal_mono.map_min @[simp, norm_cast] theorem toENNReal_max (m n : ℕ∞) : ↑(max m n) = (max m n : ℝ≥0∞) := toENNReal_mono.map_max @[simp, norm_cast] theorem toENNReal_sub (m n : ℕ∞) : ↑(m - n) = (m - n : ℝ≥0∞) := WithTop.map_sub Nat.cast_tsub Nat.cast_zero m n end ENat
Data\Real\EReal.lean
/- Copyright (c) 2019 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard -/ import Mathlib.Data.Real.Basic import Mathlib.Data.ENNReal.Real import Mathlib.Data.Sign /-! # The extended reals [-∞, ∞]. This file defines `EReal`, the real numbers together with a top and bottom element, referred to as ⊤ and ⊥. It is implemented as `WithBot (WithTop ℝ)` Addition and multiplication are problematic in the presence of ±∞, but negation has a natural definition and satisfies the usual properties. An ad hoc addition is defined, for which `EReal` is an `AddCommMonoid`, and even an ordered one (if `a ≤ a'` and `b ≤ b'` then `a + b ≤ a' + b'`). Note however that addition is badly behaved at `(⊥, ⊤)` and `(⊤, ⊥)` so this can not be upgraded to a group structure. Our choice is that `⊥ + ⊤ = ⊤ + ⊥ = ⊥`, to make sure that the exponential and the logarithm between `EReal` and `ℝ≥0∞` respect the operations (notice that the convention `0 * ∞ = 0` on `ℝ≥0∞` is enforced by measure theory). An ad hoc subtraction is then defined by `x - y = x + (-y)`. It does not have nice properties, but it is sometimes convenient to have. An ad hoc multiplication is defined, for which `EReal` is a `CommMonoidWithZero`. We make the choice that `0 * x = x * 0 = 0` for any `x` (while the other cases are defined non-ambiguously). This does not distribute with addition, as `⊥ = ⊥ + ⊤ = 1*⊥ + (-1)*⊥ ≠ (1 - 1) * ⊥ = 0 * ⊥ = 0`. `EReal` is a `CompleteLinearOrder`; this is deduced by type class inference from the fact that `WithBot (WithTop L)` is a complete linear order if `L` is a conditionally complete linear order. Coercions from `ℝ` and from `ℝ≥0∞` are registered, and their basic properties are proved. The main one is the real coercion, and is usually referred to just as `coe` (lemmas such as `EReal.coe_add` deal with this coercion). The one from `ENNReal` is usually called `coe_ennreal` in the `EReal` namespace. We define an absolute value `EReal.abs` from `EReal` to `ℝ≥0∞`. Two elements of `EReal` coincide if and only if they have the same absolute value and the same sign. ## Tags real, ereal, complete lattice -/ open Function ENNReal NNReal Set SignType noncomputable section /-- ereal : The type `[-∞, ∞]` -/ def EReal := WithBot (WithTop ℝ) deriving Bot, Zero, One, Nontrivial, AddMonoid, PartialOrder instance : ZeroLEOneClass EReal := inferInstanceAs (ZeroLEOneClass (WithBot (WithTop ℝ))) instance : SupSet EReal := inferInstanceAs (SupSet (WithBot (WithTop ℝ))) instance : InfSet EReal := inferInstanceAs (InfSet (WithBot (WithTop ℝ))) instance : CompleteLinearOrder EReal := inferInstanceAs (CompleteLinearOrder (WithBot (WithTop ℝ))) instance : LinearOrderedAddCommMonoid EReal := inferInstanceAs (LinearOrderedAddCommMonoid (WithBot (WithTop ℝ))) instance : AddCommMonoidWithOne EReal := inferInstanceAs (AddCommMonoidWithOne (WithBot (WithTop ℝ))) instance : DenselyOrdered EReal := inferInstanceAs (DenselyOrdered (WithBot (WithTop ℝ))) /-- The canonical inclusion from reals to ereals. Registered as a coercion. -/ @[coe] def Real.toEReal : ℝ → EReal := some ∘ some namespace EReal -- things unify with `WithBot.decidableLT` later if we don't provide this explicitly. instance decidableLT : DecidableRel ((· < ·) : EReal → EReal → Prop) := WithBot.decidableLT -- TODO: Provide explicitly, otherwise it is inferred noncomputably from `CompleteLinearOrder` instance : Top EReal := ⟨some ⊤⟩ instance : Coe ℝ EReal := ⟨Real.toEReal⟩ theorem coe_strictMono : StrictMono Real.toEReal := WithBot.coe_strictMono.comp WithTop.coe_strictMono theorem coe_injective : Injective Real.toEReal := coe_strictMono.injective @[simp, norm_cast] protected theorem coe_le_coe_iff {x y : ℝ} : (x : EReal) ≤ (y : EReal) ↔ x ≤ y := coe_strictMono.le_iff_le @[simp, norm_cast] protected theorem coe_lt_coe_iff {x y : ℝ} : (x : EReal) < (y : EReal) ↔ x < y := coe_strictMono.lt_iff_lt @[simp, norm_cast] protected theorem coe_eq_coe_iff {x y : ℝ} : (x : EReal) = (y : EReal) ↔ x = y := coe_injective.eq_iff protected theorem coe_ne_coe_iff {x y : ℝ} : (x : EReal) ≠ (y : EReal) ↔ x ≠ y := coe_injective.ne_iff /-- The canonical map from nonnegative extended reals to extended reals -/ @[coe] def _root_.ENNReal.toEReal : ℝ≥0∞ → EReal | ⊤ => ⊤ | .some x => x.1 instance hasCoeENNReal : Coe ℝ≥0∞ EReal := ⟨ENNReal.toEReal⟩ instance : Inhabited EReal := ⟨0⟩ @[simp, norm_cast] theorem coe_zero : ((0 : ℝ) : EReal) = 0 := rfl @[simp, norm_cast] theorem coe_one : ((1 : ℝ) : EReal) = 1 := rfl /-- A recursor for `EReal` in terms of the coercion. When working in term mode, note that pattern matching can be used directly. -/ @[elab_as_elim, induction_eliminator, cases_eliminator] protected def rec {C : EReal → Sort*} (h_bot : C ⊥) (h_real : ∀ a : ℝ, C a) (h_top : C ⊤) : ∀ a : EReal, C a | ⊥ => h_bot | (a : ℝ) => h_real a | ⊤ => h_top /-- The multiplication on `EReal`. Our definition satisfies `0 * x = x * 0 = 0` for any `x`, and picks the only sensible value elsewhere. -/ protected def mul : EReal → EReal → EReal | ⊥, ⊥ => ⊤ | ⊥, ⊤ => ⊥ | ⊥, (y : ℝ) => if 0 < y then ⊥ else if y = 0 then 0 else ⊤ | ⊤, ⊥ => ⊥ | ⊤, ⊤ => ⊤ | ⊤, (y : ℝ) => if 0 < y then ⊤ else if y = 0 then 0 else ⊥ | (x : ℝ), ⊤ => if 0 < x then ⊤ else if x = 0 then 0 else ⊥ | (x : ℝ), ⊥ => if 0 < x then ⊥ else if x = 0 then 0 else ⊤ | (x : ℝ), (y : ℝ) => (x * y : ℝ) instance : Mul EReal := ⟨EReal.mul⟩ @[simp, norm_cast] theorem coe_mul (x y : ℝ) : (↑(x * y) : EReal) = x * y := rfl /-- Induct on two `EReal`s by performing case splits on the sign of one whenever the other is infinite. -/ @[elab_as_elim] theorem induction₂ {P : EReal → EReal → Prop} (top_top : P ⊤ ⊤) (top_pos : ∀ x : ℝ, 0 < x → P ⊤ x) (top_zero : P ⊤ 0) (top_neg : ∀ x : ℝ, x < 0 → P ⊤ x) (top_bot : P ⊤ ⊥) (pos_top : ∀ x : ℝ, 0 < x → P x ⊤) (pos_bot : ∀ x : ℝ, 0 < x → P x ⊥) (zero_top : P 0 ⊤) (coe_coe : ∀ x y : ℝ, P x y) (zero_bot : P 0 ⊥) (neg_top : ∀ x : ℝ, x < 0 → P x ⊤) (neg_bot : ∀ x : ℝ, x < 0 → P x ⊥) (bot_top : P ⊥ ⊤) (bot_pos : ∀ x : ℝ, 0 < x → P ⊥ x) (bot_zero : P ⊥ 0) (bot_neg : ∀ x : ℝ, x < 0 → P ⊥ x) (bot_bot : P ⊥ ⊥) : ∀ x y, P x y | ⊥, ⊥ => bot_bot | ⊥, (y : ℝ) => by rcases lt_trichotomy y 0 with (hy | rfl | hy) exacts [bot_neg y hy, bot_zero, bot_pos y hy] | ⊥, ⊤ => bot_top | (x : ℝ), ⊥ => by rcases lt_trichotomy x 0 with (hx | rfl | hx) exacts [neg_bot x hx, zero_bot, pos_bot x hx] | (x : ℝ), (y : ℝ) => coe_coe _ _ | (x : ℝ), ⊤ => by rcases lt_trichotomy x 0 with (hx | rfl | hx) exacts [neg_top x hx, zero_top, pos_top x hx] | ⊤, ⊥ => top_bot | ⊤, (y : ℝ) => by rcases lt_trichotomy y 0 with (hy | rfl | hy) exacts [top_neg y hy, top_zero, top_pos y hy] | ⊤, ⊤ => top_top /-- Induct on two `EReal`s by performing case splits on the sign of one whenever the other is infinite. This version eliminates some cases by assuming that the relation is symmetric. -/ @[elab_as_elim] theorem induction₂_symm {P : EReal → EReal → Prop} (symm : ∀ {x y}, P x y → P y x) (top_top : P ⊤ ⊤) (top_pos : ∀ x : ℝ, 0 < x → P ⊤ x) (top_zero : P ⊤ 0) (top_neg : ∀ x : ℝ, x < 0 → P ⊤ x) (top_bot : P ⊤ ⊥) (pos_bot : ∀ x : ℝ, 0 < x → P x ⊥) (coe_coe : ∀ x y : ℝ, P x y) (zero_bot : P 0 ⊥) (neg_bot : ∀ x : ℝ, x < 0 → P x ⊥) (bot_bot : P ⊥ ⊥) : ∀ x y, P x y := @induction₂ P top_top top_pos top_zero top_neg top_bot (fun _ h => symm <| top_pos _ h) pos_bot (symm top_zero) coe_coe zero_bot (fun _ h => symm <| top_neg _ h) neg_bot (symm top_bot) (fun _ h => symm <| pos_bot _ h) (symm zero_bot) (fun _ h => symm <| neg_bot _ h) bot_bot /-! `EReal` with its multiplication is a `CommMonoidWithZero`. However, the proof of associativity by hand is extremely painful (with 125 cases...). Instead, we will deduce it later on from the facts that the absolute value and the sign are multiplicative functions taking value in associative objects, and that they characterize an extended real number. For now, we only record more basic properties of multiplication. -/ protected theorem mul_comm (x y : EReal) : x * y = y * x := by induction x <;> induction y <;> try { rfl } rw [← coe_mul, ← coe_mul, mul_comm] protected theorem one_mul : ∀ x : EReal, 1 * x = x | ⊤ => if_pos one_pos | ⊥ => if_pos one_pos | (x : ℝ) => congr_arg Real.toEReal (one_mul x) protected theorem zero_mul : ∀ x : EReal, 0 * x = 0 | ⊤ => (if_neg (lt_irrefl _)).trans (if_pos rfl) | ⊥ => (if_neg (lt_irrefl _)).trans (if_pos rfl) | (x : ℝ) => congr_arg Real.toEReal (zero_mul x) instance : MulZeroOneClass EReal where one_mul := EReal.one_mul mul_one := fun x => by rw [EReal.mul_comm, EReal.one_mul] zero_mul := EReal.zero_mul mul_zero := fun x => by rw [EReal.mul_comm, EReal.zero_mul] /-! ### Real coercion -/ instance canLift : CanLift EReal ℝ (↑) fun r => r ≠ ⊤ ∧ r ≠ ⊥ where prf x hx := by induction x · simp at hx · simp · simp at hx /-- The map from extended reals to reals sending infinities to zero. -/ def toReal : EReal → ℝ | ⊥ => 0 | ⊤ => 0 | (x : ℝ) => x @[simp] theorem toReal_top : toReal ⊤ = 0 := rfl @[simp] theorem toReal_bot : toReal ⊥ = 0 := rfl @[simp] theorem toReal_zero : toReal 0 = 0 := rfl @[simp] theorem toReal_one : toReal 1 = 1 := rfl @[simp] theorem toReal_coe (x : ℝ) : toReal (x : EReal) = x := rfl @[simp] theorem bot_lt_coe (x : ℝ) : (⊥ : EReal) < x := WithBot.bot_lt_coe _ @[simp] theorem coe_ne_bot (x : ℝ) : (x : EReal) ≠ ⊥ := (bot_lt_coe x).ne' @[simp] theorem bot_ne_coe (x : ℝ) : (⊥ : EReal) ≠ x := (bot_lt_coe x).ne @[simp] theorem coe_lt_top (x : ℝ) : (x : EReal) < ⊤ := WithBot.coe_lt_coe.2 <| WithTop.coe_lt_top _ @[simp] theorem coe_ne_top (x : ℝ) : (x : EReal) ≠ ⊤ := (coe_lt_top x).ne @[simp] theorem top_ne_coe (x : ℝ) : (⊤ : EReal) ≠ x := (coe_lt_top x).ne' @[simp] theorem bot_lt_zero : (⊥ : EReal) < 0 := bot_lt_coe 0 @[simp] theorem bot_ne_zero : (⊥ : EReal) ≠ 0 := (coe_ne_bot 0).symm @[simp] theorem zero_ne_bot : (0 : EReal) ≠ ⊥ := coe_ne_bot 0 @[simp] theorem zero_lt_top : (0 : EReal) < ⊤ := coe_lt_top 0 @[simp] theorem zero_ne_top : (0 : EReal) ≠ ⊤ := coe_ne_top 0 @[simp] theorem top_ne_zero : (⊤ : EReal) ≠ 0 := (coe_ne_top 0).symm theorem range_coe : range Real.toEReal = {⊥, ⊤}ᶜ := by ext x induction x <;> simp theorem range_coe_eq_Ioo : range Real.toEReal = Ioo ⊥ ⊤ := by ext x induction x <;> simp @[simp, norm_cast] theorem coe_add (x y : ℝ) : (↑(x + y) : EReal) = x + y := rfl -- `coe_mul` moved up @[norm_cast] theorem coe_nsmul (n : ℕ) (x : ℝ) : (↑(n • x) : EReal) = n • (x : EReal) := map_nsmul (⟨⟨Real.toEReal, coe_zero⟩, coe_add⟩ : ℝ →+ EReal) _ _ @[simp, norm_cast] theorem coe_eq_zero {x : ℝ} : (x : EReal) = 0 ↔ x = 0 := EReal.coe_eq_coe_iff @[simp, norm_cast] theorem coe_eq_one {x : ℝ} : (x : EReal) = 1 ↔ x = 1 := EReal.coe_eq_coe_iff theorem coe_ne_zero {x : ℝ} : (x : EReal) ≠ 0 ↔ x ≠ 0 := EReal.coe_ne_coe_iff theorem coe_ne_one {x : ℝ} : (x : EReal) ≠ 1 ↔ x ≠ 1 := EReal.coe_ne_coe_iff @[simp, norm_cast] protected theorem coe_nonneg {x : ℝ} : (0 : EReal) ≤ x ↔ 0 ≤ x := EReal.coe_le_coe_iff @[simp, norm_cast] protected theorem coe_nonpos {x : ℝ} : (x : EReal) ≤ 0 ↔ x ≤ 0 := EReal.coe_le_coe_iff @[simp, norm_cast] protected theorem coe_pos {x : ℝ} : (0 : EReal) < x ↔ 0 < x := EReal.coe_lt_coe_iff @[simp, norm_cast] protected theorem coe_neg' {x : ℝ} : (x : EReal) < 0 ↔ x < 0 := EReal.coe_lt_coe_iff theorem toReal_le_toReal {x y : EReal} (h : x ≤ y) (hx : x ≠ ⊥) (hy : y ≠ ⊤) : x.toReal ≤ y.toReal := by lift x to ℝ using ⟨ne_top_of_le_ne_top hy h, hx⟩ lift y to ℝ using ⟨hy, ne_bot_of_le_ne_bot hx h⟩ simpa using h theorem coe_toReal {x : EReal} (hx : x ≠ ⊤) (h'x : x ≠ ⊥) : (x.toReal : EReal) = x := by lift x to ℝ using ⟨hx, h'x⟩ rfl theorem le_coe_toReal {x : EReal} (h : x ≠ ⊤) : x ≤ x.toReal := by by_cases h' : x = ⊥ · simp only [h', bot_le] · simp only [le_refl, coe_toReal h h'] theorem coe_toReal_le {x : EReal} (h : x ≠ ⊥) : ↑x.toReal ≤ x := by by_cases h' : x = ⊤ · simp only [h', le_top] · simp only [le_refl, coe_toReal h' h] theorem eq_top_iff_forall_lt (x : EReal) : x = ⊤ ↔ ∀ y : ℝ, (y : EReal) < x := by constructor · rintro rfl exact EReal.coe_lt_top · contrapose! intro h exact ⟨x.toReal, le_coe_toReal h⟩ theorem eq_bot_iff_forall_lt (x : EReal) : x = ⊥ ↔ ∀ y : ℝ, x < (y : EReal) := by constructor · rintro rfl exact bot_lt_coe · contrapose! intro h exact ⟨x.toReal, coe_toReal_le h⟩ /-! ### Intervals and coercion from reals -/ lemma exists_between_coe_real {x z : EReal} (h : x < z) : ∃ y : ℝ, x < y ∧ y < z := by obtain ⟨a, ha₁, ha₂⟩ := exists_between h induction a with | h_bot => exact (not_lt_bot ha₁).elim | h_real a₀ => exact ⟨a₀, ha₁, ha₂⟩ | h_top => exact (not_top_lt ha₂).elim @[simp] lemma image_coe_Icc (x y : ℝ) : Real.toEReal '' Icc x y = Icc ↑x ↑y := by refine (image_comp WithBot.some WithTop.some _).trans ?_ rw [WithTop.image_coe_Icc, WithBot.image_coe_Icc] rfl @[simp] lemma image_coe_Ico (x y : ℝ) : Real.toEReal '' Ico x y = Ico ↑x ↑y := by refine (image_comp WithBot.some WithTop.some _).trans ?_ rw [WithTop.image_coe_Ico, WithBot.image_coe_Ico] rfl @[simp] lemma image_coe_Ici (x : ℝ) : Real.toEReal '' Ici x = Ico ↑x ⊤ := by refine (image_comp WithBot.some WithTop.some _).trans ?_ rw [WithTop.image_coe_Ici, WithBot.image_coe_Ico] rfl @[simp] lemma image_coe_Ioc (x y : ℝ) : Real.toEReal '' Ioc x y = Ioc ↑x ↑y := by refine (image_comp WithBot.some WithTop.some _).trans ?_ rw [WithTop.image_coe_Ioc, WithBot.image_coe_Ioc] rfl @[simp] lemma image_coe_Ioo (x y : ℝ) : Real.toEReal '' Ioo x y = Ioo ↑x ↑y := by refine (image_comp WithBot.some WithTop.some _).trans ?_ rw [WithTop.image_coe_Ioo, WithBot.image_coe_Ioo] rfl @[simp] lemma image_coe_Ioi (x : ℝ) : Real.toEReal '' Ioi x = Ioo ↑x ⊤ := by refine (image_comp WithBot.some WithTop.some _).trans ?_ rw [WithTop.image_coe_Ioi, WithBot.image_coe_Ioo] rfl @[simp] lemma image_coe_Iic (x : ℝ) : Real.toEReal '' Iic x = Ioc ⊥ ↑x := by refine (image_comp WithBot.some WithTop.some _).trans ?_ rw [WithTop.image_coe_Iic, WithBot.image_coe_Iic] rfl @[simp] lemma image_coe_Iio (x : ℝ) : Real.toEReal '' Iio x = Ioo ⊥ ↑x := by refine (image_comp WithBot.some WithTop.some _).trans ?_ rw [WithTop.image_coe_Iio, WithBot.image_coe_Iio] rfl @[simp] lemma preimage_coe_Ici (x : ℝ) : Real.toEReal ⁻¹' Ici x = Ici x := by change (WithBot.some ∘ WithTop.some) ⁻¹' (Ici (WithBot.some (WithTop.some x))) = _ refine preimage_comp.trans ?_ simp only [WithBot.preimage_coe_Ici, WithTop.preimage_coe_Ici] @[simp] lemma preimage_coe_Ioi (x : ℝ) : Real.toEReal ⁻¹' Ioi x = Ioi x := by change (WithBot.some ∘ WithTop.some) ⁻¹' (Ioi (WithBot.some (WithTop.some x))) = _ refine preimage_comp.trans ?_ simp only [WithBot.preimage_coe_Ioi, WithTop.preimage_coe_Ioi] @[simp] lemma preimage_coe_Ioi_bot : Real.toEReal ⁻¹' Ioi ⊥ = univ := by change (WithBot.some ∘ WithTop.some) ⁻¹' (Ioi ⊥) = _ refine preimage_comp.trans ?_ simp only [WithBot.preimage_coe_Ioi_bot, preimage_univ] @[simp] lemma preimage_coe_Iic (y : ℝ) : Real.toEReal ⁻¹' Iic y = Iic y := by change (WithBot.some ∘ WithTop.some) ⁻¹' (Iic (WithBot.some (WithTop.some y))) = _ refine preimage_comp.trans ?_ simp only [WithBot.preimage_coe_Iic, WithTop.preimage_coe_Iic] @[simp] lemma preimage_coe_Iio (y : ℝ) : Real.toEReal ⁻¹' Iio y = Iio y := by change (WithBot.some ∘ WithTop.some) ⁻¹' (Iio (WithBot.some (WithTop.some y))) = _ refine preimage_comp.trans ?_ simp only [WithBot.preimage_coe_Iio, WithTop.preimage_coe_Iio] @[simp] lemma preimage_coe_Iio_top : Real.toEReal ⁻¹' Iio ⊤ = univ := by change (WithBot.some ∘ WithTop.some) ⁻¹' (Iio (WithBot.some ⊤)) = _ refine preimage_comp.trans ?_ simp only [WithBot.preimage_coe_Iio, WithTop.preimage_coe_Iio_top] @[simp] lemma preimage_coe_Icc (x y : ℝ) : Real.toEReal ⁻¹' Icc x y = Icc x y := by simp_rw [← Ici_inter_Iic] simp @[simp] lemma preimage_coe_Ico (x y : ℝ) : Real.toEReal ⁻¹' Ico x y = Ico x y := by simp_rw [← Ici_inter_Iio] simp @[simp] lemma preimage_coe_Ioc (x y : ℝ) : Real.toEReal ⁻¹' Ioc x y = Ioc x y := by simp_rw [← Ioi_inter_Iic] simp @[simp] lemma preimage_coe_Ioo (x y : ℝ) : Real.toEReal ⁻¹' Ioo x y = Ioo x y := by simp_rw [← Ioi_inter_Iio] simp @[simp] lemma preimage_coe_Ico_top (x : ℝ) : Real.toEReal ⁻¹' Ico x ⊤ = Ici x := by rw [← Ici_inter_Iio] simp @[simp] lemma preimage_coe_Ioo_top (x : ℝ) : Real.toEReal ⁻¹' Ioo x ⊤ = Ioi x := by rw [← Ioi_inter_Iio] simp @[simp] lemma preimage_coe_Ioc_bot (y : ℝ) : Real.toEReal ⁻¹' Ioc ⊥ y = Iic y := by rw [← Ioi_inter_Iic] simp @[simp] lemma preimage_coe_Ioo_bot (y : ℝ) : Real.toEReal ⁻¹' Ioo ⊥ y = Iio y := by rw [← Ioi_inter_Iio] simp @[simp] lemma preimage_coe_Ioo_bot_top : Real.toEReal ⁻¹' Ioo ⊥ ⊤ = univ := by rw [← Ioi_inter_Iio] simp /-! ### ennreal coercion -/ @[simp] theorem toReal_coe_ennreal : ∀ {x : ℝ≥0∞}, toReal (x : EReal) = ENNReal.toReal x | ⊤ => rfl | .some _ => rfl @[simp] theorem coe_ennreal_ofReal {x : ℝ} : (ENNReal.ofReal x : EReal) = max x 0 := rfl theorem coe_nnreal_eq_coe_real (x : ℝ≥0) : ((x : ℝ≥0∞) : EReal) = (x : ℝ) := rfl @[simp, norm_cast] theorem coe_ennreal_zero : ((0 : ℝ≥0∞) : EReal) = 0 := rfl @[simp, norm_cast] theorem coe_ennreal_one : ((1 : ℝ≥0∞) : EReal) = 1 := rfl @[simp, norm_cast] theorem coe_ennreal_top : ((⊤ : ℝ≥0∞) : EReal) = ⊤ := rfl theorem coe_ennreal_strictMono : StrictMono ((↑) : ℝ≥0∞ → EReal) := WithTop.strictMono_iff.2 ⟨fun _ _ => EReal.coe_lt_coe_iff.2, fun _ => coe_lt_top _⟩ theorem coe_ennreal_injective : Injective ((↑) : ℝ≥0∞ → EReal) := coe_ennreal_strictMono.injective @[simp] theorem coe_ennreal_eq_top_iff {x : ℝ≥0∞} : (x : EReal) = ⊤ ↔ x = ⊤ := coe_ennreal_injective.eq_iff' rfl theorem coe_nnreal_ne_top (x : ℝ≥0) : ((x : ℝ≥0∞) : EReal) ≠ ⊤ := coe_ne_top x @[simp] theorem coe_nnreal_lt_top (x : ℝ≥0) : ((x : ℝ≥0∞) : EReal) < ⊤ := coe_lt_top x @[simp, norm_cast] theorem coe_ennreal_le_coe_ennreal_iff {x y : ℝ≥0∞} : (x : EReal) ≤ (y : EReal) ↔ x ≤ y := coe_ennreal_strictMono.le_iff_le @[simp, norm_cast] theorem coe_ennreal_lt_coe_ennreal_iff {x y : ℝ≥0∞} : (x : EReal) < (y : EReal) ↔ x < y := coe_ennreal_strictMono.lt_iff_lt @[simp, norm_cast] theorem coe_ennreal_eq_coe_ennreal_iff {x y : ℝ≥0∞} : (x : EReal) = (y : EReal) ↔ x = y := coe_ennreal_injective.eq_iff theorem coe_ennreal_ne_coe_ennreal_iff {x y : ℝ≥0∞} : (x : EReal) ≠ (y : EReal) ↔ x ≠ y := coe_ennreal_injective.ne_iff @[simp, norm_cast] theorem coe_ennreal_eq_zero {x : ℝ≥0∞} : (x : EReal) = 0 ↔ x = 0 := by rw [← coe_ennreal_eq_coe_ennreal_iff, coe_ennreal_zero] @[simp, norm_cast] theorem coe_ennreal_eq_one {x : ℝ≥0∞} : (x : EReal) = 1 ↔ x = 1 := by rw [← coe_ennreal_eq_coe_ennreal_iff, coe_ennreal_one] @[norm_cast] theorem coe_ennreal_ne_zero {x : ℝ≥0∞} : (x : EReal) ≠ 0 ↔ x ≠ 0 := coe_ennreal_eq_zero.not @[norm_cast] theorem coe_ennreal_ne_one {x : ℝ≥0∞} : (x : EReal) ≠ 1 ↔ x ≠ 1 := coe_ennreal_eq_one.not theorem coe_ennreal_nonneg (x : ℝ≥0∞) : (0 : EReal) ≤ x := coe_ennreal_le_coe_ennreal_iff.2 (zero_le x) @[simp] theorem range_coe_ennreal : range ((↑) : ℝ≥0∞ → EReal) = Set.Ici 0 := Subset.antisymm (range_subset_iff.2 coe_ennreal_nonneg) fun x => match x with | ⊥ => fun h => absurd h bot_lt_zero.not_le | ⊤ => fun _ => ⟨⊤, rfl⟩ | (x : ℝ) => fun h => ⟨.some ⟨x, EReal.coe_nonneg.1 h⟩, rfl⟩ instance : CanLift EReal ℝ≥0∞ (↑) (0 ≤ ·) := ⟨range_coe_ennreal.ge⟩ @[simp, norm_cast] theorem coe_ennreal_pos {x : ℝ≥0∞} : (0 : EReal) < x ↔ 0 < x := by rw [← coe_ennreal_zero, coe_ennreal_lt_coe_ennreal_iff] @[simp] theorem bot_lt_coe_ennreal (x : ℝ≥0∞) : (⊥ : EReal) < x := (bot_lt_coe 0).trans_le (coe_ennreal_nonneg _) @[simp] theorem coe_ennreal_ne_bot (x : ℝ≥0∞) : (x : EReal) ≠ ⊥ := (bot_lt_coe_ennreal x).ne' @[simp, norm_cast] theorem coe_ennreal_add (x y : ENNReal) : ((x + y : ℝ≥0∞) : EReal) = x + y := by cases x <;> cases y <;> rfl private theorem coe_ennreal_top_mul (x : ℝ≥0) : ((⊤ * x : ℝ≥0∞) : EReal) = ⊤ * x := by rcases eq_or_ne x 0 with (rfl | h0) · simp · rw [ENNReal.top_mul (ENNReal.coe_ne_zero.2 h0)] exact Eq.symm <| if_pos <| NNReal.coe_pos.2 h0.bot_lt @[simp, norm_cast] theorem coe_ennreal_mul : ∀ x y : ℝ≥0∞, ((x * y : ℝ≥0∞) : EReal) = (x : EReal) * y | ⊤, ⊤ => rfl | ⊤, (y : ℝ≥0) => coe_ennreal_top_mul y | (x : ℝ≥0), ⊤ => by rw [mul_comm, coe_ennreal_top_mul, EReal.mul_comm, coe_ennreal_top] | (x : ℝ≥0), (y : ℝ≥0) => by simp only [← ENNReal.coe_mul, coe_nnreal_eq_coe_real, NNReal.coe_mul, EReal.coe_mul] @[norm_cast] theorem coe_ennreal_nsmul (n : ℕ) (x : ℝ≥0∞) : (↑(n • x) : EReal) = n • (x : EReal) := map_nsmul (⟨⟨(↑), coe_ennreal_zero⟩, coe_ennreal_add⟩ : ℝ≥0∞ →+ EReal) _ _ /-! ### nat coercion -/ theorem coe_coe_eq_natCast (n : ℕ) : (n : ℝ) = (n : EReal) := rfl theorem natCast_ne_bot (n : ℕ) : (n : EReal) ≠ ⊥ := Ne.symm (ne_of_beq_false rfl) theorem natCast_ne_top (n : ℕ) : (n : EReal) ≠ ⊤ := Ne.symm (ne_of_beq_false rfl) @[simp, norm_cast] theorem natCast_eq_iff {m n : ℕ} : (m : EReal) = (n : EReal) ↔ m = n := by rw [← coe_coe_eq_natCast n, ← coe_coe_eq_natCast m, EReal.coe_eq_coe_iff, Nat.cast_inj] theorem natCast_ne_iff {m n : ℕ} : (m : EReal) ≠ (n : EReal) ↔ m ≠ n := not_iff_not.2 natCast_eq_iff @[simp, norm_cast] theorem natCast_le_iff {m n : ℕ} : (m : EReal) ≤ (n : EReal) ↔ m ≤ n := by rw [← coe_coe_eq_natCast n, ← coe_coe_eq_natCast m, EReal.coe_le_coe_iff, Nat.cast_le] @[simp, norm_cast] theorem natCast_lt_iff {m n : ℕ} : (m : EReal) < (n : EReal) ↔ m < n := by rw [← coe_coe_eq_natCast n, ← coe_coe_eq_natCast m, EReal.coe_lt_coe_iff, Nat.cast_lt] @[simp, norm_cast] theorem natCast_mul (m n : ℕ) : (m * n : ℕ) = (m : EReal) * (n : EReal) := by rw [← coe_coe_eq_natCast, ← coe_coe_eq_natCast, ← coe_coe_eq_natCast, Nat.cast_mul, EReal.coe_mul] /-! ### Order -/ theorem exists_rat_btwn_of_lt : ∀ {a b : EReal}, a < b → ∃ x : ℚ, a < (x : ℝ) ∧ ((x : ℝ) : EReal) < b | ⊤, b, h => (not_top_lt h).elim | (a : ℝ), ⊥, h => (lt_irrefl _ ((bot_lt_coe a).trans h)).elim | (a : ℝ), (b : ℝ), h => by simp [exists_rat_btwn (EReal.coe_lt_coe_iff.1 h)] | (a : ℝ), ⊤, _ => let ⟨b, hab⟩ := exists_rat_gt a ⟨b, by simpa using hab, coe_lt_top _⟩ | ⊥, ⊥, h => (lt_irrefl _ h).elim | ⊥, (a : ℝ), _ => let ⟨b, hab⟩ := exists_rat_lt a ⟨b, bot_lt_coe _, by simpa using hab⟩ | ⊥, ⊤, _ => ⟨0, bot_lt_coe _, coe_lt_top _⟩ theorem lt_iff_exists_rat_btwn {a b : EReal} : a < b ↔ ∃ x : ℚ, a < (x : ℝ) ∧ ((x : ℝ) : EReal) < b := ⟨fun hab => exists_rat_btwn_of_lt hab, fun ⟨_x, ax, xb⟩ => ax.trans xb⟩ theorem lt_iff_exists_real_btwn {a b : EReal} : a < b ↔ ∃ x : ℝ, a < x ∧ (x : EReal) < b := ⟨fun hab => let ⟨x, ax, xb⟩ := exists_rat_btwn_of_lt hab ⟨(x : ℝ), ax, xb⟩, fun ⟨_x, ax, xb⟩ => ax.trans xb⟩ /-- The set of numbers in `EReal` that are not equal to `±∞` is equivalent to `ℝ`. -/ def neTopBotEquivReal : ({⊥, ⊤}ᶜ : Set EReal) ≃ ℝ where toFun x := EReal.toReal x invFun x := ⟨x, by simp⟩ left_inv := fun ⟨x, hx⟩ => by lift x to ℝ · simpa [not_or, and_comm] using hx · simp right_inv x := by simp /-! ### Addition -/ @[simp] theorem add_bot (x : EReal) : x + ⊥ = ⊥ := WithBot.add_bot _ @[simp] theorem bot_add (x : EReal) : ⊥ + x = ⊥ := WithBot.bot_add _ @[simp] theorem add_eq_bot_iff {x y : EReal} : x + y = ⊥ ↔ x = ⊥ ∨ y = ⊥ := WithBot.add_eq_bot @[simp] theorem bot_lt_add_iff {x y : EReal} : ⊥ < x + y ↔ ⊥ < x ∧ ⊥ < y := by simp [bot_lt_iff_ne_bot, not_or] @[simp] theorem top_add_top : (⊤ : EReal) + ⊤ = ⊤ := rfl @[simp] theorem top_add_coe (x : ℝ) : (⊤ : EReal) + x = ⊤ := rfl /-- For any extended real number `x` which is not `⊥`, the sum of `⊤` and `x` is equal to `⊤`. -/ @[simp] theorem top_add_of_ne_bot {x : EReal} (h : x ≠ ⊥) : ⊤ + x = ⊤ := by induction x · exfalso; exact h (Eq.refl ⊥) · exact top_add_coe _ · exact top_add_top /-- For any extended real number `x`, the sum of `⊤` and `x` is equal to `⊤` if and only if `x` is not `⊥`. -/ theorem top_add_iff_ne_bot {x : EReal} : ⊤ + x = ⊤ ↔ x ≠ ⊥ := by constructor <;> intro h · rintro rfl rw [add_bot] at h exact bot_ne_top h · cases x with | h_bot => contradiction | h_top => rfl | h_real r => exact top_add_of_ne_bot h /-- For any extended real number `x` which is not `⊥`, the sum of `x` and `⊤` is equal to `⊤`. -/ @[simp] theorem add_top_of_ne_bot {x : EReal} (h : x ≠ ⊥) : x + ⊤ = ⊤ := by rw [add_comm, top_add_of_ne_bot h] /-- For any extended real number `x`, the sum of `x` and `⊤` is equal to `⊤` if and only if `x` is not `⊥`. -/ theorem add_top_iff_ne_bot {x : EReal} : x + ⊤ = ⊤ ↔ x ≠ ⊥ := by rw [add_comm, top_add_iff_ne_bot] /-- For any two extended real numbers `a` and `b`, if both `a` and `b` are greater than `0`, then their sum is also greater than `0`. -/ theorem add_pos {a b : EReal} (ha : 0 < a) (hb : 0 < b) : 0 < a + b := by induction a · exfalso; exact not_lt_bot ha · induction b · exfalso; exact not_lt_bot hb · norm_cast at *; exact Left.add_pos ha hb · exact add_top_of_ne_bot (bot_lt_zero.trans ha).ne' ▸ hb · rw [top_add_of_ne_bot (bot_lt_zero.trans hb).ne'] exact ha @[simp] theorem coe_add_top (x : ℝ) : (x : EReal) + ⊤ = ⊤ := rfl theorem toReal_add {x y : EReal} (hx : x ≠ ⊤) (h'x : x ≠ ⊥) (hy : y ≠ ⊤) (h'y : y ≠ ⊥) : toReal (x + y) = toReal x + toReal y := by lift x to ℝ using ⟨hx, h'x⟩ lift y to ℝ using ⟨hy, h'y⟩ rfl theorem addLECancellable_coe (x : ℝ) : AddLECancellable (x : EReal) | _, ⊤, _ => le_top | ⊥, _, _ => bot_le | ⊤, (z : ℝ), h => by simp only [coe_add_top, ← coe_add, top_le_iff, coe_ne_top] at h | _, ⊥, h => by simpa using h | (y : ℝ), (z : ℝ), h => by simpa only [← coe_add, EReal.coe_le_coe_iff, add_le_add_iff_left] using h -- Porting note (#11215): TODO: add `MulLECancellable.strictMono*` etc theorem add_lt_add_right_coe {x y : EReal} (h : x < y) (z : ℝ) : x + z < y + z := not_le.1 <| mt (addLECancellable_coe z).add_le_add_iff_right.1 h.not_le theorem add_lt_add_left_coe {x y : EReal} (h : x < y) (z : ℝ) : (z : EReal) + x < z + y := by simpa [add_comm] using add_lt_add_right_coe h z theorem add_lt_add {x y z t : EReal} (h1 : x < y) (h2 : z < t) : x + z < y + t := by rcases eq_or_ne x ⊥ with (rfl | hx) · simp [h1, bot_le.trans_lt h2] · lift x to ℝ using ⟨h1.ne_top, hx⟩ calc (x : EReal) + z < x + t := add_lt_add_left_coe h2 _ _ ≤ y + t := add_le_add_right h1.le _ theorem add_lt_add_of_lt_of_le' {x y z t : EReal} (h : x < y) (h' : z ≤ t) (hbot : t ≠ ⊥) (htop : t = ⊤ → z = ⊤ → x = ⊥) : x + z < y + t := by rcases h'.eq_or_lt with (rfl | hlt) · rcases eq_or_ne z ⊤ with (rfl | hz) · obtain rfl := htop rfl rfl simpa lift z to ℝ using ⟨hz, hbot⟩ exact add_lt_add_right_coe h z · exact add_lt_add h hlt /-- See also `EReal.add_lt_add_of_lt_of_le'` for a version with weaker but less convenient assumptions. -/ theorem add_lt_add_of_lt_of_le {x y z t : EReal} (h : x < y) (h' : z ≤ t) (hz : z ≠ ⊥) (ht : t ≠ ⊤) : x + z < y + t := add_lt_add_of_lt_of_le' h h' (ne_bot_of_le_ne_bot hz h') fun ht' => (ht ht').elim theorem add_lt_top {x y : EReal} (hx : x ≠ ⊤) (hy : y ≠ ⊤) : x + y < ⊤ := by rw [← EReal.top_add_top] exact EReal.add_lt_add hx.lt_top hy.lt_top /-- We do not have a notion of `LinearOrderedAddCommMonoidWithBot` but we can at least make the order dual of the extended reals into a `LinearOrderedAddCommMonoidWithTop`. -/ instance : LinearOrderedAddCommMonoidWithTop ERealᵒᵈ where le_top := by simp top_add' := by rw [OrderDual.forall] intro x rw [← OrderDual.toDual_bot, ← toDual_add, bot_add, OrderDual.toDual_bot] /-! ### Negation -/ /-- negation on `EReal` -/ protected def neg : EReal → EReal | ⊥ => ⊤ | ⊤ => ⊥ | (x : ℝ) => (-x : ℝ) instance : Neg EReal := ⟨EReal.neg⟩ instance : SubNegZeroMonoid EReal where neg_zero := congr_arg Real.toEReal neg_zero zsmul := zsmulRec @[simp] theorem neg_top : -(⊤ : EReal) = ⊥ := rfl @[simp] theorem neg_bot : -(⊥ : EReal) = ⊤ := rfl @[simp, norm_cast] theorem coe_neg (x : ℝ) : (↑(-x) : EReal) = -↑x := rfl @[simp, norm_cast] theorem coe_sub (x y : ℝ) : (↑(x - y) : EReal) = x - y := rfl @[norm_cast] theorem coe_zsmul (n : ℤ) (x : ℝ) : (↑(n • x) : EReal) = n • (x : EReal) := map_zsmul' (⟨⟨(↑), coe_zero⟩, coe_add⟩ : ℝ →+ EReal) coe_neg _ _ instance : InvolutiveNeg EReal where neg_neg a := match a with | ⊥ => rfl | ⊤ => rfl | (a : ℝ) => congr_arg Real.toEReal (neg_neg a) @[simp] theorem toReal_neg : ∀ {a : EReal}, toReal (-a) = -toReal a | ⊤ => by simp | ⊥ => by simp | (x : ℝ) => rfl @[simp] theorem neg_eq_top_iff {x : EReal} : -x = ⊤ ↔ x = ⊥ := neg_injective.eq_iff' rfl @[simp] theorem neg_eq_bot_iff {x : EReal} : -x = ⊥ ↔ x = ⊤ := neg_injective.eq_iff' rfl @[simp] theorem neg_eq_zero_iff {x : EReal} : -x = 0 ↔ x = 0 := neg_injective.eq_iff' neg_zero theorem neg_strictAnti : StrictAnti (- · : EReal → EReal) := WithBot.strictAnti_iff.2 ⟨WithTop.strictAnti_iff.2 ⟨coe_strictMono.comp_strictAnti fun _ _ => neg_lt_neg, fun _ => bot_lt_coe _⟩, WithTop.forall.2 ⟨bot_lt_top, fun _ => coe_lt_top _⟩⟩ @[simp] theorem neg_le_neg_iff {a b : EReal} : -a ≤ -b ↔ b ≤ a := neg_strictAnti.le_iff_le @[simp] theorem neg_lt_neg_iff {a b : EReal} : -a < -b ↔ b < a := neg_strictAnti.lt_iff_lt /-- `-a ≤ b ↔ -b ≤ a` on `EReal`. -/ protected theorem neg_le {a b : EReal} : -a ≤ b ↔ -b ≤ a := by rw [← neg_le_neg_iff, neg_neg] /-- if `-a ≤ b` then `-b ≤ a` on `EReal`. -/ protected theorem neg_le_of_neg_le {a b : EReal} (h : -a ≤ b) : -b ≤ a := EReal.neg_le.mp h /-- `a ≤ -b → b ≤ -a` on ereal -/ theorem le_neg_of_le_neg {a b : EReal} (h : a ≤ -b) : b ≤ -a := by rwa [← neg_neg b, EReal.neg_le, neg_neg] /-- Negation as an order reversing isomorphism on `EReal`. -/ def negOrderIso : EReal ≃o ERealᵒᵈ := { Equiv.neg EReal with toFun := fun x => OrderDual.toDual (-x) invFun := fun x => -OrderDual.ofDual x map_rel_iff' := neg_le_neg_iff } theorem neg_lt_iff_neg_lt {a b : EReal} : -a < b ↔ -b < a := by rw [← neg_lt_neg_iff, neg_neg] theorem neg_lt_of_neg_lt {a b : EReal} (h : -a < b) : -b < a := neg_lt_iff_neg_lt.1 h lemma neg_add {x y : EReal} (h1 : x ≠ ⊥ ∨ y ≠ ⊤) (h2 : x ≠ ⊤ ∨ y ≠ ⊥) : - (x + y) = - x - y := by induction x <;> induction y <;> try tauto rw [← coe_add, ← coe_neg, ← coe_neg, ← coe_sub, neg_add'] lemma neg_sub {x y : EReal} (h1 : x ≠ ⊥ ∨ y ≠ ⊥) (h2 : x ≠ ⊤ ∨ y ≠ ⊤) : - (x - y) = - x + y := by rw [sub_eq_add_neg, neg_add _ _, sub_eq_add_neg, neg_neg] <;> simp_all /-! ### Subtraction Subtraction on `EReal` is defined by `x - y = x + (-y)`. Since addition is badly behaved at some points, so is subtraction. There is no standard algebraic typeclass involving subtraction that is registered on `EReal`, beyond `SubNegZeroMonoid`, because of this bad behavior. -/ @[simp] theorem bot_sub (x : EReal) : ⊥ - x = ⊥ := bot_add x @[simp] theorem sub_top (x : EReal) : x - ⊤ = ⊥ := add_bot x @[simp] theorem top_sub_bot : (⊤ : EReal) - ⊥ = ⊤ := rfl @[simp] theorem top_sub_coe (x : ℝ) : (⊤ : EReal) - x = ⊤ := rfl @[simp] theorem coe_sub_bot (x : ℝ) : (x : EReal) - ⊥ = ⊤ := rfl theorem sub_le_sub {x y z t : EReal} (h : x ≤ y) (h' : t ≤ z) : x - z ≤ y - t := add_le_add h (neg_le_neg_iff.2 h') theorem sub_lt_sub_of_lt_of_le {x y z t : EReal} (h : x < y) (h' : z ≤ t) (hz : z ≠ ⊥) (ht : t ≠ ⊤) : x - t < y - z := add_lt_add_of_lt_of_le h (neg_le_neg_iff.2 h') (by simp [ht]) (by simp [hz]) theorem coe_real_ereal_eq_coe_toNNReal_sub_coe_toNNReal (x : ℝ) : (x : EReal) = Real.toNNReal x - Real.toNNReal (-x) := by rcases le_total 0 x with (h | h) · lift x to ℝ≥0 using h rw [Real.toNNReal_of_nonpos (neg_nonpos.mpr x.coe_nonneg), Real.toNNReal_coe, ENNReal.coe_zero, coe_ennreal_zero, sub_zero] rfl · rw [Real.toNNReal_of_nonpos h, ENNReal.coe_zero, coe_ennreal_zero, coe_nnreal_eq_coe_real, Real.coe_toNNReal, zero_sub, coe_neg, neg_neg] exact neg_nonneg.2 h theorem toReal_sub {x y : EReal} (hx : x ≠ ⊤) (h'x : x ≠ ⊥) (hy : y ≠ ⊤) (h'y : y ≠ ⊥) : toReal (x - y) = toReal x - toReal y := by lift x to ℝ using ⟨hx, h'x⟩ lift y to ℝ using ⟨hy, h'y⟩ rfl lemma add_sub_cancel_right {a : EReal} {b : Real} : a + b - b = a := by induction a · rw [bot_add b, bot_sub b] · norm_cast; linarith · rw [top_add_of_ne_bot (coe_ne_bot b), top_sub_coe] /-! ### Multiplication -/ @[simp] lemma top_mul_top : (⊤ : EReal) * ⊤ = ⊤ := rfl @[simp] lemma top_mul_bot : (⊤ : EReal) * ⊥ = ⊥ := rfl @[simp] lemma bot_mul_top : (⊥ : EReal) * ⊤ = ⊥ := rfl @[simp] lemma bot_mul_bot : (⊥ : EReal) * ⊥ = ⊤ := rfl lemma coe_mul_top_of_pos {x : ℝ} (h : 0 < x) : (x : EReal) * ⊤ = ⊤ := if_pos h lemma coe_mul_top_of_neg {x : ℝ} (h : x < 0) : (x : EReal) * ⊤ = ⊥ := (if_neg h.not_lt).trans (if_neg h.ne) lemma top_mul_coe_of_pos {x : ℝ} (h : 0 < x) : (⊤ : EReal) * x = ⊤ := if_pos h lemma top_mul_coe_of_neg {x : ℝ} (h : x < 0) : (⊤ : EReal) * x = ⊥ := (if_neg h.not_lt).trans (if_neg h.ne) lemma mul_top_of_pos : ∀ {x : EReal}, 0 < x → x * ⊤ = ⊤ | ⊥, h => absurd h not_lt_bot | (x : ℝ), h => coe_mul_top_of_pos (EReal.coe_pos.1 h) | ⊤, _ => rfl lemma mul_top_of_neg : ∀ {x : EReal}, x < 0 → x * ⊤ = ⊥ | ⊥, _ => rfl | (x : ℝ), h => coe_mul_top_of_neg (EReal.coe_neg'.1 h) | ⊤, h => absurd h not_top_lt lemma top_mul_of_pos {x : EReal} (h : 0 < x) : ⊤ * x = ⊤ := by rw [EReal.mul_comm] exact mul_top_of_pos h /-- The product of two positive extended real numbers is positive. -/ lemma mul_pos {a b : EReal} (ha : 0 < a) (hb : 0 < b) : 0 < a * b := by induction a · exfalso; exact not_lt_bot ha · induction b · exfalso; exact not_lt_bot hb · norm_cast at *; exact Left.mul_pos ha hb · rw [EReal.mul_comm, top_mul_of_pos ha]; exact hb · rw [top_mul_of_pos hb]; exact ha lemma top_mul_of_neg {x : EReal} (h : x < 0) : ⊤ * x = ⊥ := by rw [EReal.mul_comm] exact mul_top_of_neg h lemma coe_mul_bot_of_pos {x : ℝ} (h : 0 < x) : (x : EReal) * ⊥ = ⊥ := if_pos h lemma coe_mul_bot_of_neg {x : ℝ} (h : x < 0) : (x : EReal) * ⊥ = ⊤ := (if_neg h.not_lt).trans (if_neg h.ne) lemma bot_mul_coe_of_pos {x : ℝ} (h : 0 < x) : (⊥ : EReal) * x = ⊥ := if_pos h lemma bot_mul_coe_of_neg {x : ℝ} (h : x < 0) : (⊥ : EReal) * x = ⊤ := (if_neg h.not_lt).trans (if_neg h.ne) lemma mul_bot_of_pos : ∀ {x : EReal}, 0 < x → x * ⊥ = ⊥ | ⊥, h => absurd h not_lt_bot | (x : ℝ), h => coe_mul_bot_of_pos (EReal.coe_pos.1 h) | ⊤, _ => rfl lemma mul_bot_of_neg : ∀ {x : EReal}, x < 0 → x * ⊥ = ⊤ | ⊥, _ => rfl | (x : ℝ), h => coe_mul_bot_of_neg (EReal.coe_neg'.1 h) | ⊤, h => absurd h not_top_lt lemma bot_mul_of_pos {x : EReal} (h : 0 < x) : ⊥ * x = ⊥ := by rw [EReal.mul_comm] exact mul_bot_of_pos h lemma bot_mul_of_neg {x : EReal} (h : x < 0) : ⊥ * x = ⊤ := by rw [EReal.mul_comm] exact mul_bot_of_neg h lemma toReal_mul {x y : EReal} : toReal (x * y) = toReal x * toReal y := by induction x, y using induction₂_symm with | top_zero | zero_bot | top_top | top_bot | bot_bot => simp | symm h => rwa [mul_comm, EReal.mul_comm] | coe_coe => norm_cast | top_pos _ h => simp [top_mul_coe_of_pos h] | top_neg _ h => simp [top_mul_coe_of_neg h] | pos_bot _ h => simp [coe_mul_bot_of_pos h] | neg_bot _ h => simp [coe_mul_bot_of_neg h] /-- Induct on two ereals by performing case splits on the sign of one whenever the other is infinite. This version eliminates some cases by assuming that `P x y` implies `P (-x) y` for all `x`, `y`. -/ @[elab_as_elim] lemma induction₂_neg_left {P : EReal → EReal → Prop} (neg_left : ∀ {x y}, P x y → P (-x) y) (top_top : P ⊤ ⊤) (top_pos : ∀ x : ℝ, 0 < x → P ⊤ x) (top_zero : P ⊤ 0) (top_neg : ∀ x : ℝ, x < 0 → P ⊤ x) (top_bot : P ⊤ ⊥) (zero_top : P 0 ⊤) (zero_bot : P 0 ⊥) (pos_top : ∀ x : ℝ, 0 < x → P x ⊤) (pos_bot : ∀ x : ℝ, 0 < x → P x ⊥) (coe_coe : ∀ x y : ℝ, P x y) : ∀ x y, P x y := have : ∀ y, (∀ x : ℝ, 0 < x → P x y) → ∀ x : ℝ, x < 0 → P x y := fun _ h x hx => neg_neg (x : EReal) ▸ neg_left <| h _ (neg_pos_of_neg hx) @induction₂ P top_top top_pos top_zero top_neg top_bot pos_top pos_bot zero_top coe_coe zero_bot (this _ pos_top) (this _ pos_bot) (neg_left top_top) (fun x hx => neg_left <| top_pos x hx) (neg_left top_zero) (fun x hx => neg_left <| top_neg x hx) (neg_left top_bot) /-- Induct on two ereals by performing case splits on the sign of one whenever the other is infinite. This version eliminates some cases by assuming that `P` is symmetric and `P x y` implies `P (-x) y` for all `x`, `y`. -/ @[elab_as_elim] lemma induction₂_symm_neg {P : EReal → EReal → Prop} (symm : ∀ {x y}, P x y → P y x) (neg_left : ∀ {x y}, P x y → P (-x) y) (top_top : P ⊤ ⊤) (top_pos : ∀ x : ℝ, 0 < x → P ⊤ x) (top_zero : P ⊤ 0) (coe_coe : ∀ x y : ℝ, P x y) : ∀ x y, P x y := have neg_right : ∀ {x y}, P x y → P x (-y) := fun h => symm <| neg_left <| symm h have : ∀ x, (∀ y : ℝ, 0 < y → P x y) → ∀ y : ℝ, y < 0 → P x y := fun _ h y hy => neg_neg (y : EReal) ▸ neg_right (h _ (neg_pos_of_neg hy)) @induction₂_neg_left P neg_left top_top top_pos top_zero (this _ top_pos) (neg_right top_top) (symm top_zero) (symm <| neg_left top_zero) (fun x hx => symm <| top_pos x hx) (fun x hx => symm <| neg_left <| top_pos x hx) coe_coe protected lemma neg_mul (x y : EReal) : -x * y = -(x * y) := by induction x, y using induction₂_neg_left with | top_zero | zero_top | zero_bot => simp only [zero_mul, mul_zero, neg_zero] | top_top | top_bot => rfl | neg_left h => rw [h, neg_neg, neg_neg] | coe_coe => norm_cast; exact neg_mul _ _ | top_pos _ h => rw [top_mul_coe_of_pos h, neg_top, bot_mul_coe_of_pos h] | pos_top _ h => rw [coe_mul_top_of_pos h, neg_top, ← coe_neg, coe_mul_top_of_neg (neg_neg_of_pos h)] | top_neg _ h => rw [top_mul_coe_of_neg h, neg_top, bot_mul_coe_of_neg h, neg_bot] | pos_bot _ h => rw [coe_mul_bot_of_pos h, neg_bot, ← coe_neg, coe_mul_bot_of_neg (neg_neg_of_pos h)] instance : HasDistribNeg EReal where neg_mul := EReal.neg_mul mul_neg := fun x y => by rw [x.mul_comm, x.mul_comm] exact y.neg_mul x lemma right_distrib_of_nonneg {a b c : EReal} (ha : 0 ≤ a) (hb : 0 ≤ b) : (a + b) * c = a * c + b * c := by rcases eq_or_lt_of_le ha with (rfl | a_pos) · simp rcases eq_or_lt_of_le hb with (rfl | b_pos) · simp rcases lt_trichotomy c 0 with (c_neg | rfl | c_pos) · induction c · rw [mul_bot_of_pos a_pos, mul_bot_of_pos b_pos, mul_bot_of_pos (add_pos a_pos b_pos), add_bot ⊥] · induction a · exfalso; exact not_lt_bot a_pos · induction b · norm_cast · norm_cast; exact right_distrib _ _ _ · norm_cast rw [add_top_of_ne_bot (coe_ne_bot _), top_mul_of_neg c_neg, add_bot] · rw [top_add_of_ne_bot (ne_bot_of_gt b_pos), top_mul_of_neg c_neg, bot_add] · exfalso; exact not_top_lt c_neg · simp · induction c · exfalso; exact not_lt_bot c_pos · induction a · exfalso; exact not_lt_bot a_pos · induction b · norm_cast · norm_cast; exact right_distrib _ _ _ · norm_cast rw [add_top_of_ne_bot (coe_ne_bot _), top_mul_of_pos c_pos, add_top_of_ne_bot (coe_ne_bot _)] · rw [top_add_of_ne_bot (ne_bot_of_gt b_pos), top_mul_of_pos c_pos, top_add_of_ne_bot (ne_bot_of_gt (mul_pos b_pos c_pos))] · rw [mul_top_of_pos a_pos, mul_top_of_pos b_pos, mul_top_of_pos (add_pos a_pos b_pos), top_add_top] lemma left_distrib_of_nonneg {a b c : EReal} (ha : 0 ≤ a) (hb : 0 ≤ b) : c * (a + b) = c * a + c * b := by nth_rewrite 1 [EReal.mul_comm]; nth_rewrite 2 [EReal.mul_comm]; nth_rewrite 3 [EReal.mul_comm] exact right_distrib_of_nonneg ha hb lemma le_iff_le_forall_real_gt (x y : EReal) : (∀ z : ℝ, x < z → y ≤ z) ↔ y ≤ x := by symm refine ⟨fun h z x_lt_z ↦ le_trans h (le_of_lt x_lt_z), ?_⟩ intro h induction x · apply le_of_eq ((eq_bot_iff_forall_lt y).2 _) intro z specialize h (z-1) (bot_lt_coe (z-1)) apply lt_of_le_of_lt h rw [EReal.coe_lt_coe_iff] exact sub_one_lt z · induction y · exact bot_le · norm_cast norm_cast at h by_contra x_lt_y rcases exists_between (lt_of_not_le x_lt_y) with ⟨z, x_lt_z, z_lt_y⟩ specialize h z x_lt_z exact not_le_of_lt z_lt_y h · exfalso specialize h (_+ 1) (EReal.coe_lt_coe_iff.2 (lt_add_one _)) exact not_le_of_lt (coe_lt_top (_ + 1)) h · exact le_top lemma ge_iff_le_forall_real_lt (x y : EReal) : (∀ z : ℝ, z < y → z ≤ x) ↔ y ≤ x := by refine ⟨fun h ↦ ?_, fun h z z_lt_y ↦ le_trans (le_of_lt z_lt_y) h⟩ induction x with | h_bot => refine ((eq_bot_iff_forall_lt y).2 fun z ↦ ?_).le refine lt_of_not_le fun z_le_y ↦ (not_le_of_lt (bot_lt_coe (z - 1)) (h (z - 1) (lt_of_lt_of_le ?_ z_le_y))) exact_mod_cast sub_one_lt z | h_real x => induction y with | h_bot => exact bot_le | h_real y => norm_cast at h ⊢ by_contra! x_lt_y rcases exists_between x_lt_y with ⟨z, x_lt_z, z_lt_y⟩ exact not_le_of_lt x_lt_z (h z z_lt_y) | h_top => exfalso norm_cast at h exact not_le_of_lt (lt_add_one x) <| h (x + 1) (coe_lt_top (x + 1)) | h_top => exact le_top /-! ### Absolute value -/ -- Porting note (#11215): TODO: use `Real.nnabs` for the case `(x : ℝ)` /-- The absolute value from `EReal` to `ℝ≥0∞`, mapping `⊥` and `⊤` to `⊤` and a real `x` to `|x|`. -/ protected def abs : EReal → ℝ≥0∞ | ⊥ => ⊤ | ⊤ => ⊤ | (x : ℝ) => ENNReal.ofReal |x| @[simp] theorem abs_top : (⊤ : EReal).abs = ⊤ := rfl @[simp] theorem abs_bot : (⊥ : EReal).abs = ⊤ := rfl theorem abs_def (x : ℝ) : (x : EReal).abs = ENNReal.ofReal |x| := rfl theorem abs_coe_lt_top (x : ℝ) : (x : EReal).abs < ⊤ := ENNReal.ofReal_lt_top @[simp] theorem abs_eq_zero_iff {x : EReal} : x.abs = 0 ↔ x = 0 := by induction x · simp only [abs_bot, ENNReal.top_ne_zero, bot_ne_zero] · simp only [abs_def, coe_eq_zero, ENNReal.ofReal_eq_zero, abs_nonpos_iff] · simp only [abs_top, ENNReal.top_ne_zero, top_ne_zero] @[simp] theorem abs_zero : (0 : EReal).abs = 0 := by rw [abs_eq_zero_iff] @[simp] theorem coe_abs (x : ℝ) : ((x : EReal).abs : EReal) = (|x| : ℝ) := by rw [abs_def, ← Real.coe_nnabs, ENNReal.ofReal_coe_nnreal]; rfl @[simp] protected theorem abs_neg : ∀ x : EReal, (-x).abs = x.abs | ⊤ => rfl | ⊥ => rfl | (x : ℝ) => by rw [abs_def, ← coe_neg, abs_def, abs_neg] @[simp] theorem abs_mul (x y : EReal) : (x * y).abs = x.abs * y.abs := by induction x, y using induction₂_symm_neg with | top_zero => simp only [zero_mul, mul_zero, abs_zero] | top_top => rfl | symm h => rwa [mul_comm, EReal.mul_comm] | coe_coe => simp only [← coe_mul, abs_def, _root_.abs_mul, ENNReal.ofReal_mul (abs_nonneg _)] | top_pos _ h => rw [top_mul_coe_of_pos h, abs_top, ENNReal.top_mul] rw [Ne, abs_eq_zero_iff, coe_eq_zero] exact h.ne' | neg_left h => rwa [neg_mul, EReal.abs_neg, EReal.abs_neg] /-! ### Sign -/ open SignType (sign) theorem sign_top : sign (⊤ : EReal) = 1 := rfl theorem sign_bot : sign (⊥ : EReal) = -1 := rfl @[simp] theorem sign_coe (x : ℝ) : sign (x : EReal) = sign x := by simp only [sign, OrderHom.coe_mk, EReal.coe_pos, EReal.coe_neg'] @[simp, norm_cast] theorem coe_coe_sign (x : SignType) : ((x : ℝ) : EReal) = x := by cases x <;> rfl @[simp] theorem sign_neg : ∀ x : EReal, sign (-x) = -sign x | ⊤ => rfl | ⊥ => rfl | (x : ℝ) => by rw [← coe_neg, sign_coe, sign_coe, Left.sign_neg] @[simp] theorem sign_mul (x y : EReal) : sign (x * y) = sign x * sign y := by induction x, y using induction₂_symm_neg with | top_zero => simp only [zero_mul, mul_zero, sign_zero] | top_top => rfl | symm h => rwa [mul_comm, EReal.mul_comm] | coe_coe => simp only [← coe_mul, sign_coe, _root_.sign_mul, ENNReal.ofReal_mul (abs_nonneg _)] | top_pos _ h => rw [top_mul_coe_of_pos h, sign_top, one_mul, sign_pos (EReal.coe_pos.2 h)] | neg_left h => rw [neg_mul, sign_neg, sign_neg, h, neg_mul] @[simp] protected theorem sign_mul_abs : ∀ x : EReal, (sign x * x.abs : EReal) = x | ⊥ => by simp | ⊤ => by simp | (x : ℝ) => by rw [sign_coe, coe_abs, ← coe_coe_sign, ← coe_mul, sign_mul_abs] @[simp] protected theorem abs_mul_sign (x : EReal) : (x.abs * sign x : EReal) = x := by rw [EReal.mul_comm, EReal.sign_mul_abs] theorem sign_eq_and_abs_eq_iff_eq {x y : EReal} : x.abs = y.abs ∧ sign x = sign y ↔ x = y := by constructor · rintro ⟨habs, hsign⟩ rw [← x.sign_mul_abs, ← y.sign_mul_abs, habs, hsign] · rintro rfl exact ⟨rfl, rfl⟩ theorem le_iff_sign {x y : EReal} : x ≤ y ↔ sign x < sign y ∨ sign x = SignType.neg ∧ sign y = SignType.neg ∧ y.abs ≤ x.abs ∨ sign x = SignType.zero ∧ sign y = SignType.zero ∨ sign x = SignType.pos ∧ sign y = SignType.pos ∧ x.abs ≤ y.abs := by constructor · intro h refine (sign.monotone h).lt_or_eq.imp_right (fun hs => ?_) rw [← x.sign_mul_abs, ← y.sign_mul_abs] at h cases hy : sign y <;> rw [hs, hy] at h ⊢ · simp · left; simpa using h · right; right; simpa using h · rintro (h | h | h | h) · exact (sign.monotone.reflect_lt h).le all_goals rw [← x.sign_mul_abs, ← y.sign_mul_abs]; simp [h] instance : CommMonoidWithZero EReal := { inferInstanceAs (MulZeroOneClass EReal) with mul_assoc := fun x y z => by rw [← sign_eq_and_abs_eq_iff_eq] simp only [mul_assoc, abs_mul, eq_self_iff_true, sign_mul, and_self_iff] mul_comm := EReal.mul_comm } instance : PosMulMono EReal := posMulMono_iff_covariant_pos.2 <| .mk <| by rintro ⟨x, x0⟩ a b h simp only [le_iff_sign, EReal.sign_mul, sign_pos x0, one_mul, EReal.abs_mul] at h ⊢ exact h.imp_right <| Or.imp (And.imp_right <| And.imp_right (mul_le_mul_left' · _)) <| Or.imp_right <| And.imp_right <| And.imp_right (mul_le_mul_left' · _) instance : MulPosMono EReal := posMulMono_iff_mulPosMono.1 inferInstance instance : PosMulReflectLT EReal := PosMulMono.toPosMulReflectLT instance : MulPosReflectLT EReal := MulPosMono.toMulPosReflectLT @[simp, norm_cast] theorem coe_pow (x : ℝ) (n : ℕ) : (↑(x ^ n) : EReal) = (x : EReal) ^ n := map_pow (⟨⟨(↑), coe_one⟩, coe_mul⟩ : ℝ →* EReal) _ _ @[simp, norm_cast] theorem coe_ennreal_pow (x : ℝ≥0∞) (n : ℕ) : (↑(x ^ n) : EReal) = (x : EReal) ^ n := map_pow (⟨⟨(↑), coe_ennreal_one⟩, coe_ennreal_mul⟩ : ℝ≥0∞ →* EReal) _ _ /-! ### Min and Max -/ lemma min_neg_neg (x y : EReal) : min (-x) (-y) = -max x y := by rcases le_total x y with (h | h) <;> simp_all lemma max_neg_neg (x y : EReal) : max (-x) (-y) = -min x y := by rcases le_total x y with (h | h) <;> simp_all /-! ### Inverse -/ /-- Multiplicative inverse of an `EReal`. We choose `0⁻¹ = 0` to guarantee several good properties, for instance `(a * b)⁻¹ = a⁻¹ * b⁻¹`. -/ protected def inv : EReal → EReal | ⊥ => 0 | ⊤ => 0 | (x : ℝ) => (x⁻¹ : ℝ) instance : Inv (EReal) := ⟨EReal.inv⟩ noncomputable instance : DivInvMonoid EReal where inv := EReal.inv @[simp] lemma inv_bot : (⊥ : EReal)⁻¹ = 0 := rfl @[simp] lemma inv_top : (⊤ : EReal)⁻¹ = 0 := rfl lemma coe_inv (x : ℝ) : (x⁻¹ : ℝ) = (x : EReal)⁻¹ := rfl @[simp] lemma inv_zero : (0 : EReal)⁻¹ = 0 := by change (0 : ℝ)⁻¹ = (0 : EReal) rw [GroupWithZero.inv_zero, coe_zero] noncomputable instance : DivInvOneMonoid EReal where inv_one := by nth_rw 1 [← coe_one, ← coe_inv 1, _root_.inv_one, coe_one] lemma inv_neg (a : EReal) : (-a)⁻¹ = -a⁻¹ := by induction a · rw [neg_bot, inv_top, inv_bot, neg_zero] · rw [← coe_inv _, ← coe_neg _⁻¹, ← coe_neg _, ← coe_inv (-_)] exact EReal.coe_eq_coe_iff.2 _root_.inv_neg · rw [neg_top, inv_bot, inv_top, neg_zero] lemma inv_inv {a : EReal} (h : a ≠ ⊥) (h' : a ≠ ⊤) : (a⁻¹)⁻¹ = a := by rw [← coe_toReal h' h, ← coe_inv a.toReal, ← coe_inv a.toReal⁻¹, _root_.inv_inv a.toReal] lemma mul_inv (a b : EReal) : (a * b)⁻¹ = a⁻¹ * b⁻¹ := by induction a, b using EReal.induction₂_symm with | top_top | top_zero | top_bot | zero_bot | bot_bot => simp | @symm a b h => rw [mul_comm b a, mul_comm b⁻¹ a⁻¹]; exact h | top_pos x x_pos => rw [top_mul_of_pos (EReal.coe_pos.2 x_pos), inv_top, zero_mul] | top_neg x x_neg => rw [top_mul_of_neg (EReal.coe_neg'.2 x_neg), inv_bot, inv_top, zero_mul] | pos_bot x x_pos => rw [mul_bot_of_pos (EReal.coe_pos.2 x_pos), inv_bot, mul_zero] | coe_coe x y => rw [← coe_mul, ← coe_inv, _root_.mul_inv, coe_mul, coe_inv, coe_inv] | neg_bot x x_neg => rw [mul_bot_of_neg (EReal.coe_neg'.2 x_neg), inv_top, inv_bot, mul_zero] /-! #### Inversion and Absolute Value -/ lemma sign_mul_inv_abs (a : EReal) : (sign a) * (a.abs : EReal)⁻¹ = a⁻¹ := by induction a with | h_bot | h_top => simp | h_real a => rcases lt_trichotomy a 0 with (a_neg | rfl | a_pos) · rw [sign_coe, _root_.sign_neg a_neg, coe_neg_one, neg_one_mul, ← inv_neg, abs_def a, coe_ennreal_ofReal, max_eq_left (abs_nonneg a), ← coe_neg |a|, abs_of_neg a_neg, neg_neg] · rw [coe_zero, sign_zero, SignType.coe_zero, abs_zero, coe_ennreal_zero, inv_zero, mul_zero] · rw [sign_coe, _root_.sign_pos a_pos, SignType.coe_one, one_mul] simp only [abs_def a, coe_ennreal_ofReal, abs_nonneg, max_eq_left] congr exact abs_of_pos a_pos lemma sign_mul_inv_abs' (a : EReal) : (sign a) * ((a.abs⁻¹ : ℝ≥0∞) : EReal) = a⁻¹ := by induction a with | h_bot | h_top => simp | h_real a => rcases lt_trichotomy a 0 with (a_neg | rfl | a_pos) · rw [sign_coe, _root_.sign_neg a_neg, coe_neg_one, neg_one_mul, abs_def a, ← ofReal_inv_of_pos (abs_pos_of_neg a_neg), coe_ennreal_ofReal, max_eq_left (inv_nonneg.2 (abs_nonneg a)), ← coe_neg |a|⁻¹, ← coe_inv a, abs_of_neg a_neg, ← _root_.inv_neg, neg_neg] · simp · rw [sign_coe, _root_.sign_pos a_pos, SignType.coe_one, one_mul, abs_def a, ← ofReal_inv_of_pos (abs_pos_of_pos a_pos), coe_ennreal_ofReal, max_eq_left (inv_nonneg.2 (abs_nonneg a)), ← coe_inv a] congr exact abs_of_pos a_pos /-! #### Inversion and Positivity -/ lemma inv_nonneg_of_nonneg {a : EReal} (h : 0 ≤ a) : 0 ≤ a⁻¹ := by induction a with | h_bot | h_top => simp | h_real a => rw [← coe_inv a, EReal.coe_nonneg, inv_nonneg]; exact EReal.coe_nonneg.1 h lemma inv_nonpos_of_nonpos {a : EReal} (h : a ≤ 0) : a⁻¹ ≤ 0 := by induction a with | h_bot | h_top => simp | h_real a => rw [← coe_inv a, EReal.coe_nonpos, inv_nonpos]; exact EReal.coe_nonpos.1 h lemma inv_pos_of_pos_ne_top {a : EReal} (h : 0 < a) (h' : a ≠ ⊤) : 0 < a⁻¹ := by induction a with | h_bot => exact (not_lt_bot h).rec | h_real a => rw [← coe_inv a]; norm_cast at *; exact inv_pos_of_pos h | h_top => exact (h' (Eq.refl ⊤)).rec lemma inv_neg_of_neg_ne_bot {a : EReal} (h : a < 0) (h' : a ≠ ⊥) : a⁻¹ < 0 := by induction a with | h_bot => exact (h' (Eq.refl ⊥)).rec | h_real a => rw [← coe_inv a]; norm_cast at *; exact inv_lt_zero.2 h | h_top => exact (not_top_lt h).rec /-! ### Division -/ lemma div_eq_inv_mul (a b : EReal) : a / b = b⁻¹ * a := EReal.mul_comm a b⁻¹ lemma coe_div (a b : ℝ) : (a / b : ℝ) = (a : EReal) / (b : EReal) := rfl theorem natCast_div_le (m n : ℕ) : (m / n : ℕ) ≤ (m : EReal) / (n : EReal) := by rw [← coe_coe_eq_natCast, ← coe_coe_eq_natCast, ← coe_coe_eq_natCast, ← coe_div, EReal.coe_le_coe_iff] exact Nat.cast_div_le @[simp] lemma div_bot {a : EReal} : a / ⊥ = 0 := inv_bot ▸ mul_zero a @[simp] lemma div_top {a : EReal} : a / ⊤ = 0 := inv_top ▸ mul_zero a @[simp] lemma div_zero {a : EReal} : a / 0 = 0 := by change a * 0⁻¹ = 0 rw [inv_zero, mul_zero a] @[simp] lemma zero_div {a : EReal} : 0 / a = 0 := zero_mul a⁻¹ lemma top_div_of_pos_ne_top {a : EReal} (h : 0 < a) (h' : a ≠ ⊤) : ⊤ / a = ⊤ := top_mul_of_pos (inv_pos_of_pos_ne_top h h') lemma top_div_of_neg_ne_bot {a : EReal} (h : a < 0) (h' : a ≠ ⊥) : ⊤ / a = ⊥ := top_mul_of_neg (inv_neg_of_neg_ne_bot h h') lemma bot_div_of_pos_ne_top {a : EReal} (h : 0 < a) (h' : a ≠ ⊤) : ⊥ / a = ⊥ := bot_mul_of_pos (inv_pos_of_pos_ne_top h h') lemma bot_div_of_neg_ne_bot {a : EReal} (h : a < 0) (h' : a ≠ ⊥) : ⊥ / a = ⊤ := bot_mul_of_neg (inv_neg_of_neg_ne_bot h h') /-! #### Division and Multiplication -/ lemma div_self {a : EReal} (h₁ : a ≠ ⊥) (h₂ : a ≠ ⊤) (h₃ : a ≠ 0) : a / a = 1 := by rw [← coe_toReal h₂ h₁] at h₃ ⊢ rw [← coe_div, _root_.div_self (coe_ne_zero.1 h₃), coe_one] lemma mul_div (a b c : EReal) : a * (b / c) = (a * b) / c := by change a * (b * c⁻¹) = (a * b) * c⁻¹ rw [mul_assoc] lemma mul_div_right (a b c : EReal) : (a / b) * c = (a * c) / b := by rw [mul_comm, EReal.mul_div, mul_comm] lemma div_div (a b c : EReal) : a / b / c = a / (b * c) := by change (a * b⁻¹) * c⁻¹ = a * (b * c)⁻¹ rw [mul_assoc a b⁻¹, mul_inv] lemma div_mul_cancel {a b : EReal} (h₁ : b ≠ ⊥) (h₂ : b ≠ ⊤) (h₃ : b ≠ 0) : (a / b) * b = a := by change (a * b⁻¹) * b = a rw [mul_assoc, mul_comm b⁻¹ b] change a * (b / b) = a rw [div_self h₁ h₂ h₃, mul_one] lemma mul_div_cancel {a b : EReal} (h₁ : b ≠ ⊥) (h₂ : b ≠ ⊤) (h₃ : b ≠ 0) : b * (a / b) = a := by rw [mul_comm, div_mul_cancel h₁ h₂ h₃] lemma mul_div_mul_cancel {a b c : EReal} (h₁ : c ≠ ⊥) (h₂ : c ≠ ⊤) (h₃ : c ≠ 0) : (a * c) / (b * c) = a / b := by change (a * c) * (b * c)⁻¹ = a * b⁻¹ rw [mul_assoc, mul_inv b c] congr exact mul_div_cancel h₁ h₂ h₃ /-! #### Division Distributivity -/ lemma div_right_distrib_of_nonneg {a b c : EReal} (h : 0 ≤ a) (h' : 0 ≤ b) : (a + b) / c = (a / c) + (b / c) := EReal.right_distrib_of_nonneg h h' /-! #### Division and Order s-/ lemma monotone_div_right_of_nonneg {b : EReal} (h : 0 ≤ b) : Monotone fun a ↦ a / b := fun _ _ h' ↦ mul_le_mul_of_nonneg_right h' (inv_nonneg_of_nonneg h) lemma div_le_div_right_of_nonneg {a a' b : EReal} (h : 0 ≤ b) (h' : a ≤ a') : a / b ≤ a' / b := monotone_div_right_of_nonneg h h' lemma strictMono_div_right_of_pos {b : EReal} (h : 0 < b) (h' : b ≠ ⊤) : StrictMono fun a ↦ a / b := by intro a a' a_lt_a' apply lt_of_le_of_ne <| div_le_div_right_of_nonneg (le_of_lt h) (le_of_lt a_lt_a') intro hyp apply ne_of_lt a_lt_a' rw [← @EReal.mul_div_cancel a b (ne_bot_of_gt h) h' (ne_of_gt h), hyp, @EReal.mul_div_cancel a' b (ne_bot_of_gt h) h' (ne_of_gt h)] lemma div_lt_div_right_of_pos {a a' b : EReal} (h₁ : 0 < b) (h₂ : b ≠ ⊤) (h₃ : a < a') : a / b < a' / b := strictMono_div_right_of_pos h₁ h₂ h₃ lemma antitone_div_right_of_nonpos {b : EReal} (h : b ≤ 0) : Antitone fun a ↦ a / b := by intro a a' h' change a' * b⁻¹ ≤ a * b⁻¹ rw [← neg_neg (a * b⁻¹), ← neg_neg (a' * b⁻¹), neg_le_neg_iff, mul_comm a b⁻¹, mul_comm a' b⁻¹, ← neg_mul b⁻¹ a, ← neg_mul b⁻¹ a', mul_comm (-b⁻¹) a, mul_comm (-b⁻¹) a', ← inv_neg b] have : 0 ≤ -b := by apply le_neg_of_le_neg; simp [h] exact div_le_div_right_of_nonneg this h' lemma div_le_div_right_of_nonpos {a a' b : EReal} (h : b ≤ 0) (h' : a ≤ a') : a' / b ≤ a / b := antitone_div_right_of_nonpos h h' lemma strictAnti_div_right_of_neg {b : EReal} (h : b < 0) (h' : b ≠ ⊥) : StrictAnti fun a ↦ a / b := by intro a a' a_lt_a' simp only apply lt_of_le_of_ne <| div_le_div_right_of_nonpos (le_of_lt h) (le_of_lt a_lt_a') intro hyp apply ne_of_lt a_lt_a' rw [← @EReal.mul_div_cancel a b h' (ne_top_of_lt h) (ne_of_lt h), ← hyp, @EReal.mul_div_cancel a' b h' (ne_top_of_lt h) (ne_of_lt h)] lemma div_lt_div_right_of_neg {a a' b : EReal} (h₁ : b < 0) (h₂ : b ≠ ⊥) (h₃ : a < a') : a' / b < a / b := strictAnti_div_right_of_neg h₁ h₂ h₃ lemma le_div_iff_mul_le {a b c : EReal} (h : b > 0) (h' : b ≠ ⊤) : a ≤ c / b ↔ a * b ≤ c := by nth_rw 1 [← @mul_div_cancel a b (ne_bot_of_gt h) h' (ne_of_gt h)] rw [mul_div b a b, mul_comm a b] exact StrictMono.le_iff_le (strictMono_div_right_of_pos h h') lemma div_le_iff_le_mul {a b c : EReal} (h : 0 < b) (h' : b ≠ ⊤) : a / b ≤ c ↔ a ≤ b * c := by nth_rw 1 [← @mul_div_cancel c b (ne_bot_of_gt h) h' (ne_of_gt h)] rw [mul_div b c b, mul_comm b] exact StrictMono.le_iff_le (strictMono_div_right_of_pos h h') lemma div_nonneg {a b : EReal} (h : 0 ≤ a) (h' : 0 ≤ b) : 0 ≤ a / b := mul_nonneg h (inv_nonneg_of_nonneg h') lemma div_nonpos_of_nonpos_of_nonneg {a b : EReal} (h : a ≤ 0) (h' : 0 ≤ b) : a / b ≤ 0 := mul_nonpos_of_nonpos_of_nonneg h (inv_nonneg_of_nonneg h') lemma div_nonpos_of_nonneg_of_nonpos {a b : EReal} (h : 0 ≤ a) (h' : b ≤ 0) : a / b ≤ 0 := mul_nonpos_of_nonneg_of_nonpos h (inv_nonpos_of_nonpos h') lemma div_nonneg_of_nonpos_of_nonpos {a b : EReal} (h : a ≤ 0) (h' : b ≤ 0) : 0 ≤ a / b := le_of_eq_of_le (Eq.symm zero_div) (div_le_div_right_of_nonpos h' h) end EReal -- Porting note(https://github.com/leanprover-community/mathlib4/issues/6038): restore /- namespace Tactic open Positivity private theorem ereal_coe_ne_zero {r : ℝ} : r ≠ 0 → (r : EReal) ≠ 0 := EReal.coe_ne_zero.2 private theorem ereal_coe_nonneg {r : ℝ} : 0 ≤ r → 0 ≤ (r : EReal) := EReal.coe_nonneg.2 private theorem ereal_coe_pos {r : ℝ} : 0 < r → 0 < (r : EReal) := EReal.coe_pos.2 private theorem ereal_coe_ennreal_pos {r : ℝ≥0∞} : 0 < r → 0 < (r : EReal) := EReal.coe_ennreal_pos.2 /-- Extension for the `positivity` tactic: cast from `ℝ` to `EReal`. -/ @[positivity] unsafe def positivity_coe_real_ereal : expr → tactic strictness | q(@coe _ _ $(inst) $(a)) => do unify inst q(@coeToLift _ _ <| @coeBase _ _ EReal.hasCoe) let strictness_a ← core a match strictness_a with | positive p => positive <$> mk_app `` ereal_coe_pos [p] | nonnegative p => nonnegative <$> mk_mapp `` ereal_coe_nonneg [a, p] | nonzero p => nonzero <$> mk_mapp `` ereal_coe_ne_zero [a, p] | e => pp e >>= fail ∘ format.bracket "The expression " " is not of the form `(r : ereal)` for `r : ℝ`" /-- Extension for the `positivity` tactic: cast from `ℝ≥0∞` to `EReal`. -/ @[positivity] unsafe def positivity_coe_ennreal_ereal : expr → tactic strictness | q(@coe _ _ $(inst) $(a)) => do unify inst q(@coeToLift _ _ <| @coeBase _ _ EReal.hasCoeENNReal) let strictness_a ← core a match strictness_a with | positive p => positive <$> mk_app `` ereal_coe_ennreal_pos [p] | _ => nonnegative <$> mk_mapp `ereal.coe_ennreal_nonneg [a] | e => pp e >>= fail ∘ format.bracket "The expression " " is not of the form `(r : ereal)` for `r : ℝ≥0∞`" end Tactic -/
Data\Real\GoldenRatio.lean
/- Copyright (c) 2020 Anatole Dedecker. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anatole Dedecker, Alexey Soloyev, Junyan Xu, Kamila Szewczyk -/ import Mathlib.Data.Real.Irrational import Mathlib.Data.Nat.Fib.Basic import Mathlib.Data.Fin.VecNotation import Mathlib.Algebra.LinearRecurrence import Mathlib.Tactic.NormNum.NatFib import Mathlib.Tactic.NormNum.Prime /-! # The golden ratio and its conjugate This file defines the golden ratio `φ := (1 + √5)/2` and its conjugate `ψ := (1 - √5)/2`, which are the two real roots of `X² - X - 1`. Along with various computational facts about them, we prove their irrationality, and we link them to the Fibonacci sequence by proving Binet's formula. -/ noncomputable section open Polynomial /-- The golden ratio `φ := (1 + √5)/2`. -/ abbrev goldenRatio : ℝ := (1 + √5) / 2 /-- The conjugate of the golden ratio `ψ := (1 - √5)/2`. -/ abbrev goldenConj : ℝ := (1 - √5) / 2 @[inherit_doc goldenRatio] scoped[goldenRatio] notation "φ" => goldenRatio @[inherit_doc goldenConj] scoped[goldenRatio] notation "ψ" => goldenConj open Real goldenRatio /-- The inverse of the golden ratio is the opposite of its conjugate. -/ theorem inv_gold : φ⁻¹ = -ψ := by have : 1 + √5 ≠ 0 := ne_of_gt (add_pos (by norm_num) <| Real.sqrt_pos.mpr (by norm_num)) field_simp [sub_mul, mul_add] norm_num /-- The opposite of the golden ratio is the inverse of its conjugate. -/ theorem inv_goldConj : ψ⁻¹ = -φ := by rw [inv_eq_iff_eq_inv, ← neg_inv, ← neg_eq_iff_eq_neg] exact inv_gold.symm @[simp] theorem gold_mul_goldConj : φ * ψ = -1 := by field_simp rw [← sq_sub_sq] norm_num @[simp] theorem goldConj_mul_gold : ψ * φ = -1 := by rw [mul_comm] exact gold_mul_goldConj @[simp] theorem gold_add_goldConj : φ + ψ = 1 := by rw [goldenRatio, goldenConj] ring theorem one_sub_goldConj : 1 - φ = ψ := by linarith [gold_add_goldConj] theorem one_sub_gold : 1 - ψ = φ := by linarith [gold_add_goldConj] @[simp] theorem gold_sub_goldConj : φ - ψ = √5 := by ring theorem gold_pow_sub_gold_pow (n : ℕ) : φ ^ (n + 2) - φ ^ (n + 1) = φ ^ n := by rw [goldenRatio]; ring_nf; norm_num; ring @[simp 1200] theorem gold_sq : φ ^ 2 = φ + 1 := by rw [goldenRatio, ← sub_eq_zero] ring_nf rw [Real.sq_sqrt] <;> norm_num @[simp 1200] theorem goldConj_sq : ψ ^ 2 = ψ + 1 := by rw [goldenConj, ← sub_eq_zero] ring_nf rw [Real.sq_sqrt] <;> norm_num theorem gold_pos : 0 < φ := mul_pos (by apply add_pos <;> norm_num) <| inv_pos.2 zero_lt_two theorem gold_ne_zero : φ ≠ 0 := ne_of_gt gold_pos theorem one_lt_gold : 1 < φ := by refine lt_of_mul_lt_mul_left ?_ (le_of_lt gold_pos) simp [← sq, gold_pos, zero_lt_one, - div_pow] -- Porting note: Added `- div_pow` theorem gold_lt_two : φ < 2 := by calc (1 + sqrt 5) / 2 < (1 + 3) / 2 := by gcongr; rw [sqrt_lt'] <;> norm_num _ = 2 := by norm_num theorem goldConj_neg : ψ < 0 := by linarith [one_sub_goldConj, one_lt_gold] theorem goldConj_ne_zero : ψ ≠ 0 := ne_of_lt goldConj_neg theorem neg_one_lt_goldConj : -1 < ψ := by rw [neg_lt, ← inv_gold] exact inv_lt_one one_lt_gold /-! ## Irrationality -/ /-- The golden ratio is irrational. -/ theorem gold_irrational : Irrational φ := by have := Nat.Prime.irrational_sqrt (show Nat.Prime 5 by norm_num) have := this.rat_add 1 have := this.rat_mul (show (0.5 : ℚ) ≠ 0 by norm_num) convert this norm_num field_simp /-- The conjugate of the golden ratio is irrational. -/ theorem goldConj_irrational : Irrational ψ := by have := Nat.Prime.irrational_sqrt (show Nat.Prime 5 by norm_num) have := this.rat_sub 1 have := this.rat_mul (show (0.5 : ℚ) ≠ 0 by norm_num) convert this norm_num field_simp /-! ## Links with Fibonacci sequence -/ section Fibrec variable {α : Type*} [CommSemiring α] /-- The recurrence relation satisfied by the Fibonacci sequence. -/ def fibRec : LinearRecurrence α where order := 2 coeffs := ![1, 1] section Poly open Polynomial /-- The characteristic polynomial of `fibRec` is `X² - (X + 1)`. -/ theorem fibRec_charPoly_eq {β : Type*} [CommRing β] : fibRec.charPoly = X ^ 2 - (X + (1 : β[X])) := by rw [fibRec, LinearRecurrence.charPoly] simp [Finset.sum_fin_eq_sum_range, Finset.sum_range_succ', ← smul_X_eq_monomial] end Poly /-- As expected, the Fibonacci sequence is a solution of `fibRec`. -/ theorem fib_isSol_fibRec : fibRec.IsSolution (fun x => x.fib : ℕ → α) := by rw [fibRec] intro n simp only rw [Nat.fib_add_two, add_comm] simp [Finset.sum_fin_eq_sum_range, Finset.sum_range_succ'] /-- The geometric sequence `fun n ↦ φ^n` is a solution of `fibRec`. -/ theorem geom_gold_isSol_fibRec : fibRec.IsSolution (φ ^ ·) := by rw [fibRec.geom_sol_iff_root_charPoly, fibRec_charPoly_eq] simp [sub_eq_zero, - div_pow] -- Porting note: Added `- div_pow` /-- The geometric sequence `fun n ↦ ψ^n` is a solution of `fibRec`. -/ theorem geom_goldConj_isSol_fibRec : fibRec.IsSolution (ψ ^ ·) := by rw [fibRec.geom_sol_iff_root_charPoly, fibRec_charPoly_eq] simp [sub_eq_zero, - div_pow] -- Porting note: Added `- div_pow` end Fibrec /-- Binet's formula as a function equality. -/ theorem Real.coe_fib_eq' : (fun n => Nat.fib n : ℕ → ℝ) = fun n => (φ ^ n - ψ ^ n) / √5 := by rw [fibRec.sol_eq_of_eq_init] · intro i hi norm_cast at hi fin_cases hi · simp · simp only [goldenRatio, goldenConj] ring_nf rw [mul_inv_cancel]; norm_num · exact fib_isSol_fibRec · -- Porting note: Rewrote this proof suffices LinearRecurrence.IsSolution fibRec ((fun n ↦ (√5)⁻¹ * φ ^ n) - (fun n ↦ (√5)⁻¹ * ψ ^ n)) by convert this rw [Pi.sub_apply] ring apply (@fibRec ℝ _).solSpace.sub_mem · exact Submodule.smul_mem fibRec.solSpace (√5)⁻¹ geom_gold_isSol_fibRec · exact Submodule.smul_mem fibRec.solSpace (√5)⁻¹ geom_goldConj_isSol_fibRec /-- Binet's formula as a dependent equality. -/ theorem Real.coe_fib_eq : ∀ n, (Nat.fib n : ℝ) = (φ ^ n - ψ ^ n) / √5 := by rw [← Function.funext_iff, Real.coe_fib_eq'] /-- Relationship between the Fibonacci Sequence, Golden Ratio and its conjugate's exponents --/ theorem fib_golden_conj_exp (n : ℕ) : Nat.fib (n + 1) - φ * Nat.fib n = ψ ^ n := by repeat rw [coe_fib_eq] rw [mul_div, div_sub_div_same, mul_sub, ← pow_succ'] ring_nf have nz : sqrt 5 ≠ 0 := by norm_num rw [← (mul_inv_cancel nz).symm, one_mul] /-- Relationship between the Fibonacci Sequence, Golden Ratio and its exponents --/ theorem fib_golden_exp' (n : ℕ) : φ * Nat.fib (n + 1) + Nat.fib n = φ ^ (n + 1) := by induction n with | zero => norm_num | succ n ih => calc _ = φ * (Nat.fib n) + φ ^ 2 * (Nat.fib (n + 1)) := by simp only [Nat.fib_add_one (Nat.succ_ne_zero n), Nat.succ_sub_succ_eq_sub, tsub_zero, Nat.cast_add, gold_sq]; ring _ = φ * ((Nat.fib n) + φ * (Nat.fib (n + 1))) := by ring _ = φ ^ (n + 2) := by rw [add_comm, ih]; ring
Data\Real\Hyperreal.lean
/- Copyright (c) 2019 Abhimanyu Pallavi Sudhir. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Abhimanyu Pallavi Sudhir -/ import Mathlib.Order.Filter.FilterProduct import Mathlib.Analysis.SpecificLimits.Basic /-! # Construction of the hyperreal numbers as an ultraproduct of real sequences. -/ open scoped Classical open Filter Germ Topology /-- Hyperreal numbers on the ultrafilter extending the cofinite filter -/ def Hyperreal : Type := Germ (hyperfilter ℕ : Filter ℕ) ℝ deriving Inhabited namespace Hyperreal @[inherit_doc] notation "ℝ*" => Hyperreal noncomputable instance : LinearOrderedField ℝ* := inferInstanceAs (LinearOrderedField (Germ _ _)) /-- Natural embedding `ℝ → ℝ*`. -/ @[coe] def ofReal : ℝ → ℝ* := const noncomputable instance : CoeTC ℝ ℝ* := ⟨ofReal⟩ @[simp, norm_cast] theorem coe_eq_coe {x y : ℝ} : (x : ℝ*) = y ↔ x = y := Germ.const_inj theorem coe_ne_coe {x y : ℝ} : (x : ℝ*) ≠ y ↔ x ≠ y := coe_eq_coe.not @[simp, norm_cast] theorem coe_eq_zero {x : ℝ} : (x : ℝ*) = 0 ↔ x = 0 := coe_eq_coe @[simp, norm_cast] theorem coe_eq_one {x : ℝ} : (x : ℝ*) = 1 ↔ x = 1 := coe_eq_coe @[norm_cast] theorem coe_ne_zero {x : ℝ} : (x : ℝ*) ≠ 0 ↔ x ≠ 0 := coe_ne_coe @[norm_cast] theorem coe_ne_one {x : ℝ} : (x : ℝ*) ≠ 1 ↔ x ≠ 1 := coe_ne_coe @[simp, norm_cast] theorem coe_one : ↑(1 : ℝ) = (1 : ℝ*) := rfl @[simp, norm_cast] theorem coe_zero : ↑(0 : ℝ) = (0 : ℝ*) := rfl @[simp, norm_cast] theorem coe_inv (x : ℝ) : ↑x⁻¹ = (x⁻¹ : ℝ*) := rfl @[simp, norm_cast] theorem coe_neg (x : ℝ) : ↑(-x) = (-x : ℝ*) := rfl @[simp, norm_cast] theorem coe_add (x y : ℝ) : ↑(x + y) = (x + y : ℝ*) := rfl -- See note [no_index around OfNat.ofNat] @[simp, norm_cast] theorem coe_ofNat (n : ℕ) [n.AtLeastTwo] : ((no_index (OfNat.ofNat n : ℝ)) : ℝ*) = OfNat.ofNat n := rfl @[simp, norm_cast] theorem coe_mul (x y : ℝ) : ↑(x * y) = (x * y : ℝ*) := rfl @[simp, norm_cast] theorem coe_div (x y : ℝ) : ↑(x / y) = (x / y : ℝ*) := rfl @[simp, norm_cast] theorem coe_sub (x y : ℝ) : ↑(x - y) = (x - y : ℝ*) := rfl @[simp, norm_cast] theorem coe_le_coe {x y : ℝ} : (x : ℝ*) ≤ y ↔ x ≤ y := Germ.const_le_iff @[simp, norm_cast] theorem coe_lt_coe {x y : ℝ} : (x : ℝ*) < y ↔ x < y := Germ.const_lt_iff @[simp, norm_cast] theorem coe_nonneg {x : ℝ} : 0 ≤ (x : ℝ*) ↔ 0 ≤ x := coe_le_coe @[simp, norm_cast] theorem coe_pos {x : ℝ} : 0 < (x : ℝ*) ↔ 0 < x := coe_lt_coe @[simp, norm_cast] theorem coe_abs (x : ℝ) : ((|x| : ℝ) : ℝ*) = |↑x| := const_abs x @[simp, norm_cast] theorem coe_max (x y : ℝ) : ((max x y : ℝ) : ℝ*) = max ↑x ↑y := Germ.const_max _ _ @[simp, norm_cast] theorem coe_min (x y : ℝ) : ((min x y : ℝ) : ℝ*) = min ↑x ↑y := Germ.const_min _ _ /-- Construct a hyperreal number from a sequence of real numbers. -/ def ofSeq (f : ℕ → ℝ) : ℝ* := (↑f : Germ (hyperfilter ℕ : Filter ℕ) ℝ) theorem ofSeq_surjective : Function.Surjective ofSeq := Quot.exists_rep theorem ofSeq_lt_ofSeq {f g : ℕ → ℝ} : ofSeq f < ofSeq g ↔ ∀ᶠ n in hyperfilter ℕ, f n < g n := Germ.coe_lt /-- A sample infinitesimal hyperreal-/ noncomputable def epsilon : ℝ* := ofSeq fun n => n⁻¹ /-- A sample infinite hyperreal-/ noncomputable def omega : ℝ* := ofSeq Nat.cast @[inherit_doc] scoped notation "ε" => Hyperreal.epsilon @[inherit_doc] scoped notation "ω" => Hyperreal.omega @[simp] theorem inv_omega : ω⁻¹ = ε := rfl @[simp] theorem inv_epsilon : ε⁻¹ = ω := @inv_inv _ _ ω theorem omega_pos : 0 < ω := Germ.coe_pos.2 <| Nat.hyperfilter_le_atTop <| (eventually_gt_atTop 0).mono fun _ ↦ Nat.cast_pos.2 theorem epsilon_pos : 0 < ε := inv_pos_of_pos omega_pos theorem epsilon_ne_zero : ε ≠ 0 := epsilon_pos.ne' theorem omega_ne_zero : ω ≠ 0 := omega_pos.ne' theorem epsilon_mul_omega : ε * ω = 1 := @inv_mul_cancel _ _ ω omega_ne_zero theorem lt_of_tendsto_zero_of_pos {f : ℕ → ℝ} (hf : Tendsto f atTop (𝓝 0)) : ∀ {r : ℝ}, 0 < r → ofSeq f < (r : ℝ*) := fun hr ↦ ofSeq_lt_ofSeq.2 <| (hf.eventually <| gt_mem_nhds hr).filter_mono Nat.hyperfilter_le_atTop theorem neg_lt_of_tendsto_zero_of_pos {f : ℕ → ℝ} (hf : Tendsto f atTop (𝓝 0)) : ∀ {r : ℝ}, 0 < r → (-r : ℝ*) < ofSeq f := fun hr => have hg := hf.neg neg_lt_of_neg_lt (by rw [neg_zero] at hg; exact lt_of_tendsto_zero_of_pos hg hr) theorem gt_of_tendsto_zero_of_neg {f : ℕ → ℝ} (hf : Tendsto f atTop (𝓝 0)) : ∀ {r : ℝ}, r < 0 → (r : ℝ*) < ofSeq f := fun {r} hr => by rw [← neg_neg r, coe_neg]; exact neg_lt_of_tendsto_zero_of_pos hf (neg_pos.mpr hr) theorem epsilon_lt_pos (x : ℝ) : 0 < x → ε < x := lt_of_tendsto_zero_of_pos tendsto_inverse_atTop_nhds_zero_nat /-- Standard part predicate -/ def IsSt (x : ℝ*) (r : ℝ) := ∀ δ : ℝ, 0 < δ → (r - δ : ℝ*) < x ∧ x < r + δ /-- Standard part function: like a "round" to ℝ instead of ℤ -/ noncomputable def st : ℝ* → ℝ := fun x => if h : ∃ r, IsSt x r then Classical.choose h else 0 /-- A hyperreal number is infinitesimal if its standard part is 0 -/ def Infinitesimal (x : ℝ*) := IsSt x 0 /-- A hyperreal number is positive infinite if it is larger than all real numbers -/ def InfinitePos (x : ℝ*) := ∀ r : ℝ, ↑r < x /-- A hyperreal number is negative infinite if it is smaller than all real numbers -/ def InfiniteNeg (x : ℝ*) := ∀ r : ℝ, x < r /-- A hyperreal number is infinite if it is infinite positive or infinite negative -/ def Infinite (x : ℝ*) := InfinitePos x ∨ InfiniteNeg x /-! ### Some facts about `st` -/ theorem isSt_ofSeq_iff_tendsto {f : ℕ → ℝ} {r : ℝ} : IsSt (ofSeq f) r ↔ Tendsto f (hyperfilter ℕ) (𝓝 r) := Iff.trans (forall₂_congr fun _ _ ↦ (ofSeq_lt_ofSeq.and ofSeq_lt_ofSeq).trans eventually_and.symm) (nhds_basis_Ioo_pos _).tendsto_right_iff.symm theorem isSt_iff_tendsto {x : ℝ*} {r : ℝ} : IsSt x r ↔ x.Tendsto (𝓝 r) := by rcases ofSeq_surjective x with ⟨f, rfl⟩ exact isSt_ofSeq_iff_tendsto theorem isSt_of_tendsto {f : ℕ → ℝ} {r : ℝ} (hf : Tendsto f atTop (𝓝 r)) : IsSt (ofSeq f) r := isSt_ofSeq_iff_tendsto.2 <| hf.mono_left Nat.hyperfilter_le_atTop -- Porting note: moved up, renamed protected theorem IsSt.lt {x y : ℝ*} {r s : ℝ} (hxr : IsSt x r) (hys : IsSt y s) (hrs : r < s) : x < y := by rcases ofSeq_surjective x with ⟨f, rfl⟩ rcases ofSeq_surjective y with ⟨g, rfl⟩ rw [isSt_ofSeq_iff_tendsto] at hxr hys exact ofSeq_lt_ofSeq.2 <| hxr.eventually_lt hys hrs theorem IsSt.unique {x : ℝ*} {r s : ℝ} (hr : IsSt x r) (hs : IsSt x s) : r = s := by rcases ofSeq_surjective x with ⟨f, rfl⟩ rw [isSt_ofSeq_iff_tendsto] at hr hs exact tendsto_nhds_unique hr hs theorem IsSt.st_eq {x : ℝ*} {r : ℝ} (hxr : IsSt x r) : st x = r := by have h : ∃ r, IsSt x r := ⟨r, hxr⟩ rw [st, dif_pos h] exact (Classical.choose_spec h).unique hxr theorem IsSt.not_infinite {x : ℝ*} {r : ℝ} (h : IsSt x r) : ¬Infinite x := fun hi ↦ hi.elim (fun hp ↦ lt_asymm (h 1 one_pos).2 (hp (r + 1))) fun hn ↦ lt_asymm (h 1 one_pos).1 (hn (r - 1)) theorem not_infinite_of_exists_st {x : ℝ*} : (∃ r : ℝ, IsSt x r) → ¬Infinite x := fun ⟨_r, hr⟩ => hr.not_infinite theorem Infinite.st_eq {x : ℝ*} (hi : Infinite x) : st x = 0 := dif_neg fun ⟨_r, hr⟩ ↦ hr.not_infinite hi theorem isSt_sSup {x : ℝ*} (hni : ¬Infinite x) : IsSt x (sSup { y : ℝ | (y : ℝ*) < x }) := let S : Set ℝ := { y : ℝ | (y : ℝ*) < x } let R : ℝ := sSup S let ⟨r₁, hr₁⟩ := not_forall.mp (not_or.mp hni).2 let ⟨r₂, hr₂⟩ := not_forall.mp (not_or.mp hni).1 have HR₁ : S.Nonempty := ⟨r₁ - 1, lt_of_lt_of_le (coe_lt_coe.2 <| sub_one_lt _) (not_lt.mp hr₁)⟩ have HR₂ : BddAbove S := ⟨r₂, fun _y hy => le_of_lt (coe_lt_coe.1 (lt_of_lt_of_le hy (not_lt.mp hr₂)))⟩ fun δ hδ => ⟨lt_of_not_le fun c => have hc : ∀ y ∈ S, y ≤ R - δ := fun _y hy => coe_le_coe.1 <| le_of_lt <| lt_of_lt_of_le hy c not_lt_of_le (csSup_le HR₁ hc) <| sub_lt_self R hδ, lt_of_not_le fun c => have hc : ↑(R + δ / 2) < x := lt_of_lt_of_le (add_lt_add_left (coe_lt_coe.2 (half_lt_self hδ)) R) c not_lt_of_le (le_csSup HR₂ hc) <| (lt_add_iff_pos_right _).mpr <| half_pos hδ⟩ theorem exists_st_of_not_infinite {x : ℝ*} (hni : ¬Infinite x) : ∃ r : ℝ, IsSt x r := ⟨sSup { y : ℝ | (y : ℝ*) < x }, isSt_sSup hni⟩ theorem st_eq_sSup {x : ℝ*} : st x = sSup { y : ℝ | (y : ℝ*) < x } := by rcases _root_.em (Infinite x) with (hx|hx) · rw [hx.st_eq] cases hx with | inl hx => convert Real.sSup_univ.symm exact Set.eq_univ_of_forall hx | inr hx => convert Real.sSup_empty.symm exact Set.eq_empty_of_forall_not_mem fun y hy ↦ hy.out.not_lt (hx _) · exact (isSt_sSup hx).st_eq theorem exists_st_iff_not_infinite {x : ℝ*} : (∃ r : ℝ, IsSt x r) ↔ ¬Infinite x := ⟨not_infinite_of_exists_st, exists_st_of_not_infinite⟩ theorem infinite_iff_not_exists_st {x : ℝ*} : Infinite x ↔ ¬∃ r : ℝ, IsSt x r := iff_not_comm.mp exists_st_iff_not_infinite theorem IsSt.isSt_st {x : ℝ*} {r : ℝ} (hxr : IsSt x r) : IsSt x (st x) := by rwa [hxr.st_eq] theorem isSt_st_of_exists_st {x : ℝ*} (hx : ∃ r : ℝ, IsSt x r) : IsSt x (st x) := let ⟨_r, hr⟩ := hx; hr.isSt_st theorem isSt_st' {x : ℝ*} (hx : ¬Infinite x) : IsSt x (st x) := (isSt_sSup hx).isSt_st theorem isSt_st {x : ℝ*} (hx : st x ≠ 0) : IsSt x (st x) := isSt_st' <| mt Infinite.st_eq hx theorem isSt_refl_real (r : ℝ) : IsSt r r := isSt_ofSeq_iff_tendsto.2 tendsto_const_nhds theorem st_id_real (r : ℝ) : st r = r := (isSt_refl_real r).st_eq theorem eq_of_isSt_real {r s : ℝ} : IsSt r s → r = s := (isSt_refl_real r).unique theorem isSt_real_iff_eq {r s : ℝ} : IsSt r s ↔ r = s := ⟨eq_of_isSt_real, fun hrs => hrs ▸ isSt_refl_real r⟩ theorem isSt_symm_real {r s : ℝ} : IsSt r s ↔ IsSt s r := by rw [isSt_real_iff_eq, isSt_real_iff_eq, eq_comm] theorem isSt_trans_real {r s t : ℝ} : IsSt r s → IsSt s t → IsSt r t := by rw [isSt_real_iff_eq, isSt_real_iff_eq, isSt_real_iff_eq]; exact Eq.trans theorem isSt_inj_real {r₁ r₂ s : ℝ} (h1 : IsSt r₁ s) (h2 : IsSt r₂ s) : r₁ = r₂ := Eq.trans (eq_of_isSt_real h1) (eq_of_isSt_real h2).symm theorem isSt_iff_abs_sub_lt_delta {x : ℝ*} {r : ℝ} : IsSt x r ↔ ∀ δ : ℝ, 0 < δ → |x - ↑r| < δ := by simp only [abs_sub_lt_iff, sub_lt_iff_lt_add, IsSt, and_comm, add_comm] theorem IsSt.map {x : ℝ*} {r : ℝ} (hxr : IsSt x r) {f : ℝ → ℝ} (hf : ContinuousAt f r) : IsSt (x.map f) (f r) := by rcases ofSeq_surjective x with ⟨g, rfl⟩ exact isSt_ofSeq_iff_tendsto.2 <| hf.tendsto.comp (isSt_ofSeq_iff_tendsto.1 hxr) theorem IsSt.map₂ {x y : ℝ*} {r s : ℝ} (hxr : IsSt x r) (hys : IsSt y s) {f : ℝ → ℝ → ℝ} (hf : ContinuousAt (Function.uncurry f) (r, s)) : IsSt (x.map₂ f y) (f r s) := by rcases ofSeq_surjective x with ⟨x, rfl⟩ rcases ofSeq_surjective y with ⟨y, rfl⟩ rw [isSt_ofSeq_iff_tendsto] at hxr hys exact isSt_ofSeq_iff_tendsto.2 <| hf.tendsto.comp (hxr.prod_mk_nhds hys) theorem IsSt.add {x y : ℝ*} {r s : ℝ} (hxr : IsSt x r) (hys : IsSt y s) : IsSt (x + y) (r + s) := hxr.map₂ hys continuous_add.continuousAt theorem IsSt.neg {x : ℝ*} {r : ℝ} (hxr : IsSt x r) : IsSt (-x) (-r) := hxr.map continuous_neg.continuousAt theorem IsSt.sub {x y : ℝ*} {r s : ℝ} (hxr : IsSt x r) (hys : IsSt y s) : IsSt (x - y) (r - s) := hxr.map₂ hys continuous_sub.continuousAt theorem IsSt.le {x y : ℝ*} {r s : ℝ} (hrx : IsSt x r) (hsy : IsSt y s) (hxy : x ≤ y) : r ≤ s := not_lt.1 fun h ↦ hxy.not_lt <| hsy.lt hrx h theorem st_le_of_le {x y : ℝ*} (hix : ¬Infinite x) (hiy : ¬Infinite y) : x ≤ y → st x ≤ st y := (isSt_st' hix).le (isSt_st' hiy) theorem lt_of_st_lt {x y : ℝ*} (hix : ¬Infinite x) (hiy : ¬Infinite y) : st x < st y → x < y := (isSt_st' hix).lt (isSt_st' hiy) /-! ### Basic lemmas about infinite -/ theorem infinitePos_def {x : ℝ*} : InfinitePos x ↔ ∀ r : ℝ, ↑r < x := Iff.rfl theorem infiniteNeg_def {x : ℝ*} : InfiniteNeg x ↔ ∀ r : ℝ, x < r := Iff.rfl theorem InfinitePos.pos {x : ℝ*} (hip : InfinitePos x) : 0 < x := hip 0 theorem InfiniteNeg.lt_zero {x : ℝ*} : InfiniteNeg x → x < 0 := fun hin => hin 0 theorem Infinite.ne_zero {x : ℝ*} (hI : Infinite x) : x ≠ 0 := hI.elim (fun hip => hip.pos.ne') fun hin => hin.lt_zero.ne theorem not_infinite_zero : ¬Infinite 0 := fun hI => hI.ne_zero rfl theorem InfiniteNeg.not_infinitePos {x : ℝ*} : InfiniteNeg x → ¬InfinitePos x := fun hn hp => (hn 0).not_lt (hp 0) theorem InfinitePos.not_infiniteNeg {x : ℝ*} (hp : InfinitePos x) : ¬InfiniteNeg x := fun hn ↦ hn.not_infinitePos hp theorem InfinitePos.neg {x : ℝ*} : InfinitePos x → InfiniteNeg (-x) := fun hp r => neg_lt.mp (hp (-r)) theorem InfiniteNeg.neg {x : ℝ*} : InfiniteNeg x → InfinitePos (-x) := fun hp r => lt_neg.mp (hp (-r)) -- Porting note: swapped LHS with RHS; added @[simp] @[simp] theorem infiniteNeg_neg {x : ℝ*} : InfiniteNeg (-x) ↔ InfinitePos x := ⟨fun hin => neg_neg x ▸ hin.neg, InfinitePos.neg⟩ -- Porting note: swapped LHS with RHS; added @[simp] @[simp] theorem infinitePos_neg {x : ℝ*} : InfinitePos (-x) ↔ InfiniteNeg x := ⟨fun hin => neg_neg x ▸ hin.neg, InfiniteNeg.neg⟩ -- Porting note: swapped LHS with RHS; added @[simp] @[simp] theorem infinite_neg {x : ℝ*} : Infinite (-x) ↔ Infinite x := or_comm.trans <| infiniteNeg_neg.or infinitePos_neg nonrec theorem Infinitesimal.not_infinite {x : ℝ*} (h : Infinitesimal x) : ¬Infinite x := h.not_infinite theorem Infinite.not_infinitesimal {x : ℝ*} (h : Infinite x) : ¬Infinitesimal x := fun h' ↦ h'.not_infinite h theorem InfinitePos.not_infinitesimal {x : ℝ*} (h : InfinitePos x) : ¬Infinitesimal x := Infinite.not_infinitesimal (Or.inl h) theorem InfiniteNeg.not_infinitesimal {x : ℝ*} (h : InfiniteNeg x) : ¬Infinitesimal x := Infinite.not_infinitesimal (Or.inr h) theorem infinitePos_iff_infinite_and_pos {x : ℝ*} : InfinitePos x ↔ Infinite x ∧ 0 < x := ⟨fun hip => ⟨Or.inl hip, hip 0⟩, fun ⟨hi, hp⟩ => hi.casesOn (fun hip => hip) fun hin => False.elim (not_lt_of_lt hp (hin 0))⟩ theorem infiniteNeg_iff_infinite_and_neg {x : ℝ*} : InfiniteNeg x ↔ Infinite x ∧ x < 0 := ⟨fun hip => ⟨Or.inr hip, hip 0⟩, fun ⟨hi, hp⟩ => hi.casesOn (fun hin => False.elim (not_lt_of_lt hp (hin 0))) fun hip => hip⟩ theorem infinitePos_iff_infinite_of_nonneg {x : ℝ*} (hp : 0 ≤ x) : InfinitePos x ↔ Infinite x := .symm <| or_iff_left fun h ↦ h.lt_zero.not_le hp theorem infinitePos_iff_infinite_of_pos {x : ℝ*} (hp : 0 < x) : InfinitePos x ↔ Infinite x := infinitePos_iff_infinite_of_nonneg hp.le theorem infiniteNeg_iff_infinite_of_neg {x : ℝ*} (hn : x < 0) : InfiniteNeg x ↔ Infinite x := .symm <| or_iff_right fun h ↦ h.pos.not_lt hn theorem infinitePos_abs_iff_infinite_abs {x : ℝ*} : InfinitePos |x| ↔ Infinite |x| := infinitePos_iff_infinite_of_nonneg (abs_nonneg _) -- Porting note: swapped LHS with RHS; added @[simp] @[simp] theorem infinite_abs_iff {x : ℝ*} : Infinite |x| ↔ Infinite x := by cases le_total 0 x <;> simp [*, abs_of_nonneg, abs_of_nonpos, infinite_neg] -- Porting note: swapped LHS with RHS; -- Porting note (#11215): TODO: make it a `simp` lemma @[simp] theorem infinitePos_abs_iff_infinite {x : ℝ*} : InfinitePos |x| ↔ Infinite x := infinitePos_abs_iff_infinite_abs.trans infinite_abs_iff theorem infinite_iff_abs_lt_abs {x : ℝ*} : Infinite x ↔ ∀ r : ℝ, (|r| : ℝ*) < |x| := infinitePos_abs_iff_infinite.symm.trans ⟨fun hI r => coe_abs r ▸ hI |r|, fun hR r => (le_abs_self _).trans_lt (hR r)⟩ theorem infinitePos_add_not_infiniteNeg {x y : ℝ*} : InfinitePos x → ¬InfiniteNeg y → InfinitePos (x + y) := by intro hip hnin r cases' not_forall.mp hnin with r₂ hr₂ convert add_lt_add_of_lt_of_le (hip (r + -r₂)) (not_lt.mp hr₂) using 1 simp theorem not_infiniteNeg_add_infinitePos {x y : ℝ*} : ¬InfiniteNeg x → InfinitePos y → InfinitePos (x + y) := fun hx hy => add_comm y x ▸ infinitePos_add_not_infiniteNeg hy hx theorem infiniteNeg_add_not_infinitePos {x y : ℝ*} : InfiniteNeg x → ¬InfinitePos y → InfiniteNeg (x + y) := by rw [← infinitePos_neg, ← infinitePos_neg, ← @infiniteNeg_neg y, neg_add] exact infinitePos_add_not_infiniteNeg theorem not_infinitePos_add_infiniteNeg {x y : ℝ*} : ¬InfinitePos x → InfiniteNeg y → InfiniteNeg (x + y) := fun hx hy => add_comm y x ▸ infiniteNeg_add_not_infinitePos hy hx theorem infinitePos_add_infinitePos {x y : ℝ*} : InfinitePos x → InfinitePos y → InfinitePos (x + y) := fun hx hy => infinitePos_add_not_infiniteNeg hx hy.not_infiniteNeg theorem infiniteNeg_add_infiniteNeg {x y : ℝ*} : InfiniteNeg x → InfiniteNeg y → InfiniteNeg (x + y) := fun hx hy => infiniteNeg_add_not_infinitePos hx hy.not_infinitePos theorem infinitePos_add_not_infinite {x y : ℝ*} : InfinitePos x → ¬Infinite y → InfinitePos (x + y) := fun hx hy => infinitePos_add_not_infiniteNeg hx (not_or.mp hy).2 theorem infiniteNeg_add_not_infinite {x y : ℝ*} : InfiniteNeg x → ¬Infinite y → InfiniteNeg (x + y) := fun hx hy => infiniteNeg_add_not_infinitePos hx (not_or.mp hy).1 theorem infinitePos_of_tendsto_top {f : ℕ → ℝ} (hf : Tendsto f atTop atTop) : InfinitePos (ofSeq f) := fun r => have hf' := tendsto_atTop_atTop.mp hf let ⟨i, hi⟩ := hf' (r + 1) have hi' : ∀ a : ℕ, f a < r + 1 → a < i := fun a => lt_imp_lt_of_le_imp_le (hi a) have hS : { a : ℕ | r < f a }ᶜ ⊆ { a : ℕ | a ≤ i } := by simp only [Set.compl_setOf, not_lt] exact fun a har => le_of_lt (hi' a (lt_of_le_of_lt har (lt_add_one _))) Germ.coe_lt.2 <| mem_hyperfilter_of_finite_compl <| (Set.finite_le_nat _).subset hS theorem infiniteNeg_of_tendsto_bot {f : ℕ → ℝ} (hf : Tendsto f atTop atBot) : InfiniteNeg (ofSeq f) := fun r => have hf' := tendsto_atTop_atBot.mp hf let ⟨i, hi⟩ := hf' (r - 1) have hi' : ∀ a : ℕ, r - 1 < f a → a < i := fun a => lt_imp_lt_of_le_imp_le (hi a) have hS : { a : ℕ | f a < r }ᶜ ⊆ { a : ℕ | a ≤ i } := by simp only [Set.compl_setOf, not_lt] exact fun a har => le_of_lt (hi' a (lt_of_lt_of_le (sub_one_lt _) har)) Germ.coe_lt.2 <| mem_hyperfilter_of_finite_compl <| (Set.finite_le_nat _).subset hS theorem not_infinite_neg {x : ℝ*} : ¬Infinite x → ¬Infinite (-x) := mt infinite_neg.mp theorem not_infinite_add {x y : ℝ*} (hx : ¬Infinite x) (hy : ¬Infinite y) : ¬Infinite (x + y) := have ⟨r, hr⟩ := exists_st_of_not_infinite hx have ⟨s, hs⟩ := exists_st_of_not_infinite hy not_infinite_of_exists_st <| ⟨r + s, hr.add hs⟩ theorem not_infinite_iff_exist_lt_gt {x : ℝ*} : ¬Infinite x ↔ ∃ r s : ℝ, (r : ℝ*) < x ∧ x < s := ⟨fun hni ↦ let ⟨r, hr⟩ := exists_st_of_not_infinite hni; ⟨r - 1, r + 1, hr 1 one_pos⟩, fun ⟨r, s, hr, hs⟩ hi ↦ hi.elim (fun hp ↦ (hp s).not_lt hs) (fun hn ↦ (hn r).not_lt hr)⟩ theorem not_infinite_real (r : ℝ) : ¬Infinite r := by rw [not_infinite_iff_exist_lt_gt] exact ⟨r - 1, r + 1, coe_lt_coe.2 <| sub_one_lt r, coe_lt_coe.2 <| lt_add_one r⟩ theorem Infinite.ne_real {x : ℝ*} : Infinite x → ∀ r : ℝ, x ≠ r := fun hi r hr => not_infinite_real r <| @Eq.subst _ Infinite _ _ hr hi /-! ### Facts about `st` that require some infinite machinery -/ theorem IsSt.mul {x y : ℝ*} {r s : ℝ} (hxr : IsSt x r) (hys : IsSt y s) : IsSt (x * y) (r * s) := hxr.map₂ hys continuous_mul.continuousAt --AN INFINITE LEMMA THAT REQUIRES SOME MORE ST MACHINERY theorem not_infinite_mul {x y : ℝ*} (hx : ¬Infinite x) (hy : ¬Infinite y) : ¬Infinite (x * y) := have ⟨_r, hr⟩ := exists_st_of_not_infinite hx have ⟨_s, hs⟩ := exists_st_of_not_infinite hy (hr.mul hs).not_infinite --- theorem st_add {x y : ℝ*} (hx : ¬Infinite x) (hy : ¬Infinite y) : st (x + y) = st x + st y := (isSt_st' (not_infinite_add hx hy)).unique ((isSt_st' hx).add (isSt_st' hy)) theorem st_neg (x : ℝ*) : st (-x) = -st x := if h : Infinite x then by rw [h.st_eq, (infinite_neg.2 h).st_eq, neg_zero] else (isSt_st' (not_infinite_neg h)).unique (isSt_st' h).neg theorem st_mul {x y : ℝ*} (hx : ¬Infinite x) (hy : ¬Infinite y) : st (x * y) = st x * st y := have hx' := isSt_st' hx have hy' := isSt_st' hy have hxy := isSt_st' (not_infinite_mul hx hy) hxy.unique (hx'.mul hy') /-! ### Basic lemmas about infinitesimal -/ theorem infinitesimal_def {x : ℝ*} : Infinitesimal x ↔ ∀ r : ℝ, 0 < r → -(r : ℝ*) < x ∧ x < r := by simp [Infinitesimal, IsSt] theorem lt_of_pos_of_infinitesimal {x : ℝ*} : Infinitesimal x → ∀ r : ℝ, 0 < r → x < r := fun hi r hr => ((infinitesimal_def.mp hi) r hr).2 theorem lt_neg_of_pos_of_infinitesimal {x : ℝ*} : Infinitesimal x → ∀ r : ℝ, 0 < r → -↑r < x := fun hi r hr => ((infinitesimal_def.mp hi) r hr).1 theorem gt_of_neg_of_infinitesimal {x : ℝ*} (hi : Infinitesimal x) (r : ℝ) (hr : r < 0) : ↑r < x := neg_neg r ▸ (infinitesimal_def.1 hi (-r) (neg_pos.2 hr)).1 theorem abs_lt_real_iff_infinitesimal {x : ℝ*} : Infinitesimal x ↔ ∀ r : ℝ, r ≠ 0 → |x| < |↑r| := ⟨fun hi r hr ↦ abs_lt.mpr (coe_abs r ▸ infinitesimal_def.mp hi |r| (abs_pos.2 hr)), fun hR ↦ infinitesimal_def.mpr fun r hr => abs_lt.mp <| (abs_of_pos <| coe_pos.2 hr) ▸ hR r <| hr.ne'⟩ theorem infinitesimal_zero : Infinitesimal 0 := isSt_refl_real 0 theorem Infinitesimal.eq_zero {r : ℝ} : Infinitesimal r → r = 0 := eq_of_isSt_real -- Porting note: swapped LHS with RHS; added `@[simp]` @[simp] theorem infinitesimal_real_iff {r : ℝ} : Infinitesimal r ↔ r = 0 := isSt_real_iff_eq nonrec theorem Infinitesimal.add {x y : ℝ*} (hx : Infinitesimal x) (hy : Infinitesimal y) : Infinitesimal (x + y) := by simpa only [add_zero] using hx.add hy nonrec theorem Infinitesimal.neg {x : ℝ*} (hx : Infinitesimal x) : Infinitesimal (-x) := by simpa only [neg_zero] using hx.neg -- Porting note: swapped LHS and RHS, added `@[simp]` @[simp] theorem infinitesimal_neg {x : ℝ*} : Infinitesimal (-x) ↔ Infinitesimal x := ⟨fun h => neg_neg x ▸ h.neg, Infinitesimal.neg⟩ nonrec theorem Infinitesimal.mul {x y : ℝ*} (hx : Infinitesimal x) (hy : Infinitesimal y) : Infinitesimal (x * y) := by simpa only [mul_zero] using hx.mul hy theorem infinitesimal_of_tendsto_zero {f : ℕ → ℝ} (h : Tendsto f atTop (𝓝 0)) : Infinitesimal (ofSeq f) := isSt_of_tendsto h theorem infinitesimal_epsilon : Infinitesimal ε := infinitesimal_of_tendsto_zero tendsto_inverse_atTop_nhds_zero_nat theorem not_real_of_infinitesimal_ne_zero (x : ℝ*) : Infinitesimal x → x ≠ 0 → ∀ r : ℝ, x ≠ r := fun hi hx r hr => hx <| hr.trans <| coe_eq_zero.2 <| IsSt.unique (hr.symm ▸ isSt_refl_real r : IsSt x r) hi theorem IsSt.infinitesimal_sub {x : ℝ*} {r : ℝ} (hxr : IsSt x r) : Infinitesimal (x - ↑r) := by simpa only [sub_self] using hxr.sub (isSt_refl_real r) theorem infinitesimal_sub_st {x : ℝ*} (hx : ¬Infinite x) : Infinitesimal (x - ↑(st x)) := (isSt_st' hx).infinitesimal_sub theorem infinitePos_iff_infinitesimal_inv_pos {x : ℝ*} : InfinitePos x ↔ Infinitesimal x⁻¹ ∧ 0 < x⁻¹ := ⟨fun hip => ⟨infinitesimal_def.mpr fun r hr => ⟨lt_trans (coe_lt_coe.2 (neg_neg_of_pos hr)) (inv_pos.2 (hip 0)), (inv_lt (coe_lt_coe.2 hr) (hip 0)).mp (by convert hip r⁻¹)⟩, inv_pos.2 <| hip 0⟩, fun ⟨hi, hp⟩ r => @_root_.by_cases (r = 0) (↑r < x) (fun h => Eq.substr h (inv_pos.mp hp)) fun h => lt_of_le_of_lt (coe_le_coe.2 (le_abs_self r)) ((inv_lt_inv (inv_pos.mp hp) (coe_lt_coe.2 (abs_pos.2 h))).mp ((infinitesimal_def.mp hi) |r|⁻¹ (inv_pos.2 (abs_pos.2 h))).2)⟩ theorem infiniteNeg_iff_infinitesimal_inv_neg {x : ℝ*} : InfiniteNeg x ↔ Infinitesimal x⁻¹ ∧ x⁻¹ < 0 := by rw [← infinitePos_neg, infinitePos_iff_infinitesimal_inv_pos, inv_neg, neg_pos, infinitesimal_neg] theorem infinitesimal_inv_of_infinite {x : ℝ*} : Infinite x → Infinitesimal x⁻¹ := fun hi => Or.casesOn hi (fun hip => (infinitePos_iff_infinitesimal_inv_pos.mp hip).1) fun hin => (infiniteNeg_iff_infinitesimal_inv_neg.mp hin).1 theorem infinite_of_infinitesimal_inv {x : ℝ*} (h0 : x ≠ 0) (hi : Infinitesimal x⁻¹) : Infinite x := by cases' lt_or_gt_of_ne h0 with hn hp · exact Or.inr (infiniteNeg_iff_infinitesimal_inv_neg.mpr ⟨hi, inv_lt_zero.mpr hn⟩) · exact Or.inl (infinitePos_iff_infinitesimal_inv_pos.mpr ⟨hi, inv_pos.mpr hp⟩) theorem infinite_iff_infinitesimal_inv {x : ℝ*} (h0 : x ≠ 0) : Infinite x ↔ Infinitesimal x⁻¹ := ⟨infinitesimal_inv_of_infinite, infinite_of_infinitesimal_inv h0⟩ theorem infinitesimal_pos_iff_infinitePos_inv {x : ℝ*} : InfinitePos x⁻¹ ↔ Infinitesimal x ∧ 0 < x := infinitePos_iff_infinitesimal_inv_pos.trans <| by rw [inv_inv] theorem infinitesimal_neg_iff_infiniteNeg_inv {x : ℝ*} : InfiniteNeg x⁻¹ ↔ Infinitesimal x ∧ x < 0 := infiniteNeg_iff_infinitesimal_inv_neg.trans <| by rw [inv_inv] theorem infinitesimal_iff_infinite_inv {x : ℝ*} (h : x ≠ 0) : Infinitesimal x ↔ Infinite x⁻¹ := Iff.trans (by rw [inv_inv]) (infinite_iff_infinitesimal_inv (inv_ne_zero h)).symm /-! ### `Hyperreal.st` stuff that requires infinitesimal machinery -/ theorem IsSt.inv {x : ℝ*} {r : ℝ} (hi : ¬Infinitesimal x) (hr : IsSt x r) : IsSt x⁻¹ r⁻¹ := hr.map <| continuousAt_inv₀ <| by rintro rfl; exact hi hr theorem st_inv (x : ℝ*) : st x⁻¹ = (st x)⁻¹ := by by_cases h0 : x = 0 · rw [h0, inv_zero, ← coe_zero, st_id_real, inv_zero] by_cases h1 : Infinitesimal x · rw [((infinitesimal_iff_infinite_inv h0).mp h1).st_eq, h1.st_eq, inv_zero] by_cases h2 : Infinite x · rw [(infinitesimal_inv_of_infinite h2).st_eq, h2.st_eq, inv_zero] exact ((isSt_st' h2).inv h1).st_eq /-! ### Infinite stuff that requires infinitesimal machinery -/ theorem infinitePos_omega : InfinitePos ω := infinitePos_iff_infinitesimal_inv_pos.mpr ⟨infinitesimal_epsilon, epsilon_pos⟩ theorem infinite_omega : Infinite ω := (infinite_iff_infinitesimal_inv omega_ne_zero).mpr infinitesimal_epsilon theorem infinitePos_mul_of_infinitePos_not_infinitesimal_pos {x y : ℝ*} : InfinitePos x → ¬Infinitesimal y → 0 < y → InfinitePos (x * y) := fun hx hy₁ hy₂ r => by have hy₁' := not_forall.mp (mt infinitesimal_def.2 hy₁) let ⟨r₁, hy₁''⟩ := hy₁' have hyr : 0 < r₁ ∧ ↑r₁ ≤ y := by rwa [Classical.not_imp, ← abs_lt, not_lt, abs_of_pos hy₂] at hy₁'' rw [← div_mul_cancel₀ r (ne_of_gt hyr.1), coe_mul] exact mul_lt_mul (hx (r / r₁)) hyr.2 (coe_lt_coe.2 hyr.1) (le_of_lt (hx 0)) theorem infinitePos_mul_of_not_infinitesimal_pos_infinitePos {x y : ℝ*} : ¬Infinitesimal x → 0 < x → InfinitePos y → InfinitePos (x * y) := fun hx hp hy => mul_comm y x ▸ infinitePos_mul_of_infinitePos_not_infinitesimal_pos hy hx hp theorem infinitePos_mul_of_infiniteNeg_not_infinitesimal_neg {x y : ℝ*} : InfiniteNeg x → ¬Infinitesimal y → y < 0 → InfinitePos (x * y) := by rw [← infinitePos_neg, ← neg_pos, ← neg_mul_neg, ← infinitesimal_neg] exact infinitePos_mul_of_infinitePos_not_infinitesimal_pos theorem infinitePos_mul_of_not_infinitesimal_neg_infiniteNeg {x y : ℝ*} : ¬Infinitesimal x → x < 0 → InfiniteNeg y → InfinitePos (x * y) := fun hx hp hy => mul_comm y x ▸ infinitePos_mul_of_infiniteNeg_not_infinitesimal_neg hy hx hp theorem infiniteNeg_mul_of_infinitePos_not_infinitesimal_neg {x y : ℝ*} : InfinitePos x → ¬Infinitesimal y → y < 0 → InfiniteNeg (x * y) := by rw [← infinitePos_neg, ← neg_pos, neg_mul_eq_mul_neg, ← infinitesimal_neg] exact infinitePos_mul_of_infinitePos_not_infinitesimal_pos theorem infiniteNeg_mul_of_not_infinitesimal_neg_infinitePos {x y : ℝ*} : ¬Infinitesimal x → x < 0 → InfinitePos y → InfiniteNeg (x * y) := fun hx hp hy => mul_comm y x ▸ infiniteNeg_mul_of_infinitePos_not_infinitesimal_neg hy hx hp theorem infiniteNeg_mul_of_infiniteNeg_not_infinitesimal_pos {x y : ℝ*} : InfiniteNeg x → ¬Infinitesimal y → 0 < y → InfiniteNeg (x * y) := by rw [← infinitePos_neg, ← infinitePos_neg, neg_mul_eq_neg_mul] exact infinitePos_mul_of_infinitePos_not_infinitesimal_pos theorem infiniteNeg_mul_of_not_infinitesimal_pos_infiniteNeg {x y : ℝ*} : ¬Infinitesimal x → 0 < x → InfiniteNeg y → InfiniteNeg (x * y) := fun hx hp hy => by rw [mul_comm]; exact infiniteNeg_mul_of_infiniteNeg_not_infinitesimal_pos hy hx hp theorem infinitePos_mul_infinitePos {x y : ℝ*} : InfinitePos x → InfinitePos y → InfinitePos (x * y) := fun hx hy => infinitePos_mul_of_infinitePos_not_infinitesimal_pos hx hy.not_infinitesimal (hy 0) theorem infiniteNeg_mul_infiniteNeg {x y : ℝ*} : InfiniteNeg x → InfiniteNeg y → InfinitePos (x * y) := fun hx hy => infinitePos_mul_of_infiniteNeg_not_infinitesimal_neg hx hy.not_infinitesimal (hy 0) theorem infinitePos_mul_infiniteNeg {x y : ℝ*} : InfinitePos x → InfiniteNeg y → InfiniteNeg (x * y) := fun hx hy => infiniteNeg_mul_of_infinitePos_not_infinitesimal_neg hx hy.not_infinitesimal (hy 0) theorem infiniteNeg_mul_infinitePos {x y : ℝ*} : InfiniteNeg x → InfinitePos y → InfiniteNeg (x * y) := fun hx hy => infiniteNeg_mul_of_infiniteNeg_not_infinitesimal_pos hx hy.not_infinitesimal (hy 0) theorem infinite_mul_of_infinite_not_infinitesimal {x y : ℝ*} : Infinite x → ¬Infinitesimal y → Infinite (x * y) := fun hx hy => have h0 : y < 0 ∨ 0 < y := lt_or_gt_of_ne fun H0 => hy (Eq.substr H0 (isSt_refl_real 0)) hx.elim (h0.elim (fun H0 Hx => Or.inr (infiniteNeg_mul_of_infinitePos_not_infinitesimal_neg Hx hy H0)) fun H0 Hx => Or.inl (infinitePos_mul_of_infinitePos_not_infinitesimal_pos Hx hy H0)) (h0.elim (fun H0 Hx => Or.inl (infinitePos_mul_of_infiniteNeg_not_infinitesimal_neg Hx hy H0)) fun H0 Hx => Or.inr (infiniteNeg_mul_of_infiniteNeg_not_infinitesimal_pos Hx hy H0)) theorem infinite_mul_of_not_infinitesimal_infinite {x y : ℝ*} : ¬Infinitesimal x → Infinite y → Infinite (x * y) := fun hx hy => by rw [mul_comm]; exact infinite_mul_of_infinite_not_infinitesimal hy hx theorem Infinite.mul {x y : ℝ*} : Infinite x → Infinite y → Infinite (x * y) := fun hx hy => infinite_mul_of_infinite_not_infinitesimal hx hy.not_infinitesimal end Hyperreal /- Porting note (#11215): TODO: restore `positivity` plugin namespace Tactic open Positivity private theorem hyperreal_coe_ne_zero {r : ℝ} : r ≠ 0 → (r : ℝ*) ≠ 0 := Hyperreal.coe_ne_zero.2 private theorem hyperreal_coe_nonneg {r : ℝ} : 0 ≤ r → 0 ≤ (r : ℝ*) := Hyperreal.coe_nonneg.2 private theorem hyperreal_coe_pos {r : ℝ} : 0 < r → 0 < (r : ℝ*) := Hyperreal.coe_pos.2 /-- Extension for the `positivity` tactic: cast from `ℝ` to `ℝ*`. -/ @[positivity] unsafe def positivity_coe_real_hyperreal : expr → tactic strictness | q(@coe _ _ $(inst) $(a)) => do unify inst q(@coeToLift _ _ Hyperreal.hasCoeT) let strictness_a ← core a match strictness_a with | positive p => positive <$> mk_app `` hyperreal_coe_pos [p] | nonnegative p => nonnegative <$> mk_app `` hyperreal_coe_nonneg [p] | nonzero p => nonzero <$> mk_app `` hyperreal_coe_ne_zero [p] | e => pp e >>= fail ∘ format.bracket "The expression " " is not of the form `(r : ℝ*)` for `r : ℝ`" end Tactic -/
Data\Real\Irrational.lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne, Yury Kudryashov -/ import Mathlib.Algebra.Algebra.Rat import Mathlib.Data.Rat.Sqrt import Mathlib.Data.Real.Sqrt import Mathlib.RingTheory.Algebraic import Mathlib.RingTheory.Int.Basic import Mathlib.Tactic.IntervalCases /-! # Irrational real numbers In this file we define a predicate `Irrational` on `ℝ`, prove that the `n`-th root of an integer number is irrational if it is not integer, and that `√(q : ℚ)` is irrational if and only if `¬IsSquare q ∧ 0 ≤ q`. We also provide dot-style constructors like `Irrational.add_rat`, `Irrational.rat_sub` etc. With the `Decidable` instances in this file, is possible to prove `Irrational √n` using `decide`, when `n` is a numeric literal or cast; but this only works if you `unseal Nat.sqrt.iter in` before the theorem where you use this proof. -/ open Rat Real multiplicity /-- A real number is irrational if it is not equal to any rational number. -/ def Irrational (x : ℝ) := x ∉ Set.range ((↑) : ℚ → ℝ) theorem irrational_iff_ne_rational (x : ℝ) : Irrational x ↔ ∀ a b : ℤ, x ≠ a / b := by simp only [Irrational, Rat.forall, cast_mk, not_exists, Set.mem_range, cast_intCast, cast_div, eq_comm] /-- A transcendental real number is irrational. -/ theorem Transcendental.irrational {r : ℝ} (tr : Transcendental ℚ r) : Irrational r := by rintro ⟨a, rfl⟩ exact tr (isAlgebraic_algebraMap a) /-! ### Irrationality of roots of integer and rational numbers -/ /-- If `x^n`, `n > 0`, is integer and is not the `n`-th power of an integer, then `x` is irrational. -/ theorem irrational_nrt_of_notint_nrt {x : ℝ} (n : ℕ) (m : ℤ) (hxr : x ^ n = m) (hv : ¬∃ y : ℤ, x = y) (hnpos : 0 < n) : Irrational x := by rintro ⟨⟨N, D, P, C⟩, rfl⟩ rw [← cast_pow] at hxr have c1 : ((D : ℤ) : ℝ) ≠ 0 := by rw [Int.cast_ne_zero, Int.natCast_ne_zero] exact P have c2 : ((D : ℤ) : ℝ) ^ n ≠ 0 := pow_ne_zero _ c1 rw [mk'_eq_divInt, cast_pow, cast_mk, div_pow, div_eq_iff_mul_eq c2, ← Int.cast_pow, ← Int.cast_pow, ← Int.cast_mul, Int.cast_inj] at hxr have hdivn : (D : ℤ) ^ n ∣ N ^ n := Dvd.intro_left m hxr rw [← Int.dvd_natAbs, ← Int.natCast_pow, Int.natCast_dvd_natCast, Int.natAbs_pow, Nat.pow_dvd_pow_iff hnpos.ne'] at hdivn obtain rfl : D = 1 := by rw [← Nat.gcd_eq_right hdivn, C.gcd_eq_one] refine hv ⟨N, ?_⟩ rw [mk'_eq_divInt, Int.ofNat_one, divInt_one, cast_intCast] /-- If `x^n = m` is an integer and `n` does not divide the `multiplicity p m`, then `x` is irrational. -/ theorem irrational_nrt_of_n_not_dvd_multiplicity {x : ℝ} (n : ℕ) {m : ℤ} (hm : m ≠ 0) (p : ℕ) [hp : Fact p.Prime] (hxr : x ^ n = m) (hv : (multiplicity (p : ℤ) m).get (finite_int_iff.2 ⟨hp.1.ne_one, hm⟩) % n ≠ 0) : Irrational x := by rcases Nat.eq_zero_or_pos n with (rfl | hnpos) · rw [eq_comm, pow_zero, ← Int.cast_one, Int.cast_inj] at hxr simp [hxr, multiplicity.one_right (mt isUnit_iff_dvd_one.1 (mt Int.natCast_dvd_natCast.1 hp.1.not_dvd_one)), Nat.zero_mod] at hv refine irrational_nrt_of_notint_nrt _ _ hxr ?_ hnpos rintro ⟨y, rfl⟩ rw [← Int.cast_pow, Int.cast_inj] at hxr subst m have : y ≠ 0 := by rintro rfl; rw [zero_pow hnpos.ne'] at hm; exact hm rfl erw [multiplicity.pow' (Nat.prime_iff_prime_int.1 hp.1) (finite_int_iff.2 ⟨hp.1.ne_one, this⟩), Nat.mul_mod_right] at hv exact hv rfl theorem irrational_sqrt_of_multiplicity_odd (m : ℤ) (hm : 0 < m) (p : ℕ) [hp : Fact p.Prime] (Hpv : (multiplicity (p : ℤ) m).get (finite_int_iff.2 ⟨hp.1.ne_one, (ne_of_lt hm).symm⟩) % 2 = 1) : Irrational (√m) := @irrational_nrt_of_n_not_dvd_multiplicity _ 2 _ (Ne.symm (ne_of_lt hm)) p hp (sq_sqrt (Int.cast_nonneg.2 <| le_of_lt hm)) (by rw [Hpv]; exact one_ne_zero) @[simp] theorem not_irrational_zero : ¬Irrational 0 := not_not_intro ⟨0, Rat.cast_zero⟩ @[simp] theorem not_irrational_one : ¬Irrational 1 := not_not_intro ⟨1, Rat.cast_one⟩ theorem irrational_sqrt_ratCast_iff_of_nonneg {q : ℚ} (hq : 0 ≤ q) : Irrational (√q) ↔ ¬IsSquare q := by refine Iff.not (?_ : Exists _ ↔ Exists _) constructor · rintro ⟨y, hy⟩ refine ⟨y, Rat.cast_injective (α := ℝ) ?_⟩ rw [Rat.cast_mul, hy, mul_self_sqrt (Rat.cast_nonneg.2 hq)] · rintro ⟨q', rfl⟩ exact ⟨|q'|, mod_cast (sqrt_mul_self_eq_abs q').symm⟩ theorem irrational_sqrt_ratCast_iff {q : ℚ} : Irrational (√q) ↔ ¬IsSquare q ∧ 0 ≤ q := by obtain hq | hq := le_or_lt 0 q · simp_rw [irrational_sqrt_ratCast_iff_of_nonneg hq, and_iff_left hq] · rw [sqrt_eq_zero_of_nonpos (Rat.cast_nonpos.2 hq.le)] simp_rw [not_irrational_zero, false_iff, not_and, not_le, hq, implies_true] theorem irrational_sqrt_intCast_iff_of_nonneg {z : ℤ} (hz : 0 ≤ z) : Irrational (√z) ↔ ¬IsSquare z := by rw [← Rat.isSquare_intCast_iff, ← irrational_sqrt_ratCast_iff_of_nonneg (mod_cast hz), Rat.cast_intCast] theorem irrational_sqrt_intCast_iff {z : ℤ} : Irrational (√z) ↔ ¬IsSquare z ∧ 0 ≤ z := by rw [← Rat.cast_intCast, irrational_sqrt_ratCast_iff, Rat.isSquare_intCast_iff, Int.cast_nonneg] theorem irrational_sqrt_natCast_iff {n : ℕ} : Irrational (√n) ↔ ¬IsSquare n := by rw [← Rat.isSquare_natCast_iff, ← irrational_sqrt_ratCast_iff_of_nonneg n.cast_nonneg, Rat.cast_natCast] -- See note [no_index around OfNat.ofNat] theorem irrational_sqrt_ofNat_iff {n : ℕ} [n.AtLeastTwo] : Irrational (√(no_index (OfNat.ofNat n))) ↔ ¬IsSquare (OfNat.ofNat n) := irrational_sqrt_natCast_iff theorem Nat.Prime.irrational_sqrt {p : ℕ} (hp : Nat.Prime p) : Irrational (√p) := irrational_sqrt_natCast_iff.mpr hp.not_square /-- **Irrationality of the Square Root of 2** -/ theorem irrational_sqrt_two : Irrational (√2) := by simpa using Nat.prime_two.irrational_sqrt @[deprecated irrational_sqrt_ratCast_iff (since := "2024-06-16")] theorem irrational_sqrt_rat_iff (q : ℚ) : Irrational (√q) ↔ Rat.sqrt q * Rat.sqrt q ≠ q ∧ 0 ≤ q := by rw [irrational_sqrt_ratCast_iff, ne_eq, ← Rat.exists_mul_self] simp only [eq_comm, IsSquare] /-- This can be used as ```lean unseal Nat.sqrt.iter in example : Irrational √24 := by decide ``` -/ instance {n : ℕ} [n.AtLeastTwo] : Decidable (Irrational (√(no_index (OfNat.ofNat n)))) := decidable_of_iff' _ irrational_sqrt_ofNat_iff instance (n : ℕ) : Decidable (Irrational (√n)) := decidable_of_iff' _ irrational_sqrt_natCast_iff instance (z : ℤ) : Decidable (Irrational (√z)) := decidable_of_iff' _ irrational_sqrt_intCast_iff instance (q : ℚ) : Decidable (Irrational (√q)) := decidable_of_iff' _ irrational_sqrt_ratCast_iff /-! ### Dot-style operations on `Irrational` #### Coercion of a rational/integer/natural number is not irrational -/ namespace Irrational variable {x : ℝ} /-! #### Irrational number is not equal to a rational/integer/natural number -/ theorem ne_rat (h : Irrational x) (q : ℚ) : x ≠ q := fun hq => h ⟨q, hq.symm⟩ theorem ne_int (h : Irrational x) (m : ℤ) : x ≠ m := by rw [← Rat.cast_intCast] exact h.ne_rat _ theorem ne_nat (h : Irrational x) (m : ℕ) : x ≠ m := h.ne_int m theorem ne_zero (h : Irrational x) : x ≠ 0 := mod_cast h.ne_nat 0 theorem ne_one (h : Irrational x) : x ≠ 1 := by simpa only [Nat.cast_one] using h.ne_nat 1 -- See note [no_index around OfNat.ofNat] @[simp] theorem ne_ofNat (h : Irrational x) (n : ℕ) [n.AtLeastTwo] : x ≠ no_index (OfNat.ofNat n) := h.ne_nat n end Irrational @[simp] theorem Rat.not_irrational (q : ℚ) : ¬Irrational q := fun h => h ⟨q, rfl⟩ @[simp] theorem Int.not_irrational (m : ℤ) : ¬Irrational m := fun h => h.ne_int m rfl @[simp] theorem Nat.not_irrational (m : ℕ) : ¬Irrational m := fun h => h.ne_nat m rfl -- See note [no_index around OfNat.ofNat] @[simp] theorem not_irrational_ofNat (n : ℕ) [n.AtLeastTwo] : ¬Irrational (no_index (OfNat.ofNat n)) := n.not_irrational namespace Irrational variable (q : ℚ) {x y : ℝ} /-! #### Addition of rational/integer/natural numbers -/ /-- If `x + y` is irrational, then at least one of `x` and `y` is irrational. -/ theorem add_cases : Irrational (x + y) → Irrational x ∨ Irrational y := by delta Irrational contrapose! rintro ⟨⟨rx, rfl⟩, ⟨ry, rfl⟩⟩ exact ⟨rx + ry, cast_add rx ry⟩ theorem of_rat_add (h : Irrational (q + x)) : Irrational x := h.add_cases.resolve_left q.not_irrational theorem rat_add (h : Irrational x) : Irrational (q + x) := of_rat_add (-q) <| by rwa [cast_neg, neg_add_cancel_left] theorem of_add_rat : Irrational (x + q) → Irrational x := add_comm (↑q) x ▸ of_rat_add q theorem add_rat (h : Irrational x) : Irrational (x + q) := add_comm (↑q) x ▸ h.rat_add q theorem of_int_add (m : ℤ) (h : Irrational (m + x)) : Irrational x := by rw [← cast_intCast] at h exact h.of_rat_add m theorem of_add_int (m : ℤ) (h : Irrational (x + m)) : Irrational x := of_int_add m <| add_comm x m ▸ h theorem int_add (h : Irrational x) (m : ℤ) : Irrational (m + x) := by rw [← cast_intCast] exact h.rat_add m theorem add_int (h : Irrational x) (m : ℤ) : Irrational (x + m) := add_comm (↑m) x ▸ h.int_add m theorem of_nat_add (m : ℕ) (h : Irrational (m + x)) : Irrational x := h.of_int_add m theorem of_add_nat (m : ℕ) (h : Irrational (x + m)) : Irrational x := h.of_add_int m theorem nat_add (h : Irrational x) (m : ℕ) : Irrational (m + x) := h.int_add m theorem add_nat (h : Irrational x) (m : ℕ) : Irrational (x + m) := h.add_int m /-! #### Negation -/ theorem of_neg (h : Irrational (-x)) : Irrational x := fun ⟨q, hx⟩ => h ⟨-q, by rw [cast_neg, hx]⟩ protected theorem neg (h : Irrational x) : Irrational (-x) := of_neg <| by rwa [neg_neg] /-! #### Subtraction of rational/integer/natural numbers -/ theorem sub_rat (h : Irrational x) : Irrational (x - q) := by simpa only [sub_eq_add_neg, cast_neg] using h.add_rat (-q) theorem rat_sub (h : Irrational x) : Irrational (q - x) := by simpa only [sub_eq_add_neg] using h.neg.rat_add q theorem of_sub_rat (h : Irrational (x - q)) : Irrational x := of_add_rat (-q) <| by simpa only [cast_neg, sub_eq_add_neg] using h theorem of_rat_sub (h : Irrational (q - x)) : Irrational x := of_neg (of_rat_add q (by simpa only [sub_eq_add_neg] using h)) theorem sub_int (h : Irrational x) (m : ℤ) : Irrational (x - m) := by simpa only [Rat.cast_intCast] using h.sub_rat m theorem int_sub (h : Irrational x) (m : ℤ) : Irrational (m - x) := by simpa only [Rat.cast_intCast] using h.rat_sub m theorem of_sub_int (m : ℤ) (h : Irrational (x - m)) : Irrational x := of_sub_rat m <| by rwa [Rat.cast_intCast] theorem of_int_sub (m : ℤ) (h : Irrational (m - x)) : Irrational x := of_rat_sub m <| by rwa [Rat.cast_intCast] theorem sub_nat (h : Irrational x) (m : ℕ) : Irrational (x - m) := h.sub_int m theorem nat_sub (h : Irrational x) (m : ℕ) : Irrational (m - x) := h.int_sub m theorem of_sub_nat (m : ℕ) (h : Irrational (x - m)) : Irrational x := h.of_sub_int m theorem of_nat_sub (m : ℕ) (h : Irrational (m - x)) : Irrational x := h.of_int_sub m /-! #### Multiplication by rational numbers -/ theorem mul_cases : Irrational (x * y) → Irrational x ∨ Irrational y := by delta Irrational contrapose! rintro ⟨⟨rx, rfl⟩, ⟨ry, rfl⟩⟩ exact ⟨rx * ry, cast_mul rx ry⟩ theorem of_mul_rat (h : Irrational (x * q)) : Irrational x := h.mul_cases.resolve_right q.not_irrational theorem mul_rat (h : Irrational x) {q : ℚ} (hq : q ≠ 0) : Irrational (x * q) := of_mul_rat q⁻¹ <| by rwa [mul_assoc, ← cast_mul, mul_inv_cancel hq, cast_one, mul_one] theorem of_rat_mul : Irrational (q * x) → Irrational x := mul_comm x q ▸ of_mul_rat q theorem rat_mul (h : Irrational x) {q : ℚ} (hq : q ≠ 0) : Irrational (q * x) := mul_comm x q ▸ h.mul_rat hq theorem of_mul_int (m : ℤ) (h : Irrational (x * m)) : Irrational x := of_mul_rat m <| by rwa [cast_intCast] theorem of_int_mul (m : ℤ) (h : Irrational (m * x)) : Irrational x := of_rat_mul m <| by rwa [cast_intCast] theorem mul_int (h : Irrational x) {m : ℤ} (hm : m ≠ 0) : Irrational (x * m) := by rw [← cast_intCast] refine h.mul_rat ?_ rwa [Int.cast_ne_zero] theorem int_mul (h : Irrational x) {m : ℤ} (hm : m ≠ 0) : Irrational (m * x) := mul_comm x m ▸ h.mul_int hm theorem of_mul_nat (m : ℕ) (h : Irrational (x * m)) : Irrational x := h.of_mul_int m theorem of_nat_mul (m : ℕ) (h : Irrational (m * x)) : Irrational x := h.of_int_mul m theorem mul_nat (h : Irrational x) {m : ℕ} (hm : m ≠ 0) : Irrational (x * m) := h.mul_int <| Int.natCast_ne_zero.2 hm theorem nat_mul (h : Irrational x) {m : ℕ} (hm : m ≠ 0) : Irrational (m * x) := h.int_mul <| Int.natCast_ne_zero.2 hm /-! #### Inverse -/ theorem of_inv (h : Irrational x⁻¹) : Irrational x := fun ⟨q, hq⟩ => h <| hq ▸ ⟨q⁻¹, q.cast_inv⟩ protected theorem inv (h : Irrational x) : Irrational x⁻¹ := of_inv <| by rwa [inv_inv] /-! #### Division -/ theorem div_cases (h : Irrational (x / y)) : Irrational x ∨ Irrational y := h.mul_cases.imp id of_inv theorem of_rat_div (h : Irrational (q / x)) : Irrational x := (h.of_rat_mul q).of_inv theorem of_div_rat (h : Irrational (x / q)) : Irrational x := h.div_cases.resolve_right q.not_irrational theorem rat_div (h : Irrational x) {q : ℚ} (hq : q ≠ 0) : Irrational (q / x) := h.inv.rat_mul hq theorem div_rat (h : Irrational x) {q : ℚ} (hq : q ≠ 0) : Irrational (x / q) := by rw [div_eq_mul_inv, ← cast_inv] exact h.mul_rat (inv_ne_zero hq) theorem of_int_div (m : ℤ) (h : Irrational (m / x)) : Irrational x := h.div_cases.resolve_left m.not_irrational theorem of_div_int (m : ℤ) (h : Irrational (x / m)) : Irrational x := h.div_cases.resolve_right m.not_irrational theorem int_div (h : Irrational x) {m : ℤ} (hm : m ≠ 0) : Irrational (m / x) := h.inv.int_mul hm theorem div_int (h : Irrational x) {m : ℤ} (hm : m ≠ 0) : Irrational (x / m) := by rw [← cast_intCast] refine h.div_rat ?_ rwa [Int.cast_ne_zero] theorem of_nat_div (m : ℕ) (h : Irrational (m / x)) : Irrational x := h.of_int_div m theorem of_div_nat (m : ℕ) (h : Irrational (x / m)) : Irrational x := h.of_div_int m theorem nat_div (h : Irrational x) {m : ℕ} (hm : m ≠ 0) : Irrational (m / x) := h.inv.nat_mul hm theorem div_nat (h : Irrational x) {m : ℕ} (hm : m ≠ 0) : Irrational (x / m) := h.div_int <| by rwa [Int.natCast_ne_zero] theorem of_one_div (h : Irrational (1 / x)) : Irrational x := of_rat_div 1 <| by rwa [cast_one] /-! #### Natural and integer power -/ theorem of_mul_self (h : Irrational (x * x)) : Irrational x := h.mul_cases.elim id id theorem of_pow : ∀ n : ℕ, Irrational (x ^ n) → Irrational x | 0 => fun h => by rw [pow_zero] at h exact (h ⟨1, cast_one⟩).elim | n + 1 => fun h => by rw [pow_succ] at h exact h.mul_cases.elim (of_pow n) id open Int in theorem of_zpow : ∀ m : ℤ, Irrational (x ^ m) → Irrational x | (n : ℕ) => fun h => by rw [zpow_natCast] at h exact h.of_pow _ | -[n+1] => fun h => by rw [zpow_negSucc] at h exact h.of_inv.of_pow _ end Irrational section Polynomial open Polynomial open Polynomial variable (x : ℝ) (p : ℤ[X]) theorem one_lt_natDegree_of_irrational_root (hx : Irrational x) (p_nonzero : p ≠ 0) (x_is_root : aeval x p = 0) : 1 < p.natDegree := by by_contra rid rcases exists_eq_X_add_C_of_natDegree_le_one (not_lt.1 rid) with ⟨a, b, rfl⟩ clear rid have : (a : ℝ) * x = -b := by simpa [eq_neg_iff_add_eq_zero] using x_is_root rcases em (a = 0) with (rfl | ha) · obtain rfl : b = 0 := by simpa simp at p_nonzero · rw [mul_comm, ← eq_div_iff_mul_eq, eq_comm] at this · refine hx ⟨-b / a, ?_⟩ assumption_mod_cast · assumption_mod_cast end Polynomial section variable {q : ℚ} {m : ℤ} {n : ℕ} {x : ℝ} open Irrational /-! ### Simplification lemmas about operations -/ @[simp] theorem irrational_rat_add_iff : Irrational (q + x) ↔ Irrational x := ⟨of_rat_add q, rat_add q⟩ @[simp] theorem irrational_int_add_iff : Irrational (m + x) ↔ Irrational x := ⟨of_int_add m, fun h => h.int_add m⟩ @[simp] theorem irrational_nat_add_iff : Irrational (n + x) ↔ Irrational x := ⟨of_nat_add n, fun h => h.nat_add n⟩ @[simp] theorem irrational_add_rat_iff : Irrational (x + q) ↔ Irrational x := ⟨of_add_rat q, add_rat q⟩ @[simp] theorem irrational_add_int_iff : Irrational (x + m) ↔ Irrational x := ⟨of_add_int m, fun h => h.add_int m⟩ @[simp] theorem irrational_add_nat_iff : Irrational (x + n) ↔ Irrational x := ⟨of_add_nat n, fun h => h.add_nat n⟩ @[simp] theorem irrational_rat_sub_iff : Irrational (q - x) ↔ Irrational x := ⟨of_rat_sub q, rat_sub q⟩ @[simp] theorem irrational_int_sub_iff : Irrational (m - x) ↔ Irrational x := ⟨of_int_sub m, fun h => h.int_sub m⟩ @[simp] theorem irrational_nat_sub_iff : Irrational (n - x) ↔ Irrational x := ⟨of_nat_sub n, fun h => h.nat_sub n⟩ @[simp] theorem irrational_sub_rat_iff : Irrational (x - q) ↔ Irrational x := ⟨of_sub_rat q, sub_rat q⟩ @[simp] theorem irrational_sub_int_iff : Irrational (x - m) ↔ Irrational x := ⟨of_sub_int m, fun h => h.sub_int m⟩ @[simp] theorem irrational_sub_nat_iff : Irrational (x - n) ↔ Irrational x := ⟨of_sub_nat n, fun h => h.sub_nat n⟩ @[simp] theorem irrational_neg_iff : Irrational (-x) ↔ Irrational x := ⟨of_neg, Irrational.neg⟩ @[simp] theorem irrational_inv_iff : Irrational x⁻¹ ↔ Irrational x := ⟨of_inv, Irrational.inv⟩ @[simp] theorem irrational_rat_mul_iff : Irrational (q * x) ↔ q ≠ 0 ∧ Irrational x := ⟨fun h => ⟨Rat.cast_ne_zero.1 <| left_ne_zero_of_mul h.ne_zero, h.of_rat_mul q⟩, fun h => h.2.rat_mul h.1⟩ @[simp] theorem irrational_mul_rat_iff : Irrational (x * q) ↔ q ≠ 0 ∧ Irrational x := by rw [mul_comm, irrational_rat_mul_iff] @[simp] theorem irrational_int_mul_iff : Irrational (m * x) ↔ m ≠ 0 ∧ Irrational x := by rw [← cast_intCast, irrational_rat_mul_iff, Int.cast_ne_zero] @[simp] theorem irrational_mul_int_iff : Irrational (x * m) ↔ m ≠ 0 ∧ Irrational x := by rw [← cast_intCast, irrational_mul_rat_iff, Int.cast_ne_zero] @[simp] theorem irrational_nat_mul_iff : Irrational (n * x) ↔ n ≠ 0 ∧ Irrational x := by rw [← cast_natCast, irrational_rat_mul_iff, Nat.cast_ne_zero] @[simp] theorem irrational_mul_nat_iff : Irrational (x * n) ↔ n ≠ 0 ∧ Irrational x := by rw [← cast_natCast, irrational_mul_rat_iff, Nat.cast_ne_zero] @[simp] theorem irrational_rat_div_iff : Irrational (q / x) ↔ q ≠ 0 ∧ Irrational x := by simp [div_eq_mul_inv] @[simp] theorem irrational_div_rat_iff : Irrational (x / q) ↔ q ≠ 0 ∧ Irrational x := by rw [div_eq_mul_inv, ← cast_inv, irrational_mul_rat_iff, Ne, inv_eq_zero] @[simp] theorem irrational_int_div_iff : Irrational (m / x) ↔ m ≠ 0 ∧ Irrational x := by simp [div_eq_mul_inv] @[simp] theorem irrational_div_int_iff : Irrational (x / m) ↔ m ≠ 0 ∧ Irrational x := by rw [← cast_intCast, irrational_div_rat_iff, Int.cast_ne_zero] @[simp] theorem irrational_nat_div_iff : Irrational (n / x) ↔ n ≠ 0 ∧ Irrational x := by simp [div_eq_mul_inv] @[simp] theorem irrational_div_nat_iff : Irrational (x / n) ↔ n ≠ 0 ∧ Irrational x := by rw [← cast_natCast, irrational_div_rat_iff, Nat.cast_ne_zero] /-- There is an irrational number `r` between any two reals `x < r < y`. -/ theorem exists_irrational_btwn {x y : ℝ} (h : x < y) : ∃ r, Irrational r ∧ x < r ∧ r < y := let ⟨q, ⟨hq1, hq2⟩⟩ := exists_rat_btwn ((sub_lt_sub_iff_right (√2)).mpr h) ⟨q + √2, irrational_sqrt_two.rat_add _, sub_lt_iff_lt_add.mp hq1, lt_sub_iff_add_lt.mp hq2⟩ end
Data\Real\Pointwise.lean
/- Copyright (c) 2021 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Eric Wieser -/ import Mathlib.Algebra.Order.Module.OrderedSMul import Mathlib.Algebra.Order.Module.Pointwise import Mathlib.Data.Real.Archimedean /-! # Pointwise operations on sets of reals This file relates `sInf (a • s)`/`sSup (a • s)` with `a • sInf s`/`a • sSup s` for `s : Set ℝ`. From these, it relates `⨅ i, a • f i` / `⨆ i, a • f i` with `a • (⨅ i, f i)` / `a • (⨆ i, f i)`, and provides lemmas about distributing `*` over `⨅` and `⨆`. ## TODO This is true more generally for conditionally complete linear order whose default value is `0`. We don't have those yet. -/ open Set open Pointwise variable {ι : Sort*} {α : Type*} [LinearOrderedField α] section MulActionWithZero variable [MulActionWithZero α ℝ] [OrderedSMul α ℝ] {a : α} theorem Real.sInf_smul_of_nonneg (ha : 0 ≤ a) (s : Set ℝ) : sInf (a • s) = a • sInf s := by obtain rfl | hs := s.eq_empty_or_nonempty · rw [smul_set_empty, Real.sInf_empty, smul_zero] obtain rfl | ha' := ha.eq_or_lt · rw [zero_smul_set hs, zero_smul] exact csInf_singleton 0 by_cases h : BddBelow s · exact ((OrderIso.smulRight ha').map_csInf' hs h).symm · rw [Real.sInf_of_not_bddBelow (mt (bddBelow_smul_iff_of_pos ha').1 h), Real.sInf_of_not_bddBelow h, smul_zero] theorem Real.smul_iInf_of_nonneg (ha : 0 ≤ a) (f : ι → ℝ) : (a • ⨅ i, f i) = ⨅ i, a • f i := (Real.sInf_smul_of_nonneg ha _).symm.trans <| congr_arg sInf <| (range_comp _ _).symm theorem Real.sSup_smul_of_nonneg (ha : 0 ≤ a) (s : Set ℝ) : sSup (a • s) = a • sSup s := by obtain rfl | hs := s.eq_empty_or_nonempty · rw [smul_set_empty, Real.sSup_empty, smul_zero] obtain rfl | ha' := ha.eq_or_lt · rw [zero_smul_set hs, zero_smul] exact csSup_singleton 0 by_cases h : BddAbove s · exact ((OrderIso.smulRight ha').map_csSup' hs h).symm · rw [Real.sSup_of_not_bddAbove (mt (bddAbove_smul_iff_of_pos ha').1 h), Real.sSup_of_not_bddAbove h, smul_zero] theorem Real.smul_iSup_of_nonneg (ha : 0 ≤ a) (f : ι → ℝ) : (a • ⨆ i, f i) = ⨆ i, a • f i := (Real.sSup_smul_of_nonneg ha _).symm.trans <| congr_arg sSup <| (range_comp _ _).symm end MulActionWithZero section Module variable [Module α ℝ] [OrderedSMul α ℝ] {a : α} theorem Real.sInf_smul_of_nonpos (ha : a ≤ 0) (s : Set ℝ) : sInf (a • s) = a • sSup s := by obtain rfl | hs := s.eq_empty_or_nonempty · rw [smul_set_empty, Real.sInf_empty, Real.sSup_empty, smul_zero] obtain rfl | ha' := ha.eq_or_lt · rw [zero_smul_set hs, zero_smul] exact csInf_singleton 0 by_cases h : BddAbove s · exact ((OrderIso.smulRightDual ℝ ha').map_csSup' hs h).symm · rw [Real.sInf_of_not_bddBelow (mt (bddBelow_smul_iff_of_neg ha').1 h), Real.sSup_of_not_bddAbove h, smul_zero] theorem Real.smul_iSup_of_nonpos (ha : a ≤ 0) (f : ι → ℝ) : (a • ⨆ i, f i) = ⨅ i, a • f i := (Real.sInf_smul_of_nonpos ha _).symm.trans <| congr_arg sInf <| (range_comp _ _).symm theorem Real.sSup_smul_of_nonpos (ha : a ≤ 0) (s : Set ℝ) : sSup (a • s) = a • sInf s := by obtain rfl | hs := s.eq_empty_or_nonempty · rw [smul_set_empty, Real.sSup_empty, Real.sInf_empty, smul_zero] obtain rfl | ha' := ha.eq_or_lt · rw [zero_smul_set hs, zero_smul] exact csSup_singleton 0 by_cases h : BddBelow s · exact ((OrderIso.smulRightDual ℝ ha').map_csInf' hs h).symm · rw [Real.sSup_of_not_bddAbove (mt (bddAbove_smul_iff_of_neg ha').1 h), Real.sInf_of_not_bddBelow h, smul_zero] theorem Real.smul_iInf_of_nonpos (ha : a ≤ 0) (f : ι → ℝ) : (a • ⨅ i, f i) = ⨆ i, a • f i := (Real.sSup_smul_of_nonpos ha _).symm.trans <| congr_arg sSup <| (range_comp _ _).symm end Module /-! ## Special cases for real multiplication -/ section Mul variable {r : ℝ} theorem Real.mul_iInf_of_nonneg (ha : 0 ≤ r) (f : ι → ℝ) : (r * ⨅ i, f i) = ⨅ i, r * f i := Real.smul_iInf_of_nonneg ha f theorem Real.mul_iSup_of_nonneg (ha : 0 ≤ r) (f : ι → ℝ) : (r * ⨆ i, f i) = ⨆ i, r * f i := Real.smul_iSup_of_nonneg ha f theorem Real.mul_iInf_of_nonpos (ha : r ≤ 0) (f : ι → ℝ) : (r * ⨅ i, f i) = ⨆ i, r * f i := Real.smul_iInf_of_nonpos ha f theorem Real.mul_iSup_of_nonpos (ha : r ≤ 0) (f : ι → ℝ) : (r * ⨆ i, f i) = ⨅ i, r * f i := Real.smul_iSup_of_nonpos ha f theorem Real.iInf_mul_of_nonneg (ha : 0 ≤ r) (f : ι → ℝ) : (⨅ i, f i) * r = ⨅ i, f i * r := by simp only [Real.mul_iInf_of_nonneg ha, mul_comm] theorem Real.iSup_mul_of_nonneg (ha : 0 ≤ r) (f : ι → ℝ) : (⨆ i, f i) * r = ⨆ i, f i * r := by simp only [Real.mul_iSup_of_nonneg ha, mul_comm] theorem Real.iInf_mul_of_nonpos (ha : r ≤ 0) (f : ι → ℝ) : (⨅ i, f i) * r = ⨆ i, f i * r := by simp only [Real.mul_iInf_of_nonpos ha, mul_comm] theorem Real.iSup_mul_of_nonpos (ha : r ≤ 0) (f : ι → ℝ) : (⨆ i, f i) * r = ⨅ i, f i * r := by simp only [Real.mul_iSup_of_nonpos ha, mul_comm] end Mul
Data\Real\Sign.lean
/- Copyright (c) 2021 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying, Eric Wieser -/ import Mathlib.Data.Real.Basic import Mathlib.Tactic.NormNum.Inv /-! # Real sign function This file introduces and contains some results about `Real.sign` which maps negative real numbers to -1, positive real numbers to 1, and 0 to 0. ## Main definitions * `Real.sign r` is $\begin{cases} -1 & \text{if } r < 0, \\ ~~\, 0 & \text{if } r = 0, \\ ~~\, 1 & \text{if } r > 0. \end{cases}$ ## Tags sign function -/ namespace Real /-- The sign function that maps negative real numbers to -1, positive numbers to 1, and 0 otherwise. -/ noncomputable def sign (r : ℝ) : ℝ := if r < 0 then -1 else if 0 < r then 1 else 0 theorem sign_of_neg {r : ℝ} (hr : r < 0) : sign r = -1 := by rw [sign, if_pos hr] theorem sign_of_pos {r : ℝ} (hr : 0 < r) : sign r = 1 := by rw [sign, if_pos hr, if_neg hr.not_lt] @[simp] theorem sign_zero : sign 0 = 0 := by rw [sign, if_neg (lt_irrefl _), if_neg (lt_irrefl _)] @[simp] theorem sign_one : sign 1 = 1 := sign_of_pos <| by norm_num theorem sign_apply_eq (r : ℝ) : sign r = -1 ∨ sign r = 0 ∨ sign r = 1 := by obtain hn | rfl | hp := lt_trichotomy r (0 : ℝ) · exact Or.inl <| sign_of_neg hn · exact Or.inr <| Or.inl <| sign_zero · exact Or.inr <| Or.inr <| sign_of_pos hp /-- This lemma is useful for working with `ℝˣ` -/ theorem sign_apply_eq_of_ne_zero (r : ℝ) (h : r ≠ 0) : sign r = -1 ∨ sign r = 1 := h.lt_or_lt.imp sign_of_neg sign_of_pos @[simp] theorem sign_eq_zero_iff {r : ℝ} : sign r = 0 ↔ r = 0 := by refine ⟨fun h => ?_, fun h => h.symm ▸ sign_zero⟩ obtain hn | rfl | hp := lt_trichotomy r (0 : ℝ) · rw [sign_of_neg hn, neg_eq_zero] at h exact (one_ne_zero h).elim · rfl · rw [sign_of_pos hp] at h exact (one_ne_zero h).elim theorem sign_intCast (z : ℤ) : sign (z : ℝ) = ↑(Int.sign z) := by obtain hn | rfl | hp := lt_trichotomy z (0 : ℤ) · rw [sign_of_neg (Int.cast_lt_zero.mpr hn), Int.sign_eq_neg_one_of_neg hn, Int.cast_neg, Int.cast_one] · rw [Int.cast_zero, sign_zero, Int.sign_zero, Int.cast_zero] · rw [sign_of_pos (Int.cast_pos.mpr hp), Int.sign_eq_one_of_pos hp, Int.cast_one] @[deprecated (since := "2024-04-17")] alias sign_int_cast := sign_intCast theorem sign_neg {r : ℝ} : sign (-r) = -sign r := by obtain hn | rfl | hp := lt_trichotomy r (0 : ℝ) · rw [sign_of_neg hn, sign_of_pos (neg_pos.mpr hn), neg_neg] · rw [sign_zero, neg_zero, sign_zero] · rw [sign_of_pos hp, sign_of_neg (neg_lt_zero.mpr hp)] theorem sign_mul_nonneg (r : ℝ) : 0 ≤ sign r * r := by obtain hn | rfl | hp := lt_trichotomy r (0 : ℝ) · rw [sign_of_neg hn] exact mul_nonneg_of_nonpos_of_nonpos (by norm_num) hn.le · rw [mul_zero] · rw [sign_of_pos hp, one_mul] exact hp.le theorem sign_mul_pos_of_ne_zero (r : ℝ) (hr : r ≠ 0) : 0 < sign r * r := by refine lt_of_le_of_ne (sign_mul_nonneg r) fun h => hr ?_ have hs0 := (zero_eq_mul.mp h).resolve_right hr exact sign_eq_zero_iff.mp hs0 @[simp] theorem inv_sign (r : ℝ) : (sign r)⁻¹ = sign r := by obtain hn | hz | hp := sign_apply_eq r · rw [hn] norm_num · rw [hz] exact inv_zero · rw [hp] exact inv_one @[simp] theorem sign_inv (r : ℝ) : sign r⁻¹ = sign r := by obtain hn | rfl | hp := lt_trichotomy r (0 : ℝ) · rw [sign_of_neg hn, sign_of_neg (inv_lt_zero (α := ℝ) |>.mpr hn)] · rw [sign_zero, inv_zero, sign_zero] · rw [sign_of_pos hp, sign_of_pos (inv_pos (α := ℝ) |>.mpr hp)] end Real
Data\Real\Sqrt.lean
/- Copyright (c) 2020 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Floris van Doorn, Yury Kudryashov -/ import Mathlib.Topology.Instances.NNReal import Mathlib.Topology.Order.MonotoneContinuity /-! # Square root of a real number In this file we define * `NNReal.sqrt` to be the square root of a nonnegative real number. * `Real.sqrt` to be the square root of a real number, defined to be zero on negative numbers. Then we prove some basic properties of these functions. ## Implementation notes We define `NNReal.sqrt` as the noncomputable inverse to the function `x ↦ x * x`. We use general theory of inverses of strictly monotone functions to prove that `NNReal.sqrt x` exists. As a side effect, `NNReal.sqrt` is a bundled `OrderIso`, so for `NNReal` numbers we get continuity as well as theorems like `NNReal.sqrt x ≤ y ↔ x ≤ y * y` for free. Then we define `Real.sqrt x` to be `NNReal.sqrt (Real.toNNReal x)`. ## Tags square root -/ open Set Filter open scoped Filter NNReal Topology namespace NNReal variable {x y : ℝ≥0} /-- Square root of a nonnegative real number. -/ -- Porting note (kmill): `pp_nodot` has no affect here -- unless RFC lean4#1910 leads to dot notation for CoeFun @[pp_nodot] noncomputable def sqrt : ℝ≥0 ≃o ℝ≥0 := OrderIso.symm <| powOrderIso 2 two_ne_zero @[simp] lemma sq_sqrt (x : ℝ≥0) : sqrt x ^ 2 = x := sqrt.symm_apply_apply _ @[simp] lemma sqrt_sq (x : ℝ≥0) : sqrt (x ^ 2) = x := sqrt.apply_symm_apply _ @[simp] lemma mul_self_sqrt (x : ℝ≥0) : sqrt x * sqrt x = x := by rw [← sq, sq_sqrt] @[simp] lemma sqrt_mul_self (x : ℝ≥0) : sqrt (x * x) = x := by rw [← sq, sqrt_sq] lemma sqrt_le_sqrt : sqrt x ≤ sqrt y ↔ x ≤ y := sqrt.le_iff_le lemma sqrt_lt_sqrt : sqrt x < sqrt y ↔ x < y := sqrt.lt_iff_lt lemma sqrt_eq_iff_eq_sq : sqrt x = y ↔ x = y ^ 2 := sqrt.toEquiv.apply_eq_iff_eq_symm_apply lemma sqrt_le_iff_le_sq : sqrt x ≤ y ↔ x ≤ y ^ 2 := sqrt.to_galoisConnection _ _ lemma le_sqrt_iff_sq_le : x ≤ sqrt y ↔ x ^ 2 ≤ y := (sqrt.symm.to_galoisConnection _ _).symm @[deprecated (since := "2024-02-14")] alias sqrt_le_sqrt_iff := sqrt_le_sqrt @[deprecated (since := "2024-02-14")] alias sqrt_lt_sqrt_iff := sqrt_lt_sqrt @[deprecated (since := "2024-02-14")] alias sqrt_le_iff := sqrt_le_iff_le_sq @[deprecated (since := "2024-02-14")] alias le_sqrt_iff := le_sqrt_iff_sq_le @[deprecated (since := "2024-02-14")] alias sqrt_eq_iff_sq_eq := sqrt_eq_iff_eq_sq @[simp] lemma sqrt_eq_zero : sqrt x = 0 ↔ x = 0 := by simp [sqrt_eq_iff_eq_sq] @[simp] lemma sqrt_eq_one : sqrt x = 1 ↔ x = 1 := by simp [sqrt_eq_iff_eq_sq] @[simp] lemma sqrt_zero : sqrt 0 = 0 := by simp @[simp] lemma sqrt_one : sqrt 1 = 1 := by simp @[simp] lemma sqrt_le_one : sqrt x ≤ 1 ↔ x ≤ 1 := by rw [← sqrt_one, sqrt_le_sqrt, sqrt_one] @[simp] lemma one_le_sqrt : 1 ≤ sqrt x ↔ 1 ≤ x := by rw [← sqrt_one, sqrt_le_sqrt, sqrt_one] theorem sqrt_mul (x y : ℝ≥0) : sqrt (x * y) = sqrt x * sqrt y := by rw [sqrt_eq_iff_eq_sq, mul_pow, sq_sqrt, sq_sqrt] /-- `NNReal.sqrt` as a `MonoidWithZeroHom`. -/ noncomputable def sqrtHom : ℝ≥0 →*₀ ℝ≥0 := ⟨⟨sqrt, sqrt_zero⟩, sqrt_one, sqrt_mul⟩ theorem sqrt_inv (x : ℝ≥0) : sqrt x⁻¹ = (sqrt x)⁻¹ := map_inv₀ sqrtHom x theorem sqrt_div (x y : ℝ≥0) : sqrt (x / y) = sqrt x / sqrt y := map_div₀ sqrtHom x y @[continuity, fun_prop] theorem continuous_sqrt : Continuous sqrt := sqrt.continuous @[simp] theorem sqrt_pos : 0 < sqrt x ↔ 0 < x := by simp [pos_iff_ne_zero] alias ⟨_, sqrt_pos_of_pos⟩ := sqrt_pos attribute [bound] sqrt_pos_of_pos end NNReal namespace Real /-- The square root of a real number. This returns 0 for negative inputs. This has notation `√x`. Note that `√x⁻¹` is parsed as `√(x⁻¹)`. -/ noncomputable def sqrt (x : ℝ) : ℝ := NNReal.sqrt (Real.toNNReal x) -- TODO: replace this with a typeclass @[inherit_doc] prefix:max "√" => Real.sqrt /- quotient.lift_on x (λ f, mk ⟨sqrt_aux f, (sqrt_aux_converges f).fst⟩) (λ f g e, begin rcases sqrt_aux_converges f with ⟨hf, x, x0, xf, xs⟩, rcases sqrt_aux_converges g with ⟨hg, y, y0, yg, ys⟩, refine xs.trans (eq.trans _ ys.symm), rw [← @mul_self_inj_of_nonneg ℝ _ x y x0 y0, xf, yg], congr' 1, exact quotient.sound e end)-/ variable {x y : ℝ} @[simp, norm_cast] theorem coe_sqrt {x : ℝ≥0} : (NNReal.sqrt x : ℝ) = √(x : ℝ) := by rw [Real.sqrt, Real.toNNReal_coe] @[continuity] theorem continuous_sqrt : Continuous (√· : ℝ → ℝ) := NNReal.continuous_coe.comp <| NNReal.continuous_sqrt.comp continuous_real_toNNReal theorem sqrt_eq_zero_of_nonpos (h : x ≤ 0) : sqrt x = 0 := by simp [sqrt, Real.toNNReal_eq_zero.2 h] theorem sqrt_nonneg (x : ℝ) : 0 ≤ √x := NNReal.coe_nonneg _ @[simp] theorem mul_self_sqrt (h : 0 ≤ x) : √x * √x = x := by rw [Real.sqrt, ← NNReal.coe_mul, NNReal.mul_self_sqrt, Real.coe_toNNReal _ h] @[simp] theorem sqrt_mul_self (h : 0 ≤ x) : √(x * x) = x := (mul_self_inj_of_nonneg (sqrt_nonneg _) h).1 (mul_self_sqrt (mul_self_nonneg _)) theorem sqrt_eq_cases : √x = y ↔ y * y = x ∧ 0 ≤ y ∨ x < 0 ∧ y = 0 := by constructor · rintro rfl rcases le_or_lt 0 x with hle | hlt · exact Or.inl ⟨mul_self_sqrt hle, sqrt_nonneg x⟩ · exact Or.inr ⟨hlt, sqrt_eq_zero_of_nonpos hlt.le⟩ · rintro (⟨rfl, hy⟩ | ⟨hx, rfl⟩) exacts [sqrt_mul_self hy, sqrt_eq_zero_of_nonpos hx.le] theorem sqrt_eq_iff_mul_self_eq (hx : 0 ≤ x) (hy : 0 ≤ y) : √x = y ↔ y * y = x := ⟨fun h => by rw [← h, mul_self_sqrt hx], fun h => by rw [← h, sqrt_mul_self hy]⟩ theorem sqrt_eq_iff_mul_self_eq_of_pos (h : 0 < y) : √x = y ↔ y * y = x := by simp [sqrt_eq_cases, h.ne', h.le] @[simp] theorem sqrt_eq_one : √x = 1 ↔ x = 1 := calc √x = 1 ↔ 1 * 1 = x := sqrt_eq_iff_mul_self_eq_of_pos zero_lt_one _ ↔ x = 1 := by rw [eq_comm, mul_one] @[simp] theorem sq_sqrt (h : 0 ≤ x) : √x ^ 2 = x := by rw [sq, mul_self_sqrt h] @[simp] theorem sqrt_sq (h : 0 ≤ x) : √(x ^ 2) = x := by rw [sq, sqrt_mul_self h] theorem sqrt_eq_iff_sq_eq (hx : 0 ≤ x) (hy : 0 ≤ y) : √x = y ↔ y ^ 2 = x := by rw [sq, sqrt_eq_iff_mul_self_eq hx hy] theorem sqrt_mul_self_eq_abs (x : ℝ) : √(x * x) = |x| := by rw [← abs_mul_abs_self x, sqrt_mul_self (abs_nonneg _)] theorem sqrt_sq_eq_abs (x : ℝ) : √(x ^ 2) = |x| := by rw [sq, sqrt_mul_self_eq_abs] @[simp] theorem sqrt_zero : √0 = 0 := by simp [Real.sqrt] @[simp] theorem sqrt_one : √1 = 1 := by simp [Real.sqrt] @[simp] theorem sqrt_le_sqrt_iff (hy : 0 ≤ y) : √x ≤ √y ↔ x ≤ y := by rw [Real.sqrt, Real.sqrt, NNReal.coe_le_coe, NNReal.sqrt_le_sqrt, toNNReal_le_toNNReal_iff hy] @[simp] theorem sqrt_lt_sqrt_iff (hx : 0 ≤ x) : √x < √y ↔ x < y := lt_iff_lt_of_le_iff_le (sqrt_le_sqrt_iff hx) theorem sqrt_lt_sqrt_iff_of_pos (hy : 0 < y) : √x < √y ↔ x < y := by rw [Real.sqrt, Real.sqrt, NNReal.coe_lt_coe, NNReal.sqrt_lt_sqrt, toNNReal_lt_toNNReal_iff hy] @[gcongr, bound] theorem sqrt_le_sqrt (h : x ≤ y) : √x ≤ √y := by rw [Real.sqrt, Real.sqrt, NNReal.coe_le_coe, NNReal.sqrt_le_sqrt] exact toNNReal_le_toNNReal h @[gcongr, bound] theorem sqrt_lt_sqrt (hx : 0 ≤ x) (h : x < y) : √x < √y := (sqrt_lt_sqrt_iff hx).2 h theorem sqrt_le_left (hy : 0 ≤ y) : √x ≤ y ↔ x ≤ y ^ 2 := by rw [sqrt, ← Real.le_toNNReal_iff_coe_le hy, NNReal.sqrt_le_iff_le_sq, sq, ← Real.toNNReal_mul hy, Real.toNNReal_le_toNNReal_iff (mul_self_nonneg y), sq] theorem sqrt_le_iff : √x ≤ y ↔ 0 ≤ y ∧ x ≤ y ^ 2 := by rw [← and_iff_right_of_imp fun h => (sqrt_nonneg x).trans h, and_congr_right_iff] exact sqrt_le_left theorem sqrt_lt (hx : 0 ≤ x) (hy : 0 ≤ y) : √x < y ↔ x < y ^ 2 := by rw [← sqrt_lt_sqrt_iff hx, sqrt_sq hy] theorem sqrt_lt' (hy : 0 < y) : √x < y ↔ x < y ^ 2 := by rw [← sqrt_lt_sqrt_iff_of_pos (pow_pos hy _), sqrt_sq hy.le] /-- Note: if you want to conclude `x ≤ √y`, then use `Real.le_sqrt_of_sq_le`. If you have `x > 0`, consider using `Real.le_sqrt'` -/ theorem le_sqrt (hx : 0 ≤ x) (hy : 0 ≤ y) : x ≤ √y ↔ x ^ 2 ≤ y := le_iff_le_iff_lt_iff_lt.2 <| sqrt_lt hy hx theorem le_sqrt' (hx : 0 < x) : x ≤ √y ↔ x ^ 2 ≤ y := le_iff_le_iff_lt_iff_lt.2 <| sqrt_lt' hx theorem abs_le_sqrt (h : x ^ 2 ≤ y) : |x| ≤ √y := by rw [← sqrt_sq_eq_abs]; exact sqrt_le_sqrt h theorem sq_le (h : 0 ≤ y) : x ^ 2 ≤ y ↔ -√y ≤ x ∧ x ≤ √y := by constructor · simpa only [abs_le] using abs_le_sqrt · rw [← abs_le, ← sq_abs] exact (le_sqrt (abs_nonneg x) h).mp theorem neg_sqrt_le_of_sq_le (h : x ^ 2 ≤ y) : -√y ≤ x := ((sq_le ((sq_nonneg x).trans h)).mp h).1 theorem le_sqrt_of_sq_le (h : x ^ 2 ≤ y) : x ≤ √y := ((sq_le ((sq_nonneg x).trans h)).mp h).2 @[simp] theorem sqrt_inj (hx : 0 ≤ x) (hy : 0 ≤ y) : √x = √y ↔ x = y := by simp [le_antisymm_iff, hx, hy] @[simp] theorem sqrt_eq_zero (h : 0 ≤ x) : √x = 0 ↔ x = 0 := by simpa using sqrt_inj h le_rfl theorem sqrt_eq_zero' : √x = 0 ↔ x ≤ 0 := by rw [sqrt, NNReal.coe_eq_zero, NNReal.sqrt_eq_zero, Real.toNNReal_eq_zero] theorem sqrt_ne_zero (h : 0 ≤ x) : √x ≠ 0 ↔ x ≠ 0 := by rw [not_iff_not, sqrt_eq_zero h] theorem sqrt_ne_zero' : √x ≠ 0 ↔ 0 < x := by rw [← not_le, not_iff_not, sqrt_eq_zero'] @[simp] theorem sqrt_pos : 0 < √x ↔ 0 < x := lt_iff_lt_of_le_iff_le (Iff.trans (by simp [le_antisymm_iff, sqrt_nonneg]) sqrt_eq_zero') alias ⟨_, sqrt_pos_of_pos⟩ := sqrt_pos lemma sqrt_le_sqrt_iff' (hx : 0 < x) : √x ≤ √y ↔ x ≤ y := by obtain hy | hy := le_total y 0 · exact iff_of_false ((sqrt_eq_zero_of_nonpos hy).trans_lt $ sqrt_pos.2 hx).not_le (hy.trans_lt hx).not_le · exact sqrt_le_sqrt_iff hy @[simp] lemma one_le_sqrt : 1 ≤ √x ↔ 1 ≤ x := by rw [← sqrt_one, sqrt_le_sqrt_iff' zero_lt_one, sqrt_one] @[simp] lemma sqrt_le_one : √x ≤ 1 ↔ x ≤ 1 := by rw [← sqrt_one, sqrt_le_sqrt_iff zero_le_one, sqrt_one] end Real namespace Mathlib.Meta.Positivity open Lean Meta Qq Function /-- Extension for the `positivity` tactic: a square root of a strictly positive nonnegative real is positive. -/ @[positivity NNReal.sqrt _] def evalNNRealSqrt : PositivityExt where eval {u α} _zα _pα e := do match u, α, e with | 0, ~q(NNReal), ~q(NNReal.sqrt $a) => let ra ← core q(inferInstance) q(inferInstance) a assertInstancesCommute match ra with | .positive pa => pure (.positive q(NNReal.sqrt_pos_of_pos $pa)) | _ => failure -- this case is dealt with by generic nonnegativity of nnreals | _, _, _ => throwError "not NNReal.sqrt" /-- Extension for the `positivity` tactic: a square root is nonnegative, and is strictly positive if its input is. -/ @[positivity √ _] def evalSqrt : PositivityExt where eval {u α} _zα _pα e := do match u, α, e with | 0, ~q(ℝ), ~q(√$a) => let ra ← catchNone <| core q(inferInstance) q(inferInstance) a assertInstancesCommute match ra with | .positive pa => pure (.positive q(Real.sqrt_pos_of_pos $pa)) | _ => pure (.nonnegative q(Real.sqrt_nonneg $a)) | _, _, _ => throwError "not Real.sqrt" end Mathlib.Meta.Positivity namespace Real variable {x y : ℝ} @[simp] theorem sqrt_mul {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : √(x * y) = √x * √y := by simp_rw [Real.sqrt, ← NNReal.coe_mul, NNReal.coe_inj, Real.toNNReal_mul hx, NNReal.sqrt_mul] @[simp] theorem sqrt_mul' (x) {y : ℝ} (hy : 0 ≤ y) : √(x * y) = √x * √y := by rw [mul_comm, sqrt_mul hy, mul_comm] @[simp] theorem sqrt_inv (x : ℝ) : √x⁻¹ = (√x)⁻¹ := by rw [Real.sqrt, Real.toNNReal_inv, NNReal.sqrt_inv, NNReal.coe_inv, Real.sqrt] @[simp] theorem sqrt_div {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : √(x / y) = √x / √y := by rw [division_def, sqrt_mul hx, sqrt_inv, division_def] @[simp] theorem sqrt_div' (x) {y : ℝ} (hy : 0 ≤ y) : √(x / y) = √x / √y := by rw [division_def, sqrt_mul' x (inv_nonneg.2 hy), sqrt_inv, division_def] variable {x y : ℝ} @[simp] theorem div_sqrt : x / √x = √x := by rcases le_or_lt x 0 with h | h · rw [sqrt_eq_zero'.mpr h, div_zero] · rw [div_eq_iff (sqrt_ne_zero'.mpr h), mul_self_sqrt h.le] theorem sqrt_div_self' : √x / x = 1 / √x := by rw [← div_sqrt, one_div_div, div_sqrt] theorem sqrt_div_self : √x / x = (√x)⁻¹ := by rw [sqrt_div_self', one_div] theorem lt_sqrt (hx : 0 ≤ x) : x < √y ↔ x ^ 2 < y := by rw [← sqrt_lt_sqrt_iff (sq_nonneg _), sqrt_sq hx] theorem sq_lt : x ^ 2 < y ↔ -√y < x ∧ x < √y := by rw [← abs_lt, ← sq_abs, lt_sqrt (abs_nonneg _)] theorem neg_sqrt_lt_of_sq_lt (h : x ^ 2 < y) : -√y < x := (sq_lt.mp h).1 theorem lt_sqrt_of_sq_lt (h : x ^ 2 < y) : x < √y := (sq_lt.mp h).2 theorem lt_sq_of_sqrt_lt (h : √x < y) : x < y ^ 2 := by have hy := x.sqrt_nonneg.trans_lt h rwa [← sqrt_lt_sqrt_iff_of_pos (sq_pos_of_pos hy), sqrt_sq hy.le] /-- The natural square root is at most the real square root -/ theorem nat_sqrt_le_real_sqrt {a : ℕ} : ↑(Nat.sqrt a) ≤ √(a : ℝ) := by rw [Real.le_sqrt (Nat.cast_nonneg _) (Nat.cast_nonneg _)] norm_cast exact Nat.sqrt_le' a /-- The real square root is less than the natural square root plus one -/ theorem real_sqrt_lt_nat_sqrt_succ {a : ℕ} : √(a : ℝ) < Nat.sqrt a + 1 := by rw [sqrt_lt (by simp)] <;> norm_cast · exact Nat.lt_succ_sqrt' a · exact Nat.le_add_left 0 (Nat.sqrt a + 1) /-- The real square root is at most the natural square root plus one -/ theorem real_sqrt_le_nat_sqrt_succ {a : ℕ} : √(a : ℝ) ≤ Nat.sqrt a + 1 := real_sqrt_lt_nat_sqrt_succ.le /-- The floor of the real square root is the same as the natural square root. -/ @[simp] theorem floor_real_sqrt_eq_nat_sqrt {a : ℕ} : ⌊√(a : ℝ)⌋ = Nat.sqrt a := by rw [Int.floor_eq_iff] exact ⟨nat_sqrt_le_real_sqrt, real_sqrt_lt_nat_sqrt_succ⟩ /-- The natural floor of the real square root is the same as the natural square root. -/ @[simp] theorem nat_floor_real_sqrt_eq_nat_sqrt {a : ℕ} : ⌊√(a : ℝ)⌋₊ = Nat.sqrt a := by rw [Nat.floor_eq_iff (sqrt_nonneg a)] exact ⟨nat_sqrt_le_real_sqrt, real_sqrt_lt_nat_sqrt_succ⟩ /-- Bernoulli's inequality for exponent `1 / 2`, stated using `sqrt`. -/ theorem sqrt_one_add_le (h : -1 ≤ x) : √(1 + x) ≤ 1 + x / 2 := by refine sqrt_le_iff.mpr ⟨by linarith, ?_⟩ calc 1 + x _ ≤ 1 + x + (x / 2) ^ 2 := le_add_of_nonneg_right <| sq_nonneg _ _ = _ := by ring end Real open Real variable {α : Type*} theorem Filter.Tendsto.sqrt {f : α → ℝ} {l : Filter α} {x : ℝ} (h : Tendsto f l (𝓝 x)) : Tendsto (fun x => √(f x)) l (𝓝 (√x)) := (continuous_sqrt.tendsto _).comp h variable [TopologicalSpace α] {f : α → ℝ} {s : Set α} {x : α} nonrec theorem ContinuousWithinAt.sqrt (h : ContinuousWithinAt f s x) : ContinuousWithinAt (fun x => √(f x)) s x := h.sqrt @[fun_prop] nonrec theorem ContinuousAt.sqrt (h : ContinuousAt f x) : ContinuousAt (fun x => √(f x)) x := h.sqrt @[fun_prop] theorem ContinuousOn.sqrt (h : ContinuousOn f s) : ContinuousOn (fun x => √(f x)) s := fun x hx => (h x hx).sqrt @[continuity, fun_prop] theorem Continuous.sqrt (h : Continuous f) : Continuous fun x => √(f x) := continuous_sqrt.comp h namespace NNReal variable {ι : Type*} open Finset /-- **Cauchy-Schwarz inequality** for finsets using square roots in `ℝ≥0`. -/ lemma sum_mul_le_sqrt_mul_sqrt (s : Finset ι) (f g : ι → ℝ≥0) : ∑ i ∈ s, f i * g i ≤ sqrt (∑ i ∈ s, f i ^ 2) * sqrt (∑ i ∈ s, g i ^ 2) := (le_sqrt_iff_sq_le.2 $ sum_mul_sq_le_sq_mul_sq _ _ _).trans_eq <| sqrt_mul _ _ /-- **Cauchy-Schwarz inequality** for finsets using square roots in `ℝ≥0`. -/ lemma sum_sqrt_mul_sqrt_le (s : Finset ι) (f g : ι → ℝ≥0) : ∑ i ∈ s, sqrt (f i) * sqrt (g i) ≤ sqrt (∑ i ∈ s, f i) * sqrt (∑ i ∈ s, g i) := by simpa [*] using sum_mul_le_sqrt_mul_sqrt _ (fun x ↦ sqrt (f x)) (fun x ↦ sqrt (g x)) end NNReal namespace Real variable {ι : Type*} {f g : ι → ℝ} open Finset /-- **Cauchy-Schwarz inequality** for finsets using square roots in `ℝ`. -/ lemma sum_mul_le_sqrt_mul_sqrt (s : Finset ι) (f g : ι → ℝ) : ∑ i ∈ s, f i * g i ≤ √(∑ i ∈ s, f i ^ 2) * √(∑ i ∈ s, g i ^ 2) := (le_sqrt_of_sq_le <| sum_mul_sq_le_sq_mul_sq _ _ _).trans_eq <| sqrt_mul (sum_nonneg fun _ _ ↦ by positivity) _ /-- **Cauchy-Schwarz inequality** for finsets using square roots in `ℝ`. -/ lemma sum_sqrt_mul_sqrt_le (s : Finset ι) (hf : ∀ i, 0 ≤ f i) (hg : ∀ i, 0 ≤ g i) : ∑ i ∈ s, √(f i) * √(g i) ≤ √(∑ i ∈ s, f i) * √(∑ i ∈ s, g i) := by simpa [*] using sum_mul_le_sqrt_mul_sqrt _ (fun x ↦ √(f x)) (fun x ↦ √(g x)) end Real
Data\Real\Star.lean
/- Copyright (c) 2020 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Floris van Doorn, Yury Kudryashov -/ import Mathlib.Algebra.Star.Basic import Mathlib.Data.Real.Basic /-! # The real numbers are a `*`-ring, with the trivial `*`-structure -/ /-- The real numbers are a `*`-ring, with the trivial `*`-structure. -/ instance : StarRing ℝ := starRingOfComm instance : TrivialStar ℝ := ⟨fun _ => rfl⟩
Data\Real\StarOrdered.lean
/- Copyright (c) 2020 Kim Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kim Morrison -/ import Mathlib.Algebra.Star.Order import Mathlib.Data.Real.Sqrt /-! # `ℝ` and `ℝ≥0` are *-ordered rings. -/ open scoped NNReal /-- Although the instance `RCLike.toStarOrderedRing` exists, it is locked behind the `ComplexOrder` scope because currently the order on `ℂ` is not enabled globally. But we want `StarOrderedRing ℝ` to be available globally, so we include this instance separately. In addition, providing this instance here makes it available earlier in the import hierarchy; otherwise in order to access it we would need to import `Mathlib.Analysis.RCLike.Basic`. -/ instance Real.instStarOrderedRing : StarOrderedRing ℝ := StarOrderedRing.of_nonneg_iff' add_le_add_left fun r => by refine ⟨fun hr => ⟨√r, (mul_self_sqrt hr).symm⟩, ?_⟩ rintro ⟨s, rfl⟩ exact mul_self_nonneg s instance NNReal.instStarOrderedRing : StarOrderedRing ℝ≥0 := by refine .of_le_iff fun x y ↦ ⟨fun h ↦ ?_, ?_⟩ · obtain ⟨d, rfl⟩ := exists_add_of_le h refine ⟨sqrt d, ?_⟩ simp only [star_trivial, mul_self_sqrt] · rintro ⟨p, -, rfl⟩ exact le_self_add
Data\Real\Pi\Bounds.lean
/- Copyright (c) 2019 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Mario Carneiro -/ import Mathlib.Analysis.SpecialFunctions.Trigonometric.Bounds /-! # Pi This file contains lemmas which establish bounds on `Real.pi`. Notably, these include `pi_gt_sqrtTwoAddSeries` and `pi_lt_sqrtTwoAddSeries`, which bound `π` using series; numerical bounds on `π` such as `pi_gt_314`and `pi_lt_315` (more precise versions are given, too). See also `Mathlib/Data/Real/Pi/Leibniz.lean` and `Mathlib/Data/Real/Pi/Wallis.lean` for infinite formulas for `π`. -/ -- Porting note: needed to add a lot of type ascriptions for lean to interpret numbers as reals. open scoped Real namespace Real theorem pi_gt_sqrtTwoAddSeries (n : ℕ) : (2 : ℝ) ^ (n + 1) * √(2 - sqrtTwoAddSeries 0 n) < π := by have : √(2 - sqrtTwoAddSeries 0 n) / (2 : ℝ) * (2 : ℝ) ^ (n + 2) < π := by rw [← lt_div_iff, ← sin_pi_over_two_pow_succ] focus apply sin_lt apply div_pos pi_pos all_goals apply pow_pos; norm_num apply lt_of_le_of_lt (le_of_eq _) this rw [pow_succ' _ (n + 1), ← mul_assoc, div_mul_cancel₀, mul_comm]; norm_num theorem pi_lt_sqrtTwoAddSeries (n : ℕ) : π < (2 : ℝ) ^ (n + 1) * √(2 - sqrtTwoAddSeries 0 n) + 1 / (4 : ℝ) ^ n := by have : π < (√(2 - sqrtTwoAddSeries 0 n) / (2 : ℝ) + (1 : ℝ) / ((2 : ℝ) ^ n) ^ 3 / 4) * (2 : ℝ) ^ (n + 2) := by rw [← div_lt_iff (by norm_num), ← sin_pi_over_two_pow_succ] refine lt_of_lt_of_le (lt_add_of_sub_right_lt (sin_gt_sub_cube ?_ ?_)) ?_ · apply div_pos pi_pos; apply pow_pos; norm_num · rw [div_le_iff'] · refine le_trans pi_le_four ?_ simp only [show (4 : ℝ) = (2 : ℝ) ^ 2 by norm_num, mul_one] apply pow_le_pow_right (by norm_num) apply le_add_of_nonneg_left; apply Nat.zero_le · apply pow_pos; norm_num apply add_le_add_left; rw [div_le_div_right (by norm_num)] rw [le_div_iff (by norm_num), ← mul_pow] refine le_trans ?_ (le_of_eq (one_pow 3)); apply pow_le_pow_left · apply le_of_lt; apply mul_pos · apply div_pos pi_pos; apply pow_pos; norm_num · apply pow_pos; norm_num · rw [← le_div_iff (by norm_num)] refine le_trans ((div_le_div_right ?_).mpr pi_le_four) ?_ · apply pow_pos; norm_num · simp only [pow_succ', ← div_div, one_div] -- Porting note: removed `convert le_rfl` norm_num apply lt_of_lt_of_le this (le_of_eq _); rw [add_mul]; congr 1 · ring simp only [show (4 : ℝ) = 2 ^ 2 by norm_num, ← pow_mul, div_div, ← pow_add] rw [one_div, one_div, inv_mul_eq_iff_eq_mul₀, eq_comm, mul_inv_eq_iff_eq_mul₀, ← pow_add] · rw [add_assoc, Nat.mul_succ, add_comm, add_comm n, add_assoc, mul_comm n] all_goals norm_num /-- From an upper bound on `sqrtTwoAddSeries 0 n = 2 cos (π / 2 ^ (n+1))` of the form `sqrtTwoAddSeries 0 n ≤ 2 - (a / 2 ^ (n + 1)) ^ 2)`, one can deduce the lower bound `a < π` thanks to basic trigonometric inequalities as expressed in `pi_gt_sqrtTwoAddSeries`. -/ theorem pi_lower_bound_start (n : ℕ) {a} (h : sqrtTwoAddSeries ((0 : ℕ) / (1 : ℕ)) n ≤ (2 : ℝ) - (a / (2 : ℝ) ^ (n + 1)) ^ 2) : a < π := by refine lt_of_le_of_lt ?_ (pi_gt_sqrtTwoAddSeries n); rw [mul_comm] refine (div_le_iff (pow_pos (by norm_num) _ : (0 : ℝ) < _)).mp (le_sqrt_of_sq_le ?_) rwa [le_sub_comm, show (0 : ℝ) = (0 : ℕ) / (1 : ℕ) by rw [Nat.cast_zero, zero_div]] theorem sqrtTwoAddSeries_step_up (c d : ℕ) {a b n : ℕ} {z : ℝ} (hz : sqrtTwoAddSeries (c / d) n ≤ z) (hb : 0 < b) (hd : 0 < d) (h : (2 * b + a) * d ^ 2 ≤ c ^ 2 * b) : sqrtTwoAddSeries (a / b) (n + 1) ≤ z := by refine le_trans ?_ hz; rw [sqrtTwoAddSeries_succ]; apply sqrtTwoAddSeries_monotone_left have hb' : 0 < (b : ℝ) := Nat.cast_pos.2 hb have hd' : 0 < (d : ℝ) := Nat.cast_pos.2 hd rw [sqrt_le_left (div_nonneg c.cast_nonneg d.cast_nonneg), div_pow, add_div_eq_mul_add_div _ _ (ne_of_gt hb'), div_le_div_iff hb' (pow_pos hd' _)] exact mod_cast h section Tactic open Lean Elab Tactic /-- `numDen stx` takes a syntax expression `stx` and * if it is of the form `a / b`, then it returns `some (a, b)`; * otherwise it returns `none`. -/ private def numDen : Syntax → Option (Syntax.Term × Syntax.Term) | `($a / $b) => some (a, b) | _ => none /-- Create a proof of `a < π` for a fixed rational number `a`, given a witness, which is a sequence of rational numbers `√2 < r 1 < r 2 < ... < r n < 2` satisfying the property that `√(2 + r i) ≤ r(i+1)`, where `r 0 = 0` and `√(2 - r n) ≥ a/2^(n+1)`. -/ elab "pi_lower_bound " "[" l:term,* "]" : tactic => do let rat_sep := l.elemsAndSeps let sep := rat_sep.getD 1 .missing let ratStx := rat_sep.filter (· != sep) let n := ← (toExpr ratStx.size).toSyntax let els := (ratStx.map numDen).reduceOption evalTactic (← `(tactic| apply pi_lower_bound_start $n)) let _ := ← els.mapM fun (x, y) => do evalTactic (← `(tactic| apply sqrtTwoAddSeries_step_up $x $y)) evalTactic (← `(tactic| simp [sqrtTwoAddSeries])) allGoals (evalTactic (← `(tactic| norm_num1))) end Tactic /-- From a lower bound on `sqrtTwoAddSeries 0 n = 2 cos (π / 2 ^ (n+1))` of the form `2 - ((a - 1 / 4 ^ n) / 2 ^ (n + 1)) ^ 2 ≤ sqrtTwoAddSeries 0 n`, one can deduce the upper bound `π < a` thanks to basic trigonometric formulas as expressed in `pi_lt_sqrtTwoAddSeries`. -/ theorem pi_upper_bound_start (n : ℕ) {a} (h : (2 : ℝ) - ((a - 1 / (4 : ℝ) ^ n) / (2 : ℝ) ^ (n + 1)) ^ 2 ≤ sqrtTwoAddSeries ((0 : ℕ) / (1 : ℕ)) n) (h₂ : (1 : ℝ) / (4 : ℝ) ^ n ≤ a) : π < a := by refine lt_of_lt_of_le (pi_lt_sqrtTwoAddSeries n) ?_ rw [← le_sub_iff_add_le, ← le_div_iff', sqrt_le_left, sub_le_comm] · rwa [Nat.cast_zero, zero_div] at h · exact div_nonneg (sub_nonneg.2 h₂) (pow_nonneg (le_of_lt zero_lt_two) _) · exact pow_pos zero_lt_two _ theorem sqrtTwoAddSeries_step_down (a b : ℕ) {c d n : ℕ} {z : ℝ} (hz : z ≤ sqrtTwoAddSeries (a / b) n) (hb : 0 < b) (hd : 0 < d) (h : a ^ 2 * d ≤ (2 * d + c) * b ^ 2) : z ≤ sqrtTwoAddSeries (c / d) (n + 1) := by apply le_trans hz; rw [sqrtTwoAddSeries_succ]; apply sqrtTwoAddSeries_monotone_left apply le_sqrt_of_sq_le have hb' : 0 < (b : ℝ) := Nat.cast_pos.2 hb have hd' : 0 < (d : ℝ) := Nat.cast_pos.2 hd rw [div_pow, add_div_eq_mul_add_div _ _ (ne_of_gt hd'), div_le_div_iff (pow_pos hb' _) hd'] exact mod_cast h section Tactic open Lean Elab Tactic /-- Create a proof of `π < a` for a fixed rational number `a`, given a witness, which is a sequence of rational numbers `√2 < r 1 < r 2 < ... < r n < 2` satisfying the property that `√(2 + r i) ≥ r(i+1)`, where `r 0 = 0` and `√(2 - r n) ≥ (a - 1/4^n) / 2^(n+1)`. -/ elab "pi_upper_bound " "[" l:term,* "]" : tactic => do let rat_sep := l.elemsAndSeps let sep := rat_sep.getD 1 .missing let ratStx := rat_sep.filter (· != sep) let n := ← (toExpr ratStx.size).toSyntax let els := (ratStx.map numDen).reduceOption evalTactic (← `(tactic| apply pi_upper_bound_start $n)) let _ := ← els.mapM fun (x, y) => do evalTactic (← `(tactic| apply sqrtTwoAddSeries_step_down $x $y)) evalTactic (← `(tactic| simp [sqrtTwoAddSeries])) allGoals (evalTactic (← `(tactic| norm_num1))) end Tactic theorem pi_gt_three : 3 < π := by pi_lower_bound [23/16] theorem pi_gt_314 : 3.14 < π := by pi_lower_bound [99 / 70, 874 / 473, 1940 / 989, 1447 / 727] theorem pi_lt_315 : π < 3.15 := by pi_upper_bound [140 / 99, 279 / 151, 51 / 26, 412 / 207] theorem pi_gt_31415 : 3.1415 < π := by pi_lower_bound [11482 / 8119, 5401 / 2923, 2348 / 1197, 11367 / 5711, 25705 / 12868, 23235 / 11621] theorem pi_lt_31416 : π < 3.1416 := by pi_upper_bound [4756 / 3363, 101211 / 54775, 505534 / 257719, 83289 / 41846, 411278 / 205887, 438142 / 219137, 451504 / 225769, 265603 / 132804, 849938 / 424971] theorem pi_gt_3141592 : 3.141592 < π := by pi_lower_bound [11482 / 8119, 7792 / 4217, 54055 / 27557, 949247 / 476920, 3310126 / 1657059, 2635492 / 1318143, 1580265 / 790192, 1221775 / 610899, 3612247 / 1806132, 849943 / 424972] theorem pi_lt_3141593 : π < 3.141593 := by pi_upper_bound [27720 / 19601, 56935 / 30813, 49359 / 25163, 258754 / 130003, 113599 / 56868, 1101994 / 551163, 8671537 / 4336095, 3877807 / 1938940, 52483813 / 26242030, 56946167 / 28473117, 23798415 / 11899211] end Real
Data\Real\Pi\Leibniz.lean
/- Copyright (c) 2020 Benjamin Davidson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Benjamin Davidson, Jeremy Tan -/ import Mathlib.Analysis.Complex.AbelLimit import Mathlib.Analysis.SpecialFunctions.Complex.Arctan /-! ### Leibniz's series for `π` -/ namespace Real open Filter Finset open scoped Topology /-- **Leibniz's series for `π`**. The alternating sum of odd number reciprocals is `π / 4`, proved by using Abel's limit theorem to extend the Maclaurin series of `arctan` to 1. -/ theorem tendsto_sum_pi_div_four : Tendsto (fun k => ∑ i ∈ range k, (-1 : ℝ) ^ i / (2 * i + 1)) atTop (𝓝 (π / 4)) := by -- The series is alternating with terms of decreasing magnitude, so it converges to some limit obtain ⟨l, h⟩ : ∃ l, Tendsto (fun n ↦ ∑ i ∈ range n, (-1 : ℝ) ^ i / (2 * i + 1)) atTop (𝓝 l) := by apply Antitone.tendsto_alternating_series_of_tendsto_zero · exact antitone_iff_forall_lt.mpr fun _ _ _ ↦ by gcongr · apply Tendsto.inv_tendsto_atTop; apply tendsto_atTop_add_const_right exact tendsto_natCast_atTop_atTop.const_mul_atTop zero_lt_two -- Abel's limit theorem states that the corresponding power series has the same limit as `x → 1⁻` have abel := tendsto_tsum_powerSeries_nhdsWithin_lt h -- Massage the expression to get `x ^ (2 * n + 1)` in the tsum rather than `x ^ n`... have m : 𝓝[<] (1 : ℝ) ≤ 𝓝 1 := tendsto_nhdsWithin_of_tendsto_nhds fun _ a ↦ a have q : Tendsto (fun x : ℝ ↦ x ^ 2) (𝓝[<] 1) (𝓝[<] 1) := by apply tendsto_nhdsWithin_of_tendsto_nhds_of_eventually_within · nth_rw 3 [← one_pow 2] exact Tendsto.pow ‹_› _ · rw [eventually_iff_exists_mem] use Set.Ioo (-1) 1 exact ⟨(by rw [mem_nhdsWithin_Iio_iff_exists_Ioo_subset]; use -1, by simp), fun _ _ ↦ by rwa [Set.mem_Iio, sq_lt_one_iff_abs_lt_one, abs_lt, ← Set.mem_Ioo]⟩ replace abel := (abel.comp q).mul m rw [mul_one] at abel -- ...so that we can replace the tsum with the real arctangent function replace abel : Tendsto arctan (𝓝[<] 1) (𝓝 l) := by apply abel.congr' rw [eventuallyEq_nhdsWithin_iff, Metric.eventually_nhds_iff] use 1, zero_lt_one intro y hy1 hy2 rw [dist_eq, abs_sub_lt_iff] at hy1 rw [Set.mem_Iio] at hy2 have ny : ‖y‖ < 1 := by rw [norm_eq_abs, abs_lt]; constructor <;> linarith rw [← (hasSum_arctan ny).tsum_eq, Function.comp_apply, ← tsum_mul_right] simp_rw [mul_assoc, ← pow_mul, ← pow_succ, div_mul_eq_mul_div] norm_cast -- But `arctan` is continuous everywhere, so the limit is `arctan 1 = π / 4` rwa [tendsto_nhds_unique abel ((continuous_arctan.tendsto 1).mono_left m), arctan_one] at h end Real
Data\Real\Pi\Wallis.lean
/- Copyright (c) 2021 Hanting Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Hanting Zhang -/ import Mathlib.Analysis.SpecialFunctions.Integrals /-! # The Wallis formula for Pi This file establishes the Wallis product for `π` (`Real.tendsto_prod_pi_div_two`). Our proof is largely about analyzing the behaviour of the sequence `∫ x in 0..π, sin x ^ n` as `n → ∞`. See: https://en.wikipedia.org/wiki/Wallis_product The proof can be broken down into two pieces. The first step (carried out in `Analysis.SpecialFunctions.Integrals`) is to use repeated integration by parts to obtain an explicit formula for this integral, which is rational if `n` is odd and a rational multiple of `π` if `n` is even. The second step, carried out here, is to estimate the ratio `∫ (x : ℝ) in 0..π, sin x ^ (2 * k + 1) / ∫ (x : ℝ) in 0..π, sin x ^ (2 * k)` and prove that it converges to one using the squeeze theorem. The final product for `π` is obtained after some algebraic manipulation. ## Main statements * `Real.Wallis.W`: the product of the first `k` terms in Wallis' formula for `π`. * `Real.Wallis.W_eq_integral_sin_pow_div_integral_sin_pow`: express `W n` as a ratio of integrals. * `Real.Wallis.W_le` and `Real.Wallis.le_W`: upper and lower bounds for `W n`. * `Real.tendsto_prod_pi_div_two`: the Wallis product formula. -/ open scoped Real Topology Nat open Filter Finset intervalIntegral namespace Real namespace Wallis /-- The product of the first `k` terms in Wallis' formula for `π`. -/ noncomputable def W (k : ℕ) : ℝ := ∏ i ∈ range k, (2 * i + 2) / (2 * i + 1) * ((2 * i + 2) / (2 * i + 3)) theorem W_succ (k : ℕ) : W (k + 1) = W k * ((2 * k + 2) / (2 * k + 1) * ((2 * k + 2) / (2 * k + 3))) := prod_range_succ _ _ theorem W_pos (k : ℕ) : 0 < W k := by induction' k with k hk · unfold W; simp · rw [W_succ] refine mul_pos hk (mul_pos (div_pos ?_ ?_) (div_pos ?_ ?_)) <;> positivity theorem W_eq_factorial_ratio (n : ℕ) : W n = 2 ^ (4 * n) * n ! ^ 4 / ((2 * n)! ^ 2 * (2 * n + 1)) := by induction' n with n IH · simp only [W, prod_range_zero, Nat.factorial_zero, mul_zero, pow_zero, algebraMap.coe_one, one_pow, mul_one, algebraMap.coe_zero, zero_add, div_self, Ne, one_ne_zero, not_false_iff] norm_num · unfold W at IH ⊢ rw [prod_range_succ, IH, _root_.div_mul_div_comm, _root_.div_mul_div_comm] refine (div_eq_div_iff ?_ ?_).mpr ?_ any_goals exact ne_of_gt (by positivity) simp_rw [Nat.mul_succ, Nat.factorial_succ, pow_succ] push_cast ring_nf theorem W_eq_integral_sin_pow_div_integral_sin_pow (k : ℕ) : (π / 2)⁻¹ * W k = (∫ x : ℝ in (0)..π, sin x ^ (2 * k + 1)) / ∫ x : ℝ in (0)..π, sin x ^ (2 * k) := by rw [integral_sin_pow_even, integral_sin_pow_odd, mul_div_mul_comm, ← prod_div_distrib, inv_div] simp_rw [div_div_div_comm, div_div_eq_mul_div, mul_div_assoc] rfl theorem W_le (k : ℕ) : W k ≤ π / 2 := by rw [← div_le_one pi_div_two_pos, div_eq_inv_mul] rw [W_eq_integral_sin_pow_div_integral_sin_pow, div_le_one (integral_sin_pow_pos _)] apply integral_sin_pow_succ_le theorem le_W (k : ℕ) : ((2 : ℝ) * k + 1) / (2 * k + 2) * (π / 2) ≤ W k := by rw [← le_div_iff pi_div_two_pos, div_eq_inv_mul (W k) _] rw [W_eq_integral_sin_pow_div_integral_sin_pow, le_div_iff (integral_sin_pow_pos _)] convert integral_sin_pow_succ_le (2 * k + 1) rw [integral_sin_pow (2 * k)] simp only [sin_zero, ne_eq, add_eq_zero, and_false, not_false_eq_true, zero_pow, cos_zero, mul_one, sin_pi, cos_pi, mul_neg, neg_zero, sub_self, zero_div, zero_add] norm_cast theorem tendsto_W_nhds_pi_div_two : Tendsto W atTop (𝓝 <| π / 2) := by refine tendsto_of_tendsto_of_tendsto_of_le_of_le ?_ tendsto_const_nhds le_W W_le have : 𝓝 (π / 2) = 𝓝 ((1 - 0) * (π / 2)) := by rw [sub_zero, one_mul] rw [this] refine Tendsto.mul ?_ tendsto_const_nhds have h : ∀ n : ℕ, ((2 : ℝ) * n + 1) / (2 * n + 2) = 1 - 1 / (2 * n + 2) := by intro n rw [sub_div' _ _ _ (ne_of_gt (add_pos_of_nonneg_of_pos (mul_nonneg (two_pos : 0 < (2 : ℝ)).le (Nat.cast_nonneg _)) two_pos)), one_mul] congr 1; ring simp_rw [h] refine (tendsto_const_nhds.div_atTop ?_).const_sub _ refine Tendsto.atTop_add ?_ tendsto_const_nhds exact tendsto_natCast_atTop_atTop.const_mul_atTop two_pos end Wallis end Real /-- Wallis' product formula for `π / 2`. -/ theorem Real.tendsto_prod_pi_div_two : Tendsto (fun k => ∏ i ∈ range k, ((2 : ℝ) * i + 2) / (2 * i + 1) * ((2 * i + 2) / (2 * i + 3))) atTop (𝓝 (π / 2)) := Real.Wallis.tendsto_W_nhds_pi_div_two
Data\Seq\Computation.lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Coinductive formalization of unbounded computations. -/ import Mathlib.Data.Nat.Find import Mathlib.Data.Stream.Init import Mathlib.Tactic.Common /-! # Coinductive formalization of unbounded computations. This file provides a `Computation` type where `Computation α` is the type of unbounded computations returning `α`. -/ open Function universe u v w /- coinductive Computation (α : Type u) : Type u | pure : α → Computation α | think : Computation α → Computation α -/ /-- `Computation α` is the type of unbounded computations returning `α`. An element of `Computation α` is an infinite sequence of `Option α` such that if `f n = some a` for some `n` then it is constantly `some a` after that. -/ def Computation (α : Type u) : Type u := { f : Stream' (Option α) // ∀ ⦃n a⦄, f n = some a → f (n + 1) = some a } namespace Computation variable {α : Type u} {β : Type v} {γ : Type w} -- constructors /-- `pure a` is the computation that immediately terminates with result `a`. -/ -- Porting note: `return` is reserved, so changed to `pure` def pure (a : α) : Computation α := ⟨Stream'.const (some a), fun _ _ => id⟩ instance : CoeTC α (Computation α) := ⟨pure⟩ -- note [use has_coe_t] /-- `think c` is the computation that delays for one "tick" and then performs computation `c`. -/ def think (c : Computation α) : Computation α := ⟨Stream'.cons none c.1, fun n a h => by cases' n with n · contradiction · exact c.2 h⟩ /-- `thinkN c n` is the computation that delays for `n` ticks and then performs computation `c`. -/ def thinkN (c : Computation α) : ℕ → Computation α | 0 => c | n + 1 => think (thinkN c n) -- check for immediate result /-- `head c` is the first step of computation, either `some a` if `c = pure a` or `none` if `c = think c'`. -/ def head (c : Computation α) : Option α := c.1.head -- one step of computation /-- `tail c` is the remainder of computation, either `c` if `c = pure a` or `c'` if `c = think c'`. -/ def tail (c : Computation α) : Computation α := ⟨c.1.tail, fun _ _ h => c.2 h⟩ /-- `empty α` is the computation that never returns, an infinite sequence of `think`s. -/ def empty (α) : Computation α := ⟨Stream'.const none, fun _ _ => id⟩ instance : Inhabited (Computation α) := ⟨empty _⟩ /-- `runFor c n` evaluates `c` for `n` steps and returns the result, or `none` if it did not terminate after `n` steps. -/ def runFor : Computation α → ℕ → Option α := Subtype.val /-- `destruct c` is the destructor for `Computation α` as a coinductive type. It returns `inl a` if `c = pure a` and `inr c'` if `c = think c'`. -/ def destruct (c : Computation α) : α ⊕ (Computation α) := match c.1 0 with | none => Sum.inr (tail c) | some a => Sum.inl a /-- `run c` is an unsound meta function that runs `c` to completion, possibly resulting in an infinite loop in the VM. -/ unsafe def run : Computation α → α | c => match destruct c with | Sum.inl a => a | Sum.inr ca => run ca theorem destruct_eq_pure {s : Computation α} {a : α} : destruct s = Sum.inl a → s = pure a := by dsimp [destruct] induction' f0 : s.1 0 with _ <;> intro h · contradiction · apply Subtype.eq funext n induction' n with n IH · injection h with h' rwa [h'] at f0 · exact s.2 IH theorem destruct_eq_think {s : Computation α} {s'} : destruct s = Sum.inr s' → s = think s' := by dsimp [destruct] induction' f0 : s.1 0 with a' <;> intro h · injection h with h' rw [← h'] cases' s with f al apply Subtype.eq dsimp [think, tail] rw [← f0] exact (Stream'.eta f).symm · contradiction @[simp] theorem destruct_pure (a : α) : destruct (pure a) = Sum.inl a := rfl @[simp] theorem destruct_think : ∀ s : Computation α, destruct (think s) = Sum.inr s | ⟨_, _⟩ => rfl @[simp] theorem destruct_empty : destruct (empty α) = Sum.inr (empty α) := rfl @[simp] theorem head_pure (a : α) : head (pure a) = some a := rfl @[simp] theorem head_think (s : Computation α) : head (think s) = none := rfl @[simp] theorem head_empty : head (empty α) = none := rfl @[simp] theorem tail_pure (a : α) : tail (pure a) = pure a := rfl @[simp] theorem tail_think (s : Computation α) : tail (think s) = s := by cases' s with f al; apply Subtype.eq; dsimp [tail, think] @[simp] theorem tail_empty : tail (empty α) = empty α := rfl theorem think_empty : empty α = think (empty α) := destruct_eq_think destruct_empty /-- Recursion principle for computations, compare with `List.recOn`. -/ def recOn {C : Computation α → Sort v} (s : Computation α) (h1 : ∀ a, C (pure a)) (h2 : ∀ s, C (think s)) : C s := match H : destruct s with | Sum.inl v => by rw [destruct_eq_pure H] apply h1 | Sum.inr v => match v with | ⟨a, s'⟩ => by rw [destruct_eq_think H] apply h2 /-- Corecursor constructor for `corec`-/ def Corec.f (f : β → α ⊕ β) : α ⊕ β → Option α × (α ⊕ β) | Sum.inl a => (some a, Sum.inl a) | Sum.inr b => (match f b with | Sum.inl a => some a | Sum.inr _ => none, f b) /-- `corec f b` is the corecursor for `Computation α` as a coinductive type. If `f b = inl a` then `corec f b = pure a`, and if `f b = inl b'` then `corec f b = think (corec f b')`. -/ def corec (f : β → α ⊕ β) (b : β) : Computation α := by refine ⟨Stream'.corec' (Corec.f f) (Sum.inr b), fun n a' h => ?_⟩ rw [Stream'.corec'_eq] change Stream'.corec' (Corec.f f) (Corec.f f (Sum.inr b)).2 n = some a' revert h; generalize Sum.inr b = o; revert o induction' n with n IH <;> intro o · change (Corec.f f o).1 = some a' → (Corec.f f (Corec.f f o).2).1 = some a' cases' o with _ b <;> intro h · exact h unfold Corec.f at *; split <;> simp_all · rw [Stream'.corec'_eq (Corec.f f) (Corec.f f o).2, Stream'.corec'_eq (Corec.f f) o] exact IH (Corec.f f o).2 /-- left map of `⊕` -/ def lmap (f : α → β) : α ⊕ γ → β ⊕ γ | Sum.inl a => Sum.inl (f a) | Sum.inr b => Sum.inr b /-- right map of `⊕` -/ def rmap (f : β → γ) : α ⊕ β → α ⊕ γ | Sum.inl a => Sum.inl a | Sum.inr b => Sum.inr (f b) attribute [simp] lmap rmap -- Porting note: this was far less painful in mathlib3. There seem to be two issues; -- firstly, in mathlib3 we have `corec.F._match_1` and it's the obvious map α ⊕ β → option α. -- In mathlib4 we have `Corec.f.match_1` and it's something completely different. -- Secondly, the proof that `Stream'.corec' (Corec.f f) (Sum.inr b) 0` is this function -- evaluated at `f b`, used to be `rfl` and now is `cases, rfl`. @[simp] theorem corec_eq (f : β → α ⊕ β) (b : β) : destruct (corec f b) = rmap (corec f) (f b) := by dsimp [corec, destruct] rw [show Stream'.corec' (Corec.f f) (Sum.inr b) 0 = Sum.rec Option.some (fun _ ↦ none) (f b) by dsimp [Corec.f, Stream'.corec', Stream'.corec, Stream'.map, Stream'.get, Stream'.iterate] match (f b) with | Sum.inl x => rfl | Sum.inr x => rfl ] induction' h : f b with a b'; · rfl dsimp [Corec.f, destruct] apply congr_arg; apply Subtype.eq dsimp [corec, tail] rw [Stream'.corec'_eq, Stream'.tail_cons] dsimp [Corec.f]; rw [h] section Bisim variable (R : Computation α → Computation α → Prop) /-- bisimilarity relation-/ local infixl:50 " ~ " => R /-- Bisimilarity over a sum of `Computation`s-/ def BisimO : α ⊕ (Computation α) → α ⊕ (Computation α) → Prop | Sum.inl a, Sum.inl a' => a = a' | Sum.inr s, Sum.inr s' => R s s' | _, _ => False attribute [simp] BisimO /-- Attribute expressing bisimilarity over two `Computation`s-/ def IsBisimulation := ∀ ⦃s₁ s₂⦄, s₁ ~ s₂ → BisimO R (destruct s₁) (destruct s₂) -- If two computations are bisimilar, then they are equal theorem eq_of_bisim (bisim : IsBisimulation R) {s₁ s₂} (r : s₁ ~ s₂) : s₁ = s₂ := by apply Subtype.eq apply Stream'.eq_of_bisim fun x y => ∃ s s' : Computation α, s.1 = x ∧ s'.1 = y ∧ R s s' · dsimp [Stream'.IsBisimulation] intro t₁ t₂ e match t₁, t₂, e with | _, _, ⟨s, s', rfl, rfl, r⟩ => suffices head s = head s' ∧ R (tail s) (tail s') from And.imp id (fun r => ⟨tail s, tail s', by cases s; rfl, by cases s'; rfl, r⟩) this have h := bisim r; revert r h apply recOn s _ _ <;> intro r' <;> apply recOn s' _ _ <;> intro a' r h · constructor <;> dsimp at h · rw [h] · rw [h] at r rw [tail_pure, tail_pure,h] assumption · rw [destruct_pure, destruct_think] at h exact False.elim h · rw [destruct_pure, destruct_think] at h exact False.elim h · simp_all · exact ⟨s₁, s₂, rfl, rfl, r⟩ end Bisim -- It's more of a stretch to use ∈ for this relation, but it -- asserts that the computation limits to the given value. /-- Assertion that a `Computation` limits to a given value-/ protected def Mem (a : α) (s : Computation α) := some a ∈ s.1 instance : Membership α (Computation α) := ⟨Computation.Mem⟩ theorem le_stable (s : Computation α) {a m n} (h : m ≤ n) : s.1 m = some a → s.1 n = some a := by cases' s with f al induction' h with n _ IH exacts [id, fun h2 => al (IH h2)] theorem mem_unique {s : Computation α} {a b : α} : a ∈ s → b ∈ s → a = b | ⟨m, ha⟩, ⟨n, hb⟩ => by injection (le_stable s (le_max_left m n) ha.symm).symm.trans (le_stable s (le_max_right m n) hb.symm) theorem Mem.left_unique : Relator.LeftUnique ((· ∈ ·) : α → Computation α → Prop) := fun _ _ _ => mem_unique /-- `Terminates s` asserts that the computation `s` eventually terminates with some value. -/ class Terminates (s : Computation α) : Prop where /-- assertion that there is some term `a` such that the `Computation` terminates -/ term : ∃ a, a ∈ s theorem terminates_iff (s : Computation α) : Terminates s ↔ ∃ a, a ∈ s := ⟨fun h => h.1, Terminates.mk⟩ theorem terminates_of_mem {s : Computation α} {a : α} (h : a ∈ s) : Terminates s := ⟨⟨a, h⟩⟩ theorem terminates_def (s : Computation α) : Terminates s ↔ ∃ n, (s.1 n).isSome := ⟨fun ⟨⟨a, n, h⟩⟩ => ⟨n, by dsimp [Stream'.get] at h rw [← h] exact rfl⟩, fun ⟨n, h⟩ => ⟨⟨Option.get _ h, n, (Option.eq_some_of_isSome h).symm⟩⟩⟩ theorem ret_mem (a : α) : a ∈ pure a := Exists.intro 0 rfl theorem eq_of_pure_mem {a a' : α} (h : a' ∈ pure a) : a' = a := mem_unique h (ret_mem _) instance ret_terminates (a : α) : Terminates (pure a) := terminates_of_mem (ret_mem _) theorem think_mem {s : Computation α} {a} : a ∈ s → a ∈ think s | ⟨n, h⟩ => ⟨n + 1, h⟩ instance think_terminates (s : Computation α) : ∀ [Terminates s], Terminates (think s) | ⟨⟨a, n, h⟩⟩ => ⟨⟨a, n + 1, h⟩⟩ theorem of_think_mem {s : Computation α} {a} : a ∈ think s → a ∈ s | ⟨n, h⟩ => by cases' n with n' · contradiction · exact ⟨n', h⟩ theorem of_think_terminates {s : Computation α} : Terminates (think s) → Terminates s | ⟨⟨a, h⟩⟩ => ⟨⟨a, of_think_mem h⟩⟩ theorem not_mem_empty (a : α) : a ∉ empty α := fun ⟨n, h⟩ => by contradiction theorem not_terminates_empty : ¬Terminates (empty α) := fun ⟨⟨a, h⟩⟩ => not_mem_empty a h theorem eq_empty_of_not_terminates {s} (H : ¬Terminates s) : s = empty α := by apply Subtype.eq; funext n induction' h : s.val n with _; · rfl refine absurd ?_ H; exact ⟨⟨_, _, h.symm⟩⟩ theorem thinkN_mem {s : Computation α} {a} : ∀ n, a ∈ thinkN s n ↔ a ∈ s | 0 => Iff.rfl | n + 1 => Iff.trans ⟨of_think_mem, think_mem⟩ (thinkN_mem n) instance thinkN_terminates (s : Computation α) : ∀ [Terminates s] (n), Terminates (thinkN s n) | ⟨⟨a, h⟩⟩, n => ⟨⟨a, (thinkN_mem n).2 h⟩⟩ theorem of_thinkN_terminates (s : Computation α) (n) : Terminates (thinkN s n) → Terminates s | ⟨⟨a, h⟩⟩ => ⟨⟨a, (thinkN_mem _).1 h⟩⟩ /-- `Promises s a`, or `s ~> a`, asserts that although the computation `s` may not terminate, if it does, then the result is `a`. -/ def Promises (s : Computation α) (a : α) : Prop := ∀ ⦃a'⦄, a' ∈ s → a = a' /-- `Promises s a`, or `s ~> a`, asserts that although the computation `s` may not terminate, if it does, then the result is `a`. -/ scoped infixl:50 " ~> " => Promises theorem mem_promises {s : Computation α} {a : α} : a ∈ s → s ~> a := fun h _ => mem_unique h theorem empty_promises (a : α) : empty α ~> a := fun _ h => absurd h (not_mem_empty _) section get variable (s : Computation α) [h : Terminates s] /-- `length s` gets the number of steps of a terminating computation -/ def length : ℕ := Nat.find ((terminates_def _).1 h) /-- `get s` returns the result of a terminating computation -/ def get : α := Option.get _ (Nat.find_spec <| (terminates_def _).1 h) theorem get_mem : get s ∈ s := Exists.intro (length s) (Option.eq_some_of_isSome _).symm theorem get_eq_of_mem {a} : a ∈ s → get s = a := mem_unique (get_mem _) theorem mem_of_get_eq {a} : get s = a → a ∈ s := by intro h; rw [← h]; apply get_mem @[simp] theorem get_think : get (think s) = get s := get_eq_of_mem _ <| let ⟨n, h⟩ := get_mem s ⟨n + 1, h⟩ @[simp] theorem get_thinkN (n) : get (thinkN s n) = get s := get_eq_of_mem _ <| (thinkN_mem _).2 (get_mem _) theorem get_promises : s ~> get s := fun _ => get_eq_of_mem _ theorem mem_of_promises {a} (p : s ~> a) : a ∈ s := by cases' h with h cases' h with a' h rw [p h] exact h theorem get_eq_of_promises {a} : s ~> a → get s = a := get_eq_of_mem _ ∘ mem_of_promises _ end get /-- `Results s a n` completely characterizes a terminating computation: it asserts that `s` terminates after exactly `n` steps, with result `a`. -/ def Results (s : Computation α) (a : α) (n : ℕ) := ∃ h : a ∈ s, @length _ s (terminates_of_mem h) = n theorem results_of_terminates (s : Computation α) [_T : Terminates s] : Results s (get s) (length s) := ⟨get_mem _, rfl⟩ theorem results_of_terminates' (s : Computation α) [T : Terminates s] {a} (h : a ∈ s) : Results s a (length s) := by rw [← get_eq_of_mem _ h]; apply results_of_terminates theorem Results.mem {s : Computation α} {a n} : Results s a n → a ∈ s | ⟨m, _⟩ => m theorem Results.terminates {s : Computation α} {a n} (h : Results s a n) : Terminates s := terminates_of_mem h.mem theorem Results.length {s : Computation α} {a n} [_T : Terminates s] : Results s a n → length s = n | ⟨_, h⟩ => h theorem Results.val_unique {s : Computation α} {a b m n} (h1 : Results s a m) (h2 : Results s b n) : a = b := mem_unique h1.mem h2.mem theorem Results.len_unique {s : Computation α} {a b m n} (h1 : Results s a m) (h2 : Results s b n) : m = n := by haveI := h1.terminates; haveI := h2.terminates; rw [← h1.length, h2.length] theorem exists_results_of_mem {s : Computation α} {a} (h : a ∈ s) : ∃ n, Results s a n := haveI := terminates_of_mem h ⟨_, results_of_terminates' s h⟩ @[simp] theorem get_pure (a : α) : get (pure a) = a := get_eq_of_mem _ ⟨0, rfl⟩ @[simp] theorem length_pure (a : α) : length (pure a) = 0 := let h := Computation.ret_terminates a Nat.eq_zero_of_le_zero <| Nat.find_min' ((terminates_def (pure a)).1 h) rfl theorem results_pure (a : α) : Results (pure a) a 0 := ⟨ret_mem a, length_pure _⟩ @[simp] theorem length_think (s : Computation α) [h : Terminates s] : length (think s) = length s + 1 := by apply le_antisymm · exact Nat.find_min' _ (Nat.find_spec ((terminates_def _).1 h)) · have : (Option.isSome ((think s).val (length (think s))) : Prop) := Nat.find_spec ((terminates_def _).1 s.think_terminates) revert this; cases' length (think s) with n <;> intro this · simp [think, Stream'.cons] at this · apply Nat.succ_le_succ apply Nat.find_min' apply this theorem results_think {s : Computation α} {a n} (h : Results s a n) : Results (think s) a (n + 1) := haveI := h.terminates ⟨think_mem h.mem, by rw [length_think, h.length]⟩ theorem of_results_think {s : Computation α} {a n} (h : Results (think s) a n) : ∃ m, Results s a m ∧ n = m + 1 := by haveI := of_think_terminates h.terminates have := results_of_terminates' _ (of_think_mem h.mem) exact ⟨_, this, Results.len_unique h (results_think this)⟩ @[simp] theorem results_think_iff {s : Computation α} {a n} : Results (think s) a (n + 1) ↔ Results s a n := ⟨fun h => by let ⟨n', r, e⟩ := of_results_think h injection e with h'; rwa [h'], results_think⟩ theorem results_thinkN {s : Computation α} {a m} : ∀ n, Results s a m → Results (thinkN s n) a (m + n) | 0, h => h | n + 1, h => results_think (results_thinkN n h) theorem results_thinkN_pure (a : α) (n) : Results (thinkN (pure a) n) a n := by have := results_thinkN n (results_pure a); rwa [Nat.zero_add] at this @[simp] theorem length_thinkN (s : Computation α) [_h : Terminates s] (n) : length (thinkN s n) = length s + n := (results_thinkN n (results_of_terminates _)).length theorem eq_thinkN {s : Computation α} {a n} (h : Results s a n) : s = thinkN (pure a) n := by revert s induction' n with n IH <;> intro s <;> apply recOn s (fun a' => _) fun s => _ <;> intro a h · rw [← eq_of_pure_mem h.mem] rfl · cases' of_results_think h with n h cases h contradiction · have := h.len_unique (results_pure _) contradiction · rw [IH (results_think_iff.1 h)] rfl theorem eq_thinkN' (s : Computation α) [_h : Terminates s] : s = thinkN (pure (get s)) (length s) := eq_thinkN (results_of_terminates _) /-- Recursor based on membership-/ def memRecOn {C : Computation α → Sort v} {a s} (M : a ∈ s) (h1 : C (pure a)) (h2 : ∀ s, C s → C (think s)) : C s := by haveI T := terminates_of_mem M rw [eq_thinkN' s, get_eq_of_mem s M] generalize length s = n induction' n with n IH; exacts [h1, h2 _ IH] /-- Recursor based on assertion of `Terminates`-/ def terminatesRecOn {C : Computation α → Sort v} (s) [Terminates s] (h1 : ∀ a, C (pure a)) (h2 : ∀ s, C s → C (think s)) : C s := memRecOn (get_mem s) (h1 _) h2 /-- Map a function on the result of a computation. -/ def map (f : α → β) : Computation α → Computation β | ⟨s, al⟩ => ⟨s.map fun o => Option.casesOn o none (some ∘ f), fun n b => by dsimp [Stream'.map, Stream'.get] induction' e : s n with a <;> intro h · contradiction · rw [al e]; exact h⟩ /-- bind over a `Sum` of `Computation`-/ def Bind.g : β ⊕ Computation β → β ⊕ (Computation α ⊕ Computation β) | Sum.inl b => Sum.inl b | Sum.inr cb' => Sum.inr <| Sum.inr cb' /-- bind over a function mapping `α` to a `Computation`-/ def Bind.f (f : α → Computation β) : Computation α ⊕ Computation β → β ⊕ (Computation α ⊕ Computation β) | Sum.inl ca => match destruct ca with | Sum.inl a => Bind.g <| destruct (f a) | Sum.inr ca' => Sum.inr <| Sum.inl ca' | Sum.inr cb => Bind.g <| destruct cb /-- Compose two computations into a monadic `bind` operation. -/ def bind (c : Computation α) (f : α → Computation β) : Computation β := corec (Bind.f f) (Sum.inl c) instance : Bind Computation := ⟨@bind⟩ theorem has_bind_eq_bind {β} (c : Computation α) (f : α → Computation β) : c >>= f = bind c f := rfl /-- Flatten a computation of computations into a single computation. -/ def join (c : Computation (Computation α)) : Computation α := c >>= id @[simp] theorem map_pure (f : α → β) (a) : map f (pure a) = pure (f a) := rfl @[simp] theorem map_think (f : α → β) : ∀ s, map f (think s) = think (map f s) | ⟨s, al⟩ => by apply Subtype.eq; dsimp [think, map]; rw [Stream'.map_cons] @[simp] theorem destruct_map (f : α → β) (s) : destruct (map f s) = lmap f (rmap (map f) (destruct s)) := by apply s.recOn <;> intro <;> simp @[simp] theorem map_id : ∀ s : Computation α, map id s = s | ⟨f, al⟩ => by apply Subtype.eq; simp only [map, comp_apply, id_eq] have e : @Option.rec α (fun _ => Option α) none some = id := by ext ⟨⟩ <;> rfl have h : ((fun x : Option α => x) = id) := rfl simp [e, h, Stream'.map_id] theorem map_comp (f : α → β) (g : β → γ) : ∀ s : Computation α, map (g ∘ f) s = map g (map f s) | ⟨s, al⟩ => by apply Subtype.eq; dsimp [map] apply congr_arg fun f : _ → Option γ => Stream'.map f s ext ⟨⟩ <;> rfl @[simp] theorem ret_bind (a) (f : α → Computation β) : bind (pure a) f = f a := by apply eq_of_bisim fun c₁ c₂ => c₁ = bind (pure a) f ∧ c₂ = f a ∨ c₁ = corec (Bind.f f) (Sum.inr c₂) · intro c₁ c₂ h match c₁, c₂, h with | _, _, Or.inl ⟨rfl, rfl⟩ => simp only [BisimO, bind, Bind.f, corec_eq, rmap, destruct_pure] cases' destruct (f a) with b cb <;> simp [Bind.g] | _, c, Or.inr rfl => simp only [BisimO, Bind.f, corec_eq, rmap] cases' destruct c with b cb <;> simp [Bind.g] · simp @[simp] theorem think_bind (c) (f : α → Computation β) : bind (think c) f = think (bind c f) := destruct_eq_think <| by simp [bind, Bind.f] @[simp] theorem bind_pure (f : α → β) (s) : bind s (pure ∘ f) = map f s := by apply eq_of_bisim fun c₁ c₂ => c₁ = c₂ ∨ ∃ s, c₁ = bind s (pure ∘ f) ∧ c₂ = map f s · intro c₁ c₂ h match c₁, c₂, h with | _, c₂, Or.inl (Eq.refl _) => cases' destruct c₂ with b cb <;> simp | _, _, Or.inr ⟨s, rfl, rfl⟩ => apply recOn s <;> intro s · simp · simpa using Or.inr ⟨s, rfl, rfl⟩ · exact Or.inr ⟨s, rfl, rfl⟩ -- Porting note: used to use `rw [bind_pure]` @[simp] theorem bind_pure' (s : Computation α) : bind s pure = s := by apply eq_of_bisim fun c₁ c₂ => c₁ = c₂ ∨ ∃ s, c₁ = bind s pure ∧ c₂ = s · intro c₁ c₂ h match c₁, c₂, h with | _, c₂, Or.inl (Eq.refl _) => cases' destruct c₂ with b cb <;> simp | _, _, Or.inr ⟨s, rfl, rfl⟩ => apply recOn s <;> intro s <;> simp · exact Or.inr ⟨s, rfl, rfl⟩ @[simp] theorem bind_assoc (s : Computation α) (f : α → Computation β) (g : β → Computation γ) : bind (bind s f) g = bind s fun x : α => bind (f x) g := by apply eq_of_bisim fun c₁ c₂ => c₁ = c₂ ∨ ∃ s, c₁ = bind (bind s f) g ∧ c₂ = bind s fun x : α => bind (f x) g · intro c₁ c₂ h match c₁, c₂, h with | _, c₂, Or.inl (Eq.refl _) => cases' destruct c₂ with b cb <;> simp | _, _, Or.inr ⟨s, rfl, rfl⟩ => apply recOn s <;> intro s · simp only [BisimO, ret_bind]; generalize f s = fs apply recOn fs <;> intro t <;> simp · cases' destruct (g t) with b cb <;> simp · simpa [BisimO] using Or.inr ⟨s, rfl, rfl⟩ · exact Or.inr ⟨s, rfl, rfl⟩ theorem results_bind {s : Computation α} {f : α → Computation β} {a b m n} (h1 : Results s a m) (h2 : Results (f a) b n) : Results (bind s f) b (n + m) := by have := h1.mem; revert m apply memRecOn this _ fun s IH => _ · intro _ h1 rw [ret_bind] rw [h1.len_unique (results_pure _)] exact h2 · intro _ h3 _ h1 rw [think_bind] cases' of_results_think h1 with m' h cases' h with h1 e rw [e] exact results_think (h3 h1) theorem mem_bind {s : Computation α} {f : α → Computation β} {a b} (h1 : a ∈ s) (h2 : b ∈ f a) : b ∈ bind s f := let ⟨_, h1⟩ := exists_results_of_mem h1 let ⟨_, h2⟩ := exists_results_of_mem h2 (results_bind h1 h2).mem instance terminates_bind (s : Computation α) (f : α → Computation β) [Terminates s] [Terminates (f (get s))] : Terminates (bind s f) := terminates_of_mem (mem_bind (get_mem s) (get_mem (f (get s)))) @[simp] theorem get_bind (s : Computation α) (f : α → Computation β) [Terminates s] [Terminates (f (get s))] : get (bind s f) = get (f (get s)) := get_eq_of_mem _ (mem_bind (get_mem s) (get_mem (f (get s)))) @[simp] theorem length_bind (s : Computation α) (f : α → Computation β) [_T1 : Terminates s] [_T2 : Terminates (f (get s))] : length (bind s f) = length (f (get s)) + length s := (results_of_terminates _).len_unique <| results_bind (results_of_terminates _) (results_of_terminates _) theorem of_results_bind {s : Computation α} {f : α → Computation β} {b k} : Results (bind s f) b k → ∃ a m n, Results s a m ∧ Results (f a) b n ∧ k = n + m := by induction' k with n IH generalizing s <;> apply recOn s (fun a => _) fun s' => _ <;> intro e h · simp only [ret_bind, Nat.zero_eq] at h exact ⟨e, _, _, results_pure _, h, rfl⟩ · have := congr_arg head (eq_thinkN h) contradiction · simp only [ret_bind] at h exact ⟨e, _, n + 1, results_pure _, h, rfl⟩ · simp only [think_bind, results_think_iff] at h let ⟨a, m, n', h1, h2, e'⟩ := IH h rw [e'] exact ⟨a, m.succ, n', results_think h1, h2, rfl⟩ theorem exists_of_mem_bind {s : Computation α} {f : α → Computation β} {b} (h : b ∈ bind s f) : ∃ a ∈ s, b ∈ f a := let ⟨_, h⟩ := exists_results_of_mem h let ⟨a, _, _, h1, h2, _⟩ := of_results_bind h ⟨a, h1.mem, h2.mem⟩ theorem bind_promises {s : Computation α} {f : α → Computation β} {a b} (h1 : s ~> a) (h2 : f a ~> b) : bind s f ~> b := fun b' bB => by rcases exists_of_mem_bind bB with ⟨a', a's, ba'⟩ rw [← h1 a's] at ba'; exact h2 ba' instance monad : Monad Computation where map := @map pure := @pure bind := @bind instance : LawfulMonad Computation := LawfulMonad.mk' (id_map := @map_id) (bind_pure_comp := @bind_pure) (pure_bind := @ret_bind) (bind_assoc := @bind_assoc) theorem has_map_eq_map {β} (f : α → β) (c : Computation α) : f <$> c = map f c := rfl @[simp] theorem pure_def (a) : (return a : Computation α) = pure a := rfl @[simp] theorem map_pure' {α β} : ∀ (f : α → β) (a), f <$> pure a = pure (f a) := map_pure @[simp] theorem map_think' {α β} : ∀ (f : α → β) (s), f <$> think s = think (f <$> s) := map_think theorem mem_map (f : α → β) {a} {s : Computation α} (m : a ∈ s) : f a ∈ map f s := by rw [← bind_pure]; apply mem_bind m; apply ret_mem theorem exists_of_mem_map {f : α → β} {b : β} {s : Computation α} (h : b ∈ map f s) : ∃ a, a ∈ s ∧ f a = b := by rw [← bind_pure] at h let ⟨a, as, fb⟩ := exists_of_mem_bind h exact ⟨a, as, mem_unique (ret_mem _) fb⟩ instance terminates_map (f : α → β) (s : Computation α) [Terminates s] : Terminates (map f s) := by rw [← bind_pure]; exact terminates_of_mem (mem_bind (get_mem s) (get_mem (f (get s)))) theorem terminates_map_iff (f : α → β) (s : Computation α) : Terminates (map f s) ↔ Terminates s := ⟨fun ⟨⟨_, h⟩⟩ => let ⟨_, h1, _⟩ := exists_of_mem_map h ⟨⟨_, h1⟩⟩, @Computation.terminates_map _ _ _ _⟩ -- Parallel computation /-- `c₁ <|> c₂` calculates `c₁` and `c₂` simultaneously, returning the first one that gives a result. -/ def orElse (c₁ : Computation α) (c₂ : Unit → Computation α) : Computation α := @Computation.corec α (Computation α × Computation α) (fun ⟨c₁, c₂⟩ => match destruct c₁ with | Sum.inl a => Sum.inl a | Sum.inr c₁' => match destruct c₂ with | Sum.inl a => Sum.inl a | Sum.inr c₂' => Sum.inr (c₁', c₂')) (c₁, c₂ ()) instance instAlternativeComputation : Alternative Computation := { Computation.monad with orElse := @orElse failure := @empty } -- Porting note: Added unfolds as the code does not work without it @[simp] theorem ret_orElse (a : α) (c₂ : Computation α) : (pure a <|> c₂) = pure a := destruct_eq_pure <| by unfold_projs simp [orElse] -- Porting note: Added unfolds as the code does not work without it @[simp] theorem orElse_pure (c₁ : Computation α) (a : α) : (think c₁ <|> pure a) = pure a := destruct_eq_pure <| by unfold_projs simp [orElse] -- Porting note: Added unfolds as the code does not work without it @[simp] theorem orElse_think (c₁ c₂ : Computation α) : (think c₁ <|> think c₂) = think (c₁ <|> c₂) := destruct_eq_think <| by unfold_projs simp [orElse] @[simp] theorem empty_orElse (c) : (empty α <|> c) = c := by apply eq_of_bisim (fun c₁ c₂ => (empty α <|> c₂) = c₁) _ rfl intro s' s h; rw [← h] apply recOn s <;> intro s <;> rw [think_empty] <;> simp rw [← think_empty] @[simp] theorem orElse_empty (c : Computation α) : (c <|> empty α) = c := by apply eq_of_bisim (fun c₁ c₂ => (c₂ <|> empty α) = c₁) _ rfl intro s' s h; rw [← h] apply recOn s <;> intro s <;> rw [think_empty] <;> simp rw [← think_empty] /-- `c₁ ~ c₂` asserts that `c₁` and `c₂` either both terminate with the same result, or both loop forever. -/ def Equiv (c₁ c₂ : Computation α) : Prop := ∀ a, a ∈ c₁ ↔ a ∈ c₂ /-- equivalence relation for computations-/ scoped infixl:50 " ~ " => Equiv @[refl] theorem Equiv.refl (s : Computation α) : s ~ s := fun _ => Iff.rfl @[symm] theorem Equiv.symm {s t : Computation α} : s ~ t → t ~ s := fun h a => (h a).symm @[trans] theorem Equiv.trans {s t u : Computation α} : s ~ t → t ~ u → s ~ u := fun h1 h2 a => (h1 a).trans (h2 a) theorem Equiv.equivalence : Equivalence (@Equiv α) := ⟨@Equiv.refl _, @Equiv.symm _, @Equiv.trans _⟩ theorem equiv_of_mem {s t : Computation α} {a} (h1 : a ∈ s) (h2 : a ∈ t) : s ~ t := fun a' => ⟨fun ma => by rw [mem_unique ma h1]; exact h2, fun ma => by rw [mem_unique ma h2]; exact h1⟩ theorem terminates_congr {c₁ c₂ : Computation α} (h : c₁ ~ c₂) : Terminates c₁ ↔ Terminates c₂ := by simp only [terminates_iff, exists_congr h] theorem promises_congr {c₁ c₂ : Computation α} (h : c₁ ~ c₂) (a) : c₁ ~> a ↔ c₂ ~> a := forall_congr' fun a' => imp_congr (h a') Iff.rfl theorem get_equiv {c₁ c₂ : Computation α} (h : c₁ ~ c₂) [Terminates c₁] [Terminates c₂] : get c₁ = get c₂ := get_eq_of_mem _ <| (h _).2 <| get_mem _ theorem think_equiv (s : Computation α) : think s ~ s := fun _ => ⟨of_think_mem, think_mem⟩ theorem thinkN_equiv (s : Computation α) (n) : thinkN s n ~ s := fun _ => thinkN_mem n theorem bind_congr {s1 s2 : Computation α} {f1 f2 : α → Computation β} (h1 : s1 ~ s2) (h2 : ∀ a, f1 a ~ f2 a) : bind s1 f1 ~ bind s2 f2 := fun b => ⟨fun h => let ⟨a, ha, hb⟩ := exists_of_mem_bind h mem_bind ((h1 a).1 ha) ((h2 a b).1 hb), fun h => let ⟨a, ha, hb⟩ := exists_of_mem_bind h mem_bind ((h1 a).2 ha) ((h2 a b).2 hb)⟩ theorem equiv_pure_of_mem {s : Computation α} {a} (h : a ∈ s) : s ~ pure a := equiv_of_mem h (ret_mem _) /-- `LiftRel R ca cb` is a generalization of `Equiv` to relations other than equality. It asserts that if `ca` terminates with `a`, then `cb` terminates with some `b` such that `R a b`, and if `cb` terminates with `b` then `ca` terminates with some `a` such that `R a b`. -/ def LiftRel (R : α → β → Prop) (ca : Computation α) (cb : Computation β) : Prop := (∀ {a}, a ∈ ca → ∃ b, b ∈ cb ∧ R a b) ∧ ∀ {b}, b ∈ cb → ∃ a, a ∈ ca ∧ R a b theorem LiftRel.swap (R : α → β → Prop) (ca : Computation α) (cb : Computation β) : LiftRel (swap R) cb ca ↔ LiftRel R ca cb := @and_comm _ _ theorem lift_eq_iff_equiv (c₁ c₂ : Computation α) : LiftRel (· = ·) c₁ c₂ ↔ c₁ ~ c₂ := ⟨fun ⟨h1, h2⟩ a => ⟨fun a1 => by let ⟨b, b2, ab⟩ := h1 a1; rwa [ab], fun a2 => by let ⟨b, b1, ab⟩ := h2 a2; rwa [← ab]⟩, fun e => ⟨fun {a} a1 => ⟨a, (e _).1 a1, rfl⟩, fun {a} a2 => ⟨a, (e _).2 a2, rfl⟩⟩⟩ theorem LiftRel.refl (R : α → α → Prop) (H : Reflexive R) : Reflexive (LiftRel R) := fun _ => ⟨fun {a} as => ⟨a, as, H a⟩, fun {b} bs => ⟨b, bs, H b⟩⟩ theorem LiftRel.symm (R : α → α → Prop) (H : Symmetric R) : Symmetric (LiftRel R) := fun _ _ ⟨l, r⟩ => ⟨fun {_} a2 => let ⟨b, b1, ab⟩ := r a2 ⟨b, b1, H ab⟩, fun {_} a1 => let ⟨b, b2, ab⟩ := l a1 ⟨b, b2, H ab⟩⟩ theorem LiftRel.trans (R : α → α → Prop) (H : Transitive R) : Transitive (LiftRel R) := fun _ _ _ ⟨l1, r1⟩ ⟨l2, r2⟩ => ⟨fun {_} a1 => let ⟨_, b2, ab⟩ := l1 a1 let ⟨c, c3, bc⟩ := l2 b2 ⟨c, c3, H ab bc⟩, fun {_} c3 => let ⟨_, b2, bc⟩ := r2 c3 let ⟨a, a1, ab⟩ := r1 b2 ⟨a, a1, H ab bc⟩⟩ theorem LiftRel.equiv (R : α → α → Prop) : Equivalence R → Equivalence (LiftRel R) | ⟨refl, symm, trans⟩ => ⟨LiftRel.refl R refl, by apply LiftRel.symm; apply symm, by apply LiftRel.trans; apply trans⟩ -- Porting note: The code above was: -- | ⟨refl, symm, trans⟩ => ⟨LiftRel.refl R refl, LiftRel.symm R symm, LiftRel.trans R trans⟩ -- -- The code fails to identify `symm` as being symmetric. theorem LiftRel.imp {R S : α → β → Prop} (H : ∀ {a b}, R a b → S a b) (s t) : LiftRel R s t → LiftRel S s t | ⟨l, r⟩ => ⟨fun {_} as => let ⟨b, bt, ab⟩ := l as ⟨b, bt, H ab⟩, fun {_} bt => let ⟨a, as, ab⟩ := r bt ⟨a, as, H ab⟩⟩ theorem terminates_of_liftRel {R : α → β → Prop} {s t} : LiftRel R s t → (Terminates s ↔ Terminates t) | ⟨l, r⟩ => ⟨fun ⟨⟨_, as⟩⟩ => let ⟨b, bt, _⟩ := l as ⟨⟨b, bt⟩⟩, fun ⟨⟨_, bt⟩⟩ => let ⟨a, as, _⟩ := r bt ⟨⟨a, as⟩⟩⟩ theorem rel_of_liftRel {R : α → β → Prop} {ca cb} : LiftRel R ca cb → ∀ {a b}, a ∈ ca → b ∈ cb → R a b | ⟨l, _⟩, a, b, ma, mb => by let ⟨b', mb', ab'⟩ := l ma rw [mem_unique mb mb']; exact ab' theorem liftRel_of_mem {R : α → β → Prop} {a b ca cb} (ma : a ∈ ca) (mb : b ∈ cb) (ab : R a b) : LiftRel R ca cb := ⟨fun {a'} ma' => by rw [mem_unique ma' ma]; exact ⟨b, mb, ab⟩, fun {b'} mb' => by rw [mem_unique mb' mb]; exact ⟨a, ma, ab⟩⟩ theorem exists_of_liftRel_left {R : α → β → Prop} {ca cb} (H : LiftRel R ca cb) {a} (h : a ∈ ca) : ∃ b, b ∈ cb ∧ R a b := H.left h theorem exists_of_liftRel_right {R : α → β → Prop} {ca cb} (H : LiftRel R ca cb) {b} (h : b ∈ cb) : ∃ a, a ∈ ca ∧ R a b := H.right h theorem liftRel_def {R : α → β → Prop} {ca cb} : LiftRel R ca cb ↔ (Terminates ca ↔ Terminates cb) ∧ ∀ {a b}, a ∈ ca → b ∈ cb → R a b := ⟨fun h => ⟨terminates_of_liftRel h, fun {a b} ma mb => by let ⟨b', mb', ab⟩ := h.left ma rwa [mem_unique mb mb']⟩, fun ⟨l, r⟩ => ⟨fun {a} ma => let ⟨⟨b, mb⟩⟩ := l.1 ⟨⟨_, ma⟩⟩ ⟨b, mb, r ma mb⟩, fun {b} mb => let ⟨⟨a, ma⟩⟩ := l.2 ⟨⟨_, mb⟩⟩ ⟨a, ma, r ma mb⟩⟩⟩ theorem liftRel_bind {δ} (R : α → β → Prop) (S : γ → δ → Prop) {s1 : Computation α} {s2 : Computation β} {f1 : α → Computation γ} {f2 : β → Computation δ} (h1 : LiftRel R s1 s2) (h2 : ∀ {a b}, R a b → LiftRel S (f1 a) (f2 b)) : LiftRel S (bind s1 f1) (bind s2 f2) := let ⟨l1, r1⟩ := h1 ⟨fun {_} cB => let ⟨_, a1, c₁⟩ := exists_of_mem_bind cB let ⟨_, b2, ab⟩ := l1 a1 let ⟨l2, _⟩ := h2 ab let ⟨_, d2, cd⟩ := l2 c₁ ⟨_, mem_bind b2 d2, cd⟩, fun {_} dB => let ⟨_, b1, d1⟩ := exists_of_mem_bind dB let ⟨_, a2, ab⟩ := r1 b1 let ⟨_, r2⟩ := h2 ab let ⟨_, c₂, cd⟩ := r2 d1 ⟨_, mem_bind a2 c₂, cd⟩⟩ @[simp] theorem liftRel_pure_left (R : α → β → Prop) (a : α) (cb : Computation β) : LiftRel R (pure a) cb ↔ ∃ b, b ∈ cb ∧ R a b := ⟨fun ⟨l, _⟩ => l (ret_mem _), fun ⟨b, mb, ab⟩ => ⟨fun {a'} ma' => by rw [eq_of_pure_mem ma']; exact ⟨b, mb, ab⟩, fun {b'} mb' => ⟨_, ret_mem _, by rw [mem_unique mb' mb]; exact ab⟩⟩⟩ @[simp] theorem liftRel_pure_right (R : α → β → Prop) (ca : Computation α) (b : β) : LiftRel R ca (pure b) ↔ ∃ a, a ∈ ca ∧ R a b := by rw [LiftRel.swap, liftRel_pure_left] -- Porting note: `simpNF` wants to simplify based on `liftRel_pure_right` but point is to prove -- a general invariant on `LiftRel` @[simp, nolint simpNF] theorem liftRel_pure (R : α → β → Prop) (a : α) (b : β) : LiftRel R (pure a) (pure b) ↔ R a b := by rw [liftRel_pure_left] exact ⟨fun ⟨b', mb', ab'⟩ => by rwa [eq_of_pure_mem mb'] at ab', fun ab => ⟨_, ret_mem _, ab⟩⟩ @[simp] theorem liftRel_think_left (R : α → β → Prop) (ca : Computation α) (cb : Computation β) : LiftRel R (think ca) cb ↔ LiftRel R ca cb := and_congr (forall_congr' fun _ => imp_congr ⟨of_think_mem, think_mem⟩ Iff.rfl) (forall_congr' fun _ => imp_congr Iff.rfl <| exists_congr fun _ => and_congr ⟨of_think_mem, think_mem⟩ Iff.rfl) @[simp] theorem liftRel_think_right (R : α → β → Prop) (ca : Computation α) (cb : Computation β) : LiftRel R ca (think cb) ↔ LiftRel R ca cb := by rw [← LiftRel.swap R, ← LiftRel.swap R]; apply liftRel_think_left theorem liftRel_mem_cases {R : α → β → Prop} {ca cb} (Ha : ∀ a ∈ ca, LiftRel R ca cb) (Hb : ∀ b ∈ cb, LiftRel R ca cb) : LiftRel R ca cb := ⟨fun {_} ma => (Ha _ ma).left ma, fun {_} mb => (Hb _ mb).right mb⟩ theorem liftRel_congr {R : α → β → Prop} {ca ca' : Computation α} {cb cb' : Computation β} (ha : ca ~ ca') (hb : cb ~ cb') : LiftRel R ca cb ↔ LiftRel R ca' cb' := and_congr (forall_congr' fun _ => imp_congr (ha _) <| exists_congr fun _ => and_congr (hb _) Iff.rfl) (forall_congr' fun _ => imp_congr (hb _) <| exists_congr fun _ => and_congr (ha _) Iff.rfl) theorem liftRel_map {δ} (R : α → β → Prop) (S : γ → δ → Prop) {s1 : Computation α} {s2 : Computation β} {f1 : α → γ} {f2 : β → δ} (h1 : LiftRel R s1 s2) (h2 : ∀ {a b}, R a b → S (f1 a) (f2 b)) : LiftRel S (map f1 s1) (map f2 s2) := by -- Porting note: The line below was: -- rw [← bind_pure, ← bind_pure]; apply lift_rel_bind _ _ h1; simp; exact @h2 -- -- The code fails to work on the last exact. rw [← bind_pure, ← bind_pure]; apply liftRel_bind _ _ h1 simp only [comp_apply, liftRel_pure_right] intros a b h; exact ⟨f1 a, ⟨ret_mem _, @h2 a b h⟩⟩ -- Porting note: deleted initial arguments `(_R : α → α → Prop) (_S : β → β → Prop)`: unused theorem map_congr {s1 s2 : Computation α} {f : α → β} (h1 : s1 ~ s2) : map f s1 ~ map f s2 := by rw [← lift_eq_iff_equiv] exact liftRel_map Eq _ ((lift_eq_iff_equiv _ _).2 h1) fun {a} b => congr_arg _ /-- Alternate definition of `LiftRel` over relations between `Computation`s-/ def LiftRelAux (R : α → β → Prop) (C : Computation α → Computation β → Prop) : α ⊕ (Computation α) → β ⊕ (Computation β) → Prop | Sum.inl a, Sum.inl b => R a b | Sum.inl a, Sum.inr cb => ∃ b, b ∈ cb ∧ R a b | Sum.inr ca, Sum.inl b => ∃ a, a ∈ ca ∧ R a b | Sum.inr ca, Sum.inr cb => C ca cb variable {R : α → β → Prop} {C : Computation α → Computation β → Prop} -- Porting note: was attribute [simp] LiftRelAux -- but right now `simp` on defs is a Lean 4 catastrophe -- Instead we add the equation lemmas and tag them @[simp] @[simp] lemma liftRelAux_inl_inl {a : α} {b : β} : LiftRelAux R C (Sum.inl a) (Sum.inl b) = R a b := rfl @[simp] lemma liftRelAux_inl_inr {a : α} {cb} : LiftRelAux R C (Sum.inl a) (Sum.inr cb) = ∃ b, b ∈ cb ∧ R a b := rfl @[simp] lemma liftRelAux_inr_inl {b : β} {ca} : LiftRelAux R C (Sum.inr ca) (Sum.inl b) = ∃ a, a ∈ ca ∧ R a b := rfl @[simp] lemma liftRelAux_inr_inr {ca cb} : LiftRelAux R C (Sum.inr ca) (Sum.inr cb) = C ca cb := rfl @[simp] theorem LiftRelAux.ret_left (R : α → β → Prop) (C : Computation α → Computation β → Prop) (a cb) : LiftRelAux R C (Sum.inl a) (destruct cb) ↔ ∃ b, b ∈ cb ∧ R a b := by apply cb.recOn (fun b => _) fun cb => _ · intro b exact ⟨fun h => ⟨_, ret_mem _, h⟩, fun ⟨b', mb, h⟩ => by rw [mem_unique (ret_mem _) mb]; exact h⟩ · intro rw [destruct_think] exact ⟨fun ⟨b, h, r⟩ => ⟨b, think_mem h, r⟩, fun ⟨b, h, r⟩ => ⟨b, of_think_mem h, r⟩⟩ theorem LiftRelAux.swap (R : α → β → Prop) (C) (a b) : LiftRelAux (swap R) (swap C) b a = LiftRelAux R C a b := by cases' a with a ca <;> cases' b with b cb <;> simp only [LiftRelAux] @[simp] theorem LiftRelAux.ret_right (R : α → β → Prop) (C : Computation α → Computation β → Prop) (b ca) : LiftRelAux R C (destruct ca) (Sum.inl b) ↔ ∃ a, a ∈ ca ∧ R a b := by rw [← LiftRelAux.swap, LiftRelAux.ret_left] theorem LiftRelRec.lem {R : α → β → Prop} (C : Computation α → Computation β → Prop) (H : ∀ {ca cb}, C ca cb → LiftRelAux R C (destruct ca) (destruct cb)) (ca cb) (Hc : C ca cb) (a) (ha : a ∈ ca) : LiftRel R ca cb := by revert cb refine memRecOn (C := (fun ca ↦ ∀ (cb : Computation β), C ca cb → LiftRel R ca cb)) ha ?_ (fun ca' IH => ?_) <;> intro cb Hc <;> have h := H Hc · simp only [destruct_pure, LiftRelAux.ret_left] at h simp [h] · simp only [liftRel_think_left] revert h apply cb.recOn (fun b => _) fun cb' => _ <;> intros _ h · simpa using h · simpa [h] using IH _ h theorem liftRel_rec {R : α → β → Prop} (C : Computation α → Computation β → Prop) (H : ∀ {ca cb}, C ca cb → LiftRelAux R C (destruct ca) (destruct cb)) (ca cb) (Hc : C ca cb) : LiftRel R ca cb := liftRel_mem_cases (LiftRelRec.lem C (@H) ca cb Hc) fun b hb => (LiftRel.swap _ _ _).2 <| LiftRelRec.lem (swap C) (fun {_ _} h => cast (LiftRelAux.swap _ _ _ _).symm <| H h) cb ca Hc b hb end Computation
Data\Seq\Parallel.lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Data.Seq.WSeq /-! # Parallel computation Parallel computation of a computable sequence of computations by a diagonal enumeration. The important theorems of this operation are proven as terminates_parallel and exists_of_mem_parallel. (This operation is nondeterministic in the sense that it does not honor sequence equivalence (irrelevance of computation time).) -/ universe u v namespace Computation open Stream' variable {α : Type u} {β : Type v} def parallel.aux2 : List (Computation α) → α ⊕ (List (Computation α)) := List.foldr (fun c o => match o with | Sum.inl a => Sum.inl a | Sum.inr ls => rmap (fun c' => c' :: ls) (destruct c)) (Sum.inr []) def parallel.aux1 : List (Computation α) × WSeq (Computation α) → α ⊕ (List (Computation α) × WSeq (Computation α)) | (l, S) => rmap (fun l' => match Seq.destruct S with | none => (l', Seq.nil) | some (none, S') => (l', S') | some (some c, S') => (c :: l', S')) (parallel.aux2 l) /-- Parallel computation of an infinite stream of computations, taking the first result -/ def parallel (S : WSeq (Computation α)) : Computation α := corec parallel.aux1 ([], S) theorem terminates_parallel.aux : ∀ {l : List (Computation α)} {S c}, c ∈ l → Terminates c → Terminates (corec parallel.aux1 (l, S)) := by have lem1 : ∀ l S, (∃ a : α, parallel.aux2 l = Sum.inl a) → Terminates (corec parallel.aux1 (l, S)) := by intro l S e cases' e with a e have : corec parallel.aux1 (l, S) = return a := by apply destruct_eq_pure simp only [parallel.aux1, rmap, corec_eq] rw [e] rw [this] -- Porting note: This line is required. exact ret_terminates a intro l S c m T revert l S apply @terminatesRecOn _ _ c T _ _ · intro a l S m apply lem1 induction' l with c l IH <;> simp at m cases' m with e m · rw [← e] simp only [parallel.aux2, rmap, List.foldr_cons, destruct_pure] split <;> simp · cases' IH m with a' e simp only [parallel.aux2, rmap, List.foldr_cons] simp? [parallel.aux2] at e says simp only [parallel.aux2, rmap] at e rw [e] exact ⟨a', rfl⟩ · intro s IH l S m have H1 : ∀ l', parallel.aux2 l = Sum.inr l' → s ∈ l' := by induction' l with c l IH' <;> intro l' e' <;> simp at m cases' m with e m <;> simp [parallel.aux2] at e' · rw [← e] at e' -- Porting note: `revert e'` & `intro e'` are required. revert e' split · simp · simp only [destruct_think, Sum.inr.injEq] rintro rfl simp · induction' e : List.foldr (fun c o => match o with | Sum.inl a => Sum.inl a | Sum.inr ls => rmap (fun c' => c' :: ls) (destruct c)) (Sum.inr List.nil) l with a' ls <;> erw [e] at e' · contradiction have := IH' m _ e -- Porting note: `revert e'` & `intro e'` are required. revert e' cases destruct c <;> intro e' <;> [injection e'; injection e' with h'] rw [← h'] simp [this] induction' h : parallel.aux2 l with a l' · exact lem1 _ _ ⟨a, h⟩ · have H2 : corec parallel.aux1 (l, S) = think _ := destruct_eq_think (by simp only [parallel.aux1, rmap, corec_eq] rw [h]) rw [H2] refine @Computation.think_terminates _ _ ?_ have := H1 _ h rcases Seq.destruct S with (_ | ⟨_ | c, S'⟩) <;> simp [parallel.aux1] <;> apply IH <;> simp [this] theorem terminates_parallel {S : WSeq (Computation α)} {c} (h : c ∈ S) [T : Terminates c] : Terminates (parallel S) := by suffices ∀ (n) (l : List (Computation α)) (S c), c ∈ l ∨ some (some c) = Seq.get? S n → Terminates c → Terminates (corec parallel.aux1 (l, S)) from let ⟨n, h⟩ := h this n [] S c (Or.inr h) T intro n; induction' n with n IH <;> intro l S c o T · cases' o with a a · exact terminates_parallel.aux a T have H : Seq.destruct S = some (some c, Seq.tail S) := by simp [Seq.destruct, (· <$> ·), ← a] induction' h : parallel.aux2 l with a l' · have C : corec parallel.aux1 (l, S) = pure a := by apply destruct_eq_pure rw [corec_eq, parallel.aux1] dsimp only [] rw [h] simp only [rmap] rw [C] infer_instance · have C : corec parallel.aux1 (l, S) = _ := destruct_eq_think (by simp only [corec_eq, rmap, parallel.aux1.eq_1] rw [h, H]) rw [C] refine @Computation.think_terminates _ _ ?_ apply terminates_parallel.aux _ T simp · cases' o with a a · exact terminates_parallel.aux a T induction' h : parallel.aux2 l with a l' · have C : corec parallel.aux1 (l, S) = pure a := by apply destruct_eq_pure rw [corec_eq, parallel.aux1] dsimp only [] rw [h] simp only [rmap] rw [C] infer_instance · have C : corec parallel.aux1 (l, S) = _ := destruct_eq_think (by simp only [corec_eq, rmap, parallel.aux1.eq_1] rw [h]) rw [C] refine @Computation.think_terminates _ _ ?_ have TT : ∀ l', Terminates (corec parallel.aux1 (l', S.tail)) := by intro apply IH _ _ _ (Or.inr _) T rw [a] cases' S with f al rfl induction' e : Seq.get? S 0 with o · have D : Seq.destruct S = none := by dsimp [Seq.destruct] rw [e] rfl rw [D] simp only have TT := TT l' rwa [Seq.destruct_eq_nil D, Seq.tail_nil] at TT · have D : Seq.destruct S = some (o, S.tail) := by dsimp [Seq.destruct] rw [e] rfl rw [D] cases' o with c <;> simp [parallel.aux1, TT] theorem exists_of_mem_parallel {S : WSeq (Computation α)} {a} (h : a ∈ parallel S) : ∃ c ∈ S, a ∈ c := by suffices ∀ C, a ∈ C → ∀ (l : List (Computation α)) (S), corec parallel.aux1 (l, S) = C → ∃ c, (c ∈ l ∨ c ∈ S) ∧ a ∈ c from let ⟨c, h1, h2⟩ := this _ h [] S rfl ⟨c, h1.resolve_left <| List.not_mem_nil _, h2⟩ let F : List (Computation α) → α ⊕ (List (Computation α)) → Prop := by intro l a cases' a with a l' · exact ∃ c ∈ l, a ∈ c · exact ∀ a', (∃ c ∈ l', a' ∈ c) → ∃ c ∈ l, a' ∈ c have lem1 : ∀ l : List (Computation α), F l (parallel.aux2 l) := by intro l induction' l with c l IH <;> simp only [parallel.aux2, List.foldr] · intro a h rcases h with ⟨c, hn, _⟩ exact False.elim <| List.not_mem_nil _ hn · simp only [parallel.aux2] at IH -- Porting note: `revert IH` & `intro IH` are required. revert IH cases' List.foldr (fun c o => match o with | Sum.inl a => Sum.inl a | Sum.inr ls => rmap (fun c' => c' :: ls) (destruct c)) (Sum.inr List.nil) l with a ls <;> intro IH <;> simp only [parallel.aux2] · rcases IH with ⟨c', cl, ac⟩ exact ⟨c', List.Mem.tail _ cl, ac⟩ · induction' h : destruct c with a c' <;> simp only [rmap] · refine ⟨c, List.mem_cons_self _ _, ?_⟩ rw [destruct_eq_pure h] apply ret_mem · intro a' h rcases h with ⟨d, dm, ad⟩ simp? at dm says simp only [List.mem_cons] at dm cases' dm with e dl · rw [e] at ad refine ⟨c, List.mem_cons_self _ _, ?_⟩ rw [destruct_eq_think h] exact think_mem ad · cases' IH a' ⟨d, dl, ad⟩ with d dm cases' dm with dm ad exact ⟨d, List.Mem.tail _ dm, ad⟩ intro C aC -- Porting note: `revert e'` & `intro e'` are required. apply memRecOn aC <;> [skip; intro C' IH] <;> intro l S e <;> have e' := congr_arg destruct e <;> have := lem1 l <;> simp only [parallel.aux1, corec_eq, destruct_pure, destruct_think] at e' <;> revert this e' <;> cases' parallel.aux2 l with a' l' <;> intro this e' <;> [injection e' with h'; injection e'; injection e'; injection e' with h'] · rw [h'] at this rcases this with ⟨c, cl, ac⟩ exact ⟨c, Or.inl cl, ac⟩ · induction' e : Seq.destruct S with a <;> rw [e] at h' · exact let ⟨d, o, ad⟩ := IH _ _ h' let ⟨c, cl, ac⟩ := this a ⟨d, o.resolve_right (WSeq.not_mem_nil _), ad⟩ ⟨c, Or.inl cl, ac⟩ · cases' a with o S' cases' o with c <;> simp [parallel.aux1] at h' <;> rcases IH _ _ h' with ⟨d, dl | dS', ad⟩ · exact let ⟨c, cl, ac⟩ := this a ⟨d, dl, ad⟩ ⟨c, Or.inl cl, ac⟩ · refine ⟨d, Or.inr ?_, ad⟩ rw [Seq.destruct_eq_cons e] exact Seq.mem_cons_of_mem _ dS' · simp at dl cases' dl with dc dl · rw [dc] at ad refine ⟨c, Or.inr ?_, ad⟩ rw [Seq.destruct_eq_cons e] apply Seq.mem_cons · exact let ⟨c, cl, ac⟩ := this a ⟨d, dl, ad⟩ ⟨c, Or.inl cl, ac⟩ · refine ⟨d, Or.inr ?_, ad⟩ rw [Seq.destruct_eq_cons e] exact Seq.mem_cons_of_mem _ dS' theorem map_parallel (f : α → β) (S) : map f (parallel S) = parallel (S.map (map f)) := by refine eq_of_bisim (fun c1 c2 => ∃ l S, c1 = map f (corec parallel.aux1 (l, S)) ∧ c2 = corec parallel.aux1 (l.map (map f), S.map (map f))) ?_ ⟨[], S, rfl, rfl⟩ intro c1 c2 h exact match c1, c2, h with | _, _, ⟨l, S, rfl, rfl⟩ => by have : parallel.aux2 (l.map (map f)) = lmap f (rmap (List.map (map f)) (parallel.aux2 l)) := by simp only [parallel.aux2, rmap, lmap] induction' l with c l IH <;> simp rw [IH] cases List.foldr _ _ _ · simp · cases destruct c <;> simp simp only [BisimO, destruct_map, lmap, rmap, corec_eq, parallel.aux1.eq_1] rw [this] cases' parallel.aux2 l with a l' <;> simp induction' S using WSeq.recOn with c S S <;> simp <;> exact ⟨_, _, rfl, rfl⟩ theorem parallel_empty (S : WSeq (Computation α)) (h : S.head ~> none) : parallel S = empty _ := eq_empty_of_not_terminates fun ⟨⟨a, m⟩⟩ => by let ⟨c, cs, _⟩ := exists_of_mem_parallel m let ⟨n, nm⟩ := WSeq.exists_get?_of_mem cs let ⟨c', h'⟩ := WSeq.head_some_of_get?_some nm injection h h' -- The reason this isn't trivial from exists_of_mem_parallel is because it eliminates to Sort def parallelRec {S : WSeq (Computation α)} (C : α → Sort v) (H : ∀ s ∈ S, ∀ a ∈ s, C a) {a} (h : a ∈ parallel S) : C a := by let T : WSeq (Computation (α × Computation α)) := S.map fun c => c.map fun a => (a, c) have : S = T.map (map fun c => c.1) := by rw [← WSeq.map_comp] refine (WSeq.map_id _).symm.trans (congr_arg (fun f => WSeq.map f S) ?_) funext c dsimp [id, Function.comp_def] rw [← map_comp] exact (map_id _).symm have pe := congr_arg parallel this rw [← map_parallel] at pe have h' := h rw [pe] at h' haveI : Terminates (parallel T) := (terminates_map_iff _ _).1 ⟨⟨_, h'⟩⟩ induction' e : get (parallel T) with a' c have : a ∈ c ∧ c ∈ S := by rcases exists_of_mem_map h' with ⟨d, dT, cd⟩ rw [get_eq_of_mem _ dT] at e cases e dsimp at cd cases cd rcases exists_of_mem_parallel dT with ⟨d', dT', ad'⟩ rcases WSeq.exists_of_mem_map dT' with ⟨c', cs', e'⟩ rw [← e'] at ad' rcases exists_of_mem_map ad' with ⟨a', ac', e'⟩ injection e' with i1 i2 constructor · rwa [i1, i2] at ac' · rwa [i2] at cs' cases' this with ac cs apply H _ cs _ ac theorem parallel_promises {S : WSeq (Computation α)} {a} (H : ∀ s ∈ S, s ~> a) : parallel S ~> a := fun _ ma' => let ⟨_, cs, ac⟩ := exists_of_mem_parallel ma' H _ cs ac theorem mem_parallel {S : WSeq (Computation α)} {a} (H : ∀ s ∈ S, s ~> a) {c} (cs : c ∈ S) (ac : a ∈ c) : a ∈ parallel S := by haveI := terminates_of_mem ac haveI := terminates_parallel cs exact mem_of_promises _ (parallel_promises H) theorem parallel_congr_lem {S T : WSeq (Computation α)} {a} (H : S.LiftRel Equiv T) : (∀ s ∈ S, s ~> a) ↔ ∀ t ∈ T, t ~> a := ⟨fun h1 _ tT => let ⟨_, sS, se⟩ := WSeq.exists_of_liftRel_right H tT (promises_congr se _).1 (h1 _ sS), fun h2 _ sS => let ⟨_, tT, se⟩ := WSeq.exists_of_liftRel_left H sS (promises_congr se _).2 (h2 _ tT)⟩ -- The parallel operation is only deterministic when all computation paths lead to the same value theorem parallel_congr_left {S T : WSeq (Computation α)} {a} (h1 : ∀ s ∈ S, s ~> a) (H : S.LiftRel Equiv T) : parallel S ~ parallel T := let h2 := (parallel_congr_lem H).1 h1 fun a' => ⟨fun h => by have aa := parallel_promises h1 h rw [← aa] rw [← aa] at h exact let ⟨s, sS, as⟩ := exists_of_mem_parallel h let ⟨t, tT, st⟩ := WSeq.exists_of_liftRel_left H sS let aT := (st _).1 as mem_parallel h2 tT aT, fun h => by have aa := parallel_promises h2 h rw [← aa] rw [← aa] at h exact let ⟨s, sS, as⟩ := exists_of_mem_parallel h let ⟨t, tT, st⟩ := WSeq.exists_of_liftRel_right H sS let aT := (st _).2 as mem_parallel h1 tT aT⟩ theorem parallel_congr_right {S T : WSeq (Computation α)} {a} (h2 : ∀ t ∈ T, t ~> a) (H : S.LiftRel Equiv T) : parallel S ~ parallel T := parallel_congr_left ((parallel_congr_lem H).2 h2) H end Computation
Data\Seq\Seq.lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Data.Option.NAry import Mathlib.Data.Seq.Computation /-! # Possibly infinite lists This file provides a `Seq α` type representing possibly infinite lists (referred here as sequences). It is encoded as an infinite stream of options such that if `f n = none`, then `f m = none` for all `m ≥ n`. -/ namespace Stream' universe u v w /- coinductive seq (α : Type u) : Type u | nil : seq α | cons : α → seq α → seq α -/ /-- A stream `s : Option α` is a sequence if `s.get n = none` implies `s.get (n + 1) = none`. -/ def IsSeq {α : Type u} (s : Stream' (Option α)) : Prop := ∀ {n : ℕ}, s n = none → s (n + 1) = none /-- `Seq α` is the type of possibly infinite lists (referred here as sequences). It is encoded as an infinite stream of options such that if `f n = none`, then `f m = none` for all `m ≥ n`. -/ def Seq (α : Type u) : Type u := { f : Stream' (Option α) // f.IsSeq } /-- `Seq1 α` is the type of nonempty sequences. -/ def Seq1 (α) := α × Seq α namespace Seq variable {α : Type u} {β : Type v} {γ : Type w} /-- The empty sequence -/ def nil : Seq α := ⟨Stream'.const none, fun {_} _ => rfl⟩ instance : Inhabited (Seq α) := ⟨nil⟩ /-- Prepend an element to a sequence -/ def cons (a : α) (s : Seq α) : Seq α := ⟨some a::s.1, by rintro (n | _) h · contradiction · exact s.2 h⟩ @[simp] theorem val_cons (s : Seq α) (x : α) : (cons x s).val = some x::s.val := rfl /-- Get the nth element of a sequence (if it exists) -/ def get? : Seq α → ℕ → Option α := Subtype.val @[simp] theorem get?_mk (f hf) : @get? α ⟨f, hf⟩ = f := rfl @[simp] theorem get?_nil (n : ℕ) : (@nil α).get? n = none := rfl @[simp] theorem get?_cons_zero (a : α) (s : Seq α) : (cons a s).get? 0 = some a := rfl @[simp] theorem get?_cons_succ (a : α) (s : Seq α) (n : ℕ) : (cons a s).get? (n + 1) = s.get? n := rfl @[ext] protected theorem ext {s t : Seq α} (h : ∀ n : ℕ, s.get? n = t.get? n) : s = t := Subtype.eq <| funext h theorem cons_injective2 : Function.Injective2 (cons : α → Seq α → Seq α) := fun x y s t h => ⟨by rw [← Option.some_inj, ← get?_cons_zero, h, get?_cons_zero], Seq.ext fun n => by simp_rw [← get?_cons_succ x s n, h, get?_cons_succ]⟩ theorem cons_left_injective (s : Seq α) : Function.Injective fun x => cons x s := cons_injective2.left _ theorem cons_right_injective (x : α) : Function.Injective (cons x) := cons_injective2.right _ /-- A sequence has terminated at position `n` if the value at position `n` equals `none`. -/ def TerminatedAt (s : Seq α) (n : ℕ) : Prop := s.get? n = none /-- It is decidable whether a sequence terminates at a given position. -/ instance terminatedAtDecidable (s : Seq α) (n : ℕ) : Decidable (s.TerminatedAt n) := decidable_of_iff' (s.get? n).isNone <| by unfold TerminatedAt; cases s.get? n <;> simp /-- A sequence terminates if there is some position `n` at which it has terminated. -/ def Terminates (s : Seq α) : Prop := ∃ n : ℕ, s.TerminatedAt n theorem not_terminates_iff {s : Seq α} : ¬s.Terminates ↔ ∀ n, (s.get? n).isSome := by simp only [Terminates, TerminatedAt, ← Ne.eq_def, Option.ne_none_iff_isSome, not_exists, iff_self] /-- Functorial action of the functor `Option (α × _)` -/ @[simp] def omap (f : β → γ) : Option (α × β) → Option (α × γ) | none => none | some (a, b) => some (a, f b) /-- Get the first element of a sequence -/ def head (s : Seq α) : Option α := get? s 0 /-- Get the tail of a sequence (or `nil` if the sequence is `nil`) -/ def tail (s : Seq α) : Seq α := ⟨s.1.tail, fun n' => by cases' s with f al exact al n'⟩ /-- member definition for `Seq`-/ protected def Mem (a : α) (s : Seq α) := some a ∈ s.1 instance : Membership α (Seq α) := ⟨Seq.Mem⟩ theorem le_stable (s : Seq α) {m n} (h : m ≤ n) : s.get? m = none → s.get? n = none := by cases' s with f al induction' h with n _ IH exacts [id, fun h2 => al (IH h2)] /-- If a sequence terminated at position `n`, it also terminated at `m ≥ n`. -/ theorem terminated_stable : ∀ (s : Seq α) {m n : ℕ}, m ≤ n → s.TerminatedAt m → s.TerminatedAt n := le_stable /-- If `s.get? n = some aₙ` for some value `aₙ`, then there is also some value `aₘ` such that `s.get? = some aₘ` for `m ≤ n`. -/ theorem ge_stable (s : Seq α) {aₙ : α} {n m : ℕ} (m_le_n : m ≤ n) (s_nth_eq_some : s.get? n = some aₙ) : ∃ aₘ : α, s.get? m = some aₘ := have : s.get? n ≠ none := by simp [s_nth_eq_some] have : s.get? m ≠ none := mt (s.le_stable m_le_n) this Option.ne_none_iff_exists'.mp this theorem not_mem_nil (a : α) : a ∉ @nil α := fun ⟨_, (h : some a = none)⟩ => by injection h theorem mem_cons (a : α) : ∀ s : Seq α, a ∈ cons a s | ⟨_, _⟩ => Stream'.mem_cons (some a) _ theorem mem_cons_of_mem (y : α) {a : α} : ∀ {s : Seq α}, a ∈ s → a ∈ cons y s | ⟨_, _⟩ => Stream'.mem_cons_of_mem (some y) theorem eq_or_mem_of_mem_cons {a b : α} : ∀ {s : Seq α}, a ∈ cons b s → a = b ∨ a ∈ s | ⟨f, al⟩, h => (Stream'.eq_or_mem_of_mem_cons h).imp_left fun h => by injection h @[simp] theorem mem_cons_iff {a b : α} {s : Seq α} : a ∈ cons b s ↔ a = b ∨ a ∈ s := ⟨eq_or_mem_of_mem_cons, by rintro (rfl | m) <;> [apply mem_cons; exact mem_cons_of_mem _ m]⟩ /-- Destructor for a sequence, resulting in either `none` (for `nil`) or `some (a, s)` (for `cons a s`). -/ def destruct (s : Seq α) : Option (Seq1 α) := (fun a' => (a', s.tail)) <$> get? s 0 theorem destruct_eq_nil {s : Seq α} : destruct s = none → s = nil := by dsimp [destruct] induction' f0 : get? s 0 <;> intro h · apply Subtype.eq funext n induction' n with n IH exacts [f0, s.2 IH] · contradiction theorem destruct_eq_cons {s : Seq α} {a s'} : destruct s = some (a, s') → s = cons a s' := by dsimp [destruct] induction' f0 : get? s 0 with a' <;> intro h · contradiction · cases' s with f al injections _ h1 h2 rw [← h2] apply Subtype.eq dsimp [tail, cons] rw [h1] at f0 rw [← f0] exact (Stream'.eta f).symm @[simp] theorem destruct_nil : destruct (nil : Seq α) = none := rfl @[simp] theorem destruct_cons (a : α) : ∀ s, destruct (cons a s) = some (a, s) | ⟨f, al⟩ => by unfold cons destruct Functor.map apply congr_arg fun s => some (a, s) apply Subtype.eq; dsimp [tail] -- Porting note: needed universe annotation to avoid universe issues theorem head_eq_destruct (s : Seq α) : head.{u} s = Prod.fst.{u} <$> destruct.{u} s := by unfold destruct head; cases get? s 0 <;> rfl @[simp] theorem head_nil : head (nil : Seq α) = none := rfl @[simp] theorem head_cons (a : α) (s) : head (cons a s) = some a := by rw [head_eq_destruct, destruct_cons, Option.map_eq_map, Option.map_some'] @[simp] theorem tail_nil : tail (nil : Seq α) = nil := rfl @[simp] theorem tail_cons (a : α) (s) : tail (cons a s) = s := by cases' s with f al apply Subtype.eq dsimp [tail, cons] @[simp] theorem get?_tail (s : Seq α) (n) : get? (tail s) n = get? s (n + 1) := rfl /-- Recursion principle for sequences, compare with `List.recOn`. -/ def recOn {C : Seq α → Sort v} (s : Seq α) (h1 : C nil) (h2 : ∀ x s, C (cons x s)) : C s := by cases' H : destruct s with v · rw [destruct_eq_nil H] apply h1 · cases' v with a s' rw [destruct_eq_cons H] apply h2 theorem mem_rec_on {C : Seq α → Prop} {a s} (M : a ∈ s) (h1 : ∀ b s', a = b ∨ C s' → C (cons b s')) : C s := by cases' M with k e; unfold Stream'.get at e induction' k with k IH generalizing s · have TH : s = cons a (tail s) := by apply destruct_eq_cons unfold destruct get? Functor.map rw [← e] rfl rw [TH] apply h1 _ _ (Or.inl rfl) -- Porting note: had to reshuffle `intro` revert e; apply s.recOn _ fun b s' => _ · intro e; injection e · intro b s' e have h_eq : (cons b s').val (Nat.succ k) = s'.val k := by cases s'; rfl rw [h_eq] at e apply h1 _ _ (Or.inr (IH e)) /-- Corecursor over pairs of `Option` values-/ def Corec.f (f : β → Option (α × β)) : Option β → Option α × Option β | none => (none, none) | some b => match f b with | none => (none, none) | some (a, b') => (some a, some b') /-- Corecursor for `Seq α` as a coinductive type. Iterates `f` to produce new elements of the sequence until `none` is obtained. -/ def corec (f : β → Option (α × β)) (b : β) : Seq α := by refine ⟨Stream'.corec' (Corec.f f) (some b), fun {n} h => ?_⟩ rw [Stream'.corec'_eq] change Stream'.corec' (Corec.f f) (Corec.f f (some b)).2 n = none revert h; generalize some b = o; revert o induction' n with n IH <;> intro o · change (Corec.f f o).1 = none → (Corec.f f (Corec.f f o).2).1 = none cases' o with b <;> intro h · rfl dsimp [Corec.f] at h dsimp [Corec.f] revert h; cases' h₁ : f b with s <;> intro h · rfl · cases' s with a b' contradiction · rw [Stream'.corec'_eq (Corec.f f) (Corec.f f o).2, Stream'.corec'_eq (Corec.f f) o] exact IH (Corec.f f o).2 @[simp] theorem corec_eq (f : β → Option (α × β)) (b : β) : destruct (corec f b) = omap (corec f) (f b) := by dsimp [corec, destruct, get] -- Porting note: next two lines were `change`...`with`... have h : Stream'.corec' (Corec.f f) (some b) 0 = (Corec.f f (some b)).1 := rfl rw [h] dsimp [Corec.f] induction' h : f b with s; · rfl cases' s with a b'; dsimp [Corec.f] apply congr_arg fun b' => some (a, b') apply Subtype.eq dsimp [corec, tail] rw [Stream'.corec'_eq, Stream'.tail_cons] dsimp [Corec.f]; rw [h] section Bisim variable (R : Seq α → Seq α → Prop) local infixl:50 " ~ " => R /-- Bisimilarity relation over `Option` of `Seq1 α`-/ def BisimO : Option (Seq1 α) → Option (Seq1 α) → Prop | none, none => True | some (a, s), some (a', s') => a = a' ∧ R s s' | _, _ => False attribute [simp] BisimO /-- a relation is bisimilar if it meets the `BisimO` test-/ def IsBisimulation := ∀ ⦃s₁ s₂⦄, s₁ ~ s₂ → BisimO R (destruct s₁) (destruct s₂) -- If two streams are bisimilar, then they are equal theorem eq_of_bisim (bisim : IsBisimulation R) {s₁ s₂} (r : s₁ ~ s₂) : s₁ = s₂ := by apply Subtype.eq apply Stream'.eq_of_bisim fun x y => ∃ s s' : Seq α, s.1 = x ∧ s'.1 = y ∧ R s s' · dsimp [Stream'.IsBisimulation] intro t₁ t₂ e exact match t₁, t₂, e with | _, _, ⟨s, s', rfl, rfl, r⟩ => by suffices head s = head s' ∧ R (tail s) (tail s') from And.imp id (fun r => ⟨tail s, tail s', by cases s; rfl, by cases s'; rfl, r⟩) this have := bisim r; revert r this apply recOn s _ _ <;> apply recOn s' _ _ · intro r _ constructor · rfl · assumption · intro x s _ this rw [destruct_nil, destruct_cons] at this exact False.elim this · intro x s _ this rw [destruct_nil, destruct_cons] at this exact False.elim this · intro x s x' s' _ this rw [destruct_cons, destruct_cons] at this rw [head_cons, head_cons, tail_cons, tail_cons] cases' this with h1 h2 constructor · rw [h1] · exact h2 · exact ⟨s₁, s₂, rfl, rfl, r⟩ end Bisim theorem coinduction : ∀ {s₁ s₂ : Seq α}, head s₁ = head s₂ → (∀ (β : Type u) (fr : Seq α → β), fr s₁ = fr s₂ → fr (tail s₁) = fr (tail s₂)) → s₁ = s₂ | _, _, hh, ht => Subtype.eq (Stream'.coinduction hh fun β fr => ht β fun s => fr s.1) theorem coinduction2 (s) (f g : Seq α → Seq β) (H : ∀ s, BisimO (fun s1 s2 : Seq β => ∃ s : Seq α, s1 = f s ∧ s2 = g s) (destruct (f s)) (destruct (g s))) : f s = g s := by refine eq_of_bisim (fun s1 s2 => ∃ s, s1 = f s ∧ s2 = g s) ?_ ⟨s, rfl, rfl⟩ intro s1 s2 h; rcases h with ⟨s, h1, h2⟩ rw [h1, h2]; apply H /-- Embed a list as a sequence -/ @[coe] def ofList (l : List α) : Seq α := ⟨List.get? l, fun {n} h => by rw [List.get?_eq_none] at h ⊢ exact h.trans (Nat.le_succ n)⟩ instance coeList : Coe (List α) (Seq α) := ⟨ofList⟩ @[simp] theorem ofList_nil : ofList [] = (nil : Seq α) := rfl @[simp] theorem ofList_get (l : List α) (n : ℕ) : (ofList l).get? n = l.get? n := rfl @[simp] theorem ofList_cons (a : α) (l : List α) : ofList (a::l) = cons a (ofList l) := by ext1 (_ | n) <;> rfl /-- Embed an infinite stream as a sequence -/ @[coe] def ofStream (s : Stream' α) : Seq α := ⟨s.map some, fun {n} h => by contradiction⟩ instance coeStream : Coe (Stream' α) (Seq α) := ⟨ofStream⟩ section MLList /-- Embed a `MLList α` as a sequence. Note that even though this is non-meta, it will produce infinite sequences if used with cyclic `MLList`s created by meta constructions. -/ def ofMLList : MLList Id α → Seq α := corec fun l => match l.uncons with | .none => none | .some (a, l') => some (a, l') @[deprecated (since := "2024-07-26")] alias ofLazyList := ofMLList instance coeMLList : Coe (MLList Id α) (Seq α) := ⟨ofMLList⟩ @[deprecated (since := "2024-07-26")] alias coeLazyList := coeMLList /-- Translate a sequence into a `MLList`. -/ unsafe def toMLList : Seq α → MLList Id α | s => match destruct s with | none => .nil | some (a, s') => .cons a (toMLList s') @[deprecated (since := "2024-07-26")] alias toLazyList := toMLList end MLList /-- Translate a sequence to a list. This function will run forever if run on an infinite sequence. -/ unsafe def forceToList (s : Seq α) : List α := (toMLList s).force /-- The sequence of natural numbers some 0, some 1, ... -/ def nats : Seq ℕ := Stream'.nats @[simp] theorem nats_get? (n : ℕ) : nats.get? n = some n := rfl /-- Append two sequences. If `s₁` is infinite, then `s₁ ++ s₂ = s₁`, otherwise it puts `s₂` at the location of the `nil` in `s₁`. -/ def append (s₁ s₂ : Seq α) : Seq α := @corec α (Seq α × Seq α) (fun ⟨s₁, s₂⟩ => match destruct s₁ with | none => omap (fun s₂ => (nil, s₂)) (destruct s₂) | some (a, s₁') => some (a, s₁', s₂)) (s₁, s₂) /-- Map a function over a sequence. -/ def map (f : α → β) : Seq α → Seq β | ⟨s, al⟩ => ⟨s.map (Option.map f), fun {n} => by dsimp [Stream'.map, Stream'.get] induction' e : s n with e <;> intro · rw [al e] assumption · contradiction⟩ /-- Flatten a sequence of sequences. (It is required that the sequences be nonempty to ensure productivity; in the case of an infinite sequence of `nil`, the first element is never generated.) -/ def join : Seq (Seq1 α) → Seq α := corec fun S => match destruct S with | none => none | some ((a, s), S') => some (a, match destruct s with | none => S' | some s' => cons s' S') /-- Remove the first `n` elements from the sequence. -/ def drop (s : Seq α) : ℕ → Seq α | 0 => s | n + 1 => tail (drop s n) attribute [simp] drop /-- Take the first `n` elements of the sequence (producing a list) -/ def take : ℕ → Seq α → List α | 0, _ => [] | n + 1, s => match destruct s with | none => [] | some (x, r) => List.cons x (take n r) /-- Split a sequence at `n`, producing a finite initial segment and an infinite tail. -/ def splitAt : ℕ → Seq α → List α × Seq α | 0, s => ([], s) | n + 1, s => match destruct s with | none => ([], nil) | some (x, s') => let (l, r) := splitAt n s' (List.cons x l, r) section ZipWith /-- Combine two sequences with a function -/ def zipWith (f : α → β → γ) (s₁ : Seq α) (s₂ : Seq β) : Seq γ := ⟨fun n => Option.map₂ f (s₁.get? n) (s₂.get? n), fun {_} hn => Option.map₂_eq_none_iff.2 <| (Option.map₂_eq_none_iff.1 hn).imp s₁.2 s₂.2⟩ variable {s : Seq α} {s' : Seq β} {n : ℕ} @[simp] theorem get?_zipWith (f : α → β → γ) (s s' n) : (zipWith f s s').get? n = Option.map₂ f (s.get? n) (s'.get? n) := rfl end ZipWith /-- Pair two sequences into a sequence of pairs -/ def zip : Seq α → Seq β → Seq (α × β) := zipWith Prod.mk theorem get?_zip (s : Seq α) (t : Seq β) (n : ℕ) : get? (zip s t) n = Option.map₂ Prod.mk (get? s n) (get? t n) := get?_zipWith _ _ _ _ /-- Separate a sequence of pairs into two sequences -/ def unzip (s : Seq (α × β)) : Seq α × Seq β := (map Prod.fst s, map Prod.snd s) /-- Enumerate a sequence by tagging each element with its index. -/ def enum (s : Seq α) : Seq (ℕ × α) := Seq.zip nats s @[simp] theorem get?_enum (s : Seq α) (n : ℕ) : get? (enum s) n = Option.map (Prod.mk n) (get? s n) := get?_zip _ _ _ @[simp] theorem enum_nil : enum (nil : Seq α) = nil := rfl /-- Convert a sequence which is known to terminate into a list -/ def toList (s : Seq α) (h : s.Terminates) : List α := take (Nat.find h) s /-- Convert a sequence which is known not to terminate into a stream -/ def toStream (s : Seq α) (h : ¬s.Terminates) : Stream' α := fun n => Option.get _ <| not_terminates_iff.1 h n /-- Convert a sequence into either a list or a stream depending on whether it is finite or infinite. (Without decidability of the infiniteness predicate, this is not constructively possible.) -/ def toListOrStream (s : Seq α) [Decidable s.Terminates] : List α ⊕ Stream' α := if h : s.Terminates then Sum.inl (toList s h) else Sum.inr (toStream s h) @[simp] theorem nil_append (s : Seq α) : append nil s = s := by apply coinduction2; intro s dsimp [append]; rw [corec_eq] dsimp [append]; apply recOn s _ _ · trivial · intro x s rw [destruct_cons] dsimp exact ⟨rfl, s, rfl, rfl⟩ @[simp] theorem cons_append (a : α) (s t) : append (cons a s) t = cons a (append s t) := destruct_eq_cons <| by dsimp [append]; rw [corec_eq] dsimp [append]; rw [destruct_cons] @[simp] theorem append_nil (s : Seq α) : append s nil = s := by apply coinduction2 s; intro s apply recOn s _ _ · trivial · intro x s rw [cons_append, destruct_cons, destruct_cons] dsimp exact ⟨rfl, s, rfl, rfl⟩ @[simp] theorem append_assoc (s t u : Seq α) : append (append s t) u = append s (append t u) := by apply eq_of_bisim fun s1 s2 => ∃ s t u, s1 = append (append s t) u ∧ s2 = append s (append t u) · intro s1 s2 h exact match s1, s2, h with | _, _, ⟨s, t, u, rfl, rfl⟩ => by apply recOn s <;> simp · apply recOn t <;> simp · apply recOn u <;> simp · intro _ u refine ⟨nil, nil, u, ?_, ?_⟩ <;> simp · intro _ t refine ⟨nil, t, u, ?_, ?_⟩ <;> simp · intro _ s exact ⟨s, t, u, rfl, rfl⟩ · exact ⟨s, t, u, rfl, rfl⟩ @[simp] theorem map_nil (f : α → β) : map f nil = nil := rfl @[simp] theorem map_cons (f : α → β) (a) : ∀ s, map f (cons a s) = cons (f a) (map f s) | ⟨s, al⟩ => by apply Subtype.eq; dsimp [cons, map]; rw [Stream'.map_cons]; rfl @[simp] theorem map_id : ∀ s : Seq α, map id s = s | ⟨s, al⟩ => by apply Subtype.eq; dsimp [map] rw [Option.map_id, Stream'.map_id] @[simp] theorem map_tail (f : α → β) : ∀ s, map f (tail s) = tail (map f s) | ⟨s, al⟩ => by apply Subtype.eq; dsimp [tail, map] theorem map_comp (f : α → β) (g : β → γ) : ∀ s : Seq α, map (g ∘ f) s = map g (map f s) | ⟨s, al⟩ => by apply Subtype.eq; dsimp [map] apply congr_arg fun f : _ → Option γ => Stream'.map f s ext ⟨⟩ <;> rfl @[simp] theorem map_append (f : α → β) (s t) : map f (append s t) = append (map f s) (map f t) := by apply eq_of_bisim (fun s1 s2 => ∃ s t, s1 = map f (append s t) ∧ s2 = append (map f s) (map f t)) _ ⟨s, t, rfl, rfl⟩ intro s1 s2 h exact match s1, s2, h with | _, _, ⟨s, t, rfl, rfl⟩ => by apply recOn s <;> simp · apply recOn t <;> simp · intro _ t refine ⟨nil, t, ?_, ?_⟩ <;> simp · intro _ s exact ⟨s, t, rfl, rfl⟩ @[simp] theorem map_get? (f : α → β) : ∀ s n, get? (map f s) n = (get? s n).map f | ⟨_, _⟩, _ => rfl instance : Functor Seq where map := @map instance : LawfulFunctor Seq where id_map := @map_id comp_map := @map_comp map_const := rfl @[simp] theorem join_nil : join nil = (nil : Seq α) := destruct_eq_nil rfl --@[simp] -- Porting note: simp can prove: `join_cons` is more general theorem join_cons_nil (a : α) (S) : join (cons (a, nil) S) = cons a (join S) := destruct_eq_cons <| by simp [join] --@[simp] -- Porting note: simp can prove: `join_cons` is more general theorem join_cons_cons (a b : α) (s S) : join (cons (a, cons b s) S) = cons a (join (cons (b, s) S)) := destruct_eq_cons <| by simp [join] @[simp] theorem join_cons (a : α) (s S) : join (cons (a, s) S) = cons a (append s (join S)) := by apply eq_of_bisim (fun s1 s2 => s1 = s2 ∨ ∃ a s S, s1 = join (cons (a, s) S) ∧ s2 = cons a (append s (join S))) _ (Or.inr ⟨a, s, S, rfl, rfl⟩) intro s1 s2 h exact match s1, s2, h with | s, _, Or.inl <| Eq.refl s => by apply recOn s; · trivial · intro x s rw [destruct_cons] exact ⟨rfl, Or.inl rfl⟩ | _, _, Or.inr ⟨a, s, S, rfl, rfl⟩ => by apply recOn s · simp [join_cons_cons, join_cons_nil] · intro x s simpa [join_cons_cons, join_cons_nil] using Or.inr ⟨x, s, S, rfl, rfl⟩ @[simp] theorem join_append (S T : Seq (Seq1 α)) : join (append S T) = append (join S) (join T) := by apply eq_of_bisim fun s1 s2 => ∃ s S T, s1 = append s (join (append S T)) ∧ s2 = append s (append (join S) (join T)) · intro s1 s2 h exact match s1, s2, h with | _, _, ⟨s, S, T, rfl, rfl⟩ => by apply recOn s <;> simp · apply recOn S <;> simp · apply recOn T · simp · intro s T cases' s with a s; simp only [join_cons, destruct_cons, true_and] refine ⟨s, nil, T, ?_, ?_⟩ <;> simp · intro s S cases' s with a s simpa using ⟨s, S, T, rfl, rfl⟩ · intro _ s exact ⟨s, S, T, rfl, rfl⟩ · refine ⟨nil, S, T, ?_, ?_⟩ <;> simp @[simp] theorem ofStream_cons (a : α) (s) : ofStream (a::s) = cons a (ofStream s) := by apply Subtype.eq; simp only [ofStream, cons]; rw [Stream'.map_cons] @[simp] theorem ofList_append (l l' : List α) : ofList (l ++ l') = append (ofList l) (ofList l') := by induction l <;> simp [*] @[simp] theorem ofStream_append (l : List α) (s : Stream' α) : ofStream (l ++ₛ s) = append (ofList l) (ofStream s) := by induction l <;> simp [*, Stream'.nil_append_stream, Stream'.cons_append_stream] /-- Convert a sequence into a list, embedded in a computation to allow for the possibility of infinite sequences (in which case the computation never returns anything). -/ def toList' {α} (s : Seq α) : Computation (List α) := @Computation.corec (List α) (List α × Seq α) (fun ⟨l, s⟩ => match destruct s with | none => Sum.inl l.reverse | some (a, s') => Sum.inr (a::l, s')) ([], s) theorem dropn_add (s : Seq α) (m) : ∀ n, drop s (m + n) = drop (drop s m) n | 0 => rfl | n + 1 => congr_arg tail (dropn_add s _ n) theorem dropn_tail (s : Seq α) (n) : drop (tail s) n = drop s (n + 1) := by rw [Nat.add_comm]; symm; apply dropn_add @[simp] theorem head_dropn (s : Seq α) (n) : head (drop s n) = get? s n := by induction' n with n IH generalizing s; · rfl rw [← get?_tail, ← dropn_tail]; apply IH theorem mem_map (f : α → β) {a : α} : ∀ {s : Seq α}, a ∈ s → f a ∈ map f s | ⟨_, _⟩ => Stream'.mem_map (Option.map f) theorem exists_of_mem_map {f} {b : β} : ∀ {s : Seq α}, b ∈ map f s → ∃ a, a ∈ s ∧ f a = b := fun {s} h => by match s with | ⟨g, al⟩ => let ⟨o, om, oe⟩ := @Stream'.exists_of_mem_map _ _ (Option.map f) (some b) g h cases' o with a · injection oe · injection oe with h'; exact ⟨a, om, h'⟩ theorem of_mem_append {s₁ s₂ : Seq α} {a : α} (h : a ∈ append s₁ s₂) : a ∈ s₁ ∨ a ∈ s₂ := by have := h; revert this generalize e : append s₁ s₂ = ss; intro h; revert s₁ apply mem_rec_on h _ intro b s' o s₁ apply s₁.recOn _ fun c t₁ => _ · intro m _ apply Or.inr simpa using m · intro c t₁ m e have this := congr_arg destruct e cases' show a = c ∨ a ∈ append t₁ s₂ by simpa using m with e' m · rw [e'] exact Or.inl (mem_cons _ _) · cases' show c = b ∧ append t₁ s₂ = s' by simpa with i1 i2 cases' o with e' IH · simp [i1, e'] · exact Or.imp_left (mem_cons_of_mem _) (IH m i2) theorem mem_append_left {s₁ s₂ : Seq α} {a : α} (h : a ∈ s₁) : a ∈ append s₁ s₂ := by apply mem_rec_on h; intros; simp [*] @[simp] theorem enum_cons (s : Seq α) (x : α) : enum (cons x s) = cons (0, x) (map (Prod.map Nat.succ id) (enum s)) := by ext ⟨n⟩ : 1 · simp · simp only [get?_enum, get?_cons_succ, map_get?, Option.map_map] congr end Seq namespace Seq1 variable {α : Type u} {β : Type v} {γ : Type w} open Stream'.Seq /-- Convert a `Seq1` to a sequence. -/ def toSeq : Seq1 α → Seq α | (a, s) => Seq.cons a s instance coeSeq : Coe (Seq1 α) (Seq α) := ⟨toSeq⟩ /-- Map a function on a `Seq1` -/ def map (f : α → β) : Seq1 α → Seq1 β | (a, s) => (f a, Seq.map f s) theorem map_pair {f : α → β} {a s} : map f (a, s) = (f a, Seq.map f s) := rfl theorem map_id : ∀ s : Seq1 α, map id s = s | ⟨a, s⟩ => by simp [map] /-- Flatten a nonempty sequence of nonempty sequences -/ def join : Seq1 (Seq1 α) → Seq1 α | ((a, s), S) => match destruct s with | none => (a, Seq.join S) | some s' => (a, Seq.join (Seq.cons s' S)) @[simp] theorem join_nil (a : α) (S) : join ((a, nil), S) = (a, Seq.join S) := rfl @[simp] theorem join_cons (a b : α) (s S) : join ((a, Seq.cons b s), S) = (a, Seq.join (Seq.cons (b, s) S)) := by dsimp [join]; rw [destruct_cons] /-- The `return` operator for the `Seq1` monad, which produces a singleton sequence. -/ def ret (a : α) : Seq1 α := (a, nil) instance [Inhabited α] : Inhabited (Seq1 α) := ⟨ret default⟩ /-- The `bind` operator for the `Seq1` monad, which maps `f` on each element of `s` and appends the results together. (Not all of `s` may be evaluated, because the first few elements of `s` may already produce an infinite result.) -/ def bind (s : Seq1 α) (f : α → Seq1 β) : Seq1 β := join (map f s) @[simp] theorem join_map_ret (s : Seq α) : Seq.join (Seq.map ret s) = s := by apply coinduction2 s; intro s; apply recOn s <;> simp [ret] @[simp] theorem bind_ret (f : α → β) : ∀ s, bind s (ret ∘ f) = map f s | ⟨a, s⟩ => by dsimp [bind, map] -- Porting note: Was `rw [map_comp]; simp [Function.comp, ret]` rw [map_comp, ret] simp @[simp] theorem ret_bind (a : α) (f : α → Seq1 β) : bind (ret a) f = f a := by simp only [bind, map, ret.eq_1, map_nil] cases' f a with a s apply recOn s <;> intros <;> simp @[simp] theorem map_join' (f : α → β) (S) : Seq.map f (Seq.join S) = Seq.join (Seq.map (map f) S) := by apply Seq.eq_of_bisim fun s1 s2 => ∃ s S, s1 = Seq.append s (Seq.map f (Seq.join S)) ∧ s2 = append s (Seq.join (Seq.map (map f) S)) · intro s1 s2 h exact match s1, s2, h with | _, _, ⟨s, S, rfl, rfl⟩ => by apply recOn s <;> simp · apply recOn S <;> simp · intro x S cases' x with a s simpa [map] using ⟨_, _, rfl, rfl⟩ · intro _ s exact ⟨s, S, rfl, rfl⟩ · refine ⟨nil, S, ?_, ?_⟩ <;> simp @[simp] theorem map_join (f : α → β) : ∀ S, map f (join S) = join (map (map f) S) | ((a, s), S) => by apply recOn s <;> intros <;> simp [map] @[simp] theorem join_join (SS : Seq (Seq1 (Seq1 α))) : Seq.join (Seq.join SS) = Seq.join (Seq.map join SS) := by apply Seq.eq_of_bisim fun s1 s2 => ∃ s SS, s1 = Seq.append s (Seq.join (Seq.join SS)) ∧ s2 = Seq.append s (Seq.join (Seq.map join SS)) · intro s1 s2 h exact match s1, s2, h with | _, _, ⟨s, SS, rfl, rfl⟩ => by apply recOn s <;> simp · apply recOn SS <;> simp · intro S SS cases' S with s S; cases' s with x s simp only [Seq.join_cons, join_append, destruct_cons] apply recOn s <;> simp · exact ⟨_, _, rfl, rfl⟩ · intro x s refine ⟨Seq.cons x (append s (Seq.join S)), SS, ?_, ?_⟩ <;> simp · intro _ s exact ⟨s, SS, rfl, rfl⟩ · refine ⟨nil, SS, ?_, ?_⟩ <;> simp @[simp] theorem bind_assoc (s : Seq1 α) (f : α → Seq1 β) (g : β → Seq1 γ) : bind (bind s f) g = bind s fun x : α => bind (f x) g := by cases' s with a s -- porting note (#10745): was `simp [bind, map]`. simp only [bind, map_pair, map_join] rw [← map_comp] simp only [show (fun x => join (map g (f x))) = join ∘ (map g ∘ f) from rfl] rw [map_comp _ join] generalize Seq.map (map g ∘ f) s = SS rcases map g (f a) with ⟨⟨a, s⟩, S⟩ -- Porting note: Instead of `apply recOn s <;> intros`, `induction'` are used to -- give names to variables. induction' s using recOn with x s_1 <;> induction' S using recOn with x_1 s_2 <;> simp · cases' x_1 with x t apply recOn t <;> intros <;> simp · cases' x_1 with y t; simp instance monad : Monad Seq1 where map := @map pure := @ret bind := @bind instance lawfulMonad : LawfulMonad Seq1 := LawfulMonad.mk' (id_map := @map_id) (bind_pure_comp := @bind_ret) (pure_bind := @ret_bind) (bind_assoc := @bind_assoc) end Seq1 end Stream'
Data\Seq\WSeq.lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Logic.Relation import Mathlib.Data.Option.Basic import Mathlib.Data.Seq.Seq import Batteries.Data.DList /-! # Partially defined possibly infinite lists This file provides a `WSeq α` type representing partially defined possibly infinite lists (referred here as weak sequences). -/ namespace Stream' open Function universe u v w /- coinductive WSeq (α : Type u) : Type u | nil : WSeq α | cons : α → WSeq α → WSeq α | think : WSeq α → WSeq α -/ /-- Weak sequences. While the `Seq` structure allows for lists which may not be finite, a weak sequence also allows the computation of each element to involve an indeterminate amount of computation, including possibly an infinite loop. This is represented as a regular `Seq` interspersed with `none` elements to indicate that computation is ongoing. This model is appropriate for Haskell style lazy lists, and is closed under most interesting computation patterns on infinite lists, but conversely it is difficult to extract elements from it. -/ def WSeq (α) := Seq (Option α) /- coinductive WSeq (α : Type u) : Type u | nil : WSeq α | cons : α → WSeq α → WSeq α | think : WSeq α → WSeq α -/ namespace WSeq variable {α : Type u} {β : Type v} {γ : Type w} /-- Turn a sequence into a weak sequence -/ @[coe] def ofSeq : Seq α → WSeq α := (· <$> ·) some /-- Turn a list into a weak sequence -/ @[coe] def ofList (l : List α) : WSeq α := ofSeq l /-- Turn a stream into a weak sequence -/ @[coe] def ofStream (l : Stream' α) : WSeq α := ofSeq l instance coeSeq : Coe (Seq α) (WSeq α) := ⟨ofSeq⟩ instance coeList : Coe (List α) (WSeq α) := ⟨ofList⟩ instance coeStream : Coe (Stream' α) (WSeq α) := ⟨ofStream⟩ /-- The empty weak sequence -/ def nil : WSeq α := Seq.nil instance inhabited : Inhabited (WSeq α) := ⟨nil⟩ /-- Prepend an element to a weak sequence -/ def cons (a : α) : WSeq α → WSeq α := Seq.cons (some a) /-- Compute for one tick, without producing any elements -/ def think : WSeq α → WSeq α := Seq.cons none /-- Destruct a weak sequence, to (eventually possibly) produce either `none` for `nil` or `some (a, s)` if an element is produced. -/ def destruct : WSeq α → Computation (Option (α × WSeq α)) := Computation.corec fun s => match Seq.destruct s with | none => Sum.inl none | some (none, s') => Sum.inr s' | some (some a, s') => Sum.inl (some (a, s')) /-- Recursion principle for weak sequences, compare with `List.recOn`. -/ def recOn {C : WSeq α → Sort v} (s : WSeq α) (h1 : C nil) (h2 : ∀ x s, C (cons x s)) (h3 : ∀ s, C (think s)) : C s := Seq.recOn s h1 fun o => Option.recOn o h3 h2 /-- membership for weak sequences-/ protected def Mem (a : α) (s : WSeq α) := Seq.Mem (some a) s instance membership : Membership α (WSeq α) := ⟨WSeq.Mem⟩ theorem not_mem_nil (a : α) : a ∉ @nil α := Seq.not_mem_nil (some a) /-- Get the head of a weak sequence. This involves a possibly infinite computation. -/ def head (s : WSeq α) : Computation (Option α) := Computation.map (Prod.fst <$> ·) (destruct s) /-- Encode a computation yielding a weak sequence into additional `think` constructors in a weak sequence -/ def flatten : Computation (WSeq α) → WSeq α := Seq.corec fun c => match Computation.destruct c with | Sum.inl s => Seq.omap (return ·) (Seq.destruct s) | Sum.inr c' => some (none, c') /-- Get the tail of a weak sequence. This doesn't need a `Computation` wrapper, unlike `head`, because `flatten` allows us to hide this in the construction of the weak sequence itself. -/ def tail (s : WSeq α) : WSeq α := flatten <| (fun o => Option.recOn o nil Prod.snd) <$> destruct s /-- drop the first `n` elements from `s`. -/ def drop (s : WSeq α) : ℕ → WSeq α | 0 => s | n + 1 => tail (drop s n) /-- Get the nth element of `s`. -/ def get? (s : WSeq α) (n : ℕ) : Computation (Option α) := head (drop s n) /-- Convert `s` to a list (if it is finite and completes in finite time). -/ def toList (s : WSeq α) : Computation (List α) := @Computation.corec (List α) (List α × WSeq α) (fun ⟨l, s⟩ => match Seq.destruct s with | none => Sum.inl l.reverse | some (none, s') => Sum.inr (l, s') | some (some a, s') => Sum.inr (a::l, s')) ([], s) /-- Get the length of `s` (if it is finite and completes in finite time). -/ def length (s : WSeq α) : Computation ℕ := @Computation.corec ℕ (ℕ × WSeq α) (fun ⟨n, s⟩ => match Seq.destruct s with | none => Sum.inl n | some (none, s') => Sum.inr (n, s') | some (some _, s') => Sum.inr (n + 1, s')) (0, s) /-- A weak sequence is finite if `toList s` terminates. Equivalently, it is a finite number of `think` and `cons` applied to `nil`. -/ class IsFinite (s : WSeq α) : Prop where out : (toList s).Terminates instance toList_terminates (s : WSeq α) [h : IsFinite s] : (toList s).Terminates := h.out /-- Get the list corresponding to a finite weak sequence. -/ def get (s : WSeq α) [IsFinite s] : List α := (toList s).get /-- A weak sequence is *productive* if it never stalls forever - there are always a finite number of `think`s between `cons` constructors. The sequence itself is allowed to be infinite though. -/ class Productive (s : WSeq α) : Prop where get?_terminates : ∀ n, (get? s n).Terminates theorem productive_iff (s : WSeq α) : Productive s ↔ ∀ n, (get? s n).Terminates := ⟨fun h => h.1, fun h => ⟨h⟩⟩ instance get?_terminates (s : WSeq α) [h : Productive s] : ∀ n, (get? s n).Terminates := h.get?_terminates instance head_terminates (s : WSeq α) [Productive s] : (head s).Terminates := s.get?_terminates 0 /-- Replace the `n`th element of `s` with `a`. -/ def updateNth (s : WSeq α) (n : ℕ) (a : α) : WSeq α := @Seq.corec (Option α) (ℕ × WSeq α) (fun ⟨n, s⟩ => match Seq.destruct s, n with | none, _ => none | some (none, s'), n => some (none, n, s') | some (some a', s'), 0 => some (some a', 0, s') | some (some _, s'), 1 => some (some a, 0, s') | some (some a', s'), n + 2 => some (some a', n + 1, s')) (n + 1, s) /-- Remove the `n`th element of `s`. -/ def removeNth (s : WSeq α) (n : ℕ) : WSeq α := @Seq.corec (Option α) (ℕ × WSeq α) (fun ⟨n, s⟩ => match Seq.destruct s, n with | none, _ => none | some (none, s'), n => some (none, n, s') | some (some a', s'), 0 => some (some a', 0, s') | some (some _, s'), 1 => some (none, 0, s') | some (some a', s'), n + 2 => some (some a', n + 1, s')) (n + 1, s) /-- Map the elements of `s` over `f`, removing any values that yield `none`. -/ def filterMap (f : α → Option β) : WSeq α → WSeq β := Seq.corec fun s => match Seq.destruct s with | none => none | some (none, s') => some (none, s') | some (some a, s') => some (f a, s') /-- Select the elements of `s` that satisfy `p`. -/ def filter (p : α → Prop) [DecidablePred p] : WSeq α → WSeq α := filterMap fun a => if p a then some a else none -- example of infinite list manipulations /-- Get the first element of `s` satisfying `p`. -/ def find (p : α → Prop) [DecidablePred p] (s : WSeq α) : Computation (Option α) := head <| filter p s /-- Zip a function over two weak sequences -/ def zipWith (f : α → β → γ) (s1 : WSeq α) (s2 : WSeq β) : WSeq γ := @Seq.corec (Option γ) (WSeq α × WSeq β) (fun ⟨s1, s2⟩ => match Seq.destruct s1, Seq.destruct s2 with | some (none, s1'), some (none, s2') => some (none, s1', s2') | some (some _, _), some (none, s2') => some (none, s1, s2') | some (none, s1'), some (some _, _) => some (none, s1', s2) | some (some a1, s1'), some (some a2, s2') => some (some (f a1 a2), s1', s2') | _, _ => none) (s1, s2) /-- Zip two weak sequences into a single sequence of pairs -/ def zip : WSeq α → WSeq β → WSeq (α × β) := zipWith Prod.mk /-- Get the list of indexes of elements of `s` satisfying `p` -/ def findIndexes (p : α → Prop) [DecidablePred p] (s : WSeq α) : WSeq ℕ := (zip s (Stream'.nats : WSeq ℕ)).filterMap fun ⟨a, n⟩ => if p a then some n else none /-- Get the index of the first element of `s` satisfying `p` -/ def findIndex (p : α → Prop) [DecidablePred p] (s : WSeq α) : Computation ℕ := (fun o => Option.getD o 0) <$> head (findIndexes p s) /-- Get the index of the first occurrence of `a` in `s` -/ def indexOf [DecidableEq α] (a : α) : WSeq α → Computation ℕ := findIndex (Eq a) /-- Get the indexes of occurrences of `a` in `s` -/ def indexesOf [DecidableEq α] (a : α) : WSeq α → WSeq ℕ := findIndexes (Eq a) /-- `union s1 s2` is a weak sequence which interleaves `s1` and `s2` in some order (nondeterministically). -/ def union (s1 s2 : WSeq α) : WSeq α := @Seq.corec (Option α) (WSeq α × WSeq α) (fun ⟨s1, s2⟩ => match Seq.destruct s1, Seq.destruct s2 with | none, none => none | some (a1, s1'), none => some (a1, s1', nil) | none, some (a2, s2') => some (a2, nil, s2') | some (none, s1'), some (none, s2') => some (none, s1', s2') | some (some a1, s1'), some (none, s2') => some (some a1, s1', s2') | some (none, s1'), some (some a2, s2') => some (some a2, s1', s2') | some (some a1, s1'), some (some a2, s2') => some (some a1, cons a2 s1', s2')) (s1, s2) /-- Returns `true` if `s` is `nil` and `false` if `s` has an element -/ def isEmpty (s : WSeq α) : Computation Bool := Computation.map Option.isNone <| head s /-- Calculate one step of computation -/ def compute (s : WSeq α) : WSeq α := match Seq.destruct s with | some (none, s') => s' | _ => s /-- Get the first `n` elements of a weak sequence -/ def take (s : WSeq α) (n : ℕ) : WSeq α := @Seq.corec (Option α) (ℕ × WSeq α) (fun ⟨n, s⟩ => match n, Seq.destruct s with | 0, _ => none | _ + 1, none => none | m + 1, some (none, s') => some (none, m + 1, s') | m + 1, some (some a, s') => some (some a, m, s')) (n, s) /-- Split the sequence at position `n` into a finite initial segment and the weak sequence tail -/ def splitAt (s : WSeq α) (n : ℕ) : Computation (List α × WSeq α) := @Computation.corec (List α × WSeq α) (ℕ × List α × WSeq α) (fun ⟨n, l, s⟩ => match n, Seq.destruct s with | 0, _ => Sum.inl (l.reverse, s) | _ + 1, none => Sum.inl (l.reverse, s) | _ + 1, some (none, s') => Sum.inr (n, l, s') | m + 1, some (some a, s') => Sum.inr (m, a::l, s')) (n, [], s) /-- Returns `true` if any element of `s` satisfies `p` -/ def any (s : WSeq α) (p : α → Bool) : Computation Bool := Computation.corec (fun s : WSeq α => match Seq.destruct s with | none => Sum.inl false | some (none, s') => Sum.inr s' | some (some a, s') => if p a then Sum.inl true else Sum.inr s') s /-- Returns `true` if every element of `s` satisfies `p` -/ def all (s : WSeq α) (p : α → Bool) : Computation Bool := Computation.corec (fun s : WSeq α => match Seq.destruct s with | none => Sum.inl true | some (none, s') => Sum.inr s' | some (some a, s') => if p a then Sum.inr s' else Sum.inl false) s /-- Apply a function to the elements of the sequence to produce a sequence of partial results. (There is no `scanr` because this would require working from the end of the sequence, which may not exist.) -/ def scanl (f : α → β → α) (a : α) (s : WSeq β) : WSeq α := cons a <| @Seq.corec (Option α) (α × WSeq β) (fun ⟨a, s⟩ => match Seq.destruct s with | none => none | some (none, s') => some (none, a, s') | some (some b, s') => let a' := f a b some (some a', a', s')) (a, s) /-- Get the weak sequence of initial segments of the input sequence -/ def inits (s : WSeq α) : WSeq (List α) := cons [] <| @Seq.corec (Option (List α)) (Batteries.DList α × WSeq α) (fun ⟨l, s⟩ => match Seq.destruct s with | none => none | some (none, s') => some (none, l, s') | some (some a, s') => let l' := l.push a some (some l'.toList, l', s')) (Batteries.DList.empty, s) /-- Like take, but does not wait for a result. Calculates `n` steps of computation and returns the sequence computed so far -/ def collect (s : WSeq α) (n : ℕ) : List α := (Seq.take n s).filterMap id /-- Append two weak sequences. As with `Seq.append`, this may not use the second sequence if the first one takes forever to compute -/ def append : WSeq α → WSeq α → WSeq α := Seq.append /-- Map a function over a weak sequence -/ def map (f : α → β) : WSeq α → WSeq β := Seq.map (Option.map f) /-- Flatten a sequence of weak sequences. (Note that this allows empty sequences, unlike `Seq.join`.) -/ def join (S : WSeq (WSeq α)) : WSeq α := Seq.join ((fun o : Option (WSeq α) => match o with | none => Seq1.ret none | some s => (none, s)) <$> S) /-- Monadic bind operator for weak sequences -/ def bind (s : WSeq α) (f : α → WSeq β) : WSeq β := join (map f s) /-- lift a relation to a relation over weak sequences -/ @[simp] def LiftRelO (R : α → β → Prop) (C : WSeq α → WSeq β → Prop) : Option (α × WSeq α) → Option (β × WSeq β) → Prop | none, none => True | some (a, s), some (b, t) => R a b ∧ C s t | _, _ => False theorem LiftRelO.imp {R S : α → β → Prop} {C D : WSeq α → WSeq β → Prop} (H1 : ∀ a b, R a b → S a b) (H2 : ∀ s t, C s t → D s t) : ∀ {o p}, LiftRelO R C o p → LiftRelO S D o p | none, none, _ => trivial | some (_, _), some (_, _), h => And.imp (H1 _ _) (H2 _ _) h | none, some _, h => False.elim h | some (_, _), none, h => False.elim h theorem LiftRelO.imp_right (R : α → β → Prop) {C D : WSeq α → WSeq β → Prop} (H : ∀ s t, C s t → D s t) {o p} : LiftRelO R C o p → LiftRelO R D o p := LiftRelO.imp (fun _ _ => id) H /-- Definition of bisimilarity for weak sequences-/ @[simp] def BisimO (R : WSeq α → WSeq α → Prop) : Option (α × WSeq α) → Option (α × WSeq α) → Prop := LiftRelO (· = ·) R theorem BisimO.imp {R S : WSeq α → WSeq α → Prop} (H : ∀ s t, R s t → S s t) {o p} : BisimO R o p → BisimO S o p := LiftRelO.imp_right _ H /-- Two weak sequences are `LiftRel R` related if they are either both empty, or they are both nonempty and the heads are `R` related and the tails are `LiftRel R` related. (This is a coinductive definition.) -/ def LiftRel (R : α → β → Prop) (s : WSeq α) (t : WSeq β) : Prop := ∃ C : WSeq α → WSeq β → Prop, C s t ∧ ∀ {s t}, C s t → Computation.LiftRel (LiftRelO R C) (destruct s) (destruct t) /-- If two sequences are equivalent, then they have the same values and the same computational behavior (i.e. if one loops forever then so does the other), although they may differ in the number of `think`s needed to arrive at the answer. -/ def Equiv : WSeq α → WSeq α → Prop := LiftRel (· = ·) theorem liftRel_destruct {R : α → β → Prop} {s : WSeq α} {t : WSeq β} : LiftRel R s t → Computation.LiftRel (LiftRelO R (LiftRel R)) (destruct s) (destruct t) | ⟨R, h1, h2⟩ => by refine Computation.LiftRel.imp ?_ _ _ (h2 h1) apply LiftRelO.imp_right exact fun s' t' h' => ⟨R, h', @h2⟩ theorem liftRel_destruct_iff {R : α → β → Prop} {s : WSeq α} {t : WSeq β} : LiftRel R s t ↔ Computation.LiftRel (LiftRelO R (LiftRel R)) (destruct s) (destruct t) := ⟨liftRel_destruct, fun h => ⟨fun s t => LiftRel R s t ∨ Computation.LiftRel (LiftRelO R (LiftRel R)) (destruct s) (destruct t), Or.inr h, fun {s t} h => by have h : Computation.LiftRel (LiftRelO R (LiftRel R)) (destruct s) (destruct t) := by cases' h with h h · exact liftRel_destruct h · assumption apply Computation.LiftRel.imp _ _ _ h intro a b apply LiftRelO.imp_right intro s t apply Or.inl⟩⟩ -- Porting note: To avoid ambiguous notation, `~` became `~ʷ`. infixl:50 " ~ʷ " => Equiv theorem destruct_congr {s t : WSeq α} : s ~ʷ t → Computation.LiftRel (BisimO (· ~ʷ ·)) (destruct s) (destruct t) := liftRel_destruct theorem destruct_congr_iff {s t : WSeq α} : s ~ʷ t ↔ Computation.LiftRel (BisimO (· ~ʷ ·)) (destruct s) (destruct t) := liftRel_destruct_iff theorem LiftRel.refl (R : α → α → Prop) (H : Reflexive R) : Reflexive (LiftRel R) := fun s => by refine ⟨(· = ·), rfl, fun {s t} (h : s = t) => ?_⟩ rw [← h] apply Computation.LiftRel.refl intro a cases' a with a · simp · cases a simp only [LiftRelO, and_true] apply H theorem LiftRelO.swap (R : α → β → Prop) (C) : swap (LiftRelO R C) = LiftRelO (swap R) (swap C) := by funext x y rcases x with ⟨⟩ | ⟨hx, jx⟩ <;> rcases y with ⟨⟩ | ⟨hy, jy⟩ <;> rfl theorem LiftRel.swap_lem {R : α → β → Prop} {s1 s2} (h : LiftRel R s1 s2) : LiftRel (swap R) s2 s1 := by refine ⟨swap (LiftRel R), h, fun {s t} (h : LiftRel R t s) => ?_⟩ rw [← LiftRelO.swap, Computation.LiftRel.swap] apply liftRel_destruct h theorem LiftRel.swap (R : α → β → Prop) : swap (LiftRel R) = LiftRel (swap R) := funext fun _ => funext fun _ => propext ⟨LiftRel.swap_lem, LiftRel.swap_lem⟩ theorem LiftRel.symm (R : α → α → Prop) (H : Symmetric R) : Symmetric (LiftRel R) := fun s1 s2 (h : Function.swap (LiftRel R) s2 s1) => by rwa [LiftRel.swap, H.swap_eq] at h theorem LiftRel.trans (R : α → α → Prop) (H : Transitive R) : Transitive (LiftRel R) := fun s t u h1 h2 => by refine ⟨fun s u => ∃ t, LiftRel R s t ∧ LiftRel R t u, ⟨t, h1, h2⟩, fun {s u} h => ?_⟩ rcases h with ⟨t, h1, h2⟩ have h1 := liftRel_destruct h1 have h2 := liftRel_destruct h2 refine Computation.liftRel_def.2 ⟨(Computation.terminates_of_liftRel h1).trans (Computation.terminates_of_liftRel h2), fun {a c} ha hc => ?_⟩ rcases h1.left ha with ⟨b, hb, t1⟩ have t2 := Computation.rel_of_liftRel h2 hb hc cases' a with a <;> cases' c with c · trivial · cases b · cases t2 · cases t1 · cases a cases' b with b · cases t1 · cases b cases t2 · cases' a with a s cases' b with b · cases t1 cases' b with b t cases' c with c u cases' t1 with ab st cases' t2 with bc tu exact ⟨H ab bc, t, st, tu⟩ theorem LiftRel.equiv (R : α → α → Prop) : Equivalence R → Equivalence (LiftRel R) | ⟨refl, symm, trans⟩ => ⟨LiftRel.refl R refl, @(LiftRel.symm R @symm), @(LiftRel.trans R @trans)⟩ @[refl] theorem Equiv.refl : ∀ s : WSeq α, s ~ʷ s := LiftRel.refl (· = ·) Eq.refl @[symm] theorem Equiv.symm : ∀ {s t : WSeq α}, s ~ʷ t → t ~ʷ s := @(LiftRel.symm (· = ·) (@Eq.symm _)) @[trans] theorem Equiv.trans : ∀ {s t u : WSeq α}, s ~ʷ t → t ~ʷ u → s ~ʷ u := @(LiftRel.trans (· = ·) (@Eq.trans _)) theorem Equiv.equivalence : Equivalence (@Equiv α) := ⟨@Equiv.refl _, @Equiv.symm _, @Equiv.trans _⟩ open Computation @[simp] theorem destruct_nil : destruct (nil : WSeq α) = Computation.pure none := Computation.destruct_eq_pure rfl @[simp] theorem destruct_cons (a : α) (s) : destruct (cons a s) = Computation.pure (some (a, s)) := Computation.destruct_eq_pure <| by simp [destruct, cons, Computation.rmap] @[simp] theorem destruct_think (s : WSeq α) : destruct (think s) = (destruct s).think := Computation.destruct_eq_think <| by simp [destruct, think, Computation.rmap] @[simp] theorem seq_destruct_nil : Seq.destruct (nil : WSeq α) = none := Seq.destruct_nil @[simp] theorem seq_destruct_cons (a : α) (s) : Seq.destruct (cons a s) = some (some a, s) := Seq.destruct_cons _ _ @[simp] theorem seq_destruct_think (s : WSeq α) : Seq.destruct (think s) = some (none, s) := Seq.destruct_cons _ _ @[simp] theorem head_nil : head (nil : WSeq α) = Computation.pure none := by simp [head] @[simp] theorem head_cons (a : α) (s) : head (cons a s) = Computation.pure (some a) := by simp [head] @[simp] theorem head_think (s : WSeq α) : head (think s) = (head s).think := by simp [head] @[simp] theorem flatten_pure (s : WSeq α) : flatten (Computation.pure s) = s := by refine Seq.eq_of_bisim (fun s1 s2 => flatten (Computation.pure s2) = s1) ?_ rfl intro s' s h rw [← h] simp only [Seq.BisimO, flatten, Seq.omap, pure_def, Seq.corec_eq, destruct_pure] cases Seq.destruct s with | none => simp | some val => cases' val with o s' simp @[simp] theorem flatten_think (c : Computation (WSeq α)) : flatten c.think = think (flatten c) := Seq.destruct_eq_cons <| by simp [flatten, think] @[simp] theorem destruct_flatten (c : Computation (WSeq α)) : destruct (flatten c) = c >>= destruct := by refine Computation.eq_of_bisim (fun c1 c2 => c1 = c2 ∨ ∃ c, c1 = destruct (flatten c) ∧ c2 = Computation.bind c destruct) ?_ (Or.inr ⟨c, rfl, rfl⟩) intro c1 c2 h exact match c1, c2, h with | c, _, Or.inl rfl => by cases c.destruct <;> simp | _, _, Or.inr ⟨c, rfl, rfl⟩ => by induction' c using Computation.recOn with a c' · simp; cases (destruct a).destruct <;> simp · simpa using Or.inr ⟨c', rfl, rfl⟩ theorem head_terminates_iff (s : WSeq α) : Terminates (head s) ↔ Terminates (destruct s) := terminates_map_iff _ (destruct s) @[simp] theorem tail_nil : tail (nil : WSeq α) = nil := by simp [tail] @[simp] theorem tail_cons (a : α) (s) : tail (cons a s) = s := by simp [tail] @[simp] theorem tail_think (s : WSeq α) : tail (think s) = (tail s).think := by simp [tail] @[simp] theorem dropn_nil (n) : drop (nil : WSeq α) n = nil := by induction n <;> simp [*, drop] @[simp] theorem dropn_cons (a : α) (s) (n) : drop (cons a s) (n + 1) = drop s n := by induction n with | zero => simp [drop] | succ n n_ih => -- porting note (#10745): was `simp [*, drop]`. simp [drop, ← n_ih] @[simp] theorem dropn_think (s : WSeq α) (n) : drop (think s) n = (drop s n).think := by induction n <;> simp [*, drop] theorem dropn_add (s : WSeq α) (m) : ∀ n, drop s (m + n) = drop (drop s m) n | 0 => rfl | n + 1 => congr_arg tail (dropn_add s m n) theorem dropn_tail (s : WSeq α) (n) : drop (tail s) n = drop s (n + 1) := by rw [Nat.add_comm] symm apply dropn_add theorem get?_add (s : WSeq α) (m n) : get? s (m + n) = get? (drop s m) n := congr_arg head (dropn_add _ _ _) theorem get?_tail (s : WSeq α) (n) : get? (tail s) n = get? s (n + 1) := congr_arg head (dropn_tail _ _) @[simp] theorem join_nil : join nil = (nil : WSeq α) := Seq.join_nil @[simp] theorem join_think (S : WSeq (WSeq α)) : join (think S) = think (join S) := by simp only [join, think] dsimp only [(· <$> ·)] simp [join, Seq1.ret] @[simp] theorem join_cons (s : WSeq α) (S) : join (cons s S) = think (append s (join S)) := by simp only [join, think] dsimp only [(· <$> ·)] simp [join, cons, append] @[simp] theorem nil_append (s : WSeq α) : append nil s = s := Seq.nil_append _ @[simp] theorem cons_append (a : α) (s t) : append (cons a s) t = cons a (append s t) := Seq.cons_append _ _ _ @[simp] theorem think_append (s t : WSeq α) : append (think s) t = think (append s t) := Seq.cons_append _ _ _ @[simp] theorem append_nil (s : WSeq α) : append s nil = s := Seq.append_nil _ @[simp] theorem append_assoc (s t u : WSeq α) : append (append s t) u = append s (append t u) := Seq.append_assoc _ _ _ /-- auxiliary definition of tail over weak sequences-/ @[simp] def tail.aux : Option (α × WSeq α) → Computation (Option (α × WSeq α)) | none => Computation.pure none | some (_, s) => destruct s theorem destruct_tail (s : WSeq α) : destruct (tail s) = destruct s >>= tail.aux := by simp only [tail, destruct_flatten, tail.aux]; rw [← bind_pure_comp, LawfulMonad.bind_assoc] apply congr_arg; ext1 (_ | ⟨a, s⟩) <;> apply (@pure_bind Computation _ _ _ _ _ _).trans _ <;> simp /-- auxiliary definition of drop over weak sequences-/ @[simp] def drop.aux : ℕ → Option (α × WSeq α) → Computation (Option (α × WSeq α)) | 0 => Computation.pure | n + 1 => fun a => tail.aux a >>= drop.aux n theorem drop.aux_none : ∀ n, @drop.aux α n none = Computation.pure none | 0 => rfl | n + 1 => show Computation.bind (Computation.pure none) (drop.aux n) = Computation.pure none by rw [ret_bind, drop.aux_none n] theorem destruct_dropn : ∀ (s : WSeq α) (n), destruct (drop s n) = destruct s >>= drop.aux n | s, 0 => (bind_pure' _).symm | s, n + 1 => by rw [← dropn_tail, destruct_dropn _ n, destruct_tail, LawfulMonad.bind_assoc] rfl theorem head_terminates_of_head_tail_terminates (s : WSeq α) [T : Terminates (head (tail s))] : Terminates (head s) := (head_terminates_iff _).2 <| by rcases (head_terminates_iff _).1 T with ⟨⟨a, h⟩⟩ simp? [tail] at h says simp only [tail, destruct_flatten] at h rcases exists_of_mem_bind h with ⟨s', h1, _⟩ unfold Functor.map at h1 exact let ⟨t, h3, _⟩ := Computation.exists_of_mem_map h1 Computation.terminates_of_mem h3 theorem destruct_some_of_destruct_tail_some {s : WSeq α} {a} (h : some a ∈ destruct (tail s)) : ∃ a', some a' ∈ destruct s := by unfold tail Functor.map at h; simp only [destruct_flatten] at h rcases exists_of_mem_bind h with ⟨t, tm, td⟩; clear h rcases Computation.exists_of_mem_map tm with ⟨t', ht', ht2⟩; clear tm cases' t' with t' <;> rw [← ht2] at td <;> simp only [destruct_nil] at td · have := mem_unique td (ret_mem _) contradiction · exact ⟨_, ht'⟩ theorem head_some_of_head_tail_some {s : WSeq α} {a} (h : some a ∈ head (tail s)) : ∃ a', some a' ∈ head s := by unfold head at h rcases Computation.exists_of_mem_map h with ⟨o, md, e⟩; clear h cases' o with o <;> [injection e; injection e with h']; clear h' cases' destruct_some_of_destruct_tail_some md with a am exact ⟨_, Computation.mem_map (@Prod.fst α (WSeq α) <$> ·) am⟩ theorem head_some_of_get?_some {s : WSeq α} {a n} (h : some a ∈ get? s n) : ∃ a', some a' ∈ head s := by induction n generalizing a with | zero => exact ⟨_, h⟩ | succ n IH => let ⟨a', h'⟩ := head_some_of_head_tail_some h exact IH h' instance productive_tail (s : WSeq α) [Productive s] : Productive (tail s) := ⟨fun n => by rw [get?_tail]; infer_instance⟩ instance productive_dropn (s : WSeq α) [Productive s] (n) : Productive (drop s n) := ⟨fun m => by rw [← get?_add]; infer_instance⟩ /-- Given a productive weak sequence, we can collapse all the `think`s to produce a sequence. -/ def toSeq (s : WSeq α) [Productive s] : Seq α := ⟨fun n => (get? s n).get, fun {n} h => by cases e : Computation.get (get? s (n + 1)) · assumption have := Computation.mem_of_get_eq _ e simp? [get?] at this h says simp only [get?] at this h cases' head_some_of_head_tail_some this with a' h' have := mem_unique h' (@Computation.mem_of_get_eq _ _ _ _ h) contradiction⟩ theorem get?_terminates_le {s : WSeq α} {m n} (h : m ≤ n) : Terminates (get? s n) → Terminates (get? s m) := by induction' h with m' _ IH exacts [id, fun T => IH (@head_terminates_of_head_tail_terminates _ _ T)] theorem head_terminates_of_get?_terminates {s : WSeq α} {n} : Terminates (get? s n) → Terminates (head s) := get?_terminates_le (Nat.zero_le n) theorem destruct_terminates_of_get?_terminates {s : WSeq α} {n} (T : Terminates (get? s n)) : Terminates (destruct s) := (head_terminates_iff _).1 <| head_terminates_of_get?_terminates T theorem mem_rec_on {C : WSeq α → Prop} {a s} (M : a ∈ s) (h1 : ∀ b s', a = b ∨ C s' → C (cons b s')) (h2 : ∀ s, C s → C (think s)) : C s := by apply Seq.mem_rec_on M intro o s' h; cases' o with b · apply h2 cases h · contradiction · assumption · apply h1 apply Or.imp_left _ h intro h injection h @[simp] theorem mem_think (s : WSeq α) (a) : a ∈ think s ↔ a ∈ s := by cases' s with f al change (some (some a) ∈ some none::f) ↔ some (some a) ∈ f constructor <;> intro h · apply (Stream'.eq_or_mem_of_mem_cons h).resolve_left intro injections · apply Stream'.mem_cons_of_mem _ h theorem eq_or_mem_iff_mem {s : WSeq α} {a a' s'} : some (a', s') ∈ destruct s → (a ∈ s ↔ a = a' ∨ a ∈ s') := by generalize e : destruct s = c; intro h revert s apply Computation.memRecOn h <;> [skip; intro c IH] <;> intro s <;> induction' s using WSeq.recOn with x s s <;> intro m <;> have := congr_arg Computation.destruct m <;> simp at this · cases' this with i1 i2 rw [i1, i2] cases' s' with f al dsimp only [cons, (· ∈ ·), WSeq.Mem, Seq.Mem, Seq.cons] have h_a_eq_a' : a = a' ↔ some (some a) = some (some a') := by simp rw [h_a_eq_a'] refine ⟨Stream'.eq_or_mem_of_mem_cons, fun o => ?_⟩ · cases' o with e m · rw [e] apply Stream'.mem_cons · exact Stream'.mem_cons_of_mem _ m · simp [IH this] @[simp] theorem mem_cons_iff (s : WSeq α) (b) {a} : a ∈ cons b s ↔ a = b ∨ a ∈ s := eq_or_mem_iff_mem <| by simp [ret_mem] theorem mem_cons_of_mem {s : WSeq α} (b) {a} (h : a ∈ s) : a ∈ cons b s := (mem_cons_iff _ _).2 (Or.inr h) theorem mem_cons (s : WSeq α) (a) : a ∈ cons a s := (mem_cons_iff _ _).2 (Or.inl rfl) theorem mem_of_mem_tail {s : WSeq α} {a} : a ∈ tail s → a ∈ s := by intro h; have := h; cases' h with n e; revert s; simp only [Stream'.get] induction' n with n IH <;> intro s <;> induction' s using WSeq.recOn with x s s <;> simp <;> intro m e <;> injections · exact Or.inr m · exact Or.inr m · apply IH m rw [e] cases tail s rfl theorem mem_of_mem_dropn {s : WSeq α} {a} : ∀ {n}, a ∈ drop s n → a ∈ s | 0, h => h | n + 1, h => @mem_of_mem_dropn s a n (mem_of_mem_tail h) theorem get?_mem {s : WSeq α} {a n} : some a ∈ get? s n → a ∈ s := by revert s; induction' n with n IH <;> intro s h · -- Porting note: This line is required to infer metavariables in -- `Computation.exists_of_mem_map`. dsimp only [get?, head] at h rcases Computation.exists_of_mem_map h with ⟨o, h1, h2⟩ cases' o with o · injection h2 injection h2 with h' cases' o with a' s' exact (eq_or_mem_iff_mem h1).2 (Or.inl h'.symm) · have := @IH (tail s) rw [get?_tail] at this exact mem_of_mem_tail (this h) theorem exists_get?_of_mem {s : WSeq α} {a} (h : a ∈ s) : ∃ n, some a ∈ get? s n := by apply mem_rec_on h · intro a' s' h cases' h with h h · exists 0 simp only [get?, drop, head_cons] rw [h] apply ret_mem · cases' h with n h exists n + 1 -- porting note (#10745): was `simp [get?]`. simpa [get?] · intro s' h cases' h with n h exists n simp only [get?, dropn_think, head_think] apply think_mem h theorem exists_dropn_of_mem {s : WSeq α} {a} (h : a ∈ s) : ∃ n s', some (a, s') ∈ destruct (drop s n) := let ⟨n, h⟩ := exists_get?_of_mem h ⟨n, by rcases (head_terminates_iff _).1 ⟨⟨_, h⟩⟩ with ⟨⟨o, om⟩⟩ have := Computation.mem_unique (Computation.mem_map _ om) h cases' o with o · injection this injection this with i cases' o with a' s' dsimp at i rw [i] at om exact ⟨_, om⟩⟩ theorem liftRel_dropn_destruct {R : α → β → Prop} {s t} (H : LiftRel R s t) : ∀ n, Computation.LiftRel (LiftRelO R (LiftRel R)) (destruct (drop s n)) (destruct (drop t n)) | 0 => liftRel_destruct H | n + 1 => by simp only [LiftRelO, drop, Nat.add_eq, Nat.add_zero, destruct_tail, tail.aux] apply liftRel_bind · apply liftRel_dropn_destruct H n exact fun {a b} o => match a, b, o with | none, none, _ => by -- Porting note: These 2 theorems should be excluded. simp [-liftRel_pure_left, -liftRel_pure_right] | some (a, s), some (b, t), ⟨_, h2⟩ => by simpa [tail.aux] using liftRel_destruct h2 theorem exists_of_liftRel_left {R : α → β → Prop} {s t} (H : LiftRel R s t) {a} (h : a ∈ s) : ∃ b, b ∈ t ∧ R a b := by let ⟨n, h⟩ := exists_get?_of_mem h -- Porting note: This line is required to infer metavariables in -- `Computation.exists_of_mem_map`. dsimp only [get?, head] at h let ⟨some (_, s'), sd, rfl⟩ := Computation.exists_of_mem_map h let ⟨some (b, t'), td, ⟨ab, _⟩⟩ := (liftRel_dropn_destruct H n).left sd exact ⟨b, get?_mem (Computation.mem_map (Prod.fst.{v, v} <$> ·) td), ab⟩ theorem exists_of_liftRel_right {R : α → β → Prop} {s t} (H : LiftRel R s t) {b} (h : b ∈ t) : ∃ a, a ∈ s ∧ R a b := by rw [← LiftRel.swap] at H; exact exists_of_liftRel_left H h theorem head_terminates_of_mem {s : WSeq α} {a} (h : a ∈ s) : Terminates (head s) := let ⟨_, h⟩ := exists_get?_of_mem h head_terminates_of_get?_terminates ⟨⟨_, h⟩⟩ theorem of_mem_append {s₁ s₂ : WSeq α} {a : α} : a ∈ append s₁ s₂ → a ∈ s₁ ∨ a ∈ s₂ := Seq.of_mem_append theorem mem_append_left {s₁ s₂ : WSeq α} {a : α} : a ∈ s₁ → a ∈ append s₁ s₂ := Seq.mem_append_left theorem exists_of_mem_map {f} {b : β} : ∀ {s : WSeq α}, b ∈ map f s → ∃ a, a ∈ s ∧ f a = b | ⟨g, al⟩, h => by let ⟨o, om, oe⟩ := Seq.exists_of_mem_map h cases' o with a · injection oe injection oe with h' exact ⟨a, om, h'⟩ @[simp] theorem liftRel_nil (R : α → β → Prop) : LiftRel R nil nil := by rw [liftRel_destruct_iff] -- Porting note: These 2 theorems should be excluded. simp [-liftRel_pure_left, -liftRel_pure_right] @[simp] theorem liftRel_cons (R : α → β → Prop) (a b s t) : LiftRel R (cons a s) (cons b t) ↔ R a b ∧ LiftRel R s t := by rw [liftRel_destruct_iff] -- Porting note: These 2 theorems should be excluded. simp [-liftRel_pure_left, -liftRel_pure_right] @[simp] theorem liftRel_think_left (R : α → β → Prop) (s t) : LiftRel R (think s) t ↔ LiftRel R s t := by rw [liftRel_destruct_iff, liftRel_destruct_iff]; simp @[simp] theorem liftRel_think_right (R : α → β → Prop) (s t) : LiftRel R s (think t) ↔ LiftRel R s t := by rw [liftRel_destruct_iff, liftRel_destruct_iff]; simp theorem cons_congr {s t : WSeq α} (a : α) (h : s ~ʷ t) : cons a s ~ʷ cons a t := by unfold Equiv; simpa using h theorem think_equiv (s : WSeq α) : think s ~ʷ s := by unfold Equiv; simpa using Equiv.refl _ theorem think_congr {s t : WSeq α} (h : s ~ʷ t) : think s ~ʷ think t := by unfold Equiv; simpa using h theorem head_congr : ∀ {s t : WSeq α}, s ~ʷ t → head s ~ head t := by suffices ∀ {s t : WSeq α}, s ~ʷ t → ∀ {o}, o ∈ head s → o ∈ head t from fun s t h o => ⟨this h, this h.symm⟩ intro s t h o ho rcases @Computation.exists_of_mem_map _ _ _ _ (destruct s) ho with ⟨ds, dsm, dse⟩ rw [← dse] cases' destruct_congr h with l r rcases l dsm with ⟨dt, dtm, dst⟩ cases' ds with a <;> cases' dt with b · apply Computation.mem_map _ dtm · cases b cases dst · cases a cases dst · cases' a with a s' cases' b with b t' rw [dst.left] exact @Computation.mem_map _ _ (@Functor.map _ _ (α × WSeq α) _ Prod.fst) (some (b, t')) (destruct t) dtm theorem flatten_equiv {c : Computation (WSeq α)} {s} (h : s ∈ c) : flatten c ~ʷ s := by apply Computation.memRecOn h · simp [Equiv.refl] · intro s' apply Equiv.trans simp [think_equiv] theorem liftRel_flatten {R : α → β → Prop} {c1 : Computation (WSeq α)} {c2 : Computation (WSeq β)} (h : c1.LiftRel (LiftRel R) c2) : LiftRel R (flatten c1) (flatten c2) := let S s t := ∃ c1 c2, s = flatten c1 ∧ t = flatten c2 ∧ Computation.LiftRel (LiftRel R) c1 c2 ⟨S, ⟨c1, c2, rfl, rfl, h⟩, fun {s t} h => match s, t, h with | _, _, ⟨c1, c2, rfl, rfl, h⟩ => by simp only [destruct_flatten]; apply liftRel_bind _ _ h intro a b ab; apply Computation.LiftRel.imp _ _ _ (liftRel_destruct ab) intro a b; apply LiftRelO.imp_right intro s t h; refine ⟨Computation.pure s, Computation.pure t, ?_, ?_, ?_⟩ <;> -- Porting note: These 2 theorems should be excluded. simp [h, -liftRel_pure_left, -liftRel_pure_right]⟩ theorem flatten_congr {c1 c2 : Computation (WSeq α)} : Computation.LiftRel Equiv c1 c2 → flatten c1 ~ʷ flatten c2 := liftRel_flatten theorem tail_congr {s t : WSeq α} (h : s ~ʷ t) : tail s ~ʷ tail t := by apply flatten_congr dsimp only [(· <$> ·)]; rw [← Computation.bind_pure, ← Computation.bind_pure] apply liftRel_bind _ _ (destruct_congr h) intro a b h; simp only [comp_apply, liftRel_pure] cases' a with a <;> cases' b with b · trivial · cases h · cases a cases h · cases' a with a s' cases' b with b t' exact h.right theorem dropn_congr {s t : WSeq α} (h : s ~ʷ t) (n) : drop s n ~ʷ drop t n := by induction n <;> simp [*, tail_congr, drop] theorem get?_congr {s t : WSeq α} (h : s ~ʷ t) (n) : get? s n ~ get? t n := head_congr (dropn_congr h _) theorem mem_congr {s t : WSeq α} (h : s ~ʷ t) (a) : a ∈ s ↔ a ∈ t := suffices ∀ {s t : WSeq α}, s ~ʷ t → a ∈ s → a ∈ t from ⟨this h, this h.symm⟩ fun {_ _} h as => let ⟨_, hn⟩ := exists_get?_of_mem as get?_mem ((get?_congr h _ _).1 hn) theorem productive_congr {s t : WSeq α} (h : s ~ʷ t) : Productive s ↔ Productive t := by simp only [productive_iff]; exact forall_congr' fun n => terminates_congr <| get?_congr h _ theorem Equiv.ext {s t : WSeq α} (h : ∀ n, get? s n ~ get? t n) : s ~ʷ t := ⟨fun s t => ∀ n, get? s n ~ get? t n, h, fun {s t} h => by refine liftRel_def.2 ⟨?_, ?_⟩ · rw [← head_terminates_iff, ← head_terminates_iff] exact terminates_congr (h 0) · intro a b ma mb cases' a with a <;> cases' b with b · trivial · injection mem_unique (Computation.mem_map _ ma) ((h 0 _).2 (Computation.mem_map _ mb)) · injection mem_unique (Computation.mem_map _ ma) ((h 0 _).2 (Computation.mem_map _ mb)) · cases' a with a s' cases' b with b t' injection mem_unique (Computation.mem_map _ ma) ((h 0 _).2 (Computation.mem_map _ mb)) with ab refine ⟨ab, fun n => ?_⟩ refine (get?_congr (flatten_equiv (Computation.mem_map _ ma)) n).symm.trans ((?_ : get? (tail s) n ~ get? (tail t) n).trans (get?_congr (flatten_equiv (Computation.mem_map _ mb)) n)) rw [get?_tail, get?_tail] apply h⟩ theorem length_eq_map (s : WSeq α) : length s = Computation.map List.length (toList s) := by refine Computation.eq_of_bisim (fun c1 c2 => ∃ (l : List α) (s : WSeq α), c1 = Computation.corec (fun ⟨n, s⟩ => match Seq.destruct s with | none => Sum.inl n | some (none, s') => Sum.inr (n, s') | some (some _, s') => Sum.inr (n + 1, s')) (l.length, s) ∧ c2 = Computation.map List.length (Computation.corec (fun ⟨l, s⟩ => match Seq.destruct s with | none => Sum.inl l.reverse | some (none, s') => Sum.inr (l, s') | some (some a, s') => Sum.inr (a::l, s')) (l, s))) ?_ ⟨[], s, rfl, rfl⟩ intro s1 s2 h; rcases h with ⟨l, s, h⟩; rw [h.left, h.right] induction' s using WSeq.recOn with a s s <;> simp [toList, nil, cons, think, length] · refine ⟨a::l, s, ?_, ?_⟩ <;> simp · refine ⟨l, s, ?_, ?_⟩ <;> simp @[simp] theorem ofList_nil : ofList [] = (nil : WSeq α) := rfl @[simp] theorem ofList_cons (a : α) (l) : ofList (a::l) = cons a (ofList l) := show Seq.map some (Seq.ofList (a::l)) = Seq.cons (some a) (Seq.map some (Seq.ofList l)) by simp @[simp] theorem toList'_nil (l : List α) : Computation.corec (fun ⟨l, s⟩ => match Seq.destruct s with | none => Sum.inl l.reverse | some (none, s') => Sum.inr (l, s') | some (some a, s') => Sum.inr (a::l, s')) (l, nil) = Computation.pure l.reverse := destruct_eq_pure rfl @[simp] theorem toList'_cons (l : List α) (s : WSeq α) (a : α) : Computation.corec (fun ⟨l, s⟩ => match Seq.destruct s with | none => Sum.inl l.reverse | some (none, s') => Sum.inr (l, s') | some (some a, s') => Sum.inr (a::l, s')) (l, cons a s) = (Computation.corec (fun ⟨l, s⟩ => match Seq.destruct s with | none => Sum.inl l.reverse | some (none, s') => Sum.inr (l, s') | some (some a, s') => Sum.inr (a::l, s')) (a::l, s)).think := destruct_eq_think <| by simp [toList, cons] @[simp] theorem toList'_think (l : List α) (s : WSeq α) : Computation.corec (fun ⟨l, s⟩ => match Seq.destruct s with | none => Sum.inl l.reverse | some (none, s') => Sum.inr (l, s') | some (some a, s') => Sum.inr (a::l, s')) (l, think s) = (Computation.corec (fun ⟨l, s⟩ => match Seq.destruct s with | none => Sum.inl l.reverse | some (none, s') => Sum.inr (l, s') | some (some a, s') => Sum.inr (a::l, s')) (l, s)).think := destruct_eq_think <| by simp [toList, think] theorem toList'_map (l : List α) (s : WSeq α) : Computation.corec (fun ⟨l, s⟩ => match Seq.destruct s with | none => Sum.inl l.reverse | some (none, s') => Sum.inr (l, s') | some (some a, s') => Sum.inr (a :: l, s')) (l, s) = (l.reverse ++ ·) <$> toList s := by refine Computation.eq_of_bisim (fun c1 c2 => ∃ (l' : List α) (s : WSeq α), c1 = Computation.corec (fun ⟨l, s⟩ => match Seq.destruct s with | none => Sum.inl l.reverse | some (none, s') => Sum.inr (l, s') | some (some a, s') => Sum.inr (a::l, s')) (l' ++ l, s) ∧ c2 = Computation.map (l.reverse ++ ·) (Computation.corec (fun ⟨l, s⟩ => match Seq.destruct s with | none => Sum.inl l.reverse | some (none, s') => Sum.inr (l, s') | some (some a, s') => Sum.inr (a::l, s')) (l', s))) ?_ ⟨[], s, rfl, rfl⟩ intro s1 s2 h; rcases h with ⟨l', s, h⟩; rw [h.left, h.right] induction' s using WSeq.recOn with a s s <;> simp [toList, nil, cons, think, length] · refine ⟨a::l', s, ?_, ?_⟩ <;> simp · refine ⟨l', s, ?_, ?_⟩ <;> simp @[simp] theorem toList_cons (a : α) (s) : toList (cons a s) = (List.cons a <$> toList s).think := destruct_eq_think <| by unfold toList simp only [toList'_cons, Computation.destruct_think, Sum.inr.injEq] rw [toList'_map] simp only [List.reverse_cons, List.reverse_nil, List.nil_append, List.singleton_append] rfl @[simp] theorem toList_nil : toList (nil : WSeq α) = Computation.pure [] := destruct_eq_pure rfl theorem toList_ofList (l : List α) : l ∈ toList (ofList l) := by induction' l with a l IH · simp [ret_mem] · simpa [ret_mem] using think_mem (Computation.mem_map _ IH) @[simp] theorem destruct_ofSeq (s : Seq α) : destruct (ofSeq s) = Computation.pure (s.head.map fun a => (a, ofSeq s.tail)) := destruct_eq_pure <| by simp only [destruct, Seq.destruct, Option.map_eq_map, ofSeq, Computation.corec_eq, rmap, Seq.head] rw [show Seq.get? (some <$> s) 0 = some <$> Seq.get? s 0 by apply Seq.map_get?] cases' Seq.get? s 0 with a · rfl dsimp only [(· <$> ·)] simp [destruct] @[simp] theorem head_ofSeq (s : Seq α) : head (ofSeq s) = Computation.pure s.head := by simp only [head, Option.map_eq_map, destruct_ofSeq, Computation.map_pure, Option.map_map] cases Seq.head s <;> rfl @[simp] theorem tail_ofSeq (s : Seq α) : tail (ofSeq s) = ofSeq s.tail := by simp only [tail, destruct_ofSeq, map_pure', flatten_pure] induction' s using Seq.recOn with x s <;> simp only [ofSeq, Seq.tail_nil, Seq.head_nil, Option.map_none', Seq.tail_cons, Seq.head_cons, Option.map_some'] · rfl @[simp] theorem dropn_ofSeq (s : Seq α) : ∀ n, drop (ofSeq s) n = ofSeq (s.drop n) | 0 => rfl | n + 1 => by simp only [drop, Nat.add_eq, Nat.add_zero, Seq.drop] rw [dropn_ofSeq s n, tail_ofSeq] theorem get?_ofSeq (s : Seq α) (n) : get? (ofSeq s) n = Computation.pure (Seq.get? s n) := by dsimp [get?]; rw [dropn_ofSeq, head_ofSeq, Seq.head_dropn] instance productive_ofSeq (s : Seq α) : Productive (ofSeq s) := ⟨fun n => by rw [get?_ofSeq]; infer_instance⟩ theorem toSeq_ofSeq (s : Seq α) : toSeq (ofSeq s) = s := by apply Subtype.eq; funext n dsimp [toSeq]; apply get_eq_of_mem rw [get?_ofSeq]; apply ret_mem /-- The monadic `return a` is a singleton list containing `a`. -/ def ret (a : α) : WSeq α := ofList [a] @[simp] theorem map_nil (f : α → β) : map f nil = nil := rfl @[simp] theorem map_cons (f : α → β) (a s) : map f (cons a s) = cons (f a) (map f s) := Seq.map_cons _ _ _ @[simp] theorem map_think (f : α → β) (s) : map f (think s) = think (map f s) := Seq.map_cons _ _ _ @[simp] theorem map_id (s : WSeq α) : map id s = s := by simp [map] @[simp] theorem map_ret (f : α → β) (a) : map f (ret a) = ret (f a) := by simp [ret] @[simp] theorem map_append (f : α → β) (s t) : map f (append s t) = append (map f s) (map f t) := Seq.map_append _ _ _ theorem map_comp (f : α → β) (g : β → γ) (s : WSeq α) : map (g ∘ f) s = map g (map f s) := by dsimp [map]; rw [← Seq.map_comp] apply congr_fun; apply congr_arg ext ⟨⟩ <;> rfl theorem mem_map (f : α → β) {a : α} {s : WSeq α} : a ∈ s → f a ∈ map f s := Seq.mem_map (Option.map f) -- The converse is not true without additional assumptions theorem exists_of_mem_join {a : α} : ∀ {S : WSeq (WSeq α)}, a ∈ join S → ∃ s, s ∈ S ∧ a ∈ s := by suffices ∀ ss : WSeq α, a ∈ ss → ∀ s S, append s (join S) = ss → a ∈ append s (join S) → a ∈ s ∨ ∃ s, s ∈ S ∧ a ∈ s from fun S h => (this _ h nil S (by simp) (by simp [h])).resolve_left (not_mem_nil _) intro ss h; apply mem_rec_on h <;> [intro b ss o; intro ss IH] <;> intro s S · induction' s using WSeq.recOn with b' s s <;> [induction' S using WSeq.recOn with s S S; skip; skip] <;> intro ej m <;> simp at ej <;> have := congr_arg Seq.destruct ej <;> simp at this; cases this substs b' ss simp? at m ⊢ says simp only [cons_append, mem_cons_iff] at m ⊢ cases' o with e IH · simp [e] cases' m with e m · simp [e] exact Or.imp_left Or.inr (IH _ _ rfl m) · induction' s using WSeq.recOn with b' s s <;> [induction' S using WSeq.recOn with s S S; skip; skip] <;> intro ej m <;> simp at ej <;> have := congr_arg Seq.destruct ej <;> simp at this <;> subst ss · apply Or.inr -- Porting note: `exists_eq_or_imp` should be excluded. simp [-exists_eq_or_imp] at m ⊢ cases' IH s S rfl m with as ex · exact ⟨s, Or.inl rfl, as⟩ · rcases ex with ⟨s', sS, as⟩ exact ⟨s', Or.inr sS, as⟩ · apply Or.inr simp? at m says simp only [join_think, nil_append, mem_think] at m rcases (IH nil S (by simp) (by simp [m])).resolve_left (not_mem_nil _) with ⟨s, sS, as⟩ exact ⟨s, by simp [sS], as⟩ · simp only [think_append, mem_think] at m IH ⊢ apply IH _ _ rfl m theorem exists_of_mem_bind {s : WSeq α} {f : α → WSeq β} {b} (h : b ∈ bind s f) : ∃ a ∈ s, b ∈ f a := let ⟨t, tm, bt⟩ := exists_of_mem_join h let ⟨a, as, e⟩ := exists_of_mem_map tm ⟨a, as, by rwa [e]⟩ theorem destruct_map (f : α → β) (s : WSeq α) : destruct (map f s) = Computation.map (Option.map (Prod.map f (map f))) (destruct s) := by apply Computation.eq_of_bisim fun c1 c2 => ∃ s, c1 = destruct (map f s) ∧ c2 = Computation.map (Option.map (Prod.map f (map f))) (destruct s) · intro c1 c2 h cases' h with s h rw [h.left, h.right] induction' s using WSeq.recOn with a s s <;> simp exact ⟨s, rfl, rfl⟩ · exact ⟨s, rfl, rfl⟩ theorem liftRel_map {δ} (R : α → β → Prop) (S : γ → δ → Prop) {s1 : WSeq α} {s2 : WSeq β} {f1 : α → γ} {f2 : β → δ} (h1 : LiftRel R s1 s2) (h2 : ∀ {a b}, R a b → S (f1 a) (f2 b)) : LiftRel S (map f1 s1) (map f2 s2) := ⟨fun s1 s2 => ∃ s t, s1 = map f1 s ∧ s2 = map f2 t ∧ LiftRel R s t, ⟨s1, s2, rfl, rfl, h1⟩, fun {s1 s2} h => match s1, s2, h with | _, _, ⟨s, t, rfl, rfl, h⟩ => by simp only [exists_and_left, destruct_map] apply Computation.liftRel_map _ _ (liftRel_destruct h) intro o p h cases' o with a <;> cases' p with b <;> simp · cases b; cases h · cases a; cases h · cases' a with a s; cases' b with b t cases' h with r h exact ⟨h2 r, s, rfl, t, rfl, h⟩⟩ theorem map_congr (f : α → β) {s t : WSeq α} (h : s ~ʷ t) : map f s ~ʷ map f t := liftRel_map _ _ h fun {_ _} => congr_arg _ /-- auxiliary definition of `destruct_append` over weak sequences-/ @[simp] def destruct_append.aux (t : WSeq α) : Option (α × WSeq α) → Computation (Option (α × WSeq α)) | none => destruct t | some (a, s) => Computation.pure (some (a, append s t)) theorem destruct_append (s t : WSeq α) : destruct (append s t) = (destruct s).bind (destruct_append.aux t) := by apply Computation.eq_of_bisim (fun c1 c2 => ∃ s t, c1 = destruct (append s t) ∧ c2 = (destruct s).bind (destruct_append.aux t)) _ ⟨s, t, rfl, rfl⟩ intro c1 c2 h; rcases h with ⟨s, t, h⟩; rw [h.left, h.right] induction' s using WSeq.recOn with a s s <;> simp · induction' t using WSeq.recOn with b t t <;> simp · refine ⟨nil, t, ?_, ?_⟩ <;> simp · exact ⟨s, t, rfl, rfl⟩ /-- auxiliary definition of `destruct_join` over weak sequences-/ @[simp] def destruct_join.aux : Option (WSeq α × WSeq (WSeq α)) → Computation (Option (α × WSeq α)) | none => Computation.pure none | some (s, S) => (destruct (append s (join S))).think theorem destruct_join (S : WSeq (WSeq α)) : destruct (join S) = (destruct S).bind destruct_join.aux := by apply Computation.eq_of_bisim (fun c1 c2 => c1 = c2 ∨ ∃ S, c1 = destruct (join S) ∧ c2 = (destruct S).bind destruct_join.aux) _ (Or.inr ⟨S, rfl, rfl⟩) intro c1 c2 h exact match c1, c2, h with | c, _, Or.inl <| rfl => by cases c.destruct <;> simp | _, _, Or.inr ⟨S, rfl, rfl⟩ => by induction' S using WSeq.recOn with s S S <;> simp · refine Or.inr ⟨S, rfl, rfl⟩ theorem liftRel_append (R : α → β → Prop) {s1 s2 : WSeq α} {t1 t2 : WSeq β} (h1 : LiftRel R s1 t1) (h2 : LiftRel R s2 t2) : LiftRel R (append s1 s2) (append t1 t2) := ⟨fun s t => LiftRel R s t ∨ ∃ s1 t1, s = append s1 s2 ∧ t = append t1 t2 ∧ LiftRel R s1 t1, Or.inr ⟨s1, t1, rfl, rfl, h1⟩, fun {s t} h => match s, t, h with | s, t, Or.inl h => by apply Computation.LiftRel.imp _ _ _ (liftRel_destruct h) intro a b; apply LiftRelO.imp_right intro s t; apply Or.inl | _, _, Or.inr ⟨s1, t1, rfl, rfl, h⟩ => by simp only [LiftRelO, exists_and_left, destruct_append, destruct_append.aux] apply Computation.liftRel_bind _ _ (liftRel_destruct h) intro o p h cases' o with a <;> cases' p with b · simp only [destruct_append.aux] apply Computation.LiftRel.imp _ _ _ (liftRel_destruct h2) intro a b apply LiftRelO.imp_right intro s t apply Or.inl · cases b; cases h · cases a; cases h · cases' a with a s; cases' b with b t cases' h with r h -- Porting note: These 2 theorems should be excluded. simpa [-liftRel_pure_left, -liftRel_pure_right] using ⟨r, Or.inr ⟨s, rfl, t, rfl, h⟩⟩⟩ theorem liftRel_join.lem (R : α → β → Prop) {S T} {U : WSeq α → WSeq β → Prop} (ST : LiftRel (LiftRel R) S T) (HU : ∀ s1 s2, (∃ s t S T, s1 = append s (join S) ∧ s2 = append t (join T) ∧ LiftRel R s t ∧ LiftRel (LiftRel R) S T) → U s1 s2) {a} (ma : a ∈ destruct (join S)) : ∃ b, b ∈ destruct (join T) ∧ LiftRelO R U a b := by cases' exists_results_of_mem ma with n h; clear ma; revert S T ST a induction' n using Nat.strongInductionOn with n IH intro S T ST a ra; simp only [destruct_join] at ra exact let ⟨o, m, k, rs1, rs2, en⟩ := of_results_bind ra let ⟨p, mT, rop⟩ := Computation.exists_of_liftRel_left (liftRel_destruct ST) rs1.mem match o, p, rop, rs1, rs2, mT with | none, none, _, _, rs2, mT => by simp only [destruct_join] exact ⟨none, mem_bind mT (ret_mem _), by rw [eq_of_pure_mem rs2.mem]; trivial⟩ | some (s, S'), some (t, T'), ⟨st, ST'⟩, _, rs2, mT => by simp? [destruct_append] at rs2 says simp only [destruct_join.aux, destruct_append] at rs2 exact let ⟨k1, rs3, ek⟩ := of_results_think rs2 let ⟨o', m1, n1, rs4, rs5, ek1⟩ := of_results_bind rs3 let ⟨p', mt, rop'⟩ := Computation.exists_of_liftRel_left (liftRel_destruct st) rs4.mem match o', p', rop', rs4, rs5, mt with | none, none, _, _, rs5', mt => by have : n1 < n := by rw [en, ek, ek1] apply lt_of_lt_of_le _ (Nat.le_add_right _ _) apply Nat.lt_succ_of_le (Nat.le_add_right _ _) let ⟨ob, mb, rob⟩ := IH _ this ST' rs5' refine ⟨ob, ?_, rob⟩ · simp (config := { unfoldPartialApp := true }) only [destruct_join, destruct_join.aux] apply mem_bind mT simp only [destruct_append, destruct_append.aux] apply think_mem apply mem_bind mt exact mb | some (a, s'), some (b, t'), ⟨ab, st'⟩, _, rs5, mt => by simp? at rs5 says simp only [destruct_append.aux] at rs5 refine ⟨some (b, append t' (join T')), ?_, ?_⟩ · simp (config := { unfoldPartialApp := true }) only [destruct_join, destruct_join.aux] apply mem_bind mT simp only [destruct_append, destruct_append.aux] apply think_mem apply mem_bind mt apply ret_mem rw [eq_of_pure_mem rs5.mem] exact ⟨ab, HU _ _ ⟨s', t', S', T', rfl, rfl, st', ST'⟩⟩ theorem liftRel_join (R : α → β → Prop) {S : WSeq (WSeq α)} {T : WSeq (WSeq β)} (h : LiftRel (LiftRel R) S T) : LiftRel R (join S) (join T) := ⟨fun s1 s2 => ∃ s t S T, s1 = append s (join S) ∧ s2 = append t (join T) ∧ LiftRel R s t ∧ LiftRel (LiftRel R) S T, ⟨nil, nil, S, T, by simp, by simp, by simp, h⟩, fun {s1 s2} ⟨s, t, S, T, h1, h2, st, ST⟩ => by rw [h1, h2]; rw [destruct_append, destruct_append] apply Computation.liftRel_bind _ _ (liftRel_destruct st) exact fun {o p} h => match o, p, h with | some (a, s), some (b, t), ⟨h1, h2⟩ => by -- Porting note: These 2 theorems should be excluded. simpa [-liftRel_pure_left, -liftRel_pure_right] using ⟨h1, s, t, S, rfl, T, rfl, h2, ST⟩ | none, none, _ => by -- Porting note: `LiftRelO` should be excluded. dsimp [destruct_append.aux, Computation.LiftRel, -LiftRelO]; constructor · intro apply liftRel_join.lem _ ST fun _ _ => id · intro b mb rw [← LiftRelO.swap] apply liftRel_join.lem (swap R) · rw [← LiftRel.swap R, ← LiftRel.swap] apply ST · rw [← LiftRel.swap R, ← LiftRel.swap (LiftRel R)] exact fun s1 s2 ⟨s, t, S, T, h1, h2, st, ST⟩ => ⟨t, s, T, S, h2, h1, st, ST⟩ · exact mb⟩ theorem join_congr {S T : WSeq (WSeq α)} (h : LiftRel Equiv S T) : join S ~ʷ join T := liftRel_join _ h theorem liftRel_bind {δ} (R : α → β → Prop) (S : γ → δ → Prop) {s1 : WSeq α} {s2 : WSeq β} {f1 : α → WSeq γ} {f2 : β → WSeq δ} (h1 : LiftRel R s1 s2) (h2 : ∀ {a b}, R a b → LiftRel S (f1 a) (f2 b)) : LiftRel S (bind s1 f1) (bind s2 f2) := liftRel_join _ (liftRel_map _ _ h1 @h2) theorem bind_congr {s1 s2 : WSeq α} {f1 f2 : α → WSeq β} (h1 : s1 ~ʷ s2) (h2 : ∀ a, f1 a ~ʷ f2 a) : bind s1 f1 ~ʷ bind s2 f2 := liftRel_bind _ _ h1 fun {a b} h => by rw [h]; apply h2 @[simp] theorem join_ret (s : WSeq α) : join (ret s) ~ʷ s := by simpa [ret] using think_equiv _ @[simp] theorem join_map_ret (s : WSeq α) : join (map ret s) ~ʷ s := by refine ⟨fun s1 s2 => join (map ret s2) = s1, rfl, ?_⟩ intro s' s h; rw [← h] apply liftRel_rec fun c1 c2 => ∃ s, c1 = destruct (join (map ret s)) ∧ c2 = destruct s · exact fun {c1 c2} h => match c1, c2, h with | _, _, ⟨s, rfl, rfl⟩ => by clear h -- Porting note: `ret` is simplified in `simp` so `ret`s become `fun a => cons a nil` here. have : ∀ s, ∃ s' : WSeq α, (map (fun a => cons a nil) s).join.destruct = (map (fun a => cons a nil) s').join.destruct ∧ destruct s = s'.destruct := fun s => ⟨s, rfl, rfl⟩ induction' s using WSeq.recOn with a s s <;> simp (config := { unfoldPartialApp := true }) [ret, ret_mem, this, Option.exists] · exact ⟨s, rfl, rfl⟩ @[simp] theorem join_append (S T : WSeq (WSeq α)) : join (append S T) ~ʷ append (join S) (join T) := by refine ⟨fun s1 s2 => ∃ s S T, s1 = append s (join (append S T)) ∧ s2 = append s (append (join S) (join T)), ⟨nil, S, T, by simp, by simp⟩, ?_⟩ intro s1 s2 h apply liftRel_rec (fun c1 c2 => ∃ (s : WSeq α) (S T : _), c1 = destruct (append s (join (append S T))) ∧ c2 = destruct (append s (append (join S) (join T)))) _ _ _ (let ⟨s, S, T, h1, h2⟩ := h ⟨s, S, T, congr_arg destruct h1, congr_arg destruct h2⟩) rintro c1 c2 ⟨s, S, T, rfl, rfl⟩ induction' s using WSeq.recOn with a s s <;> simp · induction' S using WSeq.recOn with s S S <;> simp · induction' T using WSeq.recOn with s T T <;> simp · refine ⟨s, nil, T, ?_, ?_⟩ <;> simp · refine ⟨nil, nil, T, ?_, ?_⟩ <;> simp · exact ⟨s, S, T, rfl, rfl⟩ · refine ⟨nil, S, T, ?_, ?_⟩ <;> simp · exact ⟨s, S, T, rfl, rfl⟩ · exact ⟨s, S, T, rfl, rfl⟩ @[simp] theorem bind_ret (f : α → β) (s) : bind s (ret ∘ f) ~ʷ map f s := by dsimp [bind] rw [map_comp] apply join_map_ret @[simp] theorem ret_bind (a : α) (f : α → WSeq β) : bind (ret a) f ~ʷ f a := by simp [bind] @[simp] theorem map_join (f : α → β) (S) : map f (join S) = join (map (map f) S) := by apply Seq.eq_of_bisim fun s1 s2 => ∃ s S, s1 = append s (map f (join S)) ∧ s2 = append s (join (map (map f) S)) · intro s1 s2 h exact match s1, s2, h with | _, _, ⟨s, S, rfl, rfl⟩ => by induction' s using WSeq.recOn with a s s <;> simp · induction' S using WSeq.recOn with s S S <;> simp · exact ⟨map f s, S, rfl, rfl⟩ · refine ⟨nil, S, ?_, ?_⟩ <;> simp · exact ⟨_, _, rfl, rfl⟩ · exact ⟨_, _, rfl, rfl⟩ · refine ⟨nil, S, ?_, ?_⟩ <;> simp @[simp] theorem join_join (SS : WSeq (WSeq (WSeq α))) : join (join SS) ~ʷ join (map join SS) := by refine ⟨fun s1 s2 => ∃ s S SS, s1 = append s (join (append S (join SS))) ∧ s2 = append s (append (join S) (join (map join SS))), ⟨nil, nil, SS, by simp, by simp⟩, ?_⟩ intro s1 s2 h apply liftRel_rec (fun c1 c2 => ∃ s S SS, c1 = destruct (append s (join (append S (join SS)))) ∧ c2 = destruct (append s (append (join S) (join (map join SS))))) _ (destruct s1) (destruct s2) (let ⟨s, S, SS, h1, h2⟩ := h ⟨s, S, SS, by simp [h1], by simp [h2]⟩) intro c1 c2 h exact match c1, c2, h with | _, _, ⟨s, S, SS, rfl, rfl⟩ => by clear h induction' s using WSeq.recOn with a s s <;> simp · induction' S using WSeq.recOn with s S S <;> simp · induction' SS using WSeq.recOn with S SS SS <;> simp · refine ⟨nil, S, SS, ?_, ?_⟩ <;> simp · refine ⟨nil, nil, SS, ?_, ?_⟩ <;> simp · exact ⟨s, S, SS, rfl, rfl⟩ · refine ⟨nil, S, SS, ?_, ?_⟩ <;> simp · exact ⟨s, S, SS, rfl, rfl⟩ · exact ⟨s, S, SS, rfl, rfl⟩ @[simp] theorem bind_assoc (s : WSeq α) (f : α → WSeq β) (g : β → WSeq γ) : bind (bind s f) g ~ʷ bind s fun x : α => bind (f x) g := by simp only [bind, map_join]; erw [← map_comp f (map g), map_comp (map g ∘ f) join] apply join_join instance monad : Monad WSeq where map := @map pure := @ret bind := @bind /- Unfortunately, WSeq is not a lawful monad, because it does not satisfy the monad laws exactly, only up to sequence equivalence. Furthermore, even quotienting by the equivalence is not sufficient, because the join operation involves lists of quotient elements, with a lifted equivalence relation, and pure quotients cannot handle this type of construction. instance lawfulMonad : LawfulMonad WSeq := { id_map := @map_id, bind_pure_comp := @bind_ret, pure_bind := @ret_bind, bind_assoc := @bind_assoc } -/ end WSeq end Stream'
Data\Set\Accumulate.lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import Mathlib.Data.Set.Lattice /-! # Accumulate The function `Accumulate` takes a set `s` and returns `⋃ y ≤ x, s y`. -/ variable {α β γ : Type*} {s : α → Set β} {t : α → Set γ} namespace Set /-- `Accumulate s` is the union of `s y` for `y ≤ x`. -/ def Accumulate [LE α] (s : α → Set β) (x : α) : Set β := ⋃ y ≤ x, s y theorem accumulate_def [LE α] {x : α} : Accumulate s x = ⋃ y ≤ x, s y := rfl @[simp] theorem mem_accumulate [LE α] {x : α} {z : β} : z ∈ Accumulate s x ↔ ∃ y ≤ x, z ∈ s y := by simp_rw [accumulate_def, mem_iUnion₂, exists_prop] theorem subset_accumulate [Preorder α] {x : α} : s x ⊆ Accumulate s x := fun _ => mem_biUnion le_rfl theorem accumulate_subset_iUnion [Preorder α] (x : α) : Accumulate s x ⊆ ⋃ i, s i := (biUnion_subset_biUnion_left (subset_univ _)).trans_eq (biUnion_univ _) theorem monotone_accumulate [Preorder α] : Monotone (Accumulate s) := fun _ _ hxy => biUnion_subset_biUnion_left fun _ hz => le_trans hz hxy @[gcongr] theorem accumulate_subset_accumulate [Preorder α] {x y} (h : x ≤ y) : Accumulate s x ⊆ Accumulate s y := monotone_accumulate h theorem biUnion_accumulate [Preorder α] (x : α) : ⋃ y ≤ x, Accumulate s y = ⋃ y ≤ x, s y := by apply Subset.antisymm · exact iUnion₂_subset fun y hy => monotone_accumulate hy · exact iUnion₂_mono fun y _ => subset_accumulate theorem iUnion_accumulate [Preorder α] : ⋃ x, Accumulate s x = ⋃ x, s x := by apply Subset.antisymm · simp only [subset_def, mem_iUnion, exists_imp, mem_accumulate] intro z x x' ⟨_, hz⟩ exact ⟨x', hz⟩ · exact iUnion_mono fun i => subset_accumulate end Set
Data\Set\Basic.lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura -/ import Mathlib.Algebra.Group.ZeroOne import Mathlib.Data.Set.Defs import Mathlib.Order.Basic import Mathlib.Order.SymmDiff import Mathlib.Tactic.Tauto import Mathlib.Tactic.ByContra import Mathlib.Util.Delaborators /-! # Basic properties of sets Sets in Lean are homogeneous; all their elements have the same type. Sets whose elements have type `X` are thus defined as `Set X := X → Prop`. Note that this function need not be decidable. The definition is in the core library. This file provides some basic definitions related to sets and functions not present in the core library, as well as extra lemmas for functions in the core library (empty set, univ, union, intersection, insert, singleton, set-theoretic difference, complement, and powerset). Note that a set is a term, not a type. There is a coercion from `Set α` to `Type*` sending `s` to the corresponding subtype `↥s`. See also the file `SetTheory/ZFC.lean`, which contains an encoding of ZFC set theory in Lean. ## Main definitions Notation used here: - `f : α → β` is a function, - `s : Set α` and `s₁ s₂ : Set α` are subsets of `α` - `t : Set β` is a subset of `β`. Definitions in the file: * `Nonempty s : Prop` : the predicate `s ≠ ∅`. Note that this is the preferred way to express the fact that `s` has an element (see the Implementation Notes). * `inclusion s₁ s₂ : ↥s₁ → ↥s₂` : the map `↥s₁ → ↥s₂` induced by an inclusion `s₁ ⊆ s₂`. ## Notation * `sᶜ` for the complement of `s` ## Implementation notes * `s.Nonempty` is to be preferred to `s ≠ ∅` or `∃ x, x ∈ s`. It has the advantage that the `s.Nonempty` dot notation can be used. * For `s : Set α`, do not use `Subtype s`. Instead use `↥s` or `(s : Type*)` or `s`. ## Tags set, sets, subset, subsets, union, intersection, insert, singleton, complement, powerset -/ /-! ### Set coercion to a type -/ open Function universe u v w x namespace Set variable {α : Type u} {s t : Set α} instance instBooleanAlgebraSet : BooleanAlgebra (Set α) := { (inferInstance : BooleanAlgebra (α → Prop)) with sup := (· ∪ ·), le := (· ≤ ·), lt := fun s t => s ⊆ t ∧ ¬t ⊆ s, inf := (· ∩ ·), bot := ∅, compl := (·ᶜ), top := univ, sdiff := (· \ ·) } instance : HasSSubset (Set α) := ⟨(· < ·)⟩ @[simp] theorem top_eq_univ : (⊤ : Set α) = univ := rfl @[simp] theorem bot_eq_empty : (⊥ : Set α) = ∅ := rfl @[simp] theorem sup_eq_union : ((· ⊔ ·) : Set α → Set α → Set α) = (· ∪ ·) := rfl @[simp] theorem inf_eq_inter : ((· ⊓ ·) : Set α → Set α → Set α) = (· ∩ ·) := rfl @[simp] theorem le_eq_subset : ((· ≤ ·) : Set α → Set α → Prop) = (· ⊆ ·) := rfl @[simp] theorem lt_eq_ssubset : ((· < ·) : Set α → Set α → Prop) = (· ⊂ ·) := rfl theorem le_iff_subset : s ≤ t ↔ s ⊆ t := Iff.rfl theorem lt_iff_ssubset : s < t ↔ s ⊂ t := Iff.rfl alias ⟨_root_.LE.le.subset, _root_.HasSubset.Subset.le⟩ := le_iff_subset alias ⟨_root_.LT.lt.ssubset, _root_.HasSSubset.SSubset.lt⟩ := lt_iff_ssubset instance PiSetCoe.canLift (ι : Type u) (α : ι → Type v) [∀ i, Nonempty (α i)] (s : Set ι) : CanLift (∀ i : s, α i) (∀ i, α i) (fun f i => f i) fun _ => True := PiSubtype.canLift ι α s instance PiSetCoe.canLift' (ι : Type u) (α : Type v) [Nonempty α] (s : Set ι) : CanLift (s → α) (ι → α) (fun f i => f i) fun _ => True := PiSetCoe.canLift ι (fun _ => α) s end Set section SetCoe variable {α : Type u} instance (s : Set α) : CoeTC s α := ⟨fun x => x.1⟩ theorem Set.coe_eq_subtype (s : Set α) : ↥s = { x // x ∈ s } := rfl @[simp] theorem Set.coe_setOf (p : α → Prop) : ↥{ x | p x } = { x // p x } := rfl -- Porting note (#10618): removed `simp` because `simp` can prove it theorem SetCoe.forall {s : Set α} {p : s → Prop} : (∀ x : s, p x) ↔ ∀ (x) (h : x ∈ s), p ⟨x, h⟩ := Subtype.forall -- Porting note (#10618): removed `simp` because `simp` can prove it theorem SetCoe.exists {s : Set α} {p : s → Prop} : (∃ x : s, p x) ↔ ∃ (x : _) (h : x ∈ s), p ⟨x, h⟩ := Subtype.exists theorem SetCoe.exists' {s : Set α} {p : ∀ x, x ∈ s → Prop} : (∃ (x : _) (h : x ∈ s), p x h) ↔ ∃ x : s, p x.1 x.2 := (@SetCoe.exists _ _ fun x => p x.1 x.2).symm theorem SetCoe.forall' {s : Set α} {p : ∀ x, x ∈ s → Prop} : (∀ (x) (h : x ∈ s), p x h) ↔ ∀ x : s, p x.1 x.2 := (@SetCoe.forall _ _ fun x => p x.1 x.2).symm @[simp] theorem set_coe_cast : ∀ {s t : Set α} (H' : s = t) (H : ↥s = ↥t) (x : s), cast H x = ⟨x.1, H' ▸ x.2⟩ | _, _, rfl, _, _ => rfl theorem SetCoe.ext {s : Set α} {a b : s} : (a : α) = b → a = b := Subtype.eq theorem SetCoe.ext_iff {s : Set α} {a b : s} : (↑a : α) = ↑b ↔ a = b := Iff.intro SetCoe.ext fun h => h ▸ rfl end SetCoe /-- See also `Subtype.prop` -/ theorem Subtype.mem {α : Type*} {s : Set α} (p : s) : (p : α) ∈ s := p.prop /-- Duplicate of `Eq.subset'`, which currently has elaboration problems. -/ theorem Eq.subset {α} {s t : Set α} : s = t → s ⊆ t := fun h₁ _ h₂ => by rw [← h₁]; exact h₂ namespace Set variable {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} {a b : α} {s s₁ s₂ t t₁ t₂ u : Set α} instance : Inhabited (Set α) := ⟨∅⟩ @[trans] theorem mem_of_mem_of_subset {x : α} {s t : Set α} (hx : x ∈ s) (h : s ⊆ t) : x ∈ t := h hx theorem forall_in_swap {p : α → β → Prop} : (∀ a ∈ s, ∀ (b), p a b) ↔ ∀ (b), ∀ a ∈ s, p a b := by tauto /-! ### Lemmas about `mem` and `setOf` -/ theorem mem_setOf {a : α} {p : α → Prop} : a ∈ { x | p x } ↔ p a := Iff.rfl /-- This lemma is intended for use with `rw` where a membership predicate is needed, hence the explicit argument and the equality in the reverse direction from normal. See also `Set.mem_setOf_eq` for the reverse direction applied to an argument. -/ theorem eq_mem_setOf (p : α → Prop) : p = (· ∈ {a | p a}) := rfl /-- If `h : a ∈ {x | p x}` then `h.out : p x`. These are definitionally equal, but this can nevertheless be useful for various reasons, e.g. to apply further projection notation or in an argument to `simp`. -/ theorem _root_.Membership.mem.out {p : α → Prop} {a : α} (h : a ∈ { x | p x }) : p a := h theorem nmem_setOf_iff {a : α} {p : α → Prop} : a ∉ { x | p x } ↔ ¬p a := Iff.rfl @[simp] theorem setOf_mem_eq {s : Set α} : { x | x ∈ s } = s := rfl theorem setOf_set {s : Set α} : setOf s = s := rfl theorem setOf_app_iff {p : α → Prop} {x : α} : { x | p x } x ↔ p x := Iff.rfl theorem mem_def {a : α} {s : Set α} : a ∈ s ↔ s a := Iff.rfl theorem setOf_bijective : Bijective (setOf : (α → Prop) → Set α) := bijective_id theorem subset_setOf {p : α → Prop} {s : Set α} : s ⊆ setOf p ↔ ∀ x, x ∈ s → p x := Iff.rfl theorem setOf_subset {p : α → Prop} {s : Set α} : setOf p ⊆ s ↔ ∀ x, p x → x ∈ s := Iff.rfl @[simp] theorem setOf_subset_setOf {p q : α → Prop} : { a | p a } ⊆ { a | q a } ↔ ∀ a, p a → q a := Iff.rfl theorem setOf_and {p q : α → Prop} : { a | p a ∧ q a } = { a | p a } ∩ { a | q a } := rfl theorem setOf_or {p q : α → Prop} : { a | p a ∨ q a } = { a | p a } ∪ { a | q a } := rfl /-! ### Subset and strict subset relations -/ instance : IsRefl (Set α) (· ⊆ ·) := show IsRefl (Set α) (· ≤ ·) by infer_instance instance : IsTrans (Set α) (· ⊆ ·) := show IsTrans (Set α) (· ≤ ·) by infer_instance instance : Trans ((· ⊆ ·) : Set α → Set α → Prop) (· ⊆ ·) (· ⊆ ·) := show Trans (· ≤ ·) (· ≤ ·) (· ≤ ·) by infer_instance instance : IsAntisymm (Set α) (· ⊆ ·) := show IsAntisymm (Set α) (· ≤ ·) by infer_instance instance : IsIrrefl (Set α) (· ⊂ ·) := show IsIrrefl (Set α) (· < ·) by infer_instance instance : IsTrans (Set α) (· ⊂ ·) := show IsTrans (Set α) (· < ·) by infer_instance instance : Trans ((· ⊂ ·) : Set α → Set α → Prop) (· ⊂ ·) (· ⊂ ·) := show Trans (· < ·) (· < ·) (· < ·) by infer_instance instance : Trans ((· ⊂ ·) : Set α → Set α → Prop) (· ⊆ ·) (· ⊂ ·) := show Trans (· < ·) (· ≤ ·) (· < ·) by infer_instance instance : Trans ((· ⊆ ·) : Set α → Set α → Prop) (· ⊂ ·) (· ⊂ ·) := show Trans (· ≤ ·) (· < ·) (· < ·) by infer_instance instance : IsAsymm (Set α) (· ⊂ ·) := show IsAsymm (Set α) (· < ·) by infer_instance instance : IsNonstrictStrictOrder (Set α) (· ⊆ ·) (· ⊂ ·) := ⟨fun _ _ => Iff.rfl⟩ -- TODO(Jeremy): write a tactic to unfold specific instances of generic notation? theorem subset_def : (s ⊆ t) = ∀ x, x ∈ s → x ∈ t := rfl theorem ssubset_def : (s ⊂ t) = (s ⊆ t ∧ ¬t ⊆ s) := rfl @[refl] theorem Subset.refl (a : Set α) : a ⊆ a := fun _ => id theorem Subset.rfl {s : Set α} : s ⊆ s := Subset.refl s @[trans] theorem Subset.trans {a b c : Set α} (ab : a ⊆ b) (bc : b ⊆ c) : a ⊆ c := fun _ h => bc <| ab h @[trans] theorem mem_of_eq_of_mem {x y : α} {s : Set α} (hx : x = y) (h : y ∈ s) : x ∈ s := hx.symm ▸ h theorem Subset.antisymm {a b : Set α} (h₁ : a ⊆ b) (h₂ : b ⊆ a) : a = b := Set.ext fun _ => ⟨@h₁ _, @h₂ _⟩ theorem Subset.antisymm_iff {a b : Set α} : a = b ↔ a ⊆ b ∧ b ⊆ a := ⟨fun e => ⟨e.subset, e.symm.subset⟩, fun ⟨h₁, h₂⟩ => Subset.antisymm h₁ h₂⟩ -- an alternative name theorem eq_of_subset_of_subset {a b : Set α} : a ⊆ b → b ⊆ a → a = b := Subset.antisymm theorem mem_of_subset_of_mem {s₁ s₂ : Set α} {a : α} (h : s₁ ⊆ s₂) : a ∈ s₁ → a ∈ s₂ := @h _ theorem not_mem_subset (h : s ⊆ t) : a ∉ t → a ∉ s := mt <| mem_of_subset_of_mem h theorem not_subset : ¬s ⊆ t ↔ ∃ a ∈ s, a ∉ t := by simp only [subset_def, not_forall, exists_prop] lemma eq_of_forall_subset_iff (h : ∀ u, s ⊆ u ↔ t ⊆ u) : s = t := eq_of_forall_ge_iff h /-! ### Definition of strict subsets `s ⊂ t` and basic properties. -/ protected theorem eq_or_ssubset_of_subset (h : s ⊆ t) : s = t ∨ s ⊂ t := eq_or_lt_of_le h theorem exists_of_ssubset {s t : Set α} (h : s ⊂ t) : ∃ x ∈ t, x ∉ s := not_subset.1 h.2 protected theorem ssubset_iff_subset_ne {s t : Set α} : s ⊂ t ↔ s ⊆ t ∧ s ≠ t := @lt_iff_le_and_ne (Set α) _ s t theorem ssubset_iff_of_subset {s t : Set α} (h : s ⊆ t) : s ⊂ t ↔ ∃ x ∈ t, x ∉ s := ⟨exists_of_ssubset, fun ⟨_, hxt, hxs⟩ => ⟨h, fun h => hxs <| h hxt⟩⟩ protected theorem ssubset_of_ssubset_of_subset {s₁ s₂ s₃ : Set α} (hs₁s₂ : s₁ ⊂ s₂) (hs₂s₃ : s₂ ⊆ s₃) : s₁ ⊂ s₃ := ⟨Subset.trans hs₁s₂.1 hs₂s₃, fun hs₃s₁ => hs₁s₂.2 (Subset.trans hs₂s₃ hs₃s₁)⟩ protected theorem ssubset_of_subset_of_ssubset {s₁ s₂ s₃ : Set α} (hs₁s₂ : s₁ ⊆ s₂) (hs₂s₃ : s₂ ⊂ s₃) : s₁ ⊂ s₃ := ⟨Subset.trans hs₁s₂ hs₂s₃.1, fun hs₃s₁ => hs₂s₃.2 (Subset.trans hs₃s₁ hs₁s₂)⟩ theorem not_mem_empty (x : α) : ¬x ∈ (∅ : Set α) := id -- Porting note (#10618): removed `simp` because `simp` can prove it theorem not_not_mem : ¬a ∉ s ↔ a ∈ s := not_not /-! ### Non-empty sets -/ -- Porting note: we seem to need parentheses at `(↥s)`, -- even if we increase the right precedence of `↥` in `Mathlib.Tactic.Coe`. -- Porting note: removed `simp` as it is competing with `nonempty_subtype`. -- @[simp] theorem nonempty_coe_sort {s : Set α} : Nonempty (↥s) ↔ s.Nonempty := nonempty_subtype alias ⟨_, Nonempty.coe_sort⟩ := nonempty_coe_sort theorem nonempty_def : s.Nonempty ↔ ∃ x, x ∈ s := Iff.rfl theorem nonempty_of_mem {x} (h : x ∈ s) : s.Nonempty := ⟨x, h⟩ theorem Nonempty.not_subset_empty : s.Nonempty → ¬s ⊆ ∅ | ⟨_, hx⟩, hs => hs hx /-- Extract a witness from `s.Nonempty`. This function might be used instead of case analysis on the argument. Note that it makes a proof depend on the `Classical.choice` axiom. -/ protected noncomputable def Nonempty.some (h : s.Nonempty) : α := Classical.choose h protected theorem Nonempty.some_mem (h : s.Nonempty) : h.some ∈ s := Classical.choose_spec h theorem Nonempty.mono (ht : s ⊆ t) (hs : s.Nonempty) : t.Nonempty := hs.imp ht theorem nonempty_of_not_subset (h : ¬s ⊆ t) : (s \ t).Nonempty := let ⟨x, xs, xt⟩ := not_subset.1 h ⟨x, xs, xt⟩ theorem nonempty_of_ssubset (ht : s ⊂ t) : (t \ s).Nonempty := nonempty_of_not_subset ht.2 theorem Nonempty.of_diff (h : (s \ t).Nonempty) : s.Nonempty := h.imp fun _ => And.left theorem nonempty_of_ssubset' (ht : s ⊂ t) : t.Nonempty := (nonempty_of_ssubset ht).of_diff theorem Nonempty.inl (hs : s.Nonempty) : (s ∪ t).Nonempty := hs.imp fun _ => Or.inl theorem Nonempty.inr (ht : t.Nonempty) : (s ∪ t).Nonempty := ht.imp fun _ => Or.inr @[simp] theorem union_nonempty : (s ∪ t).Nonempty ↔ s.Nonempty ∨ t.Nonempty := exists_or theorem Nonempty.left (h : (s ∩ t).Nonempty) : s.Nonempty := h.imp fun _ => And.left theorem Nonempty.right (h : (s ∩ t).Nonempty) : t.Nonempty := h.imp fun _ => And.right theorem inter_nonempty : (s ∩ t).Nonempty ↔ ∃ x, x ∈ s ∧ x ∈ t := Iff.rfl theorem inter_nonempty_iff_exists_left : (s ∩ t).Nonempty ↔ ∃ x ∈ s, x ∈ t := by simp_rw [inter_nonempty] theorem inter_nonempty_iff_exists_right : (s ∩ t).Nonempty ↔ ∃ x ∈ t, x ∈ s := by simp_rw [inter_nonempty, and_comm] theorem nonempty_iff_univ_nonempty : Nonempty α ↔ (univ : Set α).Nonempty := ⟨fun ⟨x⟩ => ⟨x, trivial⟩, fun ⟨x, _⟩ => ⟨x⟩⟩ @[simp] theorem univ_nonempty : ∀ [Nonempty α], (univ : Set α).Nonempty | ⟨x⟩ => ⟨x, trivial⟩ theorem Nonempty.to_subtype : s.Nonempty → Nonempty (↥s) := nonempty_subtype.2 theorem Nonempty.to_type : s.Nonempty → Nonempty α := fun ⟨x, _⟩ => ⟨x⟩ instance univ.nonempty [Nonempty α] : Nonempty (↥(Set.univ : Set α)) := Set.univ_nonempty.to_subtype theorem nonempty_of_nonempty_subtype [Nonempty (↥s)] : s.Nonempty := nonempty_subtype.mp ‹_› /-! ### Lemmas about the empty set -/ theorem empty_def : (∅ : Set α) = { _x : α | False } := rfl @[simp] theorem mem_empty_iff_false (x : α) : x ∈ (∅ : Set α) ↔ False := Iff.rfl @[simp] theorem setOf_false : { _a : α | False } = ∅ := rfl @[simp] theorem setOf_bot : { _x : α | ⊥ } = ∅ := rfl @[simp] theorem empty_subset (s : Set α) : ∅ ⊆ s := nofun @[simp] theorem subset_empty_iff {s : Set α} : s ⊆ ∅ ↔ s = ∅ := (Subset.antisymm_iff.trans <| and_iff_left (empty_subset _)).symm theorem eq_empty_iff_forall_not_mem {s : Set α} : s = ∅ ↔ ∀ x, x ∉ s := subset_empty_iff.symm theorem eq_empty_of_forall_not_mem (h : ∀ x, x ∉ s) : s = ∅ := subset_empty_iff.1 h theorem eq_empty_of_subset_empty {s : Set α} : s ⊆ ∅ → s = ∅ := subset_empty_iff.1 theorem eq_empty_of_isEmpty [IsEmpty α] (s : Set α) : s = ∅ := eq_empty_of_subset_empty fun x _ => isEmptyElim x /-- There is exactly one set of a type that is empty. -/ instance uniqueEmpty [IsEmpty α] : Unique (Set α) where default := ∅ uniq := eq_empty_of_isEmpty /-- See also `Set.nonempty_iff_ne_empty`. -/ theorem not_nonempty_iff_eq_empty {s : Set α} : ¬s.Nonempty ↔ s = ∅ := by simp only [Set.Nonempty, not_exists, eq_empty_iff_forall_not_mem] /-- See also `Set.not_nonempty_iff_eq_empty`. -/ theorem nonempty_iff_ne_empty : s.Nonempty ↔ s ≠ ∅ := not_nonempty_iff_eq_empty.not_right /-- See also `nonempty_iff_ne_empty'`. -/ theorem not_nonempty_iff_eq_empty' : ¬Nonempty s ↔ s = ∅ := by rw [nonempty_subtype, not_exists, eq_empty_iff_forall_not_mem] /-- See also `not_nonempty_iff_eq_empty'`. -/ theorem nonempty_iff_ne_empty' : Nonempty s ↔ s ≠ ∅ := not_nonempty_iff_eq_empty'.not_right alias ⟨Nonempty.ne_empty, _⟩ := nonempty_iff_ne_empty @[simp] theorem not_nonempty_empty : ¬(∅ : Set α).Nonempty := fun ⟨_, hx⟩ => hx -- Porting note: removing `@[simp]` as it is competing with `isEmpty_subtype`. -- @[simp] theorem isEmpty_coe_sort {s : Set α} : IsEmpty (↥s) ↔ s = ∅ := not_iff_not.1 <| by simpa using nonempty_iff_ne_empty theorem eq_empty_or_nonempty (s : Set α) : s = ∅ ∨ s.Nonempty := or_iff_not_imp_left.2 nonempty_iff_ne_empty.2 theorem subset_eq_empty {s t : Set α} (h : t ⊆ s) (e : s = ∅) : t = ∅ := subset_empty_iff.1 <| e ▸ h theorem forall_mem_empty {p : α → Prop} : (∀ x ∈ (∅ : Set α), p x) ↔ True := iff_true_intro fun _ => False.elim @[deprecated (since := "2024-03-23")] alias ball_empty_iff := forall_mem_empty instance (α : Type u) : IsEmpty.{u + 1} (↥(∅ : Set α)) := ⟨fun x => x.2⟩ @[simp] theorem empty_ssubset : ∅ ⊂ s ↔ s.Nonempty := (@bot_lt_iff_ne_bot (Set α) _ _ _).trans nonempty_iff_ne_empty.symm alias ⟨_, Nonempty.empty_ssubset⟩ := empty_ssubset /-! ### Universal set. In Lean `@univ α` (or `univ : Set α`) is the set that contains all elements of type `α`. Mathematically it is the same as `α` but it has a different type. -/ @[simp] theorem setOf_true : { _x : α | True } = univ := rfl @[simp] theorem setOf_top : { _x : α | ⊤ } = univ := rfl @[simp] theorem univ_eq_empty_iff : (univ : Set α) = ∅ ↔ IsEmpty α := eq_empty_iff_forall_not_mem.trans ⟨fun H => ⟨fun x => H x trivial⟩, fun H x _ => @IsEmpty.false α H x⟩ theorem empty_ne_univ [Nonempty α] : (∅ : Set α) ≠ univ := fun e => not_isEmpty_of_nonempty α <| univ_eq_empty_iff.1 e.symm @[simp] theorem subset_univ (s : Set α) : s ⊆ univ := fun _ _ => trivial @[simp] theorem univ_subset_iff {s : Set α} : univ ⊆ s ↔ s = univ := @top_le_iff _ _ _ s alias ⟨eq_univ_of_univ_subset, _⟩ := univ_subset_iff theorem eq_univ_iff_forall {s : Set α} : s = univ ↔ ∀ x, x ∈ s := univ_subset_iff.symm.trans <| forall_congr' fun _ => imp_iff_right trivial theorem eq_univ_of_forall {s : Set α} : (∀ x, x ∈ s) → s = univ := eq_univ_iff_forall.2 theorem Nonempty.eq_univ [Subsingleton α] : s.Nonempty → s = univ := by rintro ⟨x, hx⟩ exact eq_univ_of_forall fun y => by rwa [Subsingleton.elim y x] theorem eq_univ_of_subset {s t : Set α} (h : s ⊆ t) (hs : s = univ) : t = univ := eq_univ_of_univ_subset <| (hs ▸ h : univ ⊆ t) theorem exists_mem_of_nonempty (α) : ∀ [Nonempty α], ∃ x : α, x ∈ (univ : Set α) | ⟨x⟩ => ⟨x, trivial⟩ theorem ne_univ_iff_exists_not_mem {α : Type*} (s : Set α) : s ≠ univ ↔ ∃ a, a ∉ s := by rw [← not_forall, ← eq_univ_iff_forall] theorem not_subset_iff_exists_mem_not_mem {α : Type*} {s t : Set α} : ¬s ⊆ t ↔ ∃ x, x ∈ s ∧ x ∉ t := by simp [subset_def] theorem univ_unique [Unique α] : @Set.univ α = {default} := Set.ext fun x => iff_of_true trivial <| Subsingleton.elim x default theorem ssubset_univ_iff : s ⊂ univ ↔ s ≠ univ := lt_top_iff_ne_top instance nontrivial_of_nonempty [Nonempty α] : Nontrivial (Set α) := ⟨⟨∅, univ, empty_ne_univ⟩⟩ /-! ### Lemmas about union -/ theorem union_def {s₁ s₂ : Set α} : s₁ ∪ s₂ = { a | a ∈ s₁ ∨ a ∈ s₂ } := rfl theorem mem_union_left {x : α} {a : Set α} (b : Set α) : x ∈ a → x ∈ a ∪ b := Or.inl theorem mem_union_right {x : α} {b : Set α} (a : Set α) : x ∈ b → x ∈ a ∪ b := Or.inr theorem mem_or_mem_of_mem_union {x : α} {a b : Set α} (H : x ∈ a ∪ b) : x ∈ a ∨ x ∈ b := H theorem MemUnion.elim {x : α} {a b : Set α} {P : Prop} (H₁ : x ∈ a ∪ b) (H₂ : x ∈ a → P) (H₃ : x ∈ b → P) : P := Or.elim H₁ H₂ H₃ @[simp] theorem mem_union (x : α) (a b : Set α) : x ∈ a ∪ b ↔ x ∈ a ∨ x ∈ b := Iff.rfl @[simp] theorem union_self (a : Set α) : a ∪ a = a := ext fun _ => or_self_iff @[simp] theorem union_empty (a : Set α) : a ∪ ∅ = a := ext fun _ => or_false_iff _ @[simp] theorem empty_union (a : Set α) : ∅ ∪ a = a := ext fun _ => false_or_iff _ theorem union_comm (a b : Set α) : a ∪ b = b ∪ a := ext fun _ => or_comm theorem union_assoc (a b c : Set α) : a ∪ b ∪ c = a ∪ (b ∪ c) := ext fun _ => or_assoc instance union_isAssoc : Std.Associative (α := Set α) (· ∪ ·) := ⟨union_assoc⟩ instance union_isComm : Std.Commutative (α := Set α) (· ∪ ·) := ⟨union_comm⟩ theorem union_left_comm (s₁ s₂ s₃ : Set α) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) := ext fun _ => or_left_comm theorem union_right_comm (s₁ s₂ s₃ : Set α) : s₁ ∪ s₂ ∪ s₃ = s₁ ∪ s₃ ∪ s₂ := ext fun _ => or_right_comm @[simp] theorem union_eq_left {s t : Set α} : s ∪ t = s ↔ t ⊆ s := sup_eq_left @[simp] theorem union_eq_right {s t : Set α} : s ∪ t = t ↔ s ⊆ t := sup_eq_right theorem union_eq_self_of_subset_left {s t : Set α} (h : s ⊆ t) : s ∪ t = t := union_eq_right.mpr h theorem union_eq_self_of_subset_right {s t : Set α} (h : t ⊆ s) : s ∪ t = s := union_eq_left.mpr h @[simp] theorem subset_union_left {s t : Set α} : s ⊆ s ∪ t := fun _ => Or.inl @[simp] theorem subset_union_right {s t : Set α} : t ⊆ s ∪ t := fun _ => Or.inr theorem union_subset {s t r : Set α} (sr : s ⊆ r) (tr : t ⊆ r) : s ∪ t ⊆ r := fun _ => Or.rec (@sr _) (@tr _) @[simp] theorem union_subset_iff {s t u : Set α} : s ∪ t ⊆ u ↔ s ⊆ u ∧ t ⊆ u := (forall_congr' fun _ => or_imp).trans forall_and @[gcongr] theorem union_subset_union {s₁ s₂ t₁ t₂ : Set α} (h₁ : s₁ ⊆ s₂) (h₂ : t₁ ⊆ t₂) : s₁ ∪ t₁ ⊆ s₂ ∪ t₂ := fun _ => Or.imp (@h₁ _) (@h₂ _) @[gcongr] theorem union_subset_union_left {s₁ s₂ : Set α} (t) (h : s₁ ⊆ s₂) : s₁ ∪ t ⊆ s₂ ∪ t := union_subset_union h Subset.rfl @[gcongr] theorem union_subset_union_right (s) {t₁ t₂ : Set α} (h : t₁ ⊆ t₂) : s ∪ t₁ ⊆ s ∪ t₂ := union_subset_union Subset.rfl h theorem subset_union_of_subset_left {s t : Set α} (h : s ⊆ t) (u : Set α) : s ⊆ t ∪ u := h.trans subset_union_left theorem subset_union_of_subset_right {s u : Set α} (h : s ⊆ u) (t : Set α) : s ⊆ t ∪ u := h.trans subset_union_right -- Porting note: replaced `⊔` in RHS theorem union_congr_left (ht : t ⊆ s ∪ u) (hu : u ⊆ s ∪ t) : s ∪ t = s ∪ u := sup_congr_left ht hu theorem union_congr_right (hs : s ⊆ t ∪ u) (ht : t ⊆ s ∪ u) : s ∪ u = t ∪ u := sup_congr_right hs ht theorem union_eq_union_iff_left : s ∪ t = s ∪ u ↔ t ⊆ s ∪ u ∧ u ⊆ s ∪ t := sup_eq_sup_iff_left theorem union_eq_union_iff_right : s ∪ u = t ∪ u ↔ s ⊆ t ∪ u ∧ t ⊆ s ∪ u := sup_eq_sup_iff_right @[simp] theorem union_empty_iff {s t : Set α} : s ∪ t = ∅ ↔ s = ∅ ∧ t = ∅ := by simp only [← subset_empty_iff] exact union_subset_iff @[simp] theorem union_univ (s : Set α) : s ∪ univ = univ := sup_top_eq _ @[simp] theorem univ_union (s : Set α) : univ ∪ s = univ := top_sup_eq _ /-! ### Lemmas about intersection -/ theorem inter_def {s₁ s₂ : Set α} : s₁ ∩ s₂ = { a | a ∈ s₁ ∧ a ∈ s₂ } := rfl @[simp, mfld_simps] theorem mem_inter_iff (x : α) (a b : Set α) : x ∈ a ∩ b ↔ x ∈ a ∧ x ∈ b := Iff.rfl theorem mem_inter {x : α} {a b : Set α} (ha : x ∈ a) (hb : x ∈ b) : x ∈ a ∩ b := ⟨ha, hb⟩ theorem mem_of_mem_inter_left {x : α} {a b : Set α} (h : x ∈ a ∩ b) : x ∈ a := h.left theorem mem_of_mem_inter_right {x : α} {a b : Set α} (h : x ∈ a ∩ b) : x ∈ b := h.right @[simp] theorem inter_self (a : Set α) : a ∩ a = a := ext fun _ => and_self_iff @[simp] theorem inter_empty (a : Set α) : a ∩ ∅ = ∅ := ext fun _ => and_false_iff _ @[simp] theorem empty_inter (a : Set α) : ∅ ∩ a = ∅ := ext fun _ => false_and_iff _ theorem inter_comm (a b : Set α) : a ∩ b = b ∩ a := ext fun _ => and_comm theorem inter_assoc (a b c : Set α) : a ∩ b ∩ c = a ∩ (b ∩ c) := ext fun _ => and_assoc instance inter_isAssoc : Std.Associative (α := Set α) (· ∩ ·) := ⟨inter_assoc⟩ instance inter_isComm : Std.Commutative (α := Set α) (· ∩ ·) := ⟨inter_comm⟩ theorem inter_left_comm (s₁ s₂ s₃ : Set α) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := ext fun _ => and_left_comm theorem inter_right_comm (s₁ s₂ s₃ : Set α) : s₁ ∩ s₂ ∩ s₃ = s₁ ∩ s₃ ∩ s₂ := ext fun _ => and_right_comm @[simp, mfld_simps] theorem inter_subset_left {s t : Set α} : s ∩ t ⊆ s := fun _ => And.left @[simp] theorem inter_subset_right {s t : Set α} : s ∩ t ⊆ t := fun _ => And.right theorem subset_inter {s t r : Set α} (rs : r ⊆ s) (rt : r ⊆ t) : r ⊆ s ∩ t := fun _ h => ⟨rs h, rt h⟩ @[simp] theorem subset_inter_iff {s t r : Set α} : r ⊆ s ∩ t ↔ r ⊆ s ∧ r ⊆ t := (forall_congr' fun _ => imp_and).trans forall_and @[simp] lemma inter_eq_left : s ∩ t = s ↔ s ⊆ t := inf_eq_left @[simp] lemma inter_eq_right : s ∩ t = t ↔ t ⊆ s := inf_eq_right @[simp] lemma left_eq_inter : s = s ∩ t ↔ s ⊆ t := left_eq_inf @[simp] lemma right_eq_inter : t = s ∩ t ↔ t ⊆ s := right_eq_inf theorem inter_eq_self_of_subset_left {s t : Set α} : s ⊆ t → s ∩ t = s := inter_eq_left.mpr theorem inter_eq_self_of_subset_right {s t : Set α} : t ⊆ s → s ∩ t = t := inter_eq_right.mpr theorem inter_congr_left (ht : s ∩ u ⊆ t) (hu : s ∩ t ⊆ u) : s ∩ t = s ∩ u := inf_congr_left ht hu theorem inter_congr_right (hs : t ∩ u ⊆ s) (ht : s ∩ u ⊆ t) : s ∩ u = t ∩ u := inf_congr_right hs ht theorem inter_eq_inter_iff_left : s ∩ t = s ∩ u ↔ s ∩ u ⊆ t ∧ s ∩ t ⊆ u := inf_eq_inf_iff_left theorem inter_eq_inter_iff_right : s ∩ u = t ∩ u ↔ t ∩ u ⊆ s ∧ s ∩ u ⊆ t := inf_eq_inf_iff_right @[simp, mfld_simps] theorem inter_univ (a : Set α) : a ∩ univ = a := inf_top_eq _ @[simp, mfld_simps] theorem univ_inter (a : Set α) : univ ∩ a = a := top_inf_eq _ @[gcongr] theorem inter_subset_inter {s₁ s₂ t₁ t₂ : Set α} (h₁ : s₁ ⊆ t₁) (h₂ : s₂ ⊆ t₂) : s₁ ∩ s₂ ⊆ t₁ ∩ t₂ := fun _ => And.imp (@h₁ _) (@h₂ _) @[gcongr] theorem inter_subset_inter_left {s t : Set α} (u : Set α) (H : s ⊆ t) : s ∩ u ⊆ t ∩ u := inter_subset_inter H Subset.rfl @[gcongr] theorem inter_subset_inter_right {s t : Set α} (u : Set α) (H : s ⊆ t) : u ∩ s ⊆ u ∩ t := inter_subset_inter Subset.rfl H theorem union_inter_cancel_left {s t : Set α} : (s ∪ t) ∩ s = s := inter_eq_self_of_subset_right subset_union_left theorem union_inter_cancel_right {s t : Set α} : (s ∪ t) ∩ t = t := inter_eq_self_of_subset_right subset_union_right theorem inter_setOf_eq_sep (s : Set α) (p : α → Prop) : s ∩ {a | p a} = {a ∈ s | p a} := rfl theorem setOf_inter_eq_sep (p : α → Prop) (s : Set α) : {a | p a} ∩ s = {a ∈ s | p a} := inter_comm _ _ /-! ### Distributivity laws -/ theorem inter_union_distrib_left (s t u : Set α) : s ∩ (t ∪ u) = s ∩ t ∪ s ∩ u := inf_sup_left _ _ _ theorem union_inter_distrib_right (s t u : Set α) : (s ∪ t) ∩ u = s ∩ u ∪ t ∩ u := inf_sup_right _ _ _ theorem union_inter_distrib_left (s t u : Set α) : s ∪ t ∩ u = (s ∪ t) ∩ (s ∪ u) := sup_inf_left _ _ _ theorem inter_union_distrib_right (s t u : Set α) : s ∩ t ∪ u = (s ∪ u) ∩ (t ∪ u) := sup_inf_right _ _ _ @[deprecated (since := "2024-03-22")] alias inter_distrib_left := inter_union_distrib_left @[deprecated (since := "2024-03-22")] alias inter_distrib_right := union_inter_distrib_right @[deprecated (since := "2024-03-22")] alias union_distrib_left := union_inter_distrib_left @[deprecated (since := "2024-03-22")] alias union_distrib_right := inter_union_distrib_right theorem union_union_distrib_left (s t u : Set α) : s ∪ (t ∪ u) = s ∪ t ∪ (s ∪ u) := sup_sup_distrib_left _ _ _ theorem union_union_distrib_right (s t u : Set α) : s ∪ t ∪ u = s ∪ u ∪ (t ∪ u) := sup_sup_distrib_right _ _ _ theorem inter_inter_distrib_left (s t u : Set α) : s ∩ (t ∩ u) = s ∩ t ∩ (s ∩ u) := inf_inf_distrib_left _ _ _ theorem inter_inter_distrib_right (s t u : Set α) : s ∩ t ∩ u = s ∩ u ∩ (t ∩ u) := inf_inf_distrib_right _ _ _ theorem union_union_union_comm (s t u v : Set α) : s ∪ t ∪ (u ∪ v) = s ∪ u ∪ (t ∪ v) := sup_sup_sup_comm _ _ _ _ theorem inter_inter_inter_comm (s t u v : Set α) : s ∩ t ∩ (u ∩ v) = s ∩ u ∩ (t ∩ v) := inf_inf_inf_comm _ _ _ _ /-! ### Lemmas about `insert` `insert α s` is the set `{α} ∪ s`. -/ theorem insert_def (x : α) (s : Set α) : insert x s = { y | y = x ∨ y ∈ s } := rfl @[simp] theorem subset_insert (x : α) (s : Set α) : s ⊆ insert x s := fun _ => Or.inr theorem mem_insert (x : α) (s : Set α) : x ∈ insert x s := Or.inl rfl theorem mem_insert_of_mem {x : α} {s : Set α} (y : α) : x ∈ s → x ∈ insert y s := Or.inr theorem eq_or_mem_of_mem_insert {x a : α} {s : Set α} : x ∈ insert a s → x = a ∨ x ∈ s := id theorem mem_of_mem_insert_of_ne : b ∈ insert a s → b ≠ a → b ∈ s := Or.resolve_left theorem eq_of_not_mem_of_mem_insert : b ∈ insert a s → b ∉ s → b = a := Or.resolve_right @[simp] theorem mem_insert_iff {x a : α} {s : Set α} : x ∈ insert a s ↔ x = a ∨ x ∈ s := Iff.rfl @[simp] theorem insert_eq_of_mem {a : α} {s : Set α} (h : a ∈ s) : insert a s = s := ext fun _ => or_iff_right_of_imp fun e => e.symm ▸ h theorem ne_insert_of_not_mem {s : Set α} (t : Set α) {a : α} : a ∉ s → s ≠ insert a t := mt fun e => e.symm ▸ mem_insert _ _ @[simp] theorem insert_eq_self : insert a s = s ↔ a ∈ s := ⟨fun h => h ▸ mem_insert _ _, insert_eq_of_mem⟩ theorem insert_ne_self : insert a s ≠ s ↔ a ∉ s := insert_eq_self.not theorem insert_subset_iff : insert a s ⊆ t ↔ a ∈ t ∧ s ⊆ t := by simp only [subset_def, mem_insert_iff, or_imp, forall_and, forall_eq] theorem insert_subset (ha : a ∈ t) (hs : s ⊆ t) : insert a s ⊆ t := insert_subset_iff.mpr ⟨ha, hs⟩ theorem insert_subset_insert (h : s ⊆ t) : insert a s ⊆ insert a t := fun _ => Or.imp_right (@h _) @[simp] theorem insert_subset_insert_iff (ha : a ∉ s) : insert a s ⊆ insert a t ↔ s ⊆ t := by refine ⟨fun h x hx => ?_, insert_subset_insert⟩ rcases h (subset_insert _ _ hx) with (rfl | hxt) exacts [(ha hx).elim, hxt] theorem subset_insert_iff_of_not_mem (ha : a ∉ s) : s ⊆ insert a t ↔ s ⊆ t := forall₂_congr fun _ hb => or_iff_right <| ne_of_mem_of_not_mem hb ha theorem ssubset_iff_insert {s t : Set α} : s ⊂ t ↔ ∃ a ∉ s, insert a s ⊆ t := by simp only [insert_subset_iff, exists_and_right, ssubset_def, not_subset] aesop theorem ssubset_insert {s : Set α} {a : α} (h : a ∉ s) : s ⊂ insert a s := ssubset_iff_insert.2 ⟨a, h, Subset.rfl⟩ theorem insert_comm (a b : α) (s : Set α) : insert a (insert b s) = insert b (insert a s) := ext fun _ => or_left_comm -- Porting note (#10618): removing `simp` attribute because `simp` can prove it theorem insert_idem (a : α) (s : Set α) : insert a (insert a s) = insert a s := insert_eq_of_mem <| mem_insert _ _ theorem insert_union : insert a s ∪ t = insert a (s ∪ t) := ext fun _ => or_assoc @[simp] theorem union_insert : s ∪ insert a t = insert a (s ∪ t) := ext fun _ => or_left_comm @[simp] theorem insert_nonempty (a : α) (s : Set α) : (insert a s).Nonempty := ⟨a, mem_insert a s⟩ instance (a : α) (s : Set α) : Nonempty (insert a s : Set α) := (insert_nonempty a s).to_subtype theorem insert_inter_distrib (a : α) (s t : Set α) : insert a (s ∩ t) = insert a s ∩ insert a t := ext fun _ => or_and_left theorem insert_union_distrib (a : α) (s t : Set α) : insert a (s ∪ t) = insert a s ∪ insert a t := ext fun _ => or_or_distrib_left theorem insert_inj (ha : a ∉ s) : insert a s = insert b s ↔ a = b := ⟨fun h => eq_of_not_mem_of_mem_insert (h.subst <| mem_insert a s) ha, congr_arg (fun x => insert x s)⟩ -- useful in proofs by induction theorem forall_of_forall_insert {P : α → Prop} {a : α} {s : Set α} (H : ∀ x, x ∈ insert a s → P x) (x) (h : x ∈ s) : P x := H _ (Or.inr h) theorem forall_insert_of_forall {P : α → Prop} {a : α} {s : Set α} (H : ∀ x, x ∈ s → P x) (ha : P a) (x) (h : x ∈ insert a s) : P x := h.elim (fun e => e.symm ▸ ha) (H _) /- Porting note: ∃ x ∈ insert a s, P x is parsed as ∃ x, x ∈ insert a s ∧ P x, where in Lean3 it was parsed as `∃ x, ∃ (h : x ∈ insert a s), P x` -/ theorem exists_mem_insert {P : α → Prop} {a : α} {s : Set α} : (∃ x ∈ insert a s, P x) ↔ (P a ∨ ∃ x ∈ s, P x) := by simp [mem_insert_iff, or_and_right, exists_and_left, exists_or] @[deprecated (since := "2024-03-23")] alias bex_insert_iff := exists_mem_insert theorem forall_mem_insert {P : α → Prop} {a : α} {s : Set α} : (∀ x ∈ insert a s, P x) ↔ P a ∧ ∀ x ∈ s, P x := forall₂_or_left.trans <| and_congr_left' forall_eq @[deprecated (since := "2024-03-23")] alias ball_insert_iff := forall_mem_insert /-! ### Lemmas about singletons -/ /- porting note: instance was in core in Lean3 -/ instance : LawfulSingleton α (Set α) := ⟨fun x => Set.ext fun a => by simp only [mem_empty_iff_false, mem_insert_iff, or_false] exact Iff.rfl⟩ theorem singleton_def (a : α) : ({a} : Set α) = insert a ∅ := (insert_emptyc_eq a).symm @[simp] theorem mem_singleton_iff {a b : α} : a ∈ ({b} : Set α) ↔ a = b := Iff.rfl theorem not_mem_singleton_iff {a b : α} : a ∉ ({b} : Set α) ↔ a ≠ b := Iff.rfl @[simp] theorem setOf_eq_eq_singleton {a : α} : { n | n = a } = {a} := rfl @[simp] theorem setOf_eq_eq_singleton' {a : α} : { x | a = x } = {a} := ext fun _ => eq_comm -- TODO: again, annotation needed --Porting note (#11119): removed `simp` attribute theorem mem_singleton (a : α) : a ∈ ({a} : Set α) := @rfl _ _ theorem eq_of_mem_singleton {x y : α} (h : x ∈ ({y} : Set α)) : x = y := h @[simp] theorem singleton_eq_singleton_iff {x y : α} : {x} = ({y} : Set α) ↔ x = y := Set.ext_iff.trans eq_iff_eq_cancel_left theorem singleton_injective : Injective (singleton : α → Set α) := fun _ _ => singleton_eq_singleton_iff.mp theorem mem_singleton_of_eq {x y : α} (H : x = y) : x ∈ ({y} : Set α) := H theorem insert_eq (x : α) (s : Set α) : insert x s = ({x} : Set α) ∪ s := rfl @[simp] theorem singleton_nonempty (a : α) : ({a} : Set α).Nonempty := ⟨a, rfl⟩ @[simp] theorem singleton_ne_empty (a : α) : ({a} : Set α) ≠ ∅ := (singleton_nonempty _).ne_empty --Porting note (#10618): removed `simp` attribute because `simp` can prove it theorem empty_ssubset_singleton : (∅ : Set α) ⊂ {a} := (singleton_nonempty _).empty_ssubset @[simp] theorem singleton_subset_iff {a : α} {s : Set α} : {a} ⊆ s ↔ a ∈ s := forall_eq theorem singleton_subset_singleton : ({a} : Set α) ⊆ {b} ↔ a = b := by simp theorem set_compr_eq_eq_singleton {a : α} : { b | b = a } = {a} := rfl @[simp] theorem singleton_union : {a} ∪ s = insert a s := rfl @[simp] theorem union_singleton : s ∪ {a} = insert a s := union_comm _ _ @[simp] theorem singleton_inter_nonempty : ({a} ∩ s).Nonempty ↔ a ∈ s := by simp only [Set.Nonempty, mem_inter_iff, mem_singleton_iff, exists_eq_left] @[simp] theorem inter_singleton_nonempty : (s ∩ {a}).Nonempty ↔ a ∈ s := by rw [inter_comm, singleton_inter_nonempty] @[simp] theorem singleton_inter_eq_empty : {a} ∩ s = ∅ ↔ a ∉ s := not_nonempty_iff_eq_empty.symm.trans singleton_inter_nonempty.not @[simp] theorem inter_singleton_eq_empty : s ∩ {a} = ∅ ↔ a ∉ s := by rw [inter_comm, singleton_inter_eq_empty] theorem nmem_singleton_empty {s : Set α} : s ∉ ({∅} : Set (Set α)) ↔ s.Nonempty := nonempty_iff_ne_empty.symm instance uniqueSingleton (a : α) : Unique (↥({a} : Set α)) := ⟨⟨⟨a, mem_singleton a⟩⟩, fun ⟨_, h⟩ => Subtype.eq h⟩ theorem eq_singleton_iff_unique_mem : s = {a} ↔ a ∈ s ∧ ∀ x ∈ s, x = a := Subset.antisymm_iff.trans <| and_comm.trans <| and_congr_left' singleton_subset_iff theorem eq_singleton_iff_nonempty_unique_mem : s = {a} ↔ s.Nonempty ∧ ∀ x ∈ s, x = a := eq_singleton_iff_unique_mem.trans <| and_congr_left fun H => ⟨fun h' => ⟨_, h'⟩, fun ⟨x, h⟩ => H x h ▸ h⟩ -- while `simp` is capable of proving this, it is not capable of turning the LHS into the RHS. @[simp] theorem default_coe_singleton (x : α) : (default : ({x} : Set α)) = ⟨x, rfl⟩ := rfl /-! ### Lemmas about sets defined as `{x ∈ s | p x}`. -/ section Sep variable {p q : α → Prop} {x : α} theorem mem_sep (xs : x ∈ s) (px : p x) : x ∈ { x ∈ s | p x } := ⟨xs, px⟩ @[simp] theorem sep_mem_eq : { x ∈ s | x ∈ t } = s ∩ t := rfl @[simp] theorem mem_sep_iff : x ∈ { x ∈ s | p x } ↔ x ∈ s ∧ p x := Iff.rfl theorem sep_ext_iff : { x ∈ s | p x } = { x ∈ s | q x } ↔ ∀ x ∈ s, p x ↔ q x := by simp_rw [Set.ext_iff, mem_sep_iff, and_congr_right_iff] theorem sep_eq_of_subset (h : s ⊆ t) : { x ∈ t | x ∈ s } = s := inter_eq_self_of_subset_right h @[simp] theorem sep_subset (s : Set α) (p : α → Prop) : { x ∈ s | p x } ⊆ s := fun _ => And.left @[simp] theorem sep_eq_self_iff_mem_true : { x ∈ s | p x } = s ↔ ∀ x ∈ s, p x := by simp_rw [Set.ext_iff, mem_sep_iff, and_iff_left_iff_imp] @[simp] theorem sep_eq_empty_iff_mem_false : { x ∈ s | p x } = ∅ ↔ ∀ x ∈ s, ¬p x := by simp_rw [Set.ext_iff, mem_sep_iff, mem_empty_iff_false, iff_false_iff, not_and] --Porting note (#10618): removed `simp` attribute because `simp` can prove it theorem sep_true : { x ∈ s | True } = s := inter_univ s --Porting note (#10618): removed `simp` attribute because `simp` can prove it theorem sep_false : { x ∈ s | False } = ∅ := inter_empty s --Porting note (#10618): removed `simp` attribute because `simp` can prove it theorem sep_empty (p : α → Prop) : { x ∈ (∅ : Set α) | p x } = ∅ := empty_inter {x | p x} --Porting note (#10618): removed `simp` attribute because `simp` can prove it theorem sep_univ : { x ∈ (univ : Set α) | p x } = { x | p x } := univ_inter {x | p x} @[simp] theorem sep_union : { x | (x ∈ s ∨ x ∈ t) ∧ p x } = { x ∈ s | p x } ∪ { x ∈ t | p x } := union_inter_distrib_right { x | x ∈ s } { x | x ∈ t } p @[simp] theorem sep_inter : { x | (x ∈ s ∧ x ∈ t) ∧ p x } = { x ∈ s | p x } ∩ { x ∈ t | p x } := inter_inter_distrib_right s t {x | p x} @[simp] theorem sep_and : { x ∈ s | p x ∧ q x } = { x ∈ s | p x } ∩ { x ∈ s | q x } := inter_inter_distrib_left s {x | p x} {x | q x} @[simp] theorem sep_or : { x ∈ s | p x ∨ q x } = { x ∈ s | p x } ∪ { x ∈ s | q x } := inter_union_distrib_left s p q @[simp] theorem sep_setOf : { x ∈ { y | p y } | q x } = { x | p x ∧ q x } := rfl end Sep @[simp] theorem subset_singleton_iff {α : Type*} {s : Set α} {x : α} : s ⊆ {x} ↔ ∀ y ∈ s, y = x := Iff.rfl theorem subset_singleton_iff_eq {s : Set α} {x : α} : s ⊆ {x} ↔ s = ∅ ∨ s = {x} := by obtain rfl | hs := s.eq_empty_or_nonempty · exact ⟨fun _ => Or.inl rfl, fun _ => empty_subset _⟩ · simp [eq_singleton_iff_nonempty_unique_mem, hs, hs.ne_empty] theorem Nonempty.subset_singleton_iff (h : s.Nonempty) : s ⊆ {a} ↔ s = {a} := subset_singleton_iff_eq.trans <| or_iff_right h.ne_empty theorem ssubset_singleton_iff {s : Set α} {x : α} : s ⊂ {x} ↔ s = ∅ := by rw [ssubset_iff_subset_ne, subset_singleton_iff_eq, or_and_right, and_not_self_iff, or_false_iff, and_iff_left_iff_imp] exact fun h => h ▸ (singleton_ne_empty _).symm theorem eq_empty_of_ssubset_singleton {s : Set α} {x : α} (hs : s ⊂ {x}) : s = ∅ := ssubset_singleton_iff.1 hs theorem eq_of_nonempty_of_subsingleton {α} [Subsingleton α] (s t : Set α) [Nonempty s] [Nonempty t] : s = t := nonempty_of_nonempty_subtype.eq_univ.trans nonempty_of_nonempty_subtype.eq_univ.symm theorem eq_of_nonempty_of_subsingleton' {α} [Subsingleton α] {s : Set α} (t : Set α) (hs : s.Nonempty) [Nonempty t] : s = t := have := hs.to_subtype; eq_of_nonempty_of_subsingleton s t theorem Nonempty.eq_zero [Subsingleton α] [Zero α] {s : Set α} (h : s.Nonempty) : s = {0} := eq_of_nonempty_of_subsingleton' {0} h theorem Nonempty.eq_one [Subsingleton α] [One α] {s : Set α} (h : s.Nonempty) : s = {1} := eq_of_nonempty_of_subsingleton' {1} h /-! ### Disjointness -/ protected theorem disjoint_iff : Disjoint s t ↔ s ∩ t ⊆ ∅ := disjoint_iff_inf_le theorem disjoint_iff_inter_eq_empty : Disjoint s t ↔ s ∩ t = ∅ := disjoint_iff theorem _root_.Disjoint.inter_eq : Disjoint s t → s ∩ t = ∅ := Disjoint.eq_bot theorem disjoint_left : Disjoint s t ↔ ∀ ⦃a⦄, a ∈ s → a ∉ t := disjoint_iff_inf_le.trans <| forall_congr' fun _ => not_and theorem disjoint_right : Disjoint s t ↔ ∀ ⦃a⦄, a ∈ t → a ∉ s := by rw [disjoint_comm, disjoint_left] lemma not_disjoint_iff : ¬Disjoint s t ↔ ∃ x, x ∈ s ∧ x ∈ t := Set.disjoint_iff.not.trans <| not_forall.trans <| exists_congr fun _ ↦ not_not lemma not_disjoint_iff_nonempty_inter : ¬ Disjoint s t ↔ (s ∩ t).Nonempty := not_disjoint_iff alias ⟨_, Nonempty.not_disjoint⟩ := not_disjoint_iff_nonempty_inter lemma disjoint_or_nonempty_inter (s t : Set α) : Disjoint s t ∨ (s ∩ t).Nonempty := (em _).imp_right not_disjoint_iff_nonempty_inter.1 lemma disjoint_iff_forall_ne : Disjoint s t ↔ ∀ ⦃a⦄, a ∈ s → ∀ ⦃b⦄, b ∈ t → a ≠ b := by simp only [Ne, disjoint_left, @imp_not_comm _ (_ = _), forall_eq'] alias ⟨_root_.Disjoint.ne_of_mem, _⟩ := disjoint_iff_forall_ne lemma disjoint_of_subset_left (h : s ⊆ u) (d : Disjoint u t) : Disjoint s t := d.mono_left h lemma disjoint_of_subset_right (h : t ⊆ u) (d : Disjoint s u) : Disjoint s t := d.mono_right h lemma disjoint_of_subset (hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) (h : Disjoint s₂ t₂) : Disjoint s₁ t₁ := h.mono hs ht @[simp] lemma disjoint_union_left : Disjoint (s ∪ t) u ↔ Disjoint s u ∧ Disjoint t u := disjoint_sup_left @[simp] lemma disjoint_union_right : Disjoint s (t ∪ u) ↔ Disjoint s t ∧ Disjoint s u := disjoint_sup_right @[simp] lemma disjoint_empty (s : Set α) : Disjoint s ∅ := disjoint_bot_right @[simp] lemma empty_disjoint (s : Set α) : Disjoint ∅ s := disjoint_bot_left @[simp] lemma univ_disjoint : Disjoint univ s ↔ s = ∅ := top_disjoint @[simp] lemma disjoint_univ : Disjoint s univ ↔ s = ∅ := disjoint_top lemma disjoint_sdiff_left : Disjoint (t \ s) s := disjoint_sdiff_self_left lemma disjoint_sdiff_right : Disjoint s (t \ s) := disjoint_sdiff_self_right -- TODO: prove this in terms of a lattice lemma theorem disjoint_sdiff_inter : Disjoint (s \ t) (s ∩ t) := disjoint_of_subset_right inter_subset_right disjoint_sdiff_left theorem diff_union_diff_cancel (hts : t ⊆ s) (hut : u ⊆ t) : s \ t ∪ t \ u = s \ u := sdiff_sup_sdiff_cancel hts hut theorem diff_diff_eq_sdiff_union (h : u ⊆ s) : s \ (t \ u) = s \ t ∪ u := sdiff_sdiff_eq_sdiff_sup h @[simp default+1] lemma disjoint_singleton_left : Disjoint {a} s ↔ a ∉ s := by simp [Set.disjoint_iff, subset_def] @[simp] lemma disjoint_singleton_right : Disjoint s {a} ↔ a ∉ s := disjoint_comm.trans disjoint_singleton_left lemma disjoint_singleton : Disjoint ({a} : Set α) {b} ↔ a ≠ b := by simp lemma subset_diff : s ⊆ t \ u ↔ s ⊆ t ∧ Disjoint s u := le_iff_subset.symm.trans le_sdiff lemma ssubset_iff_sdiff_singleton : s ⊂ t ↔ ∃ a ∈ t, s ⊆ t \ {a} := by simp [ssubset_iff_insert, subset_diff, insert_subset_iff]; aesop theorem inter_diff_distrib_left (s t u : Set α) : s ∩ (t \ u) = (s ∩ t) \ (s ∩ u) := inf_sdiff_distrib_left _ _ _ theorem inter_diff_distrib_right (s t u : Set α) : s \ t ∩ u = (s ∩ u) \ (t ∩ u) := inf_sdiff_distrib_right _ _ _ /-! ### Lemmas about complement -/ theorem compl_def (s : Set α) : sᶜ = { x | x ∉ s } := rfl theorem mem_compl {s : Set α} {x : α} (h : x ∉ s) : x ∈ sᶜ := h theorem compl_setOf {α} (p : α → Prop) : { a | p a }ᶜ = { a | ¬p a } := rfl theorem not_mem_of_mem_compl {s : Set α} {x : α} (h : x ∈ sᶜ) : x ∉ s := h theorem not_mem_compl_iff {x : α} : x ∉ sᶜ ↔ x ∈ s := not_not @[simp] theorem inter_compl_self (s : Set α) : s ∩ sᶜ = ∅ := inf_compl_eq_bot @[simp] theorem compl_inter_self (s : Set α) : sᶜ ∩ s = ∅ := compl_inf_eq_bot @[simp] theorem compl_empty : (∅ : Set α)ᶜ = univ := compl_bot @[simp] theorem compl_union (s t : Set α) : (s ∪ t)ᶜ = sᶜ ∩ tᶜ := compl_sup theorem compl_inter (s t : Set α) : (s ∩ t)ᶜ = sᶜ ∪ tᶜ := compl_inf @[simp] theorem compl_univ : (univ : Set α)ᶜ = ∅ := compl_top @[simp] theorem compl_empty_iff {s : Set α} : sᶜ = ∅ ↔ s = univ := compl_eq_bot @[simp] theorem compl_univ_iff {s : Set α} : sᶜ = univ ↔ s = ∅ := compl_eq_top theorem compl_ne_univ : sᶜ ≠ univ ↔ s.Nonempty := compl_univ_iff.not.trans nonempty_iff_ne_empty.symm theorem nonempty_compl : sᶜ.Nonempty ↔ s ≠ univ := (ne_univ_iff_exists_not_mem s).symm @[simp] lemma nonempty_compl_of_nontrivial [Nontrivial α] (x : α) : Set.Nonempty {x}ᶜ := by obtain ⟨y, hy⟩ := exists_ne x exact ⟨y, by simp [hy]⟩ theorem mem_compl_singleton_iff {a x : α} : x ∈ ({a} : Set α)ᶜ ↔ x ≠ a := Iff.rfl theorem compl_singleton_eq (a : α) : ({a} : Set α)ᶜ = { x | x ≠ a } := rfl @[simp] theorem compl_ne_eq_singleton (a : α) : ({ x | x ≠ a } : Set α)ᶜ = {a} := compl_compl _ theorem union_eq_compl_compl_inter_compl (s t : Set α) : s ∪ t = (sᶜ ∩ tᶜ)ᶜ := ext fun _ => or_iff_not_and_not theorem inter_eq_compl_compl_union_compl (s t : Set α) : s ∩ t = (sᶜ ∪ tᶜ)ᶜ := ext fun _ => and_iff_not_or_not @[simp] theorem union_compl_self (s : Set α) : s ∪ sᶜ = univ := eq_univ_iff_forall.2 fun _ => em _ @[simp] theorem compl_union_self (s : Set α) : sᶜ ∪ s = univ := by rw [union_comm, union_compl_self] theorem compl_subset_comm : sᶜ ⊆ t ↔ tᶜ ⊆ s := @compl_le_iff_compl_le _ s _ _ theorem subset_compl_comm : s ⊆ tᶜ ↔ t ⊆ sᶜ := @le_compl_iff_le_compl _ _ _ t @[simp] theorem compl_subset_compl : sᶜ ⊆ tᶜ ↔ t ⊆ s := @compl_le_compl_iff_le (Set α) _ _ _ @[gcongr] theorem compl_subset_compl_of_subset (h : t ⊆ s) : sᶜ ⊆ tᶜ := compl_subset_compl.2 h theorem subset_compl_iff_disjoint_left : s ⊆ tᶜ ↔ Disjoint t s := @le_compl_iff_disjoint_left (Set α) _ _ _ theorem subset_compl_iff_disjoint_right : s ⊆ tᶜ ↔ Disjoint s t := @le_compl_iff_disjoint_right (Set α) _ _ _ theorem disjoint_compl_left_iff_subset : Disjoint sᶜ t ↔ t ⊆ s := disjoint_compl_left_iff theorem disjoint_compl_right_iff_subset : Disjoint s tᶜ ↔ s ⊆ t := disjoint_compl_right_iff alias ⟨_, _root_.Disjoint.subset_compl_right⟩ := subset_compl_iff_disjoint_right alias ⟨_, _root_.Disjoint.subset_compl_left⟩ := subset_compl_iff_disjoint_left alias ⟨_, _root_.HasSubset.Subset.disjoint_compl_left⟩ := disjoint_compl_left_iff_subset alias ⟨_, _root_.HasSubset.Subset.disjoint_compl_right⟩ := disjoint_compl_right_iff_subset theorem subset_union_compl_iff_inter_subset {s t u : Set α} : s ⊆ t ∪ uᶜ ↔ s ∩ u ⊆ t := (@isCompl_compl _ u _).le_sup_right_iff_inf_left_le theorem compl_subset_iff_union {s t : Set α} : sᶜ ⊆ t ↔ s ∪ t = univ := Iff.symm <| eq_univ_iff_forall.trans <| forall_congr' fun _ => or_iff_not_imp_left @[simp] theorem subset_compl_singleton_iff {a : α} {s : Set α} : s ⊆ {a}ᶜ ↔ a ∉ s := subset_compl_comm.trans singleton_subset_iff theorem inter_subset (a b c : Set α) : a ∩ b ⊆ c ↔ a ⊆ bᶜ ∪ c := forall_congr' fun _ => and_imp.trans <| imp_congr_right fun _ => imp_iff_not_or theorem inter_compl_nonempty_iff {s t : Set α} : (s ∩ tᶜ).Nonempty ↔ ¬s ⊆ t := (not_subset.trans <| exists_congr fun x => by simp [mem_compl]).symm /-! ### Lemmas about set difference -/ theorem not_mem_diff_of_mem {s t : Set α} {x : α} (hx : x ∈ t) : x ∉ s \ t := fun h => h.2 hx theorem mem_of_mem_diff {s t : Set α} {x : α} (h : x ∈ s \ t) : x ∈ s := h.left theorem not_mem_of_mem_diff {s t : Set α} {x : α} (h : x ∈ s \ t) : x ∉ t := h.right theorem diff_eq_compl_inter {s t : Set α} : s \ t = tᶜ ∩ s := by rw [diff_eq, inter_comm] theorem nonempty_diff {s t : Set α} : (s \ t).Nonempty ↔ ¬s ⊆ t := inter_compl_nonempty_iff theorem diff_subset {s t : Set α} : s \ t ⊆ s := show s \ t ≤ s from sdiff_le theorem diff_subset_compl (s t : Set α) : s \ t ⊆ tᶜ := diff_eq_compl_inter ▸ inter_subset_left theorem union_diff_cancel' {s t u : Set α} (h₁ : s ⊆ t) (h₂ : t ⊆ u) : t ∪ u \ s = u := sup_sdiff_cancel' h₁ h₂ theorem union_diff_cancel {s t : Set α} (h : s ⊆ t) : s ∪ t \ s = t := sup_sdiff_cancel_right h theorem union_diff_cancel_left {s t : Set α} (h : s ∩ t ⊆ ∅) : (s ∪ t) \ s = t := Disjoint.sup_sdiff_cancel_left <| disjoint_iff_inf_le.2 h theorem union_diff_cancel_right {s t : Set α} (h : s ∩ t ⊆ ∅) : (s ∪ t) \ t = s := Disjoint.sup_sdiff_cancel_right <| disjoint_iff_inf_le.2 h @[simp] theorem union_diff_left {s t : Set α} : (s ∪ t) \ s = t \ s := sup_sdiff_left_self @[simp] theorem union_diff_right {s t : Set α} : (s ∪ t) \ t = s \ t := sup_sdiff_right_self theorem union_diff_distrib {s t u : Set α} : (s ∪ t) \ u = s \ u ∪ t \ u := sup_sdiff theorem inter_diff_assoc (a b c : Set α) : (a ∩ b) \ c = a ∩ (b \ c) := inf_sdiff_assoc @[simp] theorem inter_diff_self (a b : Set α) : a ∩ (b \ a) = ∅ := inf_sdiff_self_right @[simp] theorem inter_union_diff (s t : Set α) : s ∩ t ∪ s \ t = s := sup_inf_sdiff s t @[simp] theorem diff_union_inter (s t : Set α) : s \ t ∪ s ∩ t = s := by rw [union_comm] exact sup_inf_sdiff _ _ @[simp] theorem inter_union_compl (s t : Set α) : s ∩ t ∪ s ∩ tᶜ = s := inter_union_diff _ _ @[gcongr] theorem diff_subset_diff {s₁ s₂ t₁ t₂ : Set α} : s₁ ⊆ s₂ → t₂ ⊆ t₁ → s₁ \ t₁ ⊆ s₂ \ t₂ := show s₁ ≤ s₂ → t₂ ≤ t₁ → s₁ \ t₁ ≤ s₂ \ t₂ from sdiff_le_sdiff @[gcongr] theorem diff_subset_diff_left {s₁ s₂ t : Set α} (h : s₁ ⊆ s₂) : s₁ \ t ⊆ s₂ \ t := sdiff_le_sdiff_right ‹s₁ ≤ s₂› @[gcongr] theorem diff_subset_diff_right {s t u : Set α} (h : t ⊆ u) : s \ u ⊆ s \ t := sdiff_le_sdiff_left ‹t ≤ u› theorem compl_eq_univ_diff (s : Set α) : sᶜ = univ \ s := top_sdiff.symm @[simp] theorem empty_diff (s : Set α) : (∅ \ s : Set α) = ∅ := bot_sdiff theorem diff_eq_empty {s t : Set α} : s \ t = ∅ ↔ s ⊆ t := sdiff_eq_bot_iff @[simp] theorem diff_empty {s : Set α} : s \ ∅ = s := sdiff_bot @[simp] theorem diff_univ (s : Set α) : s \ univ = ∅ := diff_eq_empty.2 (subset_univ s) theorem diff_diff {u : Set α} : (s \ t) \ u = s \ (t ∪ u) := sdiff_sdiff_left -- the following statement contains parentheses to help the reader theorem diff_diff_comm {s t u : Set α} : (s \ t) \ u = (s \ u) \ t := sdiff_sdiff_comm theorem diff_subset_iff {s t u : Set α} : s \ t ⊆ u ↔ s ⊆ t ∪ u := show s \ t ≤ u ↔ s ≤ t ∪ u from sdiff_le_iff theorem subset_diff_union (s t : Set α) : s ⊆ s \ t ∪ t := show s ≤ s \ t ∪ t from le_sdiff_sup theorem diff_union_of_subset {s t : Set α} (h : t ⊆ s) : s \ t ∪ t = s := Subset.antisymm (union_subset diff_subset h) (subset_diff_union _ _) @[simp] theorem diff_singleton_subset_iff {x : α} {s t : Set α} : s \ {x} ⊆ t ↔ s ⊆ insert x t := by rw [← union_singleton, union_comm] apply diff_subset_iff theorem subset_diff_singleton {x : α} {s t : Set α} (h : s ⊆ t) (hx : x ∉ s) : s ⊆ t \ {x} := subset_inter h <| subset_compl_comm.1 <| singleton_subset_iff.2 hx theorem subset_insert_diff_singleton (x : α) (s : Set α) : s ⊆ insert x (s \ {x}) := by rw [← diff_singleton_subset_iff] theorem diff_subset_comm {s t u : Set α} : s \ t ⊆ u ↔ s \ u ⊆ t := show s \ t ≤ u ↔ s \ u ≤ t from sdiff_le_comm theorem diff_inter {s t u : Set α} : s \ (t ∩ u) = s \ t ∪ s \ u := sdiff_inf theorem diff_inter_diff {s t u : Set α} : s \ t ∩ (s \ u) = s \ (t ∪ u) := sdiff_sup.symm theorem diff_compl : s \ tᶜ = s ∩ t := sdiff_compl theorem diff_diff_right {s t u : Set α} : s \ (t \ u) = s \ t ∪ s ∩ u := sdiff_sdiff_right' @[simp] theorem insert_diff_of_mem (s) (h : a ∈ t) : insert a s \ t = s \ t := by ext constructor <;> simp (config := { contextual := true }) [or_imp, h] theorem insert_diff_of_not_mem (s) (h : a ∉ t) : insert a s \ t = insert a (s \ t) := by classical ext x by_cases h' : x ∈ t · have : x ≠ a := by intro H rw [H] at h' exact h h' simp [h, h', this] · simp [h, h'] theorem insert_diff_self_of_not_mem {a : α} {s : Set α} (h : a ∉ s) : insert a s \ {a} = s := by ext x simp [and_iff_left_of_imp fun hx : x ∈ s => show x ≠ a from fun hxa => h <| hxa ▸ hx] @[simp] theorem insert_diff_eq_singleton {a : α} {s : Set α} (h : a ∉ s) : insert a s \ s = {a} := by ext rw [Set.mem_diff, Set.mem_insert_iff, Set.mem_singleton_iff, or_and_right, and_not_self_iff, or_false_iff, and_iff_left_iff_imp] rintro rfl exact h theorem inter_insert_of_mem (h : a ∈ s) : s ∩ insert a t = insert a (s ∩ t) := by rw [insert_inter_distrib, insert_eq_of_mem h] theorem insert_inter_of_mem (h : a ∈ t) : insert a s ∩ t = insert a (s ∩ t) := by rw [insert_inter_distrib, insert_eq_of_mem h] theorem inter_insert_of_not_mem (h : a ∉ s) : s ∩ insert a t = s ∩ t := ext fun _ => and_congr_right fun hx => or_iff_right <| ne_of_mem_of_not_mem hx h theorem insert_inter_of_not_mem (h : a ∉ t) : insert a s ∩ t = s ∩ t := ext fun _ => and_congr_left fun hx => or_iff_right <| ne_of_mem_of_not_mem hx h @[simp] theorem union_diff_self {s t : Set α} : s ∪ t \ s = s ∪ t := sup_sdiff_self _ _ @[simp] theorem diff_union_self {s t : Set α} : s \ t ∪ t = s ∪ t := sdiff_sup_self _ _ @[simp] theorem diff_inter_self {a b : Set α} : b \ a ∩ a = ∅ := inf_sdiff_self_left @[simp] theorem diff_inter_self_eq_diff {s t : Set α} : s \ (t ∩ s) = s \ t := sdiff_inf_self_right _ _ @[simp] theorem diff_self_inter {s t : Set α} : s \ (s ∩ t) = s \ t := sdiff_inf_self_left _ _ @[simp] theorem diff_singleton_eq_self {a : α} {s : Set α} (h : a ∉ s) : s \ {a} = s := sdiff_eq_self_iff_disjoint.2 <| by simp [h] @[simp] theorem diff_singleton_sSubset {s : Set α} {a : α} : s \ {a} ⊂ s ↔ a ∈ s := sdiff_le.lt_iff_ne.trans <| sdiff_eq_left.not.trans <| by simp @[simp] theorem insert_diff_singleton {a : α} {s : Set α} : insert a (s \ {a}) = insert a s := by simp [insert_eq, union_diff_self, -union_singleton, -singleton_union] theorem insert_diff_singleton_comm (hab : a ≠ b) (s : Set α) : insert a (s \ {b}) = insert a s \ {b} := by simp_rw [← union_singleton, union_diff_distrib, diff_singleton_eq_self (mem_singleton_iff.not.2 hab.symm)] --Porting note (#10618): removed `simp` attribute because `simp` can prove it theorem diff_self {s : Set α} : s \ s = ∅ := sdiff_self theorem diff_diff_right_self (s t : Set α) : s \ (s \ t) = s ∩ t := sdiff_sdiff_right_self theorem diff_diff_cancel_left {s t : Set α} (h : s ⊆ t) : t \ (t \ s) = s := sdiff_sdiff_eq_self h theorem mem_diff_singleton {x y : α} {s : Set α} : x ∈ s \ {y} ↔ x ∈ s ∧ x ≠ y := Iff.rfl theorem mem_diff_singleton_empty {t : Set (Set α)} : s ∈ t \ {∅} ↔ s ∈ t ∧ s.Nonempty := mem_diff_singleton.trans <| and_congr_right' nonempty_iff_ne_empty.symm theorem subset_insert_iff {s t : Set α} {x : α} : s ⊆ insert x t ↔ s ⊆ t ∨ (x ∈ s ∧ s \ {x} ⊆ t) := by rw [← diff_singleton_subset_iff] by_cases hx : x ∈ s · rw [and_iff_right hx, or_iff_right_of_imp diff_subset.trans] rw [diff_singleton_eq_self hx, or_iff_left_of_imp And.right] theorem union_eq_diff_union_diff_union_inter (s t : Set α) : s ∪ t = s \ t ∪ t \ s ∪ s ∩ t := sup_eq_sdiff_sup_sdiff_sup_inf /-! ### Lemmas about pairs -/ --Porting note (#10618): removed `simp` attribute because `simp` can prove it theorem pair_eq_singleton (a : α) : ({a, a} : Set α) = {a} := union_self _ theorem pair_comm (a b : α) : ({a, b} : Set α) = {b, a} := union_comm _ _ theorem pair_eq_pair_iff {x y z w : α} : ({x, y} : Set α) = {z, w} ↔ x = z ∧ y = w ∨ x = w ∧ y = z := by simp [subset_antisymm_iff, insert_subset_iff]; aesop theorem pair_diff_left (hne : a ≠ b) : ({a, b} : Set α) \ {a} = {b} := by rw [insert_diff_of_mem _ (mem_singleton a), diff_singleton_eq_self (by simpa)] theorem pair_diff_right (hne : a ≠ b) : ({a, b} : Set α) \ {b} = {a} := by rw [pair_comm, pair_diff_left hne.symm] theorem pair_subset_iff : {a, b} ⊆ s ↔ a ∈ s ∧ b ∈ s := by rw [insert_subset_iff, singleton_subset_iff] theorem pair_subset (ha : a ∈ s) (hb : b ∈ s) : {a, b} ⊆ s := pair_subset_iff.2 ⟨ha,hb⟩ theorem subset_pair_iff : s ⊆ {a, b} ↔ ∀ x ∈ s, x = a ∨ x = b := by simp [subset_def] theorem subset_pair_iff_eq {x y : α} : s ⊆ {x, y} ↔ s = ∅ ∨ s = {x} ∨ s = {y} ∨ s = {x, y} := by refine ⟨?_, by rintro (rfl | rfl | rfl | rfl) <;> simp [pair_subset_iff]⟩ rw [subset_insert_iff, subset_singleton_iff_eq, subset_singleton_iff_eq, ← subset_empty_iff (s := s \ {x}), diff_subset_iff, union_empty, subset_singleton_iff_eq] have h : x ∈ s → {y} = s \ {x} → s = {x,y} := fun h₁ h₂ ↦ by simp [h₁, h₂] tauto theorem Nonempty.subset_pair_iff_eq (hs : s.Nonempty) : s ⊆ {a, b} ↔ s = {a} ∨ s = {b} ∨ s = {a, b} := by rw [Set.subset_pair_iff_eq, or_iff_right]; exact hs.ne_empty /-! ### Symmetric difference -/ section open scoped symmDiff theorem mem_symmDiff : a ∈ s ∆ t ↔ a ∈ s ∧ a ∉ t ∨ a ∈ t ∧ a ∉ s := Iff.rfl protected theorem symmDiff_def (s t : Set α) : s ∆ t = s \ t ∪ t \ s := rfl theorem symmDiff_subset_union : s ∆ t ⊆ s ∪ t := @symmDiff_le_sup (Set α) _ _ _ @[simp] theorem symmDiff_eq_empty : s ∆ t = ∅ ↔ s = t := symmDiff_eq_bot @[simp] theorem symmDiff_nonempty : (s ∆ t).Nonempty ↔ s ≠ t := nonempty_iff_ne_empty.trans symmDiff_eq_empty.not theorem inter_symmDiff_distrib_left (s t u : Set α) : s ∩ t ∆ u = (s ∩ t) ∆ (s ∩ u) := inf_symmDiff_distrib_left _ _ _ theorem inter_symmDiff_distrib_right (s t u : Set α) : s ∆ t ∩ u = (s ∩ u) ∆ (t ∩ u) := inf_symmDiff_distrib_right _ _ _ theorem subset_symmDiff_union_symmDiff_left (h : Disjoint s t) : u ⊆ s ∆ u ∪ t ∆ u := h.le_symmDiff_sup_symmDiff_left theorem subset_symmDiff_union_symmDiff_right (h : Disjoint t u) : s ⊆ s ∆ t ∪ s ∆ u := h.le_symmDiff_sup_symmDiff_right end /-! ### Powerset -/ theorem mem_powerset {x s : Set α} (h : x ⊆ s) : x ∈ 𝒫 s := @h theorem subset_of_mem_powerset {x s : Set α} (h : x ∈ 𝒫 s) : x ⊆ s := @h @[simp] theorem mem_powerset_iff (x s : Set α) : x ∈ 𝒫 s ↔ x ⊆ s := Iff.rfl theorem powerset_inter (s t : Set α) : 𝒫(s ∩ t) = 𝒫 s ∩ 𝒫 t := ext fun _ => subset_inter_iff @[simp] theorem powerset_mono : 𝒫 s ⊆ 𝒫 t ↔ s ⊆ t := ⟨fun h => @h _ (fun _ h => h), fun h _ hu _ ha => h (hu ha)⟩ theorem monotone_powerset : Monotone (powerset : Set α → Set (Set α)) := fun _ _ => powerset_mono.2 @[simp] theorem powerset_nonempty : (𝒫 s).Nonempty := ⟨∅, fun _ h => empty_subset s h⟩ @[simp] theorem powerset_empty : 𝒫(∅ : Set α) = {∅} := ext fun _ => subset_empty_iff @[simp] theorem powerset_univ : 𝒫(univ : Set α) = univ := eq_univ_of_forall subset_univ /-- The powerset of a singleton contains only `∅` and the singleton itself. -/ theorem powerset_singleton (x : α) : 𝒫({x} : Set α) = {∅, {x}} := by ext y rw [mem_powerset_iff, subset_singleton_iff_eq, mem_insert_iff, mem_singleton_iff] /-! ### Sets defined as an if-then-else -/ theorem mem_dite (p : Prop) [Decidable p] (s : p → Set α) (t : ¬ p → Set α) (x : α) : (x ∈ if h : p then s h else t h) ↔ (∀ h : p, x ∈ s h) ∧ ∀ h : ¬p, x ∈ t h := by split_ifs with hp · exact ⟨fun hx => ⟨fun _ => hx, fun hnp => (hnp hp).elim⟩, fun hx => hx.1 hp⟩ · exact ⟨fun hx => ⟨fun h => (hp h).elim, fun _ => hx⟩, fun hx => hx.2 hp⟩ theorem mem_dite_univ_right (p : Prop) [Decidable p] (t : p → Set α) (x : α) : (x ∈ if h : p then t h else univ) ↔ ∀ h : p, x ∈ t h := by split_ifs <;> simp_all @[simp] theorem mem_ite_univ_right (p : Prop) [Decidable p] (t : Set α) (x : α) : x ∈ ite p t Set.univ ↔ p → x ∈ t := mem_dite_univ_right p (fun _ => t) x theorem mem_dite_univ_left (p : Prop) [Decidable p] (t : ¬p → Set α) (x : α) : (x ∈ if h : p then univ else t h) ↔ ∀ h : ¬p, x ∈ t h := by split_ifs <;> simp_all @[simp] theorem mem_ite_univ_left (p : Prop) [Decidable p] (t : Set α) (x : α) : x ∈ ite p Set.univ t ↔ ¬p → x ∈ t := mem_dite_univ_left p (fun _ => t) x theorem mem_dite_empty_right (p : Prop) [Decidable p] (t : p → Set α) (x : α) : (x ∈ if h : p then t h else ∅) ↔ ∃ h : p, x ∈ t h := by simp only [mem_dite, mem_empty_iff_false, imp_false, not_not] exact ⟨fun h => ⟨h.2, h.1 h.2⟩, fun ⟨h₁, h₂⟩ => ⟨fun _ => h₂, h₁⟩⟩ @[simp] theorem mem_ite_empty_right (p : Prop) [Decidable p] (t : Set α) (x : α) : x ∈ ite p t ∅ ↔ p ∧ x ∈ t := (mem_dite_empty_right p (fun _ => t) x).trans (by simp) theorem mem_dite_empty_left (p : Prop) [Decidable p] (t : ¬p → Set α) (x : α) : (x ∈ if h : p then ∅ else t h) ↔ ∃ h : ¬p, x ∈ t h := by simp only [mem_dite, mem_empty_iff_false, imp_false] exact ⟨fun h => ⟨h.1, h.2 h.1⟩, fun ⟨h₁, h₂⟩ => ⟨fun h => h₁ h, fun _ => h₂⟩⟩ @[simp] theorem mem_ite_empty_left (p : Prop) [Decidable p] (t : Set α) (x : α) : x ∈ ite p ∅ t ↔ ¬p ∧ x ∈ t := (mem_dite_empty_left p (fun _ => t) x).trans (by simp) /-! ### If-then-else for sets -/ /-- `ite` for sets: `Set.ite t s s' ∩ t = s ∩ t`, `Set.ite t s s' ∩ tᶜ = s' ∩ tᶜ`. Defined as `s ∩ t ∪ s' \ t`. -/ protected def ite (t s s' : Set α) : Set α := s ∩ t ∪ s' \ t @[simp] theorem ite_inter_self (t s s' : Set α) : t.ite s s' ∩ t = s ∩ t := by rw [Set.ite, union_inter_distrib_right, diff_inter_self, inter_assoc, inter_self, union_empty] @[simp] theorem ite_compl (t s s' : Set α) : tᶜ.ite s s' = t.ite s' s := by rw [Set.ite, Set.ite, diff_compl, union_comm, diff_eq] @[simp] theorem ite_inter_compl_self (t s s' : Set α) : t.ite s s' ∩ tᶜ = s' ∩ tᶜ := by rw [← ite_compl, ite_inter_self] @[simp] theorem ite_diff_self (t s s' : Set α) : t.ite s s' \ t = s' \ t := ite_inter_compl_self t s s' @[simp] theorem ite_same (t s : Set α) : t.ite s s = s := inter_union_diff _ _ @[simp] theorem ite_left (s t : Set α) : s.ite s t = s ∪ t := by simp [Set.ite] @[simp] theorem ite_right (s t : Set α) : s.ite t s = t ∩ s := by simp [Set.ite] @[simp] theorem ite_empty (s s' : Set α) : Set.ite ∅ s s' = s' := by simp [Set.ite] @[simp] theorem ite_univ (s s' : Set α) : Set.ite univ s s' = s := by simp [Set.ite] @[simp] theorem ite_empty_left (t s : Set α) : t.ite ∅ s = s \ t := by simp [Set.ite] @[simp] theorem ite_empty_right (t s : Set α) : t.ite s ∅ = s ∩ t := by simp [Set.ite] theorem ite_mono (t : Set α) {s₁ s₁' s₂ s₂' : Set α} (h : s₁ ⊆ s₂) (h' : s₁' ⊆ s₂') : t.ite s₁ s₁' ⊆ t.ite s₂ s₂' := union_subset_union (inter_subset_inter_left _ h) (inter_subset_inter_left _ h') theorem ite_subset_union (t s s' : Set α) : t.ite s s' ⊆ s ∪ s' := union_subset_union inter_subset_left diff_subset theorem inter_subset_ite (t s s' : Set α) : s ∩ s' ⊆ t.ite s s' := ite_same t (s ∩ s') ▸ ite_mono _ inter_subset_left inter_subset_right theorem ite_inter_inter (t s₁ s₂ s₁' s₂' : Set α) : t.ite (s₁ ∩ s₂) (s₁' ∩ s₂') = t.ite s₁ s₁' ∩ t.ite s₂ s₂' := by ext x simp only [Set.ite, Set.mem_inter_iff, Set.mem_diff, Set.mem_union] tauto theorem ite_inter (t s₁ s₂ s : Set α) : t.ite (s₁ ∩ s) (s₂ ∩ s) = t.ite s₁ s₂ ∩ s := by rw [ite_inter_inter, ite_same] theorem ite_inter_of_inter_eq (t : Set α) {s₁ s₂ s : Set α} (h : s₁ ∩ s = s₂ ∩ s) : t.ite s₁ s₂ ∩ s = s₁ ∩ s := by rw [← ite_inter, ← h, ite_same] theorem subset_ite {t s s' u : Set α} : u ⊆ t.ite s s' ↔ u ∩ t ⊆ s ∧ u \ t ⊆ s' := by simp only [subset_def, ← forall_and] refine forall_congr' fun x => ?_ by_cases hx : x ∈ t <;> simp [*, Set.ite] theorem ite_eq_of_subset_left (t : Set α) {s₁ s₂ : Set α} (h : s₁ ⊆ s₂) : t.ite s₁ s₂ = s₁ ∪ (s₂ \ t) := by ext x by_cases hx : x ∈ t <;> simp [*, Set.ite, or_iff_right_of_imp (@h x)] theorem ite_eq_of_subset_right (t : Set α) {s₁ s₂ : Set α} (h : s₂ ⊆ s₁) : t.ite s₁ s₂ = (s₁ ∩ t) ∪ s₂ := by ext x by_cases hx : x ∈ t <;> simp [*, Set.ite, or_iff_left_of_imp (@h x)] section Preorder variable [Preorder α] [Preorder β] {f : α → β} -- Porting note: -- If we decide we want `Elem` to semireducible rather than reducible, we will need: -- instance : Preorder (↑s) := Subtype.instPreorderSubtype _ -- here, along with appropriate lemmas. theorem monotoneOn_iff_monotone : MonotoneOn f s ↔ Monotone fun a : s => f a := by simp [Monotone, MonotoneOn] theorem antitoneOn_iff_antitone : AntitoneOn f s ↔ Antitone fun a : s => f a := by simp [Antitone, AntitoneOn] theorem strictMonoOn_iff_strictMono : StrictMonoOn f s ↔ StrictMono fun a : s => f a := by simp [StrictMono, StrictMonoOn] theorem strictAntiOn_iff_strictAnti : StrictAntiOn f s ↔ StrictAnti fun a : s => f a := by simp [StrictAnti, StrictAntiOn] end Preorder section LinearOrder variable [LinearOrder α] [LinearOrder β] {f : α → β} /-- A function between linear orders which is neither monotone nor antitone makes a dent upright or downright. -/ theorem not_monotoneOn_not_antitoneOn_iff_exists_le_le : ¬MonotoneOn f s ∧ ¬AntitoneOn f s ↔ ∃ᵉ (a ∈ s) (b ∈ s) (c ∈ s), a ≤ b ∧ b ≤ c ∧ (f a < f b ∧ f c < f b ∨ f b < f a ∧ f b < f c) := by simp [monotoneOn_iff_monotone, antitoneOn_iff_antitone, and_assoc, exists_and_left, not_monotone_not_antitone_iff_exists_le_le, @and_left_comm (_ ∈ s)] /-- A function between linear orders which is neither monotone nor antitone makes a dent upright or downright. -/ theorem not_monotoneOn_not_antitoneOn_iff_exists_lt_lt : ¬MonotoneOn f s ∧ ¬AntitoneOn f s ↔ ∃ᵉ (a ∈ s) (b ∈ s) (c ∈ s), a < b ∧ b < c ∧ (f a < f b ∧ f c < f b ∨ f b < f a ∧ f b < f c) := by simp [monotoneOn_iff_monotone, antitoneOn_iff_antitone, and_assoc, exists_and_left, not_monotone_not_antitone_iff_exists_lt_lt, @and_left_comm (_ ∈ s)] end LinearOrder end Set open Set namespace Function variable {ι : Sort*} {α : Type*} {β : Type*} {f : α → β} theorem Injective.nonempty_apply_iff {f : Set α → Set β} (hf : Injective f) (h2 : f ∅ = ∅) {s : Set α} : (f s).Nonempty ↔ s.Nonempty := by rw [nonempty_iff_ne_empty, ← h2, nonempty_iff_ne_empty, hf.ne_iff] end Function open Function namespace Set /-! ### Lemmas about `inclusion`, the injection of subtypes induced by `⊆` -/ section Inclusion variable {α : Type*} {s t u : Set α} /-- `inclusion` is the "identity" function between two subsets `s` and `t`, where `s ⊆ t` -/ def inclusion (h : s ⊆ t) : s → t := fun x : s => (⟨x, h x.2⟩ : t) @[simp] theorem inclusion_self (x : s) : inclusion Subset.rfl x = x := by cases x rfl theorem inclusion_eq_id (h : s ⊆ s) : inclusion h = id := funext inclusion_self @[simp] theorem inclusion_mk {h : s ⊆ t} (a : α) (ha : a ∈ s) : inclusion h ⟨a, ha⟩ = ⟨a, h ha⟩ := rfl theorem inclusion_right (h : s ⊆ t) (x : t) (m : (x : α) ∈ s) : inclusion h ⟨x, m⟩ = x := by cases x rfl @[simp] theorem inclusion_inclusion (hst : s ⊆ t) (htu : t ⊆ u) (x : s) : inclusion htu (inclusion hst x) = inclusion (hst.trans htu) x := by cases x rfl @[simp] theorem inclusion_comp_inclusion {α} {s t u : Set α} (hst : s ⊆ t) (htu : t ⊆ u) : inclusion htu ∘ inclusion hst = inclusion (hst.trans htu) := funext (inclusion_inclusion hst htu) @[simp] theorem coe_inclusion (h : s ⊆ t) (x : s) : (inclusion h x : α) = (x : α) := rfl theorem val_comp_inclusion (h : s ⊆ t) : Subtype.val ∘ inclusion h = Subtype.val := rfl theorem inclusion_injective (h : s ⊆ t) : Injective (inclusion h) | ⟨_, _⟩, ⟨_, _⟩ => Subtype.ext_iff_val.2 ∘ Subtype.ext_iff_val.1 @[simp] theorem inclusion_inj (h : s ⊆ t) {x y : s} : inclusion h x = inclusion h y ↔ x = y := (inclusion_injective h).eq_iff theorem eq_of_inclusion_surjective {s t : Set α} {h : s ⊆ t} (h_surj : Function.Surjective (inclusion h)) : s = t := by refine Set.Subset.antisymm h (fun x hx => ?_) obtain ⟨y, hy⟩ := h_surj ⟨x, hx⟩ exact mem_of_eq_of_mem (congr_arg Subtype.val hy).symm y.prop @[simp] theorem inclusion_le_inclusion [Preorder α] {s t : Set α} (h : s ⊆ t) {x y : s} : inclusion h x ≤ inclusion h y ↔ x ≤ y := Iff.rfl @[simp] theorem inclusion_lt_inclusion [Preorder α] {s t : Set α} (h : s ⊆ t) {x y : s} : inclusion h x < inclusion h y ↔ x < y := Iff.rfl end Inclusion end Set namespace Subsingleton variable {α : Type*} [Subsingleton α] theorem eq_univ_of_nonempty {s : Set α} : s.Nonempty → s = univ := fun ⟨x, hx⟩ => eq_univ_of_forall fun y => Subsingleton.elim x y ▸ hx @[elab_as_elim] theorem set_cases {p : Set α → Prop} (h0 : p ∅) (h1 : p univ) (s) : p s := (s.eq_empty_or_nonempty.elim fun h => h.symm ▸ h0) fun h => (eq_univ_of_nonempty h).symm ▸ h1 theorem mem_iff_nonempty {α : Type*} [Subsingleton α] {s : Set α} {x : α} : x ∈ s ↔ s.Nonempty := ⟨fun hx => ⟨x, hx⟩, fun ⟨y, hy⟩ => Subsingleton.elim y x ▸ hy⟩ end Subsingleton /-! ### Decidability instances for sets -/ namespace Set variable {α : Type u} (s t : Set α) (a b : α) instance decidableSdiff [Decidable (a ∈ s)] [Decidable (a ∈ t)] : Decidable (a ∈ s \ t) := inferInstanceAs (Decidable (a ∈ s ∧ a ∉ t)) instance decidableInter [Decidable (a ∈ s)] [Decidable (a ∈ t)] : Decidable (a ∈ s ∩ t) := inferInstanceAs (Decidable (a ∈ s ∧ a ∈ t)) instance decidableUnion [Decidable (a ∈ s)] [Decidable (a ∈ t)] : Decidable (a ∈ s ∪ t) := inferInstanceAs (Decidable (a ∈ s ∨ a ∈ t)) instance decidableCompl [Decidable (a ∈ s)] : Decidable (a ∈ sᶜ) := inferInstanceAs (Decidable (a ∉ s)) instance decidableEmptyset : Decidable (a ∈ (∅ : Set α)) := Decidable.isFalse (by simp) instance decidableUniv : Decidable (a ∈ univ) := Decidable.isTrue (by simp) instance decidableInsert [Decidable (a = b)] [Decidable (a ∈ s)] : Decidable (a ∈ insert b s) := inferInstanceAs (Decidable (_ ∨ _)) -- Porting note: Lean 3 unfolded `{a}` before finding instances but Lean 4 needs additional help instance decidableSingleton [Decidable (a = b)] : Decidable (a ∈ ({b} : Set α)) := inferInstanceAs (Decidable (a = b)) instance decidableSetOf (p : α → Prop) [Decidable (p a)] : Decidable (a ∈ { a | p a }) := by assumption end Set /-! ### Monotone lemmas for sets -/ section Monotone variable {α β : Type*} theorem Monotone.inter [Preorder β] {f g : β → Set α} (hf : Monotone f) (hg : Monotone g) : Monotone fun x => f x ∩ g x := hf.inf hg theorem MonotoneOn.inter [Preorder β] {f g : β → Set α} {s : Set β} (hf : MonotoneOn f s) (hg : MonotoneOn g s) : MonotoneOn (fun x => f x ∩ g x) s := hf.inf hg theorem Antitone.inter [Preorder β] {f g : β → Set α} (hf : Antitone f) (hg : Antitone g) : Antitone fun x => f x ∩ g x := hf.inf hg theorem AntitoneOn.inter [Preorder β] {f g : β → Set α} {s : Set β} (hf : AntitoneOn f s) (hg : AntitoneOn g s) : AntitoneOn (fun x => f x ∩ g x) s := hf.inf hg theorem Monotone.union [Preorder β] {f g : β → Set α} (hf : Monotone f) (hg : Monotone g) : Monotone fun x => f x ∪ g x := hf.sup hg theorem MonotoneOn.union [Preorder β] {f g : β → Set α} {s : Set β} (hf : MonotoneOn f s) (hg : MonotoneOn g s) : MonotoneOn (fun x => f x ∪ g x) s := hf.sup hg theorem Antitone.union [Preorder β] {f g : β → Set α} (hf : Antitone f) (hg : Antitone g) : Antitone fun x => f x ∪ g x := hf.sup hg theorem AntitoneOn.union [Preorder β] {f g : β → Set α} {s : Set β} (hf : AntitoneOn f s) (hg : AntitoneOn g s) : AntitoneOn (fun x => f x ∪ g x) s := hf.sup hg namespace Set theorem monotone_setOf [Preorder α] {p : α → β → Prop} (hp : ∀ b, Monotone fun a => p a b) : Monotone fun a => { b | p a b } := fun _ _ h b => hp b h theorem antitone_setOf [Preorder α] {p : α → β → Prop} (hp : ∀ b, Antitone fun a => p a b) : Antitone fun a => { b | p a b } := fun _ _ h b => hp b h /-- Quantifying over a set is antitone in the set -/ theorem antitone_bforall {P : α → Prop} : Antitone fun s : Set α => ∀ x ∈ s, P x := fun _ _ hst h x hx => h x <| hst hx end Set end Monotone /-! ### Disjoint sets -/ variable {α β : Type*} {s t u : Set α} {f : α → β} namespace Disjoint theorem union_left (hs : Disjoint s u) (ht : Disjoint t u) : Disjoint (s ∪ t) u := hs.sup_left ht theorem union_right (ht : Disjoint s t) (hu : Disjoint s u) : Disjoint s (t ∪ u) := ht.sup_right hu theorem inter_left (u : Set α) (h : Disjoint s t) : Disjoint (s ∩ u) t := h.inf_left _ theorem inter_left' (u : Set α) (h : Disjoint s t) : Disjoint (u ∩ s) t := h.inf_left' _ theorem inter_right (u : Set α) (h : Disjoint s t) : Disjoint s (t ∩ u) := h.inf_right _ theorem inter_right' (u : Set α) (h : Disjoint s t) : Disjoint s (u ∩ t) := h.inf_right' _ theorem subset_left_of_subset_union (h : s ⊆ t ∪ u) (hac : Disjoint s u) : s ⊆ t := hac.left_le_of_le_sup_right h theorem subset_right_of_subset_union (h : s ⊆ t ∪ u) (hab : Disjoint s t) : s ⊆ u := hab.left_le_of_le_sup_left h end Disjoint @[simp] theorem Prop.compl_singleton (p : Prop) : ({p}ᶜ : Set Prop) = {¬p} := ext fun q ↦ by simpa [@Iff.comm q] using not_iff
Data\Set\BoolIndicator.lean
/- Copyright (c) 2022 Dagur Tómas Ásgeirsson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Dagur Tómas Ásgeirsson, Leonardo de Moura -/ import Mathlib.Data.Set.Basic /-! # Indicator function valued in bool See also `Set.indicator` and `Set.piecewise`. -/ open Bool namespace Set variable {α : Type*} (s : Set α) /-- `boolIndicator` maps `x` to `true` if `x ∈ s`, else to `false` -/ noncomputable def boolIndicator (x : α) := @ite _ (x ∈ s) (Classical.propDecidable _) true false theorem mem_iff_boolIndicator (x : α) : x ∈ s ↔ s.boolIndicator x = true := by unfold boolIndicator split_ifs with h <;> simp [h] theorem not_mem_iff_boolIndicator (x : α) : x ∉ s ↔ s.boolIndicator x = false := by unfold boolIndicator split_ifs with h <;> simp [h] theorem preimage_boolIndicator_true : s.boolIndicator ⁻¹' {true} = s := ext fun x ↦ (s.mem_iff_boolIndicator x).symm theorem preimage_boolIndicator_false : s.boolIndicator ⁻¹' {false} = sᶜ := ext fun x ↦ (s.not_mem_iff_boolIndicator x).symm open scoped Classical theorem preimage_boolIndicator_eq_union (t : Set Bool) : s.boolIndicator ⁻¹' t = (if true ∈ t then s else ∅) ∪ if false ∈ t then sᶜ else ∅ := by ext x simp only [boolIndicator, mem_preimage] split_ifs <;> simp [*] theorem preimage_boolIndicator (t : Set Bool) : s.boolIndicator ⁻¹' t = univ ∨ s.boolIndicator ⁻¹' t = s ∨ s.boolIndicator ⁻¹' t = sᶜ ∨ s.boolIndicator ⁻¹' t = ∅ := by simp only [preimage_boolIndicator_eq_union] split_ifs <;> simp [s.union_compl_self] end Set
Data\Set\Card.lean
/- Copyright (c) 2023 Peter Nelson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Peter Nelson -/ import Mathlib.SetTheory.Cardinal.Finite /-! # Noncomputable Set Cardinality We define the cardinality of set `s` as a term `Set.encard s : ℕ∞` and a term `Set.ncard s : ℕ`. The latter takes the junk value of zero if `s` is infinite. Both functions are noncomputable, and are defined in terms of `PartENat.card` (which takes a type as its argument); this file can be seen as an API for the same function in the special case where the type is a coercion of a `Set`, allowing for smoother interactions with the `Set` API. `Set.encard` never takes junk values, so is more mathematically natural than `Set.ncard`, even though it takes values in a less convenient type. It is probably the right choice in settings where one is concerned with the cardinalities of sets that may or may not be infinite. `Set.ncard` has a nicer codomain, but when using it, `Set.Finite` hypotheses are normally needed to make sure its values are meaningful. More generally, `Set.ncard` is intended to be used over the obvious alternative `Finset.card` when finiteness is 'propositional' rather than 'structural'. When working with sets that are finite by virtue of their definition, then `Finset.card` probably makes more sense. One setting where `Set.ncard` works nicely is in a type `α` with `[Finite α]`, where every set is automatically finite. In this setting, we use default arguments and a simple tactic so that finiteness goals are discharged automatically in `Set.ncard` theorems. ## Main Definitions * `Set.encard s` is the cardinality of the set `s` as an extended natural number, with value `⊤` if `s` is infinite. * `Set.ncard s` is the cardinality of the set `s` as a natural number, provided `s` is Finite. If `s` is Infinite, then `Set.ncard s = 0`. * `toFinite_tac` is a tactic that tries to synthesize a `Set.Finite s` argument with `Set.toFinite`. This will work for `s : Set α` where there is a `Finite α` instance. ## Implementation Notes The theorems in this file are very similar to those in `Data.Finset.Card`, but with `Set` operations instead of `Finset`. We first prove all the theorems for `Set.encard`, and then derive most of the `Set.ncard` results as a consequence. Things are done this way to avoid reliance on the `Finset` API for theorems about infinite sets, and to allow for a refactor that removes or modifies `Set.ncard` in the future. Nearly all the theorems for `Set.ncard` require finiteness of one or more of their arguments. We provide this assumption with a default argument of the form `(hs : s.Finite := by toFinite_tac)`, where `toFinite_tac` will find an `s.Finite` term in the cases where `s` is a set in a `Finite` type. Often, where there are two set arguments `s` and `t`, the finiteness of one follows from the other in the context of the theorem, in which case we only include the ones that are needed, and derive the other inside the proof. A few of the theorems, such as `ncard_union_le` do not require finiteness arguments; they are true by coincidence due to junk values. -/ namespace Set variable {α β : Type*} {s t : Set α} /-- The cardinality of a set as a term in `ℕ∞` -/ noncomputable def encard (s : Set α) : ℕ∞ := PartENat.withTopEquiv (PartENat.card s) @[simp] theorem encard_univ_coe (s : Set α) : encard (univ : Set s) = encard s := by rw [encard, encard, PartENat.card_congr (Equiv.Set.univ ↑s)] theorem encard_univ (α : Type*) : encard (univ : Set α) = PartENat.withTopEquiv (PartENat.card α) := by rw [encard, PartENat.card_congr (Equiv.Set.univ α)] theorem Finite.encard_eq_coe_toFinset_card (h : s.Finite) : s.encard = h.toFinset.card := by have := h.fintype rw [encard, PartENat.card_eq_coe_fintype_card, PartENat.withTopEquiv_natCast, toFinite_toFinset, toFinset_card] theorem encard_eq_coe_toFinset_card (s : Set α) [Fintype s] : encard s = s.toFinset.card := by have h := toFinite s rw [h.encard_eq_coe_toFinset_card, toFinite_toFinset] @[simp, norm_cast] theorem encard_coe_eq_coe_finsetCard (s : Finset α) : encard (s : Set α) = s.card := by rw [Finite.encard_eq_coe_toFinset_card (Finset.finite_toSet s)]; simp theorem Infinite.encard_eq {s : Set α} (h : s.Infinite) : s.encard = ⊤ := by have := h.to_subtype rw [encard, ← PartENat.withTopEquiv.symm.injective.eq_iff, Equiv.symm_apply_apply, PartENat.withTopEquiv_symm_top, PartENat.card_eq_top_of_infinite] @[simp] theorem encard_eq_zero : s.encard = 0 ↔ s = ∅ := by rw [encard, ← PartENat.withTopEquiv.symm.injective.eq_iff, Equiv.symm_apply_apply, PartENat.withTopEquiv_symm_zero, PartENat.card_eq_zero_iff_empty, isEmpty_subtype, eq_empty_iff_forall_not_mem] @[simp] theorem encard_empty : (∅ : Set α).encard = 0 := by rw [encard_eq_zero] theorem nonempty_of_encard_ne_zero (h : s.encard ≠ 0) : s.Nonempty := by rwa [nonempty_iff_ne_empty, Ne, ← encard_eq_zero] theorem encard_ne_zero : s.encard ≠ 0 ↔ s.Nonempty := by rw [ne_eq, encard_eq_zero, nonempty_iff_ne_empty] @[simp] theorem encard_pos : 0 < s.encard ↔ s.Nonempty := by rw [pos_iff_ne_zero, encard_ne_zero] @[simp] theorem encard_singleton (e : α) : ({e} : Set α).encard = 1 := by rw [encard, ← PartENat.withTopEquiv.symm.injective.eq_iff, Equiv.symm_apply_apply, PartENat.card_eq_coe_fintype_card, Fintype.card_ofSubsingleton, Nat.cast_one]; rfl theorem encard_union_eq (h : Disjoint s t) : (s ∪ t).encard = s.encard + t.encard := by classical have e := (Equiv.Set.union (by rwa [subset_empty_iff, ← disjoint_iff_inter_eq_empty])).symm simp [encard, ← PartENat.card_congr e, PartENat.card_sum, PartENat.withTopEquiv] theorem encard_insert_of_not_mem {a : α} (has : a ∉ s) : (insert a s).encard = s.encard + 1 := by rw [← union_singleton, encard_union_eq (by simpa), encard_singleton] theorem Finite.encard_lt_top (h : s.Finite) : s.encard < ⊤ := by refine h.induction_on (by simp) ?_ rintro a t hat _ ht' rw [encard_insert_of_not_mem hat] exact lt_tsub_iff_right.1 ht' theorem Finite.encard_eq_coe (h : s.Finite) : s.encard = ENat.toNat s.encard := (ENat.coe_toNat h.encard_lt_top.ne).symm theorem Finite.exists_encard_eq_coe (h : s.Finite) : ∃ (n : ℕ), s.encard = n := ⟨_, h.encard_eq_coe⟩ @[simp] theorem encard_lt_top_iff : s.encard < ⊤ ↔ s.Finite := ⟨fun h ↦ by_contra fun h' ↦ h.ne (Infinite.encard_eq h'), Finite.encard_lt_top⟩ @[simp] theorem encard_eq_top_iff : s.encard = ⊤ ↔ s.Infinite := by rw [← not_iff_not, ← Ne, ← lt_top_iff_ne_top, encard_lt_top_iff, not_infinite] theorem encard_ne_top_iff : s.encard ≠ ⊤ ↔ s.Finite := by simp theorem finite_of_encard_le_coe {k : ℕ} (h : s.encard ≤ k) : s.Finite := by rw [← encard_lt_top_iff]; exact h.trans_lt (WithTop.coe_lt_top _) theorem finite_of_encard_eq_coe {k : ℕ} (h : s.encard = k) : s.Finite := finite_of_encard_le_coe h.le theorem encard_le_coe_iff {k : ℕ} : s.encard ≤ k ↔ s.Finite ∧ ∃ (n₀ : ℕ), s.encard = n₀ ∧ n₀ ≤ k := ⟨fun h ↦ ⟨finite_of_encard_le_coe h, by rwa [ENat.le_coe_iff] at h⟩, fun ⟨_,⟨n₀,hs, hle⟩⟩ ↦ by rwa [hs, Nat.cast_le]⟩ section Lattice theorem encard_le_card (h : s ⊆ t) : s.encard ≤ t.encard := by rw [← union_diff_cancel h, encard_union_eq disjoint_sdiff_right]; exact le_self_add theorem encard_mono {α : Type*} : Monotone (encard : Set α → ℕ∞) := fun _ _ ↦ encard_le_card theorem encard_diff_add_encard_of_subset (h : s ⊆ t) : (t \ s).encard + s.encard = t.encard := by rw [← encard_union_eq disjoint_sdiff_left, diff_union_self, union_eq_self_of_subset_right h] @[simp] theorem one_le_encard_iff_nonempty : 1 ≤ s.encard ↔ s.Nonempty := by rw [nonempty_iff_ne_empty, Ne, ← encard_eq_zero, ENat.one_le_iff_ne_zero] theorem encard_diff_add_encard_inter (s t : Set α) : (s \ t).encard + (s ∩ t).encard = s.encard := by rw [← encard_union_eq (disjoint_of_subset_right inter_subset_right disjoint_sdiff_left), diff_union_inter] theorem encard_union_add_encard_inter (s t : Set α) : (s ∪ t).encard + (s ∩ t).encard = s.encard + t.encard := by rw [← diff_union_self, encard_union_eq disjoint_sdiff_left, add_right_comm, encard_diff_add_encard_inter] theorem encard_eq_encard_iff_encard_diff_eq_encard_diff (h : (s ∩ t).Finite) : s.encard = t.encard ↔ (s \ t).encard = (t \ s).encard := by rw [← encard_diff_add_encard_inter s t, ← encard_diff_add_encard_inter t s, inter_comm t s, WithTop.add_right_cancel_iff h.encard_lt_top.ne] theorem encard_le_encard_iff_encard_diff_le_encard_diff (h : (s ∩ t).Finite) : s.encard ≤ t.encard ↔ (s \ t).encard ≤ (t \ s).encard := by rw [← encard_diff_add_encard_inter s t, ← encard_diff_add_encard_inter t s, inter_comm t s, WithTop.add_le_add_iff_right h.encard_lt_top.ne] theorem encard_lt_encard_iff_encard_diff_lt_encard_diff (h : (s ∩ t).Finite) : s.encard < t.encard ↔ (s \ t).encard < (t \ s).encard := by rw [← encard_diff_add_encard_inter s t, ← encard_diff_add_encard_inter t s, inter_comm t s, WithTop.add_lt_add_iff_right h.encard_lt_top.ne] theorem encard_union_le (s t : Set α) : (s ∪ t).encard ≤ s.encard + t.encard := by rw [← encard_union_add_encard_inter]; exact le_self_add theorem finite_iff_finite_of_encard_eq_encard (h : s.encard = t.encard) : s.Finite ↔ t.Finite := by rw [← encard_lt_top_iff, ← encard_lt_top_iff, h] theorem infinite_iff_infinite_of_encard_eq_encard (h : s.encard = t.encard) : s.Infinite ↔ t.Infinite := by rw [← encard_eq_top_iff, h, encard_eq_top_iff] theorem Finite.finite_of_encard_le {s : Set α} {t : Set β} (hs : s.Finite) (h : t.encard ≤ s.encard) : t.Finite := encard_lt_top_iff.1 (h.trans_lt hs.encard_lt_top) theorem Finite.eq_of_subset_of_encard_le (ht : t.Finite) (hst : s ⊆ t) (hts : t.encard ≤ s.encard) : s = t := by rw [← zero_add (a := encard s), ← encard_diff_add_encard_of_subset hst] at hts have hdiff := WithTop.le_of_add_le_add_right (ht.subset hst).encard_lt_top.ne hts rw [nonpos_iff_eq_zero, encard_eq_zero, diff_eq_empty] at hdiff exact hst.antisymm hdiff theorem Finite.eq_of_subset_of_encard_le' (hs : s.Finite) (hst : s ⊆ t) (hts : t.encard ≤ s.encard) : s = t := (hs.finite_of_encard_le hts).eq_of_subset_of_encard_le hst hts theorem Finite.encard_lt_encard (ht : t.Finite) (h : s ⊂ t) : s.encard < t.encard := (encard_mono h.subset).lt_of_ne (fun he ↦ h.ne (ht.eq_of_subset_of_encard_le h.subset he.symm.le)) theorem encard_strictMono [Finite α] : StrictMono (encard : Set α → ℕ∞) := fun _ _ h ↦ (toFinite _).encard_lt_encard h theorem encard_diff_add_encard (s t : Set α) : (s \ t).encard + t.encard = (s ∪ t).encard := by rw [← encard_union_eq disjoint_sdiff_left, diff_union_self] theorem encard_le_encard_diff_add_encard (s t : Set α) : s.encard ≤ (s \ t).encard + t.encard := (encard_mono subset_union_left).trans_eq (encard_diff_add_encard _ _).symm theorem tsub_encard_le_encard_diff (s t : Set α) : s.encard - t.encard ≤ (s \ t).encard := by rw [tsub_le_iff_left, add_comm]; apply encard_le_encard_diff_add_encard theorem encard_add_encard_compl (s : Set α) : s.encard + sᶜ.encard = (univ : Set α).encard := by rw [← encard_union_eq disjoint_compl_right, union_compl_self] end Lattice section InsertErase variable {a b : α} theorem encard_insert_le (s : Set α) (x : α) : (insert x s).encard ≤ s.encard + 1 := by rw [← union_singleton, ← encard_singleton x]; apply encard_union_le theorem encard_singleton_inter (s : Set α) (x : α) : ({x} ∩ s).encard ≤ 1 := by rw [← encard_singleton x]; exact encard_le_card inter_subset_left theorem encard_diff_singleton_add_one (h : a ∈ s) : (s \ {a}).encard + 1 = s.encard := by rw [← encard_insert_of_not_mem (fun h ↦ h.2 rfl), insert_diff_singleton, insert_eq_of_mem h] theorem encard_diff_singleton_of_mem (h : a ∈ s) : (s \ {a}).encard = s.encard - 1 := by rw [← encard_diff_singleton_add_one h, ← WithTop.add_right_cancel_iff WithTop.one_ne_top, tsub_add_cancel_of_le (self_le_add_left _ _)] theorem encard_tsub_one_le_encard_diff_singleton (s : Set α) (x : α) : s.encard - 1 ≤ (s \ {x}).encard := by rw [← encard_singleton x]; apply tsub_encard_le_encard_diff theorem encard_exchange (ha : a ∉ s) (hb : b ∈ s) : (insert a (s \ {b})).encard = s.encard := by rw [encard_insert_of_not_mem, encard_diff_singleton_add_one hb] simp_all only [not_true, mem_diff, mem_singleton_iff, false_and, not_false_eq_true] theorem encard_exchange' (ha : a ∉ s) (hb : b ∈ s) : (insert a s \ {b}).encard = s.encard := by rw [← insert_diff_singleton_comm (by rintro rfl; exact ha hb), encard_exchange ha hb] theorem encard_eq_add_one_iff {k : ℕ∞} : s.encard = k + 1 ↔ (∃ a t, ¬a ∈ t ∧ insert a t = s ∧ t.encard = k) := by refine ⟨fun h ↦ ?_, ?_⟩ · obtain ⟨a, ha⟩ := nonempty_of_encard_ne_zero (s := s) (by simp [h]) refine ⟨a, s \ {a}, fun h ↦ h.2 rfl, by rwa [insert_diff_singleton, insert_eq_of_mem], ?_⟩ rw [← WithTop.add_right_cancel_iff WithTop.one_ne_top, ← h, encard_diff_singleton_add_one ha] rintro ⟨a, t, h, rfl, rfl⟩ rw [encard_insert_of_not_mem h] /-- Every set is either empty, infinite, or can have its `encard` reduced by a removal. Intended for well-founded induction on the value of `encard`. -/ theorem eq_empty_or_encard_eq_top_or_encard_diff_singleton_lt (s : Set α) : s = ∅ ∨ s.encard = ⊤ ∨ ∃ a ∈ s, (s \ {a}).encard < s.encard := by refine s.eq_empty_or_nonempty.elim Or.inl (Or.inr ∘ fun ⟨a,ha⟩ ↦ (s.finite_or_infinite.elim (fun hfin ↦ Or.inr ⟨a, ha, ?_⟩) (Or.inl ∘ Infinite.encard_eq))) rw [← encard_diff_singleton_add_one ha]; nth_rw 1 [← add_zero (encard _)] exact WithTop.add_lt_add_left (hfin.diff _).encard_lt_top.ne zero_lt_one end InsertErase section SmallSets theorem encard_pair {x y : α} (hne : x ≠ y) : ({x, y} : Set α).encard = 2 := by rw [encard_insert_of_not_mem (by simpa), ← one_add_one_eq_two, WithTop.add_right_cancel_iff WithTop.one_ne_top, encard_singleton] theorem encard_eq_one : s.encard = 1 ↔ ∃ x, s = {x} := by refine ⟨fun h ↦ ?_, fun ⟨x, hx⟩ ↦ by rw [hx, encard_singleton]⟩ obtain ⟨x, hx⟩ := nonempty_of_encard_ne_zero (s := s) (by rw [h]; simp) exact ⟨x, ((finite_singleton x).eq_of_subset_of_encard_le' (by simpa) (by simp [h])).symm⟩ theorem encard_le_one_iff_eq : s.encard ≤ 1 ↔ s = ∅ ∨ ∃ x, s = {x} := by rw [le_iff_lt_or_eq, lt_iff_not_le, ENat.one_le_iff_ne_zero, not_not, encard_eq_zero, encard_eq_one] theorem encard_le_one_iff : s.encard ≤ 1 ↔ ∀ a b, a ∈ s → b ∈ s → a = b := by rw [encard_le_one_iff_eq, or_iff_not_imp_left, ← Ne, ← nonempty_iff_ne_empty] refine ⟨fun h a b has hbs ↦ ?_, fun h ⟨x, hx⟩ ↦ ⟨x, ((singleton_subset_iff.2 hx).antisymm' (fun y hy ↦ h _ _ hy hx))⟩⟩ obtain ⟨x, rfl⟩ := h ⟨_, has⟩ rw [(has : a = x), (hbs : b = x)] theorem one_lt_encard_iff : 1 < s.encard ↔ ∃ a b, a ∈ s ∧ b ∈ s ∧ a ≠ b := by rw [← not_iff_not, not_exists, not_lt, encard_le_one_iff]; aesop theorem exists_ne_of_one_lt_encard (h : 1 < s.encard) (a : α) : ∃ b ∈ s, b ≠ a := by by_contra! h' obtain ⟨b, b', hb, hb', hne⟩ := one_lt_encard_iff.1 h apply hne rw [h' b hb, h' b' hb'] theorem encard_eq_two : s.encard = 2 ↔ ∃ x y, x ≠ y ∧ s = {x, y} := by refine ⟨fun h ↦ ?_, fun ⟨x, y, hne, hs⟩ ↦ by rw [hs, encard_pair hne]⟩ obtain ⟨x, hx⟩ := nonempty_of_encard_ne_zero (s := s) (by rw [h]; simp) rw [← insert_eq_of_mem hx, ← insert_diff_singleton, encard_insert_of_not_mem (fun h ↦ h.2 rfl), ← one_add_one_eq_two, WithTop.add_right_cancel_iff (WithTop.one_ne_top), encard_eq_one] at h obtain ⟨y, h⟩ := h refine ⟨x, y, by rintro rfl; exact (h.symm.subset rfl).2 rfl, ?_⟩ rw [← h, insert_diff_singleton, insert_eq_of_mem hx] theorem encard_eq_three {α : Type u_1} {s : Set α} : encard s = 3 ↔ ∃ x y z, x ≠ y ∧ x ≠ z ∧ y ≠ z ∧ s = {x, y, z} := by refine ⟨fun h ↦ ?_, fun ⟨x, y, z, hxy, hyz, hxz, hs⟩ ↦ ?_⟩ · obtain ⟨x, hx⟩ := nonempty_of_encard_ne_zero (s := s) (by rw [h]; simp) rw [← insert_eq_of_mem hx, ← insert_diff_singleton, encard_insert_of_not_mem (fun h ↦ h.2 rfl), (by exact rfl : (3 : ℕ∞) = 2 + 1), WithTop.add_right_cancel_iff WithTop.one_ne_top, encard_eq_two] at h obtain ⟨y, z, hne, hs⟩ := h refine ⟨x, y, z, ?_, ?_, hne, ?_⟩ · rintro rfl; exact (hs.symm.subset (Or.inl rfl)).2 rfl · rintro rfl; exact (hs.symm.subset (Or.inr rfl)).2 rfl rw [← hs, insert_diff_singleton, insert_eq_of_mem hx] rw [hs, encard_insert_of_not_mem, encard_insert_of_not_mem, encard_singleton] <;> aesop theorem Nat.encard_range (k : ℕ) : {i | i < k}.encard = k := by convert encard_coe_eq_coe_finsetCard (Finset.range k) using 1 · rw [Finset.coe_range, Iio_def] rw [Finset.card_range] end SmallSets theorem Finite.eq_insert_of_subset_of_encard_eq_succ (hs : s.Finite) (h : s ⊆ t) (hst : t.encard = s.encard + 1) : ∃ a, t = insert a s := by rw [← encard_diff_add_encard_of_subset h, add_comm, WithTop.add_left_cancel_iff hs.encard_lt_top.ne, encard_eq_one] at hst obtain ⟨x, hx⟩ := hst; use x; rw [← diff_union_of_subset h, hx, singleton_union] theorem exists_subset_encard_eq {k : ℕ∞} (hk : k ≤ s.encard) : ∃ t, t ⊆ s ∧ t.encard = k := by revert hk refine ENat.nat_induction k (fun _ ↦ ⟨∅, empty_subset _, by simp⟩) (fun n IH hle ↦ ?_) ?_ · obtain ⟨t₀, ht₀s, ht₀⟩ := IH (le_trans (by simp) hle) simp only [Nat.cast_succ] at * have hne : t₀ ≠ s := by rintro rfl; rw [ht₀, ← Nat.cast_one, ← Nat.cast_add, Nat.cast_le] at hle; simp at hle obtain ⟨x, hx⟩ := exists_of_ssubset (ht₀s.ssubset_of_ne hne) exact ⟨insert x t₀, insert_subset hx.1 ht₀s, by rw [encard_insert_of_not_mem hx.2, ht₀]⟩ simp only [top_le_iff, encard_eq_top_iff] exact fun _ hi ↦ ⟨s, Subset.rfl, hi⟩ theorem exists_superset_subset_encard_eq {k : ℕ∞} (hst : s ⊆ t) (hsk : s.encard ≤ k) (hkt : k ≤ t.encard) : ∃ r, s ⊆ r ∧ r ⊆ t ∧ r.encard = k := by obtain (hs | hs) := eq_or_ne s.encard ⊤ · rw [hs, top_le_iff] at hsk; subst hsk; exact ⟨s, Subset.rfl, hst, hs⟩ obtain ⟨k, rfl⟩ := exists_add_of_le hsk obtain ⟨k', hk'⟩ := exists_add_of_le hkt have hk : k ≤ encard (t \ s) := by rw [← encard_diff_add_encard_of_subset hst, add_comm] at hkt exact WithTop.le_of_add_le_add_right hs hkt obtain ⟨r', hr', rfl⟩ := exists_subset_encard_eq hk refine ⟨s ∪ r', subset_union_left, union_subset hst (hr'.trans diff_subset), ?_⟩ rw [encard_union_eq (disjoint_of_subset_right hr' disjoint_sdiff_right)] section Function variable {s : Set α} {t : Set β} {f : α → β} theorem InjOn.encard_image (h : InjOn f s) : (f '' s).encard = s.encard := by rw [encard, PartENat.card_image_of_injOn h, encard] theorem encard_congr (e : s ≃ t) : s.encard = t.encard := by rw [← encard_univ_coe, ← encard_univ_coe t, encard_univ, encard_univ, PartENat.card_congr e] theorem _root_.Function.Injective.encard_image (hf : f.Injective) (s : Set α) : (f '' s).encard = s.encard := hf.injOn.encard_image theorem _root_.Function.Embedding.enccard_le (e : s ↪ t) : s.encard ≤ t.encard := by rw [← encard_univ_coe, ← e.injective.encard_image, ← Subtype.coe_injective.encard_image] exact encard_mono (by simp) theorem encard_image_le (f : α → β) (s : Set α) : (f '' s).encard ≤ s.encard := by obtain (h | h) := isEmpty_or_nonempty α · rw [s.eq_empty_of_isEmpty]; simp rw [← (f.invFunOn_injOn_image s).encard_image] apply encard_le_card exact f.invFunOn_image_image_subset s theorem Finite.injOn_of_encard_image_eq (hs : s.Finite) (h : (f '' s).encard = s.encard) : InjOn f s := by obtain (h' | hne) := isEmpty_or_nonempty α · rw [s.eq_empty_of_isEmpty]; simp rw [← (f.invFunOn_injOn_image s).encard_image] at h rw [injOn_iff_invFunOn_image_image_eq_self] exact hs.eq_of_subset_of_encard_le (f.invFunOn_image_image_subset s) h.symm.le theorem encard_preimage_of_injective_subset_range (hf : f.Injective) (ht : t ⊆ range f) : (f ⁻¹' t).encard = t.encard := by rw [← hf.encard_image, image_preimage_eq_inter_range, inter_eq_self_of_subset_left ht] theorem encard_le_encard_of_injOn (hf : MapsTo f s t) (f_inj : InjOn f s) : s.encard ≤ t.encard := by rw [← f_inj.encard_image]; apply encard_le_card; rintro _ ⟨x, hx, rfl⟩; exact hf hx theorem Finite.exists_injOn_of_encard_le [Nonempty β] {s : Set α} {t : Set β} (hs : s.Finite) (hle : s.encard ≤ t.encard) : ∃ (f : α → β), s ⊆ f ⁻¹' t ∧ InjOn f s := by classical obtain (rfl | h | ⟨a, has, -⟩) := s.eq_empty_or_encard_eq_top_or_encard_diff_singleton_lt · simp · exact (encard_ne_top_iff.mpr hs h).elim obtain ⟨b, hbt⟩ := encard_pos.1 ((encard_pos.2 ⟨_, has⟩).trans_le hle) have hle' : (s \ {a}).encard ≤ (t \ {b}).encard := by rwa [← WithTop.add_le_add_iff_right WithTop.one_ne_top, encard_diff_singleton_add_one has, encard_diff_singleton_add_one hbt] obtain ⟨f₀, hf₀s, hinj⟩ := exists_injOn_of_encard_le (hs.diff {a}) hle' simp only [preimage_diff, subset_def, mem_diff, mem_singleton_iff, mem_preimage, and_imp] at hf₀s use Function.update f₀ a b rw [← insert_eq_of_mem has, ← insert_diff_singleton, injOn_insert (fun h ↦ h.2 rfl)] simp only [mem_diff, mem_singleton_iff, not_true, and_false, insert_diff_singleton, subset_def, mem_insert_iff, mem_preimage, ne_eq, Function.update_apply, forall_eq_or_imp, ite_true, and_imp, mem_image, ite_eq_left_iff, not_exists, not_and, not_forall, exists_prop, and_iff_right hbt] refine ⟨?_, ?_, fun x hxs hxa ↦ ⟨hxa, (hf₀s x hxs hxa).2⟩⟩ · rintro x hx; split_ifs with h · assumption · exact (hf₀s x hx h).1 exact InjOn.congr hinj (fun x ⟨_, hxa⟩ ↦ by rwa [Function.update_noteq]) termination_by encard s theorem Finite.exists_bijOn_of_encard_eq [Nonempty β] (hs : s.Finite) (h : s.encard = t.encard) : ∃ (f : α → β), BijOn f s t := by obtain ⟨f, hf, hinj⟩ := hs.exists_injOn_of_encard_le h.le; use f convert hinj.bijOn_image rw [(hs.image f).eq_of_subset_of_encard_le' (image_subset_iff.mpr hf) (h.symm.trans hinj.encard_image.symm).le] end Function section ncard open Nat /-- A tactic (for use in default params) that applies `Set.toFinite` to synthesize a `Set.Finite` term. -/ syntax "toFinite_tac" : tactic macro_rules | `(tactic| toFinite_tac) => `(tactic| apply Set.toFinite) /-- A tactic useful for transferring proofs for `encard` to their corresponding `card` statements -/ syntax "to_encard_tac" : tactic macro_rules | `(tactic| to_encard_tac) => `(tactic| simp only [← Nat.cast_le (α := ℕ∞), ← Nat.cast_inj (R := ℕ∞), Nat.cast_add, Nat.cast_one]) /-- The cardinality of `s : Set α` . Has the junk value `0` if `s` is infinite -/ noncomputable def ncard (s : Set α) : ℕ := ENat.toNat s.encard theorem ncard_def (s : Set α) : s.ncard = ENat.toNat s.encard := rfl theorem Finite.cast_ncard_eq (hs : s.Finite) : s.ncard = s.encard := by rwa [ncard, ENat.coe_toNat_eq_self, ne_eq, encard_eq_top_iff, Set.Infinite, not_not] theorem Nat.card_coe_set_eq (s : Set α) : Nat.card s = s.ncard := by obtain (h | h) := s.finite_or_infinite · have := h.fintype rw [ncard, h.encard_eq_coe_toFinset_card, Nat.card_eq_fintype_card, toFinite_toFinset, toFinset_card, ENat.toNat_coe] have := infinite_coe_iff.2 h rw [ncard, h.encard_eq, Nat.card_eq_zero_of_infinite, ENat.toNat_top] theorem ncard_eq_toFinset_card (s : Set α) (hs : s.Finite := by toFinite_tac) : s.ncard = hs.toFinset.card := by rw [← Nat.card_coe_set_eq, @Nat.card_eq_fintype_card _ hs.fintype, @Finite.card_toFinset _ _ hs.fintype hs] theorem ncard_eq_toFinset_card' (s : Set α) [Fintype s] : s.ncard = s.toFinset.card := by simp [← Nat.card_coe_set_eq, Nat.card_eq_fintype_card] theorem encard_le_coe_iff_finite_ncard_le {k : ℕ} : s.encard ≤ k ↔ s.Finite ∧ s.ncard ≤ k := by rw [encard_le_coe_iff, and_congr_right_iff] exact fun hfin ↦ ⟨fun ⟨n₀, hn₀, hle⟩ ↦ by rwa [ncard_def, hn₀, ENat.toNat_coe], fun h ↦ ⟨s.ncard, by rw [hfin.cast_ncard_eq], h⟩⟩ theorem Infinite.ncard (hs : s.Infinite) : s.ncard = 0 := by rw [← Nat.card_coe_set_eq, @Nat.card_eq_zero_of_infinite _ hs.to_subtype] theorem ncard_le_ncard (hst : s ⊆ t) (ht : t.Finite := by toFinite_tac) : s.ncard ≤ t.ncard := by rw [← Nat.cast_le (α := ℕ∞), ht.cast_ncard_eq, (ht.subset hst).cast_ncard_eq] exact encard_mono hst theorem ncard_mono [Finite α] : @Monotone (Set α) _ _ _ ncard := fun _ _ ↦ ncard_le_ncard @[simp] theorem ncard_eq_zero (hs : s.Finite := by toFinite_tac) : s.ncard = 0 ↔ s = ∅ := by rw [← Nat.cast_inj (R := ℕ∞), hs.cast_ncard_eq, Nat.cast_zero, encard_eq_zero] @[simp, norm_cast] theorem ncard_coe_Finset (s : Finset α) : (s : Set α).ncard = s.card := by rw [ncard_eq_toFinset_card _, Finset.finite_toSet_toFinset] theorem ncard_univ (α : Type*) : (univ : Set α).ncard = Nat.card α := by cases' finite_or_infinite α with h h · have hft := Fintype.ofFinite α rw [ncard_eq_toFinset_card, Finite.toFinset_univ, Finset.card_univ, Nat.card_eq_fintype_card] rw [Nat.card_eq_zero_of_infinite, Infinite.ncard] exact infinite_univ @[simp] theorem ncard_empty (α : Type*) : (∅ : Set α).ncard = 0 := by rw [ncard_eq_zero] theorem ncard_pos (hs : s.Finite := by toFinite_tac) : 0 < s.ncard ↔ s.Nonempty := by rw [pos_iff_ne_zero, Ne, ncard_eq_zero hs, nonempty_iff_ne_empty] theorem ncard_ne_zero_of_mem {a : α} (h : a ∈ s) (hs : s.Finite := by toFinite_tac) : s.ncard ≠ 0 := ((ncard_pos hs).mpr ⟨a, h⟩).ne.symm theorem finite_of_ncard_ne_zero (hs : s.ncard ≠ 0) : s.Finite := s.finite_or_infinite.elim id fun h ↦ (hs h.ncard).elim theorem finite_of_ncard_pos (hs : 0 < s.ncard) : s.Finite := finite_of_ncard_ne_zero hs.ne.symm theorem nonempty_of_ncard_ne_zero (hs : s.ncard ≠ 0) : s.Nonempty := by rw [nonempty_iff_ne_empty]; rintro rfl; simp at hs @[simp] theorem ncard_singleton (a : α) : ({a} : Set α).ncard = 1 := by simpa [ncard, encard_singleton] using ENat.toNat_coe 1 theorem ncard_singleton_inter (a : α) (s : Set α) : ({a} ∩ s).ncard ≤ 1 := by rw [← Nat.cast_le (α := ℕ∞), (toFinite _).cast_ncard_eq, Nat.cast_one] apply encard_singleton_inter section InsertErase @[simp] theorem ncard_insert_of_not_mem {a : α} (h : a ∉ s) (hs : s.Finite := by toFinite_tac) : (insert a s).ncard = s.ncard + 1 := by rw [← Nat.cast_inj (R := ℕ∞), (hs.insert a).cast_ncard_eq, Nat.cast_add, Nat.cast_one, hs.cast_ncard_eq, encard_insert_of_not_mem h] theorem ncard_insert_of_mem {a : α} (h : a ∈ s) : ncard (insert a s) = s.ncard := by rw [insert_eq_of_mem h] theorem ncard_insert_le (a : α) (s : Set α) : (insert a s).ncard ≤ s.ncard + 1 := by obtain hs | hs := s.finite_or_infinite · to_encard_tac; rw [hs.cast_ncard_eq, (hs.insert _).cast_ncard_eq]; apply encard_insert_le rw [(hs.mono (subset_insert a s)).ncard] exact Nat.zero_le _ theorem ncard_insert_eq_ite {a : α} [Decidable (a ∈ s)] (hs : s.Finite := by toFinite_tac) : ncard (insert a s) = if a ∈ s then s.ncard else s.ncard + 1 := by by_cases h : a ∈ s · rw [ncard_insert_of_mem h, if_pos h] · rw [ncard_insert_of_not_mem h hs, if_neg h] theorem ncard_le_ncard_insert (a : α) (s : Set α) : s.ncard ≤ (insert a s).ncard := by classical refine s.finite_or_infinite.elim (fun h ↦ ?_) (fun h ↦ by (rw [h.ncard]; exact Nat.zero_le _)) rw [ncard_insert_eq_ite h]; split_ifs <;> simp @[simp] theorem ncard_pair {a b : α} (h : a ≠ b) : ({a, b} : Set α).ncard = 2 := by rw [ncard_insert_of_not_mem, ncard_singleton]; simpa @[simp] theorem ncard_diff_singleton_add_one {a : α} (h : a ∈ s) (hs : s.Finite := by toFinite_tac) : (s \ {a}).ncard + 1 = s.ncard := by to_encard_tac; rw [hs.cast_ncard_eq, (hs.diff _).cast_ncard_eq, encard_diff_singleton_add_one h] @[simp] theorem ncard_diff_singleton_of_mem {a : α} (h : a ∈ s) (hs : s.Finite := by toFinite_tac) : (s \ {a}).ncard = s.ncard - 1 := eq_tsub_of_add_eq (ncard_diff_singleton_add_one h hs) theorem ncard_diff_singleton_lt_of_mem {a : α} (h : a ∈ s) (hs : s.Finite := by toFinite_tac) : (s \ {a}).ncard < s.ncard := by rw [← ncard_diff_singleton_add_one h hs]; apply lt_add_one theorem ncard_diff_singleton_le (s : Set α) (a : α) : (s \ {a}).ncard ≤ s.ncard := by obtain hs | hs := s.finite_or_infinite · apply ncard_le_ncard diff_subset hs convert @zero_le ℕ _ _ exact (hs.diff (by simp : Set.Finite {a})).ncard theorem pred_ncard_le_ncard_diff_singleton (s : Set α) (a : α) : s.ncard - 1 ≤ (s \ {a}).ncard := by cases' s.finite_or_infinite with hs hs · by_cases h : a ∈ s · rw [ncard_diff_singleton_of_mem h hs] rw [diff_singleton_eq_self h] apply Nat.pred_le convert Nat.zero_le _ rw [hs.ncard] theorem ncard_exchange {a b : α} (ha : a ∉ s) (hb : b ∈ s) : (insert a (s \ {b})).ncard = s.ncard := congr_arg ENat.toNat <| encard_exchange ha hb theorem ncard_exchange' {a b : α} (ha : a ∉ s) (hb : b ∈ s) : (insert a s \ {b}).ncard = s.ncard := by rw [← ncard_exchange ha hb, ← singleton_union, ← singleton_union, union_diff_distrib, @diff_singleton_eq_self _ b {a} fun h ↦ ha (by rwa [← mem_singleton_iff.mp h])] end InsertErase variable {f : α → β} theorem ncard_image_le (hs : s.Finite := by toFinite_tac) : (f '' s).ncard ≤ s.ncard := by to_encard_tac; rw [hs.cast_ncard_eq, (hs.image _).cast_ncard_eq]; apply encard_image_le theorem ncard_image_of_injOn (H : Set.InjOn f s) : (f '' s).ncard = s.ncard := congr_arg ENat.toNat <| H.encard_image theorem injOn_of_ncard_image_eq (h : (f '' s).ncard = s.ncard) (hs : s.Finite := by toFinite_tac) : Set.InjOn f s := by rw [← Nat.cast_inj (R := ℕ∞), hs.cast_ncard_eq, (hs.image _).cast_ncard_eq] at h exact hs.injOn_of_encard_image_eq h theorem ncard_image_iff (hs : s.Finite := by toFinite_tac) : (f '' s).ncard = s.ncard ↔ Set.InjOn f s := ⟨fun h ↦ injOn_of_ncard_image_eq h hs, ncard_image_of_injOn⟩ theorem ncard_image_of_injective (s : Set α) (H : f.Injective) : (f '' s).ncard = s.ncard := ncard_image_of_injOn fun _ _ _ _ h ↦ H h theorem ncard_preimage_of_injective_subset_range {s : Set β} (H : f.Injective) (hs : s ⊆ Set.range f) : (f ⁻¹' s).ncard = s.ncard := by rw [← ncard_image_of_injective _ H, image_preimage_eq_iff.mpr hs] theorem fiber_ncard_ne_zero_iff_mem_image {y : β} (hs : s.Finite := by toFinite_tac) : { x ∈ s | f x = y }.ncard ≠ 0 ↔ y ∈ f '' s := by refine ⟨nonempty_of_ncard_ne_zero, ?_⟩ rintro ⟨z, hz, rfl⟩ exact @ncard_ne_zero_of_mem _ ({ x ∈ s | f x = f z }) z (mem_sep hz rfl) (hs.subset (sep_subset _ _)) @[simp] theorem ncard_map (f : α ↪ β) : (f '' s).ncard = s.ncard := ncard_image_of_injective _ f.inj' @[simp] theorem ncard_subtype (P : α → Prop) (s : Set α) : { x : Subtype P | (x : α) ∈ s }.ncard = (s ∩ setOf P).ncard := by convert (ncard_image_of_injective _ (@Subtype.coe_injective _ P)).symm ext x simp [← and_assoc, exists_eq_right] theorem ncard_inter_le_ncard_left (s t : Set α) (hs : s.Finite := by toFinite_tac) : (s ∩ t).ncard ≤ s.ncard := ncard_le_ncard inter_subset_left hs theorem ncard_inter_le_ncard_right (s t : Set α) (ht : t.Finite := by toFinite_tac) : (s ∩ t).ncard ≤ t.ncard := ncard_le_ncard inter_subset_right ht theorem eq_of_subset_of_ncard_le (h : s ⊆ t) (h' : t.ncard ≤ s.ncard) (ht : t.Finite := by toFinite_tac) : s = t := ht.eq_of_subset_of_encard_le h (by rwa [← Nat.cast_le (α := ℕ∞), ht.cast_ncard_eq, (ht.subset h).cast_ncard_eq] at h') theorem subset_iff_eq_of_ncard_le (h : t.ncard ≤ s.ncard) (ht : t.Finite := by toFinite_tac) : s ⊆ t ↔ s = t := ⟨fun hst ↦ eq_of_subset_of_ncard_le hst h ht, Eq.subset'⟩ theorem map_eq_of_subset {f : α ↪ α} (h : f '' s ⊆ s) (hs : s.Finite := by toFinite_tac) : f '' s = s := eq_of_subset_of_ncard_le h (ncard_map _).ge hs theorem sep_of_ncard_eq {a : α} {P : α → Prop} (h : { x ∈ s | P x }.ncard = s.ncard) (ha : a ∈ s) (hs : s.Finite := by toFinite_tac) : P a := sep_eq_self_iff_mem_true.mp (eq_of_subset_of_ncard_le (by simp) h.symm.le hs) _ ha theorem ncard_lt_ncard (h : s ⊂ t) (ht : t.Finite := by toFinite_tac) : s.ncard < t.ncard := by rw [← Nat.cast_lt (α := ℕ∞), ht.cast_ncard_eq, (ht.subset h.subset).cast_ncard_eq] exact ht.encard_lt_encard h theorem ncard_strictMono [Finite α] : @StrictMono (Set α) _ _ _ ncard := fun _ _ h ↦ ncard_lt_ncard h theorem ncard_eq_of_bijective {n : ℕ} (f : ∀ i, i < n → α) (hf : ∀ a ∈ s, ∃ i, ∃ h : i < n, f i h = a) (hf' : ∀ (i) (h : i < n), f i h ∈ s) (f_inj : ∀ (i j) (hi : i < n) (hj : j < n), f i hi = f j hj → i = j) : s.ncard = n := by let f' : Fin n → α := fun i ↦ f i.val i.is_lt suffices himage : s = f' '' Set.univ by rw [← Fintype.card_fin n, ← Nat.card_eq_fintype_card, ← Set.ncard_univ, himage] exact ncard_image_of_injOn <| fun i _hi j _hj h ↦ Fin.ext <| f_inj i.val j.val i.is_lt j.is_lt h ext x simp only [image_univ, mem_range] refine ⟨fun hx ↦ ?_, fun ⟨⟨i, hi⟩, hx⟩ ↦ hx ▸ hf' i hi⟩ obtain ⟨i, hi, rfl⟩ := hf x hx use ⟨i, hi⟩ theorem ncard_congr {t : Set β} (f : ∀ a ∈ s, β) (h₁ : ∀ a ha, f a ha ∈ t) (h₂ : ∀ a b ha hb, f a ha = f b hb → a = b) (h₃ : ∀ b ∈ t, ∃ a ha, f a ha = b) : s.ncard = t.ncard := by set f' : s → t := fun x ↦ ⟨f x.1 x.2, h₁ _ _⟩ have hbij : f'.Bijective := by constructor · rintro ⟨x, hx⟩ ⟨y, hy⟩ hxy simp only [f', Subtype.mk.injEq] at hxy ⊢ exact h₂ _ _ hx hy hxy rintro ⟨y, hy⟩ obtain ⟨a, ha, rfl⟩ := h₃ y hy simp only [Subtype.mk.injEq, Subtype.exists] exact ⟨_, ha, rfl⟩ simp_rw [← Nat.card_coe_set_eq] exact Nat.card_congr (Equiv.ofBijective f' hbij) theorem ncard_le_ncard_of_injOn {t : Set β} (f : α → β) (hf : ∀ a ∈ s, f a ∈ t) (f_inj : InjOn f s) (ht : t.Finite := by toFinite_tac) : s.ncard ≤ t.ncard := by have hle := encard_le_encard_of_injOn hf f_inj to_encard_tac; rwa [ht.cast_ncard_eq, (ht.finite_of_encard_le hle).cast_ncard_eq] theorem exists_ne_map_eq_of_ncard_lt_of_maps_to {t : Set β} (hc : t.ncard < s.ncard) {f : α → β} (hf : ∀ a ∈ s, f a ∈ t) (ht : t.Finite := by toFinite_tac) : ∃ x ∈ s, ∃ y ∈ s, x ≠ y ∧ f x = f y := by by_contra h' simp only [Ne, exists_prop, not_exists, not_and, not_imp_not] at h' exact (ncard_le_ncard_of_injOn f hf h' ht).not_lt hc theorem le_ncard_of_inj_on_range {n : ℕ} (f : ℕ → α) (hf : ∀ i < n, f i ∈ s) (f_inj : ∀ i < n, ∀ j < n, f i = f j → i = j) (hs : s.Finite := by toFinite_tac) : n ≤ s.ncard := by rw [ncard_eq_toFinset_card _ hs] apply Finset.le_card_of_inj_on_range <;> simpa theorem surj_on_of_inj_on_of_ncard_le {t : Set β} (f : ∀ a ∈ s, β) (hf : ∀ a ha, f a ha ∈ t) (hinj : ∀ a₁ a₂ ha₁ ha₂, f a₁ ha₁ = f a₂ ha₂ → a₁ = a₂) (hst : t.ncard ≤ s.ncard) (ht : t.Finite := by toFinite_tac) : ∀ b ∈ t, ∃ a ha, b = f a ha := by intro b hb set f' : s → t := fun x ↦ ⟨f x.1 x.2, hf _ _⟩ have finj : f'.Injective := by rintro ⟨x, hx⟩ ⟨y, hy⟩ hxy simp only [f', Subtype.mk.injEq] at hxy ⊢ apply hinj _ _ hx hy hxy have hft := ht.fintype have hft' := Fintype.ofInjective f' finj set f'' : ∀ a, a ∈ s.toFinset → β := fun a h ↦ f a (by simpa using h) convert @Finset.surj_on_of_inj_on_of_card_le _ _ _ t.toFinset f'' _ _ _ _ (by simpa) · simp · simp [hf] · intros a₁ a₂ ha₁ ha₂ h rw [mem_toFinset] at ha₁ ha₂ exact hinj _ _ ha₁ ha₂ h rwa [← ncard_eq_toFinset_card', ← ncard_eq_toFinset_card'] theorem inj_on_of_surj_on_of_ncard_le {t : Set β} (f : ∀ a ∈ s, β) (hf : ∀ a ha, f a ha ∈ t) (hsurj : ∀ b ∈ t, ∃ a ha, f a ha = b) (hst : s.ncard ≤ t.ncard) ⦃a₁⦄ (ha₁ : a₁ ∈ s) ⦃a₂⦄ (ha₂ : a₂ ∈ s) (ha₁a₂ : f a₁ ha₁ = f a₂ ha₂) (hs : s.Finite := by toFinite_tac) : a₁ = a₂ := by classical set f' : s → t := fun x ↦ ⟨f x.1 x.2, hf _ _⟩ have hsurj : f'.Surjective := by rintro ⟨y, hy⟩ obtain ⟨a, ha, rfl⟩ := hsurj y hy simp only [Subtype.mk.injEq, Subtype.exists] exact ⟨_, ha, rfl⟩ haveI := hs.fintype haveI := Fintype.ofSurjective _ hsurj set f'' : ∀ a, a ∈ s.toFinset → β := fun a h ↦ f a (by simpa using h) exact @Finset.inj_on_of_surj_on_of_card_le _ _ _ t.toFinset f'' (fun a ha ↦ by { rw [mem_toFinset] at ha ⊢; exact hf a ha }) (by simpa) (by { rwa [← ncard_eq_toFinset_card', ← ncard_eq_toFinset_card'] }) a₁ (by simpa) a₂ (by simpa) (by simpa) section Lattice theorem ncard_union_add_ncard_inter (s t : Set α) (hs : s.Finite := by toFinite_tac) (ht : t.Finite := by toFinite_tac) : (s ∪ t).ncard + (s ∩ t).ncard = s.ncard + t.ncard := by to_encard_tac; rw [hs.cast_ncard_eq, ht.cast_ncard_eq, (hs.union ht).cast_ncard_eq, (hs.subset inter_subset_left).cast_ncard_eq, encard_union_add_encard_inter] theorem ncard_inter_add_ncard_union (s t : Set α) (hs : s.Finite := by toFinite_tac) (ht : t.Finite := by toFinite_tac) : (s ∩ t).ncard + (s ∪ t).ncard = s.ncard + t.ncard := by rw [add_comm, ncard_union_add_ncard_inter _ _ hs ht] theorem ncard_union_le (s t : Set α) : (s ∪ t).ncard ≤ s.ncard + t.ncard := by obtain (h | h) := (s ∪ t).finite_or_infinite · to_encard_tac rw [h.cast_ncard_eq, (h.subset subset_union_left).cast_ncard_eq, (h.subset subset_union_right).cast_ncard_eq] apply encard_union_le rw [h.ncard] apply zero_le theorem ncard_union_eq (h : Disjoint s t) (hs : s.Finite := by toFinite_tac) (ht : t.Finite := by toFinite_tac) : (s ∪ t).ncard = s.ncard + t.ncard := by to_encard_tac rw [hs.cast_ncard_eq, ht.cast_ncard_eq, (hs.union ht).cast_ncard_eq, encard_union_eq h] theorem ncard_diff_add_ncard_of_subset (h : s ⊆ t) (ht : t.Finite := by toFinite_tac) : (t \ s).ncard + s.ncard = t.ncard := by to_encard_tac rw [ht.cast_ncard_eq, (ht.subset h).cast_ncard_eq, (ht.diff _).cast_ncard_eq, encard_diff_add_encard_of_subset h] theorem ncard_diff (h : s ⊆ t) (ht : t.Finite := by toFinite_tac) : (t \ s).ncard = t.ncard - s.ncard := by rw [← ncard_diff_add_ncard_of_subset h ht, add_tsub_cancel_right] theorem ncard_le_ncard_diff_add_ncard (s t : Set α) (ht : t.Finite := by toFinite_tac) : s.ncard ≤ (s \ t).ncard + t.ncard := by cases' s.finite_or_infinite with hs hs · to_encard_tac rw [ht.cast_ncard_eq, hs.cast_ncard_eq, (hs.diff _).cast_ncard_eq] apply encard_le_encard_diff_add_encard convert Nat.zero_le _ rw [hs.ncard] theorem le_ncard_diff (s t : Set α) (hs : s.Finite := by toFinite_tac) : t.ncard - s.ncard ≤ (t \ s).ncard := tsub_le_iff_left.mpr (by rw [add_comm]; apply ncard_le_ncard_diff_add_ncard _ _ hs) theorem ncard_diff_add_ncard (s t : Set α) (hs : s.Finite := by toFinite_tac) (ht : t.Finite := by toFinite_tac) : (s \ t).ncard + t.ncard = (s ∪ t).ncard := by rw [← ncard_union_eq disjoint_sdiff_left (hs.diff _) ht, diff_union_self] theorem diff_nonempty_of_ncard_lt_ncard (h : s.ncard < t.ncard) (hs : s.Finite := by toFinite_tac) : (t \ s).Nonempty := by rw [Set.nonempty_iff_ne_empty, Ne, diff_eq_empty] exact fun h' ↦ h.not_le (ncard_le_ncard h' hs) theorem exists_mem_not_mem_of_ncard_lt_ncard (h : s.ncard < t.ncard) (hs : s.Finite := by toFinite_tac) : ∃ e, e ∈ t ∧ e ∉ s := diff_nonempty_of_ncard_lt_ncard h hs @[simp] theorem ncard_inter_add_ncard_diff_eq_ncard (s t : Set α) (hs : s.Finite := by toFinite_tac) : (s ∩ t).ncard + (s \ t).ncard = s.ncard := by rw [← ncard_union_eq (disjoint_of_subset_left inter_subset_right disjoint_sdiff_right) (hs.inter_of_left _) (hs.diff _), union_comm, diff_union_inter] theorem ncard_eq_ncard_iff_ncard_diff_eq_ncard_diff (hs : s.Finite := by toFinite_tac) (ht : t.Finite := by toFinite_tac) : s.ncard = t.ncard ↔ (s \ t).ncard = (t \ s).ncard := by rw [← ncard_inter_add_ncard_diff_eq_ncard s t hs, ← ncard_inter_add_ncard_diff_eq_ncard t s ht, inter_comm, add_right_inj] theorem ncard_le_ncard_iff_ncard_diff_le_ncard_diff (hs : s.Finite := by toFinite_tac) (ht : t.Finite := by toFinite_tac) : s.ncard ≤ t.ncard ↔ (s \ t).ncard ≤ (t \ s).ncard := by rw [← ncard_inter_add_ncard_diff_eq_ncard s t hs, ← ncard_inter_add_ncard_diff_eq_ncard t s ht, inter_comm, add_le_add_iff_left] theorem ncard_lt_ncard_iff_ncard_diff_lt_ncard_diff (hs : s.Finite := by toFinite_tac) (ht : t.Finite := by toFinite_tac) : s.ncard < t.ncard ↔ (s \ t).ncard < (t \ s).ncard := by rw [← ncard_inter_add_ncard_diff_eq_ncard s t hs, ← ncard_inter_add_ncard_diff_eq_ncard t s ht, inter_comm, add_lt_add_iff_left] theorem ncard_add_ncard_compl (s : Set α) (hs : s.Finite := by toFinite_tac) (hsc : sᶜ.Finite := by toFinite_tac) : s.ncard + sᶜ.ncard = Nat.card α := by rw [← ncard_univ, ← ncard_union_eq (@disjoint_compl_right _ _ s) hs hsc, union_compl_self] end Lattice /-- Given a subset `s` of a set `t`, of sizes at most and at least `n` respectively, there exists a set `u` of size `n` which is both a superset of `s` and a subset of `t`. -/ lemma exists_subsuperset_card_eq {n : ℕ} (hst : s ⊆ t) (hsn : s.ncard ≤ n) (hnt : n ≤ t.ncard) : ∃ u, s ⊆ u ∧ u ⊆ t ∧ u.ncard = n := by obtain ht | ht := t.infinite_or_finite · rw [ht.ncard, Nat.le_zero, ← ht.ncard] at hnt exact ⟨t, hst, Subset.rfl, hnt.symm⟩ lift s to Finset α using ht.subset hst lift t to Finset α using ht obtain ⟨u, hsu, hut, hu⟩ := Finset.exists_subsuperset_card_eq (mod_cast hst) (by simpa using hsn) (mod_cast hnt) exact ⟨u, mod_cast hsu, mod_cast hut, mod_cast hu⟩ /-- We can shrink a set to any smaller size. -/ lemma exists_subset_card_eq {n : ℕ} (hns : n ≤ s.ncard) : ∃ t ⊆ s, t.ncard = n := by simpa using exists_subsuperset_card_eq s.empty_subset (by simp) hns /-- Given a set `t` and a set `s` inside it, we can shrink `t` to any appropriate size, and keep `s` inside it. -/ @[deprecated exists_subsuperset_card_eq (since := "2024-06-24")] theorem exists_intermediate_Set (i : ℕ) (h₁ : i + s.ncard ≤ t.ncard) (h₂ : s ⊆ t) : ∃ r : Set α, s ⊆ r ∧ r ⊆ t ∧ r.ncard = i + s.ncard := exists_subsuperset_card_eq h₂ (Nat.le_add_left ..) h₁ @[deprecated exists_subsuperset_card_eq (since := "2024-06-24")] theorem exists_intermediate_set' {m : ℕ} (hs : s.ncard ≤ m) (ht : m ≤ t.ncard) (h : s ⊆ t) : ∃ r : Set α, s ⊆ r ∧ r ⊆ t ∧ r.ncard = m := exists_subsuperset_card_eq h hs ht /-- We can shrink `s` to any smaller size. -/ @[deprecated exists_subset_card_eq (since := "2024-06-23")] theorem exists_smaller_set (s : Set α) (i : ℕ) (h₁ : i ≤ s.ncard) : ∃ t : Set α, t ⊆ s ∧ t.ncard = i := exists_subset_card_eq h₁ theorem Infinite.exists_subset_ncard_eq {s : Set α} (hs : s.Infinite) (k : ℕ) : ∃ t, t ⊆ s ∧ t.Finite ∧ t.ncard = k := by have := hs.to_subtype obtain ⟨t', -, rfl⟩ := @Infinite.exists_subset_card_eq s univ infinite_univ k refine ⟨Subtype.val '' (t' : Set s), by simp, Finite.image _ (by simp), ?_⟩ rw [ncard_image_of_injective _ Subtype.coe_injective] simp theorem Infinite.exists_superset_ncard_eq {s t : Set α} (ht : t.Infinite) (hst : s ⊆ t) (hs : s.Finite) {k : ℕ} (hsk : s.ncard ≤ k) : ∃ s', s ⊆ s' ∧ s' ⊆ t ∧ s'.ncard = k := by obtain ⟨s₁, hs₁, hs₁fin, hs₁card⟩ := (ht.diff hs).exists_subset_ncard_eq (k - s.ncard) refine ⟨s ∪ s₁, subset_union_left, union_subset hst (hs₁.trans diff_subset), ?_⟩ rwa [ncard_union_eq (disjoint_of_subset_right hs₁ disjoint_sdiff_right) hs hs₁fin, hs₁card, add_tsub_cancel_of_le] theorem exists_subset_or_subset_of_two_mul_lt_ncard {n : ℕ} (hst : 2 * n < (s ∪ t).ncard) : ∃ r : Set α, n < r.ncard ∧ (r ⊆ s ∨ r ⊆ t) := by classical have hu := finite_of_ncard_ne_zero ((Nat.zero_le _).trans_lt hst).ne.symm rw [ncard_eq_toFinset_card _ hu, Finite.toFinset_union (hu.subset subset_union_left) (hu.subset subset_union_right)] at hst obtain ⟨r', hnr', hr'⟩ := Finset.exists_subset_or_subset_of_two_mul_lt_card hst exact ⟨r', by simpa, by simpa using hr'⟩ /-! ### Explicit description of a set from its cardinality -/ @[simp] theorem ncard_eq_one : s.ncard = 1 ↔ ∃ a, s = {a} := by refine ⟨fun h ↦ ?_, by rintro ⟨a, rfl⟩; rw [ncard_singleton]⟩ have hft := (finite_of_ncard_ne_zero (ne_zero_of_eq_one h)).fintype simp_rw [ncard_eq_toFinset_card', @Finset.card_eq_one _ (toFinset s)] at h refine h.imp fun a ha ↦ ?_ simp_rw [Set.ext_iff, mem_singleton_iff] simp only [Finset.ext_iff, mem_toFinset, Finset.mem_singleton] at ha exact ha theorem exists_eq_insert_iff_ncard (hs : s.Finite := by toFinite_tac) : (∃ a ∉ s, insert a s = t) ↔ s ⊆ t ∧ s.ncard + 1 = t.ncard := by classical cases' t.finite_or_infinite with ht ht · rw [ncard_eq_toFinset_card _ hs, ncard_eq_toFinset_card _ ht, ← @Finite.toFinset_subset_toFinset _ _ _ hs ht, ← Finset.exists_eq_insert_iff] convert Iff.rfl using 2; simp ext x simp [Finset.ext_iff, Set.ext_iff] simp only [ht.ncard, exists_prop, add_eq_zero, and_false, iff_false, not_exists, not_and] rintro x - rfl exact ht (hs.insert x) theorem ncard_le_one (hs : s.Finite := by toFinite_tac) : s.ncard ≤ 1 ↔ ∀ a ∈ s, ∀ b ∈ s, a = b := by simp_rw [ncard_eq_toFinset_card _ hs, Finset.card_le_one, Finite.mem_toFinset] theorem ncard_le_one_iff (hs : s.Finite := by toFinite_tac) : s.ncard ≤ 1 ↔ ∀ {a b}, a ∈ s → b ∈ s → a = b := by rw [ncard_le_one hs] tauto theorem ncard_le_one_iff_eq (hs : s.Finite := by toFinite_tac) : s.ncard ≤ 1 ↔ s = ∅ ∨ ∃ a, s = {a} := by obtain rfl | ⟨x, hx⟩ := s.eq_empty_or_nonempty · exact iff_of_true (by simp) (Or.inl rfl) rw [ncard_le_one_iff hs] refine ⟨fun h ↦ Or.inr ⟨x, (singleton_subset_iff.mpr hx).antisymm' fun y hy ↦ h hy hx⟩, ?_⟩ rintro (rfl | ⟨a, rfl⟩) · exact (not_mem_empty _ hx).elim simp_rw [mem_singleton_iff] at hx ⊢; subst hx simp only [forall_eq_apply_imp_iff, imp_self, implies_true] theorem ncard_le_one_iff_subset_singleton [Nonempty α] (hs : s.Finite := by toFinite_tac) : s.ncard ≤ 1 ↔ ∃ x : α, s ⊆ {x} := by simp_rw [ncard_eq_toFinset_card _ hs, Finset.card_le_one_iff_subset_singleton, Finite.toFinset_subset, Finset.coe_singleton] /-- A `Set` of a subsingleton type has cardinality at most one. -/ theorem ncard_le_one_of_subsingleton [Subsingleton α] (s : Set α) : s.ncard ≤ 1 := by rw [ncard_eq_toFinset_card] exact Finset.card_le_one_of_subsingleton _ theorem one_lt_ncard (hs : s.Finite := by toFinite_tac) : 1 < s.ncard ↔ ∃ a ∈ s, ∃ b ∈ s, a ≠ b := by simp_rw [ncard_eq_toFinset_card _ hs, Finset.one_lt_card, Finite.mem_toFinset] theorem one_lt_ncard_iff (hs : s.Finite := by toFinite_tac) : 1 < s.ncard ↔ ∃ a b, a ∈ s ∧ b ∈ s ∧ a ≠ b := by rw [one_lt_ncard hs] simp only [exists_prop, exists_and_left] theorem two_lt_ncard_iff (hs : s.Finite := by toFinite_tac) : 2 < s.ncard ↔ ∃ a b c, a ∈ s ∧ b ∈ s ∧ c ∈ s ∧ a ≠ b ∧ a ≠ c ∧ b ≠ c := by simp_rw [ncard_eq_toFinset_card _ hs, Finset.two_lt_card_iff, Finite.mem_toFinset] theorem two_lt_ncard (hs : s.Finite := by toFinite_tac) : 2 < s.ncard ↔ ∃ a ∈ s, ∃ b ∈ s, ∃ c ∈ s, a ≠ b ∧ a ≠ c ∧ b ≠ c := by simp only [two_lt_ncard_iff hs, exists_and_left, exists_prop] theorem exists_ne_of_one_lt_ncard (hs : 1 < s.ncard) (a : α) : ∃ b, b ∈ s ∧ b ≠ a := by have hsf := finite_of_ncard_ne_zero (zero_lt_one.trans hs).ne.symm rw [ncard_eq_toFinset_card _ hsf] at hs simpa only [Finite.mem_toFinset] using Finset.exists_ne_of_one_lt_card hs a theorem eq_insert_of_ncard_eq_succ {n : ℕ} (h : s.ncard = n + 1) : ∃ a t, a ∉ t ∧ insert a t = s ∧ t.ncard = n := by classical have hsf := finite_of_ncard_pos (n.zero_lt_succ.trans_eq h.symm) rw [ncard_eq_toFinset_card _ hsf, Finset.card_eq_succ] at h obtain ⟨a, t, hat, hts, rfl⟩ := h simp only [Finset.ext_iff, Finset.mem_insert, Finite.mem_toFinset] at hts refine ⟨a, t, hat, ?_, ?_⟩ · simp only [Finset.mem_coe, Set.ext_iff, mem_insert_iff] tauto simp theorem ncard_eq_succ {n : ℕ} (hs : s.Finite := by toFinite_tac) : s.ncard = n + 1 ↔ ∃ a t, a ∉ t ∧ insert a t = s ∧ t.ncard = n := by refine ⟨eq_insert_of_ncard_eq_succ, ?_⟩ rintro ⟨a, t, hat, h, rfl⟩ rw [← h, ncard_insert_of_not_mem hat (hs.subset ((subset_insert a t).trans_eq h))] theorem ncard_eq_two : s.ncard = 2 ↔ ∃ x y, x ≠ y ∧ s = {x, y} := by rw [← encard_eq_two, ncard_def, ← Nat.cast_inj (R := ℕ∞), Nat.cast_ofNat] refine ⟨fun h ↦ ?_, fun h ↦ ?_⟩ · rwa [ENat.coe_toNat] at h; rintro h'; simp [h'] at h rw [h]; rfl theorem ncard_eq_three : s.ncard = 3 ↔ ∃ x y z, x ≠ y ∧ x ≠ z ∧ y ≠ z ∧ s = {x, y, z} := by rw [← encard_eq_three, ncard_def, ← Nat.cast_inj (R := ℕ∞), Nat.cast_ofNat] refine ⟨fun h ↦ ?_, fun h ↦ ?_⟩ · rwa [ENat.coe_toNat] at h; rintro h'; simp [h'] at h rw [h]; rfl end ncard @[deprecated (since := "2023-12-27")] alias ncard_le_of_subset := ncard_le_ncard end Set
Data\Set\Constructions.lean
/- Copyright (c) 2020 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz -/ import Mathlib.Data.Finset.Basic import Mathlib.Data.Set.Lattice /-! # Constructions involving sets of sets. ## Finite Intersections We define a structure `FiniteInter` which asserts that a set `S` of subsets of `α` is closed under finite intersections. We define `finiteInterClosure` which, given a set `S` of subsets of `α`, is the smallest set of subsets of `α` which is closed under finite intersections. `finiteInterClosure S` is endowed with a term of type `FiniteInter` using `finiteInterClosure_finiteInter`. -/ variable {α : Type*} (S : Set (Set α)) /-- A structure encapsulating the fact that a set of sets is closed under finite intersection. -/ structure FiniteInter : Prop where /-- `univ_mem` states that `Set.univ` is in `S`. -/ univ_mem : Set.univ ∈ S /-- `inter_mem` states that any two intersections of sets in `S` is also in `S`. -/ inter_mem : ∀ ⦃s⦄, s ∈ S → ∀ ⦃t⦄, t ∈ S → s ∩ t ∈ S namespace FiniteInter /-- The smallest set of sets containing `S` which is closed under finite intersections. -/ inductive finiteInterClosure : Set (Set α) | basic {s} : s ∈ S → finiteInterClosure s | univ : finiteInterClosure Set.univ | inter {s t} : finiteInterClosure s → finiteInterClosure t → finiteInterClosure (s ∩ t) theorem finiteInterClosure_finiteInter : FiniteInter (finiteInterClosure S) := { univ_mem := finiteInterClosure.univ inter_mem := fun _ h _ => finiteInterClosure.inter h } variable {S} theorem finiteInter_mem (cond : FiniteInter S) (F : Finset (Set α)) : ↑F ⊆ S → ⋂₀ (↑F : Set (Set α)) ∈ S := by classical refine Finset.induction_on F (fun _ => ?_) ?_ · simp [cond.univ_mem] · intro a s _ h1 h2 suffices a ∩ ⋂₀ ↑s ∈ S by simpa exact cond.inter_mem (h2 (Finset.mem_insert_self a s)) (h1 fun x hx => h2 <| Finset.mem_insert_of_mem hx) theorem finiteInterClosure_insert {A : Set α} (cond : FiniteInter S) (P) (H : P ∈ finiteInterClosure (insert A S)) : P ∈ S ∨ ∃ Q ∈ S, P = A ∩ Q := by induction' H with S h T1 T2 _ _ h1 h2 · cases h · exact Or.inr ⟨Set.univ, cond.univ_mem, by simpa⟩ · exact Or.inl (by assumption) · exact Or.inl cond.univ_mem · rcases h1 with (h | ⟨Q, hQ, rfl⟩) <;> rcases h2 with (i | ⟨R, hR, rfl⟩) · exact Or.inl (cond.inter_mem h i) · exact Or.inr ⟨T1 ∩ R, cond.inter_mem h hR, by simp only [← Set.inter_assoc, Set.inter_comm _ A]⟩ · exact Or.inr ⟨Q ∩ T2, cond.inter_mem hQ i, by simp only [Set.inter_assoc]⟩ · exact Or.inr ⟨Q ∩ R, cond.inter_mem hQ hR, by ext x constructor <;> simp (config := { contextual := true })⟩ open Set theorem mk₂ (h: ∀ ⦃s⦄, s ∈ S → ∀ ⦃t⦄, t ∈ S → s ∩ t ∈ S) : FiniteInter (insert (univ : Set α) S) where univ_mem := Set.mem_insert Set.univ S inter_mem s hs t ht := by aesop end FiniteInter
Data\Set\Countable.lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import Mathlib.Data.Set.Finite import Mathlib.Data.Countable.Basic import Mathlib.Logic.Equiv.List import Mathlib.Data.Set.Subsingleton /-! # Countable sets In this file we define `Set.Countable s` as `Countable s` and prove basic properties of this definition. Note that this definition does not provide a computable encoding. For a noncomputable conversion to `Encodable s`, use `Set.Countable.nonempty_encodable`. ## Keywords sets, countable set -/ noncomputable section open scoped Classical open Function Set Encodable universe u v w x variable {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} namespace Set /-- A set `s` is countable if the corresponding subtype is countable, i.e., there exists an injective map `f : s → ℕ`. Note that this is an abbreviation, so `hs : Set.Countable s` in the proof context is the same as an instance `Countable s`. For a constructive version, see `Encodable`. -/ protected def Countable (s : Set α) : Prop := Countable s @[simp] theorem countable_coe_iff {s : Set α} : Countable s ↔ s.Countable := .rfl /-- Prove `Set.Countable` from a `Countable` instance on the subtype. -/ theorem to_countable (s : Set α) [Countable s] : s.Countable := ‹_› /-- Restate `Set.Countable` as a `Countable` instance. -/ alias ⟨_root_.Countable.to_set, Countable.to_subtype⟩ := countable_coe_iff protected theorem countable_iff_exists_injective {s : Set α} : s.Countable ↔ ∃ f : s → ℕ, Injective f := countable_iff_exists_injective s /-- A set `s : Set α` is countable if and only if there exists a function `α → ℕ` injective on `s`. -/ theorem countable_iff_exists_injOn {s : Set α} : s.Countable ↔ ∃ f : α → ℕ, InjOn f s := Set.countable_iff_exists_injective.trans exists_injOn_iff_injective.symm theorem countable_iff_nonempty_encodable {s : Set α} : s.Countable ↔ Nonempty (Encodable s) := Encodable.nonempty_encodable.symm alias ⟨Countable.nonempty_encodable, _⟩ := countable_iff_nonempty_encodable /-- Convert `Set.Countable s` to `Encodable s` (noncomputable). -/ protected def Countable.toEncodable {s : Set α} (hs : s.Countable) : Encodable s := Classical.choice hs.nonempty_encodable section Enumerate /-- Noncomputably enumerate elements in a set. The `default` value is used to extend the domain to all of `ℕ`. -/ def enumerateCountable {s : Set α} (h : s.Countable) (default : α) : ℕ → α := fun n => match @Encodable.decode s h.toEncodable n with | some y => y | none => default theorem subset_range_enumerate {s : Set α} (h : s.Countable) (default : α) : s ⊆ range (enumerateCountable h default) := fun x hx => ⟨@Encodable.encode s h.toEncodable ⟨x, hx⟩, by letI := h.toEncodable simp [enumerateCountable, Encodable.encodek]⟩ lemma range_enumerateCountable_subset {s : Set α} (h : s.Countable) (default : α) : range (enumerateCountable h default) ⊆ insert default s := by refine range_subset_iff.mpr (fun n ↦ ?_) rw [enumerateCountable] match @decode s (Countable.toEncodable h) n with | none => exact mem_insert _ _ | some val => simp lemma range_enumerateCountable_of_mem {s : Set α} (h : s.Countable) {default : α} (h_mem : default ∈ s) : range (enumerateCountable h default) = s := subset_antisymm ((range_enumerateCountable_subset h _).trans_eq (insert_eq_of_mem h_mem)) (subset_range_enumerate h default) lemma enumerateCountable_mem {s : Set α} (h : s.Countable) {default : α} (h_mem : default ∈ s) (n : ℕ) : enumerateCountable h default n ∈ s := by conv_rhs => rw [← range_enumerateCountable_of_mem h h_mem] exact mem_range_self n end Enumerate theorem Countable.mono {s₁ s₂ : Set α} (h : s₁ ⊆ s₂) (hs : s₂.Countable) : s₁.Countable := have := hs.to_subtype; (inclusion_injective h).countable theorem countable_range [Countable ι] (f : ι → β) : (range f).Countable := surjective_onto_range.countable.to_set theorem countable_iff_exists_subset_range [Nonempty α] {s : Set α} : s.Countable ↔ ∃ f : ℕ → α, s ⊆ range f := ⟨fun h => by inhabit α exact ⟨enumerateCountable h default, subset_range_enumerate _ _⟩, fun ⟨f, hsf⟩ => (countable_range f).mono hsf⟩ /-- A non-empty set is countable iff there exists a surjection from the natural numbers onto the subtype induced by the set. -/ protected theorem countable_iff_exists_surjective {s : Set α} (hs : s.Nonempty) : s.Countable ↔ ∃ f : ℕ → s, Surjective f := @countable_iff_exists_surjective s hs.to_subtype alias ⟨Countable.exists_surjective, _⟩ := Set.countable_iff_exists_surjective theorem countable_univ [Countable α] : (univ : Set α).Countable := to_countable univ theorem countable_univ_iff : (univ : Set α).Countable ↔ Countable α := countable_coe_iff.symm.trans (Equiv.Set.univ _).countable_iff /-- If `s : Set α` is a nonempty countable set, then there exists a map `f : ℕ → α` such that `s = range f`. -/ theorem Countable.exists_eq_range {s : Set α} (hc : s.Countable) (hs : s.Nonempty) : ∃ f : ℕ → α, s = range f := by rcases hc.exists_surjective hs with ⟨f, hf⟩ refine ⟨(↑) ∘ f, ?_⟩ rw [hf.range_comp, Subtype.range_coe] @[simp] theorem countable_empty : (∅ : Set α).Countable := to_countable _ @[simp] theorem countable_singleton (a : α) : ({a} : Set α).Countable := to_countable _ theorem Countable.image {s : Set α} (hs : s.Countable) (f : α → β) : (f '' s).Countable := by rw [image_eq_range] have := hs.to_subtype apply countable_range theorem MapsTo.countable_of_injOn {s : Set α} {t : Set β} {f : α → β} (hf : MapsTo f s t) (hf' : InjOn f s) (ht : t.Countable) : s.Countable := have := ht.to_subtype have : Injective (hf.restrict f s t) := (injOn_iff_injective.1 hf').codRestrict _ this.countable theorem Countable.preimage_of_injOn {s : Set β} (hs : s.Countable) {f : α → β} (hf : InjOn f (f ⁻¹' s)) : (f ⁻¹' s).Countable := (mapsTo_preimage f s).countable_of_injOn hf hs protected theorem Countable.preimage {s : Set β} (hs : s.Countable) {f : α → β} (hf : Injective f) : (f ⁻¹' s).Countable := hs.preimage_of_injOn hf.injOn theorem exists_seq_iSup_eq_top_iff_countable [CompleteLattice α] {p : α → Prop} (h : ∃ x, p x) : (∃ s : ℕ → α, (∀ n, p (s n)) ∧ ⨆ n, s n = ⊤) ↔ ∃ S : Set α, S.Countable ∧ (∀ s ∈ S, p s) ∧ sSup S = ⊤ := by constructor · rintro ⟨s, hps, hs⟩ refine ⟨range s, countable_range s, forall_mem_range.2 hps, ?_⟩ rwa [sSup_range] · rintro ⟨S, hSc, hps, hS⟩ rcases eq_empty_or_nonempty S with (rfl | hne) · rw [sSup_empty] at hS haveI := subsingleton_of_bot_eq_top hS rcases h with ⟨x, hx⟩ exact ⟨fun _ => x, fun _ => hx, Subsingleton.elim _ _⟩ · rcases (Set.countable_iff_exists_surjective hne).1 hSc with ⟨s, hs⟩ refine ⟨fun n => s n, fun n => hps _ (s n).coe_prop, ?_⟩ rwa [hs.iSup_comp, ← sSup_eq_iSup'] theorem exists_seq_cover_iff_countable {p : Set α → Prop} (h : ∃ s, p s) : (∃ s : ℕ → Set α, (∀ n, p (s n)) ∧ ⋃ n, s n = univ) ↔ ∃ S : Set (Set α), S.Countable ∧ (∀ s ∈ S, p s) ∧ ⋃₀ S = univ := exists_seq_iSup_eq_top_iff_countable h theorem countable_of_injective_of_countable_image {s : Set α} {f : α → β} (hf : InjOn f s) (hs : (f '' s).Countable) : s.Countable := (mapsTo_image _ _).countable_of_injOn hf hs theorem countable_iUnion {t : ι → Set α} [Countable ι] (ht : ∀ i, (t i).Countable) : (⋃ i, t i).Countable := by have := fun i ↦ (ht i).to_subtype rw [iUnion_eq_range_psigma] apply countable_range @[simp] theorem countable_iUnion_iff [Countable ι] {t : ι → Set α} : (⋃ i, t i).Countable ↔ ∀ i, (t i).Countable := ⟨fun h _ => h.mono <| subset_iUnion _ _, countable_iUnion⟩ theorem Countable.biUnion_iff {s : Set α} {t : ∀ a ∈ s, Set β} (hs : s.Countable) : (⋃ a ∈ s, t a ‹_›).Countable ↔ ∀ a (ha : a ∈ s), (t a ha).Countable := by have := hs.to_subtype rw [biUnion_eq_iUnion, countable_iUnion_iff, SetCoe.forall'] theorem Countable.sUnion_iff {s : Set (Set α)} (hs : s.Countable) : (⋃₀ s).Countable ↔ ∀ a ∈ s, a.Countable := by rw [sUnion_eq_biUnion, hs.biUnion_iff] alias ⟨_, Countable.biUnion⟩ := Countable.biUnion_iff alias ⟨_, Countable.sUnion⟩ := Countable.sUnion_iff @[simp] theorem countable_union {s t : Set α} : (s ∪ t).Countable ↔ s.Countable ∧ t.Countable := by simp [union_eq_iUnion, and_comm] theorem Countable.union {s t : Set α} (hs : s.Countable) (ht : t.Countable) : (s ∪ t).Countable := countable_union.2 ⟨hs, ht⟩ theorem Countable.of_diff {s t : Set α} (h : (s \ t).Countable) (ht : t.Countable) : s.Countable := (h.union ht).mono (subset_diff_union _ _) @[simp] theorem countable_insert {s : Set α} {a : α} : (insert a s).Countable ↔ s.Countable := by simp only [insert_eq, countable_union, countable_singleton, true_and_iff] protected theorem Countable.insert {s : Set α} (a : α) (h : s.Countable) : (insert a s).Countable := countable_insert.2 h theorem Finite.countable {s : Set α} (hs : s.Finite) : s.Countable := have := hs.to_subtype; s.to_countable @[nontriviality] theorem Countable.of_subsingleton [Subsingleton α] (s : Set α) : s.Countable := (Finite.of_subsingleton s).countable theorem Subsingleton.countable {s : Set α} (hs : s.Subsingleton) : s.Countable := hs.finite.countable theorem countable_isTop (α : Type*) [PartialOrder α] : { x : α | IsTop x }.Countable := (finite_isTop α).countable theorem countable_isBot (α : Type*) [PartialOrder α] : { x : α | IsBot x }.Countable := (finite_isBot α).countable /-- The set of finite subsets of a countable set is countable. -/ theorem countable_setOf_finite_subset {s : Set α} (hs : s.Countable) : { t | Set.Finite t ∧ t ⊆ s }.Countable := by have := hs.to_subtype refine (countable_range fun t : Finset s => Subtype.val '' (t : Set s)).mono ?_ rintro t ⟨ht, hts⟩ lift t to Set s using hts lift t to Finset s using ht.of_finite_image Subtype.val_injective.injOn exact mem_range_self _ theorem countable_univ_pi {π : α → Type*} [Finite α] {s : ∀ a, Set (π a)} (hs : ∀ a, (s a).Countable) : (pi univ s).Countable := have := fun a ↦ (hs a).to_subtype; .of_equiv _ (Equiv.Set.univPi s).symm theorem countable_pi {π : α → Type*} [Finite α] {s : ∀ a, Set (π a)} (hs : ∀ a, (s a).Countable) : { f : ∀ a, π a | ∀ a, f a ∈ s a }.Countable := by simpa only [← mem_univ_pi] using countable_univ_pi hs protected theorem Countable.prod {s : Set α} {t : Set β} (hs : s.Countable) (ht : t.Countable) : Set.Countable (s ×ˢ t) := have := hs.to_subtype; have := ht.to_subtype; .of_equiv _ <| (Equiv.Set.prod _ _).symm theorem Countable.image2 {s : Set α} {t : Set β} (hs : s.Countable) (ht : t.Countable) (f : α → β → γ) : (image2 f s t).Countable := by rw [← image_prod] exact (hs.prod ht).image _ /-- If a family of disjoint sets is included in a countable set, then only countably many of them are nonempty. -/ theorem countable_setOf_nonempty_of_disjoint {f : β → Set α} (hf : Pairwise (Disjoint on f)) {s : Set α} (h'f : ∀ t, f t ⊆ s) (hs : s.Countable) : Set.Countable {t | (f t).Nonempty} := by rw [← Set.countable_coe_iff] at hs ⊢ have : ∀ t : {t // (f t).Nonempty}, ∃ x : s, x.1 ∈ f t := by rintro ⟨t, ⟨x, hx⟩⟩ exact ⟨⟨x, (h'f t hx)⟩, hx⟩ choose F hF using this have A : Injective F := by rintro ⟨t, ht⟩ ⟨t', ht'⟩ htt' have A : (f t ∩ f t').Nonempty := by refine ⟨F ⟨t, ht⟩, hF _, ?_⟩ rw [htt'] exact hF _ simp only [Subtype.mk.injEq] by_contra H exact not_disjoint_iff_nonempty_inter.2 A (hf H) exact Injective.countable A end Set theorem Finset.countable_toSet (s : Finset α) : Set.Countable (↑s : Set α) := s.finite_toSet.countable
Data\Set\Defs.lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Johannes Hölzl, Reid Barton, Scott Morrison, Patrick Massot, Kyle Miller, Minchao Wu, Yury Kudryashov, Floris van Doorn -/ import Mathlib.Data.SProd import Mathlib.Data.Subtype import Mathlib.Order.Notation import Mathlib.Util.CompileInductive /-! # Basic definitions about sets In this file we define various operations on sets. We also provide basic lemmas needed to unfold the definitions. More advanced theorems about these definitions are located in other files in `Mathlib/Data/Set`. ## Main definitions - complement of a set and set difference; - `Set.Elem`: coercion of a set to a type; it is reducibly equal to `{x // x ∈ s}`; - `Set.preimage f s`, a.k.a. `f ⁻¹' s`: preimage of a set; - `Set.range f`: the range of a function; it is more general than `f '' univ` because it allows functions from `Sort*`; - `s ×ˢ t`: product of `s : Set α` and `t : Set β` as a set in `α × β`; - `Set.diagonal`: the diagonal in `α × α`; - `Set.offDiag s`: the part of `s ×ˢ s` that is off the diagonal; - `Set.pi`: indexed product of a family of sets `∀ i, Set (α i)`, as a set in `∀ i, α i`; - `Set.EqOn f g s`: the predicate saying that two functions are equal on a set; - `Set.MapsTo f s t`: the predicate syaing that `f` sends all points of `s` to `t; - `Set.MapsTo.restrict`: restrict `f : α → β` to `f' : s → t` provided that `Set.MapsTo f s t`; - `Set.restrictPreimage`: restrict `f : α → β` to `f' : (f ⁻¹' t) → t`; - `Set.InjOn`: the predicate saying that `f` is injective on a set; - `Set.SurjOn f s t`: the prediate saying that `t ⊆ f '' s`; - `Set.BijOn f s t`: the predicate saying that `f` is injective on `s` and `f '' s = t`; - `Set.graphOn`: the graph of a function on a set; - `Set.LeftInvOn`, `Set.RightInvOn`, `Set.InvOn`: the predicates saying that `f'` is a left, right or two-sided inverse of `f` on `s`, `t`, or both; - `Set.image2`: the image of a pair of sets under a binary operation, mostly useful to define pointwise algebraic operations on sets; - `Set.seq`: monadic `seq` operation on sets; we don't use monadic notation to ensure support for maps between different universes; ## Notations - `f '' s`: image of a set; - `f ⁻¹' s`: preimage of a set; - `s ×ˢ t`: the product of sets; - `s ∪ t`: the union of two sets; - `s ∩ t`: the intersection of two sets; - `sᶜ`: the complement of a set; - `s \ t`: the difference of two sets. ## Keywords set, image, preimage -/ -- https://github.com/leanprover/lean4/issues/2096 compile_def% Union.union compile_def% Inter.inter compile_def% SDiff.sdiff compile_def% HasCompl.compl compile_def% EmptyCollection.emptyCollection compile_def% Insert.insert compile_def% Singleton.singleton attribute [ext] Set.ext universe u v w namespace Set variable {α : Type u} {β : Type v} {γ : Type w} @[simp, mfld_simps] theorem mem_setOf_eq {x : α} {p : α → Prop} : (x ∈ {y | p y}) = p x := rfl @[simp, mfld_simps] theorem mem_univ (x : α) : x ∈ @univ α := trivial instance : HasCompl (Set α) := ⟨fun s ↦ {x | x ∉ s}⟩ @[simp] theorem mem_compl_iff (s : Set α) (x : α) : x ∈ sᶜ ↔ x ∉ s := Iff.rfl theorem diff_eq (s t : Set α) : s \ t = s ∩ tᶜ := rfl @[simp] theorem mem_diff {s t : Set α} (x : α) : x ∈ s \ t ↔ x ∈ s ∧ x ∉ t := Iff.rfl theorem mem_diff_of_mem {s t : Set α} {x : α} (h1 : x ∈ s) (h2 : x ∉ t) : x ∈ s \ t := ⟨h1, h2⟩ -- Porting note: I've introduced this abbreviation, with the `@[coe]` attribute, -- so that `norm_cast` has something to index on. -- It is currently an abbreviation so that instance coming from `Subtype` are available. -- If you're interested in making it a `def`, as it probably should be, -- you'll then need to create additional instances (and possibly prove lemmas about them). -- The first error should appear below at `monotoneOn_iff_monotone`. /-- Given the set `s`, `Elem s` is the `Type` of element of `s`. -/ @[coe, reducible] def Elem (s : Set α) : Type u := {x // x ∈ s} /-- Coercion from a set to the corresponding subtype. -/ instance : CoeSort (Set α) (Type u) := ⟨Elem⟩ /-- The preimage of `s : Set β` by `f : α → β`, written `f ⁻¹' s`, is the set of `x : α` such that `f x ∈ s`. -/ def preimage (f : α → β) (s : Set β) : Set α := {x | f x ∈ s} /-- `f ⁻¹' t` denotes the preimage of `t : Set β` under the function `f : α → β`. -/ infixl:80 " ⁻¹' " => preimage @[simp, mfld_simps] theorem mem_preimage {f : α → β} {s : Set β} {a : α} : a ∈ f ⁻¹' s ↔ f a ∈ s := Iff.rfl /-- `f '' s` denotes the image of `s : Set α` under the function `f : α → β`. -/ infixl:80 " '' " => image @[simp] theorem mem_image (f : α → β) (s : Set α) (y : β) : y ∈ f '' s ↔ ∃ x ∈ s, f x = y := Iff.rfl @[mfld_simps] theorem mem_image_of_mem (f : α → β) {x : α} {a : Set α} (h : x ∈ a) : f x ∈ f '' a := ⟨_, h, rfl⟩ /-- Restriction of `f` to `s` factors through `s.imageFactorization f : s → f '' s`. -/ def imageFactorization (f : α → β) (s : Set α) : s → f '' s := fun p => ⟨f p.1, mem_image_of_mem f p.2⟩ /-- `kernImage f s` is the set of `y` such that `f ⁻¹ y ⊆ s`. -/ def kernImage (f : α → β) (s : Set α) : Set β := {y | ∀ ⦃x⦄, f x = y → x ∈ s} lemma subset_kernImage_iff {s : Set β} {t : Set α} {f : α → β} : s ⊆ kernImage f t ↔ f ⁻¹' s ⊆ t := ⟨fun h _ hx ↦ h hx rfl, fun h _ hx y hy ↦ h (show f y ∈ s from hy.symm ▸ hx)⟩ section Range variable {ι : Sort*} {f : ι → α} /-- Range of a function. This function is more flexible than `f '' univ`, as the image requires that the domain is in Type and not an arbitrary Sort. -/ def range (f : ι → α) : Set α := {x | ∃ y, f y = x} @[simp] theorem mem_range {x : α} : x ∈ range f ↔ ∃ y, f y = x := Iff.rfl @[mfld_simps] theorem mem_range_self (i : ι) : f i ∈ range f := ⟨i, rfl⟩ /-- Any map `f : ι → α` factors through a map `rangeFactorization f : ι → range f`. -/ def rangeFactorization (f : ι → α) : ι → range f := fun i => ⟨f i, mem_range_self i⟩ end Range /-- We can use the axiom of choice to pick a preimage for every element of `range f`. -/ noncomputable def rangeSplitting (f : α → β) : range f → α := fun x => x.2.choose -- This can not be a `@[simp]` lemma because the head of the left hand side is a variable. theorem apply_rangeSplitting (f : α → β) (x : range f) : f (rangeSplitting f x) = x := x.2.choose_spec @[simp] theorem comp_rangeSplitting (f : α → β) : f ∘ rangeSplitting f = Subtype.val := by ext simp only [Function.comp_apply] apply apply_rangeSplitting section Prod /-- The cartesian product `Set.prod s t` is the set of `(a, b)` such that `a ∈ s` and `b ∈ t`. -/ def prod (s : Set α) (t : Set β) : Set (α × β) := {p | p.1 ∈ s ∧ p.2 ∈ t} @[default_instance] instance instSProd : SProd (Set α) (Set β) (Set (α × β)) where sprod := Set.prod theorem prod_eq (s : Set α) (t : Set β) : s ×ˢ t = Prod.fst ⁻¹' s ∩ Prod.snd ⁻¹' t := rfl variable {a : α} {b : β} {s : Set α} {t : Set β} {p : α × β} theorem mem_prod_eq : (p ∈ s ×ˢ t) = (p.1 ∈ s ∧ p.2 ∈ t) := rfl @[simp, mfld_simps] theorem mem_prod : p ∈ s ×ˢ t ↔ p.1 ∈ s ∧ p.2 ∈ t := .rfl @[mfld_simps] theorem prod_mk_mem_set_prod_eq : ((a, b) ∈ s ×ˢ t) = (a ∈ s ∧ b ∈ t) := rfl theorem mk_mem_prod (ha : a ∈ s) (hb : b ∈ t) : (a, b) ∈ s ×ˢ t := ⟨ha, hb⟩ end Prod section Diagonal /-- `diagonal α` is the set of `α × α` consisting of all pairs of the form `(a, a)`. -/ def diagonal (α : Type*) : Set (α × α) := {p | p.1 = p.2} theorem mem_diagonal (x : α) : (x, x) ∈ diagonal α := rfl @[simp] theorem mem_diagonal_iff {x : α × α} : x ∈ diagonal α ↔ x.1 = x.2 := .rfl /-- The off-diagonal of a set `s` is the set of pairs `(a, b)` with `a, b ∈ s` and `a ≠ b`. -/ def offDiag (s : Set α) : Set (α × α) := {x | x.1 ∈ s ∧ x.2 ∈ s ∧ x.1 ≠ x.2} @[simp] theorem mem_offDiag {x : α × α} {s : Set α} : x ∈ s.offDiag ↔ x.1 ∈ s ∧ x.2 ∈ s ∧ x.1 ≠ x.2 := Iff.rfl end Diagonal section Pi variable {ι : Type*} {α : ι → Type*} /-- Given an index set `ι` and a family of sets `t : Π i, Set (α i)`, `pi s t` is the set of dependent functions `f : Πa, π a` such that `f a` belongs to `t a` whenever `a ∈ s`. -/ def pi (s : Set ι) (t : ∀ i, Set (α i)) : Set (∀ i, α i) := {f | ∀ i ∈ s, f i ∈ t i} variable {s : Set ι} {t : ∀ i, Set (α i)} {f : ∀ i, α i} @[simp] theorem mem_pi : f ∈ s.pi t ↔ ∀ i ∈ s, f i ∈ t i := .rfl theorem mem_univ_pi : f ∈ pi univ t ↔ ∀ i, f i ∈ t i := by simp end Pi /-- Two functions `f₁ f₂ : α → β` are equal on `s` if `f₁ x = f₂ x` for all `x ∈ s`. -/ def EqOn (f₁ f₂ : α → β) (s : Set α) : Prop := ∀ ⦃x⦄, x ∈ s → f₁ x = f₂ x /-- `MapsTo f a b` means that the image of `a` is contained in `b`. -/ def MapsTo (f : α → β) (s : Set α) (t : Set β) : Prop := ∀ ⦃x⦄, x ∈ s → f x ∈ t theorem mapsTo_image (f : α → β) (s : Set α) : MapsTo f s (f '' s) := fun _ ↦ mem_image_of_mem f theorem mapsTo_preimage (f : α → β) (t : Set β) : MapsTo f (f ⁻¹' t) t := fun _ ↦ id /-- Given a map `f` sending `s : Set α` into `t : Set β`, restrict domain of `f` to `s` and the codomain to `t`. Same as `Subtype.map`. -/ def MapsTo.restrict (f : α → β) (s : Set α) (t : Set β) (h : MapsTo f s t) : s → t := Subtype.map f h /-- The restriction of a function onto the preimage of a set. -/ @[simps!] def restrictPreimage (t : Set β) (f : α → β) : f ⁻¹' t → t := (Set.mapsTo_preimage f t).restrict _ _ _ /-- `f` is injective on `a` if the restriction of `f` to `a` is injective. -/ def InjOn (f : α → β) (s : Set α) : Prop := ∀ ⦃x₁ : α⦄, x₁ ∈ s → ∀ ⦃x₂ : α⦄, x₂ ∈ s → f x₁ = f x₂ → x₁ = x₂ /-- The graph of a function `f : α → β` on a set `s`. -/ def graphOn (f : α → β) (s : Set α) : Set (α × β) := (fun x ↦ (x, f x)) '' s /-- `f` is surjective from `a` to `b` if `b` is contained in the image of `a`. -/ def SurjOn (f : α → β) (s : Set α) (t : Set β) : Prop := t ⊆ f '' s /-- `f` is bijective from `s` to `t` if `f` is injective on `s` and `f '' s = t`. -/ def BijOn (f : α → β) (s : Set α) (t : Set β) : Prop := MapsTo f s t ∧ InjOn f s ∧ SurjOn f s t /-- `g` is a left inverse to `f` on `a` means that `g (f x) = x` for all `x ∈ a`. -/ def LeftInvOn (f' : β → α) (f : α → β) (s : Set α) : Prop := ∀ ⦃x⦄, x ∈ s → f' (f x) = x /-- `g` is a right inverse to `f` on `b` if `f (g x) = x` for all `x ∈ b`. -/ abbrev RightInvOn (f' : β → α) (f : α → β) (t : Set β) : Prop := LeftInvOn f f' t /-- `g` is an inverse to `f` viewed as a map from `a` to `b` -/ def InvOn (g : β → α) (f : α → β) (s : Set α) (t : Set β) : Prop := LeftInvOn g f s ∧ RightInvOn g f t section image2 /-- The image of a binary function `f : α → β → γ` as a function `Set α → Set β → Set γ`. Mathematically this should be thought of as the image of the corresponding function `α × β → γ`. -/ def image2 (f : α → β → γ) (s : Set α) (t : Set β) : Set γ := {c | ∃ a ∈ s, ∃ b ∈ t, f a b = c} variable {f : α → β → γ} {s : Set α} {t : Set β} {a : α} {b : β} {c : γ} @[simp] theorem mem_image2 : c ∈ image2 f s t ↔ ∃ a ∈ s, ∃ b ∈ t, f a b = c := .rfl theorem mem_image2_of_mem (ha : a ∈ s) (hb : b ∈ t) : f a b ∈ image2 f s t := ⟨a, ha, b, hb, rfl⟩ end image2 /-- Given a set `s` of functions `α → β` and `t : Set α`, `seq s t` is the union of `f '' t` over all `f ∈ s`. -/ def seq (s : Set (α → β)) (t : Set α) : Set β := image2 (fun f ↦ f) s t @[simp] theorem mem_seq_iff {s : Set (α → β)} {t : Set α} {b : β} : b ∈ seq s t ↔ ∃ f ∈ s, ∃ a ∈ t, (f : α → β) a = b := Iff.rfl lemma seq_eq_image2 (s : Set (α → β)) (t : Set α) : seq s t = image2 (fun f a ↦ f a) s t := rfl end Set
Data\Set\Enumerate.lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import Mathlib.Algebra.Group.Basic import Mathlib.Algebra.Group.Nat import Mathlib.Data.Set.Basic import Mathlib.Tactic.Common /-! # Set enumeration This file allows enumeration of sets given a choice function. The definition does not assume `sel` actually is a choice function, i.e. `sel s ∈ s` and `sel s = none ↔ s = ∅`. These assumptions are added to the lemmas needing them. -/ noncomputable section open Function namespace Set section Enumerate /- Porting note: The original used parameters -/ variable {α : Type*} (sel : Set α → Option α) /-- Given a choice function `sel`, enumerates the elements of a set in the order `a 0 = sel s`, `a 1 = sel (s \ {a 0})`, `a 2 = sel (s \ {a 0, a 1})`, ... and stops when `sel (s \ {a 0, ..., a n}) = none`. Note that we don't require `sel` to be a choice function. -/ def enumerate : Set α → ℕ → Option α | s, 0 => sel s | s, n + 1 => do let a ← sel s enumerate (s \ {a}) n theorem enumerate_eq_none_of_sel {s : Set α} (h : sel s = none) : ∀ {n}, enumerate sel s n = none | 0 => by simp [h, enumerate] | n + 1 => by simp [h, enumerate] theorem enumerate_eq_none : ∀ {s n₁ n₂}, enumerate sel s n₁ = none → n₁ ≤ n₂ → enumerate sel s n₂ = none | s, 0, m => fun h _ ↦ enumerate_eq_none_of_sel sel h | s, n + 1, m => fun h hm ↦ by cases hs : sel s · exact enumerate_eq_none_of_sel sel hs · cases m with | zero => contradiction | succ m' => simp? [hs, enumerate] at h ⊢ says simp only [enumerate, hs, Option.bind_eq_bind, Option.some_bind] at h ⊢ have hm : n ≤ m' := Nat.le_of_succ_le_succ hm exact enumerate_eq_none h hm theorem enumerate_mem (h_sel : ∀ s a, sel s = some a → a ∈ s) : ∀ {s n a}, enumerate sel s n = some a → a ∈ s | s, 0, a => h_sel s a | s, n + 1, a => by cases h : sel s with | none => simp [enumerate_eq_none_of_sel, h] | some a' => simp only [enumerate, h, Nat.add_eq, add_zero] exact fun h' : enumerate sel (s \ {a'}) n = some a ↦ have : a ∈ s \ {a'} := enumerate_mem h_sel h' this.left theorem enumerate_inj {n₁ n₂ : ℕ} {a : α} {s : Set α} (h_sel : ∀ s a, sel s = some a → a ∈ s) (h₁ : enumerate sel s n₁ = some a) (h₂ : enumerate sel s n₂ = some a) : n₁ = n₂ := by /- Porting note: The `rcase, on_goal, all_goals` has been used instead of the not-yet-ported `wlog` -/ rcases le_total n₁ n₂ with (hn|hn) on_goal 2 => swap_var n₁ ↔ n₂, h₁ ↔ h₂ all_goals rcases Nat.le.dest hn with ⟨m, rfl⟩ clear hn induction n₁ generalizing s with | zero => cases m with | zero => rfl | succ m => have h' : enumerate sel (s \ {a}) m = some a := by simp_all only [enumerate, Nat.zero_eq, Nat.add_eq, zero_add]; exact h₂ have : a ∈ s \ {a} := enumerate_mem sel h_sel h' simp_all [Set.mem_diff_singleton] | succ k ih => cases h : sel s with /- Porting note: The original covered both goals with just `simp_all <;> tauto` -/ | none => simp_all only [add_comm, self_eq_add_left, Nat.add_succ, enumerate_eq_none_of_sel _ h] | some => simp_all only [add_comm, self_eq_add_left, enumerate, Option.some.injEq, Nat.add_succ, Nat.succ.injEq] exact ih h₁ h₂ end Enumerate end Set
Data\Set\Equitable.lean
/- Copyright (c) 2021 Yaël Dillies, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Bhavik Mehta -/ import Mathlib.Data.Set.Subsingleton import Mathlib.Algebra.Order.BigOperators.Group.Finset import Mathlib.Algebra.Group.Nat import Mathlib.Data.Set.Basic /-! # Equitable functions This file defines equitable functions. A function `f` is equitable on a set `s` if `f a₁ ≤ f a₂ + 1` for all `a₁, a₂ ∈ s`. This is mostly useful when the codomain of `f` is `ℕ` or `ℤ` (or more generally a successor order). ## TODO `ℕ` can be replaced by any `SuccOrder` + `ConditionallyCompleteMonoid`, but we don't have the latter yet. -/ variable {α β : Type*} namespace Set /-- A set is equitable if no element value is more than one bigger than another. -/ def EquitableOn [LE β] [Add β] [One β] (s : Set α) (f : α → β) : Prop := ∀ ⦃a₁ a₂⦄, a₁ ∈ s → a₂ ∈ s → f a₁ ≤ f a₂ + 1 @[simp] theorem equitableOn_empty [LE β] [Add β] [One β] (f : α → β) : EquitableOn ∅ f := fun a _ ha => (Set.not_mem_empty a ha).elim theorem equitableOn_iff_exists_le_le_add_one {s : Set α} {f : α → ℕ} : s.EquitableOn f ↔ ∃ b, ∀ a ∈ s, b ≤ f a ∧ f a ≤ b + 1 := by refine ⟨?_, fun ⟨b, hb⟩ x y hx hy => (hb x hx).2.trans (add_le_add_right (hb y hy).1 _)⟩ obtain rfl | ⟨x, hx⟩ := s.eq_empty_or_nonempty · simp intro hs by_cases h : ∀ y ∈ s, f x ≤ f y · exact ⟨f x, fun y hy => ⟨h _ hy, hs hy hx⟩⟩ push_neg at h obtain ⟨w, hw, hwx⟩ := h refine ⟨f w, fun y hy => ⟨Nat.le_of_succ_le_succ ?_, hs hy hw⟩⟩ rw [(Nat.succ_le_of_lt hwx).antisymm (hs hx hw)] exact hs hx hy theorem equitableOn_iff_exists_image_subset_icc {s : Set α} {f : α → ℕ} : s.EquitableOn f ↔ ∃ b, f '' s ⊆ Icc b (b + 1) := by simpa only [image_subset_iff] using equitableOn_iff_exists_le_le_add_one theorem equitableOn_iff_exists_eq_eq_add_one {s : Set α} {f : α → ℕ} : s.EquitableOn f ↔ ∃ b, ∀ a ∈ s, f a = b ∨ f a = b + 1 := by simp_rw [equitableOn_iff_exists_le_le_add_one, Nat.le_and_le_add_one_iff] section LinearOrder variable [LinearOrder β] [Add β] [One β] {s : Set α} {f : α → β} @[simp] lemma not_equitableOn : ¬s.EquitableOn f ↔ ∃ a ∈ s, ∃ b ∈ s, f b + 1 < f a := by simp [EquitableOn] end LinearOrder section OrderedSemiring variable [OrderedSemiring β] theorem Subsingleton.equitableOn {s : Set α} (hs : s.Subsingleton) (f : α → β) : s.EquitableOn f := fun i j hi hj => by rw [hs hi hj] exact le_add_of_nonneg_right zero_le_one theorem equitableOn_singleton (a : α) (f : α → β) : Set.EquitableOn {a} f := Set.subsingleton_singleton.equitableOn f end OrderedSemiring end Set open Set namespace Finset variable {s : Finset α} {f : α → ℕ} {a : α} theorem equitableOn_iff_le_le_add_one : EquitableOn (s : Set α) f ↔ ∀ a ∈ s, (∑ i ∈ s, f i) / s.card ≤ f a ∧ f a ≤ (∑ i ∈ s, f i) / s.card + 1 := by rw [Set.equitableOn_iff_exists_le_le_add_one] refine ⟨?_, fun h => ⟨_, h⟩⟩ rintro ⟨b, hb⟩ by_cases h : ∀ a ∈ s, f a = b + 1 · intro a ha rw [h _ ha, sum_const_nat h, Nat.mul_div_cancel_left _ (card_pos.2 ⟨a, ha⟩)] exact ⟨le_rfl, Nat.le_succ _⟩ push_neg at h obtain ⟨x, hx₁, hx₂⟩ := h suffices h : b = (∑ i ∈ s, f i) / s.card by simp_rw [← h] apply hb symm refine Nat.div_eq_of_lt_le (le_trans (by simp [mul_comm]) (sum_le_sum fun a ha => (hb a ha).1)) ((sum_lt_sum (fun a ha => (hb a ha).2) ⟨_, hx₁, (hb _ hx₁).2.lt_of_ne hx₂⟩).trans_le ?_) rw [mul_comm, sum_const_nat] exact fun _ _ => rfl theorem EquitableOn.le (h : EquitableOn (s : Set α) f) (ha : a ∈ s) : (∑ i ∈ s, f i) / s.card ≤ f a := (equitableOn_iff_le_le_add_one.1 h a ha).1 theorem EquitableOn.le_add_one (h : EquitableOn (s : Set α) f) (ha : a ∈ s) : f a ≤ (∑ i ∈ s, f i) / s.card + 1 := (equitableOn_iff_le_le_add_one.1 h a ha).2 theorem equitableOn_iff : EquitableOn (s : Set α) f ↔ ∀ a ∈ s, f a = (∑ i ∈ s, f i) / s.card ∨ f a = (∑ i ∈ s, f i) / s.card + 1 := by simp_rw [equitableOn_iff_le_le_add_one, Nat.le_and_le_add_one_iff] end Finset
Data\Set\Finite.lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Kyle Miller -/ import Mathlib.Data.Finset.Basic import Mathlib.Data.Finite.Basic import Mathlib.Data.Set.Functor import Mathlib.Data.Set.Lattice /-! # Finite sets This file defines predicates for finite and infinite sets and provides `Fintype` instances for many set constructions. It also proves basic facts about finite sets and gives ways to manipulate `Set.Finite` expressions. ## Main definitions * `Set.Finite : Set α → Prop` * `Set.Infinite : Set α → Prop` * `Set.toFinite` to prove `Set.Finite` for a `Set` from a `Finite` instance. * `Set.Finite.toFinset` to noncomputably produce a `Finset` from a `Set.Finite` proof. (See `Set.toFinset` for a computable version.) ## Implementation A finite set is defined to be a set whose coercion to a type has a `Finite` instance. There are two components to finiteness constructions. The first is `Fintype` instances for each construction. This gives a way to actually compute a `Finset` that represents the set, and these may be accessed using `set.toFinset`. This gets the `Finset` in the correct form, since otherwise `Finset.univ : Finset s` is a `Finset` for the subtype for `s`. The second component is "constructors" for `Set.Finite` that give proofs that `Fintype` instances exist classically given other `Set.Finite` proofs. Unlike the `Fintype` instances, these *do not* use any decidability instances since they do not compute anything. ## Tags finite sets -/ assert_not_exists OrderedRing assert_not_exists MonoidWithZero open Set Function universe u v w x variable {α : Type u} {β : Type v} {ι : Sort w} {γ : Type x} namespace Set /-- A set is finite if the corresponding `Subtype` is finite, i.e., if there exists a natural `n : ℕ` and an equivalence `s ≃ Fin n`. -/ protected def Finite (s : Set α) : Prop := Finite s -- The `protected` attribute does not take effect within the same namespace block. end Set namespace Set theorem finite_def {s : Set α} : s.Finite ↔ Nonempty (Fintype s) := finite_iff_nonempty_fintype s protected alias ⟨Finite.nonempty_fintype, _⟩ := finite_def theorem finite_coe_iff {s : Set α} : Finite s ↔ s.Finite := .rfl /-- Constructor for `Set.Finite` using a `Finite` instance. -/ theorem toFinite (s : Set α) [Finite s] : s.Finite := ‹_› /-- Construct a `Finite` instance for a `Set` from a `Finset` with the same elements. -/ protected theorem Finite.ofFinset {p : Set α} (s : Finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) : p.Finite := have := Fintype.ofFinset s H; p.toFinite /-- Projection of `Set.Finite` to its `Finite` instance. This is intended to be used with dot notation. See also `Set.Finite.Fintype` and `Set.Finite.nonempty_fintype`. -/ protected theorem Finite.to_subtype {s : Set α} (h : s.Finite) : Finite s := h /-- A finite set coerced to a type is a `Fintype`. This is the `Fintype` projection for a `Set.Finite`. Note that because `Finite` isn't a typeclass, this definition will not fire if it is made into an instance -/ protected noncomputable def Finite.fintype {s : Set α} (h : s.Finite) : Fintype s := h.nonempty_fintype.some /-- Using choice, get the `Finset` that represents this `Set`. -/ protected noncomputable def Finite.toFinset {s : Set α} (h : s.Finite) : Finset α := @Set.toFinset _ _ h.fintype theorem Finite.toFinset_eq_toFinset {s : Set α} [Fintype s] (h : s.Finite) : h.toFinset = s.toFinset := by -- Porting note: was `rw [Finite.toFinset]; congr` -- in Lean 4, a goal is left after `congr` have : h.fintype = ‹_› := Subsingleton.elim _ _ rw [Finite.toFinset, this] @[simp] theorem toFinite_toFinset (s : Set α) [Fintype s] : s.toFinite.toFinset = s.toFinset := s.toFinite.toFinset_eq_toFinset theorem Finite.exists_finset {s : Set α} (h : s.Finite) : ∃ s' : Finset α, ∀ a : α, a ∈ s' ↔ a ∈ s := by cases h.nonempty_fintype exact ⟨s.toFinset, fun _ => mem_toFinset⟩ theorem Finite.exists_finset_coe {s : Set α} (h : s.Finite) : ∃ s' : Finset α, ↑s' = s := by cases h.nonempty_fintype exact ⟨s.toFinset, s.coe_toFinset⟩ /-- Finite sets can be lifted to finsets. -/ instance : CanLift (Set α) (Finset α) (↑) Set.Finite where prf _ hs := hs.exists_finset_coe /-- A set is infinite if it is not finite. This is protected so that it does not conflict with global `Infinite`. -/ protected def Infinite (s : Set α) : Prop := ¬s.Finite @[simp] theorem not_infinite {s : Set α} : ¬s.Infinite ↔ s.Finite := not_not alias ⟨_, Finite.not_infinite⟩ := not_infinite attribute [simp] Finite.not_infinite /-- See also `finite_or_infinite`, `fintypeOrInfinite`. -/ protected theorem finite_or_infinite (s : Set α) : s.Finite ∨ s.Infinite := em _ protected theorem infinite_or_finite (s : Set α) : s.Infinite ∨ s.Finite := em' _ /-! ### Basic properties of `Set.Finite.toFinset` -/ namespace Finite variable {s t : Set α} {a : α} (hs : s.Finite) {ht : t.Finite} @[simp] protected theorem mem_toFinset : a ∈ hs.toFinset ↔ a ∈ s := @mem_toFinset _ _ hs.fintype _ @[simp] protected theorem coe_toFinset : (hs.toFinset : Set α) = s := @coe_toFinset _ _ hs.fintype @[simp] protected theorem toFinset_nonempty : hs.toFinset.Nonempty ↔ s.Nonempty := by rw [← Finset.coe_nonempty, Finite.coe_toFinset] /-- Note that this is an equality of types not holding definitionally. Use wisely. -/ theorem coeSort_toFinset : ↥hs.toFinset = ↥s := by rw [← Finset.coe_sort_coe _, hs.coe_toFinset] /-- The identity map, bundled as an equivalence between the subtypes of `s : Set α` and of `h.toFinset : Finset α`, where `h` is a proof of finiteness of `s`. -/ @[simps!] def subtypeEquivToFinset : {x // x ∈ s} ≃ {x // x ∈ hs.toFinset} := (Equiv.refl α).subtypeEquiv fun _ ↦ hs.mem_toFinset.symm variable {hs} @[simp] protected theorem toFinset_inj : hs.toFinset = ht.toFinset ↔ s = t := @toFinset_inj _ _ _ hs.fintype ht.fintype @[simp] theorem toFinset_subset {t : Finset α} : hs.toFinset ⊆ t ↔ s ⊆ t := by rw [← Finset.coe_subset, Finite.coe_toFinset] @[simp] theorem toFinset_ssubset {t : Finset α} : hs.toFinset ⊂ t ↔ s ⊂ t := by rw [← Finset.coe_ssubset, Finite.coe_toFinset] @[simp] theorem subset_toFinset {s : Finset α} : s ⊆ ht.toFinset ↔ ↑s ⊆ t := by rw [← Finset.coe_subset, Finite.coe_toFinset] @[simp] theorem ssubset_toFinset {s : Finset α} : s ⊂ ht.toFinset ↔ ↑s ⊂ t := by rw [← Finset.coe_ssubset, Finite.coe_toFinset] @[mono] protected theorem toFinset_subset_toFinset : hs.toFinset ⊆ ht.toFinset ↔ s ⊆ t := by simp only [← Finset.coe_subset, Finite.coe_toFinset] @[mono] protected theorem toFinset_ssubset_toFinset : hs.toFinset ⊂ ht.toFinset ↔ s ⊂ t := by simp only [← Finset.coe_ssubset, Finite.coe_toFinset] alias ⟨_, toFinset_mono⟩ := Finite.toFinset_subset_toFinset alias ⟨_, toFinset_strictMono⟩ := Finite.toFinset_ssubset_toFinset -- Porting note: attribute [protected] doesn't work -- attribute [protected] toFinset_mono toFinset_strictMono -- Porting note: `simp` can simplify LHS but then it simplifies something -- in the generated `Fintype {x | p x}` instance and fails to apply `Set.toFinset_setOf` @[simp high] protected theorem toFinset_setOf [Fintype α] (p : α → Prop) [DecidablePred p] (h : { x | p x }.Finite) : h.toFinset = Finset.univ.filter p := by ext -- Porting note: `simp` doesn't use the `simp` lemma `Set.toFinset_setOf` without the `_` simp [Set.toFinset_setOf _] @[simp] nonrec theorem disjoint_toFinset {hs : s.Finite} {ht : t.Finite} : Disjoint hs.toFinset ht.toFinset ↔ Disjoint s t := @disjoint_toFinset _ _ _ hs.fintype ht.fintype protected theorem toFinset_inter [DecidableEq α] (hs : s.Finite) (ht : t.Finite) (h : (s ∩ t).Finite) : h.toFinset = hs.toFinset ∩ ht.toFinset := by ext simp protected theorem toFinset_union [DecidableEq α] (hs : s.Finite) (ht : t.Finite) (h : (s ∪ t).Finite) : h.toFinset = hs.toFinset ∪ ht.toFinset := by ext simp protected theorem toFinset_diff [DecidableEq α] (hs : s.Finite) (ht : t.Finite) (h : (s \ t).Finite) : h.toFinset = hs.toFinset \ ht.toFinset := by ext simp open scoped symmDiff in protected theorem toFinset_symmDiff [DecidableEq α] (hs : s.Finite) (ht : t.Finite) (h : (s ∆ t).Finite) : h.toFinset = hs.toFinset ∆ ht.toFinset := by ext simp [mem_symmDiff, Finset.mem_symmDiff] protected theorem toFinset_compl [DecidableEq α] [Fintype α] (hs : s.Finite) (h : sᶜ.Finite) : h.toFinset = hs.toFinsetᶜ := by ext simp protected theorem toFinset_univ [Fintype α] (h : (Set.univ : Set α).Finite) : h.toFinset = Finset.univ := by simp @[simp] protected theorem toFinset_eq_empty {h : s.Finite} : h.toFinset = ∅ ↔ s = ∅ := @toFinset_eq_empty _ _ h.fintype protected theorem toFinset_empty (h : (∅ : Set α).Finite) : h.toFinset = ∅ := by simp @[simp] protected theorem toFinset_eq_univ [Fintype α] {h : s.Finite} : h.toFinset = Finset.univ ↔ s = univ := @toFinset_eq_univ _ _ _ h.fintype protected theorem toFinset_image [DecidableEq β] (f : α → β) (hs : s.Finite) (h : (f '' s).Finite) : h.toFinset = hs.toFinset.image f := by ext simp -- Porting note (#10618): now `simp` can prove it but it needs the `fintypeRange` instance -- from the next section protected theorem toFinset_range [DecidableEq α] [Fintype β] (f : β → α) (h : (range f).Finite) : h.toFinset = Finset.univ.image f := by ext simp end Finite /-! ### Fintype instances Every instance here should have a corresponding `Set.Finite` constructor in the next section. -/ section FintypeInstances instance fintypeUniv [Fintype α] : Fintype (@univ α) := Fintype.ofEquiv α (Equiv.Set.univ α).symm /-- If `(Set.univ : Set α)` is finite then `α` is a finite type. -/ noncomputable def fintypeOfFiniteUniv (H : (univ (α := α)).Finite) : Fintype α := @Fintype.ofEquiv _ (univ : Set α) H.fintype (Equiv.Set.univ _) instance fintypeUnion [DecidableEq α] (s t : Set α) [Fintype s] [Fintype t] : Fintype (s ∪ t : Set α) := Fintype.ofFinset (s.toFinset ∪ t.toFinset) <| by simp instance fintypeSep (s : Set α) (p : α → Prop) [Fintype s] [DecidablePred p] : Fintype ({ a ∈ s | p a } : Set α) := Fintype.ofFinset (s.toFinset.filter p) <| by simp instance fintypeInter (s t : Set α) [DecidableEq α] [Fintype s] [Fintype t] : Fintype (s ∩ t : Set α) := Fintype.ofFinset (s.toFinset ∩ t.toFinset) <| by simp /-- A `Fintype` instance for set intersection where the left set has a `Fintype` instance. -/ instance fintypeInterOfLeft (s t : Set α) [Fintype s] [DecidablePred (· ∈ t)] : Fintype (s ∩ t : Set α) := Fintype.ofFinset (s.toFinset.filter (· ∈ t)) <| by simp /-- A `Fintype` instance for set intersection where the right set has a `Fintype` instance. -/ instance fintypeInterOfRight (s t : Set α) [Fintype t] [DecidablePred (· ∈ s)] : Fintype (s ∩ t : Set α) := Fintype.ofFinset (t.toFinset.filter (· ∈ s)) <| by simp [and_comm] /-- A `Fintype` structure on a set defines a `Fintype` structure on its subset. -/ def fintypeSubset (s : Set α) {t : Set α} [Fintype s] [DecidablePred (· ∈ t)] (h : t ⊆ s) : Fintype t := by rw [← inter_eq_self_of_subset_right h] apply Set.fintypeInterOfLeft instance fintypeDiff [DecidableEq α] (s t : Set α) [Fintype s] [Fintype t] : Fintype (s \ t : Set α) := Fintype.ofFinset (s.toFinset \ t.toFinset) <| by simp instance fintypeDiffLeft (s t : Set α) [Fintype s] [DecidablePred (· ∈ t)] : Fintype (s \ t : Set α) := Set.fintypeSep s (· ∈ tᶜ) instance fintypeiUnion [DecidableEq α] [Fintype (PLift ι)] (f : ι → Set α) [∀ i, Fintype (f i)] : Fintype (⋃ i, f i) := Fintype.ofFinset (Finset.univ.biUnion fun i : PLift ι => (f i.down).toFinset) <| by simp instance fintypesUnion [DecidableEq α] {s : Set (Set α)} [Fintype s] [H : ∀ t : s, Fintype (t : Set α)] : Fintype (⋃₀ s) := by rw [sUnion_eq_iUnion] exact @Set.fintypeiUnion _ _ _ _ _ H /-- A union of sets with `Fintype` structure over a set with `Fintype` structure has a `Fintype` structure. -/ def fintypeBiUnion [DecidableEq α] {ι : Type*} (s : Set ι) [Fintype s] (t : ι → Set α) (H : ∀ i ∈ s, Fintype (t i)) : Fintype (⋃ x ∈ s, t x) := haveI : ∀ i : toFinset s, Fintype (t i) := fun i => H i (mem_toFinset.1 i.2) Fintype.ofFinset (s.toFinset.attach.biUnion fun x => (t x).toFinset) fun x => by simp instance fintypeBiUnion' [DecidableEq α] {ι : Type*} (s : Set ι) [Fintype s] (t : ι → Set α) [∀ i, Fintype (t i)] : Fintype (⋃ x ∈ s, t x) := Fintype.ofFinset (s.toFinset.biUnion fun x => (t x).toFinset) <| by simp lemma toFinset_iUnion [Fintype β] [DecidableEq α] (f : β → Set α) [∀ w, Fintype (f w)] : Set.toFinset (⋃ (x : β), f x) = Finset.biUnion (Finset.univ : Finset β) (fun x => (f x).toFinset) := by ext v simp only [mem_toFinset, mem_iUnion, Finset.mem_biUnion, Finset.mem_univ, true_and] section monad attribute [local instance] Set.monad /-- If `s : Set α` is a set with `Fintype` instance and `f : α → Set β` is a function such that each `f a`, `a ∈ s`, has a `Fintype` structure, then `s >>= f` has a `Fintype` structure. -/ def fintypeBind {α β} [DecidableEq β] (s : Set α) [Fintype s] (f : α → Set β) (H : ∀ a ∈ s, Fintype (f a)) : Fintype (s >>= f) := Set.fintypeBiUnion s f H instance fintypeBind' {α β} [DecidableEq β] (s : Set α) [Fintype s] (f : α → Set β) [∀ a, Fintype (f a)] : Fintype (s >>= f) := Set.fintypeBiUnion' s f end monad instance fintypeEmpty : Fintype (∅ : Set α) := Fintype.ofFinset ∅ <| by simp instance fintypeSingleton (a : α) : Fintype ({a} : Set α) := Fintype.ofFinset {a} <| by simp instance fintypePure : ∀ a : α, Fintype (pure a : Set α) := Set.fintypeSingleton /-- A `Fintype` instance for inserting an element into a `Set` using the corresponding `insert` function on `Finset`. This requires `DecidableEq α`. There is also `Set.fintypeInsert'` when `a ∈ s` is decidable. -/ instance fintypeInsert (a : α) (s : Set α) [DecidableEq α] [Fintype s] : Fintype (insert a s : Set α) := Fintype.ofFinset (insert a s.toFinset) <| by simp /-- A `Fintype` structure on `insert a s` when inserting a new element. -/ def fintypeInsertOfNotMem {a : α} (s : Set α) [Fintype s] (h : a ∉ s) : Fintype (insert a s : Set α) := Fintype.ofFinset ⟨a ::ₘ s.toFinset.1, s.toFinset.nodup.cons (by simp [h])⟩ <| by simp /-- A `Fintype` structure on `insert a s` when inserting a pre-existing element. -/ def fintypeInsertOfMem {a : α} (s : Set α) [Fintype s] (h : a ∈ s) : Fintype (insert a s : Set α) := Fintype.ofFinset s.toFinset <| by simp [h] /-- The `Set.fintypeInsert` instance requires decidable equality, but when `a ∈ s` is decidable for this particular `a` we can still get a `Fintype` instance by using `Set.fintypeInsertOfNotMem` or `Set.fintypeInsertOfMem`. This instance pre-dates `Set.fintypeInsert`, and it is less efficient. When `Set.decidableMemOfFintype` is made a local instance, then this instance would override `Set.fintypeInsert` if not for the fact that its priority has been adjusted. See Note [lower instance priority]. -/ instance (priority := 100) fintypeInsert' (a : α) (s : Set α) [Decidable <| a ∈ s] [Fintype s] : Fintype (insert a s : Set α) := if h : a ∈ s then fintypeInsertOfMem s h else fintypeInsertOfNotMem s h instance fintypeImage [DecidableEq β] (s : Set α) (f : α → β) [Fintype s] : Fintype (f '' s) := Fintype.ofFinset (s.toFinset.image f) <| by simp /-- If a function `f` has a partial inverse and sends a set `s` to a set with `[Fintype]` instance, then `s` has a `Fintype` structure as well. -/ def fintypeOfFintypeImage (s : Set α) {f : α → β} {g} (I : IsPartialInv f g) [Fintype (f '' s)] : Fintype s := Fintype.ofFinset ⟨_, (f '' s).toFinset.2.filterMap g <| injective_of_isPartialInv_right I⟩ fun a => by suffices (∃ b x, f x = b ∧ g b = some a ∧ x ∈ s) ↔ a ∈ s by simpa [exists_and_left.symm, and_comm, and_left_comm, and_assoc] rw [exists_swap] suffices (∃ x, x ∈ s ∧ g (f x) = some a) ↔ a ∈ s by simpa [and_comm, and_left_comm, and_assoc] simp [I _, (injective_of_isPartialInv I).eq_iff] instance fintypeRange [DecidableEq α] (f : ι → α) [Fintype (PLift ι)] : Fintype (range f) := Fintype.ofFinset (Finset.univ.image <| f ∘ PLift.down) <| by simp instance fintypeMap {α β} [DecidableEq β] : ∀ (s : Set α) (f : α → β) [Fintype s], Fintype (f <$> s) := Set.fintypeImage instance fintypeLTNat (n : ℕ) : Fintype { i | i < n } := Fintype.ofFinset (Finset.range n) <| by simp instance fintypeLENat (n : ℕ) : Fintype { i | i ≤ n } := by simpa [Nat.lt_succ_iff] using Set.fintypeLTNat (n + 1) /-- This is not an instance so that it does not conflict with the one in `Mathlib/Order/LocallyFinite.lean`. -/ def Nat.fintypeIio (n : ℕ) : Fintype (Iio n) := Set.fintypeLTNat n instance fintypeProd (s : Set α) (t : Set β) [Fintype s] [Fintype t] : Fintype (s ×ˢ t : Set (α × β)) := Fintype.ofFinset (s.toFinset ×ˢ t.toFinset) <| by simp instance fintypeOffDiag [DecidableEq α] (s : Set α) [Fintype s] : Fintype s.offDiag := Fintype.ofFinset s.toFinset.offDiag <| by simp /-- `image2 f s t` is `Fintype` if `s` and `t` are. -/ instance fintypeImage2 [DecidableEq γ] (f : α → β → γ) (s : Set α) (t : Set β) [hs : Fintype s] [ht : Fintype t] : Fintype (image2 f s t : Set γ) := by rw [← image_prod] apply Set.fintypeImage instance fintypeSeq [DecidableEq β] (f : Set (α → β)) (s : Set α) [Fintype f] [Fintype s] : Fintype (f.seq s) := by rw [seq_def] apply Set.fintypeBiUnion' instance fintypeSeq' {α β : Type u} [DecidableEq β] (f : Set (α → β)) (s : Set α) [Fintype f] [Fintype s] : Fintype (f <*> s) := Set.fintypeSeq f s instance fintypeMemFinset (s : Finset α) : Fintype { a | a ∈ s } := Finset.fintypeCoeSort s end FintypeInstances end Set theorem Equiv.set_finite_iff {s : Set α} {t : Set β} (hst : s ≃ t) : s.Finite ↔ t.Finite := by simp_rw [← Set.finite_coe_iff, hst.finite_iff] /-! ### Finset -/ namespace Finset /-- Gives a `Set.Finite` for the `Finset` coerced to a `Set`. This is a wrapper around `Set.toFinite`. -/ @[simp] theorem finite_toSet (s : Finset α) : (s : Set α).Finite := Set.toFinite _ -- Porting note (#10618): was @[simp], now `simp` can prove it theorem finite_toSet_toFinset (s : Finset α) : s.finite_toSet.toFinset = s := by rw [toFinite_toFinset, toFinset_coe] end Finset namespace Multiset @[simp] theorem finite_toSet (s : Multiset α) : { x | x ∈ s }.Finite := by classical simpa only [← Multiset.mem_toFinset] using s.toFinset.finite_toSet @[simp] theorem finite_toSet_toFinset [DecidableEq α] (s : Multiset α) : s.finite_toSet.toFinset = s.toFinset := by ext x simp end Multiset @[simp] theorem List.finite_toSet (l : List α) : { x | x ∈ l }.Finite := (show Multiset α from ⟦l⟧).finite_toSet /-! ### Finite instances There is seemingly some overlap between the following instances and the `Fintype` instances in `Data.Set.Finite`. While every `Fintype` instance gives a `Finite` instance, those instances that depend on `Fintype` or `Decidable` instances need an additional `Finite` instance to be able to generally apply. Some set instances do not appear here since they are consequences of others, for example `Subtype.Finite` for subsets of a finite type. -/ namespace Finite.Set open scoped Classical example {s : Set α} [Finite α] : Finite s := inferInstance example : Finite (∅ : Set α) := inferInstance example (a : α) : Finite ({a} : Set α) := inferInstance instance finite_union (s t : Set α) [Finite s] [Finite t] : Finite (s ∪ t : Set α) := by cases nonempty_fintype s cases nonempty_fintype t infer_instance instance finite_sep (s : Set α) (p : α → Prop) [Finite s] : Finite ({ a ∈ s | p a } : Set α) := by cases nonempty_fintype s infer_instance protected theorem subset (s : Set α) {t : Set α} [Finite s] (h : t ⊆ s) : Finite t := by rw [← sep_eq_of_subset h] infer_instance instance finite_inter_of_right (s t : Set α) [Finite t] : Finite (s ∩ t : Set α) := Finite.Set.subset t inter_subset_right instance finite_inter_of_left (s t : Set α) [Finite s] : Finite (s ∩ t : Set α) := Finite.Set.subset s inter_subset_left instance finite_diff (s t : Set α) [Finite s] : Finite (s \ t : Set α) := Finite.Set.subset s diff_subset instance finite_range (f : ι → α) [Finite ι] : Finite (range f) := by haveI := Fintype.ofFinite (PLift ι) infer_instance instance finite_iUnion [Finite ι] (f : ι → Set α) [∀ i, Finite (f i)] : Finite (⋃ i, f i) := by rw [iUnion_eq_range_psigma] apply Set.finite_range instance finite_sUnion {s : Set (Set α)} [Finite s] [H : ∀ t : s, Finite (t : Set α)] : Finite (⋃₀ s) := by rw [sUnion_eq_iUnion] exact @Finite.Set.finite_iUnion _ _ _ _ H theorem finite_biUnion {ι : Type*} (s : Set ι) [Finite s] (t : ι → Set α) (H : ∀ i ∈ s, Finite (t i)) : Finite (⋃ x ∈ s, t x) := by rw [biUnion_eq_iUnion] haveI : ∀ i : s, Finite (t i) := fun i => H i i.property infer_instance instance finite_biUnion' {ι : Type*} (s : Set ι) [Finite s] (t : ι → Set α) [∀ i, Finite (t i)] : Finite (⋃ x ∈ s, t x) := finite_biUnion s t fun _ _ => inferInstance /-- Example: `Finite (⋃ (i < n), f i)` where `f : ℕ → Set α` and `[∀ i, Finite (f i)]` (when given instances from `Order.Interval.Finset.Nat`). -/ instance finite_biUnion'' {ι : Type*} (p : ι → Prop) [h : Finite { x | p x }] (t : ι → Set α) [∀ i, Finite (t i)] : Finite (⋃ (x) (_ : p x), t x) := @Finite.Set.finite_biUnion' _ _ (setOf p) h t _ instance finite_iInter {ι : Sort*} [Nonempty ι] (t : ι → Set α) [∀ i, Finite (t i)] : Finite (⋂ i, t i) := Finite.Set.subset (t <| Classical.arbitrary ι) (iInter_subset _ _) instance finite_insert (a : α) (s : Set α) [Finite s] : Finite (insert a s : Set α) := Finite.Set.finite_union {a} s instance finite_image (s : Set α) (f : α → β) [Finite s] : Finite (f '' s) := by cases nonempty_fintype s infer_instance instance finite_replacement [Finite α] (f : α → β) : Finite {f x | x : α} := Finite.Set.finite_range f instance finite_prod (s : Set α) (t : Set β) [Finite s] [Finite t] : Finite (s ×ˢ t : Set (α × β)) := Finite.of_equiv _ (Equiv.Set.prod s t).symm instance finite_image2 (f : α → β → γ) (s : Set α) (t : Set β) [Finite s] [Finite t] : Finite (image2 f s t : Set γ) := by rw [← image_prod] infer_instance instance finite_seq (f : Set (α → β)) (s : Set α) [Finite f] [Finite s] : Finite (f.seq s) := by rw [seq_def] infer_instance end Finite.Set namespace Set /-! ### Constructors for `Set.Finite` Every constructor here should have a corresponding `Fintype` instance in the previous section (or in the `Fintype` module). The implementation of these constructors ideally should be no more than `Set.toFinite`, after possibly setting up some `Fintype` and classical `Decidable` instances. -/ section SetFiniteConstructors @[nontriviality] theorem Finite.of_subsingleton [Subsingleton α] (s : Set α) : s.Finite := s.toFinite theorem finite_univ [Finite α] : (@univ α).Finite := Set.toFinite _ theorem finite_univ_iff : (@univ α).Finite ↔ Finite α := (Equiv.Set.univ α).finite_iff alias ⟨_root_.Finite.of_finite_univ, _⟩ := finite_univ_iff theorem Finite.subset {s : Set α} (hs : s.Finite) {t : Set α} (ht : t ⊆ s) : t.Finite := by have := hs.to_subtype exact Finite.Set.subset _ ht theorem Finite.union {s t : Set α} (hs : s.Finite) (ht : t.Finite) : (s ∪ t).Finite := by rw [Set.Finite] at hs ht apply toFinite theorem Finite.finite_of_compl {s : Set α} (hs : s.Finite) (hsc : sᶜ.Finite) : Finite α := by rw [← finite_univ_iff, ← union_compl_self s] exact hs.union hsc theorem Finite.sup {s t : Set α} : s.Finite → t.Finite → (s ⊔ t).Finite := Finite.union theorem Finite.sep {s : Set α} (hs : s.Finite) (p : α → Prop) : { a ∈ s | p a }.Finite := hs.subset <| sep_subset _ _ theorem Finite.inter_of_left {s : Set α} (hs : s.Finite) (t : Set α) : (s ∩ t).Finite := hs.subset inter_subset_left theorem Finite.inter_of_right {s : Set α} (hs : s.Finite) (t : Set α) : (t ∩ s).Finite := hs.subset inter_subset_right theorem Finite.inf_of_left {s : Set α} (h : s.Finite) (t : Set α) : (s ⊓ t).Finite := h.inter_of_left t theorem Finite.inf_of_right {s : Set α} (h : s.Finite) (t : Set α) : (t ⊓ s).Finite := h.inter_of_right t protected lemma Infinite.mono {s t : Set α} (h : s ⊆ t) : s.Infinite → t.Infinite := mt fun ht ↦ ht.subset h theorem Finite.diff {s : Set α} (hs : s.Finite) (t : Set α) : (s \ t).Finite := hs.subset diff_subset theorem Finite.of_diff {s t : Set α} (hd : (s \ t).Finite) (ht : t.Finite) : s.Finite := (hd.union ht).subset <| subset_diff_union _ _ theorem finite_iUnion [Finite ι] {f : ι → Set α} (H : ∀ i, (f i).Finite) : (⋃ i, f i).Finite := haveI := fun i => (H i).to_subtype toFinite _ /-- Dependent version of `Finite.biUnion`. -/ theorem Finite.biUnion' {ι} {s : Set ι} (hs : s.Finite) {t : ∀ i ∈ s, Set α} (ht : ∀ i (hi : i ∈ s), (t i hi).Finite) : (⋃ i ∈ s, t i ‹_›).Finite := by have := hs.to_subtype rw [biUnion_eq_iUnion] apply finite_iUnion fun i : s => ht i.1 i.2 theorem Finite.biUnion {ι} {s : Set ι} (hs : s.Finite) {t : ι → Set α} (ht : ∀ i ∈ s, (t i).Finite) : (⋃ i ∈ s, t i).Finite := hs.biUnion' ht theorem Finite.sUnion {s : Set (Set α)} (hs : s.Finite) (H : ∀ t ∈ s, Set.Finite t) : (⋃₀ s).Finite := by simpa only [sUnion_eq_biUnion] using hs.biUnion H theorem Finite.sInter {α : Type*} {s : Set (Set α)} {t : Set α} (ht : t ∈ s) (hf : t.Finite) : (⋂₀ s).Finite := hf.subset (sInter_subset_of_mem ht) /-- If sets `s i` are finite for all `i` from a finite set `t` and are empty for `i ∉ t`, then the union `⋃ i, s i` is a finite set. -/ theorem Finite.iUnion {ι : Type*} {s : ι → Set α} {t : Set ι} (ht : t.Finite) (hs : ∀ i ∈ t, (s i).Finite) (he : ∀ i, i ∉ t → s i = ∅) : (⋃ i, s i).Finite := by suffices ⋃ i, s i ⊆ ⋃ i ∈ t, s i by exact (ht.biUnion hs).subset this refine iUnion_subset fun i x hx => ?_ by_cases hi : i ∈ t · exact mem_biUnion hi hx · rw [he i hi, mem_empty_iff_false] at hx contradiction section monad attribute [local instance] Set.monad theorem Finite.bind {α β} {s : Set α} {f : α → Set β} (h : s.Finite) (hf : ∀ a ∈ s, (f a).Finite) : (s >>= f).Finite := h.biUnion hf end monad @[simp] theorem finite_empty : (∅ : Set α).Finite := toFinite _ protected theorem Infinite.nonempty {s : Set α} (h : s.Infinite) : s.Nonempty := nonempty_iff_ne_empty.2 <| by rintro rfl exact h finite_empty @[simp] theorem finite_singleton (a : α) : ({a} : Set α).Finite := toFinite _ theorem finite_pure (a : α) : (pure a : Set α).Finite := toFinite _ @[simp] protected theorem Finite.insert (a : α) {s : Set α} (hs : s.Finite) : (insert a s).Finite := (finite_singleton a).union hs theorem Finite.image {s : Set α} (f : α → β) (hs : s.Finite) : (f '' s).Finite := by have := hs.to_subtype apply toFinite theorem finite_range (f : ι → α) [Finite ι] : (range f).Finite := toFinite _ lemma Finite.of_surjOn {s : Set α} {t : Set β} (f : α → β) (hf : SurjOn f s t) (hs : s.Finite) : t.Finite := (hs.image _).subset hf theorem Finite.dependent_image {s : Set α} (hs : s.Finite) (F : ∀ i ∈ s, β) : {y : β | ∃ x hx, F x hx = y}.Finite := by have := hs.to_subtype simpa [range] using finite_range fun x : s => F x x.2 theorem Finite.map {α β} {s : Set α} : ∀ f : α → β, s.Finite → (f <$> s).Finite := Finite.image theorem Finite.of_finite_image {s : Set α} {f : α → β} (h : (f '' s).Finite) (hi : Set.InjOn f s) : s.Finite := have := h.to_subtype .of_injective _ hi.bijOn_image.bijective.injective section preimage variable {f : α → β} {s : Set β} theorem finite_of_finite_preimage (h : (f ⁻¹' s).Finite) (hs : s ⊆ range f) : s.Finite := by rw [← image_preimage_eq_of_subset hs] exact Finite.image f h theorem Finite.of_preimage (h : (f ⁻¹' s).Finite) (hf : Surjective f) : s.Finite := hf.image_preimage s ▸ h.image _ theorem Finite.preimage (I : Set.InjOn f (f ⁻¹' s)) (h : s.Finite) : (f ⁻¹' s).Finite := (h.subset (image_preimage_subset f s)).of_finite_image I theorem Finite.preimage' (h : s.Finite) (hf : ∀ b ∈ s, (f ⁻¹' {b}).Finite) : (f ⁻¹' s).Finite := by rw [← Set.biUnion_preimage_singleton] exact Set.Finite.biUnion h hf protected lemma Infinite.preimage (hs : s.Infinite) (hf : s ⊆ range f) : (f ⁻¹' s).Infinite := fun h ↦ hs <| finite_of_finite_preimage h hf lemma Infinite.preimage' (hs : (s ∩ range f).Infinite) : (f ⁻¹' s).Infinite := (hs.preimage inter_subset_right).mono <| preimage_mono inter_subset_left theorem Finite.preimage_embedding {s : Set β} (f : α ↪ β) (h : s.Finite) : (f ⁻¹' s).Finite := h.preimage fun _ _ _ _ h' => f.injective h' end preimage theorem finite_lt_nat (n : ℕ) : Set.Finite { i | i < n } := toFinite _ theorem finite_le_nat (n : ℕ) : Set.Finite { i | i ≤ n } := toFinite _ section MapsTo variable {s : Set α} {f : α → α} theorem Finite.surjOn_iff_bijOn_of_mapsTo (hs : s.Finite) (hm : MapsTo f s s) : SurjOn f s s ↔ BijOn f s s := by refine ⟨fun h ↦ ⟨hm, ?_, h⟩, BijOn.surjOn⟩ have : Finite s := finite_coe_iff.mpr hs exact hm.restrict_inj.mp (Finite.injective_iff_surjective.mpr <| hm.restrict_surjective_iff.mpr h) theorem Finite.injOn_iff_bijOn_of_mapsTo (hs : s.Finite) (hm : MapsTo f s s) : InjOn f s ↔ BijOn f s s := by refine ⟨fun h ↦ ⟨hm, h, ?_⟩, BijOn.injOn⟩ have : Finite s := finite_coe_iff.mpr hs exact hm.restrict_surjective_iff.mp (Finite.injective_iff_surjective.mp <| hm.restrict_inj.mpr h) end MapsTo section Prod variable {s : Set α} {t : Set β} protected theorem Finite.prod (hs : s.Finite) (ht : t.Finite) : (s ×ˢ t : Set (α × β)).Finite := by have := hs.to_subtype have := ht.to_subtype apply toFinite theorem Finite.of_prod_left (h : (s ×ˢ t : Set (α × β)).Finite) : t.Nonempty → s.Finite := fun ⟨b, hb⟩ => (h.image Prod.fst).subset fun a ha => ⟨(a, b), ⟨ha, hb⟩, rfl⟩ theorem Finite.of_prod_right (h : (s ×ˢ t : Set (α × β)).Finite) : s.Nonempty → t.Finite := fun ⟨a, ha⟩ => (h.image Prod.snd).subset fun b hb => ⟨(a, b), ⟨ha, hb⟩, rfl⟩ protected theorem Infinite.prod_left (hs : s.Infinite) (ht : t.Nonempty) : (s ×ˢ t).Infinite := fun h => hs <| h.of_prod_left ht protected theorem Infinite.prod_right (ht : t.Infinite) (hs : s.Nonempty) : (s ×ˢ t).Infinite := fun h => ht <| h.of_prod_right hs protected theorem infinite_prod : (s ×ˢ t).Infinite ↔ s.Infinite ∧ t.Nonempty ∨ t.Infinite ∧ s.Nonempty := by refine ⟨fun h => ?_, ?_⟩ · simp_rw [Set.Infinite, @and_comm ¬_, ← Classical.not_imp] by_contra! exact h ((this.1 h.nonempty.snd).prod <| this.2 h.nonempty.fst) · rintro (h | h) · exact h.1.prod_left h.2 · exact h.1.prod_right h.2 theorem finite_prod : (s ×ˢ t).Finite ↔ (s.Finite ∨ t = ∅) ∧ (t.Finite ∨ s = ∅) := by simp only [← not_infinite, Set.infinite_prod, not_or, not_and_or, not_nonempty_iff_eq_empty] protected theorem Finite.offDiag {s : Set α} (hs : s.Finite) : s.offDiag.Finite := (hs.prod hs).subset s.offDiag_subset_prod protected theorem Finite.image2 (f : α → β → γ) (hs : s.Finite) (ht : t.Finite) : (image2 f s t).Finite := by have := hs.to_subtype have := ht.to_subtype apply toFinite end Prod theorem Finite.seq {f : Set (α → β)} {s : Set α} (hf : f.Finite) (hs : s.Finite) : (f.seq s).Finite := hf.image2 _ hs theorem Finite.seq' {α β : Type u} {f : Set (α → β)} {s : Set α} (hf : f.Finite) (hs : s.Finite) : (f <*> s).Finite := hf.seq hs theorem finite_mem_finset (s : Finset α) : { a | a ∈ s }.Finite := toFinite _ theorem Subsingleton.finite {s : Set α} (h : s.Subsingleton) : s.Finite := h.induction_on finite_empty finite_singleton theorem Infinite.nontrivial {s : Set α} (hs : s.Infinite) : s.Nontrivial := not_subsingleton_iff.1 <| mt Subsingleton.finite hs theorem finite_preimage_inl_and_inr {s : Set (α ⊕ β)} : (Sum.inl ⁻¹' s).Finite ∧ (Sum.inr ⁻¹' s).Finite ↔ s.Finite := ⟨fun h => image_preimage_inl_union_image_preimage_inr s ▸ (h.1.image _).union (h.2.image _), fun h => ⟨h.preimage Sum.inl_injective.injOn, h.preimage Sum.inr_injective.injOn⟩⟩ theorem exists_finite_iff_finset {p : Set α → Prop} : (∃ s : Set α, s.Finite ∧ p s) ↔ ∃ s : Finset α, p ↑s := ⟨fun ⟨_, hs, hps⟩ => ⟨hs.toFinset, hs.coe_toFinset.symm ▸ hps⟩, fun ⟨s, hs⟩ => ⟨s, s.finite_toSet, hs⟩⟩ /-- There are finitely many subsets of a given finite set -/ theorem Finite.finite_subsets {α : Type u} {a : Set α} (h : a.Finite) : { b | b ⊆ a }.Finite := by convert ((Finset.powerset h.toFinset).map Finset.coeEmb.1).finite_toSet ext s simpa [← @exists_finite_iff_finset α fun t => t ⊆ a ∧ t = s, Finite.subset_toFinset, ← and_assoc, Finset.coeEmb] using h.subset protected theorem Finite.powerset {s : Set α} (h : s.Finite) : (𝒫 s).Finite := h.finite_subsets theorem exists_subset_image_finite_and {f : α → β} {s : Set α} {p : Set β → Prop} : (∃ t ⊆ f '' s, t.Finite ∧ p t) ↔ ∃ t ⊆ s, t.Finite ∧ p (f '' t) := by classical simp_rw [@and_comm (_ ⊆ _), and_assoc, exists_finite_iff_finset, @and_comm (p _), Finset.subset_image_iff] aesop section Pi variable {ι : Type*} [Finite ι] {κ : ι → Type*} {t : ∀ i, Set (κ i)} /-- Finite product of finite sets is finite -/ theorem Finite.pi (ht : ∀ i, (t i).Finite) : (pi univ t).Finite := by cases nonempty_fintype ι lift t to ∀ d, Finset (κ d) using ht classical rw [← Fintype.coe_piFinset] apply Finset.finite_toSet /-- Finite product of finite sets is finite. Note this is a variant of `Set.Finite.pi` without the extra `i ∈ univ` binder. -/ lemma Finite.pi' (ht : ∀ i, (t i).Finite) : {f : ∀ i, κ i | ∀ i, f i ∈ t i}.Finite := by simpa [Set.pi] using Finite.pi ht end Pi /-- A finite union of finsets is finite. -/ theorem union_finset_finite_of_range_finite (f : α → Finset β) (h : (range f).Finite) : (⋃ a, (f a : Set β)).Finite := by rw [← biUnion_range] exact h.biUnion fun y _ => y.finite_toSet theorem finite_range_ite {p : α → Prop} [DecidablePred p] {f g : α → β} (hf : (range f).Finite) (hg : (range g).Finite) : (range fun x => if p x then f x else g x).Finite := (hf.union hg).subset range_ite_subset theorem finite_range_const {c : β} : (range fun _ : α => c).Finite := (finite_singleton c).subset range_const_subset end SetFiniteConstructors /-! ### Properties -/ instance Finite.inhabited : Inhabited { s : Set α // s.Finite } := ⟨⟨∅, finite_empty⟩⟩ @[simp] theorem finite_union {s t : Set α} : (s ∪ t).Finite ↔ s.Finite ∧ t.Finite := ⟨fun h => ⟨h.subset subset_union_left, h.subset subset_union_right⟩, fun ⟨hs, ht⟩ => hs.union ht⟩ theorem finite_image_iff {s : Set α} {f : α → β} (hi : InjOn f s) : (f '' s).Finite ↔ s.Finite := ⟨fun h => h.of_finite_image hi, Finite.image _⟩ theorem univ_finite_iff_nonempty_fintype : (univ : Set α).Finite ↔ Nonempty (Fintype α) := ⟨fun h => ⟨fintypeOfFiniteUniv h⟩, fun ⟨_i⟩ => finite_univ⟩ -- Porting note: moved `@[simp]` to `Set.toFinset_singleton` because `simp` can now simplify LHS theorem Finite.toFinset_singleton {a : α} (ha : ({a} : Set α).Finite := finite_singleton _) : ha.toFinset = {a} := Set.toFinite_toFinset _ @[simp] theorem Finite.toFinset_insert [DecidableEq α] {s : Set α} {a : α} (hs : (insert a s).Finite) : hs.toFinset = insert a (hs.subset <| subset_insert _ _).toFinset := Finset.ext <| by simp theorem Finite.toFinset_insert' [DecidableEq α] {a : α} {s : Set α} (hs : s.Finite) : (hs.insert a).toFinset = insert a hs.toFinset := Finite.toFinset_insert _ theorem Finite.toFinset_prod {s : Set α} {t : Set β} (hs : s.Finite) (ht : t.Finite) : hs.toFinset ×ˢ ht.toFinset = (hs.prod ht).toFinset := Finset.ext <| by simp theorem Finite.toFinset_offDiag {s : Set α} [DecidableEq α] (hs : s.Finite) : hs.offDiag.toFinset = hs.toFinset.offDiag := Finset.ext <| by simp theorem Finite.fin_embedding {s : Set α} (h : s.Finite) : ∃ (n : ℕ) (f : Fin n ↪ α), range f = s := ⟨_, (Fintype.equivFin (h.toFinset : Set α)).symm.asEmbedding, by simp only [Finset.coe_sort_coe, Equiv.asEmbedding_range, Finite.coe_toFinset, setOf_mem_eq]⟩ theorem Finite.fin_param {s : Set α} (h : s.Finite) : ∃ (n : ℕ) (f : Fin n → α), Injective f ∧ range f = s := let ⟨n, f, hf⟩ := h.fin_embedding ⟨n, f, f.injective, hf⟩ theorem finite_option {s : Set (Option α)} : s.Finite ↔ { x : α | some x ∈ s }.Finite := ⟨fun h => h.preimage_embedding Embedding.some, fun h => ((h.image some).insert none).subset fun x => x.casesOn (fun _ => Or.inl rfl) fun _ hx => Or.inr <| mem_image_of_mem _ hx⟩ theorem finite_image_fst_and_snd_iff {s : Set (α × β)} : (Prod.fst '' s).Finite ∧ (Prod.snd '' s).Finite ↔ s.Finite := ⟨fun h => (h.1.prod h.2).subset fun _ h => ⟨mem_image_of_mem _ h, mem_image_of_mem _ h⟩, fun h => ⟨h.image _, h.image _⟩⟩ theorem forall_finite_image_eval_iff {δ : Type*} [Finite δ] {κ : δ → Type*} {s : Set (∀ d, κ d)} : (∀ d, (eval d '' s).Finite) ↔ s.Finite := ⟨fun h => (Finite.pi h).subset <| subset_pi_eval_image _ _, fun h _ => h.image _⟩ theorem finite_subset_iUnion {s : Set α} (hs : s.Finite) {ι} {t : ι → Set α} (h : s ⊆ ⋃ i, t i) : ∃ I : Set ι, I.Finite ∧ s ⊆ ⋃ i ∈ I, t i := by have := hs.to_subtype choose f hf using show ∀ x : s, ∃ i, x.1 ∈ t i by simpa [subset_def] using h refine ⟨range f, finite_range f, fun x hx => ?_⟩ rw [biUnion_range, mem_iUnion] exact ⟨⟨x, hx⟩, hf _⟩ theorem eq_finite_iUnion_of_finite_subset_iUnion {ι} {s : ι → Set α} {t : Set α} (tfin : t.Finite) (h : t ⊆ ⋃ i, s i) : ∃ I : Set ι, I.Finite ∧ ∃ σ : { i | i ∈ I } → Set α, (∀ i, (σ i).Finite) ∧ (∀ i, σ i ⊆ s i) ∧ t = ⋃ i, σ i := let ⟨I, Ifin, hI⟩ := finite_subset_iUnion tfin h ⟨I, Ifin, fun x => s x ∩ t, fun i => tfin.subset inter_subset_right, fun i => inter_subset_left, by ext x rw [mem_iUnion] constructor · intro x_in rcases mem_iUnion.mp (hI x_in) with ⟨i, _, ⟨hi, rfl⟩, H⟩ exact ⟨⟨i, hi⟩, ⟨H, x_in⟩⟩ · rintro ⟨i, -, H⟩ exact H⟩ @[elab_as_elim] theorem Finite.induction_on {C : Set α → Prop} {s : Set α} (h : s.Finite) (H0 : C ∅) (H1 : ∀ {a s}, a ∉ s → Set.Finite s → C s → C (insert a s)) : C s := by lift s to Finset α using h induction' s using Finset.cons_induction_on with a s ha hs · rwa [Finset.coe_empty] · rw [Finset.coe_cons] exact @H1 a s ha (Set.toFinite _) hs /-- Analogous to `Finset.induction_on'`. -/ @[elab_as_elim] theorem Finite.induction_on' {C : Set α → Prop} {S : Set α} (h : S.Finite) (H0 : C ∅) (H1 : ∀ {a s}, a ∈ S → s ⊆ S → a ∉ s → C s → C (insert a s)) : C S := by refine @Set.Finite.induction_on α (fun s => s ⊆ S → C s) S h (fun _ => H0) ?_ Subset.rfl intro a s has _ hCs haS rw [insert_subset_iff] at haS exact H1 haS.1 haS.2 has (hCs haS.2) @[elab_as_elim] theorem Finite.dinduction_on {C : ∀ s : Set α, s.Finite → Prop} (s : Set α) (h : s.Finite) (H0 : C ∅ finite_empty) (H1 : ∀ {a s}, a ∉ s → ∀ h : Set.Finite s, C s h → C (insert a s) (h.insert a)) : C s h := have : ∀ h : s.Finite, C s h := Finite.induction_on h (fun _ => H0) fun has hs ih _ => H1 has hs (ih _) this h /-- Induction up to a finite set `S`. -/ theorem Finite.induction_to {C : Set α → Prop} {S : Set α} (h : S.Finite) (S0 : Set α) (hS0 : S0 ⊆ S) (H0 : C S0) (H1 : ∀ s ⊂ S, C s → ∃ a ∈ S \ s, C (insert a s)) : C S := by have : Finite S := Finite.to_subtype h have : Finite {T : Set α // T ⊆ S} := Finite.of_equiv (Set S) (Equiv.Set.powerset S).symm rw [← Subtype.coe_mk (p := (· ⊆ S)) _ le_rfl] rw [← Subtype.coe_mk (p := (· ⊆ S)) _ hS0] at H0 refine Finite.to_wellFoundedGT.wf.induction_bot' (fun s hs hs' ↦ ?_) H0 obtain ⟨a, ⟨ha1, ha2⟩, ha'⟩ := H1 s (ssubset_of_ne_of_subset hs s.2) hs' exact ⟨⟨insert a s.1, insert_subset ha1 s.2⟩, Set.ssubset_insert ha2, ha'⟩ /-- Induction up to `univ`. -/ theorem Finite.induction_to_univ [Finite α] {C : Set α → Prop} (S0 : Set α) (H0 : C S0) (H1 : ∀ S ≠ univ, C S → ∃ a ∉ S, C (insert a S)) : C univ := finite_univ.induction_to S0 (subset_univ S0) H0 (by simpa [ssubset_univ_iff]) section attribute [local instance] Nat.fintypeIio /-- If `P` is some relation between terms of `γ` and sets in `γ`, such that every finite set `t : Set γ` has some `c : γ` related to it, then there is a recursively defined sequence `u` in `γ` so `u n` is related to the image of `{0, 1, ..., n-1}` under `u`. (We use this later to show sequentially compact sets are totally bounded.) -/ theorem seq_of_forall_finite_exists {γ : Type*} {P : γ → Set γ → Prop} (h : ∀ t : Set γ, t.Finite → ∃ c, P c t) : ∃ u : ℕ → γ, ∀ n, P (u n) (u '' Iio n) := by haveI : Nonempty γ := (h ∅ finite_empty).nonempty choose! c hc using h set f : (n : ℕ) → (g : (m : ℕ) → m < n → γ) → γ := fun n g => c (range fun k : Iio n => g k.1 k.2) set u : ℕ → γ := fun n => Nat.strongRecOn' n f refine ⟨u, fun n => ?_⟩ convert hc (u '' Iio n) ((finite_lt_nat _).image _) rw [image_eq_range] exact Nat.strongRecOn'_beta end /-! ### Cardinality -/ theorem empty_card : Fintype.card (∅ : Set α) = 0 := rfl theorem empty_card' {h : Fintype.{u} (∅ : Set α)} : @Fintype.card (∅ : Set α) h = 0 := by simp theorem card_fintypeInsertOfNotMem {a : α} (s : Set α) [Fintype s] (h : a ∉ s) : @Fintype.card _ (fintypeInsertOfNotMem s h) = Fintype.card s + 1 := by simp [fintypeInsertOfNotMem, Fintype.card_ofFinset] @[simp] theorem card_insert {a : α} (s : Set α) [Fintype s] (h : a ∉ s) {d : Fintype.{u} (insert a s : Set α)} : @Fintype.card _ d = Fintype.card s + 1 := by rw [← card_fintypeInsertOfNotMem s h]; congr! theorem card_image_of_inj_on {s : Set α} [Fintype s] {f : α → β} [Fintype (f '' s)] (H : ∀ x ∈ s, ∀ y ∈ s, f x = f y → x = y) : Fintype.card (f '' s) = Fintype.card s := haveI := Classical.propDecidable calc Fintype.card (f '' s) = (s.toFinset.image f).card := Fintype.card_of_finset' _ (by simp) _ = s.toFinset.card := Finset.card_image_of_injOn fun x hx y hy hxy => H x (mem_toFinset.1 hx) y (mem_toFinset.1 hy) hxy _ = Fintype.card s := (Fintype.card_of_finset' _ fun a => mem_toFinset).symm theorem card_image_of_injective (s : Set α) [Fintype s] {f : α → β} [Fintype (f '' s)] (H : Function.Injective f) : Fintype.card (f '' s) = Fintype.card s := card_image_of_inj_on fun _ _ _ _ h => H h @[simp] theorem card_singleton (a : α) : Fintype.card ({a} : Set α) = 1 := Fintype.card_ofSubsingleton _ theorem card_lt_card {s t : Set α} [Fintype s] [Fintype t] (h : s ⊂ t) : Fintype.card s < Fintype.card t := Fintype.card_lt_of_injective_not_surjective (Set.inclusion h.1) (Set.inclusion_injective h.1) fun hst => (ssubset_iff_subset_ne.1 h).2 (eq_of_inclusion_surjective hst) theorem card_le_card {s t : Set α} [Fintype s] [Fintype t] (hsub : s ⊆ t) : Fintype.card s ≤ Fintype.card t := Fintype.card_le_of_injective (Set.inclusion hsub) (Set.inclusion_injective hsub) theorem eq_of_subset_of_card_le {s t : Set α} [Fintype s] [Fintype t] (hsub : s ⊆ t) (hcard : Fintype.card t ≤ Fintype.card s) : s = t := (eq_or_ssubset_of_subset hsub).elim id fun h => absurd hcard <| not_le_of_lt <| card_lt_card h theorem card_range_of_injective [Fintype α] {f : α → β} (hf : Injective f) [Fintype (range f)] : Fintype.card (range f) = Fintype.card α := Eq.symm <| Fintype.card_congr <| Equiv.ofInjective f hf theorem Finite.card_toFinset {s : Set α} [Fintype s] (h : s.Finite) : h.toFinset.card = Fintype.card s := Eq.symm <| Fintype.card_of_finset' _ fun _ ↦ h.mem_toFinset theorem card_ne_eq [Fintype α] (a : α) [Fintype { x : α | x ≠ a }] : Fintype.card { x : α | x ≠ a } = Fintype.card α - 1 := by haveI := Classical.decEq α rw [← toFinset_card, toFinset_setOf, Finset.filter_ne', Finset.card_erase_of_mem (Finset.mem_univ _), Finset.card_univ] /-! ### Infinite sets -/ variable {s t : Set α} theorem infinite_univ_iff : (@univ α).Infinite ↔ Infinite α := by rw [Set.Infinite, finite_univ_iff, not_finite_iff_infinite] theorem infinite_univ [h : Infinite α] : (@univ α).Infinite := infinite_univ_iff.2 h theorem infinite_coe_iff {s : Set α} : Infinite s ↔ s.Infinite := not_finite_iff_infinite.symm.trans finite_coe_iff.not -- Porting note: something weird happened here alias ⟨_, Infinite.to_subtype⟩ := infinite_coe_iff lemma Infinite.exists_not_mem_finite (hs : s.Infinite) (ht : t.Finite) : ∃ a, a ∈ s ∧ a ∉ t := by by_contra! h; exact hs <| ht.subset h lemma Infinite.exists_not_mem_finset (hs : s.Infinite) (t : Finset α) : ∃ a ∈ s, a ∉ t := hs.exists_not_mem_finite t.finite_toSet section Infinite variable [Infinite α] lemma Finite.exists_not_mem (hs : s.Finite) : ∃ a, a ∉ s := by by_contra! h; exact infinite_univ (hs.subset fun a _ ↦ h _) lemma _root_.Finset.exists_not_mem (s : Finset α) : ∃ a, a ∉ s := s.finite_toSet.exists_not_mem end Infinite /-- Embedding of `ℕ` into an infinite set. -/ noncomputable def Infinite.natEmbedding (s : Set α) (h : s.Infinite) : ℕ ↪ s := h.to_subtype.natEmbedding theorem Infinite.exists_subset_card_eq {s : Set α} (hs : s.Infinite) (n : ℕ) : ∃ t : Finset α, ↑t ⊆ s ∧ t.card = n := ⟨((Finset.range n).map (hs.natEmbedding _)).map (Embedding.subtype _), by simp⟩ theorem infinite_of_finite_compl [Infinite α] {s : Set α} (hs : sᶜ.Finite) : s.Infinite := fun h => Set.infinite_univ (α := α) (by simpa using hs.union h) theorem Finite.infinite_compl [Infinite α] {s : Set α} (hs : s.Finite) : sᶜ.Infinite := fun h => Set.infinite_univ (α := α) (by simpa using hs.union h) theorem Infinite.diff {s t : Set α} (hs : s.Infinite) (ht : t.Finite) : (s \ t).Infinite := fun h => hs <| h.of_diff ht @[simp] theorem infinite_union {s t : Set α} : (s ∪ t).Infinite ↔ s.Infinite ∨ t.Infinite := by simp only [Set.Infinite, finite_union, not_and_or] theorem Infinite.of_image (f : α → β) {s : Set α} (hs : (f '' s).Infinite) : s.Infinite := mt (Finite.image f) hs theorem infinite_image_iff {s : Set α} {f : α → β} (hi : InjOn f s) : (f '' s).Infinite ↔ s.Infinite := not_congr <| finite_image_iff hi theorem infinite_range_iff {f : α → β} (hi : Injective f) : (range f).Infinite ↔ Infinite α := by rw [← image_univ, infinite_image_iff hi.injOn, infinite_univ_iff] alias ⟨_, Infinite.image⟩ := infinite_image_iff -- Porting note: attribute [protected] doesn't work -- attribute [protected] infinite.image section Image2 variable {f : α → β → γ} {s : Set α} {t : Set β} {a : α} {b : β} protected theorem Infinite.image2_left (hs : s.Infinite) (hb : b ∈ t) (hf : InjOn (fun a => f a b) s) : (image2 f s t).Infinite := (hs.image hf).mono <| image_subset_image2_left hb protected theorem Infinite.image2_right (ht : t.Infinite) (ha : a ∈ s) (hf : InjOn (f a) t) : (image2 f s t).Infinite := (ht.image hf).mono <| image_subset_image2_right ha theorem infinite_image2 (hfs : ∀ b ∈ t, InjOn (fun a => f a b) s) (hft : ∀ a ∈ s, InjOn (f a) t) : (image2 f s t).Infinite ↔ s.Infinite ∧ t.Nonempty ∨ t.Infinite ∧ s.Nonempty := by refine ⟨fun h => Set.infinite_prod.1 ?_, ?_⟩ · rw [← image_uncurry_prod] at h exact h.of_image _ · rintro (⟨hs, b, hb⟩ | ⟨ht, a, ha⟩) · exact hs.image2_left hb (hfs _ hb) · exact ht.image2_right ha (hft _ ha) lemma finite_image2 (hfs : ∀ b ∈ t, InjOn (f · b) s) (hft : ∀ a ∈ s, InjOn (f a) t) : (image2 f s t).Finite ↔ s.Finite ∧ t.Finite ∨ s = ∅ ∨ t = ∅ := by rw [← not_infinite, infinite_image2 hfs hft] simp [not_or, -not_and, not_and_or, not_nonempty_iff_eq_empty] aesop end Image2 theorem infinite_of_injOn_mapsTo {s : Set α} {t : Set β} {f : α → β} (hi : InjOn f s) (hm : MapsTo f s t) (hs : s.Infinite) : t.Infinite := ((infinite_image_iff hi).2 hs).mono (mapsTo'.mp hm) theorem Infinite.exists_ne_map_eq_of_mapsTo {s : Set α} {t : Set β} {f : α → β} (hs : s.Infinite) (hf : MapsTo f s t) (ht : t.Finite) : ∃ x ∈ s, ∃ y ∈ s, x ≠ y ∧ f x = f y := by contrapose! ht exact infinite_of_injOn_mapsTo (fun x hx y hy => not_imp_not.1 (ht x hx y hy)) hf hs theorem infinite_range_of_injective [Infinite α] {f : α → β} (hi : Injective f) : (range f).Infinite := by rw [← image_univ, infinite_image_iff hi.injOn] exact infinite_univ theorem infinite_of_injective_forall_mem [Infinite α] {s : Set β} {f : α → β} (hi : Injective f) (hf : ∀ x : α, f x ∈ s) : s.Infinite := by rw [← range_subset_iff] at hf exact (infinite_range_of_injective hi).mono hf theorem not_injOn_infinite_finite_image {f : α → β} {s : Set α} (h_inf : s.Infinite) (h_fin : (f '' s).Finite) : ¬InjOn f s := by have : Finite (f '' s) := finite_coe_iff.mpr h_fin have : Infinite s := infinite_coe_iff.mpr h_inf have h := not_injective_infinite_finite ((f '' s).codRestrict (s.restrict f) fun x => ⟨x, x.property, rfl⟩) contrapose! h rwa [injective_codRestrict, ← injOn_iff_injective] theorem infinite_iUnion {ι : Type*} [Infinite ι] {s : ι → Set α} (hs : Function.Injective s) : (⋃ i, s i).Infinite := fun hfin ↦ @not_injective_infinite_finite ι _ _ hfin.finite_subsets.to_subtype (fun i ↦ ⟨s i, subset_iUnion _ _⟩) fun i j h_eq ↦ hs (by simpa using h_eq) theorem Infinite.biUnion {ι : Type*} {s : ι → Set α} {a : Set ι} (ha : a.Infinite) (hs : a.InjOn s) : (⋃ i ∈ a, s i).Infinite := by rw [biUnion_eq_iUnion] have _ := ha.to_subtype exact infinite_iUnion fun ⟨i,hi⟩ ⟨j,hj⟩ hij ↦ by simp [hs hi hj hij] theorem Infinite.sUnion {s : Set (Set α)} (hs : s.Infinite) : (⋃₀ s).Infinite := by rw [sUnion_eq_iUnion] have _ := hs.to_subtype exact infinite_iUnion Subtype.coe_injective /-! ### Order properties -/ section Preorder variable [Preorder α] [Nonempty α] {s : Set α} theorem infinite_of_forall_exists_gt (h : ∀ a, ∃ b ∈ s, a < b) : s.Infinite := by inhabit α set f : ℕ → α := fun n => Nat.recOn n (h default).choose fun _ a => (h a).choose have hf : ∀ n, f n ∈ s := by rintro (_ | _) <;> exact (h _).choose_spec.1 exact infinite_of_injective_forall_mem (strictMono_nat_of_lt_succ fun n => (h _).choose_spec.2).injective hf theorem infinite_of_forall_exists_lt (h : ∀ a, ∃ b ∈ s, b < a) : s.Infinite := infinite_of_forall_exists_gt (α := αᵒᵈ) h end Preorder theorem finite_isTop (α : Type*) [PartialOrder α] : { x : α | IsTop x }.Finite := (subsingleton_isTop α).finite theorem finite_isBot (α : Type*) [PartialOrder α] : { x : α | IsBot x }.Finite := (subsingleton_isBot α).finite theorem Infinite.exists_lt_map_eq_of_mapsTo [LinearOrder α] {s : Set α} {t : Set β} {f : α → β} (hs : s.Infinite) (hf : MapsTo f s t) (ht : t.Finite) : ∃ x ∈ s, ∃ y ∈ s, x < y ∧ f x = f y := let ⟨x, hx, y, hy, hxy, hf⟩ := hs.exists_ne_map_eq_of_mapsTo hf ht hxy.lt_or_lt.elim (fun hxy => ⟨x, hx, y, hy, hxy, hf⟩) fun hyx => ⟨y, hy, x, hx, hyx, hf.symm⟩ theorem Finite.exists_lt_map_eq_of_forall_mem [LinearOrder α] [Infinite α] {t : Set β} {f : α → β} (hf : ∀ a, f a ∈ t) (ht : t.Finite) : ∃ a b, a < b ∧ f a = f b := by rw [← mapsTo_univ_iff] at hf obtain ⟨a, -, b, -, h⟩ := infinite_univ.exists_lt_map_eq_of_mapsTo hf ht exact ⟨a, b, h⟩ theorem exists_min_image [LinearOrder β] (s : Set α) (f : α → β) (h1 : s.Finite) : s.Nonempty → ∃ a ∈ s, ∀ b ∈ s, f a ≤ f b | ⟨x, hx⟩ => by simpa only [exists_prop, Finite.mem_toFinset] using h1.toFinset.exists_min_image f ⟨x, h1.mem_toFinset.2 hx⟩ theorem exists_max_image [LinearOrder β] (s : Set α) (f : α → β) (h1 : s.Finite) : s.Nonempty → ∃ a ∈ s, ∀ b ∈ s, f b ≤ f a | ⟨x, hx⟩ => by simpa only [exists_prop, Finite.mem_toFinset] using h1.toFinset.exists_max_image f ⟨x, h1.mem_toFinset.2 hx⟩ theorem exists_lower_bound_image [Nonempty α] [LinearOrder β] (s : Set α) (f : α → β) (h : s.Finite) : ∃ a : α, ∀ b ∈ s, f a ≤ f b := by rcases s.eq_empty_or_nonempty with rfl | hs · exact ‹Nonempty α›.elim fun a => ⟨a, fun _ => False.elim⟩ · rcases Set.exists_min_image s f h hs with ⟨x₀, _, hx₀⟩ exact ⟨x₀, fun x hx => hx₀ x hx⟩ theorem exists_upper_bound_image [Nonempty α] [LinearOrder β] (s : Set α) (f : α → β) (h : s.Finite) : ∃ a : α, ∀ b ∈ s, f b ≤ f a := exists_lower_bound_image (β := βᵒᵈ) s f h theorem Finite.iSup_biInf_of_monotone {ι ι' α : Type*} [Preorder ι'] [Nonempty ι'] [IsDirected ι' (· ≤ ·)] [Order.Frame α] {s : Set ι} (hs : s.Finite) {f : ι → ι' → α} (hf : ∀ i ∈ s, Monotone (f i)) : ⨆ j, ⨅ i ∈ s, f i j = ⨅ i ∈ s, ⨆ j, f i j := by induction' s, hs using Set.Finite.dinduction_on with a s _ _ ihs hf · simp [iSup_const] · rw [forall_mem_insert] at hf simp only [iInf_insert, ← ihs hf.2] exact iSup_inf_of_monotone hf.1 fun j₁ j₂ hj => iInf₂_mono fun i hi => hf.2 i hi hj theorem Finite.iSup_biInf_of_antitone {ι ι' α : Type*} [Preorder ι'] [Nonempty ι'] [IsDirected ι' (swap (· ≤ ·))] [Order.Frame α] {s : Set ι} (hs : s.Finite) {f : ι → ι' → α} (hf : ∀ i ∈ s, Antitone (f i)) : ⨆ j, ⨅ i ∈ s, f i j = ⨅ i ∈ s, ⨆ j, f i j := @Finite.iSup_biInf_of_monotone ι ι'ᵒᵈ α _ _ _ _ _ hs _ fun i hi => (hf i hi).dual_left theorem Finite.iInf_biSup_of_monotone {ι ι' α : Type*} [Preorder ι'] [Nonempty ι'] [IsDirected ι' (swap (· ≤ ·))] [Order.Coframe α] {s : Set ι} (hs : s.Finite) {f : ι → ι' → α} (hf : ∀ i ∈ s, Monotone (f i)) : ⨅ j, ⨆ i ∈ s, f i j = ⨆ i ∈ s, ⨅ j, f i j := hs.iSup_biInf_of_antitone (α := αᵒᵈ) fun i hi => (hf i hi).dual_right theorem Finite.iInf_biSup_of_antitone {ι ι' α : Type*} [Preorder ι'] [Nonempty ι'] [IsDirected ι' (· ≤ ·)] [Order.Coframe α] {s : Set ι} (hs : s.Finite) {f : ι → ι' → α} (hf : ∀ i ∈ s, Antitone (f i)) : ⨅ j, ⨆ i ∈ s, f i j = ⨆ i ∈ s, ⨅ j, f i j := hs.iSup_biInf_of_monotone (α := αᵒᵈ) fun i hi => (hf i hi).dual_right theorem iSup_iInf_of_monotone {ι ι' α : Type*} [Finite ι] [Preorder ι'] [Nonempty ι'] [IsDirected ι' (· ≤ ·)] [Order.Frame α] {f : ι → ι' → α} (hf : ∀ i, Monotone (f i)) : ⨆ j, ⨅ i, f i j = ⨅ i, ⨆ j, f i j := by simpa only [iInf_univ] using finite_univ.iSup_biInf_of_monotone fun i _ => hf i theorem iSup_iInf_of_antitone {ι ι' α : Type*} [Finite ι] [Preorder ι'] [Nonempty ι'] [IsDirected ι' (swap (· ≤ ·))] [Order.Frame α] {f : ι → ι' → α} (hf : ∀ i, Antitone (f i)) : ⨆ j, ⨅ i, f i j = ⨅ i, ⨆ j, f i j := @iSup_iInf_of_monotone ι ι'ᵒᵈ α _ _ _ _ _ _ fun i => (hf i).dual_left theorem iInf_iSup_of_monotone {ι ι' α : Type*} [Finite ι] [Preorder ι'] [Nonempty ι'] [IsDirected ι' (swap (· ≤ ·))] [Order.Coframe α] {f : ι → ι' → α} (hf : ∀ i, Monotone (f i)) : ⨅ j, ⨆ i, f i j = ⨆ i, ⨅ j, f i j := iSup_iInf_of_antitone (α := αᵒᵈ) fun i => (hf i).dual_right theorem iInf_iSup_of_antitone {ι ι' α : Type*} [Finite ι] [Preorder ι'] [Nonempty ι'] [IsDirected ι' (· ≤ ·)] [Order.Coframe α] {f : ι → ι' → α} (hf : ∀ i, Antitone (f i)) : ⨅ j, ⨆ i, f i j = ⨆ i, ⨅ j, f i j := iSup_iInf_of_monotone (α := αᵒᵈ) fun i => (hf i).dual_right /-- An increasing union distributes over finite intersection. -/ theorem iUnion_iInter_of_monotone {ι ι' α : Type*} [Finite ι] [Preorder ι'] [IsDirected ι' (· ≤ ·)] [Nonempty ι'] {s : ι → ι' → Set α} (hs : ∀ i, Monotone (s i)) : ⋃ j : ι', ⋂ i : ι, s i j = ⋂ i : ι, ⋃ j : ι', s i j := iSup_iInf_of_monotone hs /-- A decreasing union distributes over finite intersection. -/ theorem iUnion_iInter_of_antitone {ι ι' α : Type*} [Finite ι] [Preorder ι'] [IsDirected ι' (swap (· ≤ ·))] [Nonempty ι'] {s : ι → ι' → Set α} (hs : ∀ i, Antitone (s i)) : ⋃ j : ι', ⋂ i : ι, s i j = ⋂ i : ι, ⋃ j : ι', s i j := iSup_iInf_of_antitone hs /-- An increasing intersection distributes over finite union. -/ theorem iInter_iUnion_of_monotone {ι ι' α : Type*} [Finite ι] [Preorder ι'] [IsDirected ι' (swap (· ≤ ·))] [Nonempty ι'] {s : ι → ι' → Set α} (hs : ∀ i, Monotone (s i)) : ⋂ j : ι', ⋃ i : ι, s i j = ⋃ i : ι, ⋂ j : ι', s i j := iInf_iSup_of_monotone hs /-- A decreasing intersection distributes over finite union. -/ theorem iInter_iUnion_of_antitone {ι ι' α : Type*} [Finite ι] [Preorder ι'] [IsDirected ι' (· ≤ ·)] [Nonempty ι'] {s : ι → ι' → Set α} (hs : ∀ i, Antitone (s i)) : ⋂ j : ι', ⋃ i : ι, s i j = ⋃ i : ι, ⋂ j : ι', s i j := iInf_iSup_of_antitone hs theorem iUnion_pi_of_monotone {ι ι' : Type*} [LinearOrder ι'] [Nonempty ι'] {α : ι → Type*} {I : Set ι} {s : ∀ i, ι' → Set (α i)} (hI : I.Finite) (hs : ∀ i ∈ I, Monotone (s i)) : ⋃ j : ι', I.pi (fun i => s i j) = I.pi fun i => ⋃ j, s i j := by simp only [pi_def, biInter_eq_iInter, preimage_iUnion] haveI := hI.fintype.finite refine iUnion_iInter_of_monotone (ι' := ι') (fun (i : I) j₁ j₂ h => ?_) exact preimage_mono <| hs i i.2 h theorem iUnion_univ_pi_of_monotone {ι ι' : Type*} [LinearOrder ι'] [Nonempty ι'] [Finite ι] {α : ι → Type*} {s : ∀ i, ι' → Set (α i)} (hs : ∀ i, Monotone (s i)) : ⋃ j : ι', pi univ (fun i => s i j) = pi univ fun i => ⋃ j, s i j := iUnion_pi_of_monotone finite_univ fun i _ => hs i theorem finite_range_findGreatest {P : α → ℕ → Prop} [∀ x, DecidablePred (P x)] {b : ℕ} : (range fun x => Nat.findGreatest (P x) b).Finite := (finite_le_nat b).subset <| range_subset_iff.2 fun _ => Nat.findGreatest_le _ theorem Finite.exists_maximal_wrt [PartialOrder β] (f : α → β) (s : Set α) (h : s.Finite) (hs : s.Nonempty) : ∃ a ∈ s, ∀ a' ∈ s, f a ≤ f a' → f a = f a' := by induction s, h using Set.Finite.dinduction_on with | H0 => exact absurd hs not_nonempty_empty | @H1 a s his _ ih => rcases s.eq_empty_or_nonempty with h | h · use a simp [h] rcases ih h with ⟨b, hb, ih⟩ by_cases h : f b ≤ f a · refine ⟨a, Set.mem_insert _ _, fun c hc hac => le_antisymm hac ?_⟩ rcases Set.mem_insert_iff.1 hc with (rfl | hcs) · rfl · rwa [← ih c hcs (le_trans h hac)] · refine ⟨b, Set.mem_insert_of_mem _ hb, fun c hc hbc => ?_⟩ rcases Set.mem_insert_iff.1 hc with (rfl | hcs) · exact (h hbc).elim · exact ih c hcs hbc /-- A version of `Finite.exists_maximal_wrt` with the (weaker) hypothesis that the image of `s` is finite rather than `s` itself. -/ theorem Finite.exists_maximal_wrt' [PartialOrder β] (f : α → β) (s : Set α) (h : (f '' s).Finite) (hs : s.Nonempty) : (∃ a ∈ s, ∀ (a' : α), a' ∈ s → f a ≤ f a' → f a = f a') := by obtain ⟨_, ⟨a, ha, rfl⟩, hmax⟩ := Finite.exists_maximal_wrt id (f '' s) h (hs.image f) exact ⟨a, ha, fun a' ha' hf ↦ hmax _ (mem_image_of_mem f ha') hf⟩ theorem Finite.exists_minimal_wrt [PartialOrder β] (f : α → β) (s : Set α) (h : s.Finite) (hs : s.Nonempty) : ∃ a ∈ s, ∀ a' ∈ s, f a' ≤ f a → f a = f a' := Finite.exists_maximal_wrt (β := βᵒᵈ) f s h hs /-- A version of `Finite.exists_minimal_wrt` with the (weaker) hypothesis that the image of `s` is finite rather than `s` itself. -/ lemma Finite.exists_minimal_wrt' [PartialOrder β] (f : α → β) (s : Set α) (h : (f '' s).Finite) (hs : s.Nonempty) : (∃ a ∈ s, ∀ (a' : α), a' ∈ s → f a' ≤ f a → f a = f a') := Set.Finite.exists_maximal_wrt' (β := βᵒᵈ) f s h hs section variable [Preorder α] [IsDirected α (· ≤ ·)] [Nonempty α] {s : Set α} /-- A finite set is bounded above. -/ protected theorem Finite.bddAbove (hs : s.Finite) : BddAbove s := Finite.induction_on hs bddAbove_empty fun _ _ h => h.insert _ /-- A finite union of sets which are all bounded above is still bounded above. -/ theorem Finite.bddAbove_biUnion {I : Set β} {S : β → Set α} (H : I.Finite) : BddAbove (⋃ i ∈ I, S i) ↔ ∀ i ∈ I, BddAbove (S i) := Finite.induction_on H (by simp only [biUnion_empty, bddAbove_empty, forall_mem_empty]) fun _ _ hs => by simp only [biUnion_insert, forall_mem_insert, bddAbove_union, hs] theorem infinite_of_not_bddAbove : ¬BddAbove s → s.Infinite := mt Finite.bddAbove end section variable [Preorder α] [IsDirected α (· ≥ ·)] [Nonempty α] {s : Set α} /-- A finite set is bounded below. -/ protected theorem Finite.bddBelow (hs : s.Finite) : BddBelow s := Finite.bddAbove (α := αᵒᵈ) hs /-- A finite union of sets which are all bounded below is still bounded below. -/ theorem Finite.bddBelow_biUnion {I : Set β} {S : β → Set α} (H : I.Finite) : BddBelow (⋃ i ∈ I, S i) ↔ ∀ i ∈ I, BddBelow (S i) := Finite.bddAbove_biUnion (α := αᵒᵈ) H theorem infinite_of_not_bddBelow : ¬BddBelow s → s.Infinite := mt Finite.bddBelow end end Set namespace Finset lemma exists_card_eq [Infinite α] : ∀ n : ℕ, ∃ s : Finset α, s.card = n | 0 => ⟨∅, card_empty⟩ | n + 1 => by classical obtain ⟨s, rfl⟩ := exists_card_eq n obtain ⟨a, ha⟩ := s.exists_not_mem exact ⟨insert a s, card_insert_of_not_mem ha⟩ /-- A finset is bounded above. -/ protected theorem bddAbove [SemilatticeSup α] [Nonempty α] (s : Finset α) : BddAbove (↑s : Set α) := s.finite_toSet.bddAbove /-- A finset is bounded below. -/ protected theorem bddBelow [SemilatticeInf α] [Nonempty α] (s : Finset α) : BddBelow (↑s : Set α) := s.finite_toSet.bddBelow end Finset variable [LinearOrder α] {s : Set α} /-- If a linear order does not contain any triple of elements `x < y < z`, then this type is finite. -/ lemma Finite.of_forall_not_lt_lt (h : ∀ ⦃x y z : α⦄, x < y → y < z → False) : Finite α := by nontriviality α rcases exists_pair_ne α with ⟨x, y, hne⟩ refine @Finite.of_fintype α ⟨{x, y}, fun z => ?_⟩ simpa [hne] using eq_or_eq_or_eq_of_forall_not_lt_lt h z x y /-- If a set `s` does not contain any triple of elements `x < y < z`, then `s` is finite. -/ lemma Set.finite_of_forall_not_lt_lt (h : ∀ x ∈ s, ∀ y ∈ s, ∀ z ∈ s, x < y → y < z → False) : Set.Finite s := @Set.toFinite _ s <| Finite.of_forall_not_lt_lt <| by simpa only [SetCoe.forall'] using h lemma Set.finite_diff_iUnion_Ioo (s : Set α) : (s \ ⋃ (x ∈ s) (y ∈ s), Ioo x y).Finite := Set.finite_of_forall_not_lt_lt fun _x hx _y hy _z hz hxy hyz => hy.2 <| mem_iUnion₂_of_mem hx.1 <| mem_iUnion₂_of_mem hz.1 ⟨hxy, hyz⟩ lemma Set.finite_diff_iUnion_Ioo' (s : Set α) : (s \ ⋃ x : s × s, Ioo x.1 x.2).Finite := by simpa only [iUnion, iSup_prod, iSup_subtype] using s.finite_diff_iUnion_Ioo lemma Directed.exists_mem_subset_of_finset_subset_biUnion {α ι : Type*} [Nonempty ι] {f : ι → Set α} (h : Directed (· ⊆ ·) f) {s : Finset α} (hs : (s : Set α) ⊆ ⋃ i, f i) : ∃ i, (s : Set α) ⊆ f i := by induction s using Finset.cons_induction with | empty => simp | cons b t hbt iht => simp only [Finset.coe_cons, Set.insert_subset_iff, Set.mem_iUnion] at hs ⊢ rcases hs.imp_right iht with ⟨⟨i, hi⟩, j, hj⟩ rcases h i j with ⟨k, hik, hjk⟩ exact ⟨k, hik hi, hj.trans hjk⟩ theorem DirectedOn.exists_mem_subset_of_finset_subset_biUnion {α ι : Type*} {f : ι → Set α} {c : Set ι} (hn : c.Nonempty) (hc : DirectedOn (fun i j => f i ⊆ f j) c) {s : Finset α} (hs : (s : Set α) ⊆ ⋃ i ∈ c, f i) : ∃ i ∈ c, (s : Set α) ⊆ f i := by rw [Set.biUnion_eq_iUnion] at hs haveI := hn.coe_sort simpa using (directed_comp.2 hc.directed_val).exists_mem_subset_of_finset_subset_biUnion hs
Data\Set\Function.lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Andrew Zipperer, Haitao Zhang, Minchao Wu, Yury Kudryashov -/ import Mathlib.Data.Set.Prod import Mathlib.Logic.Function.Conjugate /-! # Functions over sets ## Main definitions ### Predicate * `Set.EqOn f₁ f₂ s` : functions `f₁` and `f₂` are equal at every point of `s`; * `Set.MapsTo f s t` : `f` sends every point of `s` to a point of `t`; * `Set.InjOn f s` : restriction of `f` to `s` is injective; * `Set.SurjOn f s t` : every point in `s` has a preimage in `s`; * `Set.BijOn f s t` : `f` is a bijection between `s` and `t`; * `Set.LeftInvOn f' f s` : for every `x ∈ s` we have `f' (f x) = x`; * `Set.RightInvOn f' f t` : for every `y ∈ t` we have `f (f' y) = y`; * `Set.InvOn f' f s t` : `f'` is a two-side inverse of `f` on `s` and `t`, i.e. we have `Set.LeftInvOn f' f s` and `Set.RightInvOn f' f t`. ### Functions * `Set.restrict f s` : restrict the domain of `f` to the set `s`; * `Set.codRestrict f s h` : given `h : ∀ x, f x ∈ s`, restrict the codomain of `f` to the set `s`; * `Set.MapsTo.restrict f s t h`: given `h : MapsTo f s t`, restrict the domain of `f` to `s` and the codomain to `t`. -/ variable {α β γ : Type*} {ι : Sort*} {π : α → Type*} open Equiv Equiv.Perm Function namespace Set /-! ### Restrict -/ section restrict /-- Restrict domain of a function `f` to a set `s`. Same as `Subtype.restrict` but this version takes an argument `↥s` instead of `Subtype s`. -/ def restrict (s : Set α) (f : ∀ a : α, π a) : ∀ a : s, π a := fun x => f x theorem restrict_eq (f : α → β) (s : Set α) : s.restrict f = f ∘ Subtype.val := rfl @[simp] theorem restrict_apply (f : α → β) (s : Set α) (x : s) : s.restrict f x = f x := rfl theorem restrict_eq_iff {f : ∀ a, π a} {s : Set α} {g : ∀ a : s, π a} : restrict s f = g ↔ ∀ (a) (ha : a ∈ s), f a = g ⟨a, ha⟩ := funext_iff.trans Subtype.forall theorem eq_restrict_iff {s : Set α} {f : ∀ a : s, π a} {g : ∀ a, π a} : f = restrict s g ↔ ∀ (a) (ha : a ∈ s), f ⟨a, ha⟩ = g a := funext_iff.trans Subtype.forall @[simp] theorem range_restrict (f : α → β) (s : Set α) : Set.range (s.restrict f) = f '' s := (range_comp _ _).trans <| congr_arg (f '' ·) Subtype.range_coe theorem image_restrict (f : α → β) (s t : Set α) : s.restrict f '' (Subtype.val ⁻¹' t) = f '' (t ∩ s) := by rw [restrict_eq, image_comp, image_preimage_eq_inter_range, Subtype.range_coe] @[simp] theorem restrict_dite {s : Set α} [∀ x, Decidable (x ∈ s)] (f : ∀ a ∈ s, β) (g : ∀ a ∉ s, β) : (s.restrict fun a => if h : a ∈ s then f a h else g a h) = (fun a : s => f a a.2) := funext fun a => dif_pos a.2 @[simp] theorem restrict_dite_compl {s : Set α} [∀ x, Decidable (x ∈ s)] (f : ∀ a ∈ s, β) (g : ∀ a ∉ s, β) : (sᶜ.restrict fun a => if h : a ∈ s then f a h else g a h) = (fun a : (sᶜ : Set α) => g a a.2) := funext fun a => dif_neg a.2 @[simp] theorem restrict_ite (f g : α → β) (s : Set α) [∀ x, Decidable (x ∈ s)] : (s.restrict fun a => if a ∈ s then f a else g a) = s.restrict f := restrict_dite _ _ @[simp] theorem restrict_ite_compl (f g : α → β) (s : Set α) [∀ x, Decidable (x ∈ s)] : (sᶜ.restrict fun a => if a ∈ s then f a else g a) = sᶜ.restrict g := restrict_dite_compl _ _ @[simp] theorem restrict_piecewise (f g : α → β) (s : Set α) [∀ x, Decidable (x ∈ s)] : s.restrict (piecewise s f g) = s.restrict f := restrict_ite _ _ _ @[simp] theorem restrict_piecewise_compl (f g : α → β) (s : Set α) [∀ x, Decidable (x ∈ s)] : sᶜ.restrict (piecewise s f g) = sᶜ.restrict g := restrict_ite_compl _ _ _ theorem restrict_extend_range (f : α → β) (g : α → γ) (g' : β → γ) : (range f).restrict (extend f g g') = fun x => g x.coe_prop.choose := by classical exact restrict_dite _ _ @[simp] theorem restrict_extend_compl_range (f : α → β) (g : α → γ) (g' : β → γ) : (range f)ᶜ.restrict (extend f g g') = g' ∘ Subtype.val := by classical exact restrict_dite_compl _ _ theorem range_extend_subset (f : α → β) (g : α → γ) (g' : β → γ) : range (extend f g g') ⊆ range g ∪ g' '' (range f)ᶜ := by classical rintro _ ⟨y, rfl⟩ rw [extend_def] split_ifs with h exacts [Or.inl (mem_range_self _), Or.inr (mem_image_of_mem _ h)] theorem range_extend {f : α → β} (hf : Injective f) (g : α → γ) (g' : β → γ) : range (extend f g g') = range g ∪ g' '' (range f)ᶜ := by refine (range_extend_subset _ _ _).antisymm ?_ rintro z (⟨x, rfl⟩ | ⟨y, hy, rfl⟩) exacts [⟨f x, hf.extend_apply _ _ _⟩, ⟨y, extend_apply' _ _ _ hy⟩] /-- Restrict codomain of a function `f` to a set `s`. Same as `Subtype.coind` but this version has codomain `↥s` instead of `Subtype s`. -/ def codRestrict (f : ι → α) (s : Set α) (h : ∀ x, f x ∈ s) : ι → s := fun x => ⟨f x, h x⟩ @[simp] theorem val_codRestrict_apply (f : ι → α) (s : Set α) (h : ∀ x, f x ∈ s) (x : ι) : (codRestrict f s h x : α) = f x := rfl @[simp] theorem restrict_comp_codRestrict {f : ι → α} {g : α → β} {b : Set α} (h : ∀ x, f x ∈ b) : b.restrict g ∘ b.codRestrict f h = g ∘ f := rfl @[simp] theorem injective_codRestrict {f : ι → α} {s : Set α} (h : ∀ x, f x ∈ s) : Injective (codRestrict f s h) ↔ Injective f := by simp only [Injective, Subtype.ext_iff, val_codRestrict_apply] alias ⟨_, _root_.Function.Injective.codRestrict⟩ := injective_codRestrict end restrict /-! ### Equality on a set -/ section equality variable {s s₁ s₂ : Set α} {t t₁ t₂ : Set β} {p : Set γ} {f f₁ f₂ f₃ : α → β} {g g₁ g₂ : β → γ} {f' f₁' f₂' : β → α} {g' : γ → β} {a : α} {b : β} @[simp] theorem eqOn_empty (f₁ f₂ : α → β) : EqOn f₁ f₂ ∅ := fun _ => False.elim @[simp] theorem eqOn_singleton : Set.EqOn f₁ f₂ {a} ↔ f₁ a = f₂ a := by simp [Set.EqOn] @[simp] theorem eqOn_univ (f₁ f₂ : α → β) : EqOn f₁ f₂ univ ↔ f₁ = f₂ := by simp [EqOn, funext_iff] @[simp] theorem restrict_eq_restrict_iff : restrict s f₁ = restrict s f₂ ↔ EqOn f₁ f₂ s := restrict_eq_iff @[symm] theorem EqOn.symm (h : EqOn f₁ f₂ s) : EqOn f₂ f₁ s := fun _ hx => (h hx).symm theorem eqOn_comm : EqOn f₁ f₂ s ↔ EqOn f₂ f₁ s := ⟨EqOn.symm, EqOn.symm⟩ -- This can not be tagged as `@[refl]` with the current argument order. -- See note below at `EqOn.trans`. theorem eqOn_refl (f : α → β) (s : Set α) : EqOn f f s := fun _ _ => rfl -- Note: this was formerly tagged with `@[trans]`, and although the `trans` attribute accepted it -- the `trans` tactic could not use it. -- An update to the trans tactic coming in mathlib4#7014 will reject this attribute. -- It can be restored by changing the argument order from `EqOn f₁ f₂ s` to `EqOn s f₁ f₂`. -- This change will be made separately: [zulip](https://leanprover.zulipchat.com/#narrow/stream/287929-mathlib4/topic/Reordering.20arguments.20of.20.60Set.2EEqOn.60/near/390467581). theorem EqOn.trans (h₁ : EqOn f₁ f₂ s) (h₂ : EqOn f₂ f₃ s) : EqOn f₁ f₃ s := fun _ hx => (h₁ hx).trans (h₂ hx) theorem EqOn.image_eq (heq : EqOn f₁ f₂ s) : f₁ '' s = f₂ '' s := image_congr heq /-- Variant of `EqOn.image_eq`, for one function being the identity. -/ theorem EqOn.image_eq_self {f : α → α} (h : Set.EqOn f id s) : f '' s = s := by rw [h.image_eq, image_id] theorem EqOn.inter_preimage_eq (heq : EqOn f₁ f₂ s) (t : Set β) : s ∩ f₁ ⁻¹' t = s ∩ f₂ ⁻¹' t := ext fun x => and_congr_right_iff.2 fun hx => by rw [mem_preimage, mem_preimage, heq hx] theorem EqOn.mono (hs : s₁ ⊆ s₂) (hf : EqOn f₁ f₂ s₂) : EqOn f₁ f₂ s₁ := fun _ hx => hf (hs hx) @[simp] theorem eqOn_union : EqOn f₁ f₂ (s₁ ∪ s₂) ↔ EqOn f₁ f₂ s₁ ∧ EqOn f₁ f₂ s₂ := forall₂_or_left theorem EqOn.union (h₁ : EqOn f₁ f₂ s₁) (h₂ : EqOn f₁ f₂ s₂) : EqOn f₁ f₂ (s₁ ∪ s₂) := eqOn_union.2 ⟨h₁, h₂⟩ theorem EqOn.comp_left (h : s.EqOn f₁ f₂) : s.EqOn (g ∘ f₁) (g ∘ f₂) := fun _ ha => congr_arg _ <| h ha @[simp] theorem eqOn_range {ι : Sort*} {f : ι → α} {g₁ g₂ : α → β} : EqOn g₁ g₂ (range f) ↔ g₁ ∘ f = g₂ ∘ f := forall_mem_range.trans <| funext_iff.symm alias ⟨EqOn.comp_eq, _⟩ := eqOn_range end equality /-! ### Congruence lemmas for monotonicity and antitonicity -/ section Order variable {s : Set α} {f₁ f₂ : α → β} [Preorder α] [Preorder β] theorem _root_.MonotoneOn.congr (h₁ : MonotoneOn f₁ s) (h : s.EqOn f₁ f₂) : MonotoneOn f₂ s := by intro a ha b hb hab rw [← h ha, ← h hb] exact h₁ ha hb hab theorem _root_.AntitoneOn.congr (h₁ : AntitoneOn f₁ s) (h : s.EqOn f₁ f₂) : AntitoneOn f₂ s := h₁.dual_right.congr h theorem _root_.StrictMonoOn.congr (h₁ : StrictMonoOn f₁ s) (h : s.EqOn f₁ f₂) : StrictMonoOn f₂ s := by intro a ha b hb hab rw [← h ha, ← h hb] exact h₁ ha hb hab theorem _root_.StrictAntiOn.congr (h₁ : StrictAntiOn f₁ s) (h : s.EqOn f₁ f₂) : StrictAntiOn f₂ s := h₁.dual_right.congr h theorem EqOn.congr_monotoneOn (h : s.EqOn f₁ f₂) : MonotoneOn f₁ s ↔ MonotoneOn f₂ s := ⟨fun h₁ => h₁.congr h, fun h₂ => h₂.congr h.symm⟩ theorem EqOn.congr_antitoneOn (h : s.EqOn f₁ f₂) : AntitoneOn f₁ s ↔ AntitoneOn f₂ s := ⟨fun h₁ => h₁.congr h, fun h₂ => h₂.congr h.symm⟩ theorem EqOn.congr_strictMonoOn (h : s.EqOn f₁ f₂) : StrictMonoOn f₁ s ↔ StrictMonoOn f₂ s := ⟨fun h₁ => h₁.congr h, fun h₂ => h₂.congr h.symm⟩ theorem EqOn.congr_strictAntiOn (h : s.EqOn f₁ f₂) : StrictAntiOn f₁ s ↔ StrictAntiOn f₂ s := ⟨fun h₁ => h₁.congr h, fun h₂ => h₂.congr h.symm⟩ end Order /-! ### Monotonicity lemmas-/ section Mono variable {s s₁ s₂ : Set α} {f f₁ f₂ : α → β} [Preorder α] [Preorder β] theorem _root_.MonotoneOn.mono (h : MonotoneOn f s) (h' : s₂ ⊆ s) : MonotoneOn f s₂ := fun _ hx _ hy => h (h' hx) (h' hy) theorem _root_.AntitoneOn.mono (h : AntitoneOn f s) (h' : s₂ ⊆ s) : AntitoneOn f s₂ := fun _ hx _ hy => h (h' hx) (h' hy) theorem _root_.StrictMonoOn.mono (h : StrictMonoOn f s) (h' : s₂ ⊆ s) : StrictMonoOn f s₂ := fun _ hx _ hy => h (h' hx) (h' hy) theorem _root_.StrictAntiOn.mono (h : StrictAntiOn f s) (h' : s₂ ⊆ s) : StrictAntiOn f s₂ := fun _ hx _ hy => h (h' hx) (h' hy) protected theorem _root_.MonotoneOn.monotone (h : MonotoneOn f s) : Monotone (f ∘ Subtype.val : s → β) := fun x y hle => h x.coe_prop y.coe_prop hle protected theorem _root_.AntitoneOn.monotone (h : AntitoneOn f s) : Antitone (f ∘ Subtype.val : s → β) := fun x y hle => h x.coe_prop y.coe_prop hle protected theorem _root_.StrictMonoOn.strictMono (h : StrictMonoOn f s) : StrictMono (f ∘ Subtype.val : s → β) := fun x y hlt => h x.coe_prop y.coe_prop hlt protected theorem _root_.StrictAntiOn.strictAnti (h : StrictAntiOn f s) : StrictAnti (f ∘ Subtype.val : s → β) := fun x y hlt => h x.coe_prop y.coe_prop hlt end Mono variable {s s₁ s₂ : Set α} {t t₁ t₂ : Set β} {p : Set γ} {f f₁ f₂ f₃ : α → β} {g g₁ g₂ : β → γ} {f' f₁' f₂' : β → α} {g' : γ → β} {a : α} {b : β} section MapsTo theorem MapsTo.restrict_commutes (f : α → β) (s : Set α) (t : Set β) (h : MapsTo f s t) : Subtype.val ∘ h.restrict f s t = f ∘ Subtype.val := rfl @[simp] theorem MapsTo.val_restrict_apply (h : MapsTo f s t) (x : s) : (h.restrict f s t x : β) = f x := rfl theorem MapsTo.coe_iterate_restrict {f : α → α} (h : MapsTo f s s) (x : s) (k : ℕ) : h.restrict^[k] x = f^[k] x := by induction' k with k ih; · simp simp only [iterate_succ', comp_apply, val_restrict_apply, ih] /-- Restricting the domain and then the codomain is the same as `MapsTo.restrict`. -/ @[simp] theorem codRestrict_restrict (h : ∀ x : s, f x ∈ t) : codRestrict (s.restrict f) t h = MapsTo.restrict f s t fun x hx => h ⟨x, hx⟩ := rfl /-- Reverse of `Set.codRestrict_restrict`. -/ theorem MapsTo.restrict_eq_codRestrict (h : MapsTo f s t) : h.restrict f s t = codRestrict (s.restrict f) t fun x => h x.2 := rfl theorem MapsTo.coe_restrict (h : Set.MapsTo f s t) : Subtype.val ∘ h.restrict f s t = s.restrict f := rfl theorem MapsTo.range_restrict (f : α → β) (s : Set α) (t : Set β) (h : MapsTo f s t) : range (h.restrict f s t) = Subtype.val ⁻¹' (f '' s) := Set.range_subtype_map f h theorem mapsTo_iff_exists_map_subtype : MapsTo f s t ↔ ∃ g : s → t, ∀ x : s, f x = g x := ⟨fun h => ⟨h.restrict f s t, fun _ => rfl⟩, fun ⟨g, hg⟩ x hx => by erw [hg ⟨x, hx⟩] apply Subtype.coe_prop⟩ theorem mapsTo' : MapsTo f s t ↔ f '' s ⊆ t := image_subset_iff.symm theorem mapsTo_prod_map_diagonal : MapsTo (Prod.map f f) (diagonal α) (diagonal β) := diagonal_subset_iff.2 fun _ => rfl theorem MapsTo.subset_preimage {f : α → β} {s : Set α} {t : Set β} (hf : MapsTo f s t) : s ⊆ f ⁻¹' t := hf @[simp] theorem mapsTo_singleton {x : α} : MapsTo f {x} t ↔ f x ∈ t := singleton_subset_iff theorem mapsTo_empty (f : α → β) (t : Set β) : MapsTo f ∅ t := empty_subset _ @[simp] theorem mapsTo_empty_iff : MapsTo f s ∅ ↔ s = ∅ := by simp [mapsTo', subset_empty_iff] /-- If `f` maps `s` to `t` and `s` is non-empty, `t` is non-empty. -/ theorem MapsTo.nonempty (h : MapsTo f s t) (hs : s.Nonempty) : t.Nonempty := (hs.image f).mono (mapsTo'.mp h) theorem MapsTo.image_subset (h : MapsTo f s t) : f '' s ⊆ t := mapsTo'.1 h theorem MapsTo.congr (h₁ : MapsTo f₁ s t) (h : EqOn f₁ f₂ s) : MapsTo f₂ s t := fun _ hx => h hx ▸ h₁ hx theorem EqOn.comp_right (hg : t.EqOn g₁ g₂) (hf : s.MapsTo f t) : s.EqOn (g₁ ∘ f) (g₂ ∘ f) := fun _ ha => hg <| hf ha theorem EqOn.mapsTo_iff (H : EqOn f₁ f₂ s) : MapsTo f₁ s t ↔ MapsTo f₂ s t := ⟨fun h => h.congr H, fun h => h.congr H.symm⟩ theorem MapsTo.comp (h₁ : MapsTo g t p) (h₂ : MapsTo f s t) : MapsTo (g ∘ f) s p := fun _ h => h₁ (h₂ h) theorem mapsTo_id (s : Set α) : MapsTo id s s := fun _ => id theorem MapsTo.iterate {f : α → α} {s : Set α} (h : MapsTo f s s) : ∀ n, MapsTo f^[n] s s | 0 => fun _ => id | n + 1 => (MapsTo.iterate h n).comp h theorem MapsTo.iterate_restrict {f : α → α} {s : Set α} (h : MapsTo f s s) (n : ℕ) : (h.restrict f s s)^[n] = (h.iterate n).restrict _ _ _ := by funext x rw [Subtype.ext_iff, MapsTo.val_restrict_apply] induction' n with n ihn generalizing x · rfl · simp [Nat.iterate, ihn] lemma mapsTo_of_subsingleton' [Subsingleton β] (f : α → β) (h : s.Nonempty → t.Nonempty) : MapsTo f s t := fun a ha ↦ Subsingleton.mem_iff_nonempty.2 <| h ⟨a, ha⟩ lemma mapsTo_of_subsingleton [Subsingleton α] (f : α → α) (s : Set α) : MapsTo f s s := mapsTo_of_subsingleton' _ id theorem MapsTo.mono (hf : MapsTo f s₁ t₁) (hs : s₂ ⊆ s₁) (ht : t₁ ⊆ t₂) : MapsTo f s₂ t₂ := fun _ hx => ht (hf <| hs hx) theorem MapsTo.mono_left (hf : MapsTo f s₁ t) (hs : s₂ ⊆ s₁) : MapsTo f s₂ t := fun _ hx => hf (hs hx) theorem MapsTo.mono_right (hf : MapsTo f s t₁) (ht : t₁ ⊆ t₂) : MapsTo f s t₂ := fun _ hx => ht (hf hx) theorem MapsTo.union_union (h₁ : MapsTo f s₁ t₁) (h₂ : MapsTo f s₂ t₂) : MapsTo f (s₁ ∪ s₂) (t₁ ∪ t₂) := fun _ hx => hx.elim (fun hx => Or.inl <| h₁ hx) fun hx => Or.inr <| h₂ hx theorem MapsTo.union (h₁ : MapsTo f s₁ t) (h₂ : MapsTo f s₂ t) : MapsTo f (s₁ ∪ s₂) t := union_self t ▸ h₁.union_union h₂ @[simp] theorem mapsTo_union : MapsTo f (s₁ ∪ s₂) t ↔ MapsTo f s₁ t ∧ MapsTo f s₂ t := ⟨fun h => ⟨h.mono subset_union_left (Subset.refl t), h.mono subset_union_right (Subset.refl t)⟩, fun h => h.1.union h.2⟩ theorem MapsTo.inter (h₁ : MapsTo f s t₁) (h₂ : MapsTo f s t₂) : MapsTo f s (t₁ ∩ t₂) := fun _ hx => ⟨h₁ hx, h₂ hx⟩ theorem MapsTo.inter_inter (h₁ : MapsTo f s₁ t₁) (h₂ : MapsTo f s₂ t₂) : MapsTo f (s₁ ∩ s₂) (t₁ ∩ t₂) := fun _ hx => ⟨h₁ hx.1, h₂ hx.2⟩ @[simp] theorem mapsTo_inter : MapsTo f s (t₁ ∩ t₂) ↔ MapsTo f s t₁ ∧ MapsTo f s t₂ := ⟨fun h => ⟨h.mono (Subset.refl s) inter_subset_left, h.mono (Subset.refl s) inter_subset_right⟩, fun h => h.1.inter h.2⟩ theorem mapsTo_univ (f : α → β) (s : Set α) : MapsTo f s univ := fun _ _ => trivial theorem mapsTo_range (f : α → β) (s : Set α) : MapsTo f s (range f) := (mapsTo_image f s).mono (Subset.refl s) (image_subset_range _ _) @[simp] theorem mapsTo_image_iff {f : α → β} {g : γ → α} {s : Set γ} {t : Set β} : MapsTo f (g '' s) t ↔ MapsTo (f ∘ g) s t := ⟨fun h c hc => h ⟨c, hc, rfl⟩, fun h _ ⟨_, hc⟩ => hc.2 ▸ h hc.1⟩ @[deprecated (since := "2023-12-25")] lemma maps_image_to (f : α → β) (g : γ → α) (s : Set γ) (t : Set β) : MapsTo f (g '' s) t ↔ MapsTo (f ∘ g) s t := mapsTo_image_iff lemma MapsTo.comp_left (g : β → γ) (hf : MapsTo f s t) : MapsTo (g ∘ f) s (g '' t) := fun x hx ↦ ⟨f x, hf hx, rfl⟩ lemma MapsTo.comp_right {s : Set β} {t : Set γ} (hg : MapsTo g s t) (f : α → β) : MapsTo (g ∘ f) (f ⁻¹' s) t := fun _ hx ↦ hg hx @[simp] lemma mapsTo_univ_iff : MapsTo f univ t ↔ ∀ x, f x ∈ t := ⟨fun h _ => h (mem_univ _), fun h x _ => h x⟩ @[deprecated (since := "2023-12-25")] theorem maps_univ_to (f : α → β) (s : Set β) : MapsTo f univ s ↔ ∀ a, f a ∈ s := mapsTo_univ_iff @[simp] lemma mapsTo_range_iff {g : ι → α} : MapsTo f (range g) t ↔ ∀ i, f (g i) ∈ t := forall_mem_range @[deprecated mapsTo_range_iff (since := "2023-12-25")] theorem maps_range_to (f : α → β) (g : γ → α) (s : Set β) : MapsTo f (range g) s ↔ MapsTo (f ∘ g) univ s := by rw [← image_univ, mapsTo_image_iff] theorem surjective_mapsTo_image_restrict (f : α → β) (s : Set α) : Surjective ((mapsTo_image f s).restrict f s (f '' s)) := fun ⟨_, x, hs, hxy⟩ => ⟨⟨x, hs⟩, Subtype.ext hxy⟩ theorem MapsTo.mem_iff (h : MapsTo f s t) (hc : MapsTo f sᶜ tᶜ) {x} : f x ∈ t ↔ x ∈ s := ⟨fun ht => by_contra fun hs => hc hs ht, fun hx => h hx⟩ end MapsTo /-! ### Restriction onto preimage -/ section variable (t) variable (f s) in theorem image_restrictPreimage : t.restrictPreimage f '' (Subtype.val ⁻¹' s) = Subtype.val ⁻¹' (f '' s) := by delta Set.restrictPreimage rw [← (Subtype.coe_injective).image_injective.eq_iff, ← image_comp, MapsTo.restrict_commutes, image_comp, Subtype.image_preimage_coe, Subtype.image_preimage_coe, image_preimage_inter] variable (f) in theorem range_restrictPreimage : range (t.restrictPreimage f) = Subtype.val ⁻¹' range f := by simp only [← image_univ, ← image_restrictPreimage, preimage_univ] @[simp] theorem restrictPreimage_mk (h : a ∈ f ⁻¹' t) : t.restrictPreimage f ⟨a, h⟩ = ⟨f a, h⟩ := rfl theorem image_val_preimage_restrictPreimage {u : Set t} : Subtype.val '' (t.restrictPreimage f ⁻¹' u) = f ⁻¹' (Subtype.val '' u) := by ext simp theorem preimage_restrictPreimage {u : Set t} : t.restrictPreimage f ⁻¹' u = (fun a : f ⁻¹' t ↦ f a) ⁻¹' (Subtype.val '' u) := by rw [← preimage_preimage (g := f) (f := Subtype.val), ← image_val_preimage_restrictPreimage, preimage_image_eq _ Subtype.val_injective] variable {U : ι → Set β} lemma restrictPreimage_injective (hf : Injective f) : Injective (t.restrictPreimage f) := fun _ _ e => Subtype.coe_injective <| hf <| Subtype.mk.inj e lemma restrictPreimage_surjective (hf : Surjective f) : Surjective (t.restrictPreimage f) := fun x => ⟨⟨_, ((hf x).choose_spec.symm ▸ x.2 : _ ∈ t)⟩, Subtype.ext (hf x).choose_spec⟩ lemma restrictPreimage_bijective (hf : Bijective f) : Bijective (t.restrictPreimage f) := ⟨t.restrictPreimage_injective hf.1, t.restrictPreimage_surjective hf.2⟩ alias _root_.Function.Injective.restrictPreimage := Set.restrictPreimage_injective alias _root_.Function.Surjective.restrictPreimage := Set.restrictPreimage_surjective alias _root_.Function.Bijective.restrictPreimage := Set.restrictPreimage_bijective end /-! ### Injectivity on a set -/ section injOn theorem Subsingleton.injOn (hs : s.Subsingleton) (f : α → β) : InjOn f s := fun _ hx _ hy _ => hs hx hy @[simp] theorem injOn_empty (f : α → β) : InjOn f ∅ := subsingleton_empty.injOn f @[simp] theorem injOn_singleton (f : α → β) (a : α) : InjOn f {a} := subsingleton_singleton.injOn f @[simp] lemma injOn_pair {b : α} : InjOn f {a, b} ↔ f a = f b → a = b := by unfold InjOn; aesop theorem InjOn.eq_iff {x y} (h : InjOn f s) (hx : x ∈ s) (hy : y ∈ s) : f x = f y ↔ x = y := ⟨h hx hy, fun h => h ▸ rfl⟩ theorem InjOn.ne_iff {x y} (h : InjOn f s) (hx : x ∈ s) (hy : y ∈ s) : f x ≠ f y ↔ x ≠ y := (h.eq_iff hx hy).not alias ⟨_, InjOn.ne⟩ := InjOn.ne_iff theorem InjOn.congr (h₁ : InjOn f₁ s) (h : EqOn f₁ f₂ s) : InjOn f₂ s := fun _ hx _ hy => h hx ▸ h hy ▸ h₁ hx hy theorem EqOn.injOn_iff (H : EqOn f₁ f₂ s) : InjOn f₁ s ↔ InjOn f₂ s := ⟨fun h => h.congr H, fun h => h.congr H.symm⟩ theorem InjOn.mono (h : s₁ ⊆ s₂) (ht : InjOn f s₂) : InjOn f s₁ := fun _ hx _ hy H => ht (h hx) (h hy) H theorem injOn_union (h : Disjoint s₁ s₂) : InjOn f (s₁ ∪ s₂) ↔ InjOn f s₁ ∧ InjOn f s₂ ∧ ∀ x ∈ s₁, ∀ y ∈ s₂, f x ≠ f y := by refine ⟨fun H => ⟨H.mono subset_union_left, H.mono subset_union_right, ?_⟩, ?_⟩ · intro x hx y hy hxy obtain rfl : x = y := H (Or.inl hx) (Or.inr hy) hxy exact h.le_bot ⟨hx, hy⟩ · rintro ⟨h₁, h₂, h₁₂⟩ rintro x (hx | hx) y (hy | hy) hxy exacts [h₁ hx hy hxy, (h₁₂ _ hx _ hy hxy).elim, (h₁₂ _ hy _ hx hxy.symm).elim, h₂ hx hy hxy] theorem injOn_insert {f : α → β} {s : Set α} {a : α} (has : a ∉ s) : Set.InjOn f (insert a s) ↔ Set.InjOn f s ∧ f a ∉ f '' s := by rw [← union_singleton, injOn_union (disjoint_singleton_right.2 has)] simp theorem injective_iff_injOn_univ : Injective f ↔ InjOn f univ := ⟨fun h _ _ _ _ hxy => h hxy, fun h _ _ heq => h trivial trivial heq⟩ theorem injOn_of_injective (h : Injective f) {s : Set α} : InjOn f s := fun _ _ _ _ hxy => h hxy alias _root_.Function.Injective.injOn := injOn_of_injective -- A specialization of `injOn_of_injective` for `Subtype.val`. theorem injOn_subtype_val {s : Set { x // p x }} : Set.InjOn Subtype.val s := Subtype.coe_injective.injOn lemma injOn_id (s : Set α) : InjOn id s := injective_id.injOn theorem InjOn.comp (hg : InjOn g t) (hf : InjOn f s) (h : MapsTo f s t) : InjOn (g ∘ f) s := fun _ hx _ hy heq => hf hx hy <| hg (h hx) (h hy) heq lemma InjOn.image_of_comp (h : InjOn (g ∘ f) s) : InjOn g (f '' s) := forall_mem_image.2 fun _x hx ↦ forall_mem_image.2 fun _y hy heq ↦ congr_arg f <| h hx hy heq lemma InjOn.iterate {f : α → α} {s : Set α} (h : InjOn f s) (hf : MapsTo f s s) : ∀ n, InjOn f^[n] s | 0 => injOn_id _ | (n + 1) => (h.iterate hf n).comp h hf lemma injOn_of_subsingleton [Subsingleton α] (f : α → β) (s : Set α) : InjOn f s := (injective_of_subsingleton _).injOn theorem _root_.Function.Injective.injOn_range (h : Injective (g ∘ f)) : InjOn g (range f) := by rintro _ ⟨x, rfl⟩ _ ⟨y, rfl⟩ H exact congr_arg f (h H) theorem injOn_iff_injective : InjOn f s ↔ Injective (s.restrict f) := ⟨fun H a b h => Subtype.eq <| H a.2 b.2 h, fun H a as b bs h => congr_arg Subtype.val <| @H ⟨a, as⟩ ⟨b, bs⟩ h⟩ alias ⟨InjOn.injective, _⟩ := Set.injOn_iff_injective theorem MapsTo.restrict_inj (h : MapsTo f s t) : Injective (h.restrict f s t) ↔ InjOn f s := by rw [h.restrict_eq_codRestrict, injective_codRestrict, injOn_iff_injective] theorem exists_injOn_iff_injective [Nonempty β] : (∃ f : α → β, InjOn f s) ↔ ∃ f : s → β, Injective f := ⟨fun ⟨f, hf⟩ => ⟨_, hf.injective⟩, fun ⟨f, hf⟩ => by lift f to α → β using trivial exact ⟨f, injOn_iff_injective.2 hf⟩⟩ theorem injOn_preimage {B : Set (Set β)} (hB : B ⊆ 𝒫 range f) : InjOn (preimage f) B := fun s hs t ht hst => (preimage_eq_preimage' (@hB s hs) (@hB t ht)).1 hst -- Porting note: is there a semi-implicit variable problem with `⊆`? theorem InjOn.mem_of_mem_image {x} (hf : InjOn f s) (hs : s₁ ⊆ s) (h : x ∈ s) (h₁ : f x ∈ f '' s₁) : x ∈ s₁ := let ⟨_, h', Eq⟩ := h₁ hf (hs h') h Eq ▸ h' theorem InjOn.mem_image_iff {x} (hf : InjOn f s) (hs : s₁ ⊆ s) (hx : x ∈ s) : f x ∈ f '' s₁ ↔ x ∈ s₁ := ⟨hf.mem_of_mem_image hs hx, mem_image_of_mem f⟩ theorem InjOn.preimage_image_inter (hf : InjOn f s) (hs : s₁ ⊆ s) : f ⁻¹' (f '' s₁) ∩ s = s₁ := ext fun _ => ⟨fun ⟨h₁, h₂⟩ => hf.mem_of_mem_image hs h₂ h₁, fun h => ⟨mem_image_of_mem _ h, hs h⟩⟩ theorem EqOn.cancel_left (h : s.EqOn (g ∘ f₁) (g ∘ f₂)) (hg : t.InjOn g) (hf₁ : s.MapsTo f₁ t) (hf₂ : s.MapsTo f₂ t) : s.EqOn f₁ f₂ := fun _ ha => hg (hf₁ ha) (hf₂ ha) (h ha) theorem InjOn.cancel_left (hg : t.InjOn g) (hf₁ : s.MapsTo f₁ t) (hf₂ : s.MapsTo f₂ t) : s.EqOn (g ∘ f₁) (g ∘ f₂) ↔ s.EqOn f₁ f₂ := ⟨fun h => h.cancel_left hg hf₁ hf₂, EqOn.comp_left⟩ lemma InjOn.image_inter {s t u : Set α} (hf : u.InjOn f) (hs : s ⊆ u) (ht : t ⊆ u) : f '' (s ∩ t) = f '' s ∩ f '' t := by apply Subset.antisymm (image_inter_subset _ _ _) intro x ⟨⟨y, ys, hy⟩, ⟨z, zt, hz⟩⟩ have : y = z := by apply hf (hs ys) (ht zt) rwa [← hz] at hy rw [← this] at zt exact ⟨y, ⟨ys, zt⟩, hy⟩ lemma InjOn.image (h : s.InjOn f) : s.powerset.InjOn (image f) := fun s₁ hs₁ s₂ hs₂ h' ↦ by rw [← h.preimage_image_inter hs₁, h', h.preimage_image_inter hs₂] theorem InjOn.image_eq_image_iff (h : s.InjOn f) (h₁ : s₁ ⊆ s) (h₂ : s₂ ⊆ s) : f '' s₁ = f '' s₂ ↔ s₁ = s₂ := h.image.eq_iff h₁ h₂ lemma InjOn.image_subset_image_iff (h : s.InjOn f) (h₁ : s₁ ⊆ s) (h₂ : s₂ ⊆ s) : f '' s₁ ⊆ f '' s₂ ↔ s₁ ⊆ s₂ := by refine ⟨fun h' ↦ ?_, image_subset _⟩ rw [← h.preimage_image_inter h₁, ← h.preimage_image_inter h₂] exact inter_subset_inter_left _ (preimage_mono h') lemma InjOn.image_ssubset_image_iff (h : s.InjOn f) (h₁ : s₁ ⊆ s) (h₂ : s₂ ⊆ s) : f '' s₁ ⊂ f '' s₂ ↔ s₁ ⊂ s₂ := by simp_rw [ssubset_def, h.image_subset_image_iff h₁ h₂, h.image_subset_image_iff h₂ h₁] -- TODO: can this move to a better place? theorem _root_.Disjoint.image {s t u : Set α} {f : α → β} (h : Disjoint s t) (hf : u.InjOn f) (hs : s ⊆ u) (ht : t ⊆ u) : Disjoint (f '' s) (f '' t) := by rw [disjoint_iff_inter_eq_empty] at h ⊢ rw [← hf.image_inter hs ht, h, image_empty] lemma InjOn.image_diff {t : Set α} (h : s.InjOn f) : f '' (s \ t) = f '' s \ f '' (s ∩ t) := by refine subset_antisymm (subset_diff.2 ⟨image_subset f diff_subset, ?_⟩) (diff_subset_iff.2 (by rw [← image_union, inter_union_diff])) exact Disjoint.image disjoint_sdiff_inter h diff_subset inter_subset_left lemma InjOn.image_diff_subset {f : α → β} {t : Set α} (h : InjOn f s) (hst : t ⊆ s) : f '' (s \ t) = f '' s \ f '' t := by rw [h.image_diff, inter_eq_self_of_subset_right hst] theorem InjOn.imageFactorization_injective (h : InjOn f s) : Injective (s.imageFactorization f) := fun ⟨x, hx⟩ ⟨y, hy⟩ h' ↦ by simpa [imageFactorization, h.eq_iff hx hy] using h' @[simp] theorem imageFactorization_injective_iff : Injective (s.imageFactorization f) ↔ InjOn f s := ⟨fun h x hx y hy _ ↦ by simpa using @h ⟨x, hx⟩ ⟨y, hy⟩ (by simpa [imageFactorization]), InjOn.imageFactorization_injective⟩ end injOn section graphOn @[simp] lemma graphOn_empty (f : α → β) : graphOn f ∅ = ∅ := image_empty _ @[simp] lemma graphOn_union (f : α → β) (s t : Set α) : graphOn f (s ∪ t) = graphOn f s ∪ graphOn f t := image_union .. @[simp] lemma graphOn_singleton (f : α → β) (x : α) : graphOn f {x} = {(x, f x)} := image_singleton .. @[simp] lemma graphOn_insert (f : α → β) (x : α) (s : Set α) : graphOn f (insert x s) = insert (x, f x) (graphOn f s) := image_insert_eq .. @[simp] lemma image_fst_graphOn (f : α → β) (s : Set α) : Prod.fst '' graphOn f s = s := by simp [graphOn, image_image] lemma exists_eq_graphOn_image_fst [Nonempty β] {s : Set (α × β)} : (∃ f : α → β, s = graphOn f (Prod.fst '' s)) ↔ InjOn Prod.fst s := by refine ⟨?_, fun h ↦ ?_⟩ · rintro ⟨f, hf⟩ rw [hf] exact InjOn.image_of_comp <| injOn_id _ · have : ∀ x ∈ Prod.fst '' s, ∃ y, (x, y) ∈ s := forall_mem_image.2 fun (x, y) h ↦ ⟨y, h⟩ choose! f hf using this rw [forall_mem_image] at hf use f rw [graphOn, image_image, EqOn.image_eq_self] exact fun x hx ↦ h (hf hx) hx rfl lemma exists_eq_graphOn [Nonempty β] {s : Set (α × β)} : (∃ f t, s = graphOn f t) ↔ InjOn Prod.fst s := .trans ⟨fun ⟨f, t, hs⟩ ↦ ⟨f, by rw [hs, image_fst_graphOn]⟩, fun ⟨f, hf⟩ ↦ ⟨f, _, hf⟩⟩ exists_eq_graphOn_image_fst end graphOn /-! ### Surjectivity on a set -/ section surjOn theorem SurjOn.subset_range (h : SurjOn f s t) : t ⊆ range f := Subset.trans h <| image_subset_range f s theorem surjOn_iff_exists_map_subtype : SurjOn f s t ↔ ∃ (t' : Set β) (g : s → t'), t ⊆ t' ∧ Surjective g ∧ ∀ x : s, f x = g x := ⟨fun h => ⟨_, (mapsTo_image f s).restrict f s _, h, surjective_mapsTo_image_restrict _ _, fun _ => rfl⟩, fun ⟨t', g, htt', hg, hfg⟩ y hy => let ⟨x, hx⟩ := hg ⟨y, htt' hy⟩ ⟨x, x.2, by rw [hfg, hx, Subtype.coe_mk]⟩⟩ theorem surjOn_empty (f : α → β) (s : Set α) : SurjOn f s ∅ := empty_subset _ @[simp] theorem surjOn_empty_iff : SurjOn f ∅ t ↔ t = ∅ := by simp [SurjOn, subset_empty_iff] @[simp] lemma surjOn_singleton : SurjOn f s {b} ↔ b ∈ f '' s := singleton_subset_iff theorem surjOn_image (f : α → β) (s : Set α) : SurjOn f s (f '' s) := Subset.rfl theorem SurjOn.comap_nonempty (h : SurjOn f s t) (ht : t.Nonempty) : s.Nonempty := (ht.mono h).of_image theorem SurjOn.congr (h : SurjOn f₁ s t) (H : EqOn f₁ f₂ s) : SurjOn f₂ s t := by rwa [SurjOn, ← H.image_eq] theorem EqOn.surjOn_iff (h : EqOn f₁ f₂ s) : SurjOn f₁ s t ↔ SurjOn f₂ s t := ⟨fun H => H.congr h, fun H => H.congr h.symm⟩ theorem SurjOn.mono (hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) (hf : SurjOn f s₁ t₂) : SurjOn f s₂ t₁ := Subset.trans ht <| Subset.trans hf <| image_subset _ hs theorem SurjOn.union (h₁ : SurjOn f s t₁) (h₂ : SurjOn f s t₂) : SurjOn f s (t₁ ∪ t₂) := fun _ hx => hx.elim (fun hx => h₁ hx) fun hx => h₂ hx theorem SurjOn.union_union (h₁ : SurjOn f s₁ t₁) (h₂ : SurjOn f s₂ t₂) : SurjOn f (s₁ ∪ s₂) (t₁ ∪ t₂) := (h₁.mono subset_union_left (Subset.refl _)).union (h₂.mono subset_union_right (Subset.refl _)) theorem SurjOn.inter_inter (h₁ : SurjOn f s₁ t₁) (h₂ : SurjOn f s₂ t₂) (h : InjOn f (s₁ ∪ s₂)) : SurjOn f (s₁ ∩ s₂) (t₁ ∩ t₂) := by intro y hy rcases h₁ hy.1 with ⟨x₁, hx₁, rfl⟩ rcases h₂ hy.2 with ⟨x₂, hx₂, heq⟩ obtain rfl : x₁ = x₂ := h (Or.inl hx₁) (Or.inr hx₂) heq.symm exact mem_image_of_mem f ⟨hx₁, hx₂⟩ theorem SurjOn.inter (h₁ : SurjOn f s₁ t) (h₂ : SurjOn f s₂ t) (h : InjOn f (s₁ ∪ s₂)) : SurjOn f (s₁ ∩ s₂) t := inter_self t ▸ h₁.inter_inter h₂ h -- Porting note: Why does `simp` not call `refl` by itself? lemma surjOn_id (s : Set α) : SurjOn id s s := by simp [SurjOn, subset_rfl] theorem SurjOn.comp (hg : SurjOn g t p) (hf : SurjOn f s t) : SurjOn (g ∘ f) s p := Subset.trans hg <| Subset.trans (image_subset g hf) <| image_comp g f s ▸ Subset.refl _ lemma SurjOn.iterate {f : α → α} {s : Set α} (h : SurjOn f s s) : ∀ n, SurjOn f^[n] s s | 0 => surjOn_id _ | (n + 1) => (h.iterate n).comp h lemma SurjOn.comp_left (hf : SurjOn f s t) (g : β → γ) : SurjOn (g ∘ f) s (g '' t) := by rw [SurjOn, image_comp g f]; exact image_subset _ hf lemma SurjOn.comp_right {s : Set β} {t : Set γ} (hf : Surjective f) (hg : SurjOn g s t) : SurjOn (g ∘ f) (f ⁻¹' s) t := by rwa [SurjOn, image_comp g f, image_preimage_eq _ hf] lemma surjOn_of_subsingleton' [Subsingleton β] (f : α → β) (h : t.Nonempty → s.Nonempty) : SurjOn f s t := fun _ ha ↦ Subsingleton.mem_iff_nonempty.2 <| (h ⟨_, ha⟩).image _ lemma surjOn_of_subsingleton [Subsingleton α] (f : α → α) (s : Set α) : SurjOn f s s := surjOn_of_subsingleton' _ id theorem surjective_iff_surjOn_univ : Surjective f ↔ SurjOn f univ univ := by simp [Surjective, SurjOn, subset_def] theorem surjOn_iff_surjective : SurjOn f s univ ↔ Surjective (s.restrict f) := ⟨fun H b => let ⟨a, as, e⟩ := @H b trivial ⟨⟨a, as⟩, e⟩, fun H b _ => let ⟨⟨a, as⟩, e⟩ := H b ⟨a, as, e⟩⟩ @[simp] theorem MapsTo.restrict_surjective_iff (h : MapsTo f s t) : Surjective (MapsTo.restrict _ _ _ h) ↔ SurjOn f s t := by refine ⟨fun h' b hb ↦ ?_, fun h' ⟨b, hb⟩ ↦ ?_⟩ · obtain ⟨⟨a, ha⟩, ha'⟩ := h' ⟨b, hb⟩ replace ha' : f a = b := by simpa [Subtype.ext_iff] using ha' rw [← ha'] exact mem_image_of_mem f ha · obtain ⟨a, ha, rfl⟩ := h' hb exact ⟨⟨a, ha⟩, rfl⟩ theorem SurjOn.image_eq_of_mapsTo (h₁ : SurjOn f s t) (h₂ : MapsTo f s t) : f '' s = t := eq_of_subset_of_subset h₂.image_subset h₁ theorem image_eq_iff_surjOn_mapsTo : f '' s = t ↔ s.SurjOn f t ∧ s.MapsTo f t := by refine ⟨?_, fun h => h.1.image_eq_of_mapsTo h.2⟩ rintro rfl exact ⟨s.surjOn_image f, s.mapsTo_image f⟩ lemma SurjOn.image_preimage (h : Set.SurjOn f s t) (ht : t₁ ⊆ t) : f '' (f ⁻¹' t₁) = t₁ := image_preimage_eq_iff.2 fun _ hx ↦ mem_range_of_mem_image f s <| h <| ht hx theorem SurjOn.mapsTo_compl (h : SurjOn f s t) (h' : Injective f) : MapsTo f sᶜ tᶜ := fun _ hs ht => let ⟨_, hx', HEq⟩ := h ht hs <| h' HEq ▸ hx' theorem MapsTo.surjOn_compl (h : MapsTo f s t) (h' : Surjective f) : SurjOn f sᶜ tᶜ := h'.forall.2 fun _ ht => (mem_image_of_mem _) fun hs => ht (h hs) theorem EqOn.cancel_right (hf : s.EqOn (g₁ ∘ f) (g₂ ∘ f)) (hf' : s.SurjOn f t) : t.EqOn g₁ g₂ := by intro b hb obtain ⟨a, ha, rfl⟩ := hf' hb exact hf ha theorem SurjOn.cancel_right (hf : s.SurjOn f t) (hf' : s.MapsTo f t) : s.EqOn (g₁ ∘ f) (g₂ ∘ f) ↔ t.EqOn g₁ g₂ := ⟨fun h => h.cancel_right hf, fun h => h.comp_right hf'⟩ theorem eqOn_comp_right_iff : s.EqOn (g₁ ∘ f) (g₂ ∘ f) ↔ (f '' s).EqOn g₁ g₂ := (s.surjOn_image f).cancel_right <| s.mapsTo_image f theorem SurjOn.forall {p : β → Prop} (hf : s.SurjOn f t) (hf' : s.MapsTo f t) : (∀ y ∈ t, p y) ↔ (∀ x ∈ s, p (f x)) := ⟨fun H x hx ↦ H (f x) (hf' hx), fun H _y hy ↦ let ⟨x, hx, hxy⟩ := hf hy; hxy ▸ H x hx⟩ end surjOn /-! ### Bijectivity -/ section bijOn theorem BijOn.mapsTo (h : BijOn f s t) : MapsTo f s t := h.left theorem BijOn.injOn (h : BijOn f s t) : InjOn f s := h.right.left theorem BijOn.surjOn (h : BijOn f s t) : SurjOn f s t := h.right.right theorem BijOn.mk (h₁ : MapsTo f s t) (h₂ : InjOn f s) (h₃ : SurjOn f s t) : BijOn f s t := ⟨h₁, h₂, h₃⟩ theorem bijOn_empty (f : α → β) : BijOn f ∅ ∅ := ⟨mapsTo_empty f ∅, injOn_empty f, surjOn_empty f ∅⟩ @[simp] theorem bijOn_empty_iff_left : BijOn f s ∅ ↔ s = ∅ := ⟨fun h ↦ by simpa using h.mapsTo, by rintro rfl; exact bijOn_empty f⟩ @[simp] theorem bijOn_empty_iff_right : BijOn f ∅ t ↔ t = ∅ := ⟨fun h ↦ by simpa using h.surjOn, by rintro rfl; exact bijOn_empty f⟩ @[simp] lemma bijOn_singleton : BijOn f {a} {b} ↔ f a = b := by simp [BijOn, eq_comm] theorem BijOn.inter_mapsTo (h₁ : BijOn f s₁ t₁) (h₂ : MapsTo f s₂ t₂) (h₃ : s₁ ∩ f ⁻¹' t₂ ⊆ s₂) : BijOn f (s₁ ∩ s₂) (t₁ ∩ t₂) := ⟨h₁.mapsTo.inter_inter h₂, h₁.injOn.mono inter_subset_left, fun _ hy => let ⟨x, hx, hxy⟩ := h₁.surjOn hy.1 ⟨x, ⟨hx, h₃ ⟨hx, hxy.symm.subst hy.2⟩⟩, hxy⟩⟩ theorem MapsTo.inter_bijOn (h₁ : MapsTo f s₁ t₁) (h₂ : BijOn f s₂ t₂) (h₃ : s₂ ∩ f ⁻¹' t₁ ⊆ s₁) : BijOn f (s₁ ∩ s₂) (t₁ ∩ t₂) := inter_comm s₂ s₁ ▸ inter_comm t₂ t₁ ▸ h₂.inter_mapsTo h₁ h₃ theorem BijOn.inter (h₁ : BijOn f s₁ t₁) (h₂ : BijOn f s₂ t₂) (h : InjOn f (s₁ ∪ s₂)) : BijOn f (s₁ ∩ s₂) (t₁ ∩ t₂) := ⟨h₁.mapsTo.inter_inter h₂.mapsTo, h₁.injOn.mono inter_subset_left, h₁.surjOn.inter_inter h₂.surjOn h⟩ theorem BijOn.union (h₁ : BijOn f s₁ t₁) (h₂ : BijOn f s₂ t₂) (h : InjOn f (s₁ ∪ s₂)) : BijOn f (s₁ ∪ s₂) (t₁ ∪ t₂) := ⟨h₁.mapsTo.union_union h₂.mapsTo, h, h₁.surjOn.union_union h₂.surjOn⟩ theorem BijOn.subset_range (h : BijOn f s t) : t ⊆ range f := h.surjOn.subset_range theorem InjOn.bijOn_image (h : InjOn f s) : BijOn f s (f '' s) := BijOn.mk (mapsTo_image f s) h (Subset.refl _) theorem BijOn.congr (h₁ : BijOn f₁ s t) (h : EqOn f₁ f₂ s) : BijOn f₂ s t := BijOn.mk (h₁.mapsTo.congr h) (h₁.injOn.congr h) (h₁.surjOn.congr h) theorem EqOn.bijOn_iff (H : EqOn f₁ f₂ s) : BijOn f₁ s t ↔ BijOn f₂ s t := ⟨fun h => h.congr H, fun h => h.congr H.symm⟩ theorem BijOn.image_eq (h : BijOn f s t) : f '' s = t := h.surjOn.image_eq_of_mapsTo h.mapsTo lemma BijOn.forall {p : β → Prop} (hf : BijOn f s t) : (∀ b ∈ t, p b) ↔ ∀ a ∈ s, p (f a) where mp h a ha := h _ $ hf.mapsTo ha mpr h b hb := by obtain ⟨a, ha, rfl⟩ := hf.surjOn hb; exact h _ ha lemma BijOn.exists {p : β → Prop} (hf : BijOn f s t) : (∃ b ∈ t, p b) ↔ ∃ a ∈ s, p (f a) where mp := by rintro ⟨b, hb, h⟩; obtain ⟨a, ha, rfl⟩ := hf.surjOn hb; exact ⟨a, ha, h⟩ mpr := by rintro ⟨a, ha, h⟩; exact ⟨f a, hf.mapsTo ha, h⟩ lemma _root_.Equiv.image_eq_iff_bijOn (e : α ≃ β) : e '' s = t ↔ BijOn e s t := ⟨fun h ↦ ⟨(mapsTo_image e s).mono_right h.subset, e.injective.injOn, h ▸ surjOn_image e s⟩, BijOn.image_eq⟩ lemma bijOn_id (s : Set α) : BijOn id s s := ⟨s.mapsTo_id, s.injOn_id, s.surjOn_id⟩ theorem BijOn.comp (hg : BijOn g t p) (hf : BijOn f s t) : BijOn (g ∘ f) s p := BijOn.mk (hg.mapsTo.comp hf.mapsTo) (hg.injOn.comp hf.injOn hf.mapsTo) (hg.surjOn.comp hf.surjOn) lemma BijOn.iterate {f : α → α} {s : Set α} (h : BijOn f s s) : ∀ n, BijOn f^[n] s s | 0 => s.bijOn_id | (n + 1) => (h.iterate n).comp h lemma bijOn_of_subsingleton' [Subsingleton α] [Subsingleton β] (f : α → β) (h : s.Nonempty ↔ t.Nonempty) : BijOn f s t := ⟨mapsTo_of_subsingleton' _ h.1, injOn_of_subsingleton _ _, surjOn_of_subsingleton' _ h.2⟩ lemma bijOn_of_subsingleton [Subsingleton α] (f : α → α) (s : Set α) : BijOn f s s := bijOn_of_subsingleton' _ Iff.rfl theorem BijOn.bijective (h : BijOn f s t) : Bijective (h.mapsTo.restrict f s t) := ⟨fun x y h' => Subtype.ext <| h.injOn x.2 y.2 <| Subtype.ext_iff.1 h', fun ⟨_, hy⟩ => let ⟨x, hx, hxy⟩ := h.surjOn hy ⟨⟨x, hx⟩, Subtype.eq hxy⟩⟩ theorem bijective_iff_bijOn_univ : Bijective f ↔ BijOn f univ univ := Iff.intro (fun h => let ⟨inj, surj⟩ := h ⟨mapsTo_univ f _, inj.injOn, Iff.mp surjective_iff_surjOn_univ surj⟩) fun h => let ⟨_map, inj, surj⟩ := h ⟨Iff.mpr injective_iff_injOn_univ inj, Iff.mpr surjective_iff_surjOn_univ surj⟩ alias ⟨_root_.Function.Bijective.bijOn_univ, _⟩ := bijective_iff_bijOn_univ theorem BijOn.compl (hst : BijOn f s t) (hf : Bijective f) : BijOn f sᶜ tᶜ := ⟨hst.surjOn.mapsTo_compl hf.1, hf.1.injOn, hst.mapsTo.surjOn_compl hf.2⟩ theorem BijOn.subset_right {r : Set β} (hf : BijOn f s t) (hrt : r ⊆ t) : BijOn f (s ∩ f ⁻¹' r) r := by refine ⟨inter_subset_right, hf.injOn.mono inter_subset_left, fun x hx ↦ ?_⟩ obtain ⟨y, hy, rfl⟩ := hf.surjOn (hrt hx) exact ⟨y, ⟨hy, hx⟩, rfl⟩ theorem BijOn.subset_left {r : Set α} (hf : BijOn f s t) (hrs : r ⊆ s) : BijOn f r (f '' r) := (hf.injOn.mono hrs).bijOn_image end bijOn /-! ### left inverse -/ namespace LeftInvOn theorem eqOn (h : LeftInvOn f' f s) : EqOn (f' ∘ f) id s := h theorem eq (h : LeftInvOn f' f s) {x} (hx : x ∈ s) : f' (f x) = x := h hx theorem congr_left (h₁ : LeftInvOn f₁' f s) {t : Set β} (h₁' : MapsTo f s t) (heq : EqOn f₁' f₂' t) : LeftInvOn f₂' f s := fun _ hx => heq (h₁' hx) ▸ h₁ hx theorem congr_right (h₁ : LeftInvOn f₁' f₁ s) (heq : EqOn f₁ f₂ s) : LeftInvOn f₁' f₂ s := fun _ hx => heq hx ▸ h₁ hx theorem injOn (h : LeftInvOn f₁' f s) : InjOn f s := fun x₁ h₁ x₂ h₂ heq => calc x₁ = f₁' (f x₁) := Eq.symm <| h h₁ _ = f₁' (f x₂) := congr_arg f₁' heq _ = x₂ := h h₂ theorem surjOn (h : LeftInvOn f' f s) (hf : MapsTo f s t) : SurjOn f' t s := fun x hx => ⟨f x, hf hx, h hx⟩ theorem mapsTo (h : LeftInvOn f' f s) (hf : SurjOn f s t) : MapsTo f' t s := fun y hy => by let ⟨x, hs, hx⟩ := hf hy rwa [← hx, h hs] lemma _root_.Set.leftInvOn_id (s : Set α) : LeftInvOn id id s := fun _ _ ↦ rfl theorem comp (hf' : LeftInvOn f' f s) (hg' : LeftInvOn g' g t) (hf : MapsTo f s t) : LeftInvOn (f' ∘ g') (g ∘ f) s := fun x h => calc (f' ∘ g') ((g ∘ f) x) = f' (f x) := congr_arg f' (hg' (hf h)) _ = x := hf' h theorem mono (hf : LeftInvOn f' f s) (ht : s₁ ⊆ s) : LeftInvOn f' f s₁ := fun _ hx => hf (ht hx) theorem image_inter' (hf : LeftInvOn f' f s) : f '' (s₁ ∩ s) = f' ⁻¹' s₁ ∩ f '' s := by apply Subset.antisymm · rintro _ ⟨x, ⟨h₁, h⟩, rfl⟩ exact ⟨by rwa [mem_preimage, hf h], mem_image_of_mem _ h⟩ · rintro _ ⟨h₁, ⟨x, h, rfl⟩⟩ exact mem_image_of_mem _ ⟨by rwa [← hf h], h⟩ theorem image_inter (hf : LeftInvOn f' f s) : f '' (s₁ ∩ s) = f' ⁻¹' (s₁ ∩ s) ∩ f '' s := by rw [hf.image_inter'] refine Subset.antisymm ?_ (inter_subset_inter_left _ (preimage_mono inter_subset_left)) rintro _ ⟨h₁, x, hx, rfl⟩; exact ⟨⟨h₁, by rwa [hf hx]⟩, mem_image_of_mem _ hx⟩ theorem image_image (hf : LeftInvOn f' f s) : f' '' (f '' s) = s := by rw [Set.image_image, image_congr hf, image_id'] theorem image_image' (hf : LeftInvOn f' f s) (hs : s₁ ⊆ s) : f' '' (f '' s₁) = s₁ := (hf.mono hs).image_image end LeftInvOn /-! ### Right inverse -/ section RightInvOn namespace RightInvOn theorem eqOn (h : RightInvOn f' f t) : EqOn (f ∘ f') id t := h theorem eq (h : RightInvOn f' f t) {y} (hy : y ∈ t) : f (f' y) = y := h hy theorem _root_.Set.LeftInvOn.rightInvOn_image (h : LeftInvOn f' f s) : RightInvOn f' f (f '' s) := fun _y ⟨_x, hx, heq⟩ => heq ▸ (congr_arg f <| h.eq hx) theorem congr_left (h₁ : RightInvOn f₁' f t) (heq : EqOn f₁' f₂' t) : RightInvOn f₂' f t := h₁.congr_right heq theorem congr_right (h₁ : RightInvOn f' f₁ t) (hg : MapsTo f' t s) (heq : EqOn f₁ f₂ s) : RightInvOn f' f₂ t := LeftInvOn.congr_left h₁ hg heq theorem surjOn (hf : RightInvOn f' f t) (hf' : MapsTo f' t s) : SurjOn f s t := LeftInvOn.surjOn hf hf' theorem mapsTo (h : RightInvOn f' f t) (hf : SurjOn f' t s) : MapsTo f s t := LeftInvOn.mapsTo h hf lemma _root_.Set.rightInvOn_id (s : Set α) : RightInvOn id id s := fun _ _ ↦ rfl theorem comp (hf : RightInvOn f' f t) (hg : RightInvOn g' g p) (g'pt : MapsTo g' p t) : RightInvOn (f' ∘ g') (g ∘ f) p := LeftInvOn.comp hg hf g'pt theorem mono (hf : RightInvOn f' f t) (ht : t₁ ⊆ t) : RightInvOn f' f t₁ := LeftInvOn.mono hf ht end RightInvOn theorem InjOn.rightInvOn_of_leftInvOn (hf : InjOn f s) (hf' : LeftInvOn f f' t) (h₁ : MapsTo f s t) (h₂ : MapsTo f' t s) : RightInvOn f f' s := fun _ h => hf (h₂ <| h₁ h) h (hf' (h₁ h)) theorem eqOn_of_leftInvOn_of_rightInvOn (h₁ : LeftInvOn f₁' f s) (h₂ : RightInvOn f₂' f t) (h : MapsTo f₂' t s) : EqOn f₁' f₂' t := fun y hy => calc f₁' y = (f₁' ∘ f ∘ f₂') y := congr_arg f₁' (h₂ hy).symm _ = f₂' y := h₁ (h hy) theorem SurjOn.leftInvOn_of_rightInvOn (hf : SurjOn f s t) (hf' : RightInvOn f f' s) : LeftInvOn f f' t := fun y hy => by let ⟨x, hx, heq⟩ := hf hy rw [← heq, hf' hx] end RightInvOn /-! ### Two-side inverses -/ namespace InvOn lemma _root_.Set.invOn_id (s : Set α) : InvOn id id s s := ⟨s.leftInvOn_id, s.rightInvOn_id⟩ lemma comp (hf : InvOn f' f s t) (hg : InvOn g' g t p) (fst : MapsTo f s t) (g'pt : MapsTo g' p t) : InvOn (f' ∘ g') (g ∘ f) s p := ⟨hf.1.comp hg.1 fst, hf.2.comp hg.2 g'pt⟩ @[symm] theorem symm (h : InvOn f' f s t) : InvOn f f' t s := ⟨h.right, h.left⟩ theorem mono (h : InvOn f' f s t) (hs : s₁ ⊆ s) (ht : t₁ ⊆ t) : InvOn f' f s₁ t₁ := ⟨h.1.mono hs, h.2.mono ht⟩ /-- If functions `f'` and `f` are inverse on `s` and `t`, `f` maps `s` into `t`, and `f'` maps `t` into `s`, then `f` is a bijection between `s` and `t`. The `mapsTo` arguments can be deduced from `surjOn` statements using `LeftInvOn.mapsTo` and `RightInvOn.mapsTo`. -/ theorem bijOn (h : InvOn f' f s t) (hf : MapsTo f s t) (hf' : MapsTo f' t s) : BijOn f s t := ⟨hf, h.left.injOn, h.right.surjOn hf'⟩ end InvOn end Set /-! ### `invFunOn` is a left/right inverse -/ namespace Function variable [Nonempty α] {s : Set α} {f : α → β} {a : α} {b : β} attribute [local instance] Classical.propDecidable /-- Construct the inverse for a function `f` on domain `s`. This function is a right inverse of `f` on `f '' s`. For a computable version, see `Function.Embedding.invOfMemRange`. -/ noncomputable def invFunOn (f : α → β) (s : Set α) (b : β) : α := if h : ∃ a, a ∈ s ∧ f a = b then Classical.choose h else Classical.choice ‹Nonempty α› theorem invFunOn_pos (h : ∃ a ∈ s, f a = b) : invFunOn f s b ∈ s ∧ f (invFunOn f s b) = b := by rw [invFunOn, dif_pos h] exact Classical.choose_spec h theorem invFunOn_mem (h : ∃ a ∈ s, f a = b) : invFunOn f s b ∈ s := (invFunOn_pos h).left theorem invFunOn_eq (h : ∃ a ∈ s, f a = b) : f (invFunOn f s b) = b := (invFunOn_pos h).right theorem invFunOn_neg (h : ¬∃ a ∈ s, f a = b) : invFunOn f s b = Classical.choice ‹Nonempty α› := by rw [invFunOn, dif_neg h] @[simp] theorem invFunOn_apply_mem (h : a ∈ s) : invFunOn f s (f a) ∈ s := invFunOn_mem ⟨a, h, rfl⟩ theorem invFunOn_apply_eq (h : a ∈ s) : f (invFunOn f s (f a)) = f a := invFunOn_eq ⟨a, h, rfl⟩ end Function open Function namespace Set variable {s s₁ s₂ : Set α} {t : Set β} {f : α → β} theorem InjOn.leftInvOn_invFunOn [Nonempty α] (h : InjOn f s) : LeftInvOn (invFunOn f s) f s := fun _a ha => h (invFunOn_apply_mem ha) ha (invFunOn_apply_eq ha) theorem InjOn.invFunOn_image [Nonempty α] (h : InjOn f s₂) (ht : s₁ ⊆ s₂) : invFunOn f s₂ '' (f '' s₁) = s₁ := h.leftInvOn_invFunOn.image_image' ht theorem _root_.Function.leftInvOn_invFunOn_of_subset_image_image [Nonempty α] (h : s ⊆ (invFunOn f s) '' (f '' s)) : LeftInvOn (invFunOn f s) f s := fun x hx ↦ by obtain ⟨-, ⟨x, hx', rfl⟩, rfl⟩ := h hx rw [invFunOn_apply_eq (f := f) hx'] theorem injOn_iff_invFunOn_image_image_eq_self [Nonempty α] : InjOn f s ↔ (invFunOn f s) '' (f '' s) = s := ⟨fun h ↦ h.invFunOn_image Subset.rfl, fun h ↦ (Function.leftInvOn_invFunOn_of_subset_image_image h.symm.subset).injOn⟩ theorem _root_.Function.invFunOn_injOn_image [Nonempty α] (f : α → β) (s : Set α) : Set.InjOn (invFunOn f s) (f '' s) := by rintro _ ⟨x, hx, rfl⟩ _ ⟨x', hx', rfl⟩ he rw [← invFunOn_apply_eq (f := f) hx, he, invFunOn_apply_eq (f := f) hx'] theorem _root_.Function.invFunOn_image_image_subset [Nonempty α] (f : α → β) (s : Set α) : (invFunOn f s) '' (f '' s) ⊆ s := by rintro _ ⟨_, ⟨x,hx,rfl⟩, rfl⟩; exact invFunOn_apply_mem hx theorem SurjOn.rightInvOn_invFunOn [Nonempty α] (h : SurjOn f s t) : RightInvOn (invFunOn f s) f t := fun _y hy => invFunOn_eq <| h hy theorem BijOn.invOn_invFunOn [Nonempty α] (h : BijOn f s t) : InvOn (invFunOn f s) f s t := ⟨h.injOn.leftInvOn_invFunOn, h.surjOn.rightInvOn_invFunOn⟩ theorem SurjOn.invOn_invFunOn [Nonempty α] (h : SurjOn f s t) : InvOn (invFunOn f s) f (invFunOn f s '' t) t := by refine ⟨?_, h.rightInvOn_invFunOn⟩ rintro _ ⟨y, hy, rfl⟩ rw [h.rightInvOn_invFunOn hy] theorem SurjOn.mapsTo_invFunOn [Nonempty α] (h : SurjOn f s t) : MapsTo (invFunOn f s) t s := fun _y hy => mem_preimage.2 <| invFunOn_mem <| h hy /-- This lemma is a special case of `rightInvOn_invFunOn.image_image'`; it may make more sense to use the other lemma directly in an application. -/ theorem SurjOn.image_invFunOn_image_of_subset [Nonempty α] {r : Set β} (hf : SurjOn f s t) (hrt : r ⊆ t) : f '' (f.invFunOn s '' r) = r := hf.rightInvOn_invFunOn.image_image' hrt /-- This lemma is a special case of `rightInvOn_invFunOn.image_image`; it may make more sense to use the other lemma directly in an application. -/ theorem SurjOn.image_invFunOn_image [Nonempty α] (hf : SurjOn f s t) : f '' (f.invFunOn s '' t) = t := hf.rightInvOn_invFunOn.image_image theorem SurjOn.bijOn_subset [Nonempty α] (h : SurjOn f s t) : BijOn f (invFunOn f s '' t) t := by refine h.invOn_invFunOn.bijOn ?_ (mapsTo_image _ _) rintro _ ⟨y, hy, rfl⟩ rwa [h.rightInvOn_invFunOn hy] theorem surjOn_iff_exists_bijOn_subset : SurjOn f s t ↔ ∃ s' ⊆ s, BijOn f s' t := by constructor · rcases eq_empty_or_nonempty t with (rfl | ht) · exact fun _ => ⟨∅, empty_subset _, bijOn_empty f⟩ · intro h haveI : Nonempty α := ⟨Classical.choose (h.comap_nonempty ht)⟩ exact ⟨_, h.mapsTo_invFunOn.image_subset, h.bijOn_subset⟩ · rintro ⟨s', hs', hfs'⟩ exact hfs'.surjOn.mono hs' (Subset.refl _) alias ⟨SurjOn.exists_bijOn_subset, _⟩ := Set.surjOn_iff_exists_bijOn_subset variable (f s) lemma exists_subset_bijOn : ∃ s' ⊆ s, BijOn f s' (f '' s) := surjOn_iff_exists_bijOn_subset.mp (surjOn_image f s) lemma exists_image_eq_and_injOn : ∃ u, f '' u = f '' s ∧ InjOn f u := let ⟨u, _, hfu⟩ := exists_subset_bijOn s f ⟨u, hfu.image_eq, hfu.injOn⟩ variable {f s} lemma exists_image_eq_injOn_of_subset_range (ht : t ⊆ range f) : ∃ s, f '' s = t ∧ InjOn f s := image_preimage_eq_of_subset ht ▸ exists_image_eq_and_injOn _ _ /-- If `f` maps `s` bijectively to `t` and a set `t'` is contained in the image of some `s₁ ⊇ s`, then `s₁` has a subset containing `s` that `f` maps bijectively to `t'`.-/ theorem BijOn.exists_extend_of_subset {t' : Set β} (h : BijOn f s t) (hss₁ : s ⊆ s₁) (htt' : t ⊆ t') (ht' : SurjOn f s₁ t') : ∃ s', s ⊆ s' ∧ s' ⊆ s₁ ∧ Set.BijOn f s' t' := by obtain ⟨r, hrss, hbij⟩ := exists_subset_bijOn ((s₁ ∩ f ⁻¹' t') \ f ⁻¹' t) f rw [image_diff_preimage, image_inter_preimage] at hbij refine ⟨s ∪ r, subset_union_left, ?_, ?_, ?_, fun y hyt' ↦ ?_⟩ · exact union_subset hss₁ <| hrss.trans <| diff_subset.trans inter_subset_left · rw [mapsTo', image_union, hbij.image_eq, h.image_eq, union_subset_iff] exact ⟨htt', diff_subset.trans inter_subset_right⟩ · rw [injOn_union, and_iff_right h.injOn, and_iff_right hbij.injOn] · refine fun x hxs y hyr hxy ↦ (hrss hyr).2 ?_ rw [← h.image_eq] exact ⟨x, hxs, hxy⟩ exact (subset_diff.1 hrss).2.symm.mono_left h.mapsTo rw [image_union, h.image_eq, hbij.image_eq, union_diff_self] exact .inr ⟨ht' hyt', hyt'⟩ /-- If `f` maps `s` bijectively to `t`, and `t'` is a superset of `t` contained in the range of `f`, then `f` maps some superset of `s` bijectively to `t'`. -/ theorem BijOn.exists_extend {t' : Set β} (h : BijOn f s t) (htt' : t ⊆ t') (ht' : t' ⊆ range f) : ∃ s', s ⊆ s' ∧ BijOn f s' t' := by simpa using h.exists_extend_of_subset (subset_univ s) htt' (by simpa [SurjOn]) theorem InjOn.exists_subset_injOn_subset_range_eq {r : Set α} (hinj : InjOn f r) (hrs : r ⊆ s) : ∃ u : Set α, r ⊆ u ∧ u ⊆ s ∧ f '' u = f '' s ∧ InjOn f u := by obtain ⟨u, hru, hus, h⟩ := hinj.bijOn_image.exists_extend_of_subset hrs (image_subset f hrs) Subset.rfl exact ⟨u, hru, hus, h.image_eq, h.injOn⟩ theorem preimage_invFun_of_mem [n : Nonempty α] {f : α → β} (hf : Injective f) {s : Set α} (h : Classical.choice n ∈ s) : invFun f ⁻¹' s = f '' s ∪ (range f)ᶜ := by ext x rcases em (x ∈ range f) with (⟨a, rfl⟩ | hx) · simp only [mem_preimage, mem_union, mem_compl_iff, mem_range_self, not_true, or_false, leftInverse_invFun hf _, hf.mem_set_image] · simp only [mem_preimage, invFun_neg hx, h, hx, mem_union, mem_compl_iff, not_false_iff, or_true] theorem preimage_invFun_of_not_mem [n : Nonempty α] {f : α → β} (hf : Injective f) {s : Set α} (h : Classical.choice n ∉ s) : invFun f ⁻¹' s = f '' s := by ext x rcases em (x ∈ range f) with (⟨a, rfl⟩ | hx) · rw [mem_preimage, leftInverse_invFun hf, hf.mem_set_image] · have : x ∉ f '' s := fun h' => hx (image_subset_range _ _ h') simp only [mem_preimage, invFun_neg hx, h, this] lemma BijOn.symm {g : β → α} (h : InvOn f g t s) (hf : BijOn f s t) : BijOn g t s := ⟨h.2.mapsTo hf.surjOn, h.1.injOn, h.2.surjOn hf.mapsTo⟩ lemma bijOn_comm {g : β → α} (h : InvOn f g t s) : BijOn f s t ↔ BijOn g t s := ⟨BijOn.symm h, BijOn.symm h.symm⟩ end Set /-! ### Monotone -/ namespace Monotone variable [Preorder α] [Preorder β] {f : α → β} protected theorem restrict (h : Monotone f) (s : Set α) : Monotone (s.restrict f) := fun _ _ hxy => h hxy protected theorem codRestrict (h : Monotone f) {s : Set β} (hs : ∀ x, f x ∈ s) : Monotone (s.codRestrict f hs) := h protected theorem rangeFactorization (h : Monotone f) : Monotone (Set.rangeFactorization f) := h end Monotone /-! ### Piecewise defined function -/ namespace Set variable {δ : α → Sort*} (s : Set α) (f g : ∀ i, δ i) @[simp] theorem piecewise_empty [∀ i : α, Decidable (i ∈ (∅ : Set α))] : piecewise ∅ f g = g := by ext i simp [piecewise] @[simp] theorem piecewise_univ [∀ i : α, Decidable (i ∈ (Set.univ : Set α))] : piecewise Set.univ f g = f := by ext i simp [piecewise] --@[simp] -- Porting note: simpNF linter complains theorem piecewise_insert_self {j : α} [∀ i, Decidable (i ∈ insert j s)] : (insert j s).piecewise f g j = f j := by simp [piecewise] variable [∀ j, Decidable (j ∈ s)] -- TODO: move! instance Compl.decidableMem (j : α) : Decidable (j ∈ sᶜ) := instDecidableNot theorem piecewise_insert [DecidableEq α] (j : α) [∀ i, Decidable (i ∈ insert j s)] : (insert j s).piecewise f g = Function.update (s.piecewise f g) j (f j) := by simp (config := { unfoldPartialApp := true }) only [piecewise, mem_insert_iff] ext i by_cases h : i = j · rw [h] simp · by_cases h' : i ∈ s <;> simp [h, h'] @[simp] theorem piecewise_eq_of_mem {i : α} (hi : i ∈ s) : s.piecewise f g i = f i := if_pos hi @[simp] theorem piecewise_eq_of_not_mem {i : α} (hi : i ∉ s) : s.piecewise f g i = g i := if_neg hi theorem piecewise_singleton (x : α) [∀ y, Decidable (y ∈ ({x} : Set α))] [DecidableEq α] (f g : α → β) : piecewise {x} f g = Function.update g x (f x) := by ext y by_cases hy : y = x · subst y simp · simp [hy] theorem piecewise_eqOn (f g : α → β) : EqOn (s.piecewise f g) f s := fun _ => piecewise_eq_of_mem _ _ _ theorem piecewise_eqOn_compl (f g : α → β) : EqOn (s.piecewise f g) g sᶜ := fun _ => piecewise_eq_of_not_mem _ _ _ theorem piecewise_le {δ : α → Type*} [∀ i, Preorder (δ i)] {s : Set α} [∀ j, Decidable (j ∈ s)] {f₁ f₂ g : ∀ i, δ i} (h₁ : ∀ i ∈ s, f₁ i ≤ g i) (h₂ : ∀ i ∉ s, f₂ i ≤ g i) : s.piecewise f₁ f₂ ≤ g := fun i => if h : i ∈ s then by simp [*] else by simp [*] theorem le_piecewise {δ : α → Type*} [∀ i, Preorder (δ i)] {s : Set α} [∀ j, Decidable (j ∈ s)] {f₁ f₂ g : ∀ i, δ i} (h₁ : ∀ i ∈ s, g i ≤ f₁ i) (h₂ : ∀ i ∉ s, g i ≤ f₂ i) : g ≤ s.piecewise f₁ f₂ := @piecewise_le α (fun i => (δ i)ᵒᵈ) _ s _ _ _ _ h₁ h₂ theorem piecewise_le_piecewise {δ : α → Type*} [∀ i, Preorder (δ i)] {s : Set α} [∀ j, Decidable (j ∈ s)] {f₁ f₂ g₁ g₂ : ∀ i, δ i} (h₁ : ∀ i ∈ s, f₁ i ≤ g₁ i) (h₂ : ∀ i ∉ s, f₂ i ≤ g₂ i) : s.piecewise f₁ f₂ ≤ s.piecewise g₁ g₂ := by apply piecewise_le <;> intros <;> simp [*] @[simp] theorem piecewise_insert_of_ne {i j : α} (h : i ≠ j) [∀ i, Decidable (i ∈ insert j s)] : (insert j s).piecewise f g i = s.piecewise f g i := by simp [piecewise, h] @[simp] theorem piecewise_compl [∀ i, Decidable (i ∈ sᶜ)] : sᶜ.piecewise f g = s.piecewise g f := funext fun x => if hx : x ∈ s then by simp [hx] else by simp [hx] @[simp] theorem piecewise_range_comp {ι : Sort*} (f : ι → α) [∀ j, Decidable (j ∈ range f)] (g₁ g₂ : α → β) : (range f).piecewise g₁ g₂ ∘ f = g₁ ∘ f := (piecewise_eqOn ..).comp_eq theorem MapsTo.piecewise_ite {s s₁ s₂ : Set α} {t t₁ t₂ : Set β} {f₁ f₂ : α → β} [∀ i, Decidable (i ∈ s)] (h₁ : MapsTo f₁ (s₁ ∩ s) (t₁ ∩ t)) (h₂ : MapsTo f₂ (s₂ ∩ sᶜ) (t₂ ∩ tᶜ)) : MapsTo (s.piecewise f₁ f₂) (s.ite s₁ s₂) (t.ite t₁ t₂) := by refine (h₁.congr ?_).union_union (h₂.congr ?_) exacts [(piecewise_eqOn s f₁ f₂).symm.mono inter_subset_right, (piecewise_eqOn_compl s f₁ f₂).symm.mono inter_subset_right] theorem eqOn_piecewise {f f' g : α → β} {t} : EqOn (s.piecewise f f') g t ↔ EqOn f g (t ∩ s) ∧ EqOn f' g (t ∩ sᶜ) := by simp only [EqOn, ← forall_and] refine forall_congr' fun a => ?_; by_cases a ∈ s <;> simp [*] theorem EqOn.piecewise_ite' {f f' g : α → β} {t t'} (h : EqOn f g (t ∩ s)) (h' : EqOn f' g (t' ∩ sᶜ)) : EqOn (s.piecewise f f') g (s.ite t t') := by simp [eqOn_piecewise, *] theorem EqOn.piecewise_ite {f f' g : α → β} {t t'} (h : EqOn f g t) (h' : EqOn f' g t') : EqOn (s.piecewise f f') g (s.ite t t') := (h.mono inter_subset_left).piecewise_ite' s (h'.mono inter_subset_left) theorem piecewise_preimage (f g : α → β) (t) : s.piecewise f g ⁻¹' t = s.ite (f ⁻¹' t) (g ⁻¹' t) := ext fun x => by by_cases x ∈ s <;> simp [*, Set.ite] theorem apply_piecewise {δ' : α → Sort*} (h : ∀ i, δ i → δ' i) {x : α} : h x (s.piecewise f g x) = s.piecewise (fun x => h x (f x)) (fun x => h x (g x)) x := by by_cases hx : x ∈ s <;> simp [hx] theorem apply_piecewise₂ {δ' δ'' : α → Sort*} (f' g' : ∀ i, δ' i) (h : ∀ i, δ i → δ' i → δ'' i) {x : α} : h x (s.piecewise f g x) (s.piecewise f' g' x) = s.piecewise (fun x => h x (f x) (f' x)) (fun x => h x (g x) (g' x)) x := by by_cases hx : x ∈ s <;> simp [hx] theorem piecewise_op {δ' : α → Sort*} (h : ∀ i, δ i → δ' i) : (s.piecewise (fun x => h x (f x)) fun x => h x (g x)) = fun x => h x (s.piecewise f g x) := funext fun _ => (apply_piecewise _ _ _ _).symm theorem piecewise_op₂ {δ' δ'' : α → Sort*} (f' g' : ∀ i, δ' i) (h : ∀ i, δ i → δ' i → δ'' i) : (s.piecewise (fun x => h x (f x) (f' x)) fun x => h x (g x) (g' x)) = fun x => h x (s.piecewise f g x) (s.piecewise f' g' x) := funext fun _ => (apply_piecewise₂ _ _ _ _ _ _).symm @[simp] theorem piecewise_same : s.piecewise f f = f := by ext x by_cases hx : x ∈ s <;> simp [hx] theorem range_piecewise (f g : α → β) : range (s.piecewise f g) = f '' s ∪ g '' sᶜ := by ext y; constructor · rintro ⟨x, rfl⟩ by_cases h : x ∈ s <;> [left; right] <;> use x <;> simp [h] · rintro (⟨x, hx, rfl⟩ | ⟨x, hx, rfl⟩) <;> use x <;> simp_all theorem injective_piecewise_iff {f g : α → β} : Injective (s.piecewise f g) ↔ InjOn f s ∧ InjOn g sᶜ ∧ ∀ x ∈ s, ∀ y ∉ s, f x ≠ g y := by rw [injective_iff_injOn_univ, ← union_compl_self s, injOn_union (@disjoint_compl_right _ _ s), (piecewise_eqOn s f g).injOn_iff, (piecewise_eqOn_compl s f g).injOn_iff] refine and_congr Iff.rfl (and_congr Iff.rfl <| forall₄_congr fun x hx y hy => ?_) rw [piecewise_eq_of_mem s f g hx, piecewise_eq_of_not_mem s f g hy] theorem piecewise_mem_pi {δ : α → Type*} {t : Set α} {t' : ∀ i, Set (δ i)} {f g} (hf : f ∈ pi t t') (hg : g ∈ pi t t') : s.piecewise f g ∈ pi t t' := by intro i ht by_cases hs : i ∈ s <;> simp [hf i ht, hg i ht, hs] @[simp] theorem pi_piecewise {ι : Type*} {α : ι → Type*} (s s' : Set ι) (t t' : ∀ i, Set (α i)) [∀ x, Decidable (x ∈ s')] : pi s (s'.piecewise t t') = pi (s ∩ s') t ∩ pi (s \ s') t' := pi_if _ _ _ theorem univ_pi_piecewise {ι : Type*} {α : ι → Type*} (s : Set ι) (t t' : ∀ i, Set (α i)) [∀ x, Decidable (x ∈ s)] : pi univ (s.piecewise t t') = pi s t ∩ pi sᶜ t' := by simp [compl_eq_univ_diff] theorem univ_pi_piecewise_univ {ι : Type*} {α : ι → Type*} (s : Set ι) (t : ∀ i, Set (α i)) [∀ x, Decidable (x ∈ s)] : pi univ (s.piecewise t fun _ => univ) = pi s t := by simp end Set section strictMono theorem StrictMonoOn.injOn [LinearOrder α] [Preorder β] {f : α → β} {s : Set α} (H : StrictMonoOn f s) : s.InjOn f := fun x hx y hy hxy => show Ordering.eq.Compares x y from (H.compares hx hy).1 hxy theorem StrictAntiOn.injOn [LinearOrder α] [Preorder β] {f : α → β} {s : Set α} (H : StrictAntiOn f s) : s.InjOn f := @StrictMonoOn.injOn α βᵒᵈ _ _ f s H theorem StrictMonoOn.comp [Preorder α] [Preorder β] [Preorder γ] {g : β → γ} {f : α → β} {s : Set α} {t : Set β} (hg : StrictMonoOn g t) (hf : StrictMonoOn f s) (hs : Set.MapsTo f s t) : StrictMonoOn (g ∘ f) s := fun _x hx _y hy hxy => hg (hs hx) (hs hy) <| hf hx hy hxy theorem StrictMonoOn.comp_strictAntiOn [Preorder α] [Preorder β] [Preorder γ] {g : β → γ} {f : α → β} {s : Set α} {t : Set β} (hg : StrictMonoOn g t) (hf : StrictAntiOn f s) (hs : Set.MapsTo f s t) : StrictAntiOn (g ∘ f) s := fun _x hx _y hy hxy => hg (hs hy) (hs hx) <| hf hx hy hxy theorem StrictAntiOn.comp [Preorder α] [Preorder β] [Preorder γ] {g : β → γ} {f : α → β} {s : Set α} {t : Set β} (hg : StrictAntiOn g t) (hf : StrictAntiOn f s) (hs : Set.MapsTo f s t) : StrictMonoOn (g ∘ f) s := fun _x hx _y hy hxy => hg (hs hy) (hs hx) <| hf hx hy hxy theorem StrictAntiOn.comp_strictMonoOn [Preorder α] [Preorder β] [Preorder γ] {g : β → γ} {f : α → β} {s : Set α} {t : Set β} (hg : StrictAntiOn g t) (hf : StrictMonoOn f s) (hs : Set.MapsTo f s t) : StrictAntiOn (g ∘ f) s := fun _x hx _y hy hxy => hg (hs hx) (hs hy) <| hf hx hy hxy @[simp] theorem strictMono_restrict [Preorder α] [Preorder β] {f : α → β} {s : Set α} : StrictMono (s.restrict f) ↔ StrictMonoOn f s := by simp [Set.restrict, StrictMono, StrictMonoOn] alias ⟨_root_.StrictMono.of_restrict, _root_.StrictMonoOn.restrict⟩ := strictMono_restrict theorem StrictMono.codRestrict [Preorder α] [Preorder β] {f : α → β} (hf : StrictMono f) {s : Set β} (hs : ∀ x, f x ∈ s) : StrictMono (Set.codRestrict f s hs) := hf end strictMono namespace Function open Set variable {fa : α → α} {fb : β → β} {f : α → β} {g : β → γ} {s t : Set α} theorem Injective.comp_injOn (hg : Injective g) (hf : s.InjOn f) : s.InjOn (g ∘ f) := hg.injOn.comp hf (mapsTo_univ _ _) theorem Surjective.surjOn (hf : Surjective f) (s : Set β) : SurjOn f univ s := (surjective_iff_surjOn_univ.1 hf).mono (Subset.refl _) (subset_univ _) theorem LeftInverse.leftInvOn {g : β → α} (h : LeftInverse f g) (s : Set β) : LeftInvOn f g s := fun x _ => h x theorem RightInverse.rightInvOn {g : β → α} (h : RightInverse f g) (s : Set α) : RightInvOn f g s := fun x _ => h x theorem LeftInverse.rightInvOn_range {g : β → α} (h : LeftInverse f g) : RightInvOn f g (range g) := forall_mem_range.2 fun i => congr_arg g (h i) namespace Semiconj theorem mapsTo_image (h : Semiconj f fa fb) (ha : MapsTo fa s t) : MapsTo fb (f '' s) (f '' t) := fun _y ⟨x, hx, hy⟩ => hy ▸ ⟨fa x, ha hx, h x⟩ theorem mapsTo_range (h : Semiconj f fa fb) : MapsTo fb (range f) (range f) := fun _y ⟨x, hy⟩ => hy ▸ ⟨fa x, h x⟩ theorem surjOn_image (h : Semiconj f fa fb) (ha : SurjOn fa s t) : SurjOn fb (f '' s) (f '' t) := by rintro y ⟨x, hxt, rfl⟩ rcases ha hxt with ⟨x, hxs, rfl⟩ rw [h x] exact mem_image_of_mem _ (mem_image_of_mem _ hxs) theorem surjOn_range (h : Semiconj f fa fb) (ha : Surjective fa) : SurjOn fb (range f) (range f) := by rw [← image_univ] exact h.surjOn_image (ha.surjOn univ) theorem injOn_image (h : Semiconj f fa fb) (ha : InjOn fa s) (hf : InjOn f (fa '' s)) : InjOn fb (f '' s) := by rintro _ ⟨x, hx, rfl⟩ _ ⟨y, hy, rfl⟩ H simp only [← h.eq] at H exact congr_arg f (ha hx hy <| hf (mem_image_of_mem fa hx) (mem_image_of_mem fa hy) H) theorem injOn_range (h : Semiconj f fa fb) (ha : Injective fa) (hf : InjOn f (range fa)) : InjOn fb (range f) := by rw [← image_univ] at * exact h.injOn_image ha.injOn hf theorem bijOn_image (h : Semiconj f fa fb) (ha : BijOn fa s t) (hf : InjOn f t) : BijOn fb (f '' s) (f '' t) := ⟨h.mapsTo_image ha.mapsTo, h.injOn_image ha.injOn (ha.image_eq.symm ▸ hf), h.surjOn_image ha.surjOn⟩ theorem bijOn_range (h : Semiconj f fa fb) (ha : Bijective fa) (hf : Injective f) : BijOn fb (range f) (range f) := by rw [← image_univ] exact h.bijOn_image (bijective_iff_bijOn_univ.1 ha) hf.injOn theorem mapsTo_preimage (h : Semiconj f fa fb) {s t : Set β} (hb : MapsTo fb s t) : MapsTo fa (f ⁻¹' s) (f ⁻¹' t) := fun x hx => by simp only [mem_preimage, h x, hb hx] theorem injOn_preimage (h : Semiconj f fa fb) {s : Set β} (hb : InjOn fb s) (hf : InjOn f (f ⁻¹' s)) : InjOn fa (f ⁻¹' s) := by intro x hx y hy H have := congr_arg f H rw [h.eq, h.eq] at this exact hf hx hy (hb hx hy this) end Semiconj theorem update_comp_eq_of_not_mem_range' {α : Sort*} {β : Type*} {γ : β → Sort*} [DecidableEq β] (g : ∀ b, γ b) {f : α → β} {i : β} (a : γ i) (h : i ∉ Set.range f) : (fun j => update g i a (f j)) = fun j => g (f j) := (update_comp_eq_of_forall_ne' _ _) fun x hx => h ⟨x, hx⟩ /-- Non-dependent version of `Function.update_comp_eq_of_not_mem_range'` -/ theorem update_comp_eq_of_not_mem_range {α : Sort*} {β : Type*} {γ : Sort*} [DecidableEq β] (g : β → γ) {f : α → β} {i : β} (a : γ) (h : i ∉ Set.range f) : update g i a ∘ f = g ∘ f := update_comp_eq_of_not_mem_range' g a h theorem insert_injOn (s : Set α) : sᶜ.InjOn fun a => insert a s := fun _a ha _ _ => (insert_inj ha).1 theorem monotoneOn_of_rightInvOn_of_mapsTo {α β : Type*} [PartialOrder α] [LinearOrder β] {φ : β → α} {ψ : α → β} {t : Set β} {s : Set α} (hφ : MonotoneOn φ t) (φψs : Set.RightInvOn ψ φ s) (ψts : Set.MapsTo ψ s t) : MonotoneOn ψ s := by rintro x xs y ys l rcases le_total (ψ x) (ψ y) with (ψxy|ψyx) · exact ψxy · have := hφ (ψts ys) (ψts xs) ψyx rw [φψs.eq ys, φψs.eq xs] at this induction le_antisymm l this exact le_refl _ theorem antitoneOn_of_rightInvOn_of_mapsTo [PartialOrder α] [LinearOrder β] {φ : β → α} {ψ : α → β} {t : Set β} {s : Set α} (hφ : AntitoneOn φ t) (φψs : Set.RightInvOn ψ φ s) (ψts : Set.MapsTo ψ s t) : AntitoneOn ψ s := (monotoneOn_of_rightInvOn_of_mapsTo hφ.dual_left φψs ψts).dual_right end Function /-! ### Equivalences, permutations -/ namespace Set variable {p : β → Prop} [DecidablePred p] {f : α ≃ Subtype p} {g g₁ g₂ : Perm α} {s t : Set α} protected lemma MapsTo.extendDomain (h : MapsTo g s t) : MapsTo (g.extendDomain f) ((↑) ∘ f '' s) ((↑) ∘ f '' t) := by rintro _ ⟨a, ha, rfl⟩; exact ⟨_, h ha, by simp_rw [Function.comp_apply, extendDomain_apply_image]⟩ protected lemma SurjOn.extendDomain (h : SurjOn g s t) : SurjOn (g.extendDomain f) ((↑) ∘ f '' s) ((↑) ∘ f '' t) := by rintro _ ⟨a, ha, rfl⟩ obtain ⟨b, hb, rfl⟩ := h ha exact ⟨_, ⟨_, hb, rfl⟩, by simp_rw [Function.comp_apply, extendDomain_apply_image]⟩ protected lemma BijOn.extendDomain (h : BijOn g s t) : BijOn (g.extendDomain f) ((↑) ∘ f '' s) ((↑) ∘ f '' t) := ⟨h.mapsTo.extendDomain, (g.extendDomain f).injective.injOn, h.surjOn.extendDomain⟩ protected lemma LeftInvOn.extendDomain (h : LeftInvOn g₁ g₂ s) : LeftInvOn (g₁.extendDomain f) (g₂.extendDomain f) ((↑) ∘ f '' s) := by rintro _ ⟨a, ha, rfl⟩; simp_rw [Function.comp_apply, extendDomain_apply_image, h ha] protected lemma RightInvOn.extendDomain (h : RightInvOn g₁ g₂ t) : RightInvOn (g₁.extendDomain f) (g₂.extendDomain f) ((↑) ∘ f '' t) := by rintro _ ⟨a, ha, rfl⟩; simp_rw [Function.comp_apply, extendDomain_apply_image, h ha] protected lemma InvOn.extendDomain (h : InvOn g₁ g₂ s t) : InvOn (g₁.extendDomain f) (g₂.extendDomain f) ((↑) ∘ f '' s) ((↑) ∘ f '' t) := ⟨h.1.extendDomain, h.2.extendDomain⟩ end Set namespace Set variable {α₁ α₂ β₁ β₂ : Type*} {s₁ : Set α₁} {s₂ : Set α₂} {t₁ : Set β₁} {t₂ : Set β₂} {f₁ : α₁ → β₁} {f₂ : α₂ → β₂} {g₁ : β₁ → α₁} {g₂ : β₂ → α₂} lemma InjOn.prodMap (h₁ : s₁.InjOn f₁) (h₂ : s₂.InjOn f₂) : (s₁ ×ˢ s₂).InjOn fun x ↦ (f₁ x.1, f₂ x.2) := fun x hx y hy ↦ by simp_rw [Prod.ext_iff]; exact And.imp (h₁ hx.1 hy.1) (h₂ hx.2 hy.2) lemma SurjOn.prodMap (h₁ : SurjOn f₁ s₁ t₁) (h₂ : SurjOn f₂ s₂ t₂) : SurjOn (fun x ↦ (f₁ x.1, f₂ x.2)) (s₁ ×ˢ s₂) (t₁ ×ˢ t₂) := by rintro x hx obtain ⟨a₁, ha₁, hx₁⟩ := h₁ hx.1 obtain ⟨a₂, ha₂, hx₂⟩ := h₂ hx.2 exact ⟨(a₁, a₂), ⟨ha₁, ha₂⟩, Prod.ext hx₁ hx₂⟩ lemma MapsTo.prodMap (h₁ : MapsTo f₁ s₁ t₁) (h₂ : MapsTo f₂ s₂ t₂) : MapsTo (fun x ↦ (f₁ x.1, f₂ x.2)) (s₁ ×ˢ s₂) (t₁ ×ˢ t₂) := fun _x hx ↦ ⟨h₁ hx.1, h₂ hx.2⟩ lemma BijOn.prodMap (h₁ : BijOn f₁ s₁ t₁) (h₂ : BijOn f₂ s₂ t₂) : BijOn (fun x ↦ (f₁ x.1, f₂ x.2)) (s₁ ×ˢ s₂) (t₁ ×ˢ t₂) := ⟨h₁.mapsTo.prodMap h₂.mapsTo, h₁.injOn.prodMap h₂.injOn, h₁.surjOn.prodMap h₂.surjOn⟩ lemma LeftInvOn.prodMap (h₁ : LeftInvOn g₁ f₁ s₁) (h₂ : LeftInvOn g₂ f₂ s₂) : LeftInvOn (fun x ↦ (g₁ x.1, g₂ x.2)) (fun x ↦ (f₁ x.1, f₂ x.2)) (s₁ ×ˢ s₂) := fun _x hx ↦ Prod.ext (h₁ hx.1) (h₂ hx.2) lemma RightInvOn.prodMap (h₁ : RightInvOn g₁ f₁ t₁) (h₂ : RightInvOn g₂ f₂ t₂) : RightInvOn (fun x ↦ (g₁ x.1, g₂ x.2)) (fun x ↦ (f₁ x.1, f₂ x.2)) (t₁ ×ˢ t₂) := fun _x hx ↦ Prod.ext (h₁ hx.1) (h₂ hx.2) lemma InvOn.prodMap (h₁ : InvOn g₁ f₁ s₁ t₁) (h₂ : InvOn g₂ f₂ s₂ t₂) : InvOn (fun x ↦ (g₁ x.1, g₂ x.2)) (fun x ↦ (f₁ x.1, f₂ x.2)) (s₁ ×ˢ s₂) (t₁ ×ˢ t₂) := ⟨h₁.1.prodMap h₂.1, h₁.2.prodMap h₂.2⟩ end Set namespace Equiv open Set variable (e : α ≃ β) {s : Set α} {t : Set β} lemma bijOn' (h₁ : MapsTo e s t) (h₂ : MapsTo e.symm t s) : BijOn e s t := ⟨h₁, e.injective.injOn, fun b hb ↦ ⟨e.symm b, h₂ hb, apply_symm_apply _ _⟩⟩ protected lemma bijOn (h : ∀ a, e a ∈ t ↔ a ∈ s) : BijOn e s t := e.bijOn' (fun a ↦ (h _).2) fun b hb ↦ (h _).1 <| by rwa [apply_symm_apply] lemma invOn : InvOn e e.symm t s := ⟨e.rightInverse_symm.leftInvOn _, e.leftInverse_symm.leftInvOn _⟩ lemma bijOn_image : BijOn e s (e '' s) := e.injective.injOn.bijOn_image lemma bijOn_symm_image : BijOn e.symm (e '' s) s := e.bijOn_image.symm e.invOn variable {e} @[simp] lemma bijOn_symm : BijOn e.symm t s ↔ BijOn e s t := bijOn_comm e.symm.invOn alias ⟨_root_.Set.BijOn.of_equiv_symm, _root_.Set.BijOn.equiv_symm⟩ := bijOn_symm variable [DecidableEq α] {a b : α} lemma bijOn_swap (ha : a ∈ s) (hb : b ∈ s) : BijOn (swap a b) s s := (swap a b).bijOn fun x ↦ by obtain rfl | hxa := eq_or_ne x a <;> obtain rfl | hxb := eq_or_ne x b <;> simp [*, swap_apply_of_ne_of_ne] end Equiv
Data\Set\Functor.lean
/- Copyright (c) 2016 Leonardo de Moura. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Mathlib.Data.Set.Lattice import Mathlib.Init.Set import Mathlib.Control.Basic import Mathlib.Data.Set.Notation /-! # Functoriality of `Set` This file defines the functor structure of `Set`. -/ universe u open Function Set.Notation namespace Set variable {α β : Type u} {s : Set α} {f : α → Set β} {g : Set (α → β)} /-- The `Set` functor is a monad. This is not a global instance because it does not have computational content, so it does not make much sense using `do` notation in general. Plus, this would cause monad-related coercions and monad lifting logic to become activated. Either use `attribute [local instance] Set.monad` to make it be a local instance or use `SetM.run do ...` when `do` notation is wanted. -/ protected def monad : Monad.{u} Set where pure a := {a} bind s f := ⋃ i ∈ s, f i seq s t := Set.seq s (t ()) map := Set.image section with_instance attribute [local instance] Set.monad @[simp] theorem bind_def : s >>= f = ⋃ i ∈ s, f i := rfl @[simp] theorem fmap_eq_image (f : α → β) : f <$> s = f '' s := rfl @[simp] theorem seq_eq_set_seq (s : Set (α → β)) (t : Set α) : s <*> t = s.seq t := rfl @[simp] theorem pure_def (a : α) : (pure a : Set α) = {a} := rfl /-- `Set.image2` in terms of monadic operations. Note that this can't be taken as the definition because of the lack of universe polymorphism. -/ theorem image2_def {α β γ : Type u} (f : α → β → γ) (s : Set α) (t : Set β) : image2 f s t = f <$> s <*> t := by ext simp instance : LawfulMonad Set := LawfulMonad.mk' (id_map := image_id) (pure_bind := biUnion_singleton) (bind_assoc := fun _ _ _ => by simp only [bind_def, biUnion_iUnion]) (bind_pure_comp := fun _ _ => (image_eq_iUnion _ _).symm) (bind_map := fun _ _ => seq_def.symm) instance : CommApplicative (Set : Type u → Type u) := ⟨fun s t => prod_image_seq_comm s t⟩ instance : Alternative Set := { Set.monad with orElse := fun s t => s ∪ (t ()) failure := ∅ } /-! ### Monadic coercion lemmas -/ variable {β : Set α} {γ : Set β} theorem mem_coe_of_mem {a : α} (ha : a ∈ β) (ha' : ⟨a, ha⟩ ∈ γ) : a ∈ (γ : Set α) := ⟨_, ⟨⟨_, rfl⟩, _, ⟨ha', rfl⟩, rfl⟩⟩ theorem coe_subset : (γ : Set α) ⊆ β := by intro _ ⟨_, ⟨⟨⟨_, ha⟩, rfl⟩, _, ⟨_, rfl⟩, _⟩⟩; convert ha theorem mem_of_mem_coe {a : α} (ha : a ∈ (γ : Set α)) : ⟨a, coe_subset ha⟩ ∈ γ := by rcases ha with ⟨_, ⟨_, rfl⟩, _, ⟨ha, rfl⟩, _⟩; convert ha theorem eq_univ_of_coe_eq (hγ : (γ : Set α) = β) : γ = univ := eq_univ_of_forall fun ⟨_, ha⟩ => mem_of_mem_coe <| hγ.symm ▸ ha theorem image_coe_eq_restrict_image {δ : Type*} {f : α → δ} : f '' γ = β.restrict f '' γ := ext fun _ => ⟨fun ⟨_, h, ha⟩ => ⟨_, mem_of_mem_coe h, ha⟩, fun ⟨_, h, ha⟩ => ⟨_, mem_coe_of_mem _ h, ha⟩⟩ end with_instance /-! ### Coercion applying functoriality for `Subtype.val` The `Monad` instance gives a coercion using the internal function `Lean.Internal.coeM`. In practice this is only used for applying the `Set` functor to `Subtype.val`, as was defined in `Data.Set.Notation`. -/ /-- The coercion from `Set.monad` as an instance is equal to the coercion in `Data.Set.Notation`. -/ theorem coe_eq_image_val (t : Set s) : @Lean.Internal.coeM Set s α _ Set.monad t = (t : Set α) := by change ⋃ (x ∈ t), {x.1} = _ ext simp variable {β : Set α} {γ : Set β} {a : α} theorem mem_image_val_of_mem (ha : a ∈ β) (ha' : ⟨a, ha⟩ ∈ γ) : a ∈ (γ : Set α) := ⟨_, ha', rfl⟩ theorem image_val_subset : (γ : Set α) ⊆ β := by rintro _ ⟨⟨_, ha⟩, _, rfl⟩; exact ha theorem mem_of_mem_image_val (ha : a ∈ (γ : Set α)) : ⟨a, image_val_subset ha⟩ ∈ γ := by rcases ha with ⟨_, ha, rfl⟩; exact ha theorem eq_univ_of_image_val_eq (hγ : (γ : Set α) = β) : γ = univ := eq_univ_of_forall fun ⟨_, ha⟩ => mem_of_mem_image_val <| hγ.symm ▸ ha theorem image_image_val_eq_restrict_image {δ : Type*} {f : α → δ} : f '' γ = β.restrict f '' γ := by ext; simp end Set /-! ### Wrapper to enable the `Set` monad -/ /-- This is `Set` but with a `Monad` instance. -/ def SetM (α : Type u) := Set α instance : Monad SetM := Set.monad /-- Evaluates the `SetM` monad, yielding a `Set`. Implementation note: this is the identity function. -/ protected def SetM.run {α : Type*} (s : SetM α) : Set α := s
Data\Set\Image.lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura -/ import Mathlib.Data.Set.Subsingleton import Mathlib.Order.WithBot import Mathlib.Tactic.Use import Batteries.Tactic.Congr /-! # Images and preimages of sets ## Main definitions * `preimage f t : Set α` : the preimage f⁻¹(t) (written `f ⁻¹' t` in Lean) of a subset of β. * `range f : Set β` : the image of `univ` under `f`. Also works for `{p : Prop} (f : p → α)` (unlike `image`) ## Notation * `f ⁻¹' t` for `Set.preimage f t` * `f '' s` for `Set.image f s` ## Tags set, sets, image, preimage, pre-image, range -/ universe u v open Function Set namespace Set variable {α β γ : Type*} {ι ι' : Sort*} /-! ### Inverse image -/ section Preimage variable {f : α → β} {g : β → γ} @[simp] theorem preimage_empty : f ⁻¹' ∅ = ∅ := rfl theorem preimage_congr {f g : α → β} {s : Set β} (h : ∀ x : α, f x = g x) : f ⁻¹' s = g ⁻¹' s := by congr with x simp [h] @[gcongr] theorem preimage_mono {s t : Set β} (h : s ⊆ t) : f ⁻¹' s ⊆ f ⁻¹' t := fun _ hx => h hx @[simp, mfld_simps] theorem preimage_univ : f ⁻¹' univ = univ := rfl theorem subset_preimage_univ {s : Set α} : s ⊆ f ⁻¹' univ := subset_univ _ @[simp, mfld_simps] theorem preimage_inter {s t : Set β} : f ⁻¹' (s ∩ t) = f ⁻¹' s ∩ f ⁻¹' t := rfl @[simp] theorem preimage_union {s t : Set β} : f ⁻¹' (s ∪ t) = f ⁻¹' s ∪ f ⁻¹' t := rfl @[simp] theorem preimage_compl {s : Set β} : f ⁻¹' sᶜ = (f ⁻¹' s)ᶜ := rfl @[simp] theorem preimage_diff (f : α → β) (s t : Set β) : f ⁻¹' (s \ t) = f ⁻¹' s \ f ⁻¹' t := rfl open scoped symmDiff in @[simp] lemma preimage_symmDiff {f : α → β} (s t : Set β) : f ⁻¹' (s ∆ t) = (f ⁻¹' s) ∆ (f ⁻¹' t) := rfl @[simp] theorem preimage_ite (f : α → β) (s t₁ t₂ : Set β) : f ⁻¹' s.ite t₁ t₂ = (f ⁻¹' s).ite (f ⁻¹' t₁) (f ⁻¹' t₂) := rfl @[simp] theorem preimage_setOf_eq {p : α → Prop} {f : β → α} : f ⁻¹' { a | p a } = { a | p (f a) } := rfl @[simp] theorem preimage_id_eq : preimage (id : α → α) = id := rfl @[mfld_simps] theorem preimage_id {s : Set α} : id ⁻¹' s = s := rfl @[simp, mfld_simps] theorem preimage_id' {s : Set α} : (fun x => x) ⁻¹' s = s := rfl @[simp] theorem preimage_const_of_mem {b : β} {s : Set β} (h : b ∈ s) : (fun _ : α => b) ⁻¹' s = univ := eq_univ_of_forall fun _ => h @[simp] theorem preimage_const_of_not_mem {b : β} {s : Set β} (h : b ∉ s) : (fun _ : α => b) ⁻¹' s = ∅ := eq_empty_of_subset_empty fun _ hx => h hx theorem preimage_const (b : β) (s : Set β) [Decidable (b ∈ s)] : (fun _ : α => b) ⁻¹' s = if b ∈ s then univ else ∅ := by split_ifs with hb exacts [preimage_const_of_mem hb, preimage_const_of_not_mem hb] /-- If preimage of each singleton under `f : α → β` is either empty or the whole type, then `f` is a constant. -/ lemma exists_eq_const_of_preimage_singleton [Nonempty β] {f : α → β} (hf : ∀ b : β, f ⁻¹' {b} = ∅ ∨ f ⁻¹' {b} = univ) : ∃ b, f = const α b := by rcases em (∃ b, f ⁻¹' {b} = univ) with ⟨b, hb⟩ | hf' · exact ⟨b, funext fun x ↦ eq_univ_iff_forall.1 hb x⟩ · have : ∀ x b, f x ≠ b := fun x b ↦ eq_empty_iff_forall_not_mem.1 ((hf b).resolve_right fun h ↦ hf' ⟨b, h⟩) x exact ⟨Classical.arbitrary β, funext fun x ↦ absurd rfl (this x _)⟩ theorem preimage_comp {s : Set γ} : g ∘ f ⁻¹' s = f ⁻¹' (g ⁻¹' s) := rfl theorem preimage_comp_eq : preimage (g ∘ f) = preimage f ∘ preimage g := rfl theorem preimage_iterate_eq {f : α → α} {n : ℕ} : Set.preimage f^[n] = (Set.preimage f)^[n] := by induction' n with n ih; · simp rw [iterate_succ, iterate_succ', preimage_comp_eq, ih] theorem preimage_preimage {g : β → γ} {f : α → β} {s : Set γ} : f ⁻¹' (g ⁻¹' s) = (fun x => g (f x)) ⁻¹' s := preimage_comp.symm theorem eq_preimage_subtype_val_iff {p : α → Prop} {s : Set (Subtype p)} {t : Set α} : s = Subtype.val ⁻¹' t ↔ ∀ (x) (h : p x), (⟨x, h⟩ : Subtype p) ∈ s ↔ x ∈ t := ⟨fun s_eq x h => by rw [s_eq] simp, fun h => ext fun ⟨x, hx⟩ => by simp [h]⟩ theorem nonempty_of_nonempty_preimage {s : Set β} {f : α → β} (hf : (f ⁻¹' s).Nonempty) : s.Nonempty := let ⟨x, hx⟩ := hf ⟨f x, hx⟩ @[simp] theorem preimage_singleton_true (p : α → Prop) : p ⁻¹' {True} = {a | p a} := by ext; simp @[simp] theorem preimage_singleton_false (p : α → Prop) : p ⁻¹' {False} = {a | ¬p a} := by ext; simp theorem preimage_subtype_coe_eq_compl {s u v : Set α} (hsuv : s ⊆ u ∪ v) (H : s ∩ (u ∩ v) = ∅) : ((↑) : s → α) ⁻¹' u = ((↑) ⁻¹' v)ᶜ := by ext ⟨x, x_in_s⟩ constructor · intro x_in_u x_in_v exact eq_empty_iff_forall_not_mem.mp H x ⟨x_in_s, ⟨x_in_u, x_in_v⟩⟩ · intro hx exact Or.elim (hsuv x_in_s) id fun hx' => hx.elim hx' end Preimage /-! ### Image of a set under a function -/ section Image variable {f : α → β} {s t : Set α} -- Porting note: `Set.image` is already defined in `Init.Set` @[deprecated mem_image (since := "2024-03-23")] theorem mem_image_iff_bex {f : α → β} {s : Set α} {y : β} : y ∈ f '' s ↔ ∃ (x : _) (_ : x ∈ s), f x = y := bex_def.symm theorem image_eta (f : α → β) : f '' s = (fun x => f x) '' s := rfl theorem _root_.Function.Injective.mem_set_image {f : α → β} (hf : Injective f) {s : Set α} {a : α} : f a ∈ f '' s ↔ a ∈ s := ⟨fun ⟨_, hb, Eq⟩ => hf Eq ▸ hb, mem_image_of_mem f⟩ lemma preimage_subset_of_surjOn {t : Set β} (hf : Injective f) (h : SurjOn f s t) : f ⁻¹' t ⊆ s := fun _ hx ↦ hf.mem_set_image.1 $ h hx theorem forall_mem_image {f : α → β} {s : Set α} {p : β → Prop} : (∀ y ∈ f '' s, p y) ↔ ∀ ⦃x⦄, x ∈ s → p (f x) := by simp theorem exists_mem_image {f : α → β} {s : Set α} {p : β → Prop} : (∃ y ∈ f '' s, p y) ↔ ∃ x ∈ s, p (f x) := by simp @[deprecated (since := "2024-02-21")] alias ball_image_iff := forall_mem_image @[deprecated (since := "2024-02-21")] alias bex_image_iff := exists_mem_image @[deprecated (since := "2024-02-21")] alias ⟨_, ball_image_of_ball⟩ := forall_mem_image @[deprecated forall_mem_image (since := "2024-02-21")] theorem mem_image_elim {f : α → β} {s : Set α} {C : β → Prop} (h : ∀ x : α, x ∈ s → C (f x)) : ∀ {y : β}, y ∈ f '' s → C y := forall_mem_image.2 h _ @[deprecated forall_mem_image (since := "2024-02-21")] theorem mem_image_elim_on {f : α → β} {s : Set α} {C : β → Prop} {y : β} (h_y : y ∈ f '' s) (h : ∀ x : α, x ∈ s → C (f x)) : C y := forall_mem_image.2 h _ h_y -- Porting note: used to be `safe` @[congr] theorem image_congr {f g : α → β} {s : Set α} (h : ∀ a ∈ s, f a = g a) : f '' s = g '' s := by ext x exact exists_congr fun a ↦ and_congr_right fun ha ↦ by rw [h a ha] /-- A common special case of `image_congr` -/ theorem image_congr' {f g : α → β} {s : Set α} (h : ∀ x : α, f x = g x) : f '' s = g '' s := image_congr fun x _ => h x @[gcongr] lemma image_mono (h : s ⊆ t) : f '' s ⊆ f '' t := by rintro - ⟨a, ha, rfl⟩; exact mem_image_of_mem f (h ha) theorem image_comp (f : β → γ) (g : α → β) (a : Set α) : f ∘ g '' a = f '' (g '' a) := by aesop theorem image_comp_eq {g : β → γ} : image (g ∘ f) = image g ∘ image f := by ext; simp /-- A variant of `image_comp`, useful for rewriting -/ theorem image_image (g : β → γ) (f : α → β) (s : Set α) : g '' (f '' s) = (fun x => g (f x)) '' s := (image_comp g f s).symm theorem image_comm {β'} {f : β → γ} {g : α → β} {f' : α → β'} {g' : β' → γ} (h_comm : ∀ a, f (g a) = g' (f' a)) : (s.image g).image f = (s.image f').image g' := by simp_rw [image_image, h_comm] theorem _root_.Function.Semiconj.set_image {f : α → β} {ga : α → α} {gb : β → β} (h : Function.Semiconj f ga gb) : Function.Semiconj (image f) (image ga) (image gb) := fun _ => image_comm h theorem _root_.Function.Commute.set_image {f g : α → α} (h : Function.Commute f g) : Function.Commute (image f) (image g) := Function.Semiconj.set_image h /-- Image is monotone with respect to `⊆`. See `Set.monotone_image` for the statement in terms of `≤`. -/ @[gcongr] theorem image_subset {a b : Set α} (f : α → β) (h : a ⊆ b) : f '' a ⊆ f '' b := by simp only [subset_def, mem_image] exact fun x => fun ⟨w, h1, h2⟩ => ⟨w, h h1, h2⟩ /-- `Set.image` is monotone. See `Set.image_subset` for the statement in terms of `⊆`. -/ lemma monotone_image {f : α → β} : Monotone (image f) := fun _ _ => image_subset _ theorem image_union (f : α → β) (s t : Set α) : f '' (s ∪ t) = f '' s ∪ f '' t := ext fun x => ⟨by rintro ⟨a, h | h, rfl⟩ <;> [left; right] <;> exact ⟨_, h, rfl⟩, by rintro (⟨a, h, rfl⟩ | ⟨a, h, rfl⟩) <;> refine ⟨_, ?_, rfl⟩ · exact mem_union_left t h · exact mem_union_right s h⟩ @[simp] theorem image_empty (f : α → β) : f '' ∅ = ∅ := by ext simp theorem image_inter_subset (f : α → β) (s t : Set α) : f '' (s ∩ t) ⊆ f '' s ∩ f '' t := subset_inter (image_subset _ inter_subset_left) (image_subset _ inter_subset_right) theorem image_inter_on {f : α → β} {s t : Set α} (h : ∀ x ∈ t, ∀ y ∈ s, f x = f y → x = y) : f '' (s ∩ t) = f '' s ∩ f '' t := (image_inter_subset _ _ _).antisymm fun b ⟨⟨a₁, ha₁, h₁⟩, ⟨a₂, ha₂, h₂⟩⟩ ↦ have : a₂ = a₁ := h _ ha₂ _ ha₁ (by simp [*]) ⟨a₁, ⟨ha₁, this ▸ ha₂⟩, h₁⟩ theorem image_inter {f : α → β} {s t : Set α} (H : Injective f) : f '' (s ∩ t) = f '' s ∩ f '' t := image_inter_on fun _ _ _ _ h => H h theorem image_univ_of_surjective {ι : Type*} {f : ι → β} (H : Surjective f) : f '' univ = univ := eq_univ_of_forall <| by simpa [image] @[simp] theorem image_singleton {f : α → β} {a : α} : f '' {a} = {f a} := by ext simp [image, eq_comm] @[simp] theorem Nonempty.image_const {s : Set α} (hs : s.Nonempty) (a : β) : (fun _ => a) '' s = {a} := ext fun _ => ⟨fun ⟨_, _, h⟩ => h ▸ mem_singleton _, fun h => (eq_of_mem_singleton h).symm ▸ hs.imp fun _ hy => ⟨hy, rfl⟩⟩ @[simp, mfld_simps] theorem image_eq_empty {α β} {f : α → β} {s : Set α} : f '' s = ∅ ↔ s = ∅ := by simp only [eq_empty_iff_forall_not_mem] exact ⟨fun H a ha => H _ ⟨_, ha, rfl⟩, fun H b ⟨_, ha, _⟩ => H _ ha⟩ -- Porting note: `compl` is already defined in `Init.Set` theorem preimage_compl_eq_image_compl [BooleanAlgebra α] (S : Set α) : HasCompl.compl ⁻¹' S = HasCompl.compl '' S := Set.ext fun x => ⟨fun h => ⟨xᶜ, h, compl_compl x⟩, fun h => Exists.elim h fun _ hy => (compl_eq_comm.mp hy.2).symm.subst hy.1⟩ theorem mem_compl_image [BooleanAlgebra α] (t : α) (S : Set α) : t ∈ HasCompl.compl '' S ↔ tᶜ ∈ S := by simp [← preimage_compl_eq_image_compl] @[simp] theorem image_id_eq : image (id : α → α) = id := by ext; simp /-- A variant of `image_id` -/ @[simp] theorem image_id' (s : Set α) : (fun x => x) '' s = s := by ext simp theorem image_id (s : Set α) : id '' s = s := by simp lemma image_iterate_eq {f : α → α} {n : ℕ} : image (f^[n]) = (image f)^[n] := by induction n with | zero => simp | succ n ih => rw [iterate_succ', iterate_succ', ← ih, image_comp_eq] theorem compl_compl_image [BooleanAlgebra α] (S : Set α) : HasCompl.compl '' (HasCompl.compl '' S) = S := by rw [← image_comp, compl_comp_compl, image_id] theorem image_insert_eq {f : α → β} {a : α} {s : Set α} : f '' insert a s = insert (f a) (f '' s) := by ext simp [and_or_left, exists_or, eq_comm, or_comm, and_comm] theorem image_pair (f : α → β) (a b : α) : f '' {a, b} = {f a, f b} := by simp only [image_insert_eq, image_singleton] theorem image_subset_preimage_of_inverse {f : α → β} {g : β → α} (I : LeftInverse g f) (s : Set α) : f '' s ⊆ g ⁻¹' s := fun _ ⟨a, h, e⟩ => e ▸ ((I a).symm ▸ h : g (f a) ∈ s) theorem preimage_subset_image_of_inverse {f : α → β} {g : β → α} (I : LeftInverse g f) (s : Set β) : f ⁻¹' s ⊆ g '' s := fun b h => ⟨f b, h, I b⟩ theorem image_eq_preimage_of_inverse {f : α → β} {g : β → α} (h₁ : LeftInverse g f) (h₂ : RightInverse g f) : image f = preimage g := funext fun s => Subset.antisymm (image_subset_preimage_of_inverse h₁ s) (preimage_subset_image_of_inverse h₂ s) theorem mem_image_iff_of_inverse {f : α → β} {g : β → α} {b : β} {s : Set α} (h₁ : LeftInverse g f) (h₂ : RightInverse g f) : b ∈ f '' s ↔ g b ∈ s := by rw [image_eq_preimage_of_inverse h₁ h₂]; rfl theorem image_compl_subset {f : α → β} {s : Set α} (H : Injective f) : f '' sᶜ ⊆ (f '' s)ᶜ := Disjoint.subset_compl_left <| by simp [disjoint_iff_inf_le, ← image_inter H] theorem subset_image_compl {f : α → β} {s : Set α} (H : Surjective f) : (f '' s)ᶜ ⊆ f '' sᶜ := compl_subset_iff_union.2 <| by rw [← image_union] simp [image_univ_of_surjective H] theorem image_compl_eq {f : α → β} {s : Set α} (H : Bijective f) : f '' sᶜ = (f '' s)ᶜ := Subset.antisymm (image_compl_subset H.1) (subset_image_compl H.2) theorem subset_image_diff (f : α → β) (s t : Set α) : f '' s \ f '' t ⊆ f '' (s \ t) := by rw [diff_subset_iff, ← image_union, union_diff_self] exact image_subset f subset_union_right open scoped symmDiff in theorem subset_image_symmDiff : (f '' s) ∆ (f '' t) ⊆ f '' s ∆ t := (union_subset_union (subset_image_diff _ _ _) <| subset_image_diff _ _ _).trans (superset_of_eq (image_union _ _ _)) theorem image_diff {f : α → β} (hf : Injective f) (s t : Set α) : f '' (s \ t) = f '' s \ f '' t := Subset.antisymm (Subset.trans (image_inter_subset _ _ _) <| inter_subset_inter_right _ <| image_compl_subset hf) (subset_image_diff f s t) open scoped symmDiff in theorem image_symmDiff (hf : Injective f) (s t : Set α) : f '' s ∆ t = (f '' s) ∆ (f '' t) := by simp_rw [Set.symmDiff_def, image_union, image_diff hf] theorem Nonempty.image (f : α → β) {s : Set α} : s.Nonempty → (f '' s).Nonempty | ⟨x, hx⟩ => ⟨f x, mem_image_of_mem f hx⟩ theorem Nonempty.of_image {f : α → β} {s : Set α} : (f '' s).Nonempty → s.Nonempty | ⟨_, x, hx, _⟩ => ⟨x, hx⟩ @[simp] theorem image_nonempty {f : α → β} {s : Set α} : (f '' s).Nonempty ↔ s.Nonempty := ⟨Nonempty.of_image, fun h => h.image f⟩ @[deprecated (since := "2024-01-06")] alias nonempty_image_iff := image_nonempty theorem Nonempty.preimage {s : Set β} (hs : s.Nonempty) {f : α → β} (hf : Surjective f) : (f ⁻¹' s).Nonempty := let ⟨y, hy⟩ := hs let ⟨x, hx⟩ := hf y ⟨x, mem_preimage.2 <| hx.symm ▸ hy⟩ instance (f : α → β) (s : Set α) [Nonempty s] : Nonempty (f '' s) := (Set.Nonempty.image f nonempty_of_nonempty_subtype).to_subtype /-- image and preimage are a Galois connection -/ @[simp] theorem image_subset_iff {s : Set α} {t : Set β} {f : α → β} : f '' s ⊆ t ↔ s ⊆ f ⁻¹' t := forall_mem_image theorem image_preimage_subset (f : α → β) (s : Set β) : f '' (f ⁻¹' s) ⊆ s := image_subset_iff.2 Subset.rfl theorem subset_preimage_image (f : α → β) (s : Set α) : s ⊆ f ⁻¹' (f '' s) := fun _ => mem_image_of_mem f @[simp] theorem preimage_image_eq {f : α → β} (s : Set α) (h : Injective f) : f ⁻¹' (f '' s) = s := Subset.antisymm (fun _ ⟨_, hy, e⟩ => h e ▸ hy) (subset_preimage_image f s) @[simp] theorem image_preimage_eq {f : α → β} (s : Set β) (h : Surjective f) : f '' (f ⁻¹' s) = s := Subset.antisymm (image_preimage_subset f s) fun x hx => let ⟨y, e⟩ := h x ⟨y, (e.symm ▸ hx : f y ∈ s), e⟩ @[simp] theorem Nonempty.subset_preimage_const {s : Set α} (hs : Set.Nonempty s) (t : Set β) (a : β) : s ⊆ (fun _ => a) ⁻¹' t ↔ a ∈ t := by rw [← image_subset_iff, hs.image_const, singleton_subset_iff] @[simp] theorem preimage_eq_preimage {f : β → α} (hf : Surjective f) : f ⁻¹' s = f ⁻¹' t ↔ s = t := Iff.intro fun eq => by rw [← image_preimage_eq s hf, ← image_preimage_eq t hf, eq] fun eq => eq ▸ rfl theorem image_inter_preimage (f : α → β) (s : Set α) (t : Set β) : f '' (s ∩ f ⁻¹' t) = f '' s ∩ t := by apply Subset.antisymm · calc f '' (s ∩ f ⁻¹' t) ⊆ f '' s ∩ f '' (f ⁻¹' t) := image_inter_subset _ _ _ _ ⊆ f '' s ∩ t := inter_subset_inter_right _ (image_preimage_subset f t) · rintro _ ⟨⟨x, h', rfl⟩, h⟩ exact ⟨x, ⟨h', h⟩, rfl⟩ theorem image_preimage_inter (f : α → β) (s : Set α) (t : Set β) : f '' (f ⁻¹' t ∩ s) = t ∩ f '' s := by simp only [inter_comm, image_inter_preimage] @[simp] theorem image_inter_nonempty_iff {f : α → β} {s : Set α} {t : Set β} : (f '' s ∩ t).Nonempty ↔ (s ∩ f ⁻¹' t).Nonempty := by rw [← image_inter_preimage, image_nonempty] theorem image_diff_preimage {f : α → β} {s : Set α} {t : Set β} : f '' (s \ f ⁻¹' t) = f '' s \ t := by simp_rw [diff_eq, ← preimage_compl, image_inter_preimage] theorem compl_image : image (compl : Set α → Set α) = preimage compl := image_eq_preimage_of_inverse compl_compl compl_compl theorem compl_image_set_of {p : Set α → Prop} : compl '' { s | p s } = { s | p sᶜ } := congr_fun compl_image p theorem inter_preimage_subset (s : Set α) (t : Set β) (f : α → β) : s ∩ f ⁻¹' t ⊆ f ⁻¹' (f '' s ∩ t) := fun _ h => ⟨mem_image_of_mem _ h.left, h.right⟩ theorem union_preimage_subset (s : Set α) (t : Set β) (f : α → β) : s ∪ f ⁻¹' t ⊆ f ⁻¹' (f '' s ∪ t) := fun _ h => Or.elim h (fun l => Or.inl <| mem_image_of_mem _ l) fun r => Or.inr r theorem subset_image_union (f : α → β) (s : Set α) (t : Set β) : f '' (s ∪ f ⁻¹' t) ⊆ f '' s ∪ t := image_subset_iff.2 (union_preimage_subset _ _ _) theorem preimage_subset_iff {A : Set α} {B : Set β} {f : α → β} : f ⁻¹' B ⊆ A ↔ ∀ a : α, f a ∈ B → a ∈ A := Iff.rfl theorem image_eq_image {f : α → β} (hf : Injective f) : f '' s = f '' t ↔ s = t := Iff.symm <| (Iff.intro fun eq => eq ▸ rfl) fun eq => by rw [← preimage_image_eq s hf, ← preimage_image_eq t hf, eq] theorem subset_image_iff {t : Set β} : t ⊆ f '' s ↔ ∃ u, u ⊆ s ∧ f '' u = t := by refine ⟨fun h ↦ ⟨f ⁻¹' t ∩ s, inter_subset_right, ?_⟩, fun ⟨u, hu, hu'⟩ ↦ hu'.symm ▸ image_mono hu⟩ rwa [image_preimage_inter, inter_eq_left] @[simp] lemma exists_subset_image_iff {p : Set β → Prop} : (∃ t ⊆ f '' s, p t) ↔ ∃ t ⊆ s, p (f '' t) := by simp [subset_image_iff] @[simp] lemma forall_subset_image_iff {p : Set β → Prop} : (∀ t ⊆ f '' s, p t) ↔ ∀ t ⊆ s, p (f '' t) := by simp [subset_image_iff] theorem image_subset_image_iff {f : α → β} (hf : Injective f) : f '' s ⊆ f '' t ↔ s ⊆ t := by refine Iff.symm <| (Iff.intro (image_subset f)) fun h => ?_ rw [← preimage_image_eq s hf, ← preimage_image_eq t hf] exact preimage_mono h theorem prod_quotient_preimage_eq_image [s : Setoid α] (g : Quotient s → β) {h : α → β} (Hh : h = g ∘ Quotient.mk'') (r : Set (β × β)) : { x : Quotient s × Quotient s | (g x.1, g x.2) ∈ r } = (fun a : α × α => (⟦a.1⟧, ⟦a.2⟧)) '' ((fun a : α × α => (h a.1, h a.2)) ⁻¹' r) := Hh.symm ▸ Set.ext fun ⟨a₁, a₂⟩ => ⟨Quot.induction_on₂ a₁ a₂ fun a₁ a₂ h => ⟨(a₁, a₂), h, rfl⟩, fun ⟨⟨b₁, b₂⟩, h₁, h₂⟩ => show (g a₁, g a₂) ∈ r from have h₃ : ⟦b₁⟧ = a₁ ∧ ⟦b₂⟧ = a₂ := Prod.ext_iff.1 h₂ h₃.1 ▸ h₃.2 ▸ h₁⟩ theorem exists_image_iff (f : α → β) (x : Set α) (P : β → Prop) : (∃ a : f '' x, P a) ↔ ∃ a : x, P (f a) := ⟨fun ⟨a, h⟩ => ⟨⟨_, a.prop.choose_spec.1⟩, a.prop.choose_spec.2.symm ▸ h⟩, fun ⟨a, h⟩ => ⟨⟨_, _, a.prop, rfl⟩, h⟩⟩ theorem imageFactorization_eq {f : α → β} {s : Set α} : Subtype.val ∘ imageFactorization f s = f ∘ Subtype.val := funext fun _ => rfl theorem surjective_onto_image {f : α → β} {s : Set α} : Surjective (imageFactorization f s) := fun ⟨_, ⟨a, ha, rfl⟩⟩ => ⟨⟨a, ha⟩, rfl⟩ /-- If the only elements outside `s` are those left fixed by `σ`, then mapping by `σ` has no effect. -/ theorem image_perm {s : Set α} {σ : Equiv.Perm α} (hs : { a : α | σ a ≠ a } ⊆ s) : σ '' s = s := by ext i obtain hi | hi := eq_or_ne (σ i) i · refine ⟨?_, fun h => ⟨i, h, hi⟩⟩ rintro ⟨j, hj, h⟩ rwa [σ.injective (hi.trans h.symm)] · refine iff_of_true ⟨σ.symm i, hs fun h => hi ?_, σ.apply_symm_apply _⟩ (hs hi) convert congr_arg σ h <;> exact (σ.apply_symm_apply _).symm end Image /-! ### Lemmas about the powerset and image. -/ /-- The powerset of `{a} ∪ s` is `𝒫 s` together with `{a} ∪ t` for each `t ∈ 𝒫 s`. -/ theorem powerset_insert (s : Set α) (a : α) : 𝒫 insert a s = 𝒫 s ∪ insert a '' 𝒫 s := by ext t simp_rw [mem_union, mem_image, mem_powerset_iff] constructor · intro h by_cases hs : a ∈ t · right refine ⟨t \ {a}, ?_, ?_⟩ · rw [diff_singleton_subset_iff] assumption · rw [insert_diff_singleton, insert_eq_of_mem hs] · left exact (subset_insert_iff_of_not_mem hs).mp h · rintro (h | ⟨s', h₁, rfl⟩) · exact subset_trans h (subset_insert a s) · exact insert_subset_insert h₁ /-! ### Lemmas about range of a function. -/ section Range variable {f : ι → α} {s t : Set α} theorem forall_mem_range {p : α → Prop} : (∀ a ∈ range f, p a) ↔ ∀ i, p (f i) := by simp @[deprecated (since := "2024-02-21")] alias forall_range_iff := forall_mem_range theorem forall_subtype_range_iff {p : range f → Prop} : (∀ a : range f, p a) ↔ ∀ i, p ⟨f i, mem_range_self _⟩ := ⟨fun H i => H _, fun H ⟨y, i, hi⟩ => by subst hi apply H⟩ theorem exists_range_iff {p : α → Prop} : (∃ a ∈ range f, p a) ↔ ∃ i, p (f i) := by simp @[deprecated (since := "2024-03-10")] alias exists_range_iff' := exists_range_iff theorem exists_subtype_range_iff {p : range f → Prop} : (∃ a : range f, p a) ↔ ∃ i, p ⟨f i, mem_range_self _⟩ := ⟨fun ⟨⟨a, i, hi⟩, ha⟩ => by subst a exact ⟨i, ha⟩, fun ⟨i, hi⟩ => ⟨_, hi⟩⟩ theorem range_iff_surjective : range f = univ ↔ Surjective f := eq_univ_iff_forall alias ⟨_, _root_.Function.Surjective.range_eq⟩ := range_iff_surjective @[simp] theorem subset_range_of_surjective {f : α → β} (h : Surjective f) (s : Set β) : s ⊆ range f := Surjective.range_eq h ▸ subset_univ s @[simp] theorem image_univ {f : α → β} : f '' univ = range f := by ext simp [image, range] @[simp] theorem preimage_eq_univ_iff {f : α → β} {s} : f ⁻¹' s = univ ↔ range f ⊆ s := by rw [← univ_subset_iff, ← image_subset_iff, image_univ] theorem image_subset_range (f : α → β) (s) : f '' s ⊆ range f := by rw [← image_univ]; exact image_subset _ (subset_univ _) theorem mem_range_of_mem_image (f : α → β) (s) {x : β} (h : x ∈ f '' s) : x ∈ range f := image_subset_range f s h theorem _root_.Nat.mem_range_succ (i : ℕ) : i ∈ range Nat.succ ↔ 0 < i := ⟨by rintro ⟨n, rfl⟩ exact Nat.succ_pos n, fun h => ⟨_, Nat.succ_pred_eq_of_pos h⟩⟩ theorem Nonempty.preimage' {s : Set β} (hs : s.Nonempty) {f : α → β} (hf : s ⊆ range f) : (f ⁻¹' s).Nonempty := let ⟨_, hy⟩ := hs let ⟨x, hx⟩ := hf hy ⟨x, Set.mem_preimage.2 <| hx.symm ▸ hy⟩ theorem range_comp (g : α → β) (f : ι → α) : range (g ∘ f) = g '' range f := by aesop theorem range_subset_iff : range f ⊆ s ↔ ∀ y, f y ∈ s := forall_mem_range theorem range_subset_range_iff_exists_comp {f : α → γ} {g : β → γ} : range f ⊆ range g ↔ ∃ h : α → β, f = g ∘ h := by simp only [range_subset_iff, mem_range, Classical.skolem, Function.funext_iff, (· ∘ ·), eq_comm] theorem range_eq_iff (f : α → β) (s : Set β) : range f = s ↔ (∀ a, f a ∈ s) ∧ ∀ b ∈ s, ∃ a, f a = b := by rw [← range_subset_iff] exact le_antisymm_iff theorem range_comp_subset_range (f : α → β) (g : β → γ) : range (g ∘ f) ⊆ range g := by rw [range_comp]; apply image_subset_range theorem range_nonempty_iff_nonempty : (range f).Nonempty ↔ Nonempty ι := ⟨fun ⟨_, x, _⟩ => ⟨x⟩, fun ⟨x⟩ => ⟨f x, mem_range_self x⟩⟩ theorem range_nonempty [h : Nonempty ι] (f : ι → α) : (range f).Nonempty := range_nonempty_iff_nonempty.2 h @[simp] theorem range_eq_empty_iff {f : ι → α} : range f = ∅ ↔ IsEmpty ι := by rw [← not_nonempty_iff, ← range_nonempty_iff_nonempty, not_nonempty_iff_eq_empty] theorem range_eq_empty [IsEmpty ι] (f : ι → α) : range f = ∅ := range_eq_empty_iff.2 ‹_› instance instNonemptyRange [Nonempty ι] (f : ι → α) : Nonempty (range f) := (range_nonempty f).to_subtype @[simp] theorem image_union_image_compl_eq_range (f : α → β) : f '' s ∪ f '' sᶜ = range f := by rw [← image_union, ← image_univ, ← union_compl_self] theorem insert_image_compl_eq_range (f : α → β) (x : α) : insert (f x) (f '' {x}ᶜ) = range f := by rw [← image_insert_eq, insert_eq, union_compl_self, image_univ] theorem image_preimage_eq_range_inter {f : α → β} {t : Set β} : f '' (f ⁻¹' t) = range f ∩ t := ext fun x => ⟨fun ⟨x, hx, HEq⟩ => HEq ▸ ⟨mem_range_self _, hx⟩, fun ⟨⟨y, h_eq⟩, hx⟩ => h_eq ▸ mem_image_of_mem f <| show y ∈ f ⁻¹' t by rw [preimage, mem_setOf, h_eq]; exact hx⟩ theorem image_preimage_eq_inter_range {f : α → β} {t : Set β} : f '' (f ⁻¹' t) = t ∩ range f := by rw [image_preimage_eq_range_inter, inter_comm] theorem image_preimage_eq_of_subset {f : α → β} {s : Set β} (hs : s ⊆ range f) : f '' (f ⁻¹' s) = s := by rw [image_preimage_eq_range_inter, inter_eq_self_of_subset_right hs] theorem image_preimage_eq_iff {f : α → β} {s : Set β} : f '' (f ⁻¹' s) = s ↔ s ⊆ range f := ⟨by intro h rw [← h] apply image_subset_range, image_preimage_eq_of_subset⟩ theorem subset_range_iff_exists_image_eq {f : α → β} {s : Set β} : s ⊆ range f ↔ ∃ t, f '' t = s := ⟨fun h => ⟨_, image_preimage_eq_iff.2 h⟩, fun ⟨_, ht⟩ => ht ▸ image_subset_range _ _⟩ theorem range_image (f : α → β) : range (image f) = 𝒫 range f := ext fun _ => subset_range_iff_exists_image_eq.symm @[simp] theorem exists_subset_range_and_iff {f : α → β} {p : Set β → Prop} : (∃ s, s ⊆ range f ∧ p s) ↔ ∃ s, p (f '' s) := by rw [← exists_range_iff, range_image]; rfl @[deprecated exists_subset_range_and_iff (since := "2024-06-06")] theorem exists_subset_range_iff {f : α → β} {p : Set β → Prop} : (∃ (s : _) (_ : s ⊆ range f), p s) ↔ ∃ s, p (f '' s) := by simp @[simp] theorem forall_subset_range_iff {f : α → β} {p : Set β → Prop} : (∀ s, s ⊆ range f → p s) ↔ ∀ s, p (f '' s) := by rw [← forall_mem_range, range_image]; rfl @[simp] theorem preimage_subset_preimage_iff {s t : Set α} {f : β → α} (hs : s ⊆ range f) : f ⁻¹' s ⊆ f ⁻¹' t ↔ s ⊆ t := by constructor · intro h x hx rcases hs hx with ⟨y, rfl⟩ exact h hx intro h x; apply h theorem preimage_eq_preimage' {s t : Set α} {f : β → α} (hs : s ⊆ range f) (ht : t ⊆ range f) : f ⁻¹' s = f ⁻¹' t ↔ s = t := by constructor · intro h apply Subset.antisymm · rw [← preimage_subset_preimage_iff hs, h] · rw [← preimage_subset_preimage_iff ht, h] rintro rfl; rfl -- Porting note: -- @[simp] `simp` can prove this theorem preimage_inter_range {f : α → β} {s : Set β} : f ⁻¹' (s ∩ range f) = f ⁻¹' s := Set.ext fun x => and_iff_left ⟨x, rfl⟩ -- Porting note: -- @[simp] `simp` can prove this theorem preimage_range_inter {f : α → β} {s : Set β} : f ⁻¹' (range f ∩ s) = f ⁻¹' s := by rw [inter_comm, preimage_inter_range] theorem preimage_image_preimage {f : α → β} {s : Set β} : f ⁻¹' (f '' (f ⁻¹' s)) = f ⁻¹' s := by rw [image_preimage_eq_range_inter, preimage_range_inter] @[simp, mfld_simps] theorem range_id : range (@id α) = univ := range_iff_surjective.2 surjective_id @[simp, mfld_simps] theorem range_id' : (range fun x : α => x) = univ := range_id @[simp] theorem _root_.Prod.range_fst [Nonempty β] : range (Prod.fst : α × β → α) = univ := Prod.fst_surjective.range_eq @[simp] theorem _root_.Prod.range_snd [Nonempty α] : range (Prod.snd : α × β → β) = univ := Prod.snd_surjective.range_eq @[simp] theorem range_eval {α : ι → Sort _} [∀ i, Nonempty (α i)] (i : ι) : range (eval i : (∀ i, α i) → α i) = univ := (surjective_eval i).range_eq theorem range_inl : range (@Sum.inl α β) = {x | Sum.isLeft x} := by ext (_|_) <;> simp theorem range_inr : range (@Sum.inr α β) = {x | Sum.isRight x} := by ext (_|_) <;> simp theorem isCompl_range_inl_range_inr : IsCompl (range <| @Sum.inl α β) (range Sum.inr) := IsCompl.of_le (by rintro y ⟨⟨x₁, rfl⟩, ⟨x₂, h⟩⟩ exact Sum.noConfusion h) (by rintro (x | y) - <;> [left; right] <;> exact mem_range_self _) @[simp] theorem range_inl_union_range_inr : range (Sum.inl : α → α ⊕ β) ∪ range Sum.inr = univ := isCompl_range_inl_range_inr.sup_eq_top @[simp] theorem range_inl_inter_range_inr : range (Sum.inl : α → α ⊕ β) ∩ range Sum.inr = ∅ := isCompl_range_inl_range_inr.inf_eq_bot @[simp] theorem range_inr_union_range_inl : range (Sum.inr : β → α ⊕ β) ∪ range Sum.inl = univ := isCompl_range_inl_range_inr.symm.sup_eq_top @[simp] theorem range_inr_inter_range_inl : range (Sum.inr : β → α ⊕ β) ∩ range Sum.inl = ∅ := isCompl_range_inl_range_inr.symm.inf_eq_bot @[simp] theorem preimage_inl_image_inr (s : Set β) : Sum.inl ⁻¹' (@Sum.inr α β '' s) = ∅ := by ext simp @[simp] theorem preimage_inr_image_inl (s : Set α) : Sum.inr ⁻¹' (@Sum.inl α β '' s) = ∅ := by ext simp @[simp] theorem preimage_inl_range_inr : Sum.inl ⁻¹' range (Sum.inr : β → α ⊕ β) = ∅ := by rw [← image_univ, preimage_inl_image_inr] @[simp] theorem preimage_inr_range_inl : Sum.inr ⁻¹' range (Sum.inl : α → α ⊕ β) = ∅ := by rw [← image_univ, preimage_inr_image_inl] @[simp] theorem compl_range_inl : (range (Sum.inl : α → α ⊕ β))ᶜ = range (Sum.inr : β → α ⊕ β) := IsCompl.compl_eq isCompl_range_inl_range_inr @[simp] theorem compl_range_inr : (range (Sum.inr : β → α ⊕ β))ᶜ = range (Sum.inl : α → α ⊕ β) := IsCompl.compl_eq isCompl_range_inl_range_inr.symm theorem image_preimage_inl_union_image_preimage_inr (s : Set (α ⊕ β)) : Sum.inl '' (Sum.inl ⁻¹' s) ∪ Sum.inr '' (Sum.inr ⁻¹' s) = s := by rw [image_preimage_eq_inter_range, image_preimage_eq_inter_range, ← inter_union_distrib_left, range_inl_union_range_inr, inter_univ] @[simp] theorem range_quot_mk (r : α → α → Prop) : range (Quot.mk r) = univ := (surjective_quot_mk r).range_eq @[simp] theorem range_quot_lift {r : ι → ι → Prop} (hf : ∀ x y, r x y → f x = f y) : range (Quot.lift f hf) = range f := ext fun _ => (surjective_quot_mk _).exists -- Porting note: the `Setoid α` instance is not being filled in @[simp] theorem range_quotient_mk [sa : Setoid α] : (range (α := Quotient sa) fun x : α => ⟦x⟧) = univ := range_quot_mk _ @[simp] theorem range_quotient_lift [s : Setoid ι] (hf) : range (Quotient.lift f hf : Quotient s → α) = range f := range_quot_lift _ @[simp] theorem range_quotient_mk' {s : Setoid α} : range (Quotient.mk' : α → Quotient s) = univ := range_quot_mk _ @[simp] lemma Quotient.range_mk'' {sa : Setoid α} : range (Quotient.mk'' (s₁ := sa)) = univ := range_quotient_mk @[simp] theorem range_quotient_lift_on' {s : Setoid ι} (hf) : (range fun x : Quotient s => Quotient.liftOn' x f hf) = range f := range_quot_lift _ instance canLift (c) (p) [CanLift α β c p] : CanLift (Set α) (Set β) (c '' ·) fun s => ∀ x ∈ s, p x where prf _ hs := subset_range_iff_exists_image_eq.mp fun x hx => CanLift.prf _ (hs x hx) theorem range_const_subset {c : α} : (range fun _ : ι => c) ⊆ {c} := range_subset_iff.2 fun _ => rfl @[simp] theorem range_const : ∀ [Nonempty ι] {c : α}, (range fun _ : ι => c) = {c} | ⟨x⟩, _ => (Subset.antisymm range_const_subset) fun _ hy => (mem_singleton_iff.1 hy).symm ▸ mem_range_self x theorem range_subtype_map {p : α → Prop} {q : β → Prop} (f : α → β) (h : ∀ x, p x → q (f x)) : range (Subtype.map f h) = (↑) ⁻¹' (f '' { x | p x }) := by ext ⟨x, hx⟩ simp_rw [mem_preimage, mem_range, mem_image, Subtype.exists, Subtype.map] simp only [Subtype.mk.injEq, exists_prop, mem_setOf_eq] theorem image_swap_eq_preimage_swap : image (@Prod.swap α β) = preimage Prod.swap := image_eq_preimage_of_inverse Prod.swap_leftInverse Prod.swap_rightInverse theorem preimage_singleton_nonempty {f : α → β} {y : β} : (f ⁻¹' {y}).Nonempty ↔ y ∈ range f := Iff.rfl theorem preimage_singleton_eq_empty {f : α → β} {y : β} : f ⁻¹' {y} = ∅ ↔ y ∉ range f := not_nonempty_iff_eq_empty.symm.trans preimage_singleton_nonempty.not theorem range_subset_singleton {f : ι → α} {x : α} : range f ⊆ {x} ↔ f = const ι x := by simp [range_subset_iff, funext_iff, mem_singleton] theorem image_compl_preimage {f : α → β} {s : Set β} : f '' (f ⁻¹' s)ᶜ = range f \ s := by rw [compl_eq_univ_diff, image_diff_preimage, image_univ] theorem rangeFactorization_eq {f : ι → β} : Subtype.val ∘ rangeFactorization f = f := funext fun _ => rfl @[simp] theorem rangeFactorization_coe (f : ι → β) (a : ι) : (rangeFactorization f a : β) = f a := rfl @[simp] theorem coe_comp_rangeFactorization (f : ι → β) : (↑) ∘ rangeFactorization f = f := rfl theorem surjective_onto_range : Surjective (rangeFactorization f) := fun ⟨_, ⟨i, rfl⟩⟩ => ⟨i, rfl⟩ theorem image_eq_range (f : α → β) (s : Set α) : f '' s = range fun x : s => f x := by ext constructor · rintro ⟨x, h1, h2⟩ exact ⟨⟨x, h1⟩, h2⟩ · rintro ⟨⟨x, h1⟩, h2⟩ exact ⟨x, h1, h2⟩ theorem _root_.Sum.range_eq (f : α ⊕ β → γ) : range f = range (f ∘ Sum.inl) ∪ range (f ∘ Sum.inr) := ext fun _ => Sum.exists @[simp] theorem Sum.elim_range (f : α → γ) (g : β → γ) : range (Sum.elim f g) = range f ∪ range g := Sum.range_eq _ theorem range_ite_subset' {p : Prop} [Decidable p] {f g : α → β} : range (if p then f else g) ⊆ range f ∪ range g := by by_cases h : p · rw [if_pos h] exact subset_union_left · rw [if_neg h] exact subset_union_right theorem range_ite_subset {p : α → Prop} [DecidablePred p] {f g : α → β} : (range fun x => if p x then f x else g x) ⊆ range f ∪ range g := by rw [range_subset_iff]; intro x; by_cases h : p x · simp only [if_pos h, mem_union, mem_range, exists_apply_eq_apply, true_or] · simp [if_neg h, mem_union, mem_range_self] @[simp] theorem preimage_range (f : α → β) : f ⁻¹' range f = univ := eq_univ_of_forall mem_range_self /-- The range of a function from a `Unique` type contains just the function applied to its single value. -/ theorem range_unique [h : Unique ι] : range f = {f default} := by ext x rw [mem_range] constructor · rintro ⟨i, hi⟩ rw [h.uniq i] at hi exact hi ▸ mem_singleton _ · exact fun h => ⟨default, h.symm⟩ theorem range_diff_image_subset (f : α → β) (s : Set α) : range f \ f '' s ⊆ f '' sᶜ := fun _ ⟨⟨x, h₁⟩, h₂⟩ => ⟨x, fun h => h₂ ⟨x, h, h₁⟩, h₁⟩ theorem range_diff_image {f : α → β} (H : Injective f) (s : Set α) : range f \ f '' s = f '' sᶜ := (Subset.antisymm (range_diff_image_subset f s)) fun _ ⟨_, hx, hy⟩ => hy ▸ ⟨mem_range_self _, fun ⟨_, hx', Eq⟩ => hx <| H Eq ▸ hx'⟩ @[simp] theorem range_inclusion (h : s ⊆ t) : range (inclusion h) = { x : t | (x : α) ∈ s } := by ext ⟨x, hx⟩ -- Porting note: `simp [inclusion]` doesn't solve goal apply Iff.intro · rw [mem_range] rintro ⟨a, ha⟩ rw [inclusion, Subtype.mk.injEq] at ha rw [mem_setOf, Subtype.coe_mk, ← ha] exact Subtype.coe_prop _ · rw [mem_setOf, Subtype.coe_mk, mem_range] intro hx' use ⟨x, hx'⟩ trivial -- simp_rw [inclusion, mem_range, Subtype.mk_eq_mk] -- rw [SetCoe.exists, Subtype.coe_mk, exists_prop, exists_eq_right, mem_set_of, Subtype.coe_mk] -- When `f` is injective, see also `Equiv.ofInjective`. theorem leftInverse_rangeSplitting (f : α → β) : LeftInverse (rangeFactorization f) (rangeSplitting f) := fun x => by apply Subtype.ext -- Porting note: why doesn't `ext` find this lemma? simp only [rangeFactorization_coe] apply apply_rangeSplitting theorem rangeSplitting_injective (f : α → β) : Injective (rangeSplitting f) := (leftInverse_rangeSplitting f).injective theorem rightInverse_rangeSplitting {f : α → β} (h : Injective f) : RightInverse (rangeFactorization f) (rangeSplitting f) := (leftInverse_rangeSplitting f).rightInverse_of_injective fun _ _ hxy => h <| Subtype.ext_iff.1 hxy theorem preimage_rangeSplitting {f : α → β} (hf : Injective f) : preimage (rangeSplitting f) = image (rangeFactorization f) := (image_eq_preimage_of_inverse (rightInverse_rangeSplitting hf) (leftInverse_rangeSplitting f)).symm theorem isCompl_range_some_none (α : Type*) : IsCompl (range (some : α → Option α)) {none} := IsCompl.of_le (fun _ ⟨⟨_, ha⟩, (hn : _ = none)⟩ => Option.some_ne_none _ (ha.trans hn)) fun x _ => Option.casesOn x (Or.inr rfl) fun _ => Or.inl <| mem_range_self _ @[simp] theorem compl_range_some (α : Type*) : (range (some : α → Option α))ᶜ = {none} := (isCompl_range_some_none α).compl_eq @[simp] theorem range_some_inter_none (α : Type*) : range (some : α → Option α) ∩ {none} = ∅ := (isCompl_range_some_none α).inf_eq_bot -- Porting note: -- @[simp] `simp` can prove this theorem range_some_union_none (α : Type*) : range (some : α → Option α) ∪ {none} = univ := (isCompl_range_some_none α).sup_eq_top @[simp] theorem insert_none_range_some (α : Type*) : insert none (range (some : α → Option α)) = univ := (isCompl_range_some_none α).symm.sup_eq_top end Range section Subsingleton variable {s : Set α} /-- The image of a subsingleton is a subsingleton. -/ theorem Subsingleton.image (hs : s.Subsingleton) (f : α → β) : (f '' s).Subsingleton := fun _ ⟨_, hx, Hx⟩ _ ⟨_, hy, Hy⟩ => Hx ▸ Hy ▸ congr_arg f (hs hx hy) /-- The preimage of a subsingleton under an injective map is a subsingleton. -/ theorem Subsingleton.preimage {s : Set β} (hs : s.Subsingleton) {f : α → β} (hf : Function.Injective f) : (f ⁻¹' s).Subsingleton := fun _ ha _ hb => hf <| hs ha hb /-- If the image of a set under an injective map is a subsingleton, the set is a subsingleton. -/ theorem subsingleton_of_image {f : α → β} (hf : Function.Injective f) (s : Set α) (hs : (f '' s).Subsingleton) : s.Subsingleton := (hs.preimage hf).anti <| subset_preimage_image _ _ /-- If the preimage of a set under a surjective map is a subsingleton, the set is a subsingleton. -/ theorem subsingleton_of_preimage {f : α → β} (hf : Function.Surjective f) (s : Set β) (hs : (f ⁻¹' s).Subsingleton) : s.Subsingleton := fun fx hx fy hy => by rcases hf fx, hf fy with ⟨⟨x, rfl⟩, ⟨y, rfl⟩⟩ exact congr_arg f (hs hx hy) theorem subsingleton_range {α : Sort*} [Subsingleton α] (f : α → β) : (range f).Subsingleton := forall_mem_range.2 fun x => forall_mem_range.2 fun y => congr_arg f (Subsingleton.elim x y) /-- The preimage of a nontrivial set under a surjective map is nontrivial. -/ theorem Nontrivial.preimage {s : Set β} (hs : s.Nontrivial) {f : α → β} (hf : Function.Surjective f) : (f ⁻¹' s).Nontrivial := by rcases hs with ⟨fx, hx, fy, hy, hxy⟩ rcases hf fx, hf fy with ⟨⟨x, rfl⟩, ⟨y, rfl⟩⟩ exact ⟨x, hx, y, hy, mt (congr_arg f) hxy⟩ /-- The image of a nontrivial set under an injective map is nontrivial. -/ theorem Nontrivial.image (hs : s.Nontrivial) {f : α → β} (hf : Function.Injective f) : (f '' s).Nontrivial := let ⟨x, hx, y, hy, hxy⟩ := hs ⟨f x, mem_image_of_mem f hx, f y, mem_image_of_mem f hy, hf.ne hxy⟩ /-- If the image of a set is nontrivial, the set is nontrivial. -/ theorem nontrivial_of_image (f : α → β) (s : Set α) (hs : (f '' s).Nontrivial) : s.Nontrivial := let ⟨_, ⟨x, hx, rfl⟩, _, ⟨y, hy, rfl⟩, hxy⟩ := hs ⟨x, hx, y, hy, mt (congr_arg f) hxy⟩ @[simp] theorem image_nontrivial {f : α → β} (hf : f.Injective) : (f '' s).Nontrivial ↔ s.Nontrivial := ⟨nontrivial_of_image f s, fun h ↦ h.image hf⟩ /-- If the preimage of a set under an injective map is nontrivial, the set is nontrivial. -/ theorem nontrivial_of_preimage {f : α → β} (hf : Function.Injective f) (s : Set β) (hs : (f ⁻¹' s).Nontrivial) : s.Nontrivial := (hs.image hf).mono <| image_preimage_subset _ _ end Subsingleton end Set namespace Function variable {α β : Type*} {ι : Sort*} {f : α → β} open Set theorem Surjective.preimage_injective (hf : Surjective f) : Injective (preimage f) := fun _ _ => (preimage_eq_preimage hf).1 theorem Injective.preimage_image (hf : Injective f) (s : Set α) : f ⁻¹' (f '' s) = s := preimage_image_eq s hf theorem Injective.preimage_surjective (hf : Injective f) : Surjective (preimage f) := by intro s use f '' s rw [hf.preimage_image] theorem Injective.subsingleton_image_iff (hf : Injective f) {s : Set α} : (f '' s).Subsingleton ↔ s.Subsingleton := ⟨subsingleton_of_image hf s, fun h => h.image f⟩ theorem Surjective.image_preimage (hf : Surjective f) (s : Set β) : f '' (f ⁻¹' s) = s := image_preimage_eq s hf theorem Surjective.image_surjective (hf : Surjective f) : Surjective (image f) := by intro s use f ⁻¹' s rw [hf.image_preimage] @[simp] theorem Surjective.nonempty_preimage (hf : Surjective f) {s : Set β} : (f ⁻¹' s).Nonempty ↔ s.Nonempty := by rw [← image_nonempty, hf.image_preimage] theorem Injective.image_injective (hf : Injective f) : Injective (image f) := by intro s t h rw [← preimage_image_eq s hf, ← preimage_image_eq t hf, h] theorem Surjective.preimage_subset_preimage_iff {s t : Set β} (hf : Surjective f) : f ⁻¹' s ⊆ f ⁻¹' t ↔ s ⊆ t := by apply Set.preimage_subset_preimage_iff rw [hf.range_eq] apply subset_univ theorem Surjective.range_comp {ι' : Sort*} {f : ι → ι'} (hf : Surjective f) (g : ι' → α) : range (g ∘ f) = range g := ext fun y => (@Surjective.exists _ _ _ hf fun x => g x = y).symm theorem Injective.mem_range_iff_exists_unique (hf : Injective f) {b : β} : b ∈ range f ↔ ∃! a, f a = b := ⟨fun ⟨a, h⟩ => ⟨a, h, fun _ ha => hf (ha.trans h.symm)⟩, ExistsUnique.exists⟩ theorem Injective.exists_unique_of_mem_range (hf : Injective f) {b : β} (hb : b ∈ range f) : ∃! a, f a = b := hf.mem_range_iff_exists_unique.mp hb theorem Injective.compl_image_eq (hf : Injective f) (s : Set α) : (f '' s)ᶜ = f '' sᶜ ∪ (range f)ᶜ := by ext y rcases em (y ∈ range f) with (⟨x, rfl⟩ | hx) · simp [hf.eq_iff] · rw [mem_range, not_exists] at hx simp [hx] theorem LeftInverse.image_image {g : β → α} (h : LeftInverse g f) (s : Set α) : g '' (f '' s) = s := by rw [← image_comp, h.comp_eq_id, image_id] theorem LeftInverse.preimage_preimage {g : β → α} (h : LeftInverse g f) (s : Set α) : f ⁻¹' (g ⁻¹' s) = s := by rw [← preimage_comp, h.comp_eq_id, preimage_id] protected theorem Involutive.preimage {f : α → α} (hf : Involutive f) : Involutive (preimage f) := hf.rightInverse.preimage_preimage end Function namespace EquivLike variable {ι ι' : Sort*} {E : Type*} [EquivLike E ι ι'] @[simp] lemma range_comp {α : Type*} (f : ι' → α) (e : E) : range (f ∘ e) = range f := (EquivLike.surjective _).range_comp _ end EquivLike /-! ### Image and preimage on subtypes -/ namespace Subtype variable {α : Type*} theorem coe_image {p : α → Prop} {s : Set (Subtype p)} : (↑) '' s = { x | ∃ h : p x, (⟨x, h⟩ : Subtype p) ∈ s } := Set.ext fun a => ⟨fun ⟨⟨_, ha'⟩, in_s, h_eq⟩ => h_eq ▸ ⟨ha', in_s⟩, fun ⟨ha, in_s⟩ => ⟨⟨a, ha⟩, in_s, rfl⟩⟩ @[simp] theorem coe_image_of_subset {s t : Set α} (h : t ⊆ s) : (↑) '' { x : ↥s | ↑x ∈ t } = t := by ext x rw [mem_image] exact ⟨fun ⟨_, hx', hx⟩ => hx ▸ hx', fun hx => ⟨⟨x, h hx⟩, hx, rfl⟩⟩ theorem range_coe {s : Set α} : range ((↑) : s → α) = s := by rw [← image_univ] simp [-image_univ, coe_image] /-- A variant of `range_coe`. Try to use `range_coe` if possible. This version is useful when defining a new type that is defined as the subtype of something. In that case, the coercion doesn't fire anymore. -/ theorem range_val {s : Set α} : range (Subtype.val : s → α) = s := range_coe /-- We make this the simp lemma instead of `range_coe`. The reason is that if we write for `s : Set α` the function `(↑) : s → α`, then the inferred implicit arguments of `(↑)` are `↑α (fun x ↦ x ∈ s)`. -/ @[simp] theorem range_coe_subtype {p : α → Prop} : range ((↑) : Subtype p → α) = { x | p x } := range_coe @[simp] theorem coe_preimage_self (s : Set α) : ((↑) : s → α) ⁻¹' s = univ := by rw [← preimage_range, range_coe] theorem range_val_subtype {p : α → Prop} : range (Subtype.val : Subtype p → α) = { x | p x } := range_coe theorem coe_image_subset (s : Set α) (t : Set s) : ((↑) : s → α) '' t ⊆ s := fun x ⟨y, _, yvaleq⟩ => by rw [← yvaleq]; exact y.property theorem coe_image_univ (s : Set α) : ((↑) : s → α) '' Set.univ = s := image_univ.trans range_coe @[simp] theorem image_preimage_coe (s t : Set α) : ((↑) : s → α) '' (((↑) : s → α) ⁻¹' t) = s ∩ t := image_preimage_eq_range_inter.trans <| congr_arg (· ∩ t) range_coe theorem image_preimage_val (s t : Set α) : (Subtype.val : s → α) '' (Subtype.val ⁻¹' t) = s ∩ t := image_preimage_coe s t theorem preimage_coe_eq_preimage_coe_iff {s t u : Set α} : ((↑) : s → α) ⁻¹' t = ((↑) : s → α) ⁻¹' u ↔ s ∩ t = s ∩ u := by rw [← image_preimage_coe, ← image_preimage_coe, coe_injective.image_injective.eq_iff] theorem preimage_coe_self_inter (s t : Set α) : ((↑) : s → α) ⁻¹' (s ∩ t) = ((↑) : s → α) ⁻¹' t := by rw [preimage_coe_eq_preimage_coe_iff, ← inter_assoc, inter_self] -- Porting note: -- @[simp] `simp` can prove this theorem preimage_coe_inter_self (s t : Set α) : ((↑) : s → α) ⁻¹' (t ∩ s) = ((↑) : s → α) ⁻¹' t := by rw [inter_comm, preimage_coe_self_inter] theorem preimage_val_eq_preimage_val_iff (s t u : Set α) : (Subtype.val : s → α) ⁻¹' t = Subtype.val ⁻¹' u ↔ s ∩ t = s ∩ u := preimage_coe_eq_preimage_coe_iff lemma preimage_val_subset_preimage_val_iff (s t u : Set α) : (Subtype.val ⁻¹' t : Set s) ⊆ Subtype.val ⁻¹' u ↔ s ∩ t ⊆ s ∩ u := by constructor · rw [← image_preimage_coe, ← image_preimage_coe] exact image_subset _ · intro h x a exact (h ⟨x.2, a⟩).2 theorem exists_set_subtype {t : Set α} (p : Set α → Prop) : (∃ s : Set t, p (((↑) : t → α) '' s)) ↔ ∃ s : Set α, s ⊆ t ∧ p s := by rw [← exists_subset_range_and_iff, range_coe] theorem forall_set_subtype {t : Set α} (p : Set α → Prop) : (∀ s : Set t, p (((↑) : t → α) '' s)) ↔ ∀ s : Set α, s ⊆ t → p s := by rw [← forall_subset_range_iff, range_coe] theorem preimage_coe_nonempty {s t : Set α} : (((↑) : s → α) ⁻¹' t).Nonempty ↔ (s ∩ t).Nonempty := by rw [← image_preimage_coe, image_nonempty] theorem preimage_coe_eq_empty {s t : Set α} : ((↑) : s → α) ⁻¹' t = ∅ ↔ s ∩ t = ∅ := by simp [← not_nonempty_iff_eq_empty, preimage_coe_nonempty] -- Porting note: -- @[simp] `simp` can prove this theorem preimage_coe_compl (s : Set α) : ((↑) : s → α) ⁻¹' sᶜ = ∅ := preimage_coe_eq_empty.2 (inter_compl_self s) @[simp] theorem preimage_coe_compl' (s : Set α) : (fun x : (sᶜ : Set α) => (x : α)) ⁻¹' s = ∅ := preimage_coe_eq_empty.2 (compl_inter_self s) end Subtype /-! ### Images and preimages on `Option` -/ open Set namespace Option theorem injective_iff {α β} {f : Option α → β} : Injective f ↔ Injective (f ∘ some) ∧ f none ∉ range (f ∘ some) := by simp only [mem_range, not_exists, (· ∘ ·)] refine ⟨fun hf => ⟨hf.comp (Option.some_injective _), fun x => hf.ne <| Option.some_ne_none _⟩, ?_⟩ rintro ⟨h_some, h_none⟩ (_ | a) (_ | b) hab exacts [rfl, (h_none _ hab.symm).elim, (h_none _ hab).elim, congr_arg some (h_some hab)] theorem range_eq {α β} (f : Option α → β) : range f = insert (f none) (range (f ∘ some)) := Set.ext fun _ => Option.exists.trans <| eq_comm.or Iff.rfl end Option theorem WithBot.range_eq {α β} (f : WithBot α → β) : range f = insert (f ⊥) (range (f ∘ WithBot.some : α → β)) := Option.range_eq f theorem WithTop.range_eq {α β} (f : WithTop α → β) : range f = insert (f ⊤) (range (f ∘ WithBot.some : α → β)) := Option.range_eq f namespace Set open Function /-! ### Injectivity and surjectivity lemmas for image and preimage -/ section ImagePreimage variable {α : Type u} {β : Type v} {f : α → β} @[simp] theorem preimage_injective : Injective (preimage f) ↔ Surjective f := by refine ⟨fun h y => ?_, Surjective.preimage_injective⟩ obtain ⟨x, hx⟩ : (f ⁻¹' {y}).Nonempty := by rw [h.nonempty_apply_iff preimage_empty] apply singleton_nonempty exact ⟨x, hx⟩ @[simp] theorem preimage_surjective : Surjective (preimage f) ↔ Injective f := by refine ⟨fun h x x' hx => ?_, Injective.preimage_surjective⟩ cases' h {x} with s hs; have := mem_singleton x rwa [← hs, mem_preimage, hx, ← mem_preimage, hs, mem_singleton_iff, eq_comm] at this @[simp] theorem image_surjective : Surjective (image f) ↔ Surjective f := by refine ⟨fun h y => ?_, Surjective.image_surjective⟩ cases' h {y} with s hs have := mem_singleton y; rw [← hs] at this; rcases this with ⟨x, _, hx⟩ exact ⟨x, hx⟩ @[simp] theorem image_injective : Injective (image f) ↔ Injective f := by refine ⟨fun h x x' hx => ?_, Injective.image_injective⟩ rw [← singleton_eq_singleton_iff]; apply h rw [image_singleton, image_singleton, hx] theorem preimage_eq_iff_eq_image {f : α → β} (hf : Bijective f) {s t} : f ⁻¹' s = t ↔ s = f '' t := by rw [← image_eq_image hf.1, hf.2.image_preimage] theorem eq_preimage_iff_image_eq {f : α → β} (hf : Bijective f) {s t} : s = f ⁻¹' t ↔ f '' s = t := by rw [← image_eq_image hf.1, hf.2.image_preimage] end ImagePreimage end Set /-! ### Disjoint lemmas for image and preimage -/ section Disjoint variable {α β γ : Type*} {f : α → β} {s t : Set α} theorem Disjoint.preimage (f : α → β) {s t : Set β} (h : Disjoint s t) : Disjoint (f ⁻¹' s) (f ⁻¹' t) := disjoint_iff_inf_le.mpr fun _ hx => h.le_bot hx lemma Codisjoint.preimage (f : α → β) {s t : Set β} (h : Codisjoint s t) : Codisjoint (f ⁻¹' s) (f ⁻¹' t) := by simp only [codisjoint_iff_le_sup, Set.sup_eq_union, top_le_iff, ← Set.preimage_union] at h ⊢ rw [h]; rfl lemma IsCompl.preimage (f : α → β) {s t : Set β} (h : IsCompl s t) : IsCompl (f ⁻¹' s) (f ⁻¹' t) := ⟨h.1.preimage f, h.2.preimage f⟩ namespace Set theorem disjoint_image_image {f : β → α} {g : γ → α} {s : Set β} {t : Set γ} (h : ∀ b ∈ s, ∀ c ∈ t, f b ≠ g c) : Disjoint (f '' s) (g '' t) := disjoint_iff_inf_le.mpr <| by rintro a ⟨⟨b, hb, eq⟩, c, hc, rfl⟩; exact h b hb c hc eq theorem disjoint_image_of_injective (hf : Injective f) {s t : Set α} (hd : Disjoint s t) : Disjoint (f '' s) (f '' t) := disjoint_image_image fun _ hx _ hy => hf.ne fun H => Set.disjoint_iff.1 hd ⟨hx, H.symm ▸ hy⟩ theorem _root_.Disjoint.of_image (h : Disjoint (f '' s) (f '' t)) : Disjoint s t := disjoint_iff_inf_le.mpr fun _ hx => disjoint_left.1 h (mem_image_of_mem _ hx.1) (mem_image_of_mem _ hx.2) @[simp] theorem disjoint_image_iff (hf : Injective f) : Disjoint (f '' s) (f '' t) ↔ Disjoint s t := ⟨Disjoint.of_image, disjoint_image_of_injective hf⟩ theorem _root_.Disjoint.of_preimage (hf : Surjective f) {s t : Set β} (h : Disjoint (f ⁻¹' s) (f ⁻¹' t)) : Disjoint s t := by rw [disjoint_iff_inter_eq_empty, ← image_preimage_eq (_ ∩ _) hf, preimage_inter, h.inter_eq, image_empty] @[simp] theorem disjoint_preimage_iff (hf : Surjective f) {s t : Set β} : Disjoint (f ⁻¹' s) (f ⁻¹' t) ↔ Disjoint s t := ⟨Disjoint.of_preimage hf, Disjoint.preimage _⟩ theorem preimage_eq_empty {s : Set β} (h : Disjoint s (range f)) : f ⁻¹' s = ∅ := by simpa using h.preimage f theorem preimage_eq_empty_iff {s : Set β} : f ⁻¹' s = ∅ ↔ Disjoint s (range f) := ⟨fun h => by simp only [eq_empty_iff_forall_not_mem, disjoint_iff_inter_eq_empty, not_exists, mem_inter_iff, not_and, mem_range, mem_preimage] at h ⊢ intro y hy x hx rw [← hx] at hy exact h x hy, preimage_eq_empty⟩ end Set end Disjoint section Sigma variable {α : Type*} {β : α → Type*} {i j : α} {s : Set (β i)} lemma sigma_mk_preimage_image' (h : i ≠ j) : Sigma.mk j ⁻¹' (Sigma.mk i '' s) = ∅ := by simp [image, h] lemma sigma_mk_preimage_image_eq_self : Sigma.mk i ⁻¹' (Sigma.mk i '' s) = s := by simp [image] end Sigma
Data\Set\Lattice.lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Johannes Hölzl, Mario Carneiro -/ import Mathlib.Logic.Pairwise import Mathlib.Order.CompleteBooleanAlgebra import Mathlib.Order.Directed import Mathlib.Order.GaloisConnection /-! # The set lattice This file provides usual set notation for unions and intersections, a `CompleteLattice` instance for `Set α`, and some more set constructions. ## Main declarations * `Set.iUnion`: **i**ndexed **union**. Union of an indexed family of sets. * `Set.iInter`: **i**ndexed **inter**section. Intersection of an indexed family of sets. * `Set.sInter`: **s**et **inter**section. Intersection of sets belonging to a set of sets. * `Set.sUnion`: **s**et **union**. Union of sets belonging to a set of sets. * `Set.sInter_eq_biInter`, `Set.sUnion_eq_biInter`: Shows that `⋂₀ s = ⋂ x ∈ s, x` and `⋃₀ s = ⋃ x ∈ s, x`. * `Set.completeAtomicBooleanAlgebra`: `Set α` is a `CompleteAtomicBooleanAlgebra` with `≤ = ⊆`, `< = ⊂`, `⊓ = ∩`, `⊔ = ∪`, `⨅ = ⋂`, `⨆ = ⋃` and `\` as the set difference. See `Set.BooleanAlgebra`. * `Set.kernImage`: For a function `f : α → β`, `s.kernImage f` is the set of `y` such that `f ⁻¹ y ⊆ s`. * `Set.seq`: Union of the image of a set under a **seq**uence of functions. `seq s t` is the union of `f '' t` over all `f ∈ s`, where `t : Set α` and `s : Set (α → β)`. * `Set.unionEqSigmaOfDisjoint`: Equivalence between `⋃ i, t i` and `Σ i, t i`, where `t` is an indexed family of disjoint sets. ## Naming convention In lemma names, * `⋃ i, s i` is called `iUnion` * `⋂ i, s i` is called `iInter` * `⋃ i j, s i j` is called `iUnion₂`. This is an `iUnion` inside an `iUnion`. * `⋂ i j, s i j` is called `iInter₂`. This is an `iInter` inside an `iInter`. * `⋃ i ∈ s, t i` is called `biUnion` for "bounded `iUnion`". This is the special case of `iUnion₂` where `j : i ∈ s`. * `⋂ i ∈ s, t i` is called `biInter` for "bounded `iInter`". This is the special case of `iInter₂` where `j : i ∈ s`. ## Notation * `⋃`: `Set.iUnion` * `⋂`: `Set.iInter` * `⋃₀`: `Set.sUnion` * `⋂₀`: `Set.sInter` -/ open Function Set universe u variable {α β γ : Type*} {ι ι' ι₂ : Sort*} {κ κ₁ κ₂ : ι → Sort*} {κ' : ι' → Sort*} namespace Set /-! ### Complete lattice and complete Boolean algebra instances -/ theorem mem_iUnion₂ {x : γ} {s : ∀ i, κ i → Set γ} : (x ∈ ⋃ (i) (j), s i j) ↔ ∃ i j, x ∈ s i j := by simp_rw [mem_iUnion] /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ theorem mem_iInter₂ {x : γ} {s : ∀ i, κ i → Set γ} : (x ∈ ⋂ (i) (j), s i j) ↔ ∀ i j, x ∈ s i j := by simp_rw [mem_iInter] theorem mem_iUnion_of_mem {s : ι → Set α} {a : α} (i : ι) (ha : a ∈ s i) : a ∈ ⋃ i, s i := mem_iUnion.2 ⟨i, ha⟩ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ theorem mem_iUnion₂_of_mem {s : ∀ i, κ i → Set α} {a : α} {i : ι} (j : κ i) (ha : a ∈ s i j) : a ∈ ⋃ (i) (j), s i j := mem_iUnion₂.2 ⟨i, j, ha⟩ theorem mem_iInter_of_mem {s : ι → Set α} {a : α} (h : ∀ i, a ∈ s i) : a ∈ ⋂ i, s i := mem_iInter.2 h /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ theorem mem_iInter₂_of_mem {s : ∀ i, κ i → Set α} {a : α} (h : ∀ i j, a ∈ s i j) : a ∈ ⋂ (i) (j), s i j := mem_iInter₂.2 h instance completeAtomicBooleanAlgebra : CompleteAtomicBooleanAlgebra (Set α) := { instBooleanAlgebraSet with le_sSup := fun s t t_in a a_in => ⟨t, t_in, a_in⟩ sSup_le := fun s t h a ⟨t', ⟨t'_in, a_in⟩⟩ => h t' t'_in a_in le_sInf := fun s t h a a_in t' t'_in => h t' t'_in a_in sInf_le := fun s t t_in a h => h _ t_in iInf_iSup_eq := by intros; ext; simp [Classical.skolem] } section GaloisConnection variable {f : α → β} protected theorem image_preimage : GaloisConnection (image f) (preimage f) := fun _ _ => image_subset_iff protected theorem preimage_kernImage : GaloisConnection (preimage f) (kernImage f) := fun _ _ => subset_kernImage_iff.symm end GaloisConnection section kernImage variable {f : α → β} lemma kernImage_mono : Monotone (kernImage f) := Set.preimage_kernImage.monotone_u lemma kernImage_eq_compl {s : Set α} : kernImage f s = (f '' sᶜ)ᶜ := Set.preimage_kernImage.u_unique (Set.image_preimage.compl) (fun t ↦ compl_compl (f ⁻¹' t) ▸ Set.preimage_compl) lemma kernImage_compl {s : Set α} : kernImage f (sᶜ) = (f '' s)ᶜ := by rw [kernImage_eq_compl, compl_compl] lemma kernImage_empty : kernImage f ∅ = (range f)ᶜ := by rw [kernImage_eq_compl, compl_empty, image_univ] lemma kernImage_preimage_eq_iff {s : Set β} : kernImage f (f ⁻¹' s) = s ↔ (range f)ᶜ ⊆ s := by rw [kernImage_eq_compl, ← preimage_compl, compl_eq_comm, eq_comm, image_preimage_eq_iff, compl_subset_comm] lemma compl_range_subset_kernImage {s : Set α} : (range f)ᶜ ⊆ kernImage f s := by rw [← kernImage_empty] exact kernImage_mono (empty_subset _) lemma kernImage_union_preimage {s : Set α} {t : Set β} : kernImage f (s ∪ f ⁻¹' t) = kernImage f s ∪ t := by rw [kernImage_eq_compl, kernImage_eq_compl, compl_union, ← preimage_compl, image_inter_preimage, compl_inter, compl_compl] lemma kernImage_preimage_union {s : Set α} {t : Set β} : kernImage f (f ⁻¹' t ∪ s) = t ∪ kernImage f s := by rw [union_comm, kernImage_union_preimage, union_comm] end kernImage /-! ### Union and intersection over an indexed family of sets -/ instance : OrderTop (Set α) where top := univ le_top := by simp @[congr] theorem iUnion_congr_Prop {p q : Prop} {f₁ : p → Set α} {f₂ : q → Set α} (pq : p ↔ q) (f : ∀ x, f₁ (pq.mpr x) = f₂ x) : iUnion f₁ = iUnion f₂ := iSup_congr_Prop pq f @[congr] theorem iInter_congr_Prop {p q : Prop} {f₁ : p → Set α} {f₂ : q → Set α} (pq : p ↔ q) (f : ∀ x, f₁ (pq.mpr x) = f₂ x) : iInter f₁ = iInter f₂ := iInf_congr_Prop pq f theorem iUnion_plift_up (f : PLift ι → Set α) : ⋃ i, f (PLift.up i) = ⋃ i, f i := iSup_plift_up _ theorem iUnion_plift_down (f : ι → Set α) : ⋃ i, f (PLift.down i) = ⋃ i, f i := iSup_plift_down _ theorem iInter_plift_up (f : PLift ι → Set α) : ⋂ i, f (PLift.up i) = ⋂ i, f i := iInf_plift_up _ theorem iInter_plift_down (f : ι → Set α) : ⋂ i, f (PLift.down i) = ⋂ i, f i := iInf_plift_down _ theorem iUnion_eq_if {p : Prop} [Decidable p] (s : Set α) : ⋃ _ : p, s = if p then s else ∅ := iSup_eq_if _ theorem iUnion_eq_dif {p : Prop} [Decidable p] (s : p → Set α) : ⋃ h : p, s h = if h : p then s h else ∅ := iSup_eq_dif _ theorem iInter_eq_if {p : Prop} [Decidable p] (s : Set α) : ⋂ _ : p, s = if p then s else univ := iInf_eq_if _ theorem iInf_eq_dif {p : Prop} [Decidable p] (s : p → Set α) : ⋂ h : p, s h = if h : p then s h else univ := _root_.iInf_eq_dif _ theorem exists_set_mem_of_union_eq_top {ι : Type*} (t : Set ι) (s : ι → Set β) (w : ⋃ i ∈ t, s i = ⊤) (x : β) : ∃ i ∈ t, x ∈ s i := by have p : x ∈ ⊤ := Set.mem_univ x rw [← w, Set.mem_iUnion] at p simpa using p theorem nonempty_of_union_eq_top_of_nonempty {ι : Type*} (t : Set ι) (s : ι → Set α) (H : Nonempty α) (w : ⋃ i ∈ t, s i = ⊤) : t.Nonempty := by obtain ⟨x, m, -⟩ := exists_set_mem_of_union_eq_top t s w H.some exact ⟨x, m⟩ theorem nonempty_of_nonempty_iUnion {s : ι → Set α} (h_Union : (⋃ i, s i).Nonempty) : Nonempty ι := by obtain ⟨x, hx⟩ := h_Union exact ⟨Classical.choose <| mem_iUnion.mp hx⟩ theorem nonempty_of_nonempty_iUnion_eq_univ {s : ι → Set α} [Nonempty α] (h_Union : ⋃ i, s i = univ) : Nonempty ι := nonempty_of_nonempty_iUnion (s := s) (by simpa only [h_Union] using univ_nonempty) theorem setOf_exists (p : ι → β → Prop) : { x | ∃ i, p i x } = ⋃ i, { x | p i x } := ext fun _ => mem_iUnion.symm theorem setOf_forall (p : ι → β → Prop) : { x | ∀ i, p i x } = ⋂ i, { x | p i x } := ext fun _ => mem_iInter.symm theorem iUnion_subset {s : ι → Set α} {t : Set α} (h : ∀ i, s i ⊆ t) : ⋃ i, s i ⊆ t := iSup_le h /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ theorem iUnion₂_subset {s : ∀ i, κ i → Set α} {t : Set α} (h : ∀ i j, s i j ⊆ t) : ⋃ (i) (j), s i j ⊆ t := iUnion_subset fun x => iUnion_subset (h x) theorem subset_iInter {t : Set β} {s : ι → Set β} (h : ∀ i, t ⊆ s i) : t ⊆ ⋂ i, s i := le_iInf h /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ theorem subset_iInter₂ {s : Set α} {t : ∀ i, κ i → Set α} (h : ∀ i j, s ⊆ t i j) : s ⊆ ⋂ (i) (j), t i j := subset_iInter fun x => subset_iInter <| h x @[simp] theorem iUnion_subset_iff {s : ι → Set α} {t : Set α} : ⋃ i, s i ⊆ t ↔ ∀ i, s i ⊆ t := ⟨fun h _ => Subset.trans (le_iSup s _) h, iUnion_subset⟩ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ theorem iUnion₂_subset_iff {s : ∀ i, κ i → Set α} {t : Set α} : ⋃ (i) (j), s i j ⊆ t ↔ ∀ i j, s i j ⊆ t := by simp_rw [iUnion_subset_iff] @[simp] theorem subset_iInter_iff {s : Set α} {t : ι → Set α} : (s ⊆ ⋂ i, t i) ↔ ∀ i, s ⊆ t i := le_iInf_iff /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ -- Porting note (#10618): removing `simp`. `simp` can prove it theorem subset_iInter₂_iff {s : Set α} {t : ∀ i, κ i → Set α} : (s ⊆ ⋂ (i) (j), t i j) ↔ ∀ i j, s ⊆ t i j := by simp_rw [subset_iInter_iff] theorem subset_iUnion : ∀ (s : ι → Set β) (i : ι), s i ⊆ ⋃ i, s i := le_iSup theorem iInter_subset : ∀ (s : ι → Set β) (i : ι), ⋂ i, s i ⊆ s i := iInf_le /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ theorem subset_iUnion₂ {s : ∀ i, κ i → Set α} (i : ι) (j : κ i) : s i j ⊆ ⋃ (i') (j'), s i' j' := le_iSup₂ i j /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ theorem iInter₂_subset {s : ∀ i, κ i → Set α} (i : ι) (j : κ i) : ⋂ (i) (j), s i j ⊆ s i j := iInf₂_le i j /-- This rather trivial consequence of `subset_iUnion`is convenient with `apply`, and has `i` explicit for this purpose. -/ theorem subset_iUnion_of_subset {s : Set α} {t : ι → Set α} (i : ι) (h : s ⊆ t i) : s ⊆ ⋃ i, t i := le_iSup_of_le i h /-- This rather trivial consequence of `iInter_subset`is convenient with `apply`, and has `i` explicit for this purpose. -/ theorem iInter_subset_of_subset {s : ι → Set α} {t : Set α} (i : ι) (h : s i ⊆ t) : ⋂ i, s i ⊆ t := iInf_le_of_le i h /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ /-- This rather trivial consequence of `subset_iUnion₂` is convenient with `apply`, and has `i` and `j` explicit for this purpose. -/ theorem subset_iUnion₂_of_subset {s : Set α} {t : ∀ i, κ i → Set α} (i : ι) (j : κ i) (h : s ⊆ t i j) : s ⊆ ⋃ (i) (j), t i j := le_iSup₂_of_le i j h /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ /-- This rather trivial consequence of `iInter₂_subset` is convenient with `apply`, and has `i` and `j` explicit for this purpose. -/ theorem iInter₂_subset_of_subset {s : ∀ i, κ i → Set α} {t : Set α} (i : ι) (j : κ i) (h : s i j ⊆ t) : ⋂ (i) (j), s i j ⊆ t := iInf₂_le_of_le i j h theorem iUnion_mono {s t : ι → Set α} (h : ∀ i, s i ⊆ t i) : ⋃ i, s i ⊆ ⋃ i, t i := iSup_mono h @[gcongr] theorem iUnion_mono'' {s t : ι → Set α} (h : ∀ i, s i ⊆ t i) : iUnion s ⊆ iUnion t := iSup_mono h /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ theorem iUnion₂_mono {s t : ∀ i, κ i → Set α} (h : ∀ i j, s i j ⊆ t i j) : ⋃ (i) (j), s i j ⊆ ⋃ (i) (j), t i j := iSup₂_mono h theorem iInter_mono {s t : ι → Set α} (h : ∀ i, s i ⊆ t i) : ⋂ i, s i ⊆ ⋂ i, t i := iInf_mono h @[gcongr] theorem iInter_mono'' {s t : ι → Set α} (h : ∀ i, s i ⊆ t i) : iInter s ⊆ iInter t := iInf_mono h /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ theorem iInter₂_mono {s t : ∀ i, κ i → Set α} (h : ∀ i j, s i j ⊆ t i j) : ⋂ (i) (j), s i j ⊆ ⋂ (i) (j), t i j := iInf₂_mono h theorem iUnion_mono' {s : ι → Set α} {t : ι₂ → Set α} (h : ∀ i, ∃ j, s i ⊆ t j) : ⋃ i, s i ⊆ ⋃ i, t i := iSup_mono' h /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i' j') -/ theorem iUnion₂_mono' {s : ∀ i, κ i → Set α} {t : ∀ i', κ' i' → Set α} (h : ∀ i j, ∃ i' j', s i j ⊆ t i' j') : ⋃ (i) (j), s i j ⊆ ⋃ (i') (j'), t i' j' := iSup₂_mono' h theorem iInter_mono' {s : ι → Set α} {t : ι' → Set α} (h : ∀ j, ∃ i, s i ⊆ t j) : ⋂ i, s i ⊆ ⋂ j, t j := Set.subset_iInter fun j => let ⟨i, hi⟩ := h j iInter_subset_of_subset i hi /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i' j') -/ theorem iInter₂_mono' {s : ∀ i, κ i → Set α} {t : ∀ i', κ' i' → Set α} (h : ∀ i' j', ∃ i j, s i j ⊆ t i' j') : ⋂ (i) (j), s i j ⊆ ⋂ (i') (j'), t i' j' := subset_iInter₂_iff.2 fun i' j' => let ⟨_, _, hst⟩ := h i' j' (iInter₂_subset _ _).trans hst theorem iUnion₂_subset_iUnion (κ : ι → Sort*) (s : ι → Set α) : ⋃ (i) (_ : κ i), s i ⊆ ⋃ i, s i := iUnion_mono fun _ => iUnion_subset fun _ => Subset.rfl theorem iInter_subset_iInter₂ (κ : ι → Sort*) (s : ι → Set α) : ⋂ i, s i ⊆ ⋂ (i) (_ : κ i), s i := iInter_mono fun _ => subset_iInter fun _ => Subset.rfl theorem iUnion_setOf (P : ι → α → Prop) : ⋃ i, { x : α | P i x } = { x : α | ∃ i, P i x } := by ext exact mem_iUnion theorem iInter_setOf (P : ι → α → Prop) : ⋂ i, { x : α | P i x } = { x : α | ∀ i, P i x } := by ext exact mem_iInter theorem iUnion_congr_of_surjective {f : ι → Set α} {g : ι₂ → Set α} (h : ι → ι₂) (h1 : Surjective h) (h2 : ∀ x, g (h x) = f x) : ⋃ x, f x = ⋃ y, g y := h1.iSup_congr h h2 theorem iInter_congr_of_surjective {f : ι → Set α} {g : ι₂ → Set α} (h : ι → ι₂) (h1 : Surjective h) (h2 : ∀ x, g (h x) = f x) : ⋂ x, f x = ⋂ y, g y := h1.iInf_congr h h2 lemma iUnion_congr {s t : ι → Set α} (h : ∀ i, s i = t i) : ⋃ i, s i = ⋃ i, t i := iSup_congr h lemma iInter_congr {s t : ι → Set α} (h : ∀ i, s i = t i) : ⋂ i, s i = ⋂ i, t i := iInf_congr h /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ lemma iUnion₂_congr {s t : ∀ i, κ i → Set α} (h : ∀ i j, s i j = t i j) : ⋃ (i) (j), s i j = ⋃ (i) (j), t i j := iUnion_congr fun i => iUnion_congr <| h i /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ lemma iInter₂_congr {s t : ∀ i, κ i → Set α} (h : ∀ i j, s i j = t i j) : ⋂ (i) (j), s i j = ⋂ (i) (j), t i j := iInter_congr fun i => iInter_congr <| h i section Nonempty variable [Nonempty ι] {f : ι → Set α} {s : Set α} lemma iUnion_const (s : Set β) : ⋃ _ : ι, s = s := iSup_const lemma iInter_const (s : Set β) : ⋂ _ : ι, s = s := iInf_const lemma iUnion_eq_const (hf : ∀ i, f i = s) : ⋃ i, f i = s := (iUnion_congr hf).trans <| iUnion_const _ lemma iInter_eq_const (hf : ∀ i, f i = s) : ⋂ i, f i = s := (iInter_congr hf).trans <| iInter_const _ end Nonempty @[simp] theorem compl_iUnion (s : ι → Set β) : (⋃ i, s i)ᶜ = ⋂ i, (s i)ᶜ := compl_iSup /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ theorem compl_iUnion₂ (s : ∀ i, κ i → Set α) : (⋃ (i) (j), s i j)ᶜ = ⋂ (i) (j), (s i j)ᶜ := by simp_rw [compl_iUnion] @[simp] theorem compl_iInter (s : ι → Set β) : (⋂ i, s i)ᶜ = ⋃ i, (s i)ᶜ := compl_iInf /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ theorem compl_iInter₂ (s : ∀ i, κ i → Set α) : (⋂ (i) (j), s i j)ᶜ = ⋃ (i) (j), (s i j)ᶜ := by simp_rw [compl_iInter] -- classical -- complete_boolean_algebra theorem iUnion_eq_compl_iInter_compl (s : ι → Set β) : ⋃ i, s i = (⋂ i, (s i)ᶜ)ᶜ := by simp only [compl_iInter, compl_compl] -- classical -- complete_boolean_algebra theorem iInter_eq_compl_iUnion_compl (s : ι → Set β) : ⋂ i, s i = (⋃ i, (s i)ᶜ)ᶜ := by simp only [compl_iUnion, compl_compl] theorem inter_iUnion (s : Set β) (t : ι → Set β) : (s ∩ ⋃ i, t i) = ⋃ i, s ∩ t i := inf_iSup_eq _ _ theorem iUnion_inter (s : Set β) (t : ι → Set β) : (⋃ i, t i) ∩ s = ⋃ i, t i ∩ s := iSup_inf_eq _ _ theorem iUnion_union_distrib (s : ι → Set β) (t : ι → Set β) : ⋃ i, s i ∪ t i = (⋃ i, s i) ∪ ⋃ i, t i := iSup_sup_eq theorem iInter_inter_distrib (s : ι → Set β) (t : ι → Set β) : ⋂ i, s i ∩ t i = (⋂ i, s i) ∩ ⋂ i, t i := iInf_inf_eq theorem union_iUnion [Nonempty ι] (s : Set β) (t : ι → Set β) : (s ∪ ⋃ i, t i) = ⋃ i, s ∪ t i := sup_iSup theorem iUnion_union [Nonempty ι] (s : Set β) (t : ι → Set β) : (⋃ i, t i) ∪ s = ⋃ i, t i ∪ s := iSup_sup theorem inter_iInter [Nonempty ι] (s : Set β) (t : ι → Set β) : (s ∩ ⋂ i, t i) = ⋂ i, s ∩ t i := inf_iInf theorem iInter_inter [Nonempty ι] (s : Set β) (t : ι → Set β) : (⋂ i, t i) ∩ s = ⋂ i, t i ∩ s := iInf_inf -- classical theorem union_iInter (s : Set β) (t : ι → Set β) : (s ∪ ⋂ i, t i) = ⋂ i, s ∪ t i := sup_iInf_eq _ _ theorem iInter_union (s : ι → Set β) (t : Set β) : (⋂ i, s i) ∪ t = ⋂ i, s i ∪ t := iInf_sup_eq _ _ theorem iUnion_diff (s : Set β) (t : ι → Set β) : (⋃ i, t i) \ s = ⋃ i, t i \ s := iUnion_inter _ _ theorem diff_iUnion [Nonempty ι] (s : Set β) (t : ι → Set β) : (s \ ⋃ i, t i) = ⋂ i, s \ t i := by rw [diff_eq, compl_iUnion, inter_iInter]; rfl theorem diff_iInter (s : Set β) (t : ι → Set β) : (s \ ⋂ i, t i) = ⋃ i, s \ t i := by rw [diff_eq, compl_iInter, inter_iUnion]; rfl theorem iUnion_inter_subset {ι α} {s t : ι → Set α} : ⋃ i, s i ∩ t i ⊆ (⋃ i, s i) ∩ ⋃ i, t i := le_iSup_inf_iSup s t theorem iUnion_inter_of_monotone {ι α} [Preorder ι] [IsDirected ι (· ≤ ·)] {s t : ι → Set α} (hs : Monotone s) (ht : Monotone t) : ⋃ i, s i ∩ t i = (⋃ i, s i) ∩ ⋃ i, t i := iSup_inf_of_monotone hs ht theorem iUnion_inter_of_antitone {ι α} [Preorder ι] [IsDirected ι (swap (· ≤ ·))] {s t : ι → Set α} (hs : Antitone s) (ht : Antitone t) : ⋃ i, s i ∩ t i = (⋃ i, s i) ∩ ⋃ i, t i := iSup_inf_of_antitone hs ht theorem iInter_union_of_monotone {ι α} [Preorder ι] [IsDirected ι (swap (· ≤ ·))] {s t : ι → Set α} (hs : Monotone s) (ht : Monotone t) : ⋂ i, s i ∪ t i = (⋂ i, s i) ∪ ⋂ i, t i := iInf_sup_of_monotone hs ht theorem iInter_union_of_antitone {ι α} [Preorder ι] [IsDirected ι (· ≤ ·)] {s t : ι → Set α} (hs : Antitone s) (ht : Antitone t) : ⋂ i, s i ∪ t i = (⋂ i, s i) ∪ ⋂ i, t i := iInf_sup_of_antitone hs ht /-- An equality version of this lemma is `iUnion_iInter_of_monotone` in `Data.Set.Finite`. -/ theorem iUnion_iInter_subset {s : ι → ι' → Set α} : (⋃ j, ⋂ i, s i j) ⊆ ⋂ i, ⋃ j, s i j := iSup_iInf_le_iInf_iSup (flip s) theorem iUnion_option {ι} (s : Option ι → Set α) : ⋃ o, s o = s none ∪ ⋃ i, s (some i) := iSup_option s theorem iInter_option {ι} (s : Option ι → Set α) : ⋂ o, s o = s none ∩ ⋂ i, s (some i) := iInf_option s section variable (p : ι → Prop) [DecidablePred p] theorem iUnion_dite (f : ∀ i, p i → Set α) (g : ∀ i, ¬p i → Set α) : ⋃ i, (if h : p i then f i h else g i h) = (⋃ (i) (h : p i), f i h) ∪ ⋃ (i) (h : ¬p i), g i h := iSup_dite _ _ _ theorem iUnion_ite (f g : ι → Set α) : ⋃ i, (if p i then f i else g i) = (⋃ (i) (_ : p i), f i) ∪ ⋃ (i) (_ : ¬p i), g i := iUnion_dite _ _ _ theorem iInter_dite (f : ∀ i, p i → Set α) (g : ∀ i, ¬p i → Set α) : ⋂ i, (if h : p i then f i h else g i h) = (⋂ (i) (h : p i), f i h) ∩ ⋂ (i) (h : ¬p i), g i h := iInf_dite _ _ _ theorem iInter_ite (f g : ι → Set α) : ⋂ i, (if p i then f i else g i) = (⋂ (i) (_ : p i), f i) ∩ ⋂ (i) (_ : ¬p i), g i := iInter_dite _ _ _ end theorem image_projection_prod {ι : Type*} {α : ι → Type*} {v : ∀ i : ι, Set (α i)} (hv : (pi univ v).Nonempty) (i : ι) : ((fun x : ∀ i : ι, α i => x i) '' ⋂ k, (fun x : ∀ j : ι, α j => x k) ⁻¹' v k) = v i := by classical apply Subset.antisymm · simp [iInter_subset] · intro y y_in simp only [mem_image, mem_iInter, mem_preimage] rcases hv with ⟨z, hz⟩ refine ⟨Function.update z i y, ?_, update_same i y z⟩ rw [@forall_update_iff ι α _ z i y fun i t => t ∈ v i] exact ⟨y_in, fun j _ => by simpa using hz j⟩ /-! ### Unions and intersections indexed by `Prop` -/ theorem iInter_false {s : False → Set α} : iInter s = univ := iInf_false theorem iUnion_false {s : False → Set α} : iUnion s = ∅ := iSup_false @[simp] theorem iInter_true {s : True → Set α} : iInter s = s trivial := iInf_true @[simp] theorem iUnion_true {s : True → Set α} : iUnion s = s trivial := iSup_true @[simp] theorem iInter_exists {p : ι → Prop} {f : Exists p → Set α} : ⋂ x, f x = ⋂ (i) (h : p i), f ⟨i, h⟩ := iInf_exists @[simp] theorem iUnion_exists {p : ι → Prop} {f : Exists p → Set α} : ⋃ x, f x = ⋃ (i) (h : p i), f ⟨i, h⟩ := iSup_exists @[simp] theorem iUnion_empty : (⋃ _ : ι, ∅ : Set α) = ∅ := iSup_bot @[simp] theorem iInter_univ : (⋂ _ : ι, univ : Set α) = univ := iInf_top section variable {s : ι → Set α} @[simp] theorem iUnion_eq_empty : ⋃ i, s i = ∅ ↔ ∀ i, s i = ∅ := iSup_eq_bot @[simp] theorem iInter_eq_univ : ⋂ i, s i = univ ↔ ∀ i, s i = univ := iInf_eq_top @[simp] theorem nonempty_iUnion : (⋃ i, s i).Nonempty ↔ ∃ i, (s i).Nonempty := by simp [nonempty_iff_ne_empty] -- Porting note (#10618): removing `simp`. `simp` can prove it theorem nonempty_biUnion {t : Set α} {s : α → Set β} : (⋃ i ∈ t, s i).Nonempty ↔ ∃ i ∈ t, (s i).Nonempty := by simp theorem iUnion_nonempty_index (s : Set α) (t : s.Nonempty → Set β) : ⋃ h, t h = ⋃ x ∈ s, t ⟨x, ‹_›⟩ := iSup_exists end @[simp] theorem iInter_iInter_eq_left {b : β} {s : ∀ x : β, x = b → Set α} : ⋂ (x) (h : x = b), s x h = s b rfl := iInf_iInf_eq_left @[simp] theorem iInter_iInter_eq_right {b : β} {s : ∀ x : β, b = x → Set α} : ⋂ (x) (h : b = x), s x h = s b rfl := iInf_iInf_eq_right @[simp] theorem iUnion_iUnion_eq_left {b : β} {s : ∀ x : β, x = b → Set α} : ⋃ (x) (h : x = b), s x h = s b rfl := iSup_iSup_eq_left @[simp] theorem iUnion_iUnion_eq_right {b : β} {s : ∀ x : β, b = x → Set α} : ⋃ (x) (h : b = x), s x h = s b rfl := iSup_iSup_eq_right theorem iInter_or {p q : Prop} (s : p ∨ q → Set α) : ⋂ h, s h = (⋂ h : p, s (Or.inl h)) ∩ ⋂ h : q, s (Or.inr h) := iInf_or theorem iUnion_or {p q : Prop} (s : p ∨ q → Set α) : ⋃ h, s h = (⋃ i, s (Or.inl i)) ∪ ⋃ j, s (Or.inr j) := iSup_or /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (hp hq) -/ theorem iUnion_and {p q : Prop} (s : p ∧ q → Set α) : ⋃ h, s h = ⋃ (hp) (hq), s ⟨hp, hq⟩ := iSup_and /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (hp hq) -/ theorem iInter_and {p q : Prop} (s : p ∧ q → Set α) : ⋂ h, s h = ⋂ (hp) (hq), s ⟨hp, hq⟩ := iInf_and /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i i') -/ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i' i) -/ theorem iUnion_comm (s : ι → ι' → Set α) : ⋃ (i) (i'), s i i' = ⋃ (i') (i), s i i' := iSup_comm /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i i') -/ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i' i) -/ theorem iInter_comm (s : ι → ι' → Set α) : ⋂ (i) (i'), s i i' = ⋂ (i') (i), s i i' := iInf_comm theorem iUnion_sigma {γ : α → Type*} (s : Sigma γ → Set β) : ⋃ ia, s ia = ⋃ i, ⋃ a, s ⟨i, a⟩ := iSup_sigma theorem iUnion_sigma' {γ : α → Type*} (s : ∀ i, γ i → Set β) : ⋃ i, ⋃ a, s i a = ⋃ ia : Sigma γ, s ia.1 ia.2 := iSup_sigma' _ theorem iInter_sigma {γ : α → Type*} (s : Sigma γ → Set β) : ⋂ ia, s ia = ⋂ i, ⋂ a, s ⟨i, a⟩ := iInf_sigma theorem iInter_sigma' {γ : α → Type*} (s : ∀ i, γ i → Set β) : ⋂ i, ⋂ a, s i a = ⋂ ia : Sigma γ, s ia.1 ia.2 := iInf_sigma' _ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i₁ j₁ i₂ j₂) -/ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i₂ j₂ i₁ j₁) -/ theorem iUnion₂_comm (s : ∀ i₁, κ₁ i₁ → ∀ i₂, κ₂ i₂ → Set α) : ⋃ (i₁) (j₁) (i₂) (j₂), s i₁ j₁ i₂ j₂ = ⋃ (i₂) (j₂) (i₁) (j₁), s i₁ j₁ i₂ j₂ := iSup₂_comm _ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i₁ j₁ i₂ j₂) -/ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i₂ j₂ i₁ j₁) -/ theorem iInter₂_comm (s : ∀ i₁, κ₁ i₁ → ∀ i₂, κ₂ i₂ → Set α) : ⋂ (i₁) (j₁) (i₂) (j₂), s i₁ j₁ i₂ j₂ = ⋂ (i₂) (j₂) (i₁) (j₁), s i₁ j₁ i₂ j₂ := iInf₂_comm _ @[simp] theorem biUnion_and (p : ι → Prop) (q : ι → ι' → Prop) (s : ∀ x y, p x ∧ q x y → Set α) : ⋃ (x : ι) (y : ι') (h : p x ∧ q x y), s x y h = ⋃ (x : ι) (hx : p x) (y : ι') (hy : q x y), s x y ⟨hx, hy⟩ := by simp only [iUnion_and, @iUnion_comm _ ι'] @[simp] theorem biUnion_and' (p : ι' → Prop) (q : ι → ι' → Prop) (s : ∀ x y, p y ∧ q x y → Set α) : ⋃ (x : ι) (y : ι') (h : p y ∧ q x y), s x y h = ⋃ (y : ι') (hy : p y) (x : ι) (hx : q x y), s x y ⟨hy, hx⟩ := by simp only [iUnion_and, @iUnion_comm _ ι] @[simp] theorem biInter_and (p : ι → Prop) (q : ι → ι' → Prop) (s : ∀ x y, p x ∧ q x y → Set α) : ⋂ (x : ι) (y : ι') (h : p x ∧ q x y), s x y h = ⋂ (x : ι) (hx : p x) (y : ι') (hy : q x y), s x y ⟨hx, hy⟩ := by simp only [iInter_and, @iInter_comm _ ι'] @[simp] theorem biInter_and' (p : ι' → Prop) (q : ι → ι' → Prop) (s : ∀ x y, p y ∧ q x y → Set α) : ⋂ (x : ι) (y : ι') (h : p y ∧ q x y), s x y h = ⋂ (y : ι') (hy : p y) (x : ι) (hx : q x y), s x y ⟨hy, hx⟩ := by simp only [iInter_and, @iInter_comm _ ι] /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (x h) -/ @[simp] theorem iUnion_iUnion_eq_or_left {b : β} {p : β → Prop} {s : ∀ x : β, x = b ∨ p x → Set α} : ⋃ (x) (h), s x h = s b (Or.inl rfl) ∪ ⋃ (x) (h : p x), s x (Or.inr h) := by simp only [iUnion_or, iUnion_union_distrib, iUnion_iUnion_eq_left] /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (x h) -/ @[simp] theorem iInter_iInter_eq_or_left {b : β} {p : β → Prop} {s : ∀ x : β, x = b ∨ p x → Set α} : ⋂ (x) (h), s x h = s b (Or.inl rfl) ∩ ⋂ (x) (h : p x), s x (Or.inr h) := by simp only [iInter_or, iInter_inter_distrib, iInter_iInter_eq_left] /-! ### Bounded unions and intersections -/ /-- A specialization of `mem_iUnion₂`. -/ theorem mem_biUnion {s : Set α} {t : α → Set β} {x : α} {y : β} (xs : x ∈ s) (ytx : y ∈ t x) : y ∈ ⋃ x ∈ s, t x := mem_iUnion₂_of_mem xs ytx /-- A specialization of `mem_iInter₂`. -/ theorem mem_biInter {s : Set α} {t : α → Set β} {y : β} (h : ∀ x ∈ s, y ∈ t x) : y ∈ ⋂ x ∈ s, t x := mem_iInter₂_of_mem h /-- A specialization of `subset_iUnion₂`. -/ theorem subset_biUnion_of_mem {s : Set α} {u : α → Set β} {x : α} (xs : x ∈ s) : u x ⊆ ⋃ x ∈ s, u x := -- Porting note: Why is this not just `subset_iUnion₂ x xs`? @subset_iUnion₂ β α (· ∈ s) (fun i _ => u i) x xs /-- A specialization of `iInter₂_subset`. -/ theorem biInter_subset_of_mem {s : Set α} {t : α → Set β} {x : α} (xs : x ∈ s) : ⋂ x ∈ s, t x ⊆ t x := iInter₂_subset x xs theorem biUnion_subset_biUnion_left {s s' : Set α} {t : α → Set β} (h : s ⊆ s') : ⋃ x ∈ s, t x ⊆ ⋃ x ∈ s', t x := iUnion₂_subset fun _ hx => subset_biUnion_of_mem <| h hx theorem biInter_subset_biInter_left {s s' : Set α} {t : α → Set β} (h : s' ⊆ s) : ⋂ x ∈ s, t x ⊆ ⋂ x ∈ s', t x := subset_iInter₂ fun _ hx => biInter_subset_of_mem <| h hx theorem biUnion_mono {s s' : Set α} {t t' : α → Set β} (hs : s' ⊆ s) (h : ∀ x ∈ s, t x ⊆ t' x) : ⋃ x ∈ s', t x ⊆ ⋃ x ∈ s, t' x := (biUnion_subset_biUnion_left hs).trans <| iUnion₂_mono h theorem biInter_mono {s s' : Set α} {t t' : α → Set β} (hs : s ⊆ s') (h : ∀ x ∈ s, t x ⊆ t' x) : ⋂ x ∈ s', t x ⊆ ⋂ x ∈ s, t' x := (biInter_subset_biInter_left hs).trans <| iInter₂_mono h theorem biUnion_eq_iUnion (s : Set α) (t : ∀ x ∈ s, Set β) : ⋃ x ∈ s, t x ‹_› = ⋃ x : s, t x x.2 := iSup_subtype' theorem biInter_eq_iInter (s : Set α) (t : ∀ x ∈ s, Set β) : ⋂ x ∈ s, t x ‹_› = ⋂ x : s, t x x.2 := iInf_subtype' theorem iUnion_subtype (p : α → Prop) (s : { x // p x } → Set β) : ⋃ x : { x // p x }, s x = ⋃ (x) (hx : p x), s ⟨x, hx⟩ := iSup_subtype theorem iInter_subtype (p : α → Prop) (s : { x // p x } → Set β) : ⋂ x : { x // p x }, s x = ⋂ (x) (hx : p x), s ⟨x, hx⟩ := iInf_subtype theorem biInter_empty (u : α → Set β) : ⋂ x ∈ (∅ : Set α), u x = univ := iInf_emptyset theorem biInter_univ (u : α → Set β) : ⋂ x ∈ @univ α, u x = ⋂ x, u x := iInf_univ @[simp] theorem biUnion_self (s : Set α) : ⋃ x ∈ s, s = s := Subset.antisymm (iUnion₂_subset fun _ _ => Subset.refl s) fun _ hx => mem_biUnion hx hx @[simp] theorem iUnion_nonempty_self (s : Set α) : ⋃ _ : s.Nonempty, s = s := by rw [iUnion_nonempty_index, biUnion_self] theorem biInter_singleton (a : α) (s : α → Set β) : ⋂ x ∈ ({a} : Set α), s x = s a := iInf_singleton theorem biInter_union (s t : Set α) (u : α → Set β) : ⋂ x ∈ s ∪ t, u x = (⋂ x ∈ s, u x) ∩ ⋂ x ∈ t, u x := iInf_union theorem biInter_insert (a : α) (s : Set α) (t : α → Set β) : ⋂ x ∈ insert a s, t x = t a ∩ ⋂ x ∈ s, t x := by simp theorem biInter_pair (a b : α) (s : α → Set β) : ⋂ x ∈ ({a, b} : Set α), s x = s a ∩ s b := by rw [biInter_insert, biInter_singleton] theorem biInter_inter {ι α : Type*} {s : Set ι} (hs : s.Nonempty) (f : ι → Set α) (t : Set α) : ⋂ i ∈ s, f i ∩ t = (⋂ i ∈ s, f i) ∩ t := by haveI : Nonempty s := hs.to_subtype simp [biInter_eq_iInter, ← iInter_inter] theorem inter_biInter {ι α : Type*} {s : Set ι} (hs : s.Nonempty) (f : ι → Set α) (t : Set α) : ⋂ i ∈ s, t ∩ f i = t ∩ ⋂ i ∈ s, f i := by rw [inter_comm, ← biInter_inter hs] simp [inter_comm] theorem biUnion_empty (s : α → Set β) : ⋃ x ∈ (∅ : Set α), s x = ∅ := iSup_emptyset theorem biUnion_univ (s : α → Set β) : ⋃ x ∈ @univ α, s x = ⋃ x, s x := iSup_univ theorem biUnion_singleton (a : α) (s : α → Set β) : ⋃ x ∈ ({a} : Set α), s x = s a := iSup_singleton @[simp] theorem biUnion_of_singleton (s : Set α) : ⋃ x ∈ s, {x} = s := ext <| by simp theorem biUnion_union (s t : Set α) (u : α → Set β) : ⋃ x ∈ s ∪ t, u x = (⋃ x ∈ s, u x) ∪ ⋃ x ∈ t, u x := iSup_union @[simp] theorem iUnion_coe_set {α β : Type*} (s : Set α) (f : s → Set β) : ⋃ i, f i = ⋃ i ∈ s, f ⟨i, ‹i ∈ s›⟩ := iUnion_subtype _ _ @[simp] theorem iInter_coe_set {α β : Type*} (s : Set α) (f : s → Set β) : ⋂ i, f i = ⋂ i ∈ s, f ⟨i, ‹i ∈ s›⟩ := iInter_subtype _ _ theorem biUnion_insert (a : α) (s : Set α) (t : α → Set β) : ⋃ x ∈ insert a s, t x = t a ∪ ⋃ x ∈ s, t x := by simp theorem biUnion_pair (a b : α) (s : α → Set β) : ⋃ x ∈ ({a, b} : Set α), s x = s a ∪ s b := by simp /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ theorem inter_iUnion₂ (s : Set α) (t : ∀ i, κ i → Set α) : (s ∩ ⋃ (i) (j), t i j) = ⋃ (i) (j), s ∩ t i j := by simp only [inter_iUnion] /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ theorem iUnion₂_inter (s : ∀ i, κ i → Set α) (t : Set α) : (⋃ (i) (j), s i j) ∩ t = ⋃ (i) (j), s i j ∩ t := by simp_rw [iUnion_inter] /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ theorem union_iInter₂ (s : Set α) (t : ∀ i, κ i → Set α) : (s ∪ ⋂ (i) (j), t i j) = ⋂ (i) (j), s ∪ t i j := by simp_rw [union_iInter] /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ theorem iInter₂_union (s : ∀ i, κ i → Set α) (t : Set α) : (⋂ (i) (j), s i j) ∪ t = ⋂ (i) (j), s i j ∪ t := by simp_rw [iInter_union] theorem mem_sUnion_of_mem {x : α} {t : Set α} {S : Set (Set α)} (hx : x ∈ t) (ht : t ∈ S) : x ∈ ⋃₀S := ⟨t, ht, hx⟩ -- is this theorem really necessary? theorem not_mem_of_not_mem_sUnion {x : α} {t : Set α} {S : Set (Set α)} (hx : x ∉ ⋃₀S) (ht : t ∈ S) : x ∉ t := fun h => hx ⟨t, ht, h⟩ theorem sInter_subset_of_mem {S : Set (Set α)} {t : Set α} (tS : t ∈ S) : ⋂₀ S ⊆ t := sInf_le tS theorem subset_sUnion_of_mem {S : Set (Set α)} {t : Set α} (tS : t ∈ S) : t ⊆ ⋃₀S := le_sSup tS theorem subset_sUnion_of_subset {s : Set α} (t : Set (Set α)) (u : Set α) (h₁ : s ⊆ u) (h₂ : u ∈ t) : s ⊆ ⋃₀t := Subset.trans h₁ (subset_sUnion_of_mem h₂) theorem sUnion_subset {S : Set (Set α)} {t : Set α} (h : ∀ t' ∈ S, t' ⊆ t) : ⋃₀S ⊆ t := sSup_le h @[simp] theorem sUnion_subset_iff {s : Set (Set α)} {t : Set α} : ⋃₀s ⊆ t ↔ ∀ t' ∈ s, t' ⊆ t := sSup_le_iff /-- `sUnion` is monotone under taking a subset of each set. -/ lemma sUnion_mono_subsets {s : Set (Set α)} {f : Set α → Set α} (hf : ∀ t : Set α, t ⊆ f t) : ⋃₀ s ⊆ ⋃₀ (f '' s) := fun _ ⟨t, htx, hxt⟩ ↦ ⟨f t, mem_image_of_mem f htx, hf t hxt⟩ /-- `sUnion` is monotone under taking a superset of each set. -/ lemma sUnion_mono_supsets {s : Set (Set α)} {f : Set α → Set α} (hf : ∀ t : Set α, f t ⊆ t) : ⋃₀ (f '' s) ⊆ ⋃₀ s := -- If t ∈ f '' s is arbitrary; t = f u for some u : Set α. fun _ ⟨_, ⟨u, hus, hut⟩, hxt⟩ ↦ ⟨u, hus, (hut ▸ hf u) hxt⟩ theorem subset_sInter {S : Set (Set α)} {t : Set α} (h : ∀ t' ∈ S, t ⊆ t') : t ⊆ ⋂₀ S := le_sInf h @[simp] theorem subset_sInter_iff {S : Set (Set α)} {t : Set α} : t ⊆ ⋂₀ S ↔ ∀ t' ∈ S, t ⊆ t' := le_sInf_iff @[gcongr] theorem sUnion_subset_sUnion {S T : Set (Set α)} (h : S ⊆ T) : ⋃₀S ⊆ ⋃₀T := sUnion_subset fun _ hs => subset_sUnion_of_mem (h hs) @[gcongr] theorem sInter_subset_sInter {S T : Set (Set α)} (h : S ⊆ T) : ⋂₀ T ⊆ ⋂₀ S := subset_sInter fun _ hs => sInter_subset_of_mem (h hs) @[simp] theorem sUnion_empty : ⋃₀∅ = (∅ : Set α) := sSup_empty @[simp] theorem sInter_empty : ⋂₀ ∅ = (univ : Set α) := sInf_empty @[simp] theorem sUnion_singleton (s : Set α) : ⋃₀{s} = s := sSup_singleton @[simp] theorem sInter_singleton (s : Set α) : ⋂₀ {s} = s := sInf_singleton @[simp] theorem sUnion_eq_empty {S : Set (Set α)} : ⋃₀S = ∅ ↔ ∀ s ∈ S, s = ∅ := sSup_eq_bot @[simp] theorem sInter_eq_univ {S : Set (Set α)} : ⋂₀ S = univ ↔ ∀ s ∈ S, s = univ := sInf_eq_top theorem subset_powerset_iff {s : Set (Set α)} {t : Set α} : s ⊆ 𝒫 t ↔ ⋃₀ s ⊆ t := sUnion_subset_iff.symm /-- `⋃₀` and `𝒫` form a Galois connection. -/ theorem sUnion_powerset_gc : GaloisConnection (⋃₀ · : Set (Set α) → Set α) (𝒫 · : Set α → Set (Set α)) := gc_sSup_Iic /-- `⋃₀` and `𝒫` form a Galois insertion. -/ def sUnion_powerset_gi : GaloisInsertion (⋃₀ · : Set (Set α) → Set α) (𝒫 · : Set α → Set (Set α)) := gi_sSup_Iic /-- If all sets in a collection are either `∅` or `Set.univ`, then so is their union. -/ theorem sUnion_mem_empty_univ {S : Set (Set α)} (h : S ⊆ {∅, univ}) : ⋃₀ S ∈ ({∅, univ} : Set (Set α)) := by simp only [mem_insert_iff, mem_singleton_iff, or_iff_not_imp_left, sUnion_eq_empty, not_forall] rintro ⟨s, hs, hne⟩ obtain rfl : s = univ := (h hs).resolve_left hne exact univ_subset_iff.1 <| subset_sUnion_of_mem hs @[simp] theorem nonempty_sUnion {S : Set (Set α)} : (⋃₀S).Nonempty ↔ ∃ s ∈ S, Set.Nonempty s := by simp [nonempty_iff_ne_empty] theorem Nonempty.of_sUnion {s : Set (Set α)} (h : (⋃₀s).Nonempty) : s.Nonempty := let ⟨s, hs, _⟩ := nonempty_sUnion.1 h ⟨s, hs⟩ theorem Nonempty.of_sUnion_eq_univ [Nonempty α] {s : Set (Set α)} (h : ⋃₀s = univ) : s.Nonempty := Nonempty.of_sUnion <| h.symm ▸ univ_nonempty theorem sUnion_union (S T : Set (Set α)) : ⋃₀(S ∪ T) = ⋃₀S ∪ ⋃₀T := sSup_union theorem sInter_union (S T : Set (Set α)) : ⋂₀ (S ∪ T) = ⋂₀ S ∩ ⋂₀ T := sInf_union @[simp] theorem sUnion_insert (s : Set α) (T : Set (Set α)) : ⋃₀insert s T = s ∪ ⋃₀T := sSup_insert @[simp] theorem sInter_insert (s : Set α) (T : Set (Set α)) : ⋂₀ insert s T = s ∩ ⋂₀ T := sInf_insert @[simp] theorem sUnion_diff_singleton_empty (s : Set (Set α)) : ⋃₀(s \ {∅}) = ⋃₀s := sSup_diff_singleton_bot s @[simp] theorem sInter_diff_singleton_univ (s : Set (Set α)) : ⋂₀ (s \ {univ}) = ⋂₀ s := sInf_diff_singleton_top s theorem sUnion_pair (s t : Set α) : ⋃₀{s, t} = s ∪ t := sSup_pair theorem sInter_pair (s t : Set α) : ⋂₀ {s, t} = s ∩ t := sInf_pair @[simp] theorem sUnion_image (f : α → Set β) (s : Set α) : ⋃₀(f '' s) = ⋃ x ∈ s, f x := sSup_image @[simp] theorem sInter_image (f : α → Set β) (s : Set α) : ⋂₀ (f '' s) = ⋂ x ∈ s, f x := sInf_image @[simp] theorem sUnion_range (f : ι → Set β) : ⋃₀range f = ⋃ x, f x := rfl @[simp] theorem sInter_range (f : ι → Set β) : ⋂₀ range f = ⋂ x, f x := rfl theorem iUnion_eq_univ_iff {f : ι → Set α} : ⋃ i, f i = univ ↔ ∀ x, ∃ i, x ∈ f i := by simp only [eq_univ_iff_forall, mem_iUnion] /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ theorem iUnion₂_eq_univ_iff {s : ∀ i, κ i → Set α} : ⋃ (i) (j), s i j = univ ↔ ∀ a, ∃ i j, a ∈ s i j := by simp only [iUnion_eq_univ_iff, mem_iUnion] theorem sUnion_eq_univ_iff {c : Set (Set α)} : ⋃₀c = univ ↔ ∀ a, ∃ b ∈ c, a ∈ b := by simp only [eq_univ_iff_forall, mem_sUnion] -- classical theorem iInter_eq_empty_iff {f : ι → Set α} : ⋂ i, f i = ∅ ↔ ∀ x, ∃ i, x ∉ f i := by simp [Set.eq_empty_iff_forall_not_mem] /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ -- classical theorem iInter₂_eq_empty_iff {s : ∀ i, κ i → Set α} : ⋂ (i) (j), s i j = ∅ ↔ ∀ a, ∃ i j, a ∉ s i j := by simp only [eq_empty_iff_forall_not_mem, mem_iInter, not_forall] -- classical theorem sInter_eq_empty_iff {c : Set (Set α)} : ⋂₀ c = ∅ ↔ ∀ a, ∃ b ∈ c, a ∉ b := by simp [Set.eq_empty_iff_forall_not_mem] -- classical @[simp] theorem nonempty_iInter {f : ι → Set α} : (⋂ i, f i).Nonempty ↔ ∃ x, ∀ i, x ∈ f i := by simp [nonempty_iff_ne_empty, iInter_eq_empty_iff] /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ -- classical -- Porting note (#10618): removing `simp`. `simp` can prove it theorem nonempty_iInter₂ {s : ∀ i, κ i → Set α} : (⋂ (i) (j), s i j).Nonempty ↔ ∃ a, ∀ i j, a ∈ s i j := by simp -- classical @[simp] theorem nonempty_sInter {c : Set (Set α)} : (⋂₀ c).Nonempty ↔ ∃ a, ∀ b ∈ c, a ∈ b := by simp [nonempty_iff_ne_empty, sInter_eq_empty_iff] -- classical theorem compl_sUnion (S : Set (Set α)) : (⋃₀S)ᶜ = ⋂₀ (compl '' S) := ext fun x => by simp -- classical theorem sUnion_eq_compl_sInter_compl (S : Set (Set α)) : ⋃₀S = (⋂₀ (compl '' S))ᶜ := by rw [← compl_compl (⋃₀S), compl_sUnion] -- classical theorem compl_sInter (S : Set (Set α)) : (⋂₀ S)ᶜ = ⋃₀(compl '' S) := by rw [sUnion_eq_compl_sInter_compl, compl_compl_image] -- classical theorem sInter_eq_compl_sUnion_compl (S : Set (Set α)) : ⋂₀ S = (⋃₀(compl '' S))ᶜ := by rw [← compl_compl (⋂₀ S), compl_sInter] theorem inter_empty_of_inter_sUnion_empty {s t : Set α} {S : Set (Set α)} (hs : t ∈ S) (h : s ∩ ⋃₀S = ∅) : s ∩ t = ∅ := eq_empty_of_subset_empty <| by rw [← h]; exact inter_subset_inter_right _ (subset_sUnion_of_mem hs) theorem range_sigma_eq_iUnion_range {γ : α → Type*} (f : Sigma γ → β) : range f = ⋃ a, range fun b => f ⟨a, b⟩ := Set.ext <| by simp theorem iUnion_eq_range_sigma (s : α → Set β) : ⋃ i, s i = range fun a : Σi, s i => a.2 := by simp [Set.ext_iff] theorem iUnion_eq_range_psigma (s : ι → Set β) : ⋃ i, s i = range fun a : Σ'i, s i => a.2 := by simp [Set.ext_iff] theorem iUnion_image_preimage_sigma_mk_eq_self {ι : Type*} {σ : ι → Type*} (s : Set (Sigma σ)) : ⋃ i, Sigma.mk i '' (Sigma.mk i ⁻¹' s) = s := by ext x simp only [mem_iUnion, mem_image, mem_preimage] constructor · rintro ⟨i, a, h, rfl⟩ exact h · intro h cases' x with i a exact ⟨i, a, h, rfl⟩ theorem Sigma.univ (X : α → Type*) : (Set.univ : Set (Σa, X a)) = ⋃ a, range (Sigma.mk a) := Set.ext fun x => iff_of_true trivial ⟨range (Sigma.mk x.1), Set.mem_range_self _, x.2, Sigma.eta x⟩ alias sUnion_mono := sUnion_subset_sUnion alias sInter_mono := sInter_subset_sInter theorem iUnion_subset_iUnion_const {s : Set α} (h : ι → ι₂) : ⋃ _ : ι, s ⊆ ⋃ _ : ι₂, s := iSup_const_mono (α := Set α) h @[simp] theorem iUnion_singleton_eq_range {α β : Type*} (f : α → β) : ⋃ x : α, {f x} = range f := by ext x simp [@eq_comm _ x] theorem iUnion_of_singleton (α : Type*) : (⋃ x, {x} : Set α) = univ := by simp [Set.ext_iff] theorem iUnion_of_singleton_coe (s : Set α) : ⋃ i : s, ({(i : α)} : Set α) = s := by simp theorem sUnion_eq_biUnion {s : Set (Set α)} : ⋃₀s = ⋃ (i : Set α) (_ : i ∈ s), i := by rw [← sUnion_image, image_id'] theorem sInter_eq_biInter {s : Set (Set α)} : ⋂₀ s = ⋂ (i : Set α) (_ : i ∈ s), i := by rw [← sInter_image, image_id'] theorem sUnion_eq_iUnion {s : Set (Set α)} : ⋃₀s = ⋃ i : s, i := by simp only [← sUnion_range, Subtype.range_coe] theorem sInter_eq_iInter {s : Set (Set α)} : ⋂₀ s = ⋂ i : s, i := by simp only [← sInter_range, Subtype.range_coe] @[simp] theorem iUnion_of_empty [IsEmpty ι] (s : ι → Set α) : ⋃ i, s i = ∅ := iSup_of_empty _ @[simp] theorem iInter_of_empty [IsEmpty ι] (s : ι → Set α) : ⋂ i, s i = univ := iInf_of_empty _ theorem union_eq_iUnion {s₁ s₂ : Set α} : s₁ ∪ s₂ = ⋃ b : Bool, cond b s₁ s₂ := sup_eq_iSup s₁ s₂ theorem inter_eq_iInter {s₁ s₂ : Set α} : s₁ ∩ s₂ = ⋂ b : Bool, cond b s₁ s₂ := inf_eq_iInf s₁ s₂ theorem sInter_union_sInter {S T : Set (Set α)} : ⋂₀ S ∪ ⋂₀ T = ⋂ p ∈ S ×ˢ T, (p : Set α × Set α).1 ∪ p.2 := sInf_sup_sInf theorem sUnion_inter_sUnion {s t : Set (Set α)} : ⋃₀s ∩ ⋃₀t = ⋃ p ∈ s ×ˢ t, (p : Set α × Set α).1 ∩ p.2 := sSup_inf_sSup theorem biUnion_iUnion (s : ι → Set α) (t : α → Set β) : ⋃ x ∈ ⋃ i, s i, t x = ⋃ (i) (x ∈ s i), t x := by simp [@iUnion_comm _ ι] theorem biInter_iUnion (s : ι → Set α) (t : α → Set β) : ⋂ x ∈ ⋃ i, s i, t x = ⋂ (i) (x ∈ s i), t x := by simp [@iInter_comm _ ι] theorem sUnion_iUnion (s : ι → Set (Set α)) : ⋃₀⋃ i, s i = ⋃ i, ⋃₀s i := by simp only [sUnion_eq_biUnion, biUnion_iUnion] theorem sInter_iUnion (s : ι → Set (Set α)) : ⋂₀ ⋃ i, s i = ⋂ i, ⋂₀ s i := by simp only [sInter_eq_biInter, biInter_iUnion] theorem iUnion_range_eq_sUnion {α β : Type*} (C : Set (Set α)) {f : ∀ s : C, β → (s : Type _)} (hf : ∀ s : C, Surjective (f s)) : ⋃ y : β, range (fun s : C => (f s y).val) = ⋃₀C := by ext x; constructor · rintro ⟨s, ⟨y, rfl⟩, ⟨s, hs⟩, rfl⟩ refine ⟨_, hs, ?_⟩ exact (f ⟨s, hs⟩ y).2 · rintro ⟨s, hs, hx⟩ cases' hf ⟨s, hs⟩ ⟨x, hx⟩ with y hy refine ⟨_, ⟨y, rfl⟩, ⟨s, hs⟩, ?_⟩ exact congr_arg Subtype.val hy theorem iUnion_range_eq_iUnion (C : ι → Set α) {f : ∀ x : ι, β → C x} (hf : ∀ x : ι, Surjective (f x)) : ⋃ y : β, range (fun x : ι => (f x y).val) = ⋃ x, C x := by ext x; rw [mem_iUnion, mem_iUnion]; constructor · rintro ⟨y, i, rfl⟩ exact ⟨i, (f i y).2⟩ · rintro ⟨i, hx⟩ cases' hf i ⟨x, hx⟩ with y hy exact ⟨y, i, congr_arg Subtype.val hy⟩ theorem union_distrib_iInter_left (s : ι → Set α) (t : Set α) : (t ∪ ⋂ i, s i) = ⋂ i, t ∪ s i := sup_iInf_eq _ _ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ theorem union_distrib_iInter₂_left (s : Set α) (t : ∀ i, κ i → Set α) : (s ∪ ⋂ (i) (j), t i j) = ⋂ (i) (j), s ∪ t i j := by simp_rw [union_distrib_iInter_left] theorem union_distrib_iInter_right (s : ι → Set α) (t : Set α) : (⋂ i, s i) ∪ t = ⋂ i, s i ∪ t := iInf_sup_eq _ _ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ theorem union_distrib_iInter₂_right (s : ∀ i, κ i → Set α) (t : Set α) : (⋂ (i) (j), s i j) ∪ t = ⋂ (i) (j), s i j ∪ t := by simp_rw [union_distrib_iInter_right] section Function /-! ### Lemmas about `Set.MapsTo` Porting note: some lemmas in this section were upgraded from implications to `iff`s. -/ @[simp] theorem mapsTo_sUnion {S : Set (Set α)} {t : Set β} {f : α → β} : MapsTo f (⋃₀ S) t ↔ ∀ s ∈ S, MapsTo f s t := sUnion_subset_iff @[simp] theorem mapsTo_iUnion {s : ι → Set α} {t : Set β} {f : α → β} : MapsTo f (⋃ i, s i) t ↔ ∀ i, MapsTo f (s i) t := iUnion_subset_iff /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ theorem mapsTo_iUnion₂ {s : ∀ i, κ i → Set α} {t : Set β} {f : α → β} : MapsTo f (⋃ (i) (j), s i j) t ↔ ∀ i j, MapsTo f (s i j) t := iUnion₂_subset_iff theorem mapsTo_iUnion_iUnion {s : ι → Set α} {t : ι → Set β} {f : α → β} (H : ∀ i, MapsTo f (s i) (t i)) : MapsTo f (⋃ i, s i) (⋃ i, t i) := mapsTo_iUnion.2 fun i ↦ (H i).mono_right (subset_iUnion t i) /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ theorem mapsTo_iUnion₂_iUnion₂ {s : ∀ i, κ i → Set α} {t : ∀ i, κ i → Set β} {f : α → β} (H : ∀ i j, MapsTo f (s i j) (t i j)) : MapsTo f (⋃ (i) (j), s i j) (⋃ (i) (j), t i j) := mapsTo_iUnion_iUnion fun i => mapsTo_iUnion_iUnion (H i) @[simp] theorem mapsTo_sInter {s : Set α} {T : Set (Set β)} {f : α → β} : MapsTo f s (⋂₀ T) ↔ ∀ t ∈ T, MapsTo f s t := forall₂_swap @[simp] theorem mapsTo_iInter {s : Set α} {t : ι → Set β} {f : α → β} : MapsTo f s (⋂ i, t i) ↔ ∀ i, MapsTo f s (t i) := mapsTo_sInter.trans forall_mem_range /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ theorem mapsTo_iInter₂ {s : Set α} {t : ∀ i, κ i → Set β} {f : α → β} : MapsTo f s (⋂ (i) (j), t i j) ↔ ∀ i j, MapsTo f s (t i j) := by simp only [mapsTo_iInter] theorem mapsTo_iInter_iInter {s : ι → Set α} {t : ι → Set β} {f : α → β} (H : ∀ i, MapsTo f (s i) (t i)) : MapsTo f (⋂ i, s i) (⋂ i, t i) := mapsTo_iInter.2 fun i => (H i).mono_left (iInter_subset s i) /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ theorem mapsTo_iInter₂_iInter₂ {s : ∀ i, κ i → Set α} {t : ∀ i, κ i → Set β} {f : α → β} (H : ∀ i j, MapsTo f (s i j) (t i j)) : MapsTo f (⋂ (i) (j), s i j) (⋂ (i) (j), t i j) := mapsTo_iInter_iInter fun i => mapsTo_iInter_iInter (H i) theorem image_iInter_subset (s : ι → Set α) (f : α → β) : (f '' ⋂ i, s i) ⊆ ⋂ i, f '' s i := (mapsTo_iInter_iInter fun i => mapsTo_image f (s i)).image_subset /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ theorem image_iInter₂_subset (s : ∀ i, κ i → Set α) (f : α → β) : (f '' ⋂ (i) (j), s i j) ⊆ ⋂ (i) (j), f '' s i j := (mapsTo_iInter₂_iInter₂ fun i hi => mapsTo_image f (s i hi)).image_subset theorem image_sInter_subset (S : Set (Set α)) (f : α → β) : f '' ⋂₀ S ⊆ ⋂ s ∈ S, f '' s := by rw [sInter_eq_biInter] apply image_iInter₂_subset /-! ### `restrictPreimage` -/ section open Function variable {f : α → β} {U : ι → Set β} (hU : iUnion U = univ) theorem injective_iff_injective_of_iUnion_eq_univ : Injective f ↔ ∀ i, Injective ((U i).restrictPreimage f) := by refine ⟨fun H i => (U i).restrictPreimage_injective H, fun H x y e => ?_⟩ obtain ⟨i, hi⟩ := Set.mem_iUnion.mp (show f x ∈ Set.iUnion U by rw [hU]; trivial) injection @H i ⟨x, hi⟩ ⟨y, show f y ∈ U i from e ▸ hi⟩ (Subtype.ext e) theorem surjective_iff_surjective_of_iUnion_eq_univ : Surjective f ↔ ∀ i, Surjective ((U i).restrictPreimage f) := by refine ⟨fun H i => (U i).restrictPreimage_surjective H, fun H x => ?_⟩ obtain ⟨i, hi⟩ := Set.mem_iUnion.mp (show x ∈ Set.iUnion U by rw [hU]; trivial) exact ⟨_, congr_arg Subtype.val (H i ⟨x, hi⟩).choose_spec⟩ theorem bijective_iff_bijective_of_iUnion_eq_univ : Bijective f ↔ ∀ i, Bijective ((U i).restrictPreimage f) := by rw [Bijective, injective_iff_injective_of_iUnion_eq_univ hU, surjective_iff_surjective_of_iUnion_eq_univ hU] simp [Bijective, forall_and] end /-! ### `InjOn` -/ theorem InjOn.image_iInter_eq [Nonempty ι] {s : ι → Set α} {f : α → β} (h : InjOn f (⋃ i, s i)) : (f '' ⋂ i, s i) = ⋂ i, f '' s i := by inhabit ι refine Subset.antisymm (image_iInter_subset s f) fun y hy => ?_ simp only [mem_iInter, mem_image] at hy choose x hx hy using hy refine ⟨x default, mem_iInter.2 fun i => ?_, hy _⟩ suffices x default = x i by rw [this] apply hx replace hx : ∀ i, x i ∈ ⋃ j, s j := fun i => (subset_iUnion _ _) (hx i) apply h (hx _) (hx _) simp only [hy] /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i hi) -/ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i hi) -/ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i hi) -/ theorem InjOn.image_biInter_eq {p : ι → Prop} {s : ∀ i, p i → Set α} (hp : ∃ i, p i) {f : α → β} (h : InjOn f (⋃ (i) (hi), s i hi)) : (f '' ⋂ (i) (hi), s i hi) = ⋂ (i) (hi), f '' s i hi := by simp only [iInter, iInf_subtype'] haveI : Nonempty { i // p i } := nonempty_subtype.2 hp apply InjOn.image_iInter_eq simpa only [iUnion, iSup_subtype'] using h theorem image_iInter {f : α → β} (hf : Bijective f) (s : ι → Set α) : (f '' ⋂ i, s i) = ⋂ i, f '' s i := by cases isEmpty_or_nonempty ι · simp_rw [iInter_of_empty, image_univ_of_surjective hf.surjective] · exact hf.injective.injOn.image_iInter_eq /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ theorem image_iInter₂ {f : α → β} (hf : Bijective f) (s : ∀ i, κ i → Set α) : (f '' ⋂ (i) (j), s i j) = ⋂ (i) (j), f '' s i j := by simp_rw [image_iInter hf] theorem inj_on_iUnion_of_directed {s : ι → Set α} (hs : Directed (· ⊆ ·) s) {f : α → β} (hf : ∀ i, InjOn f (s i)) : InjOn f (⋃ i, s i) := by intro x hx y hy hxy rcases mem_iUnion.1 hx with ⟨i, hx⟩ rcases mem_iUnion.1 hy with ⟨j, hy⟩ rcases hs i j with ⟨k, hi, hj⟩ exact hf k (hi hx) (hj hy) hxy /-! ### `SurjOn` -/ theorem surjOn_sUnion {s : Set α} {T : Set (Set β)} {f : α → β} (H : ∀ t ∈ T, SurjOn f s t) : SurjOn f s (⋃₀T) := fun _ ⟨t, ht, hx⟩ => H t ht hx theorem surjOn_iUnion {s : Set α} {t : ι → Set β} {f : α → β} (H : ∀ i, SurjOn f s (t i)) : SurjOn f s (⋃ i, t i) := surjOn_sUnion <| forall_mem_range.2 H theorem surjOn_iUnion_iUnion {s : ι → Set α} {t : ι → Set β} {f : α → β} (H : ∀ i, SurjOn f (s i) (t i)) : SurjOn f (⋃ i, s i) (⋃ i, t i) := surjOn_iUnion fun i => (H i).mono (subset_iUnion _ _) (Subset.refl _) /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ theorem surjOn_iUnion₂ {s : Set α} {t : ∀ i, κ i → Set β} {f : α → β} (H : ∀ i j, SurjOn f s (t i j)) : SurjOn f s (⋃ (i) (j), t i j) := surjOn_iUnion fun i => surjOn_iUnion (H i) /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ theorem surjOn_iUnion₂_iUnion₂ {s : ∀ i, κ i → Set α} {t : ∀ i, κ i → Set β} {f : α → β} (H : ∀ i j, SurjOn f (s i j) (t i j)) : SurjOn f (⋃ (i) (j), s i j) (⋃ (i) (j), t i j) := surjOn_iUnion_iUnion fun i => surjOn_iUnion_iUnion (H i) theorem surjOn_iInter [Nonempty ι] {s : ι → Set α} {t : Set β} {f : α → β} (H : ∀ i, SurjOn f (s i) t) (Hinj : InjOn f (⋃ i, s i)) : SurjOn f (⋂ i, s i) t := by intro y hy rw [Hinj.image_iInter_eq, mem_iInter] exact fun i => H i hy theorem surjOn_iInter_iInter [Nonempty ι] {s : ι → Set α} {t : ι → Set β} {f : α → β} (H : ∀ i, SurjOn f (s i) (t i)) (Hinj : InjOn f (⋃ i, s i)) : SurjOn f (⋂ i, s i) (⋂ i, t i) := surjOn_iInter (fun i => (H i).mono (Subset.refl _) (iInter_subset _ _)) Hinj /-! ### `BijOn` -/ theorem bijOn_iUnion {s : ι → Set α} {t : ι → Set β} {f : α → β} (H : ∀ i, BijOn f (s i) (t i)) (Hinj : InjOn f (⋃ i, s i)) : BijOn f (⋃ i, s i) (⋃ i, t i) := ⟨mapsTo_iUnion_iUnion fun i => (H i).mapsTo, Hinj, surjOn_iUnion_iUnion fun i => (H i).surjOn⟩ theorem bijOn_iInter [hi : Nonempty ι] {s : ι → Set α} {t : ι → Set β} {f : α → β} (H : ∀ i, BijOn f (s i) (t i)) (Hinj : InjOn f (⋃ i, s i)) : BijOn f (⋂ i, s i) (⋂ i, t i) := ⟨mapsTo_iInter_iInter fun i => (H i).mapsTo, hi.elim fun i => (H i).injOn.mono (iInter_subset _ _), surjOn_iInter_iInter (fun i => (H i).surjOn) Hinj⟩ theorem bijOn_iUnion_of_directed {s : ι → Set α} (hs : Directed (· ⊆ ·) s) {t : ι → Set β} {f : α → β} (H : ∀ i, BijOn f (s i) (t i)) : BijOn f (⋃ i, s i) (⋃ i, t i) := bijOn_iUnion H <| inj_on_iUnion_of_directed hs fun i => (H i).injOn theorem bijOn_iInter_of_directed [Nonempty ι] {s : ι → Set α} (hs : Directed (· ⊆ ·) s) {t : ι → Set β} {f : α → β} (H : ∀ i, BijOn f (s i) (t i)) : BijOn f (⋂ i, s i) (⋂ i, t i) := bijOn_iInter H <| inj_on_iUnion_of_directed hs fun i => (H i).injOn end Function /-! ### `image`, `preimage` -/ section Image theorem image_iUnion {f : α → β} {s : ι → Set α} : (f '' ⋃ i, s i) = ⋃ i, f '' s i := by ext1 x simp only [mem_image, mem_iUnion, ← exists_and_right, ← exists_and_left] -- Porting note: `exists_swap` causes a `simp` loop in Lean4 so we use `rw` instead. rw [exists_swap] /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ theorem image_iUnion₂ (f : α → β) (s : ∀ i, κ i → Set α) : (f '' ⋃ (i) (j), s i j) = ⋃ (i) (j), f '' s i j := by simp_rw [image_iUnion] theorem univ_subtype {p : α → Prop} : (univ : Set (Subtype p)) = ⋃ (x) (h : p x), {⟨x, h⟩} := Set.ext fun ⟨x, h⟩ => by simp [h] theorem range_eq_iUnion {ι} (f : ι → α) : range f = ⋃ i, {f i} := Set.ext fun a => by simp [@eq_comm α a] theorem image_eq_iUnion (f : α → β) (s : Set α) : f '' s = ⋃ i ∈ s, {f i} := Set.ext fun b => by simp [@eq_comm β b] theorem biUnion_range {f : ι → α} {g : α → Set β} : ⋃ x ∈ range f, g x = ⋃ y, g (f y) := iSup_range /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (x y) -/ @[simp] theorem iUnion_iUnion_eq' {f : ι → α} {g : α → Set β} : ⋃ (x) (y) (_ : f y = x), g x = ⋃ y, g (f y) := by simpa using biUnion_range theorem biInter_range {f : ι → α} {g : α → Set β} : ⋂ x ∈ range f, g x = ⋂ y, g (f y) := iInf_range /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (x y) -/ @[simp] theorem iInter_iInter_eq' {f : ι → α} {g : α → Set β} : ⋂ (x) (y) (_ : f y = x), g x = ⋂ y, g (f y) := by simpa using biInter_range variable {s : Set γ} {f : γ → α} {g : α → Set β} theorem biUnion_image : ⋃ x ∈ f '' s, g x = ⋃ y ∈ s, g (f y) := iSup_image theorem biInter_image : ⋂ x ∈ f '' s, g x = ⋂ y ∈ s, g (f y) := iInf_image end Image section Preimage theorem monotone_preimage {f : α → β} : Monotone (preimage f) := fun _ _ h => preimage_mono h @[simp] theorem preimage_iUnion {f : α → β} {s : ι → Set β} : (f ⁻¹' ⋃ i, s i) = ⋃ i, f ⁻¹' s i := Set.ext <| by simp [preimage] /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ theorem preimage_iUnion₂ {f : α → β} {s : ∀ i, κ i → Set β} : (f ⁻¹' ⋃ (i) (j), s i j) = ⋃ (i) (j), f ⁻¹' s i j := by simp_rw [preimage_iUnion] theorem image_sUnion {f : α → β} {s : Set (Set α)} : (f '' ⋃₀ s) = ⋃₀ (image f '' s) := by ext b simp only [mem_image, mem_sUnion, exists_prop, sUnion_image, mem_iUnion] constructor · rintro ⟨a, ⟨t, ht₁, ht₂⟩, rfl⟩ exact ⟨t, ht₁, a, ht₂, rfl⟩ · rintro ⟨t, ht₁, a, ht₂, rfl⟩ exact ⟨a, ⟨t, ht₁, ht₂⟩, rfl⟩ @[simp] theorem preimage_sUnion {f : α → β} {s : Set (Set β)} : f ⁻¹' ⋃₀s = ⋃ t ∈ s, f ⁻¹' t := by rw [sUnion_eq_biUnion, preimage_iUnion₂] theorem preimage_iInter {f : α → β} {s : ι → Set β} : (f ⁻¹' ⋂ i, s i) = ⋂ i, f ⁻¹' s i := by ext; simp /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ theorem preimage_iInter₂ {f : α → β} {s : ∀ i, κ i → Set β} : (f ⁻¹' ⋂ (i) (j), s i j) = ⋂ (i) (j), f ⁻¹' s i j := by simp_rw [preimage_iInter] @[simp] theorem preimage_sInter {f : α → β} {s : Set (Set β)} : f ⁻¹' ⋂₀ s = ⋂ t ∈ s, f ⁻¹' t := by rw [sInter_eq_biInter, preimage_iInter₂] @[simp] theorem biUnion_preimage_singleton (f : α → β) (s : Set β) : ⋃ y ∈ s, f ⁻¹' {y} = f ⁻¹' s := by rw [← preimage_iUnion₂, biUnion_of_singleton] theorem biUnion_range_preimage_singleton (f : α → β) : ⋃ y ∈ range f, f ⁻¹' {y} = univ := by rw [biUnion_preimage_singleton, preimage_range] end Preimage section Prod theorem prod_iUnion {s : Set α} {t : ι → Set β} : (s ×ˢ ⋃ i, t i) = ⋃ i, s ×ˢ t i := by ext simp /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ theorem prod_iUnion₂ {s : Set α} {t : ∀ i, κ i → Set β} : (s ×ˢ ⋃ (i) (j), t i j) = ⋃ (i) (j), s ×ˢ t i j := by simp_rw [prod_iUnion] theorem prod_sUnion {s : Set α} {C : Set (Set β)} : s ×ˢ ⋃₀C = ⋃₀((fun t => s ×ˢ t) '' C) := by simp_rw [sUnion_eq_biUnion, biUnion_image, prod_iUnion₂] theorem iUnion_prod_const {s : ι → Set α} {t : Set β} : (⋃ i, s i) ×ˢ t = ⋃ i, s i ×ˢ t := by ext simp /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ theorem iUnion₂_prod_const {s : ∀ i, κ i → Set α} {t : Set β} : (⋃ (i) (j), s i j) ×ˢ t = ⋃ (i) (j), s i j ×ˢ t := by simp_rw [iUnion_prod_const] theorem sUnion_prod_const {C : Set (Set α)} {t : Set β} : ⋃₀C ×ˢ t = ⋃₀((fun s : Set α => s ×ˢ t) '' C) := by simp only [sUnion_eq_biUnion, iUnion₂_prod_const, biUnion_image] theorem iUnion_prod {ι ι' α β} (s : ι → Set α) (t : ι' → Set β) : ⋃ x : ι × ι', s x.1 ×ˢ t x.2 = (⋃ i : ι, s i) ×ˢ ⋃ i : ι', t i := by ext simp /-- Analogue of `iSup_prod` for sets. -/ lemma iUnion_prod' (f : β × γ → Set α) : ⋃ x : β × γ, f x = ⋃ (i : β) (j : γ), f (i, j) := iSup_prod theorem iUnion_prod_of_monotone [SemilatticeSup α] {s : α → Set β} {t : α → Set γ} (hs : Monotone s) (ht : Monotone t) : ⋃ x, s x ×ˢ t x = (⋃ x, s x) ×ˢ ⋃ x, t x := by ext ⟨z, w⟩; simp only [mem_prod, mem_iUnion, exists_imp, and_imp, iff_def]; constructor · intro x hz hw exact ⟨⟨x, hz⟩, x, hw⟩ · intro x hz x' hw exact ⟨x ⊔ x', hs le_sup_left hz, ht le_sup_right hw⟩ theorem sInter_prod_sInter_subset (S : Set (Set α)) (T : Set (Set β)) : ⋂₀ S ×ˢ ⋂₀ T ⊆ ⋂ r ∈ S ×ˢ T, r.1 ×ˢ r.2 := subset_iInter₂ fun x hx _ hy => ⟨hy.1 x.1 hx.1, hy.2 x.2 hx.2⟩ theorem sInter_prod_sInter {S : Set (Set α)} {T : Set (Set β)} (hS : S.Nonempty) (hT : T.Nonempty) : ⋂₀ S ×ˢ ⋂₀ T = ⋂ r ∈ S ×ˢ T, r.1 ×ˢ r.2 := by obtain ⟨s₁, h₁⟩ := hS obtain ⟨s₂, h₂⟩ := hT refine Set.Subset.antisymm (sInter_prod_sInter_subset S T) fun x hx => ?_ rw [mem_iInter₂] at hx exact ⟨fun s₀ h₀ => (hx (s₀, s₂) ⟨h₀, h₂⟩).1, fun s₀ h₀ => (hx (s₁, s₀) ⟨h₁, h₀⟩).2⟩ theorem sInter_prod {S : Set (Set α)} (hS : S.Nonempty) (t : Set β) : ⋂₀ S ×ˢ t = ⋂ s ∈ S, s ×ˢ t := by rw [← sInter_singleton t, sInter_prod_sInter hS (singleton_nonempty t), sInter_singleton] simp_rw [prod_singleton, mem_image, iInter_exists, biInter_and', iInter_iInter_eq_right] theorem prod_sInter {T : Set (Set β)} (hT : T.Nonempty) (s : Set α) : s ×ˢ ⋂₀ T = ⋂ t ∈ T, s ×ˢ t := by rw [← sInter_singleton s, sInter_prod_sInter (singleton_nonempty s) hT, sInter_singleton] simp_rw [singleton_prod, mem_image, iInter_exists, biInter_and', iInter_iInter_eq_right] theorem prod_iInter {s : Set α} {t : ι → Set β} [hι : Nonempty ι] : (s ×ˢ ⋂ i, t i) = ⋂ i, s ×ˢ t i := by ext x simp only [mem_prod, mem_iInter] exact ⟨fun h i => ⟨h.1, h.2 i⟩, fun h => ⟨(h hι.some).1, fun i => (h i).2⟩⟩ end Prod section Image2 variable (f : α → β → γ) {s : Set α} {t : Set β} /-- The `Set.image2` version of `Set.image_eq_iUnion` -/ theorem image2_eq_iUnion (s : Set α) (t : Set β) : image2 f s t = ⋃ (i ∈ s) (j ∈ t), {f i j} := by ext; simp [eq_comm] theorem iUnion_image_left : ⋃ a ∈ s, f a '' t = image2 f s t := by simp only [image2_eq_iUnion, image_eq_iUnion] theorem iUnion_image_right : ⋃ b ∈ t, (f · b) '' s = image2 f s t := by rw [image2_swap, iUnion_image_left] theorem image2_iUnion_left (s : ι → Set α) (t : Set β) : image2 f (⋃ i, s i) t = ⋃ i, image2 f (s i) t := by simp only [← image_prod, iUnion_prod_const, image_iUnion] theorem image2_iUnion_right (s : Set α) (t : ι → Set β) : image2 f s (⋃ i, t i) = ⋃ i, image2 f s (t i) := by simp only [← image_prod, prod_iUnion, image_iUnion] /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ theorem image2_iUnion₂_left (s : ∀ i, κ i → Set α) (t : Set β) : image2 f (⋃ (i) (j), s i j) t = ⋃ (i) (j), image2 f (s i j) t := by simp_rw [image2_iUnion_left] /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ theorem image2_iUnion₂_right (s : Set α) (t : ∀ i, κ i → Set β) : image2 f s (⋃ (i) (j), t i j) = ⋃ (i) (j), image2 f s (t i j) := by simp_rw [image2_iUnion_right] theorem image2_iInter_subset_left (s : ι → Set α) (t : Set β) : image2 f (⋂ i, s i) t ⊆ ⋂ i, image2 f (s i) t := by simp_rw [image2_subset_iff, mem_iInter] exact fun x hx y hy i => mem_image2_of_mem (hx _) hy theorem image2_iInter_subset_right (s : Set α) (t : ι → Set β) : image2 f s (⋂ i, t i) ⊆ ⋂ i, image2 f s (t i) := by simp_rw [image2_subset_iff, mem_iInter] exact fun x hx y hy i => mem_image2_of_mem hx (hy _) /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ theorem image2_iInter₂_subset_left (s : ∀ i, κ i → Set α) (t : Set β) : image2 f (⋂ (i) (j), s i j) t ⊆ ⋂ (i) (j), image2 f (s i j) t := by simp_rw [image2_subset_iff, mem_iInter] exact fun x hx y hy i j => mem_image2_of_mem (hx _ _) hy /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ theorem image2_iInter₂_subset_right (s : Set α) (t : ∀ i, κ i → Set β) : image2 f s (⋂ (i) (j), t i j) ⊆ ⋂ (i) (j), image2 f s (t i j) := by simp_rw [image2_subset_iff, mem_iInter] exact fun x hx y hy i j => mem_image2_of_mem hx (hy _ _) theorem prod_eq_biUnion_left : s ×ˢ t = ⋃ a ∈ s, (fun b => (a, b)) '' t := by rw [iUnion_image_left, image2_mk_eq_prod] theorem prod_eq_biUnion_right : s ×ˢ t = ⋃ b ∈ t, (fun a => (a, b)) '' s := by rw [iUnion_image_right, image2_mk_eq_prod] end Image2 section Seq theorem seq_def {s : Set (α → β)} {t : Set α} : seq s t = ⋃ f ∈ s, f '' t := by rw [seq_eq_image2, iUnion_image_left] theorem seq_subset {s : Set (α → β)} {t : Set α} {u : Set β} : seq s t ⊆ u ↔ ∀ f ∈ s, ∀ a ∈ t, (f : α → β) a ∈ u := image2_subset_iff @[gcongr] theorem seq_mono {s₀ s₁ : Set (α → β)} {t₀ t₁ : Set α} (hs : s₀ ⊆ s₁) (ht : t₀ ⊆ t₁) : seq s₀ t₀ ⊆ seq s₁ t₁ := image2_subset hs ht theorem singleton_seq {f : α → β} {t : Set α} : Set.seq ({f} : Set (α → β)) t = f '' t := image2_singleton_left theorem seq_singleton {s : Set (α → β)} {a : α} : Set.seq s {a} = (fun f : α → β => f a) '' s := image2_singleton_right theorem seq_seq {s : Set (β → γ)} {t : Set (α → β)} {u : Set α} : seq s (seq t u) = seq (seq ((· ∘ ·) '' s) t) u := by simp only [seq_eq_image2, image2_image_left] exact .symm <| image2_assoc fun _ _ _ ↦ rfl theorem image_seq {f : β → γ} {s : Set (α → β)} {t : Set α} : f '' seq s t = seq ((f ∘ ·) '' s) t := by simp only [seq, image_image2, image2_image_left, comp_apply] theorem prod_eq_seq {s : Set α} {t : Set β} : s ×ˢ t = (Prod.mk '' s).seq t := by rw [seq_eq_image2, image2_image_left, image2_mk_eq_prod] theorem prod_image_seq_comm (s : Set α) (t : Set β) : (Prod.mk '' s).seq t = seq ((fun b a => (a, b)) '' t) s := by rw [← prod_eq_seq, ← image_swap_prod, prod_eq_seq, image_seq, ← image_comp]; rfl theorem image2_eq_seq (f : α → β → γ) (s : Set α) (t : Set β) : image2 f s t = seq (f '' s) t := by rw [seq_eq_image2, image2_image_left] end Seq section Pi variable {π : α → Type*} theorem pi_def (i : Set α) (s : ∀ a, Set (π a)) : pi i s = ⋂ a ∈ i, eval a ⁻¹' s a := by ext simp theorem univ_pi_eq_iInter (t : ∀ i, Set (π i)) : pi univ t = ⋂ i, eval i ⁻¹' t i := by simp only [pi_def, iInter_true, mem_univ] theorem pi_diff_pi_subset (i : Set α) (s t : ∀ a, Set (π a)) : pi i s \ pi i t ⊆ ⋃ a ∈ i, eval a ⁻¹' (s a \ t a) := by refine diff_subset_comm.2 fun x hx a ha => ?_ simp only [mem_diff, mem_pi, mem_iUnion, not_exists, mem_preimage, not_and, not_not, eval_apply] at hx exact hx.2 _ ha (hx.1 _ ha) theorem iUnion_univ_pi {ι : α → Type*} (t : (a : α) → ι a → Set (π a)) : ⋃ x : (a : α) → ι a, pi univ (fun a => t a (x a)) = pi univ fun a => ⋃ j : ι a, t a j := by ext simp [Classical.skolem] end Pi section Directed theorem directedOn_iUnion {r} {f : ι → Set α} (hd : Directed (· ⊆ ·) f) (h : ∀ x, DirectedOn r (f x)) : DirectedOn r (⋃ x, f x) := by simp only [DirectedOn, exists_prop, mem_iUnion, exists_imp] exact fun a₁ b₁ fb₁ a₂ b₂ fb₂ => let ⟨z, zb₁, zb₂⟩ := hd b₁ b₂ let ⟨x, xf, xa₁, xa₂⟩ := h z a₁ (zb₁ fb₁) a₂ (zb₂ fb₂) ⟨x, ⟨z, xf⟩, xa₁, xa₂⟩ @[deprecated (since := "2024-05-05")] alias directed_on_iUnion := directedOn_iUnion theorem directedOn_sUnion {r} {S : Set (Set α)} (hd : DirectedOn (· ⊆ ·) S) (h : ∀ x ∈ S, DirectedOn r x) : DirectedOn r (⋃₀ S) := by rw [sUnion_eq_iUnion] exact directedOn_iUnion (directedOn_iff_directed.mp hd) (fun i ↦ h i.1 i.2) end Directed end Set namespace Function namespace Surjective theorem iUnion_comp {f : ι → ι₂} (hf : Surjective f) (g : ι₂ → Set α) : ⋃ x, g (f x) = ⋃ y, g y := hf.iSup_comp g theorem iInter_comp {f : ι → ι₂} (hf : Surjective f) (g : ι₂ → Set α) : ⋂ x, g (f x) = ⋂ y, g y := hf.iInf_comp g end Surjective end Function /-! ### Disjoint sets -/ section Disjoint variable {s t u : Set α} {f : α → β} namespace Set @[simp] theorem disjoint_iUnion_left {ι : Sort*} {s : ι → Set α} : Disjoint (⋃ i, s i) t ↔ ∀ i, Disjoint (s i) t := iSup_disjoint_iff @[simp] theorem disjoint_iUnion_right {ι : Sort*} {s : ι → Set α} : Disjoint t (⋃ i, s i) ↔ ∀ i, Disjoint t (s i) := disjoint_iSup_iff /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ -- Porting note (#10618): removing `simp`. `simp` can prove it theorem disjoint_iUnion₂_left {s : ∀ i, κ i → Set α} {t : Set α} : Disjoint (⋃ (i) (j), s i j) t ↔ ∀ i j, Disjoint (s i j) t := iSup₂_disjoint_iff /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ -- Porting note (#10618): removing `simp`. `simp` can prove it theorem disjoint_iUnion₂_right {s : Set α} {t : ∀ i, κ i → Set α} : Disjoint s (⋃ (i) (j), t i j) ↔ ∀ i j, Disjoint s (t i j) := disjoint_iSup₂_iff @[simp] theorem disjoint_sUnion_left {S : Set (Set α)} {t : Set α} : Disjoint (⋃₀S) t ↔ ∀ s ∈ S, Disjoint s t := sSup_disjoint_iff @[simp] theorem disjoint_sUnion_right {s : Set α} {S : Set (Set α)} : Disjoint s (⋃₀S) ↔ ∀ t ∈ S, Disjoint s t := disjoint_sSup_iff lemma biUnion_compl_eq_of_pairwise_disjoint_of_iUnion_eq_univ {ι : Type*} {Es : ι → Set α} (Es_union : ⋃ i, Es i = univ) (Es_disj : Pairwise fun i j ↦ Disjoint (Es i) (Es j)) (I : Set ι) : (⋃ i ∈ I, Es i)ᶜ = ⋃ i ∈ Iᶜ, Es i := by ext x obtain ⟨i, hix⟩ : ∃ i, x ∈ Es i := by simp [← mem_iUnion, Es_union] have obs : ∀ (J : Set ι), x ∈ ⋃ j ∈ J, Es j ↔ i ∈ J := by refine fun J ↦ ⟨?_, fun i_in_J ↦ by simpa only [mem_iUnion, exists_prop] using ⟨i, i_in_J, hix⟩⟩ intro x_in_U simp only [mem_iUnion, exists_prop] at x_in_U obtain ⟨j, j_in_J, hjx⟩ := x_in_U rwa [show i = j by by_contra i_ne_j; exact Disjoint.ne_of_mem (Es_disj i_ne_j) hix hjx rfl] have obs' : ∀ (J : Set ι), x ∈ (⋃ j ∈ J, Es j)ᶜ ↔ i ∉ J := fun J ↦ by simpa only [mem_compl_iff, not_iff_not] using obs J rw [obs, obs', mem_compl_iff] end Set end Disjoint /-! ### Intervals -/ namespace Set lemma nonempty_iInter_Iic_iff [Preorder α] {f : ι → α} : (⋂ i, Iic (f i)).Nonempty ↔ BddBelow (range f) := by have : (⋂ (i : ι), Iic (f i)) = lowerBounds (range f) := by ext c; simp [lowerBounds] simp [this, BddBelow] lemma nonempty_iInter_Ici_iff [Preorder α] {f : ι → α} : (⋂ i, Ici (f i)).Nonempty ↔ BddAbove (range f) := nonempty_iInter_Iic_iff (α := αᵒᵈ) variable [CompleteLattice α] theorem Ici_iSup (f : ι → α) : Ici (⨆ i, f i) = ⋂ i, Ici (f i) := ext fun _ => by simp only [mem_Ici, iSup_le_iff, mem_iInter] theorem Iic_iInf (f : ι → α) : Iic (⨅ i, f i) = ⋂ i, Iic (f i) := ext fun _ => by simp only [mem_Iic, le_iInf_iff, mem_iInter] /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ theorem Ici_iSup₂ (f : ∀ i, κ i → α) : Ici (⨆ (i) (j), f i j) = ⋂ (i) (j), Ici (f i j) := by simp_rw [Ici_iSup] /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ theorem Iic_iInf₂ (f : ∀ i, κ i → α) : Iic (⨅ (i) (j), f i j) = ⋂ (i) (j), Iic (f i j) := by simp_rw [Iic_iInf] theorem Ici_sSup (s : Set α) : Ici (sSup s) = ⋂ a ∈ s, Ici a := by rw [sSup_eq_iSup, Ici_iSup₂] theorem Iic_sInf (s : Set α) : Iic (sInf s) = ⋂ a ∈ s, Iic a := by rw [sInf_eq_iInf, Iic_iInf₂] end Set namespace Set variable (t : α → Set β) theorem biUnion_diff_biUnion_subset (s₁ s₂ : Set α) : ((⋃ x ∈ s₁, t x) \ ⋃ x ∈ s₂, t x) ⊆ ⋃ x ∈ s₁ \ s₂, t x := by simp only [diff_subset_iff, ← biUnion_union] apply biUnion_subset_biUnion_left rw [union_diff_self] apply subset_union_right /-- If `t` is an indexed family of sets, then there is a natural map from `Σ i, t i` to `⋃ i, t i` sending `⟨i, x⟩` to `x`. -/ def sigmaToiUnion (x : Σi, t i) : ⋃ i, t i := ⟨x.2, mem_iUnion.2 ⟨x.1, x.2.2⟩⟩ theorem sigmaToiUnion_surjective : Surjective (sigmaToiUnion t) | ⟨b, hb⟩ => have : ∃ a, b ∈ t a := by simpa using hb let ⟨a, hb⟩ := this ⟨⟨a, b, hb⟩, rfl⟩ theorem sigmaToiUnion_injective (h : Pairwise fun i j => Disjoint (t i) (t j)) : Injective (sigmaToiUnion t) | ⟨a₁, b₁, h₁⟩, ⟨a₂, b₂, h₂⟩, eq => have b_eq : b₁ = b₂ := congr_arg Subtype.val eq have a_eq : a₁ = a₂ := by_contradiction fun ne => have : b₁ ∈ t a₁ ∩ t a₂ := ⟨h₁, b_eq.symm ▸ h₂⟩ (h ne).le_bot this Sigma.eq a_eq <| Subtype.eq <| by subst b_eq; subst a_eq; rfl theorem sigmaToiUnion_bijective (h : Pairwise fun i j => Disjoint (t i) (t j)) : Bijective (sigmaToiUnion t) := ⟨sigmaToiUnion_injective t h, sigmaToiUnion_surjective t⟩ /-- Equivalence from the disjoint union of a family of sets forming a partition of `β`, to `β` itself. -/ noncomputable def sigmaEquiv (s : α → Set β) (hs : ∀ b, ∃! i, b ∈ s i) : (Σ i, s i) ≃ β where toFun | ⟨_, b⟩ => b invFun b := ⟨(hs b).choose, b, (hs b).choose_spec.1⟩ left_inv | ⟨i, b, hb⟩ => Sigma.subtype_ext ((hs b).choose_spec.2 i hb).symm rfl right_inv _ := rfl /-- Equivalence between a disjoint union and a dependent sum. -/ noncomputable def unionEqSigmaOfDisjoint {t : α → Set β} (h : Pairwise fun i j => Disjoint (t i) (t j)) : (⋃ i, t i) ≃ Σi, t i := (Equiv.ofBijective _ <| sigmaToiUnion_bijective t h).symm theorem iUnion_ge_eq_iUnion_nat_add (u : ℕ → Set α) (n : ℕ) : ⋃ i ≥ n, u i = ⋃ i, u (i + n) := iSup_ge_eq_iSup_nat_add u n theorem iInter_ge_eq_iInter_nat_add (u : ℕ → Set α) (n : ℕ) : ⋂ i ≥ n, u i = ⋂ i, u (i + n) := iInf_ge_eq_iInf_nat_add u n theorem _root_.Monotone.iUnion_nat_add {f : ℕ → Set α} (hf : Monotone f) (k : ℕ) : ⋃ n, f (n + k) = ⋃ n, f n := hf.iSup_nat_add k theorem _root_.Antitone.iInter_nat_add {f : ℕ → Set α} (hf : Antitone f) (k : ℕ) : ⋂ n, f (n + k) = ⋂ n, f n := hf.iInf_nat_add k /- Porting note: removing `simp`. LHS does not simplify. Possible linter bug. Zulip discussion: https://leanprover.zulipchat.com/#narrow/stream/287929-mathlib4/topic/complete_lattice.20and.20has_sup/near/316497982 -/ theorem iUnion_iInter_ge_nat_add (f : ℕ → Set α) (k : ℕ) : ⋃ n, ⋂ i ≥ n, f (i + k) = ⋃ n, ⋂ i ≥ n, f i := iSup_iInf_ge_nat_add f k theorem union_iUnion_nat_succ (u : ℕ → Set α) : (u 0 ∪ ⋃ i, u (i + 1)) = ⋃ i, u i := sup_iSup_nat_succ u theorem inter_iInter_nat_succ (u : ℕ → Set α) : (u 0 ∩ ⋂ i, u (i + 1)) = ⋂ i, u i := inf_iInf_nat_succ u end Set open Set variable [CompleteLattice β] theorem iSup_iUnion (s : ι → Set α) (f : α → β) : ⨆ a ∈ ⋃ i, s i, f a = ⨆ (i) (a ∈ s i), f a := by rw [iSup_comm] simp_rw [mem_iUnion, iSup_exists] theorem iInf_iUnion (s : ι → Set α) (f : α → β) : ⨅ a ∈ ⋃ i, s i, f a = ⨅ (i) (a ∈ s i), f a := iSup_iUnion (β := βᵒᵈ) s f theorem sSup_iUnion (t : ι → Set β) : sSup (⋃ i, t i) = ⨆ i, sSup (t i) := by simp_rw [sSup_eq_iSup, iSup_iUnion] theorem sSup_sUnion (s : Set (Set β)) : sSup (⋃₀ s) = ⨆ t ∈ s, sSup t := by simp only [sUnion_eq_biUnion, sSup_eq_iSup, iSup_iUnion] theorem sInf_sUnion (s : Set (Set β)) : sInf (⋃₀ s) = ⨅ t ∈ s, sInf t := sSup_sUnion (β := βᵒᵈ) s lemma iSup_sUnion (S : Set (Set α)) (f : α → β) : (⨆ x ∈ ⋃₀ S, f x) = ⨆ (s ∈ S) (x ∈ s), f x := by rw [sUnion_eq_iUnion, iSup_iUnion, ← iSup_subtype''] lemma iInf_sUnion (S : Set (Set α)) (f : α → β) : (⨅ x ∈ ⋃₀ S, f x) = ⨅ (s ∈ S) (x ∈ s), f x := by rw [sUnion_eq_iUnion, iInf_iUnion, ← iInf_subtype''] lemma forall_sUnion {S : Set (Set α)} {p : α → Prop} : (∀ x ∈ ⋃₀ S, p x) ↔ ∀ s ∈ S, ∀ x ∈ s, p x := by simp_rw [← iInf_Prop_eq, iInf_sUnion] lemma exists_sUnion {S : Set (Set α)} {p : α → Prop} : (∃ x ∈ ⋃₀ S, p x) ↔ ∃ s ∈ S, ∃ x ∈ s, p x := by simp_rw [← exists_prop, ← iSup_Prop_eq, iSup_sUnion]
Data\Set\List.lean
/- Copyright (c) 2023 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import Mathlib.Data.Set.Image import Mathlib.Data.List.Defs /-! # Lemmas about `List`s and `Set.range` In this file we prove lemmas about range of some operations on lists. -/ open List variable {α β : Type*} (l : List α) namespace Set theorem range_list_map (f : α → β) : range (map f) = { l | ∀ x ∈ l, x ∈ range f } := by refine antisymm (range_subset_iff.2 fun l => forall_mem_map.2 fun y _ => mem_range_self _) fun l hl => ?_ induction' l with a l ihl; · exact ⟨[], rfl⟩ rcases ihl fun x hx => hl x <| subset_cons_self _ _ hx with ⟨l, rfl⟩ rcases hl a (mem_cons_self _ _) with ⟨a, rfl⟩ exact ⟨a :: l, map_cons _ _ _⟩ theorem range_list_map_coe (s : Set α) : range (map ((↑) : s → α)) = { l | ∀ x ∈ l, x ∈ s } := by rw [range_list_map, Subtype.range_coe] @[simp] theorem range_list_get : range l.get = { x | x ∈ l } := by ext x rw [mem_setOf_eq, mem_iff_get, mem_range] @[deprecated (since := "2024-04-22")] alias range_list_nthLe := range_list_get theorem range_list_get? : range l.get? = insert none (some '' { x | x ∈ l }) := by rw [← range_list_get, ← range_comp] refine (range_subset_iff.2 fun n => ?_).antisymm (insert_subset_iff.2 ⟨?_, ?_⟩) exacts [(le_or_lt l.length n).imp get?_eq_none.2 (fun hlt => ⟨⟨_, hlt⟩, (get?_eq_get hlt).symm⟩), ⟨_, get?_eq_none.2 le_rfl⟩, range_subset_iff.2 fun k => ⟨_, get?_eq_get _⟩] @[simp] theorem range_list_getD (d : α) : (range fun n : Nat => l[n]?.getD d) = insert d { x | x ∈ l } := calc (range fun n => l[n]?.getD d) = (fun o : Option α => o.getD d) '' range l.get? := by simp [← range_comp, (· ∘ ·)] _ = insert d { x | x ∈ l } := by simp only [range_list_get?, image_insert_eq, Option.getD, image_image, image_id'] @[simp] theorem range_list_getI [Inhabited α] (l : List α) : range l.getI = insert default { x | x ∈ l } := by unfold List.getI simp end Set /-- If each element of a list can be lifted to some type, then the whole list can be lifted to this type. -/ instance List.canLift (c) (p) [CanLift α β c p] : CanLift (List α) (List β) (List.map c) fun l => ∀ x ∈ l, p x where prf l H := by rw [← Set.mem_range, Set.range_list_map] exact fun a ha => CanLift.prf a (H a ha)
Data\Set\MemPartition.lean
/- Copyright (c) 2024 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne -/ import Mathlib.Data.Set.Finite /-! # Partitions based on membership of a sequence of sets Let `f : ℕ → Set α` be a sequence of sets. For `n : ℕ`, we can form the set of points that are in `f 0 ∪ f 1 ∪ ... ∪ f (n-1)`; then the set of points in `(f 0)ᶜ ∪ f 1 ∪ ... ∪ f (n-1)` and so on for all 2^n choices of a set or its complement. The at most 2^n sets we obtain form a partition of `univ : Set α`. We call that partition `memPartition f n` (the membership partition of `f`). For `n = 0` we set `memPartition f 0 = {univ}`. The partition `memPartition f (n + 1)` is finer than `memPartition f n`. ## Main definitions * `memPartition f n`: the membership partition of the first `n` sets in `f`. * `memPartitionSet`: `memPartitionSet f n x` is the set in the partition `memPartition f n` to which `x` belongs. ## Main statements * `disjoint_memPartition`: the sets in `memPartition f n` are disjoint * `sUnion_memPartition`: the union of the sets in `memPartition f n` is `univ` * `finite_memPartition`: `memPartition f n` is finite -/ open Set variable {α : Type*} /-- `memPartition f n` is the partition containing at most `2^(n+1)` sets, where each set contains the points that for all `i` belong to one of `f i` or its complement. -/ def memPartition (f : ℕ → Set α) : ℕ → Set (Set α) | 0 => {univ} | n + 1 => {s | ∃ u ∈ memPartition f n, s = u ∩ f n ∨ s = u \ f n} @[simp] lemma memPartition_zero (f : ℕ → Set α) : memPartition f 0 = {univ} := rfl lemma memPartition_succ (f : ℕ → Set α) (n : ℕ) : memPartition f (n + 1) = {s | ∃ u ∈ memPartition f n, s = u ∩ f n ∨ s = u \ f n} := rfl lemma disjoint_memPartition (f : ℕ → Set α) (n : ℕ) {u v : Set α} (hu : u ∈ memPartition f n) (hv : v ∈ memPartition f n) (huv : u ≠ v) : Disjoint u v := by revert u v induction n with | zero => intro u v hu hv huv simp only [Nat.zero_eq, memPartition_zero, mem_insert_iff, mem_singleton_iff] at hu hv rw [hu, hv] at huv exact absurd rfl huv | succ n ih => intro u v hu hv huv rw [memPartition_succ] at hu hv obtain ⟨u', hu', hu'_eq⟩ := hu obtain ⟨v', hv', hv'_eq⟩ := hv rcases hu'_eq with rfl | rfl <;> rcases hv'_eq with rfl | rfl · refine Disjoint.mono inter_subset_left inter_subset_left (ih hu' hv' ?_) exact fun huv' ↦ huv (huv' ▸ rfl) · exact Disjoint.mono_left inter_subset_right Set.disjoint_sdiff_right · exact Disjoint.mono_right inter_subset_right Set.disjoint_sdiff_left · refine Disjoint.mono diff_subset diff_subset (ih hu' hv' ?_) exact fun huv' ↦ huv (huv' ▸ rfl) @[simp] lemma sUnion_memPartition (f : ℕ → Set α) (n : ℕ) : ⋃₀ memPartition f n = univ := by induction n with | zero => simp | succ n ih => rw [memPartition_succ] ext x have : x ∈ ⋃₀ memPartition f n := by simp [ih] simp only [mem_sUnion, mem_iUnion, mem_insert_iff, mem_singleton_iff, exists_prop, mem_univ, iff_true] at this ⊢ obtain ⟨t, ht, hxt⟩ := this by_cases hxf : x ∈ f n · exact ⟨t ∩ f n, ⟨t, ht, Or.inl rfl⟩, hxt, hxf⟩ · exact ⟨t \ f n, ⟨t, ht, Or.inr rfl⟩, hxt, hxf⟩ lemma finite_memPartition (f : ℕ → Set α) (n : ℕ) : Set.Finite (memPartition f n) := by induction n with | zero => simp | succ n ih => rw [memPartition_succ] have : Finite (memPartition f n) := Set.finite_coe_iff.mp ih rw [← Set.finite_coe_iff] simp_rw [setOf_exists, ← exists_prop, setOf_exists, setOf_or] refine Finite.Set.finite_biUnion (memPartition f n) _ (fun u _ ↦ ?_) rw [Set.finite_coe_iff] simp instance instFinite_memPartition (f : ℕ → Set α) (n : ℕ) : Finite (memPartition f n) := Set.finite_coe_iff.mp (finite_memPartition _ _) noncomputable instance instFintype_memPartition (f : ℕ → Set α) (n : ℕ) : Fintype (memPartition f n) := (finite_memPartition f n).fintype open Classical in /-- The set in `memPartition f n` to which `a : α` belongs. -/ def memPartitionSet (f : ℕ → Set α) : ℕ → α → Set α | 0 => fun _ ↦ univ | n + 1 => fun a ↦ if a ∈ f n then memPartitionSet f n a ∩ f n else memPartitionSet f n a \ f n @[simp] lemma memPartitionSet_zero (f : ℕ → Set α) (a : α) : memPartitionSet f 0 a = univ := by simp [memPartitionSet] lemma memPartitionSet_succ (f : ℕ → Set α) (n : ℕ) (a : α) [Decidable (a ∈ f n)] : memPartitionSet f (n + 1) a = if a ∈ f n then memPartitionSet f n a ∩ f n else memPartitionSet f n a \ f n := by simp [memPartitionSet] congr lemma memPartitionSet_mem (f : ℕ → Set α) (n : ℕ) (a : α) : memPartitionSet f n a ∈ memPartition f n := by induction n with | zero => simp [memPartitionSet] | succ n ih => classical rw [memPartitionSet_succ, memPartition_succ] refine ⟨memPartitionSet f n a, ?_⟩ split_ifs <;> simp [ih] lemma mem_memPartitionSet (f : ℕ → Set α) (n : ℕ) (a : α) : a ∈ memPartitionSet f n a := by induction n with | zero => simp [memPartitionSet] | succ n ih => classical rw [memPartitionSet_succ] split_ifs with h <;> exact ⟨ih, h⟩ lemma memPartitionSet_eq_iff {f : ℕ → Set α} {n : ℕ} (a : α) {s : Set α} (hs : s ∈ memPartition f n) : memPartitionSet f n a = s ↔ a ∈ s := by refine ⟨fun h ↦ h ▸ mem_memPartitionSet f n a, fun h ↦ ?_⟩ by_contra h_ne have h_disj : Disjoint s (memPartitionSet f n a) := disjoint_memPartition f n hs (memPartitionSet_mem f n a) (Ne.symm h_ne) refine absurd h_disj ?_ rw [not_disjoint_iff_nonempty_inter] exact ⟨a, h, mem_memPartitionSet f n a⟩ lemma memPartitionSet_of_mem {f : ℕ → Set α} {n : ℕ} {a : α} {s : Set α} (hs : s ∈ memPartition f n) (ha : a ∈ s) : memPartitionSet f n a = s := (memPartitionSet_eq_iff a hs).mpr ha
Data\Set\MulAntidiagonal.lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Floris van Doorn -/ import Mathlib.Order.WellFoundedSet /-! # Multiplication antidiagonal -/ namespace Set variable {α : Type*} section Mul variable [Mul α] {s s₁ s₂ t t₁ t₂ : Set α} {a : α} {x : α × α} /-- `Set.mulAntidiagonal s t a` is the set of all pairs of an element in `s` and an element in `t` that multiply to `a`. -/ @[to_additive "`Set.addAntidiagonal s t a` is the set of all pairs of an element in `s` and an element in `t` that add to `a`."] def mulAntidiagonal (s t : Set α) (a : α) : Set (α × α) := { x | x.1 ∈ s ∧ x.2 ∈ t ∧ x.1 * x.2 = a } @[to_additive (attr := simp)] theorem mem_mulAntidiagonal : x ∈ mulAntidiagonal s t a ↔ x.1 ∈ s ∧ x.2 ∈ t ∧ x.1 * x.2 = a := Iff.rfl @[to_additive] theorem mulAntidiagonal_mono_left (h : s₁ ⊆ s₂) : mulAntidiagonal s₁ t a ⊆ mulAntidiagonal s₂ t a := fun _ hx => ⟨h hx.1, hx.2.1, hx.2.2⟩ @[to_additive] theorem mulAntidiagonal_mono_right (h : t₁ ⊆ t₂) : mulAntidiagonal s t₁ a ⊆ mulAntidiagonal s t₂ a := fun _ hx => ⟨hx.1, h hx.2.1, hx.2.2⟩ end Mul -- Porting note: Removed simp attribute, simpnf linter can simplify lhs. Added aux version below @[to_additive] theorem swap_mem_mulAntidiagonal [CommSemigroup α] {s t : Set α} {a : α} {x : α × α} : x.swap ∈ Set.mulAntidiagonal s t a ↔ x ∈ Set.mulAntidiagonal t s a := by simp [mul_comm, and_left_comm] @[to_additive (attr := simp)] theorem swap_mem_mulAntidiagonal_aux [CommSemigroup α] {s t : Set α} {a : α} {x : α × α} : x.snd ∈ s ∧ x.fst ∈ t ∧ x.snd * x.fst = a ↔ x ∈ Set.mulAntidiagonal t s a := by simp [mul_comm, and_left_comm] namespace MulAntidiagonal section CancelCommMonoid variable [CancelCommMonoid α] {s t : Set α} {a : α} {x y : mulAntidiagonal s t a} -- Porting note: to_additive cannot translate the "Mul" in "MulAntidiagonal" by itself here @[to_additive Set.AddAntidiagonal.fst_eq_fst_iff_snd_eq_snd] theorem fst_eq_fst_iff_snd_eq_snd : (x : α × α).1 = (y : α × α).1 ↔ (x : α × α).2 = (y : α × α).2 := ⟨fun h => mul_left_cancel (y.2.2.2.trans <| by rw [← h] exact x.2.2.2.symm).symm, fun h => mul_right_cancel (y.2.2.2.trans <| by rw [← h] exact x.2.2.2.symm).symm⟩ @[to_additive Set.AddAntidiagonal.eq_of_fst_eq_fst] theorem eq_of_fst_eq_fst (h : (x : α × α).fst = (y : α × α).fst) : x = y := Subtype.ext <| Prod.ext h <| fst_eq_fst_iff_snd_eq_snd.1 h @[to_additive Set.AddAntidiagonal.eq_of_snd_eq_snd] theorem eq_of_snd_eq_snd (h : (x : α × α).snd = (y : α × α).snd) : x = y := Subtype.ext <| Prod.ext (fst_eq_fst_iff_snd_eq_snd.2 h) h end CancelCommMonoid section OrderedCancelCommMonoid variable [OrderedCancelCommMonoid α] (s t : Set α) (a : α) {x y : mulAntidiagonal s t a} @[to_additive Set.AddAntidiagonal.eq_of_fst_le_fst_of_snd_le_snd] theorem eq_of_fst_le_fst_of_snd_le_snd (h₁ : (x : α × α).1 ≤ (y : α × α).1) (h₂ : (x : α × α).2 ≤ (y : α × α).2) : x = y := eq_of_fst_eq_fst <| h₁.eq_of_not_lt fun hlt => (mul_lt_mul_of_lt_of_le hlt h₂).ne <| (mem_mulAntidiagonal.1 x.2).2.2.trans (mem_mulAntidiagonal.1 y.2).2.2.symm variable {s t} @[to_additive Set.AddAntidiagonal.finite_of_isPWO] theorem finite_of_isPWO (hs : s.IsPWO) (ht : t.IsPWO) (a) : (mulAntidiagonal s t a).Finite := by refine not_infinite.1 fun h => ?_ have h1 : (mulAntidiagonal s t a).PartiallyWellOrderedOn (Prod.fst ⁻¹'o (· ≤ ·)) := fun f hf => hs (Prod.fst ∘ f) fun n => (mem_mulAntidiagonal.1 (hf n)).1 have h2 : (mulAntidiagonal s t a).PartiallyWellOrderedOn (Prod.snd ⁻¹'o (· ≤ ·)) := fun f hf => ht (Prod.snd ∘ f) fun n => (mem_mulAntidiagonal.1 (hf n)).2.1 obtain ⟨g, hg⟩ := h1.exists_monotone_subseq (fun n => h.natEmbedding _ n) fun n => (h.natEmbedding _ n).2 obtain ⟨m, n, mn, h2'⟩ := h2 (fun x => (h.natEmbedding _) (g x)) fun n => (h.natEmbedding _ _).2 refine mn.ne (g.injective <| (h.natEmbedding _).injective ?_) exact eq_of_fst_le_fst_of_snd_le_snd _ _ _ (hg _ _ mn.le) h2' end OrderedCancelCommMonoid @[to_additive Set.AddAntidiagonal.finite_of_isWF] theorem finite_of_isWF [LinearOrderedCancelCommMonoid α] {s t : Set α} (hs : s.IsWF) (ht : t.IsWF) (a) : (mulAntidiagonal s t a).Finite := finite_of_isPWO hs.isPWO ht.isPWO a end MulAntidiagonal end Set
Data\Set\NAry.lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import Mathlib.Data.Set.Prod /-! # N-ary images of sets This file defines `Set.image2`, the binary image of sets. This is mostly useful to define pointwise operations and `Set.seq`. ## Notes This file is very similar to `Data.Finset.NAry`, to `Order.Filter.NAry`, and to `Data.Option.NAry`. Please keep them in sync. -/ open Function namespace Set variable {α α' β β' γ γ' δ δ' ε ε' ζ ζ' ν : Type*} {f f' : α → β → γ} {g g' : α → β → γ → δ} variable {s s' : Set α} {t t' : Set β} {u u' : Set γ} {v : Set δ} {a a' : α} {b b' : β} {c c' : γ} {d d' : δ} theorem mem_image2_iff (hf : Injective2 f) : f a b ∈ image2 f s t ↔ a ∈ s ∧ b ∈ t := ⟨by rintro ⟨a', ha', b', hb', h⟩ rcases hf h with ⟨rfl, rfl⟩ exact ⟨ha', hb'⟩, fun ⟨ha, hb⟩ => mem_image2_of_mem ha hb⟩ /-- image2 is monotone with respect to `⊆`. -/ theorem image2_subset (hs : s ⊆ s') (ht : t ⊆ t') : image2 f s t ⊆ image2 f s' t' := by rintro _ ⟨a, ha, b, hb, rfl⟩ exact mem_image2_of_mem (hs ha) (ht hb) theorem image2_subset_left (ht : t ⊆ t') : image2 f s t ⊆ image2 f s t' := image2_subset Subset.rfl ht theorem image2_subset_right (hs : s ⊆ s') : image2 f s t ⊆ image2 f s' t := image2_subset hs Subset.rfl theorem image_subset_image2_left (hb : b ∈ t) : (fun a => f a b) '' s ⊆ image2 f s t := forall_mem_image.2 fun _ ha => mem_image2_of_mem ha hb theorem image_subset_image2_right (ha : a ∈ s) : f a '' t ⊆ image2 f s t := forall_mem_image.2 fun _ => mem_image2_of_mem ha theorem forall_image2_iff {p : γ → Prop} : (∀ z ∈ image2 f s t, p z) ↔ ∀ x ∈ s, ∀ y ∈ t, p (f x y) := ⟨fun h x hx y hy => h _ ⟨x, hx, y, hy, rfl⟩, fun h _ ⟨x, hx, y, hy, hz⟩ => hz ▸ h x hx y hy⟩ @[simp] theorem image2_subset_iff {u : Set γ} : image2 f s t ⊆ u ↔ ∀ x ∈ s, ∀ y ∈ t, f x y ∈ u := forall_image2_iff theorem image2_subset_iff_left : image2 f s t ⊆ u ↔ ∀ a ∈ s, (fun b => f a b) '' t ⊆ u := by simp_rw [image2_subset_iff, image_subset_iff, subset_def, mem_preimage] theorem image2_subset_iff_right : image2 f s t ⊆ u ↔ ∀ b ∈ t, (fun a => f a b) '' s ⊆ u := by simp_rw [image2_subset_iff, image_subset_iff, subset_def, mem_preimage, @forall₂_swap α] variable (f) -- Porting note: Removing `simp` - LHS does not simplify lemma image_prod : (fun x : α × β ↦ f x.1 x.2) '' s ×ˢ t = image2 f s t := ext fun _ ↦ by simp [and_assoc] @[simp] lemma image_uncurry_prod (s : Set α) (t : Set β) : uncurry f '' s ×ˢ t = image2 f s t := image_prod _ @[simp] lemma image2_mk_eq_prod : image2 Prod.mk s t = s ×ˢ t := ext <| by simp -- Porting note: Removing `simp` - LHS does not simplify lemma image2_curry (f : α × β → γ) (s : Set α) (t : Set β) : image2 (fun a b ↦ f (a, b)) s t = f '' s ×ˢ t := by simp [← image_uncurry_prod, uncurry] theorem image2_swap (s : Set α) (t : Set β) : image2 f s t = image2 (fun a b => f b a) t s := by ext constructor <;> rintro ⟨a, ha, b, hb, rfl⟩ <;> exact ⟨b, hb, a, ha, rfl⟩ variable {f} theorem image2_union_left : image2 f (s ∪ s') t = image2 f s t ∪ image2 f s' t := by simp_rw [← image_prod, union_prod, image_union] theorem image2_union_right : image2 f s (t ∪ t') = image2 f s t ∪ image2 f s t' := by rw [← image2_swap, image2_union_left, image2_swap f, image2_swap f] lemma image2_inter_left (hf : Injective2 f) : image2 f (s ∩ s') t = image2 f s t ∩ image2 f s' t := by simp_rw [← image_uncurry_prod, inter_prod, image_inter hf.uncurry] lemma image2_inter_right (hf : Injective2 f) : image2 f s (t ∩ t') = image2 f s t ∩ image2 f s t' := by simp_rw [← image_uncurry_prod, prod_inter, image_inter hf.uncurry] @[simp] theorem image2_empty_left : image2 f ∅ t = ∅ := ext <| by simp @[simp] theorem image2_empty_right : image2 f s ∅ = ∅ := ext <| by simp theorem Nonempty.image2 : s.Nonempty → t.Nonempty → (image2 f s t).Nonempty := fun ⟨_, ha⟩ ⟨_, hb⟩ => ⟨_, mem_image2_of_mem ha hb⟩ @[simp] theorem image2_nonempty_iff : (image2 f s t).Nonempty ↔ s.Nonempty ∧ t.Nonempty := ⟨fun ⟨_, a, ha, b, hb, _⟩ => ⟨⟨a, ha⟩, b, hb⟩, fun h => h.1.image2 h.2⟩ theorem Nonempty.of_image2_left (h : (Set.image2 f s t).Nonempty) : s.Nonempty := (image2_nonempty_iff.1 h).1 theorem Nonempty.of_image2_right (h : (Set.image2 f s t).Nonempty) : t.Nonempty := (image2_nonempty_iff.1 h).2 @[simp] theorem image2_eq_empty_iff : image2 f s t = ∅ ↔ s = ∅ ∨ t = ∅ := by rw [← not_nonempty_iff_eq_empty, image2_nonempty_iff, not_and_or] simp [not_nonempty_iff_eq_empty] theorem Subsingleton.image2 (hs : s.Subsingleton) (ht : t.Subsingleton) (f : α → β → γ) : (image2 f s t).Subsingleton := by rw [← image_prod] apply (hs.prod ht).image theorem image2_inter_subset_left : image2 f (s ∩ s') t ⊆ image2 f s t ∩ image2 f s' t := Monotone.map_inf_le (fun _ _ ↦ image2_subset_right) s s' theorem image2_inter_subset_right : image2 f s (t ∩ t') ⊆ image2 f s t ∩ image2 f s t' := Monotone.map_inf_le (fun _ _ ↦ image2_subset_left) t t' @[simp] theorem image2_singleton_left : image2 f {a} t = f a '' t := ext fun x => by simp @[simp] theorem image2_singleton_right : image2 f s {b} = (fun a => f a b) '' s := ext fun x => by simp theorem image2_singleton : image2 f {a} {b} = {f a b} := by simp @[simp] theorem image2_insert_left : image2 f (insert a s) t = (fun b => f a b) '' t ∪ image2 f s t := by rw [insert_eq, image2_union_left, image2_singleton_left] @[simp] theorem image2_insert_right : image2 f s (insert b t) = (fun a => f a b) '' s ∪ image2 f s t := by rw [insert_eq, image2_union_right, image2_singleton_right] @[congr] theorem image2_congr (h : ∀ a ∈ s, ∀ b ∈ t, f a b = f' a b) : image2 f s t = image2 f' s t := by ext constructor <;> rintro ⟨a, ha, b, hb, rfl⟩ <;> exact ⟨a, ha, b, hb, by rw [h a ha b hb]⟩ /-- A common special case of `image2_congr` -/ theorem image2_congr' (h : ∀ a b, f a b = f' a b) : image2 f s t = image2 f' s t := image2_congr fun a _ b _ => h a b theorem image_image2 (f : α → β → γ) (g : γ → δ) : g '' image2 f s t = image2 (fun a b => g (f a b)) s t := by simp only [← image_prod, image_image] theorem image2_image_left (f : γ → β → δ) (g : α → γ) : image2 f (g '' s) t = image2 (fun a b => f (g a) b) s t := by ext; simp theorem image2_image_right (f : α → γ → δ) (g : β → γ) : image2 f s (g '' t) = image2 (fun a b => f a (g b)) s t := by ext; simp @[simp] theorem image2_left (h : t.Nonempty) : image2 (fun x _ => x) s t = s := by simp [nonempty_def.mp h, Set.ext_iff] @[simp] theorem image2_right (h : s.Nonempty) : image2 (fun _ y => y) s t = t := by simp [nonempty_def.mp h, Set.ext_iff] lemma image2_range (f : α' → β' → γ) (g : α → α') (h : β → β') : image2 f (range g) (range h) = range fun x : α × β ↦ f (g x.1) (h x.2) := by simp_rw [← image_univ, image2_image_left, image2_image_right, ← image_prod, univ_prod_univ] theorem image2_assoc {f : δ → γ → ε} {g : α → β → δ} {f' : α → ε' → ε} {g' : β → γ → ε'} (h_assoc : ∀ a b c, f (g a b) c = f' a (g' b c)) : image2 f (image2 g s t) u = image2 f' s (image2 g' t u) := eq_of_forall_subset_iff fun _ ↦ by simp only [image2_subset_iff, forall_image2_iff, h_assoc] theorem image2_comm {g : β → α → γ} (h_comm : ∀ a b, f a b = g b a) : image2 f s t = image2 g t s := (image2_swap _ _ _).trans <| by simp_rw [h_comm] theorem image2_left_comm {f : α → δ → ε} {g : β → γ → δ} {f' : α → γ → δ'} {g' : β → δ' → ε} (h_left_comm : ∀ a b c, f a (g b c) = g' b (f' a c)) : image2 f s (image2 g t u) = image2 g' t (image2 f' s u) := by rw [image2_swap f', image2_swap f] exact image2_assoc fun _ _ _ => h_left_comm _ _ _ theorem image2_right_comm {f : δ → γ → ε} {g : α → β → δ} {f' : α → γ → δ'} {g' : δ' → β → ε} (h_right_comm : ∀ a b c, f (g a b) c = g' (f' a c) b) : image2 f (image2 g s t) u = image2 g' (image2 f' s u) t := by rw [image2_swap g, image2_swap g'] exact image2_assoc fun _ _ _ => h_right_comm _ _ _ theorem image2_image2_image2_comm {f : ε → ζ → ν} {g : α → β → ε} {h : γ → δ → ζ} {f' : ε' → ζ' → ν} {g' : α → γ → ε'} {h' : β → δ → ζ'} (h_comm : ∀ a b c d, f (g a b) (h c d) = f' (g' a c) (h' b d)) : image2 f (image2 g s t) (image2 h u v) = image2 f' (image2 g' s u) (image2 h' t v) := by ext; constructor · rintro ⟨_, ⟨a, ha, b, hb, rfl⟩, _, ⟨c, hc, d, hd, rfl⟩, rfl⟩ exact ⟨_, ⟨a, ha, c, hc, rfl⟩, _, ⟨b, hb, d, hd, rfl⟩, (h_comm _ _ _ _).symm⟩ · rintro ⟨_, ⟨a, ha, c, hc, rfl⟩, _, ⟨b, hb, d, hd, rfl⟩, rfl⟩ exact ⟨_, ⟨a, ha, b, hb, rfl⟩, _, ⟨c, hc, d, hd, rfl⟩, h_comm _ _ _ _⟩ theorem image_image2_distrib {g : γ → δ} {f' : α' → β' → δ} {g₁ : α → α'} {g₂ : β → β'} (h_distrib : ∀ a b, g (f a b) = f' (g₁ a) (g₂ b)) : (image2 f s t).image g = image2 f' (s.image g₁) (t.image g₂) := by simp_rw [image_image2, image2_image_left, image2_image_right, h_distrib] /-- Symmetric statement to `Set.image2_image_left_comm`. -/ theorem image_image2_distrib_left {g : γ → δ} {f' : α' → β → δ} {g' : α → α'} (h_distrib : ∀ a b, g (f a b) = f' (g' a) b) : (image2 f s t).image g = image2 f' (s.image g') t := (image_image2_distrib h_distrib).trans <| by rw [image_id'] /-- Symmetric statement to `Set.image_image2_right_comm`. -/ theorem image_image2_distrib_right {g : γ → δ} {f' : α → β' → δ} {g' : β → β'} (h_distrib : ∀ a b, g (f a b) = f' a (g' b)) : (image2 f s t).image g = image2 f' s (t.image g') := (image_image2_distrib h_distrib).trans <| by rw [image_id'] /-- Symmetric statement to `Set.image_image2_distrib_left`. -/ theorem image2_image_left_comm {f : α' → β → γ} {g : α → α'} {f' : α → β → δ} {g' : δ → γ} (h_left_comm : ∀ a b, f (g a) b = g' (f' a b)) : image2 f (s.image g) t = (image2 f' s t).image g' := (image_image2_distrib_left fun a b => (h_left_comm a b).symm).symm /-- Symmetric statement to `Set.image_image2_distrib_right`. -/ theorem image_image2_right_comm {f : α → β' → γ} {g : β → β'} {f' : α → β → δ} {g' : δ → γ} (h_right_comm : ∀ a b, f a (g b) = g' (f' a b)) : image2 f s (t.image g) = (image2 f' s t).image g' := (image_image2_distrib_right fun a b => (h_right_comm a b).symm).symm /-- The other direction does not hold because of the `s`-`s` cross terms on the RHS. -/ theorem image2_distrib_subset_left {f : α → δ → ε} {g : β → γ → δ} {f₁ : α → β → β'} {f₂ : α → γ → γ'} {g' : β' → γ' → ε} (h_distrib : ∀ a b c, f a (g b c) = g' (f₁ a b) (f₂ a c)) : image2 f s (image2 g t u) ⊆ image2 g' (image2 f₁ s t) (image2 f₂ s u) := by rintro _ ⟨a, ha, _, ⟨b, hb, c, hc, rfl⟩, rfl⟩ rw [h_distrib] exact mem_image2_of_mem (mem_image2_of_mem ha hb) (mem_image2_of_mem ha hc) /-- The other direction does not hold because of the `u`-`u` cross terms on the RHS. -/ theorem image2_distrib_subset_right {f : δ → γ → ε} {g : α → β → δ} {f₁ : α → γ → α'} {f₂ : β → γ → β'} {g' : α' → β' → ε} (h_distrib : ∀ a b c, f (g a b) c = g' (f₁ a c) (f₂ b c)) : image2 f (image2 g s t) u ⊆ image2 g' (image2 f₁ s u) (image2 f₂ t u) := by rintro _ ⟨_, ⟨a, ha, b, hb, rfl⟩, c, hc, rfl⟩ rw [h_distrib] exact mem_image2_of_mem (mem_image2_of_mem ha hc) (mem_image2_of_mem hb hc) theorem image_image2_antidistrib {g : γ → δ} {f' : β' → α' → δ} {g₁ : β → β'} {g₂ : α → α'} (h_antidistrib : ∀ a b, g (f a b) = f' (g₁ b) (g₂ a)) : (image2 f s t).image g = image2 f' (t.image g₁) (s.image g₂) := by rw [image2_swap f] exact image_image2_distrib fun _ _ => h_antidistrib _ _ /-- Symmetric statement to `Set.image2_image_left_anticomm`. -/ theorem image_image2_antidistrib_left {g : γ → δ} {f' : β' → α → δ} {g' : β → β'} (h_antidistrib : ∀ a b, g (f a b) = f' (g' b) a) : (image2 f s t).image g = image2 f' (t.image g') s := (image_image2_antidistrib h_antidistrib).trans <| by rw [image_id'] /-- Symmetric statement to `Set.image_image2_right_anticomm`. -/ theorem image_image2_antidistrib_right {g : γ → δ} {f' : β → α' → δ} {g' : α → α'} (h_antidistrib : ∀ a b, g (f a b) = f' b (g' a)) : (image2 f s t).image g = image2 f' t (s.image g') := (image_image2_antidistrib h_antidistrib).trans <| by rw [image_id'] /-- Symmetric statement to `Set.image_image2_antidistrib_left`. -/ theorem image2_image_left_anticomm {f : α' → β → γ} {g : α → α'} {f' : β → α → δ} {g' : δ → γ} (h_left_anticomm : ∀ a b, f (g a) b = g' (f' b a)) : image2 f (s.image g) t = (image2 f' t s).image g' := (image_image2_antidistrib_left fun a b => (h_left_anticomm b a).symm).symm /-- Symmetric statement to `Set.image_image2_antidistrib_right`. -/ theorem image_image2_right_anticomm {f : α → β' → γ} {g : β → β'} {f' : β → α → δ} {g' : δ → γ} (h_right_anticomm : ∀ a b, f a (g b) = g' (f' b a)) : image2 f s (t.image g) = (image2 f' t s).image g' := (image_image2_antidistrib_right fun a b => (h_right_anticomm b a).symm).symm /-- If `a` is a left identity for `f : α → β → β`, then `{a}` is a left identity for `Set.image2 f`. -/ lemma image2_left_identity {f : α → β → β} {a : α} (h : ∀ b, f a b = b) (t : Set β) : image2 f {a} t = t := by rw [image2_singleton_left, show f a = id from funext h, image_id] /-- If `b` is a right identity for `f : α → β → α`, then `{b}` is a right identity for `Set.image2 f`. -/ lemma image2_right_identity {f : α → β → α} {b : β} (h : ∀ a, f a b = a) (s : Set α) : image2 f s {b} = s := by rw [image2_singleton_right, funext h, image_id'] theorem image2_inter_union_subset_union : image2 f (s ∩ s') (t ∪ t') ⊆ image2 f s t ∪ image2 f s' t' := by rw [image2_union_right] exact union_subset_union (image2_subset_right inter_subset_left) (image2_subset_right inter_subset_right) theorem image2_union_inter_subset_union : image2 f (s ∪ s') (t ∩ t') ⊆ image2 f s t ∪ image2 f s' t' := by rw [image2_union_left] exact union_subset_union (image2_subset_left inter_subset_left) (image2_subset_left inter_subset_right) theorem image2_inter_union_subset {f : α → α → β} {s t : Set α} (hf : ∀ a b, f a b = f b a) : image2 f (s ∩ t) (s ∪ t) ⊆ image2 f s t := by rw [inter_comm] exact image2_inter_union_subset_union.trans (union_subset (image2_comm hf).subset Subset.rfl) theorem image2_union_inter_subset {f : α → α → β} {s t : Set α} (hf : ∀ a b, f a b = f b a) : image2 f (s ∪ t) (s ∩ t) ⊆ image2 f s t := by rw [image2_comm hf] exact image2_inter_union_subset hf end Set
Data\Set\Notation.lean
/- Copyright (c) 2024 Peter Nelson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Peter Nelson -/ import Mathlib.Mathport.Notation import Mathlib.Lean.Expr.ExtraRecognizers /-! # Set Notation This file defines two pieces of scoped notation related to sets and subtypes. The first is a coercion; for each `α : Type*` and `s : Set α`, `(↑) : Set s → Set α` is the function coercing `t : Set s` into a set in the ambient type; i.e. `↑t = Subtype.val '' t`. The second, for `s t : Set α`, is the notation `s ↓∩ t`, which denotes the intersection of `s` and `t` as a set in `Set s`. These notations are developed further in `Data.Set.Functor` and `Data.Set.Subset` respectively. They are defined here separately so that this file can be added as an exception to the shake linter and can thus be imported without a linting false positive when only the notation is desired. -/ namespace Set.Notation /-- Given two sets `A` and `B`, `A ↓∩ B` denotes the intersection of `A` and `B` as a set in `Set A`. The notation is short for `((↑) ⁻¹' B : Set A)`, while giving hints to the elaborator that both `A` and `B` are terms of `Set α` for the same `α`. This set is the same as `{x : ↑A | ↑x ∈ B}`. -/ scoped notation3 A:67 " ↓∩ " B:67 => (Subtype.val ⁻¹' (B : type_of% A) : Set (A : Set _)) /-- Coercion using `(Subtype.val '' ·)` -/ instance {α : Type*} {s : Set α} : CoeHead (Set s) (Set α) := ⟨fun t => (Subtype.val '' t)⟩ open Lean PrettyPrinter Delaborator SubExpr in /-- If the `Set.Notation` namespace is open, sets of a subtype coerced to the ambient type are represented with `↑`. -/ @[scoped delab app.Set.image] def delab_set_image_subtype : Delab := whenPPOption getPPCoercions do let #[α, _, f, _] := (← getExpr).getAppArgs | failure guard <| f.isAppOfArity ``Subtype.val 2 let some _ := α.coeTypeSet? | failure let e ← withAppArg delab `(↑$e) end Set.Notation
Data\Set\Opposite.lean
/- Copyright (c) 2022 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import Mathlib.Data.Opposite import Mathlib.Data.Set.Defs /-! # The opposite of a set The opposite of a set `s` is simply the set obtained by taking the opposite of each member of `s`. -/ variable {α : Type*} open Opposite namespace Set /-- The opposite of a set `s` is the set obtained by taking the opposite of each member of `s`. -/ protected def op (s : Set α) : Set αᵒᵖ := unop ⁻¹' s /-- The unop of a set `s` is the set obtained by taking the unop of each member of `s`. -/ protected def unop (s : Set αᵒᵖ) : Set α := op ⁻¹' s @[simp] theorem mem_op {s : Set α} {a : αᵒᵖ} : a ∈ s.op ↔ unop a ∈ s := Iff.rfl @[simp 1100] theorem op_mem_op {s : Set α} {a : α} : op a ∈ s.op ↔ a ∈ s := by rfl @[simp] theorem mem_unop {s : Set αᵒᵖ} {a : α} : a ∈ s.unop ↔ op a ∈ s := Iff.rfl @[simp 1100] theorem unop_mem_unop {s : Set αᵒᵖ} {a : αᵒᵖ} : unop a ∈ s.unop ↔ a ∈ s := by rfl @[simp] theorem op_unop (s : Set α) : s.op.unop = s := rfl @[simp] theorem unop_op (s : Set αᵒᵖ) : s.unop.op = s := rfl /-- The members of the opposite of a set are in bijection with the members of the set itself. -/ @[simps] def opEquiv_self (s : Set α) : s.op ≃ s := ⟨fun x ↦ ⟨unop x, x.2⟩, fun x ↦ ⟨op x, x.2⟩, fun _ ↦ rfl, fun _ ↦ rfl⟩ /-- Taking opposites as an equivalence of powersets. -/ @[simps] def opEquiv : Set α ≃ Set αᵒᵖ := ⟨Set.op, Set.unop, op_unop, unop_op⟩ @[simp] theorem singleton_op (x : α) : ({x} : Set α).op = {op x} := by ext constructor · apply unop_injective · apply op_injective @[simp] theorem singleton_unop (x : αᵒᵖ) : ({x} : Set αᵒᵖ).unop = {unop x} := by ext constructor · apply op_injective · apply unop_injective @[simp 1100] theorem singleton_op_unop (x : α) : ({op x} : Set αᵒᵖ).unop = {x} := by ext constructor · apply op_injective · apply unop_injective @[simp 1100] theorem singleton_unop_op (x : αᵒᵖ) : ({unop x} : Set α).op = {x} := by ext constructor · apply unop_injective · apply op_injective end Set
Data\Set\Prod.lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Johannes Hölzl, Patrick Massot -/ import Mathlib.Data.Set.Image import Mathlib.Data.SProd /-! # Sets in product and pi types This file defines the product of sets in `α × β` and in `Π i, α i` along with the diagonal of a type. ## Main declarations * `Set.prod`: Binary product of sets. For `s : Set α`, `t : Set β`, we have `s.prod t : Set (α × β)`. * `Set.diagonal`: Diagonal of a type. `Set.diagonal α = {(x, x) | x : α}`. * `Set.offDiag`: Off-diagonal. `s ×ˢ s` without the diagonal. * `Set.pi`: Arbitrary product of sets. -/ open Function namespace Set /-! ### Cartesian binary product of sets -/ section Prod variable {α β γ δ : Type*} {s s₁ s₂ : Set α} {t t₁ t₂ : Set β} {a : α} {b : β} theorem Subsingleton.prod (hs : s.Subsingleton) (ht : t.Subsingleton) : (s ×ˢ t).Subsingleton := fun _x hx _y hy ↦ Prod.ext (hs hx.1 hy.1) (ht hx.2 hy.2) noncomputable instance decidableMemProd [DecidablePred (· ∈ s)] [DecidablePred (· ∈ t)] : DecidablePred (· ∈ s ×ˢ t) := fun _ => And.decidable @[gcongr] theorem prod_mono (hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) : s₁ ×ˢ t₁ ⊆ s₂ ×ˢ t₂ := fun _ ⟨h₁, h₂⟩ => ⟨hs h₁, ht h₂⟩ @[gcongr] theorem prod_mono_left (hs : s₁ ⊆ s₂) : s₁ ×ˢ t ⊆ s₂ ×ˢ t := prod_mono hs Subset.rfl @[gcongr] theorem prod_mono_right (ht : t₁ ⊆ t₂) : s ×ˢ t₁ ⊆ s ×ˢ t₂ := prod_mono Subset.rfl ht @[simp] theorem prod_self_subset_prod_self : s₁ ×ˢ s₁ ⊆ s₂ ×ˢ s₂ ↔ s₁ ⊆ s₂ := ⟨fun h _ hx => (h (mk_mem_prod hx hx)).1, fun h _ hx => ⟨h hx.1, h hx.2⟩⟩ @[simp] theorem prod_self_ssubset_prod_self : s₁ ×ˢ s₁ ⊂ s₂ ×ˢ s₂ ↔ s₁ ⊂ s₂ := and_congr prod_self_subset_prod_self <| not_congr prod_self_subset_prod_self theorem prod_subset_iff {P : Set (α × β)} : s ×ˢ t ⊆ P ↔ ∀ x ∈ s, ∀ y ∈ t, (x, y) ∈ P := ⟨fun h _ hx _ hy => h (mk_mem_prod hx hy), fun h ⟨_, _⟩ hp => h _ hp.1 _ hp.2⟩ theorem forall_prod_set {p : α × β → Prop} : (∀ x ∈ s ×ˢ t, p x) ↔ ∀ x ∈ s, ∀ y ∈ t, p (x, y) := prod_subset_iff theorem exists_prod_set {p : α × β → Prop} : (∃ x ∈ s ×ˢ t, p x) ↔ ∃ x ∈ s, ∃ y ∈ t, p (x, y) := by simp [and_assoc] @[simp] theorem prod_empty : s ×ˢ (∅ : Set β) = ∅ := by ext exact and_false_iff _ @[simp] theorem empty_prod : (∅ : Set α) ×ˢ t = ∅ := by ext exact false_and_iff _ @[simp, mfld_simps] theorem univ_prod_univ : @univ α ×ˢ @univ β = univ := by ext exact true_and_iff _ theorem univ_prod {t : Set β} : (univ : Set α) ×ˢ t = Prod.snd ⁻¹' t := by simp [prod_eq] theorem prod_univ {s : Set α} : s ×ˢ (univ : Set β) = Prod.fst ⁻¹' s := by simp [prod_eq] @[simp] lemma prod_eq_univ [Nonempty α] [Nonempty β] : s ×ˢ t = univ ↔ s = univ ∧ t = univ := by simp [eq_univ_iff_forall, forall_and] @[simp] theorem singleton_prod : ({a} : Set α) ×ˢ t = Prod.mk a '' t := by ext ⟨x, y⟩ simp [and_left_comm, eq_comm] @[simp] theorem prod_singleton : s ×ˢ ({b} : Set β) = (fun a => (a, b)) '' s := by ext ⟨x, y⟩ simp [and_left_comm, eq_comm] theorem singleton_prod_singleton : ({a} : Set α) ×ˢ ({b} : Set β) = {(a, b)} := by simp @[simp] theorem union_prod : (s₁ ∪ s₂) ×ˢ t = s₁ ×ˢ t ∪ s₂ ×ˢ t := by ext ⟨x, y⟩ simp [or_and_right] @[simp] theorem prod_union : s ×ˢ (t₁ ∪ t₂) = s ×ˢ t₁ ∪ s ×ˢ t₂ := by ext ⟨x, y⟩ simp [and_or_left] theorem inter_prod : (s₁ ∩ s₂) ×ˢ t = s₁ ×ˢ t ∩ s₂ ×ˢ t := by ext ⟨x, y⟩ simp only [← and_and_right, mem_inter_iff, mem_prod] theorem prod_inter : s ×ˢ (t₁ ∩ t₂) = s ×ˢ t₁ ∩ s ×ˢ t₂ := by ext ⟨x, y⟩ simp only [← and_and_left, mem_inter_iff, mem_prod] @[mfld_simps] theorem prod_inter_prod : s₁ ×ˢ t₁ ∩ s₂ ×ˢ t₂ = (s₁ ∩ s₂) ×ˢ (t₁ ∩ t₂) := by ext ⟨x, y⟩ simp [and_assoc, and_left_comm] lemma compl_prod_eq_union {α β : Type*} (s : Set α) (t : Set β) : (s ×ˢ t)ᶜ = (sᶜ ×ˢ univ) ∪ (univ ×ˢ tᶜ) := by ext p simp only [mem_compl_iff, mem_prod, not_and, mem_union, mem_univ, and_true, true_and] constructor <;> intro h · by_cases fst_in_s : p.fst ∈ s · exact Or.inr (h fst_in_s) · exact Or.inl fst_in_s · intro fst_in_s simpa only [fst_in_s, not_true, false_or] using h @[simp] theorem disjoint_prod : Disjoint (s₁ ×ˢ t₁) (s₂ ×ˢ t₂) ↔ Disjoint s₁ s₂ ∨ Disjoint t₁ t₂ := by simp_rw [disjoint_left, mem_prod, not_and_or, Prod.forall, and_imp, ← @forall_or_right α, ← @forall_or_left β, ← @forall_or_right (_ ∈ s₁), ← @forall_or_left (_ ∈ t₁)] theorem Disjoint.set_prod_left (hs : Disjoint s₁ s₂) (t₁ t₂ : Set β) : Disjoint (s₁ ×ˢ t₁) (s₂ ×ˢ t₂) := disjoint_left.2 fun ⟨_a, _b⟩ ⟨ha₁, _⟩ ⟨ha₂, _⟩ => disjoint_left.1 hs ha₁ ha₂ theorem Disjoint.set_prod_right (ht : Disjoint t₁ t₂) (s₁ s₂ : Set α) : Disjoint (s₁ ×ˢ t₁) (s₂ ×ˢ t₂) := disjoint_left.2 fun ⟨_a, _b⟩ ⟨_, hb₁⟩ ⟨_, hb₂⟩ => disjoint_left.1 ht hb₁ hb₂ theorem insert_prod : insert a s ×ˢ t = Prod.mk a '' t ∪ s ×ˢ t := by ext ⟨x, y⟩ simp (config := { contextual := true }) [image, iff_def, or_imp] theorem prod_insert : s ×ˢ insert b t = (fun a => (a, b)) '' s ∪ s ×ˢ t := by ext ⟨x, y⟩ -- porting note (#10745): -- was `simp (config := { contextual := true }) [image, iff_def, or_imp, Imp.swap]` simp only [mem_prod, mem_insert_iff, image, mem_union, mem_setOf_eq, Prod.mk.injEq] refine ⟨fun h => ?_, fun h => ?_⟩ · obtain ⟨hx, rfl|hy⟩ := h · exact Or.inl ⟨x, hx, rfl, rfl⟩ · exact Or.inr ⟨hx, hy⟩ · obtain ⟨x, hx, rfl, rfl⟩|⟨hx, hy⟩ := h · exact ⟨hx, Or.inl rfl⟩ · exact ⟨hx, Or.inr hy⟩ theorem prod_preimage_eq {f : γ → α} {g : δ → β} : (f ⁻¹' s) ×ˢ (g ⁻¹' t) = (fun p : γ × δ => (f p.1, g p.2)) ⁻¹' s ×ˢ t := rfl theorem prod_preimage_left {f : γ → α} : (f ⁻¹' s) ×ˢ t = (fun p : γ × β => (f p.1, p.2)) ⁻¹' s ×ˢ t := rfl theorem prod_preimage_right {g : δ → β} : s ×ˢ (g ⁻¹' t) = (fun p : α × δ => (p.1, g p.2)) ⁻¹' s ×ˢ t := rfl theorem preimage_prod_map_prod (f : α → β) (g : γ → δ) (s : Set β) (t : Set δ) : Prod.map f g ⁻¹' s ×ˢ t = (f ⁻¹' s) ×ˢ (g ⁻¹' t) := rfl theorem mk_preimage_prod (f : γ → α) (g : γ → β) : (fun x => (f x, g x)) ⁻¹' s ×ˢ t = f ⁻¹' s ∩ g ⁻¹' t := rfl @[simp] theorem mk_preimage_prod_left (hb : b ∈ t) : (fun a => (a, b)) ⁻¹' s ×ˢ t = s := by ext a simp [hb] @[simp] theorem mk_preimage_prod_right (ha : a ∈ s) : Prod.mk a ⁻¹' s ×ˢ t = t := by ext b simp [ha] @[simp] theorem mk_preimage_prod_left_eq_empty (hb : b ∉ t) : (fun a => (a, b)) ⁻¹' s ×ˢ t = ∅ := by ext a simp [hb] @[simp] theorem mk_preimage_prod_right_eq_empty (ha : a ∉ s) : Prod.mk a ⁻¹' s ×ˢ t = ∅ := by ext b simp [ha] theorem mk_preimage_prod_left_eq_if [DecidablePred (· ∈ t)] : (fun a => (a, b)) ⁻¹' s ×ˢ t = if b ∈ t then s else ∅ := by split_ifs with h <;> simp [h] theorem mk_preimage_prod_right_eq_if [DecidablePred (· ∈ s)] : Prod.mk a ⁻¹' s ×ˢ t = if a ∈ s then t else ∅ := by split_ifs with h <;> simp [h] theorem mk_preimage_prod_left_fn_eq_if [DecidablePred (· ∈ t)] (f : γ → α) : (fun a => (f a, b)) ⁻¹' s ×ˢ t = if b ∈ t then f ⁻¹' s else ∅ := by rw [← mk_preimage_prod_left_eq_if, prod_preimage_left, preimage_preimage] theorem mk_preimage_prod_right_fn_eq_if [DecidablePred (· ∈ s)] (g : δ → β) : (fun b => (a, g b)) ⁻¹' s ×ˢ t = if a ∈ s then g ⁻¹' t else ∅ := by rw [← mk_preimage_prod_right_eq_if, prod_preimage_right, preimage_preimage] @[simp] theorem preimage_swap_prod (s : Set α) (t : Set β) : Prod.swap ⁻¹' s ×ˢ t = t ×ˢ s := by ext ⟨x, y⟩ simp [and_comm] @[simp] theorem image_swap_prod (s : Set α) (t : Set β) : Prod.swap '' s ×ˢ t = t ×ˢ s := by rw [image_swap_eq_preimage_swap, preimage_swap_prod] theorem prod_image_image_eq {m₁ : α → γ} {m₂ : β → δ} : (m₁ '' s) ×ˢ (m₂ '' t) = (fun p : α × β => (m₁ p.1, m₂ p.2)) '' s ×ˢ t := ext <| by simp [-exists_and_right, exists_and_right.symm, and_left_comm, and_assoc, and_comm] theorem prod_range_range_eq {m₁ : α → γ} {m₂ : β → δ} : range m₁ ×ˢ range m₂ = range fun p : α × β => (m₁ p.1, m₂ p.2) := ext <| by simp [range] @[simp, mfld_simps] theorem range_prod_map {m₁ : α → γ} {m₂ : β → δ} : range (Prod.map m₁ m₂) = range m₁ ×ˢ range m₂ := prod_range_range_eq.symm theorem prod_range_univ_eq {m₁ : α → γ} : range m₁ ×ˢ (univ : Set β) = range fun p : α × β => (m₁ p.1, p.2) := ext <| by simp [range] theorem prod_univ_range_eq {m₂ : β → δ} : (univ : Set α) ×ˢ range m₂ = range fun p : α × β => (p.1, m₂ p.2) := ext <| by simp [range] theorem range_pair_subset (f : α → β) (g : α → γ) : (range fun x => (f x, g x)) ⊆ range f ×ˢ range g := by have : (fun x => (f x, g x)) = Prod.map f g ∘ fun x => (x, x) := funext fun x => rfl rw [this, ← range_prod_map] apply range_comp_subset_range theorem Nonempty.prod : s.Nonempty → t.Nonempty → (s ×ˢ t).Nonempty := fun ⟨x, hx⟩ ⟨y, hy⟩ => ⟨(x, y), ⟨hx, hy⟩⟩ theorem Nonempty.fst : (s ×ˢ t).Nonempty → s.Nonempty := fun ⟨x, hx⟩ => ⟨x.1, hx.1⟩ theorem Nonempty.snd : (s ×ˢ t).Nonempty → t.Nonempty := fun ⟨x, hx⟩ => ⟨x.2, hx.2⟩ @[simp] theorem prod_nonempty_iff : (s ×ˢ t).Nonempty ↔ s.Nonempty ∧ t.Nonempty := ⟨fun h => ⟨h.fst, h.snd⟩, fun h => h.1.prod h.2⟩ @[simp] theorem prod_eq_empty_iff : s ×ˢ t = ∅ ↔ s = ∅ ∨ t = ∅ := by simp only [not_nonempty_iff_eq_empty.symm, prod_nonempty_iff, not_and_or] theorem prod_sub_preimage_iff {W : Set γ} {f : α × β → γ} : s ×ˢ t ⊆ f ⁻¹' W ↔ ∀ a b, a ∈ s → b ∈ t → f (a, b) ∈ W := by simp [subset_def] theorem image_prod_mk_subset_prod {f : α → β} {g : α → γ} {s : Set α} : (fun x => (f x, g x)) '' s ⊆ (f '' s) ×ˢ (g '' s) := by rintro _ ⟨x, hx, rfl⟩ exact mk_mem_prod (mem_image_of_mem f hx) (mem_image_of_mem g hx) theorem image_prod_mk_subset_prod_left (hb : b ∈ t) : (fun a => (a, b)) '' s ⊆ s ×ˢ t := by rintro _ ⟨a, ha, rfl⟩ exact ⟨ha, hb⟩ theorem image_prod_mk_subset_prod_right (ha : a ∈ s) : Prod.mk a '' t ⊆ s ×ˢ t := by rintro _ ⟨b, hb, rfl⟩ exact ⟨ha, hb⟩ theorem prod_subset_preimage_fst (s : Set α) (t : Set β) : s ×ˢ t ⊆ Prod.fst ⁻¹' s := inter_subset_left theorem fst_image_prod_subset (s : Set α) (t : Set β) : Prod.fst '' s ×ˢ t ⊆ s := image_subset_iff.2 <| prod_subset_preimage_fst s t theorem fst_image_prod (s : Set β) {t : Set α} (ht : t.Nonempty) : Prod.fst '' s ×ˢ t = s := (fst_image_prod_subset _ _).antisymm fun y hy => let ⟨x, hx⟩ := ht ⟨(y, x), ⟨hy, hx⟩, rfl⟩ theorem prod_subset_preimage_snd (s : Set α) (t : Set β) : s ×ˢ t ⊆ Prod.snd ⁻¹' t := inter_subset_right theorem snd_image_prod_subset (s : Set α) (t : Set β) : Prod.snd '' s ×ˢ t ⊆ t := image_subset_iff.2 <| prod_subset_preimage_snd s t theorem snd_image_prod {s : Set α} (hs : s.Nonempty) (t : Set β) : Prod.snd '' s ×ˢ t = t := (snd_image_prod_subset _ _).antisymm fun y y_in => let ⟨x, x_in⟩ := hs ⟨(x, y), ⟨x_in, y_in⟩, rfl⟩ theorem prod_diff_prod : s ×ˢ t \ s₁ ×ˢ t₁ = s ×ˢ (t \ t₁) ∪ (s \ s₁) ×ˢ t := by ext x by_cases h₁ : x.1 ∈ s₁ <;> by_cases h₂ : x.2 ∈ t₁ <;> simp [*] /-- A product set is included in a product set if and only factors are included, or a factor of the first set is empty. -/ theorem prod_subset_prod_iff : s ×ˢ t ⊆ s₁ ×ˢ t₁ ↔ s ⊆ s₁ ∧ t ⊆ t₁ ∨ s = ∅ ∨ t = ∅ := by rcases (s ×ˢ t).eq_empty_or_nonempty with h | h · simp [h, prod_eq_empty_iff.1 h] have st : s.Nonempty ∧ t.Nonempty := by rwa [prod_nonempty_iff] at h refine ⟨fun H => Or.inl ⟨?_, ?_⟩, ?_⟩ · have := image_subset (Prod.fst : α × β → α) H rwa [fst_image_prod _ st.2, fst_image_prod _ (h.mono H).snd] at this · have := image_subset (Prod.snd : α × β → β) H rwa [snd_image_prod st.1, snd_image_prod (h.mono H).fst] at this · intro H simp only [st.1.ne_empty, st.2.ne_empty, or_false_iff] at H exact prod_mono H.1 H.2 theorem prod_eq_prod_iff_of_nonempty (h : (s ×ˢ t).Nonempty) : s ×ˢ t = s₁ ×ˢ t₁ ↔ s = s₁ ∧ t = t₁ := by constructor · intro heq have h₁ : (s₁ ×ˢ t₁ : Set _).Nonempty := by rwa [← heq] rw [prod_nonempty_iff] at h h₁ rw [← fst_image_prod s h.2, ← fst_image_prod s₁ h₁.2, heq, eq_self_iff_true, true_and_iff, ← snd_image_prod h.1 t, ← snd_image_prod h₁.1 t₁, heq] · rintro ⟨rfl, rfl⟩ rfl theorem prod_eq_prod_iff : s ×ˢ t = s₁ ×ˢ t₁ ↔ s = s₁ ∧ t = t₁ ∨ (s = ∅ ∨ t = ∅) ∧ (s₁ = ∅ ∨ t₁ = ∅) := by symm rcases eq_empty_or_nonempty (s ×ˢ t) with h | h · simp_rw [h, @eq_comm _ ∅, prod_eq_empty_iff, prod_eq_empty_iff.mp h, true_and_iff, or_iff_right_iff_imp] rintro ⟨rfl, rfl⟩ exact prod_eq_empty_iff.mp h rw [prod_eq_prod_iff_of_nonempty h] rw [nonempty_iff_ne_empty, Ne, prod_eq_empty_iff] at h simp_rw [h, false_and_iff, or_false_iff] @[simp] theorem prod_eq_iff_eq (ht : t.Nonempty) : s ×ˢ t = s₁ ×ˢ t ↔ s = s₁ := by simp_rw [prod_eq_prod_iff, ht.ne_empty, and_true_iff, or_iff_left_iff_imp, or_false_iff] rintro ⟨rfl, rfl⟩ rfl section Mono variable [Preorder α] {f : α → Set β} {g : α → Set γ} theorem _root_.Monotone.set_prod (hf : Monotone f) (hg : Monotone g) : Monotone fun x => f x ×ˢ g x := fun _ _ h => prod_mono (hf h) (hg h) theorem _root_.Antitone.set_prod (hf : Antitone f) (hg : Antitone g) : Antitone fun x => f x ×ˢ g x := fun _ _ h => prod_mono (hf h) (hg h) theorem _root_.MonotoneOn.set_prod (hf : MonotoneOn f s) (hg : MonotoneOn g s) : MonotoneOn (fun x => f x ×ˢ g x) s := fun _ ha _ hb h => prod_mono (hf ha hb h) (hg ha hb h) theorem _root_.AntitoneOn.set_prod (hf : AntitoneOn f s) (hg : AntitoneOn g s) : AntitoneOn (fun x => f x ×ˢ g x) s := fun _ ha _ hb h => prod_mono (hf ha hb h) (hg ha hb h) end Mono end Prod /-! ### Diagonal In this section we prove some lemmas about the diagonal set `{p | p.1 = p.2}` and the diagonal map `fun x ↦ (x, x)`. -/ section Diagonal variable {α : Type*} {s t : Set α} lemma diagonal_nonempty [Nonempty α] : (diagonal α).Nonempty := Nonempty.elim ‹_› fun x => ⟨_, mem_diagonal x⟩ instance decidableMemDiagonal [h : DecidableEq α] (x : α × α) : Decidable (x ∈ diagonal α) := h x.1 x.2 theorem preimage_coe_coe_diagonal (s : Set α) : Prod.map (fun x : s => (x : α)) (fun x : s => (x : α)) ⁻¹' diagonal α = diagonal s := by ext ⟨⟨x, hx⟩, ⟨y, hy⟩⟩ simp [Set.diagonal] @[simp] theorem range_diag : (range fun x => (x, x)) = diagonal α := by ext ⟨x, y⟩ simp [diagonal, eq_comm] theorem diagonal_subset_iff {s} : diagonal α ⊆ s ↔ ∀ x, (x, x) ∈ s := by rw [← range_diag, range_subset_iff] @[simp] theorem prod_subset_compl_diagonal_iff_disjoint : s ×ˢ t ⊆ (diagonal α)ᶜ ↔ Disjoint s t := prod_subset_iff.trans disjoint_iff_forall_ne.symm @[simp] theorem diag_preimage_prod (s t : Set α) : (fun x => (x, x)) ⁻¹' s ×ˢ t = s ∩ t := rfl theorem diag_preimage_prod_self (s : Set α) : (fun x => (x, x)) ⁻¹' s ×ˢ s = s := inter_self s theorem diag_image (s : Set α) : (fun x => (x, x)) '' s = diagonal α ∩ s ×ˢ s := by rw [← range_diag, ← image_preimage_eq_range_inter, diag_preimage_prod_self] theorem diagonal_eq_univ_iff : diagonal α = univ ↔ Subsingleton α := by simp only [subsingleton_iff, eq_univ_iff_forall, Prod.forall, mem_diagonal_iff] theorem diagonal_eq_univ [Subsingleton α] : diagonal α = univ := diagonal_eq_univ_iff.2 ‹_› end Diagonal /-- A function is `Function.const α a` for some `a` if and only if `∀ x y, f x = f y`. -/ theorem range_const_eq_diagonal {α β : Type*} [hβ : Nonempty β] : range (const α) = {f : α → β | ∀ x y, f x = f y} := by refine (range_eq_iff _ _).mpr ⟨fun _ _ _ ↦ rfl, fun f hf ↦ ?_⟩ rcases isEmpty_or_nonempty α with h|⟨⟨a⟩⟩ · exact hβ.elim fun b ↦ ⟨b, Subsingleton.elim _ _⟩ · exact ⟨f a, funext fun x ↦ hf _ _⟩ end Set section Pullback open Set variable {X Y Z} /-- The fiber product $X \times_Y Z$. -/ abbrev Function.Pullback (f : X → Y) (g : Z → Y) := {p : X × Z // f p.1 = g p.2} /-- The fiber product $X \times_Y X$. -/ abbrev Function.PullbackSelf (f : X → Y) := f.Pullback f /-- The projection from the fiber product to the first factor. -/ def Function.Pullback.fst {f : X → Y} {g : Z → Y} (p : f.Pullback g) : X := p.val.1 /-- The projection from the fiber product to the second factor. -/ def Function.Pullback.snd {f : X → Y} {g : Z → Y} (p : f.Pullback g) : Z := p.val.2 open Function.Pullback in lemma Function.pullback_comm_sq (f : X → Y) (g : Z → Y) : f ∘ @fst X Y Z f g = g ∘ @snd X Y Z f g := funext fun p ↦ p.2 /-- The diagonal map $\Delta: X \to X \times_Y X$. -/ def toPullbackDiag (f : X → Y) (x : X) : f.Pullback f := ⟨(x, x), rfl⟩ /-- The diagonal $\Delta(X) \subseteq X \times_Y X$. -/ def Function.pullbackDiagonal (f : X → Y) : Set (f.Pullback f) := {p | p.fst = p.snd} /-- Three functions between the three pairs of spaces $X_i, Y_i, Z_i$ that are compatible induce a function $X_1 \times_{Y_1} Z_1 \to X_2 \times_{Y_2} Z_2$. -/ def Function.mapPullback {X₁ X₂ Y₁ Y₂ Z₁ Z₂} {f₁ : X₁ → Y₁} {g₁ : Z₁ → Y₁} {f₂ : X₂ → Y₂} {g₂ : Z₂ → Y₂} (mapX : X₁ → X₂) (mapY : Y₁ → Y₂) (mapZ : Z₁ → Z₂) (commX : f₂ ∘ mapX = mapY ∘ f₁) (commZ : g₂ ∘ mapZ = mapY ∘ g₁) (p : f₁.Pullback g₁) : f₂.Pullback g₂ := ⟨(mapX p.fst, mapZ p.snd), (congr_fun commX _).trans <| (congr_arg mapY p.2).trans <| congr_fun commZ.symm _⟩ open Function.Pullback in /-- The projection $(X \times_Y Z) \times_Z (X \times_Y Z) \to X \times_Y X$. -/ def Function.PullbackSelf.map_fst {f : X → Y} {g : Z → Y} : (@snd X Y Z f g).PullbackSelf → f.PullbackSelf := mapPullback fst g fst (pullback_comm_sq f g) (pullback_comm_sq f g) open Function.Pullback in /-- The projection $(X \times_Y Z) \times_X (X \times_Y Z) \to Z \times_Y Z$. -/ def Function.PullbackSelf.map_snd {f : X → Y} {g : Z → Y} : (@fst X Y Z f g).PullbackSelf → g.PullbackSelf := mapPullback snd f snd (pullback_comm_sq f g).symm (pullback_comm_sq f g).symm open Function.PullbackSelf Function.Pullback theorem preimage_map_fst_pullbackDiagonal {f : X → Y} {g : Z → Y} : @map_fst X Y Z f g ⁻¹' pullbackDiagonal f = pullbackDiagonal (@snd X Y Z f g) := by ext ⟨⟨p₁, p₂⟩, he⟩ simp_rw [pullbackDiagonal, mem_setOf, Subtype.ext_iff, Prod.ext_iff] exact (and_iff_left he).symm theorem Function.Injective.preimage_pullbackDiagonal {f : X → Y} {g : Z → X} (inj : g.Injective) : mapPullback g id g (by rfl) (by rfl) ⁻¹' pullbackDiagonal f = pullbackDiagonal (f ∘ g) := ext fun _ ↦ inj.eq_iff theorem image_toPullbackDiag (f : X → Y) (s : Set X) : toPullbackDiag f '' s = pullbackDiagonal f ∩ Subtype.val ⁻¹' s ×ˢ s := by ext x constructor · rintro ⟨x, hx, rfl⟩ exact ⟨rfl, hx, hx⟩ · obtain ⟨⟨x, y⟩, h⟩ := x rintro ⟨rfl : x = y, h2x⟩ exact mem_image_of_mem _ h2x.1 theorem range_toPullbackDiag (f : X → Y) : range (toPullbackDiag f) = pullbackDiagonal f := by rw [← image_univ, image_toPullbackDiag, univ_prod_univ, preimage_univ, inter_univ] theorem injective_toPullbackDiag (f : X → Y) : (toPullbackDiag f).Injective := fun _ _ h ↦ congr_arg Prod.fst (congr_arg Subtype.val h) end Pullback namespace Set section OffDiag variable {α : Type*} {s t : Set α} {x : α × α} {a : α} theorem offDiag_mono : Monotone (offDiag : Set α → Set (α × α)) := fun _ _ h _ => And.imp (@h _) <| And.imp_left <| @h _ @[simp] theorem offDiag_nonempty : s.offDiag.Nonempty ↔ s.Nontrivial := by simp [offDiag, Set.Nonempty, Set.Nontrivial] @[simp] theorem offDiag_eq_empty : s.offDiag = ∅ ↔ s.Subsingleton := by rw [← not_nonempty_iff_eq_empty, ← not_nontrivial_iff, offDiag_nonempty.not] alias ⟨_, Nontrivial.offDiag_nonempty⟩ := offDiag_nonempty alias ⟨_, Subsingleton.offDiag_eq_empty⟩ := offDiag_nonempty variable (s t) theorem offDiag_subset_prod : s.offDiag ⊆ s ×ˢ s := fun _ hx => ⟨hx.1, hx.2.1⟩ theorem offDiag_eq_sep_prod : s.offDiag = { x ∈ s ×ˢ s | x.1 ≠ x.2 } := ext fun _ => and_assoc.symm @[simp] theorem offDiag_empty : (∅ : Set α).offDiag = ∅ := by simp @[simp] theorem offDiag_singleton (a : α) : ({a} : Set α).offDiag = ∅ := by simp @[simp] theorem offDiag_univ : (univ : Set α).offDiag = (diagonal α)ᶜ := ext <| by simp @[simp] theorem prod_sdiff_diagonal : s ×ˢ s \ diagonal α = s.offDiag := ext fun _ => and_assoc @[simp] theorem disjoint_diagonal_offDiag : Disjoint (diagonal α) s.offDiag := disjoint_left.mpr fun _ hd ho => ho.2.2 hd theorem offDiag_inter : (s ∩ t).offDiag = s.offDiag ∩ t.offDiag := ext fun x => by simp only [mem_offDiag, mem_inter_iff] tauto variable {s t} theorem offDiag_union (h : Disjoint s t) : (s ∪ t).offDiag = s.offDiag ∪ t.offDiag ∪ s ×ˢ t ∪ t ×ˢ s := by ext x simp only [mem_offDiag, mem_union, ne_eq, mem_prod] constructor · rintro ⟨h0|h0, h1|h1, h2⟩ <;> simp [h0, h1, h2] · rintro (((⟨h0, h1, h2⟩|⟨h0, h1, h2⟩)|⟨h0, h1⟩)|⟨h0, h1⟩) <;> simp [*] · rintro h3 rw [h3] at h0 exact Set.disjoint_left.mp h h0 h1 · rintro h3 rw [h3] at h0 exact (Set.disjoint_right.mp h h0 h1).elim theorem offDiag_insert (ha : a ∉ s) : (insert a s).offDiag = s.offDiag ∪ {a} ×ˢ s ∪ s ×ˢ {a} := by rw [insert_eq, union_comm, offDiag_union, offDiag_singleton, union_empty, union_right_comm] rw [disjoint_left] rintro b hb (rfl : b = a) exact ha hb end OffDiag /-! ### Cartesian set-indexed product of sets -/ section Pi variable {ι : Type*} {α β : ι → Type*} {s s₁ s₂ : Set ι} {t t₁ t₂ : ∀ i, Set (α i)} {i : ι} @[simp] theorem empty_pi (s : ∀ i, Set (α i)) : pi ∅ s = univ := by ext simp [pi] theorem subsingleton_univ_pi (ht : ∀ i, (t i).Subsingleton) : (univ.pi t).Subsingleton := fun _f hf _g hg ↦ funext fun i ↦ (ht i) (hf _ <| mem_univ _) (hg _ <| mem_univ _) @[simp] theorem pi_univ (s : Set ι) : (pi s fun i => (univ : Set (α i))) = univ := eq_univ_of_forall fun _ _ _ => mem_univ _ @[simp] theorem pi_univ_ite (s : Set ι) [DecidablePred (· ∈ s)] (t : ∀ i, Set (α i)) : (pi univ fun i => if i ∈ s then t i else univ) = s.pi t := by ext; simp_rw [Set.mem_pi]; apply forall_congr'; intro i; split_ifs with h <;> simp [h] theorem pi_mono (h : ∀ i ∈ s, t₁ i ⊆ t₂ i) : pi s t₁ ⊆ pi s t₂ := fun _ hx i hi => h i hi <| hx i hi theorem pi_inter_distrib : (s.pi fun i => t i ∩ t₁ i) = s.pi t ∩ s.pi t₁ := ext fun x => by simp only [forall_and, mem_pi, mem_inter_iff] theorem pi_congr (h : s₁ = s₂) (h' : ∀ i ∈ s₁, t₁ i = t₂ i) : s₁.pi t₁ = s₂.pi t₂ := h ▸ ext fun _ => forall₂_congr fun i hi => h' i hi ▸ Iff.rfl theorem pi_eq_empty (hs : i ∈ s) (ht : t i = ∅) : s.pi t = ∅ := by ext f simp only [mem_empty_iff_false, not_forall, iff_false_iff, mem_pi, Classical.not_imp] exact ⟨i, hs, by simp [ht]⟩ theorem univ_pi_eq_empty (ht : t i = ∅) : pi univ t = ∅ := pi_eq_empty (mem_univ i) ht theorem pi_nonempty_iff : (s.pi t).Nonempty ↔ ∀ i, ∃ x, i ∈ s → x ∈ t i := by simp [Classical.skolem, Set.Nonempty] theorem univ_pi_nonempty_iff : (pi univ t).Nonempty ↔ ∀ i, (t i).Nonempty := by simp [Classical.skolem, Set.Nonempty] theorem pi_eq_empty_iff : s.pi t = ∅ ↔ ∃ i, IsEmpty (α i) ∨ i ∈ s ∧ t i = ∅ := by rw [← not_nonempty_iff_eq_empty, pi_nonempty_iff] push_neg refine exists_congr fun i => ?_ cases isEmpty_or_nonempty (α i) <;> simp [*, forall_and, eq_empty_iff_forall_not_mem] @[simp] theorem univ_pi_eq_empty_iff : pi univ t = ∅ ↔ ∃ i, t i = ∅ := by simp [← not_nonempty_iff_eq_empty, univ_pi_nonempty_iff] @[simp] theorem univ_pi_empty [h : Nonempty ι] : pi univ (fun _ => ∅ : ∀ i, Set (α i)) = ∅ := univ_pi_eq_empty_iff.2 <| h.elim fun x => ⟨x, rfl⟩ @[simp] theorem disjoint_univ_pi : Disjoint (pi univ t₁) (pi univ t₂) ↔ ∃ i, Disjoint (t₁ i) (t₂ i) := by simp only [disjoint_iff_inter_eq_empty, ← pi_inter_distrib, univ_pi_eq_empty_iff] theorem Disjoint.set_pi (hi : i ∈ s) (ht : Disjoint (t₁ i) (t₂ i)) : Disjoint (s.pi t₁) (s.pi t₂) := disjoint_left.2 fun _ h₁ h₂ => disjoint_left.1 ht (h₁ _ hi) (h₂ _ hi) theorem uniqueElim_preimage [Unique ι] (t : ∀ i, Set (α i)) : uniqueElim ⁻¹' pi univ t = t (default : ι) := by ext; simp [Unique.forall_iff] section Nonempty variable [∀ i, Nonempty (α i)] theorem pi_eq_empty_iff' : s.pi t = ∅ ↔ ∃ i ∈ s, t i = ∅ := by simp [pi_eq_empty_iff] @[simp] theorem disjoint_pi : Disjoint (s.pi t₁) (s.pi t₂) ↔ ∃ i ∈ s, Disjoint (t₁ i) (t₂ i) := by simp only [disjoint_iff_inter_eq_empty, ← pi_inter_distrib, pi_eq_empty_iff'] end Nonempty -- Porting note: Removing `simp` - LHS does not simplify theorem range_dcomp (f : ∀ i, α i → β i) : (range fun g : ∀ i, α i => fun i => f i (g i)) = pi univ fun i => range (f i) := by refine Subset.antisymm ?_ fun x hx => ?_ · rintro _ ⟨x, rfl⟩ i - exact ⟨x i, rfl⟩ · choose y hy using hx exact ⟨fun i => y i trivial, funext fun i => hy i trivial⟩ @[simp] theorem insert_pi (i : ι) (s : Set ι) (t : ∀ i, Set (α i)) : pi (insert i s) t = eval i ⁻¹' t i ∩ pi s t := by ext simp [pi, or_imp, forall_and] @[simp] theorem singleton_pi (i : ι) (t : ∀ i, Set (α i)) : pi {i} t = eval i ⁻¹' t i := by ext simp [pi] theorem singleton_pi' (i : ι) (t : ∀ i, Set (α i)) : pi {i} t = { x | x i ∈ t i } := singleton_pi i t theorem univ_pi_singleton (f : ∀ i, α i) : (pi univ fun i => {f i}) = ({f} : Set (∀ i, α i)) := ext fun g => by simp [funext_iff] theorem preimage_pi (s : Set ι) (t : ∀ i, Set (β i)) (f : ∀ i, α i → β i) : (fun (g : ∀ i, α i) i => f _ (g i)) ⁻¹' s.pi t = s.pi fun i => f i ⁻¹' t i := rfl theorem pi_if {p : ι → Prop} [h : DecidablePred p] (s : Set ι) (t₁ t₂ : ∀ i, Set (α i)) : (pi s fun i => if p i then t₁ i else t₂ i) = pi ({ i ∈ s | p i }) t₁ ∩ pi ({ i ∈ s | ¬p i }) t₂ := by ext f refine ⟨fun h => ?_, ?_⟩ · constructor <;> · rintro i ⟨his, hpi⟩ simpa [*] using h i · rintro ⟨ht₁, ht₂⟩ i his by_cases p i <;> simp_all theorem union_pi : (s₁ ∪ s₂).pi t = s₁.pi t ∩ s₂.pi t := by simp [pi, or_imp, forall_and, setOf_and] theorem union_pi_inter (ht₁ : ∀ i ∉ s₁, t₁ i = univ) (ht₂ : ∀ i ∉ s₂, t₂ i = univ) : (s₁ ∪ s₂).pi (fun i ↦ t₁ i ∩ t₂ i) = s₁.pi t₁ ∩ s₂.pi t₂ := by ext x simp only [mem_pi, mem_union, mem_inter_iff] refine ⟨fun h ↦ ⟨fun i his₁ ↦ (h i (Or.inl his₁)).1, fun i his₂ ↦ (h i (Or.inr his₂)).2⟩, fun h i hi ↦ ?_⟩ cases' hi with hi hi · by_cases hi2 : i ∈ s₂ · exact ⟨h.1 i hi, h.2 i hi2⟩ · refine ⟨h.1 i hi, ?_⟩ rw [ht₂ i hi2] exact mem_univ _ · by_cases hi1 : i ∈ s₁ · exact ⟨h.1 i hi1, h.2 i hi⟩ · refine ⟨?_, h.2 i hi⟩ rw [ht₁ i hi1] exact mem_univ _ @[simp] theorem pi_inter_compl (s : Set ι) : pi s t ∩ pi sᶜ t = pi univ t := by rw [← union_pi, union_compl_self] theorem pi_update_of_not_mem [DecidableEq ι] (hi : i ∉ s) (f : ∀ j, α j) (a : α i) (t : ∀ j, α j → Set (β j)) : (s.pi fun j => t j (update f i a j)) = s.pi fun j => t j (f j) := (pi_congr rfl) fun j hj => by rw [update_noteq] exact fun h => hi (h ▸ hj) theorem pi_update_of_mem [DecidableEq ι] (hi : i ∈ s) (f : ∀ j, α j) (a : α i) (t : ∀ j, α j → Set (β j)) : (s.pi fun j => t j (update f i a j)) = { x | x i ∈ t i a } ∩ (s \ {i}).pi fun j => t j (f j) := calc (s.pi fun j => t j (update f i a j)) = ({i} ∪ s \ {i}).pi fun j => t j (update f i a j) := by rw [union_diff_self, union_eq_self_of_subset_left (singleton_subset_iff.2 hi)] _ = { x | x i ∈ t i a } ∩ (s \ {i}).pi fun j => t j (f j) := by rw [union_pi, singleton_pi', update_same, pi_update_of_not_mem]; simp theorem univ_pi_update [DecidableEq ι] {β : ι → Type*} (i : ι) (f : ∀ j, α j) (a : α i) (t : ∀ j, α j → Set (β j)) : (pi univ fun j => t j (update f i a j)) = { x | x i ∈ t i a } ∩ pi {i}ᶜ fun j => t j (f j) := by rw [compl_eq_univ_diff, ← pi_update_of_mem (mem_univ _)] theorem univ_pi_update_univ [DecidableEq ι] (i : ι) (s : Set (α i)) : pi univ (update (fun j : ι => (univ : Set (α j))) i s) = eval i ⁻¹' s := by rw [univ_pi_update i (fun j => (univ : Set (α j))) s fun j t => t, pi_univ, inter_univ, preimage] theorem eval_image_pi_subset (hs : i ∈ s) : eval i '' s.pi t ⊆ t i := image_subset_iff.2 fun _ hf => hf i hs theorem eval_image_univ_pi_subset : eval i '' pi univ t ⊆ t i := eval_image_pi_subset (mem_univ i) theorem subset_eval_image_pi (ht : (s.pi t).Nonempty) (i : ι) : t i ⊆ eval i '' s.pi t := by classical obtain ⟨f, hf⟩ := ht refine fun y hy => ⟨update f i y, fun j hj => ?_, update_same _ _ _⟩ obtain rfl | hji := eq_or_ne j i <;> simp [*, hf _ hj] theorem eval_image_pi (hs : i ∈ s) (ht : (s.pi t).Nonempty) : eval i '' s.pi t = t i := (eval_image_pi_subset hs).antisymm (subset_eval_image_pi ht i) lemma eval_image_pi_of_not_mem [Decidable (s.pi t).Nonempty] (hi : i ∉ s) : eval i '' s.pi t = if (s.pi t).Nonempty then univ else ∅ := by classical ext xᵢ simp only [eval, mem_image, mem_pi, Set.Nonempty, mem_ite_empty_right, mem_univ, and_true] constructor · rintro ⟨x, hx, rfl⟩ exact ⟨x, hx⟩ · rintro ⟨x, hx⟩ refine ⟨Function.update x i xᵢ, ?_⟩ simpa (config := { contextual := true }) [(ne_of_mem_of_not_mem · hi)] @[simp] theorem eval_image_univ_pi (ht : (pi univ t).Nonempty) : (fun f : ∀ i, α i => f i) '' pi univ t = t i := eval_image_pi (mem_univ i) ht theorem pi_subset_pi_iff : pi s t₁ ⊆ pi s t₂ ↔ (∀ i ∈ s, t₁ i ⊆ t₂ i) ∨ pi s t₁ = ∅ := by refine ⟨fun h => or_iff_not_imp_right.2 ?_, fun h => h.elim pi_mono fun h' => h'.symm ▸ empty_subset _⟩ rw [← Ne, ← nonempty_iff_ne_empty] intro hne i hi simpa only [eval_image_pi hi hne, eval_image_pi hi (hne.mono h)] using image_subset (fun f : ∀ i, α i => f i) h theorem univ_pi_subset_univ_pi_iff : pi univ t₁ ⊆ pi univ t₂ ↔ (∀ i, t₁ i ⊆ t₂ i) ∨ ∃ i, t₁ i = ∅ := by simp [pi_subset_pi_iff] theorem eval_preimage [DecidableEq ι] {s : Set (α i)} : eval i ⁻¹' s = pi univ (update (fun i => univ) i s) := by ext x simp [@forall_update_iff _ (fun i => Set (α i)) _ _ _ _ fun i' y => x i' ∈ y] theorem eval_preimage' [DecidableEq ι] {s : Set (α i)} : eval i ⁻¹' s = pi {i} (update (fun i => univ) i s) := by ext simp theorem update_preimage_pi [DecidableEq ι] {f : ∀ i, α i} (hi : i ∈ s) (hf : ∀ j ∈ s, j ≠ i → f j ∈ t j) : update f i ⁻¹' s.pi t = t i := by ext x refine ⟨fun h => ?_, fun hx j hj => ?_⟩ · convert h i hi simp · obtain rfl | h := eq_or_ne j i · simpa · rw [update_noteq h] exact hf j hj h theorem update_image [DecidableEq ι] (x : (i : ι) → β i) (i : ι) (s : Set (β i)) : update x i '' s = Set.univ.pi (update (fun j ↦ {x j}) i s) := by ext y simp [update_eq_iff, and_left_comm (a := _ ∈ s), forall_update_iff, eq_comm (a := y _)] theorem update_preimage_univ_pi [DecidableEq ι] {f : ∀ i, α i} (hf : ∀ j ≠ i, f j ∈ t j) : update f i ⁻¹' pi univ t = t i := update_preimage_pi (mem_univ i) fun j _ => hf j theorem subset_pi_eval_image (s : Set ι) (u : Set (∀ i, α i)) : u ⊆ pi s fun i => eval i '' u := fun f hf _ _ => ⟨f, hf, rfl⟩ theorem univ_pi_ite (s : Set ι) [DecidablePred (· ∈ s)] (t : ∀ i, Set (α i)) : (pi univ fun i => if i ∈ s then t i else univ) = s.pi t := by ext simp_rw [mem_univ_pi] refine forall_congr' fun i => ?_ split_ifs with h <;> simp [h] end Pi end Set namespace Equiv open Set variable {ι ι' : Type*} {α : ι → Type*} theorem piCongrLeft_symm_preimage_pi (f : ι' ≃ ι) (s : Set ι') (t : ∀ i, Set (α i)) : (f.piCongrLeft α).symm ⁻¹' s.pi (fun i' => t <| f i') = (f '' s).pi t := by ext; simp theorem piCongrLeft_symm_preimage_univ_pi (f : ι' ≃ ι) (t : ∀ i, Set (α i)) : (f.piCongrLeft α).symm ⁻¹' univ.pi (fun i' => t <| f i') = univ.pi t := by simpa [f.surjective.range_eq] using piCongrLeft_symm_preimage_pi f univ t theorem piCongrLeft_preimage_pi (f : ι' ≃ ι) (s : Set ι') (t : ∀ i, Set (α i)) : f.piCongrLeft α ⁻¹' (f '' s).pi t = s.pi fun i => t (f i) := by apply Set.ext rw [← (f.piCongrLeft α).symm.forall_congr_right] simp theorem piCongrLeft_preimage_univ_pi (f : ι' ≃ ι) (t : ∀ i, Set (α i)) : f.piCongrLeft α ⁻¹' univ.pi t = univ.pi fun i => t (f i) := by simpa [f.surjective.range_eq] using piCongrLeft_preimage_pi f univ t theorem sumPiEquivProdPi_symm_preimage_univ_pi (π : ι ⊕ ι' → Type*) (t : ∀ i, Set (π i)) : (sumPiEquivProdPi π).symm ⁻¹' univ.pi t = univ.pi (fun i => t (.inl i)) ×ˢ univ.pi fun i => t (.inr i) := by ext simp_rw [mem_preimage, mem_prod, mem_univ_pi, sumPiEquivProdPi_symm_apply] constructor · intro h; constructor <;> intro i <;> apply h · rintro ⟨h₁, h₂⟩ (i|i) <;> simp <;> apply_assumption end Equiv
Data\Set\Semiring.lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import Mathlib.Algebra.Order.Kleene import Mathlib.Algebra.Order.Ring.Canonical import Mathlib.Data.Set.Pointwise.Basic /-! # Sets as a semiring under union This file defines `SetSemiring α`, an alias of `Set α`, which we endow with `∪` as addition and pointwise `*` as multiplication. If `α` is a (commutative) monoid, `SetSemiring α` is a (commutative) semiring. -/ open Function Set open Pointwise variable {α β : Type*} -- Porting note: mathlib3 uses `deriving Inhabited, PartialOrder, OrderBot` /-- An alias for `Set α`, which has a semiring structure given by `∪` as "addition" and pointwise multiplication `*` as "multiplication". -/ def SetSemiring (α : Type*) : Type _ := Set α noncomputable instance (α : Type*) : Inhabited (SetSemiring α) := (inferInstance : Inhabited (Set _)) instance (α : Type*) : PartialOrder (SetSemiring α) := (inferInstance : PartialOrder (Set _)) instance (α : Type*) : OrderBot (SetSemiring α) := (inferInstance : OrderBot (Set _)) /-- The identity function `Set α → SetSemiring α`. -/ protected def Set.up : Set α ≃ SetSemiring α := Equiv.refl _ namespace SetSemiring /-- The identity function `SetSemiring α → Set α`. -/ protected def down : SetSemiring α ≃ Set α := Equiv.refl _ -- Porting note: new, since dot notation doesn't work open SetSemiring (down) open Set (up) -- Porting note (#11036): dot notation no longer works @[simp] protected theorem down_up (s : Set α) : SetSemiring.down (Set.up s) = s := rfl -- Porting note (#11036): dot notation no longer works @[simp] protected theorem up_down (s : SetSemiring α) : Set.up (SetSemiring.down s) = s := rfl -- TODO: These lemmas are not tagged `simp` because `Set.le_eq_subset` simplifies the LHS -- Porting note (#11036): dot notation no longer works theorem up_le_up {s t : Set α} : Set.up s ≤ Set.up t ↔ s ⊆ t := Iff.rfl -- Porting note (#11036): dot notation no longer works theorem up_lt_up {s t : Set α} : Set.up s < Set.up t ↔ s ⊂ t := Iff.rfl -- Porting note (#11036): dot notation no longer works @[simp] theorem down_subset_down {s t : SetSemiring α} : SetSemiring.down s ⊆ SetSemiring.down t ↔ s ≤ t := Iff.rfl -- Porting note (#11036): dot notation no longer works @[simp] theorem down_ssubset_down {s t : SetSemiring α} : SetSemiring.down s ⊂ SetSemiring.down t ↔ s < t := Iff.rfl instance : Zero (SetSemiring α) where zero := Set.up (∅ : Set α) instance : Add (SetSemiring α) where add s t := Set.up (SetSemiring.down s ∪ SetSemiring.down t) -- Porting note (#11036): dot notation no longer works instance : AddCommMonoid (SetSemiring α) where add_assoc := union_assoc zero_add := empty_union add_zero := union_empty add_comm := union_comm nsmul := nsmulRec theorem zero_def : (0 : SetSemiring α) = Set.up ∅ := rfl @[simp] theorem down_zero : down (0 : SetSemiring α) = ∅ := rfl @[simp] theorem _root_.Set.up_empty : Set.up (∅ : Set α) = 0 := rfl theorem add_def (s t : SetSemiring α) : s + t = up (down s ∪ down t) := rfl @[simp] theorem down_add (s t : SetSemiring α) : down (s + t) = down s ∪ down t := rfl @[simp] theorem _root_.Set.up_union (s t : Set α) : up (s ∪ t) = up s + up t := rfl /- Since addition on `SetSemiring` is commutative (it is set union), there is no need to also have the instance `CovariantClass (SetSemiring α) (SetSemiring α) (swap (+)) (≤)`. -/ instance covariantClass_add : CovariantClass (SetSemiring α) (SetSemiring α) (· + ·) (· ≤ ·) := ⟨fun _ _ _ => union_subset_union_right _⟩ section Mul variable [Mul α] -- Porting note (#11036): dot notation no longer works instance : NonUnitalNonAssocSemiring (SetSemiring α) := { (inferInstance : AddCommMonoid (SetSemiring α)) with mul := fun s t => Set.up (image2 (· * ·) (SetSemiring.down s) (SetSemiring.down t)) zero_mul := fun _ => empty_mul mul_zero := fun _ => mul_empty left_distrib := fun _ _ _ => mul_union right_distrib := fun _ _ _ => union_mul } -- TODO: port theorem mul_def (s t : SetSemiring α) : s * t = up (down s * down t) := rfl @[simp] theorem down_mul (s t : SetSemiring α) : down (s * t) = down s * down t := rfl @[simp] theorem _root_.Set.up_mul (s t : Set α) : up (s * t) = up s * up t := rfl instance : NoZeroDivisors (SetSemiring α) := ⟨fun {a b} ab => a.eq_empty_or_nonempty.imp_right fun ha => b.eq_empty_or_nonempty.resolve_right fun hb => Nonempty.ne_empty ⟨_, mul_mem_mul ha.some_mem hb.some_mem⟩ ab⟩ instance covariantClass_mul_left : CovariantClass (SetSemiring α) (SetSemiring α) (· * ·) (· ≤ ·) := ⟨fun _ _ _ => mul_subset_mul_left⟩ instance covariantClass_mul_right : CovariantClass (SetSemiring α) (SetSemiring α) (swap (· * ·)) (· ≤ ·) := ⟨fun _ _ _ => mul_subset_mul_right⟩ end Mul section One variable [One α] instance : One (SetSemiring α) where one := Set.up (1 : Set α) theorem one_def : (1 : SetSemiring α) = Set.up 1 := rfl @[simp] theorem down_one : down (1 : SetSemiring α) = 1 := rfl @[simp] theorem _root_.Set.up_one : up (1 : Set α) = 1 := rfl end One instance [MulOneClass α] : NonAssocSemiring (SetSemiring α) := { (inferInstance : NonUnitalNonAssocSemiring (SetSemiring α)), Set.mulOneClass with } instance [Semigroup α] : NonUnitalSemiring (SetSemiring α) := { (inferInstance : NonUnitalNonAssocSemiring (SetSemiring α)), Set.semigroup with } instance [Monoid α] : IdemSemiring (SetSemiring α) := { (inferInstance : NonAssocSemiring (SetSemiring α)), (inferInstance : NonUnitalSemiring (SetSemiring α)), (inferInstance : CompleteBooleanAlgebra (Set α)) with } instance [CommSemigroup α] : NonUnitalCommSemiring (SetSemiring α) := { (inferInstance : NonUnitalSemiring (SetSemiring α)), Set.commSemigroup with } instance [CommMonoid α] : IdemCommSemiring (SetSemiring α) := { (inferInstance : IdemSemiring (SetSemiring α)), (inferInstance : CommMonoid (Set α)) with } instance [CommMonoid α] : CommMonoid (SetSemiring α) := { (inferInstance : Monoid (SetSemiring α)), Set.commSemigroup with } instance [CommMonoid α] : CanonicallyOrderedCommSemiring (SetSemiring α) := { (inferInstance : Semiring (SetSemiring α)), (inferInstance : CommMonoid (SetSemiring α)), (inferInstance : PartialOrder (SetSemiring α)), (inferInstance : OrderBot (SetSemiring α)), (inferInstance : NoZeroDivisors (SetSemiring α)) with add_le_add_left := fun _ _ => add_le_add_left exists_add_of_le := fun {_ b} ab => ⟨b, (union_eq_right.2 ab).symm⟩ le_self_add := fun _ _ => subset_union_left } /-- The image of a set under a multiplicative homomorphism is a ring homomorphism with respect to the pointwise operations on sets. -/ def imageHom [MulOneClass α] [MulOneClass β] (f : α →* β) : SetSemiring α →+* SetSemiring β where toFun s := up (image f (down s)) map_zero' := image_empty _ map_one' := by dsimp only -- Porting note: structures do not do this automatically any more rw [down_one, image_one, map_one, singleton_one, up_one] map_add' := image_union _ map_mul' _ _ := image_mul f lemma imageHom_def [MulOneClass α] [MulOneClass β] (f : α →* β) (s : SetSemiring α) : imageHom f s = up (image f (down s)) := rfl @[simp] lemma down_imageHom [MulOneClass α] [MulOneClass β] (f : α →* β) (s : SetSemiring α) : down (imageHom f s) = f '' down s := rfl @[simp] lemma _root_.Set.up_image [MulOneClass α] [MulOneClass β] (f : α →* β) (s : Set α) : up (f '' s) = imageHom f (up s) := rfl end SetSemiring
Data\Set\Sigma.lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import Mathlib.Data.Set.Image import Mathlib.Data.Set.Lattice /-! # Sets in sigma types This file defines `Set.sigma`, the indexed sum of sets. -/ namespace Set variable {ι ι' : Type*} {α β : ι → Type*} {s s₁ s₂ : Set ι} {t t₁ t₂ : ∀ i, Set (α i)} {u : Set (Σ i, α i)} {x : Σ i, α i} {i j : ι} {a : α i} @[simp] theorem range_sigmaMk (i : ι) : range (Sigma.mk i : α i → Sigma α) = Sigma.fst ⁻¹' {i} := by apply Subset.antisymm · rintro _ ⟨b, rfl⟩ simp · rintro ⟨x, y⟩ (rfl | _) exact mem_range_self y theorem preimage_image_sigmaMk_of_ne (h : i ≠ j) (s : Set (α j)) : Sigma.mk i ⁻¹' (Sigma.mk j '' s) = ∅ := by ext x simp [h.symm] theorem image_sigmaMk_preimage_sigmaMap_subset {β : ι' → Type*} (f : ι → ι') (g : ∀ i, α i → β (f i)) (i : ι) (s : Set (β (f i))) : Sigma.mk i '' (g i ⁻¹' s) ⊆ Sigma.map f g ⁻¹' (Sigma.mk (f i) '' s) := image_subset_iff.2 fun x hx ↦ ⟨g i x, hx, rfl⟩ theorem image_sigmaMk_preimage_sigmaMap {β : ι' → Type*} {f : ι → ι'} (hf : Function.Injective f) (g : ∀ i, α i → β (f i)) (i : ι) (s : Set (β (f i))) : Sigma.mk i '' (g i ⁻¹' s) = Sigma.map f g ⁻¹' (Sigma.mk (f i) '' s) := by refine (image_sigmaMk_preimage_sigmaMap_subset f g i s).antisymm ?_ rintro ⟨j, x⟩ ⟨y, hys, hxy⟩ simp only [hf.eq_iff, Sigma.map, Sigma.ext_iff] at hxy rcases hxy with ⟨rfl, hxy⟩; rw [heq_iff_eq] at hxy; subst y exact ⟨x, hys, rfl⟩ /-- Indexed sum of sets. `s.sigma t` is the set of dependent pairs `⟨i, a⟩` such that `i ∈ s` and `a ∈ t i`. -/ protected def sigma (s : Set ι) (t : ∀ i, Set (α i)) : Set (Σ i, α i) := {x | x.1 ∈ s ∧ x.2 ∈ t x.1} @[simp] theorem mem_sigma_iff : x ∈ s.sigma t ↔ x.1 ∈ s ∧ x.2 ∈ t x.1 := Iff.rfl theorem mk_sigma_iff : (⟨i, a⟩ : Σ i, α i) ∈ s.sigma t ↔ i ∈ s ∧ a ∈ t i := Iff.rfl theorem mk_mem_sigma (hi : i ∈ s) (ha : a ∈ t i) : (⟨i, a⟩ : Σ i, α i) ∈ s.sigma t := ⟨hi, ha⟩ theorem sigma_mono (hs : s₁ ⊆ s₂) (ht : ∀ i, t₁ i ⊆ t₂ i) : s₁.sigma t₁ ⊆ s₂.sigma t₂ := fun _ hx ↦ ⟨hs hx.1, ht _ hx.2⟩ theorem sigma_subset_iff : s.sigma t ⊆ u ↔ ∀ ⦃i⦄, i ∈ s → ∀ ⦃a⦄, a ∈ t i → (⟨i, a⟩ : Σ i, α i) ∈ u := ⟨fun h _ hi _ ha ↦ h <| mk_mem_sigma hi ha, fun h _ ha ↦ h ha.1 ha.2⟩ theorem forall_sigma_iff {p : (Σ i, α i) → Prop} : (∀ x ∈ s.sigma t, p x) ↔ ∀ ⦃i⦄, i ∈ s → ∀ ⦃a⦄, a ∈ t i → p ⟨i, a⟩ := sigma_subset_iff theorem exists_sigma_iff {p : (Σi, α i) → Prop} : (∃ x ∈ s.sigma t, p x) ↔ ∃ i ∈ s, ∃ a ∈ t i, p ⟨i, a⟩ := ⟨fun ⟨⟨i, a⟩, ha, h⟩ ↦ ⟨i, ha.1, a, ha.2, h⟩, fun ⟨i, hi, a, ha, h⟩ ↦ ⟨⟨i, a⟩, ⟨hi, ha⟩, h⟩⟩ @[simp] theorem sigma_empty : s.sigma (fun i ↦ (∅ : Set (α i))) = ∅ := ext fun _ ↦ and_false_iff _ @[simp] theorem empty_sigma : (∅ : Set ι).sigma t = ∅ := ext fun _ ↦ false_and_iff _ theorem univ_sigma_univ : (@univ ι).sigma (fun _ ↦ @univ (α i)) = univ := ext fun _ ↦ true_and_iff _ @[simp] theorem sigma_univ : s.sigma (fun _ ↦ univ : ∀ i, Set (α i)) = Sigma.fst ⁻¹' s := ext fun _ ↦ and_true_iff _ @[simp] theorem univ_sigma_preimage_mk (s : Set (Σ i, α i)) : (univ : Set ι).sigma (fun i ↦ Sigma.mk i ⁻¹' s) = s := ext <| by simp @[simp] theorem singleton_sigma : ({i} : Set ι).sigma t = Sigma.mk i '' t i := ext fun x ↦ by constructor · obtain ⟨j, a⟩ := x rintro ⟨rfl : j = i, ha⟩ exact mem_image_of_mem _ ha · rintro ⟨b, hb, rfl⟩ exact ⟨rfl, hb⟩ @[simp] theorem sigma_singleton {a : ∀ i, α i} : s.sigma (fun i ↦ ({a i} : Set (α i))) = (fun i ↦ Sigma.mk i <| a i) '' s := by ext ⟨x, y⟩ simp [and_left_comm, eq_comm] theorem singleton_sigma_singleton {a : ∀ i, α i} : (({i} : Set ι).sigma fun i ↦ ({a i} : Set (α i))) = {⟨i, a i⟩} := by rw [sigma_singleton, image_singleton] @[simp] theorem union_sigma : (s₁ ∪ s₂).sigma t = s₁.sigma t ∪ s₂.sigma t := ext fun _ ↦ or_and_right @[simp] theorem sigma_union : s.sigma (fun i ↦ t₁ i ∪ t₂ i) = s.sigma t₁ ∪ s.sigma t₂ := ext fun _ ↦ and_or_left theorem sigma_inter_sigma : s₁.sigma t₁ ∩ s₂.sigma t₂ = (s₁ ∩ s₂).sigma fun i ↦ t₁ i ∩ t₂ i := by ext ⟨x, y⟩ simp [and_assoc, and_left_comm] variable {β : Type*} [CompleteLattice β] theorem _root_.biSup_sigma (s : Set ι) (t : ∀ i, Set (α i)) (f : Sigma α → β) : ⨆ ij ∈ s.sigma t, f ij = ⨆ (i ∈ s) (j ∈ t i), f ⟨i, j⟩ := eq_of_forall_ge_iff fun _ ↦ ⟨by simp_all, by simp_all⟩ theorem _root_.biSup_sigma' (s : Set ι) (t : ∀ i, Set (α i)) (f : ∀ i, α i → β) : ⨆ (i ∈ s) (j ∈ t i), f i j = ⨆ ij ∈ s.sigma t, f ij.fst ij.snd := Eq.symm (biSup_sigma _ _ _) theorem _root_.biInf_sigma (s : Set ι) (t : ∀ i, Set (α i)) (f : Sigma α → β) : ⨅ ij ∈ s.sigma t, f ij = ⨅ (i ∈ s) (j ∈ t i), f ⟨i, j⟩ := biSup_sigma (β := βᵒᵈ) _ _ _ theorem _root_.biInf_sigma' (s : Set ι) (t : ∀ i, Set (α i)) (f : ∀ i, α i → β) : ⨅ (i ∈ s) (j ∈ t i), f i j = ⨅ ij ∈ s.sigma t, f ij.fst ij.snd := Eq.symm (biInf_sigma _ _ _) variable {β : Type*} theorem biUnion_sigma (s : Set ι) (t : ∀ i, Set (α i)) (f : Sigma α → Set β) : ⋃ ij ∈ s.sigma t, f ij = ⋃ i ∈ s, ⋃ j ∈ t i, f ⟨i, j⟩ := biSup_sigma _ _ _ theorem biUnion_sigma' (s : Set ι) (t : ∀ i, Set (α i)) (f : ∀ i, α i → Set β) : ⋃ i ∈ s, ⋃ j ∈ t i, f i j = ⋃ ij ∈ s.sigma t, f ij.fst ij.snd := biSup_sigma' _ _ _ theorem biInter_sigma (s : Set ι) (t : ∀ i, Set (α i)) (f : Sigma α → Set β) : ⋂ ij ∈ s.sigma t, f ij = ⋂ i ∈ s, ⋂ j ∈ t i, f ⟨i, j⟩ := biInf_sigma _ _ _ theorem biInter_sigma' (s : Set ι) (t : ∀ i, Set (α i)) (f : ∀ i, α i → Set β) : ⋂ i ∈ s, ⋂ j ∈ t i, f i j = ⋂ ij ∈ s.sigma t, f ij.fst ij.snd := biInf_sigma' _ _ _ variable {β : ι → Type*} theorem insert_sigma : (insert i s).sigma t = Sigma.mk i '' t i ∪ s.sigma t := by rw [insert_eq, union_sigma, singleton_sigma] exact a theorem sigma_insert {a : ∀ i, α i} : s.sigma (fun i ↦ insert (a i) (t i)) = (fun i ↦ ⟨i, a i⟩) '' s ∪ s.sigma t := by simp_rw [insert_eq, sigma_union, sigma_singleton] theorem sigma_preimage_eq {f : ι' → ι} {g : ∀ i, β i → α i} : (f ⁻¹' s).sigma (fun i ↦ g (f i) ⁻¹' t (f i)) = (fun p : Σ i, β (f i) ↦ Sigma.mk _ (g _ p.2)) ⁻¹' s.sigma t := rfl theorem sigma_preimage_left {f : ι' → ι} : ((f ⁻¹' s).sigma fun i ↦ t (f i)) = (fun p : Σ i, α (f i) ↦ Sigma.mk _ p.2) ⁻¹' s.sigma t := rfl theorem sigma_preimage_right {g : ∀ i, β i → α i} : (s.sigma fun i ↦ g i ⁻¹' t i) = (fun p : Σ i, β i ↦ Sigma.mk p.1 (g _ p.2)) ⁻¹' s.sigma t := rfl theorem preimage_sigmaMap_sigma {α' : ι' → Type*} (f : ι → ι') (g : ∀ i, α i → α' (f i)) (s : Set ι') (t : ∀ i, Set (α' i)) : Sigma.map f g ⁻¹' s.sigma t = (f ⁻¹' s).sigma fun i ↦ g i ⁻¹' t (f i) := rfl @[simp] theorem mk_preimage_sigma (hi : i ∈ s) : Sigma.mk i ⁻¹' s.sigma t = t i := ext fun _ ↦ and_iff_right hi @[simp] theorem mk_preimage_sigma_eq_empty (hi : i ∉ s) : Sigma.mk i ⁻¹' s.sigma t = ∅ := ext fun _ ↦ iff_of_false (hi ∘ And.left) id theorem mk_preimage_sigma_eq_if [DecidablePred (· ∈ s)] : Sigma.mk i ⁻¹' s.sigma t = if i ∈ s then t i else ∅ := by split_ifs <;> simp [*] theorem mk_preimage_sigma_fn_eq_if {β : Type*} [DecidablePred (· ∈ s)] (g : β → α i) : (fun b ↦ Sigma.mk i (g b)) ⁻¹' s.sigma t = if i ∈ s then g ⁻¹' t i else ∅ := ext fun _ ↦ by split_ifs <;> simp [*] theorem sigma_univ_range_eq {f : ∀ i, α i → β i} : (univ : Set ι).sigma (fun i ↦ range (f i)) = range fun x : Σ i, α i ↦ ⟨x.1, f _ x.2⟩ := ext <| by simp [range] protected theorem Nonempty.sigma : s.Nonempty → (∀ i, (t i).Nonempty) → (s.sigma t).Nonempty := fun ⟨i, hi⟩ h ↦ let ⟨a, ha⟩ := h i ⟨⟨i, a⟩, hi, ha⟩ theorem Nonempty.sigma_fst : (s.sigma t).Nonempty → s.Nonempty := fun ⟨x, hx⟩ ↦ ⟨x.1, hx.1⟩ theorem Nonempty.sigma_snd : (s.sigma t).Nonempty → ∃ i ∈ s, (t i).Nonempty := fun ⟨x, hx⟩ ↦ ⟨x.1, hx.1, x.2, hx.2⟩ theorem sigma_nonempty_iff : (s.sigma t).Nonempty ↔ ∃ i ∈ s, (t i).Nonempty := ⟨Nonempty.sigma_snd, fun ⟨i, hi, a, ha⟩ ↦ ⟨⟨i, a⟩, hi, ha⟩⟩ theorem sigma_eq_empty_iff : s.sigma t = ∅ ↔ ∀ i ∈ s, t i = ∅ := not_nonempty_iff_eq_empty.symm.trans <| sigma_nonempty_iff.not.trans <| by simp only [not_nonempty_iff_eq_empty, not_and, not_exists] theorem image_sigmaMk_subset_sigma_left {a : ∀ i, α i} (ha : ∀ i, a i ∈ t i) : (fun i ↦ Sigma.mk i (a i)) '' s ⊆ s.sigma t := image_subset_iff.2 fun _ hi ↦ ⟨hi, ha _⟩ theorem image_sigmaMk_subset_sigma_right (hi : i ∈ s) : Sigma.mk i '' t i ⊆ s.sigma t := image_subset_iff.2 fun _ ↦ And.intro hi theorem sigma_subset_preimage_fst (s : Set ι) (t : ∀ i, Set (α i)) : s.sigma t ⊆ Sigma.fst ⁻¹' s := fun _ ↦ And.left theorem fst_image_sigma_subset (s : Set ι) (t : ∀ i, Set (α i)) : Sigma.fst '' s.sigma t ⊆ s := image_subset_iff.2 fun _ ↦ And.left theorem fst_image_sigma (s : Set ι) (ht : ∀ i, (t i).Nonempty) : Sigma.fst '' s.sigma t = s := (fst_image_sigma_subset _ _).antisymm fun i hi ↦ let ⟨a, ha⟩ := ht i ⟨⟨i, a⟩, ⟨hi, ha⟩, rfl⟩ theorem sigma_diff_sigma : s₁.sigma t₁ \ s₂.sigma t₂ = s₁.sigma (t₁ \ t₂) ∪ (s₁ \ s₂).sigma t₁ := ext fun x ↦ by by_cases h₁ : x.1 ∈ s₁ <;> by_cases h₂ : x.2 ∈ t₁ x.1 <;> simp [*, ← imp_iff_or_not] end Set
Data\Set\SMulAntidiagonal.lean
/- Copyright (c) 2024 Scott Carnahan. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Carnahan -/ import Mathlib.Algebra.Order.AddTorsor import Mathlib.Order.WellFoundedSet /-! # Antidiagonal for scalar multiplication Given partially ordered sets `G` and `P`, with an action of `G` on `P`, we construct, for any element `a` in `P` and subsets `s` in `G` and `t` in `P`, the set of all pairs of an element in `s` and an element in `t` that scalar-multiply to `a`. ## Definitions * SMul.antidiagonal : Set-valued antidiagonal for SMul. * VAdd.antidiagonal : Set-valued antidiagonal for VAdd. -/ variable {G P : Type*} namespace Set section SMul variable [SMul G P] {s s₁ s₂ : Set G} {t t₁ t₂ : Set P} {a : P} {x : G × P} /-- `smulAntidiagonal s t a` is the set of all pairs of an element in `s` and an element in `t` that scalar multiply to `a`.-/ @[to_additive "`vaddAntidiagonal s t a` is the set of all pairs of an element in `s` and an element in `t` that vector-add to `a`."] def smulAntidiagonal (s : Set G) (t : Set P) (a : P) : Set (G × P) := { x | x.1 ∈ s ∧ x.2 ∈ t ∧ x.1 • x.2 = a } @[to_additive (attr := simp)] theorem mem_smulAntidiagonal : x ∈ smulAntidiagonal s t a ↔ x.1 ∈ s ∧ x.2 ∈ t ∧ x.1 • x.2 = a := Iff.rfl @[to_additive] theorem smulAntidiagonal_mono_left (h : s₁ ⊆ s₂) : smulAntidiagonal s₁ t a ⊆ smulAntidiagonal s₂ t a := fun _ hx => ⟨h hx.1, hx.2.1, hx.2.2⟩ @[to_additive] theorem smulAntidiagonal_mono_right (h : t₁ ⊆ t₂) : smulAntidiagonal s t₁ a ⊆ smulAntidiagonal s t₂ a := fun _ hx => ⟨hx.1, h hx.2.1, hx.2.2⟩ end SMul open SMul namespace SMulAntidiagonal variable {s : Set G} {t : Set P} {a : P} section CancelSMul variable [SMul G P] [IsCancelSMul G P] {x y : smulAntidiagonal s t a} @[to_additive VAddAntidiagonal.fst_eq_fst_iff_snd_eq_snd] theorem fst_eq_fst_iff_snd_eq_snd : (x : G × P).1 = (y : G × P).1 ↔ (x : G × P).2 = (y : G × P).2 := ⟨fun h => IsCancelSMul.left_cancel _ _ _ (y.2.2.2.trans <| by rw [← h] exact x.2.2.2.symm).symm, fun h => IsCancelSMul.right_cancel _ _ _ (y.2.2.2.trans <| by rw [← h] exact x.2.2.2.symm).symm⟩ @[to_additive VAddAntidiagonal.eq_of_fst_eq_fst] theorem eq_of_fst_eq_fst (h : (x : G × P).fst = (y : G × P).fst) : x = y := Subtype.ext <| Prod.ext h <| fst_eq_fst_iff_snd_eq_snd.1 h @[to_additive VAddAntidiagonal.eq_of_snd_eq_snd] theorem eq_of_snd_eq_snd (h : (x : G × P).snd = (y : G × P).snd) : x = y := Subtype.ext <| Prod.ext (fst_eq_fst_iff_snd_eq_snd.2 h) h end CancelSMul variable [PartialOrder G] [PartialOrder P] [SMul G P] [IsOrderedCancelSMul G P] {x y : smulAntidiagonal s t a} @[to_additive VAddAntidiagonal.eq_of_fst_le_fst_of_snd_le_snd] theorem eq_of_fst_le_fst_of_snd_le_snd (h₁ : (x : G × P).1 ≤ (y : G × P).1) (h₂ : (x : G × P).2 ≤ (y : G × P).2) : x = y := eq_of_fst_eq_fst <| h₁.eq_of_not_lt fun hlt => (smul_lt_smul_of_lt_of_le hlt h₂).ne <| (mem_smulAntidiagonal.1 x.2).2.2.trans (mem_smulAntidiagonal.1 y.2).2.2.symm @[to_additive VAddAntidiagonal.finite_of_isPWO] theorem finite_of_isPWO (hs : s.IsPWO) (ht : t.IsPWO) (a) : (smulAntidiagonal s t a).Finite := by refine Set.not_infinite.1 fun h => ?_ have h1 : (smulAntidiagonal s t a).PartiallyWellOrderedOn (Prod.fst ⁻¹'o (· ≤ ·)) := fun f hf => hs (Prod.fst ∘ f) fun n => (mem_smulAntidiagonal.1 (hf n)).1 have h2 : (smulAntidiagonal s t a).PartiallyWellOrderedOn (Prod.snd ⁻¹'o (· ≤ ·)) := fun f hf => ht (Prod.snd ∘ f) fun n => (mem_smulAntidiagonal.1 (hf n)).2.1 have isrfl : IsRefl (G × P) (Prod.fst ⁻¹'o fun x x_1 ↦ x ≤ x_1) := by refine { refl := ?refl } simp_all only [Order.Preimage, le_refl, Prod.forall, implies_true] have istrns : IsTrans (G × P) (Prod.fst ⁻¹'o fun x x_1 ↦ x ≤ x_1) := by refine { trans := ?trans } simp_all only [Order.Preimage, Prod.forall] exact fun a _ a_1 _ a_2 _ a_3 a_4 ↦ Preorder.le_trans a a_1 a_2 a_3 a_4 obtain ⟨g, hg⟩ := h1.exists_monotone_subseq (fun n => h.natEmbedding _ n) fun n => (h.natEmbedding _ n).2 obtain ⟨m, n, mn, h2'⟩ := h2 (fun x => (h.natEmbedding _) (g x)) fun n => (h.natEmbedding _ _).2 refine mn.ne (g.injective <| (h.natEmbedding _).injective ?_) exact eq_of_fst_le_fst_of_snd_le_snd (hg _ _ mn.le) h2' end Set.SMulAntidiagonal
Data\Set\Subset.lean
/- Copyright (c) 2024 Miguel Marco. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Miguel Marco -/ import Mathlib.Data.Set.Function import Mathlib.Data.Set.Functor /-! # Sets in subtypes This file is about sets in `Set A` when `A` is a set. It defines notation `↓∩` for sets in a type pulled down to sets in a subtype, as an inverse operation to the coercion that lifts sets in a subtype up to sets in the ambient type. This module also provides lemmas for `↓∩` and this coercion. ## Notation Let `α` be a `Type`, `A B : Set α` two sets in `α`, and `C : Set A` a set in the subtype `↑A`. - `A ↓∩ B` denotes `(Subtype.val ⁻¹' B : Set A)` (that is, `{x : ↑A | ↑x ∈ B}`). - `↑C` denotes `Subtype.val '' C` (that is, `{x : α | ∃ y ∈ C, ↑y = x}`). This notation, (together with the `↑` notation for `Set.CoeHead`) is defined in `Mathlib.Data.Set.Notation` and is scoped to the `Set.Notation` namespace. To enable it, use `open Set.Notation`. ## Naming conventions Theorem names refer to `↓∩` as `preimage_val`. ## Tags subsets -/ open Set variable {ι : Sort*} {α : Type*} {A B C : Set α} {D E : Set A} variable {S : Set (Set α)} {T : Set (Set A)} {s : ι → Set α} {t : ι → Set A} namespace Set open Notation lemma preimage_val_eq_univ_of_subset (h : A ⊆ B) : A ↓∩ B = univ := by rw [eq_univ_iff_forall, Subtype.forall] exact h lemma preimage_val_sUnion : A ↓∩ (⋃₀ S) = ⋃₀ { (A ↓∩ B) | B ∈ S } := by erw [sUnion_image] simp_rw [sUnion_eq_biUnion, preimage_iUnion] @[simp] lemma preimage_val_iInter : A ↓∩ (⋂ i, s i) = ⋂ i, A ↓∩ s i := preimage_iInter lemma preimage_val_sInter : A ↓∩ (⋂₀ S) = ⋂₀ { (A ↓∩ B) | B ∈ S } := by erw [sInter_image] simp_rw [sInter_eq_biInter, preimage_iInter] lemma preimage_val_sInter_eq_sInter : A ↓∩ (⋂₀ S) = ⋂₀ ((A ↓∩ ·) '' S) := by simp only [preimage_sInter, sInter_image] lemma eq_of_preimage_val_eq_of_subset (hB : B ⊆ A) (hC : C ⊆ A) (h : A ↓∩ B = A ↓∩ C) : B = C := by simp only [← inter_eq_right] at hB hC simp only [Subtype.preimage_val_eq_preimage_val_iff, hB, hC] at h exact h /-! The following simp lemmas try to transform operations in the subtype into operations in the ambient type, if possible. -/ @[simp] lemma image_val_union : (↑(D ∪ E) : Set α) = ↑D ∪ ↑E := image_union _ _ _ @[simp] lemma image_val_inter : (↑(D ∩ E) : Set α) = ↑D ∩ ↑E := image_inter Subtype.val_injective @[simp] lemma image_val_diff : (↑(D \ E) : Set α) = ↑D \ ↑E := image_diff Subtype.val_injective _ _ @[simp] lemma image_val_compl : ↑(Dᶜ) = A \ ↑D := by rw [compl_eq_univ_diff, image_val_diff, image_univ, Subtype.range_coe_subtype, setOf_mem_eq] @[simp] lemma image_val_sUnion : ↑(⋃₀ T) = ⋃₀ { (B : Set α) | B ∈ T} := by rw [image_sUnion, image] @[simp] lemma image_val_iUnion : ↑(⋃ i, t i) = ⋃ i, (t i : Set α) := image_iUnion @[simp] lemma image_val_sInter (hT : T.Nonempty) : (↑(⋂₀ T) : Set α) = ⋂₀ { (↑B : Set α) | B ∈ T } := by erw [sInter_image] rw [sInter_eq_biInter, Subtype.val_injective.injOn.image_biInter_eq hT] @[simp] lemma image_val_iInter [Nonempty ι] : (↑(⋂ i, t i) : Set α) = ⋂ i, (↑(t i) : Set α) := Subtype.val_injective.injOn.image_iInter_eq @[simp] lemma image_val_union_self_right_eq : A ∪ ↑D = A := union_eq_left.2 image_val_subset @[simp] lemma image_val_union_self_left_eq : ↑D ∪ A = A := union_eq_right.2 image_val_subset @[simp] lemma cou_inter_self_right_eq_coe : A ∩ ↑D = ↑D := inter_eq_right.2 image_val_subset @[simp] lemma image_val_inter_self_left_eq_coe : ↑D ∩ A = ↑D := inter_eq_left.2 image_val_subset lemma subset_preimage_val_image_val_iff : D ⊆ A ↓∩ ↑E ↔ D ⊆ E := by rw [preimage_image_eq _ Subtype.val_injective] @[simp] lemma image_val_inj : (D : Set α) = ↑E ↔ D = E := Subtype.val_injective.image_injective.eq_iff lemma image_val_injective : Function.Injective ((↑) : Set A → Set α) := Subtype.val_injective.image_injective lemma subset_of_image_val_subset_image_val (h : (↑D : Set α) ⊆ ↑E) : D ⊆ E := (image_subset_image_iff Subtype.val_injective).1 h @[mono] lemma image_val_mono (h : D ⊆ E) : (↑D : Set α) ⊆ ↑E := (image_subset_image_iff Subtype.val_injective).2 h /-! Relations between restriction and coercion. -/ lemma image_val_preimage_val_subset_self : ↑(A ↓∩ B) ⊆ B := image_preimage_subset _ _ lemma preimage_val_image_val_eq_self : A ↓∩ ↑D = D := Function.Injective.preimage_image Subtype.val_injective _ end Set
Data\Set\Subsingleton.lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura -/ import Mathlib.Data.Set.Basic /-! # Subsingleton Defines the predicate `Subsingleton s : Prop`, saying that `s` has at most one element. Also defines `Nontrivial s : Prop` : the predicate saying that `s` has at least two distinct elements. -/ open Function universe u v namespace Set /-! ### Subsingleton -/ section Subsingleton variable {α : Type u} {a : α} {s t : Set α} /-- A set `s` is a `Subsingleton` if it has at most one element. -/ protected def Subsingleton (s : Set α) : Prop := ∀ ⦃x⦄ (_ : x ∈ s) ⦃y⦄ (_ : y ∈ s), x = y theorem Subsingleton.anti (ht : t.Subsingleton) (hst : s ⊆ t) : s.Subsingleton := fun _ hx _ hy => ht (hst hx) (hst hy) theorem Subsingleton.eq_singleton_of_mem (hs : s.Subsingleton) {x : α} (hx : x ∈ s) : s = {x} := ext fun _ => ⟨fun hy => hs hx hy ▸ mem_singleton _, fun hy => (eq_of_mem_singleton hy).symm ▸ hx⟩ @[simp] theorem subsingleton_empty : (∅ : Set α).Subsingleton := fun _ => False.elim @[simp] theorem subsingleton_singleton {a} : ({a} : Set α).Subsingleton := fun _ hx _ hy => (eq_of_mem_singleton hx).symm ▸ (eq_of_mem_singleton hy).symm ▸ rfl theorem subsingleton_of_subset_singleton (h : s ⊆ {a}) : s.Subsingleton := subsingleton_singleton.anti h theorem subsingleton_of_forall_eq (a : α) (h : ∀ b ∈ s, b = a) : s.Subsingleton := fun _ hb _ hc => (h _ hb).trans (h _ hc).symm theorem subsingleton_iff_singleton {x} (hx : x ∈ s) : s.Subsingleton ↔ s = {x} := ⟨fun h => h.eq_singleton_of_mem hx, fun h => h.symm ▸ subsingleton_singleton⟩ theorem Subsingleton.eq_empty_or_singleton (hs : s.Subsingleton) : s = ∅ ∨ ∃ x, s = {x} := s.eq_empty_or_nonempty.elim Or.inl fun ⟨x, hx⟩ => Or.inr ⟨x, hs.eq_singleton_of_mem hx⟩ theorem Subsingleton.induction_on {p : Set α → Prop} (hs : s.Subsingleton) (he : p ∅) (h₁ : ∀ x, p {x}) : p s := by rcases hs.eq_empty_or_singleton with (rfl | ⟨x, rfl⟩) exacts [he, h₁ _] theorem subsingleton_univ [Subsingleton α] : (univ : Set α).Subsingleton := fun x _ y _ => Subsingleton.elim x y theorem subsingleton_of_univ_subsingleton (h : (univ : Set α).Subsingleton) : Subsingleton α := ⟨fun a b => h (mem_univ a) (mem_univ b)⟩ @[simp] theorem subsingleton_univ_iff : (univ : Set α).Subsingleton ↔ Subsingleton α := ⟨subsingleton_of_univ_subsingleton, fun h => @subsingleton_univ _ h⟩ lemma Subsingleton.inter_singleton : (s ∩ {a}).Subsingleton := Set.subsingleton_of_subset_singleton Set.inter_subset_right lemma Subsingleton.singleton_inter : ({a} ∩ s).Subsingleton := Set.subsingleton_of_subset_singleton Set.inter_subset_left theorem subsingleton_of_subsingleton [Subsingleton α] {s : Set α} : Set.Subsingleton s := subsingleton_univ.anti (subset_univ s) theorem subsingleton_isTop (α : Type*) [PartialOrder α] : Set.Subsingleton { x : α | IsTop x } := fun x hx _ hy => hx.isMax.eq_of_le (hy x) theorem subsingleton_isBot (α : Type*) [PartialOrder α] : Set.Subsingleton { x : α | IsBot x } := fun x hx _ hy => hx.isMin.eq_of_ge (hy x) theorem exists_eq_singleton_iff_nonempty_subsingleton : (∃ a : α, s = {a}) ↔ s.Nonempty ∧ s.Subsingleton := by refine ⟨?_, fun h => ?_⟩ · rintro ⟨a, rfl⟩ exact ⟨singleton_nonempty a, subsingleton_singleton⟩ · exact h.2.eq_empty_or_singleton.resolve_left h.1.ne_empty /-- `s`, coerced to a type, is a subsingleton type if and only if `s` is a subsingleton set. -/ @[simp, norm_cast] theorem subsingleton_coe (s : Set α) : Subsingleton s ↔ s.Subsingleton := by constructor · refine fun h => fun a ha b hb => ?_ exact SetCoe.ext_iff.2 (@Subsingleton.elim s h ⟨a, ha⟩ ⟨b, hb⟩) · exact fun h => Subsingleton.intro fun a b => SetCoe.ext (h a.property b.property) theorem Subsingleton.coe_sort {s : Set α} : s.Subsingleton → Subsingleton s := s.subsingleton_coe.2 /-- The `coe_sort` of a set `s` in a subsingleton type is a subsingleton. For the corresponding result for `Subtype`, see `subtype.subsingleton`. -/ instance subsingleton_coe_of_subsingleton [Subsingleton α] {s : Set α} : Subsingleton s := by rw [s.subsingleton_coe] exact subsingleton_of_subsingleton end Subsingleton /-! ### Nontrivial -/ section Nontrivial variable {α : Type u} {a : α} {s t : Set α} /-- A set `s` is `Set.Nontrivial` if it has at least two distinct elements. -/ protected def Nontrivial (s : Set α) : Prop := ∃ x ∈ s, ∃ y ∈ s, x ≠ y theorem nontrivial_of_mem_mem_ne {x y} (hx : x ∈ s) (hy : y ∈ s) (hxy : x ≠ y) : s.Nontrivial := ⟨x, hx, y, hy, hxy⟩ -- Porting note: following the pattern for `Exists`, we have renamed `some` to `choose`. /-- Extract witnesses from s.nontrivial. This function might be used instead of case analysis on the argument. Note that it makes a proof depend on the classical.choice axiom. -/ protected noncomputable def Nontrivial.choose (hs : s.Nontrivial) : α × α := (Exists.choose hs, hs.choose_spec.right.choose) protected theorem Nontrivial.choose_fst_mem (hs : s.Nontrivial) : hs.choose.fst ∈ s := hs.choose_spec.left protected theorem Nontrivial.choose_snd_mem (hs : s.Nontrivial) : hs.choose.snd ∈ s := hs.choose_spec.right.choose_spec.left protected theorem Nontrivial.choose_fst_ne_choose_snd (hs : s.Nontrivial) : hs.choose.fst ≠ hs.choose.snd := hs.choose_spec.right.choose_spec.right theorem Nontrivial.mono (hs : s.Nontrivial) (hst : s ⊆ t) : t.Nontrivial := let ⟨x, hx, y, hy, hxy⟩ := hs ⟨x, hst hx, y, hst hy, hxy⟩ theorem nontrivial_pair {x y} (hxy : x ≠ y) : ({x, y} : Set α).Nontrivial := ⟨x, mem_insert _ _, y, mem_insert_of_mem _ (mem_singleton _), hxy⟩ theorem nontrivial_of_pair_subset {x y} (hxy : x ≠ y) (h : {x, y} ⊆ s) : s.Nontrivial := (nontrivial_pair hxy).mono h theorem Nontrivial.pair_subset (hs : s.Nontrivial) : ∃ x y, x ≠ y ∧ {x, y} ⊆ s := let ⟨x, hx, y, hy, hxy⟩ := hs ⟨x, y, hxy, insert_subset hx <| singleton_subset_iff.2 hy⟩ theorem nontrivial_iff_pair_subset : s.Nontrivial ↔ ∃ x y, x ≠ y ∧ {x, y} ⊆ s := ⟨Nontrivial.pair_subset, fun H => let ⟨_, _, hxy, h⟩ := H nontrivial_of_pair_subset hxy h⟩ theorem nontrivial_of_exists_ne {x} (hx : x ∈ s) (h : ∃ y ∈ s, y ≠ x) : s.Nontrivial := let ⟨y, hy, hyx⟩ := h ⟨y, hy, x, hx, hyx⟩ theorem Nontrivial.exists_ne (hs : s.Nontrivial) (z) : ∃ x ∈ s, x ≠ z := by by_contra! H rcases hs with ⟨x, hx, y, hy, hxy⟩ rw [H x hx, H y hy] at hxy exact hxy rfl theorem nontrivial_iff_exists_ne {x} (hx : x ∈ s) : s.Nontrivial ↔ ∃ y ∈ s, y ≠ x := ⟨fun H => H.exists_ne _, nontrivial_of_exists_ne hx⟩ theorem nontrivial_of_lt [Preorder α] {x y} (hx : x ∈ s) (hy : y ∈ s) (hxy : x < y) : s.Nontrivial := ⟨x, hx, y, hy, ne_of_lt hxy⟩ theorem nontrivial_of_exists_lt [Preorder α] (H : ∃ᵉ (x ∈ s) (y ∈ s), x < y) : s.Nontrivial := let ⟨_, hx, _, hy, hxy⟩ := H nontrivial_of_lt hx hy hxy theorem Nontrivial.exists_lt [LinearOrder α] (hs : s.Nontrivial) : ∃ᵉ (x ∈ s) (y ∈ s), x < y := let ⟨x, hx, y, hy, hxy⟩ := hs Or.elim (lt_or_gt_of_ne hxy) (fun H => ⟨x, hx, y, hy, H⟩) fun H => ⟨y, hy, x, hx, H⟩ theorem nontrivial_iff_exists_lt [LinearOrder α] : s.Nontrivial ↔ ∃ᵉ (x ∈ s) (y ∈ s), x < y := ⟨Nontrivial.exists_lt, nontrivial_of_exists_lt⟩ protected theorem Nontrivial.nonempty (hs : s.Nontrivial) : s.Nonempty := let ⟨x, hx, _⟩ := hs ⟨x, hx⟩ protected theorem Nontrivial.ne_empty (hs : s.Nontrivial) : s ≠ ∅ := hs.nonempty.ne_empty theorem Nontrivial.not_subset_empty (hs : s.Nontrivial) : ¬s ⊆ ∅ := hs.nonempty.not_subset_empty @[simp] theorem not_nontrivial_empty : ¬(∅ : Set α).Nontrivial := fun h => h.ne_empty rfl @[simp] theorem not_nontrivial_singleton {x} : ¬({x} : Set α).Nontrivial := fun H => by rw [nontrivial_iff_exists_ne (mem_singleton x)] at H let ⟨y, hy, hya⟩ := H exact hya (mem_singleton_iff.1 hy) theorem Nontrivial.ne_singleton {x} (hs : s.Nontrivial) : s ≠ {x} := fun H => by rw [H] at hs exact not_nontrivial_singleton hs theorem Nontrivial.not_subset_singleton {x} (hs : s.Nontrivial) : ¬s ⊆ {x} := (not_congr subset_singleton_iff_eq).2 (not_or_of_not hs.ne_empty hs.ne_singleton) theorem nontrivial_univ [Nontrivial α] : (univ : Set α).Nontrivial := let ⟨x, y, hxy⟩ := exists_pair_ne α ⟨x, mem_univ _, y, mem_univ _, hxy⟩ theorem nontrivial_of_univ_nontrivial (h : (univ : Set α).Nontrivial) : Nontrivial α := let ⟨x, _, y, _, hxy⟩ := h ⟨⟨x, y, hxy⟩⟩ @[simp] theorem nontrivial_univ_iff : (univ : Set α).Nontrivial ↔ Nontrivial α := ⟨nontrivial_of_univ_nontrivial, fun h => @nontrivial_univ _ h⟩ theorem nontrivial_of_nontrivial (hs : s.Nontrivial) : Nontrivial α := let ⟨x, _, y, _, hxy⟩ := hs ⟨⟨x, y, hxy⟩⟩ /-- `s`, coerced to a type, is a nontrivial type if and only if `s` is a nontrivial set. -/ @[simp, norm_cast] theorem nontrivial_coe_sort {s : Set α} : Nontrivial s ↔ s.Nontrivial := by simp [← nontrivial_univ_iff, Set.Nontrivial] alias ⟨_, Nontrivial.coe_sort⟩ := nontrivial_coe_sort /-- A type with a set `s` whose `coe_sort` is a nontrivial type is nontrivial. For the corresponding result for `Subtype`, see `Subtype.nontrivial_iff_exists_ne`. -/ theorem nontrivial_of_nontrivial_coe (hs : Nontrivial s) : Nontrivial α := nontrivial_of_nontrivial <| nontrivial_coe_sort.1 hs theorem nontrivial_mono {α : Type*} {s t : Set α} (hst : s ⊆ t) (hs : Nontrivial s) : Nontrivial t := Nontrivial.coe_sort <| (nontrivial_coe_sort.1 hs).mono hst @[simp] theorem not_subsingleton_iff : ¬s.Subsingleton ↔ s.Nontrivial := by simp_rw [Set.Subsingleton, Set.Nontrivial, not_forall, exists_prop] @[simp] theorem not_nontrivial_iff : ¬s.Nontrivial ↔ s.Subsingleton := Iff.not_left not_subsingleton_iff.symm alias ⟨_, Subsingleton.not_nontrivial⟩ := not_nontrivial_iff alias ⟨_, Nontrivial.not_subsingleton⟩ := not_subsingleton_iff protected lemma subsingleton_or_nontrivial (s : Set α) : s.Subsingleton ∨ s.Nontrivial := by simp [or_iff_not_imp_right] lemma eq_singleton_or_nontrivial (ha : a ∈ s) : s = {a} ∨ s.Nontrivial := by rw [← subsingleton_iff_singleton ha]; exact s.subsingleton_or_nontrivial lemma nontrivial_iff_ne_singleton (ha : a ∈ s) : s.Nontrivial ↔ s ≠ {a} := ⟨Nontrivial.ne_singleton, (eq_singleton_or_nontrivial ha).resolve_left⟩ lemma Nonempty.exists_eq_singleton_or_nontrivial : s.Nonempty → (∃ a, s = {a}) ∨ s.Nontrivial := fun ⟨a, ha⟩ ↦ (eq_singleton_or_nontrivial ha).imp_left <| Exists.intro a theorem univ_eq_true_false : univ = ({True, False} : Set Prop) := Eq.symm <| eq_univ_of_forall fun x => by rw [mem_insert_iff, mem_singleton_iff] exact Classical.propComplete x end Nontrivial section Monotonicity /-! ### Monotonicity on singletons -/ variable {α : Type u} {β : Type v} {a : α} {s : Set α} [Preorder α] [Preorder β] (f : α → β) protected theorem Subsingleton.monotoneOn (h : s.Subsingleton) : MonotoneOn f s := fun _ ha _ hb _ => (congr_arg _ (h ha hb)).le protected theorem Subsingleton.antitoneOn (h : s.Subsingleton) : AntitoneOn f s := fun _ ha _ hb _ => (congr_arg _ (h hb ha)).le protected theorem Subsingleton.strictMonoOn (h : s.Subsingleton) : StrictMonoOn f s := fun _ ha _ hb hlt => (hlt.ne (h ha hb)).elim protected theorem Subsingleton.strictAntiOn (h : s.Subsingleton) : StrictAntiOn f s := fun _ ha _ hb hlt => (hlt.ne (h ha hb)).elim @[simp] theorem monotoneOn_singleton : MonotoneOn f {a} := subsingleton_singleton.monotoneOn f @[simp] theorem antitoneOn_singleton : AntitoneOn f {a} := subsingleton_singleton.antitoneOn f @[simp] theorem strictMonoOn_singleton : StrictMonoOn f {a} := subsingleton_singleton.strictMonoOn f @[simp] theorem strictAntiOn_singleton : StrictAntiOn f {a} := subsingleton_singleton.strictAntiOn f end Monotonicity end Set
Data\Set\Sups.lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import Mathlib.Data.Set.NAry import Mathlib.Order.UpperLower.Basic import Mathlib.Order.SupClosed /-! # Set family operations This file defines a few binary operations on `Set α` for use in set family combinatorics. ## Main declarations * `s ⊻ t`: Set of elements of the form `a ⊔ b` where `a ∈ s`, `b ∈ t`. * `s ⊼ t`: Set of elements of the form `a ⊓ b` where `a ∈ s`, `b ∈ t`. ## Notation We define the following notation in locale `SetFamily`: * `s ⊻ t` * `s ⊼ t` ## References [B. Bollobás, *Combinatorics*][bollobas1986] -/ open Function variable {F α β : Type*} /-- Notation typeclass for pointwise supremum `⊻`. -/ class HasSups (α : Type*) where /-- The point-wise supremum `a ⊔ b` of `a, b : α`. -/ sups : α → α → α /-- Notation typeclass for pointwise infimum `⊼`. -/ class HasInfs (α : Type*) where /-- The point-wise infimum `a ⊓ b` of `a, b : α`. -/ infs : α → α → α -- This notation is meant to have higher precedence than `⊔` and `⊓`, but still within the -- realm of other binary notation. @[inherit_doc] infixl:74 " ⊻ " => HasSups.sups @[inherit_doc] infixl:75 " ⊼ " => HasInfs.infs namespace Set section Sups variable [SemilatticeSup α] [SemilatticeSup β] [FunLike F α β] [SupHomClass F α β] variable (s s₁ s₂ t t₁ t₂ u v : Set α) /-- `s ⊻ t` is the set of elements of the form `a ⊔ b` where `a ∈ s`, `b ∈ t`. -/ protected def hasSups : HasSups (Set α) := ⟨image2 (· ⊔ ·)⟩ scoped[SetFamily] attribute [instance] Set.hasSups -- Porting note: opening SetFamily, because otherwise the Set.hasSups does not seem to be an -- instance open SetFamily variable {s s₁ s₂ t t₁ t₂ u} {a b c : α} @[simp] theorem mem_sups : c ∈ s ⊻ t ↔ ∃ a ∈ s, ∃ b ∈ t, a ⊔ b = c := by simp [(· ⊻ ·)] theorem sup_mem_sups : a ∈ s → b ∈ t → a ⊔ b ∈ s ⊻ t := mem_image2_of_mem theorem sups_subset : s₁ ⊆ s₂ → t₁ ⊆ t₂ → s₁ ⊻ t₁ ⊆ s₂ ⊻ t₂ := image2_subset theorem sups_subset_left : t₁ ⊆ t₂ → s ⊻ t₁ ⊆ s ⊻ t₂ := image2_subset_left theorem sups_subset_right : s₁ ⊆ s₂ → s₁ ⊻ t ⊆ s₂ ⊻ t := image2_subset_right theorem image_subset_sups_left : b ∈ t → (fun a => a ⊔ b) '' s ⊆ s ⊻ t := image_subset_image2_left theorem image_subset_sups_right : a ∈ s → (· ⊔ ·) a '' t ⊆ s ⊻ t := image_subset_image2_right theorem forall_sups_iff {p : α → Prop} : (∀ c ∈ s ⊻ t, p c) ↔ ∀ a ∈ s, ∀ b ∈ t, p (a ⊔ b) := forall_image2_iff @[simp] theorem sups_subset_iff : s ⊻ t ⊆ u ↔ ∀ a ∈ s, ∀ b ∈ t, a ⊔ b ∈ u := image2_subset_iff @[simp] theorem sups_nonempty : (s ⊻ t).Nonempty ↔ s.Nonempty ∧ t.Nonempty := image2_nonempty_iff protected theorem Nonempty.sups : s.Nonempty → t.Nonempty → (s ⊻ t).Nonempty := Nonempty.image2 theorem Nonempty.of_sups_left : (s ⊻ t).Nonempty → s.Nonempty := Nonempty.of_image2_left theorem Nonempty.of_sups_right : (s ⊻ t).Nonempty → t.Nonempty := Nonempty.of_image2_right @[simp] theorem empty_sups : ∅ ⊻ t = ∅ := image2_empty_left @[simp] theorem sups_empty : s ⊻ ∅ = ∅ := image2_empty_right @[simp] theorem sups_eq_empty : s ⊻ t = ∅ ↔ s = ∅ ∨ t = ∅ := image2_eq_empty_iff @[simp] theorem singleton_sups : {a} ⊻ t = t.image fun b => a ⊔ b := image2_singleton_left @[simp] theorem sups_singleton : s ⊻ {b} = s.image fun a => a ⊔ b := image2_singleton_right theorem singleton_sups_singleton : ({a} ⊻ {b} : Set α) = {a ⊔ b} := image2_singleton theorem sups_union_left : (s₁ ∪ s₂) ⊻ t = s₁ ⊻ t ∪ s₂ ⊻ t := image2_union_left theorem sups_union_right : s ⊻ (t₁ ∪ t₂) = s ⊻ t₁ ∪ s ⊻ t₂ := image2_union_right theorem sups_inter_subset_left : (s₁ ∩ s₂) ⊻ t ⊆ s₁ ⊻ t ∩ s₂ ⊻ t := image2_inter_subset_left theorem sups_inter_subset_right : s ⊻ (t₁ ∩ t₂) ⊆ s ⊻ t₁ ∩ s ⊻ t₂ := image2_inter_subset_right lemma image_sups (f : F) (s t : Set α) : f '' (s ⊻ t) = f '' s ⊻ f '' t := image_image2_distrib <| map_sup f lemma subset_sups_self : s ⊆ s ⊻ s := fun _a ha ↦ mem_sups.2 ⟨_, ha, _, ha, sup_idem _⟩ lemma sups_subset_self : s ⊻ s ⊆ s ↔ SupClosed s := sups_subset_iff @[simp] lemma sups_eq_self : s ⊻ s = s ↔ SupClosed s := subset_sups_self.le.le_iff_eq.symm.trans sups_subset_self lemma sep_sups_le (s t : Set α) (a : α) : {b ∈ s ⊻ t | b ≤ a} = {b ∈ s | b ≤ a} ⊻ {b ∈ t | b ≤ a} := by ext; aesop variable (s t u) theorem iUnion_image_sup_left : ⋃ a ∈ s, (· ⊔ ·) a '' t = s ⊻ t := iUnion_image_left _ theorem iUnion_image_sup_right : ⋃ b ∈ t, (· ⊔ b) '' s = s ⊻ t := iUnion_image_right _ @[simp] theorem image_sup_prod (s t : Set α) : Set.image2 (· ⊔ ·) s t = s ⊻ t := rfl theorem sups_assoc : s ⊻ t ⊻ u = s ⊻ (t ⊻ u) := image2_assoc sup_assoc theorem sups_comm : s ⊻ t = t ⊻ s := image2_comm sup_comm theorem sups_left_comm : s ⊻ (t ⊻ u) = t ⊻ (s ⊻ u) := image2_left_comm sup_left_comm theorem sups_right_comm : s ⊻ t ⊻ u = s ⊻ u ⊻ t := image2_right_comm sup_right_comm theorem sups_sups_sups_comm : s ⊻ t ⊻ (u ⊻ v) = s ⊻ u ⊻ (t ⊻ v) := image2_image2_image2_comm sup_sup_sup_comm end Sups section Infs variable [SemilatticeInf α] [SemilatticeInf β] [FunLike F α β] [InfHomClass F α β] variable (s s₁ s₂ t t₁ t₂ u v : Set α) /-- `s ⊼ t` is the set of elements of the form `a ⊓ b` where `a ∈ s`, `b ∈ t`. -/ protected def hasInfs : HasInfs (Set α) := ⟨image2 (· ⊓ ·)⟩ scoped[SetFamily] attribute [instance] Set.hasInfs -- Porting note: opening SetFamily, because otherwise the Set.hasSups does not seem to be an -- instance open SetFamily variable {s s₁ s₂ t t₁ t₂ u} {a b c : α} @[simp] theorem mem_infs : c ∈ s ⊼ t ↔ ∃ a ∈ s, ∃ b ∈ t, a ⊓ b = c := by simp [(· ⊼ ·)] theorem inf_mem_infs : a ∈ s → b ∈ t → a ⊓ b ∈ s ⊼ t := mem_image2_of_mem theorem infs_subset : s₁ ⊆ s₂ → t₁ ⊆ t₂ → s₁ ⊼ t₁ ⊆ s₂ ⊼ t₂ := image2_subset theorem infs_subset_left : t₁ ⊆ t₂ → s ⊼ t₁ ⊆ s ⊼ t₂ := image2_subset_left theorem infs_subset_right : s₁ ⊆ s₂ → s₁ ⊼ t ⊆ s₂ ⊼ t := image2_subset_right theorem image_subset_infs_left : b ∈ t → (fun a => a ⊓ b) '' s ⊆ s ⊼ t := image_subset_image2_left theorem image_subset_infs_right : a ∈ s → (a ⊓ ·) '' t ⊆ s ⊼ t := image_subset_image2_right theorem forall_infs_iff {p : α → Prop} : (∀ c ∈ s ⊼ t, p c) ↔ ∀ a ∈ s, ∀ b ∈ t, p (a ⊓ b) := forall_image2_iff @[simp] theorem infs_subset_iff : s ⊼ t ⊆ u ↔ ∀ a ∈ s, ∀ b ∈ t, a ⊓ b ∈ u := image2_subset_iff @[simp] theorem infs_nonempty : (s ⊼ t).Nonempty ↔ s.Nonempty ∧ t.Nonempty := image2_nonempty_iff protected theorem Nonempty.infs : s.Nonempty → t.Nonempty → (s ⊼ t).Nonempty := Nonempty.image2 theorem Nonempty.of_infs_left : (s ⊼ t).Nonempty → s.Nonempty := Nonempty.of_image2_left theorem Nonempty.of_infs_right : (s ⊼ t).Nonempty → t.Nonempty := Nonempty.of_image2_right @[simp] theorem empty_infs : ∅ ⊼ t = ∅ := image2_empty_left @[simp] theorem infs_empty : s ⊼ ∅ = ∅ := image2_empty_right @[simp] theorem infs_eq_empty : s ⊼ t = ∅ ↔ s = ∅ ∨ t = ∅ := image2_eq_empty_iff @[simp] theorem singleton_infs : {a} ⊼ t = t.image fun b => a ⊓ b := image2_singleton_left @[simp] theorem infs_singleton : s ⊼ {b} = s.image fun a => a ⊓ b := image2_singleton_right theorem singleton_infs_singleton : ({a} ⊼ {b} : Set α) = {a ⊓ b} := image2_singleton theorem infs_union_left : (s₁ ∪ s₂) ⊼ t = s₁ ⊼ t ∪ s₂ ⊼ t := image2_union_left theorem infs_union_right : s ⊼ (t₁ ∪ t₂) = s ⊼ t₁ ∪ s ⊼ t₂ := image2_union_right theorem infs_inter_subset_left : (s₁ ∩ s₂) ⊼ t ⊆ s₁ ⊼ t ∩ s₂ ⊼ t := image2_inter_subset_left theorem infs_inter_subset_right : s ⊼ (t₁ ∩ t₂) ⊆ s ⊼ t₁ ∩ s ⊼ t₂ := image2_inter_subset_right lemma image_infs (f : F) (s t : Set α) : f '' (s ⊼ t) = f '' s ⊼ f '' t := image_image2_distrib <| map_inf f lemma subset_infs_self : s ⊆ s ⊼ s := fun _a ha ↦ mem_infs.2 ⟨_, ha, _, ha, inf_idem _⟩ lemma infs_self_subset : s ⊼ s ⊆ s ↔ InfClosed s := infs_subset_iff @[simp] lemma infs_self : s ⊼ s = s ↔ InfClosed s := subset_infs_self.le.le_iff_eq.symm.trans infs_self_subset lemma sep_infs_le (s t : Set α) (a : α) : {b ∈ s ⊼ t | a ≤ b} = {b ∈ s | a ≤ b} ⊼ {b ∈ t | a ≤ b} := by ext; aesop variable (s t u) theorem iUnion_image_inf_left : ⋃ a ∈ s, (a ⊓ ·) '' t = s ⊼ t := iUnion_image_left _ theorem iUnion_image_inf_right : ⋃ b ∈ t, (· ⊓ b) '' s = s ⊼ t := iUnion_image_right _ @[simp] theorem image_inf_prod (s t : Set α) : Set.image2 (fun x x_1 => x ⊓ x_1) s t = s ⊼ t := by have : (s ×ˢ t).image (uncurry (· ⊓ ·)) = Set.image2 (fun x x_1 => x ⊓ x_1) s t := by simp only [Set.image_uncurry_prod] rw [← this] exact image_uncurry_prod _ _ _ theorem infs_assoc : s ⊼ t ⊼ u = s ⊼ (t ⊼ u) := image2_assoc inf_assoc theorem infs_comm : s ⊼ t = t ⊼ s := image2_comm inf_comm theorem infs_left_comm : s ⊼ (t ⊼ u) = t ⊼ (s ⊼ u) := image2_left_comm inf_left_comm theorem infs_right_comm : s ⊼ t ⊼ u = s ⊼ u ⊼ t := image2_right_comm inf_right_comm theorem infs_infs_infs_comm : s ⊼ t ⊼ (u ⊼ v) = s ⊼ u ⊼ (t ⊼ v) := image2_image2_image2_comm inf_inf_inf_comm end Infs open SetFamily section DistribLattice variable [DistribLattice α] (s t u : Set α) theorem sups_infs_subset_left : s ⊻ t ⊼ u ⊆ (s ⊻ t) ⊼ (s ⊻ u) := image2_distrib_subset_left sup_inf_left theorem sups_infs_subset_right : t ⊼ u ⊻ s ⊆ (t ⊻ s) ⊼ (u ⊻ s) := image2_distrib_subset_right sup_inf_right theorem infs_sups_subset_left : s ⊼ (t ⊻ u) ⊆ s ⊼ t ⊻ s ⊼ u := image2_distrib_subset_left inf_sup_left theorem infs_sups_subset_right : (t ⊻ u) ⊼ s ⊆ t ⊼ s ⊻ u ⊼ s := image2_distrib_subset_right inf_sup_right end DistribLattice end Set open SetFamily @[simp] theorem upperClosure_sups [SemilatticeSup α] (s t : Set α) : upperClosure (s ⊻ t) = upperClosure s ⊔ upperClosure t := by ext a simp only [SetLike.mem_coe, mem_upperClosure, Set.mem_sups, exists_and_left, exists_prop, UpperSet.coe_sup, Set.mem_inter_iff] constructor · rintro ⟨_, ⟨b, hb, c, hc, rfl⟩, ha⟩ exact ⟨⟨b, hb, le_sup_left.trans ha⟩, c, hc, le_sup_right.trans ha⟩ · rintro ⟨⟨b, hb, hab⟩, c, hc, hac⟩ exact ⟨_, ⟨b, hb, c, hc, rfl⟩, sup_le hab hac⟩ @[simp] theorem lowerClosure_infs [SemilatticeInf α] (s t : Set α) : lowerClosure (s ⊼ t) = lowerClosure s ⊓ lowerClosure t := by ext a simp only [SetLike.mem_coe, mem_lowerClosure, Set.mem_infs, exists_and_left, exists_prop, LowerSet.coe_sup, Set.mem_inter_iff] constructor · rintro ⟨_, ⟨b, hb, c, hc, rfl⟩, ha⟩ exact ⟨⟨b, hb, ha.trans inf_le_left⟩, c, hc, ha.trans inf_le_right⟩ · rintro ⟨⟨b, hb, hab⟩, c, hc, hac⟩ exact ⟨_, ⟨b, hb, c, hc, rfl⟩, le_inf hab hac⟩
Data\Set\UnionLift.lean
/- Copyright (c) 2021 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import Mathlib.Data.Set.Lattice import Mathlib.Order.Directed /-! # Union lift This file defines `Set.iUnionLift` to glue together functions defined on each of a collection of sets to make a function on the Union of those sets. ## Main definitions * `Set.iUnionLift` - Given a Union of sets `iUnion S`, define a function on any subset of the Union by defining it on each component, and proving that it agrees on the intersections. * `Set.liftCover` - Version of `Set.iUnionLift` for the special case that the sets cover the entire type. ## Main statements There are proofs of the obvious properties of `iUnionLift`, i.e. what it does to elements of each of the sets in the `iUnion`, stated in different ways. There are also three lemmas about `iUnionLift` intended to aid with proving that `iUnionLift` is a homomorphism when defined on a Union of substructures. There is one lemma each to show that constants, unary functions, or binary functions are preserved. These lemmas are: *`Set.iUnionLift_const` *`Set.iUnionLift_unary` *`Set.iUnionLift_binary` ## Tags directed union, directed supremum, glue, gluing -/ variable {α : Type*} {ι β : Sort _} namespace Set section UnionLift /- The unused argument is left in the definition so that the `simp` lemmas `iUnionLift_inclusion` will work without the user having to provide it explicitly to simplify terms involving `iUnionLift`. -/ /-- Given a union of sets `iUnion S`, define a function on the Union by defining it on each component, and proving that it agrees on the intersections. -/ @[nolint unusedArguments] noncomputable def iUnionLift (S : ι → Set α) (f : ∀ i, S i → β) (_ : ∀ (i j) (x : α) (hxi : x ∈ S i) (hxj : x ∈ S j), f i ⟨x, hxi⟩ = f j ⟨x, hxj⟩) (T : Set α) (hT : T ⊆ iUnion S) (x : T) : β := let i := Classical.indefiniteDescription _ (mem_iUnion.1 (hT x.prop)) f i ⟨x, i.prop⟩ variable {S : ι → Set α} {f : ∀ i, S i → β} {hf : ∀ (i j) (x : α) (hxi : x ∈ S i) (hxj : x ∈ S j), f i ⟨x, hxi⟩ = f j ⟨x, hxj⟩} {T : Set α} {hT : T ⊆ iUnion S} (hT' : T = iUnion S) @[simp] theorem iUnionLift_mk {i : ι} (x : S i) (hx : (x : α) ∈ T) : iUnionLift S f hf T hT ⟨x, hx⟩ = f i x := hf _ i x _ _ @[simp] theorem iUnionLift_inclusion {i : ι} (x : S i) (h : S i ⊆ T) : iUnionLift S f hf T hT (Set.inclusion h x) = f i x := iUnionLift_mk x _ theorem iUnionLift_of_mem (x : T) {i : ι} (hx : (x : α) ∈ S i) : iUnionLift S f hf T hT x = f i ⟨x, hx⟩ := by cases' x with x hx; exact hf _ _ _ _ _ theorem preimage_iUnionLift (t : Set β) : iUnionLift S f hf T hT ⁻¹' t = inclusion hT ⁻¹' (⋃ i, inclusion (subset_iUnion S i) '' (f i ⁻¹' t)) := by ext x simp only [mem_preimage, mem_iUnion, mem_image] constructor · rcases mem_iUnion.1 (hT x.prop) with ⟨i, hi⟩ refine fun h => ⟨i, ⟨x, hi⟩, ?_, rfl⟩ rwa [iUnionLift_of_mem x hi] at h · rintro ⟨i, ⟨y, hi⟩, h, hxy⟩ obtain rfl : y = x := congr_arg Subtype.val hxy rwa [iUnionLift_of_mem x hi] /-- `iUnionLift_const` is useful for proving that `iUnionLift` is a homomorphism of algebraic structures when defined on the Union of algebraic subobjects. For example, it could be used to prove that the lift of a collection of group homomorphisms on a union of subgroups preserves `1`. -/ theorem iUnionLift_const (c : T) (ci : ∀ i, S i) (hci : ∀ i, (ci i : α) = c) (cβ : β) (h : ∀ i, f i (ci i) = cβ) : iUnionLift S f hf T hT c = cβ := by let ⟨i, hi⟩ := Set.mem_iUnion.1 (hT c.prop) have : ci i = ⟨c, hi⟩ := Subtype.ext (hci i) rw [iUnionLift_of_mem _ hi, ← this, h] /-- `iUnionLift_unary` is useful for proving that `iUnionLift` is a homomorphism of algebraic structures when defined on the Union of algebraic subobjects. For example, it could be used to prove that the lift of a collection of linear_maps on a union of submodules preserves scalar multiplication. -/ theorem iUnionLift_unary (u : T → T) (ui : ∀ i, S i → S i) (hui : ∀ (i) (x : S i), u (Set.inclusion (show S i ⊆ T from hT'.symm ▸ Set.subset_iUnion S i) x) = Set.inclusion (show S i ⊆ T from hT'.symm ▸ Set.subset_iUnion S i) (ui i x)) (uβ : β → β) (h : ∀ (i) (x : S i), f i (ui i x) = uβ (f i x)) (x : T) : iUnionLift S f hf T (le_of_eq hT') (u x) = uβ (iUnionLift S f hf T (le_of_eq hT') x) := by clear hT -- this prevents the argument from getting inserted by accident. subst hT' cases' Set.mem_iUnion.1 x.prop with i hi rw [iUnionLift_of_mem x hi, ← h i] have : x = Set.inclusion (Set.subset_iUnion S i) ⟨x, hi⟩ := by cases x rfl conv_lhs => rw [this, hui, iUnionLift_inclusion] /-- `iUnionLift_binary` is useful for proving that `iUnionLift` is a homomorphism of algebraic structures when defined on the Union of algebraic subobjects. For example, it could be used to prove that the lift of a collection of group homomorphisms on a union of subgroups preserves `*`. -/ theorem iUnionLift_binary (dir : Directed (· ≤ ·) S) (op : T → T → T) (opi : ∀ i, S i → S i → S i) (hopi : ∀ i x y, Set.inclusion (show S i ⊆ T from hT'.symm ▸ Set.subset_iUnion S i) (opi i x y) = op (Set.inclusion (show S i ⊆ T from hT'.symm ▸ Set.subset_iUnion S i) x) (Set.inclusion (show S i ⊆ T from hT'.symm ▸ Set.subset_iUnion S i) y)) (opβ : β → β → β) (h : ∀ (i) (x y : S i), f i (opi i x y) = opβ (f i x) (f i y)) (x y : T) : iUnionLift S f hf T (le_of_eq hT') (op x y) = opβ (iUnionLift S f hf T (le_of_eq hT') x) (iUnionLift S f hf T (le_of_eq hT') y) := by clear hT -- this prevents the argument from getting inserted by accident. subst hT' cases' Set.mem_iUnion.1 x.prop with i hi cases' Set.mem_iUnion.1 y.prop with j hj rcases dir i j with ⟨k, hik, hjk⟩ rw [iUnionLift_of_mem x (hik hi), iUnionLift_of_mem y (hjk hj), ← h k] have hx : x = Set.inclusion (Set.subset_iUnion S k) ⟨x, hik hi⟩ := by cases x rfl have hy : y = Set.inclusion (Set.subset_iUnion S k) ⟨y, hjk hj⟩ := by cases y rfl have hxy : (Set.inclusion (Set.subset_iUnion S k) (opi k ⟨x, hik hi⟩ ⟨y, hjk hj⟩) : α) ∈ S k := (opi k ⟨x, hik hi⟩ ⟨y, hjk hj⟩).prop conv_lhs => rw [hx, hy, ← hopi, iUnionLift_of_mem _ hxy] rfl end UnionLift variable {S : ι → Set α} {f : ∀ i, S i → β} {hf : ∀ (i j) (x : α) (hxi : x ∈ S i) (hxj : x ∈ S j), f i ⟨x, hxi⟩ = f j ⟨x, hxj⟩} {hS : iUnion S = univ} /-- Glue together functions defined on each of a collection `S` of sets that cover a type. See also `Set.iUnionLift`. -/ noncomputable def liftCover (S : ι → Set α) (f : ∀ i, S i → β) (hf : ∀ (i j) (x : α) (hxi : x ∈ S i) (hxj : x ∈ S j), f i ⟨x, hxi⟩ = f j ⟨x, hxj⟩) (hS : iUnion S = univ) (a : α) : β := iUnionLift S f hf univ hS.symm.subset ⟨a, trivial⟩ @[simp] theorem liftCover_coe {i : ι} (x : S i) : liftCover S f hf hS x = f i x := iUnionLift_mk x _ theorem liftCover_of_mem {i : ι} {x : α} (hx : (x : α) ∈ S i) : liftCover S f hf hS x = f i ⟨x, hx⟩ := iUnionLift_of_mem (⟨x, trivial⟩ : {_z // True}) hx theorem preimage_liftCover (t : Set β) : liftCover S f hf hS ⁻¹' t = ⋃ i, (↑) '' (f i ⁻¹' t) := by change (iUnionLift S f hf univ hS.symm.subset ∘ fun a => ⟨a, mem_univ a⟩) ⁻¹' t = _ rw [preimage_comp, preimage_iUnionLift] ext; simp end Set
Data\Set\Pairwise\Basic.lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import Mathlib.Data.Set.Function import Mathlib.Logic.Pairwise import Mathlib.Logic.Relation /-! # Relations holding pairwise This file develops pairwise relations and defines pairwise disjoint indexed sets. We also prove many basic facts about `Pairwise`. It is possible that an intermediate file, with more imports than `Logic.Pairwise` but not importing `Data.Set.Function` would be appropriate to hold many of these basic facts. ## Main declarations * `Set.PairwiseDisjoint`: `s.PairwiseDisjoint f` states that images under `f` of distinct elements of `s` are either equal or `Disjoint`. ## Notes The spelling `s.PairwiseDisjoint id` is preferred over `s.Pairwise Disjoint` to permit dot notation on `Set.PairwiseDisjoint`, even though the latter unfolds to something nicer. -/ open Function Order Set variable {α β γ ι ι' : Type*} {r p q : α → α → Prop} section Pairwise variable {f g : ι → α} {s t u : Set α} {a b : α} theorem pairwise_on_bool (hr : Symmetric r) {a b : α} : Pairwise (r on fun c => cond c a b) ↔ r a b := by simpa [Pairwise, Function.onFun] using @hr a b theorem pairwise_disjoint_on_bool [SemilatticeInf α] [OrderBot α] {a b : α} : Pairwise (Disjoint on fun c => cond c a b) ↔ Disjoint a b := pairwise_on_bool Disjoint.symm theorem Symmetric.pairwise_on [LinearOrder ι] (hr : Symmetric r) (f : ι → α) : Pairwise (r on f) ↔ ∀ ⦃m n⦄, m < n → r (f m) (f n) := ⟨fun h _m _n hmn => h hmn.ne, fun h _m _n hmn => hmn.lt_or_lt.elim (@h _ _) fun h' => hr (h h')⟩ theorem pairwise_disjoint_on [SemilatticeInf α] [OrderBot α] [LinearOrder ι] (f : ι → α) : Pairwise (Disjoint on f) ↔ ∀ ⦃m n⦄, m < n → Disjoint (f m) (f n) := Symmetric.pairwise_on Disjoint.symm f theorem pairwise_disjoint_mono [SemilatticeInf α] [OrderBot α] (hs : Pairwise (Disjoint on f)) (h : g ≤ f) : Pairwise (Disjoint on g) := hs.mono fun i j hij => Disjoint.mono (h i) (h j) hij namespace Set theorem Pairwise.mono (h : t ⊆ s) (hs : s.Pairwise r) : t.Pairwise r := fun _x xt _y yt => hs (h xt) (h yt) theorem Pairwise.mono' (H : r ≤ p) (hr : s.Pairwise r) : s.Pairwise p := hr.imp H theorem pairwise_top (s : Set α) : s.Pairwise ⊤ := pairwise_of_forall s _ fun _ _ => trivial protected theorem Subsingleton.pairwise (h : s.Subsingleton) (r : α → α → Prop) : s.Pairwise r := fun _x hx _y hy hne => (hne (h hx hy)).elim @[simp] theorem pairwise_empty (r : α → α → Prop) : (∅ : Set α).Pairwise r := subsingleton_empty.pairwise r @[simp] theorem pairwise_singleton (a : α) (r : α → α → Prop) : Set.Pairwise {a} r := subsingleton_singleton.pairwise r theorem pairwise_iff_of_refl [IsRefl α r] : s.Pairwise r ↔ ∀ ⦃a⦄, a ∈ s → ∀ ⦃b⦄, b ∈ s → r a b := forall₄_congr fun _ _ _ _ => or_iff_not_imp_left.symm.trans <| or_iff_right_of_imp of_eq alias ⟨Pairwise.of_refl, _⟩ := pairwise_iff_of_refl theorem Nonempty.pairwise_iff_exists_forall [IsEquiv α r] {s : Set ι} (hs : s.Nonempty) : s.Pairwise (r on f) ↔ ∃ z, ∀ x ∈ s, r (f x) z := by constructor · rcases hs with ⟨y, hy⟩ refine fun H => ⟨f y, fun x hx => ?_⟩ rcases eq_or_ne x y with (rfl | hne) · apply IsRefl.refl · exact H hx hy hne · rintro ⟨z, hz⟩ x hx y hy _ exact @IsTrans.trans α r _ (f x) z (f y) (hz _ hx) (IsSymm.symm _ _ <| hz _ hy) /-- For a nonempty set `s`, a function `f` takes pairwise equal values on `s` if and only if for some `z` in the codomain, `f` takes value `z` on all `x ∈ s`. See also `Set.pairwise_eq_iff_exists_eq` for a version that assumes `[Nonempty ι]` instead of `Set.Nonempty s`. -/ theorem Nonempty.pairwise_eq_iff_exists_eq {s : Set α} (hs : s.Nonempty) {f : α → ι} : (s.Pairwise fun x y => f x = f y) ↔ ∃ z, ∀ x ∈ s, f x = z := hs.pairwise_iff_exists_forall theorem pairwise_iff_exists_forall [Nonempty ι] (s : Set α) (f : α → ι) {r : ι → ι → Prop} [IsEquiv ι r] : s.Pairwise (r on f) ↔ ∃ z, ∀ x ∈ s, r (f x) z := by rcases s.eq_empty_or_nonempty with (rfl | hne) · simp · exact hne.pairwise_iff_exists_forall /-- A function `f : α → ι` with nonempty codomain takes pairwise equal values on a set `s` if and only if for some `z` in the codomain, `f` takes value `z` on all `x ∈ s`. See also `Set.Nonempty.pairwise_eq_iff_exists_eq` for a version that assumes `Set.Nonempty s` instead of `[Nonempty ι]`. -/ theorem pairwise_eq_iff_exists_eq [Nonempty ι] (s : Set α) (f : α → ι) : (s.Pairwise fun x y => f x = f y) ↔ ∃ z, ∀ x ∈ s, f x = z := pairwise_iff_exists_forall s f theorem pairwise_union : (s ∪ t).Pairwise r ↔ s.Pairwise r ∧ t.Pairwise r ∧ ∀ a ∈ s, ∀ b ∈ t, a ≠ b → r a b ∧ r b a := by simp only [Set.Pairwise, mem_union, or_imp, forall_and] exact ⟨fun H => ⟨H.1.1, H.2.2, H.1.2, fun x hx y hy hne => H.2.1 y hy x hx hne.symm⟩, fun H => ⟨⟨H.1, H.2.2.1⟩, fun x hx y hy hne => H.2.2.2 y hy x hx hne.symm, H.2.1⟩⟩ theorem pairwise_union_of_symmetric (hr : Symmetric r) : (s ∪ t).Pairwise r ↔ s.Pairwise r ∧ t.Pairwise r ∧ ∀ a ∈ s, ∀ b ∈ t, a ≠ b → r a b := pairwise_union.trans <| by simp only [hr.iff, and_self_iff] theorem pairwise_insert : (insert a s).Pairwise r ↔ s.Pairwise r ∧ ∀ b ∈ s, a ≠ b → r a b ∧ r b a := by simp only [insert_eq, pairwise_union, pairwise_singleton, true_and_iff, mem_singleton_iff, forall_eq] theorem pairwise_insert_of_not_mem (ha : a ∉ s) : (insert a s).Pairwise r ↔ s.Pairwise r ∧ ∀ b ∈ s, r a b ∧ r b a := pairwise_insert.trans <| and_congr_right' <| forall₂_congr fun b hb => by simp [(ne_of_mem_of_not_mem hb ha).symm] protected theorem Pairwise.insert (hs : s.Pairwise r) (h : ∀ b ∈ s, a ≠ b → r a b ∧ r b a) : (insert a s).Pairwise r := pairwise_insert.2 ⟨hs, h⟩ theorem Pairwise.insert_of_not_mem (ha : a ∉ s) (hs : s.Pairwise r) (h : ∀ b ∈ s, r a b ∧ r b a) : (insert a s).Pairwise r := (pairwise_insert_of_not_mem ha).2 ⟨hs, h⟩ theorem pairwise_insert_of_symmetric (hr : Symmetric r) : (insert a s).Pairwise r ↔ s.Pairwise r ∧ ∀ b ∈ s, a ≠ b → r a b := by simp only [pairwise_insert, hr.iff a, and_self_iff] theorem pairwise_insert_of_symmetric_of_not_mem (hr : Symmetric r) (ha : a ∉ s) : (insert a s).Pairwise r ↔ s.Pairwise r ∧ ∀ b ∈ s, r a b := by simp only [pairwise_insert_of_not_mem ha, hr.iff a, and_self_iff] theorem Pairwise.insert_of_symmetric (hs : s.Pairwise r) (hr : Symmetric r) (h : ∀ b ∈ s, a ≠ b → r a b) : (insert a s).Pairwise r := (pairwise_insert_of_symmetric hr).2 ⟨hs, h⟩ theorem Pairwise.insert_of_symmetric_of_not_mem (hs : s.Pairwise r) (hr : Symmetric r) (ha : a ∉ s) (h : ∀ b ∈ s, r a b) : (insert a s).Pairwise r := (pairwise_insert_of_symmetric_of_not_mem hr ha).2 ⟨hs, h⟩ theorem pairwise_pair : Set.Pairwise {a, b} r ↔ a ≠ b → r a b ∧ r b a := by simp [pairwise_insert] theorem pairwise_pair_of_symmetric (hr : Symmetric r) : Set.Pairwise {a, b} r ↔ a ≠ b → r a b := by simp [pairwise_insert_of_symmetric hr] theorem pairwise_univ : (univ : Set α).Pairwise r ↔ Pairwise r := by simp only [Set.Pairwise, Pairwise, mem_univ, forall_const] @[simp] theorem pairwise_bot_iff : s.Pairwise (⊥ : α → α → Prop) ↔ (s : Set α).Subsingleton := ⟨fun h _a ha _b hb => h.eq ha hb id, fun h => h.pairwise _⟩ alias ⟨Pairwise.subsingleton, _⟩ := pairwise_bot_iff /-- See also `Function.injective_iff_pairwise_ne` -/ lemma injOn_iff_pairwise_ne {s : Set ι} : InjOn f s ↔ s.Pairwise (f · ≠ f ·) := by simp only [InjOn, Set.Pairwise, not_imp_not] alias ⟨InjOn.pairwise_ne, _⟩ := injOn_iff_pairwise_ne protected theorem Pairwise.image {s : Set ι} (h : s.Pairwise (r on f)) : (f '' s).Pairwise r := forall_mem_image.2 fun _x hx ↦ forall_mem_image.2 fun _y hy hne ↦ h hx hy <| ne_of_apply_ne _ hne /-- See also `Set.Pairwise.image`. -/ theorem InjOn.pairwise_image {s : Set ι} (h : s.InjOn f) : (f '' s).Pairwise r ↔ s.Pairwise (r on f) := by simp (config := { contextual := true }) [h.eq_iff, Set.Pairwise] lemma _root_.Pairwise.range_pairwise (hr : Pairwise (r on f)) : (Set.range f).Pairwise r := image_univ ▸ (pairwise_univ.mpr hr).image end Set end Pairwise theorem pairwise_subtype_iff_pairwise_set (s : Set α) (r : α → α → Prop) : (Pairwise fun (x : s) (y : s) => r x y) ↔ s.Pairwise r := by simp only [Pairwise, Set.Pairwise, SetCoe.forall, Ne, Subtype.ext_iff, Subtype.coe_mk] alias ⟨Pairwise.set_of_subtype, Set.Pairwise.subtype⟩ := pairwise_subtype_iff_pairwise_set namespace Set section PartialOrderBot variable [PartialOrder α] [OrderBot α] {s t : Set ι} {f g : ι → α} /-- A set is `PairwiseDisjoint` under `f`, if the images of any distinct two elements under `f` are disjoint. `s.Pairwise Disjoint` is (definitionally) the same as `s.PairwiseDisjoint id`. We prefer the latter in order to allow dot notation on `Set.PairwiseDisjoint`, even though the former unfolds more nicely. -/ def PairwiseDisjoint (s : Set ι) (f : ι → α) : Prop := s.Pairwise (Disjoint on f) theorem PairwiseDisjoint.subset (ht : t.PairwiseDisjoint f) (h : s ⊆ t) : s.PairwiseDisjoint f := Pairwise.mono h ht theorem PairwiseDisjoint.mono_on (hs : s.PairwiseDisjoint f) (h : ∀ ⦃i⦄, i ∈ s → g i ≤ f i) : s.PairwiseDisjoint g := fun _a ha _b hb hab => (hs ha hb hab).mono (h ha) (h hb) theorem PairwiseDisjoint.mono (hs : s.PairwiseDisjoint f) (h : g ≤ f) : s.PairwiseDisjoint g := hs.mono_on fun i _ => h i @[simp] theorem pairwiseDisjoint_empty : (∅ : Set ι).PairwiseDisjoint f := pairwise_empty _ @[simp] theorem pairwiseDisjoint_singleton (i : ι) (f : ι → α) : PairwiseDisjoint {i} f := pairwise_singleton i _ theorem pairwiseDisjoint_insert {i : ι} : (insert i s).PairwiseDisjoint f ↔ s.PairwiseDisjoint f ∧ ∀ j ∈ s, i ≠ j → Disjoint (f i) (f j) := pairwise_insert_of_symmetric <| symmetric_disjoint.comap f theorem pairwiseDisjoint_insert_of_not_mem {i : ι} (hi : i ∉ s) : (insert i s).PairwiseDisjoint f ↔ s.PairwiseDisjoint f ∧ ∀ j ∈ s, Disjoint (f i) (f j) := pairwise_insert_of_symmetric_of_not_mem (symmetric_disjoint.comap f) hi protected theorem PairwiseDisjoint.insert (hs : s.PairwiseDisjoint f) {i : ι} (h : ∀ j ∈ s, i ≠ j → Disjoint (f i) (f j)) : (insert i s).PairwiseDisjoint f := pairwiseDisjoint_insert.2 ⟨hs, h⟩ theorem PairwiseDisjoint.insert_of_not_mem (hs : s.PairwiseDisjoint f) {i : ι} (hi : i ∉ s) (h : ∀ j ∈ s, Disjoint (f i) (f j)) : (insert i s).PairwiseDisjoint f := (pairwiseDisjoint_insert_of_not_mem hi).2 ⟨hs, h⟩ theorem PairwiseDisjoint.image_of_le (hs : s.PairwiseDisjoint f) {g : ι → ι} (hg : f ∘ g ≤ f) : (g '' s).PairwiseDisjoint f := by rintro _ ⟨a, ha, rfl⟩ _ ⟨b, hb, rfl⟩ h exact (hs ha hb <| ne_of_apply_ne _ h).mono (hg a) (hg b) theorem InjOn.pairwiseDisjoint_image {g : ι' → ι} {s : Set ι'} (h : s.InjOn g) : (g '' s).PairwiseDisjoint f ↔ s.PairwiseDisjoint (f ∘ g) := h.pairwise_image theorem PairwiseDisjoint.range (g : s → ι) (hg : ∀ i : s, f (g i) ≤ f i) (ht : s.PairwiseDisjoint f) : (range g).PairwiseDisjoint f := by rintro _ ⟨x, rfl⟩ _ ⟨y, rfl⟩ hxy exact ((ht x.2 y.2) fun h => hxy <| congr_arg g <| Subtype.ext h).mono (hg x) (hg y) theorem pairwiseDisjoint_union : (s ∪ t).PairwiseDisjoint f ↔ s.PairwiseDisjoint f ∧ t.PairwiseDisjoint f ∧ ∀ ⦃i⦄, i ∈ s → ∀ ⦃j⦄, j ∈ t → i ≠ j → Disjoint (f i) (f j) := pairwise_union_of_symmetric <| symmetric_disjoint.comap f theorem PairwiseDisjoint.union (hs : s.PairwiseDisjoint f) (ht : t.PairwiseDisjoint f) (h : ∀ ⦃i⦄, i ∈ s → ∀ ⦃j⦄, j ∈ t → i ≠ j → Disjoint (f i) (f j)) : (s ∪ t).PairwiseDisjoint f := pairwiseDisjoint_union.2 ⟨hs, ht, h⟩ -- classical theorem PairwiseDisjoint.elim (hs : s.PairwiseDisjoint f) {i j : ι} (hi : i ∈ s) (hj : j ∈ s) (h : ¬Disjoint (f i) (f j)) : i = j := hs.eq hi hj h lemma PairwiseDisjoint.eq_or_disjoint (h : s.PairwiseDisjoint f) {i j : ι} (hi : i ∈ s) (hj : j ∈ s) : i = j ∨ Disjoint (f i) (f j) := by rw [or_iff_not_imp_right] exact h.elim hi hj lemma pairwiseDisjoint_range_iff {α β : Type*} {f : α → (Set β)} : (Set.range f).PairwiseDisjoint id ↔ ∀ x y, f x = f y ∨ Disjoint (f x) (f y) := by constructor · intro h x y apply h.eq_or_disjoint (Set.mem_range_self x) (Set.mem_range_self y) · rintro h _ ⟨x, rfl⟩ _ ⟨y, rfl⟩ hxy exact (h x y).resolve_left hxy /-- If the range of `f` is pairwise disjoint, then the image of any set `s` under `f` is as well. -/ lemma _root_.Pairwise.pairwiseDisjoint (h : Pairwise (Disjoint on f)) (s : Set ι) : s.PairwiseDisjoint f := h.set_pairwise s end PartialOrderBot section SemilatticeInfBot variable [SemilatticeInf α] [OrderBot α] {s t : Set ι} {f g : ι → α} -- classical theorem PairwiseDisjoint.elim' (hs : s.PairwiseDisjoint f) {i j : ι} (hi : i ∈ s) (hj : j ∈ s) (h : f i ⊓ f j ≠ ⊥) : i = j := (hs.elim hi hj) fun hij => h hij.eq_bot theorem PairwiseDisjoint.eq_of_le (hs : s.PairwiseDisjoint f) {i j : ι} (hi : i ∈ s) (hj : j ∈ s) (hf : f i ≠ ⊥) (hij : f i ≤ f j) : i = j := (hs.elim' hi hj) fun h => hf <| (inf_of_le_left hij).symm.trans h end SemilatticeInfBot /-! ### Pairwise disjoint set of sets -/ variable {s : Set ι} {t : Set ι'} theorem pairwiseDisjoint_range_singleton : (range (singleton : ι → Set ι)).PairwiseDisjoint id := Pairwise.range_pairwise fun _ _ => disjoint_singleton.2 theorem pairwiseDisjoint_fiber (f : ι → α) (s : Set α) : s.PairwiseDisjoint fun a => f ⁻¹' {a} := fun _a _ _b _ h => disjoint_iff_inf_le.mpr fun _i ⟨hia, hib⟩ => h <| (Eq.symm hia).trans hib -- classical theorem PairwiseDisjoint.elim_set {s : Set ι} {f : ι → Set α} (hs : s.PairwiseDisjoint f) {i j : ι} (hi : i ∈ s) (hj : j ∈ s) (a : α) (hai : a ∈ f i) (haj : a ∈ f j) : i = j := hs.elim hi hj <| not_disjoint_iff.2 ⟨a, hai, haj⟩ theorem PairwiseDisjoint.prod {f : ι → Set α} {g : ι' → Set β} (hs : s.PairwiseDisjoint f) (ht : t.PairwiseDisjoint g) : (s ×ˢ t : Set (ι × ι')).PairwiseDisjoint fun i => f i.1 ×ˢ g i.2 := fun ⟨_, _⟩ ⟨hi, hi'⟩ ⟨_, _⟩ ⟨hj, hj'⟩ hij => disjoint_left.2 fun ⟨_, _⟩ ⟨hai, hbi⟩ ⟨haj, hbj⟩ => hij <| Prod.ext (hs.elim_set hi hj _ hai haj) <| ht.elim_set hi' hj' _ hbi hbj theorem pairwiseDisjoint_pi {ι' α : ι → Type*} {s : ∀ i, Set (ι' i)} {f : ∀ i, ι' i → Set (α i)} (hs : ∀ i, (s i).PairwiseDisjoint (f i)) : ((univ : Set ι).pi s).PairwiseDisjoint fun I => (univ : Set ι).pi fun i => f _ (I i) := fun _ hI _ hJ hIJ => disjoint_left.2 fun a haI haJ => hIJ <| funext fun i => (hs i).elim_set (hI i trivial) (hJ i trivial) (a i) (haI i trivial) (haJ i trivial) /-- The partial images of a binary function `f` whose partial evaluations are injective are pairwise disjoint iff `f` is injective . -/ theorem pairwiseDisjoint_image_right_iff {f : α → β → γ} {s : Set α} {t : Set β} (hf : ∀ a ∈ s, Injective (f a)) : (s.PairwiseDisjoint fun a => f a '' t) ↔ (s ×ˢ t).InjOn fun p => f p.1 p.2 := by refine ⟨fun hs x hx y hy (h : f _ _ = _) => ?_, fun hs x hx y hy h => ?_⟩ · suffices x.1 = y.1 by exact Prod.ext this (hf _ hx.1 <| h.trans <| by rw [this]) refine hs.elim hx.1 hy.1 (not_disjoint_iff.2 ⟨_, mem_image_of_mem _ hx.2, ?_⟩) rw [h] exact mem_image_of_mem _ hy.2 · refine disjoint_iff_inf_le.mpr ?_ rintro _ ⟨⟨a, ha, hab⟩, b, hb, rfl⟩ exact h (congr_arg Prod.fst <| hs (mk_mem_prod hx ha) (mk_mem_prod hy hb) hab) /-- The partial images of a binary function `f` whose partial evaluations are injective are pairwise disjoint iff `f` is injective . -/ theorem pairwiseDisjoint_image_left_iff {f : α → β → γ} {s : Set α} {t : Set β} (hf : ∀ b ∈ t, Injective fun a => f a b) : (t.PairwiseDisjoint fun b => (fun a => f a b) '' s) ↔ (s ×ˢ t).InjOn fun p => f p.1 p.2 := by refine ⟨fun ht x hx y hy (h : f _ _ = _) => ?_, fun ht x hx y hy h => ?_⟩ · suffices x.2 = y.2 by exact Prod.ext (hf _ hx.2 <| h.trans <| by rw [this]) this refine ht.elim hx.2 hy.2 (not_disjoint_iff.2 ⟨_, mem_image_of_mem _ hx.1, ?_⟩) rw [h] exact mem_image_of_mem _ hy.1 · refine disjoint_iff_inf_le.mpr ?_ rintro _ ⟨⟨a, ha, hab⟩, b, hb, rfl⟩ exact h (congr_arg Prod.snd <| ht (mk_mem_prod ha hx) (mk_mem_prod hb hy) hab) lemma exists_ne_mem_inter_of_not_pairwiseDisjoint {f : ι → Set α} (h : ¬ s.PairwiseDisjoint f) : ∃ i ∈ s, ∃ j ∈ s, i ≠ j ∧ ∃ x : α, x ∈ f i ∩ f j := by change ¬ ∀ i, i ∈ s → ∀ j, j ∈ s → i ≠ j → ∀ t, t ≤ f i → t ≤ f j → t ≤ ⊥ at h simp only [not_forall] at h obtain ⟨i, hi, j, hj, h_ne, t, hfi, hfj, ht⟩ := h replace ht : t.Nonempty := by rwa [le_bot_iff, bot_eq_empty, ← Ne, ← nonempty_iff_ne_empty] at ht obtain ⟨x, hx⟩ := ht exact ⟨i, hi, j, hj, h_ne, x, hfi hx, hfj hx⟩ lemma exists_lt_mem_inter_of_not_pairwiseDisjoint [LinearOrder ι] {f : ι → Set α} (h : ¬ s.PairwiseDisjoint f) : ∃ i ∈ s, ∃ j ∈ s, i < j ∧ ∃ x, x ∈ f i ∩ f j := by obtain ⟨i, hi, j, hj, hne, x, hx₁, hx₂⟩ := exists_ne_mem_inter_of_not_pairwiseDisjoint h cases' lt_or_lt_iff_ne.mpr hne with h_lt h_lt · exact ⟨i, hi, j, hj, h_lt, x, hx₁, hx₂⟩ · exact ⟨j, hj, i, hi, h_lt, x, hx₂, hx₁⟩ end Set lemma exists_ne_mem_inter_of_not_pairwise_disjoint {f : ι → Set α} (h : ¬ Pairwise (Disjoint on f)) : ∃ i j : ι, i ≠ j ∧ ∃ x, x ∈ f i ∩ f j := by rw [← pairwise_univ] at h obtain ⟨i, _hi, j, _hj, h⟩ := exists_ne_mem_inter_of_not_pairwiseDisjoint h exact ⟨i, j, h⟩ lemma exists_lt_mem_inter_of_not_pairwise_disjoint [LinearOrder ι] {f : ι → Set α} (h : ¬ Pairwise (Disjoint on f)) : ∃ i j : ι, i < j ∧ ∃ x, x ∈ f i ∩ f j := by rw [← pairwise_univ] at h obtain ⟨i, _hi, j, _hj, h⟩ := exists_lt_mem_inter_of_not_pairwiseDisjoint h exact ⟨i, j, h⟩ theorem pairwise_disjoint_fiber (f : ι → α) : Pairwise (Disjoint on fun a : α => f ⁻¹' {a}) := pairwise_univ.1 <| Set.pairwiseDisjoint_fiber f univ lemma subsingleton_setOf_mem_iff_pairwise_disjoint {f : ι → Set α} : (∀ a, {i | a ∈ f i}.Subsingleton) ↔ Pairwise (Disjoint on f) := ⟨fun h _ _ hij ↦ disjoint_left.2 fun a hi hj ↦ hij (h a hi hj), fun h _ _ hx _ hy ↦ by_contra fun hne ↦ disjoint_left.1 (h hne) hx hy⟩
Data\Set\Pairwise\Lattice.lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import Mathlib.Data.Set.Lattice import Mathlib.Data.Set.Pairwise.Basic /-! # Relations holding pairwise In this file we prove many facts about `Pairwise` and the set lattice. -/ open Function Set Order variable {α β γ ι ι' : Type*} {κ : Sort*} {r p q : α → α → Prop} section Pairwise variable {f g : ι → α} {s t u : Set α} {a b : α} namespace Set theorem pairwise_iUnion {f : κ → Set α} (h : Directed (· ⊆ ·) f) : (⋃ n, f n).Pairwise r ↔ ∀ n, (f n).Pairwise r := by constructor · intro H n exact Pairwise.mono (subset_iUnion _ _) H · intro H i hi j hj hij rcases mem_iUnion.1 hi with ⟨m, hm⟩ rcases mem_iUnion.1 hj with ⟨n, hn⟩ rcases h m n with ⟨p, mp, np⟩ exact H p (mp hm) (np hn) hij theorem pairwise_sUnion {r : α → α → Prop} {s : Set (Set α)} (h : DirectedOn (· ⊆ ·) s) : (⋃₀ s).Pairwise r ↔ ∀ a ∈ s, Set.Pairwise a r := by rw [sUnion_eq_iUnion, pairwise_iUnion h.directed_val, SetCoe.forall] end Set end Pairwise namespace Set section PartialOrderBot variable [PartialOrder α] [OrderBot α] {s t : Set ι} {f g : ι → α} theorem pairwiseDisjoint_iUnion {g : ι' → Set ι} (h : Directed (· ⊆ ·) g) : (⋃ n, g n).PairwiseDisjoint f ↔ ∀ ⦃n⦄, (g n).PairwiseDisjoint f := pairwise_iUnion h theorem pairwiseDisjoint_sUnion {s : Set (Set ι)} (h : DirectedOn (· ⊆ ·) s) : (⋃₀ s).PairwiseDisjoint f ↔ ∀ ⦃a⦄, a ∈ s → Set.PairwiseDisjoint a f := pairwise_sUnion h end PartialOrderBot section CompleteLattice variable [CompleteLattice α] {s : Set ι} {t : Set ι'} /-- Bind operation for `Set.PairwiseDisjoint`. If you want to only consider finsets of indices, you can use `Set.PairwiseDisjoint.biUnion_finset`. -/ theorem PairwiseDisjoint.biUnion {s : Set ι'} {g : ι' → Set ι} {f : ι → α} (hs : s.PairwiseDisjoint fun i' : ι' => ⨆ i ∈ g i', f i) (hg : ∀ i ∈ s, (g i).PairwiseDisjoint f) : (⋃ i ∈ s, g i).PairwiseDisjoint f := by rintro a ha b hb hab simp_rw [Set.mem_iUnion] at ha hb obtain ⟨c, hc, ha⟩ := ha obtain ⟨d, hd, hb⟩ := hb obtain hcd | hcd := eq_or_ne (g c) (g d) · exact hg d hd (hcd.subst ha) hb hab -- Porting note: the elaborator couldn't figure out `f` here. · exact (hs hc hd <| ne_of_apply_ne _ hcd).mono (le_iSup₂ (f := fun i (_ : i ∈ g c) => f i) a ha) (le_iSup₂ (f := fun i (_ : i ∈ g d) => f i) b hb) /-- If the suprema of columns are pairwise disjoint and suprema of rows as well, then everything is pairwise disjoint. Not to be confused with `Set.PairwiseDisjoint.prod`. -/ theorem PairwiseDisjoint.prod_left {f : ι × ι' → α} (hs : s.PairwiseDisjoint fun i => ⨆ i' ∈ t, f (i, i')) (ht : t.PairwiseDisjoint fun i' => ⨆ i ∈ s, f (i, i')) : (s ×ˢ t : Set (ι × ι')).PairwiseDisjoint f := by rintro ⟨i, i'⟩ hi ⟨j, j'⟩ hj h rw [mem_prod] at hi hj obtain rfl | hij := eq_or_ne i j · refine (ht hi.2 hj.2 <| (Prod.mk.inj_left _).ne_iff.1 h).mono ?_ ?_ · convert le_iSup₂ (α := α) i hi.1; rfl · convert le_iSup₂ (α := α) i hj.1; rfl · refine (hs hi.1 hj.1 hij).mono ?_ ?_ · convert le_iSup₂ (α := α) i' hi.2; rfl · convert le_iSup₂ (α := α) j' hj.2; rfl end CompleteLattice section Frame variable [Frame α] theorem pairwiseDisjoint_prod_left {s : Set ι} {t : Set ι'} {f : ι × ι' → α} : (s ×ˢ t : Set (ι × ι')).PairwiseDisjoint f ↔ (s.PairwiseDisjoint fun i => ⨆ i' ∈ t, f (i, i')) ∧ t.PairwiseDisjoint fun i' => ⨆ i ∈ s, f (i, i') := by refine ⟨fun h => ⟨fun i hi j hj hij => ?_, fun i hi j hj hij => ?_⟩, fun h => h.1.prod_left h.2⟩ <;> simp_rw [Function.onFun, iSup_disjoint_iff, disjoint_iSup_iff] <;> intro i' hi' j' hj' · exact h (mk_mem_prod hi hi') (mk_mem_prod hj hj') (ne_of_apply_ne Prod.fst hij) · exact h (mk_mem_prod hi' hi) (mk_mem_prod hj' hj) (ne_of_apply_ne Prod.snd hij) end Frame theorem biUnion_diff_biUnion_eq {s t : Set ι} {f : ι → Set α} (h : (s ∪ t).PairwiseDisjoint f) : ((⋃ i ∈ s, f i) \ ⋃ i ∈ t, f i) = ⋃ i ∈ s \ t, f i := by refine (biUnion_diff_biUnion_subset f s t).antisymm (iUnion₂_subset fun i hi a ha => (mem_diff _).2 ⟨mem_biUnion hi.1 ha, ?_⟩) rw [mem_iUnion₂]; rintro ⟨j, hj, haj⟩ exact (h (Or.inl hi.1) (Or.inr hj) (ne_of_mem_of_not_mem hj hi.2).symm).le_bot ⟨ha, haj⟩ /-- Equivalence between a disjoint bounded union and a dependent sum. -/ noncomputable def biUnionEqSigmaOfDisjoint {s : Set ι} {f : ι → Set α} (h : s.PairwiseDisjoint f) : (⋃ i ∈ s, f i) ≃ Σi : s, f i := (Equiv.setCongr (biUnion_eq_iUnion _ _)).trans <| unionEqSigmaOfDisjoint fun ⟨_i, hi⟩ ⟨_j, hj⟩ ne => h hi hj fun eq => ne <| Subtype.eq eq end Set section variable {f : ι → Set α} {s t : Set ι} theorem Set.PairwiseDisjoint.subset_of_biUnion_subset_biUnion (h₀ : (s ∪ t).PairwiseDisjoint f) (h₁ : ∀ i ∈ s, (f i).Nonempty) (h : ⋃ i ∈ s, f i ⊆ ⋃ i ∈ t, f i) : s ⊆ t := by rintro i hi obtain ⟨a, hai⟩ := h₁ i hi obtain ⟨j, hj, haj⟩ := mem_iUnion₂.1 (h <| mem_iUnion₂_of_mem hi hai) rwa [h₀.eq (subset_union_left hi) (subset_union_right hj) (not_disjoint_iff.2 ⟨a, hai, haj⟩)] theorem Pairwise.subset_of_biUnion_subset_biUnion (h₀ : Pairwise (Disjoint on f)) (h₁ : ∀ i ∈ s, (f i).Nonempty) (h : ⋃ i ∈ s, f i ⊆ ⋃ i ∈ t, f i) : s ⊆ t := Set.PairwiseDisjoint.subset_of_biUnion_subset_biUnion (h₀.set_pairwise _) h₁ h theorem Pairwise.biUnion_injective (h₀ : Pairwise (Disjoint on f)) (h₁ : ∀ i, (f i).Nonempty) : Injective fun s : Set ι => ⋃ i ∈ s, f i := fun _s _t h => ((h₀.subset_of_biUnion_subset_biUnion fun _ _ => h₁ _) <| h.subset).antisymm <| (h₀.subset_of_biUnion_subset_biUnion fun _ _ => h₁ _) <| h.superset /-- In a disjoint union we can identify the unique set an element belongs to. -/ theorem pairwiseDisjoint_unique {y : α} (h_disjoint : PairwiseDisjoint s f) (hy : y ∈ (⋃ i ∈ s, f i)) : ∃! i, i ∈ s ∧ y ∈ f i := by refine exists_unique_of_exists_of_unique ?ex ?unique · simpa only [mem_iUnion, exists_prop] using hy · rintro i j ⟨his, hi⟩ ⟨hjs, hj⟩ exact h_disjoint.elim his hjs <| not_disjoint_iff.mpr ⟨y, ⟨hi, hj⟩⟩ end
Data\Set\Pointwise\Basic.lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Floris van Doorn -/ import Mathlib.Algebra.Group.Equiv.Basic import Mathlib.Algebra.Group.Units.Hom import Mathlib.Algebra.Opposites import Mathlib.Algebra.Ring.Defs import Mathlib.Algebra.GroupWithZero.Basic import Mathlib.Data.Set.Lattice import Mathlib.Tactic.Common /-! # Pointwise operations of sets This file defines pointwise algebraic operations on sets. ## Main declarations For sets `s` and `t` and scalar `a`: * `s * t`: Multiplication, set of all `x * y` where `x ∈ s` and `y ∈ t`. * `s + t`: Addition, set of all `x + y` where `x ∈ s` and `y ∈ t`. * `s⁻¹`: Inversion, set of all `x⁻¹` where `x ∈ s`. * `-s`: Negation, set of all `-x` where `x ∈ s`. * `s / t`: Division, set of all `x / y` where `x ∈ s` and `y ∈ t`. * `s - t`: Subtraction, set of all `x - y` where `x ∈ s` and `y ∈ t`. For `α` a semigroup/monoid, `Set α` is a semigroup/monoid. As an unfortunate side effect, this means that `n • s`, where `n : ℕ`, is ambiguous between pointwise scaling and repeated pointwise addition; the former has `(2 : ℕ) • {1, 2} = {2, 4}`, while the latter has `(2 : ℕ) • {1, 2} = {2, 3, 4}`. See note [pointwise nat action]. Appropriate definitions and results are also transported to the additive theory via `to_additive`. ## Implementation notes * The following expressions are considered in simp-normal form in a group: `(fun h ↦ h * g) ⁻¹' s`, `(fun h ↦ g * h) ⁻¹' s`, `(fun h ↦ h * g⁻¹) ⁻¹' s`, `(fun h ↦ g⁻¹ * h) ⁻¹' s`, `s * t`, `s⁻¹`, `(1 : Set _)` (and similarly for additive variants). Expressions equal to one of these will be simplified. * We put all instances in the locale `Pointwise`, so that these instances are not available by default. Note that we do not mark them as reducible (as argued by note [reducible non-instances]) since we expect the locale to be open whenever the instances are actually used (and making the instances reducible changes the behavior of `simp`. ## Tags set multiplication, set addition, pointwise addition, pointwise multiplication, pointwise subtraction -/ library_note "pointwise nat action"/-- Pointwise monoids (`Set`, `Finset`, `Filter`) have derived pointwise actions of the form `SMul α β → SMul α (Set β)`. When `α` is `ℕ` or `ℤ`, this action conflicts with the nat or int action coming from `Set β` being a `Monoid` or `DivInvMonoid`. For example, `2 • {a, b}` can both be `{2 • a, 2 • b}` (pointwise action, pointwise repeated addition, `Set.smulSet`) and `{a + a, a + b, b + a, b + b}` (nat or int action, repeated pointwise addition, `Set.NSMul`). Because the pointwise action can easily be spelled out in such cases, we give higher priority to the nat and int actions. -/ open Function variable {F α β γ : Type*} namespace Set /-! ### `0`/`1` as sets -/ assert_not_exists OrderedAddCommMonoid section One variable [One α] {s : Set α} {a : α} /-- The set `1 : Set α` is defined as `{1}` in locale `Pointwise`. -/ @[to_additive "The set `0 : Set α` is defined as `{0}` in locale `Pointwise`."] protected noncomputable def one : One (Set α) := ⟨{1}⟩ scoped[Pointwise] attribute [instance] Set.one Set.zero open Pointwise @[to_additive] theorem singleton_one : ({1} : Set α) = 1 := rfl @[to_additive (attr := simp)] theorem mem_one : a ∈ (1 : Set α) ↔ a = 1 := Iff.rfl @[to_additive] theorem one_mem_one : (1 : α) ∈ (1 : Set α) := Eq.refl _ @[to_additive (attr := simp)] theorem one_subset : 1 ⊆ s ↔ (1 : α) ∈ s := singleton_subset_iff @[to_additive] theorem one_nonempty : (1 : Set α).Nonempty := ⟨1, rfl⟩ @[to_additive (attr := simp)] theorem image_one {f : α → β} : f '' 1 = {f 1} := image_singleton @[to_additive] theorem subset_one_iff_eq : s ⊆ 1 ↔ s = ∅ ∨ s = 1 := subset_singleton_iff_eq @[to_additive] theorem Nonempty.subset_one_iff (h : s.Nonempty) : s ⊆ 1 ↔ s = 1 := h.subset_singleton_iff /-- The singleton operation as a `OneHom`. -/ @[to_additive "The singleton operation as a `ZeroHom`."] noncomputable def singletonOneHom : OneHom α (Set α) where toFun := singleton; map_one' := singleton_one @[to_additive (attr := simp)] theorem coe_singletonOneHom : (singletonOneHom : α → Set α) = singleton := rfl end One /-! ### Set negation/inversion -/ section Inv /-- The pointwise inversion of set `s⁻¹` is defined as `{x | x⁻¹ ∈ s}` in locale `Pointwise`. It is equal to `{x⁻¹ | x ∈ s}`, see `Set.image_inv`. -/ @[to_additive "The pointwise negation of set `-s` is defined as `{x | -x ∈ s}` in locale `Pointwise`. It is equal to `{-x | x ∈ s}`, see `Set.image_neg`."] protected def inv [Inv α] : Inv (Set α) := ⟨preimage Inv.inv⟩ scoped[Pointwise] attribute [instance] Set.inv Set.neg open Pointwise section Inv variable {ι : Sort*} [Inv α] {s t : Set α} {a : α} @[to_additive (attr := simp)] theorem mem_inv : a ∈ s⁻¹ ↔ a⁻¹ ∈ s := Iff.rfl @[to_additive (attr := simp)] theorem inv_preimage : Inv.inv ⁻¹' s = s⁻¹ := rfl @[to_additive (attr := simp)] theorem inv_empty : (∅ : Set α)⁻¹ = ∅ := rfl @[to_additive (attr := simp)] theorem inv_univ : (univ : Set α)⁻¹ = univ := rfl @[to_additive (attr := simp)] theorem inter_inv : (s ∩ t)⁻¹ = s⁻¹ ∩ t⁻¹ := preimage_inter @[to_additive (attr := simp)] theorem union_inv : (s ∪ t)⁻¹ = s⁻¹ ∪ t⁻¹ := preimage_union @[to_additive (attr := simp)] theorem iInter_inv (s : ι → Set α) : (⋂ i, s i)⁻¹ = ⋂ i, (s i)⁻¹ := preimage_iInter @[to_additive (attr := simp)] theorem iUnion_inv (s : ι → Set α) : (⋃ i, s i)⁻¹ = ⋃ i, (s i)⁻¹ := preimage_iUnion @[to_additive (attr := simp)] theorem compl_inv : sᶜ⁻¹ = s⁻¹ᶜ := preimage_compl end Inv section InvolutiveInv variable [InvolutiveInv α] {s t : Set α} {a : α} @[to_additive] theorem inv_mem_inv : a⁻¹ ∈ s⁻¹ ↔ a ∈ s := by simp only [mem_inv, inv_inv] @[to_additive (attr := simp)] theorem nonempty_inv : s⁻¹.Nonempty ↔ s.Nonempty := inv_involutive.surjective.nonempty_preimage @[to_additive] theorem Nonempty.inv (h : s.Nonempty) : s⁻¹.Nonempty := nonempty_inv.2 h @[to_additive (attr := simp)] theorem image_inv : Inv.inv '' s = s⁻¹ := congr_fun (image_eq_preimage_of_inverse inv_involutive.leftInverse inv_involutive.rightInverse) _ @[to_additive (attr := simp)] theorem inv_eq_empty : s⁻¹ = ∅ ↔ s = ∅ := by rw [← image_inv, image_eq_empty] @[to_additive (attr := simp)] noncomputable instance involutiveInv : InvolutiveInv (Set α) where inv := Inv.inv inv_inv s := by simp only [← inv_preimage, preimage_preimage, inv_inv, preimage_id'] @[to_additive (attr := simp)] theorem inv_subset_inv : s⁻¹ ⊆ t⁻¹ ↔ s ⊆ t := (Equiv.inv α).surjective.preimage_subset_preimage_iff @[to_additive] theorem inv_subset : s⁻¹ ⊆ t ↔ s ⊆ t⁻¹ := by rw [← inv_subset_inv, inv_inv] @[to_additive (attr := simp)] theorem inv_singleton (a : α) : ({a} : Set α)⁻¹ = {a⁻¹} := by rw [← image_inv, image_singleton] @[to_additive (attr := simp)] theorem inv_insert (a : α) (s : Set α) : (insert a s)⁻¹ = insert a⁻¹ s⁻¹ := by rw [insert_eq, union_inv, inv_singleton, insert_eq] @[to_additive] theorem inv_range {ι : Sort*} {f : ι → α} : (range f)⁻¹ = range fun i => (f i)⁻¹ := by rw [← image_inv] exact (range_comp _ _).symm open MulOpposite @[to_additive] theorem image_op_inv : op '' s⁻¹ = (op '' s)⁻¹ := by simp_rw [← image_inv, Function.Semiconj.set_image op_inv s] end InvolutiveInv end Inv open Pointwise /-! ### Set addition/multiplication -/ section Mul variable {ι : Sort*} {κ : ι → Sort*} [Mul α] {s s₁ s₂ t t₁ t₂ u : Set α} {a b : α} /-- The pointwise multiplication of sets `s * t` and `t` is defined as `{x * y | x ∈ s, y ∈ t}` in locale `Pointwise`. -/ @[to_additive "The pointwise addition of sets `s + t` is defined as `{x + y | x ∈ s, y ∈ t}` in locale `Pointwise`."] protected def mul : Mul (Set α) := ⟨image2 (· * ·)⟩ scoped[Pointwise] attribute [instance] Set.mul Set.add @[to_additive (attr := simp)] theorem image2_mul : image2 (· * ·) s t = s * t := rfl @[to_additive] theorem mem_mul : a ∈ s * t ↔ ∃ x ∈ s, ∃ y ∈ t, x * y = a := Iff.rfl @[to_additive] theorem mul_mem_mul : a ∈ s → b ∈ t → a * b ∈ s * t := mem_image2_of_mem @[to_additive add_image_prod] theorem image_mul_prod : (fun x : α × α => x.fst * x.snd) '' s ×ˢ t = s * t := image_prod _ @[to_additive (attr := simp)] theorem empty_mul : ∅ * s = ∅ := image2_empty_left @[to_additive (attr := simp)] theorem mul_empty : s * ∅ = ∅ := image2_empty_right @[to_additive (attr := simp)] theorem mul_eq_empty : s * t = ∅ ↔ s = ∅ ∨ t = ∅ := image2_eq_empty_iff @[to_additive (attr := simp)] theorem mul_nonempty : (s * t).Nonempty ↔ s.Nonempty ∧ t.Nonempty := image2_nonempty_iff @[to_additive] theorem Nonempty.mul : s.Nonempty → t.Nonempty → (s * t).Nonempty := Nonempty.image2 @[to_additive] theorem Nonempty.of_mul_left : (s * t).Nonempty → s.Nonempty := Nonempty.of_image2_left @[to_additive] theorem Nonempty.of_mul_right : (s * t).Nonempty → t.Nonempty := Nonempty.of_image2_right @[to_additive (attr := simp)] theorem mul_singleton : s * {b} = (· * b) '' s := image2_singleton_right @[to_additive (attr := simp)] theorem singleton_mul : {a} * t = (a * ·) '' t := image2_singleton_left -- Porting note (#10618): simp can prove this @[to_additive] theorem singleton_mul_singleton : ({a} : Set α) * {b} = {a * b} := image2_singleton @[to_additive (attr := mono)] theorem mul_subset_mul : s₁ ⊆ t₁ → s₂ ⊆ t₂ → s₁ * s₂ ⊆ t₁ * t₂ := image2_subset @[to_additive] theorem mul_subset_mul_left : t₁ ⊆ t₂ → s * t₁ ⊆ s * t₂ := image2_subset_left @[to_additive] theorem mul_subset_mul_right : s₁ ⊆ s₂ → s₁ * t ⊆ s₂ * t := image2_subset_right @[to_additive] theorem mul_subset_iff : s * t ⊆ u ↔ ∀ x ∈ s, ∀ y ∈ t, x * y ∈ u := image2_subset_iff @[to_additive] theorem union_mul : (s₁ ∪ s₂) * t = s₁ * t ∪ s₂ * t := image2_union_left @[to_additive] theorem mul_union : s * (t₁ ∪ t₂) = s * t₁ ∪ s * t₂ := image2_union_right @[to_additive] theorem inter_mul_subset : s₁ ∩ s₂ * t ⊆ s₁ * t ∩ (s₂ * t) := image2_inter_subset_left @[to_additive] theorem mul_inter_subset : s * (t₁ ∩ t₂) ⊆ s * t₁ ∩ (s * t₂) := image2_inter_subset_right @[to_additive] theorem inter_mul_union_subset_union : s₁ ∩ s₂ * (t₁ ∪ t₂) ⊆ s₁ * t₁ ∪ s₂ * t₂ := image2_inter_union_subset_union @[to_additive] theorem union_mul_inter_subset_union : (s₁ ∪ s₂) * (t₁ ∩ t₂) ⊆ s₁ * t₁ ∪ s₂ * t₂ := image2_union_inter_subset_union @[to_additive] theorem iUnion_mul_left_image : ⋃ a ∈ s, (a * ·) '' t = s * t := iUnion_image_left _ @[to_additive] theorem iUnion_mul_right_image : ⋃ a ∈ t, (· * a) '' s = s * t := iUnion_image_right _ @[to_additive] theorem iUnion_mul (s : ι → Set α) (t : Set α) : (⋃ i, s i) * t = ⋃ i, s i * t := image2_iUnion_left _ _ _ @[to_additive] theorem mul_iUnion (s : Set α) (t : ι → Set α) : (s * ⋃ i, t i) = ⋃ i, s * t i := image2_iUnion_right _ _ _ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ @[to_additive] theorem iUnion₂_mul (s : ∀ i, κ i → Set α) (t : Set α) : (⋃ (i) (j), s i j) * t = ⋃ (i) (j), s i j * t := image2_iUnion₂_left _ _ _ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ @[to_additive] theorem mul_iUnion₂ (s : Set α) (t : ∀ i, κ i → Set α) : (s * ⋃ (i) (j), t i j) = ⋃ (i) (j), s * t i j := image2_iUnion₂_right _ _ _ @[to_additive] theorem iInter_mul_subset (s : ι → Set α) (t : Set α) : (⋂ i, s i) * t ⊆ ⋂ i, s i * t := Set.image2_iInter_subset_left _ _ _ @[to_additive] theorem mul_iInter_subset (s : Set α) (t : ι → Set α) : (s * ⋂ i, t i) ⊆ ⋂ i, s * t i := image2_iInter_subset_right _ _ _ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ @[to_additive] theorem iInter₂_mul_subset (s : ∀ i, κ i → Set α) (t : Set α) : (⋂ (i) (j), s i j) * t ⊆ ⋂ (i) (j), s i j * t := image2_iInter₂_subset_left _ _ _ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ @[to_additive] theorem mul_iInter₂_subset (s : Set α) (t : ∀ i, κ i → Set α) : (s * ⋂ (i) (j), t i j) ⊆ ⋂ (i) (j), s * t i j := image2_iInter₂_subset_right _ _ _ /-- The singleton operation as a `MulHom`. -/ @[to_additive "The singleton operation as an `AddHom`."] noncomputable def singletonMulHom : α →ₙ* Set α where toFun := singleton map_mul' _ _ := singleton_mul_singleton.symm @[to_additive (attr := simp)] theorem coe_singletonMulHom : (singletonMulHom : α → Set α) = singleton := rfl @[to_additive (attr := simp)] theorem singletonMulHom_apply (a : α) : singletonMulHom a = {a} := rfl open MulOpposite @[to_additive (attr := simp)] theorem image_op_mul : op '' (s * t) = op '' t * op '' s := image_image2_antidistrib op_mul end Mul /-! ### Set subtraction/division -/ section Div variable {ι : Sort*} {κ : ι → Sort*} [Div α] {s s₁ s₂ t t₁ t₂ u : Set α} {a b : α} /-- The pointwise division of sets `s / t` is defined as `{x / y | x ∈ s, y ∈ t}` in locale `Pointwise`. -/ @[to_additive "The pointwise subtraction of sets `s - t` is defined as `{x - y | x ∈ s, y ∈ t}` in locale `Pointwise`."] protected def div : Div (Set α) := ⟨image2 (· / ·)⟩ scoped[Pointwise] attribute [instance] Set.div Set.sub @[to_additive (attr := simp)] theorem image2_div : image2 Div.div s t = s / t := rfl @[to_additive] theorem mem_div : a ∈ s / t ↔ ∃ x ∈ s, ∃ y ∈ t, x / y = a := Iff.rfl @[to_additive] theorem div_mem_div : a ∈ s → b ∈ t → a / b ∈ s / t := mem_image2_of_mem @[to_additive sub_image_prod] theorem image_div_prod : (fun x : α × α => x.fst / x.snd) '' s ×ˢ t = s / t := image_prod _ @[to_additive (attr := simp)] theorem empty_div : ∅ / s = ∅ := image2_empty_left @[to_additive (attr := simp)] theorem div_empty : s / ∅ = ∅ := image2_empty_right @[to_additive (attr := simp)] theorem div_eq_empty : s / t = ∅ ↔ s = ∅ ∨ t = ∅ := image2_eq_empty_iff @[to_additive (attr := simp)] theorem div_nonempty : (s / t).Nonempty ↔ s.Nonempty ∧ t.Nonempty := image2_nonempty_iff @[to_additive] theorem Nonempty.div : s.Nonempty → t.Nonempty → (s / t).Nonempty := Nonempty.image2 @[to_additive] theorem Nonempty.of_div_left : (s / t).Nonempty → s.Nonempty := Nonempty.of_image2_left @[to_additive] theorem Nonempty.of_div_right : (s / t).Nonempty → t.Nonempty := Nonempty.of_image2_right @[to_additive (attr := simp)] theorem div_singleton : s / {b} = (· / b) '' s := image2_singleton_right @[to_additive (attr := simp)] theorem singleton_div : {a} / t = (· / ·) a '' t := image2_singleton_left -- Porting note (#10618): simp can prove this @[to_additive] theorem singleton_div_singleton : ({a} : Set α) / {b} = {a / b} := image2_singleton @[to_additive (attr := mono)] theorem div_subset_div : s₁ ⊆ t₁ → s₂ ⊆ t₂ → s₁ / s₂ ⊆ t₁ / t₂ := image2_subset @[to_additive] theorem div_subset_div_left : t₁ ⊆ t₂ → s / t₁ ⊆ s / t₂ := image2_subset_left @[to_additive] theorem div_subset_div_right : s₁ ⊆ s₂ → s₁ / t ⊆ s₂ / t := image2_subset_right @[to_additive] theorem div_subset_iff : s / t ⊆ u ↔ ∀ x ∈ s, ∀ y ∈ t, x / y ∈ u := image2_subset_iff @[to_additive] theorem union_div : (s₁ ∪ s₂) / t = s₁ / t ∪ s₂ / t := image2_union_left @[to_additive] theorem div_union : s / (t₁ ∪ t₂) = s / t₁ ∪ s / t₂ := image2_union_right @[to_additive] theorem inter_div_subset : s₁ ∩ s₂ / t ⊆ s₁ / t ∩ (s₂ / t) := image2_inter_subset_left @[to_additive] theorem div_inter_subset : s / (t₁ ∩ t₂) ⊆ s / t₁ ∩ (s / t₂) := image2_inter_subset_right @[to_additive] theorem inter_div_union_subset_union : s₁ ∩ s₂ / (t₁ ∪ t₂) ⊆ s₁ / t₁ ∪ s₂ / t₂ := image2_inter_union_subset_union @[to_additive] theorem union_div_inter_subset_union : (s₁ ∪ s₂) / (t₁ ∩ t₂) ⊆ s₁ / t₁ ∪ s₂ / t₂ := image2_union_inter_subset_union @[to_additive] theorem iUnion_div_left_image : ⋃ a ∈ s, (a / ·) '' t = s / t := iUnion_image_left _ @[to_additive] theorem iUnion_div_right_image : ⋃ a ∈ t, (· / a) '' s = s / t := iUnion_image_right _ @[to_additive] theorem iUnion_div (s : ι → Set α) (t : Set α) : (⋃ i, s i) / t = ⋃ i, s i / t := image2_iUnion_left _ _ _ @[to_additive] theorem div_iUnion (s : Set α) (t : ι → Set α) : (s / ⋃ i, t i) = ⋃ i, s / t i := image2_iUnion_right _ _ _ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ @[to_additive] theorem iUnion₂_div (s : ∀ i, κ i → Set α) (t : Set α) : (⋃ (i) (j), s i j) / t = ⋃ (i) (j), s i j / t := image2_iUnion₂_left _ _ _ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ @[to_additive] theorem div_iUnion₂ (s : Set α) (t : ∀ i, κ i → Set α) : (s / ⋃ (i) (j), t i j) = ⋃ (i) (j), s / t i j := image2_iUnion₂_right _ _ _ @[to_additive] theorem iInter_div_subset (s : ι → Set α) (t : Set α) : (⋂ i, s i) / t ⊆ ⋂ i, s i / t := image2_iInter_subset_left _ _ _ @[to_additive] theorem div_iInter_subset (s : Set α) (t : ι → Set α) : (s / ⋂ i, t i) ⊆ ⋂ i, s / t i := image2_iInter_subset_right _ _ _ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ @[to_additive] theorem iInter₂_div_subset (s : ∀ i, κ i → Set α) (t : Set α) : (⋂ (i) (j), s i j) / t ⊆ ⋂ (i) (j), s i j / t := image2_iInter₂_subset_left _ _ _ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ /- ./././Mathport/Syntax/Translate/Expr.lean:107:6: warning: expanding binder group (i j) -/ @[to_additive] theorem div_iInter₂_subset (s : Set α) (t : ∀ i, κ i → Set α) : (s / ⋂ (i) (j), t i j) ⊆ ⋂ (i) (j), s / t i j := image2_iInter₂_subset_right _ _ _ end Div open Pointwise /-- Repeated pointwise addition (not the same as pointwise repeated addition!) of a `Set`. See note [pointwise nat action]. -/ protected def NSMul [Zero α] [Add α] : SMul ℕ (Set α) := ⟨nsmulRec⟩ /-- Repeated pointwise multiplication (not the same as pointwise repeated multiplication!) of a `Set`. See note [pointwise nat action]. -/ @[to_additive existing] protected def NPow [One α] [Mul α] : Pow (Set α) ℕ := ⟨fun s n => npowRec n s⟩ /-- Repeated pointwise addition/subtraction (not the same as pointwise repeated addition/subtraction!) of a `Set`. See note [pointwise nat action]. -/ protected def ZSMul [Zero α] [Add α] [Neg α] : SMul ℤ (Set α) := ⟨zsmulRec⟩ /-- Repeated pointwise multiplication/division (not the same as pointwise repeated multiplication/division!) of a `Set`. See note [pointwise nat action]. -/ @[to_additive existing] protected def ZPow [One α] [Mul α] [Inv α] : Pow (Set α) ℤ := ⟨fun s n => zpowRec npowRec n s⟩ scoped[Pointwise] attribute [instance] Set.NSMul Set.NPow Set.ZSMul Set.ZPow /-- `Set α` is a `Semigroup` under pointwise operations if `α` is. -/ @[to_additive "`Set α` is an `AddSemigroup` under pointwise operations if `α` is."] protected noncomputable def semigroup [Semigroup α] : Semigroup (Set α) := { Set.mul with mul_assoc := fun _ _ _ => image2_assoc mul_assoc } section CommSemigroup variable [CommSemigroup α] {s t : Set α} /-- `Set α` is a `CommSemigroup` under pointwise operations if `α` is. -/ @[to_additive "`Set α` is an `AddCommSemigroup` under pointwise operations if `α` is."] protected noncomputable def commSemigroup : CommSemigroup (Set α) := { Set.semigroup with mul_comm := fun _ _ => image2_comm mul_comm } @[to_additive] theorem inter_mul_union_subset : s ∩ t * (s ∪ t) ⊆ s * t := image2_inter_union_subset mul_comm @[to_additive] theorem union_mul_inter_subset : (s ∪ t) * (s ∩ t) ⊆ s * t := image2_union_inter_subset mul_comm end CommSemigroup section MulOneClass variable [MulOneClass α] /-- `Set α` is a `MulOneClass` under pointwise operations if `α` is. -/ @[to_additive "`Set α` is an `AddZeroClass` under pointwise operations if `α` is."] protected noncomputable def mulOneClass : MulOneClass (Set α) := { Set.one, Set.mul with mul_one := image2_right_identity mul_one one_mul := image2_left_identity one_mul } scoped[Pointwise] attribute [instance] Set.mulOneClass Set.addZeroClass Set.semigroup Set.addSemigroup Set.commSemigroup Set.addCommSemigroup @[to_additive] theorem subset_mul_left (s : Set α) {t : Set α} (ht : (1 : α) ∈ t) : s ⊆ s * t := fun x hx => ⟨x, hx, 1, ht, mul_one _⟩ @[to_additive] theorem subset_mul_right {s : Set α} (t : Set α) (hs : (1 : α) ∈ s) : t ⊆ s * t := fun x hx => ⟨1, hs, x, hx, one_mul _⟩ /-- The singleton operation as a `MonoidHom`. -/ @[to_additive "The singleton operation as an `AddMonoidHom`."] noncomputable def singletonMonoidHom : α →* Set α := { singletonMulHom, singletonOneHom with } @[to_additive (attr := simp)] theorem coe_singletonMonoidHom : (singletonMonoidHom : α → Set α) = singleton := rfl @[to_additive (attr := simp)] theorem singletonMonoidHom_apply (a : α) : singletonMonoidHom a = {a} := rfl end MulOneClass section Monoid variable [Monoid α] {s t : Set α} {a : α} {m n : ℕ} /-- `Set α` is a `Monoid` under pointwise operations if `α` is. -/ @[to_additive "`Set α` is an `AddMonoid` under pointwise operations if `α` is."] protected noncomputable def monoid : Monoid (Set α) := { Set.semigroup, Set.mulOneClass, @Set.NPow α _ _ with } scoped[Pointwise] attribute [instance] Set.monoid Set.addMonoid @[to_additive] theorem pow_mem_pow (ha : a ∈ s) : ∀ n : ℕ, a ^ n ∈ s ^ n | 0 => by rw [pow_zero] exact one_mem_one | n + 1 => by rw [pow_succ] exact mul_mem_mul (pow_mem_pow ha _) ha @[to_additive] theorem pow_subset_pow (hst : s ⊆ t) : ∀ n : ℕ, s ^ n ⊆ t ^ n | 0 => by rw [pow_zero] exact Subset.rfl | n + 1 => by rw [pow_succ] exact mul_subset_mul (pow_subset_pow hst _) hst @[to_additive] theorem pow_subset_pow_of_one_mem (hs : (1 : α) ∈ s) (hn : m ≤ n) : s ^ m ⊆ s ^ n := by -- Porting note: `Nat.le_induction` didn't work as an induction principle in mathlib3, this was -- `refine Nat.le_induction ...` induction' n, hn using Nat.le_induction with _ _ ih · exact Subset.rfl · dsimp only rw [pow_succ'] exact ih.trans (subset_mul_right _ hs) @[to_additive (attr := simp)] theorem empty_pow {n : ℕ} (hn : n ≠ 0) : (∅ : Set α) ^ n = ∅ := by match n with | n + 1 => rw [pow_succ', empty_mul] @[to_additive] theorem mul_univ_of_one_mem (hs : (1 : α) ∈ s) : s * univ = univ := eq_univ_iff_forall.2 fun _ => mem_mul.2 ⟨_, hs, _, mem_univ _, one_mul _⟩ @[to_additive] theorem univ_mul_of_one_mem (ht : (1 : α) ∈ t) : univ * t = univ := eq_univ_iff_forall.2 fun _ => mem_mul.2 ⟨_, mem_univ _, _, ht, mul_one _⟩ @[to_additive (attr := simp)] theorem univ_mul_univ : (univ : Set α) * univ = univ := mul_univ_of_one_mem <| mem_univ _ --TODO: `to_additive` trips up on the `1 : ℕ` used in the pattern-matching. @[simp] theorem nsmul_univ {α : Type*} [AddMonoid α] : ∀ {n : ℕ}, n ≠ 0 → n • (univ : Set α) = univ | 0 => fun h => (h rfl).elim | 1 => fun _ => one_nsmul _ | n + 2 => fun _ => by rw [succ_nsmul, nsmul_univ n.succ_ne_zero, univ_add_univ] @[to_additive existing (attr := simp) nsmul_univ] theorem univ_pow : ∀ {n : ℕ}, n ≠ 0 → (univ : Set α) ^ n = univ | 0 => fun h => (h rfl).elim | 1 => fun _ => pow_one _ | n + 2 => fun _ => by rw [pow_succ, univ_pow n.succ_ne_zero, univ_mul_univ] @[to_additive] protected theorem _root_.IsUnit.set : IsUnit a → IsUnit ({a} : Set α) := IsUnit.map (singletonMonoidHom : α →* Set α) end Monoid /-- `Set α` is a `CommMonoid` under pointwise operations if `α` is. -/ @[to_additive "`Set α` is an `AddCommMonoid` under pointwise operations if `α` is."] protected noncomputable def commMonoid [CommMonoid α] : CommMonoid (Set α) := { Set.monoid, Set.commSemigroup with } scoped[Pointwise] attribute [instance] Set.commMonoid Set.addCommMonoid open Pointwise section DivisionMonoid variable [DivisionMonoid α] {s t : Set α} @[to_additive] protected theorem mul_eq_one_iff : s * t = 1 ↔ ∃ a b, s = {a} ∧ t = {b} ∧ a * b = 1 := by refine ⟨fun h => ?_, ?_⟩ · have hst : (s * t).Nonempty := h.symm.subst one_nonempty obtain ⟨a, ha⟩ := hst.of_image2_left obtain ⟨b, hb⟩ := hst.of_image2_right have H : ∀ {a b}, a ∈ s → b ∈ t → a * b = (1 : α) := fun {a b} ha hb => h.subset <| mem_image2_of_mem ha hb refine ⟨a, b, ?_, ?_, H ha hb⟩ <;> refine eq_singleton_iff_unique_mem.2 ⟨‹_›, fun x hx => ?_⟩ · exact (eq_inv_of_mul_eq_one_left <| H hx hb).trans (inv_eq_of_mul_eq_one_left <| H ha hb) · exact (eq_inv_of_mul_eq_one_right <| H ha hx).trans (inv_eq_of_mul_eq_one_right <| H ha hb) · rintro ⟨b, c, rfl, rfl, h⟩ rw [singleton_mul_singleton, h, singleton_one] /-- `Set α` is a division monoid under pointwise operations if `α` is. -/ @[to_additive subtractionMonoid "`Set α` is a subtraction monoid under pointwise operations if `α` is."] protected noncomputable def divisionMonoid : DivisionMonoid (Set α) := { Set.monoid, Set.involutiveInv, Set.div, @Set.ZPow α _ _ _ with mul_inv_rev := fun s t => by simp_rw [← image_inv] exact image_image2_antidistrib mul_inv_rev inv_eq_of_mul := fun s t h => by obtain ⟨a, b, rfl, rfl, hab⟩ := Set.mul_eq_one_iff.1 h rw [inv_singleton, inv_eq_of_mul_eq_one_right hab] div_eq_mul_inv := fun s t => by rw [← image_id (s / t), ← image_inv] exact image_image2_distrib_right div_eq_mul_inv } scoped[Pointwise] attribute [instance] Set.divisionMonoid Set.subtractionMonoid @[to_additive (attr := simp 500)] theorem isUnit_iff : IsUnit s ↔ ∃ a, s = {a} ∧ IsUnit a := by constructor · rintro ⟨u, rfl⟩ obtain ⟨a, b, ha, hb, h⟩ := Set.mul_eq_one_iff.1 u.mul_inv refine ⟨a, ha, ⟨a, b, h, singleton_injective ?_⟩, rfl⟩ rw [← singleton_mul_singleton, ← ha, ← hb] exact u.inv_mul · rintro ⟨a, rfl, ha⟩ exact ha.set @[to_additive (attr := simp)] lemma univ_div_univ : (univ / univ : Set α) = univ := by simp [div_eq_mul_inv] end DivisionMonoid /-- `Set α` is a commutative division monoid under pointwise operations if `α` is. -/ @[to_additive subtractionCommMonoid "`Set α` is a commutative subtraction monoid under pointwise operations if `α` is."] protected noncomputable def divisionCommMonoid [DivisionCommMonoid α] : DivisionCommMonoid (Set α) := { Set.divisionMonoid, Set.commSemigroup with } /-- `Set α` has distributive negation if `α` has. -/ protected noncomputable def hasDistribNeg [Mul α] [HasDistribNeg α] : HasDistribNeg (Set α) := { Set.involutiveNeg with neg_mul := fun _ _ => by simp_rw [← image_neg] exact image2_image_left_comm neg_mul mul_neg := fun _ _ => by simp_rw [← image_neg] exact image_image2_right_comm mul_neg } scoped[Pointwise] attribute [instance] Set.divisionCommMonoid Set.subtractionCommMonoid Set.hasDistribNeg section Distrib variable [Distrib α] (s t u : Set α) /-! Note that `Set α` is not a `Distrib` because `s * t + s * u` has cross terms that `s * (t + u)` lacks. -/ theorem mul_add_subset : s * (t + u) ⊆ s * t + s * u := image2_distrib_subset_left mul_add theorem add_mul_subset : (s + t) * u ⊆ s * u + t * u := image2_distrib_subset_right add_mul end Distrib section MulZeroClass variable [MulZeroClass α] {s t : Set α} /-! Note that `Set` is not a `MulZeroClass` because `0 * ∅ ≠ 0`. -/ theorem mul_zero_subset (s : Set α) : s * 0 ⊆ 0 := by simp [subset_def, mem_mul] theorem zero_mul_subset (s : Set α) : 0 * s ⊆ 0 := by simp [subset_def, mem_mul] theorem Nonempty.mul_zero (hs : s.Nonempty) : s * 0 = 0 := s.mul_zero_subset.antisymm <| by simpa [mem_mul] using hs theorem Nonempty.zero_mul (hs : s.Nonempty) : 0 * s = 0 := s.zero_mul_subset.antisymm <| by simpa [mem_mul] using hs end MulZeroClass section Group variable [Group α] {s t : Set α} {a b : α} /-! Note that `Set` is not a `Group` because `s / s ≠ 1` in general. -/ @[to_additive (attr := simp)] theorem one_mem_div_iff : (1 : α) ∈ s / t ↔ ¬Disjoint s t := by simp [not_disjoint_iff_nonempty_inter, mem_div, div_eq_one, Set.Nonempty] @[to_additive] theorem not_one_mem_div_iff : (1 : α) ∉ s / t ↔ Disjoint s t := one_mem_div_iff.not_left alias ⟨_, _root_.Disjoint.one_not_mem_div_set⟩ := not_one_mem_div_iff attribute [to_additive] Disjoint.one_not_mem_div_set @[to_additive] theorem Nonempty.one_mem_div (h : s.Nonempty) : (1 : α) ∈ s / s := let ⟨a, ha⟩ := h mem_div.2 ⟨a, ha, a, ha, div_self' _⟩ @[to_additive] theorem isUnit_singleton (a : α) : IsUnit ({a} : Set α) := (Group.isUnit a).set @[to_additive (attr := simp)] theorem isUnit_iff_singleton : IsUnit s ↔ ∃ a, s = {a} := by simp only [isUnit_iff, Group.isUnit, and_true_iff] @[to_additive (attr := simp)] theorem image_mul_left : (a * ·) '' t = (a⁻¹ * ·) ⁻¹' t := by rw [image_eq_preimage_of_inverse] <;> intro c <;> simp @[to_additive (attr := simp)] theorem image_mul_right : (· * b) '' t = (· * b⁻¹) ⁻¹' t := by rw [image_eq_preimage_of_inverse] <;> intro c <;> simp @[to_additive] theorem image_mul_left' : (a⁻¹ * ·) '' t = (a * ·) ⁻¹' t := by simp @[to_additive] theorem image_mul_right' : (· * b⁻¹) '' t = (· * b) ⁻¹' t := by simp @[to_additive (attr := simp)] theorem preimage_mul_left_singleton : (a * ·) ⁻¹' {b} = {a⁻¹ * b} := by rw [← image_mul_left', image_singleton] @[to_additive (attr := simp)] theorem preimage_mul_right_singleton : (· * a) ⁻¹' {b} = {b * a⁻¹} := by rw [← image_mul_right', image_singleton] @[to_additive (attr := simp)] theorem preimage_mul_left_one : (a * ·) ⁻¹' 1 = {a⁻¹} := by rw [← image_mul_left', image_one, mul_one] @[to_additive (attr := simp)] theorem preimage_mul_right_one : (· * b) ⁻¹' 1 = {b⁻¹} := by rw [← image_mul_right', image_one, one_mul] @[to_additive] theorem preimage_mul_left_one' : (a⁻¹ * ·) ⁻¹' 1 = {a} := by simp @[to_additive] theorem preimage_mul_right_one' : (· * b⁻¹) ⁻¹' 1 = {b} := by simp @[to_additive (attr := simp)] theorem mul_univ (hs : s.Nonempty) : s * (univ : Set α) = univ := let ⟨a, ha⟩ := hs eq_univ_of_forall fun b => ⟨a, ha, a⁻¹ * b, trivial, mul_inv_cancel_left _ _⟩ @[to_additive (attr := simp)] theorem univ_mul (ht : t.Nonempty) : (univ : Set α) * t = univ := let ⟨a, ha⟩ := ht eq_univ_of_forall fun b => ⟨b * a⁻¹, trivial, a, ha, inv_mul_cancel_right _ _⟩ end Group section GroupWithZero variable [GroupWithZero α] {s t : Set α} theorem div_zero_subset (s : Set α) : s / 0 ⊆ 0 := by simp [subset_def, mem_div] theorem zero_div_subset (s : Set α) : 0 / s ⊆ 0 := by simp [subset_def, mem_div] theorem Nonempty.div_zero (hs : s.Nonempty) : s / 0 = 0 := s.div_zero_subset.antisymm <| by simpa [mem_div] using hs theorem Nonempty.zero_div (hs : s.Nonempty) : 0 / s = 0 := s.zero_div_subset.antisymm <| by simpa [mem_div] using hs end GroupWithZero section Mul variable [Mul α] [Mul β] [FunLike F α β] [MulHomClass F α β] (m : F) {s t : Set α} @[to_additive] theorem image_mul : m '' (s * t) = m '' s * m '' t := image_image2_distrib <| map_mul m @[to_additive] lemma mul_subset_range {s t : Set β} (hs : s ⊆ range m) (ht : t ⊆ range m) : s * t ⊆ range m := by rintro _ ⟨a, ha, b, hb, rfl⟩ obtain ⟨a, rfl⟩ := hs ha obtain ⟨b, rfl⟩ := ht hb exact ⟨a * b, map_mul _ _ _⟩ @[to_additive] theorem preimage_mul_preimage_subset {s t : Set β} : m ⁻¹' s * m ⁻¹' t ⊆ m ⁻¹' (s * t) := by rintro _ ⟨_, _, _, _, rfl⟩ exact ⟨_, ‹_›, _, ‹_›, (map_mul m _ _).symm⟩ @[to_additive] lemma preimage_mul (hm : Injective m) {s t : Set β} (hs : s ⊆ range m) (ht : t ⊆ range m) : m ⁻¹' (s * t) = m ⁻¹' s * m ⁻¹' t := hm.image_injective <| by rw [image_mul, image_preimage_eq_iff.2 hs, image_preimage_eq_iff.2 ht, image_preimage_eq_iff.2 (mul_subset_range m hs ht)] end Mul section Group variable [Group α] [DivisionMonoid β] [FunLike F α β] [MonoidHomClass F α β] (m : F) {s t : Set α} @[to_additive] theorem image_div : m '' (s / t) = m '' s / m '' t := image_image2_distrib <| map_div m @[to_additive] lemma div_subset_range {s t : Set β} (hs : s ⊆ range m) (ht : t ⊆ range m) : s / t ⊆ range m := by rintro _ ⟨a, ha, b, hb, rfl⟩ obtain ⟨a, rfl⟩ := hs ha obtain ⟨b, rfl⟩ := ht hb exact ⟨a / b, map_div _ _ _⟩ @[to_additive] theorem preimage_div_preimage_subset {s t : Set β} : m ⁻¹' s / m ⁻¹' t ⊆ m ⁻¹' (s / t) := by rintro _ ⟨_, _, _, _, rfl⟩ exact ⟨_, ‹_›, _, ‹_›, (map_div m _ _).symm⟩ @[to_additive] lemma preimage_div (hm : Injective m) {s t : Set β} (hs : s ⊆ range m) (ht : t ⊆ range m) : m ⁻¹' (s / t) = m ⁻¹' s / m ⁻¹' t := hm.image_injective <| by rw [image_div, image_preimage_eq_iff.2 hs, image_preimage_eq_iff.2 ht, image_preimage_eq_iff.2 (div_subset_range m hs ht)] end Group end Set /-! ### Miscellaneous -/ open Set open Pointwise namespace Group @[to_additive] theorem card_pow_eq_card_pow_card_univ_aux {f : ℕ → ℕ} (h1 : Monotone f) {B : ℕ} (h2 : ∀ n, f n ≤ B) (h3 : ∀ n, f n = f (n + 1) → f (n + 1) = f (n + 2)) : ∀ k, B ≤ k → f k = f B := by have key : ∃ n : ℕ, n ≤ B ∧ f n = f (n + 1) := by contrapose! h2 suffices ∀ n : ℕ, n ≤ B + 1 → n ≤ f n by exact ⟨B + 1, this (B + 1) (le_refl (B + 1))⟩ exact fun n => Nat.rec (fun _ => Nat.zero_le (f 0)) (fun n ih h => lt_of_le_of_lt (ih (n.le_succ.trans h)) (lt_of_le_of_ne (h1 n.le_succ) (h2 n (Nat.succ_le_succ_iff.mp h)))) n obtain ⟨n, hn1, hn2⟩ := key replace key : ∀ k : ℕ, f (n + k) = f (n + k + 1) ∧ f (n + k) = f n := fun k => Nat.rec ⟨hn2, rfl⟩ (fun k ih => ⟨h3 _ ih.1, ih.1.symm.trans ih.2⟩) k replace key : ∀ k : ℕ, n ≤ k → f k = f n := fun k hk => (congr_arg f (Nat.add_sub_of_le hk)).symm.trans (key (k - n)).2 exact fun k hk => (key k (hn1.trans hk)).trans (key B hn1).symm end Group
Data\Set\Pointwise\BigOperators.lean
/- Copyright (c) 2021 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import Mathlib.Algebra.BigOperators.Group.Finset import Mathlib.Data.Set.Pointwise.Basic /-! # Results about pointwise operations on sets and big operators. -/ namespace Set open Pointwise Function variable {ι α β F : Type*} [FunLike F α β] section Monoid variable [Monoid α] [Monoid β] [MonoidHomClass F α β] @[to_additive] theorem image_list_prod (f : F) : ∀ l : List (Set α), (f : α → β) '' l.prod = (l.map fun s => f '' s).prod | [] => image_one.trans <| congr_arg singleton (map_one f) | a :: as => by rw [List.map_cons, List.prod_cons, List.prod_cons, image_mul, image_list_prod _ _] end Monoid section CommMonoid variable [CommMonoid α] [CommMonoid β] [MonoidHomClass F α β] @[to_additive] theorem image_multiset_prod (f : F) : ∀ m : Multiset (Set α), (f : α → β) '' m.prod = (m.map fun s => f '' s).prod := Quotient.ind <| by simpa only [Multiset.quot_mk_to_coe, Multiset.prod_coe, Multiset.map_coe] using image_list_prod f @[to_additive] theorem image_finset_prod (f : F) (m : Finset ι) (s : ι → Set α) : ((f : α → β) '' ∏ i ∈ m, s i) = ∏ i ∈ m, f '' s i := (image_multiset_prod f _).trans <| congr_arg Multiset.prod <| Multiset.map_map _ _ _ /-- The n-ary version of `Set.mem_mul`. -/ @[to_additive " The n-ary version of `Set.mem_add`. "] theorem mem_finset_prod (t : Finset ι) (f : ι → Set α) (a : α) : (a ∈ ∏ i ∈ t, f i) ↔ ∃ (g : ι → α) (_ : ∀ {i}, i ∈ t → g i ∈ f i), ∏ i ∈ t, g i = a := by classical induction' t using Finset.induction_on with i is hi ih generalizing a · simp_rw [Finset.prod_empty, Set.mem_one] exact ⟨fun h ↦ ⟨fun _ ↦ a, fun hi ↦ False.elim (Finset.not_mem_empty _ hi), h.symm⟩, fun ⟨_, _, hf⟩ ↦ hf.symm⟩ rw [Finset.prod_insert hi, Set.mem_mul] simp_rw [Finset.prod_insert hi] simp_rw [ih] constructor · rintro ⟨x, y, hx, ⟨g, hg, rfl⟩, rfl⟩ refine ⟨Function.update g i x, ?_, ?_⟩ · intro j hj obtain rfl | hj := Finset.mem_insert.mp hj · rwa [Function.update_same] · rw [update_noteq (ne_of_mem_of_not_mem hj hi)] exact hg hj · rw [Finset.prod_update_of_not_mem hi, Function.update_same] · rintro ⟨g, hg, rfl⟩ exact ⟨g i, hg (is.mem_insert_self _), is.prod g, ⟨⟨g, fun hi ↦ hg (Finset.mem_insert_of_mem hi), rfl⟩, rfl⟩⟩ /-- A version of `Set.mem_finset_prod` with a simpler RHS for products over a Fintype. -/ @[to_additive " A version of `Set.mem_finset_sum` with a simpler RHS for sums over a Fintype. "] theorem mem_fintype_prod [Fintype ι] (f : ι → Set α) (a : α) : (a ∈ ∏ i, f i) ↔ ∃ (g : ι → α) (_ : ∀ i, g i ∈ f i), ∏ i, g i = a := by rw [mem_finset_prod] simp /-- An n-ary version of `Set.mul_mem_mul`. -/ @[to_additive " An n-ary version of `Set.add_mem_add`. "] theorem list_prod_mem_list_prod (t : List ι) (f : ι → Set α) (g : ι → α) (hg : ∀ i ∈ t, g i ∈ f i) : (t.map g).prod ∈ (t.map f).prod := by induction' t with h tl ih · simp_rw [List.map_nil, List.prod_nil, Set.mem_one] · simp_rw [List.map_cons, List.prod_cons] exact mul_mem_mul (hg h <| List.mem_cons_self _ _) (ih fun i hi ↦ hg i <| List.mem_cons_of_mem _ hi) /-- An n-ary version of `Set.mul_subset_mul`. -/ @[to_additive " An n-ary version of `Set.add_subset_add`. "] theorem list_prod_subset_list_prod (t : List ι) (f₁ f₂ : ι → Set α) (hf : ∀ i ∈ t, f₁ i ⊆ f₂ i) : (t.map f₁).prod ⊆ (t.map f₂).prod := by induction' t with h tl ih · rfl · simp_rw [List.map_cons, List.prod_cons] exact mul_subset_mul (hf h <| List.mem_cons_self _ _) (ih fun i hi ↦ hf i <| List.mem_cons_of_mem _ hi) @[to_additive] theorem list_prod_singleton {M : Type*} [CommMonoid M] (s : List M) : (s.map fun i ↦ ({i} : Set M)).prod = {s.prod} := (map_list_prod (singletonMonoidHom : M →* Set M) _).symm /-- An n-ary version of `Set.mul_mem_mul`. -/ @[to_additive " An n-ary version of `Set.add_mem_add`. "] theorem multiset_prod_mem_multiset_prod (t : Multiset ι) (f : ι → Set α) (g : ι → α) (hg : ∀ i ∈ t, g i ∈ f i) : (t.map g).prod ∈ (t.map f).prod := by induction t using Quotient.inductionOn simp_rw [Multiset.quot_mk_to_coe, Multiset.map_coe, Multiset.prod_coe] exact list_prod_mem_list_prod _ _ _ hg /-- An n-ary version of `Set.mul_subset_mul`. -/ @[to_additive " An n-ary version of `Set.add_subset_add`. "] theorem multiset_prod_subset_multiset_prod (t : Multiset ι) (f₁ f₂ : ι → Set α) (hf : ∀ i ∈ t, f₁ i ⊆ f₂ i) : (t.map f₁).prod ⊆ (t.map f₂).prod := by induction t using Quotient.inductionOn simp_rw [Multiset.quot_mk_to_coe, Multiset.map_coe, Multiset.prod_coe] exact list_prod_subset_list_prod _ _ _ hf @[to_additive] theorem multiset_prod_singleton {M : Type*} [CommMonoid M] (s : Multiset M) : (s.map fun i ↦ ({i} : Set M)).prod = {s.prod} := (map_multiset_prod (singletonMonoidHom : M →* Set M) _).symm /-- An n-ary version of `Set.mul_mem_mul`. -/ @[to_additive " An n-ary version of `Set.add_mem_add`. "] theorem finset_prod_mem_finset_prod (t : Finset ι) (f : ι → Set α) (g : ι → α) (hg : ∀ i ∈ t, g i ∈ f i) : (∏ i ∈ t, g i) ∈ ∏ i ∈ t, f i := multiset_prod_mem_multiset_prod _ _ _ hg /-- An n-ary version of `Set.mul_subset_mul`. -/ @[to_additive " An n-ary version of `Set.add_subset_add`. "] theorem finset_prod_subset_finset_prod (t : Finset ι) (f₁ f₂ : ι → Set α) (hf : ∀ i ∈ t, f₁ i ⊆ f₂ i) : ∏ i ∈ t, f₁ i ⊆ ∏ i ∈ t, f₂ i := multiset_prod_subset_multiset_prod _ _ _ hf @[to_additive] theorem finset_prod_singleton {M ι : Type*} [CommMonoid M] (s : Finset ι) (I : ι → M) : ∏ i ∈ s, ({I i} : Set M) = {∏ i ∈ s, I i} := (map_prod (singletonMonoidHom : M →* Set M) _ _).symm /-- The n-ary version of `Set.image_mul_prod`. -/ @[to_additive "The n-ary version of `Set.add_image_prod`. "] theorem image_finset_prod_pi (l : Finset ι) (S : ι → Set α) : (fun f : ι → α => ∏ i ∈ l, f i) '' (l : Set ι).pi S = ∏ i ∈ l, S i := by ext simp_rw [mem_finset_prod, mem_image, mem_pi, exists_prop, Finset.mem_coe] /-- A special case of `Set.image_finset_prod_pi` for `Finset.univ`. -/ @[to_additive "A special case of `Set.image_finset_sum_pi` for `Finset.univ`. "] theorem image_fintype_prod_pi [Fintype ι] (S : ι → Set α) : (fun f : ι → α => ∏ i, f i) '' univ.pi S = ∏ i, S i := by simpa only [Finset.coe_univ] using image_finset_prod_pi Finset.univ S end CommMonoid /-! TODO: define `decidable_mem_finset_prod` and `decidable_mem_finset_sum`. -/ end Set
Data\Set\Pointwise\BoundedMul.lean
/- Copyright (c) 2021 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. KudryashovJ -/ import Mathlib.Algebra.Order.Monoid.Defs import Mathlib.Data.Set.Pointwise.Basic /-! # Pointwise multiplication of sets preserves boundedness above. TODO: Can be combined with future results about pointwise multiplication on sets that use ordered algebraic classes. -/ variable {α : Type*} namespace Set open Pointwise @[to_additive] theorem BddAbove.mul [OrderedCommMonoid α] {A B : Set α} (hA : BddAbove A) (hB : BddAbove B) : BddAbove (A * B) := hA.image2 (fun _ _ _ h ↦ mul_le_mul_right' h _) (fun _ _ _ h ↦ mul_le_mul_left' h _) hB end Set
Data\Set\Pointwise\Finite.lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Floris van Doorn -/ import Mathlib.Data.Set.Finite import Mathlib.Data.Set.Pointwise.SMul /-! # Finiteness lemmas for pointwise operations on sets -/ open Pointwise variable {F α β γ : Type*} namespace Set section One variable [One α] @[to_additive (attr := simp)] theorem finite_one : (1 : Set α).Finite := finite_singleton _ end One section InvolutiveInv variable [InvolutiveInv α] {s : Set α} @[to_additive] theorem Finite.inv (hs : s.Finite) : s⁻¹.Finite := hs.preimage inv_injective.injOn end InvolutiveInv section Mul variable [Mul α] {s t : Set α} @[to_additive] theorem Finite.mul : s.Finite → t.Finite → (s * t).Finite := Finite.image2 _ /-- Multiplication preserves finiteness. -/ @[to_additive "Addition preserves finiteness."] def fintypeMul [DecidableEq α] (s t : Set α) [Fintype s] [Fintype t] : Fintype (s * t : Set α) := Set.fintypeImage2 _ _ _ end Mul section Monoid variable [Monoid α] {s t : Set α} @[to_additive] instance decidableMemMul [Fintype α] [DecidableEq α] [DecidablePred (· ∈ s)] [DecidablePred (· ∈ t)] : DecidablePred (· ∈ s * t) := fun _ ↦ decidable_of_iff _ mem_mul.symm @[to_additive] instance decidableMemPow [Fintype α] [DecidableEq α] [DecidablePred (· ∈ s)] (n : ℕ) : DecidablePred (· ∈ s ^ n) := by induction' n with n ih · simp only [Nat.zero_eq, pow_zero, mem_one] infer_instance · letI := ih rw [pow_succ] infer_instance end Monoid section SMul variable [SMul α β] {s : Set α} {t : Set β} @[to_additive] theorem Finite.smul : s.Finite → t.Finite → (s • t).Finite := Finite.image2 _ end SMul section HasSMulSet variable [SMul α β] {s : Set β} {a : α} @[to_additive] theorem Finite.smul_set : s.Finite → (a • s).Finite := Finite.image _ @[to_additive] theorem Infinite.of_smul_set : (a • s).Infinite → s.Infinite := Infinite.of_image _ end HasSMulSet section Vsub variable [VSub α β] {s t : Set β} theorem Finite.vsub (hs : s.Finite) (ht : t.Finite) : Set.Finite (s -ᵥ t) := hs.image2 _ ht end Vsub section Cancel variable [Mul α] [IsLeftCancelMul α] [IsRightCancelMul α] {s t : Set α} @[to_additive] theorem infinite_mul : (s * t).Infinite ↔ s.Infinite ∧ t.Nonempty ∨ t.Infinite ∧ s.Nonempty := infinite_image2 (fun _ _ => (mul_left_injective _).injOn) fun _ _ => (mul_right_injective _).injOn @[to_additive] lemma finite_mul : (s * t).Finite ↔ s.Finite ∧ t.Finite ∨ s = ∅ ∨ t = ∅ := finite_image2 (fun _ _ ↦ (mul_left_injective _).injOn) fun _ _ ↦ (mul_right_injective _).injOn end Cancel section Group variable [Group α] [MulAction α β] {a : α} {s : Set β} @[to_additive (attr := simp)] theorem finite_smul_set : (a • s).Finite ↔ s.Finite := finite_image_iff (MulAction.injective _).injOn @[to_additive (attr := simp)] theorem infinite_smul_set : (a • s).Infinite ↔ s.Infinite := infinite_image_iff (MulAction.injective _).injOn alias ⟨Finite.of_smul_set, _⟩ := finite_smul_set alias ⟨_, Infinite.smul_set⟩ := infinite_smul_set attribute [to_additive] Finite.of_smul_set Infinite.smul_set end Group end Set open Set namespace Group variable {G : Type*} [Group G] [Fintype G] (S : Set G) @[to_additive] theorem card_pow_eq_card_pow_card_univ [∀ k : ℕ, DecidablePred (· ∈ S ^ k)] : ∀ k, Fintype.card G ≤ k → Fintype.card (↥(S ^ k)) = Fintype.card (↥(S ^ Fintype.card G)) := by have hG : 0 < Fintype.card G := Fintype.card_pos rcases S.eq_empty_or_nonempty with (rfl | ⟨a, ha⟩) · refine fun k hk ↦ Fintype.card_congr ?_ rw [empty_pow (hG.trans_le hk).ne', empty_pow (ne_of_gt hG)] have key : ∀ (a) (s t : Set G) [Fintype s] [Fintype t], (∀ b : G, b ∈ s → b * a ∈ t) → Fintype.card s ≤ Fintype.card t := by refine fun a s t _ _ h ↦ Fintype.card_le_of_injective (fun ⟨b, hb⟩ ↦ ⟨b * a, h b hb⟩) ?_ rintro ⟨b, hb⟩ ⟨c, hc⟩ hbc exact Subtype.ext (mul_right_cancel (Subtype.ext_iff.mp hbc)) have mono : Monotone (fun n ↦ Fintype.card (↥(S ^ n)) : ℕ → ℕ) := monotone_nat_of_le_succ fun n ↦ key a _ _ fun b hb ↦ Set.mul_mem_mul hb ha refine card_pow_eq_card_pow_card_univ_aux mono (fun n ↦ set_fintype_card_le_univ (S ^ n)) fun n h ↦ le_antisymm (mono (n + 1).le_succ) (key a⁻¹ (S ^ (n + 2)) (S ^ (n + 1)) ?_) replace h₂ : S ^ n * {a} = S ^ (n + 1) := by have : Fintype (S ^ n * Set.singleton a) := by classical apply fintypeMul refine Set.eq_of_subset_of_card_le ?_ (le_trans (ge_of_eq h) ?_) · exact mul_subset_mul Set.Subset.rfl (Set.singleton_subset_iff.mpr ha) · convert key a (S ^ n) (S ^ n * {a}) fun b hb ↦ Set.mul_mem_mul hb (Set.mem_singleton a) rw [pow_succ', ← h₂, ← mul_assoc, ← pow_succ', h₂, mul_singleton, forall_mem_image] intro x hx rwa [mul_inv_cancel_right] end Group
Data\Set\Pointwise\Interval.lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov, Patrick Massot -/ import Mathlib.Order.Interval.Set.UnorderedInterval import Mathlib.Algebra.Order.Interval.Set.Monoid import Mathlib.Data.Set.Pointwise.Basic import Mathlib.Algebra.Order.Field.Basic import Mathlib.Algebra.Order.Group.MinMax /-! # (Pre)images of intervals In this file we prove a bunch of trivial lemmas like “if we add `a` to all points of `[b, c]`, then we get `[a + b, a + c]`”. For the functions `x ↦ x ± a`, `x ↦ a ± x`, and `x ↦ -x` we prove lemmas about preimages and images of all intervals. We also prove a few lemmas about images under `x ↦ a * x`, `x ↦ x * a` and `x ↦ x⁻¹`. -/ open Interval Pointwise variable {α : Type*} namespace Set /-! ### Binary pointwise operations Note that the subset operations below only cover the cases with the largest possible intervals on the LHS: to conclude that `Ioo a b * Ioo c d ⊆ Ioo (a * c) (c * d)`, you can use monotonicity of `*` and `Set.Ico_mul_Ioc_subset`. TODO: repeat these lemmas for the generality of `mul_le_mul` (which assumes nonnegativity), which the unprimed names have been reserved for -/ section ContravariantLE variable [Mul α] [Preorder α] variable [CovariantClass α α (· * ·) (· ≤ ·)] [CovariantClass α α (Function.swap HMul.hMul) LE.le] @[to_additive Icc_add_Icc_subset] theorem Icc_mul_Icc_subset' (a b c d : α) : Icc a b * Icc c d ⊆ Icc (a * c) (b * d) := by rintro x ⟨y, ⟨hya, hyb⟩, z, ⟨hzc, hzd⟩, rfl⟩ exact ⟨mul_le_mul' hya hzc, mul_le_mul' hyb hzd⟩ @[to_additive Iic_add_Iic_subset] theorem Iic_mul_Iic_subset' (a b : α) : Iic a * Iic b ⊆ Iic (a * b) := by rintro x ⟨y, hya, z, hzb, rfl⟩ exact mul_le_mul' hya hzb @[to_additive Ici_add_Ici_subset] theorem Ici_mul_Ici_subset' (a b : α) : Ici a * Ici b ⊆ Ici (a * b) := by rintro x ⟨y, hya, z, hzb, rfl⟩ exact mul_le_mul' hya hzb end ContravariantLE section ContravariantLT variable [Mul α] [PartialOrder α] variable [CovariantClass α α (· * ·) (· < ·)] [CovariantClass α α (Function.swap HMul.hMul) LT.lt] @[to_additive Icc_add_Ico_subset] theorem Icc_mul_Ico_subset' (a b c d : α) : Icc a b * Ico c d ⊆ Ico (a * c) (b * d) := by haveI := covariantClass_le_of_lt rintro x ⟨y, ⟨hya, hyb⟩, z, ⟨hzc, hzd⟩, rfl⟩ exact ⟨mul_le_mul' hya hzc, mul_lt_mul_of_le_of_lt hyb hzd⟩ @[to_additive Ico_add_Icc_subset] theorem Ico_mul_Icc_subset' (a b c d : α) : Ico a b * Icc c d ⊆ Ico (a * c) (b * d) := by haveI := covariantClass_le_of_lt rintro x ⟨y, ⟨hya, hyb⟩, z, ⟨hzc, hzd⟩, rfl⟩ exact ⟨mul_le_mul' hya hzc, mul_lt_mul_of_lt_of_le hyb hzd⟩ @[to_additive Ioc_add_Ico_subset] theorem Ioc_mul_Ico_subset' (a b c d : α) : Ioc a b * Ico c d ⊆ Ioo (a * c) (b * d) := by haveI := covariantClass_le_of_lt rintro x ⟨y, ⟨hya, hyb⟩, z, ⟨hzc, hzd⟩, rfl⟩ exact ⟨mul_lt_mul_of_lt_of_le hya hzc, mul_lt_mul_of_le_of_lt hyb hzd⟩ @[to_additive Ico_add_Ioc_subset] theorem Ico_mul_Ioc_subset' (a b c d : α) : Ico a b * Ioc c d ⊆ Ioo (a * c) (b * d) := by haveI := covariantClass_le_of_lt rintro x ⟨y, ⟨hya, hyb⟩, z, ⟨hzc, hzd⟩, rfl⟩ exact ⟨mul_lt_mul_of_le_of_lt hya hzc, mul_lt_mul_of_lt_of_le hyb hzd⟩ @[to_additive Iic_add_Iio_subset] theorem Iic_mul_Iio_subset' (a b : α) : Iic a * Iio b ⊆ Iio (a * b) := by haveI := covariantClass_le_of_lt rintro x ⟨y, hya, z, hzb, rfl⟩ exact mul_lt_mul_of_le_of_lt hya hzb @[to_additive Iio_add_Iic_subset] theorem Iio_mul_Iic_subset' (a b : α) : Iio a * Iic b ⊆ Iio (a * b) := by haveI := covariantClass_le_of_lt rintro x ⟨y, hya, z, hzb, rfl⟩ exact mul_lt_mul_of_lt_of_le hya hzb @[to_additive Ioi_add_Ici_subset] theorem Ioi_mul_Ici_subset' (a b : α) : Ioi a * Ici b ⊆ Ioi (a * b) := by haveI := covariantClass_le_of_lt rintro x ⟨y, hya, z, hzb, rfl⟩ exact mul_lt_mul_of_lt_of_le hya hzb @[to_additive Ici_add_Ioi_subset] theorem Ici_mul_Ioi_subset' (a b : α) : Ici a * Ioi b ⊆ Ioi (a * b) := by haveI := covariantClass_le_of_lt rintro x ⟨y, hya, z, hzb, rfl⟩ exact mul_lt_mul_of_le_of_lt hya hzb end ContravariantLT section OrderedAddCommGroup variable [OrderedAddCommGroup α] (a b c : α) /-! ### Preimages under `x ↦ a + x` -/ @[simp] theorem preimage_const_add_Ici : (fun x => a + x) ⁻¹' Ici b = Ici (b - a) := ext fun _x => sub_le_iff_le_add'.symm @[simp] theorem preimage_const_add_Ioi : (fun x => a + x) ⁻¹' Ioi b = Ioi (b - a) := ext fun _x => sub_lt_iff_lt_add'.symm @[simp] theorem preimage_const_add_Iic : (fun x => a + x) ⁻¹' Iic b = Iic (b - a) := ext fun _x => le_sub_iff_add_le'.symm @[simp] theorem preimage_const_add_Iio : (fun x => a + x) ⁻¹' Iio b = Iio (b - a) := ext fun _x => lt_sub_iff_add_lt'.symm @[simp] theorem preimage_const_add_Icc : (fun x => a + x) ⁻¹' Icc b c = Icc (b - a) (c - a) := by simp [← Ici_inter_Iic] @[simp] theorem preimage_const_add_Ico : (fun x => a + x) ⁻¹' Ico b c = Ico (b - a) (c - a) := by simp [← Ici_inter_Iio] @[simp] theorem preimage_const_add_Ioc : (fun x => a + x) ⁻¹' Ioc b c = Ioc (b - a) (c - a) := by simp [← Ioi_inter_Iic] @[simp] theorem preimage_const_add_Ioo : (fun x => a + x) ⁻¹' Ioo b c = Ioo (b - a) (c - a) := by simp [← Ioi_inter_Iio] /-! ### Preimages under `x ↦ x + a` -/ @[simp] theorem preimage_add_const_Ici : (fun x => x + a) ⁻¹' Ici b = Ici (b - a) := ext fun _x => sub_le_iff_le_add.symm @[simp] theorem preimage_add_const_Ioi : (fun x => x + a) ⁻¹' Ioi b = Ioi (b - a) := ext fun _x => sub_lt_iff_lt_add.symm @[simp] theorem preimage_add_const_Iic : (fun x => x + a) ⁻¹' Iic b = Iic (b - a) := ext fun _x => le_sub_iff_add_le.symm @[simp] theorem preimage_add_const_Iio : (fun x => x + a) ⁻¹' Iio b = Iio (b - a) := ext fun _x => lt_sub_iff_add_lt.symm @[simp] theorem preimage_add_const_Icc : (fun x => x + a) ⁻¹' Icc b c = Icc (b - a) (c - a) := by simp [← Ici_inter_Iic] @[simp] theorem preimage_add_const_Ico : (fun x => x + a) ⁻¹' Ico b c = Ico (b - a) (c - a) := by simp [← Ici_inter_Iio] @[simp] theorem preimage_add_const_Ioc : (fun x => x + a) ⁻¹' Ioc b c = Ioc (b - a) (c - a) := by simp [← Ioi_inter_Iic] @[simp] theorem preimage_add_const_Ioo : (fun x => x + a) ⁻¹' Ioo b c = Ioo (b - a) (c - a) := by simp [← Ioi_inter_Iio] /-! ### Preimages under `x ↦ -x` -/ @[simp] theorem preimage_neg_Ici : -Ici a = Iic (-a) := ext fun _x => le_neg @[simp] theorem preimage_neg_Iic : -Iic a = Ici (-a) := ext fun _x => neg_le @[simp] theorem preimage_neg_Ioi : -Ioi a = Iio (-a) := ext fun _x => lt_neg @[simp] theorem preimage_neg_Iio : -Iio a = Ioi (-a) := ext fun _x => neg_lt @[simp] theorem preimage_neg_Icc : -Icc a b = Icc (-b) (-a) := by simp [← Ici_inter_Iic, inter_comm] @[simp] theorem preimage_neg_Ico : -Ico a b = Ioc (-b) (-a) := by simp [← Ici_inter_Iio, ← Ioi_inter_Iic, inter_comm] @[simp] theorem preimage_neg_Ioc : -Ioc a b = Ico (-b) (-a) := by simp [← Ioi_inter_Iic, ← Ici_inter_Iio, inter_comm] @[simp] theorem preimage_neg_Ioo : -Ioo a b = Ioo (-b) (-a) := by simp [← Ioi_inter_Iio, inter_comm] /-! ### Preimages under `x ↦ x - a` -/ @[simp] theorem preimage_sub_const_Ici : (fun x => x - a) ⁻¹' Ici b = Ici (b + a) := by simp [sub_eq_add_neg] @[simp] theorem preimage_sub_const_Ioi : (fun x => x - a) ⁻¹' Ioi b = Ioi (b + a) := by simp [sub_eq_add_neg] @[simp] theorem preimage_sub_const_Iic : (fun x => x - a) ⁻¹' Iic b = Iic (b + a) := by simp [sub_eq_add_neg] @[simp] theorem preimage_sub_const_Iio : (fun x => x - a) ⁻¹' Iio b = Iio (b + a) := by simp [sub_eq_add_neg] @[simp] theorem preimage_sub_const_Icc : (fun x => x - a) ⁻¹' Icc b c = Icc (b + a) (c + a) := by simp [sub_eq_add_neg] @[simp] theorem preimage_sub_const_Ico : (fun x => x - a) ⁻¹' Ico b c = Ico (b + a) (c + a) := by simp [sub_eq_add_neg] @[simp] theorem preimage_sub_const_Ioc : (fun x => x - a) ⁻¹' Ioc b c = Ioc (b + a) (c + a) := by simp [sub_eq_add_neg] @[simp] theorem preimage_sub_const_Ioo : (fun x => x - a) ⁻¹' Ioo b c = Ioo (b + a) (c + a) := by simp [sub_eq_add_neg] /-! ### Preimages under `x ↦ a - x` -/ @[simp] theorem preimage_const_sub_Ici : (fun x => a - x) ⁻¹' Ici b = Iic (a - b) := ext fun _x => le_sub_comm @[simp] theorem preimage_const_sub_Iic : (fun x => a - x) ⁻¹' Iic b = Ici (a - b) := ext fun _x => sub_le_comm @[simp] theorem preimage_const_sub_Ioi : (fun x => a - x) ⁻¹' Ioi b = Iio (a - b) := ext fun _x => lt_sub_comm @[simp] theorem preimage_const_sub_Iio : (fun x => a - x) ⁻¹' Iio b = Ioi (a - b) := ext fun _x => sub_lt_comm @[simp] theorem preimage_const_sub_Icc : (fun x => a - x) ⁻¹' Icc b c = Icc (a - c) (a - b) := by simp [← Ici_inter_Iic, inter_comm] @[simp] theorem preimage_const_sub_Ico : (fun x => a - x) ⁻¹' Ico b c = Ioc (a - c) (a - b) := by simp [← Ioi_inter_Iic, ← Ici_inter_Iio, inter_comm] @[simp] theorem preimage_const_sub_Ioc : (fun x => a - x) ⁻¹' Ioc b c = Ico (a - c) (a - b) := by simp [← Ioi_inter_Iic, ← Ici_inter_Iio, inter_comm] @[simp] theorem preimage_const_sub_Ioo : (fun x => a - x) ⁻¹' Ioo b c = Ioo (a - c) (a - b) := by simp [← Ioi_inter_Iio, inter_comm] /-! ### Images under `x ↦ a + x` -/ -- @[simp] -- Porting note (#10618): simp can prove this modulo `add_comm` theorem image_const_add_Iic : (fun x => a + x) '' Iic b = Iic (a + b) := by simp [add_comm] -- @[simp] -- Porting note (#10618): simp can prove this modulo `add_comm` theorem image_const_add_Iio : (fun x => a + x) '' Iio b = Iio (a + b) := by simp [add_comm] /-! ### Images under `x ↦ x + a` -/ -- @[simp] -- Porting note (#10618): simp can prove this theorem image_add_const_Iic : (fun x => x + a) '' Iic b = Iic (b + a) := by simp -- @[simp] -- Porting note (#10618): simp can prove this theorem image_add_const_Iio : (fun x => x + a) '' Iio b = Iio (b + a) := by simp /-! ### Images under `x ↦ -x` -/ theorem image_neg_Ici : Neg.neg '' Ici a = Iic (-a) := by simp theorem image_neg_Iic : Neg.neg '' Iic a = Ici (-a) := by simp theorem image_neg_Ioi : Neg.neg '' Ioi a = Iio (-a) := by simp theorem image_neg_Iio : Neg.neg '' Iio a = Ioi (-a) := by simp theorem image_neg_Icc : Neg.neg '' Icc a b = Icc (-b) (-a) := by simp theorem image_neg_Ico : Neg.neg '' Ico a b = Ioc (-b) (-a) := by simp theorem image_neg_Ioc : Neg.neg '' Ioc a b = Ico (-b) (-a) := by simp theorem image_neg_Ioo : Neg.neg '' Ioo a b = Ioo (-b) (-a) := by simp /-! ### Images under `x ↦ a - x` -/ @[simp] theorem image_const_sub_Ici : (fun x => a - x) '' Ici b = Iic (a - b) := by have := image_comp (fun x => a + x) fun x => -x; dsimp [Function.comp_def] at this simp [sub_eq_add_neg, this, add_comm] @[simp] theorem image_const_sub_Iic : (fun x => a - x) '' Iic b = Ici (a - b) := by have := image_comp (fun x => a + x) fun x => -x; dsimp [Function.comp_def] at this simp [sub_eq_add_neg, this, add_comm] @[simp] theorem image_const_sub_Ioi : (fun x => a - x) '' Ioi b = Iio (a - b) := by have := image_comp (fun x => a + x) fun x => -x; dsimp [Function.comp_def] at this simp [sub_eq_add_neg, this, add_comm] @[simp] theorem image_const_sub_Iio : (fun x => a - x) '' Iio b = Ioi (a - b) := by have := image_comp (fun x => a + x) fun x => -x; dsimp [Function.comp_def] at this simp [sub_eq_add_neg, this, add_comm] @[simp] theorem image_const_sub_Icc : (fun x => a - x) '' Icc b c = Icc (a - c) (a - b) := by have := image_comp (fun x => a + x) fun x => -x; dsimp [Function.comp_def] at this simp [sub_eq_add_neg, this, add_comm] @[simp] theorem image_const_sub_Ico : (fun x => a - x) '' Ico b c = Ioc (a - c) (a - b) := by have := image_comp (fun x => a + x) fun x => -x; dsimp [Function.comp_def] at this simp [sub_eq_add_neg, this, add_comm] @[simp] theorem image_const_sub_Ioc : (fun x => a - x) '' Ioc b c = Ico (a - c) (a - b) := by have := image_comp (fun x => a + x) fun x => -x; dsimp [Function.comp_def] at this simp [sub_eq_add_neg, this, add_comm] @[simp] theorem image_const_sub_Ioo : (fun x => a - x) '' Ioo b c = Ioo (a - c) (a - b) := by have := image_comp (fun x => a + x) fun x => -x; dsimp [Function.comp_def] at this simp [sub_eq_add_neg, this, add_comm] /-! ### Images under `x ↦ x - a` -/ @[simp] theorem image_sub_const_Ici : (fun x => x - a) '' Ici b = Ici (b - a) := by simp [sub_eq_neg_add] @[simp] theorem image_sub_const_Iic : (fun x => x - a) '' Iic b = Iic (b - a) := by simp [sub_eq_neg_add] @[simp] theorem image_sub_const_Ioi : (fun x => x - a) '' Ioi b = Ioi (b - a) := by simp [sub_eq_neg_add] @[simp] theorem image_sub_const_Iio : (fun x => x - a) '' Iio b = Iio (b - a) := by simp [sub_eq_neg_add] @[simp] theorem image_sub_const_Icc : (fun x => x - a) '' Icc b c = Icc (b - a) (c - a) := by simp [sub_eq_neg_add] @[simp] theorem image_sub_const_Ico : (fun x => x - a) '' Ico b c = Ico (b - a) (c - a) := by simp [sub_eq_neg_add] @[simp] theorem image_sub_const_Ioc : (fun x => x - a) '' Ioc b c = Ioc (b - a) (c - a) := by simp [sub_eq_neg_add] @[simp] theorem image_sub_const_Ioo : (fun x => x - a) '' Ioo b c = Ioo (b - a) (c - a) := by simp [sub_eq_neg_add] /-! ### Bijections -/ theorem Iic_add_bij : BijOn (· + a) (Iic b) (Iic (b + a)) := image_add_const_Iic a b ▸ (add_left_injective _).injOn.bijOn_image theorem Iio_add_bij : BijOn (· + a) (Iio b) (Iio (b + a)) := image_add_const_Iio a b ▸ (add_left_injective _).injOn.bijOn_image end OrderedAddCommGroup section LinearOrderedAddCommGroup variable [LinearOrderedAddCommGroup α] (a b c d : α) @[simp] theorem preimage_const_add_uIcc : (fun x => a + x) ⁻¹' [[b, c]] = [[b - a, c - a]] := by simp only [← Icc_min_max, preimage_const_add_Icc, min_sub_sub_right, max_sub_sub_right] @[simp] theorem preimage_add_const_uIcc : (fun x => x + a) ⁻¹' [[b, c]] = [[b - a, c - a]] := by simpa only [add_comm] using preimage_const_add_uIcc a b c -- TODO: Why is the notation `-[[a, b]]` broken? @[simp] theorem preimage_neg_uIcc : @Neg.neg (Set α) Set.neg [[a, b]] = [[-a, -b]] := by simp only [← Icc_min_max, preimage_neg_Icc, min_neg_neg, max_neg_neg] @[simp] theorem preimage_sub_const_uIcc : (fun x => x - a) ⁻¹' [[b, c]] = [[b + a, c + a]] := by simp [sub_eq_add_neg] @[simp] theorem preimage_const_sub_uIcc : (fun x => a - x) ⁻¹' [[b, c]] = [[a - b, a - c]] := by simp_rw [← Icc_min_max, preimage_const_sub_Icc] simp only [sub_eq_add_neg, min_add_add_left, max_add_add_left, min_neg_neg, max_neg_neg] -- @[simp] -- Porting note (#10618): simp can prove this module `add_comm` theorem image_const_add_uIcc : (fun x => a + x) '' [[b, c]] = [[a + b, a + c]] := by simp [add_comm] -- @[simp] -- Porting note (#10618): simp can prove this theorem image_add_const_uIcc : (fun x => x + a) '' [[b, c]] = [[b + a, c + a]] := by simp @[simp] theorem image_const_sub_uIcc : (fun x => a - x) '' [[b, c]] = [[a - b, a - c]] := by have := image_comp (fun x => a + x) fun x => -x; dsimp [Function.comp_def] at this simp [sub_eq_add_neg, this, add_comm] @[simp] theorem image_sub_const_uIcc : (fun x => x - a) '' [[b, c]] = [[b - a, c - a]] := by simp [sub_eq_add_neg, add_comm] theorem image_neg_uIcc : Neg.neg '' [[a, b]] = [[-a, -b]] := by simp variable {a b c d} /-- If `[c, d]` is a subinterval of `[a, b]`, then the distance between `c` and `d` is less than or equal to that of `a` and `b` -/ theorem abs_sub_le_of_uIcc_subset_uIcc (h : [[c, d]] ⊆ [[a, b]]) : |d - c| ≤ |b - a| := by rw [← max_sub_min_eq_abs, ← max_sub_min_eq_abs] rw [uIcc_subset_uIcc_iff_le] at h exact sub_le_sub h.2 h.1 /-- If `c ∈ [a, b]`, then the distance between `a` and `c` is less than or equal to that of `a` and `b` -/ theorem abs_sub_left_of_mem_uIcc (h : c ∈ [[a, b]]) : |c - a| ≤ |b - a| := abs_sub_le_of_uIcc_subset_uIcc <| uIcc_subset_uIcc_left h /-- If `x ∈ [a, b]`, then the distance between `c` and `b` is less than or equal to that of `a` and `b` -/ theorem abs_sub_right_of_mem_uIcc (h : c ∈ [[a, b]]) : |b - c| ≤ |b - a| := abs_sub_le_of_uIcc_subset_uIcc <| uIcc_subset_uIcc_right h end LinearOrderedAddCommGroup /-! ### Multiplication and inverse in a field -/ section LinearOrderedField variable [LinearOrderedField α] {a : α} @[simp] theorem preimage_mul_const_Iio (a : α) {c : α} (h : 0 < c) : (fun x => x * c) ⁻¹' Iio a = Iio (a / c) := ext fun _x => (lt_div_iff h).symm @[simp] theorem preimage_mul_const_Ioi (a : α) {c : α} (h : 0 < c) : (fun x => x * c) ⁻¹' Ioi a = Ioi (a / c) := ext fun _x => (div_lt_iff h).symm @[simp] theorem preimage_mul_const_Iic (a : α) {c : α} (h : 0 < c) : (fun x => x * c) ⁻¹' Iic a = Iic (a / c) := ext fun _x => (le_div_iff h).symm @[simp] theorem preimage_mul_const_Ici (a : α) {c : α} (h : 0 < c) : (fun x => x * c) ⁻¹' Ici a = Ici (a / c) := ext fun _x => (div_le_iff h).symm @[simp] theorem preimage_mul_const_Ioo (a b : α) {c : α} (h : 0 < c) : (fun x => x * c) ⁻¹' Ioo a b = Ioo (a / c) (b / c) := by simp [← Ioi_inter_Iio, h] @[simp] theorem preimage_mul_const_Ioc (a b : α) {c : α} (h : 0 < c) : (fun x => x * c) ⁻¹' Ioc a b = Ioc (a / c) (b / c) := by simp [← Ioi_inter_Iic, h] @[simp] theorem preimage_mul_const_Ico (a b : α) {c : α} (h : 0 < c) : (fun x => x * c) ⁻¹' Ico a b = Ico (a / c) (b / c) := by simp [← Ici_inter_Iio, h] @[simp] theorem preimage_mul_const_Icc (a b : α) {c : α} (h : 0 < c) : (fun x => x * c) ⁻¹' Icc a b = Icc (a / c) (b / c) := by simp [← Ici_inter_Iic, h] @[simp] theorem preimage_mul_const_Iio_of_neg (a : α) {c : α} (h : c < 0) : (fun x => x * c) ⁻¹' Iio a = Ioi (a / c) := ext fun _x => (div_lt_iff_of_neg h).symm @[simp] theorem preimage_mul_const_Ioi_of_neg (a : α) {c : α} (h : c < 0) : (fun x => x * c) ⁻¹' Ioi a = Iio (a / c) := ext fun _x => (lt_div_iff_of_neg h).symm @[simp] theorem preimage_mul_const_Iic_of_neg (a : α) {c : α} (h : c < 0) : (fun x => x * c) ⁻¹' Iic a = Ici (a / c) := ext fun _x => (div_le_iff_of_neg h).symm @[simp] theorem preimage_mul_const_Ici_of_neg (a : α) {c : α} (h : c < 0) : (fun x => x * c) ⁻¹' Ici a = Iic (a / c) := ext fun _x => (le_div_iff_of_neg h).symm @[simp] theorem preimage_mul_const_Ioo_of_neg (a b : α) {c : α} (h : c < 0) : (fun x => x * c) ⁻¹' Ioo a b = Ioo (b / c) (a / c) := by simp [← Ioi_inter_Iio, h, inter_comm] @[simp] theorem preimage_mul_const_Ioc_of_neg (a b : α) {c : α} (h : c < 0) : (fun x => x * c) ⁻¹' Ioc a b = Ico (b / c) (a / c) := by simp [← Ioi_inter_Iic, ← Ici_inter_Iio, h, inter_comm] @[simp] theorem preimage_mul_const_Ico_of_neg (a b : α) {c : α} (h : c < 0) : (fun x => x * c) ⁻¹' Ico a b = Ioc (b / c) (a / c) := by simp [← Ici_inter_Iio, ← Ioi_inter_Iic, h, inter_comm] @[simp] theorem preimage_mul_const_Icc_of_neg (a b : α) {c : α} (h : c < 0) : (fun x => x * c) ⁻¹' Icc a b = Icc (b / c) (a / c) := by simp [← Ici_inter_Iic, h, inter_comm] @[simp] theorem preimage_const_mul_Iio (a : α) {c : α} (h : 0 < c) : (c * ·) ⁻¹' Iio a = Iio (a / c) := ext fun _x => (lt_div_iff' h).symm @[simp] theorem preimage_const_mul_Ioi (a : α) {c : α} (h : 0 < c) : (c * ·) ⁻¹' Ioi a = Ioi (a / c) := ext fun _x => (div_lt_iff' h).symm @[simp] theorem preimage_const_mul_Iic (a : α) {c : α} (h : 0 < c) : (c * ·) ⁻¹' Iic a = Iic (a / c) := ext fun _x => (le_div_iff' h).symm @[simp] theorem preimage_const_mul_Ici (a : α) {c : α} (h : 0 < c) : (c * ·) ⁻¹' Ici a = Ici (a / c) := ext fun _x => (div_le_iff' h).symm @[simp] theorem preimage_const_mul_Ioo (a b : α) {c : α} (h : 0 < c) : (c * ·) ⁻¹' Ioo a b = Ioo (a / c) (b / c) := by simp [← Ioi_inter_Iio, h] @[simp] theorem preimage_const_mul_Ioc (a b : α) {c : α} (h : 0 < c) : (c * ·) ⁻¹' Ioc a b = Ioc (a / c) (b / c) := by simp [← Ioi_inter_Iic, h] @[simp] theorem preimage_const_mul_Ico (a b : α) {c : α} (h : 0 < c) : (c * ·) ⁻¹' Ico a b = Ico (a / c) (b / c) := by simp [← Ici_inter_Iio, h] @[simp] theorem preimage_const_mul_Icc (a b : α) {c : α} (h : 0 < c) : (c * ·) ⁻¹' Icc a b = Icc (a / c) (b / c) := by simp [← Ici_inter_Iic, h] @[simp] theorem preimage_const_mul_Iio_of_neg (a : α) {c : α} (h : c < 0) : (c * ·) ⁻¹' Iio a = Ioi (a / c) := by simpa only [mul_comm] using preimage_mul_const_Iio_of_neg a h @[simp] theorem preimage_const_mul_Ioi_of_neg (a : α) {c : α} (h : c < 0) : (c * ·) ⁻¹' Ioi a = Iio (a / c) := by simpa only [mul_comm] using preimage_mul_const_Ioi_of_neg a h @[simp] theorem preimage_const_mul_Iic_of_neg (a : α) {c : α} (h : c < 0) : (c * ·) ⁻¹' Iic a = Ici (a / c) := by simpa only [mul_comm] using preimage_mul_const_Iic_of_neg a h @[simp] theorem preimage_const_mul_Ici_of_neg (a : α) {c : α} (h : c < 0) : (c * ·) ⁻¹' Ici a = Iic (a / c) := by simpa only [mul_comm] using preimage_mul_const_Ici_of_neg a h @[simp] theorem preimage_const_mul_Ioo_of_neg (a b : α) {c : α} (h : c < 0) : (c * ·) ⁻¹' Ioo a b = Ioo (b / c) (a / c) := by simpa only [mul_comm] using preimage_mul_const_Ioo_of_neg a b h @[simp] theorem preimage_const_mul_Ioc_of_neg (a b : α) {c : α} (h : c < 0) : (c * ·) ⁻¹' Ioc a b = Ico (b / c) (a / c) := by simpa only [mul_comm] using preimage_mul_const_Ioc_of_neg a b h @[simp] theorem preimage_const_mul_Ico_of_neg (a b : α) {c : α} (h : c < 0) : (c * ·) ⁻¹' Ico a b = Ioc (b / c) (a / c) := by simpa only [mul_comm] using preimage_mul_const_Ico_of_neg a b h @[simp] theorem preimage_const_mul_Icc_of_neg (a b : α) {c : α} (h : c < 0) : (c * ·) ⁻¹' Icc a b = Icc (b / c) (a / c) := by simpa only [mul_comm] using preimage_mul_const_Icc_of_neg a b h @[simp] theorem preimage_mul_const_uIcc (ha : a ≠ 0) (b c : α) : (· * a) ⁻¹' [[b, c]] = [[b / a, c / a]] := (lt_or_gt_of_ne ha).elim (fun h => by simp [← Icc_min_max, h, h.le, min_div_div_right_of_nonpos, max_div_div_right_of_nonpos]) fun ha : 0 < a => by simp [← Icc_min_max, ha, ha.le, min_div_div_right, max_div_div_right] @[simp] theorem preimage_const_mul_uIcc (ha : a ≠ 0) (b c : α) : (a * ·) ⁻¹' [[b, c]] = [[b / a, c / a]] := by simp only [← preimage_mul_const_uIcc ha, mul_comm] @[simp] theorem preimage_div_const_uIcc (ha : a ≠ 0) (b c : α) : (fun x => x / a) ⁻¹' [[b, c]] = [[b * a, c * a]] := by simp only [div_eq_mul_inv, preimage_mul_const_uIcc (inv_ne_zero ha), inv_inv] @[simp] theorem image_mul_const_uIcc (a b c : α) : (· * a) '' [[b, c]] = [[b * a, c * a]] := if ha : a = 0 then by simp [ha] else calc (fun x => x * a) '' [[b, c]] = (· * a⁻¹) ⁻¹' [[b, c]] := (Units.mk0 a ha).mulRight.image_eq_preimage _ _ = (fun x => x / a) ⁻¹' [[b, c]] := by simp only [div_eq_mul_inv] _ = [[b * a, c * a]] := preimage_div_const_uIcc ha _ _ @[simp] theorem image_const_mul_uIcc (a b c : α) : (a * ·) '' [[b, c]] = [[a * b, a * c]] := by simpa only [mul_comm] using image_mul_const_uIcc a b c @[simp] theorem image_div_const_uIcc (a b c : α) : (fun x => x / a) '' [[b, c]] = [[b / a, c / a]] := by simp only [div_eq_mul_inv, image_mul_const_uIcc] theorem image_mul_right_Icc' (a b : α) {c : α} (h : 0 < c) : (fun x => x * c) '' Icc a b = Icc (a * c) (b * c) := ((Units.mk0 c h.ne').mulRight.image_eq_preimage _).trans (by simp [h, division_def]) theorem image_mul_right_Icc {a b c : α} (hab : a ≤ b) (hc : 0 ≤ c) : (fun x => x * c) '' Icc a b = Icc (a * c) (b * c) := by cases eq_or_lt_of_le hc · subst c simp [(nonempty_Icc.2 hab).image_const] exact image_mul_right_Icc' a b ‹0 < c› theorem image_mul_left_Icc' {a : α} (h : 0 < a) (b c : α) : (a * ·) '' Icc b c = Icc (a * b) (a * c) := by convert image_mul_right_Icc' b c h using 1 <;> simp only [mul_comm _ a] theorem image_mul_left_Icc {a b c : α} (ha : 0 ≤ a) (hbc : b ≤ c) : (a * ·) '' Icc b c = Icc (a * b) (a * c) := by convert image_mul_right_Icc hbc ha using 1 <;> simp only [mul_comm _ a] theorem image_mul_right_Ioo (a b : α) {c : α} (h : 0 < c) : (fun x => x * c) '' Ioo a b = Ioo (a * c) (b * c) := ((Units.mk0 c h.ne').mulRight.image_eq_preimage _).trans (by simp [h, division_def]) theorem image_mul_left_Ioo {a : α} (h : 0 < a) (b c : α) : (a * ·) '' Ioo b c = Ioo (a * b) (a * c) := by convert image_mul_right_Ioo b c h using 1 <;> simp only [mul_comm _ a] /-- The (pre)image under `inv` of `Ioo 0 a` is `Ioi a⁻¹`. -/ theorem inv_Ioo_0_left {a : α} (ha : 0 < a) : (Ioo 0 a)⁻¹ = Ioi a⁻¹ := by ext x exact ⟨fun h => inv_inv x ▸ (inv_lt_inv ha h.1).2 h.2, fun h => ⟨inv_pos (α := α) |>.2 <| (inv_pos (α := α) |>.2 ha).trans h, inv_inv a ▸ (inv_lt_inv ((inv_pos (α := α) |>.2 ha).trans h) (inv_pos (α := α) |>.2 ha)).2 h⟩⟩ theorem inv_Ioi {a : α} (ha : 0 < a) : (Ioi a)⁻¹ = Ioo 0 a⁻¹ := by rw [inv_eq_iff_eq_inv, inv_Ioo_0_left (inv_pos (α := α) |>.2 ha), inv_inv] theorem image_const_mul_Ioi_zero {k : Type*} [LinearOrderedField k] {x : k} (hx : 0 < x) : (fun y => x * y) '' Ioi (0 : k) = Ioi 0 := by erw [(Units.mk0 x hx.ne').mulLeft.image_eq_preimage, preimage_const_mul_Ioi 0 (inv_pos (α := k) |>.mpr hx), zero_div] /-! ### Images under `x ↦ a * x + b` -/ @[simp] theorem image_affine_Icc' {a : α} (h : 0 < a) (b c d : α) : (a * · + b) '' Icc c d = Icc (a * c + b) (a * d + b) := by suffices (· + b) '' ((a * ·) '' Icc c d) = Icc (a * c + b) (a * d + b) by rwa [Set.image_image] at this rw [image_mul_left_Icc' h, image_add_const_Icc] end LinearOrderedField end Set
Data\Set\Pointwise\Iterate.lean
/- Copyright (c) 2022 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import Mathlib.Algebra.GroupPower.IterateHom import Mathlib.Data.Set.Pointwise.SMul import Mathlib.Dynamics.FixedPoints.Basic /-! # Results about pointwise operations on sets with iteration. -/ open Pointwise open Set Function /-- Let `n : ℤ` and `s` a subset of a commutative group `G` that is invariant under preimage for the map `x ↦ x^n`. Then `s` is invariant under the pointwise action of the subgroup of elements `g : G` such that `g^(n^j) = 1` for some `j : ℕ`. (This subgroup is called the Prüfer subgroup when `G` is the `Circle` and `n` is prime.) -/ @[to_additive "Let `n : ℤ` and `s` a subset of an additive commutative group `G` that is invariant under preimage for the map `x ↦ n • x`. Then `s` is invariant under the pointwise action of the additive subgroup of elements `g : G` such that `(n^j) • g = 0` for some `j : ℕ`. (This additive subgroup is called the Prüfer subgroup when `G` is the `AddCircle` and `n` is prime.)"] theorem smul_eq_self_of_preimage_zpow_eq_self {G : Type*} [CommGroup G] {n : ℤ} {s : Set G} (hs : (fun x => x ^ n) ⁻¹' s = s) {g : G} {j : ℕ} (hg : g ^ n ^ j = 1) : g • s = s := by suffices ∀ {g' : G} (_ : g' ^ n ^ j = 1), g' • s ⊆ s by refine le_antisymm (this hg) ?_ conv_lhs => rw [← smul_inv_smul g s] replace hg : g⁻¹ ^ n ^ j = 1 := by rw [inv_zpow, hg, inv_one] simpa only [le_eq_subset, set_smul_subset_set_smul_iff] using this hg rw [(IsFixedPt.preimage_iterate hs j : (zpowGroupHom n)^[j] ⁻¹' s = s).symm] rintro g' hg' - ⟨y, hy, rfl⟩ change (zpowGroupHom n)^[j] (g' * y) ∈ s replace hg' : (zpowGroupHom n)^[j] g' = 1 := by simpa [zpowGroupHom] rwa [iterate_map_mul, hg', one_mul]
Data\Set\Pointwise\ListOfFn.lean
/- Copyright (c) 2022 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import Mathlib.Algebra.BigOperators.Group.List import Mathlib.Data.List.OfFn import Mathlib.Data.Set.Pointwise.Basic /-! # Pointwise operations with lists of sets This file proves some lemmas about pointwise algebraic operations with lists of sets. -/ namespace Set variable {F α β γ : Type*} variable [Monoid α] {s t : Set α} {a : α} {m n : ℕ} open Pointwise @[to_additive] theorem mem_prod_list_ofFn {a : α} {s : Fin n → Set α} : a ∈ (List.ofFn s).prod ↔ ∃ f : ∀ i : Fin n, s i, (List.ofFn fun i ↦ (f i : α)).prod = a := by induction' n with n ih generalizing a · simp_rw [List.ofFn_zero, List.prod_nil, Fin.exists_fin_zero_pi, eq_comm, Set.mem_one] · simp_rw [List.ofFn_succ, List.prod_cons, Fin.exists_fin_succ_pi, Fin.cons_zero, Fin.cons_succ, mem_mul, @ih, exists_exists_eq_and, SetCoe.exists, exists_prop] @[to_additive] theorem mem_list_prod {l : List (Set α)} {a : α} : a ∈ l.prod ↔ ∃ l' : List (Σs : Set α, ↥s), List.prod (l'.map fun x ↦ (Sigma.snd x : α)) = a ∧ l'.map Sigma.fst = l := by induction' l using List.ofFnRec with n f simp only [mem_prod_list_ofFn, List.exists_iff_exists_tuple, List.map_ofFn, Function.comp, List.ofFn_inj', Sigma.mk.inj_iff, and_left_comm, exists_and_left, exists_eq_left, heq_eq_eq] constructor · rintro ⟨fi, rfl⟩ exact ⟨fun i ↦ ⟨_, fi i⟩, rfl, rfl⟩ · rintro ⟨fi, rfl, rfl⟩ exact ⟨fun i ↦ _, rfl⟩ @[to_additive] theorem mem_pow {a : α} {n : ℕ} : a ∈ s ^ n ↔ ∃ f : Fin n → s, (List.ofFn fun i ↦ (f i : α)).prod = a := by rw [← mem_prod_list_ofFn, List.ofFn_const, List.prod_replicate] end Set
Data\Set\Pointwise\SMul.lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Floris van Doorn -/ import Mathlib.Algebra.Group.Pi.Basic import Mathlib.Algebra.Module.Defs import Mathlib.Data.Set.Pairwise.Basic import Mathlib.Data.Set.Pointwise.Basic import Mathlib.GroupTheory.GroupAction.Group /-! # Pointwise operations of sets This file defines pointwise algebraic operations on sets. ## Main declarations For sets `s` and `t` and scalar `a`: * `s • t`: Scalar multiplication, set of all `x • y` where `x ∈ s` and `y ∈ t`. * `s +ᵥ t`: Scalar addition, set of all `x +ᵥ y` where `x ∈ s` and `y ∈ t`. * `s -ᵥ t`: Scalar subtraction, set of all `x -ᵥ y` where `x ∈ s` and `y ∈ t`. * `a • s`: Scaling, set of all `a • x` where `x ∈ s`. * `a +ᵥ s`: Translation, set of all `a +ᵥ x` where `x ∈ s`. For `α` a semigroup/monoid, `Set α` is a semigroup/monoid. Appropriate definitions and results are also transported to the additive theory via `to_additive`. ## Implementation notes * We put all instances in the locale `Pointwise`, so that these instances are not available by default. Note that we do not mark them as reducible (as argued by note [reducible non-instances]) since we expect the locale to be open whenever the instances are actually used (and making the instances reducible changes the behavior of `simp`. -/ open Function MulOpposite variable {F α β γ : Type*} namespace Set open Pointwise /-! ### Translation/scaling of sets -/ section SMul /-- The dilation of set `x • s` is defined as `{x • y | y ∈ s}` in locale `Pointwise`. -/ @[to_additive "The translation of set `x +ᵥ s` is defined as `{x +ᵥ y | y ∈ s}` in locale `Pointwise`."] protected def smulSet [SMul α β] : SMul α (Set β) := ⟨fun a ↦ image (a • ·)⟩ /-- The pointwise scalar multiplication of sets `s • t` is defined as `{x • y | x ∈ s, y ∈ t}` in locale `Pointwise`. -/ @[to_additive "The pointwise scalar addition of sets `s +ᵥ t` is defined as `{x +ᵥ y | x ∈ s, y ∈ t}` in locale `Pointwise`."] protected def smul [SMul α β] : SMul (Set α) (Set β) := ⟨image2 (· • ·)⟩ scoped[Pointwise] attribute [instance] Set.smulSet Set.smul scoped[Pointwise] attribute [instance] Set.vaddSet Set.vadd section SMul variable {ι : Sort*} {κ : ι → Sort*} [SMul α β] {s s₁ s₂ : Set α} {t t₁ t₂ u : Set β} {a : α} {b : β} @[to_additive (attr := simp)] theorem image2_smul : image2 SMul.smul s t = s • t := rfl @[to_additive vadd_image_prod] theorem image_smul_prod : (fun x : α × β ↦ x.fst • x.snd) '' s ×ˢ t = s • t := image_prod _ @[to_additive] theorem mem_smul : b ∈ s • t ↔ ∃ x ∈ s, ∃ y ∈ t, x • y = b := Iff.rfl @[to_additive] theorem smul_mem_smul : a ∈ s → b ∈ t → a • b ∈ s • t := mem_image2_of_mem @[to_additive (attr := simp)] theorem empty_smul : (∅ : Set α) • t = ∅ := image2_empty_left @[to_additive (attr := simp)] theorem smul_empty : s • (∅ : Set β) = ∅ := image2_empty_right @[to_additive (attr := simp)] theorem smul_eq_empty : s • t = ∅ ↔ s = ∅ ∨ t = ∅ := image2_eq_empty_iff @[to_additive (attr := simp)] theorem smul_nonempty : (s • t).Nonempty ↔ s.Nonempty ∧ t.Nonempty := image2_nonempty_iff @[to_additive] theorem Nonempty.smul : s.Nonempty → t.Nonempty → (s • t).Nonempty := Nonempty.image2 @[to_additive] theorem Nonempty.of_smul_left : (s • t).Nonempty → s.Nonempty := Nonempty.of_image2_left @[to_additive] theorem Nonempty.of_smul_right : (s • t).Nonempty → t.Nonempty := Nonempty.of_image2_right @[to_additive (attr := simp low+1)] theorem smul_singleton : s • ({b} : Set β) = (· • b) '' s := image2_singleton_right @[to_additive (attr := simp low+1)] theorem singleton_smul : ({a} : Set α) • t = a • t := image2_singleton_left @[to_additive (attr := simp high)] theorem singleton_smul_singleton : ({a} : Set α) • ({b} : Set β) = {a • b} := image2_singleton @[to_additive (attr := mono)] theorem smul_subset_smul : s₁ ⊆ s₂ → t₁ ⊆ t₂ → s₁ • t₁ ⊆ s₂ • t₂ := image2_subset @[to_additive] theorem smul_subset_smul_left : t₁ ⊆ t₂ → s • t₁ ⊆ s • t₂ := image2_subset_left @[to_additive] theorem smul_subset_smul_right : s₁ ⊆ s₂ → s₁ • t ⊆ s₂ • t := image2_subset_right @[to_additive] theorem smul_subset_iff : s • t ⊆ u ↔ ∀ a ∈ s, ∀ b ∈ t, a • b ∈ u := image2_subset_iff @[to_additive] theorem union_smul : (s₁ ∪ s₂) • t = s₁ • t ∪ s₂ • t := image2_union_left @[to_additive] theorem smul_union : s • (t₁ ∪ t₂) = s • t₁ ∪ s • t₂ := image2_union_right @[to_additive] theorem inter_smul_subset : (s₁ ∩ s₂) • t ⊆ s₁ • t ∩ s₂ • t := image2_inter_subset_left @[to_additive] theorem smul_inter_subset : s • (t₁ ∩ t₂) ⊆ s • t₁ ∩ s • t₂ := image2_inter_subset_right @[to_additive] theorem inter_smul_union_subset_union : (s₁ ∩ s₂) • (t₁ ∪ t₂) ⊆ s₁ • t₁ ∪ s₂ • t₂ := image2_inter_union_subset_union @[to_additive] theorem union_smul_inter_subset_union : (s₁ ∪ s₂) • (t₁ ∩ t₂) ⊆ s₁ • t₁ ∪ s₂ • t₂ := image2_union_inter_subset_union @[to_additive] theorem iUnion_smul_left_image : ⋃ a ∈ s, a • t = s • t := iUnion_image_left _ @[to_additive] theorem iUnion_smul_right_image : ⋃ a ∈ t, (· • a) '' s = s • t := iUnion_image_right _ @[to_additive] theorem iUnion_smul (s : ι → Set α) (t : Set β) : (⋃ i, s i) • t = ⋃ i, s i • t := image2_iUnion_left _ _ _ @[to_additive] theorem smul_iUnion (s : Set α) (t : ι → Set β) : (s • ⋃ i, t i) = ⋃ i, s • t i := image2_iUnion_right _ _ _ @[to_additive] theorem iUnion₂_smul (s : ∀ i, κ i → Set α) (t : Set β) : (⋃ (i) (j), s i j) • t = ⋃ (i) (j), s i j • t := image2_iUnion₂_left _ _ _ @[to_additive] theorem smul_iUnion₂ (s : Set α) (t : ∀ i, κ i → Set β) : (s • ⋃ (i) (j), t i j) = ⋃ (i) (j), s • t i j := image2_iUnion₂_right _ _ _ @[to_additive] theorem iInter_smul_subset (s : ι → Set α) (t : Set β) : (⋂ i, s i) • t ⊆ ⋂ i, s i • t := image2_iInter_subset_left _ _ _ @[to_additive] theorem smul_iInter_subset (s : Set α) (t : ι → Set β) : (s • ⋂ i, t i) ⊆ ⋂ i, s • t i := image2_iInter_subset_right _ _ _ @[to_additive] theorem iInter₂_smul_subset (s : ∀ i, κ i → Set α) (t : Set β) : (⋂ (i) (j), s i j) • t ⊆ ⋂ (i) (j), s i j • t := image2_iInter₂_subset_left _ _ _ @[to_additive] theorem smul_iInter₂_subset (s : Set α) (t : ∀ i, κ i → Set β) : (s • ⋂ (i) (j), t i j) ⊆ ⋂ (i) (j), s • t i j := image2_iInter₂_subset_right _ _ _ @[to_additive] theorem smul_set_subset_smul {s : Set α} : a ∈ s → a • t ⊆ s • t := image_subset_image2_right @[to_additive (attr := simp)] theorem iUnion_smul_set (s : Set α) (t : Set β) : ⋃ a ∈ s, a • t = s • t := iUnion_image_left _ end SMul section SMulSet variable {ι : Sort*} {κ : ι → Sort*} [SMul α β] {s t t₁ t₂ : Set β} {a : α} {b : β} {x y : β} @[to_additive] theorem image_smul : (fun x ↦ a • x) '' t = a • t := rfl scoped[Pointwise] attribute [simp] Set.image_smul Set.image_vadd @[to_additive] theorem mem_smul_set : x ∈ a • t ↔ ∃ y, y ∈ t ∧ a • y = x := Iff.rfl @[to_additive] theorem smul_mem_smul_set : b ∈ s → a • b ∈ a • s := mem_image_of_mem _ @[to_additive (attr := simp)] theorem smul_set_empty : a • (∅ : Set β) = ∅ := image_empty _ @[to_additive (attr := simp)] theorem smul_set_eq_empty : a • s = ∅ ↔ s = ∅ := image_eq_empty @[to_additive (attr := simp)] theorem smul_set_nonempty : (a • s).Nonempty ↔ s.Nonempty := image_nonempty @[to_additive (attr := simp)] theorem smul_set_singleton : a • ({b} : Set β) = {a • b} := image_singleton @[to_additive] theorem smul_set_mono : s ⊆ t → a • s ⊆ a • t := image_subset _ @[to_additive] theorem smul_set_subset_iff : a • s ⊆ t ↔ ∀ ⦃b⦄, b ∈ s → a • b ∈ t := image_subset_iff @[to_additive] theorem smul_set_union : a • (t₁ ∪ t₂) = a • t₁ ∪ a • t₂ := image_union _ _ _ @[to_additive] theorem smul_set_inter_subset : a • (t₁ ∩ t₂) ⊆ a • t₁ ∩ a • t₂ := image_inter_subset _ _ _ @[to_additive] theorem smul_set_iUnion (a : α) (s : ι → Set β) : (a • ⋃ i, s i) = ⋃ i, a • s i := image_iUnion @[to_additive] theorem smul_set_iUnion₂ (a : α) (s : ∀ i, κ i → Set β) : (a • ⋃ (i) (j), s i j) = ⋃ (i) (j), a • s i j := image_iUnion₂ _ _ @[to_additive] theorem smul_set_iInter_subset (a : α) (t : ι → Set β) : (a • ⋂ i, t i) ⊆ ⋂ i, a • t i := image_iInter_subset _ _ @[to_additive] theorem smul_set_iInter₂_subset (a : α) (t : ∀ i, κ i → Set β) : (a • ⋂ (i) (j), t i j) ⊆ ⋂ (i) (j), a • t i j := image_iInter₂_subset _ _ @[to_additive] theorem Nonempty.smul_set : s.Nonempty → (a • s).Nonempty := Nonempty.image _ end SMulSet section Mul variable [Mul α] {s t u : Set α} {a : α} @[to_additive] theorem op_smul_set_subset_mul : a ∈ t → op a • s ⊆ s * t := image_subset_image2_left @[to_additive] theorem image_op_smul : (op '' s) • t = t * s := by rw [← image2_smul, ← image2_mul, image2_image_left, image2_swap] rfl @[to_additive (attr := simp)] theorem iUnion_op_smul_set (s t : Set α) : ⋃ a ∈ t, MulOpposite.op a • s = s * t := iUnion_image_right _ @[to_additive] theorem mul_subset_iff_left : s * t ⊆ u ↔ ∀ a ∈ s, a • t ⊆ u := image2_subset_iff_left @[to_additive] theorem mul_subset_iff_right : s * t ⊆ u ↔ ∀ b ∈ t, op b • s ⊆ u := image2_subset_iff_right end Mul variable {s s₁ s₂ : Set α} {t t₁ t₂ : Set β} {a : α} {b : β} @[to_additive] theorem range_smul_range {ι κ : Type*} [SMul α β] (b : ι → α) (c : κ → β) : range b • range c = range fun p : ι × κ ↦ b p.1 • c p.2 := image2_range .. @[to_additive] theorem smul_set_range [SMul α β] {ι : Sort*} (a : α) (f : ι → β) : a • range f = range fun i ↦ a • f i := (range_comp _ _).symm @[to_additive] lemma range_smul [SMul α β] {ι : Sort*} (a : α) (f : ι → β) : range (fun i ↦ a • f i) = a • range f := (smul_set_range ..).symm @[to_additive] lemma range_mul [Mul α] {ι : Sort*} (a : α) (f : ι → α) : range (fun i ↦ a * f i) = a • range f := range_smul a f @[to_additive] instance smulCommClass_set [SMul α γ] [SMul β γ] [SMulCommClass α β γ] : SMulCommClass α β (Set γ) := ⟨fun _ _ ↦ Commute.set_image <| smul_comm _ _⟩ @[to_additive] instance smulCommClass_set' [SMul α γ] [SMul β γ] [SMulCommClass α β γ] : SMulCommClass α (Set β) (Set γ) := ⟨fun _ _ _ ↦ image_image2_distrib_right <| smul_comm _⟩ @[to_additive] instance smulCommClass_set'' [SMul α γ] [SMul β γ] [SMulCommClass α β γ] : SMulCommClass (Set α) β (Set γ) := haveI := SMulCommClass.symm α β γ SMulCommClass.symm _ _ _ @[to_additive] instance smulCommClass [SMul α γ] [SMul β γ] [SMulCommClass α β γ] : SMulCommClass (Set α) (Set β) (Set γ) := ⟨fun _ _ _ ↦ image2_left_comm smul_comm⟩ @[to_additive vaddAssocClass] instance isScalarTower [SMul α β] [SMul α γ] [SMul β γ] [IsScalarTower α β γ] : IsScalarTower α β (Set γ) where smul_assoc a b T := by simp only [← image_smul, image_image, smul_assoc] @[to_additive vaddAssocClass'] instance isScalarTower' [SMul α β] [SMul α γ] [SMul β γ] [IsScalarTower α β γ] : IsScalarTower α (Set β) (Set γ) := ⟨fun _ _ _ ↦ image2_image_left_comm <| smul_assoc _⟩ @[to_additive vaddAssocClass''] instance isScalarTower'' [SMul α β] [SMul α γ] [SMul β γ] [IsScalarTower α β γ] : IsScalarTower (Set α) (Set β) (Set γ) where smul_assoc _ _ _ := image2_assoc smul_assoc @[to_additive] instance isCentralScalar [SMul α β] [SMul αᵐᵒᵖ β] [IsCentralScalar α β] : IsCentralScalar α (Set β) := ⟨fun _ S ↦ (congr_arg fun f ↦ f '' S) <| funext fun _ ↦ op_smul_eq_smul _ _⟩ /-- A multiplicative action of a monoid `α` on a type `β` gives a multiplicative action of `Set α` on `Set β`. -/ @[to_additive "An additive action of an additive monoid `α` on a type `β` gives an additive action of `Set α` on `Set β`"] protected def mulAction [Monoid α] [MulAction α β] : MulAction (Set α) (Set β) where mul_smul _ _ _ := image2_assoc mul_smul one_smul s := image2_singleton_left.trans <| by simp_rw [one_smul, image_id'] /-- A multiplicative action of a monoid on a type `β` gives a multiplicative action on `Set β`. -/ @[to_additive "An additive action of an additive monoid on a type `β` gives an additive action on `Set β`."] protected def mulActionSet [Monoid α] [MulAction α β] : MulAction α (Set β) where mul_smul _ _ _ := by simp only [← image_smul, image_image, ← mul_smul] one_smul _ := by simp only [← image_smul, one_smul, image_id'] scoped[Pointwise] attribute [instance] Set.mulActionSet Set.addActionSet Set.mulAction Set.addAction /-- If scalar multiplication by elements of `α` sends `(0 : β)` to zero, then the same is true for `(0 : Set β)`. -/ protected def smulZeroClassSet [Zero β] [SMulZeroClass α β] : SMulZeroClass α (Set β) where smul_zero _ := image_singleton.trans <| by rw [smul_zero, singleton_zero] scoped[Pointwise] attribute [instance] Set.smulZeroClassSet /-- If the scalar multiplication `(· • ·) : α → β → β` is distributive, then so is `(· • ·) : α → Set β → Set β`. -/ protected def distribSMulSet [AddZeroClass β] [DistribSMul α β] : DistribSMul α (Set β) where smul_add _ _ _ := image_image2_distrib <| smul_add _ scoped[Pointwise] attribute [instance] Set.distribSMulSet /-- A distributive multiplicative action of a monoid on an additive monoid `β` gives a distributive multiplicative action on `Set β`. -/ protected def distribMulActionSet [Monoid α] [AddMonoid β] [DistribMulAction α β] : DistribMulAction α (Set β) where smul_add := smul_add smul_zero := smul_zero /-- A multiplicative action of a monoid on a monoid `β` gives a multiplicative action on `Set β`. -/ protected def mulDistribMulActionSet [Monoid α] [Monoid β] [MulDistribMulAction α β] : MulDistribMulAction α (Set β) where smul_mul _ _ _ := image_image2_distrib <| smul_mul' _ smul_one _ := image_singleton.trans <| by rw [smul_one, singleton_one] scoped[Pointwise] attribute [instance] Set.distribMulActionSet Set.mulDistribMulActionSet instance [Zero α] [Zero β] [SMul α β] [NoZeroSMulDivisors α β] : NoZeroSMulDivisors (Set α) (Set β) := ⟨fun {s t} h ↦ by by_contra! H have hst : (s • t).Nonempty := h.symm.subst zero_nonempty rw [Ne, ← hst.of_smul_left.subset_zero_iff, Ne, ← hst.of_smul_right.subset_zero_iff] at H simp only [not_subset, mem_zero] at H obtain ⟨⟨a, hs, ha⟩, b, ht, hb⟩ := H exact (eq_zero_or_eq_zero_of_smul_eq_zero <| h.subset <| smul_mem_smul hs ht).elim ha hb⟩ instance noZeroSMulDivisors_set [Zero α] [Zero β] [SMul α β] [NoZeroSMulDivisors α β] : NoZeroSMulDivisors α (Set β) := ⟨fun {a s} h ↦ by by_contra! H have hst : (a • s).Nonempty := h.symm.subst zero_nonempty rw [Ne, Ne, ← hst.of_image.subset_zero_iff, not_subset] at H obtain ⟨ha, b, ht, hb⟩ := H exact (eq_zero_or_eq_zero_of_smul_eq_zero <| h.subset <| smul_mem_smul_set ht).elim ha hb⟩ instance [Zero α] [Mul α] [NoZeroDivisors α] : NoZeroDivisors (Set α) := ⟨fun h ↦ eq_zero_or_eq_zero_of_smul_eq_zero h⟩ end SMul section VSub variable {ι : Sort*} {κ : ι → Sort*} [VSub α β] {s s₁ s₂ t t₁ t₂ : Set β} {u : Set α} {a : α} {b c : β} instance vsub : VSub (Set α) (Set β) := ⟨image2 (· -ᵥ ·)⟩ @[simp] theorem image2_vsub : (image2 VSub.vsub s t : Set α) = s -ᵥ t := rfl theorem image_vsub_prod : (fun x : β × β ↦ x.fst -ᵥ x.snd) '' s ×ˢ t = s -ᵥ t := image_prod _ theorem mem_vsub : a ∈ s -ᵥ t ↔ ∃ x ∈ s, ∃ y ∈ t, x -ᵥ y = a := Iff.rfl theorem vsub_mem_vsub (hb : b ∈ s) (hc : c ∈ t) : b -ᵥ c ∈ s -ᵥ t := mem_image2_of_mem hb hc @[simp] theorem empty_vsub (t : Set β) : ∅ -ᵥ t = ∅ := image2_empty_left @[simp] theorem vsub_empty (s : Set β) : s -ᵥ ∅ = ∅ := image2_empty_right @[simp] theorem vsub_eq_empty : s -ᵥ t = ∅ ↔ s = ∅ ∨ t = ∅ := image2_eq_empty_iff @[simp] theorem vsub_nonempty : (s -ᵥ t : Set α).Nonempty ↔ s.Nonempty ∧ t.Nonempty := image2_nonempty_iff theorem Nonempty.vsub : s.Nonempty → t.Nonempty → (s -ᵥ t : Set α).Nonempty := Nonempty.image2 theorem Nonempty.of_vsub_left : (s -ᵥ t : Set α).Nonempty → s.Nonempty := Nonempty.of_image2_left theorem Nonempty.of_vsub_right : (s -ᵥ t : Set α).Nonempty → t.Nonempty := Nonempty.of_image2_right @[simp low+1] theorem vsub_singleton (s : Set β) (b : β) : s -ᵥ {b} = (· -ᵥ b) '' s := image2_singleton_right @[simp low+1] theorem singleton_vsub (t : Set β) (b : β) : {b} -ᵥ t = (b -ᵥ ·) '' t := image2_singleton_left @[simp high] theorem singleton_vsub_singleton : ({b} : Set β) -ᵥ {c} = {b -ᵥ c} := image2_singleton @[mono] theorem vsub_subset_vsub : s₁ ⊆ s₂ → t₁ ⊆ t₂ → s₁ -ᵥ t₁ ⊆ s₂ -ᵥ t₂ := image2_subset theorem vsub_subset_vsub_left : t₁ ⊆ t₂ → s -ᵥ t₁ ⊆ s -ᵥ t₂ := image2_subset_left theorem vsub_subset_vsub_right : s₁ ⊆ s₂ → s₁ -ᵥ t ⊆ s₂ -ᵥ t := image2_subset_right theorem vsub_subset_iff : s -ᵥ t ⊆ u ↔ ∀ x ∈ s, ∀ y ∈ t, x -ᵥ y ∈ u := image2_subset_iff theorem vsub_self_mono (h : s ⊆ t) : s -ᵥ s ⊆ t -ᵥ t := vsub_subset_vsub h h theorem union_vsub : s₁ ∪ s₂ -ᵥ t = s₁ -ᵥ t ∪ (s₂ -ᵥ t) := image2_union_left theorem vsub_union : s -ᵥ (t₁ ∪ t₂) = s -ᵥ t₁ ∪ (s -ᵥ t₂) := image2_union_right theorem inter_vsub_subset : s₁ ∩ s₂ -ᵥ t ⊆ (s₁ -ᵥ t) ∩ (s₂ -ᵥ t) := image2_inter_subset_left theorem vsub_inter_subset : s -ᵥ t₁ ∩ t₂ ⊆ (s -ᵥ t₁) ∩ (s -ᵥ t₂) := image2_inter_subset_right theorem inter_vsub_union_subset_union : s₁ ∩ s₂ -ᵥ (t₁ ∪ t₂) ⊆ s₁ -ᵥ t₁ ∪ (s₂ -ᵥ t₂) := image2_inter_union_subset_union theorem union_vsub_inter_subset_union : s₁ ∪ s₂ -ᵥ t₁ ∩ t₂ ⊆ s₁ -ᵥ t₁ ∪ (s₂ -ᵥ t₂) := image2_union_inter_subset_union theorem iUnion_vsub_left_image : ⋃ a ∈ s, (a -ᵥ ·) '' t = s -ᵥ t := iUnion_image_left _ theorem iUnion_vsub_right_image : ⋃ a ∈ t, (· -ᵥ a) '' s = s -ᵥ t := iUnion_image_right _ theorem iUnion_vsub (s : ι → Set β) (t : Set β) : (⋃ i, s i) -ᵥ t = ⋃ i, s i -ᵥ t := image2_iUnion_left _ _ _ theorem vsub_iUnion (s : Set β) (t : ι → Set β) : (s -ᵥ ⋃ i, t i) = ⋃ i, s -ᵥ t i := image2_iUnion_right _ _ _ theorem iUnion₂_vsub (s : ∀ i, κ i → Set β) (t : Set β) : (⋃ (i) (j), s i j) -ᵥ t = ⋃ (i) (j), s i j -ᵥ t := image2_iUnion₂_left _ _ _ theorem vsub_iUnion₂ (s : Set β) (t : ∀ i, κ i → Set β) : (s -ᵥ ⋃ (i) (j), t i j) = ⋃ (i) (j), s -ᵥ t i j := image2_iUnion₂_right _ _ _ theorem iInter_vsub_subset (s : ι → Set β) (t : Set β) : (⋂ i, s i) -ᵥ t ⊆ ⋂ i, s i -ᵥ t := image2_iInter_subset_left _ _ _ theorem vsub_iInter_subset (s : Set β) (t : ι → Set β) : (s -ᵥ ⋂ i, t i) ⊆ ⋂ i, s -ᵥ t i := image2_iInter_subset_right _ _ _ theorem iInter₂_vsub_subset (s : ∀ i, κ i → Set β) (t : Set β) : (⋂ (i) (j), s i j) -ᵥ t ⊆ ⋂ (i) (j), s i j -ᵥ t := image2_iInter₂_subset_left _ _ _ theorem vsub_iInter₂_subset (s : Set β) (t : ∀ i, κ i → Set β) : (s -ᵥ ⋂ (i) (j), t i j) ⊆ ⋂ (i) (j), s -ᵥ t i j := image2_iInter₂_subset_right _ _ _ end VSub open Pointwise @[to_additive] theorem image_smul_comm [SMul α β] [SMul α γ] (f : β → γ) (a : α) (s : Set β) : (∀ b, f (a • b) = a • f b) → f '' (a • s) = a • f '' s := image_comm @[to_additive] theorem image_smul_distrib [MulOneClass α] [MulOneClass β] [FunLike F α β] [MonoidHomClass F α β] (f : F) (a : α) (s : Set α) : f '' (a • s) = f a • f '' s := image_comm <| map_mul _ _ section SMul variable [SMul αᵐᵒᵖ β] [SMul β γ] [SMul α γ] -- TODO: replace hypothesis and conclusion with a typeclass @[to_additive] theorem op_smul_set_smul_eq_smul_smul_set (a : α) (s : Set β) (t : Set γ) (h : ∀ (a : α) (b : β) (c : γ), (op a • b) • c = b • a • c) : (op a • s) • t = s • a • t := by ext simp [mem_smul, mem_smul_set, h] end SMul section SMulZeroClass variable [Zero β] [SMulZeroClass α β] {s : Set α} {t : Set β} {a : α} theorem smul_zero_subset (s : Set α) : s • (0 : Set β) ⊆ 0 := by simp [subset_def, mem_smul] theorem Nonempty.smul_zero (hs : s.Nonempty) : s • (0 : Set β) = 0 := s.smul_zero_subset.antisymm <| by simpa [mem_smul] using hs theorem zero_mem_smul_set (h : (0 : β) ∈ t) : (0 : β) ∈ a • t := ⟨0, h, smul_zero _⟩ variable [Zero α] [NoZeroSMulDivisors α β] theorem zero_mem_smul_set_iff (ha : a ≠ 0) : (0 : β) ∈ a • t ↔ (0 : β) ∈ t := by refine ⟨?_, zero_mem_smul_set⟩ rintro ⟨b, hb, h⟩ rwa [(eq_zero_or_eq_zero_of_smul_eq_zero h).resolve_left ha] at hb end SMulZeroClass section SMulWithZero variable [Zero α] [Zero β] [SMulWithZero α β] {s : Set α} {t : Set β} /-! Note that we have neither `SMulWithZero α (Set β)` nor `SMulWithZero (Set α) (Set β)` because `0 * ∅ ≠ 0`. -/ theorem zero_smul_subset (t : Set β) : (0 : Set α) • t ⊆ 0 := by simp [subset_def, mem_smul] theorem Nonempty.zero_smul (ht : t.Nonempty) : (0 : Set α) • t = 0 := t.zero_smul_subset.antisymm <| by simpa [mem_smul] using ht /-- A nonempty set is scaled by zero to the singleton set containing 0. -/ @[simp] theorem zero_smul_set {s : Set β} (h : s.Nonempty) : (0 : α) • s = (0 : Set β) := by simp only [← image_smul, image_eta, zero_smul, h.image_const, singleton_zero] theorem zero_smul_set_subset (s : Set β) : (0 : α) • s ⊆ 0 := image_subset_iff.2 fun x _ ↦ zero_smul α x theorem subsingleton_zero_smul_set (s : Set β) : ((0 : α) • s).Subsingleton := subsingleton_singleton.anti <| zero_smul_set_subset s variable [NoZeroSMulDivisors α β] {a : α} theorem zero_mem_smul_iff : (0 : β) ∈ s • t ↔ (0 : α) ∈ s ∧ t.Nonempty ∨ (0 : β) ∈ t ∧ s.Nonempty := by constructor · rintro ⟨a, ha, b, hb, h⟩ obtain rfl | rfl := eq_zero_or_eq_zero_of_smul_eq_zero h · exact Or.inl ⟨ha, b, hb⟩ · exact Or.inr ⟨hb, a, ha⟩ · rintro (⟨hs, b, hb⟩ | ⟨ht, a, ha⟩) · exact ⟨0, hs, b, hb, zero_smul _ _⟩ · exact ⟨a, ha, 0, ht, smul_zero _⟩ end SMulWithZero section Semigroup variable [Semigroup α] @[to_additive] theorem op_smul_set_mul_eq_mul_smul_set (a : α) (s : Set α) (t : Set α) : op a • s * t = s * a • t := op_smul_set_smul_eq_smul_smul_set _ _ _ fun _ _ _ => mul_assoc _ _ _ end Semigroup section IsLeftCancelMul variable [Mul α] [IsLeftCancelMul α] {s t : Set α} @[to_additive] theorem pairwiseDisjoint_smul_iff : s.PairwiseDisjoint (· • t) ↔ (s ×ˢ t).InjOn fun p ↦ p.1 * p.2 := pairwiseDisjoint_image_right_iff fun _ _ ↦ mul_right_injective _ end IsLeftCancelMul section Group variable [Group α] [MulAction α β] {s t A B : Set β} {a : α} {x : β} @[to_additive (attr := simp)] theorem smul_mem_smul_set_iff : a • x ∈ a • s ↔ x ∈ s := (MulAction.injective _).mem_set_image @[to_additive] theorem mem_smul_set_iff_inv_smul_mem : x ∈ a • A ↔ a⁻¹ • x ∈ A := show x ∈ MulAction.toPerm a '' A ↔ _ from mem_image_equiv @[to_additive] theorem mem_inv_smul_set_iff : x ∈ a⁻¹ • A ↔ a • x ∈ A := by simp only [← image_smul, mem_image, inv_smul_eq_iff, exists_eq_right] @[to_additive] theorem preimage_smul (a : α) (t : Set β) : (fun x ↦ a • x) ⁻¹' t = a⁻¹ • t := ((MulAction.toPerm a).symm.image_eq_preimage _).symm @[to_additive] theorem preimage_smul_inv (a : α) (t : Set β) : (fun x ↦ a⁻¹ • x) ⁻¹' t = a • t := preimage_smul (toUnits a)⁻¹ t @[to_additive (attr := simp)] theorem set_smul_subset_set_smul_iff : a • A ⊆ a • B ↔ A ⊆ B := image_subset_image_iff <| MulAction.injective _ @[to_additive] theorem set_smul_subset_iff : a • A ⊆ B ↔ A ⊆ a⁻¹ • B := image_subset_iff.trans <| iff_of_eq <| congr_arg _ <| preimage_equiv_eq_image_symm _ <| MulAction.toPerm _ @[to_additive] theorem subset_set_smul_iff : A ⊆ a • B ↔ a⁻¹ • A ⊆ B := Iff.symm <| image_subset_iff.trans <| Iff.symm <| iff_of_eq <| congr_arg _ <| image_equiv_eq_preimage_symm _ <| MulAction.toPerm _ @[to_additive] theorem smul_set_inter : a • (s ∩ t) = a • s ∩ a • t := image_inter <| MulAction.injective a @[to_additive] theorem smul_set_iInter {ι : Type*} (a : α) (t : ι → Set β) : (a • ⋂ i, t i) = ⋂ i, a • t i := image_iInter (MulAction.bijective a) t @[to_additive] theorem smul_set_sdiff : a • (s \ t) = a • s \ a • t := image_diff (MulAction.injective a) _ _ open scoped symmDiff in @[to_additive] theorem smul_set_symmDiff : a • s ∆ t = (a • s) ∆ (a • t) := image_symmDiff (MulAction.injective a) _ _ @[to_additive (attr := simp)] theorem smul_set_univ : a • (univ : Set β) = univ := image_univ_of_surjective <| MulAction.surjective a @[to_additive (attr := simp)] theorem smul_univ {s : Set α} (hs : s.Nonempty) : s • (univ : Set β) = univ := let ⟨a, ha⟩ := hs eq_univ_of_forall fun b ↦ ⟨a, ha, a⁻¹ • b, trivial, smul_inv_smul _ _⟩ @[to_additive] theorem smul_set_compl : a • sᶜ = (a • s)ᶜ := by simp_rw [Set.compl_eq_univ_diff, smul_set_sdiff, smul_set_univ] @[to_additive] theorem smul_inter_ne_empty_iff {s t : Set α} {x : α} : x • s ∩ t ≠ ∅ ↔ ∃ a b, (a ∈ t ∧ b ∈ s) ∧ a * b⁻¹ = x := by rw [← nonempty_iff_ne_empty] constructor · rintro ⟨a, h, ha⟩ obtain ⟨b, hb, rfl⟩ := mem_smul_set.mp h exact ⟨x • b, b, ⟨ha, hb⟩, by simp⟩ · rintro ⟨a, b, ⟨ha, hb⟩, rfl⟩ exact ⟨a, mem_inter (mem_smul_set.mpr ⟨b, hb, by simp⟩) ha⟩ @[to_additive] theorem smul_inter_ne_empty_iff' {s t : Set α} {x : α} : x • s ∩ t ≠ ∅ ↔ ∃ a b, (a ∈ t ∧ b ∈ s) ∧ a / b = x := by simp_rw [smul_inter_ne_empty_iff, div_eq_mul_inv] @[to_additive] theorem op_smul_inter_ne_empty_iff {s t : Set α} {x : αᵐᵒᵖ} : x • s ∩ t ≠ ∅ ↔ ∃ a b, (a ∈ s ∧ b ∈ t) ∧ a⁻¹ * b = MulOpposite.unop x := by rw [← nonempty_iff_ne_empty] constructor · rintro ⟨a, h, ha⟩ obtain ⟨b, hb, rfl⟩ := mem_smul_set.mp h exact ⟨b, x • b, ⟨hb, ha⟩, by simp⟩ · rintro ⟨a, b, ⟨ha, hb⟩, H⟩ have : MulOpposite.op (a⁻¹ * b) = x := congr_arg MulOpposite.op H exact ⟨b, mem_inter (mem_smul_set.mpr ⟨a, ha, by simp [← this]⟩) hb⟩ @[to_additive (attr := simp)] theorem iUnion_inv_smul : ⋃ g : α, g⁻¹ • s = ⋃ g : α, g • s := (Function.Surjective.iSup_congr _ inv_surjective) fun _ ↦ rfl @[to_additive] theorem iUnion_smul_eq_setOf_exists {s : Set β} : ⋃ g : α, g • s = { a | ∃ g : α, g • a ∈ s } := by simp_rw [← iUnion_setOf, ← iUnion_inv_smul, ← preimage_smul, preimage] @[to_additive (attr := simp)] lemma inv_smul_set_distrib (a : α) (s : Set α) : (a • s)⁻¹ = op a⁻¹ • s⁻¹ := by ext; simp [mem_smul_set_iff_inv_smul_mem] @[to_additive (attr := simp)] lemma inv_op_smul_set_distrib (a : α) (s : Set α) : (op a • s)⁻¹ = a⁻¹ • s⁻¹ := by ext; simp [mem_smul_set_iff_inv_smul_mem] @[to_additive (attr := simp)] lemma smul_set_disjoint_iff : Disjoint (a • s) (a • t) ↔ Disjoint s t := by simp [disjoint_iff, ← smul_set_inter] end Group section GroupWithZero variable [GroupWithZero α] [MulAction α β] {s t : Set β} {a : α} @[simp] theorem smul_mem_smul_set_iff₀ (ha : a ≠ 0) (A : Set β) (x : β) : a • x ∈ a • A ↔ x ∈ A := show Units.mk0 a ha • _ ∈ _ ↔ _ from smul_mem_smul_set_iff theorem mem_smul_set_iff_inv_smul_mem₀ (ha : a ≠ 0) (A : Set β) (x : β) : x ∈ a • A ↔ a⁻¹ • x ∈ A := show _ ∈ Units.mk0 a ha • _ ↔ _ from mem_smul_set_iff_inv_smul_mem theorem mem_inv_smul_set_iff₀ (ha : a ≠ 0) (A : Set β) (x : β) : x ∈ a⁻¹ • A ↔ a • x ∈ A := show _ ∈ (Units.mk0 a ha)⁻¹ • _ ↔ _ from mem_inv_smul_set_iff theorem preimage_smul₀ (ha : a ≠ 0) (t : Set β) : (fun x ↦ a • x) ⁻¹' t = a⁻¹ • t := preimage_smul (Units.mk0 a ha) t theorem preimage_smul_inv₀ (ha : a ≠ 0) (t : Set β) : (fun x ↦ a⁻¹ • x) ⁻¹' t = a • t := preimage_smul (Units.mk0 a ha)⁻¹ t @[simp] theorem set_smul_subset_set_smul_iff₀ (ha : a ≠ 0) {A B : Set β} : a • A ⊆ a • B ↔ A ⊆ B := show Units.mk0 a ha • _ ⊆ _ ↔ _ from set_smul_subset_set_smul_iff theorem set_smul_subset_iff₀ (ha : a ≠ 0) {A B : Set β} : a • A ⊆ B ↔ A ⊆ a⁻¹ • B := show Units.mk0 a ha • _ ⊆ _ ↔ _ from set_smul_subset_iff theorem subset_set_smul_iff₀ (ha : a ≠ 0) {A B : Set β} : A ⊆ a • B ↔ a⁻¹ • A ⊆ B := show _ ⊆ Units.mk0 a ha • _ ↔ _ from subset_set_smul_iff theorem smul_set_inter₀ (ha : a ≠ 0) : a • (s ∩ t) = a • s ∩ a • t := show Units.mk0 a ha • _ = _ from smul_set_inter theorem smul_set_sdiff₀ (ha : a ≠ 0) : a • (s \ t) = a • s \ a • t := image_diff (MulAction.injective₀ ha) _ _ open scoped symmDiff in theorem smul_set_symmDiff₀ (ha : a ≠ 0) : a • s ∆ t = (a • s) ∆ (a • t) := image_symmDiff (MulAction.injective₀ ha) _ _ theorem smul_set_univ₀ (ha : a ≠ 0) : a • (univ : Set β) = univ := image_univ_of_surjective <| MulAction.surjective₀ ha theorem smul_univ₀ {s : Set α} (hs : ¬s ⊆ 0) : s • (univ : Set β) = univ := let ⟨a, ha, ha₀⟩ := not_subset.1 hs eq_univ_of_forall fun b ↦ ⟨a, ha, a⁻¹ • b, trivial, smul_inv_smul₀ ha₀ _⟩ theorem smul_univ₀' {s : Set α} (hs : s.Nontrivial) : s • (univ : Set β) = univ := smul_univ₀ hs.not_subset_singleton @[simp] protected lemma inv_zero : (0 : Set α)⁻¹ = 0 := by ext; simp @[simp] lemma inv_smul_set_distrib₀ (a : α) (s : Set α) : (a • s)⁻¹ = op a⁻¹ • s⁻¹ := by obtain rfl | ha := eq_or_ne a 0 · obtain rfl | hs := s.eq_empty_or_nonempty <;> simp [*] · ext; simp [mem_smul_set_iff_inv_smul_mem₀, *] @[simp] lemma inv_op_smul_set_distrib₀ (a : α) (s : Set α) : (op a • s)⁻¹ = a⁻¹ • s⁻¹ := by obtain rfl | ha := eq_or_ne a 0 · obtain rfl | hs := s.eq_empty_or_nonempty <;> simp [*] · ext; simp [mem_smul_set_iff_inv_smul_mem₀, *] end GroupWithZero section Monoid variable [Monoid α] [AddGroup β] [DistribMulAction α β] (a : α) (s : Set α) (t : Set β) @[simp] theorem smul_set_neg : a • -t = -(a • t) := by simp_rw [← image_smul, ← image_neg, image_image, smul_neg] @[simp] protected theorem smul_neg : s • -t = -(s • t) := by simp_rw [← image_neg] exact image_image2_right_comm smul_neg end Monoid section Semiring variable [Semiring α] [AddCommMonoid β] [Module α β] theorem add_smul_subset (a b : α) (s : Set β) : (a + b) • s ⊆ a • s + b • s := by rintro _ ⟨x, hx, rfl⟩ simpa only [add_smul] using add_mem_add (smul_mem_smul_set hx) (smul_mem_smul_set hx) end Semiring section Ring variable [Ring α] [AddCommGroup β] [Module α β] (a : α) (s : Set α) (t : Set β) @[simp] theorem neg_smul_set : -a • t = -(a • t) := by simp_rw [← image_smul, ← image_neg, image_image, neg_smul] @[simp] protected theorem neg_smul : -s • t = -(s • t) := by simp_rw [← image_neg] exact image2_image_left_comm neg_smul end Ring end Set
Data\Set\Pointwise\Support.lean
/- Copyright (c) 2022 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import Mathlib.Algebra.Group.Support import Mathlib.Data.Set.Pointwise.SMul /-! # Support of a function composed with a scalar action We show that the support of `x ↦ f (c⁻¹ • x)` is equal to `c • support f`. -/ open Pointwise open Function Set section Group variable {α β γ : Type*} [Group α] [MulAction α β] theorem mulSupport_comp_inv_smul [One γ] (c : α) (f : β → γ) : (mulSupport fun x ↦ f (c⁻¹ • x)) = c • mulSupport f := by ext x simp only [mem_smul_set_iff_inv_smul_mem, mem_mulSupport] /- Note: to_additive also automatically translates `SMul` to `VAdd`, so we give the additive version manually. -/ theorem support_comp_inv_smul [Zero γ] (c : α) (f : β → γ) : (support fun x ↦ f (c⁻¹ • x)) = c • support f := by ext x simp only [mem_smul_set_iff_inv_smul_mem, mem_support] attribute [to_additive existing support_comp_inv_smul] mulSupport_comp_inv_smul end Group section GroupWithZero variable {α β γ : Type*} [GroupWithZero α] [MulAction α β] theorem mulSupport_comp_inv_smul₀ [One γ] {c : α} (hc : c ≠ 0) (f : β → γ) : (mulSupport fun x ↦ f (c⁻¹ • x)) = c • mulSupport f := by ext x simp only [mem_smul_set_iff_inv_smul_mem₀ hc, mem_mulSupport] /- Note: to_additive also automatically translates `SMul` to `VAdd`, so we give the additive version manually. -/ theorem support_comp_inv_smul₀ [Zero γ] {c : α} (hc : c ≠ 0) (f : β → γ) : (support fun x ↦ f (c⁻¹ • x)) = c • support f := by ext x simp only [mem_smul_set_iff_inv_smul_mem₀ hc, mem_support] attribute [to_additive existing support_comp_inv_smul₀] mulSupport_comp_inv_smul₀ end GroupWithZero
Data\SetLike\Basic.lean
/- Copyright (c) 2021 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import Mathlib.Data.Set.Basic import Mathlib.Tactic.Monotonicity.Attr import Mathlib.Tactic.SetLike /-! # Typeclass for types with a set-like extensionality property The `Membership` typeclass is used to let terms of a type have elements. Many instances of `Membership` have a set-like extensionality property: things are equal iff they have the same elements. The `SetLike` typeclass provides a unified interface to define a `Membership` that is extensional in this way. The main use of `SetLike` is for algebraic subobjects (such as `Submonoid` and `Submodule`), whose non-proof data consists only of a carrier set. In such a situation, the projection to the carrier set is injective. In general, a type `A` is `SetLike` with elements of type `B` if it has an injective map to `Set B`. This module provides standard boilerplate for every `SetLike`: a `coe_sort`, a `coe` to set, a `PartialOrder`, and various extensionality and simp lemmas. A typical subobject should be declared as: ``` structure MySubobject (X : Type*) [ObjectTypeclass X] := (carrier : Set X) (op_mem' : ∀ {x : X}, x ∈ carrier → sorry ∈ carrier) namespace MySubobject variable {X : Type*} [ObjectTypeclass X] {x : X} instance : SetLike (MySubobject X) X := ⟨MySubobject.carrier, fun p q h => by cases p; cases q; congr!⟩ @[simp] lemma mem_carrier {p : MySubobject X} : x ∈ p.carrier ↔ x ∈ (p : Set X) := Iff.rfl @[ext] theorem ext {p q : MySubobject X} (h : ∀ x, x ∈ p ↔ x ∈ q) : p = q := SetLike.ext h /-- Copy of a `MySubobject` with a new `carrier` equal to the old one. Useful to fix definitional equalities. See Note [range copy pattern]. -/ protected def copy (p : MySubobject X) (s : Set X) (hs : s = ↑p) : MySubobject X := { carrier := s op_mem' := hs.symm ▸ p.op_mem' } @[simp] lemma coe_copy (p : MySubobject X) (s : Set X) (hs : s = ↑p) : (p.copy s hs : Set X) = s := rfl lemma copy_eq (p : MySubobject X) (s : Set X) (hs : s = ↑p) : p.copy s hs = p := SetLike.coe_injective hs end MySubobject ``` An alternative to `SetLike` could have been an extensional `Membership` typeclass: ``` class ExtMembership (α : out_param <| Type u) (β : Type v) extends Membership α β := (ext_iff : ∀ {s t : β}, s = t ↔ ∀ (x : α), x ∈ s ↔ x ∈ t) ``` While this is equivalent, `SetLike` conveniently uses a carrier set projection directly. ## Tags subobjects -/ /-- A class to indicate that there is a canonical injection between `A` and `Set B`. This has the effect of giving terms of `A` elements of type `B` (through a `Membership` instance) and a compatible coercion to `Type*` as a subtype. Note: if `SetLike.coe` is a projection, implementers should create a simp lemma such as ``` @[simp] lemma mem_carrier {p : MySubobject X} : x ∈ p.carrier ↔ x ∈ (p : Set X) := Iff.rfl ``` to normalize terms. If you declare an unbundled subclass of `SetLike`, for example: ``` class MulMemClass (S : Type*) (M : Type*) [Mul M] [SetLike S M] where ... ``` Then you should *not* repeat the `outParam` declaration so `SetLike` will supply the value instead. This ensures your subclass will not have issues with synthesis of the `[Mul M]` parameter starting before the value of `M` is known. -/ @[notation_class * carrier Simps.findCoercionArgs] class SetLike (A : Type*) (B : outParam Type*) where /-- The coercion from a term of a `SetLike` to its corresponding `Set`. -/ protected coe : A → Set B /-- The coercion from a term of a `SetLike` to its corresponding `Set` is injective. -/ protected coe_injective' : Function.Injective coe attribute [coe] SetLike.coe namespace SetLike variable {A : Type*} {B : Type*} [i : SetLike A B] instance : CoeTC A (Set B) where coe := SetLike.coe instance (priority := 100) instMembership : Membership B A := ⟨fun x p => x ∈ (p : Set B)⟩ instance (priority := 100) : CoeSort A (Type _) := ⟨fun p => { x : B // x ∈ p }⟩ section Delab open Lean PrettyPrinter.Delaborator SubExpr /-- For terms that match the `CoeSort` instance's body, pretty print as `↥S` rather than as `{ x // x ∈ S }`. The discriminating feature is that membership uses the `SetLike.instMembership` instance. -/ @[delab app.Subtype] def delabSubtypeSetLike : Delab := whenPPOption getPPNotation do let #[_, .lam n _ body _] := (← getExpr).getAppArgs | failure guard <| body.isAppOf ``Membership.mem let #[_, _, inst, .bvar 0, _] := body.getAppArgs | failure guard <| inst.isAppOfArity ``instMembership 3 let S ← withAppArg <| withBindingBody n <| withNaryArg 4 delab `(↥$S) end Delab variable (p q : A) @[simp, norm_cast] theorem coe_sort_coe : ((p : Set B) : Type _) = p := rfl variable {p q} protected theorem «exists» {q : p → Prop} : (∃ x, q x) ↔ ∃ (x : B) (h : x ∈ p), q ⟨x, ‹_›⟩ := SetCoe.exists protected theorem «forall» {q : p → Prop} : (∀ x, q x) ↔ ∀ (x : B) (h : x ∈ p), q ⟨x, ‹_›⟩ := SetCoe.forall theorem coe_injective : Function.Injective (SetLike.coe : A → Set B) := fun _ _ h => SetLike.coe_injective' h @[simp, norm_cast] theorem coe_set_eq : (p : Set B) = q ↔ p = q := coe_injective.eq_iff @[norm_cast] lemma coe_ne_coe : (p : Set B) ≠ q ↔ p ≠ q := coe_injective.ne_iff theorem ext' (h : (p : Set B) = q) : p = q := coe_injective h theorem ext'_iff : p = q ↔ (p : Set B) = q := coe_set_eq.symm /-- Note: implementers of `SetLike` must copy this lemma in order to tag it with `@[ext]`. -/ theorem ext (h : ∀ x, x ∈ p ↔ x ∈ q) : p = q := coe_injective <| Set.ext h theorem ext_iff : p = q ↔ ∀ x, x ∈ p ↔ x ∈ q := coe_injective.eq_iff.symm.trans Set.ext_iff @[simp] theorem mem_coe {x : B} : x ∈ (p : Set B) ↔ x ∈ p := Iff.rfl @[simp, norm_cast] theorem coe_eq_coe {x y : p} : (x : B) = y ↔ x = y := Subtype.ext_iff_val.symm -- Porting note: this is not necessary anymore due to the way coercions work @[simp] theorem coe_mem (x : p) : (x : B) ∈ p := x.2 @[aesop 5% apply (rule_sets := [SetLike])] lemma mem_of_subset {s : Set B} (hp : s ⊆ p) {x : B} (hx : x ∈ s) : x ∈ p := hp hx -- Porting note: removed `@[simp]` because `simpNF` linter complained protected theorem eta (x : p) (hx : (x : B) ∈ p) : (⟨x, hx⟩ : p) = x := rfl instance (priority := 100) instPartialOrder : PartialOrder A := { PartialOrder.lift (SetLike.coe : A → Set B) coe_injective with le := fun H K => ∀ ⦃x⦄, x ∈ H → x ∈ K } theorem le_def {S T : A} : S ≤ T ↔ ∀ ⦃x : B⦄, x ∈ S → x ∈ T := Iff.rfl @[simp, norm_cast] theorem coe_subset_coe {S T : A} : (S : Set B) ⊆ T ↔ S ≤ T := Iff.rfl @[mono] theorem coe_mono : Monotone (SetLike.coe : A → Set B) := fun _ _ => coe_subset_coe.mpr @[simp, norm_cast] theorem coe_ssubset_coe {S T : A} : (S : Set B) ⊂ T ↔ S < T := Iff.rfl @[mono] theorem coe_strictMono : StrictMono (SetLike.coe : A → Set B) := fun _ _ => coe_ssubset_coe.mpr theorem not_le_iff_exists : ¬p ≤ q ↔ ∃ x ∈ p, x ∉ q := Set.not_subset theorem exists_of_lt : p < q → ∃ x ∈ q, x ∉ p := Set.exists_of_ssubset theorem lt_iff_le_and_exists : p < q ↔ p ≤ q ∧ ∃ x ∈ q, x ∉ p := by rw [lt_iff_le_not_le, not_le_iff_exists] end SetLike
Data\SetLike\Fintype.lean
/- Copyright (c) 2021 . All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import Mathlib.Data.SetLike.Basic import Mathlib.Data.Fintype.Powerset /-! # Set-like fintype This file contains a fintype instance for set-like objects such as subgroups. If `SetLike A B` and `Fintype B` then `Fintype A`. -/ namespace SetLike /-- TODO: It should be possible to obtain a computable version of this for most SetLike objects. If we add those instances, we should remove this one. -/ noncomputable instance (priority := 100) {A B : Type*} [SetLike A B] [Fintype B] : Fintype A := Fintype.ofInjective SetLike.coe SetLike.coe_injective -- See note [lower instance priority] instance (priority := 100) {A B : Type*} [SetLike A B] [Finite B] : Finite A := Finite.of_injective SetLike.coe SetLike.coe_injective end SetLike
Data\Setoid\Basic.lean
/- Copyright (c) 2019 Amelia Livingston. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Amelia Livingston, Bryan Gin-ge Chen -/ import Mathlib.Logic.Relation import Mathlib.Order.GaloisConnection /-! # Equivalence relations This file defines the complete lattice of equivalence relations on a type, results about the inductively defined equivalence closure of a binary relation, and the analogues of some isomorphism theorems for quotients of arbitrary types. ## Implementation notes The function `Rel` and lemmas ending in ' make it easier to talk about different equivalence relations on the same type. The complete lattice instance for equivalence relations could have been defined by lifting the Galois insertion of equivalence relations on α into binary relations on α, and then using `CompleteLattice.copy` to define a complete lattice instance with more appropriate definitional equalities (a similar example is `Filter.CompleteLattice` in `Order/Filter/Basic.lean`). This does not save space, however, and is less clear. Partitions are not defined as a separate structure here; users are encouraged to reason about them using the existing `Setoid` and its infrastructure. ## Tags setoid, equivalence, iseqv, relation, equivalence relation -/ attribute [refl] Setoid.refl attribute [symm] Setoid.symm attribute [trans] Setoid.trans variable {α : Type*} {β : Type*} /-- A version of `Setoid.r` that takes the equivalence relation as an explicit argument. -/ def Setoid.Rel (r : Setoid α) : α → α → Prop := @Setoid.r _ r instance Setoid.decidableRel (r : Setoid α) [h : DecidableRel r.r] : DecidableRel r.Rel := h /-- A version of `Quotient.eq'` compatible with `Setoid.Rel`, to make rewriting possible. -/ theorem Quotient.eq_rel {r : Setoid α} {x y} : (Quotient.mk' x : Quotient r) = Quotient.mk' y ↔ r.Rel x y := Quotient.eq namespace Setoid @[ext] theorem ext' {r s : Setoid α} (H : ∀ a b, r.Rel a b ↔ s.Rel a b) : r = s := ext H theorem ext_iff {r s : Setoid α} : r = s ↔ ∀ a b, r.Rel a b ↔ s.Rel a b := ⟨fun h _ _ => h ▸ Iff.rfl, ext'⟩ /-- Two equivalence relations are equal iff their underlying binary operations are equal. -/ theorem eq_iff_rel_eq {r₁ r₂ : Setoid α} : r₁ = r₂ ↔ r₁.Rel = r₂.Rel := ⟨fun h => h ▸ rfl, fun h => Setoid.ext' fun _ _ => h ▸ Iff.rfl⟩ /-- Defining `≤` for equivalence relations. -/ instance : LE (Setoid α) := ⟨fun r s => ∀ ⦃x y⦄, r.Rel x y → s.Rel x y⟩ theorem le_def {r s : Setoid α} : r ≤ s ↔ ∀ {x y}, r.Rel x y → s.Rel x y := Iff.rfl @[refl] theorem refl' (r : Setoid α) (x) : r.Rel x x := r.iseqv.refl x @[symm] theorem symm' (r : Setoid α) : ∀ {x y}, r.Rel x y → r.Rel y x := r.iseqv.symm @[trans] theorem trans' (r : Setoid α) : ∀ {x y z}, r.Rel x y → r.Rel y z → r.Rel x z := r.iseqv.trans theorem comm' (s : Setoid α) {x y} : s.Rel x y ↔ s.Rel y x := ⟨s.symm', s.symm'⟩ /-- The kernel of a function is an equivalence relation. -/ def ker (f : α → β) : Setoid α := ⟨(· = ·) on f, eq_equivalence.comap f⟩ /-- The kernel of the quotient map induced by an equivalence relation r equals r. -/ @[simp] theorem ker_mk_eq (r : Setoid α) : ker (@Quotient.mk'' _ r) = r := ext' fun _ _ => Quotient.eq theorem ker_apply_mk_out {f : α → β} (a : α) : f (haveI := Setoid.ker f; ⟦a⟧.out) = f a := @Quotient.mk_out _ (Setoid.ker f) a theorem ker_apply_mk_out' {f : α → β} (a : α) : f (Quotient.mk _ a : Quotient <| Setoid.ker f).out' = f a := @Quotient.mk_out' _ (Setoid.ker f) a theorem ker_def {f : α → β} {x y : α} : (ker f).Rel x y ↔ f x = f y := Iff.rfl /-- Given types `α`, `β`, the product of two equivalence relations `r` on `α` and `s` on `β`: `(x₁, x₂), (y₁, y₂) ∈ α × β` are related by `r.prod s` iff `x₁` is related to `y₁` by `r` and `x₂` is related to `y₂` by `s`. -/ protected def prod (r : Setoid α) (s : Setoid β) : Setoid (α × β) where r x y := r.Rel x.1 y.1 ∧ s.Rel x.2 y.2 iseqv := ⟨fun x => ⟨r.refl' x.1, s.refl' x.2⟩, fun h => ⟨r.symm' h.1, s.symm' h.2⟩, fun h₁ h₂ => ⟨r.trans' h₁.1 h₂.1, s.trans' h₁.2 h₂.2⟩⟩ /-- The infimum of two equivalence relations. -/ instance : Inf (Setoid α) := ⟨fun r s => ⟨fun x y => r.Rel x y ∧ s.Rel x y, ⟨fun x => ⟨r.refl' x, s.refl' x⟩, fun h => ⟨r.symm' h.1, s.symm' h.2⟩, fun h1 h2 => ⟨r.trans' h1.1 h2.1, s.trans' h1.2 h2.2⟩⟩⟩⟩ /-- The infimum of 2 equivalence relations r and s is the same relation as the infimum of the underlying binary operations. -/ theorem inf_def {r s : Setoid α} : (r ⊓ s).Rel = r.Rel ⊓ s.Rel := rfl theorem inf_iff_and {r s : Setoid α} {x y} : (r ⊓ s).Rel x y ↔ r.Rel x y ∧ s.Rel x y := Iff.rfl /-- The infimum of a set of equivalence relations. -/ instance : InfSet (Setoid α) := ⟨fun S => { r := fun x y => ∀ r ∈ S, r.Rel x y iseqv := ⟨fun x r _ => r.refl' x, fun h r hr => r.symm' <| h r hr, fun h1 h2 r hr => r.trans' (h1 r hr) <| h2 r hr⟩ }⟩ /-- The underlying binary operation of the infimum of a set of equivalence relations is the infimum of the set's image under the map to the underlying binary operation. -/ theorem sInf_def {s : Set (Setoid α)} : (sInf s).Rel = sInf (Rel '' s) := by ext simp only [sInf_image, iInf_apply, iInf_Prop_eq] rfl instance : PartialOrder (Setoid α) where le := (· ≤ ·) lt r s := r ≤ s ∧ ¬s ≤ r le_refl _ _ _ := id le_trans _ _ _ hr hs _ _ h := hs <| hr h lt_iff_le_not_le _ _ := Iff.rfl le_antisymm _ _ h1 h2 := Setoid.ext' fun _ _ => ⟨fun h => h1 h, fun h => h2 h⟩ /-- The complete lattice of equivalence relations on a type, with bottom element `=` and top element the trivial equivalence relation. -/ instance completeLattice : CompleteLattice (Setoid α) := { (completeLatticeOfInf (Setoid α)) fun _ => ⟨fun _ hr _ _ h => h _ hr, fun _ hr _ _ h _ hr' => hr hr' h⟩ with inf := Inf.inf inf_le_left := fun _ _ _ _ h => h.1 inf_le_right := fun _ _ _ _ h => h.2 le_inf := fun _ _ _ h1 h2 _ _ h => ⟨h1 h, h2 h⟩ top := ⟨fun _ _ => True, ⟨fun _ => trivial, fun h => h, fun h1 _ => h1⟩⟩ le_top := fun _ _ _ _ => trivial bot := ⟨(· = ·), ⟨fun _ => rfl, fun h => h.symm, fun h1 h2 => h1.trans h2⟩⟩ bot_le := fun r x _ h => h ▸ r.2.1 x } @[simp] theorem top_def : (⊤ : Setoid α).Rel = ⊤ := rfl @[simp] theorem bot_def : (⊥ : Setoid α).Rel = (· = ·) := rfl theorem eq_top_iff {s : Setoid α} : s = (⊤ : Setoid α) ↔ ∀ x y : α, s.Rel x y := by rw [_root_.eq_top_iff, Setoid.le_def, Setoid.top_def] simp only [Pi.top_apply, Prop.top_eq_true, forall_true_left] lemma sInf_equiv {S : Set (Setoid α)} {x y : α} : letI := sInf S x ≈ y ↔ ∀ s ∈ S, s.Rel x y := Iff.rfl lemma quotient_mk_sInf_eq {S : Set (Setoid α)} {x y : α} : Quotient.mk (sInf S) x = Quotient.mk (sInf S) y ↔ ∀ s ∈ S, s.Rel x y := by simp [sInf_equiv] /-- The map induced between quotients by a setoid inequality. -/ def map_of_le {s t : Setoid α} (h : s ≤ t) : Quotient s → Quotient t := Quotient.map' id h /-- The map from the quotient of the infimum of a set of setoids into the quotient by an element of this set. -/ def map_sInf {S : Set (Setoid α)} {s : Setoid α} (h : s ∈ S) : Quotient (sInf S) → Quotient s := Setoid.map_of_le fun _ _ a ↦ a s h /-- The inductively defined equivalence closure of a binary relation r is the infimum of the set of all equivalence relations containing r. -/ theorem eqvGen_eq (r : α → α → Prop) : EqvGen.Setoid r = sInf { s : Setoid α | ∀ ⦃x y⦄, r x y → s.Rel x y } := le_antisymm (fun _ _ H => EqvGen.rec (fun _ _ h _ hs => hs h) (refl' _) (fun _ _ _ => symm' _) (fun _ _ _ _ _ => trans' _) H) (sInf_le fun _ _ h => EqvGen.rel _ _ h) /-- The supremum of two equivalence relations r and s is the equivalence closure of the binary relation `x is related to y by r or s`. -/ theorem sup_eq_eqvGen (r s : Setoid α) : r ⊔ s = EqvGen.Setoid fun x y => r.Rel x y ∨ s.Rel x y := by rw [eqvGen_eq] apply congr_arg sInf simp only [le_def, or_imp, ← forall_and] /-- The supremum of 2 equivalence relations r and s is the equivalence closure of the supremum of the underlying binary operations. -/ theorem sup_def {r s : Setoid α} : r ⊔ s = EqvGen.Setoid (r.Rel ⊔ s.Rel) := by rw [sup_eq_eqvGen]; rfl /-- The supremum of a set S of equivalence relations is the equivalence closure of the binary relation `there exists r ∈ S relating x and y`. -/ theorem sSup_eq_eqvGen (S : Set (Setoid α)) : sSup S = EqvGen.Setoid fun x y => ∃ r : Setoid α, r ∈ S ∧ r.Rel x y := by rw [eqvGen_eq] apply congr_arg sInf simp only [upperBounds, le_def, and_imp, exists_imp] ext exact ⟨fun H x y r hr => H hr, fun H r hr x y => H r hr⟩ /-- The supremum of a set of equivalence relations is the equivalence closure of the supremum of the set's image under the map to the underlying binary operation. -/ theorem sSup_def {s : Set (Setoid α)} : sSup s = EqvGen.Setoid (sSup (Rel '' s)) := by rw [sSup_eq_eqvGen, sSup_image] congr with (x y) simp only [iSup_apply, iSup_Prop_eq, exists_prop] /-- The equivalence closure of an equivalence relation r is r. -/ @[simp] theorem eqvGen_of_setoid (r : Setoid α) : EqvGen.Setoid r.r = r := le_antisymm (by rw [eqvGen_eq]; exact sInf_le fun _ _ => id) EqvGen.rel /-- Equivalence closure is idempotent. -/ @[simp] theorem eqvGen_idem (r : α → α → Prop) : EqvGen.Setoid (EqvGen.Setoid r).Rel = EqvGen.Setoid r := eqvGen_of_setoid _ /-- The equivalence closure of a binary relation r is contained in any equivalence relation containing r. -/ theorem eqvGen_le {r : α → α → Prop} {s : Setoid α} (h : ∀ x y, r x y → s.Rel x y) : EqvGen.Setoid r ≤ s := by rw [eqvGen_eq]; exact sInf_le h /-- Equivalence closure of binary relations is monotone. -/ theorem eqvGen_mono {r s : α → α → Prop} (h : ∀ x y, r x y → s x y) : EqvGen.Setoid r ≤ EqvGen.Setoid s := eqvGen_le fun _ _ hr => EqvGen.rel _ _ <| h _ _ hr /-- There is a Galois insertion of equivalence relations on α into binary relations on α, with equivalence closure the lower adjoint. -/ def gi : @GaloisInsertion (α → α → Prop) (Setoid α) _ _ EqvGen.Setoid Rel where choice r _ := EqvGen.Setoid r gc _ s := ⟨fun H _ _ h => H <| EqvGen.rel _ _ h, fun H => eqvGen_of_setoid s ▸ eqvGen_mono H⟩ le_l_u x := (eqvGen_of_setoid x).symm ▸ le_refl x choice_eq _ _ := rfl open Function /-- A function from α to β is injective iff its kernel is the bottom element of the complete lattice of equivalence relations on α. -/ theorem injective_iff_ker_bot (f : α → β) : Injective f ↔ ker f = ⊥ := (@eq_bot_iff (Setoid α) _ _ (ker f)).symm /-- The elements related to x ∈ α by the kernel of f are those in the preimage of f(x) under f. -/ theorem ker_iff_mem_preimage {f : α → β} {x y} : (ker f).Rel x y ↔ x ∈ f ⁻¹' {f y} := Iff.rfl /-- Equivalence between functions `α → β` such that `r x y → f x = f y` and functions `quotient r → β`. -/ def liftEquiv (r : Setoid α) : { f : α → β // r ≤ ker f } ≃ (Quotient r → β) where toFun f := Quotient.lift (f : α → β) f.2 invFun f := ⟨f ∘ Quotient.mk'', fun x y h => by simp [ker_def, Quotient.sound' h]⟩ left_inv := fun ⟨f, hf⟩ => Subtype.eq <| funext fun x => rfl right_inv f := funext fun x => Quotient.inductionOn' x fun x => rfl /-- The uniqueness part of the universal property for quotients of an arbitrary type. -/ theorem lift_unique {r : Setoid α} {f : α → β} (H : r ≤ ker f) (g : Quotient r → β) (Hg : f = g ∘ Quotient.mk'') : Quotient.lift f H = g := by ext ⟨x⟩ erw [Quotient.lift_mk f H, Hg] rfl /-- Given a map f from α to β, the natural map from the quotient of α by the kernel of f is injective. -/ theorem ker_lift_injective (f : α → β) : Injective (@Quotient.lift _ _ (ker f) f fun _ _ h => h) := fun x y => Quotient.inductionOn₂' x y fun _ _ h => Quotient.sound' h /-- Given a map f from α to β, the kernel of f is the unique equivalence relation on α whose induced map from the quotient of α to β is injective. -/ theorem ker_eq_lift_of_injective {r : Setoid α} (f : α → β) (H : ∀ x y, r.Rel x y → f x = f y) (h : Injective (Quotient.lift f H)) : ker f = r := le_antisymm (fun x y hk => Quotient.exact <| h <| show Quotient.lift f H ⟦x⟧ = Quotient.lift f H ⟦y⟧ from hk) H variable (r : Setoid α) (f : α → β) /-- The first isomorphism theorem for sets: the quotient of α by the kernel of a function f bijects with f's image. -/ noncomputable def quotientKerEquivRange : Quotient (ker f) ≃ Set.range f := Equiv.ofBijective ((@Quotient.lift _ (Set.range f) (ker f) fun x => ⟨f x, Set.mem_range_self x⟩) fun _ _ h => Subtype.ext_val h) ⟨fun x y h => ker_lift_injective f <| by rcases x with ⟨⟩; rcases y with ⟨⟩; injections, fun ⟨w, z, hz⟩ => ⟨@Quotient.mk'' _ (ker f) z, Subtype.ext_iff_val.2 hz⟩⟩ /-- If `f` has a computable right-inverse, then the quotient by its kernel is equivalent to its domain. -/ @[simps] def quotientKerEquivOfRightInverse (g : β → α) (hf : Function.RightInverse g f) : Quotient (ker f) ≃ β where toFun a := (Quotient.liftOn' a f) fun _ _ => id invFun b := Quotient.mk'' (g b) left_inv a := Quotient.inductionOn' a fun a => Quotient.sound' <| hf (f a) right_inv := hf /-- The quotient of α by the kernel of a surjective function f bijects with f's codomain. If a specific right-inverse of `f` is known, `Setoid.quotientKerEquivOfRightInverse` can be definitionally more useful. -/ noncomputable def quotientKerEquivOfSurjective (hf : Surjective f) : Quotient (ker f) ≃ β := quotientKerEquivOfRightInverse _ (Function.surjInv hf) (rightInverse_surjInv hf) variable {r f} /-- Given a function `f : α → β` and equivalence relation `r` on `α`, the equivalence closure of the relation on `f`'s image defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by `r`.' -/ def map (r : Setoid α) (f : α → β) : Setoid β := EqvGen.Setoid fun x y => ∃ a b, f a = x ∧ f b = y ∧ r.Rel a b /-- Given a surjective function f whose kernel is contained in an equivalence relation r, the equivalence relation on f's codomain defined by x ≈ y ↔ the elements of f⁻¹(x) are related to the elements of f⁻¹(y) by r. -/ def mapOfSurjective (r) (f : α → β) (h : ker f ≤ r) (hf : Surjective f) : Setoid β := ⟨fun x y => ∃ a b, f a = x ∧ f b = y ∧ r.Rel a b, ⟨fun x => let ⟨y, hy⟩ := hf x ⟨y, y, hy, hy, r.refl' y⟩, fun ⟨x, y, hx, hy, h⟩ => ⟨y, x, hy, hx, r.symm' h⟩, fun ⟨x, y, hx, hy, h₁⟩ ⟨y', z, hy', hz, h₂⟩ => ⟨x, z, hx, hz, r.trans' h₁ <| r.trans' (h <| by rwa [← hy'] at hy) h₂⟩⟩⟩ /-- A special case of the equivalence closure of an equivalence relation r equalling r. -/ theorem mapOfSurjective_eq_map (h : ker f ≤ r) (hf : Surjective f) : map r f = mapOfSurjective r f h hf := by rw [← eqvGen_of_setoid (mapOfSurjective r f h hf)]; rfl /-- Given a function `f : α → β`, an equivalence relation `r` on `β` induces an equivalence relation on `α` defined by '`x ≈ y` iff `f(x)` is related to `f(y)` by `r`'. See note [reducible non-instances]. -/ abbrev comap (f : α → β) (r : Setoid β) : Setoid α := ⟨r.Rel on f, r.iseqv.comap _⟩ theorem comap_rel (f : α → β) (r : Setoid β) (x y : α) : (comap f r).Rel x y ↔ r.Rel (f x) (f y) := Iff.rfl /-- Given a map `f : N → M` and an equivalence relation `r` on `β`, the equivalence relation induced on `α` by `f` equals the kernel of `r`'s quotient map composed with `f`. -/ theorem comap_eq {f : α → β} {r : Setoid β} : comap f r = ker (@Quotient.mk'' _ r ∘ f) := ext fun x y => show _ ↔ ⟦_⟧ = ⟦_⟧ by rw [Quotient.eq]; rfl /-- The second isomorphism theorem for sets. -/ noncomputable def comapQuotientEquiv (f : α → β) (r : Setoid β) : Quotient (comap f r) ≃ Set.range (@Quotient.mk'' _ r ∘ f) := (Quotient.congrRight <| ext_iff.1 comap_eq).trans <| quotientKerEquivRange <| Quotient.mk'' ∘ f variable (r f) /-- The third isomorphism theorem for sets. -/ def quotientQuotientEquivQuotient (s : Setoid α) (h : r ≤ s) : Quotient (ker (Quot.mapRight h)) ≃ Quotient s where toFun x := (Quotient.liftOn' x fun w => (Quotient.liftOn' w (@Quotient.mk'' _ s)) fun x y H => Quotient.sound <| h H) fun x y => Quotient.inductionOn₂' x y fun w z H => show @Quot.mk _ _ _ = @Quot.mk _ _ _ from H invFun x := (Quotient.liftOn' x fun w => @Quotient.mk'' _ (ker <| Quot.mapRight h) <| @Quotient.mk'' _ r w) fun x y H => Quotient.sound' <| show @Quot.mk _ _ _ = @Quot.mk _ _ _ from Quotient.sound H left_inv x := Quotient.inductionOn' x fun y => Quotient.inductionOn' y fun w => by show ⟦_⟧ = _; rfl right_inv x := Quotient.inductionOn' x fun y => by show ⟦_⟧ = _; rfl variable {r f} open Quotient /-- Given an equivalence relation `r` on `α`, the order-preserving bijection between the set of equivalence relations containing `r` and the equivalence relations on the quotient of `α` by `r`. -/ def correspondence (r : Setoid α) : { s // r ≤ s } ≃o Setoid (Quotient r) where toFun s := ⟨Quotient.lift₂ s.1.1 fun _ _ _ _ h₁ h₂ ↦ Eq.propIntro (fun h ↦ s.1.trans' (s.1.trans' (s.1.symm' (s.2 h₁)) h) (s.2 h₂)) (fun h ↦ s.1.trans' (s.1.trans' (s.2 h₁) h) (s.1.symm' (s.2 h₂))), ⟨Quotient.ind s.1.2.1, @fun x y ↦ Quotient.inductionOn₂ x y fun _ _ ↦ s.1.2.2, @fun x y z ↦ Quotient.inductionOn₃ x y z fun _ _ _ ↦ s.1.2.3⟩⟩ invFun s := ⟨comap Quotient.mk' s, fun x y h => by rw [comap_rel, eq_rel.2 h]⟩ left_inv s := rfl right_inv s := ext fun x y ↦ Quotient.inductionOn₂ x y fun _ _ ↦ Iff.rfl map_rel_iff' := ⟨fun h x y hs ↦ @h ⟦x⟧ ⟦y⟧ hs, fun h x y ↦ Quotient.inductionOn₂ x y fun _ _ hs ↦ h hs⟩ /-- Given two equivalence relations with `r ≤ s`, a bijection between the sum of the quotients by `r` on each equivalence class by `s` and the quotient by `r`. -/ def sigmaQuotientEquivOfLe {r s : Setoid α} (hle : r ≤ s) : (Σ q : Quotient s, Quotient (r.comap (Subtype.val : Quotient.mk s ⁻¹' {q} → α))) ≃ Quotient r := .trans (.symm <| .sigmaCongrRight fun _ ↦ .subtypeQuotientEquivQuotientSubtype (s₁ := r) (s₂ := r.comap Subtype.val) _ (fun _ ↦ Iff.rfl) fun _ _ ↦ Iff.rfl) (.sigmaFiberEquiv fun a ↦ a.lift (Quotient.mk s) fun _ _ h ↦ Quotient.sound <| hle h) end Setoid @[simp] theorem Quotient.subsingleton_iff {s : Setoid α} : Subsingleton (Quotient s) ↔ s = ⊤ := by simp only [_root_.subsingleton_iff, eq_top_iff, Setoid.le_def, Setoid.top_def, Pi.top_apply, forall_const] refine (surjective_quotient_mk' _).forall.trans (forall_congr' fun a => ?_) refine (surjective_quotient_mk' _).forall.trans (forall_congr' fun b => ?_) simp_rw [Prop.top_eq_true, true_implies, Quotient.eq'] rfl theorem Quot.subsingleton_iff (r : α → α → Prop) : Subsingleton (Quot r) ↔ EqvGen r = ⊤ := by simp only [_root_.subsingleton_iff, _root_.eq_top_iff, Pi.le_def, Pi.top_apply, forall_const] refine (surjective_quot_mk _).forall.trans (forall_congr' fun a => ?_) refine (surjective_quot_mk _).forall.trans (forall_congr' fun b => ?_) rw [Quot.eq] simp only [forall_const, le_Prop_eq, Pi.top_apply, Prop.top_eq_true, true_implies]
Data\Setoid\Partition.lean
/- Copyright (c) 2019 Amelia Livingston. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Amelia Livingston, Bryan Gin-ge Chen, Patrick Massot, Wen Yang, Johan Commelin -/ import Mathlib.Data.Set.Finite import Mathlib.Order.Partition.Finpartition /-! # Equivalence relations: partitions This file comprises properties of equivalence relations viewed as partitions. There are two implementations of partitions here: * A collection `c : Set (Set α)` of sets is a partition of `α` if `∅ ∉ c` and each element `a : α` belongs to a unique set `b ∈ c`. This is expressed as `IsPartition c` * An indexed partition is a map `s : ι → α` whose image is a partition. This is expressed as `IndexedPartition s`. Of course both implementations are related to `Quotient` and `Setoid`. `Setoid.isPartition.partition` and `Finpartition.isPartition_parts` furnish a link between `Setoid.IsPartition` and `Finpartition`. ## TODO Could the design of `Finpartition` inform the one of `Setoid.IsPartition`? Maybe bundling it and changing it from `Set (Set α)` to `Set α` where `[Lattice α] [OrderBot α]` would make it more usable. ## Tags setoid, equivalence, iseqv, relation, equivalence relation, partition, equivalence class -/ namespace Setoid variable {α : Type*} /-- If x ∈ α is in 2 elements of a set of sets partitioning α, those 2 sets are equal. -/ theorem eq_of_mem_eqv_class {c : Set (Set α)} (H : ∀ a, ∃! b ∈ c, a ∈ b) {x b b'} (hc : b ∈ c) (hb : x ∈ b) (hc' : b' ∈ c) (hb' : x ∈ b') : b = b' := (H x).unique ⟨hc, hb⟩ ⟨hc', hb'⟩ /-- Makes an equivalence relation from a set of sets partitioning α. -/ def mkClasses (c : Set (Set α)) (H : ∀ a, ∃! b ∈ c, a ∈ b) : Setoid α where r x y := ∀ s ∈ c, x ∈ s → y ∈ s iseqv.refl := fun _ _ _ hx => hx iseqv.symm := fun {x _y} h s hs hy => by obtain ⟨t, ⟨ht, hx⟩, _⟩ := H x rwa [eq_of_mem_eqv_class H hs hy ht (h t ht hx)] iseqv.trans := fun {_x y z} h1 h2 s hs hx => h2 s hs (h1 s hs hx) /-- Makes the equivalence classes of an equivalence relation. -/ def classes (r : Setoid α) : Set (Set α) := { s | ∃ y, s = { x | r.Rel x y } } theorem mem_classes (r : Setoid α) (y) : { x | r.Rel x y } ∈ r.classes := ⟨y, rfl⟩ theorem classes_ker_subset_fiber_set {β : Type*} (f : α → β) : (Setoid.ker f).classes ⊆ Set.range fun y => { x | f x = y } := by rintro s ⟨x, rfl⟩ rw [Set.mem_range] exact ⟨f x, rfl⟩ theorem finite_classes_ker {α β : Type*} [Finite β] (f : α → β) : (Setoid.ker f).classes.Finite := (Set.finite_range _).subset <| classes_ker_subset_fiber_set f theorem card_classes_ker_le {α β : Type*} [Fintype β] (f : α → β) [Fintype (Setoid.ker f).classes] : Fintype.card (Setoid.ker f).classes ≤ Fintype.card β := by classical exact le_trans (Set.card_le_card (classes_ker_subset_fiber_set f)) (Fintype.card_range_le _) /-- Two equivalence relations are equal iff all their equivalence classes are equal. -/ theorem eq_iff_classes_eq {r₁ r₂ : Setoid α} : r₁ = r₂ ↔ ∀ x, { y | r₁.Rel x y } = { y | r₂.Rel x y } := ⟨fun h _x => h ▸ rfl, fun h => ext' fun x => Set.ext_iff.1 <| h x⟩ theorem rel_iff_exists_classes (r : Setoid α) {x y} : r.Rel x y ↔ ∃ c ∈ r.classes, x ∈ c ∧ y ∈ c := ⟨fun h => ⟨_, r.mem_classes y, h, r.refl' y⟩, fun ⟨c, ⟨z, hz⟩, hx, hy⟩ => by subst c exact r.trans' hx (r.symm' hy)⟩ /-- Two equivalence relations are equal iff their equivalence classes are equal. -/ theorem classes_inj {r₁ r₂ : Setoid α} : r₁ = r₂ ↔ r₁.classes = r₂.classes := ⟨fun h => h ▸ rfl, fun h => ext' fun a b => by simp only [rel_iff_exists_classes, exists_prop, h]⟩ /-- The empty set is not an equivalence class. -/ theorem empty_not_mem_classes {r : Setoid α} : ∅ ∉ r.classes := fun ⟨y, hy⟩ => Set.not_mem_empty y <| hy.symm ▸ r.refl' y /-- Equivalence classes partition the type. -/ theorem classes_eqv_classes {r : Setoid α} (a) : ∃! b ∈ r.classes, a ∈ b := ExistsUnique.intro { x | r.Rel x a } ⟨r.mem_classes a, r.refl' _⟩ <| by rintro y ⟨⟨_, rfl⟩, ha⟩ ext x exact ⟨fun hx => r.trans' hx (r.symm' ha), fun hx => r.trans' hx ha⟩ /-- If x ∈ α is in 2 equivalence classes, the equivalence classes are equal. -/ theorem eq_of_mem_classes {r : Setoid α} {x b} (hc : b ∈ r.classes) (hb : x ∈ b) {b'} (hc' : b' ∈ r.classes) (hb' : x ∈ b') : b = b' := eq_of_mem_eqv_class classes_eqv_classes hc hb hc' hb' /-- The elements of a set of sets partitioning α are the equivalence classes of the equivalence relation defined by the set of sets. -/ theorem eq_eqv_class_of_mem {c : Set (Set α)} (H : ∀ a, ∃! b ∈ c, a ∈ b) {s y} (hs : s ∈ c) (hy : y ∈ s) : s = { x | (mkClasses c H).Rel x y } := by ext x constructor · intro hx _s' hs' hx' rwa [eq_of_mem_eqv_class H hs' hx' hs hx] · intro hx obtain ⟨b', ⟨hc, hb'⟩, _⟩ := H x rwa [eq_of_mem_eqv_class H hs hy hc (hx b' hc hb')] /-- The equivalence classes of the equivalence relation defined by a set of sets partitioning α are elements of the set of sets. -/ theorem eqv_class_mem {c : Set (Set α)} (H : ∀ a, ∃! b ∈ c, a ∈ b) {y} : { x | (mkClasses c H).Rel x y } ∈ c := (H y).elim fun _ hc _ => eq_eqv_class_of_mem H hc.1 hc.2 ▸ hc.1 theorem eqv_class_mem' {c : Set (Set α)} (H : ∀ a, ∃! b ∈ c, a ∈ b) {x} : { y : α | (mkClasses c H).Rel x y } ∈ c := by convert @Setoid.eqv_class_mem _ _ H x using 3 rw [Setoid.comm'] /-- Distinct elements of a set of sets partitioning α are disjoint. -/ theorem eqv_classes_disjoint {c : Set (Set α)} (H : ∀ a, ∃! b ∈ c, a ∈ b) : c.PairwiseDisjoint id := fun _b₁ h₁ _b₂ h₂ h => Set.disjoint_left.2 fun x hx1 hx2 => (H x).elim fun _b _hc _hx => h <| eq_of_mem_eqv_class H h₁ hx1 h₂ hx2 /-- A set of disjoint sets covering α partition α (classical). -/ theorem eqv_classes_of_disjoint_union {c : Set (Set α)} (hu : Set.sUnion c = @Set.univ α) (H : c.PairwiseDisjoint id) (a) : ∃! b ∈ c, a ∈ b := let ⟨b, hc, ha⟩ := Set.mem_sUnion.1 <| show a ∈ _ by rw [hu]; exact Set.mem_univ a ExistsUnique.intro b ⟨hc, ha⟩ fun b' hc' => H.elim_set hc'.1 hc _ hc'.2 ha /-- Makes an equivalence relation from a set of disjoints sets covering α. -/ def setoidOfDisjointUnion {c : Set (Set α)} (hu : Set.sUnion c = @Set.univ α) (H : c.PairwiseDisjoint id) : Setoid α := Setoid.mkClasses c <| eqv_classes_of_disjoint_union hu H /-- The equivalence relation made from the equivalence classes of an equivalence relation r equals r. -/ theorem mkClasses_classes (r : Setoid α) : mkClasses r.classes classes_eqv_classes = r := ext' fun x _y => ⟨fun h => r.symm' (h { z | r.Rel z x } (r.mem_classes x) <| r.refl' x), fun h _b hb hx => eq_of_mem_classes (r.mem_classes x) (r.refl' x) hb hx ▸ r.symm' h⟩ @[simp] theorem sUnion_classes (r : Setoid α) : ⋃₀ r.classes = Set.univ := Set.eq_univ_of_forall fun x => Set.mem_sUnion.2 ⟨{ y | r.Rel y x }, ⟨x, rfl⟩, Setoid.refl _⟩ /-- The equivalence between the quotient by an equivalence relation and its type of equivalence classes. -/ noncomputable def quotientEquivClasses (r : Setoid α) : Quotient r ≃ Setoid.classes r := by let f (a : α) : Setoid.classes r := ⟨{ x | Setoid.r x a }, Setoid.mem_classes r a⟩ have f_respects_relation (a b : α) (a_rel_b : Setoid.r a b) : f a = f b := by rw [Subtype.mk.injEq] exact Setoid.eq_of_mem_classes (Setoid.mem_classes r a) (Setoid.symm a_rel_b) (Setoid.mem_classes r b) (Setoid.refl b) apply Equiv.ofBijective (Quot.lift f f_respects_relation) constructor · intro (q_a : Quotient r) (q_b : Quotient r) h_eq induction' q_a using Quotient.ind with a induction' q_b using Quotient.ind with b simp only [Subtype.ext_iff, Quotient.lift_mk, Subtype.ext_iff] at h_eq apply Quotient.sound show a ∈ { x | Setoid.r x b } rw [← h_eq] exact Setoid.refl a · rw [Quot.surjective_lift] intro ⟨c, a, hc⟩ exact ⟨a, Subtype.ext hc.symm⟩ @[simp] lemma quotientEquivClasses_mk_eq (r : Setoid α) (a : α) : (quotientEquivClasses r (Quotient.mk r a) : Set α) = { x | r.Rel x a } := (@Subtype.ext_iff_val _ _ _ ⟨{ x | r.Rel x a }, Setoid.mem_classes r a⟩).mp rfl section Partition /-- A collection `c : Set (Set α)` of sets is a partition of `α` into pairwise disjoint sets if `∅ ∉ c` and each element `a : α` belongs to a unique set `b ∈ c`. -/ def IsPartition (c : Set (Set α)) := ∅ ∉ c ∧ ∀ a, ∃! b ∈ c, a ∈ b /-- A partition of `α` does not contain the empty set. -/ theorem nonempty_of_mem_partition {c : Set (Set α)} (hc : IsPartition c) {s} (h : s ∈ c) : s.Nonempty := Set.nonempty_iff_ne_empty.2 fun hs0 => hc.1 <| hs0 ▸ h theorem isPartition_classes (r : Setoid α) : IsPartition r.classes := ⟨empty_not_mem_classes, classes_eqv_classes⟩ theorem IsPartition.pairwiseDisjoint {c : Set (Set α)} (hc : IsPartition c) : c.PairwiseDisjoint id := eqv_classes_disjoint hc.2 lemma _root_.Set.PairwiseDisjoint.isPartition_of_exists_of_ne_empty {α : Type*} {s : Set (Set α)} (h₁ : s.PairwiseDisjoint id) (h₂ : ∀ a : α, ∃ x ∈ s, a ∈ x) (h₃ : ∅ ∉ s) : Setoid.IsPartition s := by refine ⟨h₃, fun a ↦ exists_unique_of_exists_of_unique (h₂ a) ?_⟩ intro b₁ b₂ hb₁ hb₂ apply h₁.elim hb₁.1 hb₂.1 simp only [Set.not_disjoint_iff] exact ⟨a, hb₁.2, hb₂.2⟩ theorem IsPartition.sUnion_eq_univ {c : Set (Set α)} (hc : IsPartition c) : ⋃₀ c = Set.univ := Set.eq_univ_of_forall fun x => Set.mem_sUnion.2 <| let ⟨t, ht⟩ := hc.2 x ⟨t, by simp only [exists_unique_iff_exists] at ht tauto⟩ /-- All elements of a partition of α are the equivalence class of some y ∈ α. -/ theorem exists_of_mem_partition {c : Set (Set α)} (hc : IsPartition c) {s} (hs : s ∈ c) : ∃ y, s = { x | (mkClasses c hc.2).Rel x y } := let ⟨y, hy⟩ := nonempty_of_mem_partition hc hs ⟨y, eq_eqv_class_of_mem hc.2 hs hy⟩ /-- The equivalence classes of the equivalence relation defined by a partition of α equal the original partition. -/ theorem classes_mkClasses (c : Set (Set α)) (hc : IsPartition c) : (mkClasses c hc.2).classes = c := by ext s constructor · rintro ⟨y, rfl⟩ obtain ⟨b, ⟨hb, hy⟩, _⟩ := hc.2 y rwa [← eq_eqv_class_of_mem _ hb hy] · exact exists_of_mem_partition hc /-- Defining `≤` on partitions as the `≤` defined on their induced equivalence relations. -/ instance Partition.le : LE (Subtype (@IsPartition α)) := ⟨fun x y => mkClasses x.1 x.2.2 ≤ mkClasses y.1 y.2.2⟩ /-- Defining a partial order on partitions as the partial order on their induced equivalence relations. -/ instance Partition.partialOrder : PartialOrder (Subtype (@IsPartition α)) where le := (· ≤ ·) lt x y := x ≤ y ∧ ¬y ≤ x le_refl _ := @le_refl (Setoid α) _ _ le_trans _ _ _ := @le_trans (Setoid α) _ _ _ _ lt_iff_le_not_le _ _ := Iff.rfl le_antisymm x y hx hy := by let h := @le_antisymm (Setoid α) _ _ _ hx hy rw [Subtype.ext_iff_val, ← classes_mkClasses x.1 x.2, ← classes_mkClasses y.1 y.2, h] variable (α) /-- The order-preserving bijection between equivalence relations on a type `α`, and partitions of `α` into subsets. -/ protected def Partition.orderIso : Setoid α ≃o { C : Set (Set α) // IsPartition C } where toFun r := ⟨r.classes, empty_not_mem_classes, classes_eqv_classes⟩ invFun C := mkClasses C.1 C.2.2 left_inv := mkClasses_classes right_inv C := by rw [Subtype.ext_iff_val, ← classes_mkClasses C.1 C.2] map_rel_iff' {r s} := by conv_rhs => rw [← mkClasses_classes r, ← mkClasses_classes s] rfl variable {α} /-- A complete lattice instance for partitions; there is more infrastructure for the equivalent complete lattice on equivalence relations. -/ instance Partition.completeLattice : CompleteLattice (Subtype (@IsPartition α)) := GaloisInsertion.liftCompleteLattice <| @OrderIso.toGaloisInsertion _ (Subtype (@IsPartition α)) _ (PartialOrder.toPreorder) <| Partition.orderIso α end Partition /-- A finite setoid partition furnishes a finpartition -/ @[simps] def IsPartition.finpartition {c : Finset (Set α)} (hc : Setoid.IsPartition (c : Set (Set α))) : Finpartition (Set.univ : Set α) where parts := c supIndep := Finset.supIndep_iff_pairwiseDisjoint.mpr <| eqv_classes_disjoint hc.2 sup_parts := c.sup_id_set_eq_sUnion.trans hc.sUnion_eq_univ not_bot_mem := hc.left end Setoid /-- A finpartition gives rise to a setoid partition -/ theorem Finpartition.isPartition_parts {α} (f : Finpartition (Set.univ : Set α)) : Setoid.IsPartition (f.parts : Set (Set α)) := ⟨f.not_bot_mem, Setoid.eqv_classes_of_disjoint_union (f.parts.sup_id_set_eq_sUnion.symm.trans f.sup_parts) f.supIndep.pairwiseDisjoint⟩ /-- Constructive information associated with a partition of a type `α` indexed by another type `ι`, `s : ι → Set α`. `IndexedPartition.index` sends an element to its index, while `IndexedPartition.some` sends an index to an element of the corresponding set. This type is primarily useful for definitional control of `s` - if this is not needed, then `Setoid.ker index` by itself may be sufficient. -/ structure IndexedPartition {ι α : Type*} (s : ι → Set α) where /-- two indexes are equal if they are equal in membership -/ eq_of_mem : ∀ {x i j}, x ∈ s i → x ∈ s j → i = j /-- sends an index to an element of the corresponding set-/ some : ι → α /-- membership invariance for `some`-/ some_mem : ∀ i, some i ∈ s i /-- index for type `α`-/ index : α → ι /-- membership invariance for `index`-/ mem_index : ∀ x, x ∈ s (index x) /-- The non-constructive constructor for `IndexedPartition`. -/ noncomputable def IndexedPartition.mk' {ι α : Type*} (s : ι → Set α) (dis : Pairwise fun i j => Disjoint (s i) (s j)) (nonempty : ∀ i, (s i).Nonempty) (ex : ∀ x, ∃ i, x ∈ s i) : IndexedPartition s where eq_of_mem {_x _i _j} hxi hxj := by_contradiction fun h => (dis h).le_bot ⟨hxi, hxj⟩ some i := (nonempty i).some some_mem i := (nonempty i).choose_spec index x := (ex x).choose mem_index x := (ex x).choose_spec namespace IndexedPartition open Set variable {ι α : Type*} {s : ι → Set α} (hs : IndexedPartition s) /-- On a unique index set there is the obvious trivial partition -/ instance [Unique ι] [Inhabited α] : Inhabited (IndexedPartition fun _i : ι => (Set.univ : Set α)) := ⟨{ eq_of_mem := fun {_x _i _j} _hi _hj => Subsingleton.elim _ _ some := default some_mem := Set.mem_univ index := default mem_index := Set.mem_univ }⟩ -- Porting note: `simpNF` complains about `mem_index` attribute [simp] some_mem --mem_index theorem exists_mem (x : α) : ∃ i, x ∈ s i := ⟨hs.index x, hs.mem_index x⟩ theorem iUnion : ⋃ i, s i = univ := by ext x simp [hs.exists_mem x] theorem disjoint : Pairwise fun i j => Disjoint (s i) (s j) := fun {_i _j} h => disjoint_left.mpr fun {_x} hxi hxj => h (hs.eq_of_mem hxi hxj) theorem mem_iff_index_eq {x i} : x ∈ s i ↔ hs.index x = i := ⟨fun hxi => (hs.eq_of_mem hxi (hs.mem_index x)).symm, fun h => h ▸ hs.mem_index _⟩ theorem eq (i) : s i = { x | hs.index x = i } := Set.ext fun _ => hs.mem_iff_index_eq /-- The equivalence relation associated to an indexed partition. Two elements are equivalent if they belong to the same set of the partition. -/ protected abbrev setoid (hs : IndexedPartition s) : Setoid α := Setoid.ker hs.index @[simp] theorem index_some (i : ι) : hs.index (hs.some i) = i := (mem_iff_index_eq _).1 <| hs.some_mem i theorem some_index (x : α) : hs.setoid.Rel (hs.some (hs.index x)) x := hs.index_some (hs.index x) /-- The quotient associated to an indexed partition. -/ protected def Quotient := Quotient hs.setoid /-- The projection onto the quotient associated to an indexed partition. -/ def proj : α → hs.Quotient := Quotient.mk'' instance [Inhabited α] : Inhabited hs.Quotient := ⟨hs.proj default⟩ theorem proj_eq_iff {x y : α} : hs.proj x = hs.proj y ↔ hs.index x = hs.index y := Quotient.eq_rel @[simp] theorem proj_some_index (x : α) : hs.proj (hs.some (hs.index x)) = hs.proj x := Quotient.eq''.2 (hs.some_index x) /-- The obvious equivalence between the quotient associated to an indexed partition and the indexing type. -/ def equivQuotient : ι ≃ hs.Quotient := (Setoid.quotientKerEquivOfRightInverse hs.index hs.some <| hs.index_some).symm @[simp] theorem equivQuotient_index_apply (x : α) : hs.equivQuotient (hs.index x) = hs.proj x := hs.proj_eq_iff.mpr (some_index hs x) @[simp] theorem equivQuotient_symm_proj_apply (x : α) : hs.equivQuotient.symm (hs.proj x) = hs.index x := rfl theorem equivQuotient_index : hs.equivQuotient ∘ hs.index = hs.proj := funext hs.equivQuotient_index_apply /-- A map choosing a representative for each element of the quotient associated to an indexed partition. This is a computable version of `Quotient.out'` using `IndexedPartition.some`. -/ def out : hs.Quotient ↪ α := hs.equivQuotient.symm.toEmbedding.trans ⟨hs.some, Function.LeftInverse.injective hs.index_some⟩ /-- This lemma is analogous to `Quotient.mk_out'`. -/ @[simp] theorem out_proj (x : α) : hs.out (hs.proj x) = hs.some (hs.index x) := rfl /-- The indices of `Quotient.out'` and `IndexedPartition.out` are equal. -/ theorem index_out' (x : hs.Quotient) : hs.index x.out' = hs.index (hs.out x) := Quotient.inductionOn' x fun x => (Setoid.ker_apply_mk_out' x).trans (hs.index_some _).symm /-- This lemma is analogous to `Quotient.out_eq'`. -/ @[simp] theorem proj_out (x : hs.Quotient) : hs.proj (hs.out x) = x := Quotient.inductionOn' x fun x => Quotient.sound' <| hs.some_index x theorem class_of {x : α} : setOf (hs.setoid.Rel x) = s (hs.index x) := Set.ext fun _y => eq_comm.trans hs.mem_iff_index_eq.symm theorem proj_fiber (x : hs.Quotient) : hs.proj ⁻¹' {x} = s (hs.equivQuotient.symm x) := Quotient.inductionOn' x fun x => by ext y simp only [Set.mem_preimage, Set.mem_singleton_iff, hs.mem_iff_index_eq] exact Quotient.eq'' /-- Combine functions with disjoint domains into a new function. You can use the regular expression `def.*piecewise` to search for other ways to define piecewise functions in mathlib4. -/ def piecewise {β : Type*} (f : ι → α → β) : α → β := fun x => f (hs.index x) x lemma piecewise_apply {β : Type*} {f : ι → α → β} (x : α) : hs.piecewise f x = f (hs.index x) x := rfl open Function /-- A family of injective functions with pairwise disjoint domains and pairwise disjoint ranges can be glued together to form an injective function. -/ theorem piecewise_inj {β : Type*} {f : ι → α → β} (h_injOn : ∀ i, InjOn (f i) (s i)) (h_disjoint : PairwiseDisjoint (univ : Set ι) fun i => (f i) '' (s i)) : Injective (piecewise hs f) := by intro x y h suffices hs.index x = hs.index y by apply h_injOn (hs.index x) (hs.mem_index x) (this ▸ hs.mem_index y) simpa only [piecewise_apply, this] using h apply h_disjoint.elim trivial trivial contrapose! h exact h.ne_of_mem (mem_image_of_mem _ (hs.mem_index x)) (mem_image_of_mem _ (hs.mem_index y)) /-- A family of bijective functions with pairwise disjoint domains and pairwise disjoint ranges can be glued together to form a bijective function. -/ theorem piecewise_bij {β : Type*} {f : ι → α → β} {t : ι → Set β} (ht : IndexedPartition t) (hf : ∀ i, BijOn (f i) (s i) (t i)) : Bijective (piecewise hs f) := by set g := piecewise hs f with hg have hg_bij : ∀ i, BijOn g (s i) (t i) := by intro i refine BijOn.congr (hf i) ?_ intro x hx rw [hg, piecewise_apply, hs.mem_iff_index_eq.mp hx] have hg_inj : InjOn g (⋃ i, s i) := by refine injOn_of_injective ?_ refine piecewise_inj hs (fun i ↦ BijOn.injOn (hf i)) ?h_disjoint simp only [fun i ↦ BijOn.image_eq (hf i)] rintro i - j - hij exact ht.disjoint hij rw [bijective_iff_bijOn_univ, ← hs.iUnion, ← ht.iUnion] exact bijOn_iUnion hg_bij hg_inj end IndexedPartition
Data\Sigma\Basic.lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import Mathlib.Logic.Function.Defs import Mathlib.Logic.Function.Basic /-! # Sigma types This file proves basic results about sigma types. A sigma type is a dependent pair type. Like `α × β` but where the type of the second component depends on the first component. More precisely, given `β : ι → Type*`, `Sigma β` is made of stuff which is of type `β i` for some `i : ι`, so the sigma type is a disjoint union of types. For example, the sum type `X ⊕ Y` can be emulated using a sigma type, by taking `ι` with exactly two elements (see `Equiv.sumEquivSigmaBool`). `Σ x, A x` is notation for `Sigma A` (note that this is `\Sigma`, not the sum operator `∑`). `Σ x y z ..., A x y z ...` is notation for `Σ x, Σ y, Σ z, ..., A x y z ...`. Here we have `α : Type*`, `β : α → Type*`, `γ : Π a : α, β a → Type*`, ..., `A : Π (a : α) (b : β a) (c : γ a b) ..., Type*` with `x : α` `y : β x`, `z : γ x y`, ... ## Notes The definition of `Sigma` takes values in `Type*`. This effectively forbids `Prop`- valued sigma types. To that effect, we have `PSigma`, which takes value in `Sort*` and carries a more complicated universe signature as a consequence. -/ open Function section Sigma variable {α α₁ α₂ : Type*} {β : α → Type*} {β₁ : α₁ → Type*} {β₂ : α₂ → Type*} namespace Sigma instance instInhabitedSigma [Inhabited α] [Inhabited (β default)] : Inhabited (Sigma β) := ⟨⟨default, default⟩⟩ instance instDecidableEqSigma [h₁ : DecidableEq α] [h₂ : ∀ a, DecidableEq (β a)] : DecidableEq (Sigma β) | ⟨a₁, b₁⟩, ⟨a₂, b₂⟩ => match a₁, b₁, a₂, b₂, h₁ a₁ a₂ with | _, b₁, _, b₂, isTrue (Eq.refl _) => match b₁, b₂, h₂ _ b₁ b₂ with | _, _, isTrue (Eq.refl _) => isTrue rfl | _, _, isFalse n => isFalse fun h ↦ Sigma.noConfusion h fun _ e₂ ↦ n <| eq_of_heq e₂ | _, _, _, _, isFalse n => isFalse fun h ↦ Sigma.noConfusion h fun e₁ _ ↦ n e₁ -- sometimes the built-in injectivity support does not work @[simp] -- @[nolint simpNF] theorem mk.inj_iff {a₁ a₂ : α} {b₁ : β a₁} {b₂ : β a₂} : Sigma.mk a₁ b₁ = ⟨a₂, b₂⟩ ↔ a₁ = a₂ ∧ HEq b₁ b₂ := ⟨fun h ↦ by cases h; simp, fun ⟨h₁, h₂⟩ ↦ by subst h₁; rw [eq_of_heq h₂]⟩ @[simp] theorem eta : ∀ x : Σa, β a, Sigma.mk x.1 x.2 = x | ⟨_, _⟩ => rfl /-- A version of `Iff.mp Sigma.ext_iff` for functions from a nonempty type to a sigma type. -/ theorem _root_.Function.eq_of_sigmaMk_comp {γ : Type*} [Nonempty γ] {a b : α} {f : γ → β a} {g : γ → β b} (h : Sigma.mk a ∘ f = Sigma.mk b ∘ g) : a = b ∧ HEq f g := by rcases ‹Nonempty γ› with ⟨i⟩ obtain rfl : a = b := congr_arg Sigma.fst (congr_fun h i) simpa [funext_iff] using h /-- A specialized ext lemma for equality of sigma types over an indexed subtype. -/ @[ext] theorem subtype_ext {β : Type*} {p : α → β → Prop} : ∀ {x₀ x₁ : Σa, Subtype (p a)}, x₀.fst = x₁.fst → (x₀.snd : β) = x₁.snd → x₀ = x₁ | ⟨_, _, _⟩, ⟨_, _, _⟩, rfl, rfl => rfl @[simp] theorem «forall» {p : (Σa, β a) → Prop} : (∀ x, p x) ↔ ∀ a b, p ⟨a, b⟩ := ⟨fun h a b ↦ h ⟨a, b⟩, fun h ⟨a, b⟩ ↦ h a b⟩ @[simp] theorem «exists» {p : (Σa, β a) → Prop} : (∃ x, p x) ↔ ∃ a b, p ⟨a, b⟩ := ⟨fun ⟨⟨a, b⟩, h⟩ ↦ ⟨a, b, h⟩, fun ⟨a, b, h⟩ ↦ ⟨⟨a, b⟩, h⟩⟩ lemma exists' {p : ∀ a, β a → Prop} : (∃ a b, p a b) ↔ ∃ x : Σ a, β a, p x.1 x.2 := (Sigma.exists (p := fun x ↦ p x.1 x.2)).symm lemma forall' {p : ∀ a, β a → Prop} : (∀ a b, p a b) ↔ ∀ x : Σ a, β a, p x.1 x.2 := (Sigma.forall (p := fun x ↦ p x.1 x.2)).symm theorem _root_.sigma_mk_injective {i : α} : Injective (@Sigma.mk α β i) | _, _, rfl => rfl theorem fst_surjective [h : ∀ a, Nonempty (β a)] : Surjective (fst : (Σ a, β a) → α) := fun a ↦ let ⟨b⟩ := h a; ⟨⟨a, b⟩, rfl⟩ theorem fst_surjective_iff : Surjective (fst : (Σ a, β a) → α) ↔ ∀ a, Nonempty (β a) := ⟨fun h a ↦ let ⟨x, hx⟩ := h a; hx ▸ ⟨x.2⟩, @fst_surjective _ _⟩ theorem fst_injective [h : ∀ a, Subsingleton (β a)] : Injective (fst : (Σ a, β a) → α) := by rintro ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ (rfl : a₁ = a₂) exact congr_arg (mk a₁) <| Subsingleton.elim _ _ theorem fst_injective_iff : Injective (fst : (Σ a, β a) → α) ↔ ∀ a, Subsingleton (β a) := ⟨fun h _ ↦ ⟨fun _ _ ↦ sigma_mk_injective <| h rfl⟩, @fst_injective _ _⟩ /-- Map the left and right components of a sigma -/ def map (f₁ : α₁ → α₂) (f₂ : ∀ a, β₁ a → β₂ (f₁ a)) (x : Sigma β₁) : Sigma β₂ := ⟨f₁ x.1, f₂ x.1 x.2⟩ lemma map_mk (f₁ : α₁ → α₂) (f₂ : ∀ a, β₁ a → β₂ (f₁ a)) (x : α₁) (y : β₁ x) : map f₁ f₂ ⟨x, y⟩ = ⟨f₁ x, f₂ x y⟩ := rfl end Sigma theorem Function.Injective.sigma_map {f₁ : α₁ → α₂} {f₂ : ∀ a, β₁ a → β₂ (f₁ a)} (h₁ : Injective f₁) (h₂ : ∀ a, Injective (f₂ a)) : Injective (Sigma.map f₁ f₂) | ⟨i, x⟩, ⟨j, y⟩, h => by obtain rfl : i = j := h₁ (Sigma.mk.inj_iff.mp h).1 obtain rfl : x = y := h₂ i (sigma_mk_injective h) rfl theorem Function.Injective.of_sigma_map {f₁ : α₁ → α₂} {f₂ : ∀ a, β₁ a → β₂ (f₁ a)} (h : Injective (Sigma.map f₁ f₂)) (a : α₁) : Injective (f₂ a) := fun x y hxy ↦ sigma_mk_injective <| @h ⟨a, x⟩ ⟨a, y⟩ (Sigma.ext rfl (heq_of_eq hxy)) theorem Function.Injective.sigma_map_iff {f₁ : α₁ → α₂} {f₂ : ∀ a, β₁ a → β₂ (f₁ a)} (h₁ : Injective f₁) : Injective (Sigma.map f₁ f₂) ↔ ∀ a, Injective (f₂ a) := ⟨fun h ↦ h.of_sigma_map, h₁.sigma_map⟩ theorem Function.Surjective.sigma_map {f₁ : α₁ → α₂} {f₂ : ∀ a, β₁ a → β₂ (f₁ a)} (h₁ : Surjective f₁) (h₂ : ∀ a, Surjective (f₂ a)) : Surjective (Sigma.map f₁ f₂) := by simp only [Surjective, Sigma.forall, h₁.forall] exact fun i ↦ (h₂ _).forall.2 fun x ↦ ⟨⟨i, x⟩, rfl⟩ /-- Interpret a function on `Σ x : α, β x` as a dependent function with two arguments. This also exists as an `Equiv` as `Equiv.piCurry γ`. -/ def Sigma.curry {γ : ∀ a, β a → Type*} (f : ∀ x : Sigma β, γ x.1 x.2) (x : α) (y : β x) : γ x y := f ⟨x, y⟩ /-- Interpret a dependent function with two arguments as a function on `Σ x : α, β x`. This also exists as an `Equiv` as `(Equiv.piCurry γ).symm`. -/ def Sigma.uncurry {γ : ∀ a, β a → Type*} (f : ∀ (x) (y : β x), γ x y) (x : Sigma β) : γ x.1 x.2 := f x.1 x.2 @[simp] theorem Sigma.uncurry_curry {γ : ∀ a, β a → Type*} (f : ∀ x : Sigma β, γ x.1 x.2) : Sigma.uncurry (Sigma.curry f) = f := funext fun ⟨_, _⟩ ↦ rfl @[simp] theorem Sigma.curry_uncurry {γ : ∀ a, β a → Type*} (f : ∀ (x) (y : β x), γ x y) : Sigma.curry (Sigma.uncurry f) = f := rfl theorem Sigma.curry_update {γ : ∀ a, β a → Type*} [DecidableEq α] [∀ a, DecidableEq (β a)] (i : Σ a, β a) (f : (i : Σ a, β a) → γ i.1 i.2) (x : γ i.1 i.2) : Sigma.curry (Function.update f i x) = Function.update (Sigma.curry f) i.1 (Function.update (Sigma.curry f i.1) i.2 x) := by obtain ⟨ia, ib⟩ := i ext ja jb unfold Sigma.curry obtain rfl | ha := eq_or_ne ia ja · obtain rfl | hb := eq_or_ne ib jb · simp · simp only [update_same] rw [Function.update_noteq (mt _ hb.symm), Function.update_noteq hb.symm] rintro h injection h · rw [Function.update_noteq (ne_of_apply_ne Sigma.fst _), Function.update_noteq] · exact ha.symm · exact ha.symm /-- Convert a product type to a Σ-type. -/ def Prod.toSigma {α β} (p : α × β) : Σ_ : α, β := ⟨p.1, p.2⟩ @[simp] theorem Prod.fst_comp_toSigma {α β} : Sigma.fst ∘ @Prod.toSigma α β = Prod.fst := rfl @[simp] theorem Prod.fst_toSigma {α β} (x : α × β) : (Prod.toSigma x).fst = x.fst := rfl @[simp] theorem Prod.snd_toSigma {α β} (x : α × β) : (Prod.toSigma x).snd = x.snd := rfl @[simp] theorem Prod.toSigma_mk {α β} (x : α) (y : β) : (x, y).toSigma = ⟨x, y⟩ := rfl -- Porting note: the meta instance `has_reflect (Σa, β a)` was removed here. end Sigma namespace PSigma variable {α : Sort*} {β : α → Sort*} /-- Nondependent eliminator for `PSigma`. -/ def elim {γ} (f : ∀ a, β a → γ) (a : PSigma β) : γ := PSigma.casesOn a f @[simp] theorem elim_val {γ} (f : ∀ a, β a → γ) (a b) : PSigma.elim f ⟨a, b⟩ = f a b := rfl instance [Inhabited α] [Inhabited (β default)] : Inhabited (PSigma β) := ⟨⟨default, default⟩⟩ instance decidableEq [h₁ : DecidableEq α] [h₂ : ∀ a, DecidableEq (β a)] : DecidableEq (PSigma β) | ⟨a₁, b₁⟩, ⟨a₂, b₂⟩ => match a₁, b₁, a₂, b₂, h₁ a₁ a₂ with | _, b₁, _, b₂, isTrue (Eq.refl _) => match b₁, b₂, h₂ _ b₁ b₂ with | _, _, isTrue (Eq.refl _) => isTrue rfl | _, _, isFalse n => isFalse fun h ↦ PSigma.noConfusion h fun _ e₂ ↦ n <| eq_of_heq e₂ | _, _, _, _, isFalse n => isFalse fun h ↦ PSigma.noConfusion h fun e₁ _ ↦ n e₁ -- See https://leanprover.zulipchat.com/#narrow/stream/287929-mathlib4/topic/porting.20data.2Esigma.2Ebasic/near/304855864 -- for an explanation of why this is currently needed. It generates `PSigma.mk.inj`. -- This could be done elsewhere. gen_injective_theorems% PSigma theorem mk.inj_iff {a₁ a₂ : α} {b₁ : β a₁} {b₂ : β a₂} : @PSigma.mk α β a₁ b₁ = @PSigma.mk α β a₂ b₂ ↔ a₁ = a₂ ∧ HEq b₁ b₂ := (Iff.intro PSigma.mk.inj) fun ⟨h₁, h₂⟩ ↦ match a₁, a₂, b₁, b₂, h₁, h₂ with | _, _, _, _, Eq.refl _, HEq.refl _ => rfl @[simp] theorem «forall» {p : (Σ'a, β a) → Prop} : (∀ x, p x) ↔ ∀ a b, p ⟨a, b⟩ := ⟨fun h a b ↦ h ⟨a, b⟩, fun h ⟨a, b⟩ ↦ h a b⟩ #adaptation_note /-- This should be renamed back to `exists` after `nightly-2024-07-31`. -/ @[simp] theorem exists' {p : (Σ'a, β a) → Prop} : (∃ x, p x) ↔ ∃ a b, p ⟨a, b⟩ := ⟨fun ⟨⟨a, b⟩, h⟩ ↦ ⟨a, b, h⟩, fun ⟨a, b, h⟩ ↦ ⟨⟨a, b⟩, h⟩⟩ /-- A specialized ext lemma for equality of `PSigma` types over an indexed subtype. -/ @[ext] theorem subtype_ext {β : Sort*} {p : α → β → Prop} : ∀ {x₀ x₁ : Σ'a, Subtype (p a)}, x₀.fst = x₁.fst → (x₀.snd : β) = x₁.snd → x₀ = x₁ | ⟨_, _, _⟩, ⟨_, _, _⟩, rfl, rfl => rfl variable {α₁ : Sort*} {α₂ : Sort*} {β₁ : α₁ → Sort*} {β₂ : α₂ → Sort*} /-- Map the left and right components of a sigma -/ def map (f₁ : α₁ → α₂) (f₂ : ∀ a, β₁ a → β₂ (f₁ a)) : PSigma β₁ → PSigma β₂ | ⟨a, b⟩ => ⟨f₁ a, f₂ a b⟩ end PSigma
Data\Sigma\Interval.lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import Mathlib.Data.Sigma.Order import Mathlib.Order.Interval.Finset.Defs /-! # Finite intervals in a sigma type This file provides the `LocallyFiniteOrder` instance for the disjoint sum of orders `Σ i, α i` and calculates the cardinality of its finite intervals. ## TODO Do the same for the lexicographical order -/ open Finset Function namespace Sigma variable {ι : Type*} {α : ι → Type*} /-! ### Disjoint sum of orders -/ section Disjoint variable [DecidableEq ι] [∀ i, Preorder (α i)] [∀ i, LocallyFiniteOrder (α i)] instance instLocallyFiniteOrder : LocallyFiniteOrder (Σ i, α i) where finsetIcc := sigmaLift fun _ => Icc finsetIco := sigmaLift fun _ => Ico finsetIoc := sigmaLift fun _ => Ioc finsetIoo := sigmaLift fun _ => Ioo finset_mem_Icc := fun ⟨i, a⟩ ⟨j, b⟩ ⟨k, c⟩ => by simp_rw [mem_sigmaLift, le_def, mem_Icc, exists_and_left, ← exists_and_right, ← exists_prop] exact exists₂_congr fun _ _ => by constructor <;> rintro ⟨⟨⟩, ht⟩ <;> exact ⟨rfl, ht⟩ finset_mem_Ico := fun ⟨i, a⟩ ⟨j, b⟩ ⟨k, c⟩ => by simp_rw [mem_sigmaLift, le_def, lt_def, mem_Ico, exists_and_left, ← exists_and_right, ← exists_prop] exact exists₂_congr fun _ _ => by constructor <;> rintro ⟨⟨⟩, ht⟩ <;> exact ⟨rfl, ht⟩ finset_mem_Ioc := fun ⟨i, a⟩ ⟨j, b⟩ ⟨k, c⟩ => by simp_rw [mem_sigmaLift, le_def, lt_def, mem_Ioc, exists_and_left, ← exists_and_right, ← exists_prop] exact exists₂_congr fun _ _ => by constructor <;> rintro ⟨⟨⟩, ht⟩ <;> exact ⟨rfl, ht⟩ finset_mem_Ioo := fun ⟨i, a⟩ ⟨j, b⟩ ⟨k, c⟩ => by simp_rw [mem_sigmaLift, lt_def, mem_Ioo, exists_and_left, ← exists_and_right, ← exists_prop] exact exists₂_congr fun _ _ => by constructor <;> rintro ⟨⟨⟩, ht⟩ <;> exact ⟨rfl, ht⟩ section variable (a b : Σ i, α i) theorem card_Icc : (Icc a b).card = if h : a.1 = b.1 then (Icc (h.rec a.2) b.2).card else 0 := card_sigmaLift (fun _ => Icc) _ _ theorem card_Ico : (Ico a b).card = if h : a.1 = b.1 then (Ico (h.rec a.2) b.2).card else 0 := card_sigmaLift (fun _ => Ico) _ _ theorem card_Ioc : (Ioc a b).card = if h : a.1 = b.1 then (Ioc (h.rec a.2) b.2).card else 0 := card_sigmaLift (fun _ => Ioc) _ _ theorem card_Ioo : (Ioo a b).card = if h : a.1 = b.1 then (Ioo (h.rec a.2) b.2).card else 0 := card_sigmaLift (fun _ => Ioo) _ _ end variable (i : ι) (a b : α i) @[simp] theorem Icc_mk_mk : Icc (⟨i, a⟩ : Sigma α) ⟨i, b⟩ = (Icc a b).map (Embedding.sigmaMk i) := dif_pos rfl @[simp] theorem Ico_mk_mk : Ico (⟨i, a⟩ : Sigma α) ⟨i, b⟩ = (Ico a b).map (Embedding.sigmaMk i) := dif_pos rfl @[simp] theorem Ioc_mk_mk : Ioc (⟨i, a⟩ : Sigma α) ⟨i, b⟩ = (Ioc a b).map (Embedding.sigmaMk i) := dif_pos rfl @[simp] theorem Ioo_mk_mk : Ioo (⟨i, a⟩ : Sigma α) ⟨i, b⟩ = (Ioo a b).map (Embedding.sigmaMk i) := dif_pos rfl end Disjoint end Sigma
Data\Sigma\Lex.lean
/- Copyright (c) 2021 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import Mathlib.Order.RelClasses /-! # Lexicographic order on a sigma type This defines the lexicographical order of two arbitrary relations on a sigma type and proves some lemmas about `PSigma.Lex`, which is defined in core Lean. Given a relation in the index type and a relation on each summand, the lexicographical order on the sigma type relates `a` and `b` if their summands are related or they are in the same summand and related by the summand's relation. ## See also Related files are: * `Combinatorics.CoLex`: Colexicographic order on finite sets. * `Data.List.Lex`: Lexicographic order on lists. * `Data.Sigma.Order`: Lexicographic order on `Σ i, α i` per say. * `Data.PSigma.Order`: Lexicographic order on `Σ' i, α i`. * `Data.Prod.Lex`: Lexicographic order on `α × β`. Can be thought of as the special case of `Sigma.Lex` where all summands are the same -/ namespace Sigma variable {ι : Type*} {α : ι → Type*} {r r₁ r₂ : ι → ι → Prop} {s s₁ s₂ : ∀ i, α i → α i → Prop} {a b : Σ i, α i} /-- The lexicographical order on a sigma type. It takes in a relation on the index type and a relation for each summand. `a` is related to `b` iff their summands are related or they are in the same summand and are related through the summand's relation. -/ inductive Lex (r : ι → ι → Prop) (s : ∀ i, α i → α i → Prop) : ∀ _ _ : Σ i, α i, Prop | left {i j : ι} (a : α i) (b : α j) : r i j → Lex r s ⟨i, a⟩ ⟨j, b⟩ | right {i : ι} (a b : α i) : s i a b → Lex r s ⟨i, a⟩ ⟨i, b⟩ theorem lex_iff : Lex r s a b ↔ r a.1 b.1 ∨ ∃ h : a.1 = b.1, s b.1 (h.rec a.2) b.2 := by constructor · rintro (⟨a, b, hij⟩ | ⟨a, b, hab⟩) · exact Or.inl hij · exact Or.inr ⟨rfl, hab⟩ · obtain ⟨i, a⟩ := a obtain ⟨j, b⟩ := b dsimp only rintro (h | ⟨rfl, h⟩) · exact Lex.left _ _ h · exact Lex.right _ _ h instance Lex.decidable (r : ι → ι → Prop) (s : ∀ i, α i → α i → Prop) [DecidableEq ι] [DecidableRel r] [∀ i, DecidableRel (s i)] : DecidableRel (Lex r s) := fun _ _ => decidable_of_decidable_of_iff lex_iff.symm theorem Lex.mono (hr : ∀ a b, r₁ a b → r₂ a b) (hs : ∀ i a b, s₁ i a b → s₂ i a b) {a b : Σ i, α i} (h : Lex r₁ s₁ a b) : Lex r₂ s₂ a b := by obtain ⟨a, b, hij⟩ | ⟨a, b, hab⟩ := h · exact Lex.left _ _ (hr _ _ hij) · exact Lex.right _ _ (hs _ _ _ hab) theorem Lex.mono_left (hr : ∀ a b, r₁ a b → r₂ a b) {a b : Σ i, α i} (h : Lex r₁ s a b) : Lex r₂ s a b := h.mono hr fun _ _ _ => id theorem Lex.mono_right (hs : ∀ i a b, s₁ i a b → s₂ i a b) {a b : Σ i, α i} (h : Lex r s₁ a b) : Lex r s₂ a b := h.mono (fun _ _ => id) hs theorem lex_swap : Lex (Function.swap r) s a b ↔ Lex r (fun i => Function.swap (s i)) b a := by constructor <;> · rintro (⟨a, b, h⟩ | ⟨a, b, h⟩) exacts [Lex.left _ _ h, Lex.right _ _ h] instance [∀ i, IsRefl (α i) (s i)] : IsRefl _ (Lex r s) := ⟨fun ⟨_, _⟩ => Lex.right _ _ <| refl _⟩ instance [IsIrrefl ι r] [∀ i, IsIrrefl (α i) (s i)] : IsIrrefl _ (Lex r s) := ⟨by rintro _ (⟨a, b, hi⟩ | ⟨a, b, ha⟩) · exact irrefl _ hi · exact irrefl _ ha ⟩ instance [IsTrans ι r] [∀ i, IsTrans (α i) (s i)] : IsTrans _ (Lex r s) := ⟨by rintro _ _ _ (⟨a, b, hij⟩ | ⟨a, b, hab⟩) (⟨_, c, hk⟩ | ⟨_, c, hc⟩) · exact Lex.left _ _ (_root_.trans hij hk) · exact Lex.left _ _ hij · exact Lex.left _ _ hk · exact Lex.right _ _ (_root_.trans hab hc)⟩ instance [IsSymm ι r] [∀ i, IsSymm (α i) (s i)] : IsSymm _ (Lex r s) := ⟨by rintro _ _ (⟨a, b, hij⟩ | ⟨a, b, hab⟩) · exact Lex.left _ _ (symm hij) · exact Lex.right _ _ (symm hab) ⟩ attribute [local instance] IsAsymm.isIrrefl instance [IsAsymm ι r] [∀ i, IsAntisymm (α i) (s i)] : IsAntisymm _ (Lex r s) := ⟨by rintro _ _ (⟨a, b, hij⟩ | ⟨a, b, hab⟩) (⟨_, _, hji⟩ | ⟨_, _, hba⟩) · exact (asymm hij hji).elim · exact (irrefl _ hij).elim · exact (irrefl _ hji).elim · exact congr_arg (Sigma.mk _ ·) <| antisymm hab hba⟩ instance [IsTrichotomous ι r] [∀ i, IsTotal (α i) (s i)] : IsTotal _ (Lex r s) := ⟨by rintro ⟨i, a⟩ ⟨j, b⟩ obtain hij | rfl | hji := trichotomous_of r i j · exact Or.inl (Lex.left _ _ hij) · obtain hab | hba := total_of (s i) a b · exact Or.inl (Lex.right _ _ hab) · exact Or.inr (Lex.right _ _ hba) · exact Or.inr (Lex.left _ _ hji)⟩ instance [IsTrichotomous ι r] [∀ i, IsTrichotomous (α i) (s i)] : IsTrichotomous _ (Lex r s) := ⟨by rintro ⟨i, a⟩ ⟨j, b⟩ obtain hij | rfl | hji := trichotomous_of r i j · exact Or.inl (Lex.left _ _ hij) · obtain hab | rfl | hba := trichotomous_of (s i) a b · exact Or.inl (Lex.right _ _ hab) · exact Or.inr (Or.inl rfl) · exact Or.inr (Or.inr <| Lex.right _ _ hba) · exact Or.inr (Or.inr <| Lex.left _ _ hji)⟩ end Sigma /-! ### `PSigma` -/ namespace PSigma variable {ι : Sort*} {α : ι → Sort*} {r r₁ r₂ : ι → ι → Prop} {s s₁ s₂ : ∀ i, α i → α i → Prop} theorem lex_iff {a b : Σ' i, α i} : Lex r s a b ↔ r a.1 b.1 ∨ ∃ h : a.1 = b.1, s b.1 (h.rec a.2) b.2 := by constructor · rintro (⟨a, b, hij⟩ | ⟨i, hab⟩) · exact Or.inl hij · exact Or.inr ⟨rfl, hab⟩ · obtain ⟨i, a⟩ := a obtain ⟨j, b⟩ := b dsimp only rintro (h | ⟨rfl, h⟩) · exact Lex.left _ _ h · exact Lex.right _ h instance Lex.decidable (r : ι → ι → Prop) (s : ∀ i, α i → α i → Prop) [DecidableEq ι] [DecidableRel r] [∀ i, DecidableRel (s i)] : DecidableRel (Lex r s) := fun _ _ => decidable_of_decidable_of_iff lex_iff.symm theorem Lex.mono {r₁ r₂ : ι → ι → Prop} {s₁ s₂ : ∀ i, α i → α i → Prop} (hr : ∀ a b, r₁ a b → r₂ a b) (hs : ∀ i a b, s₁ i a b → s₂ i a b) {a b : Σ' i, α i} (h : Lex r₁ s₁ a b) : Lex r₂ s₂ a b := by obtain ⟨a, b, hij⟩ | ⟨i, hab⟩ := h · exact Lex.left _ _ (hr _ _ hij) · exact Lex.right _ (hs _ _ _ hab) theorem Lex.mono_left {r₁ r₂ : ι → ι → Prop} {s : ∀ i, α i → α i → Prop} (hr : ∀ a b, r₁ a b → r₂ a b) {a b : Σ' i, α i} (h : Lex r₁ s a b) : Lex r₂ s a b := h.mono hr fun _ _ _ => id theorem Lex.mono_right {r : ι → ι → Prop} {s₁ s₂ : ∀ i, α i → α i → Prop} (hs : ∀ i a b, s₁ i a b → s₂ i a b) {a b : Σ' i, α i} (h : Lex r s₁ a b) : Lex r s₂ a b := h.mono (fun _ _ => id) hs end PSigma
Data\Sigma\Order.lean
/- Copyright (c) 2021 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import Mathlib.Data.Sigma.Lex import Mathlib.Order.BoundedOrder import Mathlib.Mathport.Notation import Mathlib.Data.Sigma.Basic /-! # Orders on a sigma type This file defines two orders on a sigma type: * The disjoint sum of orders. `a` is less `b` iff `a` and `b` are in the same summand and `a` is less than `b` there. * The lexicographical order. `a` is less than `b` if its summand is strictly less than the summand of `b` or they are in the same summand and `a` is less than `b` there. We make the disjoint sum of orders the default set of instances. The lexicographic order goes on a type synonym. ## Notation * `_root_.Lex (Sigma α)`: Sigma type equipped with the lexicographic order. Type synonym of `Σ i, α i`. ## See also Related files are: * `Data.Finset.CoLex`: Colexicographic order on finite sets. * `Data.List.Lex`: Lexicographic order on lists. * `Data.Pi.Lex`: Lexicographic order on `Πₗ i, α i`. * `Data.PSigma.Order`: Lexicographic order on `Σₗ' i, α i`. Basically a twin of this file. * `Data.Prod.Lex`: Lexicographic order on `α × β`. ## TODO Upgrade `Equiv.sigma_congr_left`, `Equiv.sigma_congr`, `Equiv.sigma_assoc`, `Equiv.sigma_prod_of_equiv`, `Equiv.sigma_equiv_prod`, ... to order isomorphisms. -/ namespace Sigma variable {ι : Type*} {α : ι → Type*} /-! ### Disjoint sum of orders on `Sigma` -/ -- Porting note: I made this `le` instead of `LE` because the output type is `Prop` /-- Disjoint sum of orders. `⟨i, a⟩ ≤ ⟨j, b⟩` iff `i = j` and `a ≤ b`. -/ protected inductive le [∀ i, LE (α i)] : ∀ _a _b : Σ i, α i, Prop | fiber (i : ι) (a b : α i) : a ≤ b → Sigma.le ⟨i, a⟩ ⟨i, b⟩ /-- Disjoint sum of orders. `⟨i, a⟩ < ⟨j, b⟩` iff `i = j` and `a < b`. -/ protected inductive lt [∀ i, LT (α i)] : ∀ _a _b : Σi, α i, Prop | fiber (i : ι) (a b : α i) : a < b → Sigma.lt ⟨i, a⟩ ⟨i, b⟩ protected instance LE [∀ i, LE (α i)] : LE (Σi, α i) where le := Sigma.le protected instance LT [∀ i, LT (α i)] : LT (Σi, α i) where lt := Sigma.lt @[simp] theorem mk_le_mk_iff [∀ i, LE (α i)] {i : ι} {a b : α i} : (⟨i, a⟩ : Sigma α) ≤ ⟨i, b⟩ ↔ a ≤ b := ⟨fun ⟨_, _, _, h⟩ => h, Sigma.le.fiber _ _ _⟩ @[simp] theorem mk_lt_mk_iff [∀ i, LT (α i)] {i : ι} {a b : α i} : (⟨i, a⟩ : Sigma α) < ⟨i, b⟩ ↔ a < b := ⟨fun ⟨_, _, _, h⟩ => h, Sigma.lt.fiber _ _ _⟩ theorem le_def [∀ i, LE (α i)] {a b : Σi, α i} : a ≤ b ↔ ∃ h : a.1 = b.1, h.rec a.2 ≤ b.2 := by constructor · rintro ⟨i, a, b, h⟩ exact ⟨rfl, h⟩ · obtain ⟨i, a⟩ := a obtain ⟨j, b⟩ := b rintro ⟨rfl : i = j, h⟩ exact le.fiber _ _ _ h theorem lt_def [∀ i, LT (α i)] {a b : Σi, α i} : a < b ↔ ∃ h : a.1 = b.1, h.rec a.2 < b.2 := by constructor · rintro ⟨i, a, b, h⟩ exact ⟨rfl, h⟩ · obtain ⟨i, a⟩ := a obtain ⟨j, b⟩ := b rintro ⟨rfl : i = j, h⟩ exact lt.fiber _ _ _ h protected instance preorder [∀ i, Preorder (α i)] : Preorder (Σi, α i) := { Sigma.LE, Sigma.LT with le_refl := fun ⟨i, a⟩ => Sigma.le.fiber i a a le_rfl, le_trans := by rintro _ _ _ ⟨i, a, b, hab⟩ ⟨_, _, c, hbc⟩ exact le.fiber i a c (hab.trans hbc), lt_iff_le_not_le := fun _ _ => by constructor · rintro ⟨i, a, b, hab⟩ rwa [mk_le_mk_iff, mk_le_mk_iff, ← lt_iff_le_not_le] · rintro ⟨⟨i, a, b, hab⟩, h⟩ rw [mk_le_mk_iff] at h exact mk_lt_mk_iff.2 (hab.lt_of_not_le h) } instance [∀ i, PartialOrder (α i)] : PartialOrder (Σi, α i) := { Sigma.preorder with le_antisymm := by rintro _ _ ⟨i, a, b, hab⟩ ⟨_, _, _, hba⟩ exact congr_arg (Sigma.mk _ ·) <| hab.antisymm hba } instance [∀ i, Preorder (α i)] [∀ i, DenselyOrdered (α i)] : DenselyOrdered (Σi, α i) where dense := by rintro ⟨i, a⟩ ⟨_, _⟩ ⟨_, _, b, h⟩ obtain ⟨c, ha, hb⟩ := exists_between h exact ⟨⟨i, c⟩, lt.fiber i a c ha, lt.fiber i c b hb⟩ /-! ### Lexicographical order on `Sigma` -/ namespace Lex /-- The notation `Σₗ i, α i` refers to a sigma type equipped with the lexicographic order. -/ notation3 "Σₗ "(...)", "r:(scoped p => _root_.Lex (Sigma p)) => r /-- The lexicographical `≤` on a sigma type. -/ protected instance LE [LT ι] [∀ i, LE (α i)] : LE (Σₗ i, α i) where le := Lex (· < ·) fun _ => (· ≤ ·) /-- The lexicographical `<` on a sigma type. -/ protected instance LT [LT ι] [∀ i, LT (α i)] : LT (Σₗ i, α i) where lt := Lex (· < ·) fun _ => (· < ·) theorem le_def [LT ι] [∀ i, LE (α i)] {a b : Σₗ i, α i} : a ≤ b ↔ a.1 < b.1 ∨ ∃ h : a.1 = b.1, h.rec a.2 ≤ b.2 := Sigma.lex_iff theorem lt_def [LT ι] [∀ i, LT (α i)] {a b : Σₗ i, α i} : a < b ↔ a.1 < b.1 ∨ ∃ h : a.1 = b.1, h.rec a.2 < b.2 := Sigma.lex_iff /-- The lexicographical preorder on a sigma type. -/ instance preorder [Preorder ι] [∀ i, Preorder (α i)] : Preorder (Σₗ i, α i) := { Sigma.Lex.LE, Sigma.Lex.LT with le_refl := fun ⟨i, a⟩ => Lex.right a a le_rfl, le_trans := fun _ _ _ => trans_of ((Lex (· < ·)) fun _ => (· ≤ ·)), lt_iff_le_not_le := by refine fun a b => ⟨fun hab => ⟨hab.mono_right fun i a b => le_of_lt, ?_⟩, ?_⟩ · rintro (⟨b, a, hji⟩ | ⟨b, a, hba⟩) <;> obtain ⟨_, _, hij⟩ | ⟨_, _, hab⟩ := hab · exact hij.not_lt hji · exact lt_irrefl _ hji · exact lt_irrefl _ hij · exact hab.not_le hba · rintro ⟨⟨a, b, hij⟩ | ⟨a, b, hab⟩, hba⟩ · exact Sigma.Lex.left _ _ hij · exact Sigma.Lex.right _ _ (hab.lt_of_not_le fun h => hba <| Sigma.Lex.right _ _ h) } /-- The lexicographical partial order on a sigma type. -/ instance partialOrder [Preorder ι] [∀ i, PartialOrder (α i)] : PartialOrder (Σₗ i, α i) := { Lex.preorder with le_antisymm := fun _ _ => antisymm_of ((Lex (· < ·)) fun _ => (· ≤ ·)) } /-- The lexicographical linear order on a sigma type. -/ instance linearOrder [LinearOrder ι] [∀ i, LinearOrder (α i)] : LinearOrder (Σₗ i, α i) := { Lex.partialOrder with le_total := total_of ((Lex (· < ·)) fun _ => (· ≤ ·)), decidableEq := Sigma.instDecidableEqSigma, decidableLE := Lex.decidable _ _ } /-- The lexicographical linear order on a sigma type. -/ instance orderBot [PartialOrder ι] [OrderBot ι] [∀ i, Preorder (α i)] [OrderBot (α ⊥)] : OrderBot (Σₗ i, α i) where bot := ⟨⊥, ⊥⟩ bot_le := fun ⟨a, b⟩ => by obtain rfl | ha := eq_bot_or_bot_lt a · exact Lex.right _ _ bot_le · exact Lex.left _ _ ha /-- The lexicographical linear order on a sigma type. -/ instance orderTop [PartialOrder ι] [OrderTop ι] [∀ i, Preorder (α i)] [OrderTop (α ⊤)] : OrderTop (Σₗ i, α i) where top := ⟨⊤, ⊤⟩ le_top := fun ⟨a, b⟩ => by obtain rfl | ha := eq_top_or_lt_top a · exact Lex.right _ _ le_top · exact Lex.left _ _ ha /-- The lexicographical linear order on a sigma type. -/ instance boundedOrder [PartialOrder ι] [BoundedOrder ι] [∀ i, Preorder (α i)] [OrderBot (α ⊥)] [OrderTop (α ⊤)] : BoundedOrder (Σₗ i, α i) := { Lex.orderBot, Lex.orderTop with } instance denselyOrdered [Preorder ι] [DenselyOrdered ι] [∀ i, Nonempty (α i)] [∀ i, Preorder (α i)] [∀ i, DenselyOrdered (α i)] : DenselyOrdered (Σₗ i, α i) where dense := by rintro ⟨i, a⟩ ⟨j, b⟩ (⟨_, _, h⟩ | ⟨_, b, h⟩) · obtain ⟨k, hi, hj⟩ := exists_between h obtain ⟨c⟩ : Nonempty (α k) := inferInstance exact ⟨⟨k, c⟩, left _ _ hi, left _ _ hj⟩ · obtain ⟨c, ha, hb⟩ := exists_between h exact ⟨⟨i, c⟩, right _ _ ha, right _ _ hb⟩ instance denselyOrdered_of_noMaxOrder [Preorder ι] [∀ i, Preorder (α i)] [∀ i, DenselyOrdered (α i)] [∀ i, NoMaxOrder (α i)] : DenselyOrdered (Σₗ i, α i) where dense := by rintro ⟨i, a⟩ ⟨j, b⟩ (⟨_, _, h⟩ | ⟨_, b, h⟩) · obtain ⟨c, ha⟩ := exists_gt a exact ⟨⟨i, c⟩, right _ _ ha, left _ _ h⟩ · obtain ⟨c, ha, hb⟩ := exists_between h exact ⟨⟨i, c⟩, right _ _ ha, right _ _ hb⟩ instance denselyOrdered_of_noMinOrder [Preorder ι] [∀ i, Preorder (α i)] [∀ i, DenselyOrdered (α i)] [∀ i, NoMinOrder (α i)] : DenselyOrdered (Σₗ i, α i) where dense := by rintro ⟨i, a⟩ ⟨j, b⟩ (⟨_, _, h⟩ | ⟨_, b, h⟩) · obtain ⟨c, hb⟩ := exists_lt b exact ⟨⟨j, c⟩, left _ _ h, right _ _ hb⟩ · obtain ⟨c, ha, hb⟩ := exists_between h exact ⟨⟨i, c⟩, right _ _ ha, right _ _ hb⟩ instance noMaxOrder_of_nonempty [Preorder ι] [∀ i, Preorder (α i)] [NoMaxOrder ι] [∀ i, Nonempty (α i)] : NoMaxOrder (Σₗ i, α i) where exists_gt := by rintro ⟨i, a⟩ obtain ⟨j, h⟩ := exists_gt i obtain ⟨b⟩ : Nonempty (α j) := inferInstance exact ⟨⟨j, b⟩, left _ _ h⟩ instance noMinOrder_of_nonempty [Preorder ι] [∀ i, Preorder (α i)] [NoMinOrder ι] [∀ i, Nonempty (α i)] : NoMinOrder (Σₗ i, α i) where exists_lt := by rintro ⟨i, a⟩ obtain ⟨j, h⟩ := exists_lt i obtain ⟨b⟩ : Nonempty (α j) := inferInstance exact ⟨⟨j, b⟩, left _ _ h⟩ instance noMaxOrder [Preorder ι] [∀ i, Preorder (α i)] [∀ i, NoMaxOrder (α i)] : NoMaxOrder (Σₗ i, α i) where exists_gt := by rintro ⟨i, a⟩ obtain ⟨b, h⟩ := exists_gt a exact ⟨⟨i, b⟩, right _ _ h⟩ instance noMinOrder [Preorder ι] [∀ i, Preorder (α i)] [∀ i, NoMinOrder (α i)] : NoMinOrder (Σₗ i, α i) where exists_lt := by rintro ⟨i, a⟩ obtain ⟨b, h⟩ := exists_lt a exact ⟨⟨i, b⟩, right _ _ h⟩ end Lex end Sigma
Data\Stream\Defs.lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Mathlib.Data.Nat.Notation /-! # Definition of `Stream'` and functions on streams A stream `Stream' α` is an infinite sequence of elements of `α`. One can also think about it as an infinite list. In this file we define `Stream'` and some functions that take and/or return streams. Note that we already have `Stream` to represent a similar object, hence the awkward naming. -/ universe u v w variable {α : Type u} {β : Type v} {δ : Type w} /-- A stream `Stream' α` is an infinite sequence of elements of `α`. -/ def Stream' (α : Type u) := ℕ → α namespace Stream' /-- Prepend an element to a stream. -/ def cons (a : α) (s : Stream' α) : Stream' α | 0 => a | n + 1 => s n scoped infixr:67 " :: " => cons /-- Get the `n`-th element of a stream. -/ def get (s : Stream' α) (n : ℕ) : α := s n /-- Head of a stream: `Stream'.head s = Stream'.get s 0`. -/ abbrev head (s : Stream' α) : α := s.get 0 /-- Tail of a stream: `Stream'.tail (h :: t) = t`. -/ def tail (s : Stream' α) : Stream' α := fun i => s.get (i + 1) /-- Drop first `n` elements of a stream. -/ def drop (n : ℕ) (s : Stream' α) : Stream' α := fun i => s.get (i + n) /-- Proposition saying that all elements of a stream satisfy a predicate. -/ def All (p : α → Prop) (s : Stream' α) := ∀ n, p (get s n) /-- Proposition saying that at least one element of a stream satisfies a predicate. -/ def Any (p : α → Prop) (s : Stream' α) := ∃ n, p (get s n) /-- `a ∈ s` means that `a = Stream'.get n s` for some `n`. -/ instance : Membership α (Stream' α) := ⟨fun a s => Any (fun b => a = b) s⟩ /-- Apply a function `f` to all elements of a stream `s`. -/ def map (f : α → β) (s : Stream' α) : Stream' β := fun n => f (get s n) /-- Zip two streams using a binary operation: `Stream'.get n (Stream'.zip f s₁ s₂) = f (Stream'.get s₁) (Stream'.get s₂)`. -/ def zip (f : α → β → δ) (s₁ : Stream' α) (s₂ : Stream' β) : Stream' δ := fun n => f (get s₁ n) (get s₂ n) /-- Enumerate a stream by tagging each element with its index. -/ def enum (s : Stream' α) : Stream' (ℕ × α) := fun n => (n, s.get n) /-- The constant stream: `Stream'.get n (Stream'.const a) = a`. -/ def const (a : α) : Stream' α := fun _ => a -- Porting note: used to be implemented using RecOn /-- Iterates of a function as a stream. -/ def iterate (f : α → α) (a : α) : Stream' α | 0 => a | n + 1 => f (iterate f a n) def corec (f : α → β) (g : α → α) : α → Stream' β := fun a => map f (iterate g a) def corecOn (a : α) (f : α → β) (g : α → α) : Stream' β := corec f g a def corec' (f : α → β × α) : α → Stream' β := corec (Prod.fst ∘ f) (Prod.snd ∘ f) /-- Use a state monad to generate a stream through corecursion -/ def corecState {σ α} (cmd : StateM σ α) (s : σ) : Stream' α := corec Prod.fst (cmd.run ∘ Prod.snd) (cmd.run s) -- corec is also known as unfold abbrev unfolds (g : α → β) (f : α → α) (a : α) : Stream' β := corec g f a /-- Interleave two streams. -/ def interleave (s₁ s₂ : Stream' α) : Stream' α := corecOn (s₁, s₂) (fun ⟨s₁, _⟩ => head s₁) fun ⟨s₁, s₂⟩ => (s₂, tail s₁) infixl:65 " ⋈ " => interleave /-- Elements of a stream with even indices. -/ def even (s : Stream' α) : Stream' α := corec (fun s => head s) (fun s => tail (tail s)) s /-- Elements of a stream with odd indices. -/ def odd (s : Stream' α) : Stream' α := even (tail s) /-- Append a stream to a list. -/ def appendStream' : List α → Stream' α → Stream' α | [], s => s | List.cons a l, s => a::appendStream' l s infixl:65 " ++ₛ " => appendStream' /-- `take n s` returns a list of the `n` first elements of stream `s` -/ def take : ℕ → Stream' α → List α | 0, _ => [] | n + 1, s => List.cons (head s) (take n (tail s)) /-- An auxiliary definition for `Stream'.cycle` corecursive def -/ protected def cycleF : α × List α × α × List α → α | (v, _, _, _) => v /-- An auxiliary definition for `Stream'.cycle` corecursive def -/ protected def cycleG : α × List α × α × List α → α × List α × α × List α | (_, [], v₀, l₀) => (v₀, l₀, v₀, l₀) | (_, List.cons v₂ l₂, v₀, l₀) => (v₂, l₂, v₀, l₀) /-- Interpret a nonempty list as a cyclic stream. -/ def cycle : ∀ l : List α, l ≠ [] → Stream' α | [], h => absurd rfl h | List.cons a l, _ => corec Stream'.cycleF Stream'.cycleG (a, l, a, l) /-- Tails of a stream, starting with `Stream'.tail s`. -/ def tails (s : Stream' α) : Stream' (Stream' α) := corec id tail (tail s) /-- An auxiliary definition for `Stream'.inits`. -/ def initsCore (l : List α) (s : Stream' α) : Stream' (List α) := corecOn (l, s) (fun ⟨a, _⟩ => a) fun p => match p with | (l', s') => (l' ++ [head s'], tail s') /-- Nonempty initial segments of a stream. -/ def inits (s : Stream' α) : Stream' (List α) := initsCore [head s] (tail s) /-- A constant stream, same as `Stream'.const`. -/ def pure (a : α) : Stream' α := const a /-- Given a stream of functions and a stream of values, apply `n`-th function to `n`-th value. -/ def apply (f : Stream' (α → β)) (s : Stream' α) : Stream' β := fun n => (get f n) (get s n) infixl:75 " ⊛ " => apply -- Porting note: "input as \o*" was here but doesn't work for the above notation /-- The stream of natural numbers: `Stream'.get n Stream'.nats = n`. -/ def nats : Stream' ℕ := fun n => n end Stream'