blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
7
139
content_id
stringlengths
40
40
detected_licenses
listlengths
0
16
license_type
stringclasses
2 values
repo_name
stringlengths
7
55
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
6 values
visit_date
int64
1,471B
1,694B
revision_date
int64
1,378B
1,694B
committer_date
int64
1,378B
1,694B
github_id
float64
1.33M
604M
star_events_count
int64
0
43.5k
fork_events_count
int64
0
1.5k
gha_license_id
stringclasses
6 values
gha_event_created_at
int64
1,402B
1,695B
gha_created_at
int64
1,359B
1,637B
gha_language
stringclasses
19 values
src_encoding
stringclasses
2 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
1 class
length_bytes
int64
3
6.4M
extension
stringclasses
4 values
content
stringlengths
3
6.12M
5397beec0b85c08fc2cb5164efe472596d3e5d46
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/order/filter/at_top_bot.lean
e0cc32ed65b4bcd2722acbf2b46fb096ccc77135
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
80,831
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, Jeremy Avigad, Yury Kudryashov, Patrick Massot -/ import algebra.order.field.basic import data.finset.preimage import data.set.intervals.disjoint import data.set.intervals.order_iso import order.filter.bases import algebra.order.group.min_max /-! # `at_top` and `at_bot` filters on preorded sets, monoids and groups. In this file we define the filters * `at_top`: corresponds to `n → +∞`; * `at_bot`: corresponds to `n → -∞`. Then we prove many lemmas like “if `f → +∞`, then `f ± c → +∞`”. -/ variables {ι ι' α β γ : Type*} open set open_locale classical filter big_operators namespace filter /-- `at_top` is the filter representing the limit `→ ∞` on an ordered set. It is generated by the collection of up-sets `{b | a ≤ b}`. (The preorder need not have a top element for this to be well defined, and indeed is trivial when a top element exists.) -/ def at_top [preorder α] : filter α := ⨅ a, 𝓟 (Ici a) /-- `at_bot` is the filter representing the limit `→ -∞` on an ordered set. It is generated by the collection of down-sets `{b | b ≤ a}`. (The preorder need not have a bottom element for this to be well defined, and indeed is trivial when a bottom element exists.) -/ def at_bot [preorder α] : filter α := ⨅ a, 𝓟 (Iic a) lemma mem_at_top [preorder α] (a : α) : {b : α | a ≤ b} ∈ @at_top α _ := mem_infi_of_mem a $ subset.refl _ lemma Ici_mem_at_top [preorder α] (a : α) : Ici a ∈ (at_top : filter α) := mem_at_top a lemma Ioi_mem_at_top [preorder α] [no_max_order α] (x : α) : Ioi x ∈ (at_top : filter α) := let ⟨z, hz⟩ := exists_gt x in mem_of_superset (mem_at_top z) $ λ y h, lt_of_lt_of_le hz h lemma mem_at_bot [preorder α] (a : α) : {b : α | b ≤ a} ∈ @at_bot α _ := mem_infi_of_mem a $ subset.refl _ lemma Iic_mem_at_bot [preorder α] (a : α) : Iic a ∈ (at_bot : filter α) := mem_at_bot a lemma Iio_mem_at_bot [preorder α] [no_min_order α] (x : α) : Iio x ∈ (at_bot : filter α) := let ⟨z, hz⟩ := exists_lt x in mem_of_superset (mem_at_bot z) $ λ y h, lt_of_le_of_lt h hz lemma disjoint_at_bot_principal_Ioi [preorder α] (x : α) : disjoint at_bot (𝓟 (Ioi x)) := disjoint_of_disjoint_of_mem (Iic_disjoint_Ioi le_rfl) (Iic_mem_at_bot x) (mem_principal_self _) lemma disjoint_at_top_principal_Iio [preorder α] (x : α) : disjoint at_top (𝓟 (Iio x)) := @disjoint_at_bot_principal_Ioi αᵒᵈ _ _ lemma disjoint_at_top_principal_Iic [preorder α] [no_max_order α] (x : α) : disjoint at_top (𝓟 (Iic x)) := disjoint_of_disjoint_of_mem (Iic_disjoint_Ioi le_rfl).symm (Ioi_mem_at_top x) (mem_principal_self _) lemma disjoint_at_bot_principal_Ici [preorder α] [no_min_order α] (x : α) : disjoint at_bot (𝓟 (Ici x)) := @disjoint_at_top_principal_Iic αᵒᵈ _ _ _ lemma disjoint_pure_at_top [preorder α] [no_max_order α] (x : α) : disjoint (pure x) at_top := disjoint.symm ((disjoint_at_top_principal_Iic x).mono_right $ le_principal_iff.2 le_rfl) lemma disjoint_pure_at_bot [preorder α] [no_min_order α] (x : α) : disjoint (pure x) at_bot := @disjoint_pure_at_top αᵒᵈ _ _ _ lemma not_tendsto_const_at_top [preorder α] [no_max_order α] (x : α) (l : filter β) [l.ne_bot] : ¬tendsto (λ _, x) l at_top := tendsto_const_pure.not_tendsto (disjoint_pure_at_top x) lemma not_tendsto_const_at_bot [preorder α] [no_min_order α] (x : α) (l : filter β) [l.ne_bot] : ¬tendsto (λ _, x) l at_bot := tendsto_const_pure.not_tendsto (disjoint_pure_at_bot x) lemma disjoint_at_bot_at_top [partial_order α] [nontrivial α] : disjoint (at_bot : filter α) at_top := begin rcases exists_pair_ne α with ⟨x, y, hne⟩, by_cases hle : x ≤ y, { refine disjoint_of_disjoint_of_mem _ (Iic_mem_at_bot x) (Ici_mem_at_top y), exact Iic_disjoint_Ici.2 (hle.lt_of_ne hne).not_le }, { refine disjoint_of_disjoint_of_mem _ (Iic_mem_at_bot y) (Ici_mem_at_top x), exact Iic_disjoint_Ici.2 hle } end lemma disjoint_at_top_at_bot [partial_order α] [nontrivial α] : disjoint (at_top : filter α) at_bot := disjoint_at_bot_at_top.symm lemma at_top_basis [nonempty α] [semilattice_sup α] : (@at_top α _).has_basis (λ _, true) Ici := has_basis_infi_principal (directed_of_sup $ λ a b, Ici_subset_Ici.2) lemma at_top_basis' [semilattice_sup α] (a : α) : (@at_top α _).has_basis (λ x, a ≤ x) Ici := ⟨λ t, (@at_top_basis α ⟨a⟩ _).mem_iff.trans ⟨λ ⟨x, _, hx⟩, ⟨x ⊔ a, le_sup_right, λ y hy, hx (le_trans le_sup_left hy)⟩, λ ⟨x, _, hx⟩, ⟨x, trivial, hx⟩⟩⟩ lemma at_bot_basis [nonempty α] [semilattice_inf α] : (@at_bot α _).has_basis (λ _, true) Iic := @at_top_basis αᵒᵈ _ _ lemma at_bot_basis' [semilattice_inf α] (a : α) : (@at_bot α _).has_basis (λ x, x ≤ a) Iic := @at_top_basis' αᵒᵈ _ _ @[instance] lemma at_top_ne_bot [nonempty α] [semilattice_sup α] : ne_bot (at_top : filter α) := at_top_basis.ne_bot_iff.2 $ λ a _, nonempty_Ici @[instance] lemma at_bot_ne_bot [nonempty α] [semilattice_inf α] : ne_bot (at_bot : filter α) := @at_top_ne_bot αᵒᵈ _ _ @[simp] lemma mem_at_top_sets [nonempty α] [semilattice_sup α] {s : set α} : s ∈ (at_top : filter α) ↔ ∃a:α, ∀b≥a, b ∈ s := at_top_basis.mem_iff.trans $ exists_congr $ λ _, exists_const _ @[simp] lemma mem_at_bot_sets [nonempty α] [semilattice_inf α] {s : set α} : s ∈ (at_bot : filter α) ↔ ∃a:α, ∀b≤a, b ∈ s := @mem_at_top_sets αᵒᵈ _ _ _ @[simp] lemma eventually_at_top [semilattice_sup α] [nonempty α] {p : α → Prop} : (∀ᶠ x in at_top, p x) ↔ (∃ a, ∀ b ≥ a, p b) := mem_at_top_sets @[simp] lemma eventually_at_bot [semilattice_inf α] [nonempty α] {p : α → Prop} : (∀ᶠ x in at_bot, p x) ↔ (∃ a, ∀ b ≤ a, p b) := mem_at_bot_sets lemma eventually_ge_at_top [preorder α] (a : α) : ∀ᶠ x in at_top, a ≤ x := mem_at_top a lemma eventually_le_at_bot [preorder α] (a : α) : ∀ᶠ x in at_bot, x ≤ a := mem_at_bot a lemma eventually_gt_at_top [preorder α] [no_max_order α] (a : α) : ∀ᶠ x in at_top, a < x := Ioi_mem_at_top a lemma eventually_ne_at_top [preorder α] [no_max_order α] (a : α) : ∀ᶠ x in at_top, x ≠ a := (eventually_gt_at_top a).mono $ λ x, ne_of_gt lemma tendsto.eventually_gt_at_top [preorder β] [no_max_order β] {f : α → β} {l : filter α} (hf : tendsto f l at_top) (c : β) : ∀ᶠ x in l, c < f x := hf.eventually (eventually_gt_at_top c) lemma tendsto.eventually_ge_at_top [preorder β] {f : α → β} {l : filter α} (hf : tendsto f l at_top) (c : β) : ∀ᶠ x in l, c ≤ f x := hf.eventually (eventually_ge_at_top c) lemma tendsto.eventually_ne_at_top [preorder β] [no_max_order β] {f : α → β} {l : filter α} (hf : tendsto f l at_top) (c : β) : ∀ᶠ x in l, f x ≠ c := hf.eventually (eventually_ne_at_top c) lemma tendsto.eventually_ne_at_top' [preorder β] [no_max_order β] {f : α → β} {l : filter α} (hf : tendsto f l at_top) (c : α) : ∀ᶠ x in l, x ≠ c := (hf.eventually_ne_at_top (f c)).mono $ λ x, ne_of_apply_ne f lemma eventually_lt_at_bot [preorder α] [no_min_order α] (a : α) : ∀ᶠ x in at_bot, x < a := Iio_mem_at_bot a lemma eventually_ne_at_bot [preorder α] [no_min_order α] (a : α) : ∀ᶠ x in at_bot, x ≠ a := (eventually_lt_at_bot a).mono $ λ x, ne_of_lt lemma tendsto.eventually_lt_at_bot [preorder β] [no_min_order β] {f : α → β} {l : filter α} (hf : tendsto f l at_bot) (c : β) : ∀ᶠ x in l, f x < c := hf.eventually (eventually_lt_at_bot c) lemma tendsto.eventually_le_at_bot [preorder β] {f : α → β} {l : filter α} (hf : tendsto f l at_bot) (c : β) : ∀ᶠ x in l, f x ≤ c := hf.eventually (eventually_le_at_bot c) lemma tendsto.eventually_ne_at_bot [preorder β] [no_min_order β] {f : α → β} {l : filter α} (hf : tendsto f l at_bot) (c : β) : ∀ᶠ x in l, f x ≠ c := hf.eventually (eventually_ne_at_bot c) lemma at_top_basis_Ioi [nonempty α] [semilattice_sup α] [no_max_order α] : (@at_top α _).has_basis (λ _, true) Ioi := at_top_basis.to_has_basis (λ a ha, ⟨a, ha, Ioi_subset_Ici_self⟩) $ λ a ha, (exists_gt a).imp $ λ b hb, ⟨ha, Ici_subset_Ioi.2 hb⟩ lemma at_top_countable_basis [nonempty α] [semilattice_sup α] [countable α] : has_countable_basis (at_top : filter α) (λ _, true) Ici := { countable := to_countable _, .. at_top_basis } lemma at_bot_countable_basis [nonempty α] [semilattice_inf α] [countable α] : has_countable_basis (at_bot : filter α) (λ _, true) Iic := { countable := to_countable _, .. at_bot_basis } @[priority 200] instance at_top.is_countably_generated [preorder α] [countable α] : (at_top : filter $ α).is_countably_generated := is_countably_generated_seq _ @[priority 200] instance at_bot.is_countably_generated [preorder α] [countable α] : (at_bot : filter $ α).is_countably_generated := is_countably_generated_seq _ lemma order_top.at_top_eq (α) [partial_order α] [order_top α] : (at_top : filter α) = pure ⊤ := le_antisymm (le_pure_iff.2 $ (eventually_ge_at_top ⊤).mono $ λ b, top_unique) (le_infi $ λ b, le_principal_iff.2 le_top) lemma order_bot.at_bot_eq (α) [partial_order α] [order_bot α] : (at_bot : filter α) = pure ⊥ := @order_top.at_top_eq αᵒᵈ _ _ @[nontriviality] lemma subsingleton.at_top_eq (α) [subsingleton α] [preorder α] : (at_top : filter α) = ⊤ := begin refine top_unique (λ s hs x, _), letI : unique α := ⟨⟨x⟩, λ y, subsingleton.elim y x⟩, rw [at_top, infi_unique, unique.default_eq x, mem_principal] at hs, exact hs left_mem_Ici end @[nontriviality] lemma subsingleton.at_bot_eq (α) [subsingleton α] [preorder α] : (at_bot : filter α) = ⊤ := @subsingleton.at_top_eq αᵒᵈ _ _ lemma tendsto_at_top_pure [partial_order α] [order_top α] (f : α → β) : tendsto f at_top (pure $ f ⊤) := (order_top.at_top_eq α).symm ▸ tendsto_pure_pure _ _ lemma tendsto_at_bot_pure [partial_order α] [order_bot α] (f : α → β) : tendsto f at_bot (pure $ f ⊥) := @tendsto_at_top_pure αᵒᵈ _ _ _ _ lemma eventually.exists_forall_of_at_top [semilattice_sup α] [nonempty α] {p : α → Prop} (h : ∀ᶠ x in at_top, p x) : ∃ a, ∀ b ≥ a, p b := eventually_at_top.mp h lemma eventually.exists_forall_of_at_bot [semilattice_inf α] [nonempty α] {p : α → Prop} (h : ∀ᶠ x in at_bot, p x) : ∃ a, ∀ b ≤ a, p b := eventually_at_bot.mp h lemma frequently_at_top [semilattice_sup α] [nonempty α] {p : α → Prop} : (∃ᶠ x in at_top, p x) ↔ (∀ a, ∃ b ≥ a, p b) := by simp [at_top_basis.frequently_iff] lemma frequently_at_bot [semilattice_inf α] [nonempty α] {p : α → Prop} : (∃ᶠ x in at_bot, p x) ↔ (∀ a, ∃ b ≤ a, p b) := @frequently_at_top αᵒᵈ _ _ _ lemma frequently_at_top' [semilattice_sup α] [nonempty α] [no_max_order α] {p : α → Prop} : (∃ᶠ x in at_top, p x) ↔ (∀ a, ∃ b > a, p b) := by simp [at_top_basis_Ioi.frequently_iff] lemma frequently_at_bot' [semilattice_inf α] [nonempty α] [no_min_order α] {p : α → Prop} : (∃ᶠ x in at_bot, p x) ↔ (∀ a, ∃ b < a, p b) := @frequently_at_top' αᵒᵈ _ _ _ _ lemma frequently.forall_exists_of_at_top [semilattice_sup α] [nonempty α] {p : α → Prop} (h : ∃ᶠ x in at_top, p x) : ∀ a, ∃ b ≥ a, p b := frequently_at_top.mp h lemma frequently.forall_exists_of_at_bot [semilattice_inf α] [nonempty α] {p : α → Prop} (h : ∃ᶠ x in at_bot, p x) : ∀ a, ∃ b ≤ a, p b := frequently_at_bot.mp h lemma map_at_top_eq [nonempty α] [semilattice_sup α] {f : α → β} : at_top.map f = (⨅a, 𝓟 $ f '' {a' | a ≤ a'}) := (at_top_basis.map _).eq_infi lemma map_at_bot_eq [nonempty α] [semilattice_inf α] {f : α → β} : at_bot.map f = (⨅a, 𝓟 $ f '' {a' | a' ≤ a}) := @map_at_top_eq αᵒᵈ _ _ _ _ lemma tendsto_at_top [preorder β] {m : α → β} {f : filter α} : tendsto m f at_top ↔ (∀b, ∀ᶠ a in f, b ≤ m a) := by simp only [at_top, tendsto_infi, tendsto_principal, mem_Ici] lemma tendsto_at_bot [preorder β] {m : α → β} {f : filter α} : tendsto m f at_bot ↔ (∀b, ∀ᶠ a in f, m a ≤ b) := @tendsto_at_top α βᵒᵈ _ m f lemma tendsto_at_top_mono' [preorder β] (l : filter α) ⦃f₁ f₂ : α → β⦄ (h : f₁ ≤ᶠ[l] f₂) : tendsto f₁ l at_top → tendsto f₂ l at_top := assume h₁, tendsto_at_top.2 $ λ b, mp_mem (tendsto_at_top.1 h₁ b) (monotone_mem (λ a ha ha₁, le_trans ha₁ ha) h) lemma tendsto_at_bot_mono' [preorder β] (l : filter α) ⦃f₁ f₂ : α → β⦄ (h : f₁ ≤ᶠ[l] f₂) : tendsto f₂ l at_bot → tendsto f₁ l at_bot := @tendsto_at_top_mono' _ βᵒᵈ _ _ _ _ h lemma tendsto_at_top_mono [preorder β] {l : filter α} {f g : α → β} (h : ∀ n, f n ≤ g n) : tendsto f l at_top → tendsto g l at_top := tendsto_at_top_mono' l $ eventually_of_forall h lemma tendsto_at_bot_mono [preorder β] {l : filter α} {f g : α → β} (h : ∀ n, f n ≤ g n) : tendsto g l at_bot → tendsto f l at_bot := @tendsto_at_top_mono _ βᵒᵈ _ _ _ _ h end filter namespace order_iso open filter variables [preorder α] [preorder β] @[simp] lemma comap_at_top (e : α ≃o β) : comap e at_top = at_top := by simp [at_top, ← e.surjective.infi_comp] @[simp] lemma comap_at_bot (e : α ≃o β) : comap e at_bot = at_bot := e.dual.comap_at_top @[simp] lemma map_at_top (e : α ≃o β) : map (e : α → β) at_top = at_top := by rw [← e.comap_at_top, map_comap_of_surjective e.surjective] @[simp] lemma map_at_bot (e : α ≃o β) : map (e : α → β) at_bot = at_bot := e.dual.map_at_top lemma tendsto_at_top (e : α ≃o β) : tendsto e at_top at_top := e.map_at_top.le lemma tendsto_at_bot (e : α ≃o β) : tendsto e at_bot at_bot := e.map_at_bot.le @[simp] lemma tendsto_at_top_iff {l : filter γ} {f : γ → α} (e : α ≃o β) : tendsto (λ x, e (f x)) l at_top ↔ tendsto f l at_top := by rw [← e.comap_at_top, tendsto_comap_iff] @[simp] lemma tendsto_at_bot_iff {l : filter γ} {f : γ → α} (e : α ≃o β) : tendsto (λ x, e (f x)) l at_bot ↔ tendsto f l at_bot := e.dual.tendsto_at_top_iff end order_iso namespace filter /-! ### Sequences -/ lemma inf_map_at_top_ne_bot_iff [semilattice_sup α] [nonempty α] {F : filter β} {u : α → β} : ne_bot (F ⊓ (map u at_top)) ↔ ∀ U ∈ F, ∀ N, ∃ n ≥ N, u n ∈ U := by simp_rw [inf_ne_bot_iff_frequently_left, frequently_map, frequently_at_top]; refl lemma inf_map_at_bot_ne_bot_iff [semilattice_inf α] [nonempty α] {F : filter β} {u : α → β} : ne_bot (F ⊓ (map u at_bot)) ↔ ∀ U ∈ F, ∀ N, ∃ n ≤ N, u n ∈ U := @inf_map_at_top_ne_bot_iff αᵒᵈ _ _ _ _ _ lemma extraction_of_frequently_at_top' {P : ℕ → Prop} (h : ∀ N, ∃ n > N, P n) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, P (φ n) := begin choose u hu using h, cases forall_and_distrib.mp hu with hu hu', exact ⟨u ∘ (nat.rec 0 (λ n v, u v)), strict_mono_nat_of_lt_succ (λ n, hu _), λ n, hu' _⟩, end lemma extraction_of_frequently_at_top {P : ℕ → Prop} (h : ∃ᶠ n in at_top, P n) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, P (φ n) := begin rw frequently_at_top' at h, exact extraction_of_frequently_at_top' h, end lemma extraction_of_eventually_at_top {P : ℕ → Prop} (h : ∀ᶠ n in at_top, P n) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, P (φ n) := extraction_of_frequently_at_top h.frequently lemma extraction_forall_of_frequently {P : ℕ → ℕ → Prop} (h : ∀ n, ∃ᶠ k in at_top, P n k) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, P n (φ n) := begin simp only [frequently_at_top'] at h, choose u hu hu' using h, use (λ n, nat.rec_on n (u 0 0) (λ n v, u (n+1) v) : ℕ → ℕ), split, { apply strict_mono_nat_of_lt_succ, intro n, apply hu }, { intros n, cases n ; simp [hu'] }, end lemma extraction_forall_of_eventually {P : ℕ → ℕ → Prop} (h : ∀ n, ∀ᶠ k in at_top, P n k) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, P n (φ n) := extraction_forall_of_frequently (λ n, (h n).frequently) lemma extraction_forall_of_eventually' {P : ℕ → ℕ → Prop} (h : ∀ n, ∃ N, ∀ k ≥ N, P n k) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, P n (φ n) := extraction_forall_of_eventually (by simp [eventually_at_top, h]) lemma exists_le_of_tendsto_at_top [semilattice_sup α] [preorder β] {u : α → β} (h : tendsto u at_top at_top) (a : α) (b : β) : ∃ a' ≥ a, b ≤ u a' := begin have : ∀ᶠ x in at_top, a ≤ x ∧ b ≤ u x := (eventually_ge_at_top a).and (h.eventually $ eventually_ge_at_top b), haveI : nonempty α := ⟨a⟩, rcases this.exists with ⟨a', ha, hb⟩, exact ⟨a', ha, hb⟩ end @[nolint ge_or_gt] -- see Note [nolint_ge] lemma exists_le_of_tendsto_at_bot [semilattice_sup α] [preorder β] {u : α → β} (h : tendsto u at_top at_bot) : ∀ a b, ∃ a' ≥ a, u a' ≤ b := @exists_le_of_tendsto_at_top _ βᵒᵈ _ _ _ h lemma exists_lt_of_tendsto_at_top [semilattice_sup α] [preorder β] [no_max_order β] {u : α → β} (h : tendsto u at_top at_top) (a : α) (b : β) : ∃ a' ≥ a, b < u a' := begin cases exists_gt b with b' hb', rcases exists_le_of_tendsto_at_top h a b' with ⟨a', ha', ha''⟩, exact ⟨a', ha', lt_of_lt_of_le hb' ha''⟩ end @[nolint ge_or_gt] -- see Note [nolint_ge] lemma exists_lt_of_tendsto_at_bot [semilattice_sup α] [preorder β] [no_min_order β] {u : α → β} (h : tendsto u at_top at_bot) : ∀ a b, ∃ a' ≥ a, u a' < b := @exists_lt_of_tendsto_at_top _ βᵒᵈ _ _ _ _ h /-- If `u` is a sequence which is unbounded above, then after any point, it reaches a value strictly greater than all previous values. -/ lemma high_scores [linear_order β] [no_max_order β] {u : ℕ → β} (hu : tendsto u at_top at_top) : ∀ N, ∃ n ≥ N, ∀ k < n, u k < u n := begin intros N, obtain ⟨k : ℕ, hkn : k ≤ N, hku : ∀ l ≤ N, u l ≤ u k⟩ : ∃ k ≤ N, ∀ l ≤ N, u l ≤ u k, from exists_max_image _ u (finite_le_nat N) ⟨N, le_refl N⟩, have ex : ∃ n ≥ N, u k < u n, from exists_lt_of_tendsto_at_top hu _ _, obtain ⟨n : ℕ, hnN : n ≥ N, hnk : u k < u n, hn_min : ∀ m, m < n → N ≤ m → u m ≤ u k⟩ : ∃ n ≥ N, u k < u n ∧ ∀ m, m < n → N ≤ m → u m ≤ u k, { rcases nat.find_x ex with ⟨n, ⟨hnN, hnk⟩, hn_min⟩, push_neg at hn_min, exact ⟨n, hnN, hnk, hn_min⟩ }, use [n, hnN], rintros (l : ℕ) (hl : l < n), have hlk : u l ≤ u k, { cases (le_total l N : l ≤ N ∨ N ≤ l) with H H, { exact hku l H }, { exact hn_min l hl H } }, calc u l ≤ u k : hlk ... < u n : hnk end /-- If `u` is a sequence which is unbounded below, then after any point, it reaches a value strictly smaller than all previous values. -/ @[nolint ge_or_gt] -- see Note [nolint_ge] lemma low_scores [linear_order β] [no_min_order β] {u : ℕ → β} (hu : tendsto u at_top at_bot) : ∀ N, ∃ n ≥ N, ∀ k < n, u n < u k := @high_scores βᵒᵈ _ _ _ hu /-- If `u` is a sequence which is unbounded above, then it `frequently` reaches a value strictly greater than all previous values. -/ lemma frequently_high_scores [linear_order β] [no_max_order β] {u : ℕ → β} (hu : tendsto u at_top at_top) : ∃ᶠ n in at_top, ∀ k < n, u k < u n := by simpa [frequently_at_top] using high_scores hu /-- If `u` is a sequence which is unbounded below, then it `frequently` reaches a value strictly smaller than all previous values. -/ lemma frequently_low_scores [linear_order β] [no_min_order β] {u : ℕ → β} (hu : tendsto u at_top at_bot) : ∃ᶠ n in at_top, ∀ k < n, u n < u k := @frequently_high_scores βᵒᵈ _ _ _ hu lemma strict_mono_subseq_of_tendsto_at_top {β : Type*} [linear_order β] [no_max_order β] {u : ℕ → β} (hu : tendsto u at_top at_top) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ strict_mono (u ∘ φ) := let ⟨φ, h, h'⟩ := extraction_of_frequently_at_top (frequently_high_scores hu) in ⟨φ, h, λ n m hnm, h' m _ (h hnm)⟩ lemma strict_mono_subseq_of_id_le {u : ℕ → ℕ} (hu : ∀ n, n ≤ u n) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ strict_mono (u ∘ φ) := strict_mono_subseq_of_tendsto_at_top (tendsto_at_top_mono hu tendsto_id) lemma _root_.strict_mono.tendsto_at_top {φ : ℕ → ℕ} (h : strict_mono φ) : tendsto φ at_top at_top := tendsto_at_top_mono h.id_le tendsto_id section ordered_add_comm_monoid variables [ordered_add_comm_monoid β] {l : filter α} {f g : α → β} lemma tendsto_at_top_add_nonneg_left' (hf : ∀ᶠ x in l, 0 ≤ f x) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_mono' l (hf.mono (λ x, le_add_of_nonneg_left)) hg lemma tendsto_at_bot_add_nonpos_left' (hf : ∀ᶠ x in l, f x ≤ 0) (hg : tendsto g l at_bot) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_nonneg_left' _ βᵒᵈ _ _ _ _ hf hg lemma tendsto_at_top_add_nonneg_left (hf : ∀ x, 0 ≤ f x) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_nonneg_left' (eventually_of_forall hf) hg lemma tendsto_at_bot_add_nonpos_left (hf : ∀ x, f x ≤ 0) (hg : tendsto g l at_bot) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_nonneg_left _ βᵒᵈ _ _ _ _ hf hg lemma tendsto_at_top_add_nonneg_right' (hf : tendsto f l at_top) (hg : ∀ᶠ x in l, 0 ≤ g x) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_mono' l (monotone_mem (λ x, le_add_of_nonneg_right) hg) hf lemma tendsto_at_bot_add_nonpos_right' (hf : tendsto f l at_bot) (hg : ∀ᶠ x in l, g x ≤ 0) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_nonneg_right' _ βᵒᵈ _ _ _ _ hf hg lemma tendsto_at_top_add_nonneg_right (hf : tendsto f l at_top) (hg : ∀ x, 0 ≤ g x) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_nonneg_right' hf (eventually_of_forall hg) lemma tendsto_at_bot_add_nonpos_right (hf : tendsto f l at_bot) (hg : ∀ x, g x ≤ 0) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_nonneg_right _ βᵒᵈ _ _ _ _ hf hg lemma tendsto_at_top_add (hf : tendsto f l at_top) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_nonneg_left' (tendsto_at_top.mp hf 0) hg lemma tendsto_at_bot_add (hf : tendsto f l at_bot) (hg : tendsto g l at_bot) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add _ βᵒᵈ _ _ _ _ hf hg lemma tendsto.nsmul_at_top (hf : tendsto f l at_top) {n : ℕ} (hn : 0 < n) : tendsto (λ x, n • f x) l at_top := tendsto_at_top.2 $ λ y, (tendsto_at_top.1 hf y).mp $ (tendsto_at_top.1 hf 0).mono $ λ x h₀ hy, calc y ≤ f x : hy ... = 1 • f x : (one_nsmul _).symm ... ≤ n • f x : nsmul_le_nsmul h₀ hn lemma tendsto.nsmul_at_bot (hf : tendsto f l at_bot) {n : ℕ} (hn : 0 < n) : tendsto (λ x, n • f x) l at_bot := @tendsto.nsmul_at_top α βᵒᵈ _ l f hf n hn lemma tendsto_bit0_at_top : tendsto bit0 (at_top : filter β) at_top := tendsto_at_top_add tendsto_id tendsto_id lemma tendsto_bit0_at_bot : tendsto bit0 (at_bot : filter β) at_bot := tendsto_at_bot_add tendsto_id tendsto_id end ordered_add_comm_monoid section ordered_cancel_add_comm_monoid variables [ordered_cancel_add_comm_monoid β] {l : filter α} {f g : α → β} lemma tendsto_at_top_of_add_const_left (C : β) (hf : tendsto (λ x, C + f x) l at_top) : tendsto f l at_top := tendsto_at_top.2 $ assume b, (tendsto_at_top.1 hf (C + b)).mono (λ x, le_of_add_le_add_left) lemma tendsto_at_bot_of_add_const_left (C : β) (hf : tendsto (λ x, C + f x) l at_bot) : tendsto f l at_bot := @tendsto_at_top_of_add_const_left _ βᵒᵈ _ _ _ C hf lemma tendsto_at_top_of_add_const_right (C : β) (hf : tendsto (λ x, f x + C) l at_top) : tendsto f l at_top := tendsto_at_top.2 $ assume b, (tendsto_at_top.1 hf (b + C)).mono (λ x, le_of_add_le_add_right) lemma tendsto_at_bot_of_add_const_right (C : β) (hf : tendsto (λ x, f x + C) l at_bot) : tendsto f l at_bot := @tendsto_at_top_of_add_const_right _ βᵒᵈ _ _ _ C hf lemma tendsto_at_top_of_add_bdd_above_left' (C) (hC : ∀ᶠ x in l, f x ≤ C) (h : tendsto (λ x, f x + g x) l at_top) : tendsto g l at_top := tendsto_at_top_of_add_const_left C (tendsto_at_top_mono' l (hC.mono (λ x hx, add_le_add_right hx (g x))) h) lemma tendsto_at_bot_of_add_bdd_below_left' (C) (hC : ∀ᶠ x in l, C ≤ f x) (h : tendsto (λ x, f x + g x) l at_bot) : tendsto g l at_bot := @tendsto_at_top_of_add_bdd_above_left' _ βᵒᵈ _ _ _ _ C hC h lemma tendsto_at_top_of_add_bdd_above_left (C) (hC : ∀ x, f x ≤ C) : tendsto (λ x, f x + g x) l at_top → tendsto g l at_top := tendsto_at_top_of_add_bdd_above_left' C (univ_mem' hC) lemma tendsto_at_bot_of_add_bdd_below_left (C) (hC : ∀ x, C ≤ f x) : tendsto (λ x, f x + g x) l at_bot → tendsto g l at_bot := @tendsto_at_top_of_add_bdd_above_left _ βᵒᵈ _ _ _ _ C hC lemma tendsto_at_top_of_add_bdd_above_right' (C) (hC : ∀ᶠ x in l, g x ≤ C) (h : tendsto (λ x, f x + g x) l at_top) : tendsto f l at_top := tendsto_at_top_of_add_const_right C (tendsto_at_top_mono' l (hC.mono (λ x hx, add_le_add_left hx (f x))) h) lemma tendsto_at_bot_of_add_bdd_below_right' (C) (hC : ∀ᶠ x in l, C ≤ g x) (h : tendsto (λ x, f x + g x) l at_bot) : tendsto f l at_bot := @tendsto_at_top_of_add_bdd_above_right' _ βᵒᵈ _ _ _ _ C hC h lemma tendsto_at_top_of_add_bdd_above_right (C) (hC : ∀ x, g x ≤ C) : tendsto (λ x, f x + g x) l at_top → tendsto f l at_top := tendsto_at_top_of_add_bdd_above_right' C (univ_mem' hC) lemma tendsto_at_bot_of_add_bdd_below_right (C) (hC : ∀ x, C ≤ g x) : tendsto (λ x, f x + g x) l at_bot → tendsto f l at_bot := @tendsto_at_top_of_add_bdd_above_right _ βᵒᵈ _ _ _ _ C hC end ordered_cancel_add_comm_monoid section ordered_group variables [ordered_add_comm_group β] (l : filter α) {f g : α → β} lemma tendsto_at_top_add_left_of_le' (C : β) (hf : ∀ᶠ x in l, C ≤ f x) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := @tendsto_at_top_of_add_bdd_above_left' _ _ _ l (λ x, -(f x)) (λ x, f x + g x) (-C) (by simpa) (by simpa) lemma tendsto_at_bot_add_left_of_ge' (C : β) (hf : ∀ᶠ x in l, f x ≤ C) (hg : tendsto g l at_bot) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_left_of_le' _ βᵒᵈ _ _ _ _ C hf hg lemma tendsto_at_top_add_left_of_le (C : β) (hf : ∀ x, C ≤ f x) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_left_of_le' l C (univ_mem' hf) hg lemma tendsto_at_bot_add_left_of_ge (C : β) (hf : ∀ x, f x ≤ C) (hg : tendsto g l at_bot) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_left_of_le _ βᵒᵈ _ _ _ _ C hf hg lemma tendsto_at_top_add_right_of_le' (C : β) (hf : tendsto f l at_top) (hg : ∀ᶠ x in l, C ≤ g x) : tendsto (λ x, f x + g x) l at_top := @tendsto_at_top_of_add_bdd_above_right' _ _ _ l (λ x, f x + g x) (λ x, -(g x)) (-C) (by simp [hg]) (by simp [hf]) lemma tendsto_at_bot_add_right_of_ge' (C : β) (hf : tendsto f l at_bot) (hg : ∀ᶠ x in l, g x ≤ C) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_right_of_le' _ βᵒᵈ _ _ _ _ C hf hg lemma tendsto_at_top_add_right_of_le (C : β) (hf : tendsto f l at_top) (hg : ∀ x, C ≤ g x) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_right_of_le' l C hf (univ_mem' hg) lemma tendsto_at_bot_add_right_of_ge (C : β) (hf : tendsto f l at_bot) (hg : ∀ x, g x ≤ C) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_right_of_le _ βᵒᵈ _ _ _ _ C hf hg lemma tendsto_at_top_add_const_left (C : β) (hf : tendsto f l at_top) : tendsto (λ x, C + f x) l at_top := tendsto_at_top_add_left_of_le' l C (univ_mem' $ λ _, le_refl C) hf lemma tendsto_at_bot_add_const_left (C : β) (hf : tendsto f l at_bot) : tendsto (λ x, C + f x) l at_bot := @tendsto_at_top_add_const_left _ βᵒᵈ _ _ _ C hf lemma tendsto_at_top_add_const_right (C : β) (hf : tendsto f l at_top) : tendsto (λ x, f x + C) l at_top := tendsto_at_top_add_right_of_le' l C hf (univ_mem' $ λ _, le_refl C) lemma tendsto_at_bot_add_const_right (C : β) (hf : tendsto f l at_bot) : tendsto (λ x, f x + C) l at_bot := @tendsto_at_top_add_const_right _ βᵒᵈ _ _ _ C hf lemma map_neg_at_bot : map (has_neg.neg : β → β) at_bot = at_top := (order_iso.neg β).map_at_bot lemma map_neg_at_top : map (has_neg.neg : β → β) at_top = at_bot := (order_iso.neg β).map_at_top @[simp] lemma comap_neg_at_bot : comap (has_neg.neg : β → β) at_bot = at_top := (order_iso.neg β).comap_at_top @[simp] lemma comap_neg_at_top : comap (has_neg.neg : β → β) at_top = at_bot := (order_iso.neg β).comap_at_bot lemma tendsto_neg_at_top_at_bot : tendsto (has_neg.neg : β → β) at_top at_bot := (order_iso.neg β).tendsto_at_top lemma tendsto_neg_at_bot_at_top : tendsto (has_neg.neg : β → β) at_bot at_top := @tendsto_neg_at_top_at_bot βᵒᵈ _ variable {l} @[simp] lemma tendsto_neg_at_top_iff : tendsto (λ x, -f x) l at_top ↔ tendsto f l at_bot := (order_iso.neg β).tendsto_at_bot_iff @[simp] lemma tendsto_neg_at_bot_iff : tendsto (λ x, -f x) l at_bot ↔ tendsto f l at_top := (order_iso.neg β).tendsto_at_top_iff end ordered_group section strict_ordered_semiring variables [strict_ordered_semiring α] {l : filter β} {f g : β → α} lemma tendsto_bit1_at_top : tendsto bit1 (at_top : filter α) at_top := tendsto_at_top_add_nonneg_right tendsto_bit0_at_top (λ _, zero_le_one) lemma tendsto.at_top_mul_at_top (hf : tendsto f l at_top) (hg : tendsto g l at_top) : tendsto (λ x, f x * g x) l at_top := begin refine tendsto_at_top_mono' _ _ hg, filter_upwards [hg.eventually (eventually_ge_at_top 0), hf.eventually (eventually_ge_at_top 1)] with _ using le_mul_of_one_le_left, end lemma tendsto_mul_self_at_top : tendsto (λ x : α, x * x) at_top at_top := tendsto_id.at_top_mul_at_top tendsto_id /-- The monomial function `x^n` tends to `+∞` at `+∞` for any positive natural `n`. A version for positive real powers exists as `tendsto_rpow_at_top`. -/ lemma tendsto_pow_at_top {n : ℕ} (hn : n ≠ 0) : tendsto (λ x : α, x ^ n) at_top at_top := tendsto_at_top_mono' _ ((eventually_ge_at_top 1).mono $ λ x hx, le_self_pow hx hn) tendsto_id end strict_ordered_semiring lemma zero_pow_eventually_eq [monoid_with_zero α] : (λ n : ℕ, (0 : α) ^ n) =ᶠ[at_top] (λ n, 0) := eventually_at_top.2 ⟨1, λ n hn, zero_pow (zero_lt_one.trans_le hn)⟩ section strict_ordered_ring variables [strict_ordered_ring α] {l : filter β} {f g : β → α} lemma tendsto.at_top_mul_at_bot (hf : tendsto f l at_top) (hg : tendsto g l at_bot) : tendsto (λ x, f x * g x) l at_bot := have _ := (hf.at_top_mul_at_top $ tendsto_neg_at_bot_at_top.comp hg), by simpa only [(∘), neg_mul_eq_mul_neg, neg_neg] using tendsto_neg_at_top_at_bot.comp this lemma tendsto.at_bot_mul_at_top (hf : tendsto f l at_bot) (hg : tendsto g l at_top) : tendsto (λ x, f x * g x) l at_bot := have tendsto (λ x, (-f x) * g x) l at_top := ( (tendsto_neg_at_bot_at_top.comp hf).at_top_mul_at_top hg), by simpa only [(∘), neg_mul_eq_neg_mul, neg_neg] using tendsto_neg_at_top_at_bot.comp this lemma tendsto.at_bot_mul_at_bot (hf : tendsto f l at_bot) (hg : tendsto g l at_bot) : tendsto (λ x, f x * g x) l at_top := have tendsto (λ x, (-f x) * (-g x)) l at_top := (tendsto_neg_at_bot_at_top.comp hf).at_top_mul_at_top (tendsto_neg_at_bot_at_top.comp hg), by simpa only [neg_mul_neg] using this end strict_ordered_ring section linear_ordered_add_comm_group variables [linear_ordered_add_comm_group α] /-- $\lim_{x\to+\infty}|x|=+\infty$ -/ lemma tendsto_abs_at_top_at_top : tendsto (abs : α → α) at_top at_top := tendsto_at_top_mono le_abs_self tendsto_id /-- $\lim_{x\to-\infty}|x|=+\infty$ -/ lemma tendsto_abs_at_bot_at_top : tendsto (abs : α → α) at_bot at_top := tendsto_at_top_mono neg_le_abs_self tendsto_neg_at_bot_at_top @[simp] lemma comap_abs_at_top : comap (abs : α → α) at_top = at_bot ⊔ at_top := begin refine le_antisymm (((at_top_basis.comap _).le_basis_iff (at_bot_basis.sup at_top_basis)).2 _) (sup_le tendsto_abs_at_bot_at_top.le_comap tendsto_abs_at_top_at_top.le_comap), rintro ⟨a, b⟩ -, refine ⟨max (-a) b, trivial, λ x hx, _⟩, rw [mem_preimage, mem_Ici, le_abs', max_le_iff, ← min_neg_neg, le_min_iff, neg_neg] at hx, exact hx.imp and.left and.right end end linear_ordered_add_comm_group section linear_ordered_semiring variables [linear_ordered_semiring α] {l : filter β} {f : β → α} lemma tendsto.at_top_of_const_mul {c : α} (hc : 0 < c) (hf : tendsto (λ x, c * f x) l at_top) : tendsto f l at_top := tendsto_at_top.2 $ λ b, (tendsto_at_top.1 hf (c * b)).mono $ λ x hx, le_of_mul_le_mul_left hx hc lemma tendsto.at_top_of_mul_const {c : α} (hc : 0 < c) (hf : tendsto (λ x, f x * c) l at_top) : tendsto f l at_top := tendsto_at_top.2 $ λ b, (tendsto_at_top.1 hf (b * c)).mono $ λ x hx, le_of_mul_le_mul_right hx hc @[simp] lemma tendsto_pow_at_top_iff {n : ℕ} : tendsto (λ x : α, x ^ n) at_top at_top ↔ n ≠ 0 := ⟨λ h hn, by simpa only [hn, pow_zero, not_tendsto_const_at_top] using h, tendsto_pow_at_top⟩ end linear_ordered_semiring lemma nonneg_of_eventually_pow_nonneg [linear_ordered_ring α] {a : α} (h : ∀ᶠ n in at_top, 0 ≤ a ^ (n : ℕ)) : 0 ≤ a := let ⟨n, hn⟩ := (tendsto_bit1_at_top.eventually h).exists in pow_bit1_nonneg_iff.1 hn lemma not_tendsto_pow_at_top_at_bot [linear_ordered_ring α] : ∀ {n : ℕ}, ¬tendsto (λ x : α, x ^ n) at_top at_bot | 0 := by simp [not_tendsto_const_at_bot] | (n + 1) := (tendsto_pow_at_top n.succ_ne_zero).not_tendsto disjoint_at_top_at_bot section linear_ordered_semifield variables [linear_ordered_semifield α] {l : filter β} {f : β → α} {r c : α} {n : ℕ} /-! ### Multiplication by constant: iff lemmas -/ /-- If `r` is a positive constant, then `λ x, r * f x` tends to infinity along a filter if and only if `f` tends to infinity along the same filter. -/ lemma tendsto_const_mul_at_top_of_pos (hr : 0 < r) : tendsto (λ x, r * f x) l at_top ↔ tendsto f l at_top := ⟨λ h, h.at_top_of_const_mul hr, λ h, tendsto.at_top_of_const_mul (inv_pos.2 hr) $ by simpa only [inv_mul_cancel_left₀ hr.ne']⟩ /-- If `r` is a positive constant, then `λ x, f x * r` tends to infinity along a filter if and only if `f` tends to infinity along the same filter. -/ lemma tendsto_mul_const_at_top_of_pos (hr : 0 < r) : tendsto (λ x, f x * r) l at_top ↔ tendsto f l at_top := by simpa only [mul_comm] using tendsto_const_mul_at_top_of_pos hr /-- If `f` tends to infinity along a nontrivial filter `l`, then `λ x, r * f x` tends to infinity if and only if `0 < r. `-/ lemma tendsto_const_mul_at_top_iff_pos [ne_bot l] (h : tendsto f l at_top) : tendsto (λ x, r * f x) l at_top ↔ 0 < r := begin refine ⟨λ hrf, not_le.mp $ λ hr, _, λ hr, (tendsto_const_mul_at_top_of_pos hr).mpr h⟩, rcases ((h.eventually_ge_at_top 0).and (hrf.eventually_gt_at_top 0)).exists with ⟨x, hx, hrx⟩, exact (mul_nonpos_of_nonpos_of_nonneg hr hx).not_lt hrx end /-- If `f` tends to infinity along a nontrivial filter `l`, then `λ x, f x * r` tends to infinity if and only if `0 < r. `-/ lemma tendsto_mul_const_at_top_iff_pos [ne_bot l] (h : tendsto f l at_top) : tendsto (λ x, f x * r) l at_top ↔ 0 < r := by simp only [mul_comm _ r, tendsto_const_mul_at_top_iff_pos h] /-- If a function tends to infinity along a filter, then this function multiplied by a positive constant (on the left) also tends to infinity. For a version working in `ℕ` or `ℤ`, use `filter.tendsto.const_mul_at_top'` instead. -/ lemma tendsto.const_mul_at_top (hr : 0 < r) (hf : tendsto f l at_top) : tendsto (λx, r * f x) l at_top := (tendsto_const_mul_at_top_of_pos hr).2 hf /-- If a function tends to infinity along a filter, then this function multiplied by a positive constant (on the right) also tends to infinity. For a version working in `ℕ` or `ℤ`, use `filter.tendsto.at_top_mul_const'` instead. -/ lemma tendsto.at_top_mul_const (hr : 0 < r) (hf : tendsto f l at_top) : tendsto (λx, f x * r) l at_top := (tendsto_mul_const_at_top_of_pos hr).2 hf /-- If a function tends to infinity along a filter, then this function divided by a positive constant also tends to infinity. -/ lemma tendsto.at_top_div_const (hr : 0 < r) (hf : tendsto f l at_top) : tendsto (λx, f x / r) l at_top := by simpa only [div_eq_mul_inv] using hf.at_top_mul_const (inv_pos.2 hr) lemma tendsto_const_mul_pow_at_top (hn : n ≠ 0) (hc : 0 < c) : tendsto (λ x, c * x^n) at_top at_top := tendsto.const_mul_at_top hc (tendsto_pow_at_top hn) lemma tendsto_const_mul_pow_at_top_iff : tendsto (λ x, c * x^n) at_top at_top ↔ n ≠ 0 ∧ 0 < c := begin refine ⟨λ h, ⟨_, _⟩, λ h, tendsto_const_mul_pow_at_top h.1 h.2⟩, { rintro rfl, simpa only [pow_zero, not_tendsto_const_at_top] using h }, { rcases ((h.eventually_gt_at_top 0).and (eventually_ge_at_top 0)).exists with ⟨k, hck, hk⟩, exact pos_of_mul_pos_left hck (pow_nonneg hk _) }, end end linear_ordered_semifield section linear_ordered_field variables [linear_ordered_field α] {l : filter β} {f : β → α} {r : α} /-- If `r` is a positive constant, then `λ x, r * f x` tends to negative infinity along a filter if and only if `f` tends to negative infinity along the same filter. -/ lemma tendsto_const_mul_at_bot_of_pos (hr : 0 < r) : tendsto (λ x, r * f x) l at_bot ↔ tendsto f l at_bot := by simpa only [← mul_neg, ← tendsto_neg_at_top_iff] using tendsto_const_mul_at_top_of_pos hr /-- If `r` is a positive constant, then `λ x, f x * r` tends to negative infinity along a filter if and only if `f` tends to negative infinity along the same filter. -/ lemma tendsto_mul_const_at_bot_of_pos (hr : 0 < r) : tendsto (λ x, f x * r) l at_bot ↔ tendsto f l at_bot := by simpa only [mul_comm] using tendsto_const_mul_at_bot_of_pos hr /-- If `r` is a negative constant, then `λ x, r * f x` tends to infinity along a filter if and only if `f` tends to negative infinity along the same filter. -/ lemma tendsto_const_mul_at_top_of_neg (hr : r < 0) : tendsto (λ x, r * f x) l at_top ↔ tendsto f l at_bot := by simpa only [neg_mul, tendsto_neg_at_bot_iff] using tendsto_const_mul_at_bot_of_pos (neg_pos.2 hr) /-- If `r` is a negative constant, then `λ x, f x * r` tends to infinity along a filter if and only if `f` tends to negative infinity along the same filter. -/ lemma tendsto_mul_const_at_top_of_neg (hr : r < 0) : tendsto (λ x, f x * r) l at_top ↔ tendsto f l at_bot := by simpa only [mul_comm] using tendsto_const_mul_at_top_of_neg hr /-- If `r` is a negative constant, then `λ x, r * f x` tends to negative infinity along a filter if and only if `f` tends to infinity along the same filter. -/ lemma tendsto_const_mul_at_bot_of_neg (hr : r < 0) : tendsto (λ x, r * f x) l at_bot ↔ tendsto f l at_top := by simpa only [neg_mul, tendsto_neg_at_top_iff] using tendsto_const_mul_at_top_of_pos (neg_pos.2 hr) /-- If `r` is a negative constant, then `λ x, f x * r` tends to negative infinity along a filter if and only if `f` tends to infinity along the same filter. -/ lemma tendsto_mul_const_at_bot_of_neg (hr : r < 0) : tendsto (λ x, f x * r) l at_bot ↔ tendsto f l at_top := by simpa only [mul_comm] using tendsto_const_mul_at_bot_of_neg hr /-- The function `λ x, r * f x` tends to infinity along a nontrivial filter if and only if `r > 0` and `f` tends to infinity or `r < 0` and `f` tends to negative infinity. -/ lemma tendsto_const_mul_at_top_iff [ne_bot l] : tendsto (λ x, r * f x) l at_top ↔ 0 < r ∧ tendsto f l at_top ∨ r < 0 ∧ tendsto f l at_bot := begin rcases lt_trichotomy r 0 with hr|rfl|hr, { simp [hr, hr.not_lt, tendsto_const_mul_at_top_of_neg] }, { simp [not_tendsto_const_at_top] }, { simp [hr, hr.not_lt, tendsto_const_mul_at_top_of_pos] } end /-- The function `λ x, f x * r` tends to infinity along a nontrivial filter if and only if `r > 0` and `f` tends to infinity or `r < 0` and `f` tends to negative infinity. -/ lemma tendsto_mul_const_at_top_iff [ne_bot l] : tendsto (λ x, f x * r) l at_top ↔ 0 < r ∧ tendsto f l at_top ∨ r < 0 ∧ tendsto f l at_bot := by simp only [mul_comm _ r, tendsto_const_mul_at_top_iff] /-- The function `λ x, r * f x` tends to negative infinity along a nontrivial filter if and only if `r > 0` and `f` tends to negative infinity or `r < 0` and `f` tends to infinity. -/ lemma tendsto_const_mul_at_bot_iff [ne_bot l] : tendsto (λ x, r * f x) l at_bot ↔ 0 < r ∧ tendsto f l at_bot ∨ r < 0 ∧ tendsto f l at_top := by simp only [← tendsto_neg_at_top_iff, ← mul_neg, tendsto_const_mul_at_top_iff, neg_neg] /-- The function `λ x, f x * r` tends to negative infinity along a nontrivial filter if and only if `r > 0` and `f` tends to negative infinity or `r < 0` and `f` tends to infinity. -/ lemma tendsto_mul_const_at_bot_iff [ne_bot l] : tendsto (λ x, f x * r) l at_bot ↔ 0 < r ∧ tendsto f l at_bot ∨ r < 0 ∧ tendsto f l at_top := by simp only [mul_comm _ r, tendsto_const_mul_at_bot_iff] /-- If `f` tends to negative infinity along a nontrivial filter `l`, then `λ x, r * f x` tends to infinity if and only if `r < 0. `-/ lemma tendsto_const_mul_at_top_iff_neg [ne_bot l] (h : tendsto f l at_bot) : tendsto (λ x, r * f x) l at_top ↔ r < 0 := by simp [tendsto_const_mul_at_top_iff, h, h.not_tendsto disjoint_at_bot_at_top] /-- If `f` tends to negative infinity along a nontrivial filter `l`, then `λ x, f x * r` tends to infinity if and only if `r < 0. `-/ lemma tendsto_mul_const_at_top_iff_neg [ne_bot l] (h : tendsto f l at_bot) : tendsto (λ x, f x * r) l at_top ↔ r < 0 := by simp only [mul_comm _ r, tendsto_const_mul_at_top_iff_neg h] /-- If `f` tends to negative infinity along a nontrivial filter `l`, then `λ x, r * f x` tends to negative infinity if and only if `0 < r. `-/ lemma tendsto_const_mul_at_bot_iff_pos [ne_bot l] (h : tendsto f l at_bot) : tendsto (λ x, r * f x) l at_bot ↔ 0 < r := by simp [tendsto_const_mul_at_bot_iff, h, h.not_tendsto disjoint_at_bot_at_top] /-- If `f` tends to negative infinity along a nontrivial filter `l`, then `λ x, f x * r` tends to negative infinity if and only if `0 < r. `-/ lemma tendsto_mul_const_at_bot_iff_pos [ne_bot l] (h : tendsto f l at_bot) : tendsto (λ x, f x * r) l at_bot ↔ 0 < r := by simp only [mul_comm _ r, tendsto_const_mul_at_bot_iff_pos h] /-- If `f` tends to infinity along a nontrivial filter `l`, then `λ x, r * f x` tends to negative infinity if and only if `r < 0. `-/ lemma tendsto_const_mul_at_bot_iff_neg [ne_bot l] (h : tendsto f l at_top) : tendsto (λ x, r * f x) l at_bot ↔ r < 0 := by simp [tendsto_const_mul_at_bot_iff, h, h.not_tendsto disjoint_at_top_at_bot] /-- If `f` tends to infinity along a nontrivial filter `l`, then `λ x, f x * r` tends to negative infinity if and only if `r < 0. `-/ lemma tendsto_mul_const_at_bot_iff_neg [ne_bot l] (h : tendsto f l at_top) : tendsto (λ x, f x * r) l at_bot ↔ r < 0 := by simp only [mul_comm _ r, tendsto_const_mul_at_bot_iff_neg h] /-- If a function tends to infinity along a filter, then this function multiplied by a negative constant (on the left) tends to negative infinity. -/ lemma tendsto.neg_const_mul_at_top (hr : r < 0) (hf : tendsto f l at_top) : tendsto (λ x, r * f x) l at_bot := (tendsto_const_mul_at_bot_of_neg hr).2 hf /-- If a function tends to infinity along a filter, then this function multiplied by a negative constant (on the right) tends to negative infinity. -/ lemma tendsto.at_top_mul_neg_const (hr : r < 0) (hf : tendsto f l at_top) : tendsto (λ x, f x * r) l at_bot := (tendsto_mul_const_at_bot_of_neg hr).2 hf /-- If a function tends to negative infinity along a filter, then this function multiplied by a positive constant (on the left) also tends to negative infinity. -/ lemma tendsto.const_mul_at_bot (hr : 0 < r) (hf : tendsto f l at_bot) : tendsto (λx, r * f x) l at_bot := (tendsto_const_mul_at_bot_of_pos hr).2 hf /-- If a function tends to negative infinity along a filter, then this function multiplied by a positive constant (on the right) also tends to negative infinity. -/ lemma tendsto.at_bot_mul_const (hr : 0 < r) (hf : tendsto f l at_bot) : tendsto (λx, f x * r) l at_bot := (tendsto_mul_const_at_bot_of_pos hr).2 hf /-- If a function tends to negative infinity along a filter, then this function divided by a positive constant also tends to negative infinity. -/ lemma tendsto.at_bot_div_const (hr : 0 < r) (hf : tendsto f l at_bot) : tendsto (λx, f x / r) l at_bot := by simpa only [div_eq_mul_inv] using hf.at_bot_mul_const (inv_pos.2 hr) /-- If a function tends to negative infinity along a filter, then this function multiplied by a negative constant (on the left) tends to positive infinity. -/ lemma tendsto.neg_const_mul_at_bot (hr : r < 0) (hf : tendsto f l at_bot) : tendsto (λ x, r * f x) l at_top := (tendsto_const_mul_at_top_of_neg hr).2 hf /-- If a function tends to negative infinity along a filter, then this function multiplied by a negative constant (on the right) tends to positive infinity. -/ lemma tendsto.at_bot_mul_neg_const (hr : r < 0) (hf : tendsto f l at_bot) : tendsto (λ x, f x * r) l at_top := (tendsto_mul_const_at_top_of_neg hr).2 hf lemma tendsto_neg_const_mul_pow_at_top {c : α} {n : ℕ} (hn : n ≠ 0) (hc : c < 0) : tendsto (λ x, c * x^n) at_top at_bot := tendsto.neg_const_mul_at_top hc (tendsto_pow_at_top hn) lemma tendsto_const_mul_pow_at_bot_iff {c : α} {n : ℕ} : tendsto (λ x, c * x^n) at_top at_bot ↔ n ≠ 0 ∧ c < 0 := by simp only [← tendsto_neg_at_top_iff, ← neg_mul, tendsto_const_mul_pow_at_top_iff, neg_pos] end linear_ordered_field open_locale filter lemma tendsto_at_top' [nonempty α] [semilattice_sup α] {f : α → β} {l : filter β} : tendsto f at_top l ↔ (∀s ∈ l, ∃a, ∀b≥a, f b ∈ s) := by simp only [tendsto_def, mem_at_top_sets]; refl lemma tendsto_at_bot' [nonempty α] [semilattice_inf α] {f : α → β} {l : filter β} : tendsto f at_bot l ↔ (∀s ∈ l, ∃a, ∀b≤a, f b ∈ s) := @tendsto_at_top' αᵒᵈ _ _ _ _ _ theorem tendsto_at_top_principal [nonempty β] [semilattice_sup β] {f : β → α} {s : set α} : tendsto f at_top (𝓟 s) ↔ ∃N, ∀n≥N, f n ∈ s := by rw [tendsto_iff_comap, comap_principal, le_principal_iff, mem_at_top_sets]; refl theorem tendsto_at_bot_principal [nonempty β] [semilattice_inf β] {f : β → α} {s : set α} : tendsto f at_bot (𝓟 s) ↔ ∃N, ∀n≤N, f n ∈ s := @tendsto_at_top_principal _ βᵒᵈ _ _ _ _ /-- A function `f` grows to `+∞` independent of an order-preserving embedding `e`. -/ lemma tendsto_at_top_at_top [nonempty α] [semilattice_sup α] [preorder β] {f : α → β} : tendsto f at_top at_top ↔ ∀ b : β, ∃ i : α, ∀ a : α, i ≤ a → b ≤ f a := iff.trans tendsto_infi $ forall_congr $ assume b, tendsto_at_top_principal lemma tendsto_at_top_at_bot [nonempty α] [semilattice_sup α] [preorder β] {f : α → β} : tendsto f at_top at_bot ↔ ∀ (b : β), ∃ (i : α), ∀ (a : α), i ≤ a → f a ≤ b := @tendsto_at_top_at_top α βᵒᵈ _ _ _ f lemma tendsto_at_bot_at_top [nonempty α] [semilattice_inf α] [preorder β] {f : α → β} : tendsto f at_bot at_top ↔ ∀ (b : β), ∃ (i : α), ∀ (a : α), a ≤ i → b ≤ f a := @tendsto_at_top_at_top αᵒᵈ β _ _ _ f lemma tendsto_at_bot_at_bot [nonempty α] [semilattice_inf α] [preorder β] {f : α → β} : tendsto f at_bot at_bot ↔ ∀ (b : β), ∃ (i : α), ∀ (a : α), a ≤ i → f a ≤ b := @tendsto_at_top_at_top αᵒᵈ βᵒᵈ _ _ _ f lemma tendsto_at_top_at_top_of_monotone [preorder α] [preorder β] {f : α → β} (hf : monotone f) (h : ∀ b, ∃ a, b ≤ f a) : tendsto f at_top at_top := tendsto_infi.2 $ λ b, tendsto_principal.2 $ let ⟨a, ha⟩ := h b in mem_of_superset (mem_at_top a) $ λ a' ha', le_trans ha (hf ha') lemma tendsto_at_bot_at_bot_of_monotone [preorder α] [preorder β] {f : α → β} (hf : monotone f) (h : ∀ b, ∃ a, f a ≤ b) : tendsto f at_bot at_bot := tendsto_infi.2 $ λ b, tendsto_principal.2 $ let ⟨a, ha⟩ := h b in mem_of_superset (mem_at_bot a) $ λ a' ha', le_trans (hf ha') ha lemma tendsto_at_top_at_top_iff_of_monotone [nonempty α] [semilattice_sup α] [preorder β] {f : α → β} (hf : monotone f) : tendsto f at_top at_top ↔ ∀ b : β, ∃ a : α, b ≤ f a := tendsto_at_top_at_top.trans $ forall_congr $ λ b, exists_congr $ λ a, ⟨λ h, h a (le_refl a), λ h a' ha', le_trans h $ hf ha'⟩ lemma tendsto_at_bot_at_bot_iff_of_monotone [nonempty α] [semilattice_inf α] [preorder β] {f : α → β} (hf : monotone f) : tendsto f at_bot at_bot ↔ ∀ b : β, ∃ a : α, f a ≤ b := tendsto_at_bot_at_bot.trans $ forall_congr $ λ b, exists_congr $ λ a, ⟨λ h, h a (le_refl a), λ h a' ha', le_trans (hf ha') h⟩ alias tendsto_at_top_at_top_of_monotone ← _root_.monotone.tendsto_at_top_at_top alias tendsto_at_bot_at_bot_of_monotone ← _root_.monotone.tendsto_at_bot_at_bot alias tendsto_at_top_at_top_iff_of_monotone ← _root_.monotone.tendsto_at_top_at_top_iff alias tendsto_at_bot_at_bot_iff_of_monotone ← _root_.monotone.tendsto_at_bot_at_bot_iff lemma comap_embedding_at_top [preorder β] [preorder γ] {e : β → γ} (hm : ∀b₁ b₂, e b₁ ≤ e b₂ ↔ b₁ ≤ b₂) (hu : ∀c, ∃b, c ≤ e b) : comap e at_top = at_top := le_antisymm (le_infi $ λ b, le_principal_iff.2 $ mem_comap.2 ⟨Ici (e b), mem_at_top _, λ x, (hm _ _).1⟩) (tendsto_at_top_at_top_of_monotone (λ _ _, (hm _ _).2) hu).le_comap lemma comap_embedding_at_bot [preorder β] [preorder γ] {e : β → γ} (hm : ∀ b₁ b₂, e b₁ ≤ e b₂ ↔ b₁ ≤ b₂) (hu : ∀c, ∃b, e b ≤ c) : comap e at_bot = at_bot := @comap_embedding_at_top βᵒᵈ γᵒᵈ _ _ e (function.swap hm) hu lemma tendsto_at_top_embedding [preorder β] [preorder γ] {f : α → β} {e : β → γ} {l : filter α} (hm : ∀b₁ b₂, e b₁ ≤ e b₂ ↔ b₁ ≤ b₂) (hu : ∀c, ∃b, c ≤ e b) : tendsto (e ∘ f) l at_top ↔ tendsto f l at_top := by rw [← comap_embedding_at_top hm hu, tendsto_comap_iff] /-- A function `f` goes to `-∞` independent of an order-preserving embedding `e`. -/ lemma tendsto_at_bot_embedding [preorder β] [preorder γ] {f : α → β} {e : β → γ} {l : filter α} (hm : ∀b₁ b₂, e b₁ ≤ e b₂ ↔ b₁ ≤ b₂) (hu : ∀c, ∃b, e b ≤ c) : tendsto (e ∘ f) l at_bot ↔ tendsto f l at_bot := @tendsto_at_top_embedding α βᵒᵈ γᵒᵈ _ _ f e l (function.swap hm) hu lemma tendsto_finset_range : tendsto finset.range at_top at_top := finset.range_mono.tendsto_at_top_at_top finset.exists_nat_subset_range lemma at_top_finset_eq_infi : (at_top : filter $ finset α) = ⨅ x : α, 𝓟 (Ici {x}) := begin refine le_antisymm (le_infi (λ i, le_principal_iff.2 $ mem_at_top {i})) _, refine le_infi (λ s, le_principal_iff.2 $ mem_infi_of_Inter s.finite_to_set (λ i, mem_principal_self _) _), simp only [subset_def, mem_Inter, set_coe.forall, mem_Ici, finset.le_iff_subset, finset.mem_singleton, finset.subset_iff, forall_eq], dsimp, exact λ t, id end /-- If `f` is a monotone sequence of `finset`s and each `x` belongs to one of `f n`, then `tendsto f at_top at_top`. -/ lemma tendsto_at_top_finset_of_monotone [preorder β] {f : β → finset α} (h : monotone f) (h' : ∀ x : α, ∃ n, x ∈ f n) : tendsto f at_top at_top := begin simp only [at_top_finset_eq_infi, tendsto_infi, tendsto_principal], intro a, rcases h' a with ⟨b, hb⟩, exact eventually.mono (mem_at_top b) (λ b' hb', le_trans (finset.singleton_subset_iff.2 hb) (h hb')), end alias tendsto_at_top_finset_of_monotone ← _root_.monotone.tendsto_at_top_finset lemma tendsto_finset_image_at_top_at_top {i : β → γ} {j : γ → β} (h : function.left_inverse j i) : tendsto (finset.image j) at_top at_top := (finset.image_mono j).tendsto_at_top_finset $ assume a, ⟨{i a}, by simp only [finset.image_singleton, h a, finset.mem_singleton]⟩ lemma tendsto_finset_preimage_at_top_at_top {f : α → β} (hf : function.injective f) : tendsto (λ s : finset β, s.preimage f (hf.inj_on _)) at_top at_top := (finset.monotone_preimage hf).tendsto_at_top_finset $ λ x, ⟨{f x}, finset.mem_preimage.2 $ finset.mem_singleton_self _⟩ lemma prod_at_top_at_top_eq {β₁ β₂ : Type*} [semilattice_sup β₁] [semilattice_sup β₂] : (at_top : filter β₁) ×ᶠ (at_top : filter β₂) = (at_top : filter (β₁ × β₂)) := begin casesI (is_empty_or_nonempty β₁).symm, casesI (is_empty_or_nonempty β₂).symm, { simp [at_top, prod_infi_left, prod_infi_right, infi_prod], exact infi_comm, }, { simp only [at_top.filter_eq_bot_of_is_empty, prod_bot] }, { simp only [at_top.filter_eq_bot_of_is_empty, bot_prod] }, end lemma prod_at_bot_at_bot_eq {β₁ β₂ : Type*} [semilattice_inf β₁] [semilattice_inf β₂] : (at_bot : filter β₁) ×ᶠ (at_bot : filter β₂) = (at_bot : filter (β₁ × β₂)) := @prod_at_top_at_top_eq β₁ᵒᵈ β₂ᵒᵈ _ _ lemma prod_map_at_top_eq {α₁ α₂ β₁ β₂ : Type*} [semilattice_sup β₁] [semilattice_sup β₂] (u₁ : β₁ → α₁) (u₂ : β₂ → α₂) : (map u₁ at_top) ×ᶠ (map u₂ at_top) = map (prod.map u₁ u₂) at_top := by rw [prod_map_map_eq, prod_at_top_at_top_eq, prod.map_def] lemma prod_map_at_bot_eq {α₁ α₂ β₁ β₂ : Type*} [semilattice_inf β₁] [semilattice_inf β₂] (u₁ : β₁ → α₁) (u₂ : β₂ → α₂) : (map u₁ at_bot) ×ᶠ (map u₂ at_bot) = map (prod.map u₁ u₂) at_bot := @prod_map_at_top_eq _ _ β₁ᵒᵈ β₂ᵒᵈ _ _ _ _ lemma tendsto.subseq_mem {F : filter α} {V : ℕ → set α} (h : ∀ n, V n ∈ F) {u : ℕ → α} (hu : tendsto u at_top F) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, u (φ n) ∈ V n := extraction_forall_of_eventually' (λ n, tendsto_at_top'.mp hu _ (h n) : ∀ n, ∃ N, ∀ k ≥ N, u k ∈ V n) lemma tendsto_at_bot_diagonal [semilattice_inf α] : tendsto (λ a : α, (a, a)) at_bot at_bot := by { rw ← prod_at_bot_at_bot_eq, exact tendsto_id.prod_mk tendsto_id } lemma tendsto_at_top_diagonal [semilattice_sup α] : tendsto (λ a : α, (a, a)) at_top at_top := by { rw ← prod_at_top_at_top_eq, exact tendsto_id.prod_mk tendsto_id } lemma tendsto.prod_map_prod_at_bot [semilattice_inf γ] {F : filter α} {G : filter β} {f : α → γ} {g : β → γ} (hf : tendsto f F at_bot) (hg : tendsto g G at_bot) : tendsto (prod.map f g) (F ×ᶠ G) at_bot := by { rw ← prod_at_bot_at_bot_eq, exact hf.prod_map hg, } lemma tendsto.prod_map_prod_at_top [semilattice_sup γ] {F : filter α} {G : filter β} {f : α → γ} {g : β → γ} (hf : tendsto f F at_top) (hg : tendsto g G at_top) : tendsto (prod.map f g) (F ×ᶠ G) at_top := by { rw ← prod_at_top_at_top_eq, exact hf.prod_map hg, } lemma tendsto.prod_at_bot [semilattice_inf α] [semilattice_inf γ] {f g : α → γ} (hf : tendsto f at_bot at_bot) (hg : tendsto g at_bot at_bot) : tendsto (prod.map f g) at_bot at_bot := by { rw ← prod_at_bot_at_bot_eq, exact hf.prod_map_prod_at_bot hg, } lemma tendsto.prod_at_top [semilattice_sup α] [semilattice_sup γ] {f g : α → γ} (hf : tendsto f at_top at_top) (hg : tendsto g at_top at_top) : tendsto (prod.map f g) at_top at_top := by { rw ← prod_at_top_at_top_eq, exact hf.prod_map_prod_at_top hg, } lemma eventually_at_bot_prod_self [semilattice_inf α] [nonempty α] {p : α × α → Prop} : (∀ᶠ x in at_bot, p x) ↔ (∃ a, ∀ k l, k ≤ a → l ≤ a → p (k, l)) := by simp [← prod_at_bot_at_bot_eq, at_bot_basis.prod_self.eventually_iff] lemma eventually_at_top_prod_self [semilattice_sup α] [nonempty α] {p : α × α → Prop} : (∀ᶠ x in at_top, p x) ↔ (∃ a, ∀ k l, a ≤ k → a ≤ l → p (k, l)) := by simp [← prod_at_top_at_top_eq, at_top_basis.prod_self.eventually_iff] lemma eventually_at_bot_prod_self' [semilattice_inf α] [nonempty α] {p : α × α → Prop} : (∀ᶠ x in at_bot, p x) ↔ (∃ a, ∀ k ≤ a, ∀ l ≤ a, p (k, l)) := begin rw filter.eventually_at_bot_prod_self, apply exists_congr, tauto, end lemma eventually_at_top_prod_self' [semilattice_sup α] [nonempty α] {p : α × α → Prop} : (∀ᶠ x in at_top, p x) ↔ (∃ a, ∀ k ≥ a, ∀ l ≥ a, p (k, l)) := begin rw filter.eventually_at_top_prod_self, apply exists_congr, tauto, end lemma eventually_at_top_curry [semilattice_sup α] [semilattice_sup β] {p : α × β → Prop} (hp : ∀ᶠ (x : α × β) in filter.at_top, p x) : ∀ᶠ k in at_top, ∀ᶠ l in at_top, p (k, l) := begin rw ← prod_at_top_at_top_eq at hp, exact hp.curry, end lemma eventually_at_bot_curry [semilattice_inf α] [semilattice_inf β] {p : α × β → Prop} (hp : ∀ᶠ (x : α × β) in filter.at_bot, p x) : ∀ᶠ k in at_bot, ∀ᶠ l in at_bot, p (k, l) := @eventually_at_top_curry αᵒᵈ βᵒᵈ _ _ _ hp /-- A function `f` maps upwards closed sets (at_top sets) to upwards closed sets when it is a Galois insertion. The Galois "insertion" and "connection" is weakened to only require it to be an insertion and a connetion above `b'`. -/ lemma map_at_top_eq_of_gc [semilattice_sup α] [semilattice_sup β] {f : α → β} (g : β → α) (b' : β) (hf : monotone f) (gc : ∀a, ∀b≥b', f a ≤ b ↔ a ≤ g b) (hgi : ∀b≥b', b ≤ f (g b)) : map f at_top = at_top := begin refine le_antisymm (hf.tendsto_at_top_at_top $ λ b, ⟨g (b ⊔ b'), le_sup_left.trans $ hgi _ le_sup_right⟩) _, rw [@map_at_top_eq _ _ ⟨g b'⟩], refine le_infi (λ a, infi_le_of_le (f a ⊔ b') $ principal_mono.2 $ λ b hb, _), rw [mem_Ici, sup_le_iff] at hb, exact ⟨g b, (gc _ _ hb.2).1 hb.1, le_antisymm ((gc _ _ hb.2).2 le_rfl) (hgi _ hb.2)⟩ end lemma map_at_bot_eq_of_gc [semilattice_inf α] [semilattice_inf β] {f : α → β} (g : β → α) (b' : β) (hf : monotone f) (gc : ∀a, ∀b≤b', b ≤ f a ↔ g b ≤ a) (hgi : ∀b≤b', f (g b) ≤ b) : map f at_bot = at_bot := @map_at_top_eq_of_gc αᵒᵈ βᵒᵈ _ _ _ _ _ hf.dual gc hgi lemma map_coe_at_top_of_Ici_subset [semilattice_sup α] {a : α} {s : set α} (h : Ici a ⊆ s) : map (coe : s → α) at_top = at_top := begin have : directed (≥) (λ x : s, 𝓟 (Ici x)), { intros x y, use ⟨x ⊔ y ⊔ a, h le_sup_right⟩, simp only [ge_iff_le, principal_mono, Ici_subset_Ici, ← subtype.coe_le_coe, subtype.coe_mk], exact ⟨le_sup_left.trans le_sup_left, le_sup_right.trans le_sup_left⟩ }, haveI : nonempty s := ⟨⟨a, h le_rfl⟩⟩, simp only [le_antisymm_iff, at_top, le_infi_iff, le_principal_iff, mem_map, mem_set_of_eq, map_infi_eq this, map_principal], split, { intro x, refine mem_of_superset (mem_infi_of_mem ⟨x ⊔ a, h le_sup_right⟩ (mem_principal_self _)) _, rintro _ ⟨y, hy, rfl⟩, exact le_trans le_sup_left (subtype.coe_le_coe.2 hy) }, { intro x, filter_upwards [mem_at_top (↑x ⊔ a)] with b hb, exact ⟨⟨b, h $ le_sup_right.trans hb⟩, subtype.coe_le_coe.1 (le_sup_left.trans hb), rfl⟩, }, end /-- The image of the filter `at_top` on `Ici a` under the coercion equals `at_top`. -/ @[simp] lemma map_coe_Ici_at_top [semilattice_sup α] (a : α) : map (coe : Ici a → α) at_top = at_top := map_coe_at_top_of_Ici_subset (subset.refl _) /-- The image of the filter `at_top` on `Ioi a` under the coercion equals `at_top`. -/ @[simp] lemma map_coe_Ioi_at_top [semilattice_sup α] [no_max_order α] (a : α) : map (coe : Ioi a → α) at_top = at_top := let ⟨b, hb⟩ := exists_gt a in map_coe_at_top_of_Ici_subset $ Ici_subset_Ioi.2 hb /-- The `at_top` filter for an open interval `Ioi a` comes from the `at_top` filter in the ambient order. -/ lemma at_top_Ioi_eq [semilattice_sup α] (a : α) : at_top = comap (coe : Ioi a → α) at_top := begin nontriviality, rcases nontrivial_iff_nonempty.1 ‹_› with ⟨b, hb⟩, rw [← map_coe_at_top_of_Ici_subset (Ici_subset_Ioi.2 hb), comap_map subtype.coe_injective] end /-- The `at_top` filter for an open interval `Ici a` comes from the `at_top` filter in the ambient order. -/ lemma at_top_Ici_eq [semilattice_sup α] (a : α) : at_top = comap (coe : Ici a → α) at_top := by rw [← map_coe_Ici_at_top a, comap_map subtype.coe_injective] /-- The `at_bot` filter for an open interval `Iio a` comes from the `at_bot` filter in the ambient order. -/ @[simp] lemma map_coe_Iio_at_bot [semilattice_inf α] [no_min_order α] (a : α) : map (coe : Iio a → α) at_bot = at_bot := @map_coe_Ioi_at_top αᵒᵈ _ _ _ /-- The `at_bot` filter for an open interval `Iio a` comes from the `at_bot` filter in the ambient order. -/ lemma at_bot_Iio_eq [semilattice_inf α] (a : α) : at_bot = comap (coe : Iio a → α) at_bot := @at_top_Ioi_eq αᵒᵈ _ _ /-- The `at_bot` filter for an open interval `Iic a` comes from the `at_bot` filter in the ambient order. -/ @[simp] lemma map_coe_Iic_at_bot [semilattice_inf α] (a : α) : map (coe : Iic a → α) at_bot = at_bot := @map_coe_Ici_at_top αᵒᵈ _ _ /-- The `at_bot` filter for an open interval `Iic a` comes from the `at_bot` filter in the ambient order. -/ lemma at_bot_Iic_eq [semilattice_inf α] (a : α) : at_bot = comap (coe : Iic a → α) at_bot := @at_top_Ici_eq αᵒᵈ _ _ lemma tendsto_Ioi_at_top [semilattice_sup α] {a : α} {f : β → Ioi a} {l : filter β} : tendsto f l at_top ↔ tendsto (λ x, (f x : α)) l at_top := by rw [at_top_Ioi_eq, tendsto_comap_iff] lemma tendsto_Iio_at_bot [semilattice_inf α] {a : α} {f : β → Iio a} {l : filter β} : tendsto f l at_bot ↔ tendsto (λ x, (f x : α)) l at_bot := by rw [at_bot_Iio_eq, tendsto_comap_iff] lemma tendsto_Ici_at_top [semilattice_sup α] {a : α} {f : β → Ici a} {l : filter β} : tendsto f l at_top ↔ tendsto (λ x, (f x : α)) l at_top := by rw [at_top_Ici_eq, tendsto_comap_iff] lemma tendsto_Iic_at_bot [semilattice_inf α] {a : α} {f : β → Iic a} {l : filter β} : tendsto f l at_bot ↔ tendsto (λ x, (f x : α)) l at_bot := by rw [at_bot_Iic_eq, tendsto_comap_iff] @[simp] lemma tendsto_comp_coe_Ioi_at_top [semilattice_sup α] [no_max_order α] {a : α} {f : α → β} {l : filter β} : tendsto (λ x : Ioi a, f x) at_top l ↔ tendsto f at_top l := by rw [← map_coe_Ioi_at_top a, tendsto_map'_iff] @[simp] lemma tendsto_comp_coe_Ici_at_top [semilattice_sup α] {a : α} {f : α → β} {l : filter β} : tendsto (λ x : Ici a, f x) at_top l ↔ tendsto f at_top l := by rw [← map_coe_Ici_at_top a, tendsto_map'_iff] @[simp] lemma tendsto_comp_coe_Iio_at_bot [semilattice_inf α] [no_min_order α] {a : α} {f : α → β} {l : filter β} : tendsto (λ x : Iio a, f x) at_bot l ↔ tendsto f at_bot l := by rw [← map_coe_Iio_at_bot a, tendsto_map'_iff] @[simp] lemma tendsto_comp_coe_Iic_at_bot [semilattice_inf α] {a : α} {f : α → β} {l : filter β} : tendsto (λ x : Iic a, f x) at_bot l ↔ tendsto f at_bot l := by rw [← map_coe_Iic_at_bot a, tendsto_map'_iff] lemma map_add_at_top_eq_nat (k : ℕ) : map (λa, a + k) at_top = at_top := map_at_top_eq_of_gc (λa, a - k) k (assume a b h, add_le_add_right h k) (assume a b h, (le_tsub_iff_right h).symm) (assume a h, by rw [tsub_add_cancel_of_le h]) lemma map_sub_at_top_eq_nat (k : ℕ) : map (λa, a - k) at_top = at_top := map_at_top_eq_of_gc (λa, a + k) 0 (assume a b h, tsub_le_tsub_right h _) (assume a b _, tsub_le_iff_right) (assume b _, by rw [add_tsub_cancel_right]) lemma tendsto_add_at_top_nat (k : ℕ) : tendsto (λa, a + k) at_top at_top := le_of_eq (map_add_at_top_eq_nat k) lemma tendsto_sub_at_top_nat (k : ℕ) : tendsto (λa, a - k) at_top at_top := le_of_eq (map_sub_at_top_eq_nat k) lemma tendsto_add_at_top_iff_nat {f : ℕ → α} {l : filter α} (k : ℕ) : tendsto (λn, f (n + k)) at_top l ↔ tendsto f at_top l := show tendsto (f ∘ (λn, n + k)) at_top l ↔ tendsto f at_top l, by rw [← tendsto_map'_iff, map_add_at_top_eq_nat] lemma map_div_at_top_eq_nat (k : ℕ) (hk : 0 < k) : map (λa, a / k) at_top = at_top := map_at_top_eq_of_gc (λb, b * k + (k - 1)) 1 (assume a b h, nat.div_le_div_right h) (assume a b _, calc a / k ≤ b ↔ a / k < b + 1 : by rw [← nat.succ_eq_add_one, nat.lt_succ_iff] ... ↔ a < (b + 1) * k : nat.div_lt_iff_lt_mul hk ... ↔ _ : begin cases k, exact (lt_irrefl _ hk).elim, rw [add_mul, one_mul, nat.succ_sub_succ_eq_sub, tsub_zero, nat.add_succ, nat.lt_succ_iff], end) (assume b _, calc b = (b * k) / k : by rw [nat.mul_div_cancel b hk] ... ≤ (b * k + (k - 1)) / k : nat.div_le_div_right $ nat.le_add_right _ _) /-- If `u` is a monotone function with linear ordered codomain and the range of `u` is not bounded above, then `tendsto u at_top at_top`. -/ lemma tendsto_at_top_at_top_of_monotone' [preorder ι] [linear_order α] {u : ι → α} (h : monotone u) (H : ¬bdd_above (range u)) : tendsto u at_top at_top := begin apply h.tendsto_at_top_at_top, intro b, rcases not_bdd_above_iff.1 H b with ⟨_, ⟨N, rfl⟩, hN⟩, exact ⟨N, le_of_lt hN⟩, end /-- If `u` is a monotone function with linear ordered codomain and the range of `u` is not bounded below, then `tendsto u at_bot at_bot`. -/ lemma tendsto_at_bot_at_bot_of_monotone' [preorder ι] [linear_order α] {u : ι → α} (h : monotone u) (H : ¬bdd_below (range u)) : tendsto u at_bot at_bot := @tendsto_at_top_at_top_of_monotone' ιᵒᵈ αᵒᵈ _ _ _ h.dual H lemma unbounded_of_tendsto_at_top [nonempty α] [semilattice_sup α] [preorder β] [no_max_order β] {f : α → β} (h : tendsto f at_top at_top) : ¬ bdd_above (range f) := begin rintros ⟨M, hM⟩, cases mem_at_top_sets.mp (h $ Ioi_mem_at_top M) with a ha, apply lt_irrefl M, calc M < f a : ha a le_rfl ... ≤ M : hM (set.mem_range_self a) end lemma unbounded_of_tendsto_at_bot [nonempty α] [semilattice_sup α] [preorder β] [no_min_order β] {f : α → β} (h : tendsto f at_top at_bot) : ¬ bdd_below (range f) := @unbounded_of_tendsto_at_top _ βᵒᵈ _ _ _ _ _ h lemma unbounded_of_tendsto_at_top' [nonempty α] [semilattice_inf α] [preorder β] [no_max_order β] {f : α → β} (h : tendsto f at_bot at_top) : ¬ bdd_above (range f) := @unbounded_of_tendsto_at_top αᵒᵈ _ _ _ _ _ _ h lemma unbounded_of_tendsto_at_bot' [nonempty α] [semilattice_inf α] [preorder β] [no_min_order β] {f : α → β} (h : tendsto f at_bot at_bot) : ¬ bdd_below (range f) := @unbounded_of_tendsto_at_top αᵒᵈ βᵒᵈ _ _ _ _ _ h /-- If a monotone function `u : ι → α` tends to `at_top` along *some* non-trivial filter `l`, then it tends to `at_top` along `at_top`. -/ lemma tendsto_at_top_of_monotone_of_filter [preorder ι] [preorder α] {l : filter ι} {u : ι → α} (h : monotone u) [ne_bot l] (hu : tendsto u l at_top) : tendsto u at_top at_top := h.tendsto_at_top_at_top $ λ b, (hu.eventually (mem_at_top b)).exists /-- If a monotone function `u : ι → α` tends to `at_bot` along *some* non-trivial filter `l`, then it tends to `at_bot` along `at_bot`. -/ lemma tendsto_at_bot_of_monotone_of_filter [preorder ι] [preorder α] {l : filter ι} {u : ι → α} (h : monotone u) [ne_bot l] (hu : tendsto u l at_bot) : tendsto u at_bot at_bot := @tendsto_at_top_of_monotone_of_filter ιᵒᵈ αᵒᵈ _ _ _ _ h.dual _ hu lemma tendsto_at_top_of_monotone_of_subseq [preorder ι] [preorder α] {u : ι → α} {φ : ι' → ι} (h : monotone u) {l : filter ι'} [ne_bot l] (H : tendsto (u ∘ φ) l at_top) : tendsto u at_top at_top := tendsto_at_top_of_monotone_of_filter h (tendsto_map' H) lemma tendsto_at_bot_of_monotone_of_subseq [preorder ι] [preorder α] {u : ι → α} {φ : ι' → ι} (h : monotone u) {l : filter ι'} [ne_bot l] (H : tendsto (u ∘ φ) l at_bot) : tendsto u at_bot at_bot := tendsto_at_bot_of_monotone_of_filter h (tendsto_map' H) /-- Let `f` and `g` be two maps to the same commutative monoid. This lemma gives a sufficient condition for comparison of the filter `at_top.map (λ s, ∏ b in s, f b)` with `at_top.map (λ s, ∏ b in s, g b)`. This is useful to compare the set of limit points of `Π b in s, f b` as `s → at_top` with the similar set for `g`. -/ @[to_additive "Let `f` and `g` be two maps to the same commutative additive monoid. This lemma gives a sufficient condition for comparison of the filter `at_top.map (λ s, ∑ b in s, f b)` with `at_top.map (λ s, ∑ b in s, g b)`. This is useful to compare the set of limit points of `∑ b in s, f b` as `s → at_top` with the similar set for `g`."] lemma map_at_top_finset_prod_le_of_prod_eq [comm_monoid α] {f : β → α} {g : γ → α} (h_eq : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ ∏ x in u', g x = ∏ b in v', f b) : at_top.map (λs:finset β, ∏ b in s, f b) ≤ at_top.map (λs:finset γ, ∏ x in s, g x) := by rw [map_at_top_eq, map_at_top_eq]; from (le_infi $ assume b, let ⟨v, hv⟩ := h_eq b in infi_le_of_le v $ by simp [set.image_subset_iff]; exact hv) lemma has_antitone_basis.eventually_subset [preorder ι] {l : filter α} {s : ι → set α} (hl : l.has_antitone_basis s) {t : set α} (ht : t ∈ l) : ∀ᶠ i in at_top, s i ⊆ t := let ⟨i, _, hi⟩ := hl.to_has_basis.mem_iff.1 ht in (eventually_ge_at_top i).mono $ λ j hj, (hl.antitone hj).trans hi protected lemma has_antitone_basis.tendsto [preorder ι] {l : filter α} {s : ι → set α} (hl : l.has_antitone_basis s) {φ : ι → α} (h : ∀ i : ι, φ i ∈ s i) : tendsto φ at_top l := λ t ht, mem_map.2 $ (hl.eventually_subset ht).mono $ λ i hi, hi (h i) lemma has_antitone_basis.comp_mono [semilattice_sup ι] [nonempty ι] [preorder ι'] {l : filter α} {s : ι' → set α} (hs : l.has_antitone_basis s) {φ : ι → ι'} (φ_mono : monotone φ) (hφ : tendsto φ at_top at_top) : l.has_antitone_basis (s ∘ φ) := ⟨hs.to_has_basis.to_has_basis (λ n hn, (hφ.eventually (eventually_ge_at_top n)).exists.imp $ λ m hm, ⟨trivial, hs.antitone hm⟩) (λ n hn, ⟨φ n, trivial, subset.rfl⟩), hs.antitone.comp_monotone φ_mono⟩ lemma has_antitone_basis.comp_strict_mono {l : filter α} {s : ℕ → set α} (hs : l.has_antitone_basis s) {φ : ℕ → ℕ} (hφ : strict_mono φ) : l.has_antitone_basis (s ∘ φ) := hs.comp_mono hφ.monotone hφ.tendsto_at_top /-- Given an antitone basis `s : ℕ → set α` of a filter, extract an antitone subbasis `s ∘ φ`, `φ : ℕ → ℕ`, such that `m < n` implies `r (φ m) (φ n)`. This lemma can be used to extract an antitone basis with basis sets decreasing "sufficiently fast". -/ lemma has_antitone_basis.subbasis_with_rel {f : filter α} {s : ℕ → set α} (hs : f.has_antitone_basis s) {r : ℕ → ℕ → Prop} (hr : ∀ m, ∀ᶠ n in at_top, r m n) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ (∀ ⦃m n⦄, m < n → r (φ m) (φ n)) ∧ f.has_antitone_basis (s ∘ φ) := begin rsuffices ⟨φ, hφ, hrφ⟩ : ∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ m n, m < n → r (φ m) (φ n), { exact ⟨φ, hφ, hrφ, hs.comp_strict_mono hφ⟩ }, have : ∀ t : set ℕ, t.finite → ∀ᶠ n in at_top, ∀ m ∈ t, m < n ∧ r m n, from λ t ht, (eventually_all_finite ht).2 (λ m hm, (eventually_gt_at_top m).and (hr _)), rcases seq_of_forall_finite_exists (λ t ht, (this t ht).exists) with ⟨φ, hφ⟩, simp only [ball_image_iff, forall_and_distrib, mem_Iio] at hφ, exact ⟨φ, forall_swap.2 hφ.1, forall_swap.2 hφ.2⟩ end /-- If `f` is a nontrivial countably generated filter, then there exists a sequence that converges to `f`. -/ lemma exists_seq_tendsto (f : filter α) [is_countably_generated f] [ne_bot f] : ∃ x : ℕ → α, tendsto x at_top f := begin obtain ⟨B, h⟩ := f.exists_antitone_basis, choose x hx using λ n, filter.nonempty_of_mem (h.mem n), exact ⟨x, h.tendsto hx⟩ end /-- An abstract version of continuity of sequentially continuous functions on metric spaces: if a filter `k` is countably generated then `tendsto f k l` iff for every sequence `u` converging to `k`, `f ∘ u` tends to `l`. -/ lemma tendsto_iff_seq_tendsto {f : α → β} {k : filter α} {l : filter β} [k.is_countably_generated] : tendsto f k l ↔ (∀ x : ℕ → α, tendsto x at_top k → tendsto (f ∘ x) at_top l) := begin refine ⟨λ h x hx, h.comp hx, λ H s hs, _⟩, contrapose! H, haveI : ne_bot (k ⊓ 𝓟 (f ⁻¹' sᶜ)), by simpa [ne_bot_iff, inf_principal_eq_bot], rcases (k ⊓ 𝓟 (f ⁻¹' sᶜ)).exists_seq_tendsto with ⟨x, hx⟩, rw [tendsto_inf, tendsto_principal] at hx, refine ⟨x, hx.1, λ h, _⟩, rcases (hx.2.and (h hs)).exists with ⟨N, hnmem, hmem⟩, exact hnmem hmem end lemma tendsto_of_seq_tendsto {f : α → β} {k : filter α} {l : filter β} [k.is_countably_generated] : (∀ x : ℕ → α, tendsto x at_top k → tendsto (f ∘ x) at_top l) → tendsto f k l := tendsto_iff_seq_tendsto.2 lemma tendsto_iff_forall_eventually_mem {α ι : Type*} {x : ι → α} {f : filter α} {l : filter ι} : tendsto x l f ↔ ∀ s ∈ f, ∀ᶠ n in l, x n ∈ s := by { rw tendsto_def, refine forall_congr (λ s, imp_congr_right (λ hsf, _)), refl, } lemma not_tendsto_iff_exists_frequently_nmem {α ι : Type*} {x : ι → α} {f : filter α} {l : filter ι} : ¬ tendsto x l f ↔ ∃ s ∈ f, ∃ᶠ n in l, x n ∉ s := begin rw tendsto_iff_forall_eventually_mem, push_neg, refine exists_congr (λ s, _), rw [not_eventually, exists_prop], end lemma frequently_iff_seq_frequently {ι : Type*} {l : filter ι} {p : ι → Prop} [hl : l.is_countably_generated] : (∃ᶠ n in l, p n) ↔ ∃ (x : ℕ → ι), tendsto x at_top l ∧ ∃ᶠ (n : ℕ) in at_top, p (x n) := begin refine ⟨λ h_freq, _, λ h_exists_freq, _⟩, { haveI : ne_bot (l ⊓ 𝓟 {x : ι | p x}), by simpa [ne_bot_iff, inf_principal_eq_bot], obtain ⟨x, hx⟩ := exists_seq_tendsto (l ⊓ (𝓟 {x : ι | p x})), rw tendsto_inf at hx, cases hx with hx_l hx_p, refine ⟨x, hx_l, _⟩, rw tendsto_principal at hx_p, exact hx_p.frequently, }, { obtain ⟨x, hx_tendsto, hx_freq⟩ := h_exists_freq, simp_rw [filter.frequently, filter.eventually] at hx_freq ⊢, have : {n : ℕ | ¬p (x n)} = {n | x n ∈ {y | ¬ p y}} := rfl, rw [this, ← mem_map'] at hx_freq, contrapose! hx_freq, exact hx_tendsto hx_freq, }, end lemma eventually_iff_seq_eventually {ι : Type*} {l : filter ι} {p : ι → Prop} [hl : l.is_countably_generated] : (∀ᶠ n in l, p n) ↔ ∀ (x : ℕ → ι), tendsto x at_top l → ∀ᶠ (n : ℕ) in at_top, p (x n) := begin have : (∀ᶠ n in l, p n) ↔ ¬ ∃ᶠ n in l, ¬(p n), { rw not_frequently, simp_rw not_not, }, rw [this, frequently_iff_seq_frequently], push_neg, simp_rw [not_frequently, not_not], end lemma subseq_forall_of_frequently {ι : Type*} {x : ℕ → ι} {p : ι → Prop} {l : filter ι} (h_tendsto : tendsto x at_top l) (h : ∃ᶠ n in at_top, p (x n)) : ∃ ns : ℕ → ℕ, tendsto (λ n, x (ns n)) at_top l ∧ ∀ n, p (x (ns n)) := begin rw tendsto_iff_seq_tendsto at h_tendsto, choose ns hge hns using frequently_at_top.1 h, exact ⟨ns, h_tendsto ns (tendsto_at_top_mono hge tendsto_id), hns⟩, end lemma exists_seq_forall_of_frequently {ι : Type*} {l : filter ι} {p : ι → Prop} [hl : l.is_countably_generated] (h : ∃ᶠ n in l, p n) : ∃ ns : ℕ → ι, tendsto ns at_top l ∧ ∀ n, p (ns n) := begin rw frequently_iff_seq_frequently at h, obtain ⟨x, hx_tendsto, hx_freq⟩ := h, obtain ⟨n_to_n, h_tendsto, h_freq⟩ := subseq_forall_of_frequently hx_tendsto hx_freq, exact ⟨x ∘ n_to_n, h_tendsto, h_freq⟩, end /-- A sequence converges if every subsequence has a convergent subsequence. -/ lemma tendsto_of_subseq_tendsto {α ι : Type*} {x : ι → α} {f : filter α} {l : filter ι} [l.is_countably_generated] (hxy : ∀ ns : ℕ → ι, tendsto ns at_top l → ∃ ms : ℕ → ℕ, tendsto (λ n, x (ns $ ms n)) at_top f) : tendsto x l f := begin by_contra h, obtain ⟨s, hs, hfreq⟩ : ∃ s ∈ f, ∃ᶠ n in l, x n ∉ s, by rwa not_tendsto_iff_exists_frequently_nmem at h, obtain ⟨y, hy_tendsto, hy_freq⟩ := exists_seq_forall_of_frequently hfreq, specialize hxy y hy_tendsto, obtain ⟨ms, hms_tendsto⟩ := hxy, specialize hms_tendsto hs, rw mem_map at hms_tendsto, have hms_freq : ∀ (n : ℕ), x (y (ms n)) ∉ s, from λ n, hy_freq (ms n), have h_empty : (λ (n : ℕ), x (y (ms n))) ⁻¹' s = ∅, { ext1 n, simp only [set.mem_preimage, set.mem_empty_iff_false, iff_false], exact hms_freq n, }, rw h_empty at hms_tendsto, exact empty_not_mem at_top hms_tendsto, end lemma subseq_tendsto_of_ne_bot {f : filter α} [is_countably_generated f] {u : ℕ → α} (hx : ne_bot (f ⊓ map u at_top)) : ∃ (θ : ℕ → ℕ), (strict_mono θ) ∧ (tendsto (u ∘ θ) at_top f) := begin obtain ⟨B, h⟩ := f.exists_antitone_basis, have : ∀ N, ∃ n ≥ N, u n ∈ B N, from λ N, filter.inf_map_at_top_ne_bot_iff.mp hx _ (h.to_has_basis.mem_of_mem trivial) N, choose φ hφ using this, cases forall_and_distrib.mp hφ with φ_ge φ_in, have lim_uφ : tendsto (u ∘ φ) at_top f, from h.tendsto φ_in, have lim_φ : tendsto φ at_top at_top, from (tendsto_at_top_mono φ_ge tendsto_id), obtain ⟨ψ, hψ, hψφ⟩ : ∃ ψ : ℕ → ℕ, strict_mono ψ ∧ strict_mono (φ ∘ ψ), from strict_mono_subseq_of_tendsto_at_top lim_φ, exact ⟨φ ∘ ψ, hψφ, lim_uφ.comp hψ.tendsto_at_top⟩, end end filter open filter finset section variables {R : Type*} [linear_ordered_semiring R] lemma exists_lt_mul_self (a : R) : ∃ x ≥ 0, a < x * x := let ⟨x, hxa, hx0⟩ := ((tendsto_mul_self_at_top.eventually (eventually_gt_at_top a)).and (eventually_ge_at_top 0)).exists in ⟨x, hx0, hxa⟩ lemma exists_le_mul_self (a : R) : ∃ x ≥ 0, a ≤ x * x := let ⟨x, hx0, hxa⟩ := exists_lt_mul_self a in ⟨x, hx0, hxa.le⟩ end /-- Let `g : γ → β` be an injective function and `f : β → α` be a function from the codomain of `g` to a commutative monoid. Suppose that `f x = 1` outside of the range of `g`. Then the filters `at_top.map (λ s, ∏ i in s, f (g i))` and `at_top.map (λ s, ∏ i in s, f i)` coincide. The additive version of this lemma is used to prove the equality `∑' x, f (g x) = ∑' y, f y` under the same assumptions.-/ @[to_additive] lemma function.injective.map_at_top_finset_prod_eq [comm_monoid α] {g : γ → β} (hg : function.injective g) {f : β → α} (hf : ∀ x ∉ set.range g, f x = 1) : map (λ s, ∏ i in s, f (g i)) at_top = map (λ s, ∏ i in s, f i) at_top := begin apply le_antisymm; refine map_at_top_finset_prod_le_of_prod_eq (λ s, _), { refine ⟨s.preimage g (hg.inj_on _), λ t ht, _⟩, refine ⟨t.image g ∪ s, finset.subset_union_right _ _, _⟩, rw [← finset.prod_image (hg.inj_on _)], refine (prod_subset (subset_union_left _ _) _).symm, simp only [finset.mem_union, finset.mem_image], refine λ y hy hyt, hf y (mt _ hyt), rintros ⟨x, rfl⟩, exact ⟨x, ht (finset.mem_preimage.2 $ hy.resolve_left hyt), rfl⟩ }, { refine ⟨s.image g, λ t ht, _⟩, simp only [← prod_preimage _ _ (hg.inj_on _) _ (λ x _, hf x)], exact ⟨_, (image_subset_iff_subset_preimage _).1 ht, rfl⟩ } end /-- Let `g : γ → β` be an injective function and `f : β → α` be a function from the codomain of `g` to an additive commutative monoid. Suppose that `f x = 0` outside of the range of `g`. Then the filters `at_top.map (λ s, ∑ i in s, f (g i))` and `at_top.map (λ s, ∑ i in s, f i)` coincide. This lemma is used to prove the equality `∑' x, f (g x) = ∑' y, f y` under the same assumptions.-/ add_decl_doc function.injective.map_at_top_finset_sum_eq
48b0e762bc6d04b5c78ab4e08e1883d37e5d034b
63abd62053d479eae5abf4951554e1064a4c45b4
/src/data/dfinsupp.lean
35810fb2c7b790ce6b646bf4275ec81105419136
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
42,025
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Kenny Lau -/ import algebra.module.linear_map import algebra.module.pi import algebra.big_operators.basic import data.set.finite import linear_algebra.basic /-! # Dependent functions with finite support For a non-dependent version see `data/finsupp.lean`. -/ universes u u₁ u₂ v v₁ v₂ v₃ w x y l open_locale big_operators variables (ι : Type u) (β : ι → Type v) namespace dfinsupp variable [Π i, has_zero (β i)] structure pre : Type (max u v) := (to_fun : Π i, β i) (pre_support : multiset ι) (zero : ∀ i, i ∈ pre_support ∨ to_fun i = 0) instance inhabited_pre : inhabited (pre ι β) := ⟨⟨λ i, 0, ∅, λ i, or.inr rfl⟩⟩ instance : setoid (pre ι β) := { r := λ x y, ∀ i, x.to_fun i = y.to_fun i, iseqv := ⟨λ f i, rfl, λ f g H i, (H i).symm, λ f g h H1 H2 i, (H1 i).trans (H2 i)⟩ } end dfinsupp variable {ι} /-- A dependent function `Π i, β i` with finite support. -/ @[reducible] def dfinsupp [Π i, has_zero (β i)] : Type* := quotient (dfinsupp.pre.setoid ι β) variable {β} notation `Π₀` binders `, ` r:(scoped f, dfinsupp f) := r infix ` →ₚ `:25 := dfinsupp namespace dfinsupp section basic variables [Π i, has_zero (β i)] variables {β₁ : ι → Type v₁} {β₂ : ι → Type v₂} variables [Π i, has_zero (β₁ i)] [Π i, has_zero (β₂ i)] instance : has_coe_to_fun (Π₀ i, β i) := ⟨λ _, Π i, β i, λ f, quotient.lift_on f pre.to_fun $ λ _ _, funext⟩ instance : has_zero (Π₀ i, β i) := ⟨⟦⟨λ i, 0, ∅, λ i, or.inr rfl⟩⟧⟩ instance : inhabited (Π₀ i, β i) := ⟨0⟩ @[simp] lemma zero_apply (i : ι) : (0 : Π₀ i, β i) i = 0 := rfl @[ext] lemma ext {f g : Π₀ i, β i} (H : ∀ i, f i = g i) : f = g := quotient.induction_on₂ f g (λ _ _ H, quotient.sound H) H /-- The composition of `f : β₁ → β₂` and `g : Π₀ i, β₁ i` is `map_range f hf g : Π₀ i, β₂ i`, well defined when `f 0 = 0`. -/ def map_range (f : Π i, β₁ i → β₂ i) (hf : ∀ i, f i 0 = 0) (g : Π₀ i, β₁ i) : Π₀ i, β₂ i := quotient.lift_on g (λ x, ⟦(⟨λ i, f i (x.1 i), x.2, λ i, or.cases_on (x.3 i) or.inl $ λ H, or.inr $ by rw [H, hf]⟩ : pre ι β₂)⟧) $ λ x y H, quotient.sound $ λ i, by simp only [H i] @[simp] lemma map_range_apply (f : Π i, β₁ i → β₂ i) (hf : ∀ i, f i 0 = 0) (g : Π₀ i, β₁ i) (i : ι) : map_range f hf g i = f i (g i) := quotient.induction_on g $ λ x, rfl /-- Let `f i` be a binary operation `β₁ i → β₂ i → β i` such that `f i 0 0 = 0`. Then `zip_with f hf` is a binary operation `Π₀ i, β₁ i → Π₀ i, β₂ i → Π₀ i, β i`. -/ def zip_with (f : Π i, β₁ i → β₂ i → β i) (hf : ∀ i, f i 0 0 = 0) (g₁ : Π₀ i, β₁ i) (g₂ : Π₀ i, β₂ i) : (Π₀ i, β i) := begin refine quotient.lift_on₂ g₁ g₂ (λ x y, ⟦(⟨λ i, f i (x.1 i) (y.1 i), x.2 + y.2, λ i, _⟩ : pre ι β)⟧) _, { cases x.3 i with h1 h1, { left, rw multiset.mem_add, left, exact h1 }, cases y.3 i with h2 h2, { left, rw multiset.mem_add, right, exact h2 }, right, rw [h1, h2, hf] }, exact λ x₁ x₂ y₁ y₂ H1 H2, quotient.sound $ λ i, by simp only [H1 i, H2 i] end @[simp] lemma zip_with_apply (f : Π i, β₁ i → β₂ i → β i) (hf : ∀ i, f i 0 0 = 0) (g₁ : Π₀ i, β₁ i) (g₂ : Π₀ i, β₂ i) (i : ι) : zip_with f hf g₁ g₂ i = f i (g₁ i) (g₂ i) := quotient.induction_on₂ g₁ g₂ $ λ _ _, rfl end basic section algebra instance [Π i, add_monoid (β i)] : has_add (Π₀ i, β i) := ⟨zip_with (λ _, (+)) (λ _, add_zero 0)⟩ @[simp] lemma add_apply [Π i, add_monoid (β i)] (g₁ g₂ : Π₀ i, β i) (i : ι) : (g₁ + g₂) i = g₁ i + g₂ i := zip_with_apply _ _ g₁ g₂ i instance [Π i, add_monoid (β i)] : add_monoid (Π₀ i, β i) := { add_monoid . zero := 0, add := (+), add_assoc := λ f g h, ext $ λ i, by simp only [add_apply, add_assoc], zero_add := λ f, ext $ λ i, by simp only [add_apply, zero_apply, zero_add], add_zero := λ f, ext $ λ i, by simp only [add_apply, zero_apply, add_zero] } instance is_add_monoid_hom [Π i, add_monoid (β i)] {i : ι} : is_add_monoid_hom (λ g : Π₀ i : ι, β i, g i) := { map_add := λ f g, add_apply f g i, map_zero := zero_apply i } instance [Π i, add_group (β i)] : has_neg (Π₀ i, β i) := ⟨λ f, f.map_range (λ _, has_neg.neg) (λ _, neg_zero)⟩ instance [Π i, add_comm_monoid (β i)] : add_comm_monoid (Π₀ i, β i) := { add_comm := λ f g, ext $ λ i, by simp only [add_apply, add_comm], .. dfinsupp.add_monoid } @[simp] lemma neg_apply [Π i, add_group (β i)] (g : Π₀ i, β i) (i : ι) : (- g) i = - g i := map_range_apply _ _ g i instance [Π i, add_group (β i)] : add_group (Π₀ i, β i) := { add_left_neg := λ f, ext $ λ i, by simp only [add_apply, neg_apply, zero_apply, add_left_neg], .. dfinsupp.add_monoid, .. (infer_instance : has_neg (Π₀ i, β i)) } @[simp] lemma sub_apply [Π i, add_group (β i)] (g₁ g₂ : Π₀ i, β i) (i : ι) : (g₁ - g₂) i = g₁ i - g₂ i := by rw [sub_eq_add_neg]; simp [sub_eq_add_neg] instance [Π i, add_comm_group (β i)] : add_comm_group (Π₀ i, β i) := { add_comm := λ f g, ext $ λ i, by simp only [add_apply, add_comm], ..dfinsupp.add_group } /-- Dependent functions with finite support inherit a semiring action from an action on each coordinate. -/ instance {γ : Type w} [semiring γ] [Π i, add_comm_monoid (β i)] [Π i, semimodule γ (β i)] : has_scalar γ (Π₀ i, β i) := ⟨λc v, v.map_range (λ _, (•) c) (λ _, smul_zero _)⟩ @[simp] lemma smul_apply {γ : Type w} [semiring γ] [Π i, add_comm_monoid (β i)] [Π i, semimodule γ (β i)] (b : γ) (v : Π₀ i, β i) (i : ι) : (b • v) i = b • (v i) := map_range_apply _ _ v i /-- Dependent functions with finite support inherit a semimodule structure from such a structure on each coordinate. -/ instance {γ : Type w} [semiring γ] [Π i, add_comm_monoid (β i)] [Π i, semimodule γ (β i)] : semimodule γ (Π₀ i, β i) := { smul_zero := λ c, ext $ λ i, by simp only [smul_apply, smul_zero, zero_apply], zero_smul := λ c, ext $ λ i, by simp only [smul_apply, zero_smul, zero_apply], smul_add := λ c x y, ext $ λ i, by simp only [add_apply, smul_apply, smul_add], add_smul := λ c x y, ext $ λ i, by simp only [add_apply, smul_apply, add_smul], one_smul := λ x, ext $ λ i, by simp only [smul_apply, one_smul], mul_smul := λ r s x, ext $ λ i, by simp only [smul_apply, smul_smul], .. (infer_instance : has_scalar γ (Π₀ i, β i)) } end algebra section filter_and_subtype_domain /-- `filter p f` is the function which is `f i` if `p i` is true and 0 otherwise. -/ def filter [Π i, has_zero (β i)] (p : ι → Prop) [decidable_pred p] (f : Π₀ i, β i) : Π₀ i, β i := quotient.lift_on f (λ x, ⟦(⟨λ i, if p i then x.1 i else 0, x.2, λ i, or.cases_on (x.3 i) or.inl $ λ H, or.inr $ by rw [H, if_t_t]⟩ : pre ι β)⟧) $ λ x y H, quotient.sound $ λ i, by simp only [H i] @[simp] lemma filter_apply [Π i, has_zero (β i)] (p : ι → Prop) [decidable_pred p] (i : ι) (f : Π₀ i, β i) : f.filter p i = if p i then f i else 0 := quotient.induction_on f $ λ x, rfl lemma filter_apply_pos [Π i, has_zero (β i)] {p : ι → Prop} [decidable_pred p] (f : Π₀ i, β i) {i : ι} (h : p i) : f.filter p i = f i := by simp only [filter_apply, if_pos h] lemma filter_apply_neg [Π i, has_zero (β i)] {p : ι → Prop} [decidable_pred p] (f : Π₀ i, β i) {i : ι} (h : ¬ p i) : f.filter p i = 0 := by simp only [filter_apply, if_neg h] lemma filter_pos_add_filter_neg [Π i, add_monoid (β i)] (f : Π₀ i, β i) (p : ι → Prop) [decidable_pred p] : f.filter p + f.filter (λi, ¬ p i) = f := ext $ λ i, by simp only [add_apply, filter_apply]; split_ifs; simp only [add_zero, zero_add] /-- `subtype_domain p f` is the restriction of the finitely supported function `f` to the subtype `p`. -/ def subtype_domain [Π i, has_zero (β i)] (p : ι → Prop) [decidable_pred p] (f : Π₀ i, β i) : Π₀ i : subtype p, β i := begin fapply quotient.lift_on f, { intro x, refine ⟦⟨λ i, x.1 (i : ι), (x.2.filter p).attach.map $ λ j, ⟨j, (multiset.mem_filter.1 j.2).2⟩, _⟩⟧, refine λ i, or.cases_on (x.3 i) (λ H, _) or.inr, left, rw multiset.mem_map, refine ⟨⟨i, multiset.mem_filter.2 ⟨H, i.2⟩⟩, _, subtype.eta _ _⟩, apply multiset.mem_attach }, intros x y H, exact quotient.sound (λ i, H i) end @[simp] lemma subtype_domain_zero [Π i, has_zero (β i)] {p : ι → Prop} [decidable_pred p] : subtype_domain p (0 : Π₀ i, β i) = 0 := rfl @[simp] lemma subtype_domain_apply [Π i, has_zero (β i)] {p : ι → Prop} [decidable_pred p] {i : subtype p} {v : Π₀ i, β i} : (subtype_domain p v) i = v i := quotient.induction_on v $ λ x, rfl @[simp] lemma subtype_domain_add [Π i, add_monoid (β i)] {p : ι → Prop} [decidable_pred p] {v v' : Π₀ i, β i} : (v + v').subtype_domain p = v.subtype_domain p + v'.subtype_domain p := ext $ λ i, by simp only [add_apply, subtype_domain_apply] instance subtype_domain.is_add_monoid_hom [Π i, add_monoid (β i)] {p : ι → Prop} [decidable_pred p] : is_add_monoid_hom (subtype_domain p : (Π₀ i : ι, β i) → Π₀ i : subtype p, β i) := { map_add := λ _ _, subtype_domain_add, map_zero := subtype_domain_zero } @[simp] lemma subtype_domain_neg [Π i, add_group (β i)] {p : ι → Prop} [decidable_pred p] {v : Π₀ i, β i} : (- v).subtype_domain p = - v.subtype_domain p := ext $ λ i, by simp only [neg_apply, subtype_domain_apply] @[simp] lemma subtype_domain_sub [Π i, add_group (β i)] {p : ι → Prop} [decidable_pred p] {v v' : Π₀ i, β i} : (v - v').subtype_domain p = v.subtype_domain p - v'.subtype_domain p := ext $ λ i, by simp only [sub_apply, subtype_domain_apply] end filter_and_subtype_domain variable [dec : decidable_eq ι] include dec section basic variable [Π i, has_zero (β i)] omit dec lemma finite_supp (f : Π₀ i, β i) : set.finite {i | f i ≠ 0} := begin classical, exact quotient.induction_on f (λ x, x.2.to_finset.finite_to_set.subset (λ i H, multiset.mem_to_finset.2 ((x.3 i).resolve_right H))) end include dec /-- Create an element of `Π₀ i, β i` from a finset `s` and a function `x` defined on this `finset`. -/ def mk (s : finset ι) (x : Π i : (↑s : set ι), β (i : ι)) : Π₀ i, β i := ⟦⟨λ i, if H : i ∈ s then x ⟨i, H⟩ else 0, s.1, λ i, if H : i ∈ s then or.inl H else or.inr $ dif_neg H⟩⟧ @[simp] lemma mk_apply {s : finset ι} {x : Π i : (↑s : set ι), β i} {i : ι} : (mk s x : Π i, β i) i = if H : i ∈ s then x ⟨i, H⟩ else 0 := rfl theorem mk_injective (s : finset ι) : function.injective (@mk ι β _ _ s) := begin intros x y H, ext i, have h1 : (mk s x : Π i, β i) i = (mk s y : Π i, β i) i, {rw H}, cases i with i hi, change i ∈ s at hi, dsimp only [mk_apply, subtype.coe_mk] at h1, simpa only [dif_pos hi] using h1 end /-- The function `single i b : Π₀ i, β i` sends `i` to `b` and all other points to `0`. -/ def single (i : ι) (b : β i) : Π₀ i, β i := mk {i} $ λ j, eq.rec_on (finset.mem_singleton.1 j.prop).symm b @[simp] lemma single_apply {i i' b} : (single i b : Π₀ i, β i) i' = (if h : i = i' then eq.rec_on h b else 0) := begin dsimp only [single], by_cases h : i = i', { have h1 : i' ∈ ({i} : finset ι) := finset.mem_singleton.2 h.symm, simp only [mk_apply, dif_pos h, dif_pos h1], refl }, { have h1 : i' ∉ ({i} : finset ι) := finset.not_mem_singleton.2 (ne.symm h), simp only [mk_apply, dif_neg h, dif_neg h1] } end @[simp] lemma single_zero {i} : (single i 0 : Π₀ i, β i) = 0 := quotient.sound $ λ j, if H : j ∈ ({i} : finset _) then by dsimp only; rw [dif_pos H]; cases finset.mem_singleton.1 H; refl else dif_neg H @[simp] lemma single_eq_same {i b} : (single i b : Π₀ i, β i) i = b := by simp only [single_apply, dif_pos rfl] lemma single_eq_of_ne {i i' b} (h : i ≠ i') : (single i b : Π₀ i, β i) i' = 0 := by simp only [single_apply, dif_neg h] lemma single_injective {i} : function.injective (single i : β i → Π₀ i, β i) := λ x y H, congr_fun (mk_injective _ H) ⟨i, by simp⟩ /-- Like `finsupp.single_eq_single_iff`, but with a `heq` due to dependent types -/ lemma single_eq_single_iff (i j : ι) (xi : β i) (xj : β j) : dfinsupp.single i xi = dfinsupp.single j xj ↔ i = j ∧ xi == xj ∨ xi = 0 ∧ xj = 0 := begin split, { intro h, by_cases hij : i = j, { subst hij, exact or.inl ⟨rfl, heq_of_eq (dfinsupp.single_injective h)⟩, }, { have h_coe : ⇑(dfinsupp.single i xi) = dfinsupp.single j xj := congr_arg coe_fn h, have hci := congr_fun h_coe i, have hcj := congr_fun h_coe j, rw dfinsupp.single_eq_same at hci hcj, rw dfinsupp.single_eq_of_ne (ne.symm hij) at hci, rw dfinsupp.single_eq_of_ne (hij) at hcj, exact or.inr ⟨hci, hcj.symm⟩, }, }, { rintros (⟨hi, hxi⟩ | ⟨hi, hj⟩), { subst hi, rw eq_of_heq hxi, }, { rw [hi, hj, dfinsupp.single_zero, dfinsupp.single_zero], }, }, end /-- Redefine `f i` to be `0`. -/ def erase (i : ι) (f : Π₀ i, β i) : Π₀ i, β i := quotient.lift_on f (λ x, ⟦(⟨λ j, if j = i then 0 else x.1 j, x.2, λ j, or.cases_on (x.3 j) or.inl $ λ H, or.inr $ by simp only [H, if_t_t]⟩ : pre ι β)⟧) $ λ x y H, quotient.sound $ λ j, if h : j = i then by simp only [if_pos h] else by simp only [if_neg h, H j] @[simp] lemma erase_apply {i j : ι} {f : Π₀ i, β i} : (f.erase i) j = if j = i then 0 else f j := quotient.induction_on f $ λ x, rfl @[simp] lemma erase_same {i : ι} {f : Π₀ i, β i} : (f.erase i) i = 0 := by simp lemma erase_ne {i i' : ι} {f : Π₀ i, β i} (h : i' ≠ i) : (f.erase i) i' = f i' := by simp [h] end basic section add_monoid variable [Π i, add_monoid (β i)] @[simp] lemma single_add {i : ι} {b₁ b₂ : β i} : single i (b₁ + b₂) = single i b₁ + single i b₂ := ext $ assume i', begin by_cases h : i = i', { subst h, simp only [add_apply, single_eq_same] }, { simp only [add_apply, single_eq_of_ne h, zero_add] } end variables (β) /-- `dfinsupp.single` as an `add_monoid_hom`. -/ @[simps] def single_add_hom (i : ι) : β i →+ Π₀ i, β i := { to_fun := single i, map_zero' := single_zero, map_add' := λ _ _, single_add } variables {β} lemma single_add_erase {i : ι} {f : Π₀ i, β i} : single i (f i) + f.erase i = f := ext $ λ i', if h : i = i' then by subst h; simp only [add_apply, single_apply, erase_apply, dif_pos rfl, if_pos, add_zero] else by simp only [add_apply, single_apply, erase_apply, dif_neg h, if_neg (ne.symm h), zero_add] lemma erase_add_single {i : ι} {f : Π₀ i, β i} : f.erase i + single i (f i) = f := ext $ λ i', if h : i = i' then by subst h; simp only [add_apply, single_apply, erase_apply, dif_pos rfl, if_pos, zero_add] else by simp only [add_apply, single_apply, erase_apply, dif_neg h, if_neg (ne.symm h), add_zero] protected theorem induction {p : (Π₀ i, β i) → Prop} (f : Π₀ i, β i) (h0 : p 0) (ha : ∀i b (f : Π₀ i, β i), f i = 0 → b ≠ 0 → p f → p (single i b + f)) : p f := begin refine quotient.induction_on f (λ x, _), cases x with f s H, revert f H, apply multiset.induction_on s, { intros f H, convert h0, ext i, exact (H i).resolve_left id }, intros i s ih f H, by_cases H1 : i ∈ s, { have H2 : ∀ j, j ∈ s ∨ f j = 0, { intro j, cases H j with H2 H2, { cases multiset.mem_cons.1 H2 with H3 H3, { left, rw H3, exact H1 }, { left, exact H3 } }, right, exact H2 }, have H3 : (⟦{to_fun := f, pre_support := i ::ₘ s, zero := H}⟧ : Π₀ i, β i) = ⟦{to_fun := f, pre_support := s, zero := H2}⟧, { exact quotient.sound (λ i, rfl) }, rw H3, apply ih }, have H2 : p (erase i ⟦{to_fun := f, pre_support := i ::ₘ s, zero := H}⟧), { dsimp only [erase, quotient.lift_on_beta], have H2 : ∀ j, j ∈ s ∨ ite (j = i) 0 (f j) = 0, { intro j, cases H j with H2 H2, { cases multiset.mem_cons.1 H2 with H3 H3, { right, exact if_pos H3 }, { left, exact H3 } }, right, split_ifs; [refl, exact H2] }, have H3 : (⟦{to_fun := λ (j : ι), ite (j = i) 0 (f j), pre_support := i ::ₘ s, zero := _}⟧ : Π₀ i, β i) = ⟦{to_fun := λ (j : ι), ite (j = i) 0 (f j), pre_support := s, zero := H2}⟧ := quotient.sound (λ i, rfl), rw H3, apply ih }, have H3 : single i _ + _ = (⟦{to_fun := f, pre_support := i ::ₘ s, zero := H}⟧ : Π₀ i, β i) := single_add_erase, rw ← H3, change p (single i (f i) + _), cases classical.em (f i = 0) with h h, { rw [h, single_zero, zero_add], exact H2 }, refine ha _ _ _ _ h H2, rw erase_same end lemma induction₂ {p : (Π₀ i, β i) → Prop} (f : Π₀ i, β i) (h0 : p 0) (ha : ∀i b (f : Π₀ i, β i), f i = 0 → b ≠ 0 → p f → p (f + single i b)) : p f := dfinsupp.induction f h0 $ λ i b f h1 h2 h3, have h4 : f + single i b = single i b + f, { ext j, by_cases H : i = j, { subst H, simp [h1] }, { simp [H] } }, eq.rec_on h4 $ ha i b f h1 h2 h3 @[simp] lemma add_closure_Union_range_single : add_submonoid.closure (⋃ i : ι, set.range (single i : β i → (Π₀ i, β i))) = ⊤ := top_unique $ λ x hx, (begin apply dfinsupp.induction x, exact add_submonoid.zero_mem _, exact λ a b f ha hb hf, add_submonoid.add_mem _ (add_submonoid.subset_closure $ set.mem_Union.2 ⟨a, set.mem_range_self _⟩) hf end) /-- If two additive homomorphisms from `Π₀ i, β i` are equal on each `single a b`, then they are equal. -/ lemma add_hom_ext {γ : Type w} [add_monoid γ] ⦃f g : (Π₀ i, β i) →+ γ⦄ (H : ∀ (i : ι) (y : β i), f (single i y) = g (single i y)) : f = g := begin refine add_monoid_hom.eq_of_eq_on_mdense add_closure_Union_range_single (λ f hf, _), simp only [set.mem_Union, set.mem_range] at hf, rcases hf with ⟨x, y, rfl⟩, apply H end /-- If two additive homomorphisms from `Π₀ i, β i` are equal on each `single a b`, then they are equal. We formulate this using equality of `add_monoid_hom`s so that `ext` tactic can apply a type-specific extensionality lemma after this one. E.g., if the fiber `M` is `ℕ` or `ℤ`, then it suffices to verify `f (single a 1) = g (single a 1)`. -/ @[ext] lemma add_hom_ext' {γ : Type w} [add_monoid γ] ⦃f g : (Π₀ i, β i) →+ γ⦄ (H : ∀ x, f.comp (single_add_hom β x) = g.comp (single_add_hom β x)) : f = g := add_hom_ext $ λ x, add_monoid_hom.congr_fun (H x) end add_monoid @[simp] lemma mk_add [Π i, add_monoid (β i)] {s : finset ι} {x y : Π i : (↑s : set ι), β i} : mk s (x + y) = mk s x + mk s y := ext $ λ i, by simp only [add_apply, mk_apply]; split_ifs; [refl, rw zero_add] @[simp] lemma mk_zero [Π i, has_zero (β i)] {s : finset ι} : mk s (0 : Π i : (↑s : set ι), β i.1) = 0 := ext $ λ i, by simp only [mk_apply]; split_ifs; refl @[simp] lemma mk_neg [Π i, add_group (β i)] {s : finset ι} {x : Π i : (↑s : set ι), β i.1} : mk s (-x) = -mk s x := ext $ λ i, by simp only [neg_apply, mk_apply]; split_ifs; [refl, rw neg_zero] @[simp] lemma mk_sub [Π i, add_group (β i)] {s : finset ι} {x y : Π i : (↑s : set ι), β i.1} : mk s (x - y) = mk s x - mk s y := ext $ λ i, by simp only [sub_apply, mk_apply]; split_ifs; [refl, rw sub_zero] instance [Π i, add_group (β i)] {s : finset ι} : is_add_group_hom (@mk ι β _ _ s) := { map_add := λ _ _, mk_add } section variables (γ : Type w) [semiring γ] [Π i, add_comm_monoid (β i)] [Π i, semimodule γ (β i)] include γ @[simp] lemma mk_smul {s : finset ι} {c : γ} (x : Π i : (↑s : set ι), β i.1) : mk s (c • x) = c • mk s x := ext $ λ i, by simp only [smul_apply, mk_apply]; split_ifs; [refl, rw smul_zero] @[simp] lemma single_smul {i : ι} {c : γ} {x : β i} : single i (c • x) = c • single i x := ext $ λ i, by simp only [smul_apply, single_apply]; split_ifs; [cases h, rw smul_zero]; refl variable β /-- `dfinsupp.mk` as a `linear_map`. -/ def lmk (s : finset ι) : (Π i : (↑s : set ι), β i.1) →ₗ[γ] Π₀ i, β i := ⟨mk s, λ _ _, mk_add, λ c x, by rw [mk_smul γ x]⟩ /-- `dfinsupp.single` as a `linear_map` -/ def lsingle (i) : β i →ₗ[γ] Π₀ i, β i := ⟨single i, λ _ _, single_add, λ _ _, single_smul _⟩ variable {β} /-- Two `R`-linear maps from `Π₀ i, β i` which agree on each `single i x` agree everywhere. -/ lemma lhom_ext {δ : Type*} [add_comm_monoid δ] [semimodule γ δ] ⦃φ ψ : (Π₀ i, β i) →ₗ[γ] δ⦄ (h : ∀ i x, φ (single i x) = ψ (single i x)) : φ = ψ := linear_map.to_add_monoid_hom_injective $ add_hom_ext h /-- Two `R`-linear maps from `Π₀ i, β i` which agree on each `single i x` agree everywhere. We formulate this fact using equality of linear maps `φ.comp (lsingle a)` and `ψ.comp (lsingle a)` so that the `ext` tactic can apply a type-specific extensionality lemma to prove equality of these maps. E.g., if `M = R`, then it suffices to verify `φ (single a 1) = ψ (single a 1)`. -/ @[ext] lemma lhom_ext' {δ : Type*} [add_comm_monoid δ] [semimodule γ δ] ⦃φ ψ : (Π₀ i, β i) →ₗ[γ] δ⦄ (h : ∀ i, φ.comp (lsingle β γ i) = ψ.comp (lsingle β γ i)) : φ = ψ := lhom_ext γ $ λ i, linear_map.congr_fun (h i) @[simp] lemma lmk_apply {s : finset ι} {x} : lmk β γ s x = mk s x := rfl @[simp] lemma lsingle_apply {i : ι} {x : β i} : lsingle β γ i x = single i x := rfl end section support_basic variables [Π i, has_zero (β i)] [Π i (x : β i), decidable (x ≠ 0)] /-- Set `{i | f x ≠ 0}` as a `finset`. -/ def support (f : Π₀ i, β i) : finset ι := quotient.lift_on f (λ x, x.2.to_finset.filter $ λ i, x.1 i ≠ 0) $ begin intros x y Hxy, ext i, split, { intro H, rcases finset.mem_filter.1 H with ⟨h1, h2⟩, rw Hxy i at h2, exact finset.mem_filter.2 ⟨multiset.mem_to_finset.2 $ (y.3 i).resolve_right h2, h2⟩ }, { intro H, rcases finset.mem_filter.1 H with ⟨h1, h2⟩, rw ← Hxy i at h2, exact finset.mem_filter.2 ⟨multiset.mem_to_finset.2 $ (x.3 i).resolve_right h2, h2⟩ }, end @[simp] theorem support_mk_subset {s : finset ι} {x : Π i : (↑s : set ι), β i.1} : (mk s x).support ⊆ s := λ i H, multiset.mem_to_finset.1 (finset.mem_filter.1 H).1 @[simp] theorem mem_support_to_fun (f : Π₀ i, β i) (i) : i ∈ f.support ↔ f i ≠ 0 := begin refine quotient.induction_on f (λ x, _), dsimp only [support, quotient.lift_on_beta], rw [finset.mem_filter, multiset.mem_to_finset], exact and_iff_right_of_imp (x.3 i).resolve_right end theorem eq_mk_support (f : Π₀ i, β i) : f = mk f.support (λ i, f i) := begin change f = mk f.support (λ i, f i.1), ext i, by_cases h : f i ≠ 0; [skip, rw [not_not] at h]; simp [h] end @[simp] lemma support_zero : (0 : Π₀ i, β i).support = ∅ := rfl lemma mem_support_iff (f : Π₀ i, β i) : ∀i:ι, i ∈ f.support ↔ f i ≠ 0 := f.mem_support_to_fun @[simp] lemma support_eq_empty {f : Π₀ i, β i} : f.support = ∅ ↔ f = 0 := ⟨λ H, ext $ by simpa [finset.ext_iff] using H, by simp {contextual:=tt}⟩ instance decidable_zero : decidable_pred (eq (0 : Π₀ i, β i)) := λ f, decidable_of_iff _ $ support_eq_empty.trans eq_comm lemma support_subset_iff {s : set ι} {f : Π₀ i, β i} : ↑f.support ⊆ s ↔ (∀i∉s, f i = 0) := by simp [set.subset_def]; exact forall_congr (assume i, not_imp_comm) lemma support_single_ne_zero {i : ι} {b : β i} (hb : b ≠ 0) : (single i b).support = {i} := begin ext j, by_cases h : i = j, { subst h, simp [hb] }, simp [ne.symm h, h] end lemma support_single_subset {i : ι} {b : β i} : (single i b).support ⊆ {i} := support_mk_subset section map_range_and_zip_with variables {β₁ : ι → Type v₁} {β₂ : ι → Type v₂} variables [Π i, has_zero (β₁ i)] [Π i, has_zero (β₂ i)] lemma map_range_def [Π i (x : β₁ i), decidable (x ≠ 0)] {f : Π i, β₁ i → β₂ i} {hf : ∀ i, f i 0 = 0} {g : Π₀ i, β₁ i} : map_range f hf g = mk g.support (λ i, f i.1 (g i.1)) := begin ext i, by_cases h : g i ≠ 0; simp at h; simp [h, hf] end @[simp] lemma map_range_single {f : Π i, β₁ i → β₂ i} {hf : ∀ i, f i 0 = 0} {i : ι} {b : β₁ i} : map_range f hf (single i b) = single i (f i b) := dfinsupp.ext $ λ i', by by_cases i = i'; [{subst i', simp}, simp [h, hf]] variables [Π i (x : β₁ i), decidable (x ≠ 0)] [Π i (x : β₂ i), decidable (x ≠ 0)] lemma support_map_range {f : Π i, β₁ i → β₂ i} {hf : ∀ i, f i 0 = 0} {g : Π₀ i, β₁ i} : (map_range f hf g).support ⊆ g.support := by simp [map_range_def] lemma zip_with_def {f : Π i, β₁ i → β₂ i → β i} {hf : ∀ i, f i 0 0 = 0} {g₁ : Π₀ i, β₁ i} {g₂ : Π₀ i, β₂ i} : zip_with f hf g₁ g₂ = mk (g₁.support ∪ g₂.support) (λ i, f i.1 (g₁ i.1) (g₂ i.1)) := begin ext i, by_cases h1 : g₁ i ≠ 0; by_cases h2 : g₂ i ≠ 0; simp only [not_not, ne.def] at h1 h2; simp [h1, h2, hf] end lemma support_zip_with {f : Π i, β₁ i → β₂ i → β i} {hf : ∀ i, f i 0 0 = 0} {g₁ : Π₀ i, β₁ i} {g₂ : Π₀ i, β₂ i} : (zip_with f hf g₁ g₂).support ⊆ g₁.support ∪ g₂.support := by simp [zip_with_def] end map_range_and_zip_with lemma erase_def (i : ι) (f : Π₀ i, β i) : f.erase i = mk (f.support.erase i) (λ j, f j.1) := by { ext j, by_cases h1 : j = i; by_cases h2 : f j ≠ 0; simp at h2; simp [h1, h2] } @[simp] lemma support_erase (i : ι) (f : Π₀ i, β i) : (f.erase i).support = f.support.erase i := by { ext j, by_cases h1 : j = i; by_cases h2 : f j ≠ 0; simp at h2; simp [h1, h2] } section filter_and_subtype_domain variables {p : ι → Prop} [decidable_pred p] lemma filter_def (f : Π₀ i, β i) : f.filter p = mk (f.support.filter p) (λ i, f i.1) := by ext i; by_cases h1 : p i; by_cases h2 : f i ≠ 0; simp at h2; simp [h1, h2] @[simp] lemma support_filter (f : Π₀ i, β i) : (f.filter p).support = f.support.filter p := by ext i; by_cases h : p i; simp [h] lemma subtype_domain_def (f : Π₀ i, β i) : f.subtype_domain p = mk (f.support.subtype p) (λ i, f i) := by ext i; by_cases h1 : p i; by_cases h2 : f i ≠ 0; try {simp at h2}; dsimp; simp [h1, h2, ← subtype.val_eq_coe] @[simp] lemma support_subtype_domain {f : Π₀ i, β i} : (subtype_domain p f).support = f.support.subtype p := by ext i; by_cases h1 : p i; by_cases h2 : f i ≠ 0; try {simp at h2}; dsimp; simp [h1, h2] end filter_and_subtype_domain end support_basic lemma support_add [Π i, add_monoid (β i)] [Π i (x : β i), decidable (x ≠ 0)] {g₁ g₂ : Π₀ i, β i} : (g₁ + g₂).support ⊆ g₁.support ∪ g₂.support := support_zip_with @[simp] lemma support_neg [Π i, add_group (β i)] [Π i (x : β i), decidable (x ≠ 0)] {f : Π₀ i, β i} : support (-f) = support f := by ext i; simp lemma support_smul {γ : Type w} [semiring γ] [Π i, add_comm_monoid (β i)] [Π i, semimodule γ (β i)] [Π ( i : ι) (x : β i), decidable (x ≠ 0)] (b : γ) (v : Π₀ i, β i) : (b • v).support ⊆ v.support := support_map_range instance [Π i, has_zero (β i)] [Π i, decidable_eq (β i)] : decidable_eq (Π₀ i, β i) := assume f g, decidable_of_iff (f.support = g.support ∧ (∀i∈f.support, f i = g i)) ⟨assume ⟨h₁, h₂⟩, ext $ assume i, if h : i ∈ f.support then h₂ i h else have hf : f i = 0, by rwa [f.mem_support_iff, not_not] at h, have hg : g i = 0, by rwa [h₁, g.mem_support_iff, not_not] at h, by rw [hf, hg], by intro h; subst h; simp⟩ section prod_and_sum variables {γ : Type w} -- [to_additive sum] for dfinsupp.prod doesn't work, the equation lemmas are not generated /-- `sum f g` is the sum of `g i (f i)` over the support of `f`. -/ def sum [Π i, has_zero (β i)] [Π i (x : β i), decidable (x ≠ 0)] [add_comm_monoid γ] (f : Π₀ i, β i) (g : Π i, β i → γ) : γ := ∑ i in f.support, g i (f i) /-- `prod f g` is the product of `g i (f i)` over the support of `f`. -/ @[to_additive] def prod [Π i, has_zero (β i)] [Π i (x : β i), decidable (x ≠ 0)] [comm_monoid γ] (f : Π₀ i, β i) (g : Π i, β i → γ) : γ := ∏ i in f.support, g i (f i) @[to_additive] lemma prod_map_range_index {β₁ : ι → Type v₁} {β₂ : ι → Type v₂} [Π i, has_zero (β₁ i)] [Π i, has_zero (β₂ i)] [Π i (x : β₁ i), decidable (x ≠ 0)] [Π i (x : β₂ i), decidable (x ≠ 0)] [comm_monoid γ] {f : Π i, β₁ i → β₂ i} {hf : ∀ i, f i 0 = 0} {g : Π₀ i, β₁ i} {h : Π i, β₂ i → γ} (h0 : ∀i, h i 0 = 1) : (map_range f hf g).prod h = g.prod (λi b, h i (f i b)) := begin rw [map_range_def], refine (finset.prod_subset support_mk_subset _).trans _, { intros i h1 h2, dsimp, simp [h1] at h2, dsimp at h2, simp [h1, h2, h0] }, { refine finset.prod_congr rfl _, intros i h1, simp [h1] } end @[to_additive] lemma prod_zero_index [Π i, add_comm_monoid (β i)] [Π i (x : β i), decidable (x ≠ 0)] [comm_monoid γ] {h : Π i, β i → γ} : (0 : Π₀ i, β i).prod h = 1 := rfl @[to_additive] lemma prod_single_index [Π i, has_zero (β i)] [Π i (x : β i), decidable (x ≠ 0)] [comm_monoid γ] {i : ι} {b : β i} {h : Π i, β i → γ} (h_zero : h i 0 = 1) : (single i b).prod h = h i b := begin by_cases h : b ≠ 0, { simp [dfinsupp.prod, support_single_ne_zero h] }, { rw [not_not] at h, simp [h, prod_zero_index, h_zero], refl } end @[to_additive] lemma prod_neg_index [Π i, add_group (β i)] [Π i (x : β i), decidable (x ≠ 0)] [comm_monoid γ] {g : Π₀ i, β i} {h : Π i, β i → γ} (h0 : ∀i, h i 0 = 1) : (-g).prod h = g.prod (λi b, h i (- b)) := prod_map_range_index h0 omit dec @[simp] lemma sum_apply {ι₁ : Type u₁} [decidable_eq ι₁] {β₁ : ι₁ → Type v₁} [Π i₁, has_zero (β₁ i₁)] [Π i (x : β₁ i), decidable (x ≠ 0)] [Π i, add_comm_monoid (β i)] {f : Π₀ i₁, β₁ i₁} {g : Π i₁, β₁ i₁ → Π₀ i, β i} {i₂ : ι} : (f.sum g) i₂ = f.sum (λi₁ b, g i₁ b i₂) := (f.support.sum_hom (λf : Π₀ i, β i, f i₂)).symm include dec lemma support_sum {ι₁ : Type u₁} [decidable_eq ι₁] {β₁ : ι₁ → Type v₁} [Π i₁, has_zero (β₁ i₁)] [Π i (x : β₁ i), decidable (x ≠ 0)] [Π i, add_comm_monoid (β i)] [Π i (x : β i), decidable (x ≠ 0)] {f : Π₀ i₁, β₁ i₁} {g : Π i₁, β₁ i₁ → Π₀ i, β i} : (f.sum g).support ⊆ f.support.bind (λi, (g i (f i)).support) := have ∀i₁ : ι, f.sum (λ (i : ι₁) (b : β₁ i), (g i b) i₁) ≠ 0 → (∃ (i : ι₁), f i ≠ 0 ∧ ¬ (g i (f i)) i₁ = 0), from assume i₁ h, let ⟨i, hi, ne⟩ := finset.exists_ne_zero_of_sum_ne_zero h in ⟨i, (f.mem_support_iff i).mp hi, ne⟩, by simpa [finset.subset_iff, mem_support_iff, finset.mem_bind, sum_apply] using this @[simp, to_additive] lemma prod_one [Π i, add_comm_monoid (β i)] [Π i (x : β i), decidable (x ≠ 0)] [comm_monoid γ] {f : Π₀ i, β i} : f.prod (λi b, (1 : γ)) = 1 := finset.prod_const_one @[simp, to_additive] lemma prod_mul [Π i, add_comm_monoid (β i)] [Π i (x : β i), decidable (x ≠ 0)] [comm_monoid γ] {f : Π₀ i, β i} {h₁ h₂ : Π i, β i → γ} : f.prod (λi b, h₁ i b * h₂ i b) = f.prod h₁ * f.prod h₂ := finset.prod_mul_distrib @[simp, to_additive] lemma prod_inv [Π i, add_comm_monoid (β i)] [Π i (x : β i), decidable (x ≠ 0)] [comm_group γ] {f : Π₀ i, β i} {h : Π i, β i → γ} : f.prod (λi b, (h i b)⁻¹) = (f.prod h)⁻¹ := f.support.prod_hom (@has_inv.inv γ _) @[to_additive] lemma prod_add_index [Π i, add_comm_monoid (β i)] [Π i (x : β i), decidable (x ≠ 0)] [comm_monoid γ] {f g : Π₀ i, β i} {h : Π i, β i → γ} (h_zero : ∀i, h i 0 = 1) (h_add : ∀i b₁ b₂, h i (b₁ + b₂) = h i b₁ * h i b₂) : (f + g).prod h = f.prod h * g.prod h := have f_eq : ∏ i in f.support ∪ g.support, h i (f i) = f.prod h, from (finset.prod_subset (finset.subset_union_left _ _) $ by simp [mem_support_iff, h_zero] {contextual := tt}).symm, have g_eq : ∏ i in f.support ∪ g.support, h i (g i) = g.prod h, from (finset.prod_subset (finset.subset_union_right _ _) $ by simp [mem_support_iff, h_zero] {contextual := tt}).symm, calc ∏ i in (f + g).support, h i ((f + g) i) = ∏ i in f.support ∪ g.support, h i ((f + g) i) : finset.prod_subset support_add $ by simp [mem_support_iff, h_zero] {contextual := tt} ... = (∏ i in f.support ∪ g.support, h i (f i)) * (∏ i in f.support ∪ g.support, h i (g i)) : by simp [h_add, finset.prod_mul_distrib] ... = _ : by rw [f_eq, g_eq] /-- When summing over an `add_monoid_hom`, the decidability assumption is not needed, and the result is also an `add_monoid_hom`. -/ def sum_add_hom [Π i, add_monoid (β i)] [add_comm_monoid γ] (φ : Π i, β i →+ γ) : (Π₀ i, β i) →+ γ := { to_fun := (λ f, quotient.lift_on f (λ x, ∑ i in x.2.to_finset, φ i (x.1 i)) $ λ x y H, begin have H1 : x.2.to_finset ∩ y.2.to_finset ⊆ x.2.to_finset, from finset.inter_subset_left _ _, have H2 : x.2.to_finset ∩ y.2.to_finset ⊆ y.2.to_finset, from finset.inter_subset_right _ _, refine (finset.sum_subset H1 _).symm.trans ((finset.sum_congr rfl _).trans (finset.sum_subset H2 _)), { intros i H1 H2, rw finset.mem_inter at H2, rw H i, simp only [multiset.mem_to_finset] at H1 H2, rw [(y.3 i).resolve_left (mt (and.intro H1) H2), add_monoid_hom.map_zero] }, { intros i H1, rw H i }, { intros i H1 H2, rw finset.mem_inter at H2, rw ← H i, simp only [multiset.mem_to_finset] at H1 H2, rw [(x.3 i).resolve_left (mt (λ H3, and.intro H3 H1) H2), add_monoid_hom.map_zero] } end), map_add' := assume f g, begin refine quotient.induction_on f (λ x, _), refine quotient.induction_on g (λ y, _), change ∑ i in _, _ = (∑ i in _, _) + (∑ i in _, _), simp only, conv { to_lhs, congr, skip, funext, rw add_monoid_hom.map_add }, simp only [finset.sum_add_distrib], congr' 1, { refine (finset.sum_subset _ _).symm, { intro i, simp only [multiset.mem_to_finset, multiset.mem_add], exact or.inl }, { intros i H1 H2, simp only [multiset.mem_to_finset, multiset.mem_add] at H2, rw [(x.3 i).resolve_left H2, add_monoid_hom.map_zero] } }, { refine (finset.sum_subset _ _).symm, { intro i, simp only [multiset.mem_to_finset, multiset.mem_add], exact or.inr }, { intros i H1 H2, simp only [multiset.mem_to_finset, multiset.mem_add] at H2, rw [(y.3 i).resolve_left H2, add_monoid_hom.map_zero] } } end, map_zero' := rfl } @[simp] lemma sum_add_hom_single [Π i, add_monoid (β i)] [add_comm_monoid γ] (φ : Π i, β i →+ γ) (i) (x : β i) : sum_add_hom φ (single i x) = φ i x := (add_zero _).trans $ congr_arg (φ i) $ show (if H : i ∈ ({i} : finset _) then x else 0) = x, from dif_pos $ finset.mem_singleton_self i @[simp] lemma sum_add_hom_comp_single [Π i, add_comm_monoid (β i)] [add_comm_monoid γ] (f : Π i, β i →+ γ) (i : ι) : (sum_add_hom f).comp (single_add_hom β i) = f i := add_monoid_hom.ext $ λ x, sum_add_hom_single f i x /-- While we didn't need decidable instances to define it, we do to reduce it to a sum -/ lemma sum_add_hom_apply [Π i, add_monoid (β i)] [Π i (x : β i), decidable (x ≠ 0)] [add_comm_monoid γ] (φ : Π i, β i →+ γ) (f : Π₀ i, β i) : sum_add_hom φ f = f.sum (λ x, φ x) := begin refine quotient.induction_on f (λ x, _), change ∑ i in _, _ = (∑ i in finset.filter _ _, _), rw [finset.sum_filter, finset.sum_congr rfl], intros i _, dsimp only, split_ifs, refl, rw [(not_not.mp h), add_monoid_hom.map_zero], end /-- The `dfinsupp` version of `finsupp.lift_add_hom`,-/ @[simps apply symm_apply] def lift_add_hom [Π i, add_monoid (β i)] [add_comm_monoid γ] : (Π i, β i →+ γ) ≃+ ((Π₀ i, β i) →+ γ) := { to_fun := sum_add_hom, inv_fun := λ F i, F.comp (single_add_hom β i), left_inv := λ x, by { ext, simp }, right_inv := λ ψ, by { ext, simp }, map_add' := λ F G, by { ext, simp } } /-- The `dfinsupp` version of `finsupp.lift_add_hom_single_add_hom`,-/ @[simp] lemma lift_add_hom_single_add_hom [Π i, add_comm_monoid (β i)] : lift_add_hom (single_add_hom β) = add_monoid_hom.id (Π₀ i, β i) := lift_add_hom.to_equiv.apply_eq_iff_eq_symm_apply.2 rfl /-- The `dfinsupp` version of `finsupp.lift_add_hom_apply_single`,-/ lemma lift_add_hom_apply_single [Π i, add_comm_monoid (β i)] [add_comm_monoid γ] (f : Π i, β i →+ γ) (i : ι) (x : β i) : lift_add_hom f (single i x) = f i x := by simp /-- The `dfinsupp` version of `finsupp.lift_add_hom_comp_single`,-/ lemma lift_add_hom_comp_single [Π i, add_comm_monoid (β i)] [add_comm_monoid γ] (f : Π i, β i →+ γ) (i : ι) : (lift_add_hom f).comp (single_add_hom β i) = f i := by simp /-- The `dfinsupp` version of `finsupp.comp_lift_add_hom`,-/ lemma comp_lift_add_hom {δ : Type*} [Π i, add_comm_monoid (β i)] [add_comm_monoid γ] [add_comm_monoid δ] (g : γ →+ δ) (f : Π i, β i →+ γ) : g.comp (lift_add_hom f) = lift_add_hom (λ a, g.comp (f a)) := lift_add_hom.symm_apply_eq.1 $ funext $ λ a, by rw [lift_add_hom_symm_apply, add_monoid_hom.comp_assoc, lift_add_hom_comp_single] lemma sum_sub_index [Π i, add_comm_group (β i)] [Π i (x : β i), decidable (x ≠ 0)] [add_comm_group γ] {f g : Π₀ i, β i} {h : Π i, β i → γ} (h_sub : ∀i b₁ b₂, h i (b₁ - b₂) = h i b₁ - h i b₂) : (f - g).sum h = f.sum h - g.sum h := begin have := (lift_add_hom (λ a, add_monoid_hom.of_map_sub (h a) (h_sub a))).map_sub f g, rw [lift_add_hom_apply, sum_add_hom_apply, sum_add_hom_apply, sum_add_hom_apply] at this, exact this, end @[to_additive] lemma prod_finset_sum_index {γ : Type w} {α : Type x} [Π i, add_comm_monoid (β i)] [Π i (x : β i), decidable (x ≠ 0)] [comm_monoid γ] {s : finset α} {g : α → Π₀ i, β i} {h : Π i, β i → γ} (h_zero : ∀i, h i 0 = 1) (h_add : ∀i b₁ b₂, h i (b₁ + b₂) = h i b₁ * h i b₂) : ∏ i in s, (g i).prod h = (∑ i in s, g i).prod h := begin classical, exact finset.induction_on s (by simp [prod_zero_index]) (by simp [prod_add_index, h_zero, h_add] {contextual := tt}) end @[to_additive] lemma prod_sum_index {ι₁ : Type u₁} [decidable_eq ι₁] {β₁ : ι₁ → Type v₁} [Π i₁, has_zero (β₁ i₁)] [Π i (x : β₁ i), decidable (x ≠ 0)] [Π i, add_comm_monoid (β i)] [Π i (x : β i), decidable (x ≠ 0)] [comm_monoid γ] {f : Π₀ i₁, β₁ i₁} {g : Π i₁, β₁ i₁ → Π₀ i, β i} {h : Π i, β i → γ} (h_zero : ∀i, h i 0 = 1) (h_add : ∀i b₁ b₂, h i (b₁ + b₂) = h i b₁ * h i b₂) : (f.sum g).prod h = f.prod (λi b, (g i b).prod h) := (prod_finset_sum_index h_zero h_add).symm @[simp] lemma sum_single [Π i, add_comm_monoid (β i)] [Π i (x : β i), decidable (x ≠ 0)] {f : Π₀ i, β i} : f.sum single = f := begin have := add_monoid_hom.congr_fun lift_add_hom_single_add_hom f, rw [lift_add_hom_apply, sum_add_hom_apply] at this, exact this, end /-- The `dfinsupp` version of `finsupp.lsum`,-/ @[simps apply symm_apply] def lsum {R : Type*} [semiring R] [Π i, add_comm_monoid (β i)] [Π i, semimodule R (β i)] [add_comm_monoid γ] [semimodule R γ] : (Π i, β i →ₗ[R] γ) ≃+ ((Π₀ i, β i) →ₗ[R] γ) := { to_fun := λ F, { to_fun := sum_add_hom (λ i, (F i).to_add_monoid_hom), map_add' := (lift_add_hom (λ i, (F i).to_add_monoid_hom)).map_add, map_smul' := λ c f, by { apply dfinsupp.induction f, { rw [smul_zero, add_monoid_hom.map_zero, smul_zero] }, { intros a b f ha hb hf, rw [smul_add, add_monoid_hom.map_add, add_monoid_hom.map_add, smul_add, hf, ←single_smul, sum_add_hom_single, sum_add_hom_single, linear_map.to_add_monoid_hom_coe, linear_map.map_smul], } } }, inv_fun := λ F i, F.comp (lsingle β R i), left_inv := λ F, by { ext x y, simp }, right_inv := λ F, by { ext x y, simp }, map_add' := λ F G, by { ext x y, simp } } @[to_additive] lemma prod_subtype_domain_index [Π i, has_zero (β i)] [Π i (x : β i), decidable (x ≠ 0)] [comm_monoid γ] {v : Π₀ i, β i} {p : ι → Prop} [decidable_pred p] {h : Π i, β i → γ} (hp : ∀ x ∈ v.support, p x) : (v.subtype_domain p).prod (λi b, h i b) = v.prod h := finset.prod_bij (λp _, p) (by simp) (by simp) (assume ⟨a₀, ha₀⟩ ⟨a₁, ha₁⟩, by simp) (λ i hi, ⟨⟨i, hp i hi⟩, by simpa using hi, rfl⟩) omit dec lemma subtype_domain_sum [Π i, add_comm_monoid (β i)] {s : finset γ} {h : γ → Π₀ i, β i} {p : ι → Prop} [decidable_pred p] : (∑ c in s, h c).subtype_domain p = ∑ c in s, (h c).subtype_domain p := eq.symm (s.sum_hom _) lemma subtype_domain_finsupp_sum {δ : γ → Type x} [decidable_eq γ] [Π c, has_zero (δ c)] [Π c (x : δ c), decidable (x ≠ 0)] [Π i, add_comm_monoid (β i)] {p : ι → Prop} [decidable_pred p] {s : Π₀ c, δ c} {h : Π c, δ c → Π₀ i, β i} : (s.sum h).subtype_domain p = s.sum (λc d, (h c d).subtype_domain p) := subtype_domain_sum end prod_and_sum end dfinsupp
1b7231f39f3cfc3c1b37a62b122d12939c979d53
957a80ea22c5abb4f4670b250d55534d9db99108
/library/init/category/state.lean
0d879655224c8aaedb040fefd091d4c208533617
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
3,648
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.interactive universes u v def state (σ α : Type u) : Type u := σ → α × σ section variables {σ α β : Type u} @[inline] def state_return (a : α) : state σ α := λ s, (a, s) @[inline] def state_bind (a : state σ α) (b : α → state σ β) : state σ β := λ s, match (a s) with (a', s') := b a' s' end instance (σ : Type u) : monad (state σ) := {pure := @state_return σ, bind := @state_bind σ, id_map := begin intros, apply funext, intro s, simp [state_bind], cases x s, apply rfl end, pure_bind := by intros; apply rfl, bind_assoc := begin intros, apply funext, intro s, simp [state_bind], cases x s, apply rfl end} end namespace state @[inline] def read {σ : Type u} : state σ σ := λ s, (s, s) @[inline] def write {σ : Type} : σ → state σ unit := λ s' s, ((), s') @[inline] def write' {σ : Type u} : σ → state σ punit := λ s' s, (punit.star, s') end state def state_t (σ : Type u) (m : Type u → Type v) [monad m] (α : Type u) : Type (max u v) := σ → m (α × σ) section variable {σ : Type u} variable {m : Type u → Type v} variable [monad m] variables {α β : Type u} def state_t_return (a : α) : state_t σ m α := λ s, show m (α × σ), from return (a, s) def state_t_bind (act₁ : state_t σ m α) (act₂ : α → state_t σ m β) : state_t σ m β := λ s, show m (β × σ), from do (a, new_s) ← act₁ s, act₂ a new_s end instance (σ : Type u) (m : Type u → Type v) [monad m] : monad (state_t σ m) := {pure := @state_t_return σ m _, bind := @state_t_bind σ m _, id_map := begin intros, apply funext, intro, simp [state_t_bind, state_t_return, function.comp, return], have h : state_t_bind._match_1 (λ (x : α) (s : σ), @pure m _ _ (x, s)) = pure, { apply funext, intro s, cases s, apply rfl }, { rw h, apply @monad.bind_pure _ σ }, end, pure_bind := begin intros, apply funext, intro, simp [state_t_bind, state_t_return, monad.pure_bind] end, bind_assoc := begin intros, apply funext, intro, simp [state_t_bind, state_t_return, monad.bind_assoc], apply congr_arg, apply funext, intro r, cases r, refl end} section variable {σ : Type u} variable {m : Type u → Type v} variable [monad m] variable [alternative m] variable {α : Type u} def state_t_orelse (act₁ act₂ : state_t σ m α) : state_t σ m α := λ s, act₁ s <|> act₂ s def state_t_failure : state_t σ m α := λ s, failure end instance (σ : Type u) (m : Type u → Type v) [alternative m] [monad m] : alternative (state_t σ m) := { state_t.monad σ m with failure := @state_t_failure σ m _ _, orelse := @state_t_orelse σ m _ _ } namespace state_t def read {σ : Type u} {m : Type u → Type v} [monad m] : state_t σ m σ := λ s, return (s, s) def write {σ : Type} {m : Type → Type v} [monad m] : σ → state_t σ m unit := λ s' s, return ((), s') def write' {σ : Type u} {m : Type u → Type v} [monad m] : σ → state_t σ m punit := λ s' s, return (punit.star, s') def modify {σ : Type} {m : Type → Type v} [monad m] (f : σ → σ) : state_t σ m unit := do s ← read, write (f s) def modify' {σ : Type u} {m : Type u → Type v} [monad m] (f : σ → σ) : state_t σ m punit := do s ← read, write' (f s) def lift {α σ : Type u} {m : Type u → Type v} [monad m] (t : m α) : state_t σ m α := λ s, do a ← t, return (a, s) end state_t
4908d662b49d48499d3a3c0a98a91d0925e32df7
367134ba5a65885e863bdc4507601606690974c1
/archive/imo/imo1964_q1.lean
4e98e810eccb32fe0a96c9ffc9bf1bab403a7862
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
2,877
lean
/- Copyright (c) 2020 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard -/ import tactic import data.nat.modeq /-! # IMO 1964 Q1 (a) Find all positive integers $n$ for which $2^n-1$ is divisible by $7$. (b) Prove that there is no positive integer $n$ for which $2^n+1$ is divisible by $7$. We define a predicate for the solutions in (a), and prove that it is the set of positive integers which are a multiple of 3. -/ /-! ## Intermediate lemmas -/ open nat.modeq lemma two_pow_three_mul_mod_seven (m : ℕ) : 2 ^ (3 * m) ≡ 1 [MOD 7] := begin rw pow_mul, have h : 8 ≡ 1 [MOD 7] := modeq_of_dvd (by {use -1, norm_num }), convert modeq_pow _ h, simp, end lemma two_pow_three_mul_add_one_mod_seven (m : ℕ) : 2 ^ (3 * m + 1) ≡ 2 [MOD 7] := begin rw pow_add, exact modeq_mul (two_pow_three_mul_mod_seven m) (show 2 ^ 1 ≡ 2 [MOD 7], by refl), end lemma two_pow_three_mul_add_two_mod_seven (m : ℕ) : 2 ^ (3 * m + 2) ≡ 4 [MOD 7] := begin rw pow_add, exact modeq_mul (two_pow_three_mul_mod_seven m) (show 2 ^ 2 ≡ 4 [MOD 7], by refl), end /-! ## The question -/ def problem_predicate (n : ℕ) : Prop := 7 ∣ 2 ^ n - 1 lemma aux (n : ℕ) : problem_predicate n ↔ 2 ^ n ≡ 1 [MOD 7] := begin rw nat.modeq.comm, apply (modeq_iff_dvd' _).symm, apply nat.one_le_pow' end theorem imo1964_q1a (n : ℕ) (hn : 0 < n) : problem_predicate n ↔ 3 ∣ n := begin rw aux, split, { intro h, let t := n % 3, rw [(show n = 3 * (n / 3) + t, from (nat.div_add_mod n 3).symm)] at h, have ht : t < 3 := nat.mod_lt _ dec_trivial, interval_cases t with hr; rw hr at h, { exact nat.dvd_of_mod_eq_zero hr }, { exfalso, have nonsense := (two_pow_three_mul_add_one_mod_seven _).symm.trans h, rw modeq_iff_dvd at nonsense, norm_num at nonsense }, { exfalso, have nonsense := (two_pow_three_mul_add_two_mod_seven _).symm.trans h, rw modeq_iff_dvd at nonsense, norm_num at nonsense } }, { rintro ⟨m, rfl⟩, apply two_pow_three_mul_mod_seven } end theorem imo1964_q1b (n : ℕ) : ¬ (7 ∣ 2 ^ n + 1) := begin let t := n % 3, rw [← modeq_zero_iff, (show n = 3 * (n / 3) + t, from (nat.div_add_mod n 3).symm)], have ht : t < 3 := nat.mod_lt _ dec_trivial, interval_cases t with hr; rw hr, { rw add_zero, intro h, have := h.symm.trans (modeq_add (two_pow_three_mul_mod_seven _) (nat.modeq.refl _)), rw modeq_iff_dvd at this, norm_num at this }, { intro h, have := h.symm.trans (modeq_add (two_pow_three_mul_add_one_mod_seven _) (nat.modeq.refl _)), rw modeq_iff_dvd at this, norm_num at this }, { intro h, have := h.symm.trans (modeq_add (two_pow_three_mul_add_two_mod_seven _) (nat.modeq.refl _)), rw modeq_iff_dvd at this, norm_num at this }, end
7b97631f1bf648ee2559328307fabbedef090c76
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/topology/metric_space/basic.lean
614e336e1644e2bca19492b7d5a3249aca82f4f6
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
103,831
lean
/- Copyright (c) 2015, 2017 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Robert Y. Lewis, Johannes Hölzl, Mario Carneiro, Sébastien Gouëzel -/ import data.int.interval import topology.algebra.ordered.compact import topology.metric_space.emetric_space /-! # Metric spaces This file defines metric spaces. Many definitions and theorems expected on metric spaces are already introduced on uniform spaces and topological spaces. For example: open and closed sets, compactness, completeness, continuity and uniform continuity ## Main definitions * `has_dist α`: Endows a space `α` with a function `dist a b`. * `pseudo_metric_space α`: A space endowed with a distance function, which can be zero even if the two elements are non-equal. * `metric.ball x ε`: The set of all points `y` with `dist y x < ε`. * `metric.bounded s`: Whether a subset of a `pseudo_metric_space` is bounded. * `metric_space α`: A `pseudo_metric_space` with the guarantee `dist x y = 0 → x = y`. Additional useful definitions: * `nndist a b`: `dist` as a function to the non-negative reals. * `metric.closed_ball x ε`: The set of all points `y` with `dist y x ≤ ε`. * `metric.sphere x ε`: The set of all points `y` with `dist y x = ε`. * `proper_space α`: A `pseudo_metric_space` where all closed balls are compact. * `metric.diam s` : The `supr` of the distances of members of `s`. Defined in terms of `emetric.diam`, for better handling of the case when it should be infinite. TODO (anyone): Add "Main results" section. ## Implementation notes Since a lot of elementary properties don't require `eq_of_dist_eq_zero` we start setting up the theory of `pseudo_metric_space`, where we don't require `dist x y = 0 → x = y` and we specialize to `metric_space` at the end. ## Tags metric, pseudo_metric, dist -/ open set filter topological_space open_locale uniformity topological_space big_operators filter nnreal ennreal universes u v w variables {α : Type u} {β : Type v} /-- Construct a uniform structure core from a distance function and metric space axioms. This is a technical construction that can be immediately used to construct a uniform structure from a distance function and metric space axioms but is also useful when discussing metrizable topologies, see `pseudo_metric_space.of_metrizable`. -/ def uniform_space.core_of_dist {α : Type*} (dist : α → α → ℝ) (dist_self : ∀ x : α, dist x x = 0) (dist_comm : ∀ x y : α, dist x y = dist y x) (dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) : uniform_space.core α := { uniformity := (⨅ ε>0, 𝓟 {p:α×α | dist p.1 p.2 < ε}), refl := le_infi $ assume ε, le_infi $ by simp [set.subset_def, id_rel, dist_self, (>)] {contextual := tt}, comp := le_infi $ assume ε, le_infi $ assume h, lift'_le (mem_infi_of_mem (ε / 2) $ mem_infi_of_mem (div_pos h zero_lt_two) (subset.refl _)) $ have ∀ (a b c : α), dist a c < ε / 2 → dist c b < ε / 2 → dist a b < ε, from assume a b c hac hcb, calc dist a b ≤ dist a c + dist c b : dist_triangle _ _ _ ... < ε / 2 + ε / 2 : add_lt_add hac hcb ... = ε : by rw [div_add_div_same, add_self_div_two], by simpa [comp_rel], symm := tendsto_infi.2 $ assume ε, tendsto_infi.2 $ assume h, tendsto_infi' ε $ tendsto_infi' h $ tendsto_principal_principal.2 $ by simp [dist_comm] } /-- Construct a uniform structure from a distance function and metric space axioms -/ def uniform_space_of_dist (dist : α → α → ℝ) (dist_self : ∀ x : α, dist x x = 0) (dist_comm : ∀ x y : α, dist x y = dist y x) (dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) : uniform_space α := uniform_space.of_core (uniform_space.core_of_dist dist dist_self dist_comm dist_triangle) /-- The distance function (given an ambient metric space on `α`), which returns a nonnegative real number `dist x y` given `x y : α`. -/ class has_dist (α : Type*) := (dist : α → α → ℝ) export has_dist (dist) -- the uniform structure and the emetric space structure are embedded in the metric space structure -- to avoid instance diamond issues. See Note [forgetful inheritance]. /-- This is an internal lemma used inside the default of `pseudo_metric_space.edist`. -/ private theorem pseudo_metric_space.dist_nonneg' {α} {x y : α} (dist : α → α → ℝ) (dist_self : ∀ x : α, dist x x = 0) (dist_comm : ∀ x y : α, dist x y = dist y x) (dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z): 0 ≤ dist x y := have 2 * dist x y ≥ 0, from calc 2 * dist x y = dist x y + dist y x : by rw [dist_comm x y, two_mul] ... ≥ 0 : by rw ← dist_self x; apply dist_triangle, nonneg_of_mul_nonneg_left this zero_lt_two /-- This tactic is used to populate `pseudo_metric_space.edist_dist` when the default `edist` is used. -/ protected meta def pseudo_metric_space.edist_dist_tac : tactic unit := tactic.intros >> `[exact (ennreal.of_real_eq_coe_nnreal _).symm <|> control_laws_tac] /-- Metric space Each metric space induces a canonical `uniform_space` and hence a canonical `topological_space`. This is enforced in the type class definition, by extending the `uniform_space` structure. When instantiating a `metric_space` structure, the uniformity fields are not necessary, they will be filled in by default. In the same way, each metric space induces an emetric space structure. It is included in the structure, but filled in by default. -/ class pseudo_metric_space (α : Type u) extends has_dist α : Type u := (dist_self : ∀ x : α, dist x x = 0) (dist_comm : ∀ x y : α, dist x y = dist y x) (dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) (edist : α → α → ℝ≥0∞ := λ x y, @coe (ℝ≥0) _ _ ⟨dist x y, pseudo_metric_space.dist_nonneg' _ ‹_› ‹_› ‹_›⟩) (edist_dist : ∀ x y : α, edist x y = ennreal.of_real (dist x y) . pseudo_metric_space.edist_dist_tac) (to_uniform_space : uniform_space α := uniform_space_of_dist dist dist_self dist_comm dist_triangle) (uniformity_dist : 𝓤 α = ⨅ ε>0, 𝓟 {p:α×α | dist p.1 p.2 < ε} . control_laws_tac) variables [pseudo_metric_space α] @[priority 100] -- see Note [lower instance priority] instance metric_space.to_uniform_space' : uniform_space α := pseudo_metric_space.to_uniform_space @[priority 200] -- see Note [lower instance priority] instance pseudo_metric_space.to_has_edist : has_edist α := ⟨pseudo_metric_space.edist⟩ /-- Construct a pseudo-metric space structure whose underlying topological space structure (definitionally) agrees which a pre-existing topology which is compatible with a given distance function. -/ def pseudo_metric_space.of_metrizable {α : Type*} [topological_space α] (dist : α → α → ℝ) (dist_self : ∀ x : α, dist x x = 0) (dist_comm : ∀ x y : α, dist x y = dist y x) (dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) (H : ∀ s : set α, is_open s ↔ ∀ x ∈ s, ∃ ε > 0, ∀ y, dist x y < ε → y ∈ s) : pseudo_metric_space α := { dist := dist, dist_self := dist_self, dist_comm := dist_comm, dist_triangle := dist_triangle, to_uniform_space := { is_open_uniformity := begin dsimp only [uniform_space.core_of_dist], intros s, change is_open s ↔ _, rw H s, apply forall_congr, intro x, apply forall_congr, intro x_in, erw (has_basis_binfi_principal _ nonempty_Ioi).mem_iff, { apply exists_congr, intros ε, apply exists_congr, intros ε_pos, simp only [prod.forall, set_of_subset_set_of], split, { rintros h _ y H rfl, exact h y H }, { intros h y hxy, exact h _ _ hxy rfl } }, { exact λ r (hr : 0 < r) p (hp : 0 < p), ⟨min r p, lt_min hr hp, λ x (hx : dist _ _ < _), lt_of_lt_of_le hx (min_le_left r p), λ x (hx : dist _ _ < _), lt_of_lt_of_le hx (min_le_right r p)⟩ }, { apply_instance } end, ..uniform_space.core_of_dist dist dist_self dist_comm dist_triangle }, uniformity_dist := rfl } @[simp] theorem dist_self (x : α) : dist x x = 0 := pseudo_metric_space.dist_self x theorem dist_comm (x y : α) : dist x y = dist y x := pseudo_metric_space.dist_comm x y theorem edist_dist (x y : α) : edist x y = ennreal.of_real (dist x y) := pseudo_metric_space.edist_dist x y theorem dist_triangle (x y z : α) : dist x z ≤ dist x y + dist y z := pseudo_metric_space.dist_triangle x y z theorem dist_triangle_left (x y z : α) : dist x y ≤ dist z x + dist z y := by rw dist_comm z; apply dist_triangle theorem dist_triangle_right (x y z : α) : dist x y ≤ dist x z + dist y z := by rw dist_comm y; apply dist_triangle lemma dist_triangle4 (x y z w : α) : dist x w ≤ dist x y + dist y z + dist z w := calc dist x w ≤ dist x z + dist z w : dist_triangle x z w ... ≤ (dist x y + dist y z) + dist z w : add_le_add_right (dist_triangle x y z) _ lemma dist_triangle4_left (x₁ y₁ x₂ y₂ : α) : dist x₂ y₂ ≤ dist x₁ y₁ + (dist x₁ x₂ + dist y₁ y₂) := by { rw [add_left_comm, dist_comm x₁, ← add_assoc], apply dist_triangle4 } lemma dist_triangle4_right (x₁ y₁ x₂ y₂ : α) : dist x₁ y₁ ≤ dist x₁ x₂ + dist y₁ y₂ + dist x₂ y₂ := by { rw [add_right_comm, dist_comm y₁], apply dist_triangle4 } /-- The triangle (polygon) inequality for sequences of points; `finset.Ico` version. -/ lemma dist_le_Ico_sum_dist (f : ℕ → α) {m n} (h : m ≤ n) : dist (f m) (f n) ≤ ∑ i in finset.Ico m n, dist (f i) (f (i + 1)) := begin revert n, apply nat.le_induction, { simp only [finset.sum_empty, finset.Ico_self, dist_self] }, { assume n hn hrec, calc dist (f m) (f (n+1)) ≤ dist (f m) (f n) + dist _ _ : dist_triangle _ _ _ ... ≤ ∑ i in finset.Ico m n, _ + _ : add_le_add hrec (le_refl _) ... = ∑ i in finset.Ico m (n+1), _ : by rw [nat.Ico_succ_right_eq_insert_Ico hn, finset.sum_insert, add_comm]; simp } end /-- The triangle (polygon) inequality for sequences of points; `finset.range` version. -/ lemma dist_le_range_sum_dist (f : ℕ → α) (n : ℕ) : dist (f 0) (f n) ≤ ∑ i in finset.range n, dist (f i) (f (i + 1)) := nat.Ico_zero_eq_range ▸ dist_le_Ico_sum_dist f (nat.zero_le n) /-- A version of `dist_le_Ico_sum_dist` with each intermediate distance replaced with an upper estimate. -/ lemma dist_le_Ico_sum_of_dist_le {f : ℕ → α} {m n} (hmn : m ≤ n) {d : ℕ → ℝ} (hd : ∀ {k}, m ≤ k → k < n → dist (f k) (f (k + 1)) ≤ d k) : dist (f m) (f n) ≤ ∑ i in finset.Ico m n, d i := le_trans (dist_le_Ico_sum_dist f hmn) $ finset.sum_le_sum $ λ k hk, hd (finset.mem_Ico.1 hk).1 (finset.mem_Ico.1 hk).2 /-- A version of `dist_le_range_sum_dist` with each intermediate distance replaced with an upper estimate. -/ lemma dist_le_range_sum_of_dist_le {f : ℕ → α} (n : ℕ) {d : ℕ → ℝ} (hd : ∀ {k}, k < n → dist (f k) (f (k + 1)) ≤ d k) : dist (f 0) (f n) ≤ ∑ i in finset.range n, d i := nat.Ico_zero_eq_range ▸ dist_le_Ico_sum_of_dist_le (zero_le n) (λ _ _, hd) theorem swap_dist : function.swap (@dist α _) = dist := by funext x y; exact dist_comm _ _ theorem abs_dist_sub_le (x y z : α) : |dist x z - dist y z| ≤ dist x y := abs_sub_le_iff.2 ⟨sub_le_iff_le_add.2 (dist_triangle _ _ _), sub_le_iff_le_add.2 (dist_triangle_left _ _ _)⟩ theorem dist_nonneg {x y : α} : 0 ≤ dist x y := pseudo_metric_space.dist_nonneg' dist dist_self dist_comm dist_triangle @[simp] theorem abs_dist {a b : α} : |dist a b| = dist a b := abs_of_nonneg dist_nonneg /-- A version of `has_dist` that takes value in `ℝ≥0`. -/ class has_nndist (α : Type*) := (nndist : α → α → ℝ≥0) export has_nndist (nndist) /-- Distance as a nonnegative real number. -/ @[priority 100] -- see Note [lower instance priority] instance pseudo_metric_space.to_has_nndist : has_nndist α := ⟨λ a b, ⟨dist a b, dist_nonneg⟩⟩ /--Express `nndist` in terms of `edist`-/ lemma nndist_edist (x y : α) : nndist x y = (edist x y).to_nnreal := by simp [nndist, edist_dist, real.to_nnreal, max_eq_left dist_nonneg, ennreal.of_real] /--Express `edist` in terms of `nndist`-/ lemma edist_nndist (x y : α) : edist x y = ↑(nndist x y) := by { simpa only [edist_dist, ennreal.of_real_eq_coe_nnreal dist_nonneg] } @[simp, norm_cast] lemma coe_nnreal_ennreal_nndist (x y : α) : ↑(nndist x y) = edist x y := (edist_nndist x y).symm @[simp, norm_cast] lemma edist_lt_coe {x y : α} {c : ℝ≥0} : edist x y < c ↔ nndist x y < c := by rw [edist_nndist, ennreal.coe_lt_coe] @[simp, norm_cast] lemma edist_le_coe {x y : α} {c : ℝ≥0} : edist x y ≤ c ↔ nndist x y ≤ c := by rw [edist_nndist, ennreal.coe_le_coe] /--In a pseudometric space, the extended distance is always finite-/ lemma edist_lt_top {α : Type*} [pseudo_metric_space α] (x y : α) : edist x y < ⊤ := (edist_dist x y).symm ▸ ennreal.of_real_lt_top /--In a pseudometric space, the extended distance is always finite-/ lemma edist_ne_top (x y : α) : edist x y ≠ ⊤ := (edist_lt_top x y).ne /--`nndist x x` vanishes-/ @[simp] lemma nndist_self (a : α) : nndist a a = 0 := (nnreal.coe_eq_zero _).1 (dist_self a) /--Express `dist` in terms of `nndist`-/ lemma dist_nndist (x y : α) : dist x y = ↑(nndist x y) := rfl @[simp, norm_cast] lemma coe_nndist (x y : α) : ↑(nndist x y) = dist x y := (dist_nndist x y).symm @[simp, norm_cast] lemma dist_lt_coe {x y : α} {c : ℝ≥0} : dist x y < c ↔ nndist x y < c := iff.rfl @[simp, norm_cast] lemma dist_le_coe {x y : α} {c : ℝ≥0} : dist x y ≤ c ↔ nndist x y ≤ c := iff.rfl /--Express `nndist` in terms of `dist`-/ lemma nndist_dist (x y : α) : nndist x y = real.to_nnreal (dist x y) := by rw [dist_nndist, real.to_nnreal_coe] theorem nndist_comm (x y : α) : nndist x y = nndist y x := by simpa only [dist_nndist, nnreal.coe_eq] using dist_comm x y /--Triangle inequality for the nonnegative distance-/ theorem nndist_triangle (x y z : α) : nndist x z ≤ nndist x y + nndist y z := dist_triangle _ _ _ theorem nndist_triangle_left (x y z : α) : nndist x y ≤ nndist z x + nndist z y := dist_triangle_left _ _ _ theorem nndist_triangle_right (x y z : α) : nndist x y ≤ nndist x z + nndist y z := dist_triangle_right _ _ _ /--Express `dist` in terms of `edist`-/ lemma dist_edist (x y : α) : dist x y = (edist x y).to_real := by rw [edist_dist, ennreal.to_real_of_real (dist_nonneg)] namespace metric /- instantiate pseudometric space as a topology -/ variables {x y z : α} {ε ε₁ ε₂ : ℝ} {s : set α} /-- `ball x ε` is the set of all points `y` with `dist y x < ε` -/ def ball (x : α) (ε : ℝ) : set α := {y | dist y x < ε} @[simp] theorem mem_ball : y ∈ ball x ε ↔ dist y x < ε := iff.rfl theorem mem_ball' : y ∈ ball x ε ↔ dist x y < ε := by rw dist_comm; refl theorem pos_of_mem_ball (hy : y ∈ ball x ε) : 0 < ε := dist_nonneg.trans_lt hy theorem mem_ball_self (h : 0 < ε) : x ∈ ball x ε := show dist x x < ε, by rw dist_self; assumption @[simp] lemma nonempty_ball : (ball x ε).nonempty ↔ 0 < ε := ⟨λ ⟨x, hx⟩, pos_of_mem_ball hx, λ h, ⟨x, mem_ball_self h⟩⟩ @[simp] lemma ball_eq_empty : ball x ε = ∅ ↔ ε ≤ 0 := by rw [← not_nonempty_iff_eq_empty, nonempty_ball, not_lt] @[simp] lemma ball_zero : ball x 0 = ∅ := by rw [ball_eq_empty] lemma ball_eq_ball (ε : ℝ) (x : α) : uniform_space.ball x {p | dist p.2 p.1 < ε} = metric.ball x ε := rfl lemma ball_eq_ball' (ε : ℝ) (x : α) : uniform_space.ball x {p | dist p.1 p.2 < ε} = metric.ball x ε := by { ext, simp [dist_comm, uniform_space.ball] } @[simp] lemma Union_ball_nat (x : α) : (⋃ n : ℕ, ball x n) = univ := Union_eq_univ_iff.2 $ λ y, exists_nat_gt (dist y x) @[simp] lemma Union_ball_nat_succ (x : α) : (⋃ n : ℕ, ball x (n + 1)) = univ := Union_eq_univ_iff.2 $ λ y, (exists_nat_gt (dist y x)).imp $ λ n hn, hn.trans (lt_add_one _) /-- `closed_ball x ε` is the set of all points `y` with `dist y x ≤ ε` -/ def closed_ball (x : α) (ε : ℝ) := {y | dist y x ≤ ε} @[simp] theorem mem_closed_ball : y ∈ closed_ball x ε ↔ dist y x ≤ ε := iff.rfl /-- `sphere x ε` is the set of all points `y` with `dist y x = ε` -/ def sphere (x : α) (ε : ℝ) := {y | dist y x = ε} @[simp] theorem mem_sphere : y ∈ sphere x ε ↔ dist y x = ε := iff.rfl theorem mem_closed_ball' : y ∈ closed_ball x ε ↔ dist x y ≤ ε := by { rw dist_comm, refl } theorem mem_closed_ball_self (h : 0 ≤ ε) : x ∈ closed_ball x ε := show dist x x ≤ ε, by rw dist_self; assumption @[simp] lemma nonempty_closed_ball : (closed_ball x ε).nonempty ↔ 0 ≤ ε := ⟨λ ⟨x, hx⟩, dist_nonneg.trans hx, λ h, ⟨x, mem_closed_ball_self h⟩⟩ @[simp] lemma closed_ball_eq_empty : closed_ball x ε = ∅ ↔ ε < 0 := by rw [← not_nonempty_iff_eq_empty, nonempty_closed_ball, not_le] theorem ball_subset_closed_ball : ball x ε ⊆ closed_ball x ε := assume y (hy : _ < _), le_of_lt hy theorem sphere_subset_closed_ball : sphere x ε ⊆ closed_ball x ε := λ y, le_of_eq lemma ball_disjoint_ball (x y : α) (rx ry : ℝ) (h : rx + ry ≤ dist x y) : disjoint (ball x rx) (ball y ry) := begin rw disjoint_left, assume a ax ay, apply lt_irrefl (dist x y), calc dist x y ≤ dist x a + dist a y : dist_triangle _ _ _ ... < rx + ry : add_lt_add (mem_ball'.1 ax) (mem_ball.1 ay) ... ≤ dist x y : h end theorem sphere_disjoint_ball : disjoint (sphere x ε) (ball x ε) := λ y ⟨hy₁, hy₂⟩, absurd hy₁ $ ne_of_lt hy₂ @[simp] theorem ball_union_sphere : ball x ε ∪ sphere x ε = closed_ball x ε := set.ext $ λ y, (@le_iff_lt_or_eq ℝ _ _ _).symm @[simp] theorem sphere_union_ball : sphere x ε ∪ ball x ε = closed_ball x ε := by rw [union_comm, ball_union_sphere] @[simp] theorem closed_ball_diff_sphere : closed_ball x ε \ sphere x ε = ball x ε := by rw [← ball_union_sphere, set.union_diff_cancel_right sphere_disjoint_ball.symm] @[simp] theorem closed_ball_diff_ball : closed_ball x ε \ ball x ε = sphere x ε := by rw [← ball_union_sphere, set.union_diff_cancel_left sphere_disjoint_ball.symm] theorem mem_ball_comm : x ∈ ball y ε ↔ y ∈ ball x ε := by simp [dist_comm] theorem ball_subset_ball (h : ε₁ ≤ ε₂) : ball x ε₁ ⊆ ball x ε₂ := λ y (yx : _ < ε₁), lt_of_lt_of_le yx h lemma ball_subset_ball' (h : ε₁ + dist x y ≤ ε₂) : ball x ε₁ ⊆ ball y ε₂ := λ z hz, calc dist z y ≤ dist z x + dist x y : dist_triangle _ _ _ ... < ε₁ + dist x y : add_lt_add_right hz _ ... ≤ ε₂ : h theorem closed_ball_subset_closed_ball (h : ε₁ ≤ ε₂) : closed_ball x ε₁ ⊆ closed_ball x ε₂ := λ y (yx : _ ≤ ε₁), le_trans yx h lemma closed_ball_subset_closed_ball' (h : ε₁ + dist x y ≤ ε₂) : closed_ball x ε₁ ⊆ closed_ball y ε₂ := λ z hz, calc dist z y ≤ dist z x + dist x y : dist_triangle _ _ _ ... ≤ ε₁ + dist x y : add_le_add_right hz _ ... ≤ ε₂ : h theorem closed_ball_subset_ball (h : ε₁ < ε₂) : closed_ball x ε₁ ⊆ ball x ε₂ := λ y (yh : dist y x ≤ ε₁), lt_of_le_of_lt yh h lemma dist_le_add_of_nonempty_closed_ball_inter_closed_ball (h : (closed_ball x ε₁ ∩ closed_ball y ε₂).nonempty) : dist x y ≤ ε₁ + ε₂ := let ⟨z, hz⟩ := h in calc dist x y ≤ dist z x + dist z y : dist_triangle_left _ _ _ ... ≤ ε₁ + ε₂ : add_le_add hz.1 hz.2 lemma dist_lt_add_of_nonempty_closed_ball_inter_ball (h : (closed_ball x ε₁ ∩ ball y ε₂).nonempty) : dist x y < ε₁ + ε₂ := let ⟨z, hz⟩ := h in calc dist x y ≤ dist z x + dist z y : dist_triangle_left _ _ _ ... < ε₁ + ε₂ : add_lt_add_of_le_of_lt hz.1 hz.2 lemma dist_lt_add_of_nonempty_ball_inter_closed_ball (h : (ball x ε₁ ∩ closed_ball y ε₂).nonempty) : dist x y < ε₁ + ε₂ := begin rw inter_comm at h, rw [add_comm, dist_comm], exact dist_lt_add_of_nonempty_closed_ball_inter_ball h end lemma dist_lt_add_of_nonempty_ball_inter_ball (h : (ball x ε₁ ∩ ball y ε₂).nonempty) : dist x y < ε₁ + ε₂ := dist_lt_add_of_nonempty_closed_ball_inter_ball $ h.mono (inter_subset_inter ball_subset_closed_ball subset.rfl) @[simp] lemma Union_closed_ball_nat (x : α) : (⋃ n : ℕ, closed_ball x n) = univ := Union_eq_univ_iff.2 $ λ y, exists_nat_ge (dist y x) theorem ball_disjoint (h : ε₁ + ε₂ ≤ dist x y) : ball x ε₁ ∩ ball y ε₂ = ∅ := eq_empty_iff_forall_not_mem.2 $ λ z ⟨h₁, h₂⟩, not_lt_of_le (dist_triangle_left x y z) (lt_of_lt_of_le (add_lt_add h₁ h₂) h) theorem ball_disjoint_same (h : ε ≤ dist x y / 2) : ball x ε ∩ ball y ε = ∅ := ball_disjoint $ by rwa [← two_mul, ← le_div_iff' (@zero_lt_two ℝ _ _)] theorem ball_subset (h : dist x y ≤ ε₂ - ε₁) : ball x ε₁ ⊆ ball y ε₂ := λ z zx, by rw ← add_sub_cancel'_right ε₁ ε₂; exact lt_of_le_of_lt (dist_triangle z x y) (add_lt_add_of_lt_of_le zx h) theorem ball_half_subset (y) (h : y ∈ ball x (ε / 2)) : ball y (ε / 2) ⊆ ball x ε := ball_subset $ by rw sub_self_div_two; exact le_of_lt h theorem exists_ball_subset_ball (h : y ∈ ball x ε) : ∃ ε' > 0, ball y ε' ⊆ ball x ε := ⟨_, sub_pos.2 h, ball_subset $ by rw sub_sub_self⟩ theorem uniformity_basis_dist : (𝓤 α).has_basis (λ ε : ℝ, 0 < ε) (λ ε, {p:α×α | dist p.1 p.2 < ε}) := begin rw ← pseudo_metric_space.uniformity_dist.symm, refine has_basis_binfi_principal _ nonempty_Ioi, exact λ r (hr : 0 < r) p (hp : 0 < p), ⟨min r p, lt_min hr hp, λ x (hx : dist _ _ < _), lt_of_lt_of_le hx (min_le_left r p), λ x (hx : dist _ _ < _), lt_of_lt_of_le hx (min_le_right r p)⟩ end /-- Given `f : β → ℝ`, if `f` sends `{i | p i}` to a set of positive numbers accumulating to zero, then `f i`-neighborhoods of the diagonal form a basis of `𝓤 α`. For specific bases see `uniformity_basis_dist`, `uniformity_basis_dist_inv_nat_succ`, and `uniformity_basis_dist_inv_nat_pos`. -/ protected theorem mk_uniformity_basis {β : Type*} {p : β → Prop} {f : β → ℝ} (hf₀ : ∀ i, p i → 0 < f i) (hf : ∀ ⦃ε⦄, 0 < ε → ∃ i (hi : p i), f i ≤ ε) : (𝓤 α).has_basis p (λ i, {p:α×α | dist p.1 p.2 < f i}) := begin refine ⟨λ s, uniformity_basis_dist.mem_iff.trans _⟩, split, { rintros ⟨ε, ε₀, hε⟩, obtain ⟨i, hi, H⟩ : ∃ i (hi : p i), f i ≤ ε, from hf ε₀, exact ⟨i, hi, λ x (hx : _ < _), hε $ lt_of_lt_of_le hx H⟩ }, { exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, H⟩ } end theorem uniformity_basis_dist_inv_nat_succ : (𝓤 α).has_basis (λ _, true) (λ n:ℕ, {p:α×α | dist p.1 p.2 < 1 / (↑n+1) }) := metric.mk_uniformity_basis (λ n _, div_pos zero_lt_one $ nat.cast_add_one_pos n) (λ ε ε0, (exists_nat_one_div_lt ε0).imp $ λ n hn, ⟨trivial, le_of_lt hn⟩) theorem uniformity_basis_dist_inv_nat_pos : (𝓤 α).has_basis (λ n:ℕ, 0<n) (λ n:ℕ, {p:α×α | dist p.1 p.2 < 1 / ↑n }) := metric.mk_uniformity_basis (λ n hn, div_pos zero_lt_one $ nat.cast_pos.2 hn) (λ ε ε0, let ⟨n, hn⟩ := exists_nat_one_div_lt ε0 in ⟨n+1, nat.succ_pos n, hn.le⟩) theorem uniformity_basis_dist_pow {r : ℝ} (h0 : 0 < r) (h1 : r < 1) : (𝓤 α).has_basis (λ n:ℕ, true) (λ n:ℕ, {p:α×α | dist p.1 p.2 < r ^ n }) := metric.mk_uniformity_basis (λ n hn, pow_pos h0 _) (λ ε ε0, let ⟨n, hn⟩ := exists_pow_lt_of_lt_one ε0 h1 in ⟨n, trivial, hn.le⟩) theorem uniformity_basis_dist_lt {R : ℝ} (hR : 0 < R) : (𝓤 α).has_basis (λ r : ℝ, 0 < r ∧ r < R) (λ r, {p : α × α | dist p.1 p.2 < r}) := metric.mk_uniformity_basis (λ r, and.left) $ λ r hr, ⟨min r (R / 2), ⟨lt_min hr (half_pos hR), min_lt_iff.2 $ or.inr (half_lt_self hR)⟩, min_le_left _ _⟩ /-- Given `f : β → ℝ`, if `f` sends `{i | p i}` to a set of positive numbers accumulating to zero, then closed neighborhoods of the diagonal of sizes `{f i | p i}` form a basis of `𝓤 α`. Currently we have only one specific basis `uniformity_basis_dist_le` based on this constructor. More can be easily added if needed in the future. -/ protected theorem mk_uniformity_basis_le {β : Type*} {p : β → Prop} {f : β → ℝ} (hf₀ : ∀ x, p x → 0 < f x) (hf : ∀ ε, 0 < ε → ∃ x (hx : p x), f x ≤ ε) : (𝓤 α).has_basis p (λ x, {p:α×α | dist p.1 p.2 ≤ f x}) := begin refine ⟨λ s, uniformity_basis_dist.mem_iff.trans _⟩, split, { rintros ⟨ε, ε₀, hε⟩, rcases exists_between ε₀ with ⟨ε', hε'⟩, rcases hf ε' hε'.1 with ⟨i, hi, H⟩, exact ⟨i, hi, λ x (hx : _ ≤ _), hε $ lt_of_le_of_lt (le_trans hx H) hε'.2⟩ }, { exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, λ x (hx : _ < _), H (le_of_lt hx)⟩ } end /-- Contant size closed neighborhoods of the diagonal form a basis of the uniformity filter. -/ theorem uniformity_basis_dist_le : (𝓤 α).has_basis (λ ε : ℝ, 0 < ε) (λ ε, {p:α×α | dist p.1 p.2 ≤ ε}) := metric.mk_uniformity_basis_le (λ _, id) (λ ε ε₀, ⟨ε, ε₀, le_refl ε⟩) theorem uniformity_basis_dist_le_pow {r : ℝ} (h0 : 0 < r) (h1 : r < 1) : (𝓤 α).has_basis (λ n:ℕ, true) (λ n:ℕ, {p:α×α | dist p.1 p.2 ≤ r ^ n }) := metric.mk_uniformity_basis_le (λ n hn, pow_pos h0 _) (λ ε ε0, let ⟨n, hn⟩ := exists_pow_lt_of_lt_one ε0 h1 in ⟨n, trivial, hn.le⟩) theorem mem_uniformity_dist {s : set (α×α)} : s ∈ 𝓤 α ↔ (∃ε>0, ∀{a b:α}, dist a b < ε → (a, b) ∈ s) := uniformity_basis_dist.mem_uniformity_iff /-- A constant size neighborhood of the diagonal is an entourage. -/ theorem dist_mem_uniformity {ε:ℝ} (ε0 : 0 < ε) : {p:α×α | dist p.1 p.2 < ε} ∈ 𝓤 α := mem_uniformity_dist.2 ⟨ε, ε0, λ a b, id⟩ theorem uniform_continuous_iff [pseudo_metric_space β] {f : α → β} : uniform_continuous f ↔ ∀ ε > 0, ∃ δ > 0, ∀{a b:α}, dist a b < δ → dist (f a) (f b) < ε := uniformity_basis_dist.uniform_continuous_iff uniformity_basis_dist lemma uniform_continuous_on_iff [pseudo_metric_space β] {f : α → β} {s : set α} : uniform_continuous_on f s ↔ ∀ ε > 0, ∃ δ > 0, ∀ x y ∈ s, dist x y < δ → dist (f x) (f y) < ε := metric.uniformity_basis_dist.uniform_continuous_on_iff metric.uniformity_basis_dist lemma uniform_continuous_on_iff_le [pseudo_metric_space β] {f : α → β} {s : set α} : uniform_continuous_on f s ↔ ∀ ε > 0, ∃ δ > 0, ∀ x y ∈ s, dist x y ≤ δ → dist (f x) (f y) ≤ ε := metric.uniformity_basis_dist_le.uniform_continuous_on_iff metric.uniformity_basis_dist_le theorem uniform_embedding_iff [pseudo_metric_space β] {f : α → β} : uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧ ∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, dist (f a) (f b) < ε → dist a b < δ := uniform_embedding_def'.trans $ and_congr iff.rfl $ and_congr iff.rfl ⟨λ H δ δ0, let ⟨t, tu, ht⟩ := H _ (dist_mem_uniformity δ0), ⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 tu in ⟨ε, ε0, λ a b h, ht _ _ (hε h)⟩, λ H s su, let ⟨δ, δ0, hδ⟩ := mem_uniformity_dist.1 su, ⟨ε, ε0, hε⟩ := H _ δ0 in ⟨_, dist_mem_uniformity ε0, λ a b h, hδ (hε h)⟩⟩ /-- If a map between pseudometric spaces is a uniform embedding then the distance between `f x` and `f y` is controlled in terms of the distance between `x` and `y`. -/ theorem controlled_of_uniform_embedding [pseudo_metric_space β] {f : α → β} : uniform_embedding f → (∀ ε > 0, ∃ δ > 0, ∀ {a b : α}, dist a b < δ → dist (f a) (f b) < ε) ∧ (∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, dist (f a) (f b) < ε → dist a b < δ) := begin assume h, exact ⟨uniform_continuous_iff.1 (uniform_embedding_iff.1 h).2.1, (uniform_embedding_iff.1 h).2.2⟩ end theorem totally_bounded_iff {s : set α} : totally_bounded s ↔ ∀ ε > 0, ∃t : set α, finite t ∧ s ⊆ ⋃y∈t, ball y ε := ⟨λ H ε ε0, H _ (dist_mem_uniformity ε0), λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 ru, ⟨t, ft, h⟩ := H ε ε0 in ⟨t, ft, subset.trans h $ Union_subset_Union $ λ y, Union_subset_Union $ λ yt z, hε⟩⟩ /-- A pseudometric space is totally bounded if one can reconstruct up to any ε>0 any element of the space from finitely many data. -/ lemma totally_bounded_of_finite_discretization {s : set α} (H : ∀ε > (0 : ℝ), ∃ (β : Type u) (_ : fintype β) (F : s → β), ∀x y, F x = F y → dist (x:α) y < ε) : totally_bounded s := begin cases s.eq_empty_or_nonempty with hs hs, { rw hs, exact totally_bounded_empty }, rcases hs with ⟨x0, hx0⟩, haveI : inhabited s := ⟨⟨x0, hx0⟩⟩, refine totally_bounded_iff.2 (λ ε ε0, _), rcases H ε ε0 with ⟨β, fβ, F, hF⟩, resetI, let Finv := function.inv_fun F, refine ⟨range (subtype.val ∘ Finv), finite_range _, λ x xs, _⟩, let x' := Finv (F ⟨x, xs⟩), have : F x' = F ⟨x, xs⟩ := function.inv_fun_eq ⟨⟨x, xs⟩, rfl⟩, simp only [set.mem_Union, set.mem_range], exact ⟨_, ⟨F ⟨x, xs⟩, rfl⟩, hF _ _ this.symm⟩ end theorem finite_approx_of_totally_bounded {s : set α} (hs : totally_bounded s) : ∀ ε > 0, ∃ t ⊆ s, finite t ∧ s ⊆ ⋃y∈t, ball y ε := begin intros ε ε_pos, rw totally_bounded_iff_subset at hs, exact hs _ (dist_mem_uniformity ε_pos), end /-- Expressing locally uniform convergence on a set using `dist`. -/ lemma tendsto_locally_uniformly_on_iff {ι : Type*} [topological_space β] {F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} : tendsto_locally_uniformly_on F f p s ↔ ∀ ε > 0, ∀ x ∈ s, ∃ t ∈ 𝓝[s] x, ∀ᶠ n in p, ∀ y ∈ t, dist (f y) (F n y) < ε := begin refine ⟨λ H ε hε, H _ (dist_mem_uniformity hε), λ H u hu x hx, _⟩, rcases mem_uniformity_dist.1 hu with ⟨ε, εpos, hε⟩, rcases H ε εpos x hx with ⟨t, ht, Ht⟩, exact ⟨t, ht, Ht.mono (λ n hs x hx, hε (hs x hx))⟩ end /-- Expressing uniform convergence on a set using `dist`. -/ lemma tendsto_uniformly_on_iff {ι : Type*} {F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} : tendsto_uniformly_on F f p s ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x ∈ s, dist (f x) (F n x) < ε := begin refine ⟨λ H ε hε, H _ (dist_mem_uniformity hε), λ H u hu, _⟩, rcases mem_uniformity_dist.1 hu with ⟨ε, εpos, hε⟩, exact (H ε εpos).mono (λ n hs x hx, hε (hs x hx)) end /-- Expressing locally uniform convergence using `dist`. -/ lemma tendsto_locally_uniformly_iff {ι : Type*} [topological_space β] {F : ι → β → α} {f : β → α} {p : filter ι} : tendsto_locally_uniformly F f p ↔ ∀ ε > 0, ∀ (x : β), ∃ t ∈ 𝓝 x, ∀ᶠ n in p, ∀ y ∈ t, dist (f y) (F n y) < ε := by simp only [← tendsto_locally_uniformly_on_univ, tendsto_locally_uniformly_on_iff, nhds_within_univ, mem_univ, forall_const, exists_prop] /-- Expressing uniform convergence using `dist`. -/ lemma tendsto_uniformly_iff {ι : Type*} {F : ι → β → α} {f : β → α} {p : filter ι} : tendsto_uniformly F f p ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x, dist (f x) (F n x) < ε := by { rw [← tendsto_uniformly_on_univ, tendsto_uniformly_on_iff], simp } protected lemma cauchy_iff {f : filter α} : cauchy f ↔ ne_bot f ∧ ∀ ε > 0, ∃ t ∈ f, ∀ x y ∈ t, dist x y < ε := uniformity_basis_dist.cauchy_iff theorem nhds_basis_ball : (𝓝 x).has_basis (λ ε:ℝ, 0 < ε) (ball x) := nhds_basis_uniformity uniformity_basis_dist theorem mem_nhds_iff : s ∈ 𝓝 x ↔ ∃ε>0, ball x ε ⊆ s := nhds_basis_ball.mem_iff theorem eventually_nhds_iff {p : α → Prop} : (∀ᶠ y in 𝓝 x, p y) ↔ ∃ε>0, ∀ ⦃y⦄, dist y x < ε → p y := mem_nhds_iff lemma eventually_nhds_iff_ball {p : α → Prop} : (∀ᶠ y in 𝓝 x, p y) ↔ ∃ ε>0, ∀ y ∈ ball x ε, p y := mem_nhds_iff theorem nhds_basis_closed_ball : (𝓝 x).has_basis (λ ε:ℝ, 0 < ε) (closed_ball x) := nhds_basis_uniformity uniformity_basis_dist_le theorem nhds_basis_ball_inv_nat_succ : (𝓝 x).has_basis (λ _, true) (λ n:ℕ, ball x (1 / (↑n+1))) := nhds_basis_uniformity uniformity_basis_dist_inv_nat_succ theorem nhds_basis_ball_inv_nat_pos : (𝓝 x).has_basis (λ n, 0<n) (λ n:ℕ, ball x (1 / ↑n)) := nhds_basis_uniformity uniformity_basis_dist_inv_nat_pos theorem nhds_basis_ball_pow {r : ℝ} (h0 : 0 < r) (h1 : r < 1) : (𝓝 x).has_basis (λ n, true) (λ n:ℕ, ball x (r ^ n)) := nhds_basis_uniformity (uniformity_basis_dist_pow h0 h1) theorem nhds_basis_closed_ball_pow {r : ℝ} (h0 : 0 < r) (h1 : r < 1) : (𝓝 x).has_basis (λ n, true) (λ n:ℕ, closed_ball x (r ^ n)) := nhds_basis_uniformity (uniformity_basis_dist_le_pow h0 h1) theorem is_open_iff : is_open s ↔ ∀x∈s, ∃ε>0, ball x ε ⊆ s := by simp only [is_open_iff_mem_nhds, mem_nhds_iff] theorem is_open_ball : is_open (ball x ε) := is_open_iff.2 $ λ y, exists_ball_subset_ball theorem ball_mem_nhds (x : α) {ε : ℝ} (ε0 : 0 < ε) : ball x ε ∈ 𝓝 x := is_open.mem_nhds is_open_ball (mem_ball_self ε0) theorem closed_ball_mem_nhds (x : α) {ε : ℝ} (ε0 : 0 < ε) : closed_ball x ε ∈ 𝓝 x := mem_of_superset (ball_mem_nhds x ε0) ball_subset_closed_ball theorem nhds_within_basis_ball {s : set α} : (𝓝[s] x).has_basis (λ ε:ℝ, 0 < ε) (λ ε, ball x ε ∩ s) := nhds_within_has_basis nhds_basis_ball s theorem mem_nhds_within_iff {t : set α} : s ∈ 𝓝[t] x ↔ ∃ε>0, ball x ε ∩ t ⊆ s := nhds_within_basis_ball.mem_iff theorem tendsto_nhds_within_nhds_within [pseudo_metric_space β] {t : set β} {f : α → β} {a b} : tendsto f (𝓝[s] a) (𝓝[t] b) ↔ ∀ ε > 0, ∃ δ > 0, ∀{x:α}, x ∈ s → dist x a < δ → f x ∈ t ∧ dist (f x) b < ε := (nhds_within_basis_ball.tendsto_iff nhds_within_basis_ball).trans $ by simp only [inter_comm, mem_inter_iff, and_imp, mem_ball] theorem tendsto_nhds_within_nhds [pseudo_metric_space β] {f : α → β} {a b} : tendsto f (𝓝[s] a) (𝓝 b) ↔ ∀ ε > 0, ∃ δ > 0, ∀{x:α}, x ∈ s → dist x a < δ → dist (f x) b < ε := by { rw [← nhds_within_univ b, tendsto_nhds_within_nhds_within], simp only [mem_univ, true_and] } theorem tendsto_nhds_nhds [pseudo_metric_space β] {f : α → β} {a b} : tendsto f (𝓝 a) (𝓝 b) ↔ ∀ ε > 0, ∃ δ > 0, ∀{x:α}, dist x a < δ → dist (f x) b < ε := nhds_basis_ball.tendsto_iff nhds_basis_ball theorem continuous_at_iff [pseudo_metric_space β] {f : α → β} {a : α} : continuous_at f a ↔ ∀ ε > 0, ∃ δ > 0, ∀{x:α}, dist x a < δ → dist (f x) (f a) < ε := by rw [continuous_at, tendsto_nhds_nhds] theorem continuous_within_at_iff [pseudo_metric_space β] {f : α → β} {a : α} {s : set α} : continuous_within_at f s a ↔ ∀ ε > 0, ∃ δ > 0, ∀{x:α}, x ∈ s → dist x a < δ → dist (f x) (f a) < ε := by rw [continuous_within_at, tendsto_nhds_within_nhds] theorem continuous_on_iff [pseudo_metric_space β] {f : α → β} {s : set α} : continuous_on f s ↔ ∀ (b ∈ s) (ε > 0), ∃ δ > 0, ∀a ∈ s, dist a b < δ → dist (f a) (f b) < ε := by simp [continuous_on, continuous_within_at_iff] theorem continuous_iff [pseudo_metric_space β] {f : α → β} : continuous f ↔ ∀b (ε > 0), ∃ δ > 0, ∀a, dist a b < δ → dist (f a) (f b) < ε := continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds_nhds theorem tendsto_nhds {f : filter β} {u : β → α} {a : α} : tendsto u f (𝓝 a) ↔ ∀ ε > 0, ∀ᶠ x in f, dist (u x) a < ε := nhds_basis_ball.tendsto_right_iff theorem continuous_at_iff' [topological_space β] {f : β → α} {b : β} : continuous_at f b ↔ ∀ ε > 0, ∀ᶠ x in 𝓝 b, dist (f x) (f b) < ε := by rw [continuous_at, tendsto_nhds] theorem continuous_within_at_iff' [topological_space β] {f : β → α} {b : β} {s : set β} : continuous_within_at f s b ↔ ∀ ε > 0, ∀ᶠ x in 𝓝[s] b, dist (f x) (f b) < ε := by rw [continuous_within_at, tendsto_nhds] theorem continuous_on_iff' [topological_space β] {f : β → α} {s : set β} : continuous_on f s ↔ ∀ (b ∈ s) (ε > 0), ∀ᶠ x in 𝓝[s] b, dist (f x) (f b) < ε := by simp [continuous_on, continuous_within_at_iff'] theorem continuous_iff' [topological_space β] {f : β → α} : continuous f ↔ ∀a (ε > 0), ∀ᶠ x in 𝓝 a, dist (f x) (f a) < ε := continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds theorem tendsto_at_top [nonempty β] [semilattice_sup β] {u : β → α} {a : α} : tendsto u at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n≥N, dist (u n) a < ε := (at_top_basis.tendsto_iff nhds_basis_ball).trans $ by { simp only [exists_prop, true_and], refl } /-- A variant of `tendsto_at_top` that uses `∃ N, ∀ n > N, ...` rather than `∃ N, ∀ n ≥ N, ...` -/ theorem tendsto_at_top' [nonempty β] [semilattice_sup β] [no_top_order β] {u : β → α} {a : α} : tendsto u at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n>N, dist (u n) a < ε := (at_top_basis_Ioi.tendsto_iff nhds_basis_ball).trans $ by { simp only [exists_prop, true_and], refl } lemma is_open_singleton_iff {α : Type*} [pseudo_metric_space α] {x : α} : is_open ({x} : set α) ↔ ∃ ε > 0, ∀ y, dist y x < ε → y = x := by simp [is_open_iff, subset_singleton_iff, mem_ball] /-- Given a point `x` in a discrete subset `s` of a pseudometric space, there is an open ball centered at `x` and intersecting `s` only at `x`. -/ lemma exists_ball_inter_eq_singleton_of_mem_discrete [discrete_topology s] {x : α} (hx : x ∈ s) : ∃ ε > 0, metric.ball x ε ∩ s = {x} := nhds_basis_ball.exists_inter_eq_singleton_of_mem_discrete hx /-- Given a point `x` in a discrete subset `s` of a pseudometric space, there is a closed ball of positive radius centered at `x` and intersecting `s` only at `x`. -/ lemma exists_closed_ball_inter_eq_singleton_of_discrete [discrete_topology s] {x : α} (hx : x ∈ s) : ∃ ε > 0, metric.closed_ball x ε ∩ s = {x} := nhds_basis_closed_ball.exists_inter_eq_singleton_of_mem_discrete hx end metric open metric /-Instantiate a pseudometric space as a pseudoemetric space. Before we can state the instance, we need to show that the uniform structure coming from the edistance and the distance coincide. -/ /-- Expressing the uniformity in terms of `edist` -/ protected lemma pseudo_metric.uniformity_basis_edist : (𝓤 α).has_basis (λ ε:ℝ≥0∞, 0 < ε) (λ ε, {p | edist p.1 p.2 < ε}) := ⟨begin intro t, refine mem_uniformity_dist.trans ⟨_, _⟩; rintro ⟨ε, ε0, Hε⟩, { use [ennreal.of_real ε, ennreal.of_real_pos.2 ε0], rintros ⟨a, b⟩, simp only [edist_dist, ennreal.of_real_lt_of_real_iff ε0], exact Hε }, { rcases ennreal.lt_iff_exists_real_btwn.1 ε0 with ⟨ε', _, ε0', hε⟩, rw [ennreal.of_real_pos] at ε0', refine ⟨ε', ε0', λ a b h, Hε (lt_trans _ hε)⟩, rwa [edist_dist, ennreal.of_real_lt_of_real_iff ε0'] } end⟩ theorem metric.uniformity_edist : 𝓤 α = (⨅ ε>0, 𝓟 {p:α×α | edist p.1 p.2 < ε}) := pseudo_metric.uniformity_basis_edist.eq_binfi /-- A pseudometric space induces a pseudoemetric space -/ @[priority 100] -- see Note [lower instance priority] instance pseudo_metric_space.to_pseudo_emetric_space : pseudo_emetric_space α := { edist := edist, edist_self := by simp [edist_dist], edist_comm := by simp only [edist_dist, dist_comm]; simp, edist_triangle := assume x y z, begin simp only [edist_dist, ← ennreal.of_real_add, dist_nonneg], rw ennreal.of_real_le_of_real_iff _, { exact dist_triangle _ _ _ }, { simpa using add_le_add (dist_nonneg : 0 ≤ dist x y) dist_nonneg } end, uniformity_edist := metric.uniformity_edist, ..‹pseudo_metric_space α› } /-- In a pseudometric space, an open ball of infinite radius is the whole space -/ lemma metric.eball_top_eq_univ (x : α) : emetric.ball x ∞ = set.univ := set.eq_univ_iff_forall.mpr (λ y, edist_lt_top y x) /-- Balls defined using the distance or the edistance coincide -/ @[simp] lemma metric.emetric_ball {x : α} {ε : ℝ} : emetric.ball x (ennreal.of_real ε) = ball x ε := begin ext y, simp only [emetric.mem_ball, mem_ball, edist_dist], exact ennreal.of_real_lt_of_real_iff_of_nonneg dist_nonneg end /-- Balls defined using the distance or the edistance coincide -/ @[simp] lemma metric.emetric_ball_nnreal {x : α} {ε : ℝ≥0} : emetric.ball x ε = ball x ε := by { convert metric.emetric_ball, simp } /-- Closed balls defined using the distance or the edistance coincide -/ lemma metric.emetric_closed_ball {x : α} {ε : ℝ} (h : 0 ≤ ε) : emetric.closed_ball x (ennreal.of_real ε) = closed_ball x ε := by ext y; simp [edist_dist]; rw ennreal.of_real_le_of_real_iff h /-- Closed balls defined using the distance or the edistance coincide -/ @[simp] lemma metric.emetric_closed_ball_nnreal {x : α} {ε : ℝ≥0} : emetric.closed_ball x ε = closed_ball x ε := by { convert metric.emetric_closed_ball ε.2, simp } @[simp] lemma metric.emetric_ball_top (x : α) : emetric.ball x ⊤ = univ := eq_univ_of_forall $ λ y, edist_lt_top _ _ /-- Build a new pseudometric space from an old one where the bundled uniform structure is provably (but typically non-definitionaly) equal to some given uniform structure. See Note [forgetful inheritance]. -/ def pseudo_metric_space.replace_uniformity {α} [U : uniform_space α] (m : pseudo_metric_space α) (H : @uniformity _ U = @uniformity _ pseudo_emetric_space.to_uniform_space') : pseudo_metric_space α := { dist := @dist _ m.to_has_dist, dist_self := dist_self, dist_comm := dist_comm, dist_triangle := dist_triangle, edist := edist, edist_dist := edist_dist, to_uniform_space := U, uniformity_dist := H.trans pseudo_metric_space.uniformity_dist } /-- One gets a pseudometric space from an emetric space if the edistance is everywhere finite, by pushing the edistance to reals. We set it up so that the edist and the uniformity are defeq in the pseudometric space and the pseudoemetric space. In this definition, the distance is given separately, to be able to prescribe some expression which is not defeq to the push-forward of the edistance to reals. -/ def pseudo_emetric_space.to_pseudo_metric_space_of_dist {α : Type u} [e : pseudo_emetric_space α] (dist : α → α → ℝ) (edist_ne_top : ∀x y: α, edist x y ≠ ⊤) (h : ∀x y, dist x y = ennreal.to_real (edist x y)) : pseudo_metric_space α := let m : pseudo_metric_space α := { dist := dist, dist_self := λx, by simp [h], dist_comm := λx y, by simp [h, pseudo_emetric_space.edist_comm], dist_triangle := λx y z, begin simp only [h], rw [← ennreal.to_real_add (edist_ne_top _ _) (edist_ne_top _ _), ennreal.to_real_le_to_real (edist_ne_top _ _)], { exact edist_triangle _ _ _ }, { simp [ennreal.add_eq_top, edist_ne_top] } end, edist := λx y, edist x y, edist_dist := λx y, by simp [h, ennreal.of_real_to_real, edist_ne_top] } in m.replace_uniformity $ by { rw [uniformity_pseudoedist, metric.uniformity_edist], refl } /-- One gets a pseudometric space from an emetric space if the edistance is everywhere finite, by pushing the edistance to reals. We set it up so that the edist and the uniformity are defeq in the pseudometric space and the emetric space. -/ def pseudo_emetric_space.to_pseudo_metric_space {α : Type u} [e : pseudo_emetric_space α] (h : ∀x y: α, edist x y ≠ ⊤) : pseudo_metric_space α := pseudo_emetric_space.to_pseudo_metric_space_of_dist (λx y, ennreal.to_real (edist x y)) h (λx y, rfl) /-- A very useful criterion to show that a space is complete is to show that all sequences which satisfy a bound of the form `dist (u n) (u m) < B N` for all `n m ≥ N` are converging. This is often applied for `B N = 2^{-N}`, i.e., with a very fast convergence to `0`, which makes it possible to use arguments of converging series, while this is impossible to do in general for arbitrary Cauchy sequences. -/ theorem metric.complete_of_convergent_controlled_sequences (B : ℕ → real) (hB : ∀n, 0 < B n) (H : ∀u : ℕ → α, (∀N n m : ℕ, N ≤ n → N ≤ m → dist (u n) (u m) < B N) → ∃x, tendsto u at_top (𝓝 x)) : complete_space α := begin -- this follows from the same criterion in emetric spaces. We just need to translate -- the convergence assumption from `dist` to `edist` apply emetric.complete_of_convergent_controlled_sequences (λn, ennreal.of_real (B n)), { simp [hB] }, { assume u Hu, apply H, assume N n m hn hm, rw [← ennreal.of_real_lt_of_real_iff (hB N), ← edist_dist], exact Hu N n m hn hm } end theorem metric.complete_of_cauchy_seq_tendsto : (∀ u : ℕ → α, cauchy_seq u → ∃a, tendsto u at_top (𝓝 a)) → complete_space α := emetric.complete_of_cauchy_seq_tendsto section real /-- Instantiate the reals as a pseudometric space. -/ noncomputable instance real.pseudo_metric_space : pseudo_metric_space ℝ := { dist := λx y, |x - y|, dist_self := by simp [abs_zero], dist_comm := assume x y, abs_sub_comm _ _, dist_triangle := assume x y z, abs_sub_le _ _ _ } theorem real.dist_eq (x y : ℝ) : dist x y = |x - y| := rfl theorem real.nndist_eq (x y : ℝ) : nndist x y = real.nnabs (x - y) := rfl theorem real.nndist_eq' (x y : ℝ) : nndist x y = real.nnabs (y - x) := nndist_comm _ _ theorem real.dist_0_eq_abs (x : ℝ) : dist x 0 = |x| := by simp [real.dist_eq] theorem real.dist_left_le_of_mem_interval {x y z : ℝ} (h : y ∈ interval x z) : dist x y ≤ dist x z := by simpa only [dist_comm x] using abs_sub_left_of_mem_interval h theorem real.dist_right_le_of_mem_interval {x y z : ℝ} (h : y ∈ interval x z) : dist y z ≤ dist x z := by simpa only [dist_comm _ z] using abs_sub_right_of_mem_interval h theorem real.dist_le_of_mem_interval {x y x' y' : ℝ} (hx : x ∈ interval x' y') (hy : y ∈ interval x' y') : dist x y ≤ dist x' y' := abs_sub_le_of_subinterval $ interval_subset_interval (by rwa interval_swap) (by rwa interval_swap) theorem real.dist_le_of_mem_Icc {x y x' y' : ℝ} (hx : x ∈ Icc x' y') (hy : y ∈ Icc x' y') : dist x y ≤ y' - x' := by simpa only [real.dist_eq, abs_of_nonpos (sub_nonpos.2 $ hx.1.trans hx.2), neg_sub] using real.dist_le_of_mem_interval (Icc_subset_interval hx) (Icc_subset_interval hy) theorem real.dist_le_of_mem_Icc_01 {x y : ℝ} (hx : x ∈ Icc (0:ℝ) 1) (hy : y ∈ Icc (0:ℝ) 1) : dist x y ≤ 1 := by simpa only [sub_zero] using real.dist_le_of_mem_Icc hx hy instance : order_topology ℝ := order_topology_of_nhds_abs $ λ x, by simp only [nhds_basis_ball.eq_binfi, ball, real.dist_eq, abs_sub_comm] lemma real.ball_eq (x r : ℝ) : ball x r = Ioo (x - r) (x + r) := set.ext $ λ y, by rw [mem_ball, dist_comm, real.dist_eq, abs_sub_lt_iff, mem_Ioo, ← sub_lt_iff_lt_add', sub_lt] lemma real.closed_ball_eq {x r : ℝ} : closed_ball x r = Icc (x - r) (x + r) := by ext y; rw [mem_closed_ball, dist_comm, real.dist_eq, abs_sub_le_iff, mem_Icc, ← sub_le_iff_le_add', sub_le] section metric_ordered variables [conditionally_complete_linear_order α] [order_topology α] lemma totally_bounded_Icc (a b : α) : totally_bounded (Icc a b) := is_compact_Icc.totally_bounded lemma totally_bounded_Ico (a b : α) : totally_bounded (Ico a b) := totally_bounded_subset Ico_subset_Icc_self (totally_bounded_Icc a b) lemma totally_bounded_Ioc (a b : α) : totally_bounded (Ioc a b) := totally_bounded_subset Ioc_subset_Icc_self (totally_bounded_Icc a b) lemma totally_bounded_Ioo (a b : α) : totally_bounded (Ioo a b) := totally_bounded_subset Ioo_subset_Icc_self (totally_bounded_Icc a b) end metric_ordered /-- Special case of the sandwich theorem; see `tendsto_of_tendsto_of_tendsto_of_le_of_le'` for the general case. -/ lemma squeeze_zero' {α} {f g : α → ℝ} {t₀ : filter α} (hf : ∀ᶠ t in t₀, 0 ≤ f t) (hft : ∀ᶠ t in t₀, f t ≤ g t) (g0 : tendsto g t₀ (nhds 0)) : tendsto f t₀ (𝓝 0) := tendsto_of_tendsto_of_tendsto_of_le_of_le' tendsto_const_nhds g0 hf hft /-- Special case of the sandwich theorem; see `tendsto_of_tendsto_of_tendsto_of_le_of_le` and `tendsto_of_tendsto_of_tendsto_of_le_of_le'` for the general case. -/ lemma squeeze_zero {α} {f g : α → ℝ} {t₀ : filter α} (hf : ∀t, 0 ≤ f t) (hft : ∀t, f t ≤ g t) (g0 : tendsto g t₀ (𝓝 0)) : tendsto f t₀ (𝓝 0) := squeeze_zero' (eventually_of_forall hf) (eventually_of_forall hft) g0 theorem metric.uniformity_eq_comap_nhds_zero : 𝓤 α = comap (λp:α×α, dist p.1 p.2) (𝓝 (0 : ℝ)) := by { ext s, simp [mem_uniformity_dist, (nhds_basis_ball.comap _).mem_iff, subset_def, real.dist_0_eq_abs] } lemma cauchy_seq_iff_tendsto_dist_at_top_0 [nonempty β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ tendsto (λ (n : β × β), dist (u n.1) (u n.2)) at_top (𝓝 0) := by rw [cauchy_seq_iff_tendsto, metric.uniformity_eq_comap_nhds_zero, tendsto_comap_iff, prod.map_def] lemma tendsto_uniformity_iff_dist_tendsto_zero {ι : Type*} {f : ι → α × α} {p : filter ι} : tendsto f p (𝓤 α) ↔ tendsto (λ x, dist (f x).1 (f x).2) p (𝓝 0) := by rw [metric.uniformity_eq_comap_nhds_zero, tendsto_comap_iff] lemma filter.tendsto.congr_dist {ι : Type*} {f₁ f₂ : ι → α} {p : filter ι} {a : α} (h₁ : tendsto f₁ p (𝓝 a)) (h : tendsto (λ x, dist (f₁ x) (f₂ x)) p (𝓝 0)) : tendsto f₂ p (𝓝 a) := h₁.congr_uniformity $ tendsto_uniformity_iff_dist_tendsto_zero.2 h alias filter.tendsto.congr_dist ← tendsto_of_tendsto_of_dist lemma tendsto_iff_of_dist {ι : Type*} {f₁ f₂ : ι → α} {p : filter ι} {a : α} (h : tendsto (λ x, dist (f₁ x) (f₂ x)) p (𝓝 0)) : tendsto f₁ p (𝓝 a) ↔ tendsto f₂ p (𝓝 a) := uniform.tendsto_congr $ tendsto_uniformity_iff_dist_tendsto_zero.2 h end real section cauchy_seq variables [nonempty β] [semilattice_sup β] /-- In a pseudometric space, Cauchy sequences are characterized by the fact that, eventually, the distance between its elements is arbitrarily small -/ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem metric.cauchy_seq_iff {u : β → α} : cauchy_seq u ↔ ∀ε>0, ∃N, ∀m n≥N, dist (u m) (u n) < ε := uniformity_basis_dist.cauchy_seq_iff /-- A variation around the pseudometric characterization of Cauchy sequences -/ theorem metric.cauchy_seq_iff' {u : β → α} : cauchy_seq u ↔ ∀ε>0, ∃N, ∀n≥N, dist (u n) (u N) < ε := uniformity_basis_dist.cauchy_seq_iff' /-- If the distance between `s n` and `s m`, `n, m ≥ N` is bounded above by `b N` and `b` converges to zero, then `s` is a Cauchy sequence. -/ lemma cauchy_seq_of_le_tendsto_0 {s : β → α} (b : β → ℝ) (h : ∀ n m N : β, N ≤ n → N ≤ m → dist (s n) (s m) ≤ b N) (h₀ : tendsto b at_top (nhds 0)) : cauchy_seq s := metric.cauchy_seq_iff.2 $ λ ε ε0, (metric.tendsto_at_top.1 h₀ ε ε0).imp $ λ N hN m n hm hn, calc dist (s m) (s n) ≤ b N : h m n N hm hn ... ≤ |b N| : le_abs_self _ ... = dist (b N) 0 : by rw real.dist_0_eq_abs; refl ... < ε : (hN _ (le_refl N)) /-- A Cauchy sequence on the natural numbers is bounded. -/ theorem cauchy_seq_bdd {u : ℕ → α} (hu : cauchy_seq u) : ∃ R > 0, ∀ m n, dist (u m) (u n) < R := begin rcases metric.cauchy_seq_iff'.1 hu 1 zero_lt_one with ⟨N, hN⟩, suffices : ∃ R > 0, ∀ n, dist (u n) (u N) < R, { rcases this with ⟨R, R0, H⟩, exact ⟨_, add_pos R0 R0, λ m n, lt_of_le_of_lt (dist_triangle_right _ _ _) (add_lt_add (H m) (H n))⟩ }, let R := finset.sup (finset.range N) (λ n, nndist (u n) (u N)), refine ⟨↑R + 1, add_pos_of_nonneg_of_pos R.2 zero_lt_one, λ n, _⟩, cases le_or_lt N n, { exact lt_of_lt_of_le (hN _ h) (le_add_of_nonneg_left R.2) }, { have : _ ≤ R := finset.le_sup (finset.mem_range.2 h), exact lt_of_le_of_lt this (lt_add_of_pos_right _ zero_lt_one) } end /-- Yet another metric characterization of Cauchy sequences on integers. This one is often the most efficient. -/ lemma cauchy_seq_iff_le_tendsto_0 {s : ℕ → α} : cauchy_seq s ↔ ∃ b : ℕ → ℝ, (∀ n, 0 ≤ b n) ∧ (∀ n m N : ℕ, N ≤ n → N ≤ m → dist (s n) (s m) ≤ b N) ∧ tendsto b at_top (𝓝 0) := ⟨λ hs, begin /- `s` is a Cauchy sequence. The sequence `b` will be constructed by taking the supremum of the distances between `s n` and `s m` for `n m ≥ N`. First, we prove that all these distances are bounded, as otherwise the Sup would not make sense. -/ let S := λ N, (λ(p : ℕ × ℕ), dist (s p.1) (s p.2)) '' {p | p.1 ≥ N ∧ p.2 ≥ N}, have hS : ∀ N, ∃ x, ∀ y ∈ S N, y ≤ x, { rcases cauchy_seq_bdd hs with ⟨R, R0, hR⟩, refine λ N, ⟨R, _⟩, rintro _ ⟨⟨m, n⟩, _, rfl⟩, exact le_of_lt (hR m n) }, have bdd : bdd_above (range (λ(p : ℕ × ℕ), dist (s p.1) (s p.2))), { rcases cauchy_seq_bdd hs with ⟨R, R0, hR⟩, use R, rintro _ ⟨⟨m, n⟩, rfl⟩, exact le_of_lt (hR m n) }, -- Prove that it bounds the distances of points in the Cauchy sequence have ub : ∀ m n N, N ≤ m → N ≤ n → dist (s m) (s n) ≤ Sup (S N) := λ m n N hm hn, le_cSup (hS N) ⟨⟨_, _⟩, ⟨hm, hn⟩, rfl⟩, have S0m : ∀ n, (0:ℝ) ∈ S n := λ n, ⟨⟨n, n⟩, ⟨le_refl _, le_refl _⟩, dist_self _⟩, have S0 := λ n, le_cSup (hS n) (S0m n), -- Prove that it tends to `0`, by using the Cauchy property of `s` refine ⟨λ N, Sup (S N), S0, ub, metric.tendsto_at_top.2 (λ ε ε0, _)⟩, refine (metric.cauchy_seq_iff.1 hs (ε/2) (half_pos ε0)).imp (λ N hN n hn, _), rw [real.dist_0_eq_abs, abs_of_nonneg (S0 n)], refine lt_of_le_of_lt (cSup_le ⟨_, S0m _⟩ _) (half_lt_self ε0), rintro _ ⟨⟨m', n'⟩, ⟨hm', hn'⟩, rfl⟩, exact le_of_lt (hN _ _ (le_trans hn hm') (le_trans hn hn')) end, λ ⟨b, _, b_bound, b_lim⟩, cauchy_seq_of_le_tendsto_0 b b_bound b_lim⟩ end cauchy_seq /-- Pseudometric space structure pulled back by a function. -/ def pseudo_metric_space.induced {α β} (f : α → β) (m : pseudo_metric_space β) : pseudo_metric_space α := { dist := λ x y, dist (f x) (f y), dist_self := λ x, dist_self _, dist_comm := λ x y, dist_comm _ _, dist_triangle := λ x y z, dist_triangle _ _ _, edist := λ x y, edist (f x) (f y), edist_dist := λ x y, edist_dist _ _, to_uniform_space := uniform_space.comap f m.to_uniform_space, uniformity_dist := begin apply @uniformity_dist_of_mem_uniformity _ _ _ _ _ (λ x y, dist (f x) (f y)), refine λ s, mem_comap.trans _, split; intro H, { rcases H with ⟨r, ru, rs⟩, rcases mem_uniformity_dist.1 ru with ⟨ε, ε0, hε⟩, refine ⟨ε, ε0, λ a b h, rs (hε _)⟩, exact h }, { rcases H with ⟨ε, ε0, hε⟩, exact ⟨_, dist_mem_uniformity ε0, λ ⟨a, b⟩, hε⟩ } end } /-- Pull back a pseudometric space structure by a uniform inducing map. This is a version of `pseudo_metric_space.induced` useful in case if the domain already has a `uniform_space` structure. -/ def uniform_inducing.comap_pseudo_metric_space {α β} [uniform_space α] [pseudo_metric_space β] (f : α → β) (h : uniform_inducing f) : pseudo_metric_space α := (pseudo_metric_space.induced f ‹_›).replace_uniformity h.comap_uniformity.symm instance subtype.psudo_metric_space {α : Type*} {p : α → Prop} [t : pseudo_metric_space α] : pseudo_metric_space (subtype p) := pseudo_metric_space.induced coe t theorem subtype.pseudo_dist_eq {p : α → Prop} (x y : subtype p) : dist x y = dist (x : α) y := rfl section nnreal noncomputable instance : pseudo_metric_space ℝ≥0 := by unfold nnreal; apply_instance lemma nnreal.dist_eq (a b : ℝ≥0) : dist a b = |(a:ℝ) - b| := rfl lemma nnreal.nndist_eq (a b : ℝ≥0) : nndist a b = max (a - b) (b - a) := begin wlog h : a ≤ b, { apply nnreal.coe_eq.1, rw [tsub_eq_zero_iff_le.2 h, max_eq_right (zero_le $ b - a), ← dist_nndist, nnreal.dist_eq, nnreal.coe_sub h, abs_eq_max_neg, neg_sub], apply max_eq_right, linarith [nnreal.coe_le_coe.2 h] }, rwa [nndist_comm, max_comm] end end nnreal section prod noncomputable instance prod.pseudo_metric_space_max [pseudo_metric_space β] : pseudo_metric_space (α × β) := { dist := λ x y, max (dist x.1 y.1) (dist x.2 y.2), dist_self := λ x, by simp, dist_comm := λ x y, by simp [dist_comm], dist_triangle := λ x y z, max_le (le_trans (dist_triangle _ _ _) (add_le_add (le_max_left _ _) (le_max_left _ _))) (le_trans (dist_triangle _ _ _) (add_le_add (le_max_right _ _) (le_max_right _ _))), edist := λ x y, max (edist x.1 y.1) (edist x.2 y.2), edist_dist := assume x y, begin have : monotone ennreal.of_real := assume x y h, ennreal.of_real_le_of_real h, rw [edist_dist, edist_dist, ← this.map_max] end, uniformity_dist := begin refine uniformity_prod.trans _, simp only [uniformity_basis_dist.eq_binfi, comap_infi], rw ← infi_inf_eq, congr, funext, rw ← infi_inf_eq, congr, funext, simp [inf_principal, ext_iff, max_lt_iff] end, to_uniform_space := prod.uniform_space } lemma prod.dist_eq [pseudo_metric_space β] {x y : α × β} : dist x y = max (dist x.1 y.1) (dist x.2 y.2) := rfl theorem ball_prod_same [pseudo_metric_space β] (x : α) (y : β) (r : ℝ) : (ball x r).prod (ball y r) = ball (x, y) r := ext $ λ z, by simp [prod.dist_eq] theorem closed_ball_prod_same [pseudo_metric_space β] (x : α) (y : β) (r : ℝ) : (closed_ball x r).prod (closed_ball y r) = closed_ball (x, y) r := ext $ λ z, by simp [prod.dist_eq] end prod theorem uniform_continuous_dist : uniform_continuous (λp:α×α, dist p.1 p.2) := metric.uniform_continuous_iff.2 (λ ε ε0, ⟨ε/2, half_pos ε0, begin suffices, { intros p q h, cases p with p₁ p₂, cases q with q₁ q₂, cases max_lt_iff.1 h with h₁ h₂, clear h, dsimp at h₁ h₂ ⊢, rw real.dist_eq, refine abs_sub_lt_iff.2 ⟨_, _⟩, { revert p₁ p₂ q₁ q₂ h₁ h₂, exact this }, { apply this; rwa dist_comm } }, intros p₁ p₂ q₁ q₂ h₁ h₂, have := add_lt_add (abs_sub_lt_iff.1 (lt_of_le_of_lt (abs_dist_sub_le p₁ q₁ p₂) h₁)).1 (abs_sub_lt_iff.1 (lt_of_le_of_lt (abs_dist_sub_le p₂ q₂ q₁) h₂)).1, rwa [add_halves, dist_comm p₂, sub_add_sub_cancel, dist_comm q₂] at this end⟩) theorem uniform_continuous.dist [uniform_space β] {f g : β → α} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (λb, dist (f b) (g b)) := uniform_continuous_dist.comp (hf.prod_mk hg) @[continuity] theorem continuous_dist : continuous (λp:α×α, dist p.1 p.2) := uniform_continuous_dist.continuous @[continuity] theorem continuous.dist [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : continuous (λb, dist (f b) (g b)) := continuous_dist.comp (hf.prod_mk hg : _) theorem filter.tendsto.dist {f g : β → α} {x : filter β} {a b : α} (hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) : tendsto (λx, dist (f x) (g x)) x (𝓝 (dist a b)) := (continuous_dist.tendsto (a, b)).comp (hf.prod_mk_nhds hg) lemma nhds_comap_dist (a : α) : (𝓝 (0 : ℝ)).comap (λa', dist a' a) = 𝓝 a := by simp only [@nhds_eq_comap_uniformity α, metric.uniformity_eq_comap_nhds_zero, comap_comap, (∘), dist_comm] lemma tendsto_iff_dist_tendsto_zero {f : β → α} {x : filter β} {a : α} : (tendsto f x (𝓝 a)) ↔ (tendsto (λb, dist (f b) a) x (𝓝 0)) := by rw [← nhds_comap_dist a, tendsto_comap_iff] lemma uniform_continuous_nndist : uniform_continuous (λp:α×α, nndist p.1 p.2) := uniform_continuous_subtype_mk uniform_continuous_dist _ lemma uniform_continuous.nndist [uniform_space β] {f g : β → α} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (λ b, nndist (f b) (g b)) := uniform_continuous_nndist.comp (hf.prod_mk hg) lemma continuous_nndist : continuous (λp:α×α, nndist p.1 p.2) := uniform_continuous_nndist.continuous lemma continuous.nndist [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : continuous (λb, nndist (f b) (g b)) := continuous_nndist.comp (hf.prod_mk hg : _) theorem filter.tendsto.nndist {f g : β → α} {x : filter β} {a b : α} (hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) : tendsto (λx, nndist (f x) (g x)) x (𝓝 (nndist a b)) := (continuous_nndist.tendsto (a, b)).comp (hf.prod_mk_nhds hg) namespace metric variables {x y z : α} {ε ε₁ ε₂ : ℝ} {s : set α} theorem is_closed_ball : is_closed (closed_ball x ε) := is_closed_le (continuous_id.dist continuous_const) continuous_const lemma is_closed_sphere : is_closed (sphere x ε) := is_closed_eq (continuous_id.dist continuous_const) continuous_const @[simp] theorem closure_closed_ball : closure (closed_ball x ε) = closed_ball x ε := is_closed_ball.closure_eq theorem closure_ball_subset_closed_ball : closure (ball x ε) ⊆ closed_ball x ε := closure_minimal ball_subset_closed_ball is_closed_ball theorem frontier_ball_subset_sphere : frontier (ball x ε) ⊆ sphere x ε := frontier_lt_subset_eq (continuous_id.dist continuous_const) continuous_const theorem frontier_closed_ball_subset_sphere : frontier (closed_ball x ε) ⊆ sphere x ε := frontier_le_subset_eq (continuous_id.dist continuous_const) continuous_const theorem ball_subset_interior_closed_ball : ball x ε ⊆ interior (closed_ball x ε) := interior_maximal ball_subset_closed_ball is_open_ball /-- ε-characterization of the closure in pseudometric spaces-/ theorem mem_closure_iff {α : Type u} [pseudo_metric_space α] {s : set α} {a : α} : a ∈ closure s ↔ ∀ε>0, ∃b ∈ s, dist a b < ε := (mem_closure_iff_nhds_basis nhds_basis_ball).trans $ by simp only [mem_ball, dist_comm] lemma mem_closure_range_iff {α : Type u} [pseudo_metric_space α] {e : β → α} {a : α} : a ∈ closure (range e) ↔ ∀ε>0, ∃ k : β, dist a (e k) < ε := by simp only [mem_closure_iff, exists_range_iff] lemma mem_closure_range_iff_nat {α : Type u} [pseudo_metric_space α] {e : β → α} {a : α} : a ∈ closure (range e) ↔ ∀n : ℕ, ∃ k : β, dist a (e k) < 1 / ((n : ℝ) + 1) := (mem_closure_iff_nhds_basis nhds_basis_ball_inv_nat_succ).trans $ by simp only [mem_ball, dist_comm, exists_range_iff, forall_const] theorem mem_of_closed' {α : Type u} [pseudo_metric_space α] {s : set α} (hs : is_closed s) {a : α} : a ∈ s ↔ ∀ε>0, ∃b ∈ s, dist a b < ε := by simpa only [hs.closure_eq] using @mem_closure_iff _ _ s a end metric section pi open finset variables {π : β → Type*} [fintype β] [∀b, pseudo_metric_space (π b)] /-- A finite product of pseudometric spaces is a pseudometric space, with the sup distance. -/ noncomputable instance pseudo_metric_space_pi : pseudo_metric_space (Πb, π b) := begin /- we construct the instance from the pseudoemetric space instance to avoid checking again that the uniformity is the same as the product uniformity, but we register nevertheless a nice formula for the distance -/ refine pseudo_emetric_space.to_pseudo_metric_space_of_dist (λf g, ((sup univ (λb, nndist (f b) (g b)) : ℝ≥0) : ℝ)) _ _, show ∀ (x y : Π (b : β), π b), edist x y ≠ ⊤, { assume x y, rw ← lt_top_iff_ne_top, have : (⊥ : ℝ≥0∞) < ⊤ := ennreal.coe_lt_top, simp [edist_pi_def, finset.sup_lt_iff this, edist_lt_top] }, show ∀ (x y : Π (b : β), π b), ↑(sup univ (λ (b : β), nndist (x b) (y b))) = ennreal.to_real (sup univ (λ (b : β), edist (x b) (y b))), { assume x y, simp only [edist_nndist], norm_cast } end lemma nndist_pi_def (f g : Πb, π b) : nndist f g = sup univ (λb, nndist (f b) (g b)) := subtype.eta _ _ lemma dist_pi_def (f g : Πb, π b) : dist f g = (sup univ (λb, nndist (f b) (g b)) : ℝ≥0) := rfl @[simp] lemma dist_pi_const [nonempty β] (a b : α) : dist (λ x : β, a) (λ _, b) = dist a b := by simpa only [dist_edist] using congr_arg ennreal.to_real (edist_pi_const a b) @[simp] lemma nndist_pi_const [nonempty β] (a b : α) : nndist (λ x : β, a) (λ _, b) = nndist a b := nnreal.eq $ dist_pi_const a b lemma dist_pi_lt_iff {f g : Πb, π b} {r : ℝ} (hr : 0 < r) : dist f g < r ↔ ∀b, dist (f b) (g b) < r := begin lift r to ℝ≥0 using hr.le, simp [dist_pi_def, finset.sup_lt_iff (show ⊥ < r, from hr)], end lemma dist_pi_le_iff {f g : Πb, π b} {r : ℝ} (hr : 0 ≤ r) : dist f g ≤ r ↔ ∀b, dist (f b) (g b) ≤ r := begin lift r to ℝ≥0 using hr, simp [nndist_pi_def] end lemma nndist_le_pi_nndist (f g : Πb, π b) (b : β) : nndist (f b) (g b) ≤ nndist f g := by { rw [nndist_pi_def], exact finset.le_sup (finset.mem_univ b) } lemma dist_le_pi_dist (f g : Πb, π b) (b : β) : dist (f b) (g b) ≤ dist f g := by simp only [dist_nndist, nnreal.coe_le_coe, nndist_le_pi_nndist f g b] /-- An open ball in a product space is a product of open balls. See also `metric.ball_pi'` for a version assuming `nonempty β` instead of `0 < r`. -/ lemma ball_pi (x : Πb, π b) {r : ℝ} (hr : 0 < r) : ball x r = set.pi univ (λ b, ball (x b) r) := by { ext p, simp [dist_pi_lt_iff hr] } /-- An open ball in a product space is a product of open balls. See also `metric.ball_pi` for a version assuming `0 < r` instead of `nonempty β`. -/ lemma ball_pi' [nonempty β] (x : Π b, π b) (r : ℝ) : ball x r = set.pi univ (λ b, ball (x b) r) := (lt_or_le 0 r).elim (ball_pi x) $ λ hr, by simp [ball_eq_empty.2 hr] /-- A closed ball in a product space is a product of closed balls. See also `metric.closed_ball_pi'` for a version assuming `nonempty β` instead of `0 ≤ r`. -/ lemma closed_ball_pi (x : Πb, π b) {r : ℝ} (hr : 0 ≤ r) : closed_ball x r = set.pi univ (λ b, closed_ball (x b) r) := by { ext p, simp [dist_pi_le_iff hr] } /-- A closed ball in a product space is a product of closed balls. See also `metric.closed_ball_pi` for a version assuming `0 ≤ r` instead of `nonempty β`. -/ lemma closed_ball_pi' [nonempty β] (x : Π b, π b) (r : ℝ) : closed_ball x r = set.pi univ (λ b, closed_ball (x b) r) := (le_or_lt 0 r).elim (closed_ball_pi x) $ λ hr, by simp [closed_ball_eq_empty.2 hr] lemma real.dist_le_of_mem_pi_Icc {x y x' y' : β → ℝ} (hx : x ∈ Icc x' y') (hy : y ∈ Icc x' y') : dist x y ≤ dist x' y' := begin refine (dist_pi_le_iff dist_nonneg).2 (λ b, (real.dist_le_of_mem_interval _ _).trans (dist_le_pi_dist _ _ b)); refine Icc_subset_interval _, exacts [⟨hx.1 _, hx.2 _⟩, ⟨hy.1 _, hy.2 _⟩] end end pi section compact /-- Any compact set in a pseudometric space can be covered by finitely many balls of a given positive radius -/ lemma finite_cover_balls_of_compact {α : Type u} [pseudo_metric_space α] {s : set α} (hs : is_compact s) {e : ℝ} (he : 0 < e) : ∃t ⊆ s, finite t ∧ s ⊆ ⋃x∈t, ball x e := begin apply hs.elim_finite_subcover_image, { simp [is_open_ball] }, { intros x xs, simp, exact ⟨x, ⟨xs, by simpa⟩⟩ } end alias finite_cover_balls_of_compact ← is_compact.finite_cover_balls end compact section proper_space open metric /-- A pseudometric space is proper if all closed balls are compact. -/ class proper_space (α : Type u) [pseudo_metric_space α] : Prop := (is_compact_closed_ball : ∀x:α, ∀r, is_compact (closed_ball x r)) /-- In a proper pseudometric space, all spheres are compact. -/ lemma is_compact_sphere {α : Type*} [pseudo_metric_space α] [proper_space α] (x : α) (r : ℝ) : is_compact (sphere x r) := compact_of_is_closed_subset (proper_space.is_compact_closed_ball x r) is_closed_sphere sphere_subset_closed_ball /-- In a proper pseudometric space, any sphere is a `compact_space` when considered as a subtype. -/ instance {α : Type*} [pseudo_metric_space α] [proper_space α] (x : α) (r : ℝ) : compact_space (sphere x r) := is_compact_iff_compact_space.mp (is_compact_sphere _ _) /-- A proper pseudo metric space is sigma compact, and therefore second countable. -/ @[priority 100] -- see Note [lower instance priority] instance second_countable_of_proper [proper_space α] : second_countable_topology α := begin -- We already have `sigma_compact_space_of_locally_compact_second_countable`, so we don't -- add an instance for `sigma_compact_space`. suffices : sigma_compact_space α, by exactI emetric.second_countable_of_sigma_compact α, rcases em (nonempty α) with ⟨⟨x⟩⟩|hn, { exact ⟨⟨λ n, closed_ball x n, λ n, proper_space.is_compact_closed_ball _ _, Union_closed_ball_nat _⟩⟩ }, { exact ⟨⟨λ n, ∅, λ n, is_compact_empty, Union_eq_univ_iff.2 $ λ x, (hn ⟨x⟩).elim⟩⟩ } end lemma tendsto_dist_right_cocompact_at_top [proper_space α] (x : α) : tendsto (λ y, dist y x) (cocompact α) at_top := (has_basis_cocompact.tendsto_iff at_top_basis).2 $ λ r hr, ⟨closed_ball x r, proper_space.is_compact_closed_ball x r, λ y hy, (not_le.1 $ mt mem_closed_ball.2 hy).le⟩ lemma tendsto_dist_left_cocompact_at_top [proper_space α] (x : α) : tendsto (dist x) (cocompact α) at_top := by simpa only [dist_comm] using tendsto_dist_right_cocompact_at_top x /-- If all closed balls of large enough radius are compact, then the space is proper. Especially useful when the lower bound for the radius is 0. -/ lemma proper_space_of_compact_closed_ball_of_le (R : ℝ) (h : ∀x:α, ∀r, R ≤ r → is_compact (closed_ball x r)) : proper_space α := ⟨begin assume x r, by_cases hr : R ≤ r, { exact h x r hr }, { have : closed_ball x r = closed_ball x R ∩ closed_ball x r, { symmetry, apply inter_eq_self_of_subset_right, exact closed_ball_subset_closed_ball (le_of_lt (not_le.1 hr)) }, rw this, exact (h x R (le_refl _)).inter_right is_closed_ball } end⟩ /- A compact pseudometric space is proper -/ @[priority 100] -- see Note [lower instance priority] instance proper_of_compact [compact_space α] : proper_space α := ⟨assume x r, is_closed_ball.is_compact⟩ /-- A proper space is locally compact -/ @[priority 100] -- see Note [lower instance priority] instance locally_compact_of_proper [proper_space α] : locally_compact_space α := locally_compact_space_of_has_basis (λ x, nhds_basis_closed_ball) $ λ x ε ε0, proper_space.is_compact_closed_ball _ _ /-- A proper space is complete -/ @[priority 100] -- see Note [lower instance priority] instance complete_of_proper [proper_space α] : complete_space α := ⟨begin intros f hf, /- We want to show that the Cauchy filter `f` is converging. It suffices to find a closed ball (therefore compact by properness) where it is nontrivial. -/ obtain ⟨t, t_fset, ht⟩ : ∃ t ∈ f, ∀ x y ∈ t, dist x y < 1 := (metric.cauchy_iff.1 hf).2 1 zero_lt_one, rcases hf.1.nonempty_of_mem t_fset with ⟨x, xt⟩, have : closed_ball x 1 ∈ f := mem_of_superset t_fset (λ y yt, (ht y x yt xt).le), rcases (compact_iff_totally_bounded_complete.1 (proper_space.is_compact_closed_ball x 1)).2 f hf (le_principal_iff.2 this) with ⟨y, -, hy⟩, exact ⟨y, hy⟩ end⟩ /-- A finite product of proper spaces is proper. -/ instance pi_proper_space {π : β → Type*} [fintype β] [∀b, pseudo_metric_space (π b)] [h : ∀b, proper_space (π b)] : proper_space (Πb, π b) := begin refine proper_space_of_compact_closed_ball_of_le 0 (λx r hr, _), rw closed_ball_pi _ hr, apply is_compact_univ_pi (λb, _), apply (h b).is_compact_closed_ball end variables [proper_space α] {x : α} {r : ℝ} {s : set α} /-- If a nonempty ball in a proper space includes a closed set `s`, then there exists a nonempty ball with the same center and a strictly smaller radius that includes `s`. -/ lemma exists_pos_lt_subset_ball (hr : 0 < r) (hs : is_closed s) (h : s ⊆ ball x r) : ∃ r' ∈ Ioo 0 r, s ⊆ ball x r' := begin unfreezingI { rcases eq_empty_or_nonempty s with rfl|hne }, { exact ⟨r / 2, ⟨half_pos hr, half_lt_self hr⟩, empty_subset _⟩ }, have : is_compact s, from compact_of_is_closed_subset (proper_space.is_compact_closed_ball x r) hs (subset.trans h ball_subset_closed_ball), obtain ⟨y, hys, hy⟩ : ∃ y ∈ s, s ⊆ closed_ball x (dist y x), from this.exists_forall_ge hne (continuous_id.dist continuous_const).continuous_on, have hyr : dist y x < r, from h hys, rcases exists_between hyr with ⟨r', hyr', hrr'⟩, exact ⟨r', ⟨dist_nonneg.trans_lt hyr', hrr'⟩, subset.trans hy $ closed_ball_subset_ball hyr'⟩ end /-- If a ball in a proper space includes a closed set `s`, then there exists a ball with the same center and a strictly smaller radius that includes `s`. -/ lemma exists_lt_subset_ball (hs : is_closed s) (h : s ⊆ ball x r) : ∃ r' < r, s ⊆ ball x r' := begin cases le_or_lt r 0 with hr hr, { rw [ball_eq_empty.2 hr, subset_empty_iff] at h, unfreezingI { subst s }, exact (no_bot r).imp (λ r' hr', ⟨hr', empty_subset _⟩) }, { exact (exists_pos_lt_subset_ball hr hs h).imp (λ r' hr', ⟨hr'.fst.2, hr'.snd⟩) } end end proper_space namespace metric section second_countable open topological_space /-- A pseudometric space is second countable if, for every `ε > 0`, there is a countable set which is `ε`-dense. -/ lemma second_countable_of_almost_dense_set (H : ∀ε > (0 : ℝ), ∃ s : set α, countable s ∧ (∀x, ∃y ∈ s, dist x y ≤ ε)) : second_countable_topology α := begin refine emetric.second_countable_of_almost_dense_set (λ ε ε0, _), rcases ennreal.lt_iff_exists_nnreal_btwn.1 ε0 with ⟨ε', ε'0, ε'ε⟩, choose s hsc y hys hyx using H ε' (by exact_mod_cast ε'0), refine ⟨s, hsc, bUnion_eq_univ_iff.2 (λ x, ⟨y x, hys _, le_trans _ ε'ε.le⟩)⟩, exact_mod_cast hyx x end end second_countable end metric lemma lebesgue_number_lemma_of_metric {s : set α} {ι} {c : ι → set α} (hs : is_compact s) (hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) : ∃ δ > 0, ∀ x ∈ s, ∃ i, ball x δ ⊆ c i := let ⟨n, en, hn⟩ := lebesgue_number_lemma hs hc₁ hc₂, ⟨δ, δ0, hδ⟩ := mem_uniformity_dist.1 en in ⟨δ, δ0, assume x hx, let ⟨i, hi⟩ := hn x hx in ⟨i, assume y hy, hi (hδ (mem_ball'.mp hy))⟩⟩ lemma lebesgue_number_lemma_of_metric_sUnion {s : set α} {c : set (set α)} (hs : is_compact s) (hc₁ : ∀ t ∈ c, is_open t) (hc₂ : s ⊆ ⋃₀ c) : ∃ δ > 0, ∀ x ∈ s, ∃ t ∈ c, ball x δ ⊆ t := by rw sUnion_eq_Union at hc₂; simpa using lebesgue_number_lemma_of_metric hs (by simpa) hc₂ namespace metric /-- Boundedness of a subset of a pseudometric space. We formulate the definition to work even in the empty space. -/ def bounded (s : set α) : Prop := ∃C, ∀x y ∈ s, dist x y ≤ C section bounded variables {x : α} {s t : set α} {r : ℝ} @[simp] lemma bounded_empty : bounded (∅ : set α) := ⟨0, by simp⟩ lemma bounded_iff_mem_bounded : bounded s ↔ ∀ x ∈ s, bounded s := ⟨λ h _ _, h, λ H, s.eq_empty_or_nonempty.elim (λ hs, hs.symm ▸ bounded_empty) (λ ⟨x, hx⟩, H x hx)⟩ /-- Subsets of a bounded set are also bounded -/ lemma bounded.mono (incl : s ⊆ t) : bounded t → bounded s := Exists.imp $ λ C hC x y hx hy, hC x y (incl hx) (incl hy) /-- Closed balls are bounded -/ lemma bounded_closed_ball : bounded (closed_ball x r) := ⟨r + r, λ y z hy hz, begin simp only [mem_closed_ball] at *, calc dist y z ≤ dist y x + dist z x : dist_triangle_right _ _ _ ... ≤ r + r : add_le_add hy hz end⟩ /-- Open balls are bounded -/ lemma bounded_ball : bounded (ball x r) := bounded_closed_ball.mono ball_subset_closed_ball /-- Given a point, a bounded subset is included in some ball around this point -/ lemma bounded_iff_subset_ball (c : α) : bounded s ↔ ∃r, s ⊆ closed_ball c r := begin split; rintro ⟨C, hC⟩, { cases s.eq_empty_or_nonempty with h h, { subst s, exact ⟨0, by simp⟩ }, { rcases h with ⟨x, hx⟩, exact ⟨C + dist x c, λ y hy, calc dist y c ≤ dist y x + dist x c : dist_triangle _ _ _ ... ≤ C + dist x c : add_le_add_right (hC y x hy hx) _⟩ } }, { exact bounded_closed_ball.mono hC } end lemma bounded.subset_ball (h : bounded s) (c : α) : ∃ r, s ⊆ closed_ball c r := (bounded_iff_subset_ball c).1 h lemma bounded_closure_of_bounded (h : bounded s) : bounded (closure s) := let ⟨C, h⟩ := h in ⟨C, λ a b ha hb, (is_closed_le' C).closure_subset $ map_mem_closure2 continuous_dist ha hb h⟩ alias bounded_closure_of_bounded ← metric.bounded.closure @[simp] lemma bounded_closure_iff : bounded (closure s) ↔ bounded s := ⟨λ h, h.mono subset_closure, λ h, h.closure⟩ /-- The union of two bounded sets is bounded iff each of the sets is bounded -/ @[simp] lemma bounded_union : bounded (s ∪ t) ↔ bounded s ∧ bounded t := ⟨λh, ⟨h.mono (by simp), h.mono (by simp)⟩, begin rintro ⟨hs, ht⟩, refine bounded_iff_mem_bounded.2 (λ x _, _), rw bounded_iff_subset_ball x at hs ht ⊢, rcases hs with ⟨Cs, hCs⟩, rcases ht with ⟨Ct, hCt⟩, exact ⟨max Cs Ct, union_subset (subset.trans hCs $ closed_ball_subset_closed_ball $ le_max_left _ _) (subset.trans hCt $ closed_ball_subset_closed_ball $ le_max_right _ _)⟩, end⟩ /-- A finite union of bounded sets is bounded -/ lemma bounded_bUnion {I : set β} {s : β → set α} (H : finite I) : bounded (⋃i∈I, s i) ↔ ∀i ∈ I, bounded (s i) := finite.induction_on H (by simp) $ λ x I _ _ IH, by simp [or_imp_distrib, forall_and_distrib, IH] /-- A totally bounded set is bounded -/ lemma _root_.totally_bounded.bounded {s : set α} (h : totally_bounded s) : bounded s := -- We cover the totally bounded set by finitely many balls of radius 1, -- and then argue that a finite union of bounded sets is bounded let ⟨t, fint, subs⟩ := (totally_bounded_iff.mp h) 1 zero_lt_one in bounded.mono subs $ (bounded_bUnion fint).2 $ λ i hi, bounded_ball /-- A compact set is bounded -/ lemma _root_.is_compact.bounded {s : set α} (h : is_compact s) : bounded s := -- A compact set is totally bounded, thus bounded h.totally_bounded.bounded /-- A finite set is bounded -/ lemma bounded_of_finite {s : set α} (h : finite s) : bounded s := h.is_compact.bounded alias bounded_of_finite ← set.finite.bounded /-- A singleton is bounded -/ lemma bounded_singleton {x : α} : bounded ({x} : set α) := bounded_of_finite $ finite_singleton _ /-- Characterization of the boundedness of the range of a function -/ lemma bounded_range_iff {f : β → α} : bounded (range f) ↔ ∃C, ∀x y, dist (f x) (f y) ≤ C := exists_congr $ λ C, ⟨ λ H x y, H _ _ ⟨x, rfl⟩ ⟨y, rfl⟩, by rintro H _ _ ⟨x, rfl⟩ ⟨y, rfl⟩; exact H x y⟩ /-- In a compact space, all sets are bounded -/ lemma bounded_of_compact_space [compact_space α] : bounded s := compact_univ.bounded.mono (subset_univ _) lemma is_compact_of_is_closed_bounded [proper_space α] (hc : is_closed s) (hb : bounded s) : is_compact s := begin unfreezingI { rcases eq_empty_or_nonempty s with (rfl|⟨x, hx⟩) }, { exact is_compact_empty }, { rcases hb.subset_ball x with ⟨r, hr⟩, exact compact_of_is_closed_subset (proper_space.is_compact_closed_ball x r) hc hr } end /-- The Heine–Borel theorem: In a proper space, a set is compact if and only if it is closed and bounded -/ lemma compact_iff_closed_bounded [t2_space α] [proper_space α] : is_compact s ↔ is_closed s ∧ bounded s := ⟨λ h, ⟨h.is_closed, h.bounded⟩, λ h, is_compact_of_is_closed_bounded h.1 h.2⟩ lemma compact_space_iff_bounded_univ [proper_space α] : compact_space α ↔ bounded (univ : set α) := ⟨@bounded_of_compact_space α _ _, λ hb, ⟨is_compact_of_is_closed_bounded is_closed_univ hb⟩⟩ section conditionally_complete_linear_order variables [conditionally_complete_linear_order α] [order_topology α] lemma bounded_Icc (a b : α) : bounded (Icc a b) := (totally_bounded_Icc a b).bounded lemma bounded_Ico (a b : α) : bounded (Ico a b) := (totally_bounded_Ico a b).bounded lemma bounded_Ioc (a b : α) : bounded (Ioc a b) := (totally_bounded_Ioc a b).bounded lemma bounded_Ioo (a b : α) : bounded (Ioo a b) := (totally_bounded_Ioo a b).bounded /-- In a pseudo metric space with a conditionally complete linear order such that the order and the metric structure give the same topology, any order-bounded set is metric-bounded. -/ lemma bounded_of_bdd_above_of_bdd_below {s : set α} (h₁ : bdd_above s) (h₂ : bdd_below s) : bounded s := let ⟨u, hu⟩ := h₁, ⟨l, hl⟩ := h₂ in bounded.mono (λ x hx, mem_Icc.mpr ⟨hl hx, hu hx⟩) (bounded_Icc l u) end conditionally_complete_linear_order end bounded section diam variables {s : set α} {x y z : α} /-- The diameter of a set in a metric space. To get controllable behavior even when the diameter should be infinite, we express it in terms of the emetric.diameter -/ noncomputable def diam (s : set α) : ℝ := ennreal.to_real (emetric.diam s) /-- The diameter of a set is always nonnegative -/ lemma diam_nonneg : 0 ≤ diam s := ennreal.to_real_nonneg lemma diam_subsingleton (hs : s.subsingleton) : diam s = 0 := by simp only [diam, emetric.diam_subsingleton hs, ennreal.zero_to_real] /-- The empty set has zero diameter -/ @[simp] lemma diam_empty : diam (∅ : set α) = 0 := diam_subsingleton subsingleton_empty /-- A singleton has zero diameter -/ @[simp] lemma diam_singleton : diam ({x} : set α) = 0 := diam_subsingleton subsingleton_singleton -- Does not work as a simp-lemma, since {x, y} reduces to (insert y {x}) lemma diam_pair : diam ({x, y} : set α) = dist x y := by simp only [diam, emetric.diam_pair, dist_edist] -- Does not work as a simp-lemma, since {x, y, z} reduces to (insert z (insert y {x})) lemma diam_triple : metric.diam ({x, y, z} : set α) = max (max (dist x y) (dist x z)) (dist y z) := begin simp only [metric.diam, emetric.diam_triple, dist_edist], rw [ennreal.to_real_max, ennreal.to_real_max]; apply_rules [ne_of_lt, edist_lt_top, max_lt] end /-- If the distance between any two points in a set is bounded by some constant `C`, then `ennreal.of_real C` bounds the emetric diameter of this set. -/ lemma ediam_le_of_forall_dist_le {C : ℝ} (h : ∀ (x ∈ s) (y ∈ s), dist x y ≤ C) : emetric.diam s ≤ ennreal.of_real C := emetric.diam_le $ λ x hx y hy, (edist_dist x y).symm ▸ ennreal.of_real_le_of_real (h x hx y hy) /-- If the distance between any two points in a set is bounded by some non-negative constant, this constant bounds the diameter. -/ lemma diam_le_of_forall_dist_le {C : ℝ} (h₀ : 0 ≤ C) (h : ∀ (x ∈ s) (y ∈ s), dist x y ≤ C) : diam s ≤ C := ennreal.to_real_le_of_le_of_real h₀ (ediam_le_of_forall_dist_le h) /-- If the distance between any two points in a nonempty set is bounded by some constant, this constant bounds the diameter. -/ lemma diam_le_of_forall_dist_le_of_nonempty (hs : s.nonempty) {C : ℝ} (h : ∀ (x ∈ s) (y ∈ s), dist x y ≤ C) : diam s ≤ C := have h₀ : 0 ≤ C, from let ⟨x, hx⟩ := hs in le_trans dist_nonneg (h x hx x hx), diam_le_of_forall_dist_le h₀ h /-- The distance between two points in a set is controlled by the diameter of the set. -/ lemma dist_le_diam_of_mem' (h : emetric.diam s ≠ ⊤) (hx : x ∈ s) (hy : y ∈ s) : dist x y ≤ diam s := begin rw [diam, dist_edist], rw ennreal.to_real_le_to_real (edist_ne_top _ _) h, exact emetric.edist_le_diam_of_mem hx hy end /-- Characterize the boundedness of a set in terms of the finiteness of its emetric.diameter. -/ lemma bounded_iff_ediam_ne_top : bounded s ↔ emetric.diam s ≠ ⊤ := iff.intro (λ ⟨C, hC⟩, ne_top_of_le_ne_top ennreal.of_real_ne_top (ediam_le_of_forall_dist_le $ λ x hx y hy, hC x y hx hy)) (λ h, ⟨diam s, λ x y hx hy, dist_le_diam_of_mem' h hx hy⟩) lemma bounded.ediam_ne_top (h : bounded s) : emetric.diam s ≠ ⊤ := bounded_iff_ediam_ne_top.1 h lemma ediam_univ_eq_top_iff_noncompact [proper_space α] : emetric.diam (univ : set α) = ∞ ↔ noncompact_space α := by rw [← not_compact_space_iff, compact_space_iff_bounded_univ, bounded_iff_ediam_ne_top, not_not] @[simp] lemma ediam_univ_of_noncompact [proper_space α] [noncompact_space α] : emetric.diam (univ : set α) = ∞ := ediam_univ_eq_top_iff_noncompact.mpr ‹_› @[simp] lemma diam_univ_of_noncompact [proper_space α] [noncompact_space α] : diam (univ : set α) = 0 := by simp [diam] /-- The distance between two points in a set is controlled by the diameter of the set. -/ lemma dist_le_diam_of_mem (h : bounded s) (hx : x ∈ s) (hy : y ∈ s) : dist x y ≤ diam s := dist_le_diam_of_mem' h.ediam_ne_top hx hy lemma ediam_of_unbounded (h : ¬(bounded s)) : emetric.diam s = ∞ := by rwa [bounded_iff_ediam_ne_top, not_not] at h /-- An unbounded set has zero diameter. If you would prefer to get the value ∞, use `emetric.diam`. This lemma makes it possible to avoid side conditions in some situations -/ lemma diam_eq_zero_of_unbounded (h : ¬(bounded s)) : diam s = 0 := by rw [diam, ediam_of_unbounded h, ennreal.top_to_real] /-- If `s ⊆ t`, then the diameter of `s` is bounded by that of `t`, provided `t` is bounded. -/ lemma diam_mono {s t : set α} (h : s ⊆ t) (ht : bounded t) : diam s ≤ diam t := begin unfold diam, rw ennreal.to_real_le_to_real (bounded.mono h ht).ediam_ne_top ht.ediam_ne_top, exact emetric.diam_mono h end /-- The diameter of a union is controlled by the sum of the diameters, and the distance between any two points in each of the sets. This lemma is true without any side condition, since it is obviously true if `s ∪ t` is unbounded. -/ lemma diam_union {t : set α} (xs : x ∈ s) (yt : y ∈ t) : diam (s ∪ t) ≤ diam s + dist x y + diam t := begin by_cases H : bounded (s ∪ t), { have hs : bounded s, from H.mono (subset_union_left _ _), have ht : bounded t, from H.mono (subset_union_right _ _), rw [bounded_iff_ediam_ne_top] at H hs ht, rw [dist_edist, diam, diam, diam, ← ennreal.to_real_add, ← ennreal.to_real_add, ennreal.to_real_le_to_real]; repeat { apply ennreal.add_ne_top.2; split }; try { assumption }; try { apply edist_ne_top }, exact emetric.diam_union xs yt }, { rw [diam_eq_zero_of_unbounded H], apply_rules [add_nonneg, diam_nonneg, dist_nonneg] } end /-- If two sets intersect, the diameter of the union is bounded by the sum of the diameters. -/ lemma diam_union' {t : set α} (h : (s ∩ t).nonempty) : diam (s ∪ t) ≤ diam s + diam t := begin rcases h with ⟨x, ⟨xs, xt⟩⟩, simpa using diam_union xs xt end /-- The diameter of a closed ball of radius `r` is at most `2 r`. -/ lemma diam_closed_ball {r : ℝ} (h : 0 ≤ r) : diam (closed_ball x r) ≤ 2 * r := diam_le_of_forall_dist_le (mul_nonneg (le_of_lt zero_lt_two) h) $ λa ha b hb, calc dist a b ≤ dist a x + dist b x : dist_triangle_right _ _ _ ... ≤ r + r : add_le_add ha hb ... = 2 * r : by simp [mul_two, mul_comm] /-- The diameter of a ball of radius `r` is at most `2 r`. -/ lemma diam_ball {r : ℝ} (h : 0 ≤ r) : diam (ball x r) ≤ 2 * r := le_trans (diam_mono ball_subset_closed_ball bounded_closed_ball) (diam_closed_ball h) end diam end metric lemma comap_dist_right_at_top_le_cocompact (x : α) : comap (λ y, dist y x) at_top ≤ cocompact α := begin refine filter.has_basis_cocompact.ge_iff.2 (λ s hs, mem_comap.2 _), rcases hs.bounded.subset_ball x with ⟨r, hr⟩, exact ⟨Ioi r, Ioi_mem_at_top r, λ y hy hys, (mem_closed_ball.1 $ hr hys).not_lt hy⟩ end lemma comap_dist_left_at_top_le_cocompact (x : α) : comap (dist x) at_top ≤ cocompact α := by simpa only [dist_comm _ x] using comap_dist_right_at_top_le_cocompact x lemma comap_dist_right_at_top_eq_cocompact [proper_space α] (x : α) : comap (λ y, dist y x) at_top = cocompact α := (comap_dist_right_at_top_le_cocompact x).antisymm $ (tendsto_dist_right_cocompact_at_top x).le_comap lemma comap_dist_left_at_top_eq_cocompact [proper_space α] (x : α) : comap (dist x) at_top = cocompact α := (comap_dist_left_at_top_le_cocompact x).antisymm $ (tendsto_dist_left_cocompact_at_top x).le_comap lemma tendsto_cocompact_of_tendsto_dist_comp_at_top {f : β → α} {l : filter β} (x : α) (h : tendsto (λ y, dist (f y) x) l at_top) : tendsto f l (cocompact α) := by { refine tendsto.mono_right _ (comap_dist_right_at_top_le_cocompact x), rwa tendsto_comap_iff } namespace int open metric /-- Under the coercion from `ℤ` to `ℝ`, inverse images of compact sets are finite. -/ lemma tendsto_coe_cofinite : tendsto (coe : ℤ → ℝ) cofinite (cocompact ℝ) := begin refine tendsto_cocompact_of_tendsto_dist_comp_at_top (0 : ℝ) _, simp only [filter.tendsto_at_top, eventually_cofinite, not_le, ← mem_ball], change ∀ r : ℝ, finite (coe ⁻¹' (ball (0 : ℝ) r)), simp [real.ball_eq, set.finite_Ioo], end end int /-- We now define `metric_space`, extending `pseudo_metric_space`. -/ class metric_space (α : Type u) extends pseudo_metric_space α : Type u := (eq_of_dist_eq_zero : ∀ {x y : α}, dist x y = 0 → x = y) /-- Construct a metric space structure whose underlying topological space structure (definitionally) agrees which a pre-existing topology which is compatible with a given distance function. -/ def metric_space.of_metrizable {α : Type*} [topological_space α] (dist : α → α → ℝ) (dist_self : ∀ x : α, dist x x = 0) (dist_comm : ∀ x y : α, dist x y = dist y x) (dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) (H : ∀ s : set α, is_open s ↔ ∀ x ∈ s, ∃ ε > 0, ∀ y, dist x y < ε → y ∈ s) (eq_of_dist_eq_zero : ∀ x y : α, dist x y = 0 → x = y) : metric_space α := { eq_of_dist_eq_zero := eq_of_dist_eq_zero, ..pseudo_metric_space.of_metrizable dist dist_self dist_comm dist_triangle H } variables {γ : Type w} [metric_space γ] theorem eq_of_dist_eq_zero {x y : γ} : dist x y = 0 → x = y := metric_space.eq_of_dist_eq_zero @[simp] theorem dist_eq_zero {x y : γ} : dist x y = 0 ↔ x = y := iff.intro eq_of_dist_eq_zero (assume : x = y, this ▸ dist_self _) @[simp] theorem zero_eq_dist {x y : γ} : 0 = dist x y ↔ x = y := by rw [eq_comm, dist_eq_zero] theorem dist_ne_zero {x y : γ} : dist x y ≠ 0 ↔ x ≠ y := by simpa only [not_iff_not] using dist_eq_zero @[simp] theorem dist_le_zero {x y : γ} : dist x y ≤ 0 ↔ x = y := by simpa [le_antisymm_iff, dist_nonneg] using @dist_eq_zero _ _ x y @[simp] theorem dist_pos {x y : γ} : 0 < dist x y ↔ x ≠ y := by simpa only [not_le] using not_congr dist_le_zero theorem eq_of_forall_dist_le {x y : γ} (h : ∀ ε > 0, dist x y ≤ ε) : x = y := eq_of_dist_eq_zero (eq_of_le_of_forall_le_of_dense dist_nonneg h) /--Deduce the equality of points with the vanishing of the nonnegative distance-/ theorem eq_of_nndist_eq_zero {x y : γ} : nndist x y = 0 → x = y := by simp only [← nnreal.eq_iff, ← dist_nndist, imp_self, nnreal.coe_zero, dist_eq_zero] /--Characterize the equality of points with the vanishing of the nonnegative distance-/ @[simp] theorem nndist_eq_zero {x y : γ} : nndist x y = 0 ↔ x = y := by simp only [← nnreal.eq_iff, ← dist_nndist, imp_self, nnreal.coe_zero, dist_eq_zero] @[simp] theorem zero_eq_nndist {x y : γ} : 0 = nndist x y ↔ x = y := by simp only [← nnreal.eq_iff, ← dist_nndist, imp_self, nnreal.coe_zero, zero_eq_dist] namespace metric variables {x : γ} {s : set γ} @[simp] lemma closed_ball_zero : closed_ball x 0 = {x} := set.ext $ λ y, dist_le_zero /-- A map between metric spaces is a uniform embedding if and only if the distance between `f x` and `f y` is controlled in terms of the distance between `x` and `y` and conversely. -/ theorem uniform_embedding_iff' [metric_space β] {f : γ → β} : uniform_embedding f ↔ (∀ ε > 0, ∃ δ > 0, ∀ {a b : γ}, dist a b < δ → dist (f a) (f b) < ε) ∧ (∀ δ > 0, ∃ ε > 0, ∀ {a b : γ}, dist (f a) (f b) < ε → dist a b < δ) := begin split, { assume h, exact ⟨uniform_continuous_iff.1 (uniform_embedding_iff.1 h).2.1, (uniform_embedding_iff.1 h).2.2⟩ }, { rintros ⟨h₁, h₂⟩, refine uniform_embedding_iff.2 ⟨_, uniform_continuous_iff.2 h₁, h₂⟩, assume x y hxy, have : dist x y ≤ 0, { refine le_of_forall_lt' (λδ δpos, _), rcases h₂ δ δpos with ⟨ε, εpos, hε⟩, have : dist (f x) (f y) < ε, by simpa [hxy], exact hε this }, simpa using this } end @[priority 100] -- see Note [lower instance priority] instance metric_space.to_separated : separated_space γ := separated_def.2 $ λ x y h, eq_of_forall_dist_le $ λ ε ε0, le_of_lt (h _ (dist_mem_uniformity ε0)) /-- If a `pseudo_metric_space` is separated, then it is a `metric_space`. -/ def of_t2_pseudo_metric_space {α : Type*} [pseudo_metric_space α] (h : separated_space α) : metric_space α := { eq_of_dist_eq_zero := λ x y hdist, begin refine separated_def.1 h x y (λ s hs, _), obtain ⟨ε, hε, H⟩ := mem_uniformity_dist.1 hs, exact H (show dist x y < ε, by rwa [hdist]) end ..‹pseudo_metric_space α› } /-- A metric space induces an emetric space -/ @[priority 100] -- see Note [lower instance priority] instance metric_space.to_emetric_space : emetric_space γ := { eq_of_edist_eq_zero := assume x y h, by simpa [edist_dist] using h, ..pseudo_metric_space.to_pseudo_emetric_space, } lemma is_closed_of_pairwise_le_dist {s : set γ} {ε : ℝ} (hε : 0 < ε) (hs : s.pairwise (λ x y, ε ≤ dist x y)) : is_closed s := is_closed_of_spaced_out (dist_mem_uniformity hε) $ by simpa using hs lemma closed_embedding_of_pairwise_le_dist {α : Type*} [topological_space α] [discrete_topology α] {ε : ℝ} (hε : 0 < ε) {f : α → γ} (hf : pairwise (λ x y, ε ≤ dist (f x) (f y))) : closed_embedding f := closed_embedding_of_spaced_out (dist_mem_uniformity hε) $ by simpa using hf /-- If `f : β → α` sends any two distinct points to points at distance at least `ε > 0`, then `f` is a uniform embedding with respect to the discrete uniformity on `β`. -/ lemma uniform_embedding_bot_of_pairwise_le_dist {β : Type*} {ε : ℝ} (hε : 0 < ε) {f : β → α} (hf : pairwise (λ x y, ε ≤ dist (f x) (f y))) : @uniform_embedding _ _ ⊥ (by apply_instance) f := uniform_embedding_of_spaced_out (dist_mem_uniformity hε) $ by simpa using hf end metric /-- Build a new metric space from an old one where the bundled uniform structure is provably (but typically non-definitionaly) equal to some given uniform structure. See Note [forgetful inheritance]. -/ def metric_space.replace_uniformity {γ} [U : uniform_space γ] (m : metric_space γ) (H : @uniformity _ U = @uniformity _ emetric_space.to_uniform_space') : metric_space γ := { eq_of_dist_eq_zero := @eq_of_dist_eq_zero _ _, ..pseudo_metric_space.replace_uniformity m.to_pseudo_metric_space H, } /-- One gets a metric space from an emetric space if the edistance is everywhere finite, by pushing the edistance to reals. We set it up so that the edist and the uniformity are defeq in the metric space and the emetric space. In this definition, the distance is given separately, to be able to prescribe some expression which is not defeq to the push-forward of the edistance to reals. -/ def emetric_space.to_metric_space_of_dist {α : Type u} [e : emetric_space α] (dist : α → α → ℝ) (edist_ne_top : ∀x y: α, edist x y ≠ ⊤) (h : ∀x y, dist x y = ennreal.to_real (edist x y)) : metric_space α := { dist := dist, eq_of_dist_eq_zero := λx y hxy, by simpa [h, ennreal.to_real_eq_zero_iff, edist_ne_top x y] using hxy, ..pseudo_emetric_space.to_pseudo_metric_space_of_dist dist edist_ne_top h, } /-- One gets a metric space from an emetric space if the edistance is everywhere finite, by pushing the edistance to reals. We set it up so that the edist and the uniformity are defeq in the metric space and the emetric space. -/ def emetric_space.to_metric_space {α : Type u} [e : emetric_space α] (h : ∀x y: α, edist x y ≠ ⊤) : metric_space α := emetric_space.to_metric_space_of_dist (λx y, ennreal.to_real (edist x y)) h (λx y, rfl) /-- Metric space structure pulled back by an injective function. Injectivity is necessary to ensure that `dist x y = 0` only if `x = y`. -/ def metric_space.induced {γ β} (f : γ → β) (hf : function.injective f) (m : metric_space β) : metric_space γ := { eq_of_dist_eq_zero := λ x y h, hf (dist_eq_zero.1 h), ..pseudo_metric_space.induced f m.to_pseudo_metric_space } /-- Pull back a metric space structure by a uniform embedding. This is a version of `metric_space.induced` useful in case if the domain already has a `uniform_space` structure. -/ def uniform_embedding.comap_metric_space {α β} [uniform_space α] [metric_space β] (f : α → β) (h : uniform_embedding f) : metric_space α := (metric_space.induced f h.inj ‹_›).replace_uniformity h.comap_uniformity.symm instance subtype.metric_space {α : Type*} {p : α → Prop} [t : metric_space α] : metric_space (subtype p) := metric_space.induced coe (λ x y, subtype.ext) t theorem subtype.dist_eq {p : α → Prop} (x y : subtype p) : dist x y = dist (x : α) y := rfl instance : metric_space empty := { dist := λ _ _, 0, dist_self := λ _, rfl, dist_comm := λ _ _, rfl, eq_of_dist_eq_zero := λ _ _ _, subsingleton.elim _ _, dist_triangle := λ _ _ _, show (0:ℝ) ≤ 0 + 0, by rw add_zero, } instance : metric_space punit := { dist := λ _ _, 0, dist_self := λ _, rfl, dist_comm := λ _ _, rfl, eq_of_dist_eq_zero := λ _ _ _, subsingleton.elim _ _, dist_triangle := λ _ _ _, show (0:ℝ) ≤ 0 + 0, by rw add_zero, } section real /-- Instantiate the reals as a metric space. -/ noncomputable instance real.metric_space : metric_space ℝ := { eq_of_dist_eq_zero := λ x y h, by simpa [dist, sub_eq_zero] using h, ..real.pseudo_metric_space } end real section nnreal noncomputable instance : metric_space ℝ≥0 := subtype.metric_space end nnreal section prod noncomputable instance prod.metric_space_max [metric_space β] : metric_space (γ × β) := { eq_of_dist_eq_zero := λ x y h, begin cases max_le_iff.1 (le_of_eq h) with h₁ h₂, exact prod.ext_iff.2 ⟨dist_le_zero.1 h₁, dist_le_zero.1 h₂⟩ end, ..prod.pseudo_metric_space_max, } end prod section pi open finset variables {π : β → Type*} [fintype β] [∀b, metric_space (π b)] /-- A finite product of metric spaces is a metric space, with the sup distance. -/ noncomputable instance metric_space_pi : metric_space (Πb, π b) := /- we construct the instance from the emetric space instance to avoid checking again that the uniformity is the same as the product uniformity, but we register nevertheless a nice formula for the distance -/ { eq_of_dist_eq_zero := assume f g eq0, begin have eq1 : edist f g = 0 := by simp only [edist_dist, eq0, ennreal.of_real_zero], have eq2 : sup univ (λ (b : β), edist (f b) (g b)) ≤ 0 := le_of_eq eq1, simp only [finset.sup_le_iff] at eq2, exact (funext $ assume b, edist_le_zero.1 $ eq2 b $ mem_univ b) end, ..pseudo_metric_space_pi } end pi namespace metric section second_countable open topological_space /-- A metric space is second countable if one can reconstruct up to any `ε>0` any element of the space from countably many data. -/ lemma second_countable_of_countable_discretization {α : Type u} [metric_space α] (H : ∀ε > (0 : ℝ), ∃ (β : Type*) (_ : encodable β) (F : α → β), ∀x y, F x = F y → dist x y ≤ ε) : second_countable_topology α := begin cases (univ : set α).eq_empty_or_nonempty with hs hs, { haveI : compact_space α := ⟨by rw hs; exact is_compact_empty⟩, by apply_instance }, rcases hs with ⟨x0, hx0⟩, letI : inhabited α := ⟨x0⟩, refine second_countable_of_almost_dense_set (λε ε0, _), rcases H ε ε0 with ⟨β, fβ, F, hF⟩, resetI, let Finv := function.inv_fun F, refine ⟨range Finv, ⟨countable_range _, λx, _⟩⟩, let x' := Finv (F x), have : F x' = F x := function.inv_fun_eq ⟨x, rfl⟩, exact ⟨x', mem_range_self _, hF _ _ this.symm⟩ end end second_countable end metric section eq_rel /-- The canonical equivalence relation on a pseudometric space. -/ def pseudo_metric.dist_setoid (α : Type u) [pseudo_metric_space α] : setoid α := setoid.mk (λx y, dist x y = 0) begin unfold equivalence, repeat { split }, { exact pseudo_metric_space.dist_self }, { assume x y h, rwa pseudo_metric_space.dist_comm }, { assume x y z hxy hyz, refine le_antisymm _ dist_nonneg, calc dist x z ≤ dist x y + dist y z : pseudo_metric_space.dist_triangle _ _ _ ... = 0 + 0 : by rw [hxy, hyz] ... = 0 : by simp } end local attribute [instance] pseudo_metric.dist_setoid /-- The canonical quotient of a pseudometric space, identifying points at distance `0`. -/ @[reducible] definition pseudo_metric_quot (α : Type u) [pseudo_metric_space α] : Type* := quotient (pseudo_metric.dist_setoid α) instance has_dist_metric_quot {α : Type u} [pseudo_metric_space α] : has_dist (pseudo_metric_quot α) := { dist := quotient.lift₂ (λp q : α, dist p q) begin assume x y x' y' hxx' hyy', have Hxx' : dist x x' = 0 := hxx', have Hyy' : dist y y' = 0 := hyy', have A : dist x y ≤ dist x' y' := calc dist x y ≤ dist x x' + dist x' y : pseudo_metric_space.dist_triangle _ _ _ ... = dist x' y : by simp [Hxx'] ... ≤ dist x' y' + dist y' y : pseudo_metric_space.dist_triangle _ _ _ ... = dist x' y' : by simp [pseudo_metric_space.dist_comm, Hyy'], have B : dist x' y' ≤ dist x y := calc dist x' y' ≤ dist x' x + dist x y' : pseudo_metric_space.dist_triangle _ _ _ ... = dist x y' : by simp [pseudo_metric_space.dist_comm, Hxx'] ... ≤ dist x y + dist y y' : pseudo_metric_space.dist_triangle _ _ _ ... = dist x y : by simp [Hyy'], exact le_antisymm A B end } lemma pseudo_metric_quot_dist_eq {α : Type u} [pseudo_metric_space α] (p q : α) : dist ⟦p⟧ ⟦q⟧ = dist p q := rfl instance metric_space_quot {α : Type u} [pseudo_metric_space α] : metric_space (pseudo_metric_quot α) := { dist_self := begin refine quotient.ind (λy, _), exact pseudo_metric_space.dist_self _ end, eq_of_dist_eq_zero := λxc yc, by exact quotient.induction_on₂ xc yc (λx y H, quotient.sound H), dist_comm := λxc yc, quotient.induction_on₂ xc yc (λx y, pseudo_metric_space.dist_comm _ _), dist_triangle := λxc yc zc, quotient.induction_on₃ xc yc zc (λx y z, pseudo_metric_space.dist_triangle _ _ _) } end eq_rel
427b8dd508a70ca3b0289e8c9696d04a1e605eff
ff5230333a701471f46c57e8c115a073ebaaa448
/library/init/algebra/order.lean
ab3f8320ab324a3e02cc88fe974e7bab664fa26f
[ "Apache-2.0" ]
permissive
stanford-cs242/lean
f81721d2b5d00bc175f2e58c57b710d465e6c858
7bd861261f4a37326dcf8d7a17f1f1f330e4548c
refs/heads/master
1,600,957,431,849
1,576,465,093,000
1,576,465,093,000
225,779,423
0
3
Apache-2.0
1,575,433,936,000
1,575,433,935,000
null
UTF-8
Lean
false
false
9,253
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.logic init.classical init.meta.name init.algebra.classes /- Make sure instances defined in this file have lower priority than the ones defined for concrete structures -/ set_option default_priority 100 set_option old_structure_cmd true universe u variables {α : Type u} set_option auto_param.check_exists false /-- A preorder is a reflexive, transitive relation `≤` with `a < b` defined in the obvious way. -/ class preorder (α : Type u) extends has_le α, has_lt α := (le_refl : ∀ a : α, a ≤ a) (le_trans : ∀ a b c : α, a ≤ b → b ≤ c → a ≤ c) (lt := λ a b, a ≤ b ∧ ¬ b ≤ a) (lt_iff_le_not_le : ∀ a b : α, a < b ↔ (a ≤ b ∧ ¬ b ≤ a) . order_laws_tac) /-- A partial order is a reflexive, transitive, antisymmetric relation `≤`. -/ class partial_order (α : Type u) extends preorder α := (le_antisymm : ∀ a b : α, a ≤ b → b ≤ a → a = b) /-- A linear order is reflexive, transitive, antisymmetric and total relation `≤`.-/ class linear_order (α : Type u) extends partial_order α := (le_total : ∀ a b : α, a ≤ b ∨ b ≤ a) @[refl] lemma le_refl [preorder α] : ∀ a : α, a ≤ a := preorder.le_refl @[trans] lemma le_trans [preorder α] : ∀ {a b c : α}, a ≤ b → b ≤ c → a ≤ c := preorder.le_trans lemma lt_iff_le_not_le [preorder α] : ∀ {a b : α}, a < b ↔ (a ≤ b ∧ ¬ b ≤ a) := preorder.lt_iff_le_not_le _ lemma lt_of_le_not_le [preorder α] : ∀ {a b : α}, a ≤ b → ¬ b ≤ a → a < b | a b hab hba := lt_iff_le_not_le.mpr ⟨hab, hba⟩ lemma le_not_le_of_lt [preorder α] : ∀ {a b : α}, a < b → a ≤ b ∧ ¬ b ≤ a | a b hab := lt_iff_le_not_le.mp hab lemma le_antisymm [partial_order α] : ∀ {a b : α}, a ≤ b → b ≤ a → a = b := partial_order.le_antisymm lemma le_of_eq [preorder α] {a b : α} : a = b → a ≤ b := λ h, h ▸ le_refl a lemma le_antisymm_iff [partial_order α] {a b : α} : a = b ↔ a ≤ b ∧ b ≤ a := ⟨λe, ⟨le_of_eq e, le_of_eq e.symm⟩, λ⟨h1, h2⟩, le_antisymm h1 h2⟩ @[trans] lemma ge_trans [preorder α] : ∀ {a b c : α}, a ≥ b → b ≥ c → a ≥ c := λ a b c h₁ h₂, le_trans h₂ h₁ lemma le_total [linear_order α] : ∀ a b : α, a ≤ b ∨ b ≤ a := linear_order.le_total lemma le_of_not_ge [linear_order α] {a b : α} : ¬ a ≥ b → a ≤ b := or.resolve_left (le_total b a) lemma le_of_not_le [linear_order α] {a b : α} : ¬ a ≤ b → b ≤ a := or.resolve_left (le_total a b) lemma lt_irrefl [preorder α] : ∀ a : α, ¬ a < a | a haa := match le_not_le_of_lt haa with | ⟨h1, h2⟩ := false.rec _ (h2 h1) end lemma gt_irrefl [preorder α] : ∀ a : α, ¬ a > a := lt_irrefl @[trans] lemma lt_trans [preorder α] : ∀ {a b c : α}, a < b → b < c → a < c | a b c hab hbc := match le_not_le_of_lt hab, le_not_le_of_lt hbc with | ⟨hab, hba⟩, ⟨hbc, hcb⟩ := lt_of_le_not_le (le_trans hab hbc) (λ hca, hcb (le_trans hca hab)) end def lt.trans := @lt_trans @[trans] lemma gt_trans [preorder α] : ∀ {a b c : α}, a > b → b > c → a > c := λ a b c h₁ h₂, lt_trans h₂ h₁ def gt.trans := @gt_trans lemma ne_of_lt [preorder α] {a b : α} (h : a < b) : a ≠ b := λ he, absurd h (he ▸ lt_irrefl a) lemma ne_of_gt [preorder α] {a b : α} (h : a > b) : a ≠ b := λ he, absurd h (he ▸ lt_irrefl a) lemma lt_asymm [preorder α] {a b : α} (h : a < b) : ¬ b < a := λ h1 : b < a, lt_irrefl a (lt_trans h h1) lemma not_lt_of_gt [linear_order α] {a b : α} (h : a > b) : ¬ a < b := lt_asymm h lemma le_of_lt [preorder α] : ∀ {a b : α}, a < b → a ≤ b | a b hab := (le_not_le_of_lt hab).left @[trans] lemma lt_of_lt_of_le [preorder α] : ∀ {a b c : α}, a < b → b ≤ c → a < c | a b c hab hbc := let ⟨hab, hba⟩ := le_not_le_of_lt hab in lt_of_le_not_le (le_trans hab hbc) $ λ hca, hba (le_trans hbc hca) @[trans] lemma lt_of_le_of_lt [preorder α] : ∀ {a b c : α}, a ≤ b → b < c → a < c | a b c hab hbc := let ⟨hbc, hcb⟩ := le_not_le_of_lt hbc in lt_of_le_not_le (le_trans hab hbc) $ λ hca, hcb (le_trans hca hab) @[trans] lemma gt_of_gt_of_ge [preorder α] {a b c : α} (h₁ : a > b) (h₂ : b ≥ c) : a > c := lt_of_le_of_lt h₂ h₁ @[trans] lemma gt_of_ge_of_gt [preorder α] {a b c : α} (h₁ : a ≥ b) (h₂ : b > c) : a > c := lt_of_lt_of_le h₂ h₁ lemma not_le_of_gt [preorder α] {a b : α} (h : a > b) : ¬ a ≤ b := (le_not_le_of_lt h).right lemma not_lt_of_ge [preorder α] {a b : α} (h : a ≥ b) : ¬ a < b := λ hab, not_le_of_gt hab h lemma lt_or_eq_of_le [partial_order α] : ∀ {a b : α}, a ≤ b → a < b ∨ a = b | a b hab := classical.by_cases (λ hba : b ≤ a, or.inr (le_antisymm hab hba)) (λ hba, or.inl (lt_of_le_not_le hab hba)) lemma le_of_lt_or_eq [preorder α] : ∀ {a b : α}, (a < b ∨ a = b) → a ≤ b | a b (or.inl hab) := le_of_lt hab | a b (or.inr hab) := hab ▸ le_refl _ lemma le_iff_lt_or_eq [partial_order α] : ∀ {a b : α}, a ≤ b ↔ a < b ∨ a = b | a b := ⟨lt_or_eq_of_le, le_of_lt_or_eq⟩ lemma lt_of_le_of_ne [partial_order α] {a b : α} : a ≤ b → a ≠ b → a < b := λ h₁ h₂, or.resolve_right (lt_or_eq_of_le h₁) h₂ lemma lt_trichotomy [linear_order α] (a b : α) : a < b ∨ a = b ∨ b < a := or.elim (le_total a b) (λ h : a ≤ b, or.elim (lt_or_eq_of_le h) (λ h : a < b, or.inl h) (λ h : a = b, or.inr (or.inl h))) (λ h : b ≤ a, or.elim (lt_or_eq_of_le h) (λ h : b < a, or.inr (or.inr h)) (λ h : b = a, or.inr (or.inl h.symm))) lemma le_of_not_gt [linear_order α] {a b : α} (h : ¬ a > b) : a ≤ b := match lt_trichotomy a b with | or.inl hlt := le_of_lt hlt | or.inr (or.inl heq) := heq ▸ le_refl a | or.inr (or.inr hgt) := absurd hgt h end lemma lt_of_not_ge [linear_order α] {a b : α} (h : ¬ a ≥ b) : a < b := match lt_trichotomy a b with | or.inl hlt := hlt | or.inr (or.inl heq) := absurd (heq ▸ le_refl a : a ≥ b) h | or.inr (or.inr hgt) := absurd (le_of_lt hgt) h end lemma lt_or_ge [linear_order α] (a b : α) : a < b ∨ a ≥ b := match lt_trichotomy a b with | or.inl hlt := or.inl hlt | or.inr (or.inl heq) := or.inr (heq ▸ le_refl a) | or.inr (or.inr hgt) := or.inr (le_of_lt hgt) end lemma le_or_gt [linear_order α] (a b : α) : a ≤ b ∨ a > b := or.swap (lt_or_ge b a) lemma lt_or_gt_of_ne [linear_order α] {a b : α} (h : a ≠ b) : a < b ∨ a > b := match lt_trichotomy a b with | or.inl hlt := or.inl hlt | or.inr (or.inl heq) := absurd heq h | or.inr (or.inr hgt) := or.inr hgt end lemma le_of_eq_or_lt [preorder α] {a b : α} (h : a = b ∨ a < b) : a ≤ b := or.elim h le_of_eq le_of_lt lemma ne_iff_lt_or_gt [linear_order α] {a b : α} : a ≠ b ↔ a < b ∨ a > b := ⟨lt_or_gt_of_ne, λo, or.elim o ne_of_lt ne_of_gt⟩ lemma lt_iff_not_ge [linear_order α] (x y : α) : x < y ↔ ¬ x ≥ y := ⟨not_le_of_gt, lt_of_not_ge⟩ instance decidable_lt_of_decidable_le [preorder α] [decidable_rel ((≤) : α → α → Prop)] : decidable_rel ((<) : α → α → Prop) | a b := if hab : a ≤ b then if hba : b ≤ a then is_false $ λ hab', not_le_of_gt hab' hba else is_true $ lt_of_le_not_le hab hba else is_false $ λ hab', hab (le_of_lt hab') instance decidable_eq_of_decidable_le [partial_order α] [decidable_rel ((≤) : α → α → Prop)] : decidable_eq α | a b := if hab : a ≤ b then if hba : b ≤ a then is_true (le_antisymm hab hba) else is_false (λ heq, hba (heq ▸ le_refl _)) else is_false (λ heq, hab (heq ▸ le_refl _)) class decidable_linear_order (α : Type u) extends linear_order α := (decidable_le : decidable_rel (≤)) (decidable_eq : decidable_eq α := @decidable_eq_of_decidable_le _ _ decidable_le) (decidable_lt : decidable_rel ((<) : α → α → Prop) := @decidable_lt_of_decidable_le _ _ decidable_le) instance [decidable_linear_order α] (a b : α) : decidable (a < b) := decidable_linear_order.decidable_lt α a b instance [decidable_linear_order α] (a b : α) : decidable (a ≤ b) := decidable_linear_order.decidable_le α a b instance [decidable_linear_order α] (a b : α) : decidable (a = b) := decidable_linear_order.decidable_eq α a b lemma eq_or_lt_of_not_lt [decidable_linear_order α] {a b : α} (h : ¬ a < b) : a = b ∨ b < a := if h₁ : a = b then or.inl h₁ else or.inr (lt_of_not_ge (λ hge, h (lt_of_le_of_ne hge h₁))) instance [decidable_linear_order α] : is_total_preorder α (≤) := {trans := @le_trans _ _, total := le_total} /- TODO(Leo): decide whether we should keep this instance or not -/ instance is_strict_weak_order_of_decidable_linear_order [decidable_linear_order α] : is_strict_weak_order α (<) := is_strict_weak_order_of_is_total_preorder lt_iff_not_ge /- TODO(Leo): decide whether we should keep this instance or not -/ instance is_strict_total_order_of_decidable_linear_order [decidable_linear_order α] : is_strict_total_order α (<) := { trichotomous := lt_trichotomy }
3148cf9c5c69af97808a40225d510042f1c3231e
9bb72db9297f7837f673785604fb89b3184e13f8
/tests/lean/json.lean
8a5974327565568d00a4e1ed590bae8069b45ace
[ "Apache-2.0" ]
permissive
dselsam/lean
ec83d7592199faa85687d884bbaaa570b62c1652
6b0bd5bc2e07e13880d332c89093fe3032bb2469
refs/heads/master
1,621,807,064,966
1,611,454,685,000
1,611,975,642,000
42,734,348
3
3
null
1,498,748,560,000
1,442,594,289,000
C++
UTF-8
Lean
false
false
1,537
lean
#eval to_string $ json.parse $ "[0.7]" run_cmd tactic.success_if_fail $ json.parse "spurgles" meta def ball : list bool → bool := λ xs, xs.foldl band tt meta instance : decidable_eq native.float := by apply_instance meta def json.compare : Π (x y : json), bool | (json.of_string s) (json.of_string s') := s = s' | (json.of_int k) (json.of_int k') := k = k' | (json.of_float x) (json.of_float x') := x = x' | (json.of_bool b) (json.of_bool b') := b = b' | (json.null) (json.null) := tt | (json.object kvs) (json.object kvs') := (list.zip kvs kvs').foldr (λ ⟨⟨k₁, v₁⟩, ⟨k₂, v₂⟩⟩ acc, json.compare k₁ k₂ && json.compare v₁ v₂ && acc) tt | (json.array args) (json.array args') := (list.zip args args').foldr (λ ⟨j₁, j₂⟩ acc, acc && json.compare j₁ j₂) tt | _ _ := ff meta def test_parse_unparse : tactic unit := do { f ← native.float.of_string "0.4", let obj : json := json.object [ ("hello", f) , ("world", json.array [ json.null , tt , ff , json.of_int 1 , json.of_int 2 , json.of_int 3 , "this is a \"string with an annoying quote in it" ] ) ], let obj_msg := json.unparse obj, obj' ← json.parse obj_msg, guard (obj.compare obj') <|> tactic.trace format!"FAILED:\n{obj}\n{obj'}", let obj_msg' := json.unparse obj', guard (obj_msg = obj_msg') <|> tactic.trace format!"FAILED:\n{obj_msg}\n{obj_msg'}" } #eval test_parse_unparse
7fe2a43b787cecf162c68eb39da4b8b4112234bd
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/interactive/goal_info.lean
96bbbbd758c310dfb02172d624c89e9653c9d526
[ "Apache-2.0" ]
permissive
bre7k30/lean
de893411bcfa7b3c5572e61b9e1c52951b310aa4
5a924699d076dab1bd5af23a8f910b433e598d7a
refs/heads/master
1,610,900,145,817
1,488,006,845,000
1,488,006,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
925
lean
constant addc {a b : nat} : a + b = b + a constant addassoc {a b c : nat} : (a + b) + c = a + (b + c) constant zadd (a : nat) : 0 + a = a open nat example : ∀ n m : ℕ, n + m = m + n := begin intros n m, induction m with m' ih, --^ "command": "info" { change n + 0 = 0 + n, simp [zadd] }, --^ "command": "info" { change succ (n + m') = succ m' + n, rw [succ_add, ih] --^ "command":"info" } end example : ∀ n m : ℕ, n + m = m + n := begin intros n m, induction m with m' ih, { change n + 0 = 0 + n, simp [zadd] }, --^ "command": "info" { change succ (n + m') = succ m' + n, rw [succ_add, ih] } end example : ∀ n m : ℕ, n + m = m + n := begin intros n m, induction m with m' ih, { change n + 0 = 0 + n, simp [zadd] }, --^ "command": "info" { change succ (n + m') = succ m' + n, rw [succ_add, ih] } end
fe4cc74d89dcf4d39929730eb265b0be51f8b5a1
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/fully_faithful.lean
678eb927e4c37939304ffb7bb76ad00088de9d66
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
11,038
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.natural_isomorphism import Mathlib.data.equiv.basic import Mathlib.PostPort universes v₁ v₂ u₁ u₂ l v₃ u₃ namespace Mathlib namespace category_theory /-- A functor `F : C ⥤ D` is full if for each `X Y : C`, `F.map` is surjective. In fact, we use a constructive definition, so the `full F` typeclass contains data, specifying a particular preimage of each `f : F.obj X ⟶ F.obj Y`. See https://stacks.math.columbia.edu/tag/001C. -/ class full {C : Type u₁} [category C] {D : Type u₂} [category D] (F : C ⥤ D) where preimage : {X Y : C} → (functor.obj F X ⟶ functor.obj F Y) → (X ⟶ Y) witness' : autoParam (∀ {X Y : C} (f : functor.obj F X ⟶ functor.obj F Y), functor.map F (preimage f) = f) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") []) @[simp] theorem full.witness {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} [c : full F] {X : C} {Y : C} (f : functor.obj F X ⟶ functor.obj F Y) : functor.map F (full.preimage f) = f := sorry /-- A functor `F : C ⥤ D` is faithful if for each `X Y : C`, `F.map` is injective. See https://stacks.math.columbia.edu/tag/001C. -/ class faithful {C : Type u₁} [category C] {D : Type u₂} [category D] (F : C ⥤ D) where map_injective' : autoParam (∀ {X Y : C}, function.injective (functor.map F)) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") []) theorem faithful.map_injective {C : Type u₁} [category C] {D : Type u₂} [category D] (F : C ⥤ D) [c : faithful F] {X : C} {Y : C} : function.injective (functor.map F) := sorry namespace functor theorem map_injective {C : Type u₁} [category C] {D : Type u₂} [category D] (F : C ⥤ D) [faithful F] {X : C} {Y : C} : function.injective (map F) := faithful.map_injective F /-- The specified preimage of a morphism under a full functor. -/ def preimage {C : Type u₁} [category C] {D : Type u₂} [category D] (F : C ⥤ D) [full F] {X : C} {Y : C} (f : obj F X ⟶ obj F Y) : X ⟶ Y := full.preimage f @[simp] theorem image_preimage {C : Type u₁} [category C] {D : Type u₂} [category D] (F : C ⥤ D) [full F] {X : C} {Y : C} (f : obj F X ⟶ obj F Y) : map F (preimage F f) = f := sorry end functor @[simp] theorem preimage_id {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} [full F] [faithful F] {X : C} : functor.preimage F 𝟙 = 𝟙 := sorry @[simp] theorem preimage_comp {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} [full F] [faithful F] {X : C} {Y : C} {Z : C} (f : functor.obj F X ⟶ functor.obj F Y) (g : functor.obj F Y ⟶ functor.obj F Z) : functor.preimage F (f ≫ g) = functor.preimage F f ≫ functor.preimage F g := sorry @[simp] theorem preimage_map {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} [full F] [faithful F] {X : C} {Y : C} (f : X ⟶ Y) : functor.preimage F (functor.map F f) = f := sorry /-- If `F : C ⥤ D` is fully faithful, every isomorphism `F.obj X ≅ F.obj Y` has a preimage. -/ def preimage_iso {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} [full F] [faithful F] {X : C} {Y : C} (f : functor.obj F X ≅ functor.obj F Y) : X ≅ Y := iso.mk (functor.preimage F (iso.hom f)) (functor.preimage F (iso.inv f)) @[simp] theorem preimage_iso_hom {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} [full F] [faithful F] {X : C} {Y : C} (f : functor.obj F X ≅ functor.obj F Y) : iso.hom (preimage_iso f) = functor.preimage F (iso.hom f) := rfl @[simp] theorem preimage_iso_inv {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} [full F] [faithful F] {X : C} {Y : C} (f : functor.obj F X ≅ functor.obj F Y) : iso.inv (preimage_iso f) = functor.preimage F (iso.inv f) := rfl @[simp] theorem preimage_iso_map_iso {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} [full F] [faithful F] {X : C} {Y : C} (f : X ≅ Y) : preimage_iso (functor.map_iso F f) = f := sorry /-- If the image of a morphism under a fully faithful functor in an isomorphism, then the original morphisms is also an isomorphism. -/ def is_iso_of_fully_faithful {C : Type u₁} [category C] {D : Type u₂} [category D] (F : C ⥤ D) [full F] [faithful F] {X : C} {Y : C} (f : X ⟶ Y) [is_iso (functor.map F f)] : is_iso f := is_iso.mk (functor.preimage F (inv (functor.map F f))) /-- If `F` is fully faithful, we have an equivalence of hom-sets `X ⟶ Y` and `F X ⟶ F Y`. -/ def equiv_of_fully_faithful {C : Type u₁} [category C] {D : Type u₂} [category D] (F : C ⥤ D) [full F] [faithful F] {X : C} {Y : C} : (X ⟶ Y) ≃ (functor.obj F X ⟶ functor.obj F Y) := equiv.mk (fun (f : X ⟶ Y) => functor.map F f) (fun (f : functor.obj F X ⟶ functor.obj F Y) => functor.preimage F f) sorry sorry @[simp] theorem equiv_of_fully_faithful_apply {C : Type u₁} [category C] {D : Type u₂} [category D] (F : C ⥤ D) [full F] [faithful F] {X : C} {Y : C} (f : X ⟶ Y) : coe_fn (equiv_of_fully_faithful F) f = functor.map F f := rfl @[simp] theorem equiv_of_fully_faithful_symm_apply {C : Type u₁} [category C] {D : Type u₂} [category D] (F : C ⥤ D) [full F] [faithful F] {X : C} {Y : C} (f : functor.obj F X ⟶ functor.obj F Y) : coe_fn (equiv.symm (equiv_of_fully_faithful F)) f = functor.preimage F f := rfl end category_theory namespace category_theory protected instance full.id {C : Type u₁} [category C] : full 𝟭 := full.mk fun (_x _x_1 : C) (f : functor.obj 𝟭 _x ⟶ functor.obj 𝟭 _x_1) => f protected instance faithful.id {C : Type u₁} [category C] : faithful 𝟭 := faithful.mk protected instance faithful.comp {C : Type u₁} [category C] {D : Type u₂} [category D] {E : Type u₃} [category E] (F : C ⥤ D) (G : D ⥤ E) [faithful F] [faithful G] : faithful (F ⋙ G) := faithful.mk theorem faithful.of_comp {C : Type u₁} [category C] {D : Type u₂} [category D] {E : Type u₃} [category E] (F : C ⥤ D) (G : D ⥤ E) [faithful (F ⋙ G)] : faithful F := faithful.mk theorem faithful.of_iso {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {F' : C ⥤ D} [faithful F] (α : F ≅ F') : faithful F' := faithful.mk theorem faithful.of_comp_iso {C : Type u₁} [category C] {D : Type u₂} [category D] {E : Type u₃} [category E] {F : C ⥤ D} {G : D ⥤ E} {H : C ⥤ E} [ℋ : faithful H] (h : F ⋙ G ≅ H) : faithful F := faithful.of_comp F G theorem iso.faithful_of_comp {C : Type u₁} [category C] {D : Type u₂} [category D] {E : Type u₃} [category E] {F : C ⥤ D} {G : D ⥤ E} {H : C ⥤ E} [ℋ : faithful H] (h : F ⋙ G ≅ H) : faithful F := faithful.of_comp_iso -- We could prove this from `faithful.of_comp_iso` using `eq_to_iso`, -- but that would introduce a cyclic import. theorem faithful.of_comp_eq {C : Type u₁} [category C] {D : Type u₂} [category D] {E : Type u₃} [category E] {F : C ⥤ D} {G : D ⥤ E} {H : C ⥤ E} [ℋ : faithful H] (h : F ⋙ G = H) : faithful F := faithful.of_comp F G theorem Mathlib.eq.faithful_of_comp {C : Type u₁} [category C] {D : Type u₂} [category D] {E : Type u₃} [category E] {F : C ⥤ D} {G : D ⥤ E} {H : C ⥤ E} [ℋ : faithful H] (h : F ⋙ G = H) : faithful F := faithful.of_comp_eq /-- “Divide” a functor by a faithful functor. -/ protected def faithful.div {C : Type u₁} [category C] {D : Type u₂} [category D] {E : Type u₃} [category E] (F : C ⥤ E) (G : D ⥤ E) [faithful G] (obj : C → D) (h_obj : ∀ (X : C), functor.obj G (obj X) = functor.obj F X) (map : {X Y : C} → (X ⟶ Y) → (obj X ⟶ obj Y)) (h_map : ∀ {X Y : C} {f : X ⟶ Y}, functor.map G (map f) == functor.map F f) : C ⥤ D := functor.mk obj map -- This follows immediately from `functor.hext` (`functor.hext h_obj @h_map`), -- but importing `category_theory.eq_to_hom` causes an import loop: -- category_theory.eq_to_hom → category_theory.opposites → -- category_theory.equivalence → category_theory.fully_faithful theorem faithful.div_comp {C : Type u₁} [category C] {D : Type u₂} [category D] {E : Type u₃} [category E] (F : C ⥤ E) [faithful F] (G : D ⥤ E) [faithful G] (obj : C → D) (h_obj : ∀ (X : C), functor.obj G (obj X) = functor.obj F X) (map : {X Y : C} → (X ⟶ Y) → (obj X ⟶ obj Y)) (h_map : ∀ {X Y : C} {f : X ⟶ Y}, functor.map G (map f) == functor.map F f) : faithful.div F G obj h_obj map h_map ⋙ G = F := sorry theorem faithful.div_faithful {C : Type u₁} [category C] {D : Type u₂} [category D] {E : Type u₃} [category E] (F : C ⥤ E) [faithful F] (G : D ⥤ E) [faithful G] (obj : C → D) (h_obj : ∀ (X : C), functor.obj G (obj X) = functor.obj F X) (map : {X Y : C} → (X ⟶ Y) → (obj X ⟶ obj Y)) (h_map : ∀ {X Y : C} {f : X ⟶ Y}, functor.map G (map f) == functor.map F f) : faithful (faithful.div F G obj h_obj map h_map) := eq.faithful_of_comp (faithful.div_comp F G (fun (X : C) => obj X) h_obj (fun (X Y : C) (f : X ⟶ Y) => map f) h_map) protected instance full.comp {C : Type u₁} [category C] {D : Type u₂} [category D] {E : Type u₃} [category E] (F : C ⥤ D) (G : D ⥤ E) [full F] [full G] : full (F ⋙ G) := full.mk fun (_x _x_1 : C) (f : functor.obj (F ⋙ G) _x ⟶ functor.obj (F ⋙ G) _x_1) => functor.preimage F (functor.preimage G f) /-- Given a natural isomorphism between `F ⋙ H` and `G ⋙ H` for a fully faithful functor `H`, we can 'cancel' it to give a natural iso between `F` and `G`. -/ def fully_faithful_cancel_right {C : Type u₁} [category C] {D : Type u₂} [category D] {E : Type u₃} [category E] {F : C ⥤ D} {G : C ⥤ D} (H : D ⥤ E) [full H] [faithful H] (comp_iso : F ⋙ H ≅ G ⋙ H) : F ≅ G := nat_iso.of_components (fun (X : C) => preimage_iso (iso.app comp_iso X)) sorry @[simp] theorem fully_faithful_cancel_right_hom_app {C : Type u₁} [category C] {D : Type u₂} [category D] {E : Type u₃} [category E] {F : C ⥤ D} {G : C ⥤ D} {H : D ⥤ E} [full H] [faithful H] (comp_iso : F ⋙ H ≅ G ⋙ H) (X : C) : nat_trans.app (iso.hom (fully_faithful_cancel_right H comp_iso)) X = functor.preimage H (nat_trans.app (iso.hom comp_iso) X) := rfl @[simp] theorem fully_faithful_cancel_right_inv_app {C : Type u₁} [category C] {D : Type u₂} [category D] {E : Type u₃} [category E] {F : C ⥤ D} {G : C ⥤ D} {H : D ⥤ E} [full H] [faithful H] (comp_iso : F ⋙ H ≅ G ⋙ H) (X : C) : nat_trans.app (iso.inv (fully_faithful_cancel_right H comp_iso)) X = functor.preimage H (nat_trans.app (iso.inv comp_iso) X) := rfl
0cb8e846f27b3f999f4fcad94274337f476d563b
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/measure_theory/measure/ae_disjoint.lean
6b740e0197ffc5d10ba353156405b738802fee5f
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
5,560
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 measure_theory.measure.measure_space_def /-! # Almost everywhere disjoint sets > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We say that sets `s` and `t` are `μ`-a.e. disjoint (see `measure_theory.ae_disjoint`) if their intersection has measure zero. This assumption can be used instead of `disjoint` in most theorems in measure theory. -/ open set function namespace measure_theory variables {ι α : Type*} {m : measurable_space α} (μ : measure α) /-- Two sets are said to be `μ`-a.e. disjoint if their intersection has measure zero. -/ def ae_disjoint (s t : set α) := μ (s ∩ t) = 0 variables {μ} {s t u v : set α} /-- If `s : ι → set α` is a countable family of pairwise a.e. disjoint sets, then there exists a family of measurable null sets `t i` such that `s i \ t i` are pairwise disjoint. -/ lemma exists_null_pairwise_disjoint_diff [countable ι] {s : ι → set α} (hd : pairwise (ae_disjoint μ on s)) : ∃ t : ι → set α, (∀ i, measurable_set (t i)) ∧ (∀ i, μ (t i) = 0) ∧ pairwise (disjoint on (λ i, s i \ t i)) := begin refine ⟨λ i, to_measurable μ (s i ∩ ⋃ j ∈ ({i}ᶜ : set ι), s j), λ i, measurable_set_to_measurable _ _, λ i, _, _⟩, { simp only [measure_to_measurable, inter_Union], exact (measure_bUnion_null_iff $ to_countable _).2 (λ j hj, hd (ne.symm hj)) }, { simp only [pairwise, disjoint_left, on_fun, mem_diff, not_and, and_imp, not_not], intros i j hne x hi hU hj, replace hU : x ∉ s i ∩ ⋃ j ≠ i, s j := λ h, hU (subset_to_measurable _ _ h), simp only [mem_inter_iff, mem_Union, not_and, not_exists] at hU, exact (hU hi j hne.symm hj).elim } end namespace ae_disjoint protected lemma eq (h : ae_disjoint μ s t) : μ (s ∩ t) = 0 := h @[symm] protected lemma symm (h : ae_disjoint μ s t) : ae_disjoint μ t s := by rwa [ae_disjoint, inter_comm] protected lemma symmetric : symmetric (ae_disjoint μ) := λ s t h, h.symm protected lemma comm : ae_disjoint μ s t ↔ ae_disjoint μ t s := ⟨λ h, h.symm, λ h, h.symm⟩ protected lemma _root_.disjoint.ae_disjoint (h : disjoint s t) : ae_disjoint μ s t := by rw [ae_disjoint, disjoint_iff_inter_eq_empty.1 h, measure_empty] protected lemma _root_.pairwise.ae_disjoint {f : ι → set α} (hf : pairwise (disjoint on f)) : pairwise (ae_disjoint μ on f) := hf.mono $ λ i j h, h.ae_disjoint protected lemma _root_.set.pairwise_disjoint.ae_disjoint {f : ι → set α} {s : set ι} (hf : s.pairwise_disjoint f) : s.pairwise (ae_disjoint μ on f) := hf.mono' $ λ i j h, h.ae_disjoint lemma mono_ae (h : ae_disjoint μ s t) (hu : u ≤ᵐ[μ] s) (hv : v ≤ᵐ[μ] t) : ae_disjoint μ u v := measure_mono_null_ae (hu.inter hv) h protected lemma mono (h : ae_disjoint μ s t) (hu : u ⊆ s) (hv : v ⊆ t) : ae_disjoint μ u v := h.mono_ae hu.eventually_le hv.eventually_le protected lemma congr (h : ae_disjoint μ s t) (hu : u =ᵐ[μ] s) (hv : v =ᵐ[μ] t) : ae_disjoint μ u v := h.mono_ae (filter.eventually_eq.le hu) (filter.eventually_eq.le hv) @[simp] lemma Union_left_iff [countable ι] {s : ι → set α} : ae_disjoint μ (⋃ i, s i) t ↔ ∀ i, ae_disjoint μ (s i) t := by simp only [ae_disjoint, Union_inter, measure_Union_null_iff] @[simp] lemma Union_right_iff [countable ι] {t : ι → set α} : ae_disjoint μ s (⋃ i, t i) ↔ ∀ i, ae_disjoint μ s (t i) := by simp only [ae_disjoint, inter_Union, measure_Union_null_iff] @[simp] lemma union_left_iff : ae_disjoint μ (s ∪ t) u ↔ ae_disjoint μ s u ∧ ae_disjoint μ t u := by simp [union_eq_Union, and.comm] @[simp] lemma union_right_iff : ae_disjoint μ s (t ∪ u) ↔ ae_disjoint μ s t ∧ ae_disjoint μ s u := by simp [union_eq_Union, and.comm] lemma union_left (hs : ae_disjoint μ s u) (ht : ae_disjoint μ t u) : ae_disjoint μ (s ∪ t) u := union_left_iff.mpr ⟨hs, ht⟩ lemma union_right (ht : ae_disjoint μ s t) (hu : ae_disjoint μ s u) : ae_disjoint μ s (t ∪ u) := union_right_iff.2 ⟨ht, hu⟩ lemma diff_ae_eq_left (h : ae_disjoint μ s t) : (s \ t : set α) =ᵐ[μ] s := @diff_self_inter _ s t ▸ diff_null_ae_eq_self h lemma diff_ae_eq_right (h : ae_disjoint μ s t) : (t \ s : set α) =ᵐ[μ] t := h.symm.diff_ae_eq_left lemma measure_diff_left (h : ae_disjoint μ s t) : μ (s \ t) = μ s := measure_congr h.diff_ae_eq_left lemma measure_diff_right (h : ae_disjoint μ s t) : μ (t \ s) = μ t := measure_congr h.diff_ae_eq_right /-- If `s` and `t` are `μ`-a.e. disjoint, then `s \ u` and `t` are disjoint for some measurable null set `u`. -/ lemma exists_disjoint_diff (h : ae_disjoint μ s t) : ∃ u, measurable_set u ∧ μ u = 0 ∧ disjoint (s \ u) t := ⟨to_measurable μ (s ∩ t), measurable_set_to_measurable _ _, (measure_to_measurable _).trans h, disjoint_sdiff_self_left.mono_left $ λ x hx, ⟨hx.1, λ hxt, hx.2 $ subset_to_measurable _ _ ⟨hx.1, hxt⟩⟩⟩ lemma of_null_right (h : μ t = 0) : ae_disjoint μ s t := measure_mono_null (inter_subset_right _ _) h lemma of_null_left (h : μ s = 0) : ae_disjoint μ s t := (of_null_right h).symm end ae_disjoint lemma ae_disjoint_compl_left : ae_disjoint μ sᶜ s := (@disjoint_compl_left _ _ s).ae_disjoint lemma ae_disjoint_compl_right : ae_disjoint μ s sᶜ := (@disjoint_compl_right _ _ s).ae_disjoint end measure_theory
a2e7e2b21964b5cf0b774e62c7f3dd4c98beb616
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/algebra/pi_instances.lean
d516f73c1df9ca6214ce6715f4fd425b885c3d29
[ "Apache-2.0" ]
permissive
kmill/mathlib
ea5a007b67ae4e9e18dd50d31d8aa60f650425ee
1a419a9fea7b959317eddd556e1bb9639f4dcc05
refs/heads/master
1,668,578,197,719
1,593,629,163,000
1,593,629,163,000
276,482,939
0
0
null
1,593,637,960,000
1,593,637,959,000
null
UTF-8
Lean
false
false
19,229
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Patrick Massot -/ import algebra.module import ring_theory.subring import ring_theory.prod open_locale big_operators /-! # Pi instances for algebraic structures ## Implementation notes We don't use `by pi_instance` directly because currently instances generated by this tactic have slightly wrong definitions (extra `id`s and `group.mul` instead of `has_mul.mul`). These little bugs prevent Lean from applying a `simp` lemma about `pi.has_one` to `1` coming from `pi.group`. ## TODO Properly fix `tactic.pi_instance`. -/ namespace pi universes u v w variable {I : Type u} -- The indexing type variable {f : I → Type v} -- The family of types already equipped with instances variables (x y : Π i, f i) (i : I) @[to_additive] instance has_one [∀ i, has_one $ f i] : has_one (Π i : I, f i) := ⟨λ _, 1⟩ @[simp, to_additive] lemma one_apply [∀ i, has_one $ f i] : (1 : Π i, f i) i = 1 := rfl @[to_additive] instance has_mul [∀ i, has_mul $ f i] : has_mul (Π i : I, f i) := ⟨λ f g i, f i * g i⟩ @[simp, to_additive] lemma mul_apply [∀ i, has_mul $ f i] : (x * y) i = x i * y i := rfl @[to_additive] instance has_inv [∀ i, has_inv $ f i] : has_inv (Π i : I, f i) := ⟨λ f i, (f i)⁻¹⟩ @[simp, to_additive] lemma inv_apply [∀ i, has_inv $ f i] : x⁻¹ i = (x i)⁻¹ := rfl instance has_scalar {α : Type*} [Π i, has_scalar α $ f i] : has_scalar α (Π i : I, f i) := ⟨λ s x, λ i, s • (x i)⟩ @[simp] lemma smul_apply {α : Type*} [Π i, has_scalar α $ f i] (s : α) : (s • x) i = s • x i := rfl instance has_scalar' {g : I → Type*} [Π i, has_scalar (f i) (g i)] : has_scalar (Π i, f i) (Π i : I, g i) := ⟨λ s x, λ i, (s i) • (x i)⟩ @[simp] lemma smul_apply' {g : I → Type*} [∀ i, has_scalar (f i) (g i)] (s : Π i, f i) (x : Π i, g i) : (s • x) i = s i • x i := rfl @[to_additive add_semigroup] instance semigroup [∀ i, semigroup $ f i] : semigroup (Π i : I, f i) := by refine_struct { mul := (*), .. }; tactic.pi_instance_derive_field @[to_additive add_comm_semigroup] instance comm_semigroup [∀ i, comm_semigroup $ f i] : comm_semigroup (Π i : I, f i) := by refine_struct { mul := (*), .. }; tactic.pi_instance_derive_field @[to_additive add_monoid] instance monoid [∀ i, monoid $ f i] : monoid (Π i : I, f i) := by refine_struct { one := (1 : Π i, f i), mul := (*), .. }; tactic.pi_instance_derive_field @[to_additive add_comm_monoid] instance comm_monoid [∀ i, comm_monoid $ f i] : comm_monoid (Π i : I, f i) := by refine_struct { one := (1 : Π i, f i), mul := (*), .. }; tactic.pi_instance_derive_field @[to_additive add_group] instance group [∀ i, group $ f i] : group (Π i : I, f i) := by refine_struct { one := (1 : Π i, f i), mul := (*), inv := has_inv.inv, .. }; tactic.pi_instance_derive_field @[to_additive add_comm_group] instance comm_group [∀ i, comm_group $ f i] : comm_group (Π i : I, f i) := by refine_struct { one := (1 : Π i, f i), mul := (*), inv := has_inv.inv, .. }; tactic.pi_instance_derive_field instance mul_zero_class [Π i, mul_zero_class $ f i] : mul_zero_class (Π i : I, f i) := by refine_struct { zero := (0 : Π i, f i), mul := (*), .. }; tactic.pi_instance_derive_field instance distrib [Π i, distrib $ f i] : distrib (Π i : I, f i) := by refine_struct { add := (+), mul := (*), .. }; tactic.pi_instance_derive_field instance semiring [∀ i, semiring $ f i] : semiring (Π i : I, f i) := by refine_struct { zero := (0 : Π i, f i), one := 1, add := (+), mul := (*), .. }; tactic.pi_instance_derive_field instance ring [∀ i, ring $ f i] : ring (Π i : I, f i) := by refine_struct { zero := (0 : Π i, f i), one := 1, add := (+), mul := (*), neg := has_neg.neg, .. }; tactic.pi_instance_derive_field instance comm_ring [∀ i, comm_ring $ f i] : comm_ring (Π i : I, f i) := by refine_struct { zero := (0 : Π i, f i), one := 1, add := (+), mul := (*), neg := has_neg.neg, .. }; tactic.pi_instance_derive_field instance mul_action (α) {m : monoid α} [Π i, mul_action α $ f i] : @mul_action α (Π i : I, f i) m := { smul := (•), mul_smul := λ r s f, funext $ λ i, mul_smul _ _ _, one_smul := λ f, funext $ λ i, one_smul α _ } instance mul_action' {g : I → Type*} {m : Π i, monoid (f i)} [Π i, mul_action (f i) (g i)] : @mul_action (Π i, f i) (Π i : I, g i) (@pi.monoid I f m) := { smul := (•), mul_smul := λ r s f, funext $ λ i, mul_smul _ _ _, one_smul := λ f, funext $ λ i, one_smul _ _ } instance distrib_mul_action (α) {m : monoid α} {n : ∀ i, add_monoid $ f i} [∀ i, distrib_mul_action α $ f i] : @distrib_mul_action α (Π i : I, f i) m (@pi.add_monoid I f n) := { smul_zero := λ c, funext $ λ i, smul_zero _, smul_add := λ c f g, funext $ λ i, smul_add _ _ _, ..pi.mul_action _ } instance distrib_mul_action' {g : I → Type*} {m : Π i, monoid (f i)} {n : Π i, add_monoid $ g i} [Π i, distrib_mul_action (f i) (g i)] : @distrib_mul_action (Π i, f i) (Π i : I, g i) (@pi.monoid I f m) (@pi.add_monoid I g n) := { smul_add := by { intros, ext x, apply smul_add }, smul_zero := by { intros, ext x, apply smul_zero } } variables (I f) instance semimodule (α) {r : semiring α} {m : ∀ i, add_comm_monoid $ f i} [∀ i, semimodule α $ f i] : @semimodule α (Π i : I, f i) r (@pi.add_comm_monoid I f m) := { add_smul := λ c f g, funext $ λ i, add_smul _ _ _, zero_smul := λ f, funext $ λ i, zero_smul α _, ..pi.distrib_mul_action _ } variables {I f} instance semimodule' {g : I → Type*} {r : Π i, semiring (f i)} {m : Π i, add_comm_monoid (g i)} [Π i, semimodule (f i) (g i)] : semimodule (Π i, f i) (Π i, g i) := { add_smul := by { intros, ext1, apply add_smul }, zero_smul := by { intros, ext1, apply zero_smul } } @[to_additive add_left_cancel_semigroup] instance left_cancel_semigroup [∀ i, left_cancel_semigroup $ f i] : left_cancel_semigroup (Π i : I, f i) := by refine_struct { mul := (*) }; tactic.pi_instance_derive_field @[to_additive add_right_cancel_semigroup] instance right_cancel_semigroup [∀ i, right_cancel_semigroup $ f i] : right_cancel_semigroup (Π i : I, f i) := by refine_struct { mul := (*) }; tactic.pi_instance_derive_field @[to_additive ordered_cancel_add_comm_monoid] instance ordered_cancel_comm_monoid [∀ i, ordered_cancel_comm_monoid $ f i] : ordered_cancel_comm_monoid (Π i : I, f i) := by refine_struct { mul := (*), one := (1 : Π i, f i), le := (≤), lt := (<), .. pi.partial_order }; tactic.pi_instance_derive_field @[to_additive ordered_add_comm_group] instance ordered_comm_group [∀ i, ordered_comm_group $ f i] : ordered_comm_group (Π i : I, f i) := { mul_le_mul_left := λ x y hxy c i, mul_le_mul_left' (hxy i), ..pi.comm_group, ..pi.partial_order } @[simp] lemma sub_apply [∀ i, add_group $ f i] : (x - y) i = x i - y i := rfl @[to_additive] lemma list_prod_apply {α : Type*} {β : α → Type*} [∀a, monoid (β a)] (a : α) : ∀ (l : list (Πa, β a)), l.prod a = (l.map (λf:Πa, β a, f a)).prod | [] := rfl | (f :: l) := by simp [mul_apply f l.prod a, list_prod_apply l] @[to_additive] lemma multiset_prod_apply {α : Type*} {β : α → Type*} [∀a, comm_monoid (β a)] (a : α) (s : multiset (Πa, β a)) : s.prod a = (s.map (λf:Πa, β a, f a)).prod := quotient.induction_on s $ assume l, begin simp [list_prod_apply a l] end @[to_additive] lemma finset_prod_apply {α : Type*} {β : α → Type*} {γ} [∀a, comm_monoid (β a)] (a : α) (s : finset γ) (g : γ → Πa, β a) : (∏ c in s, g c) a = ∏ c in s, g c a := show (s.val.map g).prod a = (s.val.map (λc, g c a)).prod, by rw [multiset_prod_apply, multiset.map_map] /-- A family of ring homomorphisms `f a : γ →+* β a` defines a ring homomorphism `pi.ring_hom f : γ →+* Π a, β a` given by `pi.ring_hom f x b = f b x`. -/ protected def ring_hom {α : Type u} {β : α → Type v} [R : Π a : α, semiring (β a)] {γ : Type w} [semiring γ] (f : Π a : α, γ →+* β a) : γ →+* Π a, β a := { to_fun := λ x b, f b x, map_add' := λ x y, funext $ λ z, (f z).map_add x y, map_mul' := λ x y, funext $ λ z, (f z).map_mul x y, map_one' := funext $ λ z, (f z).map_one, map_zero' := funext $ λ z, (f z).map_zero } instance is_ring_hom_pi {α : Type u} {β : α → Type v} [R : Π a : α, ring (β a)] {γ : Type w} [ring γ] (f : Π a : α, γ → β a) [Rh : Π a : α, is_ring_hom (f a)] : is_ring_hom (λ x b, f b x) := (show γ →+* Π a, β a, from pi.ring_hom (λ a, ring_hom.of (f a))).is_ring_hom -- Note that we only define `single` here for dependent functions with additive fibres. section variables [decidable_eq I] variables [Π i, has_zero (f i)] /-- The function supported at `i`, with value `x` there. -/ def single (i : I) (x : f i) : Π i, f i := λ i', if h : i' = i then (by { subst h, exact x }) else 0 @[simp] lemma single_eq_same (i : I) (x : f i) : single i x i = x := begin dsimp [single], split_ifs, { refl, }, { exfalso, exact h rfl, } end @[simp] lemma single_eq_of_ne {i i' : I} (h : i' ≠ i) (x : f i) : single i x i' = 0 := begin dsimp [single], split_ifs with h', { exfalso, exact h h', }, { refl, } end end end pi section universes u v variable {I : Type u} -- The indexing type variable (f : I → Type v) -- The family of types already equipped with instances variables [Π i, monoid (f i)] /-- Evaluation of functions into an indexed collection of monoids at a point is a monoid homomorphism. -/ @[to_additive "Evaluation of functions into an indexed collection of additive monoids at a point is an additive monoid homomorphism."] def monoid_hom.apply (i : I) : (Π i, f i) →* f i := { to_fun := λ g, g i, map_one' := rfl, map_mul' := λ x y, rfl, } @[simp, to_additive] lemma monoid_hom.apply_apply (i : I) (g : Π i, f i) : (monoid_hom.apply f i) g = g i := rfl end section universes u v variable {I : Type u} -- The indexing type variable (f : I → Type v) -- The family of types already equipped with instances variables [Π i, semiring (f i)] /-- Evaluation of functions into an indexed collection of monoids at a point is a monoid homomorphism. -/ def ring_hom.apply (i : I) : (Π i, f i) →+* f i := { ..(monoid_hom.apply f i), ..(add_monoid_hom.apply f i) } @[simp] lemma ring_hom.apply_apply (i : I) (g : Π i, f i) : (ring_hom.apply f i) g = g i := rfl end section variables {I : Type*} (Z : I → Type*) variables [Π i, comm_monoid (Z i)] @[simp, to_additive] lemma finset.prod_apply {γ : Type*} {s : finset γ} (h : γ → (Π i, Z i)) (i : I) : (∏ g in s, h g) i = ∏ g in s, h g i := begin classical, induction s using finset.induction_on with b s nmem ih, { simp only [finset.prod_empty], refl }, { simp only [nmem, finset.prod_insert, not_false_iff], rw pi.mul_apply (h b) _ i, rw ih, } end end section -- As we only defined `single` into `add_monoid`, we only prove the `finset.sum` version here. variables {I : Type*} [decidable_eq I] {Z : I → Type*} variables [Π i, add_comm_monoid (Z i)] lemma finset.univ_sum_single [fintype I] (f : Π i, Z i) : ∑ i, pi.single i (f i) = f := begin ext a, rw [finset.sum_apply, finset.sum_eq_single a], { simp, }, { intros b _ h, simp [h.symm], }, { intro h, exfalso, simpa using h, }, end end section open pi variables {I : Type*} [decidable_eq I] variable (f : I → Type*) section variables [Π i, add_monoid (f i)] /-- The additive monoid homomorphism including a single additive monoid into a dependent family of additive monoids, as functions supported at a point. -/ def add_monoid_hom.single (i : I) : f i →+ Π i, f i := { to_fun := λ x, single i x, map_zero' := begin ext i', by_cases h : i' = i, { subst h, simp only [single_eq_same], refl, }, { simp only [h, single_eq_of_ne, ne.def, not_false_iff], refl, }, end, map_add' := λ x y, begin ext i', by_cases h : i' = i, -- FIXME in the next two `simp only`s, -- it would be really nice to not have to provide the arguments to `add_apply`. { subst h, simp only [single_eq_same, add_apply (single i' x) (single i' y) i'], }, { simp only [h, add_zero, single_eq_of_ne, add_apply (single i x) (single i y) i', ne.def, not_false_iff], }, end, } @[simp] lemma add_monoid_hom.single_apply {i : I} (x : f i) : (add_monoid_hom.single f i) x = single i x := rfl end section variables {f} variables [Π i, add_comm_monoid (f i)] @[ext] lemma add_monoid_hom.functions_ext [fintype I] (G : Type*) [add_comm_monoid G] (g h : (Π i, f i) →+ G) (w : ∀ (i : I) (x : f i), g (single i x) = h (single i x)) : g = h := begin ext k, rw [←finset.univ_sum_single k, add_monoid_hom.map_sum, add_monoid_hom.map_sum], apply finset.sum_congr rfl, intros, apply w, end end section variables {f} variables [Π i, semiring (f i)] -- we need `apply`+`convert` because Lean fails to unify different `add_monoid` instances -- on `Π i, f i` @[ext] lemma ring_hom.functions_ext [fintype I] (G : Type*) [semiring G] (g h : (Π i, f i) →+* G) (w : ∀ (i : I) (x : f i), g (single i x) = h (single i x)) : g = h := begin apply ring_hom.coe_add_monoid_hom_injective, convert add_monoid_hom.functions_ext _ _ _ _; assumption end end end namespace prod variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {p q : α × β} @[to_additive is_add_monoid_hom] lemma fst.is_monoid_hom [monoid α] [monoid β] : is_monoid_hom (prod.fst : α × β → α) := { map_mul := λ _ _, rfl, map_one := rfl } @[to_additive is_add_monoid_hom] lemma snd.is_monoid_hom [monoid α] [monoid β] : is_monoid_hom (prod.snd : α × β → β) := { map_mul := λ _ _, rfl, map_one := rfl } @[to_additive is_add_group_hom] lemma fst.is_group_hom [group α] [group β] : is_group_hom (prod.fst : α × β → α) := { map_mul := λ _ _, rfl } @[to_additive is_add_group_hom] lemma snd.is_group_hom [group α] [group β] : is_group_hom (prod.snd : α × β → β) := { map_mul := λ _ _, rfl } attribute [instance] fst.is_monoid_hom fst.is_add_monoid_hom snd.is_monoid_hom snd.is_add_monoid_hom fst.is_group_hom fst.is_add_group_hom snd.is_group_hom snd.is_add_group_hom @[to_additive] lemma fst_prod [comm_monoid α] [comm_monoid β] {t : finset γ} {f : γ → α × β} : (∏ c in t, f c).1 = ∏ c in t, (f c).1 := (monoid_hom.fst α β).map_prod f t @[to_additive] lemma snd_prod [comm_monoid α] [comm_monoid β] {t : finset γ} {f : γ → α × β} : (∏ c in t, f c).2 = ∏ c in t, (f c).2 := (monoid_hom.snd α β).map_prod f t instance fst.is_semiring_hom [semiring α] [semiring β] : is_semiring_hom (prod.fst : α × β → α) := (ring_hom.fst α β).is_semiring_hom instance snd.is_semiring_hom [semiring α] [semiring β] : is_semiring_hom (prod.snd : α × β → β) := (ring_hom.snd α β).is_semiring_hom instance fst.is_ring_hom [ring α] [ring β] : is_ring_hom (prod.fst : α × β → α) := (ring_hom.fst α β).is_ring_hom instance snd.is_ring_hom [ring α] [ring β] : is_ring_hom (prod.snd : α × β → β) := (ring_hom.snd α β).is_ring_hom /-- Left injection function for the inner product From a vector space (and also group and module) perspective the product is the same as the sum of two vector spaces. `inl` and `inr` provide the corresponding injection functions. -/ def inl [has_zero β] (a : α) : α × β := (a, 0) /-- Right injection function for the inner product -/ def inr [has_zero α] (b : β) : α × β := (0, b) lemma inl_injective [has_zero β] : function.injective (inl : α → α × β) := assume x y h, (prod.mk.inj_iff.mp h).1 lemma inr_injective [has_zero α] : function.injective (inr : β → α × β) := assume x y h, (prod.mk.inj_iff.mp h).2 @[simp] lemma inl_eq_inl [has_zero β] {a₁ a₂ : α} : (inl a₁ : α × β) = inl a₂ ↔ a₁ = a₂ := iff.intro (assume h, inl_injective h) (assume h, h ▸ rfl) @[simp] lemma inr_eq_inr [has_zero α] {b₁ b₂ : β} : (inr b₁ : α × β) = inr b₂ ↔ b₁ = b₂ := iff.intro (assume h, inr_injective h) (assume h, h ▸ rfl) @[simp] lemma inl_eq_inr [has_zero α] [has_zero β] {a : α} {b : β} : inl a = inr b ↔ a = 0 ∧ b = 0 := by constructor; simp [inl, inr] {contextual := tt} @[simp] lemma inr_eq_inl [has_zero α] [has_zero β] {a : α} {b : β} : inr b = inl a ↔ a = 0 ∧ b = 0 := by constructor; simp [inl, inr] {contextual := tt} @[simp] lemma fst_inl [has_zero β] (a : α) : (inl a : α × β).1 = a := rfl @[simp] lemma snd_inl [has_zero β] (a : α) : (inl a : α × β).2 = 0 := rfl @[simp] lemma fst_inr [has_zero α] (b : β) : (inr b : α × β).1 = 0 := rfl @[simp] lemma snd_inr [has_zero α] (b : β) : (inr b : α × β).2 = b := rfl instance [has_scalar α β] [has_scalar α γ] : has_scalar α (β × γ) := ⟨λa p, (a • p.1, a • p.2)⟩ @[simp] theorem smul_fst [has_scalar α β] [has_scalar α γ] (a : α) (x : β × γ) : (a • x).1 = a • x.1 := rfl @[simp] theorem smul_snd [has_scalar α β] [has_scalar α γ] (a : α) (x : β × γ) : (a • x).2 = a • x.2 := rfl @[simp] theorem smul_mk [has_scalar α β] [has_scalar α γ] (a : α) (b : β) (c : γ) : a • (b, c) = (a • b, a • c) := rfl instance {r : semiring α} [add_comm_monoid β] [add_comm_monoid γ] [semimodule α β] [semimodule α γ] : semimodule α (β × γ) := { smul_add := assume a p₁ p₂, mk.inj_iff.mpr ⟨smul_add _ _ _, smul_add _ _ _⟩, add_smul := assume a p₁ p₂, mk.inj_iff.mpr ⟨add_smul _ _ _, add_smul _ _ _⟩, mul_smul := assume a₁ a₂ p, mk.inj_iff.mpr ⟨mul_smul _ _ _, mul_smul _ _ _⟩, one_smul := assume ⟨b, c⟩, mk.inj_iff.mpr ⟨one_smul _ _, one_smul _ _⟩, zero_smul := assume ⟨b, c⟩, mk.inj_iff.mpr ⟨zero_smul _ _, zero_smul _ _⟩, smul_zero := assume a, mk.inj_iff.mpr ⟨smul_zero _, smul_zero _⟩, .. prod.has_scalar } section substructures variables (s : set α) (t : set β) @[to_additive is_add_submonoid] instance [monoid α] [monoid β] [is_submonoid s] [is_submonoid t] : is_submonoid (s.prod t) := { one_mem := by rw set.mem_prod; split; apply is_submonoid.one_mem, mul_mem := by intros; rw set.mem_prod at *; split; apply is_submonoid.mul_mem; tauto } @[to_additive prod.is_add_subgroup.prod] instance is_subgroup.prod [group α] [group β] [is_subgroup s] [is_subgroup t] : is_subgroup (s.prod t) := { inv_mem := by intros; rw set.mem_prod at *; split; apply is_subgroup.inv_mem; tauto, .. prod.is_submonoid s t } instance is_subring.prod [ring α] [ring β] [is_subring s] [is_subring t] : is_subring (s.prod t) := { .. prod.is_submonoid s t, .. prod.is_add_subgroup.prod s t } end substructures end prod namespace finset @[to_additive prod_mk_sum] lemma prod_mk_prod {α β γ : Type*} [comm_monoid α] [comm_monoid β] (s : finset γ) (f : γ → α) (g : γ → β) : (∏ x in s, f x, ∏ x in s, g x) = ∏ x in s, (f x, g x) := by haveI := classical.dec_eq γ; exact finset.induction_on s rfl (by simp [prod.ext_iff] {contextual := tt}) end finset
b5bcdcba94c4ab6b1c611748d838248a389f1a49
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/do_const_pat.lean
6fcf9604a86a8e3d6171d0b7435f84156f0dbcbc
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
59
lean
run_cmd do tt ← pure ff | tactic.skip, tactic.failed
8d29a24822195420e1fe8b4fd2044039b8d92ac2
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/group_theory/perm/cycle_type.lean
efb6b818ee83e24aef6cb7d21a4ba3e95f3409ef
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
18,882
lean
/- Copyright (c) 2020 Thomas Browning. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning -/ import combinatorics.partition import algebra.gcd_monoid.multiset import tactic.linarith import group_theory.perm.cycles import group_theory.sylow /-! # Cycle Types In this file we define the cycle type of a partition. ## Main definitions - `σ.cycle_type` where `σ` is a permutation of a `fintype` - `σ.partition` where `σ` is a permutation of a `fintype` ## Main results - `sum_cycle_type` : The sum of `σ.cycle_type` equals `σ.support.card` - `lcm_cycle_type` : The lcm of `σ.cycle_type` equals `order_of σ` - `is_conj_iff_cycle_type_eq` : Two permutations are conjugate if and only if they have the same cycle type. -/ namespace equiv.perm open equiv list multiset variables {α : Type*} [fintype α] section cycle_type variables [decidable_eq α] /-- The cycle type of a permutation -/ def cycle_type (σ : perm α) : multiset ℕ := σ.trunc_cycle_factors.lift (λ l, l.1.map (finset.card ∘ support)) (λ ⟨l₁, h₁l₁, h₂l₁, h₃l₁⟩ ⟨l₂, h₁l₂, h₂l₂, h₃l₂⟩, coe_eq_coe.mpr (perm.map _ (list_cycles_perm_list_cycles (h₁l₁.trans h₁l₂.symm) h₂l₁ h₂l₂ h₃l₁ h₃l₂))) lemma two_le_of_mem_cycle_type {σ : perm α} {n : ℕ} (h : n ∈ σ.cycle_type) : 2 ≤ n := begin rw [cycle_type, ←σ.trunc_cycle_factors.out_eq] at h, obtain ⟨τ, hτ, rfl⟩ := list.mem_map.mp h, exact (σ.trunc_cycle_factors.out.2.2.1 τ hτ).two_le_card_support, end lemma one_lt_of_mem_cycle_type {σ : perm α} {n : ℕ} (h : n ∈ σ.cycle_type) : 1 < n := two_le_of_mem_cycle_type h lemma cycle_type_eq {σ : perm α} (l : list (perm α)) (h0 : l.prod = σ) (h1 : ∀ σ : perm α, σ ∈ l → σ.is_cycle) (h2 : l.pairwise disjoint) : σ.cycle_type = l.map (finset.card ∘ support) := by rw [cycle_type, trunc.eq σ.trunc_cycle_factors (trunc.mk ⟨l, h0, h1, h2⟩), trunc.lift_mk] lemma cycle_type_one : (1 : perm α).cycle_type = 0 := cycle_type_eq [] rfl (λ _, false.elim) pairwise.nil lemma cycle_type_eq_zero {σ : perm α} : σ.cycle_type = 0 ↔ σ = 1 := begin split, { intro h, obtain ⟨l, h₁l, h₂l, h₃l⟩ := σ.trunc_cycle_factors.out, rw [cycle_type_eq l h₁l h₂l h₃l, coe_eq_zero, map_eq_nil] at h, exact h₁l.symm.trans (congr_arg _ h) }, { exact λ h, by rw [h, cycle_type_one] }, end lemma card_cycle_type_eq_zero {σ : perm α} : σ.cycle_type.card = 0 ↔ σ = 1 := by rw [card_eq_zero, cycle_type_eq_zero] lemma is_cycle.cycle_type {σ : perm α} (hσ : is_cycle σ) : σ.cycle_type = [σ.support.card] := cycle_type_eq [σ] (mul_one σ) (λ τ hτ, (congr_arg is_cycle (list.mem_singleton.mp hτ)).mpr hσ) (pairwise_singleton disjoint σ) lemma card_cycle_type_eq_one {σ : perm α} : σ.cycle_type.card = 1 ↔ σ.is_cycle := begin split, { intro hσ, obtain ⟨l, h₁l, h₂l, h₃l⟩ := σ.trunc_cycle_factors.out, rw [cycle_type_eq l h₁l h₂l h₃l, coe_card, length_map] at hσ, obtain ⟨τ, hτ⟩ := length_eq_one.mp hσ, rw [←h₁l, hτ, list.prod_singleton], apply h₂l, rw [hτ, list.mem_singleton] }, { exact λ hσ, by rw [hσ.cycle_type, coe_card, length_singleton] }, end lemma disjoint.cycle_type {σ τ : perm α} (h : disjoint σ τ) : (σ * τ).cycle_type = σ.cycle_type + τ.cycle_type := begin obtain ⟨l₁, h₁l₁, h₂l₁, h₃l₁⟩ := σ.trunc_cycle_factors.out, obtain ⟨l₂, h₁l₂, h₂l₂, h₃l₂⟩ := τ.trunc_cycle_factors.out, rw [cycle_type_eq l₁ h₁l₁ h₂l₁ h₃l₁, cycle_type_eq l₂ h₁l₂ h₂l₂ h₃l₂, cycle_type_eq (l₁ ++ l₂) _ _ _, map_append, ←coe_add], { rw [prod_append, h₁l₁, h₁l₂] }, { exact λ f hf, (mem_append.mp hf).elim (h₂l₁ f) (h₂l₂ f) }, { refine pairwise_append.mpr ⟨h₃l₁, h₃l₂, λ f hf g hg a, by_contra (λ H, _)⟩, rw not_or_distrib at H, rw [←ne.def, ←ne.def, ←mem_support, ←mem_support] at H, replace H : a ∈ l₁.prod.support ∧ a ∈ l₂.prod.support, { refine H.imp (λ H, _) (λ H, _); exact support_le_prod_of_mem ‹_› ‹_› H }, rw [h₁l₁, h₁l₂] at H, exact h.disjoint_support (finset.mem_inter_of_mem H.left H.right) } end lemma cycle_type_inv (σ : perm α) : σ⁻¹.cycle_type = σ.cycle_type := cycle_induction_on (λ τ : perm α, τ⁻¹.cycle_type = τ.cycle_type) σ rfl (λ σ hσ, by rw [hσ.cycle_type, hσ.inv.cycle_type, support_inv]) (λ σ τ hστ hc hσ hτ, by rw [mul_inv_rev, hστ.cycle_type, ←hσ, ←hτ, add_comm, disjoint.cycle_type (λ x, or.imp (λ h : τ x = x, inv_eq_iff_eq.mpr h.symm) (λ h : σ x = x, inv_eq_iff_eq.mpr h.symm) (hστ x).symm)]) lemma cycle_type_conj {σ τ : perm α} : (τ * σ * τ⁻¹).cycle_type = σ.cycle_type := begin revert τ, apply cycle_induction_on _ σ, { intro, simp }, { intros σ hσ τ, rw [hσ.cycle_type, hσ.is_cycle_conj.cycle_type, card_support_conj] }, { intros σ τ hd hc hσ hτ π, rw [← conj_mul, hd.cycle_type, disjoint.cycle_type, hσ, hτ], intro a, apply (hd (π⁻¹ a)).imp _ _; { intro h, rw [perm.mul_apply, perm.mul_apply, h, apply_inv_self] } } end lemma sum_cycle_type (σ : perm α) : σ.cycle_type.sum = σ.support.card := cycle_induction_on (λ τ : perm α, τ.cycle_type.sum = τ.support.card) σ (by rw [cycle_type_one, sum_zero, support_one, finset.card_empty]) (λ σ hσ, by rw [hσ.cycle_type, coe_sum, list.sum_singleton]) (λ σ τ hστ hc hσ hτ, by rw [hστ.cycle_type, sum_add, hσ, hτ, hστ.card_support_mul]) lemma sign_of_cycle_type (σ : perm α) : sign σ = (σ.cycle_type.map (λ n, -(-1 : units ℤ) ^ n)).prod := cycle_induction_on (λ τ : perm α, sign τ = (τ.cycle_type.map (λ n, -(-1 : units ℤ) ^ n)).prod) σ (by rw [sign_one, cycle_type_one, map_zero, prod_zero]) (λ σ hσ, by rw [hσ.sign, hσ.cycle_type, coe_map, coe_prod, list.map_singleton, list.prod_singleton]) (λ σ τ hστ hc hσ hτ, by rw [sign_mul, hσ, hτ, hστ.cycle_type, map_add, prod_add]) lemma lcm_cycle_type (σ : perm α) : σ.cycle_type.lcm = order_of σ := cycle_induction_on (λ τ : perm α, τ.cycle_type.lcm = order_of τ) σ (by rw [cycle_type_one, lcm_zero, order_of_one]) (λ σ hσ, by rw [hσ.cycle_type, ←singleton_coe, lcm_singleton, order_of_is_cycle hσ, nat.normalize_eq]) (λ σ τ hστ hc hσ hτ, by rw [hστ.cycle_type, lcm_add, nat.lcm_eq_lcm, hστ.order_of, hσ, hτ]) lemma dvd_of_mem_cycle_type {σ : perm α} {n : ℕ} (h : n ∈ σ.cycle_type) : n ∣ order_of σ := begin rw ← lcm_cycle_type, exact dvd_lcm h, end lemma two_dvd_card_support {σ : perm α} (hσ : σ ^ 2 = 1) : 2 ∣ σ.support.card := (congr_arg (has_dvd.dvd 2) σ.sum_cycle_type).mp (multiset.dvd_sum (λ n hn, by rw le_antisymm (nat.le_of_dvd zero_lt_two (dvd_trans (dvd_of_mem_cycle_type hn) (order_of_dvd_of_pow_eq_one hσ))) (two_le_of_mem_cycle_type hn))) lemma cycle_type_prime_order {σ : perm α} (hσ : (order_of σ).prime) : ∃ n : ℕ, σ.cycle_type = repeat (order_of σ) (n + 1) := begin rw eq_repeat_of_mem (λ n hn, or_iff_not_imp_left.mp (hσ.2 n (dvd_of_mem_cycle_type hn)) (ne_of_gt (one_lt_of_mem_cycle_type hn))), use σ.cycle_type.card - 1, rw nat.sub_add_cancel, rw [nat.succ_le_iff, pos_iff_ne_zero, ne, card_cycle_type_eq_zero], rintro rfl, rw order_of_one at hσ, exact hσ.ne_one rfl, end lemma is_cycle_of_prime_order {σ : perm α} (h1 : (order_of σ).prime) (h2 : σ.support.card < 2 * (order_of σ)) : σ.is_cycle := begin obtain ⟨n, hn⟩ := cycle_type_prime_order h1, rw [←σ.sum_cycle_type, hn, multiset.sum_repeat, nsmul_eq_mul, nat.cast_id, mul_lt_mul_right (order_of_pos σ), nat.succ_lt_succ_iff, nat.lt_succ_iff, nat.le_zero_iff] at h2, rw [←card_cycle_type_eq_one, hn, card_repeat, h2], end theorem is_conj_of_cycle_type_eq {σ τ : perm α} (h : cycle_type σ = cycle_type τ) : is_conj σ τ := begin revert τ, apply cycle_induction_on _ σ, { intros τ h, rw [cycle_type_one, eq_comm, cycle_type_eq_zero] at h, rw h }, { intros σ hσ τ hστ, have hτ := card_cycle_type_eq_one.2 hσ, rw [hστ, card_cycle_type_eq_one] at hτ, apply hσ.is_conj hτ, rw [hσ.cycle_type, hτ.cycle_type, coe_eq_coe, singleton_perm] at hστ, simp only [and_true, eq_self_iff_true] at hστ, exact hστ }, { intros σ τ hστ hσ h1 h2 π hπ, obtain ⟨l, rfl, hl1, hl2⟩ := trunc_cycle_factors π, rw [hστ.cycle_type, hσ.cycle_type, cycle_type_eq _ rfl hl1 hl2] at hπ, have h : σ.support.card ∈ map (finset.card ∘ perm.support) l, { rw [← multiset.mem_coe, ← hπ], simp }, obtain ⟨σ', hσ'l, hσ'⟩ := list.mem_map.1 h, rw [disjoint_prod_perm hl2 (list.perm_cons_erase hσ'l), list.prod_cons], refine hστ.is_conj_mul (h1 _) (h2 _) _, { simp only [hσ.cycle_type, (hl1 _ hσ'l).cycle_type, ←hσ'] }, { rw [← coe_map, coe_eq_coe.2 (list.perm_cons_erase hσ'l), singleton_add, ← cons_coe, multiset.map_cons, hσ', cons_inj_right, coe_map] at hπ, rw [hπ, cycle_type_eq (l.erase σ') rfl (λ f hf, hl1 f (list.erase_subset _ _ hf)) (list.pairwise_of_sublist (list.erase_sublist _ _) hl2)] }, { refine disjoint_prod_right _ (λ g hg, list.rel_of_pairwise_cons _ hg), refine (list.perm.pairwise_iff _ (list.perm_cons_erase hσ'l).symm).2 hl2, exact disjoint.symmetric } } end theorem is_conj_iff_cycle_type_eq {σ τ : perm α} : is_conj σ τ ↔ σ.cycle_type = τ.cycle_type := ⟨λ h, begin obtain ⟨π, rfl⟩ := is_conj_iff.1 h, rw cycle_type_conj, end, is_conj_of_cycle_type_eq⟩ @[simp] lemma cycle_type_extend_domain {β : Type*} [fintype β] [decidable_eq β] {p : β → Prop} [decidable_pred p] (f : α ≃ subtype p) {g : perm α} : cycle_type (g.extend_domain f) = cycle_type g := begin apply cycle_induction_on _ g, { rw [extend_domain_one, cycle_type_one, cycle_type_one] }, { intros σ hσ, rw [(hσ.extend_domain f).cycle_type, hσ.cycle_type, card_support_extend_domain] }, { intros σ τ hd hc hσ hτ, rw [hd.cycle_type, ← extend_domain_mul, (hd.extend_domain f).cycle_type, hσ, hτ] } end lemma mem_cycle_type_iff {n : ℕ} {σ : perm α} : n ∈ cycle_type σ ↔ ∃ c τ : perm α, σ = c * τ ∧ disjoint c τ ∧ is_cycle c ∧ c.support.card = n := begin split, { intro h, obtain ⟨l, rfl, hlc, hld⟩ := trunc_cycle_factors σ, rw cycle_type_eq _ rfl hlc hld at h, obtain ⟨c, cl, rfl⟩ := list.exists_of_mem_map h, rw (list.perm_cons_erase cl).pairwise_iff (λ _ _ hd, _) at hld, swap, { exact hd.symm }, refine ⟨c, (l.erase c).prod, _, _, hlc _ cl, rfl⟩, { rw [← list.prod_cons, (list.perm_cons_erase cl).symm.prod_eq' (hld.imp (λ _ _, disjoint.commute))] }, { exact disjoint_prod_right _ (λ g, list.rel_of_pairwise_cons hld) } }, { rintros ⟨c, t, rfl, hd, hc, rfl⟩, simp [hd.cycle_type, hc.cycle_type] } end lemma le_card_support_of_mem_cycle_type {n : ℕ} {σ : perm α} (h : n ∈ cycle_type σ) : n ≤ σ.support.card := (le_sum_of_mem h).trans (le_of_eq σ.sum_cycle_type) lemma cycle_type_of_card_le_mem_cycle_type_add_two {n : ℕ} {g : perm α} (hn2 : fintype.card α < n + 2) (hng : n ∈ g.cycle_type) : g.cycle_type = {n} := begin obtain ⟨c, g', rfl, hd, hc, rfl⟩ := mem_cycle_type_iff.1 hng, by_cases g'1 : g' = 1, { rw [hd.cycle_type, hc.cycle_type, multiset.singleton_eq_singleton, multiset.singleton_coe, g'1, cycle_type_one, add_zero] }, contrapose! hn2, apply le_trans _ (c * g').support.card_le_univ, rw [hd.card_support_mul], exact add_le_add_left (two_le_card_support_of_ne_one g'1) _, end end cycle_type lemma is_cycle_of_prime_order' {σ : perm α} (h1 : (order_of σ).prime) (h2 : fintype.card α < 2 * (order_of σ)) : σ.is_cycle := begin classical, exact is_cycle_of_prime_order h1 (lt_of_le_of_lt σ.support.card_le_univ h2), end lemma is_cycle_of_prime_order'' {σ : perm α} (h1 : (fintype.card α).prime) (h2 : order_of σ = fintype.card α) : σ.is_cycle := is_cycle_of_prime_order' ((congr_arg nat.prime h2).mpr h1) begin classical, rw [←one_mul (fintype.card α), ←h2, mul_lt_mul_right (order_of_pos σ)], exact one_lt_two, end lemma subgroup_eq_top_of_swap_mem [decidable_eq α] {H : subgroup (perm α)} [d : decidable_pred (∈ H)] {τ : perm α} (h0 : (fintype.card α).prime) (h1 : fintype.card α ∣ fintype.card H) (h2 : τ ∈ H) (h3 : is_swap τ) : H = ⊤ := begin haveI : fact (fintype.card α).prime := ⟨h0⟩, obtain ⟨σ, hσ⟩ := sylow.exists_prime_order_of_dvd_card (fintype.card α) h1, have hσ1 : order_of (σ : perm α) = fintype.card α := (order_of_subgroup σ).trans hσ, have hσ2 : is_cycle ↑σ := is_cycle_of_prime_order'' h0 hσ1, have hσ3 : (σ : perm α).support = ⊤ := finset.eq_univ_of_card (σ : perm α).support ((order_of_is_cycle hσ2).symm.trans hσ1), have hσ4 : subgroup.closure {↑σ, τ} = ⊤ := closure_prime_cycle_swap h0 hσ2 hσ3 h3, rw [eq_top_iff, ←hσ4, subgroup.closure_le, set.insert_subset, set.singleton_subset_iff], exact ⟨subtype.mem σ, h2⟩, end section partition variables [decidable_eq α] /-- The partition corresponding to a permutation -/ def partition (σ : perm α) : partition (fintype.card α) := { parts := σ.cycle_type + repeat 1 (fintype.card α - σ.support.card), parts_pos := λ n hn, begin cases mem_add.mp hn with hn hn, { exact zero_lt_one.trans (one_lt_of_mem_cycle_type hn) }, { exact lt_of_lt_of_le zero_lt_one (ge_of_eq (multiset.eq_of_mem_repeat hn)) }, end, parts_sum := by rw [sum_add, sum_cycle_type, multiset.sum_repeat, nsmul_eq_mul, nat.cast_id, mul_one, nat.add_sub_cancel' σ.support.card_le_univ] } lemma parts_partition {σ : perm α} : σ.partition.parts = σ.cycle_type + repeat 1 (fintype.card α - σ.support.card) := rfl lemma filter_parts_partition_eq_cycle_type {σ : perm α} : (partition σ).parts.filter (λ n, 2 ≤ n) = σ.cycle_type := begin rw [parts_partition, filter_add, multiset.filter_eq_self.2 (λ _, two_le_of_mem_cycle_type), multiset.filter_eq_nil.2 (λ a h, _), add_zero], rw multiset.eq_of_mem_repeat h, dec_trivial end lemma partition_eq_of_is_conj {σ τ : perm α} : is_conj σ τ ↔ σ.partition = τ.partition := begin rw [is_conj_iff_cycle_type_eq], refine ⟨λ h, _, λ h, _⟩, { rw [partition.ext_iff, parts_partition, parts_partition, ← sum_cycle_type, ← sum_cycle_type, h] }, { rw [← filter_parts_partition_eq_cycle_type, ← filter_parts_partition_eq_cycle_type, h] } end end partition /-! ### 3-cycles -/ /-- A three-cycle is a cycle of length 3. -/ def is_three_cycle [decidable_eq α] (σ : perm α) : Prop := σ.cycle_type = {3} namespace is_three_cycle variables [decidable_eq α] {σ : perm α} lemma cycle_type (h : is_three_cycle σ) : σ.cycle_type = {3} := h lemma card_support (h : is_three_cycle σ) : σ.support.card = 3 := by rw [←sum_cycle_type, h.cycle_type, singleton_eq_singleton, multiset.sum_cons, sum_zero] lemma _root_.card_support_eq_three_iff : σ.support.card = 3 ↔ σ.is_three_cycle := begin refine ⟨λ h, _, is_three_cycle.card_support⟩, by_cases h0 : σ.cycle_type = 0, { rw [←sum_cycle_type, h0, sum_zero] at h, exact (ne_of_lt zero_lt_three h).elim }, obtain ⟨n, hn⟩ := exists_mem_of_ne_zero h0, by_cases h1 : σ.cycle_type.erase n = 0, { rw [←sum_cycle_type, ←cons_erase hn, h1, multiset.sum_singleton] at h, rw [is_three_cycle, ←cons_erase hn, h1, h, singleton_eq_singleton] }, obtain ⟨m, hm⟩ := exists_mem_of_ne_zero h1, rw [←sum_cycle_type, ←cons_erase hn, ←cons_erase hm, multiset.sum_cons, multiset.sum_cons] at h, linarith [two_le_of_mem_cycle_type hn, two_le_of_mem_cycle_type (mem_of_mem_erase hm)], end lemma is_cycle (h : is_three_cycle σ) : is_cycle σ := by rw [←card_cycle_type_eq_one, h.cycle_type, singleton_eq_singleton, card_singleton] lemma sign (h : is_three_cycle σ) : sign σ = 1 := begin rw [sign_of_cycle_type, h.cycle_type], refl, end lemma inv {f : perm α} (h : is_three_cycle f) : is_three_cycle (f⁻¹) := by rwa [is_three_cycle, cycle_type_inv] @[simp] lemma inv_iff {f : perm α} : is_three_cycle (f⁻¹) ↔ is_three_cycle f := ⟨by { rw ← inv_inv f, apply inv }, inv⟩ lemma order_of {g : perm α} (ht : is_three_cycle g) : order_of g = 3 := by rw [←lcm_cycle_type, ht.cycle_type, multiset.singleton_eq_singleton, multiset.lcm_singleton, nat.normalize_eq] lemma is_three_cycle_sq {g : perm α} (ht : is_three_cycle g) : is_three_cycle (g * g) := begin rw [←pow_two, ←card_support_eq_three_iff, support_pow_coprime, ht.card_support], rw [ht.order_of, nat.coprime_iff_gcd_eq_one], norm_num, end end is_three_cycle section variable [decidable_eq α] lemma is_three_cycle_swap_mul_swap_same {a b c : α} (ab : a ≠ b) (ac : a ≠ c) (bc : b ≠ c) : is_three_cycle (swap a b * swap a c) := begin suffices h : support (swap a b * swap a c) = {a, b, c}, { rw [←card_support_eq_three_iff, h], simp [ab, ac, bc] }, apply le_antisymm ((support_mul_le _ _).trans (λ x, _)) (λ x hx, _), { simp [ab, ac, bc] }, { simp only [finset.mem_insert, finset.mem_singleton] at hx, rw mem_support, simp only [perm.coe_mul, function.comp_app, ne.def], obtain rfl | rfl | rfl := hx, { rw [swap_apply_left, swap_apply_of_ne_of_ne ac.symm bc.symm], exact ac.symm }, { rw [swap_apply_of_ne_of_ne ab.symm bc, swap_apply_right], exact ab }, { rw [swap_apply_right, swap_apply_left], exact bc } } end open subgroup lemma swap_mul_swap_same_mem_closure_three_cycles {a b c : α} (ab : a ≠ b) (ac : a ≠ c) : (swap a b * swap a c) ∈ closure {σ : perm α | is_three_cycle σ } := begin by_cases bc : b = c, { subst bc, simp [one_mem] }, exact subset_closure (is_three_cycle_swap_mul_swap_same ab ac bc) end lemma is_swap.mul_mem_closure_three_cycles {σ τ : perm α} (hσ : is_swap σ) (hτ : is_swap τ) : σ * τ ∈ closure {σ : perm α | is_three_cycle σ } := begin obtain ⟨a, b, ab, rfl⟩ := hσ, obtain ⟨c, d, cd, rfl⟩ := hτ, by_cases ac : a = c, { subst ac, exact swap_mul_swap_same_mem_closure_three_cycles ab cd }, have h' : swap a b * swap c d = swap a b * swap a c * (swap c a * swap c d), { simp [swap_comm c a, mul_assoc] }, rw h', exact mul_mem _ (swap_mul_swap_same_mem_closure_three_cycles ab ac) (swap_mul_swap_same_mem_closure_three_cycles (ne.symm ac) cd), end end end equiv.perm
2a5a572dff6b33058b1db4768e6153709a706e66
63abd62053d479eae5abf4951554e1064a4c45b4
/src/category_theory/simple.lean
02ffe82a9f44edbbdd9f18ce464a3086101b2471
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
3,994
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel, Scott Morrison -/ import category_theory.limits.shapes.zero import category_theory.limits.shapes.kernels import category_theory.abelian.basic noncomputable theory open category_theory.limits namespace category_theory universes v u variables {C : Type u} [category.{v} C] section variables [has_zero_morphisms C] /-- An object is simple if monomorphisms into it are (exclusively) either isomorphisms or zero. -/ -- This is a constructive definition, from which we can extract an inverse for `f` given `f ≠ 0`. -- We show below that although it contains data, it is a subsingleton. class simple (X : C) : Type (max u v) := (mono_is_iso_equiv_nonzero : ∀ {Y : C} (f : Y ⟶ X) [mono f], is_iso f ≃ (f ≠ 0)) @[ext] lemma simple.ext {X : C} {a b : simple X} : a = b := begin casesI a, casesI b, congr, funext Y f m, ext, refl, end instance subsingleton_simple (X : C) : subsingleton (simple X) := subsingleton.intro (@simple.ext _ _ _ X) /-- A nonzero monomorphism to a simple object is an isomorphism. -/ def is_iso_of_mono_of_nonzero {X Y : C} [simple Y] {f : X ⟶ Y} [mono f] (w : f ≠ 0) : is_iso f := (simple.mono_is_iso_equiv_nonzero f).symm w lemma kernel_zero_of_nonzero_from_simple {X Y : C} [simple X] {f : X ⟶ Y} [has_kernel f] (w : f ≠ 0) : kernel.ι f = 0 := begin classical, by_contradiction h, haveI := is_iso_of_mono_of_nonzero h, exact w (eq_zero_of_epi_kernel f), end lemma mono_to_simple_zero_of_not_iso {X Y : C} [simple Y] {f : X ⟶ Y} [mono f] (w : is_iso f → false) : f = 0 := begin classical, by_contradiction h, apply w, exact is_iso_of_mono_of_nonzero h, end lemma id_nonzero (X : C) [simple.{v} X] : 𝟙 X ≠ 0 := (simple.mono_is_iso_equiv_nonzero (𝟙 X)) (by apply_instance) section variable [has_zero_object C] local attribute [instance] has_zero_object.has_zero /-- We don't want the definition of 'simple' to include the zero object, so we check that here. -/ lemma zero_not_simple [simple (0 : C)] : false := (simple.mono_is_iso_equiv_nonzero (0 : (0 : C) ⟶ (0 : C))) { inv := 0, } rfl end end -- We next make the dual arguments, but for this we must be in an abelian category. section abelian variables [abelian C] /-- In an abelian category, an object satisfying the dual of the definition of a simple object is simple. -/ def simple_of_cosimple (X : C) (h : ∀ {Z : C} (f : X ⟶ Z) [epi f], is_iso f ≃ (f ≠ 0)) : simple X := ⟨λ Y f I, begin classical, apply equiv_of_subsingleton_of_subsingleton, { introsI, have hx := cokernel.π_of_epi f, by_contradiction h, push_neg at h, substI h, exact h _ (cokernel.π_of_zero _ _) hx }, { intro hf, suffices : epi f, { resetI, apply abelian.is_iso_of_mono_of_epi }, apply preadditive.epi_of_cokernel_zero, by_contradiction h', exact cokernel_not_iso_of_nonzero hf ((h _).symm h') } end⟩ /-- A nonzero epimorphism from a simple object is an isomorphism. -/ def is_iso_of_epi_of_nonzero {X Y : C} [simple X] {f : X ⟶ Y} [epi f] (w : f ≠ 0) : is_iso f := begin -- `f ≠ 0` means that `kernel.ι f` is not an iso, and hence zero, and hence `f` is a mono. haveI : mono f := preadditive.mono_of_kernel_zero (mono_to_simple_zero_of_not_iso (kernel_not_iso_of_nonzero w)), exact abelian.is_iso_of_mono_of_epi f, end lemma cokernel_zero_of_nonzero_to_simple {X Y : C} [simple Y] {f : X ⟶ Y} [has_cokernel f] (w : f ≠ 0) : cokernel.π f = 0 := begin classical, by_contradiction h, haveI := is_iso_of_epi_of_nonzero h, exact w (eq_zero_of_mono_cokernel f), end lemma epi_from_simple_zero_of_not_iso {X Y : C} [simple X] {f : X ⟶ Y} [epi f] (w : is_iso f → false) : f = 0 := begin classical, by_contradiction h, apply w, exact is_iso_of_epi_of_nonzero h, end end abelian end category_theory
b8db17bfe6b726f676483fab389e9b5832ed9d12
8b9f17008684d796c8022dab552e42f0cb6fb347
/tests/lean/run/tactic17.lean
b8f0ebe99bf93112c3444ba23cf8e418c417c196
[ "Apache-2.0" ]
permissive
chubbymaggie/lean
0d06ae25f9dd396306fb02190e89422ea94afd7b
d2c7b5c31928c98f545b16420d37842c43b4ae9a
refs/heads/master
1,611,313,622,901
1,430,266,839,000
1,430,267,083,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
243
lean
import logic open tactic constant A : Type.{1} constant f : A → A → A theorem tst {a b c : A} (H1 : a = b) (H2 : b = c) : f a b = f b c := begin apply (@congr A A _ _ (f a) (f b)), assumption, apply (congr_arg f), assumption end
e8c98596475c56fe3e9460a391e5e5a8f80585b8
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/ring_theory/derivation.lean
81ea1dd99b7ea92d22d50460f39f566f7be044f4
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
9,838
lean
/- Copyright © 2020 Nicolò Cavalleri. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nicolò Cavalleri -/ import algebra.lie.of_associative import ring_theory.algebra_tower /-! # Derivations This file defines derivation. A derivation `D` from the `R`-algebra `A` to the `A`-module `M` is an `R`-linear map that satisfy the Leibniz rule `D (a * b) = a * D b + D a * b`. ## Notation The notation `⁅D1, D2⁆` is used for the commutator of two derivations. TODO: this file is just a stub to go on with some PRs in the geometry section. It only implements the definition of derivations in commutative algebra. This will soon change: as soon as bimodules will be there in mathlib I will change this file to take into account the non-commutative case. Any development on the theory of derivations is discouraged until the definitive definition of derivation will be implemented. -/ open algebra ring_hom /-- `D : derivation R A M` is an `R`-linear map from `A` to `M` that satisfies the `leibniz` equality. TODO: update this when bimodules are defined. -/ @[protect_proj] structure derivation (R : Type*) (A : Type*) [comm_semiring R] [comm_semiring A] [algebra R A] (M : Type*) [add_cancel_comm_monoid M] [module A M] [module R M] [is_scalar_tower R A M] extends A →ₗ[R] M := (leibniz' (a b : A) : to_fun (a * b) = a • to_fun b + b • to_fun a) namespace derivation section variables {R : Type*} [comm_semiring R] variables {A : Type*} [comm_semiring A] [algebra R A] variables {M : Type*} [add_cancel_comm_monoid M] [module A M] [module R M] variables [is_scalar_tower R A M] variables (D : derivation R A M) {D1 D2 : derivation R A M} (r : R) (a b : A) instance : has_coe_to_fun (derivation R A M) := ⟨_, λ D, D.to_linear_map.to_fun⟩ instance has_coe_to_linear_map : has_coe (derivation R A M) (A →ₗ[R] M) := ⟨λ D, D.to_linear_map⟩ @[simp] lemma mk_coe (f : A →ₗ[R] M) (h) : ((⟨f, h⟩ : derivation R A M) : A → M) = f := rfl @[simp] lemma to_fun_eq_coe : D.to_fun = ⇑D := rfl @[simp, norm_cast] lemma coe_fn_coe (f : derivation R A M) : ⇑(f : A →ₗ[R] M) = f := rfl lemma coe_injective (H : ⇑D1 = D2) : D1 = D2 := by { cases D1, cases D2, congr', exact linear_map.coe_injective H } @[ext] theorem ext (H : ∀ a, D1 a = D2 a) : D1 = D2 := coe_injective $ funext H @[simp] lemma map_add : D (a + b) = D a + D b := is_add_hom.map_add D a b @[simp] lemma map_zero : D 0 = 0 := is_add_monoid_hom.map_zero D @[simp] lemma map_smul : D (r • a) = r • D a := linear_map.map_smul D r a @[simp] lemma leibniz : D (a * b) = a • D b + b • D a := D.leibniz' _ _ @[simp] lemma map_one_eq_zero : D 1 = 0 := begin have h : D 1 = D (1 * 1) := by rw mul_one, rwa [leibniz D 1 1, one_smul, self_eq_add_right] at h end @[simp] lemma map_algebra_map : D (algebra_map R A r) = 0 := by rw [←mul_one r, ring_hom.map_mul, map_one, ←smul_def, map_smul, map_one_eq_zero, smul_zero] instance : has_zero (derivation R A M) := ⟨⟨(0 : A →ₗ[R] M), λ a b, by simp only [add_zero, linear_map.zero_apply, linear_map.to_fun_eq_coe, smul_zero]⟩⟩ instance : inhabited (derivation R A M) := ⟨0⟩ instance : add_comm_monoid (derivation R A M) := { add := λ D1 D2, ⟨D1 + D2, λ a b, by { simp only [leibniz, linear_map.add_apply, linear_map.to_fun_eq_coe, coe_fn_coe, smul_add], cc }⟩, add_assoc := λ D E F, ext $ λ a, add_assoc _ _ _, zero_add := λ D, ext $ λ a, zero_add _, add_zero := λ D, ext $ λ a, add_zero _, add_comm := λ D E, ext $ λ a, add_comm _ _, ..derivation.has_zero } @[simp] lemma add_apply : (D1 + D2) a = D1 a + D2 a := rfl @[priority 100] instance derivation.Rmodule : module R (derivation R A M) := { smul := λ r D, ⟨r • D, λ a b, by simp only [linear_map.smul_apply, leibniz, linear_map.to_fun_eq_coe, smul_algebra_smul_comm, coe_fn_coe, smul_add, add_comm],⟩, mul_smul := λ a1 a2 D, ext $ λ b, mul_smul _ _ _, one_smul := λ D, ext $ λ b, one_smul _ _, smul_add := λ a D1 D2, ext $ λ b, smul_add _ _ _, smul_zero := λ a, ext $ λ b, smul_zero _, add_smul := λ a1 a2 D, ext $ λ b, add_smul _ _ _, zero_smul := λ D, ext $ λ b, zero_smul _ _ } @[simp] lemma smul_to_linear_map_coe : ↑(r • D) = (r • D : A →ₗ[R] M) := rfl @[simp] lemma Rsmul_apply : (r • D) a = r • D a := rfl instance : module A (derivation R A M) := { smul := λ a D, ⟨a • D, λ b c, by { dsimp, simp only [smul_add, leibniz, smul_comm a, add_comm] }⟩, mul_smul := λ a1 a2 D, ext $ λ b, mul_smul _ _ _, one_smul := λ D, ext $ λ b, one_smul A _, smul_add := λ a D1 D2, ext $ λ b, smul_add _ _ _, smul_zero := λ a, ext $ λ b, smul_zero _, add_smul := λ a1 a2 D, ext $ λ b, add_smul _ _ _, zero_smul := λ D, ext $ λ b, zero_smul A _ } @[simp] lemma smul_apply : (a • D) b = a • D b := rfl instance : is_scalar_tower R A (derivation R A M) := ⟨λ x y z, ext (λ a, smul_assoc _ _ _)⟩ section push_forward variables {N : Type*} [add_cancel_comm_monoid N] [module A N] [module R N] [is_scalar_tower R A N] variables (f : M →ₗ[A] N) /-- We can push forward derivations using linear maps, i.e., the composition of a derivation with a linear map is a derivation. Furthermore, this operation is linear on the spaces of derivations. -/ def comp : derivation R A M →ₗ[R] derivation R A N := { to_fun := λ D, { leibniz' := λ a b, begin simp only [coe_fn_coe, function.comp_app, linear_map.coe_comp, linear_map.map_add, leibniz, linear_map.coe_coe_is_scalar_tower, linear_map.map_smul, linear_map.to_fun_eq_coe], end, .. (f : M →ₗ[R] N).comp (D : A →ₗ[R] M), }, map_add' := λ D₁ D₂, begin ext, simp only [mk_coe, add_apply, coe_fn_coe, linear_map.coe_mk, function.comp_app, linear_map.coe_comp, linear_map.to_fun_eq_coe, linear_map.map_add], end, map_smul' := λ r D, begin ext, simp only [coe_fn_coe, Rsmul_apply, linear_map.map_smul_of_tower, mk_coe, linear_map.coe_mk, function.comp_app, linear_map.coe_comp, linear_map.to_fun_eq_coe], end, } @[simp] lemma coe_to_linear_map_comp : (comp f D : A →ₗ[R] N) = (f : M →ₗ[R] N).comp (D : A →ₗ[R] M) := rfl @[simp] lemma coe_comp : (comp f D : A → N) = (f : M →ₗ[R] N).comp (D : A →ₗ[R] M) := rfl end push_forward end section variables {R : Type*} [comm_ring R] variables {A : Type*} [comm_ring A] [algebra R A] section variables {M : Type*} [add_comm_group M] [module A M] [module R M] [is_scalar_tower R A M] variables (D : derivation R A M) {D1 D2 : derivation R A M} (r : R) (a b : A) @[simp] lemma map_neg : D (-a) = -D a := linear_map.map_neg D a @[simp] lemma map_sub : D (a - b) = D a - D b := linear_map.map_sub D a b instance : add_comm_group (derivation R A M) := { neg := λ D, ⟨-D, λ a b, by simp only [linear_map.neg_apply, smul_neg, neg_add_rev, leibniz, linear_map.to_fun_eq_coe, coe_fn_coe, add_comm]⟩, sub := λ D1 D2, ⟨D1 - D2, λ a b, by { simp only [linear_map.to_fun_eq_coe, linear_map.sub_apply, leibniz, coe_fn_coe, smul_sub], abel }⟩, sub_eq_add_neg := λ D1 D2, ext (λ i, sub_eq_add_neg _ _), add_left_neg := λ D, ext $ λ a, add_left_neg _, ..derivation.add_comm_monoid } @[simp] lemma sub_apply : (D1 - D2) a = D1 a - D2 a := rfl end section lie_structures /-! # Lie structures -/ variables (D : derivation R A A) {D1 D2 : derivation R A A} (r : R) (a b : A) /-- The commutator of derivations is again a derivation. -/ def commutator (D1 D2 : derivation R A A) : derivation R A A := { leibniz' := λ a b, by { simp only [ring.lie_def, map_add, id.smul_eq_mul, linear_map.mul_apply, leibniz, linear_map.to_fun_eq_coe, coe_fn_coe, linear_map.sub_apply], ring, }, ..⁅(D1 : module.End R A), (D2 : module.End R A)⁆, } instance : has_bracket (derivation R A A) (derivation R A A) := ⟨derivation.commutator⟩ @[simp] lemma commutator_coe_linear_map : ↑⁅D1, D2⁆ = ⁅(D1 : module.End R A), (D2 : module.End R A)⁆ := rfl lemma commutator_apply : ⁅D1, D2⁆ a = D1 (D2 a) - D2 (D1 a) := rfl instance : lie_ring (derivation R A A) := { add_lie := λ d e f, by { ext a, simp only [commutator_apply, add_apply, map_add], ring, }, lie_add := λ d e f, by { ext a, simp only [commutator_apply, add_apply, map_add], ring, }, lie_self := λ d, by { ext a, simp only [commutator_apply, add_apply, map_add], ring_nf, }, leibniz_lie := λ d e f, by { ext a, simp only [commutator_apply, add_apply, sub_apply, map_sub], ring, } } instance : lie_algebra R (derivation R A A) := { lie_smul := λ r d e, by { ext a, simp only [commutator_apply, map_smul, smul_sub, Rsmul_apply]}, ..derivation.Rmodule } end lie_structures end end derivation section comp_der namespace linear_map variables {R : Type*} [comm_semiring R] variables {A : Type*} [comm_semiring A] [algebra R A] variables {M : Type*} [add_cancel_comm_monoid M] [module A M] [module R M] variables {N : Type*} [add_cancel_comm_monoid N] [module A N] [module R N] variables [is_scalar_tower R A M] [is_scalar_tower R A N] /-- The composition of a linear map and a derivation is a derivation. -/ def comp_der (f : M →ₗ[A] N) (D : derivation R A M) : derivation R A N := { to_fun := λ a, f (D a), map_add' := λ a1 a2, by rw [D.map_add, f.map_add], map_smul' := λ r a, by rw [derivation.map_smul, map_smul_of_tower], leibniz' := λ a b, by simp only [derivation.leibniz, linear_map.map_smul, linear_map.map_add, add_comm] } @[simp] lemma comp_der_apply (f : M →ₗ[A] N) (D : derivation R A M) (a : A) : f.comp_der D a = f (D a) := rfl end linear_map end comp_der
a09be8d7a88fbb235a69d56f6ebdbf2f10b52e05
b00eb947a9c4141624aa8919e94ce6dcd249ed70
/src/Lean/LocalContext.lean
9b50d7252eacd328251e718a7c75332ef07d142c
[ "Apache-2.0" ]
permissive
gebner/lean4-old
a4129a041af2d4d12afb3a8d4deedabde727719b
ee51cdfaf63ee313c914d83264f91f414a0e3b6e
refs/heads/master
1,683,628,606,745
1,622,651,300,000
1,622,654,405,000
142,608,821
1
0
null
null
null
null
UTF-8
Lean
false
false
15,089
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Std.Data.PersistentArray import Lean.Expr import Lean.Hygiene namespace Lean inductive LocalDecl where | cdecl (index : Nat) (fvarId : FVarId) (userName : Name) (type : Expr) (bi : BinderInfo) | ldecl (index : Nat) (fvarId : FVarId) (userName : Name) (type : Expr) (value : Expr) (nonDep : Bool) deriving Inhabited @[export lean_mk_local_decl] def mkLocalDeclEx (index : Nat) (fvarId : FVarId) (userName : Name) (type : Expr) (bi : BinderInfo) : LocalDecl := LocalDecl.cdecl index fvarId userName type bi @[export lean_mk_let_decl] def mkLetDeclEx (index : Nat) (fvarId : FVarId) (userName : Name) (type : Expr) (val : Expr) : LocalDecl := LocalDecl.ldecl index fvarId userName type val false @[export lean_local_decl_binder_info] def LocalDecl.binderInfoEx : LocalDecl → BinderInfo | LocalDecl.cdecl _ _ _ _ bi => bi | _ => BinderInfo.default namespace LocalDecl def isLet : LocalDecl → Bool | cdecl .. => false | ldecl .. => true def index : LocalDecl → Nat | cdecl (index := i) .. => i | ldecl (index := i) .. => i def setIndex : LocalDecl → Nat → LocalDecl | cdecl _ id n t bi, idx => cdecl idx id n t bi | ldecl _ id n t v nd, idx => ldecl idx id n t v nd def fvarId : LocalDecl → FVarId | cdecl (fvarId := id) .. => id | ldecl (fvarId := id) .. => id def userName : LocalDecl → Name | cdecl (userName := n) .. => n | ldecl (userName := n) .. => n def type : LocalDecl → Expr | cdecl (type := t) .. => t | ldecl (type := t) .. => t def setType : LocalDecl → Expr → LocalDecl | cdecl idx id n _ bi, t => cdecl idx id n t bi | ldecl idx id n _ v nd, t => ldecl idx id n t v nd def binderInfo : LocalDecl → BinderInfo | cdecl (bi := bi) .. => bi | ldecl .. => BinderInfo.default def isAuxDecl (d : LocalDecl) : Bool := d.binderInfo.isAuxDecl def value? : LocalDecl → Option Expr | cdecl .. => none | ldecl (value := v) .. => some v def value : LocalDecl → Expr | cdecl .. => panic! "let declaration expected" | ldecl (value := v) .. => v def hasValue : LocalDecl → Bool | cdecl .. => false | ldecl .. => true def setValue : LocalDecl → Expr → LocalDecl | ldecl idx id n t _ nd, v => ldecl idx id n t v nd | d, _ => d def setUserName : LocalDecl → Name → LocalDecl | cdecl index id _ type bi, userName => cdecl index id userName type bi | ldecl index id _ type val nd, userName => ldecl index id userName type val nd def setBinderInfo : LocalDecl → BinderInfo → LocalDecl | cdecl index id n type _, bi => cdecl index id n type bi | ldecl .., _ => panic! "unexpected let declaration" def toExpr (decl : LocalDecl) : Expr := mkFVar decl.fvarId def hasExprMVar : LocalDecl → Bool | cdecl (type := t) .. => t.hasExprMVar | ldecl (type := t) (value := v) .. => t.hasExprMVar || v.hasExprMVar end LocalDecl open Std (PersistentHashMap PersistentArray PArray) structure LocalContext where fvarIdToDecl : PersistentHashMap FVarId LocalDecl := {} decls : PersistentArray (Option LocalDecl) := {} deriving Inhabited namespace LocalContext @[export lean_mk_empty_local_ctx] def mkEmpty : Unit → LocalContext := fun _ => {} def empty : LocalContext := {} @[export lean_local_ctx_is_empty] def isEmpty (lctx : LocalContext) : Bool := lctx.fvarIdToDecl.isEmpty /- Low level API for creating local declarations. It is used to implement actions in the monads `Elab` and `Tactic`. It should not be used directly since the argument `(name : Name)` is assumed to be "unique". -/ @[export lean_local_ctx_mk_local_decl] def mkLocalDecl (lctx : LocalContext) (fvarId : FVarId) (userName : Name) (type : Expr) (bi : BinderInfo := BinderInfo.default) : LocalContext := match lctx with | { fvarIdToDecl := map, decls := decls } => let idx := decls.size let decl := LocalDecl.cdecl idx fvarId userName type bi { fvarIdToDecl := map.insert fvarId decl, decls := decls.push decl } @[export lean_local_ctx_mk_let_decl] def mkLetDecl (lctx : LocalContext) (fvarId : FVarId) (userName : Name) (type : Expr) (value : Expr) (nonDep := false) : LocalContext := match lctx with | { fvarIdToDecl := map, decls := decls } => let idx := decls.size let decl := LocalDecl.ldecl idx fvarId userName type value nonDep { fvarIdToDecl := map.insert fvarId decl, decls := decls.push decl } /- Low level API -/ def addDecl (lctx : LocalContext) (newDecl : LocalDecl) : LocalContext := match lctx with | { fvarIdToDecl := map, decls := decls } => let idx := decls.size let newDecl := newDecl.setIndex idx { fvarIdToDecl := map.insert newDecl.fvarId newDecl, decls := decls.push newDecl } @[export lean_local_ctx_find] def find? (lctx : LocalContext) (fvarId : FVarId) : Option LocalDecl := lctx.fvarIdToDecl.find? fvarId def findFVar? (lctx : LocalContext) (e : Expr) : Option LocalDecl := lctx.find? e.fvarId! def get! (lctx : LocalContext) (fvarId : FVarId) : LocalDecl := match lctx.find? fvarId with | some d => d | none => panic! "unknown free variable" def getFVar! (lctx : LocalContext) (e : Expr) : LocalDecl := lctx.get! e.fvarId! def contains (lctx : LocalContext) (fvarId : FVarId) : Bool := lctx.fvarIdToDecl.contains fvarId def containsFVar (lctx : LocalContext) (e : Expr) : Bool := lctx.contains e.fvarId! def getFVarIds (lctx : LocalContext) : Array FVarId := lctx.decls.foldl (init := #[]) fun r decl? => match decl? with | some decl => r.push decl.fvarId | none => r def getFVars (lctx : LocalContext) : Array Expr := lctx.getFVarIds.map mkFVar private partial def popTailNoneAux (a : PArray (Option LocalDecl)) : PArray (Option LocalDecl) := if a.size == 0 then a else match a.get! (a.size - 1) with | none => popTailNoneAux a.pop | some _ => a @[export lean_local_ctx_erase] def erase (lctx : LocalContext) (fvarId : FVarId) : LocalContext := match lctx with | { fvarIdToDecl := map, decls := decls } => match map.find? fvarId with | none => lctx | some decl => { fvarIdToDecl := map.erase fvarId, decls := popTailNoneAux (decls.set decl.index none) } @[export lean_local_ctx_pop] def pop (lctx : LocalContext): LocalContext := match lctx with | { fvarIdToDecl := map, decls := decls } => if decls.size == 0 then lctx else match decls.get! (decls.size - 1) with | none => lctx -- unreachable | some decl => { fvarIdToDecl := map.erase decl.fvarId, decls := popTailNoneAux decls.pop } @[export lean_local_ctx_find_from_user_name] def findFromUserName? (lctx : LocalContext) (userName : Name) : Option LocalDecl := lctx.decls.findSomeRev? fun decl => match decl with | none => none | some decl => if decl.userName == userName then some decl else none @[export lean_local_ctx_uses_user_name] def usesUserName (lctx : LocalContext) (userName : Name) : Bool := (lctx.findFromUserName? userName).isSome private partial def getUnusedNameAux (lctx : LocalContext) (suggestion : Name) (i : Nat) : Name × Nat := let curr := suggestion.appendIndexAfter i if lctx.usesUserName curr then getUnusedNameAux lctx suggestion (i + 1) else (curr, i + 1) @[export lean_local_ctx_get_unused_name] def getUnusedName (lctx : LocalContext) (suggestion : Name) : Name := let suggestion := suggestion.eraseMacroScopes if lctx.usesUserName suggestion then (getUnusedNameAux lctx suggestion 1).1 else suggestion @[export lean_local_ctx_last_decl] def lastDecl (lctx : LocalContext) : Option LocalDecl := lctx.decls.get! (lctx.decls.size - 1) def setUserName (lctx : LocalContext) (fvarId : FVarId) (userName : Name) : LocalContext := let decl := lctx.get! fvarId let decl := decl.setUserName userName { fvarIdToDecl := lctx.fvarIdToDecl.insert decl.fvarId decl, decls := lctx.decls.set decl.index decl } @[export lean_local_ctx_rename_user_name] def renameUserName (lctx : LocalContext) (fromName : Name) (toName : Name) : LocalContext := match lctx with | { fvarIdToDecl := map, decls := decls } => match lctx.findFromUserName? fromName with | none => lctx | some decl => let decl := decl.setUserName toName; { fvarIdToDecl := map.insert decl.fvarId decl, decls := decls.set decl.index decl } /-- Low-level function for updating the local context. Assumptions about `f`, the resulting nested expressions must be definitionally equal to their original values, the `index` nor `fvarId` are modified. -/ @[inline] def modifyLocalDecl (lctx : LocalContext) (fvarId : FVarId) (f : LocalDecl → LocalDecl) : LocalContext := match lctx with | { fvarIdToDecl := map, decls := decls } => match lctx.find? fvarId with | none => lctx | some decl => let decl := f decl; { fvarIdToDecl := map.insert decl.fvarId decl, decls := decls.set decl.index decl } def setBinderInfo (lctx : LocalContext) (fvarId : FVarId) (bi : BinderInfo) : LocalContext := modifyLocalDecl lctx fvarId fun decl => decl.setBinderInfo bi @[export lean_local_ctx_num_indices] def numIndices (lctx : LocalContext) : Nat := lctx.decls.size @[export lean_local_ctx_get] def getAt? (lctx : LocalContext) (i : Nat) : Option LocalDecl := lctx.decls.get! i section universes u v variable {m : Type u → Type v} [Monad m] variable {β : Type u} @[specialize] def foldlM (lctx : LocalContext) (f : β → LocalDecl → m β) (init : β) (start : Nat := 0) : m β := lctx.decls.foldlM (init := init) (start := start) fun b decl => match decl with | none => pure b | some decl => f b decl @[specialize] def forM (lctx : LocalContext) (f : LocalDecl → m PUnit) : m PUnit := lctx.decls.forM fun decl => match decl with | none => pure PUnit.unit | some decl => f decl @[specialize] def findDeclM? (lctx : LocalContext) (f : LocalDecl → m (Option β)) : m (Option β) := lctx.decls.findSomeM? fun decl => match decl with | none => pure none | some decl => f decl @[specialize] def findDeclRevM? (lctx : LocalContext) (f : LocalDecl → m (Option β)) : m (Option β) := lctx.decls.findSomeRevM? fun decl => match decl with | none => pure none | some decl => f decl instance : ForIn m LocalContext LocalDecl where forIn lctx init f := lctx.decls.forIn init fun d? b => match d? with | none => ForInStep.yield b | some d => f d b end @[inline] def foldl {β} (lctx : LocalContext) (f : β → LocalDecl → β) (init : β) (start : Nat := 0) : β := Id.run <| lctx.foldlM f init start @[inline] def findDecl? {β} (lctx : LocalContext) (f : LocalDecl → Option β) : Option β := Id.run <| lctx.findDeclM? f @[inline] def findDeclRev? {β} (lctx : LocalContext) (f : LocalDecl → Option β) : Option β := Id.run <| lctx.findDeclRevM? f partial def isSubPrefixOfAux (a₁ a₂ : PArray (Option LocalDecl)) (exceptFVars : Array Expr) (i j : Nat) : Bool := if i < a₁.size then match a₁[i] with | none => isSubPrefixOfAux a₁ a₂ exceptFVars (i+1) j | some decl₁ => if exceptFVars.any fun fvar => fvar.fvarId! == decl₁.fvarId then isSubPrefixOfAux a₁ a₂ exceptFVars (i+1) j else if j < a₂.size then match a₂[j] with | none => isSubPrefixOfAux a₁ a₂ exceptFVars i (j+1) | some decl₂ => if decl₁.fvarId == decl₂.fvarId then isSubPrefixOfAux a₁ a₂ exceptFVars (i+1) (j+1) else isSubPrefixOfAux a₁ a₂ exceptFVars i (j+1) else false else true /- Given `lctx₁ - exceptFVars` of the form `(x_1 : A_1) ... (x_n : A_n)`, then return true iff there is a local context `B_1* (x_1 : A_1) ... B_n* (x_n : A_n)` which is a prefix of `lctx₂` where `B_i`'s are (possibly empty) sequences of local declarations. -/ def isSubPrefixOf (lctx₁ lctx₂ : LocalContext) (exceptFVars : Array Expr := #[]) : Bool := isSubPrefixOfAux lctx₁.decls lctx₂.decls exceptFVars 0 0 @[inline] def mkBinding (isLambda : Bool) (lctx : LocalContext) (xs : Array Expr) (b : Expr) : Expr := let b := b.abstract xs xs.size.foldRev (init := b) fun i b => let x := xs[i] match lctx.findFVar? x with | some (LocalDecl.cdecl _ _ n ty bi) => let ty := ty.abstractRange i xs; if isLambda then Lean.mkLambda n bi ty b else Lean.mkForall n bi ty b | some (LocalDecl.ldecl _ _ n ty val nonDep) => if b.hasLooseBVar 0 then let ty := ty.abstractRange i xs let val := val.abstractRange i xs mkLet n ty val b nonDep else b.lowerLooseBVars 1 1 | none => panic! "unknown free variable" def mkLambda (lctx : LocalContext) (xs : Array Expr) (b : Expr) : Expr := mkBinding true lctx xs b def mkForall (lctx : LocalContext) (xs : Array Expr) (b : Expr) : Expr := mkBinding false lctx xs b section universes u variable {m : Type → Type u} [Monad m] @[inline] def anyM (lctx : LocalContext) (p : LocalDecl → m Bool) : m Bool := lctx.decls.anyM fun d => match d with | some decl => p decl | none => pure false @[inline] def allM (lctx : LocalContext) (p : LocalDecl → m Bool) : m Bool := lctx.decls.allM fun d => match d with | some decl => p decl | none => pure true end @[inline] def any (lctx : LocalContext) (p : LocalDecl → Bool) : Bool := Id.run <| lctx.anyM p @[inline] def all (lctx : LocalContext) (p : LocalDecl → Bool) : Bool := Id.run <| lctx.allM p def sanitizeNames (lctx : LocalContext) : StateM NameSanitizerState LocalContext := do let st ← get if !getSanitizeNames st.options then pure lctx else StateT.run' (s := ({} : NameSet)) <| lctx.decls.size.foldRevM (init := lctx) fun i lctx => do match lctx.decls[i] with | none => pure lctx | some decl => if decl.userName.hasMacroScopes || (← get).contains decl.userName then do modify fun s => s.insert decl.userName let userNameNew ← liftM <| sanitizeName decl.userName pure <| lctx.setUserName decl.fvarId userNameNew else modify fun s => s.insert decl.userName pure lctx end LocalContext class MonadLCtx (m : Type → Type) where getLCtx : m LocalContext export MonadLCtx (getLCtx) instance (m n) [MonadLift m n] [MonadLCtx m] : MonadLCtx n where getLCtx := liftM (getLCtx : m _) def replaceFVarIdAtLocalDecl (fvarId : FVarId) (e : Expr) (d : LocalDecl) : LocalDecl := if d.fvarId == fvarId then d else match d with | LocalDecl.cdecl idx id n type bi => LocalDecl.cdecl idx id n (type.replaceFVarId fvarId e) bi | LocalDecl.ldecl idx id n type val nonDep => LocalDecl.ldecl idx id n (type.replaceFVarId fvarId e) (val.replaceFVarId fvarId e) nonDep end Lean
be20b92216460beafcada4afab96c5a249e91287
1b8f093752ba748c5ca0083afef2959aaa7dace5
/src/category_theory/equivalence/default.lean
176dcda2b1d567261adfc51d474ba6bbec3c4599
[]
no_license
khoek/lean-category-theory
7ec4cda9cc64a5a4ffeb84712ac7d020dbbba386
63dcb598e9270a3e8b56d1769eb4f825a177cd95
refs/heads/master
1,585,251,725,759
1,539,344,445,000
1,539,344,445,000
145,281,070
0
0
null
1,534,662,376,000
1,534,662,376,000
null
UTF-8
Lean
false
false
6,482
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Tim Baumann, Stephen Morgan, Scott Morrison import category_theory.embedding import category_theory.tactics.obviously import category_theory.follow_your_nose namespace category_theory universes u₁ v₁ u₂ v₂ u₃ v₃ structure equivalence (C : Type u₁) [category.{u₁ v₁} C] (D : Type u₂) [category.{u₂ v₂} D] := (functor : C ⥤ D) (inverse : D ⥤ C) (fun_inv_id' : (functor ⋙ inverse) ≅ (category_theory.functor.id C) . obviously) (inv_fun_id' : (inverse ⋙ functor) ≅ (category_theory.functor.id D) . obviously) restate_axiom equivalence.fun_inv_id' restate_axiom equivalence.inv_fun_id' infixr ` ≌ `:10 := equivalence namespace equivalence variables {C : Type u₁} [𝒞 : category.{u₁ v₁} C] include 𝒞 def refl : C ≌ C := { functor := functor.id C, inverse := functor.id C } variables {D : Type u₂} [𝒟 : category.{u₂ v₂} D] include 𝒟 def symm (e : C ≌ D) : D ≌ C := { functor := e.inverse, inverse := e.functor, fun_inv_id' := e.inv_fun_id, inv_fun_id' := e.fun_inv_id } @[simp,search] lemma fun_inv_map (e : C ≌ D) (X Y : D) (f : X ⟶ Y) : e.functor.map (e.inverse.map f) = (e.inv_fun_id.hom X) ≫ f ≫ (e.inv_fun_id.inv Y) := by obviously @[simp,search] lemma inv_fun_map (e : C ≌ D) (X Y : C) (f : X ⟶ Y) : e.inverse.map (e.functor.map f) = (e.fun_inv_id.hom X) ≫ f ≫ (e.fun_inv_id.inv Y) := by obviously variables {E : Type u₃} [ℰ : category.{u₃ v₃} E] include ℰ attribute [trans] category.comp def effe_id (e : C ≌ D) (f : D ≌ E) (X : C) : (e.inverse) ((f.inverse) ((f.functor) ((e.functor) X))) ⟶ X := calc _ ⟶ (e.inverse) ((e.functor) X) : e.inverse.map (f.fun_inv_id.hom.app _) ... ⟶ X : e.fun_inv_id.hom.app _ def id_effe (e : C ≌ D) (f : D ≌ E) (X : C) : (functor.id C) X ⟶ ((e.functor ⋙ f.functor) ⋙ f.inverse ⋙ e.inverse) X := calc X ⟶ (e.functor ⋙ e.inverse) X : e.fun_inv_id.inv.app _ ... ⟶ _ : e.inverse.map (f.fun_inv_id.inv.app _) def feef_id (e : C ≌ D) (f : D ≌ E) (X : E) : (f.functor) ((e.functor) ((e.inverse) ((f.inverse) X))) ⟶ X := calc _ ⟶ (f.functor) ((f.inverse) X) : f.functor.map (e.inv_fun_id.hom.app _) ... ⟶ X : f.inv_fun_id.hom.app _ def id_feef (e : C ≌ D) (f : D ≌ E) (X : E) : X ⟶ ((f.inverse ⋙ e.inverse) ⋙ e.functor ⋙ f.functor) X := calc X ⟶ (f.inverse ⋙ f.functor) X : f.inv_fun_id.inv.app _ ... ⟶ _ : f.functor.map (e.inv_fun_id.inv.app _) set_option trace.tidy true def trans (e : C ≌ D) (f : D ≌ E) : C ≌ E := { functor := e.functor ⋙ f.functor, inverse := f.inverse ⋙ e.inverse, fun_inv_id' := { hom := { app := λ X, effe_id e f X, naturality' := begin dsimp [effe_id], intros, rw ← category.assoc, rw ← functor.map_comp, rw nat_trans.app_eq_coe, erw nat_trans.naturality ((fun_inv_id f).hom), -- work out why this is so difficult: we must be missing something sorry end /-begin tidy, rewrite_search_using [`search] end-/ }, -- These fail, exceeding max iterations. inv := { app := λ X, id_effe e f X, naturality' := sorry }, hom_inv_id' := sorry, -- These seem to work: 13 step rewrites! inv_hom_id' := sorry }, inv_fun_id' := { hom := { app := λ X, feef_id e f X, naturality' := sorry }, inv := { app := λ X, id_feef e f X, naturality' := sorry }, hom_inv_id' := sorry, inv_hom_id' := sorry }, } end equivalence variables {C : Type u₁} [𝒞 : category.{u₁ v₁} C] include 𝒞 section variables {D : Type u₂} [𝒟 : category.{u₂ v₂} D] include 𝒟 class is_equivalence (F : C ⥤ D) := (inverse : D ⥤ C) (fun_inv_id' : (F ⋙ inverse) ≅ (functor.id C) . obviously) (inv_fun_id' : (inverse ⋙ F) ≅ (functor.id D) . obviously) restate_axiom is_equivalence.fun_inv_id' restate_axiom is_equivalence.inv_fun_id' end namespace functor instance is_equivalence_refl : is_equivalence (functor.id C) := { inverse := functor.id C } end functor variables {D : Type u₂} [𝒟 : category.{u₂ v₂} D] include 𝒟 namespace functor def inv (F : C ⥤ D) [is_equivalence F] : D ⥤ C := is_equivalence.inverse F instance is_equivalence_symm (F : C ⥤ D) [is_equivalence F] : is_equivalence (F.inv) := { inverse := F, fun_inv_id' := is_equivalence.inv_fun_id F, inv_fun_id' := is_equivalence.fun_inv_id F } def fun_inv_id (F : C ⥤ D) [is_equivalence F] : (F ⋙ F.inv) ≅ functor.id C := is_equivalence.fun_inv_id F def inv_fun_id (F : C ⥤ D) [is_equivalence F] : (F.inv ⋙ F) ≅ functor.id D := is_equivalence.inv_fun_id F def as_equivalence (F : C ⥤ D) [is_equivalence F] : C ≌ D := { functor := F, inverse := is_equivalence.inverse F, fun_inv_id' := is_equivalence.fun_inv_id F, inv_fun_id' := is_equivalence.inv_fun_id F } variables {E : Type u₃} [ℰ : category.{u₃ v₃} E] include ℰ instance is_equivalence_trans (F : C ⥤ D) (G : D ⥤ E) [is_equivalence F] [is_equivalence G] : is_equivalence (F ⋙ G) := sorry end functor namespace is_equivalence instance is_equivalence_functor (e : C ≌ D) : is_equivalence e.functor := { inverse := e.inverse, fun_inv_id' := e.fun_inv_id, inv_fun_id' := e.inv_fun_id } instance is_equivalence_inverse (e : C ≌ D) : is_equivalence e.inverse := { inverse := e.functor, fun_inv_id' := e.inv_fun_id, inv_fun_id' := e.fun_inv_id } @[simp,search] lemma fun_inv_map (F : C ⥤ D) [is_equivalence F] (X Y : D) (f : X ⟶ Y) : F.map (F.inv.map f) = (F.inv_fun_id.hom.app X) ≫ f ≫ (F.inv_fun_id.inv.app Y) := by obviously @[simp,search] lemma inv_fun_map (F : C ⥤ D) [is_equivalence F] (X Y : C) (f : X ⟶ Y) : F.inv.map (F.map f) = (F.fun_inv_id.hom.app X) ≫ f ≫ (F.fun_inv_id.inv.app Y) := by obviously end is_equivalence class ess_surj (F : C ⥤ D) := (obj_preimage (d : D) : C) (iso' (d : D) : F (obj_preimage d) ≅ d . obviously) restate_axiom ess_surj.iso' namespace functor def obj_preimage (F : C ⥤ D) [ess_surj F] (d : D) : C := ess_surj.obj_preimage.{u₁ v₁ u₂ v₂} F d def fun_obj_preimage_iso (F : C ⥤ D) [ess_surj F] (d : D) : F (F.obj_preimage d) ≅ d := ess_surj.iso F d end functor end category_theory
c066f94f13f523d66cfbd2687885ff7a67c431dc
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/data/equiv/transfer_instance.lean
e7808c3644b3f47314660fa46c4f1e82d950f8fe
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
12,575
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import data.equiv.basic import algebra.field import algebra.module import algebra.algebra.basic import algebra.group.type_tags import ring_theory.ideal.basic /-! # Transfer algebraic structures across `equiv`s In this file we prove theorems of the following form: if `β` has a group structure and `α ≃ β` then `α` has a group structure, and similarly for monoids, semigroups, rings, integral domains, fields and so on. Note that most of these constructions can also be obtained using the `transport` tactic. ## Tags equiv, group, ring, field, module, algebra -/ universes u v variables {α : Type u} {β : Type v} namespace equiv section instances variables (e : α ≃ β) /-- Transfer `has_one` across an `equiv` -/ @[to_additive "Transfer `has_zero` across an `equiv`"] protected def has_one [has_one β] : has_one α := ⟨e.symm 1⟩ @[to_additive] lemma one_def [has_one β] : @has_one.one _ (equiv.has_one e) = e.symm 1 := rfl /-- Transfer `has_mul` across an `equiv` -/ @[to_additive "Transfer `has_add` across an `equiv`"] protected def has_mul [has_mul β] : has_mul α := ⟨λ x y, e.symm (e x * e y)⟩ @[to_additive] lemma mul_def [has_mul β] (x y : α) : @has_mul.mul _ (equiv.has_mul e) x y = e.symm (e x * e y) := rfl /-- Transfer `has_div` across an `equiv` -/ @[to_additive "Transfer `has_sub` across an `equiv`"] protected def has_div [has_div β] : has_div α := ⟨λ x y, e.symm (e x / e y)⟩ @[to_additive] lemma div_def [has_div β] (x y : α) : @has_div.div _ (equiv.has_div e) x y = e.symm (e x / e y) := rfl /-- Transfer `has_inv` across an `equiv` -/ @[to_additive "Transfer `has_neg` across an `equiv`"] protected def has_inv [has_inv β] : has_inv α := ⟨λ x, e.symm (e x)⁻¹⟩ @[to_additive] lemma inv_def [has_inv β] (x : α) : @has_inv.inv _ (equiv.has_inv e) x = e.symm (e x)⁻¹ := rfl /-- Transfer `has_scalar` across an `equiv` -/ protected def has_scalar {R : Type*} [has_scalar R β] : has_scalar R α := ⟨λ r x, e.symm (r • (e x))⟩ lemma smul_def {R : Type*} [has_scalar R β] (r : R) (x : α) : @has_scalar.smul _ _ (equiv.has_scalar e) r x = e.symm (r • (e x)) := rfl /-- An equivalence `e : α ≃ β` gives a multiplicative equivalence `α ≃* β` where the multiplicative structure on `α` is the one obtained by transporting a multiplicative structure on `β` back along `e`. -/ @[to_additive "An equivalence `e : α ≃ β` gives a additive equivalence `α ≃+ β` where the additive structure on `α` is the one obtained by transporting an additive structure on `β` back along `e`."] def mul_equiv (e : α ≃ β) [has_mul β] : by { letI := equiv.has_mul e, exact α ≃* β } := begin introsI, exact { map_mul' := λ x y, by { apply e.symm.injective, simp, refl, }, ..e } end @[simp, to_additive] lemma mul_equiv_apply (e : α ≃ β) [has_mul β] (a : α) : (mul_equiv e) a = e a := rfl @[to_additive] lemma mul_equiv_symm_apply (e : α ≃ β) [has_mul β] (b : β) : by { letI := equiv.has_mul e, exact (mul_equiv e).symm b = e.symm b } := begin intros, refl, end /-- An equivalence `e : α ≃ β` gives a ring equivalence `α ≃+* β` where the ring structure on `α` is the one obtained by transporting a ring structure on `β` back along `e`. -/ def ring_equiv (e : α ≃ β) [has_add β] [has_mul β] : by { letI := equiv.has_add e, letI := equiv.has_mul e, exact α ≃+* β } := begin introsI, exact { map_add' := λ x y, by { apply e.symm.injective, simp, refl, }, map_mul' := λ x y, by { apply e.symm.injective, simp, refl, }, ..e } end @[simp] lemma ring_equiv_apply (e : α ≃ β) [has_add β] [has_mul β] (a : α) : (ring_equiv e) a = e a := rfl lemma ring_equiv_symm_apply (e : α ≃ β) [has_add β] [has_mul β] (b : β) : by { letI := equiv.has_add e, letI := equiv.has_mul e, exact (ring_equiv e).symm b = e.symm b } := begin intros, refl, end /-- Transfer `semigroup` across an `equiv` -/ @[to_additive "Transfer `add_semigroup` across an `equiv`"] protected def semigroup [semigroup β] : semigroup α := let mul := e.has_mul in by resetI; apply e.injective.semigroup _; intros; exact e.apply_symm_apply _ /-- Transfer `semigroup_with_zero` across an `equiv` -/ protected def semigroup_with_zero [semigroup_with_zero β] : semigroup_with_zero α := let mul := e.has_mul, zero := e.has_zero in by resetI; apply e.injective.semigroup_with_zero _; intros; exact e.apply_symm_apply _ /-- Transfer `comm_semigroup` across an `equiv` -/ @[to_additive "Transfer `add_comm_semigroup` across an `equiv`"] protected def comm_semigroup [comm_semigroup β] : comm_semigroup α := let mul := e.has_mul in by resetI; apply e.injective.comm_semigroup _; intros; exact e.apply_symm_apply _ /-- Transfer `mul_zero_class` across an `equiv` -/ protected def mul_zero_class [mul_zero_class β] : mul_zero_class α := let zero := e.has_zero, mul := e.has_mul in by resetI; apply e.injective.mul_zero_class _; intros; exact e.apply_symm_apply _ /-- Transfer `mul_one_class` across an `equiv` -/ @[to_additive "Transfer `add_zero_class` across an `equiv`"] protected def mul_one_class [mul_one_class β] : mul_one_class α := let one := e.has_one, mul := e.has_mul in by resetI; apply e.injective.mul_one_class _; intros; exact e.apply_symm_apply _ /-- Transfer `mul_zero_one_class` across an `equiv` -/ protected def mul_zero_one_class [mul_zero_one_class β] : mul_zero_one_class α := let zero := e.has_zero, one := e.has_one,mul := e.has_mul in by resetI; apply e.injective.mul_zero_one_class _; intros; exact e.apply_symm_apply _ /-- Transfer `monoid` across an `equiv` -/ @[to_additive "Transfer `add_monoid` across an `equiv`"] protected def monoid [monoid β] : monoid α := let one := e.has_one, mul := e.has_mul in by resetI; apply e.injective.monoid _; intros; exact e.apply_symm_apply _ /-- Transfer `comm_monoid` across an `equiv` -/ @[to_additive "Transfer `add_comm_monoid` across an `equiv`"] protected def comm_monoid [comm_monoid β] : comm_monoid α := let one := e.has_one, mul := e.has_mul in by resetI; apply e.injective.comm_monoid _; intros; exact e.apply_symm_apply _ /-- Transfer `group` across an `equiv` -/ @[to_additive "Transfer `add_group` across an `equiv`"] protected def group [group β] : group α := let one := e.has_one, mul := e.has_mul, inv := e.has_inv, div := e.has_div in by resetI; apply e.injective.group _; intros; exact e.apply_symm_apply _ /-- Transfer `comm_group` across an `equiv` -/ @[to_additive "Transfer `add_comm_group` across an `equiv`"] protected def comm_group [comm_group β] : comm_group α := let one := e.has_one, mul := e.has_mul, inv := e.has_inv, div := e.has_div in by resetI; apply e.injective.comm_group _; intros; exact e.apply_symm_apply _ /-- Transfer `semiring` across an `equiv` -/ protected def semiring [semiring β] : semiring α := let zero := e.has_zero, add := e.has_add, one := e.has_one, mul := e.has_mul in by resetI; apply e.injective.semiring _; intros; exact e.apply_symm_apply _ /-- Transfer `comm_semiring` across an `equiv` -/ protected def comm_semiring [comm_semiring β] : comm_semiring α := let zero := e.has_zero, add := e.has_add, one := e.has_one, mul := e.has_mul in by resetI; apply e.injective.comm_semiring _; intros; exact e.apply_symm_apply _ /-- Transfer `ring` across an `equiv` -/ protected def ring [ring β] : ring α := let zero := e.has_zero, add := e.has_add, one := e.has_one, mul := e.has_mul, neg := e.has_neg, sub := e.has_sub in by resetI; apply e.injective.ring _; intros; exact e.apply_symm_apply _ /-- Transfer `comm_ring` across an `equiv` -/ protected def comm_ring [comm_ring β] : comm_ring α := let zero := e.has_zero, add := e.has_add, one := e.has_one, mul := e.has_mul, neg := e.has_neg, sub := e.has_sub in by resetI; apply e.injective.comm_ring _; intros; exact e.apply_symm_apply _ /-- Transfer `nonzero` across an `equiv` -/ protected theorem nontrivial [nontrivial β] : nontrivial α := e.surjective.nontrivial /-- Transfer `domain` across an `equiv` -/ protected def domain [domain β] : domain α := let zero := e.has_zero, add := e.has_add, one := e.has_one, mul := e.has_mul, neg := e.has_neg, sub := e.has_sub in by resetI; apply e.injective.domain _; intros; exact e.apply_symm_apply _ /-- Transfer `integral_domain` across an `equiv` -/ protected def integral_domain [integral_domain β] : integral_domain α := let zero := e.has_zero, add := e.has_add, one := e.has_one, mul := e.has_mul, neg := e.has_neg, sub := e.has_sub in by resetI; apply e.injective.integral_domain _; intros; exact e.apply_symm_apply _ /-- Transfer `division_ring` across an `equiv` -/ protected def division_ring [division_ring β] : division_ring α := let zero := e.has_zero, add := e.has_add, one := e.has_one, mul := e.has_mul, neg := e.has_neg, sub := e.has_sub, inv := e.has_inv, div := e.has_div in by resetI; apply e.injective.division_ring _; intros; exact e.apply_symm_apply _ /-- Transfer `field` across an `equiv` -/ protected def field [field β] : field α := let zero := e.has_zero, add := e.has_add, one := e.has_one, mul := e.has_mul, neg := e.has_neg, sub := e.has_sub, inv := e.has_inv, div := e.has_div in by resetI; apply e.injective.field _; intros; exact e.apply_symm_apply _ section R variables (R : Type*) include R section variables [monoid R] /-- Transfer `mul_action` across an `equiv` -/ protected def mul_action (e : α ≃ β) [mul_action R β] : mul_action R α := { one_smul := by simp [smul_def], mul_smul := by simp [smul_def, mul_smul], ..equiv.has_scalar e } /-- Transfer `distrib_mul_action` across an `equiv` -/ protected def distrib_mul_action (e : α ≃ β) [add_comm_monoid β] : begin letI := equiv.add_comm_monoid e, exact Π [distrib_mul_action R β], distrib_mul_action R α end := begin intros, letI := equiv.add_comm_monoid e, exact ( { smul_zero := by simp [zero_def, smul_def], smul_add := by simp [add_def, smul_def, smul_add], ..equiv.mul_action R e } : distrib_mul_action R α) end end section variables [semiring R] /-- Transfer `module` across an `equiv` -/ protected def module (e : α ≃ β) [add_comm_monoid β] : begin letI := equiv.add_comm_monoid e, exact Π [module R β], module R α end := begin introsI, exact ( { zero_smul := by simp [zero_def, smul_def], add_smul := by simp [add_def, smul_def, add_smul], ..equiv.distrib_mul_action R e } : module R α) end /-- An equivalence `e : α ≃ β` gives a linear equivalence `α ≃ₗ[R] β` where the `R`-module structure on `α` is the one obtained by transporting an `R`-module structure on `β` back along `e`. -/ def linear_equiv (e : α ≃ β) [add_comm_monoid β] [module R β] : begin letI := equiv.add_comm_monoid e, letI := equiv.module R e, exact α ≃ₗ[R] β end := begin introsI, exact { map_smul' := λ r x, by { apply e.symm.injective, simp, refl, }, ..equiv.add_equiv e } end end section variables [comm_semiring R] /-- Transfer `algebra` across an `equiv` -/ protected def algebra (e : α ≃ β) [semiring β] : begin letI := equiv.semiring e, exact Π [algebra R β], algebra R α end := begin introsI, fapply ring_hom.to_algebra', { exact ((ring_equiv e).symm : β →+* α).comp (algebra_map R β), }, { intros r x, simp only [function.comp_app, ring_hom.coe_comp], have p := ring_equiv_symm_apply e, dsimp at p, erw p, clear p, apply (ring_equiv e).injective, simp only [(ring_equiv e).map_mul], simp [algebra.commutes], } end /-- An equivalence `e : α ≃ β` gives an algebra equivalence `α ≃ₐ[R] β` where the `R`-algebra structure on `α` is the one obtained by transporting an `R`-algebra structure on `β` back along `e`. -/ def alg_equiv (e : α ≃ β) [semiring β] [algebra R β] : begin letI := equiv.semiring e, letI := equiv.algebra R e, exact α ≃ₐ[R] β end := begin introsI, exact { commutes' := λ r, by { apply e.symm.injective, simp, refl, }, ..equiv.ring_equiv e } end end end R end instances end equiv namespace ring_equiv protected lemma local_ring {A B : Type*} [comm_ring A] [local_ring A] [comm_ring B] (e : A ≃+* B) : local_ring B := begin haveI := e.symm.to_equiv.nontrivial, refine @local_of_surjective A B _ _ _ _ e e.to_equiv.surjective, end end ring_equiv
44034637a0b90dcb22c2d14ecbb2e961febe7e4b
4b846d8dabdc64e7ea03552bad8f7fa74763fc67
/tests/lean/run/smt_rsimp.lean
43794ddaefc62cb659c2807466209273319fac2c
[ "Apache-2.0" ]
permissive
pacchiano/lean
9324b33f3ac3b5c5647285160f9f6ea8d0d767dc
fdadada3a970377a6df8afcd629a6f2eab6e84e8
refs/heads/master
1,611,357,380,399
1,489,870,101,000
1,489,870,101,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
412
lean
constant p {α} : α → α → Prop axiom pax {α} : ∀ n : α, p n n open tactic meta def check_expr (p : pexpr) (t : expr) : tactic unit := do e ← to_expr p, guard (t = e) meta def check_target (p : pexpr) : tactic unit := target >>= check_expr p example (s t : list nat) (h : t = s) : p (s ++ []) ([] ++ t) := begin [smt] add_simp_lemmas, ematch, rsimp, check_target `(p s s), apply pax end
39bb995d4e7a87911671d92c2a689b55deb5c677
680b0d1592ce164979dab866b232f6fa743f2cc8
/hott/types/equiv.hlean
c9ca55f39461f8321c29da4d3e62c441cf8a608f
[ "Apache-2.0" ]
permissive
syohex/lean
657428ab520f8277fc18cf04bea2ad200dbae782
081ad1212b686780f3ff8a6d0e5f8a1d29a7d8bc
refs/heads/master
1,611,274,838,635
1,452,668,188,000
1,452,668,188,000
49,562,028
0
0
null
1,452,675,604,000
1,452,675,602,000
null
UTF-8
Lean
false
false
7,541
hlean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn Ported from Coq HoTT Theorems about the types equiv and is_equiv -/ import .fiber .arrow arity ..hprop_trunc open eq is_trunc sigma sigma.ops pi fiber function equiv equiv.ops namespace is_equiv variables {A B : Type} (f : A → B) [H : is_equiv f] include H /- is_equiv f is a mere proposition -/ definition is_contr_fiber_of_is_equiv [instance] (b : B) : is_contr (fiber f b) := is_contr.mk (fiber.mk (f⁻¹ b) (right_inv f b)) (λz, fiber.rec_on z (λa p, fiber_eq ((ap f⁻¹ p)⁻¹ ⬝ left_inv f a) (calc right_inv f b = (ap (f ∘ f⁻¹) p)⁻¹ ⬝ ((ap (f ∘ f⁻¹) p) ⬝ right_inv f b) : by rewrite inv_con_cancel_left ... = (ap (f ∘ f⁻¹) p)⁻¹ ⬝ (right_inv f (f a) ⬝ p) : by rewrite ap_con_eq_con ... = (ap (f ∘ f⁻¹) p)⁻¹ ⬝ (ap f (left_inv f a) ⬝ p) : by rewrite [adj f] ... = (ap (f ∘ f⁻¹) p)⁻¹ ⬝ ap f (left_inv f a) ⬝ p : by rewrite con.assoc ... = (ap f (ap f⁻¹ p))⁻¹ ⬝ ap f (left_inv f a) ⬝ p : by rewrite ap_compose ... = ap f (ap f⁻¹ p)⁻¹ ⬝ ap f (left_inv f a) ⬝ p : by rewrite ap_inv ... = ap f ((ap f⁻¹ p)⁻¹ ⬝ left_inv f a) ⬝ p : by rewrite ap_con))) definition is_contr_right_inverse : is_contr (Σ(g : B → A), f ∘ g ~ id) := begin fapply is_trunc_equiv_closed, {apply sigma_equiv_sigma_id, intro g, apply eq_equiv_homotopy}, fapply is_trunc_equiv_closed, {apply fiber.sigma_char}, fapply is_contr_fiber_of_is_equiv, apply (to_is_equiv (arrow_equiv_arrow_right B (equiv.mk f H))), end definition is_contr_right_coherence (u : Σ(g : B → A), f ∘ g ~ id) : is_contr (Σ(η : u.1 ∘ f ~ id), Π(a : A), u.2 (f a) = ap f (η a)) := begin fapply is_trunc_equiv_closed, {apply equiv.symm, apply sigma_pi_equiv_pi_sigma}, fapply is_trunc_equiv_closed, {apply pi_equiv_pi_id, intro a, apply (fiber_eq_equiv (fiber.mk (u.1 (f a)) (u.2 (f a))) (fiber.mk a idp))}, end omit H protected definition sigma_char : (is_equiv f) ≃ (Σ(g : B → A) (ε : f ∘ g ~ id) (η : g ∘ f ~ id), Π(a : A), ε (f a) = ap f (η a)) := equiv.MK (λH, ⟨inv f, right_inv f, left_inv f, adj f⟩) (λp, is_equiv.mk f p.1 p.2.1 p.2.2.1 p.2.2.2) (λp, begin induction p with p1 p2, induction p2 with p21 p22, induction p22 with p221 p222, reflexivity end) (λH, by induction H; reflexivity) protected definition sigma_char' : (is_equiv f) ≃ (Σ(u : Σ(g : B → A), f ∘ g ~ id), Σ(η : u.1 ∘ f ~ id), Π(a : A), u.2 (f a) = ap f (η a)) := calc (is_equiv f) ≃ (Σ(g : B → A) (ε : f ∘ g ~ id) (η : g ∘ f ~ id), Π(a : A), ε (f a) = ap f (η a)) : is_equiv.sigma_char ... ≃ (Σ(u : Σ(g : B → A), f ∘ g ~ id), Σ(η : u.1 ∘ f ~ id), Π(a : A), u.2 (f a) = ap f (η a)) : {sigma_assoc_equiv (λu, Σ(η : u.1 ∘ f ~ id), Π(a : A), u.2 (f a) = ap f (η a))} local attribute is_contr_right_inverse [instance] [priority 1600] local attribute is_contr_right_coherence [instance] [priority 1600] theorem is_hprop_is_equiv [instance] : is_hprop (is_equiv f) := is_hprop_of_imp_is_contr (λ(H : is_equiv f), is_trunc_equiv_closed -2 (equiv.symm !is_equiv.sigma_char')) definition inv_eq_inv {A B : Type} {f f' : A → B} {Hf : is_equiv f} {Hf' : is_equiv f'} (p : f = f') : f⁻¹ = f'⁻¹ := apd011 inv p !is_hprop.elim /- contractible fibers -/ definition is_contr_fun_of_is_equiv [H : is_equiv f] : is_contr_fun f := is_contr_fiber_of_is_equiv f definition is_hprop_is_contr_fun (f : A → B) : is_hprop (is_contr_fun f) := _ definition is_equiv_of_is_contr_fun [H : is_contr_fun f] : is_equiv f := adjointify _ (λb, point (center (fiber f b))) (λb, point_eq (center (fiber f b))) (λa, ap point (center_eq (fiber.mk a idp))) definition is_equiv_of_imp_is_equiv (H : B → is_equiv f) : is_equiv f := @is_equiv_of_is_contr_fun _ _ f (λb, @is_contr_fiber_of_is_equiv _ _ _ (H b) _) definition is_equiv_equiv_is_contr_fun : is_equiv f ≃ is_contr_fun f := equiv_of_is_hprop _ (λH, !is_equiv_of_is_contr_fun) end is_equiv namespace is_equiv /- Theorem 4.7.7 -/ variables {A : Type} {P Q : A → Type} variable (f : Πa, P a → Q a) definition is_fiberwise_equiv [reducible] := Πa, is_equiv (f a) definition is_equiv_total_of_is_fiberwise_equiv [H : is_fiberwise_equiv f] : is_equiv (total f) := is_equiv_sigma_functor id f definition is_fiberwise_equiv_of_is_equiv_total [H : is_equiv (total f)] : is_fiberwise_equiv f := begin intro a, apply is_equiv_of_is_contr_fun, intro q, apply @is_contr_equiv_closed _ _ (fiber_total_equiv f q) end end is_equiv namespace equiv open is_equiv variables {A B C : Type} definition equiv_mk_eq {f f' : A → B} [H : is_equiv f] [H' : is_equiv f'] (p : f = f') : equiv.mk f H = equiv.mk f' H' := apd011 equiv.mk p !is_hprop.elim definition equiv_eq {f f' : A ≃ B} (p : to_fun f = to_fun f') : f = f' := by (cases f; cases f'; apply (equiv_mk_eq p)) definition equiv_eq' {f f' : A ≃ B} (p : to_fun f ~ to_fun f') : f = f' := by apply equiv_eq;apply eq_of_homotopy p definition trans_symm (f : A ≃ B) (g : B ≃ C) : (f ⬝e g)⁻¹ᵉ = g⁻¹ᵉ ⬝e f⁻¹ᵉ :> (C ≃ A) := equiv_eq idp definition symm_symm (f : A ≃ B) : f⁻¹ᵉ⁻¹ᵉ = f :> (A ≃ B) := equiv_eq idp protected definition equiv.sigma_char [constructor] (A B : Type) : (A ≃ B) ≃ Σ(f : A → B), is_equiv f := begin fapply equiv.MK, {intro F, exact ⟨to_fun F, to_is_equiv F⟩}, {intro p, cases p with f H, exact (equiv.mk f H)}, {intro p, cases p, exact idp}, {intro F, cases F, exact idp}, end definition equiv_eq_char (f f' : A ≃ B) : (f = f') ≃ (to_fun f = to_fun f') := calc (f = f') ≃ (to_fun !equiv.sigma_char f = to_fun !equiv.sigma_char f') : eq_equiv_fn_eq (to_fun !equiv.sigma_char) ... ≃ ((to_fun !equiv.sigma_char f).1 = (to_fun !equiv.sigma_char f').1 ) : equiv_subtype ... ≃ (to_fun f = to_fun f') : equiv.refl definition is_equiv_ap_to_fun (f f' : A ≃ B) : is_equiv (ap to_fun : f = f' → to_fun f = to_fun f') := begin fapply adjointify, {intro p, cases f with f H, cases f' with f' H', cases p, apply ap (mk f'), apply is_hprop.elim}, {intro p, cases f with f H, cases f' with f' H', cases p, apply @concat _ _ (ap to_fun (ap (equiv.mk f') (is_hprop.elim H H'))), {apply idp}, generalize is_hprop.elim H H', intro q, cases q, apply idp}, {intro p, cases p, cases f with f H, apply ap (ap (equiv.mk f)), apply is_hset.elim} end definition equiv_pathover {A : Type} {a a' : A} (p : a = a') {B : A → Type} {C : A → Type} (f : B a ≃ C a) (g : B a' ≃ C a') (r : Π(b : B a) (b' : B a') (q : b =[p] b'), f b =[p] g b') : f =[p] g := begin fapply pathover_of_fn_pathover_fn, { intro a, apply equiv.sigma_char}, { fapply sigma_pathover, esimp, apply arrow_pathover, exact r, apply is_hprop.elimo} end end equiv
6418378dc615cdd220cad6878f924326e8eb84b9
7565ffb53cc64430691ce89265da0f944ee43051
/hott/homotopy/homotopy_group.hlean
3c56158d2e572e82de9cd3800ac1f3d710f4812f
[ "Apache-2.0" ]
permissive
EgbertRijke/lean2
cacddba3d150f8b38688e044960a208bf851f90e
519dcee739fbca5a4ab77d66db7652097b4604cd
refs/heads/master
1,606,936,954,854
1,498,836,083,000
1,498,910,882,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
12,535
hlean
/- Copyright (c) 2016 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Clive Newstead -/ import .LES_of_homotopy_groups .sphere .complex_hopf open eq is_trunc trunc_index pointed algebra trunc nat is_conn fiber pointed unit group namespace is_trunc -- Lemma 8.3.1 theorem trivial_homotopy_group_of_is_trunc (A : Type*) {n k : ℕ} [is_trunc n A] (H : n < k) : is_contr (π[k] A) := begin apply is_trunc_trunc_of_is_trunc, apply is_contr_loop_of_is_trunc, apply @is_trunc_of_le A n _, apply trunc_index.le_of_succ_le_succ, rewrite [succ_sub_two_succ k], exact of_nat_le_of_nat H, end theorem trivial_ghomotopy_group_of_is_trunc (A : Type*) (n k : ℕ) [is_trunc n A] (H : n ≤ k) : is_contr (πg[k+1] A) := trivial_homotopy_group_of_is_trunc A (lt_succ_of_le H) -- Lemma 8.3.2 theorem trivial_homotopy_group_of_is_conn (A : Type*) {k n : ℕ} (H : k ≤ n) [is_conn n A] : is_contr (π[k] A) := begin have H3 : is_contr (ptrunc k A), from is_conn_of_le A (of_nat_le_of_nat H), have H4 : is_contr (Ω[k](ptrunc k A)), from !is_trunc_loop_of_is_trunc, apply is_trunc_equiv_closed_rev, { apply equiv_of_pequiv (homotopy_group_pequiv_loop_ptrunc k A)} end -- Corollary 8.3.3 section open sphere sphere.ops sphere_index theorem homotopy_group_sphere_le (n k : ℕ) (H : k < n) : is_contr (π[k] (S* n)) := begin cases n with n, { exfalso, apply not_lt_zero, exact H}, { have H2 : k ≤ n, from le_of_lt_succ H, apply @(trivial_homotopy_group_of_is_conn _ H2) } end end theorem is_contr_HG_fiber_of_is_connected {A B : Type*} (k n : ℕ) (f : A →* B) [H : is_conn_fun n f] (H2 : k ≤ n) : is_contr (π[k] (pfiber f)) := @(trivial_homotopy_group_of_is_conn (pfiber f) H2) (H pt) /- Corollaries of the LES of homotopy groups -/ local attribute ab_group.to_group [coercion] local attribute is_equiv_tinverse [instance] open prod chain_complex group fin equiv function is_equiv lift /- Because of the construction of the LES this proof only gives us this result when A and B live in the same universe (because Lean doesn't have universe cumulativity). However, below we also proof that it holds for A and B in arbitrary universes. -/ theorem is_equiv_π_of_is_connected'.{u} {A B : pType.{u}} {n k : ℕ} (f : A →* B) (H2 : k ≤ n) [H : is_conn_fun n f] : is_equiv (π→[k] f) := begin cases k with k, { /- k = 0 -/ change (is_equiv (trunc_functor 0 f)), apply is_equiv_trunc_functor_of_is_conn_fun, refine is_conn_fun_of_le f (zero_le_of_nat n)}, { /- k > 0 -/ have H2' : k ≤ n, from le.trans !self_le_succ H2, exact LES_is_equiv_of_trivial f (succ k) 0 (@is_contr_HG_fiber_of_is_connected A B k n f H H2') (@is_contr_HG_fiber_of_is_connected A B (succ k) n f H H2) }, end theorem is_equiv_π_of_is_connected.{u v} {A : pType.{u}} {B : pType.{v}} {n k : ℕ} (f : A →* B) (H2 : k ≤ n) [H : is_conn_fun n f] : is_equiv (π→[k] f) := begin have π→[k] pdown.{v u} ∘* π→[k] (plift_functor f) ∘* π→[k] pup.{u v} ~* π→[k] f, begin refine pwhisker_left _ !homotopy_group_functor_compose⁻¹* ⬝* _, refine !homotopy_group_functor_compose⁻¹* ⬝* _, apply homotopy_group_functor_phomotopy, apply plift_functor_phomotopy end, have π→[k] pdown.{v u} ∘ π→[k] (plift_functor f) ∘ π→[k] pup.{u v} ~ π→[k] f, from this, apply is_equiv.homotopy_closed, rotate 1, { exact this}, { do 2 apply is_equiv_compose, { apply is_equiv_homotopy_group_functor, apply to_is_equiv !equiv_lift}, { refine @(is_equiv_π_of_is_connected' _ H2) _, apply is_conn_fun_lift_functor}, { apply is_equiv_homotopy_group_functor, apply to_is_equiv !equiv_lift⁻¹ᵉ}} end definition π_equiv_π_of_is_connected {A B : Type*} {n k : ℕ} (f : A →* B) (H2 : k ≤ n) [H : is_conn_fun n f] : π[k] A ≃* π[k] B := pequiv_of_pmap (π→[k] f) (is_equiv_π_of_is_connected f H2) -- TODO: prove this for A and B in different universe levels theorem is_surjective_π_of_is_connected.{u} {A B : pType.{u}} (n : ℕ) (f : A →* B) [H : is_conn_fun n f] : is_surjective (π→[n + 1] f) := @is_surjective_of_trivial _ (LES_of_homotopy_groups f) _ (is_exact_LES_of_homotopy_groups f (n, 2)) (@is_contr_HG_fiber_of_is_connected A B n n f H !le.refl) /- Theorem 8.8.3: Whitehead's principle and its corollaries -/ definition whitehead_principle (n : ℕ₋₂) {A B : Type} [HA : is_trunc n A] [HB : is_trunc n B] (f : A → B) (H' : is_equiv (trunc_functor 0 f)) (H : Πa k, is_equiv (π→[k + 1] (pmap_of_map f a))) : is_equiv f := begin revert A B HA HB f H' H, induction n with n IH: intros, { apply is_equiv_of_is_contr }, have Πa, is_equiv (Ω→ (pmap_of_map f a)), begin intro a, apply IH, do 2 (esimp; exact _), { rexact H a 0}, intro p k, have is_equiv (π→[k + 1] (Ω→(pmap_of_map f a))), from is_equiv_homotopy_group_functor_ap1 (k+1) (pmap_of_map f a), have Π(b : A) (p : a = b), is_equiv (pmap.to_fun (π→[k + 1] (pmap_of_map (ap f) p))), begin intro b p, induction p, apply is_equiv.homotopy_closed, exact this, refine homotopy_group_functor_phomotopy _ _, apply ap1_pmap_of_map end, have is_equiv (homotopy_group_pequiv _ (pequiv_of_eq_pt (!idp_con⁻¹ : ap f p = Ω→ (pmap_of_map f a) p)) ∘ pmap.to_fun (π→[k + 1] (pmap_of_map (ap f) p))), begin apply is_equiv_compose, exact this a p, end, apply is_equiv.homotopy_closed, exact this, refine !homotopy_group_functor_compose⁻¹* ⬝* _, apply homotopy_group_functor_phomotopy, fapply phomotopy.mk, { esimp, intro q, refine !idp_con⁻¹}, { esimp, refine !idp_con⁻¹}, end, apply is_equiv_of_is_equiv_ap1_of_is_equiv_trunc end definition whitehead_principle_pointed (n : ℕ₋₂) {A B : Type*} [HA : is_trunc n A] [HB : is_trunc n B] [is_conn 0 A] (f : A →* B) (H : Πk, is_equiv (π→[k] f)) : is_equiv f := begin apply whitehead_principle n, rexact H 0, intro a k, revert a, apply is_conn.elim -1, have is_equiv (π→[k + 1] (pointed_eta_pequiv B ⬝e* (pequiv_of_eq_pt (respect_pt f))⁻¹ᵉ*) ∘* π→[k + 1] f ∘* π→[k + 1] (pointed_eta_pequiv A)⁻¹ᵉ*), begin apply is_equiv_compose (π→[k + 1] (pointed_eta_pequiv B ⬝e* (pequiv_of_eq_pt (respect_pt f))⁻¹ᵉ*)), apply is_equiv_compose (π→[k + 1] f), all_goals apply is_equiv_homotopy_group_functor, end, refine @(is_equiv.homotopy_closed _) _ this _, apply to_homotopy, refine pwhisker_left _ !homotopy_group_functor_compose⁻¹* ⬝* _, refine !homotopy_group_functor_compose⁻¹* ⬝* _, apply homotopy_group_functor_phomotopy, apply phomotopy_pmap_of_map end open pointed.ops definition is_contr_of_trivial_homotopy (n : ℕ₋₂) (A : Type) [is_trunc n A] [is_conn 0 A] (H : Πk a, is_contr (π[k] (pointed.MK A a))) : is_contr A := begin fapply is_trunc_is_equiv_closed_rev, { exact λa, ⋆}, apply whitehead_principle n, { apply is_equiv_trunc_functor_of_is_conn_fun, apply is_conn_fun_to_unit_of_is_conn}, intro a k, apply @is_equiv_of_is_contr, refine trivial_homotopy_group_of_is_trunc _ !zero_lt_succ, end definition is_contr_of_trivial_homotopy_nat (n : ℕ) (A : Type) [is_trunc n A] [is_conn 0 A] (H : Πk a, k ≤ n → is_contr (π[k] (pointed.MK A a))) : is_contr A := begin apply is_contr_of_trivial_homotopy n, intro k a, apply @lt_ge_by_cases _ _ n k, { intro H', exact trivial_homotopy_group_of_is_trunc _ H'}, { intro H', exact H k a H'} end definition is_contr_of_trivial_homotopy_pointed (n : ℕ₋₂) (A : Type*) [is_trunc n A] (H : Πk, is_contr (π[k] A)) : is_contr A := begin have is_conn 0 A, proof H 0 qed, fapply is_contr_of_trivial_homotopy n A, intro k, apply is_conn.elim -1, cases A with A a, exact H k end definition is_contr_of_trivial_homotopy_nat_pointed (n : ℕ) (A : Type*) [is_trunc n A] (H : Πk, k ≤ n → is_contr (π[k] A)) : is_contr A := begin have is_conn 0 A, proof H 0 !zero_le qed, fapply is_contr_of_trivial_homotopy_nat n A, intro k a H', revert a, apply is_conn.elim -1, cases A with A a, exact H k H' end definition ab_group_homotopy_group_of_is_conn (n : ℕ) (A : Type*) [H : is_conn 1 A] : ab_group (π[n] A) := begin have is_conn 0 A, from !is_conn_of_is_conn_succ, cases n with n, { unfold [homotopy_group, ptrunc], apply ab_group_of_is_contr }, cases n with n, { unfold [homotopy_group, ptrunc], apply ab_group_of_is_contr }, exact ab_group_homotopy_group (n+2) A end definition is_contr_of_trivial_homotopy' (n : ℕ₋₂) (A : Type) [is_trunc n A] [is_conn -1 A] (H : Πk a, is_contr (π[k] (pointed.MK A a))) : is_contr A := begin assert aa : trunc -1 A, { apply center }, assert H3 : is_conn 0 A, { induction aa with a, exact H 0 a }, exact is_contr_of_trivial_homotopy n A H end definition is_conn_of_trivial_homotopy (n : ℕ₋₂) (m : ℕ) (A : Type) [is_trunc n A] [is_conn 0 A] (H : Π(k : ℕ) a, k ≤ m → is_contr (π[k] (pointed.MK A a))) : is_conn m A := begin apply is_contr_of_trivial_homotopy_nat m (trunc m A), intro k a H2, induction a with a, apply is_trunc_equiv_closed_rev, exact equiv_of_pequiv (homotopy_group_ptrunc_of_le H2 (pointed.MK A a)), exact H k a H2 end definition is_conn_of_trivial_homotopy_pointed (n : ℕ₋₂) (m : ℕ) (A : Type*) [is_trunc n A] (H : Π(k : ℕ), k ≤ m → is_contr (π[k] A)) : is_conn m A := begin have is_conn 0 A, proof H 0 !zero_le qed, apply is_conn_of_trivial_homotopy n m A, intro k a H2, revert a, apply is_conn.elim -1, cases A with A a, exact H k H2 end definition is_conn_fun_of_equiv_on_homotopy_groups.{u} (n : ℕ) {A B : Type.{u}} (f : A → B) [is_equiv (trunc_functor 0 f)] (H1 : Πa k, k ≤ n → is_equiv (homotopy_group_functor k (pmap_of_map f a))) (H2 : Πa, is_surjective (homotopy_group_functor (succ n) (pmap_of_map f a))) : is_conn_fun n f := have H2' : Πa k, k ≤ n → is_surjective (homotopy_group_functor (succ k) (pmap_of_map f a)), begin intro a k H, cases H with n' H', { apply H2}, { apply is_surjective_of_is_equiv, apply H1, exact succ_le_succ H'} end, have H3 : Πa, is_contr (ptrunc n (pfiber (pmap_of_map f a))), begin intro a, apply is_contr_of_trivial_homotopy_nat_pointed n, { intro k H, apply is_trunc_equiv_closed_rev, exact homotopy_group_ptrunc_of_le H _, rexact @is_contr_of_is_embedding_of_is_surjective +3ℕ (LES_of_homotopy_groups (pmap_of_map f a)) (k, 0) (is_exact_LES_of_homotopy_groups _ _) proof @(is_embedding_of_is_equiv _) (H1 a k H) qed proof (H2' a k H) qed} end, show Πb, is_contr (trunc n (fiber f b)), begin intro b, note p := right_inv (trunc_functor 0 f) (tr b), revert p, induction (trunc_functor 0 f)⁻¹ (tr b), esimp, intro p, induction !tr_eq_tr_equiv p with q, rewrite -q, exact H3 a end end is_trunc open is_trunc function /- applications to infty-connected types and maps -/ namespace is_conn definition is_conn_fun_inf_of_equiv_on_homotopy_groups.{u} {A B : Type.{u}} (f : A → B) [is_equiv (trunc_functor 0 f)] (H1 : Πa k, is_equiv (homotopy_group_functor k (pmap_of_map f a))) : is_conn_fun_inf f := begin apply is_conn_fun_inf.mk_nat, intro n, apply is_conn_fun_of_equiv_on_homotopy_groups, { intro a k H, exact H1 a k}, { intro a, apply is_surjective_of_is_equiv} end definition is_equiv_trunc_functor_of_is_conn_fun_inf.{u} (n : ℕ₋₂) {A B : Type.{u}} (f : A → B) [is_conn_fun_inf f] : is_equiv (trunc_functor n f) := _ definition is_equiv_homotopy_group_functor_of_is_conn_fun_inf.{u} {A B : pType.{u}} (f : A →* B) [is_conn_fun_inf f] (a : A) (k : ℕ) : is_equiv (homotopy_group_functor k f) := is_equiv_π_of_is_connected f (le.refl k) end is_conn
2c872e0b3b99e34ff3ef12017af4ab4a0f66fea5
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/08_Building_Theories_and_Proofs.org.19.lean
ae14473f2e7f58991989868f4a578cddb547ab79
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
190
lean
import standard set_option pp.implicit true set_option pp.universes true set_option pp.notation false set_option pp.coercions true set_option pp.numerals false set_option pp.full_names true
9169715258087f77f3524367a80fd02c4a4e4321
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/bor_lazy.lean
d3350a6f8a9ee54356075ff3e7458d31b3591c48
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
84
lean
open bool vm_eval (timeit "branch1:" (λ x, tt)) || (timeit "branch2:" (λ x, tt))
c10dc94c3e2e609c42bb5711a14f47dd008300d5
969dbdfed67fda40a6f5a2b4f8c4a3c7dc01e0fb
/src/measure_theory/lp_space.lean
6c709420a4f52ae21ac56616cab7a94ba7f0050b
[ "Apache-2.0" ]
permissive
SAAluthwela/mathlib
62044349d72dd63983a8500214736aa7779634d3
83a4b8b990907291421de54a78988c024dc8a552
refs/heads/master
1,679,433,873,417
1,615,998,031,000
1,615,998,031,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
71,221
lean
/- Copyright (c) 2020 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne, Sébastien Gouëzel -/ import measure_theory.ess_sup import measure_theory.ae_eq_fun import analysis.mean_inequalities /-! # ℒp space and Lp space This file describes properties of almost everywhere measurable functions with finite seminorm, denoted by `snorm f p μ` and defined for `p:ℝ≥0∞` as `0` if `p=0`, `(∫ ∥f a∥^p ∂μ) ^ (1/p)` for `0 < p < ∞` and `ess_sup ∥f∥ μ` for `p=∞`. The Prop-valued `mem_ℒp f p μ` states that a function `f : α → E` has finite seminorm. The space `Lp α E p μ` is the subtype of elements of `α →ₘ[μ] E` (see ae_eq_fun) such that `snorm f p μ` is finite. For `1 ≤ p`, `snorm` defines a norm and `Lp` is a complete metric space. ## Main definitions * `snorm' f p μ` : `(∫ ∥f a∥^p ∂μ) ^ (1/p)` for `f : α → F` and `p : ℝ`, where `α` is a measurable space and `F` is a normed group. * `snorm_ess_sup f μ` : seminorm in `ℒ∞`, equal to the essential supremum `ess_sup ∥f∥ μ`. * `snorm f p μ` : for `p : ℝ≥0∞`, seminorm in `ℒp`, equal to `0` for `p=0`, to `snorm' f p μ` for `0 < p < ∞` and to `snorm_ess_sup f μ` for `p = ∞`. * `mem_ℒp f p μ` : property that the function `f` is almost everywhere measurable and has finite p-seminorm for measure `μ` (`snorm f p μ < ∞`) * `Lp E p μ` : elements of `α →ₘ[μ] E` (see ae_eq_fun) such that `snorm f p μ` is finite. Defined as an `add_subgroup` of `α →ₘ[μ] E`. Lipschitz functions vanishing at zero act by composition on `Lp`. We define this action, and prove that it is continuous. In particular, * `continuous_linear_map.comp_Lp` defines the action on `Lp` of a continuous linear map. * `Lp.pos_part` is the positive part of an `Lp` function. * `Lp.neg_part` is the negative part of an `Lp` function. ## Implementation Since `Lp` is defined as an `add_subgroup`, dot notation does not work. Use `Lp.measurable f` to say that the coercion of `f` to a genuine function is measurable, instead of the non-working `f.measurable`. To prove that two `Lp` elements are equal, it suffices to show that their coercions to functions coincide almost everywhere (this is registered as an `ext` rule). This can often be done using `filter_upwards`. For instance, a proof from first principles that `f + (g + h) = (f + g) + h` could read (in the `Lp` namespace) ``` example (f g h : Lp E p μ) : (f + g) + h = f + (g + h) := begin ext1, filter_upwards [coe_fn_add (f + g) h, coe_fn_add f g, coe_fn_add f (g + h), coe_fn_add g h], assume a ha1 ha2 ha3 ha4, simp only [ha1, ha2, ha3, ha4, add_assoc], end ``` The lemma `coe_fn_add` states that the coercion of `f + g` coincides almost everywhere with the sum of the coercions of `f` and `g`. All such lemmas use `coe_fn` in their name, to distinguish the function coercion from the coercion to almost everywhere defined functions. -/ noncomputable theory open topological_space measure_theory filter open_locale nnreal ennreal big_operators topological_space lemma fact_one_le_one_ennreal : fact ((1 : ℝ≥0∞) ≤ 1) := le_refl _ lemma fact_one_le_two_ennreal : fact ((1 : ℝ≥0∞) ≤ 2) := ennreal.coe_le_coe.2 (show (1 : ℝ≥0) ≤ 2, by norm_num) lemma fact_one_le_top_ennreal : fact ((1 : ℝ≥0∞) ≤ ∞) := le_top local attribute [instance] fact_one_le_one_ennreal fact_one_le_two_ennreal fact_one_le_top_ennreal variables {α E F G : Type*} [measurable_space α] {p : ℝ≥0∞} {q : ℝ} {μ : measure α} [measurable_space E] [normed_group E] [normed_group F] [normed_group G] namespace measure_theory section ℒp /-! ### ℒp seminorm We define the ℒp seminorm, denoted by `snorm f p μ`. For real `p`, it is given by an integral formula (for which we use the notation `snorm' f p μ`), and for `p = ∞` it is the essential supremum (for which we use the notation `snorm_ess_sup f μ`). We also define a predicate `mem_ℒp f p μ`, requesting that a function is almost everywhere measurable and has finite `snorm f p μ`. This paragraph is devoted to the basic properties of these definitions. It is constructed as follows: for a given property, we prove it for `snorm'` and `snorm_ess_sup` when it makes sense, deduce it for `snorm`, and translate it in terms of `mem_ℒp`. -/ section ℒp_space_definition /-- `(∫ ∥f a∥^q ∂μ) ^ (1/q)`, which is a seminorm on the space of measurable functions for which this quantity is finite -/ def snorm' (f : α → F) (q : ℝ) (μ : measure α) : ℝ≥0∞ := (∫⁻ a, (nnnorm (f a))^q ∂μ) ^ (1/q) /-- seminorm for `ℒ∞`, equal to the essential supremum of `∥f∥`. -/ def snorm_ess_sup (f : α → F) (μ : measure α) := ess_sup (λ x, (nnnorm (f x) : ℝ≥0∞)) μ /-- `ℒp` seminorm, equal to `0` for `p=0`, to `(∫ ∥f a∥^p ∂μ) ^ (1/p)` for `0 < p < ∞` and to `ess_sup ∥f∥ μ` for `p = ∞`. -/ def snorm (f : α → F) (p : ℝ≥0∞) (μ : measure α) : ℝ≥0∞ := if p = 0 then 0 else (if p = ∞ then snorm_ess_sup f μ else snorm' f (ennreal.to_real p) μ) lemma snorm_eq_snorm' (hp_ne_zero : p ≠ 0) (hp_ne_top : p ≠ ∞) {f : α → F} : snorm f p μ = snorm' f (ennreal.to_real p) μ := by simp [snorm, hp_ne_zero, hp_ne_top] @[simp] lemma snorm_exponent_top {f : α → F} : snorm f ∞ μ = snorm_ess_sup f μ := by simp [snorm] /-- The property that `f:α→E` is ae_measurable and `(∫ ∥f a∥^p ∂μ)^(1/p)` is finite if `p < ∞`, or `ess_sup f < ∞` if `p = ∞`. -/ def mem_ℒp (f : α → E) (p : ℝ≥0∞) (μ : measure α) : Prop := ae_measurable f μ ∧ snorm f p μ < ∞ lemma mem_ℒp.ae_measurable {f : α → E} {p : ℝ≥0∞} {μ : measure α} (h : mem_ℒp f p μ) : ae_measurable f μ := h.1 lemma lintegral_rpow_nnnorm_eq_rpow_snorm' {f : α → F} (hq0_lt : 0 < q) : ∫⁻ a, (nnnorm (f a)) ^ q ∂μ = (snorm' f q μ) ^ q := begin rw [snorm', ←ennreal.rpow_mul, one_div, inv_mul_cancel, ennreal.rpow_one], exact (ne_of_lt hq0_lt).symm, end end ℒp_space_definition section top lemma mem_ℒp.snorm_lt_top {f : α → E} (hfp : mem_ℒp f p μ) : snorm f p μ < ∞ := hfp.2 lemma mem_ℒp.snorm_ne_top {f : α → E} (hfp : mem_ℒp f p μ) : snorm f p μ ≠ ∞ := ne_of_lt (hfp.2) lemma lintegral_rpow_nnnorm_lt_top_of_snorm'_lt_top {f : α → F} (hq0_lt : 0 < q) (hfq : snorm' f q μ < ∞) : ∫⁻ a, (nnnorm (f a)) ^ q ∂μ < ∞ := begin rw lintegral_rpow_nnnorm_eq_rpow_snorm' hq0_lt, exact ennreal.rpow_lt_top_of_nonneg (le_of_lt hq0_lt) (ne_of_lt hfq), end end top section zero @[simp] lemma snorm'_exponent_zero {f : α → F} : snorm' f 0 μ = 1 := by rw [snorm', div_zero, ennreal.rpow_zero] @[simp] lemma snorm_exponent_zero {f : α → F} : snorm f 0 μ = 0 := by simp [snorm] lemma mem_ℒp_zero_iff_ae_measurable {f : α → E} : mem_ℒp f 0 μ ↔ ae_measurable f μ := by simp [mem_ℒp, snorm_exponent_zero] @[simp] lemma snorm'_zero (hp0_lt : 0 < q) : snorm' (0 : α → F) q μ = 0 := by simp [snorm', hp0_lt] @[simp] lemma snorm'_zero' (hq0_ne : q ≠ 0) (hμ : μ ≠ 0) : snorm' (0 : α → F) q μ = 0 := begin cases le_or_lt 0 q with hq0 hq_neg, { exact snorm'_zero (lt_of_le_of_ne hq0 hq0_ne.symm), }, { simp [snorm', ennreal.rpow_eq_zero_iff, hμ, hq_neg], }, end @[simp] lemma snorm_ess_sup_zero : snorm_ess_sup (0 : α → F) μ = 0 := begin simp_rw [snorm_ess_sup, pi.zero_apply, nnnorm_zero, ennreal.coe_zero, ←ennreal.bot_eq_zero], exact ess_sup_const_bot, end @[simp] lemma snorm_zero : snorm (0 : α → F) p μ = 0 := begin by_cases h0 : p = 0, { simp [h0], }, by_cases h_top : p = ∞, { simp only [h_top, snorm_exponent_top, snorm_ess_sup_zero], }, rw ←ne.def at h0, simp [snorm_eq_snorm' h0 h_top, ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) h0.symm, h_top⟩], end lemma zero_mem_ℒp : mem_ℒp (0 : α → E) p μ := ⟨measurable_zero.ae_measurable, by { rw snorm_zero, exact ennreal.coe_lt_top, } ⟩ lemma snorm'_measure_zero_of_pos {f : α → F} (hq_pos : 0 < q) : snorm' f q 0 = 0 := by simp [snorm', hq_pos] lemma snorm'_measure_zero_of_exponent_zero {f : α → F} : snorm' f 0 0 = 1 := by simp [snorm'] lemma snorm'_measure_zero_of_neg {f : α → F} (hq_neg : q < 0) : snorm' f q 0 = ∞ := by simp [snorm', hq_neg] @[simp] lemma snorm_ess_sup_measure_zero {f : α → F} : snorm_ess_sup f 0 = 0 := by simp [snorm_ess_sup] @[simp] lemma snorm_measure_zero {f : α → F} : snorm f p 0 = 0 := begin by_cases h0 : p = 0, { simp [h0], }, by_cases h_top : p = ∞, { simp [h_top], }, rw ←ne.def at h0, simp [snorm_eq_snorm' h0 h_top, snorm', ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) h0.symm, h_top⟩], end end zero section const lemma snorm'_const (c : F) (hq_pos : 0 < q) : snorm' (λ x : α , c) q μ = (nnnorm c : ℝ≥0∞) * (μ set.univ) ^ (1/q) := begin rw [snorm', lintegral_const, @ennreal.mul_rpow_of_nonneg _ _ (1/q) (by simp [hq_pos.le])], congr, rw ←ennreal.rpow_mul, suffices hq_cancel : q * (1/q) = 1, by rw [hq_cancel, ennreal.rpow_one], rw [one_div, mul_inv_cancel (ne_of_lt hq_pos).symm], end lemma snorm'_const' [finite_measure μ] (c : F) (hc_ne_zero : c ≠ 0) (hq_ne_zero : q ≠ 0) : snorm' (λ x : α , c) q μ = (nnnorm c : ℝ≥0∞) * (μ set.univ) ^ (1/q) := begin rw [snorm', lintegral_const, ennreal.mul_rpow_of_ne_top _ (measure_ne_top μ set.univ)], { congr, rw ←ennreal.rpow_mul, suffices hp_cancel : q * (1/q) = 1, by rw [hp_cancel, ennreal.rpow_one], rw [one_div, mul_inv_cancel hq_ne_zero], }, { rw [ne.def, ennreal.rpow_eq_top_iff, auto.not_or_eq, auto.not_and_eq, auto.not_and_eq], split, { left, rwa [ennreal.coe_eq_zero, nnnorm_eq_zero], }, { exact or.inl ennreal.coe_ne_top, }, }, end lemma snorm_ess_sup_const (c : F) (hμ : μ ≠ 0) : snorm_ess_sup (λ x : α, c) μ = (nnnorm c : ℝ≥0∞) := by rw [snorm_ess_sup, ess_sup_const _ hμ] lemma snorm'_const_of_probability_measure (c : F) (hq_pos : 0 < q) [probability_measure μ] : snorm' (λ x : α , c) q μ = (nnnorm c : ℝ≥0∞) := by simp [snorm'_const c hq_pos, measure_univ] lemma snorm_const (c : F) (h0 : p ≠ 0) (hμ : μ ≠ 0) : snorm (λ x : α , c) p μ = (nnnorm c : ℝ≥0∞) * (μ set.univ) ^ (1/(ennreal.to_real p)) := begin by_cases h_top : p = ∞, { simp [h_top, snorm_ess_sup_const c hμ], }, simp [snorm_eq_snorm' h0 h_top, snorm'_const, ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) h0.symm, h_top⟩], end lemma snorm_const' (c : F) (h0 : p ≠ 0) (h_top: p ≠ ∞) : snorm (λ x : α , c) p μ = (nnnorm c : ℝ≥0∞) * (μ set.univ) ^ (1/(ennreal.to_real p)) := begin simp [snorm_eq_snorm' h0 h_top, snorm'_const, ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) h0.symm, h_top⟩], end lemma mem_ℒp_const (c : E) [finite_measure μ] : mem_ℒp (λ a:α, c) p μ := begin refine ⟨measurable_const.ae_measurable, _⟩, by_cases h0 : p = 0, { simp [h0], }, by_cases hμ : μ = 0, { simp [hμ], }, rw snorm_const c h0 hμ, refine ennreal.mul_lt_top ennreal.coe_lt_top _, refine ennreal.rpow_lt_top_of_nonneg _ (measure_ne_top μ set.univ), simp, end end const lemma snorm'_mono_ae {f : α → F} {g : α → G} (hq : 0 ≤ q) (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ ∥g x∥) : snorm' f q μ ≤ snorm' g q μ := begin rw [snorm'], refine ennreal.rpow_le_rpow _ (one_div_nonneg.2 hq), refine lintegral_mono_ae (h.mono $ λ x hx, _), exact ennreal.rpow_le_rpow (ennreal.coe_le_coe.2 hx) hq end lemma snorm'_congr_norm_ae {f g : α → F} (hfg : ∀ᵐ x ∂μ, ∥f x∥ = ∥g x∥) : snorm' f q μ = snorm' g q μ := begin have : (λ x, (nnnorm (f x) ^ q : ℝ≥0∞)) =ᵐ[μ] (λ x, nnnorm (g x) ^ q), from hfg.mono (λ x hx, by { simp only [← coe_nnnorm, nnreal.coe_eq] at hx, simp [hx] }), simp only [snorm', lintegral_congr_ae this] end lemma snorm'_congr_ae {f g : α → F} (hfg : f =ᵐ[μ] g) : snorm' f q μ = snorm' g q μ := snorm'_congr_norm_ae (hfg.fun_comp _) lemma snorm_ess_sup_congr_ae {f g : α → F} (hfg : f =ᵐ[μ] g) : snorm_ess_sup f μ = snorm_ess_sup g μ := ess_sup_congr_ae (hfg.fun_comp (coe ∘ nnnorm)) lemma snorm_mono_ae {f : α → F} {g : α → G} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ ∥g x∥) : snorm f p μ ≤ snorm g p μ := begin simp only [snorm], split_ifs, { exact le_rfl }, { refine ess_sup_mono_ae (h.mono $ λ x hx, _), exact_mod_cast hx }, { exact snorm'_mono_ae ennreal.to_real_nonneg h } end lemma snorm_congr_norm_ae {f : α → F} {g : α → G} (hfg : ∀ᵐ x ∂μ, ∥f x∥ = ∥g x∥) : snorm f p μ = snorm g p μ := le_antisymm (snorm_mono_ae $ eventually_eq.le hfg) (snorm_mono_ae $ (eventually_eq.symm hfg).le) @[simp] lemma snorm'_norm {f : α → F} : snorm' (λ a, ∥f a∥) q μ = snorm' f q μ := by simp [snorm'] @[simp] lemma snorm_norm (f : α → F) : snorm (λ x, ∥f x∥) p μ = snorm f p μ := snorm_congr_norm_ae $ eventually_of_forall $ λ x, norm_norm _ lemma snorm'_norm_rpow (f : α → F) (p q : ℝ) (hq_pos : 0 < q) : snorm' (λ x, ∥f x∥ ^ q) p μ = (snorm' f (p * q) μ) ^ q := begin simp_rw snorm', rw [← ennreal.rpow_mul, ←one_div_mul_one_div], simp_rw one_div, rw [mul_assoc, inv_mul_cancel hq_pos.ne.symm, mul_one], congr, ext1 x, simp_rw ← of_real_norm_eq_coe_nnnorm, rw [real.norm_eq_abs, abs_eq_self.mpr (real.rpow_nonneg_of_nonneg (norm_nonneg _) _), mul_comm, ← ennreal.of_real_rpow_of_nonneg (norm_nonneg _) hq_pos.le, ennreal.rpow_mul], end lemma snorm_norm_rpow (f : α → F) (hq_pos : 0 < q) : snorm (λ x, ∥f x∥ ^ q) p μ = (snorm f (p * ennreal.of_real q) μ) ^ q := begin by_cases h0 : p = 0, { simp [h0, ennreal.zero_rpow_of_pos hq_pos], }, by_cases hp_top : p = ∞, { simp only [hp_top, snorm_exponent_top, ennreal.top_mul, hq_pos.not_le, ennreal.of_real_eq_zero, if_false, snorm_exponent_top, snorm_ess_sup], have h_rpow : ess_sup (λ (x : α), (nnnorm (∥f x∥ ^ q) : ℝ≥0∞)) μ = ess_sup (λ (x : α), (↑(nnnorm (f x))) ^ q) μ, { congr, ext1 x, nth_rewrite 1 ← nnnorm_norm, rw [ennreal.coe_rpow_of_nonneg _ hq_pos.le, ennreal.coe_eq_coe], ext, push_cast, rw real.norm_rpow_of_nonneg (norm_nonneg _), }, rw h_rpow, have h_rpow_mono := ennreal.rpow_left_strict_mono_of_pos hq_pos, have h_rpow_surj := (ennreal.rpow_left_bijective hq_pos.ne.symm).2, let iso := h_rpow_mono.order_iso_of_surjective _ h_rpow_surj, exact (iso.ess_sup_apply (λ x, ((nnnorm (f x)) : ℝ≥0∞)) μ).symm, }, rw [snorm_eq_snorm' h0 hp_top, snorm_eq_snorm' _ _], swap, { refine mul_ne_zero h0 _, rwa [ne.def, ennreal.of_real_eq_zero, not_le], }, swap, { exact ennreal.mul_ne_top hp_top ennreal.of_real_ne_top, }, rw [ennreal.to_real_mul, ennreal.to_real_of_real hq_pos.le], exact snorm'_norm_rpow f p.to_real q hq_pos, end lemma snorm_congr_ae {f g : α → F} (hfg : f =ᵐ[μ] g) : snorm f p μ = snorm g p μ := snorm_congr_norm_ae $ hfg.mono (λ x hx, hx ▸ rfl) lemma mem_ℒp_congr_ae {f g : α → E} (hfg : f =ᵐ[μ] g) : mem_ℒp f p μ ↔ mem_ℒp g p μ := by simp only [mem_ℒp, snorm_congr_ae hfg, ae_measurable_congr hfg] lemma mem_ℒp.ae_eq {f g : α → E} (hfg : f =ᵐ[μ] g) (hf_Lp : mem_ℒp f p μ) : mem_ℒp g p μ := (mem_ℒp_congr_ae hfg).1 hf_Lp lemma mem_ℒp.of_le [measurable_space F] {f : α → E} {g : α → F} (hg : mem_ℒp g p μ) (hf : ae_measurable f μ) (hfg : ∀ᵐ x ∂μ, ∥f x∥ ≤ ∥g x∥) : mem_ℒp f p μ := ⟨hf, (snorm_mono_ae hfg).trans_lt hg.snorm_lt_top⟩ section opens_measurable_space variable [opens_measurable_space E] lemma mem_ℒp.norm {f : α → E} (h : mem_ℒp f p μ) : mem_ℒp (λ x, ∥f x∥) p μ := h.of_le h.ae_measurable.norm (eventually_of_forall (λ x, by simp)) lemma snorm'_eq_zero_of_ae_zero {f : α → F} (hq0_lt : 0 < q) (hf_zero : f =ᵐ[μ] 0) : snorm' f q μ = 0 := by rw [snorm'_congr_ae hf_zero, snorm'_zero hq0_lt] lemma snorm'_eq_zero_of_ae_zero' (hq0_ne : q ≠ 0) (hμ : μ ≠ 0) {f : α → F} (hf_zero : f =ᵐ[μ] 0) : snorm' f q μ = 0 := by rw [snorm'_congr_ae hf_zero, snorm'_zero' hq0_ne hμ] lemma ae_eq_zero_of_snorm'_eq_zero {f : α → E} (hq0 : 0 ≤ q) (hf : ae_measurable f μ) (h : snorm' f q μ = 0) : f =ᵐ[μ] 0 := begin rw [snorm', ennreal.rpow_eq_zero_iff] at h, cases h, { rw lintegral_eq_zero_iff' hf.nnnorm.ennreal_coe.ennreal_rpow_const at h, refine h.left.mono (λ x hx, _), rw [pi.zero_apply, ennreal.rpow_eq_zero_iff] at hx, cases hx, { cases hx with hx _, rwa [←ennreal.coe_zero, ennreal.coe_eq_coe, nnnorm_eq_zero] at hx, }, { exact absurd hx.left ennreal.coe_ne_top, }, }, { exfalso, rw [one_div, inv_lt_zero] at h, exact hq0.not_lt h.right }, end lemma snorm'_eq_zero_iff (hq0_lt : 0 < q) {f : α → E} (hf : ae_measurable f μ) : snorm' f q μ = 0 ↔ f =ᵐ[μ] 0 := ⟨ae_eq_zero_of_snorm'_eq_zero (le_of_lt hq0_lt) hf, snorm'_eq_zero_of_ae_zero hq0_lt⟩ lemma coe_nnnorm_ae_le_snorm_ess_sup (f : α → F) (μ : measure α) : ∀ᵐ x ∂μ, (nnnorm (f x) : ℝ≥0∞) ≤ snorm_ess_sup f μ := ennreal.ae_le_ess_sup (λ x, (nnnorm (f x) : ℝ≥0∞)) @[simp] lemma snorm_ess_sup_eq_zero_iff {f : α → F} : snorm_ess_sup f μ = 0 ↔ f =ᵐ[μ] 0 := by simp [eventually_eq, snorm_ess_sup] lemma snorm_eq_zero_iff {f : α → E} (hf : ae_measurable f μ) (h0 : p ≠ 0) : snorm f p μ = 0 ↔ f =ᵐ[μ] 0 := begin by_cases h_top : p = ∞, { rw [h_top, snorm_exponent_top, snorm_ess_sup_eq_zero_iff], }, rw snorm_eq_snorm' h0 h_top, exact snorm'_eq_zero_iff (ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) h0.symm, h_top⟩) hf, end end opens_measurable_space @[simp] lemma snorm'_neg {f : α → F} : snorm' (-f) q μ = snorm' f q μ := by simp [snorm'] @[simp] lemma snorm_neg {f : α → F} : snorm (-f) p μ = snorm f p μ := begin by_cases h0 : p = 0, { simp [h0], }, by_cases h_top : p = ∞, { simp [h_top, snorm_ess_sup], }, simp [snorm_eq_snorm' h0 h_top], end section borel_space variable [borel_space E] lemma mem_ℒp.neg {f : α → E} (hf : mem_ℒp f p μ) : mem_ℒp (-f) p μ := ⟨ae_measurable.neg hf.1, by simp [hf.right]⟩ lemma snorm'_le_snorm'_mul_rpow_measure_univ {p q : ℝ} (hp0_lt : 0 < p) (hpq : p ≤ q) {f : α → E} (hf : ae_measurable f μ) : snorm' f p μ ≤ snorm' f q μ * (μ set.univ) ^ (1/p - 1/q) := begin have hq0_lt : 0 < q, from lt_of_lt_of_le hp0_lt hpq, by_cases hpq_eq : p = q, { rw [hpq_eq, sub_self, ennreal.rpow_zero, mul_one], exact le_refl _, }, have hpq : p < q, from lt_of_le_of_ne hpq hpq_eq, let g := λ a : α, (1 : ℝ≥0∞), have h_rw : ∫⁻ a, ↑(nnnorm (f a))^p ∂ μ = ∫⁻ a, (nnnorm (f a) * (g a))^p ∂ μ, from lintegral_congr (λ a, by simp), repeat {rw snorm'}, rw h_rw, let r := p * q / (q - p), have hpqr : 1/p = 1/q + 1/r, { field_simp [(ne_of_lt hp0_lt).symm, (ne_of_lt hq0_lt).symm], ring, }, calc (∫⁻ (a : α), (↑(nnnorm (f a)) * g a) ^ p ∂μ) ^ (1/p) ≤ (∫⁻ (a : α), ↑(nnnorm (f a)) ^ q ∂μ) ^ (1/q) * (∫⁻ (a : α), (g a) ^ r ∂μ) ^ (1/r) : ennreal.lintegral_Lp_mul_le_Lq_mul_Lr hp0_lt hpq hpqr μ hf.nnnorm.ennreal_coe ae_measurable_const ... = (∫⁻ (a : α), ↑(nnnorm (f a)) ^ q ∂μ) ^ (1/q) * μ set.univ ^ (1/p - 1/q) : by simp [hpqr], end lemma snorm'_le_snorm_ess_sup_mul_rpow_measure_univ (hq_pos : 0 < q) {f : α → F} : snorm' f q μ ≤ snorm_ess_sup f μ * (μ set.univ) ^ (1/q) := begin have h_le : ∫⁻ (a : α), ↑(nnnorm (f a)) ^ q ∂μ ≤ ∫⁻ (a : α), (snorm_ess_sup f μ) ^ q ∂μ, { refine lintegral_mono_ae _, have h_nnnorm_le_snorm_ess_sup := coe_nnnorm_ae_le_snorm_ess_sup f μ, refine h_nnnorm_le_snorm_ess_sup.mono (λ x hx, ennreal.rpow_le_rpow hx (le_of_lt hq_pos)), }, rw [snorm', ←ennreal.rpow_one (snorm_ess_sup f μ)], nth_rewrite 1 ←mul_inv_cancel (ne_of_lt hq_pos).symm, rw [ennreal.rpow_mul, one_div, ←@ennreal.mul_rpow_of_nonneg _ _ q⁻¹ (by simp [hq_pos.le])], refine ennreal.rpow_le_rpow _ (by simp [hq_pos.le]), rwa lintegral_const at h_le, end lemma snorm'_le_snorm'_of_exponent_le {p q : ℝ} (hp0_lt : 0 < p) (hpq : p ≤ q) (μ : measure α) [probability_measure μ] {f : α → E} (hf : ae_measurable f μ) : snorm' f p μ ≤ snorm' f q μ := begin have h_le_μ := snorm'_le_snorm'_mul_rpow_measure_univ hp0_lt hpq hf, rwa [measure_univ, ennreal.one_rpow, mul_one] at h_le_μ, end lemma snorm'_le_snorm_ess_sup (hq_pos : 0 < q) {f : α → F} [probability_measure μ] : snorm' f q μ ≤ snorm_ess_sup f μ := le_trans (snorm'_le_snorm_ess_sup_mul_rpow_measure_univ hq_pos) (le_of_eq (by simp [measure_univ])) lemma snorm_le_snorm_of_exponent_le {p q : ℝ≥0∞} (hpq : p ≤ q) [probability_measure μ] {f : α → E} (hf : ae_measurable f μ) : snorm f p μ ≤ snorm f q μ := begin by_cases hp0 : p = 0, { simp [hp0], }, rw ←ne.def at hp0, by_cases hq_top : q = ∞, { by_cases hp_top : p = ∞, { rw [hq_top, hp_top], exact le_refl _, }, { have hp_pos : 0 < p.to_real, from ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) hp0.symm, hp_top⟩, rw [snorm_eq_snorm' hp0 hp_top, hq_top, snorm_exponent_top], refine le_trans (snorm'_le_snorm_ess_sup_mul_rpow_measure_univ hp_pos) (le_of_eq _), simp [measure_univ], }, }, { have hp_top : p ≠ ∞, { by_contra hp_eq_top, push_neg at hp_eq_top, refine hq_top _, rwa [hp_eq_top, top_le_iff] at hpq, }, have hp_pos : 0 < p.to_real, from ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) hp0.symm, hp_top⟩, have hq0 : q ≠ 0, { by_contra hq_eq_zero, push_neg at hq_eq_zero, have hp_eq_zero : p = 0, from le_antisymm (by rwa hq_eq_zero at hpq) (zero_le _), rw [hp_eq_zero, ennreal.zero_to_real] at hp_pos, exact (lt_irrefl _) hp_pos, }, have hpq_real : p.to_real ≤ q.to_real, by rwa ennreal.to_real_le_to_real hp_top hq_top, rw [snorm_eq_snorm' hp0 hp_top, snorm_eq_snorm' hq0 hq_top], exact snorm'_le_snorm'_of_exponent_le hp_pos hpq_real _ hf, }, end lemma snorm'_lt_top_of_snorm'_lt_top_of_exponent_le {p q : ℝ} [finite_measure μ] {f : α → E} (hf : ae_measurable f μ) (hfq_lt_top : snorm' f q μ < ∞) (hp_nonneg : 0 ≤ p) (hpq : p ≤ q) : snorm' f p μ < ∞ := begin cases le_or_lt p 0 with hp_nonpos hp_pos, { rw le_antisymm hp_nonpos hp_nonneg, simp, }, have hq_pos : 0 < q, from lt_of_lt_of_le hp_pos hpq, calc snorm' f p μ ≤ snorm' f q μ * (μ set.univ) ^ (1/p - 1/q) : snorm'_le_snorm'_mul_rpow_measure_univ hp_pos hpq hf ... < ∞ : begin rw ennreal.mul_lt_top_iff, refine or.inl ⟨hfq_lt_top, ennreal.rpow_lt_top_of_nonneg _ (measure_ne_top μ set.univ)⟩, rwa [le_sub, sub_zero, one_div, one_div, inv_le_inv hq_pos hp_pos], end end lemma mem_ℒp.mem_ℒp_of_exponent_le {p q : ℝ≥0∞} [finite_measure μ] {f : α → E} (hfq : mem_ℒp f q μ) (hpq : p ≤ q) : mem_ℒp f p μ := begin cases hfq with hfq_m hfq_lt_top, by_cases hp0 : p = 0, { rwa [hp0, mem_ℒp_zero_iff_ae_measurable], }, rw ←ne.def at hp0, refine ⟨hfq_m, _⟩, by_cases hp_top : p = ∞, { have hq_top : q = ∞, by rwa [hp_top, top_le_iff] at hpq, rw [hp_top], rwa hq_top at hfq_lt_top, }, have hp_pos : 0 < p.to_real, from ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) hp0.symm, hp_top⟩, by_cases hq_top : q = ∞, { rw snorm_eq_snorm' hp0 hp_top, rw [hq_top, snorm_exponent_top] at hfq_lt_top, refine lt_of_le_of_lt (snorm'_le_snorm_ess_sup_mul_rpow_measure_univ hp_pos) _, refine ennreal.mul_lt_top hfq_lt_top _, exact ennreal.rpow_lt_top_of_nonneg (by simp [le_of_lt hp_pos]) (measure_ne_top μ set.univ), }, have hq0 : q ≠ 0, { by_contra hq_eq_zero, push_neg at hq_eq_zero, have hp_eq_zero : p = 0, from le_antisymm (by rwa hq_eq_zero at hpq) (zero_le _), rw [hp_eq_zero, ennreal.zero_to_real] at hp_pos, exact (lt_irrefl _) hp_pos, }, have hpq_real : p.to_real ≤ q.to_real, by rwa ennreal.to_real_le_to_real hp_top hq_top, rw snorm_eq_snorm' hp0 hp_top, rw snorm_eq_snorm' hq0 hq_top at hfq_lt_top, exact snorm'_lt_top_of_snorm'_lt_top_of_exponent_le hfq_m hfq_lt_top (le_of_lt hp_pos) hpq_real, end lemma snorm'_add_le {f g : α → E} (hf : ae_measurable f μ) (hg : ae_measurable g μ) (hq1 : 1 ≤ q) : snorm' (f + g) q μ ≤ snorm' f q μ + snorm' g q μ := calc (∫⁻ a, ↑(nnnorm ((f + g) a)) ^ q ∂μ) ^ (1 / q) ≤ (∫⁻ a, (((λ a, (nnnorm (f a) : ℝ≥0∞)) + (λ a, (nnnorm (g a) : ℝ≥0∞))) a) ^ q ∂μ) ^ (1 / q) : begin refine @ennreal.rpow_le_rpow _ _ (1/q) _ (by simp [le_trans zero_le_one hq1]), refine lintegral_mono (λ a, ennreal.rpow_le_rpow _ (le_trans zero_le_one hq1)), simp [←ennreal.coe_add, nnnorm_add_le], end ... ≤ snorm' f q μ + snorm' g q μ : ennreal.lintegral_Lp_add_le hf.nnnorm.ennreal_coe hg.nnnorm.ennreal_coe hq1 lemma snorm_ess_sup_add_le {f g : α → F} : snorm_ess_sup (f + g) μ ≤ snorm_ess_sup f μ + snorm_ess_sup g μ := begin refine le_trans (ess_sup_mono_ae (eventually_of_forall (λ x, _))) (ennreal.ess_sup_add_le _ _), simp_rw [pi.add_apply, ←ennreal.coe_add, ennreal.coe_le_coe], exact nnnorm_add_le _ _, end lemma snorm_add_le {f g : α → E} (hf : ae_measurable f μ) (hg : ae_measurable g μ) (hp1 : 1 ≤ p) : snorm (f + g) p μ ≤ snorm f p μ + snorm g p μ := begin by_cases hp0 : p = 0, { simp [hp0], }, by_cases hp_top : p = ∞, { simp [hp_top, snorm_ess_sup_add_le], }, have hp1_real : 1 ≤ p.to_real, by rwa [← ennreal.one_to_real, ennreal.to_real_le_to_real ennreal.one_ne_top hp_top], repeat { rw snorm_eq_snorm' hp0 hp_top, }, exact snorm'_add_le hf hg hp1_real, end lemma snorm'_sum_le [second_countable_topology E] {ι} {f : ι → α → E} {s : finset ι} (hfs : ∀ i, i ∈ s → ae_measurable (f i) μ) (hq1 : 1 ≤ q) : snorm' (∑ i in s, f i) q μ ≤ ∑ i in s, snorm' (f i) q μ := finset.le_sum_of_subadditive_on_pred (λ (f : α → E), snorm' f q μ) (λ f, ae_measurable f μ) (snorm'_zero (zero_lt_one.trans_le hq1)) (λ f g hf hg, snorm'_add_le hf hg hq1) (λ x y, ae_measurable.add) _ hfs lemma snorm_sum_le [second_countable_topology E] {ι} {f : ι → α → E} {s : finset ι} (hfs : ∀ i, i ∈ s → ae_measurable (f i) μ) (hp1 : 1 ≤ p) : snorm (∑ i in s, f i) p μ ≤ ∑ i in s, snorm (f i) p μ := finset.le_sum_of_subadditive_on_pred (λ (f : α → E), snorm f p μ) (λ f, ae_measurable f μ) snorm_zero (λ f g hf hg, snorm_add_le hf hg hp1) (λ x y, ae_measurable.add) _ hfs lemma snorm_add_lt_top_of_one_le {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) (hq1 : 1 ≤ p) : snorm (f + g) p μ < ∞ := lt_of_le_of_lt (snorm_add_le hf.1 hg.1 hq1) (ennreal.add_lt_top.mpr ⟨hf.2, hg.2⟩) lemma snorm'_add_lt_top_of_le_one {f g : α → E} (hf : ae_measurable f μ) (hg : ae_measurable g μ) (hf_snorm : snorm' f q μ < ∞) (hg_snorm : snorm' g q μ < ∞) (hq_pos : 0 < q) (hq1 : q ≤ 1) : snorm' (f + g) q μ < ∞ := calc (∫⁻ a, ↑(nnnorm ((f + g) a)) ^ q ∂μ) ^ (1 / q) ≤ (∫⁻ a, (((λ a, (nnnorm (f a) : ℝ≥0∞)) + (λ a, (nnnorm (g a) : ℝ≥0∞))) a) ^ q ∂μ) ^ (1 / q) : begin refine @ennreal.rpow_le_rpow _ _ (1/q) _ (by simp [hq_pos.le]), refine lintegral_mono (λ a, ennreal.rpow_le_rpow _ hq_pos.le), simp [←ennreal.coe_add, nnnorm_add_le], end ... ≤ (∫⁻ a, (nnnorm (f a) : ℝ≥0∞) ^ q + (nnnorm (g a) : ℝ≥0∞) ^ q ∂μ) ^ (1 / q) : begin refine @ennreal.rpow_le_rpow _ _ (1/q) (lintegral_mono (λ a, _)) (by simp [hq_pos.le]), exact ennreal.rpow_add_le_add_rpow _ _ hq_pos hq1, end ... < ∞ : begin refine @ennreal.rpow_lt_top_of_nonneg _ (1/q) (by simp [hq_pos.le]) _, rw [lintegral_add' hf.nnnorm.ennreal_coe.ennreal_rpow_const hg.nnnorm.ennreal_coe.ennreal_rpow_const, ennreal.add_ne_top, ←lt_top_iff_ne_top, ←lt_top_iff_ne_top], exact ⟨lintegral_rpow_nnnorm_lt_top_of_snorm'_lt_top hq_pos hf_snorm, lintegral_rpow_nnnorm_lt_top_of_snorm'_lt_top hq_pos hg_snorm⟩, end lemma snorm_add_lt_top {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) : snorm (f + g) p μ < ∞ := begin by_cases h0 : p = 0, { simp [h0], }, rw ←ne.def at h0, cases le_total 1 p with hp1 hp1, { exact snorm_add_lt_top_of_one_le hf hg hp1, }, have hp_top : p ≠ ∞, from (lt_of_le_of_lt hp1 ennreal.coe_lt_top).ne, have hp_pos : 0 < p.to_real, { rw [← ennreal.zero_to_real, @ennreal.to_real_lt_to_real 0 p ennreal.coe_ne_top hp_top], exact ((zero_le p).lt_of_ne h0.symm), }, have hp1_real : p.to_real ≤ 1, { rwa [← ennreal.one_to_real, @ennreal.to_real_le_to_real p 1 hp_top ennreal.coe_ne_top], }, rw snorm_eq_snorm' h0 hp_top, rw [mem_ℒp, snorm_eq_snorm' h0 hp_top] at hf hg, exact snorm'_add_lt_top_of_le_one hf.1 hg.1 hf.2 hg.2 hp_pos hp1_real, end section second_countable_topology variable [second_countable_topology E] lemma mem_ℒp.add {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) : mem_ℒp (f + g) p μ := ⟨ae_measurable.add hf.1 hg.1, snorm_add_lt_top hf hg⟩ lemma mem_ℒp.sub {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) : mem_ℒp (f - g) p μ := by { rw sub_eq_add_neg, exact hf.add hg.neg } end second_countable_topology end borel_space section normed_space variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 E] [normed_space 𝕜 F] lemma snorm'_const_smul {f : α → F} (c : 𝕜) (hq0_lt : 0 < q) : snorm' (c • f) q μ = (nnnorm c : ℝ≥0∞) * snorm' f q μ := begin rw snorm', simp_rw [pi.smul_apply, nnnorm_smul, ennreal.coe_mul, ennreal.mul_rpow_of_nonneg _ _ (le_of_lt hq0_lt)], suffices h_integral : ∫⁻ a, ↑(nnnorm c) ^ q * ↑(nnnorm (f a)) ^ q ∂μ = (nnnorm c : ℝ≥0∞)^q * ∫⁻ a, (nnnorm (f a)) ^ q ∂μ, { apply_fun (λ x, x ^ (1/q)) at h_integral, rw [h_integral, @ennreal.mul_rpow_of_nonneg _ _ (1/q) (by simp [le_of_lt hq0_lt])], congr, simp_rw [←ennreal.rpow_mul, one_div, mul_inv_cancel (ne_of_lt hq0_lt).symm, ennreal.rpow_one], }, rw lintegral_const_mul', rw ennreal.coe_rpow_of_nonneg _ hq0_lt.le, exact ennreal.coe_ne_top, end lemma snorm_ess_sup_const_smul {f : α → F} (c : 𝕜) : snorm_ess_sup (c • f) μ = (nnnorm c : ℝ≥0∞) * snorm_ess_sup f μ := by simp_rw [snorm_ess_sup, pi.smul_apply, nnnorm_smul, ennreal.coe_mul, ennreal.ess_sup_const_mul] lemma snorm_const_smul {f : α → F} (c : 𝕜) : snorm (c • f) p μ = (nnnorm c : ℝ≥0∞) * snorm f p μ := begin by_cases h0 : p = 0, { simp [h0], }, by_cases h_top : p = ∞, { simp [h_top, snorm_ess_sup_const_smul], }, repeat { rw snorm_eq_snorm' h0 h_top, }, rw ←ne.def at h0, exact snorm'_const_smul c (ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) h0.symm, h_top⟩), end lemma mem_ℒp.const_smul [borel_space E] {f : α → E} (hf : mem_ℒp f p μ) (c : 𝕜) : mem_ℒp (c • f) p μ := ⟨ae_measurable.const_smul hf.1 c, lt_of_le_of_lt (le_of_eq (snorm_const_smul c)) (ennreal.mul_lt_top ennreal.coe_lt_top hf.2)⟩ lemma mem_ℒp.const_mul [measurable_space 𝕜] [borel_space 𝕜] {f : α → 𝕜} (hf : mem_ℒp f p μ) (c : 𝕜) : mem_ℒp (λ x, c * f x) p μ := hf.const_smul c lemma snorm'_smul_le_mul_snorm' [opens_measurable_space E] [measurable_space 𝕜] [opens_measurable_space 𝕜] {p q r : ℝ} {f : α → E} (hf : ae_measurable f μ) {φ : α → 𝕜} (hφ : ae_measurable φ μ) (hp0_lt : 0 < p) (hpq : p < q) (hpqr : 1/p = 1/q + 1/r) : snorm' (φ • f) p μ ≤ snorm' φ q μ * snorm' f r μ := begin simp_rw [snorm', pi.smul_apply', nnnorm_smul, ennreal.coe_mul], exact ennreal.lintegral_Lp_mul_le_Lq_mul_Lr hp0_lt hpq hpqr μ hφ.nnnorm.ennreal_coe hf.nnnorm.ennreal_coe, end end normed_space section monotonicity lemma snorm_le_mul_snorm_aux_of_nonneg {f : α → F} {g : α → G} {c : ℝ} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ c * ∥g x∥) (hc : 0 ≤ c) (p : ℝ≥0∞) : snorm f p μ ≤ (ennreal.of_real c) * snorm g p μ := begin lift c to ℝ≥0 using hc, rw [ennreal.of_real_coe_nnreal, ← c.nnnorm_eq, ← snorm_norm g, ← snorm_const_smul (c : ℝ)], swap, apply_instance, refine snorm_mono_ae _, simpa end lemma snorm_le_mul_snorm_aux_of_neg {f : α → F} {g : α → G} {c : ℝ} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ c * ∥g x∥) (hc : c < 0) (p : ℝ≥0∞) : snorm f p μ = 0 ∧ snorm g p μ = 0 := begin suffices : f =ᵐ[μ] 0 ∧ g =ᵐ[μ] 0, by simp [snorm_congr_ae this.1, snorm_congr_ae this.2], refine ⟨h.mono $ λ x hx, _, h.mono $ λ x hx, _⟩, { refine norm_le_zero_iff.1 (hx.trans _), exact mul_nonpos_of_nonpos_of_nonneg hc.le (norm_nonneg _) }, { refine norm_le_zero_iff.1 (nonpos_of_mul_nonneg_right _ hc), exact (norm_nonneg _).trans hx } end lemma snorm_le_mul_snorm_of_ae_le_mul {f : α → F} {g : α → G} {c : ℝ} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ c * ∥g x∥) (p : ℝ≥0∞) : snorm f p μ ≤ (ennreal.of_real c) * snorm g p μ := begin cases le_or_lt 0 c with hc hc, { exact snorm_le_mul_snorm_aux_of_nonneg h hc p }, { simp [snorm_le_mul_snorm_aux_of_neg h hc p] } end lemma mem_ℒp.of_le_mul [measurable_space F] {f : α → E} {g : α → F} {c : ℝ} (hg : mem_ℒp g p μ) (hf : ae_measurable f μ) (hfg : ∀ᵐ x ∂μ, ∥f x∥ ≤ c * ∥g x∥) : mem_ℒp f p μ := begin simp only [mem_ℒp, hf, true_and], apply lt_of_le_of_lt (snorm_le_mul_snorm_of_ae_le_mul hfg p), simp [lt_top_iff_ne_top, hg.snorm_ne_top], end end monotonicity end ℒp /-! ### Lp space The space of equivalence classes of measurable functions for which `snorm f p μ < ∞`. -/ @[simp] lemma snorm_ae_eq_fun {α E : Type*} [measurable_space α] {μ : measure α} [measurable_space E] [normed_group E] {p : ℝ≥0∞} {f : α → E} (hf : ae_measurable f μ) : snorm (ae_eq_fun.mk f hf) p μ = snorm f p μ := snorm_congr_ae (ae_eq_fun.coe_fn_mk _ _) lemma mem_ℒp.snorm_mk_lt_top {α E : Type*} [measurable_space α] {μ : measure α} [measurable_space E] [normed_group E] {p : ℝ≥0∞} {f : α → E} (hfp : mem_ℒp f p μ) : snorm (ae_eq_fun.mk f hfp.1) p μ < ∞ := by simp [hfp.2] /-- Lp space -/ def Lp {α} (E : Type*) [measurable_space α] [measurable_space E] [normed_group E] [borel_space E] [second_countable_topology E] (p : ℝ≥0∞) (μ : measure α) : add_subgroup (α →ₘ[μ] E) := { carrier := {f | snorm f p μ < ∞}, zero_mem' := by simp [snorm_congr_ae ae_eq_fun.coe_fn_zero, snorm_zero], add_mem' := λ f g hf hg, by simp [snorm_congr_ae (ae_eq_fun.coe_fn_add _ _), snorm_add_lt_top ⟨f.ae_measurable, hf⟩ ⟨g.ae_measurable, hg⟩], neg_mem' := λ f hf, by rwa [set.mem_set_of_eq, snorm_congr_ae (ae_eq_fun.coe_fn_neg _), snorm_neg] } notation α ` →₁[`:25 μ `] ` E := measure_theory.Lp E 1 μ namespace mem_ℒp variables [borel_space E] [second_countable_topology E] /-- make an element of Lp from a function verifying `mem_ℒp` -/ def to_Lp (f : α → E) (h_mem_ℒp : mem_ℒp f p μ) : Lp E p μ := ⟨ae_eq_fun.mk f h_mem_ℒp.1, h_mem_ℒp.snorm_mk_lt_top⟩ lemma coe_fn_to_Lp {f : α → E} (hf : mem_ℒp f p μ) : hf.to_Lp f =ᵐ[μ] f := ae_eq_fun.coe_fn_mk _ _ @[simp] lemma to_Lp_eq_to_Lp_iff {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) : hf.to_Lp f = hg.to_Lp g ↔ f =ᵐ[μ] g := by simp [to_Lp] @[simp] lemma to_Lp_zero (h : mem_ℒp (0 : α → E) p μ ) : h.to_Lp 0 = 0 := rfl lemma to_Lp_add {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) : (hf.add hg).to_Lp (f + g) = hf.to_Lp f + hg.to_Lp g := rfl lemma to_Lp_neg {f : α → E} (hf : mem_ℒp f p μ) : hf.neg.to_Lp (-f) = - hf.to_Lp f := rfl lemma to_Lp_sub {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) : (hf.sub hg).to_Lp (f - g) = hf.to_Lp f - hg.to_Lp g := by { convert hf.to_Lp_add hg.neg, exact sub_eq_add_neg f g } end mem_ℒp namespace Lp variables [borel_space E] [second_countable_topology E] instance : has_coe_to_fun (Lp E p μ) := ⟨λ _, α → E, λ f, ((f : α →ₘ[μ] E) : α → E)⟩ @[ext] lemma ext {f g : Lp E p μ} (h : f =ᵐ[μ] g) : f = g := begin cases f, cases g, simp only [subtype.mk_eq_mk], exact ae_eq_fun.ext h end lemma ext_iff {f g : Lp E p μ} : f = g ↔ f =ᵐ[μ] g := ⟨λ h, by rw h, λ h, ext h⟩ lemma mem_Lp_iff_snorm_lt_top {f : α →ₘ[μ] E} : f ∈ Lp E p μ ↔ snorm f p μ < ∞ := iff.refl _ lemma mem_Lp_iff_mem_ℒp {f : α →ₘ[μ] E} : f ∈ Lp E p μ ↔ mem_ℒp f p μ := by simp [mem_Lp_iff_snorm_lt_top, mem_ℒp, f.measurable.ae_measurable] lemma antimono [finite_measure μ] {p q : ℝ≥0∞} (hpq : p ≤ q) : Lp E q μ ≤ Lp E p μ := λ f hf, (mem_ℒp.mem_ℒp_of_exponent_le ⟨f.ae_measurable, hf⟩ hpq).2 @[simp] lemma coe_fn_mk {f : α →ₘ[μ] E} (hf : snorm f p μ < ∞) : ((⟨f, hf⟩ : Lp E p μ) : α → E) = f := rfl @[simp] lemma coe_mk {f : α →ₘ[μ] E} (hf : snorm f p μ < ∞) : ((⟨f, hf⟩ : Lp E p μ) : α →ₘ[μ] E) = f := rfl @[simp] lemma to_Lp_coe_fn (f : Lp E p μ) (hf : mem_ℒp f p μ) : hf.to_Lp f = f := by { cases f, simp [mem_ℒp.to_Lp] } lemma snorm_lt_top (f : Lp E p μ) : snorm f p μ < ∞ := f.prop lemma snorm_ne_top (f : Lp E p μ) : snorm f p μ ≠ ∞ := (snorm_lt_top f).ne protected lemma measurable (f : Lp E p μ) : measurable f := f.val.measurable protected lemma ae_measurable (f : Lp E p μ) : ae_measurable f μ := f.val.ae_measurable protected lemma mem_ℒp (f : Lp E p μ) : mem_ℒp f p μ := ⟨Lp.ae_measurable f, f.prop⟩ variables (E p μ) lemma coe_fn_zero : ⇑(0 : Lp E p μ) =ᵐ[μ] 0 := ae_eq_fun.coe_fn_zero variables {E p μ} lemma coe_fn_neg (f : Lp E p μ) : ⇑(-f) =ᵐ[μ] -f := ae_eq_fun.coe_fn_neg _ lemma coe_fn_add (f g : Lp E p μ) : ⇑(f + g) =ᵐ[μ] f + g := ae_eq_fun.coe_fn_add _ _ lemma coe_fn_sub (f g : Lp E p μ) : ⇑(f - g) =ᵐ[μ] f - g := ae_eq_fun.coe_fn_sub _ _ lemma mem_Lp_const (α) [measurable_space α] (μ : measure α) (c : E) [finite_measure μ] : @ae_eq_fun.const α _ _ μ _ c ∈ Lp E p μ := (mem_ℒp_const c).snorm_mk_lt_top instance : has_norm (Lp E p μ) := { norm := λ f, ennreal.to_real (snorm f p μ) } instance : has_dist (Lp E p μ) := { dist := λ f g, ∥f - g∥} instance : has_edist (Lp E p μ) := { edist := λ f g, ennreal.of_real (dist f g) } lemma norm_def (f : Lp E p μ) : ∥f∥ = ennreal.to_real (snorm f p μ) := rfl @[simp] lemma norm_to_Lp (f : α → E) (hf : mem_ℒp f p μ) : ∥hf.to_Lp f∥ = ennreal.to_real (snorm f p μ) := by rw [norm_def, snorm_congr_ae (mem_ℒp.coe_fn_to_Lp hf)] lemma dist_def (f g : Lp E p μ) : dist f g = (snorm (f - g) p μ).to_real := begin simp_rw [dist, norm_def], congr' 1, apply snorm_congr_ae (coe_fn_sub _ _), end lemma edist_def (f g : Lp E p μ) : edist f g = snorm (f - g) p μ := begin simp_rw [edist, dist, norm_def, ennreal.of_real_to_real (snorm_ne_top _)], exact snorm_congr_ae (coe_fn_sub _ _) end @[simp] lemma edist_to_Lp_to_Lp (f g : α → E) (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) : edist (hf.to_Lp f) (hg.to_Lp g) = snorm (f - g) p μ := by { rw edist_def, exact snorm_congr_ae (hf.coe_fn_to_Lp.sub hg.coe_fn_to_Lp) } @[simp] lemma edist_to_Lp_zero (f : α → E) (hf : mem_ℒp f p μ) : edist (hf.to_Lp f) 0 = snorm f p μ := by { convert edist_to_Lp_to_Lp f 0 hf zero_mem_ℒp, simp } @[simp] lemma norm_zero : ∥(0 : Lp E p μ)∥ = 0 := begin change (snorm ⇑(0 : α →ₘ[μ] E) p μ).to_real = 0, simp [snorm_congr_ae ae_eq_fun.coe_fn_zero, snorm_zero] end lemma norm_eq_zero_iff {f : Lp E p μ} (hp : 0 < p) : ∥f∥ = 0 ↔ f = 0 := begin refine ⟨λ hf, _, λ hf, by simp [hf]⟩, rw [norm_def, ennreal.to_real_eq_zero_iff] at hf, cases hf, { rw snorm_eq_zero_iff (Lp.ae_measurable f) hp.ne.symm at hf, exact subtype.eq (ae_eq_fun.ext (hf.trans ae_eq_fun.coe_fn_zero.symm)), }, { exact absurd hf (snorm_ne_top f), }, end lemma eq_zero_iff_ae_eq_zero {f : Lp E p μ} : f = 0 ↔ f =ᵐ[μ] 0 := begin split, { assume h, rw h, exact ae_eq_fun.coe_fn_const _ _ }, { assume h, ext1, filter_upwards [h, ae_eq_fun.coe_fn_const α (0 : E)], assume a ha h'a, rw ha, exact h'a.symm } end @[simp] lemma norm_neg {f : Lp E p μ} : ∥-f∥ = ∥f∥ := by rw [norm_def, norm_def, snorm_congr_ae (coe_fn_neg _), snorm_neg] lemma norm_le_mul_norm_of_ae_le_mul [second_countable_topology F] [measurable_space F] [borel_space F] {c : ℝ} {f : Lp E p μ} {g : Lp F p μ} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ c * ∥g x∥) : ∥f∥ ≤ c * ∥g∥ := begin by_cases pzero : p = 0, { simp [pzero, norm_def] }, cases le_or_lt 0 c with hc hc, { have := snorm_le_mul_snorm_aux_of_nonneg h hc p, rw [← ennreal.to_real_le_to_real, ennreal.to_real_mul, ennreal.to_real_of_real hc] at this, { exact this }, { exact (Lp.mem_ℒp _).snorm_ne_top }, { simp [(Lp.mem_ℒp _).snorm_ne_top] } }, { have := snorm_le_mul_snorm_aux_of_neg h hc p, simp only [snorm_eq_zero_iff (Lp.ae_measurable _) pzero, ← eq_zero_iff_ae_eq_zero] at this, simp [this] } end lemma norm_le_norm_of_ae_le [second_countable_topology F] [measurable_space F] [borel_space F] {f : Lp E p μ} {g : Lp F p μ} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ ∥g x∥) : ∥f∥ ≤ ∥g∥ := begin rw [norm_def, norm_def, ennreal.to_real_le_to_real (snorm_ne_top _) (snorm_ne_top _)], exact snorm_mono_ae h end lemma mem_Lp_of_ae_le_mul [second_countable_topology F] [measurable_space F] [borel_space F] {c : ℝ} {f : α →ₘ[μ] E} {g : Lp F p μ} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ c * ∥g x∥) : f ∈ Lp E p μ := mem_Lp_iff_mem_ℒp.2 $ mem_ℒp.of_le_mul (Lp.mem_ℒp g) (ae_eq_fun.ae_measurable f) h lemma mem_Lp_of_ae_le [second_countable_topology F] [measurable_space F] [borel_space F] {f : α →ₘ[μ] E} {g : Lp F p μ} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ ∥g x∥) : f ∈ Lp E p μ := mem_Lp_iff_mem_ℒp.2 $ mem_ℒp.of_le (Lp.mem_ℒp g) (ae_eq_fun.ae_measurable f) h instance [hp : fact (1 ≤ p)] : normed_group (Lp E p μ) := normed_group.of_core _ { norm_eq_zero_iff := λ f, norm_eq_zero_iff (ennreal.zero_lt_one.trans_le hp), triangle := begin assume f g, simp only [norm_def], rw ← ennreal.to_real_add (snorm_ne_top f) (snorm_ne_top g), suffices h_snorm : snorm ⇑(f + g) p μ ≤ snorm ⇑f p μ + snorm ⇑g p μ, { rwa ennreal.to_real_le_to_real (snorm_ne_top (f + g)), exact ennreal.add_ne_top.mpr ⟨snorm_ne_top f, snorm_ne_top g⟩, }, rw [snorm_congr_ae (coe_fn_add _ _)], exact snorm_add_le (Lp.ae_measurable f) (Lp.ae_measurable g) hp, end, norm_neg := by simp } instance normed_group_L1 : normed_group (Lp E 1 μ) := by apply_instance instance normed_group_L2 : normed_group (Lp E 2 μ) := by apply_instance instance normed_group_Ltop : normed_group (Lp E ∞ μ) := by apply_instance section normed_space variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 E] lemma mem_Lp_const_smul (c : 𝕜) (f : Lp E p μ) : c • ↑f ∈ Lp E p μ := begin rw [mem_Lp_iff_snorm_lt_top, snorm_congr_ae (ae_eq_fun.coe_fn_smul _ _), snorm_const_smul, ennreal.mul_lt_top_iff], exact or.inl ⟨ennreal.coe_lt_top, f.prop⟩, end instance : has_scalar 𝕜 (Lp E p μ) := { smul := λ c f, ⟨c • ↑f, mem_Lp_const_smul c f⟩ } lemma coe_fn_smul (c : 𝕜) (f : Lp E p μ) : ⇑(c • f) =ᵐ[μ] c • f := ae_eq_fun.coe_fn_smul _ _ instance : semimodule 𝕜 (Lp E p μ) := { one_smul := λ _, subtype.eq (one_smul 𝕜 _), mul_smul := λ _ _ _, subtype.eq (mul_smul _ _ _), smul_add := λ _ _ _, subtype.eq (smul_add _ _ _), smul_zero := λ _, subtype.eq (smul_zero _), add_smul := λ _ _ _, subtype.eq (add_smul _ _ _), zero_smul := λ _, subtype.eq (zero_smul _ _) } lemma norm_const_smul (c : 𝕜) (f : Lp E p μ) : ∥c • f∥ = ∥c∥ * ∥f∥ := by rw [norm_def, snorm_congr_ae (coe_fn_smul _ _), snorm_const_smul c, ennreal.to_real_mul, ennreal.coe_to_real, coe_nnnorm, norm_def] instance [fact (1 ≤ p)] : normed_space 𝕜 (Lp E p μ) := { norm_smul_le := λ _ _, by simp [norm_const_smul] } instance normed_space_L1 : normed_space 𝕜 (Lp E 1 μ) := by apply_instance instance normed_space_L2 : normed_space 𝕜 (Lp E 2 μ) := by apply_instance instance normed_space_Ltop : normed_space 𝕜 (Lp E ∞ μ) := by apply_instance end normed_space end Lp namespace mem_ℒp variables [borel_space E] [second_countable_topology E] {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 E] lemma to_Lp_const_smul {f : α → E} (c : 𝕜) (hf : mem_ℒp f p μ) : (hf.const_smul c).to_Lp (c • f) = c • hf.to_Lp f := rfl end mem_ℒp end measure_theory open measure_theory /-! ### Composition on `L^p` We show that Lipschitz functions vanishing at zero act by composition on `L^p`, and specialize this to the composition with continuous linear maps, and to the definition of the positive part of an `L^p` function. -/ section composition variables [second_countable_topology E] [borel_space E] [second_countable_topology F] [measurable_space F] [borel_space F] {g : E → F} {c : ℝ≥0} namespace lipschitz_with /-- When `g` is a Lipschitz function sending `0` to `0` and `f` is in `Lp`, then `g ∘ f` is well defined as an element of `Lp`. -/ def comp_Lp (hg : lipschitz_with c g) (g0 : g 0 = 0) (f : Lp E p μ) : Lp F p μ := ⟨ae_eq_fun.comp g hg.continuous.measurable (f : α →ₘ[μ] E), begin suffices : ∀ᵐ x ∂μ, ∥ae_eq_fun.comp g hg.continuous.measurable (f : α →ₘ[μ] E) x∥ ≤ c * ∥f x∥, { exact Lp.mem_Lp_of_ae_le_mul this }, filter_upwards [ae_eq_fun.coe_fn_comp g hg.continuous.measurable (f : α →ₘ[μ] E)], assume a ha, simp only [ha], rw [← dist_zero_right, ← dist_zero_right, ← g0], exact hg.dist_le_mul (f a) 0, end⟩ lemma coe_fn_comp_Lp (hg : lipschitz_with c g) (g0 : g 0 = 0) (f : Lp E p μ) : hg.comp_Lp g0 f =ᵐ[μ] g ∘ f := ae_eq_fun.coe_fn_comp _ _ _ @[simp] lemma comp_Lp_zero (hg : lipschitz_with c g) (g0 : g 0 = 0) : hg.comp_Lp g0 (0 : Lp E p μ) = 0 := begin rw Lp.eq_zero_iff_ae_eq_zero, apply (coe_fn_comp_Lp _ _ _).trans, filter_upwards [Lp.coe_fn_zero E p μ], assume a ha, simp [ha, g0] end lemma norm_comp_Lp_sub_le (hg : lipschitz_with c g) (g0 : g 0 = 0) (f f' : Lp E p μ) : ∥hg.comp_Lp g0 f - hg.comp_Lp g0 f'∥ ≤ c * ∥f - f'∥ := begin apply Lp.norm_le_mul_norm_of_ae_le_mul, filter_upwards [hg.coe_fn_comp_Lp g0 f, hg.coe_fn_comp_Lp g0 f', Lp.coe_fn_sub (hg.comp_Lp g0 f) (hg.comp_Lp g0 f'), Lp.coe_fn_sub f f'], assume a ha1 ha2 ha3 ha4, simp [ha1, ha2, ha3, ha4, ← dist_eq_norm], exact hg.dist_le_mul (f a) (f' a) end lemma norm_comp_Lp_le (hg : lipschitz_with c g) (g0 : g 0 = 0) (f : Lp E p μ) : ∥hg.comp_Lp g0 f∥ ≤ c * ∥f∥ := by simpa using hg.norm_comp_Lp_sub_le g0 f 0 lemma lipschitz_with_comp_Lp [fact (1 ≤ p)] (hg : lipschitz_with c g) (g0 : g 0 = 0) : lipschitz_with c (hg.comp_Lp g0 : Lp E p μ → Lp F p μ) := lipschitz_with.of_dist_le_mul $ λ f g, by simp [dist_eq_norm, norm_comp_Lp_sub_le] lemma continuous_comp_Lp [fact (1 ≤ p)] (hg : lipschitz_with c g) (g0 : g 0 = 0) : continuous (hg.comp_Lp g0 : Lp E p μ → Lp F p μ) := (lipschitz_with_comp_Lp hg g0).continuous end lipschitz_with namespace continuous_linear_map variables [normed_space ℝ E] [normed_space ℝ F] /-- Composing `f : Lp ` with `L : E →L[ℝ] F`. -/ def comp_Lp (L : E →L[ℝ] F) (f : Lp E p μ) : Lp F p μ := L.lipschitz.comp_Lp (map_zero L) f lemma coe_fn_comp_Lp (L : E →L[ℝ] F) (f : Lp E p μ) : ∀ᵐ a ∂μ, (L.comp_Lp f) a = L (f a) := lipschitz_with.coe_fn_comp_Lp _ _ _ variables (μ p) /-- Composing `f : Lp E p μ` with `L : E →L[ℝ] F`, seen as a `ℝ`-linear map on `Lp E p μ`. -/ def comp_Lpₗ (L : E →L[ℝ] F) : (Lp E p μ) →ₗ[ℝ] (Lp F p μ) := { to_fun := λ f, L.comp_Lp f, map_add' := begin intros f g, ext1, filter_upwards [Lp.coe_fn_add f g, coe_fn_comp_Lp L (f + g), coe_fn_comp_Lp L f, coe_fn_comp_Lp L g, Lp.coe_fn_add (L.comp_Lp f) (L.comp_Lp g)], assume a ha1 ha2 ha3 ha4 ha5, simp only [ha1, ha2, ha3, ha4, ha5, map_add, pi.add_apply], end, map_smul' := begin intros c f, ext1, filter_upwards [Lp.coe_fn_smul c f, coe_fn_comp_Lp L (c • f), Lp.coe_fn_smul c (L.comp_Lp f), coe_fn_comp_Lp L f], assume a ha1 ha2 ha3 ha4, simp only [ha1, ha2, ha3, ha4, map_smul, pi.smul_apply], end } variables {μ p} lemma norm_comp_Lp_le (L : E →L[ℝ] F) (f : Lp E p μ) : ∥L.comp_Lp f∥ ≤ ∥L∥ * ∥f∥ := lipschitz_with.norm_comp_Lp_le _ _ _ variables (μ p) /-- Composing `f : Lp E p μ` with `L : E →L[ℝ] F`, seen as a continuous `ℝ`-linear map on `Lp E p μ`. -/ def comp_LpL [fact (1 ≤ p)] (L : E →L[ℝ] F) : (Lp E p μ) →L[ℝ] (Lp F p μ) := linear_map.mk_continuous (L.comp_Lpₗ p μ) ∥L∥ L.norm_comp_Lp_le lemma norm_compLpL_le [fact (1 ≤ p)] (L : E →L[ℝ] F) : ∥L.comp_LpL p μ∥ ≤ ∥L∥ := linear_map.mk_continuous_norm_le _ (norm_nonneg _) _ end continuous_linear_map namespace measure_theory namespace Lp section pos_part lemma lipschitz_with_pos_part : lipschitz_with 1 (λ (x : ℝ), max x 0) := lipschitz_with.of_dist_le_mul $ λ x y, by simp [dist, abs_max_sub_max_le_abs] /-- Positive part of a function in `L^p`. -/ def pos_part (f : Lp ℝ p μ) : Lp ℝ p μ := lipschitz_with_pos_part.comp_Lp (max_eq_right (le_refl _)) f /-- Negative part of a function in `L^p`. -/ def neg_part (f : Lp ℝ p μ) : Lp ℝ p μ := pos_part (-f) @[norm_cast] lemma coe_pos_part (f : Lp ℝ p μ) : (pos_part f : α →ₘ[μ] ℝ) = (f : α →ₘ[μ] ℝ).pos_part := rfl lemma coe_fn_pos_part (f : Lp ℝ p μ) : ⇑(pos_part f) =ᵐ[μ] λ a, max (f a) 0 := ae_eq_fun.coe_fn_pos_part _ lemma coe_fn_neg_part_eq_max (f : Lp ℝ p μ) : ∀ᵐ a ∂μ, neg_part f a = max (- f a) 0 := begin rw neg_part, filter_upwards [coe_fn_pos_part (-f), coe_fn_neg f], assume a h₁ h₂, rw [h₁, h₂, pi.neg_apply] end lemma coe_fn_neg_part (f : Lp ℝ p μ) : ∀ᵐ a ∂μ, neg_part f a = - min (f a) 0 := (coe_fn_neg_part_eq_max f).mono $ assume a h, by rw [h, ← max_neg_neg, neg_zero] lemma continuous_pos_part [fact (1 ≤ p)] : continuous (λf : Lp ℝ p μ, pos_part f) := lipschitz_with.continuous_comp_Lp _ _ lemma continuous_neg_part [fact (1 ≤ p)] : continuous (λf : Lp ℝ p μ, neg_part f) := have eq : (λf : Lp ℝ p μ, neg_part f) = (λf : Lp ℝ p μ, pos_part (-f)) := rfl, by { rw eq, exact continuous_pos_part.comp continuous_neg } end pos_part end Lp end measure_theory end composition /-! ## `L^p` is a complete space We show that `L^p` is a complete space for `1 ≤ p`. -/ section complete_space variables [borel_space E] [second_countable_topology E] namespace measure_theory namespace Lp lemma snorm'_lim_eq_lintegral_liminf {ι} [nonempty ι] [linear_order ι] {f : ι → α → G} {p : ℝ} (hp_nonneg : 0 ≤ p) {f_lim : α → G} (h_lim : ∀ᵐ (x : α) ∂μ, tendsto (λ n, f n x) at_top (𝓝 (f_lim x))) : snorm' f_lim p μ = (∫⁻ a, at_top.liminf (λ m, (nnnorm (f m a) : ℝ≥0∞)^p) ∂μ) ^ (1/p) := begin suffices h_no_pow : (∫⁻ a, (nnnorm (f_lim a)) ^ p ∂μ) = (∫⁻ a, at_top.liminf (λ m, (nnnorm (f m a) : ℝ≥0∞)^p) ∂μ), { rw [snorm', h_no_pow], }, refine lintegral_congr_ae (h_lim.mono (λ a ha, _)), rw tendsto.liminf_eq, simp_rw [ennreal.coe_rpow_of_nonneg _ hp_nonneg, ennreal.tendsto_coe], refine ((nnreal.continuous_rpow_const hp_nonneg).tendsto (nnnorm (f_lim a))).comp _, exact (continuous_nnnorm.tendsto (f_lim a)).comp ha, end lemma snorm'_lim_le_liminf_snorm' {E} [measurable_space E] [normed_group E] [borel_space E] {f : ℕ → α → E} {p : ℝ} (hp_pos : 0 < p) (hf : ∀ n, ae_measurable (f n) μ) {f_lim : α → E} (h_lim : ∀ᵐ (x : α) ∂μ, tendsto (λ n, f n x) at_top (𝓝 (f_lim x))) : snorm' f_lim p μ ≤ at_top.liminf (λ n, snorm' (f n) p μ) := begin rw snorm'_lim_eq_lintegral_liminf hp_pos.le h_lim, rw [←@ennreal.le_rpow_one_div_iff _ _ (1/p) (by simp [hp_pos]), one_div_one_div], refine (lintegral_liminf_le' (λ m, (hf m).nnnorm.ennreal_coe.ennreal_rpow_const)).trans (le_of_eq _), have h_pow_liminf : at_top.liminf (λ n, snorm' (f n) p μ) ^ p = at_top.liminf (λ n, (snorm' (f n) p μ) ^ p), { have h_rpow_mono := ennreal.rpow_left_strict_mono_of_pos hp_pos, have h_rpow_surj := (ennreal.rpow_left_bijective hp_pos.ne.symm).2, refine (h_rpow_mono.order_iso_of_surjective _ h_rpow_surj).liminf_apply _ _ _ _, all_goals { is_bounded_default }, }, rw h_pow_liminf, simp_rw [snorm', ← ennreal.rpow_mul, one_div, inv_mul_cancel hp_pos.ne.symm, ennreal.rpow_one], end lemma snorm_exponent_top_lim_eq_ess_sup_liminf {ι} [nonempty ι] [linear_order ι] {f : ι → α → G} {f_lim : α → G} (h_lim : ∀ᵐ (x : α) ∂μ, tendsto (λ n, f n x) at_top (𝓝 (f_lim x))) : snorm f_lim ∞ μ = ess_sup (λ x, at_top.liminf (λ m, (nnnorm (f m x) : ℝ≥0∞))) μ := begin rw [snorm_exponent_top, snorm_ess_sup], refine ess_sup_congr_ae (h_lim.mono (λ x hx, _)), rw tendsto.liminf_eq, rw ennreal.tendsto_coe, exact (continuous_nnnorm.tendsto (f_lim x)).comp hx, end lemma snorm_exponent_top_lim_le_liminf_snorm_exponent_top {ι} [nonempty ι] [encodable ι] [linear_order ι] {f : ι → α → F} {f_lim : α → F} (h_lim : ∀ᵐ (x : α) ∂μ, tendsto (λ n, f n x) at_top (𝓝 (f_lim x))) : snorm f_lim ∞ μ ≤ at_top.liminf (λ n, snorm (f n) ∞ μ) := begin rw snorm_exponent_top_lim_eq_ess_sup_liminf h_lim, simp_rw [snorm_exponent_top, snorm_ess_sup], exact ennreal.ess_sup_liminf_le (λ n, (λ x, (nnnorm (f n x) : ℝ≥0∞))), end lemma snorm_lim_le_liminf_snorm {E} [measurable_space E] [normed_group E] [borel_space E] {f : ℕ → α → E} (hf : ∀ n, ae_measurable (f n) μ) (f_lim : α → E) (h_lim : ∀ᵐ (x : α) ∂μ, tendsto (λ n, f n x) at_top (𝓝 (f_lim x))) : snorm f_lim p μ ≤ at_top.liminf (λ n, snorm (f n) p μ) := begin by_cases hp0 : p = 0, { simp [hp0], }, rw ← ne.def at hp0, by_cases hp_top : p = ∞, { simp_rw [hp_top], exact snorm_exponent_top_lim_le_liminf_snorm_exponent_top h_lim, }, simp_rw snorm_eq_snorm' hp0 hp_top, have hp_pos : 0 < p.to_real, from ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) hp0.symm, hp_top⟩, exact snorm'_lim_le_liminf_snorm' hp_pos hf h_lim, end /-! ### `Lp` is complete iff Cauchy sequences of `ℒp` have limits in `ℒp` -/ lemma tendsto_Lp_of_tendsto_ℒp {ι} [linear_order ι] [hp : fact (1 ≤ p)] {f : ι → Lp E p μ} (f_lim : α → E) (f_lim_ℒp : mem_ℒp f_lim p μ) (h_tendsto : at_top.tendsto (λ n, snorm (f n - f_lim) p μ) (𝓝 0)) : at_top.tendsto f (𝓝 (f_lim_ℒp.to_Lp f_lim)) := begin by_cases hι : nonempty ι, swap, { exact tendsto_of_not_nonempty hι, }, haveI : nonempty ι := hι, rw ennreal.tendsto_at_top_zero at h_tendsto, simp_rw metric.tendsto_at_top, intros ε hε, have hε_pos : 0 < ennreal.of_real ε, from ennreal.of_real_pos.mpr hε, have hε2_pos : 0 < ennreal.of_real ε / 2, by { rw ennreal.div_pos_iff, exact ⟨hε_pos.ne.symm, ennreal.two_ne_top⟩, }, cases (h_tendsto (ennreal.of_real ε / 2) hε2_pos) with N h_tendsto, refine ⟨N, λ n hn, _⟩, specialize h_tendsto n hn, have hp_pos : 0 < p, from ennreal.zero_lt_one.trans_le hp.elim, rw [dist_def, ←@ennreal.to_real_of_real ε (le_of_lt hε), ennreal.to_real_lt_to_real _ ennreal.of_real_ne_top], swap, { rw snorm_congr_ae (coe_fn_sub _ _).symm, exact snorm_ne_top _, }, have h_coe : ⇑(f n) - f_lim =ᵐ[μ] ⇑(f n) - ⇑(mem_ℒp.to_Lp f_lim f_lim_ℒp), { have h_coe' : f_lim =ᵐ[μ] ⇑(mem_ℒp.to_Lp f_lim f_lim_ℒp), from (mem_ℒp.coe_fn_to_Lp _).symm, refine h_coe'.mono (λ x hx, _), rw [pi.sub_apply, pi.sub_apply, hx], }, rw snorm_congr_ae h_coe.symm, exact lt_of_le_of_lt h_tendsto (ennreal.half_lt_self hε_pos.ne.symm ennreal.of_real_ne_top), end lemma complete_space_Lp_of_cauchy_complete_ℒp [hp : fact (1 ≤ p)] (H : ∀ (f : ℕ → α → E) (hf : ∀ n, mem_ℒp (f n) p μ) (B : ℕ → ℝ≥0∞) (hB : ∑' i, B i < ∞) (h_cau : ∀ (N n m : ℕ), N ≤ n → N ≤ m → snorm (f n - f m) p μ < B N), ∃ (f_lim : α → E) (hf_lim_meas : mem_ℒp f_lim p μ), at_top.tendsto (λ n, snorm (f n - f_lim) p μ) (𝓝 0)) : complete_space (Lp E p μ) := begin let B := λ n : ℕ, ((1:ℝ) / 2) ^ n, have hB_pos : ∀ n, 0 < B n, from λ n, pow_pos (div_pos zero_lt_one zero_lt_two) n, refine metric.complete_of_convergent_controlled_sequences B hB_pos (λ f hf, _), suffices h_limit : ∃ (f_lim : α → E) (hf_lim_meas : mem_ℒp f_lim p μ), at_top.tendsto (λ n, snorm (f n - f_lim) p μ) (𝓝 0), { rcases h_limit with ⟨f_lim, hf_lim_meas, h_tendsto⟩, exact ⟨hf_lim_meas.to_Lp f_lim, tendsto_Lp_of_tendsto_ℒp f_lim hf_lim_meas h_tendsto⟩, }, have hB : summable B, from summable_geometric_two, cases hB with M hB, let B1 := λ n, ennreal.of_real (B n), have hB1_has : has_sum B1 (ennreal.of_real M), { have h_tsum_B1 : ∑' i, B1 i = (ennreal.of_real M), { change (∑' (n : ℕ), ennreal.of_real (B n)) = ennreal.of_real M, rw ←hB.tsum_eq, exact (ennreal.of_real_tsum_of_nonneg (λ n, le_of_lt (hB_pos n)) hB.summable).symm, }, have h_sum := (@ennreal.summable _ B1).has_sum, rwa h_tsum_B1 at h_sum, }, have hB1 : ∑' i, B1 i < ∞, by {rw hB1_has.tsum_eq, exact ennreal.of_real_lt_top, }, let f1 : ℕ → α → E := λ n, f n, refine H f1 (λ n, Lp.mem_ℒp (f n)) B1 hB1 (λ N n m hn hm, _), specialize hf N n m hn hm, rw dist_def at hf, simp_rw [f1, B1], rwa ennreal.lt_of_real_iff_to_real_lt, rw snorm_congr_ae (Lp.coe_fn_sub _ _).symm, exact Lp.snorm_ne_top _, end /-! ### Prove that controlled Cauchy sequences of `ℒp` have limits in `ℒp` -/ private lemma snorm'_sum_norm_sub_le_tsum_of_cauchy_snorm' {f : ℕ → α → E} (hf : ∀ n, ae_measurable (f n) μ) {p : ℝ} (hp1 : 1 ≤ p) {B : ℕ → ℝ≥0∞} (h_cau : ∀ (N n m : ℕ), N ≤ n → N ≤ m → snorm' (f n - f m) p μ < B N) (n : ℕ) : snorm' (λ x, ∑ i in finset.range (n + 1), norm (f (i + 1) x - f i x)) p μ ≤ ∑' i, B i := begin let f_norm_diff := λ i x, norm (f (i + 1) x - f i x), have hgf_norm_diff : ∀ n, (λ x, ∑ i in finset.range (n + 1), norm (f (i + 1) x - f i x)) = ∑ i in finset.range (n + 1), f_norm_diff i, from λ n, funext (λ x, by simp [f_norm_diff]), rw hgf_norm_diff, refine (snorm'_sum_le (λ i _, ((hf (i+1)).sub (hf i)).norm) hp1).trans _, simp_rw [←pi.sub_apply, snorm'_norm], refine (finset.sum_le_sum _).trans (sum_le_tsum _ (λ m _, zero_le _) ennreal.summable), exact λ m _, (h_cau m (m + 1) m (nat.le_succ m) (le_refl m)).le, end private lemma lintegral_rpow_sum_coe_nnnorm_sub_le_rpow_tsum {f : ℕ → α → E} (hf : ∀ n, ae_measurable (f n) μ) {p : ℝ} (hp1 : 1 ≤ p) {B : ℕ → ℝ≥0∞} (n : ℕ) (hn : snorm' (λ x, ∑ i in finset.range (n + 1), norm (f (i + 1) x - f i x)) p μ ≤ ∑' i, B i) : ∫⁻ a, (∑ i in finset.range (n + 1), nnnorm (f (i + 1) a - f i a) : ℝ≥0∞)^p ∂μ ≤ (∑' i, B i) ^ p := begin have hp_pos : 0 < p := zero_lt_one.trans_le hp1, rw [←one_div_one_div p, @ennreal.le_rpow_one_div_iff _ _ (1/p) (by simp [hp_pos]), one_div_one_div p], simp_rw snorm' at hn, have h_nnnorm_nonneg : (λ a, (nnnorm (∑ i in finset.range (n + 1), ∥f (i + 1) a - f i a∥) : ℝ≥0∞) ^ p) = λ a, (∑ i in finset.range (n + 1), (nnnorm(f (i + 1) a - f i a) : ℝ≥0∞)) ^ p, { ext1 a, congr, simp_rw ←of_real_norm_eq_coe_nnnorm, rw ←ennreal.of_real_sum_of_nonneg, { rw real.norm_of_nonneg _, exact finset.sum_nonneg (λ x hx, norm_nonneg _), }, { exact λ x hx, norm_nonneg _, }, }, change (∫⁻ a, (λ x, ↑(nnnorm (∑ i in finset.range (n + 1), ∥f (i+1) x - f i x∥))^p) a ∂μ)^(1/p) ≤ ∑' i, B i at hn, rwa h_nnnorm_nonneg at hn, end private lemma lintegral_rpow_tsum_coe_nnnorm_sub_le_tsum {f : ℕ → α → E} (hf : ∀ n, ae_measurable (f n) μ) {p : ℝ} (hp1 : 1 ≤ p) {B : ℕ → ℝ≥0∞} (h : ∀ n, ∫⁻ a, (∑ i in finset.range (n + 1), nnnorm (f (i + 1) a - f i a) : ℝ≥0∞)^p ∂μ ≤ (∑' i, B i) ^ p) : (∫⁻ a, (∑' i, nnnorm (f (i + 1) a - f i a) : ℝ≥0∞)^p ∂μ) ^ (1/p) ≤ ∑' i, B i := begin have hp_pos : 0 < p := zero_lt_one.trans_le hp1, suffices h_pow : ∫⁻ a, (∑' i, nnnorm (f (i + 1) a - f i a) : ℝ≥0∞)^p ∂μ ≤ (∑' i, B i) ^ p, by rwa [←@ennreal.le_rpow_one_div_iff _ _ (1/p) (by simp [hp_pos]), one_div_one_div], have h_tsum_1 : ∀ g : ℕ → ℝ≥0∞, ∑' i, g i = at_top.liminf (λ n, ∑ i in finset.range (n + 1), g i), by { intro g, rw [ennreal.tsum_eq_liminf_sum_nat, ← liminf_nat_add _ 1], }, simp_rw h_tsum_1 _, rw ← h_tsum_1, have h_liminf_pow : ∫⁻ a, at_top.liminf (λ n, ∑ i in finset.range (n + 1), (nnnorm (f (i + 1) a - f i a)))^p ∂μ = ∫⁻ a, at_top.liminf (λ n, (∑ i in finset.range (n + 1), (nnnorm (f (i + 1) a - f i a)))^p) ∂μ, { refine lintegral_congr (λ x, _), have h_rpow_mono := ennreal.rpow_left_strict_mono_of_pos (zero_lt_one.trans_le hp1), have h_rpow_surj := (ennreal.rpow_left_bijective hp_pos.ne.symm).2, refine (h_rpow_mono.order_iso_of_surjective _ h_rpow_surj).liminf_apply _ _ _ _, all_goals { is_bounded_default }, }, rw h_liminf_pow, refine (lintegral_liminf_le' _).trans _, { exact λ n, ae_measurable.ennreal_rpow_const (finset.ae_measurable_sum (finset.range (n+1)) (λ i, ((hf (i+1)).sub (hf i)).nnnorm.ennreal_coe)), }, { exact liminf_le_of_frequently_le' (frequently_of_forall h), }, end private lemma tsum_nnnorm_sub_ae_lt_top {f : ℕ → α → E} (hf : ∀ n, ae_measurable (f n) μ) {p : ℝ} (hp1 : 1 ≤ p) {B : ℕ → ℝ≥0∞} (hB : ∑' i, B i < ∞) (h : (∫⁻ a, (∑' i, nnnorm (f (i + 1) a - f i a) : ℝ≥0∞)^p ∂μ) ^ (1/p) ≤ ∑' i, B i) : ∀ᵐ x ∂μ, (∑' i, nnnorm (f (i + 1) x - f i x) : ℝ≥0∞) < ∞ := begin have hp_pos : 0 < p := zero_lt_one.trans_le hp1, have h_integral : ∫⁻ a, (∑' i, nnnorm (f (i + 1) a - f i a) : ℝ≥0∞)^p ∂μ < ∞, { have h_tsum_lt_top : (∑' i, B i) ^ p < ∞, from ennreal.rpow_lt_top_of_nonneg hp_pos.le (lt_top_iff_ne_top.mp hB), refine lt_of_le_of_lt _ h_tsum_lt_top, rwa [←@ennreal.le_rpow_one_div_iff _ _ (1/p) (by simp [hp_pos]), one_div_one_div] at h, }, have rpow_ae_lt_top : ∀ᵐ x ∂μ, (∑' i, nnnorm (f (i + 1) x - f i x) : ℝ≥0∞)^p < ∞, { refine ae_lt_top' (ae_measurable.ennreal_rpow_const _) h_integral, exact ae_measurable.ennreal_tsum (λ n, ((hf (n+1)).sub (hf n)).nnnorm.ennreal_coe), }, refine rpow_ae_lt_top.mono (λ x hx, _), rwa [←ennreal.lt_rpow_one_div_iff hp_pos, @ennreal.top_rpow_of_pos (1/p) (by simp [hp_pos])] at hx, end lemma ae_tendsto_of_cauchy_snorm' [complete_space E] {f : ℕ → α → E} {p : ℝ} (hf : ∀ n, ae_measurable (f n) μ) (hp1 : 1 ≤ p) {B : ℕ → ℝ≥0∞} (hB : ∑' i, B i < ∞) (h_cau : ∀ (N n m : ℕ), N ≤ n → N ≤ m → snorm' (f n - f m) p μ < B N) : ∀ᵐ x ∂μ, ∃ l : E, at_top.tendsto (λ n, f n x) (𝓝 l) := begin have h_summable : ∀ᵐ x ∂μ, summable (λ (i : ℕ), f (i + 1) x - f i x), { have h1 : ∀ n, snorm' (λ x, ∑ i in finset.range (n + 1), norm (f (i + 1) x - f i x)) p μ ≤ ∑' i, B i, from snorm'_sum_norm_sub_le_tsum_of_cauchy_snorm' hf hp1 h_cau, have h2 : ∀ n, ∫⁻ a, (∑ i in finset.range (n + 1), nnnorm (f (i + 1) a - f i a) : ℝ≥0∞)^p ∂μ ≤ (∑' i, B i) ^ p, from λ n, lintegral_rpow_sum_coe_nnnorm_sub_le_rpow_tsum hf hp1 n (h1 n), have h3 : (∫⁻ a, (∑' i, nnnorm (f (i + 1) a - f i a) : ℝ≥0∞)^p ∂μ) ^ (1/p) ≤ ∑' i, B i, from lintegral_rpow_tsum_coe_nnnorm_sub_le_tsum hf hp1 h2, have h4 : ∀ᵐ x ∂μ, (∑' i, nnnorm (f (i + 1) x - f i x) : ℝ≥0∞) < ∞, from tsum_nnnorm_sub_ae_lt_top hf hp1 hB h3, exact h4.mono (λ x hx, summable_of_summable_nnnorm (ennreal.tsum_coe_ne_top_iff_summable.mp (lt_top_iff_ne_top.mp hx))), }, have h : ∀ᵐ x ∂μ, ∃ l : E, at_top.tendsto (λ n, ∑ i in finset.range n, (f (i + 1) x - f i x)) (𝓝 l), { refine h_summable.mono (λ x hx, _), let hx_sum := (summable.has_sum_iff_tendsto_nat hx).mp hx.has_sum, exact ⟨∑' i, (f (i + 1) x - f i x), hx_sum⟩, }, refine h.mono (λ x hx, _), cases hx with l hx, have h_rw_sum : (λ n, ∑ i in finset.range n, (f (i + 1) x - f i x)) = λ n, f n x - f 0 x, { ext1 n, change ∑ (i : ℕ) in finset.range n, ((λ m, f m x) (i + 1) - (λ m, f m x) i) = f n x - f 0 x, rw finset.sum_range_sub, }, rw h_rw_sum at hx, have hf_rw : (λ n, f n x) = λ n, f n x - f 0 x + f 0 x, by { ext1 n, abel, }, rw hf_rw, exact ⟨l + f 0 x, tendsto.add_const _ hx⟩, end lemma ae_tendsto_of_cauchy_snorm [complete_space E] {f : ℕ → α → E} (hf : ∀ n, ae_measurable (f n) μ) (hp : 1 ≤ p) {B : ℕ → ℝ≥0∞} (hB : ∑' i, B i < ∞) (h_cau : ∀ (N n m : ℕ), N ≤ n → N ≤ m → snorm (f n - f m) p μ < B N) : ∀ᵐ x ∂μ, ∃ l : E, at_top.tendsto (λ n, f n x) (𝓝 l) := begin by_cases hp_top : p = ∞, { simp_rw [hp_top] at *, have h_cau_ae : ∀ᵐ x ∂μ, ∀ N n m, N ≤ n → N ≤ m → (nnnorm ((f n - f m) x) : ℝ≥0∞) < B N, { simp_rw [ae_all_iff, ae_imp_iff], exact λ N n m hnN hmN, ae_lt_of_ess_sup_lt (h_cau N n m hnN hmN), }, simp_rw [snorm_exponent_top, snorm_ess_sup] at h_cau, refine h_cau_ae.mono (λ x hx, cauchy_seq_tendsto_of_complete _), refine cauchy_seq_of_le_tendsto_0 (λ n, (B n).to_real) _ _, { intros n m N hnN hmN, specialize hx N n m hnN hmN, rw [dist_eq_norm, ←ennreal.to_real_of_real (norm_nonneg _), ennreal.to_real_le_to_real ennreal.of_real_ne_top ((ennreal.ne_top_of_tsum_ne_top (lt_top_iff_ne_top.mp hB)) N)], rw ←of_real_norm_eq_coe_nnnorm at hx, exact hx.le, }, { rw ← ennreal.zero_to_real, exact tendsto.comp (ennreal.tendsto_to_real ennreal.zero_ne_top) (ennreal.tendsto_at_top_zero_of_tsum_lt_top hB), }, }, have hp1 : 1 ≤ p.to_real, { rw [← ennreal.of_real_le_iff_le_to_real hp_top, ennreal.of_real_one], exact hp, }, have h_cau' : ∀ (N n m : ℕ), N ≤ n → N ≤ m → snorm' (f n - f m) (p.to_real) μ < B N, { intros N n m hn hm, specialize h_cau N n m hn hm, rwa snorm_eq_snorm' (ennreal.zero_lt_one.trans_le hp).ne.symm hp_top at h_cau, }, exact ae_tendsto_of_cauchy_snorm' hf hp1 hB h_cau', end lemma cauchy_tendsto_of_tendsto {f : ℕ → α → E} (hf : ∀ n, ae_measurable (f n) μ) (f_lim : α → E) {B : ℕ → ℝ≥0∞} (hB : ∑' i, B i < ∞) (h_cau : ∀ (N n m : ℕ), N ≤ n → N ≤ m → snorm (f n - f m) p μ < B N) (h_lim : ∀ᵐ (x : α) ∂μ, tendsto (λ n, f n x) at_top (𝓝 (f_lim x))) : at_top.tendsto (λ n, snorm (f n - f_lim) p μ) (𝓝 0) := begin rw ennreal.tendsto_at_top_zero, intros ε hε, have h_B : ∃ (N : ℕ), B N ≤ ε, { suffices h_tendsto_zero : ∃ (N : ℕ), ∀ n : ℕ, N ≤ n → B n ≤ ε, from ⟨h_tendsto_zero.some, h_tendsto_zero.some_spec _ (le_refl _)⟩, exact (ennreal.tendsto_at_top_zero.mp (ennreal.tendsto_at_top_zero_of_tsum_lt_top hB)) ε hε, }, cases h_B with N h_B, refine ⟨N, λ n hn, _⟩, have h_sub : snorm (f n - f_lim) p μ ≤ at_top.liminf (λ m, snorm (f n - f m) p μ), { refine snorm_lim_le_liminf_snorm (λ m, (hf n).sub (hf m)) (f n - f_lim) _, refine h_lim.mono (λ x hx, _), simp_rw sub_eq_add_neg, exact tendsto.add tendsto_const_nhds (tendsto.neg hx), }, refine h_sub.trans _, refine liminf_le_of_frequently_le' (frequently_at_top.mpr _), refine λ N1, ⟨max N N1, le_max_right _ _, _⟩, exact (h_cau N n (max N N1) hn (le_max_left _ _)).le.trans h_B, end lemma mem_ℒp_of_cauchy_tendsto (hp : 1 ≤ p) {f : ℕ → α → E} (hf : ∀ n, mem_ℒp (f n) p μ) (f_lim : α → E) (h_lim_meas : ae_measurable f_lim μ) (h_tendsto : at_top.tendsto (λ n, snorm (f n - f_lim) p μ) (𝓝 0)) : mem_ℒp f_lim p μ := begin refine ⟨h_lim_meas, _⟩, rw ennreal.tendsto_at_top_zero at h_tendsto, cases (h_tendsto 1 ennreal.zero_lt_one) with N h_tendsto_1, specialize h_tendsto_1 N (le_refl N), have h_add : f_lim = f_lim - f N + f N, by abel, rw h_add, refine lt_of_le_of_lt (snorm_add_le (h_lim_meas.sub (hf N).1) (hf N).1 hp) _, rw ennreal.add_lt_top, split, { refine lt_of_le_of_lt _ ennreal.one_lt_top, have h_neg : f_lim - f N = -(f N - f_lim), by simp, rwa [h_neg, snorm_neg], }, { exact (hf N).2, }, end lemma cauchy_complete_ℒp [complete_space E] (hp : 1 ≤ p) {f : ℕ → α → E} (hf : ∀ n, mem_ℒp (f n) p μ) {B : ℕ → ℝ≥0∞} (hB : ∑' i, B i < ∞) (h_cau : ∀ (N n m : ℕ), N ≤ n → N ≤ m → snorm (f n - f m) p μ < B N) : ∃ (f_lim : α → E) (hf_lim_meas : mem_ℒp f_lim p μ), at_top.tendsto (λ n, snorm (f n - f_lim) p μ) (𝓝 0) := begin obtain ⟨f_lim, h_f_lim_meas, h_lim⟩ : ∃ (f_lim : α → E) (hf_lim_meas : measurable f_lim), ∀ᵐ x ∂μ, tendsto (λ n, f n x) at_top (nhds (f_lim x)), from measurable_limit_of_tendsto_metric_ae (λ n, (hf n).1) (ae_tendsto_of_cauchy_snorm (λ n, (hf n).1) hp hB h_cau), have h_tendsto' : at_top.tendsto (λ n, snorm (f n - f_lim) p μ) (𝓝 0), from cauchy_tendsto_of_tendsto (λ m, (hf m).1) f_lim hB h_cau h_lim, have h_ℒp_lim : mem_ℒp f_lim p μ, from mem_ℒp_of_cauchy_tendsto hp hf f_lim h_f_lim_meas.ae_measurable h_tendsto', exact ⟨f_lim, h_ℒp_lim, h_tendsto'⟩, end /-! ### `Lp` is complete for `1 ≤ p` -/ instance [complete_space E] [hp : fact (1 ≤ p)] : complete_space (Lp E p μ) := complete_space_Lp_of_cauchy_complete_ℒp (λ f hf B hB h_cau, cauchy_complete_ℒp hp.elim hf hB h_cau) end Lp end measure_theory end complete_space
614adc01617360b3783f053c9c599a3f79ba2a57
4727251e0cd73359b15b664c3170e5d754078599
/src/data/polynomial/ring_division.lean
8943000d89706c0d34de513d616f946382877587
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
30,240
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker, Johan Commelin -/ import data.polynomial.algebra_map import data.polynomial.degree.lemmas import data.polynomial.div /-! # Theory of univariate polynomials This file starts looking like the ring theory of $ R[X] $ -/ noncomputable theory open_locale classical polynomial open finset namespace polynomial universes u v w z variables {R : Type u} {S : Type v} {T : Type w} {A : Type z} {a b : R} {n : ℕ} section comm_ring variables [comm_ring R] {p q : R[X]} section variables [semiring S] lemma nat_degree_pos_of_aeval_root [algebra R S] {p : R[X]} (hp : p ≠ 0) {z : S} (hz : aeval z p = 0) (inj : ∀ (x : R), algebra_map R S x = 0 → x = 0) : 0 < p.nat_degree := nat_degree_pos_of_eval₂_root hp (algebra_map R S) hz inj lemma degree_pos_of_aeval_root [algebra R S] {p : R[X]} (hp : p ≠ 0) {z : S} (hz : aeval z p = 0) (inj : ∀ (x : R), algebra_map R S x = 0 → x = 0) : 0 < p.degree := nat_degree_pos_iff_degree_pos.mp (nat_degree_pos_of_aeval_root hp hz inj) lemma mod_by_monic_eq_of_dvd_sub (hq : q.monic) {p₁ p₂ : R[X]} (h : q ∣ (p₁ - p₂)) : p₁ %ₘ q = p₂ %ₘ q := begin nontriviality R, obtain ⟨f, sub_eq⟩ := h, refine (div_mod_by_monic_unique (p₂ /ₘ q + f) _ hq ⟨_, degree_mod_by_monic_lt _ hq⟩).2, rw [sub_eq_iff_eq_add.mp sub_eq, mul_add, ← add_assoc, mod_by_monic_add_div _ hq, add_comm] end lemma add_mod_by_monic (p₁ p₂ : R[X]) : (p₁ + p₂) %ₘ q = p₁ %ₘ q + p₂ %ₘ q := begin by_cases hq : q.monic, { nontriviality R, exact (div_mod_by_monic_unique (p₁ /ₘ q + p₂ /ₘ q) _ hq ⟨by rw [mul_add, add_left_comm, add_assoc, mod_by_monic_add_div _ hq, ← add_assoc, add_comm (q * _), mod_by_monic_add_div _ hq], (degree_add_le _ _).trans_lt (max_lt (degree_mod_by_monic_lt _ hq) (degree_mod_by_monic_lt _ hq))⟩).2 }, { simp_rw mod_by_monic_eq_of_not_monic _ hq } end lemma smul_mod_by_monic (c : R) (p : R[X]) : (c • p) %ₘ q = c • (p %ₘ q) := begin by_cases hq : q.monic, { nontriviality R, exact (div_mod_by_monic_unique (c • (p /ₘ q)) (c • (p %ₘ q)) hq ⟨by rw [mul_smul_comm, ← smul_add, mod_by_monic_add_div p hq], (degree_smul_le _ _).trans_lt (degree_mod_by_monic_lt _ hq)⟩).2 }, { simp_rw mod_by_monic_eq_of_not_monic _ hq } end /-- `_ %ₘ q` as an `R`-linear map. -/ @[simps] def mod_by_monic_hom (q : R[X]) : R[X] →ₗ[R] R[X] := { to_fun := λ p, p %ₘ q, map_add' := add_mod_by_monic, map_smul' := smul_mod_by_monic } end section variables [ring S] lemma aeval_mod_by_monic_eq_self_of_root [algebra R S] {p q : R[X]} (hq : q.monic) {x : S} (hx : aeval x q = 0) : aeval x (p %ₘ q) = aeval x p := -- `eval₂_mod_by_monic_eq_self_of_root` doesn't work here as it needs commutativity by rw [mod_by_monic_eq_sub_mul_div p hq, _root_.map_sub, _root_.map_mul, hx, zero_mul, sub_zero] end end comm_ring section no_zero_divisors variables [semiring R] [no_zero_divisors R] {p q : R[X]} instance : no_zero_divisors R[X] := { eq_zero_or_eq_zero_of_mul_eq_zero := λ a b h, begin rw [← leading_coeff_eq_zero, ← leading_coeff_eq_zero], refine eq_zero_or_eq_zero_of_mul_eq_zero _, rw [← leading_coeff_zero, ← leading_coeff_mul, h], end } lemma nat_degree_mul (hp : p ≠ 0) (hq : q ≠ 0) : nat_degree (p * q) = nat_degree p + nat_degree q := by rw [← with_bot.coe_eq_coe, ← degree_eq_nat_degree (mul_ne_zero hp hq), with_bot.coe_add, ← degree_eq_nat_degree hp, ← degree_eq_nat_degree hq, degree_mul] @[simp] lemma nat_degree_pow (p : R[X]) (n : ℕ) : nat_degree (p ^ n) = n * nat_degree p := if hp0 : p = 0 then if hn0 : n = 0 then by simp [hp0, hn0] else by rw [hp0, zero_pow (nat.pos_of_ne_zero hn0)]; simp else nat_degree_pow' (by rw [← leading_coeff_pow, ne.def, leading_coeff_eq_zero]; exact pow_ne_zero _ hp0) lemma degree_le_mul_left (p : R[X]) (hq : q ≠ 0) : degree p ≤ degree (p * q) := if hp : p = 0 then by simp only [hp, zero_mul, le_refl] else by rw [degree_mul, degree_eq_nat_degree hp, degree_eq_nat_degree hq]; exact with_bot.coe_le_coe.2 (nat.le_add_right _ _) theorem nat_degree_le_of_dvd {p q : R[X]} (h1 : p ∣ q) (h2 : q ≠ 0) : p.nat_degree ≤ q.nat_degree := begin rcases h1 with ⟨q, rfl⟩, rw mul_ne_zero_iff at h2, rw [nat_degree_mul h2.1 h2.2], exact nat.le_add_right _ _ end /-- This lemma is useful for working with the `int_degree` of a rational function. -/ lemma nat_degree_sub_eq_of_prod_eq {p₁ p₂ q₁ q₂ : polynomial R} (hp₁ : p₁ ≠ 0) (hq₁ : q₁ ≠ 0) (hp₂ : p₂ ≠ 0) (hq₂ : q₂ ≠ 0) (h_eq : p₁ * q₂ = p₂ * q₁) : (p₁.nat_degree : ℤ) - q₁.nat_degree = (p₂.nat_degree : ℤ) - q₂.nat_degree := begin rw sub_eq_sub_iff_add_eq_add, norm_cast, rw [← nat_degree_mul hp₁ hq₂, ← nat_degree_mul hp₂ hq₁, h_eq] end end no_zero_divisors section no_zero_divisors variables [comm_semiring R] [no_zero_divisors R] {p q : R[X]} lemma root_mul : is_root (p * q) a ↔ is_root p a ∨ is_root q a := by simp_rw [is_root, eval_mul, mul_eq_zero] lemma root_or_root_of_root_mul (h : is_root (p * q) a) : is_root p a ∨ is_root q a := root_mul.1 h end no_zero_divisors section ring variables [ring R] [is_domain R] {p q : R[X]} instance : is_domain R[X] := { ..polynomial.no_zero_divisors, ..polynomial.nontrivial, } lemma nat_trailing_degree_mul (hp : p ≠ 0) (hq : q ≠ 0) : (p * q).nat_trailing_degree = p.nat_trailing_degree + q.nat_trailing_degree := begin simp only [←tsub_eq_of_eq_add_rev (nat_degree_eq_reverse_nat_degree_add_nat_trailing_degree _)], rw [reverse_mul_of_domain, nat_degree_mul hp hq, nat_degree_mul (mt reverse_eq_zero.mp hp) (mt reverse_eq_zero.mp hq), reverse_nat_degree, reverse_nat_degree, tsub_add_eq_tsub_tsub, nat.add_comm, add_tsub_assoc_of_le (nat.sub_le _ _), add_comm, add_tsub_assoc_of_le (nat.sub_le _ _)], end end ring section comm_ring variables [comm_ring R] [is_domain R] {p q : R[X]} section roots open multiset lemma degree_eq_zero_of_is_unit (h : is_unit p) : degree p = 0 := let ⟨q, hq⟩ := is_unit_iff_dvd_one.1 h in have hp0 : p ≠ 0, from λ hp0, by simpa [hp0] using hq, have hq0 : q ≠ 0, from λ hp0, by simpa [hp0] using hq, have nat_degree (1 : R[X]) = nat_degree (p * q), from congr_arg _ hq, by rw [nat_degree_one, nat_degree_mul hp0 hq0, eq_comm, _root_.add_eq_zero_iff, ← with_bot.coe_eq_coe, ← degree_eq_nat_degree hp0] at this; exact this.1 @[simp] lemma degree_coe_units (u : R[X]ˣ) : degree (u : R[X]) = 0 := degree_eq_zero_of_is_unit ⟨u, rfl⟩ theorem prime_X_sub_C (r : R) : prime (X - C r) := ⟨X_sub_C_ne_zero r, not_is_unit_X_sub_C r, λ _ _, by { simp_rw [dvd_iff_is_root, is_root.def, eval_mul, mul_eq_zero], exact id }⟩ theorem prime_X : prime (X : R[X]) := by { convert (prime_X_sub_C (0 : R)), simp } lemma monic.prime_of_degree_eq_one (hp1 : degree p = 1) (hm : monic p) : prime p := have p = X - C (- p.coeff 0), by simpa [hm.leading_coeff] using eq_X_add_C_of_degree_eq_one hp1, this.symm ▸ prime_X_sub_C _ theorem irreducible_X_sub_C (r : R) : irreducible (X - C r) := (prime_X_sub_C r).irreducible theorem irreducible_X : irreducible (X : R[X]) := prime.irreducible prime_X lemma monic.irreducible_of_degree_eq_one (hp1 : degree p = 1) (hm : monic p) : irreducible p := (hm.prime_of_degree_eq_one hp1).irreducible theorem eq_of_monic_of_associated (hp : p.monic) (hq : q.monic) (hpq : associated p q) : p = q := begin obtain ⟨u, hu⟩ := hpq, unfold monic at hp hq, rw eq_C_of_degree_le_zero (le_of_eq $ degree_coe_units _) at hu, rw [← hu, leading_coeff_mul, hp, one_mul, leading_coeff_C] at hq, rwa [hq, C_1, mul_one] at hu, apply_instance, end lemma root_multiplicity_mul {p q : R[X]} {x : R} (hpq : p * q ≠ 0) : root_multiplicity x (p * q) = root_multiplicity x p + root_multiplicity x q := begin have hp : p ≠ 0 := left_ne_zero_of_mul hpq, have hq : q ≠ 0 := right_ne_zero_of_mul hpq, rw [root_multiplicity_eq_multiplicity (p * q), dif_neg hpq, root_multiplicity_eq_multiplicity p, dif_neg hp, root_multiplicity_eq_multiplicity q, dif_neg hq, multiplicity.mul' (prime_X_sub_C x)], end lemma root_multiplicity_X_sub_C_self {x : R} : root_multiplicity x (X - C x) = 1 := by rw [root_multiplicity_eq_multiplicity, dif_neg (X_sub_C_ne_zero x), multiplicity.get_multiplicity_self] lemma root_multiplicity_X_sub_C {x y : R} : root_multiplicity x (X - C y) = if x = y then 1 else 0 := begin split_ifs with hxy, { rw hxy, exact root_multiplicity_X_sub_C_self }, exact root_multiplicity_eq_zero (mt root_X_sub_C.mp (ne.symm hxy)) end /-- The multiplicity of `a` as root of `(X - a) ^ n` is `n`. -/ lemma root_multiplicity_X_sub_C_pow (a : R) (n : ℕ) : root_multiplicity a ((X - C a) ^ n) = n := begin induction n with n hn, { refine root_multiplicity_eq_zero _, simp only [eval_one, is_root.def, not_false_iff, one_ne_zero, pow_zero] }, have hzero := pow_ne_zero n.succ (X_sub_C_ne_zero a), rw pow_succ (X - C a) n at hzero ⊢, simp only [root_multiplicity_mul hzero, root_multiplicity_X_sub_C_self, hn, nat.one_add] end /-- If `(X - a) ^ n` divides a polynomial `p` then the multiplicity of `a` as root of `p` is at least `n`. -/ lemma root_multiplicity_of_dvd {p : R[X]} {a : R} {n : ℕ} (hzero : p ≠ 0) (h : (X - C a) ^ n ∣ p) : n ≤ root_multiplicity a p := begin obtain ⟨q, hq⟩ := exists_eq_mul_right_of_dvd h, rw hq at hzero, simp only [hq, root_multiplicity_mul hzero, root_multiplicity_X_sub_C_pow, ge_iff_le, _root_.zero_le, le_add_iff_nonneg_right], end /-- The multiplicity of `p + q` is at least the minimum of the multiplicities. -/ lemma root_multiplicity_add {p q : R[X]} (a : R) (hzero : p + q ≠ 0) : min (root_multiplicity a p) (root_multiplicity a q) ≤ root_multiplicity a (p + q) := begin refine root_multiplicity_of_dvd hzero _, have hdivp : (X - C a) ^ root_multiplicity a p ∣ p := pow_root_multiplicity_dvd p a, have hdivq : (X - C a) ^ root_multiplicity a q ∣ q := pow_root_multiplicity_dvd q a, exact min_pow_dvd_add hdivp hdivq end lemma exists_multiset_roots : ∀ {p : R[X]} (hp : p ≠ 0), ∃ s : multiset R, (s.card : with_bot ℕ) ≤ degree p ∧ ∀ a, s.count a = root_multiplicity a p | p := λ hp, by haveI := classical.prop_decidable (∃ x, is_root p x); exact if h : ∃ x, is_root p x then let ⟨x, hx⟩ := h in have hpd : 0 < degree p := degree_pos_of_root hp hx, have hd0 : p /ₘ (X - C x) ≠ 0 := λ h, by rw [← mul_div_by_monic_eq_iff_is_root.2 hx, h, mul_zero] at hp; exact hp rfl, have wf : degree (p /ₘ _) < degree p := degree_div_by_monic_lt _ (monic_X_sub_C x) hp ((degree_X_sub_C x).symm ▸ dec_trivial), let ⟨t, htd, htr⟩ := @exists_multiset_roots (p /ₘ (X - C x)) hd0 in have hdeg : degree (X - C x) ≤ degree p := begin rw [degree_X_sub_C, degree_eq_nat_degree hp], rw degree_eq_nat_degree hp at hpd, exact with_bot.coe_le_coe.2 (with_bot.coe_lt_coe.1 hpd) end, have hdiv0 : p /ₘ (X - C x) ≠ 0 := mt (div_by_monic_eq_zero_iff (monic_X_sub_C x)).1 $ not_lt.2 hdeg, ⟨x ::ₘ t, calc (card (x ::ₘ t) : with_bot ℕ) = t.card + 1 : by exact_mod_cast card_cons _ _ ... ≤ degree p : by rw [← degree_add_div_by_monic (monic_X_sub_C x) hdeg, degree_X_sub_C, add_comm]; exact add_le_add (le_refl (1 : with_bot ℕ)) htd, begin assume a, conv_rhs { rw ← mul_div_by_monic_eq_iff_is_root.mpr hx }, rw [root_multiplicity_mul (mul_ne_zero (X_sub_C_ne_zero x) hdiv0), root_multiplicity_X_sub_C, ← htr a], split_ifs with ha, { rw [ha, count_cons_self, nat.succ_eq_add_one, add_comm] }, { rw [count_cons_of_ne ha, zero_add] }, end⟩ else ⟨0, (degree_eq_nat_degree hp).symm ▸ with_bot.coe_le_coe.2 (nat.zero_le _), by { intro a, rw [count_zero, root_multiplicity_eq_zero (not_exists.mp h a)] }⟩ using_well_founded {dec_tac := tactic.assumption} /-- `roots p` noncomputably gives a multiset containing all the roots of `p`, including their multiplicities. -/ noncomputable def roots (p : R[X]) : multiset R := if h : p = 0 then ∅ else classical.some (exists_multiset_roots h) @[simp] lemma roots_zero : (0 : R[X]).roots = 0 := dif_pos rfl lemma card_roots (hp0 : p ≠ 0) : ((roots p).card : with_bot ℕ) ≤ degree p := begin unfold roots, rw dif_neg hp0, exact (classical.some_spec (exists_multiset_roots hp0)).1 end lemma card_roots' (p : R[X]) : p.roots.card ≤ nat_degree p := begin by_cases hp0 : p = 0, { simp [hp0], }, exact with_bot.coe_le_coe.1 (le_trans (card_roots hp0) (le_of_eq $ degree_eq_nat_degree hp0)) end lemma card_roots_sub_C {p : R[X]} {a : R} (hp0 : 0 < degree p) : ((p - C a).roots.card : with_bot ℕ) ≤ degree p := calc ((p - C a).roots.card : with_bot ℕ) ≤ degree (p - C a) : card_roots $ mt sub_eq_zero.1 $ λ h, not_le_of_gt hp0 $ h.symm ▸ degree_C_le ... = degree p : by rw [sub_eq_add_neg, ← C_neg]; exact degree_add_C hp0 lemma card_roots_sub_C' {p : R[X]} {a : R} (hp0 : 0 < degree p) : (p - C a).roots.card ≤ nat_degree p := with_bot.coe_le_coe.1 (le_trans (card_roots_sub_C hp0) (le_of_eq $ degree_eq_nat_degree (λ h, by simp [*, lt_irrefl] at *))) @[simp] lemma count_roots (p : R[X]) : p.roots.count a = root_multiplicity a p := begin by_cases hp : p = 0, { simp [hp], }, rw [roots, dif_neg hp], exact (classical.some_spec (exists_multiset_roots hp)).2 a end @[simp] lemma mem_roots (hp : p ≠ 0) : a ∈ p.roots ↔ is_root p a := by rw [← count_pos, count_roots p, root_multiplicity_pos hp] theorem card_le_degree_of_subset_roots {p : R[X]} {Z : finset R} (h : Z.val ⊆ p.roots) : Z.card ≤ p.nat_degree := (multiset.card_le_of_le (finset.val_le_iff_val_subset.2 h)).trans (polynomial.card_roots' p) lemma eq_zero_of_infinite_is_root (p : R[X]) (h : set.infinite {x | is_root p x}) : p = 0 := begin by_contradiction hp, apply h, convert p.roots.to_finset.finite_to_set using 1, ext1 r, simp only [mem_roots hp, multiset.mem_to_finset, set.mem_set_of_eq, finset.mem_coe] end lemma exists_max_root [linear_order R] (p : R[X]) (hp : p ≠ 0) : ∃ x₀, ∀ x, p.is_root x → x ≤ x₀ := set.exists_upper_bound_image _ _ $ not_not.mp (mt (eq_zero_of_infinite_is_root p) hp) lemma exists_min_root [linear_order R] (p : R[X]) (hp : p ≠ 0) : ∃ x₀, ∀ x, p.is_root x → x₀ ≤ x := set.exists_lower_bound_image _ _ $ not_not.mp (mt (eq_zero_of_infinite_is_root p) hp) lemma eq_of_infinite_eval_eq {R : Type*} [comm_ring R] [is_domain R] (p q : R[X]) (h : set.infinite {x | eval x p = eval x q}) : p = q := begin rw [← sub_eq_zero], apply eq_zero_of_infinite_is_root, simpa only [is_root, eval_sub, sub_eq_zero] end lemma roots_mul {p q : R[X]} (hpq : p * q ≠ 0) : (p * q).roots = p.roots + q.roots := multiset.ext.mpr $ λ r, by rw [count_add, count_roots, count_roots, count_roots, root_multiplicity_mul hpq] lemma roots.le_of_dvd (h : q ≠ 0) : p ∣ q → roots p ≤ roots q := begin rintro ⟨k, rfl⟩, exact multiset.le_iff_exists_add.mpr ⟨k.roots, roots_mul h⟩ end @[simp] lemma mem_roots_sub_C {p : R[X]} {a x : R} (hp0 : 0 < degree p) : x ∈ (p - C a).roots ↔ p.eval x = a := (mem_roots (show p - C a ≠ 0, from mt sub_eq_zero.1 $ λ h, not_le_of_gt hp0 $ h.symm ▸ degree_C_le)).trans (by rw [is_root.def, eval_sub, eval_C, sub_eq_zero]) @[simp] lemma roots_X_sub_C (r : R) : roots (X - C r) = {r} := begin ext s, rw [count_roots, root_multiplicity_X_sub_C], split_ifs with h, { rw [h, count_singleton_self] }, { rw [singleton_eq_cons, count_cons_of_ne h, count_zero] } end @[simp] lemma roots_C (x : R) : (C x).roots = 0 := if H : x = 0 then by rw [H, C_0, roots_zero] else multiset.ext.mpr $ λ r, by rw [count_roots, count_zero, root_multiplicity_eq_zero (not_is_root_C _ _ H)] @[simp] lemma roots_one : (1 : R[X]).roots = ∅ := roots_C 1 lemma roots_smul_nonzero (p : R[X]) {r : R} (hr : r ≠ 0) : (r • p).roots = p.roots := begin by_cases hp : p = 0; simp [smul_eq_C_mul, roots_mul, hr, hp] end lemma roots_list_prod (L : list R[X]) : ((0 : R[X]) ∉ L) → L.prod.roots = (L : multiset R[X]).bind roots := list.rec_on L (λ _, roots_one) $ λ hd tl ih H, begin rw [list.mem_cons_iff, not_or_distrib] at H, rw [list.prod_cons, roots_mul (mul_ne_zero (ne.symm H.1) $ list.prod_ne_zero H.2), ← multiset.cons_coe, multiset.cons_bind, ih H.2] end lemma roots_multiset_prod (m : multiset R[X]) : (0 : R[X]) ∉ m → m.prod.roots = m.bind roots := by { rcases m with ⟨L⟩, simpa only [coe_prod, quot_mk_to_coe''] using roots_list_prod L } lemma roots_prod {ι : Type*} (f : ι → R[X]) (s : finset ι) : s.prod f ≠ 0 → (s.prod f).roots = s.val.bind (λ i, roots (f i)) := begin rcases s with ⟨m, hm⟩, simpa [multiset.prod_eq_zero_iff, bind_map] using roots_multiset_prod (m.map f) end lemma roots_prod_X_sub_C (s : finset R) : (s.prod (λ a, X - C a)).roots = s.val := (roots_prod (λ a, X - C a) s (prod_ne_zero_iff.mpr (λ a _, X_sub_C_ne_zero a))).trans (by simp_rw [roots_X_sub_C, multiset.bind_singleton, multiset.map_id']) lemma card_roots_X_pow_sub_C {n : ℕ} (hn : 0 < n) (a : R) : (roots ((X : R[X]) ^ n - C a)).card ≤ n := with_bot.coe_le_coe.1 $ calc ((roots ((X : R[X]) ^ n - C a)).card : with_bot ℕ) ≤ degree ((X : R[X]) ^ n - C a) : card_roots (X_pow_sub_C_ne_zero hn a) ... = n : degree_X_pow_sub_C hn a lemma le_root_multiplicity_map {K L : Type*} [comm_ring K] [comm_ring L] {p : K[X]} {f : K →+* L} (hf : function.injective f) (a : K) : root_multiplicity a p ≤ root_multiplicity (f a) (map f p) := begin by_cases hp0 : p = 0, { simp only [hp0, root_multiplicity_zero, polynomial.map_zero], }, have hmap : map f p ≠ 0, { simpa only [polynomial.map_zero] using (map_injective f hf).ne hp0, }, rw [root_multiplicity, root_multiplicity, dif_neg hp0, dif_neg hmap], simp only [not_not, nat.lt_find_iff, nat.le_find_iff], intros m hm, have := ring_hom.map_dvd (map_ring_hom f) (hm m le_rfl), simpa only [coe_map_ring_hom, map_pow, map_sub, map_X, map_C], end lemma count_map_roots {K L : Type*} [comm_ring K] [is_domain K] [comm_ring L] {p : K[X]} {f : K →+* L} (hf : function.injective f) (a : L) : count a (multiset.map f p.roots) ≤ root_multiplicity a (map f p) := begin by_cases h : ∃ t, f t = a, { rcases h with ⟨h_w, rfl⟩, rw [multiset.count_map_eq_count' f _ hf, count_roots], exact le_root_multiplicity_map hf h_w }, { suffices : multiset.count a (multiset.map f p.roots) = 0, { rw this, exact zero_le _, }, rw [multiset.count_map, multiset.card_eq_zero, multiset.filter_eq_nil], rintro k hk rfl, exact h ⟨k, rfl⟩, }, end lemma roots_map_of_injective_card_eq_total_degree {K L : Type*} [comm_ring K] [is_domain K] [comm_ring L] [is_domain L] {p : K[X]} {f : K →+* L} (hf : function.injective f) (hroots : p.roots.card = p.nat_degree) : multiset.map f p.roots = (map f p).roots := begin by_cases hp0 : p = 0, { simp only [hp0, roots_zero, multiset.map_zero, polynomial.map_zero], }, have hmap : map f p ≠ 0, { simpa only [polynomial.map_zero] using (map_injective f hf).ne hp0, }, apply multiset.eq_of_le_of_card_le, { simpa only [multiset.le_iff_count, count_roots] using count_map_roots hf }, { simpa only [multiset.card_map, hroots] using (card_roots' _).trans (nat_degree_map_le f p) }, end section nth_roots /-- `nth_roots n a` noncomputably returns the solutions to `x ^ n = a`-/ def nth_roots (n : ℕ) (a : R) : multiset R := roots ((X : R[X]) ^ n - C a) @[simp] lemma mem_nth_roots {n : ℕ} (hn : 0 < n) {a x : R} : x ∈ nth_roots n a ↔ x ^ n = a := by rw [nth_roots, mem_roots (X_pow_sub_C_ne_zero hn a), is_root.def, eval_sub, eval_C, eval_pow, eval_X, sub_eq_zero] @[simp] lemma nth_roots_zero (r : R) : nth_roots 0 r = 0 := by simp only [empty_eq_zero, pow_zero, nth_roots, ← C_1, ← C_sub, roots_C] lemma card_nth_roots (n : ℕ) (a : R) : (nth_roots n a).card ≤ n := if hn : n = 0 then if h : (X : R[X]) ^ n - C a = 0 then by simp only [nat.zero_le, nth_roots, roots, h, dif_pos rfl, empty_eq_zero, card_zero] else with_bot.coe_le_coe.1 (le_trans (card_roots h) (by { rw [hn, pow_zero, ← C_1, ← ring_hom.map_sub ], exact degree_C_le })) else by rw [← with_bot.coe_le_coe, ← degree_X_pow_sub_C (nat.pos_of_ne_zero hn) a]; exact card_roots (X_pow_sub_C_ne_zero (nat.pos_of_ne_zero hn) a) /-- The multiset `nth_roots ↑n (1 : R)` as a finset. -/ def nth_roots_finset (n : ℕ) (R : Type*) [comm_ring R] [is_domain R] : finset R := multiset.to_finset (nth_roots n (1 : R)) @[simp] lemma mem_nth_roots_finset {n : ℕ} (h : 0 < n) {x : R} : x ∈ nth_roots_finset n R ↔ x ^ (n : ℕ) = 1 := by rw [nth_roots_finset, mem_to_finset, mem_nth_roots h] @[simp] lemma nth_roots_finset_zero : nth_roots_finset 0 R = ∅ := by simp [nth_roots_finset] end nth_roots lemma monic.comp (hp : p.monic) (hq : q.monic) (h : q.nat_degree ≠ 0) : (p.comp q).monic := by rw [monic.def, leading_coeff_comp h, monic.def.1 hp, monic.def.1 hq, one_pow, one_mul] lemma monic.comp_X_add_C (hp : p.monic) (r : R) : (p.comp (X + C r)).monic := begin refine hp.comp (monic_X_add_C _) (λ ha, _), rw [nat_degree_X_add_C] at ha, exact one_ne_zero ha end lemma monic.comp_X_sub_C (hp : p.monic) (r : R) : (p.comp (X - C r)).monic := by simpa using hp.comp_X_add_C (-r) lemma units_coeff_zero_smul (c : R[X]ˣ) (p : R[X]) : (c : R[X]).coeff 0 • p = c * p := by rw [←polynomial.C_mul', ←polynomial.eq_C_of_degree_eq_zero (degree_coe_units c)] @[simp] lemma nat_degree_coe_units (u : R[X]ˣ) : nat_degree (u : R[X]) = 0 := nat_degree_eq_of_degree_eq_some (degree_coe_units u) lemma comp_eq_zero_iff : p.comp q = 0 ↔ p = 0 ∨ (p.eval (q.coeff 0) = 0 ∧ q = C (q.coeff 0)) := begin split, { intro h, have key : p.nat_degree = 0 ∨ q.nat_degree = 0, { rw [←mul_eq_zero, ←nat_degree_comp, h, nat_degree_zero] }, replace key := or.imp eq_C_of_nat_degree_eq_zero eq_C_of_nat_degree_eq_zero key, cases key, { rw [key, C_comp] at h, exact or.inl (key.trans h) }, { rw [key, comp_C, C_eq_zero] at h, exact or.inr ⟨h, key⟩ }, }, { exact λ h, or.rec (λ h, by rw [h, zero_comp]) (λ h, by rw [h.2, comp_C, h.1, C_0]) h }, end lemma zero_of_eval_zero [infinite R] (p : R[X]) (h : ∀ x, p.eval x = 0) : p = 0 := by classical; by_contradiction hp; exact fintype.false ⟨p.roots.to_finset, λ x, multiset.mem_to_finset.mpr ((mem_roots hp).mpr (h _))⟩ lemma funext [infinite R] {p q : R[X]} (ext : ∀ r : R, p.eval r = q.eval r) : p = q := begin rw ← sub_eq_zero, apply zero_of_eval_zero, intro x, rw [eval_sub, sub_eq_zero, ext], end variables [comm_ring T] /-- The set of distinct roots of `p` in `E`. If you have a non-separable polynomial, use `polynomial.roots` for the multiset where multiple roots have the appropriate multiplicity. -/ def root_set (p : T[X]) (S) [comm_ring S] [is_domain S] [algebra T S] : set S := (p.map (algebra_map T S)).roots.to_finset lemma root_set_def (p : T[X]) (S) [comm_ring S] [is_domain S] [algebra T S] : p.root_set S = (p.map (algebra_map T S)).roots.to_finset := rfl @[simp] lemma root_set_zero (S) [comm_ring S] [is_domain S] [algebra T S] : (0 : T[X]).root_set S = ∅ := by rw [root_set_def, polynomial.map_zero, roots_zero, to_finset_zero, finset.coe_empty] @[simp] lemma root_set_C [comm_ring S] [is_domain S] [algebra T S] (a : T) : (C a).root_set S = ∅ := by rw [root_set_def, map_C, roots_C, multiset.to_finset_zero, finset.coe_empty] instance root_set_fintype (p : T[X]) (S : Type*) [comm_ring S] [is_domain S] [algebra T S] : fintype (p.root_set S) := finset_coe.fintype _ lemma root_set_finite (p : T[X]) (S : Type*) [comm_ring S] [is_domain S] [algebra T S] : (p.root_set S).finite := ⟨polynomial.root_set_fintype p S⟩ theorem mem_root_set_iff' {p : T[X]} {S : Type*} [comm_ring S] [is_domain S] [algebra T S] (hp : p.map (algebra_map T S) ≠ 0) (a : S) : a ∈ p.root_set S ↔ (p.map (algebra_map T S)).eval a = 0 := by { change a ∈ multiset.to_finset _ ↔ _, rw [mem_to_finset, mem_roots hp], refl } theorem mem_root_set_iff {p : T[X]} (hp : p ≠ 0) {S : Type*} [comm_ring S] [is_domain S] [algebra T S] [no_zero_smul_divisors T S] (a : S) : a ∈ p.root_set S ↔ aeval a p = 0 := begin rw [mem_root_set_iff', ←eval₂_eq_eval_map], { refl }, intro h, rw ←polynomial.map_zero (algebra_map T S) at h, exact hp (map_injective _ (no_zero_smul_divisors.algebra_map_injective T S) h) end end roots theorem is_unit_iff {f : R[X]} : is_unit f ↔ ∃ r : R, is_unit r ∧ C r = f := ⟨λ hf, ⟨f.coeff 0, is_unit_C.1 $ eq_C_of_degree_eq_zero (degree_eq_zero_of_is_unit hf) ▸ hf, (eq_C_of_degree_eq_zero (degree_eq_zero_of_is_unit hf)).symm⟩, λ ⟨r, hr, hrf⟩, hrf ▸ is_unit_C.2 hr⟩ lemma coeff_coe_units_zero_ne_zero (u : R[X]ˣ) : coeff (u : R[X]) 0 ≠ 0 := begin conv in (0) { rw [← nat_degree_coe_units u] }, rw [← leading_coeff, ne.def, leading_coeff_eq_zero], exact units.ne_zero _ end lemma degree_eq_degree_of_associated (h : associated p q) : degree p = degree q := let ⟨u, hu⟩ := h in by simp [hu.symm] lemma degree_eq_one_of_irreducible_of_root (hi : irreducible p) {x : R} (hx : is_root p x) : degree p = 1 := let ⟨g, hg⟩ := dvd_iff_is_root.2 hx in have is_unit (X - C x) ∨ is_unit g, from hi.is_unit_or_is_unit hg, this.elim (λ h, have h₁ : degree (X - C x) = 1, from degree_X_sub_C x, have h₂ : degree (X - C x) = 0, from degree_eq_zero_of_is_unit h, by rw h₁ at h₂; exact absurd h₂ dec_trivial) (λ hgu, by rw [hg, degree_mul, degree_X_sub_C, degree_eq_zero_of_is_unit hgu, add_zero]) /-- Division by a monic polynomial doesn't change the leading coefficient. -/ lemma leading_coeff_div_by_monic_of_monic {R : Type u} [comm_ring R] {p q : R[X]} (hmonic : q.monic) (hdegree : q.degree ≤ p.degree) : (p /ₘ q).leading_coeff = p.leading_coeff := begin nontriviality, have h : q.leading_coeff * (p /ₘ q).leading_coeff ≠ 0, { simpa [div_by_monic_eq_zero_iff hmonic, hmonic.leading_coeff, nat.with_bot.one_le_iff_zero_lt] using hdegree }, nth_rewrite_rhs 0 ←mod_by_monic_add_div p hmonic, rw [leading_coeff_add_of_degree_lt, leading_coeff_monic_mul hmonic], rw [degree_mul' h, degree_add_div_by_monic hmonic hdegree], exact (degree_mod_by_monic_lt p hmonic).trans_le hdegree end lemma leading_coeff_div_by_monic_X_sub_C (p : R[X]) (hp : degree p ≠ 0) (a : R) : leading_coeff (p /ₘ (X - C a)) = leading_coeff p := begin nontriviality, cases hp.lt_or_lt with hd hd, { rw [degree_eq_bot.mp $ (nat.with_bot.lt_zero_iff _).mp hd, zero_div_by_monic] }, refine leading_coeff_div_by_monic_of_monic (monic_X_sub_C a) _, rwa [degree_X_sub_C, nat.with_bot.one_le_iff_zero_lt] end lemma eq_of_monic_of_dvd_of_nat_degree_le (hp : p.monic) (hq : q.monic) (hdiv : p ∣ q) (hdeg : q.nat_degree ≤ p.nat_degree) : q = p := begin obtain ⟨r, hr⟩ := hdiv, have rzero : r ≠ 0, { intro h, simpa [h, monic.ne_zero hq] using hr }, rw [hr, nat_degree_mul (monic.ne_zero hp) rzero] at hdeg, have hdegeq : p.nat_degree + r.nat_degree = p.nat_degree, { suffices hdegle : p.nat_degree ≤ p.nat_degree + r.nat_degree, { exact le_antisymm hdeg hdegle }, exact nat.le.intro rfl }, replace hdegeq := eq_C_of_nat_degree_eq_zero (((@add_right_inj _ _ p.nat_degree) _ 0).1 hdegeq), suffices hlead : 1 = r.leading_coeff, { have hcoeff := leading_coeff_C (r.coeff 0), rw [← hdegeq, ← hlead] at hcoeff, rw [← hcoeff, C_1] at hdegeq, rwa [hdegeq, mul_one] at hr }, have hprod : q.leading_coeff = p.leading_coeff * r.leading_coeff, { simp only [hr, leading_coeff_mul] }, rwa [monic.leading_coeff hp, monic.leading_coeff hq, one_mul] at hprod end end comm_ring section variables [semiring R] [comm_ring S] [is_domain S] (φ : R →+* S) lemma is_unit_of_is_unit_leading_coeff_of_is_unit_map (f : R[X]) (hf : is_unit (leading_coeff f)) (H : is_unit (map φ f)) : is_unit f := begin have dz := degree_eq_zero_of_is_unit H, rw degree_map_eq_of_leading_coeff_ne_zero at dz, { rw eq_C_of_degree_eq_zero dz, refine is_unit.map (C : R →+* R[X]) _, convert hf, rw (degree_eq_iff_nat_degree_eq _).1 dz, rintro rfl, simpa using H, }, { intro h, have u : is_unit (φ f.leading_coeff) := is_unit.map φ hf, rw h at u, simpa using u, } end end section variables [comm_ring R] [is_domain R] [comm_ring S] [is_domain S] (φ : R →+* S) /-- A polynomial over an integral domain `R` is irreducible if it is monic and irreducible after mapping into an integral domain `S`. A special case of this lemma is that a polynomial over `ℤ` is irreducible if it is monic and irreducible over `ℤ/pℤ` for some prime `p`. -/ lemma monic.irreducible_of_irreducible_map (f : R[X]) (h_mon : monic f) (h_irr : irreducible (map φ f)) : irreducible f := begin fsplit, { intro h, exact h_irr.not_unit (is_unit.map (map_ring_hom φ) h), }, { intros a b h, have q := (leading_coeff_mul a b).symm, rw ←h at q, dsimp [monic] at h_mon, rw h_mon at q, have au : is_unit a.leading_coeff := is_unit_of_mul_eq_one _ _ q, rw mul_comm at q, have bu : is_unit b.leading_coeff := is_unit_of_mul_eq_one _ _ q, clear q h_mon, have h' := congr_arg (map φ) h, simp only [polynomial.map_mul] at h', cases h_irr.is_unit_or_is_unit h' with w w, { left, exact is_unit_of_is_unit_leading_coeff_of_is_unit_map _ _ au w, }, { right, exact is_unit_of_is_unit_leading_coeff_of_is_unit_map _ _ bu w, }, } end end end polynomial
0a4bc5688e6486be95c1419ea5d0d70e473bfb78
205f0fc16279a69ea36e9fd158e3a97b06834ce2
/src/08_Bi_implication/01_exercise_chain.lean
b5a4e077918eca76d32cfb3b4433a149015f0521
[]
no_license
kevinsullivan/cs-dm-lean
b21d3ca1a9b2a0751ba13fcb4e7b258010a5d124
a06a94e98be77170ca1df486c8189338b16cf6c6
refs/heads/master
1,585,948,743,595
1,544,339,346,000
1,544,339,346,000
155,570,767
1
3
null
1,541,540,372,000
1,540,995,993,000
Lean
UTF-8
Lean
false
false
5,196
lean
/- Warmup: Function composition. -/ /- If we know that P implies Q and that Q implies R, we can conclude that P → R. The name, "hypothetical syllogism", or "chain rule" is given to this reasoning principle. Here's an example. Suppose P → Q express the idea that "if it's raining then the streets are wet, and Q → R, "if the streets are wet then it takes longer to stop." We can deduce "if it's raining then it takes longer to stop. This rule is sometimes called the chain rule. It also shows that implication is transitive. We can write it explicitly as an inference rule: { P Q : Prop } (pq : P → Q) (qr : Q → R) ---------------------------------------- chain pr : (P → R) We can also verify that it's a valid rule by proving it. The proof will be a function that takes P, Q, R, pq, and qr as arguments and that derives a proof, pr, of P → Q, the latter also a function that assumes a proof of P and derives a proof of R. -/ def chain : ∀ { P Q R : Prop }, (P → Q) → (Q → R) → (P → R) := /- To prove this proposition, we ... -/ /- assume P, Q, and R are propositions... -/ (λ P : Prop, (λ Q : Prop, (λ R : Prop, /- and assume we're given proofs of P → Q and Q → P -/ (λ pq : P → Q, (λ qr : Q → R, /- Now we show P → R by ... first assuming a proof of P ... -/ (λ p : P, /- then deriving a proof of R. -/ qr (pq p) ) ) ) ) ) ) /- Now we explain how we can simplify this expression by letting Lean infer types and figure out grouping of expressions on its own, without the parentheses. -/ /- We can leave out the explicit types and let Lean infer them from context. -/ def chain' : ∀ { P Q R : Prop }, (P → Q) → (Q → R) → (P → R) := (λ P, (λ Q, (λ R, (λ pq,(λ qr, (λ p, qr (pq p) ) ) ) ) ) ) /- We also don't need the parenthesis, as the lambda expressions associate to the right in any case. -/ def chain'' : ∀ { P Q R : Prop }, (P → Q) → (Q → R) → (P → R) := λ P, λ Q, λ R, λ pq, λ qr, λ p, qr (pq p) /- Finally, Lean lets us use a single λ followed by names for multiple arguments, giving us the simplest statement of this theorem. -/ def chain''' : ∀ { P Q R : Prop }, (P → Q) → (Q → R) → (P → R) := λ P Q R pq qr p, qr (pq p) /- To make the logic a little clearer, we could insert a lambda as follows. This might help the reader by making it clearer that in the context of P, Q, R, pq, and pr, we can derive of a proof of P → R in the form of a function that takes a proof, p : P and derives a proof of R. -/ def chain'''' : ∀ { P Q R : Prop }, (P → Q) → (Q → R) → (P → R) := λ P Q R pq qr, λ p, qr (pq p) /- We could also write the proof as a tactic script. -/ def chain_tactic : ∀ { P Q R : Prop }, (P → Q) → (Q → R) → (P → R) := begin assume P Q R: Prop, assume pq : P → Q, assume qr : Q → R, show P → R, from begin assume p : P, show R, from qr (pq p) end end /- We can leave out the explicit types and run all the assume lines together here, as well, yielding this more concise, albeit perhaps less immediately understandable, script. -/ def chain_tactic' : ∀ { P Q R : Prop }, (P → Q) → (Q → R) → (P → R) := begin assume P Q R pq qr, show P → R, from begin assume p, show R, from qr (pq p) end end /- Finally, you can write the same theorem in the form of an ordinary function definition, in which case assumptions are represented as arguments, the return type is made explicit, and the body of the function is just as it is in all the preceding examples. The return type could be left implicit, but that would make the code harder to understand, as it'd force the reader to figure out the type of the expression, qr (pq p). -/ def chain_prog (P Q R : Prop) (pq: (P → Q)) (qr: Q → R) (p : P): R := qr (pq p) /- -/ variables P Q R : Prop variable pq : P → Q variable qr : P → R theorem pr : P → R := begin apply chain Q, end def compose { P Q R : Prop } (pq : P ↔ Q) (qr: Q ↔ R) : P ↔ R := iff.intro (compose (qr.left) (pq.left) ) (compose (qr.right) (qr.left) ) /- def iff_compose (P Q R: Prop) (pq: P ↔ Q) (qr: Q ↔ R) : P ↔ R := iff.intro (compose ) _ -/ /- EXERCISE: Prove that ↔ is transitive. That is, if you assume P, Q and R are arbitrary propositions, and that you have proof of P ↔ Q and of Q ↔ R, then you can derive a proof of P ↔ R. -/ /- Prove ∀ P : Prop, P ↔ (P → P) -/ theorem foo: ∀ P : Prop, P ↔ (P → P), assume (P : Prop) (pfbi: P ↔ (P → P)), have forward := pfbi.left, have backward := pfbi.right,
7aae2b5278ab45997395bc4a7422de168de2cca4
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/ring_theory/free_comm_ring.lean
5dba6dffeb0cf6518c8e3dc9e333e9bf99555e11
[ "Apache-2.0" ]
permissive
kmill/mathlib
ea5a007b67ae4e9e18dd50d31d8aa60f650425ee
1a419a9fea7b959317eddd556e1bb9639f4dcc05
refs/heads/master
1,668,578,197,719
1,593,629,163,000
1,593,629,163,000
276,482,939
0
0
null
1,593,637,960,000
1,593,637,959,000
null
UTF-8
Lean
false
false
15,984
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Johan Commelin -/ import data.equiv.functor import data.mv_polynomial import ring_theory.ideal_operations import ring_theory.free_ring noncomputable theory local attribute [instance, priority 100] classical.prop_decidable universes u v variables (α : Type u) def free_comm_ring (α : Type u) : Type u := free_abelian_group $ multiplicative $ multiset α namespace free_comm_ring instance : comm_ring (free_comm_ring α) := free_abelian_group.comm_ring _ instance : inhabited (free_comm_ring α) := ⟨0⟩ variables {α} def of (x : α) : free_comm_ring α := free_abelian_group.of ([x] : multiset α) @[elab_as_eliminator] protected lemma induction_on {C : free_comm_ring α → Prop} (z : free_comm_ring α) (hn1 : C (-1)) (hb : ∀ b, C (of b)) (ha : ∀ x y, C x → C y → C (x + y)) (hm : ∀ x y, C x → C y → C (x * y)) : C z := have hn : ∀ x, C x → C (-x), from λ x ih, neg_one_mul x ▸ hm _ _ hn1 ih, have h1 : C 1, from neg_neg (1 : free_comm_ring α) ▸ hn _ hn1, free_abelian_group.induction_on z (add_left_neg (1 : free_comm_ring α) ▸ ha _ _ hn1 h1) (λ m, multiset.induction_on m h1 $ λ a m ih, hm _ _ (hb a) ih) (λ m ih, hn _ ih) ha section lift variables {β : Type v} [comm_ring β] (f : α → β) /-- Lift a map `α → R` to a ring homomorphism `free_comm_ring α → R`. For a version producing a bundled homomorphism, see `lift_hom`. -/ def lift : free_comm_ring α → β := free_abelian_group.lift $ λ s, (s.map f).prod @[simp] lemma lift_zero : lift f 0 = 0 := rfl @[simp] lemma lift_one : lift f 1 = 1 := free_abelian_group.lift.of _ _ @[simp] lemma lift_of (x : α) : lift f (of x) = f x := (free_abelian_group.lift.of _ _).trans $ mul_one _ @[simp] lemma lift_add (x y) : lift f (x + y) = lift f x + lift f y := free_abelian_group.lift.add _ _ _ @[simp] lemma lift_neg (x) : lift f (-x) = -lift f x := free_abelian_group.lift.neg _ _ @[simp] lemma lift_sub (x y) : lift f (x - y) = lift f x - lift f y := free_abelian_group.lift.sub _ _ _ @[simp] lemma lift_mul (x y) : lift f (x * y) = lift f x * lift f y := begin refine free_abelian_group.induction_on y (mul_zero _).symm _ _ _, { intros s2, conv_lhs { dsimp only [(*), distrib.mul, ring.mul, comm_ring.mul, semigroup.mul] }, rw [free_abelian_group.lift.of, lift, free_abelian_group.lift.of], refine free_abelian_group.induction_on x (zero_mul _).symm _ _ _, { intros s1, iterate 3 { rw free_abelian_group.lift.of }, calc _ = multiset.prod ((multiset.map f s1) + (multiset.map f s2)) : by {congr' 1, exact multiset.map_add _ _ _} ... = _ : multiset.prod_add _ _ }, { intros s1 ih, iterate 3 { rw free_abelian_group.lift.neg }, rw [ih, neg_mul_eq_neg_mul] }, { intros x1 x2 ih1 ih2, iterate 3 { rw free_abelian_group.lift.add }, rw [ih1, ih2, add_mul] } }, { intros s2 ih, rw [mul_neg_eq_neg_mul_symm, lift_neg, lift_neg, mul_neg_eq_neg_mul_symm, ih] }, { intros y1 y2 ih1 ih2, rw [mul_add, lift_add, lift_add, mul_add, ih1, ih2] }, end /-- Lift of a map `f : α → β` to `free_comm_ring α` as a ring homomorphism. We don't use it as the canonical form because Lean fails to coerce it to a function. -/ def lift_hom : free_comm_ring α →+* β := ⟨lift f, lift_one f, lift_mul f, lift_zero f, lift_add f⟩ instance : is_ring_hom (lift f) := (lift_hom f).is_ring_hom @[simp] lemma coe_lift_hom : ⇑(lift_hom f : free_comm_ring α →+* β) = lift f := rfl @[simp] lemma lift_pow (x) (n : ℕ) : lift f (x ^ n) = lift f x ^ n := (lift_hom f).map_pow _ _ @[simp] lemma lift_comp_of (f : free_comm_ring α → β) [is_ring_hom f] : lift (f ∘ of) = f := funext $ λ x, free_comm_ring.induction_on x (by rw [lift_neg, lift_one, is_ring_hom.map_neg f, is_ring_hom.map_one f]) (lift_of _) (λ x y ihx ihy, by rw [lift_add, is_ring_hom.map_add f, ihx, ihy]) (λ x y ihx ihy, by rw [lift_mul, is_ring_hom.map_mul f, ihx, ihy]) end lift variables {β : Type v} (f : α → β) /-- A map `f : α → β` produces a ring homomorphism `free_comm_ring α → free_comm_ring β`. -/ def map : free_comm_ring α →+* free_comm_ring β := lift_hom $ of ∘ f lemma map_zero : map f 0 = 0 := rfl lemma map_one : map f 1 = 1 := rfl lemma map_of (x : α) : map f (of x) = of (f x) := lift_of _ _ lemma map_add (x y) : map f (x + y) = map f x + map f y := lift_add _ _ _ lemma map_neg (x) : map f (-x) = -map f x := lift_neg _ _ lemma map_sub (x y) : map f (x - y) = map f x - map f y := lift_sub _ _ _ lemma map_mul (x y) : map f (x * y) = map f x * map f y := lift_mul _ _ _ lemma map_pow (x) (n : ℕ) : map f (x ^ n) = (map f x) ^ n := lift_pow _ _ _ def is_supported (x : free_comm_ring α) (s : set α) : Prop := x ∈ ring.closure (of '' s) section is_supported variables {x y : free_comm_ring α} {s t : set α} theorem is_supported_upwards (hs : is_supported x s) (hst : s ⊆ t) : is_supported x t := ring.closure_mono (set.monotone_image hst) hs theorem is_supported_add (hxs : is_supported x s) (hys : is_supported y s) : is_supported (x + y) s := is_add_submonoid.add_mem hxs hys theorem is_supported_neg (hxs : is_supported x s) : is_supported (-x) s := is_add_subgroup.neg_mem hxs theorem is_supported_sub (hxs : is_supported x s) (hys : is_supported y s) : is_supported (x - y) s := is_add_subgroup.sub_mem _ _ _ hxs hys theorem is_supported_mul (hxs : is_supported x s) (hys : is_supported y s) : is_supported (x * y) s := is_submonoid.mul_mem hxs hys theorem is_supported_zero : is_supported 0 s := is_add_submonoid.zero_mem theorem is_supported_one : is_supported 1 s := is_submonoid.one_mem theorem is_supported_int {i : ℤ} {s : set α} : is_supported ↑i s := int.induction_on i is_supported_zero (λ i hi, by rw [int.cast_add, int.cast_one]; exact is_supported_add hi is_supported_one) (λ i hi, by rw [int.cast_sub, int.cast_one]; exact is_supported_sub hi is_supported_one) end is_supported def restriction (s : set α) [decidable_pred s] (x : free_comm_ring α) : free_comm_ring s := lift (λ p, if H : p ∈ s then of ⟨p, H⟩ else 0) x section restriction variables (s : set α) [decidable_pred s] (x y : free_comm_ring α) @[simp] lemma restriction_of (p) : restriction s (of p) = if H : p ∈ s then of ⟨p, H⟩ else 0 := lift_of _ _ @[simp] lemma restriction_zero : restriction s 0 = 0 := lift_zero _ @[simp] lemma restriction_one : restriction s 1 = 1 := lift_one _ @[simp] lemma restriction_add : restriction s (x + y) = restriction s x + restriction s y := lift_add _ _ _ @[simp] lemma restriction_neg : restriction s (-x) = -restriction s x := lift_neg _ _ @[simp] lemma restriction_sub : restriction s (x - y) = restriction s x - restriction s y := lift_sub _ _ _ @[simp] lemma restriction_mul : restriction s (x * y) = restriction s x * restriction s y := lift_mul _ _ _ end restriction theorem is_supported_of {p} {s : set α} : is_supported (of p) s ↔ p ∈ s := suffices is_supported (of p) s → p ∈ s, from ⟨this, λ hps, ring.subset_closure ⟨p, hps, rfl⟩⟩, assume hps : is_supported (of p) s, begin haveI := classical.dec_pred s, have : ∀ x, is_supported x s → ∃ (n : ℤ), lift (λ a, if a ∈ s then (0 : polynomial ℤ) else polynomial.X) x = n, { intros x hx, refine ring.in_closure.rec_on hx _ _ _ _, { use 1, rw [lift_one], norm_cast }, { use -1, rw [lift_neg, lift_one], norm_cast }, { rintros _ ⟨z, hzs, rfl⟩ _ _, use 0, rw [lift_mul, lift_of, if_pos hzs, zero_mul], norm_cast }, { rintros x y ⟨q, hq⟩ ⟨r, hr⟩, refine ⟨q+r, _⟩, rw [lift_add, hq, hr], norm_cast } }, specialize this (of p) hps, rw [lift_of] at this, split_ifs at this, { exact h }, exfalso, apply ne.symm int.zero_ne_one, rcases this with ⟨w, H⟩, rw ←polynomial.C_eq_int_cast at H, have : polynomial.X.coeff 1 = (polynomial.C ↑w).coeff 1, by rw H, rwa [polynomial.coeff_C, if_neg (one_ne_zero : 1 ≠ 0), polynomial.coeff_X, if_pos rfl] at this end theorem map_subtype_val_restriction {x} (s : set α) [decidable_pred s] (hxs : is_supported x s) : map (subtype.val : s → α) (restriction s x) = x := begin refine ring.in_closure.rec_on hxs _ _ _ _, { rw restriction_one, refl }, { rw [restriction_neg, map_neg, restriction_one], refl }, { rintros _ ⟨p, hps, rfl⟩ n ih, rw [restriction_mul, restriction_of, dif_pos hps, map_mul, map_of, ih] }, { intros x y ihx ihy, rw [restriction_add, map_add, ihx, ihy] } end theorem exists_finite_support (x : free_comm_ring α) : ∃ s : set α, set.finite s ∧ is_supported x s := free_comm_ring.induction_on x ⟨∅, set.finite_empty, is_supported_neg is_supported_one⟩ (λ p, ⟨{p}, set.finite_singleton p, is_supported_of.2 $ set.mem_singleton _⟩) (λ x y ⟨s, hfs, hxs⟩ ⟨t, hft, hxt⟩, ⟨s ∪ t, hfs.union hft, is_supported_add (is_supported_upwards hxs $ set.subset_union_left s t) (is_supported_upwards hxt $ set.subset_union_right s t)⟩) (λ x y ⟨s, hfs, hxs⟩ ⟨t, hft, hxt⟩, ⟨s ∪ t, hfs.union hft, is_supported_mul (is_supported_upwards hxs $ set.subset_union_left s t) (is_supported_upwards hxt $ set.subset_union_right s t)⟩) theorem exists_finset_support (x : free_comm_ring α) : ∃ s : finset α, is_supported x ↑s := let ⟨s, hfs, hxs⟩ := exists_finite_support x in ⟨hfs.to_finset, by rwa set.finite.coe_to_finset⟩ end free_comm_ring namespace free_ring open function variable (α) def to_free_comm_ring {α} : free_ring α → free_comm_ring α := free_ring.lift free_comm_ring.of instance to_free_comm_ring.is_ring_hom : is_ring_hom (@to_free_comm_ring α) := free_ring.is_ring_hom free_comm_ring.of instance : has_coe (free_ring α) (free_comm_ring α) := ⟨to_free_comm_ring⟩ instance coe.is_ring_hom : is_ring_hom (coe : free_ring α → free_comm_ring α) := free_ring.to_free_comm_ring.is_ring_hom _ @[simp, norm_cast] protected lemma coe_zero : ↑(0 : free_ring α) = (0 : free_comm_ring α) := rfl @[simp, norm_cast] protected lemma coe_one : ↑(1 : free_ring α) = (1 : free_comm_ring α) := rfl variable {α} @[simp] protected lemma coe_of (a : α) : ↑(free_ring.of a) = free_comm_ring.of a := free_ring.lift_of _ _ @[simp, norm_cast] protected lemma coe_neg (x : free_ring α) : ↑(-x) = -(x : free_comm_ring α) := free_ring.lift_neg _ _ @[simp, norm_cast] protected lemma coe_add (x y : free_ring α) : ↑(x + y) = (x : free_comm_ring α) + y := free_ring.lift_add _ _ _ @[simp, norm_cast] protected lemma coe_sub (x y : free_ring α) : ↑(x - y) = (x : free_comm_ring α) - y := free_ring.lift_sub _ _ _ @[simp, norm_cast] protected lemma coe_mul (x y : free_ring α) : ↑(x * y) = (x : free_comm_ring α) * y := free_ring.lift_mul _ _ _ variable (α) protected lemma coe_surjective : surjective (coe : free_ring α → free_comm_ring α) := λ x, begin apply free_comm_ring.induction_on x, { use -1, refl }, { intro x, use free_ring.of x, refl }, { rintros _ _ ⟨x, rfl⟩ ⟨y, rfl⟩, use x + y, exact free_ring.lift_add _ _ _ }, { rintros _ _ ⟨x, rfl⟩ ⟨y, rfl⟩, use x * y, exact free_ring.lift_mul _ _ _ } end lemma coe_eq : (coe : free_ring α → free_comm_ring α) = @functor.map free_abelian_group _ _ _ (λ (l : list α), (l : multiset α)) := begin funext, apply @free_abelian_group.lift.ext _ _ _ (coe : free_ring α → free_comm_ring α) _ _ (free_abelian_group.lift.is_add_group_hom _), intros x, change free_ring.lift free_comm_ring.of (free_abelian_group.of x) = _, change _ = free_abelian_group.of (↑x), induction x with hd tl ih, {refl}, simp only [*, free_ring.lift, free_comm_ring.of, free_abelian_group.of, free_abelian_group.lift, free_group.of, free_group.to_group, free_group.to_group.aux, mul_one, free_group.quot_lift_mk, abelianization.lift.of, bool.cond_tt, list.prod_cons, cond, list.prod_nil, list.map] at *, refl end def subsingleton_equiv_free_comm_ring [subsingleton α] : free_ring α ≃+* free_comm_ring α := @ring_equiv.of' (free_ring α) (free_comm_ring α) _ _ (functor.map_equiv free_abelian_group (multiset.subsingleton_equiv α)) $ begin delta functor.map_equiv, rw congr_arg is_ring_hom _, work_on_goal 2 { symmetry, exact coe_eq α }, apply_instance end instance [subsingleton α] : comm_ring (free_ring α) := { mul_comm := λ x y, by rw [← (subsingleton_equiv_free_comm_ring α).left_inv (y * x), is_ring_hom.map_mul ((subsingleton_equiv_free_comm_ring α)).to_fun, mul_comm, ← is_ring_hom.map_mul ((subsingleton_equiv_free_comm_ring α)).to_fun, (subsingleton_equiv_free_comm_ring α).left_inv], .. free_ring.ring α } end free_ring def free_comm_ring_equiv_mv_polynomial_int : free_comm_ring α ≃+* mv_polynomial α ℤ := { to_fun := free_comm_ring.lift $ λ a, mv_polynomial.X a, inv_fun := mv_polynomial.eval₂ coe free_comm_ring.of, left_inv := begin intro x, haveI : is_semiring_hom (coe : int → free_comm_ring α) := (int.cast_ring_hom _).is_semiring_hom, refine free_abelian_group.induction_on x rfl _ _ _, { intro s, refine multiset.induction_on s _ _, { unfold free_comm_ring.lift, rw [free_abelian_group.lift.of], exact mv_polynomial.eval₂_one _ _ }, { intros hd tl ih, show mv_polynomial.eval₂ coe free_comm_ring.of (free_comm_ring.lift (λ a, mv_polynomial.X a) (free_comm_ring.of hd * free_abelian_group.of tl)) = free_comm_ring.of hd * free_abelian_group.of tl, rw [free_comm_ring.lift_mul, free_comm_ring.lift_of, mv_polynomial.eval₂_mul, mv_polynomial.eval₂_X, ih] } }, { intros s ih, rw [free_comm_ring.lift_neg, ← neg_one_mul, mv_polynomial.eval₂_mul, ← mv_polynomial.C_1, ← mv_polynomial.C_neg, mv_polynomial.eval₂_C, int.cast_neg, int.cast_one, neg_one_mul, ih] }, { intros x₁ x₂ ih₁ ih₂, rw [free_comm_ring.lift_add, mv_polynomial.eval₂_add, ih₁, ih₂] } end, right_inv := begin intro x, haveI : is_semiring_hom (coe : int → free_comm_ring α) := (int.cast_ring_hom _).is_semiring_hom, have : ∀ i : ℤ, free_comm_ring.lift (λ (a : α), mv_polynomial.X a) ↑i = mv_polynomial.C i, { exact λ i, int.induction_on i (by rw [int.cast_zero, free_comm_ring.lift_zero, mv_polynomial.C_0]) (λ i ih, by rw [int.cast_add, int.cast_one, free_comm_ring.lift_add, free_comm_ring.lift_one, ih, mv_polynomial.C_add, mv_polynomial.C_1]) (λ i ih, by rw [int.cast_sub, int.cast_one, free_comm_ring.lift_sub, free_comm_ring.lift_one, ih, mv_polynomial.C_sub, mv_polynomial.C_1]) }, apply mv_polynomial.induction_on x, { intro i, rw [mv_polynomial.eval₂_C, this] }, { intros p q ihp ihq, rw [mv_polynomial.eval₂_add, free_comm_ring.lift_add, ihp, ihq] }, { intros p a ih, rw [mv_polynomial.eval₂_mul, mv_polynomial.eval₂_X, free_comm_ring.lift_mul, free_comm_ring.lift_of, ih] } end, .. free_comm_ring.lift_hom $ λ a, mv_polynomial.X a } def free_comm_ring_pempty_equiv_int : free_comm_ring pempty.{u+1} ≃+* ℤ := ring_equiv.trans (free_comm_ring_equiv_mv_polynomial_int _) (mv_polynomial.pempty_ring_equiv _) def free_comm_ring_punit_equiv_polynomial_int : free_comm_ring punit.{u+1} ≃+* polynomial ℤ := ring_equiv.trans (free_comm_ring_equiv_mv_polynomial_int _) (mv_polynomial.punit_ring_equiv _) open free_ring def free_ring_pempty_equiv_int : free_ring pempty.{u+1} ≃+* ℤ := ring_equiv.trans (subsingleton_equiv_free_comm_ring _) free_comm_ring_pempty_equiv_int def free_ring_punit_equiv_polynomial_int : free_ring punit.{u+1} ≃+* polynomial ℤ := ring_equiv.trans (subsingleton_equiv_free_comm_ring _) free_comm_ring_punit_equiv_polynomial_int
2cf06f953874bc0907996c13fcb1d72fcb1a2707
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/measure_theory/group/add_circle.lean
67d2fc9588ddf1aa0fe8797405d04145f1636b2d
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
5,458
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 measure_theory.integral.periodic import data.zmod.quotient /-! # Measure-theoretic results about the additive circle > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. The file is a place to collect measure-theoretic results about the additive circle. ## Main definitions: * `add_circle.closed_ball_ae_eq_ball`: open and closed balls in the additive circle are almost equal * `add_circle.is_add_fundamental_domain_of_ae_ball`: a ball is a fundamental domain for rational angle rotation in the additive circle -/ open set function filter measure_theory measure_theory.measure metric open_locale measure_theory pointwise big_operators topology ennreal namespace add_circle variables {T : ℝ} [hT : fact (0 < T)] include hT lemma closed_ball_ae_eq_ball {x : add_circle T} {ε : ℝ} : closed_ball x ε =ᵐ[volume] ball x ε := begin cases le_or_lt ε 0 with hε hε, { rw [ball_eq_empty.mpr hε, ae_eq_empty, volume_closed_ball, min_eq_right (by linarith [hT.out] : 2 * ε ≤ T), ennreal.of_real_eq_zero], exact mul_nonpos_of_nonneg_of_nonpos zero_le_two hε, }, { suffices : volume (closed_ball x ε) ≤ volume (ball x ε), { exact (ae_eq_of_subset_of_measure_ge ball_subset_closed_ball this measurable_set_ball (measure_ne_top _ _)).symm, }, have : tendsto (λ δ, volume (closed_ball x δ)) (𝓝[<] ε) (𝓝 $ volume (closed_ball x ε)), { simp_rw volume_closed_ball, refine ennreal.tendsto_of_real (tendsto.min tendsto_const_nhds $ tendsto.const_mul _ _), convert (@monotone_id ℝ _).tendsto_nhds_within_Iio ε, simp, }, refine le_of_tendsto this (mem_nhds_within_Iio_iff_exists_Ioo_subset.mpr ⟨0, hε, λ r hr, _⟩), exact measure_mono (closed_ball_subset_ball hr.2), }, end /-- Let `G` be the subgroup of `add_circle T` generated by a point `u` of finite order `n : ℕ`. Then any set `I` that is almost equal to a ball of radius `T / 2n` is a fundamental domain for the action of `G` on `add_circle T` by left addition. -/ lemma is_add_fundamental_domain_of_ae_ball (I : set $ add_circle T) (u x : add_circle T) (hu : is_of_fin_add_order u) (hI : I =ᵐ[volume] ball x (T / (2 * add_order_of u))) : is_add_fundamental_domain (add_subgroup.zmultiples u) I := begin set G := add_subgroup.zmultiples u, set n := add_order_of u, set B := ball x (T / (2 * n)), have hn : 1 ≤ (n : ℝ), { norm_cast, linarith [add_order_of_pos' hu], }, refine is_add_fundamental_domain.mk_of_measure_univ_le _ _ _ _, { -- `null_measurable_set I volume` exact (measurable_set_ball.null_measurable_set.congr hI.symm), }, { -- `∀ (g : G), g ≠ 0 → ae_disjoint volume (g +ᵥ I) I` rintros ⟨g, hg⟩ hg', replace hg' : g ≠ 0, by simpa only [ne.def, add_subgroup.mk_eq_zero_iff] using hg', change ae_disjoint volume (g +ᵥ I) I, refine ae_disjoint.congr (disjoint.ae_disjoint _) ((quasi_measure_preserving_add_left volume (-g)).vadd_ae_eq_of_ae_eq g hI) hI, have hBg : g +ᵥ B = ball (g + x) (T / (2 * n)), { rw [add_comm g x, ← singleton_add_ball _ x g, add_ball, thickening_singleton], }, rw hBg, apply ball_disjoint_ball, rw [dist_eq_norm, add_sub_cancel, div_mul_eq_div_div, ← add_div, ← add_div, add_self_div_two, div_le_iff' (by positivity : 0 < (n : ℝ)), ← nsmul_eq_mul], refine (le_add_order_smul_norm_of_is_of_fin_add_order (hu.of_mem_zmultiples hg) hg').trans (nsmul_le_nsmul (norm_nonneg g) _), exact nat.le_of_dvd (add_order_of_pos_iff.mpr hu) (add_order_of_dvd_of_mem_zmultiples hg), }, { -- `∀ (g : G), quasi_measure_preserving (has_vadd.vadd g) volume volume` exact (λ g, quasi_measure_preserving_add_left volume g), }, { -- `volume univ ≤ ∑' (g : G), volume (g +ᵥ I)` replace hI : I =ᵐ[volume] closed_ball x (T / (2 * ↑n)) := hI.trans closed_ball_ae_eq_ball.symm, haveI : fintype G := @fintype.of_finite _ hu.finite_zmultiples, have hG_card : (finset.univ : finset G).card = n, { show _ = add_order_of u, rw [add_order_eq_card_zmultiples', nat.card_eq_fintype_card], refl }, simp_rw [measure_vadd], rw [add_circle.measure_univ, tsum_fintype, finset.sum_const, measure_congr hI, volume_closed_ball, ← ennreal.of_real_nsmul, mul_div, mul_div_mul_comm, div_self (@two_ne_zero ℝ _ _ _ _), one_mul, min_eq_right (div_le_self hT.out.le hn), hG_card, nsmul_eq_mul, mul_div_cancel' T (lt_of_lt_of_le zero_lt_one hn).ne.symm], exact le_refl _, }, end lemma volume_of_add_preimage_eq (s I : set $ add_circle T) (u x : add_circle T) (hu : is_of_fin_add_order u) (hs : (u +ᵥ s : set $ add_circle T) =ᵐ[volume] s) (hI : I =ᵐ[volume] ball x (T / (2 * add_order_of u))) : volume s = add_order_of u • volume (s ∩ I) := begin let G := add_subgroup.zmultiples u, haveI : fintype G := @fintype.of_finite _ hu.finite_zmultiples, have hsG : ∀ (g : G), (g +ᵥ s : set $ add_circle T) =ᵐ[volume] s, { rintros ⟨y, hy⟩, exact (vadd_ae_eq_self_of_mem_zmultiples hs hy : _), }, rw [(is_add_fundamental_domain_of_ae_ball I u x hu hI).measure_eq_card_smul_of_vadd_ae_eq_self s hsG, add_order_eq_card_zmultiples' u, nat.card_eq_fintype_card], end end add_circle
811b21e64e6570f0431bc06d02a3b2b2161c83d2
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/order/filter/lift.lean
557a75fbebb8e89547c76cf470980954c82335d0
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
21,327
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 -/ import order.filter.bases /-! # Lift filters along filter and set functions -/ open set open_locale classical filter namespace filter variables {α : Type*} {β : Type*} {γ : Type*} {ι : Sort*} section lift /-- A variant on `bind` using a function `g` taking a set instead of a member of `α`. This is essentially a push-forward along a function mapping each set to a filter. -/ protected def lift (f : filter α) (g : set α → filter β) := ⨅s ∈ f, g s variables {f f₁ f₂ : filter α} {g g₁ g₂ : set α → filter β} /-- If `(p : ι → Prop, s : ι → set α)` is a basis of a filter `f`, `g` is a monotone function `set α → filter γ`, and for each `i`, `(pg : β i → Prop, sg : β i → set α)` is a basis of the filter `g (s i)`, then `(λ (i : ι) (x : β i), p i ∧ pg i x, λ (i : ι) (x : β i), sg i x)` is a basis of the filter `f.lift g`. This basis is parametrized by `i : ι` and `x : β i`, so in order to formulate this fact using `has_basis` one has to use `Σ i, β i` as the index type, see `filter.has_basis.lift`. This lemma states the corresponding `mem_iff` statement without using a sigma type. -/ lemma has_basis.mem_lift_iff {ι} {p : ι → Prop} {s : ι → set α} {f : filter α} (hf : f.has_basis p s) {β : ι → Type*} {pg : Π i, β i → Prop} {sg : Π i, β i → set γ} {g : set α → filter γ} (hg : ∀ i, (g $ s i).has_basis (pg i) (sg i)) (gm : monotone g) {s : set γ} : s ∈ f.lift g ↔ ∃ (i : ι) (hi : p i) (x : β i) (hx : pg i x), sg i x ⊆ s := begin refine (mem_binfi _ ⟨univ, univ_sets _⟩).trans _, { intros t₁ ht₁ t₂ ht₂, exact ⟨t₁ ∩ t₂, inter_mem_sets ht₁ ht₂, gm $ inter_subset_left _ _, gm $ inter_subset_right _ _⟩ }, { simp only [← (hg _).mem_iff], exact hf.exists_iff (λ t₁ t₂ ht H, gm ht H) } end /-- If `(p : ι → Prop, s : ι → set α)` is a basis of a filter `f`, `g` is a monotone function `set α → filter γ`, and for each `i`, `(pg : β i → Prop, sg : β i → set α)` is a basis of the filter `g (s i)`, then `(λ (i : ι) (x : β i), p i ∧ pg i x, λ (i : ι) (x : β i), sg i x)` is a basis of the filter `f.lift g`. This basis is parametrized by `i : ι` and `x : β i`, so in order to formulate this fact using `has_basis` one has to use `Σ i, β i` as the index type. See also `filter.has_basis.mem_lift_iff` for the corresponding `mem_iff` statement formulated without using a sigma type. -/ lemma has_basis.lift {ι} {p : ι → Prop} {s : ι → set α} {f : filter α} (hf : f.has_basis p s) {β : ι → Type*} {pg : Π i, β i → Prop} {sg : Π i, β i → set γ} {g : set α → filter γ} (hg : ∀ i, (g $ s i).has_basis (pg i) (sg i)) (gm : monotone g) : (f.lift g).has_basis (λ i : Σ i, β i, p i.1 ∧ pg i.1 i.2) (λ i : Σ i, β i, sg i.1 i.2) := begin refine ⟨λ t, (hf.mem_lift_iff hg gm).trans _⟩, simp [sigma.exists, and_assoc, exists_and_distrib_left] end lemma mem_lift_sets (hg : monotone g) {s : set β} : s ∈ f.lift g ↔ ∃t∈f, s ∈ g t := (f.basis_sets.mem_lift_iff (λ s, (g s).basis_sets) hg).trans $ by simp only [id, ← exists_sets_subset_iff] lemma mem_lift {s : set β} {t : set α} (ht : t ∈ f) (hs : s ∈ g t) : s ∈ f.lift g := le_principal_iff.mp $ show f.lift g ≤ 𝓟 s, from infi_le_of_le t $ infi_le_of_le ht $ le_principal_iff.mpr hs lemma lift_le {f : filter α} {g : set α → filter β} {h : filter β} {s : set α} (hs : s ∈ f) (hg : g s ≤ h) : f.lift g ≤ h := infi_le_of_le s $ infi_le_of_le hs $ hg lemma le_lift {f : filter α} {g : set α → filter β} {h : filter β} (hh : ∀s∈f, h ≤ g s) : h ≤ f.lift g := le_infi $ assume s, le_infi $ assume hs, hh s hs lemma lift_mono (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁.lift g₁ ≤ f₂.lift g₂ := infi_le_infi $ assume s, infi_le_infi2 $ assume hs, ⟨hf hs, hg s⟩ lemma lift_mono' (hg : ∀s∈f, g₁ s ≤ g₂ s) : f.lift g₁ ≤ f.lift g₂ := infi_le_infi $ assume s, infi_le_infi $ assume hs, hg s hs lemma map_lift_eq {m : β → γ} (hg : monotone g) : map m (f.lift g) = f.lift (map m ∘ g) := have monotone (map m ∘ g), from map_mono.comp hg, filter_eq $ set.ext $ by simp only [mem_lift_sets hg, mem_lift_sets this, exists_prop, forall_const, mem_map, iff_self, function.comp_app] lemma comap_lift_eq {m : γ → β} (hg : monotone g) : comap m (f.lift g) = f.lift (comap m ∘ g) := have monotone (comap m ∘ g), from comap_mono.comp hg, filter_eq $ set.ext begin simp only [mem_lift_sets hg, mem_lift_sets this, comap, mem_lift_sets, mem_set_of_eq, exists_prop, function.comp_apply], exact λ s, ⟨λ ⟨b, ⟨a, ha, hb⟩, hs⟩, ⟨a, ha, b, hb, hs⟩, λ ⟨a, ha, b, hb, hs⟩, ⟨b, ⟨a, ha, hb⟩, hs⟩⟩ end theorem comap_lift_eq2 {m : β → α} {g : set β → filter γ} (hg : monotone g) : (comap m f).lift g = f.lift (g ∘ preimage m) := le_antisymm (le_infi $ assume s, le_infi $ assume hs, infi_le_of_le (preimage m s) $ infi_le _ ⟨s, hs, subset.refl _⟩) (le_infi $ assume s, le_infi $ assume ⟨s', hs', (h_sub : preimage m s' ⊆ s)⟩, infi_le_of_le s' $ infi_le_of_le hs' $ hg h_sub) lemma map_lift_eq2 {g : set β → filter γ} {m : α → β} (hg : monotone g) : (map m f).lift g = f.lift (g ∘ image m) := le_antisymm (infi_le_infi2 $ assume s, ⟨image m s, infi_le_infi2 $ assume hs, ⟨ f.sets_of_superset hs $ assume a h, mem_image_of_mem _ h, le_refl _⟩⟩) (infi_le_infi2 $ assume t, ⟨preimage m t, infi_le_infi2 $ assume ht, ⟨ht, hg $ assume x, assume h : x ∈ m '' preimage m t, let ⟨y, hy, h_eq⟩ := h in show x ∈ t, from h_eq ▸ hy⟩⟩) lemma lift_comm {g : filter β} {h : set α → set β → filter γ} : f.lift (λs, g.lift (h s)) = g.lift (λt, f.lift (λs, h s t)) := le_antisymm (le_infi $ assume i, le_infi $ assume hi, le_infi $ assume j, le_infi $ assume hj, infi_le_of_le j $ infi_le_of_le hj $ infi_le_of_le i $ infi_le _ hi) (le_infi $ assume i, le_infi $ assume hi, le_infi $ assume j, le_infi $ assume hj, infi_le_of_le j $ infi_le_of_le hj $ infi_le_of_le i $ infi_le _ hi) lemma lift_assoc {h : set β → filter γ} (hg : monotone g) : (f.lift g).lift h = f.lift (λs, (g s).lift h) := le_antisymm (le_infi $ assume s, le_infi $ assume hs, le_infi $ assume t, le_infi $ assume ht, infi_le_of_le t $ infi_le _ $ (mem_lift_sets hg).mpr ⟨_, hs, ht⟩) (le_infi $ assume t, le_infi $ assume ht, let ⟨s, hs, h'⟩ := (mem_lift_sets hg).mp ht in infi_le_of_le s $ infi_le_of_le hs $ infi_le_of_le t $ infi_le _ h') lemma lift_lift_same_le_lift {g : set α → set α → filter β} : f.lift (λs, f.lift (g s)) ≤ f.lift (λs, g s s) := le_infi $ assume s, le_infi $ assume hs, infi_le_of_le s $ infi_le_of_le hs $ infi_le_of_le s $ infi_le _ hs lemma lift_lift_same_eq_lift {g : set α → set α → filter β} (hg₁ : ∀s, monotone (λt, g s t)) (hg₂ : ∀t, monotone (λs, g s t)) : f.lift (λs, f.lift (g s)) = f.lift (λs, g s s) := le_antisymm lift_lift_same_le_lift (le_infi $ assume s, le_infi $ assume hs, le_infi $ assume t, le_infi $ assume ht, infi_le_of_le (s ∩ t) $ infi_le_of_le (inter_mem_sets hs ht) $ calc g (s ∩ t) (s ∩ t) ≤ g s (s ∩ t) : hg₂ (s ∩ t) (inter_subset_left _ _) ... ≤ g s t : hg₁ s (inter_subset_right _ _)) lemma lift_principal {s : set α} (hg : monotone g) : (𝓟 s).lift g = g s := le_antisymm (infi_le_of_le s $ infi_le _ $ subset.refl _) (le_infi $ assume t, le_infi $ assume hi, hg hi) theorem monotone_lift [preorder γ] {f : γ → filter α} {g : γ → set α → filter β} (hf : monotone f) (hg : monotone g) : monotone (λc, (f c).lift (g c)) := assume a b h, lift_mono (hf h) (hg h) lemma lift_ne_bot_iff (hm : monotone g) : (ne_bot $ f.lift g) ↔ (∀s∈f, ne_bot (g s)) := begin rw [filter.lift, infi_subtype', infi_ne_bot_iff_of_directed', subtype.forall'], { rintros ⟨s, hs⟩ ⟨t, ht⟩, exact ⟨⟨s ∩ t, inter_mem_sets hs ht⟩, hm (inter_subset_left s t), hm (inter_subset_right s t)⟩ } end @[simp] lemma lift_const {f : filter α} {g : filter β} : f.lift (λx, g) = g := le_antisymm (lift_le univ_mem_sets $ le_refl g) (le_lift $ assume s hs, le_refl g) @[simp] lemma lift_inf {f : filter α} {g h : set α → filter β} : f.lift (λx, g x ⊓ h x) = f.lift g ⊓ f.lift h := by simp only [filter.lift, infi_inf_eq, eq_self_iff_true] @[simp] lemma lift_principal2 {f : filter α} : f.lift 𝓟 = f := le_antisymm (assume s hs, mem_lift hs (mem_principal_self s)) (le_infi $ assume s, le_infi $ assume hs, by simp only [hs, le_principal_iff]) lemma lift_infi {f : ι → filter α} {g : set α → filter β} [hι : nonempty ι] (hg : ∀{s t}, g s ⊓ g t = g (s ∩ t)) : (infi f).lift g = (⨅i, (f i).lift g) := le_antisymm (le_infi $ assume i, lift_mono (infi_le _ _) (le_refl _)) (assume s, have g_mono : monotone g, from assume s t h, le_of_inf_eq $ eq.trans hg $ congr_arg g $ inter_eq_self_of_subset_left h, have ∀t∈(infi f), (⨅ (i : ι), filter.lift (f i) g) ≤ g t, from assume t ht, infi_sets_induct ht (let ⟨i⟩ := hι in infi_le_of_le i $ infi_le_of_le univ $ infi_le _ univ_mem_sets) (assume i s₁ s₂ hs₁ hs₂, @hg s₁ s₂ ▸ le_inf (infi_le_of_le i $ infi_le_of_le s₁ $ infi_le _ hs₁) hs₂) (assume s₁ s₂ hs₁ hs₂, le_trans hs₂ $ g_mono hs₁), begin simp only [mem_lift_sets g_mono, exists_imp_distrib], exact assume t ht hs, this t ht hs end) end lift section lift' /-- Specialize `lift` to functions `set α → set β`. This can be viewed as a generalization of `map`. This is essentially a push-forward along a function mapping each set to a set. -/ protected def lift' (f : filter α) (h : set α → set β) := f.lift (𝓟 ∘ h) variables {f f₁ f₂ : filter α} {h h₁ h₂ : set α → set β} lemma mem_lift' {t : set α} (ht : t ∈ f) : h t ∈ (f.lift' h) := le_principal_iff.mp $ show f.lift' h ≤ 𝓟 (h t), from infi_le_of_le t $ infi_le_of_le ht $ le_refl _ lemma has_basis.lift' {ι} {p : ι → Prop} {s} (hf : f.has_basis p s) (hh : monotone h) : (f.lift' h).has_basis p (h ∘ s) := begin refine ⟨λ t, (hf.mem_lift_iff _ (monotone_principal.comp hh)).trans _⟩, show ∀ i, (𝓟 (h (s i))).has_basis (λ j : unit, true) (λ (j : unit), h (s i)), from λ i, has_basis_principal _, simp only [exists_const] end lemma mem_lift'_sets (hh : monotone h) {s : set β} : s ∈ (f.lift' h) ↔ (∃t∈f, h t ⊆ s) := mem_lift_sets $ monotone_principal.comp hh lemma eventually_lift'_iff (hh : monotone h) {p : β → Prop} : (∀ᶠ y in f.lift' h, p y) ↔ (∃ t ∈ f, ∀ y ∈ h t, p y) := mem_lift'_sets hh lemma lift'_le {f : filter α} {g : set α → set β} {h : filter β} {s : set α} (hs : s ∈ f) (hg : 𝓟 (g s) ≤ h) : f.lift' g ≤ h := lift_le hs hg lemma lift'_mono (hf : f₁ ≤ f₂) (hh : h₁ ≤ h₂) : f₁.lift' h₁ ≤ f₂.lift' h₂ := lift_mono hf $ assume s, principal_mono.mpr $ hh s lemma lift'_mono' (hh : ∀s∈f, h₁ s ⊆ h₂ s) : f.lift' h₁ ≤ f.lift' h₂ := infi_le_infi $ assume s, infi_le_infi $ assume hs, principal_mono.mpr $ hh s hs lemma lift'_cong (hh : ∀s∈f, h₁ s = h₂ s) : f.lift' h₁ = f.lift' h₂ := le_antisymm (lift'_mono' $ assume s hs, le_of_eq $ hh s hs) (lift'_mono' $ assume s hs, le_of_eq $ (hh s hs).symm) lemma map_lift'_eq {m : β → γ} (hh : monotone h) : map m (f.lift' h) = f.lift' (image m ∘ h) := calc map m (f.lift' h) = f.lift (map m ∘ 𝓟 ∘ h) : map_lift_eq $ monotone_principal.comp hh ... = f.lift' (image m ∘ h) : by simp only [(∘), filter.lift', map_principal, eq_self_iff_true] lemma map_lift'_eq2 {g : set β → set γ} {m : α → β} (hg : monotone g) : (map m f).lift' g = f.lift' (g ∘ image m) := map_lift_eq2 $ monotone_principal.comp hg theorem comap_lift'_eq {m : γ → β} (hh : monotone h) : comap m (f.lift' h) = f.lift' (preimage m ∘ h) := calc comap m (f.lift' h) = f.lift (comap m ∘ 𝓟 ∘ h) : comap_lift_eq $ monotone_principal.comp hh ... = f.lift' (preimage m ∘ h) : by simp only [(∘), filter.lift', comap_principal, eq_self_iff_true] theorem comap_lift'_eq2 {m : β → α} {g : set β → set γ} (hg : monotone g) : (comap m f).lift' g = f.lift' (g ∘ preimage m) := comap_lift_eq2 $ monotone_principal.comp hg lemma lift'_principal {s : set α} (hh : monotone h) : (𝓟 s).lift' h = 𝓟 (h s) := lift_principal $ monotone_principal.comp hh lemma lift'_pure {a : α} (hh : monotone h) : (pure a : filter α).lift' h = 𝓟 (h {a}) := by rw [← principal_singleton, lift'_principal hh] lemma lift'_bot (hh : monotone h) : (⊥ : filter α).lift' h = 𝓟 (h ∅) := by rw [← principal_empty, lift'_principal hh] lemma principal_le_lift' {t : set β} (hh : ∀s∈f, t ⊆ h s) : 𝓟 t ≤ f.lift' h := le_infi $ assume s, le_infi $ assume hs, principal_mono.mpr (hh s hs) theorem monotone_lift' [preorder γ] {f : γ → filter α} {g : γ → set α → set β} (hf : monotone f) (hg : monotone g) : monotone (λc, (f c).lift' (g c)) := assume a b h, lift'_mono (hf h) (hg h) lemma lift_lift'_assoc {g : set α → set β} {h : set β → filter γ} (hg : monotone g) (hh : monotone h) : (f.lift' g).lift h = f.lift (λs, h (g s)) := calc (f.lift' g).lift h = f.lift (λs, (𝓟 (g s)).lift h) : lift_assoc (monotone_principal.comp hg) ... = f.lift (λs, h (g s)) : by simp only [lift_principal, hh, eq_self_iff_true] lemma lift'_lift'_assoc {g : set α → set β} {h : set β → set γ} (hg : monotone g) (hh : monotone h) : (f.lift' g).lift' h = f.lift' (λs, h (g s)) := lift_lift'_assoc hg (monotone_principal.comp hh) lemma lift'_lift_assoc {g : set α → filter β} {h : set β → set γ} (hg : monotone g) : (f.lift g).lift' h = f.lift (λs, (g s).lift' h) := lift_assoc hg lemma lift_lift'_same_le_lift' {g : set α → set α → set β} : f.lift (λs, f.lift' (g s)) ≤ f.lift' (λs, g s s) := lift_lift_same_le_lift lemma lift_lift'_same_eq_lift' {g : set α → set α → set β} (hg₁ : ∀s, monotone (λt, g s t)) (hg₂ : ∀t, monotone (λs, g s t)) : f.lift (λs, f.lift' (g s)) = f.lift' (λs, g s s) := lift_lift_same_eq_lift (assume s, monotone_principal.comp (hg₁ s)) (assume t, monotone_principal.comp (hg₂ t)) lemma lift'_inf_principal_eq {h : set α → set β} {s : set β} : f.lift' h ⊓ 𝓟 s = f.lift' (λt, h t ∩ s) := by simp only [filter.lift', filter.lift, (∘), ← inf_principal, infi_subtype', ← infi_inf] lemma lift'_ne_bot_iff (hh : monotone h) : (ne_bot (f.lift' h)) ↔ (∀s∈f, (h s).nonempty) := calc (ne_bot (f.lift' h)) ↔ (∀s∈f, ne_bot (𝓟 (h s))) : lift_ne_bot_iff (monotone_principal.comp hh) ... ↔ (∀s∈f, (h s).nonempty) : by simp only [principal_ne_bot_iff] @[simp] lemma lift'_id {f : filter α} : f.lift' id = f := lift_principal2 lemma le_lift' {f : filter α} {h : set α → set β} {g : filter β} (h_le : ∀s∈f, h s ∈ g) : g ≤ f.lift' h := le_infi $ assume s, le_infi $ assume hs, by simp only [h_le, le_principal_iff, function.comp_app]; exact h_le s hs lemma lift_infi' {f : ι → filter α} {g : set α → filter β} [nonempty ι] (hf : directed (≥) f) (hg : monotone g) : (infi f).lift g = (⨅i, (f i).lift g) := le_antisymm (le_infi $ assume i, lift_mono (infi_le _ _) (le_refl _)) (assume s, begin rw mem_lift_sets hg, simp only [exists_imp_distrib, mem_infi hf], exact assume t i ht hs, mem_infi_sets i $ mem_lift ht hs end) lemma lift'_infi {f : ι → filter α} {g : set α → set β} [nonempty ι] (hg : ∀{s t}, g s ∩ g t = g (s ∩ t)) : (infi f).lift' g = (⨅i, (f i).lift' g) := lift_infi $ λ s t, by simp only [principal_eq_iff_eq, inf_principal, (∘), hg] lemma lift'_inf (f g : filter α) {s : set α → set β} (hs : ∀ {t₁ t₂}, s t₁ ∩ s t₂ = s (t₁ ∩ t₂)) : (f ⊓ g).lift' s = f.lift' s ⊓ g.lift' s := have (⨅ b : bool, cond b f g).lift' s = ⨅ b : bool, (cond b f g).lift' s := lift'_infi @hs, by simpa only [infi_bool_eq] theorem comap_eq_lift' {f : filter β} {m : α → β} : comap m f = f.lift' (preimage m) := filter.ext $ λ s, (mem_lift'_sets monotone_preimage).symm lemma lift'_inf_powerset (f g : filter α) : (f ⊓ g).lift' powerset = f.lift' powerset ⊓ g.lift' powerset := lift'_inf f g $ λ _ _, (powerset_inter _ _).symm lemma eventually_lift'_powerset {f : filter α} {p : set α → Prop} : (∀ᶠ s in f.lift' powerset, p s) ↔ ∃ s ∈ f, ∀ t ⊆ s, p t := eventually_lift'_iff monotone_powerset lemma eventually_lift'_powerset' {f : filter α} {p : set α → Prop} (hp : ∀ ⦃s t⦄, s ⊆ t → p t → p s) : (∀ᶠ s in f.lift' powerset, p s) ↔ ∃ s ∈ f, p s := eventually_lift'_powerset.trans $ exists_congr $ λ s, exists_congr $ λ hsf, ⟨λ H, H s (subset.refl s), λ hs t ht, hp ht hs⟩ instance lift'_powerset_ne_bot (f : filter α) : ne_bot (f.lift' powerset) := (lift'_ne_bot_iff monotone_powerset).2 $ λ _ _, powerset_nonempty lemma tendsto_lift'_powerset_mono {la : filter α} {lb : filter β} {s t : α → set β} (ht : tendsto t la (lb.lift' powerset)) (hst : ∀ᶠ x in la, s x ⊆ t x) : tendsto s la (lb.lift' powerset) := begin simp only [filter.lift', filter.lift, (∘), tendsto_infi, tendsto_principal] at ht ⊢, exact λ u hu, (ht u hu).mp (hst.mono $ λ a hst ht, subset.trans hst ht) end @[simp] lemma eventually_lift'_powerset_forall {f : filter α} {p : α → Prop} : (∀ᶠ s in f.lift' powerset, ∀ x ∈ s, p x) ↔ ∀ᶠ x in f, p x := iff.trans (eventually_lift'_powerset' $ λ s t hst ht x hx, ht x (hst hx)) exists_sets_subset_iff alias eventually_lift'_powerset_forall ↔ filter.eventually.of_lift'_powerset filter.eventually.lift'_powerset @[simp] lemma eventually_lift'_powerset_eventually {f g : filter α} {p : α → Prop} : (∀ᶠ s in f.lift' powerset, ∀ᶠ x in g, x ∈ s → p x) ↔ ∀ᶠ x in f ⊓ g, p x := calc _ ↔ ∃ s ∈ f, ∀ᶠ x in g, x ∈ s → p x : eventually_lift'_powerset' $ λ s t hst ht, ht.mono $ λ x hx hs, hx (hst hs) ... ↔ ∃ (s ∈ f) (t ∈ g), ∀ x, x ∈ t → x ∈ s → p x : by simp only [eventually_iff_exists_mem] ... ↔ ∀ᶠ x in f ⊓ g, p x : by simp only [filter.eventually, mem_inf_sets, subset_def, mem_inter_iff, ← and_imp, and_comm, mem_set_of_eq] end lift' section prod variables {f : filter α} lemma prod_def {f : filter α} {g : filter β} : f ×ᶠ g = (f.lift $ λs, g.lift' $ set.prod s) := have ∀(s:set α) (t : set β), 𝓟 (set.prod s t) = (𝓟 s).comap prod.fst ⊓ (𝓟 t).comap prod.snd, by simp only [principal_eq_iff_eq, comap_principal, inf_principal]; intros; refl, begin simp only [filter.lift', function.comp, this, lift_inf, lift_const, lift_inf], rw [← comap_lift_eq monotone_principal, ← comap_lift_eq monotone_principal], simp only [filter.prod, lift_principal2, eq_self_iff_true] end lemma prod_same_eq : f ×ᶠ f = f.lift' (λt, set.prod t t) := by rw [prod_def]; from lift_lift'_same_eq_lift' (assume s, set.monotone_prod monotone_const monotone_id) (assume t, set.monotone_prod monotone_id monotone_const) lemma mem_prod_same_iff {s : set (α×α)} : s ∈ f ×ᶠ f ↔ (∃t∈f, set.prod t t ⊆ s) := by rw [prod_same_eq, mem_lift'_sets]; exact set.monotone_prod monotone_id monotone_id lemma tendsto_prod_self_iff {f : α × α → β} {x : filter α} {y : filter β} : filter.tendsto f (x ×ᶠ x) y ↔ ∀ W ∈ y, ∃ U ∈ x, ∀ (x x' : α), x ∈ U → x' ∈ U → f (x, x') ∈ W := by simp only [tendsto_def, mem_prod_same_iff, prod_sub_preimage_iff, exists_prop, iff_self] variables {α₁ : Type*} {α₂ : Type*} {β₁ : Type*} {β₂ : Type*} lemma prod_lift_lift {f₁ : filter α₁} {f₂ : filter α₂} {g₁ : set α₁ → filter β₁} {g₂ : set α₂ → filter β₂} (hg₁ : monotone g₁) (hg₂ : monotone g₂) : (f₁.lift g₁) ×ᶠ (f₂.lift g₂) = f₁.lift (λs, f₂.lift (λt, g₁ s ×ᶠ g₂ t)) := begin simp only [prod_def], rw [lift_assoc], apply congr_arg, funext x, rw [lift_comm], apply congr_arg, funext y, rw [lift'_lift_assoc], exact hg₂, exact hg₁ end lemma prod_lift'_lift' {f₁ : filter α₁} {f₂ : filter α₂} {g₁ : set α₁ → set β₁} {g₂ : set α₂ → set β₂} (hg₁ : monotone g₁) (hg₂ : monotone g₂) : f₁.lift' g₁ ×ᶠ f₂.lift' g₂ = f₁.lift (λs, f₂.lift' (λt, (g₁ s).prod (g₂ t))) := begin rw [prod_def, lift_lift'_assoc], apply congr_arg, funext x, rw [lift'_lift'_assoc], exact hg₂, exact set.monotone_prod monotone_const monotone_id, exact hg₁, exact (monotone_lift' monotone_const $ monotone_lam $ assume x, set.monotone_prod monotone_id monotone_const) end end prod end filter
e231bfc18512fe7d159c2b3743998ba023b3a73b
1abd1ed12aa68b375cdef28959f39531c6e95b84
/src/data/fin/basic.lean
14abcaf67191a16eb87e15fb65e496594c587709
[ "Apache-2.0" ]
permissive
jumpy4/mathlib
d3829e75173012833e9f15ac16e481e17596de0f
af36f1a35f279f0e5b3c2a77647c6bf2cfd51a13
refs/heads/master
1,693,508,842,818
1,636,203,271,000
1,636,203,271,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
78,574
lean
/- Copyright (c) 2017 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis, Keeley Hoek -/ import data.nat.cast import data.int.basic import tactic.localized import tactic.apply_fun import order.rel_iso /-! # The finite type with `n` elements `fin n` is the type whose elements are natural numbers smaller than `n`. This file expands on the development in the core library. ## Main definitions ### Induction principles * `fin_zero_elim` : Elimination principle for the empty set `fin 0`, generalizes `fin.elim0`. * `fin.succ_rec` : Define `C n i` by induction on `i : fin n` interpreted as `(0 : fin (n - i)).succ.succ…`. This function has two arguments: `H0 n` defines `0`-th element `C (n+1) 0` of an `(n+1)`-tuple, and `Hs n i` defines `(i+1)`-st element of `(n+1)`-tuple based on `n`, `i`, and `i`-th element of `n`-tuple. * `fin.succ_rec_on` : same as `fin.succ_rec` but `i : fin n` is the first argument; * `fin.induction` : Define `C i` by induction on `i : fin (n + 1)`, separating into the `nat`-like base cases of `C 0` and `C (i.succ)`. * `fin.induction_on` : same as `fin.induction` but with `i : fin (n + 1)` as the first argument. * `fin.cases` : define `f : Π i : fin n.succ, C i` by separately handling the cases `i = 0` and `i = fin.succ j`, `j : fin n`, defined using `fin.induction`. * `fin.reverse_induction`: reverse induction on `i : fin (n + 1)`; given `C (fin.last n)` and `∀ i : fin n, C (fin.succ i) → C (fin.cast_succ i)`, constructs all values `C i` by going down; * `fin.last_cases`: define `f : Π i, fin (n + 1), C i` by separately handling the cases `i = fin.last n` and `i = fin.cast_succ j`, a special case of `fin.reverse_induction`; * `fin.add_cases`: define a function on `fin (m + n)` by separately handling the cases `fin.cast_add n i` and `fin.nat_add m i`; * `fin.succ_above_cases`: given `i : fin (n + 1)`, define a function on `fin (n + 1)` by separately handling the cases `j = i` and `j = fin.succ_above i k`, same as `fin.insert_nth` but marked as eliminator and works for `Sort*`. ### Order embeddings and an order isomorphism * `fin.coe_embedding` : coercion to natural numbers as an `order_embedding`; * `fin.succ_embedding` : `fin.succ` as an `order_embedding`; * `fin.cast_le h` : embed `fin n` into `fin m`, `h : n ≤ m`; * `fin.cast eq` : order isomorphism between `fin n` and fin m` provided that `n = m`, see also `equiv.fin_congr`; * `fin.cast_add m` : embed `fin n` into `fin (n+m)`; * `fin.cast_succ` : embed `fin n` into `fin (n+1)`; * `fin.succ_above p` : embed `fin n` into `fin (n + 1)` with a hole around `p`; * `fin.add_nat m i` : add `m` on `i` on the right, generalizes `fin.succ`; * `fin.nat_add n i` adds `n` on `i` on the left; ### Other casts * `fin.of_nat'`: given a positive number `n` (deduced from `[fact (0 < n)]`), `fin.of_nat' i` is `i % n` interpreted as an element of `fin n`; * `fin.cast_lt i h` : embed `i` into a `fin` where `h` proves it belongs into; * `fin.pred_above (p : fin n) i` : embed `i : fin (n+1)` into `fin n` by subtracting one if `p < i`; * `fin.cast_pred` : embed `fin (n + 2)` into `fin (n + 1)` by mapping `fin.last (n + 1)` to `fin.last n`; * `fin.sub_nat i h` : subtract `m` from `i ≥ m`, generalizes `fin.pred`; * `fin.clamp n m` : `min n m` as an element of `fin (m + 1)`; ### Operation on tuples We interpret maps `Π i : fin n, α i` as tuples `(α 0, …, α (n-1))`. If `α i` is a constant map, then tuples are isomorphic (but not definitionally equal) to `vector`s. We define the following operations: * `tail` : the tail of an `n+1` tuple, i.e., its last `n` entries; * `cons` : adding an element at the beginning of an `n`-tuple, to get an `n+1`-tuple; * `init` : the beginning of an `n+1` tuple, i.e., its first `n` entries; * `snoc` : adding an element at the end of an `n`-tuple, to get an `n+1`-tuple. The name `snoc` comes from `cons` (i.e., adding an element to the left of a tuple) read in reverse order. * `insert_nth` : insert an element to a tuple at a given position. * `find p` : returns the first index `n` where `p n` is satisfied, and `none` if it is never satisfied. ### Misc definitions * `fin.last n` : The greatest value of `fin (n+1)`. -/ universes u v open fin nat function /-- Elimination principle for the empty set `fin 0`, dependent version. -/ def fin_zero_elim {α : fin 0 → Sort u} (x : fin 0) : α x := x.elim0 lemma fact.succ.pos {n} : fact (0 < succ n) := ⟨zero_lt_succ _⟩ lemma fact.bit0.pos {n} [h : fact (0 < n)] : fact (0 < bit0 n) := ⟨nat.zero_lt_bit0 $ ne_of_gt h.1⟩ lemma fact.bit1.pos {n} : fact (0 < bit1 n) := ⟨nat.zero_lt_bit1 _⟩ lemma fact.pow.pos {p n : ℕ} [h : fact $ 0 < p] : fact (0 < p ^ n) := ⟨pow_pos h.1 _⟩ localized "attribute [instance] fact.succ.pos" in fin_fact localized "attribute [instance] fact.bit0.pos" in fin_fact localized "attribute [instance] fact.bit1.pos" in fin_fact localized "attribute [instance] fact.pow.pos" in fin_fact namespace fin variables {n m : ℕ} {a b : fin n} instance fin_to_nat (n : ℕ) : has_coe (fin n) nat := ⟨subtype.val⟩ lemma pos_iff_nonempty {n : ℕ} : 0 < n ↔ nonempty (fin n) := ⟨λ h, ⟨⟨0, h⟩⟩, λ ⟨i⟩, lt_of_le_of_lt (nat.zero_le _) i.2⟩ section coe /-! ### coercions and constructions -/ @[simp] protected lemma eta (a : fin n) (h : (a : ℕ) < n) : (⟨(a : ℕ), h⟩ : fin n) = a := by cases a; refl @[ext] lemma ext {a b : fin n} (h : (a : ℕ) = b) : a = b := eq_of_veq h lemma ext_iff (a b : fin n) : a = b ↔ (a : ℕ) = b := iff.intro (congr_arg _) fin.eq_of_veq lemma coe_injective {n : ℕ} : injective (coe : fin n → ℕ) := subtype.coe_injective lemma eq_iff_veq (a b : fin n) : a = b ↔ a.1 = b.1 := ⟨veq_of_eq, eq_of_veq⟩ lemma ne_iff_vne (a b : fin n) : a ≠ b ↔ a.1 ≠ b.1 := ⟨vne_of_ne, ne_of_vne⟩ @[simp] lemma mk_eq_subtype_mk (a : ℕ) (h : a < n) : mk a h = ⟨a, h⟩ := rfl protected lemma mk.inj_iff {n a b : ℕ} {ha : a < n} {hb : b < n} : (⟨a, ha⟩ : fin n) = ⟨b, hb⟩ ↔ a = b := subtype.mk_eq_mk lemma mk_val {m n : ℕ} (h : m < n) : (⟨m, h⟩ : fin n).val = m := rfl lemma eq_mk_iff_coe_eq {k : ℕ} {hk : k < n} : a = ⟨k, hk⟩ ↔ (a : ℕ) = k := fin.eq_iff_veq a ⟨k, hk⟩ @[simp, norm_cast] lemma coe_mk {m n : ℕ} (h : m < n) : ((⟨m, h⟩ : fin n) : ℕ) = m := rfl lemma mk_coe (i : fin n) : (⟨i, i.property⟩ : fin n) = i := fin.eta _ _ lemma coe_eq_val (a : fin n) : (a : ℕ) = a.val := rfl @[simp] lemma val_eq_coe (a : fin n) : a.val = a := rfl /-- Assume `k = l`. If two functions defined on `fin k` and `fin l` are equal on each element, then they coincide (in the heq sense). -/ protected lemma heq_fun_iff {α : Sort*} {k l : ℕ} (h : k = l) {f : fin k → α} {g : fin l → α} : f == g ↔ (∀ (i : fin k), f i = g ⟨(i : ℕ), h ▸ i.2⟩) := by { induction h, simp [heq_iff_eq, function.funext_iff] } protected lemma heq_ext_iff {k l : ℕ} (h : k = l) {i : fin k} {j : fin l} : i == j ↔ (i : ℕ) = (j : ℕ) := by { induction h, simp [ext_iff] } lemma exists_iff {p : fin n → Prop} : (∃ i, p i) ↔ ∃ i h, p ⟨i, h⟩ := ⟨λ h, exists.elim h (λ ⟨i, hi⟩ hpi, ⟨i, hi, hpi⟩), λ h, exists.elim h (λ i hi, ⟨⟨i, hi.fst⟩, hi.snd⟩)⟩ lemma forall_iff {p : fin n → Prop} : (∀ i, p i) ↔ ∀ i h, p ⟨i, h⟩ := ⟨λ h i hi, h ⟨i, hi⟩, λ h ⟨i, hi⟩, h i hi⟩ end coe section order /-! ### order -/ lemma is_lt (i : fin n) : (i : ℕ) < n := i.2 lemma is_le (i : fin (n + 1)) : (i : ℕ) ≤ n := le_of_lt_succ i.is_lt lemma lt_iff_coe_lt_coe : a < b ↔ (a : ℕ) < b := iff.rfl lemma le_iff_coe_le_coe : a ≤ b ↔ (a : ℕ) ≤ b := iff.rfl lemma mk_lt_of_lt_coe {a : ℕ} (h : a < b) : (⟨a, h.trans b.is_lt⟩ : fin n) < b := h lemma mk_le_of_le_coe {a : ℕ} (h : a ≤ b) : (⟨a, h.trans_lt b.is_lt⟩ : fin n) ≤ b := h /-- `a < b` as natural numbers if and only if `a < b` in `fin n`. -/ @[norm_cast, simp] lemma coe_fin_lt {n : ℕ} {a b : fin n} : (a : ℕ) < (b : ℕ) ↔ a < b := iff.rfl /-- `a ≤ b` as natural numbers if and only if `a ≤ b` in `fin n`. -/ @[norm_cast, simp] lemma coe_fin_le {n : ℕ} {a b : fin n} : (a : ℕ) ≤ (b : ℕ) ↔ a ≤ b := iff.rfl instance {n : ℕ} : linear_order (fin n) := { le := (≤), lt := (<), decidable_le := fin.decidable_le, decidable_lt := fin.decidable_lt, decidable_eq := fin.decidable_eq _, ..linear_order.lift (coe : fin n → ℕ) (@fin.eq_of_veq _) } /-- The inclusion map `fin n → ℕ` is a relation embedding. -/ def coe_embedding (n) : (fin n) ↪o ℕ := ⟨⟨coe, @fin.eq_of_veq _⟩, λ a b, iff.rfl⟩ /-- The ordering on `fin n` is a well order. -/ instance fin.lt.is_well_order (n) : is_well_order (fin n) (<) := (coe_embedding n).is_well_order /-- Use the ordering on `fin n` for checking recursive definitions. For example, the following definition is not accepted by the termination checker, unless we declare the `has_well_founded` instance: ```lean def factorial {n : ℕ} : fin n → ℕ | ⟨0, _⟩ := 1 | ⟨i + 1, hi⟩ := (i + 1) * factorial ⟨i, i.lt_succ_self.trans hi⟩ ``` -/ instance {n : ℕ} : has_well_founded (fin n) := ⟨_, measure_wf coe⟩ @[simp] lemma coe_zero {n : ℕ} : ((0 : fin (n+1)) : ℕ) = 0 := rfl attribute [simp] val_zero @[simp] lemma val_zero' (n) : (0 : fin (n+1)).val = 0 := rfl @[simp] lemma mk_zero : (⟨0, nat.succ_pos'⟩ : fin (n + 1)) = (0 : fin _) := rfl lemma zero_le (a : fin (n + 1)) : 0 ≤ a := zero_le a.1 lemma zero_lt_one : (0 : fin (n + 2)) < 1 := nat.zero_lt_one lemma pos_iff_ne_zero (a : fin (n+1)) : 0 < a ↔ a ≠ 0 := by rw [← coe_fin_lt, coe_zero, pos_iff_ne_zero, ne.def, ne.def, ext_iff, coe_zero] lemma eq_zero_or_eq_succ {n : ℕ} (i : fin (n+1)) : i = 0 ∨ ∃ j : fin n, i = j.succ := begin rcases i with ⟨_|j, h⟩, { left, refl, }, { right, exact ⟨⟨j, nat.lt_of_succ_lt_succ h⟩, rfl⟩, } end /-- The greatest value of `fin (n+1)` -/ def last (n : ℕ) : fin (n+1) := ⟨_, n.lt_succ_self⟩ @[simp, norm_cast] lemma coe_last (n : ℕ) : (last n : ℕ) = n := rfl lemma last_val (n : ℕ) : (last n).val = n := rfl theorem le_last (i : fin (n+1)) : i ≤ last n := le_of_lt_succ i.is_lt instance : bounded_lattice (fin (n + 1)) := { top := last n, le_top := le_last, bot := 0, bot_le := zero_le, .. fin.linear_order, .. lattice_of_linear_order } lemma last_pos : (0 : fin (n + 2)) < last (n + 1) := by simp [lt_iff_coe_lt_coe] lemma eq_last_of_not_lt {i : fin (n+1)} (h : ¬ (i : ℕ) < n) : i = last n := le_antisymm (le_last i) (not_lt.1 h) section variables {α : Type*} [preorder α] open set /-- If `e` is an `order_iso` between `fin n` and `fin m`, then `n = m` and `e` is the identity map. In this lemma we state that for each `i : fin n` we have `(e i : ℕ) = (i : ℕ)`. -/ @[simp] lemma coe_order_iso_apply (e : fin n ≃o fin m) (i : fin n) : (e i : ℕ) = i := begin rcases i with ⟨i, hi⟩, rw [subtype.coe_mk], induction i using nat.strong_induction_on with i h, refine le_antisymm (forall_lt_iff_le.1 $ λ j hj, _) (forall_lt_iff_le.1 $ λ j hj, _), { have := e.symm.lt_iff_lt.2 (mk_lt_of_lt_coe hj), rw e.symm_apply_apply at this, convert this, simpa using h _ this (e.symm _).is_lt }, { rwa [← h j hj (hj.trans hi), ← lt_iff_coe_lt_coe, e.lt_iff_lt] } end instance order_iso_subsingleton : subsingleton (fin n ≃o α) := ⟨λ e e', by { ext i, rw [← e.symm.apply_eq_iff_eq, e.symm_apply_apply, ← e'.trans_apply, ext_iff, coe_order_iso_apply] }⟩ instance order_iso_subsingleton' : subsingleton (α ≃o fin n) := order_iso.symm_injective.subsingleton instance order_iso_unique : unique (fin n ≃o fin n) := unique.mk' _ /-- Two strictly monotone functions from `fin n` are equal provided that their ranges are equal. -/ lemma strict_mono_unique {f g : fin n → α} (hf : strict_mono f) (hg : strict_mono g) (h : range f = range g) : f = g := have (hf.order_iso f).trans (order_iso.set_congr _ _ h) = hg.order_iso g, from subsingleton.elim _ _, congr_arg (function.comp (coe : range g → α)) (funext $ rel_iso.ext_iff.1 this) /-- Two order embeddings of `fin n` are equal provided that their ranges are equal. -/ lemma order_embedding_eq {f g : fin n ↪o α} (h : range f = range g) : f = g := rel_embedding.ext $ funext_iff.1 $ strict_mono_unique f.strict_mono g.strict_mono h end /-- A function `f` on `fin n` is strictly monotone if and only if `f i < f (i+1)` for all `i`. -/ lemma strict_mono_iff_lt_succ {α : Type*} [preorder α] {f : fin n → α} : strict_mono f ↔ ∀ i (h : i + 1 < n), f ⟨i, lt_of_le_of_lt (nat.le_succ i) h⟩ < f ⟨i+1, h⟩ := begin split, { assume H i hi, apply H, exact nat.lt_succ_self _ }, { assume H, have A : ∀ i j (h : i < j) (h' : j < n), f ⟨i, lt_trans h h'⟩ < f ⟨j, h'⟩, { assume i j h h', induction h with k h IH, { exact H _ _ }, { exact lt_trans (IH (nat.lt_of_succ_lt h')) (H _ _) } }, assume i j hij, convert A (i : ℕ) (j : ℕ) hij j.2; ext; simp only [subtype.coe_eta] } end end order section add /-! ### addition, numerals, and coercion from nat -/ /-- Given a positive `n`, `fin.of_nat' i` is `i % n` as an element of `fin n`. -/ def of_nat' [h : fact (0 < n)] (i : ℕ) : fin n := ⟨i%n, mod_lt _ h.1⟩ lemma one_val {n : ℕ} : (1 : fin (n+1)).val = 1 % (n+1) := rfl lemma coe_one' {n : ℕ} : ((1 : fin (n+1)) : ℕ) = 1 % (n+1) := rfl @[simp] lemma val_one {n : ℕ} : (1 : fin (n+2)).val = 1 := rfl @[simp] lemma coe_one {n : ℕ} : ((1 : fin (n+2)) : ℕ) = 1 := rfl @[simp] lemma mk_one : (⟨1, nat.succ_lt_succ (nat.succ_pos n)⟩ : fin (n + 2)) = (1 : fin _) := rfl instance {n : ℕ} : nontrivial (fin (n + 2)) := ⟨⟨0, 1, dec_trivial⟩⟩ section monoid @[simp] protected lemma add_zero (k : fin (n + 1)) : k + 0 = k := by simp [eq_iff_veq, add_def, mod_eq_of_lt (is_lt k)] @[simp] protected lemma zero_add (k : fin (n + 1)) : (0 : fin (n + 1)) + k = k := by simp [eq_iff_veq, add_def, mod_eq_of_lt (is_lt k)] instance add_comm_monoid (n : ℕ) : add_comm_monoid (fin (n + 1)) := { add := (+), add_assoc := by simp [eq_iff_veq, add_def, add_assoc], zero := 0, zero_add := fin.zero_add, add_zero := fin.add_zero, add_comm := by simp [eq_iff_veq, add_def, add_comm] } end monoid lemma val_add {n : ℕ} : ∀ a b : fin n, (a + b).val = (a.val + b.val) % n | ⟨_, _⟩ ⟨_, _⟩ := rfl lemma coe_add {n : ℕ} : ∀ a b : fin n, ((a + b : fin n) : ℕ) = (a + b) % n | ⟨_, _⟩ ⟨_, _⟩ := rfl lemma coe_add_eq_ite {n : ℕ} (a b : fin n) : (↑(a + b) : ℕ) = if n ≤ a + b then a + b - n else a + b := by rw [fin.coe_add, nat.add_mod_eq_ite, nat.mod_eq_of_lt (show ↑a < n, from a.2), nat.mod_eq_of_lt (show ↑b < n, from b.2)] lemma coe_bit0 {n : ℕ} (k : fin n) : ((bit0 k : fin n) : ℕ) = bit0 (k : ℕ) % n := by { cases k, refl } lemma coe_bit1 {n : ℕ} (k : fin (n + 1)) : ((bit1 k : fin (n + 1)) : ℕ) = bit1 (k : ℕ) % (n + 1) := begin cases n, { cases k with k h, cases k, {show _ % _ = _, simp}, cases h with _ h, cases h }, simp [bit1, fin.coe_bit0, fin.coe_add, fin.coe_one], end lemma coe_add_one_of_lt {n : ℕ} {i : fin n.succ} (h : i < last _) : (↑(i + 1) : ℕ) = i + 1 := begin -- First show that `((1 : fin n.succ) : ℕ) = 1`, because `n.succ` is at least 2. cases n, { cases h }, -- Then just unfold the definitions. rw [fin.coe_add, fin.coe_one, nat.mod_eq_of_lt (nat.succ_lt_succ _)], exact h end @[simp] lemma last_add_one : ∀ n, last n + 1 = 0 | 0 := subsingleton.elim _ _ | (n + 1) := by { ext, rw [coe_add, coe_zero, coe_last, coe_one, nat.mod_self] } lemma coe_add_one {n : ℕ} (i : fin (n + 1)) : ((i + 1 : fin (n + 1)) : ℕ) = if i = last _ then 0 else i + 1 := begin rcases (le_last i).eq_or_lt with rfl|h, { simp }, { simpa [h.ne] using coe_add_one_of_lt h } end section bit @[simp] lemma mk_bit0 {m n : ℕ} (h : bit0 m < n) : (⟨bit0 m, h⟩ : fin n) = (bit0 ⟨m, (nat.le_add_right m m).trans_lt h⟩ : fin _) := eq_of_veq (nat.mod_eq_of_lt h).symm @[simp] lemma mk_bit1 {m n : ℕ} (h : bit1 m < n + 1) : (⟨bit1 m, h⟩ : fin (n + 1)) = (bit1 ⟨m, (nat.le_add_right m m).trans_lt ((m + m).lt_succ_self.trans h)⟩ : fin _) := begin ext, simp only [bit1, bit0] at h, simp only [bit1, bit0, coe_add, coe_one', coe_mk, ←nat.add_mod, nat.mod_eq_of_lt h], end end bit @[simp] lemma val_two {n : ℕ} : (2 : fin (n+3)).val = 2 := rfl @[simp] lemma coe_two {n : ℕ} : ((2 : fin (n+3)) : ℕ) = 2 := rfl section of_nat_coe @[simp] lemma of_nat_eq_coe (n : ℕ) (a : ℕ) : (of_nat a : fin (n+1)) = a := begin induction a with a ih, { refl }, ext, show (a+1) % (n+1) = subtype.val (a+1 : fin (n+1)), { rw [val_add, ← ih, of_nat], exact add_mod _ _ _ } end /-- Converting an in-range number to `fin (n + 1)` produces a result whose value is the original number. -/ lemma coe_val_of_lt {n : ℕ} {a : ℕ} (h : a < n + 1) : ((a : fin (n + 1)).val) = a := begin rw ←of_nat_eq_coe, exact nat.mod_eq_of_lt h end /-- Converting the value of a `fin (n + 1)` to `fin (n + 1)` results in the same value. -/ lemma coe_val_eq_self {n : ℕ} (a : fin (n + 1)) : (a.val : fin (n + 1)) = a := begin rw fin.eq_iff_veq, exact coe_val_of_lt a.property end /-- Coercing an in-range number to `fin (n + 1)`, and converting back to `ℕ`, results in that number. -/ lemma coe_coe_of_lt {n : ℕ} {a : ℕ} (h : a < n + 1) : ((a : fin (n + 1)) : ℕ) = a := coe_val_of_lt h /-- Converting a `fin (n + 1)` to `ℕ` and back results in the same value. -/ @[simp] lemma coe_coe_eq_self {n : ℕ} (a : fin (n + 1)) : ((a : ℕ) : fin (n + 1)) = a := coe_val_eq_self a lemma coe_nat_eq_last (n) : (n : fin (n + 1)) = fin.last n := by { rw [←fin.of_nat_eq_coe, fin.of_nat, fin.last], simp only [nat.mod_eq_of_lt n.lt_succ_self] } lemma le_coe_last (i : fin (n + 1)) : i ≤ n := by { rw fin.coe_nat_eq_last, exact fin.le_last i } end of_nat_coe lemma add_one_pos (i : fin (n + 1)) (h : i < fin.last n) : (0 : fin (n + 1)) < i + 1 := begin cases n, { exact absurd h (nat.not_lt_zero _) }, { rw [lt_iff_coe_lt_coe, coe_last, ←add_lt_add_iff_right 1] at h, rw [lt_iff_coe_lt_coe, coe_add, coe_zero, coe_one, nat.mod_eq_of_lt h], exact nat.zero_lt_succ _ } end lemma one_pos : (0 : fin (n + 2)) < 1 := succ_pos 0 lemma zero_ne_one : (0 : fin (n + 2)) ≠ 1 := ne_of_lt one_pos @[simp] lemma zero_eq_one_iff : (0 : fin (n + 1)) = 1 ↔ n = 0 := begin split, { cases n; intro h, { refl }, { have := zero_ne_one, contradiction } }, { rintro rfl, refl } end @[simp] lemma one_eq_zero_iff : (1 : fin (n + 1)) = 0 ↔ n = 0 := by rw [eq_comm, zero_eq_one_iff] end add section succ /-! ### succ and casts into larger fin types -/ @[simp] lemma coe_succ (j : fin n) : (j.succ : ℕ) = j + 1 := by cases j; simp [fin.succ] lemma succ_pos (a : fin n) : (0 : fin (n + 1)) < a.succ := by simp [lt_iff_coe_lt_coe] /-- `fin.succ` as an `order_embedding` -/ def succ_embedding (n : ℕ) : fin n ↪o fin (n + 1) := order_embedding.of_strict_mono fin.succ $ λ ⟨i, hi⟩ ⟨j, hj⟩ h, succ_lt_succ h @[simp] lemma coe_succ_embedding : ⇑(succ_embedding n) = fin.succ := rfl @[simp] lemma succ_le_succ_iff : a.succ ≤ b.succ ↔ a ≤ b := (succ_embedding n).le_iff_le @[simp] lemma succ_lt_succ_iff : a.succ < b.succ ↔ a < b := (succ_embedding n).lt_iff_lt lemma succ_injective (n : ℕ) : injective (@fin.succ n) := (succ_embedding n).injective @[simp] lemma succ_inj {a b : fin n} : a.succ = b.succ ↔ a = b := (succ_injective n).eq_iff lemma succ_ne_zero {n} : ∀ k : fin n, fin.succ k ≠ 0 | ⟨k, hk⟩ heq := nat.succ_ne_zero k $ (ext_iff _ _).1 heq @[simp] lemma succ_zero_eq_one : fin.succ (0 : fin (n + 1)) = 1 := rfl @[simp] lemma succ_one_eq_two : fin.succ (1 : fin (n + 2)) = 2 := rfl @[simp] lemma succ_mk (n i : ℕ) (h : i < n) : fin.succ ⟨i, h⟩ = ⟨i + 1, nat.succ_lt_succ h⟩ := rfl lemma mk_succ_pos (i : ℕ) (h : i < n) : (0 : fin (n + 1)) < ⟨i.succ, add_lt_add_right h 1⟩ := by { rw [lt_iff_coe_lt_coe, coe_zero], exact nat.succ_pos i } lemma one_lt_succ_succ (a : fin n) : (1 : fin (n + 2)) < a.succ.succ := begin cases n, { exact fin_zero_elim a }, { rw [←succ_zero_eq_one, succ_lt_succ_iff], exact succ_pos a } end lemma succ_succ_ne_one (a : fin n) : fin.succ (fin.succ a) ≠ 1 := ne_of_gt (one_lt_succ_succ a) /-- `cast_lt i h` embeds `i` into a `fin` where `h` proves it belongs into. -/ def cast_lt (i : fin m) (h : i.1 < n) : fin n := ⟨i.1, h⟩ @[simp] lemma coe_cast_lt (i : fin m) (h : i.1 < n) : (cast_lt i h : ℕ) = i := rfl @[simp] lemma cast_lt_mk (i n m : ℕ) (hn : i < n) (hm : i < m) : cast_lt ⟨i, hn⟩ hm = ⟨i, hm⟩ := rfl /-- `cast_le h i` embeds `i` into a larger `fin` type. -/ def cast_le (h : n ≤ m) : fin n ↪o fin m := order_embedding.of_strict_mono (λ a, cast_lt a (lt_of_lt_of_le a.2 h)) $ λ a b h, h @[simp] lemma coe_cast_le (h : n ≤ m) (i : fin n) : (cast_le h i : ℕ) = i := rfl @[simp] lemma cast_le_mk (i n m : ℕ) (hn : i < n) (h : n ≤ m) : cast_le h ⟨i, hn⟩ = ⟨i, lt_of_lt_of_le hn h⟩ := rfl @[simp] lemma cast_le_zero {n m : ℕ} (h : n.succ ≤ m.succ) : cast_le h 0 = 0 := by simp [eq_iff_veq] @[simp] lemma range_cast_le {n k : ℕ} (h : n ≤ k) : set.range (cast_le h) = {i | (i : ℕ) < n} := set.ext (λ x, ⟨λ ⟨y, hy⟩, hy ▸ y.2, λ hx, ⟨⟨x, hx⟩, fin.ext rfl⟩⟩) @[simp] lemma coe_of_injective_cast_le_symm {n k : ℕ} (h : n ≤ k) (i : fin k) (hi) : ((equiv.of_injective _ (cast_le h).injective).symm ⟨i, hi⟩ : ℕ) = i := begin rw ← coe_cast_le, exact congr_arg coe (equiv.apply_of_injective_symm _ _ _) end @[simp] lemma cast_le_succ {m n : ℕ} (h : (m + 1) ≤ (n + 1)) (i : fin m) : cast_le h i.succ = (cast_le (nat.succ_le_succ_iff.mp h) i).succ := by simp [fin.eq_iff_veq] /-- `cast eq i` embeds `i` into a equal `fin` type, see also `equiv.fin_congr`. -/ def cast (eq : n = m) : fin n ≃o fin m := { to_equiv := ⟨cast_le eq.le, cast_le eq.symm.le, λ a, eq_of_veq rfl, λ a, eq_of_veq rfl⟩, map_rel_iff' := λ a b, iff.rfl } @[simp] lemma symm_cast (h : n = m) : (cast h).symm = cast h.symm := rfl lemma coe_cast (h : n = m) (i : fin n) : (cast h i : ℕ) = i := rfl @[simp] lemma cast_mk (h : n = m) (i : ℕ) (hn : i < n) : cast h ⟨i, hn⟩ = ⟨i, lt_of_lt_of_le hn h.le⟩ := rfl @[simp] lemma cast_trans {k : ℕ} (h : n = m) (h' : m = k) {i : fin n} : cast h' (cast h i) = cast (eq.trans h h') i := rfl @[simp] lemma cast_refl (h : n = n := rfl) : cast h = order_iso.refl (fin n) := by { ext, refl } /-- While in many cases `fin.cast` is better than `equiv.cast`/`cast`, sometimes we want to apply a generic theorem about `cast`. -/ lemma cast_to_equiv (h : n = m) : (cast h).to_equiv = equiv.cast (h ▸ rfl) := by { subst h, simp } /-- While in many cases `fin.cast` is better than `equiv.cast`/`cast`, sometimes we want to apply a generic theorem about `cast`. -/ lemma cast_eq_cast (h : n = m) : (cast h : fin n → fin m) = _root_.cast (h ▸ rfl) := by { subst h, ext, simp } /-- `cast_add m i` embeds `i : fin n` in `fin (n+m)`. See also `fin.nat_add` and `fin.add_nat`. -/ def cast_add (m) : fin n ↪o fin (n + m) := cast_le $ nat.le_add_right n m @[simp] lemma coe_cast_add (m : ℕ) (i : fin n) : (cast_add m i : ℕ) = i := rfl lemma cast_add_lt {m : ℕ} (n : ℕ) (i : fin m) : (cast_add n i : ℕ) < m := i.2 @[simp] lemma cast_add_mk (m : ℕ) (i : ℕ) (h : i < n) : cast_add m ⟨i, h⟩ = ⟨i, lt_add_right i n m h⟩ := rfl @[simp] lemma cast_add_cast_lt (m : ℕ) (i : fin (n + m)) (hi : i.val < n) : cast_add m (cast_lt i hi) = i := ext rfl @[simp] lemma cast_lt_cast_add (m : ℕ) (i : fin n) : cast_lt (cast_add m i) (cast_add_lt m i) = i := ext rfl /-- `cast_succ i` embeds `i : fin n` in `fin (n+1)`. -/ def cast_succ : fin n ↪o fin (n + 1) := cast_add 1 @[simp] lemma coe_cast_succ (i : fin n) : (i.cast_succ : ℕ) = i := rfl @[simp] lemma cast_succ_mk (n i : ℕ) (h : i < n) : cast_succ ⟨i, h⟩ = ⟨i, nat.lt.step h⟩ := rfl lemma cast_succ_lt_succ (i : fin n) : i.cast_succ < i.succ := lt_iff_coe_lt_coe.2 $ by simp only [coe_cast_succ, coe_succ, nat.lt_succ_self] lemma le_cast_succ_iff {i : fin (n + 1)} {j : fin n} : i ≤ j.cast_succ ↔ i < j.succ := by simpa [lt_iff_coe_lt_coe, le_iff_coe_le_coe] using nat.succ_le_succ_iff.symm @[simp] lemma succ_last (n : ℕ) : (last n).succ = last (n.succ) := rfl @[simp] lemma succ_eq_last_succ {n : ℕ} (i : fin n.succ) : i.succ = last (n + 1) ↔ i = last n := by rw [← succ_last, (succ_injective _).eq_iff] @[simp] lemma cast_succ_cast_lt (i : fin (n + 1)) (h : (i : ℕ) < n) : cast_succ (cast_lt i h) = i := fin.eq_of_veq rfl @[simp] lemma cast_lt_cast_succ {n : ℕ} (a : fin n) (h : (a : ℕ) < n) : cast_lt (cast_succ a) h = a := by cases a; refl @[simp] lemma cast_succ_lt_cast_succ_iff : a.cast_succ < b.cast_succ ↔ a < b := (@cast_succ n).lt_iff_lt lemma cast_succ_injective (n : ℕ) : injective (@fin.cast_succ n) := (cast_succ : fin n ↪o _).injective lemma cast_succ_inj {a b : fin n} : a.cast_succ = b.cast_succ ↔ a = b := (cast_succ_injective n).eq_iff lemma cast_succ_lt_last (a : fin n) : cast_succ a < last n := lt_iff_coe_lt_coe.mpr a.is_lt @[simp] lemma cast_succ_zero : cast_succ (0 : fin (n + 1)) = 0 := rfl @[simp] lemma cast_succ_one {n : ℕ} : fin.cast_succ (1 : fin (n + 2)) = 1 := rfl /-- `cast_succ i` is positive when `i` is positive -/ lemma cast_succ_pos {i : fin (n + 1)} (h : 0 < i) : 0 < cast_succ i := by simpa [lt_iff_coe_lt_coe] using h @[simp] lemma cast_succ_eq_zero_iff (a : fin (n + 1)) : a.cast_succ = 0 ↔ a = 0 := subtype.ext_iff.trans $ (subtype.ext_iff.trans $ by exact iff.rfl).symm lemma cast_succ_ne_zero_iff (a : fin (n + 1)) : a.cast_succ ≠ 0 ↔ a ≠ 0 := not_iff_not.mpr $ cast_succ_eq_zero_iff a lemma cast_succ_fin_succ (n : ℕ) (j : fin n) : cast_succ (fin.succ j) = fin.succ (cast_succ j) := by simp [fin.ext_iff] @[norm_cast, simp] lemma coe_eq_cast_succ : (a : fin (n + 1)) = a.cast_succ := begin ext, exact coe_val_of_lt (nat.lt.step a.is_lt), end @[simp] lemma coe_succ_eq_succ : a.cast_succ + 1 = a.succ := begin cases n, { exact fin_zero_elim a }, { simp [a.is_lt, eq_iff_veq, add_def, nat.mod_eq_of_lt] } end lemma lt_succ : a.cast_succ < a.succ := by { rw [cast_succ, lt_iff_coe_lt_coe, coe_cast_add, coe_succ], exact lt_add_one a.val } @[simp] lemma range_cast_succ {n : ℕ} : set.range (cast_succ : fin n → fin n.succ) = {i | (i : ℕ) < n} := range_cast_le _ @[simp] lemma coe_of_injective_cast_succ_symm {n : ℕ} (i : fin n.succ) (hi) : ((equiv.of_injective cast_succ (cast_succ_injective _)).symm ⟨i, hi⟩ : ℕ) = i := begin rw ← coe_cast_succ, exact congr_arg coe (equiv.apply_of_injective_symm _ _ _) end lemma succ_cast_succ {n : ℕ} (i : fin n) : i.cast_succ.succ = i.succ.cast_succ := fin.ext (by simp) /-- `add_nat m i` adds `m` to `i`, generalizes `fin.succ`. -/ def add_nat (m) : fin n ↪o fin (n + m) := order_embedding.of_strict_mono (λ i, ⟨(i : ℕ) + m, add_lt_add_right i.2 _⟩) $ λ i j h, lt_iff_coe_lt_coe.2 $ add_lt_add_right h _ @[simp] lemma coe_add_nat (m : ℕ) (i : fin n) : (add_nat m i : ℕ) = i + m := rfl lemma le_coe_add_nat (m : ℕ) (i : fin n) : m ≤ add_nat m i := nat.le_add_left _ _ @[simp] lemma add_nat_mk (n i : ℕ) (hi : i < m) : add_nat n ⟨i, hi⟩ = ⟨i + n, add_lt_add_right hi n⟩ := rfl /-- `nat_add n i` adds `n` to `i` "on the left". -/ def nat_add (n) {m} : fin m ↪o fin (n + m) := order_embedding.of_strict_mono (λ i, ⟨n + (i : ℕ), add_lt_add_left i.2 _⟩) $ λ i j h, lt_iff_coe_lt_coe.2 $ add_lt_add_left h _ @[simp] lemma coe_nat_add (n : ℕ) {m : ℕ} (i : fin m) : (nat_add n i : ℕ) = n + i := rfl @[simp] lemma nat_add_mk (n i : ℕ) (hi : i < m) : nat_add n ⟨i, hi⟩ = ⟨n + i, add_lt_add_left hi n⟩ := rfl lemma le_coe_nat_add (m : ℕ) (i : fin n) : m ≤ nat_add m i := nat.le_add_right _ _ lemma nat_add_zero {n : ℕ} : fin.nat_add 0 = (fin.cast (zero_add n).symm).to_rel_embedding := by { ext, apply zero_add } @[simp] lemma cast_nat_add (n : ℕ) {m : ℕ} (i : fin m) : cast (add_comm _ _) (nat_add n i) = add_nat n i := ext $ add_comm _ _ @[simp] lemma cast_add_nat {n : ℕ} (m : ℕ) (i : fin n) : cast (add_comm _ _) (add_nat m i) = nat_add m i := ext $ add_comm _ _ end succ section pred /-! ### pred -/ @[simp] lemma coe_pred (j : fin (n+1)) (h : j ≠ 0) : (j.pred h : ℕ) = j - 1 := by { cases j, refl } @[simp] lemma succ_pred : ∀(i : fin (n+1)) (h : i ≠ 0), (i.pred h).succ = i | ⟨0, h⟩ hi := by contradiction | ⟨n + 1, h⟩ hi := rfl @[simp] lemma pred_succ (i : fin n) {h : i.succ ≠ 0} : i.succ.pred h = i := by { cases i, refl } @[simp] lemma pred_mk_succ (i : ℕ) (h : i < n + 1) : fin.pred ⟨i + 1, add_lt_add_right h 1⟩ (ne_of_vne (ne_of_gt (mk_succ_pos i h))) = ⟨i, h⟩ := by simp only [ext_iff, coe_pred, coe_mk, add_tsub_cancel_right] -- This is not a simp lemma by default, because `pred_mk_succ` is nicer when it applies. lemma pred_mk {n : ℕ} (i : ℕ) (h : i < n + 1) (w) : fin.pred ⟨i, h⟩ w = ⟨i - 1, by rwa tsub_lt_iff_right (nat.succ_le_of_lt $ nat.pos_of_ne_zero (fin.vne_of_ne w))⟩ := rfl @[simp] lemma pred_le_pred_iff {n : ℕ} {a b : fin n.succ} {ha : a ≠ 0} {hb : b ≠ 0} : a.pred ha ≤ b.pred hb ↔ a ≤ b := by rw [←succ_le_succ_iff, succ_pred, succ_pred] @[simp] lemma pred_lt_pred_iff {n : ℕ} {a b : fin n.succ} {ha : a ≠ 0} {hb : b ≠ 0} : a.pred ha < b.pred hb ↔ a < b := by rw [←succ_lt_succ_iff, succ_pred, succ_pred] @[simp] lemma pred_inj : ∀ {a b : fin (n + 1)} {ha : a ≠ 0} {hb : b ≠ 0}, a.pred ha = b.pred hb ↔ a = b | ⟨0, _⟩ b ha hb := by contradiction | ⟨i+1, _⟩ ⟨0, _⟩ ha hb := by contradiction | ⟨i+1, hi⟩ ⟨j+1, hj⟩ ha hb := by simp [fin.eq_iff_veq] @[simp] lemma pred_one {n : ℕ} : fin.pred (1 : fin (n + 2)) (ne.symm (ne_of_lt one_pos)) = 0 := rfl lemma pred_add_one (i : fin (n + 2)) (h : (i : ℕ) < n + 1) : pred (i + 1) (ne_of_gt (add_one_pos _ (lt_iff_coe_lt_coe.mpr h))) = cast_lt i h := begin rw [ext_iff, coe_pred, coe_cast_lt, coe_add, coe_one, mod_eq_of_lt, add_tsub_cancel_right], exact add_lt_add_right h 1, end /-- `sub_nat i h` subtracts `m` from `i`, generalizes `fin.pred`. -/ def sub_nat (m) (i : fin (n + m)) (h : m ≤ (i : ℕ)) : fin n := ⟨(i : ℕ) - m, by { rw [tsub_lt_iff_right h], exact i.is_lt }⟩ @[simp] lemma coe_sub_nat (i : fin (n + m)) (h : m ≤ i) : (i.sub_nat m h : ℕ) = i - m := rfl @[simp] lemma sub_nat_mk {i : ℕ} (h₁ : i < n + m) (h₂ : m ≤ i) : sub_nat m ⟨i, h₁⟩ h₂ = ⟨i - m, (tsub_lt_iff_right h₂).2 h₁⟩ := rfl @[simp] lemma pred_cast_succ_succ (i : fin n) : pred (cast_succ i.succ) (ne_of_gt (cast_succ_pos i.succ_pos)) = i.cast_succ := by simp [eq_iff_veq] @[simp] lemma add_nat_sub_nat {i : fin (n + m)} (h : m ≤ i) : add_nat m (sub_nat m i h) = i := ext $ tsub_add_cancel_of_le h @[simp] lemma sub_nat_add_nat (i : fin n) (m : ℕ) (h : m ≤ add_nat m i := le_coe_add_nat m i) : sub_nat m (add_nat m i) h = i := ext $ add_tsub_cancel_right i m @[simp] lemma nat_add_sub_nat_cast {i : fin (n + m)} (h : n ≤ i) : nat_add n (sub_nat n (cast (add_comm _ _) i) h) = i := by simp [← cast_add_nat] end pred section rec /-! ### recursion and induction principles -/ /-- Define `C n i` by induction on `i : fin n` interpreted as `(0 : fin (n - i)).succ.succ…`. This function has two arguments: `H0 n` defines `0`-th element `C (n+1) 0` of an `(n+1)`-tuple, and `Hs n i` defines `(i+1)`-st element of `(n+1)`-tuple based on `n`, `i`, and `i`-th element of `n`-tuple. -/ @[elab_as_eliminator] def succ_rec {C : Π n, fin n → Sort*} (H0 : Π n, C (succ n) 0) (Hs : Π n i, C n i → C (succ n) i.succ) : Π {n : ℕ} (i : fin n), C n i | 0 i := i.elim0 | (succ n) ⟨0, _⟩ := H0 _ | (succ n) ⟨succ i, h⟩ := Hs _ _ (succ_rec ⟨i, lt_of_succ_lt_succ h⟩) /-- Define `C n i` by induction on `i : fin n` interpreted as `(0 : fin (n - i)).succ.succ…`. This function has two arguments: `H0 n` defines `0`-th element `C (n+1) 0` of an `(n+1)`-tuple, and `Hs n i` defines `(i+1)`-st element of `(n+1)`-tuple based on `n`, `i`, and `i`-th element of `n`-tuple. A version of `fin.succ_rec` taking `i : fin n` as the first argument. -/ @[elab_as_eliminator] def succ_rec_on {n : ℕ} (i : fin n) {C : Π n, fin n → Sort*} (H0 : Π n, C (succ n) 0) (Hs : Π n i, C n i → C (succ n) i.succ) : C n i := i.succ_rec H0 Hs @[simp] theorem succ_rec_on_zero {C : ∀ n, fin n → Sort*} {H0 Hs} (n) : @fin.succ_rec_on (succ n) 0 C H0 Hs = H0 n := rfl @[simp] theorem succ_rec_on_succ {C : ∀ n, fin n → Sort*} {H0 Hs} {n} (i : fin n) : @fin.succ_rec_on (succ n) i.succ C H0 Hs = Hs n i (fin.succ_rec_on i H0 Hs) := by cases i; refl /-- Define `C i` by induction on `i : fin (n + 1)` via induction on the underlying `nat` value. This function has two arguments: `h0` handles the base case on `C 0`, and `hs` defines the inductive step using `C i.cast_succ`. -/ @[elab_as_eliminator] def induction {C : fin (n + 1) → Sort*} (h0 : C 0) (hs : ∀ i : fin n, C i.cast_succ → C i.succ) : Π (i : fin (n + 1)), C i := begin rintro ⟨i, hi⟩, induction i with i IH, { rwa [fin.mk_zero] }, { refine hs ⟨i, lt_of_succ_lt_succ hi⟩ _, exact IH (lt_of_succ_lt hi) } end /-- Define `C i` by induction on `i : fin (n + 1)` via induction on the underlying `nat` value. This function has two arguments: `h0` handles the base case on `C 0`, and `hs` defines the inductive step using `C i.cast_succ`. A version of `fin.induction` taking `i : fin (n + 1)` as the first argument. -/ @[elab_as_eliminator] def induction_on (i : fin (n + 1)) {C : fin (n + 1) → Sort*} (h0 : C 0) (hs : ∀ i : fin n, C i.cast_succ → C i.succ) : C i := induction h0 hs i /-- Define `f : Π i : fin n.succ, C i` by separately handling the cases `i = 0` and `i = j.succ`, `j : fin n`. -/ @[elab_as_eliminator] def cases {C : fin (succ n) → Sort*} (H0 : C 0) (Hs : Π i : fin n, C (i.succ)) : Π (i : fin (succ n)), C i := induction H0 (λ i _, Hs i) @[simp] theorem cases_zero {n} {C : fin (succ n) → Sort*} {H0 Hs} : @fin.cases n C H0 Hs 0 = H0 := rfl @[simp] theorem cases_succ {n} {C : fin (succ n) → Sort*} {H0 Hs} (i : fin n) : @fin.cases n C H0 Hs i.succ = Hs i := by cases i; refl @[simp] theorem cases_succ' {n} {C : fin (succ n) → Sort*} {H0 Hs} {i : ℕ} (h : i + 1 < n + 1) : @fin.cases n C H0 Hs ⟨i.succ, h⟩ = Hs ⟨i, lt_of_succ_lt_succ h⟩ := by cases i; refl lemma forall_fin_succ {P : fin (n+1) → Prop} : (∀ i, P i) ↔ P 0 ∧ (∀ i:fin n, P i.succ) := ⟨λ H, ⟨H 0, λ i, H _⟩, λ ⟨H0, H1⟩ i, fin.cases H0 H1 i⟩ lemma exists_fin_succ {P : fin (n+1) → Prop} : (∃ i, P i) ↔ P 0 ∨ (∃i:fin n, P i.succ) := ⟨λ ⟨i, h⟩, fin.cases or.inl (λ i hi, or.inr ⟨i, hi⟩) i h, λ h, or.elim h (λ h, ⟨0, h⟩) $ λ⟨i, hi⟩, ⟨i.succ, hi⟩⟩ lemma forall_fin_one {p : fin 1 → Prop} : (∀ i, p i) ↔ p 0 := @unique.forall_iff (fin 1) _ p lemma exists_fin_one {p : fin 1 → Prop} : (∃ i, p i) ↔ p 0 := @unique.exists_iff (fin 1) _ p lemma forall_fin_two {p : fin 2 → Prop} : (∀ i, p i) ↔ p 0 ∧ p 1 := forall_fin_succ.trans $ and_congr_right $ λ _, forall_fin_one lemma exists_fin_two {p : fin 2 → Prop} : (∃ i, p i) ↔ p 0 ∨ p 1 := exists_fin_succ.trans $ or_congr_right exists_fin_one /-- Define `C i` by reverse induction on `i : fin (n + 1)` via induction on the underlying `nat` value. This function has two arguments: `hlast` handles the base case on `C (fin.last n)`, and `hs` defines the inductive step using `C i.succ`, inducting downwards. -/ @[elab_as_eliminator] def reverse_induction {n : ℕ} {C : fin (n + 1) → Sort*} (hlast : C (fin.last n)) (hs : ∀ i : fin n, C i.succ → C i.cast_succ) : Π (i : fin (n + 1)), C i | i := if hi : i = fin.last n then _root_.cast (by rw hi) hlast else let j : fin n := ⟨i, lt_of_le_of_ne (nat.le_of_lt_succ i.2) (λ h, hi (fin.ext h))⟩ in have wf : n + 1 - j.succ < n + 1 - i, begin cases i, rw [tsub_lt_tsub_iff_left_of_le]; simp [*, nat.succ_le_iff], end, have hi : i = fin.cast_succ j, from fin.ext rfl, _root_.cast (by rw hi) (hs _ (reverse_induction j.succ)) using_well_founded { rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ i : fin (n+1), n + 1 - i)⟩], dec_tac := `[assumption] } @[simp] lemma reverse_induction_last {n : ℕ} {C : fin (n + 1) → Sort*} (h0 : C (fin.last n)) (hs : ∀ i : fin n, C i.succ → C i.cast_succ) : (reverse_induction h0 hs (fin.last n) : C (fin.last n)) = h0 := by rw [reverse_induction]; simp @[simp] lemma reverse_induction_cast_succ {n : ℕ} {C : fin (n + 1) → Sort*} (h0 : C (fin.last n)) (hs : ∀ i : fin n, C i.succ → C i.cast_succ) (i : fin n): (reverse_induction h0 hs i.cast_succ : C i.cast_succ) = hs i (reverse_induction h0 hs i.succ) := begin rw [reverse_induction, dif_neg (ne_of_lt (fin.cast_succ_lt_last i))], cases i, refl end /-- Define `f : Π i : fin n.succ, C i` by separately handling the cases `i = fin.last n` and `i = j.cast_succ`, `j : fin n`. -/ @[elab_as_eliminator, elab_strategy] def last_cases {n : ℕ} {C : fin (n + 1) → Sort*} (hlast : C (fin.last n)) (hcast : (Π (i : fin n), C i.cast_succ)) (i : fin (n + 1)) : C i := reverse_induction hlast (λ i _, hcast i) i @[simp] lemma last_cases_last {n : ℕ} {C : fin (n + 1) → Sort*} (hlast : C (fin.last n)) (hcast : (Π (i : fin n), C i.cast_succ)) : (fin.last_cases hlast hcast (fin.last n): C (fin.last n)) = hlast := reverse_induction_last _ _ @[simp] lemma last_cases_cast_succ {n : ℕ} {C : fin (n + 1) → Sort*} (hlast : C (fin.last n)) (hcast : (Π (i : fin n), C i.cast_succ)) (i : fin n) : (fin.last_cases hlast hcast (fin.cast_succ i): C (fin.cast_succ i)) = hcast i := reverse_induction_cast_succ _ _ _ /-- Define `f : Π i : fin (m + n), C i` by separately handling the cases `i = cast_add n i`, `j : fin m` and `i = nat_add m j`, `j : fin n`. -/ @[elab_as_eliminator, elab_strategy] def add_cases {m n : ℕ} {C : fin (m + n) → Sort u} (hleft : Π i, C (cast_add n i)) (hright : Π i, C (nat_add m i)) (i : fin (m + n)) : C i := if hi : (i : ℕ) < m then eq.rec_on (cast_add_cast_lt n i hi) (hleft (cast_lt i hi)) else eq.rec_on (nat_add_sub_nat_cast (le_of_not_lt hi)) (hright _) @[simp] lemma add_cases_left {m n : ℕ} {C : fin (m + n) → Sort*} (hleft : Π i, C (cast_add n i)) (hright : Π i, C (nat_add m i)) (i : fin m) : add_cases hleft hright (fin.cast_add n i) = hleft i := begin cases i with i hi, rw [add_cases, dif_pos (cast_add_lt _ _)], refl end @[simp] lemma add_cases_right {m n : ℕ} {C : fin (m + n) → Sort*} (hleft : Π i, C (cast_add n i)) (hright : Π i, C (nat_add m i)) (i : fin n) : add_cases hleft hright (nat_add m i) = hright i := begin have : ¬ (nat_add m i : ℕ) < m, from (le_coe_nat_add _ _).not_lt, rw [add_cases, dif_neg this], refine eq_of_heq ((eq_rec_heq _ _).trans _), congr' 1, simp end end rec section add_group open nat int /-- Negation on `fin n` -/ instance (n : ℕ) : has_neg (fin n) := ⟨λ a, ⟨(n - a) % n, nat.mod_lt _ (lt_of_le_of_lt (nat.zero_le _) a.2)⟩⟩ /-- Abelian group structure on `fin (n+1)`. -/ instance (n : ℕ) : add_comm_group (fin (n+1)) := { add_left_neg := λ ⟨a, ha⟩, fin.ext $ trans (nat.mod_add_mod _ _ _) $ by { rw [fin.coe_mk, fin.coe_zero, tsub_add_cancel_of_le, nat.mod_self], exact le_of_lt ha }, sub_eq_add_neg := λ ⟨a, ha⟩ ⟨b, hb⟩, fin.ext $ show (a + (n + 1 - b)) % (n + 1) = (a + (n + 1 - b) % (n + 1)) % (n + 1), by simp, sub := fin.sub, ..fin.add_comm_monoid n, ..fin.has_neg n.succ } protected lemma coe_neg (a : fin n) : ((-a : fin n) : ℕ) = (n - a) % n := rfl protected lemma coe_sub (a b : fin n) : ((a - b : fin n) : ℕ) = (a + (n - b)) % n := by cases a; cases b; refl end add_group section succ_above lemma succ_above_aux (p : fin (n + 1)) : strict_mono (λ i : fin n, if i.cast_succ < p then i.cast_succ else i.succ) := (cast_succ : fin n ↪o _).strict_mono.ite (succ_embedding n).strict_mono (λ i j hij hj, lt_trans ((cast_succ : fin n ↪o _).lt_iff_lt.2 hij) hj) (λ i, (cast_succ_lt_succ i).le) /-- `succ_above p i` embeds `fin n` into `fin (n + 1)` with a hole around `p`. -/ def succ_above (p : fin (n + 1)) : fin n ↪o fin (n + 1) := order_embedding.of_strict_mono _ p.succ_above_aux /-- Embedding `i : fin n` into `fin (n + 1)` with a hole around `p : fin (n + 1)` embeds `i` by `cast_succ` when the resulting `i.cast_succ < p`. -/ lemma succ_above_below (p : fin (n + 1)) (i : fin n) (h : i.cast_succ < p) : p.succ_above i = i.cast_succ := by { rw [succ_above], exact if_pos h } @[simp] lemma succ_above_ne_zero_zero {a : fin (n + 2)} (ha : a ≠ 0) : a.succ_above 0 = 0 := begin rw fin.succ_above_below, { refl }, { exact bot_lt_iff_ne_bot.mpr ha } end lemma succ_above_eq_zero_iff {a : fin (n + 2)} {b : fin (n + 1)} (ha : a ≠ 0) : a.succ_above b = 0 ↔ b = 0 := by simp only [←succ_above_ne_zero_zero ha, order_embedding.eq_iff_eq] lemma succ_above_ne_zero {a : fin (n + 2)} {b : fin (n + 1)} (ha : a ≠ 0) (hb : b ≠ 0) : a.succ_above b ≠ 0 := mt (succ_above_eq_zero_iff ha).mp hb /-- Embedding `fin n` into `fin (n + 1)` with a hole around zero embeds by `succ`. -/ @[simp] lemma succ_above_zero : ⇑(succ_above (0 : fin (n + 1))) = fin.succ := rfl /-- Embedding `fin n` into `fin (n + 1)` with a hole around `last n` embeds by `cast_succ`. -/ @[simp] lemma succ_above_last : succ_above (fin.last n) = cast_succ := by { ext, simp only [succ_above_below, cast_succ_lt_last] } lemma succ_above_last_apply (i : fin n) : succ_above (fin.last n) i = i.cast_succ := by rw succ_above_last /-- Embedding `i : fin n` into `fin (n + 1)` with a hole around `p : fin (n + 1)` embeds `i` by `succ` when the resulting `p < i.succ`. -/ lemma succ_above_above (p : fin (n + 1)) (i : fin n) (h : p ≤ i.cast_succ) : p.succ_above i = i.succ := by simp [succ_above, h.not_lt] /-- Embedding `i : fin n` into `fin (n + 1)` is always about some hole `p`. -/ lemma succ_above_lt_ge (p : fin (n + 1)) (i : fin n) : i.cast_succ < p ∨ p ≤ i.cast_succ := lt_or_ge (cast_succ i) p /-- Embedding `i : fin n` into `fin (n + 1)` is always about some hole `p`. -/ lemma succ_above_lt_gt (p : fin (n + 1)) (i : fin n) : i.cast_succ < p ∨ p < i.succ := or.cases_on (succ_above_lt_ge p i) (λ h, or.inl h) (λ h, or.inr (lt_of_le_of_lt h (cast_succ_lt_succ i))) /-- Embedding `i : fin n` into `fin (n + 1)` using a pivot `p` that is greater results in a value that is less than `p`. -/ @[simp] lemma succ_above_lt_iff (p : fin (n + 1)) (i : fin n) : p.succ_above i < p ↔ i.cast_succ < p := begin refine iff.intro _ _, { intro h, cases succ_above_lt_ge p i with H H, { exact H }, { rw succ_above_above _ _ H at h, exact lt_trans (cast_succ_lt_succ i) h } }, { intro h, rw succ_above_below _ _ h, exact h } end /-- Embedding `i : fin n` into `fin (n + 1)` using a pivot `p` that is lesser results in a value that is greater than `p`. -/ lemma lt_succ_above_iff (p : fin (n + 1)) (i : fin n) : p < p.succ_above i ↔ p ≤ i.cast_succ := begin refine iff.intro _ _, { intro h, cases succ_above_lt_ge p i with H H, { rw succ_above_below _ _ H at h, exact le_of_lt h }, { exact H } }, { intro h, rw succ_above_above _ _ h, exact lt_of_le_of_lt h (cast_succ_lt_succ i) }, end /-- Embedding `i : fin n` into `fin (n + 1)` with a hole around `p : fin (n + 1)` never results in `p` itself -/ theorem succ_above_ne (p : fin (n + 1)) (i : fin n) : p.succ_above i ≠ p := begin intro eq, by_cases H : i.cast_succ < p, { simpa [lt_irrefl, ←succ_above_below _ _ H, eq] using H }, { simpa [←succ_above_above _ _ (le_of_not_lt H), eq] using cast_succ_lt_succ i } end /-- Embedding a positive `fin n` results in a positive fin (n + 1)` -/ lemma succ_above_pos (p : fin (n + 2)) (i : fin (n + 1)) (h : 0 < i) : 0 < p.succ_above i := begin by_cases H : i.cast_succ < p, { simpa [succ_above_below _ _ H] using cast_succ_pos h }, { simpa [succ_above_above _ _ (le_of_not_lt H)] using succ_pos _ }, end @[simp] lemma succ_above_cast_lt {x y : fin (n + 1)} (h : x < y) (hx : x.1 < n := lt_of_lt_of_le h y.le_last) : y.succ_above (x.cast_lt hx) = x := by { rw [succ_above_below, cast_succ_cast_lt], exact h } @[simp] lemma succ_above_pred {x y : fin (n + 1)} (h : x < y) (hy : y ≠ 0 := (x.zero_le.trans_lt h).ne') : x.succ_above (y.pred hy) = y := by { rw [succ_above_above, succ_pred], simpa [le_iff_coe_le_coe] using nat.le_pred_of_lt h } lemma cast_lt_succ_above {x : fin n} {y : fin (n + 1)} (h : cast_succ x < y) (h' : (y.succ_above x).1 < n := lt_of_lt_of_le ((succ_above_lt_iff _ _).2 h) (le_last y)) : (y.succ_above x).cast_lt h' = x := by simp only [succ_above_below _ _ h, cast_lt_cast_succ] lemma pred_succ_above {x : fin n} {y : fin (n + 1)} (h : y ≤ cast_succ x) (h' : y.succ_above x ≠ 0 := (y.zero_le.trans_lt $ (lt_succ_above_iff _ _).2 h).ne') : (y.succ_above x).pred h' = x := by simp only [succ_above_above _ _ h, pred_succ] lemma exists_succ_above_eq {x y : fin (n + 1)} (h : x ≠ y) : ∃ z, y.succ_above z = x := begin cases h.lt_or_lt with hlt hlt, exacts [⟨_, succ_above_cast_lt hlt⟩, ⟨_, succ_above_pred hlt⟩], end @[simp] lemma exists_succ_above_eq_iff {x y : fin (n + 1)} : (∃ z, x.succ_above z = y) ↔ y ≠ x := begin refine ⟨_, exists_succ_above_eq⟩, rintro ⟨y, rfl⟩, exact succ_above_ne _ _ end /-- The range of `p.succ_above` is everything except `p`. -/ @[simp] lemma range_succ_above (p : fin (n + 1)) : set.range (p.succ_above) = {p}ᶜ := set.ext $ λ _, exists_succ_above_eq_iff /-- Given a fixed pivot `x : fin (n + 1)`, `x.succ_above` is injective -/ lemma succ_above_right_injective {x : fin (n + 1)} : injective (succ_above x) := (succ_above x).injective /-- Given a fixed pivot `x : fin (n + 1)`, `x.succ_above` is injective -/ lemma succ_above_right_inj {x : fin (n + 1)} : x.succ_above a = x.succ_above b ↔ a = b := succ_above_right_injective.eq_iff /-- `succ_above` is injective at the pivot -/ lemma succ_above_left_injective : injective (@succ_above n) := λ _ _ h, by simpa [range_succ_above] using congr_arg (λ f : fin n ↪o fin (n + 1), (set.range f)ᶜ) h /-- `succ_above` is injective at the pivot -/ @[simp] lemma succ_above_left_inj {x y : fin (n + 1)} : x.succ_above = y.succ_above ↔ x = y := succ_above_left_injective.eq_iff @[simp] lemma zero_succ_above {n : ℕ} (i : fin n) : (0 : fin (n + 1)).succ_above i = i.succ := rfl @[simp] lemma succ_succ_above_zero {n : ℕ} (i : fin (n + 1)) : (i.succ).succ_above 0 = 0 := succ_above_below _ _ (succ_pos _) @[simp] lemma succ_succ_above_succ {n : ℕ} (i : fin (n + 1)) (j : fin n) : (i.succ).succ_above j.succ = (i.succ_above j).succ := (lt_or_ge j.cast_succ i).elim (λ h, have h' : j.succ.cast_succ < i.succ, by simpa [lt_iff_coe_lt_coe] using h, by { ext, simp [succ_above_below _ _ h, succ_above_below _ _ h'] }) (λ h, have h' : i.succ ≤ j.succ.cast_succ, by simpa [le_iff_coe_le_coe] using h, by { ext, simp [succ_above_above _ _ h, succ_above_above _ _ h'] }) @[simp] lemma one_succ_above_zero {n : ℕ} : (1 : fin (n + 2)).succ_above 0 = 0 := succ_succ_above_zero 0 /-- By moving `succ` to the outside of this expression, we create opportunities for further simplification using `succ_above_zero` or `succ_succ_above_zero`. -/ @[simp] lemma succ_succ_above_one {n : ℕ} (i : fin (n + 2)) : (i.succ).succ_above 1 = (i.succ_above 0).succ := succ_succ_above_succ i 0 @[simp] lemma one_succ_above_succ {n : ℕ} (j : fin n) : (1 : fin (n + 2)).succ_above j.succ = j.succ.succ := succ_succ_above_succ 0 j @[simp] lemma one_succ_above_one {n : ℕ} : (1 : fin (n + 3)).succ_above 1 = 2 := succ_succ_above_succ 0 0 end succ_above section pred_above /-- `pred_above p i` embeds `i : fin (n+1)` into `fin n` by subtracting one if `p < i`. -/ def pred_above (p : fin n) (i : fin (n+1)) : fin n := if h : p.cast_succ < i then i.pred (ne_of_lt (lt_of_le_of_lt (zero_le p.cast_succ) h)).symm else i.cast_lt (lt_of_le_of_lt (le_of_not_lt h) p.2) lemma pred_above_right_monotone (p : fin n) : monotone p.pred_above := λ a b H, begin dsimp [pred_above], split_ifs with ha hb hb, all_goals { simp only [le_iff_coe_le_coe, coe_pred], }, { exact pred_le_pred H, }, { calc _ ≤ _ : nat.pred_le _ ... ≤ _ : H, }, { simp at ha, exact le_pred_of_lt (lt_of_le_of_lt ha hb), }, { exact H, }, end lemma pred_above_left_monotone (i : fin (n + 1)) : monotone (λ p, pred_above p i) := λ a b H, begin dsimp [pred_above], split_ifs with ha hb hb, all_goals { simp only [le_iff_coe_le_coe, coe_pred] }, { exact pred_le _, }, { have : b < a := cast_succ_lt_cast_succ_iff.mpr (hb.trans_le (le_of_not_gt ha)), exact absurd H this.not_le } end /-- `cast_pred` embeds `i : fin (n + 2)` into `fin (n + 1)` by lowering just `last (n + 1)` to `last n`. -/ def cast_pred (i : fin (n + 2)) : fin (n + 1) := pred_above (last n) i @[simp] lemma cast_pred_zero : cast_pred (0 : fin (n + 2)) = 0 := rfl @[simp] lemma cast_pred_one : cast_pred (1 : fin (n + 2)) = 1 := by { cases n, apply subsingleton.elim, refl } @[simp] theorem pred_above_zero {i : fin (n + 2)} (hi : i ≠ 0) : pred_above 0 i = i.pred hi := begin dsimp [pred_above], rw dif_pos, exact (pos_iff_ne_zero _).mpr hi, end @[simp] lemma cast_pred_last : cast_pred (last (n + 1)) = last n := by simp [eq_iff_veq, cast_pred, pred_above, cast_succ_lt_last] @[simp] lemma cast_pred_mk (n i : ℕ) (h : i < n + 1) : cast_pred ⟨i, lt_succ_of_lt h⟩ = ⟨i, h⟩ := begin have : ¬cast_succ (last n) < ⟨i, lt_succ_of_lt h⟩, { simpa [lt_iff_coe_lt_coe] using le_of_lt_succ h }, simp [cast_pred, pred_above, this] end lemma pred_above_below (p : fin (n + 1)) (i : fin (n + 2)) (h : i ≤ p.cast_succ) : p.pred_above i = i.cast_pred := begin have : i ≤ (last n).cast_succ := h.trans p.le_last, simp [pred_above, cast_pred, h.not_lt, this.not_lt] end @[simp] lemma pred_above_last : pred_above (fin.last n) = cast_pred := rfl lemma pred_above_last_apply (i : fin n) : pred_above (fin.last n) i = i.cast_pred := by rw pred_above_last lemma pred_above_above (p : fin n) (i : fin (n + 1)) (h : p.cast_succ < i) : p.pred_above i = i.pred (p.cast_succ.zero_le.trans_lt h).ne.symm := by simp [pred_above, h] lemma cast_pred_monotone : monotone (@cast_pred n) := pred_above_right_monotone (last _) /-- Sending `fin (n+1)` to `fin n` by subtracting one from anything above `p` then back to `fin (n+1)` with a gap around `p` is the identity away from `p`. -/ @[simp] lemma succ_above_pred_above {p : fin n} {i : fin (n + 1)} (h : i ≠ p.cast_succ) : p.cast_succ.succ_above (p.pred_above i) = i := begin dsimp [pred_above, succ_above], rcases p with ⟨p, _⟩, rcases i with ⟨i, _⟩, cases lt_or_le i p with H H, { rw dif_neg, rw if_pos, refl, exact H, simp, apply le_of_lt H, }, { rw dif_pos, rw if_neg, swap 3, -- For some reason `simp` doesn't fire fully unless we discharge the third goal. { exact lt_of_le_of_ne H (ne.symm h), }, { simp, }, { simp only [subtype.mk_eq_mk, ne.def, fin.cast_succ_mk] at h, simp only [pred, subtype.mk_lt_mk, not_lt], exact nat.le_pred_of_lt (nat.lt_of_le_and_ne H (ne.symm h)), }, }, end /-- Sending `fin n` into `fin (n + 1)` with a gap at `p` then back to `fin n` by subtracting one from anything above `p` is the identity. -/ @[simp] lemma pred_above_succ_above (p : fin n) (i : fin n) : p.pred_above (p.cast_succ.succ_above i) = i := begin dsimp [pred_above, succ_above], rcases p with ⟨p, _⟩, rcases i with ⟨i, _⟩, split_ifs, { rw dif_neg, { refl }, { simp_rw [if_pos h], simp only [subtype.mk_lt_mk, not_lt], exact le_of_lt h, }, }, { rw dif_pos, { refl, }, { simp_rw [if_neg h], exact lt_succ_iff.mpr (not_lt.mp h), }, }, end lemma cast_succ_pred_eq_pred_cast_succ {a : fin (n + 1)} (ha : a ≠ 0) (ha' := a.cast_succ_ne_zero_iff.mpr ha) : (a.pred ha).cast_succ = a.cast_succ.pred ha' := by { cases a, refl } /-- `pred` commutes with `succ_above`. -/ lemma pred_succ_above_pred {a : fin (n + 2)} {b : fin (n + 1)} (ha : a ≠ 0) (hb : b ≠ 0) (hk := succ_above_ne_zero ha hb) : (a.pred ha).succ_above (b.pred hb) = (a.succ_above b).pred hk := begin obtain hbelow | habove := lt_or_le b.cast_succ a, -- `rwa` uses them { rw fin.succ_above_below, { rwa [cast_succ_pred_eq_pred_cast_succ , fin.pred_inj, fin.succ_above_below] }, { rwa [cast_succ_pred_eq_pred_cast_succ , pred_lt_pred_iff] } }, { rw fin.succ_above_above, have : (b.pred hb).succ = b.succ.pred (fin.succ_ne_zero _), by rw [succ_pred, pred_succ], { rwa [this, fin.pred_inj, fin.succ_above_above] }, { rwa [cast_succ_pred_eq_pred_cast_succ , fin.pred_le_pred_iff] } } end @[simp] theorem cast_pred_cast_succ (i : fin (n + 1)) : cast_pred i.cast_succ = i := by simp [cast_pred, pred_above, le_last] lemma cast_succ_cast_pred {i : fin (n + 2)} (h : i < last _) : cast_succ i.cast_pred = i := begin rw [cast_pred, pred_above, dif_neg], { simp [fin.eq_iff_veq] }, { exact h.not_le } end lemma coe_cast_pred_le_self (i : fin (n + 2)) : (i.cast_pred : ℕ) ≤ i := begin rcases i.le_last.eq_or_lt with rfl|h, { simp }, { rw [cast_pred, pred_above, dif_neg], { simp }, { simpa [lt_iff_coe_lt_coe, le_iff_coe_le_coe, lt_succ_iff] using h } } end lemma coe_cast_pred_lt_iff {i : fin (n + 2)} : (i.cast_pred : ℕ) < i ↔ i = fin.last _ := begin rcases i.le_last.eq_or_lt with rfl|H, { simp }, { simp only [ne_of_lt H], rw ←cast_succ_cast_pred H, simp } end lemma lt_last_iff_coe_cast_pred {i : fin (n + 2)} : i < fin.last _ ↔ (i.cast_pred : ℕ) = i := begin rcases i.le_last.eq_or_lt with rfl|H, { simp }, { simp only [H], rw ←cast_succ_cast_pred H, simp } end end pred_above /-- `min n m` as an element of `fin (m + 1)` -/ def clamp (n m : ℕ) : fin (m + 1) := of_nat $ min n m @[simp] lemma coe_clamp (n m : ℕ) : (clamp n m : ℕ) = min n m := nat.mod_eq_of_lt $ nat.lt_succ_iff.mpr $ min_le_right _ _ section tuple /-! ### Tuples We can think of the type `Π(i : fin n), α i` as `n`-tuples of elements of possibly varying type `α i`. A particular case is `fin n → α` of elements with all the same type. Here are some relevant operations, first about adding or removing elements at the beginning of a tuple. -/ /-- There is exactly one tuple of size zero. -/ example (α : fin 0 → Sort u) : unique (Π i : fin 0, α i) := by apply_instance @[simp] lemma tuple0_le {α : Π i : fin 0, Type*} [Π i, preorder (α i)] (f g : Π i, α i) : f ≤ g := fin_zero_elim variables {α : fin (n+1) → Type u} (x : α 0) (q : Πi, α i) (p : Π(i : fin n), α (i.succ)) (i : fin n) (y : α i.succ) (z : α 0) /-- The tail of an `n+1` tuple, i.e., its last `n` entries. -/ def tail (q : Πi, α i) : (Π(i : fin n), α (i.succ)) := λ i, q i.succ lemma tail_def {n : ℕ} {α : fin (n+1) → Type*} {q : Π i, α i} : tail (λ k : fin (n+1), q k) = (λ k : fin n, q k.succ) := rfl /-- Adding an element at the beginning of an `n`-tuple, to get an `n+1`-tuple. -/ def cons (x : α 0) (p : Π(i : fin n), α (i.succ)) : Πi, α i := λ j, fin.cases x p j @[simp] lemma tail_cons : tail (cons x p) = p := by simp [tail, cons] @[simp] lemma cons_succ : cons x p i.succ = p i := by simp [cons] @[simp] lemma cons_zero : cons x p 0 = x := by simp [cons] /-- Updating a tuple and adding an element at the beginning commute. -/ @[simp] lemma cons_update : cons x (update p i y) = update (cons x p) i.succ y := begin ext j, by_cases h : j = 0, { rw h, simp [ne.symm (succ_ne_zero i)] }, { let j' := pred j h, have : j'.succ = j := succ_pred j h, rw [← this, cons_succ], by_cases h' : j' = i, { rw h', simp }, { have : j'.succ ≠ i.succ, by rwa [ne.def, succ_inj], rw [update_noteq h', update_noteq this, cons_succ] } } end /-- Adding an element at the beginning of a tuple and then updating it amounts to adding it directly. -/ lemma update_cons_zero : update (cons x p) 0 z = cons z p := begin ext j, by_cases h : j = 0, { rw h, simp }, { simp only [h, update_noteq, ne.def, not_false_iff], let j' := pred j h, have : j'.succ = j := succ_pred j h, rw [← this, cons_succ, cons_succ] } end /-- Concatenating the first element of a tuple with its tail gives back the original tuple -/ @[simp] lemma cons_self_tail : cons (q 0) (tail q) = q := begin ext j, by_cases h : j = 0, { rw h, simp }, { let j' := pred j h, have : j'.succ = j := succ_pred j h, rw [← this, tail, cons_succ] } end /-- Updating the first element of a tuple does not change the tail. -/ @[simp] lemma tail_update_zero : tail (update q 0 z) = tail q := by { ext j, simp [tail, fin.succ_ne_zero] } /-- Updating a nonzero element and taking the tail commute. -/ @[simp] lemma tail_update_succ : tail (update q i.succ y) = update (tail q) i y := begin ext j, by_cases h : j = i, { rw h, simp [tail] }, { simp [tail, (fin.succ_injective n).ne h, h] } end lemma comp_cons {α : Type*} {β : Type*} (g : α → β) (y : α) (q : fin n → α) : g ∘ (cons y q) = cons (g y) (g ∘ q) := begin ext j, by_cases h : j = 0, { rw h, refl }, { let j' := pred j h, have : j'.succ = j := succ_pred j h, rw [← this, cons_succ, comp_app, cons_succ] } end lemma comp_tail {α : Type*} {β : Type*} (g : α → β) (q : fin n.succ → α) : g ∘ (tail q) = tail (g ∘ q) := by { ext j, simp [tail] } lemma le_cons [Π i, preorder (α i)] {x : α 0} {q : Π i, α i} {p : Π i : fin n, α i.succ} : q ≤ cons x p ↔ q 0 ≤ x ∧ tail q ≤ p := forall_fin_succ.trans $ and_congr iff.rfl $ forall_congr $ λ j, by simp [tail] lemma cons_le [Π i, preorder (α i)] {x : α 0} {q : Π i, α i} {p : Π i : fin n, α i.succ} : cons x p ≤ q ↔ x ≤ q 0 ∧ p ≤ tail q := @le_cons _ (λ i, order_dual (α i)) _ x q p @[simp] lemma range_cons {α : Type*} {n : ℕ} (x : α) (b : fin n → α) : set.range (fin.cons x b : fin n.succ → α) = insert x (set.range b) := begin ext y, simp only [set.mem_range, set.mem_insert_iff], split, { rintros ⟨i, rfl⟩, refine cases (or.inl (cons_zero _ _)) (λ i, or.inr ⟨i, _⟩) i, rw cons_succ }, { rintros (rfl | ⟨i, hi⟩), { exact ⟨0, fin.cons_zero _ _⟩ }, { refine ⟨i.succ, _⟩, rw [cons_succ, hi] } } end /-- `fin.append ho u v` appends two vectors of lengths `m` and `n` to produce one of length `o = m + n`. `ho` provides control of definitional equality for the vector length. -/ def append {α : Type*} {o : ℕ} (ho : o = m + n) (u : fin m → α) (v : fin n → α) : fin o → α := λ i, if h : (i : ℕ) < m then u ⟨i, h⟩ else v ⟨(i : ℕ) - m, (tsub_lt_iff_left (le_of_not_lt h)).2 (ho ▸ i.property)⟩ @[simp] lemma fin_append_apply_zero {α : Type*} {o : ℕ} (ho : (o + 1) = (m + 1) + n) (u : fin (m + 1) → α) (v : fin n → α) : fin.append ho u v 0 = u 0 := rfl end tuple section tuple_right /-! In the previous section, we have discussed inserting or removing elements on the left of a tuple. In this section, we do the same on the right. A difference is that `fin (n+1)` is constructed inductively from `fin n` starting from the left, not from the right. This implies that Lean needs more help to realize that elements belong to the right types, i.e., we need to insert casts at several places. -/ variables {α : fin (n+1) → Type u} (x : α (last n)) (q : Πi, α i) (p : Π(i : fin n), α i.cast_succ) (i : fin n) (y : α i.cast_succ) (z : α (last n)) /-- The beginning of an `n+1` tuple, i.e., its first `n` entries -/ def init (q : Πi, α i) (i : fin n) : α i.cast_succ := q i.cast_succ lemma init_def {n : ℕ} {α : fin (n+1) → Type*} {q : Π i, α i} : init (λ k : fin (n+1), q k) = (λ k : fin n, q k.cast_succ) := rfl /-- Adding an element at the end of an `n`-tuple, to get an `n+1`-tuple. The name `snoc` comes from `cons` (i.e., adding an element to the left of a tuple) read in reverse order. -/ def snoc (p : Π(i : fin n), α i.cast_succ) (x : α (last n)) (i : fin (n+1)) : α i := if h : i.val < n then _root_.cast (by rw fin.cast_succ_cast_lt i h) (p (cast_lt i h)) else _root_.cast (by rw eq_last_of_not_lt h) x @[simp] lemma init_snoc : init (snoc p x) = p := begin ext i, have h' := fin.cast_lt_cast_succ i i.is_lt, simp [init, snoc, i.is_lt, h'], convert cast_eq rfl (p i) end @[simp] lemma snoc_cast_succ : snoc p x i.cast_succ = p i := begin have : i.cast_succ.val < n := i.is_lt, have h' := fin.cast_lt_cast_succ i i.is_lt, simp [snoc, this, h'], convert cast_eq rfl (p i) end @[simp] lemma snoc_last : snoc p x (last n) = x := by { simp [snoc] } /-- Updating a tuple and adding an element at the end commute. -/ @[simp] lemma snoc_update : snoc (update p i y) x = update (snoc p x) i.cast_succ y := begin ext j, by_cases h : j.val < n, { simp only [snoc, h, dif_pos], by_cases h' : j = cast_succ i, { have C1 : α i.cast_succ = α j, by rw h', have E1 : update (snoc p x) i.cast_succ y j = _root_.cast C1 y, { have : update (snoc p x) j (_root_.cast C1 y) j = _root_.cast C1 y, by simp, convert this, { exact h'.symm }, { exact heq_of_cast_eq (congr_arg α (eq.symm h')) rfl } }, have C2 : α i.cast_succ = α (cast_succ (cast_lt j h)), by rw [cast_succ_cast_lt, h'], have E2 : update p i y (cast_lt j h) = _root_.cast C2 y, { have : update p (cast_lt j h) (_root_.cast C2 y) (cast_lt j h) = _root_.cast C2 y, by simp, convert this, { simp [h, h'] }, { exact heq_of_cast_eq C2 rfl } }, rw [E1, E2], exact eq_rec_compose _ _ _ }, { have : ¬(cast_lt j h = i), by { assume E, apply h', rw [← E, cast_succ_cast_lt] }, simp [h', this, snoc, h] } }, { rw eq_last_of_not_lt h, simp [ne.symm (ne_of_lt (cast_succ_lt_last i))] } end /-- Adding an element at the beginning of a tuple and then updating it amounts to adding it directly. -/ lemma update_snoc_last : update (snoc p x) (last n) z = snoc p z := begin ext j, by_cases h : j.val < n, { have : j ≠ last n := ne_of_lt h, simp [h, update_noteq, this, snoc] }, { rw eq_last_of_not_lt h, simp } end /-- Concatenating the first element of a tuple with its tail gives back the original tuple -/ @[simp] lemma snoc_init_self : snoc (init q) (q (last n)) = q := begin ext j, by_cases h : j.val < n, { have : j ≠ last n := ne_of_lt h, simp [h, update_noteq, this, snoc, init, cast_succ_cast_lt], have A : cast_succ (cast_lt j h) = j := cast_succ_cast_lt _ _, rw ← cast_eq rfl (q j), congr' 1; rw A }, { rw eq_last_of_not_lt h, simp } end /-- Updating the last element of a tuple does not change the beginning. -/ @[simp] lemma init_update_last : init (update q (last n) z) = init q := by { ext j, simp [init, ne_of_lt, cast_succ_lt_last] } /-- Updating an element and taking the beginning commute. -/ @[simp] lemma init_update_cast_succ : init (update q i.cast_succ y) = update (init q) i y := begin ext j, by_cases h : j = i, { rw h, simp [init] }, { simp [init, h] } end /-- `tail` and `init` commute. We state this lemma in a non-dependent setting, as otherwise it would involve a cast to convince Lean that the two types are equal, making it harder to use. -/ lemma tail_init_eq_init_tail {β : Type*} (q : fin (n+2) → β) : tail (init q) = init (tail q) := by { ext i, simp [tail, init, cast_succ_fin_succ] } /-- `cons` and `snoc` commute. We state this lemma in a non-dependent setting, as otherwise it would involve a cast to convince Lean that the two types are equal, making it harder to use. -/ lemma cons_snoc_eq_snoc_cons {β : Type*} (a : β) (q : fin n → β) (b : β) : @cons n.succ (λ i, β) a (snoc q b) = snoc (cons a q) b := begin ext i, by_cases h : i = 0, { rw h, refl }, set j := pred i h with ji, have : i = j.succ, by rw [ji, succ_pred], rw [this, cons_succ], by_cases h' : j.val < n, { set k := cast_lt j h' with jk, have : j = k.cast_succ, by rw [jk, cast_succ_cast_lt], rw [this, ← cast_succ_fin_succ], simp }, rw [eq_last_of_not_lt h', succ_last], simp end lemma comp_snoc {α : Type*} {β : Type*} (g : α → β) (q : fin n → α) (y : α) : g ∘ (snoc q y) = snoc (g ∘ q) (g y) := begin ext j, by_cases h : j.val < n, { have : j ≠ last n := ne_of_lt h, simp [h, this, snoc, cast_succ_cast_lt] }, { rw eq_last_of_not_lt h, simp } end lemma comp_init {α : Type*} {β : Type*} (g : α → β) (q : fin n.succ → α) : g ∘ (init q) = init (g ∘ q) := by { ext j, simp [init] } end tuple_right section insert_nth variables {α : fin (n+1) → Type u} {β : Type v} /-- Define a function on `fin (n + 1)` from a value on `i : fin (n + 1)` and values on each `fin.succ_above i j`, `j : fin n`. This version is elaborated as eliminator and works for propositions, see also `fin.insert_nth` for a version without an `@[elab_as_eliminator]` attribute. -/ @[elab_as_eliminator] def succ_above_cases {α : fin (n + 1) → Sort u} (i : fin (n + 1)) (x : α i) (p : Π j : fin n, α (i.succ_above j)) (j : fin (n + 1)) : α j := if hj : j = i then eq.rec x hj.symm else if hlt : j < i then eq.rec_on (succ_above_cast_lt hlt) (p _) else eq.rec_on (succ_above_pred $ (ne.lt_or_lt hj).resolve_left hlt) (p _) lemma forall_iff_succ_above {p : fin (n + 1) → Prop} (i : fin (n + 1)) : (∀ j, p j) ↔ p i ∧ ∀ j, p (i.succ_above j) := ⟨λ h, ⟨h _, λ j, h _⟩, λ h, succ_above_cases i h.1 h.2⟩ /-- Insert an element into a tuple at a given position. For `i = 0` see `fin.cons`, for `i = fin.last n` see `fin.snoc`. See also `fin.succ_above_cases` for a version elaborated as an eliminator. -/ def insert_nth (i : fin (n + 1)) (x : α i) (p : Π j : fin n, α (i.succ_above j)) (j : fin (n + 1)) : α j := succ_above_cases i x p j @[simp] lemma insert_nth_apply_same (i : fin (n + 1)) (x : α i) (p : Π j, α (i.succ_above j)) : insert_nth i x p i = x := by simp [insert_nth, succ_above_cases] @[simp] lemma insert_nth_apply_succ_above (i : fin (n + 1)) (x : α i) (p : Π j, α (i.succ_above j)) (j : fin n) : insert_nth i x p (i.succ_above j) = p j := begin simp only [insert_nth, succ_above_cases, dif_neg (succ_above_ne _ _)], by_cases hlt : j.cast_succ < i, { rw [dif_pos ((succ_above_lt_iff _ _).2 hlt)], apply eq_of_heq ((eq_rec_heq _ _).trans _), rw [cast_lt_succ_above hlt] }, { rw [dif_neg (mt (succ_above_lt_iff _ _).1 hlt)], apply eq_of_heq ((eq_rec_heq _ _).trans _), rw [pred_succ_above (le_of_not_lt hlt)] } end @[simp] lemma succ_above_cases_eq_insert_nth : @succ_above_cases.{u + 1} = @insert_nth.{u} := rfl @[simp] lemma insert_nth_comp_succ_above (i : fin (n + 1)) (x : β) (p : fin n → β) : insert_nth i x p ∘ i.succ_above = p := funext $ insert_nth_apply_succ_above i x p lemma insert_nth_eq_iff {i : fin (n + 1)} {x : α i} {p : Π j, α (i.succ_above j)} {q : Π j, α j} : i.insert_nth x p = q ↔ q i = x ∧ p = (λ j, q (i.succ_above j)) := by simp [funext_iff, forall_iff_succ_above i, eq_comm] lemma eq_insert_nth_iff {i : fin (n + 1)} {x : α i} {p : Π j, α (i.succ_above j)} {q : Π j, α j} : q = i.insert_nth x p ↔ q i = x ∧ p = (λ j, q (i.succ_above j)) := eq_comm.trans insert_nth_eq_iff lemma insert_nth_apply_below {i j : fin (n + 1)} (h : j < i) (x : α i) (p : Π k, α (i.succ_above k)) : i.insert_nth x p j = eq.rec_on (succ_above_cast_lt h) (p $ j.cast_lt _) := by rw [insert_nth, succ_above_cases, dif_neg h.ne, dif_pos h] lemma insert_nth_apply_above {i j : fin (n + 1)} (h : i < j) (x : α i) (p : Π k, α (i.succ_above k)) : i.insert_nth x p j = eq.rec_on (succ_above_pred h) (p $ j.pred _) := by rw [insert_nth, succ_above_cases, dif_neg h.ne', dif_neg h.not_lt] lemma insert_nth_zero (x : α 0) (p : Π j : fin n, α (succ_above 0 j)) : insert_nth 0 x p = cons x (λ j, _root_.cast (congr_arg α (congr_fun succ_above_zero j)) (p j)) := begin refine insert_nth_eq_iff.2 ⟨by simp, _⟩, ext j, convert (cons_succ _ _ _).symm end @[simp] lemma insert_nth_zero' (x : β) (p : fin n → β) : @insert_nth _ (λ _, β) 0 x p = cons x p := by simp [insert_nth_zero] lemma insert_nth_last (x : α (last n)) (p : Π j : fin n, α ((last n).succ_above j)) : insert_nth (last n) x p = snoc (λ j, _root_.cast (congr_arg α (succ_above_last_apply j)) (p j)) x := begin refine insert_nth_eq_iff.2 ⟨by simp, _⟩, ext j, apply eq_of_heq, transitivity snoc (λ j, _root_.cast (congr_arg α (succ_above_last_apply j)) (p j)) x j.cast_succ, { rw [snoc_cast_succ], exact (cast_heq _ _).symm }, { apply congr_arg_heq, rw [succ_above_last] } end @[simp] lemma insert_nth_last' (x : β) (p : fin n → β) : @insert_nth _ (λ _, β) (last n) x p = snoc p x := by simp [insert_nth_last] @[simp] lemma insert_nth_zero_right [Π j, has_zero (α j)] (i : fin (n + 1)) (x : α i) : i.insert_nth x 0 = pi.single i x := insert_nth_eq_iff.2 $ by simp [succ_above_ne, pi.zero_def] lemma insert_nth_binop (op : Π j, α j → α j → α j) (i : fin (n + 1)) (x y : α i) (p q : Π j, α (i.succ_above j)) : i.insert_nth (op i x y) (λ j, op _ (p j) (q j)) = λ j, op j (i.insert_nth x p j) (i.insert_nth y q j) := insert_nth_eq_iff.2 $ by simp @[simp] lemma insert_nth_mul [Π j, has_mul (α j)] (i : fin (n + 1)) (x y : α i) (p q : Π j, α (i.succ_above j)) : i.insert_nth (x * y) (p * q) = i.insert_nth x p * i.insert_nth y q := insert_nth_binop (λ _, (*)) i x y p q @[simp] lemma insert_nth_add [Π j, has_add (α j)] (i : fin (n + 1)) (x y : α i) (p q : Π j, α (i.succ_above j)) : i.insert_nth (x + y) (p + q) = i.insert_nth x p + i.insert_nth y q := insert_nth_binop (λ _, (+)) i x y p q @[simp] lemma insert_nth_div [Π j, has_div (α j)] (i : fin (n + 1)) (x y : α i) (p q : Π j, α (i.succ_above j)) : i.insert_nth (x / y) (p / q) = i.insert_nth x p / i.insert_nth y q := insert_nth_binop (λ _, (/)) i x y p q @[simp] lemma insert_nth_sub [Π j, has_sub (α j)] (i : fin (n + 1)) (x y : α i) (p q : Π j, α (i.succ_above j)) : i.insert_nth (x - y) (p - q) = i.insert_nth x p - i.insert_nth y q := insert_nth_binop (λ _, has_sub.sub) i x y p q @[simp] lemma insert_nth_sub_same [Π j, add_group (α j)] (i : fin (n + 1)) (x y : α i) (p : Π j, α (i.succ_above j)) : i.insert_nth x p - i.insert_nth y p = pi.single i (x - y) := by simp_rw [← insert_nth_sub, ← insert_nth_zero_right, pi.sub_def, sub_self, pi.zero_def] variables [Π i, preorder (α i)] lemma insert_nth_le_iff {i : fin (n + 1)} {x : α i} {p : Π j, α (i.succ_above j)} {q : Π j, α j} : i.insert_nth x p ≤ q ↔ x ≤ q i ∧ p ≤ (λ j, q (i.succ_above j)) := by simp [pi.le_def, forall_iff_succ_above i] lemma le_insert_nth_iff {i : fin (n + 1)} {x : α i} {p : Π j, α (i.succ_above j)} {q : Π j, α j} : q ≤ i.insert_nth x p ↔ q i ≤ x ∧ (λ j, q (i.succ_above j)) ≤ p := by simp [pi.le_def, forall_iff_succ_above i] open set lemma insert_nth_mem_Icc {i : fin (n + 1)} {x : α i} {p : Π j, α (i.succ_above j)} {q₁ q₂ : Π j, α j} : i.insert_nth x p ∈ Icc q₁ q₂ ↔ x ∈ Icc (q₁ i) (q₂ i) ∧ p ∈ Icc (λ j, q₁ (i.succ_above j)) (λ j, q₂ (i.succ_above j)) := by simp only [mem_Icc, insert_nth_le_iff, le_insert_nth_iff, and.assoc, and.left_comm] lemma preimage_insert_nth_Icc_of_mem {i : fin (n + 1)} {x : α i} {q₁ q₂ : Π j, α j} (hx : x ∈ Icc (q₁ i) (q₂ i)) : i.insert_nth x ⁻¹' (Icc q₁ q₂) = Icc (λ j, q₁ (i.succ_above j)) (λ j, q₂ (i.succ_above j)) := set.ext $ λ p, by simp only [mem_preimage, insert_nth_mem_Icc, hx, true_and] lemma preimage_insert_nth_Icc_of_not_mem {i : fin (n + 1)} {x : α i} {q₁ q₂ : Π j, α j} (hx : x ∉ Icc (q₁ i) (q₂ i)) : i.insert_nth x ⁻¹' (Icc q₁ q₂) = ∅ := set.ext $ λ p, by simp only [mem_preimage, insert_nth_mem_Icc, hx, false_and, mem_empty_eq] end insert_nth section find /-- `find p` returns the first index `n` where `p n` is satisfied, and `none` if it is never satisfied. -/ def find : Π {n : ℕ} (p : fin n → Prop) [decidable_pred p], option (fin n) | 0 p _ := none | (n+1) p _ := by resetI; exact option.cases_on (@find n (λ i, p (i.cast_lt (nat.lt_succ_of_lt i.2))) _) (if h : p (fin.last n) then some (fin.last n) else none) (λ i, some (i.cast_lt (nat.lt_succ_of_lt i.2))) /-- If `find p = some i`, then `p i` holds -/ lemma find_spec : Π {n : ℕ} (p : fin n → Prop) [decidable_pred p] {i : fin n} (hi : i ∈ by exactI fin.find p), p i | 0 p I i hi := option.no_confusion hi | (n+1) p I i hi := begin dsimp [find] at hi, resetI, cases h : find (λ i : fin n, (p (i.cast_lt (nat.lt_succ_of_lt i.2)))) with j, { rw h at hi, dsimp at hi, split_ifs at hi with hl hl, { exact option.some_inj.1 hi ▸ hl }, { exact option.no_confusion hi } }, { rw h at hi, rw [← option.some_inj.1 hi], exact find_spec _ h } end /-- `find p` does not return `none` if and only if `p i` holds at some index `i`. -/ lemma is_some_find_iff : Π {n : ℕ} {p : fin n → Prop} [decidable_pred p], by exactI (find p).is_some ↔ ∃ i, p i | 0 p _ := iff_of_false (λ h, bool.no_confusion h) (λ ⟨i, _⟩, fin_zero_elim i) | (n+1) p _ := ⟨λ h, begin rw [option.is_some_iff_exists] at h, cases h with i hi, exactI ⟨i, find_spec _ hi⟩ end, λ ⟨⟨i, hin⟩, hi⟩, begin resetI, dsimp [find], cases h : find (λ i : fin n, (p (i.cast_lt (nat.lt_succ_of_lt i.2)))) with j, { split_ifs with hl hl, { exact option.is_some_some }, { have := (@is_some_find_iff n (λ x, p (x.cast_lt (nat.lt_succ_of_lt x.2))) _).2 ⟨⟨i, lt_of_le_of_ne (nat.le_of_lt_succ hin) (λ h, by clear_aux_decl; cases h; exact hl hi)⟩, hi⟩, rw h at this, exact this } }, { simp } end⟩ /-- `find p` returns `none` if and only if `p i` never holds. -/ lemma find_eq_none_iff {n : ℕ} {p : fin n → Prop} [decidable_pred p] : find p = none ↔ ∀ i, ¬ p i := by rw [← not_exists, ← is_some_find_iff]; cases (find p); simp /-- If `find p` returns `some i`, then `p j` does not hold for `j < i`, i.e., `i` is minimal among the indices where `p` holds. -/ lemma find_min : Π {n : ℕ} {p : fin n → Prop} [decidable_pred p] {i : fin n} (hi : i ∈ by exactI fin.find p) {j : fin n} (hj : j < i), ¬ p j | 0 p _ i hi j hj hpj := option.no_confusion hi | (n+1) p _ i hi ⟨j, hjn⟩ hj hpj := begin resetI, dsimp [find] at hi, cases h : find (λ i : fin n, (p (i.cast_lt (nat.lt_succ_of_lt i.2)))) with k, { rw [h] at hi, split_ifs at hi with hl hl, { have := option.some_inj.1 hi, subst this, rw [find_eq_none_iff] at h, exact h ⟨j, hj⟩ hpj }, { exact option.no_confusion hi } }, { rw h at hi, dsimp at hi, have := option.some_inj.1 hi, subst this, exact find_min h (show (⟨j, lt_trans hj k.2⟩ : fin n) < k, from hj) hpj } end lemma find_min' {p : fin n → Prop} [decidable_pred p] {i : fin n} (h : i ∈ fin.find p) {j : fin n} (hj : p j) : i ≤ j := le_of_not_gt (λ hij, find_min h hij hj) lemma nat_find_mem_find {p : fin n → Prop} [decidable_pred p] (h : ∃ i, ∃ hin : i < n, p ⟨i, hin⟩) : (⟨nat.find h, (nat.find_spec h).fst⟩ : fin n) ∈ find p := let ⟨i, hin, hi⟩ := h in begin cases hf : find p with f, { rw [find_eq_none_iff] at hf, exact (hf ⟨i, hin⟩ hi).elim }, { refine option.some_inj.2 (le_antisymm _ _), { exact find_min' hf (nat.find_spec h).snd }, { exact nat.find_min' _ ⟨f.2, by convert find_spec p hf; exact fin.eta _ _⟩ } } end lemma mem_find_iff {p : fin n → Prop} [decidable_pred p] {i : fin n} : i ∈ fin.find p ↔ p i ∧ ∀ j, p j → i ≤ j := ⟨λ hi, ⟨find_spec _ hi, λ _, find_min' hi⟩, begin rintros ⟨hpi, hj⟩, cases hfp : fin.find p, { rw [find_eq_none_iff] at hfp, exact (hfp _ hpi).elim }, { exact option.some_inj.2 (le_antisymm (find_min' hfp hpi) (hj _ (find_spec _ hfp))) } end⟩ lemma find_eq_some_iff {p : fin n → Prop} [decidable_pred p] {i : fin n} : fin.find p = some i ↔ p i ∧ ∀ j, p j → i ≤ j := mem_find_iff lemma mem_find_of_unique {p : fin n → Prop} [decidable_pred p] (h : ∀ i j, p i → p j → i = j) {i : fin n} (hi : p i) : i ∈ fin.find p := mem_find_iff.2 ⟨hi, λ j hj, le_of_eq $ h i j hi hj⟩ end find @[simp] lemma coe_of_nat_eq_mod (m n : ℕ) : ((n : fin (succ m)) : ℕ) = n % succ m := by rw [← of_nat_eq_coe]; refl @[simp] lemma coe_of_nat_eq_mod' (m n : ℕ) [I : fact (0 < m)] : (@fin.of_nat' _ I n : ℕ) = n % m := rfl section mul /-! ### mul -/ lemma val_mul {n : ℕ} : ∀ a b : fin n, (a * b).val = (a.val * b.val) % n | ⟨_, _⟩ ⟨_, _⟩ := rfl lemma coe_mul {n : ℕ} : ∀ a b : fin n, ((a * b : fin n) : ℕ) = (a * b) % n | ⟨_, _⟩ ⟨_, _⟩ := rfl @[simp] protected lemma mul_one (k : fin (n + 1)) : k * 1 = k := by { cases n, simp, simp [eq_iff_veq, mul_def, mod_eq_of_lt (is_lt k)] } @[simp] protected lemma one_mul (k : fin (n + 1)) : (1 : fin (n + 1)) * k = k := by { cases n, simp, simp [eq_iff_veq, mul_def, mod_eq_of_lt (is_lt k)] } @[simp] protected lemma mul_zero (k : fin (n + 1)) : k * 0 = 0 := by simp [eq_iff_veq, mul_def] @[simp] protected lemma zero_mul (k : fin (n + 1)) : (0 : fin (n + 1)) * k = 0 := by simp [eq_iff_veq, mul_def] end mul end fin
f954606e1506f1684f0868877f2d925879476ed7
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/tests/lean/StxQuot.lean
9051e32695e4265c0a981b57360beef95ffb395a
[ "Apache-2.0" ]
permissive
collares/lean4
861a9269c4592bce49b71059e232ff0bfe4594cc
52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee
refs/heads/master
1,691,419,031,324
1,618,678,138,000
1,618,678,138,000
358,989,750
0
0
Apache-2.0
1,618,696,333,000
1,618,696,333,000
null
UTF-8
Lean
false
false
4,125
lean
import Lean open Lean open Lean.Elab def run {α} [ToString α] : Unhygienic α → String := toString ∘ Unhygienic.run #eval run `() #eval run `(Nat.one) #eval run `($Syntax.missing) namespace Lean.Syntax #eval run `($missing) #eval run `($(missing)) #eval run `($(id Syntax.missing) + 1) #eval run $ let id := Syntax.missing; `($id + 1) end Lean.Syntax #eval run `(1 + 1) #eval run `([x,]) #eval run $ `(fun a => a) >>= pure #eval run $ `(def foo := 1) #eval run $ `(def foo := 1 def bar := 2) #eval run $ do let a ← `(Nat.one); `($a) #eval run $ do `($(← `(Nat.one))) #eval run $ do let a ← `(Nat.one); `(f $a $a) #eval run $ do let a ← `(Nat.one); `(f $ f $a 1) #eval run $ do let a ← `(Nat.one); `(f $(id a)) #eval run $ do let a ← `(Nat.one); `($(a).b) #eval run $ do let a ← `(1 + 2); match a with | `($a + $b) => `($b + $a) | _ => pure Syntax.missing #eval run $ do let a ← `(1 + 2); match a with | stx@`($a + $b) => `($stx + $a) | _ => pure Syntax.missing #eval run $ do let a ← `(def foo := 1); match a with | `($f:command) => pure f | _ => pure Syntax.missing #eval run $ do let a ← `(def foo := 1 def bar := 2); match a with | `($f:command $g:command) => `($g:command $f:command) | _ => pure Syntax.missing #eval run $ do let a ← `(aa); match a with | `($id:ident) => pure 0 | `($e) => pure 1 | _ => pure 2 #eval match mkIdent `aa with | `(aa) => 0 | _ => 1 #eval match mkIdent `aa with | `(ab) => 0 | _ => 1 #eval run $ do let a ← `(1 + 2); match a with | `($id:ident) => pure 0 | `($e) => pure 1 | _ => pure 2 #eval run $ do let params ← #[`(a), `((b : Nat))].mapM id; `(fun $params* => 1) #eval run $ do let a ← `(fun (a : Nat) b => c); match a with | `(fun $aa* => $e) => pure aa | _ => pure #[] #eval run $ do let a ← `(∀ a, c); match a with | `(∀ $id:ident, $e) => pure id | _ => pure a #eval run $ do let a ← `(∀ _, c); match a with | `(∀ $id:ident, $e) => pure id | _ => pure a -- this one should NOT check the kind of the matched node #eval run $ do let a ← `(∀ _, c); match a with | `(∀ $a, $e) => pure a | _ => pure a #eval run $ do let a ← `(a); match a with | `($id:ident) => pure id | _ => pure a #eval run $ do let a ← `(a.{0}); match a with | `($id:ident) => pure id | _ => pure a #eval run $ do let a ← `(match a with | a => 1 | _ => 2); match a with | `(match $e:term with $eqns:matchAlt*) => pure eqns | _ => pure #[] def f (stx : Syntax) : Unhygienic Syntax := match stx with | `({ $f:ident := $e $[: $a]?}) => `({ $f:ident := $e $[: $(id a)]?}) | _ => unreachable! #eval run do f (← `({ a := a : a })) #eval run do f (← `({ a := a })) def f' (stx : Syntax) : Unhygienic Syntax := match stx with | `(section $(id?)?) => `(section $(id?)?) | _ => unreachable! #eval run do f' (← `(section)) #eval run do f' (← `(section foo)) #eval run do match ← `(match a with | a => b | a + 1 => b + 1) with | `(match $e:term with $[| $pats =>%$arr $rhss]*) => `(match $e:term with $[| $pats =>%$arr $rhss]*) | _ => unreachable! #eval run do match ← `(match a with | a => b | a + 1 => b + 1) with | `(match $e:term with $alts:matchAlt*) => `(match $e:term with $alts:matchAlt*) | _ => unreachable! open Parser.Term #eval run do match ← `(structInstField|a := b) with | `(Parser.Term.structInstField| $lhs:ident := $rhs) => #[lhs, rhs] | _ => unreachable! #eval run do match ← `({ a := a : a }) with | `({ $f:ident := $e : 0 }) => "0" | `({ $f:ident := $e $[: $a?]?}) => "1" | stx => "2" #eval run `(sufficesDecl|x from x) #eval run do match ← `([1, 2, 3, 4]) with | `([$x, $ys,*, $z]) => #[x, mkNullNode ys, z] | _ => unreachable! #eval run do match ← `([1, 2]) with | `([$x, $y, $zs,*]) => zs.getElems | `([$x, $ys,*]) => ys.getElems | _ => unreachable! #check (match · with | `([1, $ys,*, 2, $zs,*, 3]) => _) #eval run do match Syntax.setHeadInfo (← `(fun x =>%$(Syntax.atom (SourceInfo.synthetic 2 2) "") x)) (SourceInfo.synthetic 1 1) with | `(fun%$i1 $x =>%$i2 $y) => pure #[i1.getPos?, i2.getPos?] | _ => unreachable!
3aa3e55c3736c59f9d8e70d99374145692872624
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/06_Inductive_Types.org.45.lean
5b7a8de01700362f176c63c241aa10d5c30791b9
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
530
lean
/- page 92 -/ import standard namespace hide inductive eq {A : Type} (a : A) : A → Prop := refl : eq a a theorem subst {A : Type} {a b : A} {P : A → Prop} (H₁ : eq a b) (H₂ : P a) : P b := eq.rec H₂ H₁ -- BEGIN theorem symm {A : Type} {a b : A} (H : eq a b) : eq b a := subst H (eq.refl a) theorem trans {A : Type} {a b c : A} (H₁ : eq a b) (H₂ : eq b c) : eq a c := subst H₂ H₁ theorem congr {A B : Type} {a b : A} (f : A → B) (H : eq a b) : eq (f a) (f b) := subst H (eq.refl (f a)) -- END end hide
75acdd5d3317188a7e0ff1a12e33bc62a96a2a93
8b9f17008684d796c8022dab552e42f0cb6fb347
/hott/algebra/precategory/functor.hlean
7413458bfbd522c1b886fd6ac89fe09c14d75a9a
[ "Apache-2.0" ]
permissive
chubbymaggie/lean
0d06ae25f9dd396306fb02190e89422ea94afd7b
d2c7b5c31928c98f545b16420d37842c43b4ae9a
refs/heads/master
1,611,313,622,901
1,430,266,839,000
1,430,267,083,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,596
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: algebra.precategory.functor Authors: Floris van Doorn, Jakob von Raumer -/ import .basic types.pi .iso open function category eq prod equiv is_equiv sigma sigma.ops is_trunc funext iso open pi structure functor (C D : Precategory) : Type := (to_fun_ob : C → D) (to_fun_hom : Π ⦃a b : C⦄, hom a b → hom (to_fun_ob a) (to_fun_ob b)) (respect_id : Π (a : C), to_fun_hom (ID a) = ID (to_fun_ob a)) (respect_comp : Π {a b c : C} (g : hom b c) (f : hom a b), to_fun_hom (g ∘ f) = to_fun_hom g ∘ to_fun_hom f) namespace functor infixl `⇒`:25 := functor variables {A B C D E : Precategory} attribute to_fun_ob [coercion] attribute to_fun_hom [coercion] -- The following lemmas will later be used to prove that the type of -- precategories forms a precategory itself protected definition compose [reducible] (G : functor D E) (F : functor C D) : functor C E := functor.mk (λ x, G (F x)) (λ a b f, G (F f)) (λ a, calc G (F (ID a)) = G (ID (F a)) : by rewrite respect_id ... = ID (G (F a)) : by rewrite respect_id) (λ a b c g f, calc G (F (g ∘ f)) = G (F g ∘ F f) : by rewrite respect_comp ... = G (F g) ∘ G (F f) : by rewrite respect_comp) infixr `∘f`:60 := compose protected definition id [reducible] {C : Precategory} : functor C C := mk (λa, a) (λ a b f, f) (λ a, idp) (λ a b c f g, idp) protected definition ID [reducible] (C : Precategory) : functor C C := id definition functor_mk_eq' {F₁ F₂ : C → D} {H₁ : Π(a b : C), hom a b → hom (F₁ a) (F₁ b)} {H₂ : Π(a b : C), hom a b → hom (F₂ a) (F₂ b)} (id₁ id₂ comp₁ comp₂) (pF : F₁ = F₂) (pH : pF ▹ H₁ = H₂) : functor.mk F₁ H₁ id₁ comp₁ = functor.mk F₂ H₂ id₂ comp₂ := apD01111 functor.mk pF pH !is_hprop.elim !is_hprop.elim definition functor_eq' {F₁ F₂ : C ⇒ D} : Π(p : to_fun_ob F₁ = to_fun_ob F₂), (transport (λx, Πa b f, hom (x a) (x b)) p (to_fun_hom F₁) = to_fun_hom F₂) → F₁ = F₂ := functor.rec_on F₁ (λO₁ H₁ id₁ comp₁, functor.rec_on F₂ (λO₂ H₂ id₂ comp₂ p, !functor_mk_eq')) definition functor_mk_eq {F₁ F₂ : C → D} {H₁ : Π(a b : C), hom a b → hom (F₁ a) (F₁ b)} {H₂ : Π(a b : C), hom a b → hom (F₂ a) (F₂ b)} (id₁ id₂ comp₁ comp₂) (pF : F₁ ∼ F₂) (pH : Π(a b : C) (f : hom a b), hom_of_eq (pF b) ∘ H₁ a b f ∘ inv_of_eq (pF a) = H₂ a b f) : functor.mk F₁ H₁ id₁ comp₁ = functor.mk F₂ H₂ id₂ comp₂ := functor_mk_eq' id₁ id₂ comp₁ comp₂ (eq_of_homotopy pF) (eq_of_homotopy (λc, eq_of_homotopy (λc', eq_of_homotopy (λf, begin apply concat, rotate_left 1, exact (pH c c' f), apply concat, rotate_left 1, apply transport_hom, apply concat, rotate_left 1, exact (pi_transport_constant (eq_of_homotopy pF) (H₁ c c') f), apply (apD10' f), apply concat, rotate_left 1, esimp, exact (pi_transport_constant (eq_of_homotopy pF) (H₁ c) c'), apply (apD10' c'), apply concat, rotate_left 1, esimp, exact (pi_transport_constant (eq_of_homotopy pF) H₁ c), apply idp end)))) definition functor_eq {F₁ F₂ : C ⇒ D} : Π(p : to_fun_ob F₁ ∼ to_fun_ob F₂), (Π(a b : C) (f : hom a b), hom_of_eq (p b) ∘ F₁ f ∘ inv_of_eq (p a) = F₂ f) → F₁ = F₂ := functor.rec_on F₁ (λO₁ H₁ id₁ comp₁, functor.rec_on F₂ (λO₂ H₂ id₂ comp₂ p, !functor_mk_eq)) definition functor_mk_eq_constant {F : C → D} {H₁ : Π(a b : C), hom a b → hom (F a) (F b)} {H₂ : Π(a b : C), hom a b → hom (F a) (F b)} (id₁ id₂ comp₁ comp₂) (pH : Π(a b : C) (f : hom a b), H₁ a b f = H₂ a b f) : functor.mk F H₁ id₁ comp₁ = functor.mk F H₂ id₂ comp₂ := functor_eq (λc, idp) (λa b f, !id_leftright ⬝ !pH) protected definition preserve_iso (F : C ⇒ D) {a b : C} (f : hom a b) [H : is_iso f] : is_iso (F f) := begin fapply @is_iso.mk, apply (F (f⁻¹)), repeat (apply concat ; apply inverse ; apply (respect_comp F) ; apply concat ; apply (ap (λ x, to_fun_hom F x)) ; (apply left_inverse | apply right_inverse); apply (respect_id F) ), end attribute preserve_iso [instance] protected definition respect_inv (F : C ⇒ D) {a b : C} (f : hom a b) [H : is_iso f] [H' : is_iso (F f)] : F (f⁻¹) = (F f)⁻¹ := begin fapply @left_inverse_eq_right_inverse, apply (F f), apply concat, apply inverse, apply (respect_comp F), apply concat, apply (ap (λ x, to_fun_hom F x)), apply left_inverse, apply respect_id, apply right_inverse, end protected definition assoc (H : C ⇒ D) (G : B ⇒ C) (F : A ⇒ B) : H ∘f (G ∘f F) = (H ∘f G) ∘f F := !functor_mk_eq_constant (λa b f, idp) protected definition id_left (F : C ⇒ D) : id ∘f F = F := functor.rec_on F (λF1 F2 F3 F4, !functor_mk_eq_constant (λa b f, idp)) protected definition id_right (F : C ⇒ D) : F ∘f id = F := functor.rec_on F (λF1 F2 F3 F4, !functor_mk_eq_constant (λa b f, idp)) protected definition comp_id_eq_id_comp (F : C ⇒ D) : F ∘f functor.id = functor.id ∘f F := !functor.id_right ⬝ !functor.id_left⁻¹ -- "functor C D" is equivalent to a certain sigma type protected definition sigma_char : (Σ (to_fun_ob : C → D) (to_fun_hom : Π ⦃a b : C⦄, hom a b → hom (to_fun_ob a) (to_fun_ob b)), (Π (a : C), to_fun_hom (ID a) = ID (to_fun_ob a)) × (Π {a b c : C} (g : hom b c) (f : hom a b), to_fun_hom (g ∘ f) = to_fun_hom g ∘ to_fun_hom f)) ≃ (functor C D) := begin fapply equiv.MK, {intro S, fapply functor.mk, exact (S.1), exact (S.2.1), -- TODO(Leo): investigate why we need to use relaxed-exact (rexact) tactic here exact (pr₁ S.2.2), rexact (pr₂ S.2.2)}, {intro F, cases F with [d1, d2, d3, d4], exact ⟨d1, d2, (d3, @d4)⟩}, {intro F, cases F, apply idp}, {intro S, cases S with [d1, S2], cases S2 with [d2, P1], cases P1, apply idp}, end set_option apply.class_instance false protected definition is_hset_functor [HD : is_hset D] : is_hset (functor C D) := begin apply is_trunc_is_equiv_closed, apply equiv.to_is_equiv, apply sigma_char, apply is_trunc_sigma, apply is_trunc_pi, intros, exact HD, intro F, apply is_trunc_sigma, apply is_trunc_pi, intro a, {apply is_trunc_pi, intro b, apply is_trunc_pi, intro c, apply !homH}, intro H, apply is_trunc_prod, {apply is_trunc_pi, intro a, apply is_trunc_eq, apply is_trunc_succ, apply !homH}, {repeat (apply is_trunc_pi; intros), apply is_trunc_eq, apply is_trunc_succ, apply !homH}, end definition functor_mk_eq'_idp (F : C → D) (H : Π(a b : C), hom a b → hom (F a) (F b)) (id comp) : functor_mk_eq' id id comp comp (idpath F) (idpath H) = idp := begin fapply (apD011 (apD01111 functor.mk idp idp)), apply is_hset.elim, apply is_hset.elim end definition functor_eq'_idp (F : C ⇒ D) : functor_eq' idp idp = (idpath F) := by (cases F; apply functor_mk_eq'_idp) definition functor_eq_eta' {F₁ F₂ : C ⇒ D} (p : F₁ = F₂) : functor_eq' (ap to_fun_ob p) (!transport_compose⁻¹ ⬝ apD to_fun_hom p) = p := begin cases p, cases F₁, apply concat, rotate_left 1, apply functor_eq'_idp, apply (ap (functor_eq' idp)), apply idp_con, end definition functor_eq2' {F₁ F₂ : C ⇒ D} {p₁ p₂ : to_fun_ob F₁ = to_fun_ob F₂} (q₁ q₂) (r : p₁ = p₂) : functor_eq' p₁ q₁ = functor_eq' p₂ q₂ := by cases r; apply (ap (functor_eq' p₂)); apply is_hprop.elim definition functor_eq2 {F₁ F₂ : C ⇒ D} (p q : F₁ = F₂) (r : ap010 to_fun_ob p ∼ ap010 to_fun_ob q) : p = q := begin cases F₁ with [ob₁, hom₁, id₁, comp₁], cases F₂ with [ob₂, hom₂, id₂, comp₂], rewrite [-functor_eq_eta' p, -functor_eq_eta' q], apply functor_eq2', apply ap_eq_ap_of_homotopy, exact r, end -- definition ap010_functor_eq_mk' {F₁ F₂ : C ⇒ D} (p : to_fun_ob F₁ = to_fun_ob F₂) -- (q : p ▹ F₁ = F₂) (c : C) : -- ap to_fun_ob (functor_eq_mk (apD10 p) (λa b f, _)) = p := sorry -- begin -- cases F₂, revert q, apply (homotopy.rec_on p), clear p, esimp, intros (p, q), -- cases p, clears (e_1, e_2), -- end -- TODO: remove sorry definition ap010_functor_eq {F₁ F₂ : C ⇒ D} (p : to_fun_ob F₁ ∼ to_fun_ob F₂) (q : (λ(a b : C) (f : hom a b), hom_of_eq (p b) ∘ F₁ f ∘ inv_of_eq (p a)) ∼3 to_fun_hom F₂) (c : C) : ap010 to_fun_ob (functor_eq p q) c = p c := begin cases F₂, revert q, apply (homotopy.rec_on p), clear p, esimp, intros [p, q], apply sorry, --apply (homotopy3.rec_on q), clear q, intro q, --cases p, --TODO: report: this fails end definition ap010_functor_mk_eq_constant {F : C → D} {H₁ : Π(a b : C), hom a b → hom (F a) (F b)} {H₂ : Π(a b : C), hom a b → hom (F a) (F b)} {id₁ id₂ comp₁ comp₂} (pH : Π(a b : C) (f : hom a b), H₁ a b f = H₂ a b f) (c : C) : ap010 to_fun_ob (functor_mk_eq_constant id₁ id₂ comp₁ comp₂ pH) c = idp := !ap010_functor_eq --do we need this theorem? definition compose_pentagon (K : D ⇒ E) (H : C ⇒ D) (G : B ⇒ C) (F : A ⇒ B) : (calc K ∘f H ∘f G ∘f F = (K ∘f H) ∘f G ∘f F : functor.assoc ... = ((K ∘f H) ∘f G) ∘f F : functor.assoc) = (calc K ∘f H ∘f G ∘f F = K ∘f (H ∘f G) ∘f F : ap (λx, K ∘f x) !functor.assoc ... = (K ∘f H ∘f G) ∘f F : functor.assoc ... = ((K ∘f H) ∘f G) ∘f F : ap (λx, x ∘f F) !functor.assoc) := sorry -- begin -- apply functor_eq2, -- intro a, -- rewrite +ap010_con, -- -- rewrite +ap010_ap, -- -- apply sorry -- /-to prove this we need a stronger ap010-lemma, something like -- ap010 (λy, to_fun_ob (f y)) (functor_mk_eq_constant ...) c = idp -- or something another way of getting ap out of ap010 -- -/ -- --rewrite +ap010_ap, -- --unfold functor.assoc, -- --rewrite ap010_functor_mk_eq_constant, -- end end functor
e84b9c71c12b5e630f0c1828ad2d900061069c28
bb31430994044506fa42fd667e2d556327e18dfe
/src/ring_theory/ring_hom/surjective.lean
a2687a5774905350636dca2df630116991e7b9db
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
2,476
lean
/- Copyright (c) 2022 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang -/ import ring_theory.local_properties /-! # The meta properties of surjective ring homomorphisms. -/ namespace ring_hom open_locale tensor_product open tensor_product algebra.tensor_product local notation `surjective` := λ {X Y : Type*} [comm_ring X] [comm_ring Y] , by exactI λ (f : X →+* Y), function.surjective f lemma surjective_stable_under_composition : stable_under_composition surjective := by { introv R hf hg, exactI hg.comp hf } lemma surjective_respects_iso : respects_iso surjective := begin apply surjective_stable_under_composition.respects_iso, introsI, exact e.surjective end lemma surjective_stable_under_base_change : stable_under_base_change surjective := begin refine stable_under_base_change.mk _ surjective_respects_iso _, classical, introv h x, resetI, induction x using tensor_product.induction_on with x y x y ex ey, { exact ⟨0, map_zero _⟩ }, { obtain ⟨y, rfl⟩ := h y, use y • x, dsimp, rw [tensor_product.smul_tmul, algebra.algebra_map_eq_smul_one] }, { obtain ⟨⟨x, rfl⟩, ⟨y, rfl⟩⟩ := ⟨ex, ey⟩, exact ⟨x + y, map_add _ x y⟩ } end open_locale big_operators lemma surjective_of_localization_span : of_localization_span surjective := begin introv R hs H, resetI, letI := f.to_algebra, show function.surjective (algebra.of_id R S), rw [← algebra.range_top_iff_surjective, eq_top_iff], rintro x -, obtain ⟨l, hl⟩ := (finsupp.mem_span_iff_total R s 1).mp (show _ ∈ ideal.span s, by { rw hs, trivial }), fapply subalgebra.mem_of_finset_sum_eq_one_of_pow_smul_mem _ l.support (λ x : s, f x) (λ x : s, f (l x)), { dsimp only, simp_rw [← _root_.map_mul, ← map_sum, ← f.map_one], exact f.congr_arg hl }, { exact λ _, set.mem_range_self _ }, { exact λ _, set.mem_range_self _ }, { intro r, obtain ⟨y, hy⟩ := H r (is_localization.mk' _ x (1 : submonoid.powers (f r))), obtain ⟨z, ⟨_, n, rfl⟩, rfl⟩ := is_localization.mk'_surjective (submonoid.powers (r : R)) y, erw [is_localization.map_mk', is_localization.eq] at hy, obtain ⟨⟨_, m, rfl⟩, hm⟩ := hy, dsimp at hm, simp_rw [_root_.mul_assoc, _root_.one_mul, ← map_pow, ← f.map_mul, ← pow_add, mul_comm x] at hm, rw map_pow at hm, refine ⟨n + m, _, hm⟩ } end end ring_hom
8ec14e9787bfad6067b8f3fb83a8eaf17dc4e596
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/topology/algebra/floor_ring.lean
bf9f481ca3b0c9cf1345881d8efc95a811317ca3
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
9,346
lean
/- Copyright (c) 2020 Anatole Dedecker. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anatole Dedecker Basic topological facts (limits and continuity) about `floor`, `ceil` and `fract` in a `floor_ring`. -/ import topology.algebra.ordered import algebra.floor open set function filter open_locale topological_space variables {α : Type*} [linear_ordered_ring α] [floor_ring α] lemma tendsto_floor_at_top : tendsto (floor : α → ℤ) at_top at_top := begin refine monotone.tendsto_at_top_at_top (λ a b hab, floor_mono hab) (λ b, _), use (b : α) + ((1 : ℤ) : α), rw [floor_add_int, floor_coe], exact (lt_add_one _).le end lemma tendsto_floor_at_bot : tendsto (floor : α → ℤ) at_bot at_bot := begin refine monotone.tendsto_at_bot_at_bot (λ a b hab, floor_mono hab) (λ b, ⟨b, _⟩), rw floor_coe end lemma tendsto_ceil_at_top : tendsto (ceil : α → ℤ) at_top at_top := tendsto_neg_at_bot_at_top.comp (tendsto_floor_at_bot.comp tendsto_neg_at_top_at_bot) lemma tendsto_ceil_at_bot : tendsto (ceil : α → ℤ) at_bot at_bot := tendsto_neg_at_top_at_bot.comp (tendsto_floor_at_top.comp tendsto_neg_at_bot_at_top) variables [topological_space α] lemma continuous_on_floor (n : ℤ) : continuous_on (λ x, floor x : α → α) (Ico n (n+1) : set α) := (continuous_on_congr $ floor_eq_on_Ico' n).mpr continuous_on_const lemma continuous_on_ceil (n : ℤ) : continuous_on (λ x, ceil x : α → α) (Ioc (n-1) n : set α) := (continuous_on_congr $ ceil_eq_on_Ioc' n).mpr continuous_on_const lemma tendsto_floor_right' [order_closed_topology α] (n : ℤ) : tendsto (λ x, floor x : α → α) (𝓝[Ici n] n) (𝓝 n) := begin rw ← nhds_within_Ico_eq_nhds_within_Ici (lt_add_one (n : α)), convert ← (continuous_on_floor _ _ (left_mem_Ico.mpr $ lt_add_one (_ : α))).tendsto, rw floor_eq_iff, exact ⟨le_refl _, lt_add_one _⟩ end lemma tendsto_ceil_left' [order_closed_topology α] (n : ℤ) : tendsto (λ x, ceil x : α → α) (𝓝[Iic n] n) (𝓝 n) := begin rw ← nhds_within_Ioc_eq_nhds_within_Iic (sub_one_lt (n : α)), convert ← (continuous_on_ceil _ _ (right_mem_Ioc.mpr $ sub_one_lt (_ : α))).tendsto, rw ceil_eq_iff, exact ⟨sub_one_lt _, le_refl _⟩ end lemma tendsto_floor_right [order_closed_topology α] (n : ℤ) : tendsto (λ x, floor x : α → α) (𝓝[Ici n] n) (𝓝[Ici n] n) := tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ (tendsto_floor_right' _) begin refine (eventually_nhds_with_of_forall $ λ x (hx : (n : α) ≤ x), _), change _ ≤ _, norm_cast, convert ← floor_mono hx, rw floor_eq_iff, exact ⟨le_refl _, lt_add_one _⟩ end lemma tendsto_ceil_left [order_closed_topology α] (n : ℤ) : tendsto (λ x, ceil x : α → α) (𝓝[Iic n] n) (𝓝[Iic n] n) := tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ (tendsto_ceil_left' _) begin refine (eventually_nhds_with_of_forall $ λ x (hx : x ≤ (n : α)), _), change _ ≤ _, norm_cast, convert ← ceil_mono hx, rw ceil_eq_iff, exact ⟨sub_one_lt _, le_refl _⟩ end lemma tendsto_floor_left [order_closed_topology α] (n : ℤ) : tendsto (λ x, floor x : α → α) (𝓝[Iio n] n) (𝓝[Iic (n-1)] (n-1)) := begin rw ← nhds_within_Ico_eq_nhds_within_Iio (sub_one_lt (n : α)), convert (tendsto_nhds_within_congr $ (λ x hx, (floor_eq_on_Ico' (n-1) x hx).symm)) (tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ tendsto_const_nhds (eventually_of_forall (λ _, mem_Iic.mpr $ le_refl _))); norm_cast <|> apply_instance, ring end lemma tendsto_ceil_right [order_closed_topology α] (n : ℤ) : tendsto (λ x, ceil x : α → α) (𝓝[Ioi n] n) (𝓝[Ici (n+1)] (n+1)) := begin rw ← nhds_within_Ioc_eq_nhds_within_Ioi (lt_add_one (n : α)), convert (tendsto_nhds_within_congr $ (λ x hx, (ceil_eq_on_Ioc' (n+1) x hx).symm)) (tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ tendsto_const_nhds (eventually_of_forall (λ _, mem_Ici.mpr $ le_refl _))); norm_cast <|> apply_instance, ring end lemma tendsto_floor_left' [order_closed_topology α] (n : ℤ) : tendsto (λ x, floor x : α → α) (𝓝[Iio n] n) (𝓝 (n-1)) := begin rw ← nhds_within_univ, exact tendsto_nhds_within_mono_right (subset_univ _) (tendsto_floor_left n), end lemma tendsto_ceil_right' [order_closed_topology α] (n : ℤ) : tendsto (λ x, ceil x : α → α) (𝓝[Ioi n] n) (𝓝 (n+1)) := begin rw ← nhds_within_univ, exact tendsto_nhds_within_mono_right (subset_univ _) (tendsto_ceil_right n), end lemma continuous_on_fract [topological_add_group α] (n : ℤ) : continuous_on (fract : α → α) (Ico n (n+1) : set α) := continuous_on_id.sub (continuous_on_floor n) lemma tendsto_fract_left' [order_closed_topology α] [topological_add_group α] (n : ℤ) : tendsto (fract : α → α) (𝓝[Iio n] n) (𝓝 1) := begin convert (tendsto_nhds_within_of_tendsto_nhds tendsto_id).sub (tendsto_floor_left' n); [{norm_cast, ring}, apply_instance, apply_instance] end lemma tendsto_fract_left [order_closed_topology α] [topological_add_group α] (n : ℤ) : tendsto (fract : α → α) (𝓝[Iio n] n) (𝓝[Iio 1] 1) := tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ (tendsto_fract_left' _) (eventually_of_forall fract_lt_one) lemma tendsto_fract_right' [order_closed_topology α] [topological_add_group α] (n : ℤ) : tendsto (fract : α → α) (𝓝[Ici n] n) (𝓝 0) := begin convert (tendsto_nhds_within_of_tendsto_nhds tendsto_id).sub (tendsto_floor_right' n); [exact (sub_self _).symm, apply_instance, apply_instance] end lemma tendsto_fract_right [order_closed_topology α] [topological_add_group α] (n : ℤ) : tendsto (fract : α → α) (𝓝[Ici n] n) (𝓝[Ici 0] 0) := tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ (tendsto_fract_right' _) (eventually_of_forall fract_nonneg) local notation `I` := (Icc 0 1 : set α) lemma continuous_on.comp_fract' {β γ : Type*} [order_topology α] [topological_add_group α] [topological_space β] [topological_space γ] {f : β → α → γ} (h : continuous_on (uncurry f) $ (univ : set β).prod I) (hf : ∀ s, f s 0 = f s 1) : continuous (λ st : β × α, f st.1 $ fract st.2) := begin change continuous ((uncurry f) ∘ (prod.map id (fract))), rw continuous_iff_continuous_at, rintro ⟨s, t⟩, by_cases ht : t = floor t, { rw ht, rw ← continuous_within_at_univ, have : (univ : set (β × α)) ⊆ (set.prod univ (Iio $ floor t)) ∪ (set.prod univ (Ici $ floor t)), { rintros p -, rw ← prod_union, exact ⟨true.intro, lt_or_le _ _⟩ }, refine continuous_within_at.mono _ this, refine continuous_within_at.union _ _, { simp only [continuous_within_at, fract_coe, nhds_within_prod_eq, nhds_within_univ, id.def, comp_app, prod.map_mk], have : (uncurry f) (s, 0) = (uncurry f) (s, (1 : α)), by simp [uncurry, hf], rw this, refine (h _ ⟨true.intro, by exact_mod_cast right_mem_Icc.mpr zero_le_one⟩).tendsto.comp _, rw [nhds_within_prod_eq, nhds_within_univ], rw nhds_within_Icc_eq_nhds_within_Iic (@zero_lt_one α _), exact tendsto_id.prod_map (tendsto_nhds_within_mono_right Iio_subset_Iic_self $ tendsto_fract_left _) }, { simp only [continuous_within_at, fract_coe, nhds_within_prod_eq, nhds_within_univ, id.def, comp_app, prod.map_mk], refine (h _ ⟨true.intro, by exact_mod_cast left_mem_Icc.mpr zero_le_one⟩).tendsto.comp _, rw [nhds_within_prod_eq, nhds_within_univ, nhds_within_Icc_eq_nhds_within_Ici (@zero_lt_one α _)], exact tendsto_id.prod_map (tendsto_fract_right _) } }, { have : t ∈ Ioo (floor t : α) ((floor t : α) + 1), from ⟨lt_of_le_of_ne (floor_le t) (ne.symm ht), lt_floor_add_one _⟩, refine (h ((prod.map _ fract) _) ⟨trivial, ⟨fract_nonneg _, (fract_lt_one _).le⟩⟩).tendsto.comp _, simp only [nhds_prod_eq, nhds_within_prod_eq, nhds_within_univ, id.def, prod.map_mk], exact continuous_at_id.tendsto.prod_map (tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ (((continuous_on_fract _ _ (Ioo_subset_Ico_self this)).mono Ioo_subset_Ico_self).continuous_at (Ioo_mem_nhds this.1 this.2)) (eventually_of_forall (λ x, ⟨fract_nonneg _, (fract_lt_one _).le⟩)) ) } end lemma continuous_on.comp_fract {β : Type*} [order_topology α] [topological_add_group α] [topological_space β] {f : α → β} (h : continuous_on f I) (hf : f 0 = f 1) : continuous (f ∘ fract) := begin let f' : unit → α → β := λ x y, f y, have : continuous_on (uncurry f') ((univ : set unit).prod I), { rintros ⟨s, t⟩ ⟨-, ht : t ∈ I⟩, simp only [continuous_within_at, uncurry, nhds_within_prod_eq, nhds_within_univ, f'], rw tendsto_prod_iff, intros W hW, specialize h t ht hW, rw mem_map_sets_iff at h, rcases h with ⟨V, hV, hVW⟩, rw image_subset_iff at hVW, use [univ, univ_mem_sets, V, hV], intros x y hx hy, exact hVW hy }, have key : continuous (λ s, ⟨unit.star, s⟩ : α → unit × α) := by continuity, exact (this.comp_fract' (λ s, hf)).comp key end
4e888e09f32ba9dcd16b7e72ff4531d9b8c80aaa
b70031c8e2c5337b91d7e70f1e0c5f528f7b0e77
/src/group_theory/perm/sign.lean
5c916e06e984a47f6c0bafd88a4d49a1c5ca218e
[ "Apache-2.0" ]
permissive
molodiuc/mathlib
cae2ba3ef1601c1f42ca0b625c79b061b63fef5b
98ebe5a6739fbe254f9ee9d401882d4388f91035
refs/heads/master
1,674,237,127,059
1,606,353,533,000
1,606,353,533,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
38,892
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import data.fintype.basic import data.finset.sort import algebra.group.conj import algebra.big_operators.basic universes u v open equiv function fintype finset open_locale big_operators variables {α : Type u} {β : Type v} namespace equiv.perm /-- If the permutation `f` fixes the subtype `{x // p x}`, then this returns the permutation on `{x // p x}` induced by `f`. -/ def subtype_perm (f : perm α) {p : α → Prop} (h : ∀ x, p x ↔ p (f x)) : perm {x // p x} := ⟨λ x, ⟨f x, (h _).1 x.2⟩, λ x, ⟨f⁻¹ x, (h (f⁻¹ x)).2 $ by simpa using x.2⟩, λ _, by simp only [perm.inv_apply_self, subtype.coe_eta, subtype.coe_mk], λ _, by simp only [perm.apply_inv_self, subtype.coe_eta, subtype.coe_mk]⟩ @[simp] lemma subtype_perm_one (p : α → Prop) (h : ∀ x, p x ↔ p ((1 : perm α) x)) : @subtype_perm α 1 p h = 1 := equiv.ext $ λ ⟨_, _⟩, rfl /-- The inclusion map of permutations on a subtype of `α` into permutations of `α`, fixing the other points. -/ def of_subtype {p : α → Prop} [decidable_pred p] : perm (subtype p) →* perm α := { to_fun := λ f, ⟨λ x, if h : p x then f ⟨x, h⟩ else x, λ x, if h : p x then f⁻¹ ⟨x, h⟩ else x, λ x, have h : ∀ h : p x, p (f ⟨x, h⟩), from λ h, (f ⟨x, h⟩).2, by { simp only [], split_ifs at *; simp only [perm.inv_apply_self, subtype.coe_eta, subtype.coe_mk, not_true, *] at * }, λ x, have h : ∀ h : p x, p (f⁻¹ ⟨x, h⟩), from λ h, (f⁻¹ ⟨x, h⟩).2, by { simp only [], split_ifs at *; simp only [perm.apply_inv_self, subtype.coe_eta, subtype.coe_mk, not_true, *] at *}⟩, map_one' := begin ext, dsimp, split_ifs; refl, end, map_mul' := λ f g, equiv.ext $ λ x, begin by_cases h : p x, { have h₁ : p (f (g ⟨x, h⟩)), from (f (g ⟨x, h⟩)).2, have h₂ : p (g ⟨x, h⟩), from (g ⟨x, h⟩).2, simp only [h, h₂, coe_fn_mk, perm.mul_apply, dif_pos, subtype.coe_eta] }, { simp only [h, coe_fn_mk, perm.mul_apply, dif_neg, not_false_iff] } end } lemma eq_inv_iff_eq {f : perm α} {x y : α} : x = f⁻¹ y ↔ f x = y := by conv {to_lhs, rw [← injective.eq_iff f.injective, apply_inv_self]} lemma inv_eq_iff_eq {f : perm α} {x y : α} : f⁻¹ x = y ↔ x = f y := by rw [eq_comm, eq_inv_iff_eq, eq_comm] /-- Two permutations `f` and `g` are `disjoint` if their supports are disjoint, i.e., every element is fixed either by `f`, or by `g`. -/ def disjoint (f g : perm α) := ∀ x, f x = x ∨ g x = x @[symm] lemma disjoint.symm {f g : perm α} : disjoint f g → disjoint g f := by simp only [disjoint, or.comm, imp_self] lemma disjoint_comm {f g : perm α} : disjoint f g ↔ disjoint g f := ⟨disjoint.symm, disjoint.symm⟩ lemma disjoint_mul_comm {f g : perm α} (h : disjoint f g) : f * g = g * f := equiv.ext $ λ x, (h x).elim (λ hf, (h (g x)).elim (λ hg, by simp [mul_apply, hf, hg]) (λ hg, by simp [mul_apply, hf, g.injective hg])) (λ hg, (h (f x)).elim (λ hf, by simp [mul_apply, f.injective hf, hg]) (λ hf, by simp [mul_apply, hf, hg])) @[simp] lemma disjoint_one_left (f : perm α) : disjoint 1 f := λ _, or.inl rfl @[simp] lemma disjoint_one_right (f : perm α) : disjoint f 1 := λ _, or.inr rfl lemma disjoint_mul_left {f g h : perm α} (H1 : disjoint f h) (H2 : disjoint g h) : disjoint (f * g) h := λ x, by cases H1 x; cases H2 x; simp * lemma disjoint_mul_right {f g h : perm α} (H1 : disjoint f g) (H2 : disjoint f h) : disjoint f (g * h) := by rw disjoint_comm; exact disjoint_mul_left H1.symm H2.symm lemma disjoint_prod_right {f : perm α} (l : list (perm α)) (h : ∀ g ∈ l, disjoint f g) : disjoint f l.prod := begin induction l with g l ih, { exact disjoint_one_right _ }, { rw list.prod_cons; exact disjoint_mul_right (h _ (list.mem_cons_self _ _)) (ih (λ g hg, h g (list.mem_cons_of_mem _ hg))) } end lemma disjoint_prod_perm {l₁ l₂ : list (perm α)} (hl : l₁.pairwise disjoint) (hp : l₁ ~ l₂) : l₁.prod = l₂.prod := hp.prod_eq' $ hl.imp $ λ f g, disjoint_mul_comm lemma of_subtype_subtype_perm {f : perm α} {p : α → Prop} [decidable_pred p] (h₁ : ∀ x, p x ↔ p (f x)) (h₂ : ∀ x, f x ≠ x → p x) : of_subtype (subtype_perm f h₁) = f := equiv.ext $ λ x, begin rw [of_subtype, subtype_perm], by_cases hx : p x, { simp only [hx, coe_fn_mk, dif_pos, monoid_hom.coe_mk, subtype.coe_mk]}, { haveI := classical.prop_decidable, simp only [hx, not_not.mp (mt (h₂ x) hx), coe_fn_mk, dif_neg, not_false_iff, monoid_hom.coe_mk] } end lemma of_subtype_apply_of_not_mem {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) {x : α} (hx : ¬ p x) : of_subtype f x = x := dif_neg hx lemma mem_iff_of_subtype_apply_mem {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) (x : α) : p x ↔ p ((of_subtype f : α → α) x) := if h : p x then by dsimp [of_subtype]; simpa [h] using (f ⟨x, h⟩).2 else by simp [h, of_subtype_apply_of_not_mem f h] @[simp] lemma subtype_perm_of_subtype {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) : subtype_perm (of_subtype f) (mem_iff_of_subtype_apply_mem f) = f := equiv.ext $ λ ⟨x, hx⟩, by dsimp [subtype_perm, of_subtype]; simp [show p x, from hx] lemma pow_apply_eq_self_of_apply_eq_self {f : perm α} {x : α} (hfx : f x = x) : ∀ n : ℕ, (f ^ n) x = x | 0 := rfl | (n+1) := by rw [pow_succ', mul_apply, hfx, pow_apply_eq_self_of_apply_eq_self] lemma gpow_apply_eq_self_of_apply_eq_self {f : perm α} {x : α} (hfx : f x = x) : ∀ n : ℤ, (f ^ n) x = x | (n : ℕ) := pow_apply_eq_self_of_apply_eq_self hfx n | -[1+ n] := by rw [gpow_neg_succ_of_nat, inv_eq_iff_eq, pow_apply_eq_self_of_apply_eq_self hfx] lemma pow_apply_eq_of_apply_apply_eq_self {f : perm α} {x : α} (hffx : f (f x) = x) : ∀ n : ℕ, (f ^ n) x = x ∨ (f ^ n) x = f x | 0 := or.inl rfl | (n+1) := (pow_apply_eq_of_apply_apply_eq_self n).elim (λ h, or.inr (by rw [pow_succ, mul_apply, h])) (λ h, or.inl (by rw [pow_succ, mul_apply, h, hffx])) lemma gpow_apply_eq_of_apply_apply_eq_self {f : perm α} {x : α} (hffx : f (f x) = x) : ∀ i : ℤ, (f ^ i) x = x ∨ (f ^ i) x = f x | (n : ℕ) := pow_apply_eq_of_apply_apply_eq_self hffx n | -[1+ n] := by rw [gpow_neg_succ_of_nat, inv_eq_iff_eq, ← injective.eq_iff f.injective, ← mul_apply, ← pow_succ, eq_comm, inv_eq_iff_eq, ← mul_apply, ← pow_succ', @eq_comm _ x, or.comm]; exact pow_apply_eq_of_apply_apply_eq_self hffx _ variable [decidable_eq α] /-- The `finset` of nonfixed points of a permutation. -/ def support [fintype α] (f : perm α) := univ.filter (λ x, f x ≠ x) @[simp] lemma mem_support [fintype α] {f : perm α} {x : α} : x ∈ f.support ↔ f x ≠ x := by simp only [support, true_and, mem_filter, mem_univ] /-- `f.is_swap` indicates that the permutation `f` is a transposition of two elements. -/ def is_swap (f : perm α) := ∃ x y, x ≠ y ∧ f = swap x y lemma swap_mul_eq_mul_swap (f : perm α) (x y : α) : swap x y * f = f * swap (f⁻¹ x) (f⁻¹ y) := equiv.ext $ λ z, begin simp only [perm.mul_apply, swap_apply_def], split_ifs; simp only [perm.apply_inv_self, *, eq_inv_iff_eq,eq_self_iff_true, not_true] at * end lemma mul_swap_eq_swap_mul (f : perm α) (x y : α) : f * swap x y = swap (f x) (f y) * f := by rw [swap_mul_eq_mul_swap, inv_apply_self, inv_apply_self] /-- Multiplying a permutation with `swap i j` twice gives the original permutation. This specialization of `swap_mul_self` is useful when using cosets of permutations. -/ @[simp] lemma swap_mul_self_mul (i j : α) (σ : perm α) : equiv.swap i j * (equiv.swap i j * σ) = σ := by rw [←mul_assoc (swap i j) (swap i j) σ, equiv.swap_mul_self, one_mul] lemma swap_mul_eq_iff {i j : α} {σ : perm α} : swap i j * σ = σ ↔ i = j := ⟨(assume h, have swap_id : swap i j = 1 := mul_right_cancel (trans h (one_mul σ).symm), by {rw [←swap_apply_right i j, swap_id], refl}), (assume h, by erw [h, swap_self, one_mul])⟩ lemma is_swap_of_subtype {p : α → Prop} [decidable_pred p] {f : perm (subtype p)} (h : is_swap f) : is_swap (of_subtype f) := let ⟨⟨x, hx⟩, ⟨y, hy⟩, hxy⟩ := h in ⟨x, y, by simp only [ne.def] at hxy; tauto, equiv.ext $ λ z, begin rw [hxy.2, of_subtype], simp only [swap_apply_def, coe_fn_mk, swap_inv, subtype.mk_eq_mk, monoid_hom.coe_mk], split_ifs; rw subtype.coe_mk <|> cc, end⟩ lemma ne_and_ne_of_swap_mul_apply_ne_self {f : perm α} {x y : α} (hy : (swap x (f x) * f) y ≠ y) : f y ≠ y ∧ y ≠ x := begin simp only [swap_apply_def, mul_apply, injective.eq_iff f.injective] at *, by_cases h : f y = x, { split; intro; simp only [*, if_true, eq_self_iff_true, not_true, ne.def] at *}, { split_ifs at hy; cc } end lemma support_swap_mul_eq [fintype α] {f : perm α} {x : α} (hffx : f (f x) ≠ x) : (swap x (f x) * f).support = f.support.erase x := have hfx : f x ≠ x, from λ hfx, by simpa [hfx] using hffx, finset.ext $ λ y, ⟨λ hy, have hy' : (swap x (f x) * f) y ≠ y, from mem_support.1 hy, mem_erase.2 ⟨λ hyx, by simp [hyx, mul_apply, *] at *, mem_support.2 $ λ hfy, by simp only [mul_apply, swap_apply_def, hfy] at hy'; split_ifs at hy'; simp only [*, eq_self_iff_true, not_true, ne.def, apply_eq_iff_eq] at *⟩, λ hy, by simp only [mem_erase, mem_support, swap_apply_def, mul_apply] at *; intro; split_ifs at *; simp only [*, eq_self_iff_true, not_true, ne.def] at *⟩ lemma card_support_swap_mul [fintype α] {f : perm α} {x : α} (hx : f x ≠ x) : (swap x (f x) * f).support.card < f.support.card := finset.card_lt_card ⟨λ z hz, mem_support.2 (ne_and_ne_of_swap_mul_apply_ne_self (mem_support.1 hz)).1, λ h, absurd (h (mem_support.2 hx)) (mt mem_support.1 (by simp))⟩ /-- Given a list `l : list α` and a permutation `f : perm α` such that the nonfixed points of `f` are in `l`, recursively factors `f` as a product of transpositions. -/ def swap_factors_aux : Π (l : list α) (f : perm α), (∀ {x}, f x ≠ x → x ∈ l) → {l : list (perm α) // l.prod = f ∧ ∀ g ∈ l, is_swap g} | [] := λ f h, ⟨[], equiv.ext $ λ x, by rw [list.prod_nil]; exact eq.symm (not_not.1 (mt h (list.not_mem_nil _))), by simp⟩ | (x :: l) := λ f h, if hfx : x = f x then swap_factors_aux l f (λ y hy, list.mem_of_ne_of_mem (λ h : y = x, by simpa [h, hfx.symm] using hy) (h hy)) else let m := swap_factors_aux l (swap x (f x) * f) (λ y hy, have f y ≠ y ∧ y ≠ x, from ne_and_ne_of_swap_mul_apply_ne_self hy, list.mem_of_ne_of_mem this.2 (h this.1)) in ⟨swap x (f x) :: m.1, by rw [list.prod_cons, m.2.1, ← mul_assoc, mul_def (swap x (f x)), swap_swap, ← one_def, one_mul], λ g hg, ((list.mem_cons_iff _ _ _).1 hg).elim (λ h, ⟨x, f x, hfx, h⟩) (m.2.2 _)⟩ /-- `swap_factors` represents a permutation as a product of a list of transpositions. The representation is non unique and depends on the linear order structure. For types without linear order `trunc_swap_factors` can be used -/ def swap_factors [fintype α] [linear_order α] (f : perm α) : {l : list (perm α) // l.prod = f ∧ ∀ g ∈ l, is_swap g} := swap_factors_aux ((@univ α _).sort (≤)) f (λ _ _, (mem_sort _).2 (mem_univ _)) /-- This computably represents the fact that any permutation can be represented as the product of a list of transpositions. -/ def trunc_swap_factors [fintype α] (f : perm α) : trunc {l : list (perm α) // l.prod = f ∧ ∀ g ∈ l, is_swap g} := quotient.rec_on_subsingleton (@univ α _).1 (λ l h, trunc.mk (swap_factors_aux l f h)) (show ∀ x, f x ≠ x → x ∈ (@univ α _).1, from λ _ _, mem_univ _) /-- An induction principle for permutations. If `P` holds for the identity permutation, and is preserved under composition with a non-trivial swap, then `P` holds for all permutations. -/ @[elab_as_eliminator] lemma swap_induction_on [fintype α] {P : perm α → Prop} (f : perm α) : P 1 → (∀ f x y, x ≠ y → P f → P (swap x y * f)) → P f := begin cases trunc.out (trunc_swap_factors f) with l hl, induction l with g l ih generalizing f, { simp only [hl.left.symm, list.prod_nil, forall_true_iff] {contextual := tt}}, { assume h1 hmul_swap, rcases hl.2 g (by simp) with ⟨x, y, hxy⟩, rw [← hl.1, list.prod_cons, hxy.2], exact hmul_swap _ _ _ hxy.1 (ih _ ⟨rfl, λ v hv, hl.2 _ (list.mem_cons_of_mem _ hv)⟩ h1 hmul_swap) } end /-- Like `swap_induction_on`, but with the composition on the right of `f`. An induction principle for permutations. If `P` holds for the identity permutation, and is preserved under composition with a non-trivial swap, then `P` holds for all permutations. -/ @[elab_as_eliminator] lemma swap_induction_on' [fintype α] {P : perm α → Prop} (f : perm α) : P 1 → (∀ f x y, x ≠ y → P f → P (f * swap x y)) → P f := λ h1 IH, inv_inv f ▸ swap_induction_on f⁻¹ h1 (λ f, IH f⁻¹) lemma swap_mul_swap_mul_swap {x y z : α} (hwz: x ≠ y) (hxz : x ≠ z) : swap y z * swap x y * swap y z = swap z x := equiv.ext $ λ n, by simp only [swap_apply_def, mul_apply]; split_ifs; cc lemma is_conj_swap {w x y z : α} (hwx : w ≠ x) (hyz : y ≠ z) : is_conj (swap w x) (swap y z) := have h : ∀ {y z : α}, y ≠ z → w ≠ z → (swap w y * swap x z) * swap w x * (swap w y * swap x z)⁻¹ = swap y z := λ y z hyz hwz, by rw [mul_inv_rev, swap_inv, swap_inv, mul_assoc (swap w y), mul_assoc (swap w y), ← mul_assoc _ (swap x z), swap_mul_swap_mul_swap hwx hwz, ← mul_assoc, swap_mul_swap_mul_swap hwz.symm hyz.symm], if hwz : w = z then have hwy : w ≠ y, by cc, ⟨swap w z * swap x y, by rw [swap_comm y z, h hyz.symm hwy]⟩ else ⟨swap w y * swap x z, h hyz hwz⟩ /-- set of all pairs (⟨a, b⟩ : Σ a : fin n, fin n) such that b < a -/ def fin_pairs_lt (n : ℕ) : finset (Σ a : fin n, fin n) := (univ : finset (fin n)).sigma (λ a, (range a).attach_fin (λ m hm, lt_trans (mem_range.1 hm) a.2)) lemma mem_fin_pairs_lt {n : ℕ} {a : Σ a : fin n, fin n} : a ∈ fin_pairs_lt n ↔ a.2 < a.1 := by simp only [fin_pairs_lt, fin.lt_iff_coe_lt_coe, true_and, mem_attach_fin, mem_range, mem_univ, mem_sigma] /-- `sign_aux σ` is the sign of a permutation on `fin n`, defined as the parity of the number of pairs `(x₁, x₂)` such that `x₂ < x₁` but `σ x₁ ≤ σ x₂` -/ def sign_aux {n : ℕ} (a : perm (fin n)) : units ℤ := ∏ x in fin_pairs_lt n, if a x.1 ≤ a x.2 then -1 else 1 @[simp] lemma sign_aux_one (n : ℕ) : sign_aux (1 : perm (fin n)) = 1 := begin unfold sign_aux, conv { to_rhs, rw ← @finset.prod_const_one _ (units ℤ) (fin_pairs_lt n) }, exact finset.prod_congr rfl (λ a ha, if_neg (not_le_of_gt (mem_fin_pairs_lt.1 ha))) end /-- `sign_bij_aux f ⟨a, b⟩` returns the pair consisting of `f a` and `f b` in decreasing order. -/ def sign_bij_aux {n : ℕ} (f : perm (fin n)) (a : Σ a : fin n, fin n) : Σ a : fin n, fin n := if hxa : f a.2 < f a.1 then ⟨f a.1, f a.2⟩ else ⟨f a.2, f a.1⟩ lemma sign_bij_aux_inj {n : ℕ} {f : perm (fin n)} : ∀ a b : Σ a : fin n, fin n, a ∈ fin_pairs_lt n → b ∈ fin_pairs_lt n → sign_bij_aux f a = sign_bij_aux f b → a = b := λ ⟨a₁, a₂⟩ ⟨b₁, b₂⟩ ha hb h, begin unfold sign_bij_aux at h, rw mem_fin_pairs_lt at *, have : ¬b₁ < b₂ := not_lt_of_ge (le_of_lt hb), split_ifs at h; simp only [*, (equiv.injective f).eq_iff, eq_self_iff_true, and_self, heq_iff_eq] at *, end lemma sign_bij_aux_surj {n : ℕ} {f : perm (fin n)} : ∀ a ∈ fin_pairs_lt n, ∃ b ∈ fin_pairs_lt n, a = sign_bij_aux f b := λ ⟨a₁, a₂⟩ ha, if hxa : f⁻¹ a₂ < f⁻¹ a₁ then ⟨⟨f⁻¹ a₁, f⁻¹ a₂⟩, mem_fin_pairs_lt.2 hxa, by dsimp [sign_bij_aux]; rw [apply_inv_self, apply_inv_self, dif_pos (mem_fin_pairs_lt.1 ha)]⟩ else ⟨⟨f⁻¹ a₂, f⁻¹ a₁⟩, mem_fin_pairs_lt.2 $ lt_of_le_of_ne (le_of_not_gt hxa) $ λ h, by simpa [mem_fin_pairs_lt, (f⁻¹).injective h, lt_irrefl] using ha, by dsimp [sign_bij_aux]; rw [apply_inv_self, apply_inv_self, dif_neg (not_lt_of_ge (le_of_lt (mem_fin_pairs_lt.1 ha)))]⟩ lemma sign_bij_aux_mem {n : ℕ} {f : perm (fin n)}: ∀ a : Σ a : fin n, fin n, a ∈ fin_pairs_lt n → sign_bij_aux f a ∈ fin_pairs_lt n := λ ⟨a₁, a₂⟩ ha, begin unfold sign_bij_aux, split_ifs with h, { exact mem_fin_pairs_lt.2 h }, { exact mem_fin_pairs_lt.2 (lt_of_le_of_ne (le_of_not_gt h) (λ h, ne_of_lt (mem_fin_pairs_lt.1 ha) (f.injective h.symm))) } end @[simp] lemma sign_aux_inv {n : ℕ} (f : perm (fin n)) : sign_aux f⁻¹ = sign_aux f := prod_bij (λ a ha, sign_bij_aux f⁻¹ a) sign_bij_aux_mem (λ ⟨a, b⟩ hab, if h : f⁻¹ b < f⁻¹ a then by rw [sign_bij_aux, dif_pos h, if_neg (not_le_of_gt h), apply_inv_self, apply_inv_self, if_neg (not_le_of_gt $ mem_fin_pairs_lt.1 hab)] else by rw [sign_bij_aux, if_pos (le_of_not_gt h), dif_neg h, apply_inv_self, apply_inv_self, if_pos (le_of_lt $ mem_fin_pairs_lt.1 hab)]) sign_bij_aux_inj sign_bij_aux_surj lemma sign_aux_mul {n : ℕ} (f g : perm (fin n)) : sign_aux (f * g) = sign_aux f * sign_aux g := begin rw ← sign_aux_inv g, unfold sign_aux, rw ← prod_mul_distrib, refine prod_bij (λ a ha, sign_bij_aux g a) sign_bij_aux_mem _ sign_bij_aux_inj sign_bij_aux_surj, rintros ⟨a, b⟩ hab, rw [sign_bij_aux, mul_apply, mul_apply], rw mem_fin_pairs_lt at hab, by_cases h : g b < g a, { rw dif_pos h, simp only [not_le_of_gt hab, mul_one, perm.inv_apply_self, if_false] }, { rw [dif_neg h, inv_apply_self, inv_apply_self, if_pos (le_of_lt hab)], by_cases h₁ : f (g b) ≤ f (g a), { have : f (g b) ≠ f (g a), { rw [ne.def, injective.eq_iff f.injective, injective.eq_iff g.injective]; exact ne_of_lt hab }, rw [if_pos h₁, if_neg (not_le_of_gt (lt_of_le_of_ne h₁ this))], refl }, { rw [if_neg h₁, if_pos (le_of_lt (lt_of_not_ge h₁))], refl } } end private lemma sign_aux_swap_zero_one {n : ℕ} (hn : 2 ≤ n) : sign_aux (swap (⟨0, lt_of_lt_of_le dec_trivial hn⟩ : fin n) ⟨1, lt_of_lt_of_le dec_trivial hn⟩) = -1 := let zero : fin n := ⟨0, lt_of_lt_of_le dec_trivial hn⟩ in let one : fin n := ⟨1, lt_of_lt_of_le dec_trivial hn⟩ in have hzo : zero < one := dec_trivial, show _ = ∏ x : Σ a : fin n, fin n in {(⟨one, zero⟩ : Σ a : fin n, fin n)}, if (equiv.swap zero one) x.1 ≤ swap zero one x.2 then (-1 : units ℤ) else 1, begin refine eq.symm (prod_subset (λ ⟨x₁, x₂⟩, by simp [mem_fin_pairs_lt, hzo] {contextual := tt}) (λ a ha₁ ha₂, _)), rcases a with ⟨⟨a₁, ha₁⟩, ⟨a₂, ha₂⟩⟩, replace ha₁ : a₂ < a₁ := mem_fin_pairs_lt.1 ha₁, simp only [swap_apply_def], have : ¬ 1 ≤ a₂ → a₂ = 0, from λ h, nat.le_zero_iff.1 (nat.le_of_lt_succ (lt_of_not_ge h)), have : a₁ ≤ 1 → a₁ = 0 ∨ a₁ = 1, from nat.cases_on a₁ (λ _, or.inl rfl) (λ a₁, nat.cases_on a₁ (λ _, or.inr rfl) (λ _ h, absurd h dec_trivial)), split_ifs; simp only [*, not_le.symm, iff.intro fin.veq_of_eq fin.eq_of_veq, nat.le_zero_iff, eq_self_iff_true, not_true, fin.le_def, one, nat.zero_le, and_self, heq_iff_eq, mem_singleton, forall_prop_of_true, or_self, le_refl] at *, end lemma sign_aux_swap : ∀ {n : ℕ} {x y : fin n} (hxy : x ≠ y), sign_aux (swap x y) = -1 | 0 := dec_trivial | 1 := dec_trivial | (n+2) := λ x y hxy, have h2n : 2 ≤ n + 2 := dec_trivial, by rw [← is_conj_iff_eq, ← sign_aux_swap_zero_one h2n]; exact (monoid_hom.mk' sign_aux sign_aux_mul).map_is_conj (is_conj_swap hxy dec_trivial) /-- When the list `l : list α` contains all nonfixed points of the permutation `f : perm α`, `sign_aux2 l f` recursively calculates the sign of `f`. -/ def sign_aux2 : list α → perm α → units ℤ | [] f := 1 | (x::l) f := if x = f x then sign_aux2 l f else -sign_aux2 l (swap x (f x) * f) lemma sign_aux_eq_sign_aux2 {n : ℕ} : ∀ (l : list α) (f : perm α) (e : α ≃ fin n) (h : ∀ x, f x ≠ x → x ∈ l), sign_aux ((e.symm.trans f).trans e) = sign_aux2 l f | [] f e h := have f = 1, from equiv.ext $ λ y, not_not.1 (mt (h y) (list.not_mem_nil _)), by rw [this, one_def, equiv.trans_refl, equiv.symm_trans, ← one_def, sign_aux_one, sign_aux2] | (x::l) f e h := begin rw sign_aux2, by_cases hfx : x = f x, { rw if_pos hfx, exact sign_aux_eq_sign_aux2 l f _ (λ y (hy : f y ≠ y), list.mem_of_ne_of_mem (λ h : y = x, by simpa [h, hfx.symm] using hy) (h y hy) ) }, { have hy : ∀ y : α, (swap x (f x) * f) y ≠ y → y ∈ l, from λ y hy, have f y ≠ y ∧ y ≠ x, from ne_and_ne_of_swap_mul_apply_ne_self hy, list.mem_of_ne_of_mem this.2 (h _ this.1), have : (e.symm.trans (swap x (f x) * f)).trans e = (swap (e x) (e (f x))) * (e.symm.trans f).trans e, by ext; simp [← equiv.symm_trans_swap_trans, mul_def], have hefx : e x ≠ e (f x), from mt (injective.eq_iff e.injective).1 hfx, rw [if_neg hfx, ← sign_aux_eq_sign_aux2 _ _ e hy, this, sign_aux_mul, sign_aux_swap hefx], simp only [units.neg_neg, one_mul, units.neg_mul]} end /-- When the multiset `s : multiset α` contains all nonfixed points of the permutation `f : perm α`, `sign_aux2 f _` recursively calculates the sign of `f`. -/ def sign_aux3 [fintype α] (f : perm α) {s : multiset α} : (∀ x, x ∈ s) → units ℤ := quotient.hrec_on s (λ l h, sign_aux2 l f) (trunc.induction_on (equiv_fin α) (λ e l₁ l₂ h, function.hfunext (show (∀ x, x ∈ l₁) = ∀ x, x ∈ l₂, by simp only [h.mem_iff]) (λ h₁ h₂ _, by rw [← sign_aux_eq_sign_aux2 _ _ e (λ _ _, h₁ _), ← sign_aux_eq_sign_aux2 _ _ e (λ _ _, h₂ _)]))) lemma sign_aux3_mul_and_swap [fintype α] (f g : perm α) (s : multiset α) (hs : ∀ x, x ∈ s) : sign_aux3 (f * g) hs = sign_aux3 f hs * sign_aux3 g hs ∧ ∀ x y, x ≠ y → sign_aux3 (swap x y) hs = -1 := let ⟨l, hl⟩ := quotient.exists_rep s in let ⟨e, _⟩ := trunc.exists_rep (equiv_fin α) in begin clear _let_match _let_match, subst hl, show sign_aux2 l (f * g) = sign_aux2 l f * sign_aux2 l g ∧ ∀ x y, x ≠ y → sign_aux2 l (swap x y) = -1, have hfg : (e.symm.trans (f * g)).trans e = (e.symm.trans f).trans e * (e.symm.trans g).trans e, from equiv.ext (λ h, by simp [mul_apply]), split, { rw [← sign_aux_eq_sign_aux2 _ _ e (λ _ _, hs _), ← sign_aux_eq_sign_aux2 _ _ e (λ _ _, hs _), ← sign_aux_eq_sign_aux2 _ _ e (λ _ _, hs _), hfg, sign_aux_mul] }, { assume x y hxy, have hexy : e x ≠ e y, from mt (injective.eq_iff e.injective).1 hxy, rw [← sign_aux_eq_sign_aux2 _ _ e (λ _ _, hs _), equiv.symm_trans_swap_trans, sign_aux_swap hexy] } end /-- `sign` of a permutation returns the signature or parity of a permutation, `1` for even permutations, `-1` for odd permutations. It is the unique surjective group homomorphism from `perm α` to the group with two elements.-/ def sign [fintype α] : perm α →* units ℤ := monoid_hom.mk' (λ f, sign_aux3 f mem_univ) (λ f g, (sign_aux3_mul_and_swap f g _ mem_univ).1) section sign variable [fintype α] @[simp] lemma sign_mul (f g : perm α) : sign (f * g) = sign f * sign g := monoid_hom.map_mul sign f g @[simp] lemma sign_one : (sign (1 : perm α)) = 1 := monoid_hom.map_one sign @[simp] lemma sign_refl : sign (equiv.refl α) = 1 := monoid_hom.map_one sign @[simp] lemma sign_inv (f : perm α) : sign f⁻¹ = sign f := by rw [monoid_hom.map_inv sign f, int.units_inv_eq_self] lemma sign_swap {x y : α} (h : x ≠ y) : sign (swap x y) = -1 := (sign_aux3_mul_and_swap 1 1 _ mem_univ).2 x y h @[simp] lemma sign_swap' {x y : α} : (swap x y).sign = if x = y then 1 else -1 := if H : x = y then by simp [H, swap_self] else by simp [sign_swap H, H] lemma sign_eq_of_is_swap {f : perm α} (h : is_swap f) : sign f = -1 := let ⟨x, y, hxy⟩ := h in hxy.2.symm ▸ sign_swap hxy.1 lemma sign_aux3_symm_trans_trans [decidable_eq β] [fintype β] (f : perm α) (e : α ≃ β) {s : multiset α} {t : multiset β} (hs : ∀ x, x ∈ s) (ht : ∀ x, x ∈ t) : sign_aux3 ((e.symm.trans f).trans e) ht = sign_aux3 f hs := quotient.induction_on₂ t s (λ l₁ l₂ h₁ h₂, show sign_aux2 _ _ = sign_aux2 _ _, from let n := trunc.out (equiv_fin β) in by rw [← sign_aux_eq_sign_aux2 _ _ n (λ _ _, h₁ _), ← sign_aux_eq_sign_aux2 _ _ (e.trans n) (λ _ _, h₂ _)]; exact congr_arg sign_aux (equiv.ext (λ x, by simp only [equiv.coe_trans, apply_eq_iff_eq, symm_trans_apply]))) ht hs lemma sign_symm_trans_trans [decidable_eq β] [fintype β] (f : perm α) (e : α ≃ β) : sign ((e.symm.trans f).trans e) = sign f := sign_aux3_symm_trans_trans f e mem_univ mem_univ lemma sign_prod_list_swap {l : list (perm α)} (hl : ∀ g ∈ l, is_swap g) : sign l.prod = (-1) ^ l.length := have h₁ : l.map sign = list.repeat (-1) l.length := list.eq_repeat.2 ⟨by simp, λ u hu, let ⟨g, hg⟩ := list.mem_map.1 hu in hg.2 ▸ sign_eq_of_is_swap (hl _ hg.1)⟩, by rw [← list.prod_repeat, ← h₁, list.prod_hom _ (@sign α _ _)] lemma sign_surjective (hα : 1 < fintype.card α) : function.surjective (sign : perm α → units ℤ) := λ a, (int.units_eq_one_or a).elim (λ h, ⟨1, by simp [h]⟩) (λ h, let ⟨x⟩ := fintype.card_pos_iff.1 (lt_trans zero_lt_one hα) in let ⟨y, hxy⟩ := fintype.exists_ne_of_one_lt_card hα x in ⟨swap y x, by rw [sign_swap hxy, h]⟩ ) lemma eq_sign_of_surjective_hom {s : perm α →* units ℤ} (hs : surjective s) : s = sign := have ∀ {f}, is_swap f → s f = -1 := λ f ⟨x, y, hxy, hxy'⟩, hxy'.symm ▸ by_contradiction (λ h, have ∀ f, is_swap f → s f = 1 := λ f ⟨a, b, hab, hab'⟩, by rw [← is_conj_iff_eq, ← or.resolve_right (int.units_eq_one_or _) h, hab']; exact (monoid_hom.of s).map_is_conj (is_conj_swap hab hxy), let ⟨g, hg⟩ := hs (-1) in let ⟨l, hl⟩ := trunc.out (trunc_swap_factors g) in have ∀ a ∈ l.map s, a = (1 : units ℤ) := λ a ha, let ⟨g, hg⟩ := list.mem_map.1 ha in hg.2 ▸ this _ (hl.2 _ hg.1), have s l.prod = 1, by rw [← l.prod_hom s, list.eq_repeat'.2 this, list.prod_repeat, one_pow], by rw [hl.1, hg] at this; exact absurd this dec_trivial), monoid_hom.ext $ λ f, let ⟨l, hl₁, hl₂⟩ := trunc.out (trunc_swap_factors f) in have hsl : ∀ a ∈ l.map s, a = (-1 : units ℤ) := λ a ha, let ⟨g, hg⟩ := list.mem_map.1 ha in hg.2 ▸ this (hl₂ _ hg.1), by rw [← hl₁, ← l.prod_hom s, list.eq_repeat'.2 hsl, list.length_map, list.prod_repeat, sign_prod_list_swap hl₂] lemma sign_subtype_perm (f : perm α) {p : α → Prop} [decidable_pred p] (h₁ : ∀ x, p x ↔ p (f x)) (h₂ : ∀ x, f x ≠ x → p x) : sign (subtype_perm f h₁) = sign f := let l := trunc.out (trunc_swap_factors (subtype_perm f h₁)) in have hl' : ∀ g' ∈ l.1.map of_subtype, is_swap g' := λ g' hg', let ⟨g, hg⟩ := list.mem_map.1 hg' in hg.2 ▸ is_swap_of_subtype (l.2.2 _ hg.1), have hl'₂ : (l.1.map of_subtype).prod = f, by rw [l.1.prod_hom of_subtype, l.2.1, of_subtype_subtype_perm _ h₂], by conv {congr, rw ← l.2.1, skip, rw ← hl'₂}; rw [sign_prod_list_swap l.2.2, sign_prod_list_swap hl', list.length_map] @[simp] lemma sign_of_subtype {p : α → Prop} [decidable_pred p] (f : perm (subtype p)) : sign (of_subtype f) = sign f := have ∀ x, of_subtype f x ≠ x → p x, from λ x, not_imp_comm.1 (of_subtype_apply_of_not_mem f), by conv {to_rhs, rw [← subtype_perm_of_subtype f, sign_subtype_perm _ _ this]} lemma sign_eq_sign_of_equiv [decidable_eq β] [fintype β] (f : perm α) (g : perm β) (e : α ≃ β) (h : ∀ x, e (f x) = g (e x)) : sign f = sign g := have hg : g = (e.symm.trans f).trans e, from equiv.ext $ by simp [h], by rw [hg, sign_symm_trans_trans] lemma sign_bij [decidable_eq β] [fintype β] {f : perm α} {g : perm β} (i : Π x : α, f x ≠ x → β) (h : ∀ x hx hx', i (f x) hx' = g (i x hx)) (hi : ∀ x₁ x₂ hx₁ hx₂, i x₁ hx₁ = i x₂ hx₂ → x₁ = x₂) (hg : ∀ y, g y ≠ y → ∃ x hx, i x hx = y) : sign f = sign g := calc sign f = sign (@subtype_perm _ f (λ x, f x ≠ x) (by simp)) : eq.symm (sign_subtype_perm _ _ (λ _, id)) ... = sign (@subtype_perm _ g (λ x, g x ≠ x) (by simp)) : sign_eq_sign_of_equiv _ _ (equiv.of_bijective (λ x : {x // f x ≠ x}, (⟨i x.1 x.2, have f (f x) ≠ f x, from mt (λ h, f.injective h) x.2, by rw [← h _ x.2 this]; exact mt (hi _ _ this x.2) x.2⟩ : {y // g y ≠ y})) ⟨λ ⟨x, hx⟩ ⟨y, hy⟩ h, subtype.eq (hi _ _ _ _ (subtype.mk.inj h)), λ ⟨y, hy⟩, let ⟨x, hfx, hx⟩ := hg y hy in ⟨⟨x, hfx⟩, subtype.eq hx⟩⟩) (λ ⟨x, _⟩, subtype.eq (h x _ _)) ... = sign g : sign_subtype_perm _ _ (λ _, id) /-- A permutation is a cycle when any two nonfixed points of the permutation are related by repeated application of the permutation. -/ def is_cycle (f : perm β) := ∃ x, f x ≠ x ∧ ∀ y, f y ≠ y → ∃ i : ℤ, (f ^ i) x = y lemma is_cycle_swap {α : Type*} [decidable_eq α] {x y : α} (hxy : x ≠ y) : is_cycle (swap x y) := ⟨y, by rwa swap_apply_right, λ a (ha : ite (a = x) y (ite (a = y) x a) ≠ a), if hya : y = a then ⟨0, hya⟩ else ⟨1, by rw [gpow_one, swap_apply_def]; split_ifs at *; cc⟩⟩ lemma is_cycle_inv {f : perm β} (hf : is_cycle f) : is_cycle (f⁻¹) := let ⟨x, hx⟩ := hf in ⟨x, by simp only [inv_eq_iff_eq, *, forall_prop_of_true, ne.def] at *; cc, λ y hy, let ⟨i, hi⟩ := hx.2 y (by simp only [inv_eq_iff_eq, *, forall_prop_of_true, ne.def] at *; cc) in ⟨-i, by rwa [gpow_neg, inv_gpow, inv_inv]⟩⟩ lemma exists_gpow_eq_of_is_cycle {f : perm β} (hf : is_cycle f) {x y : β} (hx : f x ≠ x) (hy : f y ≠ y) : ∃ i : ℤ, (f ^ i) x = y := let ⟨g, hg⟩ := hf in let ⟨a, ha⟩ := hg.2 x hx in let ⟨b, hb⟩ := hg.2 y hy in ⟨b - a, by rw [← ha, ← mul_apply, ← gpow_add, sub_add_cancel, hb]⟩ lemma is_cycle_swap_mul_aux₁ {α : Type*} [decidable_eq α] : ∀ (n : ℕ) {b x : α} {f : perm α} (hb : (swap x (f x) * f) b ≠ b) (h : (f ^ n) (f x) = b), ∃ i : ℤ, ((swap x (f x) * f) ^ i) (f x) = b | 0 := λ b x f hb h, ⟨0, h⟩ | (n+1 : ℕ) := λ b x f hb h, if hfbx : f x = b then ⟨0, hfbx⟩ else have f b ≠ b ∧ b ≠ x, from ne_and_ne_of_swap_mul_apply_ne_self hb, have hb' : (swap x (f x) * f) (f⁻¹ b) ≠ f⁻¹ b, by rw [mul_apply, apply_inv_self, swap_apply_of_ne_of_ne this.2 (ne.symm hfbx), ne.def, ← injective.eq_iff f.injective, apply_inv_self]; exact this.1, let ⟨i, hi⟩ := is_cycle_swap_mul_aux₁ n hb' (f.injective $ by rw [apply_inv_self]; rwa [pow_succ, mul_apply] at h) in ⟨i + 1, by rw [add_comm, gpow_add, mul_apply, hi, gpow_one, mul_apply, apply_inv_self, swap_apply_of_ne_of_ne (ne_and_ne_of_swap_mul_apply_ne_self hb).2 (ne.symm hfbx)]⟩ lemma is_cycle_swap_mul_aux₂ {α : Type*} [decidable_eq α] : ∀ (n : ℤ) {b x : α} {f : perm α} (hb : (swap x (f x) * f) b ≠ b) (h : (f ^ n) (f x) = b), ∃ i : ℤ, ((swap x (f x) * f) ^ i) (f x) = b | (n : ℕ) := λ b x f, is_cycle_swap_mul_aux₁ n | -[1+ n] := λ b x f hb h, if hfbx : f⁻¹ x = b then ⟨-1, by rwa [gpow_neg, gpow_one, mul_inv_rev, mul_apply, swap_inv, swap_apply_right]⟩ else if hfbx' : f x = b then ⟨0, hfbx'⟩ else have f b ≠ b ∧ b ≠ x := ne_and_ne_of_swap_mul_apply_ne_self hb, have hb : (swap x (f⁻¹ x) * f⁻¹) (f⁻¹ b) ≠ f⁻¹ b, by rw [mul_apply, swap_apply_def]; split_ifs; simp only [inv_eq_iff_eq, perm.mul_apply, gpow_neg_succ_of_nat, ne.def, perm.apply_inv_self] at *; cc, let ⟨i, hi⟩ := is_cycle_swap_mul_aux₁ n hb (show (f⁻¹ ^ n) (f⁻¹ x) = f⁻¹ b, by rw [← gpow_coe_nat, ← h, ← mul_apply, ← mul_apply, ← mul_apply, gpow_neg_succ_of_nat, ← inv_pow, pow_succ', mul_assoc, mul_assoc, inv_mul_self, mul_one, gpow_coe_nat, ← pow_succ', ← pow_succ]) in have h : (swap x (f⁻¹ x) * f⁻¹) (f x) = f⁻¹ x, by rw [mul_apply, inv_apply_self, swap_apply_left], ⟨-i, by rw [← add_sub_cancel i 1, neg_sub, sub_eq_add_neg, gpow_add, gpow_one, gpow_neg, ← inv_gpow, mul_inv_rev, swap_inv, mul_swap_eq_swap_mul, inv_apply_self, swap_comm _ x, gpow_add, gpow_one, mul_apply, mul_apply (_ ^ i), h, hi, mul_apply, apply_inv_self, swap_apply_of_ne_of_ne this.2 (ne.symm hfbx')]⟩ lemma eq_swap_of_is_cycle_of_apply_apply_eq_self {α : Type*} [decidable_eq α] {f : perm α} (hf : is_cycle f) {x : α} (hfx : f x ≠ x) (hffx : f (f x) = x) : f = swap x (f x) := equiv.ext $ λ y, let ⟨z, hz⟩ := hf in let ⟨i, hi⟩ := hz.2 x hfx in if hyx : y = x then by simp [hyx] else if hfyx : y = f x then by simp [hfyx, hffx] else begin rw [swap_apply_of_ne_of_ne hyx hfyx], refine by_contradiction (λ hy, _), cases hz.2 y hy with j hj, rw [← sub_add_cancel j i, gpow_add, mul_apply, hi] at hj, cases gpow_apply_eq_of_apply_apply_eq_self hffx (j - i) with hji hji, { rw [← hj, hji] at hyx, cc }, { rw [← hj, hji] at hfyx, cc } end lemma is_cycle_swap_mul {α : Type*} [decidable_eq α] {f : perm α} (hf : is_cycle f) {x : α} (hx : f x ≠ x) (hffx : f (f x) ≠ x) : is_cycle (swap x (f x) * f) := ⟨f x, by simp only [swap_apply_def, mul_apply]; split_ifs; simp [injective.eq_iff f.injective] at *; cc, λ y hy, let ⟨i, hi⟩ := exists_gpow_eq_of_is_cycle hf hx (ne_and_ne_of_swap_mul_apply_ne_self hy).1 in have hi : (f ^ (i - 1)) (f x) = y, from calc (f ^ (i - 1)) (f x) = (f ^ (i - 1) * f ^ (1 : ℤ)) x : by rw [gpow_one, mul_apply] ... = y : by rwa [← gpow_add, sub_add_cancel], is_cycle_swap_mul_aux₂ (i - 1) hy hi⟩ @[simp] lemma support_swap {x y : α} (hxy : x ≠ y) : (swap x y).support = {x, y} := finset.ext $ λ a, by simp [swap_apply_def]; split_ifs; cc lemma card_support_swap {x y : α} (hxy : x ≠ y) : (swap x y).support.card = 2 := show (swap x y).support.card = finset.card ⟨x ::ₘ y ::ₘ 0, by simp [hxy]⟩, from congr_arg card $ by rw [support_swap hxy]; simp [*, finset.ext_iff]; cc lemma sign_cycle : ∀ {f : perm α} (hf : is_cycle f), sign f = -(-1) ^ f.support.card | f := λ hf, let ⟨x, hx⟩ := hf in calc sign f = sign (swap x (f x) * (swap x (f x) * f)) : by rw [← mul_assoc, mul_def, mul_def, swap_swap, trans_refl] ... = -(-1) ^ f.support.card : if h1 : f (f x) = x then have h : swap x (f x) * f = 1, begin rw eq_swap_of_is_cycle_of_apply_apply_eq_self hf hx.1 h1, simp only [perm.mul_def, perm.one_def, swap_apply_left, swap_swap] end, by rw [sign_mul, sign_swap hx.1.symm, h, sign_one, eq_swap_of_is_cycle_of_apply_apply_eq_self hf hx.1 h1, card_support_swap hx.1.symm]; refl else have h : card (support (swap x (f x) * f)) + 1 = card (support f), by rw [← insert_erase (mem_support.2 hx.1), support_swap_mul_eq h1, card_insert_of_not_mem (not_mem_erase _ _)], have wf : card (support (swap x (f x) * f)) < card (support f), from card_support_swap_mul hx.1, by rw [sign_mul, sign_swap hx.1.symm, sign_cycle (is_cycle_swap_mul hf hx.1 h1), ← h]; simp only [pow_add, mul_one, units.neg_neg, one_mul, units.mul_neg, eq_self_iff_true, pow_one, units.neg_mul_neg] using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ f, f.support.card)⟩]} /-- If we apply `prod_extend_right a (σ a)` for all `a : α` in turn, we get `prod_congr_right σ`. -/ lemma prod_prod_extend_right {α : Type*} [decidable_eq α] (σ : α → perm β) {l : list α} (hl : l.nodup) (mem_l : ∀ a, a ∈ l) : (l.map (λ a, prod_extend_right a (σ a))).prod = prod_congr_right σ := begin ext ⟨a, b⟩ : 1, -- We'll use induction on the list of elements, -- but we have to keep track of whether we already passed `a` in the list. suffices : (a ∈ l ∧ (l.map (λ a, prod_extend_right a (σ a))).prod (a, b) = (a, σ a b)) ∨ (a ∉ l ∧ (l.map (λ a, prod_extend_right a (σ a))).prod (a, b) = (a, b)), { obtain ⟨_, prod_eq⟩ := or.resolve_right this (not_and.mpr (λ h _, h (mem_l a))), rw [prod_eq, prod_congr_right_apply] }, clear mem_l, induction l with a' l ih, { refine or.inr ⟨list.not_mem_nil _, _⟩, rw [list.map_nil, list.prod_nil, one_apply] }, rw [list.map_cons, list.prod_cons, mul_apply], rcases ih (list.nodup_cons.mp hl).2 with ⟨mem_l, prod_eq⟩ | ⟨not_mem_l, prod_eq⟩; rw prod_eq, { refine or.inl ⟨list.mem_cons_of_mem _ mem_l, _⟩, rw prod_extend_right_apply_ne _ (λ (h : a = a'), (list.nodup_cons.mp hl).1 (h ▸ mem_l)) }, by_cases ha' : a = a', { rw ← ha' at *, refine or.inl ⟨l.mem_cons_self a, _⟩, rw prod_extend_right_apply_eq }, { refine or.inr ⟨λ h, not_or ha' not_mem_l ((list.mem_cons_iff _ _ _).mp h), _⟩, rw prod_extend_right_apply_ne _ ha' }, end section open_locale classical lemma sign_prod_extend_right [fintype β] (a : α) (σ : perm β) : (prod_extend_right a σ).sign = σ.sign := sign_bij (λ (ab : α × β) _, ab.snd) (λ ⟨a', b⟩ hab hab', by simp [eq_of_prod_extend_right_ne hab]) (λ ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ hab₁ hab₂ h, by simpa [eq_of_prod_extend_right_ne hab₁, eq_of_prod_extend_right_ne hab₂] using h) (λ y hy, ⟨(a, y), by simpa, by simp⟩) lemma sign_prod_congr_right [fintype β] (σ : α → perm β) : sign (prod_congr_right σ) = ∏ k, (σ k).sign := begin obtain ⟨l, hl, mem_l⟩ := fintype.exists_univ_list α, have l_to_finset : l.to_finset = finset.univ, { apply eq_top_iff.mpr, intros b _, exact list.mem_to_finset.mpr (mem_l b) }, rw [← prod_prod_extend_right σ hl mem_l, sign.map_list_prod, list.map_map, ← l_to_finset, list.prod_to_finset _ hl], simp_rw ← λ a, sign_prod_extend_right a (σ a) end lemma sign_prod_congr_left [fintype β] (σ : α → perm β) : sign (prod_congr_left σ) = ∏ k, (σ k).sign := begin refine (sign_eq_sign_of_equiv _ _ (prod_comm β α) _).trans (sign_prod_congr_right σ), rintro ⟨b, α⟩, refl end @[simp] lemma sign_perm_congr {m n : Type*} [fintype m] [fintype n] (e : m ≃ n) (p : equiv.perm m) : (e.perm_congr p).sign = p.sign := equiv.perm.sign_eq_sign_of_equiv _ _ e.symm (by simp) end end sign end equiv.perm
823858fe41fff2aaf8473092bd0ef3f0c9028ca1
4727251e0cd73359b15b664c3170e5d754078599
/src/data/set/intervals/basic.lean
2db4ebb1c677c53370008e0f1faed894f9e24a89
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
57,798
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, Patrick Massot, Yury Kudryashov, Rémy Degenne -/ import algebra.order.group import order.rel_iso /-! # Intervals In any preorder `α`, we define intervals (which on each side can be either infinite, open, or closed) using the following naming conventions: - `i`: infinite - `o`: open - `c`: closed Each interval has the name `I` + letter for left side + letter for right side. For instance, `Ioc a b` denotes the inverval `(a, b]`. This file contains these definitions, and basic facts on inclusion, intersection, difference of intervals (where the precise statements may depend on the properties of the order, in particular for some statements it should be `linear_order` or `densely_ordered`). TODO: This is just the beginning; a lot of rules are missing -/ variables {α β : Type*} namespace set open set open order_dual (to_dual of_dual) section preorder variables [preorder α] {a a₁ a₂ b b₁ b₂ c x : α} /-- Left-open right-open interval -/ def Ioo (a b : α) := {x | a < x ∧ x < b} /-- Left-closed right-open interval -/ def Ico (a b : α) := {x | a ≤ x ∧ x < b} /-- Left-infinite right-open interval -/ def Iio (a : α) := {x | x < a} /-- Left-closed right-closed interval -/ def Icc (a b : α) := {x | a ≤ x ∧ x ≤ b} /-- Left-infinite right-closed interval -/ def Iic (b : α) := {x | x ≤ b} /-- Left-open right-closed interval -/ def Ioc (a b : α) := {x | a < x ∧ x ≤ b} /-- Left-closed right-infinite interval -/ def Ici (a : α) := {x | a ≤ x} /-- Left-open right-infinite interval -/ def Ioi (a : α) := {x | a < x} lemma Ioo_def (a b : α) : {x | a < x ∧ x < b} = Ioo a b := rfl lemma Ico_def (a b : α) : {x | a ≤ x ∧ x < b} = Ico a b := rfl lemma Iio_def (a : α) : {x | x < a} = Iio a := rfl lemma Icc_def (a b : α) : {x | a ≤ x ∧ x ≤ b} = Icc a b := rfl lemma Iic_def (b : α) : {x | x ≤ b} = Iic b := rfl lemma Ioc_def (a b : α) : {x | a < x ∧ x ≤ b} = Ioc a b := rfl lemma Ici_def (a : α) : {x | a ≤ x} = Ici a := rfl lemma Ioi_def (a : α) : {x | a < x} = Ioi a := rfl @[simp] lemma mem_Ioo : x ∈ Ioo a b ↔ a < x ∧ x < b := iff.rfl @[simp] lemma mem_Ico : x ∈ Ico a b ↔ a ≤ x ∧ x < b := iff.rfl @[simp] lemma mem_Iio : x ∈ Iio b ↔ x < b := iff.rfl @[simp] lemma mem_Icc : x ∈ Icc a b ↔ a ≤ x ∧ x ≤ b := iff.rfl @[simp] lemma mem_Iic : x ∈ Iic b ↔ x ≤ b := iff.rfl @[simp] lemma mem_Ioc : x ∈ Ioc a b ↔ a < x ∧ x ≤ b := iff.rfl @[simp] lemma mem_Ici : x ∈ Ici a ↔ a ≤ x := iff.rfl @[simp] lemma mem_Ioi : x ∈ Ioi a ↔ a < x := iff.rfl @[simp] lemma left_mem_Ioo : a ∈ Ioo a b ↔ false := by simp [lt_irrefl] @[simp] lemma left_mem_Ico : a ∈ Ico a b ↔ a < b := by simp [le_refl] @[simp] lemma left_mem_Icc : a ∈ Icc a b ↔ a ≤ b := by simp [le_refl] @[simp] lemma left_mem_Ioc : a ∈ Ioc a b ↔ false := by simp [lt_irrefl] lemma left_mem_Ici : a ∈ Ici a := by simp @[simp] lemma right_mem_Ioo : b ∈ Ioo a b ↔ false := by simp [lt_irrefl] @[simp] lemma right_mem_Ico : b ∈ Ico a b ↔ false := by simp [lt_irrefl] @[simp] lemma right_mem_Icc : b ∈ Icc a b ↔ a ≤ b := by simp [le_refl] @[simp] lemma right_mem_Ioc : b ∈ Ioc a b ↔ a < b := by simp [le_refl] lemma right_mem_Iic : a ∈ Iic a := by simp @[simp] lemma dual_Ici : Ici (to_dual a) = of_dual ⁻¹' Iic a := rfl @[simp] lemma dual_Iic : Iic (to_dual a) = of_dual ⁻¹' Ici a := rfl @[simp] lemma dual_Ioi : Ioi (to_dual a) = of_dual ⁻¹' Iio a := rfl @[simp] lemma dual_Iio : Iio (to_dual a) = of_dual ⁻¹' Ioi a := rfl @[simp] lemma dual_Icc : Icc (to_dual a) (to_dual b) = of_dual ⁻¹' Icc b a := set.ext $ λ x, and_comm _ _ @[simp] lemma dual_Ioc : Ioc (to_dual a) (to_dual b) = of_dual ⁻¹' Ico b a := set.ext $ λ x, and_comm _ _ @[simp] lemma dual_Ico : Ico (to_dual a) (to_dual b) = of_dual ⁻¹' Ioc b a := set.ext $ λ x, and_comm _ _ @[simp] lemma dual_Ioo : Ioo (to_dual a) (to_dual b) = of_dual ⁻¹' Ioo b a := set.ext $ λ x, and_comm _ _ @[simp] lemma nonempty_Icc : (Icc a b).nonempty ↔ a ≤ b := ⟨λ ⟨x, hx⟩, hx.1.trans hx.2, λ h, ⟨a, left_mem_Icc.2 h⟩⟩ @[simp] lemma nonempty_Ico : (Ico a b).nonempty ↔ a < b := ⟨λ ⟨x, hx⟩, hx.1.trans_lt hx.2, λ h, ⟨a, left_mem_Ico.2 h⟩⟩ @[simp] lemma nonempty_Ioc : (Ioc a b).nonempty ↔ a < b := ⟨λ ⟨x, hx⟩, hx.1.trans_le hx.2, λ h, ⟨b, right_mem_Ioc.2 h⟩⟩ @[simp] lemma nonempty_Ici : (Ici a).nonempty := ⟨a, left_mem_Ici⟩ @[simp] lemma nonempty_Iic : (Iic a).nonempty := ⟨a, right_mem_Iic⟩ @[simp] lemma nonempty_Ioo [densely_ordered α] : (Ioo a b).nonempty ↔ a < b := ⟨λ ⟨x, ha, hb⟩, ha.trans hb, exists_between⟩ @[simp] lemma nonempty_Ioi [no_max_order α] : (Ioi a).nonempty := exists_gt a @[simp] lemma nonempty_Iio [no_min_order α] : (Iio a).nonempty := exists_lt a lemma nonempty_Icc_subtype (h : a ≤ b) : nonempty (Icc a b) := nonempty.to_subtype (nonempty_Icc.mpr h) lemma nonempty_Ico_subtype (h : a < b) : nonempty (Ico a b) := nonempty.to_subtype (nonempty_Ico.mpr h) lemma nonempty_Ioc_subtype (h : a < b) : nonempty (Ioc a b) := nonempty.to_subtype (nonempty_Ioc.mpr h) /-- An interval `Ici a` is nonempty. -/ instance nonempty_Ici_subtype : nonempty (Ici a) := nonempty.to_subtype nonempty_Ici /-- An interval `Iic a` is nonempty. -/ instance nonempty_Iic_subtype : nonempty (Iic a) := nonempty.to_subtype nonempty_Iic lemma nonempty_Ioo_subtype [densely_ordered α] (h : a < b) : nonempty (Ioo a b) := nonempty.to_subtype (nonempty_Ioo.mpr h) /-- In an order without maximal elements, the intervals `Ioi` are nonempty. -/ instance nonempty_Ioi_subtype [no_max_order α] : nonempty (Ioi a) := nonempty.to_subtype nonempty_Ioi /-- In an order without minimal elements, the intervals `Iio` are nonempty. -/ instance nonempty_Iio_subtype [no_min_order α] : nonempty (Iio a) := nonempty.to_subtype nonempty_Iio @[simp] lemma Icc_eq_empty (h : ¬a ≤ b) : Icc a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x ⟨ha, hb⟩, h (ha.trans hb) @[simp] lemma Ico_eq_empty (h : ¬a < b) : Ico a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x ⟨ha, hb⟩, h (ha.trans_lt hb) @[simp] lemma Ioc_eq_empty (h : ¬a < b) : Ioc a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x ⟨ha, hb⟩, h (ha.trans_le hb) @[simp] lemma Ioo_eq_empty (h : ¬a < b) : Ioo a b = ∅ := eq_empty_iff_forall_not_mem.2 $ λ x ⟨ha, hb⟩, h (ha.trans hb) @[simp] lemma Icc_eq_empty_of_lt (h : b < a) : Icc a b = ∅ := Icc_eq_empty h.not_le @[simp] lemma Ico_eq_empty_of_le (h : b ≤ a) : Ico a b = ∅ := Ico_eq_empty h.not_lt @[simp] lemma Ioc_eq_empty_of_le (h : b ≤ a) : Ioc a b = ∅ := Ioc_eq_empty h.not_lt @[simp] lemma Ioo_eq_empty_of_le (h : b ≤ a) : Ioo a b = ∅ := Ioo_eq_empty h.not_lt @[simp] lemma Ico_self (a : α) : Ico a a = ∅ := Ico_eq_empty $ lt_irrefl _ @[simp] lemma Ioc_self (a : α) : Ioc a a = ∅ := Ioc_eq_empty $ lt_irrefl _ @[simp] lemma Ioo_self (a : α) : Ioo a a = ∅ := Ioo_eq_empty $ lt_irrefl _ lemma Ici_subset_Ici : Ici a ⊆ Ici b ↔ b ≤ a := ⟨λ h, h $ left_mem_Ici, λ h x hx, h.trans hx⟩ lemma Iic_subset_Iic : Iic a ⊆ Iic b ↔ a ≤ b := @Ici_subset_Ici αᵒᵈ _ _ _ lemma Ici_subset_Ioi : Ici a ⊆ Ioi b ↔ b < a := ⟨λ h, h left_mem_Ici, λ h x hx, h.trans_le hx⟩ lemma Iic_subset_Iio : Iic a ⊆ Iio b ↔ a < b := ⟨λ h, h right_mem_Iic, λ h x hx, lt_of_le_of_lt hx h⟩ lemma Ioo_subset_Ioo (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) : Ioo a₁ b₁ ⊆ Ioo a₂ b₂ := λ x ⟨hx₁, hx₂⟩, ⟨h₁.trans_lt hx₁, hx₂.trans_le h₂⟩ lemma Ioo_subset_Ioo_left (h : a₁ ≤ a₂) : Ioo a₂ b ⊆ Ioo a₁ b := Ioo_subset_Ioo h le_rfl lemma Ioo_subset_Ioo_right (h : b₁ ≤ b₂) : Ioo a b₁ ⊆ Ioo a b₂ := Ioo_subset_Ioo le_rfl h lemma Ico_subset_Ico (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) : Ico a₁ b₁ ⊆ Ico a₂ b₂ := λ x ⟨hx₁, hx₂⟩, ⟨h₁.trans hx₁, hx₂.trans_le h₂⟩ lemma Ico_subset_Ico_left (h : a₁ ≤ a₂) : Ico a₂ b ⊆ Ico a₁ b := Ico_subset_Ico h le_rfl lemma Ico_subset_Ico_right (h : b₁ ≤ b₂) : Ico a b₁ ⊆ Ico a b₂ := Ico_subset_Ico le_rfl h lemma Icc_subset_Icc (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) : Icc a₁ b₁ ⊆ Icc a₂ b₂ := λ x ⟨hx₁, hx₂⟩, ⟨h₁.trans hx₁, le_trans hx₂ h₂⟩ lemma Icc_subset_Icc_left (h : a₁ ≤ a₂) : Icc a₂ b ⊆ Icc a₁ b := Icc_subset_Icc h le_rfl lemma Icc_subset_Icc_right (h : b₁ ≤ b₂) : Icc a b₁ ⊆ Icc a b₂ := Icc_subset_Icc le_rfl h lemma Icc_subset_Ioo (ha : a₂ < a₁) (hb : b₁ < b₂) : Icc a₁ b₁ ⊆ Ioo a₂ b₂ := λ x hx, ⟨ha.trans_le hx.1, hx.2.trans_lt hb⟩ lemma Icc_subset_Ici_self : Icc a b ⊆ Ici a := λ x, and.left lemma Icc_subset_Iic_self : Icc a b ⊆ Iic b := λ x, and.right lemma Ioc_subset_Iic_self : Ioc a b ⊆ Iic b := λ x, and.right lemma Ioc_subset_Ioc (h₁ : a₂ ≤ a₁) (h₂ : b₁ ≤ b₂) : Ioc a₁ b₁ ⊆ Ioc a₂ b₂ := λ x ⟨hx₁, hx₂⟩, ⟨h₁.trans_lt hx₁, hx₂.trans h₂⟩ lemma Ioc_subset_Ioc_left (h : a₁ ≤ a₂) : Ioc a₂ b ⊆ Ioc a₁ b := Ioc_subset_Ioc h le_rfl lemma Ioc_subset_Ioc_right (h : b₁ ≤ b₂) : Ioc a b₁ ⊆ Ioc a b₂ := Ioc_subset_Ioc le_rfl h lemma Ico_subset_Ioo_left (h₁ : a₁ < a₂) : Ico a₂ b ⊆ Ioo a₁ b := λ x, and.imp_left h₁.trans_le lemma Ioc_subset_Ioo_right (h : b₁ < b₂) : Ioc a b₁ ⊆ Ioo a b₂ := λ x, and.imp_right $ λ h', h'.trans_lt h lemma Icc_subset_Ico_right (h₁ : b₁ < b₂) : Icc a b₁ ⊆ Ico a b₂ := λ x, and.imp_right $ λ h₂, h₂.trans_lt h₁ lemma Ioo_subset_Ico_self : Ioo a b ⊆ Ico a b := λ x, and.imp_left le_of_lt lemma Ioo_subset_Ioc_self : Ioo a b ⊆ Ioc a b := λ x, and.imp_right le_of_lt lemma Ico_subset_Icc_self : Ico a b ⊆ Icc a b := λ x, and.imp_right le_of_lt lemma Ioc_subset_Icc_self : Ioc a b ⊆ Icc a b := λ x, and.imp_left le_of_lt lemma Ioo_subset_Icc_self : Ioo a b ⊆ Icc a b := subset.trans Ioo_subset_Ico_self Ico_subset_Icc_self lemma Ico_subset_Iio_self : Ico a b ⊆ Iio b := λ x, and.right lemma Ioo_subset_Iio_self : Ioo a b ⊆ Iio b := λ x, and.right lemma Ioc_subset_Ioi_self : Ioc a b ⊆ Ioi a := λ x, and.left lemma Ioo_subset_Ioi_self : Ioo a b ⊆ Ioi a := λ x, and.left lemma Ioi_subset_Ici_self : Ioi a ⊆ Ici a := λ x hx, le_of_lt hx lemma Iio_subset_Iic_self : Iio a ⊆ Iic a := λ x hx, le_of_lt hx lemma Ico_subset_Ici_self : Ico a b ⊆ Ici a := λ x, and.left lemma Icc_subset_Icc_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Icc a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ ≤ b₂ := ⟨λ h, ⟨(h ⟨le_rfl, h₁⟩).1, (h ⟨h₁, le_rfl⟩).2⟩, λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨h.trans hx, hx'.trans h'⟩⟩ lemma Icc_subset_Ioo_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ioo a₂ b₂ ↔ a₂ < a₁ ∧ b₁ < b₂ := ⟨λ h, ⟨(h ⟨le_rfl, h₁⟩).1, (h ⟨h₁, le_rfl⟩).2⟩, λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨h.trans_le hx, hx'.trans_lt h'⟩⟩ lemma Icc_subset_Ico_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ico a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ < b₂ := ⟨λ h, ⟨(h ⟨le_rfl, h₁⟩).1, (h ⟨h₁, le_rfl⟩).2⟩, λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨h.trans hx, hx'.trans_lt h'⟩⟩ lemma Icc_subset_Ioc_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ioc a₂ b₂ ↔ a₂ < a₁ ∧ b₁ ≤ b₂ := ⟨λ h, ⟨(h ⟨le_rfl, h₁⟩).1, (h ⟨h₁, le_rfl⟩).2⟩, λ ⟨h, h'⟩ x ⟨hx, hx'⟩, ⟨h.trans_le hx, hx'.trans h'⟩⟩ lemma Icc_subset_Iio_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Iio b₂ ↔ b₁ < b₂ := ⟨λ h, h ⟨h₁, le_rfl⟩, λ h x ⟨hx, hx'⟩, hx'.trans_lt h⟩ lemma Icc_subset_Ioi_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ioi a₂ ↔ a₂ < a₁ := ⟨λ h, h ⟨le_rfl, h₁⟩, λ h x ⟨hx, hx'⟩, h.trans_le hx⟩ lemma Icc_subset_Iic_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Iic b₂ ↔ b₁ ≤ b₂ := ⟨λ h, h ⟨h₁, le_rfl⟩, λ h x ⟨hx, hx'⟩, hx'.trans h⟩ lemma Icc_subset_Ici_iff (h₁ : a₁ ≤ b₁) : Icc a₁ b₁ ⊆ Ici a₂ ↔ a₂ ≤ a₁ := ⟨λ h, h ⟨le_rfl, h₁⟩, λ h x ⟨hx, hx'⟩, h.trans hx⟩ lemma Icc_ssubset_Icc_left (hI : a₂ ≤ b₂) (ha : a₂ < a₁) (hb : b₁ ≤ b₂) : Icc a₁ b₁ ⊂ Icc a₂ b₂ := (ssubset_iff_of_subset (Icc_subset_Icc (le_of_lt ha) hb)).mpr ⟨a₂, left_mem_Icc.mpr hI, not_and.mpr (λ f g, lt_irrefl a₂ (ha.trans_le f))⟩ lemma Icc_ssubset_Icc_right (hI : a₂ ≤ b₂) (ha : a₂ ≤ a₁) (hb : b₁ < b₂) : Icc a₁ b₁ ⊂ Icc a₂ b₂ := (ssubset_iff_of_subset (Icc_subset_Icc ha (le_of_lt hb))).mpr ⟨b₂, right_mem_Icc.mpr hI, (λ f, lt_irrefl b₁ (hb.trans_le f.2))⟩ /-- If `a ≤ b`, then `(b, +∞) ⊆ (a, +∞)`. In preorders, this is just an implication. If you need the equivalence in linear orders, use `Ioi_subset_Ioi_iff`. -/ lemma Ioi_subset_Ioi (h : a ≤ b) : Ioi b ⊆ Ioi a := λ x hx, h.trans_lt hx /-- If `a ≤ b`, then `(b, +∞) ⊆ [a, +∞)`. In preorders, this is just an implication. If you need the equivalence in dense linear orders, use `Ioi_subset_Ici_iff`. -/ lemma Ioi_subset_Ici (h : a ≤ b) : Ioi b ⊆ Ici a := subset.trans (Ioi_subset_Ioi h) Ioi_subset_Ici_self /-- If `a ≤ b`, then `(-∞, a) ⊆ (-∞, b)`. In preorders, this is just an implication. If you need the equivalence in linear orders, use `Iio_subset_Iio_iff`. -/ lemma Iio_subset_Iio (h : a ≤ b) : Iio a ⊆ Iio b := λ x hx, lt_of_lt_of_le hx h /-- If `a ≤ b`, then `(-∞, a) ⊆ (-∞, b]`. In preorders, this is just an implication. If you need the equivalence in dense linear orders, use `Iio_subset_Iic_iff`. -/ lemma Iio_subset_Iic (h : a ≤ b) : Iio a ⊆ Iic b := subset.trans (Iio_subset_Iio h) Iio_subset_Iic_self lemma Ici_inter_Iic : Ici a ∩ Iic b = Icc a b := rfl lemma Ici_inter_Iio : Ici a ∩ Iio b = Ico a b := rfl lemma Ioi_inter_Iic : Ioi a ∩ Iic b = Ioc a b := rfl lemma Ioi_inter_Iio : Ioi a ∩ Iio b = Ioo a b := rfl lemma Iic_inter_Ici : Iic a ∩ Ici b = Icc b a := inter_comm _ _ lemma Iio_inter_Ici : Iio a ∩ Ici b = Ico b a := inter_comm _ _ lemma Iic_inter_Ioi : Iic a ∩ Ioi b = Ioc b a := inter_comm _ _ lemma Iio_inter_Ioi : Iio a ∩ Ioi b = Ioo b a := inter_comm _ _ lemma mem_Icc_of_Ioo (h : x ∈ Ioo a b) : x ∈ Icc a b := Ioo_subset_Icc_self h lemma mem_Ico_of_Ioo (h : x ∈ Ioo a b) : x ∈ Ico a b := Ioo_subset_Ico_self h lemma mem_Ioc_of_Ioo (h : x ∈ Ioo a b) : x ∈ Ioc a b := Ioo_subset_Ioc_self h lemma mem_Icc_of_Ico (h : x ∈ Ico a b) : x ∈ Icc a b := Ico_subset_Icc_self h lemma mem_Icc_of_Ioc (h : x ∈ Ioc a b) : x ∈ Icc a b := Ioc_subset_Icc_self h lemma mem_Ici_of_Ioi (h : x ∈ Ioi a) : x ∈ Ici a := Ioi_subset_Ici_self h lemma mem_Iic_of_Iio (h : x ∈ Iio a) : x ∈ Iic a := Iio_subset_Iic_self h lemma Icc_eq_empty_iff : Icc a b = ∅ ↔ ¬a ≤ b := by rw [←not_nonempty_iff_eq_empty, not_iff_not, nonempty_Icc] lemma Ico_eq_empty_iff : Ico a b = ∅ ↔ ¬a < b := by rw [←not_nonempty_iff_eq_empty, not_iff_not, nonempty_Ico] lemma Ioc_eq_empty_iff : Ioc a b = ∅ ↔ ¬a < b := by rw [←not_nonempty_iff_eq_empty, not_iff_not, nonempty_Ioc] lemma Ioo_eq_empty_iff [densely_ordered α] : Ioo a b = ∅ ↔ ¬a < b := by rw [←not_nonempty_iff_eq_empty, not_iff_not, nonempty_Ioo] lemma _root_.is_top.Iic_eq (h : is_top a) : Iic a = univ := eq_univ_of_forall h lemma _root_.is_bot.Ici_eq (h : is_bot a) : Ici a = univ := eq_univ_of_forall h lemma _root_.is_max.Ioi_eq (h : is_max a) : Ioi a = ∅ := eq_empty_of_subset_empty $ λ b, h.not_lt lemma _root_.is_min.Iio_eq (h : is_min a) : Iio a = ∅ := eq_empty_of_subset_empty $ λ b, h.not_lt lemma Iic_inter_Ioc_of_le (h : a ≤ c) : Iic a ∩ Ioc b c = Ioc b a := ext $ λ x, ⟨λ H, ⟨H.2.1, H.1⟩, λ H, ⟨H.2, H.1, H.2.trans h⟩⟩ end preorder section partial_order variables [partial_order α] {a b c : α} @[simp] lemma Icc_self (a : α) : Icc a a = {a} := set.ext $ by simp [Icc, le_antisymm_iff, and_comm] @[simp] lemma Icc_eq_singleton_iff : Icc a b = {c} ↔ a = c ∧ b = c := begin refine ⟨λ h, _, _⟩, { have hab : a ≤ b := nonempty_Icc.1 (h.symm.subst $ singleton_nonempty c), exact ⟨eq_of_mem_singleton $ h.subst $ left_mem_Icc.2 hab, eq_of_mem_singleton $ h.subst $ right_mem_Icc.2 hab⟩ }, { rintro ⟨rfl, rfl⟩, exact Icc_self _ } end @[simp] lemma Icc_diff_left : Icc a b \ {a} = Ioc a b := ext $ λ x, by simp [lt_iff_le_and_ne, eq_comm, and.right_comm] @[simp] lemma Icc_diff_right : Icc a b \ {b} = Ico a b := ext $ λ x, by simp [lt_iff_le_and_ne, and_assoc] @[simp] lemma Ico_diff_left : Ico a b \ {a} = Ioo a b := ext $ λ x, by simp [and.right_comm, ← lt_iff_le_and_ne, eq_comm] @[simp] lemma Ioc_diff_right : Ioc a b \ {b} = Ioo a b := ext $ λ x, by simp [and_assoc, ← lt_iff_le_and_ne] @[simp] lemma Icc_diff_both : Icc a b \ {a, b} = Ioo a b := by rw [insert_eq, ← diff_diff, Icc_diff_left, Ioc_diff_right] @[simp] lemma Ici_diff_left : Ici a \ {a} = Ioi a := ext $ λ x, by simp [lt_iff_le_and_ne, eq_comm] @[simp] lemma Iic_diff_right : Iic a \ {a} = Iio a := ext $ λ x, by simp [lt_iff_le_and_ne] @[simp] lemma Ico_diff_Ioo_same (h : a < b) : Ico a b \ Ioo a b = {a} := by rw [← Ico_diff_left, diff_diff_cancel_left (singleton_subset_iff.2 $ left_mem_Ico.2 h)] @[simp] lemma Ioc_diff_Ioo_same (h : a < b) : Ioc a b \ Ioo a b = {b} := by rw [← Ioc_diff_right, diff_diff_cancel_left (singleton_subset_iff.2 $ right_mem_Ioc.2 h)] @[simp] lemma Icc_diff_Ico_same (h : a ≤ b) : Icc a b \ Ico a b = {b} := by rw [← Icc_diff_right, diff_diff_cancel_left (singleton_subset_iff.2 $ right_mem_Icc.2 h)] @[simp] lemma Icc_diff_Ioc_same (h : a ≤ b) : Icc a b \ Ioc a b = {a} := by rw [← Icc_diff_left, diff_diff_cancel_left (singleton_subset_iff.2 $ left_mem_Icc.2 h)] @[simp] lemma Icc_diff_Ioo_same (h : a ≤ b) : Icc a b \ Ioo a b = {a, b} := by { rw [← Icc_diff_both, diff_diff_cancel_left], simp [insert_subset, h] } @[simp] lemma Ici_diff_Ioi_same : Ici a \ Ioi a = {a} := by rw [← Ici_diff_left, diff_diff_cancel_left (singleton_subset_iff.2 left_mem_Ici)] @[simp] lemma Iic_diff_Iio_same : Iic a \ Iio a = {a} := by rw [← Iic_diff_right, diff_diff_cancel_left (singleton_subset_iff.2 right_mem_Iic)] @[simp] lemma Ioi_union_left : Ioi a ∪ {a} = Ici a := ext $ λ x, by simp [eq_comm, le_iff_eq_or_lt] @[simp] lemma Iio_union_right : Iio a ∪ {a} = Iic a := ext $ λ x, le_iff_lt_or_eq.symm lemma Ioo_union_left (hab : a < b) : Ioo a b ∪ {a} = Ico a b := by rw [← Ico_diff_left, diff_union_self, union_eq_self_of_subset_right (singleton_subset_iff.2 $ left_mem_Ico.2 hab)] lemma Ioo_union_right (hab : a < b) : Ioo a b ∪ {b} = Ioc a b := by simpa only [dual_Ioo, dual_Ico] using Ioo_union_left hab.dual lemma Ioc_union_left (hab : a ≤ b) : Ioc a b ∪ {a} = Icc a b := by rw [← Icc_diff_left, diff_union_self, union_eq_self_of_subset_right (singleton_subset_iff.2 $ left_mem_Icc.2 hab)] lemma Ico_union_right (hab : a ≤ b) : Ico a b ∪ {b} = Icc a b := by simpa only [dual_Ioc, dual_Icc] using Ioc_union_left hab.dual @[simp] lemma Ico_insert_right (h : a ≤ b) : insert b (Ico a b) = Icc a b := by rw [insert_eq, union_comm, Ico_union_right h] @[simp] lemma Ioc_insert_left (h : a ≤ b) : insert a (Ioc a b) = Icc a b := by rw [insert_eq, union_comm, Ioc_union_left h] @[simp] lemma Ioo_insert_left (h : a < b) : insert a (Ioo a b) = Ico a b := by rw [insert_eq, union_comm, Ioo_union_left h] @[simp] lemma Ioo_insert_right (h : a < b) : insert b (Ioo a b) = Ioc a b := by rw [insert_eq, union_comm, Ioo_union_right h] @[simp] lemma Iio_insert : insert a (Iio a) = Iic a := ext $ λ _, le_iff_eq_or_lt.symm @[simp] lemma Ioi_insert : insert a (Ioi a) = Ici a := ext $ λ _, (or_congr_left' eq_comm).trans le_iff_eq_or_lt.symm lemma mem_Ici_Ioi_of_subset_of_subset {s : set α} (ho : Ioi a ⊆ s) (hc : s ⊆ Ici a) : s ∈ ({Ici a, Ioi a} : set (set α)) := classical.by_cases (λ h : a ∈ s, or.inl $ subset.antisymm hc $ by rw [← Ioi_union_left, union_subset_iff]; simp *) (λ h, or.inr $ subset.antisymm (λ x hx, lt_of_le_of_ne (hc hx) (λ heq, h $ heq.symm ▸ hx)) ho) lemma mem_Iic_Iio_of_subset_of_subset {s : set α} (ho : Iio a ⊆ s) (hc : s ⊆ Iic a) : s ∈ ({Iic a, Iio a} : set (set α)) := @mem_Ici_Ioi_of_subset_of_subset αᵒᵈ _ a s ho hc lemma mem_Icc_Ico_Ioc_Ioo_of_subset_of_subset {s : set α} (ho : Ioo a b ⊆ s) (hc : s ⊆ Icc a b) : s ∈ ({Icc a b, Ico a b, Ioc a b, Ioo a b} : set (set α)) := begin classical, by_cases ha : a ∈ s; by_cases hb : b ∈ s, { refine or.inl (subset.antisymm hc _), rwa [← Ico_diff_left, diff_singleton_subset_iff, insert_eq_of_mem ha, ← Icc_diff_right, diff_singleton_subset_iff, insert_eq_of_mem hb] at ho }, { refine (or.inr $ or.inl $ subset.antisymm _ _), { rw [← Icc_diff_right], exact subset_diff_singleton hc hb }, { rwa [← Ico_diff_left, diff_singleton_subset_iff, insert_eq_of_mem ha] at ho } }, { refine (or.inr $ or.inr $ or.inl $ subset.antisymm _ _), { rw [← Icc_diff_left], exact subset_diff_singleton hc ha }, { rwa [← Ioc_diff_right, diff_singleton_subset_iff, insert_eq_of_mem hb] at ho } }, { refine (or.inr $ or.inr $ or.inr $ subset.antisymm _ ho), rw [← Ico_diff_left, ← Icc_diff_right], apply_rules [subset_diff_singleton] } end lemma eq_left_or_mem_Ioo_of_mem_Ico {x : α} (hmem : x ∈ Ico a b) : x = a ∨ x ∈ Ioo a b := hmem.1.eq_or_gt.imp_right $ λ h, ⟨h, hmem.2⟩ lemma eq_right_or_mem_Ioo_of_mem_Ioc {x : α} (hmem : x ∈ Ioc a b) : x = b ∨ x ∈ Ioo a b := hmem.2.eq_or_lt.imp_right $ and.intro hmem.1 lemma eq_endpoints_or_mem_Ioo_of_mem_Icc {x : α} (hmem : x ∈ Icc a b) : x = a ∨ x = b ∨ x ∈ Ioo a b := hmem.1.eq_or_gt.imp_right $ λ h, eq_right_or_mem_Ioo_of_mem_Ioc ⟨h, hmem.2⟩ lemma _root_.is_max.Ici_eq (h : is_max a) : Ici a = {a} := eq_singleton_iff_unique_mem.2 ⟨left_mem_Ici, λ b, h.eq_of_ge⟩ lemma _root_.is_min.Iic_eq (h : is_min a) : Iic a = {a} := h.to_dual.Ici_eq end partial_order section order_top @[simp] lemma Ici_top [partial_order α] [order_top α] : Ici (⊤ : α) = {⊤} := is_max_top.Ici_eq variables [preorder α] [order_top α] {a : α} @[simp] lemma Ioi_top : Ioi (⊤ : α) = ∅ := is_max_top.Ioi_eq @[simp] lemma Iic_top : Iic (⊤ : α) = univ := is_top_top.Iic_eq @[simp] lemma Icc_top : Icc a ⊤ = Ici a := by simp [← Ici_inter_Iic] @[simp] lemma Ioc_top : Ioc a ⊤ = Ioi a := by simp [← Ioi_inter_Iic] end order_top section order_bot @[simp] lemma Iic_bot [partial_order α] [order_bot α] : Iic (⊥ : α) = {⊥} := is_min_bot.Iic_eq variables [preorder α] [order_bot α] {a : α} @[simp] lemma Iio_bot : Iio (⊥ : α) = ∅ := is_min_bot.Iio_eq @[simp] lemma Ici_bot : Ici (⊥ : α) = univ := is_bot_bot.Ici_eq @[simp] lemma Icc_bot : Icc ⊥ a = Iic a := by simp [← Ici_inter_Iic] @[simp] lemma Ico_bot : Ico ⊥ a = Iio a := by simp [← Ici_inter_Iio] end order_bot lemma Icc_bot_top [partial_order α] [bounded_order α] : Icc (⊥ : α) ⊤ = univ := by simp section linear_order variables [linear_order α] {a a₁ a₂ b b₁ b₂ c d : α} lemma not_mem_Ici : c ∉ Ici a ↔ c < a := not_le lemma not_mem_Iic : c ∉ Iic b ↔ b < c := not_le lemma not_mem_Icc_of_lt (ha : c < a) : c ∉ Icc a b := not_mem_subset Icc_subset_Ici_self $ not_mem_Ici.mpr ha lemma not_mem_Icc_of_gt (hb : b < c) : c ∉ Icc a b := not_mem_subset Icc_subset_Iic_self $ not_mem_Iic.mpr hb lemma not_mem_Ico_of_lt (ha : c < a) : c ∉ Ico a b := not_mem_subset Ico_subset_Ici_self $ not_mem_Ici.mpr ha lemma not_mem_Ioc_of_gt (hb : b < c) : c ∉ Ioc a b := not_mem_subset Ioc_subset_Iic_self $ not_mem_Iic.mpr hb lemma not_mem_Ioi : c ∉ Ioi a ↔ c ≤ a := not_lt lemma not_mem_Iio : c ∉ Iio b ↔ b ≤ c := not_lt lemma not_mem_Ioc_of_le (ha : c ≤ a) : c ∉ Ioc a b := not_mem_subset Ioc_subset_Ioi_self $ not_mem_Ioi.mpr ha lemma not_mem_Ico_of_ge (hb : b ≤ c) : c ∉ Ico a b := not_mem_subset Ico_subset_Iio_self $ not_mem_Iio.mpr hb lemma not_mem_Ioo_of_le (ha : c ≤ a) : c ∉ Ioo a b := not_mem_subset Ioo_subset_Ioi_self $ not_mem_Ioi.mpr ha lemma not_mem_Ioo_of_ge (hb : b ≤ c) : c ∉ Ioo a b := not_mem_subset Ioo_subset_Iio_self $ not_mem_Iio.mpr hb @[simp] lemma compl_Iic : (Iic a)ᶜ = Ioi a := ext $ λ _, not_le @[simp] lemma compl_Ici : (Ici a)ᶜ = Iio a := ext $ λ _, not_le @[simp] lemma compl_Iio : (Iio a)ᶜ = Ici a := ext $ λ _, not_lt @[simp] lemma compl_Ioi : (Ioi a)ᶜ = Iic a := ext $ λ _, not_lt @[simp] lemma Ici_diff_Ici : Ici a \ Ici b = Ico a b := by rw [diff_eq, compl_Ici, Ici_inter_Iio] @[simp] lemma Ici_diff_Ioi : Ici a \ Ioi b = Icc a b := by rw [diff_eq, compl_Ioi, Ici_inter_Iic] @[simp] lemma Ioi_diff_Ioi : Ioi a \ Ioi b = Ioc a b := by rw [diff_eq, compl_Ioi, Ioi_inter_Iic] @[simp] lemma Ioi_diff_Ici : Ioi a \ Ici b = Ioo a b := by rw [diff_eq, compl_Ici, Ioi_inter_Iio] @[simp] lemma Iic_diff_Iic : Iic b \ Iic a = Ioc a b := by rw [diff_eq, compl_Iic, inter_comm, Ioi_inter_Iic] @[simp] lemma Iio_diff_Iic : Iio b \ Iic a = Ioo a b := by rw [diff_eq, compl_Iic, inter_comm, Ioi_inter_Iio] @[simp] lemma Iic_diff_Iio : Iic b \ Iio a = Icc a b := by rw [diff_eq, compl_Iio, inter_comm, Ici_inter_Iic] @[simp] lemma Iio_diff_Iio : Iio b \ Iio a = Ico a b := by rw [diff_eq, compl_Iio, inter_comm, Ici_inter_Iio] lemma Ico_subset_Ico_iff (h₁ : a₁ < b₁) : Ico a₁ b₁ ⊆ Ico a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ ≤ b₂ := ⟨λ h, have a₂ ≤ a₁ ∧ a₁ < b₂ := h ⟨le_rfl, h₁⟩, ⟨this.1, le_of_not_lt $ λ h', lt_irrefl b₂ (h ⟨this.2.le, h'⟩).2⟩, λ ⟨h₁, h₂⟩, Ico_subset_Ico h₁ h₂⟩ lemma Ioc_subset_Ioc_iff (h₁ : a₁ < b₁) : Ioc a₁ b₁ ⊆ Ioc a₂ b₂ ↔ b₁ ≤ b₂ ∧ a₂ ≤ a₁ := by { convert @Ico_subset_Ico_iff αᵒᵈ _ b₁ b₂ a₁ a₂ h₁; exact (@dual_Ico α _ _ _).symm } lemma Ioo_subset_Ioo_iff [densely_ordered α] (h₁ : a₁ < b₁) : Ioo a₁ b₁ ⊆ Ioo a₂ b₂ ↔ a₂ ≤ a₁ ∧ b₁ ≤ b₂ := ⟨λ h, begin rcases exists_between h₁ with ⟨x, xa, xb⟩, split; refine le_of_not_lt (λ h', _), { have ab := (h ⟨xa, xb⟩).1.trans xb, exact lt_irrefl _ (h ⟨h', ab⟩).1 }, { have ab := xa.trans (h ⟨xa, xb⟩).2, exact lt_irrefl _ (h ⟨ab, h'⟩).2 } end, λ ⟨h₁, h₂⟩, Ioo_subset_Ioo h₁ h₂⟩ lemma Ico_eq_Ico_iff (h : a₁ < b₁ ∨ a₂ < b₂) : Ico a₁ b₁ = Ico a₂ b₂ ↔ a₁ = a₂ ∧ b₁ = b₂ := ⟨λ e, begin simp [subset.antisymm_iff] at e, simp [le_antisymm_iff], cases h; simp [Ico_subset_Ico_iff h] at e; [ rcases e with ⟨⟨h₁, h₂⟩, e'⟩, rcases e with ⟨e', ⟨h₁, h₂⟩⟩ ]; have := (Ico_subset_Ico_iff $ h₁.trans_lt $ h.trans_le h₂).1 e'; tauto end, λ ⟨h₁, h₂⟩, by rw [h₁, h₂]⟩ open_locale classical @[simp] lemma Ioi_subset_Ioi_iff : Ioi b ⊆ Ioi a ↔ a ≤ b := begin refine ⟨λ h, _, λ h, Ioi_subset_Ioi h⟩, by_contradiction ba, exact lt_irrefl _ (h (not_le.mp ba)) end @[simp] lemma Ioi_subset_Ici_iff [densely_ordered α] : Ioi b ⊆ Ici a ↔ a ≤ b := begin refine ⟨λ h, _, λ h, Ioi_subset_Ici h⟩, by_contradiction ba, obtain ⟨c, bc, ca⟩ : ∃c, b < c ∧ c < a := exists_between (not_le.mp ba), exact lt_irrefl _ (ca.trans_le (h bc)) end @[simp] lemma Iio_subset_Iio_iff : Iio a ⊆ Iio b ↔ a ≤ b := begin refine ⟨λ h, _, λ h, Iio_subset_Iio h⟩, by_contradiction ab, exact lt_irrefl _ (h (not_le.mp ab)) end @[simp] lemma Iio_subset_Iic_iff [densely_ordered α] : Iio a ⊆ Iic b ↔ a ≤ b := by rw [←diff_eq_empty, Iio_diff_Iic, Ioo_eq_empty_iff, not_lt] /-! ### Unions of adjacent intervals -/ /-! #### Two infinite intervals -/ @[simp] lemma Iic_union_Ici : Iic a ∪ Ici a = univ := eq_univ_of_forall (λ x, le_total x a) @[simp] lemma Iio_union_Ici : Iio a ∪ Ici a = univ := eq_univ_of_forall (λ x, lt_or_le x a) @[simp] lemma Iic_union_Ioi : Iic a ∪ Ioi a = univ := eq_univ_of_forall (λ x, le_or_lt x a) /-! #### A finite and an infinite interval -/ lemma Ioo_union_Ioi' (h₁ : c < b) : Ioo a b ∪ Ioi c = Ioi (min a c) := begin ext1 x, simp_rw [mem_union, mem_Ioo, mem_Ioi, min_lt_iff], by_cases hc : c < x, { tauto }, { have hxb : x < b := (le_of_not_gt hc).trans_lt h₁, tauto }, end lemma Ioo_union_Ioi (h : c < max a b) : Ioo a b ∪ Ioi c = Ioi (min a c) := begin cases le_total a b with hab hab; simp [hab] at h, { exact Ioo_union_Ioi' h }, { rw min_comm, simp [*, min_eq_left_of_lt] }, end lemma Ioi_subset_Ioo_union_Ici : Ioi a ⊆ Ioo a b ∪ Ici b := λ x hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx, hxb⟩) (λ hxb, or.inr hxb) @[simp] lemma Ioo_union_Ici_eq_Ioi (h : a < b) : Ioo a b ∪ Ici b = Ioi a := subset.antisymm (λ x hx, hx.elim and.left h.trans_le) Ioi_subset_Ioo_union_Ici lemma Ici_subset_Ico_union_Ici : Ici a ⊆ Ico a b ∪ Ici b := λ x hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx, hxb⟩) (λ hxb, or.inr hxb) @[simp] lemma Ico_union_Ici_eq_Ici (h : a ≤ b) : Ico a b ∪ Ici b = Ici a := subset.antisymm (λ x hx, hx.elim and.left h.trans) Ici_subset_Ico_union_Ici lemma Ico_union_Ici' (h₁ : c ≤ b) : Ico a b ∪ Ici c = Ici (min a c) := begin ext1 x, simp_rw [mem_union, mem_Ico, mem_Ici, min_le_iff], by_cases hc : c ≤ x, { tauto }, { have hxb : x < b := (lt_of_not_ge hc).trans_le h₁, tauto }, end lemma Ico_union_Ici (h : c ≤ max a b) : Ico a b ∪ Ici c = Ici (min a c) := begin cases le_total a b with hab hab; simp [hab] at h, { exact Ico_union_Ici' h }, { simp [*] }, end lemma Ioi_subset_Ioc_union_Ioi : Ioi a ⊆ Ioc a b ∪ Ioi b := λ x hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx, hxb⟩) (λ hxb, or.inr hxb) @[simp] lemma Ioc_union_Ioi_eq_Ioi (h : a ≤ b) : Ioc a b ∪ Ioi b = Ioi a := subset.antisymm (λ x hx, hx.elim and.left h.trans_lt) Ioi_subset_Ioc_union_Ioi lemma Ioc_union_Ioi' (h₁ : c ≤ b) : Ioc a b ∪ Ioi c = Ioi (min a c) := begin ext1 x, simp_rw [mem_union, mem_Ioc, mem_Ioi, min_lt_iff], by_cases hc : c < x, { tauto }, { have hxb : x ≤ b := (le_of_not_gt hc).trans h₁, tauto }, end lemma Ioc_union_Ioi (h : c ≤ max a b) : Ioc a b ∪ Ioi c = Ioi (min a c) := begin cases le_total a b with hab hab; simp [hab] at h, { exact Ioc_union_Ioi' h }, { simp [*] }, end lemma Ici_subset_Icc_union_Ioi : Ici a ⊆ Icc a b ∪ Ioi b := λ x hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx, hxb⟩) (λ hxb, or.inr hxb) @[simp] lemma Icc_union_Ioi_eq_Ici (h : a ≤ b) : Icc a b ∪ Ioi b = Ici a := subset.antisymm (λ x hx, hx.elim and.left $ λ hx', h.trans $ le_of_lt hx') Ici_subset_Icc_union_Ioi lemma Ioi_subset_Ioc_union_Ici : Ioi a ⊆ Ioc a b ∪ Ici b := subset.trans Ioi_subset_Ioo_union_Ici (union_subset_union_left _ Ioo_subset_Ioc_self) @[simp] lemma Ioc_union_Ici_eq_Ioi (h : a < b) : Ioc a b ∪ Ici b = Ioi a := subset.antisymm (λ x hx, hx.elim and.left h.trans_le) Ioi_subset_Ioc_union_Ici lemma Ici_subset_Icc_union_Ici : Ici a ⊆ Icc a b ∪ Ici b := subset.trans Ici_subset_Ico_union_Ici (union_subset_union_left _ Ico_subset_Icc_self) @[simp] lemma Icc_union_Ici_eq_Ici (h : a ≤ b) : Icc a b ∪ Ici b = Ici a := subset.antisymm (λ x hx, hx.elim and.left h.trans) Ici_subset_Icc_union_Ici lemma Icc_union_Ici' (h₁ : c ≤ b) : Icc a b ∪ Ici c = Ici (min a c) := begin ext1 x, simp_rw [mem_union, mem_Icc, mem_Ici, min_le_iff], by_cases hc : c ≤ x, { tauto }, { have hxb : x ≤ b := (le_of_not_ge hc).trans h₁, tauto }, end lemma Icc_union_Ici (h : c ≤ max a b) : Icc a b ∪ Ici c = Ici (min a c) := begin cases le_or_lt a b with hab hab; simp [hab] at h, { exact Icc_union_Ici' h }, { cases h, { simp [*] }, { have hca : c ≤ a := h.trans hab.le, simp [*] } }, end /-! #### An infinite and a finite interval -/ lemma Iic_subset_Iio_union_Icc : Iic b ⊆ Iio a ∪ Icc a b := λ x hx, (lt_or_le x a).elim (λ hxa, or.inl hxa) (λ hxa, or.inr ⟨hxa, hx⟩) @[simp] lemma Iio_union_Icc_eq_Iic (h : a ≤ b) : Iio a ∪ Icc a b = Iic b := subset.antisymm (λ x hx, hx.elim (λ hx, (le_of_lt hx).trans h) and.right) Iic_subset_Iio_union_Icc lemma Iio_subset_Iio_union_Ico : Iio b ⊆ Iio a ∪ Ico a b := λ x hx, (lt_or_le x a).elim (λ hxa, or.inl hxa) (λ hxa, or.inr ⟨hxa, hx⟩) @[simp] lemma Iio_union_Ico_eq_Iio (h : a ≤ b) : Iio a ∪ Ico a b = Iio b := subset.antisymm (λ x hx, hx.elim (λ hx', lt_of_lt_of_le hx' h) and.right) Iio_subset_Iio_union_Ico lemma Iio_union_Ico' (h₁ : c ≤ b) : Iio b ∪ Ico c d = Iio (max b d) := begin ext1 x, simp_rw [mem_union, mem_Iio, mem_Ico, lt_max_iff], by_cases hc : c ≤ x, { tauto }, { have hxb : x < b := (lt_of_not_ge hc).trans_le h₁, tauto }, end lemma Iio_union_Ico (h : min c d ≤ b) : Iio b ∪ Ico c d = Iio (max b d) := begin cases le_total c d with hcd hcd; simp [hcd] at h, { exact Iio_union_Ico' h }, { simp [*] }, end lemma Iic_subset_Iic_union_Ioc : Iic b ⊆ Iic a ∪ Ioc a b := λ x hx, (le_or_lt x a).elim (λ hxa, or.inl hxa) (λ hxa, or.inr ⟨hxa, hx⟩) @[simp] lemma Iic_union_Ioc_eq_Iic (h : a ≤ b) : Iic a ∪ Ioc a b = Iic b := subset.antisymm (λ x hx, hx.elim (λ hx', le_trans hx' h) and.right) Iic_subset_Iic_union_Ioc lemma Iic_union_Ioc' (h₁ : c < b) : Iic b ∪ Ioc c d = Iic (max b d) := begin ext1 x, simp_rw [mem_union, mem_Iic, mem_Ioc, le_max_iff], by_cases hc : c < x, { tauto }, { have hxb : x ≤ b := (le_of_not_gt hc).trans h₁.le, tauto }, end lemma Iic_union_Ioc (h : min c d < b) : Iic b ∪ Ioc c d = Iic (max b d) := begin cases le_total c d with hcd hcd; simp [hcd] at h, { exact Iic_union_Ioc' h }, { rw max_comm, simp [*, max_eq_right_of_lt h] }, end lemma Iio_subset_Iic_union_Ioo : Iio b ⊆ Iic a ∪ Ioo a b := λ x hx, (le_or_lt x a).elim (λ hxa, or.inl hxa) (λ hxa, or.inr ⟨hxa, hx⟩) @[simp] lemma Iic_union_Ioo_eq_Iio (h : a < b) : Iic a ∪ Ioo a b = Iio b := subset.antisymm (λ x hx, hx.elim (λ hx', lt_of_le_of_lt hx' h) and.right) Iio_subset_Iic_union_Ioo lemma Iio_union_Ioo' (h₁ : c < b) : Iio b ∪ Ioo c d = Iio (max b d) := begin ext x, cases lt_or_le x b with hba hba, { simp [hba, h₁] }, { simp only [mem_Iio, mem_union_eq, mem_Ioo, lt_max_iff], refine or_congr iff.rfl ⟨and.right, _⟩, exact λ h₂, ⟨h₁.trans_le hba, h₂⟩ }, end lemma Iio_union_Ioo (h : min c d < b) : Iio b ∪ Ioo c d = Iio (max b d) := begin cases le_total c d with hcd hcd; simp [hcd] at h, { exact Iio_union_Ioo' h }, { rw max_comm, simp [*, max_eq_right_of_lt h] }, end lemma Iic_subset_Iic_union_Icc : Iic b ⊆ Iic a ∪ Icc a b := subset.trans Iic_subset_Iic_union_Ioc (union_subset_union_right _ Ioc_subset_Icc_self) @[simp] lemma Iic_union_Icc_eq_Iic (h : a ≤ b) : Iic a ∪ Icc a b = Iic b := subset.antisymm (λ x hx, hx.elim (λ hx', le_trans hx' h) and.right) Iic_subset_Iic_union_Icc lemma Iic_union_Icc' (h₁ : c ≤ b) : Iic b ∪ Icc c d = Iic (max b d) := begin ext1 x, simp_rw [mem_union, mem_Iic, mem_Icc, le_max_iff], by_cases hc : c ≤ x, { tauto }, { have hxb : x ≤ b := (le_of_not_ge hc).trans h₁, tauto }, end lemma Iic_union_Icc (h : min c d ≤ b) : Iic b ∪ Icc c d = Iic (max b d) := begin cases le_or_lt c d with hcd hcd; simp [hcd] at h, { exact Iic_union_Icc' h }, { cases h, { have hdb : d ≤ b := hcd.le.trans h, simp [*] }, { simp [*] } }, end lemma Iio_subset_Iic_union_Ico : Iio b ⊆ Iic a ∪ Ico a b := subset.trans Iio_subset_Iic_union_Ioo (union_subset_union_right _ Ioo_subset_Ico_self) @[simp] lemma Iic_union_Ico_eq_Iio (h : a < b) : Iic a ∪ Ico a b = Iio b := subset.antisymm (λ x hx, hx.elim (λ hx', lt_of_le_of_lt hx' h) and.right) Iio_subset_Iic_union_Ico /-! #### Two finite intervals, `I?o` and `Ic?` -/ lemma Ioo_subset_Ioo_union_Ico : Ioo a c ⊆ Ioo a b ∪ Ico b c := λ x hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Ioo_union_Ico_eq_Ioo (h₁ : a < b) (h₂ : b ≤ c) : Ioo a b ∪ Ico b c = Ioo a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, hx.2.trans_le h₂⟩) (λ hx, ⟨h₁.trans_le hx.1, hx.2⟩)) Ioo_subset_Ioo_union_Ico lemma Ico_subset_Ico_union_Ico : Ico a c ⊆ Ico a b ∪ Ico b c := λ x hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Ico_union_Ico_eq_Ico (h₁ : a ≤ b) (h₂ : b ≤ c) : Ico a b ∪ Ico b c = Ico a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, hx.2.trans_le h₂⟩) (λ hx, ⟨h₁.trans hx.1, hx.2⟩)) Ico_subset_Ico_union_Ico lemma Ico_union_Ico' (h₁ : c ≤ b) (h₂ : a ≤ d) : Ico a b ∪ Ico c d = Ico (min a c) (max b d) := begin ext1 x, simp_rw [mem_union, mem_Ico, min_le_iff, lt_max_iff], by_cases hc : c ≤ x; by_cases hd : x < d, { tauto }, { have hax : a ≤ x := h₂.trans (le_of_not_gt hd), tauto }, { have hxb : x < b := (lt_of_not_ge hc).trans_le h₁, tauto }, { tauto }, end lemma Ico_union_Ico (h₁ : min a b ≤ max c d) (h₂ : min c d ≤ max a b) : Ico a b ∪ Ico c d = Ico (min a c) (max b d) := begin cases le_total a b with hab hab; cases le_total c d with hcd hcd; simp [hab, hcd] at h₁ h₂, { exact Ico_union_Ico' h₂ h₁ }, all_goals { simp [*] }, end lemma Icc_subset_Ico_union_Icc : Icc a c ⊆ Ico a b ∪ Icc b c := λ x hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Ico_union_Icc_eq_Icc (h₁ : a ≤ b) (h₂ : b ≤ c) : Ico a b ∪ Icc b c = Icc a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, hx.2.le.trans h₂⟩) (λ hx, ⟨h₁.trans hx.1, hx.2⟩)) Icc_subset_Ico_union_Icc lemma Ioc_subset_Ioo_union_Icc : Ioc a c ⊆ Ioo a b ∪ Icc b c := λ x hx, (lt_or_le x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Ioo_union_Icc_eq_Ioc (h₁ : a < b) (h₂ : b ≤ c) : Ioo a b ∪ Icc b c = Ioc a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, hx.2.le.trans h₂⟩) (λ hx, ⟨h₁.trans_le hx.1, hx.2⟩)) Ioc_subset_Ioo_union_Icc /-! #### Two finite intervals, `I?c` and `Io?` -/ lemma Ioo_subset_Ioc_union_Ioo : Ioo a c ⊆ Ioc a b ∪ Ioo b c := λ x hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Ioc_union_Ioo_eq_Ioo (h₁ : a ≤ b) (h₂ : b < c) : Ioc a b ∪ Ioo b c = Ioo a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, hx.2.trans_lt h₂⟩) (λ hx, ⟨h₁.trans_lt hx.1, hx.2⟩)) Ioo_subset_Ioc_union_Ioo lemma Ico_subset_Icc_union_Ioo : Ico a c ⊆ Icc a b ∪ Ioo b c := λ x hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Icc_union_Ioo_eq_Ico (h₁ : a ≤ b) (h₂ : b < c) : Icc a b ∪ Ioo b c = Ico a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, hx.2.trans_lt h₂⟩) (λ hx, ⟨h₁.trans hx.1.le, hx.2⟩)) Ico_subset_Icc_union_Ioo lemma Icc_subset_Icc_union_Ioc : Icc a c ⊆ Icc a b ∪ Ioc b c := λ x hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Icc_union_Ioc_eq_Icc (h₁ : a ≤ b) (h₂ : b ≤ c) : Icc a b ∪ Ioc b c = Icc a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, hx.2.trans h₂⟩) (λ hx, ⟨h₁.trans hx.1.le, hx.2⟩)) Icc_subset_Icc_union_Ioc lemma Ioc_subset_Ioc_union_Ioc : Ioc a c ⊆ Ioc a b ∪ Ioc b c := λ x hx, (le_or_lt x b).elim (λ hxb, or.inl ⟨hx.1, hxb⟩) (λ hxb, or.inr ⟨hxb, hx.2⟩) @[simp] lemma Ioc_union_Ioc_eq_Ioc (h₁ : a ≤ b) (h₂ : b ≤ c) : Ioc a b ∪ Ioc b c = Ioc a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, hx.2.trans h₂⟩) (λ hx, ⟨h₁.trans_lt hx.1, hx.2⟩)) Ioc_subset_Ioc_union_Ioc lemma Ioc_union_Ioc' (h₁ : c ≤ b) (h₂ : a ≤ d) : Ioc a b ∪ Ioc c d = Ioc (min a c) (max b d) := begin ext1 x, simp_rw [mem_union, mem_Ioc, min_lt_iff, le_max_iff], by_cases hc : c < x; by_cases hd : x ≤ d, { tauto }, { have hax : a < x := h₂.trans_lt (lt_of_not_ge hd), tauto }, { have hxb : x ≤ b := (le_of_not_gt hc).trans h₁, tauto }, { tauto }, end lemma Ioc_union_Ioc (h₁ : min a b ≤ max c d) (h₂ : min c d ≤ max a b) : Ioc a b ∪ Ioc c d = Ioc (min a c) (max b d) := begin cases le_total a b with hab hab; cases le_total c d with hcd hcd; simp [hab, hcd] at h₁ h₂, { exact Ioc_union_Ioc' h₂ h₁ }, all_goals { simp [*] }, end /-! #### Two finite intervals with a common point -/ lemma Ioo_subset_Ioc_union_Ico : Ioo a c ⊆ Ioc a b ∪ Ico b c := subset.trans Ioo_subset_Ioc_union_Ioo (union_subset_union_right _ Ioo_subset_Ico_self) @[simp] lemma Ioc_union_Ico_eq_Ioo (h₁ : a < b) (h₂ : b < c) : Ioc a b ∪ Ico b c = Ioo a c := subset.antisymm (λ x hx, hx.elim (λ hx', ⟨hx'.1, hx'.2.trans_lt h₂⟩) (λ hx', ⟨h₁.trans_le hx'.1, hx'.2⟩)) Ioo_subset_Ioc_union_Ico lemma Ico_subset_Icc_union_Ico : Ico a c ⊆ Icc a b ∪ Ico b c := subset.trans Ico_subset_Icc_union_Ioo (union_subset_union_right _ Ioo_subset_Ico_self) @[simp] lemma Icc_union_Ico_eq_Ico (h₁ : a ≤ b) (h₂ : b < c) : Icc a b ∪ Ico b c = Ico a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, hx.2.trans_lt h₂⟩) (λ hx, ⟨h₁.trans hx.1, hx.2⟩)) Ico_subset_Icc_union_Ico lemma Icc_subset_Icc_union_Icc : Icc a c ⊆ Icc a b ∪ Icc b c := subset.trans Icc_subset_Icc_union_Ioc (union_subset_union_right _ Ioc_subset_Icc_self) @[simp] lemma Icc_union_Icc_eq_Icc (h₁ : a ≤ b) (h₂ : b ≤ c) : Icc a b ∪ Icc b c = Icc a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, hx.2.trans h₂⟩) (λ hx, ⟨h₁.trans hx.1, hx.2⟩)) Icc_subset_Icc_union_Icc lemma Icc_union_Icc' (h₁ : c ≤ b) (h₂ : a ≤ d) : Icc a b ∪ Icc c d = Icc (min a c) (max b d) := begin ext1 x, simp_rw [mem_union, mem_Icc, min_le_iff, le_max_iff], by_cases hc : c ≤ x; by_cases hd : x ≤ d, { tauto }, { have hax : a ≤ x := h₂.trans (le_of_not_ge hd), tauto }, { have hxb : x ≤ b := (le_of_not_ge hc).trans h₁, tauto }, { tauto } end /-- We cannot replace `<` by `≤` in the hypotheses. Otherwise for `b < a = d < c` the l.h.s. is `∅` and the r.h.s. is `{a}`. -/ lemma Icc_union_Icc (h₁ : min a b < max c d) (h₂ : min c d < max a b) : Icc a b ∪ Icc c d = Icc (min a c) (max b d) := begin cases le_or_lt a b with hab hab; cases le_or_lt c d with hcd hcd; simp only [min_eq_left, min_eq_right, max_eq_left, max_eq_right, min_eq_left_of_lt, min_eq_right_of_lt, max_eq_left_of_lt, max_eq_right_of_lt, hab, hcd] at h₁ h₂, { exact Icc_union_Icc' h₂.le h₁.le }, all_goals { simp [*, min_eq_left_of_lt, max_eq_left_of_lt, min_eq_right_of_lt, max_eq_right_of_lt] }, end lemma Ioc_subset_Ioc_union_Icc : Ioc a c ⊆ Ioc a b ∪ Icc b c := subset.trans Ioc_subset_Ioc_union_Ioc (union_subset_union_right _ Ioc_subset_Icc_self) @[simp] lemma Ioc_union_Icc_eq_Ioc (h₁ : a < b) (h₂ : b ≤ c) : Ioc a b ∪ Icc b c = Ioc a c := subset.antisymm (λ x hx, hx.elim (λ hx, ⟨hx.1, hx.2.trans h₂⟩) (λ hx, ⟨h₁.trans_le hx.1, hx.2⟩)) Ioc_subset_Ioc_union_Icc lemma Ioo_union_Ioo' (h₁ : c < b) (h₂ : a < d) : Ioo a b ∪ Ioo c d = Ioo (min a c) (max b d) := begin ext1 x, simp_rw [mem_union, mem_Ioo, min_lt_iff, lt_max_iff], by_cases hc : c < x; by_cases hd : x < d, { tauto }, { have hax : a < x := h₂.trans_le (le_of_not_lt hd), tauto }, { have hxb : x < b := (le_of_not_lt hc).trans_lt h₁, tauto }, { tauto } end lemma Ioo_union_Ioo (h₁ : min a b < max c d) (h₂ : min c d < max a b) : Ioo a b ∪ Ioo c d = Ioo (min a c) (max b d) := begin cases le_total a b with hab hab; cases le_total c d with hcd hcd; simp only [min_eq_left, min_eq_right, max_eq_left, max_eq_right, hab, hcd] at h₁ h₂, { exact Ioo_union_Ioo' h₂ h₁ }, all_goals { simp [*, min_eq_left_of_lt, min_eq_right_of_lt, max_eq_left_of_lt, max_eq_right_of_lt, le_of_lt h₂, le_of_lt h₁] }, end end linear_order section lattice section inf variables [semilattice_inf α] @[simp] lemma Iic_inter_Iic {a b : α} : Iic a ∩ Iic b = Iic (a ⊓ b) := by { ext x, simp [Iic] } @[simp] lemma Ioc_inter_Iic (a b c : α) : Ioc a b ∩ Iic c = Ioc a (b ⊓ c) := by rw [← Ioi_inter_Iic, ← Ioi_inter_Iic, inter_assoc, Iic_inter_Iic] end inf section sup variables [semilattice_sup α] @[simp] lemma Ici_inter_Ici {a b : α} : Ici a ∩ Ici b = Ici (a ⊔ b) := by { ext x, simp [Ici] } @[simp] lemma Ico_inter_Ici (a b c : α) : Ico a b ∩ Ici c = Ico (a ⊔ c) b := by rw [← Ici_inter_Iio, ← Ici_inter_Iio, ← Ici_inter_Ici, inter_right_comm] end sup section both variables [lattice α] {a b c a₁ a₂ b₁ b₂ : α} lemma Icc_inter_Icc : Icc a₁ b₁ ∩ Icc a₂ b₂ = Icc (a₁ ⊔ a₂) (b₁ ⊓ b₂) := by simp only [Ici_inter_Iic.symm, Ici_inter_Ici.symm, Iic_inter_Iic.symm]; ac_refl @[simp] lemma Icc_inter_Icc_eq_singleton (hab : a ≤ b) (hbc : b ≤ c) : Icc a b ∩ Icc b c = {b} := by rw [Icc_inter_Icc, sup_of_le_right hab, inf_of_le_left hbc, Icc_self] end both end lattice section linear_order variables [linear_order α] {a a₁ a₂ b b₁ b₂ c d : α} @[simp] lemma Ioi_inter_Ioi : Ioi a ∩ Ioi b = Ioi (a ⊔ b) := ext $ λ _, sup_lt_iff.symm @[simp] lemma Iio_inter_Iio : Iio a ∩ Iio b = Iio (a ⊓ b) := ext $ λ _, lt_inf_iff.symm lemma Ico_inter_Ico : Ico a₁ b₁ ∩ Ico a₂ b₂ = Ico (a₁ ⊔ a₂) (b₁ ⊓ b₂) := by simp only [Ici_inter_Iio.symm, Ici_inter_Ici.symm, Iio_inter_Iio.symm]; ac_refl lemma Ioc_inter_Ioc : Ioc a₁ b₁ ∩ Ioc a₂ b₂ = Ioc (a₁ ⊔ a₂) (b₁ ⊓ b₂) := by simp only [Ioi_inter_Iic.symm, Ioi_inter_Ioi.symm, Iic_inter_Iic.symm]; ac_refl lemma Ioo_inter_Ioo : Ioo a₁ b₁ ∩ Ioo a₂ b₂ = Ioo (a₁ ⊔ a₂) (b₁ ⊓ b₂) := by simp only [Ioi_inter_Iio.symm, Ioi_inter_Ioi.symm, Iio_inter_Iio.symm]; ac_refl lemma Ioc_inter_Ioo_of_left_lt (h : b₁ < b₂) : Ioc a₁ b₁ ∩ Ioo a₂ b₂ = Ioc (max a₁ a₂) b₁ := ext $ λ x, by simp [and_assoc, @and.left_comm (x ≤ _), and_iff_left_iff_imp.2 (λ h', lt_of_le_of_lt h' h)] lemma Ioc_inter_Ioo_of_right_le (h : b₂ ≤ b₁) : Ioc a₁ b₁ ∩ Ioo a₂ b₂ = Ioo (max a₁ a₂) b₂ := ext $ λ x, by simp [and_assoc, @and.left_comm (x ≤ _), and_iff_right_iff_imp.2 (λ h', ((le_of_lt h').trans h))] lemma Ioo_inter_Ioc_of_left_le (h : b₁ ≤ b₂) : Ioo a₁ b₁ ∩ Ioc a₂ b₂ = Ioo (max a₁ a₂) b₁ := by rw [inter_comm, Ioc_inter_Ioo_of_right_le h, max_comm] lemma Ioo_inter_Ioc_of_right_lt (h : b₂ < b₁) : Ioo a₁ b₁ ∩ Ioc a₂ b₂ = Ioc (max a₁ a₂) b₂ := by rw [inter_comm, Ioc_inter_Ioo_of_left_lt h, max_comm] @[simp] lemma Ico_diff_Iio : Ico a b \ Iio c = Ico (max a c) b := by rw [diff_eq, compl_Iio, Ico_inter_Ici, sup_eq_max] @[simp] lemma Ioc_diff_Ioi : Ioc a b \ Ioi c = Ioc a (min b c) := ext $ by simp [iff_def] {contextual:=tt} @[simp] lemma Ioc_inter_Ioi : Ioc a b ∩ Ioi c = Ioc (a ⊔ c) b := by rw [← Ioi_inter_Iic, inter_assoc, inter_comm, inter_assoc, Ioi_inter_Ioi, inter_comm, Ioi_inter_Iic, sup_comm] @[simp] lemma Ico_inter_Iio : Ico a b ∩ Iio c = Ico a (min b c) := ext $ by simp [iff_def] {contextual:=tt} @[simp] lemma Ioc_diff_Iic : Ioc a b \ Iic c = Ioc (max a c) b := by rw [diff_eq, compl_Iic, Ioc_inter_Ioi, sup_eq_max] @[simp] lemma Ioc_union_Ioc_right : Ioc a b ∪ Ioc a c = Ioc a (max b c) := by rw [Ioc_union_Ioc, min_self]; exact (min_le_left _ _).trans (le_max_left _ _) @[simp] lemma Ioc_union_Ioc_left : Ioc a c ∪ Ioc b c = Ioc (min a b) c := by rw [Ioc_union_Ioc, max_self]; exact (min_le_right _ _).trans (le_max_right _ _) @[simp] lemma Ioc_union_Ioc_symm : Ioc a b ∪ Ioc b a = Ioc (min a b) (max a b) := by { rw max_comm, apply Ioc_union_Ioc; rw max_comm; exact min_le_max } @[simp] lemma Ioc_union_Ioc_union_Ioc_cycle : Ioc a b ∪ Ioc b c ∪ Ioc c a = Ioc (min a (min b c)) (max a (max b c)) := begin rw [Ioc_union_Ioc, Ioc_union_Ioc], ac_refl, all_goals { solve_by_elim [min_le_of_left_le, min_le_of_right_le, le_max_of_le_left, le_max_of_le_right, le_refl] { max_depth := 5 }} end end linear_order /-! ### Closed intervals in `α × β` -/ section prod variables [preorder α] [preorder β] @[simp] lemma Iic_prod_Iic (a : α) (b : β) : Iic a ×ˢ Iic b = Iic (a, b) := rfl @[simp] lemma Ici_prod_Ici (a : α) (b : β) : Ici a ×ˢ Ici b = Ici (a, b) := rfl lemma Ici_prod_eq (a : α × β) : Ici a = Ici a.1 ×ˢ Ici a.2 := rfl lemma Iic_prod_eq (a : α × β) : Iic a = Iic a.1 ×ˢ Iic a.2 := rfl @[simp] lemma Icc_prod_Icc (a₁ a₂ : α) (b₁ b₂ : β) : Icc a₁ a₂ ×ˢ Icc b₁ b₂ = Icc (a₁, b₁) (a₂, b₂) := by { ext ⟨x, y⟩, simp [and.assoc, and_comm, and.left_comm] } lemma Icc_prod_eq (a b : α × β) : Icc a b = Icc a.1 b.1 ×ˢ Icc a.2 b.2 := by simp end prod /-! ### Lemmas about membership of arithmetic operations -/ section ordered_comm_group variables [ordered_comm_group α] {a b c d : α} /-! `inv_mem_Ixx_iff`, `sub_mem_Ixx_iff` -/ @[to_additive] lemma inv_mem_Icc_iff : a⁻¹ ∈ set.Icc c d ↔ a ∈ set.Icc (d⁻¹) (c⁻¹) := (and_comm _ _).trans $ and_congr inv_le' le_inv' @[to_additive] lemma inv_mem_Ico_iff : a⁻¹ ∈ set.Ico c d ↔ a ∈ set.Ioc (d⁻¹) (c⁻¹) := (and_comm _ _).trans $ and_congr inv_lt' le_inv' @[to_additive] lemma inv_mem_Ioc_iff : a⁻¹ ∈ set.Ioc c d ↔ a ∈ set.Ico (d⁻¹) (c⁻¹) := (and_comm _ _).trans $ and_congr inv_le' lt_inv' @[to_additive] lemma inv_mem_Ioo_iff : a⁻¹ ∈ set.Ioo c d ↔ a ∈ set.Ioo (d⁻¹) (c⁻¹) := (and_comm _ _).trans $ and_congr inv_lt' lt_inv' end ordered_comm_group section ordered_add_comm_group variables [ordered_add_comm_group α] {a b c d : α} /-! `add_mem_Ixx_iff_left` -/ lemma add_mem_Icc_iff_left : a + b ∈ set.Icc c d ↔ a ∈ set.Icc (c - b) (d - b) := (and_congr sub_le_iff_le_add le_sub_iff_add_le).symm lemma add_mem_Ico_iff_left : a + b ∈ set.Ico c d ↔ a ∈ set.Ico (c - b) (d - b) := (and_congr sub_le_iff_le_add lt_sub_iff_add_lt).symm lemma add_mem_Ioc_iff_left : a + b ∈ set.Ioc c d ↔ a ∈ set.Ioc (c - b) (d - b) := (and_congr sub_lt_iff_lt_add le_sub_iff_add_le).symm lemma add_mem_Ioo_iff_left : a + b ∈ set.Ioo c d ↔ a ∈ set.Ioo (c - b) (d - b) := (and_congr sub_lt_iff_lt_add lt_sub_iff_add_lt).symm /-! `add_mem_Ixx_iff_right` -/ lemma add_mem_Icc_iff_right : a + b ∈ set.Icc c d ↔ b ∈ set.Icc (c - a) (d - a) := (and_congr sub_le_iff_le_add' le_sub_iff_add_le').symm lemma add_mem_Ico_iff_right : a + b ∈ set.Ico c d ↔ b ∈ set.Ico (c - a) (d - a) := (and_congr sub_le_iff_le_add' lt_sub_iff_add_lt').symm lemma add_mem_Ioc_iff_right : a + b ∈ set.Ioc c d ↔ b ∈ set.Ioc (c - a) (d - a) := (and_congr sub_lt_iff_lt_add' le_sub_iff_add_le').symm lemma add_mem_Ioo_iff_right : a + b ∈ set.Ioo c d ↔ b ∈ set.Ioo (c - a) (d - a) := (and_congr sub_lt_iff_lt_add' lt_sub_iff_add_lt').symm /-! `sub_mem_Ixx_iff_left` -/ lemma sub_mem_Icc_iff_left : a - b ∈ set.Icc c d ↔ a ∈ set.Icc (c + b) (d + b) := and_congr le_sub_iff_add_le sub_le_iff_le_add lemma sub_mem_Ico_iff_left : a - b ∈ set.Ico c d ↔ a ∈ set.Ico (c + b) (d + b) := and_congr le_sub_iff_add_le sub_lt_iff_lt_add lemma sub_mem_Ioc_iff_left : a - b ∈ set.Ioc c d ↔ a ∈ set.Ioc (c + b) (d + b) := and_congr lt_sub_iff_add_lt sub_le_iff_le_add lemma sub_mem_Ioo_iff_left : a - b ∈ set.Ioo c d ↔ a ∈ set.Ioo (c + b) (d + b) := and_congr lt_sub_iff_add_lt sub_lt_iff_lt_add /-! `sub_mem_Ixx_iff_right` -/ lemma sub_mem_Icc_iff_right : a - b ∈ set.Icc c d ↔ b ∈ set.Icc (a - d) (a - c) := (and_comm _ _).trans $ and_congr sub_le le_sub lemma sub_mem_Ico_iff_right : a - b ∈ set.Ico c d ↔ b ∈ set.Ioc (a - d) (a - c) := (and_comm _ _).trans $ and_congr sub_lt le_sub lemma sub_mem_Ioc_iff_right : a - b ∈ set.Ioc c d ↔ b ∈ set.Ico (a - d) (a - c) := (and_comm _ _).trans $ and_congr sub_le lt_sub lemma sub_mem_Ioo_iff_right : a - b ∈ set.Ioo c d ↔ b ∈ set.Ioo (a - d) (a - c) := (and_comm _ _).trans $ and_congr sub_lt lt_sub -- I think that symmetric intervals deserve attention and API: they arise all the time, -- for instance when considering metric balls in `ℝ`. lemma mem_Icc_iff_abs_le {R : Type*} [linear_ordered_add_comm_group R] {x y z : R} : |x - y| ≤ z ↔ y ∈ Icc (x - z) (x + z) := abs_le.trans $ (and_comm _ _).trans $ and_congr sub_le neg_le_sub_iff_le_add end ordered_add_comm_group section linear_ordered_add_comm_group variables [linear_ordered_add_comm_group α] /-- If we remove a smaller interval from a larger, the result is nonempty -/ lemma nonempty_Ico_sdiff {x dx y dy : α} (h : dy < dx) (hx : 0 < dx) : nonempty ↥(Ico x (x + dx) \ Ico y (y + dy)) := begin cases lt_or_le x y with h' h', { use x, simp [*, not_le.2 h'] }, { use max x (x + dy), simp [*, le_refl] } end end linear_ordered_add_comm_group end set open set namespace order_iso section preorder variables [preorder α] [preorder β] @[simp] lemma preimage_Iic (e : α ≃o β) (b : β) : e ⁻¹' (Iic b) = Iic (e.symm b) := by { ext x, simp [← e.le_iff_le] } @[simp] lemma preimage_Ici (e : α ≃o β) (b : β) : e ⁻¹' (Ici b) = Ici (e.symm b) := by { ext x, simp [← e.le_iff_le] } @[simp] lemma preimage_Iio (e : α ≃o β) (b : β) : e ⁻¹' (Iio b) = Iio (e.symm b) := by { ext x, simp [← e.lt_iff_lt] } @[simp] lemma preimage_Ioi (e : α ≃o β) (b : β) : e ⁻¹' (Ioi b) = Ioi (e.symm b) := by { ext x, simp [← e.lt_iff_lt] } @[simp] lemma preimage_Icc (e : α ≃o β) (a b : β) : e ⁻¹' (Icc a b) = Icc (e.symm a) (e.symm b) := by simp [← Ici_inter_Iic] @[simp] lemma preimage_Ico (e : α ≃o β) (a b : β) : e ⁻¹' (Ico a b) = Ico (e.symm a) (e.symm b) := by simp [← Ici_inter_Iio] @[simp] lemma preimage_Ioc (e : α ≃o β) (a b : β) : e ⁻¹' (Ioc a b) = Ioc (e.symm a) (e.symm b) := by simp [← Ioi_inter_Iic] @[simp] lemma preimage_Ioo (e : α ≃o β) (a b : β) : e ⁻¹' (Ioo a b) = Ioo (e.symm a) (e.symm b) := by simp [← Ioi_inter_Iio] @[simp] lemma image_Iic (e : α ≃o β) (a : α) : e '' (Iic a) = Iic (e a) := by rw [e.image_eq_preimage, e.symm.preimage_Iic, e.symm_symm] @[simp] lemma image_Ici (e : α ≃o β) (a : α) : e '' (Ici a) = Ici (e a) := e.dual.image_Iic a @[simp] lemma image_Iio (e : α ≃o β) (a : α) : e '' (Iio a) = Iio (e a) := by rw [e.image_eq_preimage, e.symm.preimage_Iio, e.symm_symm] @[simp] lemma image_Ioi (e : α ≃o β) (a : α) : e '' (Ioi a) = Ioi (e a) := e.dual.image_Iio a @[simp] lemma image_Ioo (e : α ≃o β) (a b : α) : e '' (Ioo a b) = Ioo (e a) (e b) := by rw [e.image_eq_preimage, e.symm.preimage_Ioo, e.symm_symm] @[simp] lemma image_Ioc (e : α ≃o β) (a b : α) : e '' (Ioc a b) = Ioc (e a) (e b) := by rw [e.image_eq_preimage, e.symm.preimage_Ioc, e.symm_symm] @[simp] lemma image_Ico (e : α ≃o β) (a b : α) : e '' (Ico a b) = Ico (e a) (e b) := by rw [e.image_eq_preimage, e.symm.preimage_Ico, e.symm_symm] @[simp] lemma image_Icc (e : α ≃o β) (a b : α) : e '' (Icc a b) = Icc (e a) (e b) := by rw [e.image_eq_preimage, e.symm.preimage_Icc, e.symm_symm] end preorder /-- Order isomorphism between `Iic (⊤ : α)` and `α` when `α` has a top element -/ def Iic_top [preorder α] [order_top α] : set.Iic (⊤ : α) ≃o α := { map_rel_iff' := λ x y, by refl, .. (@equiv.subtype_univ_equiv α (set.Iic (⊤ : α)) (λ x, le_top)), } /-- Order isomorphism between `Ici (⊥ : α)` and `α` when `α` has a bottom element -/ def Ici_bot [preorder α] [order_bot α] : set.Ici (⊥ : α) ≃o α := { map_rel_iff' := λ x y, by refl, .. (@equiv.subtype_univ_equiv α (set.Ici (⊥ : α)) (λ x, bot_le)) } end order_iso /-! ### Lemmas about intervals in dense orders -/ section dense variables (α) [preorder α] [densely_ordered α] {x y : α} instance : no_min_order (set.Ioo x y) := ⟨λ ⟨a, ha₁, ha₂⟩, begin rcases exists_between ha₁ with ⟨b, hb₁, hb₂⟩, exact ⟨⟨b, hb₁, hb₂.trans ha₂⟩, hb₂⟩ end⟩ instance : no_min_order (set.Ioc x y) := ⟨λ ⟨a, ha₁, ha₂⟩, begin rcases exists_between ha₁ with ⟨b, hb₁, hb₂⟩, exact ⟨⟨b, hb₁, hb₂.le.trans ha₂⟩, hb₂⟩ end⟩ instance : no_min_order (set.Ioi x) := ⟨λ ⟨a, ha⟩, begin rcases exists_between ha with ⟨b, hb₁, hb₂⟩, exact ⟨⟨b, hb₁⟩, hb₂⟩ end⟩ instance : no_max_order (set.Ioo x y) := ⟨λ ⟨a, ha₁, ha₂⟩, begin rcases exists_between ha₂ with ⟨b, hb₁, hb₂⟩, exact ⟨⟨b, ha₁.trans hb₁, hb₂⟩, hb₁⟩ end⟩ instance : no_max_order (set.Ico x y) := ⟨λ ⟨a, ha₁, ha₂⟩, begin rcases exists_between ha₂ with ⟨b, hb₁, hb₂⟩, exact ⟨⟨b, ha₁.trans hb₁.le, hb₂⟩, hb₁⟩ end⟩ instance : no_max_order (set.Iio x) := ⟨λ ⟨a, ha⟩, begin rcases exists_between ha with ⟨b, hb₁, hb₂⟩, exact ⟨⟨b, hb₂⟩, hb₁⟩ end⟩ end dense
d543d1e6e46cdea5679d5209e9fff473d861d958
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/algebra/graded_monoid.lean
17cc1345ad14c889abedf2a8fcfecf91c42e196f
[ "Apache-2.0" ]
permissive
ayush1801/mathlib
78949b9f789f488148142221606bf15c02b960d2
ce164e28f262acbb3de6281b3b03660a9f744e3c
refs/heads/master
1,692,886,907,941
1,635,270,866,000
1,635,270,866,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
12,401
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 algebra.group.inj_surj import algebra.group_power.basic import data.set_like.basic import data.sigma.basic import group_theory.group_action.defs /-! # Additively-graded multiplicative structures This module provides a set of heterogeneous typeclasses for defining a multiplicative structure over the sigma type `graded_monoid A` such that `(*) : A i → A j → A (i + j)`; that is to say, `A` forms an additively-graded monoid. The typeclasses are: * `graded_monoid.ghas_one A` * `graded_monoid.ghas_mul A` * `graded_monoid.gmonoid A` * `graded_monoid.gcomm_monoid A` With the `sigma_graded` locale open, these respectively imbue: * `has_one (graded_monoid A)` * `has_mul (graded_monoid A)` * `monoid (graded_monoid A)` * `comm_monoid (graded_monoid A)` the base type `A 0` with: * `graded_monoid.grade_zero.has_one` * `graded_monoid.grade_zero.has_mul` * `graded_monoid.grade_zero.monoid` * `graded_monoid.grade_zero.comm_monoid` and the `i`th grade `A i` with `A 0`-actions (`•`) defined as left-multiplication: * (nothing) * `graded_monoid.grade_zero.has_scalar (A 0)` * `graded_monoid.grade_zero.mul_action (A 0)` * (nothing) For now, these typeclasses are primarily used in the construction of `direct_sum.ring` and the rest of that file. ## Indexed subobjects Additionally, this module provides helper functions to construct `gmonoid` and `gcomm_monoid` instances for collections of subobjects: * `ghas_one.of_add_subobjects` * `ghas_mul.of_add_subobjects` * `gmonoid.of_add_subobjects` * `gcomm_monoid.of_add_subobjects` ## tags graded monoid -/ set_option old_structure_cmd true variables {ι : Type*} /-- A type alias of sigma types for graded monoids. -/ def graded_monoid (A : ι → Type*) := sigma A namespace graded_monoid instance {A : ι → Type*} [inhabited ι] [inhabited (A (default ι))]: inhabited (graded_monoid A) := sigma.inhabited /-- Construct an element of a graded monoid. -/ def mk {A : ι → Type*} : Π i, A i → graded_monoid A := sigma.mk /-! ### Typeclasses -/ section defs variables (A : ι → Type*) /-- A graded version of `has_one`, which must be of grade 0. -/ class ghas_one [has_zero ι] := (one : A 0) /-- `ghas_one` implies `has_one (graded_monoid A)` -/ instance ghas_one.to_has_one [has_zero ι] [ghas_one A] : has_one (graded_monoid A) := ⟨⟨_, ghas_one.one⟩⟩ /-- A graded version of `has_mul`. Multiplication combines grades additively, like `add_monoid_algebra`. -/ class ghas_mul [has_add ι] := (mul {i j} : A i → A j → A (i + j)) /-- `ghas_mul` implies `has_mul (graded_monoid A)`. -/ instance ghas_mul.to_has_mul [has_add ι] [ghas_mul A] : has_mul (graded_monoid A) := ⟨λ (x y : graded_monoid A), ⟨_, ghas_mul.mul x.snd y.snd⟩⟩ lemma mk_mul_mk [has_add ι] [ghas_mul A] {i j} (a : A i) (b : A j) : mk i a * mk j b = mk (i + j) (ghas_mul.mul a b) := rfl namespace gmonoid variables {A} [add_monoid ι] [ghas_mul A] [ghas_one A] /-- A default implementation of power on a graded monoid, like `npow_rec`. `gmonoid.gnpow` should be used instead. -/ def gnpow_rec : Π (n : ℕ) {i}, A i → A (n • i) | 0 i a := cast (congr_arg A (zero_nsmul i).symm) ghas_one.one | (n + 1) i a := cast (congr_arg A (succ_nsmul i n).symm) (ghas_mul.mul a $ gnpow_rec _ a) @[simp] lemma gnpow_rec_zero (a : graded_monoid A) : graded_monoid.mk _ (gnpow_rec 0 a.snd) = 1 := sigma.ext (zero_nsmul _) (heq_of_cast_eq _ rfl).symm /-- Tactic used to autofill `graded_monoid.gmonoid.gnpow_zero'` when the default `graded_monoid.gmonoid.gnpow_rec` is used. -/ meta def apply_gnpow_rec_zero_tac : tactic unit := `[apply direct_sum.gmonoid.gnpow_rec_zero] @[simp] lemma gnpow_rec_succ (n : ℕ) (a : graded_monoid A) : (graded_monoid.mk _ $ gnpow_rec n.succ a.snd) = a * ⟨_, gnpow_rec n a.snd⟩ := sigma.ext (succ_nsmul _ _) (heq_of_cast_eq _ rfl).symm /-- Tactic used to autofill `graded_monoid.gmonoid.gnpow_succ'` when the default `graded_monoid.gmonoid.gnpow_rec` is used. -/ meta def apply_gnpow_rec_succ_tac : tactic unit := `[apply direct_sum.gmonoid.gnpow_rec_succ] end gmonoid /-- A graded version of `monoid`. Like `monoid.npow`, this has an optional `gmonoid.gnpow` field to allow definitional control of natural powers of a graded monoid. -/ class gmonoid [add_monoid ι] extends ghas_mul A, ghas_one A := (one_mul (a : graded_monoid A) : 1 * a = a) (mul_one (a : graded_monoid A) : a * 1 = a) (mul_assoc (a b c : graded_monoid A) : a * b * c = a * (b * c)) (gnpow : Π (n : ℕ) {i}, A i → A (n • i) := gmonoid.gnpow_rec) (gnpow_zero' : Π (a : graded_monoid A), graded_monoid.mk _ (gnpow 0 a.snd) = 1 . gmonoid.apply_gnpow_rec_zero_tac) (gnpow_succ' : Π (n : ℕ) (a : graded_monoid A), (graded_monoid.mk _ $ gnpow n.succ a.snd) = a * ⟨_, gnpow n a.snd⟩ . gmonoid.apply_gnpow_rec_succ_tac) /-- `gmonoid` implies a `monoid (graded_monoid A)`. -/ instance gmonoid.to_monoid [add_monoid ι] [gmonoid A] : monoid (graded_monoid A) := { one := (1), mul := (*), npow := λ n a, graded_monoid.mk _ (gmonoid.gnpow n a.snd), npow_zero' := λ a, gmonoid.gnpow_zero' a, npow_succ' := λ n a, gmonoid.gnpow_succ' n a, one_mul := gmonoid.one_mul, mul_one := gmonoid.mul_one, mul_assoc := gmonoid.mul_assoc } lemma mk_pow [add_monoid ι] [gmonoid A] {i} (a : A i) (n : ℕ) : mk i a ^ n = mk (n • i) (gmonoid.gnpow _ a) := begin induction n with n, { rw [pow_zero], exact (gmonoid.gnpow_zero' ⟨_, a⟩).symm, }, { rw [pow_succ, n_ih, mk_mul_mk], exact (gmonoid.gnpow_succ' n ⟨_, a⟩).symm, }, end /-- A graded version of `comm_monoid`. -/ class gcomm_monoid [add_comm_monoid ι] extends gmonoid A := (mul_comm (a : graded_monoid A) (b : graded_monoid A) : a * b = b * a) /-- `gcomm_monoid` implies a `comm_monoid (graded_monoid A)`, although this is only used as an instance locally to define notation in `gmonoid` and similar typeclasses. -/ instance gcomm_monoid.to_comm_monoid [add_comm_monoid ι] [gcomm_monoid A] : comm_monoid (graded_monoid A) := { mul_comm := gcomm_monoid.mul_comm, ..gmonoid.to_monoid A } end defs /-! ### Instances for `A 0` The various `g*` instances are enough to promote the `add_comm_monoid (A 0)` structure to various types of multiplicative structure. -/ section grade_zero variables (A : ι → Type*) section one variables [has_zero ι] [ghas_one A] /-- `1 : A 0` is the value provided in `ghas_one.one`. -/ @[nolint unused_arguments] instance grade_zero.has_one : has_one (A 0) := ⟨ghas_one.one⟩ end one section mul variables [add_monoid ι] [ghas_mul A] /-- `(•) : A 0 → A i → A i` is the value provided in `direct_sum.ghas_mul.mul`, composed with an `eq.rec` to turn `A (0 + i)` into `A i`. -/ instance grade_zero.has_scalar (i : ι) : has_scalar (A 0) (A i) := { smul := λ x y, (zero_add i).rec (ghas_mul.mul x y) } /-- `(*) : A 0 → A 0 → A 0` is the value provided in `direct_sum.ghas_mul.mul`, composed with an `eq.rec` to turn `A (0 + 0)` into `A 0`. -/ instance grade_zero.has_mul : has_mul (A 0) := { mul := (•) } variables {A} @[simp] lemma mk_zero_smul {i} (a : A 0) (b : A i) : mk _ (a • b) = mk _ a * mk _ b := sigma.ext (zero_add _).symm $ eq_rec_heq _ _ @[simp] lemma grade_zero.smul_eq_mul (a b : A 0) : a • b = a * b := rfl end mul section monoid variables [add_monoid ι] [gmonoid A] /-- The `monoid` structure derived from `gmonoid A`. -/ instance grade_zero.monoid : monoid (A 0) := function.injective.monoid (mk 0) sigma_mk_injective rfl mk_zero_smul end monoid section monoid variables [add_comm_monoid ι] [gcomm_monoid A] /-- The `comm_monoid` structure derived from `gcomm_monoid A`. -/ instance grade_zero.comm_monoid : comm_monoid (A 0) := function.injective.comm_monoid (mk 0) sigma_mk_injective rfl mk_zero_smul end monoid section mul_action variables [add_monoid ι] [gmonoid A] /-- `graded_monoid.mk 0` is a `monoid_hom`, using the `graded_monoid.grade_zero.monoid` structure. -/ def mk_zero_monoid_hom : A 0 →* (graded_monoid A) := { to_fun := mk 0, map_one' := rfl, map_mul' := mk_zero_smul } /-- Each grade `A i` derives a `A 0`-action structure from `gmonoid A`. -/ instance grade_zero.mul_action {i} : mul_action (A 0) (A i) := begin letI := mul_action.comp_hom (graded_monoid A) (mk_zero_monoid_hom A), exact function.injective.mul_action (mk i) sigma_mk_injective mk_zero_smul, end end mul_action end grade_zero /-! ### Shorthands for creating instance of the above typeclasses for collections of subobjects -/ section subobjects variables {R : Type*} /-- Build a `ghas_one` instance for a collection of subobjects. -/ @[simps one] def ghas_one.of_subobjects {S : Type*} [set_like S R] [has_one R] [has_zero ι] (carriers : ι → S) (one_mem : (1 : R) ∈ carriers 0) : ghas_one (λ i, carriers i) := { one := ⟨1, one_mem⟩ } /-- Build a `ghas_mul` instance for a collection of subobjects. -/ @[simps mul] def ghas_mul.of_subobjects {S : Type*} [set_like S R] [has_mul R] [has_add ι] (carriers : ι → S) (mul_mem : ∀ ⦃i j⦄ (gi : carriers i) (gj : carriers j), (gi * gj : R) ∈ carriers (i + j)) : ghas_mul (λ i, carriers i) := { mul := λ i j a b, ⟨(a * b : R), mul_mem a b⟩ } /-- Build a `gmonoid` instance for a collection of subobjects. See note [reducible non-instances]. -/ @[reducible] def gmonoid.of_subobjects {S : Type*} [set_like S R] [monoid R] [add_monoid ι] (carriers : ι → S) (one_mem : (1 : R) ∈ carriers 0) (mul_mem : ∀ ⦃i j⦄ (gi : carriers i) (gj : carriers j), (gi * gj : R) ∈ carriers (i + j)) : gmonoid (λ i, carriers i) := { one_mul := λ ⟨i, a, h⟩, sigma.subtype_ext (zero_add _) (one_mul _), mul_one := λ ⟨i, a, h⟩, sigma.subtype_ext (add_zero _) (mul_one _), mul_assoc := λ ⟨i, a, ha⟩ ⟨j, b, hb⟩ ⟨k, c, hc⟩, sigma.subtype_ext (add_assoc _ _ _) (mul_assoc _ _ _), gnpow := λ n i a, ⟨a ^ n, begin induction n, { rw [pow_zero, zero_nsmul], exact one_mem }, { rw [pow_succ', succ_nsmul'], exact mul_mem ⟨_, n_ih⟩ a }, end⟩, gnpow_zero' := λ n, sigma.subtype_ext (zero_nsmul _) (pow_zero _), gnpow_succ' := λ n a, sigma.subtype_ext (succ_nsmul _ _) (pow_succ _ _), ..ghas_one.of_subobjects carriers one_mem, ..ghas_mul.of_subobjects carriers mul_mem } /-- Build a `gcomm_monoid` instance for a collection of subobjects. See note [reducible non-instances]. -/ @[reducible] def gcomm_monoid.of_subobjects {S : Type*} [set_like S R] [comm_monoid R] [add_comm_monoid ι] (carriers : ι → S) (one_mem : (1 : R) ∈ carriers 0) (mul_mem : ∀ ⦃i j⦄ (gi : carriers i) (gj : carriers j), (gi * gj : R) ∈ carriers (i + j)) : gcomm_monoid (λ i, carriers i) := { mul_comm := λ ⟨i, a, ha⟩ ⟨j, b, hb⟩, sigma.subtype_ext (add_comm _ _) (mul_comm _ _), ..gmonoid.of_subobjects carriers one_mem mul_mem} end subobjects end graded_monoid /-! ### Concrete instances -/ section variables (ι) {R : Type*} @[simps one] instance has_one.ghas_one [has_zero ι] [has_one R] : graded_monoid.ghas_one (λ i : ι, R) := { one := 1 } @[simps mul] instance has_mul.ghas_mul [has_add ι] [has_mul R] : graded_monoid.ghas_mul (λ i : ι, R) := { mul := λ i j, (*) } /-- If all grades are the same type and themselves form a monoid, then there is a trivial grading structure. -/ @[simps gnpow] instance monoid.gmonoid [add_monoid ι] [monoid R] : graded_monoid.gmonoid (λ i : ι, R) := { one_mul := λ a, sigma.ext (zero_add _) (heq_of_eq (one_mul _)), mul_one := λ a, sigma.ext (add_zero _) (heq_of_eq (mul_one _)), mul_assoc := λ a b c, sigma.ext (add_assoc _ _ _) (heq_of_eq (mul_assoc _ _ _)), gnpow := λ n i a, a ^ n, gnpow_zero' := λ a, sigma.ext (zero_nsmul _) (heq_of_eq (monoid.npow_zero' _)), gnpow_succ' := λ n ⟨i, a⟩, sigma.ext (succ_nsmul _ _) (heq_of_eq (monoid.npow_succ' _ _)), ..has_one.ghas_one ι, ..has_mul.ghas_mul ι } /-- If all grades are the same type and themselves form a commutative monoid, then there is a trivial grading structure. -/ instance comm_monoid.gcomm_monoid [add_comm_monoid ι] [comm_monoid R] : graded_monoid.gcomm_monoid (λ i : ι, R) := { mul_comm := λ a b, sigma.ext (add_comm _ _) (heq_of_eq (mul_comm _ _)), ..monoid.gmonoid ι } end
60b2b767f832d5084b9248757affc76d98db64f9
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Lean/Linter/UnusedVariables.lean
cec35d72bdc94db782df85d4690f3b3cdad86901
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
10,303
lean
import Lean.Elab.Command import Lean.Linter.Util import Lean.Elab.InfoTree import Lean.Server.InfoUtils import Lean.Server.References import Std.Data.HashMap namespace Lean.Linter open Lean.Elab.Command Lean.Server Std register_builtin_option linter.unusedVariables : Bool := { defValue := true, descr := "enable the 'unused variables' linter" } register_builtin_option linter.unusedVariables.funArgs : Bool := { defValue := true, descr := "enable the 'unused variables' linter to mark unused function arguments" } register_builtin_option linter.unusedVariables.patternVars : Bool := { defValue := true, descr := "enable the 'unused variables' linter to mark unused pattern variables" } def getLinterUnusedVariables (o : Options) : Bool := getLinterValue linter.unusedVariables o def getLinterUnusedVariablesFunArgs (o : Options) : Bool := o.get linter.unusedVariables.funArgs.name (getLinterUnusedVariables o) def getLinterUnusedVariablesPatternVars (o : Options) : Bool := o.get linter.unusedVariables.patternVars.name (getLinterUnusedVariables o) builtin_initialize builtinUnusedVariablesIgnoreFnsRef : IO.Ref <| Array IgnoreFunction ← IO.mkRef #[] def addBuiltinUnusedVariablesIgnoreFn (ignoreFn : IgnoreFunction) : IO Unit := do (← builtinUnusedVariablesIgnoreFnsRef.get) |> (·.push ignoreFn) |> builtinUnusedVariablesIgnoreFnsRef.set -- matches builtinUnused variable pattern builtin_initialize addBuiltinUnusedVariablesIgnoreFn (fun stx _ _ => stx.getId.toString.startsWith "_") -- is variable builtin_initialize addBuiltinUnusedVariablesIgnoreFn (fun _ stack _ => stackMatches stack [`null, none, `null, ``Lean.Parser.Command.variable]) -- is in structure builtin_initialize addBuiltinUnusedVariablesIgnoreFn (fun _ stack _ => stackMatches stack [`null, none, `null, ``Lean.Parser.Command.structure]) -- is in inductive builtin_initialize addBuiltinUnusedVariablesIgnoreFn (fun _ stack _ => stackMatches stack [`null, none, `null, none, ``Lean.Parser.Command.inductive] && (stack.get? 3 |>.any fun (stx, pos) => pos == 0 && [``Lean.Parser.Command.optDeclSig, ``Lean.Parser.Command.declSig].any (stx.isOfKind ·))) -- in in constructor or structure binder builtin_initialize addBuiltinUnusedVariablesIgnoreFn (fun _ stack _ => stackMatches stack [`null, none, `null, ``Lean.Parser.Command.optDeclSig, none] && (stack.get? 4 |>.any fun (stx, _) => [``Lean.Parser.Command.ctor, ``Lean.Parser.Command.structSimpleBinder].any (stx.isOfKind ·))) -- is in opaque or axiom builtin_initialize addBuiltinUnusedVariablesIgnoreFn (fun _ stack _ => stackMatches stack [`null, none, `null, ``Lean.Parser.Command.declSig, none] && (stack.get? 4 |>.any fun (stx, _) => [``Lean.Parser.Command.opaque, ``Lean.Parser.Command.axiom].any (stx.isOfKind ·))) -- is in definition with foreign definition builtin_initialize addBuiltinUnusedVariablesIgnoreFn (fun _ stack _ => stackMatches stack [`null, none, `null, none, none, ``Lean.Parser.Command.declaration] && (stack.get? 3 |>.any fun (stx, _) => stx.isOfKind ``Lean.Parser.Command.optDeclSig || stx.isOfKind ``Lean.Parser.Command.declSig) && (stack.get? 5 |>.any fun (stx, _) => match stx[0] with | `(Lean.Parser.Command.declModifiersT| $[$_:docComment]? @[$[$attrs:attr],*] $[$vis]? $[noncomputable]?) => attrs.any (fun attr => attr.raw.isOfKind ``Parser.Attr.extern || attr matches `(attr| implementedBy $_)) | _ => false)) -- is in dependent arrow builtin_initialize addBuiltinUnusedVariablesIgnoreFn (fun _ stack _ => stackMatches stack [`null, ``Lean.Parser.Term.explicitBinder, ``Lean.Parser.Term.depArrow]) -- is in let declaration builtin_initialize addBuiltinUnusedVariablesIgnoreFn (fun _ stack opts => !getLinterUnusedVariablesFunArgs opts && stackMatches stack [`null, none, `null, ``Lean.Parser.Term.letIdDecl, none] && (stack.get? 3 |>.any fun (_, pos) => pos == 1) && (stack.get? 5 |>.any fun (stx, _) => !stx.isOfKind ``Lean.Parser.Command.whereStructField)) -- is in declaration signature builtin_initialize addBuiltinUnusedVariablesIgnoreFn (fun _ stack opts => !getLinterUnusedVariablesFunArgs opts && stackMatches stack [`null, none, `null, none] && (stack.get? 3 |>.any fun (stx, pos) => pos == 0 && [``Lean.Parser.Command.optDeclSig, ``Lean.Parser.Command.declSig].any (stx.isOfKind ·))) -- is in function definition builtin_initialize addBuiltinUnusedVariablesIgnoreFn (fun _ stack opts => !getLinterUnusedVariablesFunArgs opts && (stackMatches stack [`null, ``Lean.Parser.Term.basicFun] || stackMatches stack [`null, ``Lean.Parser.Term.paren, `null, ``Lean.Parser.Term.basicFun])) -- is pattern variable builtin_initialize addBuiltinUnusedVariablesIgnoreFn (fun _ stack opts => !getLinterUnusedVariablesPatternVars opts && stack.any fun (stx, pos) => (stx.isOfKind ``Lean.Parser.Term.matchAlt && pos == 1) || (stx.isOfKind ``Lean.Parser.Tactic.inductionAltLHS && pos == 2)) builtin_initialize unusedVariablesIgnoreFnsExt : SimplePersistentEnvExtension Name Unit ← registerSimplePersistentEnvExtension { name := `unusedVariablesIgnoreFns addEntryFn := fun _ _ => () addImportedFn := fun _ => () } builtin_initialize registerBuiltinAttribute { name := `unusedVariablesIgnoreFn descr := "Marks a function of type `Lean.Linter.IgnoreFunction` for suppressing unused variable warnings" add := fun decl stx kind => do Attribute.Builtin.ensureNoArgs stx unless kind == AttributeKind.global do throwError "invalid attribute 'unusedVariablesIgnoreFn', must be global" unless (← getConstInfo decl).type.isConstOf ``IgnoreFunction do throwError "invalid attribute 'unusedVariablesIgnoreFn', must be of type `Lean.Linter.IgnoreFunction`" let env ← getEnv setEnv <| unusedVariablesIgnoreFnsExt.addEntry env decl } unsafe def getUnusedVariablesIgnoreFnsImpl : CommandElabM (Array IgnoreFunction) := do let ents := unusedVariablesIgnoreFnsExt.getEntries (← getEnv) let ents ← ents.mapM (evalConstCheck IgnoreFunction ``IgnoreFunction) return (← builtinUnusedVariablesIgnoreFnsRef.get) ++ ents @[implementedBy getUnusedVariablesIgnoreFnsImpl] opaque getUnusedVariablesIgnoreFns : CommandElabM (Array IgnoreFunction) def unusedVariables : Linter := fun cmdStx => do unless getLinterUnusedVariables (← getOptions) do return -- NOTE: `messages` is local to the current command if (← get).messages.hasErrors then return let some cmdStxRange := cmdStx.getRange? | pure () let infoTrees := (← get).infoState.trees.toArray let fileMap := (← read).fileMap if (← infoTrees.anyM (·.hasSorry)) then return -- collect references let refs := findModuleRefs fileMap infoTrees (allowSimultaneousBinderUse := true) let mut vars : HashMap FVarId RefInfo := .empty let mut constDecls : HashSet String.Range := .empty for (ident, info) in refs.toList do match ident with | .fvar id => vars := vars.insert id info | .const _ => if let some definition := info.definition then if let some range := definition.stx.getRange? then constDecls := constDecls.insert range -- collect uses from tactic infos let tacticMVarAssignments : HashMap MVarId Expr := infoTrees.foldr (init := .empty) fun tree assignments => tree.foldInfo (init := assignments) (fun _ i assignments => match i with | .ofTacticInfo ti => ti.mctxAfter.eAssignment.foldl (init := assignments) fun assignments mvar expr => if assignments.contains mvar then assignments else assignments.insert mvar expr | _ => assignments) let tacticFVarUses : HashSet FVarId ← tacticMVarAssignments.foldM (init := .empty) fun uses _ expr => do let (_, s) ← StateT.run (s := uses) <| expr.forEach fun | .fvar id => modify (·.insert id) | _ => pure () return s -- collect ignore functions let ignoreFns := (← getUnusedVariablesIgnoreFns) |>.insertAt 0 (isTopLevelDecl constDecls) -- determine unused variables for (id, ⟨decl?, uses⟩) in vars.toList do -- process declaration let some decl := decl? | continue let declStx := skipDeclIdIfPresent decl.stx let some range := declStx.getRange? | continue let some localDecl := decl.info.lctx.find? id | continue if !cmdStxRange.contains range.start || localDecl.userName.hasMacroScopes then continue -- check if variable is used if !uses.isEmpty || tacticFVarUses.contains id || decl.aliases.any (match · with | .fvar id => tacticFVarUses.contains id | _ => false) then continue -- check linter options let opts := decl.ci.options if !getLinterUnusedVariables opts then continue -- evaluate ignore functions on original syntax if let some stack := findSyntaxStack? cmdStx declStx then if ignoreFns.any (· declStx stack opts) then continue else continue -- evaluate ignore functions on macro expansion outputs if ← infoTrees.anyM fun tree => do if let some macroExpansions ← collectMacroExpansions? range tree then return macroExpansions.any fun expansion => if let some stack := findSyntaxStack? expansion.output declStx then ignoreFns.any (· declStx stack opts) else false else return false then continue -- publish warning if variable is unused and not ignored logLint linter.unusedVariables declStx m!"unused variable `{localDecl.userName}`" return () where skipDeclIdIfPresent (stx : Syntax) : Syntax := if stx.isOfKind ``Lean.Parser.Command.declId then stx[0] else stx isTopLevelDecl (constDecls : HashSet String.Range) : IgnoreFunction := fun stx stack _ => Id.run <| do let some declRange := stx.getRange? | false constDecls.contains declRange && !stackMatches stack [``Lean.Parser.Term.letIdDecl] builtin_initialize addLinter unusedVariables end Linter def MessageData.isUnusedVariableWarning (msg : MessageData) : Bool := msg.hasTag (· == Linter.linter.unusedVariables.name)
384b48793050abd632add146558dce53b3778158
c86b74188c4b7a462728b1abd659ab4e5828dd61
/stage0/src/Lean/Elab/Do.lean
e4c7a2a9f3f9a377d22db74d8f964c375c23c625
[ "Apache-2.0" ]
permissive
cwb96/lean4
75e1f92f1ba98bbaa6b34da644b3dfab2ce7bf89
b48831cda76e64f13dd1c0edde7ba5fb172ed57a
refs/heads/master
1,686,347,881,407
1,624,483,842,000
1,624,483,842,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
69,700
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.Term import Lean.Elab.Binders import Lean.Elab.Match import Lean.Elab.Quotation.Util import Lean.Parser.Do -- HACK: avoid code explosion until heuristics are improved set_option compiler.reuse false namespace Lean.Elab.Term open Lean.Parser.Term open Meta private def getDoSeqElems (doSeq : Syntax) : List Syntax := if doSeq.getKind == `Lean.Parser.Term.doSeqBracketed then doSeq[1].getArgs.toList.map fun arg => arg[0] else if doSeq.getKind == `Lean.Parser.Term.doSeqIndent then doSeq[0].getArgs.toList.map fun arg => arg[0] else [] private def getDoSeq (doStx : Syntax) : Syntax := doStx[1] @[builtinTermElab liftMethod] def elabLiftMethod : TermElab := fun stx _ => throwErrorAt stx "invalid use of `(<- ...)`, must be nested inside a 'do' expression" /-- Return true if we should not lift `(<- ...)` actions nested in the syntax nodes with the given kind. -/ private def liftMethodDelimiter (k : SyntaxNodeKind) : Bool := k == ``Lean.Parser.Term.do || k == ``Lean.Parser.Term.doSeqIndent || k == ``Lean.Parser.Term.doSeqBracketed || k == ``Lean.Parser.Term.termReturn || k == ``Lean.Parser.Term.termUnless || k == ``Lean.Parser.Term.termTry || k == ``Lean.Parser.Term.termFor /-- Given `stx` which is a `letPatDecl`, `letEqnsDecl`, or `letIdDecl`, return true if it has binders. -/ private def letDeclArgHasBinders (letDeclArg : Syntax) : Bool := let k := letDeclArg.getKind if k == ``Lean.Parser.Term.letPatDecl then false else if k == ``Lean.Parser.Term.letEqnsDecl then true else if k == ``Lean.Parser.Term.letIdDecl then -- letIdLhs := ident >> checkWsBefore "expected space before binders" >> many (ppSpace >> (simpleBinderWithoutType <|> bracketedBinder)) >> optType let binders := letDeclArg[1] binders.getNumArgs > 0 else false /-- Return `true` if the given `letDecl` contains binders. -/ private def letDeclHasBinders (letDecl : Syntax) : Bool := letDeclArgHasBinders letDecl[0] /-- Return true if we should generate an error message when lifting a method over this kind of syntax. -/ private def liftMethodForbiddenBinder (stx : Syntax) : Bool := let k := stx.getKind if k == ``Lean.Parser.Term.fun || k == ``Lean.Parser.Term.matchAlts || k == ``Lean.Parser.Term.doLetRec || k == ``Lean.Parser.Term.letrec then -- It is never ok to lift over this kind of binder true -- The following kinds of `let`-expressions require extra checks to decide whether they contain binders or not else if k == ``Lean.Parser.Term.let then letDeclHasBinders stx[1] else if k == ``Lean.Parser.Term.doLet then letDeclHasBinders stx[2] else if k == ``Lean.Parser.Term.doLetArrow then letDeclArgHasBinders stx[2] else false private partial def hasLiftMethod : Syntax → Bool | Syntax.node k args => if liftMethodDelimiter k then false -- NOTE: We don't check for lifts in quotations here, which doesn't break anything but merely makes this rare case a -- bit slower else if k == `Lean.Parser.Term.liftMethod then true else args.any hasLiftMethod | _ => false structure ExtractMonadResult where m : Expr α : Expr hasBindInst : Expr expectedType : Expr private def mkIdBindFor (type : Expr) : TermElabM ExtractMonadResult := do let u ← getDecLevel type let id := Lean.mkConst `Id [u] let idBindVal := Lean.mkConst `Id.hasBind [u] pure { m := id, hasBindInst := idBindVal, α := type, expectedType := mkApp id type } private partial def extractBind (expectedType? : Option Expr) : TermElabM ExtractMonadResult := do match expectedType? with | none => throwError "invalid 'do' notation, expected type is not available" | some expectedType => let extractStep? (type : Expr) : MetaM (Option ExtractMonadResult) := do match type with | Expr.app m α _ => try let bindInstType ← mkAppM `Bind #[m] let bindInstVal ← Meta.synthInstance bindInstType return some { m := m, hasBindInst := bindInstVal, α := α, expectedType := expectedType } catch _ => return none | _ => return none let rec extract? (type : Expr) : MetaM (Option ExtractMonadResult) := do match (← extractStep? type) with | some r => return r | none => let typeNew ← whnfCore type if typeNew != type then extract? typeNew else if typeNew.getAppFn.isMVar then throwError "invalid 'do' notation, expected type is not available" match (← unfoldDefinition? typeNew) with | some typeNew => extract? typeNew | none => return none match (← extract? expectedType) with | some r => return r | none => mkIdBindFor expectedType namespace Do /- A `doMatch` alternative. `vars` is the array of variables declared by `patterns`. -/ structure Alt (σ : Type) where ref : Syntax vars : Array Name patterns : Syntax rhs : σ deriving Inhabited /- Auxiliary datastructure for representing a `do` code block, and compiling "reassignments" (e.g., `x := x + 1`). We convert `Code` into a `Syntax` term representing the: - `do`-block, or - the visitor argument for the `forIn` combinator. We say the following constructors are terminals: - `break`: for interrupting a `for x in s` - `continue`: for interrupting the current iteration of a `for x in s` - `return e`: for returning `e` as the result for the whole `do` computation block - `action a`: for executing action `a` as a terminal - `ite`: if-then-else - `match`: pattern matching - `jmp` a goto to a join-point We say the terminals `break`, `continue`, `action`, and `return` are "exit points" Note that, `return e` is not equivalent to `action (pure e)`. Here is an example: ``` def f (x : Nat) : IO Unit := do if x == 0 then return () IO.println "hello" ``` Executing `#eval f 0` will not print "hello". Now, consider ``` def g (x : Nat) : IO Unit := do if x == 0 then pure () IO.println "hello" ``` The `if` statement is essentially a noop, and "hello" is printed when we execute `g 0`. - `decl` represents all declaration-like `doElem`s (e.g., `let`, `have`, `let rec`). The field `stx` is the actual `doElem`, `vars` is the array of variables declared by it, and `cont` is the next instruction in the `do` code block. `vars` is an array since we have declarations such as `let (a, b) := s`. - `reassign` is an reassignment-like `doElem` (e.g., `x := x + 1`). - `joinpoint` is a join point declaration: an auxiliary `let`-declaration used to represent the control-flow. - `seq a k` executes action `a`, ignores its result, and then executes `k`. We also store the do-elements `dbg_trace` and `assert!` as actions in a `seq`. A code block `C` is well-formed if - For every `jmp ref j as` in `C`, there is a `joinpoint j ps b k` and `jmp ref j as` is in `k`, and `ps.size == as.size` -/ inductive Code where | decl (xs : Array Name) (doElem : Syntax) (k : Code) | reassign (xs : Array Name) (doElem : Syntax) (k : Code) /- The Boolean value in `params` indicates whether we should use `(x : typeof! x)` when generating term Syntax or not -/ | joinpoint (name : Name) (params : Array (Name × Bool)) (body : Code) (k : Code) | seq (action : Syntax) (k : Code) | action (action : Syntax) | «break» (ref : Syntax) | «continue» (ref : Syntax) | «return» (ref : Syntax) (val : Syntax) /- Recall that an if-then-else may declare a variable using `optIdent` for the branches `thenBranch` and `elseBranch`. We store the variable name at `var?`. -/ | ite (ref : Syntax) (h? : Option Name) (optIdent : Syntax) (cond : Syntax) (thenBranch : Code) (elseBranch : Code) | «match» (ref : Syntax) (gen : Syntax) (discrs : Syntax) (optType : Syntax) (alts : Array (Alt Code)) | jmp (ref : Syntax) (jpName : Name) (args : Array Syntax) deriving Inhabited /- A code block, and the collection of variables updated by it. -/ structure CodeBlock where code : Code uvars : NameSet := {} -- set of variables updated by `code` private def nameSetToArray (s : NameSet) : Array Name := s.fold (fun (xs : Array Name) x => xs.push x) #[] private def varsToMessageData (vars : Array Name) : MessageData := MessageData.joinSep (vars.toList.map fun n => MessageData.ofName (n.simpMacroScopes)) " " partial def CodeBlocl.toMessageData (codeBlock : CodeBlock) : MessageData := let us := MessageData.ofList $ (nameSetToArray codeBlock.uvars).toList.map MessageData.ofName let rec loop : Code → MessageData | Code.decl xs _ k => m!"let {varsToMessageData xs} := ...\n{loop k}" | Code.reassign xs _ k => m!"{varsToMessageData xs} := ...\n{loop k}" | Code.joinpoint n ps body k => m!"let {n.simpMacroScopes} {varsToMessageData (ps.map Prod.fst)} := {indentD (loop body)}\n{loop k}" | Code.seq e k => m!"{e}\n{loop k}" | Code.action e => e | Code.ite _ _ _ c t e => m!"if {c} then {indentD (loop t)}\nelse{loop e}" | Code.jmp _ j xs => m!"jmp {j.simpMacroScopes} {xs.toList}" | Code.«break» _ => m!"break {us}" | Code.«continue» _ => m!"continue {us}" | Code.«return» _ v => m!"return {v} {us}" | Code.«match» _ _ ds t alts => m!"match {ds} with" ++ alts.foldl (init := m!"") fun acc alt => acc ++ m!"\n| {alt.patterns} => {loop alt.rhs}" loop codeBlock.code /- Return true if the give code contains an exit point that satisfies `p` -/ @[inline] partial def hasExitPointPred (c : Code) (p : Code → Bool) : Bool := let rec @[specialize] loop : Code → Bool | Code.decl _ _ k => loop k | Code.reassign _ _ k => loop k | Code.joinpoint _ _ b k => loop b || loop k | Code.seq _ k => loop k | Code.ite _ _ _ _ t e => loop t || loop e | Code.«match» _ _ _ _ alts => alts.any (loop ·.rhs) | Code.jmp _ _ _ => false | c => p c loop c def hasExitPoint (c : Code) : Bool := hasExitPointPred c fun c => true def hasReturn (c : Code) : Bool := hasExitPointPred c fun | Code.«return» _ _ => true | _ => false def hasTerminalAction (c : Code) : Bool := hasExitPointPred c fun | Code.«action» _ => true | _ => false def hasBreakContinue (c : Code) : Bool := hasExitPointPred c fun | Code.«break» _ => true | Code.«continue» _ => true | _ => false def hasBreakContinueReturn (c : Code) : Bool := hasExitPointPred c fun | Code.«break» _ => true | Code.«continue» _ => true | Code.«return» _ _ => true | _ => false def mkAuxDeclFor {m} [Monad m] [MonadQuotation m] (e : Syntax) (mkCont : Syntax → m Code) : m Code := withRef e <| withFreshMacroScope do let y ← `(y) let yName := y.getId let doElem ← `(doElem| let y ← $e:term) -- Add elaboration hint for producing sane error message let y ← `(ensureExpectedType% "type mismatch, result value" $y) let k ← mkCont y pure $ Code.decl #[yName] doElem k /- Convert `action _ e` instructions in `c` into `let y ← e; jmp _ jp (xs y)`. -/ partial def convertTerminalActionIntoJmp (code : Code) (jp : Name) (xs : Array Name) : MacroM Code := let rec loop : Code → MacroM Code | Code.decl xs stx k => do Code.decl xs stx (← loop k) | Code.reassign xs stx k => do Code.reassign xs stx (← loop k) | Code.joinpoint n ps b k => do Code.joinpoint n ps (← loop b) (← loop k) | Code.seq e k => do Code.seq e (← loop k) | Code.ite ref x? h c t e => do Code.ite ref x? h c (← loop t) (← loop e) | Code.«match» ref g ds t alts => do Code.«match» ref g ds t (← alts.mapM fun alt => do pure { alt with rhs := (← loop alt.rhs) }) | Code.action e => mkAuxDeclFor e fun y => let ref := e -- We jump to `jp` with xs **and** y let jmpArgs := xs.map $ mkIdentFrom ref let jmpArgs := jmpArgs.push y pure $ Code.jmp ref jp jmpArgs | c => pure c loop code structure JPDecl where name : Name params : Array (Name × Bool) body : Code def attachJP (jpDecl : JPDecl) (k : Code) : Code := Code.joinpoint jpDecl.name jpDecl.params jpDecl.body k def attachJPs (jpDecls : Array JPDecl) (k : Code) : Code := jpDecls.foldr attachJP k def mkFreshJP (ps : Array (Name × Bool)) (body : Code) : TermElabM JPDecl := do let ps ← if ps.isEmpty then let y ← mkFreshUserName `y pure #[(y, false)] else pure ps -- Remark: the compiler frontend implemented in C++ currently detects jointpoints created by -- the "do" notation by testing the name. See hack at method `visit_let` at `lcnf.cpp` -- We will remove this hack when we re-implement the compiler frontend in Lean. let name ← mkFreshUserName `_do_jp pure { name := name, params := ps, body := body } def mkFreshJP' (xs : Array Name) (body : Code) : TermElabM JPDecl := mkFreshJP (xs.map fun x => (x, true)) body def addFreshJP (ps : Array (Name × Bool)) (body : Code) : StateRefT (Array JPDecl) TermElabM Name := do let jp ← mkFreshJP ps body modify fun (jps : Array JPDecl) => jps.push jp pure jp.name def insertVars (rs : NameSet) (xs : Array Name) : NameSet := xs.foldl (·.insert ·) rs def eraseVars (rs : NameSet) (xs : Array Name) : NameSet := xs.foldl (·.erase ·) rs def eraseOptVar (rs : NameSet) (x? : Option Name) : NameSet := match x? with | none => rs | some x => rs.insert x /- Create a new jointpoint for `c`, and jump to it with the variables `rs` -/ def mkSimpleJmp (ref : Syntax) (rs : NameSet) (c : Code) : StateRefT (Array JPDecl) TermElabM Code := do let xs := nameSetToArray rs let jp ← addFreshJP (xs.map fun x => (x, true)) c if xs.isEmpty then let unit ← ``(Unit.unit) return Code.jmp ref jp #[unit] else return Code.jmp ref jp (xs.map $ mkIdentFrom ref) /- Create a new joinpoint that takes `rs` and `val` as arguments. `val` must be syntax representing a pure value. The body of the joinpoint is created using `mkJPBody yFresh`, where `yFresh` is a fresh variable created by this method. -/ def mkJmp (ref : Syntax) (rs : NameSet) (val : Syntax) (mkJPBody : Syntax → MacroM Code) : StateRefT (Array JPDecl) TermElabM Code := do let xs := nameSetToArray rs let args := xs.map $ mkIdentFrom ref let args := args.push val let yFresh ← mkFreshUserName `y let ps := xs.map fun x => (x, true) let ps := ps.push (yFresh, false) let jpBody ← liftMacroM $ mkJPBody (mkIdentFrom ref yFresh) let jp ← addFreshJP ps jpBody pure $ Code.jmp ref jp args /- `pullExitPointsAux rs c` auxiliary method for `pullExitPoints`, `rs` is the set of update variable in the current path. -/ partial def pullExitPointsAux : NameSet → Code → StateRefT (Array JPDecl) TermElabM Code | rs, Code.decl xs stx k => do Code.decl xs stx (← pullExitPointsAux (eraseVars rs xs) k) | rs, Code.reassign xs stx k => do Code.reassign xs stx (← pullExitPointsAux (insertVars rs xs) k) | rs, Code.joinpoint j ps b k => do Code.joinpoint j ps (← pullExitPointsAux rs b) (← pullExitPointsAux rs k) | rs, Code.seq e k => do Code.seq e (← pullExitPointsAux rs k) | rs, Code.ite ref x? o c t e => do Code.ite ref x? o c (← pullExitPointsAux (eraseOptVar rs x?) t) (← pullExitPointsAux (eraseOptVar rs x?) e) | rs, Code.«match» ref g ds t alts => do Code.«match» ref g ds t (← alts.mapM fun alt => do pure { alt with rhs := (← pullExitPointsAux (eraseVars rs alt.vars) alt.rhs) }) | rs, c@(Code.jmp _ _ _) => pure c | rs, Code.«break» ref => mkSimpleJmp ref rs (Code.«break» ref) | rs, Code.«continue» ref => mkSimpleJmp ref rs (Code.«continue» ref) | rs, Code.«return» ref val => mkJmp ref rs val (fun y => pure $ Code.«return» ref y) | rs, Code.action e => -- We use `mkAuxDeclFor` because `e` is not pure. mkAuxDeclFor e fun y => let ref := e mkJmp ref rs y (fun yFresh => do pure $ Code.action (← ``(Pure.pure $yFresh))) /- Auxiliary operation for adding new variables to the collection of updated variables in a CodeBlock. When a new variable is not already in the collection, but is shadowed by some declaration in `c`, we create auxiliary join points to make sure we preserve the semantics of the code block. Example: suppose we have the code block `print x; let x := 10; return x`. And we want to extend it with the reassignment `x := x + 1`. We first use `pullExitPoints` to create ``` let jp (x!1) := return x!1; print x; let x := 10; jmp jp x ``` and then we add the reassignment ``` x := x + 1 let jp (x!1) := return x!1; print x; let x := 10; jmp jp x ``` Note that we created a fresh variable `x!1` to avoid accidental name capture. As another example, consider ``` print x; let x := 10 y := y + 1; return x; ``` We transform it into ``` let jp (y x!1) := return x!1; print x; let x := 10 y := y + 1; jmp jp y x ``` and then we add the reassignment as in the previous example. We need to include `y` in the jump, because each exit point is implicitly returning the set of update variables. We implement the method as follows. Let `us` be `c.uvars`, then 1- for each `return _ y` in `c`, we create a join point `let j (us y!1) := return y!1` and replace the `return _ y` with `jmp us y` 2- for each `break`, we create a join point `let j (us) := break` and replace the `break` with `jmp us`. 3- Same as 2 for `continue`. -/ def pullExitPoints (c : Code) : TermElabM Code := do if hasExitPoint c then let (c, jpDecls) ← (pullExitPointsAux {} c).run #[] pure $ attachJPs jpDecls c else pure c partial def extendUpdatedVarsAux (c : Code) (ws : NameSet) : TermElabM Code := let rec update : Code → TermElabM Code | Code.joinpoint j ps b k => do Code.joinpoint j ps (← update b) (← update k) | Code.seq e k => do Code.seq e (← update k) | c@(Code.«match» ref g ds t alts) => do if alts.any fun alt => alt.vars.any fun x => ws.contains x then -- If a pattern variable is shadowing a variable in ws, we `pullExitPoints` pullExitPoints c else Code.«match» ref g ds t (← alts.mapM fun alt => do pure { alt with rhs := (← update alt.rhs) }) | Code.ite ref none o c t e => do Code.ite ref none o c (← update t) (← update e) | c@(Code.ite ref (some h) o cond t e) => do if ws.contains h then -- if the `h` at `if h:c then t else e` shadows a variable in `ws`, we `pullExitPoints` pullExitPoints c else Code.ite ref (some h) o cond (← update t) (← update e) | Code.reassign xs stx k => do Code.reassign xs stx (← update k) | c@(Code.decl xs stx k) => do if xs.any fun x => ws.contains x then -- One the declared variables is shadowing a variable in `ws` pullExitPoints c else Code.decl xs stx (← update k) | c => pure c update c /- Extend the set of updated variables. It assumes `ws` is a super set of `c.uvars`. We **cannot** simply update the field `c.uvars`, because `c` may have shadowed some variable in `ws`. See discussion at `pullExitPoints`. -/ partial def extendUpdatedVars (c : CodeBlock) (ws : NameSet) : TermElabM CodeBlock := do if ws.any fun x => !c.uvars.contains x then -- `ws` contains a variable that is not in `c.uvars`, but in `c.dvars` (i.e., it has been shadowed) pure { code := (← extendUpdatedVarsAux c.code ws), uvars := ws } else pure { c with uvars := ws } private def union (s₁ s₂ : NameSet) : NameSet := s₁.fold (·.insert ·) s₂ /- Given two code blocks `c₁` and `c₂`, make sure they have the same set of updated variables. Let `ws` the union of the updated variables in `c₁‵ and ‵c₂`. We use `extendUpdatedVars c₁ ws` and `extendUpdatedVars c₂ ws` -/ def homogenize (c₁ c₂ : CodeBlock) : TermElabM (CodeBlock × CodeBlock) := do let ws := union c₁.uvars c₂.uvars let c₁ ← extendUpdatedVars c₁ ws let c₂ ← extendUpdatedVars c₂ ws pure (c₁, c₂) /- Extending code blocks with variable declarations: `let x : t := v` and `let x : t ← v`. We remove `x` from the collection of updated varibles. Remark: `stx` is the syntax for the declaration (e.g., `letDecl`), and `xs` are the variables declared by it. It is an array because we have let-declarations that declare multiple variables. Example: `let (x, y) := t` -/ def mkVarDeclCore (xs : Array Name) (stx : Syntax) (c : CodeBlock) : CodeBlock := { code := Code.decl xs stx c.code, uvars := eraseVars c.uvars xs } /- Extending code blocks with reassignments: `x : t := v` and `x : t ← v`. Remark: `stx` is the syntax for the declaration (e.g., `letDecl`), and `xs` are the variables declared by it. It is an array because we have let-declarations that declare multiple variables. Example: `(x, y) ← t` -/ def mkReassignCore (xs : Array Name) (stx : Syntax) (c : CodeBlock) : TermElabM CodeBlock := do let us := c.uvars let ws := insertVars us xs -- If `xs` contains a new updated variable, then we must use `extendUpdatedVars`. -- See discussion at `pullExitPoints` let code ← if xs.any fun x => !us.contains x then extendUpdatedVarsAux c.code ws else pure c.code pure { code := Code.reassign xs stx code, uvars := ws } def mkSeq (action : Syntax) (c : CodeBlock) : CodeBlock := { c with code := Code.seq action c.code } def mkTerminalAction (action : Syntax) : CodeBlock := { code := Code.action action } def mkReturn (ref : Syntax) (val : Syntax) : CodeBlock := { code := Code.«return» ref val } def mkBreak (ref : Syntax) : CodeBlock := { code := Code.«break» ref } def mkContinue (ref : Syntax) : CodeBlock := { code := Code.«continue» ref } def mkIte (ref : Syntax) (optIdent : Syntax) (cond : Syntax) (thenBranch : CodeBlock) (elseBranch : CodeBlock) : TermElabM CodeBlock := do let x? := if optIdent.isNone then none else some optIdent[0].getId let (thenBranch, elseBranch) ← homogenize thenBranch elseBranch pure { code := Code.ite ref x? optIdent cond thenBranch.code elseBranch.code, uvars := thenBranch.uvars, } private def mkUnit : MacroM Syntax := ``((⟨⟩ : PUnit)) private def mkPureUnit : MacroM Syntax := ``(pure PUnit.unit) def mkPureUnitAction : MacroM CodeBlock := do mkTerminalAction (← mkPureUnit) def mkUnless (cond : Syntax) (c : CodeBlock) : MacroM CodeBlock := do let thenBranch ← mkPureUnitAction pure { c with code := Code.ite (← getRef) none mkNullNode cond thenBranch.code c.code } def mkMatch (ref : Syntax) (genParam : Syntax) (discrs : Syntax) (optType : Syntax) (alts : Array (Alt CodeBlock)) : TermElabM CodeBlock := do -- nary version of homogenize let ws := alts.foldl (union · ·.rhs.uvars) {} let alts ← alts.mapM fun alt => do let rhs ← extendUpdatedVars alt.rhs ws pure { ref := alt.ref, vars := alt.vars, patterns := alt.patterns, rhs := rhs.code : Alt Code } pure { code := Code.«match» ref genParam discrs optType alts, uvars := ws } /- Return a code block that executes `terminal` and then `k` with the value produced by `terminal`. This method assumes `terminal` is a terminal -/ def concat (terminal : CodeBlock) (kRef : Syntax) (y? : Option Name) (k : CodeBlock) : TermElabM CodeBlock := do unless hasTerminalAction terminal.code do throwErrorAt kRef "'do' element is unreachable" let (terminal, k) ← homogenize terminal k let xs := nameSetToArray k.uvars let y ← match y? with | some y => pure y | none => mkFreshUserName `y let ps := xs.map fun x => (x, true) let ps := ps.push (y, false) let jpDecl ← mkFreshJP ps k.code let jp := jpDecl.name let terminal ← liftMacroM $ convertTerminalActionIntoJmp terminal.code jp xs pure { code := attachJP jpDecl terminal, uvars := k.uvars } def getLetIdDeclVar (letIdDecl : Syntax) : Name := letIdDecl[0].getId -- support both regular and syntax match def getPatternVarsEx (pattern : Syntax) : TermElabM (Array Name) := getPatternVarNames <$> getPatternVars pattern <|> Array.map Syntax.getId <$> Quotation.getPatternVars pattern def getPatternsVarsEx (patterns : Array Syntax) : TermElabM (Array Name) := getPatternVarNames <$> getPatternsVars patterns <|> Array.map Syntax.getId <$> Quotation.getPatternsVars patterns def getLetPatDeclVars (letPatDecl : Syntax) : TermElabM (Array Name) := do let pattern := letPatDecl[0] getPatternVarsEx pattern def getLetEqnsDeclVar (letEqnsDecl : Syntax) : Name := letEqnsDecl[0].getId def getLetDeclVars (letDecl : Syntax) : TermElabM (Array Name) := do let arg := letDecl[0] if arg.getKind == `Lean.Parser.Term.letIdDecl then pure #[getLetIdDeclVar arg] else if arg.getKind == `Lean.Parser.Term.letPatDecl then getLetPatDeclVars arg else if arg.getKind == `Lean.Parser.Term.letEqnsDecl then pure #[getLetEqnsDeclVar arg] else throwError "unexpected kind of let declaration" def getDoLetVars (doLet : Syntax) : TermElabM (Array Name) := -- leading_parser "let " >> optional "mut " >> letDecl getLetDeclVars doLet[2] def getDoHaveVar (doHave : Syntax) : Name := /- `leading_parser "have " >> Term.haveDecl` where ``` haveDecl := leading_parser optIdent >> termParser >> (haveAssign <|> fromTerm <|> byTactic) optIdent := optional (try (ident >> " : ")) ``` -/ let optIdent := doHave[1][0] if optIdent.isNone then `this else optIdent[0].getId def getDoLetRecVars (doLetRec : Syntax) : TermElabM (Array Name) := do -- letRecDecls is an array of `(group (optional attributes >> letDecl))` let letRecDecls := doLetRec[1][0].getSepArgs let letDecls := letRecDecls.map fun p => p[2] let mut allVars := #[] for letDecl in letDecls do let vars ← getLetDeclVars letDecl allVars := allVars ++ vars pure allVars -- ident >> optType >> leftArrow >> termParser def getDoIdDeclVar (doIdDecl : Syntax) : Name := doIdDecl[0].getId -- termParser >> leftArrow >> termParser >> optional (" | " >> termParser) def getDoPatDeclVars (doPatDecl : Syntax) : TermElabM (Array Name) := do let pattern := doPatDecl[0] getPatternVarsEx pattern -- leading_parser "let " >> optional "mut " >> (doIdDecl <|> doPatDecl) def getDoLetArrowVars (doLetArrow : Syntax) : TermElabM (Array Name) := do let decl := doLetArrow[2] if decl.getKind == `Lean.Parser.Term.doIdDecl then pure #[getDoIdDeclVar decl] else if decl.getKind == `Lean.Parser.Term.doPatDecl then getDoPatDeclVars decl else throwError "unexpected kind of 'do' declaration" def getDoReassignVars (doReassign : Syntax) : TermElabM (Array Name) := do let arg := doReassign[0] if arg.getKind == `Lean.Parser.Term.letIdDecl then pure #[getLetIdDeclVar arg] else if arg.getKind == `Lean.Parser.Term.letPatDecl then getLetPatDeclVars arg else throwError "unexpected kind of reassignment" def mkDoSeq (doElems : Array Syntax) : Syntax := mkNode `Lean.Parser.Term.doSeqIndent #[mkNullNode $ doElems.map fun doElem => mkNullNode #[doElem, mkNullNode]] def mkSingletonDoSeq (doElem : Syntax) : Syntax := mkDoSeq #[doElem] /- If the given syntax is a `doIf`, return an equivalente `doIf` that has an `else` but no `else if`s or `if let`s. -/ private def expandDoIf? (stx : Syntax) : MacroM (Option Syntax) := match stx with | `(doElem|if $p:doIfProp then $t else $e) => pure none | `(doElem|if%$i $cond:doIfCond then $t $[else if%$is $conds:doIfCond then $ts]* $[else $e?]?) => withRef stx do let mut e := e?.getD (← `(doSeq|pure PUnit.unit)) let mut eIsSeq := true for (i, cond, t) in Array.zip (is.reverse.push i) (Array.zip (conds.reverse.push cond) (ts.reverse.push t)) do e ← if eIsSeq then e else `(doSeq|$e:doElem) e ← withRef cond <| match cond with | `(doIfCond|let $pat := $d) => `(doElem| match%$i $d:term with | $pat:term => $t | _ => $e) | `(doIfCond|let $pat ← $d) => `(doElem| match%$i ← $d with | $pat:term => $t | _ => $e) | `(doIfCond|$cond:doIfProp) => `(doElem| if%$i $cond:doIfProp then $t else $e) | _ => `(doElem| if%$i $(Syntax.missing) then $t else $e) eIsSeq := false return some e | _ => pure none structure DoIfView where ref : Syntax optIdent : Syntax cond : Syntax thenBranch : Syntax elseBranch : Syntax /- This method assumes `expandDoIf?` is not applicable. -/ private def mkDoIfView (doIf : Syntax) : MacroM DoIfView := do pure { ref := doIf, optIdent := doIf[1][0], cond := doIf[1][1], thenBranch := doIf[3], elseBranch := doIf[5][1] } /- We use `MProd` instead of `Prod` to group values when expanding the `do` notation. `MProd` is a universe monomorphic product. The motivation is to generate simpler universe constraints in code that was not written by the user. Note that we are not restricting the macro power since the `Bind.bind` combinator already forces values computed by monadic actions to be in the same universe. -/ private def mkTuple (elems : Array Syntax) : MacroM Syntax := do if elems.size == 0 then mkUnit else if elems.size == 1 then pure elems[0] else (elems.extract 0 (elems.size - 1)).foldrM (fun elem tuple => ``(MProd.mk $elem $tuple)) (elems.back) /- Return `some action` if `doElem` is a `doExpr <action>`-/ def isDoExpr? (doElem : Syntax) : Option Syntax := if doElem.getKind == `Lean.Parser.Term.doExpr then some doElem[0] else none /-- Given `uvars := #[a_1, ..., a_n, a_{n+1}]` construct term ``` let a_1 := x.1 let x := x.2 let a_2 := x.1 let x := x.2 ... let a_n := x.1 let a_{n+1} := x.2 body ``` Special cases - `uvars := #[]` => `body` - `uvars := #[a]` => `let a := x; body` We use this method when expanding the `for-in` notation. -/ private def destructTuple (uvars : Array Name) (x : Syntax) (body : Syntax) : MacroM Syntax := do if uvars.size == 0 then return body else if uvars.size == 1 then `(let $(← mkIdentFromRef uvars[0]):ident := $x; $body) else destruct uvars.toList x body where destruct (as : List Name) (x : Syntax) (body : Syntax) : MacroM Syntax := do match as with | [a, b] => `(let $(← mkIdentFromRef a):ident := $x.1; let $(← mkIdentFromRef b):ident := $x.2; $body) | a :: as => withFreshMacroScope do let rest ← destruct as (← `(x)) body `(let $(← mkIdentFromRef a):ident := $x.1; let x := $x.2; $rest) | _ => unreachable! /- The procedure `ToTerm.run` converts a `CodeBlock` into a `Syntax` term. We use this method to convert 1- The `CodeBlock` for a root `do ...` term into a `Syntax` term. This kind of `CodeBlock` never contains `break` nor `continue`. Moreover, the collection of updated variables is not packed into the result. Thus, we have two kinds of exit points - `Code.action e` which is converted into `e` - `Code.return _ e` which is converted into `pure e` We use `Kind.regular` for this case. 2- The `CodeBlock` for `b` at `for x in xs do b`. In this case, we need to generate a `Syntax` term representing a function for the `xs.forIn` combinator. a) If `b` contain a `Code.return _ a` exit point. The generated `Syntax` term has type `m (ForInStep (Option α × σ))`, where `a : α`, and the `σ` is the type of the tuple of variables reassigned by `b`. We use `Kind.forInWithReturn` for this case b) If `b` does not contain a `Code.return _ a` exit point. Then, the generated `Syntax` term has type `m (ForInStep σ)`. We use `Kind.forIn` for this case. 3- The `CodeBlock` `c` for a `do` sequence nested in a monadic combinator (e.g., `MonadExcept.tryCatch`). The generated `Syntax` term for `c` must inform whether `c` "exited" using `Code.action`, `Code.return`, `Code.break` or `Code.continue`. We use the auxiliary types `DoResult`s for storing this information. For example, the auxiliary type `DoResultPBC α σ` is used for a code block that exits with `Code.action`, **and** `Code.break`/`Code.continue`, `α` is the type of values produced by the exit `action`, and `σ` is the type of the tuple of reassigned variables. The type `DoResult α β σ` is usedf for code blocks that exit with `Code.action`, `Code.return`, **and** `Code.break`/`Code.continue`, `β` is the type of the returned values. We don't use `DoResult α β σ` for all cases because: a) The elaborator would not be able to infer all type parameters without extra annotations. For example, if the code block does not contain `Code.return _ _`, the elaborator will not be able to infer `β`. b) We need to pattern match on the result produced by the combinator (e.g., `MonadExcept.tryCatch`), but we don't want to consider "unreachable" cases. We do not distinguish between cases that contain `break`, but not `continue`, and vice versa. When listing all cases, we use `a` to indicate the code block contains `Code.action _`, `r` for `Code.return _ _`, and `b/c` for a code block that contains `Code.break _` or `Code.continue _`. - `a`: `Kind.regular`, type `m (α × σ)` - `r`: `Kind.regular`, type `m (α × σ)` Note that the code that pattern matches on the result will behave differently in this case. It produces `return a` for this case, and `pure a` for the previous one. - `b/c`: `Kind.nestedBC`, type `m (DoResultBC σ)` - `a` and `r`: `Kind.nestedPR`, type `m (DoResultPR α β σ)` - `a` and `bc`: `Kind.nestedSBC`, type `m (DoResultSBC α σ)` - `r` and `bc`: `Kind.nestedSBC`, type `m (DoResultSBC α σ)` Again the code that pattern matches on the result will behave differently in this case and the previous one. It produces `return a` for the constructor `DoResultSPR.pureReturn a u` for this case, and `pure a` for the previous case. - `a`, `r`, `b/c`: `Kind.nestedPRBC`, type type `m (DoResultPRBC α β σ)` Here is the recipe for adding new combinators with nested `do`s. Example: suppose we want to support `repeat doSeq`. Assuming we have `repeat : m α → m α` 1- Convert `doSeq` into `codeBlock : CodeBlock` 2- Create term `term` using `mkNestedTerm code m uvars a r bc` where `code` is `codeBlock.code`, `uvars` is an array containing `codeBlock.uvars`, `m` is a `Syntax` representing the Monad, and `a` is true if `code` contains `Code.action _`, `r` is true if `code` contains `Code.return _ _`, `bc` is true if `code` contains `Code.break _` or `Code.continue _`. Remark: for combinators such as `repeat` that take a single `doSeq`, all arguments, but `m`, are extracted from `codeBlock`. 3- Create the term `repeat $term` 4- and then, convert it into a `doSeq` using `matchNestedTermResult ref (repeat $term) uvsar a r bc` -/ namespace ToTerm inductive Kind where | regular | forIn | forInWithReturn | nestedBC | nestedPR | nestedSBC | nestedPRBC instance : Inhabited Kind := ⟨Kind.regular⟩ def Kind.isRegular : Kind → Bool | Kind.regular => true | _ => false structure Context where m : Syntax -- Syntax to reference the monad associated with the do notation. uvars : Array Name kind : Kind abbrev M := ReaderT Context MacroM def mkUVarTuple : M Syntax := do let ctx ← read let uvarIdents ← ctx.uvars.mapM mkIdentFromRef mkTuple uvarIdents def returnToTerm (val : Syntax) : M Syntax := do let ctx ← read let u ← mkUVarTuple match ctx.kind with | Kind.regular => if ctx.uvars.isEmpty then ``(Pure.pure $val) else ``(Pure.pure (MProd.mk $val $u)) | Kind.forIn => ``(Pure.pure (ForInStep.done $u)) | Kind.forInWithReturn => ``(Pure.pure (ForInStep.done (MProd.mk (some $val) $u))) | Kind.nestedBC => unreachable! | Kind.nestedPR => ``(Pure.pure (DoResultPR.«return» $val $u)) | Kind.nestedSBC => ``(Pure.pure (DoResultSBC.«pureReturn» $val $u)) | Kind.nestedPRBC => ``(Pure.pure (DoResultPRBC.«return» $val $u)) def continueToTerm : M Syntax := do let ctx ← read let u ← mkUVarTuple match ctx.kind with | Kind.regular => unreachable! | Kind.forIn => ``(Pure.pure (ForInStep.yield $u)) | Kind.forInWithReturn => ``(Pure.pure (ForInStep.yield (MProd.mk none $u))) | Kind.nestedBC => ``(Pure.pure (DoResultBC.«continue» $u)) | Kind.nestedPR => unreachable! | Kind.nestedSBC => ``(Pure.pure (DoResultSBC.«continue» $u)) | Kind.nestedPRBC => ``(Pure.pure (DoResultPRBC.«continue» $u)) def breakToTerm : M Syntax := do let ctx ← read let u ← mkUVarTuple match ctx.kind with | Kind.regular => unreachable! | Kind.forIn => ``(Pure.pure (ForInStep.done $u)) | Kind.forInWithReturn => ``(Pure.pure (ForInStep.done (MProd.mk none $u))) | Kind.nestedBC => ``(Pure.pure (DoResultBC.«break» $u)) | Kind.nestedPR => unreachable! | Kind.nestedSBC => ``(Pure.pure (DoResultSBC.«break» $u)) | Kind.nestedPRBC => ``(Pure.pure (DoResultPRBC.«break» $u)) def actionTerminalToTerm (action : Syntax) : M Syntax := withRef action <| withFreshMacroScope do let ctx ← read let u ← mkUVarTuple match ctx.kind with | Kind.regular => if ctx.uvars.isEmpty then pure action else ``(Bind.bind $action fun y => Pure.pure (MProd.mk y $u)) | Kind.forIn => ``(Bind.bind $action fun (_ : PUnit) => Pure.pure (ForInStep.yield $u)) | Kind.forInWithReturn => ``(Bind.bind $action fun (_ : PUnit) => Pure.pure (ForInStep.yield (MProd.mk none $u))) | Kind.nestedBC => unreachable! | Kind.nestedPR => ``(Bind.bind $action fun y => (Pure.pure (DoResultPR.«pure» y $u))) | Kind.nestedSBC => ``(Bind.bind $action fun y => (Pure.pure (DoResultSBC.«pureReturn» y $u))) | Kind.nestedPRBC => ``(Bind.bind $action fun y => (Pure.pure (DoResultPRBC.«pure» y $u))) def seqToTerm (action : Syntax) (k : Syntax) : M Syntax := withRef action <| withFreshMacroScope do if action.getKind == `Lean.Parser.Term.doDbgTrace then let msg := action[1] `(dbg_trace $msg; $k) else if action.getKind == `Lean.Parser.Term.doAssert then let cond := action[1] `(assert! $cond; $k) else let action ← withRef action ``(($action : $((←read).m) PUnit)) ``(Bind.bind $action (fun (_ : PUnit) => $k)) def declToTerm (decl : Syntax) (k : Syntax) : M Syntax := withRef decl <| withFreshMacroScope do let kind := decl.getKind if kind == `Lean.Parser.Term.doLet then let letDecl := decl[2] `(let $letDecl:letDecl; $k) else if kind == `Lean.Parser.Term.doLetRec then let letRecToken := decl[0] let letRecDecls := decl[1] pure $ mkNode `Lean.Parser.Term.letrec #[letRecToken, letRecDecls, mkNullNode, k] else if kind == `Lean.Parser.Term.doLetArrow then let arg := decl[2] let ref := arg if arg.getKind == `Lean.Parser.Term.doIdDecl then let id := arg[0] let type := expandOptType ref arg[1] let doElem := arg[3] -- `doElem` must be a `doExpr action`. See `doLetArrowToCode` match isDoExpr? doElem with | some action => let action ← withRef action `(($action : $((← read).m) $type)) ``(Bind.bind $action (fun ($id:ident : $type) => $k)) | none => Macro.throwErrorAt decl "unexpected kind of 'do' declaration" else Macro.throwErrorAt decl "unexpected kind of 'do' declaration" else if kind == `Lean.Parser.Term.doHave then -- The `have` term is of the form `"have " >> haveDecl >> optSemicolon termParser` let args := decl.getArgs let args := args ++ #[mkNullNode /- optional ';' -/, k] pure $ mkNode `Lean.Parser.Term.«have» args else Macro.throwErrorAt decl "unexpected kind of 'do' declaration" def reassignToTerm (reassign : Syntax) (k : Syntax) : MacroM Syntax := withRef reassign <| withFreshMacroScope do let kind := reassign.getKind if kind == `Lean.Parser.Term.doReassign then -- doReassign := leading_parser (letIdDecl <|> letPatDecl) let arg := reassign[0] if arg.getKind == `Lean.Parser.Term.letIdDecl then -- letIdDecl := leading_parser ident >> many (ppSpace >> bracketedBinder) >> optType >> " := " >> termParser let x := arg[0] let val := arg[4] let newVal ← `(ensureTypeOf% $x $(quote "invalid reassignment, value") $val) let arg := arg.setArg 4 newVal let letDecl := mkNode `Lean.Parser.Term.letDecl #[arg] `(let $letDecl:letDecl; $k) else -- TODO: ensure the types did not change let letDecl := mkNode `Lean.Parser.Term.letDecl #[arg] `(let $letDecl:letDecl; $k) else -- Note that `doReassignArrow` is expanded by `doReassignArrowToCode Macro.throwErrorAt reassign "unexpected kind of 'do' reassignment" def mkIte (optIdent : Syntax) (cond : Syntax) (thenBranch : Syntax) (elseBranch : Syntax) : MacroM Syntax := do if optIdent.isNone then ``(ite $cond $thenBranch $elseBranch) else let h := optIdent[0] ``(dite $cond (fun $h => $thenBranch) (fun $h => $elseBranch)) def mkJoinPoint (j : Name) (ps : Array (Name × Bool)) (body : Syntax) (k : Syntax) : M Syntax := withRef body <| withFreshMacroScope do let pTypes ← ps.mapM fun ⟨id, useTypeOf⟩ => do if useTypeOf then `(typeOf% $(← mkIdentFromRef id)) else `(_) let ps ← ps.mapM fun ⟨id, useTypeOf⟩ => mkIdentFromRef id /- We use `let_delayed` instead of `let` for joinpoints to make sure `$k` is elaborated before `$body`. By elaborating `$k` first, we "learn" more about `$body`'s type. For example, consider the following example `do` expression ``` def f (x : Nat) : IO Unit := do if x > 0 then IO.println "x is not zero" -- Error is here IO.mkRef true ``` it is expanded into ``` def f (x : Nat) : IO Unit := do let jp (u : Unit) : IO _ := IO.mkRef true; if x > 0 then IO.println "not zero" jp () else jp () ``` If we use the regular `let` instead of `let_delayed`, the joinpoint `jp` will be elaborated and its type will be inferred to be `Unit → IO (IO.Ref Bool)`. Then, we get a typing error at `jp ()`. By using `let_delayed`, we first elaborate `if x > 0 ...` and learn that `jp` has type `Unit → IO Unit`. Then, we get the expected type mismatch error at `IO.mkRef true`. -/ `(let_delayed $(← mkIdentFromRef j):ident $[($ps : $pTypes)]* : $((← read).m) _ := $body; $k) def mkJmp (ref : Syntax) (j : Name) (args : Array Syntax) : Syntax := Syntax.mkApp (mkIdentFrom ref j) args partial def toTerm : Code → M Syntax | Code.«return» ref val => withRef ref <| returnToTerm val | Code.«continue» ref => withRef ref continueToTerm | Code.«break» ref => withRef ref breakToTerm | Code.action e => actionTerminalToTerm e | Code.joinpoint j ps b k => do mkJoinPoint j ps (← toTerm b) (← toTerm k) | Code.jmp ref j args => pure $ mkJmp ref j args | Code.decl _ stx k => do declToTerm stx (← toTerm k) | Code.reassign _ stx k => do reassignToTerm stx (← toTerm k) | Code.seq stx k => do seqToTerm stx (← toTerm k) | Code.ite ref _ o c t e => withRef ref <| do mkIte o c (← toTerm t) (← toTerm e) | Code.«match» ref genParam discrs optType alts => do let mut termAlts := #[] for alt in alts do let rhs ← toTerm alt.rhs let termAlt := mkNode `Lean.Parser.Term.matchAlt #[mkAtomFrom alt.ref "|", alt.patterns, mkAtomFrom alt.ref "=>", rhs] termAlts := termAlts.push termAlt let termMatchAlts := mkNode `Lean.Parser.Term.matchAlts #[mkNullNode termAlts] pure $ mkNode `Lean.Parser.Term.«match» #[mkAtomFrom ref "match", genParam, discrs, optType, mkAtomFrom ref "with", termMatchAlts] def run (code : Code) (m : Syntax) (uvars : Array Name := #[]) (kind := Kind.regular) : MacroM Syntax := do let term ← toTerm code { m := m, kind := kind, uvars := uvars } pure term /- Given - `a` is true if the code block has a `Code.action _` exit point - `r` is true if the code block has a `Code.return _ _` exit point - `bc` is true if the code block has a `Code.break _` or `Code.continue _` exit point generate Kind. See comment at the beginning of the `ToTerm` namespace. -/ def mkNestedKind (a r bc : Bool) : Kind := match a, r, bc with | true, false, false => Kind.regular | false, true, false => Kind.regular | false, false, true => Kind.nestedBC | true, true, false => Kind.nestedPR | true, false, true => Kind.nestedSBC | false, true, true => Kind.nestedSBC | true, true, true => Kind.nestedPRBC | false, false, false => unreachable! def mkNestedTerm (code : Code) (m : Syntax) (uvars : Array Name) (a r bc : Bool) : MacroM Syntax := do ToTerm.run code m uvars (mkNestedKind a r bc) /- Given a term `term` produced by `ToTerm.run`, pattern match on its result. See comment at the beginning of the `ToTerm` namespace. - `a` is true if the code block has a `Code.action _` exit point - `r` is true if the code block has a `Code.return _ _` exit point - `bc` is true if the code block has a `Code.break _` or `Code.continue _` exit point The result is a sequence of `doElem` -/ def matchNestedTermResult (term : Syntax) (uvars : Array Name) (a r bc : Bool) : MacroM (List Syntax) := do let toDoElems (auxDo : Syntax) : List Syntax := getDoSeqElems (getDoSeq auxDo) let u ← mkTuple (← uvars.mapM mkIdentFromRef) match a, r, bc with | true, false, false => if uvars.isEmpty then toDoElems (← `(do $term:term)) else toDoElems (← `(do let r ← $term:term; $u:term := r.2; pure r.1)) | false, true, false => if uvars.isEmpty then toDoElems (← `(do let r ← $term:term; return r)) else toDoElems (← `(do let r ← $term:term; $u:term := r.2; return r.1)) | false, false, true => toDoElems <$> `(do let r ← $term:term; match r with | DoResultBC.«break» u => $u:term := u; break | DoResultBC.«continue» u => $u:term := u; continue) | true, true, false => toDoElems <$> `(do let r ← $term:term; match r with | DoResultPR.«pure» a u => $u:term := u; pure a | DoResultPR.«return» b u => $u:term := u; return b) | true, false, true => toDoElems <$> `(do let r ← $term:term; match r with | DoResultSBC.«pureReturn» a u => $u:term := u; pure a | DoResultSBC.«break» u => $u:term := u; break | DoResultSBC.«continue» u => $u:term := u; continue) | false, true, true => toDoElems <$> `(do let r ← $term:term; match r with | DoResultSBC.«pureReturn» a u => $u:term := u; return a | DoResultSBC.«break» u => $u:term := u; break | DoResultSBC.«continue» u => $u:term := u; continue) | true, true, true => toDoElems <$> `(do let r ← $term:term; match r with | DoResultPRBC.«pure» a u => $u:term := u; pure a | DoResultPRBC.«return» a u => $u:term := u; return a | DoResultPRBC.«break» u => $u:term := u; break | DoResultPRBC.«continue» u => $u:term := u; continue) | false, false, false => unreachable! end ToTerm def isMutableLet (doElem : Syntax) : Bool := let kind := doElem.getKind (kind == `Lean.Parser.Term.doLetArrow || kind == `Lean.Parser.Term.doLet) && !doElem[1].isNone namespace ToCodeBlock structure Context where ref : Syntax m : Syntax -- Syntax representing the monad associated with the do notation. mutableVars : NameSet := {} insideFor : Bool := false abbrev M := ReaderT Context TermElabM @[inline] def withNewMutableVars {α} (newVars : Array Name) (mutable : Bool) (x : M α) : M α := withReader (fun ctx => if mutable then { ctx with mutableVars := insertVars ctx.mutableVars newVars } else ctx) x def checkReassignable (xs : Array Name) : M Unit := do let throwInvalidReassignment (x : Name) : M Unit := throwError "'{x.simpMacroScopes}' cannot be reassigned" let ctx ← read for x in xs do unless ctx.mutableVars.contains x do throwInvalidReassignment x def checkNotShadowingMutable (xs : Array Name) : M Unit := do let throwInvalidShadowing (x : Name) : M Unit := throwError "mutable variable '{x.simpMacroScopes}' cannot be shadowed" let ctx ← read for x in xs do if ctx.mutableVars.contains x then throwInvalidShadowing x @[inline] def withFor {α} (x : M α) : M α := withReader (fun ctx => { ctx with insideFor := true }) x structure ToForInTermResult where uvars : Array Name term : Syntax def mkForInBody (x : Syntax) (forInBody : CodeBlock) : M ToForInTermResult := do let ctx ← read let uvars := forInBody.uvars let uvars := nameSetToArray uvars let term ← liftMacroM $ ToTerm.run forInBody.code ctx.m uvars (if hasReturn forInBody.code then ToTerm.Kind.forInWithReturn else ToTerm.Kind.forIn) pure ⟨uvars, term⟩ def ensureInsideFor : M Unit := unless (← read).insideFor do throwError "invalid 'do' element, it must be inside 'for'" def ensureEOS (doElems : List Syntax) : M Unit := unless doElems.isEmpty do throwError "must be last element in a 'do' sequence" private partial def expandLiftMethodAux (inQuot : Bool) (inBinder : Bool) : Syntax → StateT (List Syntax) MacroM Syntax | stx@(Syntax.node k args) => if liftMethodDelimiter k then return stx else if k == `Lean.Parser.Term.liftMethod && !inQuot then withFreshMacroScope do if inBinder then Macro.throwErrorAt stx "cannot lift `(<- ...)` over a binder, this error usually happens when you are trying to lift a method nested in a `fun`, `let`, or `match`-alternative, and it can often be fixed by adding a missing `do`" let term := args[1] let term ← expandLiftMethodAux inQuot inBinder term let auxDoElem ← `(doElem| let a ← $term:term) modify fun s => s ++ [auxDoElem] `(a) else do let inAntiquot := stx.isAntiquot && !stx.isEscapedAntiquot let inBinder := inBinder || (!inQuot && liftMethodForbiddenBinder stx) let args ← args.mapM (expandLiftMethodAux (inQuot && !inAntiquot || stx.isQuot) inBinder) return Syntax.node k args | stx => pure stx def expandLiftMethod (doElem : Syntax) : MacroM (List Syntax × Syntax) := do if !hasLiftMethod doElem then pure ([], doElem) else let (doElem, doElemsNew) ← (expandLiftMethodAux false false doElem).run [] pure (doElemsNew, doElem) def checkLetArrowRHS (doElem : Syntax) : M Unit := do let kind := doElem.getKind if kind == `Lean.Parser.Term.doLetArrow || kind == `Lean.Parser.Term.doLet || kind == `Lean.Parser.Term.doLetRec || kind == `Lean.Parser.Term.doHave || kind == `Lean.Parser.Term.doReassign || kind == `Lean.Parser.Term.doReassignArrow then throwErrorAt doElem "invalid kind of value '{kind}' in an assignment" /- Generate `CodeBlock` for `doReturn` which is of the form ``` "return " >> optional termParser ``` `doElems` is only used for sanity checking. -/ def doReturnToCode (doReturn : Syntax) (doElems: List Syntax) : M CodeBlock := withRef doReturn do ensureEOS doElems let argOpt := doReturn[1] let arg ← if argOpt.isNone then liftMacroM mkUnit else pure argOpt[0] return mkReturn (← getRef) arg structure Catch where x : Syntax optType : Syntax codeBlock : CodeBlock def getTryCatchUpdatedVars (tryCode : CodeBlock) (catches : Array Catch) (finallyCode? : Option CodeBlock) : NameSet := let ws := tryCode.uvars let ws := catches.foldl (fun ws alt => union alt.codeBlock.uvars ws) ws let ws := match finallyCode? with | none => ws | some c => union c.uvars ws ws def tryCatchPred (tryCode : CodeBlock) (catches : Array Catch) (finallyCode? : Option CodeBlock) (p : Code → Bool) : Bool := p tryCode.code || catches.any (fun «catch» => p «catch».codeBlock.code) || match finallyCode? with | none => false | some finallyCode => p finallyCode.code mutual /- "Concatenate" `c` with `doSeqToCode doElems` -/ partial def concatWith (c : CodeBlock) (doElems : List Syntax) : M CodeBlock := match doElems with | [] => pure c | nextDoElem :: _ => do let k ← doSeqToCode doElems let ref := nextDoElem concat c ref none k /- Generate `CodeBlock` for `doLetArrow; doElems` `doLetArrow` is of the form ``` "let " >> optional "mut " >> (doIdDecl <|> doPatDecl) ``` where ``` def doIdDecl := leading_parser ident >> optType >> leftArrow >> doElemParser def doPatDecl := leading_parser termParser >> leftArrow >> doElemParser >> optional (" | " >> doElemParser) ``` -/ partial def doLetArrowToCode (doLetArrow : Syntax) (doElems : List Syntax) : M CodeBlock := do let ref := doLetArrow let decl := doLetArrow[2] if decl.getKind == `Lean.Parser.Term.doIdDecl then let y := decl[0].getId checkNotShadowingMutable #[y] let doElem := decl[3] let k ← withNewMutableVars #[y] (isMutableLet doLetArrow) (doSeqToCode doElems) match isDoExpr? doElem with | some action => pure $ mkVarDeclCore #[y] doLetArrow k | none => checkLetArrowRHS doElem let c ← doSeqToCode [doElem] match doElems with | [] => pure c | kRef::_ => concat c kRef y k else if decl.getKind == `Lean.Parser.Term.doPatDecl then let pattern := decl[0] let doElem := decl[2] let optElse := decl[3] if optElse.isNone then withFreshMacroScope do let auxDo ← if isMutableLet doLetArrow then `(do let discr ← $doElem; let mut $pattern:term := discr) else `(do let discr ← $doElem; let $pattern:term := discr) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems else if isMutableLet doLetArrow then throwError "'mut' is currently not supported in let-decls with 'else' case" let contSeq := mkDoSeq doElems.toArray let elseSeq := mkSingletonDoSeq optElse[1] let auxDo ← `(do let discr ← $doElem; match discr with | $pattern:term => $contSeq | _ => $elseSeq) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) else throwError "unexpected kind of 'do' declaration" /- Generate `CodeBlock` for `doReassignArrow; doElems` `doReassignArrow` is of the form ``` (doIdDecl <|> doPatDecl) ``` -/ partial def doReassignArrowToCode (doReassignArrow : Syntax) (doElems : List Syntax) : M CodeBlock := do let ref := doReassignArrow let decl := doReassignArrow[0] if decl.getKind == `Lean.Parser.Term.doIdDecl then let doElem := decl[3] let y := decl[0] let auxDo ← `(do let r ← $doElem; $y:ident := r) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems else if decl.getKind == `Lean.Parser.Term.doPatDecl then let pattern := decl[0] let doElem := decl[2] let optElse := decl[3] if optElse.isNone then withFreshMacroScope do let auxDo ← `(do let discr ← $doElem; $pattern:term := discr) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems else throwError "reassignment with `|` (i.e., \"else clause\") is not currently supported" else throwError "unexpected kind of 'do' reassignment" /- Generate `CodeBlock` for `doIf; doElems` `doIf` is of the form ``` "if " >> optIdent >> termParser >> " then " >> doSeq >> many (group (try (group (" else " >> " if ")) >> optIdent >> termParser >> " then " >> doSeq)) >> optional (" else " >> doSeq) ``` -/ partial def doIfToCode (doIf : Syntax) (doElems : List Syntax) : M CodeBlock := do let view ← liftMacroM $ mkDoIfView doIf let thenBranch ← doSeqToCode (getDoSeqElems view.thenBranch) let elseBranch ← doSeqToCode (getDoSeqElems view.elseBranch) let ite ← mkIte view.ref view.optIdent view.cond thenBranch elseBranch concatWith ite doElems /- Generate `CodeBlock` for `doUnless; doElems` `doUnless` is of the form ``` "unless " >> termParser >> "do " >> doSeq ``` -/ partial def doUnlessToCode (doUnless : Syntax) (doElems : List Syntax) : M CodeBlock := withRef doUnless do let ref := doUnless let cond := doUnless[1] let doSeq := doUnless[3] let body ← doSeqToCode (getDoSeqElems doSeq) let unlessCode ← liftMacroM <| mkUnless cond body concatWith unlessCode doElems /- Generate `CodeBlock` for `doFor; doElems` `doFor` is of the form ``` def doForDecl := leading_parser termParser >> " in " >> withForbidden "do" termParser def doFor := leading_parser "for " >> sepBy1 doForDecl ", " >> "do " >> doSeq ``` -/ partial def doForToCode (doFor : Syntax) (doElems : List Syntax) : M CodeBlock := do let doForDecls := doFor[1].getSepArgs if doForDecls.size > 1 then /- Expand ``` for x in xs, y in ys do body ``` into ``` let s := toStream ys for x in xs do match Stream.next? s with | none => break | some (y, s') => s := s' body ``` -/ -- Extract second element let doForDecl := doForDecls[1] let y := doForDecl[0] let ys := doForDecl[2] let doForDecls := doForDecls.eraseIdx 1 let body := doFor[3] withFreshMacroScope do let toStreamFn ← withRef ys ``(toStream) let auxDo ← `(do let mut s := $toStreamFn:ident $ys for $doForDecls:doForDecl,* do match Stream.next? s with | none => break | some ($y, s') => s := s' do $body) doSeqToCode (getDoSeqElems (getDoSeq auxDo) ++ doElems) else withRef doFor do let x := doForDecls[0][0] withRef x <| checkNotShadowingMutable (← getPatternVarsEx x) let xs := doForDecls[0][2] let forElems := getDoSeqElems doFor[3] let forInBodyCodeBlock ← withFor (doSeqToCode forElems) let ⟨uvars, forInBody⟩ ← mkForInBody x forInBodyCodeBlock let uvarsTuple ← liftMacroM do mkTuple (← uvars.mapM mkIdentFromRef) if hasReturn forInBodyCodeBlock.code then let forInBody ← liftMacroM <| destructTuple uvars (← `(r)) forInBody let forInTerm ← `(forIn% $(xs) (MProd.mk none $uvarsTuple) fun $x r => let r := r.2; $forInBody) let auxDo ← `(do let r ← $forInTerm:term; $uvarsTuple:term := r.2; match r.1 with | none => Pure.pure (ensureExpectedType% "type mismatch, 'for'" PUnit.unit) | some a => return ensureExpectedType% "type mismatch, 'for'" a) doSeqToCode (getDoSeqElems (getDoSeq auxDo) ++ doElems) else let forInBody ← liftMacroM <| destructTuple uvars (← `(r)) forInBody let forInTerm ← `(forIn% $(xs) $uvarsTuple fun $x r => $forInBody) if doElems.isEmpty then let auxDo ← `(do let r ← $forInTerm:term; $uvarsTuple:term := r; Pure.pure (ensureExpectedType% "type mismatch, 'for'" PUnit.unit)) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) else let auxDo ← `(do let r ← $forInTerm:term; $uvarsTuple:term := r) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems /-- Generate `CodeBlock` for `doMatch; doElems` -/ partial def doMatchToCode (doMatch : Syntax) (doElems: List Syntax) : M CodeBlock := do let ref := doMatch let genParam := doMatch[1] let discrs := doMatch[2] let optType := doMatch[3] let matchAlts := doMatch[5][0].getArgs -- Array of `doMatchAlt` let alts ← matchAlts.mapM fun matchAlt => do let patterns := matchAlt[1] let vars ← getPatternsVarsEx patterns.getSepArgs withRef patterns <| checkNotShadowingMutable vars let rhs := matchAlt[3] let rhs ← doSeqToCode (getDoSeqElems rhs) pure { ref := matchAlt, vars := vars, patterns := patterns, rhs := rhs : Alt CodeBlock } let matchCode ← mkMatch ref genParam discrs optType alts concatWith matchCode doElems /-- Generate `CodeBlock` for `doTry; doElems` ``` def doTry := leading_parser "try " >> doSeq >> many (doCatch <|> doCatchMatch) >> optional doFinally def doCatch := leading_parser "catch " >> binderIdent >> optional (":" >> termParser) >> darrow >> doSeq def doCatchMatch := leading_parser "catch " >> doMatchAlts def doFinally := leading_parser "finally " >> doSeq ``` -/ partial def doTryToCode (doTry : Syntax) (doElems: List Syntax) : M CodeBlock := do let ref := doTry let tryCode ← doSeqToCode (getDoSeqElems doTry[1]) let optFinally := doTry[3] let catches ← doTry[2].getArgs.mapM fun catchStx => do if catchStx.getKind == `Lean.Parser.Term.doCatch then let x := catchStx[1] if x.isIdent then withRef x <| checkNotShadowingMutable #[x.getId] let optType := catchStx[2] let c ← doSeqToCode (getDoSeqElems catchStx[4]) pure { x := x, optType := optType, codeBlock := c : Catch } else if catchStx.getKind == `Lean.Parser.Term.doCatchMatch then let matchAlts := catchStx[1] let x ← `(ex) let auxDo ← `(do match ex with $matchAlts) let c ← doSeqToCode (getDoSeqElems (getDoSeq auxDo)) pure { x := x, codeBlock := c, optType := mkNullNode : Catch } else throwError "unexpected kind of 'catch'" let finallyCode? ← if optFinally.isNone then pure none else some <$> doSeqToCode (getDoSeqElems optFinally[0][1]) if catches.isEmpty && finallyCode?.isNone then throwError "invalid 'try', it must have a 'catch' or 'finally'" let ctx ← read let ws := getTryCatchUpdatedVars tryCode catches finallyCode? let uvars := nameSetToArray ws let a := tryCatchPred tryCode catches finallyCode? hasTerminalAction let r := tryCatchPred tryCode catches finallyCode? hasReturn let bc := tryCatchPred tryCode catches finallyCode? hasBreakContinue let toTerm (codeBlock : CodeBlock) : M Syntax := do let codeBlock ← liftM $ extendUpdatedVars codeBlock ws liftMacroM $ ToTerm.mkNestedTerm codeBlock.code ctx.m uvars a r bc let term ← toTerm tryCode let term ← catches.foldlM (fun term «catch» => do let catchTerm ← toTerm «catch».codeBlock if catch.optType.isNone then ``(MonadExcept.tryCatch $term (fun $(«catch».x):ident => $catchTerm)) else let type := «catch».optType[1] ``(tryCatchThe $type $term (fun $(«catch».x):ident => $catchTerm))) term let term ← match finallyCode? with | none => pure term | some finallyCode => withRef optFinally do unless finallyCode.uvars.isEmpty do throwError "'finally' currently does not support reassignments" if hasBreakContinueReturn finallyCode.code then throwError "'finally' currently does 'return', 'break', nor 'continue'" let finallyTerm ← liftMacroM <| ToTerm.run finallyCode.code ctx.m {} ToTerm.Kind.regular ``(tryFinally $term $finallyTerm) let doElemsNew ← liftMacroM <| ToTerm.matchNestedTermResult term uvars a r bc doSeqToCode (doElemsNew ++ doElems) partial def doSeqToCode : List Syntax → M CodeBlock | [] => do liftMacroM mkPureUnitAction | doElem::doElems => withIncRecDepth <| withRef doElem do checkMaxHeartbeats "'do'-expander" match (← liftMacroM <| expandMacro? doElem) with | some doElem => doSeqToCode (doElem::doElems) | none => match (← liftMacroM <| expandDoIf? doElem) with | some doElem => doSeqToCode (doElem::doElems) | none => let (liftedDoElems, doElem) ← liftM (liftMacroM <| expandLiftMethod doElem : TermElabM _) if !liftedDoElems.isEmpty then doSeqToCode (liftedDoElems ++ [doElem] ++ doElems) else let ref := doElem let concatWithRest (c : CodeBlock) : M CodeBlock := concatWith c doElems let k := doElem.getKind if k == `Lean.Parser.Term.doLet then let vars ← getDoLetVars doElem checkNotShadowingMutable vars mkVarDeclCore vars doElem <$> withNewMutableVars vars (isMutableLet doElem) (doSeqToCode doElems) else if k == `Lean.Parser.Term.doHave then let var := getDoHaveVar doElem checkNotShadowingMutable #[var] mkVarDeclCore #[var] doElem <$> (doSeqToCode doElems) else if k == `Lean.Parser.Term.doLetRec then let vars ← getDoLetRecVars doElem checkNotShadowingMutable vars mkVarDeclCore vars doElem <$> (doSeqToCode doElems) else if k == `Lean.Parser.Term.doReassign then let vars ← getDoReassignVars doElem checkReassignable vars let k ← doSeqToCode doElems mkReassignCore vars doElem k else if k == `Lean.Parser.Term.doLetArrow then doLetArrowToCode doElem doElems else if k == `Lean.Parser.Term.doReassignArrow then doReassignArrowToCode doElem doElems else if k == `Lean.Parser.Term.doIf then doIfToCode doElem doElems else if k == `Lean.Parser.Term.doUnless then doUnlessToCode doElem doElems else if k == `Lean.Parser.Term.doFor then withFreshMacroScope do doForToCode doElem doElems else if k == `Lean.Parser.Term.doMatch then doMatchToCode doElem doElems else if k == `Lean.Parser.Term.doTry then doTryToCode doElem doElems else if k == `Lean.Parser.Term.doBreak then ensureInsideFor ensureEOS doElems return mkBreak ref else if k == `Lean.Parser.Term.doContinue then ensureInsideFor ensureEOS doElems return mkContinue ref else if k == `Lean.Parser.Term.doReturn then doReturnToCode doElem doElems else if k == `Lean.Parser.Term.doDbgTrace then return mkSeq doElem (← doSeqToCode doElems) else if k == `Lean.Parser.Term.doAssert then return mkSeq doElem (← doSeqToCode doElems) else if k == `Lean.Parser.Term.doNested then let nestedDoSeq := doElem[1] doSeqToCode (getDoSeqElems nestedDoSeq ++ doElems) else if k == `Lean.Parser.Term.doExpr then let term := doElem[0] if doElems.isEmpty then return mkTerminalAction term else return mkSeq term (← doSeqToCode doElems) else throwError "unexpected do-element of kind {doElem.getKind}:\n{doElem}" end def run (doStx : Syntax) (m : Syntax) : TermElabM CodeBlock := (doSeqToCode <| getDoSeqElems <| getDoSeq doStx).run { ref := doStx, m := m } end ToCodeBlock /- Create a synthetic metavariable `?m` and assign `m` to it. We use `?m` to refer to `m` when expanding the `do` notation. -/ private def mkMonadAlias (m : Expr) : TermElabM Syntax := do let result ← `(?m) let mType ← inferType m let mvar ← elabTerm result mType assignExprMVar mvar.mvarId! m pure result @[builtinTermElab «do»] def elabDo : TermElab := fun stx expectedType? => do tryPostponeIfNoneOrMVar expectedType? let bindInfo ← extractBind expectedType? let m ← mkMonadAlias bindInfo.m let codeBlock ← ToCodeBlock.run stx m let stxNew ← liftMacroM $ ToTerm.run codeBlock.code m trace[Elab.do] stxNew withMacroExpansion stx stxNew $ elabTermEnsuringType stxNew bindInfo.expectedType end Do builtin_initialize registerTraceClass `Elab.do private def toDoElem (newKind : SyntaxNodeKind) : Macro := fun stx => do let stx := stx.setKind newKind withRef stx `(do $stx:doElem) @[builtinMacro Lean.Parser.Term.termFor] def expandTermFor : Macro := toDoElem `Lean.Parser.Term.doFor @[builtinMacro Lean.Parser.Term.termTry] def expandTermTry : Macro := toDoElem `Lean.Parser.Term.doTry @[builtinMacro Lean.Parser.Term.termUnless] def expandTermUnless : Macro := toDoElem `Lean.Parser.Term.doUnless @[builtinMacro Lean.Parser.Term.termReturn] def expandTermReturn : Macro := toDoElem `Lean.Parser.Term.doReturn end Lean.Elab.Term
b717d9b7c13a103a2fe63b6c8ecfb8845dceae85
bdb33f8b7ea65f7705fc342a178508e2722eb851
/data/quot.lean
6d879f039b222d68575aa2690046a7eb086714a7
[ "Apache-2.0" ]
permissive
rwbarton/mathlib
939ae09bf8d6eb1331fc2f7e067d39567e10e33d
c13c5ea701bb1eec057e0a242d9f480a079105e9
refs/heads/master
1,584,015,335,862
1,524,142,167,000
1,524,142,167,000
130,614,171
0
0
Apache-2.0
1,548,902,667,000
1,524,437,371,000
Lean
UTF-8
Lean
false
false
4,417
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 Quotients -- extends the core library -/ variables {α : Sort*} {β : Sort*} @[simp] theorem quotient.eq [r : setoid α] {x y : α} : ⟦x⟧ = ⟦y⟧ ↔ x ≈ y := ⟨quotient.exact, quotient.sound⟩ theorem forall_quotient_iff {α : Type*} [r : setoid α] {p : quotient r → Prop} : (∀a:quotient r, p a) ↔ (∀a:α, p ⟦a⟧) := ⟨assume h x, h _, assume h a, a.induction_on h⟩ @[simp] lemma quotient.lift_beta [s : setoid α] (f : α → β) (h : ∀ (a b : α), a ≈ b → f a = f b) (x : α): quotient.lift f h (quotient.mk x) = f x := rfl @[simp] lemma quotient.lift_on_beta [s : setoid α] (f : α → β) (h : ∀ (a b : α), a ≈ b → f a = f b) (x : α): quotient.lift_on (quotient.mk x) f h = f x := rfl /-- Choose an element of the equivalence class using the axiom of choice. Sound but noncomputable. -/ noncomputable def quot.out {r : α → α → Prop} (q : quot r) : α := classical.some (quot.exists_rep q) /-- Unwrap the VM representation of a quotient to obtain an element of the equivalence class. Computable but unsound. -/ meta def quot.unquot {r : α → α → Prop} : quot r → α := unchecked_cast @[simp] theorem quot.out_eq {r : α → α → Prop} (q : quot r) : quot.mk r q.out = q := classical.some_spec (quot.exists_rep q) /-- Choose an element of the equivalence class using the axiom of choice. Sound but noncomputable. -/ noncomputable def quotient.out [s : setoid α] : quotient s → α := quot.out @[simp] theorem quotient.out_eq [s : setoid α] (q : quotient s) : ⟦q.out⟧ = q := q.out_eq theorem quotient.mk_out [s : setoid α] (a : α) : ⟦a⟧.out ≈ a := quotient.exact (quotient.out_eq _) /-- `trunc α` is the quotient of `α` by the always-true relation. This is related to the propositional truncation in HoTT, and is similar in effect to `nonempty α`, but unlike `nonempty α`, `trunc α` is data, so the VM representation is the same as `α`, and so this can be used to maintain computability. -/ def {u} trunc (α : Sort u) : Sort u := @quot α (λ _ _, true) namespace trunc /-- Constructor for `trunc α` -/ def mk (a : α) : trunc α := quot.mk _ a /-- Any constant function lifts to a function out of the truncation -/ def lift (f : α → β) (c : ∀ a b : α, f a = f b) : trunc α → β := quot.lift f (λ a b _, c a b) theorem ind {β : trunc α → Prop} : (∀ a : α, β (mk a)) → ∀ q : trunc α, β q := quot.ind protected theorem lift_beta (f : α → β) (c) (a : α) : lift f c (mk a) = f a := rfl @[reducible, elab_as_eliminator] protected def lift_on (q : trunc α) (f : α → β) (c : ∀ a b : α, f a = f b) : β := lift f c q @[elab_as_eliminator] protected theorem induction_on {β : trunc α → Prop} (q : trunc α) (h : ∀ a, β (mk a)) : β q := ind h q theorem exists_rep (q : trunc α) : ∃ a : α, mk a = q := quot.exists_rep q attribute [elab_as_eliminator] protected theorem induction_on₂ {C : trunc α → trunc β → Prop} (q₁ : trunc α) (q₂ : trunc β) (h : ∀ a b, C (mk a) (mk b)) : C q₁ q₂ := trunc.induction_on q₁ $ λ a₁, trunc.induction_on q₂ (h a₁) protected theorem eq (a b : trunc α) : a = b := trunc.induction_on₂ a b (λ x y, quot.sound trivial) instance : subsingleton (trunc α) := ⟨trunc.eq⟩ variable {C : trunc α → Sort*} @[reducible, elab_as_eliminator] protected def rec (f : Π a, C (mk a)) (h : ∀ (a b : α), (eq.rec (f a) (trunc.eq (mk a) (mk b)) : C (mk b)) = f b) (q : trunc α) : C q := quot.rec f (λ a b _, h a b) q @[reducible, elab_as_eliminator] protected def rec_on (q : trunc α) (f : Π a, C (mk a)) (h : ∀ (a b : α), (eq.rec (f a) (trunc.eq (mk a) (mk b)) : C (mk b)) = f b) : C q := trunc.rec f h q @[reducible, elab_as_eliminator] protected def rec_on_subsingleton [∀ a, subsingleton (C (mk a))] (q : trunc α) (f : Π a, C (mk a)) : C q := trunc.rec f (λ a b, subsingleton.elim _ (f b)) q /-- Noncomputably extract a representative of `trunc α` (using the axiom of choice). -/ noncomputable def out : trunc α → α := quot.out @[simp] theorem out_eq (q : trunc α) : mk q.out = q := trunc.eq _ _ end trunc theorem nonempty_of_trunc (q : trunc α) : nonempty α := let ⟨a, _⟩ := q.exists_rep in ⟨a⟩
cf8037d7bf4f6fcfdd30754361a4f8b02da014ac
32317185abf7e7c963f4c67c190aec61af6b3628
/library/theories/analysis/real_limit.lean
9f7c9bf0c70bd3f607ed59da7e02a4af26577e37
[ "Apache-2.0" ]
permissive
Andrew-Zipperer-unorganized/lean
198a2317f21198cd8d26e7085e484b86277f17f7
dcb35008e1474a0abebe632b1dced120e5f8c009
refs/heads/master
1,622,526,520,945
1,453,576,559,000
1,454,612,842,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
25,106
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Robert Y. Lewis Instantiates the reals as a Banach space. -/ import .metric_space data.real.complete data.set .normed_space open real classical analysis nat noncomputable theory /- sup and inf -/ -- Expresses completeness, sup, and inf in a manner that is less constructive, but more convenient, -- than the way it is done in data.real.complete. -- Issue: real.sup and real.inf conflict with sup and inf in lattice. -- Perhaps put algebra sup and inf into a namespace? namespace real open set private definition exists_is_sup {X : set ℝ} (H : (∃ x, x ∈ X) ∧ (∃ b, ∀ x, x ∈ X → x ≤ b)) : ∃ y, is_sup X y := let x := some (and.left H), b := some (and.right H) in exists_is_sup_of_inh_of_bdd X x (some_spec (and.left H)) b (some_spec (and.right H)) private definition sup_aux {X : set ℝ} (H : (∃ x, x ∈ X) ∧ (∃ b, ∀ x, x ∈ X → x ≤ b)) := some (exists_is_sup H) private definition sup_aux_spec {X : set ℝ} (H : (∃ x, x ∈ X) ∧ (∃ b, ∀ x, x ∈ X → x ≤ b)) : is_sup X (sup_aux H) := some_spec (exists_is_sup H) definition sup (X : set ℝ) : ℝ := if H : (∃ x, x ∈ X) ∧ (∃ b, ∀ x, x ∈ X → x ≤ b) then sup_aux H else 0 proposition le_sup {x : ℝ} {X : set ℝ} (Hx : x ∈ X) {b : ℝ} (Hb : ∀ x, x ∈ X → x ≤ b) : x ≤ sup X := have H : (∃ x, x ∈ X) ∧ (∃ b, ∀ x, x ∈ X → x ≤ b), from and.intro (exists.intro x Hx) (exists.intro b Hb), by+ rewrite [↑sup, dif_pos H]; exact and.left (sup_aux_spec H) x Hx proposition sup_le {X : set ℝ} (HX : ∃ x, x ∈ X) {b : ℝ} (Hb : ∀ x, x ∈ X → x ≤ b) : sup X ≤ b := have H : (∃ x, x ∈ X) ∧ (∃ b, ∀ x, x ∈ X → x ≤ b), from and.intro HX (exists.intro b Hb), by+ rewrite [↑sup, dif_pos H]; exact and.right (sup_aux_spec H) b Hb proposition exists_mem_and_lt_of_lt_sup {X : set ℝ} (HX : ∃ x, x ∈ X) {b : ℝ} (Hb : b < sup X) : ∃ x, x ∈ X ∧ b < x := have ¬ ∀ x, x ∈ X → x ≤ b, from assume H, not_le_of_gt Hb (sup_le HX H), obtain x (Hx : ¬ (x ∈ X → x ≤ b)), from exists_not_of_not_forall this, exists.intro x (have x ∈ X ∧ ¬ x ≤ b, by rewrite [-not_implies_iff_and_not]; apply Hx, and.intro (and.left this) (lt_of_not_ge (and.right this))) private definition exists_is_inf {X : set ℝ} (H : (∃ x, x ∈ X) ∧ (∃ b, ∀ x, x ∈ X → b ≤ x)) : ∃ y, is_inf X y := let x := some (and.left H), b := some (and.right H) in exists_is_inf_of_inh_of_bdd X x (some_spec (and.left H)) b (some_spec (and.right H)) private definition inf_aux {X : set ℝ} (H : (∃ x, x ∈ X) ∧ (∃ b, ∀ x, x ∈ X → b ≤ x)) := some (exists_is_inf H) private definition inf_aux_spec {X : set ℝ} (H : (∃ x, x ∈ X) ∧ (∃ b, ∀ x, x ∈ X → b ≤ x)) : is_inf X (inf_aux H) := some_spec (exists_is_inf H) definition inf (X : set ℝ) : ℝ := if H : (∃ x, x ∈ X) ∧ (∃ b, ∀ x, x ∈ X → b ≤ x) then inf_aux H else 0 proposition inf_le {x : ℝ} {X : set ℝ} (Hx : x ∈ X) {b : ℝ} (Hb : ∀ x, x ∈ X → b ≤ x) : inf X ≤ x := have H : (∃ x, x ∈ X) ∧ (∃ b, ∀ x, x ∈ X → b ≤ x), from and.intro (exists.intro x Hx) (exists.intro b Hb), by+ rewrite [↑inf, dif_pos H]; exact and.left (inf_aux_spec H) x Hx proposition le_inf {X : set ℝ} (HX : ∃ x, x ∈ X) {b : ℝ} (Hb : ∀ x, x ∈ X → b ≤ x) : b ≤ inf X := have H : (∃ x, x ∈ X) ∧ (∃ b, ∀ x, x ∈ X → b ≤ x), from and.intro HX (exists.intro b Hb), by+ rewrite [↑inf, dif_pos H]; exact and.right (inf_aux_spec H) b Hb proposition exists_mem_and_lt_of_inf_lt {X : set ℝ} (HX : ∃ x, x ∈ X) {b : ℝ} (Hb : inf X < b) : ∃ x, x ∈ X ∧ x < b := have ¬ ∀ x, x ∈ X → b ≤ x, from assume H, not_le_of_gt Hb (le_inf HX H), obtain x (Hx : ¬ (x ∈ X → b ≤ x)), from exists_not_of_not_forall this, exists.intro x (have x ∈ X ∧ ¬ b ≤ x, by rewrite [-not_implies_iff_and_not]; apply Hx, and.intro (and.left this) (lt_of_not_ge (and.right this))) section local attribute mem [quasireducible] -- TODO: is there a better place to put this? proposition image_neg_eq (X : set ℝ) : (λ x, -x) ' X = {x | -x ∈ X} := set.ext (take x, iff.intro (assume H, obtain y [(Hy₁ : y ∈ X) (Hy₂ : -y = x)], from H, show -x ∈ X, by rewrite [-Hy₂, neg_neg]; exact Hy₁) (assume H : -x ∈ X, exists.intro (-x) (and.intro H !neg_neg))) proposition sup_neg {X : set ℝ} (nonempty_X : ∃ x, x ∈ X) {b : ℝ} (Hb : ∀ x, x ∈ X → b ≤ x) : sup {x | -x ∈ X} = - inf X := let negX := {x | -x ∈ X} in have nonempty_negX : ∃ x, x ∈ negX, from obtain x Hx, from nonempty_X, have -(-x) ∈ X, by rewrite neg_neg; apply Hx, exists.intro (-x) this, have H₁ : ∀ x, x ∈ negX → x ≤ - inf X, from take x, assume H, have inf X ≤ -x, from inf_le H Hb, show x ≤ - inf X, from le_neg_of_le_neg this, have H₂ : ∀ x, x ∈ X → -sup negX ≤ x, from take x, assume H, have -(-x) ∈ X, by rewrite neg_neg; apply H, have -x ≤ sup negX, from le_sup this H₁, show -sup negX ≤ x, from !neg_le_of_neg_le this, eq_of_le_of_ge (show sup negX ≤ - inf X, from sup_le nonempty_negX H₁) (show -inf X ≤ sup negX, from !neg_le_of_neg_le (le_inf nonempty_X H₂)) proposition inf_neg {X : set ℝ} (nonempty_X : ∃ x, x ∈ X) {b : ℝ} (Hb : ∀ x, x ∈ X → x ≤ b) : inf {x | -x ∈ X} = - sup X := let negX := {x | -x ∈ X} in have nonempty_negX : ∃ x, x ∈ negX, from obtain x Hx, from nonempty_X, have -(-x) ∈ X, by rewrite neg_neg; apply Hx, exists.intro (-x) this, have Hb' : ∀ x, x ∈ negX → -b ≤ x, from take x, assume H, !neg_le_of_neg_le (Hb _ H), have HX : X = {x | -x ∈ negX}, from set.ext (take x, by rewrite [↑set_of, ↑mem, +neg_neg]), show inf {x | -x ∈ X} = - sup X, using HX Hb' nonempty_negX, by rewrite [HX at {2}, sup_neg nonempty_negX Hb', neg_neg] end end real /- the reals form a complete metric space -/ namespace analysis theorem dist_eq_abs (x y : real) : dist x y = abs (x - y) := rfl proposition converges_to_seq_real_intro {X : ℕ → ℝ} {y : ℝ} (H : ∀ ⦃ε : ℝ⦄, ε > 0 → ∃ N : ℕ, ∀ {n}, n ≥ N → abs (X n - y) < ε) : (X ⟶ y in ℕ) := H proposition converges_to_seq_real_elim {X : ℕ → ℝ} {y : ℝ} (H : X ⟶ y in ℕ) : ∀ ⦃ε : ℝ⦄, ε > 0 → ∃ N : ℕ, ∀ {n}, n ≥ N → abs (X n - y) < ε := H proposition converges_to_seq_real_intro' {X : ℕ → ℝ} {y : ℝ} (H : ∀ ⦃ε : ℝ⦄, ε > 0 → ∃ N : ℕ, ∀ {n}, n ≥ N → abs (X n - y) ≤ ε) : converges_to_seq X y := converges_to_seq.intro H open pnat subtype local postfix ⁻¹ := pnat.inv private definition pnat.succ (n : ℕ) : ℕ+ := tag (succ n) !succ_pos private definition r_seq_of (X : ℕ → ℝ) : r_seq := λ n, X (elt_of n) private lemma rate_of_cauchy_aux {X : ℕ → ℝ} (H : cauchy X) : ∀ k : ℕ+, ∃ N : ℕ+, ∀ m n : ℕ+, m ≥ N → n ≥ N → abs (X (elt_of m) - X (elt_of n)) ≤ of_rat k⁻¹ := take k : ℕ+, have H1 : (k⁻¹ >[rat] (rat.of_num 0)), from !pnat.inv_pos, have H2 : (of_rat k⁻¹ > of_rat (rat.of_num 0)), from !of_rat_lt_of_rat_of_lt H1, obtain (N : ℕ) (H : ∀ m n, m ≥ N → n ≥ N → abs (X m - X n) < of_rat k⁻¹), from H _ H2, exists.intro (pnat.succ N) (take m n : ℕ+, assume Hm : m ≥ (pnat.succ N), assume Hn : n ≥ (pnat.succ N), have Hm' : elt_of m ≥ N, begin apply le.trans, apply le_succ, apply Hm end, have Hn' : elt_of n ≥ N, begin apply le.trans, apply le_succ, apply Hn end, show abs (X (elt_of m) - X (elt_of n)) ≤ of_rat k⁻¹, from le_of_lt (H _ _ Hm' Hn')) private definition rate_of_cauchy {X : ℕ → ℝ} (H : cauchy X) (k : ℕ+) : ℕ+ := some (rate_of_cauchy_aux H k) private lemma cauchy_with_rate_of_cauchy {X : ℕ → ℝ} (H : cauchy X) : cauchy_with_rate (r_seq_of X) (rate_of_cauchy H) := take k : ℕ+, some_spec (rate_of_cauchy_aux H k) private lemma converges_to_with_rate_of_cauchy {X : ℕ → ℝ} (H : cauchy X) : ∃ l Nb, converges_to_with_rate (r_seq_of X) l Nb := begin apply exists.intro, apply exists.intro, apply converges_to_with_rate_of_cauchy_with_rate, exact cauchy_with_rate_of_cauchy H end theorem converges_seq_of_cauchy {X : ℕ → ℝ} (H : cauchy X) : converges_seq X := obtain l Nb (conv : converges_to_with_rate (r_seq_of X) l Nb), from converges_to_with_rate_of_cauchy H, exists.intro l (take ε : ℝ, suppose ε > 0, obtain (k' : ℕ) (Hn : 1 / succ k' < ε), from archimedean_small `ε > 0`, let k : ℕ+ := tag (succ k') !succ_pos, N : ℕ+ := Nb k in have Hk : real.of_rat k⁻¹ < ε, by rewrite [↑pnat.inv, of_rat_divide]; exact Hn, exists.intro (elt_of N) (take n : ℕ, assume Hn : n ≥ elt_of N, let n' : ℕ+ := tag n (nat.lt_of_lt_of_le (has_property N) Hn) in have abs (X n - l) ≤ real.of_rat k⁻¹, by apply conv k n' Hn, show abs (X n - l) < ε, from lt_of_le_of_lt this Hk)) end analysis definition complete_metric_space_real [reducible] [trans_instance] : complete_metric_space ℝ := ⦃complete_metric_space, metric_space_real, complete := @analysis.converges_seq_of_cauchy ⦄ /- the real numbers can be viewed as a banach space -/ definition real_vector_space_real : real_vector_space ℝ := ⦃ real_vector_space, real.discrete_linear_ordered_field, smul := mul, smul_left_distrib := left_distrib, smul_right_distrib := right_distrib, mul_smul := mul.assoc, one_smul := one_mul ⦄ definition banach_space_real [trans_instance] [reducible] : banach_space ℝ := ⦃ banach_space, real_vector_space_real, norm := abs, norm_zero := abs_zero, eq_zero_of_norm_eq_zero := λ a H, eq_zero_of_abs_eq_zero H, norm_triangle := abs_add_le_abs_add_abs, norm_smul := abs_mul, complete := λ X H, analysis.complete ℝ H ⦄ /- limits under pointwise operations -/ section limit_operations variables {X Y : ℕ → ℝ} variables {x y : ℝ} proposition mul_left_converges_to_seq (c : ℝ) (HX : X ⟶ x in ℕ) : (λ n, c * X n) ⟶ c * x in ℕ := smul_converges_to_seq c HX proposition mul_right_converges_to_seq (c : ℝ) (HX : X ⟶ x in ℕ) : (λ n, X n * c) ⟶ x * c in ℕ := have (λ n, X n * c) = (λ n, c * X n), from funext (take x, !mul.comm), by+ rewrite [this, mul.comm]; apply mul_left_converges_to_seq c HX theorem converges_to_seq_squeeze (HX : X ⟶ x in ℕ) (HY : Y ⟶ x in ℕ) {Z : ℕ → ℝ} (HZX : ∀ n, X n ≤ Z n) (HZY : ∀ n, Z n ≤ Y n) : Z ⟶ x in ℕ := begin intros ε Hε, have Hε4 : ε / 4 > 0, from div_pos_of_pos_of_pos Hε four_pos, cases HX Hε4 with N1 HN1, cases HY Hε4 with N2 HN2, existsi max N1 N2, intro n Hn, have HXY : abs (Y n - X n) < ε / 2, begin apply lt_of_le_of_lt, apply abs_sub_le _ x, have Hε24 : ε / 2 = ε / 4 + ε / 4, from eq.symm !add_quarters, rewrite Hε24, apply add_lt_add, apply HN2, apply ge.trans Hn !le_max_right, rewrite abs_sub, apply HN1, apply ge.trans Hn !le_max_left end, have HZX : abs (Z n - X n) < ε / 2, begin have HZXnp : Z n - X n ≥ 0, from sub_nonneg_of_le !HZX, have HXYnp : Y n - X n ≥ 0, from sub_nonneg_of_le (le.trans !HZX !HZY), rewrite [abs_of_nonneg HZXnp, abs_of_nonneg HXYnp at HXY], note Hgt := lt_add_of_sub_lt_right HXY, have Hlt : Z n < ε / 2 + X n, from calc Z n ≤ Y n : HZY ... < ε / 2 + X n : Hgt, apply sub_lt_right_of_lt_add Hlt end, have H : abs (Z n - x) < ε, begin apply lt_of_le_of_lt, apply abs_sub_le _ (X n), apply lt.trans, apply add_lt_add, apply HZX, apply HN1, apply ge.trans Hn !le_max_left, apply div_two_add_div_four_lt Hε end, exact H end proposition converges_to_seq_of_abs_sub_converges_to_seq (Habs : (λ n, abs (X n - x)) ⟶ 0 in ℕ) : X ⟶ x in ℕ := begin intros ε Hε, cases Habs Hε with N HN, existsi N, intro n Hn, have Hn' : abs (abs (X n - x) - 0) < ε, from HN Hn, rewrite [sub_zero at Hn', abs_abs at Hn'], exact Hn' end proposition abs_sub_converges_to_seq_of_converges_to_seq (HX : X ⟶ x in ℕ) : (λ n, abs (X n - x)) ⟶ 0 in ℕ := begin intros ε Hε, cases HX Hε with N HN, existsi N, intro n Hn, have Hn' : abs (abs (X n - x) - 0) < ε, by rewrite [sub_zero, abs_abs]; apply HN Hn, exact Hn' end proposition mul_converges_to_seq (HX : X ⟶ x in ℕ) (HY : Y ⟶ y in ℕ) : (λ n, X n * Y n) ⟶ x * y in ℕ := begin have Hbd : ∃ K : ℝ, ∀ n : ℕ, abs (X n) ≤ K, begin cases bounded_of_converges_seq HX with K HK, existsi K + abs x, intro n, note Habs := le.trans (abs_abs_sub_abs_le_abs_sub (X n) x) !HK, apply le_add_of_sub_right_le, apply le.trans, apply le_abs_self, assumption end, cases Hbd with K HK, have Habsle : ∀ n, abs (X n * Y n - x * y) ≤ K * abs (Y n - y) + abs y * abs (X n - x), begin intro, have Heq : X n * Y n - x * y = (X n * Y n - X n * y) + (X n * y - x * y), by rewrite [-sub_add_cancel (X n * Y n) (X n * y) at {1}, sub_eq_add_neg, *add.assoc], apply le.trans, rewrite Heq, apply abs_add_le_abs_add_abs, apply add_le_add, rewrite [-mul_sub_left_distrib, abs_mul], apply mul_le_mul_of_nonneg_right, apply HK, apply abs_nonneg, rewrite [-mul_sub_right_distrib, abs_mul, mul.comm], apply le.refl end, have Hdifflim : (λ n, abs (X n * Y n - x * y)) ⟶ 0 in ℕ, begin apply converges_to_seq_squeeze, rotate 2, intro, apply abs_nonneg, apply Habsle, apply converges_to_seq_constant, rewrite -{0}zero_add, apply add_converges_to_seq, rewrite -(mul_zero K), apply mul_left_converges_to_seq, apply abs_sub_converges_to_seq_of_converges_to_seq, exact HY, rewrite -(mul_zero (abs y)), apply mul_left_converges_to_seq, apply abs_sub_converges_to_seq_of_converges_to_seq, exact HX end, apply converges_to_seq_of_abs_sub_converges_to_seq, apply Hdifflim end -- TODO: converges_to_seq_div, converges_to_seq_mul_left_iff, etc. proposition abs_converges_to_seq_zero (HX : X ⟶ 0 in ℕ) : (λ n, abs (X n)) ⟶ 0 in ℕ := norm_converges_to_seq_zero HX proposition converges_to_seq_zero_of_abs_converges_to_seq_zero (HX : (λ n, abs (X n)) ⟶ 0 in ℕ) : X ⟶ 0 in ℕ := converges_to_seq_zero_of_norm_converges_to_seq_zero HX proposition abs_converges_to_seq_zero_iff (X : ℕ → ℝ) : ((λ n, abs (X n)) ⟶ 0 in ℕ) ↔ (X ⟶ 0 in ℕ) := iff.intro converges_to_seq_zero_of_abs_converges_to_seq_zero abs_converges_to_seq_zero -- TODO: products of two sequences, converges_seq, limit_seq end limit_operations /- properties of converges_to_at -/ section limit_operations_continuous variables {f g : ℝ → ℝ} variables {a b x y : ℝ} theorem mul_converges_to_at (Hf : f ⟶ a at x) (Hg : g ⟶ b at x) : (λ z, f z * g z) ⟶ a * b at x := begin apply converges_to_at_of_all_conv_seqs, intro X HX, apply mul_converges_to_seq, note Hfc := all_conv_seqs_of_converges_to_at Hf, apply Hfc _ HX, note Hgb := all_conv_seqs_of_converges_to_at Hg, apply Hgb _ HX end end limit_operations_continuous /- monotone sequences -/ section monotone_sequences open real set variable {X : ℕ → ℝ} definition nondecreasing (X : ℕ → ℝ) : Prop := ∀ ⦃i j⦄, i ≤ j → X i ≤ X j proposition nondecreasing_of_forall_le_succ (H : ∀ i, X i ≤ X (succ i)) : nondecreasing X := take i j, suppose i ≤ j, have ∀ n, X i ≤ X (i + n), from take n, nat.induction_on n (by rewrite nat.add_zero; apply le.refl) (take n, assume ih, le.trans ih (H (i + n))), have X i ≤ X (i + (j - i)), from !this, by+ rewrite [add_sub_of_le `i ≤ j` at this]; exact this proposition converges_to_seq_sup_of_nondecreasing (nondecX : nondecreasing X) {b : ℝ} (Hb : ∀ i, X i ≤ b) : X ⟶ sup (X ' univ) in ℕ := let sX := sup (X ' univ) in have Xle : ∀ i, X i ≤ sX, from take i, have ∀ x, x ∈ X ' univ → x ≤ b, from (take x, assume H, obtain i [H' (Hi : X i = x)], from H, by rewrite -Hi; exact Hb i), show X i ≤ sX, from le_sup (mem_image_of_mem X !mem_univ) this, have exX : ∃ x, x ∈ X ' univ, from exists.intro (X 0) (mem_image_of_mem X !mem_univ), take ε, assume epos : ε > 0, have sX - ε < sX, from !sub_lt_of_pos epos, obtain x' [(H₁x' : x' ∈ X ' univ) (H₂x' : sX - ε < x')], from exists_mem_and_lt_of_lt_sup exX this, obtain i [H' (Hi : X i = x')], from H₁x', have Hi' : ∀ j, j ≥ i → sX - ε < X j, from take j, assume Hj, lt_of_lt_of_le (by rewrite Hi; apply H₂x') (nondecX Hj), exists.intro i (take j, assume Hj : j ≥ i, have X j - sX ≤ 0, from sub_nonpos_of_le (Xle j), have eq₁ : abs (X j - sX) = sX - X j, using this, by rewrite [abs_of_nonpos this, neg_sub], have sX - ε < X j, from lt_of_lt_of_le (by rewrite Hi; apply H₂x') (nondecX Hj), have sX < X j + ε, from lt_add_of_sub_lt_right this, have sX - X j < ε, from sub_lt_left_of_lt_add this, show (abs (X j - sX)) < ε, using eq₁ this, by rewrite eq₁; exact this) definition nonincreasing (X : ℕ → ℝ) : Prop := ∀ ⦃i j⦄, i ≤ j → X i ≥ X j proposition nodecreasing_of_nonincreasing_neg (nonincX : nonincreasing (λ n, - X n)) : nondecreasing (λ n, X n) := take i j, suppose i ≤ j, show X i ≤ X j, from le_of_neg_le_neg (nonincX this) proposition noincreasing_neg_of_nondecreasing (nondecX : nondecreasing X) : nonincreasing (λ n, - X n) := take i j, suppose i ≤ j, show - X i ≥ - X j, from neg_le_neg (nondecX this) proposition nonincreasing_neg_iff (X : ℕ → ℝ) : nonincreasing (λ n, - X n) ↔ nondecreasing X := iff.intro nodecreasing_of_nonincreasing_neg noincreasing_neg_of_nondecreasing proposition nonincreasing_of_nondecreasing_neg (nondecX : nondecreasing (λ n, - X n)) : nonincreasing (λ n, X n) := take i j, suppose i ≤ j, show X i ≥ X j, from le_of_neg_le_neg (nondecX this) proposition nodecreasing_neg_of_nonincreasing (nonincX : nonincreasing X) : nondecreasing (λ n, - X n) := take i j, suppose i ≤ j, show - X i ≤ - X j, from neg_le_neg (nonincX this) proposition nondecreasing_neg_iff (X : ℕ → ℝ) : nondecreasing (λ n, - X n) ↔ nonincreasing X := iff.intro nonincreasing_of_nondecreasing_neg nodecreasing_neg_of_nonincreasing proposition nonincreasing_of_forall_succ_le (H : ∀ i, X (succ i) ≤ X i) : nonincreasing X := begin rewrite -nondecreasing_neg_iff, show nondecreasing (λ n : ℕ, - X n), from nondecreasing_of_forall_le_succ (take i, neg_le_neg (H i)) end proposition converges_to_seq_inf_of_nonincreasing (nonincX : nonincreasing X) {b : ℝ} (Hb : ∀ i, b ≤ X i) : X ⟶ inf (X ' univ) in ℕ := have H₁ : ∃ x, x ∈ X ' univ, from exists.intro (X 0) (mem_image_of_mem X !mem_univ), have H₂ : ∀ x, x ∈ X ' univ → b ≤ x, from (take x, assume H, obtain i [Hi₁ (Hi₂ : X i = x)], from H, show b ≤ x, by rewrite -Hi₂; apply Hb i), have H₃ : {x : ℝ | -x ∈ X ' univ} = {x : ℝ | x ∈ (λ n, -X n) ' univ}, from calc {x : ℝ | -x ∈ X ' univ} = (λ y, -y) ' (X ' univ) : by rewrite image_neg_eq ... = {x : ℝ | x ∈ (λ n, -X n) ' univ} : image_compose, have H₄ : ∀ i, - X i ≤ - b, from take i, neg_le_neg (Hb i), begin+ -- need krewrite here krewrite [-neg_converges_to_seq_iff, -sup_neg H₁ H₂, H₃, -nondecreasing_neg_iff at nonincX], apply converges_to_seq_sup_of_nondecreasing nonincX H₄ end end monotone_sequences /- x^n converges to 0 if abs x < 1 -/ section xn open nat set theorem pow_converges_to_seq_zero {x : ℝ} (H : abs x < 1) : (λ n, x^n) ⟶ 0 in ℕ := suffices H' : (λ n, (abs x)^n) ⟶ 0 in ℕ, from have (λ n, (abs x)^n) = (λ n, abs (x^n)), from funext (take n, eq.symm !abs_pow), using this, by rewrite this at H'; exact converges_to_seq_zero_of_abs_converges_to_seq_zero H', let aX := (λ n, (abs x)^n), iaX := real.inf (aX ' univ), asX := (λ n, (abs x)^(succ n)) in have noninc_aX : nonincreasing aX, from nonincreasing_of_forall_succ_le (take i, assert (abs x) * (abs x)^i ≤ 1 * (abs x)^i, from mul_le_mul_of_nonneg_right (le_of_lt H) (!pow_nonneg_of_nonneg !abs_nonneg), assert (abs x) * (abs x)^i ≤ (abs x)^i, by krewrite one_mul at this; exact this, show (abs x) ^ (succ i) ≤ (abs x)^i, by rewrite pow_succ; apply this), have bdd_aX : ∀ i, 0 ≤ aX i, from take i, !pow_nonneg_of_nonneg !abs_nonneg, assert aXconv : aX ⟶ iaX in ℕ, proof converges_to_seq_inf_of_nonincreasing noninc_aX bdd_aX qed, have asXconv : asX ⟶ iaX in ℕ, from converges_to_seq_offset_succ aXconv, have asXconv' : asX ⟶ (abs x) * iaX in ℕ, from mul_left_converges_to_seq (abs x) aXconv, have iaX = (abs x) * iaX, from converges_to_seq_unique asXconv asXconv', assert iaX = 0, from eq_zero_of_mul_eq_self_left (ne_of_lt H) (eq.symm this), show aX ⟶ 0 in ℕ, begin rewrite -this, exact aXconv end --from this ▸ aXconv end xn /- continuity on the reals -/ section continuous theorem continuous_real_elim {f : ℝ → ℝ} (H : continuous f) : ∀ x : ℝ, ∀ ⦃ε : ℝ⦄, ε > 0 → ∃ δ : ℝ, δ > 0 ∧ ∀ x' : ℝ, abs (x' - x) < δ → abs (f x' - f x) < ε := H theorem continuous_real_intro {f : ℝ → ℝ} (H : ∀ x : ℝ, ∀ ⦃ε : ℝ⦄, ε > 0 → ∃ δ : ℝ, δ > 0 ∧ ∀ x' : ℝ, abs (x' - x) < δ → abs (f x' - f x) < ε) : continuous f := H theorem pos_on_nbhd_of_cts_of_pos {f : ℝ → ℝ} (Hf : continuous f) {b : ℝ} (Hb : f b > 0) : ∃ δ : ℝ, δ > 0 ∧ ∀ y, abs (y - b) < δ → f y > 0 := begin let Hcont := continuous_real_elim Hf b Hb, cases Hcont with δ Hδ, existsi δ, split, exact and.left Hδ, intro y Hy, let Hy' := and.right Hδ y Hy, note Hlt := sub_lt_of_abs_sub_lt_left Hy', rewrite sub_self at Hlt, assumption end theorem neg_on_nbhd_of_cts_of_neg {f : ℝ → ℝ} (Hf : continuous f) {b : ℝ} (Hb : f b < 0) : ∃ δ : ℝ, δ > 0 ∧ ∀ y, abs (y - b) < δ → f y < 0 := begin let Hcont := continuous_real_elim Hf b (neg_pos_of_neg Hb), cases Hcont with δ Hδ, existsi δ, split, exact and.left Hδ, intro y Hy, let Hy' := and.right Hδ y Hy, let Hlt := sub_lt_of_abs_sub_lt_right Hy', note Hlt' := lt_add_of_sub_lt_left Hlt, rewrite [add.comm at Hlt', -sub_eq_add_neg at Hlt', sub_self at Hlt'], assumption end theorem continuous_neg_of_continuous {f : ℝ → ℝ} (Hcon : continuous f) : continuous (λ x, - f x) := begin apply continuous_real_intro, intros x ε Hε, cases continuous_real_elim Hcon x Hε with δ Hδ, cases Hδ with Hδ₁ Hδ₂, existsi δ, split, assumption, intros x' Hx', let HD := Hδ₂ x' Hx', rewrite [-abs_neg, neg_neg_sub_neg], exact HD end theorem continuous_offset_of_continuous {f : ℝ → ℝ} (Hcon : continuous f) (a : ℝ) : continuous (λ x, (f x) + a) := begin apply continuous_real_intro, intros x ε Hε, cases continuous_real_elim Hcon x Hε with δ Hδ, cases Hδ with Hδ₁ Hδ₂, existsi δ, split, assumption, intros x' Hx', rewrite [add_sub_comm, sub_self, add_zero], apply Hδ₂, assumption end theorem continuous_mul_of_continuous {f g : ℝ → ℝ} (Hconf : continuous f) (Hcong : continuous g) : continuous (λ x, f x * g x) := begin intro x, apply continuous_at_of_converges_to_at, apply mul_converges_to_at, all_goals apply converges_to_at_of_continuous_at, apply Hconf, apply Hcong end end continuous /- proposition converges_to_at_unique {f : M → N} {y₁ y₂ : N} {x : M} (H₁ : f ⟶ y₁ '[at x]) (H₂ : f ⟶ y₂ '[at x]) : y₁ = y₂ := eq_of_forall_dist_le (take ε, suppose ε > 0, have e2pos : ε / 2 > 0, from div_pos_of_pos_of_pos `ε > 0` two_pos, obtain δ₁ [(δ₁pos : δ₁ > 0) (Hδ₁ : ∀ x', x ≠ x' ∧ dist x x' < δ₁ → dist (f x') y₁ < ε / 2)], from H₁ e2pos, obtain δ₂ [(δ₂pos : δ₂ > 0) (Hδ₂ : ∀ x', x ≠ x' ∧ dist x x' < δ₂ → dist (f x') y₂ < ε / 2)], from H₂ e2pos, let δ := min δ₁ δ₂ in have δ > 0, from lt_min δ₁pos δ₂pos, -/
d336de320d073326351534cbcb919db3b03bc7a8
439bc6c3e74a118aa51df633b8e1f24415804d86
/psh_as_func.lean
90a5bd65387b8663b95c1b58673da89f495ceef7
[]
no_license
jcommelin/lt2019_slides
4ca498db02b5187c5778c21b985126d52d260696
3234cd92920d3d4321cc2cef78b48e5fa55be413
refs/heads/master
1,586,718,101,957
1,546,930,855,000
1,546,930,855,000
162,697,592
1
0
null
null
null
null
UTF-8
Lean
false
false
50
lean
def presheaf (X : Top) := opens(X)ᵒᵖ ⥤ Type
c9e98561f80804fa4c79dea55a694f9ba3b48e8f
46125763b4dbf50619e8846a1371029346f4c3db
/src/geometry/manifold/smooth_manifold_with_corners.lean
1879e9e87456790feb96ede212a6112d3f9a051e
[ "Apache-2.0" ]
permissive
thjread/mathlib
a9d97612cedc2c3101060737233df15abcdb9eb1
7cffe2520a5518bba19227a107078d83fa725ddc
refs/heads/master
1,615,637,696,376
1,583,953,063,000
1,583,953,063,000
246,680,271
0
0
Apache-2.0
1,583,960,875,000
1,583,960,875,000
null
UTF-8
Lean
false
false
25,415
lean
/- Copyright (c) 2019 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 analysis.calculus.times_cont_diff geometry.manifold.manifold /-! # Smooth manifolds (possibly with boundary or corners) A smooth manifold is a manifold modelled on a normed vector space, or a subset like a half-space (to get manifolds with boundaries) for which the change of coordinates are smooth maps. We define a model with corners as a map `I : H → E` embedding nicely the topological space `H` in the vector space `E` (or more precisely as a structure containing all the relevant properties). Given such a model with corners `I` on `(E, H)`, we define the groupoid of local homeomorphisms of `H` which are smooth when read in `E` (for any regularity `n : with_top ℕ`). With this groupoid at hand and the general machinery of manifolds, we thus get the notion of `C^n` manifold with respect to any model with corners `I` on `(E, H)`. We also introduce a specific type class for `C^∞` manifolds as these are the most commonly used. ## Main definitions * `model_with_corners 𝕜 E H` : a structure containing informations on the way a space `H` embeds in a model vector space E over the field `𝕜`. This is all that is needed to define a smooth manifold with model space `H`, and model vector space `E`. * `model_with_corners_self 𝕜 E` : trivial model with corners structure on the space `E` embedded in itself by the identity. * `times_cont_diff_groupoid n I` : when `I` is a model with corners on `(𝕜, E, H)`, this is the groupoid of local homeos of `H` which are of class `C^n` over the normed field `𝕜`, when read in `E`. * `smooth_manifold_with_corners I M` : a type class saying that the manifold `M`, modelled on the space `H`, has `C^∞` changes of coordinates with respect to the model with corners `I` on `(𝕜, E, H)`. This type class is just a shortcut for `has_groupoid M (times_cont_diff_groupoid ⊤ I)`. * `ext_chart_at I x`: in a smooth manifold with corners with the model `I` on `(E, H)`, the charts take values in `H`, but often we may want to use their `E`-valued version, obtained by composing the charts with `I`. Since the target is in general not open, we can not register them as local homeomorphisms, but we register them as local equivs. `ext_chart_at I x` is the canonical such local equiv around `x`. As specific examples of models with corners, we define (in the file `real_instances.lean`) * `euclidean_space n` for a model vector space of dimension `n`. * `model_with_corners ℝ (euclidean_space n) (euclidean_half_space n)` for the model space used to define `n`-dimensional real manifolds with boundary and * `model_with_corners ℝ (euclidean_space n) (euclidean_quadrant n)` for the model space used to define `n`-dimensional real manifolds with corners With these definitions at hand, to invoke an `n`-dimensional real manifold without boundary, one could use `variables {n : ℕ} {M : Type*} [topological_space M] [manifold (euclidean_space n)] [smooth_manifold_with_corners (model_with_corners_self ℝ (euclidean_space n)) M]`. However, this is not the recommended way: a theorem proved using this assumption would not apply for instance to the tangent space of such a manifold, which is modelled on `(euclidean_space n) × (euclidean_space n)` and not on `euclidean_space (2 * n)`! In the same way, it would not apply to product manifolds, modelled on `(euclidean_space n) × (euclidean_space m)`. The right invocation does not focus on one specific construction, but on all constructions sharing the right properties, like `variables {E : Type*} [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E] {I : model_with_corners ℝ E E} [I.boundaryless] {M : Type*} [topological_space M] [manifold E M] [smooth_manifold_with_corners I M]` Here, `I.boundaryless` is a typeclass property ensuring that there is no boundary (this is for instance the case for model_with_corners_self, or products of these). Note that one could consider as a natural assumption to only use the trivial model with corners `model_with_corners_self ℝ E`, but again in product manifolds the natural model with corners will not be this one but the product one (and they are not defeq as `(λp : E × F, (p.1, p.2))` is not defeq to the identity). So, it is important to use the above incantation to maximize the applicability of theorems. ## Implementation notes We want to talk about manifolds modelled on a vector space, but also on manifolds with boundary, modelled on a half space (or even manifolds with corners). For the latter examples, we still want to define smooth functions, tangent bundles, and so on. As smooth functions are well defined on vector spaces or subsets of these, one could take for model space a subtype of a vector space. With the drawback that the whole vector space itself (which is the most basic example) is not directly a subtype of itself: the inclusion of `univ : set E` in `set E` would show up in the definition, instead of `id`. A good abstraction covering both cases it to have a vector space `E` (with basic example the Euclidean space), a model space H`` (with basic example the upper half space), and an embedding of `H` into `E` (which can be the identity for `H = E`, or `subtype.val` for manifolds with corners). We say that the pair `(E, H)` with their embedding is a model with corners, and we encompass all the relevant properties (in particular the fact that the image of `H` in `E` should have unique differentials) in the definition of `model_with_corners`. We concentrate on `C^∞` manifolds: all the definitions work equally well for `C^n` manifolds, but later on it is a pain to carry all over the smoothness parameter, especially when one wants to deal with `C^k` functions as there would be additional conditions `k ≤ n` everywhere. Since one deals almost all the time with `C^∞` (or analytic) manifolds, this seems to be a reasonable choice that one could revisit later if needed. `C^k` manifolds are still available, but they should be called using `has_groupoid M (times_cont_diff_groupoid k I)` where `I` is the model with corners. I have considered using the model with corners `I` as a typeclass argument, possibly `out_param`, to get lighter notations later on, but it did not turn out right, as on `E × F` there are two natural model with corners, the trivial (identity) one, and the product one, and they are not defeq and one needs to indicate to Lean which one we want to use. This means that when talking on objects on manifolds one will most often need to specify the model with corners one is using. For instance, the tangent bundle will be `tangent_bundle I M` and the derivative will be `mfderiv I I' f`, instead of the more natural notations `tangent_bundle 𝕜 M` and `mfderiv 𝕜 f` (the field has to be explicit anyway, as some manifolds could be considered both as real and complex manifolds). -/ noncomputable theory universes u v w u' v' w' open set section model_with_corners /-! ### Models with corners. -/ /-- A structure containing informations on the way a space `H` embeds in a model vector space `E` over the field `𝕜`. This is all what is needed to define a smooth manifold with model space `H`, and model vector space `E`. -/ structure model_with_corners (𝕜 : Type*) [nondiscrete_normed_field 𝕜] (E : Type*) [normed_group E] [normed_space 𝕜 E] (H : Type*) [topological_space H] extends local_equiv H E := (source_eq : source = univ) (unique_diff : unique_diff_on 𝕜 (range to_fun)) (continuous_to_fun : continuous to_fun) (continuous_inv_fun : continuous inv_fun) attribute [simp] model_with_corners.source_eq /-- A vector space is a model with corners. -/ def model_with_corners_self (𝕜 : Type*) [nondiscrete_normed_field 𝕜] (E : Type*) [normed_group E] [normed_space 𝕜 E] : model_with_corners 𝕜 E E := { to_fun := id, inv_fun := id, source := univ, target := univ, source_eq := rfl, map_source := λ_ _, mem_univ _, map_target := λ_ _, mem_univ _, left_inv := λ_ _, rfl, right_inv := λ_ _, rfl, unique_diff := by { rw range_id, exact is_open_univ.unique_diff_on }, continuous_to_fun := continuous_id, continuous_inv_fun := continuous_id } /-- In the trivial model with corners, the associated local equiv is the identity. -/ @[simp] lemma model_with_corners_self_local_equiv (𝕜 : Type*) [nondiscrete_normed_field 𝕜] (E : Type*) [normed_group E] [normed_space 𝕜 E] : (model_with_corners_self 𝕜 E).to_local_equiv = local_equiv.refl E := rfl section variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H) @[simp] lemma model_with_corners_target : I.target = range I.to_fun := by rw [← image_univ, ← local_equiv.image_source_eq_target, I.source_eq] @[simp] lemma model_with_corners_left_inv (x : H) : I.inv_fun (I.to_fun x) = x := by simp [I.left_inv, I.source_eq] @[simp] lemma model_with_corners_inv_fun_comp : I.inv_fun ∘ I.to_fun = id := by { ext x, exact model_with_corners_left_inv _ _ } @[simp] lemma model_with_corners_right_inv {x : E} (hx : x ∈ range I.to_fun) : I.to_fun (I.inv_fun x) = x := begin apply I.right_inv, simp [hx] end lemma model_with_corners.image (s : set H) : I.to_fun '' s = I.inv_fun ⁻¹' s ∩ range I.to_fun := begin ext x, simp only [mem_image, mem_inter_eq, mem_range, mem_preimage], split, { rintros ⟨y, ⟨ys, hy⟩⟩, rw ← hy, simp [ys], exact ⟨y, rfl⟩ }, { rintros ⟨xs, ⟨y, yx⟩⟩, rw ← yx at xs, simp at xs, exact ⟨y, ⟨xs, yx⟩⟩ } end end /-- Given two model_with_corners `I` on `(E, H)` and `I'` on `(E', H')`, we define the model with corners `I.prod I'` on `(E × E', H × H')`. This appears in particular for the manifold structure on the tangent bundle to a manifold modelled on `(E, H)`: it will be modelled on `(E × E, H × E)`. -/ def model_with_corners.prod {𝕜 : Type u} [nondiscrete_normed_field 𝕜] {E : Type v} [normed_group E] [normed_space 𝕜 E] {H : Type w} [topological_space H] (I : model_with_corners 𝕜 E H) {E' : Type v'} [normed_group E'] [normed_space 𝕜 E'] {H' : Type w'} [topological_space H'] (I' : model_with_corners 𝕜 E' H') : model_with_corners 𝕜 (E × E') (H × H') := { to_fun := λp, (I.to_fun p.1, I'.to_fun p.2), inv_fun := λp, (I.inv_fun p.1, I'.inv_fun p.2), source := (univ : set (H × H')), target := set.prod (range I.to_fun) (range I'.to_fun), map_source := λ ⟨x, x'⟩ _, by simp [-mem_range, mem_range_self], map_target := λ ⟨x, x'⟩ _, mem_univ _, left_inv := λ ⟨x, x'⟩ _, by simp, right_inv := λ ⟨x, x'⟩ ⟨hx, hx'⟩, by rw [I.right_inv, I'.right_inv]; rwa model_with_corners_target, source_eq := rfl, unique_diff := begin have : range (λ(p : H × H'), (I.to_fun p.1, I'.to_fun p.2)) = set.prod (range I.to_fun) (range I'.to_fun), by { rw ← prod_range_range_eq }, rw this, exact unique_diff_on.prod I.unique_diff I'.unique_diff, end, continuous_to_fun := (continuous.comp I.continuous_to_fun continuous_fst).prod_mk (continuous.comp I'.continuous_to_fun continuous_snd), continuous_inv_fun := (continuous.comp I.continuous_inv_fun continuous_fst).prod_mk (continuous.comp I'.continuous_inv_fun continuous_snd) } /-- Special case of product model with corners, which is trivial on the second factor. This shows up as the model to tangent bundles. -/ @[reducible] def model_with_corners.tangent {𝕜 : Type u} [nondiscrete_normed_field 𝕜] {E : Type v} [normed_group E] [normed_space 𝕜 E] {H : Type w} [topological_space H] (I : model_with_corners 𝕜 E H) : model_with_corners 𝕜 (E × E) (H × E) := I.prod (model_with_corners_self 𝕜 E) section boundaryless /-- Property ensuring that the model with corners `I` defines manifolds without boundary. -/ class model_with_corners.boundaryless {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H) : Prop := (range_eq_univ : range I.to_fun = univ) /-- The trivial model with corners has no boundary -/ instance model_with_corners_self_range (𝕜 : Type*) [nondiscrete_normed_field 𝕜] (E : Type*) [normed_group E] [normed_space 𝕜 E] : (model_with_corners_self 𝕜 E).boundaryless := ⟨by simp⟩ /-- If two model with corners are boundaryless, their product also is -/ instance model_with_corners.range_eq_univ_prod {𝕜 : Type u} [nondiscrete_normed_field 𝕜] {E : Type v} [normed_group E] [normed_space 𝕜 E] {H : Type w} [topological_space H] (I : model_with_corners 𝕜 E H) [I.boundaryless] {E' : Type v'} [normed_group E'] [normed_space 𝕜 E'] {H' : Type w'} [topological_space H'] (I' : model_with_corners 𝕜 E' H') [I'.boundaryless] : (I.prod I').boundaryless := begin split, dsimp [model_with_corners.prod], rw [← prod_range_range_eq, model_with_corners.boundaryless.range_eq_univ, model_with_corners.boundaryless.range_eq_univ, univ_prod_univ] end end boundaryless section times_cont_diff_groupoid /-! ### Smooth functions on models with corners -/ variables {m n : with_top ℕ} {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H) {M : Type*} [topological_space M] variable (n) /-- Given a model with corners `(E, H)`, we define the groupoid of `C^n` transformations of `H` as the maps that are `C^n` when read in `E` through `I`. -/ def times_cont_diff_groupoid : structure_groupoid H := pregroupoid.groupoid { property := λf s, times_cont_diff_on 𝕜 n (I.to_fun ∘ f ∘ I.inv_fun) (I.inv_fun ⁻¹' s ∩ range I.to_fun), comp := λf g u v hf hg huv, begin have : I.to_fun ∘ (g ∘ f) ∘ I.inv_fun = (I.to_fun ∘ g ∘ I.inv_fun) ∘ (I.to_fun ∘ f ∘ I.inv_fun), by { ext x, simp }, rw this, apply times_cont_diff_on.comp hg _, { rintros x ⟨hx1, hx2⟩, simp at ⊢ hx1, exact ⟨hx1.2, (f (I.inv_fun x)), rfl⟩ }, { refine hf.mono _, rintros x ⟨hx1, hx2⟩, exact ⟨hx1.1, hx2⟩ } end, id_mem := begin apply times_cont_diff_on.congr (times_cont_diff_id.times_cont_diff_on), rintros x ⟨hx1, hx2⟩, rcases mem_range.1 hx2 with ⟨y, hy⟩, rw ← hy, simp, end, locality := λf u hu H, begin apply times_cont_diff_on_of_locally_times_cont_diff_on, rintros y ⟨hy1, hy2⟩, rcases mem_range.1 hy2 with ⟨x, hx⟩, rw ← hx at ⊢ hy1, simp at ⊢ hy1, rcases H x hy1 with ⟨v, v_open, xv, hv⟩, have : ((I.inv_fun ⁻¹' (u ∩ v)) ∩ (range (I.to_fun))) = ((I.inv_fun ⁻¹' u) ∩ (range (I.to_fun)) ∩ I.inv_fun ⁻¹' v), { rw [preimage_inter, inter_assoc, inter_assoc], congr' 1, rw inter_comm }, rw this at hv, exact ⟨I.inv_fun ⁻¹' v, I.continuous_inv_fun _ v_open, by simpa, hv⟩ end, congr := λf g u hu fg hf, begin apply hf.congr, rintros y ⟨hy1, hy2⟩, rcases mem_range.1 hy2 with ⟨x, hx⟩, rw ← hx at ⊢ hy1, simp at ⊢ hy1, rw fg _ hy1 end } variable {n} /-- Inclusion of the groupoid of `C^n` local diffeos in the groupoid of `C^m` local diffeos when `m ≤ n` -/ lemma times_cont_diff_groupoid_le (h : m ≤ n) : times_cont_diff_groupoid n I ≤ times_cont_diff_groupoid m I := begin rw [times_cont_diff_groupoid, times_cont_diff_groupoid], apply groupoid_of_pregroupoid_le, assume f s hfs, exact times_cont_diff_on.of_le hfs h end /-- The groupoid of `0`-times continuously differentiable maps is just the groupoid of all local homeomorphisms -/ lemma times_cont_diff_groupoid_zero_eq : times_cont_diff_groupoid 0 I = continuous_groupoid H := begin apply le_antisymm lattice.le_top, assume u hu, -- we have to check that every local homeomorphism belongs to `times_cont_diff_groupoid 0 I`, -- by unfolding its definition change u ∈ times_cont_diff_groupoid 0 I, rw [times_cont_diff_groupoid, mem_groupoid_of_pregroupoid], simp only [times_cont_diff_on_zero], split, { apply continuous_on.comp (@continuous.continuous_on _ _ _ _ _ univ I.continuous_to_fun) _ (subset_univ _), apply continuous_on.comp u.continuous_to_fun I.continuous_inv_fun.continuous_on (inter_subset_left _ _) }, { apply continuous_on.comp (@continuous.continuous_on _ _ _ _ _ univ I.continuous_to_fun) _ (subset_univ _), apply continuous_on.comp u.continuous_inv_fun I.continuous_inv_fun.continuous_on (inter_subset_left _ _) }, end variable (n) /-- An identity local homeomorphism belongs to the `C^n` groupoid. -/ lemma of_set_mem_times_cont_diff_groupoid {s : set H} (hs : is_open s) : local_homeomorph.of_set s hs ∈ times_cont_diff_groupoid n I := begin rw [times_cont_diff_groupoid, mem_groupoid_of_pregroupoid], suffices h : times_cont_diff_on 𝕜 n (I.to_fun ∘ I.inv_fun) (I.inv_fun ⁻¹' s ∩ range I.to_fun), by simp [h], have : times_cont_diff_on 𝕜 n id (univ : set E) := times_cont_diff_id.times_cont_diff_on, exact this.congr_mono (λ x hx, by simp [hx.2]) (subset_univ _) end /-- The composition of a local homeomorphism from `H` to `M` and its inverse belongs to the `C^n` groupoid. -/ lemma symm_trans_mem_times_cont_diff_groupoid (e : local_homeomorph M H) : e.symm.trans e ∈ times_cont_diff_groupoid n I := begin have : e.symm.trans e ≈ local_homeomorph.of_set e.target e.open_target := local_homeomorph.trans_symm_self _, exact structure_groupoid.eq_on_source _ _ _ (of_set_mem_times_cont_diff_groupoid n I e.open_target) this end end times_cont_diff_groupoid end model_with_corners /-! ### Smooth manifolds with corners -/ /-- Typeclass defining smooth manifolds with corners with respect to a model with corners, over a field `𝕜` and with infinite smoothness to simplify typeclass search and statements later on. -/ class smooth_manifold_with_corners {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H) (M : Type*) [topological_space M] [manifold H M] extends has_groupoid M (times_cont_diff_groupoid ⊤ I) : Prop /-- For any model with corners, the model space is a smooth manifold -/ instance model_space_smooth {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] {I : model_with_corners 𝕜 E H} : smooth_manifold_with_corners I H := {} section extended_charts open_locale topological_space variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H) {M : Type*} [topological_space M] [manifold H M] (x : M) {s t : set M} /-! ### Extended charts In a smooth manifold with corners, the model space is the space `H`. However, we will also need to use extended charts taking values in the model vector space `E`. These extended charts are not `local_homeomorph` as the target is not open in `E` in general, but we can still register them as `local_equiv`. -/ /-- The preferred extended chart on a manifold with corners around a point `x`, from a neighborhood of `x` to the model vector space. -/ def ext_chart_at (x : M) : local_equiv M E := (chart_at H x).to_local_equiv.trans I.to_local_equiv lemma ext_chart_at_source : (ext_chart_at I x).source = (chart_at H x).source := by rw [ext_chart_at, local_equiv.trans_source, I.source_eq, preimage_univ, inter_univ] lemma ext_chart_at_open_source : is_open (ext_chart_at I x).source := by { rw ext_chart_at_source, exact (chart_at H x).open_source } @[simp] lemma mem_ext_chart_source : x ∈ (ext_chart_at I x).source := by { rw ext_chart_at_source, exact mem_chart_source _ _ } @[simp] lemma ext_chart_at_to_inv : (ext_chart_at I x).inv_fun ((ext_chart_at I x).to_fun x) = x := by rw (ext_chart_at I x).left_inv (mem_ext_chart_source _ _) lemma ext_chart_at_source_mem_nhds : (ext_chart_at I x).source ∈ 𝓝 x := mem_nhds_sets (ext_chart_at_open_source I x) (mem_ext_chart_source I x) lemma ext_chart_at_continuous_on_to_fun : continuous_on (ext_chart_at I x).to_fun (ext_chart_at I x).source := begin refine continuous_on.comp I.continuous_to_fun.continuous_on _ subset_preimage_univ, rw ext_chart_at_source, exact (chart_at H x).continuous_to_fun end lemma ext_chart_at_continuous_at_to_fun : continuous_at (ext_chart_at I x).to_fun x := (ext_chart_at_continuous_on_to_fun I x x (mem_ext_chart_source I x)).continuous_at (ext_chart_at_source_mem_nhds I x) lemma ext_chart_at_continuous_on_inv_fun : continuous_on (ext_chart_at I x).inv_fun (ext_chart_at I x).target := begin apply continuous_on.comp (chart_at H x).continuous_inv_fun I.continuous_inv_fun.continuous_on, simp [ext_chart_at, local_equiv.trans_target] end lemma ext_chart_at_target_mem_nhds_within : (ext_chart_at I x).target ∈ nhds_within ((ext_chart_at I x).to_fun x) (range I.to_fun) := begin rw [ext_chart_at, local_equiv.trans_target], simp only [function.comp_app, local_equiv.trans_to_fun, model_with_corners_target], refine inter_mem_nhds_within _ (mem_nhds_sets (I.continuous_inv_fun _ (chart_at H x).open_target) _), simp only [model_with_corners_left_inv, mem_preimage], exact (chart_at H x).map_source (mem_chart_source _ _), end lemma nhds_within_ext_chart_target_eq : nhds_within ((ext_chart_at I x).to_fun x) (ext_chart_at I x).target = nhds_within ((ext_chart_at I x).to_fun x) (range I.to_fun) := begin apply le_antisymm, { apply nhds_within_mono, simp [ext_chart_at, local_equiv.trans_target], }, { apply nhds_within_le_of_mem (ext_chart_at_target_mem_nhds_within _ _) } end lemma ext_chart_continuous_at_inv_fun' {x' : M} (h : x' ∈ (ext_chart_at I x).source) : continuous_at (ext_chart_at I x).inv_fun ((ext_chart_at I x).to_fun x') := begin apply continuous_at.comp, { simp [ext_chart_at], rw ext_chart_at_source at h, exact ((chart_at H x).continuous_inv_fun _ ((chart_at H x).map_source h)).continuous_at (mem_nhds_sets (chart_at H x).open_target ((chart_at H x).map_source h)) }, { exact I.continuous_inv_fun.continuous_at } end lemma ext_chart_continuous_at_inv_fun : continuous_at (ext_chart_at I x).inv_fun ((ext_chart_at I x).to_fun x) := ext_chart_continuous_at_inv_fun' I x (mem_ext_chart_source I x) /-- Technical lemma ensuring that the preimage under an extended chart of a neighborhood of a point in the source is a neighborhood of the preimage, within a set. -/ lemma ext_chart_preimage_mem_nhds_within' {x' : M} (h : x' ∈ (ext_chart_at I x).source) (ht : t ∈ nhds_within x' s) : (ext_chart_at I x).inv_fun ⁻¹' t ∈ nhds_within ((ext_chart_at I x).to_fun x') ((ext_chart_at I x).inv_fun ⁻¹' s ∩ range I.to_fun) := begin apply (ext_chart_continuous_at_inv_fun' I x h).continuous_within_at.tendsto_nhds_within_image, rw (ext_chart_at I x).left_inv h, apply nhds_within_mono _ _ ht, have : (ext_chart_at I x).inv_fun '' ((ext_chart_at I x).inv_fun ⁻¹' s) ⊆ s := image_preimage_subset _ _, exact subset.trans (image_subset _ (inter_subset_left _ _)) this end /-- Technical lemma ensuring that the preimage under an extended chart of a neighborhood of the base point is a neighborhood of the preimage, within a set. -/ lemma ext_chart_preimage_mem_nhds_within (ht : t ∈ nhds_within x s) : (ext_chart_at I x).inv_fun ⁻¹' t ∈ nhds_within ((ext_chart_at I x).to_fun x) ((ext_chart_at I x).inv_fun ⁻¹' s ∩ range I.to_fun) := ext_chart_preimage_mem_nhds_within' I x (mem_ext_chart_source I x) ht /-- Technical lemma ensuring that the preimage under an extended chart of a neighborhood of a point is a neighborhood of the preimage. -/ lemma ext_chart_preimage_mem_nhds (ht : t ∈ 𝓝 x) : (ext_chart_at I x).inv_fun ⁻¹' t ∈ 𝓝 ((ext_chart_at I x).to_fun x) := begin apply (ext_chart_continuous_at_inv_fun I x).preimage_mem_nhds, rwa (ext_chart_at I x).left_inv (mem_ext_chart_source _ _) end /-- Technical lemma to rewrite suitably the preimage of an intersection under an extended chart, to bring it into a convenient form to apply derivative lemmas. -/ lemma ext_chart_preimage_inter_eq : ((ext_chart_at I x).inv_fun ⁻¹' (s ∩ t) ∩ range I.to_fun) = ((ext_chart_at I x).inv_fun ⁻¹' s ∩ range (I.to_fun)) ∩ ((ext_chart_at I x).inv_fun ⁻¹' t) := begin rw [preimage_inter, inter_assoc, inter_assoc], congr' 1, rw inter_comm end end extended_charts /-- In the case of the manifold structure on a vector space, the extended charts are just the identity.-/ @[simp] lemma ext_chart_model_space_eq_id (𝕜 : Type*) [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] (x : E) : ext_chart_at (model_with_corners_self 𝕜 E) x = local_equiv.refl E := by simp [ext_chart_at]
8faec14a48cc5771847537ff6dbdae6f7cea6413
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/typeclass_append.lean
0cf95002d88ba24f620eea778f394e146acba34c
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
814
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Daniel Selsam Performance test to ensure quadratic blowup is avoided. -/ class AppendList {α : Type} (xs₁ xs₂ : List α) (out : outParam $ List α) : Type := (u : Unit := ()) instance AppendBase {α : Type} (xs₂ : List α) : AppendList [] xs₂ xs₂ := {} instance AppendStep {α : Type} (x : α) (xs₁ xs₂ out : List α) [AppendList xs₁ xs₂ out] : AppendList (x::xs₁) xs₂ (x::out) := {} #synth AppendList [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] [200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211]
6773465b354f4cc2a58f98e66d3d8e6e78e10315
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/theories/number_theory/bezout.lean
a313696322ca7b04fcf6440dd4675ec407ec97ba
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
3,903
lean
/- Copyright (c) 2015 William Peterson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: William Peterson, Jeremy Avigad Extended gcd, Bezout's theorem, chinese remainder theorem. -/ import data.nat.div data.int .primes /- Bezout's theorem -/ section Bezout open nat int open eq.ops well_founded decidable prod private definition pair_nat.lt : ℕ × ℕ → ℕ × ℕ → Prop := measure pr₂ private definition pair_nat.lt.wf : well_founded pair_nat.lt := intro_k (measure.wf pr₂) 20 local attribute pair_nat.lt.wf [instance] local infixl `≺`:50 := pair_nat.lt private definition gcd.lt.dec (x y₁ : ℕ) : (succ y₁, x % succ y₁) ≺ (x, succ y₁) := !nat.mod_lt (succ_pos y₁) private definition egcd_rec_f (z : ℤ) : ℤ → ℤ → ℤ × ℤ := λ s t, (t, s - t * z) definition egcd.F : Π (p₁ : ℕ × ℕ), (Π p₂ : ℕ × ℕ, p₂ ≺ p₁ → ℤ × ℤ) → ℤ × ℤ | (x, y) := nat.cases_on y (λ f, (1, 0) ) (λ y₁ (f : Π p₂, p₂ ≺ (x, succ y₁) → ℤ × ℤ), let bz := f (succ y₁, x % succ y₁) !gcd.lt.dec in prod.cases_on bz (egcd_rec_f (x / succ y₁))) definition egcd (x y : ℕ) := fix egcd.F (pair x y) theorem egcd_zero (x : ℕ) : egcd x 0 = (1, 0) := well_founded.fix_eq egcd.F (x, 0) theorem egcd_succ (x y : ℕ) : egcd x (succ y) = prod.cases_on (egcd (succ y) (x % succ y)) (egcd_rec_f (x / succ y)) := well_founded.fix_eq egcd.F (x, succ y) theorem egcd_of_pos (x : ℕ) {y : ℕ} (ypos : y > 0) : let erec := egcd y (x % y), u := pr₁ erec, v := pr₂ erec in egcd x y = (v, u - v * (x / y)) := obtain (y' : nat) (yeq : y = succ y'), from exists_eq_succ_of_pos ypos, begin rewrite [yeq, egcd_succ, -prod.eta (egcd _ _)], esimp, unfold egcd_rec_f, rewrite [of_nat_div] end theorem egcd_prop (x y : ℕ) : (pr₁ (egcd x y)) * x + (pr₂ (egcd x y)) * y = gcd x y := gcd.induction x y (take m, by krewrite [egcd_zero, mul_zero, one_mul]) (take m n, assume npos : 0 < n, assume IH, begin note H := egcd_of_pos m npos, esimp at H, rewrite H, esimp, rewrite [gcd_rec, -IH], rewrite [add.comm], rewrite [-of_nat_mod], rewrite [int.mod_def], rewrite [+mul_sub_right_distrib], rewrite [+mul_sub_left_distrib, *left_distrib], rewrite [*sub_eq_add_neg, {pr₂ (egcd n (m % n)) * of_nat m + - _}add.comm], rewrite [-add.assoc, mul.assoc] end) theorem Bezout_aux (x y : ℕ) : ∃ a b : ℤ, a * x + b * y = gcd x y := exists.intro _ (exists.intro _ (egcd_prop x y)) theorem Bezout (x y : ℤ) : ∃ a b : ℤ, a * x + b * y = gcd x y := obtain a' b' (H : a' * nat_abs x + b' * nat_abs y = gcd x y), from !Bezout_aux, begin existsi (a' * sign x), existsi (b' * sign y), rewrite [*mul.assoc, -*abs_eq_sign_mul, -*of_nat_nat_abs], apply H end end Bezout /- A sample application of Bezout's theorem, namely, an alternative proof that irreducible implies prime (dvd_or_dvd_of_prime_of_dvd_mul). -/ namespace nat open int example {p x y : ℕ} (pp : prime p) (H : p ∣ x * y) : p ∣ x ∨ p ∣ y := decidable.by_cases (suppose p ∣ x, or.inl this) (suppose ¬ p ∣ x, have cpx : coprime p x, from coprime_of_prime_of_not_dvd pp this, obtain (a b : ℤ) (Hab : a * p + b * x = gcd p x), from Bezout_aux p x, have a * p * y + b * x * y = y, by krewrite [-right_distrib, Hab, ↑coprime at cpx, cpx, int.one_mul], have p ∣ y, begin apply dvd_of_of_nat_dvd_of_nat, rewrite [-this], apply @dvd_add, {apply dvd_mul_of_dvd_left, apply dvd_mul_of_dvd_right, apply dvd.refl}, {rewrite mul.assoc, apply dvd_mul_of_dvd_right, apply of_nat_dvd_of_nat_of_dvd H} end, or.inr this) end nat
b03169f768dcc942cf0586b3413535d09adf4d6d
9b9a16fa2cb737daee6b2785474678b6fa91d6d4
/src/field_theory/perfect_closure.lean
b69c055f3e72b3d5f8e87f005e158a44fb20958b
[ "Apache-2.0" ]
permissive
johoelzl/mathlib
253f46daa30b644d011e8e119025b01ad69735c4
592e3c7a2dfbd5826919b4605559d35d4d75938f
refs/heads/master
1,625,657,216,488
1,551,374,946,000
1,551,374,946,000
98,915,829
0
0
Apache-2.0
1,522,917,267,000
1,501,524,499,000
Lean
UTF-8
Lean
false
false
17,187
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Kenny Lau The perfect closure of a field. -/ import algebra.char_p universes u v /-- A perfect field is a field of characteristic p that has p-th root. -/ class perfect_field (α : Type u) [field α] (p : ℕ) [char_p α p] : Type u := (pth_root : α → α) (frobenius_pth_root : ∀ x, frobenius α p (pth_root x) = x) theorem frobenius_pth_root (α : Type u) [field α] (p : ℕ) [char_p α p] [perfect_field α p] (x : α) : frobenius α p (perfect_field.pth_root p x) = x := perfect_field.frobenius_pth_root p x theorem pth_root_frobenius (α : Type u) [field α] (p : ℕ) [nat.prime p] [char_p α p] [perfect_field α p] (x : α) : perfect_field.pth_root p (frobenius α p x) = x := frobenius_inj α p _ _ (by rw frobenius_pth_root) instance pth_root.is_ring_hom (α : Type u) [field α] (p : ℕ) [nat.prime p] [char_p α p] [perfect_field α p] : is_ring_hom (@perfect_field.pth_root α _ p _ _) := { map_one := frobenius_inj α p _ _ (by rw [frobenius_pth_root, frobenius_one]), map_mul := λ x y, frobenius_inj α p _ _ (by simp only [frobenius_pth_root, frobenius_mul]), map_add := λ x y, frobenius_inj α p _ _ (by simp only [frobenius_pth_root, frobenius_add]) } theorem is_ring_hom.pth_root {α : Type u} [field α] (p : ℕ) [nat.prime p] [char_p α p] [perfect_field α p] {β : Type v} [field β] [char_p β p] [perfect_field β p] (f : α → β) [is_ring_hom f] {x : α} : f (perfect_field.pth_root p x) = perfect_field.pth_root p (f x) := frobenius_inj β p _ _ (by rw [← is_monoid_hom.map_frobenius f, frobenius_pth_root, frobenius_pth_root]) inductive perfect_closure.r (α : Type u) [monoid α] (p : ℕ) : (ℕ × α) → (ℕ × α) → Prop | intro : ∀ n x, perfect_closure.r (n, x) (n+1, frobenius α p x) run_cmd tactic.mk_iff_of_inductive_prop `perfect_closure.r `perfect_closure.r_iff /-- The perfect closure is the smallest extension that makes frobenius surjective. -/ def perfect_closure (α : Type u) [monoid α] (p : ℕ) : Type u := quot (perfect_closure.r α p) namespace perfect_closure variables (α : Type u) private lemma mul_aux_left [comm_monoid α] (p : ℕ) (x1 x2 y : ℕ × α) (H : r α p x1 x2) : quot.mk (r α p) (x1.1 + y.1, ((frobenius α p)^[y.1] x1.2) * ((frobenius α p)^[x1.1] y.2)) = quot.mk (r α p) (x2.1 + y.1, ((frobenius α p)^[y.1] x2.2) * ((frobenius α p)^[x2.1] y.2)) := match x1, x2, H with | _, _, r.intro _ n x := quot.sound $ by rw [← nat.iterate_succ, nat.iterate_succ', nat.iterate_succ', ← frobenius_mul, nat.succ_add]; apply r.intro end private lemma mul_aux_right [comm_monoid α] (p : ℕ) (x y1 y2 : ℕ × α) (H : r α p y1 y2) : quot.mk (r α p) (x.1 + y1.1, ((frobenius α p)^[y1.1] x.2) * ((frobenius α p)^[x.1] y1.2)) = quot.mk (r α p) (x.1 + y2.1, ((frobenius α p)^[y2.1] x.2) * ((frobenius α p)^[x.1] y2.2)) := match y1, y2, H with | _, _, r.intro _ n y := quot.sound $ by rw [← nat.iterate_succ, nat.iterate_succ', nat.iterate_succ', ← frobenius_mul]; apply r.intro end instance [comm_monoid α] (p : ℕ) : has_mul (perfect_closure α p) := ⟨quot.lift (λ x:ℕ×α, quot.lift (λ y:ℕ×α, quot.mk (r α p) (x.1 + y.1, ((frobenius α p)^[y.1] x.2) * ((frobenius α p)^[x.1] y.2))) (mul_aux_right α p x)) (λ x1 x2 (H : r α p x1 x2), funext $ λ e, quot.induction_on e $ λ y, mul_aux_left α p x1 x2 y H)⟩ instance [comm_monoid α] (p : ℕ) : comm_monoid (perfect_closure α p) := { mul_assoc := λ e f g, quot.induction_on e $ λ ⟨m, x⟩, quot.induction_on f $ λ ⟨n, y⟩, quot.induction_on g $ λ ⟨s, z⟩, congr_arg (quot.mk _) $ by simp only [add_assoc, mul_assoc, nat.iterate₂ (frobenius_mul _ _), (nat.iterate_add _ _ _ _).symm, add_comm, add_left_comm], one := quot.mk _ (0, 1), one_mul := λ e, quot.induction_on e (λ ⟨n, x⟩, congr_arg (quot.mk _) $ by simp only [nat.iterate₀ (frobenius_one _ _), nat.iterate_zero, one_mul, zero_add]), mul_one := λ e, quot.induction_on e (λ ⟨n, x⟩, congr_arg (quot.mk _) $ by simp only [nat.iterate₀ (frobenius_one _ _), nat.iterate_zero, mul_one, add_zero]), mul_comm := λ e f, quot.induction_on e (λ ⟨m, x⟩, quot.induction_on f (λ ⟨n, y⟩, congr_arg (quot.mk _) $ by simp only [add_comm, mul_comm])), .. (infer_instance : has_mul (perfect_closure α p)) } private lemma add_aux_left [comm_ring α] (p : ℕ) (hp : nat.prime p) [char_p α p] (x1 x2 y : ℕ × α) (H : r α p x1 x2) : quot.mk (r α p) (x1.1 + y.1, ((frobenius α p)^[y.1] x1.2) + ((frobenius α p)^[x1.1] y.2)) = quot.mk (r α p) (x2.1 + y.1, ((frobenius α p)^[y.1] x2.2) + ((frobenius α p)^[x2.1] y.2)) := match x1, x2, H with | _, _, r.intro _ n x := quot.sound $ by rw [← nat.iterate_succ, nat.iterate_succ', nat.iterate_succ', ← frobenius_add, nat.succ_add]; apply r.intro end private lemma add_aux_right [comm_ring α] (p : ℕ) (hp : nat.prime p) [char_p α p] (x y1 y2 : ℕ × α) (H : r α p y1 y2) : quot.mk (r α p) (x.1 + y1.1, ((frobenius α p)^[y1.1] x.2) + ((frobenius α p)^[x.1] y1.2)) = quot.mk (r α p) (x.1 + y2.1, ((frobenius α p)^[y2.1] x.2) + ((frobenius α p)^[x.1] y2.2)) := match y1, y2, H with | _, _, r.intro _ n y := quot.sound $ by rw [← nat.iterate_succ, nat.iterate_succ', nat.iterate_succ', ← frobenius_add]; apply r.intro end instance [comm_ring α] (p : ℕ) [hp : nat.prime p] [char_p α p] : has_add (perfect_closure α p) := ⟨quot.lift (λ x:ℕ×α, quot.lift (λ y:ℕ×α, quot.mk (r α p) (x.1 + y.1, ((frobenius α p)^[y.1] x.2) + ((frobenius α p)^[x.1] y.2))) (add_aux_right α p hp x)) (λ x1 x2 (H : r α p x1 x2), funext $ λ e, quot.induction_on e $ λ y, add_aux_left α p hp x1 x2 y H)⟩ instance [comm_ring α] (p : ℕ) [nat.prime p] [char_p α p] : has_neg (perfect_closure α p) := ⟨quot.lift (λ x:ℕ×α, quot.mk (r α p) (x.1, -x.2)) (λ x y (H : r α p x y), match x, y, H with | _, _, r.intro _ n x := quot.sound $ by rw ← frobenius_neg; apply r.intro end)⟩ theorem mk_zero [comm_ring α] (p : ℕ) [nat.prime p] (n : ℕ) : quot.mk (r α p) (n, 0) = quot.mk (r α p) (0, 0) := by induction n with n ih; [refl, rw ← ih]; symmetry; apply quot.sound; have := r.intro p n (0:α); rwa [frobenius_zero α p] at this theorem r.sound [monoid α] (p m n : ℕ) (x y : α) (H : frobenius α p^[m] x = y) : quot.mk (r α p) (n, x) = quot.mk (r α p) (m + n, y) := by subst H; induction m with m ih; [simp only [zero_add, nat.iterate_zero], rw [ih, nat.succ_add, nat.iterate_succ']]; apply quot.sound; apply r.intro instance [comm_ring α] (p : ℕ) [nat.prime p] [char_p α p] : comm_ring (perfect_closure α p) := { add_assoc := λ e f g, quot.induction_on e $ λ ⟨m, x⟩, quot.induction_on f $ λ ⟨n, y⟩, quot.induction_on g $ λ ⟨s, z⟩, congr_arg (quot.mk _) $ by simp only [add_assoc, nat.iterate₂ (frobenius_add α p), (nat.iterate_add _ _ _ _).symm, add_comm, add_left_comm], zero := quot.mk _ (0, 0), zero_add := λ e, quot.induction_on e (λ ⟨n, x⟩, congr_arg (quot.mk _) $ by simp only [nat.iterate₀ (frobenius_zero α p), nat.iterate_zero, zero_add]), add_zero := λ e, quot.induction_on e (λ ⟨n, x⟩, congr_arg (quot.mk _) $ by simp only [nat.iterate₀ (frobenius_zero α p), nat.iterate_zero, add_zero]), add_left_neg := λ e, quot.induction_on e (λ ⟨n, x⟩, show quot.mk _ _ = _, by simp only [nat.iterate₁ (frobenius_neg α p), add_left_neg, mk_zero]; refl), add_comm := λ e f, quot.induction_on e (λ ⟨m, x⟩, quot.induction_on f (λ ⟨n, y⟩, congr_arg (quot.mk _) $ by simp only [add_comm])), left_distrib := λ e f g, quot.induction_on e $ λ ⟨m, x⟩, quot.induction_on f $ λ ⟨n, y⟩, quot.induction_on g $ λ ⟨s, z⟩, show quot.mk _ _ = quot.mk _ _, by simp only [add_assoc, add_comm, add_left_comm]; apply r.sound; simp only [nat.iterate₂ (frobenius_mul α p), nat.iterate₂ (frobenius_add α p), (nat.iterate_add _ _ _ _).symm, mul_add, add_comm, add_left_comm], right_distrib := λ e f g, quot.induction_on e $ λ ⟨m, x⟩, quot.induction_on f $ λ ⟨n, y⟩, quot.induction_on g $ λ ⟨s, z⟩, show quot.mk _ _ = quot.mk _ _, by simp only [add_assoc, add_comm _ s, add_left_comm _ s]; apply r.sound; simp only [nat.iterate₂ (frobenius_mul α p), nat.iterate₂ (frobenius_add α p), (nat.iterate_add _ _ _ _).symm, add_mul, add_comm, add_left_comm], .. (infer_instance : has_add (perfect_closure α p)), .. (infer_instance : has_neg (perfect_closure α p)), .. (infer_instance : comm_monoid (perfect_closure α p)) } instance [discrete_field α] (p : ℕ) [nat.prime p] [char_p α p] : has_inv (perfect_closure α p) := ⟨quot.lift (λ x:ℕ×α, quot.mk (r α p) (x.1, x.2⁻¹)) (λ x y (H : r α p x y), match x, y, H with | _, _, r.intro _ n x := quot.sound $ by simp only [frobenius]; rw inv_pow'; apply r.intro end)⟩ theorem eq_iff' [comm_ring α] (p : ℕ) [nat.prime p] [char_p α p] (x y : ℕ × α) : quot.mk (r α p) x = quot.mk (r α p) y ↔ ∃ z, (frobenius α p^[y.1 + z] x.2) = (frobenius α p^[x.1 + z] y.2) := begin split, { intro H, replace H := quot.exact _ H, induction H, case eqv_gen.rel : x y H { cases H with n x, exact ⟨0, rfl⟩ }, case eqv_gen.refl : H { exact ⟨0, rfl⟩ }, case eqv_gen.symm : x y H ih { cases ih with w ih, exact ⟨w, ih.symm⟩ }, case eqv_gen.trans : x y z H1 H2 ih1 ih2 { cases ih1 with z1 ih1, cases ih2 with z2 ih2, existsi z2+(y.1+z1), rw [← add_assoc, nat.iterate_add, ih1], rw [← nat.iterate_add, add_comm, nat.iterate_add, ih2], rw [← nat.iterate_add], simp only [add_comm, add_left_comm] } }, intro H, cases x with m x, cases y with n y, cases H with z H, dsimp only at H, rw [r.sound α p (n+z) m x _ rfl, r.sound α p (m+z) n y _ rfl, H], rw [add_assoc, add_comm, add_comm z] end theorem eq_iff [integral_domain α] (p : ℕ) [nat.prime p] [char_p α p] (x y : ℕ × α) : quot.mk (r α p) x = quot.mk (r α p) y ↔ (frobenius α p^[y.1] x.2) = (frobenius α p^[x.1] y.2) := (eq_iff' α p x y).trans ⟨λ ⟨z, H⟩, nat.iterate_inj (frobenius_inj α p) z _ _ $ by simpa only [add_comm, nat.iterate_add] using H, λ H, ⟨0, H⟩⟩ instance [discrete_field α] (p : ℕ) [nat.prime p] [char_p α p] : discrete_field (perfect_closure α p) := { zero_ne_one := λ H, zero_ne_one ((eq_iff _ _ _ _).1 H), mul_inv_cancel := λ e, quot.induction_on e $ λ ⟨m, x⟩ H, have _ := mt (eq_iff _ _ _ _).2 H, (eq_iff _ _ _ _).2 (by simp only [nat.iterate₀ (frobenius_one _ _), nat.iterate₀ (frobenius_zero α p), nat.iterate_zero, (nat.iterate₂ (frobenius_mul α p)).symm] at this ⊢; rw [mul_inv_cancel this, nat.iterate₀ (frobenius_one _ _)]), inv_mul_cancel := λ e, quot.induction_on e $ λ ⟨m, x⟩ H, have _ := mt (eq_iff _ _ _ _).2 H, (eq_iff _ _ _ _).2 (by simp only [nat.iterate₀ (frobenius_one _ _), nat.iterate₀ (frobenius_zero α p), nat.iterate_zero, (nat.iterate₂ (frobenius_mul α p)).symm] at this ⊢; rw [inv_mul_cancel this, nat.iterate₀ (frobenius_one _ _)]), has_decidable_eq := λ e f, quot.rec_on_subsingleton e $ λ ⟨m, x⟩, quot.rec_on_subsingleton f $ λ ⟨n, y⟩, decidable_of_iff' _ (eq_iff α p _ _), inv_zero := congr_arg (quot.mk (r α p)) (by rw [inv_zero]), .. (infer_instance : has_inv (perfect_closure α p)), .. (infer_instance : comm_ring (perfect_closure α p)) } theorem frobenius_mk [comm_monoid α] (p : ℕ) (x : ℕ × α) : frobenius (perfect_closure α p) p (quot.mk (r α p) x) = quot.mk _ (x.1, x.2^p) := begin unfold frobenius, cases x with n x, dsimp only, suffices : ∀ p':ℕ, (quot.mk (r α p) (n, x) ^ p' : perfect_closure α p) = quot.mk (r α p) (n, x ^ p'), { apply this }, intro p, induction p with p ih, case nat.zero { apply r.sound, rw [nat.iterate₀ (frobenius_one _ _), pow_zero] }, case nat.succ { rw [pow_succ, ih], symmetry, apply r.sound, simp only [pow_succ, nat.iterate₂ (frobenius_mul _ _)] } end def frobenius_equiv [comm_ring α] (p : ℕ) [nat.prime p] [char_p α p] : perfect_closure α p ≃ perfect_closure α p := { to_fun := frobenius (perfect_closure α p) p, inv_fun := λ e, quot.lift_on e (λ x, quot.mk (r α p) (x.1 + 1, x.2)) (λ x y H, match x, y, H with | _, _, r.intro _ n x := quot.sound (r.intro _ _ _) end), left_inv := λ e, quot.induction_on e (λ ⟨m, x⟩, by rw frobenius_mk; symmetry; apply quot.sound; apply r.intro), right_inv := λ e, quot.induction_on e (λ ⟨m, x⟩, by rw frobenius_mk; symmetry; apply quot.sound; apply r.intro) } theorem frobenius_equiv_apply [comm_ring α] (p : ℕ) [nat.prime p] [char_p α p] {x : perfect_closure α p} : frobenius_equiv α p x = frobenius _ p x := rfl theorem nat_cast [comm_ring α] (p : ℕ) [nat.prime p] [char_p α p] (n x : ℕ) : (x : perfect_closure α p) = quot.mk (r α p) (n, x) := begin induction n with n ih, { induction x with x ih, {refl}, rw [nat.cast_succ, nat.cast_succ, ih], refl }, rw ih, apply quot.sound, conv {congr, skip, skip, rw ← frobenius_nat_cast α p x}, apply r.intro end theorem int_cast [comm_ring α] (p : ℕ) [nat.prime p] [char_p α p] (x : ℤ) : (x : perfect_closure α p) = quot.mk (r α p) (0, x) := by induction x; simp only [int.cast_of_nat, int.cast_neg_succ_of_nat, nat_cast α p 0]; refl theorem nat_cast_eq_iff [comm_ring α] (p : ℕ) [nat.prime p] [char_p α p] (x y : ℕ) : (x : perfect_closure α p) = y ↔ (x : α) = y := begin split; intro H, { rw [nat_cast α p 0, nat_cast α p 0, eq_iff'] at H, cases H with z H, simpa only [zero_add, nat.iterate₀ (frobenius_nat_cast α p _)] using H }, rw [nat_cast α p 0, nat_cast α p 0, H] end instance [comm_ring α] (p : ℕ) [nat.prime p] [char_p α p] : char_p (perfect_closure α p) p := begin constructor, intro x, rw ← char_p.cast_eq_zero_iff α, rw [← nat.cast_zero, nat_cast_eq_iff, nat.cast_zero] end instance [discrete_field α] (p : ℕ) [nat.prime p] [char_p α p] : perfect_field (perfect_closure α p) p := { pth_root := (frobenius_equiv α p).symm, frobenius_pth_root := (frobenius_equiv α p).apply_inverse_apply } def of [monoid α] (p : ℕ) (x : α) : perfect_closure α p := quot.mk _ (0, x) instance [comm_ring α] (p : ℕ) [nat.prime p] [char_p α p] : is_ring_hom (of α p) := { map_one := rfl, map_mul := λ x y, rfl, map_add := λ x y, rfl } theorem eq_pth_root [discrete_field α] (p : ℕ) [nat.prime p] [char_p α p] (m : ℕ) (x : α) : quot.mk (r α p) (m, x) = (perfect_field.pth_root p^[m] (of α p x) : perfect_closure α p) := begin unfold of, induction m with m ih, {refl}, rw [nat.iterate_succ', ← ih]; refl end def UMP [discrete_field α] (p : ℕ) [nat.prime p] [char_p α p] (β : Type v) [discrete_field β] [char_p β p] [perfect_field β p] : { f : α → β // is_ring_hom f } ≃ { f : perfect_closure α p → β // is_ring_hom f } := { to_fun := λ f, ⟨λ e, quot.lift_on e (λ x, perfect_field.pth_root p^[x.1] (f.1 x.2)) (λ x y H, match x, y, H with | _, _, r.intro _ n x := by letI := f.2; simp only [is_monoid_hom.map_frobenius f.1, nat.iterate_succ, pth_root_frobenius] end), show f.1 1 = 1, from f.2.1, λ j k, quot.induction_on j $ λ ⟨m, x⟩, quot.induction_on k $ λ ⟨n, y⟩, show (perfect_field.pth_root p^[_] _) = (perfect_field.pth_root p^[_] _) * (perfect_field.pth_root p^[_] _), by letI := f.2; simp only [is_ring_hom.map_mul f.1, (nat.iterate₁ (λ x, (is_monoid_hom.map_frobenius f.1 p x).symm)).symm, @nat.iterate₂ β _ (*) (λ x y, is_ring_hom.map_mul (perfect_field.pth_root p))]; rw [nat.iterate_add, nat.iterate_cancel (pth_root_frobenius β p), add_comm, nat.iterate_add, nat.iterate_cancel (pth_root_frobenius β p)], λ j k, quot.induction_on j $ λ ⟨m, x⟩, quot.induction_on k $ λ ⟨n, y⟩, show (perfect_field.pth_root p^[_] _) = (perfect_field.pth_root p^[_] _) + (perfect_field.pth_root p^[_] _), by letI := f.2; simp only [is_ring_hom.map_add f.1, (nat.iterate₁ (λ x, (is_monoid_hom.map_frobenius f.1 p x).symm)).symm, @nat.iterate₂ β _ (+) (λ x y, is_ring_hom.map_add (perfect_field.pth_root p))]; rw [nat.iterate_add, nat.iterate_cancel (pth_root_frobenius β p), add_comm m, nat.iterate_add, nat.iterate_cancel (pth_root_frobenius β p)]⟩, inv_fun := λ f, ⟨f.1 ∘ of α p, @@is_ring_hom.comp _ _ _ _ _ _ f.2⟩, left_inv := λ ⟨f, hf⟩, subtype.eq rfl, right_inv := λ ⟨f, hf⟩, subtype.eq $ funext $ λ i, quot.induction_on i $ λ ⟨m, x⟩, show perfect_field.pth_root p^[m] (f _) = f _, by resetI; rw [eq_pth_root, @nat.iterate₁ _ _ _ _ f (λ x:perfect_closure α p, (is_ring_hom.pth_root p f).symm)] } end perfect_closure
566bdaea81ad1e99a5b903063eaccfcdde9b3b99
f083c4ed5d443659f3ed9b43b1ca5bb037ddeb58
/algebra/field_power.lean
d6f640a5b88e5f62211f9281d23549cc4483019b
[ "Apache-2.0" ]
permissive
semorrison/mathlib
1be6f11086e0d24180fec4b9696d3ec58b439d10
20b4143976dad48e664c4847b75a85237dca0a89
refs/heads/master
1,583,799,212,170
1,535,634,130,000
1,535,730,505,000
129,076,205
0
0
Apache-2.0
1,551,697,998,000
1,523,442,265,000
Lean
UTF-8
Lean
false
false
3,313
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis Integer power operation on fields. -/ import algebra.group_power tactic.wlog universe u section field_power open int nat variables {α : Type u} [division_ring α] @[simp] lemma zero_gpow : ∀ z : ℕ, z ≠ 0 → (0 : α)^z = 0 | 0 h := absurd rfl h | (k+1) h := zero_mul _ def fpow (a : α) : ℤ → α | (of_nat n) := a ^ n | -[1+n] := 1/(a ^ (n+1)) lemma unit_pow {a : α} (ha : a ≠ 0) : ∀ n : ℕ, a ^ n = ↑((units.mk0 a ha)^n) | 0 := by simp; refl | (k+1) := by simp [_root_.pow_add]; congr; apply unit_pow lemma fpow_eq_gpow {a : α} (h : a ≠ 0) : ∀ (z : ℤ), fpow a z = ↑(gpow (units.mk0 a h) z) | (of_nat k) := by simp only [fpow, gpow]; apply unit_pow | -[1+k] := by simp [fpow, gpow]; congr; apply unit_pow lemma fpow_inv (a : α) : fpow a (-1) = a⁻¹ := begin change fpow a -[1+0] = a⁻¹, simp [fpow] end lemma fpow_ne_zero_of_ne_zero {a : α} (ha : a ≠ 0) : ∀ (z : ℤ), fpow a z ≠ 0 | (of_nat n) := pow_ne_zero _ ha | -[1+n] := one_div_ne_zero $ pow_ne_zero _ ha @[simp] lemma fpow_zero {a : α} : fpow a 0 = 1 := pow_zero _ lemma fpow_add {a : α} (ha : a ≠ 0) (z1 z2 : ℤ) : fpow a (z1 + z2) = fpow a z1 * fpow a z2 := begin simp only [fpow_eq_gpow ha], rw ←units.mul_coe, congr, apply gpow_add end end field_power section discrete_field_power open int nat variables {α : Type u} [discrete_field α] lemma zero_fpow : ∀ z : ℤ, z ≠ 0 → fpow (0 : α) z = 0 | (of_nat n) h := have h2 : n ≠ 0, from assume : n = 0, by simpa [this] using h, by simp [h, h2, fpow] | -[1+n] h := have h1 : (0 : α) ^ (n+1) = 0, from zero_mul _, by simp [fpow, h1] end discrete_field_power section ordered_field_power open int variables {α : Type u} [discrete_linear_ordered_field α] lemma fpow_nonneg_of_nonneg {a : α} (ha : a ≥ 0) : ∀ (z : ℤ), fpow a z ≥ 0 | (of_nat n) := pow_nonneg ha _ | -[1+n] := div_nonneg' zero_le_one $ pow_nonneg ha _ lemma fpow_le_of_le {x : α} (hx : 1 ≤ x) {a b : ℤ} (h : a ≤ b) : fpow x a ≤ fpow x b := begin induction a with a a; induction b with b b, { simp only [fpow], apply pow_le_pow hx, apply le_of_coe_nat_le_coe_nat h }, { apply absurd h, apply not_le_of_gt, exact lt_of_lt_of_le (neg_succ_lt_zero _) (of_nat_nonneg _) }, { simp only [fpow, one_div_eq_inv], apply le_trans (inv_le_one _); apply one_le_pow_of_one_le hx }, { simp only [fpow], apply (one_div_le_one_div _ _).2, { apply pow_le_pow hx, have : -(↑(a+1) : ℤ) ≤ -(↑(b+1) : ℤ), from h, have h' := le_of_neg_le_neg this, apply le_of_coe_nat_le_coe_nat h' }, repeat { apply pow_pos (lt_of_lt_of_le zero_lt_one hx) } } end lemma pow_le_max_of_min_le {x : α} (hx : x ≥ 1) {a b c : ℤ} (h : min a b ≤ c) : fpow x (-c) ≤ max (fpow x (-a)) (fpow x (-b)) := begin wlog hle : a ≤ b, have hnle : -b ≤ -a, from neg_le_neg hle, have hfle : fpow x (-b) ≤ fpow x (-a), from fpow_le_of_le hx hnle, have : fpow x (-c) ≤ fpow x (-a), { apply fpow_le_of_le hx, simpa [hle, min_eq_left] using h }, simpa [hfle, max_eq_left] using this end end ordered_field_power
18c01638fb47db523229690ade2ff1ece98b92a2
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/topology/compact_open.lean
566c6ddcc13a20b3bd5d293fc690144399504529
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,685
lean
/- Copyright (c) 2018 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton -/ import tactic.tidy import topology.continuous_function.basic import topology.homeomorph import topology.subset_properties /-! # The compact-open topology In this file, we define the compact-open topology on the set of continuous maps between two topological spaces. ## Main definitions * `compact_open` is the compact-open topology on `C(α, β)`. It is declared as an instance. * `ev` is the evaluation map `C(α, β) × α → β`. It is continuous as long as `α` is locally compact. * `coev` is the coevaluation map `β → C(α, β × α)`. It is always continuous. * `continuous_map.curry` is the currying map `C(α × β, γ) → C(α, C(β, γ))`. This map always exists and it is continuous as long as `α × β` is locally compact. * `continuous_map.uncurry` is the uncurrying map `C(α, C(β, γ)) → C(α × β, γ)`. For this map to exist, we need `β` to be locally compact. If `α` is also locally compact, then this map is continuous. * `homeomorph.curry` combines the currying and uncurrying operations into a homeomorphism `C(α × β, γ) ≃ₜ C(α, C(β, γ))`. This homeomorphism exists if `α` and `β` are locally compact. ## Tags compact-open, curry, function space -/ open set open_locale topological_space namespace continuous_map section compact_open variables {α : Type*} {β : Type*} {γ : Type*} variables [topological_space α] [topological_space β] [topological_space γ] /-- A generating set for the compact-open topology (when `s` is compact and `u` is open). -/ def compact_open.gen (s : set α) (u : set β) : set C(α,β) := {f | f '' s ⊆ u} -- The compact-open topology on the space of continuous maps α → β. instance compact_open : topological_space C(α, β) := topological_space.generate_from {m | ∃ (s : set α) (hs : is_compact s) (u : set β) (hu : is_open u), m = compact_open.gen s u} private lemma is_open_gen {s : set α} (hs : is_compact s) {u : set β} (hu : is_open u) : is_open (compact_open.gen s u) := topological_space.generate_open.basic _ (by dsimp [mem_set_of_eq]; tauto) section functorial variables (g : C(β, γ)) private lemma preimage_gen {s : set α} (hs : is_compact s) {u : set γ} (hu : is_open u) : continuous_map.comp g ⁻¹' (compact_open.gen s u) = compact_open.gen s (g ⁻¹' u) := begin ext ⟨f, _⟩, change g ∘ f '' s ⊆ u ↔ f '' s ⊆ g ⁻¹' u, rw [image_comp, image_subset_iff] end /-- C(α, -) is a functor. -/ lemma continuous_comp : continuous (continuous_map.comp g : C(α, β) → C(α, γ)) := continuous_generated_from $ assume m ⟨s, hs, u, hu, hm⟩, by rw [hm, preimage_gen g hs hu]; exact is_open_gen hs (hu.preimage g.2) end functorial section ev variables (α β) /-- The evaluation map `map C(α, β) × α → β` -/ def ev (p : C(α, β) × α) : β := p.1 p.2 variables {α β} /-- The evaluation map `C(α, β) × α → β` is continuous if `α` is locally compact. -/ lemma continuous_ev [locally_compact_space α] : continuous (ev α β) := continuous_iff_continuous_at.mpr $ assume ⟨f, x⟩ n hn, let ⟨v, vn, vo, fxv⟩ := mem_nhds_iff.mp hn in have v ∈ 𝓝 (f x), from is_open.mem_nhds vo fxv, let ⟨s, hs, sv, sc⟩ := locally_compact_space.local_compact_nhds x (f ⁻¹' v) (f.continuous.tendsto x this) in let ⟨u, us, uo, xu⟩ := mem_nhds_iff.mp hs in show (ev α β) ⁻¹' n ∈ 𝓝 (f, x), from let w := set.prod (compact_open.gen s v) u in have w ⊆ ev α β ⁻¹' n, from assume ⟨f', x'⟩ ⟨hf', hx'⟩, calc f' x' ∈ f' '' s : mem_image_of_mem f' (us hx') ... ⊆ v : hf' ... ⊆ n : vn, have is_open w, from (is_open_gen sc vo).prod uo, have (f, x) ∈ w, from ⟨image_subset_iff.mpr sv, xu⟩, mem_nhds_iff.mpr ⟨w, by assumption, by assumption, by assumption⟩ lemma continuous_ev₁ [locally_compact_space α] (a : α) : continuous (λ f : C(α, β), f a) := continuous_ev.comp (continuous_id.prod_mk continuous_const) instance [t2_space β] [locally_compact_space α] : t2_space C(α, β) := ⟨ begin intros f₁ f₂ h, obtain ⟨p, hp⟩ := not_forall.mp (mt continuous_map.ext h), exact separated_by_continuous (continuous_ev₁ p) hp, end ⟩ end ev section Inf_induced lemma compact_open_le_induced (s : set α) : (continuous_map.compact_open : topological_space C(α, β)) ≤ topological_space.induced (continuous_map.restrict s) continuous_map.compact_open := begin simp only [induced_generate_from_eq, continuous_map.compact_open], apply generate_from_mono, rintros b ⟨a, ⟨c, hc, u, hu, rfl⟩, rfl⟩, refine ⟨coe '' c, hc.image continuous_subtype_coe, u, hu, _⟩, ext f, simp only [compact_open.gen, mem_set_of_eq, mem_preimage, continuous_map.coe_restrict], rw image_comp f (coe : s → α), end /-- The compact-open topology on `C(α, β)` is equal to the infimum of the compact-open topologies on `C(s, β)` for `s` a compact subset of `α`. The key point of the proof is that the union of the compact subsets of `α` is equal to the union of compact subsets of the compact subsets of `α`. -/ lemma compact_open_eq_Inf_induced : (continuous_map.compact_open : topological_space C(α, β)) = ⨅ (s : set α) (hs : is_compact s), topological_space.induced (continuous_map.restrict s) continuous_map.compact_open := begin refine le_antisymm _ _, { refine le_binfi _, exact λ s hs, compact_open_le_induced s }, simp only [← generate_from_Union, induced_generate_from_eq, continuous_map.compact_open], apply generate_from_mono, rintros _ ⟨s, hs, u, hu, rfl⟩, rw mem_bUnion_iff', refine ⟨s, hs, _, ⟨univ, is_compact_iff_is_compact_univ.mp hs, u, hu, rfl⟩, _⟩, ext f, simp only [compact_open.gen, mem_set_of_eq, mem_preimage, continuous_map.coe_restrict], rw image_comp f (coe : s → α), simp end /-- For any subset `s` of `α`, the restriction of continuous functions to `s` is continuous as a function from `C(α, β)` to `C(s, β)` with their respective compact-open topologies. -/ lemma continuous_restrict (s : set α) : continuous (λ F : C(α, β), F.restrict s) := by { rw continuous_iff_le_induced, exact compact_open_le_induced s } lemma nhds_compact_open_eq_Inf_nhds_induced (f : C(α, β)) : 𝓝 f = ⨅ s (hs : is_compact s), (𝓝 (f.restrict s)).comap (continuous_map.restrict s) := by { rw [compact_open_eq_Inf_induced], simp [nhds_infi, nhds_induced] } lemma tendsto_compact_open_restrict {ι : Type*} {l : filter ι} {F : ι → C(α, β)} {f : C(α, β)} (hFf : filter.tendsto F l (𝓝 f)) (s : set α) : filter.tendsto (λ i, (F i).restrict s) l (𝓝 (f.restrict s)) := (continuous_restrict s).continuous_at.tendsto.comp hFf lemma tendsto_compact_open_iff_forall {ι : Type*} {l : filter ι} (F : ι → C(α, β)) (f : C(α, β)) : filter.tendsto F l (𝓝 f) ↔ ∀ s (hs : is_compact s), filter.tendsto (λ i, (F i).restrict s) l (𝓝 (f.restrict s)) := by { rw [compact_open_eq_Inf_induced], simp [nhds_infi, nhds_induced, filter.tendsto_comap_iff] } /-- A family `F` of functions in `C(α, β)` converges in the compact-open topology, if and only if it converges in the compact-open topology on each compact subset of `α`. -/ lemma exists_tendsto_compact_open_iff_forall [locally_compact_space α] [t2_space α] [t2_space β] {ι : Type*} {l : filter ι} [filter.ne_bot l] (F : ι → C(α, β)) : (∃ f, filter.tendsto F l (𝓝 f)) ↔ ∀ (s : set α) (hs : is_compact s), ∃ f, filter.tendsto (λ i, (F i).restrict s) l (𝓝 f) := begin split, { rintros ⟨f, hf⟩ s hs, exact ⟨f.restrict s, tendsto_compact_open_restrict hf s⟩ }, { intros h, choose f hf using h, -- By uniqueness of limits in a `t2_space`, since `λ i, F i x` tends to both `f s₁ hs₁ x` and -- `f s₂ hs₂ x`, we have `f s₁ hs₁ x = f s₂ hs₂ x` have h : ∀ s₁ (hs₁ : is_compact s₁) s₂ (hs₂ : is_compact s₂) (x : α) (hxs₁ : x ∈ s₁) (hxs₂ : x ∈ s₂), f s₁ hs₁ ⟨x, hxs₁⟩ = f s₂ hs₂ ⟨x, hxs₂⟩, { rintros s₁ hs₁ s₂ hs₂ x hxs₁ hxs₂, haveI := is_compact_iff_compact_space.mp hs₁, haveI := is_compact_iff_compact_space.mp hs₂, have h₁ := (continuous_ev₁ (⟨x, hxs₁⟩ : s₁)).continuous_at.tendsto.comp (hf s₁ hs₁), have h₂ := (continuous_ev₁ (⟨x, hxs₂⟩ : s₂)).continuous_at.tendsto.comp (hf s₂ hs₂), exact tendsto_nhds_unique h₁ h₂ }, -- So glue the `f s hs` together and prove that this glued function `f₀` is a limit on each -- compact set `s` have hs : ∀ x : α, ∃ s (hs : is_compact s), s ∈ 𝓝 x, { intros x, obtain ⟨s, hs, hs'⟩ := exists_compact_mem_nhds x, exact ⟨s, hs, hs'⟩ }, refine ⟨lift_cover' _ _ h hs, _⟩, rw tendsto_compact_open_iff_forall, intros s hs, rw lift_cover_restrict', exact hf s hs } end end Inf_induced section coev variables (α β) /-- The coevaluation map `β → C(α, β × α)` sending a point `x : β` to the continuous function on `α` sending `y` to `(x, y)`. -/ def coev (b : β) : C(α, β × α) := ⟨λ a, (b, a), continuous.prod_mk continuous_const continuous_id⟩ variables {α β} lemma image_coev {y : β} (s : set α) : (coev α β y) '' s = set.prod {y} s := by tidy -- The coevaluation map β → C(α, β × α) is continuous (always). lemma continuous_coev : continuous (coev α β) := continuous_generated_from $ begin rintros _ ⟨s, sc, u, uo, rfl⟩, rw is_open_iff_forall_mem_open, intros y hy, change (coev α β y) '' s ⊆ u at hy, rw image_coev s at hy, rcases generalized_tube_lemma is_compact_singleton sc uo hy with ⟨v, w, vo, wo, yv, sw, vwu⟩, refine ⟨v, _, vo, singleton_subset_iff.mp yv⟩, intros y' hy', change (coev α β y') '' s ⊆ u, rw image_coev s, exact subset.trans (prod_mono (singleton_subset_iff.mpr hy') sw) vwu end end coev section curry /-- Auxiliary definition, see `continuous_map.curry` and `homeomorph.curry`. -/ def curry' (f : C(α × β, γ)) (a : α) : C(β, γ) := ⟨function.curry f a⟩ /-- If a map `α × β → γ` is continuous, then its curried form `α → C(β, γ)` is continuous. -/ lemma continuous_curry' (f : C(α × β, γ)) : continuous (curry' f) := have hf : curry' f = continuous_map.comp f ∘ coev _ _, by { ext, refl }, hf ▸ continuous.comp (continuous_comp f) continuous_coev /-- To show continuity of a map `α → C(β, γ)`, it suffices to show that its uncurried form `α × β → γ` is continuous. -/ lemma continuous_of_continuous_uncurry (f : α → C(β, γ)) (h : continuous (function.uncurry (λ x y, f x y))) : continuous f := by { convert continuous_curry' ⟨_, h⟩, ext, refl } /-- The curried form of a continuous map `α × β → γ` as a continuous map `α → C(β, γ)`. If `a × β` is locally compact, this is continuous. If `α` and `β` are both locally compact, then this is a homeomorphism, see `homeomorph.curry`. -/ def curry (f : C(α × β, γ)) : C(α, C(β, γ)) := ⟨_, continuous_curry' f⟩ /-- The currying process is a continuous map between function spaces. -/ lemma continuous_curry [locally_compact_space (α × β)] : continuous (curry : C(α × β, γ) → C(α, C(β, γ))) := begin apply continuous_of_continuous_uncurry, apply continuous_of_continuous_uncurry, rw ←homeomorph.comp_continuous_iff' (homeomorph.prod_assoc _ _ _).symm, convert continuous_ev; tidy end @[simp] lemma curry_apply (f : C(α × β, γ)) (a : α) (b : β) : f.curry a b = f (a, b) := rfl /-- The uncurried form of a continuous map `α → C(β, γ)` is a continuous map `α × β → γ`. -/ lemma continuous_uncurry_of_continuous [locally_compact_space β] (f : C(α, C(β, γ))) : continuous (function.uncurry (λ x y, f x y)) := have hf : function.uncurry (λ x y, f x y) = ev β γ ∘ prod.map f id, by { ext, refl }, hf ▸ continuous.comp continuous_ev $ continuous.prod_map f.2 id.2 /-- The uncurried form of a continuous map `α → C(β, γ)` as a continuous map `α × β → γ` (if `β` is locally compact). If `α` is also locally compact, then this is a homeomorphism between the two function spaces, see `homeomorph.curry`. -/ def uncurry [locally_compact_space β] (f : C(α, C(β, γ))) : C(α × β, γ) := ⟨_, continuous_uncurry_of_continuous f⟩ /-- The uncurrying process is a continuous map between function spaces. -/ lemma continuous_uncurry [locally_compact_space α] [locally_compact_space β] : continuous (uncurry : C(α, C(β, γ)) → C(α × β, γ)) := begin apply continuous_of_continuous_uncurry, rw ←homeomorph.comp_continuous_iff' (homeomorph.prod_assoc _ _ _), apply continuous.comp continuous_ev (continuous.prod_map continuous_ev id.2); apply_instance end /-- The family of constant maps: `β → C(α, β)` as a continuous map. -/ def const' : C(β, C(α, β)) := curry ⟨prod.fst, continuous_fst⟩ @[simp] lemma coe_const' : (const' : β → C(α, β)) = const := rfl lemma continuous_const' : continuous (const : β → C(α, β)) := const'.continuous end curry end compact_open end continuous_map open continuous_map namespace homeomorph variables {α : Type*} {β : Type*} {γ : Type*} variables [topological_space α] [topological_space β] [topological_space γ] /-- Currying as a homeomorphism between the function spaces `C(α × β, γ)` and `C(α, C(β, γ))`. -/ def curry [locally_compact_space α] [locally_compact_space β] : C(α × β, γ) ≃ₜ C(α, C(β, γ)) := ⟨⟨curry, uncurry, by tidy, by tidy⟩, continuous_curry, continuous_uncurry⟩ /-- If `α` has a single element, then `β` is homeomorphic to `C(α, β)`. -/ def continuous_map_of_unique [unique α] : β ≃ₜ C(α, β) := { to_fun := continuous_map.comp ⟨_, continuous_fst⟩ ∘ coev α β, inv_fun := ev α β ∘ (λ f, (f, default α)), left_inv := λ a, rfl, right_inv := λ f, by { ext, rw unique.eq_default x, refl }, continuous_to_fun := continuous.comp (continuous_comp _) continuous_coev, continuous_inv_fun := continuous.comp continuous_ev (continuous.prod_mk continuous_id continuous_const) } @[simp] lemma continuous_map_of_unique_apply [unique α] (b : β) (a : α) : continuous_map_of_unique b a = b := rfl @[simp] lemma continuous_map_of_unique_symm_apply [unique α] (f : C(α, β)) : continuous_map_of_unique.symm f = f (default α) := rfl end homeomorph
fb1c1695eb1981bb970500b47f0353f402449d59
737dc4b96c97368cb66b925eeea3ab633ec3d702
/stage0/src/Lean/Environment.lean
6653f9a48388c0726320a17c58dcbfecb04794b8
[ "Apache-2.0" ]
permissive
Bioye97/lean4
1ace34638efd9913dc5991443777b01a08983289
bc3900cbb9adda83eed7e6affeaade7cfd07716d
refs/heads/master
1,690,589,820,211
1,631,051,000,000
1,631,067,598,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
34,277
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Std.Data.HashMap import Lean.ImportingFlag import Lean.Data.SMap import Lean.Declaration import Lean.LocalContext import Lean.Util.Path import Lean.Util.FindExpr import Lean.Util.Profile namespace Lean /- Opaque environment extension state. -/ constant EnvExtensionStateSpec : PointedType.{0} def EnvExtensionState : Type := EnvExtensionStateSpec.type instance : Inhabited EnvExtensionState where default := EnvExtensionStateSpec.val def ModuleIdx := Nat instance : Inhabited ModuleIdx := inferInstanceAs (Inhabited Nat) abbrev ConstMap := SMap Name ConstantInfo structure Import where module : Name runtimeOnly : Bool := false instance : ToString Import := ⟨fun imp => toString imp.module ++ if imp.runtimeOnly then " (runtime)" else ""⟩ /-- A compacted region holds multiple Lean objects in a contiguous memory region, which can be read/written to/from disk. Objects inside the region do not have reference counters and cannot be freed individually. The contents of .olean files are compacted regions. -/ def CompactedRegion := USize @[extern "lean_compacted_region_is_memory_mapped"] constant CompactedRegion.isMemoryMapped : CompactedRegion → Bool /-- Free a compacted region and its contents. No live references to the contents may exist at the time of invocation. -/ @[extern "lean_compacted_region_free"] unsafe constant CompactedRegion.free : CompactedRegion → IO Unit /- Environment fields that are not used often. -/ structure EnvironmentHeader where trustLevel : UInt32 := 0 quotInit : Bool := false mainModule : Name := arbitrary imports : Array Import := #[] -- direct imports regions : Array CompactedRegion := #[] -- compacted regions of all imported modules moduleNames : Array Name := #[] -- names of all imported modules deriving Inhabited open Std (HashMap) structure Environment where const2ModIdx : HashMap Name ModuleIdx constants : ConstMap extensions : Array EnvExtensionState header : EnvironmentHeader := {} deriving Inhabited namespace Environment def addAux (env : Environment) (cinfo : ConstantInfo) : Environment := { env with constants := env.constants.insert cinfo.name cinfo } @[export lean_environment_find] def find? (env : Environment) (n : Name) : Option ConstantInfo := /- It is safe to use `find'` because we never overwrite imported declarations. -/ env.constants.find?' n def contains (env : Environment) (n : Name) : Bool := env.constants.contains n def imports (env : Environment) : Array Import := env.header.imports def allImportedModuleNames (env : Environment) : Array Name := env.header.moduleNames @[export lean_environment_set_main_module] def setMainModule (env : Environment) (m : Name) : Environment := { env with header := { env.header with mainModule := m } } @[export lean_environment_main_module] def mainModule (env : Environment) : Name := env.header.mainModule @[export lean_environment_mark_quot_init] private def markQuotInit (env : Environment) : Environment := { env with header := { env.header with quotInit := true } } @[export lean_environment_quot_init] private def isQuotInit (env : Environment) : Bool := env.header.quotInit @[export lean_environment_trust_level] private def getTrustLevel (env : Environment) : UInt32 := env.header.trustLevel def getModuleIdxFor? (env : Environment) (declName : Name) : Option ModuleIdx := env.const2ModIdx.find? declName def isConstructor (env : Environment) (declName : Name) : Bool := match env.find? declName with | ConstantInfo.ctorInfo _ => true | _ => false def getModuleIdx? (env : Environment) (moduleName : Name) : Option ModuleIdx := env.header.moduleNames.findIdx? (. == moduleName) end Environment inductive KernelException where | unknownConstant (env : Environment) (name : Name) | alreadyDeclared (env : Environment) (name : Name) | declTypeMismatch (env : Environment) (decl : Declaration) (givenType : Expr) | declHasMVars (env : Environment) (name : Name) (expr : Expr) | declHasFVars (env : Environment) (name : Name) (expr : Expr) | funExpected (env : Environment) (lctx : LocalContext) (expr : Expr) | typeExpected (env : Environment) (lctx : LocalContext) (expr : Expr) | letTypeMismatch (env : Environment) (lctx : LocalContext) (name : Name) (givenType : Expr) (expectedType : Expr) | exprTypeMismatch (env : Environment) (lctx : LocalContext) (expr : Expr) (expectedType : Expr) | appTypeMismatch (env : Environment) (lctx : LocalContext) (app : Expr) (funType : Expr) (argType : Expr) | invalidProj (env : Environment) (lctx : LocalContext) (proj : Expr) | other (msg : String) namespace Environment /- Type check given declaration and add it to the environment -/ @[extern "lean_add_decl"] constant addDecl (env : Environment) (decl : @& Declaration) : Except KernelException Environment /- Compile the given declaration, it assumes the declaration has already been added to the environment using `addDecl`. -/ @[extern "lean_compile_decl"] constant compileDecl (env : Environment) (opt : @& Options) (decl : @& Declaration) : Except KernelException Environment def addAndCompile (env : Environment) (opt : Options) (decl : Declaration) : Except KernelException Environment := do let env ← addDecl env decl compileDecl env opt decl end Environment /- Interface for managing environment extensions. -/ structure EnvExtensionInterface where ext : Type → Type inhabitedExt {σ} : Inhabited σ → Inhabited (ext σ) registerExt {σ} (mkInitial : IO σ) : IO (ext σ) setState {σ} (e : ext σ) (env : Environment) : σ → Environment modifyState {σ} (e : ext σ) (env : Environment) : (σ → σ) → Environment getState {σ} [Inhabited σ] (e : ext σ) (env : Environment) : σ mkInitialExtStates : IO (Array EnvExtensionState) ensureExtensionsSize : Environment → IO Environment instance : Inhabited EnvExtensionInterface where default := { ext := id inhabitedExt := id ensureExtensionsSize := fun env => pure env registerExt := fun mk => mk setState := fun _ env _ => env modifyState := fun _ env _ => env getState := fun ext _ => ext mkInitialExtStates := pure #[] } /- Unsafe implementation of `EnvExtensionInterface` -/ namespace EnvExtensionInterfaceUnsafe structure Ext (σ : Type) where idx : Nat mkInitial : IO σ deriving Inhabited private builtin_initialize envExtensionsRef : IO.Ref (Array (Ext EnvExtensionState)) ← IO.mkRef #[] /-- User-defined environment extensions are declared using the `initialize` command. This command is just syntax sugar for the `init` attribute. When we `import` lean modules, the vector stored at `envExtensionsRef` may increase in size because of user-defined environment extensions. When this happens, we must adjust the size of the `env.extensions`. This method is invoked when processing `import`s. -/ partial def ensureExtensionsArraySize (env : Environment) : IO Environment := do loop env.extensions.size env where loop (i : Nat) (env : Environment) : IO Environment := do let envExtensions ← envExtensionsRef.get if h : i < envExtensions.size then let s ← envExtensions[i].mkInitial let env := { env with extensions := env.extensions.push s } loop (i + 1) env else return env private def invalidExtMsg := "invalid environment extension has been accessed" unsafe def setState {σ} (ext : Ext σ) (env : Environment) (s : σ) : Environment := if h : ext.idx < env.extensions.size then { env with extensions := env.extensions.set ⟨ext.idx, h⟩ (unsafeCast s) } else panic! invalidExtMsg @[inline] unsafe def modifyState {σ : Type} (ext : Ext σ) (env : Environment) (f : σ → σ) : Environment := if ext.idx < env.extensions.size then { env with extensions := env.extensions.modify ext.idx fun s => let s : σ := unsafeCast s let s : σ := f s unsafeCast s } else panic! invalidExtMsg unsafe def getState {σ} [Inhabited σ] (ext : Ext σ) (env : Environment) : σ := if h : ext.idx < env.extensions.size then let s : EnvExtensionState := env.extensions.get ⟨ext.idx, h⟩ unsafeCast s else panic! invalidExtMsg unsafe def registerExt {σ} (mkInitial : IO σ) : IO (Ext σ) := do unless (← initializing) do throw (IO.userError "failed to register environment, extensions can only be registered during initialization") let exts ← envExtensionsRef.get let idx := exts.size let ext : Ext σ := { idx := idx, mkInitial := mkInitial, } envExtensionsRef.modify fun exts => exts.push (unsafeCast ext) pure ext def mkInitialExtStates : IO (Array EnvExtensionState) := do let exts ← envExtensionsRef.get exts.mapM fun ext => ext.mkInitial unsafe def imp : EnvExtensionInterface := { ext := Ext ensureExtensionsSize := ensureExtensionsArraySize inhabitedExt := fun _ => ⟨arbitrary⟩ registerExt := registerExt setState := setState modifyState := modifyState getState := getState mkInitialExtStates := mkInitialExtStates } end EnvExtensionInterfaceUnsafe @[implementedBy EnvExtensionInterfaceUnsafe.imp] constant EnvExtensionInterfaceImp : EnvExtensionInterface def EnvExtension (σ : Type) : Type := EnvExtensionInterfaceImp.ext σ private def ensureExtensionsArraySize (env : Environment) : IO Environment := EnvExtensionInterfaceImp.ensureExtensionsSize env namespace EnvExtension instance {σ} [s : Inhabited σ] : Inhabited (EnvExtension σ) := EnvExtensionInterfaceImp.inhabitedExt s def setState {σ : Type} (ext : EnvExtension σ) (env : Environment) (s : σ) : Environment := EnvExtensionInterfaceImp.setState ext env s def modifyState {σ : Type} (ext : EnvExtension σ) (env : Environment) (f : σ → σ) : Environment := EnvExtensionInterfaceImp.modifyState ext env f def getState {σ : Type} [Inhabited σ] (ext : EnvExtension σ) (env : Environment) : σ := EnvExtensionInterfaceImp.getState ext env end EnvExtension /- Environment extensions can only be registered during initialization. Reasons: 1- Our implementation assumes the number of extensions does not change after an environment object is created. 2- We do not use any synchronization primitive to access `envExtensionsRef`. -/ def registerEnvExtension {σ : Type} (mkInitial : IO σ) : IO (EnvExtension σ) := EnvExtensionInterfaceImp.registerExt mkInitial private def mkInitialExtensionStates : IO (Array EnvExtensionState) := EnvExtensionInterfaceImp.mkInitialExtStates @[export lean_mk_empty_environment] def mkEmptyEnvironment (trustLevel : UInt32 := 0) : IO Environment := do let initializing ← IO.initializing if initializing then throw (IO.userError "environment objects cannot be created during initialization") let exts ← mkInitialExtensionStates pure { const2ModIdx := {}, constants := {}, header := { trustLevel := trustLevel }, extensions := exts } structure PersistentEnvExtensionState (α : Type) (σ : Type) where importedEntries : Array (Array α) -- entries per imported module state : σ structure ImportM.Context where env : Environment opts : Options abbrev ImportM := ReaderT Lean.ImportM.Context IO /- An environment extension with support for storing/retrieving entries from a .olean file. - α is the type of the entries that are stored in .olean files. - β is the type of values used to update the state. - σ is the actual state. Remark: for most extensions α and β coincide. Note that `addEntryFn` is not in `IO`. This is intentional, and allows us to write simple functions such as ``` def addAlias (env : Environment) (a : Name) (e : Name) : Environment := aliasExtension.addEntry env (a, e) ``` without using `IO`. We have many functions like `addAlias`. `α` and ‵β` do not coincide for extensions where the data used to update the state contains, for example, closures which we currently cannot store in files. -/ structure PersistentEnvExtension (α : Type) (β : Type) (σ : Type) where toEnvExtension : EnvExtension (PersistentEnvExtensionState α σ) name : Name addImportedFn : Array (Array α) → ImportM σ addEntryFn : σ → β → σ exportEntriesFn : σ → Array α statsFn : σ → Format /- Opaque persistent environment extension entry. -/ constant EnvExtensionEntrySpec : PointedType.{0} def EnvExtensionEntry : Type := EnvExtensionEntrySpec.type instance : Inhabited EnvExtensionEntry := ⟨EnvExtensionEntrySpec.val⟩ instance {α σ} [Inhabited σ] : Inhabited (PersistentEnvExtensionState α σ) := ⟨{importedEntries := #[], state := arbitrary }⟩ instance {α β σ} [Inhabited σ] : Inhabited (PersistentEnvExtension α β σ) where default := { toEnvExtension := arbitrary, name := arbitrary, addImportedFn := fun _ => arbitrary, addEntryFn := fun s _ => s, exportEntriesFn := fun _ => #[], statsFn := fun _ => Format.nil } namespace PersistentEnvExtension def getModuleEntries {α β σ : Type} [Inhabited σ] (ext : PersistentEnvExtension α β σ) (env : Environment) (m : ModuleIdx) : Array α := (ext.toEnvExtension.getState env).importedEntries.get! m def addEntry {α β σ : Type} (ext : PersistentEnvExtension α β σ) (env : Environment) (b : β) : Environment := ext.toEnvExtension.modifyState env fun s => let state := ext.addEntryFn s.state b; { s with state := state } def getState {α β σ : Type} [Inhabited σ] (ext : PersistentEnvExtension α β σ) (env : Environment) : σ := (ext.toEnvExtension.getState env).state def setState {α β σ : Type} (ext : PersistentEnvExtension α β σ) (env : Environment) (s : σ) : Environment := ext.toEnvExtension.modifyState env $ fun ps => { ps with state := s } def modifyState {α β σ : Type} (ext : PersistentEnvExtension α β σ) (env : Environment) (f : σ → σ) : Environment := ext.toEnvExtension.modifyState env $ fun ps => { ps with state := f (ps.state) } end PersistentEnvExtension builtin_initialize persistentEnvExtensionsRef : IO.Ref (Array (PersistentEnvExtension EnvExtensionEntry EnvExtensionEntry EnvExtensionState)) ← IO.mkRef #[] structure PersistentEnvExtensionDescr (α β σ : Type) where name : Name mkInitial : IO σ addImportedFn : Array (Array α) → ImportM σ addEntryFn : σ → β → σ exportEntriesFn : σ → Array α statsFn : σ → Format := fun _ => Format.nil unsafe def registerPersistentEnvExtensionUnsafe {α β σ : Type} [Inhabited σ] (descr : PersistentEnvExtensionDescr α β σ) : IO (PersistentEnvExtension α β σ) := do let pExts ← persistentEnvExtensionsRef.get if pExts.any (fun ext => ext.name == descr.name) then throw (IO.userError s!"invalid environment extension, '{descr.name}' has already been used") let ext ← registerEnvExtension do let initial ← descr.mkInitial let s : PersistentEnvExtensionState α σ := { importedEntries := #[], state := initial } pure s let pExt : PersistentEnvExtension α β σ := { toEnvExtension := ext, name := descr.name, addImportedFn := descr.addImportedFn, addEntryFn := descr.addEntryFn, exportEntriesFn := descr.exportEntriesFn, statsFn := descr.statsFn } persistentEnvExtensionsRef.modify fun pExts => pExts.push (unsafeCast pExt) return pExt @[implementedBy registerPersistentEnvExtensionUnsafe] constant registerPersistentEnvExtension {α β σ : Type} [Inhabited σ] (descr : PersistentEnvExtensionDescr α β σ) : IO (PersistentEnvExtension α β σ) /- Simple PersistentEnvExtension that implements exportEntriesFn using a list of entries. -/ def SimplePersistentEnvExtension (α σ : Type) := PersistentEnvExtension α α (List α × σ) @[specialize] def mkStateFromImportedEntries {α σ : Type} (addEntryFn : σ → α → σ) (initState : σ) (as : Array (Array α)) : σ := as.foldl (fun r es => es.foldl (fun r e => addEntryFn r e) r) initState structure SimplePersistentEnvExtensionDescr (α σ : Type) where name : Name addEntryFn : σ → α → σ addImportedFn : Array (Array α) → σ toArrayFn : List α → Array α := fun es => es.toArray def registerSimplePersistentEnvExtension {α σ : Type} [Inhabited σ] (descr : SimplePersistentEnvExtensionDescr α σ) : IO (SimplePersistentEnvExtension α σ) := registerPersistentEnvExtension { name := descr.name, mkInitial := pure ([], descr.addImportedFn #[]), addImportedFn := fun as => pure ([], descr.addImportedFn as), addEntryFn := fun s e => match s with | (entries, s) => (e::entries, descr.addEntryFn s e), exportEntriesFn := fun s => descr.toArrayFn s.1.reverse, statsFn := fun s => format "number of local entries: " ++ format s.1.length } namespace SimplePersistentEnvExtension instance {α σ : Type} [Inhabited σ] : Inhabited (SimplePersistentEnvExtension α σ) := inferInstanceAs (Inhabited (PersistentEnvExtension α α (List α × σ))) def getEntries {α σ : Type} [Inhabited σ] (ext : SimplePersistentEnvExtension α σ) (env : Environment) : List α := (PersistentEnvExtension.getState ext env).1 def getState {α σ : Type} [Inhabited σ] (ext : SimplePersistentEnvExtension α σ) (env : Environment) : σ := (PersistentEnvExtension.getState ext env).2 def setState {α σ : Type} (ext : SimplePersistentEnvExtension α σ) (env : Environment) (s : σ) : Environment := PersistentEnvExtension.modifyState ext env (fun ⟨entries, _⟩ => (entries, s)) def modifyState {α σ : Type} (ext : SimplePersistentEnvExtension α σ) (env : Environment) (f : σ → σ) : Environment := PersistentEnvExtension.modifyState ext env (fun ⟨entries, s⟩ => (entries, f s)) end SimplePersistentEnvExtension /-- Environment extension for tagging declarations. Declarations must only be tagged in the module where they were declared. -/ def TagDeclarationExtension := SimplePersistentEnvExtension Name NameSet def mkTagDeclarationExtension (name : Name) : IO TagDeclarationExtension := registerSimplePersistentEnvExtension { name := name, addImportedFn := fun as => {}, addEntryFn := fun s n => s.insert n, toArrayFn := fun es => es.toArray.qsort Name.quickLt } namespace TagDeclarationExtension instance : Inhabited TagDeclarationExtension := inferInstanceAs (Inhabited (SimplePersistentEnvExtension Name NameSet)) def tag (ext : TagDeclarationExtension) (env : Environment) (n : Name) : Environment := ext.addEntry env n def isTagged (ext : TagDeclarationExtension) (env : Environment) (n : Name) : Bool := match env.getModuleIdxFor? n with | some modIdx => (ext.getModuleEntries env modIdx).binSearchContains n Name.quickLt | none => (ext.getState env).contains n end TagDeclarationExtension /-- Environment extension for mapping declarations to values. -/ def MapDeclarationExtension (α : Type) := SimplePersistentEnvExtension (Name × α) (NameMap α) def mkMapDeclarationExtension [Inhabited α] (name : Name) : IO (MapDeclarationExtension α) := registerSimplePersistentEnvExtension { name := name, addImportedFn := fun as => {}, addEntryFn := fun s n => s.insert n.1 n.2 , toArrayFn := fun es => es.toArray.qsort (fun a b => Name.quickLt a.1 b.1) } namespace MapDeclarationExtension instance : Inhabited (MapDeclarationExtension α) := inferInstanceAs (Inhabited (SimplePersistentEnvExtension ..)) def insert (ext : MapDeclarationExtension α) (env : Environment) (declName : Name) (val : α) : Environment := ext.addEntry env (declName, val) def find? [Inhabited α] (ext : MapDeclarationExtension α) (env : Environment) (declName : Name) : Option α := match env.getModuleIdxFor? declName with | some modIdx => match (ext.getModuleEntries env modIdx).binSearch (declName, arbitrary) (fun a b => Name.quickLt a.1 b.1) with | some e => some e.2 | none => none | none => (ext.getState env).find? declName def contains [Inhabited α] (ext : MapDeclarationExtension α) (env : Environment) (declName : Name) : Bool := match env.getModuleIdxFor? declName with | some modIdx => (ext.getModuleEntries env modIdx).binSearchContains (declName, arbitrary) (fun a b => Name.quickLt a.1 b.1) | none => (ext.getState env).contains declName end MapDeclarationExtension /- Content of a .olean file. We use `compact.cpp` to generate the image of this object in disk. -/ structure ModuleData where imports : Array Import constants : Array ConstantInfo entries : Array (Name × Array EnvExtensionEntry) instance : Inhabited ModuleData := ⟨{imports := arbitrary, constants := arbitrary, entries := arbitrary }⟩ @[extern "lean_save_module_data"] constant saveModuleData (fname : @& System.FilePath) (mod : @& Name) (data : @& ModuleData) : IO Unit @[extern "lean_read_module_data"] constant readModuleData (fname : @& System.FilePath) : IO (ModuleData × CompactedRegion) /-- Free compacted regions of imports. No live references to imported objects may exist at the time of invocation; in particular, `env` should be the last reference to any `Environment` derived from these imports. -/ @[noinline, export lean_environment_free_regions] unsafe def Environment.freeRegions (env : Environment) : IO Unit := /- NOTE: This assumes `env` is not inferred as a borrowed parameter, and is freed after extracting the `header` field. Otherwise, we would encounter undefined behavior when the constant map in `env`, which may reference objects in compacted regions, is freed after the regions. In the currently produced IR, we indeed see: ``` def Lean.Environment.freeRegions (x_1 : obj) (x_2 : obj) : obj := let x_3 : obj := proj[3] x_1; inc x_3; dec x_1; ... ``` TODO: statically check for this. -/ env.header.regions.forM CompactedRegion.free def mkModuleData (env : Environment) : IO ModuleData := do let pExts ← persistentEnvExtensionsRef.get let entries : Array (Name × Array EnvExtensionEntry) := pExts.size.fold (fun i result => let state := (pExts.get! i).getState env let exportEntriesFn := (pExts.get! i).exportEntriesFn let extName := (pExts.get! i).name result.push (extName, exportEntriesFn state)) #[] pure { imports := env.header.imports, constants := env.constants.foldStage2 (fun cs _ c => cs.push c) #[], entries := entries } @[export lean_write_module] def writeModule (env : Environment) (fname : System.FilePath) : IO Unit := do saveModuleData fname env.mainModule (← mkModuleData env) private partial def getEntriesFor (mod : ModuleData) (extId : Name) (i : Nat) : Array EnvExtensionEntry := if i < mod.entries.size then let curr := mod.entries.get! i; if curr.1 == extId then curr.2 else getEntriesFor mod extId (i+1) else #[] private def setImportedEntries (env : Environment) (mods : Array ModuleData) (startingAt : Nat := 0) : IO Environment := do let mut env := env let pExtDescrs ← persistentEnvExtensionsRef.get for mod in mods do for extDescr in pExtDescrs[startingAt:] do let entries := getEntriesFor mod extDescr.name 0 env ← extDescr.toEnvExtension.modifyState env fun s => { s with importedEntries := s.importedEntries.push entries } return env /- "Forward declaration" needed for updating the attribute table with user-defined attributes. User-defined attributes are declared using the `initialize` command. The `initialize` command is just syntax sugar for the `init` attribute. The `init` attribute is initialized after the `attributeExtension` is initialized. We cannot change the order since the `init` attribute is an attribute, and requires this extension. The `attributeExtension` initializer uses `attributeMapRef` to initialize the attribute mapping. When we a new user-defined attribute declaration is imported, `attributeMapRef` is updated. Later, we set this method with code that adds the user-defined attributes that were imported after we initialized `attributeExtension`. -/ builtin_initialize updateEnvAttributesRef : IO.Ref (Environment → IO Environment) ← IO.mkRef (fun env => pure env) private partial def finalizePersistentExtensions (env : Environment) (mods : Array ModuleData) (opts : Options) : IO Environment := do loop 0 env where loop (i : Nat) (env : Environment) : IO Environment := do -- Recall that the size of the array stored `persistentEnvExtensionRef` may increase when we import user-defined environment extensions. let pExtDescrs ← persistentEnvExtensionsRef.get if h : i < pExtDescrs.size then let extDescr := pExtDescrs[i] let s := extDescr.toEnvExtension.getState env let prevSize := (← persistentEnvExtensionsRef.get).size let newState ← extDescr.addImportedFn s.importedEntries { env := env, opts := opts } let mut env ← extDescr.toEnvExtension.setState env { s with state := newState } env ← ensureExtensionsArraySize env if (← persistentEnvExtensionsRef.get).size > prevSize then -- This branch is executed when `pExtDescrs[i]` is the extension associated with the `init` attribute, and -- a user-defined persistent extension is imported. -- Thus, we invoke `setImportedEntries` to update the array `importedEntries` with the entries for the new extensions. env ← setImportedEntries env mods prevSize -- See comment at `updateEnvAttributesRef` env ← (← updateEnvAttributesRef.get) env loop (i + 1) env else return env structure ImportState where moduleNameSet : NameSet := {} moduleNames : Array Name := #[] moduleData : Array ModuleData := #[] regions : Array CompactedRegion := #[] @[export lean_import_modules] partial def importModules (imports : List Import) (opts : Options) (trustLevel : UInt32 := 0) : IO Environment := profileitIO "import" opts do withImporting do let (_, s) ← importMods imports |>.run {} let mut numConsts := 0 for mod in s.moduleData do numConsts := numConsts + mod.constants.size let mut modIdx : Nat := 0 let mut const2ModIdx : HashMap Name ModuleIdx := Std.mkHashMap (capacity := numConsts) let mut constantMap : HashMap Name ConstantInfo := Std.mkHashMap (capacity := numConsts) for mod in s.moduleData do for cinfo in mod.constants do const2ModIdx := const2ModIdx.insert cinfo.name modIdx match constantMap.insert' cinfo.name cinfo with | (constantMap', replaced) => constantMap := constantMap' if replaced then throw (IO.userError s!"import failed, environment already contains '{cinfo.name}'") modIdx := modIdx + 1 let constants : ConstMap := SMap.fromHashMap constantMap false let exts ← mkInitialExtensionStates let env : Environment := { const2ModIdx := const2ModIdx, constants := constants, extensions := exts, header := { quotInit := !imports.isEmpty, -- We assume `core.lean` initializes quotient module trustLevel := trustLevel, imports := imports.toArray, regions := s.regions, moduleNames := s.moduleNames } } let env ← setImportedEntries env s.moduleData let env ← finalizePersistentExtensions env s.moduleData opts pure env where importMods : List Import → StateRefT ImportState IO Unit | [] => pure () | i::is => do if i.runtimeOnly || (← get).moduleNameSet.contains i.module then importMods is else do modify fun s => { s with moduleNameSet := s.moduleNameSet.insert i.module } let mFile ← findOLean i.module unless (← mFile.pathExists) do throw $ IO.userError s!"object file '{mFile}' of module {i.module} does not exist" let (mod, region) ← readModuleData mFile importMods mod.imports.toList modify fun s => { s with moduleData := s.moduleData.push mod regions := s.regions.push region moduleNames := s.moduleNames.push i.module } importMods is /-- Create environment object from imports and free compacted regions after calling `act`. No live references to the environment object or imported objects may exist after `act` finishes. -/ unsafe def withImportModules {α : Type} (imports : List Import) (opts : Options) (trustLevel : UInt32 := 0) (x : Environment → IO α) : IO α := do let env ← importModules imports opts trustLevel try x env finally env.freeRegions builtin_initialize namespacesExt : SimplePersistentEnvExtension Name NameSSet ← registerSimplePersistentEnvExtension { name := `namespaces, addImportedFn := fun as => mkStateFromImportedEntries NameSSet.insert NameSSet.empty as |>.switch, addEntryFn := fun s n => s.insert n } namespace Environment def registerNamespace (env : Environment) (n : Name) : Environment := if (namespacesExt.getState env).contains n then env else namespacesExt.addEntry env n def isNamespace (env : Environment) (n : Name) : Bool := (namespacesExt.getState env).contains n def getNamespaceSet (env : Environment) : NameSSet := namespacesExt.getState env private def isNamespaceName : Name → Bool | Name.str Name.anonymous _ _ => true | Name.str p _ _ => isNamespaceName p | _ => false private def registerNamePrefixes : Environment → Name → Environment | env, Name.str p _ _ => if isNamespaceName p then registerNamePrefixes (registerNamespace env p) p else env | env, _ => env @[export lean_environment_add] def add (env : Environment) (cinfo : ConstantInfo) : Environment := let env := registerNamePrefixes env cinfo.name env.addAux cinfo @[export lean_display_stats] def displayStats (env : Environment) : IO Unit := do let pExtDescrs ← persistentEnvExtensionsRef.get IO.println ("direct imports: " ++ toString env.header.imports); IO.println ("number of imported modules: " ++ toString env.header.regions.size); IO.println ("number of memory-mapped modules: " ++ toString (env.header.regions.filter (·.isMemoryMapped) |>.size)); IO.println ("number of consts: " ++ toString env.constants.size); IO.println ("number of imported consts: " ++ toString env.constants.stageSizes.1); IO.println ("number of local consts: " ++ toString env.constants.stageSizes.2); IO.println ("number of buckets for imported consts: " ++ toString env.constants.numBuckets); IO.println ("trust level: " ++ toString env.header.trustLevel); IO.println ("number of extensions: " ++ toString env.extensions.size); pExtDescrs.forM $ fun extDescr => do IO.println ("extension '" ++ toString extDescr.name ++ "'") let s := extDescr.toEnvExtension.getState env let fmt := extDescr.statsFn s.state unless fmt.isNil do IO.println (" " ++ toString (Format.nest 2 (extDescr.statsFn s.state))) IO.println (" number of imported entries: " ++ toString (s.importedEntries.foldl (fun sum es => sum + es.size) 0)) @[extern "lean_eval_const"] unsafe constant evalConst (α) (env : @& Environment) (opts : @& Options) (constName : @& Name) : Except String α private def throwUnexpectedType {α} (typeName : Name) (constName : Name) : ExceptT String Id α := throw ("unexpected type at '" ++ toString constName ++ "', `" ++ toString typeName ++ "` expected") /-- Like `evalConst`, but first check that `constName` indeed is a declaration of type `typeName`. This function is still unsafe because it cannot guarantee that `typeName` is in fact the name of the type `α`. -/ unsafe def evalConstCheck (α) (env : Environment) (opts : Options) (typeName : Name) (constName : Name) : ExceptT String Id α := match env.find? constName with | none => throw ("unknown constant '" ++ toString constName ++ "'") | some info => match info.type with | Expr.const c _ _ => if c != typeName then throwUnexpectedType typeName constName else env.evalConst α opts constName | _ => throwUnexpectedType typeName constName def hasUnsafe (env : Environment) (e : Expr) : Bool := let c? := e.find? $ fun e => match e with | Expr.const c _ _ => match env.find? c with | some cinfo => cinfo.isUnsafe | none => false | _ => false; c?.isSome end Environment namespace Kernel /- Kernel API -/ /-- Kernel isDefEq predicate. We use it mainly for debugging purposes. Recall that the Kernel type checker does not support metavariables. When implementing automation, consider using the `MetaM` methods. -/ @[extern "lean_kernel_is_def_eq"] constant isDefEq (env : Environment) (lctx : LocalContext) (a b : Expr) : Bool /-- Kernel WHNF function. We use it mainly for debugging purposes. Recall that the Kernel type checker does not support metavariables. When implementing automation, consider using the `MetaM` methods. -/ @[extern "lean_kernel_whnf"] constant whnf (env : Environment) (lctx : LocalContext) (a : Expr) : Expr end Kernel class MonadEnv (m : Type → Type) where getEnv : m Environment modifyEnv : (Environment → Environment) → m Unit export MonadEnv (getEnv modifyEnv) instance (m n) [MonadLift m n] [MonadEnv m] : MonadEnv n where getEnv := liftM (getEnv : m Environment) modifyEnv := fun f => liftM (modifyEnv f : m Unit) end Lean
4de0287555c32bb7416f8db25390188ed0905a0c
82e44445c70db0f03e30d7be725775f122d72f3e
/src/order/lattice.lean
380a83bf5a967083da96158d9705a014d1c0f27d
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
26,891
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 order.rel_classes import tactic.simps /-! # (Semi-)lattices Semilattices are partially ordered sets with join (greatest lower bound, or `sup`) or meet (least upper bound, or `inf`) operations. Lattices are posets that are both join-semilattices and meet-semilattices. Distributive lattices are lattices which satisfy any of four equivalent distributivity properties, of `sup` over `inf`, on the left or on the right. ## Main declarations * `has_sup`: type class for the `⊔` notation * `has_inf`: type class for the `⊓` notation * `semilattice_sup`: a type class for join semilattices * `semilattice_sup.mk'`: an alternative constructor for `semilattice_sup` via proofs that `⊔` is commutative, associative and idempotent. * `semilattice_inf`: a type class for meet semilattices * `semilattice_sup.mk'`: an alternative constructor for `semilattice_inf` via proofs that `⊓` is commutative, associative and idempotent. * `lattice`: a type class for lattices * `lattice.mk'`: an alternative constructor for `lattice` via profs that `⊔` and `⊓` are commutative, associative and satisfy a pair of "absorption laws". * `distrib_lattice`: a type class for distributive lattices. ## Notations * `a ⊔ b`: the supremum or join of `a` and `b` * `a ⊓ b`: the infimum or meet of `a` and `b` ## TODO * (Semi-)lattice homomorphisms * Alternative constructors for distributive lattices from the other distributive properties ## Tags semilattice, lattice -/ set_option old_structure_cmd true universes u v w variables {α : Type u} {β : Type v} -- TODO: move this eventually, if we decide to use them attribute [ematch] le_trans lt_of_le_of_lt lt_of_lt_of_le lt_trans section -- TODO: this seems crazy, but it also seems to work reasonably well @[ematch] theorem le_antisymm' [partial_order α] : ∀ {a b : α}, (: a ≤ b :) → b ≤ a → a = b := @le_antisymm _ _ end /- TODO: automatic construction of dual definitions / theorems -/ /-- Typeclass for the `⊔` (`\lub`) notation -/ @[notation_class] class has_sup (α : Type u) := (sup : α → α → α) /-- Typeclass for the `⊓` (`\glb`) notation -/ @[notation_class] class has_inf (α : Type u) := (inf : α → α → α) infix ⊔ := has_sup.sup infix ⊓ := has_inf.inf /-! ### Join-semilattices -/ /-- A `semilattice_sup` is a join-semilattice, that is, a partial order with a join (a.k.a. lub / least upper bound, sup / supremum) operation `⊔` which is the least element larger than both factors. -/ class semilattice_sup (α : Type u) extends has_sup α, partial_order α := (le_sup_left : ∀ a b : α, a ≤ a ⊔ b) (le_sup_right : ∀ a b : α, b ≤ a ⊔ b) (sup_le : ∀ a b c : α, a ≤ c → b ≤ c → a ⊔ b ≤ c) /-- A type with a commutative, associative and idempotent binary `sup` operation has the structure of a join-semilattice. The partial order is defined so that `a ≤ b` unfolds to `a ⊔ b = b`; cf. `sup_eq_right`. -/ def semilattice_sup.mk' {α : Type*} [has_sup α] (sup_comm : ∀ (a b : α), a ⊔ b = b ⊔ a) (sup_assoc : ∀ (a b c : α), a ⊔ b ⊔ c = a ⊔ (b ⊔ c)) (sup_idem : ∀ (a : α), a ⊔ a = a) : semilattice_sup α := { sup := (⊔), le := λ a b, a ⊔ b = b, le_refl := sup_idem, le_trans := λ a b c hab hbc, begin dsimp only [(≤)] at *, rwa [←hbc, ←sup_assoc, hab], end, le_antisymm := λ a b hab hba, begin dsimp only [(≤)] at *, rwa [←hba, sup_comm], end, le_sup_left := λ a b, show a ⊔ (a ⊔ b) = (a ⊔ b), by rw [←sup_assoc, sup_idem], le_sup_right := λ a b, show b ⊔ (a ⊔ b) = (a ⊔ b), by rw [sup_comm, sup_assoc, sup_idem], sup_le := λ a b c hac hbc, begin dsimp only [(≤), preorder.le] at *, rwa [sup_assoc, hbc], end } instance (α : Type*) [has_inf α] : has_sup (order_dual α) := ⟨((⊓) : α → α → α)⟩ instance (α : Type*) [has_sup α] : has_inf (order_dual α) := ⟨((⊔) : α → α → α)⟩ section semilattice_sup variables [semilattice_sup α] {a b c d : α} @[simp] theorem le_sup_left : a ≤ a ⊔ b := semilattice_sup.le_sup_left a b @[ematch] theorem le_sup_left' : a ≤ (: a ⊔ b :) := le_sup_left @[simp] theorem le_sup_right : b ≤ a ⊔ b := semilattice_sup.le_sup_right a b @[ematch] theorem le_sup_right' : b ≤ (: a ⊔ b :) := le_sup_right theorem le_sup_of_le_left (h : c ≤ a) : c ≤ a ⊔ b := le_trans h le_sup_left theorem le_sup_of_le_right (h : c ≤ b) : c ≤ a ⊔ b := le_trans h le_sup_right theorem sup_le : a ≤ c → b ≤ c → a ⊔ b ≤ c := semilattice_sup.sup_le a b c @[simp] theorem sup_le_iff : a ⊔ b ≤ c ↔ a ≤ c ∧ b ≤ c := ⟨assume h : a ⊔ b ≤ c, ⟨le_trans le_sup_left h, le_trans le_sup_right h⟩, assume ⟨h₁, h₂⟩, sup_le h₁ h₂⟩ @[simp] theorem sup_eq_left : a ⊔ b = a ↔ b ≤ a := le_antisymm_iff.trans $ by simp [le_refl] theorem sup_of_le_left (h : b ≤ a) : a ⊔ b = a := sup_eq_left.2 h @[simp] theorem left_eq_sup : a = a ⊔ b ↔ b ≤ a := eq_comm.trans sup_eq_left @[simp] theorem sup_eq_right : a ⊔ b = b ↔ a ≤ b := le_antisymm_iff.trans $ by simp [le_refl] theorem sup_of_le_right (h : a ≤ b) : a ⊔ b = b := sup_eq_right.2 h @[simp] theorem right_eq_sup : b = a ⊔ b ↔ a ≤ b := eq_comm.trans sup_eq_right theorem sup_le_sup (h₁ : a ≤ b) (h₂ : c ≤ d) : a ⊔ c ≤ b ⊔ d := sup_le (le_sup_of_le_left h₁) (le_sup_of_le_right h₂) theorem sup_le_sup_left (h₁ : a ≤ b) (c) : c ⊔ a ≤ c ⊔ b := sup_le_sup (le_refl _) h₁ theorem sup_le_sup_right (h₁ : a ≤ b) (c) : a ⊔ c ≤ b ⊔ c := sup_le_sup h₁ (le_refl _) theorem le_of_sup_eq (h : a ⊔ b = b) : a ≤ b := by { rw ← h, simp } lemma sup_ind [is_total α (≤)] (a b : α) {p : α → Prop} (ha : p a) (hb : p b) : p (a ⊔ b) := (is_total.total a b).elim (λ h : a ≤ b, by rwa sup_eq_right.2 h) (λ h, by rwa sup_eq_left.2 h) @[simp] lemma sup_lt_iff [is_total α (≤)] {a b c : α} : b ⊔ c < a ↔ b < a ∧ c < a := ⟨λ h, ⟨le_sup_left.trans_lt h, le_sup_right.trans_lt h⟩, λ h, sup_ind b c h.1 h.2⟩ @[simp] lemma le_sup_iff [is_total α (≤)] {a b c : α} : a ≤ b ⊔ c ↔ a ≤ b ∨ a ≤ c := ⟨λ h, (total_of (≤) c b).imp (λ bc, by rwa sup_eq_left.2 bc at h) (λ bc, by rwa sup_eq_right.2 bc at h), λ h, h.elim le_sup_of_le_left le_sup_of_le_right⟩ @[simp] lemma lt_sup_iff [is_total α (≤)] {a b c : α} : a < b ⊔ c ↔ a < b ∨ a < c := ⟨λ h, (total_of (≤) c b).imp (λ bc, by rwa sup_eq_left.2 bc at h) (λ bc, by rwa sup_eq_right.2 bc at h), λ h, h.elim (λ h, h.trans_le le_sup_left) (λ h, h.trans_le le_sup_right)⟩ @[simp] theorem sup_idem : a ⊔ a = a := by apply le_antisymm; simp instance sup_is_idempotent : is_idempotent α (⊔) := ⟨@sup_idem _ _⟩ theorem sup_comm : a ⊔ b = b ⊔ a := by apply le_antisymm; simp instance sup_is_commutative : is_commutative α (⊔) := ⟨@sup_comm _ _⟩ theorem sup_assoc : a ⊔ b ⊔ c = a ⊔ (b ⊔ c) := le_antisymm (sup_le (sup_le le_sup_left (le_sup_of_le_right le_sup_left)) (le_sup_of_le_right le_sup_right)) (sup_le (le_sup_of_le_left le_sup_left) (sup_le (le_sup_of_le_left le_sup_right) le_sup_right)) instance sup_is_associative : is_associative α (⊔) := ⟨@sup_assoc _ _⟩ lemma sup_left_right_swap (a b c : α) : a ⊔ b ⊔ c = c ⊔ b ⊔ a := by rw [sup_comm, @sup_comm _ _ a, sup_assoc] @[simp] lemma sup_left_idem : a ⊔ (a ⊔ b) = a ⊔ b := by rw [← sup_assoc, sup_idem] @[simp] lemma sup_right_idem : (a ⊔ b) ⊔ b = a ⊔ b := by rw [sup_assoc, sup_idem] lemma sup_left_comm (a b c : α) : a ⊔ (b ⊔ c) = b ⊔ (a ⊔ c) := by rw [← sup_assoc, ← sup_assoc, @sup_comm α _ a] lemma sup_right_comm (a b c : α) : a ⊔ b ⊔ c = a ⊔ c ⊔ b := by rw [sup_assoc, sup_assoc, @sup_comm _ _ b] lemma forall_le_or_exists_lt_sup (a : α) : (∀b, b ≤ a) ∨ (∃b, a < b) := suffices (∃b, ¬b ≤ a) → (∃b, a < b), by rwa [or_iff_not_imp_left, not_forall], assume ⟨b, hb⟩, ⟨a ⊔ b, lt_of_le_of_ne le_sup_left $ mt left_eq_sup.1 hb⟩ /-- If `f` is a monotonically increasing sequence, `g` is a monotonically decreasing sequence, and `f n ≤ g n` for all `n`, then for all `m`, `n` we have `f m ≤ g n`. -/ theorem forall_le_of_monotone_of_mono_decr {β : Type*} [preorder β] {f g : α → β} (hf : monotone f) (hg : ∀ ⦃m n⦄, m ≤ n → g n ≤ g m) (h : ∀ n, f n ≤ g n) (m n : α) : f m ≤ g n := calc f m ≤ f (m ⊔ n) : hf le_sup_left ... ≤ g (m ⊔ n) : h _ ... ≤ g n : hg le_sup_right theorem semilattice_sup.ext_sup {α} {A B : semilattice_sup α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) (x y : α) : (by haveI := A; exact (x ⊔ y)) = x ⊔ y := eq_of_forall_ge_iff $ λ c, by simp only [sup_le_iff]; rw [← H, @sup_le_iff α A, H, H] theorem semilattice_sup.ext {α} {A B : semilattice_sup α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin have := partial_order.ext H, have ss := funext (λ x, funext $ semilattice_sup.ext_sup H x), casesI A, casesI B, injection this; congr' end end semilattice_sup /-! ### Meet-semilattices -/ /-- A `semilattice_inf` is a meet-semilattice, that is, a partial order with a meet (a.k.a. glb / greatest lower bound, inf / infimum) operation `⊓` which is the greatest element smaller than both factors. -/ class semilattice_inf (α : Type u) extends has_inf α, partial_order α := (inf_le_left : ∀ a b : α, a ⊓ b ≤ a) (inf_le_right : ∀ a b : α, a ⊓ b ≤ b) (le_inf : ∀ a b c : α, a ≤ b → a ≤ c → a ≤ b ⊓ c) instance (α) [semilattice_inf α] : semilattice_sup (order_dual α) := { le_sup_left := semilattice_inf.inf_le_left, le_sup_right := semilattice_inf.inf_le_right, sup_le := assume a b c hca hcb, @semilattice_inf.le_inf α _ _ _ _ hca hcb, .. order_dual.partial_order α, .. order_dual.has_sup α } instance (α) [semilattice_sup α] : semilattice_inf (order_dual α) := { inf_le_left := @le_sup_left α _, inf_le_right := @le_sup_right α _, le_inf := assume a b c hca hcb, @sup_le α _ _ _ _ hca hcb, .. order_dual.partial_order α, .. order_dual.has_inf α } theorem semilattice_sup.dual_dual (α : Type*) [H : semilattice_sup α] : order_dual.semilattice_sup (order_dual α) = H := semilattice_sup.ext $ λ _ _, iff.rfl section semilattice_inf variables [semilattice_inf α] {a b c d : α} @[simp] theorem inf_le_left : a ⊓ b ≤ a := semilattice_inf.inf_le_left a b @[ematch] theorem inf_le_left' : (: a ⊓ b :) ≤ a := semilattice_inf.inf_le_left a b @[simp] theorem inf_le_right : a ⊓ b ≤ b := semilattice_inf.inf_le_right a b @[ematch] theorem inf_le_right' : (: a ⊓ b :) ≤ b := semilattice_inf.inf_le_right a b theorem le_inf : a ≤ b → a ≤ c → a ≤ b ⊓ c := semilattice_inf.le_inf a b c theorem inf_le_of_left_le (h : a ≤ c) : a ⊓ b ≤ c := le_trans inf_le_left h theorem inf_le_of_right_le (h : b ≤ c) : a ⊓ b ≤ c := le_trans inf_le_right h @[simp] theorem le_inf_iff : a ≤ b ⊓ c ↔ a ≤ b ∧ a ≤ c := @sup_le_iff (order_dual α) _ _ _ _ @[simp] theorem inf_eq_left : a ⊓ b = a ↔ a ≤ b := le_antisymm_iff.trans $ by simp [le_refl] theorem inf_of_le_left (h : a ≤ b) : a ⊓ b = a := inf_eq_left.2 h @[simp] theorem left_eq_inf : a = a ⊓ b ↔ a ≤ b := eq_comm.trans inf_eq_left @[simp] theorem inf_eq_right : a ⊓ b = b ↔ b ≤ a := le_antisymm_iff.trans $ by simp [le_refl] theorem inf_of_le_right (h : b ≤ a) : a ⊓ b = b := inf_eq_right.2 h @[simp] theorem right_eq_inf : b = a ⊓ b ↔ b ≤ a := eq_comm.trans inf_eq_right theorem inf_le_inf (h₁ : a ≤ b) (h₂ : c ≤ d) : a ⊓ c ≤ b ⊓ d := le_inf (inf_le_of_left_le h₁) (inf_le_of_right_le h₂) lemma inf_le_inf_right (a : α) {b c : α} (h : b ≤ c) : b ⊓ a ≤ c ⊓ a := inf_le_inf h (le_refl _) lemma inf_le_inf_left (a : α) {b c : α} (h : b ≤ c) : a ⊓ b ≤ a ⊓ c := inf_le_inf (le_refl _) h theorem le_of_inf_eq (h : a ⊓ b = a) : a ≤ b := by { rw ← h, simp } lemma inf_ind [is_total α (≤)] (a b : α) {p : α → Prop} (ha : p a) (hb : p b) : p (a ⊓ b) := @sup_ind (order_dual α) _ _ _ _ _ ha hb @[simp] lemma lt_inf_iff [is_total α (≤)] {a b c : α} : a < b ⊓ c ↔ a < b ∧ a < c := @sup_lt_iff (order_dual α) _ _ _ _ _ @[simp] lemma inf_le_iff [is_total α (≤)] {a b c : α} : b ⊓ c ≤ a ↔ b ≤ a ∨ c ≤ a := @le_sup_iff (order_dual α) _ _ _ _ _ @[simp] theorem inf_idem : a ⊓ a = a := @sup_idem (order_dual α) _ _ instance inf_is_idempotent : is_idempotent α (⊓) := ⟨@inf_idem _ _⟩ theorem inf_comm : a ⊓ b = b ⊓ a := @sup_comm (order_dual α) _ _ _ instance inf_is_commutative : is_commutative α (⊓) := ⟨@inf_comm _ _⟩ theorem inf_assoc : a ⊓ b ⊓ c = a ⊓ (b ⊓ c) := @sup_assoc (order_dual α) _ a b c instance inf_is_associative : is_associative α (⊓) := ⟨@inf_assoc _ _⟩ lemma inf_left_right_swap (a b c : α) : a ⊓ b ⊓ c = c ⊓ b ⊓ a := by rw [inf_comm, @inf_comm _ _ a, inf_assoc] @[simp] lemma inf_left_idem : a ⊓ (a ⊓ b) = a ⊓ b := @sup_left_idem (order_dual α) _ a b @[simp] lemma inf_right_idem : (a ⊓ b) ⊓ b = a ⊓ b := @sup_right_idem (order_dual α) _ a b lemma inf_left_comm (a b c : α) : a ⊓ (b ⊓ c) = b ⊓ (a ⊓ c) := @sup_left_comm (order_dual α) _ a b c lemma inf_right_comm (a b c : α) : a ⊓ b ⊓ c = a ⊓ c ⊓ b := @sup_right_comm (order_dual α) _ a b c lemma forall_le_or_exists_lt_inf (a : α) : (∀b, a ≤ b) ∨ (∃b, b < a) := @forall_le_or_exists_lt_sup (order_dual α) _ a theorem semilattice_inf.ext_inf {α} {A B : semilattice_inf α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) (x y : α) : (by haveI := A; exact (x ⊓ y)) = x ⊓ y := eq_of_forall_le_iff $ λ c, by simp only [le_inf_iff]; rw [← H, @le_inf_iff α A, H, H] theorem semilattice_inf.ext {α} {A B : semilattice_inf α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin have := partial_order.ext H, have ss := funext (λ x, funext $ semilattice_inf.ext_inf H x), casesI A, casesI B, injection this; congr' end theorem semilattice_inf.dual_dual (α : Type*) [H : semilattice_inf α] : order_dual.semilattice_inf (order_dual α) = H := semilattice_inf.ext $ λ _ _, iff.rfl end semilattice_inf /-- A type with a commutative, associative and idempotent binary `inf` operation has the structure of a meet-semilattice. The partial order is defined so that `a ≤ b` unfolds to `b ⊓ a = a`; cf. `inf_eq_right`. -/ def semilattice_inf.mk' {α : Type*} [has_inf α] (inf_comm : ∀ (a b : α), a ⊓ b = b ⊓ a) (inf_assoc : ∀ (a b c : α), a ⊓ b ⊓ c = a ⊓ (b ⊓ c)) (inf_idem : ∀ (a : α), a ⊓ a = a) : semilattice_inf α := begin haveI : semilattice_sup (order_dual α) := semilattice_sup.mk' inf_comm inf_assoc inf_idem, haveI i := order_dual.semilattice_inf (order_dual α), exact i, end /-! ### Lattices -/ /-- A lattice is a join-semilattice which is also a meet-semilattice. -/ class lattice (α : Type u) extends semilattice_sup α, semilattice_inf α instance (α) [lattice α] : lattice (order_dual α) := { .. order_dual.semilattice_sup α, .. order_dual.semilattice_inf α } /-- The partial orders from `semilattice_sup_mk'` and `semilattice_inf_mk'` agree if `sup` and `inf` satisfy the lattice absorption laws `sup_inf_self` (`a ⊔ a ⊓ b = a`) and `inf_sup_self` (`a ⊓ (a ⊔ b) = a`). -/ lemma semilattice_sup_mk'_partial_order_eq_semilattice_inf_mk'_partial_order {α : Type*} [has_sup α] [has_inf α] (sup_comm : ∀ (a b : α), a ⊔ b = b ⊔ a) (sup_assoc : ∀ (a b c : α), a ⊔ b ⊔ c = a ⊔ (b ⊔ c)) (sup_idem : ∀ (a : α), a ⊔ a = a) (inf_comm : ∀ (a b : α), a ⊓ b = b ⊓ a) (inf_assoc : ∀ (a b c : α), a ⊓ b ⊓ c = a ⊓ (b ⊓ c)) (inf_idem : ∀ (a : α), a ⊓ a = a) (sup_inf_self : ∀ (a b : α), a ⊔ a ⊓ b = a) (inf_sup_self : ∀ (a b : α), a ⊓ (a ⊔ b) = a) : @semilattice_sup.to_partial_order _ (semilattice_sup.mk' sup_comm sup_assoc sup_idem) = @semilattice_inf.to_partial_order _ (semilattice_inf.mk' inf_comm inf_assoc inf_idem) := partial_order.ext $ λ a b, show a ⊔ b = b ↔ b ⊓ a = a, from ⟨λ h, by rw [←h, inf_comm, inf_sup_self], λ h, by rw [←h, sup_comm, sup_inf_self]⟩ /-- A type with a pair of commutative and associative binary operations which satisfy two absorption laws relating the two operations has the structure of a lattice. The partial order is defined so that `a ≤ b` unfolds to `a ⊔ b = b`; cf. `sup_eq_right`. -/ def lattice.mk' {α : Type*} [has_sup α] [has_inf α] (sup_comm : ∀ (a b : α), a ⊔ b = b ⊔ a) (sup_assoc : ∀ (a b c : α), a ⊔ b ⊔ c = a ⊔ (b ⊔ c)) (inf_comm : ∀ (a b : α), a ⊓ b = b ⊓ a) (inf_assoc : ∀ (a b c : α), a ⊓ b ⊓ c = a ⊓ (b ⊓ c)) (sup_inf_self : ∀ (a b : α), a ⊔ a ⊓ b = a) (inf_sup_self : ∀ (a b : α), a ⊓ (a ⊔ b) = a) : lattice α := have sup_idem : ∀ (b : α), b ⊔ b = b := λ b, calc b ⊔ b = b ⊔ b ⊓ (b ⊔ b) : by rw inf_sup_self ... = b : by rw sup_inf_self, have inf_idem : ∀ (b : α), b ⊓ b = b := λ b, calc b ⊓ b = b ⊓ (b ⊔ b ⊓ b) : by rw sup_inf_self ... = b : by rw inf_sup_self, let semilatt_inf_inst := semilattice_inf.mk' inf_comm inf_assoc inf_idem, semilatt_sup_inst := semilattice_sup.mk' sup_comm sup_assoc sup_idem, -- here we help Lean to see that the two partial orders are equal partial_order_inst := @semilattice_sup.to_partial_order _ semilatt_sup_inst in have partial_order_eq : partial_order_inst = @semilattice_inf.to_partial_order _ semilatt_inf_inst := semilattice_sup_mk'_partial_order_eq_semilattice_inf_mk'_partial_order _ _ _ _ _ _ sup_inf_self inf_sup_self, { inf_le_left := λ a b, by { rw partial_order_eq, apply inf_le_left }, inf_le_right := λ a b, by { rw partial_order_eq, apply inf_le_right }, le_inf := λ a b c, by { rw partial_order_eq, apply le_inf }, ..partial_order_inst, ..semilatt_sup_inst, ..semilatt_inf_inst, } section lattice variables [lattice α] {a b c d : α} /-! #### Distributivity laws -/ /- TODO: better names? -/ theorem sup_inf_le : a ⊔ (b ⊓ c) ≤ (a ⊔ b) ⊓ (a ⊔ c) := le_inf (sup_le_sup_left inf_le_left _) (sup_le_sup_left inf_le_right _) theorem le_inf_sup : (a ⊓ b) ⊔ (a ⊓ c) ≤ a ⊓ (b ⊔ c) := sup_le (inf_le_inf_left _ le_sup_left) (inf_le_inf_left _ le_sup_right) theorem inf_sup_self : a ⊓ (a ⊔ b) = a := by simp theorem sup_inf_self : a ⊔ (a ⊓ b) = a := by simp theorem sup_eq_iff_inf_eq : a ⊔ b = b ↔ a ⊓ b = a := by rw [sup_eq_right, ←inf_eq_left] theorem lattice.ext {α} {A B : lattice α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin have SS : @lattice.to_semilattice_sup α A = @lattice.to_semilattice_sup α B := semilattice_sup.ext H, have II := semilattice_inf.ext H, casesI A, casesI B, injection SS; injection II; congr' end end lattice /-! ### Distributive lattices -/ /-- A distributive lattice is a lattice that satisfies any of four equivalent distributive properties (of `sup` over `inf` or `inf` over `sup`, on the left or right). The definition here chooses `le_sup_inf`: `(x ⊔ y) ⊓ (x ⊔ z) ≤ x ⊔ (y ⊓ z)`. A classic example of a distributive lattice is the lattice of subsets of a set, and in fact this example is generic in the sense that every distributive lattice is realizable as a sublattice of a powerset lattice. -/ class distrib_lattice α extends lattice α := (le_sup_inf : ∀x y z : α, (x ⊔ y) ⊓ (x ⊔ z) ≤ x ⊔ (y ⊓ z)) /- TODO: alternative constructors from the other distributive properties, and perhaps a `tfae` statement -/ section distrib_lattice variables [distrib_lattice α] {x y z : α} theorem le_sup_inf : ∀{x y z : α}, (x ⊔ y) ⊓ (x ⊔ z) ≤ x ⊔ (y ⊓ z) := distrib_lattice.le_sup_inf theorem sup_inf_left : x ⊔ (y ⊓ z) = (x ⊔ y) ⊓ (x ⊔ z) := le_antisymm sup_inf_le le_sup_inf theorem sup_inf_right : (y ⊓ z) ⊔ x = (y ⊔ x) ⊓ (z ⊔ x) := by simp only [sup_inf_left, λy:α, @sup_comm α _ y x, eq_self_iff_true] theorem inf_sup_left : x ⊓ (y ⊔ z) = (x ⊓ y) ⊔ (x ⊓ z) := calc x ⊓ (y ⊔ z) = (x ⊓ (x ⊔ z)) ⊓ (y ⊔ z) : by rw [inf_sup_self] ... = x ⊓ ((x ⊓ y) ⊔ z) : by simp only [inf_assoc, sup_inf_right, eq_self_iff_true] ... = (x ⊔ (x ⊓ y)) ⊓ ((x ⊓ y) ⊔ z) : by rw [sup_inf_self] ... = ((x ⊓ y) ⊔ x) ⊓ ((x ⊓ y) ⊔ z) : by rw [sup_comm] ... = (x ⊓ y) ⊔ (x ⊓ z) : by rw [sup_inf_left] instance (α : Type*) [distrib_lattice α] : distrib_lattice (order_dual α) := { le_sup_inf := assume x y z, le_of_eq inf_sup_left.symm, .. order_dual.lattice α } theorem inf_sup_right : (y ⊔ z) ⊓ x = (y ⊓ x) ⊔ (z ⊓ x) := by simp only [inf_sup_left, λy:α, @inf_comm α _ y x, eq_self_iff_true] lemma le_of_inf_le_sup_le (h₁ : x ⊓ z ≤ y ⊓ z) (h₂ : x ⊔ z ≤ y ⊔ z) : x ≤ y := calc x ≤ (y ⊓ z) ⊔ x : le_sup_right ... = (y ⊔ x) ⊓ (x ⊔ z) : by rw [sup_inf_right, @sup_comm _ _ x] ... ≤ (y ⊔ x) ⊓ (y ⊔ z) : inf_le_inf_left _ h₂ ... = y ⊔ (x ⊓ z) : sup_inf_left.symm ... ≤ y ⊔ (y ⊓ z) : sup_le_sup_left h₁ _ ... ≤ _ : sup_le (le_refl y) inf_le_left lemma eq_of_inf_eq_sup_eq {α : Type u} [distrib_lattice α] {a b c : α} (h₁ : b ⊓ a = c ⊓ a) (h₂ : b ⊔ a = c ⊔ a) : b = c := le_antisymm (le_of_inf_le_sup_le (le_of_eq h₁) (le_of_eq h₂)) (le_of_inf_le_sup_le (le_of_eq h₁.symm) (le_of_eq h₂.symm)) end distrib_lattice /-! ### Lattices derived from linear orders -/ @[priority 100] -- see Note [lower instance priority] instance lattice_of_linear_order {α : Type u} [o : linear_order α] : lattice α := { sup := max, le_sup_left := le_max_left, le_sup_right := le_max_right, sup_le := assume a b c, max_le, inf := min, inf_le_left := min_le_left, inf_le_right := min_le_right, le_inf := assume a b c, le_min, ..o } theorem sup_eq_max [linear_order α] {x y : α} : x ⊔ y = max x y := rfl theorem inf_eq_min [linear_order α] {x y : α} : x ⊓ y = min x y := rfl @[priority 100] -- see Note [lower instance priority] instance distrib_lattice_of_linear_order {α : Type u} [o : linear_order α] : distrib_lattice α := { le_sup_inf := assume a b c, match le_total b c with | or.inl h := inf_le_of_left_le $ sup_le_sup_left (le_inf (le_refl b) h) _ | or.inr h := inf_le_of_right_le $ sup_le_sup_left (le_inf h (le_refl c)) _ end, ..lattice_of_linear_order } instance nat.distrib_lattice : distrib_lattice ℕ := by apply_instance /-! ### Monotone functions and lattices -/ namespace monotone lemma le_map_sup [semilattice_sup α] [semilattice_sup β] {f : α → β} (h : monotone f) (x y : α) : f x ⊔ f y ≤ f (x ⊔ y) := sup_le (h le_sup_left) (h le_sup_right) lemma map_sup [semilattice_sup α] [is_total α (≤)] [semilattice_sup β] {f : α → β} (hf : monotone f) (x y : α) : f (x ⊔ y) = f x ⊔ f y := (is_total.total x y).elim (λ h : x ≤ y, by simp only [h, hf h, sup_of_le_right]) (λ h, by simp only [h, hf h, sup_of_le_left]) lemma map_inf_le [semilattice_inf α] [semilattice_inf β] {f : α → β} (h : monotone f) (x y : α) : f (x ⊓ y) ≤ f x ⊓ f y := le_inf (h inf_le_left) (h inf_le_right) lemma map_inf [semilattice_inf α] [is_total α (≤)] [semilattice_inf β] {f : α → β} (hf : monotone f) (x y : α) : f (x ⊓ y) = f x ⊓ f y := @monotone.map_sup (order_dual α) _ _ _ _ _ hf.order_dual x y end monotone /-! ### Products of (semi-)lattices -/ namespace prod variables (α β) instance [has_sup α] [has_sup β] : has_sup (α × β) := ⟨λp q, ⟨p.1 ⊔ q.1, p.2 ⊔ q.2⟩⟩ instance [has_inf α] [has_inf β] : has_inf (α × β) := ⟨λp q, ⟨p.1 ⊓ q.1, p.2 ⊓ q.2⟩⟩ instance [semilattice_sup α] [semilattice_sup β] : semilattice_sup (α × β) := { sup_le := assume a b c h₁ h₂, ⟨sup_le h₁.1 h₂.1, sup_le h₁.2 h₂.2⟩, le_sup_left := assume a b, ⟨le_sup_left, le_sup_left⟩, le_sup_right := assume a b, ⟨le_sup_right, le_sup_right⟩, .. prod.partial_order α β, .. prod.has_sup α β } instance [semilattice_inf α] [semilattice_inf β] : semilattice_inf (α × β) := { le_inf := assume a b c h₁ h₂, ⟨le_inf h₁.1 h₂.1, le_inf h₁.2 h₂.2⟩, inf_le_left := assume a b, ⟨inf_le_left, inf_le_left⟩, inf_le_right := assume a b, ⟨inf_le_right, inf_le_right⟩, .. prod.partial_order α β, .. prod.has_inf α β } instance [lattice α] [lattice β] : lattice (α × β) := { .. prod.semilattice_inf α β, .. prod.semilattice_sup α β } instance [distrib_lattice α] [distrib_lattice β] : distrib_lattice (α × β) := { le_sup_inf := assume a b c, ⟨le_sup_inf, le_sup_inf⟩, .. prod.lattice α β } end prod /-! ### Subtypes of (semi-)lattices -/ namespace subtype /-- A subtype forms a `⊔`-semilattice if `⊔` preserves the property. -/ protected def semilattice_sup [semilattice_sup α] {P : α → Prop} (Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) : semilattice_sup {x : α // P x} := { sup := λ x y, ⟨x.1 ⊔ y.1, Psup x.2 y.2⟩, le_sup_left := λ x y, @le_sup_left _ _ (x : α) y, le_sup_right := λ x y, @le_sup_right _ _ (x : α) y, sup_le := λ x y z h1 h2, @sup_le α _ _ _ _ h1 h2, ..subtype.partial_order P } /-- A subtype forms a `⊓`-semilattice if `⊓` preserves the property. -/ protected def semilattice_inf [semilattice_inf α] {P : α → Prop} (Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) : semilattice_inf {x : α // P x} := { inf := λ x y, ⟨x.1 ⊓ y.1, Pinf x.2 y.2⟩, inf_le_left := λ x y, @inf_le_left _ _ (x : α) y, inf_le_right := λ x y, @inf_le_right _ _ (x : α) y, le_inf := λ x y z h1 h2, @le_inf α _ _ _ _ h1 h2, ..subtype.partial_order P } /-- A subtype forms a lattice if `⊔` and `⊓` preserve the property. -/ protected def lattice [lattice α] {P : α → Prop} (Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) (Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) : lattice {x : α // P x} := { ..subtype.semilattice_inf Pinf, ..subtype.semilattice_sup Psup } end subtype
9b05a5d8f6db203dd5595e2287d8e77d493263fb
94637389e03c919023691dcd05bd4411b1034aa5
/src/assignments/assignment_2/assignment_2_help.lean
c7b70616599b7536973e77d2a54c441bca4b3d20
[]
no_license
kevinsullivan/complogic-s21
7c4eef2105abad899e46502270d9829d913e8afc
99039501b770248c8ceb39890be5dfe129dc1082
refs/heads/master
1,682,985,669,944
1,621,126,241,000
1,621,126,241,000
335,706,272
0
38
null
1,618,325,669,000
1,612,374,118,000
Lean
UTF-8
Lean
false
false
739
lean
inductive ST : Type | empty | salmon (e : ST) | trout (e: ST) open ST def e1 := ST.empty def e2 := ST.salmon ST.empty def e3 := salmon (trout (trout e1 ) ) /-salmon empty salmon trout trout empty -/ def fishEvalHelper : ST → prod nat nat → prod nat nat | ST.empty (prod.mk s t) := (prod.mk s t) | (ST.salmon e) (prod.mk s t) := _ def fishEval : ST → prod nat nat | e := fishEvalHelper e (0,0) #eval fishEval e1 #eval fishEval e2 def o1 : option nat := option.some 1 def o2 : option nat := option.none def foo : option nat → string | (option.none) := "no answer" | (option.some n) := "the answer was " ++ repr n #eval foo o1 #eval foo o2
1979913c74864edf6aefc584dd33ec424e3a5166
367134ba5a65885e863bdc4507601606690974c1
/src/order/filter/germ.lean
48169a5137bedbc5cf99343a8508e248cd53ae2d
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
21,662
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, Abhimanyu Pallavi Sudhir -/ import order.filter.basic import algebra.module.pi /-! # Germ of a function at a filter The germ of a function `f : α → β` at a filter `l : filter α` is the equivalence class of `f` with respect to the equivalence relation `eventually_eq l`: `f ≈ g` means `∀ᶠ x in l, f x = g x`. ## Main definitions We define * `germ l β` to be the space of germs of functions `α → β` at a filter `l : filter α`; * coercion from `α → β` to `germ l β`: `(f : germ l β)` is the germ of `f : α → β` at `l : filter α`; this coercion is declared as `has_coe_t`, so it does not require an explicit up arrow `↑`; * coercion from `β` to `germ l β`: `(↑c : germ l β)` is the germ of the constant function `λ x:α, c` at a filter `l`; this coercion is declared as `has_lift_t`, so it requires an explicit up arrow `↑`, see [TPiL][TPiL_coe] for details. * `map (F : β → γ) (f : germ l β)` to be the composition of a function `F` and a germ `f`; * `map₂ (F : β → γ → δ) (f : germ l β) (g : germ l γ)` to be the germ of `λ x, F (f x) (g x)` at `l`; * `f.tendsto lb`: we say that a germ `f : germ l β` tends to a filter `lb` if its representatives tend to `lb` along `l`; * `f.comp_tendsto g hg` and `f.comp_tendsto' g hg`: given `f : germ l β` and a function `g : γ → α` (resp., a germ `g : germ lc α`), if `g` tends to `l` along `lc`, then the composition `f ∘ g` is a well-defined germ at `lc`; * `germ.lift_pred`, `germ.lift_rel`: lift a predicate or a relation to the space of germs: `(f : germ l β).lift_pred p` means `∀ᶠ x in l, p (f x)`, and similarly for a relation. [TPiL_coe]: https://leanprover.github.io/theorem_proving_in_lean/type_classes.html#coercions-using-type-classes We also define `map (F : β → γ) : germ l β → germ l γ` sending each germ `f` to `F ∘ f`. For each of the following structures we prove that if `β` has this structure, then so does `germ l β`: * one-operation algebraic structures up to `comm_group`; * `mul_zero_class`, `distrib`, `semiring`, `comm_semiring`, `ring`, `comm_ring`; * `mul_action`, `distrib_mul_action`, `semimodule`; * `preorder`, `partial_order`, and `lattice` structures up to `bounded_lattice`; * `ordered_cancel_comm_monoid` and `ordered_cancel_add_comm_monoid`. ## Tags filter, germ -/ namespace filter variables {α β γ δ : Type*} {l : filter α} {f g h : α → β} lemma const_eventually_eq' [ne_bot l] {a b : β} : (∀ᶠ x in l, a = b) ↔ a = b := eventually_const lemma const_eventually_eq [ne_bot l] {a b : β} : ((λ _, a) =ᶠ[l] (λ _, b)) ↔ a = b := @const_eventually_eq' _ _ _ _ a b lemma eventually_eq.comp_tendsto {f' : α → β} (H : f =ᶠ[l] f') {g : γ → α} {lc : filter γ} (hg : tendsto g lc l) : f ∘ g =ᶠ[lc] f' ∘ g := hg.eventually H /-- Setoid used to define the space of germs. -/ def germ_setoid (l : filter α) (β : Type*) : setoid (α → β) := { r := eventually_eq l, iseqv := ⟨eventually_eq.refl _, λ _ _, eventually_eq.symm, λ _ _ _, eventually_eq.trans⟩ } /-- The space of germs of functions `α → β` at a filter `l`. -/ def germ (l : filter α) (β : Type*) : Type* := quotient (germ_setoid l β) namespace germ instance : has_coe_t (α → β) (germ l β) := ⟨quotient.mk'⟩ instance : has_lift_t β (germ l β) := ⟨λ c, ↑(λ (x : α), c)⟩ @[simp] lemma quot_mk_eq_coe (l : filter α) (f : α → β) : quot.mk _ f = (f : germ l β) := rfl @[simp] lemma mk'_eq_coe (l : filter α) (f : α → β) : quotient.mk' f = (f : germ l β) := rfl @[elab_as_eliminator] lemma induction_on (f : germ l β) {p : germ l β → Prop} (h : ∀ f : α → β, p f) : p f := quotient.induction_on' f h @[elab_as_eliminator] lemma induction_on₂ (f : germ l β) (g : germ l γ) {p : germ l β → germ l γ → Prop} (h : ∀ (f : α → β) (g : α → γ), p f g) : p f g := quotient.induction_on₂' f g h @[elab_as_eliminator] lemma induction_on₃ (f : germ l β) (g : germ l γ) (h : germ l δ) {p : germ l β → germ l γ → germ l δ → Prop} (H : ∀ (f : α → β) (g : α → γ) (h : α → δ), p f g h) : p f g h := quotient.induction_on₃' f g h H /-- Given a map `F : (α → β) → (γ → δ)` that sends functions eventually equal at `l` to functions eventually equal at `lc`, returns a map from `germ l β` to `germ lc δ`. -/ def map' {lc : filter γ} (F : (α → β) → (γ → δ)) (hF : (l.eventually_eq ⇒ lc.eventually_eq) F F) : germ l β → germ lc δ := quotient.map' F hF /-- Given a germ `f : germ l β` and a function `F : (α → β) → γ` sending eventually equal functions to the same value, returns the value `F` takes on functions having germ `f` at `l`. -/ def lift_on {γ : Sort*} (f : germ l β) (F : (α → β) → γ) (hF : (l.eventually_eq ⇒ (=)) F F) : γ := quotient.lift_on' f F hF @[simp] lemma map'_coe {lc : filter γ} (F : (α → β) → (γ → δ)) (hF : (l.eventually_eq ⇒ lc.eventually_eq) F F) (f : α → β) : map' F hF f = F f := rfl @[simp, norm_cast] lemma coe_eq : (f : germ l β) = g ↔ (f =ᶠ[l] g) := quotient.eq' alias coe_eq ↔ _ filter.eventually_eq.germ_eq /-- Lift a function `β → γ` to a function `germ l β → germ l γ`. -/ def map (op : β → γ) : germ l β → germ l γ := map' ((∘) op) $ λ f g H, H.mono $ λ x H, congr_arg op H @[simp] lemma map_coe (op : β → γ) (f : α → β) : map op (f : germ l β) = op ∘ f := rfl @[simp] lemma map_id : map id = (id : germ l β → germ l β) := by { ext ⟨f⟩, refl } lemma map_map (op₁ : γ → δ) (op₂ : β → γ) (f : germ l β) : map op₁ (map op₂ f) = map (op₁ ∘ op₂) f := induction_on f $ λ f, rfl /-- Lift a binary function `β → γ → δ` to a function `germ l β → germ l γ → germ l δ`. -/ def map₂ (op : β → γ → δ) : germ l β → germ l γ → germ l δ := quotient.map₂' (λ f g x, op (f x) (g x)) $ λ f f' Hf g g' Hg, Hg.mp $ Hf.mono $ λ x Hf Hg, by simp only [Hf, Hg] @[simp] lemma map₂_coe (op : β → γ → δ) (f : α → β) (g : α → γ) : map₂ op (f : germ l β) g = λ x, op (f x) (g x) := rfl /-- A germ at `l` of maps from `α` to `β` tends to `lb : filter β` if it is represented by a map which tends to `lb` along `l`. -/ protected def tendsto (f : germ l β) (lb : filter β) : Prop := lift_on f (λ f, tendsto f l lb) $ λ f g H, propext (tendsto_congr' H) @[simp, norm_cast] lemma coe_tendsto {f : α → β} {lb : filter β} : (f : germ l β).tendsto lb ↔ tendsto f l lb := iff.rfl alias coe_tendsto ↔ _ filter.tendsto.germ_tendsto /-- Given two germs `f : germ l β`, and `g : germ lc α`, where `l : filter α`, if `g` tends to `l`, then the composition `f ∘ g` is well-defined as a germ at `lc`. -/ def comp_tendsto' (f : germ l β) {lc : filter γ} (g : germ lc α) (hg : g.tendsto l) : germ lc β := lift_on f (λ f, g.map f) $ λ f₁ f₂ hF, (induction_on g $ λ g hg, coe_eq.2 $ hg.eventually hF) hg @[simp] lemma coe_comp_tendsto' (f : α → β) {lc : filter γ} {g : germ lc α} (hg : g.tendsto l) : (f : germ l β).comp_tendsto' g hg = g.map f := rfl /-- Given a germ `f : germ l β` and a function `g : γ → α`, where `l : filter α`, if `g` tends to `l` along `lc : filter γ`, then the composition `f ∘ g` is well-defined as a germ at `lc`. -/ def comp_tendsto (f : germ l β) {lc : filter γ} (g : γ → α) (hg : tendsto g lc l) : germ lc β := f.comp_tendsto' _ hg.germ_tendsto @[simp] lemma coe_comp_tendsto (f : α → β) {lc : filter γ} {g : γ → α} (hg : tendsto g lc l) : (f : germ l β).comp_tendsto g hg = f ∘ g := rfl @[simp] lemma comp_tendsto'_coe (f : germ l β) {lc : filter γ} {g : γ → α} (hg : tendsto g lc l) : f.comp_tendsto' _ hg.germ_tendsto = f.comp_tendsto g hg := rfl @[simp, norm_cast] lemma const_inj [ne_bot l] {a b : β} : (↑a : germ l β) = ↑b ↔ a = b := coe_eq.trans $ const_eventually_eq @[simp] lemma map_const (l : filter α) (a : β) (f : β → γ) : (↑a : germ l β).map f = ↑(f a) := rfl @[simp] lemma map₂_const (l : filter α) (b : β) (c : γ) (f : β → γ → δ) : map₂ f (↑b : germ l β) ↑c = ↑(f b c) := rfl @[simp] lemma const_comp_tendsto {l : filter α} (b : β) {lc : filter γ} {g : γ → α} (hg : tendsto g lc l) : (↑b : germ l β).comp_tendsto g hg = ↑b := rfl @[simp] lemma const_comp_tendsto' {l : filter α} (b : β) {lc : filter γ} {g : germ lc α} (hg : g.tendsto l) : (↑b : germ l β).comp_tendsto' g hg = ↑b := induction_on g (λ _ _, rfl) hg /-- Lift a predicate on `β` to `germ l β`. -/ def lift_pred (p : β → Prop) (f : germ l β) : Prop := lift_on f (λ f, ∀ᶠ x in l, p (f x)) $ λ f g H, propext $ eventually_congr $ H.mono $ λ x hx, hx ▸ iff.rfl @[simp] lemma lift_pred_coe {p : β → Prop} {f : α → β} : lift_pred p (f : germ l β) ↔ ∀ᶠ x in l, p (f x) := iff.rfl lemma lift_pred_const {p : β → Prop} {x : β} (hx : p x) : lift_pred p (↑x : germ l β) := eventually_of_forall $ λ y, hx @[simp] lemma lift_pred_const_iff [ne_bot l] {p : β → Prop} {x : β} : lift_pred p (↑x : germ l β) ↔ p x := @eventually_const _ _ _ (p x) /-- Lift a relation `r : β → γ → Prop` to `germ l β → germ l γ → Prop`. -/ def lift_rel (r : β → γ → Prop) (f : germ l β) (g : germ l γ) : Prop := quotient.lift_on₂' f g (λ f g, ∀ᶠ x in l, r (f x) (g x)) $ λ f g f' g' Hf Hg, propext $ eventually_congr $ Hg.mp $ Hf.mono $ λ x hf hg, hf ▸ hg ▸ iff.rfl @[simp] lemma lift_rel_coe {r : β → γ → Prop} {f : α → β} {g : α → γ} : lift_rel r (f : germ l β) g ↔ ∀ᶠ x in l, r (f x) (g x) := iff.rfl lemma lift_rel_const {r : β → γ → Prop} {x : β} {y : γ} (h : r x y) : lift_rel r (↑x : germ l β) ↑y := eventually_of_forall $ λ _, h @[simp] lemma lift_rel_const_iff [ne_bot l] {r : β → γ → Prop} {x : β} {y : γ} : lift_rel r (↑x : germ l β) ↑y ↔ r x y := @eventually_const _ _ _ (r x y) instance [inhabited β] : inhabited (germ l β) := ⟨↑(default β)⟩ section monoid variables {M : Type*} {G : Type*} @[to_additive] instance [has_mul M] : has_mul (germ l M) := ⟨map₂ (*)⟩ @[simp, to_additive] lemma coe_mul [has_mul M] (f g : α → M) : ↑(f * g) = (f * g : germ l M) := rfl attribute [norm_cast] coe_mul coe_add @[to_additive] instance [has_one M] : has_one (germ l M) := ⟨↑(1:M)⟩ @[simp, to_additive] lemma coe_one [has_one M] : ↑(1 : α → M) = (1 : germ l M) := rfl attribute [norm_cast] coe_one coe_zero @[to_additive] instance [semigroup M] : semigroup (germ l M) := { mul := (*), mul_assoc := by { rintros ⟨f⟩ ⟨g⟩ ⟨h⟩, simp only [mul_assoc, quot_mk_eq_coe, ← coe_mul] } } @[to_additive] instance [comm_semigroup M] : comm_semigroup (germ l M) := { mul := (*), mul_comm := by { rintros ⟨f⟩ ⟨g⟩, simp only [mul_comm, quot_mk_eq_coe, ← coe_mul] }, .. germ.semigroup } @[to_additive add_left_cancel_semigroup] instance [left_cancel_semigroup M] : left_cancel_semigroup (germ l M) := { mul := (*), mul_left_cancel := λ f₁ f₂ f₃, induction_on₃ f₁ f₂ f₃ $ λ f₁ f₂ f₃ H, coe_eq.2 ((coe_eq.1 H).mono $ λ x, mul_left_cancel), .. germ.semigroup } @[to_additive add_right_cancel_semigroup] instance [right_cancel_semigroup M] : right_cancel_semigroup (germ l M) := { mul := (*), mul_right_cancel := λ f₁ f₂ f₃, induction_on₃ f₁ f₂ f₃ $ λ f₁ f₂ f₃ H, coe_eq.2 $ (coe_eq.1 H).mono $ λ x, mul_right_cancel, .. germ.semigroup } @[to_additive] instance [monoid M] : monoid (germ l M) := { mul := (*), one := 1, one_mul := λ f, induction_on f $ λ f, by { norm_cast, rw [one_mul] }, mul_one := λ f, induction_on f $ λ f, by { norm_cast, rw [mul_one] }, .. germ.semigroup } /-- coercion from functions to germs as a monoid homomorphism. -/ @[to_additive] def coe_mul_hom [monoid M] (l : filter α) : (α → M) →* germ l M := ⟨coe, rfl, λ f g, rfl⟩ /-- coercion from functions to germs as an additive monoid homomorphism. -/ add_decl_doc coe_add_hom @[simp, to_additive] lemma coe_coe_mul_hom [monoid M] : (coe_mul_hom l : (α → M) → germ l M) = coe := rfl @[to_additive] instance [comm_monoid M] : comm_monoid (germ l M) := { mul := (*), one := 1, .. germ.comm_semigroup, .. germ.monoid } @[to_additive] instance [has_inv G] : has_inv (germ l G) := ⟨map has_inv.inv⟩ @[simp, to_additive] lemma coe_inv [has_inv G] (f : α → G) : ↑f⁻¹ = (f⁻¹ : germ l G) := rfl attribute [norm_cast] coe_inv coe_neg @[to_additive] instance [has_div M] : has_div (germ l M) := ⟨map₂ (/)⟩ @[simp, norm_cast, to_additive] lemma coe_div [has_div M] (f g : α → M) : ↑(f / g) = (f / g : germ l M) := rfl @[to_additive] instance [div_inv_monoid G] : div_inv_monoid (germ l G) := { inv := has_inv.inv, div := has_div.div, div_eq_mul_inv := by { rintros ⟨f⟩ ⟨g⟩, exact congr_arg (quot.mk _) (div_eq_mul_inv f g) }, .. germ.monoid } @[to_additive] instance [group G] : group (germ l G) := { mul := (*), one := 1, mul_left_inv := by { rintros ⟨f⟩, exact congr_arg (quot.mk _) (mul_left_inv f) }, .. germ.div_inv_monoid } @[to_additive] instance [comm_group G] : comm_group (germ l G) := { mul := (*), one := 1, inv := has_inv.inv, .. germ.group, .. germ.comm_monoid } end monoid section ring variables {R : Type*} instance nontrivial [nontrivial R] [ne_bot l] : nontrivial (germ l R) := let ⟨x, y, h⟩ := exists_pair_ne R in ⟨⟨↑x, ↑y, mt const_inj.1 h⟩⟩ instance [mul_zero_class R] : mul_zero_class (germ l R) := { zero := 0, mul := (*), mul_zero := λ f, induction_on f $ λ f, by { norm_cast, rw [mul_zero] }, zero_mul := λ f, induction_on f $ λ f, by { norm_cast, rw [zero_mul] } } instance [distrib R] : distrib (germ l R) := { mul := (*), add := (+), left_distrib := λ f g h, induction_on₃ f g h $ λ f g h, by { norm_cast, rw [left_distrib] }, right_distrib := λ f g h, induction_on₃ f g h $ λ f g h, by { norm_cast, rw [right_distrib] } } instance [semiring R] : semiring (germ l R) := { .. germ.add_comm_monoid, .. germ.monoid, .. germ.distrib, .. germ.mul_zero_class } /-- Coercion `(α → R) → germ l R` as a `ring_hom`. -/ def coe_ring_hom [semiring R] (l : filter α) : (α → R) →+* germ l R := { to_fun := coe, .. (coe_mul_hom l : _ →* germ l R), .. (coe_add_hom l : _ →+ germ l R) } @[simp] lemma coe_coe_ring_hom [semiring R] : (coe_ring_hom l : (α → R) → germ l R) = coe := rfl instance [ring R] : ring (germ l R) := { .. germ.add_comm_group, .. germ.monoid, .. germ.distrib, .. germ.mul_zero_class } instance [comm_semiring R] : comm_semiring (germ l R) := { .. germ.semiring, .. germ.comm_monoid } instance [comm_ring R] : comm_ring (germ l R) := { .. germ.ring, .. germ.comm_monoid } end ring section module variables {M N R : Type*} instance [has_scalar M β] : has_scalar M (germ l β) := ⟨λ c, map ((•) c)⟩ instance has_scalar' [has_scalar M β] : has_scalar (germ l M) (germ l β) := ⟨map₂ (•)⟩ @[simp, norm_cast] lemma coe_smul [has_scalar M β] (c : M) (f : α → β) : ↑(c • f) = (c • f : germ l β) := rfl @[simp, norm_cast] lemma coe_smul' [has_scalar M β] (c : α → M) (f : α → β) : ↑(c • f) = (c : germ l M) • (f : germ l β) := rfl instance [monoid M] [mul_action M β] : mul_action M (germ l β) := { one_smul := λ f, induction_on f $ λ f, by { norm_cast, simp only [one_smul] }, mul_smul := λ c₁ c₂ f, induction_on f $ λ f, by { norm_cast, simp only [mul_smul] } } instance mul_action' [monoid M] [mul_action M β] : mul_action (germ l M) (germ l β) := { one_smul := λ f, induction_on f $ λ f, by simp only [← coe_one, ← coe_smul', one_smul], mul_smul := λ c₁ c₂ f, induction_on₃ c₁ c₂ f $ λ c₁ c₂ f, by { norm_cast, simp only [mul_smul] } } instance [monoid M] [add_monoid N] [distrib_mul_action M N] : distrib_mul_action M (germ l N) := { smul_add := λ c f g, induction_on₂ f g $ λ f g, by { norm_cast, simp only [smul_add] }, smul_zero := λ c, by simp only [← coe_zero, ← coe_smul, smul_zero] } instance distrib_mul_action' [monoid M] [add_monoid N] [distrib_mul_action M N] : distrib_mul_action (germ l M) (germ l N) := { smul_add := λ c f g, induction_on₃ c f g $ λ c f g, by { norm_cast, simp only [smul_add] }, smul_zero := λ c, induction_on c $ λ c, by simp only [← coe_zero, ← coe_smul', smul_zero] } instance [semiring R] [add_comm_monoid M] [semimodule R M] : semimodule R (germ l M) := { add_smul := λ c₁ c₂ f, induction_on f $ λ f, by { norm_cast, simp only [add_smul] }, zero_smul := λ f, induction_on f $ λ f, by { norm_cast, simp only [zero_smul, coe_zero] } } instance semimodule' [semiring R] [add_comm_monoid M] [semimodule R M] : semimodule (germ l R) (germ l M) := { add_smul := λ c₁ c₂ f, induction_on₃ c₁ c₂ f $ λ c₁ c₂ f, by { norm_cast, simp only [add_smul] }, zero_smul := λ f, induction_on f $ λ f, by simp only [← coe_zero, ← coe_smul', zero_smul] } end module instance [has_le β] : has_le (germ l β) := ⟨lift_rel (≤)⟩ @[simp] lemma coe_le [has_le β] : (f : germ l β) ≤ g ↔ (f ≤ᶠ[l] g) := iff.rfl lemma le_def [has_le β] : ((≤) : germ l β → germ l β → Prop) = lift_rel (≤) := rfl lemma const_le [has_le β] {x y : β} (h : x ≤ y) : (↑x : germ l β) ≤ ↑y := lift_rel_const h @[simp, norm_cast] lemma const_le_iff [has_le β] [ne_bot l] {x y : β} : (↑x : germ l β) ≤ ↑y ↔ x ≤ y := lift_rel_const_iff instance [preorder β] : preorder (germ l β) := { le := (≤), le_refl := λ f, induction_on f $ eventually_le.refl l, le_trans := λ f₁ f₂ f₃, induction_on₃ f₁ f₂ f₃ $ λ f₁ f₂ f₃, eventually_le.trans } instance [partial_order β] : partial_order (germ l β) := { le := (≤), le_antisymm := λ f g, induction_on₂ f g $ λ f g h₁ h₂, (eventually_le.antisymm h₁ h₂).germ_eq, .. germ.preorder } instance [has_bot β] : has_bot (germ l β) := ⟨↑(⊥:β)⟩ @[simp, norm_cast] lemma const_bot [has_bot β] : (↑(⊥:β) : germ l β) = ⊥ := rfl instance [order_bot β] : order_bot (germ l β) := { bot := ⊥, le := (≤), bot_le := λ f, induction_on f $ λ f, eventually_of_forall $ λ x, bot_le, .. germ.partial_order } instance [has_top β] : has_top (germ l β) := ⟨↑(⊤:β)⟩ @[simp, norm_cast] lemma const_top [has_top β] : (↑(⊤:β) : germ l β) = ⊤ := rfl instance [order_top β] : order_top (germ l β) := { top := ⊤, le := (≤), le_top := λ f, induction_on f $ λ f, eventually_of_forall $ λ x, le_top, .. germ.partial_order } instance [has_sup β] : has_sup (germ l β) := ⟨map₂ (⊔)⟩ @[simp, norm_cast] lemma const_sup [has_sup β] (a b : β) : ↑(a ⊔ b) = (↑a ⊔ ↑b : germ l β) := rfl instance [has_inf β] : has_inf (germ l β) := ⟨map₂ (⊓)⟩ @[simp, norm_cast] lemma const_inf [has_inf β] (a b : β) : ↑(a ⊓ b) = (↑a ⊓ ↑b : germ l β) := rfl instance [semilattice_sup β] : semilattice_sup (germ l β) := { sup := (⊔), le_sup_left := λ f g, induction_on₂ f g $ λ f g, eventually_of_forall $ λ x, le_sup_left, le_sup_right := λ f g, induction_on₂ f g $ λ f g, eventually_of_forall $ λ x, le_sup_right, sup_le := λ f₁ f₂ g, induction_on₃ f₁ f₂ g $ λ f₁ f₂ g h₁ h₂, h₂.mp $ h₁.mono $ λ x, sup_le, .. germ.partial_order } instance [semilattice_inf β] : semilattice_inf (germ l β) := { inf := (⊓), inf_le_left := λ f g, induction_on₂ f g $ λ f g, eventually_of_forall $ λ x, inf_le_left, inf_le_right := λ f g, induction_on₂ f g $ λ f g, eventually_of_forall $ λ x, inf_le_right, le_inf := λ f₁ f₂ g, induction_on₃ f₁ f₂ g $ λ f₁ f₂ g h₁ h₂, h₂.mp $ h₁.mono $ λ x, le_inf, .. germ.partial_order } instance [semilattice_inf_bot β] : semilattice_inf_bot (germ l β) := { .. germ.semilattice_inf, .. germ.order_bot } instance [semilattice_sup_bot β] : semilattice_sup_bot (germ l β) := { .. germ.semilattice_sup, .. germ.order_bot } instance [semilattice_inf_top β] : semilattice_inf_top (germ l β) := { .. germ.semilattice_inf, .. germ.order_top } instance [semilattice_sup_top β] : semilattice_sup_top (germ l β) := { .. germ.semilattice_sup, .. germ.order_top } instance [lattice β] : lattice (germ l β) := { .. germ.semilattice_sup, .. germ.semilattice_inf } instance [bounded_lattice β] : bounded_lattice (germ l β) := { .. germ.lattice, .. germ.order_bot, .. germ.order_top } @[to_additive] instance [ordered_cancel_comm_monoid β] : ordered_cancel_comm_monoid (germ l β) := { mul_le_mul_left := λ f g, induction_on₂ f g $ λ f g H h, induction_on h $ λ h, H.mono $ λ x H, mul_le_mul_left' H _, le_of_mul_le_mul_left := λ f g h, induction_on₃ f g h $ λ f g h H, H.mono $ λ x, le_of_mul_le_mul_left', .. germ.partial_order, .. germ.comm_monoid, .. germ.left_cancel_semigroup, .. germ.right_cancel_semigroup } @[to_additive] instance ordered_comm_group [ordered_comm_group β] : ordered_comm_group (germ l β) := { mul_le_mul_left := λ f g, induction_on₂ f g $ λ f g H h, induction_on h $ λ h, H.mono $ λ x H, mul_le_mul_left' H _, .. germ.partial_order, .. germ.comm_group } end germ end filter
4cb9b47c2c924128ea3f411bc8c503b0b4e00499
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/number_theory/liouville/liouville_with.lean
f202e4554a99c97c20c56a0ff9f69f15b51774f8
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
14,930
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. Kudryashov -/ import analysis.special_functions.pow.asymptotics import number_theory.liouville.basic import topology.instances.irrational /-! # Liouville numbers with a given exponent > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We say that a real number `x` is a Liouville number with exponent `p : ℝ` if there exists a real number `C` such that for infinitely many denominators `n` there exists a numerator `m` such that `x ≠ m / n` and `|x - m / n| < C / n ^ p`. A number is a Liouville number in the sense of `liouville` if it is `liouville_with` any real exponent, see `forall_liouville_with_iff`. * If `p ≤ 1`, then this condition is trivial. * If `1 < p ≤ 2`, then this condition is equivalent to `irrational x`. The forward implication does not require `p ≤ 2` and is formalized as `liouville_with.irrational`; the other implication follows from approximations by continued fractions and is not formalized yet. * If `p > 2`, then this is a non-trivial condition on irrational numbers. In particular, [Thue–Siegel–Roth theorem](https://en.wikipedia.org/wiki/Roth's_theorem) states that such numbers must be transcendental. In this file we define the predicate `liouville_with` and prove some basic facts about this predicate. ## Tags Liouville number, irrational, irrationality exponent -/ open filter metric real set open_locale filter topology /-- We say that a real number `x` is a Liouville number with exponent `p : ℝ` if there exists a real number `C` such that for infinitely many denominators `n` there exists a numerator `m` such that `x ≠ m / n` and `|x - m / n| < C / n ^ p`. A number is a Liouville number in the sense of `liouville` if it is `liouville_with` any real exponent. -/ def liouville_with (p x : ℝ) : Prop := ∃ C, ∃ᶠ n : ℕ in at_top, ∃ m : ℤ, x ≠ m / n ∧ |x - m / n| < C / n ^ p /-- For `p = 1` (hence, for any `p ≤ 1`), the condition `liouville_with p x` is trivial. -/ lemma liouville_with_one (x : ℝ) : liouville_with 1 x := begin use 2, refine ((eventually_gt_at_top 0).mono $ λ n hn, _).frequently, have hn' : (0 : ℝ) < n, by simpa, have : x < ↑(⌊x * ↑n⌋ + 1) / ↑n, { rw [lt_div_iff hn', int.cast_add, int.cast_one], exact int.lt_floor_add_one _ }, refine ⟨⌊x * n⌋ + 1, this.ne, _⟩, rw [abs_sub_comm, abs_of_pos (sub_pos.2 this), rpow_one, sub_lt_iff_lt_add', add_div_eq_mul_add_div _ _ hn'.ne', div_lt_div_right hn'], simpa [bit0, ← add_assoc] using (int.floor_le (x * n)).trans_lt (lt_add_one _) end namespace liouville_with variables {p q x y : ℝ} {r : ℚ} {m : ℤ} {n : ℕ} /-- The constant `C` provided by the definition of `liouville_with` can be made positive. We also add `1 ≤ n` to the list of assumptions about the denominator. While it is equivalent to the original statement, the case `n = 0` breaks many arguments. -/ lemma exists_pos (h : liouville_with p x) : ∃ (C : ℝ) (h₀ : 0 < C), ∃ᶠ n : ℕ in at_top, 1 ≤ n ∧ ∃ m : ℤ, x ≠ m / n ∧ |x - m / n| < C / n ^ p := begin rcases h with ⟨C, hC⟩, refine ⟨max C 1, zero_lt_one.trans_le $ le_max_right _ _, _⟩, refine ((eventually_ge_at_top 1).and_frequently hC).mono _, rintro n ⟨hle, m, hne, hlt⟩, refine ⟨hle, m, hne, hlt.trans_le _⟩, exact div_le_div_of_le (rpow_nonneg_of_nonneg n.cast_nonneg _) (le_max_left _ _) end /-- If a number is Liouville with exponent `p`, then it is Liouville with any smaller exponent. -/ lemma mono (h : liouville_with p x) (hle : q ≤ p) : liouville_with q x := begin rcases h.exists_pos with ⟨C, hC₀, hC⟩, refine ⟨C, hC.mono _⟩, rintro n ⟨hn, m, hne, hlt⟩, refine ⟨m, hne, hlt.trans_le $ div_le_div_of_le_left hC₀.le _ _⟩, exacts [rpow_pos_of_pos (nat.cast_pos.2 hn) _, rpow_le_rpow_of_exponent_le (nat.one_le_cast.2 hn) hle] end /-- If `x` satisfies Liouville condition with exponent `p` and `q < p`, then `x` satisfies Liouville condition with exponent `q` and constant `1`. -/ lemma frequently_lt_rpow_neg (h : liouville_with p x) (hlt : q < p) : ∃ᶠ n : ℕ in at_top, ∃ m : ℤ, x ≠ m / n ∧ |x - m / n| < n ^ (-q) := begin rcases h.exists_pos with ⟨C, hC₀, hC⟩, have : ∀ᶠ n : ℕ in at_top, C < n ^ (p - q), by simpa only [(∘), neg_sub, one_div] using ((tendsto_rpow_at_top (sub_pos.2 hlt)).comp tendsto_coe_nat_at_top_at_top).eventually (eventually_gt_at_top C), refine (this.and_frequently hC).mono _, rintro n ⟨hnC, hn, m, hne, hlt⟩, replace hn : (0 : ℝ) < n := nat.cast_pos.2 hn, refine ⟨m, hne, hlt.trans $ (div_lt_iff $ rpow_pos_of_pos hn _).2 _⟩, rwa [mul_comm, ← rpow_add hn, ← sub_eq_add_neg] end /-- The product of a Liouville number and a nonzero rational number is again a Liouville number. -/ lemma mul_rat (h : liouville_with p x) (hr : r ≠ 0) : liouville_with p (x * r) := begin rcases h.exists_pos with ⟨C, hC₀, hC⟩, refine ⟨r.denom ^ p * (|r| * C), (tendsto_id.nsmul_at_top r.pos).frequently (hC.mono _)⟩, rintro n ⟨hn, m, hne, hlt⟩, have A : (↑(r.num * m) : ℝ) / ↑(r.denom • id n) = (m / n) * r, by simp [← div_mul_div_comm, ← r.cast_def, mul_comm], refine ⟨r.num * m, _, _⟩, { rw A, simp [hne, hr] }, { rw [A, ← sub_mul, abs_mul], simp only [smul_eq_mul, id.def, nat.cast_mul], refine (mul_lt_mul_of_pos_right hlt $ abs_pos.2 $ rat.cast_ne_zero.2 hr).trans_le _, rw [mul_rpow, mul_div_mul_left, mul_comm, mul_div_assoc], exacts [(rpow_pos_of_pos (nat.cast_pos.2 r.pos) _).ne', nat.cast_nonneg _, nat.cast_nonneg _] } end /-- The product `x * r`, `r : ℚ`, `r ≠ 0`, is a Liouville number with exponent `p` if and only if `x` satisfies the same condition. -/ lemma mul_rat_iff (hr : r ≠ 0) : liouville_with p (x * r) ↔ liouville_with p x := ⟨λ h, by simpa only [mul_assoc, ← rat.cast_mul, mul_inv_cancel hr, rat.cast_one, mul_one] using h.mul_rat (inv_ne_zero hr), λ h, h.mul_rat hr⟩ /-- The product `r * x`, `r : ℚ`, `r ≠ 0`, is a Liouville number with exponent `p` if and only if `x` satisfies the same condition. -/ lemma rat_mul_iff (hr : r ≠ 0) : liouville_with p (r * x) ↔ liouville_with p x := by rw [mul_comm, mul_rat_iff hr] lemma rat_mul (h : liouville_with p x) (hr : r ≠ 0) : liouville_with p (r * x) := (rat_mul_iff hr).2 h lemma mul_int_iff (hm : m ≠ 0) : liouville_with p (x * m) ↔ liouville_with p x := by rw [← rat.cast_coe_int, mul_rat_iff (int.cast_ne_zero.2 hm)] lemma mul_int (h : liouville_with p x) (hm : m ≠ 0) : liouville_with p (x * m) := (mul_int_iff hm).2 h lemma int_mul_iff (hm : m ≠ 0) : liouville_with p (m * x) ↔ liouville_with p x := by rw [mul_comm, mul_int_iff hm] lemma int_mul (h : liouville_with p x) (hm : m ≠ 0) : liouville_with p (m * x) := (int_mul_iff hm).2 h lemma mul_nat_iff (hn : n ≠ 0) : liouville_with p (x * n) ↔ liouville_with p x := by rw [← rat.cast_coe_nat, mul_rat_iff (nat.cast_ne_zero.2 hn)] lemma mul_nat (h : liouville_with p x) (hn : n ≠ 0) : liouville_with p (x * n) := (mul_nat_iff hn).2 h lemma nat_mul_iff (hn : n ≠ 0) : liouville_with p (n * x) ↔ liouville_with p x:= by rw [mul_comm, mul_nat_iff hn] lemma nat_mul (h : liouville_with p x) (hn : n ≠ 0) : liouville_with p (n * x) := by { rw mul_comm, exact h.mul_nat hn } lemma add_rat (h : liouville_with p x) (r : ℚ) : liouville_with p (x + r) := begin rcases h.exists_pos with ⟨C, hC₀, hC⟩, refine ⟨r.denom ^ p * C, (tendsto_id.nsmul_at_top r.pos).frequently (hC.mono _)⟩, rintro n ⟨hn, m, hne, hlt⟩, have hr : (0 : ℝ) < r.denom, from nat.cast_pos.2 r.pos, have hn' : (n : ℝ) ≠ 0, from nat.cast_ne_zero.2 (zero_lt_one.trans_le hn).ne', have : (↑(r.denom * m + r.num * n : ℤ) / ↑(r.denom • id n) : ℝ) = m / n + r, by simp [add_div, hr.ne', mul_div_mul_left, mul_div_mul_right, hn', ← rat.cast_def], refine ⟨r.denom * m + r.num * n, _⟩, rw [this, add_sub_add_right_eq_sub], refine ⟨by simpa, hlt.trans_le (le_of_eq _)⟩, have : (r.denom ^ p : ℝ) ≠ 0, from (rpow_pos_of_pos hr _).ne', simp [mul_rpow, nat.cast_nonneg, mul_div_mul_left, this] end @[simp] lemma add_rat_iff : liouville_with p (x + r) ↔ liouville_with p x := ⟨λ h, by simpa using h.add_rat (-r), λ h, h.add_rat r⟩ @[simp] lemma rat_add_iff : liouville_with p (r + x) ↔ liouville_with p x := by rw [add_comm, add_rat_iff] lemma rat_add (h : liouville_with p x) (r : ℚ) : liouville_with p (r + x) := add_comm x r ▸ h.add_rat r @[simp] lemma add_int_iff : liouville_with p (x + m) ↔ liouville_with p x := by rw [← rat.cast_coe_int m, add_rat_iff] @[simp] lemma int_add_iff : liouville_with p (m + x) ↔ liouville_with p x := by rw [add_comm, add_int_iff] @[simp] lemma add_nat_iff : liouville_with p (x + n) ↔ liouville_with p x := by rw [← rat.cast_coe_nat n, add_rat_iff] @[simp] lemma nat_add_iff : liouville_with p (n + x) ↔ liouville_with p x := by rw [add_comm, add_nat_iff] lemma add_int (h : liouville_with p x) (m : ℤ) : liouville_with p (x + m) := add_int_iff.2 h lemma int_add (h : liouville_with p x) (m : ℤ) : liouville_with p (m + x) := int_add_iff.2 h lemma add_nat (h : liouville_with p x) (n : ℕ) : liouville_with p (x + n) := h.add_int n lemma nat_add (h : liouville_with p x) (n : ℕ) : liouville_with p (n + x) := h.int_add n protected lemma neg (h : liouville_with p x) : liouville_with p (-x) := begin rcases h with ⟨C, hC⟩, refine ⟨C, hC.mono _⟩, rintro n ⟨m, hne, hlt⟩, use (-m), simp [neg_div, abs_sub_comm _ x, *] end @[simp] lemma neg_iff : liouville_with p (-x) ↔ liouville_with p x := ⟨λ h, neg_neg x ▸ h.neg, liouville_with.neg⟩ @[simp] lemma sub_rat_iff : liouville_with p (x - r) ↔ liouville_with p x := by rw [sub_eq_add_neg, ← rat.cast_neg, add_rat_iff] lemma sub_rat (h : liouville_with p x) (r : ℚ) : liouville_with p (x - r) := sub_rat_iff.2 h @[simp] lemma sub_int_iff : liouville_with p (x - m) ↔ liouville_with p x := by rw [← rat.cast_coe_int, sub_rat_iff] lemma sub_int (h : liouville_with p x) (m : ℤ) : liouville_with p (x - m) := sub_int_iff.2 h @[simp] lemma sub_nat_iff : liouville_with p (x - n) ↔ liouville_with p x := by rw [← rat.cast_coe_nat, sub_rat_iff] lemma sub_nat (h : liouville_with p x) (n : ℕ) : liouville_with p (x - n) := sub_nat_iff.2 h @[simp] lemma rat_sub_iff : liouville_with p (r - x) ↔ liouville_with p x := by simp [sub_eq_add_neg] lemma rat_sub (h : liouville_with p x) (r : ℚ) : liouville_with p (r - x) := rat_sub_iff.2 h @[simp] lemma int_sub_iff : liouville_with p (m - x) ↔ liouville_with p x := by simp [sub_eq_add_neg] lemma int_sub (h : liouville_with p x) (m : ℤ) : liouville_with p (m - x) := int_sub_iff.2 h @[simp] lemma nat_sub_iff : liouville_with p (n - x) ↔ liouville_with p x := by simp [sub_eq_add_neg] lemma nat_sub (h : liouville_with p x) (n : ℕ) : liouville_with p (n - x) := nat_sub_iff.2 h lemma ne_cast_int (h : liouville_with p x) (hp : 1 < p) (m : ℤ) : x ≠ m := begin rintro rfl, rename m M, rcases ((eventually_gt_at_top 0).and_frequently (h.frequently_lt_rpow_neg hp)).exists with ⟨n : ℕ, hn : 0 < n, m : ℤ, hne : (M : ℝ) ≠ m / n, hlt : |(M - m / n : ℝ)| < n ^ (-1 : ℝ)⟩, refine hlt.not_le _, have hn' : (0 : ℝ) < n, by simpa, rw [rpow_neg_one, ← one_div, sub_div' _ _ _ hn'.ne', abs_div, nat.abs_cast, div_le_div_right hn'], norm_cast, rw [← zero_add (1 : ℤ), int.add_one_le_iff, abs_pos, sub_ne_zero], rw [ne.def, eq_div_iff hn'.ne'] at hne, exact_mod_cast hne end /-- A number satisfying the Liouville condition with exponent `p > 1` is an irrational number. -/ protected lemma irrational (h : liouville_with p x) (hp : 1 < p) : irrational x := begin rintro ⟨r, rfl⟩, rcases eq_or_ne r 0 with (rfl|h0), { refine h.ne_cast_int hp 0 _, rw [rat.cast_zero, int.cast_zero] }, { refine (h.mul_rat (inv_ne_zero h0)).ne_cast_int hp 1 _, simp [rat.cast_ne_zero.2 h0] } end end liouville_with namespace liouville variables {x : ℝ} /-- If `x` is a Liouville number, then for any `n`, for infinitely many denominators `b` there exists a numerator `a` such that `x ≠ a / b` and `|x - a / b| < 1 / b ^ n`. -/ lemma frequently_exists_num (hx : liouville x) (n : ℕ) : ∃ᶠ b : ℕ in at_top, ∃ a : ℤ, x ≠ a / b ∧ |x - a / b| < 1 / b ^ n := begin refine not_not.1 (λ H, _), simp only [liouville, not_forall, not_exists, not_frequently, not_and, not_lt, eventually_at_top] at H, rcases H with ⟨N, hN⟩, have : ∀ b > (1 : ℕ), ∀ᶠ m : ℕ in at_top, ∀ a : ℤ, (1 / b ^ m : ℝ) ≤ |x - a / b|, { intros b hb, replace hb : (1 : ℝ) < b := nat.one_lt_cast.2 hb, have H : tendsto (λ m, 1 / b ^ m : ℕ → ℝ) at_top (𝓝 0), { simp only [one_div], exact tendsto_inv_at_top_zero.comp (tendsto_pow_at_top_at_top_of_one_lt hb) }, refine (H.eventually (hx.irrational.eventually_forall_le_dist_cast_div b)).mono _, exact λ m hm a, hm a }, have : ∀ᶠ m : ℕ in at_top, ∀ b < N, 1 < b → ∀ a : ℤ, (1 / b ^ m : ℝ) ≤ |x - a / b|, from (finite_lt_nat N).eventually_all.2 (λ b hb, eventually_imp_distrib_left.2 (this b)), rcases (this.and (eventually_ge_at_top n)).exists with ⟨m, hm, hnm⟩, rcases hx m with ⟨a, b, hb, hne, hlt⟩, lift b to ℕ using zero_le_one.trans hb.le, norm_cast at hb, push_cast at hne hlt, cases le_or_lt N b, { refine (hN b h a hne).not_lt (hlt.trans_le _), replace hb : (1 : ℝ) < b := nat.one_lt_cast.2 hb, have hb0 : (0 : ℝ) < b := zero_lt_one.trans hb, exact one_div_le_one_div_of_le (pow_pos hb0 _) (pow_le_pow hb.le hnm) }, { exact (hm b h hb _).not_lt hlt } end /-- A Liouville number is a Liouville number with any real exponent. -/ protected lemma liouville_with (hx : liouville x) (p : ℝ) : liouville_with p x := begin suffices : liouville_with ⌈p⌉₊ x, from this.mono (nat.le_ceil p), refine ⟨1, ((eventually_gt_at_top 1).and_frequently (hx.frequently_exists_num ⌈p⌉₊)).mono _⟩, rintro b ⟨hb, a, hne, hlt⟩, refine ⟨a, hne, _⟩, rwa rpow_nat_cast end end liouville /-- A number satisfies the Liouville condition with any exponent if and only if it is a Liouville number. -/ lemma forall_liouville_with_iff {x : ℝ} : (∀ p, liouville_with p x) ↔ liouville x := begin refine ⟨λ H n, _, liouville.liouville_with⟩, rcases ((eventually_gt_at_top 1).and_frequently ((H (n + 1)).frequently_lt_rpow_neg (lt_add_one n))).exists with ⟨b, hb, a, hne, hlt⟩, exact ⟨a, b, by exact_mod_cast hb, hne, by simpa [rpow_neg] using hlt⟩, end
427848fb415bdfd576465df1277ecfaced01367d
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/number_theory/bernoulli_polynomials.lean
3e7801f402ce0695f2e02e25f409cc1905700f76
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
9,972
lean
/- Copyright (c) 2021 Ashvni Narayanan. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Ashvni Narayanan, David Loeffler -/ import data.polynomial.algebra_map import data.polynomial.derivative import data.nat.choose.cast import number_theory.bernoulli /-! # Bernoulli polynomials The [Bernoulli polynomials](https://en.wikipedia.org/wiki/Bernoulli_polynomials) are an important tool obtained from Bernoulli numbers. ## Mathematical overview The $n$-th Bernoulli polynomial is defined as $$ B_n(X) = ∑_{k = 0}^n {n \choose k} (-1)^k B_k X^{n - k} $$ where $B_k$ is the $k$-th Bernoulli number. The Bernoulli polynomials are generating functions, $$ \frac{t e^{tX} }{ e^t - 1} = ∑_{n = 0}^{\infty} B_n(X) \frac{t^n}{n!} $$ ## Implementation detail Bernoulli polynomials are defined using `bernoulli`, the Bernoulli numbers. ## Main theorems - `sum_bernoulli`: The sum of the $k^\mathrm{th}$ Bernoulli polynomial with binomial coefficients up to `n` is `(n + 1) * X^n`. - `polynomial.bernoulli_generating_function`: The Bernoulli polynomials act as generating functions for the exponential. ## TODO - `bernoulli_eval_one_neg` : $$ B_n(1 - x) = (-1)^n B_n(x) $$ -/ noncomputable theory open_locale big_operators open_locale nat polynomial open nat finset namespace polynomial /-- The Bernoulli polynomials are defined in terms of the negative Bernoulli numbers. -/ def bernoulli (n : ℕ) : ℚ[X] := ∑ i in range (n + 1), polynomial.monomial (n - i) ((_root_.bernoulli i) * (choose n i)) lemma bernoulli_def (n : ℕ) : bernoulli n = ∑ i in range (n + 1), polynomial.monomial i ((_root_.bernoulli (n - i)) * (choose n i)) := begin rw [←sum_range_reflect, add_succ_sub_one, add_zero, bernoulli], apply sum_congr rfl, rintros x hx, rw mem_range_succ_iff at hx, rw [choose_symm hx, tsub_tsub_cancel_of_le hx], end /- ### examples -/ section examples @[simp] lemma bernoulli_zero : bernoulli 0 = 1 := by simp [bernoulli] @[simp] lemma bernoulli_eval_zero (n : ℕ) : (bernoulli n).eval 0 = _root_.bernoulli n := begin rw [bernoulli, eval_finset_sum, sum_range_succ], have : ∑ (x : ℕ) in range n, _root_.bernoulli x * (n.choose x) * 0 ^ (n - x) = 0, { apply sum_eq_zero (λ x hx, _), have h : 0 < n - x := tsub_pos_of_lt (mem_range.1 hx), simp [h] }, simp [this], end @[simp] lemma bernoulli_eval_one (n : ℕ) : (bernoulli n).eval 1 = _root_.bernoulli' n := begin simp only [bernoulli, eval_finset_sum], simp only [←succ_eq_add_one, sum_range_succ, mul_one, cast_one, choose_self, (_root_.bernoulli _).mul_comm, sum_bernoulli, one_pow, mul_one, eval_C, eval_monomial], by_cases h : n = 1, { norm_num [h], }, { simp [h], exact bernoulli_eq_bernoulli'_of_ne_one h, } end end examples lemma derivative_bernoulli_add_one (k : ℕ) : (bernoulli (k + 1)).derivative = (k + 1) * bernoulli k := begin simp_rw [bernoulli, derivative_sum, derivative_monomial, nat.sub_sub, nat.add_sub_add_right], -- LHS sum has an extra term, but the coefficient is zero: rw [range_add_one, sum_insert not_mem_range_self, tsub_self, cast_zero, mul_zero, map_zero, zero_add, mul_sum], -- the rest of the sum is termwise equal: refine sum_congr (by refl) (λ m hm, _), conv_rhs { rw [←nat.cast_one, ←nat.cast_add, ←C_eq_nat_cast, C_mul_monomial, mul_comm], }, rw [mul_assoc, mul_assoc, ←nat.cast_mul, ←nat.cast_mul], congr' 3, rw [(choose_mul_succ_eq k m).symm, mul_comm], end lemma derivative_bernoulli (k : ℕ) : (bernoulli k).derivative = k * bernoulli (k - 1) := begin cases k, { rw [nat.cast_zero, zero_mul, bernoulli_zero, derivative_one], }, { exact_mod_cast derivative_bernoulli_add_one k, } end @[simp] theorem sum_bernoulli (n : ℕ) : ∑ k in range (n + 1), ((n + 1).choose k : ℚ) • bernoulli k = monomial n (n + 1 : ℚ) := begin simp_rw [bernoulli_def, finset.smul_sum, finset.range_eq_Ico, ←finset.sum_Ico_Ico_comm, finset.sum_Ico_eq_sum_range], simp only [add_tsub_cancel_left, tsub_zero, zero_add, linear_map.map_add], simp_rw [smul_monomial, mul_comm (_root_.bernoulli _) _, smul_eq_mul, ←mul_assoc], conv_lhs { apply_congr, skip, conv { apply_congr, skip, rw [← nat.cast_mul, choose_mul ((le_tsub_iff_left $ mem_range_le H).1 $ mem_range_le H_1) (le.intro rfl), nat.cast_mul, add_comm x x_1, add_tsub_cancel_right, mul_assoc, mul_comm, ←smul_eq_mul, ←smul_monomial] }, rw [←sum_smul], }, rw [sum_range_succ_comm], simp only [add_right_eq_self, mul_one, cast_one, cast_add, add_tsub_cancel_left, choose_succ_self_right, one_smul, _root_.bernoulli_zero, sum_singleton, zero_add, linear_map.map_add, range_one], apply sum_eq_zero (λ x hx, _), have f : ∀ x ∈ range n, ¬ n + 1 - x = 1, { rintros x H, rw [mem_range] at H, rw [eq_comm], exact ne_of_lt (nat.lt_of_lt_of_le one_lt_two (le_tsub_of_add_le_left (succ_le_succ H))) }, rw [sum_bernoulli], have g : (ite (n + 1 - x = 1) (1 : ℚ) 0) = 0, { simp only [ite_eq_right_iff, one_ne_zero], intro h₁, exact (f x hx) h₁, }, rw [g, zero_smul], end /-- Another version of `polynomial.sum_bernoulli`. -/ lemma bernoulli_eq_sub_sum (n : ℕ) : (n.succ : ℚ) • bernoulli n = monomial n (n.succ : ℚ) - ∑ k in finset.range n, ((n + 1).choose k : ℚ) • bernoulli k := by rw [nat.cast_succ, ← sum_bernoulli n, sum_range_succ, add_sub_cancel', choose_succ_self_right, nat.cast_succ] /-- Another version of `bernoulli.sum_range_pow`. -/ lemma sum_range_pow_eq_bernoulli_sub (n p : ℕ) : (p + 1 : ℚ) * ∑ k in range n, (k : ℚ) ^ p = (bernoulli p.succ).eval n - (_root_.bernoulli p.succ) := begin rw [sum_range_pow, bernoulli_def, eval_finset_sum, ←sum_div, mul_div_cancel' _ _], { simp_rw [eval_monomial], symmetry, rw [←sum_flip _, sum_range_succ], simp only [tsub_self, tsub_zero, choose_zero_right, cast_one, mul_one, pow_zero, add_tsub_cancel_right], apply sum_congr rfl (λ x hx, _), apply congr_arg2 _ (congr_arg2 _ _ _) rfl, { rw nat.sub_sub_self (mem_range_le hx), }, { rw ←choose_symm (mem_range_le hx), }, }, { norm_cast, apply succ_ne_zero _, }, end /-- Rearrangement of `polynomial.sum_range_pow_eq_bernoulli_sub`. -/ lemma bernoulli_succ_eval (n p : ℕ) : (bernoulli p.succ).eval n = _root_.bernoulli (p.succ) + (p + 1 : ℚ) * ∑ k in range n, (k : ℚ) ^ p := by { apply eq_add_of_sub_eq', rw sum_range_pow_eq_bernoulli_sub, } lemma bernoulli_eval_one_add (n : ℕ) (x : ℚ) : (bernoulli n).eval (1 + x) = (bernoulli n).eval x + n * x^(n - 1) := begin apply nat.strong_induction_on n (λ d hd, _), have nz : ((d.succ : ℕ): ℚ) ≠ 0, { norm_cast, exact d.succ_ne_zero, }, apply (mul_right_inj' nz).1, rw [← smul_eq_mul, ←eval_smul, bernoulli_eq_sub_sum, mul_add, ←smul_eq_mul, ←eval_smul, bernoulli_eq_sub_sum, eval_sub, eval_finset_sum], conv_lhs { congr, skip, apply_congr, skip, rw [eval_smul, hd x_1 (mem_range.1 H)], }, rw [eval_sub, eval_finset_sum], simp_rw [eval_smul, smul_add], rw [sum_add_distrib, sub_add, sub_eq_sub_iff_sub_eq_sub, _root_.add_sub_sub_cancel], conv_rhs { congr, skip, congr, rw [succ_eq_add_one, ←choose_succ_self_right d], }, rw [nat.cast_succ, ← smul_eq_mul, ←sum_range_succ _ d, eval_monomial_one_add_sub], simp_rw [smul_eq_mul], end open power_series variables {A : Type*} [comm_ring A] [algebra ℚ A] -- TODO: define exponential generating functions, and use them here -- This name should probably be updated afterwards /-- The theorem that $(e^X - 1) * ∑ Bₙ(t)* X^n/n! = Xe^{tX}$ -/ theorem bernoulli_generating_function (t : A) : mk (λ n, aeval t ((1 / n! : ℚ) • bernoulli n)) * (exp A - 1) = power_series.X * rescale t (exp A) := begin -- check equality of power series by checking coefficients of X^n ext n, -- n = 0 case solved by `simp` cases n, { simp }, -- n ≥ 1, the coefficients is a sum to n+2, so use `sum_range_succ` to write as -- last term plus sum to n+1 rw [coeff_succ_X_mul, coeff_rescale, coeff_exp, power_series.coeff_mul, nat.sum_antidiagonal_eq_sum_range_succ_mk, sum_range_succ], -- last term is zero so kill with `add_zero` simp only [ring_hom.map_sub, tsub_self, constant_coeff_one, constant_coeff_exp, coeff_zero_eq_constant_coeff, mul_zero, sub_self, add_zero], -- Let's multiply both sides by (n+1)! (OK because it's a unit) have hnp1 : is_unit ((n+1)! : ℚ) := is_unit.mk0 _ (by exact_mod_cast factorial_ne_zero (n+1)), rw ←(hnp1.map (algebra_map ℚ A)).mul_right_inj, -- do trivial rearrangements to make RHS (n+1)*t^n rw [mul_left_comm, ←ring_hom.map_mul], change _ = t^n * algebra_map ℚ A (((n+1)*n! : ℕ)*(1/n!)), rw [cast_mul, mul_assoc, mul_one_div_cancel (show (n! : ℚ) ≠ 0, from cast_ne_zero.2 (factorial_ne_zero n)), mul_one, mul_comm (t^n), ← aeval_monomial, cast_add, cast_one], -- But this is the RHS of `sum_bernoulli_poly` rw [← sum_bernoulli, finset.mul_sum, alg_hom.map_sum], -- and now we have to prove a sum is a sum, but all the terms are equal. apply finset.sum_congr rfl, -- The rest is just trivialities, hampered by the fact that we're coercing -- factorials and binomial coefficients between ℕ and ℚ and A. intros i hi, -- deal with coefficients of e^X-1 simp only [nat.cast_choose ℚ (mem_range_le hi), coeff_mk, if_neg (mem_range_sub_ne_zero hi), one_div, alg_hom.map_smul, power_series.coeff_one, coeff_exp, sub_zero, linear_map.map_sub, algebra.smul_mul_assoc, algebra.smul_def, mul_right_comm _ ((aeval t) _), ←mul_assoc, ← ring_hom.map_mul, succ_eq_add_one, ← polynomial.C_eq_algebra_map, polynomial.aeval_mul, polynomial.aeval_C], -- finally cancel the Bernoulli polynomial and the algebra_map congr', apply congr_arg, rw [mul_assoc, div_eq_mul_inv, ← mul_inv], end end polynomial
472924306b5166f7eacb24857ad3367a8d4bc3e3
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/meta/mk_inhabited_instance_auto.lean
da1a8166a07d62d2f1ad838707439edf1fec9be8
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
632
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura Helper tactic for showing that a type is inhabited. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.meta.interactive_base import Mathlib.Lean3Lib.init.meta.contradiction_tactic import Mathlib.Lean3Lib.init.meta.constructor_tactic import Mathlib.Lean3Lib.init.meta.injection_tactic import Mathlib.Lean3Lib.init.meta.relation_tactics namespace Mathlib namespace tactic /- Retrieve the name of the type we are building an inhabitant instance for. -/ end Mathlib
cb13eb64f1b0a5055fd7cb7156855349474aacd8
b7f22e51856f4989b970961f794f1c435f9b8f78
/hott/hit/trunc.hlean
f5730c1101c54b23fd28a654beb3a3e100be97c8
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
5,678
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn n-truncation of types. Ported from Coq HoTT -/ /- The hit n-truncation is primitive, declared in init.hit. -/ import types.sigma types.pointed open is_trunc eq equiv is_equiv function prod sum sigma namespace trunc protected definition elim {n : trunc_index} {A : Type} {P : Type} [Pt : is_trunc n P] (H : A → P) : trunc n A → P := trunc.rec H protected definition elim_on {n : trunc_index} {A : Type} {P : Type} (aa : trunc n A) [Pt : is_trunc n P] (H : A → P) : P := trunc.elim H aa end trunc attribute trunc.elim_on [unfold 4] attribute trunc.rec [recursor 6] attribute trunc.elim [recursor 6] [unfold 6] namespace trunc variables {X Y Z : Type} {P : X → Type} (n : trunc_index) (A B : Type) local attribute is_trunc_eq [instance] variables {A n} definition untrunc_of_is_trunc [reducible] [H : is_trunc n A] : trunc n A → A := trunc.rec id variables (A n) definition is_equiv_tr [instance] [constructor] [H : is_trunc n A] : is_equiv (@tr n A) := adjointify _ (untrunc_of_is_trunc) (λaa, trunc.rec_on aa (λa, idp)) (λa, idp) definition trunc_equiv [constructor] [H : is_trunc n A] : trunc n A ≃ A := (equiv.mk tr _)⁻¹ᵉ definition is_trunc_of_is_equiv_tr [H : is_equiv (@tr n A)] : is_trunc n A := is_trunc_is_equiv_closed n (@tr n _)⁻¹ /- Functoriality -/ definition trunc_functor [unfold 5] (f : X → Y) : trunc n X → trunc n Y := λxx, trunc.rec_on xx (λx, tr (f x)) definition trunc_functor_compose [unfold 7] (f : X → Y) (g : Y → Z) : trunc_functor n (g ∘ f) ~ trunc_functor n g ∘ trunc_functor n f := λxx, trunc.rec_on xx (λx, idp) definition trunc_functor_id : trunc_functor n (@id A) ~ id := λxx, trunc.rec_on xx (λx, idp) definition trunc_functor_cast {X Y : Type} (n : ℕ₋₂) (p : X = Y) : trunc_functor n (cast p) ~ cast (ap (trunc n) p) := begin intro x, induction x with x, esimp, exact fn_tr_eq_tr_fn p (λy, tr) x ⬝ !tr_compose end definition is_equiv_trunc_functor [constructor] (f : X → Y) [H : is_equiv f] : is_equiv (trunc_functor n f) := adjointify _ (trunc_functor n f⁻¹) (λyy, trunc.rec_on yy (λy, ap tr !right_inv)) (λxx, trunc.rec_on xx (λx, ap tr !left_inv)) definition trunc_homotopy {f g : X → Y} (p : f ~ g) : trunc_functor n f ~ trunc_functor n g := λxx, trunc.rec_on xx (λx, ap tr (p x)) section definition trunc_equiv_trunc [constructor] (f : X ≃ Y) : trunc n X ≃ trunc n Y := equiv.mk _ (is_equiv_trunc_functor n f) end section open prod.ops definition trunc_prod_equiv [constructor] : trunc n (X × Y) ≃ trunc n X × trunc n Y := begin fapply equiv.MK, {exact (λpp, trunc.rec_on pp (λp, (tr p.1, tr p.2)))}, {intro p, cases p with xx yy, apply (trunc.rec_on xx), intro x, apply (trunc.rec_on yy), intro y, exact (tr (x,y))}, {intro p, cases p with xx yy, apply (trunc.rec_on xx), intro x, apply (trunc.rec_on yy), intro y, apply idp}, {intro pp, apply (trunc.rec_on pp), intro p, cases p, apply idp} end end /- Propositional truncation -/ definition ttrunc [constructor] (n : ℕ₋₂) (X : Type) : n-Type := trunctype.mk (trunc n X) _ -- should this live in Prop? definition merely [reducible] [constructor] (A : Type) : Prop := ttrunc -1 A notation `||`:max A `||`:0 := merely A notation `∥`:max A `∥`:0 := merely A definition Exists [reducible] [constructor] (P : X → Type) : Prop := ∥ sigma P ∥ definition or [reducible] [constructor] (A B : Type) : Prop := ∥ A ⊎ B ∥ notation `exists` binders `,` r:(scoped P, Exists P) := r notation `∃` binders `,` r:(scoped P, Exists P) := r notation A ` \/ ` B := or A B notation A ∨ B := or A B definition merely.intro [reducible] [constructor] (a : A) : ∥ A ∥ := tr a definition exists.intro [reducible] [constructor] (x : X) (p : P x) : ∃x, P x := tr ⟨x, p⟩ definition or.intro_left [reducible] [constructor] (x : X) : X ∨ Y := tr (inl x) definition or.intro_right [reducible] [constructor] (y : Y) : X ∨ Y := tr (inr y) definition is_contr_of_merely_prop [H : is_prop A] (aa : merely A) : is_contr A := is_contr_of_inhabited_prop (trunc.rec_on aa id) section open sigma.ops definition trunc_sigma_equiv [constructor] : trunc n (Σ x, P x) ≃ trunc n (Σ x, trunc n (P x)) := equiv.MK (λpp, trunc.rec_on pp (λp, tr ⟨p.1, tr p.2⟩)) (λpp, trunc.rec_on pp (λp, trunc.rec_on p.2 (λb, tr ⟨p.1, b⟩))) (λpp, trunc.rec_on pp (λp, sigma.rec_on p (λa bb, trunc.rec_on bb (λb, by esimp)))) (λpp, trunc.rec_on pp (λp, sigma.rec_on p (λa b, by esimp))) definition trunc_sigma_equiv_of_is_trunc [H : is_trunc n X] : trunc n (Σ x, P x) ≃ Σ x, trunc n (P x) := calc trunc n (Σ x, P x) ≃ trunc n (Σ x, trunc n (P x)) : trunc_sigma_equiv ... ≃ Σ x, trunc n (P x) : !trunc_equiv end /- the (non-dependent) universal property -/ definition trunc_arrow_equiv [constructor] [H : is_trunc n B] : (trunc n A → B) ≃ (A → B) := begin fapply equiv.MK, { intro g a, exact g (tr a)}, { intro f x, exact trunc.rec_on x f}, { intro f, apply eq_of_homotopy, intro a, reflexivity}, { intro g, apply eq_of_homotopy, intro x, exact trunc.rec_on x (λa, idp)}, end end trunc
d5e4acc45eee56dba55bfee296aa82b4714223bb
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/ring_theory/witt_vector/truncated.lean
28a88b8f8070b24b5f70ec2dae137e819889e8fd
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
15,803
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Robert Y. Lewis -/ import ring_theory.witt_vector.init_tail /-! # Truncated Witt vectors > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. The ring of truncated Witt vectors (of length `n`) is a quotient of the ring of Witt vectors. It retains the first `n` coefficients of each Witt vector. In this file, we set up the basic quotient API for this ring. The ring of Witt vectors is the projective limit of all the rings of truncated Witt vectors. ## Main declarations - `truncated_witt_vector`: the underlying type of the ring of truncated Witt vectors - `truncated_witt_vector.comm_ring`: the ring structure on truncated Witt vectors - `witt_vector.truncate`: the quotient homomorphism that truncates a Witt vector, to obtain a truncated Witt vector - `truncated_witt_vector.truncate`: the homomorphism that truncates a truncated Witt vector of length `n` to one of length `m` (for some `m ≤ n`) - `witt_vector.lift`: the unique ring homomorphism into the ring of Witt vectors that is compatible with a family of ring homomorphisms to the truncated Witt vectors: this realizes the ring of Witt vectors as projective limit of the rings of truncated Witt vectors ## References * [Hazewinkel, *Witt Vectors*][Haze09] * [Commelin and Lewis, *Formalizing the Ring of Witt Vectors*][CL21] -/ open function (injective surjective) noncomputable theory variables {p : ℕ} [hp : fact p.prime] (n : ℕ) (R : Type*) local notation `𝕎` := witt_vector p -- type as `\bbW` /-- A truncated Witt vector over `R` is a vector of elements of `R`, i.e., the first `n` coefficients of a Witt vector. We will define operations on this type that are compatible with the (untruncated) Witt vector operations. `truncated_witt_vector p n R` takes a parameter `p : ℕ` that is not used in the definition. In practice, this number `p` is assumed to be a prime number, and under this assumption we construct a ring structure on `truncated_witt_vector p n R`. (`truncated_witt_vector p₁ n R` and `truncated_witt_vector p₂ n R` are definitionally equal as types but will have different ring operations.) -/ @[nolint unused_arguments] def truncated_witt_vector (p : ℕ) (n : ℕ) (R : Type*) := fin n → R instance (p n : ℕ) (R : Type*) [inhabited R] : inhabited (truncated_witt_vector p n R) := ⟨λ _, default⟩ variables {n R} namespace truncated_witt_vector variables (p) /-- Create a `truncated_witt_vector` from a vector `x`. -/ def mk (x : fin n → R) : truncated_witt_vector p n R := x variables {p} /-- `x.coeff i` is the `i`th entry of `x`. -/ def coeff (i : fin n) (x : truncated_witt_vector p n R) : R := x i @[ext] lemma ext {x y : truncated_witt_vector p n R} (h : ∀ i, x.coeff i = y.coeff i) : x = y := funext h lemma ext_iff {x y : truncated_witt_vector p n R} : x = y ↔ ∀ i, x.coeff i = y.coeff i := ⟨λ h i, by rw h, ext⟩ @[simp] lemma coeff_mk (x : fin n → R) (i : fin n) : (mk p x).coeff i = x i := rfl @[simp] lemma mk_coeff (x : truncated_witt_vector p n R) : mk p (λ i, x.coeff i) = x := by { ext i, rw [coeff_mk] } variable [comm_ring R] /-- We can turn a truncated Witt vector `x` into a Witt vector by setting all coefficients after `x` to be 0. -/ def out (x : truncated_witt_vector p n R) : 𝕎 R := witt_vector.mk p $ λ i, if h : i < n then x.coeff ⟨i, h⟩ else 0 @[simp] lemma coeff_out (x : truncated_witt_vector p n R) (i : fin n) : x.out.coeff i = x.coeff i := by rw [out, witt_vector.coeff_mk, dif_pos i.is_lt, fin.eta] lemma out_injective : injective (@out p n R _) := begin intros x y h, ext i, rw [witt_vector.ext_iff] at h, simpa only [coeff_out] using h ↑i end end truncated_witt_vector namespace witt_vector variables {p} (n) section /-- `truncate_fun n x` uses the first `n` entries of `x` to construct a `truncated_witt_vector`, which has the same base `p` as `x`. This function is bundled into a ring homomorphism in `witt_vector.truncate` -/ def truncate_fun (x : 𝕎 R) : truncated_witt_vector p n R := truncated_witt_vector.mk p $ λ i, x.coeff i end variables {n} @[simp] lemma coeff_truncate_fun (x : 𝕎 R) (i : fin n) : (truncate_fun n x).coeff i = x.coeff i := by rw [truncate_fun, truncated_witt_vector.coeff_mk] variable [comm_ring R] @[simp] lemma out_truncate_fun (x : 𝕎 R) : (truncate_fun n x).out = init n x := begin ext i, dsimp [truncated_witt_vector.out, init, select], split_ifs with hi, swap, { refl }, rw [coeff_truncate_fun, fin.coe_mk], end end witt_vector namespace truncated_witt_vector variable [comm_ring R] @[simp] lemma truncate_fun_out (x : truncated_witt_vector p n R) : x.out.truncate_fun n = x := by simp only [witt_vector.truncate_fun, coeff_out, mk_coeff] open witt_vector variables (p n R) include hp instance : has_zero (truncated_witt_vector p n R) := ⟨truncate_fun n 0⟩ instance : has_one (truncated_witt_vector p n R) := ⟨truncate_fun n 1⟩ instance : has_nat_cast (truncated_witt_vector p n R) := ⟨λ i, truncate_fun n i⟩ instance : has_int_cast (truncated_witt_vector p n R) := ⟨λ i, truncate_fun n i⟩ instance : has_add (truncated_witt_vector p n R) := ⟨λ x y, truncate_fun n (x.out + y.out)⟩ instance : has_mul (truncated_witt_vector p n R) := ⟨λ x y, truncate_fun n (x.out * y.out)⟩ instance : has_neg (truncated_witt_vector p n R) := ⟨λ x, truncate_fun n (- x.out)⟩ instance : has_sub (truncated_witt_vector p n R) := ⟨λ x y, truncate_fun n (x.out - y.out)⟩ instance has_nat_scalar : has_smul ℕ (truncated_witt_vector p n R) := ⟨λ m x, truncate_fun n (m • x.out)⟩ instance has_int_scalar : has_smul ℤ (truncated_witt_vector p n R) := ⟨λ m x, truncate_fun n (m • x.out)⟩ instance has_nat_pow : has_pow (truncated_witt_vector p n R) ℕ := ⟨λ x m, truncate_fun n (x.out ^ m)⟩ @[simp] lemma coeff_zero (i : fin n) : (0 : truncated_witt_vector p n R).coeff i = 0 := begin show coeff i (truncate_fun _ 0 : truncated_witt_vector p n R) = 0, rw [coeff_truncate_fun, witt_vector.zero_coeff], end end truncated_witt_vector /-- A macro tactic used to prove that `truncate_fun` respects ring operations. -/ meta def tactic.interactive.witt_truncate_fun_tac : tactic unit := `[show _ = truncate_fun n _, apply truncated_witt_vector.out_injective, iterate { rw [out_truncate_fun] }] namespace witt_vector variables (p n R) variable [comm_ring R] lemma truncate_fun_surjective : surjective (@truncate_fun p n R) := function.right_inverse.surjective truncated_witt_vector.truncate_fun_out include hp @[simp] lemma truncate_fun_zero : truncate_fun n (0 : 𝕎 R) = 0 := rfl @[simp] lemma truncate_fun_one : truncate_fun n (1 : 𝕎 R) = 1 := rfl variables {p R} @[simp] lemma truncate_fun_add (x y : 𝕎 R) : truncate_fun n (x + y) = truncate_fun n x + truncate_fun n y := by { witt_truncate_fun_tac, rw init_add } @[simp] lemma truncate_fun_mul (x y : 𝕎 R) : truncate_fun n (x * y) = truncate_fun n x * truncate_fun n y := by { witt_truncate_fun_tac, rw init_mul } lemma truncate_fun_neg (x : 𝕎 R) : truncate_fun n (-x) = -truncate_fun n x := by { witt_truncate_fun_tac, rw init_neg } lemma truncate_fun_sub (x y : 𝕎 R) : truncate_fun n (x - y) = truncate_fun n x - truncate_fun n y := by { witt_truncate_fun_tac, rw init_sub } lemma truncate_fun_nsmul (x : 𝕎 R) (m : ℕ) : truncate_fun n (m • x) = m • truncate_fun n x := by { witt_truncate_fun_tac, rw init_nsmul } lemma truncate_fun_zsmul (x : 𝕎 R) (m : ℤ) : truncate_fun n (m • x) = m • truncate_fun n x := by { witt_truncate_fun_tac, rw init_zsmul } lemma truncate_fun_pow (x : 𝕎 R) (m : ℕ) : truncate_fun n (x ^ m) = truncate_fun n x ^ m := by { witt_truncate_fun_tac, rw init_pow } lemma truncate_fun_nat_cast (m : ℕ) : truncate_fun n (m : 𝕎 R) = m := rfl lemma truncate_fun_int_cast (m : ℤ) : truncate_fun n (m : 𝕎 R) = m := rfl end witt_vector namespace truncated_witt_vector open witt_vector variables (p n R) variable [comm_ring R] include hp instance : comm_ring (truncated_witt_vector p n R) := (truncate_fun_surjective p n R).comm_ring _ (truncate_fun_zero p n R) (truncate_fun_one p n R) (truncate_fun_add n) (truncate_fun_mul n) (truncate_fun_neg n) (truncate_fun_sub n) (truncate_fun_nsmul n) (truncate_fun_zsmul n) (truncate_fun_pow n) (truncate_fun_nat_cast n) (truncate_fun_int_cast n) end truncated_witt_vector namespace witt_vector open truncated_witt_vector variables (n) variable [comm_ring R] include hp /-- `truncate n` is a ring homomorphism that truncates `x` to its first `n` entries to obtain a `truncated_witt_vector`, which has the same base `p` as `x`. -/ noncomputable! def truncate : 𝕎 R →+* truncated_witt_vector p n R := { to_fun := truncate_fun n, map_zero' := truncate_fun_zero p n R, map_add' := truncate_fun_add n, map_one' := truncate_fun_one p n R, map_mul' := truncate_fun_mul n } variables (p n R) lemma truncate_surjective : surjective (truncate n : 𝕎 R → truncated_witt_vector p n R) := truncate_fun_surjective p n R variables {p n R} @[simp] lemma coeff_truncate (x : 𝕎 R) (i : fin n) : (truncate n x).coeff i = x.coeff i := coeff_truncate_fun _ _ variables (n) lemma mem_ker_truncate (x : 𝕎 R) : x ∈ (@truncate p _ n R _).ker ↔ ∀ i < n, x.coeff i = 0 := begin simp only [ring_hom.mem_ker, truncate, truncate_fun, ring_hom.coe_mk, truncated_witt_vector.ext_iff, truncated_witt_vector.coeff_mk, coeff_zero], exact fin.forall_iff end variables (p) @[simp] lemma truncate_mk (f : ℕ → R) : truncate n (mk p f) = truncated_witt_vector.mk _ (λ k, f k) := begin ext i, rw [coeff_truncate, coeff_mk, truncated_witt_vector.coeff_mk], end end witt_vector namespace truncated_witt_vector variable [comm_ring R] include hp /-- A ring homomorphism that truncates a truncated Witt vector of length `m` to a truncated Witt vector of length `n`, for `n ≤ m`. -/ def truncate {m : ℕ} (hm : n ≤ m) : truncated_witt_vector p m R →+* truncated_witt_vector p n R := ring_hom.lift_of_right_inverse (witt_vector.truncate m) out truncate_fun_out ⟨witt_vector.truncate n, begin intro x, simp only [witt_vector.mem_ker_truncate], intros h i hi, exact h i (lt_of_lt_of_le hi hm) end⟩ @[simp] lemma truncate_comp_witt_vector_truncate {m : ℕ} (hm : n ≤ m) : (@truncate p _ n R _ m hm).comp (witt_vector.truncate m) = witt_vector.truncate n := ring_hom.lift_of_right_inverse_comp _ _ _ _ @[simp] lemma truncate_witt_vector_truncate {m : ℕ} (hm : n ≤ m) (x : 𝕎 R) : truncate hm (witt_vector.truncate m x) = witt_vector.truncate n x := ring_hom.lift_of_right_inverse_comp_apply _ _ _ _ _ @[simp] lemma truncate_truncate {n₁ n₂ n₃ : ℕ} (h1 : n₁ ≤ n₂) (h2 : n₂ ≤ n₃) (x : truncated_witt_vector p n₃ R) : (truncate h1) (truncate h2 x) = truncate (h1.trans h2) x := begin obtain ⟨x, rfl⟩ := witt_vector.truncate_surjective p n₃ R x, simp only [truncate_witt_vector_truncate], end @[simp] lemma truncate_comp {n₁ n₂ n₃ : ℕ} (h1 : n₁ ≤ n₂) (h2 : n₂ ≤ n₃) : (@truncate p _ _ R _ _ h1).comp (truncate h2) = truncate (h1.trans h2) := begin ext1 x, simp only [truncate_truncate, function.comp_app, ring_hom.coe_comp] end lemma truncate_surjective {m : ℕ} (hm : n ≤ m) : surjective (@truncate p _ _ R _ _ hm) := begin intro x, obtain ⟨x, rfl⟩ := witt_vector.truncate_surjective p _ R x, exact ⟨witt_vector.truncate _ x, truncate_witt_vector_truncate _ _⟩ end @[simp] lemma coeff_truncate {m : ℕ} (hm : n ≤ m) (i : fin n) (x : truncated_witt_vector p m R) : (truncate hm x).coeff i = x.coeff (fin.cast_le hm i) := begin obtain ⟨y, rfl⟩ := witt_vector.truncate_surjective p _ _ x, simp only [truncate_witt_vector_truncate, witt_vector.coeff_truncate, fin.coe_cast_le], end section fintype omit hp instance {R : Type*} [fintype R] : fintype (truncated_witt_vector p n R) := pi.fintype variables (p n R) lemma card {R : Type*} [fintype R] : fintype.card (truncated_witt_vector p n R) = fintype.card R ^ n := by simp only [truncated_witt_vector, fintype.card_fin, fintype.card_fun] end fintype lemma infi_ker_truncate : (⨅ i : ℕ, (@witt_vector.truncate p _ i R _).ker) = ⊥ := begin rw [submodule.eq_bot_iff], intros x hx, ext, simp only [witt_vector.mem_ker_truncate, ideal.mem_infi, witt_vector.zero_coeff] at hx ⊢, exact hx _ _ (nat.lt_succ_self _) end end truncated_witt_vector namespace witt_vector open truncated_witt_vector (hiding truncate coeff) section lift variable [comm_ring R] variables {S : Type*} [semiring S] variable (f : Π k : ℕ, S →+* truncated_witt_vector p k R) variable f_compat : ∀ (k₁ k₂ : ℕ) (hk : k₁ ≤ k₂), (truncated_witt_vector.truncate hk).comp (f k₂) = f k₁ variables {p R} variable (n) /-- Given a family `fₖ : S → truncated_witt_vector p k R` and `s : S`, we produce a Witt vector by defining the `k`th entry to be the final entry of `fₖ s`. -/ def lift_fun (s : S) : 𝕎 R := witt_vector.mk p $ λ k, truncated_witt_vector.coeff (fin.last k) (f (k+1) s) variables {f} include f_compat @[simp] lemma truncate_lift_fun (s : S) : witt_vector.truncate n (lift_fun f s) = f n s := begin ext i, simp only [lift_fun, truncated_witt_vector.coeff_mk, witt_vector.truncate_mk], rw [← f_compat (i+1) n i.is_lt, ring_hom.comp_apply, truncated_witt_vector.coeff_truncate], -- this is a bit unfortunate congr' with _, simp only [fin.coe_last, fin.coe_cast_le], end variable (f) /-- Given compatible ring homs from `S` into `truncated_witt_vector n` for each `n`, we can lift these to a ring hom `S → 𝕎 R`. `lift` defines the universal property of `𝕎 R` as the inverse limit of `truncated_witt_vector n`. -/ def lift : S →+* 𝕎 R := by refine_struct { to_fun := lift_fun f }; { intros, rw [← sub_eq_zero, ← ideal.mem_bot, ← infi_ker_truncate, ideal.mem_infi], simp [ring_hom.mem_ker, f_compat] } variable {f} @[simp] lemma truncate_lift (s : S) : witt_vector.truncate n (lift _ f_compat s) = f n s := truncate_lift_fun _ f_compat s @[simp] lemma truncate_comp_lift : (witt_vector.truncate n).comp (lift _ f_compat) = f n := by { ext1, rw [ring_hom.comp_apply, truncate_lift] } /-- The uniqueness part of the universal property of `𝕎 R`. -/ lemma lift_unique (g : S →+* 𝕎 R) (g_compat : ∀ k, (witt_vector.truncate k).comp g = f k) : lift _ f_compat = g := begin ext1 x, rw [← sub_eq_zero, ← ideal.mem_bot, ← infi_ker_truncate, ideal.mem_infi], intro i, simp only [ring_hom.mem_ker, g_compat, ←ring_hom.comp_apply, truncate_comp_lift, ring_hom.map_sub, sub_self], end omit f_compat include hp /-- The universal property of `𝕎 R` as projective limit of truncated Witt vector rings. -/ @[simps] def lift_equiv : {f : Π k, S →+* truncated_witt_vector p k R // ∀ k₁ k₂ (hk : k₁ ≤ k₂), (truncated_witt_vector.truncate hk).comp (f k₂) = f k₁} ≃ (S →+* 𝕎 R) := { to_fun := λ f, lift f.1 f.2, inv_fun := λ g, ⟨λ k, (truncate k).comp g, by { intros _ _ h, simp only [←ring_hom.comp_assoc, truncate_comp_witt_vector_truncate] }⟩, left_inv := by { rintro ⟨f, hf⟩, simp only [truncate_comp_lift] }, right_inv := λ g, lift_unique _ _ $ λ _, rfl } lemma hom_ext (g₁ g₂ : S →+* 𝕎 R) (h : ∀ k, (truncate k).comp g₁ = (truncate k).comp g₂) : g₁ = g₂ := lift_equiv.symm.injective $ subtype.ext $ funext h end lift end witt_vector
244c4463cc390f6fb7d7d27c348415aa41dad43b
1dd482be3f611941db7801003235dc84147ec60a
/src/ring_theory/polynomial.lean
f59d0f4fcddc2b6e3b0bdd8894b4d7a2799fce20
[ "Apache-2.0" ]
permissive
sanderdahmen/mathlib
479039302bd66434bb5672c2a4cecf8d69981458
8f0eae75cd2d8b7a083cf935666fcce4565df076
refs/heads/master
1,587,491,322,775
1,549,672,060,000
1,549,672,060,000
169,748,224
0
0
Apache-2.0
1,549,636,694,000
1,549,636,694,000
null
UTF-8
Lean
false
false
9,143
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau Hilbert basis theorem: if a ring is noetherian then so is its polynomial ring. -/ import linear_algebra.multivariate_polynomial import data.polynomial import ring_theory.principal_ideal_domain import ring_theory.subring universes u v w namespace polynomial variables (R : Type u) [comm_ring R] [decidable_eq R] /-- The `R`-submodule of `R[X]` consisting of polynomials of degree ≤ `n`. -/ def degree_le (n : with_bot ℕ) : submodule R (polynomial R) := ⨅ k : ℕ, ⨅ h : ↑k > n, (lcoeff R k).ker variable {R} theorem mem_degree_le {n : with_bot ℕ} {f : polynomial R} : f ∈ degree_le R n ↔ degree f ≤ n := by simp only [degree_le, submodule.mem_infi, degree_le_iff_coeff_zero, linear_map.mem_ker]; refl theorem degree_le_mono {m n : with_bot ℕ} (H : m ≤ n): degree_le R m ≤ degree_le R n := λ f hf, mem_degree_le.2 (le_trans (mem_degree_le.1 hf) H) theorem degree_le_eq_span_X_pow {n : ℕ} : degree_le R n = submodule.span R ↑((finset.range (n+1)).image (λ n, X^n) : finset (polynomial R)) := begin apply le_antisymm, { intros p hp, replace hp := mem_degree_le.1 hp, rw [← finsupp.sum_single p, finsupp.sum, submodule.mem_coe], refine submodule.sum_mem _ (λ k hk, _), have := with_bot.coe_le_coe.1 (finset.sup_le_iff.1 hp k hk), rw [single_eq_C_mul_X, C_mul'], refine submodule.smul_mem _ _ (submodule.subset_span $ finset.mem_coe.2 $ finset.mem_image.2 ⟨_, finset.mem_range.2 (nat.lt_succ_of_le this), rfl⟩) }, rw [submodule.span_le, finset.coe_image, set.image_subset_iff], intros k hk, apply mem_degree_le.2, apply le_trans (degree_X_pow_le _) (with_bot.coe_le_coe.2 $ nat.le_of_lt_succ $ finset.mem_range.1 hk) end end polynomial variables {R : Type u} [comm_ring R] [decidable_eq R] namespace ideal open polynomial /-- Transport an ideal of `R[X]` to an `R`-submodule of `R[X]`. -/ def of_polynomial (I : ideal (polynomial R)) : submodule R (polynomial R) := { carrier := I.carrier, zero := I.zero_mem, add := λ _ _, I.add_mem, smul := λ c x H, by rw [← C_mul']; exact submodule.smul_mem _ _ H } variables {I : ideal (polynomial R)} theorem mem_of_polynomial (x) : x ∈ I.of_polynomial ↔ x ∈ I := iff.rfl variables (I) /-- Given an ideal `I` of `R[X]`, make the `R`-submodule of `I` consisting of polynomials of degree ≤ `n`. -/ def degree_le (n : with_bot ℕ) : submodule R (polynomial R) := degree_le R n ⊓ I.of_polynomial /-- Given an ideal `I` of `R[X]`, make the ideal in `R` of leading coefficients of polynomials in `I` with degree ≤ `n`. -/ def leading_coeff_nth (n : ℕ) : ideal R := (I.degree_le n).map $ lcoeff R n theorem mem_leading_coeff_nth (n : ℕ) (x) : x ∈ I.leading_coeff_nth n ↔ ∃ p ∈ I, degree p ≤ n ∧ leading_coeff p = x := begin simp only [leading_coeff_nth, degree_le, submodule.mem_map, lcoeff_apply, submodule.mem_inf, mem_degree_le], split, { rintro ⟨p, ⟨hpdeg, hpI⟩, rfl⟩, cases lt_or_eq_of_le hpdeg with hpdeg hpdeg, { refine ⟨0, I.zero_mem, lattice.bot_le, _⟩, rw [leading_coeff_zero, eq_comm], exact coeff_eq_zero_of_degree_lt hpdeg }, { refine ⟨p, hpI, le_of_eq hpdeg, _⟩, rw [leading_coeff, nat_degree, hpdeg], refl } }, { rintro ⟨p, hpI, hpdeg, rfl⟩, have : nat_degree p + (n - nat_degree p) = n, { exact nat.add_sub_cancel' (nat_degree_le_of_degree_le hpdeg) }, refine ⟨p * X ^ (n - nat_degree p), ⟨_, I.mul_mem_right hpI⟩, _⟩, { apply le_trans (degree_mul_le _ _) _, apply le_trans (add_le_add' (degree_le_nat_degree) (degree_X_pow_le _)) _, rw [← with_bot.coe_add, this], exact le_refl _ }, { rw [leading_coeff, ← coeff_mul_X_pow p (n - nat_degree p), this] } } end theorem mem_leading_coeff_nth_zero (x) : x ∈ I.leading_coeff_nth 0 ↔ C x ∈ I := (mem_leading_coeff_nth _ _ _).trans ⟨λ ⟨p, hpI, hpdeg, hpx⟩, by rwa [← hpx, leading_coeff, nat.eq_zero_of_le_zero (nat_degree_le_of_degree_le hpdeg), ← eq_C_of_degree_le_zero hpdeg], λ hx, ⟨C x, hx, degree_C_le, leading_coeff_C x⟩⟩ theorem leading_coeff_nth_mono {m n : ℕ} (H : m ≤ n) : I.leading_coeff_nth m ≤ I.leading_coeff_nth n := begin intros r hr, simp only [submodule.mem_coe, mem_leading_coeff_nth] at hr ⊢, rcases hr with ⟨p, hpI, hpdeg, rfl⟩, refine ⟨p * X ^ (n - m), I.mul_mem_right hpI, _, leading_coeff_mul_X_pow⟩, refine le_trans (degree_mul_le _ _) _, refine le_trans (add_le_add' hpdeg (degree_X_pow_le _)) _, rw [← with_bot.coe_add, nat.add_sub_cancel' H], exact le_refl _ end /-- Given an ideal `I` in `R[X]`, make the ideal in `R` of the leading coefficients in `I`. -/ def leading_coeff : ideal R := ⨆ n : ℕ, I.leading_coeff_nth n theorem mem_leading_coeff (x) : x ∈ I.leading_coeff ↔ ∃ p ∈ I, polynomial.leading_coeff p = x := begin rw [leading_coeff, submodule.mem_supr_of_directed], simp only [mem_leading_coeff_nth], { split, { rintro ⟨i, p, hpI, hpdeg, rfl⟩, exact ⟨p, hpI, rfl⟩ }, rintro ⟨p, hpI, rfl⟩, exact ⟨nat_degree p, p, hpI, degree_le_nat_degree, rfl⟩ }, { exact ⟨0⟩ }, intros i j, exact ⟨i + j, I.leading_coeff_nth_mono (nat.le_add_right _ _), I.leading_coeff_nth_mono (nat.le_add_left _ _)⟩ end theorem is_fg_degree_le [is_noetherian_ring R] (n : ℕ) : submodule.fg (I.degree_le n) := is_noetherian_submodule_left.1 (is_noetherian_of_fg_of_noetherian _ ⟨_, degree_le_eq_span_X_pow.symm⟩) _ end ideal /-- Hilbert basis theorem. -/ theorem is_noetherian_ring_polynomial [is_noetherian_ring R] : is_noetherian_ring (polynomial R) := ⟨assume I : ideal (polynomial R), let L := I.leading_coeff in let M := well_founded.min (is_noetherian_iff_well_founded.1 (by apply_instance)) (set.range I.leading_coeff_nth) (set.ne_empty_of_mem ⟨0, rfl⟩) in have hm : M ∈ set.range I.leading_coeff_nth := well_founded.min_mem _ _ _, let ⟨N, HN⟩ := hm, ⟨s, hs⟩ := I.is_fg_degree_le N in have hm2 : ∀ k, I.leading_coeff_nth k ≤ M := λ k, or.cases_on (le_or_lt k N) (λ h, HN ▸ I.leading_coeff_nth_mono h) (λ h x hx, classical.by_contradiction $ λ hxm, have ¬M < I.leading_coeff_nth k, by refine well_founded.not_lt_min well_founded_submodule_gt _ _ _; exact ⟨k, rfl⟩, this ⟨HN ▸ I.leading_coeff_nth_mono (le_of_lt h), λ H, hxm (H hx)⟩), have hs2 : ∀ {x}, x ∈ I.degree_le N → x ∈ ideal.span (↑s : set (polynomial R)), from hs ▸ λ x hx, submodule.span_induction hx (λ _ hx, ideal.subset_span hx) (ideal.zero_mem _) (λ _ _, ideal.add_mem _) (λ c f hf, f.C_mul' c ▸ ideal.mul_mem_left _ hf), ⟨s, le_antisymm (ideal.span_le.2 $ λ x hx, have x ∈ I.degree_le N, from hs ▸ submodule.subset_span hx, this.2) $ begin change I ≤ ideal.span ↑s, intros p hp, generalize hn : p.nat_degree = k, induction k using nat.strong_induction_on with k ih generalizing p, cases le_or_lt k N, { subst k, refine hs2 ⟨polynomial.mem_degree_le.2 (le_trans polynomial.degree_le_nat_degree $ with_bot.coe_le_coe.2 h), hp⟩ }, { have hp0 : p ≠ 0, { rintro rfl, cases hn, exact nat.not_lt_zero _ h }, have : (0 : R) ≠ 1, { intro h, apply hp0, ext i, refine (mul_one _).symm.trans _, rw [← h, mul_zero], refl }, letI : nonzero_comm_ring R := { zero_ne_one := this, ..(infer_instance : comm_ring R) }, have : p.leading_coeff ∈ I.leading_coeff_nth N, { rw HN, exact hm2 k ((I.mem_leading_coeff_nth _ _).2 ⟨_, hp, hn ▸ polynomial.degree_le_nat_degree, rfl⟩) }, rw I.mem_leading_coeff_nth at this, rcases this with ⟨q, hq, hdq, hlqp⟩, have hq0 : q ≠ 0, { intro H, rw [← polynomial.leading_coeff_eq_zero] at H, rw [hlqp, polynomial.leading_coeff_eq_zero] at H, exact hp0 H }, have h1 : p.degree = (q * polynomial.X ^ (k - q.nat_degree)).degree, { rw [polynomial.degree_mul_eq', polynomial.degree_X_pow], rw [polynomial.degree_eq_nat_degree hp0, polynomial.degree_eq_nat_degree hq0], rw [← with_bot.coe_add, nat.add_sub_cancel', hn], { refine le_trans (polynomial.nat_degree_le_of_degree_le hdq) (le_of_lt h) }, rw [polynomial.leading_coeff_X_pow, mul_one], exact mt polynomial.leading_coeff_eq_zero.1 hq0 }, have h2 : p.leading_coeff = (q * polynomial.X ^ (k - q.nat_degree)).leading_coeff, { rw [← hlqp, polynomial.leading_coeff_mul_X_pow] }, have := polynomial.degree_sub_lt h1 hp0 h2, rw [polynomial.degree_eq_nat_degree hp0] at this, rw ← sub_add_cancel p (q * polynomial.X ^ (k - q.nat_degree)), refine (ideal.span ↑s).add_mem _ ((ideal.span ↑s).mul_mem_right _), { by_cases hpq : p - q * polynomial.X ^ (k - q.nat_degree) = 0, { rw hpq, exact ideal.zero_mem _ }, refine ih _ _ (I.sub_mem hp (I.mul_mem_right hq)) rfl, rwa [polynomial.degree_eq_nat_degree hpq, with_bot.coe_lt_coe, hn] at this }, exact hs2 ⟨polynomial.mem_degree_le.2 hdq, hq⟩ } end⟩⟩
5e0696d8c82299ce51eae100991f30891c0f0d57
9dc8cecdf3c4634764a18254e94d43da07142918
/src/deprecated/subfield.lean
e6029b971b9a0e242dc6ee1195889dc25c990ce7
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
6,158
lean
/- Copyright (c) 2018 Andreas Swerdlow. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andreas Swerdlow -/ import deprecated.subring import algebra.group_with_zero.power /-! # Unbundled subfields (deprecated) This file is deprecated, and is no longer imported by anything in mathlib other than other deprecated files, and test files. You should not need to import it. This file defines predicates for unbundled subfields. Instead of using this file, please use `subfield`, defined in `field_theory.subfield`, for subfields of fields. ## Main definitions `is_subfield (S : set F) : Prop` : the predicate that `S` is the underlying set of a subfield of the field `F`. The bundled variant `subfield F` should be used in preference to this. ## Tags is_subfield -/ variables {F : Type*} [field F] (S : set F) /-- `is_subfield (S : set F)` is the predicate saying that a given subset of a field is the set underlying a subfield. This structure is deprecated; use the bundled variant `subfield F` to model subfields of a field. -/ structure is_subfield extends is_subring S : Prop := (inv_mem : ∀ {x : F}, x ∈ S → x⁻¹ ∈ S) lemma is_subfield.div_mem {S : set F} (hS : is_subfield S) {x y : F} (hx : x ∈ S) (hy : y ∈ S) : x / y ∈ S := by { rw div_eq_mul_inv, exact hS.to_is_subring.to_is_submonoid.mul_mem hx (hS.inv_mem hy) } lemma is_subfield.pow_mem {a : F} {n : ℤ} {s : set F} (hs : is_subfield s) (h : a ∈ s) : a ^ n ∈ s := begin cases n, { rw zpow_of_nat, exact hs.to_is_subring.to_is_submonoid.pow_mem h }, { rw zpow_neg_succ_of_nat, exact hs.inv_mem (hs.to_is_subring.to_is_submonoid.pow_mem h) }, end lemma univ.is_subfield : is_subfield (@set.univ F) := { inv_mem := by intros; trivial, ..univ.is_submonoid, ..is_add_subgroup.univ_add_subgroup } lemma preimage.is_subfield {K : Type*} [field K] (f : F →+* K) {s : set K} (hs : is_subfield s) : is_subfield (f ⁻¹' s) := { inv_mem := λ a (ha : f a ∈ s), show f a⁻¹ ∈ s, by { rw [map_inv₀], exact hs.inv_mem ha }, ..f.is_subring_preimage hs.to_is_subring } lemma image.is_subfield {K : Type*} [field K] (f : F →+* K) {s : set F} (hs : is_subfield s) : is_subfield (f '' s) := { inv_mem := λ a ⟨x, xmem, ha⟩, ⟨x⁻¹, hs.inv_mem xmem, ha ▸ map_inv₀ f _⟩, ..f.is_subring_image hs.to_is_subring } lemma range.is_subfield {K : Type*} [field K] (f : F →+* K) : is_subfield (set.range f) := by { rw ← set.image_univ, apply image.is_subfield _ univ.is_subfield } namespace field /-- `field.closure s` is the minimal subfield that includes `s`. -/ def closure : set F := { x | ∃ y ∈ ring.closure S, ∃ z ∈ ring.closure S, y / z = x } variables {S} theorem ring_closure_subset : ring.closure S ⊆ closure S := λ x hx, ⟨x, hx, 1, ring.closure.is_subring.to_is_submonoid.one_mem, div_one x⟩ lemma closure.is_submonoid : is_submonoid (closure S) := { mul_mem := by rintros _ _ ⟨p, hp, q, hq, hq0, rfl⟩ ⟨r, hr, s, hs, hs0, rfl⟩; exact ⟨p * r, is_submonoid.mul_mem ring.closure.is_subring.to_is_submonoid hp hr, q * s, is_submonoid.mul_mem ring.closure.is_subring.to_is_submonoid hq hs, (div_mul_div_comm _ _ _ _).symm⟩, one_mem := ring_closure_subset $ is_submonoid.one_mem ring.closure.is_subring.to_is_submonoid } lemma closure.is_subfield : is_subfield (closure S) := have h0 : (0:F) ∈ closure S, from ring_closure_subset $ ring.closure.is_subring.to_is_add_subgroup.to_is_add_submonoid.zero_mem, { add_mem := begin intros a b ha hb, rcases (id ha) with ⟨p, hp, q, hq, rfl⟩, rcases (id hb) with ⟨r, hr, s, hs, rfl⟩, classical, by_cases hq0 : q = 0, by simp [hb, hq0], by_cases hs0 : s = 0, by simp [ha, hs0], exact ⟨p * s + q * r, is_add_submonoid.add_mem ring.closure.is_subring.to_is_add_subgroup.to_is_add_submonoid (ring.closure.is_subring.to_is_submonoid.mul_mem hp hs) (ring.closure.is_subring.to_is_submonoid.mul_mem hq hr), q * s, ring.closure.is_subring.to_is_submonoid.mul_mem hq hs, (div_add_div p r hq0 hs0).symm⟩ end, zero_mem := h0, neg_mem := begin rintros _ ⟨p, hp, q, hq, rfl⟩, exact ⟨-p, ring.closure.is_subring.to_is_add_subgroup.neg_mem hp, q, hq, neg_div q p⟩ end, inv_mem := begin rintros _ ⟨p, hp, q, hq, rfl⟩, exact ⟨q, hq, p, hp, (inv_div _ _).symm⟩ end, ..closure.is_submonoid } theorem mem_closure {a : F} (ha : a ∈ S) : a ∈ closure S := ring_closure_subset $ ring.mem_closure ha theorem subset_closure : S ⊆ closure S := λ _, mem_closure theorem closure_subset {T : set F} (hT : is_subfield T) (H : S ⊆ T) : closure S ⊆ T := by rintros _ ⟨p, hp, q, hq, hq0, rfl⟩; exact hT.div_mem (ring.closure_subset hT.to_is_subring H hp) (ring.closure_subset hT.to_is_subring H hq) theorem closure_subset_iff {s t : set F} (ht : is_subfield t) : closure s ⊆ t ↔ s ⊆ t := ⟨set.subset.trans subset_closure, closure_subset ht⟩ theorem closure_mono {s t : set F} (H : s ⊆ t) : closure s ⊆ closure t := closure_subset closure.is_subfield $ set.subset.trans H subset_closure end field lemma is_subfield_Union_of_directed {ι : Type*} [hι : nonempty ι] {s : ι → set F} (hs : ∀ i, is_subfield (s i)) (directed : ∀ i j, ∃ k, s i ⊆ s k ∧ s j ⊆ s k) : is_subfield (⋃i, s i) := { inv_mem := λ x hx, let ⟨i, hi⟩ := set.mem_Union.1 hx in set.mem_Union.2 ⟨i, (hs i).inv_mem hi⟩, to_is_subring := is_subring_Union_of_directed (λ i, (hs i).to_is_subring) directed } lemma is_subfield.inter {S₁ S₂ : set F} (hS₁ : is_subfield S₁) (hS₂ : is_subfield S₂) : is_subfield (S₁ ∩ S₂) := { inv_mem := λ x hx, ⟨hS₁.inv_mem hx.1, hS₂.inv_mem hx.2⟩, ..is_subring.inter hS₁.to_is_subring hS₂.to_is_subring } lemma is_subfield.Inter {ι : Sort*} {S : ι → set F} (h : ∀ y : ι, is_subfield (S y)) : is_subfield (set.Inter S) := { inv_mem := λ x hx, set.mem_Inter.2 $ λ y, (h y).inv_mem $ set.mem_Inter.1 hx y, ..is_subring.Inter (λ y, (h y).to_is_subring) }
023ed16cc8232db463dfa0b1c86d0cc88b5d3546
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/ring_theory/polynomial/cyclotomic/roots.lean
41e73830f5ffc9d853f89f3ddc83f043e4a6e735
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
10,542
lean
/- Copyright (c) 2020 Riccardo Brasca. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Riccardo Brasca -/ import ring_theory.polynomial.cyclotomic.basic import ring_theory.roots_of_unity.minpoly /-! # Roots of cyclotomic polynomials. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We gather results about roots of cyclotomic polynomials. In particular we show in `polynomial.cyclotomic_eq_minpoly` that `cyclotomic n R` is the minimal polynomial of a primitive root of unity. ## Main results * `is_primitive_root.is_root_cyclotomic` : Any `n`-th primitive root of unity is a root of `cyclotomic n R`. * `is_root_cyclotomic_iff` : if `ne_zero (n : R)`, then `μ` is a root of `cyclotomic n R` if and only if `μ` is a primitive root of unity. * `polynomial.cyclotomic_eq_minpoly` : `cyclotomic n ℤ` is the minimal polynomial of a primitive `n`-th root of unity `μ`. * `polynomial.cyclotomic.irreducible` : `cyclotomic n ℤ` is irreducible. ## Implementation details To prove `polynomial.cyclotomic.irreducible`, the irreducibility of `cyclotomic n ℤ`, we show in `polynomial.cyclotomic_eq_minpoly` that `cyclotomic n ℤ` is the minimal polynomial of any `n`-th primitive root of unity `μ : K`, where `K` is a field of characteristic `0`. -/ open_locale big_operators namespace polynomial variables {R : Type*} [comm_ring R] {n : ℕ} lemma is_root_of_unity_of_root_cyclotomic {ζ : R} {i : ℕ} (hi : i ∈ n.divisors) (h : (cyclotomic i R).is_root ζ) : ζ ^ n = 1 := begin rcases n.eq_zero_or_pos with rfl | hn, { exact pow_zero _ }, have := congr_arg (eval ζ) (prod_cyclotomic_eq_X_pow_sub_one hn R).symm, rw [eval_sub, eval_pow, eval_X, eval_one] at this, convert eq_add_of_sub_eq' this, convert (add_zero _).symm, apply eval_eq_zero_of_dvd_of_eval_eq_zero _ h, exact finset.dvd_prod_of_mem _ hi end section is_domain variable [is_domain R] lemma _root_.is_root_of_unity_iff (h : 0 < n) (R : Type*) [comm_ring R] [is_domain R] {ζ : R} : ζ ^ n = 1 ↔ ∃ i ∈ n.divisors, (cyclotomic i R).is_root ζ := by rw [←mem_nth_roots h, nth_roots, mem_roots $ X_pow_sub_C_ne_zero h _, C_1, ←prod_cyclotomic_eq_X_pow_sub_one h, is_root_prod]; apply_instance /-- Any `n`-th primitive root of unity is a root of `cyclotomic n R`.-/ lemma _root_.is_primitive_root.is_root_cyclotomic (hpos : 0 < n) {μ : R} (h : is_primitive_root μ n) : is_root (cyclotomic n R) μ := begin rw [← mem_roots (cyclotomic_ne_zero n R), cyclotomic_eq_prod_X_sub_primitive_roots h, roots_prod_X_sub_C, ← finset.mem_def], rwa [← mem_primitive_roots hpos] at h, end private lemma is_root_cyclotomic_iff' {n : ℕ} {K : Type*} [field K] {μ : K} [ne_zero (n : K)] : is_root (cyclotomic n K) μ ↔ is_primitive_root μ n := begin -- in this proof, `o` stands for `order_of μ` have hnpos : 0 < n := (ne_zero.of_ne_zero_coe K).out.bot_lt, refine ⟨λ hμ, _, is_primitive_root.is_root_cyclotomic hnpos⟩, have hμn : μ ^ n = 1, { rw is_root_of_unity_iff hnpos _, exact ⟨n, n.mem_divisors_self hnpos.ne', hμ⟩, all_goals { apply_instance } }, by_contra hnμ, have ho : 0 < order_of μ, { apply order_of_pos', rw is_of_fin_order_iff_pow_eq_one, exact ⟨n, hnpos, hμn⟩ }, have := pow_order_of_eq_one μ, rw is_root_of_unity_iff ho at this, obtain ⟨i, hio, hiμ⟩ := this, replace hio := nat.dvd_of_mem_divisors hio, rw is_primitive_root.not_iff at hnμ, rw ←order_of_dvd_iff_pow_eq_one at hμn, have key : i < n := (nat.le_of_dvd ho hio).trans_lt ((nat.le_of_dvd hnpos hμn).lt_of_ne hnμ), have key' : i ∣ n := hio.trans hμn, rw ←polynomial.dvd_iff_is_root at hμ hiμ, have hni : {i, n} ⊆ n.divisors, { simpa [finset.insert_subset, key'] using hnpos.ne' }, obtain ⟨k, hk⟩ := hiμ, obtain ⟨j, hj⟩ := hμ, have := prod_cyclotomic_eq_X_pow_sub_one hnpos K, rw [←finset.prod_sdiff hni, finset.prod_pair key.ne, hk, hj] at this, have hn := (X_pow_sub_one_separable_iff.mpr $ ne_zero.nat_cast_ne n K).squarefree, rw [←this, squarefree] at hn, contrapose! hn, refine ⟨X - C μ, ⟨(∏ x in n.divisors \ {i, n}, cyclotomic x K) * k * j, by ring⟩, _⟩, simp [polynomial.is_unit_iff_degree_eq_zero], all_goals { apply_instance } end lemma is_root_cyclotomic_iff [ne_zero (n : R)] {μ : R} : is_root (cyclotomic n R) μ ↔ is_primitive_root μ n := begin have hf : function.injective _ := is_fraction_ring.injective R (fraction_ring R), haveI : ne_zero (n : fraction_ring R) := ne_zero.nat_of_injective hf, rw [←is_root_map_iff hf, ←is_primitive_root.map_iff_of_injective hf, map_cyclotomic, ←is_root_cyclotomic_iff'] end lemma roots_cyclotomic_nodup [ne_zero (n : R)] : (cyclotomic n R).roots.nodup := begin obtain h | ⟨ζ, hζ⟩ := (cyclotomic n R).roots.empty_or_exists_mem, { exact h.symm ▸ multiset.nodup_zero }, rw [mem_roots $ cyclotomic_ne_zero n R, is_root_cyclotomic_iff] at hζ, refine multiset.nodup_of_le (roots.le_of_dvd (X_pow_sub_C_ne_zero (ne_zero.pos_of_ne_zero_coe R) 1) $ cyclotomic.dvd_X_pow_sub_one n R) hζ.nth_roots_nodup, end lemma cyclotomic.roots_to_finset_eq_primitive_roots [ne_zero (n : R)] : (⟨(cyclotomic n R).roots, roots_cyclotomic_nodup⟩ : finset _) = primitive_roots n R := by { ext, simp [cyclotomic_ne_zero n R, is_root_cyclotomic_iff, mem_primitive_roots, ne_zero.pos_of_ne_zero_coe R] } lemma cyclotomic.roots_eq_primitive_roots_val [ne_zero (n : R)] : (cyclotomic n R).roots = (primitive_roots n R).val := by rw ←cyclotomic.roots_to_finset_eq_primitive_roots /-- If `R` is of characteristic zero, then `ζ` is a root of `cyclotomic n R` if and only if it is a primitive `n`-th root of unity. -/ lemma is_root_cyclotomic_iff_char_zero {n : ℕ} {R : Type*} [comm_ring R] [is_domain R] [char_zero R] {μ : R} (hn : 0 < n) : (polynomial.cyclotomic n R).is_root μ ↔ is_primitive_root μ n := by { letI := ne_zero.of_gt hn, exact is_root_cyclotomic_iff } end is_domain /-- Over a ring `R` of characteristic zero, `λ n, cyclotomic n R` is injective. -/ lemma cyclotomic_injective [char_zero R] : function.injective (λ n, cyclotomic n R) := begin intros n m hnm, simp only at hnm, rcases eq_or_ne n 0 with rfl | hzero, { rw [cyclotomic_zero] at hnm, replace hnm := congr_arg nat_degree hnm, rw [nat_degree_one, nat_degree_cyclotomic] at hnm, by_contra, exact (nat.totient_pos (zero_lt_iff.2 (ne.symm h))).ne hnm }, { haveI := ne_zero.mk hzero, rw [← map_cyclotomic_int _ R, ← map_cyclotomic_int _ R] at hnm, replace hnm := map_injective (int.cast_ring_hom R) int.cast_injective hnm, replace hnm := congr_arg (map (int.cast_ring_hom ℂ)) hnm, rw [map_cyclotomic_int, map_cyclotomic_int] at hnm, have hprim := complex.is_primitive_root_exp _ hzero, have hroot := is_root_cyclotomic_iff.2 hprim, rw hnm at hroot, haveI hmzero : ne_zero m := ⟨λ h, by simpa [h] using hroot⟩, rw is_root_cyclotomic_iff at hroot, replace hprim := hprim.eq_order_of, rwa [← is_primitive_root.eq_order_of hroot] at hprim} end /-- The minimal polynomial of a primitive `n`-th root of unity `μ` divides `cyclotomic n ℤ`. -/ lemma _root_.is_primitive_root.minpoly_dvd_cyclotomic {n : ℕ} {K : Type*} [field K] {μ : K} (h : is_primitive_root μ n) (hpos : 0 < n) [char_zero K] : minpoly ℤ μ ∣ cyclotomic n ℤ := begin apply minpoly.is_integrally_closed_dvd (h.is_integral hpos), simpa [aeval_def, eval₂_eq_eval_map, is_root.def] using h.is_root_cyclotomic hpos end section minpoly open is_primitive_root complex lemma _root_.is_primitive_root.minpoly_eq_cyclotomic_of_irreducible {K : Type*} [field K] {R : Type*} [comm_ring R] [is_domain R] {μ : R} {n : ℕ} [algebra K R] (hμ : is_primitive_root μ n) (h : irreducible $ cyclotomic n K) [ne_zero (n : K)] : cyclotomic n K = minpoly K μ := begin haveI := ne_zero.of_no_zero_smul_divisors K R n, refine minpoly.eq_of_irreducible_of_monic h _ (cyclotomic.monic n K), rwa [aeval_def, eval₂_eq_eval_map, map_cyclotomic, ←is_root.def, is_root_cyclotomic_iff] end /-- `cyclotomic n ℤ` is the minimal polynomial of a primitive `n`-th root of unity `μ`. -/ lemma cyclotomic_eq_minpoly {n : ℕ} {K : Type*} [field K] {μ : K} (h : is_primitive_root μ n) (hpos : 0 < n) [char_zero K] : cyclotomic n ℤ = minpoly ℤ μ := begin refine eq_of_monic_of_dvd_of_nat_degree_le (minpoly.monic (is_integral h hpos)) (cyclotomic.monic n ℤ) (h.minpoly_dvd_cyclotomic hpos) _, simpa [nat_degree_cyclotomic n ℤ] using totient_le_degree_minpoly h end /-- `cyclotomic n ℚ` is the minimal polynomial of a primitive `n`-th root of unity `μ`. -/ lemma cyclotomic_eq_minpoly_rat {n : ℕ} {K : Type*} [field K] {μ : K} (h : is_primitive_root μ n) (hpos : 0 < n) [char_zero K] : cyclotomic n ℚ = minpoly ℚ μ := begin rw [← map_cyclotomic_int, cyclotomic_eq_minpoly h hpos], exact (minpoly.is_integrally_closed_eq_field_fractions' _ (is_integral h hpos)).symm end /-- `cyclotomic n ℤ` is irreducible. -/ lemma cyclotomic.irreducible {n : ℕ} (hpos : 0 < n) : irreducible (cyclotomic n ℤ) := begin rw [cyclotomic_eq_minpoly (is_primitive_root_exp n hpos.ne') hpos], apply minpoly.irreducible, exact (is_primitive_root_exp n hpos.ne').is_integral hpos, end /-- `cyclotomic n ℚ` is irreducible. -/ lemma cyclotomic.irreducible_rat {n : ℕ} (hpos : 0 < n) : irreducible (cyclotomic n ℚ) := begin rw [← map_cyclotomic_int], exact (is_primitive.irreducible_iff_irreducible_map_fraction_map (cyclotomic.is_primitive n ℤ)).1 (cyclotomic.irreducible hpos), end /-- If `n ≠ m`, then `(cyclotomic n ℚ)` and `(cyclotomic m ℚ)` are coprime. -/ lemma cyclotomic.is_coprime_rat {n m : ℕ} (h : n ≠ m) : is_coprime (cyclotomic n ℚ) (cyclotomic m ℚ) := begin rcases n.eq_zero_or_pos with rfl | hnzero, { exact is_coprime_one_left }, rcases m.eq_zero_or_pos with rfl | hmzero, { exact is_coprime_one_right }, rw (irreducible.coprime_iff_not_dvd $ cyclotomic.irreducible_rat $ hnzero), exact (λ hdiv, h $ cyclotomic_injective $ eq_of_monic_of_associated (cyclotomic.monic n ℚ) (cyclotomic.monic m ℚ) $ irreducible.associated_of_dvd (cyclotomic.irreducible_rat hnzero) (cyclotomic.irreducible_rat hmzero) hdiv), end end minpoly end polynomial
a8fea3d22b21cee61874130b7f43f5188b03b6b5
cf39355caa609c0f33405126beee2739aa3cb77e
/library/init/control/alternative.lean
9847396fd26fae1b09ec8d8b329a84ecd11d9b5b
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
1,348
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import init.logic init.control.applicative universes u v class has_orelse (f : Type u → Type v) : Type (max (u+1) v) := (orelse : Π {α : Type u}, f α → f α → f α) infixr ` <|> `:2 := has_orelse.orelse class alternative (f : Type u → Type v) extends applicative f, has_orelse f : Type (max (u+1) v) := (failure : Π {α : Type u}, f α) section variables {f : Type u → Type v} [alternative f] {α : Type u} @[inline] def failure : f α := alternative.failure /-- If the condition `p` is decided to be false, then fail, otherwise, return unit. -/ @[inline] def guard {f : Type → Type v} [alternative f] (p : Prop) [decidable p] : f unit := if p then pure () else failure @[inline] def assert {f : Type → Type v} [alternative f] (p : Prop) [decidable p] : f (inhabited p) := if h : p then pure ⟨h⟩ else failure /- Later we define a coercion from bool to Prop, but this version will still be useful. Given (t : tactic bool), we can write t >>= guardb -/ @[inline] def guardb {f : Type → Type v} [alternative f] : bool → f unit | tt := pure () | ff := failure @[inline] def optional (x : f α) : f (option α) := some <$> x <|> pure none end
4aa584346924c95ddf450f0820efb973965cc1f0
e0f9ba56b7fedc16ef8697f6caeef5898b435143
/src/linear_algebra/finsupp.lean
6bcfe09e38ec4a671f64835dffe50a9d7efb6b47
[ "Apache-2.0" ]
permissive
anrddh/mathlib
6a374da53c7e3a35cb0298b0cd67824efef362b4
a4266a01d2dcb10de19369307c986d038c7bb6a6
refs/heads/master
1,656,710,827,909
1,589,560,456,000
1,589,560,456,000
264,271,800
0
0
Apache-2.0
1,589,568,062,000
1,589,568,061,000
null
UTF-8
Lean
false
false
17,023
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl Linear structures on function with finite support `α →₀ M`. -/ import data.monoid_algebra noncomputable theory open set linear_map submodule open_locale classical namespace finsupp variables {α : Type*} {M : Type*} {R : Type*} variables [ring R] [add_comm_group M] [module R M] def lsingle (a : α) : M →ₗ[R] (α →₀ M) := ⟨single a, assume a b, single_add, assume c b, (smul_single _ _ _).symm⟩ def lapply (a : α) : (α →₀ M) →ₗ[R] M := ⟨λg, g a, assume a b, rfl, assume a b, rfl⟩ section lsubtype_domain variables (s : set α) def lsubtype_domain : (α →₀ M) →ₗ[R] (s →₀ M) := ⟨subtype_domain (λx, x ∈ s), assume a b, subtype_domain_add, assume c a, ext $ assume a, rfl⟩ lemma lsubtype_domain_apply (f : α →₀ M) : (lsubtype_domain s : (α →₀ M) →ₗ[R] (s →₀ M)) f = subtype_domain (λx, x ∈ s) f := rfl end lsubtype_domain @[simp] lemma lsingle_apply (a : α) (b : M) : (lsingle a : M →ₗ[R] (α →₀ M)) b = single a b := rfl @[simp] lemma lapply_apply (a : α) (f : α →₀ M) : (lapply a : (α →₀ M) →ₗ[R] M) f = f a := rfl @[simp] lemma ker_lsingle (a : α) : (lsingle a : M →ₗ[R] (α →₀ M)).ker = ⊥ := ker_eq_bot.2 (injective_single a) lemma lsingle_range_le_ker_lapply (s t : set α) (h : disjoint s t) : (⨆a∈s, (lsingle a : M →ₗ[R] (α →₀ M)).range) ≤ (⨅a∈t, ker (lapply a)) := begin refine supr_le (assume a₁, supr_le $ assume h₁, range_le_iff_comap.2 _), simp only [(ker_comp _ _).symm, eq_top_iff, le_def', mem_ker, comap_infi, mem_infi], assume b hb a₂ h₂, have : a₁ ≠ a₂ := assume eq, h ⟨h₁, eq.symm ▸ h₂⟩, exact single_eq_of_ne this end lemma infi_ker_lapply_le_bot : (⨅a, ker (lapply a : (α →₀ M) →ₗ[R] M)) ≤ ⊥ := begin simp only [le_def', mem_infi, mem_ker, mem_bot, lapply_apply], exact assume a h, finsupp.ext h end lemma supr_lsingle_range : (⨆a, (lsingle a : M →ₗ[R] (α →₀ M)).range) = ⊤ := begin refine (eq_top_iff.2 $ le_def'.2 $ assume f _, _), rw [← sum_single f], refine sum_mem _ (assume a ha, submodule.mem_supr_of_mem _ a $ set.mem_image_of_mem _ trivial) end lemma disjoint_lsingle_lsingle (s t : set α) (hs : disjoint s t) : disjoint (⨆a∈s, (lsingle a : M →ₗ[R] (α →₀ M)).range) (⨆a∈t, (lsingle a).range) := begin refine disjoint.mono (lsingle_range_le_ker_lapply _ _ $ disjoint_compl s) (lsingle_range_le_ker_lapply _ _ $ disjoint_compl t) (le_trans (le_infi $ assume i, _) infi_ker_lapply_le_bot), classical, by_cases his : i ∈ s, { by_cases hit : i ∈ t, { exact (hs ⟨his, hit⟩).elim }, exact inf_le_right_of_le (infi_le_of_le i $ infi_le _ hit) }, exact inf_le_left_of_le (infi_le_of_le i $ infi_le _ his) end lemma span_single_image (s : set M) (a : α) : submodule.span R (single a '' s) = (submodule.span R s).map (lsingle a) := by rw ← span_image; refl variables (M R) def supported (s : set α) : submodule R (α →₀ M) := begin refine ⟨ {p | ↑p.support ⊆ s }, _, _, _ ⟩, { simp only [subset_def, finset.mem_coe, set.mem_set_of_eq, mem_support_iff, zero_apply], assume h ha, exact (ha rfl).elim }, { assume p q hp hq, refine subset.trans (subset.trans (finset.coe_subset.2 support_add) _) (union_subset hp hq), rw [finset.coe_union] }, { assume a p hp, refine subset.trans (finset.coe_subset.2 support_smul) hp } end variables {M} lemma mem_supported {s : set α} (p : α →₀ M) : p ∈ (supported M R s) ↔ ↑p.support ⊆ s := iff.rfl lemma mem_supported' {s : set α} (p : α →₀ M) : p ∈ supported M R s ↔ ∀ x ∉ s, p x = 0 := by haveI := classical.dec_pred (λ (x : α), x ∈ s); simp [mem_supported, set.subset_def, not_imp_comm] lemma single_mem_supported {s : set α} {a : α} (b : M) (h : a ∈ s) : single a b ∈ supported M R s := set.subset.trans support_single_subset (set.singleton_subset_iff.2 h) lemma supported_eq_span_single (s : set α) : supported R R s = span R ((λ i, single i 1) '' s) := begin refine (span_eq_of_le _ _ (le_def'.2 $ λ l hl, _)).symm, { rintro _ ⟨_, hp, rfl ⟩ , exact single_mem_supported R 1 hp }, { rw ← l.sum_single, refine sum_mem _ (λ i il, _), convert @smul_mem R (α →₀ R) _ _ _ _ (single i 1) (l i) _, { simp }, apply subset_span, apply set.mem_image_of_mem _ (hl il) } end variables (M R) def restrict_dom (s : set α) : (α →₀ M) →ₗ supported M R s := linear_map.cod_restrict _ { to_fun := filter (∈ s), add := λ l₁ l₂, filter_add, smul := λ a l, filter_smul } (λ l, (mem_supported' _ _).2 $ λ x, filter_apply_neg (∈ s) l) variables {M R} section @[simp] theorem restrict_dom_apply (s : set α) (l : α →₀ M) : ((restrict_dom M R s : (α →₀ M) →ₗ supported M R s) l : α →₀ M) = finsupp.filter (∈ s) l := rfl end theorem restrict_dom_comp_subtype (s : set α) : (restrict_dom M R s).comp (submodule.subtype _) = linear_map.id := begin ext l, apply subtype.coe_ext.2, simp, ext a, by_cases a ∈ s, { simp [h] }, { rw [filter_apply_neg (λ x, x ∈ s) _ h], exact ((mem_supported' R l.1).1 l.2 a h).symm } end theorem range_restrict_dom (s : set α) : (restrict_dom M R s).range = ⊤ := begin have := linear_map.range_comp (submodule.subtype _) (restrict_dom M R s), rw [restrict_dom_comp_subtype, linear_map.range_id] at this, exact eq_top_mono (submodule.map_mono le_top) this.symm end theorem supported_mono {s t : set α} (st : s ⊆ t) : supported M R s ≤ supported M R t := λ l h, set.subset.trans h st @[simp] theorem supported_empty : supported M R (∅ : set α) = ⊥ := eq_bot_iff.2 $ λ l h, (submodule.mem_bot R).2 $ by ext; simp [*, mem_supported'] at * @[simp] theorem supported_univ : supported M R (set.univ : set α) = ⊤ := eq_top_iff.2 $ λ l _, set.subset_univ _ theorem supported_Union {δ : Type*} (s : δ → set α) : supported M R (⋃ i, s i) = ⨆ i, supported M R (s i) := begin refine le_antisymm _ (supr_le $ λ i, supported_mono $ set.subset_Union _ _), haveI := classical.dec_pred (λ x, x ∈ (⋃ i, s i)), suffices : ((submodule.subtype _).comp (restrict_dom M R (⋃ i, s i))).range ≤ ⨆ i, supported M R (s i), { rwa [linear_map.range_comp, range_restrict_dom, map_top, range_subtype] at this }, rw [range_le_iff_comap, eq_top_iff], rintro l ⟨⟩, rw mem_coe, apply finsupp.induction l, {exact zero_mem _}, refine λ x a l hl a0, add_mem _ _, haveI := classical.dec_pred (λ x, ∃ i, x ∈ s i), by_cases (∃ i, x ∈ s i); simp [h], { cases h with i hi, exact le_supr (λ i, supported M R (s i)) i (single_mem_supported R _ hi) }, { rw filter_single_of_neg, { simp }, { exact h } } end theorem supported_union (s t : set α) : supported M R (s ∪ t) = supported M R s ⊔ supported M R t := by erw [set.union_eq_Union, supported_Union, supr_bool_eq]; refl theorem supported_Inter {ι : Type*} (s : ι → set α) : supported M R (⋂ i, s i) = ⨅ i, supported M R (s i) := begin refine le_antisymm (le_infi $ λ i, supported_mono $ set.Inter_subset _ _) _, simp [le_def, infi_coe, set.subset_def], exact λ l, set.subset_Inter end section def supported_equiv_finsupp (s : set α) : (supported M R s) ≃ₗ[R] (s →₀ M) := (restrict_support_equiv s).to_linear_equiv begin show is_linear_map R ((lsubtype_domain s : (α →₀ M) →ₗ[R] (s →₀ M)).comp (submodule.subtype (supported M R s))), exact linear_map.is_linear _ end end def lsum (f : α → R →ₗ[R] M) : (α →₀ R) →ₗ[R] M := ⟨λ d, d.sum (λ i, f i), assume d₁ d₂, by simp [sum_add_index], assume a d, by simp [sum_smul_index, smul_sum, -smul_eq_mul, smul_eq_mul.symm]⟩ @[simp] theorem lsum_apply (f : α → R →ₗ[R] M) (l : α →₀ R) : (finsupp.lsum f : (α →₀ R) →ₗ M) l = l.sum (λ b, f b) := rfl section lmap_domain variables {α' : Type*} {α'' : Type*} (M R) def lmap_domain (f : α → α') : (α →₀ M) →ₗ[R] (α' →₀ M) := ⟨map_domain f, assume a b, map_domain_add, map_domain_smul⟩ @[simp] theorem lmap_domain_apply (f : α → α') (l : α →₀ M) : (lmap_domain M R f : (α →₀ M) →ₗ[R] (α' →₀ M)) l = map_domain f l := rfl @[simp] theorem lmap_domain_id : (lmap_domain M R id : (α →₀ M) →ₗ[R] α →₀ M) = linear_map.id := linear_map.ext $ λ l, map_domain_id theorem lmap_domain_comp (f : α → α') (g : α' → α'') : lmap_domain M R (g ∘ f) = (lmap_domain M R g).comp (lmap_domain M R f) := linear_map.ext $ λ l, map_domain_comp theorem supported_comap_lmap_domain (f : α → α') (s : set α') : supported M R (f ⁻¹' s) ≤ (supported M R s).comap (lmap_domain M R f) := λ l (hl : ↑l.support ⊆ f ⁻¹' s), show ↑(map_domain f l).support ⊆ s, begin rw [← set.image_subset_iff, ← finset.coe_image] at hl, exact set.subset.trans map_domain_support hl end theorem lmap_domain_supported [nonempty α] (f : α → α') (s : set α) : (supported M R s).map (lmap_domain M R f) = supported M R (f '' s) := begin inhabit α, refine le_antisymm (map_le_iff_le_comap.2 $ le_trans (supported_mono $ set.subset_preimage_image _ _) (supported_comap_lmap_domain _ _ _ _)) _, intros l hl, refine ⟨(lmap_domain M R (function.inv_fun_on f s) : (α' →₀ M) →ₗ α →₀ M) l, λ x hx, _, _⟩, { rcases finset.mem_image.1 (map_domain_support hx) with ⟨c, hc, rfl⟩, exact function.inv_fun_on_mem (by simpa using hl hc) }, { rw [← linear_map.comp_apply, ← lmap_domain_comp], refine (map_domain_congr $ λ c hc, _).trans map_domain_id, exact function.inv_fun_on_eq (by simpa using hl hc) } end theorem lmap_domain_disjoint_ker (f : α → α') {s : set α} (H : ∀ a b ∈ s, f a = f b → a = b) : disjoint (supported M R s) (lmap_domain M R f).ker := begin rintro l ⟨h₁, h₂⟩, rw [mem_coe, mem_ker, lmap_domain_apply, map_domain] at h₂, simp, ext x, haveI := classical.dec_pred (λ x, x ∈ s), by_cases xs : x ∈ s, { have : finsupp.sum l (λ a, finsupp.single (f a)) (f x) = 0, {rw h₂, refl}, rw [finsupp.sum_apply, finsupp.sum, finset.sum_eq_single x] at this, { simpa [finsupp.single_apply] }, { intros y hy xy, simp [mt (H _ _ (h₁ hy) xs) xy] }, { simp {contextual := tt} } }, { by_contra h, exact xs (h₁ $ finsupp.mem_support_iff.2 h) } end end lmap_domain section total variables (α) {α' : Type*} (M) {M' : Type*} (R) [add_comm_group M'] [module R M'] (v : α → M) {v' : α' → M'} /-- Interprets (l : α →₀ R) as linear combination of the elements in the family (v : α → M) and evaluates this linear combination. -/ protected def total : (α →₀ R) →ₗ M := finsupp.lsum (λ i, linear_map.id.smul_right (v i)) variables {α M v} theorem total_apply (l : α →₀ R) : finsupp.total α M R v l = l.sum (λ i a, a • v i) := rfl @[simp] theorem total_single (c : R) (a : α) : finsupp.total α M R v (single a c) = c • (v a) := by simp [total_apply, sum_single_index] theorem total_range (h : function.surjective v) : (finsupp.total α M R v).range = ⊤ := begin apply range_eq_top.2, intros x, apply exists.elim (h x), exact λ i hi, ⟨single i 1, by simp [hi]⟩ end lemma range_total : (finsupp.total α M R v).range = span R (range v) := begin ext x, split, { intros hx, rw [linear_map.mem_range] at hx, rcases hx with ⟨l, hl⟩, rw ← hl, rw finsupp.total_apply, unfold finsupp.sum, apply sum_mem (span R (range v)), exact λ i hi, submodule.smul _ _ (subset_span (mem_range_self i)) }, { apply span_le.2, intros x hx, rcases hx with ⟨i, hi⟩, rw [mem_coe, linear_map.mem_range], use finsupp.single i 1, simp [hi] } end theorem lmap_domain_total (f : α → α') (g : M →ₗ[R] M') (h : ∀ i, g (v i) = v' (f i)) : (finsupp.total α' M' R v').comp (lmap_domain R R f) = g.comp (finsupp.total α M R v) := by ext l; simp [total_apply, finsupp.sum_map_domain_index, add_smul, h] theorem total_emb_domain (f : α ↪ α') (l : α →₀ R) : (finsupp.total α' M' R v') (emb_domain f l) = (finsupp.total α M' R (v' ∘ f)) l := by simp [total_apply, finsupp.sum, support_emb_domain, emb_domain_apply] theorem total_map_domain (f : α → α') (hf : function.injective f) (l : α →₀ R) : (finsupp.total α' M' R v') (map_domain f l) = (finsupp.total α M' R (v' ∘ f)) l := begin have : map_domain f l = emb_domain ⟨f, hf⟩ l, { rw emb_domain_eq_map_domain ⟨f, hf⟩, refl }, rw this, apply total_emb_domain R ⟨f, hf⟩ l end theorem span_eq_map_total (s : set α): span R (v '' s) = submodule.map (finsupp.total α M R v) (supported R R s) := begin apply span_eq_of_le, { intros x hx, rw set.mem_image at hx, apply exists.elim hx, intros i hi, exact ⟨_, finsupp.single_mem_supported R 1 hi.1, by simp [hi.2]⟩ }, { refine map_le_iff_le_comap.2 (λ z hz, _), have : ∀i, z i • v i ∈ span R (v '' s), { intro c, haveI := classical.dec_pred (λ x, x ∈ s), by_cases c ∈ s, { exact smul_mem _ _ (subset_span (set.mem_image_of_mem _ h)) }, { simp [(finsupp.mem_supported' R _).1 hz _ h] } }, refine sum_mem _ _, simp [this] } end theorem mem_span_iff_total {s : set α} {x : M} : x ∈ span R (v '' s) ↔ ∃ l ∈ supported R R s, finsupp.total α M R v l = x := by rw span_eq_map_total; simp variables (α) (M) (v) protected def total_on (s : set α) : supported R R s →ₗ[R] span R (v '' s) := linear_map.cod_restrict _ ((finsupp.total _ _ _ v).comp (submodule.subtype (supported R R s))) $ λ ⟨l, hl⟩, (mem_span_iff_total _).2 ⟨l, hl, rfl⟩ variables {α} {M} {v} theorem total_on_range (s : set α) : (finsupp.total_on α M R v s).range = ⊤ := by rw [finsupp.total_on, linear_map.range, linear_map.map_cod_restrict, ← linear_map.range_le_iff_comap, range_subtype, map_top, linear_map.range_comp, range_subtype]; exact le_of_eq (span_eq_map_total _ _) theorem total_comp (f : α' → α) : (finsupp.total α' M R (v ∘ f)) = (finsupp.total α M R v).comp (lmap_domain R R f) := begin ext l, simp [total_apply], rw sum_map_domain_index; simp [add_smul], end lemma total_comap_domain (f : α → α') (l : α' →₀ R) (hf : set.inj_on f (f ⁻¹' ↑l.support)) : finsupp.total α M R v (finsupp.comap_domain f l hf) = (l.support.preimage hf).sum (λ i, (l (f i)) • (v i)) := by rw finsupp.total_apply; refl end total protected def dom_lcongr {α₁ : Type*} {α₂ : Type*} (e : α₁ ≃ α₂) : (α₁ →₀ M) ≃ₗ[R] (α₂ →₀ M) := (finsupp.dom_congr e).to_linear_equiv begin change is_linear_map R (lmap_domain M R e : (α₁ →₀ M) →ₗ[R] (α₂ →₀ M)), exact linear_map.is_linear _ end noncomputable def congr {α' : Type*} (s : set α) (t : set α') (e : s ≃ t) : supported M R s ≃ₗ[R] supported M R t := begin haveI := classical.dec_pred (λ x, x ∈ s), haveI := classical.dec_pred (λ x, x ∈ t), refine linear_equiv.trans (finsupp.supported_equiv_finsupp s) (linear_equiv.trans _ (finsupp.supported_equiv_finsupp t).symm), exact finsupp.dom_lcongr e end end finsupp variables {R : Type*} {M : Type*} {N : Type*} variables [ring R] [add_comm_group M] [module R M] [add_comm_group N] [module R N] lemma linear_map.map_finsupp_total (f : M →ₗ[R] N) {ι : Type*} {g : ι → M} (l : ι →₀ R) : f (finsupp.total ι M R g l) = finsupp.total ι N R (f ∘ g) l := by simp only [finsupp.total_apply, finsupp.total_apply, finsupp.sum, f.map_sum, f.map_smul] lemma submodule.exists_finset_of_mem_supr {ι : Sort*} (p : ι → submodule R M) {m : M} (hm : m ∈ ⨆ i, p i) : ∃ s : finset ι, m ∈ ⨆ i ∈ s, p i := begin obtain ⟨f, hf, rfl⟩ : ∃ f ∈ finsupp.supported R R (⋃ i, ↑(p i)), finsupp.total M M R id f = m, { have aux : (id : M → M) '' (⋃ (i : ι), ↑(p i)) = (⋃ (i : ι), ↑(p i)) := set.image_id _, rwa [supr_eq_span, ← aux, finsupp.mem_span_iff_total R] at hm }, let t : finset M := f.support, have ht : ∀ x : {x // x ∈ t}, ∃ i, ↑x ∈ p i, { intros x, rw finsupp.mem_supported at hf, specialize hf x.2, rwa set.mem_Union at hf }, choose g hg using ht, let s : finset ι := finset.univ.image g, use s, simp only [mem_supr, supr_le_iff], assume N hN, rw [finsupp.total_apply, finsupp.sum, ← submodule.mem_coe], apply is_add_submonoid.finset_sum_mem, assume x hx, apply submodule.smul_mem, let i : ι := g ⟨x, hx⟩, have hi : i ∈ s, { rw finset.mem_image, exact ⟨⟨x, hx⟩, finset.mem_univ _, rfl⟩ }, exact hN i hi (hg _), end
a100a31c5014f6c9c61c462c0c05eadd42788689
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/tactic/tidy.lean
e1c5f505f64d3abaf35cb0f770ec764d5a687205
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,367
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import tactic.auto_cases import tactic.chain import tactic.norm_cast namespace tactic namespace tidy /-- Tag interactive tactics (locally) with `[tidy]` to add them to the list of default tactics called by `tidy`. -/ @[user_attribute] meta def tidy_attribute : user_attribute := { name := `tidy, descr := "A tactic that should be called by `tidy`." } add_tactic_doc { name := "tidy", category := doc_category.attr, decl_names := [`tactic.tidy.tidy_attribute], tags := ["search"] } meta def run_tactics : tactic string := do names ← attribute.get_instances `tidy, first (names.map name_to_tactic) <|> fail "no @[tidy] tactics succeeded" @[hint_tactic] meta def ext1_wrapper : tactic string := do ng ← num_goals, ext1 [] {apply_cfg . new_goals := new_goals.all}, ng' ← num_goals, return $ if ng' > ng then "tactic.ext1 [] {new_goals := tactic.new_goals.all}" else "ext1" meta def default_tactics : list (tactic string) := [ reflexivity >> pure "refl", `[exact dec_trivial] >> pure "exact dec_trivial", propositional_goal >> assumption >> pure "assumption", intros1 >>= λ ns, pure ("intros " ++ (" ".intercalate $ ns.map $ λ e, e.to_string)), auto_cases, `[apply_auto_param] >> pure "apply_auto_param", `[dsimp at *] >> pure "dsimp at *", `[simp at *] >> pure "simp at *", ext1_wrapper, fsplit >> pure "fsplit", injections_and_clear >> pure "injections_and_clear", propositional_goal >> (`[solve_by_elim]) >> pure "solve_by_elim", `[norm_cast] >> pure "norm_cast", `[unfold_coes] >> pure "unfold_coes", `[unfold_aux] >> pure "unfold_aux", tidy.run_tactics ] meta structure cfg := (trace_result : bool := ff) (trace_result_prefix : string := "Try this: ") (tactics : list (tactic string) := default_tactics) declare_trace tidy meta def core (cfg : cfg := {}) : tactic (list string) := do results ← chain cfg.tactics, when (cfg.trace_result) $ trace (cfg.trace_result_prefix ++ (", ".intercalate results)), return results end tidy meta def tidy (cfg : tidy.cfg := {}) := tactic.tidy.core cfg >> skip namespace interactive open lean.parser interactive /-- Use a variety of conservative tactics to solve goals. `tidy?` reports back the tactic script it found. As an example ```lean example : ∀ x : unit, x = unit.star := begin tidy? -- Prints the trace message: "Try this: intros x, exact dec_trivial" end ``` The default list of tactics is stored in `tactic.tidy.default_tidy_tactics`. This list can be overridden using `tidy { tactics := ... }`. (The list must be a `list` of `tactic string`, so that `tidy?` can report a usable tactic script.) Tactics can also be added to the list by tagging them (locally) with the `[tidy]` attribute. -/ meta def tidy (trace : parse $ optional (tk "?")) (cfg : tidy.cfg := {}) := tactic.tidy { trace_result := trace.is_some, ..cfg } end interactive add_tactic_doc { name := "tidy", category := doc_category.tactic, decl_names := [`tactic.interactive.tidy], tags := ["search", "Try this", "finishing"] } /-- Invoking the hole command `tidy` ("Use `tidy` to complete the goal") runs the tactic of the same name, replacing the hole with the tactic script `tidy` produces. -/ @[hole_command] meta def tidy_hole_cmd : hole_command := { name := "tidy", descr := "Use `tidy` to complete the goal.", action := λ _, do script ← tidy.core, return [("begin " ++ (", ".intercalate script) ++ " end", "by tidy")] } add_tactic_doc { name := "tidy", category := doc_category.hole_cmd, decl_names := [`tactic.tidy_hole_cmd], tags := ["search"] } end tactic
7554ec632ad1a5a31189334d836f63be6497dd9f
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/topology/algebra/affine.lean
547ef38792c526213675f03da44a89884028447c
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
1,498
lean
/- Copyright (c) 2020 Frédéric Dupuis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Frédéric Dupuis -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.topology.algebra.continuous_functions import Mathlib.linear_algebra.affine_space.affine_map import Mathlib.PostPort universes u_1 u_2 u_3 namespace Mathlib /-! # Topological properties of affine spaces and maps For now, this contains only a few facts regarding the continuity of affine maps in the special case when the point space and vector space are the same. -/ namespace affine_map /- TODO: Deal with the case where the point spaces are different from the vector spaces. -/ /-- An affine map is continuous iff its underlying linear map is continuous. -/ theorem continuous_iff {R : Type u_1} {E : Type u_2} {F : Type u_3} [ring R] [add_comm_group E] [semimodule R E] [topological_space E] [add_comm_group F] [semimodule R F] [topological_space F] [topological_add_group F] {f : affine_map R E F} : continuous ⇑f ↔ continuous ⇑(linear f) := sorry /-- The line map is continuous. -/ theorem line_map_continuous {R : Type u_1} {F : Type u_3} [ring R] [add_comm_group F] [semimodule R F] [topological_space F] [topological_add_group F] [topological_space R] [topological_semimodule R F] {p : F} {v : F} : continuous ⇑(line_map p v) := iff.mpr continuous_iff (continuous.add (continuous.smul continuous_id continuous_const) continuous_const)
87a7ac1fd2ea44b5b477bbdbc04b0f1eaef1c18a
94e33a31faa76775069b071adea97e86e218a8ee
/src/measure_theory/measure/ae_measurable.lean
23d39122c84a1ef224770cbc0fce96dd73de5917
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
15,104
lean
/- Copyright (c) 2021 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 measure_theory.measure.measure_space /-! # Almost everywhere measurable functions A function is almost everywhere measurable if it coincides almost everywhere with a measurable function. This property, called `ae_measurable f μ`, is defined in the file `measure_space_def`. We discuss several of its properties that are analogous to properties of measurable functions. -/ open measure_theory measure_theory.measure filter set function open_locale measure_theory filter classical ennreal interval variables {ι α β γ δ R : Type*} {m0 : measurable_space α} [measurable_space β] [measurable_space γ] [measurable_space δ] {f g : α → β} {μ ν : measure α} include m0 section @[nontriviality, measurability] lemma subsingleton.ae_measurable [subsingleton α] : ae_measurable f μ := subsingleton.measurable.ae_measurable @[nontriviality, measurability] lemma ae_measurable_of_subsingleton_codomain [subsingleton β] : ae_measurable f μ := (measurable_of_subsingleton_codomain f).ae_measurable @[simp, measurability] lemma ae_measurable_zero_measure : ae_measurable f (0 : measure α) := begin nontriviality α, inhabit α, exact ⟨λ x, f default, measurable_const, rfl⟩ end namespace ae_measurable lemma mono_measure (h : ae_measurable f μ) (h' : ν ≤ μ) : ae_measurable f ν := ⟨h.mk f, h.measurable_mk, eventually.filter_mono (ae_mono h') h.ae_eq_mk⟩ lemma mono_set {s t} (h : s ⊆ t) (ht : ae_measurable f (μ.restrict t)) : ae_measurable f (μ.restrict s) := ht.mono_measure (restrict_mono h le_rfl) protected lemma mono' (h : ae_measurable f μ) (h' : ν ≪ μ) : ae_measurable f ν := ⟨h.mk f, h.measurable_mk, h' h.ae_eq_mk⟩ lemma ae_mem_imp_eq_mk {s} (h : ae_measurable f (μ.restrict s)) : ∀ᵐ x ∂μ, x ∈ s → f x = h.mk f x := ae_imp_of_ae_restrict h.ae_eq_mk lemma ae_inf_principal_eq_mk {s} (h : ae_measurable f (μ.restrict s)) : f =ᶠ[μ.ae ⊓ 𝓟 s] h.mk f := le_ae_restrict h.ae_eq_mk @[measurability] lemma sum_measure [encodable ι] {μ : ι → measure α} (h : ∀ i, ae_measurable f (μ i)) : ae_measurable f (sum μ) := begin nontriviality β, inhabit β, set s : ι → set α := λ i, to_measurable (μ i) {x | f x ≠ (h i).mk f x}, have hsμ : ∀ i, μ i (s i) = 0, { intro i, rw measure_to_measurable, exact (h i).ae_eq_mk }, have hsm : measurable_set (⋂ i, s i), from measurable_set.Inter (λ i, measurable_set_to_measurable _ _), have hs : ∀ i x, x ∉ s i → f x = (h i).mk f x, { intros i x hx, contrapose! hx, exact subset_to_measurable _ _ hx }, set g : α → β := (⋂ i, s i).piecewise (const α default) f, refine ⟨g, measurable_of_restrict_of_restrict_compl hsm _ _, ae_sum_iff.mpr $ λ i, _⟩, { rw [restrict_piecewise], simp only [set.restrict, const], exact measurable_const }, { rw [restrict_piecewise_compl, compl_Inter], intros t ht, refine ⟨⋃ i, ((h i).mk f ⁻¹' t) ∩ (s i)ᶜ, measurable_set.Union $ λ i, (measurable_mk _ ht).inter (measurable_set_to_measurable _ _).compl, _⟩, ext ⟨x, hx⟩, simp only [mem_preimage, mem_Union, subtype.coe_mk, set.restrict, mem_inter_eq, mem_compl_iff] at hx ⊢, split, { rintro ⟨i, hxt, hxs⟩, rwa hs _ _ hxs }, { rcases hx with ⟨i, hi⟩, rw hs _ _ hi, exact λ h, ⟨i, h, hi⟩ } }, { refine measure_mono_null (λ x (hx : f x ≠ g x), _) (hsμ i), contrapose! hx, refine (piecewise_eq_of_not_mem _ _ _ _).symm, exact λ h, hx (mem_Inter.1 h i) } end @[simp] lemma _root_.ae_measurable_sum_measure_iff [encodable ι] {μ : ι → measure α} : ae_measurable f (sum μ) ↔ ∀ i, ae_measurable f (μ i) := ⟨λ h i, h.mono_measure (le_sum _ _), sum_measure⟩ @[simp] lemma _root_.ae_measurable_add_measure_iff : ae_measurable f (μ + ν) ↔ ae_measurable f μ ∧ ae_measurable f ν := by { rw [← sum_cond, ae_measurable_sum_measure_iff, bool.forall_bool, and.comm], refl } @[measurability] lemma add_measure {f : α → β} (hμ : ae_measurable f μ) (hν : ae_measurable f ν) : ae_measurable f (μ + ν) := ae_measurable_add_measure_iff.2 ⟨hμ, hν⟩ @[measurability] protected lemma Union [encodable ι] {s : ι → set α} (h : ∀ i, ae_measurable f (μ.restrict (s i))) : ae_measurable f (μ.restrict (⋃ i, s i)) := (sum_measure h).mono_measure $ restrict_Union_le @[simp] lemma _root_.ae_measurable_Union_iff [encodable ι] {s : ι → set α} : ae_measurable f (μ.restrict (⋃ i, s i)) ↔ ∀ i, ae_measurable f (μ.restrict (s i)) := ⟨λ h i, h.mono_measure $ restrict_mono (subset_Union _ _) le_rfl, ae_measurable.Union⟩ @[simp] lemma _root_.ae_measurable_union_iff {s t : set α} : ae_measurable f (μ.restrict (s ∪ t)) ↔ ae_measurable f (μ.restrict s) ∧ ae_measurable f (μ.restrict t) := by simp only [union_eq_Union, ae_measurable_Union_iff, bool.forall_bool, cond, and.comm] @[measurability] lemma smul_measure [monoid R] [distrib_mul_action R ℝ≥0∞] [is_scalar_tower R ℝ≥0∞ ℝ≥0∞] (h : ae_measurable f μ) (c : R) : ae_measurable f (c • μ) := ⟨h.mk f, h.measurable_mk, ae_smul_measure h.ae_eq_mk c⟩ lemma comp_ae_measurable {f : α → δ} {g : δ → β} (hg : ae_measurable g (μ.map f)) (hf : ae_measurable f μ) : ae_measurable (g ∘ f) μ := ⟨hg.mk g ∘ hf.mk f, hg.measurable_mk.comp hf.measurable_mk, (ae_eq_comp hf hg.ae_eq_mk).trans ((hf.ae_eq_mk).fun_comp (mk g hg))⟩ lemma comp_measurable {f : α → δ} {g : δ → β} (hg : ae_measurable g (μ.map f)) (hf : measurable f) : ae_measurable (g ∘ f) μ := hg.comp_ae_measurable hf.ae_measurable lemma comp_measurable' {ν : measure δ} {f : α → δ} {g : δ → β} (hg : ae_measurable g ν) (hf : measurable f) (h : μ.map f ≪ ν) : ae_measurable (g ∘ f) μ := (hg.mono' h).comp_measurable hf lemma map_map_of_ae_measurable {g : β → γ} {f : α → β} (hg : ae_measurable g (measure.map f μ)) (hf : ae_measurable f μ) : (μ.map f).map g = μ.map (g ∘ f) := begin ext1 s hs, let g' := hg.mk g, have A : map g (map f μ) = map g' (map f μ), { apply measure_theory.measure.map_congr, exact hg.ae_eq_mk }, have B : map (g ∘ f) μ = map (g' ∘ f) μ, { apply measure_theory.measure.map_congr, exact ae_of_ae_map hf hg.ae_eq_mk }, simp only [A, B, hs, hg.measurable_mk.ae_measurable.comp_ae_measurable hf, hg.measurable_mk, hg.measurable_mk hs, hf, map_apply, map_apply_of_ae_measurable], refl, end @[measurability] lemma prod_mk {f : α → β} {g : α → γ} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ x, (f x, g x)) μ := ⟨λ a, (hf.mk f a, hg.mk g a), hf.measurable_mk.prod_mk hg.measurable_mk, eventually_eq.prod_mk hf.ae_eq_mk hg.ae_eq_mk⟩ lemma exists_ae_eq_range_subset (H : ae_measurable f μ) {t : set β} (ht : ∀ᵐ x ∂μ, f x ∈ t) (h₀ : t.nonempty) : ∃ g, measurable g ∧ range g ⊆ t ∧ f =ᵐ[μ] g := begin let s : set α := to_measurable μ {x | f x = H.mk f x ∧ f x ∈ t}ᶜ, let g : α → β := piecewise s (λ x, h₀.some) (H.mk f), refine ⟨g, _, _, _⟩, { exact measurable.piecewise (measurable_set_to_measurable _ _) measurable_const H.measurable_mk }, { rintros _ ⟨x, rfl⟩, by_cases hx : x ∈ s, { simpa [g, hx] using h₀.some_mem }, { simp only [g, hx, piecewise_eq_of_not_mem, not_false_iff], contrapose! hx, apply subset_to_measurable, simp only [hx, mem_compl_eq, mem_set_of_eq, not_and, not_false_iff, implies_true_iff] {contextual := tt} } }, { have A : μ (to_measurable μ {x | f x = H.mk f x ∧ f x ∈ t}ᶜ) = 0, { rw [measure_to_measurable, ← compl_mem_ae_iff, compl_compl], exact H.ae_eq_mk.and ht }, filter_upwards [compl_mem_ae_iff.2 A] with x hx, rw mem_compl_iff at hx, simp only [g, hx, piecewise_eq_of_not_mem, not_false_iff], contrapose! hx, apply subset_to_measurable, simp only [hx, mem_compl_eq, mem_set_of_eq, false_and, not_false_iff] } end lemma exists_measurable_nonneg {β} [preorder β] [has_zero β] {mβ : measurable_space β} {f : α → β} (hf : ae_measurable f μ) (f_nn : ∀ᵐ t ∂μ, 0 ≤ f t) : ∃ g, measurable g ∧ 0 ≤ g ∧ f =ᵐ[μ] g := begin obtain ⟨G, hG_meas, hG_mem, hG_ae_eq⟩ := hf.exists_ae_eq_range_subset f_nn ⟨0, le_rfl⟩, exact ⟨G, hG_meas, λ x, hG_mem (mem_range_self x), hG_ae_eq⟩, end lemma subtype_mk (h : ae_measurable f μ) {s : set β} {hfs : ∀ x, f x ∈ s} : ae_measurable (cod_restrict f s hfs) μ := begin nontriviality α, inhabit α, obtain ⟨g, g_meas, hg, fg⟩ : ∃ (g : α → β), measurable g ∧ range g ⊆ s ∧ f =ᵐ[μ] g := h.exists_ae_eq_range_subset (eventually_of_forall hfs) ⟨_, hfs default⟩, refine ⟨cod_restrict g s (λ x, hg (mem_range_self _)), measurable.subtype_mk g_meas, _⟩, filter_upwards [fg] with x hx, simpa [subtype.ext_iff], end protected lemma null_measurable (h : ae_measurable f μ) : null_measurable f μ := let ⟨g, hgm, hg⟩ := h in hgm.null_measurable.congr hg.symm end ae_measurable lemma ae_measurable_interval_oc_iff [linear_order α] {f : α → β} {a b : α} : (ae_measurable f $ μ.restrict $ Ι a b) ↔ (ae_measurable f $ μ.restrict $ Ioc a b) ∧ (ae_measurable f $ μ.restrict $ Ioc b a) := by rw [interval_oc_eq_union, ae_measurable_union_iff] lemma ae_measurable_iff_measurable [μ.is_complete] : ae_measurable f μ ↔ measurable f := ⟨λ h, h.null_measurable.measurable_of_complete, λ h, h.ae_measurable⟩ lemma measurable_embedding.ae_measurable_map_iff {g : β → γ} (hf : measurable_embedding f) : ae_measurable g (μ.map f) ↔ ae_measurable (g ∘ f) μ := begin refine ⟨λ H, H.comp_measurable hf.measurable, _⟩, rintro ⟨g₁, hgm₁, heq⟩, rcases hf.exists_measurable_extend hgm₁ (λ x, ⟨g x⟩) with ⟨g₂, hgm₂, rfl⟩, exact ⟨g₂, hgm₂, hf.ae_map_iff.2 heq⟩ end lemma measurable_embedding.ae_measurable_comp_iff {g : β → γ} (hg : measurable_embedding g) {μ : measure α} : ae_measurable (g ∘ f) μ ↔ ae_measurable f μ := begin refine ⟨λ H, _, hg.measurable.comp_ae_measurable⟩, suffices : ae_measurable ((range_splitting g ∘ range_factorization g) ∘ f) μ, by rwa [(right_inverse_range_splitting hg.injective).comp_eq_id] at this, exact hg.measurable_range_splitting.comp_ae_measurable H.subtype_mk end lemma ae_measurable_restrict_iff_comap_subtype {s : set α} (hs : measurable_set s) {μ : measure α} {f : α → β} : ae_measurable f (μ.restrict s) ↔ ae_measurable (f ∘ coe : s → β) (comap coe μ) := by rw [← map_comap_subtype_coe hs, (measurable_embedding.subtype_coe hs).ae_measurable_map_iff] @[simp, to_additive] lemma ae_measurable_one [has_one β] : ae_measurable (λ a : α, (1 : β)) μ := measurable_one.ae_measurable @[simp] lemma ae_measurable_smul_measure_iff {c : ℝ≥0∞} (hc : c ≠ 0) : ae_measurable f (c • μ) ↔ ae_measurable f μ := ⟨λ h, ⟨h.mk f, h.measurable_mk, (ae_smul_measure_iff hc).1 h.ae_eq_mk⟩, λ h, ⟨h.mk f, h.measurable_mk, (ae_smul_measure_iff hc).2 h.ae_eq_mk⟩⟩ lemma ae_measurable_of_ae_measurable_trim {α} {m m0 : measurable_space α} {μ : measure α} (hm : m ≤ m0) {f : α → β} (hf : ae_measurable f (μ.trim hm)) : ae_measurable f μ := ⟨hf.mk f, measurable.mono hf.measurable_mk hm le_rfl, ae_eq_of_ae_eq_trim hf.ae_eq_mk⟩ lemma ae_measurable_restrict_of_measurable_subtype {s : set α} (hs : measurable_set s) (hf : measurable (λ x : s, f x)) : ae_measurable f (μ.restrict s) := (ae_measurable_restrict_iff_comap_subtype hs).2 hf.ae_measurable lemma ae_measurable_map_equiv_iff (e : α ≃ᵐ β) {f : β → γ} : ae_measurable f (μ.map e) ↔ ae_measurable (f ∘ e) μ := e.measurable_embedding.ae_measurable_map_iff end lemma ae_measurable.restrict (hfm : ae_measurable f μ) {s} : ae_measurable f (μ.restrict s) := ⟨ae_measurable.mk f hfm, hfm.measurable_mk, ae_restrict_of_ae hfm.ae_eq_mk⟩ lemma ae_measurable_Ioi_of_forall_Ioc {β} {mβ : measurable_space β} [linear_order α] [(at_top : filter α).is_countably_generated] {x : α} {g : α → β} (g_meas : ∀ t > x, ae_measurable g (μ.restrict (Ioc x t))) : ae_measurable g (μ.restrict (Ioi x)) := begin haveI : nonempty α := ⟨x⟩, haveI : (at_top : filter α).ne_bot := at_top_ne_bot, obtain ⟨u, hu_tendsto⟩ := exists_seq_tendsto (at_top : filter α), have Ioi_eq_Union : Ioi x = ⋃ n : ℕ, Ioc x (u n), { rw Union_Ioc_eq_Ioi_self_iff.mpr _, rw tendsto_at_top_at_top at hu_tendsto, exact λ y _, ⟨(hu_tendsto y).some, (hu_tendsto y).some_spec (hu_tendsto y).some le_rfl⟩, }, rw [Ioi_eq_Union, ae_measurable_Union_iff], intros n, cases lt_or_le x (u n), { exact g_meas (u n) h, }, { rw Ioc_eq_empty (not_lt.mpr h), simp only [measure.restrict_empty], exact ae_measurable_zero_measure, }, end variables [has_zero β] lemma ae_measurable_indicator_iff {s} (hs : measurable_set s) : ae_measurable (indicator s f) μ ↔ ae_measurable f (μ.restrict s) := begin split, { intro h, exact (h.mono_measure measure.restrict_le_self).congr (indicator_ae_eq_restrict hs) }, { intro h, refine ⟨indicator s (h.mk f), h.measurable_mk.indicator hs, _⟩, have A : s.indicator f =ᵐ[μ.restrict s] s.indicator (ae_measurable.mk f h) := (indicator_ae_eq_restrict hs).trans (h.ae_eq_mk.trans $ (indicator_ae_eq_restrict hs).symm), have B : s.indicator f =ᵐ[μ.restrict sᶜ] s.indicator (ae_measurable.mk f h) := (indicator_ae_eq_restrict_compl hs).trans (indicator_ae_eq_restrict_compl hs).symm, exact ae_of_ae_restrict_of_ae_restrict_compl _ A B }, end @[measurability] lemma ae_measurable.indicator (hfm : ae_measurable f μ) {s} (hs : measurable_set s) : ae_measurable (s.indicator f) μ := (ae_measurable_indicator_iff hs).mpr hfm.restrict lemma measure_theory.measure.restrict_map_of_ae_measurable {f : α → δ} (hf : ae_measurable f μ) {s : set δ} (hs : measurable_set s) : (μ.map f).restrict s = (μ.restrict $ f ⁻¹' s).map f := calc (μ.map f).restrict s = (μ.map (hf.mk f)).restrict s : by { congr' 1, apply measure.map_congr hf.ae_eq_mk } ... = (μ.restrict $ (hf.mk f) ⁻¹' s).map (hf.mk f) : measure.restrict_map hf.measurable_mk hs ... = (μ.restrict $ (hf.mk f) ⁻¹' s).map f : measure.map_congr (ae_restrict_of_ae (hf.ae_eq_mk.symm)) ... = (μ.restrict $ f ⁻¹' s).map f : begin apply congr_arg, ext1 t ht, simp only [ht, measure.restrict_apply], apply measure_congr, apply (eventually_eq.refl _ _).inter (hf.ae_eq_mk.symm.preimage s) end lemma measure_theory.measure.map_mono_of_ae_measurable {f : α → δ} (h : μ ≤ ν) (hf : ae_measurable f ν) : μ.map f ≤ ν.map f := λ s hs, by simpa [hf, hs, hf.mono_measure h] using measure.le_iff'.1 h (f ⁻¹' s)
a4136dd9f34104a92270fad94da9a2f8b2bbc768
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/idempotents/biproducts.lean
88c8757c3259c95e847febec138e0b9621c629e4
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
6,016
lean
/- Copyright (c) 2022 Joël Riou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joël Riou -/ import category_theory.idempotents.karoubi /-! # Biproducts in the idempotent completion of a preadditive category > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file, we define an instance expressing that if `C` is an additive category (i.e. is preadditive and has finite biproducts), then `karoubi C` is also an additive category. We also obtain that for all `P : karoubi C` where `C` is a preadditive category `C`, there is a canonical isomorphism `P ⊞ P.complement ≅ (to_karoubi C).obj P.X` in the category `karoubi C` where `P.complement` is the formal direct factor of `P.X` corresponding to the idempotent endomorphism `𝟙 P.X - P.p`. -/ noncomputable theory open category_theory.category open category_theory.limits open category_theory.preadditive universes v namespace category_theory namespace idempotents namespace karoubi variables {C : Type*} [category.{v} C] [preadditive C] namespace biproducts /-- The `bicone` used in order to obtain the existence of the biproduct of a functor `J ⥤ karoubi C` when the category `C` is additive. -/ @[simps] def bicone [has_finite_biproducts C] {J : Type} [fintype J] (F : J → karoubi C) : bicone F := { X := { X := biproduct (λ j, (F j).X), p := biproduct.map (λ j, (F j).p), idem := begin ext j, simp only [biproduct.ι_map_assoc, biproduct.ι_map], slice_lhs 1 2 { rw (F j).idem, }, end, }, π := λ j, { f := biproduct.map (λ j, (F j).p) ≫ bicone.π _ j, comm := by simp only [assoc, biproduct.bicone_π, biproduct.map_π, biproduct.map_π_assoc, (F j).idem], }, ι := λ j, { f := (by exact bicone.ι _ j) ≫ biproduct.map (λ j, (F j).p), comm := by rw [biproduct.ι_map, ← assoc, ← assoc, (F j).idem, assoc, biproduct.ι_map, ← assoc, (F j).idem], }, ι_π := λ j j', begin split_ifs, { subst h, simp only [assoc, idem, biproduct.map_π, biproduct.map_π_assoc, eq_to_hom_refl, id_eq, hom_ext, comp_f, biproduct.ι_π_self_assoc], }, { simp only [biproduct.ι_π_ne_assoc _ h, assoc, biproduct.map_π, biproduct.map_π_assoc, hom_ext, comp_f, zero_comp, quiver.hom.add_comm_group_zero_f], }, end, } end biproducts lemma karoubi_has_finite_biproducts [has_finite_biproducts C] : has_finite_biproducts (karoubi C) := { out := λ n, { has_biproduct := λ F, begin classical, apply has_biproduct_of_total (biproducts.bicone F), ext1, ext1, simp only [id_eq, comp_id, biproducts.bicone_X_p, biproduct.ι_map], rw [sum_hom, comp_sum, finset.sum_eq_single j], rotate, { intros j' h1 h2, simp only [biproduct.ι_map, biproducts.bicone_ι_f, biproducts.bicone_π_f, assoc, comp_f, biproduct.map_π], slice_lhs 1 2 { rw biproduct.ι_π, }, split_ifs, { exfalso, exact h2 h.symm, }, { simp only [zero_comp], } }, { intro h, exfalso, simpa only [finset.mem_univ, not_true] using h, }, { simp only [biproducts.bicone_π_f, comp_f, biproduct.ι_map, assoc, biproducts.bicone_ι_f, biproduct.map_π], slice_lhs 1 2 { rw biproduct.ι_π, }, split_ifs, swap, { exfalso, exact h rfl, }, simp only [eq_to_hom_refl, id_comp, (F j).idem], }, end, } } attribute [instance] karoubi_has_finite_biproducts /-- `P.complement` is the formal direct factor of `P.X` given by the idempotent endomorphism `𝟙 P.X - P.p` -/ @[simps] def complement (P : karoubi C) : karoubi C := { X := P.X, p := 𝟙 _ - P.p, idem := idem_of_id_sub_idem P.p P.idem, } instance (P : karoubi C) : has_binary_biproduct P P.complement := has_binary_biproduct_of_total { X := P.X, fst := P.decomp_id_p, snd := P.complement.decomp_id_p, inl := P.decomp_id_i, inr := P.complement.decomp_id_i, inl_fst' := P.decomp_id.symm, inl_snd' := begin simp only [decomp_id_i_f, decomp_id_p_f, complement_p, comp_sub, comp_f, hom_ext, quiver.hom.add_comm_group_zero_f, P.idem], erw [comp_id, sub_self], end, inr_fst' := begin simp only [decomp_id_i_f, complement_p, decomp_id_p_f, sub_comp, comp_f, hom_ext, quiver.hom.add_comm_group_zero_f, P.idem], erw [id_comp, sub_self], end, inr_snd' := P.complement.decomp_id.symm, } (by simp only [hom_ext, ← decomp_p, quiver.hom.add_comm_group_add_f, to_karoubi_map_f, id_eq, coe_p, complement_p, add_sub_cancel'_right]) /-- A formal direct factor `P : karoubi C` of an object `P.X : C` in a preadditive category is actually a direct factor of the image `(to_karoubi C).obj P.X` of `P.X` in the category `karoubi C` -/ def decomposition (P : karoubi C) : P ⊞ P.complement ≅ (to_karoubi _).obj P.X := { hom := biprod.desc P.decomp_id_i P.complement.decomp_id_i, inv := biprod.lift P.decomp_id_p P.complement.decomp_id_p, hom_inv_id' := begin ext1, { simp only [← assoc, biprod.inl_desc, comp_id, biprod.lift_eq, comp_add, ← decomp_id, id_comp, add_right_eq_self], convert zero_comp, ext, simp only [decomp_id_i_f, decomp_id_p_f, complement_p, comp_sub, comp_f, quiver.hom.add_comm_group_zero_f, P.idem], erw [comp_id, sub_self], }, { simp only [← assoc, biprod.inr_desc, biprod.lift_eq, comp_add, ← decomp_id, comp_id, id_comp, add_left_eq_self], convert zero_comp, ext, simp only [decomp_id_i_f, decomp_id_p_f, complement_p, sub_comp, comp_f, quiver.hom.add_comm_group_zero_f, P.idem], erw [id_comp, sub_self], } end, inv_hom_id' := begin rw biprod.lift_desc, simp only [← decomp_p], ext, dsimp only [complement, to_karoubi], simp only [quiver.hom.add_comm_group_add_f, add_sub_cancel'_right, id_eq], end, } end karoubi end idempotents end category_theory
9168329b0e74828a404ef2b2a3c55a0a3b216b64
6d50885e7b3f72447a03f21d5268d6af87c0a404
/instructor-notes/2019.10.14.prop_logic/myreverse.lean
871d514acac20666611d0e05b769cf9ba5f8dde8
[]
no_license
kevinsullivan/uva-cs-dm-s20-old
583c756cded281fcee7f1afc42cb3e08f89c2493
797672cb0ffae6a42a3518c9225d5807191fd113
refs/heads/master
1,607,500,914,982
1,578,752,991,000
1,578,752,991,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
290
lean
def app {α : Type} : list α → list α → list α | list.nil l := l | (list.cons h t) l := list.cons h (app t l) def rev {α : Type} : list α → list α | list.nil := list.nil | (list.cons h t) := app (rev t) (list.cons h list.nil) --list.cons (rev t) h #reduce rev [1,2,3,4,5,6]
7081d7d50ddaa23496152135d945b5e0b2f5b194
7cef822f3b952965621309e88eadf618da0c8ae9
/src/topology/algebra/module.lean
32c01063d79c3e6979558a1f84e665df8a83c130
[ "Apache-2.0" ]
permissive
rmitta/mathlib
8d90aee30b4db2b013e01f62c33f297d7e64a43d
883d974b608845bad30ae19e27e33c285200bf84
refs/heads/master
1,585,776,832,544
1,576,874,096,000
1,576,874,096,000
153,663,165
0
2
Apache-2.0
1,544,806,490,000
1,539,884,365,000
Lean
UTF-8
Lean
false
false
13,917
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jan-David Salchow, Sébastien Gouëzel, Jean Lo -/ import topology.algebra.ring linear_algebra.basic ring_theory.algebra /-! # Theory of topological modules and continuous linear maps. We define classes `topological_semimodule`, `topological_module` and `topological_vector_spaces`, as extensions of the corresponding algebraic classes where the algebraic operations are continuous. We also define continuous linear maps, as linear maps between topological modules which are continuous. The set of continuous linear maps between the topological `α`-modules `β` and `γ` is denoted by `β →L[α] γ`. ## Implementation notes Topological vector spaces are defined as an `abbreviation` for topological modules, if the base ring is a field. This has as advantage that topological vector spaces are completely transparent for type class inference, which means that all instances for topological modules are immediately picked up for vector spaces as well. A cosmetic disadvantage is that one can not extend topological vector spaces. The solution is to extend `topological_module` instead. -/ open topological_space universes u v w u' section prio set_option default_priority 100 -- see Note [default priority] /-- A topological semimodule, over a semiring which is also a topological space, is a semimodule in which scalar multiplication is continuous. In applications, α will be a topological semiring and β a topological additive semigroup, but this is not needed for the definition -/ class topological_semimodule (α : Type u) (β : Type v) [semiring α] [topological_space α] [topological_space β] [add_comm_monoid β] [semimodule α β] : Prop := (continuous_smul : continuous (λp : α × β, p.1 • p.2)) end prio section variables {α : Type u} {β : Type v} [semiring α] [topological_space α] [topological_space β] [add_comm_monoid β] [semimodule α β] [topological_semimodule α β] lemma continuous_smul : continuous (λp:α×β, p.1 • p.2) := topological_semimodule.continuous_smul α β lemma continuous.smul {γ : Type*} [topological_space γ] {f : γ → α} {g : γ → β} (hf : continuous f) (hg : continuous g) : continuous (λp, f p • g p) := continuous_smul.comp (hf.prod_mk hg) end section prio set_option default_priority 100 -- see Note [default priority] /-- A topological module, over a ring which is also a topological space, is a module in which scalar multiplication is continuous. In applications, α will be a topological ring and β a topological additive group, but this is not needed for the definition -/ class topological_module (α : Type u) (β : Type v) [ring α] [topological_space α] [topological_space β] [add_comm_group β] [module α β] extends topological_semimodule α β : Prop /-- A topological vector space is a topological module over a field. -/ abbreviation topological_vector_space (α : Type u) (β : Type v) [discrete_field α] [topological_space α] [topological_space β] [add_comm_group β] [module α β] := topological_module α β end prio section variables {α : Type*} {β : Type*} [ring α] [topological_space α] [topological_space β] [add_comm_group β] [module α β] [topological_module α β] /-- Scalar multiplication by a unit is a homeomorphism from a topological module onto itself. -/ protected def homeomorph.smul_of_unit (a : units α) : β ≃ₜ β := { to_fun := λ x, (a : α) • x, inv_fun := λ x, ((a⁻¹ : units α) : α) • x, right_inv := λ x, calc (a : α) • ((a⁻¹ : units α) : α) • x = x : by rw [smul_smul, units.mul_inv, one_smul], left_inv := λ x, calc ((a⁻¹ : units α) : α) • (a : α) • x = x : by rw [smul_smul, units.inv_mul, one_smul], continuous_to_fun := continuous_const.smul continuous_id, continuous_inv_fun := continuous_const.smul continuous_id } lemma is_open_map_smul_of_unit (a : units α) : is_open_map (λ (x : β), (a : α) • x) := (homeomorph.smul_of_unit a).is_open_map lemma is_closed_map_smul_of_unit (a : units α) : is_closed_map (λ (x : β), (a : α) • x) := (homeomorph.smul_of_unit a).is_closed_map end section variables {α : Type*} {β : Type*} {a : α} [discrete_field α] [topological_space α] [topological_space β] [add_comm_group β] [vector_space α β] [topological_vector_space α β] set_option class.instance_max_depth 36 /-- Scalar multiplication by a non-zero field element is a homeomorphism from a topological vector space onto itself. -/ protected def homeomorph.smul_of_ne_zero (ha : a ≠ 0) : β ≃ₜ β := {.. homeomorph.smul_of_unit ((equiv.units_equiv_ne_zero _).inv_fun ⟨_, ha⟩)} lemma is_open_map_smul_of_ne_zero (ha : a ≠ 0) : is_open_map (λ (x : β), a • x) := (homeomorph.smul_of_ne_zero ha).is_open_map lemma is_closed_map_smul_of_ne_zero (ha : a ≠ 0) : is_closed_map (λ (x : β), a • x) := (homeomorph.smul_of_ne_zero ha).is_closed_map end /-- Continuous linear maps between modules. We only put the type classes that are necessary for the definition, although in applications β and γ will be topological modules over the topological ring α -/ structure continuous_linear_map (α : Type*) [ring α] (β : Type*) [topological_space β] [add_comm_group β] (γ : Type*) [topological_space γ] [add_comm_group γ] [module α β] [module α γ] extends linear_map α β γ := (cont : continuous to_fun) notation β ` →L[`:25 α `] ` γ := continuous_linear_map α β γ namespace continuous_linear_map section general_ring /- Properties that hold for non-necessarily commutative rings. -/ variables {α : Type*} [ring α] {β : Type*} [topological_space β] [add_comm_group β] {γ : Type*} [topological_space γ] [add_comm_group γ] {δ : Type*} [topological_space δ] [add_comm_group δ] [module α β] [module α γ] [module α δ] /-- Coerce continuous linear maps to linear maps. -/ instance : has_coe (β →L[α] γ) (β →ₗ[α] γ) := ⟨to_linear_map⟩ protected lemma continuous (f : β →L[α] γ) : continuous f := f.2 /-- Coerce continuous linear maps to functions. -/ instance to_fun : has_coe_to_fun $ β →L[α] γ := ⟨_, λ f, f.to_fun⟩ @[ext] theorem ext {f g : β →L[α] γ} (h : ∀ x, f x = g x) : f = g := by cases f; cases g; congr' 1; ext x; apply h theorem ext_iff {f g : β →L[α] γ} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, by rw h, by ext⟩ variables (c : α) (f g : β →L[α] γ) (h : γ →L[α] δ) (x y z : β) -- make some straightforward lemmas available to `simp`. @[simp] lemma map_zero : f (0 : β) = 0 := (to_linear_map _).map_zero @[simp] lemma map_add : f (x + y) = f x + f y := (to_linear_map _).map_add _ _ @[simp] lemma map_sub : f (x - y) = f x - f y := (to_linear_map _).map_sub _ _ @[simp] lemma map_smul : f (c • x) = c • f x := (to_linear_map _).map_smul _ _ @[simp] lemma map_neg : f (-x) = - (f x) := (to_linear_map _).map_neg _ @[simp, squash_cast] lemma coe_coe : ((f : β →ₗ[α] γ) : (β → γ)) = (f : β → γ) := rfl /-- The continuous map that is constantly zero. -/ def zero : β →L[α] γ := ⟨0, by exact continuous_const⟩ instance: has_zero (β →L[α] γ) := ⟨zero⟩ @[simp] lemma zero_apply : (0 : β →L[α] γ) x = 0 := rfl @[simp, elim_cast] lemma coe_zero : ((0 : β →L[α] γ) : β →ₗ[α] γ) = 0 := rfl /- no simp attribute on the next line as simp does not always simplify 0 x to x when 0 is the zero function, while it does for the zero continuous linear map, and this is the most important property we care about. -/ @[elim_cast] lemma coe_zero' : ((0 : β →L[α] γ) : β → γ) = 0 := rfl /-- the identity map as a continuous linear map. -/ def id : β →L[α] β := ⟨linear_map.id, continuous_id⟩ instance : has_one (β →L[α] β) := ⟨id⟩ @[simp] lemma id_apply : (id : β →L[α] β) x = x := rfl @[simp, elim_cast] lemma coe_id : ((id : β →L[α] β) : β →ₗ[α] β) = linear_map.id := rfl @[simp, elim_cast] lemma coe_id' : ((id : β →L[α] β) : β → β) = _root_.id := rfl @[simp] lemma one_apply : (1 : β →L[α] β) x = x := rfl section add variables [topological_add_group γ] instance : has_add (β →L[α] γ) := ⟨λ f g, ⟨f + g, f.2.add g.2⟩⟩ @[simp] lemma add_apply : (f + g) x = f x + g x := rfl @[simp, move_cast] lemma coe_add : (((f + g) : β →L[α] γ) : β →ₗ[α] γ) = (f : β →ₗ[α] γ) + g := rfl @[move_cast] lemma coe_add' : (((f + g) : β →L[α] γ) : β → γ) = (f : β → γ) + g := rfl instance : has_neg (β →L[α] γ) := ⟨λ f, ⟨-f, f.2.neg⟩⟩ @[simp] lemma neg_apply : (-f) x = - (f x) := rfl @[simp, move_cast] lemma coe_neg : (((-f) : β →L[α] γ) : β →ₗ[α] γ) = -(f : β →ₗ[α] γ) := rfl @[move_cast] lemma coe_neg' : (((-f) : β →L[α] γ) : β → γ) = -(f : β → γ) := rfl instance : add_comm_group (β →L[α] γ) := by refine {zero := 0, add := (+), neg := has_neg.neg, ..}; intros; ext; simp @[simp] lemma sub_apply (x : β) : (f - g) x = f x - g x := rfl @[simp, move_cast] lemma coe_sub : (((f - g) : β →L[α] γ) : β →ₗ[α] γ) = (f : β →ₗ[α] γ) - g := rfl @[simp, move_cast] lemma coe_sub' : (((f - g) : β →L[α] γ) : β → γ) = (f : β → γ) - g := rfl end add /-- Composition of bounded linear maps. -/ def comp (g : γ →L[α] δ) (f : β →L[α] γ) : β →L[α] δ := ⟨linear_map.comp g.to_linear_map f.to_linear_map, g.2.comp f.2⟩ @[simp, move_cast] lemma coe_comp : ((h.comp f) : (β →ₗ[α] δ)) = (h : γ →ₗ[α] δ).comp f := rfl @[simp, move_cast] lemma coe_comp' : ((h.comp f) : (β → δ)) = (h : γ → δ) ∘ f := rfl @[simp] theorem comp_id : f.comp id = f := ext $ λ x, rfl @[simp] theorem id_comp : id.comp f = f := ext $ λ x, rfl @[simp] theorem comp_zero : f.comp (0 : δ →L[α] β) = 0 := by { ext, simp } @[simp] theorem zero_comp : (0 : γ →L[α] δ).comp f = 0 := by { ext, simp } @[simp] lemma comp_add [topological_add_group γ] [topological_add_group δ] (g : γ →L[α] δ) (f₁ f₂ : β →L[α] γ) : g.comp (f₁ + f₂) = g.comp f₁ + g.comp f₂ := by { ext, simp } @[simp] lemma add_comp [topological_add_group δ] (g₁ g₂ : γ →L[α] δ) (f : β →L[α] γ) : (g₁ + g₂).comp f = g₁.comp f + g₂.comp f := by { ext, simp } instance : has_mul (β →L[α] β) := ⟨comp⟩ instance [topological_add_group β] : ring (β →L[α] β) := { mul := (*), one := 1, mul_one := λ _, ext $ λ _, rfl, one_mul := λ _, ext $ λ _, rfl, mul_assoc := λ _ _ _, ext $ λ _, rfl, left_distrib := λ _ _ _, ext $ λ _, map_add _ _ _, right_distrib := λ _ _ _, ext $ λ _, linear_map.add_apply _ _ _, ..continuous_linear_map.add_comm_group } /-- The cartesian product of two bounded linear maps, as a bounded linear map. -/ def prod (f₁ : β →L[α] γ) (f₂ : β →L[α] δ) : β →L[α] (γ × δ) := { cont := f₁.2.prod_mk f₂.2, ..f₁.to_linear_map.prod f₂.to_linear_map } end general_ring section comm_ring variables {α : Type*} [comm_ring α] [topological_space α] {β : Type*} [topological_space β] [add_comm_group β] {γ : Type*} [topological_space γ] [add_comm_group γ] {δ : Type*} [topological_space δ] [add_comm_group δ] [module α β] [module α γ] [module α δ] [topological_module α δ] instance : has_scalar α (β →L[α] δ) := ⟨λ c f, ⟨c • f, continuous_const.smul f.2⟩⟩ variables (c : α) (h : γ →L[α] δ) (f g : β →L[α] γ) (x y z : β) @[simp] lemma smul_comp : (c • h).comp f = c • (h.comp f) := rfl variable [topological_module α γ] @[simp] lemma smul_apply : (c • f) x = c • (f x) := rfl @[simp, move_cast] lemma coe_apply : (((c • f) : β →L[α] γ) : β →ₗ[α] γ) = c • (f : β →ₗ[α] γ) := rfl @[move_cast] lemma coe_apply' : (((c • f) : β →L[α] γ) : β → γ) = c • (f : β → γ) := rfl @[simp] lemma comp_smul : h.comp (c • f) = c • (h.comp f) := by { ext, simp } /-- The linear map `λ x, c x • f`. Associates to a scalar-valued linear map and an element of `γ` the `γ`-valued linear map obtained by multiplying the two (a.k.a. tensoring by `γ`) -/ def smul_right (c : β →L[α] α) (f : γ) : β →L[α] γ := { cont := c.2.smul continuous_const, ..c.to_linear_map.smul_right f } @[simp] lemma smul_right_apply {c : β →L[α] α} {f : γ} {x : β} : (smul_right c f : β → γ) x = (c : β → α) x • f := rfl @[simp] lemma smul_right_one_one (c : α →L[α] γ) : smul_right 1 ((c : α → γ) 1) = c := by ext; simp [-continuous_linear_map.map_smul, (continuous_linear_map.map_smul _ _ _).symm] @[simp] lemma smul_right_one_eq_iff {f f' : γ} : smul_right (1 : α →L[α] α) f = smul_right 1 f' ↔ f = f' := ⟨λ h, have (smul_right (1 : α →L[α] α) f : α → γ) 1 = (smul_right (1 : α →L[α] α) f' : α → γ) 1, by rw h, by simp at this; assumption, by cc⟩ variable [topological_add_group γ] instance : module α (β →L[α] γ) := { smul_zero := λ _, ext $ λ _, smul_zero _, zero_smul := λ _, ext $ λ _, zero_smul _ _, one_smul := λ _, ext $ λ _, one_smul _ _, mul_smul := λ _ _ _, ext $ λ _, mul_smul _ _ _, add_smul := λ _ _ _, ext $ λ _, add_smul _ _ _, smul_add := λ _ _ _, ext $ λ _, smul_add _ _ _ } set_option class.instance_max_depth 55 instance : is_ring_hom (λ c : α, c • (1 : γ →L[α] γ)) := { map_one := one_smul _ _, map_add := λ _ _, ext $ λ _, add_smul _ _ _, map_mul := λ _ _, ext $ λ _, mul_smul _ _ _ } instance : algebra α (γ →L[α] γ) := { to_fun := λ c, c • 1, smul_def' := λ _ _, rfl, commutes' := λ _ _, ext $ λ _, map_smul _ _ _ } end comm_ring end continuous_linear_map
df23d68bc1c0b5c871467e693860b82002cbd565
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/periodic.lean
987bef4bdd16bcf6c1cd67da481e4d65ab7f518f
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
18,169
lean
/- Copyright (c) 2021 Benjamin Davidson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Benjamin Davidson -/ import algebra.field.opposite import algebra.module.basic import algebra.order.archimedean import data.int.parity import group_theory.coset /-! # Periodicity In this file we define and then prove facts about periodic and antiperiodic functions. ## Main definitions * `function.periodic`: A function `f` is *periodic* if `∀ x, f (x + c) = f x`. `f` is referred to as periodic with period `c` or `c`-periodic. * `function.antiperiodic`: A function `f` is *antiperiodic* if `∀ x, f (x + c) = -f x`. `f` is referred to as antiperiodic with antiperiod `c` or `c`-antiperiodic. Note that any `c`-antiperiodic function will necessarily also be `2*c`-periodic. ## Tags period, periodic, periodicity, antiperiodic -/ variables {α β γ : Type*} {f g : α → β} {c c₁ c₂ x : α} open_locale big_operators namespace function /-! ### Periodicity -/ /-- A function `f` is said to be `periodic` with period `c` if for all `x`, `f (x + c) = f x`. -/ @[simp] def periodic [has_add α] (f : α → β) (c : α) : Prop := ∀ x : α, f (x + c) = f x lemma periodic.funext [has_add α] (h : periodic f c) : (λ x, f (x + c)) = f := funext h lemma periodic.comp [has_add α] (h : periodic f c) (g : β → γ) : periodic (g ∘ f) c := by simp * at * lemma periodic.comp_add_hom [has_add α] [has_add γ] (h : periodic f c) (g : add_hom γ α) (g_inv : α → γ) (hg : right_inverse g_inv g) : periodic (f ∘ g) (g_inv c) := λ x, by simp only [hg c, h (g x), add_hom.map_add, comp_app] @[to_additive] lemma periodic.mul [has_add α] [has_mul β] (hf : periodic f c) (hg : periodic g c) : periodic (f * g) c := by simp * at * @[to_additive] lemma periodic.div [has_add α] [has_div β] (hf : periodic f c) (hg : periodic g c) : periodic (f / g) c := by simp * at * @[to_additive] lemma _root_.list.periodic_prod [has_add α] [comm_monoid β] (l : list (α → β)) (hl : ∀ f ∈ l, periodic f c) : periodic l.prod c := begin induction l with g l ih hl, { simp, }, { simp only [list.mem_cons_iff, forall_eq_or_imp] at hl, obtain ⟨hg, hl⟩ := hl, simp only [list.prod_cons], exact hg.mul (ih hl), }, end @[to_additive] lemma _root_.multiset.periodic_prod [has_add α] [comm_monoid β] (s : multiset (α → β)) (hs : ∀ f ∈ s, periodic f c) : periodic s.prod c := s.prod_to_list ▸ s.to_list.periodic_prod $ λ f hf, hs f $ (multiset.mem_to_list f s).mp hf @[to_additive] lemma _root_.finset.periodic_prod [has_add α] [comm_monoid β] {ι : Type*} {f : ι → α → β} (s : finset ι) (hs : ∀ i ∈ s, periodic (f i) c) : periodic (∏ i in s, f i) c := s.prod_to_list f ▸ (s.to_list.map f).periodic_prod (by simpa [-periodic]) @[to_additive] lemma periodic.smul [has_add α] [has_scalar γ β] (h : periodic f c) (a : γ) : periodic (a • f) c := by simp * at * lemma periodic.const_smul [add_monoid α] [group γ] [distrib_mul_action γ α] (h : periodic f c) (a : γ) : periodic (λ x, f (a • x)) (a⁻¹ • c) := λ x, by simpa only [smul_add, smul_inv_smul] using h (a • x) lemma periodic.const_smul₀ [add_comm_monoid α] [division_ring γ] [module γ α] (h : periodic f c) (a : γ) : periodic (λ x, f (a • x)) (a⁻¹ • c) := begin intro x, by_cases ha : a = 0, { simp only [ha, zero_smul] }, simpa only [smul_add, smul_inv_smul₀ ha] using h (a • x), end lemma periodic.const_mul [division_ring α] (h : periodic f c) (a : α) : periodic (λ x, f (a * x)) (a⁻¹ * c) := h.const_smul₀ a lemma periodic.const_inv_smul [add_monoid α] [group γ] [distrib_mul_action γ α] (h : periodic f c) (a : γ) : periodic (λ x, f (a⁻¹ • x)) (a • c) := by simpa only [inv_inv] using h.const_smul a⁻¹ lemma periodic.const_inv_smul₀ [add_comm_monoid α] [division_ring γ] [module γ α] (h : periodic f c) (a : γ) : periodic (λ x, f (a⁻¹ • x)) (a • c) := by simpa only [inv_inv] using h.const_smul₀ a⁻¹ lemma periodic.const_inv_mul [division_ring α] (h : periodic f c) (a : α) : periodic (λ x, f (a⁻¹ * x)) (a * c) := h.const_inv_smul₀ a lemma periodic.mul_const [division_ring α] (h : periodic f c) (a : α) : periodic (λ x, f (x * a)) (c * a⁻¹) := h.const_smul₀ $ mul_opposite.op a lemma periodic.mul_const' [division_ring α] (h : periodic f c) (a : α) : periodic (λ x, f (x * a)) (c / a) := by simpa only [div_eq_mul_inv] using h.mul_const a lemma periodic.mul_const_inv [division_ring α] (h : periodic f c) (a : α) : periodic (λ x, f (x * a⁻¹)) (c * a) := h.const_inv_smul₀ $ mul_opposite.op a lemma periodic.div_const [division_ring α] (h : periodic f c) (a : α) : periodic (λ x, f (x / a)) (c * a) := by simpa only [div_eq_mul_inv] using h.mul_const_inv a lemma periodic.add_period [add_semigroup α] (h1 : periodic f c₁) (h2 : periodic f c₂) : periodic f (c₁ + c₂) := by simp [*, ← add_assoc] at * lemma periodic.sub_eq [add_group α] (h : periodic f c) (x : α) : f (x - c) = f x := by simpa only [sub_add_cancel] using (h (x - c)).symm lemma periodic.sub_eq' [add_comm_group α] (h : periodic f c) : f (c - x) = f (-x) := by simpa only [sub_eq_neg_add] using h (-x) lemma periodic.neg [add_group α] (h : periodic f c) : periodic f (-c) := by simpa only [sub_eq_add_neg, periodic] using h.sub_eq lemma periodic.sub_period [add_comm_group α] (h1 : periodic f c₁) (h2 : periodic f c₂) : periodic f (c₁ - c₂) := let h := h2.neg in by simp [*, sub_eq_add_neg, add_comm c₁, ← add_assoc] at * lemma periodic.nsmul [add_monoid α] (h : periodic f c) (n : ℕ) : periodic f (n • c) := by induction n; simp [nat.succ_eq_add_one, add_nsmul, ← add_assoc, zero_nsmul, *] at * lemma periodic.nat_mul [semiring α] (h : periodic f c) (n : ℕ) : periodic f (n * c) := by simpa only [nsmul_eq_mul] using h.nsmul n lemma periodic.neg_nsmul [add_group α] (h : periodic f c) (n : ℕ) : periodic f (-(n • c)) := (h.nsmul n).neg lemma periodic.neg_nat_mul [ring α] (h : periodic f c) (n : ℕ) : periodic f (-(n * c)) := (h.nat_mul n).neg lemma periodic.sub_nsmul_eq [add_group α] (h : periodic f c) (n : ℕ) : f (x - n • c) = f x := by simpa only [sub_eq_add_neg] using h.neg_nsmul n x lemma periodic.sub_nat_mul_eq [ring α] (h : periodic f c) (n : ℕ) : f (x - n * c) = f x := by simpa only [nsmul_eq_mul] using h.sub_nsmul_eq n lemma periodic.nsmul_sub_eq [add_comm_group α] (h : periodic f c) (n : ℕ) : f (n • c - x) = f (-x) := by simpa only [sub_eq_neg_add] using h.nsmul n (-x) lemma periodic.nat_mul_sub_eq [ring α] (h : periodic f c) (n : ℕ) : f (n * c - x) = f (-x) := by simpa only [sub_eq_neg_add] using h.nat_mul n (-x) lemma periodic.zsmul [add_group α] (h : periodic f c) (n : ℤ) : periodic f (n • c) := begin cases n, { simpa only [int.of_nat_eq_coe, coe_nat_zsmul] using h.nsmul n }, { simpa only [zsmul_neg_succ_of_nat] using (h.nsmul n.succ).neg }, end lemma periodic.int_mul [ring α] (h : periodic f c) (n : ℤ) : periodic f (n * c) := by simpa only [zsmul_eq_mul] using h.zsmul n lemma periodic.sub_zsmul_eq [add_group α] (h : periodic f c) (n : ℤ) : f (x - n • c) = f x := (h.zsmul n).sub_eq x lemma periodic.sub_int_mul_eq [ring α] (h : periodic f c) (n : ℤ) : f (x - n * c) = f x := (h.int_mul n).sub_eq x lemma periodic.zsmul_sub_eq [add_comm_group α] (h : periodic f c) (n : ℤ) : f (n • c - x) = f (-x) := by simpa only [sub_eq_neg_add] using h.zsmul n (-x) lemma periodic.int_mul_sub_eq [ring α] (h : periodic f c) (n : ℤ) : f (n * c - x) = f (-x) := by simpa only [sub_eq_neg_add] using h.int_mul n (-x) lemma periodic.eq [add_zero_class α] (h : periodic f c) : f c = f 0 := by simpa only [zero_add] using h 0 lemma periodic.neg_eq [add_group α] (h : periodic f c) : f (-c) = f 0 := h.neg.eq lemma periodic.nsmul_eq [add_monoid α] (h : periodic f c) (n : ℕ) : f (n • c) = f 0 := (h.nsmul n).eq lemma periodic.nat_mul_eq [semiring α] (h : periodic f c) (n : ℕ) : f (n * c) = f 0 := (h.nat_mul n).eq lemma periodic.zsmul_eq [add_group α] (h : periodic f c) (n : ℤ) : f (n • c) = f 0 := (h.zsmul n).eq lemma periodic.int_mul_eq [ring α] (h : periodic f c) (n : ℤ) : f (n * c) = f 0 := (h.int_mul n).eq /-- If a function `f` is `periodic` with positive period `c`, then for all `x` there exists some `y ∈ Ico 0 c` such that `f x = f y`. -/ lemma periodic.exists_mem_Ico₀ [linear_ordered_add_comm_group α] [archimedean α] (h : periodic f c) (hc : 0 < c) (x) : ∃ y ∈ set.Ico 0 c, f x = f y := let ⟨n, H, _⟩ := exists_unique_zsmul_near_of_pos' hc x in ⟨x - n • c, H, (h.sub_zsmul_eq n).symm⟩ /-- If a function `f` is `periodic` with positive period `c`, then for all `x` there exists some `y ∈ Ico a (a + c)` such that `f x = f y`. -/ lemma periodic.exists_mem_Ico [linear_ordered_add_comm_group α] [archimedean α] (h : periodic f c) (hc : 0 < c) (x a) : ∃ y ∈ set.Ico a (a + c), f x = f y := let ⟨n, H, _⟩ := exists_unique_add_zsmul_mem_Ico hc x a in ⟨x + n • c, H, (h.zsmul n x).symm⟩ /-- If a function `f` is `periodic` with positive period `c`, then for all `x` there exists some `y ∈ Ioc a (a + c)` such that `f x = f y`. -/ lemma periodic.exists_mem_Ioc [linear_ordered_add_comm_group α] [archimedean α] (h : periodic f c) (hc : 0 < c) (x a) : ∃ y ∈ set.Ioc a (a + c), f x = f y := let ⟨n, H, _⟩ := exists_unique_add_zsmul_mem_Ioc hc x a in ⟨x + n • c, H, (h.zsmul n x).symm⟩ lemma periodic.image_Ioc [linear_ordered_add_comm_group α] [archimedean α] (h : periodic f c) (hc : 0 < c) (a : α) : f '' set.Ioc a (a + c) = set.range f := (set.image_subset_range _ _).antisymm $ set.range_subset_iff.2 $ λ x, let ⟨y, hy, hyx⟩ := h.exists_mem_Ioc hc x a in ⟨y, hy, hyx.symm⟩ lemma periodic_with_period_zero [add_zero_class α] (f : α → β) : periodic f 0 := λ x, by rw add_zero lemma periodic.map_vadd_zmultiples [add_comm_group α] (hf : periodic f c) (a : add_subgroup.zmultiples c) (x : α) : f (a +ᵥ x) = f x := by { rcases a with ⟨_, m, rfl⟩, simp [add_subgroup.vadd_def, add_comm _ x, hf.zsmul m x] } lemma periodic.map_vadd_multiples [add_comm_monoid α] (hf : periodic f c) (a : add_submonoid.multiples c) (x : α) : f (a +ᵥ x) = f x := by { rcases a with ⟨_, m, rfl⟩, simp [add_submonoid.vadd_def, add_comm _ x, hf.nsmul m x] } /-- Lift a periodic function to a function from the quotient group. -/ def periodic.lift [add_group α] (h : periodic f c) (x : α ⧸ add_subgroup.zmultiples c) : β := quotient.lift_on' x f $ λ a b ⟨k, hk⟩, (h.zsmul k _).symm.trans $ congr_arg f $ add_eq_of_eq_neg_add hk @[simp] lemma periodic.lift_coe [add_group α] (h : periodic f c) (a : α) : h.lift (a : α ⧸ add_subgroup.zmultiples c) = f a := rfl /-! ### Antiperiodicity -/ /-- A function `f` is said to be `antiperiodic` with antiperiod `c` if for all `x`, `f (x + c) = -f x`. -/ @[simp] def antiperiodic [has_add α] [has_neg β] (f : α → β) (c : α) : Prop := ∀ x : α, f (x + c) = -f x lemma antiperiodic.funext [has_add α] [has_neg β] (h : antiperiodic f c) : (λ x, f (x + c)) = -f := funext h lemma antiperiodic.funext' [has_add α] [add_group β] (h : antiperiodic f c) : (λ x, -f (x + c)) = f := (eq_neg_iff_eq_neg.mp h.funext).symm /-- If a function is `antiperiodic` with antiperiod `c`, then it is also `periodic` with period `2 * c`. -/ lemma antiperiodic.periodic [semiring α] [add_group β] (h : antiperiodic f c) : periodic f (2 * c) := by simp [two_mul, ← add_assoc, h _] lemma antiperiodic.eq [add_zero_class α] [has_neg β] (h : antiperiodic f c) : f c = -f 0 := by simpa only [zero_add] using h 0 lemma antiperiodic.nat_even_mul_periodic [semiring α] [add_group β] (h : antiperiodic f c) (n : ℕ) : periodic f (n * (2 * c)) := h.periodic.nat_mul n lemma antiperiodic.nat_odd_mul_antiperiodic [semiring α] [add_group β] (h : antiperiodic f c) (n : ℕ) : antiperiodic f (n * (2 * c) + c) := λ x, by rw [← add_assoc, h, h.periodic.nat_mul] lemma antiperiodic.int_even_mul_periodic [ring α] [add_group β] (h : antiperiodic f c) (n : ℤ) : periodic f (n * (2 * c)) := h.periodic.int_mul n lemma antiperiodic.int_odd_mul_antiperiodic [ring α] [add_group β] (h : antiperiodic f c) (n : ℤ) : antiperiodic f (n * (2 * c) + c) := λ x, by rw [← add_assoc, h, h.periodic.int_mul] lemma antiperiodic.nat_mul_eq_of_eq_zero [comm_semiring α] [add_group β] (h : antiperiodic f c) (hi : f 0 = 0) (n : ℕ) : f (n * c) = 0 := begin rcases nat.even_or_odd n with ⟨k, rfl⟩ | ⟨k, rfl⟩; have hk : (k : α) * (2 * c) = 2 * k * c := by rw [mul_left_comm, ← mul_assoc], { simpa [← two_mul, hk, hi] using (h.nat_even_mul_periodic k).eq }, { simpa [add_mul, hk, hi] using (h.nat_odd_mul_antiperiodic k).eq }, end lemma antiperiodic.int_mul_eq_of_eq_zero [comm_ring α] [add_group β] (h : antiperiodic f c) (hi : f 0 = 0) (n : ℤ) : f (n * c) = 0 := begin rcases int.even_or_odd n with ⟨k, rfl⟩ | ⟨k, rfl⟩; have hk : (k : α) * (2 * c) = 2 * k * c := by rw [mul_left_comm, ← mul_assoc], { simpa [← two_mul, hk, hi] using (h.int_even_mul_periodic k).eq }, { simpa [add_mul, hk, hi] using (h.int_odd_mul_antiperiodic k).eq }, end lemma antiperiodic.sub_eq [add_group α] [add_group β] (h : antiperiodic f c) (x : α) : f (x - c) = -f x := by simp only [eq_neg_iff_eq_neg.mp (h (x - c)), sub_add_cancel] lemma antiperiodic.sub_eq' [add_comm_group α] [add_group β] (h : antiperiodic f c) : f (c - x) = -f (-x) := by simpa only [sub_eq_neg_add] using h (-x) lemma antiperiodic.neg [add_group α] [add_group β] (h : antiperiodic f c) : antiperiodic f (-c) := by simpa only [sub_eq_add_neg, antiperiodic] using h.sub_eq lemma antiperiodic.neg_eq [add_group α] [add_group β] (h : antiperiodic f c) : f (-c) = -f 0 := by simpa only [zero_add] using h.neg 0 lemma antiperiodic.smul [has_add α] [monoid γ] [add_group β] [distrib_mul_action γ β] (h : antiperiodic f c) (a : γ) : antiperiodic (a • f) c := by simp * at * lemma antiperiodic.const_smul [add_monoid α] [has_neg β] [group γ] [distrib_mul_action γ α] (h : antiperiodic f c) (a : γ) : antiperiodic (λ x, f (a • x)) (a⁻¹ • c) := λ x, by simpa only [smul_add, smul_inv_smul] using h (a • x) lemma antiperiodic.const_smul₀ [add_comm_monoid α] [has_neg β] [division_ring γ] [module γ α] (h : antiperiodic f c) {a : γ} (ha : a ≠ 0) : antiperiodic (λ x, f (a • x)) (a⁻¹ • c) := λ x, by simpa only [smul_add, smul_inv_smul₀ ha] using h (a • x) lemma antiperiodic.const_mul [division_ring α] [has_neg β] (h : antiperiodic f c) {a : α} (ha : a ≠ 0) : antiperiodic (λ x, f (a * x)) (a⁻¹ * c) := h.const_smul₀ ha lemma antiperiodic.const_inv_smul [add_monoid α] [has_neg β] [group γ] [distrib_mul_action γ α] (h : antiperiodic f c) (a : γ) : antiperiodic (λ x, f (a⁻¹ • x)) (a • c) := by simpa only [inv_inv] using h.const_smul a⁻¹ lemma antiperiodic.const_inv_smul₀ [add_comm_monoid α] [has_neg β] [division_ring γ] [module γ α] (h : antiperiodic f c) {a : γ} (ha : a ≠ 0) : antiperiodic (λ x, f (a⁻¹ • x)) (a • c) := by simpa only [inv_inv] using h.const_smul₀ (inv_ne_zero ha) lemma antiperiodic.const_inv_mul [division_ring α] [has_neg β] (h : antiperiodic f c) {a : α} (ha : a ≠ 0) : antiperiodic (λ x, f (a⁻¹ * x)) (a * c) := h.const_inv_smul₀ ha lemma antiperiodic.mul_const [division_ring α] [has_neg β] (h : antiperiodic f c) {a : α} (ha : a ≠ 0) : antiperiodic (λ x, f (x * a)) (c * a⁻¹) := h.const_smul₀ $ (mul_opposite.op_ne_zero_iff a).mpr ha lemma antiperiodic.mul_const' [division_ring α] [has_neg β] (h : antiperiodic f c) {a : α} (ha : a ≠ 0) : antiperiodic (λ x, f (x * a)) (c / a) := by simpa only [div_eq_mul_inv] using h.mul_const ha lemma antiperiodic.mul_const_inv [division_ring α] [has_neg β] (h : antiperiodic f c) {a : α} (ha : a ≠ 0) : antiperiodic (λ x, f (x * a⁻¹)) (c * a) := h.const_inv_smul₀ $ (mul_opposite.op_ne_zero_iff a).mpr ha lemma antiperiodic.div_inv [division_ring α] [has_neg β] (h : antiperiodic f c) {a : α} (ha : a ≠ 0) : antiperiodic (λ x, f (x / a)) (c * a) := by simpa only [div_eq_mul_inv] using h.mul_const_inv ha lemma antiperiodic.add [add_group α] [add_group β] (h1 : antiperiodic f c₁) (h2 : antiperiodic f c₂) : periodic f (c₁ + c₂) := by simp [*, ← add_assoc] at * lemma antiperiodic.sub [add_comm_group α] [add_group β] (h1 : antiperiodic f c₁) (h2 : antiperiodic f c₂) : periodic f (c₁ - c₂) := let h := h2.neg in by simp [*, sub_eq_add_neg, add_comm c₁, ← add_assoc] at * lemma periodic.add_antiperiod [add_group α] [add_group β] (h1 : periodic f c₁) (h2 : antiperiodic f c₂) : antiperiodic f (c₁ + c₂) := by simp [*, ← add_assoc] at * lemma periodic.sub_antiperiod [add_comm_group α] [add_group β] (h1 : periodic f c₁) (h2 : antiperiodic f c₂) : antiperiodic f (c₁ - c₂) := let h := h2.neg in by simp [*, sub_eq_add_neg, add_comm c₁, ← add_assoc] at * lemma periodic.add_antiperiod_eq [add_group α] [add_group β] (h1 : periodic f c₁) (h2 : antiperiodic f c₂) : f (c₁ + c₂) = -f 0 := (h1.add_antiperiod h2).eq lemma periodic.sub_antiperiod_eq [add_comm_group α] [add_group β] (h1 : periodic f c₁) (h2 : antiperiodic f c₂) : f (c₁ - c₂) = -f 0 := (h1.sub_antiperiod h2).eq lemma antiperiodic.mul [has_add α] [ring β] (hf : antiperiodic f c) (hg : antiperiodic g c) : periodic (f * g) c := by simp * at * lemma antiperiodic.div [has_add α] [division_ring β] (hf : antiperiodic f c) (hg : antiperiodic g c) : periodic (f / g) c := by simp [*, neg_div_neg_eq] at * end function
81c618073afedfa0a0497875a5d87912ecdee9e8
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
/stage0/src/Lean/Parser/Transform.lean
ac076594741643d543d8c6f0dcaf60ef7a285ffc
[ "Apache-2.0" ]
permissive
dupuisf/lean4
d082d13b01243e1de29ae680eefb476961221eef
6a39c65bd28eb0e28c3870188f348c8914502718
refs/heads/master
1,676,948,755,391
1,610,665,114,000
1,610,665,114,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,686
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.Parser.Basic namespace Lean namespace Syntax def manyToSepBy (stx : Syntax) (sepTk : String) : Syntax := do match stx with | node k args => if args.size == 0 then stx else let mut argsNew := #[args[0]] for i in [1:args.size] do let arg := args[i] let prev := argsNew.back match prev.getTailInfo with | some info => let prevArg := prev.setTailInfo { trailing := none } argsNew := argsNew.set! (argsNew.size - 1) prev argsNew := argsNew.push (atom info sepTk) argsNew := argsNew.push arg | none => argsNew := argsNew.push (atom {} sepTk) argsNew := argsNew.push arg node k argsNew | stx => stx def removeParen (stx : Syntax) : Syntax := stx.ifNodeKind `Lean.Parser.Term.paren (fun stx => let body := stx.getArg 1 if body.getNumArgs != 2 then stx.val else if (body.getArg 1).isNone then let body := body.getArg 0 match stx.getArg 2, body.getTailInfo with | atom { trailing := some outer } ")", some bodyInfo@{ trailing := some inner } => let bodyInfoTrail := inner.toString ++ " " -- add whithespaces for removed parentheses let bodyInfoTrail := bodyInfoTrail ++ outer.toString -- add close paren trailing spaces body.setTailInfo { bodyInfo with trailing := bodyInfoTrail.toSubstring } | _, _ => stx.val else stx.val) (fun _ => stx) end Syntax end Lean
910ab14ad4f68f44cd2cd3d79acc9b966757ddb1
cc060cf567f81c404a13ee79bf21f2e720fa6db0
/lean/20170310-extracting-lemmas.lean
14cf537f00872e093fe963b3e4e7d57900914f45
[ "Apache-2.0" ]
permissive
semorrison/proof
cf0a8c6957153bdb206fd5d5a762a75958a82bca
5ee398aa239a379a431190edbb6022b1a0aa2c70
refs/heads/master
1,610,414,502,842
1,518,696,851,000
1,518,696,851,000
78,375,937
2
1
null
null
null
null
UTF-8
Lean
false
false
3,892
lean
open tactic open smt_tactic meta def blast : tactic unit := using_smt $ intros >> try simp >> try eblast notation `♮` := by abstract { blast } universe variables u v structure Category := (Obj : Type u) (Hom : Obj → Obj → Type v) (identity : Π X : Obj, Hom X X) (compose : Π { X Y Z : Obj }, Hom X Y → Hom Y Z → Hom X Z) (left_identity : ∀ { X Y : Obj } (f : Hom X Y), compose (identity X) f = f) (right_identity : ∀ { X Y : Obj } (f : Hom X Y), compose f (identity Y) = f) (associativity : ∀ { W X Y Z : Obj } (f : Hom W X) (g : Hom X Y) (h : Hom Y Z), compose (compose f g) h = compose f (compose g h)) attribute [ematch,simp] Category.left_identity attribute [ematch,simp] Category.right_identity attribute [ematch] Category.associativity universe variables u1 v1 u2 v2 structure Functor (C : Category.{ u1 v1 }) (D : Category.{ u2 v2 }) := (onObjects : C^.Obj → D^.Obj) (onMorphisms : Π { X Y : C^.Obj }, C^.Hom X Y → D^.Hom (onObjects X) (onObjects Y)) (identities : ∀ (X : C^.Obj), onMorphisms (C^.identity X) = D^.identity (onObjects X)) (functoriality : ∀ { X Y Z : C^.Obj } (f : C^.Hom X Y) (g : C^.Hom Y Z), onMorphisms (C^.compose f g) = D^.compose (onMorphisms f) (onMorphisms g)) attribute [simp,ematch] Functor.identities attribute [simp,ematch] Functor.functoriality instance Functor_to_onObjects { C D : Category }: has_coe_to_fun (Functor C D) := { F := λ f, C^.Obj → D^.Obj, coe := Functor.onObjects } structure NaturalTransformation { C D : Category } ( F G : Functor C D ) := (components: Π X : C^.Obj, D^.Hom (F X) (G X)) (naturality: ∀ { X Y : C^.Obj } (f : C^.Hom X Y), D^.compose (F^.onMorphisms f) (components Y) = D^.compose (components X) (G^.onMorphisms f)) attribute [ematch] NaturalTransformation.naturality instance NaturalTransformation_to_components { C D : Category } { F G : Functor C D } : has_coe_to_fun (NaturalTransformation F G) := { F := λ f, Π X : C^.Obj, D^.Hom (F X) (G X), coe := NaturalTransformation.components } lemma NaturalTransformations_componentwise_equal { C D : Category } { F G : Functor C D } ( α β : NaturalTransformation F G ) ( w : ∀ X : C^.Obj, α X = β X ) : α = β := begin induction α with α_components α_naturality, induction β with β_components β_naturality, have hc : α_components = β_components, from funext w, by subst hc end @[reducible] definition IdentityNaturalTransformation { C D : Category } (F : Functor C D) : NaturalTransformation F F := { components := λ X, D^.identity (F X), naturality := ♮ } @[reducible] definition vertical_composition_of_NaturalTransformations { C D : Category } { F G H : Functor C D } ( α : NaturalTransformation F G ) ( β : NaturalTransformation G H ) : NaturalTransformation F H := { components := λ X, D^.compose (α X) (β X), naturality := ♮ } definition FunctorCategory ( C D : Category ) : Category := { Obj := Functor C D, Hom := λ F G, NaturalTransformation F G, identity := λ F, IdentityNaturalTransformation F, compose := @vertical_composition_of_NaturalTransformations C D, left_identity := begin blast, apply NaturalTransformations_componentwise_equal, blast end, right_identity := begin blast, apply NaturalTransformations_componentwise_equal, blast end, associativity := begin blast, apply NaturalTransformations_componentwise_equal, blast end } -- TODO This is pure boilerplate! How can we automatically form this lemma? Ideally we'd just annotate a field of FunctorCategory! @[simp] lemma FunctorCategory_left_identity ( C D : Category ) ( F G : Functor C D ) ( α : NaturalTransformation F G ) : vertical_composition_of_NaturalTransformations (IdentityNaturalTransformation F) α = α := (FunctorCategory C D)^.left_identity α
3456203ea7889047a1442431087e0380e35fbd65
f4bff2062c030df03d65e8b69c88f79b63a359d8
/kb_solns/sets_level06.lean
9ad4045db461d5b798f887d9f998364e8cda8683
[ "Apache-2.0" ]
permissive
adastra7470/real-number-game
776606961f52db0eb824555ed2f8e16f92216ea3
f9dcb7d9255a79b57e62038228a23346c2dc301b
refs/heads/master
1,669,221,575,893
1,594,669,800,000
1,594,669,800,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,235
lean
import game.sets.sets_level05 -- hide import tactic -- hide namespace xena -- hide variable X : Type /- # Chapter 1 : Sets ## Level 6 -/ /- See if you can prove the identity below using the `ext` tactic. Applying `ext,` with no arguments will apply as many *extensionality* lemmas as Lean can find. The following extensionality theorems can be found in mathlib. -/ /- Hint : Propositional Extensionality `constant propext {a b : Prop} : (a ↔ b) → a = b` If two propositions imply one another, then those two propositions are equal. Here `constant` indicates that this is not just a theorem but an axiom. Curly braces indicate that the arguments of `propext` may be left implicit and inferred from context. -/ /- Hint : Function Extensionality `theorem funext {f₁ f₂ : Π x : α, β x} (h : ∀ x, f₁ x = f₂ x) : f₁ = f₂.` If two functions agree on all arguments, then those functions are equal. -/ /- Hint : Set Extensionality `theorem ext_iff {s t : set α} : s = t ↔ ∀ x, x ∈ s ↔ x ∈ t` Two sets are equal if and only if they contain the same elements. -/ /- For example, `ext` will reduce a goal `S = T` to a goal `∀x (x ∈ S ↔ x ∈ T)`. This makes `ext` especially useful for proving identities. For this level, you need to know that the *complement* of a set `A` is denoted `-A` (usually $A^{c}$ in textbooks). It is the set of all elements *not* in `A`. In Lean this is defined in terms of a universal set `univ` containing all and only the elements of the domain (here, all members of X). Given two sets `A` and `B`, the *set difference* `A \ B` is the set of all elements that are in `A` but not in `B`. -/ /- Hint : Hint : A goal of `x ∈ -A` is definitionally equal to a goal of `x ∉ A`. -/ /- Lemma If $A$ and $B$ are sets with elements of type $X$, then $$(A \setminus B) = A \cap B^{c}.$$ -/ theorem setdiff_eq_intersect_comp (A B : set X) : A \ B = A ∩ -B := begin ext, split, { intro h1, split, { cases h1 with p q, exact p }, { cases h1 with p q, exact q, } }, { intro h2, exact h2 } end end xena -- hide
89a3fc5613f2b9cdb529bcd6f0d2ebd95bf21351
abd677583c7e4d55daf9487b82da11b7c5498d8d
/src/fol.lean
ade9390c9296f6e70396d72f091c8d9300079351
[ "Apache-2.0" ]
permissive
jesse-michael-han/embed
e9c346918ad58e03933bdaa057a571c0cc4a7641
c2fc188328e871e18e0dcb8258c6d0462c70a8c9
refs/heads/master
1,584,677,705,005
1,528,451,877,000
1,528,451,877,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,390
lean
import .prop namespace fol variable {α : Type} class is_symb (α : Type) extends prop.is_symb α := (fa : α) (ex : α) inductive symb : Type | fn : string → symb | prd : string → symb | true : symb | false : symb | not : symb | and : symb | or : symb | imp : symb | fa : symb | ex : symb instance : decidable_eq symb := by tactic.mk_dec_eq_instance instance : is_symb symb := { true := symb.true, false := symb.false, not := symb.not, and := symb.and, or := symb.or, imp := symb.imp, fa := symb.fa, ex := symb.ex } def fa [is_symb α] (p : exp α) := exp.app (exp.cst (is_symb.fa α)) (exp.lam p) notation `∀'` p := fa p def ex [is_symb α] (p : exp α) := exp.app (exp.cst (is_symb.ex α)) (exp.lam p) notation `∃'` p := ex p def pred (P : string) (args : list (exp symb)) : exp symb := list.foldl exp.app (exp.cst (symb.prd P)) args def func (F : string) (args : list (exp symb)) : exp symb := list.foldl exp.app (exp.cst (symb.fn F)) args inductive inf [is_symb α] : list (seq α) → seq α → Prop | prop : ∀ S s, prop.inf S s → inf S s | fal : ∀ t Γ Δ p, inf [(inst t p)::Γ ==> Δ] ((∀' p)::Γ ==> Δ) | far : ∀ k Γ Δ p, k ∉ fvrs_list Γ → k ∉ fvrs_list Δ → inf [Γ ==> (inst (exp.fvr α k) p)::Δ] (Γ ==> (∀' p)::Δ) | exl : ∀ k Γ Δ p, k ∉ fvrs_list Γ → k ∉ fvrs_list Δ → inf [(inst (exp.fvr α k) p)::Γ ==> Δ] ((∃' p)::Γ ==> Δ) | exr : ∀ t Γ Δ p, inf [Γ ==> (inst t p)::Δ] (Γ ==> (∃' p)::Δ) inductive thm [is_symb α] : (seq α) → Prop | inf : ∀ {s S}, inf S s → (∀ s' ∈ S, thm s') → thm s /- Derived rules -/ open list lemma thm.id [is_symb α] : ∀ (Γ Δ : list (exp α)) p, thm (p::Γ ==> p::Δ) := begin intros Γ Δ p, apply thm.inf, apply inf.prop, apply prop.inf.id, apply forall_mem_nil end lemma thm.truer [is_symb α] : ∀ (Γ Δ : list (exp α)), thm (Γ ==> ⊤'::Δ) := begin intros Γ Δ, apply thm.inf, apply inf.prop, apply prop.inf.truer, apply forall_mem_nil end lemma thm.falsel [is_symb α] : ∀ (Γ Δ : list (exp α)), thm (⊥'::Γ ==> Δ) := begin intros Γ Δ, apply thm.inf, apply inf.prop, apply prop.inf.falsel, apply forall_mem_nil end lemma thm.andl [is_symb α] : ∀ (Γ Δ : list (exp α)) p q, thm ((p ∧' q)::Γ ==> Δ) → thm (p::q::Γ ==> Δ) := begin intros Γ Δ p q h, apply thm.inf, apply inf.prop, apply prop.inf.andl, rewrite forall_mem_singleton, apply h end lemma thm.andr [is_symb α] : ∀ (Γ Δ : list (exp α)) p q, thm (Γ ==> p::Δ) → thm (Γ ==> q::Δ) → thm (Γ ==> (p ∧' q)::Δ) := begin intros Γ Δ p q h1 h2, apply thm.inf, apply inf.prop, apply prop.inf.andr, intros s hs, rewrite mem_cons_iff at hs, cases hs with hs hs, rewrite hs, apply h1, rewrite mem_singleton at hs, rewrite hs, apply h2 end lemma thm.orl [is_symb α] : ∀ (Γ Δ : list (exp α)) p q, thm (p::Γ ==> Δ) → thm (q::Γ ==> Δ) → thm ((p ∨' q)::Γ ==> Δ) := begin intros Γ Δ p q h1 h2, apply thm.inf, apply inf.prop, apply prop.inf.orl, intros s hs, rewrite mem_cons_iff at hs, cases hs with hs hs, rewrite hs, apply h1, rewrite mem_singleton at hs, rewrite hs, apply h2 end lemma thm.orr [is_symb α] : ∀ (Γ Δ : list (exp α)) p q, thm (Γ ==> p::q::Δ) → thm (Γ ==> (p ∨' q)::Δ) := begin intros Γ Δ p q h, apply thm.inf, apply inf.prop, apply prop.inf.orr, rewrite forall_mem_singleton, apply h end lemma thm.impl [is_symb α] : ∀ (Γ Δ : list (exp α)) p q, thm (Γ ==> p::Δ) → thm (q::Γ ==> Δ) → thm ((p →' q)::Γ ==> Δ) := begin intros Γ Δ p q h1 h2, apply thm.inf, apply inf.prop, apply prop.inf.impl, intros s hs, rewrite mem_cons_iff at hs, cases hs with hs hs, rewrite hs, apply h1, rewrite mem_singleton at hs, rewrite hs, apply h2 end lemma thm.impr [is_symb α] : ∀ (Γ Δ : list (exp α)) p q, thm (p::Γ ==> q::Δ) → thm (Γ ==> (p →' q)::Δ) := begin intros Γ Δ p q h, apply thm.inf, apply inf.prop, apply prop.inf.impr, rewrite forall_mem_singleton, apply h end lemma thm.wl [is_symb α] : ∀ (Γ Δ : list (exp α)) p, thm (Γ ==> Δ) → thm (p::Γ ==> Δ) := begin intros Γ Δ p h, apply thm.inf, apply inf.prop, apply prop.inf.wl, rewrite forall_mem_singleton, apply h end lemma thm.wr [is_symb α] : ∀ (Γ Δ : list (exp α)) p, thm (Γ ==> Δ) → thm (Γ ==> p::Δ) := begin intros Γ Δ p h, apply thm.inf, apply inf.prop, apply prop.inf.wr, rewrite forall_mem_singleton, apply h end lemma thm.cl [is_symb α] : ∀ (Γ Δ : list (exp α)) p, thm (p::p::Γ ==> Δ) → thm (p::Γ ==> Δ) := begin intros Γ Δ p h, apply thm.inf, apply inf.prop, apply prop.inf.cl, rewrite forall_mem_singleton, apply h end lemma thm.cr [is_symb α] : ∀ (Γ Δ : list (exp α)) p, thm (Γ ==> p::p::Δ) → thm (Γ ==> p::Δ) := begin intros Γ Δ p h, apply thm.inf, apply inf.prop, apply prop.inf.cr, rewrite forall_mem_singleton, apply h end lemma thm.rl [is_symb α] : ∀ n (Γ Δ : list (exp α)), thm (rotate n Γ ==> Δ) → thm (Γ ==> Δ) := begin intros n Γ Δ h, apply thm.inf, apply inf.prop, apply prop.inf.pl (rotate n Γ), apply perm_rotate, intros s' hs', rewrite list.mem_singleton at hs', rewrite hs', apply h end lemma thm.rr [is_symb α] : ∀ n (Γ Δ : list (exp α)), thm (Γ ==> rotate n Δ) → thm (Γ ==> Δ) := begin intros n Γ Δ h, apply thm.inf, apply inf.prop, apply prop.inf.pr _ (rotate n Δ), apply perm_rotate, intros s' hs', rewrite list.mem_singleton at hs', rewrite hs', apply h end lemma thm.fal [is_symb α] : ∀ t (Γ Δ : list (exp α)) p, thm ((inst t p)::Γ ==> Δ) → thm ((∀' p)::Γ ==> Δ) := begin intros t Γ Δ p h, apply thm.inf, apply inf.fal t, rewrite list.forall_mem_singleton, apply h end lemma thm.far [is_symb α] : ∀ k (Γ Δ : list (exp α)) p, k ∉ fvrs_list Γ → k ∉ fvrs_list Δ → thm (Γ ==> (inst (exp.fvr α k) p)::Δ) → thm (Γ ==> (∀' p)::Δ) := begin intros k Γ Δ p h1 h2 h3, apply thm.inf, apply inf.far k; try {assumption}, rewrite list.forall_mem_singleton, apply h3 end lemma thm.exl [is_symb α] : ∀ k (Γ Δ : list (exp α)) p, k ∉ fvrs_list Γ → k ∉ fvrs_list Δ → thm ((inst (exp.fvr α k) p)::Γ ==> Δ) → thm ((∃' p)::Γ ==> Δ) := begin intros k Γ Δ p h1 h2 h3, apply thm.inf, apply inf.exl k; try {assumption}, rewrite list.forall_mem_singleton, apply h3 end lemma thm.exr [is_symb α] : ∀ t (Γ Δ : list (exp α)) p, thm (Γ ==> (inst t p)::Δ) → thm (Γ ==> (∃' p)::Δ) := begin intros t Γ Δ p h, apply thm.inf, apply inf.exr t, rewrite list.forall_mem_singleton, apply h end open tactic meta def apply_exl (n : nat) : tactic unit := do to_expr ``(thm.exl %%(`(n))) >>= apply, dec_triv_tac, dec_triv_tac meta def apply_far (n : nat) : tactic unit := do to_expr ``(thm.far %%(`(n))) >>= apply, dec_triv_tac, dec_triv_tac /- Printing -/ open expr meta def getsqt : tactic (list (exp symb) × list (exp symb)) := do `(thm (%%Γe ==> %%Δe)) ← tactic.target, Γ ← eval_expr (list (exp symb)) Γe, Δ ← eval_expr (list (exp symb)) Δe, return (Γ,Δ) def fml2str : exp symb → string | (exp.app (exp.app e p) q) := if e = exp.cst (prop.is_symb.and symb) then "(" ++ fml2str p ++ " ∧ " ++ fml2str q ++ ")" else if e = exp.cst (prop.is_symb.or symb) then "(" ++ fml2str p ++ " ∨ " ++ fml2str q ++ ")" else if e = exp.cst (prop.is_symb.imp symb) then "(" ++ fml2str p ++ " → " ++ fml2str q ++ ")" else fml2str (exp.app e p) ++ " " ++ fml2str q | (exp.app e1 e2) := fml2str e1 ++ " " ++ fml2str e2 | (exp.lam e) := fml2str e | (exp.cst s) := if s = prop.is_symb.true symb then "⊤" else if s = prop.is_symb.false symb then "⊥" else match s with | (symb.fa) := "∀" | (symb.ex) := "∃" | (symb.not) := "¬" | (symb.prd str) := str | (symb.fn str) := str | _ := "ERROR 1" end | (exp.bvr _ n) := "#" ++ to_string n | (exp.fvr _ n) := "&" ++ to_string n meta def showgoal : tactic unit := (do (Γ,Δ) ← getsqt, trace (sqt2str fml2str Γ Δ)) <|> trace "No Goals" /- Examples -/ example : thm ([] ==> [∀' (pred "P" [# 0]) →' ∃' (pred "P" [# 0])]) := begin showgoal, apply thm.impr, apply thm.fal (& 0), apply thm.exr (& 0), apply thm.id, showgoal end example : thm ([∃' (pred "P" [# 0] ∨' pred "Q" [# 0])] ==> [∃' (pred "P" [# 0]) ∨' ∃' (pred "Q" [# 0])]) := begin showgoal, apply_exl 0, apply thm.orr, apply thm.orl, apply thm.exr (& 0), apply thm.id, apply thm.rr 1, apply thm.exr (& 0), apply thm.id, showgoal end example : thm ([∀' (pred "P" [# 0]), ∀' ((pred "P" [# 0]) →' (pred "Q" [# 0]))] ==> [∀' (pred "Q" [# 0])]) := begin showgoal, apply_far 0, apply thm.fal (& 0), apply thm.rl 1, apply thm.fal (& 0), apply thm.impl, apply thm.id, apply thm.id, showgoal end example : thm ([∀' (pred "P" [# 0]), (pred "P" [& 0]) →' ((pred "P" [& 1]) →' (pred "Q" []))] ==> [pred "Q" []]) := begin showgoal, apply thm.rl 1, apply thm.impl, apply thm.fal (& 0), apply thm.id, apply thm.impl, apply thm.fal (& 1), apply thm.id, apply thm.id, showgoal end end fol
b148bc688e6fe51753b1729e0122c29e9f46bd3c
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/fintype/sigma.lean
17ca0c138b29750e6a50241aed5de84a4b916830
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
867
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 data.fintype.basic import data.finset.sigma /-! # fintype instances for sigma types -/ open function open_locale nat universes u v variables {α β γ : Type*} open finset function instance {α : Type*} (β : α → Type*) [fintype α] [∀ a, fintype (β a)] : fintype (sigma β) := ⟨univ.sigma (λ _, univ), λ ⟨a, b⟩, by simp⟩ @[simp] lemma finset.univ_sigma_univ {α : Type*} {β : α → Type*} [fintype α] [∀ a, fintype (β a)] : (univ : finset α).sigma (λ a, (univ : finset (β a))) = univ := rfl instance psigma.fintype {α : Type*} {β : α → Type*} [fintype α] [∀ a, fintype (β a)] : fintype (Σ' a, β a) := fintype.of_equiv _ (equiv.psigma_equiv_sigma _).symm
86fa8324dce5ef8f4908344fe8cdaf8b4ae4abad
86f6f4f8d827a196a32bfc646234b73328aeb306
/examples/logic/unnamed_2016.lean
7afb204c4662517e0b967634030fa3a0a17ce1b6
[]
no_license
jamescheuk91/mathematics_in_lean
09f1f87d2b0dce53464ff0cbe592c568ff59cf5e
4452499264e2975bca2f42565c0925506ba5dda3
refs/heads/master
1,679,716,410,967
1,613,957,947,000
1,613,957,947,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
247
lean
import tactic -- BEGIN example {m n k : ℕ} (h : m ∣ n ∨ m ∣ k) : m ∣ n * k := begin rcases h with ⟨a, rfl⟩ | ⟨b, rfl⟩, { rw [mul_assoc], apply dvd_mul_right }, rw [mul_comm, mul_assoc], apply dvd_mul_right end -- END
a490468ee4af5d9f4690722b53e6ff0fab953c38
82e44445c70db0f03e30d7be725775f122d72f3e
/src/measure_theory/prod_group.lean
7f553a4158b93317765e6a670977cca600f633d1
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
11,092
lean
/- Copyright (c) 2021 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import measure_theory.prod import measure_theory.group /-! # Measure theory in the product of groups In this file we show properties about measure theory in products of topological groups and properties of iterated integrals in topological groups. These lemmas show the uniqueness of left invariant measures on locally compact groups, up to scaling. In this file we follow the proof and refer to the book *Measure Theory* by Paul Halmos. The idea of the proof is to use the translation invariance of measures to prove `μ(F) = c * μ(E)` for two sets `E` and `F`, where `c` is a constant that does not depend on `μ`. Let `e` and `f` be the characteristic functions of `E` and `F`. Assume that `μ` and `ν` are left-invariant measures. Then the map `(x, y) ↦ (y * x, x⁻¹)` preserves the measure `μ.prod ν`, which means that ``` ∫ x, ∫ y, h x y ∂ν ∂μ = ∫ x, ∫ y, h (y * x) x⁻¹ ∂ν ∂μ ``` If we apply this to `h x y := e x * f y⁻¹ / ν ((λ h, h * y⁻¹) ⁻¹' E)`, we can rewrite the RHS to `μ(F)`, and the LHS to `c * μ(E)`, where `c = c(ν)` does not depend on `μ`. Applying this to `μ` and to `ν` gives `μ (F) / μ (E) = ν (F) / ν (E)`, which is the uniqueness up to scalar multiplication. The proof in [Halmos] seems to contain an omission in §60 Th. A, see `measure_theory.measure_lintegral_div_measure` and https://math.stackexchange.com/questions/3974485/does-right-translation-preserve-finiteness-for-a-left-invariant-measure -/ noncomputable theory open topological_space set (hiding prod_eq) function open_locale classical ennreal namespace measure_theory open measure variables {G : Type*} [topological_space G] [measurable_space G] [second_countable_topology G] variables [borel_space G] [group G] [topological_group G] variables {μ ν : measure G} [sigma_finite ν] [sigma_finite μ] /-- This condition is part of the definition of a measurable group in [Halmos, §59]. There, the map in this lemma is called `S`. -/ @[to_additive map_prod_sum_eq] lemma map_prod_mul_eq (hν : is_mul_left_invariant ν) : map (λ z : G × G, (z.1, z.1 * z.2)) (μ.prod ν) = μ.prod ν := begin refine (prod_eq _).symm, intros s t hs ht, simp_rw [map_apply (measurable_fst.prod_mk (measurable_fst.mul measurable_snd)) (hs.prod ht), prod_apply ((measurable_fst.prod_mk (measurable_fst.mul measurable_snd)) (hs.prod ht)), preimage_preimage], conv_lhs { congr, skip, funext, rw [mk_preimage_prod_right_fn_eq_if ((*) x), measure_if] }, simp_rw [hν _ ht, lintegral_indicator _ hs, set_lintegral_const, mul_comm] end /-- The function we are mapping along is `SR` in [Halmos, §59], where `S` is the map in `map_prod_mul_eq` and `R` is `prod.swap`. -/ @[to_additive map_prod_add_eq_swap] lemma map_prod_mul_eq_swap (hμ : is_mul_left_invariant μ) : map (λ z : G × G, (z.2, z.2 * z.1)) (μ.prod ν) = ν.prod μ := begin rw [← prod_swap], simp_rw [map_map (measurable_snd.prod_mk (measurable_snd.mul measurable_fst)) measurable_swap], exact map_prod_mul_eq hμ end /-- The function we are mapping along is `S⁻¹` in [Halmos, §59], where `S` is the map in `map_prod_mul_eq`. -/ @[to_additive map_prod_neg_add_eq] lemma map_prod_inv_mul_eq (hν : is_mul_left_invariant ν) : map (λ z : G × G, (z.1, z.1⁻¹ * z.2)) (μ.prod ν) = μ.prod ν := (homeomorph.shear_mul_right G).to_measurable_equiv.map_apply_eq_iff_map_symm_apply_eq.mp $ map_prod_mul_eq hν /-- The function we are mapping along is `S⁻¹R` in [Halmos, §59], where `S` is the map in `map_prod_mul_eq` and `R` is `prod.swap`. -/ @[to_additive map_prod_neg_add_eq_swap] lemma map_prod_inv_mul_eq_swap (hμ : is_mul_left_invariant μ) : map (λ z : G × G, (z.2, z.2⁻¹ * z.1)) (μ.prod ν) = ν.prod μ := begin rw [← prod_swap], simp_rw [map_map (measurable_snd.prod_mk $ measurable_snd.inv.mul measurable_fst) measurable_swap], exact map_prod_inv_mul_eq hμ end /-- The function we are mapping along is `S⁻¹RSR` in [Halmos, §59], where `S` is the map in `map_prod_mul_eq` and `R` is `prod.swap`. -/ @[to_additive map_prod_add_neg_eq] lemma map_prod_mul_inv_eq (hμ : is_mul_left_invariant μ) (hν : is_mul_left_invariant ν) : map (λ z : G × G, (z.2 * z.1, z.1⁻¹)) (μ.prod ν) = μ.prod ν := begin let S := (homeomorph.shear_mul_right G).to_measurable_equiv, suffices : map ((λ z : G × G, (z.2, z.2⁻¹ * z.1)) ∘ (λ z : G × G, (z.2, z.2 * z.1))) (μ.prod ν) = μ.prod ν, { convert this, ext1 ⟨x, y⟩, simp }, simp_rw [← map_map (measurable_snd.prod_mk (measurable_snd.inv.mul measurable_fst)) (measurable_snd.prod_mk (measurable_snd.mul measurable_fst)), map_prod_mul_eq_swap hμ, map_prod_inv_mul_eq_swap hν] end @[to_additive] lemma measure_null_of_measure_inv_null (hμ : is_mul_left_invariant μ) {E : set G} (hE : measurable_set E) (h2E : μ ((λ x, x⁻¹) ⁻¹' E) = 0) : μ E = 0 := begin have hf : measurable (λ z : G × G, (z.2 * z.1, z.1⁻¹)) := (measurable_snd.mul measurable_fst).prod_mk measurable_fst.inv, suffices : map (λ z : G × G, (z.2 * z.1, z.1⁻¹)) (μ.prod μ) (E.prod E) = 0, { simpa only [map_prod_mul_inv_eq hμ hμ, prod_prod hE hE, mul_eq_zero, or_self] using this }, simp_rw [map_apply hf (hE.prod hE), prod_apply_symm (hf (hE.prod hE)), preimage_preimage, mk_preimage_prod], convert lintegral_zero, ext1 x, refine measure_mono_null (inter_subset_right _ _) h2E end @[to_additive] lemma measure_inv_null (hμ : is_mul_left_invariant μ) {E : set G} (hE : measurable_set E) : μ ((λ x, x⁻¹) ⁻¹' E) = 0 ↔ μ E = 0 := begin refine ⟨measure_null_of_measure_inv_null hμ hE, _⟩, intro h2E, apply measure_null_of_measure_inv_null hμ (measurable_inv hE), convert h2E using 2, exact set.inv_inv end @[to_additive] lemma measurable_measure_mul_right {E : set G} (hE : measurable_set E) : measurable (λ x, μ ((λ y, y * x) ⁻¹' E)) := begin suffices : measurable (λ y, μ ((λ x, (x, y)) ⁻¹' ((λ z : G × G, (1, z.1 * z.2)) ⁻¹' set.prod univ E))), { convert this, ext1 x, congr' 1 with y : 1, simp }, apply measurable_measure_prod_mk_right, exact measurable_const.prod_mk (measurable_fst.mul measurable_snd) (measurable_set.univ.prod hE) end @[to_additive] lemma lintegral_lintegral_mul_inv (hμ : is_mul_left_invariant μ) (hν : is_mul_left_invariant ν) (f : G → G → ℝ≥0∞) (hf : ae_measurable (uncurry f) (μ.prod ν)) : ∫⁻ x, ∫⁻ y, f (y * x) x⁻¹ ∂ν ∂μ = ∫⁻ x, ∫⁻ y, f x y ∂ν ∂μ := begin have h : measurable (λ z : G × G, (z.2 * z.1, z.1⁻¹)) := (measurable_snd.mul measurable_fst).prod_mk measurable_fst.inv, have h2f : ae_measurable (uncurry $ λ x y, f (y * x) x⁻¹) (μ.prod ν), { apply hf.comp_measurable' h (map_prod_mul_inv_eq hμ hν).absolutely_continuous }, simp_rw [lintegral_lintegral h2f, lintegral_lintegral hf], conv_rhs { rw [← map_prod_mul_inv_eq hμ hν] }, symmetry, exact lintegral_map' (hf.mono' (map_prod_mul_inv_eq hμ hν).absolutely_continuous) h, end @[to_additive] lemma measure_mul_right_null (hμ : is_mul_left_invariant μ) {E : set G} (hE : measurable_set E) (y : G) : μ ((λ x, x * y) ⁻¹' E) = 0 ↔ μ E = 0 := begin rw [← measure_inv_null hμ hE, ← hμ y⁻¹ (measurable_inv hE), ← measure_inv_null hμ (measurable_mul_const y hE)], convert iff.rfl using 3, ext x, simp, end @[to_additive] lemma measure_mul_right_ne_zero (hμ : is_mul_left_invariant μ) {E : set G} (hE : measurable_set E) (h2E : μ E ≠ 0) (y : G) : μ ((λ x, x * y) ⁻¹' E) ≠ 0 := (not_iff_not_of_iff (measure_mul_right_null hμ hE y)).mpr h2E /-- A technical lemma relating two different measures. This is basically [Halmos, §60 Th. A]. Note that if `f` is the characteristic function of a measurable set `F` this states that `μ F = c * μ E` for a constant `c` that does not depend on `μ`. There seems to be a gap in the last step of the proof in [Halmos]. In the last line, the equality `g(x⁻¹)ν(Ex⁻¹) = f(x)` holds if we can prove that `0 < ν(Ex⁻¹) < ∞`. The first inequality follows from §59, Th. D, but I couldn't find the second inequality. For this reason, we use a compact `E` instead of a measurable `E` as in [Halmos], and additionally assume that `ν` is a regular measure (we only need that it is finite on compact sets). -/ @[to_additive] lemma measure_lintegral_div_measure [t2_space G] (hμ : is_mul_left_invariant μ) (hν : is_mul_left_invariant ν) [regular ν] {E : set G} (hE : is_compact E) (h2E : ν E ≠ 0) (f : G → ℝ≥0∞) (hf : measurable f) : μ E * ∫⁻ y, f y⁻¹ / ν ((λ h, h * y⁻¹) ⁻¹' E) ∂ν = ∫⁻ x, f x ∂μ := begin have Em := hE.measurable_set, symmetry, set g := λ y, f y⁻¹ / ν ((λ h, h * y⁻¹) ⁻¹' E), have hg : measurable g := (hf.comp measurable_inv).div ((measurable_measure_mul_right Em).comp measurable_inv), rw [← set_lintegral_one, ← lintegral_indicator _ Em, ← lintegral_lintegral_mul (measurable_const.indicator Em).ae_measurable hg.ae_measurable, ← lintegral_lintegral_mul_inv hμ hν], swap, { exact (((measurable_const.indicator Em).comp measurable_fst).mul (hg.comp measurable_snd)).ae_measurable }, have mE : ∀ x : G, measurable (λ y, ((λ z, z * x) ⁻¹' E).indicator (λ z, (1 : ℝ≥0∞)) y) := λ x, measurable_const.indicator (measurable_mul_const _ Em), have : ∀ x y, E.indicator (λ (z : G), (1 : ℝ≥0∞)) (y * x) = ((λ z, z * x) ⁻¹' E).indicator (λ (b : G), 1) y, { intros x y, symmetry, convert indicator_comp_right (λ y, y * x), ext1 z, refl }, have h3E : ∀ y, ν ((λ x, x * y) ⁻¹' E) ≠ ∞ := λ y, ennreal.lt_top_iff_ne_top.mp (regular.lt_top_of_is_compact $ (homeomorph.mul_right _).compact_preimage.mpr hE), simp_rw [this, lintegral_mul_const _ (mE _), lintegral_indicator _ (measurable_mul_const _ Em), set_lintegral_one, g, inv_inv, ennreal.mul_div_cancel' (measure_mul_right_ne_zero hν Em h2E _) (h3E _)] end /-- This is roughly the uniqueness (up to a scalar) of left invariant Borel measures on a second countable locally compact group. The uniqueness of Haar measure is proven from this in `measure_theory.measure.haar_measure_unique` -/ @[to_additive] lemma measure_mul_measure_eq [t2_space G] (hμ : is_mul_left_invariant μ) (hν : is_mul_left_invariant ν) [regular ν] {E F : set G} (hE : is_compact E) (hF : measurable_set F) (h2E : ν E ≠ 0) : μ E * ν F = ν E * μ F := begin have h1 := measure_lintegral_div_measure hν hν hE h2E (F.indicator (λ x, 1)) (measurable_const.indicator hF), have h2 := measure_lintegral_div_measure hμ hν hE h2E (F.indicator (λ x, 1)) (measurable_const.indicator hF), rw [lintegral_indicator _ hF, set_lintegral_one] at h1 h2, rw [← h1, mul_left_comm, h2], end end measure_theory
727b9a8049c0caf874a190262646480b5b5adbaf
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/data/set/lattice.lean
28812007955e520394a143b7b3318f2d82c7230c
[ "Apache-2.0" ]
permissive
agjftucker/mathlib
d634cd0d5256b6325e3c55bb7fb2403548371707
87fe50de17b00af533f72a102d0adefe4a2285e8
refs/heads/master
1,625,378,131,941
1,599,166,526,000
1,599,166,526,000
160,748,509
0
0
Apache-2.0
1,544,141,789,000
1,544,141,789,000
null
UTF-8
Lean
false
false
45,254
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 -- QUESTION: can make the first argument in ∀ x ∈ a, ... implicit? -/ import order.complete_boolean_algebra import data.sigma.basic import order.galois_connection import order.directed open function tactic set auto universes u v w x y variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} {ι' : Sort y} namespace set instance lattice_set : complete_lattice (set α) := { Sup := λs, {a | ∃ t ∈ s, a ∈ t }, Inf := λs, {a | ∀ t ∈ s, a ∈ t }, le_Sup := assume s t t_in a a_in, ⟨t, ⟨t_in, a_in⟩⟩, Sup_le := assume s t h a ⟨t', ⟨t'_in, a_in⟩⟩, h t' t'_in a_in, le_Inf := assume s t h a a_in t' t'_in, h t' t'_in a_in, Inf_le := assume s t t_in a h, h _ t_in, .. set.boolean_algebra, .. (infer_instance : complete_lattice (α → Prop)) } /-- Image is monotone. See `set.image_image` for the statement in terms of `⊆`. -/ lemma monotone_image {f : α → β} : monotone (image f) := assume s t, assume h : s ⊆ t, image_subset _ h theorem monotone_inter [preorder β] {f g : β → set α} (hf : monotone f) (hg : monotone g) : monotone (λx, f x ∩ g x) := assume b₁ b₂ h, inter_subset_inter (hf h) (hg h) theorem monotone_union [preorder β] {f g : β → set α} (hf : monotone f) (hg : monotone g) : monotone (λx, f x ∪ g x) := assume b₁ b₂ h, union_subset_union (hf h) (hg h) theorem monotone_set_of [preorder α] {p : α → β → Prop} (hp : ∀b, monotone (λa, p a b)) : monotone (λa, {b | p a b}) := assume a a' h b, hp b h section galois_connection variables {f : α → β} protected lemma image_preimage : galois_connection (image f) (preimage f) := assume a b, image_subset_iff /-- `kern_image f s` is the set of `y` such that `f ⁻¹ y ⊆ s` -/ def kern_image (f : α → β) (s : set α) : set β := {y | ∀ ⦃x⦄, f x = y → x ∈ s} protected lemma preimage_kern_image : galois_connection (preimage f) (kern_image f) := assume a b, ⟨ assume h x hx y hy, have f y ∈ a, from hy.symm ▸ hx, h this, assume h x (hx : f x ∈ a), h hx rfl⟩ end galois_connection /- union and intersection over a family of sets indexed by a type -/ /-- Indexed union of a family of sets -/ @[reducible] def Union (s : ι → set β) : set β := supr s /-- Indexed intersection of a family of sets -/ @[reducible] def Inter (s : ι → set β) : set β := infi s notation `⋃` binders `, ` r:(scoped f, Union f) := r notation `⋂` binders `, ` r:(scoped f, Inter f) := r @[simp] theorem mem_Union {x : β} {s : ι → set β} : x ∈ Union s ↔ ∃ i, x ∈ s i := ⟨assume ⟨t, ⟨⟨a, (t_eq : s a = t)⟩, (h : x ∈ t)⟩⟩, ⟨a, t_eq.symm ▸ h⟩, assume ⟨a, h⟩, ⟨s a, ⟨⟨a, rfl⟩, h⟩⟩⟩ /- alternative proof: dsimp [Union, supr, Sup]; simp -/ -- TODO: more rewrite rules wrt forall / existentials and logical connectives -- TODO: also eliminate ∃i, ... ∧ i = t ∧ ... theorem set_of_exists (p : ι → β → Prop) : {x | ∃ i, p i x} = ⋃ i, {x | p i x} := ext $ λ i, mem_Union.symm @[simp] theorem mem_Inter {x : β} {s : ι → set β} : x ∈ Inter s ↔ ∀ i, x ∈ s i := ⟨assume (h : ∀a ∈ {a : set β | ∃i, s i = a}, x ∈ a) a, h (s a) ⟨a, rfl⟩, assume h t ⟨a, (eq : s a = t)⟩, eq ▸ h a⟩ theorem set_of_forall (p : ι → β → Prop) : {x | ∀ i, p i x} = ⋂ i, {x | p i x} := ext $ λ i, mem_Inter.symm theorem Union_subset {s : ι → set β} {t : set β} (h : ∀ i, s i ⊆ t) : (⋃ i, s i) ⊆ t := -- TODO: should be simpler when sets' order is based on lattices @supr_le (set β) _ set.lattice_set _ _ h theorem Union_subset_iff {s : ι → set β} {t : set β} : (⋃ i, s i) ⊆ t ↔ (∀ i, s i ⊆ t) := ⟨assume h i, subset.trans (le_supr s _) h, Union_subset⟩ theorem mem_Inter_of_mem {x : β} {s : ι → set β} : (∀ i, x ∈ s i) → (x ∈ ⋂ i, s i) := mem_Inter.2 theorem subset_Inter {t : set β} {s : ι → set β} (h : ∀ i, t ⊆ s i) : t ⊆ ⋂ i, s i := -- TODO: should be simpler when sets' order is based on lattices @le_infi (set β) _ set.lattice_set _ _ h theorem subset_Union : ∀ (s : ι → set β) (i : ι), s i ⊆ (⋃ i, s i) := le_supr -- This rather trivial consequence is convenient with `apply`, -- and has `i` explicit for this use case. theorem subset_subset_Union {A : set β} {s : ι → set β} (i : ι) (h : A ⊆ s i) : A ⊆ ⋃ (i : ι), s i := subset.trans h (subset_Union s i) theorem Inter_subset : ∀ (s : ι → set β) (i : ι), (⋂ i, s i) ⊆ s i := infi_le lemma Inter_subset_of_subset {s : ι → set α} {t : set α} (i : ι) (h : s i ⊆ t) : (⋂ i, s i) ⊆ t := set.subset.trans (set.Inter_subset s i) h lemma Inter_subset_Inter {s t : ι → set α} (h : ∀ i, s i ⊆ t i) : (⋂ i, s i) ⊆ (⋂ i, t i) := set.subset_Inter $ λ i, set.Inter_subset_of_subset i (h i) lemma Inter_subset_Inter2 {s : ι → set α} {t : ι' → set α} (h : ∀ j, ∃ i, s i ⊆ t j) : (⋂ i, s i) ⊆ (⋂ j, t j) := set.subset_Inter $ λ j, let ⟨i, hi⟩ := h j in Inter_subset_of_subset i hi lemma Inter_set_of (P : ι → α → Prop) : (⋂ i, {x : α | P i x }) = {x : α | ∀ i, P i x} := by { ext, simp } theorem Union_const [nonempty ι] (s : set β) : (⋃ i:ι, s) = s := ext $ by simp theorem Inter_const [nonempty ι] (s : set β) : (⋂ i:ι, s) = s := ext $ by simp @[simp] -- complete_boolean_algebra theorem compl_Union (s : ι → set β) : (⋃ i, s i)ᶜ = (⋂ i, (s i)ᶜ) := ext (by simp) -- classical -- complete_boolean_algebra theorem compl_Inter (s : ι → set β) : (⋂ i, s i)ᶜ = (⋃ i, (s i)ᶜ) := ext (λ x, by simp [not_forall]) -- classical -- complete_boolean_algebra theorem Union_eq_comp_Inter_comp (s : ι → set β) : (⋃ i, s i) = (⋂ i, (s i)ᶜ)ᶜ := by simp [compl_Inter, compl_compl] -- classical -- complete_boolean_algebra theorem Inter_eq_comp_Union_comp (s : ι → set β) : (⋂ i, s i) = (⋃ i, (s i)ᶜ)ᶜ := by simp [compl_compl] theorem inter_Union (s : set β) (t : ι → set β) : s ∩ (⋃ i, t i) = ⋃ i, s ∩ t i := ext $ by simp theorem Union_inter (s : set β) (t : ι → set β) : (⋃ i, t i) ∩ s = ⋃ i, t i ∩ s := ext $ by simp theorem Union_union_distrib (s : ι → set β) (t : ι → set β) : (⋃ i, s i ∪ t i) = (⋃ i, s i) ∪ (⋃ i, t i) := ext $ by simp [exists_or_distrib] theorem Inter_inter_distrib (s : ι → set β) (t : ι → set β) : (⋂ i, s i ∩ t i) = (⋂ i, s i) ∩ (⋂ i, t i) := ext $ by simp [forall_and_distrib] theorem union_Union [nonempty ι] (s : set β) (t : ι → set β) : s ∪ (⋃ i, t i) = ⋃ i, s ∪ t i := by rw [Union_union_distrib, Union_const] theorem Union_union [nonempty ι] (s : set β) (t : ι → set β) : (⋃ i, t i) ∪ s = ⋃ i, t i ∪ s := by rw [Union_union_distrib, Union_const] theorem inter_Inter [nonempty ι] (s : set β) (t : ι → set β) : s ∩ (⋂ i, t i) = ⋂ i, s ∩ t i := by rw [Inter_inter_distrib, Inter_const] theorem Inter_inter [nonempty ι] (s : set β) (t : ι → set β) : (⋂ i, t i) ∩ s = ⋂ i, t i ∩ s := by rw [Inter_inter_distrib, Inter_const] -- classical theorem union_Inter (s : set β) (t : ι → set β) : s ∪ (⋂ i, t i) = ⋂ i, s ∪ t i := ext $ assume x, by simp [forall_or_distrib_left] theorem Union_diff (s : set β) (t : ι → set β) : (⋃ i, t i) \ s = ⋃ i, t i \ s := Union_inter _ _ theorem diff_Union [nonempty ι] (s : set β) (t : ι → set β) : s \ (⋃ i, t i) = ⋂ i, s \ t i := by rw [diff_eq, compl_Union, inter_Inter]; refl theorem diff_Inter (s : set β) (t : ι → set β) : s \ (⋂ i, t i) = ⋃ i, s \ t i := by rw [diff_eq, compl_Inter, inter_Union]; refl lemma directed_on_Union {r} {ι : Sort v} {f : ι → set α} (hd : directed (⊆) f) (h : ∀x, directed_on r (f x)) : directed_on r (⋃x, f x) := by simp only [directed_on, exists_prop, mem_Union, exists_imp_distrib]; exact assume a₁ b₁ fb₁ a₂ b₂ fb₂, let ⟨z, zb₁, zb₂⟩ := hd b₁ b₂, ⟨x, xf, xa₁, xa₂⟩ := h z a₁ (zb₁ fb₁) a₂ (zb₂ fb₂) in ⟨x, ⟨z, xf⟩, xa₁, xa₂⟩ /- bounded unions and intersections -/ theorem mem_bUnion_iff {s : set α} {t : α → set β} {y : β} : y ∈ (⋃ x ∈ s, t x) ↔ ∃ x ∈ s, y ∈ t x := by simp theorem mem_bInter_iff {s : set α} {t : α → set β} {y : β} : y ∈ (⋂ x ∈ s, t x) ↔ ∀ x ∈ s, y ∈ t x := by simp theorem mem_bUnion {s : set α} {t : α → set β} {x : α} {y : β} (xs : x ∈ s) (ytx : y ∈ t x) : y ∈ ⋃ x ∈ s, t x := by simp; exact ⟨x, ⟨xs, ytx⟩⟩ theorem mem_bInter {s : set α} {t : α → set β} {y : β} (h : ∀ x ∈ s, y ∈ t x) : y ∈ ⋂ x ∈ s, t x := by simp; assumption theorem bUnion_subset {s : set α} {t : set β} {u : α → set β} (h : ∀ x ∈ s, u x ⊆ t) : (⋃ x ∈ s, u x) ⊆ t := show (⨆ x ∈ s, u x) ≤ t, -- TODO: should not be necessary when sets' order is based on lattices from supr_le $ assume x, supr_le (h x) theorem subset_bInter {s : set α} {t : set β} {u : α → set β} (h : ∀ x ∈ s, t ⊆ u x) : t ⊆ (⋂ x ∈ s, u x) := subset_Inter $ assume x, subset_Inter $ h x theorem subset_bUnion_of_mem {s : set α} {u : α → set β} {x : α} (xs : x ∈ s) : u x ⊆ (⋃ x ∈ s, u x) := show u x ≤ (⨆ x ∈ s, u x), from le_supr_of_le x $ le_supr _ xs theorem bInter_subset_of_mem {s : set α} {t : α → set β} {x : α} (xs : x ∈ s) : (⋂ x ∈ s, t x) ⊆ t x := show (⨅x ∈ s, t x) ≤ t x, from infi_le_of_le x $ infi_le _ xs theorem bUnion_subset_bUnion_left {s s' : set α} {t : α → set β} (h : s ⊆ s') : (⋃ x ∈ s, t x) ⊆ (⋃ x ∈ s', t x) := bUnion_subset (λ x xs, subset_bUnion_of_mem (h xs)) theorem bInter_subset_bInter_left {s s' : set α} {t : α → set β} (h : s' ⊆ s) : (⋂ x ∈ s, t x) ⊆ (⋂ x ∈ s', t x) := subset_bInter (λ x xs, bInter_subset_of_mem (h xs)) theorem bUnion_subset_bUnion_right {s : set α} {t1 t2 : α → set β} (h : ∀ x ∈ s, t1 x ⊆ t2 x) : (⋃ x ∈ s, t1 x) ⊆ (⋃ x ∈ s, t2 x) := bUnion_subset (λ x xs, subset.trans (h x xs) (subset_bUnion_of_mem xs)) theorem bInter_subset_bInter_right {s : set α} {t1 t2 : α → set β} (h : ∀ x ∈ s, t1 x ⊆ t2 x) : (⋂ x ∈ s, t1 x) ⊆ (⋂ x ∈ s, t2 x) := subset_bInter (λ x xs, subset.trans (bInter_subset_of_mem xs) (h x xs)) theorem bUnion_subset_bUnion {γ : Type*} {s : set α} {t : α → set β} {s' : set γ} {t' : γ → set β} (h : ∀ x ∈ s, ∃ y ∈ s', t x ⊆ t' y) : (⋃ x ∈ s, t x) ⊆ (⋃ y ∈ s', t' y) := begin intros x, simp only [mem_Union], rintros ⟨a, a_in, ha⟩, rcases h a a_in with ⟨c, c_in, hc⟩, exact ⟨c, c_in, hc ha⟩ end theorem bInter_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) := begin intros x x_in, simp only [mem_Inter] at *, exact λ a a_in, h a a_in $ x_in _ (hs a_in) end theorem bInter_mono {s : set α} {t t' : α → set β} (h : ∀ x ∈ s, t x ⊆ t' x) : (⋂ x ∈ s, t x) ⊆ (⋂ x ∈ s, t' x) := bInter_mono' (subset.refl s) h theorem bUnion_mono {s : set α} {t t' : α → set β} (h : ∀ x ∈ s, t x ⊆ t' x) : (⋃ x ∈ s, t x) ⊆ (⋃ x ∈ s, t' x) := bUnion_subset_bUnion (λ x x_in, ⟨x, x_in, h x x_in⟩) theorem bUnion_eq_Union (s : set α) (t : Π x ∈ s, set β) : (⋃ x ∈ s, t x ‹_›) = (⋃ x : s, t x x.2) := supr_subtype' theorem bInter_eq_Inter (s : set α) (t : Π x ∈ s, set β) : (⋂ x ∈ s, t x ‹_›) = (⋂ x : s, t x x.2) := infi_subtype' theorem bInter_empty (u : α → set β) : (⋂ x ∈ (∅ : set α), u x) = univ := show (⨅x ∈ (∅ : set α), u x) = ⊤, -- simplifier should be able to rewrite x ∈ ∅ to false. from infi_emptyset theorem bInter_univ (u : α → set β) : (⋂ x ∈ @univ α, u x) = ⋂ x, u x := infi_univ -- TODO(Jeremy): here is an artifact of the the encoding of bounded intersection: -- without dsimp, the next theorem fails to type check, because there is a lambda -- in a type that needs to be contracted. Using simp [eq_of_mem_singleton xa] also works. @[simp] theorem bInter_singleton (a : α) (s : α → set β) : (⋂ x ∈ ({a} : set α), s x) = s a := show (⨅ x ∈ ({a} : set α), s x) = s a, by simp theorem bInter_union (s t : set α) (u : α → set β) : (⋂ x ∈ s ∪ t, u x) = (⋂ x ∈ s, u x) ∩ (⋂ x ∈ t, u x) := show (⨅ x ∈ s ∪ t, u x) = (⨅ x ∈ s, u x) ⊓ (⨅ x ∈ t, u x), from infi_union -- TODO(Jeremy): simp [insert_eq, bInter_union] doesn't work @[simp] theorem bInter_insert (a : α) (s : set α) (t : α → set β) : (⋂ x ∈ insert a s, t x) = t a ∩ (⋂ x ∈ s, t x) := begin rw insert_eq, simp [bInter_union] end -- TODO(Jeremy): another example of where an annotation is needed theorem bInter_pair (a b : α) (s : α → set β) : (⋂ x ∈ ({a, b} : set α), s x) = s a ∩ s b := by simp [inter_comm] theorem bUnion_empty (s : α → set β) : (⋃ x ∈ (∅ : set α), s x) = ∅ := supr_emptyset theorem bUnion_univ (s : α → set β) : (⋃ x ∈ @univ α, s x) = ⋃ x, s x := supr_univ @[simp] theorem bUnion_singleton (a : α) (s : α → set β) : (⋃ x ∈ ({a} : set α), s x) = s a := supr_singleton @[simp] theorem bUnion_of_singleton (s : set α) : (⋃ x ∈ s, {x}) = s := ext $ by simp theorem bUnion_union (s t : set α) (u : α → set β) : (⋃ x ∈ s ∪ t, u x) = (⋃ x ∈ s, u x) ∪ (⋃ x ∈ t, u x) := supr_union -- TODO(Jeremy): once again, simp doesn't do it alone. @[simp] theorem bUnion_insert (a : α) (s : set α) (t : α → set β) : (⋃ x ∈ insert a s, t x) = t a ∪ (⋃ x ∈ s, t x) := begin rw [insert_eq], simp [bUnion_union] end theorem bUnion_pair (a b : α) (s : α → set β) : (⋃ x ∈ ({a, b} : set α), s x) = s a ∪ s b := by simp [union_comm] @[simp] -- complete_boolean_algebra theorem compl_bUnion (s : set α) (t : α → set β) : (⋃ i ∈ s, t i)ᶜ = (⋂ i ∈ s, (t i)ᶜ) := ext (λ x, by simp) -- classical -- complete_boolean_algebra theorem compl_bInter (s : set α) (t : α → set β) : (⋂ i ∈ s, t i)ᶜ = (⋃ i ∈ s, (t i)ᶜ) := ext (λ x, by simp [not_forall]) theorem inter_bUnion (s : set α) (t : α → set β) (u : set β) : u ∩ (⋃ i ∈ s, t i) = ⋃ i ∈ s, u ∩ t i := begin ext x, simp only [exists_prop, mem_Union, mem_inter_eq], exact ⟨λ ⟨hx, ⟨i, is, xi⟩⟩, ⟨i, is, hx, xi⟩, λ ⟨i, is, hx, xi⟩, ⟨hx, ⟨i, is, xi⟩⟩⟩ end theorem bUnion_inter (s : set α) (t : α → set β) (u : set β) : (⋃ i ∈ s, t i) ∩ u = (⋃ i ∈ s, t i ∩ u) := by simp [@inter_comm _ _ u, inter_bUnion] /-- Intersection of a set of sets. -/ @[reducible] def sInter (S : set (set α)) : set α := Inf S prefix `⋂₀`:110 := sInter theorem mem_sUnion_of_mem {x : α} {t : set α} {S : set (set α)} (hx : x ∈ t) (ht : t ∈ S) : x ∈ ⋃₀ S := ⟨t, ⟨ht, hx⟩⟩ theorem mem_sUnion {x : α} {S : set (set α)} : x ∈ ⋃₀ S ↔ ∃t ∈ S, x ∈ t := iff.rfl -- 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 := λ h, hx ⟨t, ht, h⟩ @[simp] theorem mem_sInter {x : α} {S : set (set α)} : x ∈ ⋂₀ S ↔ ∀ t ∈ S, x ∈ t := iff.rfl theorem sInter_subset_of_mem {S : set (set α)} {t : set α} (tS : t ∈ S) : ⋂₀ S ⊆ t := Inf_le tS theorem subset_sUnion_of_mem {S : set (set α)} {t : set α} (tS : t ∈ S) : t ⊆ ⋃₀ S := le_Sup tS lemma 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 := Sup_le h theorem sUnion_subset_iff {s : set (set α)} {t : set α} : ⋃₀ s ⊆ t ↔ ∀t' ∈ s, t' ⊆ t := ⟨assume h t' ht', subset.trans (subset_sUnion_of_mem ht') h, sUnion_subset⟩ theorem subset_sInter {S : set (set α)} {t : set α} (h : ∀t' ∈ S, t ⊆ t') : t ⊆ (⋂₀ S) := le_Inf h theorem sUnion_subset_sUnion {S T : set (set α)} (h : S ⊆ T) : ⋃₀ S ⊆ ⋃₀ T := sUnion_subset $ λ s hs, subset_sUnion_of_mem (h hs) theorem sInter_subset_sInter {S T : set (set α)} (h : S ⊆ T) : ⋂₀ T ⊆ ⋂₀ S := subset_sInter $ λ s hs, sInter_subset_of_mem (h hs) @[simp] theorem sUnion_empty : ⋃₀ ∅ = (∅ : set α) := Sup_empty @[simp] theorem sInter_empty : ⋂₀ ∅ = (univ : set α) := Inf_empty @[simp] theorem sUnion_singleton (s : set α) : ⋃₀ {s} = s := Sup_singleton @[simp] theorem sInter_singleton (s : set α) : ⋂₀ {s} = s := Inf_singleton theorem sUnion_union (S T : set (set α)) : ⋃₀ (S ∪ T) = ⋃₀ S ∪ ⋃₀ T := Sup_union theorem sInter_union (S T : set (set α)) : ⋂₀ (S ∪ T) = ⋂₀ S ∩ ⋂₀ T := Inf_union theorem sInter_Union (s : ι → set (set α)) : ⋂₀ (⋃ i, s i) = ⋂ i, ⋂₀ s i := begin ext x, simp only [mem_Union, mem_Inter, mem_sInter, exists_imp_distrib], split ; tauto end @[simp] theorem sUnion_insert (s : set α) (T : set (set α)) : ⋃₀ (insert s T) = s ∪ ⋃₀ T := Sup_insert @[simp] theorem sInter_insert (s : set α) (T : set (set α)) : ⋂₀ (insert s T) = s ∩ ⋂₀ T := Inf_insert theorem sUnion_pair (s t : set α) : ⋃₀ {s, t} = s ∪ t := Sup_pair theorem sInter_pair (s t : set α) : ⋂₀ {s, t} = s ∩ t := Inf_pair @[simp] theorem sUnion_image (f : α → set β) (s : set α) : ⋃₀ (f '' s) = ⋃ x ∈ s, f x := Sup_image @[simp] theorem sInter_image (f : α → set β) (s : set α) : ⋂₀ (f '' s) = ⋂ x ∈ s, f x := Inf_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 lemma sUnion_eq_univ_iff {c : set (set α)} : ⋃₀ c = @set.univ α ↔ ∀ a, ∃ b ∈ c, a ∈ b := ⟨λ H a, let ⟨b, hm, hb⟩ := mem_sUnion.1 $ by rw H; exact mem_univ a in ⟨b, hm, hb⟩, λ H, set.univ_subset_iff.1 $ λ x hx, let ⟨b, hm, hb⟩ := H x in set.mem_sUnion_of_mem hb hm⟩ theorem compl_sUnion (S : set (set α)) : (⋃₀ S)ᶜ = ⋂₀ (compl '' S) := set.ext $ assume x, ⟨assume : ¬ (∃s∈S, x ∈ s), assume s h, match s, h with ._, ⟨t, hs, rfl⟩ := assume h, this ⟨t, hs, h⟩ end, assume : ∀s, s ∈ compl '' S → x ∈ s, assume ⟨t, tS, xt⟩, this (compl t) (mem_image_of_mem _ tS) xt⟩ -- 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_comp_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_Union_range {γ : α → Type*} (f : sigma γ → β) : range f = ⋃ a, range (λ b, f ⟨a, b⟩) := set.ext $ by simp theorem Union_eq_range_sigma (s : α → set β) : (⋃ i, s i) = range (λ a : Σ i, s i, a.2) := by simp [set.ext_iff] theorem Union_image_preimage_sigma_mk_eq_self {ι : Type*} {σ : ι → Type*} (s : set (sigma σ)) : (⋃ i, sigma.mk i '' (sigma.mk i ⁻¹' s)) = s := begin ext x, simp only [mem_Union, mem_image, mem_preimage], split, { rintros ⟨i, a, h, rfl⟩, exact h }, { intro h, cases x with i a, exact ⟨i, a, h, rfl⟩ } end lemma sUnion_mono {s t : set (set α)} (h : s ⊆ t) : (⋃₀ s) ⊆ (⋃₀ t) := sUnion_subset $ assume t' ht', subset_sUnion_of_mem $ h ht' lemma Union_subset_Union {s t : ι → set α} (h : ∀i, s i ⊆ t i) : (⋃i, s i) ⊆ (⋃i, t i) := @supr_le_supr (set α) ι _ s t h lemma Union_subset_Union2 {ι₂ : Sort*} {s : ι → set α} {t : ι₂ → set α} (h : ∀i, ∃j, s i ⊆ t j) : (⋃i, s i) ⊆ (⋃i, t i) := @supr_le_supr2 (set α) ι ι₂ _ s t h lemma Union_subset_Union_const {ι₂ : Sort x} {s : set α} (h : ι → ι₂) : (⋃ i:ι, s) ⊆ (⋃ j:ι₂, s) := @supr_le_supr_const (set α) ι ι₂ _ s h @[simp] lemma Union_of_singleton (α : Type u) : (⋃(x : α), {x}) = @set.univ α := ext $ λ x, ⟨λ h, ⟨⟩, λ h, ⟨{x}, ⟨⟨x, rfl⟩, mem_singleton x⟩⟩⟩ theorem bUnion_subset_Union (s : set α) (t : α → set β) : (⋃ x ∈ s, t x) ⊆ (⋃ x, t x) := Union_subset_Union $ λ i, Union_subset $ λ h, by refl lemma sUnion_eq_bUnion {s : set (set α)} : (⋃₀ s) = (⋃ (i : set α) (h : i ∈ s), i) := by rw [← sUnion_image, image_id'] lemma sInter_eq_bInter {s : set (set α)} : (⋂₀ s) = (⋂ (i : set α) (h : i ∈ s), i) := by rw [← sInter_image, image_id'] lemma sUnion_eq_Union {s : set (set α)} : (⋃₀ s) = (⋃ (i : s), i) := by simp only [←sUnion_range, subtype.range_coe] lemma sInter_eq_Inter {s : set (set α)} : (⋂₀ s) = (⋂ (i : s), i) := by simp only [←sInter_range, subtype.range_coe] lemma union_eq_Union {s₁ s₂ : set α} : s₁ ∪ s₂ = ⋃ b : bool, cond b s₁ s₂ := set.ext $ λ x, by simp [bool.exists_bool, or_comm] lemma inter_eq_Inter {s₁ s₂ : set α} : s₁ ∩ s₂ = ⋂ b : bool, cond b s₁ s₂ := set.ext $ λ x, by simp [bool.forall_bool, and_comm] instance : complete_boolean_algebra (set α) := { compl := compl, sdiff := (\), infi_sup_le_sup_Inf := assume s t x, show x ∈ (⋂ b ∈ t, s ∪ b) → x ∈ s ∪ (⋂₀ t), by simp; exact assume h, or.imp_right (assume hn : x ∉ s, assume i hi, or.resolve_left (h i hi) hn) (classical.em $ x ∈ s), inf_Sup_le_supr_inf := assume s t x, show x ∈ s ∩ (⋃₀ t) → x ∈ (⋃ b ∈ t, s ∩ b), by simp [-and_imp, and.left_comm], .. set.boolean_algebra, .. set.lattice_set } lemma sInter_union_sInter {S T : set (set α)} : (⋂₀S) ∪ (⋂₀T) = (⋂p ∈ S.prod T, (p : (set α) × (set α)).1 ∪ p.2) := Inf_sup_Inf lemma sUnion_inter_sUnion {s t : set (set α)} : (⋃₀s) ∩ (⋃₀t) = (⋃p ∈ s.prod t, (p : (set α) × (set α )).1 ∩ p.2) := Sup_inf_Sup /-- If `S` is a set of sets, and each `s ∈ S` can be represented as an intersection of sets `T s hs`, then `⋂₀ S` is the intersection of the union of all `T s hs`. -/ lemma sInter_bUnion {S : set (set α)} {T : Π s ∈ S, set (set α)} (hT : ∀s∈S, s = ⋂₀ T s ‹s ∈ S›) : ⋂₀ (⋃s∈S, T s ‹_›) = ⋂₀ S := begin ext, simp only [and_imp, exists_prop, set.mem_sInter, set.mem_Union, exists_imp_distrib], split, { assume H s sS, rw [hT s sS, mem_sInter], assume t tTs, exact H t s sS tTs }, { assume H t s sS tTs, suffices : s ⊆ t, exact this (H s sS), rw [hT s sS, sInter_eq_bInter], exact bInter_subset_of_mem tTs } end /-- If `S` is a set of sets, and each `s ∈ S` can be represented as an union of sets `T s hs`, then `⋃₀ S` is the union of the union of all `T s hs`. -/ lemma sUnion_bUnion {S : set (set α)} {T : Π s ∈ S, set (set α)} (hT : ∀s∈S, s = ⋃₀ T s ‹_›) : ⋃₀ (⋃s∈S, T s ‹_›) = ⋃₀ S := begin ext, simp only [exists_prop, set.mem_Union, set.mem_set_of_eq], split, { rintros ⟨t, ⟨⟨s, ⟨sS, tTs⟩⟩, xt⟩⟩, refine ⟨s, ⟨sS, _⟩⟩, rw hT s sS, exact subset_sUnion_of_mem tTs xt }, { rintros ⟨s, ⟨sS, xs⟩⟩, rw hT s sS at xs, rcases mem_sUnion.1 xs with ⟨t, tTs, xt⟩, exact ⟨t, ⟨⟨s, ⟨sS, tTs⟩⟩, xt⟩⟩ } end lemma Union_range_eq_sUnion {α β : Type*} (C : set (set α)) {f : ∀(s : C), β → s} (hf : ∀(s : C), surjective (f s)) : (⋃(y : β), range (λ(s : C), (f s y).val)) = ⋃₀ C := begin ext x, split, { 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 } end lemma Union_range_eq_Union {ι α β : Type*} (C : ι → set α) {f : ∀(x : ι), β → C x} (hf : ∀(x : ι), surjective (f x)) : (⋃(y : β), range (λ(x : ι), (f x y).val)) = ⋃x, C x := begin ext x, rw [mem_Union, mem_Union], split, { rintro ⟨y, ⟨i, rfl⟩⟩, exact ⟨i, (f i y).2⟩ }, { rintro ⟨i, hx⟩, cases hf i ⟨x, hx⟩ with y hy, refine ⟨y, ⟨i, congr_arg subtype.val hy⟩⟩ } end lemma union_distrib_Inter_right {ι : Type*} (s : ι → set α) (t : set α) : (⋂ i, s i) ∪ t = (⋂ i, s i ∪ t) := begin ext x, rw [mem_union_eq, mem_Inter], split ; finish end lemma union_distrib_Inter_left {ι : Type*} (s : ι → set α) (t : set α) : t ∪ (⋂ i, s i) = (⋂ i, t ∪ s i) := begin rw [union_comm, union_distrib_Inter_right], simp [union_comm] end section function /-! ### `maps_to` -/ lemma maps_to_sUnion {S : set (set α)} {t : set β} {f : α → β} (H : ∀ s ∈ S, maps_to f s t) : maps_to f (⋃₀ S) t := λ x ⟨s, hs, hx⟩, H s hs hx lemma maps_to_Union {s : ι → set α} {t : set β} {f : α → β} (H : ∀ i, maps_to f (s i) t) : maps_to f (⋃ i, s i) t := maps_to_sUnion $ forall_range_iff.2 H lemma maps_to_bUnion {p : ι → Prop} {s : Π (i : ι) (hi : p i), set α} {t : set β} {f : α → β} (H : ∀ i hi, maps_to f (s i hi) t) : maps_to f (⋃ i hi, s i hi) t := maps_to_Union $ λ i, maps_to_Union (H i) lemma maps_to_Union_Union {s : ι → set α} {t : ι → set β} {f : α → β} (H : ∀ i, maps_to f (s i) (t i)) : maps_to f (⋃ i, s i) (⋃ i, t i) := maps_to_Union $ λ i, (H i).mono (subset.refl _) (subset_Union t i) lemma maps_to_bUnion_bUnion {p : ι → Prop} {s : Π i (hi : p i), set α} {t : Π i (hi : p i), set β} {f : α → β} (H : ∀ i hi, maps_to f (s i hi) (t i hi)) : maps_to f (⋃ i hi, s i hi) (⋃ i hi, t i hi) := maps_to_Union_Union $ λ i, maps_to_Union_Union (H i) lemma maps_to_sInter {s : set α} {T : set (set β)} {f : α → β} (H : ∀ t ∈ T, maps_to f s t) : maps_to f s (⋂₀ T) := λ x hx t ht, H t ht hx lemma maps_to_Inter {s : set α} {t : ι → set β} {f : α → β} (H : ∀ i, maps_to f s (t i)) : maps_to f s (⋂ i, t i) := λ x hx, mem_Inter.2 $ λ i, H i hx lemma maps_to_bInter {p : ι → Prop} {s : set α} {t : Π i (hi : p i), set β} {f : α → β} (H : ∀ i hi, maps_to f s (t i hi)) : maps_to f s (⋂ i hi, t i hi) := maps_to_Inter $ λ i, maps_to_Inter (H i) lemma maps_to_Inter_Inter {s : ι → set α} {t : ι → set β} {f : α → β} (H : ∀ i, maps_to f (s i) (t i)) : maps_to f (⋂ i, s i) (⋂ i, t i) := maps_to_Inter $ λ i, (H i).mono (Inter_subset s i) (subset.refl _) lemma maps_to_bInter_bInter {p : ι → Prop} {s : Π i (hi : p i), set α} {t : Π i (hi : p i), set β} {f : α → β} (H : ∀ i hi, maps_to f (s i hi) (t i hi)) : maps_to f (⋂ i hi, s i hi) (⋂ i hi, t i hi) := maps_to_Inter_Inter $ λ i, maps_to_Inter_Inter (H i) lemma image_Inter_subset (s : ι → set α) (f : α → β) : f '' (⋂ i, s i) ⊆ ⋂ i, f '' (s i) := (maps_to_Inter_Inter $ λ i, maps_to_image f (s i)).image_subset lemma image_bInter_subset {p : ι → Prop} (s : Π i (hi : p i), set α) (f : α → β) : f '' (⋂ i hi, s i hi) ⊆ ⋂ i hi, f '' (s i hi) := (maps_to_bInter_bInter $ λ i hi, maps_to_image f (s i hi)).image_subset lemma image_sInter_subset (S : set (set α)) (f : α → β) : f '' (⋂₀ S) ⊆ ⋂ s ∈ S, f '' s := by { rw sInter_eq_bInter, apply image_bInter_subset } /-! ### `inj_on` -/ lemma inj_on.image_Inter_eq [nonempty ι] {s : ι → set α} {f : α → β} (h : inj_on f (⋃ i, s i)) : f '' (⋂ i, s i) = ⋂ i, f '' (s i) := begin inhabit ι, refine subset.antisymm (image_Inter_subset s f) (λ y hy, _), simp only [mem_Inter, mem_image_iff_bex] at hy, choose x hx hy using hy, refine ⟨x (default ι), mem_Inter.2 $ λ i, _, hy _⟩, suffices : x (default ι) = x i, { rw this, apply hx }, replace hx : ∀ i, x i ∈ ⋃ j, s j := λ i, (subset_Union _ _) (hx i), apply h (hx _) (hx _), simp only [hy] end lemma inj_on.image_bInter_eq {p : ι → Prop} {s : Π i (hi : p i), set α} (hp : ∃ i, p i) {f : α → β} (h : inj_on f (⋃ i hi, s i hi)) : f '' (⋂ i hi, s i hi) = ⋂ i hi, f '' (s i hi) := begin simp only [Inter, infi_subtype'], haveI : nonempty {i // p i} := nonempty_subtype.2 hp, apply inj_on.image_Inter_eq, simpa only [Union, supr_subtype'] using h end lemma inj_on_Union_of_directed {s : ι → set α} (hs : directed (⊆) s) {f : α → β} (hf : ∀ i, inj_on f (s i)) : inj_on f (⋃ i, s i) := begin intros x hx y hy hxy, rcases mem_Union.1 hx with ⟨i, hx⟩, rcases mem_Union.1 hy with ⟨j, hy⟩, rcases hs i j with ⟨k, hi, hj⟩, exact hf k (hi hx) (hj hy) hxy end /-! ### `surj_on` -/ lemma surj_on_sUnion {s : set α} {T : set (set β)} {f : α → β} (H : ∀ t ∈ T, surj_on f s t) : surj_on f s (⋃₀ T) := λ x ⟨t, ht, hx⟩, H t ht hx lemma surj_on_Union {s : set α} {t : ι → set β} {f : α → β} (H : ∀ i, surj_on f s (t i)) : surj_on f s (⋃ i, t i) := surj_on_sUnion $ forall_range_iff.2 H lemma surj_on_Union_Union {s : ι → set α} {t : ι → set β} {f : α → β} (H : ∀ i, surj_on f (s i) (t i)) : surj_on f (⋃ i, s i) (⋃ i, t i) := surj_on_Union $ λ i, (H i).mono (subset_Union _ _) (subset.refl _) lemma surj_on_bUnion {p : ι → Prop} {s : set α} {t : Π i (hi : p i), set β} {f : α → β} (H : ∀ i hi, surj_on f s (t i hi)) : surj_on f s (⋃ i hi, t i hi) := surj_on_Union $ λ i, surj_on_Union (H i) lemma surj_on_bUnion_bUnion {p : ι → Prop} {s : Π i (hi : p i), set α} {t : Π i (hi : p i), set β} {f : α → β} (H : ∀ i hi, surj_on f (s i hi) (t i hi)) : surj_on f (⋃ i hi, s i hi) (⋃ i hi, t i hi) := surj_on_Union_Union $ λ i, surj_on_Union_Union (H i) lemma surj_on_Inter [hi : nonempty ι] {s : ι → set α} {t : set β} {f : α → β} (H : ∀ i, surj_on f (s i) t) (Hinj : inj_on f (⋃ i, s i)) : surj_on f (⋂ i, s i) t := begin intros y hy, rw [Hinj.image_Inter_eq, mem_Inter], exact λ i, H i hy end lemma surj_on_Inter_Inter [hi : nonempty ι] {s : ι → set α} {t : ι → set β} {f : α → β} (H : ∀ i, surj_on f (s i) (t i)) (Hinj : inj_on f (⋃ i, s i)) : surj_on f (⋂ i, s i) (⋂ i, t i) := surj_on_Inter (λ i, (H i).mono (subset.refl _) (Inter_subset _ _)) Hinj /-! ### `bij_on` -/ lemma bij_on_Union {s : ι → set α} {t : ι → set β} {f : α → β} (H : ∀ i, bij_on f (s i) (t i)) (Hinj : inj_on f (⋃ i, s i)) : bij_on f (⋃ i, s i) (⋃ i, t i) := ⟨maps_to_Union_Union $ λ i, (H i).maps_to, Hinj, surj_on_Union_Union $ λ i, (H i).surj_on⟩ lemma bij_on_Inter [hi :nonempty ι] {s : ι → set α} {t : ι → set β} {f : α → β} (H : ∀ i, bij_on f (s i) (t i)) (Hinj : inj_on f (⋃ i, s i)) : bij_on f (⋂ i, s i) (⋂ i, t i) := ⟨maps_to_Inter_Inter $ λ i, (H i).maps_to, hi.elim $ λ i, (H i).inj_on.mono (Inter_subset _ _), surj_on_Inter_Inter (λ i, (H i).surj_on) Hinj⟩ lemma bij_on_Union_of_directed {s : ι → set α} (hs : directed (⊆) s) {t : ι → set β} {f : α → β} (H : ∀ i, bij_on f (s i) (t i)) : bij_on f (⋃ i, s i) (⋃ i, t i) := bij_on_Union H $ inj_on_Union_of_directed hs (λ i, (H i).inj_on) lemma bij_on_Inter_of_directed [nonempty ι] {s : ι → set α} (hs : directed (⊆) s) {t : ι → set β} {f : α → β} (H : ∀ i, bij_on f (s i) (t i)) : bij_on f (⋂ i, s i) (⋂ i, t i) := bij_on_Inter H $ inj_on_Union_of_directed hs (λ i, (H i).inj_on) end function section variables {p : Prop} {μ : p → set α} @[simp] lemma Inter_pos (hp : p) : (⋂h:p, μ h) = μ hp := infi_pos hp @[simp] lemma Inter_neg (hp : ¬ p) : (⋂h:p, μ h) = univ := infi_neg hp @[simp] lemma Union_pos (hp : p) : (⋃h:p, μ h) = μ hp := supr_pos hp @[simp] lemma Union_neg (hp : ¬ p) : (⋃h:p, μ h) = ∅ := supr_neg hp @[simp] lemma Union_empty {ι : Sort*} : (⋃i:ι, ∅:set α) = ∅ := supr_bot @[simp] lemma Inter_univ {ι : Sort*} : (⋂i:ι, univ:set α) = univ := infi_top end section image lemma image_Union {f : α → β} {s : ι → set α} : f '' (⋃ i, s i) = (⋃i, f '' s i) := begin apply set.ext, intro x, simp [image, exists_and_distrib_right.symm, -exists_and_distrib_right], exact exists_swap end lemma univ_subtype {p : α → Prop} : (univ : set (subtype p)) = (⋃x (h : p x), {⟨x, h⟩}) := set.ext $ assume ⟨x, h⟩, by simp [h] lemma range_eq_Union {ι} (f : ι → α) : range f = (⋃i, {f i}) := set.ext $ assume a, by simp [@eq_comm α a] lemma image_eq_Union (f : α → β) (s : set α) : f '' s = (⋃i∈s, {f i}) := set.ext $ assume b, by simp [@eq_comm β b] @[simp] lemma bUnion_range {f : ι → α} {g : α → set β} : (⋃x ∈ range f, g x) = (⋃y, g (f y)) := supr_range @[simp] lemma bInter_range {f : ι → α} {g : α → set β} : (⋂x ∈ range f, g x) = (⋂y, g (f y)) := infi_range variables {s : set γ} {f : γ → α} {g : α → set β} @[simp] lemma bUnion_image : (⋃x∈ (f '' s), g x) = (⋃y ∈ s, g (f y)) := supr_image @[simp] lemma bInter_image : (⋂x∈ (f '' s), g x) = (⋂y ∈ s, g (f y)) := infi_image end image section image2 variables (f : α → β → γ) {s : set α} {t : set β} lemma Union_image_left : (⋃ a ∈ s, f a '' t) = image2 f s t := by { ext y, split; simp only [mem_Union]; rintros ⟨a, ha, x, hx, ax⟩; exact ⟨a, x, ha, hx, ax⟩ } lemma Union_image_right : (⋃ b ∈ t, (λ a, f a b) '' s) = image2 f s t := by { ext y, split; simp only [mem_Union]; rintros ⟨a, b, c, d, e⟩, exact ⟨c, a, d, b, e⟩, exact ⟨b, d, a, c, e⟩ } end image2 section preimage theorem monotone_preimage {f : α → β} : monotone (preimage f) := assume a b h, preimage_mono h @[simp] theorem preimage_Union {ι : Sort w} {f : α → β} {s : ι → set β} : preimage f (⋃i, s i) = (⋃i, preimage f (s i)) := set.ext $ by simp [preimage] theorem preimage_bUnion {ι} {f : α → β} {s : set ι} {t : ι → set β} : f ⁻¹' (⋃i ∈ s, t i) = (⋃i ∈ s, f ⁻¹' (t i)) := by simp @[simp] theorem preimage_sUnion {f : α → β} {s : set (set β)} : f ⁻¹' (⋃₀ s) = (⋃t ∈ s, f ⁻¹' t) := set.ext $ by simp [preimage] lemma preimage_Inter {ι : Sort*} {s : ι → set β} {f : α → β} : f ⁻¹' (⋂ i, s i) = (⋂ i, f ⁻¹' s i) := by ext; simp lemma preimage_bInter {s : γ → set β} {t : set γ} {f : α → β} : f ⁻¹' (⋂ i∈t, s i) = (⋂ i∈t, f ⁻¹' s i) := by ext; simp @[simp] lemma bUnion_preimage_singleton (f : α → β) (s : set β) : (⋃ y ∈ s, f ⁻¹' {y}) = f ⁻¹' s := by rw [← preimage_bUnion, bUnion_of_singleton] lemma bUnion_range_preimage_singleton (f : α → β) : (⋃ y ∈ range f, f ⁻¹' {y}) = univ := by simp end preimage section seq /-- 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 β := {b | ∃f∈s, ∃a∈t, (f : α → β) a = b} lemma seq_def {s : set (α → β)} {t : set α} : seq s t = ⋃f∈s, f '' t := set.ext $ by simp [seq] @[simp] lemma mem_seq_iff {s : set (α → β)} {t : set α} {b : β} : b ∈ seq s t ↔ ∃ (f ∈ s) (a ∈ t), (f : α → β) a = b := iff.rfl lemma seq_subset {s : set (α → β)} {t : set α} {u : set β} : seq s t ⊆ u ↔ (∀f∈s, ∀a∈t, (f : α → β) a ∈ u) := iff.intro (assume h f hf a ha, h ⟨f, hf, a, ha, rfl⟩) (assume h b ⟨f, hf, a, ha, eq⟩, eq ▸ h f hf a ha) lemma seq_mono {s₀ s₁ : set (α → β)} {t₀ t₁ : set α} (hs : s₀ ⊆ s₁) (ht : t₀ ⊆ t₁) : seq s₀ t₀ ⊆ seq s₁ t₁ := assume b ⟨f, hf, a, ha, eq⟩, ⟨f, hs hf, a, ht ha, eq⟩ lemma singleton_seq {f : α → β} {t : set α} : set.seq {f} t = f '' t := set.ext $ by simp lemma seq_singleton {s : set (α → β)} {a : α} : set.seq s {a} = (λf:α→β, f a) '' s := set.ext $ by simp lemma seq_seq {s : set (β → γ)} {t : set (α → β)} {u : set α} : seq s (seq t u) = seq (seq ((∘) '' s) t) u := begin refine set.ext (assume c, iff.intro _ _), { rintros ⟨f, hfs, b, ⟨g, hg, a, hau, rfl⟩, rfl⟩, exact ⟨f ∘ g, ⟨(∘) f, mem_image_of_mem _ hfs, g, hg, rfl⟩, a, hau, rfl⟩ }, { rintros ⟨fg, ⟨fc, ⟨f, hfs, rfl⟩, g, hgt, rfl⟩, a, ha, rfl⟩, exact ⟨f, hfs, g a, ⟨g, hgt, a, ha, rfl⟩, rfl⟩ } end lemma image_seq {f : β → γ} {s : set (α → β)} {t : set α} : f '' seq s t = seq ((∘) f '' s) t := by rw [← singleton_seq, ← singleton_seq, seq_seq, image_singleton] lemma prod_eq_seq {s : set α} {t : set β} : s.prod t = (prod.mk '' s).seq t := begin ext ⟨a, b⟩, split, { rintros ⟨ha, hb⟩, exact ⟨prod.mk a, ⟨a, ha, rfl⟩, b, hb, rfl⟩ }, { rintros ⟨f, ⟨x, hx, rfl⟩, y, hy, eq⟩, rw ← eq, exact ⟨hx, hy⟩ } end lemma prod_image_seq_comm (s : set α) (t : set β) : (prod.mk '' s).seq t = seq ((λb a, (a, b)) '' t) s := by rw [← prod_eq_seq, ← image_swap_prod, prod_eq_seq, image_seq, ← image_comp, prod.swap] end seq theorem monotone_prod [preorder α] {f : α → set β} {g : α → set γ} (hf : monotone f) (hg : monotone g) : monotone (λx, (f x).prod (g x)) := assume a b h, prod_mono (hf h) (hg h) instance : monad set := { pure := λ(α : Type u) a, {a}, bind := λ(α β : Type u) s f, ⋃i∈s, f i, seq := λ(α β : Type u), set.seq, map := λ(α β : Type u), set.image } section monad variables {α' β' : Type u} {s : set α'} {f : α' → set β'} {g : set (α' → β')} @[simp] lemma bind_def : s >>= f = ⋃i∈s, f i := rfl @[simp] lemma fmap_eq_image (f : α' → β') : f <$> s = f '' s := rfl @[simp] lemma seq_eq_set_seq {α β : Type*} (s : set (α → β)) (t : set α) : s <*> t = s.seq t := rfl @[simp] lemma pure_def (a : α) : (pure a : set α) = {a} := rfl end monad instance : is_lawful_monad set := { pure_bind := assume α β x f, by simp, bind_assoc := assume α β γ s f g, set.ext $ assume a, by simp [exists_and_distrib_right.symm, -exists_and_distrib_right, exists_and_distrib_left.symm, -exists_and_distrib_left, and_assoc]; exact exists_swap, id_map := assume α, id_map, bind_pure_comp_eq_map := assume α β f s, set.ext $ by simp [set.image, eq_comm], bind_map_eq_seq := assume α β s t, by simp [seq_def] } instance : is_comm_applicative (set : Type u → Type u) := ⟨ assume α β s t, prod_image_seq_comm s t ⟩ section pi lemma pi_def {α : Type*} {π : α → Type*} (i : set α) (s : Πa, set (π a)) : pi i s = (⋂ a∈i, ((λf:(Πa, π a), f a) ⁻¹' (s a))) := by ext; simp [pi] end pi end set /- disjoint sets -/ namespace set protected theorem disjoint_iff {s t : set α} : disjoint s t ↔ s ∩ t ⊆ ∅ := iff.rfl theorem disjoint_iff_inter_eq_empty {s t : set α} : disjoint s t ↔ s ∩ t = ∅ := disjoint_iff lemma not_disjoint_iff {s t : set α} : ¬disjoint s t ↔ ∃x, x ∈ s ∧ x ∈ t := not_forall.trans $ exists_congr $ λ x, not_not lemma disjoint_left {s t : set α} : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t := show (∀ x, ¬(x ∈ s ∩ t)) ↔ _, from ⟨λ h a, not_and.1 $ h a, λ h a, not_and.2 $ h a⟩ theorem disjoint_right {s t : set α} : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s := by rw [disjoint.comm, disjoint_left] theorem disjoint_of_subset_left {s t u : set α} (h : s ⊆ u) (d : disjoint u t) : disjoint s t := d.mono_left h theorem disjoint_of_subset_right {s t u : set α} (h : t ⊆ u) (d : disjoint s u) : disjoint s t := d.mono_right h theorem disjoint_of_subset {s t u v : set α} (h1 : s ⊆ u) (h2 : t ⊆ v) (d : disjoint u v) : disjoint s t := d.mono h1 h2 @[simp] theorem disjoint_union_left {s t u : set α} : disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u := disjoint_sup_left theorem disjoint.union_left {s t u : set α} (hs : disjoint s u) (ht : disjoint t u) : disjoint (s ∪ t) u := hs.sup_left ht @[simp] theorem disjoint_union_right {s t u : set α} : disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u := disjoint_sup_right theorem disjoint.union_right {s t u : set α} (ht : disjoint s t) (hu : disjoint s u) : disjoint s (t ∪ u) := ht.sup_right hu theorem disjoint_diff {a b : set α} : disjoint a (b \ a) := disjoint_iff.2 (inter_diff_self _ _) theorem disjoint_compl (s : set α) : disjoint s sᶜ := assume a ⟨h₁, h₂⟩, h₂ h₁ theorem disjoint_singleton_left {a : α} {s : set α} : disjoint {a} s ↔ a ∉ s := by simp [set.disjoint_iff, subset_def]; exact iff.rfl theorem disjoint_singleton_right {a : α} {s : set α} : disjoint s {a} ↔ a ∉ s := by rw [disjoint.comm]; exact disjoint_singleton_left theorem disjoint_image_image {f : β → α} {g : γ → α} {s : set β} {t : set γ} (h : ∀b∈s, ∀c∈t, f b ≠ g c) : disjoint (f '' s) (g '' t) := by rintros a ⟨⟨b, hb, eq⟩, ⟨c, hc, rfl⟩⟩; exact h b hb c hc eq lemma disjoint.preimage {α β} (f : α → β) {s t : set β} (h : disjoint s t) : disjoint (f ⁻¹' s) (f ⁻¹' t) := λ x hx, h hx theorem pairwise_on_disjoint_fiber (f : α → β) (s : set β) : pairwise_on s (disjoint on (λ y, f ⁻¹' {y})) := λ y₁ _ y₂ _ hy x ⟨hx₁, hx₂⟩, hy (eq.trans (eq.symm hx₁) hx₂) /-- A collection of sets is `pairwise_disjoint`, if any two different sets in this collection are disjoint. -/ def pairwise_disjoint (s : set (set α)) : Prop := pairwise_on s disjoint lemma pairwise_disjoint.subset {s t : set (set α)} (h : s ⊆ t) (ht : pairwise_disjoint t) : pairwise_disjoint s := pairwise_on.mono h ht lemma pairwise_disjoint.range {s : set (set α)} (f : s → set α) (hf : ∀(x : s), f x ⊆ x.1) (ht : pairwise_disjoint s) : pairwise_disjoint (range f) := begin rintro _ ⟨x, rfl⟩ _ ⟨y, rfl⟩ hxy, refine (ht _ x.2 _ y.2 _).mono (hf x) (hf y), intro h, apply hxy, apply congr_arg f, exact subtype.eq h end /- warning: classical -/ lemma pairwise_disjoint.elim {s : set (set α)} (h : pairwise_disjoint s) {x y : set α} (hx : x ∈ s) (hy : y ∈ s) (z : α) (hzx : z ∈ x) (hzy : z ∈ y) : x = y := not_not.1 $ λ h', h x hx y hy h' ⟨hzx, hzy⟩ end set namespace set variables (t : α → set β) lemma subset_diff {s t u : set α} : s ⊆ t \ u ↔ s ⊆ t ∧ disjoint s u := ⟨λ h, ⟨λ x hxs, (h hxs).1, λ x ⟨hxs, hxu⟩, (h hxs).2 hxu⟩, λ ⟨h1, h2⟩ x hxs, ⟨h1 hxs, λ hxu, h2 ⟨hxs, hxu⟩⟩⟩ /-- 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 sigma_to_Union (x : Σi, t i) : (⋃i, t i) := ⟨x.2, mem_Union.2 ⟨x.1, x.2.2⟩⟩ lemma sigma_to_Union_surjective : surjective (sigma_to_Union t) | ⟨b, hb⟩ := have ∃a, b ∈ t a, by simpa using hb, let ⟨a, hb⟩ := this in ⟨⟨a, ⟨b, hb⟩⟩, rfl⟩ lemma sigma_to_Union_injective (h : ∀i j, i ≠ j → disjoint (t i) (t j)) : injective (sigma_to_Union t) | ⟨a₁, ⟨b₁, h₁⟩⟩ ⟨a₂, ⟨b₂, h₂⟩⟩ eq := have b_eq : b₁ = b₂, from congr_arg subtype.val eq, have a_eq : a₁ = a₂, from classical.by_contradiction $ assume ne, have b₁ ∈ t a₁ ∩ t a₂, from ⟨h₁, b_eq.symm ▸ h₂⟩, h _ _ ne this, sigma.eq a_eq $ subtype.eq $ by subst b_eq; subst a_eq lemma sigma_to_Union_bijective (h : ∀i j, i ≠ j → disjoint (t i) (t j)) : bijective (sigma_to_Union t) := ⟨sigma_to_Union_injective t h, sigma_to_Union_surjective t⟩ /-- Equivalence between a disjoint union and a dependent sum. -/ noncomputable def Union_eq_sigma_of_disjoint {t : α → set β} (h : ∀i j, i ≠ j → disjoint (t i) (t j)) : (⋃i, t i) ≃ (Σi, t i) := (equiv.of_bijective _ $ sigma_to_Union_bijective t h).symm /-- Equivalence between a disjoint bounded union and a dependent sum. -/ noncomputable def bUnion_eq_sigma_of_disjoint {s : set α} {t : α → set β} (h : pairwise_on s (disjoint on t)) : (⋃i∈s, t i) ≃ (Σi:s, t i.val) := equiv.trans (equiv.set_congr (bUnion_eq_Union _ _)) $ Union_eq_sigma_of_disjoint $ assume ⟨i, hi⟩ ⟨j, hj⟩ ne, h _ hi _ hj $ assume eq, ne $ subtype.eq eq end set
5b335a351d7316e40aca0ab1600d54167401c7cf
94e33a31faa76775069b071adea97e86e218a8ee
/src/measure_theory/measure/null_measurable.lean
5fac6e285d8ab8e1fc5fb8efe1d003e062e359ba
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
19,221
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, Yury Kudryashov -/ import measure_theory.measure.ae_disjoint /-! # Null measurable sets and complete measures ## Main definitions ### Null measurable sets and functions A set `s : set α` is called *null measurable* (`measure_theory.null_measurable_set`) if it satisfies any of the following equivalent conditions: * there exists a measurable set `t` such that `s =ᵐ[μ] t` (this is used as a definition); * `measure_theory.to_measurable μ s =ᵐ[μ] s`; * there exists a measurable subset `t ⊆ s` such that `t =ᵐ[μ] s` (in this case the latter equality means that `μ (s \ t) = 0`); * `s` can be represented as a union of a measurable set and a set of measure zero; * `s` can be represented as a difference of a measurable set and a set of measure zero. Null measurable sets form a σ-algebra that is registered as a `measurable_space` instance on `measure_theory.null_measurable_space α μ`. We also say that `f : α → β` is `measure_theory.null_measurable` if the preimage of a measurable set is a null measurable set. In other words, `f : α → β` is null measurable if it is measurable as a function `measure_theory.null_measurable_space α μ → β`. ### Complete measures We say that a measure `μ` is complete w.r.t. the `measurable_space α` σ-algebra (or the σ-algebra is complete w.r.t measure `μ`) if every set of measure zero is measurable. In this case all null measurable sets and functions are measurable. For each measure `μ`, we define `measure_theory.measure.completion μ` to be the same measure interpreted as a measure on `measure_theory.null_measurable_space α μ` and prove that this is a complete measure. ## Implementation notes We define `measure_theory.null_measurable_set` as `@measurable_set (null_measurable_space α μ) _` so that theorems about `measurable_set`s like `measurable_set.union` can be applied to `null_measurable_set`s. However, these lemmas output terms of the same form `@measurable_set (null_measurable_space α μ) _ _`. While this is definitionally equal to the expected output `null_measurable_set s μ`, it looks different and may be misleading. So we copy all standard lemmas about measurable sets to the `measure_theory.null_measurable_set` namespace and fix the output type. ## Tags measurable, measure, null measurable, completion -/ open filter set encodable variables {ι α β γ : Type*} namespace measure_theory /-- A type tag for `α` with `measurable_set` given by `null_measurable_set`. -/ @[nolint unused_arguments] def null_measurable_space (α : Type*) [measurable_space α] (μ : measure α . volume_tac) : Type* := α section variables {m0 : measurable_space α} {μ : measure α} {s t : set α} instance [h : inhabited α] : inhabited (null_measurable_space α μ) := h instance [h : subsingleton α] : subsingleton (null_measurable_space α μ) := h instance : measurable_space (null_measurable_space α μ) := { measurable_set' := λ s, ∃ t, measurable_set t ∧ s =ᵐ[μ] t, measurable_set_empty := ⟨∅, measurable_set.empty, ae_eq_refl _⟩, measurable_set_compl := λ s ⟨t, htm, hts⟩, ⟨tᶜ, htm.compl, hts.compl⟩, measurable_set_Union := λ s hs, by { choose t htm hts using hs, exact ⟨⋃ i, t i, measurable_set.Union htm, eventually_eq.countable_Union hts⟩ } } /-- A set is called `null_measurable_set` if it can be approximated by a measurable set up to a set of null measure. -/ def null_measurable_set [measurable_space α] (s : set α) (μ : measure α . volume_tac) : Prop := @measurable_set (null_measurable_space α μ) _ s @[simp] lemma _root_.measurable_set.null_measurable_set (h : measurable_set s) : null_measurable_set s μ := ⟨s, h, ae_eq_refl _⟩ @[simp] lemma null_measurable_set_empty : null_measurable_set ∅ μ := measurable_set.empty @[simp] lemma null_measurable_set_univ : null_measurable_set univ μ := measurable_set.univ namespace null_measurable_set lemma of_null (h : μ s = 0) : null_measurable_set s μ := ⟨∅, measurable_set.empty, ae_eq_empty.2 h⟩ lemma compl (h : null_measurable_set s μ) : null_measurable_set sᶜ μ := h.compl lemma of_compl (h : null_measurable_set sᶜ μ) : null_measurable_set s μ := h.of_compl @[simp] lemma compl_iff : null_measurable_set sᶜ μ ↔ null_measurable_set s μ := measurable_set.compl_iff @[nontriviality] lemma of_subsingleton [subsingleton α] : null_measurable_set s μ := subsingleton.measurable_set protected lemma congr (hs : null_measurable_set s μ) (h : s =ᵐ[μ] t) : null_measurable_set t μ := let ⟨s', hm, hs'⟩ := hs in ⟨s', hm, h.symm.trans hs'⟩ protected lemma Union [encodable ι] {s : ι → set α} (h : ∀ i, null_measurable_set (s i) μ) : null_measurable_set (⋃ i, s i) μ := measurable_set.Union h protected lemma bUnion_decode₂ [encodable ι] ⦃f : ι → set α⦄ (h : ∀ i, null_measurable_set (f i) μ) (n : ℕ) : null_measurable_set (⋃ b ∈ encodable.decode₂ ι n, f b) μ := measurable_set.bUnion_decode₂ h n protected lemma bUnion {f : ι → set α} {s : set ι} (hs : s.countable) (h : ∀ b ∈ s, null_measurable_set (f b) μ) : null_measurable_set (⋃ b ∈ s, f b) μ := measurable_set.bUnion hs h protected lemma sUnion {s : set (set α)} (hs : s.countable) (h : ∀ t ∈ s, null_measurable_set t μ) : null_measurable_set (⋃₀ s) μ := by { rw sUnion_eq_bUnion, exact measurable_set.bUnion hs h } lemma Union_Prop {p : Prop} {f : p → set α} (hf : ∀ i, null_measurable_set (f i) μ) : null_measurable_set (⋃ i, f i) μ := measurable_set.Union_Prop hf lemma Union_fintype [fintype ι] {f : ι → set α} (h : ∀ b, null_measurable_set (f b) μ) : null_measurable_set (⋃ b, f b) μ := measurable_set.Union_fintype h protected lemma Inter [encodable ι] {f : ι → set α} (h : ∀ i, null_measurable_set (f i) μ) : null_measurable_set (⋂ i, f i) μ := measurable_set.Inter h protected lemma bInter {f : β → set α} {s : set β} (hs : s.countable) (h : ∀ b ∈ s, null_measurable_set (f b) μ) : null_measurable_set (⋂ b ∈ s, f b) μ := measurable_set.bInter hs h protected lemma sInter {s : set (set α)} (hs : s.countable) (h : ∀ t ∈ s, null_measurable_set t μ) : null_measurable_set (⋂₀ s) μ := measurable_set.sInter hs h lemma Inter_Prop {p : Prop} {f : p → set α} (hf : ∀ b, null_measurable_set (f b) μ) : null_measurable_set (⋂ b, f b) μ := measurable_set.Inter_Prop hf lemma Inter_fintype [fintype ι] {f : ι → set α} (h : ∀ b, null_measurable_set (f b) μ) : null_measurable_set (⋂ b, f b) μ := measurable_set.Inter_fintype h @[simp] protected lemma union (hs : null_measurable_set s μ) (ht : null_measurable_set t μ) : null_measurable_set (s ∪ t) μ := hs.union ht protected lemma union_null (hs : null_measurable_set s μ) (ht : μ t = 0) : null_measurable_set (s ∪ t) μ := hs.union (of_null ht) @[simp] protected lemma inter (hs : null_measurable_set s μ) (ht : null_measurable_set t μ) : null_measurable_set (s ∩ t) μ := hs.inter ht @[simp] protected lemma diff (hs : null_measurable_set s μ) (ht : null_measurable_set t μ) : null_measurable_set (s \ t) μ := hs.diff ht @[simp] protected lemma disjointed {f : ℕ → set α} (h : ∀ i, null_measurable_set (f i) μ) (n) : null_measurable_set (disjointed f n) μ := measurable_set.disjointed h n @[simp] protected lemma const (p : Prop) : null_measurable_set {a : α | p} μ := measurable_set.const p instance [measurable_singleton_class α] : measurable_singleton_class (null_measurable_space α μ) := ⟨λ x, (@measurable_set_singleton α _ _ x).null_measurable_set⟩ protected lemma insert [measurable_singleton_class (null_measurable_space α μ)] (hs : null_measurable_set s μ) (a : α) : null_measurable_set (insert a s) μ := hs.insert a lemma exists_measurable_superset_ae_eq (h : null_measurable_set s μ) : ∃ t ⊇ s, measurable_set t ∧ t =ᵐ[μ] s := begin rcases h with ⟨t, htm, hst⟩, refine ⟨t ∪ to_measurable μ (s \ t), _, htm.union (measurable_set_to_measurable _ _), _⟩, { exact diff_subset_iff.1 (subset_to_measurable _ _) }, { have : to_measurable μ (s \ t) =ᵐ[μ] (∅ : set α), by simp [ae_le_set.1 hst.le], simpa only [union_empty] using hst.symm.union this } end lemma to_measurable_ae_eq (h : null_measurable_set s μ) : to_measurable μ s =ᵐ[μ] s := begin rw [to_measurable, dif_pos], exact h.exists_measurable_superset_ae_eq.some_spec.snd.2 end lemma compl_to_measurable_compl_ae_eq (h : null_measurable_set s μ) : (to_measurable μ sᶜ)ᶜ =ᵐ[μ] s := by simpa only [compl_compl] using h.compl.to_measurable_ae_eq.compl lemma exists_measurable_subset_ae_eq (h : null_measurable_set s μ) : ∃ t ⊆ s, measurable_set t ∧ t =ᵐ[μ] s := ⟨(to_measurable μ sᶜ)ᶜ, compl_subset_comm.2 $ subset_to_measurable _ _, (measurable_set_to_measurable _ _).compl, h.compl_to_measurable_compl_ae_eq⟩ end null_measurable_set /-- If `sᵢ` is a countable family of (null) measurable pairwise `μ`-a.e. disjoint sets, then there exists a subordinate family `tᵢ ⊆ sᵢ` of measurable pairwise disjoint sets such that `tᵢ =ᵐ[μ] sᵢ`. -/ lemma exists_subordinate_pairwise_disjoint [encodable ι] {s : ι → set α} (h : ∀ i, null_measurable_set (s i) μ) (hd : pairwise (ae_disjoint μ on s)) : ∃ t : ι → set α, (∀ i, t i ⊆ s i) ∧ (∀ i, s i =ᵐ[μ] t i) ∧ (∀ i, measurable_set (t i)) ∧ pairwise (disjoint on t) := begin choose t ht_sub htm ht_eq using λ i, (h i).exists_measurable_subset_ae_eq, rcases exists_null_pairwise_disjoint_diff hd with ⟨u, hum, hu₀, hud⟩, exact ⟨λ i, t i \ u i, λ i, (diff_subset _ _).trans (ht_sub _), λ i, (ht_eq _).symm.trans (diff_null_ae_eq_self (hu₀ i)).symm, λ i, (htm i).diff (hum i), hud.mono $ λ i j h, h.mono (diff_subset_diff_left (ht_sub i)) (diff_subset_diff_left (ht_sub j))⟩ end lemma measure_Union {m0 : measurable_space α} {μ : measure α} [encodable ι] {f : ι → set α} (hn : pairwise (disjoint on f)) (h : ∀ i, measurable_set (f i)) : μ (⋃ i, f i) = ∑' i, μ (f i) := begin rw [measure_eq_extend (measurable_set.Union h), extend_Union measurable_set.empty _ measurable_set.Union _ hn h], { simp [measure_eq_extend, h] }, { exact μ.empty }, { exact μ.m_Union } end lemma measure_Union₀ [encodable ι] {f : ι → set α} (hd : pairwise (ae_disjoint μ on f)) (h : ∀ i, null_measurable_set (f i) μ) : μ (⋃ i, f i) = ∑' i, μ (f i) := begin rcases exists_subordinate_pairwise_disjoint h hd with ⟨t, ht_sub, ht_eq, htm, htd⟩, calc μ (⋃ i, f i) = μ (⋃ i, t i) : measure_congr (eventually_eq.countable_Union ht_eq) ... = ∑' i, μ (t i) : measure_Union htd htm ... = ∑' i, μ (f i) : tsum_congr (λ i, measure_congr (ht_eq _).symm) end lemma measure_union₀_aux (hs : null_measurable_set s μ) (ht : null_measurable_set t μ) (hd : ae_disjoint μ s t) : μ (s ∪ t) = μ s + μ t := begin rw [union_eq_Union, measure_Union₀, tsum_fintype, fintype.sum_bool, cond, cond], exacts [(pairwise_on_bool ae_disjoint.symmetric).2 hd, λ b, bool.cases_on b ht hs] end /-- A null measurable set `t` is Carathéodory measurable: for any `s`, we have `μ (s ∩ t) + μ (s \ t) = μ s`. -/ lemma measure_inter_add_diff₀ (s : set α) (ht : null_measurable_set t μ) : μ (s ∩ t) + μ (s \ t) = μ s := begin refine le_antisymm _ _, { rcases exists_measurable_superset μ s with ⟨s', hsub, hs'm, hs'⟩, replace hs'm : null_measurable_set s' μ := hs'm.null_measurable_set, calc μ (s ∩ t) + μ (s \ t) ≤ μ (s' ∩ t) + μ (s' \ t) : add_le_add (measure_mono $ inter_subset_inter_left _ hsub) (measure_mono $ diff_subset_diff_left hsub) ... = μ (s' ∩ t ∪ s' \ t) : (measure_union₀_aux (hs'm.inter ht) (hs'm.diff ht) $ (@disjoint_inf_sdiff _ s' t _).ae_disjoint).symm ... = μ s' : congr_arg μ (inter_union_diff _ _) ... = μ s : hs' }, { calc μ s = μ (s ∩ t ∪ s \ t) : by rw inter_union_diff ... ≤ μ (s ∩ t) + μ (s \ t) : measure_union_le _ _ } end lemma measure_union_add_inter₀ (s : set α) (ht : null_measurable_set t μ) : μ (s ∪ t) + μ (s ∩ t) = μ s + μ t := by rw [← measure_inter_add_diff₀ (s ∪ t) ht, union_inter_cancel_right, union_diff_right, ← measure_inter_add_diff₀ s ht, add_comm, ← add_assoc, add_right_comm] lemma measure_union_add_inter₀' (hs : null_measurable_set s μ) (t : set α) : μ (s ∪ t) + μ (s ∩ t) = μ s + μ t := by rw [union_comm, inter_comm, measure_union_add_inter₀ t hs, add_comm] lemma measure_union₀ (ht : null_measurable_set t μ) (hd : ae_disjoint μ s t) : μ (s ∪ t) = μ s + μ t := by rw [← measure_union_add_inter₀ s ht, hd.eq, add_zero] lemma measure_union₀' (hs : null_measurable_set s μ) (hd : ae_disjoint μ s t) : μ (s ∪ t) = μ s + μ t := by rw [union_comm, measure_union₀ hs hd.symm, add_comm] section measurable_singleton_class variable [measurable_singleton_class (null_measurable_space α μ)] lemma null_measurable_set_singleton (x : α) : null_measurable_set {x} μ := measurable_set_singleton x @[simp] lemma null_measurable_set_insert {a : α} {s : set α} : null_measurable_set (insert a s) μ ↔ null_measurable_set s μ := measurable_set_insert lemma null_measurable_set_eq {a : α} : null_measurable_set {x | x = a} μ := null_measurable_set_singleton a protected lemma _root_.set.finite.null_measurable_set (hs : s.finite) : null_measurable_set s μ := finite.measurable_set hs protected lemma _root_.finset.null_measurable_set (s : finset α) : null_measurable_set ↑s μ := finset.measurable_set s end measurable_singleton_class lemma _root_.set.finite.null_measurable_set_bUnion {f : ι → set α} {s : set ι} (hs : s.finite) (h : ∀ b ∈ s, null_measurable_set (f b) μ) : null_measurable_set (⋃ b ∈ s, f b) μ := finite.measurable_set_bUnion hs h lemma _root_.finset.null_measurable_set_bUnion {f : ι → set α} (s : finset ι) (h : ∀ b ∈ s, null_measurable_set (f b) μ) : null_measurable_set (⋃ b ∈ s, f b) μ := finset.measurable_set_bUnion s h lemma _root_.set.finite.null_measurable_set_sUnion {s : set (set α)} (hs : s.finite) (h : ∀ t ∈ s, null_measurable_set t μ) : null_measurable_set (⋃₀ s) μ := finite.measurable_set_sUnion hs h lemma _root_.set.finite.null_measurable_set_bInter {f : ι → set α} {s : set ι} (hs : s.finite) (h : ∀ b ∈ s, null_measurable_set (f b) μ) : null_measurable_set (⋂ b ∈ s, f b) μ := finite.measurable_set_bInter hs h lemma _root_.finset.null_measurable_set_bInter {f : ι → set α} (s : finset ι) (h : ∀ b ∈ s, null_measurable_set (f b) μ) : null_measurable_set (⋂ b ∈ s, f b) μ := s.finite_to_set.null_measurable_set_bInter h lemma _root_.set.finite.null_measurable_set_sInter {s : set (set α)} (hs : s.finite) (h : ∀ t ∈ s, null_measurable_set t μ) : null_measurable_set (⋂₀ s) μ := null_measurable_set.sInter hs.countable h lemma null_measurable_set_to_measurable : null_measurable_set (to_measurable μ s) μ := (measurable_set_to_measurable _ _).null_measurable_set end section null_measurable variables [measurable_space α] [measurable_space β] [measurable_space γ] {f : α → β} {μ : measure α} /-- A function `f : α → β` is null measurable if the preimage of a measurable set is a null measurable set. -/ def null_measurable (f : α → β) (μ : measure α . volume_tac) : Prop := ∀ ⦃s : set β⦄, measurable_set s → null_measurable_set (f ⁻¹' s) μ protected lemma _root_.measurable.null_measurable (h : measurable f) : null_measurable f μ := λ s hs, (h hs).null_measurable_set protected lemma null_measurable.measurable' (h : null_measurable f μ) : @measurable (null_measurable_space α μ) β _ _ f := h lemma measurable.comp_null_measurable {g : β → γ} (hg : measurable g) (hf : null_measurable f μ) : null_measurable (g ∘ f) μ := hg.comp hf lemma null_measurable.congr {g : α → β} (hf : null_measurable f μ) (hg : f =ᵐ[μ] g) : null_measurable g μ := λ s hs, (hf hs).congr $ eventually_eq_set.2 $ hg.mono $ λ x hx, by rw [mem_preimage, mem_preimage, hx] end null_measurable section is_complete /-- A measure is complete if every null set is also measurable. A null set is a subset of a measurable set with measure `0`. Since every measure is defined as a special case of an outer measure, we can more simply state that a set `s` is null if `μ s = 0`. -/ class measure.is_complete {_ : measurable_space α} (μ : measure α) : Prop := (out' : ∀ s, μ s = 0 → measurable_set s) variables {m0 : measurable_space α} {μ : measure α} {s t : set α} theorem measure.is_complete_iff : μ.is_complete ↔ ∀ s, μ s = 0 → measurable_set s := ⟨λ h, h.1, λ h, ⟨h⟩⟩ theorem measure.is_complete.out (h : μ.is_complete) : ∀ s, μ s = 0 → measurable_set s := h.1 theorem measurable_set_of_null [μ.is_complete] (hs : μ s = 0) : measurable_set s := measure_theory.measure.is_complete.out' s hs theorem null_measurable_set.measurable_of_complete (hs : null_measurable_set s μ) [μ.is_complete] : measurable_set s := diff_diff_cancel_left (subset_to_measurable μ s) ▸ (measurable_set_to_measurable _ _).diff (measurable_set_of_null (ae_le_set.1 hs.to_measurable_ae_eq.le)) theorem null_measurable.measurable_of_complete [μ.is_complete] {m1 : measurable_space β} {f : α → β} (hf : null_measurable f μ) : measurable f := λ s hs, (hf hs).measurable_of_complete lemma _root_.measurable.congr_ae {α β} [measurable_space α] [measurable_space β] {μ : measure α} [hμ : μ.is_complete] {f g : α → β} (hf : measurable f) (hfg : f =ᵐ[μ] g) : measurable g := (hf.null_measurable.congr hfg).measurable_of_complete namespace measure /-- Given a measure we can complete it to a (complete) measure on all null measurable sets. -/ def completion {_ : measurable_space α} (μ : measure α) : @measure_theory.measure (null_measurable_space α μ) _ := { to_outer_measure := μ.to_outer_measure, m_Union := λ s hs hd, measure_Union₀ (hd.mono $ λ i j h, h.ae_disjoint) hs, trimmed := begin refine le_antisymm (λ s, _) (outer_measure.le_trim _), rw outer_measure.trim_eq_infi, simp only [to_outer_measure_apply], refine (infi₂_mono _).trans_eq (measure_eq_infi _).symm, exact λ t ht, infi_mono' (λ h, ⟨h.null_measurable_set, le_rfl⟩) end } instance completion.is_complete {m : measurable_space α} (μ : measure α) : μ.completion.is_complete := ⟨λ z hz, null_measurable_set.of_null hz⟩ @[simp] lemma coe_completion {_ : measurable_space α} (μ : measure α) : ⇑μ.completion = μ := rfl lemma completion_apply {_ : measurable_space α} (μ : measure α) (s : set α) : μ.completion s = μ s := rfl end measure end is_complete end measure_theory
83a233e792126d32ebaf70c614a0307865cf35c9
a11f4536efad51bc2b648123619720f3b9318c0f
/src/not_not_not.lean
03b1c0f0ffb9924b11d2713080c969635ea61949
[]
no_license
ezrasitorus/codewars_lean
909471d43f5130669a90b8e11afc37aec2f21d8f
6d1abcc1253403511f4cfd767c645596175e4fd3
refs/heads/master
1,672,659,589,352
1,603,281,507,000
1,603,281,507,000
288,579,451
0
0
null
null
null
null
UTF-8
Lean
false
false
163
lean
theorem not_not_not (P : Prop) : ¬ ¬ ¬ P → ¬ P := λ h p, h $ not_not_intro p theorem not_not_not' (P : Prop) : ¬ P → ¬ ¬ ¬ P := λ x y, y x
919bc5b5224c708b433f82e2ac049efecd250721
54d7e71c3616d331b2ec3845d31deb08f3ff1dea
/tests/lean/run/tick_id.lean
5443e46a226120fb7a4d5c963a6aa1c923713385
[ "Apache-2.0" ]
permissive
pachugupta/lean
6f3305c4292288311cc4ab4550060b17d49ffb1d
0d02136a09ac4cf27b5c88361750e38e1f485a1a
refs/heads/master
1,611,110,653,606
1,493,130,117,000
1,493,167,649,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
237
lean
def id₁ {'a : Type} (x : 'a) : 'a := x def id₂ {α : Type} (a : α) : α := a def id₃ {β : Type} (b : β) : β := b #check λ (α β : Type) (f : α → β) (a : α), f a #check λ ('a 'b : Type) (f : 'a → 'b) (a : 'a), f a
871447ba2bb40413caac255b77c3d3f43a59e9d3
cf39355caa609c0f33405126beee2739aa3cb77e
/tmp/mini_crush.lean
e2c0fdd3a16b22642bb7d909bb8cb99fb110d4b4
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
12,913
lean
declare_trace mini_crush namespace mini_crush open smt_tactic tactic /- Collect relevant functions -/ meta def is_auto_construction : name → bool | (name.mk_string "brec_on" p) := tt | (name.mk_string "cases_on" p) := tt | (name.mk_string "rec_on" p) := tt | (name.mk_string "no_confusion" p) := tt | (name.mk_string "below" p) := tt | _ := ff meta def is_relevant_fn (n : name) : tactic bool := do env ← get_env, if ¬env^.is_definition n ∨ is_auto_construction n then return ff else if env^.in_current_file n then return tt else in_open_namespaces n meta def collect_revelant_fns_aux : name_set → expr → tactic name_set | s e := e^.mfold s $ λ t _ s, match t with | expr.const c _ := if s^.contains c then return s else mcond (is_relevant_fn c) (do new_s ← return $ if c^.is_internal then s else s^.insert c, d ← get_decl c, collect_revelant_fns_aux new_s d^.value) (return s) | _ := return s end meta def collect_revelant_fns : tactic name_set := do ctx ← local_context, s₁ ← mfoldl (λ s e, infer_type e >>= collect_revelant_fns_aux s) mk_name_set ctx, target >>= collect_revelant_fns_aux s₁ /- repeat simp & intro -/ meta def collect_ctx_simps : tactic (list expr) := meta def size (e : expr) : nat := e^.fold 1 (λ e _ n, n+1) structure config := (num_rounds := 5) (max_depth := 2) (timeout := 10000) meta def close_easy (cfg : config) : smt_tactic unit := all_goals (repeat_at_most cfg^.num_rounds (ematch >> try close)) meta def destruct_and_close (cfg : config) (e : expr) : smt_tactic unit := destruct e >> close_easy cfg meta def induction_and_close (cfg : config) (e : expr) : smt_tactic unit := smt_tactic.induction e >> close_easy cfg open expr tactic meta def is_inductive (e : expr) : tactic bool := do type ← infer_type e, C ← return type^.get_app_fn, env ← get_env, return $ C^.is_constant && env^.is_inductive C^.const_name open monad meta def collect_inductive_aux : expr_set → expr → tactic expr_set | S e := if S^.contains e then return S else do new_S ← cond (is_inductive e) (return $ S^.insert e) (return S), if e^.is_app then fold_explicit_args e new_S collect_inductive_aux else return new_S meta def collect_inductive : expr → tactic expr_set := collect_inductive_aux mk_expr_set meta def collect_inductive_from_target_aux : tactic (list expr) := do S ← target >>= collect_inductive, return $ list.qsort (λ e₁ e₂, size e₁ < size e₂) $ S^.to_list meta def collect_inductive_from_target : smt_tactic (list expr) := collect_inductive_from_target_aux meta def snapshot := smt_state × tactic_state meta def save : smt_tactic snapshot := smt_tactic.read meta def restore : snapshot → smt_tactic unit := smt_tactic.write open smt_tactic meta def rsimp_target : smt_tactic unit := do ccs ← to_cc_state, rsimp.rsimplify_goal ccs meta def try_snapshots {α} (cont : α → smt_tactic unit) : list (α × snapshot) → smt_tactic unit | [] := failed | ((a, s)::ss) := (restore s >> cont a) <|> try_snapshots ss meta def search {α} (max_depth : nat) (act : nat → α → smt_tactic (list (α × snapshot))) : nat → α → smt_tactic unit | n s := do all_goals $ try intros >> try close, now <|> if n > max_depth then trace "max depth reached" >> trace_state >> failed else all_goals $ try intros >> act n s >>= try_snapshots (search (n+1)) meta def init_lemmas : smt_tactic unit := do /- Add equational lemmas for relevant functions -/ fns ← collect_revelant_fns, mfor' fns^.to_list add_ematch_eqn_lemmas_for, /- Add [rsimp] lemmas -/ get_hinst_lemmas_for_attr `rsimp_attr >>= add_lemmas meta def try_induction_aux (hs : hinst_lemmas) (cont : smt_tactic unit) : list expr → smt_tactic unit | [] := failed | (e::es) := (induction e >> all_goals (set_lemmas hs >> try intros >> cont >> now)) <|> try_induction_aux es meta def try_induction (hs : hinst_lemmas) (cont : smt_tactic unit) : smt_tactic unit := collect_inductive_from_target >>= mfilter (λ e, return $ e^.is_local_constant) >>= try_induction_aux hs cont meta def mini_crush_1 (cfg : config := {}) : tactic unit := using_smt $ do init_lemmas, hs ← get_lemmas, close_easy cfg, now <|> try_induction hs (close_easy cfg) universe variable u export nat (succ) def is_zero : ℕ → bool | 0 := tt | (succ _) := ff def plus : ℕ → ℕ → ℕ | 0 m := m | (succ n') m := succ (plus n' m) def times : ℕ → ℕ → ℕ | 0 m := m | (succ n) m := plus m (times n m) @[simp] theorem n_plus_0 (n : ℕ) : plus n 0 = n := by mini_crush_1 @[simp] theorem plus_assoc (n1 n2 n3 : nat) : plus (plus n1 n2) n3 = plus n1 (plus n2 n3) := by mini_crush_1 inductive nat_list : Type | NNil : nat_list | NCons : nat → nat_list → nat_list open nat_list def nlength : nat_list → ℕ | NNil := 0 | (NCons _ ls') := succ (nlength ls') def napp : nat_list → nat_list → nat_list | NNil ls2 := ls2 | (NCons n ls1') ls2 := NCons n (napp ls1' ls2) theorem nlength_napp (ls1 ls2 : nat_list) : nlength (napp ls1 ls2) = plus (nlength ls1) (nlength ls2) := by mini_crush_1 inductive nat_btree : Type | NLeaf : nat_btree | NNode : nat_btree → ℕ → nat_btree → nat_btree open nat_btree def nsize : nat_btree → ℕ | NLeaf := succ 0 | (NNode tr1 _ tr2) := plus (nsize tr1) (nsize tr2) def nsplice : nat_btree → nat_btree → nat_btree | NLeaf tr2 := NNode tr2 0 NLeaf | (NNode tr1' n tr2') tr2 := NNode (nsplice tr1' tr2) n tr2' theorem nsize_nsplice (tr1 tr2 : nat_btree) : nsize (nsplice tr1 tr2) = plus (nsize tr2) (nsize tr1) := by mini_crush_1 inductive formula : Type | Eq : nat → nat → formula | And : formula → formula → formula | Forall : (nat → formula) → formula open formula example forall_refl : formula := Forall (λ x, Eq x x) def formula_denote : formula → Prop | (Eq n1 n2) := n1 = n2 | (And f1 f2) := formula_denote f1 ∧ formula_denote f2 | (Forall f') := ∀ n : nat, formula_denote (f' n) def swapper : formula → formula | (Eq n1 n2) := Eq n2 n1 | (And f1 f2) := And (swapper f2) (swapper f1) | (Forall f') := Forall (λ n, swapper (f' n)) attribute [simp] formula_denote swapper theorem swapper_preserves_truth (f) : formula_denote f → formula_denote (swapper f) := by induction f; simph; intros; rsimp exit begin [smt] induction f, admit, admit, intros, init_lemmas, add_lemmas_from_facts, eblast, rsimp_target, intros, eblast, rsimp_target end exit begin [smt] induction ls1, init_lemmas, eblast end exit (intros >> close >> now) <|> (if n > max_depth then (trace "max depth reached" >> rsimp >> trace_state) else all_goals $ intros ) exit smt_tactic.intros >> collect_inductive_from_target >>= try_destruct cfg >>= try_snapshots (search (n+1)) meta def try_and_save {α} (t : smt_tactic α) : smt_tactic (option (α × nat × snapshot)) := do { s ← save, a ← t, new_s ← save, n ← num_goals, restore s, return (a, n, new_s) } <|> return none meta def try_all_aux {α} (ts : α → smt_tactic unit) : list α → list (α × nat × snapshot) → smt_tactic (list (α × nat × snapshot)) | [] [] := failed | [] rs := return rs^.reverse | (v::vs) rs := do r ← try_and_save (ts v), match r with | some (_, 0, s) := return [(v, 0, s)] | some (_, n, s) := try_all_aux vs ((v, n, s)::rs) | none := try_all_aux vs rs end meta def try_all {α} (ts : α → smt_tactic unit) (vs : list α) : smt_tactic (list (α × nat × snapshot)) := try_all_aux ts vs [] meta def sort_snapshots (rs : list (expr × nat × snapshot)) : list snapshot := let ss := flip list.qsort rs $ λ ⟨e₁, n₁, _⟩ ⟨e₂, n₂, _⟩, if n₁ ≠ n₂ then n₁ < n₂ else size e₁ < size e₂ in ss^.for $ λ ⟨_, _, s⟩, s meta def try_destruct (cfg : config) (es : list expr) : smt_tactic (list snapshot) := sort_snapshots <$> try_all (destruct_and_close cfg) es meta def try_induction (cfg : config) (es : list expr) : smt_tactic (list snapshot) := sort_snapshots <$> try_all (induction_and_close cfg) es meta def try_snapshots {α} (cont : smt_tactic α) : list snapshot → smt_tactic α | [] := failed | (s::ss) := (restore s >> cont) <|> try_snapshots ss meta def search (cfg : config) : nat → smt_tactic unit | n := close >> now <|> if n > cfg^.max_depth then trace "max depth reached" >> rsimp >> trace_state else all_goals $ smt_tactic.intros >> collect_inductive_from_target >>= try_destruct cfg >>= try_snapshots (search (n+1)) meta def with_smt (t : smt_tactic unit) : tactic unit := using_smt_with {em_attr := `rsimp_attr} t meta def strategy_1 (cfg : config := {}) : tactic unit := try_for cfg^.timeout (try simph >> try intros >> try simph >> try contradiction >> now) meta def strategy_2 (cfg : config := {}) : tactic unit := try_for cfg^.timeout $ with_smt $ collect_inductive_from_target >>= try_induction cfg >>= try_snapshots (all_goals $ trace "------------" >> trace_state >> now) -- exit -- try close >> try simph >> try intros >> try simph >> try contradiction >> now) meta def strategy_3 (cfg : config := {}) : tactic unit := try_for cfg^.timeout $ with_smt $ collect_inductive_from_target >>= try_induction cfg >>= try_snapshots (all_goals $ trace "------------" >> trace_state >> trace "--------" >> try close >> try (search cfg 1)) meta def main (cfg : config := {}) : tactic unit := strategy_2 <|> strategy_3 end mini_crush meta def mini_crush := mini_crush.main universe variable u export nat (succ) def is_zero : ℕ → bool | 0 := tt | (succ _) := ff def plus : ℕ → ℕ → ℕ | 0 m := m | (succ n') m := succ (plus n' m) def times : ℕ → ℕ → ℕ | 0 m := m | (succ n) m := plus m (times n m) attribute [simp] is_zero plus set_option trace.smt.ematch true theorem n_plus_0 (n : ℕ) : plus n 0 = n := by mini_crush.strategy_3 exit inductive nat_list : Type | NNil : nat_list | NCons : nat → nat_list → nat_list open nat_list def nlength : nat_list → ℕ | NNil := 0 | (NCons _ ls') := succ (nlength ls') def napp : nat_list → nat_list → nat_list | NNil ls2 := ls2 | (NCons n ls1') ls2 := NCons n (napp ls1' ls2) attribute [simp] nlength napp theorem nlength_napp (ls1 ls2 : nat_list) : nlength (napp ls1 ls2) = plus (nlength ls1) (nlength ls2) := by induction ls1; rsimp inductive nat_btree : Type | NLeaf : nat_btree | NNode : nat_btree → ℕ → nat_btree → nat_btree open nat_btree def nsize : nat_btree → ℕ | NLeaf := succ 0 | (NNode tr1 _ tr2) := plus (nsize tr1) (nsize tr2) def nsplice : nat_btree → nat_btree → nat_btree | NLeaf tr2 := NNode tr2 0 NLeaf | (NNode tr1' n tr2') tr2 := NNode (nsplice tr1' tr2) n tr2' attribute [simp] nsize nsplice theorem plus_assoc (n1 n2 n3 : nat) : plus (plus n1 n2) n3 = plus n1 (plus n2 n3) := by induction n1; simph attribute [simp] n_plus_0 plus_assoc theorem nsize_nsplice (tr1 tr2 : nat_btree) : nsize (nsplice tr1 tr2) = plus (nsize tr2) (nsize tr1) := by induction tr1; simph export list (nil cons) def length {α : Type u} : list α → ℕ | nil := 0 | (cons _ ls') := succ (length ls') def app {α : Type u} : list α → list α → list α | nil ls2 := ls2 | (cons x ls1') ls2 := cons x (app ls1' ls2) attribute [simp] length app theorem length_app {α : Type u} (ls1 ls2 : list α) : length (app ls1 ls2) = plus (length ls1) (length ls2) := by induction ls1; simph inductive pformula : Type | Truth : pformula | Falsehood : pformula | Conjunction : pformula → pformula → pformula. open pformula def pformula_denote : pformula → Prop | Truth := true | Falsehood := false | (Conjunction f1 f2) := pformula_denote f1 ∧ pformula_denote f2 attribute [simp] pformula_denote open pformula inductive formula : Type | Eq : nat → nat → formula | And : formula → formula → formula | Forall : (nat → formula) → formula open formula example forall_refl : formula := Forall (λ x, Eq x x) def formula_denote : formula → Prop | (Eq n1 n2) := n1 = n2 | (And f1 f2) := formula_denote f1 ∧ formula_denote f2 | (Forall f') := ∀ n : nat, formula_denote (f' n) def swapper : formula → formula | (Eq n1 n2) := Eq n2 n1 | (And f1 f2) := And (swapper f2) (swapper f1) | (Forall f') := Forall (λ n, swapper (f' n)) attribute [simp] formula_denote swapper theorem swapper_preserves_truth (f) : formula_denote f → formula_denote (swapper f) := begin (do s ← mini_crush.collect_revelant_fns, tactic.trace s^.to_list), induction f; intro h; simp at h; simph; intros; rsimp end
462201f5046c593b69114653ab2fad74ca0c7368
32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7
/tests/lean/run/match1.lean
ad67f5d62632429c13b226447c61dfdfcb76f123
[ "Apache-2.0" ]
permissive
walterhu1015/lean4
b2c71b688975177402758924eaa513475ed6ce72
2214d81e84646a905d0b20b032c89caf89c737ad
refs/heads/master
1,671,342,096,906
1,599,695,985,000
1,599,695,985,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,103
lean
new_frontend def f (xs : List Nat) : List Bool := xs.map fun | 0 => true | _ => false #eval f [1, 2, 0, 2] theorem ex1 : f [1, 0, 2] = [false, true, false] := rfl #check f def g (xs : List Nat) : List Bool := xs.map $ by { intro | 0 => exact true | _ => exact false } theorem ex2 : g [1, 0, 2] = [false, true, false] := rfl theorem ex3 {p q r : Prop} : p ∨ q → r → (q ∧ r) ∨ (p ∧ r) := by intro | Or.inl hp, h => { apply Or.inr; apply And.intro; assumption; assumption } | Or.inr hq, h => { apply Or.inl; exact ⟨hq, h⟩ } inductive C | mk₁ : Nat → C | mk₂ : Nat → Nat → C def C.x : C → Nat | C.mk₁ x => x | C.mk₂ x _ => x def head : {α : Type} → List α → Option α | _, a::as => some a | _, _ => none theorem ex4 : head [1, 2] = some 1 := rfl def head2 : {α : Type} → List α → Option α := @fun | _, a::as => some a | _, _ => none theorem ex5 : head2 [1, 2] = some 1 := rfl def head3 {α : Type} (xs : List α) : Option α := let rec aux : {α : Type} → List α → Option α | _, a::as => some a | _, _ => none; aux xs theorem ex6 : head3 [1, 2] = some 1 := rfl inductive Vec.{u} (α : Type u) : Nat → Type u | nil : Vec α 0 | cons {n} (head : α) (tail : Vec α n) : Vec α (n+1) def Vec.mapHead1 {α β δ} : {n : Nat} → Vec α n → Vec β n → (α → β → δ) → Option δ | _, nil, nil, f => none | _, cons a as, cons b bs, f => some (f a b) def Vec.mapHead2 {α β δ} : {n : Nat} → Vec α n → Vec β n → (α → β → δ) → Option δ | _, nil, nil, f => none | _, @cons _ n a as, cons b bs, f => some (f a b) def Vec.mapHead3 {α β δ} : {n : Nat} → Vec α n → Vec β n → (α → β → δ) → Option δ | _, nil, nil, f => none | _, cons (tail := as) (head := a), cons b bs, f => some (f a b) inductive Foo | mk₁ (x y z w : Nat) | mk₂ (x y z w : Nat) def Foo.z : Foo → Nat | mk₁ (z := z) .. => z | mk₂ (z := z) .. => z #eval (Foo.mk₁ 10 20 30 40).z theorem ex7 : (Foo.mk₁ 10 20 30 40).z = 30 := rfl def Foo.addY? : Foo × Foo → Option Nat | (mk₁ (y := y₁) .., mk₁ (y := y₂) ..) => some (y₁ + y₂) | _ => none #eval Foo.addY? (Foo.mk₁ 1 2 3 4, Foo.mk₁ 10 20 30 40) theorem ex8 : Foo.addY? (Foo.mk₁ 1 2 3 4, Foo.mk₁ 10 20 30 40) = some 22 := rfl instance {α} : Inhabited (Sigma fun m => Vec α m) := ⟨⟨0, Vec.nil⟩⟩ partial def filter {α} (p : α → Bool) : {n : Nat} → Vec α n → Sigma fun m => Vec α m | _, Vec.nil => ⟨0, Vec.nil⟩ | _, Vec.cons x xs => match p x, filter p xs with | true, ⟨_, ys⟩ => ⟨_, Vec.cons x ys⟩ | false, ys => ys inductive Bla | ofNat (x : Nat) | ofBool (x : Bool) def Bla.optional? : Bla → Option Nat | ofNat x => some x | ofBool _ => none def Bla.isNat? (b : Bla) : Option { x : Nat // optional? b = some x } := match h:b.optional? with | some x => some ⟨x, h⟩ -- here `h` is a proof for `b.optional?=some x` | none => none -- here `h` is a proof for `b.optional?=none`
1434ab873e19a9327ec9ea2a2e14e73cd02110e7
c777c32c8e484e195053731103c5e52af26a25d1
/src/data/set/Union_lift.lean
80b88373cbbede0c806cfcc5279f84dc341167db
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
7,117
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 data.set.lattice import order.directed /-! # Union lift > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines `set.Union_lift` 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.Union_lift` - Given a Union of sets `Union 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.lift_cover` - Version of `set.Union_lift` for the special case that the sets cover the entire type. ## Main statements There are proofs of the obvious properties of `Union_lift`, i.e. what it does to elements of each of the sets in the `Union`, stated in different ways. There are also three lemmas about `Union_lift` intended to aid with proving that `Union_lift` 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.Union_lift_const` *`set.Union_lift_unary` *`set.Union_lift_binary` ## Tags directed union, directed supremum, glue, gluing -/ variables {α ι β : Type*} namespace set section Union_lift /- The unused argument `hf` is left in the definition so that the `simp` lemmas `Union_lift_inclusion` will work without the user having to provide `hf` explicitly to simplify terms involving `Union_lift`. -/ /-- Given a Union of sets `Union S`, define a function on the Union by defining it on each component, and proving that it agrees on the intersections. -/ @[nolint unused_arguments] noncomputable def Union_lift (S : ι → set α) (f : Π i (x : 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 ⊆ Union S) (x : T) : β := let i := classical.indefinite_description _ (mem_Union.1 (hT x.prop)) in f i ⟨x, i.prop⟩ variables {S : ι → set α} {f : Π i (x : 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 ⊆ Union S} (hT' : T = Union S) @[simp] lemma Union_lift_mk {i : ι} (x : S i) (hx : (x : α) ∈ T) : Union_lift S f hf T hT ⟨x, hx⟩ = f i x := let j := classical.indefinite_description _ (mem_Union.1 (hT hx)) in by cases x with x hx; exact hf j i x j.2 _ @[simp] lemma Union_lift_inclusion {i : ι} (x : S i) (h : S i ⊆ T) : Union_lift S f hf T hT (set.inclusion h x) = f i x := Union_lift_mk x _ lemma Union_lift_of_mem (x : T) {i : ι} (hx : (x : α) ∈ S i) : Union_lift S f hf T hT x = f i ⟨x, hx⟩ := by cases x with x hx; exact hf _ _ _ _ _ /-- `Union_lift_const` is useful for proving that `Union_lift` 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`. -/ lemma Union_lift_const (c : T) (ci : Π i, S i) (hci : ∀ i, (ci i : α) = c) (cβ : β) (h : ∀ i, f i (ci i) = cβ) : Union_lift S f hf T hT c = cβ := let ⟨i, hi⟩ := set.mem_Union.1 (hT c.prop) in have (ci i) = ⟨c, hi⟩, from subtype.ext (hci i), by rw [Union_lift_of_mem _ hi, ← this, h] /-- `Union_lift_unary` is useful for proving that `Union_lift` 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. -/ lemma Union_lift_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_Union S i) x) = set.inclusion (show S i ⊆ T, from hT'.symm ▸ set.subset_Union S i) (ui i x)) (uβ : β → β) (h : ∀ i (x : S i), (f i (ui i x)) = uβ (f i x)) (x : T) : Union_lift S f hf T (le_of_eq hT') (u x) = uβ (Union_lift S f hf T (le_of_eq hT') x) := begin subst hT', cases set.mem_Union.1 x.prop with i hi, rw [Union_lift_of_mem x hi, ← h i], have : x = (set.inclusion (set.subset_Union S i) ⟨x, hi⟩), { cases x, refl }, have hx' : (set.inclusion (set.subset_Union S i) (ui i ⟨x, hi⟩) : α) ∈ S i, from (ui i ⟨x, hi⟩).prop, conv_lhs { rw [this, hui, Union_lift_inclusion] } end /-- `Union_lift_binary` is useful for proving that `Union_lift` 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 `*`. -/ lemma Union_lift_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_Union S i) (opi i x y) = op (set.inclusion (show S i ⊆ T, from hT'.symm ▸ set.subset_Union S i) x) (set.inclusion (show S i ⊆ T, from hT'.symm ▸ set.subset_Union 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) : Union_lift S f hf T (le_of_eq hT') (op x y) = opβ (Union_lift S f hf T (le_of_eq hT') x) (Union_lift S f hf T (le_of_eq hT') y) := begin subst hT', cases set.mem_Union.1 x.prop with i hi, cases set.mem_Union.1 y.prop with j hj, rcases dir i j with ⟨k, hik, hjk⟩, rw [Union_lift_of_mem x (hik hi), Union_lift_of_mem y (hjk hj), ← h k], have hx : x = (set.inclusion (set.subset_Union S k) ⟨x, hik hi⟩), { cases x, refl }, have hy : y = (set.inclusion (set.subset_Union S k) ⟨y, hjk hj⟩), { cases y, refl }, have hxy : (set.inclusion (set.subset_Union S k) (opi k ⟨x, hik hi⟩ ⟨y, hjk hj⟩) : α) ∈ S k, from (opi k ⟨x, hik hi⟩ ⟨y, hjk hj⟩).prop, conv_lhs { rw [hx, hy, ← hopi, Union_lift_of_mem _ hxy] }, simp only [coe_inclusion, subtype.coe_eta] end end Union_lift variables {S : ι → set α} {f : Π i (x : S i), β} {hf : ∀ i j (x : α) (hxi : x ∈ S i) (hxj : x ∈ S j), f i ⟨x, hxi⟩ = f j ⟨x, hxj⟩} {hS : Union S = univ} /-- Glue together functions defined on each of a collection `S` of sets that cover a type. See also `set.Union_lift`. -/ noncomputable def lift_cover (S : ι → set α) (f : Π i (x : S i), β) (hf : ∀ i j (x : α) (hxi : x ∈ S i) (hxj : x ∈ S j), f i ⟨x, hxi⟩ = f j ⟨x, hxj⟩) (hS : Union S = univ) (a : α) : β := Union_lift S f hf univ (hS ▸ set.subset.refl _) ⟨a, trivial⟩ @[simp] lemma lift_cover_coe {i : ι} (x : S i) : lift_cover S f hf hS x = f i x := Union_lift_mk x _ lemma lift_cover_of_mem {i : ι} {x : α} (hx : (x : α) ∈ S i) : lift_cover S f hf hS x = f i ⟨x, hx⟩ := Union_lift_of_mem ⟨x, trivial⟩ hx attribute [irreducible] Union_lift lift_cover end set
ba3c4a966bc5753433c6b97324c0eeee86cae265
8e381650eb2c1c5361be64ff97e47d956bf2ab9f
/src/Kenny/projective_line.lean
e07eced3cbc1424b2c4a527352c1d9ee8e5daba0
[]
no_license
alreadydone/lean-scheme
04c51ab08eca7ccf6c21344d45d202780fa667af
52d7624f57415eea27ed4dfa916cd94189221a1c
refs/heads/master
1,599,418,221,423
1,562,248,559,000
1,562,248,559,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
19,824
lean
import Kenny.sheaf_of_rings_on_opens instances.affine_scheme data.polynomial universes u v w open topological_space namespace localization variables {R : Type u} [comm_ring R] theorem away.inv_self_mul_of (x : R) : away.inv_self x * of x = 1 := show mk (1 * x) (⟨x, _⟩ * 1) = 1, by rw [one_mul, mul_one, mk_self] theorem away.of_mul_inv_self (x : R) : of x * away.inv_self x = 1 := show mk (x * 1) (1 * ⟨x, _⟩) = 1, by rw [one_mul, mul_one, mk_self] theorem away.lift'_inv_self (x : R) {A : Type v} [comm_ring A] (f : R → A) [is_ring_hom f] (g hg) : lift' f g hg (away.inv_self x) = ((g ⟨x, 1, pow_one x⟩)⁻¹ : units A) := by rw [away.inv_self, lift'_mk, is_ring_hom.map_one f, one_mul] theorem inj_Zariski_induced_localization_of (S : set R) [is_submonoid S] : function.injective (Zariski.induced (of : R → localization R S)) := λ p q h, subtype.eq $ calc p.1 = ideal.map of (ideal.comap of p.1) : (map_comap _ _).symm ... = ideal.map of ((Zariski.induced of p).1) : rfl ... = ideal.map of ((Zariski.induced of q).1) : by rw h ... = ideal.map of (ideal.comap of q.1) : rfl ... = q.1 : map_comap _ _ -- theorem Zariski_induced_localization_of_D (S : set R) [is_submonoid S] (r : R) (s : S) : -- Zariski.induced of '' (Spec.DO (localization R S) (mk r s)).1 = -- Spec.DO R r := -- set.ext $ λ p, ⟨λ ⟨q, hq, hqp⟩, by change mk r s ∉ q.1.1 at hq, _⟩ -- #exit theorem map_eq (S : set R) [is_submonoid S] (I : ideal R) : (I.map (of : R → localization R S)).1 = { m | ∃ r ∈ I, ∃ s ∈ S, mk r ⟨s, H⟩ = m } := set.ext $ λ x, ⟨λ hx, submodule.span_induction hx (λ x ⟨r, hrI, hrx⟩, ⟨r, hrI, 1, is_submonoid.one_mem S, hrx⟩) ⟨0, I.zero_mem, 1, is_submonoid.one_mem S, rfl⟩ (λ x y ⟨r1, hrI1, s1, hs1, ihx⟩ ⟨r2, hrI2, s2, hs2, ihy⟩, ⟨s1 * r2 + s2 * r1, I.add_mem (I.mul_mem_left hrI2) (I.mul_mem_left hrI1), s1 * s2, is_submonoid.mul_mem hs1 hs2, by rw [← ihx, ← ihy]; refl⟩) (λ c x ⟨r, hrI, s, hs, hx⟩, localization.induction_on c $ λ r2 s2, ⟨r2 * r, I.mul_mem_left hrI, s2.1 * s, is_submonoid.mul_mem s2.2 hs, hx ▸ rfl⟩), λ ⟨r, hrI, s, hs, hx⟩, by rw [← hx, mk_eq]; exact (I.map (of : R → localization R S)).mul_mem_right (ideal.mem_map_of_mem hrI)⟩ theorem mem_map (S : set R) [is_submonoid S] (I : ideal R) (x : localization R S) : x ∈ I.map (of : R → localization R S) ↔ ∃ r ∈ I, ∃ s ∈ S, mk r ⟨s, H⟩ = x := show x ∈ (I.map of).1 ↔ _, by rw map_eq; refl theorem comap_map (S : set R) [is_submonoid S] (I : ideal R) : ((I.map (of : R → localization R S)).comap of).1 = { r | ∃ s ∈ S, r * s ∈ I } := begin change of ⁻¹' (I.map of).1 = _, rw map_eq, ext x, split, { rintros ⟨r, hrI, s, hs, hx⟩, rcases quotient.exact hx with ⟨t, htS, ht⟩, change (s * x - 1 * r) * t = 0 at ht, rw [sub_mul, one_mul, sub_eq_zero] at ht, refine ⟨s * t, is_submonoid.mul_mem hs htS, _⟩, rw [mul_left_comm, ← mul_assoc, ht], exact I.mul_mem_right hrI }, { rintros ⟨s, hs, hxsI⟩, refine ⟨x * s, hxsI, s, hs, mk_mul_cancel_right x ⟨s, hs⟩⟩ } end theorem mem_comap_map (S : set R) [is_submonoid S] (I : ideal R) (x : R) : x ∈ (I.map (of : R → localization R S)).comap of ↔ ∃ s ∈ S, x * s ∈ I := show x ∈ ((I.map of).comap of).1 ↔ _, by rw comap_map; refl theorem prime_map (S : set R) [is_submonoid S] (p : ideal R) (hp1 : p.is_prime) (hp2 : S ∩ p.1 = ∅) : (p.map (of : R → localization R S)).is_prime := begin rw set.eq_empty_iff_forall_not_mem at hp2, split, { intros h1, have h2 : ((p.map (of : R → localization R S)).comap of).1 = set.univ, { rw h1, refl }, rw [comap_map, set.eq_univ_iff_forall] at h2, rcases h2 1 with ⟨s, hs, hsp⟩, rw one_mul at hsp, exact hp2 s ⟨hs, hsp⟩ }, intros x y, refine localization.induction_on x (λ r1 s1, localization.induction_on y (λ r2 s2, _)), cases s1 with s1 hs1, cases s2 with s2 hs2, rw [mem_map, mem_map, mem_map], rintros ⟨r, hrp, s, hs, h1⟩, rcases quotient.exact h1 with ⟨t, hts, ht⟩, change (s * (r1 * r2) - s1 * s2 * r) * t = 0 at ht, rw [sub_mul, sub_eq_zero] at ht, have h2 : s1 * s2 * r * t ∈ p := p.mul_mem_right (p.mul_mem_left hrp), rw ← ht at h2, have hsp : s ∉ p := mt (and.intro hs) (hp2 s), have htp : t ∉ p := mt (and.intro hts) (hp2 t), replace h2 := (hp1.2 h2).resolve_right htp, replace h2 := (hp1.2 h2).resolve_left hsp, cases hp1.2 h2 with hrp1 hrp2, { exact or.inl ⟨r1, hrp1, s1, hs1, rfl⟩ }, { exact or.inr ⟨r2, hrp2, s2, hs2, rfl⟩ } end end localization variables {R : Type u} [comm_ring R] theorem range_Zariski_induced_localization_of (S : set R) [is_submonoid S] : set.range (Zariski.induced (localization.of : R → localization R S)) = ⋂ s ∈ S, (Spec.DO R s).1 := set.ext $ λ p, ⟨λ ⟨q, hqp⟩, hqp ▸ set.mem_bInter (λ s hs hsq, p.2.1 $ p.1.eq_top_iff_one.2 $ have localization.mk s ⟨s, hs⟩ = 1, from localization.mk_self, by rw ← hqp; change localization.of (1:R) ∈ q.1; rw [localization.of_one, ← this, localization.mk_eq]; exact q.1.mul_mem_right hsq), λ hp, ⟨⟨ideal.map localization.of p.1, localization.prime_map _ _ p.2 (set.eq_empty_iff_forall_not_mem.2 $ λ r hr, set.mem_bInter_iff.1 hp r hr.1 hr.2)⟩, subtype.eq $ ideal.ext $ λ x, ⟨λ hx, let ⟨s, hs, hxsp⟩ := (localization.mem_comap_map _ _ _).1 hx in (p.2.2 hxsp).resolve_right $ set.mem_bInter_iff.1 hp s hs, λ hx, (localization.mem_comap_map _ _ _).2 ⟨1, is_submonoid.one_mem S, by rwa mul_one⟩⟩⟩⟩ @[simp] theorem Spec.D'_one : Spec.D' (1:R) = set.univ := set.eq_univ_of_forall $ λ p hp, p.2.1 $ p.1.eq_top_iff_one.2 hp @[simp] theorem Spec.DO_one : Spec.DO R 1 = ⊤ := opens.ext Spec.D'_one @[simp] theorem Spec.D'_pow_succ (x : R) (n : ℕ) : Spec.D' (x^(n+1)) = Spec.D' x := set.ext $ λ p, not_congr ⟨p.2.mem_of_pow_mem (n+1), p.1.mul_mem_right⟩ @[simp] theorem Spec.DO_pow_succ (x : R) {n : ℕ} : Spec.DO R (x^(n+1)) = Spec.DO R x := opens.ext $ Spec.D'_pow_succ x n theorem range_Zariski_induced_localization_away_of (x : R) : set.range (Zariski.induced (localization.of : R → localization.away x)) = (Spec.DO R x).1 := (range_Zariski_induced_localization_of _).trans $ set.subset.antisymm (set.bInter_subset_of_mem ⟨1, pow_one x⟩) (set.subset_bInter $ λ r ⟨n, hxnr⟩, hxnr ▸ nat.cases_on n (by rw [pow_zero, Spec.DO_one]; exact set.subset_univ _) (λ n, by rw Spec.DO_pow_succ; exact set.subset.refl _)) theorem exists_Zariski_induced_of_not_mem (x : R) (p : Spec R) (hp : x ∉ p.1) : ∃ q : Spec (localization.away x), Zariski.induced localization.of q = p := ((set.ext_iff _ _).1 (range_Zariski_induced_localization_away_of x) _).2 hp theorem localization.mk_mem_iff (S : set R) [is_submonoid S] (I : ideal (localization R S)) (r : R) (s : S) : localization.mk r s ∈ I ↔ localization.of r ∈ I := ⟨λ hx, have localization.mk r s * localization.mk s 1 ∈ I := I.mul_mem_right hx, by rwa [localization.mk_mul_mk, mul_one, localization.mk_mul_cancel_right] at this, λ hx, by rw localization.mk_eq_mul_mk_one; exact I.mul_mem_right hx⟩ theorem Zariski_induced_localized_of_V (S : set R) [is_submonoid S] (E : set (localization R S)) : Zariski.induced localization.of '' Spec.V E = Spec.V { r | ∃ s : S, localization.mk r s ∈ E } ∩ set.range (Zariski.induced (localization.of : R → localization R S)) := set.ext $ λ p, ⟨λ ⟨q, hq, hqp⟩, ⟨λ r ⟨s, hrs⟩, hqp ▸ (localization.mk_mem_iff _ _ _ _).1 (hq hrs), q, hqp⟩, λ ⟨hp, q, hqp⟩, ⟨q, λ x, localization.induction_on x $ λ r s hrs, (localization.mk_mem_iff _ _ _ _).2 (show r ∈ (Zariski.induced localization.of q).1, from hqp.symm ▸ hp ⟨s, hrs⟩), hqp⟩⟩ theorem set.image_compl_of_injective {α : Type u} {β : Type v} {f : α → β} (hf : function.injective f) (s : set α) : f '' -s = set.range f \ f '' s := set.ext $ λ b, ⟨λ ⟨a, hnas, hab⟩, ⟨⟨a, hab⟩, λ ⟨x, hxs, hxb⟩, hnas (hf (hxb.trans hab.symm) ▸ hxs)⟩, λ ⟨⟨a, hab⟩, hnbs⟩, ⟨a, λ has, hnbs (hab ▸ ⟨a, has, rfl⟩), hab⟩⟩ theorem set.diff_inter {α : Type u} (s t u : set α) : s \ (t ∩ u) = (s \ t) ∪ (s \ u) := set.ext $ λ x, by simp only [set.mem_diff, set.mem_inter_iff, set.mem_union, not_and, auto.classical.implies_iff_not_or, and_or_distrib_left] theorem Zariski_induced_localized_of_D (S : set R) [is_submonoid S] (E : set (localization R S)) : Zariski.induced localization.of '' Spec.D E = Spec.D { r | ∃ s : S, localization.mk r s ∈ E } ∩ set.range (Zariski.induced (localization.of : R → localization R S)) := by rw [Spec.D, set.image_compl_of_injective (localization.inj_Zariski_induced_localization_of S), Zariski_induced_localized_of_V, set.diff_inter, set.diff_self, set.union_empty, set.inter_comm]; refl theorem Zariski.is_open_iff (U : set (Spec R)) : is_open U ↔ ∃ E : set R, Spec.D E = U := ⟨λ ⟨E, HE⟩, ⟨E, set.compl_compl U ▸ HE ▸ rfl⟩, λ ⟨E, HE⟩, ⟨E, HE ▸ (set.compl_compl $ Spec.V E).symm⟩⟩ theorem open_Zariski_induced_localization_of (x : R) (U : set (Spec (localization.away x))) (hu : is_open U) : is_open (Zariski.induced localization.of '' U) := let ⟨E, HEU⟩ := (Zariski.is_open_iff U).1 hu in by rw [← HEU, Zariski_induced_localized_of_D, range_Zariski_induced_localization_away_of]; exact is_open_inter ((Zariski.is_open_iff _).2 ⟨_, rfl⟩) (Spec.DO R x).2 @[simp] lemma congr_arg_Zariski {A : Type v} [comm_ring A] {f g : R → A} [is_ring_hom f] [is_ring_hom g] (h : f = g) (p) : Zariski.induced f p = Zariski.induced g p := subtype.eq $ ideal.ext $ λ x, show f x ∈ p.1 ↔ g x ∈ p.1, by rw h @[simp] lemma Zariski_induced_id (p) : Zariski.induced (id : R → R) p = p := subtype.eq $ ideal.ext $ λ x, iff.rfl @[simp] lemma Zariski_induced_comp {A : Type v} [comm_ring A] {B : Type w} [comm_ring B] (f : R → A) [is_ring_hom f] (g : A → B) [is_ring_hom g] (p) : Zariski.induced (g ∘ f) p = Zariski.induced f (Zariski.induced g p) := rfl namespace projective_line variables (R) [decidable_eq R] def inr_aux : polynomial R → localization.away (polynomial.X : polynomial R) := polynomial.eval₂ (localization.of ∘ polynomial.C) (localization.away.inv_self (polynomial.X)) set_option class.instance_max_depth 52 -- not one lower instance is_ring_hom_inr_aux : is_ring_hom (inr_aux R) := polynomial.eval₂.is_ring_hom _ def inverse : localization.away (polynomial.X : polynomial R) → localization.away (polynomial.X : polynomial R) := localization.lift' (inr_aux R) (λ p, ⟨inr_aux R p.1, localization.of p.1, by rcases p with ⟨_, n, rfl⟩; rw [inr_aux, polynomial.eval₂_pow, polynomial.eval₂_X, localization.of_pow, ← mul_pow, localization.away.inv_self_mul_of, one_pow], by rcases p with ⟨_, n, rfl⟩; rw [inr_aux, polynomial.eval₂_pow, polynomial.eval₂_X, localization.of_pow, ← mul_pow, localization.away.of_mul_inv_self, one_pow]⟩) (λ p, rfl) instance is_ring_hom_inverse : is_ring_hom (inverse R) := localization.lift'.is_ring_hom _ _ _ theorem inverse_inverse : inverse R ∘ inverse R = id := @@localization.funext _ _ _ (inverse R ∘ inverse R) _ (is_ring_hom.comp _ _) is_ring_hom.id $ λ p, polynomial.induction_on p (λ r, by simp only [inverse, function.comp_apply, localization.lift'_coe, localization.lift'_of, inr_aux, polynomial.eval₂_C]; refl) (λ p q hp hq, by rw [localization.coe_add, is_ring_hom.map_add (inverse R ∘ inverse R), hp, hq]; refl) (λ n r ih, by rw [pow_add, pow_one, ← mul_assoc, localization.coe_mul, is_ring_hom.map_mul (inverse R ∘ inverse R), ih]; simp only [inverse, function.comp_apply, localization.lift'_coe, localization.lift'_of, inr_aux, polynomial.eval₂_X, localization.away.lift'_inv_self]; refl) theorem Zariski_induced_inverse (p : Spec (localization.away (polynomial.X : polynomial R))) : Zariski.induced (inverse R) (Zariski.induced (inverse R) p) = p := calc Zariski.induced (inverse R) (Zariski.induced (inverse R) p) = Zariski.induced (inverse R ∘ inverse R) p : (Zariski_induced_comp (inverse R) (inverse R) p).symm ... = Zariski.induced id p : congr_arg_Zariski (inverse_inverse R) p ... = p : Zariski_induced_id p set_option class.instance_max_depth 32 inductive r : Spec (polynomial R) ⊕ Spec (polynomial R) → Spec (polynomial R) ⊕ Spec (polynomial R) → Prop | inv : ∀ p : Spec (localization.away (polynomial.X : polynomial R)), r (sum.inl $ Zariski.induced localization.of p) (sum.inr $ Zariski.induced (inr_aux R) p) end projective_line def projective_line (R : Type u) [comm_ring R] [decidable_eq R] : Type u := quot (projective_line.r R) namespace projective_line variables (R) [decidable_eq R] def inl (p : Spec (polynomial R)) : projective_line R := quot.mk _ $ sum.inl p def inr (p : Spec (polynomial R)) : projective_line R := quot.mk _ $ sum.inr p instance : topological_space (projective_line R) := { is_open := λ s, is_open (inl R ⁻¹' s) ∧ is_open (inr R ⁻¹' s), is_open_univ := ⟨is_open_univ, is_open_univ⟩, is_open_inter := λ s t hs ht, ⟨is_open_inter hs.1 ht.1, is_open_inter hs.2 ht.2⟩, is_open_sUnion := λ S HS, ⟨by rw set.preimage_sUnion; exact is_open_bUnion (λ i his, (HS i his).1), by rw set.preimage_sUnion; exact is_open_bUnion (λ i his, (HS i his).2)⟩ } theorem continuous_inl : continuous (inl R) := λ s hs, hs.1 theorem continuous_inr : continuous (inr R) := λ s hs, hs.2 theorem inj_indl : function.injective (Zariski.induced localization.of : Spec (localization.away (polynomial.X : polynomial R)) → Spec (polynomial R)) := localization.inj_Zariski_induced_localization_of (powers polynomial.X) theorem inverse_comp_localization_of : inverse R ∘ localization.of = inr_aux R := funext $ λ p, by rw [inverse, function.comp_apply, localization.lift'_of] theorem inj_indr : function.injective (Zariski.induced (inr_aux R) : Spec (localization.away (polynomial.X : polynomial R)) → Spec (polynomial R)) := have h2 : function.injective (Zariski.induced (inverse R)), from (equiv.bijective { to_fun := Zariski.induced (inverse R), inv_fun := Zariski.induced (inverse R), left_inv := λ p, by rw [← Zariski_induced_comp, @@congr_arg_Zariski _ _ (inverse R ∘ inverse R) id (is_ring_hom.comp _ _) is_ring_hom.id (inverse_inverse R), Zariski_induced_id], right_inv := λ p, by rw [← Zariski_induced_comp, @@congr_arg_Zariski _ _ (inverse R ∘ inverse R) id (is_ring_hom.comp _ _) is_ring_hom.id (inverse_inverse R), Zariski_induced_id] }).1, λ p1 p2 H, h2 $ inj_indl R $ by haveI : is_ring_hom (inverse R ∘ localization.of) := is_ring_hom.comp _ _; calc Zariski.induced localization.of (Zariski.induced (inverse R) p1) = Zariski.induced (inverse R ∘ localization.of) p1 : (Zariski_induced_comp _ _ _).symm ... = Zariski.induced (inr_aux R) p1 : congr_arg_Zariski (inverse_comp_localization_of R) p1 ... = Zariski.induced (inr_aux R) p2 : H ... = Zariski.induced (inverse R ∘ localization.of) p2 : congr_arg_Zariski (inverse_comp_localization_of R).symm p2 ... = Zariski.induced localization.of (Zariski.induced (inverse R) p2) : Zariski_induced_comp _ _ _ theorem exact (s t) (H : (quot.mk _ s : projective_line R) = quot.mk _ t) : s = t ∨ (∃ p, s = sum.inl (Zariski.induced localization.of p) ∧ t = sum.inr (Zariski.induced (inr_aux R) p)) ∨ ∃ p, s = sum.inr (Zariski.induced (inr_aux R) p) ∧ t = sum.inl (Zariski.induced localization.of p) := begin replace H := quot.exact _ H, induction H, case eqv_gen.rel : _ _ h { cases h, exact or.inr (or.inl ⟨_, rfl, rfl⟩) }, case eqv_gen.refl { left, refl }, case eqv_gen.symm : _ _ _ ih { rcases ih with rfl | ⟨p, rfl, rfl⟩ | ⟨p, rfl, rfl⟩, { exact or.inl rfl }, { exact or.inr (or.inr ⟨p, rfl, rfl⟩) }, { exact or.inr (or.inl ⟨p, rfl, rfl⟩) } }, case eqv_gen.trans : _ _ _ _ _ ih1 ih2 { rcases ih1 with rfl | ⟨p, rfl, rfl⟩ | ⟨p, rfl, rfl⟩, { exact ih2 }, { rcases ih2 with rfl | ⟨q, ih2, rfl⟩ | ⟨q, ih2, rfl⟩, { exact or.inr (or.inl ⟨p, rfl, rfl⟩) }, { cases ih2 }, { replace ih2 := inj_indr R (sum.inr.inj ih2), subst ih2, exact or.inl rfl } }, { rcases ih2 with rfl | ⟨q, ih2, rfl⟩ | ⟨q, ih2, rfl⟩, { exact or.inr (or.inr ⟨p, rfl, rfl⟩) }, { replace ih2 := inj_indl R (sum.inl.inj ih2), subst ih2, exact or.inl rfl }, { cases ih2 } } } end theorem inl_preimage_range_inr : inl R ⁻¹' set.range (inr R) = (Spec.DO (polynomial R) polynomial.X).1 := begin ext p, split, { rintros ⟨q, hq⟩ hp, rcases exact R _ _ hq with h | ⟨s, h1, h2⟩ | ⟨s, h1, h2⟩, { cases h }, { cases h1 }, cases h2, exact s.2.1 (s.1.eq_top_of_is_unit_mem hp $ is_unit_of_mul_one _ _ $ localization.away.of_mul_inv_self _) }, { rintros hp, rcases exists_Zariski_induced_of_not_mem _ _ hp with ⟨q, rfl⟩, use Zariski.induced (inr_aux R) q, symmetry, apply quot.sound, constructor } end theorem open_preimagelr : is_open (inl R ⁻¹' set.range (inr R)) := by rw inl_preimage_range_inr; exact D_fs_open _ _ set_option class.instance_max_depth 52 theorem inr_preimage_range_inl : inr R ⁻¹' set.range (inl R) = (Spec.DO (polynomial R) polynomial.X).1 := begin ext p, split, { rintros ⟨q, hq⟩ hp, rcases exact R _ _ hq with h | ⟨s, h1, h2⟩ | ⟨s, h1, h2⟩, { cases h }, { cases h2, refine s.2.1 (s.1.eq_top_of_is_unit_mem hp $ is_unit_of_mul_one _ (localization.of polynomial.X) _), rw [inr_aux, polynomial.eval₂_X, localization.away.inv_self_mul_of] }, { cases h1 } }, { rintros hp, rcases exists_Zariski_induced_of_not_mem _ _ hp with ⟨q, rfl⟩, rw [← Zariski_induced_inverse R q, ← Zariski_induced_comp, congr_arg_Zariski.{u u} (inverse_comp_localization_of R)], split, apply quot.sound, constructor } end set_option class.instance_max_depth 32 theorem open_preimagerl : is_open (inr R ⁻¹' set.range (inl R)) := by rw inr_preimage_range_inl; exact D_fs_open _ _ theorem set.preimage_range {α : Type u} {β : Type v} {f : α → β} : f ⁻¹' set.range f = set.univ := set.eq_univ_of_forall $ λ x, ⟨x, rfl⟩ def opl : opens (projective_line R) := ⟨set.range (inl R), by rw set.preimage_range; exact is_open_univ, open_preimagerl R⟩ def opr : opens (projective_line R) := ⟨set.range (inr R), open_preimagelr R, by rw set.preimage_range; exact is_open_univ⟩ inductive pbool : Type u | ff | tt. protected def covering : covering (⊤ : opens (projective_line R)) := { γ := pbool, Uis := λ b, pbool.rec_on b (opl R) (opr R), Hcov := opens.ext $ set.eq_univ_of_forall $ λ x, quot.induction_on x $ λ p, sum.cases_on p (λ v, set.mem_sUnion.2 ⟨_, ⟨_, ⟨pbool.ff, rfl⟩, rfl⟩, v, rfl⟩) (λ v, set.mem_sUnion.2 ⟨_, ⟨_, ⟨pbool.tt, rfl⟩, rfl⟩, v, rfl⟩) } def soropl : sheaf_of_rings_on_opens (projective_line R) (opl R) := sheaf_of_rings.pushforward (continuous_inl R) (structure_sheaf (polynomial R)) def soropr : sheaf_of_rings_on_opens (projective_line R) (opr R) := sheaf_of_rings.pushforward (continuous_inr R) (structure_sheaf (polynomial R)) def sorope : sheaf_of_rings_on_opens.equiv (sheaf_of_rings_on_opens.res_subset (soropl R) (opl R ⊓ opr R) lattice.inf_le_left) (sheaf_of_rings_on_opens.res_subset (soropr R) (opl R ⊓ opr R) lattice.inf_le_right) := sorry def sor : sheaf_of_rings (projective_line R) := sheaf_of_rings_on_opens.sheaf_glue (projective_line.covering R).Uis (λ b, pbool.rec_on b (soropl R) (soropr R)) (λ b₁ b₂, sorry) end projective_line
a45089409aaf016deff9ea0d8a54bcab626e0cdd
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/tests/lean/run/n1.lean
7ec581b0ebf4bce30aa0091869d417bb38f26ba2
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
843
lean
constant A : Type.{1} constant a : A constant g : A → A constant f : A → A → A (* local f = Const("f") local g = Const("g") local comma = name(",") function parse_pair() local p1 = parser.parse_expr() parser.check_token_next(comma, "invalid pair, ',' expected") print("line: " .. tostring(parser.pos())) local p2 = parser.parse_expr() return f(p1, p2) end local lbracket = name("[") local rbracket = name("]") function parse_bracket() local l, c = parser.pos() parser.check_token_next(lbracket, "'[' expected") local r = parser.parse_expr() parser.check_token_next(rbracket, "']' expected") return parser.save_pos(g(r), l, c) end *) notation `tst` A:(call parse_pair) := A notation `simple` A:(call parse_bracket) `,` B:(call parse_bracket) := f A B constant b : A check g (tst (simple [b], [a]), a)
d20642c6ea4425ee1a8bf945c92d1dda97b2ba55
9dc8cecdf3c4634764a18254e94d43da07142918
/src/order/modular_lattice.lean
278327a0625cfb74908d1c4df7b9d6ed4751a0c9
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
14,784
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson, Yaël Dillies -/ import order.cover import order.lattice_intervals /-! # Modular Lattices This file defines (semi)modular lattices, a kind of lattice useful in algebra. For examples, look to the subobject lattices of abelian groups, submodules, and ideals, or consider any distributive lattice. ## Typeclasses We define (semi)modularity typeclasses as Prop-valued mixins. * `is_weak_upper_modular_lattice`: Weakly upper modular lattices. Lattice where `a ⊔ b` covers `a` and `b` if `a` and `b` both cover `a ⊓ b`. * `is_weak_lower_modular_lattice`: Weakly lower modular lattices. Lattice where `a` and `b` cover `a ⊓ b` if `a ⊔ b` covers both `a` and `b` * `is_upper_modular_lattice`: Upper modular lattices. Lattices where `a ⊔ b` covers `a` if `b` covers `a ⊓ b`. * `is_lower_modular_lattice`: Lower modular lattices. Lattices where `a` covers `a ⊓ b` if `a ⊔ b` covers `b`. - `is_modular_lattice`: Modular lattices. Lattices where `a ≤ c → (a ⊔ b) ⊓ c = a ⊔ (b ⊓ c)`. We only require an inequality because the other direction holds in all lattices. ## Main Definitions - `inf_Icc_order_iso_Icc_sup` gives an order isomorphism between the intervals `[a ⊓ b, a]` and `[b, a ⊔ b]`. This corresponds to the diamond (or second) isomorphism theorems of algebra. ## Main Results - `is_modular_lattice_iff_inf_sup_inf_assoc`: Modularity is equivalent to the `inf_sup_inf_assoc`: `(x ⊓ z) ⊔ (y ⊓ z) = ((x ⊓ z) ⊔ y) ⊓ z` - `distrib_lattice.is_modular_lattice`: Distributive lattices are modular. ## References * [Manfred Stern, *Semimodular lattices. {Theory} and applications*][stern2009] * [Wikipedia, *Modular Lattice*][https://en.wikipedia.org/wiki/Modular_lattice] ## TODO - Relate atoms and coatoms in modular lattices - Prove that a modular lattice is both upper and lower modular. -/ variable {α : Type*} /-- A weakly upper modular lattice is a lattice where `a ⊔ b` covers `a` and `b` if `a` and `b` both cover `a ⊓ b`. -/ class is_weak_upper_modular_lattice (α : Type*) [lattice α] : Prop := (covby_sup_of_inf_covby_covby {a b : α} : a ⊓ b ⋖ a → a ⊓ b ⋖ b → a ⋖ a ⊔ b) /-- A weakly lower modular lattice is a lattice where `a` and `b` cover `a ⊓ b` if `a ⊔ b` covers both `a` and `b`. -/ class is_weak_lower_modular_lattice (α : Type*) [lattice α] : Prop := (inf_covby_of_covby_covby_sup {a b : α} : a ⋖ a ⊔ b → b ⋖ a ⊔ b → a ⊓ b ⋖ a) /-- An upper modular lattice, aka semimodular lattice, is a lattice where `a ⊔ b` covers `a` and `b` if either `a` or `b` covers `a ⊓ b`. -/ class is_upper_modular_lattice (α : Type*) [lattice α] : Prop := (covby_sup_of_inf_covby {a b : α} : a ⊓ b ⋖ a → b ⋖ a ⊔ b) /-- A lower modular lattice is a lattice where `a` and `b` both cover `a ⊓ b` if `a ⊔ b` covers either `a` or `b`. -/ class is_lower_modular_lattice (α : Type*) [lattice α] : Prop := (inf_covby_of_covby_sup {a b : α} : a ⋖ a ⊔ b → a ⊓ b ⋖ b) /-- A modular lattice is one with a limited associativity between `⊓` and `⊔`. -/ class is_modular_lattice (α : Type*) [lattice α] : Prop := (sup_inf_le_assoc_of_le : ∀ {x : α} (y : α) {z : α}, x ≤ z → (x ⊔ y) ⊓ z ≤ x ⊔ (y ⊓ z)) section weak_upper_modular variables [lattice α] [is_weak_upper_modular_lattice α] {a b : α} lemma covby_sup_of_inf_covby_of_inf_covby_left : a ⊓ b ⋖ a → a ⊓ b ⋖ b → a ⋖ a ⊔ b := is_weak_upper_modular_lattice.covby_sup_of_inf_covby_covby lemma covby_sup_of_inf_covby_of_inf_covby_right : a ⊓ b ⋖ a → a ⊓ b ⋖ b → b ⋖ a ⊔ b := by { rw [inf_comm, sup_comm], exact λ ha hb, covby_sup_of_inf_covby_of_inf_covby_left hb ha } alias covby_sup_of_inf_covby_of_inf_covby_left ← covby.sup_of_inf_of_inf_left alias covby_sup_of_inf_covby_of_inf_covby_right ← covby.sup_of_inf_of_inf_right instance : is_weak_lower_modular_lattice (order_dual α) := ⟨λ a b ha hb, (ha.of_dual.sup_of_inf_of_inf_left hb.of_dual).to_dual⟩ end weak_upper_modular section weak_lower_modular variables [lattice α] [is_weak_lower_modular_lattice α] {a b : α} lemma inf_covby_of_covby_sup_of_covby_sup_left : a ⋖ a ⊔ b → b ⋖ a ⊔ b → a ⊓ b ⋖ a := is_weak_lower_modular_lattice.inf_covby_of_covby_covby_sup lemma inf_covby_of_covby_sup_of_covby_sup_right : a ⋖ a ⊔ b → b ⋖ a ⊔ b → a ⊓ b ⋖ b := by { rw [sup_comm, inf_comm], exact λ ha hb, inf_covby_of_covby_sup_of_covby_sup_left hb ha } alias inf_covby_of_covby_sup_of_covby_sup_left ← covby.inf_of_sup_of_sup_left alias inf_covby_of_covby_sup_of_covby_sup_right ← covby.inf_of_sup_of_sup_right instance : is_weak_upper_modular_lattice (order_dual α) := ⟨λ a b ha hb, (ha.of_dual.inf_of_sup_of_sup_left hb.of_dual).to_dual⟩ end weak_lower_modular section upper_modular variables [lattice α] [is_upper_modular_lattice α] {a b : α} lemma covby_sup_of_inf_covby_left : a ⊓ b ⋖ a → b ⋖ a ⊔ b := is_upper_modular_lattice.covby_sup_of_inf_covby lemma covby_sup_of_inf_covby_right : a ⊓ b ⋖ b → a ⋖ a ⊔ b := by { rw [sup_comm, inf_comm], exact covby_sup_of_inf_covby_left } alias covby_sup_of_inf_covby_left ← covby.sup_of_inf_left alias covby_sup_of_inf_covby_right ← covby.sup_of_inf_right @[priority 100] -- See note [lower instance priority] instance is_upper_modular_lattice.to_is_weak_upper_modular_lattice : is_weak_upper_modular_lattice α := ⟨λ a b _, covby.sup_of_inf_right⟩ instance : is_lower_modular_lattice (order_dual α) := ⟨λ a b h, h.of_dual.sup_of_inf_left.to_dual⟩ end upper_modular section lower_modular variables [lattice α] [is_lower_modular_lattice α] {a b : α} lemma inf_covby_of_covby_sup_left : a ⋖ a ⊔ b → a ⊓ b ⋖ b := is_lower_modular_lattice.inf_covby_of_covby_sup lemma inf_covby_of_covby_sup_right : b ⋖ a ⊔ b → a ⊓ b ⋖ a := by { rw [inf_comm, sup_comm], exact inf_covby_of_covby_sup_left } alias inf_covby_of_covby_sup_left ← covby.inf_of_sup_left alias inf_covby_of_covby_sup_right ← covby.inf_of_sup_right @[priority 100] -- See note [lower instance priority] instance is_lower_modular_lattice.to_is_weak_lower_modular_lattice : is_weak_lower_modular_lattice α := ⟨λ a b _, covby.inf_of_sup_right⟩ instance : is_upper_modular_lattice (order_dual α) := ⟨λ a b h, h.of_dual.inf_of_sup_left.to_dual⟩ end lower_modular section is_modular_lattice variables [lattice α] [is_modular_lattice α] theorem sup_inf_assoc_of_le {x : α} (y : α) {z : α} (h : x ≤ z) : (x ⊔ y) ⊓ z = x ⊔ (y ⊓ z) := le_antisymm (is_modular_lattice.sup_inf_le_assoc_of_le y h) (le_inf (sup_le_sup_left inf_le_left _) (sup_le h inf_le_right)) theorem is_modular_lattice.inf_sup_inf_assoc {x y z : α} : (x ⊓ z) ⊔ (y ⊓ z) = ((x ⊓ z) ⊔ y) ⊓ z := (sup_inf_assoc_of_le y inf_le_right).symm lemma inf_sup_assoc_of_le {x : α} (y : α) {z : α} (h : z ≤ x) : (x ⊓ y) ⊔ z = x ⊓ (y ⊔ z) := by rw [inf_comm, sup_comm, ← sup_inf_assoc_of_le y h, inf_comm, sup_comm] instance : is_modular_lattice αᵒᵈ := ⟨λ x y z xz, le_of_eq (by { rw [inf_comm, sup_comm, eq_comm, inf_comm, sup_comm], exact @sup_inf_assoc_of_le α _ _ _ y _ xz })⟩ variables {x y z : α} theorem is_modular_lattice.sup_inf_sup_assoc : (x ⊔ z) ⊓ (y ⊔ z) = ((x ⊔ z) ⊓ y) ⊔ z := @is_modular_lattice.inf_sup_inf_assoc αᵒᵈ _ _ _ _ _ theorem eq_of_le_of_inf_le_of_sup_le (hxy : x ≤ y) (hinf : y ⊓ z ≤ x ⊓ z) (hsup : y ⊔ z ≤ x ⊔ z) : x = y := le_antisymm hxy $ have h : y ≤ x ⊔ z, from calc y ≤ y ⊔ z : le_sup_left ... ≤ x ⊔ z : hsup, calc y ≤ (x ⊔ z) ⊓ y : le_inf h le_rfl ... = x ⊔ (z ⊓ y) : sup_inf_assoc_of_le _ hxy ... ≤ x ⊔ (z ⊓ x) : sup_le_sup_left (by rw [inf_comm, @inf_comm _ _ z]; exact hinf) _ ... ≤ x : sup_le le_rfl inf_le_right theorem sup_lt_sup_of_lt_of_inf_le_inf (hxy : x < y) (hinf : y ⊓ z ≤ x ⊓ z) : x ⊔ z < y ⊔ z := lt_of_le_of_ne (sup_le_sup_right (le_of_lt hxy) _) (λ hsup, ne_of_lt hxy $ eq_of_le_of_inf_le_of_sup_le (le_of_lt hxy) hinf (le_of_eq hsup.symm)) theorem inf_lt_inf_of_lt_of_sup_le_sup (hxy : x < y) (hinf : y ⊔ z ≤ x ⊔ z) : x ⊓ z < y ⊓ z := @sup_lt_sup_of_lt_of_inf_le_inf αᵒᵈ _ _ _ _ _ hxy hinf /-- A generalization of the theorem that if `N` is a submodule of `M` and `N` and `M / N` are both Artinian, then `M` is Artinian. -/ theorem well_founded_lt_exact_sequence {β γ : Type*} [partial_order β] [preorder γ] (h₁ : well_founded ((<) : β → β → Prop)) (h₂ : well_founded ((<) : γ → γ → Prop)) (K : α) (f₁ : β → α) (f₂ : α → β) (g₁ : γ → α) (g₂ : α → γ) (gci : galois_coinsertion f₁ f₂) (gi : galois_insertion g₂ g₁) (hf : ∀ a, f₁ (f₂ a) = a ⊓ K) (hg : ∀ a, g₁ (g₂ a) = a ⊔ K) : well_founded ((<) : α → α → Prop) := subrelation.wf (λ A B hAB, show prod.lex (<) (<) (f₂ A, g₂ A) (f₂ B, g₂ B), begin simp only [prod.lex_def, lt_iff_le_not_le, ← gci.l_le_l_iff, ← gi.u_le_u_iff, hf, hg, le_antisymm_iff], simp only [gci.l_le_l_iff, gi.u_le_u_iff, ← lt_iff_le_not_le, ← le_antisymm_iff], cases lt_or_eq_of_le (inf_le_inf_right K (le_of_lt hAB)) with h h, { exact or.inl h }, { exact or.inr ⟨h, sup_lt_sup_of_lt_of_inf_le_inf hAB (le_of_eq h.symm)⟩ } end) (inv_image.wf _ (prod.lex_wf h₁ h₂)) /-- A generalization of the theorem that if `N` is a submodule of `M` and `N` and `M / N` are both Noetherian, then `M` is Noetherian. -/ theorem well_founded_gt_exact_sequence {β γ : Type*} [preorder β] [partial_order γ] (h₁ : well_founded ((>) : β → β → Prop)) (h₂ : well_founded ((>) : γ → γ → Prop)) (K : α) (f₁ : β → α) (f₂ : α → β) (g₁ : γ → α) (g₂ : α → γ) (gci : galois_coinsertion f₁ f₂) (gi : galois_insertion g₂ g₁) (hf : ∀ a, f₁ (f₂ a) = a ⊓ K) (hg : ∀ a, g₁ (g₂ a) = a ⊔ K) : well_founded ((>) : α → α → Prop) := @well_founded_lt_exact_sequence αᵒᵈ _ _ γᵒᵈ βᵒᵈ _ _ h₂ h₁ K g₁ g₂ f₁ f₂ gi.dual gci.dual hg hf /-- The diamond isomorphism between the intervals `[a ⊓ b, a]` and `[b, a ⊔ b]` -/ def inf_Icc_order_iso_Icc_sup (a b : α) : set.Icc (a ⊓ b) a ≃o set.Icc b (a ⊔ b) := { to_fun := λ x, ⟨x ⊔ b, ⟨le_sup_right, sup_le_sup_right x.prop.2 b⟩⟩, inv_fun := λ x, ⟨a ⊓ x, ⟨inf_le_inf_left a x.prop.1, inf_le_left⟩⟩, left_inv := λ x, subtype.ext (by { change a ⊓ (↑x ⊔ b) = ↑x, rw [sup_comm, ← inf_sup_assoc_of_le _ x.prop.2, sup_eq_right.2 x.prop.1] }), right_inv := λ x, subtype.ext (by { change a ⊓ ↑x ⊔ b = ↑x, rw [inf_comm, inf_sup_assoc_of_le _ x.prop.1, inf_eq_left.2 x.prop.2] }), map_rel_iff' := λ x y, begin simp only [subtype.mk_le_mk, equiv.coe_fn_mk, and_true, le_sup_right], rw [← subtype.coe_le_coe], refine ⟨λ h, _, λ h, sup_le_sup_right h _⟩, rw [← sup_eq_right.2 x.prop.1, inf_sup_assoc_of_le _ x.prop.2, sup_comm, ← sup_eq_right.2 y.prop.1, inf_sup_assoc_of_le _ y.prop.2, @sup_comm _ _ b], exact inf_le_inf_left _ h end } end is_modular_lattice namespace is_compl variables [lattice α] [bounded_order α] [is_modular_lattice α] /-- The diamond isomorphism between the intervals `set.Iic a` and `set.Ici b`. -/ def Iic_order_iso_Ici {a b : α} (h : is_compl a b) : set.Iic a ≃o set.Ici b := (order_iso.set_congr (set.Iic a) (set.Icc (a ⊓ b) a) (h.inf_eq_bot.symm ▸ set.Icc_bot.symm)).trans $ (inf_Icc_order_iso_Icc_sup a b).trans (order_iso.set_congr (set.Icc b (a ⊔ b)) (set.Ici b) (h.sup_eq_top.symm ▸ set.Icc_top)) end is_compl theorem is_modular_lattice_iff_inf_sup_inf_assoc [lattice α] : is_modular_lattice α ↔ ∀ (x y z : α), (x ⊓ z) ⊔ (y ⊓ z) = ((x ⊓ z) ⊔ y) ⊓ z := ⟨λ h, @is_modular_lattice.inf_sup_inf_assoc _ _ h, λ h, ⟨λ x y z xz, by rw [← inf_eq_left.2 xz, h]⟩⟩ namespace distrib_lattice @[priority 100] instance [distrib_lattice α] : is_modular_lattice α := ⟨λ x y z xz, by rw [inf_sup_right, inf_eq_left.2 xz]⟩ end distrib_lattice theorem disjoint.disjoint_sup_right_of_disjoint_sup_left [lattice α] [order_bot α] [is_modular_lattice α] {a b c : α} (h : disjoint a b) (hsup : disjoint (a ⊔ b) c) : disjoint a (b ⊔ c) := begin rw [disjoint, ← h.eq_bot, sup_comm], apply le_inf inf_le_left, apply (inf_le_inf_right (c ⊔ b) le_sup_right).trans, rw [sup_comm, is_modular_lattice.sup_inf_sup_assoc, hsup.eq_bot, bot_sup_eq] end theorem disjoint.disjoint_sup_left_of_disjoint_sup_right [lattice α] [order_bot α] [is_modular_lattice α] {a b c : α} (h : disjoint b c) (hsup : disjoint a (b ⊔ c)) : disjoint (a ⊔ b) c := begin rw [disjoint.comm, sup_comm], apply disjoint.disjoint_sup_right_of_disjoint_sup_left h.symm, rwa [sup_comm, disjoint.comm] at hsup, end namespace is_modular_lattice variables [lattice α] [is_modular_lattice α] {a : α} instance is_modular_lattice_Iic : is_modular_lattice (set.Iic a) := ⟨λ x y z xz, (sup_inf_le_assoc_of_le (y : α) xz : (↑x ⊔ ↑y) ⊓ ↑z ≤ ↑x ⊔ ↑y ⊓ ↑z)⟩ instance is_modular_lattice_Ici : is_modular_lattice (set.Ici a) := ⟨λ x y z xz, (sup_inf_le_assoc_of_le (y : α) xz : (↑x ⊔ ↑y) ⊓ ↑z ≤ ↑x ⊔ ↑y ⊓ ↑z)⟩ section complemented_lattice variables [bounded_order α] [complemented_lattice α] instance complemented_lattice_Iic : complemented_lattice (set.Iic a) := ⟨λ ⟨x, hx⟩, let ⟨y, hy⟩ := exists_is_compl x in ⟨⟨y ⊓ a, set.mem_Iic.2 inf_le_right⟩, begin split, { change x ⊓ (y ⊓ a) ≤ ⊥, -- improve lattice subtype API rw ← inf_assoc, exact le_trans inf_le_left hy.1 }, { change a ≤ x ⊔ (y ⊓ a), -- improve lattice subtype API rw [← sup_inf_assoc_of_le _ (set.mem_Iic.1 hx), top_le_iff.1 hy.2, top_inf_eq] } end⟩⟩ instance complemented_lattice_Ici : complemented_lattice (set.Ici a) := ⟨λ ⟨x, hx⟩, let ⟨y, hy⟩ := exists_is_compl x in ⟨⟨y ⊔ a, set.mem_Ici.2 le_sup_right⟩, begin split, { change x ⊓ (y ⊔ a) ≤ a, -- improve lattice subtype API rw [← inf_sup_assoc_of_le _ (set.mem_Ici.1 hx), le_bot_iff.1 hy.1, bot_sup_eq] }, { change ⊤ ≤ x ⊔ (y ⊔ a), -- improve lattice subtype API rw ← sup_assoc, exact le_trans hy.2 le_sup_left } end⟩⟩ end complemented_lattice end is_modular_lattice
c7c271c2560747790d0abb799f79d92ec41381cb
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/field_theory/ratfunc.lean
a7966a588eebc2b1b5c871a0065b39a58bb3f5cf
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
59,856
lean
/- Copyright (c) 2021 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import ring_theory.euclidean_domain import ring_theory.laurent_series import ring_theory.localization.fraction_ring import ring_theory.polynomial.content /-! # The field of rational functions This file defines the field `ratfunc K` of rational functions over a field `K`, and shows it is the field of fractions of `K[X]`. ## Main definitions Working with rational functions as polynomials: - `ratfunc.field` provides a field structure - `ratfunc.C` is the constant polynomial - `ratfunc.X` is the indeterminate - `ratfunc.eval` evaluates a rational function given a value for the indeterminate You can use `is_fraction_ring` API to treat `ratfunc` as the field of fractions of polynomials: * `algebra_map K[X] (ratfunc K)` maps polynomials to rational functions * `is_fraction_ring.alg_equiv` maps other fields of fractions of `K[X]` to `ratfunc K`, in particular: * `fraction_ring.alg_equiv K[X] (ratfunc K)` maps the generic field of fraction construction to `ratfunc K`. Combine this with `alg_equiv.restrict_scalars` to change the `fraction_ring K[X] ≃ₐ[K[X]] ratfunc K` to `fraction_ring K[X] ≃ₐ[K] ratfunc K`. Working with rational functions as fractions: - `ratfunc.num` and `ratfunc.denom` give the numerator and denominator. These values are chosen to be coprime and such that `ratfunc.denom` is monic. Embedding of rational functions into Laurent series, provided as a coercion, utilizing the underlying `ratfunc.coe_alg_hom`. Lifting homomorphisms of polynomials to other types, by mapping and dividing, as long as the homomorphism retains the non-zero-divisor property: - `ratfunc.lift_monoid_with_zero_hom` lifts a `K[X] →*₀ G₀` to a `ratfunc K →*₀ G₀`, where `[comm_ring K] [comm_group_with_zero G₀]` - `ratfunc.lift_ring_hom` lifts a `K[X] →+* L` to a `ratfunc K →+* L`, where `[comm_ring K] [field L]` - `ratfunc.lift_alg_hom` lifts a `K[X] →ₐ[S] L` to a `ratfunc K →ₐ[S] L`, where `[comm_ring K] [field L] [comm_semiring S] [algebra S K[X]] [algebra S L]` This is satisfied by injective homs. We also have lifting homomorphisms of polynomials to other polynomials, with the same condition on retaining the non-zero-divisor property across the map: - `ratfunc.map` lifts `K[X] →* R[X]` when `[comm_ring K] [comm_ring R]` - `ratfunc.map_ring_hom` lifts `K[X] →+* R[X]` when `[comm_ring K] [comm_ring R]` - `ratfunc.map_alg_hom` lifts `K[X] →ₐ[S] R[X]` when `[comm_ring K] [is_domain K] [comm_ring R] [is_domain R]` We also have a set of recursion and induction principles: - `ratfunc.lift_on`: define a function by mapping a fraction of polynomials `p/q` to `f p q`, if `f` is well-defined in the sense that `p/q = p'/q' → f p q = f p' q'`. - `ratfunc.lift_on'`: define a function by mapping a fraction of polynomials `p/q` to `f p q`, if `f` is well-defined in the sense that `f (a * p) (a * q) = f p' q'`. - `ratfunc.induction_on`: if `P` holds on `p / q` for all polynomials `p q`, then `P` holds on all rational functions We define the degree of a rational function, with values in `ℤ`: - `int_degree` is the degree of a rational function, defined as the difference between the `nat_degree` of its numerator and the `nat_degree` of its denominator. In particular, `int_degree 0 = 0`. ## Implementation notes To provide good API encapsulation and speed up unification problems, `ratfunc` is defined as a structure, and all operations are `@[irreducible] def`s We need a couple of maps to set up the `field` and `is_fraction_ring` structure, namely `ratfunc.of_fraction_ring`, `ratfunc.to_fraction_ring`, `ratfunc.mk` and `ratfunc.to_fraction_ring_ring_equiv`. All these maps get `simp`ed to bundled morphisms like `algebra_map K[X] (ratfunc K)` and `is_localization.alg_equiv`. There are separate lifts and maps of homomorphisms, to provide routes of lifting even when the codomain is not a field or even an integral domain. ## References * [Kleiman, *Misconceptions about $K_X$*][kleiman1979] * https://freedommathdance.blogspot.com/2012/11/misconceptions-about-kx.html * https://stacks.math.columbia.edu/tag/01X1 -/ noncomputable theory open_locale classical open_locale non_zero_divisors polynomial universes u v variables (K : Type u) [hring : comm_ring K] [hdomain : is_domain K] include hring /-- `ratfunc K` is `K(x)`, the field of rational functions over `K`. The inclusion of polynomials into `ratfunc` is `algebra_map K[X] (ratfunc K)`, the maps between `ratfunc K` and another field of fractions of `K[X]`, especially `fraction_ring K[X]`, are given by `is_localization.algebra_equiv`. -/ structure ratfunc : Type u := of_fraction_ring :: (to_fraction_ring : fraction_ring K[X]) namespace ratfunc variables {K} section rec /-! ### Constructing `ratfunc`s and their induction principles -/ lemma of_fraction_ring_injective : function.injective (of_fraction_ring : _ → ratfunc K) := λ x y, of_fraction_ring.inj lemma to_fraction_ring_injective : function.injective (to_fraction_ring : _ → fraction_ring K[X]) | ⟨x⟩ ⟨y⟩ rfl := rfl /-- Non-dependent recursion principle for `ratfunc K`: To construct a term of `P : Sort*` out of `x : ratfunc K`, it suffices to provide a constructor `f : Π (p q : K[X]), P` and a proof that `f p q = f p' q'` for all `p q p' q'` such that `p * q' = p' * q` where both `q` and `q'` are not zero divisors, stated as `q ∉ K[X]⁰`, `q' ∉ K[X]⁰`. If considering `K` as an integral domain, this is the same as saying that we construct a value of `P` for such elements of `ratfunc K` by setting `lift_on (p / q) f _ = f p q`. When `[is_domain K]`, one can use `ratfunc.lift_on'`, which has the stronger requirement of `∀ {p q a : K[X]} (hq : q ≠ 0) (ha : a ≠ 0), f (a * p) (a * q) = f p q)`. -/ @[irreducible] protected def lift_on {P : Sort v} (x : ratfunc K) (f : ∀ (p q : K[X]), P) (H : ∀ {p q p' q'} (hq : q ∈ K[X]⁰) (hq' : q' ∈ K[X]⁰), p * q' = p' * q → f p q = f p' q') : P := localization.lift_on (by exact to_fraction_ring x) -- Fix timeout by manipulating elaboration order (λ p q, f p q) (λ p p' q q' h, H q.2 q'.2 (let ⟨⟨c, hc⟩, mul_eq⟩ := (localization.r_iff_exists).mp h in mul_cancel_right_coe_non_zero_divisor.mp mul_eq)) lemma lift_on_of_fraction_ring_mk {P : Sort v} (n : K[X]) (d : K[X]⁰) (f : ∀ (p q : K[X]), P) (H : ∀ {p q p' q'} (hq : q ∈ K[X]⁰) (hq' : q' ∈ K[X]⁰), p * q' = p' * q → f p q = f p' q') : ratfunc.lift_on (by exact of_fraction_ring (localization.mk n d)) f @H = f n d := begin unfold ratfunc.lift_on, exact localization.lift_on_mk _ _ _ _ end include hdomain /-- `ratfunc.mk (p q : K[X])` is `p / q` as a rational function. If `q = 0`, then `mk` returns 0. This is an auxiliary definition used to define an `algebra` structure on `ratfunc`; the `simp` normal form of `mk p q` is `algebra_map _ _ p / algebra_map _ _ q`. -/ @[irreducible] protected def mk (p q : K[X]) : ratfunc K := of_fraction_ring (algebra_map _ _ p / algebra_map _ _ q) lemma mk_eq_div' (p q : K[X]) : ratfunc.mk p q = of_fraction_ring (algebra_map _ _ p / algebra_map _ _ q) := by unfold ratfunc.mk lemma mk_zero (p : K[X]) : ratfunc.mk p 0 = of_fraction_ring 0 := by rw [mk_eq_div', ring_hom.map_zero, div_zero] lemma mk_coe_def (p : K[X]) (q : K[X]⁰) : ratfunc.mk p q = of_fraction_ring (is_localization.mk' _ p q) := by simp only [mk_eq_div', ← localization.mk_eq_mk', fraction_ring.mk_eq_div] lemma mk_def_of_mem (p : K[X]) {q} (hq : q ∈ K[X]⁰) : ratfunc.mk p q = of_fraction_ring (is_localization.mk' _ p ⟨q, hq⟩) := by simp only [← mk_coe_def, set_like.coe_mk] lemma mk_def_of_ne (p : K[X]) {q : K[X]} (hq : q ≠ 0) : ratfunc.mk p q = of_fraction_ring (is_localization.mk' _ p ⟨q, mem_non_zero_divisors_iff_ne_zero.mpr hq⟩) := mk_def_of_mem p _ lemma mk_eq_localization_mk (p : K[X]) {q : K[X]} (hq : q ≠ 0) : ratfunc.mk p q = of_fraction_ring (localization.mk p ⟨q, mem_non_zero_divisors_iff_ne_zero.mpr hq⟩) := by rw [mk_def_of_ne, localization.mk_eq_mk'] lemma mk_one' (p : K[X]) : ratfunc.mk p 1 = of_fraction_ring (algebra_map _ _ p) := by rw [← is_localization.mk'_one (fraction_ring K[X]) p, ← mk_coe_def, submonoid.coe_one] lemma mk_eq_mk {p q p' q' : K[X]} (hq : q ≠ 0) (hq' : q' ≠ 0) : ratfunc.mk p q = ratfunc.mk p' q' ↔ p * q' = p' * q := by rw [mk_def_of_ne _ hq, mk_def_of_ne _ hq', of_fraction_ring_injective.eq_iff, is_localization.mk'_eq_iff_eq, set_like.coe_mk, set_like.coe_mk, (is_fraction_ring.injective K[X] (fraction_ring K[X])).eq_iff] lemma lift_on_mk {P : Sort v} (p q : K[X]) (f : ∀ (p q : K[X]), P) (f0 : ∀ p, f p 0 = f 0 1) (H' : ∀ {p q p' q'} (hq : q ≠ 0) (hq' : q' ≠ 0), p * q' = p' * q → f p q = f p' q') (H : ∀ {p q p' q'} (hq : q ∈ K[X]⁰) (hq' : q' ∈ K[X]⁰), p * q' = p' * q → f p q = f p' q' := λ p q p' q' hq hq' h, H' (non_zero_divisors.ne_zero hq) (non_zero_divisors.ne_zero hq') h) : (ratfunc.mk p q).lift_on f @H = f p q := begin by_cases hq : q = 0, { subst hq, simp only [mk_zero, f0, ← localization.mk_zero 1, localization.lift_on_mk, lift_on_of_fraction_ring_mk, submonoid.coe_one], }, { simp only [mk_eq_localization_mk _ hq, localization.lift_on_mk, lift_on_of_fraction_ring_mk, set_like.coe_mk] } end lemma lift_on_condition_of_lift_on'_condition {P : Sort v} {f : ∀ (p q : K[X]), P} (H : ∀ {p q a} (hq : q ≠ 0) (ha : a ≠ 0), f (a * p) (a * q) = f p q) ⦃p q p' q' : K[X]⦄ (hq : q ≠ 0) (hq' : q' ≠ 0) (h : p * q' = p' * q) : f p q = f p' q' := begin have H0 : f 0 q = f 0 q', { calc f 0 q = f (q' * 0) (q' * q) : (H hq hq').symm ... = f (q * 0) (q * q') : by rw [mul_zero, mul_zero, mul_comm] ... = f 0 q' : H hq' hq }, by_cases hp : p = 0, { simp only [hp, hq, zero_mul, or_false, zero_eq_mul] at ⊢ h, rw [h, H0] }, by_cases hp' : p' = 0, { simpa only [hp, hp', hq', zero_mul, or_self, mul_eq_zero] using h }, calc f p q = f (p' * p) (p' * q) : (H hq hp').symm ... = f (p * p') (p * q') : by rw [mul_comm p p', h] ... = f p' q' : H hq' hp end -- f /-- Non-dependent recursion principle for `ratfunc K`: if `f p q : P` for all `p q`, such that `f (a * p) (a * q) = f p q`, then we can find a value of `P` for all elements of `ratfunc K` by setting `lift_on' (p / q) f _ = f p q`. The value of `f p 0` for any `p` is never used and in principle this may be anything, although many usages of `lift_on'` assume `f p 0 = f 0 1`. -/ @[irreducible] protected def lift_on' {P : Sort v} (x : ratfunc K) (f : ∀ (p q : K[X]), P) (H : ∀ {p q a} (hq : q ≠ 0) (ha : a ≠ 0), f (a * p) (a * q) = f p q) : P := x.lift_on f (λ p q p' q' hq hq', lift_on_condition_of_lift_on'_condition @H (non_zero_divisors.ne_zero hq) (non_zero_divisors.ne_zero hq')) lemma lift_on'_mk {P : Sort v} (p q : K[X]) (f : ∀ (p q : K[X]), P) (f0 : ∀ p, f p 0 = f 0 1) (H : ∀ {p q a} (hq : q ≠ 0) (ha : a ≠ 0), f (a * p) (a * q) = f p q) : (ratfunc.mk p q).lift_on' f @H = f p q := begin rw [ratfunc.lift_on', ratfunc.lift_on_mk _ _ _ f0], exact lift_on_condition_of_lift_on'_condition @H end /-- Induction principle for `ratfunc K`: if `f p q : P (ratfunc.mk p q)` for all `p q`, then `P` holds on all elements of `ratfunc K`. See also `induction_on`, which is a recursion principle defined in terms of `algebra_map`. -/ @[irreducible] protected lemma induction_on' {P : ratfunc K → Prop} : Π (x : ratfunc K) (f : ∀ (p q : K[X]) (hq : q ≠ 0), P (ratfunc.mk p q)), P x | ⟨x⟩ f := localization.induction_on x (λ ⟨p, q⟩, by simpa only [mk_coe_def, localization.mk_eq_mk'] using f p q (mem_non_zero_divisors_iff_ne_zero.mp q.2)) end rec section field /-! ### Defining the field structure -/ /-- The zero rational function. -/ @[irreducible] protected def zero : ratfunc K := ⟨0⟩ instance : has_zero (ratfunc K) := ⟨ratfunc.zero⟩ lemma of_fraction_ring_zero : (of_fraction_ring 0 : ratfunc K) = 0 := by unfold has_zero.zero ratfunc.zero /-- Addition of rational functions. -/ @[irreducible] protected def add : ratfunc K → ratfunc K → ratfunc K | ⟨p⟩ ⟨q⟩ := ⟨p + q⟩ instance : has_add (ratfunc K) := ⟨ratfunc.add⟩ lemma of_fraction_ring_add (p q : fraction_ring K[X]) : of_fraction_ring (p + q) = of_fraction_ring p + of_fraction_ring q := by unfold has_add.add ratfunc.add /-- Subtraction of rational functions. -/ @[irreducible] protected def sub : ratfunc K → ratfunc K → ratfunc K | ⟨p⟩ ⟨q⟩ := ⟨p - q⟩ instance : has_sub (ratfunc K) := ⟨ratfunc.sub⟩ lemma of_fraction_ring_sub (p q : fraction_ring K[X]) : of_fraction_ring (p - q) = of_fraction_ring p - of_fraction_ring q := by unfold has_sub.sub ratfunc.sub /-- Additive inverse of a rational function. -/ @[irreducible] protected def neg : ratfunc K → ratfunc K | ⟨p⟩ := ⟨-p⟩ instance : has_neg (ratfunc K) := ⟨ratfunc.neg⟩ lemma of_fraction_ring_neg (p : fraction_ring K[X]) : of_fraction_ring (-p) = - of_fraction_ring p := by unfold has_neg.neg ratfunc.neg /-- The multiplicative unit of rational functions. -/ @[irreducible] protected def one : ratfunc K := ⟨1⟩ instance : has_one (ratfunc K) := ⟨ratfunc.one⟩ lemma of_fraction_ring_one : (of_fraction_ring 1 : ratfunc K) = 1 := by unfold has_one.one ratfunc.one /-- Multiplication of rational functions. -/ @[irreducible] protected def mul : ratfunc K → ratfunc K → ratfunc K | ⟨p⟩ ⟨q⟩ := ⟨p * q⟩ instance : has_mul (ratfunc K) := ⟨ratfunc.mul⟩ lemma of_fraction_ring_mul (p q : fraction_ring K[X]) : of_fraction_ring (p * q) = of_fraction_ring p * of_fraction_ring q := by unfold has_mul.mul ratfunc.mul include hdomain /-- Division of rational functions. -/ @[irreducible] protected def div : ratfunc K → ratfunc K → ratfunc K | ⟨p⟩ ⟨q⟩ := ⟨p / q⟩ instance : has_div (ratfunc K) := ⟨ratfunc.div⟩ lemma of_fraction_ring_div (p q : fraction_ring K[X]) : of_fraction_ring (p / q) = of_fraction_ring p / of_fraction_ring q := by unfold has_div.div ratfunc.div /-- Multiplicative inverse of a rational function. -/ @[irreducible] protected def inv : ratfunc K → ratfunc K | ⟨p⟩ := ⟨p⁻¹⟩ instance : has_inv (ratfunc K) := ⟨ratfunc.inv⟩ lemma of_fraction_ring_inv (p : fraction_ring K[X]) : of_fraction_ring (p⁻¹) = (of_fraction_ring p)⁻¹ := by unfold has_inv.inv ratfunc.inv -- Auxiliary lemma for the `field` instance lemma mul_inv_cancel : ∀ {p : ratfunc K} (hp : p ≠ 0), p * p⁻¹ = 1 | ⟨p⟩ h := have p ≠ 0 := λ hp, h $ by rw [hp, of_fraction_ring_zero], by simpa only [← of_fraction_ring_inv, ← of_fraction_ring_mul, ← of_fraction_ring_one] using _root_.mul_inv_cancel this section has_smul omit hdomain variables {R : Type*} /-- Scalar multiplication of rational functions. -/ @[irreducible] protected def smul [has_smul R (fraction_ring K[X])] : R → ratfunc K → ratfunc K | r ⟨p⟩ := ⟨r • p⟩ @[nolint fails_quickly] -- cannot reproduce instance [has_smul R (fraction_ring K[X])] : has_smul R (ratfunc K) := ⟨ratfunc.smul⟩ lemma of_fraction_ring_smul [has_smul R (fraction_ring K[X])] (c : R) (p : fraction_ring K[X]) : of_fraction_ring (c • p) = c • of_fraction_ring p := by unfold has_smul.smul ratfunc.smul lemma to_fraction_ring_smul [has_smul R (fraction_ring K[X])] (c : R) (p : ratfunc K) : to_fraction_ring (c • p) = c • to_fraction_ring p := by { cases p, rw ←of_fraction_ring_smul } lemma smul_eq_C_smul (x : ratfunc K) (r : K) : r • x = polynomial.C r • x := begin cases x, induction x, { rw [←of_fraction_ring_smul, ←of_fraction_ring_smul, localization.smul_mk, localization.smul_mk, smul_eq_mul, polynomial.smul_eq_C_mul] }, { simp only } end include hdomain variables [monoid R] [distrib_mul_action R K[X]] variables [htower : is_scalar_tower R K[X] K[X]] include htower lemma mk_smul (c : R) (p q : K[X]) : ratfunc.mk (c • p) q = c • ratfunc.mk p q := begin by_cases hq : q = 0, { rw [hq, mk_zero, mk_zero, ←of_fraction_ring_smul, smul_zero] }, { rw [mk_eq_localization_mk _ hq, mk_eq_localization_mk _ hq, ←localization.smul_mk, ←of_fraction_ring_smul] } end instance : is_scalar_tower R K[X] (ratfunc K) := ⟨λ c p q, q.induction_on' (λ q r _, by rw [← mk_smul, smul_assoc, mk_smul, mk_smul])⟩ end has_smul variables (K) omit hdomain instance [subsingleton K] : subsingleton (ratfunc K) := to_fraction_ring_injective.subsingleton instance : inhabited (ratfunc K) := ⟨0⟩ instance [nontrivial K] : nontrivial (ratfunc K) := of_fraction_ring_injective.nontrivial /-- `ratfunc K` is isomorphic to the field of fractions of `K[X]`, as rings. This is an auxiliary definition; `simp`-normal form is `is_localization.alg_equiv`. -/ @[simps apply] def to_fraction_ring_ring_equiv : ratfunc K ≃+* fraction_ring K[X] := { to_fun := to_fraction_ring, inv_fun := of_fraction_ring, left_inv := λ ⟨_⟩, rfl, right_inv := λ _, rfl, map_add' := λ ⟨_⟩ ⟨_⟩, by simp [←of_fraction_ring_add], map_mul' := λ ⟨_⟩ ⟨_⟩, by simp [←of_fraction_ring_mul] } omit hring /-- Solve equations for `ratfunc K` by working in `fraction_ring K[X]`. -/ meta def frac_tac : tactic unit := `[repeat { rintro (⟨⟩ : ratfunc _) }, simp only [← of_fraction_ring_zero, ← of_fraction_ring_add, ← of_fraction_ring_sub, ← of_fraction_ring_neg, ← of_fraction_ring_one, ← of_fraction_ring_mul, ← of_fraction_ring_div, ← of_fraction_ring_inv, add_assoc, zero_add, add_zero, mul_assoc, mul_zero, mul_one, mul_add, inv_zero, add_comm, add_left_comm, mul_comm, mul_left_comm, sub_eq_add_neg, div_eq_mul_inv, add_mul, zero_mul, one_mul, neg_mul, mul_neg, add_right_neg]] /-- Solve equations for `ratfunc K` by applying `ratfunc.induction_on`. -/ meta def smul_tac : tactic unit := `[repeat { rintro (⟨⟩ : ratfunc _) <|> intro }, simp_rw [←of_fraction_ring_smul], simp only [add_comm, mul_comm, zero_smul, succ_nsmul, zsmul_eq_mul, mul_add, mul_one, mul_zero, neg_add, mul_neg, int.of_nat_eq_coe, int.coe_nat_succ, int.cast_zero, int.cast_add, int.cast_one, int.cast_neg_succ_of_nat, int.cast_coe_nat, nat.cast_succ, localization.mk_zero, localization.add_mk_self, localization.neg_mk, of_fraction_ring_zero, ← of_fraction_ring_add, ← of_fraction_ring_neg]] include hring instance : comm_ring (ratfunc K) := { add := (+), add_assoc := by frac_tac, add_comm := by frac_tac, zero := 0, zero_add := by frac_tac, add_zero := by frac_tac, neg := has_neg.neg, add_left_neg := by frac_tac, sub := has_sub.sub, sub_eq_add_neg := by frac_tac, mul := (*), mul_assoc := by frac_tac, mul_comm := by frac_tac, left_distrib := by frac_tac, right_distrib := by frac_tac, one := 1, one_mul := by frac_tac, mul_one := by frac_tac, nsmul := (•), nsmul_zero' := by smul_tac, nsmul_succ' := λ _, by smul_tac, zsmul := (•), zsmul_zero' := by smul_tac, zsmul_succ' := λ _, by smul_tac, zsmul_neg' := λ _, by smul_tac, npow := npow_rec } variables {K} section lift_hom variables {G₀ L R S F : Type*} [comm_group_with_zero G₀] [field L] [comm_ring R] [comm_ring S] omit hring /-- Lift a monoid homomorphism that maps polynomials `φ : R[X] →* S[X]` to a `ratfunc R →* ratfunc S`, on the condition that `φ` maps non zero divisors to non zero divisors, by mapping both the numerator and denominator and quotienting them. -/ def map [monoid_hom_class F R[X] S[X]] (φ : F) (hφ : R[X]⁰ ≤ S[X]⁰.comap φ) : ratfunc R →* ratfunc S := { to_fun := λ f, ratfunc.lift_on f (λ n d, if h : φ d ∈ S[X]⁰ then of_fraction_ring (localization.mk (φ n) ⟨φ d, h⟩) else 0) $ λ p q p' q' hq hq' h, begin rw [dif_pos, dif_pos, of_fraction_ring.inj_eq, localization.mk_eq_mk_iff], rotate, { exact hφ hq' }, { exact hφ hq }, refine localization.r_of_eq _, simpa only [map_mul] using (congr_arg φ h).symm, end, map_one' := begin rw [←of_fraction_ring_one, ←localization.mk_one, lift_on_of_fraction_ring_mk, dif_pos], { simpa using of_fraction_ring_one }, { simpa using submonoid.one_mem _} end, map_mul' := λ x y, begin cases x, cases y, induction x with p q, induction y with p' q', { have hq : φ q ∈ S[X]⁰ := hφ q.prop, have hq' : φ q' ∈ S[X]⁰ := hφ q'.prop, have hqq' : φ ↑(q * q') ∈ S[X]⁰, { simpa using submonoid.mul_mem _ hq hq' }, simp_rw [←of_fraction_ring_mul, localization.mk_mul, lift_on_of_fraction_ring_mk, dif_pos hq, dif_pos hq', dif_pos hqq', ←of_fraction_ring_mul, submonoid.coe_mul, map_mul, localization.mk_mul, submonoid.mk_mul_mk] }, { refl }, { refl } end } lemma map_apply_of_fraction_ring_mk [monoid_hom_class F R[X] S[X]] (φ : F) (hφ : R[X]⁰ ≤ S[X]⁰.comap φ) (n : R[X]) (d : R[X]⁰) : map φ hφ (of_fraction_ring (localization.mk n d)) = of_fraction_ring (localization.mk (φ n) ⟨φ d, hφ d.prop⟩) := begin convert lift_on_of_fraction_ring_mk _ _ _ _, rw dif_pos end lemma map_injective [monoid_hom_class F R[X] S[X]] (φ : F) (hφ : R[X]⁰ ≤ S[X]⁰.comap φ) (hf : function.injective φ) : function.injective (map φ hφ) := begin rintro ⟨x⟩ ⟨y⟩ h, induction x, induction y, { simpa only [map_apply_of_fraction_ring_mk, of_fraction_ring_injective.eq_iff, localization.mk_eq_mk_iff, localization.r_iff_exists, mul_cancel_right_coe_non_zero_divisor, exists_const, set_like.coe_mk, ←map_mul, hf.eq_iff] using h }, { refl }, { refl } end /-- Lift a ring homomorphism that maps polynomials `φ : R[X] →+* S[X]` to a `ratfunc R →+* ratfunc S`, on the condition that `φ` maps non zero divisors to non zero divisors, by mapping both the numerator and denominator and quotienting them. -/ def map_ring_hom [ring_hom_class F R[X] S[X]] (φ : F) (hφ : R[X]⁰ ≤ S[X]⁰.comap φ) : ratfunc R →+* ratfunc S := { map_zero' := begin simp_rw [monoid_hom.to_fun_eq_coe, ←of_fraction_ring_zero, ←localization.mk_zero (1 : R[X]⁰), ←localization.mk_zero (1 : S[X]⁰), map_apply_of_fraction_ring_mk, map_zero, localization.mk_eq_mk', is_localization.mk'_zero], end, map_add' := begin rintro ⟨x⟩ ⟨y⟩, induction x, induction y, { simp only [←of_fraction_ring_add, localization.add_mk, map_add, set_like.coe_mk, map_mul, monoid_hom.to_fun_eq_coe, map_apply_of_fraction_ring_mk, submonoid.mk_mul_mk, submonoid.coe_mul] }, { refl }, { refl } end, ..map φ hφ } lemma coe_map_ring_hom_eq_coe_map [ring_hom_class F R[X] S[X]] (φ : F) (hφ : R[X]⁰ ≤ S[X]⁰.comap φ) : (map_ring_hom φ hφ : ratfunc R → ratfunc S) = map φ hφ := rfl -- TODO: Generalize to `fun_like` classes, /-- Lift an monoid with zero homomorphism `R[X] →*₀ G₀` to a `ratfunc R →*₀ G₀` on the condition that `φ` maps non zero divisors to non zero divisors, by mapping both the numerator and denominator and quotienting them. -/ def lift_monoid_with_zero_hom (φ : R[X] →*₀ G₀) (hφ : R[X]⁰ ≤ G₀⁰.comap φ) : ratfunc R →*₀ G₀ := { to_fun := λ f, ratfunc.lift_on f (λ p q, φ p / (φ q)) $ λ p q p' q' hq hq' h, begin casesI subsingleton_or_nontrivial R, { rw [subsingleton.elim p q, subsingleton.elim p' q, subsingleton.elim q' q] }, rw [div_eq_div_iff, ←map_mul, h, map_mul]; exact non_zero_divisors.ne_zero (hφ ‹_›), end, map_one' := by { rw [←of_fraction_ring_one, ←localization.mk_one, lift_on_of_fraction_ring_mk], simp only [map_one, submonoid.coe_one, div_one] }, map_mul' := λ x y, by { cases x, cases y, induction x with p q, induction y with p' q', { rw [←of_fraction_ring_mul, localization.mk_mul], simp only [lift_on_of_fraction_ring_mk, div_mul_div_comm, map_mul, submonoid.coe_mul] }, { refl }, { refl } }, map_zero' := by { rw [←of_fraction_ring_zero, ←localization.mk_zero (1 : R[X]⁰), lift_on_of_fraction_ring_mk], simp only [map_zero, zero_div] } } lemma lift_monoid_with_zero_hom_apply_of_fraction_ring_mk (φ : R[X] →*₀ G₀) (hφ : R[X]⁰ ≤ G₀⁰.comap φ) (n : R[X]) (d : R[X]⁰) : lift_monoid_with_zero_hom φ hφ (of_fraction_ring (localization.mk n d)) = φ n / φ d := lift_on_of_fraction_ring_mk _ _ _ _ lemma lift_monoid_with_zero_hom_injective [nontrivial R] (φ : R[X] →*₀ G₀) (hφ : function.injective φ) (hφ' : R[X]⁰ ≤ G₀⁰.comap φ := non_zero_divisors_le_comap_non_zero_divisors_of_injective _ hφ) : function.injective (lift_monoid_with_zero_hom φ hφ') := begin rintro ⟨x⟩ ⟨y⟩, induction x, induction y, { simp_rw [lift_monoid_with_zero_hom_apply_of_fraction_ring_mk, localization.mk_eq_mk_iff], intro h, refine localization.r_of_eq _, simpa only [←hφ.eq_iff, map_mul] using mul_eq_mul_of_div_eq_div _ _ _ _ h.symm; exact (map_ne_zero_of_mem_non_zero_divisors _ hφ (set_like.coe_mem _)) }, { exact λ _, rfl }, { exact λ _, rfl } end /-- Lift an injective ring homomorphism `R[X] →+* L` to a `ratfunc R →+* L` by mapping both the numerator and denominator and quotienting them. -/ def lift_ring_hom (φ : R[X] →+* L) (hφ : R[X]⁰ ≤ L⁰.comap φ) : ratfunc R →+* L := { map_add' := λ x y, by { simp only [monoid_with_zero_hom.to_fun_eq_coe], casesI subsingleton_or_nontrivial R, { rw [subsingleton.elim (x + y) y, subsingleton.elim x 0, map_zero, zero_add] }, cases x, cases y, induction x with p q, induction y with p' q', { rw [←of_fraction_ring_add, localization.add_mk], simp only [ring_hom.to_monoid_with_zero_hom_eq_coe, lift_monoid_with_zero_hom_apply_of_fraction_ring_mk], rw [div_add_div, div_eq_div_iff], { rw [mul_comm _ p, mul_comm _ p', mul_comm _ (φ p'), add_comm], simp only [map_add, map_mul, submonoid.coe_mul] }, all_goals { try { simp only [←map_mul, ←submonoid.coe_mul] }, exact non_zero_divisors.ne_zero (hφ (set_like.coe_mem _)) } }, { refl }, { refl } }, ..lift_monoid_with_zero_hom φ.to_monoid_with_zero_hom hφ } lemma lift_ring_hom_apply_of_fraction_ring_mk (φ : R[X] →+* L) (hφ : R[X]⁰ ≤ L⁰.comap φ) (n : R[X]) (d : R[X]⁰) : lift_ring_hom φ hφ (of_fraction_ring (localization.mk n d)) = φ n / φ d := lift_monoid_with_zero_hom_apply_of_fraction_ring_mk _ _ _ _ lemma lift_ring_hom_injective [nontrivial R] (φ : R[X] →+* L) (hφ : function.injective φ) (hφ' : R[X]⁰ ≤ L⁰.comap φ := non_zero_divisors_le_comap_non_zero_divisors_of_injective _ hφ) : function.injective (lift_ring_hom φ hφ') := lift_monoid_with_zero_hom_injective _ hφ end lift_hom variables (K) include hdomain instance : field (ratfunc K) := { inv := has_inv.inv, inv_zero := by frac_tac, div := (/), div_eq_mul_inv := by frac_tac, mul_inv_cancel := λ _, mul_inv_cancel, zpow := zpow_rec, .. ratfunc.comm_ring K, .. ratfunc.nontrivial K } end field section is_fraction_ring /-! ### `ratfunc` as field of fractions of `polynomial` -/ include hdomain instance (R : Type*) [comm_semiring R] [algebra R K[X]] : algebra R (ratfunc K) := { to_fun := λ x, ratfunc.mk (algebra_map _ _ x) 1, map_add' := λ x y, by simp only [mk_one', ring_hom.map_add, of_fraction_ring_add], map_mul' := λ x y, by simp only [mk_one', ring_hom.map_mul, of_fraction_ring_mul], map_one' := by simp only [mk_one', ring_hom.map_one, of_fraction_ring_one], map_zero' := by simp only [mk_one', ring_hom.map_zero, of_fraction_ring_zero], smul := (•), smul_def' := λ c x, x.induction_on' $ λ p q hq, by simp_rw [mk_one', ← mk_smul, mk_def_of_ne (c • p) hq, mk_def_of_ne p hq, ← of_fraction_ring_mul, is_localization.mul_mk'_eq_mk'_of_mul, algebra.smul_def], commutes' := λ c x, mul_comm _ _ } variables {K} lemma mk_one (x : K[X]) : ratfunc.mk x 1 = algebra_map _ _ x := rfl lemma of_fraction_ring_algebra_map (x : K[X]) : of_fraction_ring (algebra_map _ (fraction_ring K[X]) x) = algebra_map _ _ x := by rw [← mk_one, mk_one'] @[simp] lemma mk_eq_div (p q : K[X]) : ratfunc.mk p q = (algebra_map _ _ p / algebra_map _ _ q) := by simp only [mk_eq_div', of_fraction_ring_div, of_fraction_ring_algebra_map] @[simp] lemma div_smul {R} [monoid R] [distrib_mul_action R K[X]] [is_scalar_tower R K[X] K[X]] (c : R) (p q : K[X]) : algebra_map _ (ratfunc K) (c • p) / (algebra_map _ _ q) = c • (algebra_map _ _ p / algebra_map _ _ q) := by rw [←mk_eq_div, mk_smul, mk_eq_div] lemma algebra_map_apply {R : Type*} [comm_semiring R] [algebra R K[X]] (x : R) : algebra_map R (ratfunc K) x = (algebra_map _ _ (algebra_map R K[X] x)) / (algebra_map K[X] _ 1) := by { rw [←mk_eq_div], refl } lemma map_apply_div_ne_zero {R F : Type*} [comm_ring R] [is_domain R] [monoid_hom_class F K[X] R[X]] (φ : F) (hφ : K[X]⁰ ≤ R[X]⁰.comap φ) (p q : K[X]) (hq : q ≠ 0) : map φ hφ (algebra_map _ _ p / algebra_map _ _ q) = algebra_map _ _ (φ p) / algebra_map _ _ (φ q) := begin have hq' : φ q ≠ 0 := non_zero_divisors.ne_zero (hφ (mem_non_zero_divisors_iff_ne_zero.mpr hq)), simp only [←mk_eq_div, mk_eq_localization_mk _ hq, map_apply_of_fraction_ring_mk, mk_eq_localization_mk _ hq', set_like.coe_mk], end @[simp] lemma map_apply_div {R F : Type*} [comm_ring R] [is_domain R] [monoid_with_zero_hom_class F K[X] R[X]] (φ : F) (hφ : K[X]⁰ ≤ R[X]⁰.comap φ) (p q : K[X]) : map φ hφ (algebra_map _ _ p / algebra_map _ _ q) = algebra_map _ _ (φ p) / algebra_map _ _ (φ q) := begin rcases eq_or_ne q 0 with rfl|hq, { have : (0 : ratfunc K) = algebra_map K[X] _ 0 / algebra_map K[X] _ 1, { simp }, rw [map_zero, map_zero, map_zero, div_zero, div_zero, this, map_apply_div_ne_zero, map_one, map_one, div_one, map_zero, map_zero], exact one_ne_zero }, exact map_apply_div_ne_zero _ _ _ _ hq end @[simp] lemma lift_monoid_with_zero_hom_apply_div {L : Type*} [comm_group_with_zero L] (φ : monoid_with_zero_hom K[X] L) (hφ : K[X]⁰ ≤ L⁰.comap φ) (p q : K[X]) : lift_monoid_with_zero_hom φ hφ (algebra_map _ _ p / algebra_map _ _ q) = φ p / φ q := begin rcases eq_or_ne q 0 with rfl|hq, { simp only [div_zero, map_zero] }, simpa only [←mk_eq_div, mk_eq_localization_mk _ hq, lift_monoid_with_zero_hom_apply_of_fraction_ring_mk], end @[simp] lemma lift_ring_hom_apply_div {L : Type*} [field L] (φ : K[X] →+* L) (hφ : K[X]⁰ ≤ L⁰.comap φ) (p q : K[X]) : lift_ring_hom φ hφ (algebra_map _ _ p / algebra_map _ _ q) = φ p / φ q := lift_monoid_with_zero_hom_apply_div _ _ _ _ variables (K) lemma of_fraction_ring_comp_algebra_map : of_fraction_ring ∘ algebra_map K[X] (fraction_ring K[X]) = algebra_map _ _ := funext of_fraction_ring_algebra_map lemma algebra_map_injective : function.injective (algebra_map K[X] (ratfunc K)) := begin rw ← of_fraction_ring_comp_algebra_map, exact of_fraction_ring_injective.comp (is_fraction_ring.injective _ _), end @[simp] lemma algebra_map_eq_zero_iff {x : K[X]} : algebra_map K[X] (ratfunc K) x = 0 ↔ x = 0 := ⟨(injective_iff_map_eq_zero _).mp (algebra_map_injective K) _, λ hx, by rw [hx, ring_hom.map_zero]⟩ variables {K} lemma algebra_map_ne_zero {x : K[X]} (hx : x ≠ 0) : algebra_map K[X] (ratfunc K) x ≠ 0 := mt (algebra_map_eq_zero_iff K).mp hx section lift_alg_hom variables {L R S : Type*} [field L] [comm_ring R] [is_domain R] [comm_semiring S] [algebra S K[X]] [algebra S L] [algebra S R[X]] (φ : K[X] →ₐ[S] L) (hφ : K[X]⁰ ≤ L⁰.comap φ) /-- Lift an algebra homomorphism that maps polynomials `φ : K[X] →ₐ[S] R[X]` to a `ratfunc K →ₐ[S] ratfunc R`, on the condition that `φ` maps non zero divisors to non zero divisors, by mapping both the numerator and denominator and quotienting them. -/ def map_alg_hom (φ : K[X] →ₐ[S] R[X]) (hφ : K[X]⁰ ≤ R[X]⁰.comap φ) : ratfunc K →ₐ[S] ratfunc R := { commutes' := λ r, by simp_rw [ring_hom.to_fun_eq_coe, coe_map_ring_hom_eq_coe_map, algebra_map_apply r, map_apply_div, map_one, alg_hom.commutes], ..map_ring_hom φ hφ } lemma coe_map_alg_hom_eq_coe_map (φ : K[X] →ₐ[S] R[X]) (hφ : K[X]⁰ ≤ R[X]⁰.comap φ) : (map_alg_hom φ hφ : ratfunc K → ratfunc R) = map φ hφ := rfl /-- Lift an injective algebra homomorphism `K[X] →ₐ[S] L` to a `ratfunc K →ₐ[S] L` by mapping both the numerator and denominator and quotienting them. -/ def lift_alg_hom : ratfunc K →ₐ[S] L := { commutes' := λ r, by simp_rw [ring_hom.to_fun_eq_coe, alg_hom.to_ring_hom_eq_coe, algebra_map_apply r, lift_ring_hom_apply_div, alg_hom.coe_to_ring_hom, map_one, div_one, alg_hom.commutes], ..lift_ring_hom φ.to_ring_hom hφ } lemma lift_alg_hom_apply_of_fraction_ring_mk (n : K[X]) (d : K[X]⁰) : lift_alg_hom φ hφ (of_fraction_ring (localization.mk n d)) = φ n / φ d := lift_monoid_with_zero_hom_apply_of_fraction_ring_mk _ _ _ _ lemma lift_alg_hom_injective (φ : K[X] →ₐ[S] L) (hφ : function.injective φ) (hφ' : K[X]⁰ ≤ L⁰.comap φ := non_zero_divisors_le_comap_non_zero_divisors_of_injective _ hφ) : function.injective (lift_alg_hom φ hφ') := lift_monoid_with_zero_hom_injective _ hφ @[simp] lemma lift_alg_hom_apply_div (p q : K[X]) : lift_alg_hom φ hφ (algebra_map _ _ p / algebra_map _ _ q) = φ p / φ q := lift_monoid_with_zero_hom_apply_div _ _ _ _ end lift_alg_hom variables (K) omit hdomain include hdomain /-- `ratfunc K` is the field of fractions of the polynomials over `K`. -/ instance : is_fraction_ring K[X] (ratfunc K) := { map_units := λ y, by rw ← of_fraction_ring_algebra_map; exact (to_fraction_ring_ring_equiv K).symm.to_ring_hom.is_unit_map (is_localization.map_units _ y), eq_iff_exists := λ x y, by rw [← of_fraction_ring_algebra_map, ← of_fraction_ring_algebra_map]; exact (to_fraction_ring_ring_equiv K).symm.injective.eq_iff.trans (is_localization.eq_iff_exists _ _), surj := by { rintro ⟨z⟩, convert is_localization.surj K[X]⁰ z, ext ⟨x, y⟩, simp only [← of_fraction_ring_algebra_map, function.comp_app, ← of_fraction_ring_mul] } } variables {K} @[simp] lemma lift_on_div {P : Sort v} (p q : K[X]) (f : ∀ (p q : K[X]), P) (f0 : ∀ p, f p 0 = f 0 1) (H' : ∀ {p q p' q'} (hq : q ≠ 0) (hq' : q' ≠ 0), p * q' = p' * q → f p q = f p' q') (H : ∀ {p q p' q'} (hq : q ∈ K[X]⁰) (hq' : q' ∈ K[X]⁰), p * q' = p' * q → f p q = f p' q' := λ p q p' q' hq hq' h, H' (non_zero_divisors.ne_zero hq) (non_zero_divisors.ne_zero hq') h) : (algebra_map _ (ratfunc K) p / algebra_map _ _ q).lift_on f @H = f p q := by rw [← mk_eq_div, lift_on_mk _ _ f f0 @H'] @[simp] lemma lift_on'_div {P : Sort v} (p q : K[X]) (f : ∀ (p q : K[X]), P) (f0 : ∀ p, f p 0 = f 0 1) (H) : (algebra_map _ (ratfunc K) p / algebra_map _ _ q).lift_on' f @H = f p q := begin rw [ratfunc.lift_on', lift_on_div _ _ _ f0], exact lift_on_condition_of_lift_on'_condition @H end /-- Induction principle for `ratfunc K`: if `f p q : P (p / q)` for all `p q : K[X]`, then `P` holds on all elements of `ratfunc K`. See also `induction_on'`, which is a recursion principle defined in terms of `ratfunc.mk`. -/ protected lemma induction_on {P : ratfunc K → Prop} (x : ratfunc K) (f : ∀ (p q : K[X]) (hq : q ≠ 0), P (algebra_map _ (ratfunc K) p / algebra_map _ _ q)) : P x := x.induction_on' (λ p q hq, by simpa using f p q hq) lemma of_fraction_ring_mk' (x : K[X]) (y : K[X]⁰) : of_fraction_ring (is_localization.mk' _ x y) = is_localization.mk' (ratfunc K) x y := by rw [is_fraction_ring.mk'_eq_div, is_fraction_ring.mk'_eq_div, ← mk_eq_div', ← mk_eq_div] @[simp] lemma of_fraction_ring_eq : (of_fraction_ring : fraction_ring K[X] → ratfunc K) = is_localization.alg_equiv K[X]⁰ _ _ := funext $ λ x, localization.induction_on x $ λ x, by simp only [is_localization.alg_equiv_apply, is_localization.ring_equiv_of_ring_equiv_apply, ring_equiv.to_fun_eq_coe, localization.mk_eq_mk'_apply, is_localization.map_mk', of_fraction_ring_mk', ring_equiv.coe_to_ring_hom, ring_equiv.refl_apply, set_like.eta] @[simp] lemma to_fraction_ring_eq : (to_fraction_ring : ratfunc K → fraction_ring K[X]) = is_localization.alg_equiv K[X]⁰ _ _ := funext $ λ ⟨x⟩, localization.induction_on x $ λ x, by simp only [localization.mk_eq_mk'_apply, of_fraction_ring_mk', is_localization.alg_equiv_apply, ring_equiv.to_fun_eq_coe, is_localization.ring_equiv_of_ring_equiv_apply, is_localization.map_mk', ring_equiv.coe_to_ring_hom, ring_equiv.refl_apply, set_like.eta] @[simp] lemma to_fraction_ring_ring_equiv_symm_eq : (to_fraction_ring_ring_equiv K).symm = (is_localization.alg_equiv K[X]⁰ _ _).to_ring_equiv := by { ext x, simp [to_fraction_ring_ring_equiv, of_fraction_ring_eq, alg_equiv.coe_ring_equiv'] } end is_fraction_ring section num_denom /-! ### Numerator and denominator -/ open gcd_monoid polynomial omit hring variables [hfield : field K] include hfield /-- `ratfunc.num_denom` are numerator and denominator of a rational function over a field, normalized such that the denominator is monic. -/ def num_denom (x : ratfunc K) : K[X] × K[X] := x.lift_on' (λ p q, if q = 0 then ⟨0, 1⟩ else let r := gcd p q in ⟨polynomial.C ((q / r).leading_coeff⁻¹) * (p / r), polynomial.C ((q / r).leading_coeff⁻¹) * (q / r)⟩) begin intros p q a hq ha, rw [if_neg hq, if_neg (mul_ne_zero ha hq)], have hpq : gcd p q ≠ 0 := mt (and.right ∘ (gcd_eq_zero_iff _ _).mp) hq, have ha' : a.leading_coeff ≠ 0 := polynomial.leading_coeff_ne_zero.mpr ha, have hainv : (a.leading_coeff)⁻¹ ≠ 0 := inv_ne_zero ha', simp only [prod.ext_iff, gcd_mul_left, normalize_apply, polynomial.coe_norm_unit, mul_assoc, comm_group_with_zero.coe_norm_unit _ ha'], have hdeg : (gcd p q).degree ≤ q.degree := degree_gcd_le_right _ hq, have hdeg' : (polynomial.C (a.leading_coeff⁻¹) * gcd p q).degree ≤ q.degree, { rw [polynomial.degree_mul, polynomial.degree_C hainv, zero_add], exact hdeg }, have hdivp : (polynomial.C a.leading_coeff⁻¹) * gcd p q ∣ p := (C_mul_dvd hainv).mpr (gcd_dvd_left p q), have hdivq : (polynomial.C a.leading_coeff⁻¹) * gcd p q ∣ q := (C_mul_dvd hainv).mpr (gcd_dvd_right p q), rw [euclidean_domain.mul_div_mul_cancel ha hdivp, euclidean_domain.mul_div_mul_cancel ha hdivq, leading_coeff_div hdeg, leading_coeff_div hdeg', polynomial.leading_coeff_mul, polynomial.leading_coeff_C, div_C_mul, div_C_mul, ← mul_assoc, ← polynomial.C_mul, ← mul_assoc, ← polynomial.C_mul], split; congr; rw [inv_div, mul_comm, mul_div_assoc, ← mul_assoc, inv_inv, _root_.mul_inv_cancel ha', one_mul, inv_div], end @[simp] lemma num_denom_div (p : K[X]) {q : K[X]} (hq : q ≠ 0) : num_denom (algebra_map _ _ p / algebra_map _ _ q) = (polynomial.C ((q / gcd p q).leading_coeff⁻¹) * (p / gcd p q), polynomial.C ((q / gcd p q).leading_coeff⁻¹) * (q / gcd p q)) := begin rw [num_denom, lift_on'_div, if_neg hq], intros p, rw [if_pos rfl, if_neg (one_ne_zero' K[X])], simp, end /-- `ratfunc.num` is the numerator of a rational function, normalized such that the denominator is monic. -/ def num (x : ratfunc K) : K[X] := x.num_denom.1 private lemma num_div' (p : K[X]) {q : K[X]} (hq : q ≠ 0) : num (algebra_map _ _ p / algebra_map _ _ q) = polynomial.C ((q / gcd p q).leading_coeff⁻¹) * (p / gcd p q) := by rw [num, num_denom_div _ hq] @[simp] lemma num_zero : num (0 : ratfunc K) = 0 := by { convert num_div' (0 : K[X]) one_ne_zero; simp } @[simp] lemma num_div (p q : K[X]) : num (algebra_map _ _ p / algebra_map _ _ q) = polynomial.C ((q / gcd p q).leading_coeff⁻¹) * (p / gcd p q) := begin by_cases hq : q = 0, { simp [hq] }, { exact num_div' p hq, }, end @[simp] lemma num_one : num (1 : ratfunc K) = 1 := by { convert num_div (1 : K[X]) 1; simp } @[simp] lemma num_algebra_map (p : K[X]) : num (algebra_map _ _ p) = p := by { convert num_div p 1; simp } lemma num_div_dvd (p : K[X]) {q : K[X]} (hq : q ≠ 0) : num (algebra_map _ _ p / algebra_map _ _ q) ∣ p := begin rw [num_div _ q, C_mul_dvd], { exact euclidean_domain.div_dvd_of_dvd (gcd_dvd_left p q) }, { simpa only [ne.def, inv_eq_zero, polynomial.leading_coeff_eq_zero] using right_div_gcd_ne_zero hq }, end /-- A version of `num_div_dvd` with the LHS in simp normal form -/ @[simp] lemma num_div_dvd' (p : K[X]) {q : K[X]} (hq : q ≠ 0) : C ((q / gcd p q).leading_coeff)⁻¹ * (p / gcd p q) ∣ p := by simpa using num_div_dvd p hq /-- `ratfunc.denom` is the denominator of a rational function, normalized such that it is monic. -/ def denom (x : ratfunc K) : K[X] := x.num_denom.2 @[simp] lemma denom_div (p : K[X]) {q : K[X]} (hq : q ≠ 0) : denom (algebra_map _ _ p / algebra_map _ _ q) = polynomial.C ((q / gcd p q).leading_coeff⁻¹) * (q / gcd p q) := by rw [denom, num_denom_div _ hq] lemma monic_denom (x : ratfunc K) : (denom x).monic := x.induction_on (λ p q hq, begin rw [denom_div p hq, mul_comm], exact polynomial.monic_mul_leading_coeff_inv (right_div_gcd_ne_zero hq) end) lemma denom_ne_zero (x : ratfunc K) : denom x ≠ 0 := (monic_denom x).ne_zero @[simp] lemma denom_zero : denom (0 : ratfunc K) = 1 := by { convert denom_div (0 : K[X]) one_ne_zero; simp } @[simp] lemma denom_one : denom (1 : ratfunc K) = 1 := by { convert denom_div (1 : K[X]) one_ne_zero; simp } @[simp] lemma denom_algebra_map (p : K[X]) : denom (algebra_map _ (ratfunc K) p) = 1 := by { convert denom_div p one_ne_zero; simp } @[simp] lemma denom_div_dvd (p q : K[X]) : denom (algebra_map _ _ p / algebra_map _ _ q) ∣ q := begin by_cases hq : q = 0, { simp [hq], }, rw [denom_div _ hq, C_mul_dvd], { exact euclidean_domain.div_dvd_of_dvd (gcd_dvd_right p q) }, { simpa only [ne.def, inv_eq_zero, polynomial.leading_coeff_eq_zero] using right_div_gcd_ne_zero hq }, end @[simp] lemma num_div_denom (x : ratfunc K) : algebra_map _ _ (num x) / algebra_map _ _ (denom x) = x := x.induction_on (λ p q hq, begin have q_div_ne_zero := right_div_gcd_ne_zero hq, rw [num_div p q, denom_div p hq, ring_hom.map_mul, ring_hom.map_mul, mul_div_mul_left, div_eq_div_iff, ← ring_hom.map_mul, ← ring_hom.map_mul, mul_comm _ q, ← euclidean_domain.mul_div_assoc, ← euclidean_domain.mul_div_assoc, mul_comm], { apply gcd_dvd_right }, { apply gcd_dvd_left }, { exact algebra_map_ne_zero q_div_ne_zero }, { exact algebra_map_ne_zero hq }, { refine algebra_map_ne_zero (mt polynomial.C_eq_zero.mp _), exact inv_ne_zero (polynomial.leading_coeff_ne_zero.mpr q_div_ne_zero) }, end) @[simp] lemma num_eq_zero_iff {x : ratfunc K} : num x = 0 ↔ x = 0 := ⟨λ h, by rw [← num_div_denom x, h, ring_hom.map_zero, zero_div], λ h, h.symm ▸ num_zero⟩ lemma num_ne_zero {x : ratfunc K} (hx : x ≠ 0) : num x ≠ 0 := mt num_eq_zero_iff.mp hx lemma num_mul_eq_mul_denom_iff {x : ratfunc K} {p q : K[X]} (hq : q ≠ 0) : x.num * q = p * x.denom ↔ x = algebra_map _ _ p / algebra_map _ _ q := begin rw [← (algebra_map_injective K).eq_iff, eq_div_iff (algebra_map_ne_zero hq)], conv_rhs { rw ← num_div_denom x }, rw [ring_hom.map_mul, ring_hom.map_mul, div_eq_mul_inv, mul_assoc, mul_comm (has_inv.inv _), ← mul_assoc, ← div_eq_mul_inv, div_eq_iff], exact algebra_map_ne_zero (denom_ne_zero x) end lemma num_denom_add (x y : ratfunc K) : (x + y).num * (x.denom * y.denom) = (x.num * y.denom + x.denom * y.num) * (x + y).denom := (num_mul_eq_mul_denom_iff (mul_ne_zero (denom_ne_zero x) (denom_ne_zero y))).mpr $ begin conv_lhs { rw [← num_div_denom x, ← num_div_denom y] }, rw [div_add_div, ring_hom.map_mul, ring_hom.map_add, ring_hom.map_mul, ring_hom.map_mul], { exact algebra_map_ne_zero (denom_ne_zero x) }, { exact algebra_map_ne_zero (denom_ne_zero y) } end lemma num_denom_neg (x : ratfunc K) : (-x).num * x.denom = - x.num * (-x).denom := by rw [num_mul_eq_mul_denom_iff (denom_ne_zero x), _root_.map_neg, neg_div, num_div_denom] lemma num_denom_mul (x y : ratfunc K) : (x * y).num * (x.denom * y.denom) = x.num * y.num * (x * y).denom := (num_mul_eq_mul_denom_iff (mul_ne_zero (denom_ne_zero x) (denom_ne_zero y))).mpr $ by conv_lhs { rw [← num_div_denom x, ← num_div_denom y, div_mul_div_comm, ← ring_hom.map_mul, ← ring_hom.map_mul] } lemma num_dvd {x : ratfunc K} {p : K[X]} (hp : p ≠ 0) : num x ∣ p ↔ ∃ (q : K[X]) (hq : q ≠ 0), x = algebra_map _ _ p / algebra_map _ _ q := begin split, { rintro ⟨q, rfl⟩, obtain ⟨hx, hq⟩ := mul_ne_zero_iff.mp hp, use denom x * q, rw [ring_hom.map_mul, ring_hom.map_mul, ← div_mul_div_comm, div_self, mul_one, num_div_denom], { exact ⟨mul_ne_zero (denom_ne_zero x) hq, rfl⟩ }, { exact algebra_map_ne_zero hq } }, { rintro ⟨q, hq, rfl⟩, exact num_div_dvd p hq }, end lemma denom_dvd {x : ratfunc K} {q : K[X]} (hq : q ≠ 0) : denom x ∣ q ↔ ∃ (p : K[X]), x = algebra_map _ _ p / algebra_map _ _ q := begin split, { rintro ⟨p, rfl⟩, obtain ⟨hx, hp⟩ := mul_ne_zero_iff.mp hq, use num x * p, rw [ring_hom.map_mul, ring_hom.map_mul, ← div_mul_div_comm, div_self, mul_one, num_div_denom], { exact algebra_map_ne_zero hp } }, { rintro ⟨p, rfl⟩, exact denom_div_dvd p q }, end lemma num_mul_dvd (x y : ratfunc K) : num (x * y) ∣ num x * num y := begin by_cases hx : x = 0, { simp [hx] }, by_cases hy : y = 0, { simp [hy] }, rw num_dvd (mul_ne_zero (num_ne_zero hx) (num_ne_zero hy)), refine ⟨x.denom * y.denom, mul_ne_zero (denom_ne_zero x) (denom_ne_zero y), _⟩, rw [ring_hom.map_mul, ring_hom.map_mul, ← div_mul_div_comm, num_div_denom, num_div_denom] end lemma denom_mul_dvd (x y : ratfunc K) : denom (x * y) ∣ denom x * denom y := begin rw denom_dvd (mul_ne_zero (denom_ne_zero x) (denom_ne_zero y)), refine ⟨x.num * y.num, _⟩, rw [ring_hom.map_mul, ring_hom.map_mul, ← div_mul_div_comm, num_div_denom, num_div_denom] end lemma denom_add_dvd (x y : ratfunc K) : denom (x + y) ∣ denom x * denom y := begin rw denom_dvd (mul_ne_zero (denom_ne_zero x) (denom_ne_zero y)), refine ⟨x.num * y.denom + x.denom * y.num, _⟩, rw [ring_hom.map_mul, ring_hom.map_add, ring_hom.map_mul, ring_hom.map_mul, ← div_add_div, num_div_denom, num_div_denom], { exact algebra_map_ne_zero (denom_ne_zero x) }, { exact algebra_map_ne_zero (denom_ne_zero y) }, end lemma map_denom_ne_zero {L F : Type*} [has_zero L] [zero_hom_class F K[X] L] (φ : F) (hφ : function.injective φ) (f : ratfunc K) : φ f.denom ≠ 0 := λ H, (denom_ne_zero f) ((map_eq_zero_iff φ hφ).mp H) lemma map_apply {R F : Type*} [comm_ring R] [is_domain R] [monoid_hom_class F K[X] R[X]] (φ : F) (hφ : K[X]⁰ ≤ R[X]⁰.comap φ) (f : ratfunc K) : map φ hφ f = algebra_map _ _ (φ f.num) / algebra_map _ _ (φ f.denom) := begin rw [←num_div_denom f, map_apply_div_ne_zero, num_div_denom f], exact denom_ne_zero _ end lemma lift_monoid_with_zero_hom_apply {L : Type*} [comm_group_with_zero L] (φ : K[X] →*₀ L) (hφ : K[X]⁰ ≤ L⁰.comap φ) (f : ratfunc K) : lift_monoid_with_zero_hom φ hφ f = φ f.num / φ f.denom := by rw [←num_div_denom f, lift_monoid_with_zero_hom_apply_div, num_div_denom] lemma lift_ring_hom_apply {L : Type*} [field L] (φ : K[X] →+* L) (hφ : K[X]⁰ ≤ L⁰.comap φ) (f : ratfunc K) : lift_ring_hom φ hφ f = φ f.num / φ f.denom := lift_monoid_with_zero_hom_apply _ _ _ lemma lift_alg_hom_apply {L S : Type*} [field L] [comm_semiring S] [algebra S K[X]] [algebra S L] (φ : K[X] →ₐ[S] L) (hφ : K[X]⁰ ≤ L⁰.comap φ) (f : ratfunc K) : lift_alg_hom φ hφ f = φ f.num / φ f.denom := lift_monoid_with_zero_hom_apply _ _ _ lemma num_mul_denom_add_denom_mul_num_ne_zero {x y : ratfunc K} (hxy : x + y ≠ 0) : x.num * y.denom + x.denom * y.num ≠ 0 := begin intro h_zero, have h := num_denom_add x y, rw [h_zero, zero_mul] at h, exact (mul_ne_zero (num_ne_zero hxy) (mul_ne_zero x.denom_ne_zero y.denom_ne_zero)) h end end num_denom section eval /-! ### Polynomial structure: `C`, `X`, `eval` -/ include hdomain /-- `ratfunc.C a` is the constant rational function `a`. -/ def C : K →+* ratfunc K := algebra_map _ _ @[simp] lemma algebra_map_eq_C : algebra_map K (ratfunc K) = C := rfl @[simp] lemma algebra_map_C (a : K) : algebra_map K[X] (ratfunc K) (polynomial.C a) = C a := rfl @[simp] lemma algebra_map_comp_C : (algebra_map K[X] (ratfunc K)).comp polynomial.C = C := rfl lemma smul_eq_C_mul (r : K) (x : ratfunc K) : r • x = C r * x := by rw [algebra.smul_def, algebra_map_eq_C] /-- `ratfunc.X` is the polynomial variable (aka indeterminate). -/ def X : ratfunc K := algebra_map K[X] (ratfunc K) polynomial.X @[simp] lemma algebra_map_X : algebra_map K[X] (ratfunc K) polynomial.X = X := rfl omit hring hdomain variables [hfield : field K] include hfield @[simp] lemma num_C (c : K) : num (C c) = polynomial.C c := num_algebra_map _ @[simp] lemma denom_C (c : K) : denom (C c) = 1 := denom_algebra_map _ @[simp] lemma num_X : num (X : ratfunc K) = polynomial.X := num_algebra_map _ @[simp] lemma denom_X : denom (X : ratfunc K) = 1 := denom_algebra_map _ lemma X_ne_zero : (ratfunc.X : ratfunc K) ≠ 0 := ratfunc.algebra_map_ne_zero polynomial.X_ne_zero variables {L : Type*} [field L] /-- Evaluate a rational function `p` given a ring hom `f` from the scalar field to the target and a value `x` for the variable in the target. Fractions are reduced by clearing common denominators before evaluating: `eval id 1 ((X^2 - 1) / (X - 1)) = eval id 1 (X + 1) = 2`, not `0 / 0 = 0`. -/ def eval (f : K →+* L) (a : L) (p : ratfunc K) : L := (num p).eval₂ f a / (denom p).eval₂ f a variables {f : K →+* L} {a : L} lemma eval_eq_zero_of_eval₂_denom_eq_zero {x : ratfunc K} (h : polynomial.eval₂ f a (denom x) = 0) : eval f a x = 0 := by rw [eval, h, div_zero] lemma eval₂_denom_ne_zero {x : ratfunc K} (h : eval f a x ≠ 0) : polynomial.eval₂ f a (denom x) ≠ 0 := mt eval_eq_zero_of_eval₂_denom_eq_zero h variables (f a) @[simp] lemma eval_C {c : K} : eval f a (C c) = f c := by simp [eval] @[simp] lemma eval_X : eval f a X = a := by simp [eval] @[simp] lemma eval_zero : eval f a 0 = 0 := by simp [eval] @[simp] lemma eval_one : eval f a 1 = 1 := by simp [eval] @[simp] lemma eval_algebra_map {S : Type*} [comm_semiring S] [algebra S K[X]] (p : S) : eval f a (algebra_map _ _ p) = (algebra_map _ K[X] p).eval₂ f a := by simp [eval, is_scalar_tower.algebra_map_apply S K[X] (ratfunc K)] /-- `eval` is an additive homomorphism except when a denominator evaluates to `0`. Counterexample: `eval _ 1 (X / (X-1)) + eval _ 1 (-1 / (X-1)) = 0` `... ≠ 1 = eval _ 1 ((X-1) / (X-1))`. See also `ratfunc.eval₂_denom_ne_zero` to make the hypotheses simpler but less general. -/ lemma eval_add {x y : ratfunc K} (hx : polynomial.eval₂ f a (denom x) ≠ 0) (hy : polynomial.eval₂ f a (denom y) ≠ 0) : eval f a (x + y) = eval f a x + eval f a y := begin unfold eval, by_cases hxy : polynomial.eval₂ f a (denom (x + y)) = 0, { have := polynomial.eval₂_eq_zero_of_dvd_of_eval₂_eq_zero f a (denom_add_dvd x y) hxy, rw polynomial.eval₂_mul at this, cases mul_eq_zero.mp this; contradiction }, rw [div_add_div _ _ hx hy, eq_div_iff (mul_ne_zero hx hy), div_eq_mul_inv, mul_right_comm, ← div_eq_mul_inv, div_eq_iff hxy], simp only [← polynomial.eval₂_mul, ← polynomial.eval₂_add], congr' 1, apply num_denom_add end /-- `eval` is a multiplicative homomorphism except when a denominator evaluates to `0`. Counterexample: `eval _ 0 X * eval _ 0 (1/X) = 0 ≠ 1 = eval _ 0 1 = eval _ 0 (X * 1/X)`. See also `ratfunc.eval₂_denom_ne_zero` to make the hypotheses simpler but less general. -/ lemma eval_mul {x y : ratfunc K} (hx : polynomial.eval₂ f a (denom x) ≠ 0) (hy : polynomial.eval₂ f a (denom y) ≠ 0) : eval f a (x * y) = eval f a x * eval f a y := begin unfold eval, by_cases hxy : polynomial.eval₂ f a (denom (x * y)) = 0, { have := polynomial.eval₂_eq_zero_of_dvd_of_eval₂_eq_zero f a (denom_mul_dvd x y) hxy, rw polynomial.eval₂_mul at this, cases mul_eq_zero.mp this; contradiction }, rw [div_mul_div_comm, eq_div_iff (mul_ne_zero hx hy), div_eq_mul_inv, mul_right_comm, ← div_eq_mul_inv, div_eq_iff hxy], repeat { rw ← polynomial.eval₂_mul }, congr' 1, apply num_denom_mul, end end eval section int_degree open polynomial omit hring variables [field K] /-- `int_degree x` is the degree of the rational function `x`, defined as the difference between the `nat_degree` of its numerator and the `nat_degree` of its denominator. In particular, `int_degree 0 = 0`. -/ def int_degree (x : ratfunc K) : ℤ := nat_degree x.num - nat_degree x.denom @[simp] lemma int_degree_zero : int_degree (0 : ratfunc K) = 0 := by rw [int_degree, num_zero, nat_degree_zero, denom_zero, nat_degree_one, sub_self] @[simp] lemma int_degree_one : int_degree (1 : ratfunc K) = 0 := by rw [int_degree, num_one, denom_one, sub_self] @[simp] lemma int_degree_C (k : K): int_degree (ratfunc.C k) = 0 := by rw [int_degree, num_C, nat_degree_C, denom_C, nat_degree_one, sub_self] @[simp] lemma int_degree_X : int_degree (X : ratfunc K) = 1 := by rw [int_degree, ratfunc.num_X, polynomial.nat_degree_X, ratfunc.denom_X, polynomial.nat_degree_one, int.coe_nat_one, int.coe_nat_zero, sub_zero] @[simp] lemma int_degree_polynomial {p : K[X]} : int_degree (algebra_map K[X] (ratfunc K) p) = nat_degree p := by rw [int_degree, ratfunc.num_algebra_map, ratfunc.denom_algebra_map, polynomial.nat_degree_one, int.coe_nat_zero, sub_zero] lemma int_degree_mul {x y : ratfunc K} (hx : x ≠ 0) (hy : y ≠ 0) : int_degree (x * y) = int_degree x + int_degree y := begin simp only [int_degree, add_sub, sub_add, sub_sub_eq_add_sub, sub_sub, sub_eq_sub_iff_add_eq_add], norm_cast, rw [← polynomial.nat_degree_mul x.denom_ne_zero y.denom_ne_zero, ← polynomial.nat_degree_mul (ratfunc.num_ne_zero (mul_ne_zero hx hy)) (mul_ne_zero x.denom_ne_zero y.denom_ne_zero), ← polynomial.nat_degree_mul (ratfunc.num_ne_zero hx) (ratfunc.num_ne_zero hy), ← polynomial.nat_degree_mul (mul_ne_zero (ratfunc.num_ne_zero hx) (ratfunc.num_ne_zero hy)) (x * y).denom_ne_zero, ratfunc.num_denom_mul] end @[simp] lemma int_degree_neg (x : ratfunc K) : int_degree (-x) = int_degree x := begin by_cases hx : x = 0, { rw [hx, neg_zero] }, { rw [int_degree, int_degree, ← nat_degree_neg x.num], exact nat_degree_sub_eq_of_prod_eq (num_ne_zero (neg_ne_zero.mpr hx)) (denom_ne_zero (- x)) (neg_ne_zero.mpr (num_ne_zero hx)) (denom_ne_zero x) (num_denom_neg x) } end lemma int_degree_add {x y : ratfunc K} (hxy : x + y ≠ 0) : (x + y).int_degree = (x.num * y.denom + x.denom * y.num).nat_degree - (x.denom * y.denom).nat_degree := nat_degree_sub_eq_of_prod_eq (num_ne_zero hxy) ((x + y).denom_ne_zero) (num_mul_denom_add_denom_mul_num_ne_zero hxy) (mul_ne_zero x.denom_ne_zero y.denom_ne_zero) (num_denom_add x y) lemma nat_degree_num_mul_right_sub_nat_degree_denom_mul_left_eq_int_degree {x : ratfunc K} (hx : x ≠ 0) {s : K[X]} (hs : s ≠ 0) : ((x.num * s).nat_degree : ℤ) - (s * x.denom).nat_degree = x.int_degree := begin apply nat_degree_sub_eq_of_prod_eq (mul_ne_zero (num_ne_zero hx) hs) (mul_ne_zero hs x.denom_ne_zero) (num_ne_zero hx) x.denom_ne_zero, rw mul_assoc end lemma int_degree_add_le {x y : ratfunc K} (hy : y ≠ 0) (hxy : x + y ≠ 0) : int_degree (x + y) ≤ max (int_degree x) (int_degree y) := begin by_cases hx : x = 0, { simp [hx] at *, }, rw [int_degree_add hxy, ← nat_degree_num_mul_right_sub_nat_degree_denom_mul_left_eq_int_degree hx y.denom_ne_zero, mul_comm y.denom, ← nat_degree_num_mul_right_sub_nat_degree_denom_mul_left_eq_int_degree hy x.denom_ne_zero, le_max_iff,sub_le_sub_iff_right, int.coe_nat_le, sub_le_sub_iff_right, int.coe_nat_le, ← le_max_iff, mul_comm y.num], exact nat_degree_add_le _ _, end end int_degree section laurent_series open power_series laurent_series hahn_series omit hring variables {F : Type u} [field F] (p q : F[X]) (f g : ratfunc F) /-- The coercion `ratfunc F → laurent_series F` as bundled alg hom. -/ def coe_alg_hom (F : Type u) [field F] : ratfunc F →ₐ[F[X]] laurent_series F := lift_alg_hom (algebra.of_id _ _) $ non_zero_divisors_le_comap_non_zero_divisors_of_injective _ $ polynomial.algebra_map_hahn_series_injective _ instance coe_to_laurent_series : has_coe (ratfunc F) (laurent_series F) := ⟨coe_alg_hom F⟩ lemma coe_def : (f : laurent_series F) = coe_alg_hom F f := rfl lemma coe_num_denom : (f : laurent_series F) = f.num / f.denom := lift_alg_hom_apply _ _ f lemma coe_injective : function.injective (coe : ratfunc F → laurent_series F) := lift_alg_hom_injective _ (polynomial.algebra_map_hahn_series_injective _) @[simp, norm_cast] lemma coe_apply : coe_alg_hom F f = f := rfl @[simp, norm_cast] lemma coe_zero : ((0 : ratfunc F) : laurent_series F) = 0 := (coe_alg_hom F).map_zero @[simp, norm_cast] lemma coe_one : ((1 : ratfunc F) : laurent_series F) = 1 := (coe_alg_hom F).map_one @[simp, norm_cast] lemma coe_add : ((f + g : ratfunc F) : laurent_series F) = f + g := (coe_alg_hom F).map_add _ _ @[simp, norm_cast] lemma coe_mul : ((f * g : ratfunc F) : laurent_series F) = f * g := (coe_alg_hom F).map_mul _ _ @[simp, norm_cast] lemma coe_div : ((f / g : ratfunc F) : laurent_series F) = (f : laurent_series F) / (g : laurent_series F) := map_div₀ (coe_alg_hom F) _ _ @[simp, norm_cast] lemma coe_C (r : F) : ((C r : ratfunc F) : laurent_series F) = hahn_series.C r := by rw [coe_num_denom, num_C, denom_C, coe_coe, polynomial.coe_C, coe_C, coe_coe, polynomial.coe_one, power_series.coe_one, div_one] -- TODO: generalize over other modules @[simp, norm_cast] lemma coe_smul (r : F) : ((r • f : ratfunc F) : laurent_series F) = r • f := by rw [smul_eq_C_mul, ←C_mul_eq_smul, coe_mul, coe_C] @[simp, norm_cast] lemma coe_X : ((X : ratfunc F) : laurent_series F) = single 1 1 := by rw [coe_num_denom, num_X, denom_X, coe_coe, polynomial.coe_X, coe_X, coe_coe, polynomial.coe_one, power_series.coe_one, div_one] instance : algebra (ratfunc F) (laurent_series F) := ring_hom.to_algebra (coe_alg_hom F).to_ring_hom lemma algebra_map_apply_div : algebra_map (ratfunc F) (laurent_series F) (algebra_map _ _ p / algebra_map _ _ q) = algebra_map F[X] (laurent_series F) p / algebra_map _ _ q := begin convert coe_div _ _; rw [←mk_one, coe_def, coe_alg_hom, mk_eq_div, lift_alg_hom_apply_div, map_one, div_one, algebra.of_id_apply] end instance : is_scalar_tower F[X] (ratfunc F) (laurent_series F) := ⟨λ x y z, by { ext, simp }⟩ end laurent_series end ratfunc
c7d123b09f1f83777ae0ae4186d4d2dc45d625e1
7cef822f3b952965621309e88eadf618da0c8ae9
/src/tactic/find.lean
f4f4b5119ada1328e0412175753feca248d469c8
[ "Apache-2.0" ]
permissive
rmitta/mathlib
8d90aee30b4db2b013e01f62c33f297d7e64a43d
883d974b608845bad30ae19e27e33c285200bf84
refs/heads/master
1,585,776,832,544
1,576,874,096,000
1,576,874,096,000
153,663,165
0
2
Apache-2.0
1,544,806,490,000
1,539,884,365,000
Lean
UTF-8
Lean
false
false
2,484
lean
/- Copyright (c) 2017 Sebastian Ullrich. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich -/ import tactic.core open expr open interactive open lean.parser open tactic private meta def match_subexpr (p : pattern) : expr → tactic (list expr) | e := prod.snd <$> match_pattern p e <|> match e with | app e₁ e₂ := match_subexpr e₁ <|> match_subexpr e₂ | pi _ _ _ b := mk_fresh_name >>= match_subexpr ∘ b.instantiate_var ∘ mk_local | lam _ _ _ b := mk_fresh_name >>= match_subexpr ∘ b.instantiate_var ∘ mk_local | _ := failed end private meta def match_exact : pexpr → expr → tactic (list expr) | p e := do (app p₁ p₂) ← pure p | match_expr p e, if pexpr.is_placeholder p₁ then -- `_ p` pattern ~> match `p` recursively do p ← pexpr_to_pattern p₂, match_subexpr p e else match_expr p e meta def expr.get_pis : expr → tactic (list expr × expr) | (pi n bi d b) := do l ← mk_local' n bi d, (pis, b) ← expr.get_pis (b.instantiate_var l), pure (d::pis, b) | e := pure ([], e) meta def pexpr.get_uninst_pis : pexpr → tactic (list pexpr × pexpr) | (pi n bi d b) := do (pis, b) ← pexpr.get_uninst_pis b, pure (d::pis, b) | e := pure ([], e) private meta def match_hyps : list pexpr → list expr → list expr → tactic unit | (p::ps) old_hyps (h::new_hyps) := do some _ ← try_core (match_exact p h) | match_hyps (p::ps) (h::old_hyps) new_hyps, match_hyps ps [] (old_hyps ++ new_hyps) | [] _ _ := skip | (_::_) _ [] := failed private meta def match_sig (p : pexpr) (e : expr) : tactic unit := do (p_pis, p) ← p.get_uninst_pis, (pis, e) ← e.get_pis, match_exact p e, match_hyps p_pis [] pis private meta def trace_match (pat : pexpr) (ty : expr) (n : name) : tactic unit := try $ do guard ¬ n.is_internal, match_sig pat ty, ty ← pp ty, trace format!"{n}: {ty}" @[user_command] meta def find_cmd (_ : parse $ tk "#find") : lean.parser unit := do pat ← lean.parser.pexpr 0, env ← get_env, env.mfold () $ λ d _, match d with | declaration.thm n _ ty _ := trace_match pat ty n | declaration.defn n _ ty _ _ _ := trace_match pat ty n | _ := skip end -- #find (_ : nat) + _ = _ + _ -- #find _ + _ = _ + _ -- #find _ (_ + _) → _ + _ = _ + _ -- TODO(Mario): no results -- #find add_group _ → _ + _ = _ + _ -- TODO(Mario): no results
ff90718f472a1a027cf5e9afbcc7d4f31b9ad5ec
37aad7bb98943e11b08c81f7d485a6fc6af1bc08
/src/dev.lean
267616b369908fbd7bb4a57609f9341dc23905e4
[]
no_license
tomhoule/migrate-dev-lean
6f5aae79a4420c960a51b126052bdd199f2e3445
910b62d1bea1d4534560e449ed82aa59100e2e75
refs/heads/main
1,675,289,840,202
1,608,732,095,000
1,608,732,095,000
322,549,132
0
0
null
null
null
null
UTF-8
Lean
false
false
6,297
lean
import data.option.basic /-! # Model of the Prisma migration engine `devDiagnostic` command The `devDiagnostic` RPC command acts as a wrapper around `diagnoseMigrationHistory`. Its role is to interpret the diagnostic output, and translate it to a concrete action to be performed by the CLI. The corresponding control flow in the CLI should be: 1. Call `RPC devDiagnostic`. Check the output: - Error / BrokenMigration -> display the error (regular user-facing error, no CLI code should be needed) - Reset -> Prompt the user to reset with the provided reason. Call `RPC reset`, then proceed with 2. - CreateMigration -> proceed with 2. 2. Call `RPC applyMigrations` 3. If we have no migration name, prompt for it. 4. Check for the `--create-only` flag - If it was passed, call `RPC evaluateDataLoss`, show the warnings, `RPC createMigration`. Done. - Otherwise, call `RPC evaluateDataLoss`, potentially ask for confirmation, `RPC createMigration`, `RPC applyMigrations`. Generate the client. Done. Implemented JSON-RPC API: ```typescript interface DevDiagnosticInput {} interface DevDiagnosticOutput { action: DevAction } type DevAction = { tag: "reset", reason: string } | { tag: "createMigration" } ``` -/ open except (error ok) variables { α : Type } universes u v /-- The top-level RPC input type. -/ inductive DevInput : Type | mk : DevInput inductive ResetReason | Drifted | Unspecified /-- The top-level RPC output type. -/ inductive DevOutput | CreateMigration | Reset : ResetReason → DevOutput -- This manifests itself as a user-facing error output, it does need any special -- handling in the CLI. | BrokenMigration : string -> DevOutput open DevOutput inductive DriftDiagnostic : Type | DriftDetected : string -> DriftDiagnostic | MigrationFailedToApply : string -> DriftDiagnostic inductive HistoryDiagnostic : Type | DatabaseIsBehind | MigrationDirectoryIsBehind | HistoriesDiverge structure DiagnoseMigrationHistoryOutput := mk :: ( drift : option DriftDiagnostic ) ( history : option HistoryDiagnostic ) ( failedMigrationNames : list string ) ( editedMigrationNames : list string ) ( errorInUnappliedMigrations : option string ) ( hasMigrationsTable : bool ) def DiagnoseMigrationHistoryOutput.resetReason : DiagnoseMigrationHistoryOutput → option ResetReason := λ projectState, if ( ¬projectState.failedMigrationNames.is_nil || ¬projectState.editedMigrationNames.is_nil ) then some ResetReason.Unspecified else if ¬projectState.drift.is_none then some ResetReason.Drifted else match projectState.history with | some HistoryDiagnostic.MigrationDirectoryIsBehind := some ResetReason.Unspecified | some HistoryDiagnostic.HistoriesDiverge := some ResetReason.Unspecified | _ := none end def DiagnoseMigrationHistoryOutput.brokenMigration : DiagnoseMigrationHistoryOutput → option string := λ o, match (o.drift, o.errorInUnappliedMigrations) with | ⟨some (DriftDiagnostic.MigrationFailedToApply name), _⟩ := some name | ⟨_, some name⟩ := some name | _ := none end example : monad id := by apply_instance /-- Machinery to define early returns. -/ def devState : Type → Type := except_t DevOutput id instance devStateMonad : monad devState := by { unfold devState, apply_instance } instance devStateMonadError : monad_except DevOutput devState := by { unfold devState, apply_instance } instance devStateMonadRun : monad_run (except DevOutput) devState := by { unfold devState, apply_instance } /-- Check that no migration (applied or unapplied) is broken. -/ def checkBrokenMigration : DiagnoseMigrationHistoryOutput → devState punit := λ state, match state.brokenMigration with | some name := throw $ BrokenMigration name | none := pure () end /-- Check whether we have a ground for a reset. -/ def checkReset : DiagnoseMigrationHistoryOutput → devState punit := λ state, match state.resetReason with | some reason := throw $ Reset reason | none := pure () end /-- The model implementation of `dev`. -/ def dev : DevInput → DiagnoseMigrationHistoryOutput → devState DevOutput := λ input projectState, checkBrokenMigration projectState >> checkReset projectState >> pure CreateMigration /-- Convenience wrapper around `dev` to make proof types more readable. -/ def runDev : DevInput → DiagnoseMigrationHistoryOutput → DevOutput := λ input diagnostics, match run (dev input diagnostics) with | (error output) := output | (ok output) := output end -- -- ---- ---- ---- ---- ---- ---- ---- ---- - -- Proofs about `dev`'s model defined above. -- -- ---- ---- ---- ---- ---- ---- ---- ---- ---- /-- If the migrations are working and we should reset, we will always return `Reset`. -/ theorem devReset : ∀ (input : DevInput) (projectState : DiagnoseMigrationHistoryOutput), projectState.brokenMigration = none → projectState.resetReason.is_some → ∃ r, runDev input projectState = Reset r := begin intros input projectState hBroken hReset, delta runDev dev checkBrokenMigration checkReset, obtain ⟨r, hSome⟩ : ∃ r, projectState.resetReason = some r, from option.is_some_iff_exists.mp hReset, existsi r, simp [hReset], rw [hSome, hBroken], refl end /-- Whenever we are not in a reset situation and no migration is broken, we will return `CreateMigration`. -/ theorem devCreateMigration : ∀ (input : DevInput) (projectState : DiagnoseMigrationHistoryOutput), projectState.resetReason = none → projectState.brokenMigration = none → runDev input projectState = CreateMigration := begin intros input projectState hNoReset hNoBrokenMigration, delta runDev dev checkBrokenMigration checkReset, rw [hNoReset, hNoBrokenMigration], refl end /-- `dev` will always return an error before asking for a reset in case a migration doesn't apply cleanly to the dev database. It never prematurely asks for a reset. -/ theorem devBrokenMigration : ∀ (input : DevInput) (projectState : DiagnoseMigrationHistoryOutput) (brokenMigrationName : string), projectState.brokenMigration = some brokenMigrationName → runDev input projectState = BrokenMigration brokenMigrationName := begin rintros input projectState brokenMigrationName hBroken, unfold runDev dev checkBrokenMigration, simpa [hBroken] end
34f7e1f93677dc6267eb72595f0bbdd39483b6bb
302b541ac2e998a523ae04da7673fd0932ded126
/tests/bench/const_folding.lean
956be8ae2a847ae979f3480ae4fa0eb43669a226
[]
no_license
mattweingarten/lambdapure
4aeff69e8e3b8e78ea3c0a2b9b61770ef5a689b1
f920a4ad78e6b1e3651f30bf8445c9105dfa03a8
refs/heads/master
1,680,665,168,790
1,618,420,180,000
1,618,420,180,000
310,816,264
2
1
null
null
null
null
UTF-8
Lean
false
false
180
lean
set_option trace.compiler.ir.init true inductive Expr | Var : Nat → Expr | Val : Nat → Expr | Add : Expr → Expr → Expr | Mul : Expr → Expr → Expr open Expr Nat
273a7a14263edada24b432b9dc1600a1ccdee676
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/field_theory/adjoin.lean
650537e0402a8b116cd320edf78111ab64857fed
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
33,305
lean
/- Copyright (c) 2020 Thomas Browning, Patrick Lutz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning, Patrick Lutz -/ import field_theory.intermediate_field import field_theory.splitting_field import field_theory.separable import ring_theory.adjoin_root import ring_theory.power_basis /-! # Adjoining Elements to Fields In this file we introduce the notion of adjoining elements to fields. This isn't quite the same as adjoining elements to rings. For example, `algebra.adjoin K {x}` might not include `x⁻¹`. ## Main results - `adjoin_adjoin_left`: adjoining S and then T is the same as adjoining `S ∪ T`. - `bot_eq_top_of_dim_adjoin_eq_one`: if `F⟮x⟯` has dimension `1` over `F` for every `x` in `E` then `F = E` ## Notation - `F⟮α⟯`: adjoin a single element `α` to `F`. -/ open finite_dimensional polynomial open_locale classical namespace intermediate_field section adjoin_def variables (F : Type*) [field F] {E : Type*} [field E] [algebra F E] (S : set E) /-- `adjoin F S` extends a field `F` by adjoining a set `S ⊆ E`. -/ def adjoin : intermediate_field F E := { algebra_map_mem' := λ x, subfield.subset_closure (or.inl (set.mem_range_self x)), ..subfield.closure (set.range (algebra_map F E) ∪ S) } end adjoin_def section lattice variables {F : Type*} [field F] {E : Type*} [field E] [algebra F E] @[simp] lemma adjoin_le_iff {S : set E} {T : intermediate_field F E} : adjoin F S ≤ T ↔ S ≤ T := ⟨λ H, le_trans (le_trans (set.subset_union_right _ _) subfield.subset_closure) H, λ H, (@subfield.closure_le E _ (set.range (algebra_map F E) ∪ S) T.to_subfield).mpr (set.union_subset (intermediate_field.set_range_subset T) H)⟩ lemma gc : galois_connection (adjoin F : set E → intermediate_field F E) coe := λ _ _, adjoin_le_iff /-- Galois insertion between `adjoin` and `coe`. -/ def gi : galois_insertion (adjoin F : set E → intermediate_field F E) coe := { choice := λ S _, adjoin F S, gc := intermediate_field.gc, le_l_u := λ S, (intermediate_field.gc (S : set E) (adjoin F S)).1 $ le_refl _, choice_eq := λ _ _, rfl } instance : complete_lattice (intermediate_field F E) := galois_insertion.lift_complete_lattice intermediate_field.gi instance : inhabited (intermediate_field F E) := ⟨⊤⟩ lemma mem_bot {x : E} : x ∈ (⊥ : intermediate_field F E) ↔ x ∈ set.range (algebra_map F E) := begin suffices : set.range (algebra_map F E) = (⊥ : intermediate_field F E), { rw this, refl }, { change set.range (algebra_map F E) = subfield.closure (set.range (algebra_map F E) ∪ ∅), simp [←set.image_univ, ←ring_hom.map_field_closure] } end lemma mem_top {x : E} : x ∈ (⊤ : intermediate_field F E) := subfield.subset_closure $ or.inr trivial @[simp] lemma bot_to_subalgebra : (⊥ : intermediate_field F E).to_subalgebra = ⊥ := by { ext, rw [mem_to_subalgebra, algebra.mem_bot, mem_bot] } @[simp] lemma top_to_subalgebra : (⊤ : intermediate_field F E).to_subalgebra = ⊤ := by { ext, rw [mem_to_subalgebra, iff_true_right algebra.mem_top], exact mem_top } /-- Construct an algebra isomorphism from an equality of subalgebras -/ def subalgebra.equiv_of_eq {X Y : subalgebra F E} (h : X = Y) : X ≃ₐ[F] Y := by refine { to_fun := λ x, ⟨x, _⟩, inv_fun := λ x, ⟨x, _⟩, .. }; tidy /-- The bottom intermediate_field is isomorphic to the field. -/ noncomputable def bot_equiv : (⊥ : intermediate_field F E) ≃ₐ[F] F := (subalgebra.equiv_of_eq bot_to_subalgebra).trans (algebra.bot_equiv F E) @[simp] lemma bot_equiv_def (x : F) : bot_equiv (algebra_map F (⊥ : intermediate_field F E) x) = x := alg_equiv.commutes bot_equiv x noncomputable instance algebra_over_bot : algebra (⊥ : intermediate_field F E) F := ring_hom.to_algebra intermediate_field.bot_equiv.to_alg_hom.to_ring_hom instance is_scalar_tower_over_bot : is_scalar_tower (⊥ : intermediate_field F E) F E := is_scalar_tower.of_algebra_map_eq begin intro x, let ϕ := algebra.of_id F (⊥ : subalgebra F E), let ψ := alg_equiv.of_bijective ϕ ((algebra.bot_equiv F E).symm.bijective), change (↑x : E) = ↑(ψ (ψ.symm ⟨x, _⟩)), rw alg_equiv.apply_symm_apply ψ ⟨x, _⟩, refl end /-- The top intermediate_field is isomorphic to the field. -/ noncomputable def top_equiv : (⊤ : intermediate_field F E) ≃ₐ[F] E := (subalgebra.equiv_of_eq top_to_subalgebra).trans algebra.top_equiv @[simp] lemma top_equiv_def (x : (⊤ : intermediate_field F E)) : top_equiv x = ↑x := begin suffices : algebra.to_top (top_equiv x) = algebra.to_top (x : E), { rwa subtype.ext_iff at this }, exact alg_equiv.apply_symm_apply (alg_equiv.of_bijective algebra.to_top ⟨λ _ _, subtype.mk.inj, λ x, ⟨x.val, by { ext, refl }⟩⟩ : E ≃ₐ[F] (⊤ : subalgebra F E)) (subalgebra.equiv_of_eq top_to_subalgebra x), end @[simp] lemma coe_bot_eq_self (K : intermediate_field F E) : ↑(⊥ : intermediate_field K E) = K := by { ext, rw [mem_lift2, mem_bot], exact set.ext_iff.mp subtype.range_coe x } @[simp] lemma coe_top_eq_top (K : intermediate_field F E) : ↑(⊤ : intermediate_field K E) = (⊤ : intermediate_field F E) := set_like.ext_iff.mpr $ λ _, mem_lift2.trans (iff_of_true mem_top mem_top) end lattice section adjoin_def variables (F : Type*) [field F] {E : Type*} [field E] [algebra F E] (S : set E) lemma adjoin_eq_range_algebra_map_adjoin : (adjoin F S : set E) = set.range (algebra_map (adjoin F S) E) := (subtype.range_coe).symm lemma adjoin.algebra_map_mem (x : F) : algebra_map F E x ∈ adjoin F S := intermediate_field.algebra_map_mem (adjoin F S) x lemma adjoin.range_algebra_map_subset : set.range (algebra_map F E) ⊆ adjoin F S := begin intros x hx, cases hx with f hf, rw ← hf, exact adjoin.algebra_map_mem F S f, end instance adjoin.field_coe : has_coe_t F (adjoin F S) := {coe := λ x, ⟨algebra_map F E x, adjoin.algebra_map_mem F S x⟩} lemma subset_adjoin : S ⊆ adjoin F S := λ x hx, subfield.subset_closure (or.inr hx) instance adjoin.set_coe : has_coe_t S (adjoin F S) := {coe := λ x, ⟨x,subset_adjoin F S (subtype.mem x)⟩} @[mono] lemma adjoin.mono (T : set E) (h : S ⊆ T) : adjoin F S ≤ adjoin F T := galois_connection.monotone_l gc h lemma adjoin_contains_field_as_subfield (F : subfield E) : (F : set E) ⊆ adjoin F S := λ x hx, adjoin.algebra_map_mem F S ⟨x, hx⟩ lemma subset_adjoin_of_subset_left {F : subfield E} {T : set E} (HT : T ⊆ F) : T ⊆ adjoin F S := λ x hx, (adjoin F S).algebra_map_mem ⟨x, HT hx⟩ lemma subset_adjoin_of_subset_right {T : set E} (H : T ⊆ S) : T ⊆ adjoin F S := λ x hx, subset_adjoin F S (H hx) @[simp] lemma adjoin_empty (F E : Type*) [field F] [field E] [algebra F E] : adjoin F (∅ : set E) = ⊥ := eq_bot_iff.mpr (adjoin_le_iff.mpr (set.empty_subset _)) /-- If `K` is a field with `F ⊆ K` and `S ⊆ K` then `adjoin F S ≤ K`. -/ lemma adjoin_le_subfield {K : subfield E} (HF : set.range (algebra_map F E) ⊆ K) (HS : S ⊆ K) : (adjoin F S).to_subfield ≤ K := begin apply subfield.closure_le.mpr, rw set.union_subset_iff, exact ⟨HF, HS⟩, end lemma adjoin_subset_adjoin_iff {F' : Type*} [field F'] [algebra F' E] {S S' : set E} : (adjoin F S : set E) ⊆ adjoin F' S' ↔ set.range (algebra_map F E) ⊆ adjoin F' S' ∧ S ⊆ adjoin F' S' := ⟨λ h, ⟨trans (adjoin.range_algebra_map_subset _ _) h, trans (subset_adjoin _ _) h⟩, λ ⟨hF, hS⟩, subfield.closure_le.mpr (set.union_subset hF hS)⟩ /-- `F[S][T] = F[S ∪ T]` -/ lemma adjoin_adjoin_left (T : set E) : ↑(adjoin (adjoin F S) T) = adjoin F (S ∪ T) := begin rw set_like.ext'_iff, change ↑(adjoin (adjoin F S) T) = _, apply set.eq_of_subset_of_subset; rw adjoin_subset_adjoin_iff; split, { rintros _ ⟨⟨x, hx⟩, rfl⟩, exact adjoin.mono _ _ _ (set.subset_union_left _ _) hx }, { exact subset_adjoin_of_subset_right _ _ (set.subset_union_right _ _) }, { exact subset_adjoin_of_subset_left _ (adjoin.range_algebra_map_subset _ _) }, { exact set.union_subset (subset_adjoin_of_subset_left _ (subset_adjoin _ _)) (subset_adjoin _ _) }, end @[simp] lemma adjoin_insert_adjoin (x : E) : adjoin F (insert x (adjoin F S : set E)) = adjoin F (insert x S) := le_antisymm (adjoin_le_iff.mpr (set.insert_subset.mpr ⟨subset_adjoin _ _ (set.mem_insert _ _), adjoin_le_iff.mpr (subset_adjoin_of_subset_right _ _ (set.subset_insert _ _))⟩)) (adjoin.mono _ _ _ (set.insert_subset_insert (subset_adjoin _ _))) /-- `F[S][T] = F[T][S]` -/ lemma adjoin_adjoin_comm (T : set E) : ↑(adjoin (adjoin F S) T) = (↑(adjoin (adjoin F T) S) : (intermediate_field F E)) := by rw [adjoin_adjoin_left, adjoin_adjoin_left, set.union_comm] lemma adjoin_map {E' : Type*} [field E'] [algebra F E'] (f : E →ₐ[F] E') : (adjoin F S).map f = adjoin F (f '' S) := begin ext x, show x ∈ (subfield.closure (set.range (algebra_map F E) ∪ S)).map (f : E →+* E') ↔ x ∈ subfield.closure (set.range (algebra_map F E') ∪ f '' S), rw [ring_hom.map_field_closure, set.image_union, ← set.range_comp, ← ring_hom.coe_comp, f.comp_algebra_map], refl, end lemma algebra_adjoin_le_adjoin : algebra.adjoin F S ≤ (adjoin F S).to_subalgebra := algebra.adjoin_le (subset_adjoin _ _) lemma adjoin_eq_algebra_adjoin (inv_mem : ∀ x ∈ algebra.adjoin F S, x⁻¹ ∈ algebra.adjoin F S) : (adjoin F S).to_subalgebra = algebra.adjoin F S := le_antisymm (show adjoin F S ≤ { neg_mem' := λ x, (algebra.adjoin F S).neg_mem, inv_mem' := inv_mem, .. algebra.adjoin F S}, from adjoin_le_iff.mpr (algebra.subset_adjoin)) (algebra_adjoin_le_adjoin _ _) lemma eq_adjoin_of_eq_algebra_adjoin (K : intermediate_field F E) (h : K.to_subalgebra = algebra.adjoin F S) : K = adjoin F S := begin apply to_subalgebra_injective, rw h, refine (adjoin_eq_algebra_adjoin _ _ _).symm, intros x, convert K.inv_mem, rw ← h, refl end @[elab_as_eliminator] lemma adjoin_induction {s : set E} {p : E → Prop} {x} (h : x ∈ adjoin F s) (Hs : ∀ x ∈ s, p x) (Hmap : ∀ x, p (algebra_map F E x)) (Hadd : ∀ x y, p x → p y → p (x + y)) (Hneg : ∀ x, p x → p (-x)) (Hinv : ∀ x, p x → p x⁻¹) (Hmul : ∀ x y, p x → p y → p (x * y)) : p x := subfield.closure_induction h (λ x hx, or.cases_on hx (λ ⟨x, hx⟩, hx ▸ Hmap x) (Hs x)) ((algebra_map F E).map_one ▸ Hmap 1) Hadd Hneg Hinv Hmul /-- Variation on `set.insert` to enable good notation for adjoining elements to fields. Used to preferentially use `singleton` rather than `insert` when adjoining one element. -/ --this definition of notation is courtesy of Kyle Miller on zulip class insert {α : Type*} (s : set α) := (insert : α → set α) @[priority 1000] instance insert_empty {α : Type*} : insert (∅ : set α) := { insert := λ x, @singleton _ _ set.has_singleton x } @[priority 900] instance insert_nonempty {α : Type*} (s : set α) : insert s := { insert := λ x, set.insert x s } notation K`⟮`:std.prec.max_plus l:(foldr `, ` (h t, insert.insert t h) ∅) `⟯` := adjoin K l section adjoin_simple variables (α : E) lemma mem_adjoin_simple_self : α ∈ F⟮α⟯ := subset_adjoin F {α} (set.mem_singleton α) /-- generator of `F⟮α⟯` -/ def adjoin_simple.gen : F⟮α⟯ := ⟨α, mem_adjoin_simple_self F α⟩ @[simp] lemma adjoin_simple.algebra_map_gen : algebra_map F⟮α⟯ E (adjoin_simple.gen F α) = α := rfl lemma adjoin_simple_adjoin_simple (β : E) : ↑F⟮α⟯⟮β⟯ = F⟮α, β⟯ := adjoin_adjoin_left _ _ _ lemma adjoin_simple_comm (β : E) : ↑F⟮α⟯⟮β⟯ = (↑F⟮β⟯⟮α⟯ : intermediate_field F E) := adjoin_adjoin_comm _ _ _ -- TODO: develop the API for `subalgebra.is_field_of_algebraic` so it can be used here lemma adjoin_simple_to_subalgebra_of_integral (hα : is_integral F α) : (F⟮α⟯).to_subalgebra = algebra.adjoin F {α} := begin apply adjoin_eq_algebra_adjoin, intros x hx, by_cases x = 0, { rw [h, inv_zero], exact subalgebra.zero_mem (algebra.adjoin F {α}) }, let ϕ := alg_equiv.adjoin_singleton_equiv_adjoin_root_minpoly F α, haveI := minpoly.irreducible hα, suffices : ϕ ⟨x, hx⟩ * (ϕ ⟨x, hx⟩)⁻¹ = 1, { convert subtype.mem (ϕ.symm (ϕ ⟨x, hx⟩)⁻¹), refine (eq_inv_of_mul_right_eq_one _).symm, apply_fun ϕ.symm at this, rw [alg_equiv.map_one, alg_equiv.map_mul, alg_equiv.symm_apply_apply] at this, rw [←subsemiring.coe_one, ←this, subsemiring.coe_mul, subtype.coe_mk] }, rw mul_inv_cancel (mt (λ key, _) h), rw ← ϕ.map_zero at key, change ↑(⟨x, hx⟩ : algebra.adjoin F {α}) = _, rw [ϕ.injective key, subalgebra.coe_zero] end end adjoin_simple end adjoin_def section adjoin_intermediate_field_lattice variables {F : Type*} [field F] {E : Type*} [field E] [algebra F E] {α : E} {S : set E} @[simp] lemma adjoin_eq_bot_iff : adjoin F S = ⊥ ↔ S ⊆ (⊥ : intermediate_field F E) := by { rw [eq_bot_iff, adjoin_le_iff], refl, } @[simp] lemma adjoin_simple_eq_bot_iff : F⟮α⟯ = ⊥ ↔ α ∈ (⊥ : intermediate_field F E) := by { rw adjoin_eq_bot_iff, exact set.singleton_subset_iff } @[simp] lemma adjoin_zero : F⟮(0 : E)⟯ = ⊥ := adjoin_simple_eq_bot_iff.mpr (zero_mem ⊥) @[simp] lemma adjoin_one : F⟮(1 : E)⟯ = ⊥ := adjoin_simple_eq_bot_iff.mpr (one_mem ⊥) @[simp] lemma adjoin_int (n : ℤ) : F⟮(n : E)⟯ = ⊥ := adjoin_simple_eq_bot_iff.mpr (coe_int_mem ⊥ n) @[simp] lemma adjoin_nat (n : ℕ) : F⟮(n : E)⟯ = ⊥ := adjoin_simple_eq_bot_iff.mpr (coe_int_mem ⊥ n) section adjoin_dim open finite_dimensional vector_space variables {K L : intermediate_field F E} @[simp] lemma dim_eq_one_iff : dim F K = 1 ↔ K = ⊥ := by rw [← to_subalgebra_eq_iff, ← dim_eq_dim_subalgebra, subalgebra.dim_eq_one_iff, bot_to_subalgebra] @[simp] lemma findim_eq_one_iff : findim F K = 1 ↔ K = ⊥ := by rw [← to_subalgebra_eq_iff, ← findim_eq_findim_subalgebra, subalgebra.findim_eq_one_iff, bot_to_subalgebra] lemma dim_adjoin_eq_one_iff : dim F (adjoin F S) = 1 ↔ S ⊆ (⊥ : intermediate_field F E) := iff.trans dim_eq_one_iff adjoin_eq_bot_iff lemma dim_adjoin_simple_eq_one_iff : dim F F⟮α⟯ = 1 ↔ α ∈ (⊥ : intermediate_field F E) := by { rw dim_adjoin_eq_one_iff, exact set.singleton_subset_iff } lemma findim_adjoin_eq_one_iff : findim F (adjoin F S) = 1 ↔ S ⊆ (⊥ : intermediate_field F E) := iff.trans findim_eq_one_iff adjoin_eq_bot_iff lemma findim_adjoin_simple_eq_one_iff : findim F F⟮α⟯ = 1 ↔ α ∈ (⊥ : intermediate_field F E) := by { rw [findim_adjoin_eq_one_iff], exact set.singleton_subset_iff } /-- If `F⟮x⟯` has dimension `1` over `F` for every `x ∈ E` then `F = E`. -/ lemma bot_eq_top_of_dim_adjoin_eq_one (h : ∀ x : E, dim F F⟮x⟯ = 1) : (⊥ : intermediate_field F E) = ⊤ := begin ext, rw iff_true_right intermediate_field.mem_top, exact dim_adjoin_simple_eq_one_iff.mp (h x), end lemma bot_eq_top_of_findim_adjoin_eq_one (h : ∀ x : E, findim F F⟮x⟯ = 1) : (⊥ : intermediate_field F E) = ⊤ := begin ext, rw iff_true_right intermediate_field.mem_top, exact findim_adjoin_simple_eq_one_iff.mp (h x), end lemma subsingleton_of_dim_adjoin_eq_one (h : ∀ x : E, dim F F⟮x⟯ = 1) : subsingleton (intermediate_field F E) := subsingleton_of_bot_eq_top (bot_eq_top_of_dim_adjoin_eq_one h) lemma subsingleton_of_findim_adjoin_eq_one (h : ∀ x : E, findim F F⟮x⟯ = 1) : subsingleton (intermediate_field F E) := subsingleton_of_bot_eq_top (bot_eq_top_of_findim_adjoin_eq_one h) /-- If `F⟮x⟯` has dimension `≤1` over `F` for every `x ∈ E` then `F = E`. -/ lemma bot_eq_top_of_findim_adjoin_le_one [finite_dimensional F E] (h : ∀ x : E, findim F F⟮x⟯ ≤ 1) : (⊥ : intermediate_field F E) = ⊤ := begin apply bot_eq_top_of_findim_adjoin_eq_one, exact λ x, by linarith [h x, show 0 < findim F F⟮x⟯, from findim_pos], end lemma subsingleton_of_findim_adjoin_le_one [finite_dimensional F E] (h : ∀ x : E, findim F F⟮x⟯ ≤ 1) : subsingleton (intermediate_field F E) := subsingleton_of_bot_eq_top (bot_eq_top_of_findim_adjoin_le_one h) end adjoin_dim end adjoin_intermediate_field_lattice section adjoin_integral_element variables (F : Type*) [field F] {E : Type*} [field E] [algebra F E] {α : E} variables {K : Type*} [field K] [algebra F K] lemma aeval_gen_minpoly (α : E) : aeval (adjoin_simple.gen F α) (minpoly F α) = 0 := begin ext, convert minpoly.aeval F α, conv in (aeval α) { rw [← adjoin_simple.algebra_map_gen F α] }, exact is_scalar_tower.algebra_map_aeval F F⟮α⟯ E _ _ end /-- algebra isomorphism between `adjoin_root` and `F⟮α⟯` -/ noncomputable def adjoin_root_equiv_adjoin (h : is_integral F α) : adjoin_root (minpoly F α) ≃ₐ[F] F⟮α⟯ := alg_equiv.of_bijective (alg_hom.mk (adjoin_root.lift (algebra_map F F⟮α⟯) (adjoin_simple.gen F α) (aeval_gen_minpoly F α)) (ring_hom.map_one _) (λ x y, ring_hom.map_mul _ x y) (ring_hom.map_zero _) (λ x y, ring_hom.map_add _ x y) (by { exact λ _, adjoin_root.lift_of })) (begin set f := adjoin_root.lift _ _ (aeval_gen_minpoly F α), haveI := minpoly.irreducible h, split, { exact ring_hom.injective f }, { suffices : F⟮α⟯.to_subfield ≤ ring_hom.field_range ((F⟮α⟯.to_subfield.subtype).comp f), { exact λ x, Exists.cases_on (this (subtype.mem x)) (λ y hy, ⟨y, subtype.ext hy.2⟩) }, exact subfield.closure_le.mpr (set.union_subset (λ x hx, Exists.cases_on hx (λ y hy, ⟨y, ⟨subfield.mem_top y, by { rw [ring_hom.comp_apply, adjoin_root.lift_of], exact hy }⟩⟩)) (set.singleton_subset_iff.mpr ⟨adjoin_root.root (minpoly F α), ⟨subfield.mem_top (adjoin_root.root (minpoly F α)), by { rw [ring_hom.comp_apply, adjoin_root.lift_root], refl }⟩⟩)) } end) lemma adjoin_root_equiv_adjoin_apply_root (h : is_integral F α) : adjoin_root_equiv_adjoin F h (adjoin_root.root (minpoly F α)) = adjoin_simple.gen F α := begin refine adjoin_root.lift_root, { exact minpoly F α }, { exact aeval_gen_minpoly F α } end /-- Algebra homomorphism `F⟮α⟯ →ₐ[F] K` are in bijection with the set of roots of `minpoly α` in `K`. -/ noncomputable def alg_hom_adjoin_integral_equiv (h : is_integral F α) : (F⟮α⟯ →ₐ[F] K) ≃ {x // x ∈ ((minpoly F α).map (algebra_map F K)).roots} := let ϕ := adjoin_root_equiv_adjoin F h, swap1 : (F⟮α⟯ →ₐ[F] K) ≃ (adjoin_root (minpoly F α) →ₐ[F] K) := { to_fun := λ f, f.comp ϕ.to_alg_hom, inv_fun := λ f, f.comp ϕ.symm.to_alg_hom, left_inv := λ _, by { ext, simp only [alg_equiv.coe_alg_hom, alg_equiv.to_alg_hom_eq_coe, alg_hom.comp_apply, alg_equiv.apply_symm_apply]}, right_inv := λ _, by { ext, simp only [alg_equiv.symm_apply_apply, alg_equiv.coe_alg_hom, alg_equiv.to_alg_hom_eq_coe, alg_hom.comp_apply] } }, swap2 := adjoin_root.equiv F K (minpoly F α) (minpoly.ne_zero h) in swap1.trans swap2 /-- Fintype of algebra homomorphism `F⟮α⟯ →ₐ[F] K` -/ noncomputable def fintype_of_alg_hom_adjoin_integral (h : is_integral F α) : fintype (F⟮α⟯ →ₐ[F] K) := fintype.of_equiv _ (alg_hom_adjoin_integral_equiv F h).symm lemma card_alg_hom_adjoin_integral (h : is_integral F α) (h_sep : (minpoly F α).separable) (h_splits : (minpoly F α).splits (algebra_map F K)) : @fintype.card (F⟮α⟯ →ₐ[F] K) (fintype_of_alg_hom_adjoin_integral F h) = (minpoly F α).nat_degree := begin let s := ((minpoly F α).map (algebra_map F K)).roots.to_finset, have H := λ x, multiset.mem_to_finset, rw [fintype.card_congr (alg_hom_adjoin_integral_equiv F h), fintype.card_of_subtype s H, nat_degree_eq_card_roots h_splits, multiset.to_finset_card_of_nodup], exact nodup_roots ((separable_map (algebra_map F K)).mpr h_sep), end end adjoin_integral_element section induction variables {F : Type*} [field F] {E : Type*} [field E] [algebra F E] /-- An intermediate field `S` is finitely generated if there exists `t : finset E` such that `intermediate_field.adjoin F t = S`. -/ def fg (S : intermediate_field F E) : Prop := ∃ (t : finset E), adjoin F ↑t = S lemma fg_adjoin_finset (t : finset E) : (adjoin F (↑t : set E)).fg := ⟨t, rfl⟩ theorem fg_def {S : intermediate_field F E} : S.fg ↔ ∃ t : set E, set.finite t ∧ adjoin F t = S := ⟨λ ⟨t, ht⟩, ⟨↑t, set.finite_mem_finset t, ht⟩, λ ⟨t, ht1, ht2⟩, ⟨ht1.to_finset, by rwa set.finite.coe_to_finset⟩⟩ theorem fg_bot : (⊥ : intermediate_field F E).fg := ⟨∅, adjoin_empty F E⟩ lemma fg_of_fg_to_subalgebra (S : intermediate_field F E) (h : S.to_subalgebra.fg) : S.fg := begin cases h with t ht, exact ⟨t, (eq_adjoin_of_eq_algebra_adjoin _ _ _ ht.symm).symm⟩ end lemma fg_of_noetherian (S : intermediate_field F E) [is_noetherian F E] : S.fg := S.fg_of_fg_to_subalgebra S.to_subalgebra.fg_of_noetherian lemma induction_on_adjoin_finset (S : finset E) (P : intermediate_field F E → Prop) (base : P ⊥) (ih : ∀ (K : intermediate_field F E) (x ∈ S), P K → P ↑K⟮x⟯) : P (adjoin F ↑S) := begin apply finset.induction_on' S, { exact base }, { intros a s h1 _ _ h4, rw [finset.coe_insert, set.insert_eq, set.union_comm, ←adjoin_adjoin_left], exact ih (adjoin F s) a h1 h4 } end lemma induction_on_adjoin_fg (P : intermediate_field F E → Prop) (base : P ⊥) (ih : ∀ (K : intermediate_field F E) (x : E), P K → P ↑K⟮x⟯) (K : intermediate_field F E) (hK : K.fg) : P K := begin obtain ⟨S, rfl⟩ := hK, exact induction_on_adjoin_finset S P base (λ K x _ hK, ih K x hK), end lemma induction_on_adjoin [fd : finite_dimensional F E] (P : intermediate_field F E → Prop) (base : P ⊥) (ih : ∀ (K : intermediate_field F E) (x : E), P K → P ↑K⟮x⟯) (K : intermediate_field F E) : P K := induction_on_adjoin_fg P base ih K K.fg_of_noetherian end induction section alg_hom_mk_adjoin_splits variables (F E K : Type*) [field F] [field E] [field K] [algebra F E] [algebra F K] {S : set E} /-- Lifts `L → K` of `F → K` -/ def lifts := Σ (L : intermediate_field F E), (L →ₐ[F] K) variables {F E K} noncomputable instance : order_bot (lifts F E K) := { le := λ x y, x.1 ≤ y.1 ∧ (∀ (s : x.1) (t : y.1), (s : E) = t → x.2 s = y.2 t), le_refl := λ x, ⟨le_refl x.1, λ s t hst, congr_arg x.2 (subtype.ext hst)⟩, le_trans := λ x y z hxy hyz, ⟨le_trans hxy.1 hyz.1, λ s u hsu, eq.trans (hxy.2 s ⟨s, hxy.1 s.mem⟩ rfl) (hyz.2 ⟨s, hxy.1 s.mem⟩ u hsu)⟩, le_antisymm := begin rintros ⟨x1, x2⟩ ⟨y1, y2⟩ ⟨hxy1, hxy2⟩ ⟨hyx1, hyx2⟩, have : x1 = y1 := le_antisymm hxy1 hyx1, subst this, congr, exact alg_hom.ext (λ s, hxy2 s s rfl), end, bot := ⟨⊥, (algebra.of_id F K).comp bot_equiv.to_alg_hom⟩, bot_le := λ x, ⟨bot_le, λ s t hst, begin cases intermediate_field.mem_bot.mp s.mem with u hu, rw [show s = (algebra_map F _) u, from subtype.ext hu.symm, alg_hom.commutes], rw [show t = (algebra_map F _) u, from subtype.ext (eq.trans hu hst).symm, alg_hom.commutes], end⟩ } noncomputable instance : inhabited (lifts F E K) := ⟨⊥⟩ lemma lifts.eq_of_le {x y : lifts F E K} (hxy : x ≤ y) (s : x.1) : x.2 s = y.2 ⟨s, hxy.1 s.mem⟩ := hxy.2 s ⟨s, hxy.1 s.mem⟩ rfl lemma lifts.exists_max_two {c : set (lifts F E K)} {x y : lifts F E K} (hc : zorn.chain (≤) c) (hx : x ∈ set.insert ⊥ c) (hy : y ∈ set.insert ⊥ c) : ∃ z : lifts F E K, z ∈ set.insert ⊥ c ∧ x ≤ z ∧ y ≤ z := begin cases (zorn.chain_insert hc (λ _ _ _, or.inl bot_le)).total_of_refl hx hy with hxy hyx, { exact ⟨y, hy, hxy, le_refl y⟩ }, { exact ⟨x, hx, le_refl x, hyx⟩ }, end lemma lifts.exists_max_three {c : set (lifts F E K)} {x y z : lifts F E K} (hc : zorn.chain (≤) c) (hx : x ∈ set.insert ⊥ c) (hy : y ∈ set.insert ⊥ c) (hz : z ∈ set.insert ⊥ c) : ∃ w : lifts F E K, w ∈ set.insert ⊥ c ∧ x ≤ w ∧ y ≤ w ∧ z ≤ w := begin obtain ⟨v, hv, hxv, hyv⟩ := lifts.exists_max_two hc hx hy, obtain ⟨w, hw, hzw, hvw⟩ := lifts.exists_max_two hc hz hv, exact ⟨w, hw, le_trans hxv hvw, le_trans hyv hvw, hzw⟩, end /-- An upper bound on a chain of lifts -/ def lifts.upper_bound_intermediate_field {c : set (lifts F E K)} (hc : zorn.chain (≤) c) : intermediate_field F E := { carrier := λ s, ∃ x : (lifts F E K), x ∈ set.insert ⊥ c ∧ (s ∈ x.1 : Prop), zero_mem' := ⟨⊥, set.mem_insert ⊥ c, zero_mem ⊥⟩, one_mem' := ⟨⊥, set.mem_insert ⊥ c, one_mem ⊥⟩, neg_mem' := by { rintros _ ⟨x, y, h⟩, exact ⟨x, ⟨y, x.1.neg_mem h⟩⟩ }, inv_mem' := by { rintros _ ⟨x, y, h⟩, exact ⟨x, ⟨y, x.1.inv_mem h⟩⟩ }, add_mem' := by { rintros _ _ ⟨x, hx, ha⟩ ⟨y, hy, hb⟩, obtain ⟨z, hz, hxz, hyz⟩ := lifts.exists_max_two hc hx hy, exact ⟨z, hz, z.1.add_mem (hxz.1 ha) (hyz.1 hb)⟩ }, mul_mem' := by { rintros _ _ ⟨x, hx, ha⟩ ⟨y, hy, hb⟩, obtain ⟨z, hz, hxz, hyz⟩ := lifts.exists_max_two hc hx hy, exact ⟨z, hz, z.1.mul_mem (hxz.1 ha) (hyz.1 hb)⟩ }, algebra_map_mem' := λ s, ⟨⊥, set.mem_insert ⊥ c, algebra_map_mem ⊥ s⟩ } /-- The lift on the upper bound on a chain of lifts -/ noncomputable def lifts.upper_bound_alg_hom {c : set (lifts F E K)} (hc : zorn.chain (≤) c) : lifts.upper_bound_intermediate_field hc →ₐ[F] K := { to_fun := λ s, (classical.some s.mem).2 ⟨s, (classical.some_spec s.mem).2⟩, map_zero' := alg_hom.map_zero _, map_one' := alg_hom.map_one _, map_add' := λ s t, begin obtain ⟨w, hw, hxw, hyw, hzw⟩ := lifts.exists_max_three hc (classical.some_spec s.mem).1 (classical.some_spec t.mem).1 (classical.some_spec (s + t).mem).1, rw [lifts.eq_of_le hxw, lifts.eq_of_le hyw, lifts.eq_of_le hzw, ←w.2.map_add], refl, end, map_mul' := λ s t, begin obtain ⟨w, hw, hxw, hyw, hzw⟩ := lifts.exists_max_three hc (classical.some_spec s.mem).1 (classical.some_spec t.mem).1 (classical.some_spec (s * t).mem).1, rw [lifts.eq_of_le hxw, lifts.eq_of_le hyw, lifts.eq_of_le hzw, ←w.2.map_mul], refl, end, commutes' := λ _, alg_hom.commutes _ _ } /-- An upper bound on a chain of lifts -/ noncomputable def lifts.upper_bound {c : set (lifts F E K)} (hc : zorn.chain (≤) c) : lifts F E K := ⟨lifts.upper_bound_intermediate_field hc, lifts.upper_bound_alg_hom hc⟩ lemma lifts.exists_upper_bound (c : set (lifts F E K)) (hc : zorn.chain (≤) c) : ∃ ub, ∀ a ∈ c, a ≤ ub := ⟨lifts.upper_bound hc, begin intros x hx, split, { exact λ s hs, ⟨x, set.mem_insert_of_mem ⊥ hx, hs⟩ }, { intros s t hst, change x.2 s = (classical.some t.mem).2 ⟨t, (classical.some_spec t.mem).2⟩, obtain ⟨z, hz, hxz, hyz⟩ := lifts.exists_max_two hc (set.mem_insert_of_mem ⊥ hx) (classical.some_spec t.mem).1, rw [lifts.eq_of_le hxz, lifts.eq_of_le hyz], exact congr_arg z.2 (subtype.ext hst) }, end⟩ /-- Extend a lift `x : lifts F E K` to an element `s : E` whose conjugates are all in `K` -/ noncomputable def lifts.lift_of_splits (x : lifts F E K) {s : E} (h1 : is_integral F s) (h2 : (minpoly F s).splits (algebra_map F K)) : lifts F E K := let h3 : is_integral x.1 s := is_integral_of_is_scalar_tower s h1 in let key : (minpoly x.1 s).splits x.2.to_ring_hom := splits_of_splits_of_dvd _ (map_ne_zero (minpoly.ne_zero h1)) ((splits_map_iff _ _).mpr (by {convert h2, exact ring_hom.ext (λ y, x.2.commutes y)})) (minpoly.dvd_map_of_is_scalar_tower _ _ _) in ⟨↑x.1⟮s⟯, (@alg_hom_equiv_sigma F x.1 (↑x.1⟮s⟯ : intermediate_field F E) K _ _ _ _ _ _ _ (intermediate_field.algebra x.1⟮s⟯) (is_scalar_tower.of_algebra_map_eq (λ _, rfl))).inv_fun ⟨x.2, (@alg_hom_adjoin_integral_equiv x.1 _ E _ _ s K _ x.2.to_ring_hom.to_algebra h3).inv_fun ⟨root_of_splits x.2.to_ring_hom key (ne_of_gt (minpoly.degree_pos h3)), by { simp_rw [mem_roots (map_ne_zero (minpoly.ne_zero h3)), is_root, ←eval₂_eq_eval_map], exact map_root_of_splits x.2.to_ring_hom key (ne_of_gt (minpoly.degree_pos h3)) }⟩⟩⟩ lemma lifts.le_lifts_of_splits (x : lifts F E K) {s : E} (h1 : is_integral F s) (h2 : (minpoly F s).splits (algebra_map F K)) : x ≤ x.lift_of_splits h1 h2 := ⟨λ z hz, algebra_map_mem x.1⟮s⟯ ⟨z, hz⟩, λ t u htu, eq.symm begin rw [←(show algebra_map x.1 x.1⟮s⟯ t = u, from subtype.ext htu)], letI : algebra x.1 K := x.2.to_ring_hom.to_algebra, exact (alg_hom.commutes _ t), end⟩ lemma lifts.mem_lifts_of_splits (x : lifts F E K) {s : E} (h1 : is_integral F s) (h2 : (minpoly F s).splits (algebra_map F K)) : s ∈ (x.lift_of_splits h1 h2).1 := mem_adjoin_simple_self x.1 s lemma lifts.exists_lift_of_splits (x : lifts F E K) {s : E} (h1 : is_integral F s) (h2 : (minpoly F s).splits (algebra_map F K)) : ∃ y, x ≤ y ∧ s ∈ y.1 := ⟨x.lift_of_splits h1 h2, x.le_lifts_of_splits h1 h2, x.mem_lifts_of_splits h1 h2⟩ lemma alg_hom_mk_adjoin_splits (hK : ∀ s ∈ S, is_integral F (s : E) ∧ (minpoly F s).splits (algebra_map F K)) : nonempty (adjoin F S →ₐ[F] K) := begin obtain ⟨x : lifts F E K, hx⟩ := zorn.zorn_partial_order lifts.exists_upper_bound, refine ⟨alg_hom.mk (λ s, x.2 ⟨s, adjoin_le_iff.mpr (λ s hs, _) s.mem⟩) x.2.map_one (λ s t, x.2.map_mul ⟨s, _⟩ ⟨t, _⟩) x.2.map_zero (λ s t, x.2.map_add ⟨s, _⟩ ⟨t, _⟩) x.2.commutes⟩, rcases (x.exists_lift_of_splits (hK s hs).1 (hK s hs).2) with ⟨y, h1, h2⟩, rwa hx y h1 at h2 end lemma alg_hom_mk_adjoin_splits' (hS : adjoin F S = ⊤) (hK : ∀ x ∈ S, is_integral F (x : E) ∧ (minpoly F x).splits (algebra_map F K)) : nonempty (E →ₐ[F] K) := begin cases alg_hom_mk_adjoin_splits hK with ϕ, rw hS at ϕ, exact ⟨ϕ.comp top_equiv.symm.to_alg_hom⟩, end end alg_hom_mk_adjoin_splits end intermediate_field section power_basis variables {K L : Type*} [field K] [field L] [algebra K L] namespace intermediate_field lemma power_basis_is_basis {x : L} (hx : is_integral K x) : is_basis K (λ (i : fin (minpoly K x).nat_degree), (adjoin_simple.gen K x ^ (i : ℕ))) := begin let ϕ := (adjoin_root_equiv_adjoin K hx).to_linear_equiv, have key : ϕ (adjoin_root.root (minpoly K x)) = adjoin_simple.gen K x, { exact intermediate_field.adjoin_root_equiv_adjoin_apply_root K hx }, suffices : ϕ ∘ (λ (i : fin (minpoly K x).nat_degree), adjoin_root.root (minpoly K x) ^ (i.val)) = (λ (i : fin (minpoly K x).nat_degree), (adjoin_simple.gen K x) ^ ↑i), { rw ← this, exact linear_equiv.is_basis (adjoin_root.power_basis_is_basis (minpoly.ne_zero hx)) ϕ }, ext y, rw [function.comp_app, fin.val_eq_coe, alg_equiv.to_linear_equiv_apply, alg_equiv.map_pow], rw intermediate_field.adjoin_root_equiv_adjoin_apply_root K hx, end /-- The power basis `1, x, ..., x ^ (d - 1)` for `K⟮x⟯`, where `d` is the degree of the minimal polynomial of `x`. -/ noncomputable def adjoin.power_basis {x : L} (hx : is_integral K x) : power_basis K K⟮x⟯ := { gen := adjoin_simple.gen K x, dim := (minpoly K x).nat_degree, is_basis := power_basis_is_basis hx } @[simp] lemma adjoin.power_basis.gen_eq {x : L} (hx : is_integral K x) : (adjoin.power_basis hx).gen = adjoin_simple.gen K x := rfl lemma adjoin.finite_dimensional {x : L} (hx : is_integral K x) : finite_dimensional K K⟮x⟯ := power_basis.finite_dimensional (adjoin.power_basis hx) lemma adjoin.findim {x : L} (hx : is_integral K x) : finite_dimensional.findim K K⟮x⟯ = (minpoly K x).nat_degree := begin rw power_basis.findim (adjoin.power_basis hx), refl, end end intermediate_field namespace power_basis open intermediate_field /-- `pb.equiv_adjoin_simple` is the equivalence between `K⟮pb.gen⟯` and `L` itself. -/ noncomputable def equiv_adjoin_simple (pb : power_basis K L) : K⟮pb.gen⟯ ≃ₐ[K] L := (adjoin.power_basis pb.is_integral_gen).equiv pb (minpoly.eq_of_algebra_map_eq (algebra_map K⟮pb.gen⟯ L).injective (adjoin.power_basis pb.is_integral_gen).is_integral_gen (by rw [adjoin.power_basis.gen_eq, adjoin_simple.algebra_map_gen])) @[simp] lemma equiv_adjoin_simple_aeval (pb : power_basis K L) (f : polynomial K) : pb.equiv_adjoin_simple (aeval (adjoin_simple.gen K pb.gen) f) = aeval pb.gen f := equiv_aeval _ pb _ f @[simp] lemma equiv_adjoin_simple_gen (pb : power_basis K L) : pb.equiv_adjoin_simple (adjoin_simple.gen K pb.gen) = pb.gen := equiv_gen _ pb _ @[simp] lemma equiv_adjoin_simple_symm_aeval (pb : power_basis K L) (f : polynomial K) : pb.equiv_adjoin_simple.symm (aeval pb.gen f) = aeval (adjoin_simple.gen K pb.gen) f := by rw [equiv_adjoin_simple, equiv_symm, equiv_aeval, adjoin.power_basis.gen_eq] @[simp] lemma equiv_adjoin_simple_symm_gen (pb : power_basis K L) : pb.equiv_adjoin_simple.symm pb.gen = (adjoin_simple.gen K pb.gen) := by rw [equiv_adjoin_simple, equiv_symm, equiv_gen, adjoin.power_basis.gen_eq] end power_basis end power_basis
d4d9b2e4c84820ce5e16f4213ee350f19fa219ec
90edd5cdcf93124fe15627f7304069fdce3442dd
/src/Lean/Aesop/RuleBuilder.lean
201f2621726fddad67663fb51cd86023bd06ca00
[ "Apache-2.0" ]
permissive
JLimperg/lean4-aesop
8a9d9cd3ee484a8e67fda2dd9822d76708098712
5c4b9a3e05c32f69a4357c3047c274f4b94f9c71
refs/heads/master
1,689,415,944,104
1,627,383,284,000
1,627,383,284,000
377,536,770
0
0
null
null
null
null
UTF-8
Lean
false
false
4,747
lean
/- Copyright (c) 2021 Jannis Limperg. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jannis Limperg -/ import Lean.Aesop.Rule import Lean.Aesop.RuleTac open Lean.Meta namespace Lean.Aesop structure RegularRuleBuilderResult where builderName : Name tac : RuleTac indexingMode : IndexingMode deriving Inhabited inductive NormRuleBuilderResult | regular (r : RegularRuleBuilderResult) | simpEntries (es : Array SimpEntry) deriving Inhabited inductive RuleIdent | const (decl : Name) | fvar (userName : Name) deriving Inhabited namespace RuleIdent instance : ToFormat RuleIdent where format | const decl => format decl | fvar userName => format userName protected def type : RuleIdent → MetaM Expr | const c => return (← getConstInfo c).type | fvar userName => return (← getLocalDeclFromUserName userName).type protected def ruleName : RuleIdent → Name | const c => `global ++ c | fvar userName => `local ++ userName protected def ofName (n : Name) : MetaM RuleIdent := do try let _ ← getLocalDeclFromUserName n pure $ fvar n catch _ => pure $ const n end RuleIdent abbrev RuleBuilder α := RuleIdent → MetaM α namespace RuleBuilder def normSimpUnfold : RuleBuilder NormRuleBuilderResult | RuleIdent.const decl => do let info ← getConstInfo decl unless info.hasValue do throwError "aesop: expected {decl} to be a definition to unfold" return NormRuleBuilderResult.simpEntries #[SimpEntry.toUnfold decl] | RuleIdent.fvar _ => throwError "aesop: local hypotheses cannot be added as simp lemmas" def normSimpLemmas : RuleBuilder NormRuleBuilderResult | RuleIdent.const decl => do let info ← getConstInfo decl unless (← isProp info.type) do throwError "aesop: tried to add {decl} as a simp lemma, but it is not a proposition" let simpLemmas ← mkSimpLemmasFromConst decl (post := true) (prio := 0) -- TODO I don't really know what the `post` and `prio` above mean. return NormRuleBuilderResult.simpEntries $ simpLemmas.map SimpEntry.lemma | RuleIdent.fvar _ => do throwError "aesop: local hypotheses cannot be added as simp lemmas" def applyIndexingMode (type : Expr) : MetaM IndexingMode := do let savedState ← saveState let path ← try let (_, _, conclusion) ← forallMetaTelescope type DiscrTree.mkPath conclusion finally restoreState savedState -- We use a meta telescope because `DiscrTree.mkPath` ignores metas (they -- turn into `Key.star`) but not fvars. return IndexingMode.indexTarget path def apply : RuleBuilder RegularRuleBuilderResult := λ ruleIdent => do let type := (← ruleIdent.type) let tac ← match ruleIdent with | RuleIdent.const decl => RuleTacBuilder.apply decl | RuleIdent.fvar userName => RuleTacBuilder.applyFVar userName return { builderName := `apply tac := tac indexingMode := (← applyIndexingMode type) } def tactic : RuleBuilder RegularRuleBuilderResult | RuleIdent.const decl => return { builderName := `tactic tac := (← RuleTacBuilder.tactic decl) indexingMode := IndexingMode.unindexed } | RuleIdent.fvar _ => throwError "aesop: tactic builder does not support local hypotheses." -- TODO In the default builders below, we should distinguish between fatal and -- nonfatal errors. E.g. if the `tactic` builder finds a declaration that is not -- of tactic type, this is a nonfatal error and we should continue with the next -- builder. But if the simp builder finds an equation that cannot be interpreted -- as a simp lemma for some reason, this is a fatal error. Continuing with the -- next builder is more confusing than anything because the user probably -- intended to add a simp lemma. def unsafeRuleDefault : RuleBuilder RegularRuleBuilderResult | i@(RuleIdent.const _) => tactic i <|> apply i <|> err i | i@(RuleIdent.fvar _) => apply i <|> err i where err i := throwError "aesop: Unable to interpret {i} as an unsafe rule." def safeRuleDefault : RuleBuilder RegularRuleBuilderResult | i@(RuleIdent.const _) => tactic i <|> apply i <|> err i | i@(RuleIdent.fvar _) => apply i <|> err i where err i := throwError "aesop: Unable to interpret {i} as a safe rule." def normRuleDefault : RuleBuilder NormRuleBuilderResult | i@(RuleIdent.const _) => (NormRuleBuilderResult.regular <$> tactic i) <|> normSimpLemmas i <|> (NormRuleBuilderResult.regular <$> apply i) <|> throwError "aesop: Unable to interpret {i} as a normalization rule." | i@(RuleIdent.fvar _) => throwError "aesop: Please specify a builder for norm rule {i}." end Lean.Aesop.RuleBuilder
5d9753610bd03b88077a53f33532079df2c7dc48
a4673261e60b025e2c8c825dfa4ab9108246c32e
/stage0/src/Init/Data/Array/Basic.lean
0aa19fa240a87247010ffec41fb5ebe918586170
[ "Apache-2.0" ]
permissive
jcommelin/lean4
c02dec0cc32c4bccab009285475f265f17d73228
2909313475588cc20ac0436e55548a4502050d0a
refs/heads/master
1,674,129,550,893
1,606,415,348,000
1,606,415,348,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
26,936
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Data.Nat.Basic import Init.Data.Fin.Basic import Init.Data.UInt import Init.Data.Repr import Init.Data.ToString.Basic import Init.Util universes u v w namespace Array variables {α : Type u} @[extern "lean_mk_array"] def mkArray {α : Type u} (n : Nat) (v : α) : Array α := { data := List.replicate n v } theorem sizeMkArrayEq (n : Nat) (v : α) : (mkArray n v).size = n := List.lengthReplicateEq .. instance : EmptyCollection (Array α) := ⟨Array.empty⟩ instance : Inhabited (Array α) := ⟨Array.empty⟩ def isEmpty (a : Array α) : Bool := a.size = 0 def singleton (v : α) : Array α := mkArray 1 v /- Low-level version of `fget` which is as fast as a C array read. `Fin` values are represented as tag pointers in the Lean runtime. Thus, `fget` may be slightly slower than `uget`. -/ @[extern "lean_array_uget"] def uget (a : @& Array α) (i : USize) (h : i.toNat < a.size) : α := a.get ⟨i.toNat, h⟩ def back [Inhabited α] (a : Array α) : α := a.get! (a.size - 1) def get? (a : Array α) (i : Nat) : Option α := if h : i < a.size then some (a.get ⟨i, h⟩) else none def getD (a : Array α) (i : Nat) (v₀ : α) : α := if h : i < a.size then a.get ⟨i, h⟩ else v₀ -- auxiliary declaration used in the equation compiler when pattern matching array literals. abbrev getLit {α : Type u} {n : Nat} (a : Array α) (i : Nat) (h₁ : a.size = n) (h₂ : i < n) : α := a.get ⟨i, h₁.symm ▸ h₂⟩ theorem sizeSetEq (a : Array α) (i : Fin a.size) (v : α) : (set a i v).size = a.size := List.lengthSetEq .. theorem sizePushEq (a : Array α) (v : α) : (push a v).size = a.size + 1 := List.lengthConcatEq .. /- Low-level version of `fset` which is as fast as a C array fset. `Fin` values are represented as tag pointers in the Lean runtime. Thus, `fset` may be slightly slower than `uset`. -/ @[extern "lean_array_uset"] def uset (a : Array α) (i : USize) (v : α) (h : i.toNat < a.size) : Array α := a.set ⟨i.toNat, h⟩ v @[extern "lean_array_fswap"] def swap (a : Array α) (i j : @& Fin a.size) : Array α := let v₁ := a.get i let v₂ := a.get j let a' := a.set i v₂ a'.set (sizeSetEq a i v₂ ▸ j) v₁ @[extern "lean_array_swap"] def swap! (a : Array α) (i j : @& Nat) : Array α := if h₁ : i < a.size then if h₂ : j < a.size then swap a ⟨i, h₁⟩ ⟨j, h₂⟩ else panic! "index out of bounds" else panic! "index out of bounds" @[inline] def swapAt (a : Array α) (i : Fin a.size) (v : α) : α × Array α := let e := a.get i let a := a.set i v (e, a) @[inline] def swapAt! (a : Array α) (i : Nat) (v : α) : α × Array α := if h : i < a.size then swapAt a ⟨i, h⟩ v else have Inhabited α from ⟨v⟩ panic! ("index " ++ toString i ++ " out of bounds") @[extern "lean_array_pop"] def pop (a : Array α) : Array α := { data := a.data.dropLast } def shrink (a : Array α) (n : Nat) : Array α := let rec loop | 0, a => a | n+1, a => loop n a.pop loop (a.size - n) a @[inline] def modifyM [Monad m] [Inhabited α] (a : Array α) (i : Nat) (f : α → m α) : m (Array α) := do if h : i < a.size then let idx : Fin a.size := ⟨i, h⟩ let v := a.get idx let a' := a.set idx arbitrary let v ← f v pure <| a'.set (sizeSetEq a .. ▸ idx) v else pure a @[inline] def modify [Inhabited α] (a : Array α) (i : Nat) (f : α → α) : Array α := Id.run <| a.modifyM i f @[inline] def modifyOp [Inhabited α] (self : Array α) (idx : Nat) (f : α → α) : Array α := self.modify idx f /- We claim this unsafe implementation is correct because an array cannot have more than `usizeSz` elements in our runtime. This kind of low level trick can be removed with a little bit of compiler support. For example, if the compiler simplifies `as.size < usizeSz` to true. -/ @[inline] unsafe def forInUnsafe {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (as : Array α) (b : β) (f : α → β → m (ForInStep β)) : m β := let sz := USize.ofNat as.size let rec @[specialize] loop (i : USize) (b : β) : m β := do if i < sz then let a := as.uget i lcProof match (← f a b) with | ForInStep.done b => pure b | ForInStep.yield b => loop (i+1) b else pure b loop 0 b -- Move? private theorem zeroLtOfLt : {a b : Nat} → a < b → 0 < b | 0, _, h => h | a+1, b, h => have a < b from Nat.ltTrans (Nat.ltSuccSelf _) h zeroLtOfLt this /- Reference implementation for `forIn` -/ @[implementedBy Array.forInUnsafe] def forIn {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (as : Array α) (b : β) (f : α → β → m (ForInStep β)) : m β := let rec loop (i : Nat) (h : i ≤ as.size) (b : β) : m β := do match i, h with | 0, _ => pure b | i+1, h => have h' : i < as.size from Nat.ltOfLtOfLe (Nat.ltSuccSelf i) h have as.size - 1 < as.size from Nat.subLt (zeroLtOfLt h') (decide! : 0 < 1) have as.size - 1 - i < as.size from Nat.ltOfLeOfLt (Nat.subLe (as.size - 1) i) this match (← f (as.get ⟨as.size - 1 - i, this⟩) b) with | ForInStep.done b => pure b | ForInStep.yield b => loop i (Nat.leOfLt h') b loop as.size (Nat.leRefl _) b /- See comment at forInUnsafe -/ @[inline] unsafe def foldlMUnsafe {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (f : β → α → m β) (init : β) (as : Array α) (start := 0) (stop := as.size) : m β := let rec @[specialize] fold (i : USize) (stop : USize) (b : β) : m β := do if i == stop then pure b else fold (i+1) stop (← f b (as.uget i lcProof)) if start < stop then if stop ≤ as.size then fold (USize.ofNat start) (USize.ofNat stop) init else pure init else pure init /- Reference implementation for `foldlM` -/ @[implementedBy foldlMUnsafe] def foldlM {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (f : β → α → m β) (init : β) (as : Array α) (start := 0) (stop := as.size) : m β := let fold (stop : Nat) (h : stop ≤ as.size) := let rec loop (i : Nat) (j : Nat) (b : β) : m β := do if hlt : j < stop then match i with | 0 => pure b | i'+1 => loop i' (j+1) (← f b (as.get ⟨j, Nat.ltOfLtOfLe hlt h⟩)) else pure b loop (stop - start) start init if h : stop ≤ as.size then fold stop h else fold as.size (Nat.leRefl _) /- See comment at forInUnsafe -/ @[inline] unsafe def foldrMUnsafe {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (f : α → β → m β) (init : β) (as : Array α) (start := as.size) (stop := 0) : m β := let rec @[specialize] fold (i : USize) (stop : USize) (b : β) : m β := do if i == stop then pure b else fold (i-1) stop (← f (as.uget (i-1) lcProof) b) if start ≤ as.size then if stop < start then fold (USize.ofNat start) (USize.ofNat stop) init else pure init else if stop < as.size then fold (USize.ofNat as.size) (USize.ofNat stop) init else pure init /- Reference implementation for `foldrM` -/ @[implementedBy foldrMUnsafe] def foldrM {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (f : α → β → m β) (init : β) (as : Array α) (start := as.size) (stop := 0) : m β := let rec fold (i : Nat) (h : i ≤ as.size) (b : β) : m β := do if i == stop then pure b else match i, h with | 0, _ => pure b | i+1, h => have i < as.size from Nat.ltOfLtOfLe (Nat.ltSuccSelf _) h fold i (Nat.leOfLt this) (← f (as.get ⟨i, this⟩) b) if h : start ≤ as.size then if stop < start then fold start h init else pure init else if stop < as.size then fold as.size (Nat.leRefl _) init else pure init /- See comment at forInUnsafe -/ @[inline] unsafe def mapMUnsafe {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (f : α → m β) (as : Array α) : m (Array β) := let sz := USize.ofNat as.size let rec @[specialize] map (i : USize) (r : Array NonScalar) : m (Array PNonScalar.{v}) := do if i < sz then let v := r.uget i lcProof let r := r.uset i arbitrary lcProof let vNew ← f (unsafeCast v) map (i+1) (r.uset i (unsafeCast vNew) lcProof) else pure (unsafeCast r) unsafeCast <| map 0 (unsafeCast as) /- Reference implementation for `mapM` -/ @[implementedBy mapMUnsafe] def mapM {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (f : α → m β) (as : Array α) : m (Array β) := as.foldlM (fun bs a => do let b ← f a; pure (bs.push b)) (mkEmpty as.size) @[inline] def mapIdxM {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (as : Array α) (f : Fin as.size → α → m β) : m (Array β) := let rec @[specialize] map (i : Nat) (j : Nat) (inv : i + j = as.size) (bs : Array β) : m (Array β) := do match i, inv with | 0, _ => pure bs | i+1, inv => have j < as.size by rw [← inv, Nat.addAssoc, Nat.addComm 1 j, Nat.addLeftComm]; apply Nat.leAddRight let idx : Fin as.size := ⟨j, this⟩ have i + (j + 1) = as.size by rw [← inv, Nat.addComm j 1, Nat.addAssoc]; exact rfl map i (j+1) this (bs.push (← f idx (as.get idx))) map as.size 0 rfl (mkEmpty as.size) @[inline] def findSomeM? {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (as : Array α) (f : α → m (Option β)) : m (Option β) := do for a in as do match (← f a) with | some b => return b | _ => pure ⟨⟩ return none @[inline] def findM? {α : Type} {m : Type → Type} [Monad m] (as : Array α) (p : α → m Bool) : m (Option α) := do for a in as do if (← p a) then return a return none @[inline] def findIdxM? [Monad m] (as : Array α) (p : α → m Bool) : m (Option Nat) := do let mut i := 0 for a in as do if (← p a) then return i i := i + 1 return none @[inline] unsafe def anyMUnsafe {α : Type u} {m : Type → Type w} [Monad m] (p : α → m Bool) (as : Array α) (start := 0) (stop := as.size) : m Bool := let rec @[specialize] any (i : USize) (stop : USize) : m Bool := do if i == stop then pure false else if (← p (as.uget i lcProof)) then pure true else any (i+1) stop if start < stop then if stop ≤ as.size then any (USize.ofNat start) (USize.ofNat stop) else pure false else pure false @[implementedBy anyMUnsafe] def anyM {α : Type u} {m : Type → Type w} [Monad m] (p : α → m Bool) (as : Array α) (start := 0) (stop := as.size) : m Bool := let any (stop : Nat) (h : stop ≤ as.size) := let rec loop (i : Nat) (j : Nat) : m Bool := do if hlt : j < stop then match i with | 0 => pure false | i'+1 => if (← p (as.get ⟨j, Nat.ltOfLtOfLe hlt h⟩)) then pure true else loop i' (j+1) else pure false loop (stop - start) start if h : stop ≤ as.size then any stop h else any as.size (Nat.leRefl _) @[inline] def allM {α : Type u} {m : Type → Type w} [Monad m] (p : α → m Bool) (as : Array α) (start := 0) (stop := as.size) : m Bool := return !(← as.anyM fun v => return !(← p v)) @[inline] def findSomeRevM? {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (as : Array α) (f : α → m (Option β)) : m (Option β) := let rec @[specialize] find : (i : Nat) → i ≤ as.size → m (Option β) | 0, h => pure none | i+1, h => do have i < as.size from Nat.ltOfLtOfLe (Nat.ltSuccSelf _) h let r ← f (as.get ⟨i, this⟩) match r with | some v => pure r | none => have i ≤ as.size from Nat.leOfLt this find i this find as.size (Nat.leRefl _) @[inline] def findRevM? {α : Type} {m : Type → Type w} [Monad m] (as : Array α) (p : α → m Bool) : m (Option α) := as.findSomeRevM? fun a => return if (← p a) then some a else none @[inline] def forM {α : Type u} {m : Type v → Type w} [Monad m] (f : α → m PUnit) (as : Array α) (start := 0) (stop := as.size) : m PUnit := as.foldlM (fun _ => f) ⟨⟩ start stop @[inline] def forRevM {α : Type u} {m : Type v → Type w} [Monad m] (f : α → m PUnit) (as : Array α) (start := as.size) (stop := 0) : m PUnit := as.foldrM (fun a _ => f a) ⟨⟩ start stop @[inline] def foldl {α : Type u} {β : Type v} (f : β → α → β) (init : β) (as : Array α) (start := 0) (stop := as.size) : β := Id.run <| as.foldlM f init start stop @[inline] def foldr {α : Type u} {β : Type v} (f : α → β → β) (init : β) (as : Array α) (start := as.size) (stop := 0) : β := Id.run <| as.foldrM f init start stop @[inline] def map {α : Type u} {β : Type v} (f : α → β) (as : Array α) : Array β := Id.run <| as.mapM f @[inline] def mapIdx {α : Type u} {β : Type v} (as : Array α) (f : Fin as.size → α → β) : Array β := Id.run <| as.mapIdxM f @[inline] def find? {α : Type} (as : Array α) (p : α → Bool) : Option α := Id.run <| as.findM? p @[inline] def findSome? {α : Type u} {β : Type v} (as : Array α) (f : α → Option β) : Option β := Id.run <| as.findSomeM? f @[inline] def findSome! {α : Type u} {β : Type v} [Inhabited β] (a : Array α) (f : α → Option β) : β := match findSome? a f with | some b => b | none => panic! "failed to find element" @[inline] def findSomeRev? {α : Type u} {β : Type v} (as : Array α) (f : α → Option β) : Option β := Id.run <| as.findSomeRevM? f @[inline] def findRev? {α : Type} (as : Array α) (p : α → Bool) : Option α := Id.run <| as.findRevM? p @[inline] def findIdx? {α : Type u} (as : Array α) (p : α → Bool) : Option Nat := let rec loop (i : Nat) (j : Nat) (inv : i + j = as.size) : Option Nat := if hlt : j < as.size then match i, inv with | 0, inv => by apply False.elim rw [Nat.zeroAdd] at inv rw [inv] at hlt exact absurd hlt (Nat.ltIrrefl _) | i+1, inv => if p (as.get ⟨j, hlt⟩) then some j else have i + (j+1) = as.size by rw [← inv, Nat.addComm j 1, Nat.addAssoc]; exact rfl loop i (j+1) this else none loop as.size 0 rfl def getIdx? [BEq α] (a : Array α) (v : α) : Option Nat := a.findIdx? fun a => a == v @[inline] def any (p : α → Bool) (as : Array α) (start := 0) (stop := as.size) : Bool := Id.run <| as.anyM p start stop @[inline] def all (p : α → Bool) (as : Array α) (start := 0) (stop := as.size) : Bool := Id.run <| as.allM p start stop def contains [BEq α] (as : Array α) (a : α) : Bool := as.any fun b => a == b def elem [BEq α] (a : α) (as : Array α) : Bool := as.contains a -- TODO(Leo): justify termination using wf-rec, and use `swap` partial def reverse (as : Array α) : Array α := let n := as.size let mid := n / 2 let rec rev (as : Array α) (i : Nat) := if i < mid then rev (as.swap! i (n - i - 1)) (i+1) else as rev as 0 @[inline] def getEvenElems (as : Array α) : Array α := (·.2) <| as.foldl (init := (true, Array.empty)) fun (even, r) a => if even then (false, r.push a) else (true, r) @[export lean_array_to_list] def toList (as : Array α) : List α := as.foldr List.cons [] instance [Repr α] : Repr (Array α) := ⟨fun a => "#" ++ repr a.toList⟩ instance [ToString α] : ToString (Array α) := ⟨fun a => "#" ++ toString a.toList⟩ protected def append (as : Array α) (bs : Array α) : Array α := bs.foldl (init := as) fun r v => r.push v instance : Append (Array α) := ⟨Array.append⟩ end Array @[inlineIfReduce] def List.toArrayAux : List α → Array α → Array α | [], r => r | a::as, r => toArrayAux as (r.push a) @[inlineIfReduce] def List.redLength : List α → Nat | [] => 0 | _::as => as.redLength + 1 @[inline, matchPattern, export lean_list_to_array] def List.toArray (as : List α) : Array α := as.toArrayAux (Array.mkEmpty as.redLength) export Array (mkArray) syntax "#[" sepBy(term, ", ") "]" : term macro_rules | `(#[ $elems* ]) => `(List.toArray [ $elems* ]) namespace Array -- TODO(Leo): cleanup @[specialize] partial def isEqvAux (a b : Array α) (hsz : a.size = b.size) (p : α → α → Bool) (i : Nat) : Bool := if h : i < a.size then let aidx : Fin a.size := ⟨i, h⟩; let bidx : Fin b.size := ⟨i, hsz ▸ h⟩; match p (a.get aidx) (b.get bidx) with | true => isEqvAux a b hsz p (i+1) | false => false else true @[inline] def isEqv (a b : Array α) (p : α → α → Bool) : Bool := if h : a.size = b.size then isEqvAux a b h p 0 else false instance [BEq α] : BEq (Array α) := ⟨fun a b => isEqv a b BEq.beq⟩ @[inline] def filter (p : α → Bool) (as : Array α) (start := 0) (stop := as.size) : Array α := as.foldl (init := #[]) (start := start) (stop := stop) fun r a => if p a then r.push a else r @[inline] def filterM [Monad m] (p : α → m Bool) (as : Array α) (start := 0) (stop := as.size) : m (Array α) := as.foldlM (init := #[]) (start := start) (stop := stop) fun r a => do if (← p a) then r.push a else r @[specialize] def filterMapM [Monad m] (f : α → m (Option β)) (as : Array α) (start := 0) (stop := as.size) : m (Array β) := as.foldlM (init := #[]) (start := start) (stop := stop) fun bs a => do match (← f a) with | some b => pure (bs.push b) | none => pure bs @[inline] def filterMap (f : α → Option β) (as : Array α) (start := 0) (stop := as.size) : Array β := Id.run <| as.filterMapM f (start := start) (stop := stop) @[specialize] def getMax? (as : Array α) (lt : α → α → Bool) : Option α := if h : 0 < as.size then let a0 := as.get ⟨0, h⟩ some <| as.foldl (init := a0) (start := 1) fun best a => if lt best a then a else best else none @[inline] def partition (p : α → Bool) (as : Array α) : Array α × Array α := do let mut bs := #[] let mut cs := #[] for a in as do if p a then bs := bs.push a else cs := cs.push a return (bs, cs) theorem ext (a b : Array α) (h₁ : a.size = b.size) (h₂ : (i : Nat) → (hi₁ : i < a.size) → (hi₂ : i < b.size) → a.get ⟨i, hi₁⟩ = b.get ⟨i, hi₂⟩) : a = b := by let rec extAux (a b : List α) (h₁ : a.length = b.length) (h₂ : (i : Nat) → (hi₁ : i < a.length) → (hi₂ : i < b.length) → a.get i hi₁ = b.get i hi₂) : a = b := by induction a generalizing b with | nil => cases b with | nil => rfl | cons b bs => rw [List.lengthConsEq] at h₁; injection h₁ | cons a as ih => cases b with | nil => rw [List.lengthConsEq] at h₁; injection h₁ | cons b bs => have hz₁ : 0 < (a::as).length by rw [List.lengthConsEq]; apply Nat.zeroLtSucc have hz₂ : 0 < (b::bs).length by rw [List.lengthConsEq]; apply Nat.zeroLtSucc have headEq : a = b from h₂ 0 hz₁ hz₂ have h₁' : as.length = bs.length by rw [List.lengthConsEq, List.lengthConsEq] at h₁; injection h₁; assumption have h₂' : (i : Nat) → (hi₁ : i < as.length) → (hi₂ : i < bs.length) → as.get i hi₁ = bs.get i hi₂ by intro i hi₁ hi₂ have hi₁' : i+1 < (a::as).length by rw [List.lengthConsEq]; apply Nat.succLtSucc; assumption have hi₂' : i+1 < (b::bs).length by rw [List.lengthConsEq]; apply Nat.succLtSucc; assumption have (a::as).get (i+1) hi₁' = (b::bs).get (i+1) hi₂' from h₂ (i+1) hi₁' hi₂' apply this have tailEq : as = bs from ih bs h₁' h₂' rw [headEq, tailEq] rfl cases a; cases b apply congrArg apply extAux assumption assumption theorem extLit {n : Nat} (a b : Array α) (hsz₁ : a.size = n) (hsz₂ : b.size = n) (h : (i : Nat) → (hi : i < n) → a.getLit i hsz₁ hi = b.getLit i hsz₂ hi) : a = b := Array.ext a b (hsz₁.trans hsz₂.symm) fun i hi₁ hi₂ => h i (hsz₁ ▸ hi₁) end Array -- CLEANUP the following code namespace Array partial def indexOfAux [BEq α] (a : Array α) (v : α) : Nat → Option (Fin a.size) | i => if h : i < a.size then let idx : Fin a.size := ⟨i, h⟩; if a.get idx == v then some idx else indexOfAux a v (i+1) else none def indexOf? [BEq α] (a : Array α) (v : α) : Option (Fin a.size) := indexOfAux a v 0 partial def eraseIdxAux : Nat → Array α → Array α | i, a => if h : i < a.size then let idx : Fin a.size := ⟨i, h⟩; let idx1 : Fin a.size := ⟨i - 1, Nat.ltOfLeOfLt (Nat.predLe i) h⟩; eraseIdxAux (i+1) (a.swap idx idx1) else a.pop def feraseIdx (a : Array α) (i : Fin a.size) : Array α := eraseIdxAux (i.val + 1) a def eraseIdx (a : Array α) (i : Nat) : Array α := if i < a.size then eraseIdxAux (i+1) a else a theorem sizeSwapEq (a : Array α) (i j : Fin a.size) : (a.swap i j).size = a.size := by show ((a.set i (a.get j)).set (sizeSetEq a i _ ▸ j) (a.get i)).size = a.size rw [sizeSetEq, sizeSetEq] rfl theorem sizePopEq (a : Array α) : a.pop.size = a.size - 1 := List.lengthDropLast .. section /- Instance for justifying `partial` declaration. We should be able to delete it as soon as we restore support for well-founded recursion. -/ instance eraseIdxSzAuxInstance (a : Array α) : Inhabited { r : Array α // r.size = a.size - 1 } := ⟨⟨a.pop, sizePopEq a⟩⟩ partial def eraseIdxSzAux (a : Array α) : ∀ (i : Nat) (r : Array α), r.size = a.size → { r : Array α // r.size = a.size - 1 } | i, r, heq => if h : i < r.size then let idx : Fin r.size := ⟨i, h⟩; let idx1 : Fin r.size := ⟨i - 1, Nat.ltOfLeOfLt (Nat.predLe i) h⟩; eraseIdxSzAux a (i+1) (r.swap idx idx1) ((sizeSwapEq r idx idx1).trans heq) else ⟨r.pop, (sizePopEq r).trans (heq ▸ rfl)⟩ end def eraseIdx' (a : Array α) (i : Fin a.size) : { r : Array α // r.size = a.size - 1 } := eraseIdxSzAux a (i.val + 1) a rfl def erase [BEq α] (as : Array α) (a : α) : Array α := match as.indexOf? a with | none => as | some i => as.feraseIdx i partial def insertAtAux (i : Nat) : Array α → Nat → Array α | as, j => if i == j then as else let as := as.swap! (j-1) j; insertAtAux i as (j-1) /-- Insert element `a` at position `i`. Pre: `i < as.size` -/ def insertAt (as : Array α) (i : Nat) (a : α) : Array α := if i > as.size then panic! "invalid index" else let as := as.push a; as.insertAtAux i as.size def toListLitAux (a : Array α) (n : Nat) (hsz : a.size = n) : ∀ (i : Nat), i ≤ a.size → List α → List α | 0, hi, acc => acc | (i+1), hi, acc => toListLitAux a n hsz i (Nat.leOfSuccLe hi) (a.getLit i hsz (Nat.ltOfLtOfEq (Nat.ltOfLtOfLe (Nat.ltSuccSelf i) hi) hsz) :: acc) def toArrayLit (a : Array α) (n : Nat) (hsz : a.size = n) : Array α := List.toArray <| toListLitAux a n hsz n (hsz ▸ Nat.leRefl _) [] theorem toArrayLitEq (a : Array α) (n : Nat) (hsz : a.size = n) : a = toArrayLit a n hsz := -- TODO: this is painful to prove without proper automation sorry /- First, we need to prove ∀ i j acc, i ≤ a.size → (toListLitAux a n hsz (i+1) hi acc).index j = if j < i then a.getLit j hsz _ else acc.index (j - i) by induction Base case is trivial (j : Nat) (acc : List α) (hi : 0 ≤ a.size) |- (toListLitAux a n hsz 0 hi acc).index j = if j < 0 then a.getLit j hsz _ else acc.index (j - 0) ... |- acc.index j = acc.index j Induction (j : Nat) (acc : List α) (hi : i+1 ≤ a.size) |- (toListLitAux a n hsz (i+1) hi acc).index j = if j < i + 1 then a.getLit j hsz _ else acc.index (j - (i + 1)) ... |- (toListLitAux a n hsz i hi' (a.getLit i hsz _ :: acc)).index j = if j < i + 1 then a.getLit j hsz _ else acc.index (j - (i + 1)) * by def ... |- if j < i then a.getLit j hsz _ else (a.getLit i hsz _ :: acc).index (j-i) * by induction hypothesis = if j < i + 1 then a.getLit j hsz _ else acc.index (j - (i + 1)) If j < i, then both are a.getLit j hsz _ If j = i, then lhs reduces else-branch to (a.getLit i hsz _) and rhs is then-brachn (a.getLit i hsz _) If j >= i + 1, we use - j - i >= 1 > 0 - (a::as).index k = as.index (k-1) If k > 0 - j - (i + 1) = (j - i) - 1 Then lhs = (a.getLit i hsz _ :: acc).index (j-i) = acc.index (j-i-1) = acc.index (j-(i+1)) = rhs With this proof, we have ∀ j, j < n → (toListLitAux a n hsz n _ []).index j = a.getLit j hsz _ We also need - (toListLitAux a n hsz n _ []).length = n - j < n -> (List.toArray as).getLit j _ _ = as.index j Then using Array.extLit, we have that a = List.toArray <| toListLitAux a n hsz n _ [] -/ partial def isPrefixOfAux [BEq α] (as bs : Array α) (hle : as.size ≤ bs.size) : Nat → Bool | i => if h : i < as.size then let a := as.get ⟨i, h⟩; let b := bs.get ⟨i, Nat.ltOfLtOfLe h hle⟩; if a == b then isPrefixOfAux as bs hle (i+1) else false else true /- Return true iff `as` is a prefix of `bs` -/ def isPrefixOf [BEq α] (as bs : Array α) : Bool := if h : as.size ≤ bs.size then isPrefixOfAux as bs h 0 else false private def allDiffAuxAux [BEq α] (as : Array α) (a : α) : forall (i : Nat), i < as.size → Bool | 0, h => true | i+1, h => have i < as.size from Nat.ltTrans (Nat.ltSuccSelf _) h; a != as.get ⟨i, this⟩ && allDiffAuxAux as a i this private partial def allDiffAux [BEq α] (as : Array α) : Nat → Bool | i => if h : i < as.size then allDiffAuxAux as (as.get ⟨i, h⟩) i h && allDiffAux as (i+1) else true def allDiff [BEq α] (as : Array α) : Bool := allDiffAux as 0 @[specialize] partial def zipWithAux (f : α → β → γ) (as : Array α) (bs : Array β) : Nat → Array γ → Array γ | i, cs => if h : i < as.size then let a := as.get ⟨i, h⟩; if h : i < bs.size then let b := bs.get ⟨i, h⟩; zipWithAux f as bs (i+1) <| cs.push <| f a b else cs else cs @[inline] def zipWith (as : Array α) (bs : Array β) (f : α → β → γ) : Array γ := zipWithAux f as bs 0 #[] def zip (as : Array α) (bs : Array β) : Array (α × β) := zipWith as bs Prod.mk end Array
90e87977496e7b77949fd50bbe33bbb88586cb4f
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/category_theory/limits/shapes/strict_initial.lean
8e78962313e962bb2ced535bc6b5e9b026894b46
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
8,303
lean
/- Copyright (c) 2021 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.limits.shapes.terminal import category_theory.limits.shapes.binary_products import category_theory.epi_mono /-! # Strict initial objects This file sets up the basic theory of strict initial objects: initial objects where every morphism to it is an isomorphism. This generalises a property of the empty set in the category of sets: namely that the only function to the empty set is from itself. We say `C` has strict initial objects if every initial object is strict, ie given any morphism `f : A ⟶ I` where `I` is initial, then `f` is an isomorphism. Strictly speaking, this says that *any* initial object must be strict, rather than that strict initial objects exist, which turns out to be a more useful notion to formalise. If the binary product of `X` with a strict initial object exists, it is also initial. To show a category `C` with an initial object has strict initial objects, the most convenient way is to show any morphism to the (chosen) initial object is an isomorphism and use `has_strict_initial_objects_of_initial_is_strict`. The dual notion (strict terminal objects) occurs much less frequently in practice so is ignored. ## TODO * Construct examples of this: `Type*`, `Top`, `Groupoid`, simplicial types, posets. * Construct the bottom element of the subobject lattice given strict initials. * Show cartesian closed categories have strict initials ## References * https://ncatlab.org/nlab/show/strict+initial+object -/ universes v u namespace category_theory namespace limits open category variables (C : Type u) [category.{v} C] section strict_initial /-- We say `C` has strict initial objects if every initial object is strict, ie given any morphism `f : A ⟶ I` where `I` is initial, then `f` is an isomorphism. Strictly speaking, this says that *any* initial object must be strict, rather than that strict initial objects exist. -/ class has_strict_initial_objects : Prop := (out : ∀ {I A : C} (f : A ⟶ I), is_initial I → is_iso f) variables {C} section variables [has_strict_initial_objects C] {I : C} lemma is_initial.is_iso_to (hI : is_initial I) {A : C} (f : A ⟶ I) : is_iso f := has_strict_initial_objects.out f hI lemma is_initial.strict_hom_ext (hI : is_initial I) {A : C} (f g : A ⟶ I) : f = g := begin haveI := hI.is_iso_to f, haveI := hI.is_iso_to g, exact eq_of_inv_eq_inv (hI.hom_ext (inv f) (inv g)), end lemma is_initial.subsingleton_to (hI : is_initial I) {A : C} : subsingleton (A ⟶ I) := ⟨hI.strict_hom_ext⟩ @[priority 100] instance initial_mono_of_strict_initial_objects : initial_mono_class C := { is_initial_mono_from := λ I A hI, { right_cancellation := λ B g h i, hI.strict_hom_ext _ _ } } /-- If `I` is initial, then `X ⨯ I` is isomorphic to it. -/ @[simps hom] noncomputable def mul_is_initial (X : C) [has_binary_product X I] (hI : is_initial I) : X ⨯ I ≅ I := @@as_iso _ prod.snd (hI.is_iso_to _) @[simp] lemma mul_is_initial_inv (X : C) [has_binary_product X I] (hI : is_initial I) : (mul_is_initial X hI).inv = hI.to _ := hI.hom_ext _ _ /-- If `I` is initial, then `I ⨯ X` is isomorphic to it. -/ @[simps hom] noncomputable def is_initial_mul (X : C) [has_binary_product I X] (hI : is_initial I) : I ⨯ X ≅ I := @@as_iso _ prod.fst (hI.is_iso_to _) @[simp] lemma is_initial_mul_inv (X : C) [has_binary_product I X] (hI : is_initial I) : (is_initial_mul X hI).inv = hI.to _ := hI.hom_ext _ _ variable [has_initial C] instance initial_is_iso_to {A : C} (f : A ⟶ ⊥_ C) : is_iso f := initial_is_initial.is_iso_to _ @[ext] lemma initial.hom_ext {A : C} (f g : A ⟶ ⊥_ C) : f = g := initial_is_initial.strict_hom_ext _ _ lemma initial.subsingleton_to {A : C} : subsingleton (A ⟶ ⊥_ C) := initial_is_initial.subsingleton_to /-- The product of `X` with an initial object in a category with strict initial objects is itself initial. This is the generalisation of the fact that `X × empty ≃ empty` for types (or `n * 0 = 0`). -/ @[simps hom] noncomputable def mul_initial (X : C) [has_binary_product X ⊥_ C] : X ⨯ ⊥_ C ≅ ⊥_ C := mul_is_initial _ initial_is_initial @[simp] lemma mul_initial_inv (X : C) [has_binary_product X ⊥_ C] : (mul_initial X).inv = initial.to _ := subsingleton.elim _ _ /-- The product of `X` with an initial object in a category with strict initial objects is itself initial. This is the generalisation of the fact that `empty × X ≃ empty` for types (or `0 * n = 0`). -/ @[simps hom] noncomputable def initial_mul (X : C) [has_binary_product (⊥_ C) X] : ⊥_ C ⨯ X ≅ ⊥_ C := is_initial_mul _ initial_is_initial @[simp] lemma initial_mul_inv (X : C) [has_binary_product (⊥_ C) X] : (initial_mul X).inv = initial.to _ := subsingleton.elim _ _ end /-- If `C` has an initial object such that every morphism *to* it is an isomorphism, then `C` has strict initial objects. -/ lemma has_strict_initial_objects_of_initial_is_strict [has_initial C] (h : ∀ A (f : A ⟶ ⊥_ C), is_iso f) : has_strict_initial_objects C := { out := λ I A f hI, begin haveI := h A (f ≫ hI.to _), exact ⟨⟨hI.to _ ≫ inv (f ≫ hI.to ⊥_ C), by rw [←assoc, is_iso.hom_inv_id], hI.hom_ext _ _⟩⟩, end } end strict_initial section strict_terminal /-- We say `C` has strict terminal objects if every terminal object is strict, ie given any morphism `f : I ⟶ A` where `I` is terminal, then `f` is an isomorphism. Strictly speaking, this says that *any* terminal object must be strict, rather than that strict terminal objects exist. -/ class has_strict_terminal_objects : Prop := (out : ∀ {I A : C} (f : I ⟶ A), is_terminal I → is_iso f) variables {C} section variables [has_strict_terminal_objects C] {I : C} lemma is_terminal.is_iso_from (hI : is_terminal I) {A : C} (f : I ⟶ A) : is_iso f := has_strict_terminal_objects.out f hI lemma is_terminal.strict_hom_ext (hI : is_terminal I) {A : C} (f g : I ⟶ A) : f = g := begin haveI := hI.is_iso_from f, haveI := hI.is_iso_from g, exact eq_of_inv_eq_inv (hI.hom_ext (inv f) (inv g)), end lemma is_terminal.subsingleton_to (hI : is_terminal I) {A : C} : subsingleton (I ⟶ A) := ⟨hI.strict_hom_ext⟩ variables {J : Type v} [small_category J] /-- If all but one object in a diagram is strict terminal, the the limit is isomorphic to the said object via `limit.π`. -/ lemma limit_π_is_iso_of_is_strict_terminal (F : J ⥤ C) [has_limit F] (i : J) (H : ∀ j ≠ i, is_terminal (F.obj j)) [subsingleton (i ⟶ i)] : is_iso (limit.π F i) := begin classical, refine ⟨⟨limit.lift _ ⟨_,⟨_,_⟩⟩,_,_⟩⟩, { exact λ j, dite (j = i) (λ h, eq_to_hom (by { cases h, refl })) (λ h, (H _ h).from _) }, { intros j k f, split_ifs, { cases h, cases h_1, have : f = 𝟙 _ := subsingleton.elim _ _, subst this, simpa }, { cases h, erw category.comp_id, haveI : is_iso (F.map f) := (H _ h_1).is_iso_from _, rw ← is_iso.comp_inv_eq, apply (H _ h_1).hom_ext }, { cases h_1, apply (H _ h).hom_ext }, { apply (H _ h).hom_ext } }, { ext, rw [assoc, limit.lift_π], dsimp only, split_ifs, { cases h, rw [id_comp, eq_to_hom_refl], exact comp_id _ }, { apply (H _ h).hom_ext } }, { rw limit.lift_π, simpa } end variable [has_terminal C] instance terminal_is_iso_from {A : C} (f : ⊤_ C ⟶ A) : is_iso f := terminal_is_terminal.is_iso_from _ @[ext] lemma terminal.hom_ext {A : C} (f g : ⊤_ C ⟶ A) : f = g := terminal_is_terminal.strict_hom_ext _ _ lemma terminal.subsingleton_to {A : C} : subsingleton (⊤_ C ⟶ A) := terminal_is_terminal.subsingleton_to end /-- If `C` has an object such that every morphism *from* it is an isomorphism, then `C` has strict terminal objects. -/ lemma has_strict_terminal_objects_of_terminal_is_strict (I : C) (h : ∀ A (f : I ⟶ A), is_iso f) : has_strict_terminal_objects C := { out := λ I' A f hI', begin haveI := h A (hI'.from _ ≫ f), exact ⟨⟨inv (hI'.from I ≫ f) ≫ hI'.from I, hI'.hom_ext _ _, by rw [assoc, is_iso.inv_hom_id]⟩⟩, end } end strict_terminal end limits end category_theory
c2fe9200a394920a2098573f23439f3b3fd9d777
12ba6fe891179eac82e287c24c8812a046221563
/src/to_mathlib.lean
8acbdc859d37e9139baba74b33c817943f68ca8a
[]
no_license
b-mehta/combinatorics
eca586b4cb7b5e1fd22ec3288f5a2cb4ed6ce4dd
2a8b30709d35f124f3fc9baa5652d231389e9f63
refs/heads/master
1,653,708,057,336
1,626,885,184,000
1,626,885,184,000
228,850,404
19
0
null
null
null
null
UTF-8
Lean
false
false
10,076
lean
/- A collection of useful lemmas that might be useful in mathlib, approximately sorted by where they belong -/ import data.finset import algebra.big_operators import tactic open finset section finset variables {α : Type*} [decidable_eq α] -- lemma sdiff_inter_inter (A B : finset α) : disjoint (A \ B) (A ∩ B) := -- disjoint_sdiff_inter _ _ -- @[simp] lemma sdiff_empty (s : finset α) : s \ ∅ = s := -- empty_union s -- @[simp] lemma sdiff_self (s : finset α) : s \ s = ∅ := -- by simp only [ext, not_mem_empty, iff_self, mem_sdiff, and_not_self, forall_true_iff] -- lemma inter_union_self (s t : finset α) : s ∩ (t ∪ s) = s := -- by simp only [ext, mem_inter, mem_union]; tauto -- lemma union_sdiff_self (s t : finset α) : (s ∪ t) \ t = s \ t := -- by simp only [ext, mem_union, mem_sdiff]; tauto -- lemma singleton_union_eq_insert (a : α) (s : finset α) : finset.singleton a ∪ s = insert a s := -- rfl -- lemma sdiff_singleton_eq_erase (a : α) (s : finset α) : s \ finset.singleton a = erase s a := -- begin ext, rw [mem_erase, mem_sdiff, mem_singleton], tauto end -- lemma union_sdiff_distrib_right (s₁ s₂ t : finset α) : (s₁ ∪ s₂) \ t = s₁ \ t ∪ s₂ \ t := -- by simp only [ext, mem_sdiff, mem_union]; tauto -- lemma sdiff_union_distrib_left (s t₁ t₂ : finset α) : s \ (t₁ ∪ t₂) = (s \ t₁) ∩ (s \ t₂) := -- by simp only [ext, mem_union, mem_sdiff, mem_inter]; tauto -- lemma union_eq_left_of_subset {s t : finset α} (h : t ⊆ s) : s ∪ t = s := lattice.sup_of_le_left h -- lemma not_mem_sdiff_of_mem_right {a : α} {s t : finset α} (h : a ∈ t) : a ∉ s \ t := -- begin simp only [mem_sdiff, h, not_true, not_false_iff, and_false] end -- lemma sdiff_sdiff_self_left (s t : finset α) : s \ (s \ t) = s ∩ t := -- by simp only [ext, mem_sdiff, mem_inter]; tauto -- lemma union_empty_iff (A B : finset α) : A ∪ B = ∅ ↔ A = ∅ ∧ B = ∅ := lattice.sup_eq_bot_iff -- lemma sdiff_eq_self_of_disjoint {s t : finset α} : disjoint s t → s \ t = s := -- by simp [ext, disjoint_left]; tauto -- lemma sdiff_eq_self_iff_disjoint {s t : finset α} : s \ t = s ↔ disjoint s t := -- ⟨λ p, p ▸ sdiff_disjoint, sdiff_eq_self_of_disjoint⟩ -- lemma disjoint_self_iff_empty (s : finset α) : disjoint s s ↔ s = ∅ := -- disjoint_self -- lemma sdiff_subset_left (s t : finset α) : s \ t ⊆ s := -- by simp [subset_iff]; tauto -- -- TODO: This could be an iff -- lemma sdiff_partially_injective {s t₁ t₂ : finset α} : s \ t₁ = s \ t₂ → s ∩ t₁ = s ∩ t₂ := -- by simp [ext]; intros b c; replace b := b c; split; tauto -- instance decidable_disjoint (U V : finset α) : decidable (disjoint U V) := -- decidable_of_decidable_of_iff (by apply_instance) disjoint_iff_inter_eq_empty.symm -- -- There's a similar thing in data.finset already, but this one is sometimes more practical -- lemma min_ne_max_of_card {α : Type*} [decidable_linear_order α] {U : finset α} {h₁ : U ≠ ∅} -- (h₂ : 1 < card U) : min' U h₁ ≠ max' U h₁ := -- begin -- intro, apply not_le_of_lt h₂ (le_of_eq _), rw card_eq_one, -- use max' U h₁, rw eq_singleton_iff_unique_mem, -- exact ⟨max'_mem _ _, λ t Ht, le_antisymm (le_max' U h₁ t Ht) (a ▸ min'_le U h₁ t Ht)⟩ -- end -- /-- -- Given a set A and a set B inside it, we can shrink A to any appropriate size, and keep B -- inside it. -- -/ -- lemma exists_intermediate_set {A B : finset α} (i : ℕ) -- (h₁ : card A ≥ i + card B) (h₂ : B ⊆ A) : -- ∃ (C : finset α), B ⊆ C ∧ C ⊆ A ∧ card C = i + card B := -- begin -- rcases nat.le.dest h₁ with ⟨k, _⟩, clear h₁, revert A, -- induction k with k ih, -- intros A BsubA cards, exact ⟨A, BsubA, subset.refl _, cards.symm⟩, -- intros A BsubA cards, -- have: ∃ i, i ∈ A \ B, -- rw [exists_mem_iff_ne_empty, ← ne, ← card_pos, card_sdiff BsubA, -- ← cards, nat.add_right_comm, nat.add_sub_cancel, nat.add_succ], -- apply nat.succ_pos, -- rcases this with ⟨a, ha⟩, -- set A' := erase A a, -- have z: i + card B + k = card A', -- rw [card_erase_of_mem, ← cards, nat.add_succ, nat.pred_succ], -- rw mem_sdiff at ha, exact ha.1, -- rcases ih _ z with ⟨B', hB', B'subA', cards⟩, -- refine ⟨B', hB', trans B'subA' (erase_subset _ _), cards⟩, -- rintros t th, apply mem_erase_of_ne_of_mem _ (BsubA th), rintro rfl, -- rw mem_sdiff at ha, tauto -- end -- /-- We can shrink A to any smaller size. -/ -- lemma exists_smaller_set (A : finset α) (i : ℕ) (h₁ : card A ≥ i) : -- ∃ (B : finset α), B ⊆ A ∧ card B = i := -- begin -- rcases exists_intermediate_set i _ (empty_subset A) with ⟨B, _, x₁, x₂⟩, -- simp at x₂, exact ⟨B, x₁, x₂⟩, simpa, -- end -- /-- A flipped version of exists_min from data.finset. -/ -- lemma exists_max {α β : Type*} [decidable_linear_order α] (s : finset β) (f : β → α) -- (h : s ≠ ∅) : ∃ x ∈ s, ∀ x' ∈ s, f x' ≤ f x := -- begin -- have : s.image f ≠ ∅, -- rwa [ne, image_eq_empty, ← ne.def], -- cases max_of_ne_empty this with y hy, -- rcases mem_image.mp (mem_of_max hy) with ⟨x, hx, rfl⟩, -- exact ⟨x, hx, λ x' hx', le_max_of_mem (mem_image_of_mem f hx') hy⟩, -- end -- /-- An alternate version of the above with different typeclass requirements. -/ -- lemma exists_max' {α β : Type*} [linear_order α] [decidable_eq β] (s : finset β) (f : β → α) : -- s ≠ ∅ → ∃ x ∈ s, ∀ y ∈ s, f y ≤ f x := -- begin -- letI := classical.DLO α, -- apply finset.induction_on s, -- intro a, exfalso, apply a, refl, -- intros i B hi ih _, by_cases (B = ∅), rw h, refine ⟨i, mem_insert_self _ _, λ t th, _⟩, -- rw [mem_insert] at th, rw or.resolve_right th (not_mem_empty t), -- specialize ih h, rcases ih with ⟨k, kB, q⟩, -- apply or.elim (le_total (f i) (f k)), -- intro ik, refine ⟨k, mem_insert_of_mem kB, λ t th, _⟩, -- rw mem_insert at th, cases th, rwa th, apply q _ th, -- intro ki, refine ⟨i, mem_insert_self _ _, λ t th, _⟩, -- rw mem_insert at th, cases th, rwa th, apply trans (q _ th) ki, -- end end finset -- lemma bind_sub_bind_of_sub_left {α β : Type*} [decidable_eq α] {s₁ s₂ : finset β} -- (t : β → finset α) (h : s₁ ⊆ s₂) : s₁.bind t ⊆ s₂.bind t := -- by intro x; simp; intros y hy hty; refine ⟨y, h hy, hty⟩ section big_operators -- lemma sum_div {α β : Type*} [division_ring β] {s : finset α} {f : α → β} {b : β} : -- s.sum f / b = s.sum (λx, f x / b) := -- calc s.sum f / b = s.sum (λ x, f x * (1 / b)) : by rw [div_eq_mul_one_div, sum_mul] -- ... = s.sum (λ x, f x / b) : by congr; ext; rw ← div_eq_mul_one_div (f x) b -- lemma sum_const_nat {α : Type*} {m : ℕ} {f : α → ℕ} {s : finset α} (h₁ : ∀x ∈ s, f x = m) : -- s.sum f = card s * m := -- begin -- rw [← nat.smul_eq_mul, ← sum_const], -- apply sum_congr rfl h₁ -- end -- lemma sum_lt_sum {α β : Type*} {s : finset α} {f g : α → β} [decidable_eq α] [ordered_cancel_comm_monoid β] : -- s ≠ ∅ → (∀ x ∈ s, f x < g x) → s.sum f < s.sum g := -- begin -- apply finset.induction_on s, intro, exfalso, apply a, refl, -- intros x s not_mem ih _ assump, simp only [sum_insert not_mem], -- apply lt_of_lt_of_le, -- rw add_lt_add_iff_right (s.sum f), -- exact assump x (mem_insert_self _ _), -- rw add_le_add_iff_left, -- by_cases (s = ∅), simp only [h, sum_empty], -- exact (le_of_lt $ ih h $ λ t, assump t ∘ mem_insert_of_mem), -- end -- lemma sum_flip {α : Type*} [add_comm_monoid α] {n : ℕ} (f : ℕ → α) : sum (range (n+1)) (λ r, f (n - r)) = sum (range (n+1)) (λ r, f r) := -- begin -- induction n with n ih, -- rw [sum_range_one, sum_range_one], -- rw sum_range_succ', -- rw sum_range_succ _ (nat.succ n), -- simp [ih], -- end end big_operators -- section nat -- lemma choose_symm' {n a b : ℕ} (h : n = a + b) : nat.choose n a = nat.choose n b := -- begin -- have: a = n - b, rw h, rw nat.add_sub_cancel, -- rw [this, nat.choose_symm], apply nat.le.intro, symmetry, rwa add_comm -- end -- end nat -- section natchoose -- lemma dominate_choose_lt {r n : ℕ} (h : r < n/2) : -- nat.choose n r ≤ nat.choose n (r+1) := -- begin -- refine le_of_mul_le_mul_right _ (nat.lt_sub_left_of_add_lt (lt_of_lt_of_le h (nat.div_le_self n 2))), -- rw ← nat.choose_succ_right_eq, -- apply nat.mul_le_mul_left, -- rw [← nat.lt_iff_add_one_le, nat.lt_sub_left_iff_add_lt, ← mul_two], -- exact lt_of_lt_of_le (mul_lt_mul_of_pos_right h zero_lt_two) (nat.div_mul_le_self n 2), -- end -- lemma dominate_choose_lt' {n r : ℕ} (hr : r ≤ n/2) : nat.choose n r ≤ nat.choose n (n/2) := -- begin -- refine @nat.decreasing_induction (λ k, k ≤ n/2 → nat.choose n k ≤ nat.choose n (n/2)) (λ m k a, _) r (n/2) hr (λ _, by refl) hr, -- rcases eq_or_lt_of_le a with rfl | h, refl, -- exact trans (dominate_choose_lt h) (k h) -- end -- lemma dominate_choose {r n : ℕ} : nat.choose n r ≤ nat.choose n (n/2) := -- begin -- cases le_or_gt r n with b b, -- cases le_or_lt r (n/2) with a h, -- apply dominate_choose_lt' a, -- rw ← nat.choose_symm b, -- apply dominate_choose_lt', -- rw [nat.div_lt_iff_lt_mul' zero_lt_two] at h, -- rw [nat.le_div_iff_mul_le' zero_lt_two, nat.mul_sub_right_distrib, nat.sub_le_iff, mul_two, nat.add_sub_cancel], -- exact le_of_lt h, -- rw nat.choose_eq_zero_of_lt b, -- apply zero_le -- end -- end natchoose lemma div_nonneg_of_nonneg_of_nonneg {α : Type*} [linear_ordered_field α] {a b : α} : 0 ≤ a → 0 ≤ b → 0 ≤ a / b := div_nonneg
7c6a9066c7062c7800bbec5411162af1eb8a0af2
82e44445c70db0f03e30d7be725775f122d72f3e
/src/analysis/convex/basic.lean
eef7c1989cbcadd07821120e0e8a399f5af89e7b
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
69,074
lean
/- Copyright (c) 2019 Alexander Bentkamp. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp, Yury Kudriashov -/ import data.complex.module import data.set.intervals.image_preimage import linear_algebra.affine_space.affine_map import order.closure /-! # Convex sets and functions on real vector spaces In a real vector space, we define the following objects and properties. * `segment x y` is the closed segment joining `x` and `y`. * `open_segment x y` is the open segment joining `x` and `y`. * A set `s` is `convex` if for any two points `x y ∈ s` it includes `segment x y`; * A function `f : E → β` is `convex_on` a set `s` if `s` is itself a convex set, and for any two points `x y ∈ s` the segment joining `(x, f x)` to `(y, f y)` is (non-strictly) above the graph of `f`; equivalently, `convex_on f s` means that the epigraph `{p : E × β | p.1 ∈ s ∧ f p.1 ≤ p.2}` is a convex set; * Center mass of a finite set of points with prescribed weights. * Convex hull of a set `s` is the minimal convex set that includes `s`. * Standard simplex `std_simplex ι [fintype ι]` is the intersection of the positive quadrant with the hyperplane `s.sum = 1` in the space `ι → ℝ`. We also provide various equivalent versions of the definitions above, prove that some specific sets are convex, and prove Jensen's inequality. Note: To define convexity for functions `f : E → β`, we need `β` to be an ordered vector space, defined using the instance `ordered_module ℝ β`. ## Notations We use the following local notations: * `I = Icc (0:ℝ) 1`; * `[x, y] = segment x y`. They are defined using `local notation`, so they are not available outside of this file. ## Implementation notes `convex_hull` is defined as a closure operator. This gives access to the `closure_operator` API while the impact on writing code is minimal as `convex_hull s` is automatically elaborated as `⇑convex_hull s`. -/ universes u' u v v' w x variables {E : Type u} {F : Type v} {ι : Type w} {ι' : Type x} {α : Type v'} [add_comm_group E] [module ℝ E] [add_comm_group F] [module ℝ F] [linear_ordered_field α] {s : set E} open set linear_map open_locale classical big_operators local notation `I` := (Icc 0 1 : set ℝ) section sets /-! ### Segment -/ /-- Segments in a vector space. -/ def segment (x y : E) : set E := {z : E | ∃ (a b : ℝ) (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1), a • x + b • y = z} local notation `[`x `, ` y `]` := segment x y lemma segment_symm (x y : E) : [x, y] = [y, x] := set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, H⟩, ⟨b, a, hb, ha, (add_comm _ _).trans hab, (add_comm _ _).trans H⟩, λ ⟨a, b, ha, hb, hab, H⟩, ⟨b, a, hb, ha, (add_comm _ _).trans hab, (add_comm _ _).trans H⟩⟩ lemma left_mem_segment (x y : E) : x ∈ [x, y] := ⟨1, 0, zero_le_one, le_refl 0, add_zero 1, by rw [zero_smul, one_smul, add_zero]⟩ lemma right_mem_segment (x y : E) : y ∈ [x, y] := segment_symm y x ▸ left_mem_segment y x lemma segment_same (x : E) : [x, x] = {x} := set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, hz⟩, by simpa only [(add_smul _ _ _).symm, mem_singleton_iff, hab, one_smul, eq_comm] using hz, λ h, mem_singleton_iff.1 h ▸ left_mem_segment z z⟩ lemma segment_eq_image (x y : E) : [x, y] = (λ θ : ℝ, (1 - θ) • x + θ • y) '' I := set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, hz⟩, ⟨b, ⟨hb, hab ▸ le_add_of_nonneg_left ha⟩, hab ▸ hz ▸ by simp only [add_sub_cancel]⟩, λ ⟨θ, ⟨hθ₀, hθ₁⟩, hz⟩, ⟨1-θ, θ, sub_nonneg.2 hθ₁, hθ₀, sub_add_cancel _ _, hz⟩⟩ lemma segment_eq_image' (x y : E) : [x, y] = (λ (θ : ℝ), x + θ • (y - x)) '' I := by { convert segment_eq_image x y, ext θ, simp only [smul_sub, sub_smul, one_smul], abel } lemma segment_eq_image₂ (x y : E) : [x, y] = (λ p : ℝ×ℝ, p.1 • x + p.2 • y) '' {p | 0 ≤ p.1 ∧ 0 ≤ p.2 ∧ p.1 + p.2 = 1} := by simp only [segment, image, prod.exists, mem_set_of_eq, exists_prop, and_assoc] lemma segment_eq_Icc {a b : ℝ} (h : a ≤ b) : [a, b] = Icc a b := begin rw [segment_eq_image'], show (((+) a) ∘ (λ t, t * (b - a))) '' Icc 0 1 = Icc a b, rw [image_comp, image_mul_right_Icc (@zero_le_one ℝ _) (sub_nonneg.2 h), image_const_add_Icc], simp end lemma segment_eq_Icc' (a b : ℝ) : [a, b] = Icc (min a b) (max a b) := by cases le_total a b; [skip, rw segment_symm]; simp [segment_eq_Icc, *] lemma segment_eq_interval (a b : ℝ) : segment a b = interval a b := segment_eq_Icc' _ _ lemma mem_segment_translate (a : E) {x b c} : a + x ∈ [a + b, a + c] ↔ x ∈ [b, c] := begin rw [segment_eq_image', segment_eq_image'], refine exists_congr (λ θ, and_congr iff.rfl _), simp only [add_sub_add_left_eq_sub, add_assoc, add_right_inj] end lemma segment_translate_preimage (a b c : E) : (λ x, a + x) ⁻¹' [a + b, a + c] = [b, c] := set.ext $ λ x, mem_segment_translate a lemma segment_translate_image (a b c : E) : (λx, a + x) '' [b, c] = [a + b, a + c] := segment_translate_preimage a b c ▸ image_preimage_eq _ $ add_left_surjective a lemma segment_image (f : E →ₗ[ℝ] F) (a b : E) : f '' [a, b] = [f a, f b] := set.ext (λ x, by simp [segment_eq_image]) /-- Open segment in a vector space. Note that `open_segment x x = {x}` instead of being `∅`. -/ def open_segment (x y : E) : set E := {z : E | ∃ (a b : ℝ) (ha : 0 < a) (hb : 0 < b) (hab : a + b = 1), a • x + b • y = z} lemma open_segment_subset_segment (x y : E) : open_segment x y ⊆ [x, y] := λ z ⟨a, b, ha, hb, hab, hz⟩, ⟨a, b, ha.le, hb.le, hab, hz⟩ lemma mem_open_segment_of_ne_left_right {x y z : E} (hx : x ≠ z) (hy : y ≠ z) (hz : z ∈ [x, y]) : z ∈ open_segment x y := begin obtain ⟨a, b, ha, hb, hab, hz⟩ := hz, by_cases ha' : a ≠ 0, by_cases hb' : b ≠ 0, { exact ⟨a, b, ha.lt_of_ne (ne.symm ha'), hb.lt_of_ne (ne.symm hb'), hab, hz⟩ }, all_goals { simp only [*, add_zero, not_not, one_smul, zero_smul, zero_add] at * } end lemma open_segment_symm (x y : E) : open_segment x y = open_segment y x := set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, H⟩, ⟨b, a, hb, ha, (add_comm _ _).trans hab, (add_comm _ _).trans H⟩, λ ⟨a, b, ha, hb, hab, H⟩, ⟨b, a, hb, ha, (add_comm _ _).trans hab, (add_comm _ _).trans H⟩⟩ @[simp] lemma open_segment_same (x : E) : open_segment x x = {x} := set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, hz⟩, by simpa only [← add_smul, mem_singleton_iff, hab, one_smul, eq_comm] using hz, λ h, mem_singleton_iff.1 h ▸ ⟨1/2, 1/2, one_half_pos, one_half_pos, add_halves 1, by rw [←add_smul, add_halves, one_smul]⟩⟩ @[simp] lemma left_mem_open_segment_iff {x y : E} : x ∈ open_segment x y ↔ x = y := begin split, { rintro ⟨a, b, ha, hb, hab, hx⟩, refine smul_left_injective _ hb.ne' ((add_right_inj (a • x)).1 _), rw [hx, ←add_smul, hab, one_smul] }, rintro rfl, simp only [open_segment_same, mem_singleton], end @[simp] lemma right_mem_open_segment_iff {x y : E} : y ∈ open_segment x y ↔ x = y := by rw [open_segment_symm, left_mem_open_segment_iff, eq_comm] lemma open_segment_eq_image (x y : E) : open_segment x y = (λ (θ : ℝ), (1 - θ) • x + θ • y) '' (Ioo 0 1 : set ℝ) := set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, hz⟩, ⟨b, ⟨hb, hab ▸ lt_add_of_pos_left _ ha⟩, hab ▸ hz ▸ by simp only [add_sub_cancel]⟩, λ ⟨θ, ⟨hθ₀, hθ₁⟩, hz⟩, ⟨1 - θ, θ, sub_pos.2 hθ₁, hθ₀, sub_add_cancel _ _, hz⟩⟩ lemma open_segment_eq_image' (x y : E) : open_segment x y = (λ (θ : ℝ), x + θ • (y - x)) '' (Ioo 0 1 : set ℝ) := by { convert open_segment_eq_image x y, ext θ, simp only [smul_sub, sub_smul, one_smul], abel } lemma open_segment_eq_image₂ (x y : E) : open_segment x y = (λ p:ℝ×ℝ, p.1 • x + p.2 • y) '' {p | 0 < p.1 ∧ 0 < p.2 ∧ p.1 + p.2 = 1} := by simp only [open_segment, image, prod.exists, mem_set_of_eq, exists_prop, and_assoc] @[simp] lemma open_segment_eq_Ioo {a b : ℝ} (h : a < b) : open_segment a b = Ioo a b := begin rw open_segment_eq_image', show (((+) a) ∘ (λ t, t * (b - a))) '' Ioo 0 1 = Ioo a b, rw [image_comp, image_mul_right_Ioo _ _ (sub_pos.2 h), image_const_add_Ioo], simp end lemma open_segment_eq_Ioo' {a b : ℝ} (hab : a ≠ b) : open_segment a b = Ioo (min a b) (max a b) := begin cases le_total a b, { rw open_segment_eq_Ioo (h.lt_of_ne hab), simp * }, rw [open_segment_symm, open_segment_eq_Ioo (h.lt_of_ne hab.symm)], simp *, end @[simp] lemma mem_open_segment_translate (a : E) {x b c : E} : a + x ∈ open_segment (a + b) (a + c) ↔ x ∈ open_segment b c := begin rw [open_segment_eq_image', open_segment_eq_image'], refine exists_congr (λ θ, and_congr iff.rfl _), simp only [add_sub_add_left_eq_sub, add_assoc, add_right_inj], end @[simp] lemma open_segment_translate_preimage (a b c : E) : (λ x, a + x) ⁻¹' open_segment (a + b) (a + c) = open_segment b c := set.ext $ λ x, mem_open_segment_translate a lemma open_segment_translate_image (a b c : E) : (λ x, a + x) '' open_segment b c = open_segment (a + b) (a + c) := open_segment_translate_preimage a b c ▸ image_preimage_eq _ $ add_left_surjective a @[simp] lemma open_segment_image (f : E →ₗ[ℝ] F) (a b : E) : f '' open_segment a b = open_segment (f a) (f b) := set.ext (λ x, by simp [open_segment_eq_image]) /-! ### Convexity of sets -/ /-- Convexity of sets. -/ def convex (s : set E) := ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → a + b = 1 → a • x + b • y ∈ s lemma convex_iff_forall_pos : convex s ↔ ∀ ⦃x y⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 < a → 0 < b → a + b = 1 → a • x + b • y ∈ s := begin refine ⟨λ h x y hx hy a b ha hb hab, h hx hy (le_of_lt ha) (le_of_lt hb) hab, _⟩, intros h x y hx hy a b ha hb hab, cases eq_or_lt_of_le ha with ha ha, { subst a, rw [zero_add] at hab, simp [hab, hy] }, cases eq_or_lt_of_le hb with hb hb, { subst b, rw [add_zero] at hab, simp [hab, hx] }, exact h hx hy ha hb hab end lemma convex_iff_segment_subset : convex s ↔ ∀ ⦃x y⦄, x ∈ s → y ∈ s → [x, y] ⊆ s := by simp only [convex, segment_eq_image₂, subset_def, ball_image_iff, prod.forall, mem_set_of_eq, and_imp] lemma convex_iff_open_segment_subset : convex s ↔ ∀ ⦃x y⦄, x ∈ s → y ∈ s → open_segment x y ⊆ s := by simp only [convex_iff_forall_pos, open_segment_eq_image₂, subset_def, ball_image_iff, prod.forall, mem_set_of_eq, and_imp] lemma convex.segment_subset (h : convex s) {x y : E} (hx : x ∈ s) (hy : y ∈ s) : [x, y] ⊆ s := convex_iff_segment_subset.1 h hx hy lemma convex.open_segment_subset (h : convex s) {x y : E} (hx : x ∈ s) (hy : y ∈ s) : open_segment x y ⊆ s := convex_iff_open_segment_subset.1 h hx hy lemma convex.add_smul_sub_mem (h : convex s) {x y : E} (hx : x ∈ s) (hy : y ∈ s) {t : ℝ} (ht : t ∈ Icc (0 : ℝ) 1) : x + t • (y - x) ∈ s := begin apply h.segment_subset hx hy, rw segment_eq_image', apply mem_image_of_mem, exact ht end lemma convex.add_smul_mem (h : convex s) {x y : E} (hx : x ∈ s) (hy : x + y ∈ s) {t : ℝ} (ht : t ∈ Icc (0 : ℝ) 1) : x + t • y ∈ s := by { convert h.add_smul_sub_mem hx hy ht, abel } lemma convex.smul_mem_of_zero_mem (h : convex s) {x : E} (zero_mem : (0:E) ∈ s) (hx : x ∈ s) {t : ℝ} (ht : t ∈ Icc (0 : ℝ) 1) : t • x ∈ s := by simpa using h.add_smul_mem zero_mem (by simpa using hx) ht lemma convex.mem_smul_of_zero_mem (h : convex s) {x : E} (zero_mem : (0:E) ∈ s) (hx : x ∈ s) {t : ℝ} (ht : 1 ≤ t) : x ∈ t • s := begin rw mem_smul_set_iff_inv_smul_mem (zero_lt_one.trans_le ht).ne', exact h.smul_mem_of_zero_mem zero_mem hx ⟨inv_nonneg.2 (zero_le_one.trans ht), inv_le_one ht⟩, end /-- Alternative definition of set convexity, in terms of pointwise set operations. -/ lemma convex_iff_pointwise_add_subset: convex s ↔ ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → a + b = 1 → a • s + b • s ⊆ s := iff.intro begin rintros hA a b ha hb hab w ⟨au, bv, ⟨u, hu, rfl⟩, ⟨v, hv, rfl⟩, rfl⟩, exact hA hu hv ha hb hab end (λ h x y hx hy a b ha hb hab, (h ha hb hab) (set.add_mem_add ⟨_, hx, rfl⟩ ⟨_, hy, rfl⟩)) /-- Alternative definition of set convexity, using division. -/ lemma convex_iff_div: convex s ↔ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → 0 < a + b → (a/(a+b)) • x + (b/(a+b)) • y ∈ s := ⟨begin assume h x y hx hy a b ha hb hab, apply h hx hy, have ha', from mul_le_mul_of_nonneg_left ha (le_of_lt (inv_pos.2 hab)), rwa [mul_zero, ←div_eq_inv_mul] at ha', have hb', from mul_le_mul_of_nonneg_left hb (le_of_lt (inv_pos.2 hab)), rwa [mul_zero, ←div_eq_inv_mul] at hb', rw [←add_div], exact div_self (ne_of_lt hab).symm end, begin assume h x y hx hy a b ha hb hab, have h', from h hx hy ha hb, rw [hab, div_one, div_one] at h', exact h' zero_lt_one end⟩ /-! ### Examples of convex sets -/ lemma convex_empty : convex (∅ : set E) := by finish lemma convex_singleton (c : E) : convex ({c} : set E) := begin intros x y hx hy a b ha hb hab, rw [set.eq_of_mem_singleton hx, set.eq_of_mem_singleton hy, ←add_smul, hab, one_smul], exact mem_singleton c end lemma convex_univ : convex (set.univ : set E) := λ _ _ _ _ _ _ _ _ _, trivial lemma convex.inter {t : set E} (hs: convex s) (ht: convex t) : convex (s ∩ t) := λ x y (hx : x ∈ s ∩ t) (hy : y ∈ s ∩ t) a b (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1), ⟨hs hx.left hy.left ha hb hab, ht hx.right hy.right ha hb hab⟩ lemma convex_sInter {S : set (set E)} (h : ∀ s ∈ S, convex s) : convex (⋂₀ S) := assume x y hx hy a b ha hb hab s hs, h s hs (hx s hs) (hy s hs) ha hb hab lemma convex_Inter {ι : Sort*} {s : ι → set E} (h : ∀ i : ι, convex (s i)) : convex (⋂ i, s i) := (sInter_range s) ▸ convex_sInter $ forall_range_iff.2 h lemma convex.prod {s : set E} {t : set F} (hs : convex s) (ht : convex t) : convex (s.prod t) := begin intros x y hx hy a b ha hb hab, apply mem_prod.2, exact ⟨hs (mem_prod.1 hx).1 (mem_prod.1 hy).1 ha hb hab, ht (mem_prod.1 hx).2 (mem_prod.1 hy).2 ha hb hab⟩ end lemma directed.convex_Union {ι : Sort*} {s : ι → set E} (hdir : directed has_subset.subset s) (hc : ∀ ⦃i : ι⦄, convex (s i)) : convex (⋃ i, s i) := begin rintro x y hx hy a b ha hb hab, rw mem_Union at ⊢ hx hy, obtain ⟨i, hx⟩ := hx, obtain ⟨j, hy⟩ := hy, obtain ⟨k, hik, hjk⟩ := hdir i j, exact ⟨k, hc (hik hx) (hjk hy) ha hb hab⟩, end lemma directed_on.convex_sUnion {c : set (set E)} (hdir : directed_on has_subset.subset c) (hc : ∀ ⦃A : set E⦄, A ∈ c → convex A) : convex (⋃₀c) := begin rw sUnion_eq_Union, exact (directed_on_iff_directed.1 hdir).convex_Union (λ A, hc A.2), end lemma convex.combo_to_vadd {a b : ℝ} {x y : E} (h : a + b = 1) : a • x + b • y = b • (y - x) + x := calc a • x + b • y = (b • y - b • x) + (a • x + b • x) : by abel ... = b • (y - x) + (a + b) • x : by rw [smul_sub, add_smul] ... = b • (y - x) + (1 : ℝ) • x : by rw [h] ... = b • (y - x) + x : by rw [one_smul] /-- Applying an affine map to an affine combination of two points yields an affine combination of the images. -/ lemma convex.combo_affine_apply {a b : ℝ} {x y : E} {f : E →ᵃ[ℝ] F} (h : a + b = 1) : f (a • x + b • y) = a • f x + b • f y := begin simp only [convex.combo_to_vadd h, ← vsub_eq_sub], exact f.apply_line_map _ _ _, end /-- The preimage of a convex set under an affine map is convex. -/ lemma convex.affine_preimage (f : E →ᵃ[ℝ] F) {s : set F} (hs : convex s) : convex (f ⁻¹' s) := begin intros x y xs ys a b ha hb hab, rw [mem_preimage, convex.combo_affine_apply hab], exact hs xs ys ha hb hab, end /-- The image of a convex set under an affine map is convex. -/ lemma convex.affine_image (f : E →ᵃ[ℝ] F) {s : set E} (hs : convex s) : convex (f '' s) := begin rintros x y ⟨x', ⟨hx', hx'f⟩⟩ ⟨y', ⟨hy', hy'f⟩⟩ a b ha hb hab, refine ⟨a • x' + b • y', ⟨hs hx' hy' ha hb hab, _⟩⟩, rw [convex.combo_affine_apply hab, hx'f, hy'f] end lemma convex.linear_image (hs : convex s) (f : E →ₗ[ℝ] F) : convex (image f s) := hs.affine_image f.to_affine_map lemma convex.is_linear_image (hs : convex s) {f : E → F} (hf : is_linear_map ℝ f) : convex (f '' s) := hs.linear_image $ hf.mk' f lemma convex.linear_preimage {s : set F} (hs : convex s) (f : E →ₗ[ℝ] F) : convex (preimage f s) := hs.affine_preimage f.to_affine_map lemma convex.is_linear_preimage {s : set F} (hs : convex s) {f : E → F} (hf : is_linear_map ℝ f) : convex (preimage f s) := hs.linear_preimage $ hf.mk' f lemma convex.neg (hs : convex s) : convex ((λ z, -z) '' s) := hs.is_linear_image is_linear_map.is_linear_map_neg lemma convex.neg_preimage (hs : convex s) : convex ((λ z, -z) ⁻¹' s) := hs.is_linear_preimage is_linear_map.is_linear_map_neg lemma convex.smul (c : ℝ) (hs : convex s) : convex (c • s) := hs.linear_image (linear_map.lsmul _ _ c) lemma convex.smul_preimage (c : ℝ) (hs : convex s) : convex ((λ z, c • z) ⁻¹' s) := hs.linear_preimage (linear_map.lsmul _ _ c) lemma convex.add {t : set E} (hs : convex s) (ht : convex t) : convex (s + t) := by { rw ← add_image_prod, exact (hs.prod ht).is_linear_image is_linear_map.is_linear_map_add } lemma convex.sub {t : set E} (hs : convex s) (ht : convex t) : convex ((λx : E × E, x.1 - x.2) '' (s.prod t)) := (hs.prod ht).is_linear_image is_linear_map.is_linear_map_sub lemma convex.translate (hs : convex s) (z : E) : convex ((λx, z + x) '' s) := hs.affine_image $ affine_map.const ℝ E z +ᵥ affine_map.id ℝ E /-- The translation of a convex set is also convex. -/ lemma convex.translate_preimage_right (hs : convex s) (a : E) : convex ((λ z, a + z) ⁻¹' s) := hs.affine_preimage $ affine_map.const ℝ E a +ᵥ affine_map.id ℝ E /-- The translation of a convex set is also convex. -/ lemma convex.translate_preimage_left (hs : convex s) (a : E) : convex ((λ z, z + a) ⁻¹' s) := by simpa only [add_comm] using hs.translate_preimage_right a lemma convex.affinity (hs : convex s) (z : E) (c : ℝ) : convex ((λx, z + c • x) '' s) := hs.affine_image $ affine_map.const ℝ E z +ᵥ c • affine_map.id ℝ E lemma real.convex_iff_ord_connected {s : set ℝ} : convex s ↔ ord_connected s := begin simp only [convex_iff_segment_subset, segment_eq_interval, ord_connected_iff_interval_subset], exact forall_congr (λ x, forall_swap) end alias real.convex_iff_ord_connected ↔ convex.ord_connected set.ord_connected.convex lemma convex_Iio (r : ℝ) : convex (Iio r) := ord_connected_Iio.convex lemma convex_Ioi (r : ℝ) : convex (Ioi r) := ord_connected_Ioi.convex lemma convex_Iic (r : ℝ) : convex (Iic r) := ord_connected_Iic.convex lemma convex_Ici (r : ℝ) : convex (Ici r) := ord_connected_Ici.convex lemma convex_Ioo (r s : ℝ) : convex (Ioo r s) := ord_connected_Ioo.convex lemma convex_Ico (r s : ℝ) : convex (Ico r s) := ord_connected_Ico.convex lemma convex_Ioc (r : ℝ) (s : ℝ) : convex (Ioc r s) := ord_connected_Ioc.convex lemma convex_Icc (r : ℝ) (s : ℝ) : convex (Icc r s) := ord_connected_Icc.convex lemma convex_interval (r : ℝ) (s : ℝ) : convex (interval r s) := ord_connected_interval.convex lemma convex_segment (a b : E) : convex [a, b] := begin have : (λ (t : ℝ), a + t • (b - a)) = (λ z : E, a + z) ∘ (λ t : ℝ, t • (b - a)) := rfl, rw [segment_eq_image', this, image_comp], refine ((convex_Icc _ _).is_linear_image _).translate _, exact is_linear_map.is_linear_map_smul' _ end lemma convex_open_segment (a b : E) : convex (open_segment a b) := begin have : (λ (t : ℝ), a + t • (b - a)) = (λ z : E, a + z) ∘ (λ t : ℝ, t • (b - a)) := rfl, rw [open_segment_eq_image', this, image_comp], refine ((convex_Ioo _ _).is_linear_image _).translate _, exact is_linear_map.is_linear_map_smul' _, end lemma convex_halfspace_lt {f : E → ℝ} (h : is_linear_map ℝ f) (r : ℝ) : convex {w | f w < r} := (convex_Iio r).is_linear_preimage h lemma convex_halfspace_le {f : E → ℝ} (h : is_linear_map ℝ f) (r : ℝ) : convex {w | f w ≤ r} := (convex_Iic r).is_linear_preimage h lemma convex_halfspace_gt {f : E → ℝ} (h : is_linear_map ℝ f) (r : ℝ) : convex {w | r < f w} := (convex_Ioi r).is_linear_preimage h lemma convex_halfspace_ge {f : E → ℝ} (h : is_linear_map ℝ f) (r : ℝ) : convex {w | r ≤ f w} := (convex_Ici r).is_linear_preimage h lemma convex_hyperplane {f : E → ℝ} (h : is_linear_map ℝ f) (r : ℝ) : convex {w | f w = r} := begin show convex (f ⁻¹' {p | p = r}), rw set_of_eq_eq_singleton, exact (convex_singleton r).is_linear_preimage h end lemma convex_halfspace_re_lt (r : ℝ) : convex {c : ℂ | c.re < r} := convex_halfspace_lt (is_linear_map.mk complex.add_re complex.smul_re) _ lemma convex_halfspace_re_le (r : ℝ) : convex {c : ℂ | c.re ≤ r} := convex_halfspace_le (is_linear_map.mk complex.add_re complex.smul_re) _ lemma convex_halfspace_re_gt (r : ℝ) : convex {c : ℂ | r < c.re } := convex_halfspace_gt (is_linear_map.mk complex.add_re complex.smul_re) _ lemma convex_halfspace_re_lge (r : ℝ) : convex {c : ℂ | r ≤ c.re} := convex_halfspace_ge (is_linear_map.mk complex.add_re complex.smul_re) _ lemma convex_halfspace_im_lt (r : ℝ) : convex {c : ℂ | c.im < r} := convex_halfspace_lt (is_linear_map.mk complex.add_im complex.smul_im) _ lemma convex_halfspace_im_le (r : ℝ) : convex {c : ℂ | c.im ≤ r} := convex_halfspace_le (is_linear_map.mk complex.add_im complex.smul_im) _ lemma convex_halfspace_im_gt (r : ℝ) : convex {c : ℂ | r < c.im } := convex_halfspace_gt (is_linear_map.mk complex.add_im complex.smul_im) _ lemma convex_halfspace_im_lge (r : ℝ) : convex {c : ℂ | r ≤ c.im} := convex_halfspace_ge (is_linear_map.mk complex.add_im complex.smul_im) _ /-! ### Convex combinations in intervals -/ lemma convex.combo_self (a : α) {x y : α} (h : x + y = 1) : a = x * a + y * a := calc a = 1 * a : by rw [one_mul] ... = (x + y) * a : by rw [h] ... = x * a + y * a : by rw [add_mul] /-- If `x` is in an `Ioo`, it can be expressed as a convex combination of the endpoints. -/ lemma convex.mem_Ioo {a b x : α} (h : a < b) : x ∈ Ioo a b ↔ ∃ (x_a x_b : α), 0 < x_a ∧ 0 < x_b ∧ x_a + x_b = 1 ∧ x_a * a + x_b * b = x := begin split, { rintros ⟨h_ax, h_bx⟩, by_cases hab : ¬a < b, { exfalso; exact hab h }, { refine ⟨(b-x) / (b-a), (x-a) / (b-a), _⟩, refine ⟨div_pos (by linarith) (by linarith), div_pos (by linarith) (by linarith),_,_⟩; { field_simp [show b - a ≠ 0, by linarith], ring } } }, { rw [mem_Ioo], rintros ⟨xa, xb, ⟨hxa, hxb, hxaxb, h₂⟩⟩, rw [←h₂], exact ⟨by nlinarith [convex.combo_self a hxaxb], by nlinarith [convex.combo_self b hxaxb]⟩ } end /-- If `x` is in an `Ioc`, it can be expressed as a convex combination of the endpoints. -/ lemma convex.mem_Ioc {a b x : α} (h : a < b) : x ∈ Ioc a b ↔ ∃ (x_a x_b : α), 0 ≤ x_a ∧ 0 < x_b ∧ x_a + x_b = 1 ∧ x_a * a + x_b * b = x := begin split, { rintros ⟨h_ax, h_bx⟩, by_cases h_x : x = b, { exact ⟨0, 1, by linarith, by linarith, by ring, by {rw [h_x], ring}⟩ }, { rcases (convex.mem_Ioo h).mp ⟨h_ax, lt_of_le_of_ne h_bx h_x⟩ with ⟨x_a, x_b, Ioo_case⟩, exact ⟨x_a, x_b, by linarith, Ioo_case.2⟩ } }, { rw [mem_Ioc], rintros ⟨xa, xb, ⟨hxa, hxb, hxaxb, h₂⟩⟩, rw [←h₂], exact ⟨by nlinarith [convex.combo_self a hxaxb], by nlinarith [convex.combo_self b hxaxb]⟩ } end /-- If `x` is in an `Ico`, it can be expressed as a convex combination of the endpoints. -/ lemma convex.mem_Ico {a b x : α} (h : a < b) : x ∈ Ico a b ↔ ∃ (x_a x_b : α), 0 < x_a ∧ 0 ≤ x_b ∧ x_a + x_b = 1 ∧ x_a * a + x_b * b = x := begin split, { rintros ⟨h_ax, h_bx⟩, by_cases h_x : x = a, { exact ⟨1, 0, by linarith, by linarith, by ring, by {rw [h_x], ring}⟩ }, { rcases (convex.mem_Ioo h).mp ⟨lt_of_le_of_ne h_ax (ne.symm h_x), h_bx⟩ with ⟨x_a, x_b, Ioo_case⟩, exact ⟨x_a, x_b, Ioo_case.1, by linarith, (Ioo_case.2).2⟩ } }, { rw [mem_Ico], rintros ⟨xa, xb, ⟨hxa, hxb, hxaxb, h₂⟩⟩, rw [←h₂], exact ⟨by nlinarith [convex.combo_self a hxaxb], by nlinarith [convex.combo_self b hxaxb]⟩ } end /-- If `x` is in an `Icc`, it can be expressed as a convex combination of the endpoints. -/ lemma convex.mem_Icc {a b x : α} (h : a ≤ b) : x ∈ Icc a b ↔ ∃ (x_a x_b : α), 0 ≤ x_a ∧ 0 ≤ x_b ∧ x_a + x_b = 1 ∧ x_a * a + x_b * b = x := begin split, { intro x_in_I, rw [Icc, mem_set_of_eq] at x_in_I, rcases x_in_I with ⟨h_ax, h_bx⟩, by_cases hab' : a = b, { exact ⟨0, 1, le_refl 0, by linarith, by ring, by linarith⟩ }, change a ≠ b at hab', replace h : a < b, exact lt_of_le_of_ne h hab', by_cases h_x : x = a, { exact ⟨1, 0, by linarith, by linarith, by ring, by {rw [h_x], ring}⟩ }, { rcases (convex.mem_Ioc h).mp ⟨lt_of_le_of_ne h_ax (ne.symm h_x), h_bx⟩ with ⟨x_a, x_b, Ioo_case⟩, exact ⟨x_a, x_b, Ioo_case.1, by linarith, (Ioo_case.2).2⟩ } }, { rw [mem_Icc], rintros ⟨xa, xb, ⟨hxa, hxb, hxaxb, h₂⟩⟩, rw [←h₂], exact ⟨by nlinarith [convex.combo_self a hxaxb], by nlinarith [convex.combo_self b hxaxb]⟩ } end section submodule open submodule lemma submodule.convex (K : submodule ℝ E) : convex (↑K : set E) := by { repeat {intro}, refine add_mem _ (smul_mem _ _ _) (smul_mem _ _ _); assumption } lemma subspace.convex (K : subspace ℝ E) : convex (↑K : set E) := K.convex end submodule end sets /-! ### Convex and concave functions -/ section functions variables {β : Type*} [ordered_add_comm_monoid β] [module ℝ β] local notation `[`x `, ` y `]` := segment x y /-- Convexity of functions -/ def convex_on (s : set E) (f : E → β) : Prop := convex s ∧ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → a + b = 1 → f (a • x + b • y) ≤ a • f x + b • f y /-- Concavity of functions -/ def concave_on (s : set E) (f : E → β) : Prop := convex s ∧ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → a + b = 1 → a • f x + b • f y ≤ f (a • x + b • y) section variables [ordered_module ℝ β] /-- A function `f` is concave iff `-f` is convex. -/ @[simp] lemma neg_convex_on_iff {γ : Type*} [ordered_add_comm_group γ] [module ℝ γ] (s : set E) (f : E → γ) : convex_on s (-f) ↔ concave_on s f := begin split, { rintros ⟨hconv, h⟩, refine ⟨hconv, _⟩, intros x y xs ys a b ha hb hab, specialize h xs ys ha hb hab, simp [neg_apply, neg_le, add_comm] at h, exact h }, { rintros ⟨hconv, h⟩, refine ⟨hconv, _⟩, intros x y xs ys a b ha hb hab, specialize h xs ys ha hb hab, simp [neg_apply, neg_le, add_comm, h] } end /-- A function `f` is concave iff `-f` is convex. -/ @[simp] lemma neg_concave_on_iff {γ : Type*} [ordered_add_comm_group γ] [module ℝ γ] (s : set E) (f : E → γ) : concave_on s (-f) ↔ convex_on s f:= by rw [← neg_convex_on_iff s (-f), neg_neg f] end lemma convex_on_id {s : set ℝ} (hs : convex s) : convex_on s id := ⟨hs, by { intros, refl }⟩ lemma concave_on_id {s : set ℝ} (hs : convex s) : concave_on s id := ⟨hs, by { intros, refl }⟩ lemma convex_on_const (c : β) (hs : convex s) : convex_on s (λ x:E, c) := ⟨hs, by { intros, simp only [← add_smul, *, one_smul] }⟩ lemma concave_on_const (c : β) (hs : convex s) : concave_on s (λ x:E, c) := @convex_on_const _ _ _ _ (order_dual β) _ _ c hs variables {t : set E} lemma convex_on_iff_div {f : E → β} : convex_on s f ↔ convex s ∧ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → 0 < a + b → f ((a/(a+b)) • x + (b/(a+b)) • y) ≤ (a/(a+b)) • f x + (b/(a+b)) • f y := and_congr iff.rfl ⟨begin intros h x y hx hy a b ha hb hab, apply h hx hy (div_nonneg ha $ le_of_lt hab) (div_nonneg hb $ le_of_lt hab), rw [←add_div], exact div_self (ne_of_gt hab) end, begin intros h x y hx hy a b ha hb hab, simpa [hab, zero_lt_one] using h hx hy ha hb, end⟩ lemma concave_on_iff_div {f : E → β} : concave_on s f ↔ convex s ∧ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → 0 < a + b → (a/(a+b)) • f x + (b/(a+b)) • f y ≤ f ((a/(a+b)) • x + (b/(a+b)) • y) := @convex_on_iff_div _ _ _ _ (order_dual β) _ _ _ /-- For a function on a convex set in a linear ordered space, in order to prove that it is convex it suffices to verify the inequality `f (a • x + b • y) ≤ a • f x + b • f y` only for `x < y` and positive `a`, `b`. The main use case is `E = ℝ` however one can apply it, e.g., to `ℝ^n` with lexicographic order. -/ lemma linear_order.convex_on_of_lt {f : E → β} [linear_order E] (hs : convex s) (hf : ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → x < y → ∀ ⦃a b : ℝ⦄, 0 < a → 0 < b → a + b = 1 → f (a • x + b • y) ≤ a • f x + b • f y) : convex_on s f := begin use hs, intros x y hx hy a b ha hb hab, wlog hxy : x<=y using [x y a b, y x b a], { exact le_total _ _ }, { cases eq_or_lt_of_le hxy with hxy hxy, by { subst y, rw [← add_smul, ← add_smul, hab, one_smul, one_smul] }, cases eq_or_lt_of_le ha with ha ha, by { subst a, rw [zero_add] at hab, subst b, simp }, cases eq_or_lt_of_le hb with hb hb, by { subst b, rw [add_zero] at hab, subst a, simp }, exact hf hx hy hxy ha hb hab } end /-- For a function on a convex set in a linear ordered space, in order to prove that it is concave it suffices to verify the inequality `a • f x + b • f y ≤ f (a • x + b • y)` only for `x < y` and positive `a`, `b`. The main use case is `E = ℝ` however one can apply it, e.g., to `ℝ^n` with lexicographic order. -/ lemma linear_order.concave_on_of_lt {f : E → β} [linear_order E] (hs : convex s) (hf : ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → x < y → ∀ ⦃a b : ℝ⦄, 0 < a → 0 < b → a + b = 1 → a • f x + b • f y ≤ f (a • x + b • y)) : concave_on s f := @linear_order.convex_on_of_lt _ _ _ _ (order_dual β) _ _ f _ hs hf /-- For a function `f` defined on a convex subset `D` of `ℝ`, if for any three points `x<y<z` the slope of the secant line of `f` on `[x, y]` is less than or equal to the slope of the secant line of `f` on `[x, z]`, then `f` is convex on `D`. This way of proving convexity of a function is used in the proof of convexity of a function with a monotone derivative. -/ lemma convex_on_real_of_slope_mono_adjacent {s : set ℝ} (hs : convex s) {f : ℝ → ℝ} (hf : ∀ {x y z : ℝ}, x ∈ s → z ∈ s → x < y → y < z → (f y - f x) / (y - x) ≤ (f z - f y) / (z - y)) : convex_on s f := linear_order.convex_on_of_lt hs begin assume x z hx hz hxz a b ha hb hab, let y := a * x + b * z, have hxy : x < y, { rw [← one_mul x, ← hab, add_mul], exact add_lt_add_left ((mul_lt_mul_left hb).2 hxz) _ }, have hyz : y < z, { rw [← one_mul z, ← hab, add_mul], exact add_lt_add_right ((mul_lt_mul_left ha).2 hxz) _ }, have : (f y - f x) * (z - y) ≤ (f z - f y) * (y - x), from (div_le_div_iff (sub_pos.2 hxy) (sub_pos.2 hyz)).1 (hf hx hz hxy hyz), have A : z - y + (y - x) = z - x, by abel, have B : 0 < z - x, from sub_pos.2 (lt_trans hxy hyz), rw [sub_mul, sub_mul, sub_le_iff_le_add', ← add_sub_assoc, le_sub_iff_add_le, ← mul_add, A, ← le_div_iff B, add_div, mul_div_assoc, mul_div_assoc, mul_comm (f x), mul_comm (f z)] at this, rw [eq_comm, ← sub_eq_iff_eq_add] at hab; subst a, convert this; symmetry; simp only [div_eq_iff (ne_of_gt B), y]; ring end /-- For a function `f` defined on a subset `D` of `ℝ`, if `f` is convex on `D`, then for any three points `x<y<z`, the slope of the secant line of `f` on `[x, y]` is less than or equal to the slope of the secant line of `f` on `[x, z]`. -/ lemma convex_on.slope_mono_adjacent {s : set ℝ} {f : ℝ → ℝ} (hf : convex_on s f) {x y z : ℝ} (hx : x ∈ s) (hz : z ∈ s) (hxy : x < y) (hyz : y < z) : (f y - f x) / (y - x) ≤ (f z - f y) / (z - y) := begin have h₁ : 0 < y - x := by linarith, have h₂ : 0 < z - y := by linarith, have h₃ : 0 < z - x := by linarith, suffices : f y / (y - x) + f y / (z - y) ≤ f x / (y - x) + f z / (z - y), by { ring_nf at this ⊢, linarith }, set a := (z - y) / (z - x), set b := (y - x) / (z - x), have heqz : a • x + b • z = y, by { field_simp, rw div_eq_iff; [ring, linarith], }, have key, from hf.2 hx hz (show 0 ≤ a, by apply div_nonneg; linarith) (show 0 ≤ b, by apply div_nonneg; linarith) (show a + b = 1, by { field_simp, rw div_eq_iff; [ring, linarith], }), rw heqz at key, replace key := mul_le_mul_of_nonneg_left key (le_of_lt h₃), field_simp [ne_of_gt h₁, ne_of_gt h₂, ne_of_gt h₃, mul_comm (z - x) _] at key ⊢, rw div_le_div_right, { linarith, }, { nlinarith, }, end /-- For a function `f` defined on a convex subset `D` of `ℝ`, `f` is convex on `D` iff for any three points `x<y<z` the slope of the secant line of `f` on `[x, y]` is less than or equal to the slope of the secant line of `f` on `[x, z]`. -/ lemma convex_on_real_iff_slope_mono_adjacent {s : set ℝ} (hs : convex s) {f : ℝ → ℝ} : convex_on s f ↔ (∀ {x y z : ℝ}, x ∈ s → z ∈ s → x < y → y < z → (f y - f x) / (y - x) ≤ (f z - f y) / (z - y)) := ⟨convex_on.slope_mono_adjacent, convex_on_real_of_slope_mono_adjacent hs⟩ /-- For a function `f` defined on a convex subset `D` of `ℝ`, if for any three points `x<y<z` the slope of the secant line of `f` on `[x, y]` is greater than or equal to the slope of the secant line of `f` on `[x, z]`, then `f` is concave on `D`. -/ lemma concave_on_real_of_slope_mono_adjacent {s : set ℝ} (hs : convex s) {f : ℝ → ℝ} (hf : ∀ {x y z : ℝ}, x ∈ s → z ∈ s → x < y → y < z → (f z - f y) / (z - y) ≤ (f y - f x) / (y - x)) : concave_on s f := begin rw [←neg_convex_on_iff], apply convex_on_real_of_slope_mono_adjacent hs, intros x y z xs zs xy yz, rw [←neg_le_neg_iff, ←neg_div, ←neg_div, neg_sub, neg_sub], simp only [hf xs zs xy yz, neg_sub_neg, pi.neg_apply], end /-- For a function `f` defined on a subset `D` of `ℝ`, if `f` is concave on `D`, then for any three points `x<y<z`, the slope of the secant line of `f` on `[x, y]` is greater than or equal to the slope of the secant line of `f` on `[x, z]`. -/ lemma concave_on.slope_mono_adjacent {s : set ℝ} {f : ℝ → ℝ} (hf : concave_on s f) {x y z : ℝ} (hx : x ∈ s) (hz : z ∈ s) (hxy : x < y) (hyz : y < z) : (f z - f y) / (z - y) ≤ (f y - f x) / (y - x) := begin rw [←neg_le_neg_iff, ←neg_div, ←neg_div, neg_sub, neg_sub], rw [←neg_sub_neg (f y), ←neg_sub_neg (f z)], simp_rw [←pi.neg_apply], rw [←neg_convex_on_iff] at hf, apply convex_on.slope_mono_adjacent hf; assumption, end /-- For a function `f` defined on a convex subset `D` of `ℝ`, `f` is concave on `D` iff for any three points `x<y<z` the slope of the secant line of `f` on `[x, y]` is greater than or equal to the slope of the secant line of `f` on `[x, z]`. -/ lemma concave_on_real_iff_slope_mono_adjacent {s : set ℝ} (hs : convex s) {f : ℝ → ℝ} : concave_on s f ↔ (∀ {x y z : ℝ}, x ∈ s → z ∈ s → x < y → y < z → (f z - f y) / (z - y) ≤ (f y - f x) / (y - x)) := ⟨concave_on.slope_mono_adjacent, concave_on_real_of_slope_mono_adjacent hs⟩ lemma convex_on.subset {f : E → β} (h_convex_on : convex_on t f) (h_subset : s ⊆ t) (h_convex : convex s) : convex_on s f := begin apply and.intro h_convex, intros x y hx hy, exact h_convex_on.2 (h_subset hx) (h_subset hy), end lemma concave_on.subset {f : E → β} (h_concave_on : concave_on t f) (h_subset : s ⊆ t) (h_convex : convex s) : concave_on s f := @convex_on.subset _ _ _ _ (order_dual β) _ _ t f h_concave_on h_subset h_convex lemma convex_on.add {f g : E → β} (hf : convex_on s f) (hg : convex_on s g) : convex_on s (λx, f x + g x) := begin apply and.intro hf.1, intros x y hx hy a b ha hb hab, calc f (a • x + b • y) + g (a • x + b • y) ≤ (a • f x + b • f y) + (a • g x + b • g y) : add_le_add (hf.2 hx hy ha hb hab) (hg.2 hx hy ha hb hab) ... = a • f x + a • g x + b • f y + b • g y : by abel ... = a • (f x + g x) + b • (f y + g y) : by simp [smul_add, add_assoc] end lemma concave_on.add {f g : E → β} (hf : concave_on s f) (hg : concave_on s g) : concave_on s (λx, f x + g x) := @convex_on.add _ _ _ _ (order_dual β) _ _ f g hf hg lemma convex_on.smul [ordered_module ℝ β] {f : E → β} {c : ℝ} (hc : 0 ≤ c) (hf : convex_on s f) : convex_on s (λx, c • f x) := begin apply and.intro hf.1, intros x y hx hy a b ha hb hab, calc c • f (a • x + b • y) ≤ c • (a • f x + b • f y) : smul_le_smul_of_nonneg (hf.2 hx hy ha hb hab) hc ... = a • (c • f x) + b • (c • f y) : by simp only [smul_add, smul_comm c] end lemma concave_on.smul [ordered_module ℝ β] {f : E → β} {c : ℝ} (hc : 0 ≤ c) (hf : concave_on s f) : concave_on s (λx, c • f x) := @convex_on.smul _ _ _ _ (order_dual β) _ _ _ f c hc hf section linear_order variables {γ : Type*} [linear_ordered_add_comm_group γ] [module ℝ γ] [ordered_module ℝ γ] {f : E → γ} /-- A convex function on a segment is upper-bounded by the max of its endpoints. -/ lemma convex_on.le_on_segment' (hf : convex_on s f) {x y : E} {a b : ℝ} (hx : x ∈ s) (hy : y ∈ s) (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1) : f (a • x + b • y) ≤ max (f x) (f y) := calc f (a • x + b • y) ≤ a • f x + b • f y : hf.2 hx hy ha hb hab ... ≤ a • max (f x) (f y) + b • max (f x) (f y) : add_le_add (smul_le_smul_of_nonneg (le_max_left _ _) ha) (smul_le_smul_of_nonneg (le_max_right _ _) hb) ... = max (f x) (f y) : by rw [←add_smul, hab, one_smul] /-- A concave function on a segment is lower-bounded by the min of its endpoints. -/ lemma concave_on.le_on_segment' (hf : concave_on s f) {x y : E} {a b : ℝ} (hx : x ∈ s) (hy : y ∈ s) (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1) : min (f x) (f y) ≤ f (a • x + b • y) := @convex_on.le_on_segment' _ _ _ _ (order_dual γ) _ _ _ f hf x y a b hx hy ha hb hab /-- A convex function on a segment is upper-bounded by the max of its endpoints. -/ lemma convex_on.le_on_segment (hf : convex_on s f) {x y z : E} (hx : x ∈ s) (hy : y ∈ s) (hz : z ∈ [x, y]) : f z ≤ max (f x) (f y) := let ⟨a, b, ha, hb, hab, hz⟩ := hz in hz ▸ hf.le_on_segment' hx hy ha hb hab /-- A concave function on a segment is lower-bounded by the min of its endpoints. -/ lemma concave_on.le_on_segment {γ : Type*} [linear_ordered_add_comm_group γ] [module ℝ γ] [ordered_module ℝ γ] {f : E → γ} (hf : concave_on s f) {x y z : E} (hx : x ∈ s) (hy : y ∈ s) (hz : z ∈ [x, y]) : min (f x) (f y) ≤ f z := @convex_on.le_on_segment _ _ _ _ (order_dual γ) _ _ _ f hf x y z hx hy hz -- could be shown without contradiction but yeah lemma convex_on.le_left_of_right_le' (hf : convex_on s f) {x y : E} {a b : ℝ} (hx : x ∈ s) (hy : y ∈ s) (ha : 0 < a) (hb : 0 ≤ b) (hab : a + b = 1) (hxy : f y ≤ f (a • x + b • y)) : f (a • x + b • y) ≤ f x := begin apply le_of_not_lt (λ h, lt_irrefl (f (a • x + b • y)) _), calc f (a • x + b • y) ≤ a • f x + b • f y : hf.2 hx hy ha.le hb hab ... < a • f (a • x + b • y) + b • f (a • x + b • y) : add_lt_add_of_lt_of_le (smul_lt_smul_of_pos h ha) (smul_le_smul_of_nonneg hxy hb) ... = f (a • x + b • y) : by rw [←add_smul, hab, one_smul], end lemma concave_on.left_le_of_le_right' (hf : concave_on s f) {x y : E} {a b : ℝ} (hx : x ∈ s) (hy : y ∈ s) (ha : 0 < a) (hb : 0 ≤ b) (hab : a + b = 1) (hxy : f (a • x + b • y) ≤ f y) : f x ≤ f (a • x + b • y) := @convex_on.le_left_of_right_le' _ _ _ _ (order_dual γ) _ _ _ f hf x y a b hx hy ha hb hab hxy lemma convex_on.le_right_of_left_le' (hf : convex_on s f) {x y : E} {a b : ℝ} (hx : x ∈ s) (hy : y ∈ s) (ha : 0 ≤ a) (hb : 0 < b) (hab : a + b = 1) (hxy : f x ≤ f (a • x + b • y)) : f (a • x + b • y) ≤ f y := begin rw add_comm at ⊢ hab hxy, exact hf.le_left_of_right_le' hy hx hb ha hab hxy, end lemma concave_on.le_right_of_left_le' (hf : concave_on s f) {x y : E} {a b : ℝ} (hx : x ∈ s) (hy : y ∈ s) (ha : 0 ≤ a) (hb : 0 < b) (hab : a + b = 1) (hxy : f (a • x + b • y) ≤ f x) : f y ≤ f (a • x + b • y) := @convex_on.le_right_of_left_le' _ _ _ _ (order_dual γ) _ _ _ f hf x y a b hx hy ha hb hab hxy lemma convex_on.le_left_of_right_le (hf : convex_on s f) {x y z : E} (hx : x ∈ s) (hy : y ∈ s) (hz : z ∈ open_segment x y) (hyz : f y ≤ f z) : f z ≤ f x := begin obtain ⟨a, b, ha, hb, hab, rfl⟩ := hz, exact hf.le_left_of_right_le' hx hy ha hb.le hab hyz, end lemma concave_on.left_le_of_le_right (hf : concave_on s f) {x y z : E} (hx : x ∈ s) (hy : y ∈ s) (hz : z ∈ open_segment x y) (hyz : f z ≤ f y) : f x ≤ f z := @convex_on.le_left_of_right_le _ _ _ _ (order_dual γ) _ _ _ f hf x y z hx hy hz hyz lemma convex_on.le_right_of_left_le (hf : convex_on s f) {x y z : E} (hx : x ∈ s) (hy : y ∈ s) (hz : z ∈ open_segment x y) (hxz : f x ≤ f z) : f z ≤ f y := begin obtain ⟨a, b, ha, hb, hab, rfl⟩ := hz, exact hf.le_right_of_left_le' hx hy ha.le hb hab hxz, end lemma concave_on.le_right_of_left_le (hf : concave_on s f) {x y z : E} (hx : x ∈ s) (hy : y ∈ s) (hz : z ∈ open_segment x y) (hxz : f z ≤ f x) : f y ≤ f z := @convex_on.le_right_of_left_le _ _ _ _ (order_dual γ) _ _ _ f hf x y z hx hy hz hxz end linear_order lemma convex_on.convex_le [ordered_module ℝ β] {f : E → β} (hf : convex_on s f) (r : β) : convex {x ∈ s | f x ≤ r} := λ x y hx hy a b ha hb hab, begin refine ⟨hf.1 hx.1 hy.1 ha hb hab, _⟩, calc f (a • x + b • y) ≤ a • (f x) + b • (f y) : hf.2 hx.1 hy.1 ha hb hab ... ≤ a • r + b • r : add_le_add (smul_le_smul_of_nonneg hx.2 ha) (smul_le_smul_of_nonneg hy.2 hb) ... ≤ r : by simp [←add_smul, hab] end lemma concave_on.concave_le [ordered_module ℝ β] {f : E → β} (hf : concave_on s f) (r : β) : convex {x ∈ s | r ≤ f x} := @convex_on.convex_le _ _ _ _ (order_dual β) _ _ _ f hf r lemma convex_on.convex_lt {γ : Type*} [ordered_cancel_add_comm_monoid γ] [module ℝ γ] [ordered_module ℝ γ] {f : E → γ} (hf : convex_on s f) (r : γ) : convex {x ∈ s | f x < r} := begin intros a b as bs xa xb hxa hxb hxaxb, refine ⟨hf.1 as.1 bs.1 hxa hxb hxaxb, _⟩, by_cases H : xa = 0, { have H' : xb = 1 := by rwa [H, zero_add] at hxaxb, rw [H, H', zero_smul, one_smul, zero_add], exact bs.2 }, { calc f (xa • a + xb • b) ≤ xa • (f a) + xb • (f b) : hf.2 as.1 bs.1 hxa hxb hxaxb ... < xa • r + xb • (f b) : (add_lt_add_iff_right (xb • (f b))).mpr (smul_lt_smul_of_pos as.2 (lt_of_le_of_ne hxa (ne.symm H))) ... ≤ xa • r + xb • r : (add_le_add_iff_left (xa • r)).mpr (smul_le_smul_of_nonneg bs.2.le hxb) ... = r : by simp only [←add_smul, hxaxb, one_smul] } end lemma concave_on.convex_lt {γ : Type*} [ordered_cancel_add_comm_monoid γ] [module ℝ γ] [ordered_module ℝ γ] {f : E → γ} (hf : concave_on s f) (r : γ) : convex {x ∈ s | r < f x} := @convex_on.convex_lt _ _ _ _ (order_dual γ) _ _ _ f hf r lemma convex_on.convex_epigraph {γ : Type*} [ordered_add_comm_group γ] [module ℝ γ] [ordered_module ℝ γ] {f : E → γ} (hf : convex_on s f) : convex {p : E × γ | p.1 ∈ s ∧ f p.1 ≤ p.2} := begin rintros ⟨x, r⟩ ⟨y, t⟩ ⟨hx, hr⟩ ⟨hy, ht⟩ a b ha hb hab, refine ⟨hf.1 hx hy ha hb hab, _⟩, calc f (a • x + b • y) ≤ a • f x + b • f y : hf.2 hx hy ha hb hab ... ≤ a • r + b • t : add_le_add (smul_le_smul_of_nonneg hr ha) (smul_le_smul_of_nonneg ht hb) end lemma concave_on.convex_hypograph {γ : Type*} [ordered_add_comm_group γ] [module ℝ γ] [ordered_module ℝ γ] {f : E → γ} (hf : concave_on s f) : convex {p : E × γ | p.1 ∈ s ∧ p.2 ≤ f p.1} := @convex_on.convex_epigraph _ _ _ _ (order_dual γ) _ _ _ f hf lemma convex_on_iff_convex_epigraph {γ : Type*} [ordered_add_comm_group γ] [module ℝ γ] [ordered_module ℝ γ] {f : E → γ} : convex_on s f ↔ convex {p : E × γ | p.1 ∈ s ∧ f p.1 ≤ p.2} := begin refine ⟨convex_on.convex_epigraph, λ h, ⟨_, _⟩⟩, { assume x y hx hy a b ha hb hab, exact (@h (x, f x) (y, f y) ⟨hx, le_refl _⟩ ⟨hy, le_refl _⟩ a b ha hb hab).1 }, { assume x y hx hy a b ha hb hab, exact (@h (x, f x) (y, f y) ⟨hx, le_refl _⟩ ⟨hy, le_refl _⟩ a b ha hb hab).2 } end lemma concave_on_iff_convex_hypograph {γ : Type*} [ordered_add_comm_group γ] [module ℝ γ] [ordered_module ℝ γ] {f : E → γ} : concave_on s f ↔ convex {p : E × γ | p.1 ∈ s ∧ p.2 ≤ f p.1} := @convex_on_iff_convex_epigraph _ _ _ _ (order_dual γ) _ _ _ f /- A linear map is convex. -/ lemma linear_map.convex_on (f : E →ₗ[ℝ] β) {s : set E} (hs : convex s) : convex_on s f := ⟨hs, λ _ _ _ _ _ _ _ _ _, by rw [f.map_add, f.map_smul, f.map_smul]⟩ /- A linear map is concave. -/ lemma linear_map.concave_on (f : E →ₗ[ℝ] β) {s : set E} (hs : convex s) : concave_on s f := ⟨hs, λ _ _ _ _ _ _ _ _ _, by rw [f.map_add, f.map_smul, f.map_smul]⟩ /-- If a function is convex on `s`, it remains convex when precomposed by an affine map. -/ lemma convex_on.comp_affine_map {f : F → β} (g : E →ᵃ[ℝ] F) {s : set F} (hf : convex_on s f) : convex_on (g ⁻¹' s) (f ∘ g) := begin refine ⟨hf.1.affine_preimage _,_⟩, intros x y xs ys a b ha hb hab, calc (f ∘ g) (a • x + b • y) = f (g (a • x + b • y)) : rfl ... = f (a • (g x) + b • (g y)) : by rw [convex.combo_affine_apply hab] ... ≤ a • f (g x) + b • f (g y) : hf.2 xs ys ha hb hab ... = a • (f ∘ g) x + b • (f ∘ g) y : rfl end /-- If a function is concave on `s`, it remains concave when precomposed by an affine map. -/ lemma concave_on.comp_affine_map {f : F → β} (g : E →ᵃ[ℝ] F) {s : set F} (hf : concave_on s f) : concave_on (g ⁻¹' s) (f ∘ g) := @convex_on.comp_affine_map _ _ _ _ _ _ (order_dual β) _ _ f g s hf /-- If `g` is convex on `s`, so is `(g ∘ f)` on `f ⁻¹' s` for a linear `f`. -/ lemma convex_on.comp_linear_map {g : F → β} {s : set F} (hg : convex_on s g) (f : E →ₗ[ℝ] F) : convex_on (f ⁻¹' s) (g ∘ f) := hg.comp_affine_map f.to_affine_map /-- If `g` is concave on `s`, so is `(g ∘ f)` on `f ⁻¹' s` for a linear `f`. -/ lemma concave_on.comp_linear_map {g : F → β} {s : set F} (hg : concave_on s g) (f : E →ₗ[ℝ] F) : concave_on (f ⁻¹' s) (g ∘ f) := hg.comp_affine_map f.to_affine_map /-- If a function is convex on `s`, it remains convex after a translation. -/ lemma convex_on.translate_right {f : E → β} {s : set E} {a : E} (hf : convex_on s f) : convex_on ((λ z, a + z) ⁻¹' s) (f ∘ (λ z, a + z)) := hf.comp_affine_map $ affine_map.const ℝ E a +ᵥ affine_map.id ℝ E /-- If a function is concave on `s`, it remains concave after a translation. -/ lemma concave_on.translate_right {f : E → β} {s : set E} {a : E} (hf : concave_on s f) : concave_on ((λ z, a + z) ⁻¹' s) (f ∘ (λ z, a + z)) := hf.comp_affine_map $ affine_map.const ℝ E a +ᵥ affine_map.id ℝ E /-- If a function is convex on `s`, it remains convex after a translation. -/ lemma convex_on.translate_left {f : E → β} {s : set E} {a : E} (hf : convex_on s f) : convex_on ((λ z, a + z) ⁻¹' s) (f ∘ (λ z, z + a)) := by simpa only [add_comm] using hf.translate_right /-- If a function is concave on `s`, it remains concave after a translation. -/ lemma concave_on.translate_left {f : E → β} {s : set E} {a : E} (hf : concave_on s f) : concave_on ((λ z, a + z) ⁻¹' s) (f ∘ (λ z, z + a)) := by simpa only [add_comm] using hf.translate_right end functions /-! ### Center of mass -/ section center_mass /-- Center of mass of a finite collection of points with prescribed weights. Note that we require neither `0 ≤ w i` nor `∑ w = 1`. -/ noncomputable def finset.center_mass (t : finset ι) (w : ι → ℝ) (z : ι → E) : E := (∑ i in t, w i)⁻¹ • (∑ i in t, w i • z i) variables (i j : ι) (c : ℝ) (t : finset ι) (w : ι → ℝ) (z : ι → E) open finset lemma finset.center_mass_empty : (∅ : finset ι).center_mass w z = 0 := by simp only [center_mass, sum_empty, smul_zero] lemma finset.center_mass_pair (hne : i ≠ j) : ({i, j} : finset ι).center_mass w z = (w i / (w i + w j)) • z i + (w j / (w i + w j)) • z j := by simp only [center_mass, sum_pair hne, smul_add, (mul_smul _ _ _).symm, div_eq_inv_mul] variable {w} lemma finset.center_mass_insert (ha : i ∉ t) (hw : ∑ j in t, w j ≠ 0) : (insert i t).center_mass w z = (w i / (w i + ∑ j in t, w j)) • z i + ((∑ j in t, w j) / (w i + ∑ j in t, w j)) • t.center_mass w z := begin simp only [center_mass, sum_insert ha, smul_add, (mul_smul _ _ _).symm, ← div_eq_inv_mul], congr' 2, rw [div_mul_eq_mul_div, mul_inv_cancel hw, one_div] end lemma finset.center_mass_singleton (hw : w i ≠ 0) : ({i} : finset ι).center_mass w z = z i := by rw [center_mass, sum_singleton, sum_singleton, ← mul_smul, inv_mul_cancel hw, one_smul] lemma finset.center_mass_eq_of_sum_1 (hw : ∑ i in t, w i = 1) : t.center_mass w z = ∑ i in t, w i • z i := by simp only [finset.center_mass, hw, inv_one, one_smul] lemma finset.center_mass_smul : t.center_mass w (λ i, c • z i) = c • t.center_mass w z := by simp only [finset.center_mass, finset.smul_sum, (mul_smul _ _ _).symm, mul_comm c, mul_assoc] /-- A convex combination of two centers of mass is a center of mass as well. This version deals with two different index types. -/ lemma finset.center_mass_segment' (s : finset ι) (t : finset ι') (ws : ι → ℝ) (zs : ι → E) (wt : ι' → ℝ) (zt : ι' → E) (hws : ∑ i in s, ws i = 1) (hwt : ∑ i in t, wt i = 1) (a b : ℝ) (hab : a + b = 1) : a • s.center_mass ws zs + b • t.center_mass wt zt = (s.map function.embedding.inl ∪ t.map function.embedding.inr).center_mass (sum.elim (λ i, a * ws i) (λ j, b * wt j)) (sum.elim zs zt) := begin rw [s.center_mass_eq_of_sum_1 _ hws, t.center_mass_eq_of_sum_1 _ hwt, smul_sum, smul_sum, ← finset.sum_sum_elim, finset.center_mass_eq_of_sum_1], { congr' with ⟨⟩; simp only [sum.elim_inl, sum.elim_inr, mul_smul] }, { rw [sum_sum_elim, ← mul_sum, ← mul_sum, hws, hwt, mul_one, mul_one, hab] } end /-- A convex combination of two centers of mass is a center of mass as well. This version works if two centers of mass share the set of original points. -/ lemma finset.center_mass_segment (s : finset ι) (w₁ w₂ : ι → ℝ) (z : ι → E) (hw₁ : ∑ i in s, w₁ i = 1) (hw₂ : ∑ i in s, w₂ i = 1) (a b : ℝ) (hab : a + b = 1) : a • s.center_mass w₁ z + b • s.center_mass w₂ z = s.center_mass (λ i, a * w₁ i + b * w₂ i) z := have hw : ∑ i in s, (a * w₁ i + b * w₂ i) = 1, by simp only [mul_sum.symm, sum_add_distrib, mul_one, *], by simp only [finset.center_mass_eq_of_sum_1, smul_sum, sum_add_distrib, add_smul, mul_smul, *] lemma finset.center_mass_ite_eq (hi : i ∈ t) : t.center_mass (λ j, if (i = j) then 1 else 0) z = z i := begin rw [finset.center_mass_eq_of_sum_1], transitivity ∑ j in t, if (i = j) then z i else 0, { congr' with i, split_ifs, exacts [h ▸ one_smul _ _, zero_smul _ _] }, { rw [sum_ite_eq, if_pos hi] }, { rw [sum_ite_eq, if_pos hi] } end variables {t w} lemma finset.center_mass_subset {t' : finset ι} (ht : t ⊆ t') (h : ∀ i ∈ t', i ∉ t → w i = 0) : t.center_mass w z = t'.center_mass w z := begin rw [center_mass, sum_subset ht h, smul_sum, center_mass, smul_sum], apply sum_subset ht, assume i hit' hit, rw [h i hit' hit, zero_smul, smul_zero] end lemma finset.center_mass_filter_ne_zero : (t.filter (λ i, w i ≠ 0)).center_mass w z = t.center_mass w z := finset.center_mass_subset z (filter_subset _ _) $ λ i hit hit', by simpa only [hit, mem_filter, true_and, ne.def, not_not] using hit' variable {z} /-- The center of mass of a finite subset of a convex set belongs to the set provided that all weights are non-negative, and the total weight is positive. -/ lemma convex.center_mass_mem (hs : convex s) : (∀ i ∈ t, 0 ≤ w i) → (0 < ∑ i in t, w i) → (∀ i ∈ t, z i ∈ s) → t.center_mass w z ∈ s := begin induction t using finset.induction with i t hi ht, { simp [lt_irrefl] }, intros h₀ hpos hmem, have zi : z i ∈ s, from hmem _ (mem_insert_self _ _), have hs₀ : ∀ j ∈ t, 0 ≤ w j, from λ j hj, h₀ j $ mem_insert_of_mem hj, rw [sum_insert hi] at hpos, by_cases hsum_t : ∑ j in t, w j = 0, { have ws : ∀ j ∈ t, w j = 0, from (sum_eq_zero_iff_of_nonneg hs₀).1 hsum_t, have wz : ∑ j in t, w j • z j = 0, from sum_eq_zero (λ i hi, by simp [ws i hi]), simp only [center_mass, sum_insert hi, wz, hsum_t, add_zero], simp only [hsum_t, add_zero] at hpos, rw [← mul_smul, inv_mul_cancel (ne_of_gt hpos), one_smul], exact zi }, { rw [finset.center_mass_insert _ _ _ hi hsum_t], refine convex_iff_div.1 hs zi (ht hs₀ _ _) _ (sum_nonneg hs₀) hpos, { exact lt_of_le_of_ne (sum_nonneg hs₀) (ne.symm hsum_t) }, { intros j hj, exact hmem j (mem_insert_of_mem hj) }, { exact h₀ _ (mem_insert_self _ _) } } end lemma convex.sum_mem (hs : convex s) (h₀ : ∀ i ∈ t, 0 ≤ w i) (h₁ : ∑ i in t, w i = 1) (hz : ∀ i ∈ t, z i ∈ s) : ∑ i in t, w i • z i ∈ s := by simpa only [h₁, center_mass, inv_one, one_smul] using hs.center_mass_mem h₀ (h₁.symm ▸ zero_lt_one) hz lemma convex_iff_sum_mem : convex s ↔ (∀ (t : finset E) (w : E → ℝ), (∀ i ∈ t, 0 ≤ w i) → ∑ i in t, w i = 1 → (∀ x ∈ t, x ∈ s) → ∑ x in t, w x • x ∈ s ) := begin refine ⟨λ hs t w hw₀ hw₁ hts, hs.sum_mem hw₀ hw₁ hts, _⟩, intros h x y hx hy a b ha hb hab, by_cases h_cases: x = y, { rw [h_cases, ←add_smul, hab, one_smul], exact hy }, { convert h {x, y} (λ z, if z = y then b else a) _ _ _, { simp only [sum_pair h_cases, if_neg h_cases, if_pos rfl] }, { simp_intros i hi, cases hi; subst i; simp [ha, hb, if_neg h_cases] }, { simp only [sum_pair h_cases, if_neg h_cases, if_pos rfl, hab] }, { simp_intros i hi, cases hi; subst i; simp [hx, hy, if_neg h_cases] } } end /-- Jensen's inequality, `finset.center_mass` version. -/ lemma convex_on.map_center_mass_le {f : E → ℝ} (hf : convex_on s f) (h₀ : ∀ i ∈ t, 0 ≤ w i) (hpos : 0 < ∑ i in t, w i) (hmem : ∀ i ∈ t, z i ∈ s) : f (t.center_mass w z) ≤ t.center_mass w (f ∘ z) := begin have hmem' : ∀ i ∈ t, (z i, (f ∘ z) i) ∈ {p : E × ℝ | p.1 ∈ s ∧ f p.1 ≤ p.2}, from λ i hi, ⟨hmem i hi, le_refl _⟩, convert (hf.convex_epigraph.center_mass_mem h₀ hpos hmem').2; simp only [center_mass, function.comp, prod.smul_fst, prod.fst_sum, prod.smul_snd, prod.snd_sum] end /-- Jensen's inequality, `finset.sum` version. -/ lemma convex_on.map_sum_le {f : E → ℝ} (hf : convex_on s f) (h₀ : ∀ i ∈ t, 0 ≤ w i) (h₁ : ∑ i in t, w i = 1) (hmem : ∀ i ∈ t, z i ∈ s) : f (∑ i in t, w i • z i) ≤ ∑ i in t, w i * (f (z i)) := by simpa only [center_mass, h₁, inv_one, one_smul] using hf.map_center_mass_le h₀ (h₁.symm ▸ zero_lt_one) hmem /-- If a function `f` is convex on `s` takes value `y` at the center of mass of some points `z i ∈ s`, then for some `i` we have `y ≤ f (z i)`. -/ lemma convex_on.exists_ge_of_center_mass {f : E → ℝ} (h : convex_on s f) (hw₀ : ∀ i ∈ t, 0 ≤ w i) (hws : 0 < ∑ i in t, w i) (hz : ∀ i ∈ t, z i ∈ s) : ∃ i ∈ t, f (t.center_mass w z) ≤ f (z i) := begin set y := t.center_mass w z, have : f y ≤ t.center_mass w (f ∘ z) := h.map_center_mass_le hw₀ hws hz, rw ← sum_filter_ne_zero at hws, rw [← finset.center_mass_filter_ne_zero (f ∘ z), center_mass, smul_eq_mul, ← div_eq_inv_mul, le_div_iff hws, mul_sum] at this, replace : ∃ i ∈ t.filter (λ i, w i ≠ 0), f y * w i ≤ w i • (f ∘ z) i := exists_le_of_sum_le (nonempty_of_sum_ne_zero (ne_of_gt hws)) this, rcases this with ⟨i, hi, H⟩, rw [mem_filter] at hi, use [i, hi.1], simp only [smul_eq_mul, mul_comm (w i)] at H, refine (mul_le_mul_right _).1 H, exact lt_of_le_of_ne (hw₀ i hi.1) hi.2.symm end end center_mass /-! ### Convex hull -/ section convex_hull variable {t : set E} /-- The convex hull of a set `s` is the minimal convex set that includes `s`. -/ def convex_hull : closure_operator (set E) := closure_operator.mk₃ (λ s, ⋂ (t : set E) (hst : s ⊆ t) (ht : convex t), t) convex (λ s, set.subset_Inter (λ t, set.subset_Inter $ λ hst, set.subset_Inter $ λ ht, hst)) (λ s, convex_Inter $ λ t, convex_Inter $ λ ht, convex_Inter id) (λ s t hst ht, set.Inter_subset_of_subset t $ set.Inter_subset_of_subset hst $ set.Inter_subset _ ht) variable (s) lemma subset_convex_hull : s ⊆ convex_hull s := convex_hull.le_closure s lemma convex_convex_hull : convex (convex_hull s) := closure_operator.closure_mem_mk₃ s variable {s} lemma convex_hull_min (hst : s ⊆ t) (ht : convex t) : convex_hull s ⊆ t := closure_operator.closure_le_mk₃_iff (show s ≤ t, from hst) ht lemma convex_hull_mono (hst : s ⊆ t) : convex_hull s ⊆ convex_hull t := convex_hull.monotone hst lemma convex.convex_hull_eq {s : set E} (hs : convex s) : convex_hull s = s := closure_operator.mem_mk₃_closed hs @[simp] lemma convex_hull_empty : convex_hull (∅ : set E) = ∅ := convex_empty.convex_hull_eq @[simp] lemma convex_hull_empty_iff : convex_hull s = ∅ ↔ s = ∅ := begin split, { intro h, rw [←set.subset_empty_iff, ←h], exact subset_convex_hull _ }, { rintro rfl, exact convex_hull_empty } end @[simp] lemma convex_hull_nonempty_iff : (convex_hull s).nonempty ↔ s.nonempty := begin rw [←ne_empty_iff_nonempty, ←ne_empty_iff_nonempty, ne.def, ne.def], exact not_congr convex_hull_empty_iff, end @[simp] lemma convex_hull_singleton {x : E} : convex_hull ({x} : set E) = {x} := (convex_singleton x).convex_hull_eq lemma convex.convex_remove_iff_not_mem_convex_hull_remove {s : set E} (hs : convex s) (x : E) : convex (s \ {x}) ↔ x ∉ convex_hull (s \ {x}) := begin split, { rintro hsx hx, rw hsx.convex_hull_eq at hx, exact hx.2 (mem_singleton _) }, rintro hx, suffices h : s \ {x} = convex_hull (s \ {x}), { convert convex_convex_hull _ }, exact subset.antisymm (subset_convex_hull _) (λ y hy, ⟨convex_hull_min (diff_subset _ _) hs hy, by { rintro (rfl : y = x), exact hx hy }⟩), end lemma is_linear_map.image_convex_hull {f : E → F} (hf : is_linear_map ℝ f) : f '' (convex_hull s) = convex_hull (f '' s) := begin refine set.subset.antisymm _ _, { rw [set.image_subset_iff], exact convex_hull_min (set.image_subset_iff.1 $ subset_convex_hull $ f '' s) ((convex_convex_hull (f '' s)).is_linear_preimage hf) }, { exact convex_hull_min (set.image_subset _ $ subset_convex_hull s) ((convex_convex_hull s).is_linear_image hf) } end lemma linear_map.image_convex_hull (f : E →ₗ[ℝ] F) : f '' (convex_hull s) = convex_hull (f '' s) := f.is_linear.image_convex_hull lemma finset.center_mass_mem_convex_hull (t : finset ι) {w : ι → ℝ} (hw₀ : ∀ i ∈ t, 0 ≤ w i) (hws : 0 < ∑ i in t, w i) {z : ι → E} (hz : ∀ i ∈ t, z i ∈ s) : t.center_mass w z ∈ convex_hull s := (convex_convex_hull s).center_mass_mem hw₀ hws (λ i hi, subset_convex_hull s $ hz i hi) -- TODO : Do we need other versions of the next lemma? /-- Convex hull of `s` is equal to the set of all centers of masses of `finset`s `t`, `z '' t ⊆ s`. This version allows finsets in any type in any universe. -/ lemma convex_hull_eq (s : set E) : convex_hull s = {x : E | ∃ (ι : Type u') (t : finset ι) (w : ι → ℝ) (z : ι → E) (hw₀ : ∀ i ∈ t, 0 ≤ w i) (hw₁ : ∑ i in t, w i = 1) (hz : ∀ i ∈ t, z i ∈ s), t.center_mass w z = x} := begin refine subset.antisymm (convex_hull_min _ _) _, { intros x hx, use [punit, {punit.star}, λ _, 1, λ _, x, λ _ _, zero_le_one, finset.sum_singleton, λ _ _, hx], simp only [finset.center_mass, finset.sum_singleton, inv_one, one_smul] }, { rintros x y ⟨ι, sx, wx, zx, hwx₀, hwx₁, hzx, rfl⟩ ⟨ι', sy, wy, zy, hwy₀, hwy₁, hzy, rfl⟩ a b ha hb hab, rw [finset.center_mass_segment' _ _ _ _ _ _ hwx₁ hwy₁ _ _ hab], refine ⟨_, _, _, _, _, _, _, rfl⟩, { rintros i hi, rw [finset.mem_union, finset.mem_map, finset.mem_map] at hi, rcases hi with ⟨j, hj, rfl⟩|⟨j, hj, rfl⟩; simp only [sum.elim_inl, sum.elim_inr]; apply_rules [mul_nonneg, hwx₀, hwy₀] }, { simp [finset.sum_sum_elim, finset.mul_sum.symm, *] }, { intros i hi, rw [finset.mem_union, finset.mem_map, finset.mem_map] at hi, rcases hi with ⟨j, hj, rfl⟩|⟨j, hj, rfl⟩; apply_rules [hzx, hzy] } }, { rintros _ ⟨ι, t, w, z, hw₀, hw₁, hz, rfl⟩, exact t.center_mass_mem_convex_hull hw₀ (hw₁.symm ▸ zero_lt_one) hz } end /-- Maximum principle for convex functions. If a function `f` is convex on the convex hull of `s`, then `f` can't have a maximum on `convex_hull s` outside of `s`. -/ lemma convex_on.exists_ge_of_mem_convex_hull {f : E → ℝ} (hf : convex_on (convex_hull s) f) {x} (hx : x ∈ convex_hull s) : ∃ y ∈ s, f x ≤ f y := begin rw convex_hull_eq at hx, rcases hx with ⟨α, t, w, z, hw₀, hw₁, hz, rfl⟩, rcases hf.exists_ge_of_center_mass hw₀ (hw₁.symm ▸ zero_lt_one) (λ i hi, subset_convex_hull s (hz i hi)) with ⟨i, hit, Hi⟩, exact ⟨z i, hz i hit, Hi⟩ end lemma finset.convex_hull_eq (s : finset E) : convex_hull ↑s = {x : E | ∃ (w : E → ℝ) (hw₀ : ∀ y ∈ s, 0 ≤ w y) (hw₁ : ∑ y in s, w y = 1), s.center_mass w id = x} := begin refine subset.antisymm (convex_hull_min _ _) _, { intros x hx, rw [finset.mem_coe] at hx, refine ⟨_, _, _, finset.center_mass_ite_eq _ _ _ hx⟩, { intros, split_ifs, exacts [zero_le_one, le_refl 0] }, { rw [finset.sum_ite_eq, if_pos hx] } }, { rintros x y ⟨wx, hwx₀, hwx₁, rfl⟩ ⟨wy, hwy₀, hwy₁, rfl⟩ a b ha hb hab, rw [finset.center_mass_segment _ _ _ _ hwx₁ hwy₁ _ _ hab], refine ⟨_, _, _, rfl⟩, { rintros i hi, apply_rules [add_nonneg, mul_nonneg, hwx₀, hwy₀], }, { simp only [finset.sum_add_distrib, finset.mul_sum.symm, mul_one, *] } }, { rintros _ ⟨w, hw₀, hw₁, rfl⟩, exact s.center_mass_mem_convex_hull (λ x hx, hw₀ _ hx) (hw₁.symm ▸ zero_lt_one) (λ x hx, hx) } end lemma set.finite.convex_hull_eq {s : set E} (hs : finite s) : convex_hull s = {x : E | ∃ (w : E → ℝ) (hw₀ : ∀ y ∈ s, 0 ≤ w y) (hw₁ : ∑ y in hs.to_finset, w y = 1), hs.to_finset.center_mass w id = x} := by simpa only [set.finite.coe_to_finset, set.finite.mem_to_finset, exists_prop] using hs.to_finset.convex_hull_eq lemma convex_hull_eq_union_convex_hull_finite_subsets (s : set E) : convex_hull s = ⋃ (t : finset E) (w : ↑t ⊆ s), convex_hull ↑t := begin refine subset.antisymm _ _, { rw [convex_hull_eq.{u}], rintros x ⟨ι, t, w, z, hw₀, hw₁, hz, rfl⟩, simp only [mem_Union], refine ⟨t.image z, _, _⟩, { rw [finset.coe_image, image_subset_iff], exact hz }, { apply t.center_mass_mem_convex_hull hw₀, { simp only [hw₁, zero_lt_one] }, { exact λ i hi, finset.mem_coe.2 (finset.mem_image_of_mem _ hi) } } }, { exact Union_subset (λ i, Union_subset convex_hull_mono), }, end lemma is_linear_map.convex_hull_image {f : E → F} (hf : is_linear_map ℝ f) (s : set E) : convex_hull (f '' s) = f '' convex_hull s := set.subset.antisymm (convex_hull_min (image_subset _ (subset_convex_hull s)) $ (convex_convex_hull s).is_linear_image hf) (image_subset_iff.2 $ convex_hull_min (image_subset_iff.1 $ subset_convex_hull _) ((convex_convex_hull _).is_linear_preimage hf)) lemma linear_map.convex_hull_image (f : E →ₗ[ℝ] F) (s : set E) : convex_hull (f '' s) = f '' convex_hull s := f.is_linear.convex_hull_image s end convex_hull /-! ### Simplex -/ section simplex variables (ι) [fintype ι] {f : ι → ℝ} /-- The standard simplex in the space of functions `ι → ℝ` is the set of vectors with non-negative coordinates with total sum `1`. -/ def std_simplex (ι : Type*) [fintype ι] : set (ι → ℝ) := {f | (∀ x, 0 ≤ f x) ∧ ∑ x, f x = 1} lemma std_simplex_eq_inter : std_simplex ι = (⋂ x, {f | 0 ≤ f x}) ∩ {f | ∑ x, f x = 1} := by { ext f, simp only [std_simplex, set.mem_inter_eq, set.mem_Inter, set.mem_set_of_eq] } lemma convex_std_simplex : convex (std_simplex ι) := begin refine λ f g hf hg a b ha hb hab, ⟨λ x, _, _⟩, { apply_rules [add_nonneg, mul_nonneg, hf.1, hg.1] }, { erw [finset.sum_add_distrib, ← finset.smul_sum, ← finset.smul_sum, hf.2, hg.2, smul_eq_mul, smul_eq_mul, mul_one, mul_one], exact hab } end variable {ι} lemma ite_eq_mem_std_simplex (i : ι) : (λ j, ite (i = j) (1:ℝ) 0) ∈ std_simplex ι := ⟨λ j, by simp only; split_ifs; norm_num, by rw [finset.sum_ite_eq, if_pos (finset.mem_univ _)]⟩ /-- `std_simplex ι` is the convex hull of the canonical basis in `ι → ℝ`. -/ lemma convex_hull_basis_eq_std_simplex : convex_hull (range $ λ(i j:ι), if i = j then (1:ℝ) else 0) = std_simplex ι := begin refine subset.antisymm (convex_hull_min _ (convex_std_simplex ι)) _, { rintros _ ⟨i, rfl⟩, exact ite_eq_mem_std_simplex i }, { rintros w ⟨hw₀, hw₁⟩, rw [pi_eq_sum_univ w, ← finset.univ.center_mass_eq_of_sum_1 _ hw₁], exact finset.univ.center_mass_mem_convex_hull (λ i hi, hw₀ i) (hw₁.symm ▸ zero_lt_one) (λ i hi, mem_range_self i) } end variable {ι} /-- The convex hull of a finite set is the image of the standard simplex in `s → ℝ` under the linear map sending each function `w` to `∑ x in s, w x • x`. Since we have no sums over finite sets, we use sum over `@finset.univ _ hs.fintype`. The map is defined in terms of operations on `(s → ℝ) →ₗ[ℝ] ℝ` so that later we will not need to prove that this map is linear. -/ lemma set.finite.convex_hull_eq_image {s : set E} (hs : finite s) : convex_hull s = by haveI := hs.fintype; exact (⇑(∑ x : s, (@linear_map.proj ℝ s _ (λ i, ℝ) _ _ x).smul_right x.1)) '' (std_simplex s) := begin rw [← convex_hull_basis_eq_std_simplex, ← linear_map.convex_hull_image, ← set.range_comp, (∘)], apply congr_arg, convert subtype.range_coe.symm, ext x, simp [linear_map.sum_apply, ite_smul, finset.filter_eq] end /-- All values of a function `f ∈ std_simplex ι` belong to `[0, 1]`. -/ lemma mem_Icc_of_mem_std_simplex (hf : f ∈ std_simplex ι) (x) : f x ∈ I := ⟨hf.1 x, hf.2 ▸ finset.single_le_sum (λ y hy, hf.1 y) (finset.mem_univ x)⟩ end simplex
22f35edfa049bc27b3c22a65ed4a8efa515d1c29
cf39355caa609c0f33405126beee2739aa3cb77e
/library/init/meta/contradiction_tactic.lean
cb4c422f149011f128d0d27876947e8cf2fb2533
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
2,741
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.tactic init.function namespace tactic open expr tactic decidable environment private meta def contra_p_not_p : list expr → list expr → tactic unit | [] Hs := failed | (H1 :: Rs) Hs := do t ← (extract_opt_auto_param <$> infer_type H1) >>= whnf, (do a ← match_not t, H2 ← find_same_type a Hs, tgt ← target, pr ← mk_app `absurd [tgt, H2, H1], exact pr) <|> contra_p_not_p Rs Hs private meta def contra_false : list expr → tactic unit | [] := failed | (H :: Hs) := do t ← extract_opt_auto_param <$> infer_type H, if is_false t then do tgt ← target, pr ← mk_app `false.rec [tgt, H], exact pr else contra_false Hs private meta def contra_not_a_refl_rel_a : list expr → tactic unit | [] := failed | (H :: Hs) := do t ← (extract_opt_auto_param <$> infer_type H) >>= head_beta, (do (lhs, rhs) ← match_ne t, unify lhs rhs, tgt ← target, refl_pr ← mk_app `eq.refl [lhs], mk_app `absurd [tgt, refl_pr, H] >>= exact) <|> (do p ← match_not t, (refl_lemma, lhs, rhs) ← match_refl_app p, unify lhs rhs, tgt ← target, refl_pr ← mk_app refl_lemma [lhs], mk_app `absurd [tgt, refl_pr, H] >>= exact) <|> contra_not_a_refl_rel_a Hs private meta def contra_constructor_eq : list expr → tactic unit | [] := failed | (H :: Hs) := do t ← (extract_opt_auto_param <$> infer_type H) >>= whnf, match t with | `((%%lhs_0 : %%α) = %%rhs_0) := do env ← get_env, lhs ← whnf lhs_0, rhs ← whnf rhs_0, if is_constructor_app env lhs ∧ is_constructor_app env rhs ∧ const_name (get_app_fn lhs) ≠ const_name (get_app_fn rhs) then do tgt ← target, I_name ← return $ name.get_prefix (const_name (get_app_fn lhs)), pr ← mk_app (I_name <.> "no_confusion") [tgt, lhs, rhs, H], exact pr else contra_constructor_eq Hs | _ := contra_constructor_eq Hs end meta def contradiction : tactic unit := do try intro1, ctx ← local_context, (contra_false ctx <|> contra_not_a_refl_rel_a ctx <|> contra_p_not_p ctx ctx <|> contra_constructor_eq ctx <|> fail "contradiction tactic failed") meta def exfalso : tactic unit := do fail_if_no_goals, assert `Hfalse (expr.const `false []), swap, contradiction end tactic
8aaaf69e3cb96f30aec89e2abe7c02cd51b9c58c
2731214ea32f2a1a985300e281fb3117640a16c3
/portmanteau_open_equiv_closed.lean
d89536bd5ff359157bc0681ac6a91a8b03a8cca3
[ "Apache-2.0" ]
permissive
kkytola/lean_portmanteau
5d6a156db959974ebc4f5bed9118a7a2438a33fa
ac55eb4e24be43032cbc082e2b68d8fb8bd63f22
refs/heads/main
1,686,107,117,334
1,625,177,052,000
1,625,177,052,000
381,514,032
1
0
null
null
null
null
UTF-8
Lean
false
false
3,330
lean
/- Copyright (c) 2021 Kalle Kytölä. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kalle Kytölä -/ import portmanteau_definitions import portmanteau_topological_lemmas import portmanteau_proba_lemmas noncomputable theory open measure_theory open filter namespace portmanteau section portmanteau_open_equiv_closed variables {α : Type} [topological_space α] notation `borel_measure`(α) := @measure_theory.measure α (borel α) notation `borel_set`(α) E := (borel α).measurable_set' E lemma portmanteau_open_imp_closed_cond (μseq : ℕ → (borel_measure(α))) (μseq_fin : ∀ (n : ℕ) , @probability_measure α (borel(α)) (μseq(n))) (μ : borel_measure(α)) (μ_fin : @probability_measure α (borel(α)) μ) : portmanteau_open μseq μ → portmanteau_closed μseq μ := begin intros hopcond F F_clos , set G := Fᶜ with hG , have G_open : is_open G := is_open_compl_iff.mpr F_clos , specialize hopcond G G_open , rw hG at hopcond , have eq : μ Fᶜ = 1 - μ F := @proba_compl α (borel(α)) F μ μ_fin (closed_imp_borel F_clos) , have eq_seq : (λ n , (μseq(n)) Fᶜ) = (λ n , 1 - (μseq(n)) F) , { funext n , exact @proba_compl α (borel(α)) F (μseq(n)) (μseq_fin(n)) (closed_imp_borel F_clos) , } , rw [eq , eq_seq] at hopcond , rw liminf_const_sub 1 (ennreal.one_ne_top) at hopcond , have le₁ : μ(F) ≤ 1 := proba_le_one μ F , have le₂ : limsup_enn (λ n , (μseq(n))(F)) ≤ 1 := limsup_le_of_le_ennreal (λ n , proba_le_one (μseq(n)) F) , exact le_of_self_sub_le_self_sub_ennreal 1 _ _ ennreal.one_ne_top le₁ le₂ hopcond , end lemma portmanteau_closed_imp_open_cond (μseq : ℕ → (borel_measure(α))) (μseq_fin : ∀ (n : ℕ) , @probability_measure α (borel(α)) (μseq(n))) (μ : borel_measure(α)) (μ_fin : @probability_measure α (borel(α)) μ) : portmanteau_closed μseq μ → portmanteau_open μseq μ := begin intros hclcond G G_open , set F := Gᶜ with hF , have F_closed : is_closed F := is_closed_compl_iff.mpr G_open , specialize hclcond F F_closed , rw hF at hclcond , have eq : μ Gᶜ = 1 - μ G := @proba_compl α (borel(α)) G μ μ_fin (open_imp_borel G_open) , have eq_seq : (λ n , (μseq(n)) Gᶜ) = (λ n , 1 - (μseq(n)) G) , { funext n , exact @proba_compl α (borel(α)) G (μseq(n)) (μseq_fin(n)) (open_imp_borel G_open) , } , rw [eq , eq_seq] at hclcond , rw limsup_const_sub 1 (ennreal.one_ne_top) at hclcond , have le₁ : μ(G) ≤ 1 := proba_le_one μ G , have le₂ : liminf_enn (λ n , (μseq(n))(G)) ≤ 1 := liminf_le_of_le_ennreal (λ n , proba_le_one (μseq(n)) G) , exact le_of_self_sub_le_self_sub_ennreal 1 _ _ ennreal.one_ne_top le₂ le₁ hclcond , end lemma portmanteau_closed_and_open_cond_equivalent (μseq : ℕ → (borel_measure(α))) (μseq_fin : ∀ (n : ℕ) , @probability_measure α (borel(α)) (μseq(n))) (μ : borel_measure(α)) (μ_fin : @probability_measure α (borel(α)) μ) : portmanteau_closed μseq μ ↔ portmanteau_open μseq μ := begin split , { exact portmanteau_closed_imp_open_cond μseq μseq_fin μ μ_fin , } , { exact portmanteau_open_imp_closed_cond μseq μseq_fin μ μ_fin , } , end end portmanteau_open_equiv_closed end portmanteau