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
0f03af1ac980fc24d9a2cdc3b15cfb197385cd70
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/topology/algebra/field.lean
59f014b248c50c1abd0455e8b6b718d60a7695d2
[ "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
4,735
lean
/- Copyright (c) 2021 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Scott Morrison -/ import topology.algebra.ring import topology.algebra.group_with_zero /-! # Topological fields A topological division ring is a topological ring whose inversion function is continuous at every non-zero element. -/ namespace topological_ring open topological_space function variables (R : Type*) [ring R] variables [topological_space R] /-- The induced topology on units of a topological ring. This is not a global instance since other topologies could be relevant. Instead there is a class `induced_units` asserting that something equivalent to this construction holds. -/ def topological_space_units : topological_space Rˣ := induced (coe : Rˣ → R) ‹_› /-- Asserts the topology on units is the induced topology. Note: this is not always the correct topology. Another good candidate is the subspace topology of $R \times R$, with the units embedded via $u \mapsto (u, u^{-1})$. These topologies are not (propositionally) equal in general. -/ class induced_units [t : topological_space $ Rˣ] : Prop := (top_eq : t = induced (coe : Rˣ → R) ‹_›) variables [topological_space $ Rˣ] lemma units_topology_eq [induced_units R] : ‹topological_space Rˣ› = induced (coe : Rˣ → R) ‹_› := induced_units.top_eq lemma induced_units.continuous_coe [induced_units R] : continuous (coe : Rˣ → R) := (units_topology_eq R).symm ▸ continuous_induced_dom lemma units_embedding [induced_units R] : embedding (coe : Rˣ → R) := { induced := units_topology_eq R, inj := λ x y h, units.ext h } instance top_monoid_units [topological_ring R] [induced_units R] : has_continuous_mul Rˣ := ⟨begin let mulR := (λ (p : R × R), p.1*p.2), let mulRx := (λ (p : Rˣ × Rˣ), p.1*p.2), have key : coe ∘ mulRx = mulR ∘ (λ p, (p.1.val, p.2.val)), from rfl, rw [continuous_iff_le_induced, units_topology_eq R, prod_induced_induced, induced_compose, key, ← induced_compose], apply induced_mono, rw ← continuous_iff_le_induced, exact continuous_mul, end⟩ end topological_ring variables (K : Type*) [division_ring K] [topological_space K] /-- A topological division ring is a division ring with a topology where all operations are continuous, including inversion. -/ class topological_division_ring extends topological_ring K : Prop := (continuous_inv : ∀ x : K, x ≠ 0 → continuous_at (λ x : K, x⁻¹ : K → K) x) namespace topological_division_ring open filter set /-! In this section, we show that units of a topological division ring endowed with the induced topology form a topological group. These are not global instances because one could want another topology on units. To turn on this feature, use: ```lean local attribute [instance] topological_ring.topological_space_units topological_division_ring.units_top_group ``` -/ local attribute [instance] topological_ring.topological_space_units @[priority 100] instance induced_units : topological_ring.induced_units K := ⟨rfl⟩ variables [topological_division_ring K] lemma units_top_group : topological_group Kˣ := { continuous_inv := begin have : (coe : Kˣ → K) ∘ (λ x, x⁻¹ : Kˣ → Kˣ) = (λ x, x⁻¹ : K → K) ∘ (coe : Kˣ → K), from funext units.coe_inv', rw continuous_iff_continuous_at, intros x, rw [continuous_at, nhds_induced, nhds_induced, tendsto_iff_comap, comap_comm this], apply comap_mono, rw [← tendsto_iff_comap, units.coe_inv'], exact topological_division_ring.continuous_inv (x : K) x.ne_zero end , ..topological_ring.top_monoid_units K} local attribute [instance] units_top_group lemma continuous_units_inv : continuous (λ x : Kˣ, (↑(x⁻¹) : K)) := (topological_ring.induced_units.continuous_coe K).comp topological_group.continuous_inv end topological_division_ring section affine_homeomorph /-! This section is about affine homeomorphisms from a topological field `𝕜` to itself. Technically it does not require `𝕜` to be a topological field, a topological ring that happens to be a field is enough. -/ variables {𝕜 : Type*} [field 𝕜] [topological_space 𝕜] [topological_ring 𝕜] /-- The map `λ x, a * x + b`, as a homeomorphism from `𝕜` (a topological field) to itself, when `a ≠ 0`. -/ @[simps] def affine_homeomorph (a b : 𝕜) (h : a ≠ 0) : 𝕜 ≃ₜ 𝕜 := { to_fun := λ x, a * x + b, inv_fun := λ y, (y - b) / a, left_inv := λ x, by { simp only [add_sub_cancel], exact mul_div_cancel_left x h, }, right_inv := λ y, by { simp [mul_div_cancel' _ h], }, } end affine_homeomorph
1e1475a49d28fd5c3e7bf2fb27dc8fa3f4bdcbeb
8cb37a089cdb4af3af9d8bf1002b417e407a8e9e
/tests/lean/run/372c.lean
a5d7c580df7cd378ec45b572d4ad2daff81de8ad
[ "Apache-2.0" ]
permissive
kbuzzard/lean
ae3c3db4bb462d750dbf7419b28bafb3ec983ef7
ed1788fd674bb8991acffc8fca585ec746711928
refs/heads/master
1,620,983,366,617
1,618,937,600,000
1,618,937,600,000
359,886,396
1
0
Apache-2.0
1,618,936,987,000
1,618,936,987,000
null
UTF-8
Lean
false
false
165
lean
def foo (n : ℕ) := Type def beta (n : ℕ) : foo n := by unfold foo; exact ℕ → ℕ lemma baz (n : ℕ) : beta n := id example : ℕ := by apply baz <|> exact 0
ea47f21f5b45de6e3af01838d533b7a3ff4c4714
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/data/finset/lattice.lean
0ab7c3be88db447f838849fd18306ee27b6c5131
[ "Apache-2.0" ]
permissive
hamdysalah1/mathlib
b915f86b2503feeae268de369f1b16932321f097
95454452f6b3569bf967d35aab8d852b1ddf8017
refs/heads/master
1,677,154,116,545
1,611,797,994,000
1,611,797,994,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
27,870
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import data.finset.fold import data.multiset.lattice import order.order_dual import order.complete_lattice /-! # Lattice operations on finsets -/ variables {α β γ : Type*} namespace finset open multiset order_dual /-! ### sup -/ section sup variables [semilattice_sup_bot α] /-- Supremum of a finite set: `sup {a, b, c} f = f a ⊔ f b ⊔ f c` -/ def sup (s : finset β) (f : β → α) : α := s.fold (⊔) ⊥ f variables {s s₁ s₂ : finset β} {f : β → α} lemma sup_def : s.sup f = (s.1.map f).sup := rfl @[simp] lemma sup_empty : (∅ : finset β).sup f = ⊥ := fold_empty @[simp] lemma sup_insert [decidable_eq β] {b : β} : (insert b s : finset β).sup f = f b ⊔ s.sup f := fold_insert_idem @[simp] lemma sup_singleton {b : β} : ({b} : finset β).sup f = f b := sup_singleton lemma sup_union [decidable_eq β] : (s₁ ∪ s₂).sup f = s₁.sup f ⊔ s₂.sup f := finset.induction_on s₁ (by rw [empty_union, sup_empty, bot_sup_eq]) $ λ a s has ih, by rw [insert_union, sup_insert, sup_insert, ih, sup_assoc] theorem sup_congr {f g : β → α} (hs : s₁ = s₂) (hfg : ∀a∈s₂, f a = g a) : s₁.sup f = s₂.sup g := by subst hs; exact finset.fold_congr hfg @[simp] lemma sup_le_iff {a : α} : s.sup f ≤ a ↔ (∀b ∈ s, f b ≤ a) := begin apply iff.trans multiset.sup_le, simp only [multiset.mem_map, and_imp, exists_imp_distrib], exact ⟨λ k b hb, k _ _ hb rfl, λ k a' b hb h, h ▸ k _ hb⟩, end lemma sup_const {s : finset β} (h : s.nonempty) (c : α) : s.sup (λ _, c) = c := eq_of_forall_ge_iff $ λ b, sup_le_iff.trans h.forall_const lemma sup_le {a : α} : (∀b ∈ s, f b ≤ a) → s.sup f ≤ a := sup_le_iff.2 lemma le_sup {b : β} (hb : b ∈ s) : f b ≤ s.sup f := sup_le_iff.1 (le_refl _) _ hb lemma sup_mono_fun {g : β → α} (h : ∀b∈s, f b ≤ g b) : s.sup f ≤ s.sup g := sup_le (λ b hb, le_trans (h b hb) (le_sup hb)) lemma sup_mono (h : s₁ ⊆ s₂) : s₁.sup f ≤ s₂.sup f := sup_le $ assume b hb, le_sup (h hb) @[simp] lemma sup_lt_iff [is_total α (≤)] {a : α} (ha : ⊥ < a) : s.sup f < a ↔ (∀b ∈ s, f b < a) := by letI := classical.dec_eq β; from ⟨ λh b hb, lt_of_le_of_lt (le_sup hb) h, finset.induction_on s (by simp [ha]) (by simp {contextual := tt}) ⟩ lemma comp_sup_eq_sup_comp [semilattice_sup_bot γ] {s : finset β} {f : β → α} (g : α → γ) (g_sup : ∀ x y, g (x ⊔ y) = g x ⊔ g y) (bot : g ⊥ = ⊥) : g (s.sup f) = s.sup (g ∘ f) := by letI := classical.dec_eq β; from finset.induction_on s (by simp [bot]) (by simp [g_sup] {contextual := tt}) lemma comp_sup_eq_sup_comp_of_is_total [is_total α (≤)] {γ : Type} [semilattice_sup_bot γ] (g : α → γ) (mono_g : monotone g) (bot : g ⊥ = ⊥) : g (s.sup f) = s.sup (g ∘ f) := comp_sup_eq_sup_comp g mono_g.map_sup bot /-- Computating `sup` in a subtype (closed under `sup`) is the same as computing it in `α`. -/ lemma sup_coe {P : α → Prop} {Pbot : P ⊥} {Psup : ∀{{x y}}, P x → P y → P (x ⊔ y)} (t : finset β) (f : β → {x : α // P x}) : (@sup _ _ (subtype.semilattice_sup_bot Pbot Psup) t f : α) = t.sup (λ x, f x) := by { classical, rw [comp_sup_eq_sup_comp coe]; intros; refl } @[simp] lemma sup_to_finset {α β} [decidable_eq β] (s : finset α) (f : α → multiset β) : (s.sup f).to_finset = s.sup (λ x, (f x).to_finset) := comp_sup_eq_sup_comp multiset.to_finset to_finset_union rfl theorem subset_range_sup_succ (s : finset ℕ) : s ⊆ range (s.sup id).succ := λ n hn, mem_range.2 $ nat.lt_succ_of_le $ le_sup hn theorem exists_nat_subset_range (s : finset ℕ) : ∃n : ℕ, s ⊆ range n := ⟨_, s.subset_range_sup_succ⟩ lemma sup_subset {α β} [semilattice_sup_bot β] {s t : finset α} (hst : s ⊆ t) (f : α → β) : s.sup f ≤ t.sup f := by classical; calc t.sup f = (s ∪ t).sup f : by rw [finset.union_eq_right_iff_subset.mpr hst] ... = s.sup f ⊔ t.sup f : by rw finset.sup_union ... ≥ s.sup f : le_sup_left lemma sup_closed_of_sup_closed {s : set α} (t : finset α) (htne : t.nonempty) (h_subset : ↑t ⊆ s) (h : ∀⦃a b⦄, a ∈ s → b ∈ s → a ⊔ b ∈ s) : t.sup id ∈ s := begin classical, induction t using finset.induction_on with x t h₀ h₁, { exfalso, apply finset.not_nonempty_empty htne, }, { rw [finset.coe_insert, set.insert_subset] at h_subset, cases t.eq_empty_or_nonempty with hte htne, { subst hte, simp only [insert_emptyc_eq, id.def, finset.sup_singleton, h_subset], }, { rw [finset.sup_insert, id.def], exact h h_subset.1 (h₁ htne h_subset.2), }, }, end lemma sup_le_of_le_directed {α : Type*} [semilattice_sup_bot α] (s : set α) (hs : s.nonempty) (hdir : directed_on (≤) s) (t : finset α): (∀ x ∈ t, ∃ y ∈ s, x ≤ y) → ∃ x, x ∈ s ∧ t.sup id ≤ x := begin classical, apply finset.induction_on t, { simpa only [forall_prop_of_true, and_true, forall_prop_of_false, bot_le, not_false_iff, sup_empty, forall_true_iff, not_mem_empty], }, { intros a r har ih h, have incs : ↑r ⊆ ↑(insert a r), by { rw finset.coe_subset, apply finset.subset_insert, }, -- x ∈ s is above the sup of r obtain ⟨x, ⟨hxs, hsx_sup⟩⟩ := ih (λ x hx, h x $ incs hx), -- y ∈ s is above a obtain ⟨y, hys, hay⟩ := h a (finset.mem_insert_self a r), -- z ∈ s is above x and y obtain ⟨z, hzs, ⟨hxz, hyz⟩⟩ := hdir x hxs y hys, use [z, hzs], rw [sup_insert, id.def, _root_.sup_le_iff], exact ⟨le_trans hay hyz, le_trans hsx_sup hxz⟩, }, end end sup lemma sup_eq_supr [complete_lattice β] (s : finset α) (f : α → β) : s.sup f = (⨆a∈s, f a) := le_antisymm (finset.sup_le $ assume a ha, le_supr_of_le a $ le_supr _ ha) (supr_le $ assume a, supr_le $ assume ha, le_sup ha) lemma sup_eq_Sup [complete_lattice α] (s : finset α) : s.sup id = Sup s := by simp [Sup_eq_supr, sup_eq_supr] /-! ### inf -/ section inf variables [semilattice_inf_top α] /-- Infimum of a finite set: `inf {a, b, c} f = f a ⊓ f b ⊓ f c` -/ def inf (s : finset β) (f : β → α) : α := s.fold (⊓) ⊤ f variables {s s₁ s₂ : finset β} {f : β → α} lemma inf_def : s.inf f = (s.1.map f).inf := rfl @[simp] lemma inf_empty : (∅ : finset β).inf f = ⊤ := fold_empty lemma le_inf_iff {a : α} : a ≤ s.inf f ↔ ∀b ∈ s, a ≤ f b := @sup_le_iff (order_dual α) _ _ _ _ _ @[simp] lemma inf_insert [decidable_eq β] {b : β} : (insert b s : finset β).inf f = f b ⊓ s.inf f := fold_insert_idem @[simp] lemma inf_singleton {b : β} : ({b} : finset β).inf f = f b := inf_singleton lemma inf_union [decidable_eq β] : (s₁ ∪ s₂).inf f = s₁.inf f ⊓ s₂.inf f := @sup_union (order_dual α) _ _ _ _ _ _ theorem inf_congr {f g : β → α} (hs : s₁ = s₂) (hfg : ∀a∈s₂, f a = g a) : s₁.inf f = s₂.inf g := by subst hs; exact finset.fold_congr hfg lemma inf_le {b : β} (hb : b ∈ s) : s.inf f ≤ f b := le_inf_iff.1 (le_refl _) _ hb lemma le_inf {a : α} : (∀b ∈ s, a ≤ f b) → a ≤ s.inf f := le_inf_iff.2 lemma inf_mono_fun {g : β → α} (h : ∀b∈s, f b ≤ g b) : s.inf f ≤ s.inf g := le_inf (λ b hb, le_trans (inf_le hb) (h b hb)) lemma inf_mono (h : s₁ ⊆ s₂) : s₂.inf f ≤ s₁.inf f := le_inf $ assume b hb, inf_le (h hb) lemma lt_inf_iff [h : is_total α (≤)] {a : α} (ha : a < ⊤) : a < s.inf f ↔ (∀b ∈ s, a < f b) := @sup_lt_iff (order_dual α) _ _ _ _ (@is_total.swap α _ h) _ ha lemma comp_inf_eq_inf_comp [semilattice_inf_top γ] {s : finset β} {f : β → α} (g : α → γ) (g_inf : ∀ x y, g (x ⊓ y) = g x ⊓ g y) (top : g ⊤ = ⊤) : g (s.inf f) = s.inf (g ∘ f) := @comp_sup_eq_sup_comp (order_dual α) _ (order_dual γ) _ _ _ _ _ g_inf top lemma comp_inf_eq_inf_comp_of_is_total [h : is_total α (≤)] {γ : Type} [semilattice_inf_top γ] (g : α → γ) (mono_g : monotone g) (top : g ⊤ = ⊤) : g (s.inf f) = s.inf (g ∘ f) := comp_inf_eq_inf_comp g mono_g.map_inf top /-- Computating `inf` in a subtype (closed under `inf`) is the same as computing it in `α`. -/ lemma inf_coe {P : α → Prop} {Ptop : P ⊤} {Pinf : ∀{{x y}}, P x → P y → P (x ⊓ y)} (t : finset β) (f : β → {x : α // P x}) : (@inf _ _ (subtype.semilattice_inf_top Ptop Pinf) t f : α) = t.inf (λ x, f x) := by { classical, rw [comp_inf_eq_inf_comp coe]; intros; refl } end inf lemma inf_eq_infi [complete_lattice β] (s : finset α) (f : α → β) : s.inf f = (⨅a∈s, f a) := @sup_eq_supr _ (order_dual β) _ _ _ lemma inf_eq_Inf [complete_lattice α] (s : finset α) : s.inf id = Inf s := by simp [Inf_eq_infi, inf_eq_infi] /-! ### max and min of finite sets -/ section max_min variables [linear_order α] /-- Let `s` be a finset in a linear order. Then `s.max` is the maximum of `s` if `s` is not empty, and `none` otherwise. It belongs to `option α`. If you want to get an element of `α`, see `s.max'`. -/ protected def max : finset α → option α := fold (option.lift_or_get max) none some theorem max_eq_sup_with_bot (s : finset α) : s.max = @sup (with_bot α) α _ s some := rfl @[simp] theorem max_empty : (∅ : finset α).max = none := rfl @[simp] theorem max_insert {a : α} {s : finset α} : (insert a s).max = option.lift_or_get max (some a) s.max := fold_insert_idem @[simp] theorem max_singleton {a : α} : finset.max {a} = some a := by { rw [← insert_emptyc_eq], exact max_insert } theorem max_of_mem {s : finset α} {a : α} (h : a ∈ s) : ∃ b, b ∈ s.max := (@le_sup (with_bot α) _ _ _ _ _ h _ rfl).imp $ λ b, Exists.fst theorem max_of_nonempty {s : finset α} (h : s.nonempty) : ∃ a, a ∈ s.max := let ⟨a, ha⟩ := h in max_of_mem ha theorem max_eq_none {s : finset α} : s.max = none ↔ s = ∅ := ⟨λ h, s.eq_empty_or_nonempty.elim id (λ H, let ⟨a, ha⟩ := max_of_nonempty H in by rw h at ha; cases ha), λ h, h.symm ▸ max_empty⟩ theorem mem_of_max {s : finset α} : ∀ {a : α}, a ∈ s.max → a ∈ s := finset.induction_on s (λ _ H, by cases H) (λ b s _ (ih : ∀ {a}, a ∈ s.max → a ∈ s) a (h : a ∈ (insert b s).max), begin by_cases p : b = a, { induction p, exact mem_insert_self b s }, { cases option.lift_or_get_choice max_choice (some b) s.max with q q; rw [max_insert, q] at h, { cases h, cases p rfl }, { exact mem_insert_of_mem (ih h) } } end) theorem le_max_of_mem {s : finset α} {a b : α} (h₁ : a ∈ s) (h₂ : b ∈ s.max) : a ≤ b := by rcases @le_sup (with_bot α) _ _ _ _ _ h₁ _ rfl with ⟨b', hb, ab⟩; cases h₂.symm.trans hb; assumption /-- Let `s` be a finset in a linear order. Then `s.min` is the minimum of `s` if `s` is not empty, and `none` otherwise. It belongs to `option α`. If you want to get an element of `α`, see `s.min'`. -/ protected def min : finset α → option α := fold (option.lift_or_get min) none some theorem min_eq_inf_with_top (s : finset α) : s.min = @inf (with_top α) α _ s some := rfl @[simp] theorem min_empty : (∅ : finset α).min = none := rfl @[simp] theorem min_insert {a : α} {s : finset α} : (insert a s).min = option.lift_or_get min (some a) s.min := fold_insert_idem @[simp] theorem min_singleton {a : α} : finset.min {a} = some a := by { rw ← insert_emptyc_eq, exact min_insert } theorem min_of_mem {s : finset α} {a : α} (h : a ∈ s) : ∃ b, b ∈ s.min := (@inf_le (with_top α) _ _ _ _ _ h _ rfl).imp $ λ b, Exists.fst theorem min_of_nonempty {s : finset α} (h : s.nonempty) : ∃ a, a ∈ s.min := let ⟨a, ha⟩ := h in min_of_mem ha theorem min_eq_none {s : finset α} : s.min = none ↔ s = ∅ := ⟨λ h, s.eq_empty_or_nonempty.elim id (λ H, let ⟨a, ha⟩ := min_of_nonempty H in by rw h at ha; cases ha), λ h, h.symm ▸ min_empty⟩ theorem mem_of_min {s : finset α} : ∀ {a : α}, a ∈ s.min → a ∈ s := finset.induction_on s (λ _ H, by cases H) $ λ b s _ (ih : ∀ {a}, a ∈ s.min → a ∈ s) a (h : a ∈ (insert b s).min), begin by_cases p : b = a, { induction p, exact mem_insert_self b s }, { cases option.lift_or_get_choice min_choice (some b) s.min with q q; rw [min_insert, q] at h, { cases h, cases p rfl }, { exact mem_insert_of_mem (ih h) } } end theorem min_le_of_mem {s : finset α} {a b : α} (h₁ : b ∈ s) (h₂ : a ∈ s.min) : a ≤ b := by rcases @inf_le (with_top α) _ _ _ _ _ h₁ _ rfl with ⟨b', hb, ab⟩; cases h₂.symm.trans hb; assumption /-- Given a nonempty finset `s` in a linear order `α `, then `s.min' h` is its minimum, as an element of `α`, where `h` is a proof of nonemptiness. Without this assumption, use instead `s.min`, taking values in `option α`. -/ def min' (s : finset α) (H : s.nonempty) : α := @option.get _ s.min $ let ⟨k, hk⟩ := H in let ⟨b, hb⟩ := min_of_mem hk in by simp at hb; simp [hb] /-- Given a nonempty finset `s` in a linear order `α `, then `s.max' h` is its maximum, as an element of `α`, where `h` is a proof of nonemptiness. Without this assumption, use instead `s.max`, taking values in `option α`. -/ def max' (s : finset α) (H : s.nonempty) : α := @option.get _ s.max $ let ⟨k, hk⟩ := H in let ⟨b, hb⟩ := max_of_mem hk in by simp at hb; simp [hb] variables (s : finset α) (H : s.nonempty) theorem min'_mem : s.min' H ∈ s := mem_of_min $ by simp [min'] theorem min'_le (x) (H2 : x ∈ s) : s.min' ⟨x, H2⟩ ≤ x := min_le_of_mem H2 $ option.get_mem _ theorem le_min' (x) (H2 : ∀ y ∈ s, x ≤ y) : x ≤ s.min' H := H2 _ $ min'_mem _ _ /-- `{a}.min' _` is `a`. -/ @[simp] lemma min'_singleton (a : α) : ({a} : finset α).min' (singleton_nonempty _) = a := by simp [min'] theorem max'_mem : s.max' H ∈ s := mem_of_max $ by simp [max'] theorem le_max' (x) (H2 : x ∈ s) : x ≤ s.max' ⟨x, H2⟩ := le_max_of_mem H2 $ option.get_mem _ theorem max'_le (x) (H2 : ∀ y ∈ s, y ≤ x) : s.max' H ≤ x := H2 _ $ max'_mem _ _ /-- `{a}.max' _` is `a`. -/ @[simp] lemma max'_singleton (a : α) : ({a} : finset α).max' (singleton_nonempty _) = a := by simp [max'] theorem min'_lt_max' {i j} (H1 : i ∈ s) (H2 : j ∈ s) (H3 : i ≠ j) : s.min' ⟨i, H1⟩ < s.max' ⟨i, H1⟩ := begin rcases lt_trichotomy i j with H4 | H4 | H4, { have H5 := min'_le s i H1, have H6 := le_max' s j H2, apply lt_of_le_of_lt H5, apply lt_of_lt_of_le H4 H6 }, { cc }, { have H5 := min'_le s j H2, have H6 := le_max' s i H1, apply lt_of_le_of_lt H5, apply lt_of_lt_of_le H4 H6 } end /-- If there's more than 1 element, the min' is less than the max'. An alternate version of `min'_lt_max'` which is sometimes more convenient. -/ lemma min'_lt_max'_of_card (h₂ : 1 < card s) : s.min' (finset.card_pos.mp $ lt_trans zero_lt_one h₂) < s.max' (finset.card_pos.mp $ lt_trans zero_lt_one h₂) := begin apply lt_of_not_ge, intro a, apply not_le_of_lt h₂ (le_of_eq _), rw card_eq_one, use (max' s (finset.card_pos.mp $ lt_trans zero_lt_one h₂)), rw eq_singleton_iff_unique_mem, refine ⟨max'_mem _ _, λ t Ht, le_antisymm (le_max' s t Ht) (le_trans a (min'_le s t Ht))⟩, end lemma max'_eq_of_dual_min' {s : finset α} (hs : s.nonempty) : max' s hs = of_dual (min' (image to_dual s) (nonempty.image hs to_dual)) := begin rw [of_dual, to_dual, equiv.coe_fn_mk, equiv.coe_fn_symm_mk, id.def], simp_rw (@image_id (order_dual α) (s : finset (order_dual α))), refl, end lemma min'_eq_of_dual_max' {s : finset α} (hs : s.nonempty) : min' s hs = of_dual (max' (image to_dual s) (nonempty.image hs to_dual)) := begin rw [of_dual, to_dual, equiv.coe_fn_mk, equiv.coe_fn_symm_mk, id.def], simp_rw (@image_id (order_dual α) (s : finset (order_dual α))), refl, end @[simp] lemma of_dual_max_eq_min_of_dual {a b : α} : of_dual (max a b) = min (of_dual a) (of_dual b) := rfl @[simp] lemma of_dual_min_eq_max_of_dual {a b : α} : of_dual (min a b) = max (of_dual a) (of_dual b) := rfl end max_min section exists_max_min variables [linear_order α] lemma exists_max_image (s : finset β) (f : β → α) (h : s.nonempty) : ∃ x ∈ s, ∀ x' ∈ s, f x' ≤ f x := begin cases max_of_nonempty (h.image f) 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 lemma exists_min_image (s : finset β) (f : β → α) (h : s.nonempty) : ∃ x ∈ s, ∀ x' ∈ s, f x ≤ f x' := @exists_max_image (order_dual α) β _ s f h end exists_max_min end finset namespace multiset lemma count_sup [decidable_eq β] (s : finset α) (f : α → multiset β) (b : β) : count b (s.sup f) = s.sup (λa, count b (f a)) := begin letI := classical.dec_eq α, refine s.induction _ _, { exact count_zero _ }, { assume i s his ih, rw [finset.sup_insert, sup_eq_union, count_union, finset.sup_insert, ih], refl } end lemma mem_sup {α β} [decidable_eq β] {s : finset α} {f : α → multiset β} {x : β} : x ∈ s.sup f ↔ ∃ v ∈ s, x ∈ f v := begin classical, apply s.induction_on, { simp }, { intros a s has hxs, rw [finset.sup_insert, multiset.sup_eq_union, multiset.mem_union], split, { intro hxi, cases hxi with hf hf, { refine ⟨a, _, hf⟩, simp only [true_or, eq_self_iff_true, finset.mem_insert] }, { rcases hxs.mp hf with ⟨v, hv, hfv⟩, refine ⟨v, _, hfv⟩, simp only [hv, or_true, finset.mem_insert] } }, { rintros ⟨v, hv, hfv⟩, rw [finset.mem_insert] at hv, rcases hv with rfl | hv, { exact or.inl hfv }, { refine or.inr (hxs.mpr ⟨v, hv, hfv⟩) } } }, end end multiset namespace finset lemma mem_sup {α β} [decidable_eq β] {s : finset α} {f : α → finset β} {x : β} : x ∈ s.sup f ↔ ∃ v ∈ s, x ∈ f v := begin change _ ↔ ∃ v ∈ s, x ∈ (f v).val, rw [←multiset.mem_sup, ←multiset.mem_to_finset, sup_to_finset], simp_rw [val_to_finset], end lemma sup_eq_bUnion {α β} [decidable_eq β] (s : finset α) (t : α → finset β) : s.sup t = s.bUnion t := by { ext, rw [mem_sup, mem_bUnion], } end finset section lattice variables {ι : Type*} {ι' : Sort*} [complete_lattice α] /-- Supremum of `s i`, `i : ι`, is equal to the supremum over `t : finset ι` of suprema `⨆ i ∈ t, s i`. This version assumes `ι` is a `Type*`. See `supr_eq_supr_finset'` for a version that works for `ι : Sort*`. -/ lemma supr_eq_supr_finset (s : ι → α) : (⨆i, s i) = (⨆t:finset ι, ⨆i∈t, s i) := begin classical, exact le_antisymm (supr_le $ assume b, le_supr_of_le {b} $ le_supr_of_le b $ le_supr_of_le (by simp) $ le_refl _) (supr_le $ assume t, supr_le $ assume b, supr_le $ assume hb, le_supr _ _) end /-- Supremum of `s i`, `i : ι`, is equal to the supremum over `t : finset ι` of suprema `⨆ i ∈ t, s i`. This version works for `ι : Sort*`. See `supr_eq_supr_finset` for a version that assumes `ι : Type*` but has no `plift`s. -/ lemma supr_eq_supr_finset' (s : ι' → α) : (⨆i, s i) = (⨆t:finset (plift ι'), ⨆i∈t, s (plift.down i)) := by rw [← supr_eq_supr_finset, ← equiv.plift.surjective.supr_comp]; refl /-- Infimum of `s i`, `i : ι`, is equal to the infimum over `t : finset ι` of infima `⨆ i ∈ t, s i`. This version assumes `ι` is a `Type*`. See `infi_eq_infi_finset'` for a version that works for `ι : Sort*`. -/ lemma infi_eq_infi_finset (s : ι → α) : (⨅i, s i) = (⨅t:finset ι, ⨅i∈t, s i) := @supr_eq_supr_finset (order_dual α) _ _ _ /-- Infimum of `s i`, `i : ι`, is equal to the infimum over `t : finset ι` of infima `⨆ i ∈ t, s i`. This version works for `ι : Sort*`. See `infi_eq_infi_finset` for a version that assumes `ι : Type*` but has no `plift`s. -/ lemma infi_eq_infi_finset' (s : ι' → α) : (⨅i, s i) = (⨅t:finset (plift ι'), ⨅i∈t, s (plift.down i)) := @supr_eq_supr_finset' (order_dual α) _ _ _ end lattice namespace set variables {ι : Type*} {ι' : Sort*} /-- Union of an indexed family of sets `s : ι → set α` is equal to the union of the unions of finite subfamilies. This version assumes `ι : Type*`. See also `Union_eq_Union_finset'` for a version that works for `ι : Sort*`. -/ lemma Union_eq_Union_finset (s : ι → set α) : (⋃i, s i) = (⋃t:finset ι, ⋃i∈t, s i) := supr_eq_supr_finset s /-- Union of an indexed family of sets `s : ι → set α` is equal to the union of the unions of finite subfamilies. This version works for `ι : Sort*`. See also `Union_eq_Union_finset` for a version that assumes `ι : Type*` but avoids `plift`s in the right hand side. -/ lemma Union_eq_Union_finset' (s : ι' → set α) : (⋃i, s i) = (⋃t:finset (plift ι'), ⋃i∈t, s (plift.down i)) := supr_eq_supr_finset' s /-- Intersection of an indexed family of sets `s : ι → set α` is equal to the intersection of the intersections of finite subfamilies. This version assumes `ι : Type*`. See also `Inter_eq_Inter_finset'` for a version that works for `ι : Sort*`. -/ lemma Inter_eq_Inter_finset (s : ι → set α) : (⋂i, s i) = (⋂t:finset ι, ⋂i∈t, s i) := infi_eq_infi_finset s /-- Intersection of an indexed family of sets `s : ι → set α` is equal to the intersection of the intersections of finite subfamilies. This version works for `ι : Sort*`. See also `Inter_eq_Inter_finset` for a version that assumes `ι : Type*` but avoids `plift`s in the right hand side. -/ lemma Inter_eq_Inter_finset' (s : ι' → set α) : (⋂i, s i) = (⋂t:finset (plift ι'), ⋂i∈t, s (plift.down i)) := infi_eq_infi_finset' s end set namespace finset open function /-! ### Interaction with big lattice/set operations -/ section lattice lemma supr_coe [has_Sup β] (f : α → β) (s : finset α) : (⨆ x ∈ (↑s : set α), f x) = ⨆ x ∈ s, f x := rfl lemma infi_coe [has_Inf β] (f : α → β) (s : finset α) : (⨅ x ∈ (↑s : set α), f x) = ⨅ x ∈ s, f x := rfl variables [complete_lattice β] theorem supr_singleton (a : α) (s : α → β) : (⨆ x ∈ ({a} : finset α), s x) = s a := by simp theorem infi_singleton (a : α) (s : α → β) : (⨅ x ∈ ({a} : finset α), s x) = s a := by simp lemma supr_option_to_finset (o : option α) (f : α → β) : (⨆ x ∈ o.to_finset, f x) = ⨆ x ∈ o, f x := by { congr, ext, rw [option.mem_to_finset] } lemma infi_option_to_finset (o : option α) (f : α → β) : (⨅ x ∈ o.to_finset, f x) = ⨅ x ∈ o, f x := @supr_option_to_finset _ (order_dual β) _ _ _ variables [decidable_eq α] theorem supr_union {f : α → β} {s t : finset α} : (⨆ x ∈ s ∪ t, f x) = (⨆x∈s, f x) ⊔ (⨆x∈t, f x) := by simp [supr_or, supr_sup_eq] theorem infi_union {f : α → β} {s t : finset α} : (⨅ x ∈ s ∪ t, f x) = (⨅ x ∈ s, f x) ⊓ (⨅ x ∈ t, f x) := by simp [infi_or, infi_inf_eq] lemma supr_insert (a : α) (s : finset α) (t : α → β) : (⨆ x ∈ insert a s, t x) = t a ⊔ (⨆ x ∈ s, t x) := by { rw insert_eq, simp only [supr_union, finset.supr_singleton] } lemma infi_insert (a : α) (s : finset α) (t : α → β) : (⨅ x ∈ insert a s, t x) = t a ⊓ (⨅ x ∈ s, t x) := by { rw insert_eq, simp only [infi_union, finset.infi_singleton] } lemma supr_finset_image {f : γ → α} {g : α → β} {s : finset γ} : (⨆ x ∈ s.image f, g x) = (⨆ y ∈ s, g (f y)) := by rw [← supr_coe, coe_image, supr_image, supr_coe] lemma sup_finset_image {f : γ → α} {g : α → β} {s : finset γ} : s.sup (g ∘ f) = (s.image f).sup g := by { simp_rw [sup_eq_supr, comp_app], rw supr_finset_image, } lemma infi_finset_image {f : γ → α} {g : α → β} {s : finset γ} : (⨅ x ∈ s.image f, g x) = (⨅ y ∈ s, g (f y)) := by rw [← infi_coe, coe_image, infi_image, infi_coe] lemma supr_insert_update {x : α} {t : finset α} (f : α → β) {s : β} (hx : x ∉ t) : (⨆ (i ∈ insert x t), function.update f x s i) = (s ⊔ ⨆ (i ∈ t), f i) := begin simp only [finset.supr_insert, update_same], rcongr i hi, apply update_noteq, rintro rfl, exact hx hi end lemma infi_insert_update {x : α} {t : finset α} (f : α → β) {s : β} (hx : x ∉ t) : (⨅ (i ∈ insert x t), update f x s i) = (s ⊓ ⨅ (i ∈ t), f i) := @supr_insert_update α (order_dual β) _ _ _ _ f _ hx lemma supr_bUnion (s : finset γ) (t : γ → finset α) (f : α → β) : (⨆ y ∈ s.bUnion t, f y) = ⨆ (x ∈ s) (y ∈ t x), f y := calc (⨆ y ∈ s.bUnion t, f y) = ⨆ y (hy : ∃ x ∈ s, y ∈ t x), f y : congr_arg _ $ funext $ λ y, by rw [mem_bUnion] ... = _ : by simp only [supr_exists, @supr_comm _ α] lemma infi_bUnion (s : finset γ) (t : γ → finset α) (f : α → β) : (⨅ y ∈ s.bUnion t, f y) = ⨅ (x ∈ s) (y ∈ t x), f y := @supr_bUnion _ (order_dual β) _ _ _ _ _ _ end lattice @[simp] theorem set_bUnion_coe (s : finset α) (t : α → set β) : (⋃ x ∈ (↑s : set α), t x) = ⋃ x ∈ s, t x := rfl @[simp] theorem set_bInter_coe (s : finset α) (t : α → set β) : (⋂ x ∈ (↑s : set α), t x) = ⋂ x ∈ s, t x := rfl @[simp] theorem set_bUnion_singleton (a : α) (s : α → set β) : (⋃ x ∈ ({a} : finset α), s x) = s a := supr_singleton a s @[simp] theorem set_bInter_singleton (a : α) (s : α → set β) : (⋂ x ∈ ({a} : finset α), s x) = s a := infi_singleton a s @[simp] lemma set_bUnion_preimage_singleton (f : α → β) (s : finset β) : (⋃ y ∈ s, f ⁻¹' {y}) = f ⁻¹' ↑s := set.bUnion_preimage_singleton f ↑s @[simp] lemma set_bUnion_option_to_finset (o : option α) (f : α → set β) : (⋃ x ∈ o.to_finset, f x) = ⋃ x ∈ o, f x := supr_option_to_finset o f @[simp] lemma set_bInter_option_to_finset (o : option α) (f : α → set β) : (⋂ x ∈ o.to_finset, f x) = ⋂ x ∈ o, f x := infi_option_to_finset o f variables [decidable_eq α] lemma set_bUnion_union (s t : finset α) (u : α → set β) : (⋃ x ∈ s ∪ t, u x) = (⋃ x ∈ s, u x) ∪ (⋃ x ∈ t, u x) := supr_union lemma set_bInter_inter (s t : finset α) (u : α → set β) : (⋂ x ∈ s ∪ t, u x) = (⋂ x ∈ s, u x) ∩ (⋂ x ∈ t, u x) := infi_union @[simp] lemma set_bUnion_insert (a : α) (s : finset α) (t : α → set β) : (⋃ x ∈ insert a s, t x) = t a ∪ (⋃ x ∈ s, t x) := supr_insert a s t @[simp] lemma set_bInter_insert (a : α) (s : finset α) (t : α → set β) : (⋂ x ∈ insert a s, t x) = t a ∩ (⋂ x ∈ s, t x) := infi_insert a s t @[simp] lemma set_bUnion_finset_image {f : γ → α} {g : α → set β} {s : finset γ} : (⋃x ∈ s.image f, g x) = (⋃y ∈ s, g (f y)) := supr_finset_image @[simp] lemma set_bInter_finset_image {f : γ → α} {g : α → set β} {s : finset γ} : (⋂ x ∈ s.image f, g x) = (⋂ y ∈ s, g (f y)) := infi_finset_image lemma set_bUnion_insert_update {x : α} {t : finset α} (f : α → set β) {s : set β} (hx : x ∉ t) : (⋃ (i ∈ insert x t), @update _ _ _ f x s i) = (s ∪ ⋃ (i ∈ t), f i) := supr_insert_update f hx lemma set_bInter_insert_update {x : α} {t : finset α} (f : α → set β) {s : set β} (hx : x ∉ t) : (⋂ (i ∈ insert x t), @update _ _ _ f x s i) = (s ∩ ⋂ (i ∈ t), f i) := infi_insert_update f hx @[simp] lemma set_bUnion_bUnion (s : finset γ) (t : γ → finset α) (f : α → set β) : (⋃ y ∈ s.bUnion t, f y) = ⋃ (x ∈ s) (y ∈ t x), f y := supr_bUnion s t f @[simp] lemma set_bInter_bUnion (s : finset γ) (t : γ → finset α) (f : α → set β) : (⋂ y ∈ s.bUnion t, f y) = ⋂ (x ∈ s) (y ∈ t x), f y := infi_bUnion s t f end finset
55210adcf3b8ded7a8564c6450080eaa28ccd544
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/doc/examples/NFM2022/nfm24.lean
9b3d1687d4facc5f72ba0bab1379a6d0ce205afb
[ "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
286
lean
/- induction tactic -/ example (as : List α) (a : α) : (as.concat a).length = as.length + 1 := by induction as with | nil => rfl | cons x xs ih => simp [List.concat, ih] example (as : List α) (a : α) : (as.concat a).length = as.length + 1 := by induction as <;> simp! [*]
0e3b209b291abbb4de5028ff934e1ccb7ecf2156
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/measure_theory/integration.lean
d6879a5e8ea26b236855d4e4b44812f7be1b69a0
[ "Apache-2.0" ]
permissive
hamdysalah1/mathlib
b915f86b2503feeae268de369f1b16932321f097
95454452f6b3569bf967d35aab8d852b1ddf8017
refs/heads/master
1,677,154,116,545
1,611,797,994,000
1,611,797,994,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
81,924
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Johannes Hölzl -/ import measure_theory.measure_space import measure_theory.borel_space import data.indicator_function import data.support /-! # Lebesgue integral for `ennreal`-valued functions We define simple functions and show that each Borel measurable function on `ennreal` can be approximated by a sequence of simple functions. To prove something for an arbitrary measurable function into `ennreal`, the theorem `measurable.ennreal_induction` shows that is it sufficient to show that the property holds for (multiples of) characteristic functions and is closed under addition and supremum of increasing sequences of functions. ## Notation We introduce the following notation for the lower Lebesgue integral of a function `f : α → ennreal`. * `∫⁻ x, f x ∂μ`: integral of a function `f : α → ennreal` with respect to a measure `μ`; * `∫⁻ x, f x`: integral of a function `f : α → ennreal` with respect to the canonical measure `volume` on `α`; * `∫⁻ x in s, f x ∂μ`: integral of a function `f : α → ennreal` over a set `s` with respect to a measure `μ`, defined as `∫⁻ x, f x ∂(μ.restrict s)`; * `∫⁻ x in s, f x`: integral of a function `f : α → ennreal` over a set `s` with respect to the canonical measure `volume`, defined as `∫⁻ x, f x ∂(volume.restrict s)`. -/ noncomputable theory open set (hiding restrict restrict_apply) filter ennreal open_locale classical topological_space big_operators nnreal namespace measure_theory variables {α β γ δ : Type*} /-- A function `f` from a measurable space to any type is called *simple*, if every preimage `f ⁻¹' {x}` is measurable, and the range is finite. This structure bundles a function with these properties. -/ structure {u v} simple_func (α : Type u) [measurable_space α] (β : Type v) := (to_fun : α → β) (is_measurable_fiber' : ∀ x, is_measurable (to_fun ⁻¹' {x})) (finite_range' : (set.range to_fun).finite) local infixr ` →ₛ `:25 := simple_func namespace simple_func section measurable variables [measurable_space α] instance has_coe_to_fun : has_coe_to_fun (α →ₛ β) := ⟨_, to_fun⟩ lemma coe_injective ⦃f g : α →ₛ β⦄ (H : ⇑f = g) : f = g := by cases f; cases g; congr; exact H @[ext] theorem ext {f g : α →ₛ β} (H : ∀ a, f a = g a) : f = g := coe_injective $ funext H lemma finite_range (f : α →ₛ β) : (set.range f).finite := f.finite_range' lemma is_measurable_fiber (f : α →ₛ β) (x : β) : is_measurable (f ⁻¹' {x}) := f.is_measurable_fiber' x /-- Range of a simple function `α →ₛ β` as a `finset β`. -/ protected def range (f : α →ₛ β) : finset β := f.finite_range.to_finset @[simp] theorem mem_range {f : α →ₛ β} {b} : b ∈ f.range ↔ b ∈ range f := finite.mem_to_finset theorem mem_range_self (f : α →ₛ β) (x : α) : f x ∈ f.range := mem_range.2 ⟨x, rfl⟩ @[simp] lemma coe_range (f : α →ₛ β) : (↑f.range : set β) = set.range f := f.finite_range.coe_to_finset theorem mem_range_of_measure_ne_zero {f : α →ₛ β} {x : β} {μ : measure α} (H : μ (f ⁻¹' {x}) ≠ 0) : x ∈ f.range := let ⟨a, ha⟩ := nonempty_of_measure_ne_zero H in mem_range.2 ⟨a, ha⟩ lemma forall_range_iff {f : α →ₛ β} {p : β → Prop} : (∀ y ∈ f.range, p y) ↔ ∀ x, p (f x) := by simp only [mem_range, set.forall_range_iff] lemma exists_range_iff {f : α →ₛ β} {p : β → Prop} : (∃ y ∈ f.range, p y) ↔ ∃ x, p (f x) := by simpa only [mem_range, exists_prop] using set.exists_range_iff lemma preimage_eq_empty_iff (f : α →ₛ β) (b : β) : f ⁻¹' {b} = ∅ ↔ b ∉ f.range := preimage_singleton_eq_empty.trans $ not_congr mem_range.symm lemma exists_forall_le [nonempty β] [directed_order β] (f : α →ₛ β) : ∃ C, ∀ x, f x ≤ C := f.range.exists_le.imp $ λ C, forall_range_iff.1 /-- Constant function as a `simple_func`. -/ def const (α) {β} [measurable_space α] (b : β) : α →ₛ β := ⟨λ a, b, λ x, is_measurable.const _, finite_range_const⟩ instance [inhabited β] : inhabited (α →ₛ β) := ⟨const _ (default _)⟩ theorem const_apply (a : α) (b : β) : (const α b) a = b := rfl @[simp] theorem coe_const (b : β) : ⇑(const α b) = function.const α b := rfl @[simp] lemma range_const (α) [measurable_space α] [nonempty α] (b : β) : (const α b).range = {b} := finset.coe_injective $ by simp lemma is_measurable_cut (r : α → β → Prop) (f : α →ₛ β) (h : ∀b, is_measurable {a | r a b}) : is_measurable {a | r a (f a)} := begin have : {a | r a (f a)} = ⋃ b ∈ range f, {a | r a b} ∩ f ⁻¹' {b}, { ext a, suffices : r a (f a) ↔ ∃ i, r a (f i) ∧ f a = f i, by simpa, exact ⟨λ h, ⟨a, ⟨h, rfl⟩⟩, λ ⟨a', ⟨h', e⟩⟩, e.symm ▸ h'⟩ }, rw this, exact is_measurable.bUnion f.finite_range.countable (λ b _, is_measurable.inter (h b) (f.is_measurable_fiber _)) end theorem is_measurable_preimage (f : α →ₛ β) (s) : is_measurable (f ⁻¹' s) := is_measurable_cut (λ _ b, b ∈ s) f (λ b, is_measurable.const (b ∈ s)) /-- A simple function is measurable -/ protected theorem measurable [measurable_space β] (f : α →ₛ β) : measurable f := λ s _, is_measurable_preimage f s protected theorem ae_measurable [measurable_space β] {μ : measure α} (f : α →ₛ β) : ae_measurable f μ := f.measurable.ae_measurable protected lemma sum_measure_preimage_singleton (f : α →ₛ β) {μ : measure α} (s : finset β) : ∑ y in s, μ (f ⁻¹' {y}) = μ (f ⁻¹' ↑s) := sum_measure_preimage_singleton _ (λ _ _, f.is_measurable_fiber _) lemma sum_range_measure_preimage_singleton (f : α →ₛ β) (μ : measure α) : ∑ y in f.range, μ (f ⁻¹' {y}) = μ univ := by rw [f.sum_measure_preimage_singleton, coe_range, preimage_range] /-- If-then-else as a `simple_func`. -/ def piecewise (s : set α) (hs : is_measurable s) (f g : α →ₛ β) : α →ₛ β := ⟨s.piecewise f g, λ x, by letI : measurable_space β := ⊤; exact f.measurable.piecewise hs g.measurable trivial, (f.finite_range.union g.finite_range).subset range_ite_subset⟩ @[simp] theorem coe_piecewise {s : set α} (hs : is_measurable s) (f g : α →ₛ β) : ⇑(piecewise s hs f g) = s.piecewise f g := rfl theorem piecewise_apply {s : set α} (hs : is_measurable s) (f g : α →ₛ β) (a) : piecewise s hs f g a = if a ∈ s then f a else g a := rfl @[simp] lemma piecewise_compl {s : set α} (hs : is_measurable sᶜ) (f g : α →ₛ β) : piecewise sᶜ hs f g = piecewise s hs.of_compl g f := coe_injective $ by simp [hs] @[simp] lemma piecewise_univ (f g : α →ₛ β) : piecewise univ is_measurable.univ f g = f := coe_injective $ by simp @[simp] lemma piecewise_empty (f g : α →ₛ β) : piecewise ∅ is_measurable.empty f g = g := coe_injective $ by simp lemma measurable_bind [measurable_space γ] (f : α →ₛ β) (g : β → α → γ) (hg : ∀ b, measurable (g b)) : measurable (λ a, g (f a) a) := λ s hs, f.is_measurable_cut (λ a b, g b a ∈ s) $ λ b, hg b hs /-- If `f : α →ₛ β` is a simple function and `g : β → α →ₛ γ` is a family of simple functions, then `f.bind g` binds the first argument of `g` to `f`. In other words, `f.bind g a = g (f a) a`. -/ def bind (f : α →ₛ β) (g : β → α →ₛ γ) : α →ₛ γ := ⟨λa, g (f a) a, λ c, f.is_measurable_cut (λ a b, g b a = c) $ λ b, (g b).is_measurable_preimage {c}, (f.finite_range.bUnion (λ b _, (g b).finite_range)).subset $ by rintro _ ⟨a, rfl⟩; simp; exact ⟨a, a, rfl⟩⟩ @[simp] theorem bind_apply (f : α →ₛ β) (g : β → α →ₛ γ) (a) : f.bind g a = g (f a) a := rfl /-- Given a function `g : β → γ` and a simple function `f : α →ₛ β`, `f.map g` return the simple function `g ∘ f : α →ₛ γ` -/ def map (g : β → γ) (f : α →ₛ β) : α →ₛ γ := bind f (const α ∘ g) theorem map_apply (g : β → γ) (f : α →ₛ β) (a) : f.map g a = g (f a) := rfl theorem map_map (g : β → γ) (h: γ → δ) (f : α →ₛ β) : (f.map g).map h = f.map (h ∘ g) := rfl @[simp] theorem coe_map (g : β → γ) (f : α →ₛ β) : (f.map g : α → γ) = g ∘ f := rfl @[simp] theorem range_map [decidable_eq γ] (g : β → γ) (f : α →ₛ β) : (f.map g).range = f.range.image g := finset.coe_injective $ by simp [range_comp] @[simp] theorem map_const (g : β → γ) (b : β) : (const α b).map g = const α (g b) := rfl lemma map_preimage (f : α →ₛ β) (g : β → γ) (s : set γ) : (f.map g) ⁻¹' s = f ⁻¹' ↑(f.range.filter (λb, g b ∈ s)) := by { simp only [coe_range, sep_mem_eq, set.mem_range, function.comp_app, coe_map, finset.coe_filter, ← mem_preimage, inter_comm, preimage_inter_range], apply preimage_comp } lemma map_preimage_singleton (f : α →ₛ β) (g : β → γ) (c : γ) : (f.map g) ⁻¹' {c} = f ⁻¹' ↑(f.range.filter (λ b, g b = c)) := map_preimage _ _ _ /-- Composition of a `simple_fun` and a measurable function is a `simple_func`. -/ def comp [measurable_space β] (f : β →ₛ γ) (g : α → β) (hgm : measurable g) : α →ₛ γ := { to_fun := f ∘ g, finite_range' := f.finite_range.subset $ set.range_comp_subset_range _ _, is_measurable_fiber' := λ z, hgm (f.is_measurable_fiber z) } @[simp] lemma coe_comp [measurable_space β] (f : β →ₛ γ) {g : α → β} (hgm : measurable g) : ⇑(f.comp g hgm) = f ∘ g := rfl lemma range_comp_subset_range [measurable_space β] (f : β →ₛ γ) {g : α → β} (hgm : measurable g) : (f.comp g hgm).range ⊆ f.range := finset.coe_subset.1 $ by simp only [coe_range, coe_comp, set.range_comp_subset_range] /-- If `f` is a simple function taking values in `β → γ` and `g` is another simple function with the same domain and codomain `β`, then `f.seq g = f a (g a)`. -/ def seq (f : α →ₛ (β → γ)) (g : α →ₛ β) : α →ₛ γ := f.bind (λf, g.map f) @[simp] lemma seq_apply (f : α →ₛ (β → γ)) (g : α →ₛ β) (a : α) : f.seq g a = f a (g a) := rfl /-- Combine two simple functions `f : α →ₛ β` and `g : α →ₛ β` into `λ a, (f a, g a)`. -/ def pair (f : α →ₛ β) (g : α →ₛ γ) : α →ₛ (β × γ) := (f.map prod.mk).seq g @[simp] lemma pair_apply (f : α →ₛ β) (g : α →ₛ γ) (a) : pair f g a = (f a, g a) := rfl lemma pair_preimage (f : α →ₛ β) (g : α →ₛ γ) (s : set β) (t : set γ) : (pair f g) ⁻¹' (set.prod s t) = (f ⁻¹' s) ∩ (g ⁻¹' t) := rfl /- A special form of `pair_preimage` -/ lemma pair_preimage_singleton (f : α →ₛ β) (g : α →ₛ γ) (b : β) (c : γ) : (pair f g) ⁻¹' {(b, c)} = (f ⁻¹' {b}) ∩ (g ⁻¹' {c}) := by { rw ← singleton_prod_singleton, exact pair_preimage _ _ _ _ } theorem bind_const (f : α →ₛ β) : f.bind (const α) = f := by ext; simp instance [has_zero β] : has_zero (α →ₛ β) := ⟨const α 0⟩ instance [has_add β] : has_add (α →ₛ β) := ⟨λf g, (f.map (+)).seq g⟩ instance [has_mul β] : has_mul (α →ₛ β) := ⟨λf g, (f.map (*)).seq g⟩ instance [has_sup β] : has_sup (α →ₛ β) := ⟨λf g, (f.map (⊔)).seq g⟩ instance [has_inf β] : has_inf (α →ₛ β) := ⟨λf g, (f.map (⊓)).seq g⟩ instance [has_le β] : has_le (α →ₛ β) := ⟨λf g, ∀a, f a ≤ g a⟩ @[simp, norm_cast] lemma coe_zero [has_zero β] : ⇑(0 : α →ₛ β) = 0 := rfl @[simp] lemma const_zero [has_zero β] : const α (0:β) = 0 := rfl @[simp, norm_cast] lemma coe_add [has_add β] (f g : α →ₛ β) : ⇑(f + g) = f + g := rfl @[simp, norm_cast] lemma coe_mul [has_mul β] (f g : α →ₛ β) : ⇑(f * g) = f * g := rfl @[simp, norm_cast] lemma coe_le [preorder β] {f g : α →ₛ β} : (f : α → β) ≤ g ↔ f ≤ g := iff.rfl @[simp] lemma range_zero [nonempty α] [has_zero β] : (0 : α →ₛ β).range = {0} := finset.ext $ λ x, by simp [eq_comm] lemma eq_zero_of_mem_range_zero [has_zero β] : ∀ {y : β}, y ∈ (0 : α →ₛ β).range → y = 0 := forall_range_iff.2 $ λ x, rfl lemma sup_apply [has_sup β] (f g : α →ₛ β) (a : α) : (f ⊔ g) a = f a ⊔ g a := rfl lemma mul_apply [has_mul β] (f g : α →ₛ β) (a : α) : (f * g) a = f a * g a := rfl lemma add_apply [has_add β] (f g : α →ₛ β) (a : α) : (f + g) a = f a + g a := rfl lemma add_eq_map₂ [has_add β] (f g : α →ₛ β) : f + g = (pair f g).map (λp:β×β, p.1 + p.2) := rfl lemma mul_eq_map₂ [has_mul β] (f g : α →ₛ β) : f * g = (pair f g).map (λp:β×β, p.1 * p.2) := rfl lemma sup_eq_map₂ [has_sup β] (f g : α →ₛ β) : f ⊔ g = (pair f g).map (λp:β×β, p.1 ⊔ p.2) := rfl lemma const_mul_eq_map [has_mul β] (f : α →ₛ β) (b : β) : const α b * f = f.map (λa, b * a) := rfl theorem map_add [has_add β] [has_add γ] {g : β → γ} (hg : ∀ x y, g (x + y) = g x + g y) (f₁ f₂ : α →ₛ β) : (f₁ + f₂).map g = f₁.map g + f₂.map g := ext $ λ x, hg _ _ instance [add_monoid β] : add_monoid (α →ₛ β) := function.injective.add_monoid (λ f, show α → β, from f) coe_injective coe_zero coe_add instance add_comm_monoid [add_comm_monoid β] : add_comm_monoid (α →ₛ β) := function.injective.add_comm_monoid (λ f, show α → β, from f) coe_injective coe_zero coe_add instance [has_neg β] : has_neg (α →ₛ β) := ⟨λf, f.map (has_neg.neg)⟩ @[simp, norm_cast] lemma coe_neg [has_neg β] (f : α →ₛ β) : ⇑(-f) = -f := rfl instance [has_sub β] : has_sub (α →ₛ β) := ⟨λf g, (f.map (has_sub.sub)).seq g⟩ @[simp, norm_cast] lemma coe_sub [has_sub β] (f g : α →ₛ β) : ⇑(f - g) = f - g := rfl lemma sub_apply [has_sub β] (f g : α →ₛ β) (x : α) : (f - g) x = f x - g x := rfl instance [add_group β] : add_group (α →ₛ β) := function.injective.add_group_sub (λ f, show α → β, from f) coe_injective coe_zero coe_add coe_neg coe_sub instance [add_comm_group β] : add_comm_group (α →ₛ β) := function.injective.add_comm_group_sub (λ f, show α → β, from f) coe_injective coe_zero coe_add coe_neg coe_sub variables {K : Type*} instance [has_scalar K β] : has_scalar K (α →ₛ β) := ⟨λk f, f.map ((•) k)⟩ @[simp] lemma coe_smul [has_scalar K β] (c : K) (f : α →ₛ β) : ⇑(c • f) = c • f := rfl lemma smul_apply [has_scalar K β] (k : K) (f : α →ₛ β) (a : α) : (k • f) a = k • f a := rfl instance [semiring K] [add_comm_monoid β] [semimodule K β] : semimodule K (α →ₛ β) := function.injective.semimodule K ⟨λ f, show α → β, from f, coe_zero, coe_add⟩ coe_injective coe_smul lemma smul_eq_map [has_scalar K β] (k : K) (f : α →ₛ β) : k • f = f.map ((•) k) := rfl instance [preorder β] : preorder (α →ₛ β) := { le_refl := λf a, le_refl _, le_trans := λf g h hfg hgh a, le_trans (hfg _) (hgh a), .. simple_func.has_le } instance [partial_order β] : partial_order (α →ₛ β) := { le_antisymm := assume f g hfg hgf, ext $ assume a, le_antisymm (hfg a) (hgf a), .. simple_func.preorder } instance [order_bot β] : order_bot (α →ₛ β) := { bot := const α ⊥, bot_le := λf a, bot_le, .. simple_func.partial_order } instance [order_top β] : order_top (α →ₛ β) := { top := const α ⊤, le_top := λf a, le_top, .. simple_func.partial_order } instance [semilattice_inf β] : semilattice_inf (α →ₛ β) := { inf := (⊓), inf_le_left := assume f g a, inf_le_left, inf_le_right := assume f g a, inf_le_right, le_inf := assume f g h hfh hgh a, le_inf (hfh a) (hgh a), .. simple_func.partial_order } instance [semilattice_sup β] : semilattice_sup (α →ₛ β) := { sup := (⊔), le_sup_left := assume f g a, le_sup_left, le_sup_right := assume f g a, le_sup_right, sup_le := assume f g h hfh hgh a, sup_le (hfh a) (hgh a), .. simple_func.partial_order } instance [semilattice_sup_bot β] : semilattice_sup_bot (α →ₛ β) := { .. simple_func.semilattice_sup,.. simple_func.order_bot } instance [lattice β] : lattice (α →ₛ β) := { .. simple_func.semilattice_sup,.. simple_func.semilattice_inf } instance [bounded_lattice β] : bounded_lattice (α →ₛ β) := { .. simple_func.lattice, .. simple_func.order_bot, .. simple_func.order_top } lemma finset_sup_apply [semilattice_sup_bot β] {f : γ → α →ₛ β} (s : finset γ) (a : α) : s.sup f a = s.sup (λc, f c a) := begin refine finset.induction_on s rfl _, assume a s hs ih, rw [finset.sup_insert, finset.sup_insert, sup_apply, ih] end section restrict variables [has_zero β] /-- Restrict a simple function `f : α →ₛ β` to a set `s`. If `s` is measurable, then `f.restrict s a = if a ∈ s then f a else 0`, otherwise `f.restrict s = const α 0`. -/ def restrict (f : α →ₛ β) (s : set α) : α →ₛ β := if hs : is_measurable s then piecewise s hs f 0 else 0 theorem restrict_of_not_measurable {f : α →ₛ β} {s : set α} (hs : ¬is_measurable s) : restrict f s = 0 := dif_neg hs @[simp] theorem coe_restrict (f : α →ₛ β) {s : set α} (hs : is_measurable s) : ⇑(restrict f s) = indicator s f := by { rw [restrict, dif_pos hs], refl } @[simp] theorem restrict_univ (f : α →ₛ β) : restrict f univ = f := by simp [restrict] @[simp] theorem restrict_empty (f : α →ₛ β) : restrict f ∅ = 0 := by simp [restrict] theorem map_restrict_of_zero [has_zero γ] {g : β → γ} (hg : g 0 = 0) (f : α →ₛ β) (s : set α) : (f.restrict s).map g = (f.map g).restrict s := ext $ λ x, if hs : is_measurable s then by simp [hs, set.indicator_comp_of_zero hg] else by simp [restrict_of_not_measurable hs, hg] theorem map_coe_ennreal_restrict (f : α →ₛ ℝ≥0) (s : set α) : (f.restrict s).map (coe : ℝ≥0 → ennreal) = (f.map coe).restrict s := map_restrict_of_zero ennreal.coe_zero _ _ theorem map_coe_nnreal_restrict (f : α →ₛ ℝ≥0) (s : set α) : (f.restrict s).map (coe : ℝ≥0 → ℝ) = (f.map coe).restrict s := map_restrict_of_zero nnreal.coe_zero _ _ theorem restrict_apply (f : α →ₛ β) {s : set α} (hs : is_measurable s) (a) : restrict f s a = if a ∈ s then f a else 0 := by simp only [hs, coe_restrict] theorem restrict_preimage (f : α →ₛ β) {s : set α} (hs : is_measurable s) {t : set β} (ht : (0:β) ∉ t) : restrict f s ⁻¹' t = s ∩ f ⁻¹' t := by simp [hs, indicator_preimage_of_not_mem _ _ ht] theorem restrict_preimage_singleton (f : α →ₛ β) {s : set α} (hs : is_measurable s) {r : β} (hr : r ≠ 0) : restrict f s ⁻¹' {r} = s ∩ f ⁻¹' {r} := f.restrict_preimage hs hr.symm lemma mem_restrict_range {r : β} {s : set α} {f : α →ₛ β} (hs : is_measurable s) : r ∈ (restrict f s).range ↔ (r = 0 ∧ s ≠ univ) ∨ (r ∈ f '' s) := by rw [← finset.mem_coe, coe_range, coe_restrict _ hs, mem_range_indicator] lemma mem_image_of_mem_range_restrict {r : β} {s : set α} {f : α →ₛ β} (hr : r ∈ (restrict f s).range) (h0 : r ≠ 0) : r ∈ f '' s := if hs : is_measurable s then by simpa [mem_restrict_range hs, h0] using hr else by { rw [restrict_of_not_measurable hs] at hr, exact (h0 $ eq_zero_of_mem_range_zero hr).elim } @[mono] lemma restrict_mono [preorder β] (s : set α) {f g : α →ₛ β} (H : f ≤ g) : f.restrict s ≤ g.restrict s := if hs : is_measurable s then λ x, by simp only [coe_restrict _ hs, indicator_le_indicator (H x)] else by simp only [restrict_of_not_measurable hs, le_refl] end restrict section approx section variables [semilattice_sup_bot β] [has_zero β] /-- Fix a sequence `i : ℕ → β`. Given a function `α → β`, its `n`-th approximation by simple functions is defined so that in case `β = ennreal` it sends each `a` to the supremum of the set `{i k | k ≤ n ∧ i k ≤ f a}`, see `approx_apply` and `supr_approx_apply` for details. -/ def approx (i : ℕ → β) (f : α → β) (n : ℕ) : α →ₛ β := (finset.range n).sup (λk, restrict (const α (i k)) {a:α | i k ≤ f a}) lemma approx_apply [topological_space β] [order_closed_topology β] [measurable_space β] [opens_measurable_space β] {i : ℕ → β} {f : α → β} {n : ℕ} (a : α) (hf : measurable f) : (approx i f n : α →ₛ β) a = (finset.range n).sup (λk, if i k ≤ f a then i k else 0) := begin dsimp only [approx], rw [finset_sup_apply], congr, funext k, rw [restrict_apply], refl, exact (hf is_measurable_Ici) end lemma monotone_approx (i : ℕ → β) (f : α → β) : monotone (approx i f) := assume n m h, finset.sup_mono $ finset.range_subset.2 h lemma approx_comp [topological_space β] [order_closed_topology β] [measurable_space β] [opens_measurable_space β] [measurable_space γ] {i : ℕ → β} {f : γ → β} {g : α → γ} {n : ℕ} (a : α) (hf : measurable f) (hg : measurable g) : (approx i (f ∘ g) n : α →ₛ β) a = (approx i f n : γ →ₛ β) (g a) := by rw [approx_apply _ hf, approx_apply _ (hf.comp hg)] end lemma supr_approx_apply [topological_space β] [complete_lattice β] [order_closed_topology β] [has_zero β] [measurable_space β] [opens_measurable_space β] (i : ℕ → β) (f : α → β) (a : α) (hf : measurable f) (h_zero : (0 : β) = ⊥) : (⨆n, (approx i f n : α →ₛ β) a) = (⨆k (h : i k ≤ f a), i k) := begin refine le_antisymm (supr_le $ assume n, _) (supr_le $ assume k, supr_le $ assume hk, _), { rw [approx_apply a hf, h_zero], refine finset.sup_le (assume k hk, _), split_ifs, exact le_supr_of_le k (le_supr _ h), exact bot_le }, { refine le_supr_of_le (k+1) _, rw [approx_apply a hf], have : k ∈ finset.range (k+1) := finset.mem_range.2 (nat.lt_succ_self _), refine le_trans (le_of_eq _) (finset.le_sup this), rw [if_pos hk] } end end approx section eapprox /-- A sequence of `ennreal`s such that its range is the set of non-negative rational numbers. -/ def ennreal_rat_embed (n : ℕ) : ennreal := ennreal.of_real ((encodable.decode ℚ n).get_or_else (0 : ℚ)) lemma ennreal_rat_embed_encode (q : ℚ) : ennreal_rat_embed (encodable.encode q) = nnreal.of_real q := by rw [ennreal_rat_embed, encodable.encodek]; refl /-- Approximate a function `α → ennreal` by a sequence of simple functions. -/ def eapprox : (α → ennreal) → ℕ → α →ₛ ennreal := approx ennreal_rat_embed @[mono] lemma monotone_eapprox (f : α → ennreal) : monotone (eapprox f) := monotone_approx _ f lemma supr_eapprox_apply (f : α → ennreal) (hf : measurable f) (a : α) : (⨆n, (eapprox f n : α →ₛ ennreal) a) = f a := begin rw [eapprox, supr_approx_apply ennreal_rat_embed f a hf rfl], refine le_antisymm (supr_le $ assume i, supr_le $ assume hi, hi) (le_of_not_gt _), assume h, rcases ennreal.lt_iff_exists_rat_btwn.1 h with ⟨q, hq, lt_q, q_lt⟩, have : (nnreal.of_real q : ennreal) ≤ (⨆ (k : ℕ) (h : ennreal_rat_embed k ≤ f a), ennreal_rat_embed k), { refine le_supr_of_le (encodable.encode q) _, rw [ennreal_rat_embed_encode q], refine le_supr_of_le (le_of_lt q_lt) _, exact le_refl _ }, exact lt_irrefl _ (lt_of_le_of_lt this lt_q) end lemma eapprox_comp [measurable_space γ] {f : γ → ennreal} {g : α → γ} {n : ℕ} (hf : measurable f) (hg : measurable g) : (eapprox (f ∘ g) n : α → ennreal) = (eapprox f n : γ →ₛ ennreal) ∘ g := funext $ assume a, approx_comp a hf hg end eapprox end measurable section measure variables [measurable_space α] {μ : measure α} /-- Integral of a simple function whose codomain is `ennreal`. -/ def lintegral (f : α →ₛ ennreal) (μ : measure α) : ennreal := ∑ x in f.range, x * μ (f ⁻¹' {x}) lemma lintegral_eq_of_subset (f : α →ₛ ennreal) {s : finset ennreal} (hs : ∀ x, f x ≠ 0 → μ (f ⁻¹' {f x}) ≠ 0 → f x ∈ s) : f.lintegral μ = ∑ x in s, x * μ (f ⁻¹' {x}) := begin refine finset.sum_bij_ne_zero (λr _ _, r) _ _ _ _, { simpa only [forall_range_iff, mul_ne_zero_iff, and_imp] }, { intros, assumption }, { intros b _ hb, refine ⟨b, _, hb, rfl⟩, rw [mem_range, ← preimage_singleton_nonempty], exact nonempty_of_measure_ne_zero (mul_ne_zero_iff.1 hb).2 }, { intros, refl } end /-- Calculate the integral of `(g ∘ f)`, where `g : β → ennreal` and `f : α →ₛ β`. -/ lemma map_lintegral (g : β → ennreal) (f : α →ₛ β) : (f.map g).lintegral μ = ∑ x in f.range, g x * μ (f ⁻¹' {x}) := begin simp only [lintegral, range_map], refine finset.sum_image' _ (assume b hb, _), rcases mem_range.1 hb with ⟨a, rfl⟩, rw [map_preimage_singleton, ← f.sum_measure_preimage_singleton, finset.mul_sum], refine finset.sum_congr _ _, { congr }, { assume x, simp only [finset.mem_filter], rintro ⟨_, h⟩, rw h }, end lemma add_lintegral (f g : α →ₛ ennreal) : (f + g).lintegral μ = f.lintegral μ + g.lintegral μ := calc (f + g).lintegral μ = ∑ x in (pair f g).range, (x.1 * μ (pair f g ⁻¹' {x}) + x.2 * μ (pair f g ⁻¹' {x})) : by rw [add_eq_map₂, map_lintegral]; exact finset.sum_congr rfl (assume a ha, add_mul _ _ _) ... = ∑ x in (pair f g).range, x.1 * μ (pair f g ⁻¹' {x}) + ∑ x in (pair f g).range, x.2 * μ (pair f g ⁻¹' {x}) : by rw [finset.sum_add_distrib] ... = ((pair f g).map prod.fst).lintegral μ + ((pair f g).map prod.snd).lintegral μ : by rw [map_lintegral, map_lintegral] ... = lintegral f μ + lintegral g μ : rfl lemma const_mul_lintegral (f : α →ₛ ennreal) (x : ennreal) : (const α x * f).lintegral μ = x * f.lintegral μ := calc (f.map (λa, x * a)).lintegral μ = ∑ r in f.range, x * r * μ (f ⁻¹' {r}) : map_lintegral _ _ ... = ∑ r in f.range, x * (r * μ (f ⁻¹' {r})) : finset.sum_congr rfl (assume a ha, mul_assoc _ _ _) ... = x * f.lintegral μ : finset.mul_sum.symm /-- Integral of a simple function `α →ₛ ennreal` as a bilinear map. -/ def lintegralₗ : (α →ₛ ennreal) →ₗ[ennreal] measure α →ₗ[ennreal] ennreal := { to_fun := λ f, { to_fun := lintegral f, map_add' := by simp [lintegral, mul_add, finset.sum_add_distrib], map_smul' := λ c μ, by simp [lintegral, mul_left_comm _ c, finset.mul_sum] }, map_add' := λ f g, linear_map.ext (λ μ, add_lintegral f g), map_smul' := λ c f, linear_map.ext (λ μ, const_mul_lintegral f c) } @[simp] lemma zero_lintegral : (0 : α →ₛ ennreal).lintegral μ = 0 := linear_map.ext_iff.1 lintegralₗ.map_zero μ lemma lintegral_add {ν} (f : α →ₛ ennreal) : f.lintegral (μ + ν) = f.lintegral μ + f.lintegral ν := (lintegralₗ f).map_add μ ν lemma lintegral_smul (f : α →ₛ ennreal) (c : ennreal) : f.lintegral (c • μ) = c • f.lintegral μ := (lintegralₗ f).map_smul c μ @[simp] lemma lintegral_zero (f : α →ₛ ennreal) : f.lintegral 0 = 0 := (lintegralₗ f).map_zero lemma lintegral_sum {ι} (f : α →ₛ ennreal) (μ : ι → measure α) : f.lintegral (measure.sum μ) = ∑' i, f.lintegral (μ i) := begin simp only [lintegral, measure.sum_apply, f.is_measurable_preimage, ← finset.tsum_subtype, ← ennreal.tsum_mul_left], apply ennreal.tsum_comm end lemma restrict_lintegral (f : α →ₛ ennreal) {s : set α} (hs : is_measurable s) : (restrict f s).lintegral μ = ∑ r in f.range, r * μ (f ⁻¹' {r} ∩ s) := calc (restrict f s).lintegral μ = ∑ r in f.range, r * μ (restrict f s ⁻¹' {r}) : lintegral_eq_of_subset _ $ λ x hx, if hxs : x ∈ s then by simp [f.restrict_apply hs, if_pos hxs, mem_range_self] else false.elim $ hx $ by simp [*] ... = ∑ r in f.range, r * μ (f ⁻¹' {r} ∩ s) : finset.sum_congr rfl $ forall_range_iff.2 $ λ b, if hb : f b = 0 then by simp only [hb, zero_mul] else by rw [restrict_preimage_singleton _ hs hb, inter_comm] lemma lintegral_restrict (f : α →ₛ ennreal) (s : set α) (μ : measure α) : f.lintegral (μ.restrict s) = ∑ y in f.range, y * μ (f ⁻¹' {y} ∩ s) := by simp only [lintegral, measure.restrict_apply, f.is_measurable_preimage] lemma restrict_lintegral_eq_lintegral_restrict (f : α →ₛ ennreal) {s : set α} (hs : is_measurable s) : (restrict f s).lintegral μ = f.lintegral (μ.restrict s) := by rw [f.restrict_lintegral hs, lintegral_restrict] lemma const_lintegral (c : ennreal) : (const α c).lintegral μ = c * μ univ := begin rw [lintegral], by_cases ha : nonempty α, { resetI, simp [preimage_const_of_mem] }, { simp [μ.eq_zero_of_not_nonempty ha] } end lemma const_lintegral_restrict (c : ennreal) (s : set α) : (const α c).lintegral (μ.restrict s) = c * μ s := by rw [const_lintegral, measure.restrict_apply is_measurable.univ, univ_inter] lemma restrict_const_lintegral (c : ennreal) {s : set α} (hs : is_measurable s) : ((const α c).restrict s).lintegral μ = c * μ s := by rw [restrict_lintegral_eq_lintegral_restrict _ hs, const_lintegral_restrict] lemma le_sup_lintegral (f g : α →ₛ ennreal) : f.lintegral μ ⊔ g.lintegral μ ≤ (f ⊔ g).lintegral μ := calc f.lintegral μ ⊔ g.lintegral μ = ((pair f g).map prod.fst).lintegral μ ⊔ ((pair f g).map prod.snd).lintegral μ : rfl ... ≤ ∑ x in (pair f g).range, (x.1 ⊔ x.2) * μ (pair f g ⁻¹' {x}) : begin rw [map_lintegral, map_lintegral], refine sup_le _ _; refine finset.sum_le_sum (λ a _, canonically_ordered_semiring.mul_le_mul _ (le_refl _)), exact le_sup_left, exact le_sup_right end ... = (f ⊔ g).lintegral μ : by rw [sup_eq_map₂, map_lintegral] /-- `simple_func.lintegral` is monotone both in function and in measure. -/ @[mono] lemma lintegral_mono {f g : α →ₛ ennreal} (hfg : f ≤ g) {μ ν : measure α} (hμν : μ ≤ ν) : f.lintegral μ ≤ g.lintegral ν := calc f.lintegral μ ≤ f.lintegral μ ⊔ g.lintegral μ : le_sup_left ... ≤ (f ⊔ g).lintegral μ : le_sup_lintegral _ _ ... = g.lintegral μ : by rw [sup_of_le_right hfg] ... ≤ g.lintegral ν : finset.sum_le_sum $ λ y hy, ennreal.mul_left_mono $ hμν _ (g.is_measurable_preimage _) /-- `simple_func.lintegral` depends only on the measures of `f ⁻¹' {y}`. -/ lemma lintegral_eq_of_measure_preimage [measurable_space β] {f : α →ₛ ennreal} {g : β →ₛ ennreal} {ν : measure β} (H : ∀ y, μ (f ⁻¹' {y}) = ν (g ⁻¹' {y})) : f.lintegral μ = g.lintegral ν := begin simp only [lintegral, ← H], apply lintegral_eq_of_subset, simp only [H], intros, exact mem_range_of_measure_ne_zero ‹_› end /-- If two simple functions are equal a.e., then their `lintegral`s are equal. -/ lemma lintegral_congr {f g : α →ₛ ennreal} (h : f =ᵐ[μ] g) : f.lintegral μ = g.lintegral μ := lintegral_eq_of_measure_preimage $ λ y, measure_congr $ eventually.set_eq $ h.mono $ λ x hx, by simp [hx] lemma lintegral_map {β} [measurable_space β] {μ' : measure β} (f : α →ₛ ennreal) (g : β →ₛ ennreal) (m : α → β) (eq : ∀a:α, f a = g (m a)) (h : ∀s:set β, is_measurable s → μ' s = μ (m ⁻¹' s)) : f.lintegral μ = g.lintegral μ' := lintegral_eq_of_measure_preimage $ λ y, by { simp only [preimage, eq], exact (h (g ⁻¹' {y}) (g.is_measurable_preimage _)).symm } end measure section fin_meas_supp variables [measurable_space α] [has_zero β] [has_zero γ] {μ : measure α} open finset ennreal function lemma support_eq (f : α →ₛ β) : support f = ⋃ y ∈ f.range.filter (λ y, y ≠ 0), f ⁻¹' {y} := set.ext $ λ x, by simp only [finset.set_bUnion_preimage_singleton, mem_support, set.mem_preimage, finset.mem_coe, mem_filter, mem_range_self, true_and] /-- A `simple_func` has finite measure support if it is equal to `0` outside of a set of finite measure. -/ protected def fin_meas_supp (f : α →ₛ β) (μ : measure α) : Prop := f =ᶠ[μ.cofinite] 0 lemma fin_meas_supp_iff_support {f : α →ₛ β} {μ : measure α} : f.fin_meas_supp μ ↔ μ (support f) < ⊤ := iff.rfl lemma fin_meas_supp_iff {f : α →ₛ β} {μ : measure α} : f.fin_meas_supp μ ↔ ∀ y ≠ 0, μ (f ⁻¹' {y}) < ⊤ := begin split, { refine λ h y hy, lt_of_le_of_lt (measure_mono _) h, exact λ x hx (H : f x = 0), hy $ H ▸ eq.symm hx }, { intro H, rw [fin_meas_supp_iff_support, support_eq], refine lt_of_le_of_lt (measure_bUnion_finset_le _ _) (sum_lt_top _), exact λ y hy, H y (finset.mem_filter.1 hy).2 } end namespace fin_meas_supp lemma meas_preimage_singleton_ne_zero {f : α →ₛ β} (h : f.fin_meas_supp μ) {y : β} (hy : y ≠ 0) : μ (f ⁻¹' {y}) < ⊤ := fin_meas_supp_iff.1 h y hy protected lemma map {f : α →ₛ β} {g : β → γ} (hf : f.fin_meas_supp μ) (hg : g 0 = 0) : (f.map g).fin_meas_supp μ := flip lt_of_le_of_lt hf (measure_mono $ support_comp_subset hg f) lemma of_map {f : α →ₛ β} {g : β → γ} (h : (f.map g).fin_meas_supp μ) (hg : ∀b, g b = 0 → b = 0) : f.fin_meas_supp μ := flip lt_of_le_of_lt h $ measure_mono $ support_subset_comp hg _ lemma map_iff {f : α →ₛ β} {g : β → γ} (hg : ∀ {b}, g b = 0 ↔ b = 0) : (f.map g).fin_meas_supp μ ↔ f.fin_meas_supp μ := ⟨λ h, h.of_map $ λ b, hg.1, λ h, h.map $ hg.2 rfl⟩ protected lemma pair {f : α →ₛ β} {g : α →ₛ γ} (hf : f.fin_meas_supp μ) (hg : g.fin_meas_supp μ) : (pair f g).fin_meas_supp μ := calc μ (support $ pair f g) = μ (support f ∪ support g) : congr_arg μ $ support_prod_mk f g ... ≤ μ (support f) + μ (support g) : measure_union_le _ _ ... < _ : add_lt_top.2 ⟨hf, hg⟩ protected lemma map₂ [has_zero δ] {μ : measure α} {f : α →ₛ β} (hf : f.fin_meas_supp μ) {g : α →ₛ γ} (hg : g.fin_meas_supp μ) {op : β → γ → δ} (H : op 0 0 = 0) : ((pair f g).map (function.uncurry op)).fin_meas_supp μ := (hf.pair hg).map H protected lemma add {β} [add_monoid β] {f g : α →ₛ β} (hf : f.fin_meas_supp μ) (hg : g.fin_meas_supp μ) : (f + g).fin_meas_supp μ := by { rw [add_eq_map₂], exact hf.map₂ hg (zero_add 0) } protected lemma mul {β} [monoid_with_zero β] {f g : α →ₛ β} (hf : f.fin_meas_supp μ) (hg : g.fin_meas_supp μ) : (f * g).fin_meas_supp μ := by { rw [mul_eq_map₂], exact hf.map₂ hg (zero_mul 0) } lemma lintegral_lt_top {f : α →ₛ ennreal} (hm : f.fin_meas_supp μ) (hf : ∀ᵐ a ∂μ, f a < ⊤) : f.lintegral μ < ⊤ := begin refine sum_lt_top (λ a ha, _), rcases eq_or_lt_of_le (le_top : a ≤ ⊤) with rfl|ha, { simp only [ae_iff, lt_top_iff_ne_top, ne.def, not_not] at hf, simp [set.preimage, hf] }, { by_cases ha0 : a = 0, { subst a, rwa [zero_mul] }, { exact mul_lt_top ha (fin_meas_supp_iff.1 hm _ ha0) } } end lemma of_lintegral_lt_top {f : α →ₛ ennreal} (h : f.lintegral μ < ⊤) : f.fin_meas_supp μ := begin refine fin_meas_supp_iff.2 (λ b hb, _), rw [lintegral, sum_lt_top_iff] at h, by_cases b_mem : b ∈ f.range, { rw ennreal.lt_top_iff_ne_top, have h : ¬ _ = ⊤ := ennreal.lt_top_iff_ne_top.1 (h b b_mem), simp only [mul_eq_top, not_or_distrib, not_and_distrib] at h, rcases h with ⟨h, h'⟩, refine or.elim h (λh, by contradiction) (λh, h) }, { rw ← preimage_eq_empty_iff at b_mem, rw [b_mem, measure_empty], exact with_top.zero_lt_top } end lemma iff_lintegral_lt_top {f : α →ₛ ennreal} (hf : ∀ᵐ a ∂μ, f a < ⊤) : f.fin_meas_supp μ ↔ f.lintegral μ < ⊤ := ⟨λ h, h.lintegral_lt_top hf, λ h, of_lintegral_lt_top h⟩ end fin_meas_supp end fin_meas_supp /-- To prove something for an arbitrary simple function, it suffices to show that the property holds for (multiples of) characteristic functions and is closed under addition (of functions with disjoint support). It is possible to make the hypotheses in `h_sum` a bit stronger, and such conditions can be added once we need them (for example it is only necessary to consider the case where `g` is a multiple of a characteristic function, and that this multiple doesn't appear in the image of `f`) -/ @[elab_as_eliminator] protected lemma induction {α γ} [measurable_space α] [add_monoid γ] {P : simple_func α γ → Prop} (h_ind : ∀ c {s} (hs : is_measurable s), P (simple_func.piecewise s hs (simple_func.const _ c) (simple_func.const _ 0))) (h_sum : ∀ ⦃f g : simple_func α γ⦄, set.univ ⊆ f ⁻¹' {0} ∪ g ⁻¹' {0} → P f → P g → P (f + g)) (f : simple_func α γ) : P f := begin generalize' h : f.range \ {0} = s, rw [← finset.coe_inj, finset.coe_sdiff, finset.coe_singleton, simple_func.coe_range] at h, revert s f h, refine finset.induction _ _, { intros f hf, rw [finset.coe_empty, diff_eq_empty, range_subset_singleton] at hf, convert h_ind 0 is_measurable.univ, ext x, simp [hf] }, { intros x s hxs ih f hf, have mx := f.is_measurable_preimage {x}, let g := simple_func.piecewise (f ⁻¹' {x}) mx 0 f, have Pg : P g, { apply ih, simp only [g, simple_func.coe_piecewise, range_piecewise], rw [image_compl_preimage, union_diff_distrib, diff_diff_comm, hf, finset.coe_insert, insert_diff_self_of_not_mem, diff_eq_empty.mpr, set.empty_union], { rw [set.image_subset_iff], convert set.subset_univ _, exact preimage_const_of_mem (mem_singleton _) }, { rwa [finset.mem_coe] }}, convert h_sum _ Pg (h_ind x mx), { ext1 y, by_cases hy : y ∈ f ⁻¹' {x}; [simpa [hy], simp [hy]] }, { rintro y -, by_cases hy : y ∈ f ⁻¹' {x}; simp [hy] } } end end simple_func section lintegral open simple_func variables [measurable_space α] {μ : measure α} /-- The lower Lebesgue integral of a function `f` with respect to a measure `μ`. -/ def lintegral (μ : measure α) (f : α → ennreal) : ennreal := ⨆ (g : α →ₛ ennreal) (hf : ⇑g ≤ f), g.lintegral μ /-! In the notation for integrals, an expression like `∫⁻ x, g ∥x∥ ∂μ` will not be parsed correctly, and needs parentheses. We do not set the binding power of `r` to `0`, because then `∫⁻ x, f x = 0` will be parsed incorrectly. -/ notation `∫⁻` binders `, ` r:(scoped:60 f, f) ` ∂` μ:70 := lintegral μ r notation `∫⁻` binders `, ` r:(scoped:60 f, lintegral volume f) := r notation `∫⁻` binders ` in ` s `, ` r:(scoped:60 f, f) ` ∂` μ:70 := lintegral (measure.restrict μ s) r notation `∫⁻` binders ` in ` s `, ` r:(scoped:60 f, lintegral (measure.restrict volume s) f) := r theorem simple_func.lintegral_eq_lintegral (f : α →ₛ ennreal) (μ : measure α) : ∫⁻ a, f a ∂ μ = f.lintegral μ := le_antisymm (bsupr_le $ λ g hg, lintegral_mono hg $ le_refl _) (le_supr_of_le f $ le_supr_of_le (le_refl _) (le_refl _)) @[mono] lemma lintegral_mono' ⦃μ ν : measure α⦄ (hμν : μ ≤ ν) ⦃f g : α → ennreal⦄ (hfg : f ≤ g) : ∫⁻ a, f a ∂μ ≤ ∫⁻ a, g a ∂ν := supr_le_supr $ λ φ, supr_le_supr2 $ λ hφ, ⟨le_trans hφ hfg, lintegral_mono (le_refl φ) hμν⟩ lemma lintegral_mono ⦃f g : α → ennreal⦄ (hfg : f ≤ g) : ∫⁻ a, f a ∂μ ≤ ∫⁻ a, g a ∂μ := lintegral_mono' (le_refl μ) hfg lemma lintegral_mono_nnreal {f g : α → ℝ≥0} (h : f ≤ g) : ∫⁻ a, f a ∂μ ≤ ∫⁻ a, g a ∂μ := begin refine lintegral_mono _, intro a, rw ennreal.coe_le_coe, exact h a, end lemma monotone_lintegral (μ : measure α) : monotone (lintegral μ) := lintegral_mono @[simp] lemma lintegral_const (c : ennreal) : ∫⁻ a, c ∂μ = c * μ univ := by rw [← simple_func.const_lintegral, ← simple_func.lintegral_eq_lintegral, simple_func.coe_const] @[simp] lemma lintegral_one : ∫⁻ a, (1 : ennreal) ∂μ = μ univ := by rw [lintegral_const, one_mul] lemma set_lintegral_const (s : set α) (c : ennreal) : ∫⁻ a in s, c ∂μ = c * μ s := by rw [lintegral_const, measure.restrict_apply_univ] lemma set_lintegral_one (s) : ∫⁻ a in s, 1 ∂μ = μ s := by rw [set_lintegral_const, one_mul] /-- `∫⁻ a in s, f a ∂μ` is defined as the supremum of integrals of simple functions `φ : α →ₛ ennreal` such that `φ ≤ f`. This lemma says that it suffices to take functions `φ : α →ₛ ℝ≥0`. -/ lemma lintegral_eq_nnreal (f : α → ennreal) (μ : measure α) : (∫⁻ a, f a ∂μ) = (⨆ (φ : α →ₛ ℝ≥0) (hf : ∀ x, ↑(φ x) ≤ f x), (φ.map (coe : ℝ≥0 → ennreal)).lintegral μ) := begin refine le_antisymm (bsupr_le $ assume φ hφ, _) (supr_le_supr2 $ λ φ, ⟨φ.map (coe : ℝ≥0 → ennreal), le_refl _⟩), by_cases h : ∀ᵐ a ∂μ, φ a ≠ ⊤, { let ψ := φ.map ennreal.to_nnreal, replace h : ψ.map (coe : ℝ≥0 → ennreal) =ᵐ[μ] φ := h.mono (λ a, ennreal.coe_to_nnreal), have : ∀ x, ↑(ψ x) ≤ f x := λ x, le_trans ennreal.coe_to_nnreal_le_self (hφ x), exact le_supr_of_le (φ.map ennreal.to_nnreal) (le_supr_of_le this (ge_of_eq $ lintegral_congr h)) }, { have h_meas : μ (φ ⁻¹' {⊤}) ≠ 0, from mt measure_zero_iff_ae_nmem.1 h, refine le_trans le_top (ge_of_eq $ (supr_eq_top _).2 $ λ b hb, _), obtain ⟨n, hn⟩ : ∃ n : ℕ, b < n * μ (φ ⁻¹' {⊤}), from exists_nat_mul_gt h_meas (ne_of_lt hb), use (const α (n : ℝ≥0)).restrict (φ ⁻¹' {⊤}), simp only [lt_supr_iff, exists_prop, coe_restrict, φ.is_measurable_preimage, coe_const, ennreal.coe_indicator, map_coe_ennreal_restrict, map_const, ennreal.coe_nat, restrict_const_lintegral], refine ⟨indicator_le (λ x hx, le_trans _ (hφ _)), hn⟩, simp only [mem_preimage, mem_singleton_iff] at hx, simp only [hx, le_top] } end lemma exists_simple_func_forall_lintegral_sub_lt_of_pos {f : α → ennreal} (h : ∫⁻ x, f x ∂μ < ⊤) {ε : ennreal} (hε : 0 < ε) : ∃ φ : α →ₛ ℝ≥0, (∀ x, ↑(φ x) ≤ f x) ∧ ∀ ψ : α →ₛ ℝ≥0, (∀ x, ↑(ψ x) ≤ f x) → (map coe (ψ - φ)).lintegral μ < ε := begin rw lintegral_eq_nnreal at h, have := ennreal.lt_add_right h hε, erw ennreal.bsupr_add at this; [skip, exact ⟨0, λ x, by simp⟩], simp_rw [lt_supr_iff, supr_lt_iff, supr_le_iff] at this, rcases this with ⟨φ, hle : ∀ x, ↑(φ x) ≤ f x, b, hbφ, hb⟩, refine ⟨φ, hle, λ ψ hψ, _⟩, have : (map coe φ).lintegral μ < ⊤, from (le_bsupr φ hle).trans_lt h, rw [← add_lt_add_iff_left this, ← add_lintegral, ← map_add @ennreal.coe_add], refine (hb _ (λ x, le_trans _ (max_le (hle x) (hψ x)))).trans_lt hbφ, norm_cast, simp only [add_apply, sub_apply, nnreal.add_sub_eq_max] end theorem supr_lintegral_le {ι : Sort*} (f : ι → α → ennreal) : (⨆i, ∫⁻ a, f i a ∂μ) ≤ (∫⁻ a, ⨆i, f i a ∂μ) := begin simp only [← supr_apply], exact (monotone_lintegral μ).le_map_supr end theorem supr2_lintegral_le {ι : Sort*} {ι' : ι → Sort*} (f : Π i, ι' i → α → ennreal) : (⨆i (h : ι' i), ∫⁻ a, f i h a ∂μ) ≤ (∫⁻ a, ⨆i (h : ι' i), f i h a ∂μ) := by { convert (monotone_lintegral μ).le_map_supr2 f, ext1 a, simp only [supr_apply] } theorem le_infi_lintegral {ι : Sort*} (f : ι → α → ennreal) : (∫⁻ a, ⨅i, f i a ∂μ) ≤ (⨅i, ∫⁻ a, f i a ∂μ) := by { simp only [← infi_apply], exact (monotone_lintegral μ).map_infi_le } theorem le_infi2_lintegral {ι : Sort*} {ι' : ι → Sort*} (f : Π i, ι' i → α → ennreal) : (∫⁻ a, ⨅ i (h : ι' i), f i h a ∂μ) ≤ (⨅ i (h : ι' i), ∫⁻ a, f i h a ∂μ) := by { convert (monotone_lintegral μ).map_infi2_le f, ext1 a, simp only [infi_apply] } lemma lintegral_mono_ae {f g : α → ennreal} (h : ∀ᵐ a ∂μ, f a ≤ g a) : (∫⁻ a, f a ∂μ) ≤ (∫⁻ a, g a ∂μ) := begin rcases exists_is_measurable_superset_of_null h with ⟨t, hts, ht, ht0⟩, have : ∀ᵐ x ∂μ, x ∉ t := measure_zero_iff_ae_nmem.1 ht0, refine (supr_le $ assume s, supr_le $ assume hfs, le_supr_of_le (s.restrict tᶜ) $ le_supr_of_le _ _), { assume a, by_cases a ∈ t; simp [h, restrict_apply, ht.compl], exact le_trans (hfs a) (by_contradiction $ assume hnfg, h (hts hnfg)) }, { refine le_of_eq (simple_func.lintegral_congr $ this.mono $ λ a hnt, _), by_cases hat : a ∈ t; simp [hat, ht.compl], exact (hnt hat).elim } end lemma lintegral_congr_ae {f g : α → ennreal} (h : f =ᵐ[μ] g) : (∫⁻ a, f a ∂μ) = (∫⁻ a, g a ∂μ) := le_antisymm (lintegral_mono_ae $ h.le) (lintegral_mono_ae $ h.symm.le) lemma lintegral_congr {f g : α → ennreal} (h : ∀ a, f a = g a) : (∫⁻ a, f a ∂μ) = (∫⁻ a, g a ∂μ) := by simp only [h] lemma set_lintegral_congr {f : α → ennreal} {s t : set α} (h : s =ᵐ[μ] t) : ∫⁻ x in s, f x ∂μ = ∫⁻ x in t, f x ∂μ := by rw [restrict_congr_set h] /-- Monotone convergence theorem -- sometimes called Beppo-Levi convergence. See `lintegral_supr_directed` for a more general form. -/ theorem lintegral_supr {f : ℕ → α → ennreal} (hf : ∀n, measurable (f n)) (h_mono : monotone f) : (∫⁻ a, ⨆n, f n a ∂μ) = (⨆n, ∫⁻ a, f n a ∂μ) := begin set c : ℝ≥0 → ennreal := coe, set F := λ a:α, ⨆n, f n a, have hF : measurable F := measurable_supr hf, refine le_antisymm _ (supr_lintegral_le _), rw [lintegral_eq_nnreal], refine supr_le (assume s, supr_le (assume hsf, _)), refine ennreal.le_of_forall_lt_one_mul_le (assume a ha, _), rcases ennreal.lt_iff_exists_coe.1 ha with ⟨r, rfl, ha⟩, have ha : r < 1 := ennreal.coe_lt_coe.1 ha, let rs := s.map (λa, r * a), have eq_rs : (const α r : α →ₛ ennreal) * map c s = rs.map c, { ext1 a, exact ennreal.coe_mul.symm }, have eq : ∀p, (rs.map c) ⁻¹' {p} = (⋃n, (rs.map c) ⁻¹' {p} ∩ {a | p ≤ f n a}), { assume p, rw [← inter_Union, ← inter_univ ((map c rs) ⁻¹' {p})] {occs := occurrences.pos [1]}, refine set.ext (assume x, and_congr_right $ assume hx, (true_iff _).2 _), by_cases p_eq : p = 0, { simp [p_eq] }, simp at hx, subst hx, have : r * s x ≠ 0, { rwa [(≠), ← ennreal.coe_eq_zero] }, have : s x ≠ 0, { refine mt _ this, assume h, rw [h, mul_zero] }, have : (rs.map c) x < ⨆ (n : ℕ), f n x, { refine lt_of_lt_of_le (ennreal.coe_lt_coe.2 (_)) (hsf x), suffices : r * s x < 1 * s x, simpa [rs], exact mul_lt_mul_of_pos_right ha (pos_iff_ne_zero.2 this) }, rcases lt_supr_iff.1 this with ⟨i, hi⟩, exact mem_Union.2 ⟨i, le_of_lt hi⟩ }, have mono : ∀r:ennreal, monotone (λn, (rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a}), { assume r i j h, refine inter_subset_inter (subset.refl _) _, assume x hx, exact le_trans hx (h_mono h x) }, have h_meas : ∀n, is_measurable {a : α | ⇑(map c rs) a ≤ f n a} := assume n, is_measurable_le (simple_func.measurable _) (hf n), calc (r:ennreal) * (s.map c).lintegral μ = ∑ r in (rs.map c).range, r * μ ((rs.map c) ⁻¹' {r}) : by rw [← const_mul_lintegral, eq_rs, simple_func.lintegral] ... ≤ ∑ r in (rs.map c).range, r * μ (⋃n, (rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a}) : le_of_eq (finset.sum_congr rfl $ assume x hx, by rw ← eq) ... ≤ ∑ r in (rs.map c).range, (⨆n, r * μ ((rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a})) : le_of_eq (finset.sum_congr rfl $ assume x hx, begin rw [measure_Union_eq_supr _ (directed_of_sup $ mono x), ennreal.mul_supr], { assume i, refine ((rs.map c).is_measurable_preimage _).inter _, exact hf i is_measurable_Ici } end) ... ≤ ⨆n, ∑ r in (rs.map c).range, r * μ ((rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a}) : begin refine le_of_eq _, rw [ennreal.finset_sum_supr_nat], assume p i j h, exact canonically_ordered_semiring.mul_le_mul (le_refl _) (measure_mono $ mono p h) end ... ≤ (⨆n:ℕ, ((rs.map c).restrict {a | (rs.map c) a ≤ f n a}).lintegral μ) : begin refine supr_le_supr (assume n, _), rw [restrict_lintegral _ (h_meas n)], { refine le_of_eq (finset.sum_congr rfl $ assume r hr, _), congr' 2 with a, refine and_congr_right _, simp {contextual := tt} } end ... ≤ (⨆n, ∫⁻ a, f n a ∂μ) : begin refine supr_le_supr (assume n, _), rw [← simple_func.lintegral_eq_lintegral], refine lintegral_mono (assume a, _), dsimp, rw [restrict_apply], split_ifs; simp, simpa using h, exact h_meas n end end /-- Monotone convergence theorem -- sometimes called Beppo-Levi convergence. Version with ae_measurable functions. -/ theorem lintegral_supr' {f : ℕ → α → ennreal} (hf : ∀n, ae_measurable (f n) μ) (h_mono : ∀ᵐ x ∂μ, monotone (λ n, f n x)) : (∫⁻ a, ⨆n, f n a ∂μ) = (⨆n, ∫⁻ a, f n a ∂μ) := begin simp_rw ←supr_apply, let p : α → (ℕ → ennreal) → Prop := λ x f', monotone f', have hp : ∀ᵐ x ∂μ, p x (λ i, f i x), from h_mono, have h_ae_seq_mono : monotone (ae_seq hf p), { intros n m hnm x, by_cases hx : x ∈ ae_seq_set hf p, { exact ae_seq.prop_of_mem_ae_seq_set hf hx hnm, }, { simp only [ae_seq, hx, if_false], exact le_refl _, }, }, rw lintegral_congr_ae (ae_seq.supr hf hp).symm, simp_rw supr_apply, rw @lintegral_supr _ _ μ _ (ae_seq.measurable hf p) h_ae_seq_mono, congr, exact funext (λ n, lintegral_congr_ae (ae_seq.ae_seq_n_eq_fun_n_ae hf hp n)), end lemma lintegral_eq_supr_eapprox_lintegral {f : α → ennreal} (hf : measurable f) : (∫⁻ a, f a ∂μ) = (⨆n, (eapprox f n).lintegral μ) := calc (∫⁻ a, f a ∂μ) = (∫⁻ a, ⨆n, (eapprox f n : α → ennreal) a ∂μ) : by congr; ext a; rw [supr_eapprox_apply f hf] ... = (⨆n, ∫⁻ a, (eapprox f n : α → ennreal) a ∂μ) : begin rw [lintegral_supr], { assume n, exact (eapprox f n).measurable }, { assume i j h, exact (monotone_eapprox f h) } end ... = (⨆n, (eapprox f n).lintegral μ) : by congr; ext n; rw [(eapprox f n).lintegral_eq_lintegral] /-- If `f` has finite integral, then `∫⁻ x in s, f x ∂μ` is absolutely continuous in `s`: it tends to zero as `μ s` tends to zero. This lemma states states this fact in terms of `ε` and `δ`. -/ lemma exists_pos_set_lintegral_lt_of_measure_lt {f : α → ennreal} (h : ∫⁻ x, f x ∂μ < ⊤) {ε : ennreal} (hε : 0 < ε) : ∃ δ > 0, ∀ s, μ s < δ → ∫⁻ x in s, f x ∂μ < ε := begin rcases exists_between hε with ⟨ε₂, hε₂0, hε₂ε⟩, rcases exists_between hε₂0 with ⟨ε₁, hε₁0, hε₁₂⟩, rcases exists_simple_func_forall_lintegral_sub_lt_of_pos h hε₁0 with ⟨φ, hle, hφ⟩, rcases φ.exists_forall_le with ⟨C, hC⟩, use [(ε₂ - ε₁) / C, ennreal.div_pos_iff.2 ⟨(zero_lt_sub_iff_lt.2 hε₁₂).ne', ennreal.coe_ne_top⟩], intros s hs, simp only [lintegral_eq_nnreal, supr_lt_iff, supr_le_iff], refine ⟨ε₂, hε₂ε, λ ψ hψ, _⟩, calc (map coe ψ).lintegral (μ.restrict s) ≤ (map coe φ).lintegral (μ.restrict s) + (map coe (ψ - φ)).lintegral (μ.restrict s) : begin rw [← simple_func.add_lintegral, ← simple_func.map_add @ennreal.coe_add], refine simple_func.lintegral_mono (λ x, _) le_rfl, simp [-ennreal.coe_add, nnreal.add_sub_eq_max, le_max_right] end ... ≤ (map coe φ).lintegral (μ.restrict s) + ε₁ : begin refine add_le_add le_rfl (le_trans _ (hφ _ hψ).le), exact simple_func.lintegral_mono le_rfl measure.restrict_le_self end ... ≤ (simple_func.const α (C : ennreal)).lintegral (μ.restrict s) + ε₁ : by { mono*, exacts [λ x, coe_le_coe.2 (hC x), le_rfl, le_rfl] } ... = C * μ s + ε₁ : by simp [← simple_func.lintegral_eq_lintegral] ... ≤ C * ((ε₂ - ε₁) / C) + ε₁ : by { mono*, exacts [le_rfl, hs.le, le_rfl] } ... ≤ (ε₂ - ε₁) + ε₁ : add_le_add mul_div_le le_rfl ... = ε₂ : sub_add_cancel_of_le hε₁₂.le, end /-- If `f` has finite integral, then `∫⁻ x in s, f x ∂μ` is absolutely continuous in `s`: it tends to zero as `μ s` tends to zero. -/ lemma tendsto_set_lintegral_zero {ι} {f : α → ennreal} (h : ∫⁻ x, f x ∂μ < ⊤) {l : filter ι} {s : ι → set α} (hl : tendsto (μ ∘ s) l (𝓝 0)) : tendsto (λ i, ∫⁻ x in s i, f x ∂μ) l (𝓝 0) := begin simp only [ennreal.nhds_zero, tendsto_infi, tendsto_principal, mem_Iio, ← pos_iff_ne_zero] at hl ⊢, intros ε ε0, rcases exists_pos_set_lintegral_lt_of_measure_lt h ε0 with ⟨δ, δ0, hδ⟩, exact (hl δ δ0).mono (λ i, hδ _) end @[simp] lemma lintegral_add {f g : α → ennreal} (hf : measurable f) (hg : measurable g) : (∫⁻ a, f a + g a ∂μ) = (∫⁻ a, f a ∂μ) + (∫⁻ a, g a ∂μ) := calc (∫⁻ a, f a + g a ∂μ) = (∫⁻ a, (⨆n, (eapprox f n : α → ennreal) a) + (⨆n, (eapprox g n : α → ennreal) a) ∂μ) : by simp only [supr_eapprox_apply, hf, hg] ... = (∫⁻ a, (⨆n, (eapprox f n + eapprox g n : α → ennreal) a) ∂μ) : begin congr, funext a, rw [ennreal.supr_add_supr_of_monotone], { refl }, { assume i j h, exact monotone_eapprox _ h a }, { assume i j h, exact monotone_eapprox _ h a }, end ... = (⨆n, (eapprox f n).lintegral μ + (eapprox g n).lintegral μ) : begin rw [lintegral_supr], { congr, funext n, rw [← simple_func.add_lintegral, ← simple_func.lintegral_eq_lintegral], refl }, { assume n, exact measurable.add (eapprox f n).measurable (eapprox g n).measurable }, { assume i j h a, exact add_le_add (monotone_eapprox _ h _) (monotone_eapprox _ h _) } end ... = (⨆n, (eapprox f n).lintegral μ) + (⨆n, (eapprox g n).lintegral μ) : by refine (ennreal.supr_add_supr_of_monotone _ _).symm; { assume i j h, exact simple_func.lintegral_mono (monotone_eapprox _ h) (le_refl μ) } ... = (∫⁻ a, f a ∂μ) + (∫⁻ a, g a ∂μ) : by rw [lintegral_eq_supr_eapprox_lintegral hf, lintegral_eq_supr_eapprox_lintegral hg] lemma lintegral_add' {f g : α → ennreal} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : (∫⁻ a, f a + g a ∂μ) = (∫⁻ a, f a ∂μ) + (∫⁻ a, g a ∂μ) := calc (∫⁻ a, f a + g a ∂μ) = (∫⁻ a, hf.mk f a + hg.mk g a ∂μ) : lintegral_congr_ae (eventually_eq.add hf.ae_eq_mk hg.ae_eq_mk) ... = (∫⁻ a, hf.mk f a ∂μ) + (∫⁻ a, hg.mk g a ∂μ) : lintegral_add hf.measurable_mk hg.measurable_mk ... = (∫⁻ a, f a ∂μ) + (∫⁻ a, g a ∂μ) : begin congr' 1, { exact lintegral_congr_ae hf.ae_eq_mk.symm }, { exact lintegral_congr_ae hg.ae_eq_mk.symm }, end lemma lintegral_zero : (∫⁻ a:α, 0 ∂μ) = 0 := by simp lemma lintegral_zero_fun : (∫⁻ a:α, (0 : α → ennreal) a ∂μ) = 0 := by simp @[simp] lemma lintegral_smul_measure (c : ennreal) (f : α → ennreal) : ∫⁻ a, f a ∂ (c • μ) = c * ∫⁻ a, f a ∂μ := by simp only [lintegral, supr_subtype', simple_func.lintegral_smul, ennreal.mul_supr, smul_eq_mul] @[simp] lemma lintegral_sum_measure {ι} (f : α → ennreal) (μ : ι → measure α) : ∫⁻ a, f a ∂(measure.sum μ) = ∑' i, ∫⁻ a, f a ∂(μ i) := begin simp only [lintegral, supr_subtype', simple_func.lintegral_sum, ennreal.tsum_eq_supr_sum], rw [supr_comm], congr, funext s, induction s using finset.induction_on with i s hi hs, { apply bot_unique, simp }, simp only [finset.sum_insert hi, ← hs], refine (ennreal.supr_add_supr _).symm, intros φ ψ, exact ⟨⟨φ ⊔ ψ, λ x, sup_le (φ.2 x) (ψ.2 x)⟩, add_le_add (simple_func.lintegral_mono le_sup_left (le_refl _)) (finset.sum_le_sum $ λ j hj, simple_func.lintegral_mono le_sup_right (le_refl _))⟩ end @[simp] lemma lintegral_add_measure (f : α → ennreal) (μ ν : measure α) : ∫⁻ a, f a ∂ (μ + ν) = ∫⁻ a, f a ∂μ + ∫⁻ a, f a ∂ν := by simpa [tsum_fintype] using lintegral_sum_measure f (λ b, cond b μ ν) @[simp] lemma lintegral_zero_measure (f : α → ennreal) : ∫⁻ a, f a ∂0 = 0 := bot_unique $ by simp [lintegral] lemma lintegral_finset_sum (s : finset β) {f : β → α → ennreal} (hf : ∀b, measurable (f b)) : (∫⁻ a, ∑ b in s, f b a ∂μ) = ∑ b in s, ∫⁻ a, f b a ∂μ := begin refine finset.induction_on s _ _, { simp }, { assume a s has ih, simp only [finset.sum_insert has], rw [lintegral_add (hf _) (s.measurable_sum hf), ih] } end @[simp] lemma lintegral_const_mul (r : ennreal) {f : α → ennreal} (hf : measurable f) : (∫⁻ a, r * f a ∂μ) = r * (∫⁻ a, f a ∂μ) := calc (∫⁻ a, r * f a ∂μ) = (∫⁻ a, (⨆n, (const α r * eapprox f n) a) ∂μ) : by { congr, funext a, rw [← supr_eapprox_apply f hf, ennreal.mul_supr], refl } ... = (⨆n, r * (eapprox f n).lintegral μ) : begin rw [lintegral_supr], { congr, funext n, rw [← simple_func.const_mul_lintegral, ← simple_func.lintegral_eq_lintegral] }, { assume n, exact simple_func.measurable _ }, { assume i j h a, exact canonically_ordered_semiring.mul_le_mul (le_refl _) (monotone_eapprox _ h _) } end ... = r * (∫⁻ a, f a ∂μ) : by rw [← ennreal.mul_supr, lintegral_eq_supr_eapprox_lintegral hf] lemma lintegral_const_mul'' (r : ennreal) {f : α → ennreal} (hf : ae_measurable f μ) : (∫⁻ a, r * f a ∂μ) = r * (∫⁻ a, f a ∂μ) := begin have A : ∫⁻ a, f a ∂μ = ∫⁻ a, hf.mk f a ∂μ := lintegral_congr_ae hf.ae_eq_mk, have B : ∫⁻ a, r * f a ∂μ = ∫⁻ a, r * hf.mk f a ∂μ := lintegral_congr_ae (eventually_eq.fun_comp hf.ae_eq_mk _), rw [A, B, lintegral_const_mul _ hf.measurable_mk], end lemma lintegral_const_mul_le (r : ennreal) (f : α → ennreal) : r * (∫⁻ a, f a ∂μ) ≤ (∫⁻ a, r * f a ∂μ) := begin rw [lintegral, ennreal.mul_supr], refine supr_le (λs, _), rw [ennreal.mul_supr], simp only [supr_le_iff, ge_iff_le], assume hs, rw ← simple_func.const_mul_lintegral, refine le_supr_of_le (const α r * s) (le_supr_of_le (λx, _) (le_refl _)), exact canonically_ordered_semiring.mul_le_mul (le_refl _) (hs x) end lemma lintegral_const_mul' (r : ennreal) (f : α → ennreal) (hr : r ≠ ⊤) : (∫⁻ a, r * f a ∂μ) = r * (∫⁻ a, f a ∂μ) := begin by_cases h : r = 0, { simp [h] }, apply le_antisymm _ (lintegral_const_mul_le r f), have rinv : r * r⁻¹ = 1 := ennreal.mul_inv_cancel h hr, have rinv' : r ⁻¹ * r = 1, by { rw mul_comm, exact rinv }, have := lintegral_const_mul_le (r⁻¹) (λx, r * f x), simp [(mul_assoc _ _ _).symm, rinv'] at this, simpa [(mul_assoc _ _ _).symm, rinv] using canonically_ordered_semiring.mul_le_mul (le_refl r) this end lemma lintegral_mul_const (r : ennreal) {f : α → ennreal} (hf : measurable f) : ∫⁻ a, f a * r ∂μ = ∫⁻ a, f a ∂μ * r := by simp_rw [mul_comm, lintegral_const_mul r hf] lemma lintegral_mul_const'' (r : ennreal) {f : α → ennreal} (hf : ae_measurable f μ) : ∫⁻ a, f a * r ∂μ = ∫⁻ a, f a ∂μ * r := by simp_rw [mul_comm, lintegral_const_mul'' r hf] lemma lintegral_mul_const_le (r : ennreal) (f : α → ennreal) : ∫⁻ a, f a ∂μ * r ≤ ∫⁻ a, f a * r ∂μ := by simp_rw [mul_comm, lintegral_const_mul_le r f] lemma lintegral_mul_const' (r : ennreal) (f : α → ennreal) (hr : r ≠ ⊤): ∫⁻ a, f a * r ∂μ = ∫⁻ a, f a ∂μ * r := by simp_rw [mul_comm, lintegral_const_mul' r f hr] /- A double integral of a product where each factor contains only one variable is a product of integrals -/ lemma lintegral_lintegral_mul {β} [measurable_space β] {ν : measure β} {f : α → ennreal} {g : β → ennreal} (hf : measurable f) (hg : measurable g) : ∫⁻ x, ∫⁻ y, f x * g y ∂ν ∂μ = ∫⁻ x, f x ∂μ * ∫⁻ y, g y ∂ν := by simp [lintegral_const_mul _ hg, lintegral_mul_const _ hf] -- TODO: Need a better way of rewriting inside of a integral lemma lintegral_rw₁ {f f' : α → β} (h : f =ᵐ[μ] f') (g : β → ennreal) : (∫⁻ a, g (f a) ∂μ) = (∫⁻ a, g (f' a) ∂μ) := lintegral_congr_ae $ h.mono $ λ a h, by rw h -- TODO: Need a better way of rewriting inside of a integral lemma lintegral_rw₂ {f₁ f₁' : α → β} {f₂ f₂' : α → γ} (h₁ : f₁ =ᵐ[μ] f₁') (h₂ : f₂ =ᵐ[μ] f₂') (g : β → γ → ennreal) : (∫⁻ a, g (f₁ a) (f₂ a) ∂μ) = (∫⁻ a, g (f₁' a) (f₂' a) ∂μ) := lintegral_congr_ae $ h₁.mp $ h₂.mono $ λ _ h₂ h₁, by rw [h₁, h₂] @[simp] lemma lintegral_indicator (f : α → ennreal) {s : set α} (hs : is_measurable s) : ∫⁻ a, s.indicator f a ∂μ = ∫⁻ a in s, f a ∂μ := begin simp only [lintegral, ← restrict_lintegral_eq_lintegral_restrict _ hs, supr_subtype'], apply le_antisymm; refine supr_le_supr2 (subtype.forall.2 $ λ φ hφ, _), { refine ⟨⟨φ, le_trans hφ (indicator_le_self _ _)⟩, _⟩, refine simple_func.lintegral_mono (λ x, _) (le_refl _), by_cases hx : x ∈ s, { simp [hx, hs, le_refl] }, { apply le_trans (hφ x), simp [hx, hs, le_refl] } }, { refine ⟨⟨φ.restrict s, λ x, _⟩, le_refl _⟩, simp [hφ x, hs, indicator_le_indicator] } end /-- Chebyshev's inequality -/ lemma mul_meas_ge_le_lintegral {f : α → ennreal} (hf : measurable f) (ε : ennreal) : ε * μ {x | ε ≤ f x} ≤ ∫⁻ a, f a ∂μ := begin have : is_measurable {a : α | ε ≤ f a }, from hf is_measurable_Ici, rw [← simple_func.restrict_const_lintegral _ this, ← simple_func.lintegral_eq_lintegral], refine lintegral_mono (λ a, _), simp only [restrict_apply _ this], split_ifs; [assumption, exact zero_le _] end lemma meas_ge_le_lintegral_div {f : α → ennreal} (hf : measurable f) {ε : ennreal} (hε : ε ≠ 0) (hε' : ε ≠ ⊤) : μ {x | ε ≤ f x} ≤ (∫⁻ a, f a ∂μ) / ε := (ennreal.le_div_iff_mul_le (or.inl hε) (or.inl hε')).2 $ by { rw [mul_comm], exact mul_meas_ge_le_lintegral hf ε } @[simp] lemma lintegral_eq_zero_iff {f : α → ennreal} (hf : measurable f) : ∫⁻ a, f a ∂μ = 0 ↔ (f =ᵐ[μ] 0) := begin refine iff.intro (assume h, _) (assume h, _), { have : ∀n:ℕ, ∀ᵐ a ∂μ, f a < n⁻¹, { assume n, rw [ae_iff, ← nonpos_iff_eq_zero, ← @ennreal.zero_div n⁻¹, ennreal.le_div_iff_mul_le, mul_comm], simp only [not_lt], -- TODO: why `rw ← h` fails with "not an equality or an iff"? exacts [h ▸ mul_meas_ge_le_lintegral hf n⁻¹, or.inl (ennreal.inv_ne_zero.2 ennreal.coe_nat_ne_top), or.inr ennreal.zero_ne_top] }, refine (ae_all_iff.2 this).mono (λ a ha, _), by_contradiction h, rcases ennreal.exists_inv_nat_lt h with ⟨n, hn⟩, exact (lt_irrefl _ $ lt_trans hn $ ha n).elim }, { calc ∫⁻ a, f a ∂μ = ∫⁻ a, 0 ∂μ : lintegral_congr_ae h ... = 0 : lintegral_zero } end @[simp] lemma lintegral_eq_zero_iff' {f : α → ennreal} (hf : ae_measurable f μ) : ∫⁻ a, f a ∂μ = 0 ↔ (f =ᵐ[μ] 0) := begin have : ∫⁻ a, f a ∂μ = ∫⁻ a, hf.mk f a ∂μ := lintegral_congr_ae hf.ae_eq_mk, rw [this, lintegral_eq_zero_iff hf.measurable_mk], exact ⟨λ H, hf.ae_eq_mk.trans H, λ H, hf.ae_eq_mk.symm.trans H⟩ end lemma lintegral_pos_iff_support {f : α → ennreal} (hf : measurable f) : 0 < ∫⁻ a, f a ∂μ ↔ 0 < μ (function.support f) := by simp [pos_iff_ne_zero, hf, filter.eventually_eq, ae_iff, function.support] /-- Weaker version of the monotone convergence theorem-/ lemma lintegral_supr_ae {f : ℕ → α → ennreal} (hf : ∀n, measurable (f n)) (h_mono : ∀n, ∀ᵐ a ∂μ, f n a ≤ f n.succ a) : (∫⁻ a, ⨆n, f n a ∂μ) = (⨆n, ∫⁻ a, f n a ∂μ) := let ⟨s, hs⟩ := exists_is_measurable_superset_of_null (ae_iff.1 (ae_all_iff.2 h_mono)) in let g := λ n a, if a ∈ s then 0 else f n a in have g_eq_f : ∀ᵐ a ∂μ, ∀n, g n a = f n a, from (measure_zero_iff_ae_nmem.1 hs.2.2).mono (assume a ha n, if_neg ha), calc ∫⁻ a, ⨆n, f n a ∂μ = ∫⁻ a, ⨆n, g n a ∂μ : lintegral_congr_ae $ g_eq_f.mono $ λ a ha, by simp only [ha] ... = ⨆n, (∫⁻ a, g n a ∂μ) : lintegral_supr (assume n, measurable_const.piecewise hs.2.1 (hf n)) (monotone_of_monotone_nat $ assume n a, classical.by_cases (assume h : a ∈ s, by simp [g, if_pos h]) (assume h : a ∉ s, begin simp only [g, if_neg h], have := hs.1, rw subset_def at this, have := mt (this a) h, simp only [not_not, mem_set_of_eq] at this, exact this n end)) ... = ⨆n, (∫⁻ a, f n a ∂μ) : by simp only [lintegral_congr_ae (g_eq_f.mono $ λ a ha, ha _)] lemma lintegral_sub {f g : α → ennreal} (hf : measurable f) (hg : measurable g) (hg_fin : ∫⁻ a, g a ∂μ < ⊤) (h_le : g ≤ᵐ[μ] f) : ∫⁻ a, f a - g a ∂μ = ∫⁻ a, f a ∂μ - ∫⁻ a, g a ∂μ := begin rw [← ennreal.add_left_inj hg_fin, ennreal.sub_add_cancel_of_le (lintegral_mono_ae h_le), ← lintegral_add (hf.ennreal_sub hg) hg], refine lintegral_congr_ae (h_le.mono $ λ x hx, _), exact ennreal.sub_add_cancel_of_le hx end /-- Monotone convergence theorem for nonincreasing sequences of functions -/ lemma lintegral_infi_ae {f : ℕ → α → ennreal} (h_meas : ∀n, measurable (f n)) (h_mono : ∀n:ℕ, f n.succ ≤ᵐ[μ] f n) (h_fin : ∫⁻ a, f 0 a ∂μ < ⊤) : ∫⁻ a, ⨅n, f n a ∂μ = ⨅n, ∫⁻ a, f n a ∂μ := have fn_le_f0 : ∫⁻ a, ⨅n, f n a ∂μ ≤ ∫⁻ a, f 0 a ∂μ, from lintegral_mono (assume a, infi_le_of_le 0 (le_refl _)), have fn_le_f0' : (⨅n, ∫⁻ a, f n a ∂μ) ≤ ∫⁻ a, f 0 a ∂μ, from infi_le_of_le 0 (le_refl _), (ennreal.sub_right_inj h_fin fn_le_f0 fn_le_f0').1 $ show ∫⁻ a, f 0 a ∂μ - ∫⁻ a, ⨅n, f n a ∂μ = ∫⁻ a, f 0 a ∂μ - (⨅n, ∫⁻ a, f n a ∂μ), from calc ∫⁻ a, f 0 a ∂μ - (∫⁻ a, ⨅n, f n a ∂μ) = ∫⁻ a, f 0 a - ⨅n, f n a ∂μ: (lintegral_sub (h_meas 0) (measurable_infi h_meas) (calc (∫⁻ a, ⨅n, f n a ∂μ) ≤ ∫⁻ a, f 0 a ∂μ : lintegral_mono (assume a, infi_le _ _) ... < ⊤ : h_fin ) (ae_of_all _ $ assume a, infi_le _ _)).symm ... = ∫⁻ a, ⨆n, f 0 a - f n a ∂μ : congr rfl (funext (assume a, ennreal.sub_infi)) ... = ⨆n, ∫⁻ a, f 0 a - f n a ∂μ : lintegral_supr_ae (assume n, (h_meas 0).ennreal_sub (h_meas n)) (assume n, (h_mono n).mono $ assume a ha, ennreal.sub_le_sub (le_refl _) ha) ... = ⨆n, ∫⁻ a, f 0 a ∂μ - ∫⁻ a, f n a ∂μ : have h_mono : ∀ᵐ a ∂μ, ∀n:ℕ, f n.succ a ≤ f n a := ae_all_iff.2 h_mono, have h_mono : ∀n, ∀ᵐ a ∂μ, f n a ≤ f 0 a := assume n, h_mono.mono $ assume a h, begin induction n with n ih, {exact le_refl _}, {exact le_trans (h n) ih} end, congr rfl (funext $ assume n, lintegral_sub (h_meas _) (h_meas _) (calc ∫⁻ a, f n a ∂μ ≤ ∫⁻ a, f 0 a ∂μ : lintegral_mono_ae $ h_mono n ... < ⊤ : h_fin) (h_mono n)) ... = ∫⁻ a, f 0 a ∂μ - ⨅n, ∫⁻ a, f n a ∂μ : ennreal.sub_infi.symm /-- Monotone convergence theorem for nonincreasing sequences of functions -/ lemma lintegral_infi {f : ℕ → α → ennreal} (h_meas : ∀n, measurable (f n)) (h_mono : ∀ ⦃m n⦄, m ≤ n → f n ≤ f m) (h_fin : ∫⁻ a, f 0 a ∂μ < ⊤) : ∫⁻ a, ⨅n, f n a ∂μ = ⨅n, ∫⁻ a, f n a ∂μ := lintegral_infi_ae h_meas (λ n, ae_of_all _ $ h_mono $ le_of_lt n.lt_succ_self) h_fin /-- Known as Fatou's lemma, version with `ae_measurable` functions -/ lemma lintegral_liminf_le' {f : ℕ → α → ennreal} (h_meas : ∀n, ae_measurable (f n) μ) : ∫⁻ a, liminf at_top (λ n, f n a) ∂μ ≤ liminf at_top (λ n, ∫⁻ a, f n a ∂μ) := calc ∫⁻ a, liminf at_top (λ n, f n a) ∂μ = ∫⁻ a, ⨆n:ℕ, ⨅i≥n, f i a ∂μ : by simp only [liminf_eq_supr_infi_of_nat] ... = ⨆n:ℕ, ∫⁻ a, ⨅i≥n, f i a ∂μ : lintegral_supr' (assume n, ae_measurable_binfi _ (countable_encodable _) h_meas) (ae_of_all μ (assume a n m hnm, infi_le_infi_of_subset $ λ i hi, le_trans hnm hi)) ... ≤ ⨆n:ℕ, ⨅i≥n, ∫⁻ a, f i a ∂μ : supr_le_supr $ λ n, le_infi2_lintegral _ ... = at_top.liminf (λ n, ∫⁻ a, f n a ∂μ) : filter.liminf_eq_supr_infi_of_nat.symm /-- Known as Fatou's lemma -/ lemma lintegral_liminf_le {f : ℕ → α → ennreal} (h_meas : ∀n, measurable (f n)) : ∫⁻ a, liminf at_top (λ n, f n a) ∂μ ≤ liminf at_top (λ n, ∫⁻ a, f n a ∂μ) := lintegral_liminf_le' (λ n, (h_meas n).ae_measurable) lemma limsup_lintegral_le {f : ℕ → α → ennreal} {g : α → ennreal} (hf_meas : ∀ n, measurable (f n)) (h_bound : ∀n, f n ≤ᵐ[μ] g) (h_fin : ∫⁻ a, g a ∂μ < ⊤) : limsup at_top (λn, ∫⁻ a, f n a ∂μ) ≤ ∫⁻ a, limsup at_top (λn, f n a) ∂μ := calc limsup at_top (λn, ∫⁻ a, f n a ∂μ) = ⨅n:ℕ, ⨆i≥n, ∫⁻ a, f i a ∂μ : limsup_eq_infi_supr_of_nat ... ≤ ⨅n:ℕ, ∫⁻ a, ⨆i≥n, f i a ∂μ : infi_le_infi $ assume n, supr2_lintegral_le _ ... = ∫⁻ a, ⨅n:ℕ, ⨆i≥n, f i a ∂μ : begin refine (lintegral_infi _ _ _).symm, { assume n, exact measurable_bsupr _ (countable_encodable _) hf_meas }, { assume n m hnm a, exact (supr_le_supr_of_subset $ λ i hi, le_trans hnm hi) }, { refine lt_of_le_of_lt (lintegral_mono_ae _) h_fin, refine (ae_all_iff.2 h_bound).mono (λ n hn, _), exact supr_le (λ i, supr_le $ λ hi, hn i) } end ... = ∫⁻ a, limsup at_top (λn, f n a) ∂μ : by simp only [limsup_eq_infi_supr_of_nat] /-- Dominated convergence theorem for nonnegative functions -/ lemma tendsto_lintegral_of_dominated_convergence {F : ℕ → α → ennreal} {f : α → ennreal} (bound : α → ennreal) (hF_meas : ∀n, measurable (F n)) (h_bound : ∀n, F n ≤ᵐ[μ] bound) (h_fin : ∫⁻ a, bound a ∂μ < ⊤) (h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) at_top (𝓝 (f a))) : tendsto (λn, ∫⁻ a, F n a ∂μ) at_top (𝓝 (∫⁻ a, f a ∂μ)) := tendsto_of_le_liminf_of_limsup_le (calc ∫⁻ a, f a ∂μ = ∫⁻ a, liminf at_top (λ (n : ℕ), F n a) ∂μ : lintegral_congr_ae $ h_lim.mono $ assume a h, h.liminf_eq.symm ... ≤ liminf at_top (λ n, ∫⁻ a, F n a ∂μ) : lintegral_liminf_le hF_meas) (calc limsup at_top (λ (n : ℕ), ∫⁻ a, F n a ∂μ) ≤ ∫⁻ a, limsup at_top (λn, F n a) ∂μ : limsup_lintegral_le hF_meas h_bound h_fin ... = ∫⁻ a, f a ∂μ : lintegral_congr_ae $ h_lim.mono $ λ a h, h.limsup_eq) /-- Dominated convergence theorem for nonnegative functions which are just almost everywhere measurable. -/ lemma tendsto_lintegral_of_dominated_convergence' {F : ℕ → α → ennreal} {f : α → ennreal} (bound : α → ennreal) (hF_meas : ∀n, ae_measurable (F n) μ) (h_bound : ∀n, F n ≤ᵐ[μ] bound) (h_fin : ∫⁻ a, bound a ∂μ < ⊤) (h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) at_top (𝓝 (f a))) : tendsto (λn, ∫⁻ a, F n a ∂μ) at_top (𝓝 (∫⁻ a, f a ∂μ)) := begin have : ∀ n, ∫⁻ a, F n a ∂μ = ∫⁻ a, (hF_meas n).mk (F n) a ∂μ := λ n, lintegral_congr_ae (hF_meas n).ae_eq_mk, simp_rw this, apply tendsto_lintegral_of_dominated_convergence bound (λ n, (hF_meas n).measurable_mk) _ h_fin, { have : ∀ n, ∀ᵐ a ∂μ, (hF_meas n).mk (F n) a = F n a := λ n, (hF_meas n).ae_eq_mk.symm, have : ∀ᵐ a ∂μ, ∀ n, (hF_meas n).mk (F n) a = F n a := ae_all_iff.mpr this, filter_upwards [this, h_lim], assume a H H', simp_rw H, exact H' }, { assume n, filter_upwards [h_bound n, (hF_meas n).ae_eq_mk], assume a H H', rwa H' at H } end /-- Dominated convergence theorem for filters with a countable basis -/ lemma tendsto_lintegral_filter_of_dominated_convergence {ι} {l : filter ι} {F : ι → α → ennreal} {f : α → ennreal} (bound : α → ennreal) (hl_cb : l.is_countably_generated) (hF_meas : ∀ᶠ n in l, measurable (F n)) (h_bound : ∀ᶠ n in l, ∀ᵐ a ∂μ, F n a ≤ bound a) (h_fin : ∫⁻ a, bound a ∂μ < ⊤) (h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) l (𝓝 (f a))) : tendsto (λn, ∫⁻ a, F n a ∂μ) l (𝓝 $ ∫⁻ a, f a ∂μ) := begin rw hl_cb.tendsto_iff_seq_tendsto, { intros x xl, have hxl, { rw tendsto_at_top' at xl, exact xl }, have h := inter_mem_sets hF_meas h_bound, replace h := hxl _ h, rcases h with ⟨k, h⟩, rw ← tendsto_add_at_top_iff_nat k, refine tendsto_lintegral_of_dominated_convergence _ _ _ _ _, { exact bound }, { intro, refine (h _ _).1, exact nat.le_add_left _ _ }, { intro, refine (h _ _).2, exact nat.le_add_left _ _ }, { assumption }, { refine h_lim.mono (λ a h_lim, _), apply @tendsto.comp _ _ _ (λn, x (n + k)) (λn, F n a), { assumption }, rw tendsto_add_at_top_iff_nat, assumption } }, end section open encodable /-- Monotone convergence for a suprema over a directed family and indexed by an encodable type -/ theorem lintegral_supr_directed [encodable β] {f : β → α → ennreal} (hf : ∀b, measurable (f b)) (h_directed : directed (≤) f) : ∫⁻ a, ⨆b, f b a ∂μ = ⨆b, ∫⁻ a, f b a ∂μ := begin by_cases hβ : nonempty β, swap, { simp [supr_of_empty hβ] }, resetI, inhabit β, have : ∀a, (⨆ b, f b a) = (⨆ n, f (h_directed.sequence f n) a), { assume a, refine le_antisymm (supr_le $ assume b, _) (supr_le $ assume n, le_supr (λn, f n a) _), exact le_supr_of_le (encode b + 1) (h_directed.le_sequence b a) }, calc ∫⁻ a, ⨆ b, f b a ∂μ = ∫⁻ a, ⨆ n, f (h_directed.sequence f n) a ∂μ : by simp only [this] ... = ⨆ n, ∫⁻ a, f (h_directed.sequence f n) a ∂μ : lintegral_supr (assume n, hf _) h_directed.sequence_mono ... = ⨆ b, ∫⁻ a, f b a ∂μ : begin refine le_antisymm (supr_le $ assume n, _) (supr_le $ assume b, _), { exact le_supr (λb, ∫⁻ a, f b a ∂μ) _ }, { exact le_supr_of_le (encode b + 1) (lintegral_mono $ h_directed.le_sequence b) } end end end lemma lintegral_tsum [encodable β] {f : β → α → ennreal} (hf : ∀i, measurable (f i)) : ∫⁻ a, ∑' i, f i a ∂μ = ∑' i, ∫⁻ a, f i a ∂μ := begin simp only [ennreal.tsum_eq_supr_sum], rw [lintegral_supr_directed], { simp [lintegral_finset_sum _ hf] }, { assume b, exact finset.measurable_sum _ hf }, { assume s t, use [s ∪ t], split, exact assume a, finset.sum_le_sum_of_subset (finset.subset_union_left _ _), exact assume a, finset.sum_le_sum_of_subset (finset.subset_union_right _ _) } end open measure lemma lintegral_Union [encodable β] {s : β → set α} (hm : ∀ i, is_measurable (s i)) (hd : pairwise (disjoint on s)) (f : α → ennreal) : ∫⁻ a in ⋃ i, s i, f a ∂μ = ∑' i, ∫⁻ a in s i, f a ∂μ := by simp only [measure.restrict_Union hd hm, lintegral_sum_measure] lemma lintegral_Union_le [encodable β] (s : β → set α) (f : α → ennreal) : ∫⁻ a in ⋃ i, s i, f a ∂μ ≤ ∑' i, ∫⁻ a in s i, f a ∂μ := begin rw [← lintegral_sum_measure], exact lintegral_mono' restrict_Union_le (le_refl _) end lemma lintegral_map [measurable_space β] {f : β → ennreal} {g : α → β} (hf : measurable f) (hg : measurable g) : ∫⁻ a, f a ∂(map g μ) = ∫⁻ a, f (g a) ∂μ := begin simp only [lintegral_eq_supr_eapprox_lintegral, hf, hf.comp hg], { congr, funext n, symmetry, apply simple_func.lintegral_map, { assume a, exact congr_fun (simple_func.eapprox_comp hf hg) a }, { assume s hs, exact map_apply hg hs } }, end lemma lintegral_map' [measurable_space β] {f : β → ennreal} {g : α → β} (hf : ae_measurable f (measure.map g μ)) (hg : measurable g) : ∫⁻ a, f a ∂(measure.map g μ) = ∫⁻ a, f (g a) ∂μ := calc ∫⁻ a, f a ∂(measure.map g μ) = ∫⁻ a, hf.mk f a ∂(measure.map g μ) : lintegral_congr_ae hf.ae_eq_mk ... = ∫⁻ a, hf.mk f (g a) ∂μ : lintegral_map hf.measurable_mk hg ... = ∫⁻ a, f (g a) ∂μ : lintegral_congr_ae (ae_eq_comp hg hf.ae_eq_mk.symm) lemma lintegral_comp [measurable_space β] {f : β → ennreal} {g : α → β} (hf : measurable f) (hg : measurable g) : lintegral μ (f ∘ g) = ∫⁻ a, f a ∂(map g μ) := (lintegral_map hf hg).symm lemma set_lintegral_map [measurable_space β] {f : β → ennreal} {g : α → β} {s : set β} (hs : is_measurable s) (hf : measurable f) (hg : measurable g) : ∫⁻ y in s, f y ∂(map g μ) = ∫⁻ x in g ⁻¹' s, f (g x) ∂μ := by rw [restrict_map hg hs, lintegral_map hf hg] lemma lintegral_dirac' (a : α) {f : α → ennreal} (hf : measurable f) : ∫⁻ a, f a ∂(dirac a) = f a := by simp [lintegral_congr_ae (ae_eq_dirac' hf)] lemma lintegral_dirac [measurable_singleton_class α] (a : α) (f : α → ennreal) : ∫⁻ a, f a ∂(dirac a) = f a := by simp [lintegral_congr_ae (ae_eq_dirac f)] lemma lintegral_count' {f : α → ennreal} (hf : measurable f) : ∫⁻ a, f a ∂count = ∑' a, f a := begin rw [count, lintegral_sum_measure], congr, exact funext (λ a, lintegral_dirac' a hf), end lemma lintegral_count [measurable_singleton_class α] (f : α → ennreal) : ∫⁻ a, f a ∂count = ∑' a, f a := begin rw [count, lintegral_sum_measure], congr, exact funext (λ a, lintegral_dirac a f), end lemma ae_lt_top {f : α → ennreal} (hf : measurable f) (h2f : ∫⁻ x, f x ∂μ < ⊤) : ∀ᵐ x ∂μ, f x < ⊤ := begin simp_rw [ae_iff, ennreal.not_lt_top], by_contra h, rw [← not_le] at h2f, apply h2f, have : (f ⁻¹' {⊤}).indicator ⊤ ≤ f, { intro x, by_cases hx : x ∈ f ⁻¹' {⊤}; [simpa [hx], simp [hx]] }, convert lintegral_mono this, rw [lintegral_indicator _ (hf (is_measurable_singleton ⊤))], simp [ennreal.top_mul, preimage, h] end /-- Given a measure `μ : measure α` and a function `f : α → ennreal`, `μ.with_density f` is the measure such that for a measurable set `s` we have `μ.with_density f s = ∫⁻ a in s, f a ∂μ`. -/ def measure.with_density (μ : measure α) (f : α → ennreal) : measure α := measure.of_measurable (λs hs, ∫⁻ a in s, f a ∂μ) (by simp) (λ s hs hd, lintegral_Union hs hd _) @[simp] lemma with_density_apply (f : α → ennreal) {s : set α} (hs : is_measurable s) : μ.with_density f s = ∫⁻ a in s, f a ∂μ := measure.of_measurable_apply s hs end lintegral end measure_theory open measure_theory measure_theory.simple_func /-- To prove something for an arbitrary measurable function into `ennreal`, it suffices to show that the property holds for (multiples of) characteristic functions and is closed under addition and supremum of increasing sequences of functions. It is possible to make the hypotheses in the induction steps a bit stronger, and such conditions can be added once we need them (for example in `h_sum` it is only necessary to consider the sum of a simple function with a multiple of a characteristic function and that the intersection of their images is a subset of `{0}`. -/ @[elab_as_eliminator] theorem measurable.ennreal_induction {α} [measurable_space α] {P : (α → ennreal) → Prop} (h_ind : ∀ (c : ennreal) ⦃s⦄, is_measurable s → P (indicator s (λ _, c))) (h_sum : ∀ ⦃f g : α → ennreal⦄, set.univ ⊆ f ⁻¹' {0} ∪ g ⁻¹' {0} → measurable f → measurable g → P f → P g → P (f + g)) (h_supr : ∀ ⦃f : ℕ → α → ennreal⦄ (hf : ∀n, measurable (f n)) (h_mono : monotone f) (hP : ∀ n, P (f n)), P (λ x, ⨆ n, f n x)) ⦃f : α → ennreal⦄ (hf : measurable f) : P f := begin convert h_supr (λ n, (eapprox f n).measurable) (monotone_eapprox f) _, { ext1 x, rw [supr_eapprox_apply f hf] }, { exact λ n, simple_func.induction (λ c s hs, h_ind c hs) (λ f g hfg hf hg, h_sum hfg f.measurable g.measurable hf hg) (eapprox f n) } end namespace measure_theory /-- This is Exercise 1.2.1 from [tao2010]. It allows you to express integration of a measurable function with respect to `(μ.with_density f)` as an integral with respect to `μ`, called the base measure. `μ` is often the Lebesgue measure, and in this circumstance `f` is the probability density function, and `(μ.with_density f)` represents any continuous random variable as a probability measure, such as the uniform distribution between 0 and 1, the Gaussian distribution, the exponential distribution, the Beta distribution, or the Cauchy distribution (see Section 2.4 of [wasserman2004]). Thus, this method shows how to one can calculate expectations, variances, and other moments as a function of the probability density function. -/ lemma lintegral_with_density_eq_lintegral_mul {α} [measurable_space α] (μ : measure α) {f : α → ennreal} (h_mf : measurable f) : ∀ {g : α → ennreal}, measurable g → ∫⁻ a, g a ∂(μ.with_density f) = ∫⁻ a, (f * g) a ∂μ := begin apply measurable.ennreal_induction, { intros c s h_ms, simp [*, mul_comm _ c] }, { intros g h h_univ h_mea_g h_mea_h h_ind_g h_ind_h, simp [mul_add, *, measurable.ennreal_mul] }, { intros g h_mea_g h_mono_g h_ind, have : monotone (λ n a, f a * g n a) := λ m n hmn x, ennreal.mul_le_mul le_rfl (h_mono_g hmn x), simp [lintegral_supr, ennreal.mul_supr, h_mf.ennreal_mul (h_mea_g _), *] } end end measure_theory
fd8c338c8024e2faa405b6620d7aee7ae1bcfe68
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/logic/basic.lean
c99f87e5c17e44c71d6c3c2ddb3a4299d129d4e0
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
39,761
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura -/ import tactic.doc_commands /-! # Basic logic properties This file is one of the earliest imports in mathlib. ## Implementation notes Theorems that require decidability hypotheses are in the namespace "decidable". Classical versions are in the namespace "classical". In the presence of automation, this whole file may be unnecessary. On the other hand, maybe it is useful for writing automation. -/ section miscellany /- We add the `inline` attribute to optimize VM computation using these declarations. For example, `if p ∧ q then ... else ...` will not evaluate the decidability of `q` if `p` is false. -/ attribute [inline] and.decidable or.decidable decidable.false xor.decidable iff.decidable decidable.true implies.decidable not.decidable ne.decidable bool.decidable_eq decidable.to_bool attribute [simp] cast_eq variables {α : Type*} {β : Type*} @[reducible] def hidden {α : Sort*} {a : α} := a def empty.elim {C : Sort*} : empty → C. instance : subsingleton empty := ⟨λa, a.elim⟩ instance subsingleton.prod {α β : Type*} [subsingleton α] [subsingleton β] : subsingleton (α × β) := ⟨by { intros a b, cases a, cases b, congr, }⟩ instance : decidable_eq empty := λa, a.elim instance sort.inhabited : inhabited (Sort*) := ⟨punit⟩ instance sort.inhabited' : inhabited (default (Sort*)) := ⟨punit.star⟩ instance psum.inhabited_left {α β} [inhabited α] : inhabited (psum α β) := ⟨psum.inl (default _)⟩ instance psum.inhabited_right {α β} [inhabited β] : inhabited (psum α β) := ⟨psum.inr (default _)⟩ @[priority 10] instance decidable_eq_of_subsingleton {α} [subsingleton α] : decidable_eq α | a b := is_true (subsingleton.elim a b) @[simp] lemma eq_iff_true_of_subsingleton [subsingleton α] (x y : α) : x = y ↔ true := by cc /-- Add an instance to "undo" coercion transitivity into a chain of coercions, because most simp lemmas are stated with respect to simple coercions and will not match when part of a chain. -/ @[simp] theorem coe_coe {α β γ} [has_coe α β] [has_coe_t β γ] (a : α) : (a : γ) = (a : β) := rfl theorem coe_fn_coe_trans {α β γ} [has_coe α β] [has_coe_t_aux β γ] [has_coe_to_fun γ] (x : α) : @coe_fn α _ x = @coe_fn β _ x := rfl @[simp] theorem coe_fn_coe_base {α β} [has_coe α β] [has_coe_to_fun β] (x : α) : @coe_fn α _ x = @coe_fn β _ x := rfl theorem coe_sort_coe_trans {α β γ} [has_coe α β] [has_coe_t_aux β γ] [has_coe_to_sort γ] (x : α) : @coe_sort α _ x = @coe_sort β _ x := rfl /-- Many structures such as bundled morphisms coerce to functions so that you can transparently apply them to arguments. For example, if `e : α ≃ β` and `a : α` then you can write `e a` and this is elaborated as `⇑e a`. This type of coercion is implemented using the `has_coe_to_fun`type class. There is one important consideration: If a type coerces to another type which in turn coerces to a function, then it **must** implement `has_coe_to_fun` directly: ```lean structure sparkling_equiv (α β) extends α ≃ β -- if we add a `has_coe` instance, instance {α β} : has_coe (sparkling_equiv α β) (α ≃ β) := ⟨sparkling_equiv.to_equiv⟩ -- then a `has_coe_to_fun` instance **must** be added as well: instance {α β} : has_coe_to_fun (sparkling_equiv α β) := ⟨λ _, α → β, λ f, f.to_equiv.to_fun⟩ ``` (Rationale: if we do not declare the direct coercion, then `⇑e a` is not in simp-normal form. The lemma `coe_fn_coe_base` will unfold it to `⇑↑e a`. This often causes loops in the simplifier.) -/ library_note "function coercion" @[simp] theorem coe_sort_coe_base {α β} [has_coe α β] [has_coe_to_sort β] (x : α) : @coe_sort α _ x = @coe_sort β _ x := rfl /-- `pempty` is the universe-polymorphic analogue of `empty`. -/ @[derive decidable_eq] inductive {u} pempty : Sort u def pempty.elim {C : Sort*} : pempty → C. instance subsingleton_pempty : subsingleton pempty := ⟨λa, a.elim⟩ @[simp] lemma not_nonempty_pempty : ¬ nonempty pempty := assume ⟨h⟩, h.elim @[simp] theorem forall_pempty {P : pempty → Prop} : (∀ x : pempty, P x) ↔ true := ⟨λ h, trivial, λ h x, by cases x⟩ @[simp] theorem exists_pempty {P : pempty → Prop} : (∃ x : pempty, P x) ↔ false := ⟨λ h, by { cases h with w, cases w }, false.elim⟩ lemma congr_arg_heq {α} {β : α → Sort*} (f : ∀ a, β a) : ∀ {a₁ a₂ : α}, a₁ = a₂ → f a₁ == f a₂ | a _ rfl := heq.rfl lemma plift.down_inj {α : Sort*} : ∀ (a b : plift α), a.down = b.down → a = b | ⟨a⟩ ⟨b⟩ rfl := rfl -- missing [symm] attribute for ne in core. attribute [symm] ne.symm lemma ne_comm {α} {a b : α} : a ≠ b ↔ b ≠ a := ⟨ne.symm, ne.symm⟩ @[simp] lemma eq_iff_eq_cancel_left {b c : α} : (∀ {a}, a = b ↔ a = c) ↔ (b = c) := ⟨λ h, by rw [← h], λ h a, by rw h⟩ @[simp] lemma eq_iff_eq_cancel_right {a b : α} : (∀ {c}, a = c ↔ b = c) ↔ (a = b) := ⟨λ h, by rw h, λ h a, by rw h⟩ /-- Wrapper for adding elementary propositions to the type class systems. Warning: this can easily be abused. See the rest of this docstring for details. Certain propositions should not be treated as a class globally, but sometimes it is very convenient to be able to use the type class system in specific circumstances. For example, `zmod p` is a field if and only if `p` is a prime number. In order to be able to find this field instance automatically by type class search, we have to turn `p.prime` into an instance implicit assumption. On the other hand, making `nat.prime` a class would require a major refactoring of the library, and it is questionable whether making `nat.prime` a class is desirable at all. The compromise is to add the assumption `[fact p.prime]` to `zmod.field`. In particular, this class is not intended for turning the type class system into an automated theorem prover for first order logic. -/ @[class] def fact (p : Prop) := p end miscellany /-! ### Declarations about propositional connectives -/ theorem false_ne_true : false ≠ true | h := h.symm ▸ trivial section propositional variables {a b c d : Prop} /-! ### Declarations about `implies` -/ theorem iff_of_eq (e : a = b) : a ↔ b := e ▸ iff.rfl theorem iff_iff_eq : (a ↔ b) ↔ a = b := ⟨propext, iff_of_eq⟩ @[simp] lemma eq_iff_iff {p q : Prop} : (p = q) ↔ (p ↔ q) := iff_iff_eq.symm @[simp] theorem imp_self : (a → a) ↔ true := iff_true_intro id theorem imp_intro {α β : Prop} (h : α) : β → α := λ _, h theorem imp_false : (a → false) ↔ ¬ a := iff.rfl theorem imp_and_distrib {α} : (α → b ∧ c) ↔ (α → b) ∧ (α → c) := ⟨λ h, ⟨λ ha, (h ha).left, λ ha, (h ha).right⟩, λ h ha, ⟨h.left ha, h.right ha⟩⟩ @[simp] theorem and_imp : (a ∧ b → c) ↔ (a → b → c) := iff.intro (λ h ha hb, h ⟨ha, hb⟩) (λ h ⟨ha, hb⟩, h ha hb) theorem iff_def : (a ↔ b) ↔ (a → b) ∧ (b → a) := iff_iff_implies_and_implies _ _ theorem iff_def' : (a ↔ b) ↔ (b → a) ∧ (a → b) := iff_def.trans and.comm theorem imp_true_iff {α : Sort*} : (α → true) ↔ true := iff_true_intro $ λ_, trivial @[simp] theorem imp_iff_right (ha : a) : (a → b) ↔ b := ⟨λf, f ha, imp_intro⟩ /-! ### Declarations about `not` -/ def not.elim {α : Sort*} (H1 : ¬a) (H2 : a) : α := absurd H2 H1 @[reducible] theorem not.imp {a b : Prop} (H2 : ¬b) (H1 : a → b) : ¬a := mt H1 H2 theorem not_not_of_not_imp : ¬(a → b) → ¬¬a := mt not.elim theorem not_of_not_imp {a : Prop} : ¬(a → b) → ¬b := mt imp_intro theorem dec_em (p : Prop) [decidable p] : p ∨ ¬p := decidable.em p theorem by_contradiction {p} [decidable p] : (¬p → false) → p := decidable.by_contradiction theorem not_not [decidable a] : ¬¬a ↔ a := iff.intro by_contradiction not_not_intro theorem of_not_not [decidable a] : ¬¬a → a := by_contradiction theorem of_not_imp [decidable a] (h : ¬ (a → b)) : a := by_contradiction (not_not_of_not_imp h) theorem not.imp_symm [decidable a] (h : ¬a → b) (hb : ¬b) : a := by_contradiction $ hb ∘ h theorem not_imp_comm [decidable a] [decidable b] : (¬a → b) ↔ (¬b → a) := ⟨not.imp_symm, not.imp_symm⟩ theorem imp.swap : (a → b → c) ↔ (b → a → c) := ⟨function.swap, function.swap⟩ theorem imp_not_comm : (a → ¬b) ↔ (b → ¬a) := imp.swap /-! ### Declarations about `and` -/ theorem not_and_of_not_left (b : Prop) : ¬a → ¬(a ∧ b) := mt and.left theorem not_and_of_not_right (a : Prop) {b : Prop} : ¬b → ¬(a ∧ b) := mt and.right theorem and.imp_left (h : a → b) : a ∧ c → b ∧ c := and.imp h id theorem and.imp_right (h : a → b) : c ∧ a → c ∧ b := and.imp id h lemma and.right_comm : (a ∧ b) ∧ c ↔ (a ∧ c) ∧ b := by simp [and.left_comm, and.comm] lemma and.rotate : a ∧ b ∧ c ↔ b ∧ c ∧ a := by simp [and.left_comm, and.comm] theorem and_not_self_iff (a : Prop) : a ∧ ¬ a ↔ false := iff.intro (assume h, (h.right) (h.left)) (assume h, h.elim) theorem not_and_self_iff (a : Prop) : ¬ a ∧ a ↔ false := iff.intro (assume ⟨hna, ha⟩, hna ha) false.elim theorem and_iff_left_of_imp {a b : Prop} (h : a → b) : (a ∧ b) ↔ a := iff.intro and.left (λ ha, ⟨ha, h ha⟩) theorem and_iff_right_of_imp {a b : Prop} (h : b → a) : (a ∧ b) ↔ b := iff.intro and.right (λ hb, ⟨h hb, hb⟩) lemma and.congr_right_iff : (a ∧ b ↔ a ∧ c) ↔ (a → (b ↔ c)) := ⟨λ h ha, by simp [ha] at h; exact h, and_congr_right⟩ @[simp] lemma and_self_left : a ∧ a ∧ b ↔ a ∧ b := ⟨λ h, ⟨h.1, h.2.2⟩, λ h, ⟨h.1, h.1, h.2⟩⟩ @[simp] lemma and_self_right : (a ∧ b) ∧ b ↔ a ∧ b := ⟨λ h, ⟨h.1.1, h.2⟩, λ h, ⟨⟨h.1, h.2⟩, h.2⟩⟩ /-! ### Declarations about `or` -/ theorem or_of_or_of_imp_of_imp (h₁ : a ∨ b) (h₂ : a → c) (h₃ : b → d) : c ∨ d := or.imp h₂ h₃ h₁ theorem or_of_or_of_imp_left (h₁ : a ∨ c) (h : a → b) : b ∨ c := or.imp_left h h₁ theorem or_of_or_of_imp_right (h₁ : c ∨ a) (h : a → b) : c ∨ b := or.imp_right h h₁ theorem or.elim3 (h : a ∨ b ∨ c) (ha : a → d) (hb : b → d) (hc : c → d) : d := or.elim h ha (assume h₂, or.elim h₂ hb hc) theorem or_imp_distrib : (a ∨ b → c) ↔ (a → c) ∧ (b → c) := ⟨assume h, ⟨assume ha, h (or.inl ha), assume hb, h (or.inr hb)⟩, assume ⟨ha, hb⟩, or.rec ha hb⟩ theorem or_iff_not_imp_left [decidable a] : a ∨ b ↔ (¬ a → b) := ⟨or.resolve_left, λ h, dite _ or.inl (or.inr ∘ h)⟩ theorem or_iff_not_imp_right [decidable b] : a ∨ b ↔ (¬ b → a) := or.comm.trans or_iff_not_imp_left theorem not_imp_not [decidable a] : (¬ a → ¬ b) ↔ (b → a) := ⟨assume h hb, by_contradiction $ assume na, h na hb, mt⟩ /-! ### Declarations about distributivity -/ theorem and_or_distrib_left : a ∧ (b ∨ c) ↔ (a ∧ b) ∨ (a ∧ c) := ⟨λ ⟨ha, hbc⟩, hbc.imp (and.intro ha) (and.intro ha), or.rec (and.imp_right or.inl) (and.imp_right or.inr)⟩ theorem or_and_distrib_right : (a ∨ b) ∧ c ↔ (a ∧ c) ∨ (b ∧ c) := (and.comm.trans and_or_distrib_left).trans (or_congr and.comm and.comm) theorem or_and_distrib_left : a ∨ (b ∧ c) ↔ (a ∨ b) ∧ (a ∨ c) := ⟨or.rec (λha, and.intro (or.inl ha) (or.inl ha)) (and.imp or.inr or.inr), and.rec $ or.rec (imp_intro ∘ or.inl) (or.imp_right ∘ and.intro)⟩ theorem and_or_distrib_right : (a ∧ b) ∨ c ↔ (a ∨ c) ∧ (b ∨ c) := (or.comm.trans or_and_distrib_left).trans (and_congr or.comm or.comm) @[simp] lemma or_self_left : a ∨ a ∨ b ↔ a ∨ b := ⟨λ h, h.elim or.inl id, λ h, h.elim or.inl (or.inr ∘ or.inr)⟩ @[simp] lemma or_self_right : (a ∨ b) ∨ b ↔ a ∨ b := ⟨λ h, h.elim id or.inr, λ h, h.elim (or.inl ∘ or.inl) or.inr⟩ /-! Declarations about `iff` -/ theorem iff_of_true (ha : a) (hb : b) : a ↔ b := ⟨λ_, hb, λ _, ha⟩ theorem iff_of_false (ha : ¬a) (hb : ¬b) : a ↔ b := ⟨ha.elim, hb.elim⟩ theorem iff_true_left (ha : a) : (a ↔ b) ↔ b := ⟨λ h, h.1 ha, iff_of_true ha⟩ theorem iff_true_right (ha : a) : (b ↔ a) ↔ b := iff.comm.trans (iff_true_left ha) theorem iff_false_left (ha : ¬a) : (a ↔ b) ↔ ¬b := ⟨λ h, mt h.2 ha, iff_of_false ha⟩ theorem iff_false_right (ha : ¬a) : (b ↔ a) ↔ ¬b := iff.comm.trans (iff_false_left ha) theorem not_or_of_imp [decidable a] (h : a → b) : ¬ a ∨ b := if ha : a then or.inr (h ha) else or.inl ha theorem imp_iff_not_or [decidable a] : (a → b) ↔ (¬ a ∨ b) := ⟨not_or_of_imp, or.neg_resolve_left⟩ theorem imp_or_distrib [decidable a] : (a → b ∨ c) ↔ (a → b) ∨ (a → c) := by simp [imp_iff_not_or, or.comm, or.left_comm] theorem imp_or_distrib' [decidable b] : (a → b ∨ c) ↔ (a → b) ∨ (a → c) := by by_cases b; simp [h, or_iff_right_of_imp ((∘) false.elim)] theorem not_imp_of_and_not : a ∧ ¬ b → ¬ (a → b) | ⟨ha, hb⟩ h := hb $ h ha theorem not_imp [decidable a] : ¬(a → b) ↔ a ∧ ¬b := ⟨λ h, ⟨of_not_imp h, not_of_not_imp h⟩, not_imp_of_and_not⟩ -- for monotonicity lemma imp_imp_imp (h₀ : c → a) (h₁ : b → d) : (a → b) → (c → d) := assume (h₂ : a → b), h₁ ∘ h₂ ∘ h₀ theorem peirce (a b : Prop) [decidable a] : ((a → b) → a) → a := if ha : a then λ h, ha else λ h, h ha.elim theorem peirce' {a : Prop} (H : ∀ b : Prop, (a → b) → a) : a := H _ id theorem not_iff_not [decidable a] [decidable b] : (¬ a ↔ ¬ b) ↔ (a ↔ b) := by rw [@iff_def (¬ a), @iff_def' a]; exact and_congr not_imp_not not_imp_not theorem not_iff_comm [decidable a] [decidable b] : (¬ a ↔ b) ↔ (¬ b ↔ a) := by rw [@iff_def (¬ a), @iff_def (¬ b)]; exact and_congr not_imp_comm imp_not_comm theorem not_iff [decidable b] : ¬ (a ↔ b) ↔ (¬ a ↔ b) := by split; intro h; [split, skip]; intro h'; [by_contradiction,intro,skip]; try { refine h _; simp [*] }; rw [h',not_iff_self] at h; exact h theorem iff_not_comm [decidable a] [decidable b] : (a ↔ ¬ b) ↔ (b ↔ ¬ a) := by rw [@iff_def a, @iff_def b]; exact and_congr imp_not_comm not_imp_comm theorem iff_iff_and_or_not_and_not [decidable b] : (a ↔ b) ↔ (a ∧ b) ∨ (¬ a ∧ ¬ b) := by { split; intro h, { rw h; by_cases b; [left,right]; split; assumption }, { cases h with h h; cases h; split; intro; { contradiction <|> assumption } } } theorem not_and_not_right [decidable b] : ¬(a ∧ ¬b) ↔ (a → b) := ⟨λ h ha, h.imp_symm $ and.intro ha, λ h ⟨ha, hb⟩, hb $ h ha⟩ @[inline] def decidable_of_iff (a : Prop) (h : a ↔ b) [D : decidable a] : decidable b := decidable_of_decidable_of_iff D h @[inline] def decidable_of_iff' (b : Prop) (h : a ↔ b) [D : decidable b] : decidable a := decidable_of_decidable_of_iff D h.symm def decidable_of_bool : ∀ (b : bool) (h : b ↔ a), decidable a | tt h := is_true (h.1 rfl) | ff h := is_false (mt h.2 bool.ff_ne_tt) /-! ### De Morgan's laws -/ theorem not_and_of_not_or_not (h : ¬ a ∨ ¬ b) : ¬ (a ∧ b) | ⟨ha, hb⟩ := or.elim h (absurd ha) (absurd hb) theorem not_and_distrib [decidable a] : ¬ (a ∧ b) ↔ ¬a ∨ ¬b := ⟨λ h, if ha : a then or.inr (λ hb, h ⟨ha, hb⟩) else or.inl ha, not_and_of_not_or_not⟩ theorem not_and_distrib' [decidable b] : ¬ (a ∧ b) ↔ ¬a ∨ ¬b := ⟨λ h, if hb : b then or.inl (λ ha, h ⟨ha, hb⟩) else or.inr hb, not_and_of_not_or_not⟩ @[simp] theorem not_and : ¬ (a ∧ b) ↔ (a → ¬ b) := and_imp theorem not_and' : ¬ (a ∧ b) ↔ b → ¬a := not_and.trans imp_not_comm theorem not_or_distrib : ¬ (a ∨ b) ↔ ¬ a ∧ ¬ b := ⟨λ h, ⟨λ ha, h (or.inl ha), λ hb, h (or.inr hb)⟩, λ ⟨h₁, h₂⟩ h, or.elim h h₁ h₂⟩ theorem or_iff_not_and_not [decidable a] [decidable b] : a ∨ b ↔ ¬ (¬a ∧ ¬b) := by rw [← not_or_distrib, not_not] theorem and_iff_not_or_not [decidable a] [decidable b] : a ∧ b ↔ ¬ (¬ a ∨ ¬ b) := by rw [← not_and_distrib, not_not] end propositional /-! ### Declarations about equality -/ section equality variables {α : Sort*} {a b : α} @[simp] theorem heq_iff_eq : a == b ↔ a = b := ⟨eq_of_heq, heq_of_eq⟩ theorem proof_irrel_heq {p q : Prop} (hp : p) (hq : q) : hp == hq := have p = q, from propext ⟨λ _, hq, λ _, hp⟩, by subst q; refl theorem ne_of_mem_of_not_mem {α β} [has_mem α β] {s : β} {a b : α} (h : a ∈ s) : b ∉ s → a ≠ b := mt $ λ e, e ▸ h theorem eq_equivalence : equivalence (@eq α) := ⟨eq.refl, @eq.symm _, @eq.trans _⟩ /-- Transport through trivial families is the identity. -/ @[simp] lemma eq_rec_constant {α : Sort*} {a a' : α} {β : Sort*} (y : β) (h : a = a') : (@eq.rec α a (λ a, β) y a' h) = y := by { cases h, refl, } @[simp] lemma eq_mp_rfl {α : Sort*} {a : α} : eq.mp (eq.refl α) a = a := rfl @[simp] lemma eq_mpr_rfl {α : Sort*} {a : α} : eq.mpr (eq.refl α) a = a := rfl lemma heq_of_eq_mp : ∀ {α β : Sort*} {a : α} {a' : β} (e : α = β) (h₂ : (eq.mp e a) = a'), a == a' | α ._ a a' rfl h := eq.rec_on h (heq.refl _) lemma rec_heq_of_heq {β} {C : α → Sort*} {x : C a} {y : β} (eq : a = b) (h : x == y) : @eq.rec α a C x b eq == y := by subst eq; exact h @[simp] lemma {u} eq_mpr_heq {α β : Sort u} (h : β = α) (x : α) : eq.mpr h x == x := by subst h; refl protected lemma eq.congr {x₁ x₂ y₁ y₂ : α} (h₁ : x₁ = y₁) (h₂ : x₂ = y₂) : (x₁ = x₂) ↔ (y₁ = y₂) := by { subst h₁, subst h₂ } lemma eq.congr_left {x y z : α} (h : x = y) : x = z ↔ y = z := by rw [h] lemma eq.congr_right {x y z : α} (h : x = y) : z = x ↔ z = y := by rw [h] lemma congr_arg2 {α β γ : Type*} (f : α → β → γ) {x x' : α} {y y' : β} (hx : x = x') (hy : y = y') : f x y = f x' y' := by { subst hx, subst hy } end equality /-! ### Declarations about quantifiers -/ section quantifiers variables {α : Sort*} {β : Sort*} {p q : α → Prop} {b : Prop} lemma forall_imp (h : ∀ a, p a → q a) : (∀ a, p a) → ∀ a, q a := λ h' a, h a (h' a) lemma Exists.imp (h : ∀ a, (p a → q a)) (p : ∃ a, p a) : ∃ a, q a := exists_imp_exists h p lemma exists_imp_exists' {p : α → Prop} {q : β → Prop} (f : α → β) (hpq : ∀ a, p a → q (f a)) (hp : ∃ a, p a) : ∃ b, q b := exists.elim hp (λ a hp', ⟨_, hpq _ hp'⟩) theorem forall_swap {p : α → β → Prop} : (∀ x y, p x y) ↔ ∀ y x, p x y := ⟨function.swap, function.swap⟩ theorem exists_swap {p : α → β → Prop} : (∃ x y, p x y) ↔ ∃ y x, p x y := ⟨λ ⟨x, y, h⟩, ⟨y, x, h⟩, λ ⟨y, x, h⟩, ⟨x, y, h⟩⟩ @[simp] theorem exists_imp_distrib : ((∃ x, p x) → b) ↔ ∀ x, p x → b := ⟨λ h x hpx, h ⟨x, hpx⟩, λ h ⟨x, hpx⟩, h x hpx⟩ /-- Extract an element from a existential statement, using `classical.some`. -/ -- This enables projection notation. @[reducible] noncomputable def Exists.some {p : α → Prop} (P : ∃ a, p a) : α := classical.some P /-- Show that an element extracted from `P : ∃ a, p a` using `P.some` satisfies `p`. -/ lemma Exists.some_spec {p : α → Prop} (P : ∃ a, p a) : p (P.some) := classical.some_spec P --theorem forall_not_of_not_exists (h : ¬ ∃ x, p x) : ∀ x, ¬ p x := --forall_imp_of_exists_imp h theorem not_exists_of_forall_not (h : ∀ x, ¬ p x) : ¬ ∃ x, p x := exists_imp_distrib.2 h @[simp] theorem not_exists : (¬ ∃ x, p x) ↔ ∀ x, ¬ p x := exists_imp_distrib theorem not_forall_of_exists_not : (∃ x, ¬ p x) → ¬ ∀ x, p x | ⟨x, hn⟩ h := hn (h x) theorem not_forall {p : α → Prop} [decidable (∃ x, ¬ p x)] [∀ x, decidable (p x)] : (¬ ∀ x, p x) ↔ ∃ x, ¬ p x := ⟨not.imp_symm $ λ nx x, nx.imp_symm $ λ h, ⟨x, h⟩, not_forall_of_exists_not⟩ theorem not_forall_not [decidable (∃ x, p x)] : (¬ ∀ x, ¬ p x) ↔ ∃ x, p x := (@not_iff_comm _ _ _ (decidable_of_iff (¬ ∃ x, p x) not_exists)).1 not_exists theorem not_exists_not [∀ x, decidable (p x)] : (¬ ∃ x, ¬ p x) ↔ ∀ x, p x := by simp [not_not] @[simp] theorem forall_true_iff : (α → true) ↔ true := iff_true_intro (λ _, trivial) -- Unfortunately this causes simp to loop sometimes, so we -- add the 2 and 3 cases as simp lemmas instead theorem forall_true_iff' (h : ∀ a, p a ↔ true) : (∀ a, p a) ↔ true := iff_true_intro (λ _, of_iff_true (h _)) @[simp] theorem forall_2_true_iff {β : α → Sort*} : (∀ a, β a → true) ↔ true := forall_true_iff' $ λ _, forall_true_iff @[simp] theorem forall_3_true_iff {β : α → Sort*} {γ : Π a, β a → Sort*} : (∀ a (b : β a), γ a b → true) ↔ true := forall_true_iff' $ λ _, forall_2_true_iff @[simp] theorem forall_const (α : Sort*) [i : nonempty α] : (α → b) ↔ b := ⟨i.elim, λ hb x, hb⟩ @[simp] theorem exists_const (α : Sort*) [i : nonempty α] : (∃ x : α, b) ↔ b := ⟨λ ⟨x, h⟩, h, i.elim exists.intro⟩ theorem forall_and_distrib : (∀ x, p x ∧ q x) ↔ (∀ x, p x) ∧ (∀ x, q x) := ⟨λ h, ⟨λ x, (h x).left, λ x, (h x).right⟩, λ ⟨h₁, h₂⟩ x, ⟨h₁ x, h₂ x⟩⟩ theorem exists_or_distrib : (∃ x, p x ∨ q x) ↔ (∃ x, p x) ∨ (∃ x, q x) := ⟨λ ⟨x, hpq⟩, hpq.elim (λ hpx, or.inl ⟨x, hpx⟩) (λ hqx, or.inr ⟨x, hqx⟩), λ hepq, hepq.elim (λ ⟨x, hpx⟩, ⟨x, or.inl hpx⟩) (λ ⟨x, hqx⟩, ⟨x, or.inr hqx⟩)⟩ @[simp] theorem exists_and_distrib_left {q : Prop} {p : α → Prop} : (∃x, q ∧ p x) ↔ q ∧ (∃x, p x) := ⟨λ ⟨x, hq, hp⟩, ⟨hq, x, hp⟩, λ ⟨hq, x, hp⟩, ⟨x, hq, hp⟩⟩ @[simp] theorem exists_and_distrib_right {q : Prop} {p : α → Prop} : (∃x, p x ∧ q) ↔ (∃x, p x) ∧ q := by simp [and_comm] @[simp] theorem forall_eq {a' : α} : (∀a, a = a' → p a) ↔ p a' := ⟨λ h, h a' rfl, λ h a e, e.symm ▸ h⟩ @[simp] theorem exists_eq {a' : α} : ∃ a, a = a' := ⟨_, rfl⟩ @[simp] theorem exists_eq' {a' : α} : Exists (eq a') := ⟨_, rfl⟩ @[simp] theorem exists_eq_left {a' : α} : (∃ a, a = a' ∧ p a) ↔ p a' := ⟨λ ⟨a, e, h⟩, e ▸ h, λ h, ⟨_, rfl, h⟩⟩ @[simp] theorem exists_eq_right {a' : α} : (∃ a, p a ∧ a = a') ↔ p a' := (exists_congr $ by exact λ a, and.comm).trans exists_eq_left @[simp] theorem exists_exists_and_eq_and {f : α → β} {p : α → Prop} {q : β → Prop} : (∃ b, (∃ a, p a ∧ f a = b) ∧ q b) ↔ ∃ a, p a ∧ q (f a) := ⟨λ ⟨b, ⟨a, ha, hab⟩, hb⟩, ⟨a, ha, hab.symm ▸ hb⟩, λ ⟨a, hp, hq⟩, ⟨f a, ⟨a, hp, rfl⟩, hq⟩⟩ @[simp] theorem exists_exists_eq_and {f : α → β} {p : β → Prop} : (∃ b, (∃ a, f a = b) ∧ p b) ↔ ∃ a, p (f a) := ⟨λ ⟨b, ⟨a, ha⟩, hb⟩, ⟨a, ha.symm ▸ hb⟩, λ ⟨a, ha⟩, ⟨f a, ⟨a, rfl⟩, ha⟩⟩ @[simp] theorem forall_eq' {a' : α} : (∀a, a' = a → p a) ↔ p a' := by simp [@eq_comm _ a'] @[simp] theorem exists_eq_left' {a' : α} : (∃ a, a' = a ∧ p a) ↔ p a' := by simp [@eq_comm _ a'] @[simp] theorem exists_eq_right' {a' : α} : (∃ a, p a ∧ a' = a) ↔ p a' := by simp [@eq_comm _ a'] theorem exists_comm {p : α → β → Prop} : (∃ a b, p a b) ↔ ∃ b a, p a b := ⟨λ ⟨a, b, h⟩, ⟨b, a, h⟩, λ ⟨b, a, h⟩, ⟨a, b, h⟩⟩ theorem forall_or_of_or_forall (h : b ∨ ∀x, p x) (x) : b ∨ p x := h.imp_right $ λ h₂, h₂ x theorem forall_or_distrib_left {q : Prop} {p : α → Prop} [decidable q] : (∀x, q ∨ p x) ↔ q ∨ (∀x, p x) := ⟨λ h, if hq : q then or.inl hq else or.inr $ λ x, (h x).resolve_left hq, forall_or_of_or_forall⟩ theorem forall_or_distrib_right {q : Prop} {p : α → Prop} [decidable q] : (∀x, p x ∨ q) ↔ (∀x, p x) ∨ q := by simp [or_comm, forall_or_distrib_left] /-- A predicate holds everywhere on the image of a surjective functions iff it holds everywhere. -/ theorem forall_iff_forall_surj {α β : Type*} {f : α → β} (h : function.surjective f) {P : β → Prop} : (∀ a, P (f a)) ↔ ∀ b, P b := ⟨λ ha b, by cases h b with a hab; rw ←hab; exact ha a, λ hb a, hb $ f a⟩ @[simp] theorem exists_prop {p q : Prop} : (∃ h : p, q) ↔ p ∧ q := ⟨λ ⟨h₁, h₂⟩, ⟨h₁, h₂⟩, λ ⟨h₁, h₂⟩, ⟨h₁, h₂⟩⟩ @[simp] theorem exists_false : ¬ (∃a:α, false) := assume ⟨a, h⟩, h theorem Exists.fst {p : b → Prop} : Exists p → b | ⟨h, _⟩ := h theorem Exists.snd {p : b → Prop} : ∀ h : Exists p, p h.fst | ⟨_, h⟩ := h @[simp] theorem forall_prop_of_true {p : Prop} {q : p → Prop} (h : p) : (∀ h' : p, q h') ↔ q h := @forall_const (q h) p ⟨h⟩ @[simp] theorem exists_prop_of_true {p : Prop} {q : p → Prop} (h : p) : (∃ h' : p, q h') ↔ q h := @exists_const (q h) p ⟨h⟩ @[simp] theorem forall_prop_of_false {p : Prop} {q : p → Prop} (hn : ¬ p) : (∀ h' : p, q h') ↔ true := iff_true_intro $ λ h, hn.elim h @[simp] theorem exists_prop_of_false {p : Prop} {q : p → Prop} : ¬ p → ¬ (∃ h' : p, q h') := mt Exists.fst lemma exists_unique.exists {α : Sort*} {p : α → Prop} (h : ∃! x, p x) : ∃ x, p x := exists.elim h (λ x hx, ⟨x, and.left hx⟩) lemma exists_unique.unique {α : Sort*} {p : α → Prop} (h : ∃! x, p x) {y₁ y₂ : α} (py₁ : p y₁) (py₂ : p y₂) : y₁ = y₂ := unique_of_exists_unique h py₁ py₂ @[simp] lemma exists_unique_iff_exists {α : Sort*} [subsingleton α] {p : α → Prop} : (∃! x, p x) ↔ ∃ x, p x := ⟨λ h, h.exists, Exists.imp $ λ x hx, ⟨hx, λ y _, subsingleton.elim y x⟩⟩ lemma exists_unique.elim2 {α : Sort*} {p : α → Sort*} [∀ x, subsingleton (p x)] {q : Π x (h : p x), Prop} {b : Prop} (h₂ : ∃! x (h : p x), q x h) (h₁ : ∀ x (h : p x), q x h → (∀ y (hy : p y), q y hy → y = x) → b) : b := begin simp only [exists_unique_iff_exists] at h₂, apply h₂.elim, exact λ x ⟨hxp, hxq⟩ H, h₁ x hxp hxq (λ y hyp hyq, H y ⟨hyp, hyq⟩) end lemma exists_unique.intro2 {α : Sort*} {p : α → Sort*} [∀ x, subsingleton (p x)] {q : Π (x : α) (h : p x), Prop} (w : α) (hp : p w) (hq : q w hp) (H : ∀ y (hy : p y), q y hy → y = w) : ∃! x (hx : p x), q x hx := begin simp only [exists_unique_iff_exists], exact exists_unique.intro w ⟨hp, hq⟩ (λ y ⟨hyp, hyq⟩, H y hyp hyq) end lemma exists_unique.exists2 {α : Sort*} {p : α → Sort*} {q : Π (x : α) (h : p x), Prop} (h : ∃! x (hx : p x), q x hx) : ∃ x (hx : p x), q x hx := h.exists.imp (λ x hx, hx.exists) lemma exists_unique.unique2 {α : Sort*} {p : α → Sort*} [∀ x, subsingleton (p x)] {q : Π (x : α) (hx : p x), Prop} (h : ∃! x (hx : p x), q x hx) {y₁ y₂ : α} (hpy₁ : p y₁) (hqy₁ : q y₁ hpy₁) (hpy₂ : p y₂) (hqy₂ : q y₂ hpy₂) : y₁ = y₂ := begin simp only [exists_unique_iff_exists] at h, exact h.unique ⟨hpy₁, hqy₁⟩ ⟨hpy₂, hqy₂⟩ end end quantifiers /-! ### Classical versions of earlier lemmas -/ namespace classical variables {α : Sort*} {p : α → Prop} local attribute [instance] prop_decidable @[simp] protected theorem not_forall : (¬ ∀ x, p x) ↔ (∃ x, ¬ p x) := not_forall @[simp] protected theorem not_exists_not : (¬ ∃ x, ¬ p x) ↔ ∀ x, p x := not_exists_not protected theorem forall_or_distrib_left {q : Prop} {p : α → Prop} : (∀x, q ∨ p x) ↔ q ∨ (∀x, p x) := forall_or_distrib_left protected theorem forall_or_distrib_right {q : Prop} {p : α → Prop} : (∀x, p x ∨ q) ↔ (∀x, p x) ∨ q := forall_or_distrib_right protected theorem forall_or_distrib {β} {p : α → Prop} {q : β → Prop} : (∀x y, p x ∨ q y) ↔ (∀ x, p x) ∨ (∀ y, q y) := by rw ← forall_or_distrib_right; simp [forall_or_distrib_left.symm] theorem cases {p : Prop → Prop} (h1 : p true) (h2 : p false) : ∀a, p a := assume a, cases_on a h1 h2 theorem or_not {p : Prop} : p ∨ ¬ p := by_cases or.inl or.inr protected theorem or_iff_not_imp_left {p q : Prop} : p ∨ q ↔ (¬ p → q) := or_iff_not_imp_left protected theorem or_iff_not_imp_right {p q : Prop} : q ∨ p ↔ (¬ p → q) := or_iff_not_imp_right @[simp] protected lemma not_not {p : Prop} : ¬¬p ↔ p := not_not @[simp] protected lemma not_imp {p q : Prop} : ¬(p → q) ↔ p ∧ ¬q := not_imp protected theorem not_imp_not {p q : Prop} : (¬ p → ¬ q) ↔ (q → p) := not_imp_not protected lemma not_and_distrib {p q : Prop}: ¬(p ∧ q) ↔ ¬p ∨ ¬q := not_and_distrib protected lemma imp_iff_not_or {a b : Prop} : a → b ↔ ¬a ∨ b := imp_iff_not_or lemma iff_iff_not_or_and_or_not {a b : Prop} : (a ↔ b) ↔ ((¬a ∨ b) ∧ (a ∨ ¬b)) := begin rw [iff_iff_implies_and_implies a b], simp only [imp_iff_not_or, or.comm] end /- use shortened names to avoid conflict when classical namespace is open. -/ noncomputable lemma dec (p : Prop) : decidable p := -- see Note [classical lemma] by apply_instance noncomputable lemma dec_pred (p : α → Prop) : decidable_pred p := -- see Note [classical lemma] by apply_instance noncomputable lemma dec_rel (p : α → α → Prop) : decidable_rel p := -- see Note [classical lemma] by apply_instance noncomputable lemma dec_eq (α : Sort*) : decidable_eq α := -- see Note [classical lemma] by apply_instance /-- We make decidability results that depends on `classical.choice` noncomputable lemmas. * We have to mark them as noncomputable, because otherwise Lean will try to generate bytecode for them, and fail because it depends on `classical.choice`. * We make them lemmas, and not definitions, because otherwise later definitions will raise \"failed to generate bytecode\" errors when writing something like `letI := classical.dec_eq _`. Cf. <https://leanprover-community.github.io/archive/113488general/08268noncomputabletheorem.html> -/ library_note "classical lemma" @[elab_as_eliminator] noncomputable def {u} exists_cases {C : Sort u} (H0 : C) (H : ∀ a, p a → C) : C := if h : ∃ a, p a then H (classical.some h) (classical.some_spec h) else H0 lemma some_spec2 {α : Sort*} {p : α → Prop} {h : ∃a, p a} (q : α → Prop) (hpq : ∀a, p a → q a) : q (some h) := hpq _ $ some_spec _ /-- A version of classical.indefinite_description which is definitionally equal to a pair -/ noncomputable def subtype_of_exists {α : Type*} {P : α → Prop} (h : ∃ x, P x) : {x // P x} := ⟨classical.some h, classical.some_spec h⟩ end classical @[elab_as_eliminator] noncomputable def {u} exists.classical_rec_on {α} {p : α → Prop} (h : ∃ a, p a) {C : Sort u} (H : ∀ a, p a → C) : C := H (classical.some h) (classical.some_spec h) /-! ### Declarations about bounded quantifiers -/ section bounded_quantifiers variables {α : Sort*} {r p q : α → Prop} {P Q : ∀ x, p x → Prop} {b : Prop} theorem bex_def : (∃ x (h : p x), q x) ↔ ∃ x, p x ∧ q x := ⟨λ ⟨x, px, qx⟩, ⟨x, px, qx⟩, λ ⟨x, px, qx⟩, ⟨x, px, qx⟩⟩ theorem bex.elim {b : Prop} : (∃ x h, P x h) → (∀ a h, P a h → b) → b | ⟨a, h₁, h₂⟩ h' := h' a h₁ h₂ theorem bex.intro (a : α) (h₁ : p a) (h₂ : P a h₁) : ∃ x (h : p x), P x h := ⟨a, h₁, h₂⟩ theorem ball_congr (H : ∀ x h, P x h ↔ Q x h) : (∀ x h, P x h) ↔ (∀ x h, Q x h) := forall_congr $ λ x, forall_congr (H x) theorem bex_congr (H : ∀ x h, P x h ↔ Q x h) : (∃ x h, P x h) ↔ (∃ x h, Q x h) := exists_congr $ λ x, exists_congr (H x) theorem ball.imp_right (H : ∀ x h, (P x h → Q x h)) (h₁ : ∀ x h, P x h) (x h) : Q x h := H _ _ $ h₁ _ _ theorem bex.imp_right (H : ∀ x h, (P x h → Q x h)) : (∃ x h, P x h) → ∃ x h, Q x h | ⟨x, h, h'⟩ := ⟨_, _, H _ _ h'⟩ theorem ball.imp_left (H : ∀ x, p x → q x) (h₁ : ∀ x, q x → r x) (x) (h : p x) : r x := h₁ _ $ H _ h theorem bex.imp_left (H : ∀ x, p x → q x) : (∃ x (_ : p x), r x) → ∃ x (_ : q x), r x | ⟨x, hp, hr⟩ := ⟨x, H _ hp, hr⟩ theorem ball_of_forall (h : ∀ x, p x) (x) : p x := h x theorem forall_of_ball (H : ∀ x, p x) (h : ∀ x, p x → q x) (x) : q x := h x $ H x theorem bex_of_exists (H : ∀ x, p x) : (∃ x, q x) → ∃ x (_ : p x), q x | ⟨x, hq⟩ := ⟨x, H x, hq⟩ theorem exists_of_bex : (∃ x (_ : p x), q x) → ∃ x, q x | ⟨x, _, hq⟩ := ⟨x, hq⟩ @[simp] theorem bex_imp_distrib : ((∃ x h, P x h) → b) ↔ (∀ x h, P x h → b) := by simp theorem not_bex : (¬ ∃ x h, P x h) ↔ ∀ x h, ¬ P x h := bex_imp_distrib theorem not_ball_of_bex_not : (∃ x h, ¬ P x h) → ¬ ∀ x h, P x h | ⟨x, h, hp⟩ al := hp $ al x h theorem not_ball [decidable (∃ x h, ¬ P x h)] [∀ x h, decidable (P x h)] : (¬ ∀ x h, P x h) ↔ (∃ x h, ¬ P x h) := ⟨not.imp_symm $ λ nx x h, nx.imp_symm $ λ h', ⟨x, h, h'⟩, not_ball_of_bex_not⟩ theorem ball_true_iff (p : α → Prop) : (∀ x, p x → true) ↔ true := iff_true_intro (λ h hrx, trivial) theorem ball_and_distrib : (∀ x h, P x h ∧ Q x h) ↔ (∀ x h, P x h) ∧ (∀ x h, Q x h) := iff.trans (forall_congr $ λ x, forall_and_distrib) forall_and_distrib theorem bex_or_distrib : (∃ x h, P x h ∨ Q x h) ↔ (∃ x h, P x h) ∨ (∃ x h, Q x h) := iff.trans (exists_congr $ λ x, exists_or_distrib) exists_or_distrib end bounded_quantifiers namespace classical local attribute [instance] prop_decidable theorem not_ball {α : Sort*} {p : α → Prop} {P : Π (x : α), p x → Prop} : (¬ ∀ x h, P x h) ↔ (∃ x h, ¬ P x h) := _root_.not_ball end classical lemma ite_eq_iff {α} {p : Prop} [decidable p] {a b c : α} : (if p then a else b) = c ↔ p ∧ a = c ∨ ¬p ∧ b = c := by by_cases p; simp * /-! ### Declarations about `nonempty` -/ section nonempty universe variables u v w variables {α : Type u} {β : Type v} {γ : α → Type w} attribute [simp] nonempty_of_inhabited @[priority 20] instance has_zero.nonempty [has_zero α] : nonempty α := ⟨0⟩ @[priority 20] instance has_one.nonempty [has_one α] : nonempty α := ⟨1⟩ lemma exists_true_iff_nonempty {α : Sort*} : (∃a:α, true) ↔ nonempty α := iff.intro (λ⟨a, _⟩, ⟨a⟩) (λ⟨a⟩, ⟨a, trivial⟩) @[simp] lemma nonempty_Prop {p : Prop} : nonempty p ↔ p := iff.intro (assume ⟨h⟩, h) (assume h, ⟨h⟩) lemma not_nonempty_iff_imp_false : ¬ nonempty α ↔ α → false := ⟨λ h a, h ⟨a⟩, λ h ⟨a⟩, h a⟩ @[simp] lemma nonempty_sigma : nonempty (Σa:α, γ a) ↔ (∃a:α, nonempty (γ a)) := iff.intro (assume ⟨⟨a, c⟩⟩, ⟨a, ⟨c⟩⟩) (assume ⟨a, ⟨c⟩⟩, ⟨⟨a, c⟩⟩) @[simp] lemma nonempty_subtype {α : Sort u} {p : α → Prop} : nonempty (subtype p) ↔ (∃a:α, p a) := iff.intro (assume ⟨⟨a, h⟩⟩, ⟨a, h⟩) (assume ⟨a, h⟩, ⟨⟨a, h⟩⟩) @[simp] lemma nonempty_prod : nonempty (α × β) ↔ (nonempty α ∧ nonempty β) := iff.intro (assume ⟨⟨a, b⟩⟩, ⟨⟨a⟩, ⟨b⟩⟩) (assume ⟨⟨a⟩, ⟨b⟩⟩, ⟨⟨a, b⟩⟩) @[simp] lemma nonempty_pprod {α : Sort u} {β : Sort v} : nonempty (pprod α β) ↔ (nonempty α ∧ nonempty β) := iff.intro (assume ⟨⟨a, b⟩⟩, ⟨⟨a⟩, ⟨b⟩⟩) (assume ⟨⟨a⟩, ⟨b⟩⟩, ⟨⟨a, b⟩⟩) @[simp] lemma nonempty_sum : nonempty (α ⊕ β) ↔ (nonempty α ∨ nonempty β) := iff.intro (assume ⟨h⟩, match h with sum.inl a := or.inl ⟨a⟩ | sum.inr b := or.inr ⟨b⟩ end) (assume h, match h with or.inl ⟨a⟩ := ⟨sum.inl a⟩ | or.inr ⟨b⟩ := ⟨sum.inr b⟩ end) @[simp] lemma nonempty_psum {α : Sort u} {β : Sort v} : nonempty (psum α β) ↔ (nonempty α ∨ nonempty β) := iff.intro (assume ⟨h⟩, match h with psum.inl a := or.inl ⟨a⟩ | psum.inr b := or.inr ⟨b⟩ end) (assume h, match h with or.inl ⟨a⟩ := ⟨psum.inl a⟩ | or.inr ⟨b⟩ := ⟨psum.inr b⟩ end) @[simp] lemma nonempty_psigma {α : Sort u} {β : α → Sort v} : nonempty (psigma β) ↔ (∃a:α, nonempty (β a)) := iff.intro (assume ⟨⟨a, c⟩⟩, ⟨a, ⟨c⟩⟩) (assume ⟨a, ⟨c⟩⟩, ⟨⟨a, c⟩⟩) @[simp] lemma nonempty_empty : ¬ nonempty empty := assume ⟨h⟩, h.elim @[simp] lemma nonempty_ulift : nonempty (ulift α) ↔ nonempty α := iff.intro (assume ⟨⟨a⟩⟩, ⟨a⟩) (assume ⟨a⟩, ⟨⟨a⟩⟩) @[simp] lemma nonempty_plift {α : Sort u} : nonempty (plift α) ↔ nonempty α := iff.intro (assume ⟨⟨a⟩⟩, ⟨a⟩) (assume ⟨a⟩, ⟨⟨a⟩⟩) @[simp] lemma nonempty.forall {α : Sort u} {p : nonempty α → Prop} : (∀h:nonempty α, p h) ↔ (∀a, p ⟨a⟩) := iff.intro (assume h a, h _) (assume h ⟨a⟩, h _) @[simp] lemma nonempty.exists {α : Sort u} {p : nonempty α → Prop} : (∃h:nonempty α, p h) ↔ (∃a, p ⟨a⟩) := iff.intro (assume ⟨⟨a⟩, h⟩, ⟨a, h⟩) (assume ⟨a, h⟩, ⟨⟨a⟩, h⟩) lemma classical.nonempty_pi {α : Sort u} {β : α → Sort v} : nonempty (Πa:α, β a) ↔ (∀a:α, nonempty (β a)) := iff.intro (assume ⟨f⟩ a, ⟨f a⟩) (assume f, ⟨assume a, classical.choice $ f a⟩) /-- Using `classical.choice`, lifts a (`Prop`-valued) `nonempty` instance to a (`Type`-valued) `inhabited` instance. `classical.inhabited_of_nonempty` already exists, in `core/init/classical.lean`, but the assumption is not a type class argument, which makes it unsuitable for some applications. -/ noncomputable def classical.inhabited_of_nonempty' {α : Sort u} [h : nonempty α] : inhabited α := ⟨classical.choice h⟩ /-- Using `classical.choice`, extracts a term from a `nonempty` type. -/ @[reducible] protected noncomputable def nonempty.some {α : Sort u} (h : nonempty α) : α := classical.choice h /-- Using `classical.choice`, extracts a term from a `nonempty` type. -/ @[reducible] protected noncomputable def classical.arbitrary (α : Sort u) [h : nonempty α] : α := classical.choice h /-- Given `f : α → β`, if `α` is nonempty then `β` is also nonempty. `nonempty` cannot be a `functor`, because `functor` is restricted to `Type`. -/ lemma nonempty.map {α : Sort u} {β : Sort v} (f : α → β) : nonempty α → nonempty β | ⟨h⟩ := ⟨f h⟩ protected lemma nonempty.map2 {α β γ : Sort*} (f : α → β → γ) : nonempty α → nonempty β → nonempty γ | ⟨x⟩ ⟨y⟩ := ⟨f x y⟩ protected lemma nonempty.congr {α : Sort u} {β : Sort v} (f : α → β) (g : β → α) : nonempty α ↔ nonempty β := ⟨nonempty.map f, nonempty.map g⟩ lemma nonempty.elim_to_inhabited {α : Sort*} [h : nonempty α] {p : Prop} (f : inhabited α → p) : p := h.elim $ f ∘ inhabited.mk instance {α β} [h : nonempty α] [h2 : nonempty β] : nonempty (α × β) := h.elim $ λ g, h2.elim $ λ g2, ⟨⟨g, g2⟩⟩ end nonempty section ite lemma apply_dite {α β : Type*} (f : α → β) (P : Prop) [decidable P] (x : P → α) (y : ¬P → α) : f (dite P x y) = dite P (λ h, f (x h)) (λ h, f (y h)) := by { by_cases h : P; simp [h], } lemma apply_ite {α β : Type*} (f : α → β) (P : Prop) [decidable P] (x y : α) : f (ite P x y) = ite P (f x) (f y) := apply_dite f P (λ _, x) (λ _, y) lemma dite_apply {α : Type*} {β : α → Type*} (P : Prop) [decidable P] (f : P → Π a, β a) (g : ¬ P → Π a, β a) (x : α) : (dite P f g) x = dite P (λ h, f h x) (λ h, g h x) := by { by_cases h : P; simp [h], } lemma ite_apply {α : Type*} {β : α → Type*} (P : Prop) [decidable P] (f g : Π a, β a) (x : α) : (ite P f g) x = ite P (f x) (g x) := dite_apply P (λ _, f) (λ _, g) x end ite
569f78211f754f8226e0519fe48e81ac3da13440
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/category_theory/concrete_category.lean
569ec5d0d07f0c12d9fabe78dd52dbd9db77d243
[ "Apache-2.0" ]
permissive
fpvandoorn/mathlib
b21ab4068db079cbb8590b58fda9cc4bc1f35df4
b3433a51ea8bc07c4159c1073838fc0ee9b8f227
refs/heads/master
1,624,791,089,608
1,556,715,231,000
1,556,715,231,000
165,722,980
5
0
Apache-2.0
1,552,657,455,000
1,547,494,646,000
Lean
UTF-8
Lean
false
false
3,315
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Johannes Hölzl, Reid Barton, Sean Leather Bundled type and structure. -/ import category_theory.functor import category_theory.types universes u v namespace category_theory variables {c d : Sort u → Sort v} {α : Sort u} /-- `concrete_category @hom` collects the evidence that a type constructor `c` and a morphism predicate `hom` can be thought of as a concrete category. In a typical example, `c` is the type class `topological_space` and `hom` is `continuous`. -/ structure concrete_category (hom : out_param $ ∀ {α β}, c α → c β → (α → β) → Prop) := (hom_id : ∀ {α} (ia : c α), hom ia ia id) (hom_comp : ∀ {α β γ} (ia : c α) (ib : c β) (ic : c γ) {f g}, hom ia ib f → hom ib ic g → hom ia ic (g ∘ f)) attribute [class] concrete_category /-- `bundled` is a type bundled with a type class instance for that type. Only the type class is exposed as a parameter. -/ structure bundled (c : Sort u → Sort v) : Sort (max (u+1) v) := (α : Sort u) (str : c α) def mk_ob {c : Sort u → Sort v} (α : Sort u) [str : c α] : bundled c := ⟨α, str⟩ namespace bundled instance : has_coe_to_sort (bundled c) := { S := Sort u, coe := bundled.α } /-- Map over the bundled structure -/ def map (f : ∀ {α}, c α → d α) (b : bundled c) : bundled d := ⟨b.α, f b.str⟩ section concrete_category variables (hom : ∀ {α β : Sort u}, c α → c β → (α → β) → Prop) variables [h : concrete_category @hom] include h instance : category (bundled c) := { hom := λ a b, subtype (hom a.2 b.2), id := λ a, ⟨@id a.1, h.hom_id a.2⟩, comp := λ a b c f g, ⟨g.1 ∘ f.1, h.hom_comp a.2 b.2 c.2 f.2 g.2⟩ } variables {X Y Z : bundled c} @[simp] lemma concrete_category_id (X : bundled c) : subtype.val (𝟙 X) = id := rfl @[simp] lemma concrete_category_comp (f : X ⟶ Y) (g : Y ⟶ Z) : subtype.val (f ≫ g) = g.val ∘ f.val := rfl instance : has_coe_to_fun (X ⟶ Y) := { F := λ f, X → Y, coe := λ f, f.1 } @[simp] lemma coe_id {X : bundled c} : ((𝟙 X) : X → X) = id := rfl @[simp] lemma bundled_hom_coe {X Y : bundled c} (val : X → Y) (prop) (x : X) : (⟨val, prop⟩ : X ⟶ Y) x = val x := rfl end concrete_category end bundled def concrete_functor {C : Sort u → Sort v} {hC : ∀{α β}, C α → C β → (α → β) → Prop} [concrete_category @hC] {D : Sort u → Sort v} {hD : ∀{α β}, D α → D β → (α → β) → Prop} [concrete_category @hD] (m : ∀{α}, C α → D α) (h : ∀{α β} {ia : C α} {ib : C β} {f}, hC ia ib f → hD (m ia) (m ib) f) : bundled C ⥤ bundled D := { obj := bundled.map @m, map := λ X Y f, ⟨ f, h f.2 ⟩ } section forget variables {C : Sort u → Sort v} {hom : ∀α β, C α → C β → (α → β) → Prop} [i : concrete_category hom] include i /-- The forgetful functor from a bundled category to `Sort`. -/ def forget : bundled C ⥤ Sort u := { obj := bundled.α, map := λ a b h, h.1 } instance forget.faithful : faithful (forget : bundled C ⥤ Sort u) := { injectivity' := begin rintros X Y ⟨f,_⟩ ⟨g,_⟩ p, congr, exact p, end } end forget end category_theory
00073e331d9f0c4dd8a549703687b06062391a05
9dc8cecdf3c4634764a18254e94d43da07142918
/src/ring_theory/subsemiring/basic.lean
41640480f0cf6fcf25c732ce25ac74575ae94e6b
[ "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
44,899
lean
/- Copyright (c) 2020 Yury Kudryashov All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import algebra.module.basic import algebra.ring.equiv import algebra.ring.prod import data.set.finite import group_theory.submonoid.centralizer import group_theory.submonoid.membership /-! # Bundled subsemirings We define bundled subsemirings and some standard constructions: `complete_lattice` structure, `subtype` and `inclusion` ring homomorphisms, subsemiring `map`, `comap` and range (`srange`) of a `ring_hom` etc. -/ open_locale big_operators universes u v w section add_submonoid_with_one_class /-- `add_submonoid_with_one_class S R` says `S` is a type of subsets `s ≤ R` that contain `0`, `1`, and are closed under `(+)` -/ class add_submonoid_with_one_class (S : Type*) (R : out_param $ Type*) [add_monoid_with_one R] [set_like S R] extends add_submonoid_class S R, one_mem_class S R variables {S R : Type*} [add_monoid_with_one R] [set_like S R] (s : S) lemma nat_cast_mem [add_submonoid_with_one_class S R] (n : ℕ) : (n : R) ∈ s := by induction n; simp [zero_mem, add_mem, one_mem, *] @[priority 74] instance add_submonoid_with_one_class.to_add_monoid_with_one [add_submonoid_with_one_class S R] : add_monoid_with_one s := { one := ⟨_, one_mem s⟩, nat_cast := λ n, ⟨n, nat_cast_mem s n⟩, nat_cast_zero := subtype.ext nat.cast_zero, nat_cast_succ := λ n, subtype.ext (nat.cast_succ _), .. add_submonoid_class.to_add_monoid s } end add_submonoid_with_one_class variables {R : Type u} {S : Type v} {T : Type w} [non_assoc_semiring R] (M : submonoid R) section subsemiring_class /-- `subsemiring_class S R` states that `S` is a type of subsets `s ⊆ R` that are both a multiplicative and an additive submonoid. -/ class subsemiring_class (S : Type*) (R : out_param $ Type u) [non_assoc_semiring R] [set_like S R] extends submonoid_class S R := (add_mem : ∀ {s : S} {a b : R}, a ∈ s → b ∈ s → a + b ∈ s) (zero_mem : ∀ (s : S), (0 : R) ∈ s) @[priority 100] -- See note [lower instance priority] instance subsemiring_class.add_submonoid_with_one_class (S : Type*) (R : out_param $ Type u) [non_assoc_semiring R] [set_like S R] [h : subsemiring_class S R] : add_submonoid_with_one_class S R := { .. h } variables [set_like S R] [hSR : subsemiring_class S R] (s : S) include hSR lemma coe_nat_mem (n : ℕ) : (n : R) ∈ s := by { rw ← nsmul_one, exact nsmul_mem (one_mem _) _ } namespace subsemiring_class /-- A subsemiring of a `non_assoc_semiring` inherits a `non_assoc_semiring` structure -/ @[priority 75] -- Prefer subclasses of `non_assoc_semiring` over subclasses of `subsemiring_class`. instance to_non_assoc_semiring : non_assoc_semiring s := subtype.coe_injective.non_assoc_semiring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) instance nontrivial [nontrivial R] : nontrivial s := nontrivial_of_ne 0 1 $ λ H, zero_ne_one (congr_arg subtype.val H) instance no_zero_divisors [no_zero_divisors R] : no_zero_divisors s := { eq_zero_or_eq_zero_of_mul_eq_zero := λ x y h, or.cases_on (eq_zero_or_eq_zero_of_mul_eq_zero $ subtype.ext_iff.mp h) (λ h, or.inl $ subtype.eq h) (λ h, or.inr $ subtype.eq h) } /-- The natural ring hom from a subsemiring of semiring `R` to `R`. -/ def subtype : s →+* R := { to_fun := coe, .. submonoid_class.subtype s, .. add_submonoid_class.subtype s } @[simp] theorem coe_subtype : (subtype s : s → R) = coe := rfl omit hSR /-- A subsemiring of a `semiring` is a `semiring`. -/ @[priority 75] -- Prefer subclasses of `semiring` over subclasses of `subsemiring_class`. instance to_semiring {R} [semiring R] [set_like S R] [subsemiring_class S R] : semiring s := subtype.coe_injective.semiring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) @[simp, norm_cast] lemma coe_pow {R} [semiring R] [set_like S R] [subsemiring_class S R] (x : s) (n : ℕ) : ((x^n : s) : R) = (x^n : R) := begin induction n with n ih, { simp, }, { simp [pow_succ, ih], }, end /-- A subsemiring of a `comm_semiring` is a `comm_semiring`. -/ instance to_comm_semiring {R} [comm_semiring R] [set_like S R] [subsemiring_class S R] : comm_semiring s := subtype.coe_injective.comm_semiring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) /-- A subsemiring of an `ordered_semiring` is an `ordered_semiring`. -/ instance to_ordered_semiring {R} [ordered_semiring R] [set_like S R] [subsemiring_class S R] : ordered_semiring s := subtype.coe_injective.ordered_semiring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) /-- A subsemiring of an `ordered_comm_semiring` is an `ordered_comm_semiring`. -/ instance to_ordered_comm_semiring {R} [ordered_comm_semiring R] [set_like S R] [subsemiring_class S R] : ordered_comm_semiring s := subtype.coe_injective.ordered_comm_semiring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) /-- A subsemiring of a `linear_ordered_semiring` is a `linear_ordered_semiring`. -/ instance to_linear_ordered_semiring {R} [linear_ordered_semiring R] [set_like S R] [subsemiring_class S R] : linear_ordered_semiring s := subtype.coe_injective.linear_ordered_semiring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) /-- A subsemiring of a `linear_ordered_comm_semiring` is a `linear_ordered_comm_semiring`. -/ instance to_linear_ordered_comm_semiring {R} [linear_ordered_comm_semiring R] [set_like S R] [subsemiring_class S R] : linear_ordered_comm_semiring s := subtype.coe_injective.linear_ordered_comm_semiring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) end subsemiring_class end subsemiring_class variables [non_assoc_semiring S] [non_assoc_semiring T] set_option old_structure_cmd true /-- A subsemiring of a semiring `R` is a subset `s` that is both a multiplicative and an additive submonoid. -/ structure subsemiring (R : Type u) [non_assoc_semiring R] extends submonoid R, add_submonoid R /-- Reinterpret a `subsemiring` as a `submonoid`. -/ add_decl_doc subsemiring.to_submonoid /-- Reinterpret a `subsemiring` as an `add_submonoid`. -/ add_decl_doc subsemiring.to_add_submonoid namespace subsemiring instance : set_like (subsemiring R) R := { coe := subsemiring.carrier, coe_injective' := λ p q h, by cases p; cases q; congr' } instance : subsemiring_class (subsemiring R) R := { zero_mem := zero_mem', add_mem := add_mem', one_mem := one_mem', mul_mem := mul_mem' } @[simp] lemma mem_carrier {s : subsemiring R} {x : R} : x ∈ s.carrier ↔ x ∈ s := iff.rfl /-- Two subsemirings are equal if they have the same elements. -/ @[ext] theorem ext {S T : subsemiring R} (h : ∀ x, x ∈ S ↔ x ∈ T) : S = T := set_like.ext h /-- Copy of a subsemiring with a new `carrier` equal to the old one. Useful to fix definitional equalities.-/ protected def copy (S : subsemiring R) (s : set R) (hs : s = ↑S) : subsemiring R := { carrier := s, ..S.to_add_submonoid.copy s hs, ..S.to_submonoid.copy s hs } @[simp] lemma coe_copy (S : subsemiring R) (s : set R) (hs : s = ↑S) : (S.copy s hs : set R) = s := rfl lemma copy_eq (S : subsemiring R) (s : set R) (hs : s = ↑S) : S.copy s hs = S := set_like.coe_injective hs lemma to_submonoid_injective : function.injective (to_submonoid : subsemiring R → submonoid R) | r s h := ext (set_like.ext_iff.mp h : _) @[mono] lemma to_submonoid_strict_mono : strict_mono (to_submonoid : subsemiring R → submonoid R) := λ _ _, id @[mono] lemma to_submonoid_mono : monotone (to_submonoid : subsemiring R → submonoid R) := to_submonoid_strict_mono.monotone lemma to_add_submonoid_injective : function.injective (to_add_submonoid : subsemiring R → add_submonoid R) | r s h := ext (set_like.ext_iff.mp h : _) @[mono] lemma to_add_submonoid_strict_mono : strict_mono (to_add_submonoid : subsemiring R → add_submonoid R) := λ _ _, id @[mono] lemma to_add_submonoid_mono : monotone (to_add_submonoid : subsemiring R → add_submonoid R) := to_add_submonoid_strict_mono.monotone /-- Construct a `subsemiring R` from a set `s`, a submonoid `sm`, and an additive submonoid `sa` such that `x ∈ s ↔ x ∈ sm ↔ x ∈ sa`. -/ protected def mk' (s : set R) (sm : submonoid R) (hm : ↑sm = s) (sa : add_submonoid R) (ha : ↑sa = s) : subsemiring R := { carrier := s, zero_mem' := ha ▸ sa.zero_mem, one_mem' := hm ▸ sm.one_mem, add_mem' := λ x y, by simpa only [← ha] using sa.add_mem, mul_mem' := λ x y, by simpa only [← hm] using sm.mul_mem } @[simp] lemma coe_mk' {s : set R} {sm : submonoid R} (hm : ↑sm = s) {sa : add_submonoid R} (ha : ↑sa = s) : (subsemiring.mk' s sm hm sa ha : set R) = s := rfl @[simp] lemma mem_mk' {s : set R} {sm : submonoid R} (hm : ↑sm = s) {sa : add_submonoid R} (ha : ↑sa = s) {x : R} : x ∈ subsemiring.mk' s sm hm sa ha ↔ x ∈ s := iff.rfl @[simp] lemma mk'_to_submonoid {s : set R} {sm : submonoid R} (hm : ↑sm = s) {sa : add_submonoid R} (ha : ↑sa = s) : (subsemiring.mk' s sm hm sa ha).to_submonoid = sm := set_like.coe_injective hm.symm @[simp] lemma mk'_to_add_submonoid {s : set R} {sm : submonoid R} (hm : ↑sm = s) {sa : add_submonoid R} (ha : ↑sa =s) : (subsemiring.mk' s sm hm sa ha).to_add_submonoid = sa := set_like.coe_injective ha.symm end subsemiring namespace subsemiring variables (s : subsemiring R) /-- A subsemiring contains the semiring's 1. -/ protected theorem one_mem : (1 : R) ∈ s := one_mem s /-- A subsemiring contains the semiring's 0. -/ protected theorem zero_mem : (0 : R) ∈ s := zero_mem s /-- A subsemiring is closed under multiplication. -/ protected theorem mul_mem {x y : R} : x ∈ s → y ∈ s → x * y ∈ s := mul_mem /-- A subsemiring is closed under addition. -/ protected theorem add_mem {x y : R} : x ∈ s → y ∈ s → x + y ∈ s := add_mem /-- Product of a list of elements in a `subsemiring` is in the `subsemiring`. -/ lemma list_prod_mem {R : Type*} [semiring R] (s : subsemiring R) {l : list R} : (∀x ∈ l, x ∈ s) → l.prod ∈ s := list_prod_mem /-- Sum of a list of elements in a `subsemiring` is in the `subsemiring`. -/ protected lemma list_sum_mem {l : list R} : (∀x ∈ l, x ∈ s) → l.sum ∈ s := list_sum_mem /-- Product of a multiset of elements in a `subsemiring` of a `comm_semiring` is in the `subsemiring`. -/ protected lemma multiset_prod_mem {R} [comm_semiring R] (s : subsemiring R) (m : multiset R) : (∀a ∈ m, a ∈ s) → m.prod ∈ s := multiset_prod_mem m /-- Sum of a multiset of elements in a `subsemiring` of a `semiring` is in the `add_subsemiring`. -/ protected lemma multiset_sum_mem (m : multiset R) : (∀a ∈ m, a ∈ s) → m.sum ∈ s := multiset_sum_mem m /-- Product of elements of a subsemiring of a `comm_semiring` indexed by a `finset` is in the subsemiring. -/ protected lemma prod_mem {R : Type*} [comm_semiring R] (s : subsemiring R) {ι : Type*} {t : finset ι} {f : ι → R} (h : ∀c ∈ t, f c ∈ s) : ∏ i in t, f i ∈ s := prod_mem h /-- Sum of elements in an `subsemiring` of an `semiring` indexed by a `finset` is in the `add_subsemiring`. -/ protected lemma sum_mem (s : subsemiring R) {ι : Type*} {t : finset ι} {f : ι → R} (h : ∀c ∈ t, f c ∈ s) : ∑ i in t, f i ∈ s := sum_mem h /-- A subsemiring of a `non_assoc_semiring` inherits a `non_assoc_semiring` structure -/ instance to_non_assoc_semiring : non_assoc_semiring s := { mul_zero := λ x, subtype.eq $ mul_zero x, zero_mul := λ x, subtype.eq $ zero_mul x, right_distrib := λ x y z, subtype.eq $ right_distrib x y z, left_distrib := λ x y z, subtype.eq $ left_distrib x y z, nat_cast := λ n, ⟨n, coe_nat_mem s n⟩, nat_cast_zero := by simp [nat.cast]; refl, nat_cast_succ := λ _, by simp [nat.cast]; refl, .. s.to_submonoid.to_mul_one_class, .. s.to_add_submonoid.to_add_comm_monoid } @[simp, norm_cast] lemma coe_one : ((1 : s) : R) = (1 : R) := rfl @[simp, norm_cast] lemma coe_zero : ((0 : s) : R) = (0 : R) := rfl @[simp, norm_cast] lemma coe_add (x y : s) : ((x + y : s) : R) = (x + y : R) := rfl @[simp, norm_cast] lemma coe_mul (x y : s) : ((x * y : s) : R) = (x * y : R) := rfl instance nontrivial [nontrivial R] : nontrivial s := nontrivial_of_ne 0 1 $ λ H, zero_ne_one (congr_arg subtype.val H) protected lemma pow_mem {R : Type*} [semiring R] (s : subsemiring R) {x : R} (hx : x ∈ s) (n : ℕ) : x^n ∈ s := pow_mem hx n instance no_zero_divisors [no_zero_divisors R] : no_zero_divisors s := { eq_zero_or_eq_zero_of_mul_eq_zero := λ x y h, or.cases_on (eq_zero_or_eq_zero_of_mul_eq_zero $ subtype.ext_iff.mp h) (λ h, or.inl $ subtype.eq h) (λ h, or.inr $ subtype.eq h) } /-- A subsemiring of a `semiring` is a `semiring`. -/ instance to_semiring {R} [semiring R] (s : subsemiring R) : semiring s := { ..s.to_non_assoc_semiring, ..s.to_submonoid.to_monoid } @[simp, norm_cast] lemma coe_pow {R} [semiring R] (s : subsemiring R) (x : s) (n : ℕ) : ((x^n : s) : R) = (x^n : R) := begin induction n with n ih, { simp, }, { simp [pow_succ, ih], }, end /-- A subsemiring of a `comm_semiring` is a `comm_semiring`. -/ instance to_comm_semiring {R} [comm_semiring R] (s : subsemiring R) : comm_semiring s := { mul_comm := λ _ _, subtype.eq $ mul_comm _ _, ..s.to_semiring} /-- The natural ring hom from a subsemiring of semiring `R` to `R`. -/ def subtype : s →+* R := { to_fun := coe, .. s.to_submonoid.subtype, .. s.to_add_submonoid.subtype } @[simp] theorem coe_subtype : ⇑s.subtype = coe := rfl /-- A subsemiring of an `ordered_semiring` is an `ordered_semiring`. -/ instance to_ordered_semiring {R} [ordered_semiring R] (s : subsemiring R) : ordered_semiring s := subtype.coe_injective.ordered_semiring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) /-- A subsemiring of an `ordered_comm_semiring` is an `ordered_comm_semiring`. -/ instance to_ordered_comm_semiring {R} [ordered_comm_semiring R] (s : subsemiring R) : ordered_comm_semiring s := subtype.coe_injective.ordered_comm_semiring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) /-- A subsemiring of a `linear_ordered_semiring` is a `linear_ordered_semiring`. -/ instance to_linear_ordered_semiring {R} [linear_ordered_semiring R] (s : subsemiring R) : linear_ordered_semiring s := subtype.coe_injective.linear_ordered_semiring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) /-- A subsemiring of a `linear_ordered_comm_semiring` is a `linear_ordered_comm_semiring`. -/ instance to_linear_ordered_comm_semiring {R} [linear_ordered_comm_semiring R] (s : subsemiring R) : linear_ordered_comm_semiring s := subtype.coe_injective.linear_ordered_comm_semiring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) protected lemma nsmul_mem {x : R} (hx : x ∈ s) (n : ℕ) : n • x ∈ s := nsmul_mem hx n @[simp] lemma mem_to_submonoid {s : subsemiring R} {x : R} : x ∈ s.to_submonoid ↔ x ∈ s := iff.rfl @[simp] lemma coe_to_submonoid (s : subsemiring R) : (s.to_submonoid : set R) = s := rfl @[simp] lemma mem_to_add_submonoid {s : subsemiring R} {x : R} : x ∈ s.to_add_submonoid ↔ x ∈ s := iff.rfl @[simp] lemma coe_to_add_submonoid (s : subsemiring R) : (s.to_add_submonoid : set R) = s := rfl /-- The subsemiring `R` of the semiring `R`. -/ instance : has_top (subsemiring R) := ⟨{ .. (⊤ : submonoid R), .. (⊤ : add_submonoid R) }⟩ @[simp] lemma mem_top (x : R) : x ∈ (⊤ : subsemiring R) := set.mem_univ x @[simp] lemma coe_top : ((⊤ : subsemiring R) : set R) = set.univ := rfl /-- The preimage of a subsemiring along a ring homomorphism is a subsemiring. -/ def comap (f : R →+* S) (s : subsemiring S) : subsemiring R := { carrier := f ⁻¹' s, .. s.to_submonoid.comap (f : R →* S), .. s.to_add_submonoid.comap (f : R →+ S) } @[simp] lemma coe_comap (s : subsemiring S) (f : R →+* S) : (s.comap f : set R) = f ⁻¹' s := rfl @[simp] lemma mem_comap {s : subsemiring S} {f : R →+* S} {x : R} : x ∈ s.comap f ↔ f x ∈ s := iff.rfl lemma comap_comap (s : subsemiring T) (g : S →+* T) (f : R →+* S) : (s.comap g).comap f = s.comap (g.comp f) := rfl /-- The image of a subsemiring along a ring homomorphism is a subsemiring. -/ def map (f : R →+* S) (s : subsemiring R) : subsemiring S := { carrier := f '' s, .. s.to_submonoid.map (f : R →* S), .. s.to_add_submonoid.map (f : R →+ S) } @[simp] lemma coe_map (f : R →+* S) (s : subsemiring R) : (s.map f : set S) = f '' s := rfl @[simp] lemma mem_map {f : R →+* S} {s : subsemiring R} {y : S} : y ∈ s.map f ↔ ∃ x ∈ s, f x = y := set.mem_image_iff_bex @[simp] lemma map_id : s.map (ring_hom.id R) = s := set_like.coe_injective $ set.image_id _ lemma map_map (g : S →+* T) (f : R →+* S) : (s.map f).map g = s.map (g.comp f) := set_like.coe_injective $ set.image_image _ _ _ lemma map_le_iff_le_comap {f : R →+* S} {s : subsemiring R} {t : subsemiring S} : s.map f ≤ t ↔ s ≤ t.comap f := set.image_subset_iff lemma gc_map_comap (f : R →+* S) : galois_connection (map f) (comap f) := λ S T, map_le_iff_le_comap /-- A subsemiring is isomorphic to its image under an injective function -/ noncomputable def equiv_map_of_injective (f : R →+* S) (hf : function.injective f) : s ≃+* s.map f := { map_mul' := λ _ _, subtype.ext (f.map_mul _ _), map_add' := λ _ _, subtype.ext (f.map_add _ _), ..equiv.set.image f s hf } @[simp] lemma coe_equiv_map_of_injective_apply (f : R →+* S) (hf : function.injective f) (x : s) : (equiv_map_of_injective s f hf x : S) = f x := rfl end subsemiring namespace ring_hom variables (g : S →+* T) (f : R →+* S) /-- The range of a ring homomorphism is a subsemiring. See Note [range copy pattern]. -/ def srange : subsemiring S := ((⊤ : subsemiring R).map f).copy (set.range f) set.image_univ.symm @[simp] lemma coe_srange : (f.srange : set S) = set.range f := rfl @[simp] lemma mem_srange {f : R →+* S} {y : S} : y ∈ f.srange ↔ ∃ x, f x = y := iff.rfl lemma srange_eq_map (f : R →+* S) : f.srange = (⊤ : subsemiring R).map f := by { ext, simp } lemma mem_srange_self (f : R →+* S) (x : R) : f x ∈ f.srange := mem_srange.mpr ⟨x, rfl⟩ lemma map_srange : f.srange.map g = (g.comp f).srange := by simpa only [srange_eq_map] using (⊤ : subsemiring R).map_map g f /-- The range of a morphism of semirings is a fintype, if the domain is a fintype. Note: this instance can form a diamond with `subtype.fintype` in the presence of `fintype S`.-/ instance fintype_srange [fintype R] [decidable_eq S] (f : R →+* S) : fintype (srange f) := set.fintype_range f end ring_hom namespace subsemiring instance : has_bot (subsemiring R) := ⟨(nat.cast_ring_hom R).srange⟩ instance : inhabited (subsemiring R) := ⟨⊥⟩ lemma coe_bot : ((⊥ : subsemiring R) : set R) = set.range (coe : ℕ → R) := (nat.cast_ring_hom R).coe_srange lemma mem_bot {x : R} : x ∈ (⊥ : subsemiring R) ↔ ∃ n : ℕ, ↑n=x := ring_hom.mem_srange /-- The inf of two subsemirings is their intersection. -/ instance : has_inf (subsemiring R) := ⟨λ s t, { carrier := s ∩ t, .. s.to_submonoid ⊓ t.to_submonoid, .. s.to_add_submonoid ⊓ t.to_add_submonoid }⟩ @[simp] lemma coe_inf (p p' : subsemiring R) : ((p ⊓ p' : subsemiring R) : set R) = p ∩ p' := rfl @[simp] lemma mem_inf {p p' : subsemiring R} {x : R} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl instance : has_Inf (subsemiring R) := ⟨λ s, subsemiring.mk' (⋂ t ∈ s, ↑t) (⨅ t ∈ s, subsemiring.to_submonoid t) (by simp) (⨅ t ∈ s, subsemiring.to_add_submonoid t) (by simp)⟩ @[simp, norm_cast] lemma coe_Inf (S : set (subsemiring R)) : ((Inf S : subsemiring R) : set R) = ⋂ s ∈ S, ↑s := rfl lemma mem_Inf {S : set (subsemiring R)} {x : R} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_Inter₂ @[simp] lemma Inf_to_submonoid (s : set (subsemiring R)) : (Inf s).to_submonoid = ⨅ t ∈ s, subsemiring.to_submonoid t := mk'_to_submonoid _ _ @[simp] lemma Inf_to_add_submonoid (s : set (subsemiring R)) : (Inf s).to_add_submonoid = ⨅ t ∈ s, subsemiring.to_add_submonoid t := mk'_to_add_submonoid _ _ /-- Subsemirings of a semiring form a complete lattice. -/ instance : complete_lattice (subsemiring R) := { bot := (⊥), bot_le := λ s x hx, let ⟨n, hn⟩ := mem_bot.1 hx in hn ▸ coe_nat_mem s n, top := (⊤), le_top := λ s x hx, trivial, inf := (⊓), inf_le_left := λ s t x, and.left, inf_le_right := λ s t x, and.right, le_inf := λ s t₁ t₂ h₁ h₂ x hx, ⟨h₁ hx, h₂ hx⟩, .. complete_lattice_of_Inf (subsemiring R) (λ s, is_glb.of_image (λ s t, show (s : set R) ≤ t ↔ s ≤ t, from set_like.coe_subset_coe) is_glb_binfi)} lemma eq_top_iff' (A : subsemiring R) : A = ⊤ ↔ ∀ x : R, x ∈ A := eq_top_iff.trans ⟨λ h m, h $ mem_top m, λ h m _, h m⟩ section center /-- The center of a semiring `R` is the set of elements that commute with everything in `R` -/ def center (R) [semiring R] : subsemiring R := { carrier := set.center R, zero_mem' := set.zero_mem_center R, add_mem' := λ a b, set.add_mem_center, .. submonoid.center R } lemma coe_center (R) [semiring R] : ↑(center R) = set.center R := rfl @[simp] lemma center_to_submonoid (R) [semiring R] : (center R).to_submonoid = submonoid.center R := rfl lemma mem_center_iff {R} [semiring R] {z : R} : z ∈ center R ↔ ∀ g, g * z = z * g := iff.rfl instance decidable_mem_center {R} [semiring R] [decidable_eq R] [fintype R] : decidable_pred (∈ center R) := λ _, decidable_of_iff' _ mem_center_iff @[simp] lemma center_eq_top (R) [comm_semiring R] : center R = ⊤ := set_like.coe_injective (set.center_eq_univ R) /-- The center is commutative. -/ instance {R} [semiring R] : comm_semiring (center R) := { ..submonoid.center.comm_monoid, ..(center R).to_semiring} end center section centralizer /-- The centralizer of a set as subsemiring. -/ def centralizer {R} [semiring R] (s : set R) : subsemiring R := { carrier := s.centralizer, zero_mem' := set.zero_mem_centralizer _, add_mem' := λ x y hx hy, set.add_mem_centralizer hx hy, ..submonoid.centralizer s } @[simp, norm_cast] lemma coe_centralizer {R} [semiring R] (s : set R) : (centralizer s : set R) = s.centralizer := rfl lemma centralizer_to_submonoid {R} [semiring R] (s : set R) : (centralizer s).to_submonoid = submonoid.centralizer s := rfl lemma mem_centralizer_iff {R} [semiring R] {s : set R} {z : R} : z ∈ centralizer s ↔ ∀ g ∈ s, g * z = z * g := iff.rfl lemma centralizer_le {R} [semiring R] (s t : set R) (h : s ⊆ t) : centralizer t ≤ centralizer s := set.centralizer_subset h @[simp] lemma centralizer_univ {R} [semiring R] : centralizer set.univ = center R := set_like.ext' (set.centralizer_univ R) end centralizer /-- The `subsemiring` generated by a set. -/ def closure (s : set R) : subsemiring R := Inf {S | s ⊆ S} lemma mem_closure {x : R} {s : set R} : x ∈ closure s ↔ ∀ S : subsemiring R, s ⊆ S → x ∈ S := mem_Inf /-- The subsemiring generated by a set includes the set. -/ @[simp] lemma subset_closure {s : set R} : s ⊆ closure s := λ x hx, mem_closure.2 $ λ S hS, hS hx lemma not_mem_of_not_mem_closure {s : set R} {P : R} (hP : P ∉ closure s) : P ∉ s := λ h, hP (subset_closure h) /-- A subsemiring `S` includes `closure s` if and only if it includes `s`. -/ @[simp] lemma closure_le {s : set R} {t : subsemiring R} : closure s ≤ t ↔ s ⊆ t := ⟨set.subset.trans subset_closure, λ h, Inf_le h⟩ /-- Subsemiring closure of a set is monotone in its argument: if `s ⊆ t`, then `closure s ≤ closure t`. -/ lemma closure_mono ⦃s t : set R⦄ (h : s ⊆ t) : closure s ≤ closure t := closure_le.2 $ set.subset.trans h subset_closure lemma closure_eq_of_le {s : set R} {t : subsemiring R} (h₁ : s ⊆ t) (h₂ : t ≤ closure s) : closure s = t := le_antisymm (closure_le.2 h₁) h₂ lemma mem_map_equiv {f : R ≃+* S} {K : subsemiring R} {x : S} : x ∈ K.map (f : R →+* S) ↔ f.symm x ∈ K := @set.mem_image_equiv _ _ ↑K f.to_equiv x lemma map_equiv_eq_comap_symm (f : R ≃+* S) (K : subsemiring R) : K.map (f : R →+* S) = K.comap f.symm := set_like.coe_injective (f.to_equiv.image_eq_preimage K) lemma comap_equiv_eq_map_symm (f : R ≃+* S) (K : subsemiring S) : K.comap (f : R →+* S) = K.map f.symm := (map_equiv_eq_comap_symm f.symm K).symm end subsemiring namespace submonoid /-- The additive closure of a submonoid is a subsemiring. -/ def subsemiring_closure (M : submonoid R) : subsemiring R := { one_mem' := add_submonoid.mem_closure.mpr (λ y hy, hy M.one_mem), mul_mem' := λ x y, mul_mem_class.mul_mem_add_closure, ..add_submonoid.closure (M : set R)} lemma subsemiring_closure_coe : (M.subsemiring_closure : set R) = add_submonoid.closure (M : set R) := rfl lemma subsemiring_closure_to_add_submonoid : M.subsemiring_closure.to_add_submonoid = add_submonoid.closure (M : set R) := rfl /-- The `subsemiring` generated by a multiplicative submonoid coincides with the `subsemiring.closure` of the submonoid itself . -/ lemma subsemiring_closure_eq_closure : M.subsemiring_closure = subsemiring.closure (M : set R) := begin ext, refine ⟨λ hx, _, λ hx, (subsemiring.mem_closure.mp hx) M.subsemiring_closure (λ s sM, _)⟩; rintros - ⟨H1, rfl⟩; rintros - ⟨H2, rfl⟩, { exact add_submonoid.mem_closure.mp hx H1.to_add_submonoid H2 }, { exact H2 sM } end end submonoid namespace subsemiring @[simp] lemma closure_submonoid_closure (s : set R) : closure ↑(submonoid.closure s) = closure s := le_antisymm (closure_le.mpr (λ y hy, (submonoid.mem_closure.mp hy) (closure s).to_submonoid subset_closure)) (closure_mono (submonoid.subset_closure)) /-- The elements of the subsemiring closure of `M` are exactly the elements of the additive closure of a multiplicative submonoid `M`. -/ lemma coe_closure_eq (s : set R) : (closure s : set R) = add_submonoid.closure (submonoid.closure s : set R) := by simp [← submonoid.subsemiring_closure_to_add_submonoid, submonoid.subsemiring_closure_eq_closure] lemma mem_closure_iff {s : set R} {x} : x ∈ closure s ↔ x ∈ add_submonoid.closure (submonoid.closure s : set R) := set.ext_iff.mp (coe_closure_eq s) x @[simp] lemma closure_add_submonoid_closure {s : set R} : closure ↑(add_submonoid.closure s) = closure s := begin ext x, refine ⟨λ hx, _, λ hx, closure_mono add_submonoid.subset_closure hx⟩, rintros - ⟨H, rfl⟩, rintros - ⟨J, rfl⟩, refine (add_submonoid.mem_closure.mp (mem_closure_iff.mp hx)) H.to_add_submonoid (λ y hy, _), refine (submonoid.mem_closure.mp hy) H.to_submonoid (λ z hz, _), exact (add_submonoid.mem_closure.mp hz) H.to_add_submonoid (λ w hw, J hw), end /-- An induction principle for closure membership. If `p` holds for `0`, `1`, and all elements of `s`, and is preserved under addition and multiplication, then `p` holds for all elements of the closure of `s`. -/ @[elab_as_eliminator] lemma closure_induction {s : set R} {p : R → Prop} {x} (h : x ∈ closure s) (Hs : ∀ x ∈ s, p x) (H0 : p 0) (H1 : p 1) (Hadd : ∀ x y, p x → p y → p (x + y)) (Hmul : ∀ x y, p x → p y → p (x * y)) : p x := (@closure_le _ _ _ ⟨p, Hmul, H1, Hadd, H0⟩).2 Hs h /-- An induction principle for closure membership for predicates with two arguments. -/ @[elab_as_eliminator] lemma closure_induction₂ {s : set R} {p : R → R → Prop} {x} {y : R} (hx : x ∈ closure s) (hy : y ∈ closure s) (Hs : ∀ (x ∈ s) (y ∈ s), p x y) (H0_left : ∀ x, p 0 x) (H0_right : ∀ x, p x 0) (H1_left : ∀ x, p 1 x) (H1_right : ∀ x, p x 1) (Hadd_left : ∀ x₁ x₂ y, p x₁ y → p x₂ y → p (x₁ + x₂) y) (Hadd_right : ∀ x y₁ y₂, p x y₁ → p x y₂ → p x (y₁ + y₂)) (Hmul_left : ∀ x₁ x₂ y, p x₁ y → p x₂ y → p (x₁ * x₂) y) (Hmul_right : ∀ x y₁ y₂, p x y₁ → p x y₂ → p x (y₁ * y₂)) : p x y := closure_induction hx (λ x₁ x₁s, closure_induction hy (Hs x₁ x₁s) (H0_right x₁) (H1_right x₁) (Hadd_right x₁) (Hmul_right x₁)) (H0_left y) (H1_left y) (λ z z', Hadd_left z z' y) (λ z z', Hmul_left z z' y) lemma mem_closure_iff_exists_list {R} [semiring R] {s : set R} {x} : x ∈ closure s ↔ ∃ L : list (list R), (∀ t ∈ L, ∀ y ∈ t, y ∈ s) ∧ (L.map list.prod).sum = x := ⟨λ hx, add_submonoid.closure_induction (mem_closure_iff.1 hx) (λ x hx, suffices ∃ t : list R, (∀ y ∈ t, y ∈ s) ∧ t.prod = x, from let ⟨t, ht1, ht2⟩ := this in ⟨[t], list.forall_mem_singleton.2 ht1, by rw [list.map_singleton, list.sum_singleton, ht2]⟩, submonoid.closure_induction hx (λ x hx, ⟨[x], list.forall_mem_singleton.2 hx, one_mul x⟩) ⟨[], list.forall_mem_nil _, rfl⟩ (λ x y ⟨t, ht1, ht2⟩ ⟨u, hu1, hu2⟩, ⟨t ++ u, list.forall_mem_append.2 ⟨ht1, hu1⟩, by rw [list.prod_append, ht2, hu2]⟩)) ⟨[], list.forall_mem_nil _, rfl⟩ (λ x y ⟨L, HL1, HL2⟩ ⟨M, HM1, HM2⟩, ⟨L ++ M, list.forall_mem_append.2 ⟨HL1, HM1⟩, by rw [list.map_append, list.sum_append, HL2, HM2]⟩), λ ⟨L, HL1, HL2⟩, HL2 ▸ list_sum_mem (λ r hr, let ⟨t, ht1, ht2⟩ := list.mem_map.1 hr in ht2 ▸ list_prod_mem _ (λ y hy, subset_closure $ HL1 t ht1 y hy))⟩ variable (R) /-- `closure` forms a Galois insertion with the coercion to set. -/ protected def gi : galois_insertion (@closure R _) coe := { choice := λ s _, closure s, gc := λ s t, closure_le, le_l_u := λ s, subset_closure, choice_eq := λ s h, rfl } variable {R} /-- Closure of a subsemiring `S` equals `S`. -/ lemma closure_eq (s : subsemiring R) : closure (s : set R) = s := (subsemiring.gi R).l_u_eq s @[simp] lemma closure_empty : closure (∅ : set R) = ⊥ := (subsemiring.gi R).gc.l_bot @[simp] lemma closure_univ : closure (set.univ : set R) = ⊤ := @coe_top R _ ▸ closure_eq ⊤ lemma closure_union (s t : set R) : closure (s ∪ t) = closure s ⊔ closure t := (subsemiring.gi R).gc.l_sup lemma closure_Union {ι} (s : ι → set R) : closure (⋃ i, s i) = ⨆ i, closure (s i) := (subsemiring.gi R).gc.l_supr lemma closure_sUnion (s : set (set R)) : closure (⋃₀ s) = ⨆ t ∈ s, closure t := (subsemiring.gi R).gc.l_Sup lemma map_sup (s t : subsemiring R) (f : R →+* S) : (s ⊔ t).map f = s.map f ⊔ t.map f := (gc_map_comap f).l_sup lemma map_supr {ι : Sort*} (f : R →+* S) (s : ι → subsemiring R) : (supr s).map f = ⨆ i, (s i).map f := (gc_map_comap f).l_supr lemma comap_inf (s t : subsemiring S) (f : R →+* S) : (s ⊓ t).comap f = s.comap f ⊓ t.comap f := (gc_map_comap f).u_inf lemma comap_infi {ι : Sort*} (f : R →+* S) (s : ι → subsemiring S) : (infi s).comap f = ⨅ i, (s i).comap f := (gc_map_comap f).u_infi @[simp] lemma map_bot (f : R →+* S) : (⊥ : subsemiring R).map f = ⊥ := (gc_map_comap f).l_bot @[simp] lemma comap_top (f : R →+* S) : (⊤ : subsemiring S).comap f = ⊤ := (gc_map_comap f).u_top /-- Given `subsemiring`s `s`, `t` of semirings `R`, `S` respectively, `s.prod t` is `s × t` as a subsemiring of `R × S`. -/ def prod (s : subsemiring R) (t : subsemiring S) : subsemiring (R × S) := { carrier := s ×ˢ t, .. s.to_submonoid.prod t.to_submonoid, .. s.to_add_submonoid.prod t.to_add_submonoid} @[norm_cast] lemma coe_prod (s : subsemiring R) (t : subsemiring S) : (s.prod t : set (R × S)) = s ×ˢ t := rfl lemma mem_prod {s : subsemiring R} {t : subsemiring S} {p : R × S} : p ∈ s.prod t ↔ p.1 ∈ s ∧ p.2 ∈ t := iff.rfl @[mono] lemma prod_mono ⦃s₁ s₂ : subsemiring R⦄ (hs : s₁ ≤ s₂) ⦃t₁ t₂ : subsemiring S⦄ (ht : t₁ ≤ t₂) : s₁.prod t₁ ≤ s₂.prod t₂ := set.prod_mono hs ht lemma prod_mono_right (s : subsemiring R) : monotone (λ t : subsemiring S, s.prod t) := prod_mono (le_refl s) lemma prod_mono_left (t : subsemiring S) : monotone (λ s : subsemiring R, s.prod t) := λ s₁ s₂ hs, prod_mono hs (le_refl t) lemma prod_top (s : subsemiring R) : s.prod (⊤ : subsemiring S) = s.comap (ring_hom.fst R S) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_fst] lemma top_prod (s : subsemiring S) : (⊤ : subsemiring R).prod s = s.comap (ring_hom.snd R S) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_snd] @[simp] lemma top_prod_top : (⊤ : subsemiring R).prod (⊤ : subsemiring S) = ⊤ := (top_prod _).trans $ comap_top _ /-- Product of subsemirings is isomorphic to their product as monoids. -/ def prod_equiv (s : subsemiring R) (t : subsemiring S) : s.prod t ≃+* s × t := { map_mul' := λ x y, rfl, map_add' := λ x y, rfl, .. equiv.set.prod ↑s ↑t } lemma mem_supr_of_directed {ι} [hι : nonempty ι] {S : ι → subsemiring R} (hS : directed (≤) S) {x : R} : x ∈ (⨆ i, S i) ↔ ∃ i, x ∈ S i := begin refine ⟨_, λ ⟨i, hi⟩, (set_like.le_def.1 $ le_supr S i) hi⟩, let U : subsemiring R := subsemiring.mk' (⋃ i, (S i : set R)) (⨆ i, (S i).to_submonoid) (submonoid.coe_supr_of_directed $ hS.mono_comp _ (λ _ _, id)) (⨆ i, (S i).to_add_submonoid) (add_submonoid.coe_supr_of_directed $ hS.mono_comp _ (λ _ _, id)), suffices : (⨆ i, S i) ≤ U, by simpa using @this x, exact supr_le (λ i x hx, set.mem_Union.2 ⟨i, hx⟩), end lemma coe_supr_of_directed {ι} [hι : nonempty ι] {S : ι → subsemiring R} (hS : directed (≤) S) : ((⨆ i, S i : subsemiring R) : set R) = ⋃ i, ↑(S i) := set.ext $ λ x, by simp [mem_supr_of_directed hS] lemma mem_Sup_of_directed_on {S : set (subsemiring R)} (Sne : S.nonempty) (hS : directed_on (≤) S) {x : R} : x ∈ Sup S ↔ ∃ s ∈ S, x ∈ s := begin haveI : nonempty S := Sne.to_subtype, simp only [Sup_eq_supr', mem_supr_of_directed hS.directed_coe, set_coe.exists, subtype.coe_mk] end lemma coe_Sup_of_directed_on {S : set (subsemiring R)} (Sne : S.nonempty) (hS : directed_on (≤) S) : (↑(Sup S) : set R) = ⋃ s ∈ S, ↑s := set.ext $ λ x, by simp [mem_Sup_of_directed_on Sne hS] end subsemiring namespace ring_hom variables [non_assoc_semiring T] {s : subsemiring R} variables {σR σS : Type*} variables [set_like σR R] [set_like σS S] [subsemiring_class σR R] [subsemiring_class σS S] open subsemiring /-- Restriction of a ring homomorphism to a subsemiring of the domain. -/ def restrict (f : R →+* S) (s : σR) : s →+* S := f.comp $ subsemiring_class.subtype s @[simp] lemma restrict_apply (f : R →+* S) {s : σR} (x : s) : f.restrict s x = f x := rfl /-- Restriction of a ring homomorphism to a subsemiring of the codomain. -/ def cod_restrict (f : R →+* S) (s : σS) (h : ∀ x, f x ∈ s) : R →+* s := { to_fun := λ n, ⟨f n, h n⟩, .. (f : R →* S).cod_restrict s h, .. (f : R →+ S).cod_restrict s h } /-- Restriction of a ring homomorphism to its range interpreted as a subsemiring. This is the bundled version of `set.range_factorization`. -/ def srange_restrict (f : R →+* S) : R →+* f.srange := f.cod_restrict f.srange f.mem_srange_self @[simp] lemma coe_srange_restrict (f : R →+* S) (x : R) : (f.srange_restrict x : S) = f x := rfl lemma srange_restrict_surjective (f : R →+* S) : function.surjective f.srange_restrict := λ ⟨y, hy⟩, let ⟨x, hx⟩ := mem_srange.mp hy in ⟨x, subtype.ext hx⟩ lemma srange_top_iff_surjective {f : R →+* S} : f.srange = (⊤ : subsemiring S) ↔ function.surjective f := set_like.ext'_iff.trans $ iff.trans (by rw [coe_srange, coe_top]) set.range_iff_surjective /-- The range of a surjective ring homomorphism is the whole of the codomain. -/ lemma srange_top_of_surjective (f : R →+* S) (hf : function.surjective f) : f.srange = (⊤ : subsemiring S) := srange_top_iff_surjective.2 hf /-- The subsemiring of elements `x : R` such that `f x = g x` -/ def eq_slocus (f g : R →+* S) : subsemiring R := { carrier := {x | f x = g x}, .. (f : R →* S).eq_mlocus g, .. (f : R →+ S).eq_mlocus g } /-- If two ring homomorphisms are equal on a set, then they are equal on its subsemiring closure. -/ lemma eq_on_sclosure {f g : R →+* S} {s : set R} (h : set.eq_on f g s) : set.eq_on f g (closure s) := show closure s ≤ f.eq_slocus g, from closure_le.2 h lemma eq_of_eq_on_stop {f g : R →+* S} (h : set.eq_on f g (⊤ : subsemiring R)) : f = g := ext $ λ x, h trivial lemma eq_of_eq_on_sdense {s : set R} (hs : closure s = ⊤) {f g : R →+* S} (h : s.eq_on f g) : f = g := eq_of_eq_on_stop $ hs ▸ eq_on_sclosure h lemma sclosure_preimage_le (f : R →+* S) (s : set S) : closure (f ⁻¹' s) ≤ (closure s).comap f := closure_le.2 $ λ x hx, set_like.mem_coe.2 $ mem_comap.2 $ subset_closure hx /-- The image under a ring homomorphism of the subsemiring generated by a set equals the subsemiring generated by the image of the set. -/ lemma map_sclosure (f : R →+* S) (s : set R) : (closure s).map f = closure (f '' s) := le_antisymm (map_le_iff_le_comap.2 $ le_trans (closure_mono $ set.subset_preimage_image _ _) (sclosure_preimage_le _ _)) (closure_le.2 $ set.image_subset _ subset_closure) end ring_hom namespace subsemiring open ring_hom /-- The ring homomorphism associated to an inclusion of subsemirings. -/ def inclusion {S T : subsemiring R} (h : S ≤ T) : S →+* T := S.subtype.cod_restrict _ (λ x, h x.2) @[simp] lemma srange_subtype (s : subsemiring R) : s.subtype.srange = s := set_like.coe_injective $ (coe_srange _).trans subtype.range_coe @[simp] lemma range_fst : (fst R S).srange = ⊤ := (fst R S).srange_top_of_surjective $ prod.fst_surjective @[simp] lemma range_snd : (snd R S).srange = ⊤ := (snd R S).srange_top_of_surjective $ prod.snd_surjective @[simp] lemma prod_bot_sup_bot_prod (s : subsemiring R) (t : subsemiring S) : (s.prod ⊥) ⊔ (prod ⊥ t) = s.prod t := le_antisymm (sup_le (prod_mono_right s bot_le) (prod_mono_left t bot_le)) $ assume p hp, prod.fst_mul_snd p ▸ mul_mem ((le_sup_left : s.prod ⊥ ≤ s.prod ⊥ ⊔ prod ⊥ t) ⟨hp.1, set_like.mem_coe.2 $ one_mem ⊥⟩) ((le_sup_right : prod ⊥ t ≤ s.prod ⊥ ⊔ prod ⊥ t) ⟨set_like.mem_coe.2 $ one_mem ⊥, hp.2⟩) end subsemiring namespace ring_equiv variables {s t : subsemiring R} /-- Makes the identity isomorphism from a proof two subsemirings of a multiplicative monoid are equal. -/ def subsemiring_congr (h : s = t) : s ≃+* t := { map_mul' := λ _ _, rfl, map_add' := λ _ _, rfl, ..equiv.set_congr $ congr_arg _ h } /-- Restrict a ring homomorphism with a left inverse to a ring isomorphism to its `ring_hom.srange`. -/ def sof_left_inverse {g : S → R} {f : R →+* S} (h : function.left_inverse g f) : R ≃+* f.srange := { to_fun := λ x, f.srange_restrict x, inv_fun := λ x, (g ∘ f.srange.subtype) x, left_inv := h, right_inv := λ x, subtype.ext $ let ⟨x', hx'⟩ := ring_hom.mem_srange.mp x.prop in show f (g x) = x, by rw [←hx', h x'], ..f.srange_restrict } @[simp] lemma sof_left_inverse_apply {g : S → R} {f : R →+* S} (h : function.left_inverse g f) (x : R) : ↑(sof_left_inverse h x) = f x := rfl @[simp] lemma sof_left_inverse_symm_apply {g : S → R} {f : R →+* S} (h : function.left_inverse g f) (x : f.srange) : (sof_left_inverse h).symm x = g x := rfl /-- Given an equivalence `e : R ≃+* S` of semirings and a subsemiring `s` of `R`, `subsemiring_map e s` is the induced equivalence between `s` and `s.map e` -/ @[simps] def subsemiring_map (e : R ≃+* S) (s : subsemiring R) : s ≃+* s.map e.to_ring_hom := { ..e.to_add_equiv.add_submonoid_map s.to_add_submonoid, ..e.to_mul_equiv.submonoid_map s.to_submonoid } end ring_equiv /-! ### Actions by `subsemiring`s These are just copies of the definitions about `submonoid` starting from `submonoid.mul_action`. The only new result is `subsemiring.module`. When `R` is commutative, `algebra.of_subsemiring` provides a stronger result than those found in this file, which uses the same scalar action. -/ section actions namespace subsemiring variables {R' α β : Type*} section non_assoc_semiring variables [non_assoc_semiring R'] /-- The action by a subsemiring is the action by the underlying semiring. -/ instance [has_smul R' α] (S : subsemiring R') : has_smul S α := S.to_submonoid.has_smul lemma smul_def [has_smul R' α] {S : subsemiring R'} (g : S) (m : α) : g • m = (g : R') • m := rfl instance smul_comm_class_left [has_smul R' β] [has_smul α β] [smul_comm_class R' α β] (S : subsemiring R') : smul_comm_class S α β := S.to_submonoid.smul_comm_class_left instance smul_comm_class_right [has_smul α β] [has_smul R' β] [smul_comm_class α R' β] (S : subsemiring R') : smul_comm_class α S β := S.to_submonoid.smul_comm_class_right /-- Note that this provides `is_scalar_tower S R R` which is needed by `smul_mul_assoc`. -/ instance [has_smul α β] [has_smul R' α] [has_smul R' β] [is_scalar_tower R' α β] (S : subsemiring R') : is_scalar_tower S α β := S.to_submonoid.is_scalar_tower instance [has_smul R' α] [has_faithful_smul R' α] (S : subsemiring R') : has_faithful_smul S α := S.to_submonoid.has_faithful_smul /-- The action by a subsemiring is the action by the underlying semiring. -/ instance [has_zero α] [smul_with_zero R' α] (S : subsemiring R') : smul_with_zero S α := smul_with_zero.comp_hom _ S.subtype.to_monoid_with_zero_hom.to_zero_hom end non_assoc_semiring variables [semiring R'] /-- The action by a subsemiring is the action by the underlying semiring. -/ instance [mul_action R' α] (S : subsemiring R') : mul_action S α := S.to_submonoid.mul_action /-- The action by a subsemiring is the action by the underlying semiring. -/ instance [add_monoid α] [distrib_mul_action R' α] (S : subsemiring R') : distrib_mul_action S α := S.to_submonoid.distrib_mul_action /-- The action by a subsemiring is the action by the underlying semiring. -/ instance [monoid α] [mul_distrib_mul_action R' α] (S : subsemiring R') : mul_distrib_mul_action S α := S.to_submonoid.mul_distrib_mul_action /-- The action by a subsemiring is the action by the underlying semiring. -/ instance [has_zero α] [mul_action_with_zero R' α] (S : subsemiring R') : mul_action_with_zero S α := mul_action_with_zero.comp_hom _ S.subtype.to_monoid_with_zero_hom /-- The action by a subsemiring is the action by the underlying semiring. -/ instance [add_comm_monoid α] [module R' α] (S : subsemiring R') : module S α := { smul := (•), .. module.comp_hom _ S.subtype } /-- The center of a semiring acts commutatively on that semiring. -/ instance center.smul_comm_class_left : smul_comm_class (center R') R' R' := submonoid.center.smul_comm_class_left /-- The center of a semiring acts commutatively on that semiring. -/ instance center.smul_comm_class_right : smul_comm_class R' (center R') R' := submonoid.center.smul_comm_class_right /-- If all the elements of a set `s` commute, then `closure s` is a commutative monoid. -/ def closure_comm_semiring_of_comm {s : set R'} (hcomm : ∀ (a ∈ s) (b ∈ s), a * b = b * a) : comm_semiring (closure s) := { mul_comm := λ x y, begin ext, simp only [subsemiring.coe_mul], refine closure_induction₂ x.prop y.prop hcomm (λ x, by simp only [zero_mul, mul_zero]) (λ x, by simp only [zero_mul, mul_zero]) (λ x, by simp only [one_mul, mul_one]) (λ x, by simp only [one_mul, mul_one]) (λ x y z h₁ h₂, by simp only [add_mul, mul_add, h₁, h₂]) (λ x y z h₁ h₂, by simp only [add_mul, mul_add, h₁, h₂]) (λ x y z h₁ h₂, by rw [mul_assoc, h₂, ←mul_assoc, h₁, mul_assoc]) (λ x y z h₁ h₂, by rw [←mul_assoc, h₁, mul_assoc, h₂, ←mul_assoc]) end, ..(closure s).to_semiring } end subsemiring end actions -- While this definition is not about `subsemiring`s, this is the earliest we have -- both `ordered_semiring` and `submonoid` available. /-- Submonoid of positive elements of an ordered semiring. -/ def pos_submonoid (R : Type*) [ordered_semiring R] [nontrivial R] : submonoid R := { carrier := {x | 0 < x}, one_mem' := show (0 : R) < 1, from zero_lt_one, mul_mem' := λ x y (hx : 0 < x) (hy : 0 < y), mul_pos hx hy } @[simp] lemma mem_pos_monoid {R : Type*} [ordered_semiring R] [nontrivial R] (u : Rˣ) : ↑u ∈ pos_submonoid R ↔ (0 : R) < u := iff.rfl
5c439424446fcc704955ba447615e4f53d68510c
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Elab/MutualDef.lean
e37eb7d206ef32eadfc4f01f38dbaef88adcf18a
[ "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
39,549
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.Parser.Term import Lean.Meta.Closure import Lean.Meta.Check import Lean.Meta.Transform import Lean.PrettyPrinter.Delaborator.Options import Lean.Elab.Command import Lean.Elab.Match import Lean.Elab.DefView import Lean.Elab.Deriving.Basic import Lean.Elab.PreDefinition.Main import Lean.Elab.DeclarationRange namespace Lean.Elab open Lean.Parser.Term /-- `DefView` after elaborating the header. -/ structure DefViewElabHeader where ref : Syntax modifiers : Modifiers /-- Stores whether this is the header of a definition, theorem, ... -/ kind : DefKind /-- Short name. Recall that all declarations in Lean 4 are potentially recursive. We use `shortDeclName` to refer to them at `valueStx`, and other declarations in the same mutual block. -/ shortDeclName : Name /-- Full name for this declaration. This is the name that will be added to the `Environment`. -/ declName : Name /-- Universe level parameter names explicitly provided by the user. -/ levelNames : List Name /-- Syntax objects for the binders occurring befor `:`, we use them to populate the `InfoTree` when elaborating `valueStx`. -/ binderIds : Array Syntax /-- Number of parameters before `:`, it also includes auto-implicit parameters automatically added by Lean. -/ numParams : Nat /-- Type including parameters. -/ type : Expr /-- `Syntax` object the body/value of the definition. -/ valueStx : Syntax deriving Inhabited namespace Term open Meta private def checkModifiers (m₁ m₂ : Modifiers) : TermElabM Unit := do unless m₁.isUnsafe == m₂.isUnsafe do throwError "cannot mix unsafe and safe definitions" unless m₁.isNoncomputable == m₂.isNoncomputable do throwError "cannot mix computable and non-computable definitions" unless m₁.isPartial == m₂.isPartial do throwError "cannot mix partial and non-partial definitions" private def checkKinds (k₁ k₂ : DefKind) : TermElabM Unit := do unless k₁.isExample == k₂.isExample do throwError "cannot mix examples and definitions" -- Reason: we should discard examples unless k₁.isTheorem == k₂.isTheorem do throwError "cannot mix theorems and definitions" -- Reason: we will eventually elaborate theorems in `Task`s. private def check (prevHeaders : Array DefViewElabHeader) (newHeader : DefViewElabHeader) : TermElabM Unit := do if newHeader.kind.isTheorem && newHeader.modifiers.isUnsafe then throwError "'unsafe' theorems are not allowed" if newHeader.kind.isTheorem && newHeader.modifiers.isPartial then throwError "'partial' theorems are not allowed, 'partial' is a code generation directive" if newHeader.kind.isTheorem && newHeader.modifiers.isNoncomputable then throwError "'theorem' subsumes 'noncomputable', code is not generated for theorems" if newHeader.modifiers.isNoncomputable && newHeader.modifiers.isUnsafe then throwError "'noncomputable unsafe' is not allowed" if newHeader.modifiers.isNoncomputable && newHeader.modifiers.isPartial then throwError "'noncomputable partial' is not allowed" if newHeader.modifiers.isPartial && newHeader.modifiers.isUnsafe then throwError "'unsafe' subsumes 'partial'" if h : 0 < prevHeaders.size then let firstHeader := prevHeaders.get ⟨0, h⟩ try unless newHeader.levelNames == firstHeader.levelNames do throwError "universe parameters mismatch" checkModifiers newHeader.modifiers firstHeader.modifiers checkKinds newHeader.kind firstHeader.kind catch | .error ref msg => throw (.error ref m!"invalid mutually recursive definitions, {msg}") | ex => throw ex else pure () private def registerFailedToInferDefTypeInfo (type : Expr) (ref : Syntax) : TermElabM Unit := registerCustomErrorIfMVar type ref "failed to infer definition type" /-- Return `some [b, c]` if the given `views` are representing a declaration of the form ``` opaque a b c : Nat ``` -/ private def isMultiConstant? (views : Array DefView) : Option (List Name) := if views.size == 1 && views[0]!.kind == .opaque && views[0]!.binders.getArgs.size > 0 && views[0]!.binders.getArgs.all (·.isIdent) then some (views[0]!.binders.getArgs.toList.map (·.getId)) else none private def getPendindMVarErrorMessage (views : Array DefView) : String := match isMultiConstant? views with | some ids => let idsStr := ", ".intercalate <| ids.map fun id => s!"`{id}`" let paramsStr := ", ".intercalate <| ids.map fun id => s!"`({id} : _)`" s!"\nrecall that you cannot declare multiple constants in a single declaration. The identifier(s) {idsStr} are being interpreted as parameters {paramsStr}" | none => "\nwhen the resulting type of a declaration is explicitly provided, all holes (e.g., `_`) in the header are resolved before the declaration body is processed" /-- Convert terms of the form `OfNat <type> (OfNat.ofNat Nat <num> ..)` into `OfNat <type> <num>`. We use this method on instance declaration types. The motivation is to address a recurrent mistake when users forget to use `nat_lit` when declaring `OfNat` instances. See issues #1389 and #875 -/ private def cleanupOfNat (type : Expr) : MetaM Expr := do Meta.transform type fun e => do if !e.isAppOfArity ``OfNat 2 then return .continue let arg ← instantiateMVars e.appArg! if !arg.isAppOfArity ``OfNat.ofNat 3 then return .continue let argArgs := arg.getAppArgs if !argArgs[0]!.isConstOf ``Nat then return .continue let eNew := mkApp e.appFn! argArgs[1]! return .done eNew /-- Elaborate only the declaration headers. We have to elaborate the headers first because we support mutually recursive declarations in Lean 4. -/ private def elabHeaders (views : Array DefView) : TermElabM (Array DefViewElabHeader) := do let expandedDeclIds ← views.mapM fun view => withRef view.ref do Term.expandDeclId (← getCurrNamespace) (← getLevelNames) view.declId view.modifiers withAutoBoundImplicitForbiddenPred (fun n => expandedDeclIds.any (·.shortName == n)) do let mut headers := #[] for view in views, ⟨shortDeclName, declName, levelNames⟩ in expandedDeclIds do let newHeader ← withRef view.ref do addDeclarationRanges declName view.ref applyAttributesAt declName view.modifiers.attrs .beforeElaboration withDeclName declName <| withAutoBoundImplicit <| withLevelNames levelNames <| elabBindersEx view.binders.getArgs fun xs => do let refForElabFunType := view.value let mut type ← match view.type? with | some typeStx => let type ← elabType typeStx registerFailedToInferDefTypeInfo type typeStx pure type | none => let hole := mkHole refForElabFunType let type ← elabType hole trace[Elab.definition] ">> type: {type}\n{type.mvarId!}" registerFailedToInferDefTypeInfo type refForElabFunType pure type Term.synthesizeSyntheticMVarsNoPostponing if view.isInstance then type ← cleanupOfNat type let (binderIds, xs) := xs.unzip -- TODO: add forbidden predicate using `shortDeclName` from `views` let xs ← addAutoBoundImplicits xs type ← mkForallFVars' xs type type ← instantiateMVars type let levelNames ← getLevelNames if view.type?.isSome then let pendingMVarIds ← getMVars type discard <| logUnassignedUsingErrorInfos pendingMVarIds <| getPendindMVarErrorMessage views let newHeader := { ref := view.ref modifiers := view.modifiers kind := view.kind shortDeclName := shortDeclName declName, type, levelNames, binderIds numParams := xs.size valueStx := view.value : DefViewElabHeader } check headers newHeader return newHeader headers := headers.push newHeader return headers /-- Create auxiliary local declarations `fs` for the given hearders using their `shortDeclName` and `type`, given hearders, and execute `k fs`. The new free variables are tagged as `auxDecl`. Remark: `fs.size = headers.size`. -/ private partial def withFunLocalDecls {α} (headers : Array DefViewElabHeader) (k : Array Expr → TermElabM α) : TermElabM α := let rec loop (i : Nat) (fvars : Array Expr) := do if h : i < headers.size then let header := headers.get ⟨i, h⟩ if header.modifiers.isNonrec then loop (i+1) fvars else withAuxDecl header.shortDeclName header.type header.declName fun fvar => loop (i+1) (fvars.push fvar) else k fvars loop 0 #[] private def expandWhereStructInst : Macro | `(Parser.Command.whereStructInst|where $[$decls:letDecl];* $[$whereDecls?:whereDecls]?) => do let letIdDecls ← decls.mapM fun stx => match stx with | `(letDecl|$_decl:letPatDecl) => Macro.throwErrorAt stx "patterns are not allowed here" | `(letDecl|$decl:letEqnsDecl) => expandLetEqnsDecl decl (useExplicit := false) | `(letDecl|$decl:letIdDecl) => pure decl | _ => Macro.throwUnsupported let structInstFields ← letIdDecls.mapM fun | stx@`(letIdDecl|$id:ident $binders* $[: $ty?]? := $val) => withRef stx do let mut val := val if let some ty := ty? then val ← `(($val : $ty)) -- HACK: this produces invalid syntax, but the fun elaborator supports letIdBinders as well have : Coe (TSyntax ``letIdBinder) (TSyntax ``funBinder) := ⟨(⟨·⟩)⟩ val ← if binders.size > 0 then `(fun $binders* => $val) else pure val `(structInstField|$id:ident := $val) | stx@`(letIdDecl|_ $_* $[: $_]? := $_) => Macro.throwErrorAt stx "'_' is not allowed here" | _ => Macro.throwUnsupported let body ← `({ $structInstFields,* }) match whereDecls? with | some whereDecls => expandWhereDecls whereDecls body | none => return body | _ => Macro.throwUnsupported /- Recall that ``` def declValSimple := leading_parser " :=\n" >> termParser >> optional Term.whereDecls def declValEqns := leading_parser Term.matchAltsWhereDecls def declVal := declValSimple <|> declValEqns <|> Term.whereDecls ``` -/ private def declValToTerm (declVal : Syntax) : MacroM Syntax := withRef declVal do if declVal.isOfKind ``Parser.Command.declValSimple then expandWhereDeclsOpt declVal[2] declVal[1] else if declVal.isOfKind ``Parser.Command.declValEqns then expandMatchAltsWhereDecls declVal[0] else if declVal.isOfKind ``Parser.Command.whereStructInst then expandWhereStructInst declVal else if declVal.isMissing then Macro.throwErrorAt declVal "declaration body is missing" else Macro.throwErrorAt declVal "unexpected declaration body" private def elabFunValues (headers : Array DefViewElabHeader) : TermElabM (Array Expr) := headers.mapM fun header => withDeclName header.declName <| withLevelNames header.levelNames do let valStx ← liftMacroM <| declValToTerm header.valueStx forallBoundedTelescope header.type header.numParams fun xs type => do -- Add new info nodes for new fvars. The server will detect all fvars of a binder by the binder's source location. for i in [0:header.binderIds.size] do -- skip auto-bound prefix in `xs` addLocalVarInfo header.binderIds[i]! xs[header.numParams - header.binderIds.size + i]! let val ← elabTermEnsuringType valStx type mkLambdaFVars xs val private def collectUsed (headers : Array DefViewElabHeader) (values : Array Expr) (toLift : List LetRecToLift) : StateRefT CollectFVars.State MetaM Unit := do headers.forM fun header => header.type.collectFVars values.forM fun val => val.collectFVars toLift.forM fun letRecToLift => do letRecToLift.type.collectFVars letRecToLift.val.collectFVars private def removeUnusedVars (vars : Array Expr) (headers : Array DefViewElabHeader) (values : Array Expr) (toLift : List LetRecToLift) : TermElabM (LocalContext × LocalInstances × Array Expr) := do let (_, used) ← (collectUsed headers values toLift).run {} removeUnused vars used private def withUsed {α} (vars : Array Expr) (headers : Array DefViewElabHeader) (values : Array Expr) (toLift : List LetRecToLift) (k : Array Expr → TermElabM α) : TermElabM α := do let (lctx, localInsts, vars) ← removeUnusedVars vars headers values toLift withLCtx lctx localInsts <| k vars private def isExample (views : Array DefView) : Bool := views.any (·.kind.isExample) private def isTheorem (views : Array DefView) : Bool := views.any (·.kind.isTheorem) private def instantiateMVarsAtHeader (header : DefViewElabHeader) : TermElabM DefViewElabHeader := do let type ← instantiateMVars header.type pure { header with type := type } private def instantiateMVarsAtLetRecToLift (toLift : LetRecToLift) : TermElabM LetRecToLift := do let type ← instantiateMVars toLift.type let val ← instantiateMVars toLift.val pure { toLift with type, val } private def typeHasRecFun (type : Expr) (funFVars : Array Expr) (letRecsToLift : List LetRecToLift) : Option FVarId := let occ? := type.find? fun e => match e with | Expr.fvar fvarId => funFVars.contains e || letRecsToLift.any fun toLift => toLift.fvarId == fvarId | _ => false match occ? with | some (Expr.fvar fvarId) => some fvarId | _ => none private def getFunName (fvarId : FVarId) (letRecsToLift : List LetRecToLift) : TermElabM Name := do match (← fvarId.findDecl?) with | some decl => return decl.userName | none => /- Recall that the FVarId of nested let-recs are not in the current local context. -/ match letRecsToLift.findSome? fun toLift => if toLift.fvarId == fvarId then some toLift.shortDeclName else none with | none => throwError "unknown function" | some n => return n /-- Ensures that the of let-rec definition types do not contain functions being defined. In principle, this test can be improved. We could perform it after we separate the set of functions is strongly connected components. However, this extra complication doesn't seem worth it. -/ private def checkLetRecsToLiftTypes (funVars : Array Expr) (letRecsToLift : List LetRecToLift) : TermElabM Unit := letRecsToLift.forM fun toLift => match typeHasRecFun toLift.type funVars letRecsToLift with | none => pure () | some fvarId => do let fnName ← getFunName fvarId letRecsToLift throwErrorAt toLift.ref "invalid type in 'let rec', it uses '{fnName}' which is being defined simultaneously" namespace MutualClosure /-- A mapping from FVarId to Set of FVarIds. -/ abbrev UsedFVarsMap := FVarIdMap FVarIdSet /-- Create the `UsedFVarsMap` mapping that takes the variable id for the mutually recursive functions being defined to the set of free variables in its definition. For `mainFVars`, this is just the set of section variables `sectionVars` used. For nested let-rec functions, we collect their free variables. Recall that a `let rec` expressions are encoded as follows in the elaborator. ```lean let rec f : A := t, g : B := s; body ``` is encoded as ```lean let f : A := ?m₁; let g : B := ?m₂; body ``` where `?m₁` and `?m₂` are synthetic opaque metavariables. That are assigned by this module. We may have nested `let rec`s. ```lean let rec f : A := let rec g : B := t; s; body ``` is encoded as ```lean let f : A := ?m₁; body ``` and the body of `f` is stored the field `val` of a `LetRecToLift`. For the example above, we would have a `LetRecToLift` containing: ``` { mvarId := m₁, val := `(let g : B := ?m₂; body) ... } ``` Note that `g` is not a free variable at `(let g : B := ?m₂; body)`. We recover the fact that `f` depends on `g` because it contains `m₂` -/ private def mkInitialUsedFVarsMap [Monad m] [MonadMCtx m] (sectionVars : Array Expr) (mainFVarIds : Array FVarId) (letRecsToLift : Array LetRecToLift) : m UsedFVarsMap := do let mut sectionVarSet := {} for var in sectionVars do sectionVarSet := sectionVarSet.insert var.fvarId! let mut usedFVarMap := {} for mainFVarId in mainFVarIds do usedFVarMap := usedFVarMap.insert mainFVarId sectionVarSet for toLift in letRecsToLift do let state := Lean.collectFVars {} toLift.val let state := Lean.collectFVars state toLift.type let mut set := state.fvarSet /- toLift.val may contain metavariables that are placeholders for nested let-recs. We should collect the fvarId for the associated let-rec because we need this information to compute the fixpoint later. -/ let mvarIds := (toLift.val.collectMVars {}).result for mvarId in mvarIds do match (← letRecsToLift.findSomeM? fun (toLift : LetRecToLift) => return if toLift.mvarId == (← getDelayedMVarRoot mvarId) then some toLift.fvarId else none) with | some fvarId => set := set.insert fvarId | none => pure () usedFVarMap := usedFVarMap.insert toLift.fvarId set return usedFVarMap /-! The let-recs may invoke each other. Example: ``` let rec f (x : Nat) := g x + y g : Nat → Nat | 0 => 1 | x+1 => f x + z ``` `y` is free variable in `f`, and `z` is a free variable in `g`. To close `f` and `g`, `y` and `z` must be in the closure of both. That is, we need to generate the top-level definitions. ``` def f (y z x : Nat) := g y z x + y def g (y z : Nat) : Nat → Nat | 0 => 1 | x+1 => f y z x + z ``` -/ namespace FixPoint structure State where usedFVarsMap : UsedFVarsMap := {} modified : Bool := false abbrev M := ReaderT (Array FVarId) $ StateM State private def isModified : M Bool := do pure (← get).modified private def resetModified : M Unit := modify fun s => { s with modified := false } private def markModified : M Unit := modify fun s => { s with modified := true } private def getUsedFVarsMap : M UsedFVarsMap := do pure (← get).usedFVarsMap private def modifyUsedFVars (f : UsedFVarsMap → UsedFVarsMap) : M Unit := modify fun s => { s with usedFVarsMap := f s.usedFVarsMap } -- merge s₂ into s₁ private def merge (s₁ s₂ : FVarIdSet) : M FVarIdSet := s₂.foldM (init := s₁) fun s₁ k => do if s₁.contains k then return s₁ else markModified return s₁.insert k private def updateUsedVarsOf (fvarId : FVarId) : M Unit := do let usedFVarsMap ← getUsedFVarsMap match usedFVarsMap.find? fvarId with | none => return () | some fvarIds => let fvarIdsNew ← fvarIds.foldM (init := fvarIds) fun fvarIdsNew fvarId' => do if fvarId == fvarId' then return fvarIdsNew else match usedFVarsMap.find? fvarId' with | none => return fvarIdsNew /- We are being sloppy here `otherFVarIds` may contain free variables that are not in the context of the let-rec associated with fvarId. We filter these out-of-context free variables later. -/ | some otherFVarIds => merge fvarIdsNew otherFVarIds modifyUsedFVars fun usedFVars => usedFVars.insert fvarId fvarIdsNew private partial def fixpoint : Unit → M Unit | _ => do resetModified let letRecFVarIds ← read letRecFVarIds.forM updateUsedVarsOf if (← isModified) then fixpoint () def run (letRecFVarIds : Array FVarId) (usedFVarsMap : UsedFVarsMap) : UsedFVarsMap := let (_, s) := fixpoint () |>.run letRecFVarIds |>.run { usedFVarsMap := usedFVarsMap } s.usedFVarsMap end FixPoint abbrev FreeVarMap := FVarIdMap (Array FVarId) private def mkFreeVarMap [Monad m] [MonadMCtx m] (sectionVars : Array Expr) (mainFVarIds : Array FVarId) (recFVarIds : Array FVarId) (letRecsToLift : Array LetRecToLift) : m FreeVarMap := do let usedFVarsMap ← mkInitialUsedFVarsMap sectionVars mainFVarIds letRecsToLift let letRecFVarIds := letRecsToLift.map fun toLift => toLift.fvarId let usedFVarsMap := FixPoint.run letRecFVarIds usedFVarsMap let mut freeVarMap := {} for toLift in letRecsToLift do let lctx := toLift.lctx let fvarIdsSet := usedFVarsMap.find? toLift.fvarId |>.get! let fvarIds := fvarIdsSet.fold (init := #[]) fun fvarIds fvarId => if lctx.contains fvarId && !recFVarIds.contains fvarId then fvarIds.push fvarId else fvarIds freeVarMap := freeVarMap.insert toLift.fvarId fvarIds return freeVarMap structure ClosureState where newLocalDecls : Array LocalDecl := #[] localDecls : Array LocalDecl := #[] newLetDecls : Array LocalDecl := #[] exprArgs : Array Expr := #[] private def pickMaxFVar? (lctx : LocalContext) (fvarIds : Array FVarId) : Option FVarId := fvarIds.getMax? fun fvarId₁ fvarId₂ => (lctx.get! fvarId₁).index < (lctx.get! fvarId₂).index private def preprocess (e : Expr) : TermElabM Expr := do let e ← instantiateMVars e -- which let-decls are dependent. We say a let-decl is dependent if its lambda abstraction is type incorrect. Meta.check e pure e /-- Push free variables in `s` to `toProcess` if they are not already there. -/ private def pushNewVars (toProcess : Array FVarId) (s : CollectFVars.State) : Array FVarId := s.fvarSet.fold (init := toProcess) fun toProcess fvarId => if toProcess.contains fvarId then toProcess else toProcess.push fvarId private def pushLocalDecl (toProcess : Array FVarId) (fvarId : FVarId) (userName : Name) (type : Expr) (bi : BinderInfo) (kind : LocalDeclKind) : StateRefT ClosureState TermElabM (Array FVarId) := do let type ← preprocess type modify fun s => { s with newLocalDecls := s.newLocalDecls.push <| LocalDecl.cdecl default fvarId userName type bi kind exprArgs := s.exprArgs.push (mkFVar fvarId) } return pushNewVars toProcess (collectFVars {} type) private partial def mkClosureForAux (toProcess : Array FVarId) : StateRefT ClosureState TermElabM Unit := do let lctx ← getLCtx match pickMaxFVar? lctx toProcess with | none => return () | some fvarId => trace[Elab.definition.mkClosure] "toProcess: {toProcess.map mkFVar}, maxVar: {mkFVar fvarId}" let toProcess := toProcess.erase fvarId let localDecl ← fvarId.getDecl match localDecl with | .cdecl _ _ userName type bi k => let toProcess ← pushLocalDecl toProcess fvarId userName type bi k mkClosureForAux toProcess | .ldecl _ _ userName type val _ k => let zetaFVarIds ← getZetaFVarIds if !zetaFVarIds.contains fvarId then /- Non-dependent let-decl. See comment at src/Lean/Meta/Closure.lean -/ let toProcess ← pushLocalDecl toProcess fvarId userName type .default k mkClosureForAux toProcess else /- Dependent let-decl. -/ let type ← preprocess type let val ← preprocess val modify fun s => { s with newLetDecls := s.newLetDecls.push <| .ldecl default fvarId userName type val false k, /- We don't want to interleave let and lambda declarations in our closure. So, we expand any occurrences of fvarId at `newLocalDecls` and `localDecls` -/ newLocalDecls := s.newLocalDecls.map (·.replaceFVarId fvarId val) localDecls := s.localDecls.map (·.replaceFVarId fvarId val) } mkClosureForAux (pushNewVars toProcess (collectFVars (collectFVars {} type) val)) private partial def mkClosureFor (freeVars : Array FVarId) (localDecls : Array LocalDecl) : TermElabM ClosureState := do let (_, s) ← mkClosureForAux freeVars |>.run { localDecls := localDecls } return { s with newLocalDecls := s.newLocalDecls.reverse newLetDecls := s.newLetDecls.reverse exprArgs := s.exprArgs.reverse } structure LetRecClosure where ref : Syntax localDecls : Array LocalDecl /-- Expression used to replace occurrences of the let-rec `FVarId`. -/ closed : Expr toLift : LetRecToLift private def mkLetRecClosureFor (toLift : LetRecToLift) (freeVars : Array FVarId) : TermElabM LetRecClosure := do let lctx := toLift.lctx withLCtx lctx toLift.localInstances do lambdaTelescope toLift.val fun xs val => do /- Recall that `toLift.type` and `toLift.value` may have different binder annotations. See issue #1377 for an example. -/ let userNameAndBinderInfos ← forallBoundedTelescope toLift.type xs.size fun xs _ => xs.mapM fun x => do let localDecl ← x.fvarId!.getDecl return (localDecl.userName, localDecl.binderInfo) /- Auxiliary map for preserving binder user-facing names and `BinderInfo` for types. -/ let mut userNameBinderInfoMap : FVarIdMap (Name × BinderInfo) := {} for x in xs, (userName, bi) in userNameAndBinderInfos do userNameBinderInfoMap := userNameBinderInfoMap.insert x.fvarId! (userName, bi) let type ← instantiateForall toLift.type xs let lctx ← getLCtx let s ← mkClosureFor freeVars <| xs.map fun x => lctx.get! x.fvarId! /- Apply original type binder info and user-facing names to local declarations. -/ let typeLocalDecls := s.localDecls.map fun localDecl => if let some (userName, bi) := userNameBinderInfoMap.find? localDecl.fvarId then localDecl.setBinderInfo bi |>.setUserName userName else localDecl let type := Closure.mkForall typeLocalDecls <| Closure.mkForall s.newLetDecls type let val := Closure.mkLambda s.localDecls <| Closure.mkLambda s.newLetDecls val let c := mkAppN (Lean.mkConst toLift.declName) s.exprArgs toLift.mvarId.assign c return { ref := toLift.ref localDecls := s.newLocalDecls closed := c toLift := { toLift with val, type } } private def mkLetRecClosures (sectionVars : Array Expr) (mainFVarIds : Array FVarId) (recFVarIds : Array FVarId) (letRecsToLift : Array LetRecToLift) : TermElabM (List LetRecClosure) := do -- Compute the set of free variables (excluding `recFVarIds`) for each let-rec. let mut letRecsToLift := letRecsToLift let mut freeVarMap ← mkFreeVarMap sectionVars mainFVarIds recFVarIds letRecsToLift let mut result := #[] for i in [:letRecsToLift.size] do if letRecsToLift[i]!.val.hasExprMVar then -- This can happen when this particular let-rec has nested let-rec that have been resolved in previous iterations. -- This code relies on the fact that nested let-recs occur before the outer most let-recs at `letRecsToLift`. -- Unresolved nested let-recs appear as metavariables before they are resolved. See `assignExprMVar` at `mkLetRecClosureFor` let valNew ← instantiateMVars letRecsToLift[i]!.val letRecsToLift := letRecsToLift.modify i fun t => { t with val := valNew } -- We have to recompute the `freeVarMap` in this case. This overhead should not be an issue in practice. freeVarMap ← mkFreeVarMap sectionVars mainFVarIds recFVarIds letRecsToLift let toLift := letRecsToLift[i]! result := result.push (← mkLetRecClosureFor toLift (freeVarMap.find? toLift.fvarId).get!) return result.toList /-- Mapping from FVarId of mutually recursive functions being defined to "closure" expression. -/ abbrev Replacement := FVarIdMap Expr def insertReplacementForMainFns (r : Replacement) (sectionVars : Array Expr) (mainHeaders : Array DefViewElabHeader) (mainFVars : Array Expr) : Replacement := mainFVars.size.fold (init := r) fun i r => r.insert mainFVars[i]!.fvarId! (mkAppN (Lean.mkConst mainHeaders[i]!.declName) sectionVars) def insertReplacementForLetRecs (r : Replacement) (letRecClosures : List LetRecClosure) : Replacement := letRecClosures.foldl (init := r) fun r c => r.insert c.toLift.fvarId c.closed def Replacement.apply (r : Replacement) (e : Expr) : Expr := e.replace fun e => match e with | .fvar fvarId => match r.find? fvarId with | some c => some c | _ => none | _ => none def pushMain (preDefs : Array PreDefinition) (sectionVars : Array Expr) (mainHeaders : Array DefViewElabHeader) (mainVals : Array Expr) : TermElabM (Array PreDefinition) := mainHeaders.size.foldM (init := preDefs) fun i preDefs => do let header := mainHeaders[i]! let value ← mkLambdaFVars sectionVars mainVals[i]! let type ← mkForallFVars sectionVars header.type return preDefs.push { ref := getDeclarationSelectionRef header.ref kind := header.kind declName := header.declName levelParams := [], -- we set it later modifiers := header.modifiers type, value } def pushLetRecs (preDefs : Array PreDefinition) (letRecClosures : List LetRecClosure) (kind : DefKind) (modifiers : Modifiers) : MetaM (Array PreDefinition) := letRecClosures.foldlM (init := preDefs) fun preDefs c => do let type := Closure.mkForall c.localDecls c.toLift.type let value := Closure.mkLambda c.localDecls c.toLift.val -- Convert any proof let recs inside a `def` to `theorem` kind let kind ← if kind.isDefOrAbbrevOrOpaque then withLCtx c.toLift.lctx c.toLift.localInstances do return if (← inferType c.toLift.type).isProp then .theorem else kind else pure kind return preDefs.push { ref := c.ref declName := c.toLift.declName levelParams := [] -- we set it later modifiers := { modifiers with attrs := c.toLift.attrs } kind, type, value } def getKindForLetRecs (mainHeaders : Array DefViewElabHeader) : DefKind := if mainHeaders.any fun h => h.kind.isTheorem then DefKind.«theorem» else DefKind.«def» def getModifiersForLetRecs (mainHeaders : Array DefViewElabHeader) : Modifiers := { isNoncomputable := mainHeaders.any fun h => h.modifiers.isNoncomputable recKind := if mainHeaders.any fun h => h.modifiers.isPartial then RecKind.partial else RecKind.default isUnsafe := mainHeaders.any fun h => h.modifiers.isUnsafe } /-- - `sectionVars`: The section variables used in the `mutual` block. - `mainHeaders`: The elaborated header of the top-level definitions being defined by the mutual block. - `mainFVars`: The auxiliary variables used to represent the top-level definitions being defined by the mutual block. - `mainVals`: The elaborated value for the top-level definitions - `letRecsToLift`: The let-rec's definitions that need to be lifted -/ def main (sectionVars : Array Expr) (mainHeaders : Array DefViewElabHeader) (mainFVars : Array Expr) (mainVals : Array Expr) (letRecsToLift : List LetRecToLift) : TermElabM (Array PreDefinition) := do -- Store in recFVarIds the fvarId of every function being defined by the mutual block. let letRecsToLift := letRecsToLift.toArray let mainFVarIds := mainFVars.map Expr.fvarId! let recFVarIds := (letRecsToLift.map fun toLift => toLift.fvarId) ++ mainFVarIds resetZetaFVarIds withTrackingZeta do -- By checking `toLift.type` and `toLift.val` we populate `zetaFVarIds`. See comments at `src/Lean/Meta/Closure.lean`. let letRecsToLift ← letRecsToLift.mapM fun toLift => withLCtx toLift.lctx toLift.localInstances do Meta.check toLift.type Meta.check toLift.val return { toLift with val := (← instantiateMVars toLift.val), type := (← instantiateMVars toLift.type) } let letRecClosures ← mkLetRecClosures sectionVars mainFVarIds recFVarIds letRecsToLift -- mkLetRecClosures assign metavariables that were placeholders for the lifted declarations. let mainVals ← mainVals.mapM (instantiateMVars ·) let mainHeaders ← mainHeaders.mapM instantiateMVarsAtHeader let letRecClosures ← letRecClosures.mapM fun closure => do pure { closure with toLift := (← instantiateMVarsAtLetRecToLift closure.toLift) } -- Replace fvarIds for functions being defined with closed terms let r := insertReplacementForMainFns {} sectionVars mainHeaders mainFVars let r := insertReplacementForLetRecs r letRecClosures let mainVals := mainVals.map r.apply let mainHeaders := mainHeaders.map fun h => { h with type := r.apply h.type } let letRecClosures := letRecClosures.map fun c => { c with toLift := { c.toLift with type := r.apply c.toLift.type, val := r.apply c.toLift.val } } let letRecKind := getKindForLetRecs mainHeaders let letRecMods := getModifiersForLetRecs mainHeaders pushMain (← pushLetRecs #[] letRecClosures letRecKind letRecMods) sectionVars mainHeaders mainVals end MutualClosure private def getAllUserLevelNames (headers : Array DefViewElabHeader) : List Name := if h : 0 < headers.size then -- Recall that all top-level functions must have the same levels. See `check` method above (headers.get ⟨0, h⟩).levelNames else [] /-- Eagerly convert universe metavariables occurring in theorem headers to universe parameters. -/ private def levelMVarToParamHeaders (views : Array DefView) (headers : Array DefViewElabHeader) : TermElabM (Array DefViewElabHeader) := do let rec process : StateRefT Nat TermElabM (Array DefViewElabHeader) := do let mut newHeaders := #[] for view in views, header in headers do if view.kind.isTheorem then newHeaders ← withLevelNames header.levelNames do return newHeaders.push { header with type := (← levelMVarToParam header.type), levelNames := (← getLevelNames) } else newHeaders := newHeaders.push header return newHeaders let newHeaders ← (process).run' 1 newHeaders.mapM fun header => return { header with type := (← instantiateMVars header.type) } partial def checkForHiddenUnivLevels (allUserLevelNames : List Name) (preDefs : Array PreDefinition) : TermElabM Unit := unless (← MonadLog.hasErrors) do -- We do not report this kind of error if the declaration already contains errors let mut sTypes : CollectLevelParams.State := {} let mut sValues : CollectLevelParams.State := {} for preDef in preDefs do sTypes := collectLevelParams sTypes preDef.type sValues := collectLevelParams sValues preDef.value if sValues.params.all fun u => sTypes.params.contains u || allUserLevelNames.contains u then -- If all universe level occurring in values also occur in types or explicitly provided universes, then everything is fine -- and we just return return () let checkPreDef (preDef : PreDefinition) : TermElabM Unit := -- Otherwise, we try to produce an error message containing the expression with the offending universe let rec visitLevel (u : Level) : ReaderT Expr TermElabM Unit := do match u with | .succ u => visitLevel u | .imax u v | .max u v => visitLevel u; visitLevel v | .param n => unless sTypes.visitedLevel.contains u || allUserLevelNames.contains n do let parent ← withOptions (fun o => pp.universes.set o true) do addMessageContext m!"{indentExpr (← read)}" let body ← withOptions (fun o => pp.letVarTypes.setIfNotSet (pp.funBinderTypes.setIfNotSet o true) true) do addMessageContext m!"{indentExpr preDef.value}" throwError "invalid occurrence of universe level '{u}' at '{preDef.declName}', it does not occur at the declaration type, nor it is explicit universe level provided by the user, occurring at expression{parent}\nat declaration body{body}" | _ => pure () let rec visit (e : Expr) : ReaderT Expr (MonadCacheT ExprStructEq Unit TermElabM) Unit := do checkCache { val := e : ExprStructEq } fun _ => do match e with | .forallE n d b c | .lam n d b c => visit d e; withLocalDecl n c d fun x => visit (b.instantiate1 x) e | .letE n t v b _ => visit t e; visit v e; withLetDecl n t v fun x => visit (b.instantiate1 x) e | .app .. => e.withApp fun f args => do visit f e; args.forM fun arg => visit arg e | .mdata _ b => visit b e | .proj _ _ b => visit b e | .sort u => visitLevel u (← read) | .const _ us => us.forM (visitLevel · (← read)) | _ => pure () visit preDef.value preDef.value |>.run {} for preDef in preDefs do checkPreDef preDef def elabMutualDef (vars : Array Expr) (views : Array DefView) (hints : TerminationHints) : TermElabM Unit := if isExample views then withoutModifyingEnv do -- save correct environment in info tree withSaveInfoContext do go else go where go := do let scopeLevelNames ← getLevelNames let headers ← elabHeaders views let headers ← levelMVarToParamHeaders views headers let allUserLevelNames := getAllUserLevelNames headers withFunLocalDecls headers fun funFVars => do for view in views, funFVar in funFVars do addLocalVarInfo view.declId funFVar let values ← try let values ← elabFunValues headers Term.synthesizeSyntheticMVarsNoPostponing values.mapM (instantiateMVars ·) catch ex => logException ex headers.mapM fun header => mkSorry header.type (synthetic := true) let headers ← headers.mapM instantiateMVarsAtHeader let letRecsToLift ← getLetRecsToLift let letRecsToLift ← letRecsToLift.mapM instantiateMVarsAtLetRecToLift checkLetRecsToLiftTypes funFVars letRecsToLift withUsed vars headers values letRecsToLift fun vars => do let preDefs ← MutualClosure.main vars headers funFVars values letRecsToLift for preDef in preDefs do trace[Elab.definition] "{preDef.declName} : {preDef.type} :=\n{preDef.value}" let preDefs ← withLevelNames allUserLevelNames <| levelMVarToParamPreDecls preDefs let preDefs ← instantiateMVarsAtPreDecls preDefs let preDefs ← fixLevelParams preDefs scopeLevelNames allUserLevelNames for preDef in preDefs do trace[Elab.definition] "after eraseAuxDiscr, {preDef.declName} : {preDef.type} :=\n{preDef.value}" checkForHiddenUnivLevels allUserLevelNames preDefs addPreDefinitions preDefs hints processDeriving headers processDeriving (headers : Array DefViewElabHeader) := do for header in headers, view in views do if let some classNamesStx := view.deriving? then for classNameStx in classNamesStx do let className ← resolveGlobalConstNoOverload classNameStx withRef classNameStx do unless (← processDefDeriving className header.declName) do throwError "failed to synthesize instance '{className}' for '{header.declName}'" end Term namespace Command def elabMutualDef (ds : Array Syntax) (hints : TerminationHints) : CommandElabM Unit := do let views ← ds.mapM fun d => do let modifiers ← elabModifiers d[0] if ds.size > 1 && modifiers.isNonrec then throwErrorAt d "invalid use of 'nonrec' modifier in 'mutual' block" mkDefView modifiers d[1] runTermElabM fun vars => Term.elabMutualDef vars views hints end Command end Lean.Elab
162f83801f68824f8be8610e4f05fd26119897de
94637389e03c919023691dcd05bd4411b1034aa5
/src/inClassNotes/type_library/list_test.lean
14108d908855dee2769679ca4fea63eff21840f7
[]
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
10,171
lean
import .list namespace hidden -- list is polymorphic #check list nat -- nat lives in Type #check list bool -- bool lives in Type #check list Type -- Type lives in Type 1 #check list (Type 1) -- Type 1 lives in Type 2 /- Some lists of nats -/ #eval list.nil -- can't infer α #eval @list.nil nat -- can't infer α #eval (list.nil : list nat) /- Top-down (outside-in) refinement -/ def lnat0 : list nat := list.nil def lnat1 : list nat := list.cons (_) (_) def lstr1 : list string := list.cons (_) (list.cons (_) (list.nil) ) /- cons / \ "hi" cons / \ "ho" ... -/ -- FUNCTIONS def head { α : Type } : list α → option α | list.nil := none | (list.cons h t) := some h def tail { α : Type } : list α → option (list α) | list.nil := none | (list.cons h t) := some t -- recursive definition of length (by cases) def length {α : Type} : list α → nat | list.nil := 0 | (list.cons h t) := (_) + 1 -- length in context def append {α : Type} : list α → list α → list α | list.nil m := _ | (list.cons h t) m := _ def pure {α : Type} : α → list α | a := list.cons a list.nil def reverse {α : Type} : list α → list α | list.nil := list.nil | (list.cons h t) := _ #eval reverse (list.cons 1 (list.cons 2 list.nil)) end hidden /- From here on, we use Lean's identical definition of the list type, but we gain the benefit of additional notation. -/ /- NOTATION -/ #eval list.cons "hi" (list.cons "ho" list.nil) #eval ["hi", "ho"] #eval list.cons "hi" ["ho"] #eval "hi"::["ho"] #eval let s : string := let a := ["hi","ho"] in (match a with | list.nil := "oops" | (h::t) := h end) in s ++ "!" -- more examples #eval [1,2,3,4,5] #eval 1::[2,3,4,5] #eval 1::2::3::4::5::list.nil def head { α : Type } : list α → option α | list.nil := none | (h::t) := some h def tail { α : Type } : list α → option (list α) | list.nil := none | (h::t) := some t -- recursive definition of length (by cases) def length {α : Type} : list α → nat | list.nil := 0 | (h::t) := (_) + 1 -- length in context #eval list.append ["Hi","Ho"] ["!"] #eval ["Hi","Ho"] ++ ["!"] #check @pure list #eval (pure 5 : list nat) #eval (pure 5 : option nat) -- whoa (later) def reverse {α : Type} : list α → list α | list.nil := list.nil | (h::t) := _ -- use nice notation here universe u /- HIGHER ORDER FUNCTIONS -/ /- Suppose we want to map a list of strings to a list of bools, where each bool is tt if the length of the corresponding string is even, and false otherwise. -/ def strlist := ["Hello", "There", "Lean"] def map_ev_string_bool : list string → list bool | list.nil := list.nil | (h::t) := (h.length%2=0)::_ def map_odd_string_bool : list string → list bool | list.nil := list.nil | (h::t) := (h.length%2=1)::_ def map_string_bang_string : list string → list string | list.nil := list.nil | (h::t) := (h++"!")::(map_string_bang_string t) #eval map_string_bang_string strlist /- Dimensions of variation? -- argument list element type, α -- result list element type, β -- function used to transform α → β -/ def map_list {α β : Type u} : (α → β) → list α → list β | f list.nil := list.nil | f (h::t) := (f h)::(map_list f t) #eval map_list (λ (s : string), s.length) (strlist) #eval map_list (λ (s : string), (s.length%2=0:bool)) (strlist) def exclafy : list string → list string := map_list (λ (s : string), s++"!") -- arg #eval exclafy ["Whoa","That","Is","COOL"] /- Define reduce, or fold, over a list. Let's start with an example. Suppose we're given a list of strings and we want to know if they are all of even length. What we need is a function, allEvenLength : list string → bool, that returns tt iff all strings in the list have even length. Let's do an informal case analysis: First we consider the case where the given list of strings, l, is not empty. In this case it has the form (h::t), with (h : string) and (t : list string). And in this case, every string in the list will have even length iff (1) h is of even length *AND* every string in the tail, t, of l, also has even length. Now consider the case where l is nil. What Boolean value do we return? One might guess false ... incorrectly. Suppose our function returned false (ff) for the empty list. Consider a case where l = ["Hi"]. That is, the list, l = (list.cons "Hi" list.nil). The list is non-empty, so the first rule applies: return the AND of two Boolean values: one for "Hi" and one for the rest of the list. For "Hi" we will get true, as "Hi" has even length, so our result will have to be (tt ∧ X), where X is the result for the rest of the list. But here the rest of the list is empty. So what *must* R, the result for the empty list, be for the function to return the right result, tt (as all strings in the list are even length)? Clearly the answer must be true (tt). What would happen if it were ff? So now we have our algorithm! -/ -- first a predicate function def isEvenStr (s : string) : bool := (s.length % 2 = 0) def allEvenStr : list string → bool | list.nil := tt | (h::t) := band (isEvenStr h) (allEvenStr t) #eval allEvenStr [] #eval allEvenStr ["Hi"] #eval allEvenStr ["Hi!"] #eval allEvenStr ["Hi","There!"] #eval allEvenStr ["Hi","Ho!"] /- Now suppose we want to know if there is *at least* one string of even length in any given list of strings. Again we do a case analysis. There is at least one even-length string in a non-empty list, l = h::t, iff h is of even length OR there is at least one even-lenght string in the rest of the list. Now suppose t is the empty string. What result must be returned for the function to work. Consider the case where l = ["Hi!"] = (cons "Hi" nil). The correct answer here is (ff ∨ X), with the ff because "Hi!" is not of even length, and X is the answer for the empty list. To get the correct answer, it must be that X = ff. So now again we have our algorithm. -/ /- The key idea both here and in the preceding example is that the answer for the empty list must leave the result for the preceding elements unchanged. The result must be the *identity element* for the Boolean operator being used to combine the values for the head and rest of the list. The identity element for Boolean and is tt, and for Boolean or it is ff. ∀ (b : bool), b ∧ tt = b ∀ (b : bool), b ∨ ff = b We can see these propositions are true by case analysis. Case 1: b = tt. In this case b ∧ tt = tt and b = tt so b ∧ t = b. Exercise: Finish up. -/ def someEvenStr : list string → bool | list.nil := ff | (h::t) := bor (isEvenStr h) (someEvenStr t) #eval someEvenStr [] #eval someEvenStr ["Hi"] #eval someEvenStr ["Hi!"] #eval someEvenStr ["Hello","Lean"] #eval someEvenStr ["Hello","Lean!"] /- Now a key observation: Our two functions are very similar, varying in only a few dimensions. Let's factor dimensions of variation into parameter to generalize our definition. First, we want to be able to operte on lists of values of any type, not just strings. Let call the list element type α. Second, in general, we want to reduce a list (l : list α) to a value of some other type, let's call it β, just as in our examples we reduced lists of values of type α = string to a final result of type β = bool. Third, we need a function to compute the answer for a non-empty list (h::t) where (1) (h : α), (2) the result for the rest of the list is of type β, and (3) the final combined result is of type β. The type of this reducing function is thus α → β → β. Finally, we need a result value for the empty list. This value obviously has to be of type β. Those are our parameters! Given: { α : Type u} { β : Type u} ( f : α → β → β ) ( id : β) ( l : list α) Compute result : β -/ -- By case analysis on the list l def fold { α : Type u} { β : Type u} : ( α → β → β ) → β → list α → β | f id list.nil := id | f id (h::t) := f h (fold f id t) -- allEven def allStrCombine : string → bool → bool | s b := band (isEvenStr s) b def allEvenStr' (l : list string) : bool := fold allStrCombine tt l def someStrCombine : string → bool → bool | s b := bor (isEvenStr s) b def someEvenStr' (l : list string) : bool := fold someStrCombine ff l #eval allEvenStr' [] #eval allEvenStr' ["Hi"] #eval allEvenStr' ["Hi!"] #eval allEvenStr' ["Hi","There!"] #eval allEvenStr' ["Hi","Ho!"]#eval someEvenStr [] #eval someEvenStr' ["Hi"] #eval someEvenStr' ["Hi!"] #eval someEvenStr' ["Hello","Lean"] #eval someEvenStr' ["Hello","Lean!"] #eval fold nat.add 0 [10,9,8,7,6,5,4,3,2,1] #eval fold nat.mul 1 [10,9,8,7,6,5,4,3,2,1] #eval fold string.append "" ["Hello, ", "Lean. ", "We ", "love ", "you!"] /- Given a predicate function on the type of element in a list, return the sublist of elements for which predicate is true. Define filter by case analysis with one case a base case and the other case using "structural recursion" on list argument. An opportunity to introduces if/then/else expression in Lean. -/ def filter' {α : Type u} : (α → bool) → list α → list α | f list.nil := list.nil | f (h::t) := if (f h) then h::(filter' f t) else (filter' f t) /- Take opportunity to introduce let bindings. Binds name to result of evaluation, then evaluates expr in context of that additional binding. -/ def filter {α : Type u} : (α → bool) → list α → list α | f list.nil := list.nil | f (h::t) := let restOfResult := (filter f t) in if (f h) then h::restOfResult else restOfResult def isEven (n : nat) : bool := n%2 = 0 #eval filter isEven [] #eval filter isEven [0,1,2,3,5,6,7,9,10] /- Note: the body of a let can use another let. That is, let bindings can be chained. let x := 1 in let y := 2+3 in let z := 3*4 in x + y + z To what value does this expression reduce? -/
c1df04539dee98818c06a7532091a80d08dbaad8
4727251e0cd73359b15b664c3170e5d754078599
/src/topology/compact_open.lean
f050c6a023060648425b3044f0d32c4107772bb5
[ "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
17,199
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 import topology.maps /-! # 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. * `continuous_map.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} @[simp] lemma gen_empty (u : set β) : compact_open.gen (∅ : set α) u = set.univ := set.ext (λ f, iff_true_intro ((congr_arg (⊆ u) (image_empty f)).mpr u.empty_subset)) @[simp] lemma gen_univ (s : set α) : compact_open.gen s (set.univ : set β) = set.univ := set.ext (λ f, iff_true_intro (f '' s).subset_univ) @[simp] lemma gen_inter (s : set α) (u v : set β) : compact_open.gen s (u ∩ v) = compact_open.gen s u ∩ compact_open.gen s v := set.ext (λ f, subset_inter_iff) @[simp] lemma gen_union (s t : set α) (u : set β) : compact_open.gen (s ∪ t) u = compact_open.gen s u ∩ compact_open.gen t u := set.ext (λ f, (iff_of_eq (congr_arg (⊆ u) (image_union f s t))).trans union_subset_iff) -- 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} protected 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 continuous_map.is_open_gen hs (hu.preimage g.2) end functorial section ev variables {α β} /-- The evaluation map `C(α, β) × α → β` is continuous if `α` is locally compact. See also `continuous_map.continuous_eval` -/ lemma continuous_eval' [locally_compact_space α] : continuous (λ p : C(α, β) × α, p.1 p.2) := 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 (λ p : C(α, β) × α, p.1 p.2) ⁻¹' n ∈ 𝓝 (f, x), from let w := compact_open.gen s v ×ˢ u in have w ⊆ (λ p : C(α, β) × α, p.1 p.2) ⁻¹' 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 (continuous_map.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⟩ /-- See also `continuous_map.continuous_eval_const` -/ lemma continuous_eval_const' [locally_compact_space α] (a : α) : continuous (λ f : C(α, β), f a) := continuous_eval'.comp (continuous_id.prod_mk continuous_const) /-- See also `continuous_map.continuous_coe` -/ lemma continuous_coe' [locally_compact_space α] : @continuous (C(α, β)) (α → β) _ _ coe_fn := continuous_pi continuous_eval_const' instance [t2_space β] : t2_space C(α, β) := ⟨ begin intros f₁ f₂ h, obtain ⟨x, hx⟩ := not_forall.mp (mt (fun_like.ext f₁ f₂) h), obtain ⟨u, v, hu, hv, hxu, hxv, huv⟩ := t2_separation hx, refine ⟨compact_open.gen {x} u, compact_open.gen {x} v, continuous_map.is_open_gen is_compact_singleton hu, continuous_map.is_open_gen is_compact_singleton hv, _, _, _⟩, { rwa [compact_open.gen, mem_set_of_eq, image_singleton, singleton_subset_iff] }, { rwa [compact_open.gen, mem_set_of_eq, image_singleton, singleton_subset_iff] }, { rw [←continuous_map.gen_inter, huv], refine subset_empty_iff.mp (λ f, _), rw [compact_open.gen, mem_set_of_eq, image_singleton, singleton_subset_iff], exact id }, 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_infi₂ _, 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_Union₂, 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_eval_const' (⟨x, hxs₁⟩ : s₁)).continuous_at.tendsto.comp (hf s₁ hs₁), have h₂ := (continuous_eval_const' (⟨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(α, β × α) := ⟨prod.mk b, continuous_const.prod_mk continuous_id⟩ variables {α β} lemma image_coev {y : β} (s : set α) : (coev α β y) '' s = ({y} : set β) ×ˢ 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_eval'; 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)) := continuous_eval'.comp $ f.continuous.prod_map continuous_id /-- 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_eval' (continuous.prod_map continuous_eval' continuous_id); 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 := const α, inv_fun := λ f, f default, left_inv := λ a, rfl, right_inv := λ f, by { ext, rw unique.eq_default a, refl }, continuous_to_fun := continuous_const', continuous_inv_fun := continuous_eval'.comp (continuous_id.prod_mk 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 section quotient_map variables {X₀ X Y Z : Type*} [topological_space X₀] [topological_space X] [topological_space Y] [topological_space Z] [locally_compact_space Y] {f : X₀ → X} lemma quotient_map.continuous_lift_prod_left (hf : quotient_map f) {g : X × Y → Z} (hg : continuous (λ p : X₀ × Y, g (f p.1, p.2))) : continuous g := begin let Gf : C(X₀, C(Y, Z)) := continuous_map.curry ⟨_, hg⟩, have h : ∀ x : X, continuous (λ y, g (x, y)), { intros x, obtain ⟨x₀, rfl⟩ := hf.surjective x, exact (Gf x₀).continuous }, let G : X → C(Y, Z) := λ x, ⟨_, h x⟩, have : continuous G, { rw hf.continuous_iff, exact Gf.continuous }, convert continuous_map.continuous_uncurry_of_continuous ⟨G, this⟩, ext x, cases x, refl, end lemma quotient_map.continuous_lift_prod_right (hf : quotient_map f) {g : Y × X → Z} (hg : continuous (λ p : Y × X₀, g (p.1, f p.2))) : continuous g := begin have : continuous (λ p : X₀ × Y, g ((prod.swap p).1, f (prod.swap p).2)), { exact hg.comp continuous_swap }, have : continuous (λ p : X₀ × Y, (g ∘ prod.swap) (f p.1, p.2)) := this, convert (hf.continuous_lift_prod_left this).comp continuous_swap, ext x, simp, end end quotient_map
40774149d007f6e75002e3676dae5381284fb12d
8cb37a089cdb4af3af9d8bf1002b417e407a8e9e
/library/init/data/string/basic.lean
0c401eee2615ac57423f5c197ec81b864a8d57ef
[ "Apache-2.0" ]
permissive
kbuzzard/lean
ae3c3db4bb462d750dbf7419b28bafb3ec983ef7
ed1788fd674bb8991acffc8fca585ec746711928
refs/heads/master
1,620,983,366,617
1,618,937,600,000
1,618,937,600,000
359,886,396
1
0
Apache-2.0
1,618,936,987,000
1,618,936,987,000
null
UTF-8
Lean
false
false
8,671
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.data.list.basic import init.data.char.basic /- In the VM, strings are implemented using a dynamic array and UTF-8 encoding. TODO: we currently cannot mark string_imp as private because we need to bind string_imp.mk and string_imp.cases_on in the VM. -/ structure string_imp := (data : list char) def string := string_imp def list.as_string (s : list char) : string := ⟨s⟩ namespace string instance : has_lt string := ⟨λ s₁ s₂, s₁.data < s₂.data⟩ /- Remark: this function has a VM builtin efficient implementation. -/ instance has_decidable_lt (s₁ s₂ : string) : decidable (s₁ < s₂) := list.has_decidable_lt s₁.data s₂.data instance has_decidable_eq : decidable_eq string := λ ⟨x⟩ ⟨y⟩, match list.has_dec_eq x y with | is_true p := is_true (congr_arg string_imp.mk p) | is_false p := is_false (λ q, p (string_imp.mk.inj q)) end def empty : string := ⟨[]⟩ def length : string → nat | ⟨s⟩ := s.length /- The internal implementation uses dynamic arrays and will perform destructive updates if the string is not shared. -/ def push : string → char → string | ⟨s⟩ c := ⟨s ++ [c]⟩ /- The internal implementation uses dynamic arrays and will perform destructive updates if the string is not shared. -/ def append : string → string → string | ⟨a⟩ ⟨b⟩ := ⟨a ++ b⟩ /- O(n) in the VM, where n is the length of the string -/ def to_list : string → list char | ⟨s⟩ := s def fold {α} (a : α) (f : α → char → α) (s : string) : α := s.to_list.foldl f a /- In the VM, the string iterator is implemented as a pointer to the string being iterated + index. TODO: we currently cannot mark interator_imp as private because we need to bind string_imp.mk and string_imp.cases_on in the VM. -/ structure iterator_imp := (fst : list char) (snd : list char) def iterator := iterator_imp def mk_iterator : string → iterator | ⟨s⟩ := ⟨[], s⟩ namespace iterator def curr : iterator → char | ⟨p, c::n⟩ := c | _ := default char /- In the VM, `set_curr` is constant time if the string being iterated is not shared and linear time if it is. -/ def set_curr : iterator → char → iterator | ⟨p, c::n⟩ c' := ⟨p, c'::n⟩ | it c' := it def next : iterator → iterator | ⟨p, c::n⟩ := ⟨c::p, n⟩ | ⟨p, []⟩ := ⟨p, []⟩ def prev : iterator → iterator | ⟨c::p, n⟩ := ⟨p, c::n⟩ | ⟨[], n⟩ := ⟨[], n⟩ def has_next : iterator → bool | ⟨p, []⟩ := ff | _ := tt def has_prev : iterator → bool | ⟨[], n⟩ := ff | _ := tt def insert : iterator → string → iterator | ⟨p, n⟩ ⟨s⟩ := ⟨p, s++n⟩ def remove : iterator → nat → iterator | ⟨p, n⟩ m := ⟨p, n.drop m⟩ /- In the VM, `to_string` is a constant time operation. -/ def to_string : iterator → string | ⟨p, n⟩ := ⟨p.reverse ++ n⟩ def to_end : iterator → iterator | ⟨p, n⟩ := ⟨n.reverse ++ p, []⟩ def next_to_string : iterator → string | ⟨p, n⟩ := ⟨n⟩ def prev_to_string : iterator → string | ⟨p, n⟩ := ⟨p.reverse⟩ protected def extract_core : list char → list char → option (list char) | [] cs := none | (c::cs₁) cs₂ := if cs₁ = cs₂ then some [c] else match extract_core cs₁ cs₂ with | none := none | some r := some (c::r) end def extract : iterator → iterator → option string | ⟨p₁, n₁⟩ ⟨p₂, n₂⟩ := if p₁.reverse ++ n₁ ≠ p₂.reverse ++ n₂ then none else if n₁ = n₂ then some "" else match iterator.extract_core n₁ n₂ with | none := none | some r := some ⟨r⟩ end end iterator end string /- The following definitions do not have builtin support in the VM -/ instance : inhabited string := ⟨string.empty⟩ instance : has_sizeof string := ⟨string.length⟩ instance : has_append string := ⟨string.append⟩ namespace string def str : string → char → string := push def is_empty (s : string) : bool := to_bool (s.length = 0) def front (s : string) : char := s.mk_iterator.curr def back (s : string) : char := s.mk_iterator.to_end.prev.curr def join (l : list string) : string := l.foldl (λ r s, r ++ s) "" def singleton (c : char) : string := empty.push c def intercalate (s : string) (ss : list string) : string := (list.intercalate s.to_list (ss.map to_list)).as_string namespace iterator def nextn : iterator → nat → iterator | it 0 := it | it (i+1) := nextn it.next i def prevn : iterator → nat → iterator | it 0 := it | it (i+1) := prevn it.prev i end iterator def pop_back (s : string) : string := s.mk_iterator.to_end.prev.prev_to_string def popn_back (s : string) (n : nat) : string := (s.mk_iterator.to_end.prevn n).prev_to_string def backn (s : string) (n : nat) : string := (s.mk_iterator.to_end.prevn n).next_to_string end string protected def char.to_string (c : char) : string := string.singleton c private def to_nat_core : string.iterator → nat → nat → nat | it 0 r := r | it (i+1) r := let c := it.curr in let r := r*10 + c.to_nat - '0'.to_nat in to_nat_core it.next i r def string.to_nat (s : string) : nat := to_nat_core s.mk_iterator s.length 0 namespace string private lemma nil_ne_append_singleton : ∀ (c : char) (l : list char), [] ≠ l ++ [c] | c [] := λ h, list.no_confusion h | c (d::l) := λ h, list.no_confusion h lemma empty_ne_str : ∀ (c : char) (s : string), empty ≠ str s c | c ⟨l⟩ := λ h : string_imp.mk [] = string_imp.mk (l ++ [c]), string_imp.no_confusion h $ λ h, nil_ne_append_singleton _ _ h lemma str_ne_empty (c : char) (s : string) : str s c ≠ empty := (empty_ne_str c s).symm private lemma str_ne_str_left_aux : ∀ {c₁ c₂ : char} (l₁ l₂ : list char), c₁ ≠ c₂ → l₁ ++ [c₁] ≠ l₂ ++ [c₂] | c₁ c₂ [] [] h₁ h₂ := list.no_confusion h₂ (λ h _, absurd h h₁) | c₁ c₂ (d₁::l₁) [] h₁ h₂ := have d₁ :: (l₁ ++ [c₁]) = [c₂], from h₂, have l₁ ++ [c₁] = [], from list.no_confusion this (λ _ h, h), absurd this.symm (nil_ne_append_singleton _ _) | c₁ c₂ [] (d₂::l₂) h₁ h₂ := have [c₁] = d₂ :: (l₂ ++ [c₂]), from h₂, have [] = l₂ ++ [c₂], from list.no_confusion this (λ _ h, h), absurd this (nil_ne_append_singleton _ _) | c₁ c₂ (d₁::l₁) (d₂::l₂) h₁ h₂ := have d₁ :: (l₁ ++ [c₁]) = d₂ :: (l₂ ++ [c₂]), from h₂, have l₁ ++ [c₁] = l₂ ++ [c₂], from list.no_confusion this (λ _ h, h), absurd this (str_ne_str_left_aux l₁ l₂ h₁) lemma str_ne_str_left : ∀ {c₁ c₂ : char} (s₁ s₂ : string), c₁ ≠ c₂ → str s₁ c₁ ≠ str s₂ c₂ | c₁ c₂ (string_imp.mk l₁) (string_imp.mk l₂) h₁ h₂ := have l₁ ++ [c₁] = l₂ ++ [c₂], from string_imp.no_confusion h₂ id, absurd this (str_ne_str_left_aux l₁ l₂ h₁) private lemma str_ne_str_right_aux : ∀ (c₁ c₂ : char) {l₁ l₂ : list char}, l₁ ≠ l₂ → l₁ ++ [c₁] ≠ l₂ ++ [c₂] | c₁ c₂ [] [] h₁ h₂ := absurd rfl h₁ | c₁ c₂ (d₁::l₁) [] h₁ h₂ := have d₁ :: (l₁ ++ [c₁]) = [c₂], from h₂, have l₁ ++ [c₁] = [], from list.no_confusion this (λ _ h, h), absurd this.symm (nil_ne_append_singleton _ _) | c₁ c₂ [] (d₂::l₂) h₁ h₂ := have [c₁] = d₂ :: (l₂ ++ [c₂]), from h₂, have [] = l₂ ++ [c₂], from list.no_confusion this (λ _ h, h), absurd this (nil_ne_append_singleton _ _) | c₁ c₂ (d₁::l₁) (d₂::l₂) h₁ h₂ := have aux₁ : d₁ :: (l₁ ++ [c₁]) = d₂ :: (l₂ ++ [c₂]), from h₂, have d₁ = d₂, from list.no_confusion aux₁ (λ h _, h), have aux₂ : l₁ ≠ l₂, from λ h, have d₁ :: l₁ = d₂ :: l₂, from eq.subst h (eq.subst this rfl), absurd this h₁, have l₁ ++ [c₁] = l₂ ++ [c₂], from list.no_confusion aux₁ (λ _ h, h), absurd this (str_ne_str_right_aux c₁ c₂ aux₂) lemma str_ne_str_right : ∀ (c₁ c₂ : char) {s₁ s₂ : string}, s₁ ≠ s₂ → str s₁ c₁ ≠ str s₂ c₂ | c₁ c₂ (string_imp.mk l₁) (string_imp.mk l₂) h₁ h₂ := have aux : l₁ ≠ l₂, from λ h, have string_imp.mk l₁ = string_imp.mk l₂, from eq.subst h rfl, absurd this h₁, have l₁ ++ [c₁] = l₂ ++ [c₂], from string_imp.no_confusion h₂ id, absurd this (str_ne_str_right_aux c₁ c₂ aux) end string
16a773266c83f20285cb1620645f25ed99a98f0b
ad0c7d243dc1bd563419e2767ed42fb323d7beea
/tactic/norm_num.lean
c44ae947ccb4de210cb797baef7ae7b090481792
[ "Apache-2.0" ]
permissive
sebzim4500/mathlib
e0b5a63b1655f910dee30badf09bd7e191d3cf30
6997cafbd3a7325af5cb318561768c316ceb7757
refs/heads/master
1,585,549,958,618
1,538,221,723,000
1,538,221,723,000
150,869,076
0
0
Apache-2.0
1,538,229,323,000
1,538,229,323,000
null
UTF-8
Lean
false
false
18,452
lean
/- Copyright (c) 2017 Simon Hudon All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Mario Carneiro Evaluating arithmetic expressions including *, +, -, ^, ≤ -/ import algebra.group_power data.rat tactic.interactive data.nat.prime universes u v w namespace expr protected meta def to_pos_rat : expr → option ℚ | `(%%e₁ / %%e₂) := do m ← e₁.to_nat, n ← e₂.to_nat, some (rat.mk m n) | e := do n ← e.to_nat, return (rat.of_int n) protected meta def to_rat : expr → option ℚ | `(has_neg.neg %%e) := do q ← e.to_pos_rat, some (-q) | e := e.to_pos_rat protected meta def of_rat (α : expr) : ℚ → tactic expr | ⟨(n:ℕ), d, h, c⟩ := do e₁ ← expr.of_nat α n, if d = 1 then return e₁ else do e₂ ← expr.of_nat α d, tactic.mk_app ``has_div.div [e₁, e₂] | ⟨-[1+n], d, h, c⟩ := do e₁ ← expr.of_nat α (n+1), e ← (if d = 1 then return e₁ else do e₂ ← expr.of_nat α d, tactic.mk_app ``has_div.div [e₁, e₂]), tactic.mk_app ``has_neg.neg [e] end expr namespace tactic meta def refl_conv (e : expr) : tactic (expr × expr) := do p ← mk_eq_refl e, return (e, p) meta def trans_conv (t₁ t₂ : expr → tactic (expr × expr)) (e : expr) : tactic (expr × expr) := (do (e₁, p₁) ← t₁ e, (do (e₂, p₂) ← t₂ e₁, p ← mk_eq_trans p₁ p₂, return (e₂, p)) <|> return (e₁, p₁)) <|> t₂ e end tactic open tactic namespace norm_num variable {α : Type u} lemma subst_into_neg {α} [has_neg α] (a ta t : α) (pra : a = ta) (prt : -ta = t) : -a = t := by simp [pra, prt] theorem bit0_zero [add_group α] : bit0 (0 : α) = 0 := add_zero _ theorem bit1_zero [add_group α] [has_one α] : bit1 (0 : α) = 1 := by rw [bit1, bit0_zero, zero_add] lemma pow_bit0_helper [monoid α] (a t : α) (b : ℕ) (h : a ^ b = t) : a ^ bit0 b = t * t := by simp [pow_bit0, h] lemma pow_bit1_helper [monoid α] (a t : α) (b : ℕ) (h : a ^ b = t) : a ^ bit1 b = t * t * a := by simp [pow_bit1, h] lemma lt_add_of_pos_helper [ordered_cancel_comm_monoid α] (a b c : α) (h : a + b = c) (h₂ : 0 < b) : a < c := h ▸ (lt_add_iff_pos_right _).2 h₂ lemma nat_div_helper (a b q r : ℕ) (h : r + q * b = a) (h₂ : r < b) : a / b = q := by rw [← h, nat.add_mul_div_right _ _ (lt_of_le_of_lt (nat.zero_le _) h₂), nat.div_eq_of_lt h₂, zero_add] lemma int_div_helper (a b q r : ℤ) (h : r + q * b = a) (h₁ : 0 ≤ r) (h₂ : r < b) : a / b = q := by rw [← h, int.add_mul_div_right _ _ (ne_of_gt (lt_of_le_of_lt h₁ h₂)), int.div_eq_zero_of_lt h₁ h₂, zero_add] lemma nat_mod_helper (a b q r : ℕ) (h : r + q * b = a) (h₂ : r < b) : a % b = r := by rw [← h, nat.add_mul_mod_self_right, nat.mod_eq_of_lt h₂] lemma int_mod_helper (a b q r : ℤ) (h : r + q * b = a) (h₁ : 0 ≤ r) (h₂ : r < b) : a % b = r := by rw [← h, int.add_mul_mod_self, int.mod_eq_of_lt h₁ h₂] meta def eval_pow (simp : expr → tactic (expr × expr)) : expr → tactic (expr × expr) | `(@has_pow.pow %%α _ %%m %%e₁ %%e₂) := match m with | `(nat.has_pow) := mk_app ``nat.pow [e₁, e₂] >>= eval_pow | `(@monoid.has_pow %%α %%m) := mk_app ``monoid.pow [e₁, e₂] >>= eval_pow | _ := failed end | `(monoid.pow %%e₁ 0) := do p ← mk_app ``pow_zero [e₁], a ← infer_type e₁, o ← mk_app ``has_one.one [a], return (o, p) | `(monoid.pow %%e₁ 1) := do p ← mk_app ``pow_one [e₁], return (e₁, p) | `(monoid.pow %%e₁ (bit0 %%e₂)) := do e ← mk_app ``monoid.pow [e₁, e₂], (e', p) ← simp e, p' ← mk_app ``norm_num.pow_bit0_helper [e₁, e', e₂, p], e'' ← to_expr ``(%%e' * %%e'), return (e'', p') | `(monoid.pow %%e₁ (bit1 %%e₂)) := do e ← mk_app ``monoid.pow [e₁, e₂], (e', p) ← simp e, p' ← mk_app ``norm_num.pow_bit1_helper [e₁, e', e₂, p], e'' ← to_expr ``(%%e' * %%e' * %%e₁), return (e'', p') | `(nat.pow %%e₁ %%e₂) := do p₁ ← mk_app ``nat.pow_eq_pow [e₁, e₂], e ← mk_app ``monoid.pow [e₁, e₂], (e', p₂) ← simp e, p ← mk_eq_trans p₁ p₂, return (e', p) | _ := failed meta def prove_pos : instance_cache → expr → tactic (instance_cache × expr) | c `(has_one.one _) := do (c, p) ← c.mk_app ``zero_lt_one [], return (c, p) | c `(bit0 %%e) := do (c, p) ← prove_pos c e, (c, p) ← c.mk_app ``bit0_pos [e, p], return (c, p) | c `(bit1 %%e) := do (c, p) ← prove_pos c e, (c, p) ← c.mk_app ``bit1_pos' [e, p], return (c, p) | c `(%%e₁ / %%e₂) := do (c, p₁) ← prove_pos c e₁, (c, p₂) ← prove_pos c e₂, (c, p) ← c.mk_app ``div_pos_of_pos_of_pos [e₁, e₂, p₁, p₂], return (c, p) | c e := failed meta def prove_lt (simp : expr → tactic (expr × expr)) : instance_cache → expr → expr → tactic (instance_cache × expr) | c `(- %%e₁) `(- %%e₂) := do (c, p) ← prove_lt c e₁ e₂, (c, p) ← c.mk_app ``neg_lt_neg [e₁, e₂, p], return (c, p) | c `(- %%e₁) `(has_zero.zero _) := do (c, p) ← prove_pos c e₁, (c, p) ← c.mk_app ``neg_neg_of_pos [e₁, p], return (c, p) | c `(- %%e₁) e₂ := do (c, p₁) ← prove_pos c e₁, (c, me₁) ← c.mk_app ``has_neg.neg [e₁], (c, p₁) ← c.mk_app ``neg_neg_of_pos [e₁, p₁], (c, p₂) ← prove_pos c e₂, (c, z) ← c.mk_app ``has_zero.zero [], (c, p) ← c.mk_app ``lt_trans [me₁, z, e₂, p₁, p₂], return (c, p) | c `(has_zero.zero _) e₂ := prove_pos c e₂ | c e₁ e₂ := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, d ← expr.of_rat c.α (n₂ - n₁), (c, e₃) ← c.mk_app ``has_add.add [e₁, d], (e₂', p) ← norm_num e₃, guard (e₂' =ₐ e₂), (c, p') ← prove_pos c d, (c, p) ← c.mk_app ``norm_num.lt_add_of_pos_helper [e₁, d, e₂, p, p'], return (c, p) private meta def true_intro (p : expr) : tactic (expr × expr) := prod.mk <$> mk_const `true <*> mk_app ``eq_true_intro [p] private meta def false_intro (p : expr) : tactic (expr × expr) := prod.mk <$> mk_const `false <*> mk_app ``eq_false_intro [p] meta def eval_ineq (simp : expr → tactic (expr × expr)) : expr → tactic (expr × expr) | `(%%e₁ < %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, if n₁ < n₂ then do (_, p) ← prove_lt simp c e₁ e₂, true_intro p else do (c, p) ← if n₁ = n₂ then c.mk_app ``lt_irrefl [e₁] else (do (c, p') ← prove_lt simp c e₂ e₁, c.mk_app ``not_lt_of_gt [e₁, e₂, p']), false_intro p | `(%%e₁ ≤ %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, if n₁ ≤ n₂ then do (c, p) ← if n₁ = n₂ then c.mk_app ``le_refl [e₁] else (do (c, p') ← prove_lt simp c e₁ e₂, c.mk_app ``le_of_lt [e₁, e₂, p']), true_intro p else do (c, p) ← prove_lt simp c e₂ e₁, (c, p) ← c.mk_app ``not_le_of_gt [e₁, e₂, p], false_intro p | `(%%e₁ = %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, if n₁ < n₂ then do (c, p) ← prove_lt simp c e₁ e₂, (c, p) ← c.mk_app ``ne_of_lt [e₁, e₂, p], false_intro p else if n₂ < n₁ then do (c, p) ← prove_lt simp c e₂ e₁, (c, p) ← c.mk_app ``ne_of_gt [e₁, e₂, p], false_intro p else mk_eq_refl e₁ >>= true_intro | `(%%e₁ > %%e₂) := mk_app ``has_lt.lt [e₂, e₁] >>= simp | `(%%e₁ ≥ %%e₂) := mk_app ``has_le.le [e₂, e₁] >>= simp | `(%%e₁ ≠ %%e₂) := do e ← mk_app ``eq [e₁, e₂], mk_app ``not [e] >>= simp | _ := failed meta def eval_div_ext (simp : expr → tactic (expr × expr)) : expr → tactic (expr × expr) | `(has_inv.inv %%e) := do c ← infer_type e >>= mk_instance_cache, (c, p₁) ← c.mk_app ``inv_eq_one_div [e], (c, o) ← c.mk_app ``has_one.one [], (c, e') ← c.mk_app ``has_div.div [o, e], (do (e'', p₂) ← simp e', p ← mk_eq_trans p₁ p₂, return (e'', p)) <|> return (e', p₁) | `(%%e₁ / %%e₂) := do α ← infer_type e₁, c ← mk_instance_cache α, match α with | `(nat) := do n₁ ← e₁.to_nat, n₂ ← e₂.to_nat, q ← expr.of_nat α (n₁ / n₂), r ← expr.of_nat α (n₁ % n₂), (c, e₃) ← c.mk_app ``has_mul.mul [q, e₂], (c, e₃) ← c.mk_app ``has_add.add [r, e₃], (e₁', p) ← norm_num e₃, guard (e₁' =ₐ e₁), (c, p') ← prove_lt simp c r e₂, p ← mk_app ``norm_num.nat_div_helper [e₁, e₂, q, r, p, p'], return (q, p) | `(int) := match e₂ with | `(- %%e₂') := do (c, p₁) ← c.mk_app ``int.div_neg [e₁, e₂'], (c, e) ← c.mk_app ``has_div.div [e₁, e₂'], (c, e) ← c.mk_app ``has_neg.neg [e], (e', p₂) ← simp e, p ← mk_eq_trans p₁ p₂, return (e', p) | _ := do n₁ ← e₁.to_int, n₂ ← e₂.to_int, q ← expr.of_rat α $ rat.of_int (n₁ / n₂), r ← expr.of_rat α $ rat.of_int (n₁ % n₂), (c, e₃) ← c.mk_app ``has_mul.mul [q, e₂], (c, e₃) ← c.mk_app ``has_add.add [r, e₃], (e₁', p) ← norm_num e₃, guard (e₁' =ₐ e₁), (c, r0) ← c.mk_app ``has_zero.zero [], (c, r0) ← c.mk_app ``has_le.le [r0, r], (_, p₁) ← simp r0, p₁ ← mk_app ``of_eq_true [p₁], (c, p₂) ← prove_lt simp c r e₂, p ← mk_app ``norm_num.int_div_helper [e₁, e₂, q, r, p, p₁, p₂], return (q, p) end | _ := failed end | `(%%e₁ % %%e₂) := do α ← infer_type e₁, c ← mk_instance_cache α, match α with | `(nat) := do n₁ ← e₁.to_nat, n₂ ← e₂.to_nat, q ← expr.of_nat α (n₁ / n₂), r ← expr.of_nat α (n₁ % n₂), (c, e₃) ← c.mk_app ``has_mul.mul [q, e₂], (c, e₃) ← c.mk_app ``has_add.add [r, e₃], (e₁', p) ← norm_num e₃, guard (e₁' =ₐ e₁), (c, p') ← prove_lt simp c r e₂, p ← mk_app ``norm_num.nat_mod_helper [e₁, e₂, q, r, p, p'], return (r, p) | `(int) := match e₂ with | `(- %%e₂') := do let p₁ := (expr.const ``int.mod_neg []).mk_app [e₁, e₂'], (c, e) ← c.mk_app ``has_mod.mod [e₁, e₂'], (e', p₂) ← simp e, p ← mk_eq_trans p₁ p₂, return (e', p) | _ := do n₁ ← e₁.to_int, n₂ ← e₂.to_int, q ← expr.of_rat α $ rat.of_int (n₁ / n₂), r ← expr.of_rat α $ rat.of_int (n₁ % n₂), (c, e₃) ← c.mk_app ``has_mul.mul [q, e₂], (c, e₃) ← c.mk_app ``has_add.add [r, e₃], (e₁', p) ← norm_num e₃, guard (e₁' =ₐ e₁), (c, r0) ← c.mk_app ``has_zero.zero [], (c, r0) ← c.mk_app ``has_le.le [r0, r], (_, p₁) ← simp r0, p₁ ← mk_app ``of_eq_true [p₁], (c, p₂) ← prove_lt simp c r e₂, p ← mk_app ``norm_num.int_mod_helper [e₁, e₂, q, r, p, p₁, p₂], return (r, p) end | _ := failed end | `(%%e₁ ∣ %%e₂) := do α ← infer_type e₁, c ← mk_instance_cache α, n ← match α with | `(nat) := return ``nat.dvd_iff_mod_eq_zero | `(int) := return ``int.dvd_iff_mod_eq_zero | _ := failed end, p₁ ← mk_app ``propext [@expr.const tt n [] e₁ e₂], (e', p₂) ← simp `(%%e₂ % %%e₁ = 0), p' ← mk_eq_trans p₁ p₂, return (e', p') | _ := failed lemma not_prime_helper (a b n : ℕ) (h : a * b = n) (h₁ : 1 < a) (h₂ : 1 < b) : ¬ nat.prime n := by rw ← h; exact nat.not_prime_mul h₁ h₂ lemma is_prime_helper (n : ℕ) (h₁ : 1 < n) (h₂ : nat.min_fac n = n) : nat.prime n := nat.prime_def_min_fac.2 ⟨h₁, h₂⟩ lemma min_fac_bit0 (n : ℕ) : nat.min_fac (bit0 n) = 2 := by simp [nat.min_fac_eq, show 2 ∣ bit0 n, by simp [bit0_eq_two_mul n]] def min_fac_helper (n k : ℕ) : Prop := 0 < k ∧ bit1 k ≤ nat.min_fac (bit1 n) theorem min_fac_helper.n_pos {n k : ℕ} (h : min_fac_helper n k) : 0 < n := nat.pos_iff_ne_zero.2 $ λ e, by rw e at h; exact not_le_of_lt (nat.bit1_lt h.1) h.2 lemma min_fac_ne_bit0 {n k : ℕ} : nat.min_fac (bit1 n) ≠ bit0 k := by rw bit0_eq_two_mul; exact λ e, absurd ((nat.dvd_add_iff_right (by simp [bit0_eq_two_mul n])).2 (dvd_trans ⟨_, e⟩ (nat.min_fac_dvd _))) dec_trivial lemma min_fac_helper_0 (n : ℕ) (h : 0 < n) : min_fac_helper n 1 := begin refine ⟨zero_lt_one, lt_of_le_of_ne _ min_fac_ne_bit0.symm⟩, refine @lt_of_le_of_ne ℕ _ _ _ (nat.min_fac_pos _) _, intro e, have := nat.min_fac_prime _, { rw ← e at this, exact nat.not_prime_one this }, { exact ne_of_gt (nat.bit1_lt h) } end lemma min_fac_helper_1 {n k k' : ℕ} (e : k + 1 = k') (np : nat.min_fac (bit1 n) ≠ bit1 k) (h : min_fac_helper n k) : min_fac_helper n k' := begin rw ← e, refine ⟨nat.succ_pos _, (lt_of_le_of_ne (lt_of_le_of_ne _ _ : k+1+k < _) min_fac_ne_bit0.symm : bit0 (k+1) < _)⟩, { rw add_right_comm, exact h.2 }, { rw add_right_comm, exact np.symm } end lemma min_fac_helper_2 (n k k' : ℕ) (e : k + 1 = k') (np : ¬ nat.prime (bit1 k)) (h : min_fac_helper n k) : min_fac_helper n k' := begin refine min_fac_helper_1 e _ h, intro e₁, rw ← e₁ at np, exact np (nat.min_fac_prime $ ne_of_gt $ nat.bit1_lt h.n_pos) end lemma min_fac_helper_3 (n k k' : ℕ) (e : k + 1 = k') (nd : bit1 k ∣ bit1 n = false) (h : min_fac_helper n k) : min_fac_helper n k' := begin refine min_fac_helper_1 e _ h, intro e₁, rw [eq_false, ← e₁] at nd, exact nd (nat.min_fac_dvd _) end lemma min_fac_helper_4 (n k : ℕ) (hd : bit1 k ∣ bit1 n = true) (h : min_fac_helper n k) : nat.min_fac (bit1 n) = bit1 k := by rw eq_true at hd; exact le_antisymm (nat.min_fac_le_of_dvd (nat.bit1_lt h.1) hd) h.2 lemma min_fac_helper_5 (n k k' : ℕ) (e : bit1 k * bit1 k = k') (hd : bit1 n < k') (h : min_fac_helper n k) : nat.min_fac (bit1 n) = bit1 n := begin refine (nat.prime_def_min_fac.1 (nat.prime_def_le_sqrt.2 ⟨nat.bit1_lt h.n_pos, _⟩)).2, rw ← e at hd, intros m m2 hm md, have := le_trans h.2 (le_trans (nat.min_fac_le_of_dvd m2 md) hm), rw nat.le_sqrt at this, exact not_le_of_lt hd this end meta def prove_non_prime (simp : expr → tactic (expr × expr)) (e : expr) (n d₁ : ℕ) : tactic expr := do let e₁ := reflect d₁, c ← mk_instance_cache `(nat), (c, p₁) ← prove_lt simp c `(1) e₁, let d₂ := n / d₁, let e₂ := reflect d₂, (e', p) ← mk_app ``has_mul.mul [e₁, e₂] >>= norm_num, guard (e' =ₐ e), (c, p₂) ← prove_lt simp c `(1) e₂, return $ (expr.const ``not_prime_helper []).mk_app [e₁, e₂, e, p, p₁, p₂] meta def prove_min_fac (simp : expr → tactic (expr × expr)) (e₁ : expr) (n1 : ℕ) : expr → expr → tactic (expr × expr) | e₂ p := do k ← e₂.to_nat, let k1 := bit1 k, e₁1 ← mk_app ``bit1 [e₁], e₂1 ← mk_app ``bit1 [e₂], if n1 < k1*k1 then do c ← mk_instance_cache `(nat), (c, e') ← c.mk_app ``has_mul.mul [e₂1, e₂1], (e', p₁) ← norm_num e', (c, p₂) ← prove_lt simp c e₁1 e', p' ← mk_app ``min_fac_helper_5 [e₁, e₂, e', p₁, p₂, p], return (e₁1, p') else let d := k1.min_fac in if to_bool (d < k1) then do (e', p₁) ← norm_num `(%%e₂ + 1), p₂ ← prove_non_prime simp e₂1 k1 d, mk_app ``min_fac_helper_2 [e₁, e₂, e', p₁, p₂, p] >>= prove_min_fac e' else do (_, p₂) ← simp `((%%e₂1 : ℕ) ∣ %%e₁1), if k1 ∣ n1 then do p' ← mk_app ``min_fac_helper_4 [e₁, e₂, p₂, p], return (e₂1, p') else do (e', p₁) ← norm_num `(%%e₂ + 1), mk_app ``min_fac_helper_3 [e₁, e₂, e', p₁, p₂, p] >>= prove_min_fac e' meta def eval_prime (simp : expr → tactic (expr × expr)) : expr → tactic (expr × expr) | `(nat.prime %%e) := do n ← e.to_nat, match n with | 0 := false_intro `(nat.not_prime_zero) | 1 := false_intro `(nat.not_prime_one) | _ := let d₁ := n.min_fac in if d₁ < n then prove_non_prime simp e n d₁ >>= false_intro else do let e₁ := reflect d₁, c ← mk_instance_cache `(nat), (c, p₁) ← prove_lt simp c `(1) e₁, (e₁, p) ← simp `(nat.min_fac %%e), true_intro $ (expr.const ``is_prime_helper []).mk_app [e, p₁, p] end | `(nat.min_fac 0) := refl_conv (reflect (0:ℕ)) | `(nat.min_fac 1) := refl_conv (reflect (1:ℕ)) | `(nat.min_fac (bit0 %%e)) := prod.mk `(2) <$> mk_app ``min_fac_bit0 [e] | `(nat.min_fac (bit1 %%e)) := do n ← e.to_nat, c ← mk_instance_cache `(nat), (c, p) ← prove_pos c e, mk_app ``min_fac_helper_0 [e, p] >>= prove_min_fac simp e (bit1 n) `(1) | _ := failed meta def derive1 (simp : expr → tactic (expr × expr)) (e : expr) : tactic (expr × expr) := norm_num e <|> eval_div_ext simp e <|> eval_pow simp e <|> eval_ineq simp e <|> eval_prime simp e meta def derive : expr → tactic (expr × expr) | e := do (_, e', pr) ← ext_simplify_core () {} simp_lemmas.mk (λ _, failed) (λ _ _ _ _ _, failed) (λ _ _ _ _ e, do (new_e, pr) ← derive1 derive e, guard (¬ new_e =ₐ e), return ((), new_e, some pr, tt)) `eq e, return (e', pr) end norm_num namespace tactic.interactive open norm_num interactive interactive.types /-- Basic version of `norm_num` that does not call `simp`. -/ meta def norm_num1 (loc : parse location) : tactic unit := do ns ← loc.get_locals, tt ← tactic.replace_at derive ns loc.include_goal | fail "norm_num failed to simplify", when loc.include_goal $ try tactic.triv, when (¬ ns.empty) $ try tactic.contradiction /-- Normalize numerical expressions. Supports the operations `+` `-` `*` `/` `^` `<` `≤` over ordered fields (or other appropriate classes), as well as `-` `/` `%` over `ℤ` and `ℕ`. -/ meta def norm_num (hs : parse simp_arg_list) (l : parse location) : tactic unit := repeat1 $ orelse' (norm_num1 l) $ simp_core {} (norm_num1 (loc.ns [none])) ff hs [] l meta def apply_normed (x : parse texpr) : tactic unit := do x₁ ← to_expr x, (x₂,_) ← derive x₁, tactic.exact x₂ end tactic.interactive
943b137316f02b17e00bd6f039281d71115843bc
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/combinatorics/hindman.lean
2a7da25298b5070f06a646b47c034bb97503fc66
[ "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
11,561
lean
/- Copyright (c) 2021 David Wärn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Wärn -/ import topology.stone_cech import topology.algebra.semigroup import data.stream.init /-! # Hindman's theorem on finite sums > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We prove Hindman's theorem on finite sums, using idempotent ultrafilters. Given an infinite sequence `a₀, a₁, a₂, …` of positive integers, the set `FS(a₀, …)` is the set of positive integers that can be expressed as a finite sum of `aᵢ`'s, without repetition. Hindman's theorem asserts that whenever the positive integers are finitely colored, there exists a sequence `a₀, a₁, a₂, …` such that `FS(a₀, …)` is monochromatic. There is also a stronger version, saying that whenever a set of the form `FS(a₀, …)` is finitely colored, there exists a sequence `b₀, b₁, b₂, …` such that `FS(b₀, …)` is monochromatic and contained in `FS(a₀, …)`. We prove both these versions for a general semigroup `M` instead of `ℕ+` since it is no harder, although this special case implies the general case. The idea of the proof is to extend the addition `(+) : M → M → M` to addition `(+) : βM → βM → βM` on the space `βM` of ultrafilters on `M`. One can prove that if `U` is an _idempotent_ ultrafilter, i.e. `U + U = U`, then any `U`-large subset of `M` contains some set `FS(a₀, …)` (see `exists_FS_of_large`). And with the help of a general topological argument one can show that any set of the form `FS(a₀, …)` is `U`-large according to some idempotent ultrafilter `U` (see `exists_idempotent_ultrafilter_le_FS`). This is enough to prove the theorem since in any finite partition of a `U`-large set, one of the parts is `U`-large. ## Main results - `FS_partition_regular`: the strong form of Hindman's theorem - `exists_FS_of_finite_cover`: the weak form of Hindman's theorem ## Tags Ramsey theory, ultrafilter -/ open filter /-- Multiplication of ultrafilters given by `∀ᶠ m in U*V, p m ↔ ∀ᶠ m in U, ∀ᶠ m' in V, p (m*m')`. -/ @[to_additive "Addition of ultrafilters given by `∀ᶠ m in U+V, p m ↔ ∀ᶠ m in U, ∀ᶠ m' in V, p (m+m')`." ] def ultrafilter.has_mul {M} [has_mul M] : has_mul (ultrafilter M) := { mul := λ U V, (*) <$> U <*> V } local attribute [instance] ultrafilter.has_mul ultrafilter.has_add /- We could have taken this as the definition of `U * V`, but then we would have to prove that it defines an ultrafilter. -/ @[to_additive] lemma ultrafilter.eventually_mul {M} [has_mul M] (U V : ultrafilter M) (p : M → Prop) : (∀ᶠ m in ↑(U * V), p m) ↔ ∀ᶠ m in U, ∀ᶠ m' in V, p (m * m') := iff.rfl /-- Semigroup structure on `ultrafilter M` induced by a semigroup structure on `M`. -/ @[to_additive "Additive semigroup structure on `ultrafilter M` induced by an additive semigroup structure on `M`."] def ultrafilter.semigroup {M} [semigroup M] : semigroup (ultrafilter M) := { mul_assoc := λ U V W, ultrafilter.coe_inj.mp $ filter.ext' $ λ p, by simp only [ultrafilter.eventually_mul, mul_assoc] ..ultrafilter.has_mul } local attribute [instance] ultrafilter.semigroup ultrafilter.add_semigroup /- We don't prove `continuous_mul_right`, because in general it is false! -/ @[to_additive] lemma ultrafilter.continuous_mul_left {M} [semigroup M] (V : ultrafilter M) : continuous (* V) := topological_space.is_topological_basis.continuous ultrafilter_basis_is_basis _ $ set.forall_range_iff.mpr $ λ s, ultrafilter_is_open_basic { m : M | ∀ᶠ m' in V, m * m' ∈ s } namespace hindman /-- `FS a` is the set of finite sums in `a`, i.e. `m ∈ FS a` if `m` is the sum of a nonempty subsequence of `a`. We give a direct inductive definition instead of talking about subsequences. -/ inductive FS {M} [add_semigroup M] : stream M → set M | head (a : stream M) : FS a a.head | tail (a : stream M) (m : M) (h : FS a.tail m) : FS a m | cons (a : stream M) (m : M) (h : FS a.tail m) : FS a (a.head + m) /-- `FP a` is the set of finite products in `a`, i.e. `m ∈ FP a` if `m` is the product of a nonempty subsequence of `a`. We give a direct inductive definition instead of talking about subsequences. -/ @[to_additive FS] inductive FP {M} [semigroup M] : stream M → set M | head (a : stream M) : FP a a.head | tail (a : stream M) (m : M) (h : FP a.tail m) : FP a m | cons (a : stream M) (m : M) (h : FP a.tail m) : FP a (a.head * m) /-- If `m` and `m'` are finite products in `M`, then so is `m * m'`, provided that `m'` is obtained from a subsequence of `M` starting sufficiently late. -/ @[to_additive "If `m` and `m'` are finite sums in `M`, then so is `m + m'`, provided that `m'` is obtained from a subsequence of `M` starting sufficiently late."] lemma FP.mul {M} [semigroup M] {a : stream M} {m : M} (hm : m ∈ FP a) : ∃ n, ∀ m' ∈ FP (a.drop n), m * m' ∈ FP a := begin induction hm with a a m hm ih a m hm ih, { exact ⟨1, λ m hm, FP.cons a m hm⟩, }, { cases ih with n hn, use n+1, intros m' hm', exact FP.tail _ _ (hn _ hm'), }, { cases ih with n hn, use n+1, intros m' hm', rw mul_assoc, exact FP.cons _ _ (hn _ hm'), }, end @[to_additive exists_idempotent_ultrafilter_le_FS] lemma exists_idempotent_ultrafilter_le_FP {M} [semigroup M] (a : stream M) : ∃ U : ultrafilter M, U * U = U ∧ ∀ᶠ m in U, m ∈ FP a := begin let S : set (ultrafilter M) := ⋂ n, { U | ∀ᶠ m in U, m ∈ FP (a.drop n) }, obtain ⟨U, hU, U_idem⟩ := exists_idempotent_in_compact_subsemigroup _ S _ _ _, { refine ⟨U, U_idem, _⟩, convert set.mem_Inter.mp hU 0, }, { exact ultrafilter.continuous_mul_left }, { apply is_compact.nonempty_Inter_of_sequence_nonempty_compact_closed, { intros n U hU, apply eventually.mono hU, rw [add_comm, ←stream.drop_drop, ←stream.tail_eq_drop], exact FP.tail _ }, { intro n, exact ⟨pure _, mem_pure.mpr $ FP.head _⟩, }, { exact (ultrafilter_is_closed_basic _).is_compact, }, { intro n, apply ultrafilter_is_closed_basic, }, }, { exact is_closed.is_compact (is_closed_Inter $ λ i, ultrafilter_is_closed_basic _) }, { intros U hU V hV, rw set.mem_Inter at *, intro n, rw [set.mem_set_of_eq, ultrafilter.eventually_mul], apply eventually.mono (hU n), intros m hm, obtain ⟨n', hn⟩ := FP.mul hm, apply eventually.mono (hV (n' + n)), intros m' hm', apply hn, simpa only [stream.drop_drop] using hm', } end @[to_additive exists_FS_of_large] lemma exists_FP_of_large {M} [semigroup M] (U : ultrafilter M) (U_idem : U * U = U) (s₀ : set M) (sU : s₀ ∈ U) : ∃ a, FP a ⊆ s₀ := begin /- Informally: given a `U`-large set `s₀`, the set `s₀ ∩ { m | ∀ᶠ m' in U, m * m' ∈ s₀ }` is also `U`-large (since `U` is idempotent). Thus in particular there is an `a₀` in this intersection. Now let `s₁` be the intersection `s₀ ∩ { m | a₀ * m ∈ s₀ }`. By choice of `a₀`, this is again `U`-large, so we can repeat the argument starting from `s₁`, obtaining `a₁`, `s₂`, etc. This gives the desired infinite sequence. -/ have exists_elem : ∀ {s : set M} (hs : s ∈ U), (s ∩ { m | ∀ᶠ m' in U, m * m' ∈ s }).nonempty := λ s hs, ultrafilter.nonempty_of_mem (inter_mem hs $ by { rw ←U_idem at hs, exact hs }), let elem : { s // s ∈ U } → M := λ p, (exists_elem p.property).some, let succ : { s // s ∈ U } → { s // s ∈ U } := λ p, ⟨p.val ∩ { m | elem p * m ∈ p.val }, inter_mem p.2 $ show _, from set.inter_subset_right _ _ (exists_elem p.2).some_mem⟩, use stream.corec elem succ (subtype.mk s₀ sU), suffices : ∀ (a : stream M) (m ∈ FP a), ∀ p, a = stream.corec elem succ p → m ∈ p.val, { intros m hm, exact this _ m hm ⟨s₀, sU⟩ rfl, }, clear sU s₀, intros a m h, induction h with b b n h ih b n h ih, { rintros p rfl, rw [stream.corec_eq, stream.head_cons], exact set.inter_subset_left _ _ (set.nonempty.some_mem _), }, { rintros p rfl, refine set.inter_subset_left _ _ (ih (succ p) _), rw [stream.corec_eq, stream.tail_cons], }, { rintros p rfl, have := set.inter_subset_right _ _ (ih (succ p) _), { simpa only using this }, rw [stream.corec_eq, stream.tail_cons], }, end /-- The strong form of **Hindman's theorem**: in any finite cover of an FP-set, one the parts contains an FP-set. -/ @[to_additive FS_partition_regular "The strong form of **Hindman's theorem**: in any finite cover of an FS-set, one the parts contains an FS-set."] lemma FP_partition_regular {M} [semigroup M] (a : stream M) (s : set (set M)) (sfin : s.finite) (scov : FP a ⊆ ⋃₀ s) : ∃ (c ∈ s) (b : stream M), FP b ⊆ c := let ⟨U, idem, aU⟩ := exists_idempotent_ultrafilter_le_FP a in let ⟨c, cs, hc⟩ := (ultrafilter.finite_sUnion_mem_iff sfin).mp (mem_of_superset aU scov) in ⟨c, cs, exists_FP_of_large U idem c hc⟩ /-- The weak form of **Hindman's theorem**: in any finite cover of a nonempty semigroup, one of the parts contains an FP-set. -/ @[to_additive exists_FS_of_finite_cover "The weak form of **Hindman's theorem**: in any finite cover of a nonempty additive semigroup, one of the parts contains an FS-set."] lemma exists_FP_of_finite_cover {M} [semigroup M] [nonempty M] (s : set (set M)) (sfin : s.finite) (scov : ⊤ ⊆ ⋃₀ s) : ∃ (c ∈ s) (a : stream M), FP a ⊆ c := let ⟨U, hU⟩ := exists_idempotent_of_compact_t2_of_continuous_mul_left (@ultrafilter.continuous_mul_left M _) in let ⟨c, c_s, hc⟩ := (ultrafilter.finite_sUnion_mem_iff sfin).mp (mem_of_superset univ_mem scov) in ⟨c, c_s, exists_FP_of_large U hU c hc⟩ @[to_additive FS_iter_tail_sub_FS] lemma FP_drop_subset_FP {M} [semigroup M] (a : stream M) (n : ℕ) : FP (a.drop n) ⊆ FP a := begin induction n with n ih, { refl }, rw [nat.succ_eq_one_add, ←stream.drop_drop], exact trans (FP.tail _) ih, end @[to_additive] lemma FP.singleton {M} [semigroup M] (a : stream M) (i : ℕ) : a.nth i ∈ FP a := by { induction i with i ih generalizing a, { apply FP.head }, { apply FP.tail, apply ih } } @[to_additive] lemma FP.mul_two {M} [semigroup M] (a : stream M) (i j : ℕ) (ij : i < j) : a.nth i * a.nth j ∈ FP a := begin refine FP_drop_subset_FP _ i _, rw ←stream.head_drop, apply FP.cons, rcases le_iff_exists_add.mp (nat.succ_le_of_lt ij) with ⟨d, hd⟩, have := FP.singleton (a.drop i).tail d, rw [stream.tail_eq_drop, stream.nth_drop, stream.nth_drop] at this, convert this, rw [hd, add_comm, nat.succ_add, nat.add_succ], end @[to_additive] lemma FP.finset_prod {M} [comm_monoid M] (a : stream M) (s : finset ℕ) (hs : s.nonempty) : s.prod (λ i, a.nth i) ∈ FP a := begin refine FP_drop_subset_FP _ (s.min' hs) _, induction s using finset.strong_induction with s ih, rw [←finset.mul_prod_erase _ _ (s.min'_mem hs), ←stream.head_drop], cases (s.erase (s.min' hs)).eq_empty_or_nonempty with h h, { rw [h, finset.prod_empty, mul_one], exact FP.head _ }, { apply FP.cons, rw [stream.tail_eq_drop, stream.drop_drop, add_comm], refine set.mem_of_subset_of_mem _ (ih _ (finset.erase_ssubset $ s.min'_mem hs) h), have : s.min' hs + 1 ≤ (s.erase (s.min' hs)).min' h := nat.succ_le_of_lt (finset.min'_lt_of_mem_erase_min' _ _ $ finset.min'_mem _ _), cases le_iff_exists_add.mp this with d hd, rw [hd, add_comm, ←stream.drop_drop], apply FP_drop_subset_FP } end end hindman
8f8a2839867daceedde36a7f7117517fa4dcf457
8b9f17008684d796c8022dab552e42f0cb6fb347
/hott/init/hit.hlean
5013afa37899240fb183bc4d51996a1c0d8451c7
[ "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
3,281
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: init.hit Authors: Floris van Doorn Declaration of the primitive hits in Lean -/ prelude import .trunc open is_trunc eq /- We take two higher inductive types (hits) as primitive notions in Lean. We define all other hits in terms of these two hits. The hits which are primitive are - n-truncation - type quotients (non-truncated quotients) For each of the hits we add the following constants: - the type formation - the term and path constructors - the dependent recursor We add the computation rule for point constructors judgmentally to the kernel of Lean. The computation rules for the path constructors are added (propositionally) as axioms In this file we only define the dependent recursor. For the nondependent recursor and all other uses of these hits, see the folder ../hit/ -/ constant trunc.{u} (n : trunc_index) (A : Type.{u}) : Type.{u} namespace trunc constant tr {n : trunc_index} {A : Type} (a : A) : trunc n A constant is_trunc_trunc (n : trunc_index) (A : Type) : is_trunc n (trunc n A) attribute is_trunc_trunc [instance] protected constant rec {n : trunc_index} {A : Type} {P : trunc n A → Type} [Pt : Πaa, is_trunc n (P aa)] (H : Πa, P (tr a)) : Πaa, P aa protected definition rec_on [reducible] {n : trunc_index} {A : Type} {P : trunc n A → Type} (aa : trunc n A) [Pt : Πaa, is_trunc n (P aa)] (H : Πa, P (tr a)) : P aa := trunc.rec H aa end trunc constant type_quotient.{u v} {A : Type.{u}} (R : A → A → Type.{v}) : Type.{max u v} namespace type_quotient constant class_of {A : Type} (R : A → A → Type) (a : A) : type_quotient R constant eq_of_rel {A : Type} {R : A → A → Type} {a a' : A} (H : R a a') : class_of R a = class_of R a' protected constant rec {A : Type} {R : A → A → Type} {P : type_quotient R → Type} (Pc : Π(a : A), P (class_of R a)) (Pp : Π⦃a a' : A⦄ (H : R a a'), eq_of_rel H ▹ Pc a = Pc a') (x : type_quotient R) : P x protected definition rec_on [reducible] {A : Type} {R : A → A → Type} {P : type_quotient R → Type} (x : type_quotient R) (Pc : Π(a : A), P (class_of R a)) (Pp : Π⦃a a' : A⦄ (H : R a a'), eq_of_rel H ▹ Pc a = Pc a') : P x := rec Pc Pp x end type_quotient init_hits -- Initialize builtin computational rules for trunc and type_quotient namespace trunc definition rec_tr [reducible] {n : trunc_index} {A : Type} {P : trunc n A → Type} [Pt : Πaa, is_trunc n (P aa)] (H : Πa, P (tr a)) (a : A) : trunc.rec H (tr a) = H a := idp end trunc namespace type_quotient definition rec_class_of {A : Type} {R : A → A → Type} {P : type_quotient R → Type} (Pc : Π(a : A), P (class_of R a)) (Pp : Π⦃a a' : A⦄ (H : R a a'), eq_of_rel H ▹ Pc a = Pc a') (a : A) : type_quotient.rec Pc Pp (class_of R a) = Pc a := idp constant rec_eq_of_rel {A : Type} {R : A → A → Type} {P : type_quotient R → Type} (Pc : Π(a : A), P (class_of R a)) (Pp : Π⦃a a' : A⦄ (H : R a a'), eq_of_rel H ▹ Pc a = Pc a') {a a' : A} (H : R a a') : apD (type_quotient.rec Pc Pp) (eq_of_rel H) = Pp H end type_quotient
675c6a0780a3573ca3891cb484daf9b6e33e1cb8
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/stage0/src/Init/Data/Array/Subarray.lean
3e9db469aa105d1bec1e293b391d6d01d7451779
[ "Apache-2.0" ]
permissive
banksonian/lean4
3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc
78da6b3aa2840693eea354a41e89fc5b212a5011
refs/heads/master
1,673,703,624,165
1,605,123,551,000
1,605,123,551,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,657
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 -/ prelude import Init.Data.Array.Basic universes u v w structure Subarray (α : Type u) := (as : Array α) (start : Nat) (stop : Nat) (h₁ : start ≤ stop) (h₂ : stop ≤ as.size) namespace Subarray @[inline] unsafe def forInUnsafe {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (s : Subarray α) (b : β) (f : α → β → m (ForInStep β)) : m β := let sz := USize.ofNat s.stop let rec @[specialize] loop (i : USize) (b : β) : m β := do if i < sz then let a := s.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 (USize.ofNat s.start) b -- TODO: provide reference implementation @[implementedBy Subarray.forInUnsafe] constant forIn {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (s : Subarray α) (b : β) (f : α → β → m (ForInStep β)) : m β := pure b @[inline] def foldlM {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (f : β → α → m β) (init : β) (as : Subarray α) : m β := as.as.foldlM f (init := init) (start := as.start) (stop := as.stop) @[inline] def foldrM {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (f : α → β → m β) (init : β) (as : Subarray α) : m β := as.as.foldrM f (init := init) (start := as.stop) (stop := as.start) @[inline] def anyM {α : Type u} {m : Type → Type w} [Monad m] (p : α → m Bool) (as : Subarray α) : m Bool := as.as.anyM p (start := as.start) (stop := as.stop) @[inline] def allM {α : Type u} {m : Type → Type w} [Monad m] (p : α → m Bool) (as : Subarray α) : m Bool := as.as.allM p (start := as.start) (stop := as.stop) @[inline] def forM {α : Type u} {m : Type v → Type w} [Monad m] (f : α → m PUnit) (as : Subarray α) : m PUnit := as.as.forM f (start := as.start) (stop := as.stop) @[inline] def forRevM {α : Type u} {m : Type v → Type w} [Monad m] (f : α → m PUnit) (as : Subarray α) : m PUnit := as.as.forRevM f (start := as.stop) (stop := as.start) @[inline] def foldl {α : Type u} {β : Type v} (f : β → α → β) (init : β) (as : Subarray α) : β := Id.run $ as.foldlM f (init := init) @[inline] def foldr {α : Type u} {β : Type v} (f : α → β → β) (init : β) (as : Subarray α) : β := Id.run $ as.foldrM f (init := init) @[inline] def any {α : Type u} (p : α → Bool) (as : Subarray α) : Bool := Id.run $ as.anyM p @[inline] def all {α : Type u} (p : α → Bool) (as : Subarray α) : Bool := Id.run $ as.allM p end Subarray namespace Array variables {α : Type u} def toSubarray (as : Array α) (start stop : Nat) : Subarray α := if h₂ : stop ≤ as.size then if h₁ : start ≤ stop then { as := as, start := start, stop := stop, h₁ := h₁, h₂ := h₂ } else { as := as, start := stop, stop := stop, h₁ := Nat.leRefl _, h₂ := h₂ } else if h₁ : start ≤ as.size then { as := as, start := start, stop := as.size, h₁ := h₁, h₂ := Nat.leRefl _ } else { as := as, start := as.size, stop := as.size, h₁ := Nat.leRefl _, h₂ := Nat.leRefl _ } def ofSubarray (s : Subarray α) : Array α := do let mut as := mkEmpty (s.stop - s.start) for a in s do as := as.push a return as def extract (as : Array α) (start stop : Nat) : Array α := ofSubarray (as.toSubarray start stop) instance : Coe (Subarray α) (Array α) := ⟨ofSubarray⟩ end Array
f46a0c5551ff9deae9237af7b99a7dc56e5c8181
618003631150032a5676f229d13a079ac875ff77
/src/category_theory/eq_to_hom.lean
9ade80a3eeac832690c08d64cafed9b90fd5d91d
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
2,652
lean
/- Copyright (c) 2018 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Scott Morrison -/ import category_theory.opposites universes v v' u u' -- declare the `v`'s first; see `category_theory.category` for an explanation namespace category_theory open opposite variables {C : Type u} [category.{v} C] def eq_to_hom {X Y : C} (p : X = Y) : X ⟶ Y := by rw p; exact 𝟙 _ @[simp] lemma eq_to_hom_refl (X : C) (p : X = X) : eq_to_hom p = 𝟙 X := rfl @[simp, reassoc] lemma eq_to_hom_trans {X Y Z : C} (p : X = Y) (q : Y = Z) : eq_to_hom p ≫ eq_to_hom q = eq_to_hom (p.trans q) := by cases p; cases q; simp def eq_to_iso {X Y : C} (p : X = Y) : X ≅ Y := ⟨eq_to_hom p, eq_to_hom p.symm, by simp, by simp⟩ @[simp] lemma eq_to_iso.hom {X Y : C} (p : X = Y) : (eq_to_iso p).hom = eq_to_hom p := rfl @[simp] lemma eq_to_iso.inv {X Y : C} (p : X = Y) : (eq_to_iso p).inv = eq_to_hom p.symm := rfl @[simp] lemma eq_to_iso_refl (X : C) (p : X = X) : eq_to_iso p = iso.refl X := rfl @[simp] lemma eq_to_iso_trans {X Y Z : C} (p : X = Y) (q : Y = Z) : eq_to_iso p ≪≫ eq_to_iso q = eq_to_iso (p.trans q) := by ext; simp @[simp] lemma eq_to_hom_op (X Y : C) (h : X = Y) : (eq_to_hom h).op = eq_to_hom (congr_arg op h.symm) := begin cases h, refl end variables {D : Type u'} [category.{v'} D] namespace functor /-- Proving equality between functors. This isn't an extensionality lemma, because usually you don't really want to do this. -/ lemma ext {F G : C ⥤ D} (h_obj : ∀ X, F.obj X = G.obj X) (h_map : ∀ X Y f, F.map f = eq_to_hom (h_obj X) ≫ G.map f ≫ eq_to_hom (h_obj Y).symm) : F = G := begin cases F with F_obj _ _ _, cases G with G_obj _ _ _, have : F_obj = G_obj, by ext X; apply h_obj, subst this, congr, funext X Y f, simpa using h_map X Y f end -- Using equalities between functors. lemma congr_obj {F G : C ⥤ D} (h : F = G) (X) : F.obj X = G.obj X := by subst h lemma congr_hom {F G : C ⥤ D} (h : F = G) {X Y} (f : X ⟶ Y) : F.map f = eq_to_hom (congr_obj h X) ≫ G.map f ≫ eq_to_hom (congr_obj h Y).symm := by subst h; simp end functor @[simp] lemma eq_to_hom_map (F : C ⥤ D) {X Y : C} (p : X = Y) : F.map (eq_to_hom p) = eq_to_hom (congr_arg F.obj p) := by cases p; simp @[simp] lemma eq_to_iso_map (F : C ⥤ D) {X Y : C} (p : X = Y) : F.map_iso (eq_to_iso p) = eq_to_iso (congr_arg F.obj p) := by ext; cases p; simp @[simp] lemma eq_to_hom_app {F G : C ⥤ D} (h : F = G) (X : C) : (eq_to_hom h : F ⟶ G).app X = eq_to_hom (functor.congr_obj h X) := by subst h; refl end category_theory
8869c59ac8eae0b4f82397c2ca797d112ac468b0
08bd4ba4ca87dba1f09d2c96a26f5d65da81f4b4
/tests/lean/interactive/plainGoal.lean
43d825a031866a325efd1e27d2da21a2e866ca36
[ "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", "Apache-2.0", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
gebner/lean4
d51c4922640a52a6f7426536ea669ef18a1d9af5
8cd9ce06843c9d42d6d6dc43d3e81e3b49dfc20f
refs/heads/master
1,685,732,780,391
1,672,962,627,000
1,673,459,398,000
373,307,283
0
0
Apache-2.0
1,691,316,730,000
1,622,669,271,000
Lean
UTF-8
Lean
false
false
2,759
lean
example : α → α := by --^ $/lean/plainGoal --^ $/lean/plainGoal intro a --^ $/lean/plainGoal --^ $/lean/plainGoal --v $/lean/plainGoal focus apply a example : α → α := by --^ $/lean/plainGoal example : 0 + n = n := by induction n with | zero => simp; simp --^ $/lean/plainGoal | succ --^ $/lean/plainGoal example : α → α := by intro a; apply a --^ $/lean/plainGoal --^ $/lean/plainGoal --^ $/lean/plainGoal example (h1 : n = m) (h2 : m = 0) : 0 = n := by rw [h1, h2] --^ $/lean/plainGoal --^ $/lean/plainGoal --^ $/lean/plainGoal example : 0 + n = n := by induction n focus --^ $/lean/plainGoal rfl -- TODO: goal state after dedent example : 0 + n = n := by induction n --^ $/lean/plainGoal example : 0 + n = n := by cases n --^ $/lean/plainGoal example : ∀ a b : Nat, a = b := by intro a b --^ $/lean/plainGoal example : α → α := (by --^ $/lean/plainGoal example (p : α → Prop) (a b : α) [DecidablePred p] (h : ∀ {p} [DecidablePred p], p a → p b) : p b := by apply h _ --^ $/lean/plainGoal -- should not display solved goal `⊢ DecidablePred p` example : True ∧ False := by constructor { constructor } --^ $/lean/plainGoal { } --^ $/lean/plainGoal example : True ∧ False := by constructor · constructor --^ $/lean/plainGoal · --^ $/lean/plainGoal theorem left_distrib (t a b : Nat) : t * (a + b) = t * a + t * b := by induction b next => simp next => rw [Nat.add_succ] repeat (rw [Nat.mul_succ]) --^ $/lean/plainGoal example (as bs cs : List α) : (as ++ bs) ++ cs = as ++ (bs ++ cs) := by induction as <;> skip <;> (try rename_i h; simp[h]) <;> rfl --^ $/lean/plainGoal --^ $/lean/plainGoal example : True := (by exact True.intro) --^ $/lean/plainGoal example : True := (by exact True.intro ) --^ $/lean/plainGoal example : True ∧ False := by · constructor; constructor --^ $/lean/plainGoal example : True = True := by conv => --^ $/lean/plainGoal whnf --^ $/lean/plainGoal -- --^ $/lean/plainGoal example : True := by have : True := by -- type here --^ $/lean/plainGoal -- no `this` here either, but seems okay --^ $/lean/plainGoal example : True := by have : True := by -- type here --^ $/lean/plainGoal apply this --^ $/lean/plainGoal -- note: no output here at all because of parse error example : False := by -- EOF test --^ $/lean/plainGoal
84742d6e05168b23802da457550a43416dfd235a
ebbdcbd7ddc89a9ef7c3b397b301d5f5272a918f
/qp/p1_categories/c2_limits.lean
d9e74318ac1d4cd0392767b2bc0b7bada749d5e3
[]
no_license
intoverflow/qvr
34b9ef23604738381ca20b7d622fd0399d88f2dd
0cfcd33fe4bf8d93851a00cec5bfd21e77105d74
refs/heads/master
1,616,591,570,371
1,492,575,772,000
1,492,575,772,000
80,061,627
0
0
null
null
null
null
UTF-8
Lean
false
false
120
lean
import .c2_limits.s1_limits import .c2_limits.s2_products import .c2_limits.s3_pullbacks import .c2_limits.s6_stability
b2859d7f5764f65861d7a852d84da03fb8bb551e
a46270e2f76a375564f3b3e9c1bf7b635edc1f2c
/7.10.5.lean
3879f0716f031de5e24ec01d220a71ee7b73e8b4
[ "CC0-1.0" ]
permissive
wudcscheme/lean-exercise
88ea2506714eac343de2a294d1132ee8ee6d3a20
5b23b9be3d361fff5e981d5be3a0a1175504b9f6
refs/heads/master
1,678,958,930,293
1,583,197,205,000
1,583,197,205,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
272
lean
inductive parity: Type | E | O. inductive even_or_odd: ℕ -> parity -> Prop | even_zero : even_or_odd 0 parity.E | even_succ : ∀ n, (even_or_odd n parity.O) -> even_or_odd (n+1) parity.E | odd_succ : ∀ n, (even_or_odd n parity.E) -> even_or_odd (n+1) parity.O
6e1715b619d781b72dda6b61d4646d34921bfb4d
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/data/hash_map.lean
ea0827e19c8f496ed8200539fc932faaa809324b
[ "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
29,616
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Mario Carneiro -/ import data.pnat.basic import data.list.range import data.array.lemmas import algebra.group import data.sigma.basic /-! # Hash maps Defines a hash map data structure, representing a finite key-value map with a value type that may depend on the key type. The structure requires a `nat`-valued hash function to associate keys to buckets. ## Main definitions * `hash_map`: constructed with `mk_hash_map`. ## Implementation details A hash map with key type `α` and (dependent) value type `β : α → Type*` consists of an array of *buckets*, which are lists containing key/value pairs for that bucket. The hash function is taken modulo `n` to assign keys to their respective bucket. Because of this, some care should be put into the hash function to ensure it evenly distributes keys. The bucket array is an `array`. These have special VM support for in-place modification if there is only ever one reference to them. If one takes special care to never keep references to old versions of a hash map alive after updating it, then the hash map will be modified in-place. In this documentation, when we say a hash map is modified in-place, we are assuming the API is being used in this manner. When inserting (`hash_map.insert`), if the number of stored pairs (the *size*) is going to exceed the number of buckets, then a new hash map is first created with double the number of buckets and everything in the old hash map is reinserted along with the new key/value pair. Otherwise, the bucket array is modified in-place. The amortized running time of inserting $$n$$ elements into a hash map is $$O(n)$$. When removing (`hash_map.erase`), the hash map is modified in-place. The implementation does not reduce the number of buckets in the hash map if the size gets too low. ## Tags hash map -/ universes u v w /-- `bucket_array α β` is the underlying data type for `hash_map α β`, an array of linked lists of key-value pairs. -/ def bucket_array (α : Type u) (β : α → Type v) (n : ℕ+) := array n (list Σ a, β a) /-- Make a hash_map index from a `nat` hash value and a (positive) buffer size -/ def hash_map.mk_idx (n : ℕ+) (i : nat) : fin n := ⟨i % n, nat.mod_lt _ n.2⟩ namespace bucket_array section parameters {α : Type u} {β : α → Type v} (hash_fn : α → nat) variables {n : ℕ+} (data : bucket_array α β n) instance : inhabited (bucket_array α β n) := ⟨mk_array _ []⟩ /-- Read the bucket corresponding to an element -/ def read (a : α) : list Σ a, β a := let bidx := hash_map.mk_idx n (hash_fn a) in data.read bidx /-- Write the bucket corresponding to an element -/ def write (a : α) (l : list Σ a, β a) : bucket_array α β n := let bidx := hash_map.mk_idx n (hash_fn a) in data.write bidx l /-- Modify (read, apply `f`, and write) the bucket corresponding to an element -/ def modify (a : α) (f : list (Σ a, β a) → list (Σ a, β a)) : bucket_array α β n := let bidx := hash_map.mk_idx n (hash_fn a) in array.write data bidx (f (array.read data bidx)) /-- The list of all key-value pairs in the bucket list -/ def as_list : list Σ a, β a := data.to_list.join theorem mem_as_list {a : Σ a, β a} : a ∈ data.as_list ↔ ∃i, a ∈ array.read data i := have (∃ (l : list (Σ (a : α), β a)) (i : fin (n.val)), a ∈ l ∧ array.read data i = l) ↔ ∃ (i : fin (n.val)), a ∈ array.read data i, by rw exists_swap; exact exists_congr (λ i, by simp), by simp [as_list]; simpa [array.mem.def, and_comm] /-- Fold a function `f` over the key-value pairs in the bucket list -/ def foldl {δ : Type w} (d : δ) (f : δ → Π a, β a → δ) : δ := data.foldl d (λ b d, b.foldl (λ r a, f r a.1 a.2) d) theorem foldl_eq {δ : Type w} (d : δ) (f : δ → Π a, β a → δ) : data.foldl d f = data.as_list.foldl (λ r a, f r a.1 a.2) d := by rw [foldl, as_list, list.foldl_join, ← array.to_list_foldl] end end bucket_array namespace hash_map section parameters {α : Type u} {β : α → Type v} (hash_fn : α → nat) /-- Insert the pair `⟨a, b⟩` into the correct location in the bucket array (without checking for duplication) -/ def reinsert_aux {n} (data : bucket_array α β n) (a : α) (b : β a) : bucket_array α β n := data.modify hash_fn a (λl, ⟨a, b⟩ :: l) theorem mk_as_list (n : ℕ+) : bucket_array.as_list (mk_array n [] : bucket_array α β n) = [] := list.eq_nil_iff_forall_not_mem.mpr $ λ x m, let ⟨i, h⟩ := (bucket_array.mem_as_list _).1 m in h parameter [decidable_eq α] /-- Search a bucket for a key `a` and return the value -/ def find_aux (a : α) : list (Σ a, β a) → option (β a) | [] := none | (⟨a',b⟩::t) := if h : a' = a then some (eq.rec_on h b) else find_aux t theorem find_aux_iff {a : α} {b : β a} : Π {l : list Σ a, β a}, (l.map sigma.fst).nodup → (find_aux a l = some b ↔ sigma.mk a b ∈ l) | [] nd := ⟨λn, by injection n, false.elim⟩ | (⟨a',b'⟩::t) nd := begin by_cases a' = a, { clear find_aux_iff, subst h, suffices : b' = b ↔ b' = b ∨ sigma.mk a' b ∈ t, {simpa [find_aux, eq_comm]}, refine (or_iff_left_of_imp (λ m, _)).symm, have : a' ∉ t.map sigma.fst, from list.not_mem_of_nodup_cons nd, exact this.elim (list.mem_map_of_mem sigma.fst m) }, { have : sigma.mk a b ≠ ⟨a', b'⟩, { intro e, injection e with e, exact h e.symm }, simp at nd, simp [find_aux, h, ne.symm h, find_aux_iff, nd] } end /-- Returns `tt` if the bucket `l` contains the key `a` -/ def contains_aux (a : α) (l : list Σ a, β a) : bool := (find_aux a l).is_some theorem contains_aux_iff {a : α} {l : list Σ a, β a} (nd : (l.map sigma.fst).nodup) : contains_aux a l ↔ a ∈ l.map sigma.fst := begin unfold contains_aux, cases h : find_aux a l with b; simp, { assume (b : β a) (m : sigma.mk a b ∈ l), rw (find_aux_iff nd).2 m at h, contradiction }, { show ∃ (b : β a), sigma.mk a b ∈ l, exact ⟨_, (find_aux_iff nd).1 h⟩ }, end /-- Modify a bucket to replace a value in the list. Leaves the list unchanged if the key is not found. -/ def replace_aux (a : α) (b : β a) : list (Σ a, β a) → list (Σ a, β a) | [] := [] | (⟨a', b'⟩::t) := if a' = a then ⟨a, b⟩::t else ⟨a', b'⟩ :: replace_aux t /-- Modify a bucket to remove a key, if it exists. -/ def erase_aux (a : α) : list (Σ a, β a) → list (Σ a, β a) | [] := [] | (⟨a', b'⟩::t) := if a' = a then t else ⟨a', b'⟩ :: erase_aux t /-- The predicate `valid bkts sz` means that `bkts` satisfies the `hash_map` invariants: There are exactly `sz` elements in it, every pair is in the bucket determined by its key and the hash function, and no key appears multiple times in the list. -/ structure valid {n} (bkts : bucket_array α β n) (sz : nat) : Prop := (len : bkts.as_list.length = sz) (idx : ∀ {i} {a : Σ a, β a}, a ∈ array.read bkts i → mk_idx n (hash_fn a.1) = i) (nodup : ∀i, ((array.read bkts i).map sigma.fst).nodup) theorem valid.idx_enum {n} {bkts : bucket_array α β n} {sz : nat} (v : valid bkts sz) {i l} (he : (i, l) ∈ bkts.to_list.enum) {a} {b : β a} (hl : sigma.mk a b ∈ l) : ∃ h, mk_idx n (hash_fn a) = ⟨i, h⟩ := (array.mem_to_list_enum.mp he).imp (λ h e, by subst e; exact v.idx hl) theorem valid.idx_enum_1 {n} {bkts : bucket_array α β n} {sz : nat} (v : valid bkts sz) {i l} (he : (i, l) ∈ bkts.to_list.enum) {a} {b : β a} (hl : sigma.mk a b ∈ l) : (mk_idx n (hash_fn a)).1 = i := let ⟨h, e⟩ := v.idx_enum _ he hl in by rw e; refl theorem valid.as_list_nodup {n} {bkts : bucket_array α β n} {sz : nat} (v : valid bkts sz) : (bkts.as_list.map sigma.fst).nodup := begin suffices : (bkts.to_list.map (list.map sigma.fst)).pairwise list.disjoint, { suffices : ∀ l, array.mem l bkts → (l.map sigma.fst).nodup, by simpa [bucket_array.as_list, list.nodup_join, *], rintros l ⟨i, rfl⟩, apply v.nodup }, rw [← list.enum_map_snd bkts.to_list, list.pairwise_map, list.pairwise_map], have : (bkts.to_list.enum.map prod.fst).nodup := by simp [list.nodup_range], refine list.pairwise.imp_of_mem _ ((list.pairwise_map _).1 this), rw prod.forall, intros i l₁, rw prod.forall, intros j l₂ me₁ me₂ ij, simp [list.disjoint], intros a b ml₁ b' ml₂, apply ij, rwa [← v.idx_enum_1 _ me₁ ml₁, ← v.idx_enum_1 _ me₂ ml₂] end theorem mk_valid (n : ℕ+) : @valid n (mk_array n []) 0 := ⟨by simp [mk_as_list], λ i a h, by cases h, λ i, list.nodup_nil⟩ theorem valid.find_aux_iff {n} {bkts : bucket_array α β n} {sz : nat} (v : valid bkts sz) {a : α} {b : β a} : find_aux a (bkts.read hash_fn a) = some b ↔ sigma.mk a b ∈ bkts.as_list := (find_aux_iff (v.nodup _)).trans $ by rw bkts.mem_as_list; exact ⟨λ h, ⟨_, h⟩, λ ⟨i, h⟩, (v.idx h).symm ▸ h⟩ theorem valid.contains_aux_iff {n} {bkts : bucket_array α β n} {sz : nat} (v : valid bkts sz) (a : α) : contains_aux a (bkts.read hash_fn a) ↔ a ∈ bkts.as_list.map sigma.fst := by simp [contains_aux, option.is_some_iff_exists, v.find_aux_iff hash_fn] section parameters {n : ℕ+} {bkts : bucket_array α β n} {bidx : fin n} {f : list (Σ a, β a) → list (Σ a, β a)} (u v1 v2 w : list Σ a, β a) local notation `L` := array.read bkts bidx private def bkts' : bucket_array α β n := array.write bkts bidx (f L) variables (hl : L = u ++ v1 ++ w) (hfl : f L = u ++ v2 ++ w) include hl hfl theorem append_of_modify : ∃ u' w', bkts.as_list = u' ++ v1 ++ w' ∧ bkts'.as_list = u' ++ v2 ++ w' := begin unfold bucket_array.as_list, have h : (bidx : ℕ) < bkts.to_list.length, { simp only [bidx.is_lt, array.to_list_length] }, refine ⟨(bkts.to_list.take bidx).join ++ u, w ++ (bkts.to_list.drop (bidx+1)).join, _, _⟩, { conv { to_lhs, rw [← list.take_append_drop bidx bkts.to_list, list.drop_eq_nth_le_cons h], simp [hl] }, simp }, { conv { to_lhs, rw [bkts', array.write_to_list, list.update_nth_eq_take_cons_drop _ h], simp [hfl] }, simp } end variables (hvnd : (v2.map sigma.fst).nodup) (hal : ∀ (a : Σ a, β a), a ∈ v2 → mk_idx n (hash_fn a.1) = bidx) (djuv : (u.map sigma.fst).disjoint (v2.map sigma.fst)) (djwv : (w.map sigma.fst).disjoint (v2.map sigma.fst)) include hvnd hal djuv djwv theorem valid.modify {sz : ℕ} (v : valid bkts sz) : v1.length ≤ sz + v2.length ∧ valid bkts' (sz + v2.length - v1.length) := begin rcases append_of_modify u v1 v2 w hl hfl with ⟨u', w', e₁, e₂⟩, rw [← v.len, e₁], suffices : valid bkts' (u' ++ v2 ++ w').length, { simpa [ge, add_comm, add_left_comm, nat.le_add_right, nat.add_sub_cancel_left] }, refine ⟨congr_arg _ e₂, λ i a, _, λ i, _⟩, { by_cases bidx = i, { subst i, rw [bkts', array.read_write, hfl], have := @valid.idx _ _ _ v bidx a, simp only [hl, list.mem_append, or_imp_distrib, forall_and_distrib] at this ⊢, exact ⟨⟨this.1.1, hal _⟩, this.2⟩ }, { rw [bkts', array.read_write_of_ne _ _ h], apply v.idx } }, { by_cases bidx = i, { subst i, rw [bkts', array.read_write, hfl], have := @valid.nodup _ _ _ v bidx, simp [hl, list.nodup_append] at this, simp [list.nodup_append, this, hvnd, djuv, djwv.symm] }, { rw [bkts', array.read_write_of_ne _ _ h], apply v.nodup } } end end theorem valid.replace_aux (a : α) (b : β a) : Π (l : list (Σ a, β a)), a ∈ l.map sigma.fst → ∃ (u w : list Σ a, β a) b', l = u ++ [⟨a, b'⟩] ++ w ∧ replace_aux a b l = u ++ [⟨a, b⟩] ++ w | [] := false.elim | (⟨a', b'⟩::t) := begin by_cases e : a' = a, { subst a', suffices : ∃ (u w : list Σ a, β a) (b'' : β a), (sigma.mk a b') :: t = u ++ ⟨a, b''⟩ :: w ∧ replace_aux a b (⟨a, b'⟩ :: t) = u ++ ⟨a, b⟩ :: w, {simpa}, refine ⟨[], t, b', _⟩, simp [replace_aux] }, { suffices : ∀ (x : β a) (_ : sigma.mk a x ∈ t), ∃ u w (b'' : β a), (sigma.mk a' b') :: t = u ++ ⟨a, b''⟩ :: w ∧ (sigma.mk a' b') :: (replace_aux a b t) = u ++ ⟨a, b⟩ :: w, { simpa [replace_aux, ne.symm e, e] }, intros x m, have IH : ∀ (x : β a) (_ : sigma.mk a x ∈ t), ∃ u w (b'' : β a), t = u ++ ⟨a, b''⟩ :: w ∧ replace_aux a b t = u ++ ⟨a, b⟩ :: w, { simpa using valid.replace_aux t }, rcases IH x m with ⟨u, w, b'', hl, hfl⟩, exact ⟨⟨a', b'⟩ :: u, w, b'', by simp [hl, hfl.symm, ne.symm e]⟩ } end theorem valid.replace {n : ℕ+} {bkts : bucket_array α β n} {sz : ℕ} (a : α) (b : β a) (Hc : contains_aux a (bkts.read hash_fn a)) (v : valid bkts sz) : valid (bkts.modify hash_fn a (replace_aux a b)) sz := begin have nd := v.nodup (mk_idx n (hash_fn a)), rcases hash_map.valid.replace_aux a b (array.read bkts (mk_idx n (hash_fn a))) ((contains_aux_iff nd).1 Hc) with ⟨u, w, b', hl, hfl⟩, simp [hl, list.nodup_append] at nd, refine (v.modify hash_fn u [⟨a, b'⟩] [⟨a, b⟩] w hl hfl (list.nodup_singleton _) (λa' e, by simp at e; rw e) (λa' e1 e2, _) (λa' e1 e2, _)).2; { revert e1, simp [-sigma.exists] at e2, subst a', simp [nd] } end theorem valid.insert {n : ℕ+} {bkts : bucket_array α β n} {sz : ℕ} (a : α) (b : β a) (Hnc : ¬ contains_aux a (bkts.read hash_fn a)) (v : valid bkts sz) : valid (reinsert_aux bkts a b) (sz+1) := begin have nd := v.nodup (mk_idx n (hash_fn a)), refine (v.modify hash_fn [] [] [⟨a, b⟩] (bkts.read hash_fn a) rfl rfl (list.nodup_singleton _) (λa' e, by simp at e; rw e) (λa', false.elim) (λa' e1 e2, _)).2, simp [-sigma.exists] at e2, subst a', exact Hnc ((contains_aux_iff nd).2 e1) end theorem valid.erase_aux (a : α) : Π (l : list (Σ a, β a)), a ∈ l.map sigma.fst → ∃ (u w : list Σ a, β a) b, l = u ++ [⟨a, b⟩] ++ w ∧ erase_aux a l = u ++ [] ++ w | [] := false.elim | (⟨a', b'⟩::t) := begin by_cases e : a' = a, { subst a', simpa [erase_aux, and_comm] using show ∃ u w (x : β a), t = u ++ w ∧ (sigma.mk a b') :: t = u ++ ⟨a, x⟩ :: w, from ⟨[], t, b', by simp⟩ }, { simp [erase_aux, e, ne.symm e], suffices : ∀ (b : β a) (_ : sigma.mk a b ∈ t), ∃ u w (x : β a), (sigma.mk a' b') :: t = u ++ ⟨a, x⟩ :: w ∧ (sigma.mk a' b') :: (erase_aux a t) = u ++ w, { simpa [replace_aux, ne.symm e, e] }, intros b m, have IH : ∀ (x : β a) (_ : sigma.mk a x ∈ t), ∃ u w (x : β a), t = u ++ ⟨a, x⟩ :: w ∧ erase_aux a t = u ++ w, { simpa using valid.erase_aux t }, rcases IH b m with ⟨u, w, b'', hl, hfl⟩, exact ⟨⟨a', b'⟩ :: u, w, b'', by simp [hl, hfl.symm]⟩ } end theorem valid.erase {n} {bkts : bucket_array α β n} {sz} (a : α) (Hc : contains_aux a (bkts.read hash_fn a)) (v : valid bkts sz) : valid (bkts.modify hash_fn a (erase_aux a)) (sz-1) := begin have nd := v.nodup (mk_idx n (hash_fn a)), rcases hash_map.valid.erase_aux a (array.read bkts (mk_idx n (hash_fn a))) ((contains_aux_iff nd).1 Hc) with ⟨u, w, b, hl, hfl⟩, refine (v.modify hash_fn u [⟨a, b⟩] [] w hl hfl list.nodup_nil _ _ _).2; simp end end end hash_map /-- A hash map data structure, representing a finite key-value map with key type `α` and value type `β` (which may depend on `α`). -/ structure hash_map (α : Type u) [decidable_eq α] (β : α → Type v) := (hash_fn : α → nat) (size : ℕ) (nbuckets : ℕ+) (buckets : bucket_array α β nbuckets) (is_valid : hash_map.valid hash_fn buckets size) /-- Construct an empty hash map with buffer size `nbuckets` (default 8). -/ def mk_hash_map {α : Type u} [decidable_eq α] {β : α → Type v} (hash_fn : α → nat) (nbuckets := 8) : hash_map α β := let n := if nbuckets = 0 then 8 else nbuckets in let nz : n > 0 := by abstract { cases nbuckets; simp [if_pos, nat.succ_ne_zero] } in { hash_fn := hash_fn, size := 0, nbuckets := ⟨n, nz⟩, buckets := mk_array n [], is_valid := hash_map.mk_valid _ _ } namespace hash_map variables {α : Type u} {β : α → Type v} [decidable_eq α] /-- Return the value corresponding to a key, or `none` if not found -/ def find (m : hash_map α β) (a : α) : option (β a) := find_aux a (m.buckets.read m.hash_fn a) /-- Return `tt` if the key exists in the map -/ def contains (m : hash_map α β) (a : α) : bool := (m.find a).is_some instance : has_mem α (hash_map α β) := ⟨λa m, m.contains a⟩ /-- Fold a function over the key-value pairs in the map -/ def fold {δ : Type w} (m : hash_map α β) (d : δ) (f : δ → Π a, β a → δ) : δ := m.buckets.foldl d f /-- The list of key-value pairs in the map -/ def entries (m : hash_map α β) : list Σ a, β a := m.buckets.as_list /-- The list of keys in the map -/ def keys (m : hash_map α β) : list α := m.entries.map sigma.fst theorem find_iff (m : hash_map α β) (a : α) (b : β a) : m.find a = some b ↔ sigma.mk a b ∈ m.entries := m.is_valid.find_aux_iff _ theorem contains_iff (m : hash_map α β) (a : α) : m.contains a ↔ a ∈ m.keys := m.is_valid.contains_aux_iff _ _ theorem entries_empty (hash_fn : α → nat) (n) : (@mk_hash_map α _ β hash_fn n).entries = [] := mk_as_list _ theorem keys_empty (hash_fn : α → nat) (n) : (@mk_hash_map α _ β hash_fn n).keys = [] := by dsimp [keys]; rw entries_empty; refl theorem find_empty (hash_fn : α → nat) (n a) : (@mk_hash_map α _ β hash_fn n).find a = none := by induction h : (@mk_hash_map α _ β hash_fn n).find a; [refl, { have := (find_iff _ _ _).1 h, rw entries_empty at this, contradiction }] theorem not_contains_empty (hash_fn : α → nat) (n a) : ¬ (@mk_hash_map α _ β hash_fn n).contains a := by apply bool_iff_false.2; dsimp [contains]; rw [find_empty]; refl theorem insert_lemma (hash_fn : α → nat) {n n'} {bkts : bucket_array α β n} {sz} (v : valid hash_fn bkts sz) : valid hash_fn (bkts.foldl (mk_array _ [] : bucket_array α β n') (reinsert_aux hash_fn)) sz := begin suffices : ∀ (l : list Σ a, β a) (t : bucket_array α β n') sz, valid hash_fn t sz → ((l ++ t.as_list).map sigma.fst).nodup → valid hash_fn (l.foldl (λr (a : Σ a, β a), reinsert_aux hash_fn r a.1 a.2) t) (sz + l.length), { have p := this bkts.as_list _ _ (mk_valid _ _), rw [mk_as_list, list.append_nil, zero_add, v.len] at p, rw bucket_array.foldl_eq, exact p (v.as_list_nodup _) }, intro l, induction l with c l IH; intros t sz v nd, {exact v}, rw show sz + (c :: l).length = sz + 1 + l.length, by simp [add_comm, add_assoc], rcases (show (l.map sigma.fst).nodup ∧ ((bucket_array.as_list t).map sigma.fst).nodup ∧ c.fst ∉ l.map sigma.fst ∧ c.fst ∉ (bucket_array.as_list t).map sigma.fst ∧ (l.map sigma.fst).disjoint ((bucket_array.as_list t).map sigma.fst), by simpa [list.nodup_append, not_or_distrib, and_comm, and.left_comm] using nd) with ⟨nd1, nd2, nm1, nm2, dj⟩, have v' := v.insert _ _ c.2 (λHc, nm2 $ (v.contains_aux_iff _ c.1).1 Hc), apply IH _ _ v', suffices : ∀ ⦃a : α⦄ (b : β a), sigma.mk a b ∈ l → ∀ (b' : β a), sigma.mk a b' ∈ (reinsert_aux hash_fn t c.1 c.2).as_list → false, { simpa [list.nodup_append, nd1, v'.as_list_nodup _, list.disjoint] }, intros a b m1 b' m2, rcases (reinsert_aux hash_fn t c.1 c.2).mem_as_list.1 m2 with ⟨i, im⟩, have : sigma.mk a b' ∉ array.read t i, { intro m3, have : a ∈ list.map sigma.fst t.as_list := list.mem_map_of_mem sigma.fst (t.mem_as_list.2 ⟨_, m3⟩), exact dj (list.mem_map_of_mem sigma.fst m1) this }, by_cases h : mk_idx n' (hash_fn c.1) = i, { subst h, have e : sigma.mk a b' = ⟨c.1, c.2⟩, { simpa [reinsert_aux, bucket_array.modify, array.read_write, this] using im }, injection e with e, subst a, exact nm1.elim (@list.mem_map_of_mem _ _ sigma.fst _ _ m1) }, { apply this, simpa [reinsert_aux, bucket_array.modify, array.read_write_of_ne _ _ h] using im } end /-- Insert a key-value pair into the map. (Modifies `m` in-place when applicable) -/ def insert : Π (m : hash_map α β) (a : α) (b : β a), hash_map α β | ⟨hash_fn, size, n, buckets, v⟩ a b := let bkt := buckets.read hash_fn a in if hc : contains_aux a bkt then { hash_fn := hash_fn, size := size, nbuckets := n, buckets := buckets.modify hash_fn a (replace_aux a b), is_valid := v.replace _ a b hc } else let size' := size + 1, buckets' := buckets.modify hash_fn a (λl, ⟨a, b⟩::l), valid' := v.insert _ a b hc in if size' ≤ n then { hash_fn := hash_fn, size := size', nbuckets := n, buckets := buckets', is_valid := valid' } else let n' : ℕ+ := ⟨n * 2, mul_pos n.2 dec_trivial⟩, buckets'' : bucket_array α β n' := buckets'.foldl (mk_array _ []) (reinsert_aux hash_fn) in { hash_fn := hash_fn, size := size', nbuckets := n', buckets := buckets'', is_valid := insert_lemma _ valid' } theorem mem_insert : Π (m : hash_map α β) (a b a' b'), (sigma.mk a' b' : sigma β) ∈ (m.insert a b).entries ↔ if a = a' then b == b' else sigma.mk a' b' ∈ m.entries | ⟨hash_fn, size, n, bkts, v⟩ a b a' b' := begin let bkt := bkts.read hash_fn a, have nd : (bkt.map sigma.fst).nodup := v.nodup (mk_idx n (hash_fn a)), have lem : Π (bkts' : bucket_array α β n) (v1 u w) (hl : bucket_array.as_list bkts = u ++ v1 ++ w) (hfl : bucket_array.as_list bkts' = u ++ [⟨a, b⟩] ++ w) (veq : (v1 = [] ∧ ¬ contains_aux a bkt) ∨ ∃b'', v1 = [⟨a, b''⟩]), sigma.mk a' b' ∈ bkts'.as_list ↔ if a = a' then b == b' else sigma.mk a' b' ∈ bkts.as_list, { intros bkts' v1 u w hl hfl veq, rw [hl, hfl], by_cases h : a = a', { subst a', suffices : b = b' ∨ sigma.mk a b' ∈ u ∨ sigma.mk a b' ∈ w ↔ b = b', { simpa [eq_comm, or.left_comm] }, refine or_iff_left_of_imp (not.elim $ not_or_distrib.2 _), rcases veq with ⟨rfl, Hnc⟩ | ⟨b'', rfl⟩, { have na := (not_iff_not_of_iff $ v.contains_aux_iff _ _).1 Hnc, simp [hl, not_or_distrib] at na, simp [na] }, { have nd' := v.as_list_nodup _, simp [hl, list.nodup_append] at nd', simp [nd'] } }, { suffices : sigma.mk a' b' ∉ v1, {simp [h, ne.symm h, this]}, rcases veq with ⟨rfl, Hnc⟩ | ⟨b'', rfl⟩; simp [ne.symm h] } }, by_cases Hc : (contains_aux a bkt : Prop), { rcases hash_map.valid.replace_aux a b (array.read bkts (mk_idx n (hash_fn a))) ((contains_aux_iff nd).1 Hc) with ⟨u', w', b'', hl', hfl'⟩, rcases (append_of_modify u' [⟨a, b''⟩] [⟨a, b⟩] w' hl' hfl') with ⟨u, w, hl, hfl⟩, simpa [insert, @dif_pos (contains_aux a bkt) _ Hc] using lem _ _ u w hl hfl (or.inr ⟨b'', rfl⟩) }, { let size' := size + 1, let bkts' := bkts.modify hash_fn a (λl, ⟨a, b⟩::l), have mi : sigma.mk a' b' ∈ bkts'.as_list ↔ if a = a' then b == b' else sigma.mk a' b' ∈ bkts.as_list := let ⟨u, w, hl, hfl⟩ := append_of_modify [] [] [⟨a, b⟩] _ rfl rfl in lem bkts' _ u w hl hfl $ or.inl ⟨rfl, Hc⟩, simp [insert, @dif_neg (contains_aux a bkt) _ Hc], by_cases h : size' ≤ n, { simpa [show size' ≤ n, from h] using mi }, { let n' : ℕ+ := ⟨n * 2, mul_pos n.2 dec_trivial⟩, let bkts'' : bucket_array α β n' := bkts'.foldl (mk_array _ []) (reinsert_aux hash_fn), suffices : sigma.mk a' b' ∈ bkts''.as_list ↔ sigma.mk a' b' ∈ bkts'.as_list.reverse, { simpa [show ¬ size' ≤ n, from h, mi] }, rw [show bkts'' = bkts'.as_list.foldl _ _, from bkts'.foldl_eq _ _, ← list.foldr_reverse], induction bkts'.as_list.reverse with a l IH, { simp [mk_as_list] }, { cases a with a'' b'', let B := l.foldr (λ (y : sigma β) (x : bucket_array α β n'), reinsert_aux hash_fn x y.1 y.2) (mk_array n' []), rcases append_of_modify [] [] [⟨a'', b''⟩] _ rfl rfl with ⟨u, w, hl, hfl⟩, simp [IH.symm, or.left_comm, show B.as_list = _, from hl, show (reinsert_aux hash_fn B a'' b'').as_list = _, from hfl] } } } end theorem find_insert_eq (m : hash_map α β) (a : α) (b : β a) : (m.insert a b).find a = some b := (find_iff (m.insert a b) a b).2 $ (mem_insert m a b a b).2 $ by rw if_pos rfl theorem find_insert_ne (m : hash_map α β) (a a' : α) (b : β a) (h : a ≠ a') : (m.insert a b).find a' = m.find a' := option.eq_of_eq_some $ λb', let t := mem_insert m a b a' b' in (find_iff _ _ _).trans $ iff.trans (by rwa if_neg h at t) (find_iff _ _ _).symm theorem find_insert (m : hash_map α β) (a' a : α) (b : β a) : (m.insert a b).find a' = if h : a = a' then some (eq.rec_on h b) else m.find a' := if h : a = a' then by rw dif_pos h; exact match a', h with ._, rfl := find_insert_eq m a b end else by rw dif_neg h; exact find_insert_ne m a a' b h /-- Insert a list of key-value pairs into the map. (Modifies `m` in-place when applicable) -/ def insert_all (l : list (Σ a, β a)) (m : hash_map α β) : hash_map α β := l.foldl (λ m ⟨a, b⟩, insert m a b) m /-- Construct a hash map from a list of key-value pairs. -/ def of_list (l : list (Σ a, β a)) (hash_fn) : hash_map α β := insert_all l (mk_hash_map hash_fn (2 * l.length)) /-- Remove a key from the map. (Modifies `m` in-place when applicable) -/ def erase (m : hash_map α β) (a : α) : hash_map α β := match m with ⟨hash_fn, size, n, buckets, v⟩ := if hc : contains_aux a (buckets.read hash_fn a) then { hash_fn := hash_fn, size := size - 1, nbuckets := n, buckets := buckets.modify hash_fn a (erase_aux a), is_valid := v.erase _ a hc } else m end theorem mem_erase : Π (m : hash_map α β) (a a' b'), (sigma.mk a' b' : sigma β) ∈ (m.erase a).entries ↔ a ≠ a' ∧ sigma.mk a' b' ∈ m.entries | ⟨hash_fn, size, n, bkts, v⟩ a a' b' := begin let bkt := bkts.read hash_fn a, by_cases Hc : (contains_aux a bkt : Prop), { let bkts' := bkts.modify hash_fn a (erase_aux a), suffices : sigma.mk a' b' ∈ bkts'.as_list ↔ a ≠ a' ∧ sigma.mk a' b' ∈ bkts.as_list, { simpa [erase, @dif_pos (contains_aux a bkt) _ Hc] }, have nd := v.nodup (mk_idx n (hash_fn a)), rcases valid.erase_aux a bkt ((contains_aux_iff nd).1 Hc) with ⟨u', w', b, hl', hfl'⟩, rcases append_of_modify u' [⟨a, b⟩] [] _ hl' hfl' with ⟨u, w, hl, hfl⟩, suffices : ∀_:sigma.mk a' b' ∈ u ∨ sigma.mk a' b' ∈ w, a ≠ a', { have : sigma.mk a' b' ∈ u ∨ sigma.mk a' b' ∈ w ↔ (¬a = a' ∧ a' = a) ∧ b' == b ∨ ¬a = a' ∧ (sigma.mk a' b' ∈ u ∨ sigma.mk a' b' ∈ w), { simp [eq_comm, not_and_self_iff, and_iff_right_of_imp this] }, simpa [hl, show bkts'.as_list = _, from hfl, and_or_distrib_left, and_comm, and.left_comm, or.left_comm] }, intros m e, subst a', revert m, apply not_or_distrib.2, have nd' := v.as_list_nodup _, simp [hl, list.nodup_append] at nd', simp [nd'] }, { suffices : ∀_:sigma.mk a' b' ∈ bucket_array.as_list bkts, a ≠ a', { simp [erase, @dif_neg (contains_aux a bkt) _ Hc, entries, and_iff_right_of_imp this] }, intros m e, subst a', exact Hc ((v.contains_aux_iff _ _).2 (list.mem_map_of_mem sigma.fst m)) } end theorem find_erase_eq (m : hash_map α β) (a : α) : (m.erase a).find a = none := begin cases h : (m.erase a).find a with b, {refl}, exact absurd rfl ((mem_erase m a a b).1 ((find_iff (m.erase a) a b).1 h)).left end theorem find_erase_ne (m : hash_map α β) (a a' : α) (h : a ≠ a') : (m.erase a).find a' = m.find a' := option.eq_of_eq_some $ λb', (find_iff _ _ _).trans $ (mem_erase m a a' b').trans $ (and_iff_right h).trans (find_iff _ _ _).symm theorem find_erase (m : hash_map α β) (a' a : α) : (m.erase a).find a' = if a = a' then none else m.find a' := if h : a = a' then by subst a'; simp [find_erase_eq m a] else by rw if_neg h; exact find_erase_ne m a a' h section string variables [has_to_string α] [∀ a, has_to_string (β a)] open prod private def key_data_to_string (a : α) (b : β a) (first : bool) : string := (if first then "" else ", ") ++ sformat!"{a} ← {b}" private def to_string (m : hash_map α β) : string := "⟨" ++ (fst (fold m ("", tt) (λ p a b, (fst p ++ key_data_to_string a b (snd p), ff)))) ++ "⟩" instance : has_to_string (hash_map α β) := ⟨to_string⟩ end string section format open format prod variables [has_to_format α] [∀ a, has_to_format (β a)] private meta def format_key_data (a : α) (b : β a) (first : bool) : format := (if first then to_fmt "" else to_fmt "," ++ line) ++ to_fmt a ++ space ++ to_fmt "←" ++ space ++ to_fmt b private meta def to_format (m : hash_map α β) : format := group $ to_fmt "⟨" ++ nest 1 (fst (fold m (to_fmt "", tt) (λ p a b, (fst p ++ format_key_data a b (snd p), ff)))) ++ to_fmt "⟩" meta instance : has_to_format (hash_map α β) := ⟨to_format⟩ end format /-- `hash_map` with key type `nat` and value type that may vary. -/ instance {β : ℕ → Type*} : inhabited (hash_map ℕ β) := ⟨mk_hash_map id⟩ end hash_map
d81fb26acd532ae7a1e6e4d312f1f3bc74c889cf
b70447c014d9e71cf619ebc9f539b262c19c2e0b
/hott/init/equiv.hlean
601561b5935e1561c6c34680315fb79c5e4efe73
[ "Apache-2.0" ]
permissive
ia0/lean2
c20d8da69657f94b1d161f9590a4c635f8dc87f3
d86284da630acb78fa5dc3b0b106153c50ffccd0
refs/heads/master
1,611,399,322,751
1,495,751,007,000
1,495,751,007,000
93,104,167
0
0
null
1,496,355,488,000
1,496,355,487,000
null
UTF-8
Lean
false
false
18,785
hlean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad, Jakob von Raumer, Floris van Doorn Ported from Coq HoTT -/ prelude import .path .function open eq function lift /- Equivalences -/ -- This is our definition of equivalence. In the HoTT-book it's called -- ihae (half-adjoint equivalence). structure is_equiv [class] {A B : Type} (f : A → B) := mk' :: (inv : B → A) (right_inv : Πb, f (inv b) = b) (left_inv : Πa, inv (f a) = a) (adj : Πx, right_inv (f x) = ap f (left_inv x)) attribute is_equiv.inv [reducible] -- A more bundled version of equivalence structure equiv (A B : Type) := (to_fun : A → B) (to_is_equiv : is_equiv to_fun) namespace is_equiv /- Some instances and closure properties of equivalences -/ postfix ⁻¹ := inv /- a second notation for the inverse, which is not overloaded -/ postfix [parsing_only] `⁻¹ᶠ`:std.prec.max_plus := inv section variables {A B C : Type} (g : B → C) (f : A → B) {f' : A → B} -- The variant of mk' where f is explicit. protected definition mk [constructor] := @is_equiv.mk' A B f -- The identity function is an equivalence. definition is_equiv_id [instance] [constructor] (A : Type) : (is_equiv (id : A → A)) := is_equiv.mk id id (λa, idp) (λa, idp) (λa, idp) -- The composition of two equivalences is, again, an equivalence. definition is_equiv_compose [constructor] [Hf : is_equiv f] [Hg : is_equiv g] : is_equiv (g ∘ f) := is_equiv.mk (g ∘ f) (f⁻¹ ∘ g⁻¹) abstract (λc, ap g (right_inv f (g⁻¹ c)) ⬝ right_inv g c) end abstract (λa, ap (inv f) (left_inv g (f a)) ⬝ left_inv f a) end abstract (λa, (whisker_left _ (adj g (f a))) ⬝ (ap_con g _ _)⁻¹ ⬝ ap02 g ((ap_con_eq_con (right_inv f) (left_inv g (f a)))⁻¹ ⬝ (ap_compose f (inv f) _ ◾ adj f a) ⬝ (ap_con f _ _)⁻¹ ) ⬝ (ap_compose g f _)⁻¹) end -- Any function equal to an equivalence is an equivlance as well. variable {f} definition is_equiv_eq_closed [Hf : is_equiv f] (Heq : f = f') : is_equiv f' := eq.rec_on Heq Hf end section parameters {A B : Type} (f : A → B) (g : B → A) (ret : Πb, f (g b) = b) (sec : Πa, g (f a) = a) definition adjointify_left_inv' [unfold_full] (a : A) : g (f a) = a := ap g (ap f (inverse (sec a))) ⬝ ap g (ret (f a)) ⬝ sec a theorem adjointify_adj' (a : A) : ret (f a) = ap f (adjointify_left_inv' a) := let fgretrfa := ap f (ap g (ret (f a))) in let fgfinvsect := ap f (ap g (ap f (sec a)⁻¹)) in let fgfa := f (g (f a)) in let retrfa := ret (f a) in have eq1 : ap f (sec a) = _, from calc ap f (sec a) = idp ⬝ ap f (sec a) : by rewrite idp_con ... = (ret (f a) ⬝ (ret (f a))⁻¹) ⬝ ap f (sec a) : by rewrite con.right_inv ... = ((ret fgfa)⁻¹ ⬝ ap (f ∘ g) (ret (f a))) ⬝ ap f (sec a) : by rewrite con_ap_eq_con ... = ((ret fgfa)⁻¹ ⬝ fgretrfa) ⬝ ap f (sec a) : by rewrite ap_compose ... = (ret fgfa)⁻¹ ⬝ (fgretrfa ⬝ ap f (sec a)) : by rewrite con.assoc, have eq2 : ap f (sec a) ⬝ idp = (ret fgfa)⁻¹ ⬝ (fgretrfa ⬝ ap f (sec a)), from !con_idp ⬝ eq1, have eq3 : idp = _, from calc idp = (ap f (sec a))⁻¹ ⬝ ((ret fgfa)⁻¹ ⬝ (fgretrfa ⬝ ap f (sec a))) : eq_inv_con_of_con_eq eq2 ... = ((ap f (sec a))⁻¹ ⬝ (ret fgfa)⁻¹) ⬝ (fgretrfa ⬝ ap f (sec a)) : by rewrite con.assoc' ... = (ap f (sec a)⁻¹ ⬝ (ret fgfa)⁻¹) ⬝ (fgretrfa ⬝ ap f (sec a)) : by rewrite ap_inv ... = ((ap f (sec a)⁻¹ ⬝ (ret fgfa)⁻¹) ⬝ fgretrfa) ⬝ ap f (sec a) : by rewrite con.assoc' ... = ((retrfa⁻¹ ⬝ ap (f ∘ g) (ap f (sec a)⁻¹)) ⬝ fgretrfa) ⬝ ap f (sec a) : by rewrite con_ap_eq_con ... = ((retrfa⁻¹ ⬝ fgfinvsect) ⬝ fgretrfa) ⬝ ap f (sec a) : by rewrite ap_compose ... = (retrfa⁻¹ ⬝ (fgfinvsect ⬝ fgretrfa)) ⬝ ap f (sec a) : by rewrite con.assoc' ... = retrfa⁻¹ ⬝ ap f (ap g (ap f (sec a)⁻¹) ⬝ ap g (ret (f a))) ⬝ ap f (sec a) : by rewrite ap_con ... = retrfa⁻¹ ⬝ (ap f (ap g (ap f (sec a)⁻¹) ⬝ ap g (ret (f a))) ⬝ ap f (sec a)) : by rewrite con.assoc' ... = retrfa⁻¹ ⬝ ap f ((ap g (ap f (sec a)⁻¹) ⬝ ap g (ret (f a))) ⬝ sec a) : by rewrite -ap_con, show ret (f a) = ap f ((ap g (ap f (sec a)⁻¹) ⬝ ap g (ret (f a))) ⬝ sec a), from eq_of_idp_eq_inv_con eq3 definition adjointify [constructor] : is_equiv f := is_equiv.mk f g ret adjointify_left_inv' adjointify_adj' end -- Any function pointwise equal to an equivalence is an equivalence as well. definition homotopy_closed [constructor] {A B : Type} (f : A → B) {f' : A → B} [Hf : is_equiv f] (Hty : f ~ f') : is_equiv f' := adjointify f' (inv f) (λ b, (Hty (inv f b))⁻¹ ⬝ right_inv f b) (λ a, (ap (inv f) (Hty a))⁻¹ ⬝ left_inv f a) definition inv_homotopy_closed [constructor] {A B : Type} {f : A → B} {f' : B → A} [Hf : is_equiv f] (Hty : f⁻¹ ~ f') : is_equiv f := adjointify f f' (λ b, ap f !Hty⁻¹ ⬝ right_inv f b) (λ a, !Hty⁻¹ ⬝ left_inv f a) definition is_equiv_up [instance] [constructor] (A : Type) : is_equiv (up : A → lift A) := adjointify up down (λa, by induction a;reflexivity) (λa, idp) section variables {A B C : Type} (f : A → B) {f' : A → B} [Hf : is_equiv f] (g : B → C) include Hf -- The function equiv_rect says that given an equivalence f : A → B, -- and a hypothesis from B, one may always assume that the hypothesis -- is in the image of e. -- In fibrational terms, if we have a fibration over B which has a section -- once pulled back along an equivalence f : A → B, then it has a section -- over all of B. definition is_equiv_rect (P : B → Type) (g : Πa, P (f a)) (b : B) : P b := right_inv f b ▸ g (f⁻¹ b) definition is_equiv_rect' (P : A → B → Type) (g : Πb, P (f⁻¹ b) b) (a : A) : P a (f a) := left_inv f a ▸ g (f a) definition is_equiv_rect_comp (P : B → Type) (df : Π (x : A), P (f x)) (x : A) : is_equiv_rect f P df (f x) = df x := calc is_equiv_rect f P df (f x) = right_inv f (f x) ▸ df (f⁻¹ (f x)) : by esimp ... = ap f (left_inv f x) ▸ df (f⁻¹ (f x)) : by rewrite -adj ... = left_inv f x ▸ df (f⁻¹ (f x)) : by rewrite -tr_compose ... = df x : by rewrite (apdt df (left_inv f x)) theorem adj_inv (b : B) : left_inv f (f⁻¹ b) = ap f⁻¹ (right_inv f b) := is_equiv_rect f _ (λa, eq.cancel_right (left_inv f (id a)) (whisker_left _ !ap_id⁻¹ ⬝ (ap_con_eq_con_ap (left_inv f) (left_inv f a))⁻¹) ⬝ !ap_compose ⬝ ap02 f⁻¹ (adj f a)⁻¹) b --The inverse of an equivalence is, again, an equivalence. definition is_equiv_inv [instance] [constructor] [priority 500] : is_equiv f⁻¹ := is_equiv.mk f⁻¹ f (left_inv f) (right_inv f) (adj_inv f) -- The 2-out-of-3 properties definition cancel_right (g : B → C) [Hgf : is_equiv (g ∘ f)] : (is_equiv g) := have Hfinv : is_equiv f⁻¹, from is_equiv_inv f, @homotopy_closed _ _ _ _ (is_equiv_compose (g ∘ f) f⁻¹) (λb, ap g (@right_inv _ _ f _ b)) definition cancel_left (g : C → A) [Hgf : is_equiv (f ∘ g)] : (is_equiv g) := have Hfinv : is_equiv f⁻¹, from is_equiv_inv f, @homotopy_closed _ _ _ _ (is_equiv_compose f⁻¹ (f ∘ g)) (λa, left_inv f (g a)) definition eq_of_fn_eq_fn' [unfold 4] {x y : A} (q : f x = f y) : x = y := (left_inv f x)⁻¹ ⬝ ap f⁻¹ q ⬝ left_inv f y definition ap_eq_of_fn_eq_fn' {x y : A} (q : f x = f y) : ap f (eq_of_fn_eq_fn' f q) = q := !ap_con ⬝ whisker_right _ !ap_con ⬝ ((!ap_inv ⬝ inverse2 (adj f _)⁻¹) ◾ (inverse (ap_compose f f⁻¹ _)) ◾ (adj f _)⁻¹) ⬝ con_ap_con_eq_con_con (right_inv f) _ _ ⬝ whisker_right _ !con.left_inv ⬝ !idp_con definition eq_of_fn_eq_fn'_ap {x y : A} (q : x = y) : eq_of_fn_eq_fn' f (ap f q) = q := by induction q; apply con.left_inv definition is_equiv_ap [instance] [constructor] (x y : A) : is_equiv (ap f : x = y → f x = f y) := adjointify (ap f) (eq_of_fn_eq_fn' f) (ap_eq_of_fn_eq_fn' f) (eq_of_fn_eq_fn'_ap f) end section variables {A B C : Type} {f : A → B} [Hf : is_equiv f] include Hf section rewrite_rules variables {a : A} {b : B} definition eq_of_eq_inv (p : a = f⁻¹ b) : f a = b := ap f p ⬝ right_inv f b definition eq_of_inv_eq (p : f⁻¹ b = a) : b = f a := (eq_of_eq_inv p⁻¹)⁻¹ definition inv_eq_of_eq (p : b = f a) : f⁻¹ b = a := ap f⁻¹ p ⬝ left_inv f a definition eq_inv_of_eq (p : f a = b) : a = f⁻¹ b := (inv_eq_of_eq p⁻¹)⁻¹ end rewrite_rules variable (f) section pre_compose variables (α : A → C) (β : B → C) definition homotopy_of_homotopy_inv_pre (p : β ~ α ∘ f⁻¹) : β ∘ f ~ α := λ a, p (f a) ⬝ ap α (left_inv f a) definition homotopy_of_inv_homotopy_pre (p : α ∘ f⁻¹ ~ β) : α ~ β ∘ f := λ a, (ap α (left_inv f a))⁻¹ ⬝ p (f a) definition inv_homotopy_of_homotopy_pre (p : α ~ β ∘ f) : α ∘ f⁻¹ ~ β := λ b, p (f⁻¹ b) ⬝ ap β (right_inv f b) definition homotopy_inv_of_homotopy_pre (p : β ∘ f ~ α) : β ~ α ∘ f⁻¹ := λ b, (ap β (right_inv f b))⁻¹ ⬝ p (f⁻¹ b) end pre_compose section post_compose variables (α : C → A) (β : C → B) definition homotopy_of_homotopy_inv_post (p : α ~ f⁻¹ ∘ β) : f ∘ α ~ β := λ c, ap f (p c) ⬝ (right_inv f (β c)) definition homotopy_of_inv_homotopy_post (p : f⁻¹ ∘ β ~ α) : β ~ f ∘ α := λ c, (right_inv f (β c))⁻¹ ⬝ ap f (p c) definition inv_homotopy_of_homotopy_post (p : β ~ f ∘ α) : f⁻¹ ∘ β ~ α := λ c, ap f⁻¹ (p c) ⬝ (left_inv f (α c)) definition homotopy_inv_of_homotopy_post (p : f ∘ α ~ β) : α ~ f⁻¹ ∘ β := λ c, (left_inv f (α c))⁻¹ ⬝ ap f⁻¹ (p c) end post_compose end --Transporting is an equivalence definition is_equiv_tr [constructor] {A : Type} (P : A → Type) {x y : A} (p : x = y) : (is_equiv (transport P p)) := is_equiv.mk _ (transport P p⁻¹) (tr_inv_tr p) (inv_tr_tr p) (tr_inv_tr_lemma p) -- a version where the transport is a cast. Note: A and B live in the same universe here. definition is_equiv_cast [constructor] {A B : Type} (H : A = B) : is_equiv (cast H) := is_equiv_tr (λX, X) H section variables {A : Type} {B C : A → Type} (f : Π{a}, B a → C a) [H : Πa, is_equiv (@f a)] {g : A → A} {g' : A → A} (h : Π{a}, B (g' a) → B (g a)) (h' : Π{a}, C (g' a) → C (g a)) include H definition inv_commute' (p : Π⦃a : A⦄ (b : B (g' a)), f (h b) = h' (f b)) {a : A} (c : C (g' a)) : f⁻¹ (h' c) = h (f⁻¹ c) := eq_of_fn_eq_fn' f (right_inv f (h' c) ⬝ ap h' (right_inv f c)⁻¹ ⬝ (p (f⁻¹ c))⁻¹) definition fun_commute_of_inv_commute' (p : Π⦃a : A⦄ (c : C (g' a)), f⁻¹ (h' c) = h (f⁻¹ c)) {a : A} (b : B (g' a)) : f (h b) = h' (f b) := eq_of_fn_eq_fn' f⁻¹ (left_inv f (h b) ⬝ ap h (left_inv f b)⁻¹ ⬝ (p (f b))⁻¹) definition ap_inv_commute' (p : Π⦃a : A⦄ (b : B (g' a)), f (h b) = h' (f b)) {a : A} (c : C (g' a)) : ap f (inv_commute' @f @h @h' p c) = right_inv f (h' c) ⬝ ap h' (right_inv f c)⁻¹ ⬝ (p (f⁻¹ c))⁻¹ := !ap_eq_of_fn_eq_fn' -- inv_commute'_fn is in types.equiv end -- This is inv_commute' for A ≡ unit definition inv_commute1' {B C : Type} (f : B → C) [is_equiv f] (h : B → B) (h' : C → C) (p : Π(b : B), f (h b) = h' (f b)) (c : C) : f⁻¹ (h' c) = h (f⁻¹ c) := eq_of_fn_eq_fn' f (right_inv f (h' c) ⬝ ap h' (right_inv f c)⁻¹ ⬝ (p (f⁻¹ c))⁻¹) end is_equiv open is_equiv namespace eq local attribute is_equiv_tr [instance] definition tr_inv_fn {A : Type} {B : A → Type} {a a' : A} (p : a = a') : transport B p⁻¹ = (transport B p)⁻¹ := idp definition tr_inv {A : Type} {B : A → Type} {a a' : A} (p : a = a') (b : B a') : p⁻¹ ▸ b = (transport B p)⁻¹ b := idp definition cast_inv_fn {A B : Type} (p : A = B) : cast p⁻¹ = (cast p)⁻¹ := idp definition cast_inv {A B : Type} (p : A = B) (b : B) : cast p⁻¹ b = (cast p)⁻¹ b := idp end eq infix ` ≃ `:25 := equiv attribute equiv.to_is_equiv [instance] namespace equiv attribute to_fun [coercion] section variables {A B C : Type} protected definition MK [reducible] [constructor] (f : A → B) (g : B → A) (right_inv : Πb, f (g b) = b) (left_inv : Πa, g (f a) = a) : A ≃ B := equiv.mk f (adjointify f g right_inv left_inv) definition to_inv [reducible] [unfold 3] (f : A ≃ B) : B → A := f⁻¹ definition to_right_inv [reducible] [unfold 3] (f : A ≃ B) (b : B) : f (f⁻¹ b) = b := right_inv f b definition to_left_inv [reducible] [unfold 3] (f : A ≃ B) (a : A) : f⁻¹ (f a) = a := left_inv f a protected definition rfl [refl] [constructor] : A ≃ A := equiv.mk id !is_equiv_id protected definition refl [constructor] [reducible] (A : Type) : A ≃ A := @equiv.rfl A protected definition symm [symm] [constructor] (f : A ≃ B) : B ≃ A := equiv.mk f⁻¹ !is_equiv_inv protected definition trans [trans] [constructor] (f : A ≃ B) (g : B ≃ C) : A ≃ C := equiv.mk (g ∘ f) !is_equiv_compose infixl ` ⬝e `:75 := equiv.trans postfix `⁻¹ᵉ`:(max + 1) := equiv.symm -- notation for inverse which is not overloaded abbreviation erfl [constructor] := @equiv.rfl definition to_inv_trans [reducible] [unfold_full] (f : A ≃ B) (g : B ≃ C) : to_inv (f ⬝e g) = to_fun (g⁻¹ᵉ ⬝e f⁻¹ᵉ) := idp definition equiv_change_fun [constructor] (f : A ≃ B) {f' : A → B} (Heq : f ~ f') : A ≃ B := equiv.mk f' (is_equiv.homotopy_closed f Heq) definition equiv_change_inv [constructor] (f : A ≃ B) {f' : B → A} (Heq : f⁻¹ ~ f') : A ≃ B := equiv.mk f (inv_homotopy_closed Heq) --rename: eq_equiv_fn_eq_fn_of_is_equiv definition eq_equiv_fn_eq [constructor] (f : A → B) [H : is_equiv f] (a b : A) : (a = b) ≃ (f a = f b) := equiv.mk (ap f) !is_equiv_ap --rename: eq_equiv_fn_eq_fn definition eq_equiv_fn_eq_of_equiv [constructor] (f : A ≃ B) (a b : A) : (a = b) ≃ (f a = f b) := equiv.mk (ap f) !is_equiv_ap definition equiv_ap [constructor] (P : A → Type) {a b : A} (p : a = b) : P a ≃ P b := equiv.mk (transport P p) !is_equiv_tr definition equiv_of_eq [constructor] {A B : Type} (p : A = B) : A ≃ B := equiv.mk (cast p) !is_equiv_tr definition equiv_of_eq_refl [reducible] [unfold_full] (A : Type) : equiv_of_eq (refl A) = equiv.refl A := idp definition eq_of_fn_eq_fn [unfold 3] (f : A ≃ B) {x y : A} (q : f x = f y) : x = y := (left_inv f x)⁻¹ ⬝ ap f⁻¹ q ⬝ left_inv f y definition eq_of_fn_eq_fn_inv [unfold 3] (f : A ≃ B) {x y : B} (q : f⁻¹ x = f⁻¹ y) : x = y := (right_inv f x)⁻¹ ⬝ ap f q ⬝ right_inv f y definition ap_eq_of_fn_eq_fn (f : A ≃ B) {x y : A} (q : f x = f y) : ap f (eq_of_fn_eq_fn' f q) = q := ap_eq_of_fn_eq_fn' f q definition eq_of_fn_eq_fn_ap (f : A ≃ B) {x y : A} (q : x = y) : eq_of_fn_eq_fn' f (ap f q) = q := eq_of_fn_eq_fn'_ap f q --we need this theorem for the funext_of_ua proof theorem inv_eq {A B : Type} (eqf eqg : A ≃ B) (p : eqf = eqg) : (to_fun eqf)⁻¹ = (to_fun eqg)⁻¹ := eq.rec_on p idp definition equiv_of_equiv_of_eq [trans] {A B C : Type} (p : A = B) (q : B ≃ C) : A ≃ C := equiv_of_eq p ⬝e q definition equiv_of_eq_of_equiv [trans] {A B C : Type} (p : A ≃ B) (q : B = C) : A ≃ C := p ⬝e equiv_of_eq q definition equiv_lift [constructor] (A : Type) : A ≃ lift A := equiv.mk up _ definition equiv_rect (f : A ≃ B) (P : B → Type) (g : Πa, P (f a)) (b : B) : P b := right_inv f b ▸ g (f⁻¹ b) definition equiv_rect' (f : A ≃ B) (P : A → B → Type) (g : Πb, P (f⁻¹ b) b) (a : A) : P a (f a) := left_inv f a ▸ g (f a) definition equiv_rect_comp (f : A ≃ B) (P : B → Type) (df : Π (x : A), P (f x)) (x : A) : equiv_rect f P df (f x) = df x := calc equiv_rect f P df (f x) = right_inv f (f x) ▸ df (f⁻¹ (f x)) : by esimp ... = ap f (left_inv f x) ▸ df (f⁻¹ (f x)) : by rewrite -adj ... = left_inv f x ▸ df (f⁻¹ (f x)) : by rewrite -tr_compose ... = df x : by rewrite (apdt df (left_inv f x)) end section variables {A B : Type} (f : A ≃ B) {a : A} {b : B} definition to_eq_of_eq_inv (p : a = f⁻¹ b) : f a = b := ap f p ⬝ right_inv f b definition to_eq_of_inv_eq (p : f⁻¹ b = a) : b = f a := (eq_of_eq_inv p⁻¹)⁻¹ definition to_inv_eq_of_eq (p : b = f a) : f⁻¹ b = a := ap f⁻¹ p ⬝ left_inv f a definition to_eq_inv_of_eq (p : f a = b) : a = f⁻¹ b := (inv_eq_of_eq p⁻¹)⁻¹ end section variables {A : Type} {B C : A → Type} (f : Π{a}, B a ≃ C a) {g : A → A} {g' : A → A} (h : Π{a}, B (g' a) → B (g a)) (h' : Π{a}, C (g' a) → C (g a)) definition inv_commute (p : Π⦃a : A⦄ (b : B (g' a)), f (h b) = h' (f b)) {a : A} (c : C (g' a)) : f⁻¹ (h' c) = h (f⁻¹ c) := inv_commute' @f @h @h' p c definition fun_commute_of_inv_commute (p : Π⦃a : A⦄ (c : C (g' a)), f⁻¹ (h' c) = h (f⁻¹ c)) {a : A} (b : B (g' a)) : f (h b) = h' (f b) := fun_commute_of_inv_commute' @f @h @h' p b definition inv_commute1 {B C : Type} (f : B ≃ C) (h : B → B) (h' : C → C) (p : Π(b : B), f (h b) = h' (f b)) (c : C) : f⁻¹ (h' c) = h (f⁻¹ c) := inv_commute1' (to_fun f) h h' p c end infixl ` ⬝pe `:75 := equiv_of_equiv_of_eq infixl ` ⬝ep `:75 := equiv_of_eq_of_equiv end equiv open equiv namespace is_equiv definition is_equiv_of_equiv_of_homotopy [constructor] {A B : Type} (f : A ≃ B) {f' : A → B} (Hty : f ~ f') : is_equiv f' := @(homotopy_closed f) f' _ Hty end is_equiv export [unfold] equiv export [unfold] is_equiv
1744ad0a3eff3ae357ba0f199ff4e0dfaa18b904
32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7
/src/Lean/Elab/DeclModifiers.lean
cce7bd237d94ed51715422e6cb996c4097294702
[ "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
6,239
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, Sebastian Ullrich -/ import Lean.Modifiers import Lean.Elab.Attributes import Lean.Elab.Exception import Lean.Elab.DeclUtil namespace Lean namespace Elab def checkNotAlreadyDeclared {m} [Monad m] [MonadEnv m] [MonadError m] (declName : Name) : m Unit := do env ← getEnv; when (env.contains declName) $ match privateToUserName? declName with | none => throwError ("'" ++ declName ++ "' has already been declared") | some declName => throwError ("private declaration '" ++ declName ++ "' has already been declared"); when (env.contains (mkPrivateName env declName)) $ throwError ("a private declaration '" ++ declName ++ "' has already been declared"); match privateToUserName? declName with | none => pure () | some declName => when (env.contains declName) $ throwError ("a non-private declaration '" ++ declName ++ "' has already been declared") inductive Visibility | regular | «protected» | «private» instance Visibility.hasToString : HasToString Visibility := ⟨fun v => match v with | Visibility.regular => "regular" | Visibility.private => "private" | Visibility.protected => "protected"⟩ structure Modifiers := (docString : Option String := none) (visibility : Visibility := Visibility.regular) (isNoncomputable : Bool := false) (isPartial : Bool := false) (isUnsafe : Bool := false) (attrs : Array Attribute := #[]) def Modifiers.isPrivate : Modifiers → Bool | { visibility := Visibility.private, .. } => true | _ => false def Modifiers.isProtected : Modifiers → Bool | { visibility := Visibility.protected, .. } => true | _ => false def Modifiers.addAttribute (modifiers : Modifiers) (attr : Attribute) : Modifiers := { modifiers with attrs := modifiers.attrs.push attr } instance Modifiers.hasFormat : HasFormat Modifiers := ⟨fun m => let components : List Format := (match m.docString with | some str => ["/--" ++ str ++ "-/"] | none => []) ++ (match m.visibility with | Visibility.regular => [] | Visibility.protected => ["protected"] | Visibility.private => ["private"]) ++ (if m.isNoncomputable then ["noncomputable"] else []) ++ (if m.isPartial then ["partial"] else []) ++ (if m.isUnsafe then ["unsafe"] else []) ++ m.attrs.toList.map (fun attr => fmt attr); Format.bracket "{" (Format.joinSep components ("," ++ Format.line)) "}"⟩ instance Modifiers.hasToString : HasToString Modifiers := ⟨toString ∘ format⟩ section Methods variables {m : Type → Type} [Monad m] [MonadEnv m] [MonadError m] def elabModifiers (stx : Syntax) : m Modifiers := do let docCommentStx := stx.getArg 0; let attrsStx := stx.getArg 1; let visibilityStx := stx.getArg 2; let noncompStx := stx.getArg 3; let unsafeStx := stx.getArg 4; let partialStx := stx.getArg 5; docString ← match docCommentStx.getOptional? with | none => pure none | some s => match s.getArg 1 with | Syntax.atom _ val => pure (some (val.extract 0 (val.bsize - 2))) | _ => throwErrorAt s ("unexpected doc string " ++ toString (s.getArg 1)); visibility ← match visibilityStx.getOptional? with | none => pure Visibility.regular | some v => let kind := v.getKind; if kind == `Lean.Parser.Command.private then pure Visibility.private else if kind == `Lean.Parser.Command.protected then pure Visibility.protected else throwErrorAt v "unexpected visibility modifier"; attrs ← match attrsStx.getOptional? with | none => pure #[] | some attrs => elabAttrs attrs; pure { docString := docString, visibility := visibility, isPartial := !partialStx.isNone, isUnsafe := !unsafeStx.isNone, isNoncomputable := !noncompStx.isNone, attrs := attrs } def applyVisibility (visibility : Visibility) (declName : Name) : m Name := match visibility with | Visibility.private => do env ← getEnv; let declName := mkPrivateName env declName; checkNotAlreadyDeclared declName; pure declName | Visibility.protected => do checkNotAlreadyDeclared declName; env ← getEnv; let env := addProtected env declName; setEnv env; pure declName | _ => do checkNotAlreadyDeclared declName; pure declName def mkDeclName (currNamespace : Name) (modifiers : Modifiers) (atomicName : Name) : m Name := do let name := (extractMacroScopes atomicName).name; unless (name.isAtomic || isFreshInstanceName name) $ throwError ("atomic identifier expected '" ++ atomicName ++ "'"); let declName := currNamespace ++ atomicName; applyVisibility modifiers.visibility declName /- `declId` is of the form ``` parser! ident >> optional (".{" >> sepBy1 ident ", " >> "}") ``` but we also accept a single identifier to users to make macro writing more convenient . -/ def expandDeclIdCore (declId : Syntax) : Name × Syntax := if declId.isIdent then (declId.getId, mkNullNode) else let id := declId.getIdAt 0; let optUnivDeclStx := declId.getArg 1; (id, optUnivDeclStx) structure ExpandDeclIdResult := (shortName : Name) (declName : Name) (levelNames : List Name) def expandDeclId (currNamespace : Name) (currLevelNames : List Name) (declId : Syntax) (modifiers : Modifiers) : m ExpandDeclIdResult := do -- ident >> optional (".{" >> sepBy1 ident ", " >> "}") let (shortName, optUnivDeclStx) := expandDeclIdCore declId; levelNames ← if optUnivDeclStx.isNone then pure currLevelNames else do { let extraLevels := (optUnivDeclStx.getArg 1).getArgs.getEvenElems; extraLevels.foldlM (fun levelNames idStx => let id := idStx.getId; if levelNames.elem id then withRef idStx $ throwAlreadyDeclaredUniverseLevel id else pure (id :: levelNames)) currLevelNames }; declName ← withRef declId $ mkDeclName currNamespace modifiers shortName; pure { shortName := shortName, declName := declName, levelNames := levelNames } end Methods end Elab end Lean
eac31b9c45c1a62ad01f146aad4b2c572af13ba1
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/data/list/alist.lean
a51fdf6a5648dc3d42bda90b4118e95bfac0fa5b
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
10,897
lean
/- Copyright (c) 2018 Sean Leather. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sean Leather, Mario Carneiro Association lists. -/ import data.list.sigma universes u v w open list variables {α : Type u} {β : α → Type v} /-- `alist β` is a key-value map stored as a `list` (i.e. a linked list). It is a wrapper around certain `list` functions with the added constraint that the list have unique keys. -/ structure alist (β : α → Type v) : Type (max u v) := (entries : list (sigma β)) (nodupkeys : entries.nodupkeys) def list.to_alist [decidable_eq α] {β : α → Type v} (l : list (sigma β)) : alist β := { entries := _, nodupkeys := nodupkeys_erase_dupkeys l } namespace alist @[ext] theorem ext : ∀ {s t : alist β}, s.entries = t.entries → s = t | ⟨l₁, h₁⟩ ⟨l₂, h₂⟩ H := by congr' lemma ext_iff {s t : alist β} : s = t ↔ s.entries = t.entries := ⟨congr_arg _, ext⟩ instance [decidable_eq α] [∀ a, decidable_eq (β a)] : decidable_eq (alist β) := λ xs ys, by rw ext_iff; apply_instance /- keys -/ /-- The list of keys of an association list. -/ def keys (s : alist β) : list α := s.entries.keys theorem keys_nodup (s : alist β) : s.keys.nodup := s.nodupkeys /- mem -/ /-- The predicate `a ∈ s` means that `s` has a value associated to the key `a`. -/ instance : has_mem α (alist β) := ⟨λ a s, a ∈ s.keys⟩ theorem mem_keys {a : α} {s : alist β} : a ∈ s ↔ a ∈ s.keys := iff.rfl theorem mem_of_perm {a : α} {s₁ s₂ : alist β} (p : s₁.entries ~ s₂.entries) : a ∈ s₁ ↔ a ∈ s₂ := mem_of_perm $ perm_map sigma.fst p /- empty -/ /-- The empty association list. -/ instance : has_emptyc (alist β) := ⟨⟨[], nodupkeys_nil⟩⟩ instance : inhabited (alist β) := ⟨∅⟩ theorem not_mem_empty (a : α) : a ∉ (∅ : alist β) := not_mem_nil a @[simp] theorem empty_entries : (∅ : alist β).entries = [] := rfl @[simp] theorem keys_empty : (∅ : alist β).keys = [] := rfl /- singleton -/ /-- The singleton association list. -/ def singleton (a : α) (b : β a) : alist β := ⟨[⟨a, b⟩], nodupkeys_singleton _⟩ @[simp] theorem singleton_entries (a : α) (b : β a) : (singleton a b).entries = [sigma.mk a b] := rfl @[simp] theorem keys_singleton (a : α) (b : β a) : (singleton a b).keys = [a] := rfl variables [decidable_eq α] /- lookup -/ /-- Look up the value associated to a key in an association list. -/ def lookup (a : α) (s : alist β) : option (β a) := s.entries.lookup a @[simp] theorem lookup_empty (a) : lookup a (∅ : alist β) = none := rfl theorem lookup_is_some {a : α} {s : alist β} : (s.lookup a).is_some ↔ a ∈ s := lookup_is_some theorem lookup_eq_none {a : α} {s : alist β} : lookup a s = none ↔ a ∉ s := lookup_eq_none theorem perm_lookup {a : α} {s₁ s₂ : alist β} (p : s₁.entries ~ s₂.entries) : s₁.lookup a = s₂.lookup a := perm_lookup _ s₁.nodupkeys s₂.nodupkeys p instance (a : α) (s : alist β) : decidable (a ∈ s) := decidable_of_iff _ lookup_is_some /- replace -/ /-- Replace a key with a given value in an association list. If the key is not present it does nothing. -/ def replace (a : α) (b : β a) (s : alist β) : alist β := ⟨kreplace a b s.entries, (kreplace_nodupkeys a b).2 s.nodupkeys⟩ @[simp] theorem keys_replace (a : α) (b : β a) (s : alist β) : (replace a b s).keys = s.keys := keys_kreplace _ _ _ @[simp] theorem mem_replace {a a' : α} {b : β a} {s : alist β} : a' ∈ replace a b s ↔ a' ∈ s := by rw [mem_keys, keys_replace, ←mem_keys] theorem perm_replace {a : α} {b : β a} {s₁ s₂ : alist β} : s₁.entries ~ s₂.entries → (replace a b s₁).entries ~ (replace a b s₂).entries := perm_kreplace s₁.nodupkeys /-- Fold a function over the key-value pairs in the map. -/ def foldl {δ : Type w} (f : δ → Π a, β a → δ) (d : δ) (m : alist β) : δ := m.entries.foldl (λ r a, f r a.1 a.2) d /- erase -/ /-- Erase a key from the map. If the key is not present it does nothing. -/ def erase (a : α) (s : alist β) : alist β := ⟨kerase a s.entries, kerase_nodupkeys _ s.nodupkeys⟩ @[simp] theorem keys_erase (a : α) (s : alist β) : (erase a s).keys = s.keys.erase a := by simp only [erase, keys, keys_kerase] @[simp] theorem mem_erase {a a' : α} {s : alist β} : a' ∈ erase a s ↔ a' ≠ a ∧ a' ∈ s := by rw [mem_keys, keys_erase, mem_erase_iff_of_nodup s.keys_nodup, ←mem_keys] theorem perm_erase {a : α} {s₁ s₂ : alist β} : s₁.entries ~ s₂.entries → (erase a s₁).entries ~ (erase a s₂).entries := perm_kerase s₁.nodupkeys @[simp] theorem lookup_erase (a) (s : alist β) : lookup a (erase a s) = none := lookup_kerase a s.nodupkeys @[simp] theorem lookup_erase_ne {a a'} {s : alist β} (h : a ≠ a') : lookup a (erase a' s) = lookup a s := lookup_kerase_ne h theorem erase_erase (a a' : α) (s : alist β) : (s.erase a).erase a' = (s.erase a').erase a := ext $ kerase_kerase /- insert -/ /-- Insert a key-value pair into an association list and erase any existing pair with the same key. -/ def insert (a : α) (b : β a) (s : alist β) : alist β := ⟨kinsert a b s.entries, kinsert_nodupkeys a b s.nodupkeys⟩ @[simp] theorem insert_entries {a} {b : β a} {s : alist β} : (insert a b s).entries = sigma.mk a b :: kerase a s.entries := rfl theorem insert_entries_of_neg {a} {b : β a} {s : alist β} (h : a ∉ s) : (insert a b s).entries = ⟨a, b⟩ :: s.entries := by rw [insert_entries, kerase_of_not_mem_keys h] @[simp] theorem mem_insert {a a'} {b' : β a'} (s : alist β) : a ∈ insert a' b' s ↔ a = a' ∨ a ∈ s := mem_keys_kinsert @[simp] theorem keys_insert {a} {b : β a} (s : alist β) : (insert a b s).keys = a :: s.keys.erase a := by simp [insert, keys, keys_kerase] theorem perm_insert {a} {b : β a} {s₁ s₂ : alist β} (p : s₁.entries ~ s₂.entries) : (insert a b s₁).entries ~ (insert a b s₂).entries := by simp only [insert_entries]; exact perm_kinsert s₁.nodupkeys p @[simp] theorem lookup_insert {a} {b : β a} (s : alist β) : lookup a (insert a b s) = some b := by simp only [lookup, insert, lookup_kinsert] @[simp] theorem lookup_insert_ne {a a'} {b' : β a'} {s : alist β} (h : a ≠ a') : lookup a (insert a' b' s) = lookup a s := lookup_kinsert_ne h @[simp] theorem lookup_to_alist {a} (s : list (sigma β)) : lookup a s.to_alist = s.lookup a := by rw [list.to_alist,lookup,lookup_erase_dupkeys] @[simp] theorem insert_insert {a} {b b' : β a} (s : alist β) : (s.insert a b).insert a b' = s.insert a b' := by ext : 1; simp only [alist.insert_entries, list.kerase_cons_eq]; constructor_matching* [_ ∧ _]; refl theorem insert_insert_of_ne {a a'} {b : β a} {b' : β a'} (s : alist β) (h : a ≠ a') : ((s.insert a b).insert a' b').entries ~ ((s.insert a' b').insert a b).entries := by simp only [insert_entries]; rw [kerase_cons_ne,kerase_cons_ne,kerase_comm]; [apply perm.swap, exact h, exact h.symm] @[simp] lemma insert_singleton_eq {a : α} {b b' : β a} : insert a b (singleton a b') = singleton a b := ext (by simp only [alist.insert_entries, list.kerase_cons_eq, and_self, alist.singleton_entries, heq_iff_eq, eq_self_iff_true]) @[simp] theorem entries_to_alist (xs : list (sigma β)) : (list.to_alist xs).entries = erase_dupkeys xs := rfl theorem to_alist_cons (a : α) (b : β a) (xs : list (sigma β)) : list.to_alist (⟨a,b⟩ :: xs) = insert a b xs.to_alist := rfl /- extract -/ /-- Erase a key from the map, and return the corresponding value, if found. -/ def extract (a : α) (s : alist β) : option (β a) × alist β := have (kextract a s.entries).2.nodupkeys, by rw [kextract_eq_lookup_kerase]; exact kerase_nodupkeys _ s.nodupkeys, match kextract a s.entries, this with | (b, l), h := (b, ⟨l, h⟩) end @[simp] theorem extract_eq_lookup_erase (a : α) (s : alist β) : extract a s = (lookup a s, erase a s) := by simp [extract]; split; refl /- union -/ /-- `s₁ ∪ s₂` is the key-based union of two association lists. It is left-biased: if there exists an `a ∈ s₁`, `lookup a (s₁ ∪ s₂) = lookup a s₁`. -/ def union (s₁ s₂ : alist β) : alist β := ⟨kunion s₁.entries s₂.entries, kunion_nodupkeys s₁.nodupkeys s₂.nodupkeys⟩ instance : has_union (alist β) := ⟨union⟩ @[simp] theorem union_entries {s₁ s₂ : alist β} : (s₁ ∪ s₂).entries = kunion s₁.entries s₂.entries := rfl @[simp] theorem empty_union {s : alist β} : (∅ : alist β) ∪ s = s := ext rfl @[simp] theorem union_empty {s : alist β} : s ∪ (∅ : alist β) = s := ext $ by simp @[simp] theorem mem_union {a} {s₁ s₂ : alist β} : a ∈ s₁ ∪ s₂ ↔ a ∈ s₁ ∨ a ∈ s₂ := mem_keys_kunion theorem perm_union {s₁ s₂ s₃ s₄ : alist β} (p₁₂ : s₁.entries ~ s₂.entries) (p₃₄ : s₃.entries ~ s₄.entries) : (s₁ ∪ s₃).entries ~ (s₂ ∪ s₄).entries := by simp [perm_kunion s₃.nodupkeys p₁₂ p₃₄] theorem union_erase (a : α) (s₁ s₂ : alist β) : erase a (s₁ ∪ s₂) = erase a s₁ ∪ erase a s₂ := ext kunion_kerase.symm @[simp] theorem lookup_union_left {a} {s₁ s₂ : alist β} : a ∈ s₁ → lookup a (s₁ ∪ s₂) = lookup a s₁ := lookup_kunion_left @[simp] theorem lookup_union_right {a} {s₁ s₂ : alist β} : a ∉ s₁ → lookup a (s₁ ∪ s₂) = lookup a s₂ := lookup_kunion_right @[simp] theorem mem_lookup_union {a} {b : β a} {s₁ s₂ : alist β} : b ∈ lookup a (s₁ ∪ s₂) ↔ b ∈ lookup a s₁ ∨ a ∉ s₁ ∧ b ∈ lookup a s₂ := mem_lookup_kunion theorem mem_lookup_union_middle {a} {b : β a} {s₁ s₂ s₃ : alist β} : b ∈ lookup a (s₁ ∪ s₃) → a ∉ s₂ → b ∈ lookup a (s₁ ∪ s₂ ∪ s₃) := mem_lookup_kunion_middle theorem insert_union {a} {b : β a} {s₁ s₂ : alist β} : insert a b (s₁ ∪ s₂) = insert a b s₁ ∪ s₂ := by ext; simp theorem union_assoc {s₁ s₂ s₃ : alist β} : ((s₁ ∪ s₂) ∪ s₃).entries ~ (s₁ ∪ (s₂ ∪ s₃)).entries := lookup_ext (alist.nodupkeys _) (alist.nodupkeys _) (by simp [decidable.not_or_iff_and_not,or_assoc,and_or_distrib_left,and_assoc]) /- disjoint -/ def disjoint (s₁ s₂ : alist β) := ∀ k ∈ s₁.keys, ¬ k ∈ s₂.keys theorem union_comm_of_disjoint {s₁ s₂ : alist β} (h : disjoint s₁ s₂) : (s₁ ∪ s₂).entries ~ (s₂ ∪ s₁).entries := lookup_ext (alist.nodupkeys _) (alist.nodupkeys _) (begin intros, simp, split; intro h', cases h', { right, refine ⟨_,h'⟩, apply h, rw [keys,← list.lookup_is_some,h'], exact rfl }, { left, rw h'.2 }, cases h', { right, refine ⟨_,h'⟩, intro h'', apply h _ h'', rw [keys,← list.lookup_is_some,h'], exact rfl }, { left, rw h'.2 }, end) end alist
5d9e41a41314811698b0fb619eac8d005fc0d26c
9db059bff49b1090a86ec0050ac6c577eb16ac67
/src/meetings/algebraic_structures_and_orders.lean
1d785646f2ca576cd8404fe9672a883f5895b12b
[]
no_license
fpvandoorn/Harvard-tutoring
d64cd75c4c529009ee562c30e9cb245fe237e760
a8846c08e32cdc7b91a7e28adfa5d9b2810088b0
refs/heads/master
1,680,870,428,641
1,617,022,194,000
1,617,022,194,000
330,297,467
1
0
null
null
null
null
UTF-8
Lean
false
false
15,226
lean
import data.rat.basic import tactic /- In this file we will build "the algebraic hierarchy", the classes of groups, rings, fields, modules etc. To get the exercises, run: ``` leanproject get fpvandoorn/Harvard-tutoring cp -r Harvard-tutoring/src/exercises/ Harvard-tutoring/src/my_exercises code Harvard-tutoring ``` For this week, the exercises are in the files `my_exercises/algebraic_hierarchy.lean` and `my_exercises/order.lean`. Also this week, think about a project you would like to formalize in Lean for the remaining weeks, and discuss it during your weekly meeting with your tutor. -/ /- ## Notation typeclasses We have notation typeclasses which are just there to provide notation. If you write `[has_mul G]` then `G` will have a multiplication called `*` (satisfying no axioms). Similarly `[has_one G]` gives you `(1 : G)` and `[has_inv G]` gives you a map `(λ g, g⁻¹ : G → G)` -/ #print has_mul example {G : Type} [has_mul G] (g h : G) : g * h = h * g := sorry -- this is false /- ## Groups -/ -- `extends` is used to extend other classes class my_group (G : Type) extends has_mul G, has_one G, has_inv G := (mul_assoc : ∀ (a b c : G), a * b * c = a * (b * c)) (one_mul : ∀ (a : G), 1 * a = a) (mul_left_inv : ∀ (a : G), a⁻¹ * a = 1) /- Advantages of this approach: axioms look lovely. Disadvantage: what if I want the group law to be `+`? I have embedded `has_mul` in the definition. -/ class my_add_group (G : Type) extends has_add G, has_zero G, has_neg G := (add_assoc : ∀ (a b c : G), a + b + c = a + (b + c)) (zero_add : ∀ (a : G), 0 + a = a) (add_left_neg : ∀ (a : G), -a + a = 0) attribute [to_additive] my_group /- Lean's solution: develop a `to_additive` metaprogram which translates all theorems about `group`s (with group law `*`) to theorems about `add_group`s (with group law `+`). -/ #print my_group.one_mul namespace my_group #print one_mul /- We can now prove more theorems about `my_group`, such as the following: `mul_left_cancel : ∀ (a b c : G), a * b = a * c → b = c` `mul_eq_of_eq_inv_mul {a x y : G} : x = a⁻¹ * y → a * x = y` `mul_one (a : G) : a * 1 = a` `mul_right_inv (a : G) : a * a⁻¹ = 1` -/ @[to_additive] lemma mul_left_cancel {G : Type} [my_group G] (a b c : G) (Habac : a * b = a * c) : b = c := calc b = 1 * b : by rw one_mul ... = (a⁻¹ * a) * b : by rw mul_left_inv ... = a⁻¹ * (a * b) : by rw mul_assoc ... = a⁻¹ * (a * c) : by sorry ... = (a⁻¹ * a) * c : by sorry ... = 1 * c : by sorry ... = c : by sorry #check @my_group.mul_left_cancel #check @my_add_group.add_left_cancel variables (x y : ℚ) example : x * y + y = y * (x + 1) := by { rw mul_comm, ring } #check @mul_eq_of_eq_inv_mul -- Abstract example of the power of classes: we can define products of groups with instances attribute [simp] mul_assoc one_mul mul_left_inv instance (G : Type) [my_group G] (H : Type) [my_group H] : my_group (G × H) := { mul := λ gh gh', (gh.1 * gh'.1, gh.2 * gh'.2), one := (1, 1), inv := λ gh, (gh.1⁻¹, gh.2⁻¹), mul_assoc := by { intros a b c, cases c, cases b, cases a, dsimp at *, simp at * }, one_mul := by tidy, mul_left_inv := by tidy } -- the type class inference system now knows that products of groups are groups example (G H K : Type) [my_group G] [my_group H] [my_group K] : my_group (G × H × K) := by { apply_instance } end my_group -- let's make a group of order two. -- First the elements {+1, -1} inductive mu2 | p1 : mu2 | m1 : mu2 namespace mu2 /- two preliminary facts -/ -- 1) give an algorithm to decide equality attribute [derive decidable_eq] mu2 -- 2) prove it is finite instance : fintype mu2 := ⟨⟨[mu2.p1, mu2.m1], dec_trivial⟩, λ x, by { cases x; exact dec_trivial, }⟩ -- Define multiplication by doing all cases def mul : mu2 → mu2 → mu2 | p1 p1 := p1 | p1 m1 := m1 | m1 p1 := m1 | m1 m1 := p1 -- now let's make it a group instance : my_group mu2 := begin refine { mul := mu2.mul, one := p1, inv := id, .. }, all_goals {exact dec_trivial}, end end mu2 -- Now let's build rings and modules and stuff (via monoids and add_comm_groups) -- a monoid is a group without inverses class my_monoid (M : Type) extends has_mul M, has_one M := (mul_assoc : ∀ (a b c : M), a * b * c = a * (b * c)) (one_mul : ∀ (a : M), 1 * a = a) (mul_one : ∀ (a : M), a * 1 = a) #print monoid -- rings are additive abelian groups and multiplicative monoids, -- with distributivity class my_ring (R : Type) extends my_monoid R, add_comm_group R := (mul_add : ∀ (a b c : R), a * (b + c) = a * b + a * c) (add_mul : ∀ (a b c : R), (a + b) * c = a * c + b * c) -- for commutative rings, add commutativity of multiplication class my_comm_ring (R : Type) extends my_ring R := (mul_comm : ∀ a b : R, a * b = b * a) /-- Typeclass for types with a scalar multiplication operation, denoted `•` (`\bu`) -/ class my_has_scalar (R : Type) (M : Type) := (smul : R → M → M) infixr ` • `:73 := my_has_scalar.smul -- modules over a ring class my_module (R : Type) [my_ring R] (M : Type) [add_comm_group M] extends my_has_scalar R M := (smul_add : ∀(r : R) (x y : M), r • (x + y) = r • x + r • y) (add_smul : ∀(r s : R) (x : M), (r + s) • x = r • x + s • x) (mul_smul : ∀ (r s : R) (x : M), (r * s) • x = r • s • x) (one_smul : ∀ x : M, (1 : R) • x = x) -- for fields we let ⁻¹ be defined on the entire field, and demand 0⁻¹ = 0 -- and that a⁻¹ * a = 1 for non-zero a. This is merely for convenience; -- one can easily check that it's mathematically equivalent to the usual -- definition of a field. class my_field (K : Type) extends my_comm_ring K, has_inv K := (zero_ne_one : (0 : K) ≠ 1) (mul_inv_cancel : ∀ {a : K}, a ≠ 0 → a * a⁻¹ = 1) (inv_zero : (0 : K)⁻¹ = 0) -- the type of vector spaces def my_vector_space (K : Type) [my_field K] (V : Type) [add_comm_group V] := my_module K V /- Let's check that we can make the rational numbers into a field. (easy because all the work is done in the import) -/ instance : my_field ℚ := { mul := (*), one := 1, mul_assoc := rat.mul_assoc, one_mul := rat.one_mul, mul_one := rat.mul_one, add := (+), zero := 0, neg := has_neg.neg, add_assoc := rat.add_assoc, zero_add := rat.zero_add, add_zero := rat.add_zero, add_left_neg := rat.add_left_neg, add_comm := rat.add_comm, mul_add := rat.mul_add, add_mul := rat.add_mul, mul_comm := rat.mul_comm, inv := has_inv.inv, zero_ne_one := rat.zero_ne_one, mul_inv_cancel := rat.mul_inv_cancel, inv_zero := inv_zero } /- Some tactics that will help: -/ example {G : Type} [group G] (a b c d : G) : ((a * b)⁻¹ * a * 1⁻¹⁻¹⁻¹ * b * b⁻¹ * 1 * c)⁻¹ = (c⁻¹⁻¹ * (d * d⁻¹ * 1⁻¹⁻¹) * c⁻¹ * c⁻¹⁻¹⁻¹ * b)⁻¹⁻¹ := by simp example {G : Type} [add_comm_group G] (a b : G) : (a + b) - ((b + a) + a) = -a := by abel -- rewriting in abelian groups example {R : Type} [comm_ring R] (a b : R) : (a + b) * (a - b) = a ^ 2 - b ^ 2 := by ring -- rewriting in commutative rings example {F : Type} [field F] (a b : F) (h : a ≠ 0) : (a + b) / a = 1 + b / a := by field_simp -- rewriting fractions in fields /- # Orders We also have an "order hierarchy". It starts with partially ordered sets, and then goes on to lattices. We will motivate it using subgroups. -/ open set -- The type of subgroups of a group G is called `subgroup G` in Lean. -- It already has a lattice structure in Lean. -- So let's just redo the entire theory and call it `my_subgroup G`. /-- The type of subgroups of a group `G`. -/ structure my_subgroup (G : Type) [group G] := -- A subgroup of G is a sub*set* of G, called `carrier` (carrier : set G) -- and then axioms saying it's closed under the group structure (i.e. *, 1, ⁻¹) (mul_mem {a b : G} : a ∈ carrier → b ∈ carrier → a * b ∈ carrier) (one_mem : (1 : G) ∈ carrier) (inv_mem {a : G} : a ∈ carrier → a⁻¹ ∈ carrier) namespace my_subgroup /- Note in particular that we have a function `my_subgroup.carrier : my_subgroup G → set G`, sending a subgroup of `G` to the underlying subset (`set G` is the type of subsets of G). -/ -- Let G be a group, let H,J,K be subgroups of G, and let a,b,c be elements of G. variables {G : Type} [group G] (H J K : my_subgroup G) (a b c : G) /- ## Extensionality -/ lemma carrier_injective (H J : my_subgroup G) (h : H.carrier = J.carrier) : H = J := begin cases H, cases J, simp * at *, end -- Now let's prove that two subgroups are equal iff they have the same elements. -- This is the most useful "extensionality lemma" so we tag it `@[ext]`. @[ext] theorem ext {H J : my_subgroup G} (h : ∀ (x : G), x ∈ H.carrier ↔ x ∈ J.carrier) : H = J := begin apply carrier_injective, ext, apply h, end -- We also want the `iff` version of this. theorem ext_iff {H J : my_subgroup G} : H = J ↔ ∀ (x : G), x ∈ H.carrier ↔ x ∈ J.carrier := begin sorry end /- ## Partial orders -/ -- We define `H ≤ J` to mean `H.carrier ⊆ J.carrier` -- "tidy" is a one-size-fits-all tactic which solves certain kinds of "follow your nose" goals. instance : partial_order (my_subgroup G) := { le := λ H J, H.carrier ⊆ J.carrier, le_refl := by tidy, le_trans := by tidy, le_antisymm := by tidy } -- We can give a second construction using `partial_order.lift`: example : partial_order (my_subgroup G) := partial_order.lift my_subgroup.carrier carrier_injective example {H J : my_subgroup G} (h : H < J) : H ≤ J := h.le /- ## From partial orders to lattices. We can now show that `my_subgroup G` is a semilattice with finite meets (binary meets and a top element). -/ def top : my_subgroup G := { carrier := set.univ, mul_mem := begin sorry end, one_mem := begin sorry end, inv_mem := begin sorry end } -- Add the `⊤` notation (typed with `\top`) for this subgroup: instance : has_top (my_subgroup G) := ⟨top⟩ #check (⊤ : my_subgroup G) /-- "Theorem" : intersection of two my_subgroups is a my_subgroup -/ definition inf (H K : my_subgroup G) : my_subgroup G := { carrier := H.carrier ∩ K.carrier, mul_mem := begin sorry end, one_mem := begin sorry end, inv_mem := begin sorry end } -- Add the `⊓` notation (type with `\inf`) for the intersection (inf) of two subgroups: instance : has_inf (my_subgroup G) := ⟨inf⟩ -- We now check the four axioms for a semilattice_inf_top. lemma le_top (H : my_subgroup G) : H ≤ ⊤ := begin sorry end lemma inf_le_left (H K : my_subgroup G) : H ⊓ K ≤ H := begin sorry end lemma inf_le_right (H K : my_subgroup G) : H ⊓ K ≤ K := begin sorry end lemma le_inf (H J K : my_subgroup G) (h1 : H ≤ J) (h2 : H ≤ K) : H ≤ J ⊓ K := begin sorry end -- Now we're ready to make the instance. instance : semilattice_inf_top (my_subgroup G) := { top := top, le_top := le_top, inf := inf, inf_le_left := inf_le_left, inf_le_right := inf_le_right, le_inf := le_inf, .. my_subgroup.partial_order } /- ## Complete lattices Let's now show that subgroups form a complete lattice. This has arbitrary `Inf` and `Sup`s. First we show we can form arbitrary intersections. -/ def Inf (S : set (my_subgroup G)) : my_subgroup G := { carrier := ⋂ K ∈ S, (K : my_subgroup G).carrier, mul_mem := begin intros a b ha hb, simp at *, intros K hK, apply my_subgroup.mul_mem, tidy end, one_mem := begin sorry end, inv_mem := begin sorry end } -- We now equip `my_subgroup G` with an Inf. The notation is `⨅`, or `\Inf`. instance : has_Inf (my_subgroup G) := ⟨Inf⟩ instance : complete_lattice (my_subgroup G) := complete_lattice_of_Inf _ begin sorry end /- ## Galois connections A Galois conection is a pair of adjoint functors between two partially ordered sets, considered as categories whose hom sets Hom(H,J) have size 1 if H ≤ J and size 0 otherwise. In other words, a Galois connection between two partial orders α and β is a pair of monotone functions `l : α → β` and `u : β → α` such that `∀ (a : α) (b : β), l a ≤ b ↔ a ≤ u b`. There is an example coming from Galois theory (between subfields and subgroups), and an example coming from classical algebraic geometry (between affine varieties and ideals); note that in both cases you have to use the opposite partial order on one side to make everything covariant. The examples we want to keep in mind here are: 1) α = subsets of G, β = subgroups of G, l = "subgroup generated by", u = `carrier` 2) X : Type, α := set (set X), β := topologies on X, l = topology generated by a collection of open sets, u = the open sets regarded as subsets. As you can imagine, there are a bunch of abstract theorems with simple proofs proved for Galois connections. You can see them by `#check galois_connection`, jumping to the definition, and reading the next 150 lines of the mathlib file after the definition. Examples of theorems you might recognise from contexts where you have seen this before: lemma le_u_l (a : α) : a ≤ u (l a) := ... lemma l_u_le (b : β) : l (u b) ≤ b := ... lemma u_l_u_eq_u : u ∘ l ∘ u = u := ... lemma l_u_l_eq_l : l ∘ u ∘ l = l := ... # Galois insertions A particularly cool kind of Galois connection is a Galois insertion, which is a Galois connection such that `l ∘ u = id`. This is true for both the examples we're keeping in mind (the subgroup of `G` generated by a subgroup is the same subgroup; the topology on `X` generated by a topology is the same topology). Our new goal: let's make subgroups of a group into a complete lattice, using the fact that `carrier` is part of a Galois insertion. -/ -- The adjoint functor to the `carrier` functor is the `span` functor -- from subsets to my_subgroups. Here we will CHEAT by using `Inf` to -- define `span`. We could have built `span` directly with -- an inductive definition. def span (S : set G) : my_subgroup G := Inf {H : my_subgroup G | S ⊆ H.carrier} -- Here are some theorems about it. lemma monotone_carrier : monotone (my_subgroup.carrier : my_subgroup G → set G) := begin sorry end lemma monotone_span : monotone (span : set G → my_subgroup G) := begin sorry end lemma subset_span (S : set G) : S ≤ (span S).carrier := begin sorry end lemma span_my_subgroup (H : my_subgroup G) : span H.carrier = H := begin sorry end -- We have proved all the things we need to show that `span` and `carrier` -- form a Galois insertion, using `galois_insertion.monotone_intro`. def gi_my_subgroup : galois_insertion (span : set G → my_subgroup G) (my_subgroup.carrier : my_subgroup G → set G) := galois_insertion.monotone_intro monotone_carrier monotone_span subset_span span_my_subgroup -- Note that `set G` is already a complete lattice: example : complete_lattice (set G) := by apply_instance -- and now `my_subgroup G` can also be made into a complete lattice, by -- a theorem about Galois insertions. Again, I don't use `instance` -- because we already made the instance above. example : complete_lattice (my_subgroup G) := galois_insertion.lift_complete_lattice gi_my_subgroup end my_subgroup
79b010e77e00fad5cb79b150b378aced2c411536
acc85b4be2c618b11fc7cb3005521ae6858a8d07
/data/rat.lean
6761bab15e1371f36b6816612de2ef3cc7daf1fe
[ "Apache-2.0" ]
permissive
linpingchuan/mathlib
d49990b236574df2a45d9919ba43c923f693d341
5ad8020f67eb13896a41cc7691d072c9331b1f76
refs/heads/master
1,626,019,377,808
1,508,048,784,000
1,508,048,784,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
25,917
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 Introduces the rational numbers as discrete, linear ordered field. -/ import data.nat.gcd data.pnat data.int.basic data.encodable order.basic algebra.ordered_group algebra.order pending instance int.encodable : encodable ℤ := ⟨λz, match z with | int.of_nat p := encodable.encode (@sum.inl ℕ ℕ p) | int.neg_succ_of_nat n := encodable.encode (@sum.inr ℕ ℕ n) end, λn, match encodable.decode (ℕ ⊕ ℕ) n with | option.some (sum.inl p) := int.of_nat p | option.some (sum.inr n) := int.neg_succ_of_nat n | option.none := none end, λz, match z with | int.of_nat p := by simp [int.encodable._match_1, encodable.encodek]; refl | int.neg_succ_of_nat n := by simp [int.encodable._match_1, encodable.encodek]; refl end⟩ /- linorder -/ section linear_order_cases_on universes u v variables {α : Type u} [decidable_linear_order α] {β : Sort v} def linear_order_cases_on (a b : α) (h_eq : a = b → β) (h_lt : a < b → β) (h_gt : a > b → β) : β := if h₁ : a = b then h_eq h₁ else if h₂ : a < b then h_lt h₂ else h_gt ((lt_or_gt_of_ne h₁).resolve_left h₂) variables {a b : α} {h_eq : a = b → β} {h_lt : a < b → β} {h_gt : a > b → β} @[simp] theorem linear_order_cases_on_eq (h : a = b) : linear_order_cases_on a b h_eq h_lt h_gt = h_eq h := dif_pos h @[simp] theorem linear_order_cases_on_lt (h : a < b) : linear_order_cases_on a b h_eq h_lt h_gt = h_lt h := eq.trans (dif_neg $ ne_of_lt h) $ dif_pos h @[simp] theorem linear_order_cases_on_gt (h : a > b) : linear_order_cases_on a b h_eq h_lt h_gt = h_gt h := eq.trans (dif_neg $ (ne_of_lt h).symm) (dif_neg $ not_lt_of_ge $ le_of_lt h) end linear_order_cases_on /- linorder ring -/ section ordered_ring universes u variables {α : Type u} [linear_ordered_ring α] {a b : α} theorem mul_nonneg_iff_right_nonneg_of_pos (h : 0 < a) : 0 ≤ b * a ↔ 0 ≤ b := ⟨assume : 0 ≤ b * a, nonneg_of_mul_nonneg_right this h, assume : 0 ≤ b, mul_nonneg this $ le_of_lt h⟩ end ordered_ring /- rational numbers -/ structure rat := mk' :: (num : ℤ) (denom : ℕ) (pos : denom > 0) (cop : num.nat_abs.coprime denom) notation `ℚ` := rat namespace rat def of_int (n : ℤ) : ℚ := ⟨n, 1, nat.one_pos, nat.coprime_one_right _⟩ instance coe_int_rat : has_coe ℤ ℚ := ⟨of_int⟩ instance coe_nat_rat : has_coe ℕ ℚ := ⟨of_int ∘ int.of_nat⟩ instance : has_zero ℚ := ⟨(0 : ℤ)⟩ instance : has_one ℚ := ⟨(1 : ℤ)⟩ def mk_pnat (n : ℤ) : ℕ+ → ℚ | ⟨d, dpos⟩ := let n' := n.nat_abs, g := n'.gcd d in ⟨n / g, d / g, begin apply (nat.le_div_iff_mul_le _ _ (nat.gcd_pos_of_pos_right _ dpos)).2, simp, exact nat.le_of_dvd dpos (nat.gcd_dvd_right _ _) end, begin have : int.nat_abs (n / ↑g) = n' / g, { cases int.nat_abs_eq n with e e; rw e, { refl }, rw [int.neg_div_of_dvd, int.nat_abs_neg], { refl }, exact int.coe_nat_dvd_coe_nat_of_dvd (nat.gcd_dvd_left _ _) }, rw this, exact nat.coprime_div_gcd_div_gcd (nat.gcd_pos_of_pos_right _ dpos) end⟩ def mk_nat (n : ℤ) (d : ℕ) : ℚ := if d0 : d = 0 then 0 else mk_pnat n ⟨d, nat.pos_of_ne_zero d0⟩ def mk : ℤ → ℤ → ℚ | n (int.of_nat d) := mk_nat n d | n -[1+ d] := mk_pnat (-n) d.succ_pnat local infix ` /. `:70 := mk theorem mk_pnat_eq (n d h) : mk_pnat n ⟨d, h⟩ = n /. d := by change n /. d with dite _ _ _; simp [ne_of_gt h] theorem mk_nat_eq (n d) : mk_nat n d = n /. d := rfl @[simp] theorem mk_zero (n) : n /. 0 = 0 := rfl @[simp] theorem zero_mk_pnat (n) : mk_pnat 0 n = 0 := by cases n; simp [mk_pnat]; change int.nat_abs 0 with 0; simp *; refl @[simp] theorem zero_mk_nat (n) : mk_nat 0 n = 0 := by by_cases n = 0; simp [*, mk_nat] @[simp] theorem zero_mk (n) : 0 /. n = 0 := by cases n; simp [mk] private lemma gcd_abs_dvd_left {a b} : (nat.gcd (int.nat_abs a) b : ℤ) ∣ a := int.coe_nat_dvd_right.1 (int.coe_nat_dvd_coe_nat_of_dvd $ nat.gcd_dvd_left (int.nat_abs a) b) @[simp] theorem mk_eq_zero {a b : ℤ} (b0 : b ≠ 0) : a /. b = 0 ↔ a = 0 := begin constructor; intro h; [skip, {subst a, simp}], have : ∀ {a b}, mk_pnat a b = 0 → a = 0, { intros a b e, cases b with b h, injection e with e, apply int.eq_mul_of_div_eq_right gcd_abs_dvd_left e }, cases b with b; simp [mk, mk_nat] at h, { simp [mt (congr_arg int.of_nat) b0] at h, exact this h }, { apply neg_inj, simp [this h] } end theorem mk_eq : ∀ {a b c d : ℤ} (hb : b ≠ 0) (hd : d ≠ 0), a /. b = c /. d ↔ a * d = c * b := suffices ∀ a b c d hb hd, mk_pnat a ⟨b, hb⟩ = mk_pnat c ⟨d, hd⟩ ↔ a * d = c * b, begin intros, cases b with b b; simp [mk, mk_nat, nat.succ_pnat], simp [mt (congr_arg int.of_nat) hb], all_goals { cases d with d d; simp [mk, mk_nat, nat.succ_pnat], simp [mt (congr_arg int.of_nat) hd], all_goals { rw this, try {refl} } }, { change a * ↑(d.succ) = -c * ↑b ↔ a * -(d.succ) = c * b, constructor; intro h; apply neg_inj; simp at h; simp [h] }, { change -a * ↑d = c * b.succ ↔ a * d = c * -b.succ, constructor; intro h; apply neg_inj; simp at h; simp [h] }, { change -a * d.succ = -c * b.succ ↔ a * -d.succ = c * -b.succ, simp } end, begin intros, simp [mk_pnat], constructor; intro h, { injection h with ha hb, have ha, { have dv := @gcd_abs_dvd_left, have := int.eq_mul_of_div_eq_right dv ha, rw ← int.mul_div_assoc _ dv at this, exact int.eq_mul_of_div_eq_left (dvd_mul_of_dvd_right dv _) this.symm }, have hb, { have dv := λ {a b}, nat.gcd_dvd_right (int.nat_abs a) b, have := nat.eq_mul_of_div_eq_right dv hb, rw ← nat.mul_div_assoc _ dv at this, exact nat.eq_mul_of_div_eq_left (dvd_mul_of_dvd_right dv _) this.symm }, apply eq_of_mul_eq_mul_right _, { rw [mul_assoc, mul_assoc], have := congr (congr_arg (*) ha.symm) (congr_arg coe hb), simp [int.coe_nat_mul] at this, assumption }, { apply mt int.coe_nat_inj, apply ne_of_gt, apply mul_pos; apply nat.gcd_pos_of_pos_right; assumption } }, { have : ∀ a c, a * d = c * b → a / nat.gcd a b = c / nat.gcd c d ∧ b / nat.gcd a b = d / nat.gcd c d, { intros a c h, have bd : b / nat.gcd a b = d / nat.gcd c d, { have : ∀ {a c} (b>0) (d>0), a * d = c * b → b / nat.gcd a b ≤ d / nat.gcd c d, tactic.swap, { exact le_antisymm (this _ hb _ hd h) (this _ hd _ hb h.symm) }, intros a c b hb d hd h, have gb0 := nat.gcd_pos_of_pos_right a hb, have gd0 := nat.gcd_pos_of_pos_right c hd, apply nat.le_of_dvd, apply (nat.le_div_iff_mul_le _ _ gd0).2, simp, apply nat.le_of_dvd hd (nat.gcd_dvd_right _ _), apply (nat.coprime_div_gcd_div_gcd gb0).symm.dvd_of_dvd_mul_left, refine ⟨c / c.gcd d, _⟩, rw [← nat.mul_div_assoc _ (nat.gcd_dvd_left _ _), ← nat.mul_div_assoc _ (nat.gcd_dvd_right _ _)], apply congr_arg (/ c.gcd d), rw [mul_comm, ← nat.mul_div_assoc _ (nat.gcd_dvd_left _ _), mul_comm, h, nat.mul_div_assoc _ (nat.gcd_dvd_right _ _), mul_comm] }, refine ⟨_, bd⟩, apply nat.eq_of_mul_eq_mul_left hb, rw [← nat.mul_div_assoc _ (nat.gcd_dvd_left _ _), mul_comm, nat.mul_div_assoc _ (nat.gcd_dvd_right _ _), bd, ← nat.mul_div_assoc _ (nat.gcd_dvd_right _ _), h, mul_comm, nat.mul_div_assoc _ (nat.gcd_dvd_left _ _)] }, have ha := this a.nat_abs c.nat_abs begin have := congr_arg int.nat_abs h, simp [int.nat_abs_mul] at this, exact this end, tactic.congr_core, { have hs := congr_arg int.sign h, simp [int.sign_eq_one_of_pos (int.coe_nat_lt_coe_nat_of_lt hb), int.sign_eq_one_of_pos (int.coe_nat_lt_coe_nat_of_lt hd)] at hs, conv in a { rw ← int.sign_mul_nat_abs a }, conv in c { rw ← int.sign_mul_nat_abs c }, rw [int.mul_div_assoc, int.mul_div_assoc], exact congr (congr_arg (*) hs) (congr_arg coe ha.left), all_goals { exact int.coe_nat_dvd_coe_nat_of_dvd (nat.gcd_dvd_left _ _) } }, { exact ha.right } } end @[simp] theorem div_mk_div_cancel_left {a b c : ℤ} (c0 : c ≠ 0) : (a * c) /. (b * c) = a /. b := begin by_cases b = 0 with b0, { subst b0, simp }, apply (mk_eq (mul_ne_zero b0 c0) b0).2, simp end theorem num_denom : ∀ a : ℚ, a = a.num /. a.denom | ⟨n, d, h, (c:_=1)⟩ := begin change _ = mk_nat n d, simp [mk_nat, ne_of_gt h, mk_pnat], tactic.congr_core; `[rw c, simp [int.coe_nat_one]] end theorem num_denom' (n d h c) : (⟨n, d, h, c⟩ : ℚ) = n /. d := num_denom _ @[elab_as_eliminator] theorem {u} num_denom_cases_on {C : ℚ → Sort u} : ∀ (a : ℚ) (H : ∀ n d, d > 0 → (int.nat_abs n).coprime d → C (n /. d)), C a | ⟨n, d, h, c⟩ H := by rw num_denom'; exact H n d h c @[elab_as_eliminator] theorem {u} num_denom_cases_on' {C : ℚ → Sort u} (a : ℚ) (H : ∀ (n:ℤ) (d:ℕ), (d:ℤ) ≠ 0 → C (n /. d)) : C a := num_denom_cases_on a $ λ n d h c, H n d $ ne_of_gt (int.coe_nat_lt_coe_nat_of_lt h) protected def add : ℚ → ℚ → ℚ | ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := mk_pnat (n₁ * d₂ + n₂ * d₁) ⟨d₁ * d₂, mul_pos h₁ h₂⟩ instance : has_add ℚ := ⟨rat.add⟩ theorem lift_binop_eq (f : ℚ → ℚ → ℚ) (f₁ : ℤ → ℤ → ℤ → ℤ → ℤ) (f₂ : ℤ → ℤ → ℤ → ℤ → ℤ) (fv : ∀ {n₁ d₁ h₁ c₁ n₂ d₂ h₂ c₂}, f ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ = f₁ n₁ d₁ n₂ d₂ /. f₂ n₁ d₁ n₂ d₂) (f0 : ∀ {n₁ d₁ n₂ d₂} (d₁0 : d₁ ≠ 0) (d₂0 : d₂ ≠ 0), f₂ n₁ d₁ n₂ d₂ ≠ 0) (a b c d : ℤ) (b0 : b ≠ 0) (d0 : d ≠ 0) (H : ∀ {n₁ d₁ n₂ d₂} (h₁ : a * d₁ = n₁ * b) (h₂ : c * d₂ = n₂ * d), f₁ n₁ d₁ n₂ d₂ * f₂ a b c d = f₁ a b c d * f₂ n₁ d₁ n₂ d₂) : f (a /. b) (c /. d) = f₁ a b c d /. f₂ a b c d := begin generalize ha : a /. b = x, cases x with n₁ d₁ h₁ c₁, rw num_denom' at ha, generalize hc : c /. d = x, cases x with n₂ d₂ h₂ c₂, rw num_denom' at hc, rw fv, have d₁0 := ne_of_gt (int.coe_nat_lt_coe_nat_of_lt h₁), have d₂0 := ne_of_gt (int.coe_nat_lt_coe_nat_of_lt h₂), exact (mk_eq (f0 d₁0 d₂0) (f0 b0 d0)).2 (H ((mk_eq b0 d₁0).1 ha) ((mk_eq d0 d₂0).1 hc)) end @[simp] theorem add_def {a b c d : ℤ} (b0 : b ≠ 0) (d0 : d ≠ 0) : a /. b + c /. d = (a * d + c * b) /. (b * d) := begin apply lift_binop_eq rat.add; intros; try {assumption}, { apply mk_pnat_eq }, { apply mul_ne_zero d₁0 d₂0 }, calc (n₁ * d₂ + n₂ * d₁) * (b * d) = (n₁ * b) * d₂ * d + (n₂ * d) * (d₁ * b) : by simp [mul_add, add_mul] ... = (a * d₁) * d₂ * d + (c * d₂) * (d₁ * b) : by rw [h₁, h₂] ... = (a * d + c * b) * (d₁ * d₂) : by simp [mul_add, add_mul] end protected def neg : ℚ → ℚ | ⟨n, d, h, c⟩ := ⟨-n, d, h, by simp [c]⟩ instance : has_neg ℚ := ⟨rat.neg⟩ @[simp] theorem neg_def {a b : ℤ} : -(a /. b) = -a /. b := begin by_cases b = 0 with b0, { subst b0, simp, refl }, generalize ha : a /. b = x, cases x with n₁ d₁ h₁ c₁, rw num_denom' at ha, show rat.mk' _ _ _ _ = _, rw num_denom', have d0 := ne_of_gt (int.coe_nat_lt_coe_nat_of_lt h₁), apply (mk_eq d0 b0).2, have h₁ := (mk_eq b0 d0).1 ha, simp only [neg_mul_eq_neg_mul_symm, congr_arg has_neg.neg h₁] end protected def mul : ℚ → ℚ → ℚ | ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := mk_pnat (n₁ * n₂) ⟨d₁ * d₂, mul_pos h₁ h₂⟩ instance : has_mul ℚ := ⟨rat.mul⟩ @[simp] theorem mul_def {a b c d : ℤ} (b0 : b ≠ 0) (d0 : d ≠ 0) : (a /. b) * (c /. d) = (a * c) /. (b * d) := begin apply lift_binop_eq rat.mul; intros; try {assumption}, { apply mk_pnat_eq }, { apply mul_ne_zero d₁0 d₂0 }, cc end protected def inv : ℚ → ℚ | ⟨(n+1:ℕ), d, h, c⟩ := ⟨d, n+1, n.succ_pos, c.symm⟩ | ⟨0, d, h, c⟩ := 0 | ⟨-[1+ n], d, h, c⟩ := ⟨-d, n+1, n.succ_pos, nat.coprime.symm $ by simp; exact c⟩ instance : has_inv ℚ := ⟨rat.inv⟩ @[simp] theorem inv_def {a b : ℤ} : (a /. b)⁻¹ = b /. a := begin by_cases a = 0 with a0, { subst a0, simp, refl }, by_cases b = 0 with b0, { subst b0, simp, refl }, generalize ha : a /. b = x, cases x with n d h c, rw num_denom' at ha, refine eq.trans (_ : rat.inv ⟨n, d, h, c⟩ = d /. n) _, { cases n with n; [cases n with n, skip], { refl }, { change int.of_nat n.succ with (n+1:ℕ), simp [rat.inv], rw num_denom' }, { simp [rat.inv], rw num_denom', refl } }, have n0 : n ≠ 0, { refine mt (λ (n0 : n = 0), _) a0, subst n0, simp at ha, exact (mk_eq_zero b0).1 ha }, have d0 := ne_of_gt (int.coe_nat_lt_coe_nat_of_lt h), have ha := (mk_eq b0 d0).1 ha, apply (mk_eq n0 a0).2, cc end variables (a b c : ℚ) protected theorem add_zero : a + 0 = a := num_denom_cases_on' a $ λ n d h, by rw [← zero_mk d]; simp [h, -zero_mk] protected theorem zero_add : 0 + a = a := num_denom_cases_on' a $ λ n d h, by rw [← zero_mk d]; simp [h, -zero_mk] protected theorem add_comm : a + b = b + a := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, by simp [h₁, h₂] protected theorem add_assoc : a + b + c = a + (b + c) := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, num_denom_cases_on' c $ λ n₃ d₃ h₃, by simp [h₁, h₂, h₃, mul_ne_zero, mul_add] protected theorem add_left_neg : -a + a = 0 := num_denom_cases_on' a $ λ n d h, by simp [h] protected theorem mul_one : a * 1 = a := num_denom_cases_on' a $ λ n d h, by change (1:ℚ) with 1 /. 1; simp [h] protected theorem one_mul : 1 * a = a := num_denom_cases_on' a $ λ n d h, by change (1:ℚ) with 1 /. 1; simp [h] protected theorem mul_comm : a * b = b * a := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, by simp [h₁, h₂] protected theorem mul_assoc : a * b * c = a * (b * c) := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, num_denom_cases_on' c $ λ n₃ d₃ h₃, by simp [h₁, h₂, h₃, mul_ne_zero] protected theorem add_mul : (a + b) * c = a * c + b * c := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, num_denom_cases_on' c $ λ n₃ d₃ h₃, by simp [h₁, h₂, h₃, mul_ne_zero]; refine (div_mk_div_cancel_left h₃).symm.trans _; simp [mul_add] protected theorem mul_add : a * (b + c) = a * b + a * c := by rw [rat.mul_comm, rat.add_mul, rat.mul_comm, rat.mul_comm c a] protected theorem zero_ne_one : 0 ≠ (1:ℚ) := mt (λ (h : 0 = 1 /. 1), (mk_eq_zero one_ne_zero).1 h.symm) one_ne_zero protected theorem mul_inv_cancel : a ≠ 0 → a * a⁻¹ = 1 := num_denom_cases_on' a $ λ n d h a0, have n0 : n ≠ 0, from mt (by intro e; subst e; simp) a0, by simp [h, n0]; exact eq.trans (by simp) (@div_mk_div_cancel_left 1 1 _ n0) protected theorem inv_mul_cancel (h : a ≠ 0) : a⁻¹ * a = 1 := eq.trans (rat.mul_comm _ _) (rat.mul_inv_cancel _ h) instance : decidable_eq ℚ := by tactic.mk_dec_eq_instance instance field_rat : discrete_field ℚ := { zero := 0, add := rat.add, neg := rat.neg, one := 1, mul := rat.mul, inv := rat.inv, zero_add := rat.zero_add, add_zero := rat.add_zero, add_comm := rat.add_comm, add_assoc := rat.add_assoc, add_left_neg := rat.add_left_neg, mul_one := rat.mul_one, one_mul := rat.one_mul, mul_comm := rat.mul_comm, mul_assoc := rat.mul_assoc, left_distrib := rat.mul_add, right_distrib := rat.add_mul, zero_ne_one := rat.zero_ne_one, mul_inv_cancel := rat.mul_inv_cancel, inv_mul_cancel := rat.inv_mul_cancel, has_decidable_eq := rat.decidable_eq, inv_zero := rfl } theorem sub_def {a b c d : ℤ} (b0 : b ≠ 0) (d0 : d ≠ 0) : a /. b - c /. d = (a * d - c * b) /. (b * d) := by simp [b0, d0] protected def nonneg : ℚ → Prop | ⟨n, d, h, c⟩ := n ≥ 0 @[simp] theorem mk_nonneg (a : ℤ) {b : ℤ} (h : b > 0) : (a /. b).nonneg ↔ a ≥ 0 := begin generalize ha : a /. b = x, cases x with n₁ d₁ h₁ c₁, rw num_denom' at ha, simp [rat.nonneg], have d0 := int.coe_nat_lt_coe_nat_of_lt h₁, have := (mk_eq (ne_of_gt h) (ne_of_gt d0)).1 ha, constructor; intro h₂, { apply nonneg_of_mul_nonneg_right _ d0, rw this, exact mul_nonneg h₂ (le_of_lt h) }, { apply nonneg_of_mul_nonneg_right _ h, rw ← this, exact mul_nonneg h₂ (int.coe_zero_le _) }, end protected def nonneg_add {a b} : rat.nonneg a → rat.nonneg b → rat.nonneg (a + b) := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, begin have d₁0 : (d₁:ℤ) > 0 := lt_of_le_of_ne (int.coe_zero_le _) h₁.symm, have d₂0 : (d₂:ℤ) > 0 := lt_of_le_of_ne (int.coe_zero_le _) h₂.symm, simp [d₁0, d₂0, h₁, h₂, mul_pos d₁0 d₂0], intros n₁0 n₂0, apply add_nonneg; apply mul_nonneg; {assumption <|> apply int.coe_zero_le} end protected def nonneg_mul {a b} : rat.nonneg a → rat.nonneg b → rat.nonneg (a * b) := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, begin have d₁0 : (d₁:ℤ) > 0 := lt_of_le_of_ne (int.coe_zero_le _) h₁.symm, have d₂0 : (d₂:ℤ) > 0 := lt_of_le_of_ne (int.coe_zero_le _) h₂.symm, simp [d₁0, d₂0, h₁, h₂, mul_pos d₁0 d₂0], exact mul_nonneg end protected def nonneg_antisymm {a} : rat.nonneg a → rat.nonneg (-a) → a = 0 := num_denom_cases_on' a $ λ n d h, begin have d0 : (d:ℤ) > 0 := lt_of_le_of_ne (int.coe_zero_le _) h.symm, simp [d0, h], exact λ h₁ h₂, le_antisymm (nonpos_of_neg_nonneg h₂) h₁ end protected def nonneg_total : rat.nonneg a ∨ rat.nonneg (-a) := by cases a with n; exact or.imp_right neg_nonneg_of_nonpos (le_total 0 n) instance decidable_nonneg : decidable (rat.nonneg a) := by cases a; unfold rat.nonneg; apply_instance protected def le (a b : ℚ) := rat.nonneg (b - a) instance : has_le ℚ := ⟨rat.le⟩ instance decidable_le : decidable_rel ((≤) : ℚ → ℚ → Prop) := show ∀ a b, decidable (rat.nonneg (b - a)), by intros; apply_instance protected theorem le_def {a b c d : ℤ} (b0 : b > 0) (d0 : d > 0) : a /. b ≤ c /. d ↔ a * d ≤ c * b := show rat.nonneg _ ↔ _, by simpa [ne_of_gt b0, ne_of_gt d0, mul_pos b0 d0] using @sub_nonneg _ _ (b * c) (a * d) protected theorem le_refl : a ≤ a := show rat.nonneg (a - a), by rw sub_self; exact le_refl (0 : ℤ) protected theorem le_total : a ≤ b ∨ b ≤ a := by have := rat.nonneg_total (b - a); rwa neg_sub at this protected theorem le_antisymm {a b : ℚ} (hab : a ≤ b) (hba : b ≤ a) : a = b := by have := eq_neg_of_add_eq_zero (rat.nonneg_antisymm hba $ by simpa); rwa neg_neg at this protected theorem le_trans {a b c : ℚ} (hab : a ≤ b) (hbc : b ≤ c) : a ≤ c := by simpa using rat.nonneg_add hab hbc instance : linear_order ℚ := { le := rat.le, lt := λa b, ¬ b ≤ a, lt_iff_le_not_le := assume a b, iff.intro (assume h, ⟨or.resolve_left (rat.le_total _ _) h, h⟩) (assume ⟨h1, h2⟩, h2), le_refl := rat.le_refl, le_trans := @rat.le_trans, le_antisymm := @rat.le_antisymm, le_total := rat.le_total } theorem nonneg_iff_zero_le {a} : rat.nonneg a ↔ 0 ≤ a := show rat.nonneg a ↔ rat.nonneg (a - 0), by simp theorem mk_le {a b c d : ℤ} (h₁ : b > 0) (h₂ : d > 0) : a /. b ≤ c /. d ↔ a * d ≤ c * b := by conv in (_ ≤ _) { simp only [(≤), rat.le], rw [sub_def (ne_of_gt h₂) (ne_of_gt h₁), mk_nonneg _ (mul_pos h₂ h₁), ge, sub_nonneg] } protected theorem add_le_add_left {a b c : ℚ} : c + a ≤ c + b ↔ a ≤ b := by unfold has_le.le rat.le; rw add_sub_add_left_eq_sub protected theorem mul_nonneg {a b : ℚ} (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a * b := by rw ← nonneg_iff_zero_le at ha hb ⊢; exact rat.nonneg_mul ha hb instance : discrete_linear_ordered_field ℚ := { rat.field_rat with le := (≤), lt := (<), le_refl := le_refl, le_trans := @rat.le_trans, le_antisymm := assume a b, le_antisymm, le_total := le_total, lt_iff_le_not_le := @lt_iff_le_not_le _ _, zero_lt_one := show ¬ (0:ℤ) ≤ -1, from dec_trivial, add_le_add_left := assume a b ab c, rat.add_le_add_left.2 ab, add_lt_add_left := assume a b ab c ba, ab $ rat.add_le_add_left.1 ba, mul_nonneg := @rat.mul_nonneg, mul_pos := assume a b ha hb, lt_of_le_of_ne (rat.mul_nonneg (le_of_lt ha) (le_of_lt hb)) (mul_ne_zero (ne_of_lt ha).symm (ne_of_lt hb).symm).symm, decidable_eq := by apply_instance, decidable_le := assume a b, rat.decidable_nonneg (b - a), decidable_lt := by apply_instance } theorem coe_int_eq_mk (z : ℤ) : ↑z = z /. 1 := num_denom' _ _ _ _ theorem coe_nat_rat_eq_mk (n : ℕ) : ↑n = ↑n /. 1 := coe_int_eq_mk _ theorem coe_int_inj {z₁ z₂ : ℤ} : (z₁ : ℚ) = z₂ ↔ z₁ = z₂ := by simp [coe_int_eq_mk, mk_eq] theorem coe_int_add (z₁ z₂ : ℤ) : ↑(z₁ + z₂) = (↑z₁ + ↑z₂ : ℚ) := by simp [coe_int_eq_mk] theorem coe_int_neg (z : ℤ) : ↑(-z) = (-↑z : ℚ) := by simp [coe_int_eq_mk] theorem coe_int_sub (z₁ z₂ : ℤ) : ↑(z₁ - z₂) = (↑z₁ - ↑z₂ : ℚ) := by simp [coe_int_eq_mk] theorem coe_int_mul (z₁ z₂ : ℤ) : ↑(z₁ * z₂) = (↑z₁ * ↑z₂ : ℚ) := by simp [coe_int_eq_mk] theorem coe_int_one : ↑(1 : ℤ) = (1 : ℚ) := rfl theorem coe_int_le {z₁ z₂ : ℤ} : (↑z₁ : ℚ) ≤ ↑z₂ ↔ z₁ ≤ z₂ := by simp [coe_int_eq_mk, mk_le zero_lt_one zero_lt_one] theorem coe_int_lt {z₁ z₂ : ℤ} : (↑z₁ : ℚ) < ↑z₂ ↔ z₁ < z₂ := not_iff_not.1 $ by rw [not_lt, not_lt, coe_int_le] def floor : ℚ → ℤ | ⟨n, d, h, c⟩ := n / d def ceil (r : ℚ) : ℤ := -(floor (-r)) theorem le_floor {z : ℤ} : ∀ {r : ℚ}, z ≤ floor r ↔ (z : ℚ) ≤ r | ⟨n, d, h, c⟩ := begin simp [floor], rw [num_denom'], have h' := int.coe_nat_lt_coe_nat_of_lt h, conv { to_rhs, rw [coe_int_eq_mk, mk_le zero_lt_one h', mul_one] }, exact int.le_div_iff_mul_le h' end theorem floor_lt {r : ℚ} {z : ℤ} : floor r < z ↔ r < z := not_iff_not.1 $ by rw [not_lt_iff, not_lt_iff, le_floor] theorem floor_le (r : ℚ) : (floor r : ℚ) ≤ r := le_floor.1 (le_refl _) theorem lt_succ_floor (r : ℚ) : r < (floor r).succ := floor_lt.1 $ int.lt_succ_self _ @[simp] theorem floor_coe (z : ℤ) : floor z = z := eq_of_forall_le_iff $ λ a, by rw [le_floor, coe_int_le] theorem floor_mono {a b : ℚ} (h : a ≤ b) : floor a ≤ floor b := le_floor.2 (le_trans (floor_le _) h) @[simp] theorem floor_add_int (r : ℚ) (z : ℤ) : floor (r + z) = floor r + z := le_antisymm (le_add_of_sub_right_le $ le_floor.2 $ by rw coe_int_sub; exact sub_right_le_of_le_add (floor_le _)) (le_floor.2 $ by rw [coe_int_add]; apply add_le_add_right (floor_le _)) theorem floor_sub_int (r : ℚ) (z : ℤ) : floor (r - z) = floor r - z := floor_add_int _ _ theorem ceil_le {z : ℤ} {r : ℚ} : ceil r ≤ z ↔ r ≤ z := by rw [ceil, neg_le, le_floor, coe_int_neg, neg_le_neg_iff] theorem le_ceil (r : ℚ) : r ≤ ceil r := ceil_le.1 (le_refl _) @[simp] theorem ceil_coe (z : ℤ) : ceil z = z := by rw [ceil, ← coe_int_neg, floor_coe, neg_neg] theorem ceil_mono {a b : ℚ} (h : a ≤ b) : ceil a ≤ ceil b := ceil_le.2 (le_trans h (le_ceil _)) @[simp] theorem ceil_add_int (r : ℚ) (z : ℤ) : ceil (r + z) = ceil r + z := by rw [ceil, neg_add', floor_sub_int, neg_sub, sub_eq_neg_add]; refl theorem ceil_sub_int (r : ℚ) (z : ℤ) : ceil (r - z) = ceil r - z := ceil_add_int _ _ /- nat ceiling -/ def nat_ceil (q : ℚ) : ℕ := int.to_nat (ceil q) theorem nat_ceil_le {q : ℚ} {n : ℕ} : nat_ceil q ≤ n ↔ q ≤ n := by rw [nat_ceil, int.to_nat_le, ceil_le]; refl theorem lt_nat_ceil {q : ℚ} {n : ℕ} : n < nat_ceil q ↔ (n : ℚ) < q := not_iff_not.1 $ by rw [not_lt_iff, not_lt_iff, nat_ceil_le] theorem le_nat_ceil (q : ℚ) : q ≤ nat_ceil q := nat_ceil_le.1 (le_refl _) theorem nat_ceil_mono {q₁ q₂ : ℚ} (h : q₁ ≤ q₂) : nat_ceil q₁ ≤ nat_ceil q₂ := nat_ceil_le.2 (le_trans h (le_nat_ceil _)) @[simp] theorem nat_ceil_coe (n : ℕ) : nat_ceil n = n := show (ceil (n:ℤ)).to_nat = n, by rw [ceil_coe]; refl @[simp] theorem nat_ceil_zero : nat_ceil 0 = 0 := nat_ceil_coe 0 theorem nat_ceil_add_nat {q : ℚ} (hq : 0 ≤ q) (n : ℕ) : nat_ceil (q + n) = nat_ceil q + n := show int.to_nat (ceil (q + (n:ℤ))) = int.to_nat (ceil q) + n, by rw [ceil_add_int]; exact match ceil q, int.eq_coe_of_zero_le (ceil_mono hq) with | _, ⟨m, rfl⟩ := rfl end theorem nat_ceil_lt_add_one {q : ℚ} (hq : q ≥ 0) : ↑(nat_ceil q) < q + 1 := lt_nat_ceil.1 $ by rw [ show nat_ceil (q+1) = nat_ceil q+1, from nat_ceil_add_nat hq 1]; apply nat.lt_succ_self instance : encodable ℚ := ⟨λ⟨n, d, _, _⟩, encodable.encode (n, d), λn, match encodable.decode (ℤ × ℕ) n with | option.some ⟨n, d⟩ := if h : d > 0 ∧ n.nat_abs.coprime d then option.some ⟨n, d, h.1, h.2⟩ else option.none | option.none := option.none end, assume ⟨n, d, hn, hd⟩, by simp [encodable._match_1, encodable._match_2, encodable.encodek, hn, hd]⟩ end rat
0a09114548a97a3c953012584b9dd10c121dcfee
86f6f4f8d827a196a32bfc646234b73328aeb306
/examples/sets_functions_and_relations/unnamed_808.lean
747f3edb9b47d1ddc328e3d43dd2bad7125d69f8
[]
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
176
lean
import data.set.function variables {α β : Type*} variable f : α → β variables u v : set β example : f ⁻¹' (u ∩ v) = f ⁻¹' u ∩ f ⁻¹' v := by { ext, refl }
4cc6813b71b39b4761740d7467e1fa7d4f761ea4
367134ba5a65885e863bdc4507601606690974c1
/src/category_theory/monad/limits.lean
c9fd490c2c6dece452cc0670a6710945c6d83f80
[ "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
13,861
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Bhavik Mehta -/ import category_theory.monad.adjunction import category_theory.adjunction.limits import category_theory.limits.preserves.shapes.terminal namespace category_theory open category open category_theory.limits universes v₁ v₂ u₁ u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation namespace monad variables {C : Type u₁} [category.{v₁} C] variables {T : monad C} variables {J : Type v₁} [small_category J] namespace forget_creates_limits variables (D : J ⥤ algebra T) (c : cone (D ⋙ forget T)) (t : is_limit c) /-- (Impl) The natural transformation used to define the new cone -/ @[simps] def γ : (D ⋙ forget T ⋙ ↑T) ⟶ (D ⋙ forget T) := { app := λ j, (D.obj j).a } /-- (Impl) This new cone is used to construct the algebra structure -/ @[simps] def new_cone : cone (D ⋙ forget T) := { X := T.obj c.X, π := (functor.const_comp _ _ ↑T).inv ≫ whisker_right c.π T ≫ (γ D) } /-- The algebra structure which will be the apex of the new limit cone for `D`. -/ @[simps] def cone_point : algebra T := { A := c.X, a := t.lift (new_cone D c), unit' := begin apply t.hom_ext, intro j, erw [category.assoc, t.fac (new_cone D c), id_comp], dsimp, erw [id_comp, ← category.assoc, ← T.η.naturality, functor.id_map, category.assoc, (D.obj j).unit, comp_id], end, assoc' := begin apply t.hom_ext, intro j, rw [category.assoc, category.assoc, t.fac (new_cone D c)], dsimp, erw id_comp, slice_lhs 1 2 {rw ← T.μ.naturality}, slice_lhs 2 3 {rw (D.obj j).assoc}, slice_rhs 1 2 {rw ← (T : C ⥤ C).map_comp}, rw t.fac (new_cone D c), dsimp, erw [id_comp, functor.map_comp, category.assoc] end } /-- (Impl) Construct the lifted cone in `algebra T` which will be limiting. -/ @[simps] def lifted_cone : cone D := { X := cone_point D c t, π := { app := λ j, { f := c.π.app j }, naturality' := λ X Y f, by { ext1, dsimp, erw c.w f, simp } } } /-- (Impl) Prove that the lifted cone is limiting. -/ @[simps] def lifted_cone_is_limit : is_limit (lifted_cone D c t) := { lift := λ s, { f := t.lift ((forget T).map_cone s), h' := begin apply t.hom_ext, intro j, slice_rhs 2 3 {rw t.fac ((forget T).map_cone s) j}, dsimp, slice_lhs 2 3 {rw t.fac (new_cone D c) j}, dsimp, rw category.id_comp, slice_lhs 1 2 {rw ← (T : C ⥤ C).map_comp}, rw t.fac ((forget T).map_cone s) j, exact (s.π.app j).h end }, uniq' := λ s m J, begin ext1, apply t.hom_ext, intro j, simpa [t.fac (functor.map_cone (forget T) s) j] using congr_arg algebra.hom.f (J j), end } end forget_creates_limits -- Theorem 5.6.5 from [Riehl][riehl2017] /-- The forgetful functor from the Eilenberg-Moore category creates limits. -/ instance forget_creates_limits : creates_limits (forget T) := { creates_limits_of_shape := λ J 𝒥, by exactI { creates_limit := λ D, creates_limit_of_reflects_iso (λ c t, { lifted_cone := forget_creates_limits.lifted_cone D c t, valid_lift := cones.ext (iso.refl _) (λ j, (id_comp _).symm), makes_limit := forget_creates_limits.lifted_cone_is_limit _ _ _ } ) } } /-- `D ⋙ forget T` has a limit, then `D` has a limit. -/ lemma has_limit_of_comp_forget_has_limit (D : J ⥤ algebra T) [has_limit (D ⋙ forget T)] : has_limit D := has_limit_of_created D (forget T) namespace forget_creates_colimits -- Let's hide the implementation details in a namespace variables {D : J ⥤ algebra T} (c : cocone (D ⋙ forget T)) (t : is_colimit c) -- We have a diagram D of shape J in the category of algebras, and we assume that we are given a -- colimit for its image D ⋙ forget T under the forgetful functor, say its apex is L. -- We'll construct a colimiting coalgebra for D, whose carrier will also be L. -- To do this, we must find a map TL ⟶ L. Since T preserves colimits, TL is also a colimit. -- In particular, it is a colimit for the diagram `(D ⋙ forget T) ⋙ T` -- so to construct a map TL ⟶ L it suffices to show that L is the apex of a cocone for this diagram. -- In other words, we need a natural transformation from const L to `(D ⋙ forget T) ⋙ T`. -- But we already know that L is the apex of a cocone for the diagram `D ⋙ forget T`, so it -- suffices to give a natural transformation `((D ⋙ forget T) ⋙ T) ⟶ (D ⋙ forget T)`: /-- (Impl) The natural transformation given by the algebra structure maps, used to construct a cocone `c` with apex `colimit (D ⋙ forget T)`. -/ @[simps] def γ : ((D ⋙ forget T) ⋙ ↑T) ⟶ (D ⋙ forget T) := { app := λ j, (D.obj j).a } /-- (Impl) A cocone for the diagram `(D ⋙ forget T) ⋙ T` found by composing the natural transformation `γ` with the colimiting cocone for `D ⋙ forget T`. -/ @[simps] def new_cocone : cocone ((D ⋙ forget T) ⋙ ↑T) := { X := c.X, ι := γ ≫ c.ι } variables [preserves_colimit (D ⋙ forget T) (T : C ⥤ C)] /-- (Impl) Define the map `λ : TL ⟶ L`, which will serve as the structure of the coalgebra on `L`, and we will show is the colimiting object. We use the cocone constructed by `c` and the fact that `T` preserves colimits to produce this morphism. -/ @[reducible] def lambda : ((T : C ⥤ C).map_cocone c).X ⟶ c.X := (preserves_colimit.preserves t).desc (new_cocone c) /-- (Impl) The key property defining the map `λ : TL ⟶ L`. -/ lemma commuting (j : J) : T.map (c.ι.app j) ≫ lambda c t = (D.obj j).a ≫ c.ι.app j := is_colimit.fac (preserves_colimit.preserves t) (new_cocone c) j variables [preserves_colimit ((D ⋙ forget T) ⋙ ↑T) (T : C ⥤ C)] /-- (Impl) Construct the colimiting algebra from the map `λ : TL ⟶ L` given by `lambda`. We are required to show it satisfies the two algebra laws, which follow from the algebra laws for the image of `D` and our `commuting` lemma. -/ @[simps] def cocone_point : algebra T := { A := c.X, a := lambda c t, unit' := begin apply t.hom_ext, intro j, erw [comp_id, ← category.assoc, T.η.naturality, category.assoc, commuting, ← category.assoc], erw algebra.unit, apply id_comp end, assoc' := begin apply is_colimit.hom_ext (preserves_colimit.preserves (preserves_colimit.preserves t)), intro j, erw [← category.assoc, T.μ.naturality, ← functor.map_cocone_ι_app, category.assoc, is_colimit.fac _ (new_cocone c) j], rw ← category.assoc, erw [← functor.map_comp, commuting], dsimp, erw [← category.assoc, algebra.assoc, category.assoc, functor.map_comp, category.assoc, commuting], apply_instance, apply_instance end } /-- (Impl) Construct the lifted cocone in `algebra T` which will be colimiting. -/ @[simps] def lifted_cocone : cocone D := { X := cocone_point c t, ι := { app := λ j, { f := c.ι.app j, h' := commuting _ _ _ }, naturality' := λ A B f, by { ext1, dsimp, erw [comp_id, c.w] } } } /-- (Impl) Prove that the lifted cocone is colimiting. -/ @[simps] def lifted_cocone_is_colimit : is_colimit (lifted_cocone c t) := { desc := λ s, { f := t.desc ((forget T).map_cocone s), h' := begin dsimp, apply is_colimit.hom_ext (preserves_colimit.preserves t), intro j, rw ← category.assoc, erw ← functor.map_comp, erw t.fac', rw ← category.assoc, erw forget_creates_colimits.commuting, rw category.assoc, rw t.fac', apply algebra.hom.h, apply_instance end }, uniq' := λ s m J, by { ext1, apply t.hom_ext, intro j, simpa using congr_arg algebra.hom.f (J j) } } end forget_creates_colimits open forget_creates_colimits -- TODO: the converse of this is true as well /-- The forgetful functor from the Eilenberg-Moore category for a monad creates any colimit which the monad itself preserves. -/ instance forget_creates_colimit (D : J ⥤ algebra T) [preserves_colimit (D ⋙ forget T) (T : C ⥤ C)] [preserves_colimit ((D ⋙ forget T) ⋙ ↑T) (T : C ⥤ C)] : creates_colimit D (forget T) := creates_colimit_of_reflects_iso $ λ c t, { lifted_cocone := { X := cocone_point c t, ι := { app := λ j, { f := c.ι.app j, h' := commuting _ _ _ }, naturality' := λ A B f, by { ext1, dsimp, erw [comp_id, c.w] } } }, valid_lift := cocones.ext (iso.refl _) (by tidy), makes_colimit := lifted_cocone_is_colimit _ _ } instance forget_creates_colimits_of_shape [preserves_colimits_of_shape J (T : C ⥤ C)] : creates_colimits_of_shape J (forget T) := { creates_colimit := λ K, by apply_instance } instance forget_creates_colimits [preserves_colimits (T : C ⥤ C)] : creates_colimits (forget T) := { creates_colimits_of_shape := λ J 𝒥₁, by apply_instance } /-- For `D : J ⥤ algebra T`, `D ⋙ forget T` has a colimit, then `D` has a colimit provided colimits of shape `J` are preserved by `T`. -/ lemma forget_creates_colimits_of_monad_preserves [preserves_colimits_of_shape J (T : C ⥤ C)] (D : J ⥤ algebra T) [has_colimit (D ⋙ forget T)] : has_colimit D := has_colimit_of_created D (forget T) end monad variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₁} D] variables {J : Type v₁} [small_category J] instance comp_comparison_forget_has_limit (F : J ⥤ D) (R : D ⥤ C) [monadic_right_adjoint R] [has_limit (F ⋙ R)] : has_limit ((F ⋙ monad.comparison (adjunction.of_right_adjoint R)) ⋙ monad.forget _) := @has_limit_of_iso _ _ _ _ (F ⋙ R) _ _ (iso_whisker_left F (monad.comparison_forget (adjunction.of_right_adjoint R)).symm) instance comp_comparison_has_limit (F : J ⥤ D) (R : D ⥤ C) [monadic_right_adjoint R] [has_limit (F ⋙ R)] : has_limit (F ⋙ monad.comparison (adjunction.of_right_adjoint R)) := monad.has_limit_of_comp_forget_has_limit (F ⋙ monad.comparison (adjunction.of_right_adjoint R)) /-- Any monadic functor creates limits. -/ def monadic_creates_limits (R : D ⥤ C) [monadic_right_adjoint R] : creates_limits R := creates_limits_of_nat_iso (monad.comparison_forget (adjunction.of_right_adjoint R)) /-- The forgetful functor from the Eilenberg-Moore category for a monad creates any colimit which the monad itself preserves. -/ def monadic_creates_colimit_of_preserves_colimit (R : D ⥤ C) (K : J ⥤ D) [monadic_right_adjoint R] [preserves_colimit (K ⋙ R) (left_adjoint R ⋙ R)] [preserves_colimit ((K ⋙ R) ⋙ left_adjoint R ⋙ R) (left_adjoint R ⋙ R)] : creates_colimit K R := begin apply creates_colimit_of_nat_iso (monad.comparison_forget (adjunction.of_right_adjoint R)), apply category_theory.comp_creates_colimit _ _, apply_instance, let i : ((K ⋙ monad.comparison (adjunction.of_right_adjoint R)) ⋙ monad.forget _) ≅ K ⋙ R := functor.associator _ _ _ ≪≫ iso_whisker_left K (monad.comparison_forget (adjunction.of_right_adjoint R)), apply category_theory.monad.forget_creates_colimit _, { dsimp, refine preserves_colimit_of_iso_diagram _ i.symm }, { dsimp, refine preserves_colimit_of_iso_diagram _ (iso_whisker_right i (left_adjoint R ⋙ R)).symm }, end /-- A monadic functor creates any colimits of shapes it preserves. -/ def monadic_creates_colimits_of_shape_of_preserves_colimits_of_shape (R : D ⥤ C) [monadic_right_adjoint R] [preserves_colimits_of_shape J R] : creates_colimits_of_shape J R := begin have : preserves_colimits_of_shape J (left_adjoint R ⋙ R), { apply category_theory.limits.comp_preserves_colimits_of_shape _ _, { haveI := adjunction.left_adjoint_preserves_colimits (adjunction.of_right_adjoint R), apply_instance }, apply_instance }, exactI ⟨λ K, monadic_creates_colimit_of_preserves_colimit _ _⟩, end /-- A monadic functor creates colimits if it preserves colimits. -/ def monadic_creates_colimits_of_preserves_colimits (R : D ⥤ C) [monadic_right_adjoint R] [preserves_colimits R] : creates_colimits R := { creates_colimits_of_shape := λ J 𝒥₁, by exactI monadic_creates_colimits_of_shape_of_preserves_colimits_of_shape _ } section lemma has_limit_of_reflective (F : J ⥤ D) (R : D ⥤ C) [has_limit (F ⋙ R)] [reflective R] : has_limit F := by { haveI := monadic_creates_limits R, exact has_limit_of_created F R } /-- If `C` has limits of shape `J` then any reflective subcategory has limits of shape `J`. -/ lemma has_limits_of_shape_of_reflective [has_limits_of_shape J C] (R : D ⥤ C) [reflective R] : has_limits_of_shape J D := { has_limit := λ F, has_limit_of_reflective F R } /-- If `C` has limits then any reflective subcategory has limits. -/ lemma has_limits_of_reflective (R : D ⥤ C) [has_limits C] [reflective R] : has_limits D := { has_limits_of_shape := λ J 𝒥₁, by exactI has_limits_of_shape_of_reflective R } /-- The reflector always preserves terminal objects. Note this in general doesn't apply to any other limit. -/ noncomputable def left_adjoint_preserves_terminal_of_reflective (R : D ⥤ C) [reflective R] [has_terminal C] : preserves_limits_of_shape (discrete pempty) (left_adjoint R) := { preserves_limit := λ K, begin letI : has_terminal D := has_limits_of_shape_of_reflective R, letI := monadic_creates_limits R, letI := category_theory.preserves_limit_of_creates_limit_and_has_limit (functor.empty _) R, letI : preserves_limit (functor.empty _) (left_adjoint R), { apply preserves_terminal_of_iso, apply _ ≪≫ as_iso ((adjunction.of_right_adjoint R).counit.app (⊤_ D)), apply (left_adjoint R).map_iso (preserves_terminal.iso R).symm }, apply preserves_limit_of_iso_diagram (left_adjoint R) (functor.unique_from_empty _).symm, end } end end category_theory
a15c5a7c670cb903ee85060a57217a32e35a8786
1ce2e14f78a7f514bae439fbbb1f7fa2932dd7dd
/src/vol1/chap2.lean
e00ac92b819461214bf072553df1ae67c813d5b2
[ "MIT" ]
permissive
wudcscheme/lean-mathgirls
b88faf76d12e5ca07b83d6e5580663380b0bb45c
95b64a33ffb34f3c45e212c4adff3cc988dcbc60
refs/heads/master
1,678,994,115,961
1,585,127,877,000
1,585,127,877,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
12,051
lean
-- Chapter 2. Love Letters Called Formulas import init.data.list.lemmas init.data.nat.lemmas init.data.list.basic init.data.int.order import tactic.norm_num tactic.tauto tactic tactic.basic import ..common ..list ..factorize open tactic local attribute [simp, reducible] nat.factors local attribute [simp, reducible] ite example: 1024 = 2^10 := rfl #eval divisors 1024 -- TIMEOUT -- lemma divisors_of_1024: divisors 1024 = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024] := begin -- norm_num, -- reflexivity, -- end #eval (divisors 1024).length -- = 11 #eval (divisors 1024).sum -- 2047 #print nat.prime -- the definition of primes example: ¬ (nat.prime 1) := begin unfold nat.prime, intro h, let h:=h.left, have: ¬ (2 ≤ 1), from dec_trivial, contradiction end -- Regarding `1` a prime brakes prime-decomposition uniqueness example: 24=2*2*2*3 ∧ 24=1*2*2*2*3 ∧ 24=1*1*2*2*2*3 := by repeat {split}; reflexivity example {x: ℤ}: x = -3 -> abs(-x) = 3 := begin intro h, calc abs(-x) = abs(-(-3)): by rw [h] ... = abs(3): rfl ... = 3: rfl end section sec_2_7 -- Problem 2.7: -- Let n: ℕ ≥ 1, show how to derive "the sum of n's divisors". @[simp, reducible] def sumdiv (n: ℕ) := (divisors n).sum #eval sumdiv 1024 -- = 2047 #eval sumdiv 6 -- = 12 open pnat open decidable -- sum_pow (n, e) = Σ n^k (k = 0...e) -- For notational bravity, recall geom p=(n, e) = [n^0, n^1, n^e], abbr. <| p |> @[simp, reducible] def sum_pow (p: ℕ × ℕ) := <| p |>.sum #eval sum_pow (2, 10) -- = 2047 -- A wrong equation: -- let n = factorize n = p1^b1 * p2^b2 * ... pm^bm, where -- pi: ℙ, bi ≥ 1, -- sumdiv n = (sum_pow p1 b1) + ... + (sum_pow pm bm) = Σ(sum_pow pi bi) (i=1..m) :: wrong! @[simp, reducible] def sum_sum_pow (n: ℕ) := (list.map sum_pow (factorize n)).sum -- shorthand #eval sum_sum_pow 6 -- = 7 def wrong_eqn := ∀ n, sumdiv n = sum_sum_pow n -- Show wrong_eqn is indeed wrong, by -- sumdiv 6 = 12 ≠ sum_sum_pow 6 = 7 -- I'll excessively use `factorize 6`, for which dumb `simp factorize 6` timeouts; -- so, hand-reproduce the outcome here lemma factorize_6: factorize 6 = [(2,1), (3,1)] := begin unfold factorize, have: nat.factors 6 = [2, 3], { unfold nat.factors, have: nat.min_fac (4+2) = 2, { unfold nat.min_fac, have: 2 ∣ 4, by norm_num, have: ite (2 ∣ 4) 2 _ = 2, by apply if_pos; assumption, assumption, }, rw this, clear this, simp, have: nat.factors 3 = [3], { unfold nat.factors, have: nat.min_fac 3 = 3, { unfold nat.min_fac, have: (nat.min_fac_aux (1 + 2) 3) = 3, { rw nat.min_fac_aux, reflexivity, }, rw this, clear this, have: ¬ (2 ∣ 1), by norm_num, have: ite (2 ∣ 1) _ 3 = 3, by apply if_neg; assumption, assumption, }, rw this, clear this, simp, }, have triv3: (nat.succ (4/2)) = 3, by reflexivity, rw [triv3, this], }, rw this, clear this, simp, have: list.count 2 [3] = 0, by reflexivity, rw this, clear this, have: list.count 3 [2, 3] = 1, by reflexivity, rw this, clear this, have: list.nodup [(2,1), (3,1)], by norm_num, apply list.erase_dup_eq_self.mpr this, end lemma sumdiv_6: sumdiv 6 = 12 := begin unfold sumdiv, unfold divisors, rw factorize_6, rw divisors_aux, simp, repeat {rw list.map}, simp only [list.range, list.range_core], norm_num, end lemma sum_sum_pow_6: sum_sum_pow 6 = 7 := begin unfold sum_sum_pow, rw factorize_6, reflexivity, end theorem wrong_eqn_is_wrong: ¬ wrong_eqn := begin intro h, specialize h 6, rw [sumdiv_6, sum_sum_pow_6] at h, have: 12 ≠ 7, from dec_trivial, contradiction, end -- Theorem: -- let n = factorize n = p1^b1 * p2^b2 * ... pm^bm, as above, -- sumdiv n = (sum_pow p1 b1) * ... * (sum_pow pm bm) = Π(sum_pow pi bi) (i=1..m) @[simp, reducible] def prod_sum_pow (n: ℕ) := (list.map sum_pow (factorize n)).prod theorem sumdiv_eqn: ∀ n, sumdiv n = prod_sum_pow n := begin intro, rw [sumdiv, divisors], rw [prod_sum_pow], induction (factorize n), reflexivity, { rw divisors_aux, rw tensor_sum, rw ih, rw list.map_cons, rw list.prod_cons, } end end sec_2_7 section sec_2_8 -- Section 2.8: elaborates Thm 2.7 -- Theorem (geometric series): -- 1 + x + x^2 + ... x^n = (1-x^(n+1))/(1-x), (x ≠ 1) theorem geom_sum (x: ℤ) (n: ℕ) (h: x ≠ 1): <| (x, n) |>.sum = (1 - x^(n+1))/(1-x) := begin have h': 1-x ≠ 0, by_contradiction hc, { simp at hc, have: x=1, by rw add_neg_eq_zero.mp hc, contradiction, }, have: (1 - x^(n+1)) = (1-x)*(<| (x, n) |>.sum), { induction n, case nat.zero { simp, }, case nat.succ: n ih { rw geom_succ (x, n), rw list.sum_cons, have: (x, n).fst = x, by reflexivity, rw this, clear this, rw mul_add, rw scalar_l_sum, rw [<-mul_assoc (1-x), mul_comm (1-x) x], rw mul_assoc x (1-x) (list.sum _), rw <-ih, repeat {rw pow_succ}, simp, rw [mul_add, <-add_assoc, mul_one, add_comm (-x) x, add_neg_self], rw mul_neg_eq_neg_mul_symm, rw zero_add, }, }, symmetry, rw [this, mul_comm], rw int.mul_div_cancel (<|(x, n)|>.sum) h', end -- Shorthand for (1 - x^(n+1))/(1-x) @[simp] def gs (p: ℤ × ℕ) := (1 - p.1^(p.2+1))/(1-p.1) -- I will type-cast ℕ <- from&to -> ℤ lemma gs_nonneg {p: ℤ × ℕ} (h: p.1 ≥ 0): (gs p) ≥ 0 := begin unfold gs, have: p.1 = 1 ∨ p.1 ≠ 1, by apply decidable.em, cases this, rw this, simp, rw <-geom_sum p.1 p.2 this, simp, clear this, have hran: ∀ m ∈ list.range (1 + p.snd), pow p.1 m ≥ 0,{ intros, apply pow_nonneg, assumption, }, have: ∀ z:ℤ, z ∈ (list.map (pow p.fst) (list.range (1 + p.snd))) -> z ≥ 0, by tidy, apply sum_nonneg, assumption, end @[simp] def nonneg_gs_to_nat (p: ℤ × ℕ) (h: p.1 ≥ 0): ℕ := nonneg_to_nat (gs p) (gs_nonneg h) @[simp] def gs_nat (p: ℕ × ℕ): ℕ := nonneg_gs_to_nat (↑p: ℤ × ℕ) (by tidy) lemma gs_eq_gs_nat {p: ℕ × ℕ}: gs ↑p = gs_nat p := begin have h: (↑p: (ℤ × ℕ)).1 ≥ 0, by tidy, have: gs ↑p ≥ 0, from gs_nonneg h, rw gs_nat, rw nonneg_gs_to_nat, apply nonneg_to_nat_eq, end lemma int_one {x: ℤ}: 1=x ↔ 1-x = 0 := begin apply iff.intro, omega, omega, end lemma int_ne_one {x: ℤ}: 1 ≠ x ↔ 1-x ≠ 0 := begin apply iff.intro, omega, omega, end lemma geom_sum_cast (x: ℕ) (n: ℕ): (<| (x, n) |>.sum: ℤ) = <| ((x: ℤ), n) |>.sum := begin induction n with n ih, { simp, }, { rw geom_succ (x, n), rw geom_succ (↑x, n), rw list.sum_cons, rw list.sum_cons, rw scalar_l_sum, rw scalar_l_sum, rw <-ih, norm_cast, } end theorem geom_sum_nat (x: ℕ) (n: ℕ) (h: x ≠ 1): (<| (x, n) |>.sum: ℤ) = (1 - (x:ℤ)^(n+1))/(1-x) := begin have h': (1:ℤ) + (-(x: ℤ)) ≠ 0, { apply int_ne_one.mp, symmetry, assumption_mod_cast, }, have h_int: (x: ℤ) ≠ 1, by tidy, rw <-geom_sum (x: ℤ) n h_int, rw geom_sum_cast x n, end -- Lift the theorems to lists (of prime powers) lemma geom_sums {l: list (ℤ × ℕ)} (h: ∀ p: ℤ × ℕ, p ∈ l -> p.1 ≠ 1): list.map (λ (x: ℤ × ℕ), <| x |>.sum) l = list.map gs l := begin induction l, reflexivity, case list.cons: hd tl ih { have hps: hd.fst ≠ 1 ∧ ∀ (x : ℤ × ℕ), x ∈ tl → x.fst ≠ 1, from list.forall_mem_cons.mp h, repeat {rw list.map_cons}, have hhd': hd.1 ≠ 1, from hps.1, have hhd: (hd.1 : ℤ) ≠ 1, by assumption_mod_cast, clear hhd', rw geom_sum (hd.1: ℤ) hd.2 hhd, rw ih hps.2, reflexivity, } end lemma geom_sums_nat {l: list (ℕ × ℕ)} (h: ∀ p: ℕ × ℕ, p ∈ l -> p.1 ≠ 1): (list.map (λ (x: ℕ × ℕ), <| x |>.sum) l) = list.map (λ p:ℕ × ℕ, gs_nat p) l := begin induction l, reflexivity, case list.cons: hd tl ih { have hps: hd.fst ≠ 1 ∧ ∀ (x : ℕ × ℕ), x ∈ tl → x.fst ≠ 1, from list.forall_mem_cons.mp h, repeat {rw list.map_cons}, have hhd': hd.1 ≠ 1, from hps.1, have hhd: (↑hd: ℤ × ℕ).1 ≠ 1, { have: ↑(hd.1) = (↑hd: ℤ × ℕ).1, by tidy, intro hc, rw <-this at hc, clear this, have: ↑(hd.1) = (1: ℤ) -> hd.1 = 1, by tidy, exact hhd' (this hc), }, clear hhd', rw ih hps.2, norm_cast, apply and.intro, { have: (<|hd|>.sum : ℤ) = (gs_nat hd: ℤ), { rw <-gs_eq_gs_nat, rw gs, rw <-geom_sum _ _ hhd, rw geom_sum_cast, have: (↑(hd.fst), hd.snd) = ((↑hd: ℤ × ℕ).fst, (↑hd: ℤ × ℕ).snd), by tidy, rw this, }, assumption_mod_cast, }, { reflexivity, } } end -- Theorem 2.8: -- sumdiv n = Π (1-p^(m+1)/(1-p)), (p, m) ∈ factorize n theorem sumdiv_eqn': ∀ n, sumdiv n = (list.map (λ p:ℕ × ℕ, gs_nat p) (factorize n)).prod := begin intro, unfold sumdiv, unfold divisors, have all_ne_1: ∀ p: ℕ × ℕ, p ∈ (factorize n) -> p.1 ≠ 1, by { intros p h, cases p, have: nat.prime p_fst, from factors_are_prime h, simp, apply nat.prime.ne_one, assumption, }, rw <- geom_sums_nat all_ne_1, induction (factorize n), reflexivity, { rw divisors_aux, rw tensor_sum, rw ih, rw list.map_cons, rw list.prod_cons, } end end sec_2_8 section sec_2_9 -- Section 2.9 "At the School Library" -- 2.9.1: Equations and Identities, -- "x - 1 = 0" is an equation, example: ∃ x: ℤ, x - 1 = 0 := ⟨1, rfl⟩ -- x = 1 ↔ x - 1 = 0 -- while "2(x-1) = 2x - 2" is an identity. example: ∀ x: ℤ, 2*(x-1) = 2*x - 2 := begin intros, apply mul_add, end -- A rewrite chain of identities lemma sub_left_comm (a b c: ℤ): a - b - c = a - c - b := begin rw sub_eq_add_neg a b, rw sub_eq_add_neg _ c, norm_num, end theorem square_completion_one (x: ℤ): (x+1)*(x-1) = x^2 - 1 := calc (x+1)*(x-1) = (x+1)*x - (x+1)*1: by rw mul_sub ... = x*x + 1*x -(x+1)*1: by rw add_mul ... = x*x + 1*x - x*1 - 1*1: by rw [add_mul, sub_add_eq_sub_sub_swap, sub_left_comm] ... = x^2 + x - x - 1: by rw [<-pow_two, mul_one, one_mul, one_mul] ... = x^2 - 1: by rw [sub_eq_add_neg _ x, add_assoc (x^2), add_neg_self x, add_zero] . -- This is an identity: holds for all x: #check square_completion_one -- Square-complete x^2 - 5*x + 6 theorem square_completion_2_and_3 (x: ℤ): x^2 - 5*x + 6 = (x-2)*(x-3) := by ring. -- if it's an equation (of RHS = 0), the solutions are 2&3 example (x: ℤ): x^2 - 5*x + 6 = 0 -> x=2 ∨ x=3 := begin rw square_completion_2_and_3 x, intro h, simp at h, omega, end -- 2.9.2: Product Forms and Sum Forms -- elementary quadratic equations over a general (commutative) ring R variables {R: Type} variable [comm_ring R] variables {x α β: R} -- A complete-form equation of R: #check (x-α)*(x-β) = 0 -- Expand this one-step into: x^2 - α*x - β*x +α*β theorem expand1: (x-α)*(x-β) = x^2 - α*x - β*x +α*β := begin norm_num, repeat { rw mul_add <|> rw add_mul }, rw pow_two, tidy, rw mul_comm x β, apply add_comm, end -- ... then, group the degree-1 terms: theorem group1: x^2 - α*x - β*x +α*β = x^2 - (α+β)*x +α*β := begin ring, end -- Confirm these two forms are equivalent: theorem square_completion_id: (x-α)*(x-β) = 0 ↔ x^2 - (α+β)*x +α*β = 0 := begin apply iff.intro, { intro h, rw pow_two, ring at h, rw sub_eq_neg_add at h, repeat {rw add_mul at h}, rw add_mul, rw sub_eq_neg_add, rw neg_eq_neg_one_mul, rw mul_add, repeat {rw <-mul_assoc}, repeat {rw <-neg_eq_neg_one_mul}, rw mul_comm α β, rw add_comm (-α*x) _, rw add_comm (x*x) at h, assumption, }, { intro h, rw pow_two at h, repeat {rw sub_mul <|> rw mul_sub}, rw sub_eq_add_neg, rw neg_eq_neg_one_mul, rw mul_sub, repeat {rw <-neg_eq_neg_one_mul}, rw neg_sub_neg, rw add_mul at h, rw sub_add_eq_sub_sub_swap at h, rw mul_comm β x at h, tidy, } end end sec_2_9
f74baf0b280e7e66c3a930bf9b12c16d7cef23c3
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/patbug.lean
8292c339fa33aa0d8349773aed6d91dc47557bba
[ "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
199
lean
open Lean def f : Name → Name | n@(`foo.bla) => n | _ => Name.anonymous def tst : IO Unit := do if hash `foo.bla != hash (f `foo.bla) then throw $ IO.userError "bug" IO.println "ok" #eval tst
4566e88ab95e87f1afe044fd326234309c3c9872
9dc8cecdf3c4634764a18254e94d43da07142918
/src/topology/uniform_space/completion.lean
d2a64d3752a0ef6d95a1ba6f1468def98ffd268f
[ "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
24,202
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Johannes Hölzl -/ import topology.uniform_space.abstract_completion /-! # Hausdorff completions of uniform spaces The goal is to construct a left-adjoint to the inclusion of complete Hausdorff uniform spaces into all uniform spaces. Any uniform space `α` gets a completion `completion α` and a morphism (ie. uniformly continuous map) `coe : α → completion α` which solves the universal mapping problem of factorizing morphisms from `α` to any complete Hausdorff uniform space `β`. It means any uniformly continuous `f : α → β` gives rise to a unique morphism `completion.extension f : completion α → β` such that `f = completion.extension f ∘ coe`. Actually `completion.extension f` is defined for all maps from `α` to `β` but it has the desired properties only if `f` is uniformly continuous. Beware that `coe` is not injective if `α` is not Hausdorff. But its image is always dense. The adjoint functor acting on morphisms is then constructed by the usual abstract nonsense. For every uniform spaces `α` and `β`, it turns `f : α → β` into a morphism `completion.map f : completion α → completion β` such that `coe ∘ f = (completion.map f) ∘ coe` provided `f` is uniformly continuous. This construction is compatible with composition. In this file we introduce the following concepts: * `Cauchy α` the uniform completion of the uniform space `α` (using Cauchy filters). These are not minimal filters. * `completion α := quotient (separation_setoid (Cauchy α))` the Hausdorff completion. ## References This formalization is mostly based on N. Bourbaki: General Topology I. M. James: Topologies and Uniformities From a slightly different perspective in order to reuse material in topology.uniform_space.basic. -/ noncomputable theory open filter set universes u v w x open_locale uniformity classical topological_space filter /-- Space of Cauchy filters This is essentially the completion of a uniform space. The embeddings are the neighbourhood filters. This space is not minimal, the separated uniform space (i.e. quotiented on the intersection of all entourages) is necessary for this. -/ def Cauchy (α : Type u) [uniform_space α] : Type u := { f : filter α // cauchy f } namespace Cauchy section parameters {α : Type u} [uniform_space α] variables {β : Type v} {γ : Type w} variables [uniform_space β] [uniform_space γ] /-- The pairs of Cauchy filters generated by a set. -/ def gen (s : set (α × α)) : set (Cauchy α × Cauchy α) := {p | s ∈ p.1.val ×ᶠ p.2.val } lemma monotone_gen : monotone gen := monotone_set_of $ assume p, @monotone_mem (α×α) (p.1.val ×ᶠ p.2.val) private lemma symm_gen : map prod.swap ((𝓤 α).lift' gen) ≤ (𝓤 α).lift' gen := calc map prod.swap ((𝓤 α).lift' gen) = (𝓤 α).lift' (λs:set (α×α), {p | s ∈ p.2.val ×ᶠ p.1.val }) : begin delta gen, simp [map_lift'_eq, monotone_set_of, monotone_mem, function.comp, image_swap_eq_preimage_swap, -subtype.val_eq_coe] end ... ≤ (𝓤 α).lift' gen : uniformity_lift_le_swap (monotone_principal.comp (monotone_set_of $ assume p, @monotone_mem (α×α) (p.2.val ×ᶠ p.1.val))) begin have h := λ(p:Cauchy α×Cauchy α), @filter.prod_comm _ _ (p.2.val) (p.1.val), simp [function.comp, h, -subtype.val_eq_coe, mem_map'], exact le_rfl, end private lemma comp_rel_gen_gen_subset_gen_comp_rel {s t : set (α×α)} : comp_rel (gen s) (gen t) ⊆ (gen (comp_rel s t) : set (Cauchy α × Cauchy α)) := assume ⟨f, g⟩ ⟨h, h₁, h₂⟩, let ⟨t₁, (ht₁ : t₁ ∈ f.val), t₂, (ht₂ : t₂ ∈ h.val), (h₁ : t₁ ×ˢ t₂ ⊆ s)⟩ := mem_prod_iff.mp h₁ in let ⟨t₃, (ht₃ : t₃ ∈ h.val), t₄, (ht₄ : t₄ ∈ g.val), (h₂ : t₃ ×ˢ t₄ ⊆ t)⟩ := mem_prod_iff.mp h₂ in have t₂ ∩ t₃ ∈ h.val, from inter_mem ht₂ ht₃, let ⟨x, xt₂, xt₃⟩ := h.property.left.nonempty_of_mem this in (f.val ×ᶠ g.val).sets_of_superset (prod_mem_prod ht₁ ht₄) (assume ⟨a, b⟩ ⟨(ha : a ∈ t₁), (hb : b ∈ t₄)⟩, ⟨x, h₁ (show (a, x) ∈ t₁ ×ˢ t₂, from ⟨ha, xt₂⟩), h₂ (show (x, b) ∈ t₃ ×ˢ t₄, from ⟨xt₃, hb⟩)⟩) private lemma comp_gen : ((𝓤 α).lift' gen).lift' (λs, comp_rel s s) ≤ (𝓤 α).lift' gen := calc ((𝓤 α).lift' gen).lift' (λs, comp_rel s s) = (𝓤 α).lift' (λs, comp_rel (gen s) (gen s)) : begin rw [lift'_lift'_assoc], exact monotone_gen, exact (monotone_comp_rel monotone_id monotone_id) end ... ≤ (𝓤 α).lift' (λs, gen $ comp_rel s s) : lift'_mono' $ assume s hs, comp_rel_gen_gen_subset_gen_comp_rel ... = ((𝓤 α).lift' $ λs:set(α×α), comp_rel s s).lift' gen : begin rw [lift'_lift'_assoc], exact (monotone_comp_rel monotone_id monotone_id), exact monotone_gen end ... ≤ (𝓤 α).lift' gen : lift'_mono comp_le_uniformity le_rfl instance : uniform_space (Cauchy α) := uniform_space.of_core { uniformity := (𝓤 α).lift' gen, refl := principal_le_lift' $ assume s hs ⟨a, b⟩ (a_eq_b : a = b), a_eq_b ▸ a.property.right hs, symm := symm_gen, comp := comp_gen } theorem mem_uniformity {s : set (Cauchy α × Cauchy α)} : s ∈ 𝓤 (Cauchy α) ↔ ∃ t ∈ 𝓤 α, gen t ⊆ s := mem_lift'_sets monotone_gen theorem mem_uniformity' {s : set (Cauchy α × Cauchy α)} : s ∈ 𝓤 (Cauchy α) ↔ ∃ t ∈ 𝓤 α, ∀ f g : Cauchy α, t ∈ f.1 ×ᶠ g.1 → (f, g) ∈ s := mem_uniformity.trans $ bex_congr $ λ t h, prod.forall /-- Embedding of `α` into its completion `Cauchy α` -/ def pure_cauchy (a : α) : Cauchy α := ⟨pure a, cauchy_pure⟩ lemma uniform_inducing_pure_cauchy : uniform_inducing (pure_cauchy : α → Cauchy α) := ⟨have (preimage (λ (x : α × α), (pure_cauchy (x.fst), pure_cauchy (x.snd))) ∘ gen) = id, from funext $ assume s, set.ext $ assume ⟨a₁, a₂⟩, by simp [preimage, gen, pure_cauchy, prod_principal_principal], calc comap (λ (x : α × α), (pure_cauchy (x.fst), pure_cauchy (x.snd))) ((𝓤 α).lift' gen) = (𝓤 α).lift' (preimage (λ (x : α × α), (pure_cauchy (x.fst), pure_cauchy (x.snd))) ∘ gen) : comap_lift'_eq ... = 𝓤 α : by simp [this]⟩ lemma uniform_embedding_pure_cauchy : uniform_embedding (pure_cauchy : α → Cauchy α) := { inj := assume a₁ a₂ h, pure_injective $ subtype.ext_iff_val.1 h, ..uniform_inducing_pure_cauchy } lemma dense_range_pure_cauchy : dense_range pure_cauchy := assume f, have h_ex : ∀ s ∈ 𝓤 (Cauchy α), ∃y:α, (f, pure_cauchy y) ∈ s, from assume s hs, let ⟨t'', ht''₁, (ht''₂ : gen t'' ⊆ s)⟩ := (mem_lift'_sets monotone_gen).mp hs in let ⟨t', ht'₁, ht'₂⟩ := comp_mem_uniformity_sets ht''₁ in have t' ∈ f.val ×ᶠ f.val, from f.property.right ht'₁, let ⟨t, ht, (h : t ×ˢ t ⊆ t')⟩ := mem_prod_same_iff.mp this in let ⟨x, (hx : x ∈ t)⟩ := f.property.left.nonempty_of_mem ht in have t'' ∈ f.val ×ᶠ pure x, from mem_prod_iff.mpr ⟨t, ht, {y:α | (x, y) ∈ t'}, h $ mk_mem_prod hx hx, assume ⟨a, b⟩ ⟨(h₁ : a ∈ t), (h₂ : (x, b) ∈ t')⟩, ht'₂ $ prod_mk_mem_comp_rel (@h (a, x) ⟨h₁, hx⟩) h₂⟩, ⟨x, ht''₂ $ by dsimp [gen]; exact this⟩, begin simp only [closure_eq_cluster_pts, cluster_pt, nhds_eq_uniformity, lift'_inf_principal_eq, set.inter_comm _ (range pure_cauchy), mem_set_of_eq], exact (lift'_ne_bot_iff $ monotone_const.inter monotone_preimage).mpr (assume s hs, let ⟨y, hy⟩ := h_ex s hs in have pure_cauchy y ∈ range pure_cauchy ∩ {y : Cauchy α | (f, y) ∈ s}, from ⟨mem_range_self y, hy⟩, ⟨_, this⟩) end lemma dense_inducing_pure_cauchy : dense_inducing pure_cauchy := uniform_inducing_pure_cauchy.dense_inducing dense_range_pure_cauchy lemma dense_embedding_pure_cauchy : dense_embedding pure_cauchy := uniform_embedding_pure_cauchy.dense_embedding dense_range_pure_cauchy lemma nonempty_Cauchy_iff : nonempty (Cauchy α) ↔ nonempty α := begin split ; rintro ⟨c⟩, { have := eq_univ_iff_forall.1 dense_embedding_pure_cauchy.to_dense_inducing.closure_range c, obtain ⟨_, ⟨_, a, _⟩⟩ := mem_closure_iff.1 this _ is_open_univ trivial, exact ⟨a⟩ }, { exact ⟨pure_cauchy c⟩ } end section set_option eqn_compiler.zeta true instance : complete_space (Cauchy α) := complete_space_extension uniform_inducing_pure_cauchy dense_range_pure_cauchy $ assume f hf, let f' : Cauchy α := ⟨f, hf⟩ in have map pure_cauchy f ≤ (𝓤 $ Cauchy α).lift' (preimage (prod.mk f')), from le_lift' $ assume s hs, let ⟨t, ht₁, (ht₂ : gen t ⊆ s)⟩ := (mem_lift'_sets monotone_gen).mp hs in let ⟨t', ht', (h : t' ×ˢ t' ⊆ t)⟩ := mem_prod_same_iff.mp (hf.right ht₁) in have t' ⊆ { y : α | (f', pure_cauchy y) ∈ gen t }, from assume x hx, (f ×ᶠ pure x).sets_of_superset (prod_mem_prod ht' hx) h, f.sets_of_superset ht' $ subset.trans this (preimage_mono ht₂), ⟨f', by simp [nhds_eq_uniformity]; assumption⟩ end instance [inhabited α] : inhabited (Cauchy α) := ⟨pure_cauchy default⟩ instance [h : nonempty α] : nonempty (Cauchy α) := h.rec_on $ assume a, nonempty.intro $ Cauchy.pure_cauchy a section extend /-- Extend a uniformly continuous function `α → β` to a function `Cauchy α → β`. Outputs junk when `f` is not uniformly continuous. -/ def extend (f : α → β) : Cauchy α → β := if uniform_continuous f then dense_inducing_pure_cauchy.extend f else λ x, f (nonempty_Cauchy_iff.1 ⟨x⟩).some section separated_space variables [separated_space β] lemma extend_pure_cauchy {f : α → β} (hf : uniform_continuous f) (a : α) : extend f (pure_cauchy a) = f a := begin rw [extend, if_pos hf], exact uniformly_extend_of_ind uniform_inducing_pure_cauchy dense_range_pure_cauchy hf _ end end separated_space variables [_root_.complete_space β] lemma uniform_continuous_extend {f : α → β} : uniform_continuous (extend f) := begin by_cases hf : uniform_continuous f, { rw [extend, if_pos hf], exact uniform_continuous_uniformly_extend uniform_inducing_pure_cauchy dense_range_pure_cauchy hf }, { rw [extend, if_neg hf], exact uniform_continuous_of_const (assume a b, by congr) } end end extend end theorem Cauchy_eq {α : Type*} [inhabited α] [uniform_space α] [complete_space α] [separated_space α] {f g : Cauchy α} : Lim f.1 = Lim g.1 ↔ (f, g) ∈ separation_rel (Cauchy α) := begin split, { intros e s hs, rcases Cauchy.mem_uniformity'.1 hs with ⟨t, tu, ts⟩, apply ts, rcases comp_mem_uniformity_sets tu with ⟨d, du, dt⟩, refine mem_prod_iff.2 ⟨_, f.2.le_nhds_Lim (mem_nhds_right (Lim f.1) du), _, g.2.le_nhds_Lim (mem_nhds_left (Lim g.1) du), λ x h, _⟩, cases x with a b, cases h with h₁ h₂, rw ← e at h₂, exact dt ⟨_, h₁, h₂⟩ }, { intros H, refine separated_def.1 (by apply_instance) _ _ (λ t tu, _), rcases mem_uniformity_is_closed tu with ⟨d, du, dc, dt⟩, refine H {p | (Lim p.1.1, Lim p.2.1) ∈ t} (Cauchy.mem_uniformity'.2 ⟨d, du, λ f g h, _⟩), rcases mem_prod_iff.1 h with ⟨x, xf, y, yg, h⟩, have limc : ∀ (f : Cauchy α) (x ∈ f.1), Lim f.1 ∈ closure x, { intros f x xf, rw closure_eq_cluster_pts, exact f.2.1.mono (le_inf f.2.le_nhds_Lim (le_principal_iff.2 xf)) }, have := dc.closure_subset_iff.2 h, rw closure_prod_eq at this, refine dt (this ⟨_, _⟩); dsimp; apply limc; assumption } end section local attribute [instance] uniform_space.separation_setoid lemma separated_pure_cauchy_injective {α : Type*} [uniform_space α] [s : separated_space α] : function.injective (λa:α, ⟦pure_cauchy a⟧) | a b h := separated_def.1 s _ _ $ assume s hs, let ⟨t, ht, hts⟩ := by rw [← (@uniform_embedding_pure_cauchy α _).comap_uniformity, filter.mem_comap] at hs; exact hs in have (pure_cauchy a, pure_cauchy b) ∈ t, from quotient.exact h t ht, @hts (a, b) this end end Cauchy local attribute [instance] uniform_space.separation_setoid open Cauchy set namespace uniform_space variables (α : Type*) [uniform_space α] variables {β : Type*} [uniform_space β] variables {γ : Type*} [uniform_space γ] instance complete_space_separation [h : complete_space α] : complete_space (quotient (separation_setoid α)) := ⟨assume f, assume hf : cauchy f, have cauchy (f.comap (λx, ⟦x⟧)), from hf.comap' comap_quotient_le_uniformity $ hf.left.comap_of_surj (surjective_quotient_mk _), let ⟨x, (hx : f.comap (λx, ⟦x⟧) ≤ 𝓝 x)⟩ := complete_space.complete this in ⟨⟦x⟧, (comap_le_comap_iff $ by simp).1 (hx.trans $ map_le_iff_le_comap.1 continuous_quotient_mk.continuous_at)⟩⟩ /-- Hausdorff completion of `α` -/ def completion := quotient (separation_setoid $ Cauchy α) namespace completion instance [inhabited α] : inhabited (completion α) := quotient.inhabited (separation_setoid (Cauchy α)) @[priority 50] instance : uniform_space (completion α) := separation_setoid.uniform_space instance : complete_space (completion α) := uniform_space.complete_space_separation (Cauchy α) instance : separated_space (completion α) := uniform_space.separated_separation instance : t3_space (completion α) := separated_t3 /-- Automatic coercion from `α` to its completion. Not always injective. -/ instance : has_coe_t α (completion α) := ⟨quotient.mk ∘ pure_cauchy⟩ -- note [use has_coe_t] protected lemma coe_eq : (coe : α → completion α) = quotient.mk ∘ pure_cauchy := rfl lemma comap_coe_eq_uniformity : (𝓤 _).comap (λ(p:α×α), ((p.1 : completion α), (p.2 : completion α))) = 𝓤 α := begin have : (λx:α×α, ((x.1 : completion α), (x.2 : completion α))) = (λx:(Cauchy α)×(Cauchy α), (⟦x.1⟧, ⟦x.2⟧)) ∘ (λx:α×α, (pure_cauchy x.1, pure_cauchy x.2)), { ext ⟨a, b⟩; simp; refl }, rw [this, ← filter.comap_comap], change filter.comap _ (filter.comap _ (𝓤 $ quotient $ separation_setoid $ Cauchy α)) = 𝓤 α, rw [comap_quotient_eq_uniformity, uniform_embedding_pure_cauchy.comap_uniformity] end lemma uniform_inducing_coe : uniform_inducing (coe : α → completion α) := ⟨comap_coe_eq_uniformity α⟩ variables {α} lemma dense_range_coe : dense_range (coe : α → completion α) := dense_range_pure_cauchy.quotient variables (α) /-- The Haudorff completion as an abstract completion. -/ def cpkg {α : Type*} [uniform_space α] : abstract_completion α := { space := completion α, coe := coe, uniform_struct := by apply_instance, complete := by apply_instance, separation := by apply_instance, uniform_inducing := completion.uniform_inducing_coe α, dense := completion.dense_range_coe } instance abstract_completion.inhabited : inhabited (abstract_completion α) := ⟨cpkg⟩ local attribute [instance] abstract_completion.uniform_struct abstract_completion.complete abstract_completion.separation lemma nonempty_completion_iff : nonempty (completion α) ↔ nonempty α := cpkg.dense.nonempty_iff.symm lemma uniform_continuous_coe : uniform_continuous (coe : α → completion α) := cpkg.uniform_continuous_coe lemma continuous_coe : continuous (coe : α → completion α) := cpkg.continuous_coe lemma uniform_embedding_coe [separated_space α] : uniform_embedding (coe : α → completion α) := { comap_uniformity := comap_coe_eq_uniformity α, inj := separated_pure_cauchy_injective } lemma coe_injective [separated_space α] : function.injective (coe : α → completion α) := uniform_embedding.inj (uniform_embedding_coe _) variable {α} lemma dense_inducing_coe : dense_inducing (coe : α → completion α) := { dense := dense_range_coe, ..(uniform_inducing_coe α).inducing } open topological_space instance separable_space_completion [separable_space α] : separable_space (completion α) := completion.dense_inducing_coe.separable_space lemma dense_embedding_coe [separated_space α]: dense_embedding (coe : α → completion α) := { inj := separated_pure_cauchy_injective, ..dense_inducing_coe } lemma dense_range_coe₂ : dense_range (λx:α × β, ((x.1 : completion α), (x.2 : completion β))) := dense_range_coe.prod_map dense_range_coe lemma dense_range_coe₃ : dense_range (λx:α × (β × γ), ((x.1 : completion α), ((x.2.1 : completion β), (x.2.2 : completion γ)))) := dense_range_coe.prod_map dense_range_coe₂ @[elab_as_eliminator] lemma induction_on {p : completion α → Prop} (a : completion α) (hp : is_closed {a | p a}) (ih : ∀a:α, p a) : p a := is_closed_property dense_range_coe hp ih a @[elab_as_eliminator] lemma induction_on₂ {p : completion α → completion β → Prop} (a : completion α) (b : completion β) (hp : is_closed {x : completion α × completion β | p x.1 x.2}) (ih : ∀(a:α) (b:β), p a b) : p a b := have ∀x : completion α × completion β, p x.1 x.2, from is_closed_property dense_range_coe₂ hp $ assume ⟨a, b⟩, ih a b, this (a, b) @[elab_as_eliminator] lemma induction_on₃ {p : completion α → completion β → completion γ → Prop} (a : completion α) (b : completion β) (c : completion γ) (hp : is_closed {x : completion α × completion β × completion γ | p x.1 x.2.1 x.2.2}) (ih : ∀(a:α) (b:β) (c:γ), p a b c) : p a b c := have ∀x : completion α × completion β × completion γ, p x.1 x.2.1 x.2.2, from is_closed_property dense_range_coe₃ hp $ assume ⟨a, b, c⟩, ih a b c, this (a, b, c) lemma ext {Y : Type*} [topological_space Y] [t2_space Y] {f g : completion α → Y} (hf : continuous f) (hg : continuous g) (h : ∀a:α, f a = g a) : f = g := cpkg.funext hf hg h lemma ext' {Y : Type*} [topological_space Y] [t2_space Y] {f g : completion α → Y} (hf : continuous f) (hg : continuous g) (h : ∀a:α, f a = g a) (a : completion α) : f a = g a := congr_fun (ext hf hg h) a section extension variables {f : α → β} /-- "Extension" to the completion. It is defined for any map `f` but returns an arbitrary constant value if `f` is not uniformly continuous -/ protected def extension (f : α → β) : completion α → β := cpkg.extend f section complete_space variables [complete_space β] lemma uniform_continuous_extension : uniform_continuous (completion.extension f) := cpkg.uniform_continuous_extend lemma continuous_extension : continuous (completion.extension f) := cpkg.continuous_extend end complete_space @[simp] lemma extension_coe [separated_space β] (hf : uniform_continuous f) (a : α) : (completion.extension f) a = f a := cpkg.extend_coe hf a variables [separated_space β] [complete_space β] lemma extension_unique (hf : uniform_continuous f) {g : completion α → β} (hg : uniform_continuous g) (h : ∀ a : α, f a = g (a : completion α)) : completion.extension f = g := cpkg.extend_unique hf hg h @[simp] lemma extension_comp_coe {f : completion α → β} (hf : uniform_continuous f) : completion.extension (f ∘ coe) = f := cpkg.extend_comp_coe hf end extension section map variables {f : α → β} /-- Completion functor acting on morphisms -/ protected def map (f : α → β) : completion α → completion β := cpkg.map cpkg f lemma uniform_continuous_map : uniform_continuous (completion.map f) := cpkg.uniform_continuous_map cpkg f lemma continuous_map : continuous (completion.map f) := cpkg.continuous_map cpkg f @[simp] lemma map_coe (hf : uniform_continuous f) (a : α) : (completion.map f) a = f a := cpkg.map_coe cpkg hf a lemma map_unique {f : α → β} {g : completion α → completion β} (hg : uniform_continuous g) (h : ∀a:α, ↑(f a) = g a) : completion.map f = g := cpkg.map_unique cpkg hg h @[simp] lemma map_id : completion.map (@id α) = id := cpkg.map_id lemma extension_map [complete_space γ] [separated_space γ] {f : β → γ} {g : α → β} (hf : uniform_continuous f) (hg : uniform_continuous g) : completion.extension f ∘ completion.map g = completion.extension (f ∘ g) := completion.ext (continuous_extension.comp continuous_map) continuous_extension $ by intro a; simp only [hg, hf, hf.comp hg, (∘), map_coe, extension_coe] lemma map_comp {g : β → γ} {f : α → β} (hg : uniform_continuous g) (hf : uniform_continuous f) : completion.map g ∘ completion.map f = completion.map (g ∘ f) := extension_map ((uniform_continuous_coe _).comp hg) hf end map /- In this section we construct isomorphisms between the completion of a uniform space and the completion of its separation quotient -/ section separation_quotient_completion /-- The isomorphism between the completion of a uniform space and the completion of its separation quotient. -/ def completion_separation_quotient_equiv (α : Type u) [uniform_space α] : completion (separation_quotient α) ≃ completion α := begin refine ⟨completion.extension (separation_quotient.lift (coe : α → completion α)), completion.map quotient.mk, _, _⟩, { assume a, refine induction_on a (is_closed_eq (continuous_map.comp continuous_extension) continuous_id) _, rintros ⟨a⟩, show completion.map quotient.mk (completion.extension (separation_quotient.lift coe) ↑⟦a⟧) = ↑⟦a⟧, rw [extension_coe (separation_quotient.uniform_continuous_lift _), separation_quotient.lift_mk (uniform_continuous_coe α), completion.map_coe uniform_continuous_quotient_mk] ; apply_instance }, { assume a, refine completion.induction_on a (is_closed_eq (continuous_extension.comp continuous_map) continuous_id) (λ a, _), rw [map_coe uniform_continuous_quotient_mk, extension_coe (separation_quotient.uniform_continuous_lift _), separation_quotient.lift_mk (uniform_continuous_coe α) _] ; apply_instance } end lemma uniform_continuous_completion_separation_quotient_equiv : uniform_continuous ⇑(completion_separation_quotient_equiv α) := uniform_continuous_extension lemma uniform_continuous_completion_separation_quotient_equiv_symm : uniform_continuous ⇑(completion_separation_quotient_equiv α).symm := uniform_continuous_map end separation_quotient_completion section extension₂ variables (f : α → β → γ) open function /-- Extend a two variable map to the Hausdorff completions. -/ protected def extension₂ (f : α → β → γ) : completion α → completion β → γ := cpkg.extend₂ cpkg f section separated_space variables [separated_space γ] {f} @[simp] lemma extension₂_coe_coe (hf : uniform_continuous₂ f) (a : α) (b : β) : completion.extension₂ f a b = f a b := cpkg.extension₂_coe_coe cpkg hf a b end separated_space variables [complete_space γ] (f) lemma uniform_continuous_extension₂ : uniform_continuous₂ (completion.extension₂ f) := cpkg.uniform_continuous_extension₂ cpkg f end extension₂ section map₂ open function /-- Lift a two variable map to the Hausdorff completions. -/ protected def map₂ (f : α → β → γ) : completion α → completion β → completion γ := cpkg.map₂ cpkg cpkg f lemma uniform_continuous_map₂ (f : α → β → γ) : uniform_continuous₂ (completion.map₂ f) := cpkg.uniform_continuous_map₂ cpkg cpkg f lemma continuous_map₂ {δ} [topological_space δ] {f : α → β → γ} {a : δ → completion α} {b : δ → completion β} (ha : continuous a) (hb : continuous b) : continuous (λd:δ, completion.map₂ f (a d) (b d)) := cpkg.continuous_map₂ cpkg cpkg ha hb lemma map₂_coe_coe (a : α) (b : β) (f : α → β → γ) (hf : uniform_continuous₂ f) : completion.map₂ f (a : completion α) (b : completion β) = f a b := cpkg.map₂_coe_coe cpkg cpkg a b f hf end map₂ end completion end uniform_space
c71d5923c8a2772e36930c3283cfec251ebde7d5
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/cc_ac5.lean
5d4c652e0f363a8e02f11bbd1e9f860be8e9b08e
[ "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,229
lean
universe variables u class comm_ring (α : Type u) extends has_mul α, has_add α, has_zero α, has_one α. variables {α : Type u} variables [comm_ring α] open tactic instance aa : is_associative α (+) := ⟨sorry⟩ instance ac : is_commutative α (+) := ⟨sorry⟩ instance ma : is_associative α (*) := ⟨sorry⟩ instance mc : is_commutative α (*) := ⟨sorry⟩ instance lc : is_left_cancel α (+) := ⟨sorry⟩ instance rc : is_right_cancel α (+) := ⟨sorry⟩ instance ld : is_left_distrib α (*) (+) := ⟨sorry⟩ instance rd : is_right_distrib α (*) (+) := ⟨sorry⟩ instance l0a : is_left_id α (*) 0 := ⟨sorry⟩ instance r0a : is_right_id α (*) 0 := ⟨sorry⟩ instance l0m : is_left_null α (*) 0 := ⟨sorry⟩ instance r0m : is_right_null α (*) 0 := ⟨sorry⟩ example (x1 x2 x3 x4 x5 x6 : α) : x1*x4 = x1 → x3*x6 = x5*x5 → x5 = x4 → x6 = x2 → x1 = x1*(x6*x3) := by cc example (y1 y2 x2 x3 x4 x5 x6 : α) : (y1 + y2)*x4 = (y2 + y1) → x3*x6 = x5*x5 → x5 = x4 → x6 = x2 → (y2 + y1) = (y1 + y2)*(x6*x3) := by cc example (y1 y2 y3 x2 x3 x4 x5 x6 : α) : (y1 + y2)*x4 = (y3 + y1) → x3*x6 = x5*x5 → x5 = x4 → x6 = x2 → y2 = y3 → (y2 + y1) = (y1 + y3)*(x6*x3) := by cc
42f61e3e88c7fb7594ee296a3dd81d9edc7307d4
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/algebra/category/Mon/basic.lean
c61fb005f7e883368368de1ca4bb06d19899c66a
[ "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
7,938
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 category_theory.concrete_category.bundled_hom import category_theory.concrete_category.reflects_isomorphisms import algebra.punit_instances import tactic.elementwise /-! # Category instances for monoid, add_monoid, comm_monoid, and add_comm_monoid. We introduce the bundled categories: * `Mon` * `AddMon` * `CommMon` * `AddCommMon` along with the relevant forgetful functors between them. -/ universes u v open category_theory /-- The category of monoids and monoid morphisms. -/ @[to_additive AddMon] def Mon : Type (u+1) := bundled monoid /-- The category of additive monoids and monoid morphisms. -/ add_decl_doc AddMon namespace Mon /-- `monoid_hom` doesn't actually assume associativity. This alias is needed to make the category theory machinery work. -/ @[to_additive "`add_monoid_hom` doesn't actually assume associativity. This alias is needed to make the category theory machinery work."] abbreviation assoc_monoid_hom (M N : Type*) [monoid M] [monoid N] := monoid_hom M N @[to_additive] instance bundled_hom : bundled_hom assoc_monoid_hom := ⟨λ M N [monoid M] [monoid N], by exactI @monoid_hom.to_fun M N _ _, λ M [monoid M], by exactI @monoid_hom.id M _, λ M N P [monoid M] [monoid N] [monoid P], by exactI @monoid_hom.comp M N P _ _ _, λ M N [monoid M] [monoid N], by exactI @monoid_hom.coe_inj M N _ _⟩ attribute [derive [large_category, concrete_category]] Mon attribute [to_additive] Mon.large_category Mon.concrete_category @[to_additive] instance : has_coe_to_sort Mon Type* := bundled.has_coe_to_sort /-- Construct a bundled `Mon` from the underlying type and typeclass. -/ @[to_additive] def of (M : Type u) [monoid M] : Mon := bundled.of M /-- Construct a bundled `Mon` from the underlying type and typeclass. -/ add_decl_doc AddMon.of /-- Typecheck a `monoid_hom` as a morphism in `Mon`. -/ @[to_additive] def of_hom {X Y : Type u} [monoid X] [monoid Y] (f : X →* Y) : of X ⟶ of Y := f /-- Typecheck a `add_monoid_hom` as a morphism in `AddMon`. -/ add_decl_doc AddMon.of_hom @[to_additive] instance : inhabited Mon := -- The default instance for `monoid punit` is derived via `punit.comm_ring`, -- which breaks to_additive. ⟨@of punit $ @group.to_monoid _ $ @comm_group.to_group _ punit.comm_group⟩ @[to_additive] instance (M : Mon) : monoid M := M.str @[simp, to_additive] lemma coe_of (R : Type u) [monoid R] : (Mon.of R : Type u) = R := rfl end Mon /-- The category of commutative monoids and monoid morphisms. -/ @[to_additive AddCommMon] def CommMon : Type (u+1) := bundled comm_monoid /-- The category of additive commutative monoids and monoid morphisms. -/ add_decl_doc AddCommMon namespace CommMon @[to_additive] instance : bundled_hom.parent_projection comm_monoid.to_monoid := ⟨⟩ attribute [derive [large_category, concrete_category]] CommMon attribute [to_additive] CommMon.large_category CommMon.concrete_category @[to_additive] instance : has_coe_to_sort CommMon Type* := bundled.has_coe_to_sort /-- Construct a bundled `CommMon` from the underlying type and typeclass. -/ @[to_additive] def of (M : Type u) [comm_monoid M] : CommMon := bundled.of M /-- Construct a bundled `AddCommMon` from the underlying type and typeclass. -/ add_decl_doc AddCommMon.of @[to_additive] instance : inhabited CommMon := -- The default instance for `comm_monoid punit` is derived via `punit.comm_ring`, -- which breaks to_additive. ⟨@of punit $ @comm_group.to_comm_monoid _ punit.comm_group⟩ @[to_additive] instance (M : CommMon) : comm_monoid M := M.str @[simp, to_additive] lemma coe_of (R : Type u) [comm_monoid R] : (CommMon.of R : Type u) = R := rfl @[to_additive has_forget_to_AddMon] instance has_forget_to_Mon : has_forget₂ CommMon Mon := bundled_hom.forget₂ _ _ end CommMon -- We verify that the coercions of morphisms to functions work correctly: example {R S : Mon} (f : R ⟶ S) : (R : Type) → (S : Type) := f example {R S : CommMon} (f : R ⟶ S) : (R : Type) → (S : Type) := f -- We verify that when constructing a morphism in `CommMon`, -- when we construct the `to_fun` field, the types are presented as `↥R`, -- rather than `R.α` or (as we used to have) `↥(bundled.map comm_monoid.to_monoid R)`. example (R : CommMon.{u}) : R ⟶ R := { to_fun := λ x, begin match_target (R : Type u), match_hyp x : (R : Type u), exact x * x end , map_one' := by simp, map_mul' := λ x y, begin rw [mul_assoc x y (x * y), ←mul_assoc y x y, mul_comm y x, mul_assoc, mul_assoc], end, } variables {X Y : Type u} section variables [monoid X] [monoid Y] /-- Build an isomorphism in the category `Mon` from a `mul_equiv` between `monoid`s. -/ @[to_additive add_equiv.to_AddMon_iso "Build an isomorphism in the category `AddMon` from an `add_equiv` between `add_monoid`s.", simps] def mul_equiv.to_Mon_iso (e : X ≃* Y) : Mon.of X ≅ Mon.of Y := { hom := e.to_monoid_hom, inv := e.symm.to_monoid_hom } end section variables [comm_monoid X] [comm_monoid Y] /-- Build an isomorphism in the category `CommMon` from a `mul_equiv` between `comm_monoid`s. -/ @[to_additive add_equiv.to_AddCommMon_iso "Build an isomorphism in the category `AddCommMon` from an `add_equiv` between `add_comm_monoid`s.", simps] def mul_equiv.to_CommMon_iso (e : X ≃* Y) : CommMon.of X ≅ CommMon.of Y := { hom := e.to_monoid_hom, inv := e.symm.to_monoid_hom } end namespace category_theory.iso /-- Build a `mul_equiv` from an isomorphism in the category `Mon`. -/ @[to_additive AddMon_iso_to_add_equiv "Build an `add_equiv` from an isomorphism in the category `AddMon`."] def Mon_iso_to_mul_equiv {X Y : Mon} (i : X ≅ Y) : X ≃* Y := i.hom.to_mul_equiv i.inv i.hom_inv_id i.inv_hom_id /-- Build a `mul_equiv` from an isomorphism in the category `CommMon`. -/ @[to_additive "Build an `add_equiv` from an isomorphism in the category `AddCommMon`."] def CommMon_iso_to_mul_equiv {X Y : CommMon} (i : X ≅ Y) : X ≃* Y := i.hom.to_mul_equiv i.inv i.hom_inv_id i.inv_hom_id end category_theory.iso /-- multiplicative equivalences between `monoid`s are the same as (isomorphic to) isomorphisms in `Mon` -/ @[to_additive add_equiv_iso_AddMon_iso "additive equivalences between `add_monoid`s are the same as (isomorphic to) isomorphisms in `AddMon`"] def mul_equiv_iso_Mon_iso {X Y : Type u} [monoid X] [monoid Y] : (X ≃* Y) ≅ (Mon.of X ≅ Mon.of Y) := { hom := λ e, e.to_Mon_iso, inv := λ i, i.Mon_iso_to_mul_equiv, } /-- multiplicative equivalences between `comm_monoid`s are the same as (isomorphic to) isomorphisms in `CommMon` -/ @[to_additive add_equiv_iso_AddCommMon_iso "additive equivalences between `add_comm_monoid`s are the same as (isomorphic to) isomorphisms in `AddCommMon`"] def mul_equiv_iso_CommMon_iso {X Y : Type u} [comm_monoid X] [comm_monoid Y] : (X ≃* Y) ≅ (CommMon.of X ≅ CommMon.of Y) := { hom := λ e, e.to_CommMon_iso, inv := λ i, i.CommMon_iso_to_mul_equiv, } @[to_additive] instance Mon.forget_reflects_isos : reflects_isomorphisms (forget Mon.{u}) := { reflects := λ X Y f _, begin resetI, let i := as_iso ((forget Mon).map f), let e : X ≃* Y := { ..f, ..i.to_equiv }, exact ⟨(is_iso.of_iso e.to_Mon_iso).1⟩, end } @[to_additive] instance CommMon.forget_reflects_isos : reflects_isomorphisms (forget CommMon.{u}) := { reflects := λ X Y f _, begin resetI, let i := as_iso ((forget CommMon).map f), let e : X ≃* Y := { ..f, ..i.to_equiv }, exact ⟨(is_iso.of_iso e.to_CommMon_iso).1⟩, end } /-! Once we've shown that the forgetful functors to type reflect isomorphisms, we automatically obtain that the `forget₂` functors between our concrete categories reflect isomorphisms. -/ example : reflects_isomorphisms (forget₂ CommMon Mon) := by apply_instance
d7b941c46b17654216e3e0e8976d739504222895
0d2e44896897eda703992595d71a0b19ed30b8a1
/uexp/src/uexp/rules/projectJoinTranspose.lean
900d13389880daf77d0f6ee00459f34264b5aaed
[ "BSD-2-Clause" ]
permissive
wwombat/Cosette
a87312aabefdb53ea8b67c37731bd58c7485afb6
4c5dc6172e24d3546c9818ac1fad06f72fe1c991
refs/heads/master
1,619,479,568,051
1,520,292,502,000
1,520,292,502,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
819
lean
import ..sql import ..tactics import ..u_semiring import ..extra_constants open Expr open Proj open Pred open SQL open tree theorem rule: forall (Γ scm_s2 scm_s1: Schema) (rel_r2: relation scm_s2) (rel_r1: relation scm_s1) (s2_a : Column datatypes.int scm_s2) (s2_b : Column datatypes.int scm_s2) (s1_a : Column datatypes.int scm_s1) (s1_b : Column datatypes.int scm_s1), denoteSQL ((SELECT1 (combine (right⋅left⋅s1_b) (right⋅right⋅s2_b)) FROM1 (product (table rel_r1) (table rel_r2)) ) : SQL Γ _ ) = denoteSQL ((SELECT1 (combine (right⋅left) (right⋅right)) FROM1 (product ((SELECT1 (right⋅s1_b) FROM1 (table rel_r1) )) ((SELECT1 (right⋅s2_b) FROM1 (table rel_r2) ))) ) : SQL Γ _) := begin intros, unfold_all_denotations, funext, simp, sorry end
601e756e427ce8ab31ab80d2bcfd6fff76c947a7
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/data/rat/cast.lean
8091be94a889649d0c96c74c23097ee5b48659ee
[ "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
11,989
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import data.rat.order /-! # Casts for Rational Numbers ## Summary We define the canonical injection from ℚ into an arbitrary division ring and prove various casting lemmas showing the well-behavedness of this injection. ## Notations - `/.` is infix notation for `rat.mk`. ## Tags rat, rationals, field, ℚ, numerator, denominator, num, denom, cast, coercion, casting -/ namespace rat variable {α : Type*} open_locale rat section with_div_ring variable [division_ring α] /-- Construct the canonical injection from `ℚ` into an arbitrary division ring. If the field has positive characteristic `p`, we define `1 / p = 1 / 0 = 0` for consistency with our division by zero convention. -/ -- see Note [coercion into rings] @[priority 900] instance cast_coe : has_coe_t ℚ α := ⟨λ r, r.1 / r.2⟩ @[simp] theorem cast_of_int (n : ℤ) : (of_int n : α) = n := show (n / (1:ℕ) : α) = n, by rw [nat.cast_one, div_one] @[simp, norm_cast] theorem cast_coe_int (n : ℤ) : ((n : ℚ) : α) = n := by rw [coe_int_eq_of_int, cast_of_int] @[simp, norm_cast] theorem cast_coe_nat (n : ℕ) : ((n : ℚ) : α) = n := cast_coe_int n @[simp, norm_cast] theorem cast_zero : ((0 : ℚ) : α) = 0 := (cast_of_int _).trans int.cast_zero @[simp, norm_cast] theorem cast_one : ((1 : ℚ) : α) = 1 := (cast_of_int _).trans int.cast_one theorem cast_commute (r : ℚ) (a : α) : commute ↑r a := (r.1.cast_commute a).div_left (r.2.cast_commute a) theorem commute_cast (a : α) (r : ℚ) : commute a r := (r.cast_commute a).symm @[norm_cast] theorem cast_mk_of_ne_zero (a b : ℤ) (b0 : (b:α) ≠ 0) : (a /. b : α) = a / b := begin have b0' : b ≠ 0, { refine mt _ b0, simp {contextual := tt} }, cases e : a /. b with n d h c, have d0 : (d:α) ≠ 0, { intro d0, have dd := denom_dvd a b, cases (show (d:ℤ) ∣ b, by rwa e at dd) with k ke, have : (b:α) = (d:α) * (k:α), {rw [ke, int.cast_mul], refl}, rw [d0, zero_mul] at this, contradiction }, rw [num_denom'] at e, have := congr_arg (coe : ℤ → α) ((mk_eq b0' $ ne_of_gt $ int.coe_nat_pos.2 h).1 e), rw [int.cast_mul, int.cast_mul, int.cast_coe_nat] at this, symmetry, change (a * b⁻¹ : α) = n / d, rw [eq_div_iff_mul_eq _ _ d0, mul_assoc, (d.commute_cast _).eq, ← mul_assoc, this, mul_assoc, mul_inv_cancel b0, mul_one] end @[norm_cast] theorem cast_add_of_ne_zero : ∀ {m n : ℚ}, (m.denom : α) ≠ 0 → (n.denom : α) ≠ 0 → ((m + n : ℚ) : α) = m + n | ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := λ (d₁0 : (d₁:α) ≠ 0) (d₂0 : (d₂:α) ≠ 0), begin have d₁0' : (d₁:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₁0; exact d₁0 rfl), have d₂0' : (d₂:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₂0; exact d₂0 rfl), rw [num_denom', num_denom', add_def d₁0' d₂0'], suffices : (n₁ * (d₂ * (d₂⁻¹ * d₁⁻¹)) + n₂ * (d₁ * d₂⁻¹) * d₁⁻¹ : α) = n₁ * d₁⁻¹ + n₂ * d₂⁻¹, { rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, cast_mk_of_ne_zero], { simpa [division_def, left_distrib, right_distrib, mul_inv', d₁0, d₂0, mul_assoc] }, all_goals {simp [d₁0, d₂0]} }, rw [← mul_assoc (d₂:α), mul_inv_cancel d₂0, one_mul, (nat.cast_commute _ _).eq], simp [d₁0, mul_assoc] end @[simp, norm_cast] theorem cast_neg : ∀ n, ((-n : ℚ) : α) = -n | ⟨n, d, h, c⟩ := show (↑-n * d⁻¹ : α) = -(n * d⁻¹), by rw [int.cast_neg, neg_mul_eq_neg_mul] @[norm_cast] theorem cast_sub_of_ne_zero {m n : ℚ} (m0 : (m.denom : α) ≠ 0) (n0 : (n.denom : α) ≠ 0) : ((m - n : ℚ) : α) = m - n := have ((-n).denom : α) ≠ 0, by cases n; exact n0, by simp [sub_eq_add_neg, (cast_add_of_ne_zero m0 this)] @[norm_cast] theorem cast_mul_of_ne_zero : ∀ {m n : ℚ}, (m.denom : α) ≠ 0 → (n.denom : α) ≠ 0 → ((m * n : ℚ) : α) = m * n | ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := λ (d₁0 : (d₁:α) ≠ 0) (d₂0 : (d₂:α) ≠ 0), begin have d₁0' : (d₁:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₁0; exact d₁0 rfl), have d₂0' : (d₂:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₂0; exact d₂0 rfl), rw [num_denom', num_denom', mul_def d₁0' d₂0'], suffices : (n₁ * ((n₂ * d₂⁻¹) * d₁⁻¹) : α) = n₁ * (d₁⁻¹ * (n₂ * d₂⁻¹)), { rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, cast_mk_of_ne_zero], { simpa [division_def, mul_inv', d₁0, d₂0, mul_assoc] }, all_goals {simp [d₁0, d₂0]} }, rw [(d₁.commute_cast (_:α)).inv_right'.eq] end @[norm_cast] theorem cast_inv_of_ne_zero : ∀ {n : ℚ}, (n.num : α) ≠ 0 → (n.denom : α) ≠ 0 → ((n⁻¹ : ℚ) : α) = n⁻¹ | ⟨n, d, h, c⟩ := λ (n0 : (n:α) ≠ 0) (d0 : (d:α) ≠ 0), begin have n0' : (n:ℤ) ≠ 0 := λ e, by rw e at n0; exact n0 rfl, have d0' : (d:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d0; exact d0 rfl), rw [num_denom', inv_def], rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, inv_div]; simp [n0, d0] end @[norm_cast] theorem cast_div_of_ne_zero {m n : ℚ} (md : (m.denom : α) ≠ 0) (nn : (n.num : α) ≠ 0) (nd : (n.denom : α) ≠ 0) : ((m / n : ℚ) : α) = m / n := have (n⁻¹.denom : ℤ) ∣ n.num, by conv in n⁻¹.denom { rw [←(@num_denom n), inv_def] }; apply denom_dvd, have (n⁻¹.denom : α) = 0 → (n.num : α) = 0, from λ h, let ⟨k, e⟩ := this in by have := congr_arg (coe : ℤ → α) e; rwa [int.cast_mul, int.cast_coe_nat, h, zero_mul] at this, by rw [division_def, cast_mul_of_ne_zero md (mt this nn), cast_inv_of_ne_zero nn nd, division_def] @[simp, norm_cast] theorem cast_inj [char_zero α] : ∀ {m n : ℚ}, (m : α) = n ↔ m = n | ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := begin refine ⟨λ h, _, congr_arg _⟩, have d₁0 : d₁ ≠ 0 := ne_of_gt h₁, have d₂0 : d₂ ≠ 0 := ne_of_gt h₂, have d₁a : (d₁:α) ≠ 0 := nat.cast_ne_zero.2 d₁0, have d₂a : (d₂:α) ≠ 0 := nat.cast_ne_zero.2 d₂0, rw [num_denom', num_denom'] at h ⊢, rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero] at h; simp [d₁0, d₂0] at h ⊢, rwa [eq_div_iff_mul_eq _ _ d₂a, division_def, mul_assoc, (d₁.cast_commute (d₂:α)).inv_left'.eq, ← mul_assoc, ← division_def, eq_comm, eq_div_iff_mul_eq _ _ d₁a, eq_comm, ← int.cast_coe_nat, ← int.cast_mul, ← int.cast_coe_nat, ← int.cast_mul, int.cast_inj, ← mk_eq (int.coe_nat_ne_zero.2 d₁0) (int.coe_nat_ne_zero.2 d₂0)] at h end theorem cast_injective [char_zero α] : function.injective (coe : ℚ → α) | m n := cast_inj.1 @[simp] theorem cast_eq_zero [char_zero α] {n : ℚ} : (n : α) = 0 ↔ n = 0 := by rw [← cast_zero, cast_inj] theorem cast_ne_zero [char_zero α] {n : ℚ} : (n : α) ≠ 0 ↔ n ≠ 0 := not_congr cast_eq_zero @[simp, norm_cast] theorem cast_add [char_zero α] (m n) : ((m + n : ℚ) : α) = m + n := cast_add_of_ne_zero (nat.cast_ne_zero.2 $ ne_of_gt m.pos) (nat.cast_ne_zero.2 $ ne_of_gt n.pos) @[simp, norm_cast] theorem cast_sub [char_zero α] (m n) : ((m - n : ℚ) : α) = m - n := cast_sub_of_ne_zero (nat.cast_ne_zero.2 $ ne_of_gt m.pos) (nat.cast_ne_zero.2 $ ne_of_gt n.pos) @[simp, norm_cast] theorem cast_mul [char_zero α] (m n) : ((m * n : ℚ) : α) = m * n := cast_mul_of_ne_zero (nat.cast_ne_zero.2 $ ne_of_gt m.pos) (nat.cast_ne_zero.2 $ ne_of_gt n.pos) @[simp, norm_cast] theorem cast_bit0 [char_zero α] (n : ℚ) : ((bit0 n : ℚ) : α) = bit0 n := cast_add _ _ @[simp, norm_cast] theorem cast_bit1 [char_zero α] (n : ℚ) : ((bit1 n : ℚ) : α) = bit1 n := by rw [bit1, cast_add, cast_one, cast_bit0]; refl variable (α) /-- Coercion `ℚ → α` as a `ring_hom`. -/ def cast_hom [char_zero α] : ℚ →+* α := ⟨coe, cast_one, cast_mul, cast_zero, cast_add⟩ variable {α} @[simp] lemma coe_cast_hom [char_zero α] : ⇑(cast_hom α) = coe := rfl @[simp, norm_cast] theorem cast_inv [char_zero α] (n) : ((n⁻¹ : ℚ) : α) = n⁻¹ := (cast_hom α).map_inv @[simp, norm_cast] theorem cast_div [char_zero α] (m n) : ((m / n : ℚ) : α) = m / n := (cast_hom α).map_div @[norm_cast] theorem cast_mk [char_zero α] (a b : ℤ) : ((a /. b) : α) = a / b := by simp only [mk_eq_div, cast_div, cast_coe_int] @[simp, norm_cast] theorem cast_pow [char_zero α] (q) (k : ℕ) : ((q ^ k : ℚ) : α) = q ^ k := (cast_hom α).map_pow q k end with_div_ring @[simp, norm_cast] theorem cast_nonneg [linear_ordered_field α] : ∀ {n : ℚ}, 0 ≤ (n : α) ↔ 0 ≤ n | ⟨n, d, h, c⟩ := show 0 ≤ (n * d⁻¹ : α) ↔ 0 ≤ (⟨n, d, h, c⟩ : ℚ), by rw [num_denom', ← nonneg_iff_zero_le, mk_nonneg _ (int.coe_nat_pos.2 h), mul_nonneg_iff_right_nonneg_of_pos ((@inv_pos α _ _).2 (nat.cast_pos.2 h)), int.cast_nonneg] @[simp, norm_cast] theorem cast_le [linear_ordered_field α] {m n : ℚ} : (m : α) ≤ n ↔ m ≤ n := by rw [← sub_nonneg, ← cast_sub, cast_nonneg, sub_nonneg] @[simp, norm_cast] theorem cast_lt [linear_ordered_field α] {m n : ℚ} : (m : α) < n ↔ m < n := by simpa [-cast_le] using not_congr (@cast_le α _ n m) @[simp] theorem cast_nonpos [linear_ordered_field α] {n : ℚ} : (n : α) ≤ 0 ↔ n ≤ 0 := by rw [← cast_zero, cast_le] @[simp] theorem cast_pos [linear_ordered_field α] {n : ℚ} : (0 : α) < n ↔ 0 < n := by rw [← cast_zero, cast_lt] @[simp] theorem cast_lt_zero [linear_ordered_field α] {n : ℚ} : (n : α) < 0 ↔ n < 0 := by rw [← cast_zero, cast_lt] @[simp, norm_cast] theorem cast_id : ∀ n : ℚ, ↑n = n | ⟨n, d, h, c⟩ := show (n / (d : ℤ) : ℚ) = _, by rw [num_denom', mk_eq_div] @[simp, norm_cast] theorem cast_min [discrete_linear_ordered_field α] {a b : ℚ} : (↑(min a b) : α) = min a b := by by_cases a ≤ b; simp [h, min] @[simp, norm_cast] theorem cast_max [discrete_linear_ordered_field α] {a b : ℚ} : (↑(max a b) : α) = max a b := by by_cases a ≤ b; simp [h, max] @[simp, norm_cast] theorem cast_abs [discrete_linear_ordered_field α] {q : ℚ} : ((abs q : ℚ) : α) = abs q := by simp [abs] end rat open rat ring_hom lemma ring_hom.eq_rat_cast {k} [division_ring k] (f : ℚ →+* k) (r : ℚ) : f r = r := calc f r = f (r.1 / r.2) : by conv_lhs { rw [← @num_denom r, mk_eq_div, int.cast_coe_nat] } ... = (f.comp $ int.cast_ring_hom ℚ) r.1 / (f.comp $ nat.cast_ring_hom ℚ) r.2 : f.map_div ... = r.1 / r.2 : by rw [eq_nat_cast, eq_int_cast] -- This seems to be true for a `[char_p k]` too because `k'` must have the same characteristic -- but the proof would be much longer lemma ring_hom.map_rat_cast {k k'} [division_ring k] [char_zero k] [division_ring k'] (f : k →+* k') (r : ℚ) : f r = r := (f.comp (cast_hom k)).eq_rat_cast r lemma ring_hom.ext_rat {R : Type*} [semiring R] (f g : ℚ →+* R) : f = g := begin ext r, refine rat.num_denom_cases_on' r _, intros a b b0, let φ : ℤ →+* R := f.comp (int.cast_ring_hom ℚ), let ψ : ℤ →+* R := g.comp (int.cast_ring_hom ℚ), rw [rat.mk_eq_div, int.cast_coe_nat], have b0' : (b:ℚ) ≠ 0 := nat.cast_ne_zero.2 b0, have : ∀ n : ℤ, f n = g n := λ n, show φ n = ψ n, by rw [φ.ext_int ψ], calc f (a * b⁻¹) = f a * f b⁻¹ * (g (b:ℤ) * g b⁻¹) : by rw [int.cast_coe_nat, ← g.map_mul, mul_inv_cancel b0', g.map_one, mul_one, f.map_mul] ... = g a * f b⁻¹ * (f (b:ℤ) * g b⁻¹) : by rw [this a, ← this b] ... = g (a * b⁻¹) : by rw [int.cast_coe_nat, mul_assoc, ← mul_assoc (f b⁻¹), ← f.map_mul, inv_mul_cancel b0', f.map_one, one_mul, g.map_mul] end instance rat.subsingleton_ring_hom {R : Type*} [semiring R] : subsingleton (ℚ →+* R) := ⟨ring_hom.ext_rat⟩
243b2c890abf286739ebf4fae6b150809937ebcb
3ef5255cebe505e5ab251615d9fbf31a132f461d
/lean/old/general_recursion.lean
d2b5dbe4ada3c20e124ed979f86909d4a5e94cce
[]
no_license
avigad/scratch
42441a2ea94918049391e44d7adab304d3adea51
3fb9cef15bc5581c9602561427a7f295917990a2
refs/heads/master
1,608,917,412,424
1,473,078,921,000
1,473,078,921,000
17,224,172
0
0
null
null
null
null
UTF-8
Lean
false
false
10,591
lean
--- Copyright (c) 2014 Jeremy Avigad. All rights reserved. --- Released under Apache 2.0 license as described in the file LICENSE. --- Author: Jeremy Avigad -- TODO: replace default by inhabited -- TODO: use an arbitrary well-founded relation -- general_recursion.lean -- ====================== import logic data.nat.sub algebra.relation data.prod import tools.fake_simplifier -- for the example at the end import data.sigma open nat relation relation.iff_ops prod open fake_simplifier decidable open eq.ops open sigma -- TODO: move to data.nat.basic theorem ne_zero_succ_pred {n : ℕ} (H : n ≠ 0) : succ (pred n) = n := eq.symm (or.resolve_right (zero_or_succ_pred n) H) -- TODO: move to data.nat.order theorem ne_zero_pred_lt {n : ℕ} (H : n ≠ 0) : pred n < n := eq.subst (ne_zero_succ_pred H) !self_lt_succ -- TODO: move to logic.core.decidable definition by_cases_pos {a : Prop} {b : Type} {C : decidable a} (Hab : a → b) (Hnab : ¬a → b) (Ha : a) : by_cases Hab Hnab = Hab Ha := decidable.rec (take Ha : a, rfl) (take Hna : ¬a, absurd Ha Hna) C definition by_cases_neg {a : Prop} {b : Type} {C : decidable a} (Hab : a → b) (Hnab : ¬a → b) (Hna : ¬a) : by_cases Hab Hnab = Hnab Hna := decidable.rec (take Ha : a, absurd Ha Hna) (take Hna : ¬a, rfl) C namespace gen_rec -- A general recursion principle -- ----------------------------- -- -- Data: -- -- dom : Type -- codom : dom → Type -- default : ∀x, codom x -- measure : dom → ℕ -- rec_call : (∀x : dom, codom x) → (∀x : dom, codom x) -- -- and a proof -- -- rec_decreasing : ∀g1 g2 x, (∀z, measure z < measure x → g1 z = g2 z) → -- rec_call g1 x = rec_call g2 x -- -- which says that the recursive call only depends on values with measure less than x. -- -- The result is a function f = rec_measure, satisfying -- -- f x = rec_call f x context gen_rec_params parameters {dom : Type} {codom : dom → Type} parameter (default : ∀x, codom x) parameter (measure : dom → ℕ) parameter (rec_call : (∀x : dom, codom x) → (∀x : dom, codom x)) parameter (rec_decreasing : ∀g1 g2 x, (∀z, measure z < measure x → g1 z = g2 z) → rec_call g1 x = rec_call g2 x) definition restrict (f : ∀x : dom, codom x) (m : ℕ) (x : dom) := if measure x < m then f x else default x theorem restrict_lt_eq (f : ∀x : dom, codom x) (m : ℕ) (x : dom) (H : measure x < m) : restrict f m x = f x := if_pos H theorem restrict_not_lt_eq (f : ∀x : dom, codom x) (m : ℕ) (x : dom) (H : ¬ measure x < m) : restrict f m x = default x := if_neg H definition rec_measure_aux : ℕ → (∀x : dom, codom x) := nat.rec (λx, default x) (λm g x, if measure x < succ m then rec_call g x else default x) -- this is the desired function definition rec_measure (x : dom) : codom x := rec_measure_aux (succ (measure x)) x theorem rec_measure_aux_spec (m : ℕ) : ∀x, rec_measure_aux m x = restrict rec_measure m x := let f' := rec_measure_aux, f := rec_measure in nat.case_strong_induction_on m (take x, have H1 : f' 0 x = default x, from rfl, have H2 : ¬ measure x < 0, from !not_lt_zero, have H3 : restrict f 0 x = default x, from if_neg H2, show f' 0 x = restrict f 0 x, from H1 ⬝ H3⁻¹) (take m, assume IH: ∀n, n ≤ m → ∀x, f' n x = restrict f n x, take x : dom, show f' (succ m) x = restrict f (succ m) x, from by_cases (assume H1 : measure x < succ m, have H2a : ∀z, measure z < measure x → f' m z = f z, from take z, assume Hzx : measure z < measure x, calc f' m z = restrict f m z : IH m !le_refl z ... = f z : restrict_lt_eq _ _ _ (lt_le_trans Hzx (lt_succ_imp_le H1)), have H2 : f' (succ m) x = rec_call f x, from calc f' (succ m) x = if measure x < succ m then rec_call (f' m) x else default x : rfl ... = rec_call (f' m) x : if_pos H1 ... = rec_call f x : rec_decreasing (f' m) f x H2a, let m' := measure x in have H3a : ∀z, measure z < m' → f' m' z = f z, from take z, assume Hzx : measure z < measure x, calc f' m' z = restrict f m' z : IH _ (lt_succ_imp_le H1) _ ... = f z : restrict_lt_eq _ _ _ Hzx, have H3 : restrict f (succ m) x = rec_call f x, from calc restrict f (succ m) x = f x : if_pos H1 ... = f' (succ m') x : eq.refl _ ... = if measure x < succ m' then rec_call (f' m') x else default x : rfl ... = rec_call (f' m') x : if_pos !self_lt_succ ... = rec_call f x : rec_decreasing _ _ _ H3a, show f' (succ m) x = restrict f (succ m) x, from H2 ⬝ H3⁻¹) (assume H1 : ¬ measure x < succ m, have H2 : f' (succ m) x = default x, from calc f' (succ m) x = if measure x < succ m then rec_call (f' m) x else default x : rfl ... = default x : if_neg H1, have H3 : restrict f (succ m) x = default x, from if_neg H1, show f' (succ m) x = restrict f (succ m) x, from H2 ⬝ H3⁻¹)) theorem rec_measure_spec (x : dom): rec_measure x = rec_call rec_measure x := let f' := rec_measure_aux, f := rec_measure, m := measure x in have H : ∀z, measure z < measure x → f' m z = f z, from take z, assume H1 : measure z < measure x, calc f' m z = restrict f m z : rec_measure_aux_spec m z ... = f z : restrict_lt_eq _ _ _ H1, calc f x = f' (succ m) x : rfl ... = if measure x < succ m then rec_call (f' m) x else default x : rfl ... = rec_call (f' m) x : if_pos !self_lt_succ ... = rec_call f x : rec_decreasing _ _ _ H end gen_rec_params end gen_rec -- Try it out. -- =========== -- vec -- --- -- TODO: is there any way to make the second argument to append implicit? inductive vec (A : Type) : ℕ → Type := empty {} : vec A 0, append : A → ∀n, (vec A n → vec A (succ n)) namespace vec context parameters {A : Type} (a : A) {n : ℕ} definition last (v : vec A n) : A := vec.rec a (λa' n v' x, a') v definition drop_last (v : vec A n) : vec A (pred n) := vec.rec empty (λa' n v' x, v') v definition default (n : nat) : vec A n := nat.rec empty (λn v, append a n v) n end end vec -- vec_add -- ------- definition vec_add_aux_dom : Type.{1} := Σ(n: ℕ) (v1 : vec nat n), vec nat n definition vec_add_aux_cod (x : vec_add_aux_dom) : Type.{1} := vec nat (dpr1 x) definition vec_add_aux_default (x : vec_add_aux_dom) : vec_add_aux_cod x := vec.default 0 (dpr1 x) definition vec_add_aux_measure (x : vec_add_aux_dom) : ℕ := dpr1 x definition vec_add_aux_rec_call (f : ∀x, vec_add_aux_cod x) (x : vec_add_aux_dom) : vec_add_aux_cod x := let n := dpr1 x, v1 := dpr1 (dpr2 x), v2 := dpr2 (dpr2 x) in by_cases (assume H : n = 0, eq.rec_on (eq.symm H) vec.empty) (assume H : n ≠ 0, have H1 : succ (pred n) = n, from ne_zero_succ_pred H, let x1' := vec.last 0 v1, x2' := vec.last 0 v2, v1' := vec.drop_last v1, v2' := vec.drop_last v2, rec_arg := dpair (pred n) (dpair v1' v2') in eq.rec_on H1 (vec.append (x1' + x2') _ (f rec_arg))) theorem vec_add_aux_decreasing (g1 g2 : ∀x, vec_add_aux_cod x) (x : vec_add_aux_dom) (H : ∀z, vec_add_aux_measure z < vec_add_aux_measure x → g1 z = g2 z) : vec_add_aux_rec_call g1 x = vec_add_aux_rec_call g2 x := let n := dpr1 x, v1 := dpr1 (dpr2 x), v2 := dpr2 (dpr2 x) in by_cases (assume Hz : n = 0, calc vec_add_aux_rec_call g1 x = eq.rec_on (eq.symm Hz) vec.empty : by_cases_pos _ _ Hz ... = vec_add_aux_rec_call g2 x : eq.symm (by_cases_pos _ _ Hz)) (assume Hnz : n ≠ 0, have H1 [visible] : succ (pred n) = n, from ne_zero_succ_pred Hnz, let x1' := vec.last 0 v1, x2' := vec.last 0 v2, v1' := vec.drop_last v1, v2' := vec.drop_last v2, rec_arg := dpair (pred n) (dpair v1' v2') in have H2 : vec_add_aux_measure rec_arg < vec_add_aux_measure x, from ne_zero_pred_lt Hnz, calc vec_add_aux_rec_call g1 x = eq.rec_on H1 (vec.append (x1' + x2') _ (g1 rec_arg)) : by_cases_neg _ _ Hnz ... = eq.rec_on H1 (vec.append (x1' + x2') _ (g2 rec_arg)) : {H _ H2} ... = vec_add_aux_rec_call g2 x : eq.symm (by_cases_neg _ _ Hnz)) definition vec_add_aux := gen_rec.rec_measure vec_add_aux_default vec_add_aux_measure vec_add_aux_rec_call theorem vec_add_aux_spec_zero (x : vec_add_aux_dom) (H : dpr1 x = 0) : vec_add_aux x = eq.rec_on (eq.symm H) vec.empty := eq.trans (gen_rec.rec_measure_spec vec_add_aux_default vec_add_aux_measure vec_add_aux_rec_call vec_add_aux_decreasing x) (by_cases_pos _ _ H) theorem vec_add_aux_spec_not_zero (x : vec_add_aux_dom) (H : dpr1 x ≠ 0) : vec_add_aux x = let n := dpr1 x, v1 := dpr1 (dpr2 x), v2 := dpr2 (dpr2 x), H1 := ne_zero_succ_pred H, x1' := vec.last 0 v1, x2' := vec.last 0 v2, v1' := vec.drop_last v1, v2' := vec.drop_last v2, rec_arg := dpair (pred n) (dpair v1' v2') in eq.rec_on H1 (vec.append (x1' + x2') _ (vec_add_aux rec_arg)) := eq.trans (gen_rec.rec_measure_spec vec_add_aux_default vec_add_aux_measure vec_add_aux_rec_call vec_add_aux_decreasing x) (by_cases_neg _ _ H) definition vec_add {n : ℕ} (v1 v2 : vec nat n) : vec nat n := vec_add_aux (dpair n (dpair v1 v2)) theorem vec_add_zero (v1 v2 : vec nat 0) : vec_add v1 v2 = vec.empty := eq.trans (vec_add_aux_spec_zero _ rfl) (eq.rec_on_id _ _) theorem vec_add_succ {n : ℕ} (v1 v2 : vec nat (succ n)) : vec_add v1 v2 = vec.append (vec.last 0 v1 + vec.last 0 v2) _ (vec_add (vec.drop_last v1) (vec.drop_last v2)) := eq.trans (vec_add_aux_spec_not_zero _ !nat.succ_ne_zero) (eq.rec_on_id _ _) -- easier definition of vec_add -- ---------------------------- definition vec_add' {n : ℕ} : ∀v1 v2 : vec nat n, vec nat n := nat.rec_on n (λv1 v2, vec.empty) (take n, take f : ∀v1 v2 : vec nat n, vec nat n, take v1 v2 : vec nat (succ n), vec.append (vec.last 0 v1 + vec.last 0 v2) _ (f (vec.drop_last v1) (vec.drop_last v2))) theorem vec_add_zero' (v1 v2 : vec nat 0) : vec_add' v1 v2 = vec.empty := rfl theorem vec_add_succ' {n : nat} (v1 v2 : vec nat (succ n)) : vec_add' v1 v2 = vec.append (vec.last 0 v1 + vec.last 0 v2) _ (vec_add' (vec.drop_last v1) (vec.drop_last v2)) := rfl
7ab771b6754032b33e2fdc958a1018d4b67d7abd
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/monoidal/skeleton.lean
f842f1efcedc6ee327e41c2efe0b9a541c99fdaf
[ "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
1,749
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.monoidal.braided import category_theory.monoidal.transport import category_theory.skeletal /-! # The monoid on the skeleton of a monoidal category The skeleton of a monoidal category is a monoid. -/ namespace category_theory open monoidal_category universes v u variables {C : Type u} [category.{v} C] [monoidal_category C] /-- If `C` is monoidal and skeletal, it is a monoid. See note [reducible non-instances]. -/ @[reducible] def monoid_of_skeletal_monoidal (hC : skeletal C) : monoid C := { mul := λ X Y, (X ⊗ Y : C), one := (𝟙_ C : C), one_mul := λ X, hC ⟨λ_ X⟩, mul_one := λ X, hC ⟨ρ_ X⟩, mul_assoc := λ X Y Z, hC ⟨α_ X Y Z⟩ } /-- If `C` is braided and skeletal, it is a commutative monoid. -/ def comm_monoid_of_skeletal_braided [braided_category C] (hC : skeletal C) : comm_monoid C := { mul_comm := λ X Y, hC ⟨β_ X Y⟩, ..monoid_of_skeletal_monoidal hC } /-- The skeleton of a monoidal category has a monoidal structure itself, induced by the equivalence. -/ noncomputable instance : monoidal_category (skeleton C) := monoidal.transport (skeleton_equivalence C).symm /-- The skeleton of a monoidal category can be viewed as a monoid, where the multiplication is given by the tensor product, and satisfies the monoid axioms since it is a skeleton. -/ noncomputable instance : monoid (skeleton C) := monoid_of_skeletal_monoidal (skeleton_is_skeleton _).skel -- TODO: Transfer the braided structure to the skeleton of C along the equivalence, and show that -- the skeleton is a commutative monoid. end category_theory
a2d3ec9e4ad4c6d8108758536126dbc7ec41b353
97c8e5d8aca4afeebb5b335f26a492c53680efc8
/ground_zero/HITs/suspension.lean
5960d1a83cb696e74450f42c710ae136bdda198d
[]
no_license
jfrancese/lean
cf32f0d8d5520b6f0e9d3987deb95841c553c53c
06e7efaecce4093d97fb5ecc75479df2ef1dbbdb
refs/heads/master
1,587,915,151,351
1,551,012,140,000
1,551,012,140,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,135
lean
import ground_zero.HITs.pushout ground_zero.types.unit /- Suspension. * HoTT 6.5 -/ namespace ground_zero namespace HITs abbreviation unit₀ : Type := types.unit abbreviation star₀ : unit₀ := types.unit.star def {u} suspension (α : Type u) := pushout (λ (a : α), star₀) (λ _, star₀) notation `∑` := suspension namespace suspension -- https://github.com/leanprover/lean2/blob/master/hott/homotopy/susp.hlean universes u v def north {α : Type u} : suspension α := pushout.inl types.unit.star def south {α : Type u} : suspension α := pushout.inr types.unit.star def merid {α : Type u} (a : α) : north = south :> suspension α := pushout.glue a def ind {α : Type u} {β : ∑α → Type v} (n : β north) (s : β south) (m : Π (x : α), n =[merid x] s) : Π (x : ∑α), β x := pushout.ind (begin intro x, induction x, apply n end) (begin intro x, induction x, apply s end) (by assumption) def rec {α : Type u} {β : Type v} (n s : β) (m : α → n = s :> β) : ∑α → β := pushout.rec (λ _, n) (λ _, s) m end suspension end HITs end ground_zero
817041e2b33c6b64552e3637e094c2af561ca555
4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d
/src/Lean/Elab/PreDefinition/Structural/FindRecArg.lean
57702914c75ef50977a960f22fec8118b156f236
[ "Apache-2.0" ]
permissive
subfish-zhou/leanprover-zh_CN.github.io
30b9fba9bd790720bd95764e61ae796697d2f603
8b2985d4a3d458ceda9361ac454c28168d920d3f
refs/heads/master
1,689,709,967,820
1,632,503,056,000
1,632,503,056,000
409,962,097
1
0
null
null
null
null
UTF-8
Lean
false
false
4,649
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.PreDefinition.Structural.Basic namespace Lean.Elab.Structural open Meta private def getIndexMinPos (xs : Array Expr) (indices : Array Expr) : Nat := do let mut minPos := xs.size for index in indices do match xs.indexOf? index with | some pos => if pos.val < minPos then minPos := pos.val | _ => pure () return minPos -- Indices can only depend on other indices private def hasBadIndexDep? (ys : Array Expr) (indices : Array Expr) : MetaM (Option (Expr × Expr)) := do for index in indices do let indexType ← inferType index for y in ys do if !indices.contains y && (← dependsOn indexType y.fvarId!) then return some (index, y) return none -- Inductive datatype parameters cannot depend on ys private def hasBadParamDep? (ys : Array Expr) (indParams : Array Expr) : MetaM (Option (Expr × Expr)) := do for p in indParams do let pType ← inferType p for y in ys do if ← dependsOn pType y.fvarId! then return some (p, y) return none private def throwStructuralFailed : MetaM α := throwError "structural recursion cannot be used" private def orelse' (x y : M α) : M α := do let saveState ← get orelseMergeErrors x (do set saveState; y) partial def findRecArg (numFixed : Nat) (xs : Array Expr) (k : RecArgInfo → M α) : M α := let rec loop (i : Nat) : M α := do if h : i < xs.size then let x := xs.get ⟨i, h⟩ let localDecl ← getFVarLocalDecl x if localDecl.isLet then throwStructuralFailed else let xType ← whnfD localDecl.type matchConstInduct xType.getAppFn (fun _ => loop (i+1)) fun indInfo us => do if !(← hasConst (mkBRecOnName indInfo.name)) then loop (i+1) else if indInfo.isReflexive && !(← hasConst (mkBInductionOnName indInfo.name)) then loop (i+1) else let indArgs := xType.getAppArgs let indParams := indArgs.extract 0 indInfo.numParams let indIndices := indArgs.extract indInfo.numParams indArgs.size if !indIndices.all Expr.isFVar then orelse' (throwError "argument #{i+1} was not used because its type is an inductive family and indices are not variables{indentExpr xType}") (loop (i+1)) else if !indIndices.allDiff then orelse' (throwError "argument #{i+1} was not used because its type is an inductive family and indices are not pairwise distinct{indentExpr xType}") (loop (i+1)) else let indexMinPos := getIndexMinPos xs indIndices let numFixed := if indexMinPos < numFixed then indexMinPos else numFixed let fixedParams := xs.extract 0 numFixed let ys := xs.extract numFixed xs.size match (← hasBadIndexDep? ys indIndices) with | some (index, y) => orelse' (throwError "argument #{i+1} was not used because its type is an inductive family{indentExpr xType}\nand index{indentExpr index}\ndepends on the non index{indentExpr y}") (loop (i+1)) | none => match (← hasBadParamDep? ys indParams) with | some (indParam, y) => orelse' (throwError "argument #{i+1} was not used because its type is an inductive datatype{indentExpr xType}\nand parameter{indentExpr indParam}\ndepends on{indentExpr y}") (loop (i+1)) | none => let indicesPos := indIndices.map fun index => match ys.indexOf? index with | some i => i.val | none => unreachable! orelse' (mapError (k { fixedParams := fixedParams ys := ys pos := i - fixedParams.size indicesPos := indicesPos indName := indInfo.name indLevels := us indParams := indParams indIndices := indIndices reflexive := indInfo.isReflexive indPred := ←isInductivePredicate indInfo.name }) (fun msg => m!"argument #{i+1} was not used for structural recursion{indentD msg}")) (loop (i+1)) else throwStructuralFailed loop numFixed end Lean.Elab.Structural
29433cc3f5039eb85a9fdfc954c2147bdf8eeccc
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/test/import_order_timeout.lean
b3ebf8c1725d91270b24da982b9b6792b3fc5ea7
[ "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
774
lean
import linear_algebra.tensor_product import deprecated.subring -- Swap these ↑ two imports, and then `foo` will always be happy. -- This was not the cases on commit `df4500242eb6aa6ee20b315b185b0f97a9b359c5`. -- You would get a timeout. import algebra.module.submodule.basic variables {R M N P Q : Type*} [comm_ring R] variables [add_comm_group M] [module R M] variables [add_comm_group N] [module R N] open function lemma injective_iff (f : M →ₗ[R] N) : function.injective f ↔ ∀ m, f m = 0 → m = 0 := injective_iff_map_eq_zero f lemma foo (L : submodule R (unit → R)) (H : ∀ (m : tensor_product R ↥L ↥L), (tensor_product.map L.subtype L.subtype) m = 0 → m = 0) : injective (tensor_product.map L.subtype L.subtype) := (injective_iff _).mpr H
e5e6ad755a58e604513f50433751cdfcd6b35d39
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/proof_qed_nested_tac.lean
c27e731cf2949cf73aaed4bc5535b1c32f6faf3b
[ "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
297
lean
example (a b c : nat) (f : nat → nat → nat) (H₁ : a = b) (H₂ : b = c) : f (f a a) (f b b) = f (f c c) (f c c) := assert h : a = c, from eq.trans H₁ H₂, proof calc f (f a a) (f b b) = f (f c c) (f b b) : by rewrite h ... = f (f c c) (f c c) : by rewrite H₂ qed
2f23f5729eb7de55494074c864a4d522dd6ba28d
fe84e287c662151bb313504482b218a503b972f3
/src/commutative_algebra/boolean_ring.lean
bae5db5a32e91be54a2eaca63217c0edf0ec222c
[]
no_license
NeilStrickland/lean_lib
91e163f514b829c42fe75636407138b5c75cba83
6a9563de93748ace509d9db4302db6cd77d8f92c
refs/heads/master
1,653,408,198,261
1,652,996,419,000
1,652,996,419,000
181,006,067
4
1
null
null
null
null
UTF-8
Lean
false
false
4,663
lean
import algebra.ring import order.boolean_algebra universe u variable (α : Type u) class boolean_ring (α : Type u) extends (ring α) := (mul_self : ∀ a : α, a * a = a) namespace boolean_ring variable {α} variables [boolean_ring α] lemma add_self (a : α) : a + a = 0 := begin have := mul_self (a + a), rw [add_mul, mul_add, mul_self a] at this, exact calc a + a = (a + a) + (a + a) - (a + a) : (add_sub_cancel _ _).symm ... = 0 : by rw [this, sub_self] end lemma neg_self (a : α) : - a = a := (eq_neg_iff_add_eq_zero.mpr (add_self a)).symm instance : comm_ring α := { mul_comm := λ a b, begin have h0 := mul_self (a + b), rw [mul_add, add_mul, add_mul, mul_self a, mul_self b, add_assoc] at h0, have h1 := congr_arg (has_add.add (b * a)) (add_left_cancel h0), rw [← add_assoc, add_self (b * a), zero_add] at h1, exact add_right_cancel h1 end, .. (by {apply_instance} : ring α) } open lattice instance : has_le α := ⟨λ a b, a * b = a⟩ instance : has_bot α := ⟨0⟩ instance : has_top α := ⟨1⟩ instance : has_sup α := ⟨λ a b, a + b + a * b⟩ instance : has_inf α := ⟨λ a b, a * b⟩ instance : boolean_algebra α := { le := has_le.le, bot := has_bot.bot, top := has_top.top, sup := has_sup.sup, inf := has_inf.inf, le_refl := λ a, mul_self a, le_antisymm := λ a b (hab : a * b = a) (hba : b * a = b), (hab.symm.trans (mul_comm a b)).trans hba, le_trans := λ a b c (hab : a * b = a) (hbc : b * c = b), calc a * c = a * b * c : by {rw[hab],} ... = a : by {rw[mul_assoc,hbc,hab]}, bot_le := λ a, (zero_mul a), le_top := λ a, (mul_one a), sup_le := λ a b c (hac : a * c = a) (hbc : b * c = b), show (a + b + a * b) * c = (a + b + a * b), by rw [add_mul, add_mul, mul_assoc, hac, hbc], le_sup_left := λ a b, show a * (a + b + a * b) = a, by rw [mul_add,mul_add,← mul_assoc,mul_self a,add_assoc, add_self (a * b),add_zero], le_sup_right := λ a b, show b * (a + b + a * b) = b, by rw[mul_comm a b, mul_add,mul_add,← mul_assoc,mul_self b, add_comm (b * a) b,add_assoc, add_self (b * a),add_zero], le_inf := λ a b c (hab : a * b = a) (hac : a * c = a), show a * (b * c) = a, by rw [← mul_assoc, hab, hac], inf_le_left := λ a b, show (a * b) * a = a * b, by rw [mul_assoc, mul_comm b a, ← mul_assoc, mul_self a], inf_le_right := λ a b, show (a * b) * b = a * b, by rw [mul_assoc,mul_self b], le_sup_inf := λ a b c, show (a + b + a * b) * (a + c + a * c) * (a + b * c + a * (b * c)) = (a + b + a * b) * (a + c + a * c), begin let ha := mul_self a, let hb := mul_self b, let hc := mul_self c, let u := (a + b + a * b), let v := (a + c + a * c), let w := (a + b * c + a * (b * c)), change u * v * w = u * v, have hua : u * a = a := by {rw [mul_comm], dsimp[u], rw [mul_add, mul_add, ← mul_assoc, ha, add_assoc, add_self, add_zero] }, have huc : u * c = a * c + b * c + a * b * c := by {dsimp[u],rw[add_mul,add_mul]}, have huv : u * v = a + b * c + b * c * a := by {dsimp [v], rw [mul_add, mul_add, ← mul_assoc u, hua, add_assoc, add_comm (u * c)], rw [huc, ← add_assoc (a * c), ← add_assoc (a * c), add_self (a * c), zero_add], rw [add_assoc,mul_assoc a,mul_comm a]}, have haw : a * w = a := by {dsimp [w], rw [mul_add, mul_add, ← mul_assoc a, ← mul_assoc a, ← mul_assoc a], rw [ha, add_assoc, add_self, add_zero]}, rw [huv, add_mul, add_mul, mul_assoc (b * c), haw], congr' 2, dsimp [w], rw [mul_add, mul_add, mul_comm a (b * c), ← mul_assoc (b * c) (b * c)], rw [mul_self (b * c), add_comm (b * c * a), add_assoc, add_self, add_zero], end, compl := λ a, 1 + a, sdiff := λ a b, a + a * b, sdiff_eq := λ a b, show a + a * b = a * (1 + b), by rw[mul_add,mul_one], sup_inf_sdiff := λ a b, show a * b + (a + a * b) + (a * b) * (a + a * b) = a, by rw[mul_add,mul_comm (a * b) a,← mul_assoc,mul_self a,mul_self (a * b), add_self (a * b),add_zero,add_comm a,← add_assoc,add_self (a * b),zero_add], inf_inf_sdiff := λ a b, show a * b * (a + a * b) = 0, by rw[mul_add,mul_self (a * b),mul_comm (a * b),← mul_assoc,mul_self a, add_self], inf_compl_le_bot := λ a, show a * (1 + a) * 0 = a * (1 + a), by rw[mul_zero,mul_add,mul_one,mul_self,add_self], top_le_sup_compl := λ a, show 1 * (a + (1 + a) + a * (1 + a)) = 1, by rw[one_mul,mul_add,mul_one,mul_self,add_self,add_zero, add_comm 1 a,← add_assoc,add_self,zero_add] } end boolean_ring
42024fa4d566f776127665f791b71e2fd7281562
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/control/id.lean
562be4e12cd792e860bddfab536b29cd5d8299a0
[]
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
497
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich The identity monad. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.control.lift universes u u_1 namespace Mathlib def id_bind {α : Type u} {β : Type u} (x : α) (f : α → id β) : id β := f x protected instance id.monad : Monad id := sorry protected instance id.monad_run : monad_run id id := monad_run.mk id
8235ff3bb8b7cbaabd19de8435ceffc751012ebc
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/category_theory/limits/functor_category.lean
00c41200797c23abd9140e0c1e8dcd506adf3fa8
[ "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
15,788
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 category_theory.limits.preserves.limits import category_theory.currying import category_theory.products /-! # (Co)limits in functor categories. We show that if `D` has limits, then the functor category `C ⥤ D` also has limits (`category_theory.limits.functor_category_has_limits`), and the evaluation functors preserve limits (`category_theory.limits.evaluation_preserves_limits`) (and similarly for colimits). We also show that `F : D ⥤ K ⥤ C` preserves (co)limits if it does so for each `k : K` (`category_theory.limits.preserves_limits_of_evaluation` and `category_theory.limits.preserves_colimits_of_evaluation`). -/ open category_theory category_theory.category namespace category_theory.limits universes v v₂ u u₂ -- morphism levels before object levels. See note [category_theory universes]. variables {C : Type u} [category.{v} C] {D : Type u₂} [category.{v} D] variables {J K : Type v} [small_category J] [category.{v₂} K] @[simp, reassoc] lemma limit.lift_π_app (H : J ⥤ K ⥤ C) [has_limit H] (c : cone H) (j : J) (k : K) : (limit.lift H c).app k ≫ (limit.π H j).app k = (c.π.app j).app k := congr_app (limit.lift_π c j) k @[simp, reassoc] lemma colimit.ι_desc_app (H : J ⥤ K ⥤ C) [has_colimit H] (c : cocone H) (j : J) (k : K) : (colimit.ι H j).app k ≫ (colimit.desc H c).app k = (c.ι.app j).app k := congr_app (colimit.ι_desc c j) k /-- The evaluation functors jointly reflect limits: that is, to show a cone is a limit of `F` it suffices to show that each evaluation cone is a limit. In other words, to prove a cone is limiting you can show it's pointwise limiting. -/ def evaluation_jointly_reflects_limits {F : J ⥤ K ⥤ C} (c : cone F) (t : Π (k : K), is_limit (((evaluation K C).obj k).map_cone c)) : is_limit c := { lift := λ s, { app := λ k, (t k).lift ⟨s.X.obj k, whisker_right s.π ((evaluation K C).obj k)⟩, naturality' := λ X Y f, (t Y).hom_ext $ λ j, begin rw [assoc, (t Y).fac _ j], simpa using ((t X).fac_assoc ⟨s.X.obj X, whisker_right s.π ((evaluation K C).obj X)⟩ j _).symm, end }, fac' := λ s j, nat_trans.ext _ _ $ funext $ λ k, (t k).fac _ j, uniq' := λ s m w, nat_trans.ext _ _ $ funext $ λ x, (t x).hom_ext $ λ j, (congr_app (w j) x).trans ((t x).fac ⟨s.X.obj _, whisker_right s.π ((evaluation K C).obj _)⟩ j).symm } /-- Given a functor `F` and a collection of limit cones for each diagram `X ↦ F X k`, we can stitch them together to give a cone for the diagram `F`. `combined_is_limit` shows that the new cone is limiting, and `eval_combined` shows it is (essentially) made up of the original cones. -/ @[simps] def combine_cones (F : J ⥤ K ⥤ C) (c : Π (k : K), limit_cone (F.flip.obj k)) : cone F := { X := { obj := λ k, (c k).cone.X, map := λ k₁ k₂ f, (c k₂).is_limit.lift ⟨_, (c k₁).cone.π ≫ F.flip.map f⟩, map_id' := λ k, (c k).is_limit.hom_ext (λ j, by { dsimp, simp }), map_comp' := λ k₁ k₂ k₃ f₁ f₂, (c k₃).is_limit.hom_ext (λ j, by simp) }, π := { app := λ j, { app := λ k, (c k).cone.π.app j }, naturality' := λ j₁ j₂ g, nat_trans.ext _ _ $ funext $ λ k, (c k).cone.π.naturality g } } /-- The stitched together cones each project down to the original given cones (up to iso). -/ def evaluate_combined_cones (F : J ⥤ K ⥤ C) (c : Π (k : K), limit_cone (F.flip.obj k)) (k : K) : ((evaluation K C).obj k).map_cone (combine_cones F c) ≅ (c k).cone := cones.ext (iso.refl _) (by tidy) /-- Stitching together limiting cones gives a limiting cone. -/ def combined_is_limit (F : J ⥤ K ⥤ C) (c : Π (k : K), limit_cone (F.flip.obj k)) : is_limit (combine_cones F c) := evaluation_jointly_reflects_limits _ (λ k, (c k).is_limit.of_iso_limit (evaluate_combined_cones F c k).symm) /-- The evaluation functors jointly reflect colimits: that is, to show a cocone is a colimit of `F` it suffices to show that each evaluation cocone is a colimit. In other words, to prove a cocone is colimiting you can show it's pointwise colimiting. -/ def evaluation_jointly_reflects_colimits {F : J ⥤ K ⥤ C} (c : cocone F) (t : Π (k : K), is_colimit (((evaluation K C).obj k).map_cocone c)) : is_colimit c := { desc := λ s, { app := λ k, (t k).desc ⟨s.X.obj k, whisker_right s.ι ((evaluation K C).obj k)⟩, naturality' := λ X Y f, (t X).hom_ext $ λ j, begin rw [(t X).fac_assoc _ j], erw ← (c.ι.app j).naturality_assoc f, erw (t Y).fac ⟨s.X.obj _, whisker_right s.ι _⟩ j, dsimp, simp, end }, fac' := λ s j, nat_trans.ext _ _ $ funext $ λ k, (t k).fac _ j, uniq' := λ s m w, nat_trans.ext _ _ $ funext $ λ x, (t x).hom_ext $ λ j, (congr_app (w j) x).trans ((t x).fac ⟨s.X.obj _, whisker_right s.ι ((evaluation K C).obj _)⟩ j).symm } /-- Given a functor `F` and a collection of colimit cocones for each diagram `X ↦ F X k`, we can stitch them together to give a cocone for the diagram `F`. `combined_is_colimit` shows that the new cocone is colimiting, and `eval_combined` shows it is (essentially) made up of the original cocones. -/ @[simps] def combine_cocones (F : J ⥤ K ⥤ C) (c : Π (k : K), colimit_cocone (F.flip.obj k)) : cocone F := { X := { obj := λ k, (c k).cocone.X, map := λ k₁ k₂ f, (c k₁).is_colimit.desc ⟨_, F.flip.map f ≫ (c k₂).cocone.ι⟩, map_id' := λ k, (c k).is_colimit.hom_ext (λ j, by { dsimp, simp }), map_comp' := λ k₁ k₂ k₃ f₁ f₂, (c k₁).is_colimit.hom_ext (λ j, by simp) }, ι := { app := λ j, { app := λ k, (c k).cocone.ι.app j }, naturality' := λ j₁ j₂ g, nat_trans.ext _ _ $ funext $ λ k, (c k).cocone.ι.naturality g } } /-- The stitched together cocones each project down to the original given cocones (up to iso). -/ def evaluate_combined_cocones (F : J ⥤ K ⥤ C) (c : Π (k : K), colimit_cocone (F.flip.obj k)) (k : K) : ((evaluation K C).obj k).map_cocone (combine_cocones F c) ≅ (c k).cocone := cocones.ext (iso.refl _) (by tidy) /-- Stitching together colimiting cocones gives a colimiting cocone. -/ def combined_is_colimit (F : J ⥤ K ⥤ C) (c : Π (k : K), colimit_cocone (F.flip.obj k)) : is_colimit (combine_cocones F c) := evaluation_jointly_reflects_colimits _ (λ k, (c k).is_colimit.of_iso_colimit (evaluate_combined_cocones F c k).symm) noncomputable theory instance functor_category_has_limits_of_shape [has_limits_of_shape J C] : has_limits_of_shape J (K ⥤ C) := { has_limit := λ F, has_limit.mk { cone := combine_cones F (λ k, get_limit_cone _), is_limit := combined_is_limit _ _ } } instance functor_category_has_colimits_of_shape [has_colimits_of_shape J C] : has_colimits_of_shape J (K ⥤ C) := { has_colimit := λ F, has_colimit.mk { cocone := combine_cocones _ (λ k, get_colimit_cocone _), is_colimit := combined_is_colimit _ _ } } instance functor_category_has_limits [has_limits C] : has_limits (K ⥤ C) := {} instance functor_category_has_colimits [has_colimits C] : has_colimits (K ⥤ C) := {} instance evaluation_preserves_limits_of_shape [has_limits_of_shape J C] (k : K) : preserves_limits_of_shape J ((evaluation K C).obj k) := { preserves_limit := λ F, preserves_limit_of_preserves_limit_cone (combined_is_limit _ _) $ is_limit.of_iso_limit (limit.is_limit _) (evaluate_combined_cones F _ k).symm } /-- If `F : J ⥤ K ⥤ C` is a functor into a functor category which has a limit, then the evaluation of that limit at `k` is the limit of the evaluations of `F.obj j` at `k`. -/ def limit_obj_iso_limit_comp_evaluation [has_limits_of_shape J C] (F : J ⥤ K ⥤ C) (k : K) : (limit F).obj k ≅ limit (F ⋙ ((evaluation K C).obj k)) := preserves_limit_iso ((evaluation K C).obj k) F @[simp, reassoc] lemma limit_obj_iso_limit_comp_evaluation_hom_π [has_limits_of_shape J C] (F : J ⥤ (K ⥤ C)) (j : J) (k : K) : (limit_obj_iso_limit_comp_evaluation F k).hom ≫ limit.π (F ⋙ ((evaluation K C).obj k)) j = (limit.π F j).app k := begin dsimp [limit_obj_iso_limit_comp_evaluation], simp, end @[simp, reassoc] lemma limit_obj_iso_limit_comp_evaluation_inv_π_app [has_limits_of_shape J C] (F : J ⥤ (K ⥤ C)) (j : J) (k : K): (limit_obj_iso_limit_comp_evaluation F k).inv ≫ (limit.π F j).app k = limit.π (F ⋙ ((evaluation K C).obj k)) j := begin dsimp [limit_obj_iso_limit_comp_evaluation], rw iso.inv_comp_eq, simp, end @[ext] lemma limit_obj_ext {H : J ⥤ K ⥤ C} [has_limits_of_shape J C] {k : K} {W : C} {f g : W ⟶ (limit H).obj k} (w : ∀ j, f ≫ (limits.limit.π H j).app k = g ≫ (limits.limit.π H j).app k) : f = g := begin apply (cancel_mono (limit_obj_iso_limit_comp_evaluation H k).hom).1, ext, simpa using w j, end instance evaluation_preserves_colimits_of_shape [has_colimits_of_shape J C] (k : K) : preserves_colimits_of_shape J ((evaluation K C).obj k) := { preserves_colimit := λ F, preserves_colimit_of_preserves_colimit_cocone (combined_is_colimit _ _) $ is_colimit.of_iso_colimit (colimit.is_colimit _) (evaluate_combined_cocones F _ k).symm } /-- If `F : J ⥤ K ⥤ C` is a functor into a functor category which has a colimit, then the evaluation of that colimit at `k` is the colimit of the evaluations of `F.obj j` at `k`. -/ def colimit_obj_iso_colimit_comp_evaluation [has_colimits_of_shape J C] (F : J ⥤ K ⥤ C) (k : K) : (colimit F).obj k ≅ colimit (F ⋙ ((evaluation K C).obj k)) := preserves_colimit_iso ((evaluation K C).obj k) F @[simp, reassoc] lemma colimit_obj_iso_colimit_comp_evaluation_ι_inv [has_colimits_of_shape J C] (F : J ⥤ (K ⥤ C)) (j : J) (k : K) : colimit.ι (F ⋙ ((evaluation K C).obj k)) j ≫ (colimit_obj_iso_colimit_comp_evaluation F k).inv = (colimit.ι F j).app k := begin dsimp [colimit_obj_iso_colimit_comp_evaluation], simp, end @[simp, reassoc] lemma colimit_obj_iso_colimit_comp_evaluation_ι_app_hom [has_colimits_of_shape J C] (F : J ⥤ (K ⥤ C)) (j : J) (k : K) : (colimit.ι F j).app k ≫ (colimit_obj_iso_colimit_comp_evaluation F k).hom = colimit.ι (F ⋙ ((evaluation K C).obj k)) j := begin dsimp [colimit_obj_iso_colimit_comp_evaluation], rw ←iso.eq_comp_inv, simp, end @[ext] lemma colimit_obj_ext {H : J ⥤ K ⥤ C} [has_colimits_of_shape J C] {k : K} {W : C} {f g : (colimit H).obj k ⟶ W} (w : ∀ j, (colimit.ι H j).app k ≫ f = (colimit.ι H j).app k ≫ g) : f = g := begin apply (cancel_epi (colimit_obj_iso_colimit_comp_evaluation H k).inv).1, ext, simpa using w j, end instance evaluation_preserves_limits [has_limits C] (k : K) : preserves_limits ((evaluation K C).obj k) := { preserves_limits_of_shape := λ J 𝒥, by resetI; apply_instance } /-- `F : D ⥤ K ⥤ C` preserves the limit of some `G : J ⥤ D` if it does for each `k : K`. -/ def preserves_limit_of_evaluation (F : D ⥤ K ⥤ C) (G : J ⥤ D) (H : Π (k : K), preserves_limit G (F ⋙ (evaluation K C).obj k : D ⥤ C)) : preserves_limit G F := ⟨λ c hc, begin apply evaluation_jointly_reflects_limits, intro X, haveI := H X, change is_limit ((F ⋙ (evaluation K C).obj X).map_cone c), exact preserves_limit.preserves hc, end⟩ /-- `F : D ⥤ K ⥤ C` preserves limits of shape `J` if it does for each `k : K`. -/ def preserves_limits_of_shape_of_evaluation (F : D ⥤ K ⥤ C) (J : Type v) [small_category J] (H : Π (k : K), preserves_limits_of_shape J (F ⋙ (evaluation K C).obj k)) : preserves_limits_of_shape J F := ⟨λ G, preserves_limit_of_evaluation F G (λ k, preserves_limits_of_shape.preserves_limit)⟩ /-- `F : D ⥤ K ⥤ C` preserves all limits if it does for each `k : K`. -/ def preserves_limits_of_evaluation (F : D ⥤ K ⥤ C) (H : Π (k : K), preserves_limits (F ⋙ (evaluation K C).obj k)) : preserves_limits F := ⟨λ L hL, by exactI preserves_limits_of_shape_of_evaluation F L (λ k, preserves_limits.preserves_limits_of_shape)⟩ instance evaluation_preserves_colimits [has_colimits C] (k : K) : preserves_colimits ((evaluation K C).obj k) := { preserves_colimits_of_shape := λ J 𝒥, by resetI; apply_instance } /-- `F : D ⥤ K ⥤ C` preserves the colimit of some `G : J ⥤ D` if it does for each `k : K`. -/ def preserves_colimit_of_evaluation (F : D ⥤ K ⥤ C) (G : J ⥤ D) (H : Π (k), preserves_colimit G (F ⋙ (evaluation K C).obj k)) : preserves_colimit G F := ⟨λ c hc, begin apply evaluation_jointly_reflects_colimits, intro X, haveI := H X, change is_colimit ((F ⋙ (evaluation K C).obj X).map_cocone c), exact preserves_colimit.preserves hc, end⟩ /-- `F : D ⥤ K ⥤ C` preserves all colimits of shape `J` if it does for each `k : K`. -/ def preserves_colimits_of_shape_of_evaluation (F : D ⥤ K ⥤ C) (J : Type v) [small_category J] (H : Π (k : K), preserves_colimits_of_shape J (F ⋙ (evaluation K C).obj k)) : preserves_colimits_of_shape J F := ⟨λ G, preserves_colimit_of_evaluation F G (λ k, preserves_colimits_of_shape.preserves_colimit)⟩ /-- `F : D ⥤ K ⥤ C` preserves all colimits if it does for each `k : K`. -/ def preserves_colimits_of_evaluation (F : D ⥤ K ⥤ C) (H : Π (k : K), preserves_colimits (F ⋙ (evaluation K C).obj k)) : preserves_colimits F := ⟨λ L hL, by exactI preserves_colimits_of_shape_of_evaluation F L (λ k, preserves_colimits.preserves_colimits_of_shape)⟩ open category_theory.prod /-- For a functor `G : J ⥤ K ⥤ C`, its limit `K ⥤ C` is given by `(G' : K ⥤ J ⥤ C) ⋙ lim`. Note that this does not require `K` to be small. -/ @[simps] def limit_iso_swap_comp_lim [has_limits_of_shape J C] (G : J ⥤ K ⥤ C) [has_limit G] : limit G ≅ curry.obj (swap K J ⋙ uncurry.obj G) ⋙ lim := nat_iso.of_components (λ Y, limit_obj_iso_limit_comp_evaluation G Y ≪≫ (lim.map_iso (eq_to_iso (by { apply functor.hext, { intro X, simp }, { intros X₁ X₂ f, dsimp only [swap], simp }})))) begin intros Y₁ Y₂ f, ext1 x, dsimp only [swap], simp only [limit_obj_iso_limit_comp_evaluation_hom_π_assoc, category.comp_id, limit_obj_iso_limit_comp_evaluation_hom_π, eq_to_iso.hom, curry.obj_map_app, nat_trans.naturality, category.id_comp, eq_to_hom_refl, functor.comp_map, eq_to_hom_app, lim_map_π_assoc, lim_map_π, category.assoc, uncurry.obj_map, lim_map_eq_lim_map, iso.trans_hom, nat_trans.id_app, category_theory.functor.map_id, functor.map_iso_hom], erw category.id_comp, end /-- For a functor `G : J ⥤ K ⥤ C`, its colimit `K ⥤ C` is given by `(G' : K ⥤ J ⥤ C) ⋙ colim`. Note that this does not require `K` to be small. -/ @[simps] def colimit_iso_swap_comp_colim [has_colimits_of_shape J C] (G : J ⥤ K ⥤ C) [has_colimit G] : colimit G ≅ curry.obj (swap K J ⋙ uncurry.obj G) ⋙ colim := nat_iso.of_components (λ Y, colimit_obj_iso_colimit_comp_evaluation G Y ≪≫ (colim.map_iso (eq_to_iso (by { apply functor.hext, { intro X, simp }, { intros X Y f, dsimp only [swap], simp, } })))) begin intros Y₁ Y₂ f, ext1 x, rw ← (colimit.ι G x).naturality_assoc f, dsimp only [swap], simp only [eq_to_iso.hom, colimit_obj_iso_colimit_comp_evaluation_ι_app_hom_assoc, curry.obj_map_app, colimit.ι_map, category.id_comp, eq_to_hom_refl, iso.trans_hom, functor.comp_map, eq_to_hom_app, colimit.ι_map_assoc, functor.map_iso_hom, category.assoc, uncurry.obj_map, nat_trans.id_app, category_theory.functor.map_id], erw category.id_comp, end end category_theory.limits
60dec262ca4c8e4e616ef812426251c092406b33
30b012bb72d640ec30c8fdd4c45fdfa67beb012c
/ring_theory/noetherian.lean
fbea7b0a3b8dc809fa908567f09b33171e1786d7
[ "Apache-2.0" ]
permissive
kckennylau/mathlib
21fb810b701b10d6606d9002a4004f7672262e83
47b3477e20ffb5a06588dd3abb01fe0fe3205646
refs/heads/master
1,634,976,409,281
1,542,042,832,000
1,542,319,733,000
109,560,458
0
0
Apache-2.0
1,542,369,208,000
1,509,867,494,000
Lean
UTF-8
Lean
false
false
4,310
lean
/- Copyright (c) 2018 Mario Carneiro and Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kevin Buzzard -/ import algebra.module import order.order_iso import data.fintype data.polynomial import linear_algebra.lc import tactic.tidy import ring_theory.ideals open set lattice namespace submodule variables {α : Type*} {β : Type*} [ring α] [add_comm_group β] [module α β] def fg (s : submodule α β) : Prop := ∃ t : finset β, submodule.span ↑t = s theorem fg_def {s : submodule α β} : s.fg ↔ ∃ t : set β, finite t ∧ span t = s := ⟨λ ⟨t, h⟩, ⟨_, finset.finite_to_set t, h⟩, begin rintro ⟨t', h, rfl⟩, rcases finite.exists_finset_coe h with ⟨t, rfl⟩, exact ⟨t, rfl⟩ end⟩ end submodule def is_noetherian (α β) [ring α] [add_comm_group β] [module α β] : Prop := ∀ (s : submodule α β), s.fg theorem is_noetherian_iff_well_founded {α β} [ring α] [add_comm_group β] [module α β] : is_noetherian α β ↔ well_founded ((>) : submodule α β → submodule α β → Prop) := ⟨λ h, begin apply order_embedding.well_founded_iff_no_descending_seq.2, swap, { apply is_strict_order.swap }, rintro ⟨⟨N, hN⟩⟩, let M := ⨆ n, N n, rcases submodule.fg_def.1 (h M) with ⟨t, h₁, h₂⟩, have hN' : ∀ {a b}, a ≤ b → N a ≤ N b := λ a b, (le_iff_le_of_strict_mono N (λ _ _, hN.1)).2, have : t ⊆ ⋃ i, (N i : set β), { rw [← submodule.Union_coe_of_directed _ N _], { show t ⊆ M, rw ← h₂, apply submodule.subset_span }, { apply_instance }, { exact λ i j, ⟨max i j, hN' (le_max_left _ _), hN' (le_max_right _ _)⟩ } }, simp [subset_def] at this, choose f hf using show ∀ x : t, ∃ (i : ℕ), x.1 ∈ N i, { simpa }, cases h₁ with h₁, let A := finset.sup (@finset.univ t h₁) f, have : M ≤ N A, { rw ← h₂, apply submodule.span_le.2, exact λ x h, hN' (finset.le_sup (@finset.mem_univ t h₁ _)) (hf ⟨x, h⟩) }, exact not_le_of_lt (hN.1 (nat.lt_succ_self A)) (le_trans (le_supr _ _) this) end, begin assume h N, suffices : ∀ M ≤ N, ∃ s, finite s ∧ M ⊔ submodule.span s = N, { rcases this ⊥ bot_le with ⟨s, hs, e⟩, exact submodule.fg_def.2 ⟨s, hs, by simpa using e⟩ }, refine λ M, h.induction M _, intros M IH MN, letI := classical.dec, by_cases h : ∀ x, x ∈ N → x ∈ M, { cases le_antisymm MN h, exact ⟨∅, by simp⟩ }, { simp [not_forall] at h, rcases h with ⟨x, h, h₂⟩, have : ¬M ⊔ submodule.span {x} ≤ M, { intro hn, apply h₂, have := le_trans le_sup_right hn, exact submodule.span_le.1 this (mem_singleton x) }, rcases IH (M ⊔ submodule.span {x}) ⟨@le_sup_left _ _ M _, this⟩ (sup_le MN (submodule.span_le.2 (by simpa))) with ⟨s, hs, hs₂⟩, refine ⟨insert x s, finite_insert _ hs, _⟩, rw [← hs₂, sup_assoc, ← submodule.span_union], simp } end⟩ def is_noetherian_ring (α) [ring α] : Prop := is_noetherian α α theorem ring.is_noetherian_of_fintype (R M) [ring R] [add_comm_group M] [module R M] [fintype M] : is_noetherian R M := by letI := classical.dec; exact assume s, ⟨to_finset s, by rw [finset.coe_to_finset', submodule.span_eq]⟩ theorem ring.is_noetherian_of_zero_eq_one {R} [ring R] (h01 : (0 : R) = 1) : is_noetherian_ring R := by haveI := subsingleton_of_zero_eq_one R h01; haveI := fintype.of_subsingleton (0:R); exact ring.is_noetherian_of_fintype R R theorem is_noetherian_of_submodule_of_noetherian (R M) [ring R] [add_comm_group M] [module R M] (N : submodule R M) (h : is_noetherian R M) : is_noetherian R N := begin rw is_noetherian_iff_well_founded at h ⊢, convert order_embedding.well_founded (order_embedding.rsymm (submodule.map_subtype.lt_order_embedding N)) h end theorem is_noetherian_of_quotient_of_noetherian (R) [ring R] (M) [add_comm_group M] [module R M] (N : submodule R M) (h : is_noetherian R M) : is_noetherian R N.quotient := begin rw is_noetherian_iff_well_founded at h ⊢, convert order_embedding.well_founded (order_embedding.rsymm (submodule.comap_mkq.lt_order_embedding N)) h end
4534ee46d6fbe4147b22d7130bed00dfaa97e3a5
90edd5cdcf93124fe15627f7304069fdce3442dd
/stage0/src/Lean/Elab/Deriving/FromToJson.lean
a986383e3bb795bc959e862a04a441f016a62981
[ "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
7,449
lean
/- Copyright (c) 2020 Sebastian Ullrich. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich, Dany Fabian -/ import Lean.Meta.Transform import Lean.Elab.Deriving.Basic import Lean.Elab.Deriving.Util import Lean.Data.Json.FromToJson namespace Lean.Elab.Deriving.FromToJson open Lean.Elab.Command open Lean.Json open Lean.Parser.Term open Lean.Meta def mkJsonField (n : Name) : Bool × Syntax := let s := n.toString let s₁ := s.dropRightWhile (· == '?') (s != s₁, Syntax.mkStrLit s₁) def mkToJsonInstanceHandler (declNames : Array Name) : CommandElabM Bool := do if declNames.size == 1 then if (← isStructure (← getEnv) declNames[0]) then let cmds ← liftTermElabM none <| do let ctx ← mkContext "toJson" declNames[0] let header ← mkHeader ctx ``ToJson 1 ctx.typeInfos[0] let fields := getStructureFieldsFlattened (← getEnv) declNames[0] (includeSubobjectFields := false) let fields : Array Syntax ← fields.mapM fun field => do let (isOptField, nm) ← mkJsonField field if isOptField then `(opt $nm $(mkIdent <| header.targetNames[0] ++ field)) else `([($nm, toJson $(mkIdent <| header.targetNames[0] ++ field))]) let cmd ← `(private def $(mkIdent ctx.auxFunNames[0]):ident $header.binders:explicitBinder* := mkObj <| List.join [$fields,*]) return #[cmd] ++ (← mkInstanceCmds ctx ``ToJson declNames) cmds.forM elabCommand return true else let indVal ← getConstInfoInduct declNames[0] let cmds ← liftTermElabM none <| do let ctx ← mkContext "toJson" declNames[0] let header ← mkHeader ctx ``ToJson 1 ctx.typeInfos[0] let discrs ← mkDiscrs header indVal let alts ← mkAlts indVal fun ctor args userNames => match args, userNames with | #[], _ => `(toJson $(quote ctor.name.getString!)) | #[x], none => `(mkObj [($(quote ctor.name.getString!), toJson $x)]) | xs, none => do let xs ← xs.mapM fun x => `(toJson $x) `(mkObj [($(quote ctor.name.getString!), toJson #[$[$xs:term],*])]) | xs, some userNames => do let xs ← xs.mapIdxM fun idx x => `(($(quote userNames[idx].getString!), toJson $x)) `(mkObj [($(quote ctor.name.getString!), mkObj [$[$xs:term],*])]) let auxCmd ← `(match $[$discrs],* with $alts:matchAlt*) let auxCmd ← `(private def $(mkIdent ctx.auxFunNames[0]):ident $header.binders:explicitBinder* := $auxCmd) return #[auxCmd] ++ (← mkInstanceCmds ctx ``ToJson declNames) cmds.forM elabCommand return true else return false where mkAlts (indVal : InductiveVal) (rhs : ConstructorVal → Array Syntax → (Option $ Array Name) → TermElabM Syntax) : TermElabM (Array Syntax) := do indVal.ctors.toArray.mapM fun ctor => do let ctorInfo ← getConstInfoCtor ctor forallTelescopeReducing ctorInfo.type fun xs type => do let mut patterns := #[] -- add `_` pattern for indices for i in [:indVal.numIndices] do patterns := patterns.push (← `(_)) let mut ctorArgs := #[] -- add `_` for inductive parameters, they are inaccessible for i in [:indVal.numParams] do ctorArgs := ctorArgs.push (← `(_)) let mut identNames := #[] let mut userNames := #[] for i in [:ctorInfo.numFields] do let x := xs[indVal.numParams + i] let localDecl ← getLocalDecl x.fvarId! if !localDecl.userName.hasMacroScopes then userNames := userNames.push localDecl.userName let a := mkIdent (← mkFreshUserName `a) identNames := identNames.push a ctorArgs := ctorArgs.push a patterns := patterns.push (← `(@$(mkIdent ctorInfo.name):ident $ctorArgs:term*)) let rhs ← rhs ctorInfo identNames (if userNames.size == identNames.size then some userNames else none) `(matchAltExpr| | $[$patterns:term],* => $rhs:term) def mkFromJsonInstanceHandler (declNames : Array Name) : CommandElabM Bool := do if declNames.size == 1 then if (← isStructure (← getEnv) declNames[0]) then let cmds ← liftTermElabM none <| do let ctx ← mkContext "fromJson" declNames[0] let header ← mkHeader ctx ``FromJson 0 ctx.typeInfos[0] let fields := getStructureFieldsFlattened (← getEnv) declNames[0] (includeSubobjectFields := false) let jsonFields := fields.map (Prod.snd ∘ mkJsonField) let fields := fields.map mkIdent let cmd ← `(private def $(mkIdent ctx.auxFunNames[0]):ident $header.binders:explicitBinder* (j : Json) : Except String $(← mkInductiveApp ctx.typeInfos[0] header.argNames) := do $[let $fields:ident ← getObjValAs? j _ $jsonFields]* return { $[$fields:ident := $(id fields)]* }) return #[cmd] ++ (← mkInstanceCmds ctx ``FromJson declNames) cmds.forM elabCommand return true else let indVal ← getConstInfoInduct declNames[0] let cmds ← liftTermElabM none <| do let ctx ← mkContext "fromJson" declNames[0] let header ← mkHeader ctx ``FromJson 0 ctx.typeInfos[0] let discrs ← mkDiscrs header indVal let alts ← mkAlts indVal let matchCmd ← alts.foldrM (fun xs x => `($xs <|> $x)) (←`(Except.error "no inductive constructor matched")) let cmd ← `(private def $(mkIdent ctx.auxFunNames[0]):ident $header.binders:explicitBinder* (json : Json) : Except String $(← mkInductiveApp ctx.typeInfos[0] header.argNames) := $matchCmd ) return #[cmd] ++ (← mkInstanceCmds ctx ``FromJson declNames) cmds.forM elabCommand return true else return false where mkAlts (indVal : InductiveVal) : TermElabM (Array Syntax) := do let alts ← indVal.ctors.toArray.mapM fun ctor => do let ctorInfo ← getConstInfoCtor ctor forallTelescopeReducing ctorInfo.type fun xs type => do let mut identNames := #[] let mut userNames := #[] for i in [:ctorInfo.numFields] do let x := xs[indVal.numParams + i] let localDecl ← getLocalDecl x.fvarId! if !localDecl.userName.hasMacroScopes then userNames := userNames.push localDecl.userName let xTy ← inferType x let a := mkIdent (← mkFreshUserName `a) identNames := identNames.push a let jsonAccess ← identNames.mapIdxM (fun idx _ => `(jsons[$(quote idx.val)])) let userNamesOpt ← if identNames.size == userNames.size then `(some #[$[$(userNames.map quote):ident],*]) else `(none) let stx ← `((Json.parseTagged json $(quote ctor.getString!) $(quote ctorInfo.numFields) $(quote userNamesOpt)).bind (fun jsons => do $[let $identNames:ident ← fromJson? $jsonAccess]* return $(mkIdent ctor):ident $identNames*)) (stx, ctorInfo.numFields) -- the smaller cases, especially the ones without fields are likely faster let alts := alts.qsort (fun (_, x) (_, y) => x < y) alts.map Prod.fst builtin_initialize registerBuiltinDerivingHandler ``ToJson mkToJsonInstanceHandler registerBuiltinDerivingHandler ``FromJson mkFromJsonInstanceHandler end Lean.Elab.Deriving.FromToJson
9f90e65b5ead3936640c823aa9a09719e0517b11
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/analysis/normed_space/hahn_banach.lean
734016fc8be78462cd01b8ca8d8ddd050f7021c8
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
1,401
lean
/- Copyright (c) 2020 Yury Kudryashov All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import analysis.normed_space.operator_norm analysis.convex.cone /-! # Hahn-Banach theorem In this file we prove a version of Hahn-Banach theorem for continuous linear functions on normed spaces. ## TODO Prove some corollaries -/ variables {E : Type*} [normed_group E] [normed_space ℝ E] /-- Hahn-Banach theorem for continuous linear functions. -/ theorem exists_extension_norm_eq (p : subspace ℝ E) (f : p →L[ℝ] ℝ) : ∃ g : E →L[ℝ] ℝ, (∀ x : p, g x = f x) ∧ ∥g∥ = ∥f∥ := begin rcases exists_extension_of_le_sublinear ⟨p, f⟩ (λ x, ∥f∥ * ∥x∥) (λ c hc x, by simp only [norm_smul c x, real.norm_eq_abs, abs_of_pos hc, mul_left_comm]) (λ x y, _) (λ x, le_trans (le_abs_self _) (f.le_op_norm _)) with ⟨g, g_eq, g_le⟩, set g' := g.mk_continuous (∥f∥) (λ x, abs_le.2 ⟨neg_le.1 $ g.map_neg x ▸ norm_neg x ▸ g_le (-x), g_le x⟩), { refine ⟨g', g_eq, _⟩, { apply le_antisymm (g.mk_continuous_norm_le (norm_nonneg f) _), refine f.op_norm_le_bound (norm_nonneg _) (λ x, _), dsimp at g_eq, rw ← g_eq, apply g'.le_op_norm } }, { simp only [← mul_add], exact mul_le_mul_of_nonneg_left (norm_add_le x y) (norm_nonneg f) } end
e7a5ff103ac75d1fbd3367b93c22dd81771d731f
367134ba5a65885e863bdc4507601606690974c1
/archive/100-theorems-list/70_perfect_numbers.lean
cf5b7a059c17d35db71982ffefad133872b321f6
[ "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
4,927
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Aaron Anderson. -/ import number_theory.arithmetic_function import number_theory.lucas_lehmer import algebra.geom_sum import ring_theory.multiplicity /-! # Perfect Numbers This file proves Theorem 70 from the [100 Theorems List](https://www.cs.ru.nl/~freek/100/). The theorem characterizes even perfect numbers. Euclid proved that if `2 ^ (k + 1) - 1` is prime (these primes are known as Mersenne primes), then `2 ^ k * 2 ^ (k + 1) - 1` is perfect. Euler proved the converse, that if `n` is even and perfect, then there exists `k` such that `n = 2 ^ k * 2 ^ (k + 1) - 1` and `2 ^ (k + 1) - 1` is prime. ## References https://en.wikipedia.org/wiki/Euclid%E2%80%93Euler_theorem -/ lemma odd_mersenne_succ (k : ℕ) : ¬ 2 ∣ mersenne (k + 1) := by simp [← even_iff_two_dvd, ← nat.even_succ, nat.succ_eq_add_one] with parity_simps namespace nat open arithmetic_function finset open_locale arithmetic_function lemma sigma_two_pow_eq_mersenne_succ (k : ℕ) : σ 1 (2 ^ k) = mersenne (k + 1) := by simpa [mersenne, prime_two, ← geom_sum_mul_add 1 (k+1)] /-- Euclid's theorem that Mersenne primes induce perfect numbers -/ theorem perfect_two_pow_mul_mersenne_of_prime (k : ℕ) (pr : (mersenne (k + 1)).prime) : perfect ((2 ^ k) * mersenne (k + 1)) := begin rw [perfect_iff_sum_divisors_eq_two_mul, ← mul_assoc, ← pow_succ, ← sigma_one_apply, mul_comm, is_multiplicative_sigma.map_mul_of_coprime (nat.prime_two.coprime_pow_of_not_dvd (odd_mersenne_succ _)), sigma_two_pow_eq_mersenne_succ], { simp [pr, nat.prime_two] }, { apply mul_pos (pow_pos _ k) (mersenne_pos (nat.succ_pos k)), norm_num } end lemma ne_zero_of_prime_mersenne (k : ℕ) (pr : (mersenne (k + 1)).prime) : k ≠ 0 := begin rintro rfl, simpa [mersenne, not_prime_one] using pr, end theorem even_two_pow_mul_mersenne_of_prime (k : ℕ) (pr : (mersenne (k + 1)).prime) : even ((2 ^ k) * mersenne (k + 1)) := by simp [ne_zero_of_prime_mersenne k pr] with parity_simps lemma eq_pow_two_mul_odd {n : ℕ} (hpos : 0 < n) : ∃ (k m : ℕ), n = 2 ^ k * m ∧ ¬ even m := begin have h := (multiplicity.finite_nat_iff.2 ⟨nat.prime_two.ne_one, hpos⟩), cases multiplicity.pow_multiplicity_dvd h with m hm, use [(multiplicity 2 n).get h, m], refine ⟨hm, _⟩, rw even_iff_two_dvd, have hg := multiplicity.is_greatest' h (nat.lt_succ_self _), contrapose! hg, rcases hg with ⟨k, rfl⟩, apply dvd.intro k, rw [pow_succ', mul_assoc, ← hm], end /-- Euler's theorem that even perfect numbers can be factored as a power of two times a Mersenne prime. -/ theorem eq_two_pow_mul_prime_mersenne_of_even_perfect {n : ℕ} (ev : even n) (perf : perfect n) : ∃ (k : ℕ), prime (mersenne (k + 1)) ∧ n = 2 ^ k * mersenne (k + 1) := begin have hpos := perf.2, rcases eq_pow_two_mul_odd hpos with ⟨k, m, rfl, hm⟩, use k, rw [perfect_iff_sum_divisors_eq_two_mul hpos, ← sigma_one_apply, is_multiplicative_sigma.map_mul_of_coprime (nat.prime_two.coprime_pow_of_not_dvd hm).symm, sigma_two_pow_eq_mersenne_succ, ← mul_assoc, ← pow_succ] at perf, rcases nat.coprime.dvd_of_dvd_mul_left (nat.prime_two.coprime_pow_of_not_dvd (odd_mersenne_succ _)) (dvd.intro _ perf) with ⟨j, rfl⟩, rw [← mul_assoc, mul_comm _ (mersenne _), mul_assoc] at perf, have h := mul_left_cancel' (ne_of_gt (mersenne_pos (nat.succ_pos _))) perf, rw [sigma_one_apply, sum_divisors_eq_sum_proper_divisors_add_self, ← succ_mersenne, add_mul, one_mul, add_comm] at h, have hj := add_left_cancel h, cases sum_proper_divisors_dvd (by { rw hj, apply dvd.intro_left (mersenne (k + 1)) rfl }), { have j1 : j = 1 := eq.trans hj.symm h_1, rw [j1, mul_one, sum_proper_divisors_eq_one_iff_prime] at h_1, simp [h_1, j1] }, { have jcon := eq.trans hj.symm h_1, rw [← one_mul j, ← mul_assoc, mul_one] at jcon, have jcon2 := mul_right_cancel' _ jcon, { exfalso, cases k, { apply hm, rw [← jcon2, pow_zero, one_mul, one_mul] at ev, rw [← jcon2, one_mul], exact ev }, apply ne_of_lt _ jcon2, rw [mersenne, ← nat.pred_eq_sub_one, lt_pred_iff, ← pow_one (nat.succ 1)], apply pow_lt_pow (nat.lt_succ_self 1) (nat.succ_lt_succ (nat.succ_pos k)) }, contrapose! hm, simp [hm] } end /-- The Euclid-Euler theorem characterizing even perfect numbers -/ theorem even_and_perfect_iff {n : ℕ} : (even n ∧ perfect n) ↔ ∃ (k : ℕ), prime (mersenne (k + 1)) ∧ n = 2 ^ k * mersenne (k + 1) := begin split, { rintro ⟨ev, perf⟩, exact eq_two_pow_mul_prime_mersenne_of_even_perfect ev perf }, { rintro ⟨k, pr, rfl⟩, exact ⟨even_two_pow_mul_mersenne_of_prime k pr, perfect_two_pow_mul_mersenne_of_prime k pr⟩ } end end nat
1be0ad258628e8dab5a71065e9475219cfd4f0b9
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/field_theory/abel_ruffini.lean
8c54b0d3de584efdad500bd20177915ed3b00f88
[ "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
17,167
lean
/- Copyright (c) 2020 Thomas Browning and Patrick Lutz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning, Patrick Lutz -/ import group_theory.solvable import field_theory.polynomial_galois_group import ring_theory.roots_of_unity.basic /-! # The Abel-Ruffini Theorem > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file proves one direction of the Abel-Ruffini theorem, namely that if an element is solvable by radicals, then its minimal polynomial has solvable Galois group. ## Main definitions * `solvable_by_rad F E` : the intermediate field of solvable-by-radicals elements ## Main results * the Abel-Ruffini Theorem `solvable_by_rad.is_solvable'` : An irreducible polynomial with a root that is solvable by radicals has a solvable Galois group. -/ noncomputable theory open_locale classical polynomial open polynomial intermediate_field section abel_ruffini variables {F : Type*} [field F] {E : Type*} [field E] [algebra F E] lemma gal_zero_is_solvable : is_solvable (0 : F[X]).gal := by apply_instance lemma gal_one_is_solvable : is_solvable (1 : F[X]).gal := by apply_instance lemma gal_C_is_solvable (x : F) : is_solvable (C x).gal := by apply_instance lemma gal_X_is_solvable : is_solvable (X : F[X]).gal := by apply_instance lemma gal_X_sub_C_is_solvable (x : F) : is_solvable (X - C x).gal := by apply_instance lemma gal_X_pow_is_solvable (n : ℕ) : is_solvable (X ^ n : F[X]).gal := by apply_instance lemma gal_mul_is_solvable {p q : F[X]} (hp : is_solvable p.gal) (hq : is_solvable q.gal) : is_solvable (p * q).gal := solvable_of_solvable_injective (gal.restrict_prod_injective p q) lemma gal_prod_is_solvable {s : multiset F[X]} (hs : ∀ p ∈ s, is_solvable (gal p)) : is_solvable s.prod.gal := begin apply multiset.induction_on' s, { exact gal_one_is_solvable }, { intros p t hps hts ht, rw [multiset.insert_eq_cons, multiset.prod_cons], exact gal_mul_is_solvable (hs p hps) ht }, end lemma gal_is_solvable_of_splits {p q : F[X]} (hpq : fact (p.splits (algebra_map F q.splitting_field))) (hq : is_solvable q.gal) : is_solvable p.gal := begin haveI : is_solvable (q.splitting_field ≃ₐ[F] q.splitting_field) := hq, exact solvable_of_surjective (alg_equiv.restrict_normal_hom_surjective q.splitting_field), end lemma gal_is_solvable_tower (p q : F[X]) (hpq : p.splits (algebra_map F q.splitting_field)) (hp : is_solvable p.gal) (hq : is_solvable (q.map (algebra_map F p.splitting_field)).gal) : is_solvable q.gal := begin let K := p.splitting_field, let L := q.splitting_field, haveI : fact (p.splits (algebra_map F L)) := ⟨hpq⟩, let ϕ : (L ≃ₐ[K] L) ≃* (q.map (algebra_map F K)).gal := (is_splitting_field.alg_equiv L (q.map (algebra_map F K))).aut_congr, have ϕ_inj : function.injective ϕ.to_monoid_hom := ϕ.injective, haveI : is_solvable (K ≃ₐ[F] K) := hp, haveI : is_solvable (L ≃ₐ[K] L) := solvable_of_solvable_injective ϕ_inj, exact is_solvable_of_is_scalar_tower F p.splitting_field q.splitting_field, end section gal_X_pow_sub_C lemma gal_X_pow_sub_one_is_solvable (n : ℕ) : is_solvable (X ^ n - 1 : F[X]).gal := begin by_cases hn : n = 0, { rw [hn, pow_zero, sub_self], exact gal_zero_is_solvable }, have hn' : 0 < n := pos_iff_ne_zero.mpr hn, have hn'' : (X ^ n - 1 : F[X]) ≠ 0 := X_pow_sub_C_ne_zero hn' 1, apply is_solvable_of_comm, intros σ τ, ext a ha, simp only [mem_root_set_of_ne hn'', map_sub, aeval_X_pow, aeval_one, sub_eq_zero] at ha, have key : ∀ σ : (X ^ n - 1 : F[X]).gal, ∃ m : ℕ, σ a = a ^ m, { intro σ, lift n to ℕ+ using hn', exact map_root_of_unity_eq_pow_self σ.to_alg_hom (roots_of_unity.mk_of_pow_eq a ha) }, obtain ⟨c, hc⟩ := key σ, obtain ⟨d, hd⟩ := key τ, rw [σ.mul_apply, τ.mul_apply, hc, τ.map_pow, hd, σ.map_pow, hc, ←pow_mul, pow_mul'], end lemma gal_X_pow_sub_C_is_solvable_aux (n : ℕ) (a : F) (h : (X ^ n - 1 : F[X]).splits (ring_hom.id F)) : is_solvable (X ^ n - C a).gal := begin by_cases ha : a = 0, { rw [ha, C_0, sub_zero], exact gal_X_pow_is_solvable n }, have ha' : algebra_map F (X ^ n - C a).splitting_field a ≠ 0 := mt ((injective_iff_map_eq_zero _).mp (ring_hom.injective _) a) ha, by_cases hn : n = 0, { rw [hn, pow_zero, ←C_1, ←C_sub], exact gal_C_is_solvable (1 - a) }, have hn' : 0 < n := pos_iff_ne_zero.mpr hn, have hn'' : X ^ n - C a ≠ 0 := X_pow_sub_C_ne_zero hn' a, have hn''' : (X ^ n - 1 : F[X]) ≠ 0 := X_pow_sub_C_ne_zero hn' 1, have mem_range : ∀ {c}, c ^ n = 1 → ∃ d, algebra_map F (X ^ n - C a).splitting_field d = c := λ c hc, ring_hom.mem_range.mp (minpoly.mem_range_of_degree_eq_one F c (h.def.resolve_left hn''' (minpoly.irreducible ((splitting_field.normal (X ^ n - C a)).is_integral c)) (minpoly.dvd F c (by rwa [map_id, alg_hom.map_sub, sub_eq_zero, aeval_X_pow, aeval_one])))), apply is_solvable_of_comm, intros σ τ, ext b hb, simp only [mem_root_set_of_ne hn'', map_sub, aeval_X_pow, aeval_C, sub_eq_zero] at hb, have hb' : b ≠ 0, { intro hb', rw [hb', zero_pow hn'] at hb, exact ha' hb.symm }, have key : ∀ σ : (X ^ n - C a).gal, ∃ c, σ b = b * algebra_map F _ c, { intro σ, have key : (σ b / b) ^ n = 1 := by rw [div_pow, ←σ.map_pow, hb, σ.commutes, div_self ha'], obtain ⟨c, hc⟩ := mem_range key, use c, rw [hc, mul_div_cancel' (σ b) hb'] }, obtain ⟨c, hc⟩ := key σ, obtain ⟨d, hd⟩ := key τ, rw [σ.mul_apply, τ.mul_apply, hc, τ.map_mul, τ.commutes, hd, σ.map_mul, σ.commutes, hc], rw [mul_assoc, mul_assoc, mul_right_inj' hb', mul_comm], end lemma splits_X_pow_sub_one_of_X_pow_sub_C {F : Type*} [field F] {E : Type*} [field E] (i : F →+* E) (n : ℕ) {a : F} (ha : a ≠ 0) (h : (X ^ n - C a).splits i) : (X ^ n - 1).splits i := begin have ha' : i a ≠ 0 := mt ((injective_iff_map_eq_zero i).mp (i.injective) a) ha, by_cases hn : n = 0, { rw [hn, pow_zero, sub_self], exact splits_zero i }, have hn' : 0 < n := pos_iff_ne_zero.mpr hn, have hn'' : (X ^ n - C a).degree ≠ 0 := ne_of_eq_of_ne (degree_X_pow_sub_C hn' a) (mt with_bot.coe_eq_coe.mp hn), obtain ⟨b, hb⟩ := exists_root_of_splits i h hn'', rw [eval₂_sub, eval₂_X_pow, eval₂_C, sub_eq_zero] at hb, have hb' : b ≠ 0, { intro hb', rw [hb', zero_pow hn'] at hb, exact ha' hb.symm }, let s := ((X ^ n - C a).map i).roots, have hs : _ = _ * (s.map _).prod := eq_prod_roots_of_splits h, rw [leading_coeff_X_pow_sub_C hn', ring_hom.map_one, C_1, one_mul] at hs, have hs' : s.card = n := (nat_degree_eq_card_roots h).symm.trans nat_degree_X_pow_sub_C, apply @splits_of_exists_multiset F E _ _ i (X ^ n - 1) (s.map (λ c : E, c / b)), rw [leading_coeff_X_pow_sub_one hn', ring_hom.map_one, C_1, one_mul, multiset.map_map], have C_mul_C : (C (i a⁻¹)) * (C (i a)) = 1, { rw [←C_mul, ←i.map_mul, inv_mul_cancel ha, i.map_one, C_1] }, have key1 : (X ^ n - 1).map i = C (i a⁻¹) * ((X ^ n - C a).map i).comp (C b * X), { rw [polynomial.map_sub, polynomial.map_sub, polynomial.map_pow, map_X, map_C, polynomial.map_one, sub_comp, pow_comp, X_comp, C_comp, mul_pow, ←C_pow, hb, mul_sub, ←mul_assoc, C_mul_C, one_mul] }, have key2 : (λ q : E[X], q.comp (C b * X)) ∘ (λ c : E, X - C c) = (λ c : E, C b * (X - C (c / b))), { ext1 c, change (X - C c).comp (C b * X) = C b * (X - C (c / b)), rw [sub_comp, X_comp, C_comp, mul_sub, ←C_mul, mul_div_cancel' c hb'] }, rw [key1, hs, multiset_prod_comp, multiset.map_map, key2, multiset.prod_map_mul, multiset.map_const, multiset.prod_replicate, hs', ←C_pow, hb, ←mul_assoc, C_mul_C, one_mul], all_goals { exact field.to_nontrivial F }, end lemma gal_X_pow_sub_C_is_solvable (n : ℕ) (x : F) : is_solvable (X ^ n - C x).gal := begin by_cases hx : x = 0, { rw [hx, C_0, sub_zero], exact gal_X_pow_is_solvable n }, apply gal_is_solvable_tower (X ^ n - 1) (X ^ n - C x), { exact splits_X_pow_sub_one_of_X_pow_sub_C _ n hx (splitting_field.splits _) }, { exact gal_X_pow_sub_one_is_solvable n }, { rw [polynomial.map_sub, polynomial.map_pow, map_X, map_C], apply gal_X_pow_sub_C_is_solvable_aux, have key := splitting_field.splits (X ^ n - 1 : F[X]), rwa [←splits_id_iff_splits, polynomial.map_sub, polynomial.map_pow, map_X, polynomial.map_one] at key } end end gal_X_pow_sub_C variables (F) /-- Inductive definition of solvable by radicals -/ inductive is_solvable_by_rad : E → Prop | base (α : F) : is_solvable_by_rad (algebra_map F E α) | add (α β : E) : is_solvable_by_rad α → is_solvable_by_rad β → is_solvable_by_rad (α + β) | neg (α : E) : is_solvable_by_rad α → is_solvable_by_rad (-α) | mul (α β : E) : is_solvable_by_rad α → is_solvable_by_rad β → is_solvable_by_rad (α * β) | inv (α : E) : is_solvable_by_rad α → is_solvable_by_rad α⁻¹ | rad (α : E) (n : ℕ) (hn : n ≠ 0) : is_solvable_by_rad (α^n) → is_solvable_by_rad α variables (E) /-- The intermediate field of solvable-by-radicals elements -/ def solvable_by_rad : intermediate_field F E := { carrier := is_solvable_by_rad F, zero_mem' := by { convert is_solvable_by_rad.base (0 : F), rw ring_hom.map_zero }, add_mem' := is_solvable_by_rad.add, neg_mem' := is_solvable_by_rad.neg, one_mem' := by { convert is_solvable_by_rad.base (1 : F), rw ring_hom.map_one }, mul_mem' := is_solvable_by_rad.mul, inv_mem' := is_solvable_by_rad.inv, algebra_map_mem' := is_solvable_by_rad.base } namespace solvable_by_rad variables {F} {E} {α : E} lemma induction (P : solvable_by_rad F E → Prop) (base : ∀ α : F, P (algebra_map F (solvable_by_rad F E) α)) (add : ∀ α β : solvable_by_rad F E, P α → P β → P (α + β)) (neg : ∀ α : solvable_by_rad F E, P α → P (-α)) (mul : ∀ α β : solvable_by_rad F E, P α → P β → P (α * β)) (inv : ∀ α : solvable_by_rad F E, P α → P α⁻¹) (rad : ∀ α : solvable_by_rad F E, ∀ n : ℕ, n ≠ 0 → P (α^n) → P α) (α : solvable_by_rad F E) : P α := begin revert α, suffices : ∀ (α : E), is_solvable_by_rad F α → (∃ β : solvable_by_rad F E, ↑β = α ∧ P β), { intro α, obtain ⟨α₀, hα₀, Pα⟩ := this α (subtype.mem α), convert Pα, exact subtype.ext hα₀.symm }, apply is_solvable_by_rad.rec, { exact λ α, ⟨algebra_map F (solvable_by_rad F E) α, rfl, base α⟩ }, { intros α β hα hβ Pα Pβ, obtain ⟨⟨α₀, hα₀, Pα⟩, β₀, hβ₀, Pβ⟩ := ⟨Pα, Pβ⟩, exact ⟨α₀ + β₀, by {rw [←hα₀, ←hβ₀], refl }, add α₀ β₀ Pα Pβ⟩ }, { intros α hα Pα, obtain ⟨α₀, hα₀, Pα⟩ := Pα, exact ⟨-α₀, by {rw ←hα₀, refl }, neg α₀ Pα⟩ }, { intros α β hα hβ Pα Pβ, obtain ⟨⟨α₀, hα₀, Pα⟩, β₀, hβ₀, Pβ⟩ := ⟨Pα, Pβ⟩, exact ⟨α₀ * β₀, by {rw [←hα₀, ←hβ₀], refl }, mul α₀ β₀ Pα Pβ⟩ }, { intros α hα Pα, obtain ⟨α₀, hα₀, Pα⟩ := Pα, exact ⟨α₀⁻¹, by {rw ←hα₀, refl }, inv α₀ Pα⟩ }, { intros α n hn hα Pα, obtain ⟨α₀, hα₀, Pα⟩ := Pα, refine ⟨⟨α, is_solvable_by_rad.rad α n hn hα⟩, rfl, rad _ n hn _⟩, convert Pα, exact subtype.ext (eq.trans ((solvable_by_rad F E).coe_pow _ n) hα₀.symm) } end theorem is_integral (α : solvable_by_rad F E) : is_integral F α := begin revert α, apply solvable_by_rad.induction, { exact λ _, is_integral_algebra_map }, { exact λ _ _, is_integral_add }, { exact λ _, is_integral_neg }, { exact λ _ _, is_integral_mul }, { exact λ α hα, subalgebra.inv_mem_of_algebraic (integral_closure F (solvable_by_rad F E)) (show is_algebraic F ↑(⟨α, hα⟩ : integral_closure F (solvable_by_rad F E)), by exact is_algebraic_iff_is_integral.mpr hα) }, { intros α n hn hα, obtain ⟨p, h1, h2⟩ := is_algebraic_iff_is_integral.mpr hα, refine is_algebraic_iff_is_integral.mp ⟨p.comp (X ^ n), ⟨λ h, h1 (leading_coeff_eq_zero.mp _), by rw [aeval_comp, aeval_X_pow, h2]⟩⟩, rwa [←leading_coeff_eq_zero, leading_coeff_comp, leading_coeff_X_pow, one_pow, mul_one] at h, rwa nat_degree_X_pow } end /-- The statement to be proved inductively -/ def P (α : solvable_by_rad F E) : Prop := is_solvable (minpoly F α).gal /-- An auxiliary induction lemma, which is generalized by `solvable_by_rad.is_solvable`. -/ lemma induction3 {α : solvable_by_rad F E} {n : ℕ} (hn : n ≠ 0) (hα : P (α ^ n)) : P α := begin let p := minpoly F (α ^ n), have hp : p.comp (X ^ n) ≠ 0, { intro h, cases (comp_eq_zero_iff.mp h) with h' h', { exact minpoly.ne_zero (is_integral (α ^ n)) h' }, { exact hn (by rw [←nat_degree_C _, ←h'.2, nat_degree_X_pow]) } }, apply gal_is_solvable_of_splits, { exact ⟨splits_of_splits_of_dvd _ hp (splitting_field.splits (p.comp (X ^ n))) (minpoly.dvd F α (by rw [aeval_comp, aeval_X_pow, minpoly.aeval]))⟩ }, { refine gal_is_solvable_tower p (p.comp (X ^ n)) _ hα _, { exact gal.splits_in_splitting_field_of_comp _ _ (by rwa [nat_degree_X_pow]) }, { obtain ⟨s, hs⟩ := (splits_iff_exists_multiset _).1 (splitting_field.splits p), rw [map_comp, polynomial.map_pow, map_X, hs, mul_comp, C_comp], apply gal_mul_is_solvable (gal_C_is_solvable _), rw multiset_prod_comp, apply gal_prod_is_solvable, intros q hq, rw multiset.mem_map at hq, obtain ⟨q, hq, rfl⟩ := hq, rw multiset.mem_map at hq, obtain ⟨q, hq, rfl⟩ := hq, rw [sub_comp, X_comp, C_comp], exact gal_X_pow_sub_C_is_solvable n q } }, end /-- An auxiliary induction lemma, which is generalized by `solvable_by_rad.is_solvable`. -/ lemma induction2 {α β γ : solvable_by_rad F E} (hγ : γ ∈ F⟮α, β⟯) (hα : P α) (hβ : P β) : P γ := begin let p := (minpoly F α), let q := (minpoly F β), have hpq := polynomial.splits_of_splits_mul _ (mul_ne_zero (minpoly.ne_zero (is_integral α)) (minpoly.ne_zero (is_integral β))) (splitting_field.splits (p * q)), let f : F⟮α, β⟯ →ₐ[F] (p * q).splitting_field := classical.choice (alg_hom_mk_adjoin_splits begin intros x hx, cases hx, rw hx, exact ⟨is_integral α, hpq.1⟩, cases hx, exact ⟨is_integral β, hpq.2⟩, end), have key : minpoly F γ = minpoly F (f ⟨γ, hγ⟩) := minpoly.eq_of_irreducible_of_monic (minpoly.irreducible (is_integral γ)) begin suffices : aeval (⟨γ, hγ⟩ : F ⟮α, β⟯) (minpoly F γ) = 0, { rw [aeval_alg_hom_apply, this, alg_hom.map_zero] }, apply (algebra_map F⟮α, β⟯ (solvable_by_rad F E)).injective, rw [ring_hom.map_zero, ← aeval_algebra_map_apply], exact minpoly.aeval F γ, end (minpoly.monic (is_integral γ)), rw [P, key], refine gal_is_solvable_of_splits ⟨_⟩ (gal_mul_is_solvable hα hβ), exact normal.splits (splitting_field.normal _) (f ⟨γ, hγ⟩), end /-- An auxiliary induction lemma, which is generalized by `solvable_by_rad.is_solvable`. -/ lemma induction1 {α β : solvable_by_rad F E} (hβ : β ∈ F⟮α⟯) (hα : P α) : P β := induction2 (adjoin.mono F _ _ (ge_of_eq (set.pair_eq_singleton α)) hβ) hα hα theorem is_solvable (α : solvable_by_rad F E) : is_solvable (minpoly F α).gal := begin revert α, apply solvable_by_rad.induction, { exact λ α, by { rw minpoly.eq_X_sub_C, exact gal_X_sub_C_is_solvable α } }, { exact λ α β, induction2 (add_mem (subset_adjoin F _ (set.mem_insert α _)) (subset_adjoin F _ (set.mem_insert_of_mem α (set.mem_singleton β)))) }, { exact λ α, induction1 (neg_mem (mem_adjoin_simple_self F α)) }, { exact λ α β, induction2 (mul_mem (subset_adjoin F _ (set.mem_insert α _)) (subset_adjoin F _ (set.mem_insert_of_mem α (set.mem_singleton β)))) }, { exact λ α, induction1 (inv_mem (mem_adjoin_simple_self F α)) }, { exact λ α n, induction3 }, end /-- **Abel-Ruffini Theorem** (one direction): An irreducible polynomial with an `is_solvable_by_rad` root has solvable Galois group -/ lemma is_solvable' {α : E} {q : F[X]} (q_irred : irreducible q) (q_aeval : aeval α q = 0) (hα : is_solvable_by_rad F α) : _root_.is_solvable q.gal := begin haveI : _root_.is_solvable (q * C q.leading_coeff⁻¹).gal, { rw [minpoly.eq_of_irreducible q_irred q_aeval, ←show minpoly F (⟨α, hα⟩ : solvable_by_rad F E) = minpoly F α, from minpoly.eq_of_algebra_map_eq (ring_hom.injective _) (is_integral ⟨α, hα⟩) rfl], exact is_solvable ⟨α, hα⟩ }, refine solvable_of_surjective (gal.restrict_dvd_surjective ⟨C q.leading_coeff⁻¹, rfl⟩ _), rw [mul_ne_zero_iff, ne, ne, C_eq_zero, inv_eq_zero], exact ⟨q_irred.ne_zero, leading_coeff_ne_zero.mpr q_irred.ne_zero⟩, end end solvable_by_rad end abel_ruffini
5ddbfc455449409cfc1d08ded8623e7b71ff3131
94e33a31faa76775069b071adea97e86e218a8ee
/src/group_theory/group_action/defs.lean
ed6da272ce2a1e831dfcc1749d43c55f39f082cb
[ "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
31,588
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Yury Kudryashov -/ import algebra.group.type_tags import algebra.hom.group import algebra.opposites import logic.embedding /-! # Definitions of group actions This file defines a hierarchy of group action type-classes on top of the previously defined notation classes `has_smul` and its additive version `has_vadd`: * `mul_action M α` and its additive version `add_action G P` are typeclasses used for actions of multiplicative and additive monoids and groups; they extend notation classes `has_smul` and `has_vadd` that are defined in `algebra.group.defs`; * `distrib_mul_action M A` is a typeclass for an action of a multiplicative monoid on an additive monoid such that `a • (b + c) = a • b + a • c` and `a • 0 = 0`. The hierarchy is extended further by `module`, defined elsewhere. Also provided are typeclasses for faithful and transitive actions, and typeclasses regarding the interaction of different group actions, * `smul_comm_class M N α` and its additive version `vadd_comm_class M N α`; * `is_scalar_tower M N α` (no additive version). * `is_central_scalar M α` (no additive version). ## Notation - `a • b` is used as notation for `has_smul.smul a b`. - `a +ᵥ b` is used as notation for `has_vadd.vadd a b`. ## Implementation details This file should avoid depending on other parts of `group_theory`, to avoid import cycles. More sophisticated lemmas belong in `group_theory.group_action`. ## Tags group action -/ variables {M N G A B α β γ δ : Type*} open function (injective surjective) /-! ### Faithful actions -/ /-- Typeclass for faithful actions. -/ class has_faithful_vadd (G : Type*) (P : Type*) [has_vadd G P] : Prop := (eq_of_vadd_eq_vadd : ∀ {g₁ g₂ : G}, (∀ p : P, g₁ +ᵥ p = g₂ +ᵥ p) → g₁ = g₂) /-- Typeclass for faithful actions. -/ @[to_additive] class has_faithful_smul (M : Type*) (α : Type*) [has_smul M α] : Prop := (eq_of_smul_eq_smul : ∀ {m₁ m₂ : M}, (∀ a : α, m₁ • a = m₂ • a) → m₁ = m₂) export has_faithful_smul (eq_of_smul_eq_smul) has_faithful_vadd (eq_of_vadd_eq_vadd) @[to_additive] lemma smul_left_injective' [has_smul M α] [has_faithful_smul M α] : function.injective ((•) : M → α → α) := λ m₁ m₂ h, has_faithful_smul.eq_of_smul_eq_smul (congr_fun h) /-- See also `monoid.to_mul_action` and `mul_zero_class.to_smul_with_zero`. -/ @[priority 910, to_additive] -- see Note [lower instance priority] instance has_mul.to_has_smul (α : Type*) [has_mul α] : has_smul α α := ⟨(*)⟩ @[simp, to_additive] lemma smul_eq_mul (α : Type*) [has_mul α] {a a' : α} : a • a' = a * a' := rfl /-- Type class for additive monoid actions. -/ @[ext, protect_proj] class add_action (G : Type*) (P : Type*) [add_monoid G] extends has_vadd G P := (zero_vadd : ∀ p : P, (0 : G) +ᵥ p = p) (add_vadd : ∀ (g₁ g₂ : G) (p : P), (g₁ + g₂) +ᵥ p = g₁ +ᵥ (g₂ +ᵥ p)) /-- Typeclass for multiplicative actions by monoids. This generalizes group actions. -/ @[ext, protect_proj, to_additive] class mul_action (α : Type*) (β : Type*) [monoid α] extends has_smul α β := (one_smul : ∀ b : β, (1 : α) • b = b) (mul_smul : ∀ (x y : α) (b : β), (x * y) • b = x • y • b) instance additive.add_action [monoid α] [mul_action α β] : add_action (additive α) β := { vadd := (•) ∘ additive.to_mul, zero_vadd := mul_action.one_smul, add_vadd := mul_action.mul_smul } @[simp] lemma additive.of_mul_vadd [monoid α] [mul_action α β] (a : α) (b : β) : additive.of_mul a +ᵥ b = a • b := rfl instance multiplicative.mul_action [add_monoid α] [add_action α β] : mul_action (multiplicative α) β := { smul := (+ᵥ) ∘ multiplicative.to_add, one_smul := add_action.zero_vadd, mul_smul := add_action.add_vadd } @[simp] lemma multiplicative.of_add_smul [add_monoid α] [add_action α β] (a : α) (b : β) : multiplicative.of_add a • b = a +ᵥ b := rfl /-! ### (Pre)transitive action `M` acts pretransitively on `α` if for any `x y` there is `g` such that `g • x = y` (or `g +ᵥ x = y` for an additive action). A transitive action should furthermore have `α` nonempty. In this section we define typeclasses `mul_action.is_pretransitive` and `add_action.is_pretransitive` and provide `mul_action.exists_smul_eq`/`add_action.exists_vadd_eq`, `mul_action.surjective_smul`/`add_action.surjective_vadd` as public interface to access this property. We do not provide typeclasses `*_action.is_transitive`; users should assume `[mul_action.is_pretransitive M α] [nonempty α]` instead. -/ /-- `M` acts pretransitively on `α` if for any `x y` there is `g` such that `g +ᵥ x = y`. A transitive action should furthermore have `α` nonempty. -/ class add_action.is_pretransitive (M α : Type*) [has_vadd M α] : Prop := (exists_vadd_eq : ∀ x y : α, ∃ g : M, g +ᵥ x = y) /-- `M` acts pretransitively on `α` if for any `x y` there is `g` such that `g • x = y`. A transitive action should furthermore have `α` nonempty. -/ @[to_additive] class mul_action.is_pretransitive (M α : Type*) [has_smul M α] : Prop := (exists_smul_eq : ∀ x y : α, ∃ g : M, g • x = y) namespace mul_action variables (M) {α} [has_smul M α] [is_pretransitive M α] @[to_additive] lemma exists_smul_eq (x y : α) : ∃ m : M, m • x = y := is_pretransitive.exists_smul_eq x y @[to_additive] lemma surjective_smul (x : α) : surjective (λ c : M, c • x) := exists_smul_eq M x /-- The regular action of a group on itself is transitive. -/ @[to_additive] instance regular.is_pretransitive [group G] : is_pretransitive G G := ⟨λ x y, ⟨y * x⁻¹, inv_mul_cancel_right _ _⟩⟩ end mul_action /-! ### Scalar tower and commuting actions -/ /-- A typeclass mixin saying that two additive actions on the same space commute. -/ class vadd_comm_class (M N α : Type*) [has_vadd M α] [has_vadd N α] : Prop := (vadd_comm : ∀ (m : M) (n : N) (a : α), m +ᵥ (n +ᵥ a) = n +ᵥ (m +ᵥ a)) /-- A typeclass mixin saying that two multiplicative actions on the same space commute. -/ @[to_additive] class smul_comm_class (M N α : Type*) [has_smul M α] [has_smul N α] : Prop := (smul_comm : ∀ (m : M) (n : N) (a : α), m • n • a = n • m • a) export mul_action (mul_smul) add_action (add_vadd) smul_comm_class (smul_comm) vadd_comm_class (vadd_comm) /-- Frequently, we find ourselves wanting to express a bilinear map `M →ₗ[R] N →ₗ[R] P` or an equivalence between maps `(M →ₗ[R] N) ≃ₗ[R] (M' →ₗ[R] N')` where the maps have an associated ring `R`. Unfortunately, using definitions like these requires that `R` satisfy `comm_semiring R`, and not just `semiring R`. Using `M →ₗ[R] N →+ P` and `(M →ₗ[R] N) ≃+ (M' →ₗ[R] N')` avoids this problem, but throws away structure that is useful for when we _do_ have a commutative (semi)ring. To avoid making this compromise, we instead state these definitions as `M →ₗ[R] N →ₗ[S] P` or `(M →ₗ[R] N) ≃ₗ[S] (M' →ₗ[R] N')` and require `smul_comm_class S R` on the appropriate modules. When the caller has `comm_semiring R`, they can set `S = R` and `smul_comm_class_self` will populate the instance. If the caller only has `semiring R` they can still set either `R = ℕ` or `S = ℕ`, and `add_comm_monoid.nat_smul_comm_class` or `add_comm_monoid.nat_smul_comm_class'` will populate the typeclass, which is still sufficient to recover a `≃+` or `→+` structure. An example of where this is used is `linear_map.prod_equiv`. -/ library_note "bundled maps over different rings" /-- Commutativity of actions is a symmetric relation. This lemma can't be an instance because this would cause a loop in the instance search graph. -/ @[to_additive] lemma smul_comm_class.symm (M N α : Type*) [has_smul M α] [has_smul N α] [smul_comm_class M N α] : smul_comm_class N M α := ⟨λ a' a b, (smul_comm a a' b).symm⟩ /-- Commutativity of additive actions is a symmetric relation. This lemma can't be an instance because this would cause a loop in the instance search graph. -/ add_decl_doc vadd_comm_class.symm @[to_additive] instance smul_comm_class_self (M α : Type*) [comm_monoid M] [mul_action M α] : smul_comm_class M M α := ⟨λ a a' b, by rw [← mul_smul, mul_comm, mul_smul]⟩ /-- An instance of `is_scalar_tower M N α` states that the multiplicative action of `M` on `α` is determined by the multiplicative actions of `M` on `N` and `N` on `α`. -/ class is_scalar_tower (M N α : Type*) [has_smul M N] [has_smul N α] [has_smul M α] : Prop := (smul_assoc : ∀ (x : M) (y : N) (z : α), (x • y) • z = x • (y • z)) @[simp] lemma smul_assoc {M N} [has_smul M N] [has_smul N α] [has_smul M α] [is_scalar_tower M N α] (x : M) (y : N) (z : α) : (x • y) • z = x • y • z := is_scalar_tower.smul_assoc x y z instance semigroup.is_scalar_tower [semigroup α] : is_scalar_tower α α α := ⟨mul_assoc⟩ /-- A typeclass indicating that the right (aka `mul_opposite`) and left actions by `M` on `α` are equal, that is that `M` acts centrally on `α`. This can be thought of as a version of commutativity for `•`. -/ class is_central_scalar (M α : Type*) [has_smul M α] [has_smul Mᵐᵒᵖ α] : Prop := (op_smul_eq_smul : ∀ (m : M) (a : α), mul_opposite.op m • a = m • a) lemma is_central_scalar.unop_smul_eq_smul {M α : Type*} [has_smul M α] [has_smul Mᵐᵒᵖ α] [is_central_scalar M α] (m : Mᵐᵒᵖ) (a : α) : (mul_opposite.unop m) • a = m • a := mul_opposite.rec (by exact λ m, (is_central_scalar.op_smul_eq_smul _ _).symm) m export is_central_scalar (op_smul_eq_smul unop_smul_eq_smul) -- these instances are very low priority, as there is usually a faster way to find these instances @[priority 50] instance smul_comm_class.op_left [has_smul M α] [has_smul Mᵐᵒᵖ α] [is_central_scalar M α] [has_smul N α] [smul_comm_class M N α] : smul_comm_class Mᵐᵒᵖ N α := ⟨λ m n a, by rw [←unop_smul_eq_smul m (n • a), ←unop_smul_eq_smul m a, smul_comm]⟩ @[priority 50] instance smul_comm_class.op_right [has_smul M α] [has_smul N α] [has_smul Nᵐᵒᵖ α] [is_central_scalar N α] [smul_comm_class M N α] : smul_comm_class M Nᵐᵒᵖ α := ⟨λ m n a, by rw [←unop_smul_eq_smul n (m • a), ←unop_smul_eq_smul n a, smul_comm]⟩ @[priority 50] instance is_scalar_tower.op_left [has_smul M α] [has_smul Mᵐᵒᵖ α] [is_central_scalar M α] [has_smul M N] [has_smul Mᵐᵒᵖ N] [is_central_scalar M N] [has_smul N α] [is_scalar_tower M N α] : is_scalar_tower Mᵐᵒᵖ N α := ⟨λ m n a, by rw [←unop_smul_eq_smul m (n • a), ←unop_smul_eq_smul m n, smul_assoc]⟩ @[priority 50] instance is_scalar_tower.op_right [has_smul M α] [has_smul M N] [has_smul N α] [has_smul Nᵐᵒᵖ α] [is_central_scalar N α] [is_scalar_tower M N α] : is_scalar_tower M Nᵐᵒᵖ α := ⟨λ m n a, by rw [←unop_smul_eq_smul n a, ←unop_smul_eq_smul (m • n) a, mul_opposite.unop_smul, smul_assoc]⟩ namespace has_smul variables [has_smul M α] /-- Auxiliary definition for `has_smul.comp`, `mul_action.comp_hom`, `distrib_mul_action.comp_hom`, `module.comp_hom`, etc. -/ @[simp, to_additive /-" Auxiliary definition for `has_vadd.comp`, `add_action.comp_hom`, etc. "-/] def comp.smul (g : N → M) (n : N) (a : α) : α := g n • a variables (α) /-- An action of `M` on `α` and a function `N → M` induces an action of `N` on `α`. See note [reducible non-instances]. Since this is reducible, we make sure to go via `has_smul.comp.smul` to prevent typeclass inference unfolding too far. -/ @[reducible, to_additive /-" An additive action of `M` on `α` and a function `N → M` induces an additive action of `N` on `α` "-/] def comp (g : N → M) : has_smul N α := { smul := has_smul.comp.smul g } variables {α} /-- Given a tower of scalar actions `M → α → β`, if we use `has_smul.comp` to pull back both of `M`'s actions by a map `g : N → M`, then we obtain a new tower of scalar actions `N → α → β`. This cannot be an instance because it can cause infinite loops whenever the `has_smul` arguments are still metavariables. -/ @[priority 100] lemma comp.is_scalar_tower [has_smul M β] [has_smul α β] [is_scalar_tower M α β] (g : N → M) : (by haveI := comp α g; haveI := comp β g; exact is_scalar_tower N α β) := by exact {smul_assoc := λ n, @smul_assoc _ _ _ _ _ _ _ (g n) } /-- This cannot be an instance because it can cause infinite loops whenever the `has_smul` arguments are still metavariables. -/ @[priority 100] lemma comp.smul_comm_class [has_smul β α] [smul_comm_class M β α] (g : N → M) : (by haveI := comp α g; exact smul_comm_class N β α) := by exact {smul_comm := λ n, @smul_comm _ _ _ _ _ _ (g n) } /-- This cannot be an instance because it can cause infinite loops whenever the `has_smul` arguments are still metavariables. -/ @[priority 100] lemma comp.smul_comm_class' [has_smul β α] [smul_comm_class β M α] (g : N → M) : (by haveI := comp α g; exact smul_comm_class β N α) := by exact {smul_comm := λ _ n, @smul_comm _ _ _ _ _ _ _ (g n) } end has_smul section /-- Note that the `smul_comm_class α β β` typeclass argument is usually satisfied by `algebra α β`. -/ @[to_additive] lemma mul_smul_comm [has_mul β] [has_smul α β] [smul_comm_class α β β] (s : α) (x y : β) : x * (s • y) = s • (x * y) := (smul_comm s x y).symm /-- Note that the `is_scalar_tower α β β` typeclass argument is usually satisfied by `algebra α β`. -/ lemma smul_mul_assoc [has_mul β] [has_smul α β] [is_scalar_tower α β β] (r : α) (x y : β) : (r • x) * y = r • (x * y) := smul_assoc r x y lemma smul_smul_smul_comm [has_smul α β] [has_smul α γ] [has_smul β δ] [has_smul α δ] [has_smul γ δ] [is_scalar_tower α β δ] [is_scalar_tower α γ δ] [smul_comm_class β γ δ] (a : α) (b : β) (c : γ) (d : δ) : (a • b) • (c • d) = (a • c) • b • d := by { rw [smul_assoc, smul_assoc, smul_comm b], apply_instance } variables [has_smul M α] lemma commute.smul_right [has_mul α] [smul_comm_class M α α] [is_scalar_tower M α α] {a b : α} (h : commute a b) (r : M) : commute a (r • b) := (mul_smul_comm _ _ _).trans ((congr_arg _ h).trans $ (smul_mul_assoc _ _ _).symm) lemma commute.smul_left [has_mul α] [smul_comm_class M α α] [is_scalar_tower M α α] {a b : α} (h : commute a b) (r : M) : commute (r • a) b := (h.symm.smul_right r).symm end section ite variables [has_smul M α] (p : Prop) [decidable p] @[to_additive] lemma ite_smul (a₁ a₂ : M) (b : α) : (ite p a₁ a₂) • b = ite p (a₁ • b) (a₂ • b) := by split_ifs; refl @[to_additive] lemma smul_ite (a : M) (b₁ b₂ : α) : a • (ite p b₁ b₂) = ite p (a • b₁) (a • b₂) := by split_ifs; refl end ite section variables [monoid M] [mul_action M α] @[to_additive] lemma smul_smul (a₁ a₂ : M) (b : α) : a₁ • a₂ • b = (a₁ * a₂) • b := (mul_smul _ _ _).symm variable (M) @[simp, to_additive] theorem one_smul (b : α) : (1 : M) • b = b := mul_action.one_smul _ /-- `has_smul` version of `one_mul_eq_id` -/ @[to_additive] lemma one_smul_eq_id : ((•) (1 : M) : α → α) = id := funext $ one_smul _ /-- `has_smul` version of `comp_mul_left` -/ @[to_additive] lemma comp_smul_left (a₁ a₂ : M) : (•) a₁ ∘ (•) a₂ = ((•) (a₁ * a₂) : α → α) := funext $ λ _, (mul_smul _ _ _).symm variables {M} /-- Pullback a multiplicative action along an injective map respecting `•`. See note [reducible non-instances]. -/ @[reducible, to_additive "Pullback an additive action along an injective map respecting `+ᵥ`."] protected def function.injective.mul_action [has_smul M β] (f : β → α) (hf : injective f) (smul : ∀ (c : M) x, f (c • x) = c • f x) : mul_action M β := { smul := (•), one_smul := λ x, hf $ (smul _ _).trans $ one_smul _ (f x), mul_smul := λ c₁ c₂ x, hf $ by simp only [smul, mul_smul] } /-- Pushforward a multiplicative action along a surjective map respecting `•`. See note [reducible non-instances]. -/ @[reducible, to_additive "Pushforward an additive action along a surjective map respecting `+ᵥ`."] protected def function.surjective.mul_action [has_smul M β] (f : α → β) (hf : surjective f) (smul : ∀ (c : M) x, f (c • x) = c • f x) : mul_action M β := { smul := (•), one_smul := λ y, by { rcases hf y with ⟨x, rfl⟩, rw [← smul, one_smul] }, mul_smul := λ c₁ c₂ y, by { rcases hf y with ⟨x, rfl⟩, simp only [← smul, mul_smul] } } /-- Push forward the action of `R` on `M` along a compatible surjective map `f : R →* S`. See also `function.surjective.distrib_mul_action_left` and `function.surjective.module_left`. -/ @[reducible, to_additive "Push forward the action of `R` on `M` along a compatible surjective map `f : R →+ S`."] def function.surjective.mul_action_left {R S M : Type*} [monoid R] [mul_action R M] [monoid S] [has_smul S M] (f : R →* S) (hf : function.surjective f) (hsmul : ∀ c (x : M), f c • x = c • x) : mul_action S M := { smul := (•), one_smul := λ b, by rw [← f.map_one, hsmul, one_smul], mul_smul := hf.forall₂.mpr $ λ a b x, by simp only [← f.map_mul, hsmul, mul_smul] } section variables (M) /-- The regular action of a monoid on itself by left multiplication. This is promoted to a module by `semiring.to_module`. -/ @[priority 910, to_additive] -- see Note [lower instance priority] instance monoid.to_mul_action : mul_action M M := { smul := (*), one_smul := one_mul, mul_smul := mul_assoc } /-- The regular action of a monoid on itself by left addition. This is promoted to an `add_torsor` by `add_group_is_add_torsor`. -/ add_decl_doc add_monoid.to_add_action instance is_scalar_tower.left : is_scalar_tower M M α := ⟨λ x y z, mul_smul x y z⟩ variables {M} /-- Note that the `is_scalar_tower M α α` and `smul_comm_class M α α` typeclass arguments are usually satisfied by `algebra M α`. -/ lemma smul_mul_smul [has_mul α] (r s : M) (x y : α) [is_scalar_tower M α α] [smul_comm_class M α α] : (r • x) * (s • y) = (r * s) • (x * y) := by rw [smul_mul_assoc, mul_smul_comm, ← smul_assoc, smul_eq_mul] end namespace mul_action variables (M α) /-- Embedding of `α` into functions `M → α` induced by a multiplicative action of `M` on `α`. -/ @[to_additive] def to_fun : α ↪ (M → α) := ⟨λ y x, x • y, λ y₁ y₂ H, one_smul M y₁ ▸ one_smul M y₂ ▸ by convert congr_fun H 1⟩ /-- Embedding of `α` into functions `M → α` induced by an additive action of `M` on `α`. -/ add_decl_doc add_action.to_fun variables {M α} @[simp, to_additive] lemma to_fun_apply (x : M) (y : α) : mul_action.to_fun M α y x = x • y := rfl variable (α) /-- A multiplicative action of `M` on `α` and a monoid homomorphism `N → M` induce a multiplicative action of `N` on `α`. See note [reducible non-instances]. -/ @[reducible, to_additive] def comp_hom [monoid N] (g : N →* M) : mul_action N α := { smul := has_smul.comp.smul g, one_smul := by simp [g.map_one, mul_action.one_smul], mul_smul := by simp [g.map_mul, mul_action.mul_smul] } /-- An additive action of `M` on `α` and an additive monoid homomorphism `N → M` induce an additive action of `N` on `α`. See note [reducible non-instances]. -/ add_decl_doc add_action.comp_hom end mul_action end section compatible_scalar @[simp] lemma smul_one_smul {M} (N) [monoid N] [has_smul M N] [mul_action N α] [has_smul M α] [is_scalar_tower M N α] (x : M) (y : α) : (x • (1 : N)) • y = x • y := by rw [smul_assoc, one_smul] @[simp] lemma smul_one_mul {M N} [mul_one_class N] [has_smul M N] [is_scalar_tower M N N] (x : M) (y : N) : (x • 1) * y = x • y := by rw [smul_mul_assoc, one_mul] @[simp, to_additive] lemma mul_smul_one {M N} [mul_one_class N] [has_smul M N] [smul_comm_class M N N] (x : M) (y : N) : y * (x • 1) = x • y := by rw [← smul_eq_mul, ← smul_comm, smul_eq_mul, mul_one] lemma is_scalar_tower.of_smul_one_mul {M N} [monoid N] [has_smul M N] (h : ∀ (x : M) (y : N), (x • (1 : N)) * y = x • y) : is_scalar_tower M N N := ⟨λ x y z, by rw [← h, smul_eq_mul, mul_assoc, h, smul_eq_mul]⟩ @[to_additive] lemma smul_comm_class.of_mul_smul_one {M N} [monoid N] [has_smul M N] (H : ∀ (x : M) (y : N), y * (x • (1 : N)) = x • y) : smul_comm_class M N N := ⟨λ x y z, by rw [← H x z, smul_eq_mul, ← H, smul_eq_mul, mul_assoc]⟩ end compatible_scalar /-- Typeclass for multiplicative actions on additive structures. This generalizes group modules. -/ @[ext] class distrib_mul_action (M : Type*) (A : Type*) [monoid M] [add_monoid A] extends mul_action M A := (smul_add : ∀(r : M) (x y : A), r • (x + y) = r • x + r • y) (smul_zero : ∀(r : M), r • (0 : A) = 0) section variables [monoid M] [add_monoid A] [distrib_mul_action M A] theorem smul_add (a : M) (b₁ b₂ : A) : a • (b₁ + b₂) = a • b₁ + a • b₂ := distrib_mul_action.smul_add _ _ _ @[simp] theorem smul_zero (a : M) : a • (0 : A) = 0 := distrib_mul_action.smul_zero _ /-- Pullback a distributive multiplicative action along an injective additive monoid homomorphism. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.distrib_mul_action [add_monoid B] [has_smul M B] (f : B →+ A) (hf : injective f) (smul : ∀ (c : M) x, f (c • x) = c • f x) : distrib_mul_action M B := { smul := (•), smul_add := λ c x y, hf $ by simp only [smul, f.map_add, smul_add], smul_zero := λ c, hf $ by simp only [smul, f.map_zero, smul_zero], .. hf.mul_action f smul } /-- Pushforward a distributive multiplicative action along a surjective additive monoid homomorphism. See note [reducible non-instances]. -/ @[reducible] protected def function.surjective.distrib_mul_action [add_monoid B] [has_smul M B] (f : A →+ B) (hf : surjective f) (smul : ∀ (c : M) x, f (c • x) = c • f x) : distrib_mul_action M B := { smul := (•), smul_add := λ c x y, by { rcases hf x with ⟨x, rfl⟩, rcases hf y with ⟨y, rfl⟩, simp only [smul_add, ← smul, ← f.map_add] }, smul_zero := λ c, by simp only [← f.map_zero, ← smul, smul_zero], .. hf.mul_action f smul } /-- Push forward the action of `R` on `M` along a compatible surjective map `f : R →* S`. See also `function.surjective.mul_action_left` and `function.surjective.module_left`. -/ @[reducible] def function.surjective.distrib_mul_action_left {R S M : Type*} [monoid R] [add_monoid M] [distrib_mul_action R M] [monoid S] [has_smul S M] (f : R →* S) (hf : function.surjective f) (hsmul : ∀ c (x : M), f c • x = c • x) : distrib_mul_action S M := { smul := (•), smul_zero := hf.forall.mpr $ λ c, by rw [hsmul, smul_zero], smul_add := hf.forall.mpr $ λ c x y, by simp only [hsmul, smul_add], .. hf.mul_action_left f hsmul } variable (A) /-- Compose a `distrib_mul_action` with a `monoid_hom`, with action `f r' • m`. See note [reducible non-instances]. -/ @[reducible] def distrib_mul_action.comp_hom [monoid N] (f : N →* M) : distrib_mul_action N A := { smul := has_smul.comp.smul f, smul_zero := λ x, smul_zero (f x), smul_add := λ x, smul_add (f x), .. mul_action.comp_hom A f } /-- Each element of the monoid defines a additive monoid homomorphism. -/ @[simps] def distrib_mul_action.to_add_monoid_hom (x : M) : A →+ A := { to_fun := (•) x, map_zero' := smul_zero x, map_add' := smul_add x } variables (M) /-- Each element of the monoid defines an additive monoid homomorphism. -/ @[simps] def distrib_mul_action.to_add_monoid_End : M →* add_monoid.End A := { to_fun := distrib_mul_action.to_add_monoid_hom A, map_one' := add_monoid_hom.ext $ one_smul M, map_mul' := λ x y, add_monoid_hom.ext $ mul_smul x y } instance add_monoid.nat_smul_comm_class : smul_comm_class ℕ M A := { smul_comm := λ n x y, ((distrib_mul_action.to_add_monoid_hom A x).map_nsmul y n).symm } -- `smul_comm_class.symm` is not registered as an instance, as it would cause a loop instance add_monoid.nat_smul_comm_class' : smul_comm_class M ℕ A := smul_comm_class.symm _ _ _ end section variables [monoid M] [add_group A] [distrib_mul_action M A] instance add_group.int_smul_comm_class : smul_comm_class ℤ M A := { smul_comm := λ n x y, ((distrib_mul_action.to_add_monoid_hom A x).map_zsmul y n).symm } -- `smul_comm_class.symm` is not registered as an instance, as it would cause a loop instance add_group.int_smul_comm_class' : smul_comm_class M ℤ A := smul_comm_class.symm _ _ _ @[simp] theorem smul_neg (r : M) (x : A) : r • (-x) = -(r • x) := eq_neg_of_add_eq_zero_left $ by rw [← smul_add, neg_add_self, smul_zero] theorem smul_sub (r : M) (x y : A) : r • (x - y) = r • x - r • y := by rw [sub_eq_add_neg, sub_eq_add_neg, smul_add, smul_neg] end /-- Typeclass for multiplicative actions on multiplicative structures. This generalizes conjugation actions. -/ @[ext] class mul_distrib_mul_action (M : Type*) (A : Type*) [monoid M] [monoid A] extends mul_action M A := (smul_mul : ∀ (r : M) (x y : A), r • (x * y) = (r • x) * (r • y)) (smul_one : ∀ (r : M), r • (1 : A) = 1) export mul_distrib_mul_action (smul_one) section variables [monoid M] [monoid A] [mul_distrib_mul_action M A] theorem smul_mul' (a : M) (b₁ b₂ : A) : a • (b₁ * b₂) = (a • b₁) * (a • b₂) := mul_distrib_mul_action.smul_mul _ _ _ /-- Pullback a multiplicative distributive multiplicative action along an injective monoid homomorphism. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.mul_distrib_mul_action [monoid B] [has_smul M B] (f : B →* A) (hf : injective f) (smul : ∀ (c : M) x, f (c • x) = c • f x) : mul_distrib_mul_action M B := { smul := (•), smul_mul := λ c x y, hf $ by simp only [smul, f.map_mul, smul_mul'], smul_one := λ c, hf $ by simp only [smul, f.map_one, smul_one], .. hf.mul_action f smul } /-- Pushforward a multiplicative distributive multiplicative action along a surjective monoid homomorphism. See note [reducible non-instances]. -/ @[reducible] protected def function.surjective.mul_distrib_mul_action [monoid B] [has_smul M B] (f : A →* B) (hf : surjective f) (smul : ∀ (c : M) x, f (c • x) = c • f x) : mul_distrib_mul_action M B := { smul := (•), smul_mul := λ c x y, by { rcases hf x with ⟨x, rfl⟩, rcases hf y with ⟨y, rfl⟩, simp only [smul_mul', ← smul, ← f.map_mul] }, smul_one := λ c, by simp only [← f.map_one, ← smul, smul_one], .. hf.mul_action f smul } variable (A) /-- Compose a `mul_distrib_mul_action` with a `monoid_hom`, with action `f r' • m`. See note [reducible non-instances]. -/ @[reducible] def mul_distrib_mul_action.comp_hom [monoid N] (f : N →* M) : mul_distrib_mul_action N A := { smul := has_smul.comp.smul f, smul_one := λ x, smul_one (f x), smul_mul := λ x, smul_mul' (f x), .. mul_action.comp_hom A f } /-- Scalar multiplication by `r` as a `monoid_hom`. -/ def mul_distrib_mul_action.to_monoid_hom (r : M) : A →* A := { to_fun := (•) r, map_one' := smul_one r, map_mul' := smul_mul' r } variable {A} @[simp] lemma mul_distrib_mul_action.to_monoid_hom_apply (r : M) (x : A) : mul_distrib_mul_action.to_monoid_hom A r x = r • x := rfl variables (M A) /-- Each element of the monoid defines a monoid homomorphism. -/ @[simps] def mul_distrib_mul_action.to_monoid_End : M →* monoid.End A := { to_fun := mul_distrib_mul_action.to_monoid_hom A, map_one' := monoid_hom.ext $ one_smul M, map_mul' := λ x y, monoid_hom.ext $ mul_smul x y } end section variables [monoid M] [group A] [mul_distrib_mul_action M A] @[simp] theorem smul_inv' (r : M) (x : A) : r • (x⁻¹) = (r • x)⁻¹ := (mul_distrib_mul_action.to_monoid_hom A r).map_inv x theorem smul_div' (r : M) (x y : A) : r • (x / y) = (r • x) / (r • y) := (mul_distrib_mul_action.to_monoid_hom A r).map_div x y end variable (α) /-- The monoid of endomorphisms. Note that this is generalized by `category_theory.End` to categories other than `Type u`. -/ protected def function.End := α → α instance : monoid (function.End α) := { one := id, mul := (∘), mul_assoc := λ f g h, rfl, mul_one := λ f, rfl, one_mul := λ f, rfl, } instance : inhabited (function.End α) := ⟨1⟩ variable {α} /-- The tautological action by `function.End α` on `α`. This is generalized to bundled endomorphisms by: * `equiv.perm.apply_mul_action` * `add_monoid.End.apply_distrib_mul_action` * `add_aut.apply_distrib_mul_action` * `mul_aut.apply_mul_distrib_mul_action` * `ring_hom.apply_distrib_mul_action` * `linear_equiv.apply_distrib_mul_action` * `linear_map.apply_module` * `ring_hom.apply_mul_semiring_action` * `alg_equiv.apply_mul_semiring_action` -/ instance function.End.apply_mul_action : mul_action (function.End α) α := { smul := ($), one_smul := λ _, rfl, mul_smul := λ _ _ _, rfl } @[simp] lemma function.End.smul_def (f : function.End α) (a : α) : f • a = f a := rfl /-- `function.End.apply_mul_action` is faithful. -/ instance function.End.apply_has_faithful_smul : has_faithful_smul (function.End α) α := ⟨λ x y, funext⟩ /-- The tautological action by `add_monoid.End α` on `α`. This generalizes `function.End.apply_mul_action`. -/ instance add_monoid.End.apply_distrib_mul_action [add_monoid α] : distrib_mul_action (add_monoid.End α) α := { smul := ($), smul_zero := add_monoid_hom.map_zero, smul_add := add_monoid_hom.map_add, one_smul := λ _, rfl, mul_smul := λ _ _ _, rfl } @[simp] lemma add_monoid.End.smul_def [add_monoid α] (f : add_monoid.End α) (a : α) : f • a = f a := rfl /-- `add_monoid.End.apply_distrib_mul_action` is faithful. -/ instance add_monoid.End.apply_has_faithful_smul [add_monoid α] : has_faithful_smul (add_monoid.End α) α := ⟨add_monoid_hom.ext⟩ /-- The monoid hom representing a monoid action. When `M` is a group, see `mul_action.to_perm_hom`. -/ def mul_action.to_End_hom [monoid M] [mul_action M α] : M →* function.End α := { to_fun := (•), map_one' := funext (one_smul M), map_mul' := λ x y, funext (mul_smul x y) } /-- The monoid action induced by a monoid hom to `function.End α` See note [reducible non-instances]. -/ @[reducible] def mul_action.of_End_hom [monoid M] (f : M →* function.End α) : mul_action M α := mul_action.comp_hom α f /-- The tautological additive action by `additive (function.End α)` on `α`. -/ instance add_action.function_End : add_action (additive (function.End α)) α := { vadd := ($), zero_vadd := λ _, rfl, add_vadd := λ _ _ _, rfl } /-- The additive monoid hom representing an additive monoid action. When `M` is a group, see `add_action.to_perm_hom`. -/ def add_action.to_End_hom [add_monoid M] [add_action M α] : M →+ additive (function.End α) := { to_fun := (+ᵥ), map_zero' := funext (zero_vadd M), map_add' := λ x y, funext (add_vadd x y) } /-- The additive action induced by a hom to `additive (function.End α)` See note [reducible non-instances]. -/ @[reducible] def add_action.of_End_hom [add_monoid M] (f : M →+ additive (function.End α)) : add_action M α := add_action.comp_hom α f
731f34ec0a67004b9711803cdeba57a3f47a8268
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/struct_extend_univ.lean
36a86aa7e1ed430c6e4346f39bcee2500381b7fc
[ "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
98
lean
universe u class foo (α : Sort u) := (a : α) class bar (α : Type u) extends foo α := (b : α)
916e2e76701f71f7270fae60ab7eb9ee9ccfe939
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebraic_geometry/is_open_comap_C.lean
af4393b86cfd7fb1005cf63a15ba8377722f3afc
[]
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
2,255
lean
/- Copyright (c) 2021 Damiano Testa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Damiano Testa -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebraic_geometry.prime_spectrum import Mathlib.ring_theory.polynomial.basic import Mathlib.PostPort universes u_1 namespace Mathlib /-! The morphism `Spec R[x] --> Spec R` induced by the natural inclusion `R --> R[x]` is an open map. -/ namespace algebraic_geometry namespace polynomial /-- Given a polynomial `f ∈ R[x]`, `image_of_Df` is the subset of `Spec R` where at least one of the coefficients of `f` does not vanish. Lemma `image_of_Df_eq_comap_C_compl_zero_locus` proves that `image_of_Df` is the image of `(zero_locus {f})ᶜ` under the morphism `comap C : Spec R[x] → Spec R`. -/ def image_of_Df {R : Type u_1} [comm_ring R] (f : polynomial R) : set (prime_spectrum R) := set_of fun (p : prime_spectrum R) => ∃ (i : ℕ), ¬polynomial.coeff f i ∈ prime_spectrum.as_ideal p theorem is_open_image_of_Df {R : Type u_1} [comm_ring R] {f : polynomial R} : is_open (image_of_Df f) := sorry /-- If a point of `Spec R[x]` is not contained in the vanishing set of `f`, then its image in `Spec R` is contained in the open set where at least one of the coefficients of `f` is non-zero. This lemma is a reformulation of `exists_coeff_not_mem_C_inverse`. -/ theorem comap_C_mem_image_of_Df {R : Type u_1} [comm_ring R] {f : polynomial R} {I : prime_spectrum (polynomial R)} (H : I ∈ (prime_spectrum.zero_locus (singleton f)ᶜ)) : prime_spectrum.comap polynomial.C I ∈ image_of_Df f := polynomial.exists_coeff_not_mem_C_inverse (iff.mp prime_spectrum.mem_compl_zero_locus_iff_not_mem H) /-- The open set `image_of_Df f` coincides with the image of `basic_open f` under the morphism `C⁺ : Spec R[x] → Spec R`. -/ theorem image_of_Df_eq_comap_C_compl_zero_locus {R : Type u_1} [comm_ring R] {f : polynomial R} : image_of_Df f = prime_spectrum.comap polynomial.C '' (prime_spectrum.zero_locus (singleton f)ᶜ) := sorry /-- The morphism `C⁺ : Spec R[x] → Spec R` is open. -/ theorem is_open_map_comap_C {R : Type u_1} [comm_ring R] : is_open_map (prime_spectrum.comap polynomial.C) := sorry
d9483b0bb26496dac1516e99ab689239b786c77c
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/char_auto.lean
8238d54aebc0ba9d70d2f34f4525644a903cc287
[]
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
488
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Supplementary theorems about the `char` type. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.PostPort namespace Mathlib protected instance char.linear_order : linear_order char := linear_order.mk LessEq Less sorry sorry sorry sorry char.decidable_le char.decidable_eq char.decidable_lt end Mathlib
3fae1e2aef9c892b67d297a937865436a2fa80ad
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/control/ulift.lean
0570be8666309864b1611adc83b98b73065421b7
[ "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
3,932
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Jannis Limperg -/ /-! # Monadic instances for `ulift` and `plift` > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we define `monad` and `is_lawful_monad` instances on `plift` and `ulift`. -/ universes u v namespace plift variables {α : Sort u} {β : Sort v} /-- Functorial action. -/ protected def map (f : α → β) (a : plift α) : plift β := plift.up (f a.down) @[simp] lemma map_up (f : α → β) (a : α) : (plift.up a).map f = plift.up (f a) := rfl /-- Embedding of pure values. -/ @[simp] protected def pure : α → plift α := up /-- Applicative sequencing. -/ protected def seq (f : plift (α → β)) (x : plift α) : plift β := plift.up (f.down x.down) @[simp] lemma seq_up (f : α → β) (x : α) : (plift.up f).seq (plift.up x) = plift.up (f x) := rfl /-- Monadic bind. -/ protected def bind (a : plift α) (f : α → plift β) : plift β := f a.down @[simp] lemma bind_up (a : α) (f : α → plift β) : (plift.up a).bind f = f a := rfl instance : monad plift := { map := @plift.map, pure := @plift.pure, seq := @plift.seq, bind := @plift.bind } instance : is_lawful_functor plift := { id_map := λ α ⟨x⟩, rfl, comp_map := λ α β γ g h ⟨x⟩, rfl } instance : is_lawful_applicative plift := { pure_seq_eq_map := λ α β g ⟨x⟩, rfl, map_pure := λ α β g x, rfl, seq_pure := λ α β ⟨g⟩ x, rfl, seq_assoc := λ α β γ ⟨x⟩ ⟨g⟩ ⟨h⟩, rfl } instance : is_lawful_monad plift := { bind_pure_comp_eq_map := λ α β f ⟨x⟩, rfl, bind_map_eq_seq := λ α β ⟨a⟩ ⟨b⟩, rfl, pure_bind := λ α β x f, rfl, bind_assoc := λ α β γ ⟨x⟩ f g, rfl } @[simp] lemma rec.constant {α : Sort u} {β : Type v} (b : β) : @plift.rec α (λ _, β) (λ _, b) = λ _, b := funext (λ x, plift.cases_on x (λ a, eq.refl (plift.rec (λ a', b) {down := a}))) end plift namespace ulift variables {α : Type u} {β : Type v} /-- Functorial action. -/ protected def map (f : α → β) (a : ulift α) : ulift β := ulift.up (f a.down) @[simp] lemma map_up (f : α → β) (a : α) : (ulift.up a).map f = ulift.up (f a) := rfl /-- Embedding of pure values. -/ @[simp] protected def pure : α → ulift α := up /-- Applicative sequencing. -/ protected def seq (f : ulift (α → β)) (x : ulift α) : ulift β := ulift.up (f.down x.down) @[simp] lemma seq_up (f : α → β) (x : α) : (ulift.up f).seq (ulift.up x) = ulift.up (f x) := rfl /-- Monadic bind. -/ protected def bind (a : ulift α) (f : α → ulift β) : ulift β := f a.down @[simp] lemma bind_up (a : α) (f : α → ulift β) : (ulift.up a).bind f = f a := rfl instance : monad ulift := { map := @ulift.map, pure := @ulift.pure, seq := @ulift.seq, bind := @ulift.bind } instance : is_lawful_functor ulift := { id_map := λ α ⟨x⟩, rfl, comp_map := λ α β γ g h ⟨x⟩, rfl } instance : is_lawful_applicative ulift := { to_is_lawful_functor := ulift.is_lawful_functor, pure_seq_eq_map := λ α β g ⟨x⟩, rfl, map_pure := λ α β g x, rfl, seq_pure := λ α β ⟨g⟩ x, rfl, seq_assoc := λ α β γ ⟨x⟩ ⟨g⟩ ⟨h⟩, rfl } instance : is_lawful_monad ulift := { bind_pure_comp_eq_map := λ α β f ⟨x⟩, rfl, bind_map_eq_seq := λ α β ⟨a⟩ ⟨b⟩, rfl, pure_bind := λ α β x f, by { dsimp only [bind, pure, ulift.pure, ulift.bind], cases (f x), refl }, bind_assoc := λ α β γ ⟨x⟩ f g, by { dsimp only [bind, pure, ulift.pure, ulift.bind], cases (f x), refl } } @[simp] lemma rec.constant {α : Type u} {β : Sort v} (b : β) : @ulift.rec α (λ _, β) (λ _, b) = λ _, b := funext (λ x, ulift.cases_on x (λ a, eq.refl (ulift.rec (λ a', b) {down := a}))) end ulift
e4e29b6729d3a430d6945f3fae2a3d76138a832b
218e2afdf9209a5f82db7ac0089f79064e52bd80
/lean/src/common.lean
bedf8e4a98cab457f426ce3fbb9f87083e3af3f5
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
mk12/analysis-i
1f022e81cdc5cae5b25360f93000186874e1d02b
e85deae5441f705d9284eeb204c9c3ecb450c93a
refs/heads/main
1,637,808,582,073
1,636,857,479,000
1,636,857,479,000
67,387,570
8
1
null
null
null
null
UTF-8
Lean
false
false
3,318
lean
-- Copyright 2016 Mitchell Kember. Subject to the MIT License. -- Formalization of Analysis I: Common theorems open classical (by_cases by_contradiction) -- Double negation elimination theorem not_not_elim {p : Prop} (H : ¬ ¬ p) : p := by_cases (assume Hp : p, Hp) (assume Hnp : ¬ p, absurd Hnp H) -- Triple disjunction elimination namespace or variables {a b c d : Prop} theorem elim3 (H : a ∨ b ∨ c) (Ha : a → d) (Hb : b → d) (Hc : c → d) : d := H.elim Ha (suppose b ∨ c, this.elim Hb Hc) end or -- De Morgan's laws section de_morgan variables {p q : Prop} theorem dm_not_or_not (H : ¬ (p ∧ q)) : ¬ p ∨ ¬ q := by_cases (assume Hp : p, have ¬ q, from assume Hq : q, have p ∧ q, from ⟨Hp, Hq⟩, absurd this H, show ¬ p ∨ ¬ q, from or.inr this) (suppose ¬ p, or.inl this) theorem dm_not_and (H : ¬ p ∨ ¬ q) : ¬ (p ∧ q) := assume Hpq : p ∧ q, H.elim (suppose ¬ p, absurd Hpq.left this) (suppose ¬ q, absurd Hpq.right this) theorem dm_not_and_not (H : ¬ (p ∨ q)) : ¬ p ∧ ¬ q := by_cases (suppose p, absurd (or.inl this) H) (assume Hnp : ¬ p, have Hnq : ¬ q, from suppose q, absurd (or.inr this) H, show ¬ p ∧ ¬ q, from ⟨Hnp, Hnq⟩) theorem dm_not_or (H : ¬ p ∧ ¬ q) : ¬ (p ∨ q) := suppose p ∨ q, this.elim (suppose p, absurd this H.left) (suppose q, absurd this H.right) end de_morgan -- De Morgan's laws (general) section de_morgan_general variables {A : Type} {p : A → Prop} theorem dm_exists_not (H : ¬ ∀ a : A, p a) : ∃ a : A, ¬ p a := by_contradiction (assume H₁ : ¬ ∃ a : A, ¬ p a, suffices ∀ a : A, p a, from absurd this H, assume a : A, show p a, from by_contradiction (suppose ¬ p a, have ∃ a : A, ¬ p a, from ⟨a, this⟩, absurd this H₁)) theorem dm_not_forall (H : ∃ a : A, ¬ p a) : ¬ ∀ a : A, p a := let ⟨a, (H₁ : ¬ p a)⟩ := H in suppose ∀ a : A, p a, absurd (this a) H₁ theorem dm_forall_not (H : ¬ ∃ a : A, p a) : ∀ a : A, ¬ p a := assume (a : A) (H₁ : p a), have ∃ a : A, p a, from ⟨a, H₁⟩, absurd this H theorem dm_not_exists (H : ∀ a : A, ¬ p a) : ¬ ∃ a : A, p a := suppose ∃ a : A, p a, let ⟨a, (H₁ : p a)⟩ := this in absurd H₁ (H a) end de_morgan_general -- Implication helpers section implies variables {a b : Prop} theorem imp_iff_not_or : a → b ↔ ¬ a ∨ b := iff.intro (assume H : a → b, show ¬ a ∨ b, from by_cases (suppose a, or.inr (H this)) (suppose ¬ a, or.inl this)) (assume (H : ¬ a ∨ b) (Ha : a), H.elim (suppose ¬ a, absurd Ha this) (suppose b, this)) theorem not_imp_iff_and_not : ¬ (a → b) ↔ a ∧ ¬ b := iff.intro (suppose ¬ (a → b), have ¬ (¬ a ∨ b), from mt imp_iff_not_or.mpr this, have ¬ ¬ a ∧ ¬ b, from dm_not_and_not this, show a ∧ ¬ b, from ⟨not_not_elim this.left, this.right⟩) (assume H : a ∧ ¬ b, suppose a → b, absurd (this H.left) H.right) end implies
e28956ce42f8854f44b175df5c0350075745749e
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/inner_product_space/dual.lean
2ec353f8c15f22668e1b02cb4710cf94b2f58d01
[ "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,590
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 analysis.inner_product_space.projection import analysis.normed_space.dual import analysis.normed_space.star.basic /-! # The Fréchet-Riesz representation theorem > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We consider an inner product space `E` over `𝕜`, which is either `ℝ` or `ℂ`. We define `to_dual_map`, a conjugate-linear isometric embedding of `E` into its dual, which maps an element `x` of the space to `λ y, ⟪x, y⟫`. Under the hypothesis of completeness (i.e., for Hilbert spaces), we upgrade this to `to_dual`, a conjugate-linear isometric *equivalence* of `E` onto its dual; that is, we establish the surjectivity of `to_dual_map`. This is the Fréchet-Riesz representation theorem: every element of the dual of a Hilbert space `E` has the form `λ u, ⟪x, u⟫` for some `x : E`. For a bounded sesquilinear form `B : E →L⋆[𝕜] E →L[𝕜] 𝕜`, we define a map `inner_product_space.continuous_linear_map_of_bilin B : E →L[𝕜] E`, given by substituting `E →L[𝕜] 𝕜` with `E` using `to_dual`. ## References * [M. Einsiedler and T. Ward, *Functional Analysis, Spectral Theory, and Applications*] [EinsiedlerWard2017] ## Tags dual, Fréchet-Riesz -/ noncomputable theory open_locale classical complex_conjugate universes u v namespace inner_product_space open is_R_or_C continuous_linear_map variables (𝕜 : Type*) variables (E : Type*) [is_R_or_C 𝕜] [normed_add_comm_group E] [inner_product_space 𝕜 E] local notation `⟪`x`, `y`⟫` := @inner 𝕜 E _ x y local postfix `†`:90 := star_ring_end _ /-- An element `x` of an inner product space `E` induces an element of the dual space `dual 𝕜 E`, the map `λ y, ⟪x, y⟫`; moreover this operation is a conjugate-linear isometric embedding of `E` into `dual 𝕜 E`. If `E` is complete, this operation is surjective, hence a conjugate-linear isometric equivalence; see `to_dual`. -/ def to_dual_map : E →ₗᵢ⋆[𝕜] normed_space.dual 𝕜 E := { norm_map' := innerSL_apply_norm _, ..innerSL 𝕜 } variables {E} @[simp] lemma to_dual_map_apply {x y : E} : to_dual_map 𝕜 E x y = ⟪x, y⟫ := rfl lemma innerSL_norm [nontrivial E] : ‖(innerSL 𝕜 : E →L⋆[𝕜] E →L[𝕜] 𝕜)‖ = 1 := show ‖(to_dual_map 𝕜 E).to_continuous_linear_map‖ = 1, from linear_isometry.norm_to_continuous_linear_map _ variable {𝕜} lemma ext_inner_left_basis {ι : Type*} {x y : E} (b : basis ι 𝕜 E) (h : ∀ i : ι, ⟪b i, x⟫ = ⟪b i, y⟫) : x = y := begin apply (to_dual_map 𝕜 E).map_eq_iff.mp, refine (function.injective.eq_iff continuous_linear_map.coe_injective).mp (basis.ext b _), intro i, simp only [to_dual_map_apply, continuous_linear_map.coe_coe], rw [←inner_conj_symm], nth_rewrite_rhs 0 [←inner_conj_symm], exact congr_arg conj (h i) end lemma ext_inner_right_basis {ι : Type*} {x y : E} (b : basis ι 𝕜 E) (h : ∀ i : ι, ⟪x, b i⟫ = ⟪y, b i⟫) : x = y := begin refine ext_inner_left_basis b (λ i, _), rw [←inner_conj_symm], nth_rewrite_rhs 0 [←inner_conj_symm], exact congr_arg conj (h i) end variables (𝕜) (E) [complete_space E] /-- Fréchet-Riesz representation: any `ℓ` in the dual of a Hilbert space `E` is of the form `λ u, ⟪y, u⟫` for some `y : E`, i.e. `to_dual_map` is surjective. -/ def to_dual : E ≃ₗᵢ⋆[𝕜] normed_space.dual 𝕜 E := linear_isometry_equiv.of_surjective (to_dual_map 𝕜 E) begin intros ℓ, set Y := linear_map.ker ℓ with hY, by_cases htriv : Y = ⊤, { have hℓ : ℓ = 0, { have h' := linear_map.ker_eq_top.mp htriv, rw [←coe_zero] at h', apply coe_injective, exact h' }, exact ⟨0, by simp [hℓ]⟩ }, { rw [← submodule.orthogonal_eq_bot_iff] at htriv, change Yᗮ ≠ ⊥ at htriv, rw [submodule.ne_bot_iff] at htriv, obtain ⟨z : E, hz : z ∈ Yᗮ, z_ne_0 : z ≠ 0⟩ := htriv, refine ⟨((ℓ z)† / ⟪z, z⟫) • z, _⟩, ext x, have h₁ : (ℓ z) • x - (ℓ x) • z ∈ Y, { rw [linear_map.mem_ker, map_sub, continuous_linear_map.map_smul, continuous_linear_map.map_smul, algebra.id.smul_eq_mul, algebra.id.smul_eq_mul, mul_comm], exact sub_self (ℓ x * ℓ z) }, have h₂ : (ℓ z) * ⟪z, x⟫ = (ℓ x) * ⟪z, z⟫, { have h₃ := calc 0 = ⟪z, (ℓ z) • x - (ℓ x) • z⟫ : by { rw [(Y.mem_orthogonal' z).mp hz], exact h₁ } ... = ⟪z, (ℓ z) • x⟫ - ⟪z, (ℓ x) • z⟫ : by rw [inner_sub_right] ... = (ℓ z) * ⟪z, x⟫ - (ℓ x) * ⟪z, z⟫ : by simp [inner_smul_right], exact sub_eq_zero.mp (eq.symm h₃) }, have h₄ := calc ⟪((ℓ z)† / ⟪z, z⟫) • z, x⟫ = (ℓ z) / ⟪z, z⟫ * ⟪z, x⟫ : by simp [inner_smul_left, conj_conj] ... = (ℓ z) * ⟪z, x⟫ / ⟪z, z⟫ : by rw [←div_mul_eq_mul_div] ... = (ℓ x) * ⟪z, z⟫ / ⟪z, z⟫ : by rw [h₂] ... = ℓ x : by field_simp [inner_self_ne_zero.2 z_ne_0], exact h₄ } end variables {𝕜} {E} @[simp] lemma to_dual_apply {x y : E} : to_dual 𝕜 E x y = ⟪x, y⟫ := rfl @[simp] lemma to_dual_symm_apply {x : E} {y : normed_space.dual 𝕜 E} : ⟪(to_dual 𝕜 E).symm y, x⟫ = y x := begin rw ← to_dual_apply, simp only [linear_isometry_equiv.apply_symm_apply], end variables {E 𝕜} /-- Maps a bounded sesquilinear form to its continuous linear map, given by interpreting the form as a map `B : E →L⋆[𝕜] normed_space.dual 𝕜 E` and dualizing the result using `to_dual`. -/ def continuous_linear_map_of_bilin (B : E →L⋆[𝕜] E →L[𝕜] 𝕜) : E →L[𝕜] E := comp (to_dual 𝕜 E).symm.to_continuous_linear_equiv.to_continuous_linear_map B local postfix `♯`:1025 := continuous_linear_map_of_bilin variables (B : E →L⋆[𝕜] E →L[𝕜] 𝕜) @[simp] lemma continuous_linear_map_of_bilin_apply (v w : E) : ⟪(B♯ v), w⟫ = B v w := by simp [continuous_linear_map_of_bilin] lemma unique_continuous_linear_map_of_bilin {v f : E} (is_lax_milgram : (∀ w, ⟪f, w⟫ = B v w)) : f = B♯ v := begin refine ext_inner_right 𝕜 _, intro w, rw continuous_linear_map_of_bilin_apply, exact is_lax_milgram w, end end inner_product_space
cb12dd4fe5914b6e7aca514b03df45ddb1d9521c
a4673261e60b025e2c8c825dfa4ab9108246c32e
/src/Std/Data/HashMap.lean
a471717cd7d4a6b0facc11e0e93a5d16a0b5eab1
[ "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
7,225
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ import Std.Data.AssocList namespace Std universes u v w def HashMapBucket (α : Type u) (β : Type v) := { b : Array (AssocList α β) // b.size > 0 } def HashMapBucket.update {α : Type u} {β : Type v} (data : HashMapBucket α β) (i : USize) (d : AssocList α β) (h : i.toNat < data.val.size) : HashMapBucket α β := ⟨ data.val.uset i d h, by erw [Array.sizeSetEq]; exact data.property ⟩ structure HashMapImp (α : Type u) (β : Type v) := (size : Nat) (buckets : HashMapBucket α β) def mkHashMapImp {α : Type u} {β : Type v} (nbuckets := 8) : HashMapImp α β := let n := if nbuckets = 0 then 8 else nbuckets; { size := 0, buckets := ⟨ mkArray n AssocList.nil, by rw [Array.sizeMkArrayEq]; cases nbuckets; decide!; apply Nat.zeroLtSucc; done ⟩ } namespace HashMapImp variables {α : Type u} {β : Type v} def mkIdx {n : Nat} (h : n > 0) (u : USize) : { u : USize // u.toNat < n } := ⟨u %ₙ n, USize.modnLt _ h⟩ @[inline] def reinsertAux (hashFn : α → USize) (data : HashMapBucket α β) (a : α) (b : β) : HashMapBucket α β := let ⟨i, h⟩ := mkIdx data.property (hashFn a) data.update i (AssocList.cons a b (data.val.uget i h)) h @[inline] def foldBucketsM {δ : Type w} {m : Type w → Type w} [Monad m] (data : HashMapBucket α β) (d : δ) (f : δ → α → β → m δ) : m δ := data.val.foldlM (init := d) fun d b => b.foldlM f d @[inline] def foldBuckets {δ : Type w} (data : HashMapBucket α β) (d : δ) (f : δ → α → β → δ) : δ := Id.run $ foldBucketsM data d f @[inline] def foldM {δ : Type w} {m : Type w → Type w} [Monad m] (f : δ → α → β → m δ) (d : δ) (h : HashMapImp α β) : m δ := foldBucketsM h.buckets d f @[inline] def fold {δ : Type w} (f : δ → α → β → δ) (d : δ) (m : HashMapImp α β) : δ := foldBuckets m.buckets d f def findEntry? [BEq α] [Hashable α] (m : HashMapImp α β) (a : α) : Option (α × β) := match m with | ⟨_, buckets⟩ => let ⟨i, h⟩ := mkIdx buckets.property (hash a) (buckets.val.uget i h).findEntry? a def find? [BEq α] [Hashable α] (m : HashMapImp α β) (a : α) : Option β := match m with | ⟨_, buckets⟩ => let ⟨i, h⟩ := mkIdx buckets.property (hash a) (buckets.val.uget i h).find? a def contains [BEq α] [Hashable α] (m : HashMapImp α β) (a : α) : Bool := match m with | ⟨_, buckets⟩ => let ⟨i, h⟩ := mkIdx buckets.property (hash a) (buckets.val.uget i h).contains a -- TODO: remove `partial` by using well-founded recursion partial def moveEntries [Hashable α] (i : Nat) (source : Array (AssocList α β)) (target : HashMapBucket α β) : HashMapBucket α β := if h : i < source.size then let idx : Fin source.size := ⟨i, h⟩ let es : AssocList α β := source.get idx -- We remove `es` from `source` to make sure we can reuse its memory cells when performing es.foldl let source := source.set idx AssocList.nil let target := es.foldl (reinsertAux hash) target moveEntries (i+1) source target else target def expand [Hashable α] (size : Nat) (buckets : HashMapBucket α β) : HashMapImp α β := let nbuckets := buckets.val.size * 2 have nbuckets > 0 from Nat.mulPos buckets.property (decide! : 2 > 0) let new_buckets : HashMapBucket α β := ⟨mkArray nbuckets AssocList.nil, by rw [Array.sizeMkArrayEq]; assumption⟩ { size := size, buckets := moveEntries 0 buckets.val new_buckets } def insert [BEq α] [Hashable α] (m : HashMapImp α β) (a : α) (b : β) : HashMapImp α β := match m with | ⟨size, buckets⟩ => let ⟨i, h⟩ := mkIdx buckets.property (hash a) let bkt := buckets.val.uget i h if bkt.contains a then ⟨size, buckets.update i (bkt.replace a b) h⟩ else let size' := size + 1 let buckets' := buckets.update i (AssocList.cons a b bkt) h if size' ≤ buckets.val.size then { size := size', buckets := buckets' } else expand size' buckets' def erase [BEq α] [Hashable α] (m : HashMapImp α β) (a : α) : HashMapImp α β := match m with | ⟨ size, buckets ⟩ => let ⟨i, h⟩ := mkIdx buckets.property (hash a) let bkt := buckets.val.uget i h if bkt.contains a then ⟨size - 1, buckets.update i (bkt.erase a) h⟩ else m inductive WellFormed [BEq α] [Hashable α] : HashMapImp α β → Prop := | mkWff : ∀ n, WellFormed (mkHashMapImp n) | insertWff : ∀ m a b, WellFormed m → WellFormed (insert m a b) | eraseWff : ∀ m a, WellFormed m → WellFormed (erase m a) end HashMapImp def HashMap (α : Type u) (β : Type v) [BEq α] [Hashable α] := { m : HashMapImp α β // m.WellFormed } open Std.HashMapImp def mkHashMap {α : Type u} {β : Type v} [BEq α] [Hashable α] (nbuckets := 8) : HashMap α β := ⟨ mkHashMapImp nbuckets, WellFormed.mkWff nbuckets ⟩ namespace HashMap variables {α : Type u} {β : Type v} [BEq α] [Hashable α] instance : Inhabited (HashMap α β) := ⟨mkHashMap⟩ instance : EmptyCollection (HashMap α β) := ⟨mkHashMap⟩ @[inline] def insert (m : HashMap α β) (a : α) (b : β) : HashMap α β := match m with | ⟨ m, hw ⟩ => ⟨ m.insert a b, WellFormed.insertWff m a b hw ⟩ @[inline] def erase (m : HashMap α β) (a : α) : HashMap α β := match m with | ⟨ m, hw ⟩ => ⟨ m.erase a, WellFormed.eraseWff m a hw ⟩ @[inline] def findEntry? (m : HashMap α β) (a : α) : Option (α × β) := match m with | ⟨ m, _ ⟩ => m.findEntry? a @[inline] def find? (m : HashMap α β) (a : α) : Option β := match m with | ⟨ m, _ ⟩ => m.find? a @[inline] def findD (m : HashMap α β) (a : α) (b₀ : β) : β := (m.find? a).getD b₀ @[inline] def find! [Inhabited β] (m : HashMap α β) (a : α) : β := match m.find? a with | some b => b | none => panic! "key is not in the map" @[inline] def getOp (self : HashMap α β) (idx : α) : Option β := self.find? idx @[inline] def contains (m : HashMap α β) (a : α) : Bool := match m with | ⟨ m, _ ⟩ => m.contains a @[inline] def foldM {δ : Type w} {m : Type w → Type w} [Monad m] (f : δ → α → β → m δ) (init : δ) (h : HashMap α β) : m δ := match h with | ⟨ h, _ ⟩ => h.foldM f init @[inline] def fold {δ : Type w} (f : δ → α → β → δ) (init : δ) (m : HashMap α β) : δ := match m with | ⟨ m, _ ⟩ => m.fold f init @[inline] def size (m : HashMap α β) : Nat := match m with | ⟨ {size := sz, ..}, _ ⟩ => sz @[inline] def isEmpty (m : HashMap α β) : Bool := m.size = 0 @[inline] def empty : HashMap α β := mkHashMap def toList (m : HashMap α β) : List (α × β) := m.fold (init := []) fun r k v => (k, v)::r def toArray (m : HashMap α β) : Array (α × β) := m.fold (init := #[]) fun r k v => r.push (k, v) def numBuckets (m : HashMap α β) : Nat := m.val.buckets.val.size end HashMap end Std
8aee1c04718c832e1ebc9e069173ace6fe19efc9
83c8119e3298c0bfc53fc195c41a6afb63d01513
/tests/lean/run/1685.lean
01168980384d8a08e3437cae43f26cc7970ae2e7
[ "Apache-2.0" ]
permissive
anfelor/lean
584b91c4e87a6d95f7630c2a93fb082a87319ed0
31cfc2b6bf7d674f3d0f73848b842c9c9869c9f1
refs/heads/master
1,610,067,141,310
1,585,992,232,000
1,585,992,232,000
251,683,543
0
0
Apache-2.0
1,585,676,570,000
1,585,676,569,000
null
UTF-8
Lean
false
false
2,668
lean
local attribute [simp] add_comm add_left_comm /- This test assumes the total order on terms used by simp compares local constants using the order they appear in the local context. -/ example (m : ℕ) : ∀ n k, m + n = k → n + m = k := by intros; simp; assumption example (m : ℕ) : ∀ n k, m + n = k → n + m = k := by intros; simp; assumption example (m : ℕ) : ∀ n k, m + n = k → n + m = k := by intros; simp; assumption example (m : ℕ) : ∀ n k, m + n = k → n + m = k := by intros; simp; assumption example (m : ℕ) : ∀ n k, m + n = k → n + m = k := by intros; simp; assumption example (m : ℕ) : ∀ n k, m + n = k → n + m = k := by intros; simp; assumption example (m : ℕ) : ∀ n k, m + n = k → n + m = k := by intros; simp; assumption example (m : ℕ) : ∀ n k, m + n = k → n + m = k := by intros; simp; assumption example (m : ℕ) : ∀ n k, m + n = k → n + m = k := by intros; simp; assumption example (m : ℕ) : ∀ n k, m + n = k → n + m = k := by intros; simp; assumption example (m : ℕ) : ∀ n k, m + n = k → n + m = k := by intros; simp; assumption example (m : ℕ) : ∀ n k, m + n = k → n + m = k := by intros; simp; assumption example (m : ℕ) : ∀ n k, m + n = k → n + m = k := by intros; simp; assumption example (m : ℕ) : ∀ n k, m + n = k → n + m = k := by intros; simp; assumption example (m : ℕ) : ∀ n k, m + n = k → n + m = k := by intros; simp; assumption example (m : ℕ) : ∀ n k, m + n = k → n + m = k := by intros; simp; assumption example (m : ℕ) : ∀ n k, m + n = k → n + m = k := by intros; simp; assumption example (m : ℕ) : ∀ n k, n + m = k → n + m = k := begin intros, simp, fail_if_success {assumption}, admit end example (m : ℕ) : ∀ n k, n + m = k → n + m = k := begin intros, simp, fail_if_success {assumption}, admit end example (m : ℕ) : ∀ n k, n + m = k → n + m = k := begin intros, simp, fail_if_success {assumption}, admit end example (m : ℕ) : ∀ n k, n + m = k → n + m = k := begin intros, simp, fail_if_success {assumption}, admit end example (m : ℕ) : ∀ n k, n + m = k → n + m = k := begin intros, simp, fail_if_success {assumption}, admit end example (m : ℕ) : ∀ n k, n + m = k → n + m = k := begin intros, simp, fail_if_success {assumption}, admit end example (m : ℕ) : ∀ n k, n + m = k → n + m = k := begin intros, simp, fail_if_success {assumption}, admit end example (m : ℕ) : ∀ n k, n + m = k → n + m = k := begin intros, simp, fail_if_success {assumption}, admit end example (m : ℕ) : ∀ n k, n + m = k → n + m = k := begin intros, simp, fail_if_success {assumption}, admit end
0bc3f0dd5476439ed8e9ffa604df545f4d565561
29fc903502a2f31a2009389392484557342601fe
/src/data-as-subsets.lean
0084ff665666329eb4d4d39e8c2d8bd586757782
[]
no_license
NicolasRouquette/digraphs
9a7ed10ce54ce3d60983db153624d33e47391f8f
c6a88abc2565b0b25a0b3a93665d4b285c79e51b
refs/heads/master
1,673,439,036,710
1,604,799,582,000
1,604,799,582,000
310,965,050
0
0
null
null
null
null
UTF-8
Lean
false
false
1,957
lean
import .graph -- The list of unique vertex identifiers. def vs : list string := ["a", "b", "c", "d"] def isV (s: string) : Prop := s ∈ vs -- vT is the set of strings that are vertex identifiers. -- Defining vT as a subtype, {s:string // isV s}, would require defining a -- typeclass instance for has_lift_t vT string def vT := {s:string | isV s} -- The elements of vT are pairs: a string s and a proof that it satisfies isV s def vt_a : vT := ⟨ "a", begin refine list.nth_mem _, let n := 0, exact n, exact rfl, end⟩ def vt_b : vT := ⟨ "b", begin refine list.nth_mem _, let n := 1, exact n, exact rfl, end⟩ def vt_c : vT := ⟨ "c", begin refine list.nth_mem _, let n := 2, exact n, exact rfl, end⟩ def vt_d : vT := ⟨ "d", begin refine list.nth_mem _, let n := 3, exact n, exact rfl, end⟩ -- The list of unique edge identifiers. def es : list string := [ "e1", "e2", "e3" ] def isE (e: string) : Prop := e ∈ es -- eT is the set of strings that are edge identifiers. -- Defining eT as a subtype, {s:string // isE s}, would require defining a -- typeclass instance for has_lift_t eT string def eT := { e:string | isE e } -- The elements of eT are pairs: a string s and a proof that it satisfies isE s def e1 : eT := ⟨ "e1", begin refine list.nth_mem _, let n := 0, exact n, exact rfl, end ⟩ def e2 : eT := ⟨ "e2", begin refine list.nth_mem _, let n := 1, exact n, exact rfl, end ⟩ def e3 : eT := ⟨ "e3", begin refine list.nth_mem _, let n := 2, exact n, exact rfl, end ⟩ -- The type of directed graphs with vertices in vT and edges in eT def gT := digraph vT eT def arc1 : arcT vT := arcT.mk vt_a vt_b def arc2 : arcT vT := arcT.mk vt_a vt_c def arc3 : arcT vT := arcT.mk vt_c vt_d def phi1: eT → arcT vT | e1 := arc1 def g1 : gT := digraph.mk phi1 def e1_source := digraph.source g1 e1 #eval e1_source -- result: "a" def phi2: eT → arcT vT | e1 := arc1 | e2 := arc2 | e3 := arc3 def g2 : gT := digraph.mk phi2
9377d5f26f5446b90e6e032da28c8bf7d22ba4c5
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/category/Group/preadditive.lean
1781af908eea897661f865c27bb7d8feb9dc6432
[]
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
589
lean
/- Copyright (c) 2020 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.category.Group.basic import Mathlib.category_theory.preadditive.default import Mathlib.PostPort universes u_1 namespace Mathlib /-! # The category of additive commutative groups is preadditive. -/ namespace AddCommGroup protected instance category_theory.preadditive : category_theory.preadditive AddCommGroup := category_theory.preadditive.mk
0870ff6f7b50722a4859f7d4a1d7f41886a8c0bf
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/category/Module/abelian.lean
58fc622a4d82550b42bc5a775aee7abafb9ff2e7
[ "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
4,125
lean
/- Copyright (c) 2020 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import linear_algebra.isomorphisms import algebra.category.Module.kernels import algebra.category.Module.limits import category_theory.abelian.exact /-! # The category of left R-modules is abelian. Additionally, two linear maps are exact in the categorical sense iff `range f = ker g`. -/ open category_theory open category_theory.limits noncomputable theory universes w v u namespace Module variables {R : Type u} [ring R] {M N : Module.{v} R} (f : M ⟶ N) /-- In the category of modules, every monomorphism is normal. -/ def normal_mono (hf : mono f) : normal_mono f := { Z := of R (N ⧸ f.range), g := f.range.mkq, w := linear_map.range_mkq_comp _, is_limit := is_kernel.iso_kernel _ _ (kernel_is_limit _) /- The following [invalid Lean code](https://github.com/leanprover-community/lean/issues/341) might help you understand what's going on here: ``` calc M ≃ₗ[R] f.ker.quotient : (submodule.quot_equiv_of_eq_bot _ (ker_eq_bot_of_mono _)).symm ... ≃ₗ[R] f.range : linear_map.quot_ker_equiv_range f ... ≃ₗ[R] r.range.mkq.ker : linear_equiv.of_eq _ _ (submodule.ker_mkq _).symm ``` -/ (linear_equiv.to_Module_iso' ((submodule.quot_equiv_of_eq_bot _ (ker_eq_bot_of_mono _)).symm ≪≫ₗ ((linear_map.quot_ker_equiv_range f) ≪≫ₗ (linear_equiv.of_eq _ _ (submodule.ker_mkq _).symm)))) $ by { ext, refl } } /-- In the category of modules, every epimorphism is normal. -/ def normal_epi (hf : epi f) : normal_epi f := { W := of R f.ker, g := f.ker.subtype, w := linear_map.comp_ker_subtype _, is_colimit := is_cokernel.cokernel_iso _ _ (cokernel_is_colimit _) (linear_equiv.to_Module_iso' /- The following invalid Lean code might help you understand what's going on here: ``` calc f.ker.subtype.range.quotient ≃ₗ[R] f.ker.quotient : submodule.quot_equiv_of_eq _ _ (submodule.range_subtype _) ... ≃ₗ[R] f.range : linear_map.quot_ker_equiv_range f ... ≃ₗ[R] N : linear_equiv.of_top _ (range_eq_top_of_epi _) ``` -/ (((submodule.quot_equiv_of_eq _ _ (submodule.range_subtype _)) ≪≫ₗ (linear_map.quot_ker_equiv_range f)) ≪≫ₗ (linear_equiv.of_top _ (range_eq_top_of_epi _)))) $ by { ext, refl } } /-- The category of R-modules is abelian. -/ instance : abelian (Module R) := { has_finite_products := ⟨λ n, limits.has_limits_of_shape_of_has_limits⟩, has_kernels := limits.has_kernels_of_has_equalizers (Module R), has_cokernels := has_cokernels_Module, normal_mono_of_mono := λ X Y, normal_mono, normal_epi_of_epi := λ X Y, normal_epi } section reflects_limits /- We need to put this in this weird spot because we need to know that the category of modules is balanced. -/ instance forget_reflects_limits_of_size : reflects_limits_of_size.{v v} (forget (Module.{max v w} R)) := reflects_limits_of_reflects_isomorphisms instance forget₂_reflects_limits_of_size : reflects_limits_of_size.{v v} (forget₂ (Module.{max v w} R) AddCommGroup.{max v w}) := reflects_limits_of_reflects_isomorphisms instance forget_reflects_limits : reflects_limits (forget (Module.{v} R)) := Module.forget_reflects_limits_of_size.{v v} instance forget₂_reflects_limits : reflects_limits (forget₂ (Module.{v} R) AddCommGroup.{v}) := Module.forget₂_reflects_limits_of_size.{v v} end reflects_limits variables {O : Module.{v} R} (g : N ⟶ O) open linear_map local attribute [instance] preadditive.has_equalizers_of_has_kernels theorem exact_iff : exact f g ↔ f.range = g.ker := begin rw abelian.exact_iff' f g (kernel_is_limit _) (cokernel_is_colimit _), exact ⟨λ h, le_antisymm (range_le_ker_iff.2 h.1) (ker_le_range_iff.2 h.2), λ h, ⟨range_le_ker_iff.1 $ le_of_eq h, ker_le_range_iff.1 $ le_of_eq h.symm⟩⟩ end end Module
2b8949675018509a27dfc9d3d41810938472c617
3d2a7f1582fe5bae4d0bdc2fe86e997521239a65
/spatial-reasoning/spatial-reasoning-problem-10.lean
d6960d8c0dbaf490b0cdfb343568a41e9be7c3ea
[]
no_license
own-pt/common-sense-lean
e4fa643ae010459de3d1bf673be7cbc7062563c9
f672210aecb4172f5bae265e43e6867397e13b1c
refs/heads/master
1,622,065,660,261
1,589,487,533,000
1,589,487,533,000
254,167,782
3
2
null
1,589,487,535,000
1,586,370,214,000
Lean
UTF-8
Lean
false
false
177
lean
/- Spatial Reasoning Problem 10 -/ /- It can be found at: SpatialQs.txt -/ /- (10) John is 6' tall. John is lying on the floor. How far is John's head from the floor? -/
3cf345be56a3e55b67b1d5c27fa9c64f9c7ebaf2
4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d
/stage0/src/Lean/Data/Json/FromToJson.lean
ffb4e884356068d2dbdb330053635d1755d6c4b5
[ "Apache-2.0" ]
permissive
subfish-zhou/leanprover-zh_CN.github.io
30b9fba9bd790720bd95764e61ae796697d2f603
8b2985d4a3d458ceda9361ac454c28168d920d3f
refs/heads/master
1,689,709,967,820
1,632,503,056,000
1,632,503,056,000
409,962,097
1
0
null
null
null
null
UTF-8
Lean
false
false
4,960
lean
/- Copyright (c) 2019 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner, Marc Huisinga -/ import Lean.Data.Json.Basic import Lean.Data.Json.Printer namespace Lean universe u class FromJson (α : Type u) where fromJson? : Json → Except String α export FromJson (fromJson?) class ToJson (α : Type u) where toJson : α → Json export ToJson (toJson) instance : FromJson Json := ⟨Except.ok⟩ instance : ToJson Json := ⟨id⟩ instance : FromJson JsonNumber := ⟨Json.getNum?⟩ instance : ToJson JsonNumber := ⟨Json.num⟩ -- looks like id, but there are coercions happening instance : FromJson Bool := ⟨Json.getBool?⟩ instance : ToJson Bool := ⟨fun b => b⟩ instance : FromJson Nat := ⟨Json.getNat?⟩ instance : ToJson Nat := ⟨fun n => n⟩ instance : FromJson Int := ⟨Json.getInt?⟩ instance : ToJson Int := ⟨fun n => Json.num n⟩ instance : FromJson String := ⟨Json.getStr?⟩ instance : ToJson String := ⟨fun s => s⟩ instance [FromJson α] : FromJson (Array α) where fromJson? | Json.arr a => a.mapM fromJson? | j => throw s!"expected JSON array, got '{j}'" instance [ToJson α] : ToJson (Array α) := ⟨fun a => Json.arr (a.map toJson)⟩ instance [FromJson α] : FromJson (Option α) where fromJson? | Json.null => Except.ok none | j => some <$> fromJson? j instance [ToJson α] : ToJson (Option α) := ⟨fun | none => Json.null | some a => toJson a⟩ instance [FromJson α] [FromJson β] : FromJson (α × β) where fromJson? | Json.arr #[ja, jb] => do let a ← fromJson? ja let b ← fromJson? jb return (a, b) | j => throw s!"expected pair, got '{j}'" instance [ToJson α] [ToJson β] : ToJson (α × β) where toJson := fun (a, b) => Json.arr #[toJson a, toJson b] instance : FromJson Name where fromJson? j := do let s ← j.getStr? if s == "[anonymous]" then return Name.anonymous else let some n ← Syntax.decodeNameLit ("`" ++ s) | throw s!"expected a `Name`, got '{j}'" return n instance : ToJson Name where toJson n := toString n /- Note that `USize`s and `UInt64`s are stored as strings because JavaScript cannot represent 64-bit numbers. -/ def bignumFromJson? (j : Json) : Except String Nat := do let s ← j.getStr? let some v ← Syntax.decodeNatLitVal? s -- TODO maybe this should be in Std | throw s!"expected a string-encoded number, got '{j}'" return v def bignumToJson (n : Nat) : Json := toString n instance : FromJson USize where fromJson? j := do let n ← bignumFromJson? j if n ≥ USize.size then throw "value '{j}' is too large for `USize`" return USize.ofNat n instance : ToJson USize where toJson v := bignumToJson (USize.toNat v) instance : FromJson UInt64 where fromJson? j := do let n ← bignumFromJson? j if n ≥ UInt64.size then throw "value '{j}' is too large for `UInt64`" return UInt64.ofNat n instance : ToJson UInt64 where toJson v := bignumToJson (UInt64.toNat v) namespace Json instance : FromJson Structured := ⟨fun | arr a => Structured.arr a | obj o => Structured.obj o | j => throw s!"expected structured object, got '{j}'"⟩ instance : ToJson Structured := ⟨fun | Structured.arr a => arr a | Structured.obj o => obj o⟩ def toStructured? [ToJson α] (v : α) : Except String Structured := fromJson? (toJson v) def getObjValAs? (j : Json) (α : Type u) [FromJson α] (k : String) : Except String α := fromJson? <| j.getObjValD k def opt [ToJson α] (k : String) : Option α → List (String × Json) | none => [] | some o => [⟨k, toJson o⟩] /-- Parses a JSON-encoded `structure` or `inductive` constructor. Used mostly by `deriving FromJson`. -/ def parseTagged (json : Json) (tag : String) (nFields : Nat) (fieldNames? : Option (Array Name)) : Except String (Array Json) := if nFields == 0 then match getStr? json with | Except.ok s => if s == tag then Except.ok #[] else throw s!"incorrect tag: {s} ≟ {tag}" | Except.error err => Except.error err else match getObjVal? json tag with | Except.ok payload => match fieldNames? with | some fieldNames => do let mut fields := #[] for fieldName in fieldNames do fields := fields.push (←getObjVal? payload fieldName.getString!) Except.ok fields | none => if nFields == 1 then Except.ok #[payload] else match getArr? payload with | Except.ok fields => if fields.size == nFields then Except.ok fields else Except.error s!"incorrect number of fields: {fields.size} ≟ {nFields}" | Except.error err => Except.error err | Except.error err => Except.error err end Json end Lean
b0632cb74506b358a8eeac0e0a1e4fb7bb150ab6
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/util.lean
3833257282f7a6166df8f4e3a83a01735a086530
[]
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,012
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 -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.meta.format universes u namespace Mathlib /-- This function has a native implementation that tracks time. -/ def timeit {α : Type u} (s : string) (f : thunk α) : α := f Unit.unit /-- This function has a native implementation that displays the given string in the regular output stream. -/ def trace {α : Type u} (s : string) (f : thunk α) : α := f Unit.unit /-- This function has a native implementation that shows the VM call stack. -/ def trace_call_stack {α : Type u} (f : thunk α) : α := f Unit.unit /-- This function has a native implementation that displays in the given position all trace messages used in f. The arguments line and col are filled by the elaborator. -/ def scope_trace {α : Type u} {line : ℕ} {col : ℕ} (f : thunk α) : α := f Unit.unit
f1fac32729046f7d2e21a4f1381f55b62e9dcb02
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/lean/classBadOutParam.lean
3c22148d3ed05b7a8f0b1035504c3f1c3f8bbe30
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
202
lean
class C1 (x : outParam Nat) (y : { n : Nat // n > x }) (α : Type) := -- should fail (val : α) class C2 (x : outParam Nat) (y : outParam { n : Nat // n > x }) (α : Type) := -- should work (val : α)
b62e3f8119773804ec95c1e323d9ecc24bf84bee
94e33a31faa76775069b071adea97e86e218a8ee
/src/topology/algebra/module/multilinear.lean
adf47d257ac27968eb707df19cbe5cd85c3fd0b1
[ "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
21,067
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import topology.algebra.module.basic import linear_algebra.multilinear.basic /-! # Continuous multilinear maps We define continuous multilinear maps as maps from `Π(i : ι), M₁ i` to `M₂` which are multilinear and continuous, by extending the space of multilinear maps with a continuity assumption. Here, `M₁ i` and `M₂` are modules over a ring `R`, and `ι` is an arbitrary type, and all these spaces are also topological spaces. ## Main definitions * `continuous_multilinear_map R M₁ M₂` is the space of continuous multilinear maps from `Π(i : ι), M₁ i` to `M₂`. We show that it is an `R`-module. ## Implementation notes We mostly follow the API of multilinear maps. ## Notation We introduce the notation `M [×n]→L[R] M'` for the space of continuous `n`-multilinear maps from `M^n` to `M'`. This is a particular case of the general notion (where we allow varying dependent types as the arguments of our continuous multilinear maps), but arguably the most important one, especially when defining iterated derivatives. -/ open function fin set open_locale big_operators universes u v w w₁ w₁' w₂ w₃ w₄ variables {R : Type u} {ι : Type v} {n : ℕ} {M : fin n.succ → Type w} {M₁ : ι → Type w₁} {M₁' : ι → Type w₁'} {M₂ : Type w₂} {M₃ : Type w₃} {M₄ : Type w₄} [decidable_eq ι] /-- Continuous multilinear maps over the ring `R`, from `Πi, M₁ i` to `M₂` where `M₁ i` and `M₂` are modules over `R` with a topological structure. In applications, there will be compatibility conditions between the algebraic and the topological structures, but this is not needed for the definition. -/ structure continuous_multilinear_map (R : Type u) {ι : Type v} (M₁ : ι → Type w₁) (M₂ : Type w₂) [decidable_eq ι] [semiring R] [∀i, add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [∀i, module R (M₁ i)] [module R M₂] [∀i, topological_space (M₁ i)] [topological_space M₂] extends multilinear_map R M₁ M₂ := (cont : continuous to_fun) notation M `[×`:25 n `]→L[`:25 R `] ` M' := continuous_multilinear_map R (λ (i : fin n), M) M' namespace continuous_multilinear_map section semiring variables [semiring R] [Πi, add_comm_monoid (M i)] [Πi, add_comm_monoid (M₁ i)] [Πi, add_comm_monoid (M₁' i)] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] [Π i, module R (M i)] [Π i, module R (M₁ i)] [Π i, module R (M₁' i)] [module R M₂] [module R M₃] [module R M₄] [Π i, topological_space (M i)] [Π i, topological_space (M₁ i)] [Π i, topological_space (M₁' i)] [topological_space M₂] [topological_space M₃] [topological_space M₄] (f f' : continuous_multilinear_map R M₁ M₂) instance : has_coe_to_fun (continuous_multilinear_map R M₁ M₂) (λ _, (Π i, M₁ i) → M₂) := ⟨λ f, f.to_fun⟩ /-- See Note [custom simps projection]. We need to specify this projection explicitly in this case, because it is a composition of multiple projections. -/ def simps.apply (L₁ : continuous_multilinear_map R M₁ M₂) (v : Π i, M₁ i) : M₂ := L₁ v initialize_simps_projections continuous_multilinear_map (-to_multilinear_map, to_multilinear_map_to_fun → apply) @[continuity] lemma coe_continuous : continuous (f : (Π i, M₁ i) → M₂) := f.cont @[simp] lemma coe_coe : (f.to_multilinear_map : (Π i, M₁ i) → M₂) = f := rfl theorem to_multilinear_map_inj : function.injective (continuous_multilinear_map.to_multilinear_map : continuous_multilinear_map R M₁ M₂ → multilinear_map R M₁ M₂) | ⟨f, hf⟩ ⟨g, hg⟩ rfl := rfl @[ext] theorem ext {f f' : continuous_multilinear_map R M₁ M₂} (H : ∀ x, f x = f' x) : f = f' := to_multilinear_map_inj $ multilinear_map.ext H @[simp] lemma map_add (m : Πi, M₁ i) (i : ι) (x y : M₁ i) : f (update m i (x + y)) = f (update m i x) + f (update m i y) := f.map_add' m i x y @[simp] lemma map_smul (m : Πi, M₁ i) (i : ι) (c : R) (x : M₁ i) : f (update m i (c • x)) = c • f (update m i x) := f.map_smul' m i c x lemma map_coord_zero {m : Πi, M₁ i} (i : ι) (h : m i = 0) : f m = 0 := f.to_multilinear_map.map_coord_zero i h @[simp] lemma map_zero [nonempty ι] : f 0 = 0 := f.to_multilinear_map.map_zero instance : has_zero (continuous_multilinear_map R M₁ M₂) := ⟨{ cont := continuous_const, ..(0 : multilinear_map R M₁ M₂) }⟩ instance : inhabited (continuous_multilinear_map R M₁ M₂) := ⟨0⟩ @[simp] lemma zero_apply (m : Πi, M₁ i) : (0 : continuous_multilinear_map R M₁ M₂) m = 0 := rfl @[simp] lemma to_multilinear_map_zero : (0 : continuous_multilinear_map R M₁ M₂).to_multilinear_map = 0 := rfl section has_smul variables {R' R'' A : Type*} [monoid R'] [monoid R''] [semiring A] [Π i, module A (M₁ i)] [module A M₂] [distrib_mul_action R' M₂] [has_continuous_const_smul R' M₂] [smul_comm_class A R' M₂] [distrib_mul_action R'' M₂] [has_continuous_const_smul R'' M₂] [smul_comm_class A R'' M₂] instance : has_smul R' (continuous_multilinear_map A M₁ M₂) := ⟨λ c f, { cont := f.cont.const_smul c, .. c • f.to_multilinear_map }⟩ @[simp] lemma smul_apply (f : continuous_multilinear_map A M₁ M₂) (c : R') (m : Πi, M₁ i) : (c • f) m = c • f m := rfl @[simp] lemma to_multilinear_map_smul (c : R') (f : continuous_multilinear_map A M₁ M₂) : (c • f).to_multilinear_map = c • f.to_multilinear_map := rfl instance [smul_comm_class R' R'' M₂] : smul_comm_class R' R'' (continuous_multilinear_map A M₁ M₂) := ⟨λ c₁ c₂ f, ext $ λ x, smul_comm _ _ _⟩ instance [has_smul R' R''] [is_scalar_tower R' R'' M₂] : is_scalar_tower R' R'' (continuous_multilinear_map A M₁ M₂) := ⟨λ c₁ c₂ f, ext $ λ x, smul_assoc _ _ _⟩ instance [distrib_mul_action R'ᵐᵒᵖ M₂] [is_central_scalar R' M₂] : is_central_scalar R' (continuous_multilinear_map A M₁ M₂) := ⟨λ c₁ f, ext $ λ x, op_smul_eq_smul _ _⟩ instance : mul_action R' (continuous_multilinear_map A M₁ M₂) := function.injective.mul_action to_multilinear_map to_multilinear_map_inj (λ _ _, rfl) end has_smul section has_continuous_add variable [has_continuous_add M₂] instance : has_add (continuous_multilinear_map R M₁ M₂) := ⟨λ f f', ⟨f.to_multilinear_map + f'.to_multilinear_map, f.cont.add f'.cont⟩⟩ @[simp] lemma add_apply (m : Πi, M₁ i) : (f + f') m = f m + f' m := rfl @[simp] lemma to_multilinear_map_add (f g : continuous_multilinear_map R M₁ M₂) : (f + g).to_multilinear_map = f.to_multilinear_map + g.to_multilinear_map := rfl instance add_comm_monoid : add_comm_monoid (continuous_multilinear_map R M₁ M₂) := to_multilinear_map_inj.add_comm_monoid _ rfl (λ _ _, rfl) (λ _ _, rfl) /-- Evaluation of a `continuous_multilinear_map` at a vector as an `add_monoid_hom`. -/ def apply_add_hom (m : Π i, M₁ i) : continuous_multilinear_map R M₁ M₂ →+ M₂ := ⟨λ f, f m, rfl, λ _ _, rfl⟩ @[simp] lemma sum_apply {α : Type*} (f : α → continuous_multilinear_map R M₁ M₂) (m : Πi, M₁ i) {s : finset α} : (∑ a in s, f a) m = ∑ a in s, f a m := (apply_add_hom m).map_sum f s end has_continuous_add /-- If `f` is a continuous multilinear map, then `f.to_continuous_linear_map m i` is the continuous linear map obtained by fixing all coordinates but `i` equal to those of `m`, and varying the `i`-th coordinate. -/ def to_continuous_linear_map (m : Πi, M₁ i) (i : ι) : M₁ i →L[R] M₂ := { cont := f.cont.comp (continuous_const.update i continuous_id), .. f.to_multilinear_map.to_linear_map m i } /-- The cartesian product of two continuous multilinear maps, as a continuous multilinear map. -/ def prod (f : continuous_multilinear_map R M₁ M₂) (g : continuous_multilinear_map R M₁ M₃) : continuous_multilinear_map R M₁ (M₂ × M₃) := { cont := f.cont.prod_mk g.cont, .. f.to_multilinear_map.prod g.to_multilinear_map } @[simp] lemma prod_apply (f : continuous_multilinear_map R M₁ M₂) (g : continuous_multilinear_map R M₁ M₃) (m : Πi, M₁ i) : (f.prod g) m = (f m, g m) := rfl /-- Combine a family of continuous multilinear maps with the same domain and codomains `M' i` into a continuous multilinear map taking values in the space of functions `Π i, M' i`. -/ def pi {ι' : Type*} {M' : ι' → Type*} [Π i, add_comm_monoid (M' i)] [Π i, topological_space (M' i)] [Π i, module R (M' i)] (f : Π i, continuous_multilinear_map R M₁ (M' i)) : continuous_multilinear_map R M₁ (Π i, M' i) := { cont := continuous_pi $ λ i, (f i).coe_continuous, to_multilinear_map := multilinear_map.pi (λ i, (f i).to_multilinear_map) } @[simp] lemma coe_pi {ι' : Type*} {M' : ι' → Type*} [Π i, add_comm_monoid (M' i)] [Π i, topological_space (M' i)] [Π i, module R (M' i)] (f : Π i, continuous_multilinear_map R M₁ (M' i)) : ⇑(pi f) = λ m j, f j m := rfl lemma pi_apply {ι' : Type*} {M' : ι' → Type*} [Π i, add_comm_monoid (M' i)] [Π i, topological_space (M' i)] [Π i, module R (M' i)] (f : Π i, continuous_multilinear_map R M₁ (M' i)) (m : Π i, M₁ i) (j : ι') : pi f m j = f j m := rfl /-- If `g` is continuous multilinear and `f` is a collection of continuous linear maps, then `g (f₁ m₁, ..., fₙ mₙ)` is again a continuous multilinear map, that we call `g.comp_continuous_linear_map f`. -/ def comp_continuous_linear_map (g : continuous_multilinear_map R M₁' M₄) (f : Π i : ι, M₁ i →L[R] M₁' i) : continuous_multilinear_map R M₁ M₄ := { cont := g.cont.comp $ continuous_pi $ λj, (f j).cont.comp $ continuous_apply _, .. g.to_multilinear_map.comp_linear_map (λ i, (f i).to_linear_map) } @[simp] lemma comp_continuous_linear_map_apply (g : continuous_multilinear_map R M₁' M₄) (f : Π i : ι, M₁ i →L[R] M₁' i) (m : Π i, M₁ i) : g.comp_continuous_linear_map f m = g (λ i, f i $ m i) := rfl /-- Composing a continuous multilinear map with a continuous linear map gives again a continuous multilinear map. -/ def _root_.continuous_linear_map.comp_continuous_multilinear_map (g : M₂ →L[R] M₃) (f : continuous_multilinear_map R M₁ M₂) : continuous_multilinear_map R M₁ M₃ := { cont := g.cont.comp f.cont, .. g.to_linear_map.comp_multilinear_map f.to_multilinear_map } @[simp] lemma _root_.continuous_linear_map.comp_continuous_multilinear_map_coe (g : M₂ →L[R] M₃) (f : continuous_multilinear_map R M₁ M₂) : ((g.comp_continuous_multilinear_map f) : (Πi, M₁ i) → M₃) = (g : M₂ → M₃) ∘ (f : (Πi, M₁ i) → M₂) := by { ext m, refl } /-- `continuous_multilinear_map.pi` as an `equiv`. -/ @[simps] def pi_equiv {ι' : Type*} {M' : ι' → Type*} [Π i, add_comm_monoid (M' i)] [Π i, topological_space (M' i)] [Π i, module R (M' i)] : (Π i, continuous_multilinear_map R M₁ (M' i)) ≃ continuous_multilinear_map R M₁ (Π i, M' i) := { to_fun := continuous_multilinear_map.pi, inv_fun := λ f i, (continuous_linear_map.proj i : _ →L[R] M' i).comp_continuous_multilinear_map f, left_inv := λ f, by { ext, refl }, right_inv := λ f, by { ext, refl } } /-- In the specific case of continuous multilinear maps on spaces indexed by `fin (n+1)`, where one can build an element of `Π(i : fin (n+1)), M i` using `cons`, one can express directly the additivity of a multilinear map along the first variable. -/ lemma cons_add (f : continuous_multilinear_map R M M₂) (m : Π(i : fin n), M i.succ) (x y : M 0) : f (cons (x+y) m) = f (cons x m) + f (cons y m) := f.to_multilinear_map.cons_add m x y /-- In the specific case of continuous multilinear maps on spaces indexed by `fin (n+1)`, where one can build an element of `Π(i : fin (n+1)), M i` using `cons`, one can express directly the multiplicativity of a multilinear map along the first variable. -/ lemma cons_smul (f : continuous_multilinear_map R M M₂) (m : Π(i : fin n), M i.succ) (c : R) (x : M 0) : f (cons (c • x) m) = c • f (cons x m) := f.to_multilinear_map.cons_smul m c x lemma map_piecewise_add (m m' : Πi, M₁ i) (t : finset ι) : f (t.piecewise (m + m') m') = ∑ s in t.powerset, f (s.piecewise m m') := f.to_multilinear_map.map_piecewise_add _ _ _ /-- Additivity of a continuous multilinear map along all coordinates at the same time, writing `f (m + m')` as the sum of `f (s.piecewise m m')` over all sets `s`. -/ lemma map_add_univ [fintype ι] (m m' : Πi, M₁ i) : f (m + m') = ∑ s : finset ι, f (s.piecewise m m') := f.to_multilinear_map.map_add_univ _ _ section apply_sum open fintype finset variables {α : ι → Type*} [fintype ι] (g : Π i, α i → M₁ i) (A : Π i, finset (α i)) /-- If `f` is continuous multilinear, then `f (Σ_{j₁ ∈ A₁} g₁ j₁, ..., Σ_{jₙ ∈ Aₙ} gₙ jₙ)` is the sum of `f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all functions with `r 1 ∈ A₁`, ..., `r n ∈ Aₙ`. This follows from multilinearity by expanding successively with respect to each coordinate. -/ lemma map_sum_finset : f (λ i, ∑ j in A i, g i j) = ∑ r in pi_finset A, f (λ i, g i (r i)) := f.to_multilinear_map.map_sum_finset _ _ /-- If `f` is continuous multilinear, then `f (Σ_{j₁} g₁ j₁, ..., Σ_{jₙ} gₙ jₙ)` is the sum of `f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all functions `r`. This follows from multilinearity by expanding successively with respect to each coordinate. -/ lemma map_sum [∀ i, fintype (α i)] : f (λ i, ∑ j, g i j) = ∑ r : Π i, α i, f (λ i, g i (r i)) := f.to_multilinear_map.map_sum _ end apply_sum section restrict_scalar variables (R) {A : Type*} [semiring A] [has_smul R A] [Π (i : ι), module A (M₁ i)] [module A M₂] [∀ i, is_scalar_tower R A (M₁ i)] [is_scalar_tower R A M₂] /-- Reinterpret an `A`-multilinear map as an `R`-multilinear map, if `A` is an algebra over `R` and their actions on all involved modules agree with the action of `R` on `A`. -/ def restrict_scalars (f : continuous_multilinear_map A M₁ M₂) : continuous_multilinear_map R M₁ M₂ := { to_multilinear_map := f.to_multilinear_map.restrict_scalars R, cont := f.cont } @[simp] lemma coe_restrict_scalars (f : continuous_multilinear_map A M₁ M₂) : ⇑(f.restrict_scalars R) = f := rfl end restrict_scalar end semiring section ring variables [ring R] [∀i, add_comm_group (M₁ i)] [add_comm_group M₂] [∀i, module R (M₁ i)] [module R M₂] [∀i, topological_space (M₁ i)] [topological_space M₂] (f f' : continuous_multilinear_map R M₁ M₂) @[simp] lemma map_sub (m : Πi, M₁ i) (i : ι) (x y : M₁ i) : f (update m i (x - y)) = f (update m i x) - f (update m i y) := f.to_multilinear_map.map_sub _ _ _ _ section topological_add_group variable [topological_add_group M₂] instance : has_neg (continuous_multilinear_map R M₁ M₂) := ⟨λ f, {cont := f.cont.neg, ..(-f.to_multilinear_map)}⟩ @[simp] lemma neg_apply (m : Πi, M₁ i) : (-f) m = - (f m) := rfl instance : has_sub (continuous_multilinear_map R M₁ M₂) := ⟨λ f g, { cont := f.cont.sub g.cont, .. (f.to_multilinear_map - g.to_multilinear_map) }⟩ @[simp] lemma sub_apply (m : Πi, M₁ i) : (f - f') m = f m - f' m := rfl instance : add_comm_group (continuous_multilinear_map R M₁ M₂) := to_multilinear_map_inj.add_comm_group _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) end topological_add_group end ring section comm_semiring variables [comm_semiring R] [∀i, add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [∀i, module R (M₁ i)] [module R M₂] [∀i, topological_space (M₁ i)] [topological_space M₂] (f : continuous_multilinear_map R M₁ M₂) lemma map_piecewise_smul (c : ι → R) (m : Πi, M₁ i) (s : finset ι) : f (s.piecewise (λ i, c i • m i) m) = (∏ i in s, c i) • f m := f.to_multilinear_map.map_piecewise_smul _ _ _ /-- Multiplicativity of a continuous multilinear map along all coordinates at the same time, writing `f (λ i, c i • m i)` as `(∏ i, c i) • f m`. -/ lemma map_smul_univ [fintype ι] (c : ι → R) (m : Πi, M₁ i) : f (λ i, c i • m i) = (∏ i, c i) • f m := f.to_multilinear_map.map_smul_univ _ _ end comm_semiring section distrib_mul_action variables {R' R'' A : Type*} [monoid R'] [monoid R''] [semiring A] [Π i, add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [Π i, topological_space (M₁ i)] [topological_space M₂] [Π i, module A (M₁ i)] [module A M₂] [distrib_mul_action R' M₂] [has_continuous_const_smul R' M₂] [smul_comm_class A R' M₂] [distrib_mul_action R'' M₂] [has_continuous_const_smul R'' M₂] [smul_comm_class A R'' M₂] instance [has_continuous_add M₂] : distrib_mul_action R' (continuous_multilinear_map A M₁ M₂) := function.injective.distrib_mul_action ⟨to_multilinear_map, to_multilinear_map_zero, to_multilinear_map_add⟩ to_multilinear_map_inj (λ _ _, rfl) end distrib_mul_action section module variables {R' A : Type*} [semiring R'] [semiring A] [Π i, add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [Π i, topological_space (M₁ i)] [topological_space M₂] [has_continuous_add M₂] [Π i, module A (M₁ i)] [module A M₂] [module R' M₂] [has_continuous_const_smul R' M₂] [smul_comm_class A R' M₂] /-- The space of continuous multilinear maps over an algebra over `R` is a module over `R`, for the pointwise addition and scalar multiplication. -/ instance : module R' (continuous_multilinear_map A M₁ M₂) := function.injective.module _ ⟨to_multilinear_map, to_multilinear_map_zero, to_multilinear_map_add⟩ to_multilinear_map_inj (λ _ _, rfl) /-- Linear map version of the map `to_multilinear_map` associating to a continuous multilinear map the corresponding multilinear map. -/ @[simps] def to_multilinear_map_linear : continuous_multilinear_map A M₁ M₂ →ₗ[R'] multilinear_map A M₁ M₂ := { to_fun := to_multilinear_map, map_add' := to_multilinear_map_add, map_smul' := to_multilinear_map_smul } /-- `continuous_multilinear_map.pi` as a `linear_equiv`. -/ @[simps {simp_rhs := tt}] def pi_linear_equiv {ι' : Type*} {M' : ι' → Type*} [Π i, add_comm_monoid (M' i)] [Π i, topological_space (M' i)] [∀ i, has_continuous_add (M' i)] [Π i, module R' (M' i)] [Π i, module A (M' i)] [∀ i, smul_comm_class A R' (M' i)] [Π i, has_continuous_const_smul R' (M' i)] : (Π i, continuous_multilinear_map A M₁ (M' i)) ≃ₗ[R'] continuous_multilinear_map A M₁ (Π i, M' i) := { map_add' := λ x y, rfl, map_smul' := λ c x, rfl, .. pi_equiv } end module section comm_algebra variables (R ι) (A : Type*) [fintype ι] [comm_semiring R] [comm_semiring A] [algebra R A] [topological_space A] [has_continuous_mul A] /-- The continuous multilinear map on `A^ι`, where `A` is a normed commutative algebra over `𝕜`, associating to `m` the product of all the `m i`. See also `continuous_multilinear_map.mk_pi_algebra_fin`. -/ protected def mk_pi_algebra : continuous_multilinear_map R (λ i : ι, A) A := { cont := continuous_finset_prod _ $ λ i hi, continuous_apply _, to_multilinear_map := multilinear_map.mk_pi_algebra R ι A} @[simp] lemma mk_pi_algebra_apply (m : ι → A) : continuous_multilinear_map.mk_pi_algebra R ι A m = ∏ i, m i := rfl end comm_algebra section algebra variables (R n) (A : Type*) [comm_semiring R] [semiring A] [algebra R A] [topological_space A] [has_continuous_mul A] /-- The continuous multilinear map on `A^n`, where `A` is a normed algebra over `𝕜`, associating to `m` the product of all the `m i`. See also: `continuous_multilinear_map.mk_pi_algebra`. -/ protected def mk_pi_algebra_fin : A [×n]→L[R] A := { cont := begin change continuous (λ m, (list.of_fn m).prod), simp_rw list.of_fn_eq_map, exact continuous_list_prod _ (λ i hi, continuous_apply _), end, to_multilinear_map := multilinear_map.mk_pi_algebra_fin R n A} variables {R n A} @[simp] lemma mk_pi_algebra_fin_apply (m : fin n → A) : continuous_multilinear_map.mk_pi_algebra_fin R n A m = (list.of_fn m).prod := rfl end algebra section smul_right variables [comm_semiring R] [Π i, add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [Π i, module R (M₁ i)] [module R M₂] [topological_space R] [Π i, topological_space (M₁ i)] [topological_space M₂] [has_continuous_smul R M₂] (f : continuous_multilinear_map R M₁ R) (z : M₂) /-- Given a continuous `R`-multilinear map `f` taking values in `R`, `f.smul_right z` is the continuous multilinear map sending `m` to `f m • z`. -/ @[simps to_multilinear_map apply] def smul_right : continuous_multilinear_map R M₁ M₂ := { to_multilinear_map := f.to_multilinear_map.smul_right z, cont := f.cont.smul continuous_const } end smul_right end continuous_multilinear_map
29d36825d64aa8a355104a5e6ed000f0700a47e4
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/field_theory/perfect_closure.lean
78b1dae5c0ca0241827db5a6d8e8cda8fbbaa076
[ "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
17,976
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Yury Kudryashov -/ import algebra.char_p.basic import algebra.hom.iterate import algebra.ring.equiv /-! # The perfect closure of a field -/ universes u v open function section defs variables (R : Type u) [comm_semiring R] (p : ℕ) [fact p.prime] [char_p R p] /-- A perfect ring is a ring of characteristic p that has p-th root. -/ class perfect_ring : Type u := (pth_root' : R → R) (frobenius_pth_root' : ∀ x, frobenius R p (pth_root' x) = x) (pth_root_frobenius' : ∀ x, pth_root' (frobenius R p x) = x) /-- Frobenius automorphism of a perfect ring. -/ def frobenius_equiv [perfect_ring R p] : R ≃+* R := { inv_fun := perfect_ring.pth_root' p, left_inv := perfect_ring.pth_root_frobenius', right_inv := perfect_ring.frobenius_pth_root', .. frobenius R p } /-- `p`-th root of an element in a `perfect_ring` as a `ring_hom`. -/ def pth_root [perfect_ring R p] : R →+* R := (frobenius_equiv R p).symm end defs section variables {R : Type u} [comm_semiring R] {S : Type v} [comm_semiring S] (f : R →* S) (g : R →+* S) {p : ℕ} [fact p.prime] [char_p R p] [perfect_ring R p] [char_p S p] [perfect_ring S p] @[simp] lemma coe_frobenius_equiv : ⇑(frobenius_equiv R p) = frobenius R p := rfl @[simp] lemma coe_frobenius_equiv_symm : ⇑(frobenius_equiv R p).symm = pth_root R p := rfl @[simp] theorem frobenius_pth_root (x : R) : frobenius R p (pth_root R p x) = x := (frobenius_equiv R p).apply_symm_apply x @[simp] theorem pth_root_pow_p (x : R) : pth_root R p x ^ p = x := frobenius_pth_root x @[simp] theorem pth_root_frobenius (x : R) : pth_root R p (frobenius R p x) = x := (frobenius_equiv R p).symm_apply_apply x @[simp] theorem pth_root_pow_p' (x : R) : pth_root R p (x ^ p) = x := pth_root_frobenius x theorem left_inverse_pth_root_frobenius : left_inverse (pth_root R p) (frobenius R p) := pth_root_frobenius theorem right_inverse_pth_root_frobenius : function.right_inverse (pth_root R p) (frobenius R p) := frobenius_pth_root theorem commute_frobenius_pth_root : function.commute (frobenius R p) (pth_root R p) := λ x, (frobenius_pth_root x).trans (pth_root_frobenius x).symm theorem eq_pth_root_iff {x y : R} : x = pth_root R p y ↔ frobenius R p x = y := (frobenius_equiv R p).to_equiv.eq_symm_apply theorem pth_root_eq_iff {x y : R} : pth_root R p x = y ↔ x = frobenius R p y := (frobenius_equiv R p).to_equiv.symm_apply_eq theorem monoid_hom.map_pth_root (x : R) : f (pth_root R p x) = pth_root S p (f x) := eq_pth_root_iff.2 $ by rw [← f.map_frobenius, frobenius_pth_root] theorem monoid_hom.map_iterate_pth_root (x : R) (n : ℕ) : f (pth_root R p^[n] x) = (pth_root S p^[n] (f x)) := semiconj.iterate_right f.map_pth_root n x theorem ring_hom.map_pth_root (x : R) : g (pth_root R p x) = pth_root S p (g x) := g.to_monoid_hom.map_pth_root x theorem ring_hom.map_iterate_pth_root (x : R) (n : ℕ) : g (pth_root R p^[n] x) = (pth_root S p^[n] (g x)) := g.to_monoid_hom.map_iterate_pth_root x n variables (p) lemma injective_pow_p {x y : R} (hxy : x ^ p = y ^ p) : x = y := left_inverse_pth_root_frobenius.injective hxy end section variables (K : Type u) [comm_ring K] (p : ℕ) [fact p.prime] [char_p K p] /-- `perfect_closure K p` is the quotient by this relation. -/ @[mk_iff] inductive perfect_closure.r : (ℕ × K) → (ℕ × K) → Prop | intro : ∀ n x, perfect_closure.r (n, x) (n+1, frobenius K p x) /-- The perfect closure is the smallest extension that makes frobenius surjective. -/ def perfect_closure : Type u := quot (perfect_closure.r K p) end namespace perfect_closure variables (K : Type u) section ring variables [comm_ring K] (p : ℕ) [fact p.prime] [char_p K p] /-- Constructor for `perfect_closure`. -/ def mk (x : ℕ × K) : perfect_closure K p := quot.mk (r K p) x @[simp] lemma quot_mk_eq_mk (x : ℕ × K) : (quot.mk (r K p) x : perfect_closure K p) = mk K p x := rfl variables {K p} /-- Lift a function `ℕ × K → L` to a function on `perfect_closure K p`. -/ @[elab_as_eliminator] def lift_on {L : Type*} (x : perfect_closure K p) (f : ℕ × K → L) (hf : ∀ x y, r K p x y → f x = f y) : L := quot.lift_on x f hf @[simp] lemma lift_on_mk {L : Sort*} (f : ℕ × K → L) (hf : ∀ x y, r K p x y → f x = f y) (x : ℕ × K) : (mk K p x).lift_on f hf = f x := rfl @[elab_as_eliminator] lemma induction_on (x : perfect_closure K p) {q : perfect_closure K p → Prop} (h : ∀ x, q (mk K p x)) : q x := quot.induction_on x h variables (K p) private lemma mul_aux_left (x1 x2 y : ℕ × K) (H : r K p x1 x2) : mk K p (x1.1 + y.1, ((frobenius K p)^[y.1] x1.2) * ((frobenius K p)^[x1.1] y.2)) = mk K p (x2.1 + y.1, ((frobenius K p)^[y.1] x2.2) * ((frobenius K p)^[x2.1] y.2)) := match x1, x2, H with | _, _, r.intro n x := quot.sound $ by rw [← iterate_succ_apply, iterate_succ', iterate_succ', ← frobenius_mul, nat.succ_add]; apply r.intro end private lemma mul_aux_right (x y1 y2 : ℕ × K) (H : r K p y1 y2) : mk K p (x.1 + y1.1, ((frobenius K p)^[y1.1] x.2) * ((frobenius K p)^[x.1] y1.2)) = mk K p (x.1 + y2.1, ((frobenius K p)^[y2.1] x.2) * ((frobenius K p)^[x.1] y2.2)) := match y1, y2, H with | _, _, r.intro n y := quot.sound $ by rw [← iterate_succ_apply, iterate_succ', iterate_succ', ← frobenius_mul]; apply r.intro end instance : has_mul (perfect_closure K p) := ⟨quot.lift (λ x:ℕ×K, quot.lift (λ y:ℕ×K, mk K p (x.1 + y.1, ((frobenius K p)^[y.1] x.2) * ((frobenius K p)^[x.1] y.2))) (mul_aux_right K p x)) (λ x1 x2 (H : r K p x1 x2), funext $ λ e, quot.induction_on e $ λ y, mul_aux_left K p x1 x2 y H)⟩ @[simp] lemma mk_mul_mk (x y : ℕ × K) : mk K p x * mk K p y = mk K p (x.1 + y.1, ((frobenius K p)^[y.1] x.2) * ((frobenius K p)^[x.1] y.2)) := rfl instance : comm_monoid (perfect_closure K 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, ring_hom.iterate_map_mul, ← iterate_add_apply, add_comm, add_left_comm], one := mk K p (0, 1), one_mul := λ e, quot.induction_on e (λ ⟨n, x⟩, congr_arg (quot.mk _) $ by simp only [ring_hom.iterate_map_one, iterate_zero_apply, one_mul, zero_add]), mul_one := λ e, quot.induction_on e (λ ⟨n, x⟩, congr_arg (quot.mk _) $ by simp only [ring_hom.iterate_map_one, iterate_zero_apply, 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 K p)) } lemma one_def : (1 : perfect_closure K p) = mk K p (0, 1) := rfl instance : inhabited (perfect_closure K p) := ⟨1⟩ private lemma add_aux_left (x1 x2 y : ℕ × K) (H : r K p x1 x2) : mk K p (x1.1 + y.1, ((frobenius K p)^[y.1] x1.2) + ((frobenius K p)^[x1.1] y.2)) = mk K p (x2.1 + y.1, ((frobenius K p)^[y.1] x2.2) + ((frobenius K p)^[x2.1] y.2)) := match x1, x2, H with | _, _, r.intro n x := quot.sound $ by rw [← iterate_succ_apply, iterate_succ', iterate_succ', ← frobenius_add, nat.succ_add]; apply r.intro end private lemma add_aux_right (x y1 y2 : ℕ × K) (H : r K p y1 y2) : mk K p (x.1 + y1.1, ((frobenius K p)^[y1.1] x.2) + ((frobenius K p)^[x.1] y1.2)) = mk K p (x.1 + y2.1, ((frobenius K p)^[y2.1] x.2) + ((frobenius K p)^[x.1] y2.2)) := match y1, y2, H with | _, _, r.intro n y := quot.sound $ by rw [← iterate_succ_apply, iterate_succ', iterate_succ', ← frobenius_add]; apply r.intro end instance : has_add (perfect_closure K p) := ⟨quot.lift (λ x:ℕ×K, quot.lift (λ y:ℕ×K, mk K p (x.1 + y.1, ((frobenius K p)^[y.1] x.2) + ((frobenius K p)^[x.1] y.2))) (add_aux_right K p x)) (λ x1 x2 (H : r K p x1 x2), funext $ λ e, quot.induction_on e $ λ y, add_aux_left K p x1 x2 y H)⟩ @[simp] lemma mk_add_mk (x y : ℕ × K) : mk K p x + mk K p y = mk K p (x.1 + y.1, ((frobenius K p)^[y.1] x.2) + ((frobenius K p)^[x.1] y.2)) := rfl instance : has_neg (perfect_closure K p) := ⟨quot.lift (λ x:ℕ×K, mk K p (x.1, -x.2)) (λ x y (H : r K p x y), match x, y, H with | _, _, r.intro n x := quot.sound $ by rw ← frobenius_neg; apply r.intro end)⟩ @[simp] lemma neg_mk (x : ℕ × K) : - mk K p x = mk K p (x.1, -x.2) := rfl instance : has_zero (perfect_closure K p) := ⟨mk K p (0, 0)⟩ lemma zero_def : (0 : perfect_closure K p) = mk K p (0, 0) := rfl @[simp] lemma mk_zero_zero : mk K p (0, 0) = 0 := rfl theorem mk_zero (n : ℕ) : mk K p (n, 0) = 0 := by induction n with n ih; [refl, rw ← ih]; symmetry; apply quot.sound; have := r.intro n (0:K); rwa [frobenius_zero K p] at this theorem r.sound (m n : ℕ) (x y : K) (H : frobenius K p^[m] x = y) : mk K p (n, x) = mk K p (m + n, y) := by subst H; induction m with m ih; [simp only [zero_add, iterate_zero_apply], rw [ih, nat.succ_add, iterate_succ']]; apply quot.sound; apply r.intro instance : add_comm_group (perfect_closure K 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 [ring_hom.iterate_map_add, ← iterate_add_apply, add_assoc, add_comm s _], zero := 0, zero_add := λ e, quot.induction_on e (λ ⟨n, x⟩, congr_arg (quot.mk _) $ by simp only [ring_hom.iterate_map_zero, iterate_zero_apply, zero_add]), add_zero := λ e, quot.induction_on e (λ ⟨n, x⟩, congr_arg (quot.mk _) $ by simp only [ring_hom.iterate_map_zero, iterate_zero_apply, add_zero]), sub_eq_add_neg := λ a b, rfl, add_left_neg := λ e, by exact quot.induction_on e (λ ⟨n, x⟩, by simp only [quot_mk_eq_mk, neg_mk, mk_add_mk, ring_hom.iterate_map_neg, add_left_neg, mk_zero]), 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])), .. (infer_instance : has_add (perfect_closure K p)), .. (infer_instance : has_neg (perfect_closure K p)) } instance : comm_ring (perfect_closure K p) := { 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 [ring_hom.iterate_map_mul, ring_hom.iterate_map_add, ← iterate_add_apply, 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 [ring_hom.iterate_map_mul, ring_hom.iterate_map_add, ← iterate_add_apply, add_mul, add_comm, add_left_comm], .. perfect_closure.add_comm_group K p, .. add_monoid_with_one.unary, .. (infer_instance : comm_monoid (perfect_closure K p)) } theorem eq_iff' (x y : ℕ × K) : mk K p x = mk K p y ↔ ∃ z, (frobenius K p^[y.1 + z] x.2) = (frobenius K 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, iterate_add_apply, ih1], rw [← iterate_add_apply, add_comm, iterate_add_apply, ih2], rw [← iterate_add_apply], 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 K p (n+z) m x _ rfl, r.sound K p (m+z) n y _ rfl, H], rw [add_assoc, add_comm, add_comm z] end theorem nat_cast (n x : ℕ) : (x : perfect_closure K p) = mk K p (n, x) := begin induction n with n ih, { induction x with x ih, {simp}, rw [nat.cast_succ, nat.cast_succ, ih], refl }, rw ih, apply quot.sound, conv {congr, skip, skip, rw ← frobenius_nat_cast K p x}, apply r.intro end theorem int_cast (x : ℤ) : (x : perfect_closure K p) = mk K p (0, x) := by induction x; simp only [int.cast_of_nat, int.cast_neg_succ_of_nat, nat_cast K p 0]; refl theorem nat_cast_eq_iff (x y : ℕ) : (x : perfect_closure K p) = y ↔ (x : K) = y := begin split; intro H, { rw [nat_cast K p 0, nat_cast K p 0, eq_iff'] at H, cases H with z H, simpa only [zero_add, iterate_fixed (frobenius_nat_cast K p _)] using H }, rw [nat_cast K p 0, nat_cast K p 0, H] end instance : char_p (perfect_closure K p) p := begin constructor, intro x, rw ← char_p.cast_eq_zero_iff K, rw [← nat.cast_zero, nat_cast_eq_iff, nat.cast_zero] end theorem frobenius_mk (x : ℕ × K) : (frobenius (perfect_closure K p) p : perfect_closure K p → perfect_closure K p) (mk K p x) = mk _ _ (x.1, x.2^p) := begin simp only [frobenius_def], cases x with n x, dsimp only, suffices : ∀ p':ℕ, mk K p (n, x) ^ p' = mk K p (n, x ^ p'), { apply this }, intro p, induction p with p ih, case nat.zero { apply r.sound, rw [(frobenius _ _).iterate_map_one, pow_zero] }, case nat.succ { rw [pow_succ, ih], symmetry, apply r.sound, simp only [pow_succ, (frobenius _ _).iterate_map_mul] } end /-- Embedding of `K` into `perfect_closure K p` -/ def of : K →+* perfect_closure K p := { to_fun := λ x, mk _ _ (0, x), map_one' := rfl, map_mul' := λ x y, rfl, map_zero' := rfl, map_add' := λ x y, rfl } lemma of_apply (x : K) : of K p x = mk _ _ (0, x) := rfl end ring theorem eq_iff [comm_ring K] [is_domain K] (p : ℕ) [fact p.prime] [char_p K p] (x y : ℕ × K) : quot.mk (r K p) x = quot.mk (r K p) y ↔ (frobenius K p^[y.1] x.2) = (frobenius K p^[x.1] y.2) := (eq_iff' K p x y).trans ⟨λ ⟨z, H⟩, (frobenius_inj K p).iterate z $ by simpa only [add_comm, iterate_add] using H, λ H, ⟨0, H⟩⟩ section field variables [field K] (p : ℕ) [fact p.prime] [char_p K p] instance : has_inv (perfect_closure K p) := ⟨quot.lift (λ x:ℕ×K, quot.mk (r K p) (x.1, x.2⁻¹)) (λ x y (H : r K p x y), match x, y, H with | _, _, r.intro n x := quot.sound $ by { simp only [frobenius_def], rw ← inv_pow, apply r.intro } end)⟩ instance : field (perfect_closure K p) := { exists_pair_ne := ⟨0, 1, λ H, zero_ne_one ((eq_iff _ _ _ _).1 H)⟩, mul_inv_cancel := λ e, induction_on e $ λ ⟨m, x⟩ H, have _ := mt (eq_iff _ _ _ _).2 H, (eq_iff _ _ _ _).2 (by simp only [(frobenius _ _).iterate_map_one, (frobenius K p).iterate_map_zero, iterate_zero_apply, ← (frobenius _ p).iterate_map_mul] at this ⊢; rw [mul_inv_cancel this, (frobenius _ _).iterate_map_one]), inv_zero := congr_arg (quot.mk (r K p)) (by rw [inv_zero]), .. (infer_instance : has_inv (perfect_closure K p)), .. (infer_instance : comm_ring (perfect_closure K p)) } instance : perfect_ring (perfect_closure K p) p := { pth_root' := λ e, lift_on e (λ x, mk K p (x.1 + 1, x.2)) (λ x y H, match x, y, H with | _, _, r.intro n x := quot.sound (r.intro _ _) end), frobenius_pth_root' := λ e, induction_on e (λ ⟨n, x⟩, by { simp only [lift_on_mk, frobenius_mk], exact (quot.sound $ r.intro _ _).symm }), pth_root_frobenius' := λ e, induction_on e (λ ⟨n, x⟩, by { simp only [lift_on_mk, frobenius_mk], exact (quot.sound $ r.intro _ _).symm }) } theorem eq_pth_root (x : ℕ × K) : mk K p x = (pth_root (perfect_closure K p) p^[x.1] (of K p x.2)) := begin rcases x with ⟨m, x⟩, induction m with m ih, {refl}, rw [iterate_succ_apply', ← ih]; refl end /-- Given a field `K` of characteristic `p` and a perfect ring `L` of the same characteristic, any homomorphism `K →+* L` can be lifted to `perfect_closure K p`. -/ def lift (L : Type v) [comm_semiring L] [char_p L p] [perfect_ring L p] : (K →+* L) ≃ (perfect_closure K p →+* L) := begin have := left_inverse_pth_root_frobenius.iterate, refine_struct { .. }, field to_fun { intro f, refine_struct { .. }, field to_fun { refine λ e, lift_on e (λ x, pth_root L p^[x.1] (f x.2)) _, rintro a b ⟨n⟩, simp only [f.map_frobenius, iterate_succ_apply, pth_root_frobenius] }, field map_one' { exact f.map_one }, field map_zero' { exact f.map_zero }, field map_mul' { rintro ⟨x⟩ ⟨y⟩, simp only [quot_mk_eq_mk, lift_on_mk, mk_mul_mk, ring_hom.map_iterate_frobenius, ring_hom.iterate_map_mul, ring_hom.map_mul], rw [iterate_add_apply, this _ _, add_comm, iterate_add_apply, this _ _] }, field map_add' { rintro ⟨x⟩ ⟨y⟩, simp only [quot_mk_eq_mk, lift_on_mk, mk_add_mk, ring_hom.map_iterate_frobenius, ring_hom.iterate_map_add, ring_hom.map_add], rw [iterate_add_apply, this _ _, add_comm x.1, iterate_add_apply, this _ _] } }, field inv_fun { exact λ f, f.comp (of K p) }, field left_inv { intro f, ext x, refl }, field right_inv { intro f, ext ⟨x⟩, simp only [ring_hom.coe_mk, quot_mk_eq_mk, ring_hom.comp_apply, lift_on_mk], rw [eq_pth_root, ring_hom.map_iterate_pth_root] } end end field end perfect_closure /-- A reduced ring with prime characteristic and surjective frobenius map is perfect. -/ noncomputable def perfect_ring.of_surjective (k : Type*) [comm_ring k] [is_reduced k] (p : ℕ) [fact p.prime] [char_p k p] (h : function.surjective $ frobenius k p) : perfect_ring k p := { pth_root' := function.surj_inv h, frobenius_pth_root' := function.surj_inv_eq h, pth_root_frobenius' := λ x, frobenius_inj _ _ $ function.surj_inv_eq h _ }
ccb431f522fc98143d764036fe5c98f727b4fbcf
82e44445c70db0f03e30d7be725775f122d72f3e
/src/data/polynomial/coeff.lean
cf5fae42ad7a6a6d0fe91bebd7789239d5e458f8
[ "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
7,187
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 -/ import data.polynomial.basic import data.finset.nat_antidiagonal /-! # Theory of univariate polynomials The theorems include formulas for computing coefficients, such as `coeff_add`, `coeff_sum`, `coeff_mul` -/ noncomputable theory open finsupp finset add_monoid_algebra open_locale big_operators namespace polynomial universes u v variables {R : Type u} {S : Type v} {a b : R} {n m : ℕ} variables [semiring R] {p q r : polynomial R} section coeff lemma coeff_one (n : ℕ) : coeff (1 : polynomial R) n = if 0 = n then 1 else 0 := coeff_monomial @[simp] lemma coeff_add (p q : polynomial R) (n : ℕ) : coeff (p + q) n = coeff p n + coeff q n := by { rcases p, rcases q, simp [coeff, add_to_finsupp] } @[simp] lemma coeff_smul [monoid S] [distrib_mul_action S R] (r : S) (p : polynomial R) (n : ℕ) : coeff (r • p) n = r • coeff p n := by { rcases p, simp [coeff, smul_to_finsupp] } lemma support_smul [monoid S] [distrib_mul_action S R] (r : S) (p : polynomial R) : support (r • p) ⊆ support p := begin assume i hi, simp [mem_support_iff] at hi ⊢, contrapose! hi, simp [hi] end variable (R) /-- The nth coefficient, as a linear map. -/ def lcoeff (n : ℕ) : polynomial R →ₗ[R] R := { to_fun := λ p, coeff p n, map_add' := λ p q, coeff_add p q n, map_smul' := λ r p, coeff_smul r p n } variable {R} @[simp] lemma lcoeff_apply (n : ℕ) (f : polynomial R) : lcoeff R n f = coeff f n := rfl @[simp] lemma finset_sum_coeff {ι : Type*} (s : finset ι) (f : ι → polynomial R) (n : ℕ) : coeff (∑ b in s, f b) n = ∑ b in s, coeff (f b) n := (lcoeff R n).map_sum lemma coeff_sum [semiring S] (n : ℕ) (f : ℕ → R → polynomial S) : coeff (p.sum f) n = p.sum (λ a b, coeff (f a b) n) := by { rcases p, simp [polynomial.sum, support, coeff] } /-- Decomposes the coefficient of the product `p * q` as a sum over `nat.antidiagonal`. A version which sums over `range (n + 1)` can be obtained by using `finset.nat.sum_antidiagonal_eq_sum_range_succ`. -/ lemma coeff_mul (p q : polynomial R) (n : ℕ) : coeff (p * q) n = ∑ x in nat.antidiagonal n, coeff p x.1 * coeff q x.2 := begin rcases p, rcases q, simp only [coeff, mul_to_finsupp], exact add_monoid_algebra.mul_apply_antidiagonal p q n _ (λ x, nat.mem_antidiagonal) end @[simp] lemma mul_coeff_zero (p q : polynomial R) : coeff (p * q) 0 = coeff p 0 * coeff q 0 := by simp [coeff_mul] lemma coeff_mul_X_zero (p : polynomial R) : coeff (p * X) 0 = 0 := by simp lemma coeff_X_mul_zero (p : polynomial R) : coeff (X * p) 0 = 0 := by simp lemma coeff_C_mul_X (x : R) (k n : ℕ) : coeff (C x * X^k : polynomial R) n = if n = k then x else 0 := by { rw [← monomial_eq_C_mul_X, coeff_monomial], congr' 1, simp [eq_comm] } @[simp] lemma coeff_C_mul (p : polynomial R) : coeff (C a * p) n = a * coeff p n := by { rcases p, simp only [C, monomial, monomial_fun, mul_to_finsupp, ring_hom.coe_mk, coeff, add_monoid_algebra.single_zero_mul_apply p a n] } lemma C_mul' (a : R) (f : polynomial R) : C a * f = a • f := by { ext, rw [coeff_C_mul, coeff_smul, smul_eq_mul] } @[simp] lemma coeff_mul_C (p : polynomial R) (n : ℕ) (a : R) : coeff (p * C a) n = coeff p n * a := by { rcases p, simp only [C, monomial, monomial_fun, mul_to_finsupp, ring_hom.coe_mk, coeff, add_monoid_algebra.mul_single_zero_apply p a n] } lemma coeff_X_pow (k n : ℕ) : coeff (X^k : polynomial R) n = if n = k then 1 else 0 := by simp only [one_mul, ring_hom.map_one, ← coeff_C_mul_X] @[simp] lemma coeff_X_pow_self (n : ℕ) : coeff (X^n : polynomial R) n = 1 := by simp [coeff_X_pow] theorem coeff_mul_X_pow (p : polynomial R) (n d : ℕ) : coeff (p * polynomial.X ^ n) (d + n) = coeff p d := begin rw [coeff_mul, sum_eq_single (d,n), coeff_X_pow, if_pos rfl, mul_one], { rintros ⟨i,j⟩ h1 h2, rw [coeff_X_pow, if_neg, mul_zero], rintro rfl, apply h2, rw [nat.mem_antidiagonal, add_right_cancel_iff] at h1, subst h1 }, { exact λ h1, (h1 (nat.mem_antidiagonal.2 rfl)).elim } end lemma coeff_mul_X_pow' (p : polynomial R) (n d : ℕ) : (p * X ^ n).coeff d = ite (n ≤ d) (p.coeff (d - n)) 0 := begin split_ifs, { rw [←@nat.sub_add_cancel d n h, coeff_mul_X_pow, nat.add_sub_cancel] }, { refine (coeff_mul _ _ _).trans (finset.sum_eq_zero (λ x hx, _)), rw [coeff_X_pow, if_neg, mul_zero], exact ne_of_lt (lt_of_le_of_lt (nat.le_of_add_le_right (le_of_eq (finset.nat.mem_antidiagonal.mp hx))) (not_le.mp h)) }, end @[simp] theorem coeff_mul_X (p : polynomial R) (n : ℕ) : coeff (p * X) (n + 1) = coeff p n := by simpa only [pow_one] using coeff_mul_X_pow p 1 n theorem mul_X_pow_eq_zero {p : polynomial R} {n : ℕ} (H : p * X ^ n = 0) : p = 0 := ext $ λ k, (coeff_mul_X_pow p n k).symm.trans $ ext_iff.1 H (k+n) lemma C_mul_X_pow_eq_monomial (c : R) (n : ℕ) : C c * X^n = monomial n c := by { ext1, rw [monomial_eq_smul_X, coeff_smul, coeff_C_mul, smul_eq_mul] } lemma support_mul_X_pow (c : R) (n : ℕ) (H : c ≠ 0) : (C c * X^n).support = singleton n := by rw [C_mul_X_pow_eq_monomial, support_monomial n c H] lemma support_C_mul_X_pow' {c : R} {n : ℕ} : (C c * X^n).support ⊆ singleton n := by { rw [C_mul_X_pow_eq_monomial], exact support_monomial' n c } lemma C_dvd_iff_dvd_coeff (r : R) (φ : polynomial R) : C r ∣ φ ↔ ∀ i, r ∣ φ.coeff i := begin split, { rintros ⟨φ, rfl⟩ c, rw coeff_C_mul, apply dvd_mul_right }, { intro h, choose c hc using h, classical, let c' : ℕ → R := λ i, if i ∈ φ.support then c i else 0, let ψ : polynomial R := ∑ i in φ.support, monomial i (c' i), use ψ, ext i, simp only [ψ, c', coeff_C_mul, mem_support_iff, coeff_monomial, finset_sum_coeff, finset.sum_ite_eq'], split_ifs with hi hi, { rw hc }, { rw [not_not] at hi, rwa mul_zero } }, end lemma coeff_bit0_mul (P Q : polynomial R) (n : ℕ) : coeff (bit0 P * Q) n = 2 * coeff (P * Q) n := by simp [bit0, add_mul] lemma coeff_bit1_mul (P Q : polynomial R) (n : ℕ) : coeff (bit1 P * Q) n = 2 * coeff (P * Q) n + coeff Q n := by simp [bit1, add_mul, coeff_bit0_mul] end coeff section cast @[simp] lemma nat_cast_coeff_zero {n : ℕ} {R : Type*} [semiring R] : (n : polynomial R).coeff 0 = n := begin induction n with n ih, { simp, }, { simp [ih], }, end @[simp, norm_cast] theorem nat_cast_inj {m n : ℕ} {R : Type*} [semiring R] [char_zero R] : (↑m : polynomial R) = ↑n ↔ m = n := begin fsplit, { intro h, apply_fun (λ p, p.coeff 0) at h, simpa using h, }, { rintro rfl, refl, }, end @[simp] lemma int_cast_coeff_zero {i : ℤ} {R : Type*} [ring R] : (i : polynomial R).coeff 0 = i := by cases i; simp @[simp, norm_cast] theorem int_cast_inj {m n : ℤ} {R : Type*} [ring R] [char_zero R] : (↑m : polynomial R) = ↑n ↔ m = n := begin fsplit, { intro h, apply_fun (λ p, p.coeff 0) at h, simpa using h, }, { rintro rfl, refl, }, end end cast end polynomial
9a1b331a5e85abfd5541740cdbfb25d7a2f534dd
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/src/Lean/Meta/Tactic/Replace.lean
f51f2974cef4298c3876666f45f31903e451ca0d
[ "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
tobiasgrosser/lean4
ce0fd9cca0feba1100656679bf41f0bffdbabb71
ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f
refs/heads/master
1,673,103,412,948
1,664,930,501,000
1,664,930,501,000
186,870,185
0
0
Apache-2.0
1,665,129,237,000
1,557,939,901,000
Lean
UTF-8
Lean
false
false
8,405
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.Util.ForEachExpr import Lean.Meta.AppBuilder import Lean.Meta.MatchUtil import Lean.Meta.Tactic.Util import Lean.Meta.Tactic.Revert import Lean.Meta.Tactic.Intro import Lean.Meta.Tactic.Clear import Lean.Meta.Tactic.Assert namespace Lean.Meta /-- Convert the given goal `Ctx |- target` into `Ctx |- targetNew` using an equality proof `eqProof : target = targetNew`. It assumes `eqProof` has type `target = targetNew` -/ def _root_.Lean.MVarId.replaceTargetEq (mvarId : MVarId) (targetNew : Expr) (eqProof : Expr) : MetaM MVarId := mvarId.withContext do mvarId.checkNotAssigned `replaceTarget let tag ← mvarId.getTag let mvarNew ← mkFreshExprSyntheticOpaqueMVar targetNew tag let target ← mvarId.getType let u ← getLevel target let eq ← mkEq target targetNew let newProof ← mkExpectedTypeHint eqProof eq let val := mkAppN (Lean.mkConst `Eq.mpr [u]) #[target, targetNew, newProof, mvarNew] mvarId.assign val return mvarNew.mvarId! @[deprecated MVarId.replaceTargetEq] def replaceTargetEq (mvarId : MVarId) (targetNew : Expr) (eqProof : Expr) : MetaM MVarId := mvarId.replaceTargetEq targetNew eqProof /-- Convert the given goal `Ctx |- target` into `Ctx |- targetNew`. It assumes the goals are definitionally equal. We use the proof term ``` @id target mvarNew ``` to create a checkpoint. -/ def _root_.Lean.MVarId.replaceTargetDefEq (mvarId : MVarId) (targetNew : Expr) : MetaM MVarId := mvarId.withContext do mvarId.checkNotAssigned `change let target ← mvarId.getType if target == targetNew then return mvarId else let tag ← mvarId.getTag let mvarNew ← mkFreshExprSyntheticOpaqueMVar targetNew tag let newVal ← mkExpectedTypeHint mvarNew target mvarId.assign newVal return mvarNew.mvarId! @[deprecated MVarId.replaceTargetDefEq] def replaceTargetDefEq (mvarId : MVarId) (targetNew : Expr) : MetaM MVarId := mvarId.replaceTargetDefEq targetNew private def replaceLocalDeclCore (mvarId : MVarId) (fvarId : FVarId) (typeNew : Expr) (eqProof : Expr) : MetaM AssertAfterResult := mvarId.withContext do let localDecl ← fvarId.getDecl let typeNewPr ← mkEqMP eqProof (mkFVar fvarId) -- `typeNew` may contain variables that occur after `fvarId`. -- Thus, we use the auxiliary function `findMaxFVar` to ensure `typeNew` is well-formed at the position we are inserting it. let (_, localDecl') ← findMaxFVar typeNew |>.run localDecl let result ← mvarId.assertAfter localDecl'.fvarId localDecl.userName typeNew typeNewPr (do let mvarIdNew ← result.mvarId.clear fvarId pure { result with mvarId := mvarIdNew }) <|> pure result where findMaxFVar (e : Expr) : StateRefT LocalDecl MetaM Unit := e.forEach' fun e => do if e.isFVar then let localDecl' ← e.fvarId!.getDecl modify fun localDecl => if localDecl'.index > localDecl.index then localDecl' else localDecl return false else return e.hasFVar /-- Replace type of the local declaration with id `fvarId` with one with the same user-facing name, but with type `typeNew`. This method assumes `eqProof` is a proof that type of `fvarId` is equal to `typeNew`. This tactic actually adds a new declaration and (try to) clear the old one. If the old one cannot be cleared, then at least its user-facing name becomes inaccessible. Remark: the new declaration is added immediately after `fvarId`. `typeNew` must be well-formed at `fvarId`, but `eqProof` may contain variables declared after `fvarId`. -/ abbrev _root_.Lean.MVarId.replaceLocalDecl (mvarId : MVarId) (fvarId : FVarId) (typeNew : Expr) (eqProof : Expr) : MetaM AssertAfterResult := replaceLocalDeclCore mvarId fvarId typeNew eqProof @[deprecated MVarId.replaceLocalDecl] abbrev replaceLocalDecl (mvarId : MVarId) (fvarId : FVarId) (typeNew : Expr) (eqProof : Expr) : MetaM AssertAfterResult := mvarId.replaceLocalDecl fvarId typeNew eqProof /-- Replace the type of `fvarId` at `mvarId` with `typeNew`. Remark: this method assumes that `typeNew` is definitionally equal to the current type of `fvarId`. -/ def _root_.Lean.MVarId.replaceLocalDeclDefEq (mvarId : MVarId) (fvarId : FVarId) (typeNew : Expr) : MetaM MVarId := do mvarId.withContext do let mvarDecl ← mvarId.getDecl if typeNew == mvarDecl.type then return mvarId else let lctxNew := (← getLCtx).modifyLocalDecl fvarId (·.setType typeNew) let mvarNew ← mkFreshExprMVarAt lctxNew (← getLocalInstances) mvarDecl.type mvarDecl.kind mvarDecl.userName mvarId.assign mvarNew return mvarNew.mvarId! @[deprecated MVarId.replaceLocalDeclDefEq] def replaceLocalDeclDefEq (mvarId : MVarId) (fvarId : FVarId) (typeNew : Expr) : MetaM MVarId := do mvarId.replaceLocalDeclDefEq fvarId typeNew /-- Replace the target type of `mvarId` with `typeNew`. If `checkDefEq = false`, this method assumes that `typeNew` is definitionally equal to the current target type. If `checkDefEq = true`, throw an error if `typeNew` is not definitionally equal to the current target type. -/ def _root_.Lean.MVarId.change (mvarId : MVarId) (targetNew : Expr) (checkDefEq := true) : MetaM MVarId := mvarId.withContext do let target ← mvarId.getType if checkDefEq then unless (← isDefEq target targetNew) do throwTacticEx `change mvarId m!"given type{indentExpr targetNew}\nis not definitionally equal to{indentExpr target}" mvarId.replaceTargetDefEq targetNew @[deprecated MVarId.change] def change (mvarId : MVarId) (targetNew : Expr) (checkDefEq := true) : MetaM MVarId := mvarId.withContext do mvarId.change targetNew checkDefEq /-- Replace the type of the free variable `fvarId` with `typeNew`. If `checkDefEq = false`, this method assumes that `typeNew` is definitionally equal to `fvarId` type. If `checkDefEq = true`, throw an error if `typeNew` is not definitionally equal to `fvarId` type. -/ def _root_.Lean.MVarId.changeLocalDecl (mvarId : MVarId) (fvarId : FVarId) (typeNew : Expr) (checkDefEq := true) : MetaM MVarId := do mvarId.checkNotAssigned `changeLocalDecl let (xs, mvarId) ← mvarId.revert #[fvarId] true mvarId.withContext do let numReverted := xs.size let target ← mvarId.getType let check (typeOld : Expr) : MetaM Unit := do if checkDefEq then unless (← isDefEq typeNew typeOld) do throwTacticEx `changeHypothesis mvarId m!"given type{indentExpr typeNew}\nis not definitionally equal to{indentExpr typeOld}" let finalize (targetNew : Expr) : MetaM MVarId := do let mvarId ← mvarId.replaceTargetDefEq targetNew let (_, mvarId) ← mvarId.introNP numReverted pure mvarId match target with | .forallE n d b c => do check d; finalize (mkForall n c typeNew b) | .letE n t v b _ => do check t; finalize (mkLet n typeNew v b) | _ => throwTacticEx `changeHypothesis mvarId "unexpected auxiliary target" @[deprecated MVarId.changeLocalDecl] def changeLocalDecl (mvarId : MVarId) (fvarId : FVarId) (typeNew : Expr) (checkDefEq := true) : MetaM MVarId := do mvarId.changeLocalDecl fvarId typeNew checkDefEq /-- Modify `mvarId` target type using `f`. -/ def _root_.Lean.MVarId.modifyTarget (mvarId : MVarId) (f : Expr → MetaM Expr) : MetaM MVarId := do mvarId.withContext do mvarId.checkNotAssigned `modifyTarget mvarId.change (← f (← mvarId.getType)) (checkDefEq := false) @[deprecated modifyTarget] def modifyTarget (mvarId : MVarId) (f : Expr → MetaM Expr) : MetaM MVarId := do mvarId.modifyTarget f /-- Modify `mvarId` target type left-hand-side using `f`. Throw an error if target type is not an equality. -/ def _root_.Lean.MVarId.modifyTargetEqLHS (mvarId : MVarId) (f : Expr → MetaM Expr) : MetaM MVarId := do mvarId.modifyTarget fun target => do if let some (_, lhs, rhs) ← matchEq? target then mkEq (← f lhs) rhs else throwTacticEx `modifyTargetEqLHS mvarId m!"equality expected{indentExpr target}" @[deprecated MVarId.modifyTargetEqLHS] def modifyTargetEqLHS (mvarId : MVarId) (f : Expr → MetaM Expr) : MetaM MVarId := do mvarId.modifyTargetEqLHS f end Lean.Meta
b4e2226063bd0916973e9b124e865a41d2e2b98c
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/int_eval.lean
f88c869b0b215eccac11b3d20146b783708852fe
[ "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
593
lean
vm_eval (1073741823:int) vm_eval (1073741824:int) vm_eval ((1073741824:int) + (1:int) - (3:int)) vm_eval - (2:int) vm_eval - (1000:int) vm_eval 10 - (1000:int) vm_eval (1073741824:int) * 10 vm_eval (100000:int) * (-3:int) vm_eval -(1073741823:int) vm_eval ((1073741824:int) + (1:int) - (1:int)) vm_eval int.of_nat 1000 vm_eval int.of_nat 1073741823 def Abs : int → nat | (int.of_nat n) := n | (int.neg_succ_of_nat n) := n + 1 vm_eval 10000 vm_eval Abs (- 10000) vm_eval Abs (-1073741823) vm_eval Abs (-1073741824) vm_eval Abs (-1073741825) vm_eval -(1073741823:int) * 1000000000
20d9296808082d638fccd30b2da2d22f3116e355
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Elab/PreDefinition.lean
04b0997e86e5223ea51908ae275d6fe93551ea21
[ "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
393
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.PreDefinition.Basic import Lean.Elab.PreDefinition.Structural import Lean.Elab.PreDefinition.Main import Lean.Elab.PreDefinition.MkInhabitant import Lean.Elab.PreDefinition.WF import Lean.Elab.PreDefinition.Eqns
41edbaf86fe4d7d1b9c4cb1031200d8ed3cea349
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/category/Rel.lean
9297d7d7e1cc677c116a20be419ce310f14a781f
[ "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
920
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.category.basic /-! > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > https://github.com/leanprover-community/mathlib4/pull/822 > Any changes to this file require a corresponding PR to mathlib4. The category of types with binary relations as morphisms. -/ namespace category_theory universe u /-- A type synonym for `Type`, which carries the category instance for which morphisms are binary relations. -/ def Rel := Type u instance Rel.inhabited : inhabited Rel := by unfold Rel; apply_instance /-- The category of types with binary relations as morphisms. -/ instance rel : large_category Rel := { hom := λ X Y, X → Y → Prop, id := λ X, λ x y, x = y, comp := λ X Y Z f g x z, ∃ y, f x y ∧ g y z } end category_theory
7505b60f7b733c808d02b159dcdbae591c0c0d87
9dc8cecdf3c4634764a18254e94d43da07142918
/src/measure_theory/constructions/borel_space.lean
aff33ca9e319ec7d14cd895f1588adeb0535b627
[ "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
93,106
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, Yury Kudryashov -/ import analysis.complex.basic import analysis.normed_space.finite_dimension import measure_theory.function.ae_measurable_sequence import measure_theory.group.arithmetic import measure_theory.lattice import measure_theory.measure.open_pos import topology.algebra.order.liminf_limsup import topology.continuous_function.basic import topology.instances.ereal import topology.G_delta import topology.order.lattice import topology.semicontinuous import topology.metric_space.metrizable /-! # Borel (measurable) space ## Main definitions * `borel α` : the least `σ`-algebra that contains all open sets; * `class borel_space` : a space with `topological_space` and `measurable_space` structures such that `‹measurable_space α› = borel α`; * `class opens_measurable_space` : a space with `topological_space` and `measurable_space` structures such that all open sets are measurable; equivalently, `borel α ≤ ‹measurable_space α›`. * `borel_space` instances on `empty`, `unit`, `bool`, `nat`, `int`, `rat`; * `measurable` and `borel_space` instances on `ℝ`, `ℝ≥0`, `ℝ≥0∞`. ## Main statements * `is_open.measurable_set`, `is_closed.measurable_set`: open and closed sets are measurable; * `continuous.measurable` : a continuous function is measurable; * `continuous.measurable2` : if `f : α → β` and `g : α → γ` are measurable and `op : β × γ → δ` is continuous, then `λ x, op (f x, g y)` is measurable; * `measurable.add` etc : dot notation for arithmetic operations on `measurable` predicates, and similarly for `dist` and `edist`; * `ae_measurable.add` : similar dot notation for almost everywhere measurable functions; * `measurable.ennreal*` : special cases for arithmetic operations on `ℝ≥0∞`. -/ noncomputable theory open classical set filter measure_theory open_locale classical big_operators topological_space nnreal ennreal measure_theory universes u v w x y variables {α β γ γ₂ δ : Type*} {ι : Sort y} {s t u : set α} open measurable_space topological_space /-- `measurable_space` structure generated by `topological_space`. -/ def borel (α : Type u) [topological_space α] : measurable_space α := generate_from {s : set α | is_open s} lemma borel_eq_top_of_discrete [topological_space α] [discrete_topology α] : borel α = ⊤ := top_le_iff.1 $ λ s hs, generate_measurable.basic s (is_open_discrete s) lemma borel_eq_top_of_countable [topological_space α] [t1_space α] [countable α] : borel α = ⊤ := begin refine (top_le_iff.1 $ λ s hs, bUnion_of_singleton s ▸ _), apply measurable_set.bUnion s.to_countable, intros x hx, apply measurable_set.of_compl, apply generate_measurable.basic, exact is_closed_singleton.is_open_compl end lemma borel_eq_generate_from_of_subbasis {s : set (set α)} [t : topological_space α] [second_countable_topology α] (hs : t = generate_from s) : borel α = generate_from s := le_antisymm (generate_from_le $ assume u (hu : t.is_open u), begin rw [hs] at hu, induction hu, case generate_open.basic : u hu { exact generate_measurable.basic u hu }, case generate_open.univ { exact @measurable_set.univ α (generate_from s) }, case generate_open.inter : s₁ s₂ _ _ hs₁ hs₂ { exact @measurable_set.inter α (generate_from s) _ _ hs₁ hs₂ }, case generate_open.sUnion : f hf ih { rcases is_open_sUnion_countable f (by rwa hs) with ⟨v, hv, vf, vu⟩, rw ← vu, exact @measurable_set.sUnion α (generate_from s) _ hv (λ x xv, ih _ (vf xv)) } end) (generate_from_le $ assume u hu, generate_measurable.basic _ $ show t.is_open u, by rw [hs]; exact generate_open.basic _ hu) lemma topological_space.is_topological_basis.borel_eq_generate_from [topological_space α] [second_countable_topology α] {s : set (set α)} (hs : is_topological_basis s) : borel α = generate_from s := borel_eq_generate_from_of_subbasis hs.eq_generate_from lemma is_pi_system_is_open [topological_space α] : is_pi_system (is_open : set α → Prop) := λ s hs t ht hst, is_open.inter hs ht lemma borel_eq_generate_from_is_closed [topological_space α] : borel α = generate_from {s | is_closed s} := le_antisymm (generate_from_le $ λ t ht, @measurable_set.of_compl α _ (generate_from {s | is_closed s}) (generate_measurable.basic _ $ is_closed_compl_iff.2 ht)) (generate_from_le $ λ t ht, @measurable_set.of_compl α _ (borel α) (generate_measurable.basic _ $ is_open_compl_iff.2 ht)) section order_topology variable (α) variables [topological_space α] [second_countable_topology α] [linear_order α] [order_topology α] lemma borel_eq_generate_from_Iio : borel α = generate_from (range Iio) := begin refine le_antisymm _ (generate_from_le _), { rw borel_eq_generate_from_of_subbasis (@order_topology.topology_eq_generate_intervals α _ _ _), letI : measurable_space α := measurable_space.generate_from (range Iio), have H : ∀ a : α, measurable_set (Iio a) := λ a, generate_measurable.basic _ ⟨_, rfl⟩, refine generate_from_le _, rintro _ ⟨a, rfl | rfl⟩; [skip, apply H], by_cases h : ∃ a', ∀ b, a < b ↔ a' ≤ b, { rcases h with ⟨a', ha'⟩, rw (_ : Ioi a = (Iio a')ᶜ), { exact (H _).compl }, simp [set.ext_iff, ha'] }, { rcases is_open_Union_countable (λ a' : {a' : α // a < a'}, {b | a'.1 < b}) (λ a', is_open_lt' _) with ⟨v, ⟨hv⟩, vu⟩, simp [set.ext_iff] at vu, have : Ioi a = ⋃ x : v, (Iio x.1.1)ᶜ, { simp [set.ext_iff], refine λ x, ⟨λ ax, _, λ ⟨a', ⟨h, av⟩, ax⟩, lt_of_lt_of_le h ax⟩, rcases (vu x).2 _ with ⟨a', h₁, h₂⟩, { exact ⟨a', h₁, le_of_lt h₂⟩ }, refine not_imp_comm.1 (λ h, _) h, exact ⟨x, λ b, ⟨λ ab, le_of_not_lt (λ h', h ⟨b, ab, h'⟩), lt_of_lt_of_le ax⟩⟩ }, rw this, resetI, apply measurable_set.Union, exact λ _, (H _).compl } }, { rw forall_range_iff, intro a, exact generate_measurable.basic _ is_open_Iio } end lemma borel_eq_generate_from_Ioi : borel α = generate_from (range Ioi) := @borel_eq_generate_from_Iio αᵒᵈ _ (by apply_instance : second_countable_topology α) _ _ end order_topology lemma borel_comap {f : α → β} {t : topological_space β} : @borel α (t.induced f) = (@borel β t).comap f := comap_generate_from.symm lemma continuous.borel_measurable [topological_space α] [topological_space β] {f : α → β} (hf : continuous f) : @measurable α β (borel α) (borel β) f := measurable.of_le_map $ generate_from_le $ λ s hs, generate_measurable.basic (f ⁻¹' s) (hs.preimage hf) /-- A space with `measurable_space` and `topological_space` structures such that all open sets are measurable. -/ class opens_measurable_space (α : Type*) [topological_space α] [h : measurable_space α] : Prop := (borel_le : borel α ≤ h) /-- A space with `measurable_space` and `topological_space` structures such that the `σ`-algebra of measurable sets is exactly the `σ`-algebra generated by open sets. -/ class borel_space (α : Type*) [topological_space α] [measurable_space α] : Prop := (measurable_eq : ‹measurable_space α› = borel α) namespace tactic /-- Add instances `borel α : measurable_space α` and `⟨rfl⟩ : borel_space α`. -/ meta def add_borel_instance (α : expr) : tactic unit := do n1 ← get_unused_name "_inst", to_expr ``(borel %%α) >>= pose n1, reset_instance_cache, n2 ← get_unused_name "_inst", v ← to_expr ``(borel_space.mk rfl : borel_space %%α), note n2 none v, reset_instance_cache /-- Given a type `α`, an assumption `i : measurable_space α`, and an instance `[borel_space α]`, replace `i` with `borel α`. -/ meta def borel_to_refl (α i : expr) : tactic unit := do n ← get_unused_name "h", to_expr ``(%%i = borel %%α) >>= assert n, applyc `borel_space.measurable_eq, unfreezing (tactic.subst i), n1 ← get_unused_name "_inst", to_expr ``(borel %%α) >>= pose n1, reset_instance_cache /-- Given a type `α`, if there is an assumption `[i : measurable_space α]`, then try to prove `[borel_space α]` and replace `i` with `borel α`. Otherwise, add instances `borel α : measurable_space α` and `⟨rfl⟩ : borel_space α`. -/ meta def borelize (α : expr) : tactic unit := do i ← optional (to_expr ``(measurable_space %%α) >>= find_assumption), i.elim (add_borel_instance α) (borel_to_refl α) namespace interactive setup_tactic_parser /-- The behaviour of `borelize α` depends on the existing assumptions on `α`. - if `α` is a topological space with instances `[measurable_space α] [borel_space α]`, then `borelize α` replaces the former instance by `borel α`; - otherwise, `borelize α` adds instances `borel α : measurable_space α` and `⟨rfl⟩ : borel_space α`. Finally, `borelize [α, β, γ]` runs `borelize α, borelize β, borelize γ`. -/ meta def borelize (ts : parse pexpr_list_or_texpr) : tactic unit := mmap' (λ t, to_expr t >>= tactic.borelize) ts add_tactic_doc { name := "borelize", category := doc_category.tactic, decl_names := [`tactic.interactive.borelize], tags := ["type class"] } end interactive end tactic @[priority 100] instance order_dual.opens_measurable_space {α : Type*} [topological_space α] [measurable_space α] [h : opens_measurable_space α] : opens_measurable_space αᵒᵈ := { borel_le := h.borel_le } @[priority 100] instance order_dual.borel_space {α : Type*} [topological_space α] [measurable_space α] [h : borel_space α] : borel_space αᵒᵈ := { measurable_eq := h.measurable_eq } /-- In a `borel_space` all open sets are measurable. -/ @[priority 100] instance borel_space.opens_measurable {α : Type*} [topological_space α] [measurable_space α] [borel_space α] : opens_measurable_space α := ⟨ge_of_eq $ borel_space.measurable_eq⟩ instance subtype.borel_space {α : Type*} [topological_space α] [measurable_space α] [hα : borel_space α] (s : set α) : borel_space s := ⟨by { rw [hα.1, subtype.measurable_space, ← borel_comap], refl }⟩ instance subtype.opens_measurable_space {α : Type*} [topological_space α] [measurable_space α] [h : opens_measurable_space α] (s : set α) : opens_measurable_space s := ⟨by { rw [borel_comap], exact comap_mono h.1 }⟩ theorem _root_.measurable_set.induction_on_open [topological_space α] [measurable_space α] [borel_space α] {C : set α → Prop} (h_open : ∀ U, is_open U → C U) (h_compl : ∀ t, measurable_set t → C t → C tᶜ) (h_union : ∀ f : ℕ → set α, pairwise (disjoint on f) → (∀ i, measurable_set (f i)) → (∀ i, C (f i)) → C (⋃ i, f i)) : ∀ ⦃t⦄, measurable_set t → C t := measurable_space.induction_on_inter borel_space.measurable_eq is_pi_system_is_open (h_open _ is_open_empty) h_open h_compl h_union section variables [topological_space α] [measurable_space α] [opens_measurable_space α] [topological_space β] [measurable_space β] [opens_measurable_space β] [topological_space γ] [measurable_space γ] [borel_space γ] [topological_space γ₂] [measurable_space γ₂] [borel_space γ₂] [measurable_space δ] lemma is_open.measurable_set (h : is_open s) : measurable_set s := opens_measurable_space.borel_le _ $ generate_measurable.basic _ h @[measurability] lemma measurable_set_interior : measurable_set (interior s) := is_open_interior.measurable_set lemma is_Gδ.measurable_set (h : is_Gδ s) : measurable_set s := begin rcases h with ⟨S, hSo, hSc, rfl⟩, exact measurable_set.sInter hSc (λ t ht, (hSo t ht).measurable_set) end lemma measurable_set_of_continuous_at {β} [emetric_space β] (f : α → β) : measurable_set {x | continuous_at f x} := (is_Gδ_set_of_continuous_at f).measurable_set lemma is_closed.measurable_set (h : is_closed s) : measurable_set s := h.is_open_compl.measurable_set.of_compl lemma is_compact.measurable_set [t2_space α] (h : is_compact s) : measurable_set s := h.is_closed.measurable_set @[measurability] lemma measurable_set_closure : measurable_set (closure s) := is_closed_closure.measurable_set lemma measurable_of_is_open {f : δ → γ} (hf : ∀ s, is_open s → measurable_set (f ⁻¹' s)) : measurable f := by { rw [‹borel_space γ›.measurable_eq], exact measurable_generate_from hf } lemma measurable_of_is_closed {f : δ → γ} (hf : ∀ s, is_closed s → measurable_set (f ⁻¹' s)) : measurable f := begin apply measurable_of_is_open, intros s hs, rw [← measurable_set.compl_iff, ← preimage_compl], apply hf, rw [is_closed_compl_iff], exact hs end lemma measurable_of_is_closed' {f : δ → γ} (hf : ∀ s, is_closed s → s.nonempty → s ≠ univ → measurable_set (f ⁻¹' s)) : measurable f := begin apply measurable_of_is_closed, intros s hs, cases eq_empty_or_nonempty s with h1 h1, { simp [h1] }, by_cases h2 : s = univ, { simp [h2] }, exact hf s hs h1 h2 end instance nhds_is_measurably_generated (a : α) : (𝓝 a).is_measurably_generated := begin rw [nhds, infi_subtype'], refine @filter.infi_is_measurably_generated _ _ _ _ (λ i, _), exact i.2.2.measurable_set.principal_is_measurably_generated end /-- If `s` is a measurable set, then `𝓝[s] a` is a measurably generated filter for each `a`. This cannot be an `instance` because it depends on a non-instance `hs : measurable_set s`. -/ lemma measurable_set.nhds_within_is_measurably_generated {s : set α} (hs : measurable_set s) (a : α) : (𝓝[s] a).is_measurably_generated := by haveI := hs.principal_is_measurably_generated; exact filter.inf_is_measurably_generated _ _ @[priority 100] -- see Note [lower instance priority] instance opens_measurable_space.to_measurable_singleton_class [t1_space α] : measurable_singleton_class α := ⟨λ x, is_closed_singleton.measurable_set⟩ instance pi.opens_measurable_space {ι : Type*} {π : ι → Type*} [countable ι] [t' : Π i, topological_space (π i)] [Π i, measurable_space (π i)] [∀ i, second_countable_topology (π i)] [∀ i, opens_measurable_space (π i)] : opens_measurable_space (Π i, π i) := begin constructor, have : Pi.topological_space = generate_from {t | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, s a ∈ countable_basis (π a)) ∧ t = pi ↑i s}, { rw [funext (λ a, @eq_generate_from_countable_basis (π a) _ _), pi_generate_from_eq] }, rw [borel_eq_generate_from_of_subbasis this], apply generate_from_le, rintros _ ⟨s, i, hi, rfl⟩, refine measurable_set.pi i.countable_to_set (λ a ha, is_open.measurable_set _), rw [eq_generate_from_countable_basis (π a)], exact generate_open.basic _ (hi a ha) end instance prod.opens_measurable_space [second_countable_topology α] [second_countable_topology β] : opens_measurable_space (α × β) := begin constructor, rw [((is_basis_countable_basis α).prod (is_basis_countable_basis β)).borel_eq_generate_from], apply generate_from_le, rintros _ ⟨u, v, hu, hv, rfl⟩, exact (is_open_of_mem_countable_basis hu).measurable_set.prod (is_open_of_mem_countable_basis hv).measurable_set end variables {α' : Type*} [topological_space α'] [measurable_space α'] lemma interior_ae_eq_of_null_frontier {μ : measure α'} {s : set α'} (h : μ (frontier s) = 0) : interior s =ᵐ[μ] s := interior_subset.eventually_le.antisymm $ subset_closure.eventually_le.trans (ae_le_set.2 h) lemma measure_interior_of_null_frontier {μ : measure α'} {s : set α'} (h : μ (frontier s) = 0) : μ (interior s) = μ s := measure_congr (interior_ae_eq_of_null_frontier h) lemma null_measurable_set_of_null_frontier {s : set α} {μ : measure α} (h : μ (frontier s) = 0) : null_measurable_set s μ := ⟨interior s, is_open_interior.measurable_set, (interior_ae_eq_of_null_frontier h).symm⟩ lemma closure_ae_eq_of_null_frontier {μ : measure α'} {s : set α'} (h : μ (frontier s) = 0) : closure s =ᵐ[μ] s := ((ae_le_set.2 h).trans interior_subset.eventually_le).antisymm $ subset_closure.eventually_le lemma measure_closure_of_null_frontier {μ : measure α'} {s : set α'} (h : μ (frontier s) = 0) : μ (closure s) = μ s := measure_congr (closure_ae_eq_of_null_frontier h) section preorder variables [preorder α] [order_closed_topology α] {a b x : α} @[simp, measurability] lemma measurable_set_Ici : measurable_set (Ici a) := is_closed_Ici.measurable_set @[simp, measurability] lemma measurable_set_Iic : measurable_set (Iic a) := is_closed_Iic.measurable_set @[simp, measurability] lemma measurable_set_Icc : measurable_set (Icc a b) := is_closed_Icc.measurable_set instance nhds_within_Ici_is_measurably_generated : (𝓝[Ici b] a).is_measurably_generated := measurable_set_Ici.nhds_within_is_measurably_generated _ instance nhds_within_Iic_is_measurably_generated : (𝓝[Iic b] a).is_measurably_generated := measurable_set_Iic.nhds_within_is_measurably_generated _ instance nhds_within_Icc_is_measurably_generated : is_measurably_generated (𝓝[Icc a b] x) := by { rw [← Ici_inter_Iic, nhds_within_inter], apply_instance } instance at_top_is_measurably_generated : (filter.at_top : filter α).is_measurably_generated := @filter.infi_is_measurably_generated _ _ _ _ $ λ a, (measurable_set_Ici : measurable_set (Ici a)).principal_is_measurably_generated instance at_bot_is_measurably_generated : (filter.at_bot : filter α).is_measurably_generated := @filter.infi_is_measurably_generated _ _ _ _ $ λ a, (measurable_set_Iic : measurable_set (Iic a)).principal_is_measurably_generated end preorder section partial_order variables [partial_order α] [order_closed_topology α] [second_countable_topology α] {a b : α} @[measurability] lemma measurable_set_le' : measurable_set {p : α × α | p.1 ≤ p.2} := order_closed_topology.is_closed_le'.measurable_set @[measurability] lemma measurable_set_le {f g : δ → α} (hf : measurable f) (hg : measurable g) : measurable_set {a | f a ≤ g a} := hf.prod_mk hg measurable_set_le' end partial_order section linear_order variables [linear_order α] [order_closed_topology α] {a b x : α} -- we open this locale only here to avoid issues with list being treated as intervals above open_locale interval @[simp, measurability] lemma measurable_set_Iio : measurable_set (Iio a) := is_open_Iio.measurable_set @[simp, measurability] lemma measurable_set_Ioi : measurable_set (Ioi a) := is_open_Ioi.measurable_set @[simp, measurability] lemma measurable_set_Ioo : measurable_set (Ioo a b) := is_open_Ioo.measurable_set @[simp, measurability] lemma measurable_set_Ioc : measurable_set (Ioc a b) := measurable_set_Ioi.inter measurable_set_Iic @[simp, measurability] lemma measurable_set_Ico : measurable_set (Ico a b) := measurable_set_Ici.inter measurable_set_Iio instance nhds_within_Ioi_is_measurably_generated : (𝓝[Ioi b] a).is_measurably_generated := measurable_set_Ioi.nhds_within_is_measurably_generated _ instance nhds_within_Iio_is_measurably_generated : (𝓝[Iio b] a).is_measurably_generated := measurable_set_Iio.nhds_within_is_measurably_generated _ instance nhds_within_interval_is_measurably_generated : is_measurably_generated (𝓝[[a, b]] x) := nhds_within_Icc_is_measurably_generated @[measurability] lemma measurable_set_lt' [second_countable_topology α] : measurable_set {p : α × α | p.1 < p.2} := (is_open_lt continuous_fst continuous_snd).measurable_set @[measurability] lemma measurable_set_lt [second_countable_topology α] {f g : δ → α} (hf : measurable f) (hg : measurable g) : measurable_set {a | f a < g a} := hf.prod_mk hg measurable_set_lt' lemma set.ord_connected.measurable_set (h : ord_connected s) : measurable_set s := begin let u := ⋃ (x ∈ s) (y ∈ s), Ioo x y, have huopen : is_open u := is_open_bUnion (λ x hx, is_open_bUnion (λ y hy, is_open_Ioo)), have humeas : measurable_set u := huopen.measurable_set, have hfinite : (s \ u).finite, { refine set.finite_of_forall_between_eq_endpoints (s \ u) (λ x hx y hy z hz hxy hyz, _), by_contra' h, exact hy.2 (mem_Union₂.mpr ⟨x, hx.1, mem_Union₂.mpr ⟨z, hz.1, lt_of_le_of_ne hxy h.1, lt_of_le_of_ne hyz h.2⟩⟩) }, have : u ⊆ s := Union₂_subset (λ x hx, Union₂_subset (λ y hy, Ioo_subset_Icc_self.trans (h.out hx hy))), rw ← union_diff_cancel this, exact humeas.union hfinite.measurable_set end lemma is_preconnected.measurable_set (h : is_preconnected s) : measurable_set s := h.ord_connected.measurable_set lemma generate_from_Ico_mem_le_borel {α : Type*} [topological_space α] [linear_order α] [order_closed_topology α] (s t : set α) : measurable_space.generate_from {S | ∃ (l ∈ s) (u ∈ t) (h : l < u), Ico l u = S} ≤ borel α := begin apply generate_from_le, borelize α, rintro _ ⟨a, -, b, -, -, rfl⟩, exact measurable_set_Ico end lemma dense.borel_eq_generate_from_Ico_mem_aux {α : Type*} [topological_space α] [linear_order α] [order_topology α] [second_countable_topology α] {s : set α} (hd : dense s) (hbot : ∀ x, is_bot x → x ∈ s) (hIoo : ∀ x y : α, x < y → Ioo x y = ∅ → y ∈ s) : borel α = generate_from {S : set α | ∃ (l ∈ s) (u ∈ s) (h : l < u), Ico l u = S} := begin set S : set (set α) := {S | ∃ (l ∈ s) (u ∈ s) (h : l < u), Ico l u = S}, refine le_antisymm _ (generate_from_Ico_mem_le_borel _ _), letI : measurable_space α := generate_from S, rw borel_eq_generate_from_Iio, refine generate_from_le (forall_range_iff.2 $ λ a, _), rcases hd.exists_countable_dense_subset_bot_top with ⟨t, hts, hc, htd, htb, htt⟩, by_cases ha : ∀ b < a, (Ioo b a).nonempty, { convert_to measurable_set (⋃ (l ∈ t) (u ∈ t) (hlu : l < u) (hu : u ≤ a), Ico l u), { ext y, simp only [mem_Union, mem_Iio, mem_Ico], split, { intro hy, rcases htd.exists_le' (λ b hb, htb _ hb (hbot b hb)) y with ⟨l, hlt, hly⟩, rcases htd.exists_mem_open is_open_Ioo (ha y hy) with ⟨u, hut, hyu, hua⟩, exact ⟨l, hlt, u, hut, hly.trans_lt hyu, hua.le, hly, hyu⟩ }, { rintro ⟨l, -, u, -, -, hua, -, hyu⟩, exact hyu.trans_le hua } }, { refine measurable_set.bUnion hc (λ a ha, measurable_set.bUnion hc $ λ b hb, _), refine measurable_set.Union (λ hab, measurable_set.Union $ λ hb', _), exact generate_measurable.basic _ ⟨a, hts ha, b, hts hb, hab, mem_singleton _⟩ } }, { simp only [not_forall, not_nonempty_iff_eq_empty] at ha, replace ha : a ∈ s := hIoo ha.some a ha.some_spec.fst ha.some_spec.snd, convert_to measurable_set (⋃ (l ∈ t) (hl : l < a), Ico l a), { symmetry, simp only [← Ici_inter_Iio, ← Union_inter, inter_eq_right_iff_subset, subset_def, mem_Union, mem_Ici, mem_Iio], intros x hx, rcases htd.exists_le' (λ b hb, htb _ hb (hbot b hb)) x with ⟨z, hzt, hzx⟩, exact ⟨z, hzt, hzx.trans_lt hx, hzx⟩ }, { refine measurable_set.bUnion hc (λ x hx, measurable_set.Union $ λ hlt, _), exact generate_measurable.basic _ ⟨x, hts hx, a, ha, hlt, mem_singleton _⟩ } } end lemma dense.borel_eq_generate_from_Ico_mem {α : Type*} [topological_space α] [linear_order α] [order_topology α] [second_countable_topology α] [densely_ordered α] [no_min_order α] {s : set α} (hd : dense s) : borel α = generate_from {S : set α | ∃ (l ∈ s) (u ∈ s) (h : l < u), Ico l u = S} := hd.borel_eq_generate_from_Ico_mem_aux (by simp) $ λ x y hxy H, ((nonempty_Ioo.2 hxy).ne_empty H).elim lemma borel_eq_generate_from_Ico (α : Type*) [topological_space α] [second_countable_topology α] [linear_order α] [order_topology α] : borel α = generate_from {S : set α | ∃ l u (h : l < u), Ico l u = S} := by simpa only [exists_prop, mem_univ, true_and] using (@dense_univ α _).borel_eq_generate_from_Ico_mem_aux (λ _ _, mem_univ _) (λ _ _ _ _, mem_univ _) lemma dense.borel_eq_generate_from_Ioc_mem_aux {α : Type*} [topological_space α] [linear_order α] [order_topology α] [second_countable_topology α] {s : set α} (hd : dense s) (hbot : ∀ x, is_top x → x ∈ s) (hIoo : ∀ x y : α, x < y → Ioo x y = ∅ → x ∈ s) : borel α = generate_from {S : set α | ∃ (l ∈ s) (u ∈ s) (h : l < u), Ioc l u = S} := begin convert hd.order_dual.borel_eq_generate_from_Ico_mem_aux hbot (λ x y hlt he, hIoo y x hlt _), { ext s, split; rintro ⟨l, hl, u, hu, hlt, rfl⟩, exacts [⟨u, hu, l, hl, hlt, dual_Ico⟩, ⟨u, hu, l, hl, hlt, dual_Ioc⟩] }, { erw dual_Ioo, exact he } end lemma dense.borel_eq_generate_from_Ioc_mem {α : Type*} [topological_space α] [linear_order α] [order_topology α] [second_countable_topology α] [densely_ordered α] [no_max_order α] {s : set α} (hd : dense s) : borel α = generate_from {S : set α | ∃ (l ∈ s) (u ∈ s) (h : l < u), Ioc l u = S} := hd.borel_eq_generate_from_Ioc_mem_aux (by simp) $ λ x y hxy H, ((nonempty_Ioo.2 hxy).ne_empty H).elim lemma borel_eq_generate_from_Ioc (α : Type*) [topological_space α] [second_countable_topology α] [linear_order α] [order_topology α] : borel α = generate_from {S : set α | ∃ l u (h : l < u), Ioc l u = S} := by simpa only [exists_prop, mem_univ, true_and] using (@dense_univ α _).borel_eq_generate_from_Ioc_mem_aux (λ _ _, mem_univ _) (λ _ _ _ _, mem_univ _) namespace measure_theory.measure /-- Two finite measures on a Borel space are equal if they agree on all closed-open intervals. If `α` is a conditionally complete linear order with no top element, `measure_theory.measure..ext_of_Ico` is an extensionality lemma with weaker assumptions on `μ` and `ν`. -/ lemma ext_of_Ico_finite {α : Type*} [topological_space α] {m : measurable_space α} [second_countable_topology α] [linear_order α] [order_topology α] [borel_space α] (μ ν : measure α) [is_finite_measure μ] (hμν : μ univ = ν univ) (h : ∀ ⦃a b⦄, a < b → μ (Ico a b) = ν (Ico a b)) : μ = ν := begin refine ext_of_generate_finite _ (borel_space.measurable_eq.trans (borel_eq_generate_from_Ico α)) (is_pi_system_Ico (id : α → α) id) _ hμν, { rintro - ⟨a, b, hlt, rfl⟩, exact h hlt } end /-- Two finite measures on a Borel space are equal if they agree on all open-closed intervals. If `α` is a conditionally complete linear order with no top element, `measure_theory.measure..ext_of_Ioc` is an extensionality lemma with weaker assumptions on `μ` and `ν`. -/ lemma ext_of_Ioc_finite {α : Type*} [topological_space α] {m : measurable_space α} [second_countable_topology α] [linear_order α] [order_topology α] [borel_space α] (μ ν : measure α) [is_finite_measure μ] (hμν : μ univ = ν univ) (h : ∀ ⦃a b⦄, a < b → μ (Ioc a b) = ν (Ioc a b)) : μ = ν := begin refine @ext_of_Ico_finite αᵒᵈ _ _ _ _ _ ‹_› μ ν _ hμν (λ a b hab, _), erw dual_Ico, exact h hab end /-- Two measures which are finite on closed-open intervals are equal if the agree on all closed-open intervals. -/ lemma ext_of_Ico' {α : Type*} [topological_space α] {m : measurable_space α} [second_countable_topology α] [linear_order α] [order_topology α] [borel_space α] [no_max_order α] (μ ν : measure α) (hμ : ∀ ⦃a b⦄, a < b → μ (Ico a b) ≠ ∞) (h : ∀ ⦃a b⦄, a < b → μ (Ico a b) = ν (Ico a b)) : μ = ν := begin rcases exists_countable_dense_bot_top α with ⟨s, hsc, hsd, hsb, hst⟩, have : (⋃ (l ∈ s) (u ∈ s) (h : l < u), {Ico l u} : set (set α)).countable, from hsc.bUnion (λ l hl, hsc.bUnion (λ u hu, countable_Union $ λ _, countable_singleton _)), simp only [← set_of_eq_eq_singleton, ← set_of_exists] at this, refine measure.ext_of_generate_from_of_cover_subset (borel_space.measurable_eq.trans (borel_eq_generate_from_Ico α)) (is_pi_system_Ico id id) _ this _ _ _, { rintro _ ⟨l, -, u, -, h, rfl⟩, exact ⟨l, u, h, rfl⟩ }, { refine sUnion_eq_univ_iff.2 (λ x, _), rcases hsd.exists_le' hsb x with ⟨l, hls, hlx⟩, rcases hsd.exists_gt x with ⟨u, hus, hxu⟩, exact ⟨_, ⟨l, hls, u, hus, hlx.trans_lt hxu, rfl⟩, hlx, hxu⟩ }, { rintro _ ⟨l, -, u, -, hlt, rfl⟩, exact hμ hlt }, { rintro _ ⟨l, u, hlt, rfl⟩, exact h hlt } end /-- Two measures which are finite on closed-open intervals are equal if the agree on all open-closed intervals. -/ lemma ext_of_Ioc' {α : Type*} [topological_space α] {m : measurable_space α} [second_countable_topology α] [linear_order α] [order_topology α] [borel_space α] [no_min_order α] (μ ν : measure α) (hμ : ∀ ⦃a b⦄, a < b → μ (Ioc a b) ≠ ∞) (h : ∀ ⦃a b⦄, a < b → μ (Ioc a b) = ν (Ioc a b)) : μ = ν := begin refine @ext_of_Ico' αᵒᵈ _ _ _ _ _ ‹_› _ μ ν _ _; intros a b hab; erw dual_Ico, exacts [hμ hab, h hab] end /-- Two measures which are finite on closed-open intervals are equal if the agree on all closed-open intervals. -/ lemma ext_of_Ico {α : Type*} [topological_space α] {m : measurable_space α} [second_countable_topology α] [conditionally_complete_linear_order α] [order_topology α] [borel_space α] [no_max_order α] (μ ν : measure α) [is_locally_finite_measure μ] (h : ∀ ⦃a b⦄, a < b → μ (Ico a b) = ν (Ico a b)) : μ = ν := μ.ext_of_Ico' ν (λ a b hab, measure_Ico_lt_top.ne) h /-- Two measures which are finite on closed-open intervals are equal if the agree on all open-closed intervals. -/ lemma ext_of_Ioc {α : Type*} [topological_space α] {m : measurable_space α} [second_countable_topology α] [conditionally_complete_linear_order α] [order_topology α] [borel_space α] [no_min_order α] (μ ν : measure α) [is_locally_finite_measure μ] (h : ∀ ⦃a b⦄, a < b → μ (Ioc a b) = ν (Ioc a b)) : μ = ν := μ.ext_of_Ioc' ν (λ a b hab, measure_Ioc_lt_top.ne) h /-- Two finite measures on a Borel space are equal if they agree on all left-infinite right-closed intervals. -/ lemma ext_of_Iic {α : Type*} [topological_space α] {m : measurable_space α} [second_countable_topology α] [linear_order α] [order_topology α] [borel_space α] (μ ν : measure α) [is_finite_measure μ] (h : ∀ a, μ (Iic a) = ν (Iic a)) : μ = ν := begin refine ext_of_Ioc_finite μ ν _ (λ a b hlt, _), { rcases exists_countable_dense_bot_top α with ⟨s, hsc, hsd, -, hst⟩, have : directed_on (≤) s, from directed_on_iff_directed.2 (directed_of_sup $ λ _ _, id), simp only [← bsupr_measure_Iic hsc (hsd.exists_ge' hst) this, h] }, rw [← Iic_diff_Iic, measure_diff (Iic_subset_Iic.2 hlt.le) measurable_set_Iic, measure_diff (Iic_subset_Iic.2 hlt.le) measurable_set_Iic, h a, h b], { rw ← h a, exact (measure_lt_top μ _).ne }, { exact (measure_lt_top μ _).ne } end /-- Two finite measures on a Borel space are equal if they agree on all left-closed right-infinite intervals. -/ lemma ext_of_Ici {α : Type*} [topological_space α] {m : measurable_space α} [second_countable_topology α] [linear_order α] [order_topology α] [borel_space α] (μ ν : measure α) [is_finite_measure μ] (h : ∀ a, μ (Ici a) = ν (Ici a)) : μ = ν := @ext_of_Iic αᵒᵈ _ _ _ _ _ ‹_› _ _ _ h end measure_theory.measure end linear_order section linear_order variables [linear_order α] [order_closed_topology α] @[measurability] lemma measurable_set_interval {a b : α} : measurable_set (interval a b) := measurable_set_Icc @[measurability] lemma measurable_set_interval_oc {a b : α} : measurable_set (interval_oc a b) := measurable_set_Ioc variables [second_countable_topology α] @[measurability] lemma measurable.max {f g : δ → α} (hf : measurable f) (hg : measurable g) : measurable (λ a, max (f a) (g a)) := by simpa only [max_def] using hf.piecewise (measurable_set_le hg hf) hg @[measurability] lemma ae_measurable.max {f g : δ → α} {μ : measure δ} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ a, max (f a) (g a)) μ := ⟨λ a, max (hf.mk f a) (hg.mk g a), hf.measurable_mk.max hg.measurable_mk, eventually_eq.comp₂ hf.ae_eq_mk _ hg.ae_eq_mk⟩ @[measurability] lemma measurable.min {f g : δ → α} (hf : measurable f) (hg : measurable g) : measurable (λ a, min (f a) (g a)) := by simpa only [min_def] using hf.piecewise (measurable_set_le hf hg) hg @[measurability] lemma ae_measurable.min {f g : δ → α} {μ : measure δ} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ a, min (f a) (g a)) μ := ⟨λ a, min (hf.mk f a) (hg.mk g a), hf.measurable_mk.min hg.measurable_mk, eventually_eq.comp₂ hf.ae_eq_mk _ hg.ae_eq_mk⟩ end linear_order /-- A continuous function from an `opens_measurable_space` to a `borel_space` is measurable. -/ lemma continuous.measurable {f : α → γ} (hf : continuous f) : measurable f := hf.borel_measurable.mono opens_measurable_space.borel_le (le_of_eq $ borel_space.measurable_eq) /-- A continuous function from an `opens_measurable_space` to a `borel_space` is ae-measurable. -/ lemma continuous.ae_measurable {f : α → γ} (h : continuous f) {μ : measure α} : ae_measurable f μ := h.measurable.ae_measurable lemma closed_embedding.measurable {f : α → γ} (hf : closed_embedding f) : measurable f := hf.continuous.measurable lemma continuous.is_open_pos_measure_map {f : β → γ} (hf : continuous f) (hf_surj : function.surjective f) {μ : measure β} [μ.is_open_pos_measure] : (measure.map f μ).is_open_pos_measure := begin refine ⟨λ U hUo hUne, _⟩, rw [measure.map_apply hf.measurable hUo.measurable_set], exact (hUo.preimage hf).measure_ne_zero μ (hf_surj.nonempty_preimage.mpr hUne) end /-- If a function is defined piecewise in terms of functions which are continuous on their respective pieces, then it is measurable. -/ lemma continuous_on.measurable_piecewise {f g : α → γ} {s : set α} [Π (j : α), decidable (j ∈ s)] (hf : continuous_on f s) (hg : continuous_on g sᶜ) (hs : measurable_set s) : measurable (s.piecewise f g) := begin refine measurable_of_is_open (λ t ht, _), rw [piecewise_preimage, set.ite], apply measurable_set.union, { rcases _root_.continuous_on_iff'.1 hf t ht with ⟨u, u_open, hu⟩, rw hu, exact u_open.measurable_set.inter hs }, { rcases _root_.continuous_on_iff'.1 hg t ht with ⟨u, u_open, hu⟩, rw [diff_eq_compl_inter, inter_comm, hu], exact u_open.measurable_set.inter hs.compl } end @[priority 100, to_additive] instance has_continuous_mul.has_measurable_mul [has_mul γ] [has_continuous_mul γ] : has_measurable_mul γ := { measurable_const_mul := λ c, (continuous_const.mul continuous_id).measurable, measurable_mul_const := λ c, (continuous_id.mul continuous_const).measurable } @[priority 100] instance has_continuous_sub.has_measurable_sub [has_sub γ] [has_continuous_sub γ] : has_measurable_sub γ := { measurable_const_sub := λ c, (continuous_const.sub continuous_id).measurable, measurable_sub_const := λ c, (continuous_id.sub continuous_const).measurable } @[priority 100, to_additive] instance topological_group.has_measurable_inv [group γ] [topological_group γ] : has_measurable_inv γ := ⟨continuous_inv.measurable⟩ @[priority 100] instance has_continuous_smul.has_measurable_smul {M α} [topological_space M] [topological_space α] [measurable_space M] [measurable_space α] [opens_measurable_space M] [borel_space α] [has_smul M α] [has_continuous_smul M α] : has_measurable_smul M α := ⟨λ c, (continuous_const_smul _).measurable, λ y, (continuous_id.smul continuous_const).measurable⟩ section lattice @[priority 100] instance has_continuous_sup.has_measurable_sup [has_sup γ] [has_continuous_sup γ] : has_measurable_sup γ := { measurable_const_sup := λ c, (continuous_const.sup continuous_id).measurable, measurable_sup_const := λ c, (continuous_id.sup continuous_const).measurable } @[priority 100] instance has_continuous_sup.has_measurable_sup₂ [second_countable_topology γ] [has_sup γ] [has_continuous_sup γ] : has_measurable_sup₂ γ := ⟨continuous_sup.measurable⟩ @[priority 100] instance has_continuous_inf.has_measurable_inf [has_inf γ] [has_continuous_inf γ] : has_measurable_inf γ := { measurable_const_inf := λ c, (continuous_const.inf continuous_id).measurable, measurable_inf_const := λ c, (continuous_id.inf continuous_const).measurable } @[priority 100] instance has_continuous_inf.has_measurable_inf₂ [second_countable_topology γ] [has_inf γ] [has_continuous_inf γ] : has_measurable_inf₂ γ := ⟨continuous_inf.measurable⟩ end lattice section homeomorph @[measurability] protected lemma homeomorph.measurable (h : α ≃ₜ γ) : measurable h := h.continuous.measurable /-- A homeomorphism between two Borel spaces is a measurable equivalence.-/ def homeomorph.to_measurable_equiv (h : γ ≃ₜ γ₂) : γ ≃ᵐ γ₂ := { measurable_to_fun := h.measurable, measurable_inv_fun := h.symm.measurable, to_equiv := h.to_equiv } @[simp] lemma homeomorph.to_measurable_equiv_coe (h : γ ≃ₜ γ₂) : (h.to_measurable_equiv : γ → γ₂) = h := rfl @[simp] lemma homeomorph.to_measurable_equiv_symm_coe (h : γ ≃ₜ γ₂) : (h.to_measurable_equiv.symm : γ₂ → γ) = h.symm := rfl end homeomorph @[measurability] lemma continuous_map.measurable (f : C(α, γ)) : measurable f := f.continuous.measurable lemma measurable_of_continuous_on_compl_singleton [t1_space α] {f : α → γ} (a : α) (hf : continuous_on f {a}ᶜ) : measurable f := measurable_of_measurable_on_compl_singleton a (continuous_on_iff_continuous_restrict.1 hf).measurable lemma continuous.measurable2 [second_countable_topology α] [second_countable_topology β] {f : δ → α} {g : δ → β} {c : α → β → γ} (h : continuous (λ p : α × β, c p.1 p.2)) (hf : measurable f) (hg : measurable g) : measurable (λ a, c (f a) (g a)) := h.measurable.comp (hf.prod_mk hg) lemma continuous.ae_measurable2 [second_countable_topology α] [second_countable_topology β] {f : δ → α} {g : δ → β} {c : α → β → γ} {μ : measure δ} (h : continuous (λ p : α × β, c p.1 p.2)) (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ a, c (f a) (g a)) μ := h.measurable.comp_ae_measurable (hf.prod_mk hg) @[priority 100] instance has_continuous_inv₀.has_measurable_inv [group_with_zero γ] [t1_space γ] [has_continuous_inv₀ γ] : has_measurable_inv γ := ⟨measurable_of_continuous_on_compl_singleton 0 continuous_on_inv₀⟩ @[priority 100, to_additive] instance has_continuous_mul.has_measurable_mul₂ [second_countable_topology γ] [has_mul γ] [has_continuous_mul γ] : has_measurable_mul₂ γ := ⟨continuous_mul.measurable⟩ @[priority 100] instance has_continuous_sub.has_measurable_sub₂ [second_countable_topology γ] [has_sub γ] [has_continuous_sub γ] : has_measurable_sub₂ γ := ⟨continuous_sub.measurable⟩ @[priority 100] instance has_continuous_smul.has_measurable_smul₂ {M α} [topological_space M] [second_countable_topology M] [measurable_space M] [opens_measurable_space M] [topological_space α] [second_countable_topology α] [measurable_space α] [borel_space α] [has_smul M α] [has_continuous_smul M α] : has_measurable_smul₂ M α := ⟨continuous_smul.measurable⟩ end section borel_space variables [topological_space α] [measurable_space α] [borel_space α] [topological_space β] [measurable_space β] [borel_space β] [topological_space γ] [measurable_space γ] [borel_space γ] [measurable_space δ] lemma pi_le_borel_pi {ι : Type*} {π : ι → Type*} [Π i, topological_space (π i)] [Π i, measurable_space (π i)] [∀ i, borel_space (π i)] : measurable_space.pi ≤ borel (Π i, π i) := begin have : ‹Π i, measurable_space (π i)› = λ i, borel (π i) := funext (λ i, borel_space.measurable_eq), rw [this], exact supr_le (λ i, comap_le_iff_le_map.2 $ (continuous_apply i).borel_measurable) end lemma prod_le_borel_prod : prod.measurable_space ≤ borel (α × β) := begin rw [‹borel_space α›.measurable_eq, ‹borel_space β›.measurable_eq], refine sup_le _ _, { exact comap_le_iff_le_map.mpr continuous_fst.borel_measurable }, { exact comap_le_iff_le_map.mpr continuous_snd.borel_measurable } end instance pi.borel_space {ι : Type*} {π : ι → Type*} [countable ι] [Π i, topological_space (π i)] [Π i, measurable_space (π i)] [∀ i, second_countable_topology (π i)] [∀ i, borel_space (π i)] : borel_space (Π i, π i) := ⟨le_antisymm pi_le_borel_pi opens_measurable_space.borel_le⟩ instance prod.borel_space [second_countable_topology α] [second_countable_topology β] : borel_space (α × β) := ⟨le_antisymm prod_le_borel_prod opens_measurable_space.borel_le⟩ protected lemma embedding.measurable_embedding {f : α → β} (h₁ : embedding f) (h₂ : measurable_set (range f)) : measurable_embedding f := show measurable_embedding (coe ∘ (homeomorph.of_embedding f h₁).to_measurable_equiv), from (measurable_embedding.subtype_coe h₂).comp (measurable_equiv.measurable_embedding _) protected lemma closed_embedding.measurable_embedding {f : α → β} (h : closed_embedding f) : measurable_embedding f := h.to_embedding.measurable_embedding h.closed_range.measurable_set protected lemma open_embedding.measurable_embedding {f : α → β} (h : open_embedding f) : measurable_embedding f := h.to_embedding.measurable_embedding h.open_range.measurable_set section linear_order variables [linear_order α] [order_topology α] [second_countable_topology α] lemma measurable_of_Iio {f : δ → α} (hf : ∀ x, measurable_set (f ⁻¹' Iio x)) : measurable f := begin convert measurable_generate_from _, exact borel_space.measurable_eq.trans (borel_eq_generate_from_Iio _), rintro _ ⟨x, rfl⟩, exact hf x end lemma upper_semicontinuous.measurable [topological_space δ] [opens_measurable_space δ] {f : δ → α} (hf : upper_semicontinuous f) : measurable f := measurable_of_Iio (λ y, (hf.is_open_preimage y).measurable_set) lemma measurable_of_Ioi {f : δ → α} (hf : ∀ x, measurable_set (f ⁻¹' Ioi x)) : measurable f := begin convert measurable_generate_from _, exact borel_space.measurable_eq.trans (borel_eq_generate_from_Ioi _), rintro _ ⟨x, rfl⟩, exact hf x end lemma lower_semicontinuous.measurable [topological_space δ] [opens_measurable_space δ] {f : δ → α} (hf : lower_semicontinuous f) : measurable f := measurable_of_Ioi (λ y, (hf.is_open_preimage y).measurable_set) lemma measurable_of_Iic {f : δ → α} (hf : ∀ x, measurable_set (f ⁻¹' Iic x)) : measurable f := begin apply measurable_of_Ioi, simp_rw [← compl_Iic, preimage_compl, measurable_set.compl_iff], assumption end lemma measurable_of_Ici {f : δ → α} (hf : ∀ x, measurable_set (f ⁻¹' Ici x)) : measurable f := begin apply measurable_of_Iio, simp_rw [← compl_Ici, preimage_compl, measurable_set.compl_iff], assumption end lemma measurable.is_lub {ι} [countable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, measurable (f i)) (hg : ∀ b, is_lub {a | ∃ i, f i b = a} (g b)) : measurable g := begin change ∀ b, is_lub (range $ λ i, f i b) (g b) at hg, rw [‹borel_space α›.measurable_eq, borel_eq_generate_from_Ioi α], apply measurable_generate_from, rintro _ ⟨a, rfl⟩, simp_rw [set.preimage, mem_Ioi, lt_is_lub_iff (hg _), exists_range_iff, set_of_exists], exact measurable_set.Union (λ i, hf i (is_open_lt' _).measurable_set) end private lemma ae_measurable.is_lub_of_nonempty {ι} (hι : nonempty ι) {μ : measure δ} [countable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, ae_measurable (f i) μ) (hg : ∀ᵐ b ∂μ, is_lub {a | ∃ i, f i b = a} (g b)) : ae_measurable g μ := begin let p : δ → (ι → α) → Prop := λ x f', is_lub {a | ∃ i, f' i = a} (g x), let g_seq := λ x, ite (x ∈ ae_seq_set hf p) (g x) (⟨g x⟩ : nonempty α).some, have hg_seq : ∀ b, is_lub {a | ∃ i, ae_seq hf p i b = a} (g_seq b), { intro b, haveI hα : nonempty α := nonempty.map g ⟨b⟩, simp only [ae_seq, g_seq], split_ifs, { have h_set_eq : {a : α | ∃ (i : ι), (hf i).mk (f i) b = a} = {a : α | ∃ (i : ι), f i b = a}, { ext x, simp_rw [set.mem_set_of_eq, ae_seq.mk_eq_fun_of_mem_ae_seq_set hf h], }, rw h_set_eq, exact ae_seq.fun_prop_of_mem_ae_seq_set hf h, }, { have h_singleton : {a : α | ∃ (i : ι), hα.some = a} = {hα.some}, { ext1 x, exact ⟨λ hx, hx.some_spec.symm, λ hx, ⟨hι.some, hx.symm⟩⟩, }, rw h_singleton, exact is_lub_singleton, }, }, refine ⟨g_seq, measurable.is_lub (ae_seq.measurable hf p) hg_seq, _⟩, exact (ite_ae_eq_of_measure_compl_zero g (λ x, (⟨g x⟩ : nonempty α).some) (ae_seq_set hf p) (ae_seq.measure_compl_ae_seq_set_eq_zero hf hg)).symm, end lemma ae_measurable.is_lub {ι} {μ : measure δ} [countable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, ae_measurable (f i) μ) (hg : ∀ᵐ b ∂μ, is_lub {a | ∃ i, f i b = a} (g b)) : ae_measurable g μ := begin by_cases hμ : μ = 0, { rw hμ, exact ae_measurable_zero_measure }, haveI : μ.ae.ne_bot, { simpa [ne_bot_iff] }, by_cases hι : nonempty ι, { exact ae_measurable.is_lub_of_nonempty hι hf hg, }, suffices : ∃ x, g =ᵐ[μ] λ y, g x, by { exact ⟨(λ y, g this.some), measurable_const, this.some_spec⟩, }, have h_empty : ∀ x, {a : α | ∃ (i : ι), f i x = a} = ∅, { intro x, ext1 y, rw [set.mem_set_of_eq, set.mem_empty_eq, iff_false], exact λ hi, hι (nonempty_of_exists hi), }, simp_rw h_empty at hg, exact ⟨hg.exists.some, hg.mono (λ y hy, is_lub.unique hy hg.exists.some_spec)⟩, end lemma measurable.is_glb {ι} [countable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, measurable (f i)) (hg : ∀ b, is_glb {a | ∃ i, f i b = a} (g b)) : measurable g := begin change ∀ b, is_glb (range $ λ i, f i b) (g b) at hg, rw [‹borel_space α›.measurable_eq, borel_eq_generate_from_Iio α], apply measurable_generate_from, rintro _ ⟨a, rfl⟩, simp_rw [set.preimage, mem_Iio, is_glb_lt_iff (hg _), exists_range_iff, set_of_exists], exact measurable_set.Union (λ i, hf i (is_open_gt' _).measurable_set) end private lemma ae_measurable.is_glb_of_nonempty {ι} (hι : nonempty ι) {μ : measure δ} [countable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, ae_measurable (f i) μ) (hg : ∀ᵐ b ∂μ, is_glb {a | ∃ i, f i b = a} (g b)) : ae_measurable g μ := begin let p : δ → (ι → α) → Prop := λ x f', is_glb {a | ∃ i, f' i = a} (g x), let g_seq := λ x, ite (x ∈ ae_seq_set hf p) (g x) (⟨g x⟩ : nonempty α).some, have hg_seq : ∀ b, is_glb {a | ∃ i, ae_seq hf p i b = a} (g_seq b), { intro b, haveI hα : nonempty α := nonempty.map g ⟨b⟩, simp only [ae_seq, g_seq], split_ifs, { have h_set_eq : {a : α | ∃ (i : ι), (hf i).mk (f i) b = a} = {a : α | ∃ (i : ι), f i b = a}, { ext x, simp_rw [set.mem_set_of_eq, ae_seq.mk_eq_fun_of_mem_ae_seq_set hf h], }, rw h_set_eq, exact ae_seq.fun_prop_of_mem_ae_seq_set hf h, }, { have h_singleton : {a : α | ∃ (i : ι), hα.some = a} = {hα.some}, { ext1 x, exact ⟨λ hx, hx.some_spec.symm, λ hx, ⟨hι.some, hx.symm⟩⟩, }, rw h_singleton, exact is_glb_singleton, }, }, refine ⟨g_seq, measurable.is_glb (ae_seq.measurable hf p) hg_seq, _⟩, exact (ite_ae_eq_of_measure_compl_zero g (λ x, (⟨g x⟩ : nonempty α).some) (ae_seq_set hf p) (ae_seq.measure_compl_ae_seq_set_eq_zero hf hg)).symm, end lemma ae_measurable.is_glb {ι} {μ : measure δ} [countable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, ae_measurable (f i) μ) (hg : ∀ᵐ b ∂μ, is_glb {a | ∃ i, f i b = a} (g b)) : ae_measurable g μ := begin by_cases hμ : μ = 0, { rw hμ, exact ae_measurable_zero_measure }, haveI : μ.ae.ne_bot, { simpa [ne_bot_iff] }, by_cases hι : nonempty ι, { exact ae_measurable.is_glb_of_nonempty hι hf hg, }, suffices : ∃ x, g =ᵐ[μ] λ y, g x, by { exact ⟨(λ y, g this.some), measurable_const, this.some_spec⟩, }, have h_empty : ∀ x, {a : α | ∃ (i : ι), f i x = a} = ∅, { intro x, ext1 y, rw [set.mem_set_of_eq, set.mem_empty_eq, iff_false], exact λ hi, hι (nonempty_of_exists hi), }, simp_rw h_empty at hg, exact ⟨hg.exists.some, hg.mono (λ y hy, is_glb.unique hy hg.exists.some_spec)⟩, end protected lemma monotone.measurable [linear_order β] [order_closed_topology β] {f : β → α} (hf : monotone f) : measurable f := suffices h : ∀ x, ord_connected (f ⁻¹' Ioi x), from measurable_of_Ioi (λ x, (h x).measurable_set), λ x, ord_connected_def.mpr (λ a ha b hb c hc, lt_of_lt_of_le ha (hf hc.1)) lemma ae_measurable_restrict_of_monotone_on [linear_order β] [order_closed_topology β] {μ : measure β} {s : set β} (hs : measurable_set s) {f : β → α} (hf : monotone_on f s) : ae_measurable f (μ.restrict s) := have this : monotone (f ∘ coe : s → α), from λ ⟨x, hx⟩ ⟨y, hy⟩ (hxy : x ≤ y), hf hx hy hxy, ae_measurable_restrict_of_measurable_subtype hs this.measurable protected lemma antitone.measurable [linear_order β] [order_closed_topology β] {f : β → α} (hf : antitone f) : measurable f := @monotone.measurable αᵒᵈ β _ _ ‹_› _ _ _ _ _ ‹_› _ _ _ hf lemma ae_measurable_restrict_of_antitone_on [linear_order β] [order_closed_topology β] {μ : measure β} {s : set β} (hs : measurable_set s) {f : β → α} (hf : antitone_on f s) : ae_measurable f (μ.restrict s) := @ae_measurable_restrict_of_monotone_on αᵒᵈ β _ _ ‹_› _ _ _ _ _ ‹_› _ _ _ _ hs _ hf lemma measurable_set_of_mem_nhds_within_Ioi_aux {s : set α} (h : ∀ x ∈ s, s ∈ 𝓝[>] x) (h' : ∀ x ∈ s, ∃ y, x < y) : measurable_set s := begin choose! M hM using h', suffices H : (s \ interior s).countable, { have : s = interior s ∪ (s \ interior s), by rw union_diff_cancel interior_subset, rw this, exact is_open_interior.measurable_set.union H.measurable_set }, have A : ∀ x ∈ s, ∃ y ∈ Ioi x, Ioo x y ⊆ s := λ x hx, (mem_nhds_within_Ioi_iff_exists_Ioo_subset' (hM x hx)).1 (h x hx), choose! y hy h'y using A, have B : set.pairwise_disjoint (s \ interior s) (λ x, Ioo x (y x)), { assume x hx x' hx' hxx', rcases lt_or_gt_of_ne hxx' with h'|h', { apply disjoint_left.2 (λ z hz h'z, _), have : x' ∈ interior s := mem_interior.2 ⟨Ioo x (y x), h'y _ hx.1, is_open_Ioo, ⟨h', h'z.1.trans hz.2⟩⟩, exact false.elim (hx'.2 this) }, { apply disjoint_left.2 (λ z hz h'z, _), have : x ∈ interior s := mem_interior.2 ⟨Ioo x' (y x'), h'y _ hx'.1, is_open_Ioo, ⟨h', hz.1.trans h'z.2⟩⟩, exact false.elim (hx.2 this) } }, exact B.countable_of_Ioo (λ x hx, hy x hx.1), end /-- If a set is a right-neighborhood of all of its points, then it is measurable. -/ lemma measurable_set_of_mem_nhds_within_Ioi {s : set α} (h : ∀ x ∈ s, s ∈ 𝓝[>] x) : measurable_set s := begin by_cases H : ∃ x ∈ s, is_top x, { rcases H with ⟨x₀, x₀s, h₀⟩, have : s = {x₀} ∪ (s \ {x₀}), by rw union_diff_cancel (singleton_subset_iff.2 x₀s), rw this, refine (measurable_set_singleton _).union _, have A : ∀ x ∈ s \ {x₀}, x < x₀ := λ x hx, lt_of_le_of_ne (h₀ _) (by simpa using hx.2), refine measurable_set_of_mem_nhds_within_Ioi_aux (λ x hx, _) (λ x hx, ⟨x₀, A x hx⟩), obtain ⟨u, hu, us⟩ : ∃ (u : α) (H : u ∈ Ioi x), Ioo x u ⊆ s := (mem_nhds_within_Ioi_iff_exists_Ioo_subset' (A x hx)).1 (h x hx.1), refine (mem_nhds_within_Ioi_iff_exists_Ioo_subset' (A x hx)).2 ⟨u, hu, λ y hy, ⟨us hy, _⟩⟩, exact ne_of_lt (hy.2.trans_le (h₀ _)) }, { apply measurable_set_of_mem_nhds_within_Ioi_aux h, simp only [is_top] at H, push_neg at H, exact H } end end linear_order @[measurability] lemma measurable.supr_Prop {α} [measurable_space α] [complete_lattice α] (p : Prop) {f : δ → α} (hf : measurable f) : measurable (λ b, ⨆ h : p, f b) := classical.by_cases (assume h : p, begin convert hf, funext, exact supr_pos h end) (assume h : ¬p, begin convert measurable_const, funext, exact supr_neg h end) @[measurability] lemma measurable.infi_Prop {α} [measurable_space α] [complete_lattice α] (p : Prop) {f : δ → α} (hf : measurable f) : measurable (λ b, ⨅ h : p, f b) := classical.by_cases (assume h : p, begin convert hf, funext, exact infi_pos h end ) (assume h : ¬p, begin convert measurable_const, funext, exact infi_neg h end) section complete_linear_order variables [complete_linear_order α] [order_topology α] [second_countable_topology α] @[measurability] lemma measurable_supr {ι} [countable ι] {f : ι → δ → α} (hf : ∀ i, measurable (f i)) : measurable (λ b, ⨆ i, f i b) := measurable.is_lub hf $ λ b, is_lub_supr @[measurability] lemma ae_measurable_supr {ι} {μ : measure δ} [countable ι] {f : ι → δ → α} (hf : ∀ i, ae_measurable (f i) μ) : ae_measurable (λ b, ⨆ i, f i b) μ := ae_measurable.is_lub hf $ (ae_of_all μ (λ b, is_lub_supr)) @[measurability] lemma measurable_infi {ι} [countable ι] {f : ι → δ → α} (hf : ∀ i, measurable (f i)) : measurable (λ b, ⨅ i, f i b) := measurable.is_glb hf $ λ b, is_glb_infi @[measurability] lemma ae_measurable_infi {ι} {μ : measure δ} [countable ι] {f : ι → δ → α} (hf : ∀ i, ae_measurable (f i) μ) : ae_measurable (λ b, ⨅ i, f i b) μ := ae_measurable.is_glb hf $ (ae_of_all μ (λ b, is_glb_infi)) lemma measurable_bsupr {ι} (s : set ι) {f : ι → δ → α} (hs : s.countable) (hf : ∀ i, measurable (f i)) : measurable (λ b, ⨆ i ∈ s, f i b) := by { haveI : encodable s := hs.to_encodable, simp only [supr_subtype'], exact measurable_supr (λ i, hf i) } lemma ae_measurable_bsupr {ι} {μ : measure δ} (s : set ι) {f : ι → δ → α} (hs : s.countable) (hf : ∀ i, ae_measurable (f i) μ) : ae_measurable (λ b, ⨆ i ∈ s, f i b) μ := begin haveI : encodable s := hs.to_encodable, simp only [supr_subtype'], exact ae_measurable_supr (λ i, hf i), end lemma measurable_binfi {ι} (s : set ι) {f : ι → δ → α} (hs : s.countable) (hf : ∀ i, measurable (f i)) : measurable (λ b, ⨅ i ∈ s, f i b) := by { haveI : encodable s := hs.to_encodable, simp only [infi_subtype'], exact measurable_infi (λ i, hf i) } lemma ae_measurable_binfi {ι} {μ : measure δ} (s : set ι) {f : ι → δ → α} (hs : s.countable) (hf : ∀ i, ae_measurable (f i) μ) : ae_measurable (λ b, ⨅ i ∈ s, f i b) μ := begin haveI : encodable s := hs.to_encodable, simp only [infi_subtype'], exact ae_measurable_infi (λ i, hf i), end /-- `liminf` over a general filter is measurable. See `measurable_liminf` for the version over `ℕ`. -/ lemma measurable_liminf' {ι ι'} {f : ι → δ → α} {u : filter ι} (hf : ∀ i, measurable (f i)) {p : ι' → Prop} {s : ι' → set ι} (hu : u.has_countable_basis p s) (hs : ∀ i, (s i).countable) : measurable (λ x, liminf u (λ i, f i x)) := begin simp_rw [hu.to_has_basis.liminf_eq_supr_infi], refine measurable_bsupr _ hu.countable _, exact λ i, measurable_binfi _ (hs i) hf end /-- `limsup` over a general filter is measurable. See `measurable_limsup` for the version over `ℕ`. -/ lemma measurable_limsup' {ι ι'} {f : ι → δ → α} {u : filter ι} (hf : ∀ i, measurable (f i)) {p : ι' → Prop} {s : ι' → set ι} (hu : u.has_countable_basis p s) (hs : ∀ i, (s i).countable) : measurable (λ x, limsup u (λ i, f i x)) := begin simp_rw [hu.to_has_basis.limsup_eq_infi_supr], refine measurable_binfi _ hu.countable _, exact λ i, measurable_bsupr _ (hs i) hf end /-- `liminf` over `ℕ` is measurable. See `measurable_liminf'` for a version with a general filter. -/ @[measurability] lemma measurable_liminf {f : ℕ → δ → α} (hf : ∀ i, measurable (f i)) : measurable (λ x, liminf at_top (λ i, f i x)) := measurable_liminf' hf at_top_countable_basis (λ i, to_countable _) /-- `limsup` over `ℕ` is measurable. See `measurable_limsup'` for a version with a general filter. -/ @[measurability] lemma measurable_limsup {f : ℕ → δ → α} (hf : ∀ i, measurable (f i)) : measurable (λ x, limsup at_top (λ i, f i x)) := measurable_limsup' hf at_top_countable_basis (λ i, to_countable _) end complete_linear_order section conditionally_complete_linear_order variables [conditionally_complete_linear_order α] [order_topology α] [second_countable_topology α] lemma measurable_cSup {ι} {f : ι → δ → α} {s : set ι} (hs : s.countable) (hf : ∀ i, measurable (f i)) (bdd : ∀ x, bdd_above ((λ i, f i x) '' s)) : measurable (λ x, Sup ((λ i, f i x) '' s)) := begin cases eq_empty_or_nonempty s with h2s h2s, { simp [h2s, measurable_const] }, { apply measurable_of_Iic, intro y, simp_rw [preimage, mem_Iic, cSup_le_iff (bdd _) (h2s.image _), ball_image_iff, set_of_forall], exact measurable_set.bInter hs (λ i hi, measurable_set_le (hf i) measurable_const) } end end conditionally_complete_linear_order /-- Convert a `homeomorph` to a `measurable_equiv`. -/ def homemorph.to_measurable_equiv (h : α ≃ₜ β) : α ≃ᵐ β := { to_equiv := h.to_equiv, measurable_to_fun := h.continuous_to_fun.measurable, measurable_inv_fun := h.continuous_inv_fun.measurable } protected lemma is_finite_measure_on_compacts.map {α : Type*} {m0 : measurable_space α} [topological_space α] [opens_measurable_space α] {β : Type*} [measurable_space β] [topological_space β] [borel_space β] [t2_space β] (μ : measure α) [is_finite_measure_on_compacts μ] (f : α ≃ₜ β) : is_finite_measure_on_compacts (measure.map f μ) := ⟨begin assume K hK, rw [measure.map_apply f.measurable hK.measurable_set], apply is_compact.measure_lt_top, rwa f.compact_preimage end⟩ end borel_space instance empty.borel_space : borel_space empty := ⟨borel_eq_top_of_discrete.symm⟩ instance unit.borel_space : borel_space unit := ⟨borel_eq_top_of_discrete.symm⟩ instance bool.borel_space : borel_space bool := ⟨borel_eq_top_of_discrete.symm⟩ instance nat.borel_space : borel_space ℕ := ⟨borel_eq_top_of_discrete.symm⟩ instance int.borel_space : borel_space ℤ := ⟨borel_eq_top_of_discrete.symm⟩ instance rat.borel_space : borel_space ℚ := ⟨borel_eq_top_of_countable.symm⟩ @[priority 900] instance is_R_or_C.measurable_space {𝕜 : Type*} [is_R_or_C 𝕜] : measurable_space 𝕜 := borel 𝕜 @[priority 900] instance is_R_or_C.borel_space {𝕜 : Type*} [is_R_or_C 𝕜] : borel_space 𝕜 := ⟨rfl⟩ /- Instances on `real` and `complex` are special cases of `is_R_or_C` but without these instances, Lean fails to prove `borel_space (ι → ℝ)`, so we leave them here. -/ instance real.measurable_space : measurable_space ℝ := borel ℝ instance real.borel_space : borel_space ℝ := ⟨rfl⟩ instance nnreal.measurable_space : measurable_space ℝ≥0 := subtype.measurable_space instance nnreal.borel_space : borel_space ℝ≥0 := subtype.borel_space _ instance ennreal.measurable_space : measurable_space ℝ≥0∞ := borel ℝ≥0∞ instance ennreal.borel_space : borel_space ℝ≥0∞ := ⟨rfl⟩ instance ereal.measurable_space : measurable_space ereal := borel ereal instance ereal.borel_space : borel_space ereal := ⟨rfl⟩ instance complex.measurable_space : measurable_space ℂ := borel ℂ instance complex.borel_space : borel_space ℂ := ⟨rfl⟩ /-- One can cut out `ℝ≥0∞` into the sets `{0}`, `Ico (t^n) (t^(n+1))` for `n : ℤ` and `{∞}`. This gives a way to compute the measure of a set in terms of sets on which a given function `f` does not fluctuate by more than `t`. -/ lemma measure_eq_measure_preimage_add_measure_tsum_Ico_zpow [measurable_space α] (μ : measure α) {f : α → ℝ≥0∞} (hf : measurable f) {s : set α} (hs : measurable_set s) {t : ℝ≥0} (ht : 1 < t) : μ s = μ (s ∩ f⁻¹' {0}) + μ (s ∩ f⁻¹' {∞}) + ∑' (n : ℤ), μ (s ∩ f⁻¹' (Ico (t^n) (t^(n+1)))) := begin have A : μ s = μ (s ∩ f⁻¹' {0}) + μ (s ∩ f⁻¹' (Ioi 0)), { rw ← measure_union, { congr' 1, ext x, have : 0 = f x ∨ 0 < f x := eq_or_lt_of_le bot_le, rw eq_comm at this, simp only [←and_or_distrib_left, this, mem_singleton_iff, mem_inter_eq, and_true, mem_union_eq, mem_Ioi, mem_preimage], }, { apply disjoint_left.2 (λ x hx h'x, _), have : 0 < f x := h'x.2, exact lt_irrefl 0 (this.trans_le hx.2.le) }, { exact hs.inter (hf measurable_set_Ioi) } }, have B : μ (s ∩ f⁻¹' (Ioi 0)) = μ (s ∩ f⁻¹' {∞}) + μ (s ∩ f⁻¹' (Ioo 0 ∞)), { rw ← measure_union, { rw ← inter_union_distrib_left, congr, ext x, simp only [mem_singleton_iff, mem_union_eq, mem_Ioo, mem_Ioi, mem_preimage], have H : f x = ∞ ∨ f x < ∞ := eq_or_lt_of_le le_top, cases H, { simp only [H, eq_self_iff_true, or_false, with_top.zero_lt_top, not_top_lt, and_false] }, { simp only [H, H.ne, and_true, false_or] } }, { apply disjoint_left.2 (λ x hx h'x, _), have : f x < ∞ := h'x.2.2, exact lt_irrefl _ (this.trans_le (le_of_eq hx.2.symm)) }, { exact hs.inter (hf measurable_set_Ioo) } }, have C : μ (s ∩ f⁻¹' (Ioo 0 ∞)) = ∑' (n : ℤ), μ (s ∩ f⁻¹' (Ico (t^n) (t^(n+1)))), { rw [← measure_Union, ennreal.Ioo_zero_top_eq_Union_Ico_zpow (ennreal.one_lt_coe_iff.2 ht) ennreal.coe_ne_top, preimage_Union, inter_Union], { assume i j, simp only [function.on_fun], wlog h : i ≤ j := le_total i j using [i j, j i] tactic.skip, { assume hij, replace hij : i + 1 ≤ j := lt_of_le_of_ne h hij, apply disjoint_left.2 (λ x hx h'x, lt_irrefl (f x) _), calc f x < t ^ (i + 1) : hx.2.2 ... ≤ t ^ j : ennreal.zpow_le_of_le (ennreal.one_le_coe_iff.2 ht.le) hij ... ≤ f x : h'x.2.1 }, { assume hij, rw disjoint.comm, exact this hij.symm } }, { assume n, exact hs.inter (hf measurable_set_Ico) } }, rw [A, B, C, add_assoc], end section pseudo_metric_space variables [pseudo_metric_space α] [measurable_space α] [opens_measurable_space α] variables [measurable_space β] {x : α} {ε : ℝ} open metric @[measurability] lemma measurable_set_ball : measurable_set (metric.ball x ε) := metric.is_open_ball.measurable_set @[measurability] lemma measurable_set_closed_ball : measurable_set (metric.closed_ball x ε) := metric.is_closed_ball.measurable_set @[measurability] lemma measurable_inf_dist {s : set α} : measurable (λ x, inf_dist x s) := (continuous_inf_dist_pt s).measurable @[measurability] lemma measurable.inf_dist {f : β → α} (hf : measurable f) {s : set α} : measurable (λ x, inf_dist (f x) s) := measurable_inf_dist.comp hf @[measurability] lemma measurable_inf_nndist {s : set α} : measurable (λ x, inf_nndist x s) := (continuous_inf_nndist_pt s).measurable @[measurability] lemma measurable.inf_nndist {f : β → α} (hf : measurable f) {s : set α} : measurable (λ x, inf_nndist (f x) s) := measurable_inf_nndist.comp hf section variables [second_countable_topology α] @[measurability] lemma measurable_dist : measurable (λ p : α × α, dist p.1 p.2) := continuous_dist.measurable @[measurability] lemma measurable.dist {f g : β → α} (hf : measurable f) (hg : measurable g) : measurable (λ b, dist (f b) (g b)) := (@continuous_dist α _).measurable2 hf hg @[measurability] lemma measurable_nndist : measurable (λ p : α × α, nndist p.1 p.2) := continuous_nndist.measurable @[measurability] lemma measurable.nndist {f g : β → α} (hf : measurable f) (hg : measurable g) : measurable (λ b, nndist (f b) (g b)) := (@continuous_nndist α _).measurable2 hf hg end /-- If a set has a closed thickening with finite measure, then the measure of its `r`-closed thickenings converges to the measure of its closure as `r` tends to `0`. -/ lemma tendsto_measure_cthickening {μ : measure α} {s : set α} (hs : ∃ R > 0, μ (cthickening R s) ≠ ∞) : tendsto (λ r, μ (cthickening r s)) (𝓝 0) (𝓝 (μ (closure s))) := begin have A : tendsto (λ r, μ (cthickening r s)) (𝓝[Ioi 0] 0) (𝓝 (μ (closure s))), { rw closure_eq_Inter_cthickening, exact tendsto_measure_bInter_gt (λ r hr, is_closed_cthickening.measurable_set) (λ i j ipos ij, cthickening_mono ij _) hs }, have B : tendsto (λ r, μ (cthickening r s)) (𝓝[Iic 0] 0) (𝓝 (μ (closure s))), { apply tendsto.congr' _ tendsto_const_nhds, filter_upwards [self_mem_nhds_within] with _ hr, rw cthickening_of_nonpos hr, }, convert B.sup A, exact (nhds_left_sup_nhds_right' 0).symm, end /-- If a closed set has a closed thickening with finite measure, then the measure of its `r`-closed thickenings converges to its measure as `r` tends to `0`. -/ lemma tendsto_measure_cthickening_of_is_closed {μ : measure α} {s : set α} (hs : ∃ R > 0, μ (cthickening R s) ≠ ∞) (h's : is_closed s) : tendsto (λ r, μ (cthickening r s)) (𝓝 0) (𝓝 (μ s)) := begin convert tendsto_measure_cthickening hs, exact h's.closure_eq.symm end end pseudo_metric_space /-- Given a compact set in a proper space, the measure of its `r`-closed thickenings converges to its measure as `r` tends to `0`. -/ lemma tendsto_measure_cthickening_of_is_compact [metric_space α] [measurable_space α] [opens_measurable_space α] [proper_space α] {μ : measure α} [is_finite_measure_on_compacts μ] {s : set α} (hs : is_compact s) : tendsto (λ r, μ (metric.cthickening r s)) (𝓝 0) (𝓝 (μ s)) := tendsto_measure_cthickening_of_is_closed ⟨1, zero_lt_one, hs.bounded.cthickening.measure_lt_top.ne⟩ hs.is_closed section pseudo_emetric_space variables [pseudo_emetric_space α] [measurable_space α] [opens_measurable_space α] variables [measurable_space β] {x : α} {ε : ℝ≥0∞} open emetric @[measurability] lemma measurable_set_eball : measurable_set (emetric.ball x ε) := emetric.is_open_ball.measurable_set @[measurability] lemma measurable_edist_right : measurable (edist x) := (continuous_const.edist continuous_id).measurable @[measurability] lemma measurable_edist_left : measurable (λ y, edist y x) := (continuous_id.edist continuous_const).measurable @[measurability] lemma measurable_inf_edist {s : set α} : measurable (λ x, inf_edist x s) := continuous_inf_edist.measurable @[measurability] lemma measurable.inf_edist {f : β → α} (hf : measurable f) {s : set α} : measurable (λ x, inf_edist (f x) s) := measurable_inf_edist.comp hf variables [second_countable_topology α] @[measurability] lemma measurable_edist : measurable (λ p : α × α, edist p.1 p.2) := continuous_edist.measurable @[measurability] lemma measurable.edist {f g : β → α} (hf : measurable f) (hg : measurable g) : measurable (λ b, edist (f b) (g b)) := (@continuous_edist α _).measurable2 hf hg @[measurability] lemma ae_measurable.edist {f g : β → α} {μ : measure β} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ a, edist (f a) (g a)) μ := (@continuous_edist α _).ae_measurable2 hf hg end pseudo_emetric_space namespace real open measurable_space measure_theory lemma borel_eq_generate_from_Ioo_rat : borel ℝ = generate_from (⋃(a b : ℚ) (h : a < b), {Ioo a b}) := is_topological_basis_Ioo_rat.borel_eq_generate_from lemma is_pi_system_Ioo_rat : @is_pi_system ℝ (⋃ (a b : ℚ) (h : a < b), {Ioo a b}) := begin convert is_pi_system_Ioo (coe : ℚ → ℝ) (coe : ℚ → ℝ), ext x, simp [eq_comm] end /-- The intervals `(-(n + 1), (n + 1))` form a finite spanning sets in the set of open intervals with rational endpoints for a locally finite measure `μ` on `ℝ`. -/ def finite_spanning_sets_in_Ioo_rat (μ : measure ℝ) [is_locally_finite_measure μ] : μ.finite_spanning_sets_in (⋃ (a b : ℚ) (h : a < b), {Ioo a b}) := { set := λ n, Ioo (-(n + 1)) (n + 1), set_mem := λ n, begin simp only [mem_Union, mem_singleton_iff], refine ⟨-(n + 1 : ℕ), n + 1, _, by simp⟩, -- TODO: norm_cast fails here? exact (neg_nonpos.2 (@nat.cast_nonneg ℚ _ (n + 1))).trans_lt n.cast_add_one_pos end, finite := λ n, measure_Ioo_lt_top, spanning := Union_eq_univ_iff.2 $ λ x, ⟨⌊|x|⌋₊, neg_lt.1 ((neg_le_abs_self x).trans_lt (nat.lt_floor_add_one _)), (le_abs_self x).trans_lt (nat.lt_floor_add_one _)⟩ } lemma measure_ext_Ioo_rat {μ ν : measure ℝ} [is_locally_finite_measure μ] (h : ∀ a b : ℚ, μ (Ioo a b) = ν (Ioo a b)) : μ = ν := (finite_spanning_sets_in_Ioo_rat μ).ext borel_eq_generate_from_Ioo_rat is_pi_system_Ioo_rat $ by { simp only [mem_Union, mem_singleton_iff], rintro _ ⟨a, b, -, rfl⟩, apply h } lemma borel_eq_generate_from_Iio_rat : borel ℝ = generate_from (⋃ a : ℚ, {Iio a}) := begin let g : measurable_space ℝ := generate_from (⋃ a : ℚ, {Iio a}), refine le_antisymm _ _, { rw borel_eq_generate_from_Ioo_rat, refine generate_from_le (λ t, _), simp only [mem_Union, mem_singleton_iff], rintro ⟨a, b, h, rfl⟩, rw (set.ext (λ x, _) : Ioo (a : ℝ) b = (⋃c>a, (Iio c)ᶜ) ∩ Iio b), { have hg : ∀ q : ℚ, measurable_set[g] (Iio q) := λ q, generate_measurable.basic (Iio q) (by simp), refine @measurable_set.inter _ g _ _ _ (hg _), refine @measurable_set.bUnion _ _ g _ _ (to_countable _) (λ c h, _), exact @measurable_set.compl _ _ g (hg _) }, { suffices : x < ↑b → (↑a < x ↔ ∃ (i : ℚ), a < i ∧ ↑i ≤ x), by simpa, refine λ _, ⟨λ h, _, λ ⟨i, hai, hix⟩, (rat.cast_lt.2 hai).trans_le hix⟩, rcases exists_rat_btwn h with ⟨c, ac, cx⟩, exact ⟨c, rat.cast_lt.1 ac, cx.le⟩ } }, { refine measurable_space.generate_from_le (λ _, _), simp only [mem_Union, mem_singleton_iff], rintro ⟨r, rfl⟩, exact measurable_set_Iio } end end real variable [measurable_space α] @[measurability] lemma measurable_real_to_nnreal : measurable (real.to_nnreal) := continuous_real_to_nnreal.measurable @[measurability] lemma measurable.real_to_nnreal {f : α → ℝ} (hf : measurable f) : measurable (λ x, real.to_nnreal (f x)) := measurable_real_to_nnreal.comp hf @[measurability] lemma ae_measurable.real_to_nnreal {f : α → ℝ} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, real.to_nnreal (f x)) μ := measurable_real_to_nnreal.comp_ae_measurable hf @[measurability] lemma measurable_coe_nnreal_real : measurable (coe : ℝ≥0 → ℝ) := nnreal.continuous_coe.measurable @[measurability] lemma measurable.coe_nnreal_real {f : α → ℝ≥0} (hf : measurable f) : measurable (λ x, (f x : ℝ)) := measurable_coe_nnreal_real.comp hf @[measurability] lemma ae_measurable.coe_nnreal_real {f : α → ℝ≥0} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, (f x : ℝ)) μ := measurable_coe_nnreal_real.comp_ae_measurable hf @[measurability] lemma measurable_coe_nnreal_ennreal : measurable (coe : ℝ≥0 → ℝ≥0∞) := ennreal.continuous_coe.measurable @[measurability] lemma measurable.coe_nnreal_ennreal {f : α → ℝ≥0} (hf : measurable f) : measurable (λ x, (f x : ℝ≥0∞)) := ennreal.continuous_coe.measurable.comp hf @[measurability] lemma ae_measurable.coe_nnreal_ennreal {f : α → ℝ≥0} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, (f x : ℝ≥0∞)) μ := ennreal.continuous_coe.measurable.comp_ae_measurable hf @[measurability] lemma measurable.ennreal_of_real {f : α → ℝ} (hf : measurable f) : measurable (λ x, ennreal.of_real (f x)) := ennreal.continuous_of_real.measurable.comp hf @[simp, norm_cast] lemma measurable_coe_nnreal_real_iff {f : α → ℝ≥0} : measurable (λ x, f x : α → ℝ) ↔ measurable f := ⟨λ h, by simpa only [real.to_nnreal_coe] using h.real_to_nnreal, measurable.coe_nnreal_real⟩ @[simp, norm_cast] lemma ae_measurable_coe_nnreal_real_iff {f : α → ℝ≥0} {μ : measure α} : ae_measurable (λ x, f x : α → ℝ) μ ↔ ae_measurable f μ := ⟨λ h, by simpa only [real.to_nnreal_coe] using h.real_to_nnreal, ae_measurable.coe_nnreal_real⟩ /-- The set of finite `ℝ≥0∞` numbers is `measurable_equiv` to `ℝ≥0`. -/ def measurable_equiv.ennreal_equiv_nnreal : {r : ℝ≥0∞ | r ≠ ∞} ≃ᵐ ℝ≥0 := ennreal.ne_top_homeomorph_nnreal.to_measurable_equiv namespace ennreal lemma measurable_of_measurable_nnreal {f : ℝ≥0∞ → α} (h : measurable (λ p : ℝ≥0, f p)) : measurable f := measurable_of_measurable_on_compl_singleton ∞ (measurable_equiv.ennreal_equiv_nnreal.symm.measurable_comp_iff.1 h) /-- `ℝ≥0∞` is `measurable_equiv` to `ℝ≥0 ⊕ unit`. -/ def ennreal_equiv_sum : ℝ≥0∞ ≃ᵐ ℝ≥0 ⊕ unit := { measurable_to_fun := measurable_of_measurable_nnreal measurable_inl, measurable_inv_fun := measurable_sum measurable_coe_nnreal_ennreal (@measurable_const ℝ≥0∞ unit _ _ ∞), .. equiv.option_equiv_sum_punit ℝ≥0 } open function (uncurry) lemma measurable_of_measurable_nnreal_prod [measurable_space β] [measurable_space γ] {f : ℝ≥0∞ × β → γ} (H₁ : measurable (λ p : ℝ≥0 × β, f (p.1, p.2))) (H₂ : measurable (λ x, f (∞, x))) : measurable f := let e : ℝ≥0∞ × β ≃ᵐ ℝ≥0 × β ⊕ unit × β := (ennreal_equiv_sum.prod_congr (measurable_equiv.refl β)).trans (measurable_equiv.sum_prod_distrib _ _ _) in e.symm.measurable_comp_iff.1 $ measurable_sum H₁ (H₂.comp measurable_id.snd) lemma measurable_of_measurable_nnreal_nnreal [measurable_space β] {f : ℝ≥0∞ × ℝ≥0∞ → β} (h₁ : measurable (λ p : ℝ≥0 × ℝ≥0, f (p.1, p.2))) (h₂ : measurable (λ r : ℝ≥0, f (∞, r))) (h₃ : measurable (λ r : ℝ≥0, f (r, ∞))) : measurable f := measurable_of_measurable_nnreal_prod (measurable_swap_iff.1 $ measurable_of_measurable_nnreal_prod (h₁.comp measurable_swap) h₃) (measurable_of_measurable_nnreal h₂) @[measurability] lemma measurable_of_real : measurable ennreal.of_real := ennreal.continuous_of_real.measurable @[measurability] lemma measurable_to_real : measurable ennreal.to_real := ennreal.measurable_of_measurable_nnreal measurable_coe_nnreal_real @[measurability] lemma measurable_to_nnreal : measurable ennreal.to_nnreal := ennreal.measurable_of_measurable_nnreal measurable_id instance : has_measurable_mul₂ ℝ≥0∞ := begin refine ⟨measurable_of_measurable_nnreal_nnreal _ _ _⟩, { simp only [← ennreal.coe_mul, measurable_mul.coe_nnreal_ennreal] }, { simp only [ennreal.top_mul, ennreal.coe_eq_zero], exact measurable_const.piecewise (measurable_set_singleton _) measurable_const }, { simp only [ennreal.mul_top, ennreal.coe_eq_zero], exact measurable_const.piecewise (measurable_set_singleton _) measurable_const } end instance : has_measurable_sub₂ ℝ≥0∞ := ⟨by apply measurable_of_measurable_nnreal_nnreal; simp [← with_top.coe_sub, continuous_sub.measurable.coe_nnreal_ennreal]⟩ instance : has_measurable_inv ℝ≥0∞ := ⟨continuous_inv.measurable⟩ end ennreal @[measurability] lemma measurable.ennreal_to_nnreal {f : α → ℝ≥0∞} (hf : measurable f) : measurable (λ x, (f x).to_nnreal) := ennreal.measurable_to_nnreal.comp hf @[measurability] lemma ae_measurable.ennreal_to_nnreal {f : α → ℝ≥0∞} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, (f x).to_nnreal) μ := ennreal.measurable_to_nnreal.comp_ae_measurable hf @[simp, norm_cast] lemma measurable_coe_nnreal_ennreal_iff {f : α → ℝ≥0} : measurable (λ x, (f x : ℝ≥0∞)) ↔ measurable f := ⟨λ h, h.ennreal_to_nnreal, λ h, h.coe_nnreal_ennreal⟩ @[simp, norm_cast] lemma ae_measurable_coe_nnreal_ennreal_iff {f : α → ℝ≥0} {μ : measure α} : ae_measurable (λ x, (f x : ℝ≥0∞)) μ ↔ ae_measurable f μ := ⟨λ h, h.ennreal_to_nnreal, λ h, h.coe_nnreal_ennreal⟩ @[measurability] lemma measurable.ennreal_to_real {f : α → ℝ≥0∞} (hf : measurable f) : measurable (λ x, ennreal.to_real (f x)) := ennreal.measurable_to_real.comp hf @[measurability] lemma ae_measurable.ennreal_to_real {f : α → ℝ≥0∞} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, ennreal.to_real (f x)) μ := ennreal.measurable_to_real.comp_ae_measurable hf /-- note: `ℝ≥0∞` can probably be generalized in a future version of this lemma. -/ @[measurability] lemma measurable.ennreal_tsum {ι} [countable ι] {f : ι → α → ℝ≥0∞} (h : ∀ i, measurable (f i)) : measurable (λ x, ∑' i, f i x) := by { simp_rw [ennreal.tsum_eq_supr_sum], apply measurable_supr, exact λ s, s.measurable_sum (λ i _, h i) } @[measurability] lemma measurable.ennreal_tsum' {ι} [countable ι] {f : ι → α → ℝ≥0∞} (h : ∀ i, measurable (f i)) : measurable (∑' i, f i) := begin convert measurable.ennreal_tsum h, ext1 x, exact tsum_apply (pi.summable.2 (λ _, ennreal.summable)), end @[measurability] lemma measurable.nnreal_tsum {ι} [countable ι] {f : ι → α → ℝ≥0} (h : ∀ i, measurable (f i)) : measurable (λ x, ∑' i, f i x) := begin simp_rw [nnreal.tsum_eq_to_nnreal_tsum], exact (measurable.ennreal_tsum (λ i, (h i).coe_nnreal_ennreal)).ennreal_to_nnreal, end @[measurability] lemma ae_measurable.ennreal_tsum {ι} [countable ι] {f : ι → α → ℝ≥0∞} {μ : measure α} (h : ∀ i, ae_measurable (f i) μ) : ae_measurable (λ x, ∑' i, f i x) μ := by { simp_rw [ennreal.tsum_eq_supr_sum], apply ae_measurable_supr, exact λ s, finset.ae_measurable_sum s (λ i _, h i) } @[measurability] lemma measurable_coe_real_ereal : measurable (coe : ℝ → ereal) := continuous_coe_real_ereal.measurable @[measurability] lemma measurable.coe_real_ereal {f : α → ℝ} (hf : measurable f) : measurable (λ x, (f x : ereal)) := measurable_coe_real_ereal.comp hf @[measurability] lemma ae_measurable.coe_real_ereal {f : α → ℝ} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, (f x : ereal)) μ := measurable_coe_real_ereal.comp_ae_measurable hf /-- The set of finite `ereal` numbers is `measurable_equiv` to `ℝ`. -/ def measurable_equiv.ereal_equiv_real : ({⊥, ⊤}ᶜ : set ereal) ≃ᵐ ℝ := ereal.ne_bot_top_homeomorph_real.to_measurable_equiv lemma ereal.measurable_of_measurable_real {f : ereal → α} (h : measurable (λ p : ℝ, f p)) : measurable f := measurable_of_measurable_on_compl_finite {⊥, ⊤} (by simp) (measurable_equiv.ereal_equiv_real.symm.measurable_comp_iff.1 h) @[measurability] lemma measurable_ereal_to_real : measurable ereal.to_real := ereal.measurable_of_measurable_real (by simpa using measurable_id) @[measurability] lemma measurable.ereal_to_real {f : α → ereal} (hf : measurable f) : measurable (λ x, (f x).to_real) := measurable_ereal_to_real.comp hf @[measurability] lemma ae_measurable.ereal_to_real {f : α → ereal} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, (f x).to_real) μ := measurable_ereal_to_real.comp_ae_measurable hf @[measurability] lemma measurable_coe_ennreal_ereal : measurable (coe : ℝ≥0∞ → ereal) := continuous_coe_ennreal_ereal.measurable @[measurability] lemma measurable.coe_ereal_ennreal {f : α → ℝ≥0∞} (hf : measurable f) : measurable (λ x, (f x : ereal)) := measurable_coe_ennreal_ereal.comp hf @[measurability] lemma ae_measurable.coe_ereal_ennreal {f : α → ℝ≥0∞} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, (f x : ereal)) μ := measurable_coe_ennreal_ereal.comp_ae_measurable hf section normed_add_comm_group variables [normed_add_comm_group α] [opens_measurable_space α] [measurable_space β] @[measurability] lemma measurable_norm : measurable (norm : α → ℝ) := continuous_norm.measurable @[measurability] lemma measurable.norm {f : β → α} (hf : measurable f) : measurable (λ a, norm (f a)) := measurable_norm.comp hf @[measurability] lemma ae_measurable.norm {f : β → α} {μ : measure β} (hf : ae_measurable f μ) : ae_measurable (λ a, norm (f a)) μ := measurable_norm.comp_ae_measurable hf @[measurability] lemma measurable_nnnorm : measurable (nnnorm : α → ℝ≥0) := continuous_nnnorm.measurable @[measurability] lemma measurable.nnnorm {f : β → α} (hf : measurable f) : measurable (λ a, ∥f a∥₊) := measurable_nnnorm.comp hf @[measurability] lemma ae_measurable.nnnorm {f : β → α} {μ : measure β} (hf : ae_measurable f μ) : ae_measurable (λ a, ∥f a∥₊) μ := measurable_nnnorm.comp_ae_measurable hf @[measurability] lemma measurable_ennnorm : measurable (λ x : α, (∥x∥₊ : ℝ≥0∞)) := measurable_nnnorm.coe_nnreal_ennreal @[measurability] lemma measurable.ennnorm {f : β → α} (hf : measurable f) : measurable (λ a, (∥f a∥₊ : ℝ≥0∞)) := hf.nnnorm.coe_nnreal_ennreal @[measurability] lemma ae_measurable.ennnorm {f : β → α} {μ : measure β} (hf : ae_measurable f μ) : ae_measurable (λ a, (∥f a∥₊ : ℝ≥0∞)) μ := measurable_ennnorm.comp_ae_measurable hf end normed_add_comm_group section limits variables [topological_space β] [pseudo_metrizable_space β] [measurable_space β] [borel_space β] open metric /-- A limit (over a general filter) of measurable `ℝ≥0∞` valued functions is measurable. -/ lemma measurable_of_tendsto_ennreal' {ι} {f : ι → α → ℝ≥0∞} {g : α → ℝ≥0∞} (u : filter ι) [ne_bot u] [is_countably_generated u] (hf : ∀ i, measurable (f i)) (lim : tendsto f u (𝓝 g)) : measurable g := begin rcases u.exists_seq_tendsto with ⟨x, hx⟩, rw [tendsto_pi_nhds] at lim, have : (λ y, liminf at_top (λ n, (f (x n) y : ℝ≥0∞))) = g := by { ext1 y, exact ((lim y).comp hx).liminf_eq, }, rw ← this, show measurable (λ y, liminf at_top (λ n, (f (x n) y : ℝ≥0∞))), exact measurable_liminf (λ n, hf (x n)), end /-- A sequential limit of measurable `ℝ≥0∞` valued functions is measurable. -/ lemma measurable_of_tendsto_ennreal {f : ℕ → α → ℝ≥0∞} {g : α → ℝ≥0∞} (hf : ∀ i, measurable (f i)) (lim : tendsto f at_top (𝓝 g)) : measurable g := measurable_of_tendsto_ennreal' at_top hf lim /-- A limit (over a general filter) of measurable `ℝ≥0` valued functions is measurable. -/ lemma measurable_of_tendsto_nnreal' {ι} {f : ι → α → ℝ≥0} {g : α → ℝ≥0} (u : filter ι) [ne_bot u] [is_countably_generated u] (hf : ∀ i, measurable (f i)) (lim : tendsto f u (𝓝 g)) : measurable g := begin simp_rw [← measurable_coe_nnreal_ennreal_iff] at hf ⊢, refine measurable_of_tendsto_ennreal' u hf _, rw tendsto_pi_nhds at lim ⊢, exact λ x, (ennreal.continuous_coe.tendsto (g x)).comp (lim x), end /-- A sequential limit of measurable `ℝ≥0` valued functions is measurable. -/ lemma measurable_of_tendsto_nnreal {f : ℕ → α → ℝ≥0} {g : α → ℝ≥0} (hf : ∀ i, measurable (f i)) (lim : tendsto f at_top (𝓝 g)) : measurable g := measurable_of_tendsto_nnreal' at_top hf lim /-- A limit (over a general filter) of measurable functions valued in a (pseudo) metrizable space is measurable. -/ lemma measurable_of_tendsto_metrizable' {ι} {f : ι → α → β} {g : α → β} (u : filter ι) [ne_bot u] [is_countably_generated u] (hf : ∀ i, measurable (f i)) (lim : tendsto f u (𝓝 g)) : measurable g := begin letI : pseudo_metric_space β := pseudo_metrizable_space_pseudo_metric β, apply measurable_of_is_closed', intros s h1s h2s h3s, have : measurable (λ x, inf_nndist (g x) s), { suffices : tendsto (λ i x, inf_nndist (f i x) s) u (𝓝 (λ x, inf_nndist (g x) s)), from measurable_of_tendsto_nnreal' u (λ i, (hf i).inf_nndist) this, rw [tendsto_pi_nhds] at lim ⊢, intro x, exact ((continuous_inf_nndist_pt s).tendsto (g x)).comp (lim x) }, have h4s : g ⁻¹' s = (λ x, inf_nndist (g x) s) ⁻¹' {0}, { ext x, simp [h1s, ← h1s.mem_iff_inf_dist_zero h2s, ← nnreal.coe_eq_zero] }, rw [h4s], exact this (measurable_set_singleton 0), end /-- A sequential limit of measurable functions valued in a (pseudo) metrizable space is measurable. -/ lemma measurable_of_tendsto_metrizable {f : ℕ → α → β} {g : α → β} (hf : ∀ i, measurable (f i)) (lim : tendsto f at_top (𝓝 g)) : measurable g := measurable_of_tendsto_metrizable' at_top hf lim lemma ae_measurable_of_tendsto_metrizable_ae {ι} {μ : measure α} {f : ι → α → β} {g : α → β} (u : filter ι) [hu : ne_bot u] [is_countably_generated u] (hf : ∀ n, ae_measurable (f n) μ) (h_tendsto : ∀ᵐ x ∂μ, tendsto (λ n, f n x) u (𝓝 (g x))) : ae_measurable g μ := begin rcases u.exists_seq_tendsto with ⟨v, hv⟩, have h'f : ∀ n, ae_measurable (f (v n)) μ := λ n, hf (v n), set p : α → (ℕ → β) → Prop := λ x f', tendsto (λ n, f' n) at_top (𝓝 (g x)), have hp : ∀ᵐ x ∂μ, p x (λ n, f (v n) x), by filter_upwards [h_tendsto] with x hx using hx.comp hv, set ae_seq_lim := λ x, ite (x ∈ ae_seq_set h'f p) (g x) (⟨f (v 0) x⟩ : nonempty β).some with hs, refine ⟨ae_seq_lim, measurable_of_tendsto_metrizable' at_top (ae_seq.measurable h'f p) (tendsto_pi_nhds.mpr (λ x, _)), _⟩, { simp_rw [ae_seq, ae_seq_lim], split_ifs with hx, { simp_rw ae_seq.mk_eq_fun_of_mem_ae_seq_set h'f hx, exact @ae_seq.fun_prop_of_mem_ae_seq_set _ α β _ _ _ _ _ h'f x hx, }, { exact tendsto_const_nhds } }, { exact (ite_ae_eq_of_measure_compl_zero g (λ x, (⟨f (v 0) x⟩ : nonempty β).some) (ae_seq_set h'f p) (ae_seq.measure_compl_ae_seq_set_eq_zero h'f hp)).symm }, end lemma ae_measurable_of_tendsto_metrizable_ae' {μ : measure α} {f : ℕ → α → β} {g : α → β} (hf : ∀ n, ae_measurable (f n) μ) (h_ae_tendsto : ∀ᵐ x ∂μ, tendsto (λ n, f n x) at_top (𝓝 (g x))) : ae_measurable g μ := ae_measurable_of_tendsto_metrizable_ae at_top hf h_ae_tendsto lemma ae_measurable_of_unif_approx {β} [measurable_space β] [pseudo_metric_space β] [borel_space β] {μ : measure α} {g : α → β} (hf : ∀ ε > (0 : ℝ), ∃ (f : α → β), ae_measurable f μ ∧ ∀ᵐ x ∂μ, dist (f x) (g x) ≤ ε) : ae_measurable g μ := begin obtain ⟨u, u_anti, u_pos, u_lim⟩ : ∃ (u : ℕ → ℝ), strict_anti u ∧ (∀ (n : ℕ), 0 < u n) ∧ tendsto u at_top (𝓝 0) := exists_seq_strict_anti_tendsto (0 : ℝ), choose f Hf using λ (n : ℕ), hf (u n) (u_pos n), have : ∀ᵐ x ∂μ, tendsto (λ n, f n x) at_top (𝓝 (g x)), { have : ∀ᵐ x ∂ μ, ∀ n, dist (f n x) (g x) ≤ u n := ae_all_iff.2 (λ n, (Hf n).2), filter_upwards [this], assume x hx, rw tendsto_iff_dist_tendsto_zero, exact squeeze_zero (λ n, dist_nonneg) hx u_lim }, exact ae_measurable_of_tendsto_metrizable_ae' (λ n, (Hf n).1) this, end lemma measurable_of_tendsto_metrizable_ae {μ : measure α} [μ.is_complete] {f : ℕ → α → β} {g : α → β} (hf : ∀ n, measurable (f n)) (h_ae_tendsto : ∀ᵐ x ∂μ, tendsto (λ n, f n x) at_top (𝓝 (g x))) : measurable g := ae_measurable_iff_measurable.mp (ae_measurable_of_tendsto_metrizable_ae' (λ i, (hf i).ae_measurable) h_ae_tendsto) lemma measurable_limit_of_tendsto_metrizable_ae {ι} [countable ι] [nonempty ι] {μ : measure α} {f : ι → α → β} {L : filter ι} [L.is_countably_generated] (hf : ∀ n, ae_measurable (f n) μ) (h_ae_tendsto : ∀ᵐ x ∂μ, ∃ l : β, tendsto (λ n, f n x) L (𝓝 l)) : ∃ (f_lim : α → β) (hf_lim_meas : measurable f_lim), ∀ᵐ x ∂μ, tendsto (λ n, f n x) L (𝓝 (f_lim x)) := begin inhabit ι, unfreezingI { rcases eq_or_ne L ⊥ with rfl | hL }, { exact ⟨(hf default).mk _, (hf default).measurable_mk, eventually_of_forall $ λ x, tendsto_bot⟩ }, haveI : ne_bot L := ⟨hL⟩, let p : α → (ι → β) → Prop := λ x f', ∃ l : β, tendsto (λ n, f' n) L (𝓝 l), have hp_mem : ∀ x ∈ ae_seq_set hf p, p x (λ n, f n x), from λ x hx, ae_seq.fun_prop_of_mem_ae_seq_set hf hx, have h_ae_eq : ∀ᵐ x ∂μ, ∀ n, ae_seq hf p n x = f n x, from ae_seq.ae_seq_eq_fun_ae hf h_ae_tendsto, let f_lim : α → β := λ x, dite (x ∈ ae_seq_set hf p) (λ h, (hp_mem x h).some) (λ h, (⟨f default x⟩ : nonempty β).some), have hf_lim : ∀ x, tendsto (λ n, ae_seq hf p n x) L (𝓝 (f_lim x)), { intros x, simp only [f_lim, ae_seq], split_ifs, { refine (hp_mem x h).some_spec.congr (λ n, _), exact (ae_seq.mk_eq_fun_of_mem_ae_seq_set hf h n).symm }, { exact tendsto_const_nhds, }, }, have h_ae_tendsto_f_lim : ∀ᵐ x ∂μ, tendsto (λ n, f n x) L (𝓝 (f_lim x)), from h_ae_eq.mono (λ x hx, (hf_lim x).congr hx), have h_f_lim_meas : measurable f_lim, from measurable_of_tendsto_metrizable' L (ae_seq.measurable hf p) (tendsto_pi_nhds.mpr (λ x, hf_lim x)), exact ⟨f_lim, h_f_lim_meas, h_ae_tendsto_f_lim⟩, end end limits namespace continuous_linear_map variables {𝕜 : Type*} [normed_field 𝕜] variables {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] [measurable_space E] [opens_measurable_space E] {F : Type*} [normed_add_comm_group F] [normed_space 𝕜 F] [measurable_space F] [borel_space F] @[measurability] protected lemma measurable (L : E →L[𝕜] F) : measurable L := L.continuous.measurable lemma measurable_comp (L : E →L[𝕜] F) {φ : α → E} (φ_meas : measurable φ) : measurable (λ (a : α), L (φ a)) := L.measurable.comp φ_meas end continuous_linear_map namespace continuous_linear_map variables {𝕜 : Type*} [nontrivially_normed_field 𝕜] variables {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] {F : Type*} [normed_add_comm_group F] [normed_space 𝕜 F] instance : measurable_space (E →L[𝕜] F) := borel _ instance : borel_space (E →L[𝕜] F) := ⟨rfl⟩ @[measurability] lemma measurable_apply [measurable_space F] [borel_space F] (x : E) : measurable (λ f : E →L[𝕜] F, f x) := (apply 𝕜 F x).continuous.measurable @[measurability] lemma measurable_apply' [measurable_space E] [opens_measurable_space E] [measurable_space F] [borel_space F] : measurable (λ (x : E) (f : E →L[𝕜] F), f x) := measurable_pi_lambda _ $ λ f, f.measurable @[measurability] lemma measurable_coe [measurable_space F] [borel_space F] : measurable (λ (f : E →L[𝕜] F) (x : E), f x) := measurable_pi_lambda _ measurable_apply end continuous_linear_map section continuous_linear_map_nontrivially_normed_field variables {𝕜 : Type*} [nontrivially_normed_field 𝕜] variables {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] [measurable_space E] [borel_space E] {F : Type*} [normed_add_comm_group F] [normed_space 𝕜 F] @[measurability] lemma measurable.apply_continuous_linear_map {φ : α → F →L[𝕜] E} (hφ : measurable φ) (v : F) : measurable (λ a, φ a v) := (continuous_linear_map.apply 𝕜 E v).measurable.comp hφ @[measurability] lemma ae_measurable.apply_continuous_linear_map {φ : α → F →L[𝕜] E} {μ : measure α} (hφ : ae_measurable φ μ) (v : F) : ae_measurable (λ a, φ a v) μ := (continuous_linear_map.apply 𝕜 E v).measurable.comp_ae_measurable hφ end continuous_linear_map_nontrivially_normed_field section normed_space variables {𝕜 : Type*} [nontrivially_normed_field 𝕜] [complete_space 𝕜] [measurable_space 𝕜] variables [borel_space 𝕜] {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] [measurable_space E] [borel_space E] lemma measurable_smul_const {f : α → 𝕜} {c : E} (hc : c ≠ 0) : measurable (λ x, f x • c) ↔ measurable f := (closed_embedding_smul_left hc).measurable_embedding.measurable_comp_iff lemma ae_measurable_smul_const {f : α → 𝕜} {μ : measure α} {c : E} (hc : c ≠ 0) : ae_measurable (λ x, f x • c) μ ↔ ae_measurable f μ := (closed_embedding_smul_left hc).measurable_embedding.ae_measurable_comp_iff end normed_space
6e5ddd087d0be2011e63a3a75e8fd51ede7ed71d
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/group/prod.lean
2546fc56e9435f9b9bcb7abed0314c0a2abe8b8b
[ "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
22,911
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Patrick Massot, Yury Kudryashov -/ import algebra.group.opposite import algebra.group_with_zero.units.basic import algebra.hom.units /-! # Monoid, group etc structures on `M × N` > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we define one-binop (`monoid`, `group` etc) structures on `M × N`. We also prove trivial `simp` lemmas, and define the following operations on `monoid_hom`s: * `fst M N : M × N →* M`, `snd M N : M × N →* N`: projections `prod.fst` and `prod.snd` as `monoid_hom`s; * `inl M N : M →* M × N`, `inr M N : N →* M × N`: inclusions of first/second monoid into the product; * `f.prod g : `M →* N × P`: sends `x` to `(f x, g x)`; * `f.coprod g : M × N →* P`: sends `(x, y)` to `f x * g y`; * `f.prod_map g : M × N → M' × N'`: `prod.map f g` as a `monoid_hom`, sends `(x, y)` to `(f x, g y)`. ## Main declarations * `mul_mul_hom`/`mul_monoid_hom`/`mul_monoid_with_zero_hom`: Multiplication bundled as a multiplicative/monoid/monoid with zero homomorphism. * `div_monoid_hom`/`div_monoid_with_zero_hom`: Division bundled as a monoid/monoid with zero homomorphism. -/ variables {A : Type*} {B : Type*} {G : Type*} {H : Type*} {M : Type*} {N : Type*} {P : Type*} namespace prod @[to_additive] instance [has_mul M] [has_mul N] : has_mul (M × N) := ⟨λ p q, ⟨p.1 * q.1, p.2 * q.2⟩⟩ @[simp, to_additive] lemma fst_mul [has_mul M] [has_mul N] (p q : M × N) : (p * q).1 = p.1 * q.1 := rfl @[simp, to_additive] lemma snd_mul [has_mul M] [has_mul N] (p q : M × N) : (p * q).2 = p.2 * q.2 := rfl @[simp, to_additive] lemma mk_mul_mk [has_mul M] [has_mul N] (a₁ a₂ : M) (b₁ b₂ : N) : (a₁, b₁) * (a₂, b₂) = (a₁ * a₂, b₁ * b₂) := rfl @[simp, to_additive] lemma swap_mul [has_mul M] [has_mul N] (p q : M × N) : (p * q).swap = p.swap * q.swap := rfl @[to_additive] lemma mul_def [has_mul M] [has_mul N] (p q : M × N) : p * q = (p.1 * q.1, p.2 * q.2) := rfl @[to_additive] lemma one_mk_mul_one_mk [monoid M] [has_mul N] (b₁ b₂ : N) : ((1 : M), b₁) * (1, b₂) = (1, b₁ * b₂) := by rw [mk_mul_mk, mul_one] @[to_additive] lemma mk_one_mul_mk_one [has_mul M] [monoid N] (a₁ a₂ : M) : (a₁, (1 : N)) * (a₂, 1) = (a₁ * a₂, 1) := by rw [mk_mul_mk, mul_one] @[to_additive] instance [has_one M] [has_one N] : has_one (M × N) := ⟨(1, 1)⟩ @[simp, to_additive] lemma fst_one [has_one M] [has_one N] : (1 : M × N).1 = 1 := rfl @[simp, to_additive] lemma snd_one [has_one M] [has_one N] : (1 : M × N).2 = 1 := rfl @[to_additive] lemma one_eq_mk [has_one M] [has_one N] : (1 : M × N) = (1, 1) := rfl @[simp, to_additive] lemma mk_eq_one [has_one M] [has_one N] {x : M} {y : N} : (x, y) = 1 ↔ x = 1 ∧ y = 1 := mk.inj_iff @[simp, to_additive] lemma swap_one [has_one M] [has_one N] : (1 : M × N).swap = 1 := rfl @[to_additive] lemma fst_mul_snd [mul_one_class M] [mul_one_class N] (p : M × N) : (p.fst, 1) * (1, p.snd) = p := ext (mul_one p.1) (one_mul p.2) @[to_additive] instance [has_inv M] [has_inv N] : has_inv (M × N) := ⟨λp, (p.1⁻¹, p.2⁻¹)⟩ @[simp, to_additive] lemma fst_inv [has_inv G] [has_inv H] (p : G × H) : (p⁻¹).1 = (p.1)⁻¹ := rfl @[simp, to_additive] lemma snd_inv [has_inv G] [has_inv H] (p : G × H) : (p⁻¹).2 = (p.2)⁻¹ := rfl @[simp, to_additive] lemma inv_mk [has_inv G] [has_inv H] (a : G) (b : H) : (a, b)⁻¹ = (a⁻¹, b⁻¹) := rfl @[simp, to_additive] lemma swap_inv [has_inv G] [has_inv H] (p : G × H) : (p⁻¹).swap = p.swap⁻¹ := rfl @[to_additive] instance [has_involutive_inv M] [has_involutive_inv N] : has_involutive_inv (M × N) := { inv_inv := λ a, ext (inv_inv _) (inv_inv _), ..prod.has_inv } @[to_additive] instance [has_div M] [has_div N] : has_div (M × N) := ⟨λ p q, ⟨p.1 / q.1, p.2 / q.2⟩⟩ @[simp, to_additive] lemma fst_div [has_div G] [has_div H] (a b : G × H) : (a / b).1 = a.1 / b.1 := rfl @[simp, to_additive] lemma snd_div [has_div G] [has_div H] (a b : G × H) : (a / b).2 = a.2 / b.2 := rfl @[simp, to_additive] lemma mk_div_mk [has_div G] [has_div H] (x₁ x₂ : G) (y₁ y₂ : H) : (x₁, y₁) / (x₂, y₂) = (x₁ / x₂, y₁ / y₂) := rfl @[simp, to_additive] lemma swap_div [has_div G] [has_div H] (a b : G × H) : (a / b).swap = a.swap / b.swap := rfl instance [mul_zero_class M] [mul_zero_class N] : mul_zero_class (M × N) := { zero_mul := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨zero_mul _, zero_mul _⟩, mul_zero := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨mul_zero _, mul_zero _⟩, .. prod.has_zero, .. prod.has_mul } @[to_additive] instance [semigroup M] [semigroup N] : semigroup (M × N) := { mul_assoc := assume a b c, mk.inj_iff.mpr ⟨mul_assoc _ _ _, mul_assoc _ _ _⟩, .. prod.has_mul } @[to_additive] instance [comm_semigroup G] [comm_semigroup H] : comm_semigroup (G × H) := { mul_comm := assume a b, mk.inj_iff.mpr ⟨mul_comm _ _, mul_comm _ _⟩, .. prod.semigroup } instance [semigroup_with_zero M] [semigroup_with_zero N] : semigroup_with_zero (M × N) := { .. prod.mul_zero_class, .. prod.semigroup } @[to_additive] instance [mul_one_class M] [mul_one_class N] : mul_one_class (M × N) := { one_mul := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨one_mul _, one_mul _⟩, mul_one := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨mul_one _, mul_one _⟩, .. prod.has_mul, .. prod.has_one } @[to_additive] instance [monoid M] [monoid N] : monoid (M × N) := { npow := λ z a, ⟨monoid.npow z a.1, monoid.npow z a.2⟩, npow_zero' := λ z, ext (monoid.npow_zero' _) (monoid.npow_zero' _), npow_succ' := λ z a, ext (monoid.npow_succ' _ _) (monoid.npow_succ' _ _), .. prod.semigroup, .. prod.mul_one_class } @[to_additive prod.sub_neg_monoid] instance [div_inv_monoid G] [div_inv_monoid H] : div_inv_monoid (G × H) := { div_eq_mul_inv := λ a b, mk.inj_iff.mpr ⟨div_eq_mul_inv _ _, div_eq_mul_inv _ _⟩, zpow := λ z a, ⟨div_inv_monoid.zpow z a.1, div_inv_monoid.zpow z a.2⟩, zpow_zero' := λ z, ext (div_inv_monoid.zpow_zero' _) (div_inv_monoid.zpow_zero' _), zpow_succ' := λ z a, ext (div_inv_monoid.zpow_succ' _ _) (div_inv_monoid.zpow_succ' _ _), zpow_neg' := λ z a, ext (div_inv_monoid.zpow_neg' _ _) (div_inv_monoid.zpow_neg' _ _), .. prod.monoid, .. prod.has_inv, .. prod.has_div } @[to_additive] instance [division_monoid G] [division_monoid H] : division_monoid (G × H) := { mul_inv_rev := λ a b, ext (mul_inv_rev _ _) (mul_inv_rev _ _), inv_eq_of_mul := λ a b h, ext (inv_eq_of_mul_eq_one_right $ congr_arg fst h) (inv_eq_of_mul_eq_one_right $ congr_arg snd h), .. prod.div_inv_monoid, .. prod.has_involutive_inv } @[to_additive subtraction_comm_monoid] instance [division_comm_monoid G] [division_comm_monoid H] : division_comm_monoid (G × H) := { .. prod.division_monoid, .. prod.comm_semigroup } @[to_additive] instance [group G] [group H] : group (G × H) := { mul_left_inv := assume a, mk.inj_iff.mpr ⟨mul_left_inv _, mul_left_inv _⟩, .. prod.div_inv_monoid } @[to_additive] instance [left_cancel_semigroup G] [left_cancel_semigroup H] : left_cancel_semigroup (G × H) := { mul_left_cancel := λ a b c h, prod.ext (mul_left_cancel (prod.ext_iff.1 h).1) (mul_left_cancel (prod.ext_iff.1 h).2), .. prod.semigroup } @[to_additive] instance [right_cancel_semigroup G] [right_cancel_semigroup H] : right_cancel_semigroup (G × H) := { mul_right_cancel := λ a b c h, prod.ext (mul_right_cancel (prod.ext_iff.1 h).1) (mul_right_cancel (prod.ext_iff.1 h).2), .. prod.semigroup } @[to_additive] instance [left_cancel_monoid M] [left_cancel_monoid N] : left_cancel_monoid (M × N) := { .. prod.left_cancel_semigroup, .. prod.monoid } @[to_additive] instance [right_cancel_monoid M] [right_cancel_monoid N] : right_cancel_monoid (M × N) := { .. prod.right_cancel_semigroup, .. prod.monoid } @[to_additive] instance [cancel_monoid M] [cancel_monoid N] : cancel_monoid (M × N) := { .. prod.right_cancel_monoid, .. prod.left_cancel_monoid } @[to_additive] instance [comm_monoid M] [comm_monoid N] : comm_monoid (M × N) := { .. prod.comm_semigroup, .. prod.monoid } @[to_additive] instance [cancel_comm_monoid M] [cancel_comm_monoid N] : cancel_comm_monoid (M × N) := { .. prod.left_cancel_monoid, .. prod.comm_monoid } instance [mul_zero_one_class M] [mul_zero_one_class N] : mul_zero_one_class (M × N) := { .. prod.mul_zero_class, .. prod.mul_one_class } instance [monoid_with_zero M] [monoid_with_zero N] : monoid_with_zero (M × N) := { .. prod.monoid, .. prod.mul_zero_one_class } instance [comm_monoid_with_zero M] [comm_monoid_with_zero N] : comm_monoid_with_zero (M × N) := { .. prod.comm_monoid, .. prod.monoid_with_zero } @[to_additive] instance [comm_group G] [comm_group H] : comm_group (G × H) := { .. prod.comm_semigroup, .. prod.group } end prod namespace mul_hom section prod variables (M N) [has_mul M] [has_mul N] [has_mul P] /-- Given magmas `M`, `N`, the natural projection homomorphism from `M × N` to `M`.-/ @[to_additive "Given additive magmas `A`, `B`, the natural projection homomorphism from `A × B` to `A`"] def fst : (M × N) →ₙ* M := ⟨prod.fst, λ _ _, rfl⟩ /-- Given magmas `M`, `N`, the natural projection homomorphism from `M × N` to `N`.-/ @[to_additive "Given additive magmas `A`, `B`, the natural projection homomorphism from `A × B` to `B`"] def snd : (M × N) →ₙ* N := ⟨prod.snd, λ _ _, rfl⟩ variables {M N} @[simp, to_additive] lemma coe_fst : ⇑(fst M N) = prod.fst := rfl @[simp, to_additive] lemma coe_snd : ⇑(snd M N) = prod.snd := rfl /-- Combine two `monoid_hom`s `f : M →ₙ* N`, `g : M →ₙ* P` into `f.prod g : M →ₙ* (N × P)` given by `(f.prod g) x = (f x, g x)`. -/ @[to_additive prod "Combine two `add_monoid_hom`s `f : add_hom M N`, `g : add_hom M P` into `f.prod g : add_hom M (N × P)` given by `(f.prod g) x = (f x, g x)`"] protected def prod (f : M →ₙ* N) (g : M →ₙ* P) : M →ₙ* (N × P) := { to_fun := pi.prod f g, map_mul' := λ x y, prod.ext (f.map_mul x y) (g.map_mul x y) } @[to_additive coe_prod] lemma coe_prod (f : M →ₙ* N) (g : M →ₙ* P) : ⇑(f.prod g) = pi.prod f g := rfl @[simp, to_additive prod_apply] lemma prod_apply (f : M →ₙ* N) (g : M →ₙ* P) (x) : f.prod g x = (f x, g x) := rfl @[simp, to_additive fst_comp_prod] lemma fst_comp_prod (f : M →ₙ* N) (g : M →ₙ* P) : (fst N P).comp (f.prod g) = f := ext $ λ x, rfl @[simp, to_additive snd_comp_prod] lemma snd_comp_prod (f : M →ₙ* N) (g : M →ₙ* P) : (snd N P).comp (f.prod g) = g := ext $ λ x, rfl @[simp, to_additive prod_unique] lemma prod_unique (f : M →ₙ* (N × P)) : ((fst N P).comp f).prod ((snd N P).comp f) = f := ext $ λ x, by simp only [prod_apply, coe_fst, coe_snd, comp_apply, prod.mk.eta] end prod section prod_map variables {M' : Type*} {N' : Type*} [has_mul M] [has_mul N] [has_mul M'] [has_mul N'] [has_mul P] (f : M →ₙ* M') (g : N →ₙ* N') /-- `prod.map` as a `monoid_hom`. -/ @[to_additive prod_map "`prod.map` as an `add_monoid_hom`"] def prod_map : (M × N) →ₙ* (M' × N') := (f.comp (fst M N)).prod (g.comp (snd M N)) @[to_additive prod_map_def] lemma prod_map_def : prod_map f g = (f.comp (fst M N)).prod (g.comp (snd M N)) := rfl @[simp, to_additive coe_prod_map] lemma coe_prod_map : ⇑(prod_map f g) = prod.map f g := rfl @[to_additive prod_comp_prod_map] lemma prod_comp_prod_map (f : P →ₙ* M) (g : P →ₙ* N) (f' : M →ₙ* M') (g' : N →ₙ* N') : (f'.prod_map g').comp (f.prod g) = (f'.comp f).prod (g'.comp g) := rfl end prod_map section coprod variables [has_mul M] [has_mul N] [comm_semigroup P] (f : M →ₙ* P) (g : N →ₙ* P) /-- Coproduct of two `mul_hom`s with the same codomain: `f.coprod g (p : M × N) = f p.1 * g p.2`. -/ @[to_additive "Coproduct of two `add_hom`s with the same codomain: `f.coprod g (p : M × N) = f p.1 + g p.2`."] def coprod : (M × N) →ₙ* P := f.comp (fst M N) * g.comp (snd M N) @[simp, to_additive] lemma coprod_apply (p : M × N) : f.coprod g p = f p.1 * g p.2 := rfl @[to_additive] lemma comp_coprod {Q : Type*} [comm_semigroup Q] (h : P →ₙ* Q) (f : M →ₙ* P) (g : N →ₙ* P) : h.comp (f.coprod g) = (h.comp f).coprod (h.comp g) := ext $ λ x, by simp end coprod end mul_hom namespace monoid_hom variables (M N) [mul_one_class M] [mul_one_class N] /-- Given monoids `M`, `N`, the natural projection homomorphism from `M × N` to `M`.-/ @[to_additive "Given additive monoids `A`, `B`, the natural projection homomorphism from `A × B` to `A`"] def fst : M × N →* M := ⟨prod.fst, rfl, λ _ _, rfl⟩ /-- Given monoids `M`, `N`, the natural projection homomorphism from `M × N` to `N`.-/ @[to_additive "Given additive monoids `A`, `B`, the natural projection homomorphism from `A × B` to `B`"] def snd : M × N →* N := ⟨prod.snd, rfl, λ _ _, rfl⟩ /-- Given monoids `M`, `N`, the natural inclusion homomorphism from `M` to `M × N`. -/ @[to_additive "Given additive monoids `A`, `B`, the natural inclusion homomorphism from `A` to `A × B`."] def inl : M →* M × N := ⟨λ x, (x, 1), rfl, λ _ _, prod.ext rfl (one_mul 1).symm⟩ /-- Given monoids `M`, `N`, the natural inclusion homomorphism from `N` to `M × N`. -/ @[to_additive "Given additive monoids `A`, `B`, the natural inclusion homomorphism from `B` to `A × B`."] def inr : N →* M × N := ⟨λ y, (1, y), rfl, λ _ _, prod.ext (one_mul 1).symm rfl⟩ variables {M N} @[simp, to_additive] lemma coe_fst : ⇑(fst M N) = prod.fst := rfl @[simp, to_additive] lemma coe_snd : ⇑(snd M N) = prod.snd := rfl @[simp, to_additive] lemma inl_apply (x) : inl M N x = (x, 1) := rfl @[simp, to_additive] lemma inr_apply (y) : inr M N y = (1, y) := rfl @[simp, to_additive] lemma fst_comp_inl : (fst M N).comp (inl M N) = id M := rfl @[simp, to_additive] lemma snd_comp_inl : (snd M N).comp (inl M N) = 1 := rfl @[simp, to_additive] lemma fst_comp_inr : (fst M N).comp (inr M N) = 1 := rfl @[simp, to_additive] lemma snd_comp_inr : (snd M N).comp (inr M N) = id N := rfl section prod variable [mul_one_class P] /-- Combine two `monoid_hom`s `f : M →* N`, `g : M →* P` into `f.prod g : M →* N × P` given by `(f.prod g) x = (f x, g x)`. -/ @[to_additive prod "Combine two `add_monoid_hom`s `f : M →+ N`, `g : M →+ P` into `f.prod g : M →+ N × P` given by `(f.prod g) x = (f x, g x)`"] protected def prod (f : M →* N) (g : M →* P) : M →* N × P := { to_fun := pi.prod f g, map_one' := prod.ext f.map_one g.map_one, map_mul' := λ x y, prod.ext (f.map_mul x y) (g.map_mul x y) } @[to_additive coe_prod] lemma coe_prod (f : M →* N) (g : M →* P) : ⇑(f.prod g) = pi.prod f g := rfl @[simp, to_additive prod_apply] lemma prod_apply (f : M →* N) (g : M →* P) (x) : f.prod g x = (f x, g x) := rfl @[simp, to_additive fst_comp_prod] lemma fst_comp_prod (f : M →* N) (g : M →* P) : (fst N P).comp (f.prod g) = f := ext $ λ x, rfl @[simp, to_additive snd_comp_prod] lemma snd_comp_prod (f : M →* N) (g : M →* P) : (snd N P).comp (f.prod g) = g := ext $ λ x, rfl @[simp, to_additive prod_unique] lemma prod_unique (f : M →* N × P) : ((fst N P).comp f).prod ((snd N P).comp f) = f := ext $ λ x, by simp only [prod_apply, coe_fst, coe_snd, comp_apply, prod.mk.eta] end prod section prod_map variables {M' : Type*} {N' : Type*} [mul_one_class M'] [mul_one_class N'] [mul_one_class P] (f : M →* M') (g : N →* N') /-- `prod.map` as a `monoid_hom`. -/ @[to_additive prod_map "`prod.map` as an `add_monoid_hom`"] def prod_map : M × N →* M' × N' := (f.comp (fst M N)).prod (g.comp (snd M N)) @[to_additive prod_map_def] lemma prod_map_def : prod_map f g = (f.comp (fst M N)).prod (g.comp (snd M N)) := rfl @[simp, to_additive coe_prod_map] lemma coe_prod_map : ⇑(prod_map f g) = prod.map f g := rfl @[to_additive prod_comp_prod_map] lemma prod_comp_prod_map (f : P →* M) (g : P →* N) (f' : M →* M') (g' : N →* N') : (f'.prod_map g').comp (f.prod g) = (f'.comp f).prod (g'.comp g) := rfl end prod_map section coprod variables [comm_monoid P] (f : M →* P) (g : N →* P) /-- Coproduct of two `monoid_hom`s with the same codomain: `f.coprod g (p : M × N) = f p.1 * g p.2`. -/ @[to_additive "Coproduct of two `add_monoid_hom`s with the same codomain: `f.coprod g (p : M × N) = f p.1 + g p.2`."] def coprod : M × N →* P := f.comp (fst M N) * g.comp (snd M N) @[simp, to_additive] lemma coprod_apply (p : M × N) : f.coprod g p = f p.1 * g p.2 := rfl @[simp, to_additive] lemma coprod_comp_inl : (f.coprod g).comp (inl M N) = f := ext $ λ x, by simp [coprod_apply] @[simp, to_additive] lemma coprod_comp_inr : (f.coprod g).comp (inr M N) = g := ext $ λ x, by simp [coprod_apply] @[simp, to_additive] lemma coprod_unique (f : M × N →* P) : (f.comp (inl M N)).coprod (f.comp (inr M N)) = f := ext $ λ x, by simp [coprod_apply, inl_apply, inr_apply, ← map_mul] @[simp, to_additive] lemma coprod_inl_inr {M N : Type*} [comm_monoid M] [comm_monoid N] : (inl M N).coprod (inr M N) = id (M × N) := coprod_unique (id $ M × N) @[to_additive] lemma comp_coprod {Q : Type*} [comm_monoid Q] (h : P →* Q) (f : M →* P) (g : N →* P) : h.comp (f.coprod g) = (h.comp f).coprod (h.comp g) := ext $ λ x, by simp end coprod end monoid_hom namespace mul_equiv section variables {M N} [mul_one_class M] [mul_one_class N] /-- The equivalence between `M × N` and `N × M` given by swapping the components is multiplicative. -/ @[to_additive prod_comm "The equivalence between `M × N` and `N × M` given by swapping the components is additive."] def prod_comm : M × N ≃* N × M := { map_mul' := λ ⟨x₁, y₁⟩ ⟨x₂, y₂⟩, rfl, ..equiv.prod_comm M N } @[simp, to_additive coe_prod_comm] lemma coe_prod_comm : ⇑(prod_comm : M × N ≃* N × M) = prod.swap := rfl @[simp, to_additive coe_prod_comm_symm] lemma coe_prod_comm_symm : ⇑((prod_comm : M × N ≃* N × M).symm) = prod.swap := rfl variables {M' N' : Type*} [mul_one_class M'] [mul_one_class N'] section variables (M N M' N') /-- Four-way commutativity of `prod`. The name matches `mul_mul_mul_comm`. -/ @[to_additive prod_prod_prod_comm "Four-way commutativity of `prod`. The name matches `mul_mul_mul_comm`", simps apply] def prod_prod_prod_comm : (M × N) × (M' × N') ≃* (M × M') × (N × N') := { to_fun := λ mnmn, ((mnmn.1.1, mnmn.2.1), (mnmn.1.2, mnmn.2.2)), inv_fun := λ mmnn, ((mmnn.1.1, mmnn.2.1), (mmnn.1.2, mmnn.2.2)), map_mul' := λ mnmn mnmn', rfl, ..equiv.prod_prod_prod_comm M N M' N', } @[simp, to_additive] lemma prod_prod_prod_comm_to_equiv : (prod_prod_prod_comm M N M' N').to_equiv = equiv.prod_prod_prod_comm M N M' N' := rfl @[simp] lemma prod_prod_prod_comm_symm : (prod_prod_prod_comm M N M' N').symm = prod_prod_prod_comm M M' N N' := rfl end /--Product of multiplicative isomorphisms; the maps come from `equiv.prod_congr`.-/ @[to_additive prod_congr "Product of additive isomorphisms; the maps come from `equiv.prod_congr`."] def prod_congr (f : M ≃* M') (g : N ≃* N') : M × N ≃* M' × N' := { map_mul' := λ x y, prod.ext (f.map_mul _ _) (g.map_mul _ _), ..f.to_equiv.prod_congr g.to_equiv } /--Multiplying by the trivial monoid doesn't change the structure.-/ @[to_additive unique_prod "Multiplying by the trivial monoid doesn't change the structure."] def unique_prod [unique N] : N × M ≃* M := { map_mul' := λ x y, rfl, ..equiv.unique_prod M N } /--Multiplying by the trivial monoid doesn't change the structure.-/ @[to_additive prod_unique "Multiplying by the trivial monoid doesn't change the structure."] def prod_unique [unique N] : M × N ≃* M := { map_mul' := λ x y, rfl, ..equiv.prod_unique M N } end section variables {M N} [monoid M] [monoid N] /-- The monoid equivalence between units of a product of two monoids, and the product of the units of each monoid. -/ @[to_additive prod_add_units "The additive monoid equivalence between additive units of a product of two additive monoids, and the product of the additive units of each additive monoid."] def prod_units : (M × N)ˣ ≃* Mˣ × Nˣ := { to_fun := (units.map (monoid_hom.fst M N)).prod (units.map (monoid_hom.snd M N)), inv_fun := λ u, ⟨(u.1, u.2), (↑u.1⁻¹, ↑u.2⁻¹), by simp, by simp⟩, left_inv := λ u, by simp, right_inv := λ ⟨u₁, u₂⟩, by simp [units.map], map_mul' := monoid_hom.map_mul _ } end end mul_equiv namespace units open mul_opposite /-- Canonical homomorphism of monoids from `αˣ` into `α × αᵐᵒᵖ`. Used mainly to define the natural topology of `αˣ`. -/ @[to_additive "Canonical homomorphism of additive monoids from `add_units α` into `α × αᵃᵒᵖ`. Used mainly to define the natural topology of `add_units α`.", simps] def embed_product (α : Type*) [monoid α] : αˣ →* α × αᵐᵒᵖ := { to_fun := λ x, ⟨x, op ↑x⁻¹⟩, map_one' := by simp only [inv_one, eq_self_iff_true, units.coe_one, op_one, prod.mk_eq_one, and_self], map_mul' := λ x y, by simp only [mul_inv_rev, op_mul, units.coe_mul, prod.mk_mul_mk] } @[to_additive] lemma embed_product_injective (α : Type*) [monoid α] : function.injective (embed_product α) := λ a₁ a₂ h, units.ext $ (congr_arg prod.fst h : _) end units /-! ### Multiplication and division as homomorphisms -/ section bundled_mul_div variables {α : Type*} /-- Multiplication as a multiplicative homomorphism. -/ @[to_additive "Addition as an additive homomorphism.", simps] def mul_mul_hom [comm_semigroup α] : (α × α) →ₙ* α := { to_fun := λ a, a.1 * a.2, map_mul' := λ a b, mul_mul_mul_comm _ _ _ _ } /-- Multiplication as a monoid homomorphism. -/ @[to_additive "Addition as an additive monoid homomorphism.", simps] def mul_monoid_hom [comm_monoid α] : α × α →* α := { map_one' := mul_one _, .. mul_mul_hom } /-- Multiplication as a multiplicative homomorphism with zero. -/ @[simps] def mul_monoid_with_zero_hom [comm_monoid_with_zero α] : α × α →*₀ α := { map_zero' := mul_zero _, .. mul_monoid_hom } /-- Division as a monoid homomorphism. -/ @[to_additive "Subtraction as an additive monoid homomorphism.", simps] def div_monoid_hom [division_comm_monoid α] : α × α →* α := { to_fun := λ a, a.1 / a.2, map_one' := div_one _, map_mul' := λ a b, mul_div_mul_comm _ _ _ _ } /-- Division as a multiplicative homomorphism with zero. -/ @[simps] def div_monoid_with_zero_hom [comm_group_with_zero α] : α × α →*₀ α := { to_fun := λ a, a.1 / a.2, map_zero' := zero_div _, map_one' := div_one _, map_mul' := λ a b, mul_div_mul_comm _ _ _ _ } end bundled_mul_div
dba84ed174c173a33dda8f29f5fd3373043d3106
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/topology/omega_complete_partial_order.lean
6fe2cb70602e05ff32ae7398dffe361d7b2c4d41
[ "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
5,254
lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import topology.basic import order.omega_complete_partial_order /-! # Scott Topological Spaces A type of topological spaces whose notion of continuity is equivalent to continuity in ωCPOs. ## Reference * https://ncatlab.org/nlab/show/Scott+topology -/ open omega_complete_partial_order open_locale classical universes u namespace Scott /-- -/ def is_ωSup {α : Type u} [preorder α] (c : chain α) (x : α) : Prop := (∀ i, c i ≤ x) ∧ (∀ y, (∀ i, c i ≤ y) → x ≤ y) variables (α : Type u) [omega_complete_partial_order α] local attribute [irreducible] set /-- The characteristic function of open sets is monotone and preserves the limits of chains. -/ def is_open (s : set α) : Prop := continuous' (λ x, x ∈ s) theorem is_open_univ : is_open α set.univ := ⟨λ x y h, by simp only [set.mem_univ]; refl', by convert @complete_lattice.top_continuous α Prop _ _; ext; simp ⟩ theorem is_open.inter (s t : set α) : is_open α s → is_open α t → is_open α (s ∩ t) := begin simp only [is_open, exists_imp_distrib, continuous'], intros h₀ h₁ h₂ h₃, rw ← set.inf_eq_inter, let s' : α →ₘ Prop := ⟨λ x, x ∈ s, h₀⟩, let t' : α →ₘ Prop := ⟨λ x, x ∈ t, h₂⟩, split, { change omega_complete_partial_order.continuous (s' ⊓ t'), haveI : is_total Prop (≤) := ⟨ @le_total Prop _ ⟩, apply complete_lattice.inf_continuous; assumption }, { intros x y h, apply and_implies; solve_by_elim [h₀ h, h₂ h], } end theorem is_open_sUnion : ∀s, (∀t∈s, is_open α t) → is_open α (⋃₀ s) := begin introv h₀, suffices : is_open α ({ x | Sup (flip (∈) '' s) x }), { convert this, ext, simp only [set.sUnion, Sup, set.mem_image, set.mem_set_of_eq, supr, conditionally_complete_lattice.Sup, exists_exists_and_eq_and, complete_lattice.Sup, exists_prop, set.mem_range, set_coe.exists, eq_iff_iff, subtype.coe_mk], tauto, }, dsimp [is_open] at *, apply complete_lattice.Sup_continuous' _, introv ht, specialize h₀ { x | t x } _, { simp only [flip, set.mem_image] at *, rcases ht with ⟨x,h₀,h₁⟩, subst h₁, simpa, }, { simpa using h₀ } end end Scott /-- A Scott topological space is defined on preorders such that their open sets, seen as a function `α → Prop`, preserves the joins of ω-chains -/ @[reducible] def Scott (α : Type u) := α instance Scott.topological_space (α : Type u) [omega_complete_partial_order α] : topological_space (Scott α) := { is_open := Scott.is_open α, is_open_univ := Scott.is_open_univ α, is_open_inter := Scott.is_open.inter α, is_open_sUnion := Scott.is_open_sUnion α } section not_below variables {α : Type*} [omega_complete_partial_order α] (y : Scott α) /-- `not_below` is an open set in `Scott α` used to prove the monotonicity of continuous functions -/ def not_below := { x | ¬ x ≤ y } lemma not_below_is_open : is_open (not_below y) := begin have h : monotone (not_below y), { intros x y' h, simp only [not_below, set_of, le_Prop_eq], intros h₀ h₁, apply h₀ (le_trans h h₁) }, existsi h, rintros c, apply eq_of_forall_ge_iff, intro z, rw ωSup_le_iff, simp only [ωSup_le_iff, not_below, set.mem_set_of_eq, le_Prop_eq, preorder_hom.coe_fun_mk, chain.map_to_fun, function.comp_app, exists_imp_distrib, not_forall], end end not_below open Scott (hiding is_open) open omega_complete_partial_order lemma is_ωSup_ωSup {α} [omega_complete_partial_order α] (c : chain α) : is_ωSup c (ωSup c) := begin split, { apply le_ωSup, }, { apply ωSup_le, }, end lemma Scott_continuous_of_continuous {α β} [omega_complete_partial_order α] [omega_complete_partial_order β] (f : Scott α → Scott β) (hf : continuous f) : omega_complete_partial_order.continuous' f := begin simp only [continuous_def, (⁻¹')] at hf, have h : monotone f, { intros x y h, cases (hf {x | ¬ x ≤ f y} (not_below_is_open _)) with hf hf', clear hf', specialize hf h, simp only [set.preimage, set_of, (∈), set.mem, le_Prop_eq] at hf, by_contradiction H, apply hf H (le_refl (f y)) }, existsi h, intro c, apply eq_of_forall_ge_iff, intro z, specialize (hf _ (not_below_is_open z)), cases hf, specialize hf_h c, simp only [not_below, preorder_hom.coe_fun_mk, eq_iff_iff, set.mem_set_of_eq] at hf_h, rw [← not_iff_not], simp only [ωSup_le_iff, hf_h, ωSup, supr, Sup, complete_lattice.Sup, complete_semilattice_Sup.Sup, exists_prop, set.mem_range, preorder_hom.coe_fun_mk, chain.map_to_fun, function.comp_app, eq_iff_iff, not_forall], tauto, end lemma continuous_of_Scott_continuous {α β} [omega_complete_partial_order α] [omega_complete_partial_order β] (f : Scott α → Scott β) (hf : omega_complete_partial_order.continuous' f) : continuous f := begin rw continuous_def, intros s hs, change continuous' (s ∘ f), cases hs with hs hs', cases hf with hf hf', apply continuous.of_bundled, apply continuous_comp _ _ hf' hs', end
7f4f4a8eaff9540d3c57fbc1cb95cceb5b579446
1e561612e7479c100cd9302e3fe08cbd2914aa25
/mathlib4_experiments/Commands/print_prefix.lean
7fd47234989e909210c083b0266e39e403c9a379
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib4_experiments
8de8ed7193f70748a7529e05d831203a7c64eedb
87cb879b4d602c8ecfd9283b7c0b06015abdbab1
refs/heads/master
1,687,971,389,316
1,620,336,942,000
1,620,336,942,000
353,994,588
7
4
Apache-2.0
1,622,410,748,000
1,617,361,732,000
Lean
UTF-8
Lean
false
false
1,086
lean
import Lean open Lean Lean.Meta deriving instance Inhabited for ConstantInfo -- required for Array.qsort structure FindOptions where stage1 : Bool := true checkPrivate : Bool := false def findCore (ϕ : ConstantInfo → MetaM Bool) (opts : FindOptions := {}) : MetaM (Array ConstantInfo) := do let matches ← if !opts.stage1 then #[] else (← getEnv).constants.map₁.foldM (init := #[]) check (← getEnv).constants.map₂.foldlM (init := matches) check where check matches name cinfo := do if opts.checkPrivate || (not $ isPrivateName name) then if (← ϕ cinfo) then pure (matches.push cinfo) else pure matches else pure matches def find (ϕ : ConstantInfo → MetaM Bool) (opts : FindOptions := {}) : MetaM Unit := do let cinfos ← findCore ϕ opts let cinfos := cinfos.qsort (fun p q => p.name.lt q.name) for cinfo in cinfos do println! "{cinfo.name} : {← Meta.ppExpr cinfo.type}" macro "#print prefix" name:ident : command => `(#eval find λ cinfo => $(quote name.getId).isPrefixOf cinfo.name) --#print prefix Nat
6e21948ebde5a9e2afe77695e85163a299b8dc7b
07c6143268cfb72beccd1cc35735d424ebcb187b
/src/data/num/bitwise.lean
a2fe7eb4ff7f92805e70d4f352a1baf9a4b52acb
[ "Apache-2.0" ]
permissive
khoek/mathlib
bc49a842910af13a3c372748310e86467d1dc766
aa55f8b50354b3e11ba64792dcb06cccb2d8ee28
refs/heads/master
1,588,232,063,837
1,587,304,803,000
1,587,304,803,000
176,688,517
0
0
Apache-2.0
1,553,070,585,000
1,553,070,585,000
null
UTF-8
Lean
false
false
7,570
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Bitwise operations using binary representation of integers. -/ import data.num.basic data.bitvec namespace pos_num def lor : pos_num → pos_num → pos_num | 1 (bit0 q) := bit1 q | 1 q := q | (bit0 p) 1 := bit1 p | p 1 := p | (bit0 p) (bit0 q) := bit0 (lor p q) | (bit0 p) (bit1 q) := bit1 (lor p q) | (bit1 p) (bit0 q) := bit1 (lor p q) | (bit1 p) (bit1 q) := bit1 (lor p q) def land : pos_num → pos_num → num | 1 (bit0 q) := 0 | 1 _ := 1 | (bit0 p) 1 := 0 | _ 1 := 1 | (bit0 p) (bit0 q) := num.bit0 (land p q) | (bit0 p) (bit1 q) := num.bit0 (land p q) | (bit1 p) (bit0 q) := num.bit0 (land p q) | (bit1 p) (bit1 q) := num.bit1 (land p q) def ldiff : pos_num → pos_num → num | 1 (bit0 q) := 1 | 1 _ := 0 | (bit0 p) 1 := num.pos (bit0 p) | (bit1 p) 1 := num.pos (bit0 p) | (bit0 p) (bit0 q) := num.bit0 (ldiff p q) | (bit0 p) (bit1 q) := num.bit0 (ldiff p q) | (bit1 p) (bit0 q) := num.bit1 (ldiff p q) | (bit1 p) (bit1 q) := num.bit0 (ldiff p q) def lxor : pos_num → pos_num → num | 1 1 := 0 | 1 (bit0 q) := num.pos (bit1 q) | 1 (bit1 q) := num.pos (bit0 q) | (bit0 p) 1 := num.pos (bit1 p) | (bit1 p) 1 := num.pos (bit0 p) | (bit0 p) (bit0 q) := num.bit0 (lxor p q) | (bit0 p) (bit1 q) := num.bit1 (lxor p q) | (bit1 p) (bit0 q) := num.bit1 (lxor p q) | (bit1 p) (bit1 q) := num.bit0 (lxor p q) def test_bit : pos_num → nat → bool | 1 0 := tt | 1 (n+1) := ff | (bit0 p) 0 := ff | (bit0 p) (n+1) := test_bit p n | (bit1 p) 0 := tt | (bit1 p) (n+1) := test_bit p n def one_bits : pos_num → nat → list nat | 1 d := [d] | (bit0 p) d := one_bits p (d+1) | (bit1 p) d := d :: one_bits p (d+1) def shiftl (p : pos_num) : nat → pos_num | 0 := p | (n+1) := bit0 (shiftl n) def shiftr : pos_num → nat → num | p 0 := num.pos p | 1 (n+1) := 0 | (bit0 p) (n+1) := shiftr p n | (bit1 p) (n+1) := shiftr p n end pos_num namespace num def lor : num → num → num | 0 q := q | p 0 := p | (pos p) (pos q) := pos (p.lor q) def land : num → num → num | 0 q := 0 | p 0 := 0 | (pos p) (pos q) := p.land q def ldiff : num → num → num | 0 q := 0 | p 0 := p | (pos p) (pos q) := p.ldiff q def lxor : num → num → num | 0 q := q | p 0 := p | (pos p) (pos q) := p.lxor q def shiftl : num → nat → num | 0 n := 0 | (pos p) n := pos (p.shiftl n) def shiftr : num → nat → num | 0 n := 0 | (pos p) n := p.shiftr n def test_bit : num → nat → bool | 0 n := ff | (pos p) n := p.test_bit n def one_bits : num → list nat | 0 := [] | (pos p) := p.one_bits 0 end num /-- See `snum`. -/ @[derive has_reflect, derive decidable_eq] inductive nzsnum : Type | msb : bool → nzsnum | bit : bool → nzsnum → nzsnum /-- Alternative representation of integers using a sign bit at the end. The convention on sign here is to have the argument to `msb` denote the sign of the MSB itself, with all higher bits set to the negation of this sign. The result is interpreted in two's complement. 13 = ..0001101(base 2) = nz (bit1 (bit0 (bit1 (msb tt)))) -13 = ..1110011(base 2) = nz (bit1 (bit1 (bit0 (msb ff)))) As with `num`, a special case must be added for zero, which has no msb, but by two's complement symmetry there is a second special case for -1. Here the `bool` field indicates the sign of the number. 0 = ..0000000(base 2) = zero ff -1 = ..1111111(base 2) = zero tt -/ @[derive has_reflect, derive decidable_eq] inductive snum : Type | zero : bool → snum | nz : nzsnum → snum instance : has_coe nzsnum snum := ⟨snum.nz⟩ instance : has_zero snum := ⟨snum.zero ff⟩ instance : has_one nzsnum := ⟨nzsnum.msb tt⟩ instance : has_one snum := ⟨snum.nz 1⟩ instance : inhabited nzsnum := ⟨1⟩ instance : inhabited snum := ⟨0⟩ /- The snum representation uses a bit string, essentially a list of 0 (ff) and 1 (tt) bits, and the negation of the MSB is sign-extended to all higher bits. -/ namespace nzsnum notation a :: b := bit a b def sign : nzsnum → bool | (msb b) := bnot b | (b :: p) := sign p @[pattern] def not : nzsnum → nzsnum | (msb b) := msb (bnot b) | (b :: p) := bnot b :: not p prefix ~ := not def bit0 : nzsnum → nzsnum := bit ff def bit1 : nzsnum → nzsnum := bit tt def head : nzsnum → bool | (msb b) := b | (b :: p) := b def tail : nzsnum → snum | (msb b) := snum.zero (bnot b) | (b :: p) := p end nzsnum namespace snum open nzsnum def sign : snum → bool | (zero z) := z | (nz p) := p.sign @[pattern] def not : snum → snum | (zero z) := zero (bnot z) | (nz p) := ~p prefix ~ := not @[pattern] def bit : bool → snum → snum | b (zero z) := if b = z then zero b else msb b | b (nz p) := p.bit b notation a :: b := bit a b def bit0 : snum → snum := bit ff def bit1 : snum → snum := bit tt theorem bit_zero (b) : b :: zero b = zero b := by cases b; refl theorem bit_one (b) : b :: zero (bnot b) = msb b := by cases b; refl end snum namespace nzsnum open snum def drec' {C : snum → Sort*} (z : Π b, C (snum.zero b)) (s : Π b p, C p → C (b :: p)) : Π p : nzsnum, C p | (msb b) := by rw ←bit_one; exact s b (snum.zero (bnot b)) (z (bnot b)) | (bit b p) := s b p (drec' p) end nzsnum namespace snum open nzsnum def head : snum → bool | (zero z) := z | (nz p) := p.head def tail : snum → snum | (zero z) := zero z | (nz p) := p.tail def drec' {C : snum → Sort*} (z : Π b, C (snum.zero b)) (s : Π b p, C p → C (b :: p)) : Π p, C p | (zero b) := z b | (nz p) := p.drec' z s def rec' {α} (z : bool → α) (s : bool → snum → α → α) : snum → α := drec' z s def test_bit : nat → snum → bool | 0 p := head p | (n+1) p := test_bit n (tail p) def succ : snum → snum := rec' (λ b, cond b 0 1) (λb p succp, cond b (ff :: succp) (tt :: p)) def pred : snum → snum := rec' (λ b, cond b (~1) ~0) (λb p predp, cond b (ff :: p) (tt :: predp)) protected def neg (n : snum) : snum := succ ~n instance : has_neg snum := ⟨snum.neg⟩ -- First bit is 0 or 1 (tt), second bit is 0 or -1 (tt) def czadd : bool → bool → snum → snum | ff ff p := p | ff tt p := pred p | tt ff p := succ p | tt tt p := p end snum namespace snum def bits : snum → Π n, vector bool n | p 0 := vector.nil | p (n+1) := head p :: bits (tail p) n def cadd : snum → snum → bool → snum := rec' (λ a p c, czadd c a p) $ λa p IH, rec' (λb c, czadd c b (a :: p)) $ λb q _ c, bitvec.xor3 a b c :: IH q (bitvec.carry a b c) protected def add (a b : snum) : snum := cadd a b ff instance : has_add snum := ⟨snum.add⟩ protected def sub (a b : snum) : snum := a + -b instance : has_sub snum := ⟨snum.sub⟩ protected def mul (a : snum) : snum → snum := rec' (λ b, cond b (-a) 0) $ λb q IH, cond b (bit0 IH + a) (bit0 IH) instance : has_mul snum := ⟨snum.mul⟩ end snum
54089731ed15dfb70c2e8a6c57ad6bb9739bea1a
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/order/filter/filter_product.lean
10e39b0ce41b9a8b7e37eb155fc71ddbd80a95aa
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
22,480
lean
/- Copyright (c) 2019 Abhimanyu Pallavi Sudhir. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Abhimanyu Pallavi Sudhir "Filterproducts" (ultraproducts on general filters), ultraproducts. -/ import order.filter.basic import algebra.pi_instances universes u v variables {α : Type u} (β : Type v) (φ : filter α) open_locale classical namespace filter local notation `∀*` binders `, ` r:(scoped p, filter.eventually p φ) := r /-- Two sequences are bigly equal iff the kernel of their difference is in φ -/ def bigly_equal : setoid (α → β) := ⟨ λ a b, ∀* n, a n = b n, λ a, by simp, λ a b ab, by simpa only [eq_comm], λ a b c ab bc, sets_of_superset φ (inter_sets φ ab bc) (λ n r, eq.trans r.1 r.2)⟩ /-- Ultraproduct, but on a general filter -/ def filterprod := quotient (bigly_equal β φ) local notation `β*` := filterprod β φ namespace filter_product variables {α β φ} include φ /-- Equivalence class containing the given sequence -/ def of_seq : (α → β) → β* := @quotient.mk' (α → β) (bigly_equal β φ) /-- Equivalence class containing the constant sequence of a term in β -/ def of (b : β) : β* := of_seq (function.const α b) /-- Lift function to filter product -/ def lift (f : β → β) : β* → β* := λ x, quotient.lift_on' x (λ a, (of_seq $ λ n, f (a n) : β*)) $ λ a b h, quotient.sound' $ show _ ∈ _, by filter_upwards [h] λ i hi, congr_arg _ hi /-- Lift binary operation to filter product -/ def lift₂ (f : β → β → β) : β* → β* → β* := λ x y, quotient.lift_on₂' x y (λ a b, (of_seq $ λ n, f (a n) (b n) : β*)) $ λ a₁ a₂ b₁ b₂ h1 h2, quotient.sound' $ show _ ∈ _, by filter_upwards [h1, h2] λ i hi1 hi2, congr (congr_arg _ hi1) hi2 /-- Lift properties to filter product -/ def lift_rel (R : β → Prop) : β* → Prop := λ x, quotient.lift_on' x (λ a, ∀* i, R (a i)) $ λ a b h, propext ⟨ λ ha, by filter_upwards [h, ha] λ i hi hia, by simpa [hi.symm], λ hb, by filter_upwards [h, hb] λ i hi hib, by simpa [hi.symm.symm] ⟩ /-- Lift binary relations to filter product -/ def lift_rel₂ (R : β → β → Prop) : β* → β* → Prop := λ x y, quotient.lift_on₂' x y (λ a b, ∀* i, R (a i) (b i)) $ λ a₁ a₂ b₁ b₂ h₁ h₂, propext ⟨ λ ha, by filter_upwards [h₁, h₂, ha] λ i hi1 hi2 hia, by simpa [hi1.symm, hi2.symm], λ hb, by filter_upwards [h₁, h₂, hb] λ i hi1 hi2 hib, by simpa [hi1.symm.symm, hi2.symm.symm] ⟩ instance coe_filterprod : has_coe_t β β* := ⟨ of ⟩ -- note [use has_coe_t] instance [inhabited β] : inhabited β* := ⟨of (default _)⟩ instance [has_add β] : has_add β* := { add := lift₂ has_add.add } instance [has_zero β] : has_zero β* := { zero := of 0 } instance [has_neg β] : has_neg β* := { neg := lift has_neg.neg } instance [add_semigroup β] : add_semigroup β* := { add_assoc := λ x y z, quotient.induction_on₃' x y z $ λ a b c, quotient.sound' $ show ∀* _, _ + _ + _ = _ + (_ + _), by simp only [add_assoc, eq_self_iff_true]; exact φ.univ_sets, ..filter_product.has_add } instance [add_left_cancel_semigroup β] : add_left_cancel_semigroup β* := { add_left_cancel := λ x y z, quotient.induction_on₃' x y z $ λ a b c h, have h' : _ := quotient.exact' h, quotient.sound' $ by filter_upwards [h'] λ i, add_left_cancel, ..filter_product.add_semigroup } instance [add_right_cancel_semigroup β] : add_right_cancel_semigroup β* := { add_right_cancel := λ x y z, quotient.induction_on₃' x y z $ λ a b c h, have h' : _ := quotient.exact' h, quotient.sound' $ by filter_upwards [h'] λ i, add_right_cancel, ..filter_product.add_semigroup } instance [add_monoid β] : add_monoid β* := { zero_add := λ x, quotient.induction_on' x (λ a, quotient.sound'(by simp only [zero_add]; apply setoid.iseqv.1)), add_zero := λ x, quotient.induction_on' x (λ a, quotient.sound'(by simp only [add_zero]; apply setoid.iseqv.1)), ..filter_product.add_semigroup, ..filter_product.has_zero } instance [add_comm_semigroup β] : add_comm_semigroup β* := { add_comm := λ x y, quotient.induction_on₂' x y (λ a b, quotient.sound' (by simp only [add_comm]; apply setoid.iseqv.1)), ..filter_product.add_semigroup } instance [add_comm_monoid β] : add_comm_monoid β* := { ..filter_product.add_comm_semigroup, ..filter_product.add_monoid } instance [add_group β] : add_group β* := { add_left_neg := λ x, quotient.induction_on' x (λ a, quotient.sound' (by simp only [add_left_neg]; apply setoid.iseqv.1)), ..filter_product.add_monoid, ..filter_product.has_neg } instance [add_comm_group β] : add_comm_group β* := { ..filter_product.add_comm_monoid, ..filter_product.add_group } instance [has_mul β] : has_mul β* := { mul := lift₂ has_mul.mul } instance [has_one β] : has_one β* := { one := of 1 } instance [has_inv β] : has_inv β* := { inv := lift has_inv.inv } instance [semigroup β] : semigroup β* := { mul_assoc := λ x y z, quotient.induction_on₃' x y z $ λ a b c, quotient.sound' $ show ∀* _, _ * _ * _ = _ * (_ * _), by simp only [mul_assoc, eq_self_iff_true]; exact φ.univ_sets, ..filter_product.has_mul } instance [monoid β] : monoid β* := { one_mul := λ x, quotient.induction_on' x (λ a, quotient.sound' (by simp only [one_mul]; apply setoid.iseqv.1)), mul_one := λ x, quotient.induction_on' x (λ a, quotient.sound' (by simp only [mul_one]; apply setoid.iseqv.1)), ..filter_product.semigroup, ..filter_product.has_one } instance [comm_semigroup β] : comm_semigroup β* := { mul_comm := λ x y, quotient.induction_on₂' x y (λ a b, quotient.sound' (by simp only [mul_comm]; apply setoid.iseqv.1)), ..filter_product.semigroup } instance [comm_monoid β] : comm_monoid β* := { ..filter_product.comm_semigroup, ..filter_product.monoid } instance [group β] : group β* := { mul_left_inv := λ x, quotient.induction_on' x (λ a, quotient.sound' (by simp only [mul_left_inv]; apply setoid.iseqv.1)), ..filter_product.monoid, ..filter_product.has_inv } instance [comm_group β] : comm_group β* := { ..filter_product.comm_monoid, ..filter_product.group } instance [distrib β] : distrib β* := { left_distrib := λ x y z, quotient.induction_on₃' x y z (λ x y z, quotient.sound' (by simp only [left_distrib]; apply setoid.iseqv.1)), right_distrib := λ x y z, quotient.induction_on₃' x y z (λ x y z, quotient.sound' (by simp only [right_distrib]; apply setoid.iseqv.1)), ..filter_product.has_add, ..filter_product.has_mul } instance [mul_zero_class β] : mul_zero_class β* := { zero_mul := λ x, quotient.induction_on' x (λ a, quotient.sound' (by simp only [zero_mul]; apply setoid.iseqv.1)), mul_zero := λ x, quotient.induction_on' x (λ a, quotient.sound' (by simp only [mul_zero]; apply setoid.iseqv.1)), ..filter_product.has_mul, ..filter_product.has_zero } instance [semiring β] : semiring β* := { ..filter_product.add_comm_monoid, ..filter_product.monoid, ..filter_product.distrib, ..filter_product.mul_zero_class } instance [ring β] : ring β* := { ..filter_product.add_comm_group, ..filter_product.monoid, ..filter_product.distrib } instance [comm_semiring β] : comm_semiring β* := { ..filter_product.semiring, ..filter_product.comm_monoid } instance [comm_ring β] : comm_ring β* := { ..filter_product.ring, ..filter_product.comm_semigroup } /-- If `φ ≠ ⊥` then `0 ≠ 1` in the ultraproduct. This cannot be an instance, since it depends on `φ ≠ ⊥`. -/ protected def zero_ne_one_class [zero_ne_one_class β] (NT : φ ≠ ⊥) : zero_ne_one_class β* := { zero_ne_one := λ c, have c' : _ := quotient.exact' c, by { change _ ∈ _ at c', simp only [set.set_of_false, zero_ne_one, empty_in_sets_eq_bot] at c', exact NT c' }, ..filter_product.has_zero, ..filter_product.has_one } /-- If `φ` is an ultrafilter then the ultraproduct is a division ring. This cannot be an instance, since it depends on `φ` being an ultrafilter. -/ protected def division_ring [division_ring β] (U : is_ultrafilter φ) : division_ring β* := { mul_inv_cancel := λ x, quotient.induction_on' x $ λ a hx, quotient.sound' $ have hx1 : _ := (not_imp_not.mpr quotient.eq'.mpr) hx, have hx2 : _ := (ultrafilter_iff_compl_mem_iff_not_mem.mp U _).mpr hx1, have h : {n : α | ¬a n = 0} ⊆ {n : α | a n * (a n)⁻¹ = 1} := by rw [set.set_of_subset_set_of]; exact λ n, division_ring.mul_inv_cancel, mem_sets_of_superset hx2 h, inv_mul_cancel := λ x, quotient.induction_on' x $ λ a hx, quotient.sound' $ have hx1 : _ := (not_imp_not.mpr quotient.eq'.mpr) hx, have hx2 : _ := (ultrafilter_iff_compl_mem_iff_not_mem.mp U _).mpr hx1, have h : {n : α | ¬a n = 0} ⊆ {n : α | (a n)⁻¹ * a n = 1} := by rw [set.set_of_subset_set_of]; exact λ n, division_ring.inv_mul_cancel, mem_sets_of_superset hx2 h, inv_zero := quotient.sound' $ by show _ ∈ _; simp only [inv_zero, eq_self_iff_true, (set.univ_def).symm, univ_sets], ..filter_product.ring, ..filter_product.has_inv, ..filter_product.zero_ne_one_class U.1 } /-- If `φ` is an ultrafilter then the ultraproduct is a field. This cannot be an instance, since it depends on `φ` being an ultrafilter. -/ protected def field [field β] (U : is_ultrafilter φ) : field β* := { ..filter_product.comm_ring, ..filter_product.division_ring U } instance [has_le β] : has_le β* := { le := lift_rel₂ has_le.le } instance [preorder β] : preorder β* := { le_refl := λ x, quotient.induction_on' x $ λ a, show _ ∈ _, by simp only [le_refl, (set.univ_def).symm, univ_sets], le_trans := λ x y z, quotient.induction_on₃' x y z $ λ a b c hab hbc, by filter_upwards [hab, hbc] λ i, le_trans, ..filter_product.has_le} instance [partial_order β] : partial_order β* := { le_antisymm := λ x y, quotient.induction_on₂' x y $ λ a b hab hba, quotient.sound' $ have hI : {n | a n = b n} = _ ∩ _ := set.ext (λ n, le_antisymm_iff), show _ ∈ _, by rw hI; exact inter_sets _ hab hba ..filter_product.preorder } /-- If `φ` is an ultrafilter then the ultraproduct is a linear order. This cannot be an instance, since it depends on `φ` being an ultrafilter. -/ protected def linear_order [linear_order β] (U : is_ultrafilter φ) : linear_order β* := { le_total := λ x y, quotient.induction_on₂' x y $ λ a b, have hS : _ ⊆ {i | b i ≤ a i} := λ i, le_of_not_le, or.cases_on (mem_or_compl_mem_of_ultrafilter U {i | a i ≤ b i}) (λ h, or.inl h) (λ h, or.inr (sets_of_superset _ h hS)) ..filter_product.partial_order } theorem of_inj (NT : φ ≠ ⊥) : function.injective (@of _ β φ) := begin intros r s rs, by_contra N, rw [of, of, of_seq, quotient.eq', bigly_equal] at rs, simp only [N, eventually_false_iff_eq_bot] at rs, exact NT rs end theorem of_seq_fun (f g : α → β) (h : β → β) (H : ∀* n, f n = h (g n)) : of_seq f = (lift h) (@of_seq _ _ φ g) := quotient.sound' H theorem of_seq_fun₂ (f g₁ g₂ : α → β) (h : β → β → β) (H : ∀* n, f n = h (g₁ n) (g₂ n)) : of_seq f = (lift₂ h) (@of_seq _ _ φ g₁) (@of_seq _ _ φ g₂) := quotient.sound' H @[simp] lemma of_seq_zero [has_zero β] : of_seq 0 = (0 : β*) := rfl @[simp] lemma of_seq_add [has_add β] (f g : α → β) : of_seq (f + g) = of_seq f + (of_seq g : β*) := rfl @[simp] lemma of_seq_neg [has_neg β] (f : α → β) : of_seq (-f) = - (of_seq f : β*) := rfl @[simp] lemma of_seq_one [has_one β] : of_seq 1 = (1 : β*) := rfl @[simp] lemma of_seq_mul [has_mul β] (f g : α → β) : of_seq (f * g) = of_seq f * (of_seq g : β*) := rfl @[simp] lemma of_seq_inv [has_inv β] (f : α → β) : of_seq (f⁻¹) = (of_seq f : β*)⁻¹ := rfl @[simp] lemma of_eq_coe (x : β) : of x = (x : β*) := rfl @[simp] lemma coe_injective (x y : β) (NT : φ ≠ ⊥) : (x : β*) = y ↔ x = y := ⟨λ h, of_inj NT h, λ h, by rw h⟩ lemma of_eq (x y : β) (NT : φ ≠ ⊥) : x = y ↔ of x = (of y : β*) := by simp [NT] lemma of_ne (x y : β) (NT : φ ≠ ⊥) : x ≠ y ↔ of x ≠ (of y : β*) := by show ¬ x = y ↔ of x ≠ of y; rwa [of_eq] lemma of_eq_zero [has_zero β] (NT : φ ≠ ⊥) (x : β) : x = 0 ↔ (x : β*) = (0 : β*) := of_eq _ _ NT lemma of_ne_zero [has_zero β] (NT : φ ≠ ⊥) (x : β) : x ≠ 0 ↔ (x : β*) ≠ (0 : β*) := of_ne _ _ NT @[simp, move_cast] lemma of_zero [has_zero β] : ((0 : β) : β*) = 0 := rfl @[simp, move_cast] lemma of_add [has_add β] (x y : β) : ((x + y : β) : β*) = x + y := rfl @[simp, move_cast] lemma of_bit0 [has_add β] (x : β) : ((bit0 x : β) : β*) = bit0 x := rfl @[simp, move_cast] lemma of_bit1 [has_add β] [has_one β] (x : β) : ((bit1 x : β) : β*) = bit1 x := rfl @[simp, move_cast] lemma of_neg [has_neg β] (x : β) : ((- x : β) : β*) = - x := rfl @[simp, move_cast] lemma of_sub [add_group β] (x y : β) : ((x - y : β) : β*) = x - y := rfl @[simp, move_cast] lemma of_one [has_one β] : ((1 : β) : β*) = 1 := rfl @[simp, move_cast] lemma of_mul [has_mul β] (x y : β) : ((x * y : β) : β*) = x * y := rfl @[simp, move_cast] lemma of_inv [has_inv β] (x : β) : ((x⁻¹ : β) : β*) = x⁻¹ := rfl @[simp, move_cast] lemma of_div [division_ring β] (U : is_ultrafilter φ) (x y : β) : ((x / y : β) : β*) = @has_div.div _ (@has_div_of_division_ring _ (filter_product.division_ring U)) (x : β*) (y : β*) := rfl lemma of_rel_of_rel {R : β → Prop} {x : β} : R x → (lift_rel R) (of x : β*) := λ hx, show ∀* i, R x, by simp [hx] lemma of_rel {R : β → Prop} {x : β} (NT: φ ≠ ⊥) : R x ↔ (lift_rel R) (of x : β*) := ⟨ of_rel_of_rel, begin intro hxy, change ∀* i, R x at hxy, by_contra h, simp only [h, eventually_false_iff_eq_bot] at hxy, exact NT hxy end⟩ lemma of_rel_of_rel₂ {R : β → β → Prop} {x y : β} : R x y → (lift_rel₂ R) (of x) (of y : β*) := λ hxy, show ∀* i, R x y, by simp [hxy] lemma of_rel₂ {R : β → β → Prop} {x y : β} (NT: φ ≠ ⊥) : R x y ↔ (lift_rel₂ R) (of x) (of y : β*) := ⟨ of_rel_of_rel₂, λ hxy, by change ∀* i, R x y at hxy; by_contra h; simp only [h, eventually_false_iff_eq_bot] at hxy; exact NT hxy ⟩ lemma of_le_of_le [has_le β] {x y : β} : x ≤ y → of x ≤ (of y : β*) := of_rel_of_rel₂ lemma of_le [has_le β] {x y : β} (NT: φ ≠ ⊥) : x ≤ y ↔ of x ≤ (of y : β*) := of_rel₂ NT lemma lt_def [K : preorder β] (U : is_ultrafilter φ) {x y : β*} : (x < y) ↔ lift_rel₂ (<) x y := ⟨ quotient.induction_on₂' x y $ λ a b ⟨hxy, hyx⟩, have hyx' : _ := (ultrafilter_iff_compl_mem_iff_not_mem.mp U _).mpr hyx, by filter_upwards [hxy, hyx'] λ i hi1 hi2, lt_iff_le_not_le.mpr ⟨hi1, hi2⟩, quotient.induction_on₂' x y $ λ a b hab, ⟨ by filter_upwards [hab] λ i, le_of_lt, λ hba, have hc : ∀ i : α, a i < b i ∧ b i ≤ a i → false := λ i ⟨h1, h2⟩, not_lt_of_le h2 h1, have h0 : ∅ = {i : α | a i < b i} ∩ {i : α | b i ≤ a i} := by simp only [set.inter_def, hc, set.set_of_false, eq_self_iff_true, set.mem_set_of_eq], U.1 $ empty_in_sets_eq_bot.mp $ by rw [h0]; exact inter_sets _ hab hba ⟩ ⟩ lemma lt_def' [K : preorder β] (U : is_ultrafilter φ) : ((<) : β* → β* → Prop) = lift_rel₂ (<) := by ext x y; exact lt_def U lemma of_lt_of_lt [preorder β] (U : is_ultrafilter φ) {x y : β} : x < y → of x < (of y : β*) := by rw lt_def U; apply of_rel_of_rel₂ lemma of_lt [preorder β] {x y : β} (U : is_ultrafilter φ) : x < y ↔ of x < (of y : β*) := by rw lt_def U; exact of_rel₂ U.1 lemma lift_id : lift id = (id : β* → β*) := funext $ λ x, quotient.induction_on' x $ by apply λ a, quotient.sound (setoid.refl _) /-- If `φ` is an ultrafilter then the ultraproduct is an ordered commutative group. This cannot be an instance, since it depends on `φ` being an ultrafilter. -/ protected def ordered_add_comm_group [ordered_add_comm_group β] : ordered_add_comm_group β* := { add_le_add_left := λ x y hxy z, by revert hxy; exact quotient.induction_on₃' x y z (λ a b c hab, by filter_upwards [hab] λ i hi, by simpa), ..filter_product.partial_order, ..filter_product.add_comm_group } /-- If `φ` is an ultrafilter then the ultraproduct is an ordered ring. This cannot be an instance, since it depends on `φ` being an ultrafilter. -/ protected def ordered_ring [ordered_ring β] (U : is_ultrafilter φ) : ordered_ring β* := { mul_pos := λ x y, quotient.induction_on₂' x y $ λ a b ha hb, by rw lt_def U at ha hb ⊢; filter_upwards [ha, hb] λ i, mul_pos, ..filter_product.ring, ..filter_product.ordered_add_comm_group, ..filter_product.zero_ne_one_class U.1 } /-- If `φ` is an ultrafilter then the ultraproduct is a linear ordered ring. This cannot be an instance, since it depends on `φ` being an ultrafilter. -/ protected def linear_ordered_ring [linear_ordered_ring β] (U : is_ultrafilter φ) : linear_ordered_ring β* := { zero_lt_one := by rw lt_def U; show (∀* i, (0 : β) < 1); simp [zero_lt_one], ..filter_product.ordered_ring U, ..filter_product.linear_order U } /-- If `φ` is an ultrafilter then the ultraproduct is a linear ordered field. This cannot be an instance, since it depends on `φ` being an ultrafilter. -/ protected def linear_ordered_field [linear_ordered_field β] (U : is_ultrafilter φ) : linear_ordered_field β* := { ..filter_product.linear_ordered_ring U, ..filter_product.field U } /-- If `φ` is an ultrafilter then the ultraproduct is a linear ordered commutative ring. This cannot be an instance, since it depends on `φ` being an ultrafilter. -/ protected def linear_ordered_comm_ring [linear_ordered_comm_ring β] (U : is_ultrafilter φ) : linear_ordered_comm_ring β* := { ..filter_product.linear_ordered_ring U, ..filter_product.comm_monoid } /-- If `φ` is an ultrafilter then the ultraproduct is a decidable linear order. This cannot be an instance, since it depends on `φ` being an ultrafilter. -/ protected noncomputable def decidable_linear_order [decidable_linear_order β] (U : is_ultrafilter φ) : decidable_linear_order β* := { decidable_le := by apply_instance, ..filter_product.linear_order U } /-- If `φ` is an ultrafilter then the ultraproduct is a decidable linear ordered commutative group. This cannot be an instance, since it depends on `φ` being an ultrafilter. -/ protected noncomputable def decidable_linear_ordered_add_comm_group [decidable_linear_ordered_add_comm_group β] (U : is_ultrafilter φ) : decidable_linear_ordered_add_comm_group β* := { ..filter_product.ordered_add_comm_group, ..filter_product.decidable_linear_order U } /-- If `φ` is an ultrafilter then the ultraproduct is a decidable linear ordered commutative ring. This cannot be an instance, since it depends on `φ` being an ultrafilter. -/ protected noncomputable def decidable_linear_ordered_comm_ring [decidable_linear_ordered_comm_ring β] (U : is_ultrafilter φ) : decidable_linear_ordered_comm_ring β* := { ..filter_product.linear_ordered_comm_ring U, ..filter_product.decidable_linear_ordered_add_comm_group U } /-- If `φ` is an ultrafilter then the ultraproduct is a discrete linear ordered field. This cannot be an instance, since it depends on `φ` being an ultrafilter. -/ protected noncomputable def discrete_linear_ordered_field [discrete_linear_ordered_field β] (U : is_ultrafilter φ) : discrete_linear_ordered_field β* := { ..filter_product.linear_ordered_field U, ..filter_product.decidable_linear_ordered_comm_ring U, ..filter_product.field U } instance ordered_cancel_comm_monoid [ordered_cancel_add_comm_monoid β] : ordered_cancel_add_comm_monoid β* := { add_le_add_left := λ x y hxy z, by revert hxy; exact quotient.induction_on₃' x y z (λ a b c hab, by filter_upwards [hab] λ i hi, by simpa), le_of_add_le_add_left := λ x y z, quotient.induction_on₃' x y z $ λ x y z h, by filter_upwards [h] λ i, le_of_add_le_add_left, ..filter_product.add_comm_monoid, ..filter_product.add_left_cancel_semigroup, ..filter_product.add_right_cancel_semigroup, ..filter_product.partial_order } lemma max_def [K : decidable_linear_order β] (U : is_ultrafilter φ) (x y : β*) : @max β* (filter_product.decidable_linear_order U) x y = (lift₂ max) x y := quotient.induction_on₂' x y $ λ a b, by unfold max; begin split_ifs, exact quotient.sound'(by filter_upwards [h] λ i hi, (max_eq_right hi).symm), exact quotient.sound'(by filter_upwards [@le_of_not_le _ (filter_product.linear_order U) _ _ h] λ i hi, (max_eq_left hi).symm), end lemma min_def [K : decidable_linear_order β] (U : is_ultrafilter φ) (x y : β*) : @min β* (filter_product.decidable_linear_order U) x y = (lift₂ min) x y := quotient.induction_on₂' x y $ λ a b, by unfold min; begin split_ifs, exact quotient.sound'(by filter_upwards [h] λ i hi, (min_eq_left hi).symm), exact quotient.sound'(by filter_upwards [@le_of_not_le _ (filter_product.linear_order U) _ _ h] λ i hi, (min_eq_right hi).symm), end lemma abs_def [decidable_linear_ordered_add_comm_group β] (U : is_ultrafilter φ) (x : β*) : @abs _ (filter_product.decidable_linear_ordered_add_comm_group U) x = (lift abs) x := quotient.induction_on' x $ λ a, by unfold abs; rw max_def; exact quotient.sound' (show ∀* i, abs _ = _, by simp) @[simp] lemma of_max [decidable_linear_order β] (U : is_ultrafilter φ) (x y : β) : ((max x y : β) : β*) = @max _ (filter_product.decidable_linear_order U) (x : β*) y := begin unfold max, split_ifs, { refl }, { exact false.elim (h_1 (of_le_of_le h)) }, { exact false.elim (h ((of_le U.1).mpr h_1)) }, { refl } end @[simp] lemma of_min [decidable_linear_order β] (U : is_ultrafilter φ) (x y : β) : ((min x y : β) : β*) = @min _ (filter_product.decidable_linear_order U) (x : β*) y := begin unfold min, split_ifs, { refl }, { exact false.elim (h_1 (of_le_of_le h)) }, { exact false.elim (h ((of_le U.1).mpr h_1)) }, { refl } end @[simp] lemma of_abs [decidable_linear_ordered_add_comm_group β] (U : is_ultrafilter φ) (x : β) : ((abs x : β) : β*) = @abs _ (filter_product.decidable_linear_ordered_add_comm_group U) (x : β*) := of_max U x (-x) end filter_product end filter
8cb02a9b11eff96f993e508113fb0d3b3af80551
9dc8cecdf3c4634764a18254e94d43da07142918
/src/group_theory/subsemigroup/operations.lean
db85872d922edb46c164d9f9f9d172e2fd2f8f3e
[ "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
28,686
lean
/- Copyright (c) 2022 Yakov Pechersky. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Kenny Lau, Johan Commelin, Mario Carneiro, Kevin Buzzard, Amelia Livingston, Yury Kudryashov, Yakov Pechersky, Jireh Loreaux -/ import group_theory.subsemigroup.basic /-! # Operations on `subsemigroup`s In this file we define various operations on `subsemigroup`s and `mul_hom`s. ## Main definitions ### Conversion between multiplicative and additive definitions * `subsemigroup.to_add_subsemigroup`, `subsemigroup.to_add_subsemigroup'`, `add_subsemigroup.to_subsemigroup`, `add_subsemigroup.to_subsemigroup'`: convert between multiplicative and additive subsemigroups of `M`, `multiplicative M`, and `additive M`. These are stated as `order_iso`s. ### (Commutative) semigroup structure on a subsemigroup * `subsemigroup.to_semigroup`, `subsemigroup.to_comm_semigroup`: a subsemigroup inherits a (commutative) semigroup structure. ### Operations on subsemigroups * `subsemigroup.comap`: preimage of a subsemigroup under a semigroup homomorphism as a subsemigroup of the domain; * `subsemigroup.map`: image of a subsemigroup under a semigroup homomorphism as a subsemigroup of the codomain; * `subsemigroup.prod`: product of two subsemigroups `s : subsemigroup M` and `t : subsemigroup N` as a subsemigroup of `M × N`; ### Semigroup homomorphisms between subsemigroups * `subsemigroup.subtype`: embedding of a subsemigroup into the ambient semigroup. * `subsemigroup.inclusion`: given two subsemigroups `S`, `T` such that `S ≤ T`, `S.inclusion T` is the inclusion of `S` into `T` as a semigroup homomorphism; * `mul_equiv.subsemigroup_congr`: converts a proof of `S = T` into a semigroup isomorphism between `S` and `T`. * `subsemigroup.prod_equiv`: semigroup isomorphism between `s.prod t` and `s × t`; ### Operations on `mul_hom`s * `mul_hom.srange`: range of a semigroup homomorphism as a subsemigroup of the codomain; * `mul_hom.restrict`: restrict a semigroup homomorphism to a subsemigroup; * `mul_hom.cod_restrict`: restrict the codomain of a semigroup homomorphism to a subsemigroup; * `mul_hom.srange_restrict`: restrict a semigroup homomorphism to its range; ### Implementation notes This file follows closely `group_theory/submonoid/operations.lean`, omitting only that which is necessary. ## Tags subsemigroup, range, product, map, comap -/ variables {M N P σ : Type*} /-! ### Conversion to/from `additive`/`multiplicative` -/ section variables [has_mul M] /-- Subsemigroups of semigroup `M` are isomorphic to additive subsemigroups of `additive M`. -/ @[simps] def subsemigroup.to_add_subsemigroup : subsemigroup M ≃o add_subsemigroup (additive M) := { to_fun := λ S, { carrier := additive.to_mul ⁻¹' S, add_mem' := λ _ _, S.mul_mem' }, inv_fun := λ S, { carrier := additive.of_mul ⁻¹' S, mul_mem' := λ _ _, S.add_mem' }, left_inv := λ x, by cases x; refl, right_inv := λ x, by cases x; refl, map_rel_iff' := λ a b, iff.rfl, } /-- Additive subsemigroups of an additive semigroup `additive M` are isomorphic to subsemigroups of `M`. -/ abbreviation add_subsemigroup.to_subsemigroup' : add_subsemigroup (additive M) ≃o subsemigroup M := subsemigroup.to_add_subsemigroup.symm lemma subsemigroup.to_add_subsemigroup_closure (S : set M) : (subsemigroup.closure S).to_add_subsemigroup = add_subsemigroup.closure (additive.to_mul ⁻¹' S) := le_antisymm (subsemigroup.to_add_subsemigroup.le_symm_apply.1 $ subsemigroup.closure_le.2 add_subsemigroup.subset_closure) (add_subsemigroup.closure_le.2 subsemigroup.subset_closure) lemma add_subsemigroup.to_subsemigroup'_closure (S : set (additive M)) : (add_subsemigroup.closure S).to_subsemigroup' = subsemigroup.closure (multiplicative.of_add ⁻¹' S) := le_antisymm (add_subsemigroup.to_subsemigroup'.le_symm_apply.1 $ add_subsemigroup.closure_le.2 subsemigroup.subset_closure) (subsemigroup.closure_le.2 add_subsemigroup.subset_closure) end section variables {A : Type*} [has_add A] /-- Additive subsemigroups of an additive semigroup `A` are isomorphic to multiplicative subsemigroups of `multiplicative A`. -/ @[simps] def add_subsemigroup.to_subsemigroup : add_subsemigroup A ≃o subsemigroup (multiplicative A) := { to_fun := λ S, { carrier := multiplicative.to_add ⁻¹' S, mul_mem' := λ _ _, S.add_mem' }, inv_fun := λ S, { carrier := multiplicative.of_add ⁻¹' S, add_mem' := λ _ _, S.mul_mem' }, left_inv := λ x, by cases x; refl, right_inv := λ x, by cases x; refl, map_rel_iff' := λ a b, iff.rfl, } /-- Subsemigroups of a semigroup `multiplicative A` are isomorphic to additive subsemigroups of `A`. -/ abbreviation subsemigroup.to_add_subsemigroup' : subsemigroup (multiplicative A) ≃o add_subsemigroup A := add_subsemigroup.to_subsemigroup.symm lemma add_subsemigroup.to_subsemigroup_closure (S : set A) : (add_subsemigroup.closure S).to_subsemigroup = subsemigroup.closure (multiplicative.to_add ⁻¹' S) := le_antisymm (add_subsemigroup.to_subsemigroup.to_galois_connection.l_le $ add_subsemigroup.closure_le.2 subsemigroup.subset_closure) (subsemigroup.closure_le.2 add_subsemigroup.subset_closure) lemma subsemigroup.to_add_subsemigroup'_closure (S : set (multiplicative A)) : (subsemigroup.closure S).to_add_subsemigroup' = add_subsemigroup.closure (additive.of_mul ⁻¹' S) := le_antisymm (subsemigroup.to_add_subsemigroup'.to_galois_connection.l_le $ subsemigroup.closure_le.2 add_subsemigroup.subset_closure) (add_subsemigroup.closure_le.2 subsemigroup.subset_closure) end namespace subsemigroup open set /-! ### `comap` and `map` -/ variables [has_mul M] [has_mul N] [has_mul P] (S : subsemigroup M) /-- The preimage of a subsemigroup along a semigroup homomorphism is a subsemigroup. -/ @[to_additive "The preimage of an `add_subsemigroup` along an `add_semigroup` homomorphism is an `add_subsemigroup`."] def comap (f : M →ₙ* N) (S : subsemigroup N) : subsemigroup M := { carrier := (f ⁻¹' S), mul_mem' := λ a b ha hb, show f (a * b) ∈ S, by rw map_mul; exact mul_mem ha hb } @[simp, to_additive] lemma coe_comap (S : subsemigroup N) (f : M →ₙ* N) : (S.comap f : set M) = f ⁻¹' S := rfl @[simp, to_additive] lemma mem_comap {S : subsemigroup N} {f : M →ₙ* N} {x : M} : x ∈ S.comap f ↔ f x ∈ S := iff.rfl @[to_additive] lemma comap_comap (S : subsemigroup P) (g : N →ₙ* P) (f : M →ₙ* N) : (S.comap g).comap f = S.comap (g.comp f) := rfl @[simp, to_additive] lemma comap_id (S : subsemigroup P) : S.comap (mul_hom.id _) = S := ext (by simp) /-- The image of a subsemigroup along a semigroup homomorphism is a subsemigroup. -/ @[to_additive "The image of an `add_subsemigroup` along an `add_semigroup` homomorphism is an `add_subsemigroup`."] def map (f : M →ₙ* N) (S : subsemigroup M) : subsemigroup N := { carrier := (f '' S), mul_mem' := begin rintros _ _ ⟨x, hx, rfl⟩ ⟨y, hy, rfl⟩, exact ⟨x * y, @mul_mem (subsemigroup M) M _ _ _ _ _ _ hx hy, by rw map_mul; refl⟩ end } @[simp, to_additive] lemma coe_map (f : M →ₙ* N) (S : subsemigroup M) : (S.map f : set N) = f '' S := rfl @[simp, to_additive] lemma mem_map {f : M →ₙ* N} {S : subsemigroup M} {y : N} : y ∈ S.map f ↔ ∃ x ∈ S, f x = y := mem_image_iff_bex @[to_additive] lemma mem_map_of_mem (f : M →ₙ* N) {S : subsemigroup M} {x : M} (hx : x ∈ S) : f x ∈ S.map f := mem_image_of_mem f hx @[to_additive] lemma apply_coe_mem_map (f : M →ₙ* N) (S : subsemigroup M) (x : S) : f x ∈ S.map f := mem_map_of_mem f x.prop @[to_additive] lemma map_map (g : N →ₙ* P) (f : M →ₙ* N) : (S.map f).map g = S.map (g.comp f) := set_like.coe_injective $ image_image _ _ _ @[to_additive] lemma mem_map_iff_mem {f : M →ₙ* N} (hf : function.injective f) {S : subsemigroup M} {x : M} : f x ∈ S.map f ↔ x ∈ S := hf.mem_set_image @[to_additive] lemma map_le_iff_le_comap {f : M →ₙ* N} {S : subsemigroup M} {T : subsemigroup N} : S.map f ≤ T ↔ S ≤ T.comap f := image_subset_iff @[to_additive] lemma gc_map_comap (f : M →ₙ* N) : galois_connection (map f) (comap f) := λ S T, map_le_iff_le_comap @[to_additive] lemma map_le_of_le_comap {T : subsemigroup N} {f : M →ₙ* N} : S ≤ T.comap f → S.map f ≤ T := (gc_map_comap f).l_le @[to_additive] lemma le_comap_of_map_le {T : subsemigroup N} {f : M →ₙ* N} : S.map f ≤ T → S ≤ T.comap f := (gc_map_comap f).le_u @[to_additive] lemma le_comap_map {f : M →ₙ* N} : S ≤ (S.map f).comap f := (gc_map_comap f).le_u_l _ @[to_additive] lemma map_comap_le {S : subsemigroup N} {f : M →ₙ* N} : (S.comap f).map f ≤ S := (gc_map_comap f).l_u_le _ @[to_additive] lemma monotone_map {f : M →ₙ* N} : monotone (map f) := (gc_map_comap f).monotone_l @[to_additive] lemma monotone_comap {f : M →ₙ* N} : monotone (comap f) := (gc_map_comap f).monotone_u @[simp, to_additive] lemma map_comap_map {f : M →ₙ* N} : ((S.map f).comap f).map f = S.map f := (gc_map_comap f).l_u_l_eq_l _ @[simp, to_additive] lemma comap_map_comap {S : subsemigroup N} {f : M →ₙ* N} : ((S.comap f).map f).comap f = S.comap f := (gc_map_comap f).u_l_u_eq_u _ @[to_additive] lemma map_sup (S T : subsemigroup M) (f : M →ₙ* N) : (S ⊔ T).map f = S.map f ⊔ T.map f := (gc_map_comap f).l_sup @[to_additive] lemma map_supr {ι : Sort*} (f : M →ₙ* N) (s : ι → subsemigroup M) : (supr s).map f = ⨆ i, (s i).map f := (gc_map_comap f).l_supr @[to_additive] lemma comap_inf (S T : subsemigroup N) (f : M →ₙ* N) : (S ⊓ T).comap f = S.comap f ⊓ T.comap f := (gc_map_comap f).u_inf @[to_additive] lemma comap_infi {ι : Sort*} (f : M →ₙ* N) (s : ι → subsemigroup N) : (infi s).comap f = ⨅ i, (s i).comap f := (gc_map_comap f).u_infi @[simp, to_additive] lemma map_bot (f : M →ₙ* N) : (⊥ : subsemigroup M).map f = ⊥ := (gc_map_comap f).l_bot @[simp, to_additive] lemma comap_top (f : M →ₙ* N) : (⊤ : subsemigroup N).comap f = ⊤ := (gc_map_comap f).u_top @[simp, to_additive] lemma map_id (S : subsemigroup M) : S.map (mul_hom.id M) = S := ext (λ x, ⟨λ ⟨_, h, rfl⟩, h, λ h, ⟨_, h, rfl⟩⟩) section galois_coinsertion variables {ι : Type*} {f : M →ₙ* N} (hf : function.injective f) include hf /-- `map f` and `comap f` form a `galois_coinsertion` when `f` is injective. -/ @[to_additive /-" `map f` and `comap f` form a `galois_coinsertion` when `f` is injective. "-/] def gci_map_comap : galois_coinsertion (map f) (comap f) := (gc_map_comap f).to_galois_coinsertion (λ S x, by simp [mem_comap, mem_map, hf.eq_iff]) @[to_additive] lemma comap_map_eq_of_injective (S : subsemigroup M) : (S.map f).comap f = S := (gci_map_comap hf).u_l_eq _ @[to_additive] lemma comap_surjective_of_injective : function.surjective (comap f) := (gci_map_comap hf).u_surjective @[to_additive] lemma map_injective_of_injective : function.injective (map f) := (gci_map_comap hf).l_injective @[to_additive] lemma comap_inf_map_of_injective (S T : subsemigroup M) : (S.map f ⊓ T.map f).comap f = S ⊓ T := (gci_map_comap hf).u_inf_l _ _ @[to_additive] lemma comap_infi_map_of_injective (S : ι → subsemigroup M) : (⨅ i, (S i).map f).comap f = infi S := (gci_map_comap hf).u_infi_l _ @[to_additive] lemma comap_sup_map_of_injective (S T : subsemigroup M) : (S.map f ⊔ T.map f).comap f = S ⊔ T := (gci_map_comap hf).u_sup_l _ _ @[to_additive] lemma comap_supr_map_of_injective (S : ι → subsemigroup M) : (⨆ i, (S i).map f).comap f = supr S := (gci_map_comap hf).u_supr_l _ @[to_additive] lemma map_le_map_iff_of_injective {S T : subsemigroup M} : S.map f ≤ T.map f ↔ S ≤ T := (gci_map_comap hf).l_le_l_iff @[to_additive] lemma map_strict_mono_of_injective : strict_mono (map f) := (gci_map_comap hf).strict_mono_l end galois_coinsertion section galois_insertion variables {ι : Type*} {f : M →ₙ* N} (hf : function.surjective f) include hf /-- `map f` and `comap f` form a `galois_insertion` when `f` is surjective. -/ @[to_additive /-" `map f` and `comap f` form a `galois_insertion` when `f` is surjective. "-/] def gi_map_comap : galois_insertion (map f) (comap f) := (gc_map_comap f).to_galois_insertion (λ S x h, let ⟨y, hy⟩ := hf x in mem_map.2 ⟨y, by simp [hy, h]⟩) @[to_additive] lemma map_comap_eq_of_surjective (S : subsemigroup N) : (S.comap f).map f = S := (gi_map_comap hf).l_u_eq _ @[to_additive] lemma map_surjective_of_surjective : function.surjective (map f) := (gi_map_comap hf).l_surjective @[to_additive] lemma comap_injective_of_surjective : function.injective (comap f) := (gi_map_comap hf).u_injective @[to_additive] lemma map_inf_comap_of_surjective (S T : subsemigroup N) : (S.comap f ⊓ T.comap f).map f = S ⊓ T := (gi_map_comap hf).l_inf_u _ _ @[to_additive] lemma map_infi_comap_of_surjective (S : ι → subsemigroup N) : (⨅ i, (S i).comap f).map f = infi S := (gi_map_comap hf).l_infi_u _ @[to_additive] lemma map_sup_comap_of_surjective (S T : subsemigroup N) : (S.comap f ⊔ T.comap f).map f = S ⊔ T := (gi_map_comap hf).l_sup_u _ _ @[to_additive] lemma map_supr_comap_of_surjective (S : ι → subsemigroup N) : (⨆ i, (S i).comap f).map f = supr S := (gi_map_comap hf).l_supr_u _ @[to_additive] lemma comap_le_comap_iff_of_surjective {S T : subsemigroup N} : S.comap f ≤ T.comap f ↔ S ≤ T := (gi_map_comap hf).u_le_u_iff @[to_additive] lemma comap_strict_mono_of_surjective : strict_mono (comap f) := (gi_map_comap hf).strict_mono_u end galois_insertion end subsemigroup namespace mul_mem_class variables {A : Type*} [has_mul M] [set_like A M] [hA : mul_mem_class A M] (S' : A) include hA /-- A submagma of a magma inherits a multiplication. -/ @[to_additive "An additive submagma of an additive magma inherits an addition.", priority 900] -- lower priority so other instances are found first instance has_mul : has_mul S' := ⟨λ a b, ⟨a.1 * b.1, mul_mem a.2 b.2⟩⟩ @[simp, norm_cast, to_additive, priority 900] -- lower priority so later simp lemmas are used first; to appease simp_nf lemma coe_mul (x y : S') : (↑(x * y) : M) = ↑x * ↑y := rfl @[simp, to_additive, priority 900] -- lower priority so later simp lemmas are used first; to appease simp_nf lemma mk_mul_mk (x y : M) (hx : x ∈ S') (hy : y ∈ S') : (⟨x, hx⟩ : S') * ⟨y, hy⟩ = ⟨x * y, mul_mem hx hy⟩ := rfl @[to_additive] lemma mul_def (x y : S') : x * y = ⟨x * y, mul_mem x.2 y.2⟩ := rfl omit hA /-- A subsemigroup of a semigroup inherits a semigroup structure. -/ @[to_additive "An `add_subsemigroup` of an `add_semigroup` inherits an `add_semigroup` structure."] instance to_semigroup {M : Type*} [semigroup M] {A : Type*} [set_like A M] [mul_mem_class A M] (S : A) : semigroup S := subtype.coe_injective.semigroup coe (λ _ _, rfl) /-- A subsemigroup of a `comm_semigroup` is a `comm_semigroup`. -/ @[to_additive "An `add_subsemigroup` of an `add_comm_semigroup` is an `add_comm_semigroup`."] instance to_comm_semigroup {M} [comm_semigroup M] {A : Type*} [set_like A M] [mul_mem_class A M] (S : A) : comm_semigroup S := subtype.coe_injective.comm_semigroup coe (λ _ _, rfl) include hA /-- The natural semigroup hom from a subsemigroup of semigroup `M` to `M`. -/ @[to_additive "The natural semigroup hom from an `add_subsemigroup` of `add_semigroup` `M` to `M`."] def subtype : S' →ₙ* M := ⟨coe, λ _ _, rfl⟩ @[simp, to_additive] theorem coe_subtype : (mul_mem_class.subtype S' : S' → M) = coe := rfl end mul_mem_class namespace subsemigroup variables [has_mul M] [has_mul N] [has_mul P] (S : subsemigroup M) /-- The top subsemigroup is isomorphic to the semigroup. -/ @[to_additive "The top additive subsemigroup is isomorphic to the additive semigroup.", simps] def top_equiv : (⊤ : subsemigroup M) ≃* M := { to_fun := λ x, x, inv_fun := λ x, ⟨x, mem_top x⟩, left_inv := λ x, x.eta _, right_inv := λ _, rfl, map_mul' := λ _ _, rfl } @[simp, to_additive] lemma top_equiv_to_mul_hom : (top_equiv : _ ≃* M).to_mul_hom = mul_mem_class.subtype (⊤ : subsemigroup M) := rfl /-- A subsemigroup is isomorphic to its image under an injective function -/ @[to_additive "An additive subsemigroup is isomorphic to its image under an injective function"] noncomputable def equiv_map_of_injective (f : M →ₙ* N) (hf : function.injective f) : S ≃* S.map f := { map_mul' := λ _ _, subtype.ext (map_mul f _ _), ..equiv.set.image f S hf } @[simp, to_additive] lemma coe_equiv_map_of_injective_apply (f : M →ₙ* N) (hf : function.injective f) (x : S) : (equiv_map_of_injective S f hf x : N) = f x := rfl @[simp, to_additive] lemma closure_closure_coe_preimage {s : set M} : closure ((coe : closure s → M) ⁻¹' s) = ⊤ := eq_top_iff.2 $ λ x, subtype.rec_on x $ λ x hx _, begin refine closure_induction' _ (λ g hg, _) (λ g₁ g₂ hg₁ hg₂, _) hx, { exact subset_closure hg }, { exact subsemigroup.mul_mem _ }, end /-- Given `subsemigroup`s `s`, `t` of semigroups `M`, `N` respectively, `s × t` as a subsemigroup of `M × N`. -/ @[to_additive prod "Given `add_subsemigroup`s `s`, `t` of `add_semigroup`s `A`, `B` respectively, `s × t` as an `add_subsemigroup` of `A × B`."] def prod (s : subsemigroup M) (t : subsemigroup N) : subsemigroup (M × N) := { carrier := s ×ˢ t, mul_mem' := λ p q hp hq, ⟨s.mul_mem hp.1 hq.1, t.mul_mem hp.2 hq.2⟩ } @[to_additive coe_prod] lemma coe_prod (s : subsemigroup M) (t : subsemigroup N) : (s.prod t : set (M × N)) = s ×ˢ t := rfl @[to_additive mem_prod] lemma mem_prod {s : subsemigroup M} {t : subsemigroup N} {p : M × N} : p ∈ s.prod t ↔ p.1 ∈ s ∧ p.2 ∈ t := iff.rfl @[to_additive prod_mono] lemma prod_mono {s₁ s₂ : subsemigroup M} {t₁ t₂ : subsemigroup N} (hs : s₁ ≤ s₂) (ht : t₁ ≤ t₂) : s₁.prod t₁ ≤ s₂.prod t₂ := set.prod_mono hs ht @[to_additive prod_top] lemma prod_top (s : subsemigroup M) : s.prod (⊤ : subsemigroup N) = s.comap (mul_hom.fst M N) := ext $ λ x, by simp [mem_prod, mul_hom.coe_fst] @[to_additive top_prod] lemma top_prod (s : subsemigroup N) : (⊤ : subsemigroup M).prod s = s.comap (mul_hom.snd M N) := ext $ λ x, by simp [mem_prod, mul_hom.coe_snd] @[simp, to_additive top_prod_top] lemma top_prod_top : (⊤ : subsemigroup M).prod (⊤ : subsemigroup N) = ⊤ := (top_prod _).trans $ comap_top _ @[to_additive] lemma bot_prod_bot : (⊥ : subsemigroup M).prod (⊥ : subsemigroup N) = ⊥ := set_like.coe_injective $ by simp [coe_prod, prod.one_eq_mk] /-- The product of subsemigroups is isomorphic to their product as semigroups. -/ @[to_additive prod_equiv "The product of additive subsemigroups is isomorphic to their product as additive semigroups"] def prod_equiv (s : subsemigroup M) (t : subsemigroup N) : s.prod t ≃* s × t := { map_mul' := λ x y, rfl, .. equiv.set.prod ↑s ↑t } open mul_hom @[to_additive] lemma mem_map_equiv {f : M ≃* N} {K : subsemigroup M} {x : N} : x ∈ K.map f.to_mul_hom ↔ f.symm x ∈ K := @set.mem_image_equiv _ _ ↑K f.to_equiv x @[to_additive] lemma map_equiv_eq_comap_symm (f : M ≃* N) (K : subsemigroup M) : K.map f.to_mul_hom = K.comap f.symm.to_mul_hom := set_like.coe_injective (f.to_equiv.image_eq_preimage K) @[to_additive] lemma comap_equiv_eq_map_symm (f : N ≃* M) (K : subsemigroup M) : K.comap f.to_mul_hom = K.map f.symm.to_mul_hom := (map_equiv_eq_comap_symm f.symm K).symm @[simp, to_additive] lemma map_equiv_top (f : M ≃* N) : (⊤ : subsemigroup M).map f.to_mul_hom = ⊤ := set_like.coe_injective $ set.image_univ.trans f.surjective.range_eq @[to_additive le_prod_iff] lemma le_prod_iff {s : subsemigroup M} {t : subsemigroup N} {u : subsemigroup (M × N)} : u ≤ s.prod t ↔ u.map (fst M N) ≤ s ∧ u.map (snd M N) ≤ t := begin split, { intros h, split, { rintros x ⟨⟨y1,y2⟩, ⟨hy1,rfl⟩⟩, exact (h hy1).1 }, { rintros x ⟨⟨y1,y2⟩, ⟨hy1,rfl⟩⟩, exact (h hy1).2 }, }, { rintros ⟨hH, hK⟩ ⟨x1, x2⟩ h, exact ⟨hH ⟨_ , h, rfl⟩, hK ⟨ _, h, rfl⟩⟩, } end end subsemigroup namespace mul_hom open subsemigroup variables [has_mul M] [has_mul N] [has_mul P] (S : subsemigroup M) /-- The range of a semigroup homomorphism is a subsemigroup. See Note [range copy pattern]. -/ @[to_additive "The range of an `add_hom` is an `add_subsemigroup`."] def srange (f : M →ₙ* N) : subsemigroup N := ((⊤ : subsemigroup M).map f).copy (set.range f) set.image_univ.symm @[simp, to_additive] lemma coe_srange (f : M →ₙ* N) : (f.srange : set N) = set.range f := rfl @[simp, to_additive] lemma mem_srange {f : M →ₙ* N} {y : N} : y ∈ f.srange ↔ ∃ x, f x = y := iff.rfl @[to_additive] lemma srange_eq_map (f : M →ₙ* N) : f.srange = (⊤ : subsemigroup M).map f := copy_eq _ @[to_additive] lemma map_srange (g : N →ₙ* P) (f : M →ₙ* N) : f.srange.map g = (g.comp f).srange := by simpa only [srange_eq_map] using (⊤ : subsemigroup M).map_map g f @[to_additive] lemma srange_top_iff_surjective {N} [has_mul N] {f : M →ₙ* N} : f.srange = (⊤ : subsemigroup N) ↔ function.surjective f := set_like.ext'_iff.trans $ iff.trans (by rw [coe_srange, coe_top]) set.range_iff_surjective /-- The range of a surjective semigroup hom is the whole of the codomain. -/ @[to_additive "The range of a surjective `add_semigroup` hom is the whole of the codomain."] lemma srange_top_of_surjective {N} [has_mul N] (f : M →ₙ* N) (hf : function.surjective f) : f.srange = (⊤ : subsemigroup N) := srange_top_iff_surjective.2 hf @[to_additive] lemma mclosure_preimage_le (f : M →ₙ* N) (s : set N) : closure (f ⁻¹' s) ≤ (closure s).comap f := closure_le.2 $ λ x hx, set_like.mem_coe.2 $ mem_comap.2 $ subset_closure hx /-- The image under a semigroup hom of the subsemigroup generated by a set equals the subsemigroup generated by the image of the set. -/ @[to_additive "The image under an `add_semigroup` hom of the `add_subsemigroup` generated by a set equals the `add_subsemigroup` generated by the image of the set."] lemma map_mclosure (f : M →ₙ* N) (s : set M) : (closure s).map f = closure (f '' s) := le_antisymm (map_le_iff_le_comap.2 $ le_trans (closure_mono $ set.subset_preimage_image _ _) (mclosure_preimage_le _ _)) (closure_le.2 $ set.image_subset _ subset_closure) /-- Restriction of a semigroup hom to a subsemigroup of the domain. -/ @[to_additive "Restriction of an add_semigroup hom to an `add_subsemigroup` of the domain."] def restrict {N : Type*} [has_mul N] [set_like σ M] [mul_mem_class σ M] (f : M →ₙ* N) (S : σ) : S →ₙ* N := f.comp (mul_mem_class.subtype S) @[simp, to_additive] lemma restrict_apply {N : Type*} [has_mul N] [set_like σ M] [mul_mem_class σ M] (f : M →ₙ* N) {S : σ} (x : S) : f.restrict S x = f x := rfl /-- Restriction of a semigroup hom to a subsemigroup of the codomain. -/ @[to_additive "Restriction of an `add_semigroup` hom to an `add_subsemigroup` of the codomain.", simps] def cod_restrict [set_like σ N] [mul_mem_class σ N] (f : M →ₙ* N) (S : σ) (h : ∀ x, f x ∈ S) : M →ₙ* S := { to_fun := λ n, ⟨f n, h n⟩, map_mul' := λ x y, subtype.eq (map_mul f x y) } /-- Restriction of a semigroup hom to its range interpreted as a subsemigroup. -/ @[to_additive "Restriction of an `add_semigroup` hom to its range interpreted as a subsemigroup."] def srange_restrict {N} [has_mul N] (f : M →ₙ* N) : M →ₙ* f.srange := f.cod_restrict f.srange $ λ x, ⟨x, rfl⟩ @[simp, to_additive] lemma coe_srange_restrict {N} [has_mul N] (f : M →ₙ* N) (x : M) : (f.srange_restrict x : N) = f x := rfl @[to_additive] lemma srange_restrict_surjective (f : M →ₙ* N) : function.surjective f.srange_restrict := λ ⟨_, ⟨x, rfl⟩⟩, ⟨x, rfl⟩ @[to_additive] lemma prod_map_comap_prod' {M' : Type*} {N' : Type*} [has_mul M'] [has_mul N'] (f : M →ₙ* N) (g : M' →ₙ* N') (S : subsemigroup N) (S' : subsemigroup N') : (S.prod S').comap (prod_map f g) = (S.comap f).prod (S'.comap g) := set_like.coe_injective $ set.preimage_prod_map_prod f g _ _ /-- The `mul_hom` from the preimage of a subsemigroup to itself. -/ @[to_additive "the `add_hom` from the preimage of an additive subsemigroup to itself.", simps] def subsemigroup_comap (f : M →ₙ* N) (N' : subsemigroup N) : N'.comap f →ₙ* N' := { to_fun := λ x, ⟨f x, x.prop⟩, map_mul' := λ x y, subtype.eq (@map_mul M N _ _ _ _ f x y) } /-- The `mul_hom` from a subsemigroup to its image. See `mul_equiv.subsemigroup_map` for a variant for `mul_equiv`s. -/ @[to_additive "the `add_hom` from an additive subsemigroup to its image. See `add_equiv.add_subsemigroup_map` for a variant for `add_equiv`s.", simps] def subsemigroup_map (f : M →ₙ* N) (M' : subsemigroup M) : M' →ₙ* M'.map f := { to_fun := λ x, ⟨f x, ⟨x, x.prop, rfl⟩⟩, map_mul' := λ x y, subtype.eq $ @map_mul M N _ _ _ _ f x y } @[to_additive] lemma subsemigroup_map_surjective (f : M →ₙ* N) (M' : subsemigroup M) : function.surjective (f.subsemigroup_map M') := by { rintro ⟨_, x, hx, rfl⟩, exact ⟨⟨x, hx⟩, rfl⟩ } end mul_hom namespace subsemigroup open mul_hom variables [has_mul M] [has_mul N] [has_mul P] (S : subsemigroup M) @[simp, to_additive] lemma srange_fst [nonempty N] : (fst M N).srange = ⊤ := (fst M N).srange_top_of_surjective $ prod.fst_surjective @[simp, to_additive] lemma srange_snd [nonempty M] : (snd M N).srange = ⊤ := (snd M N).srange_top_of_surjective $ prod.snd_surjective @[to_additive] lemma prod_eq_top_iff [nonempty M] [nonempty N] {s : subsemigroup M} {t : subsemigroup N} : s.prod t = ⊤ ↔ s = ⊤ ∧ t = ⊤ := by simp only [eq_top_iff, le_prod_iff, ← (gc_map_comap _).le_iff_le, ← srange_eq_map, srange_fst, srange_snd] /-- The semigroup hom associated to an inclusion of subsemigroups. -/ @[to_additive "The `add_semigroup` hom associated to an inclusion of subsemigroups."] def inclusion {S T : subsemigroup M} (h : S ≤ T) : S →ₙ* T := (mul_mem_class.subtype S).cod_restrict _ (λ x, h x.2) @[simp, to_additive] lemma range_subtype (s : subsemigroup M) : (mul_mem_class.subtype s).srange = s := set_like.coe_injective $ (coe_srange _).trans $ subtype.range_coe @[to_additive] lemma eq_top_iff' : S = ⊤ ↔ ∀ x : M, x ∈ S := eq_top_iff.trans ⟨λ h m, h $ mem_top m, λ h m _, h m⟩ end subsemigroup namespace mul_equiv variables [has_mul M] [has_mul N] {S T : subsemigroup M} /-- Makes the identity isomorphism from a proof that two subsemigroups of a multiplicative semigroup are equal. -/ @[to_additive "Makes the identity additive isomorphism from a proof two subsemigroups of an additive semigroup are equal."] def subsemigroup_congr (h : S = T) : S ≃* T := { map_mul' := λ _ _, rfl, ..equiv.set_congr $ congr_arg _ h } -- this name is primed so that the version to `f.range` instead of `f.srange` can be unprimed. /-- A semigroup homomorphism `f : M →ₙ* N` with a left-inverse `g : N → M` defines a multiplicative equivalence between `M` and `f.srange`. This is a bidirectional version of `mul_hom.srange_restrict`. -/ @[to_additive /-" An additive semigroup homomorphism `f : M →+ N` with a left-inverse `g : N → M` defines an additive equivalence between `M` and `f.srange`. This is a bidirectional version of `add_hom.srange_restrict`. "-/, simps {simp_rhs := tt}] def of_left_inverse (f : M →ₙ* N) {g : N → M} (h : function.left_inverse g f) : M ≃* f.srange := { to_fun := f.srange_restrict, inv_fun := g ∘ (mul_mem_class.subtype f.srange), left_inv := h, right_inv := λ x, subtype.ext $ let ⟨x', hx'⟩ := mul_hom.mem_srange.mp x.prop in show f (g x) = x, by rw [←hx', h x'], .. f.srange_restrict } /-- A `mul_equiv` `φ` between two semigroups `M` and `N` induces a `mul_equiv` between a subsemigroup `S ≤ M` and the subsemigroup `φ(S) ≤ N`. See `mul_hom.subsemigroup_map` for a variant for `mul_hom`s. -/ @[to_additive "An `add_equiv` `φ` between two additive semigroups `M` and `N` induces an `add_equiv` between a subsemigroup `S ≤ M` and the subsemigroup `φ(S) ≤ N`. See `add_hom.add_subsemigroup_map` for a variant for `add_hom`s.", simps] def subsemigroup_map (e : M ≃* N) (S : subsemigroup M) : S ≃* S.map e.to_mul_hom := { to_fun := λ x, ⟨e x, _⟩, inv_fun := λ x, ⟨e.symm x, _⟩, -- we restate this for `simps` to avoid `⇑e.symm.to_equiv x` ..e.to_mul_hom.subsemigroup_map S, ..e.to_equiv.image S } end mul_equiv
6bb4e13d2ab69806cce54d1f9bf641aa5b502b20
32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7
/stage0/src/Lean/Meta/Tactic/Subst.lean
de015333dc6f2d79d3f365375d2ccbf06af4828f
[ "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
6,176
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.Meta.AppBuilder import Lean.Meta.Tactic.Util import Lean.Meta.Tactic.Revert import Lean.Meta.Tactic.Intro import Lean.Meta.Tactic.Clear import Lean.Meta.Tactic.FVarSubst namespace Lean namespace Meta def substCore (mvarId : MVarId) (hFVarId : FVarId) (symm := false) (fvarSubst : FVarSubst := {}) (clearH := true) : MetaM (FVarSubst × MVarId) := withMVarContext mvarId $ do tag ← getMVarTag mvarId; checkNotAssigned mvarId `subst; hLocalDecl ← getLocalDecl hFVarId; let hFVarIdOriginal := hFVarId; match hLocalDecl.type.eq? with | none => throwTacticEx `subst mvarId "argument must be an equality proof" | some (α, lhs, rhs) => do let a := if symm then rhs else lhs; let b := if symm then lhs else rhs; a ← whnf a; match a with | Expr.fvar aFVarId _ => do let aFVarIdOriginal := aFVarId; trace! `Meta.Tactic.subst ("substituting " ++ a ++ " (id: " ++ aFVarId ++ ") with " ++ b); mctx ← getMCtx; when (mctx.exprDependsOn b aFVarId) $ throwTacticEx `subst mvarId ("'" ++ a ++ "' occurs at" ++ indentExpr b); aLocalDecl ← getLocalDecl aFVarId; (vars, mvarId) ← revert mvarId #[aFVarId, hFVarId] true; (twoVars, mvarId) ← introN mvarId 2 [] false; trace! `Meta.Tactic.subst ("reverted variables " ++ toString vars); let aFVarId := twoVars.get! 0; let a := mkFVar aFVarId; let hFVarId := twoVars.get! 1; let h := mkFVar hFVarId; withMVarContext mvarId $ do mvarDecl ← getMVarDecl mvarId; let type := mvarDecl.type; hLocalDecl ← getLocalDecl hFVarId; match hLocalDecl.type.eq? with | none => unreachable! | some (α, lhs, rhs) => do let b := if symm then lhs else rhs; mctx ← getMCtx; let depElim := mctx.exprDependsOn mvarDecl.type hFVarId; let continue (motive : Expr) (newType : Expr) : MetaM (FVarSubst × MVarId) := do { major ← if symm then pure h else mkEqSymm h; newMVar ← mkFreshExprSyntheticOpaqueMVar newType tag; let minor := newMVar; newVal ← if depElim then mkEqRec motive minor major else mkEqNDRec motive minor major; assignExprMVar mvarId newVal; let mvarId := newMVar.mvarId!; mvarId ← if clearH then do mvarId ← clear mvarId hFVarId; clear mvarId aFVarId else pure mvarId; (newFVars, mvarId) ← introN mvarId (vars.size - 2) [] false; fvarSubst ← newFVars.size.foldM (fun i (fvarSubst : FVarSubst) => let var := vars.get! (i+2); let newFVar := newFVars.get! i; pure $ fvarSubst.insert var (mkFVar newFVar)) fvarSubst; let fvarSubst := fvarSubst.insert aFVarIdOriginal (if clearH then b else mkFVar aFVarId); let fvarSubst := fvarSubst.insert hFVarIdOriginal (mkFVar hFVarId); pure (fvarSubst, mvarId) }; if depElim then do let newType := type.replaceFVar a b; reflB ← mkEqRefl b; let newType := newType.replaceFVar h reflB; if symm then do motive ← mkLambdaFVars #[a, h] type; continue motive newType else do /- `type` depends on (h : a = b). So, we use the following trick to avoid a type incorrect motive. 1- Create a new local (hAux : b = a) 2- Create newType := type [hAux.symm / h] `newType` is type correct because `h` and `hAux.symm` are definitionally equal by proof irrelevance. 3- Create motive by abstracting `a` and `hAux` in `newType`. -/ hAuxType ← mkEq b a; motive ← withLocalDeclD `_h hAuxType $ fun hAux => do { hAuxSymm ← mkEqSymm hAux; /- replace h in type with hAuxSymm -/ let newType := type.replaceFVar h hAuxSymm; mkLambdaFVars #[a, hAux] newType }; continue motive newType else do motive ← mkLambdaFVars #[a] type; let newType := type.replaceFVar a b; continue motive newType | _ => throwTacticEx `subst mvarId $ "invalid equality proof, it is not of the form " ++ (if symm then "(t = x)" else "(x = t)") ++ indentExpr hLocalDecl.type ++ Format.line ++ "after WHNF, variable expected, but obtained" ++ indentExpr a def subst (mvarId : MVarId) (hFVarId : FVarId) : MetaM MVarId := withMVarContext mvarId $ do hLocalDecl ← getLocalDecl hFVarId; match hLocalDecl.type.eq? with | some (α, lhs, rhs) => do rhs ← whnf rhs; if rhs.isFVar then Prod.snd <$> substCore mvarId hFVarId true else do lhs ← whnf lhs; if lhs.isFVar then Prod.snd <$> substCore mvarId hFVarId else do throwTacticEx `subst mvarId $ "invalid equality proof, it is not of the form (x = t) or (t = x)" ++ indentExpr hLocalDecl.type | none => do mctx ← getMCtx; lctx ← getLCtx; some (fvarId, symm) ← lctx.findDeclM? (fun localDecl => match localDecl.type.eq? with | some (α, lhs, rhs) => if rhs.isFVar && rhs.fvarId! == hFVarId && !mctx.exprDependsOn lhs hFVarId then pure $ some (localDecl.fvarId, true) else if lhs.isFVar && lhs.fvarId! == hFVarId && !mctx.exprDependsOn rhs hFVarId then pure $ some (localDecl.fvarId, false) else pure none | _ => pure none) | throwTacticEx `subst mvarId ("did not find equation for eliminating '" ++ mkFVar hFVarId ++ "'"); Prod.snd <$> substCore mvarId fvarId symm @[init] private def regTraceClasses : IO Unit := registerTraceClass `Meta.Tactic.subst end Meta end Lean
561779e8a894b62c7460fb65fc582c71bf4951ee
f1b175e38ffc5cc1c7c5551a72d0dbaf70786f83
/analysis/topology/continuity.lean
97d663c007a184016582ee0a805d96124d4f69ec
[ "Apache-2.0" ]
permissive
mjendrusch/mathlib
df3ae884dd5ce38c7edf452bcbfd3baf4e3a6214
5c209edb7eb616a26f64efe3500f2b1ba95b8d55
refs/heads/master
1,585,663,284,800
1,539,062,055,000
1,539,062,055,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
54,093
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 Continuous functions. Parts of the formalization is based on the books: N. Bourbaki: General Topology I. M. James: Topologies and Uniformities A major difference is that this formalization is heavily based on the filter library. -/ import analysis.topology.topological_space noncomputable theory open set filter lattice local attribute [instance] classical.prop_decidable variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} section variables [topological_space α] [topological_space β] [topological_space γ] /-- A function between topological spaces is continuous if the preimage of every open set is open. -/ def continuous (f : α → β) := ∀s, is_open s → is_open (f ⁻¹' s) lemma continuous_id : continuous (id : α → α) := assume s h, h lemma continuous.comp {f : α → β} {g : β → γ} (hf : continuous f) (hg : continuous g): continuous (g ∘ f) := assume s h, hf _ (hg s h) lemma continuous.tendsto {f : α → β} (hf : continuous f) (x) : tendsto f (nhds x) (nhds (f x)) | s := show s ∈ (nhds (f x)).sets → s ∈ (map f (nhds x)).sets, by simp [nhds_sets]; exact assume t t_subset t_open fx_in_t, ⟨f ⁻¹' t, preimage_mono t_subset, hf t t_open, fx_in_t⟩ lemma continuous_iff_tendsto {f : α → β} : continuous f ↔ (∀x, tendsto f (nhds x) (nhds (f x))) := ⟨continuous.tendsto, assume hf : ∀x, tendsto f (nhds x) (nhds (f x)), assume s, assume hs : is_open s, have ∀a, f a ∈ s → s ∈ (nhds (f a)).sets, by simp [nhds_sets]; exact assume a ha, ⟨s, subset.refl s, hs, ha⟩, show is_open (f ⁻¹' s), by simp [is_open_iff_nhds]; exact assume a ha, hf a (this a ha)⟩ lemma continuous_const {b : β} : continuous (λa:α, b) := continuous_iff_tendsto.mpr $ assume a, tendsto_const_nhds lemma continuous_iff_is_closed {f : α → β} : continuous f ↔ (∀s, is_closed s → is_closed (f ⁻¹' s)) := ⟨assume hf s hs, hf (-s) hs, assume hf s, by rw [←is_closed_compl_iff, ←is_closed_compl_iff]; exact hf _⟩ lemma continuous_if {p : α → Prop} {f g : α → β} {h : ∀a, decidable (p a)} (hp : ∀a∈frontier {a | p a}, f a = g a) (hf : continuous f) (hg : continuous g) : continuous (λa, @ite (p a) (h a) β (f a) (g a)) := continuous_iff_is_closed.mpr $ assume s hs, have (λa, ite (p a) (f a) (g a)) ⁻¹' s = (closure {a | p a} ∩ f ⁻¹' s) ∪ (closure {a | ¬ p a} ∩ g ⁻¹' s), from set.ext $ assume a, classical.by_cases (assume : a ∈ frontier {a | p a}, have hac : a ∈ closure {a | p a}, from this.left, have hai : a ∈ closure {a | ¬ p a}, from have a ∈ - interior {a | p a}, from this.right, by rwa [←closure_compl] at this, by by_cases p a; simp [h, hp a this, hac, hai, iff_def] {contextual := tt}) (assume hf : a ∈ - frontier {a | p a}, classical.by_cases (assume : p a, have hc : a ∈ closure {a | p a}, from subset_closure this, have hnc : a ∉ closure {a | ¬ p a}, by show a ∉ closure (- {a | p a}); rw [closure_compl]; simpa [frontier, hc] using hf, by simp [this, hc, hnc]) (assume : ¬ p a, have hc : a ∈ closure {a | ¬ p a}, from subset_closure this, have hnc : a ∉ closure {a | p a}, begin have hc : a ∈ closure (- {a | p a}), from hc, simp [closure_compl] at hc, simpa [frontier, hc] using hf end, by simp [this, hc, hnc])), by rw [this]; exact is_closed_union (is_closed_inter is_closed_closure $ continuous_iff_is_closed.mp hf s hs) (is_closed_inter is_closed_closure $ continuous_iff_is_closed.mp hg s hs) lemma image_closure_subset_closure_image {f : α → β} {s : set α} (h : continuous f) : f '' closure s ⊆ closure (f '' s) := have ∀ (a : α), nhds a ⊓ principal s ≠ ⊥ → nhds (f a) ⊓ principal (f '' s) ≠ ⊥, from assume a ha, have h₁ : ¬ map f (nhds a ⊓ principal s) = ⊥, by rwa[map_eq_bot_iff], have h₂ : map f (nhds a ⊓ principal s) ≤ nhds (f a) ⊓ principal (f '' s), from le_inf (le_trans (map_mono inf_le_left) $ by rw [continuous_iff_tendsto] at h; exact h a) (le_trans (map_mono inf_le_right) $ by simp; exact subset.refl _), neq_bot_of_le_neq_bot h₁ h₂, by simp [image_subset_iff, closure_eq_nhds]; assumption lemma compact_image {s : set α} {f : α → β} (hs : compact s) (hf : continuous f) : compact (f '' s) := compact_of_finite_subcover $ assume c hco hcs, have hdo : ∀t∈c, is_open (f ⁻¹' t), from assume t' ht, hf _ $ hco _ ht, have hds : s ⊆ ⋃i∈c, f ⁻¹' i, by simpa [subset_def, -mem_image] using hcs, let ⟨d', hcd', hfd', hd'⟩ := compact_elim_finite_subcover_image hs hdo hds in ⟨d', hcd', hfd', by simpa [subset_def, -mem_image, image_subset_iff] using hd'⟩ end section constructions local notation `cont` := @continuous _ _ local notation `tspace` := topological_space open topological_space variables {f : α → β} {ι : Sort*} lemma continuous_iff_le_coinduced {t₁ : tspace α} {t₂ : tspace β} : cont t₁ t₂ f ↔ t₂ ≤ coinduced f t₁ := iff.rfl lemma continuous_iff_induced_le {t₁ : tspace α} {t₂ : tspace β} : cont t₁ t₂ f ↔ induced f t₂ ≤ t₁ := iff.trans continuous_iff_le_coinduced (gc_induced_coinduced f _ _).symm theorem continuous_generated_from {t : tspace α} {b : set (set β)} (h : ∀s∈b, is_open (f ⁻¹' s)) : cont t (generate_from b) f := continuous_iff_le_coinduced.2 $ generate_from_le h lemma continuous_induced_dom {t : tspace β} : cont (induced f t) t f := assume s h, ⟨_, h, rfl⟩ lemma continuous_induced_rng {g : γ → α} {t₂ : tspace β} {t₁ : tspace γ} (h : cont t₁ t₂ (f ∘ g)) : cont t₁ (induced f t₂) g := assume s ⟨t, ht, s_eq⟩, s_eq.symm ▸ h t ht lemma continuous_coinduced_rng {t : tspace α} : cont t (coinduced f t) f := assume s h, h lemma continuous_coinduced_dom {g : β → γ} {t₁ : tspace α} {t₂ : tspace γ} (h : cont t₁ t₂ (g ∘ f)) : cont (coinduced f t₁) t₂ g := assume s hs, h s hs lemma continuous_le_dom {t₁ t₂ : tspace α} {t₃ : tspace β} (h₁ : t₁ ≤ t₂) (h₂ : cont t₁ t₃ f) : cont t₂ t₃ f := assume s h, h₁ _ (h₂ s h) lemma continuous_le_rng {t₁ : tspace α} {t₂ t₃ : tspace β} (h₁ : t₃ ≤ t₂) (h₂ : cont t₁ t₂ f) : cont t₁ t₃ f := assume s h, h₂ s (h₁ s h) lemma continuous_inf_dom {t₁ t₂ : tspace α} {t₃ : tspace β} (h₁ : cont t₁ t₃ f) (h₂ : cont t₂ t₃ f) : cont (t₁ ⊓ t₂) t₃ f := assume s h, ⟨h₁ s h, h₂ s h⟩ lemma continuous_inf_rng_left {t₁ : tspace α} {t₃ t₂ : tspace β} : cont t₁ t₂ f → cont t₁ (t₂ ⊓ t₃) f := continuous_le_rng inf_le_left lemma continuous_inf_rng_right {t₁ : tspace α} {t₃ t₂ : tspace β} : cont t₁ t₃ f → cont t₁ (t₂ ⊓ t₃) f := continuous_le_rng inf_le_right lemma continuous_Inf_dom {t₁ : set (tspace α)} {t₂ : tspace β} (h : ∀t∈t₁, cont t t₂ f) : cont (Inf t₁) t₂ f := continuous_iff_induced_le.2 $ le_Inf $ assume t ht, continuous_iff_induced_le.1 $ h t ht lemma continuous_Inf_rng {t₁ : tspace α} {t₂ : set (tspace β)} {t : tspace β} (h₁ : t ∈ t₂) (hf : cont t₁ t f) : cont t₁ (Inf t₂) f := continuous_iff_le_coinduced.2 $ Inf_le_of_le h₁ $ continuous_iff_le_coinduced.1 hf lemma continuous_infi_dom {t₁ : ι → tspace α} {t₂ : tspace β} (h : ∀i, cont (t₁ i) t₂ f) : cont (infi t₁) t₂ f := continuous_Inf_dom $ assume t ⟨i, (t_eq : t = t₁ i)⟩, t_eq.symm ▸ h i lemma continuous_infi_rng {t₁ : tspace α} {t₂ : ι → tspace β} {i : ι} (h : cont t₁ (t₂ i) f) : cont t₁ (infi t₂) f := continuous_Inf_rng ⟨i, rfl⟩ h lemma continuous_sup_rng {t₁ : tspace α} {t₂ t₃ : tspace β} (h₁ : cont t₁ t₂ f) (h₂ : cont t₁ t₃ f) : cont t₁ (t₂ ⊔ t₃) f := continuous_iff_le_coinduced.2 $ sup_le (continuous_iff_le_coinduced.1 h₁) (continuous_iff_le_coinduced.1 h₂) lemma continuous_sup_dom_left {t₁ t₂ : tspace α} {t₃ : tspace β} : cont t₁ t₃ f → cont (t₁ ⊔ t₂) t₃ f := continuous_le_dom le_sup_left lemma continuous_sup_dom_right {t₁ t₂ : tspace α} {t₃ : tspace β} : cont t₂ t₃ f → cont (t₁ ⊔ t₂) t₃ f := continuous_le_dom le_sup_right lemma continuous_Sup_dom {t₁ : set (tspace α)} {t₂ : tspace β} {t : tspace α} (h₁ : t ∈ t₁) : cont t t₂ f → cont (Sup t₁) t₂ f := continuous_le_dom $ le_Sup h₁ lemma continuous_Sup_rng {t₁ : tspace α} {t₂ : set (tspace β)} (h : ∀t∈t₂, cont t₁ t f) : cont t₁ (Sup t₂) f := continuous_iff_le_coinduced.2 $ Sup_le $ assume b hb, continuous_iff_le_coinduced.1 $ h b hb lemma continuous_supr_dom {t₁ : ι → tspace α} {t₂ : tspace β} {i : ι} : cont (t₁ i) t₂ f → cont (supr t₁) t₂ f := continuous_le_dom $ le_supr _ _ lemma continuous_supr_rng {t₁ : tspace α} {t₂ : ι → tspace β} (h : ∀i, cont t₁ (t₂ i) f) : cont t₁ (supr t₂) f := continuous_iff_le_coinduced.2 $ supr_le $ assume i, continuous_iff_le_coinduced.1 $ h i lemma continuous_top {t : tspace β} : cont ⊤ t f := continuous_iff_induced_le.2 $ le_top lemma continuous_bot {t : tspace α} : cont t ⊥ f := continuous_iff_le_coinduced.2 $ bot_le end constructions section induced open topological_space variables [t : topological_space β] {f : α → β} theorem is_open_induced {s : set β} (h : is_open s) : (induced f t).is_open (f ⁻¹' s) := ⟨s, h, rfl⟩ lemma nhds_induced_eq_comap {a : α} : @nhds α (induced f t) a = comap f (nhds (f a)) := le_antisymm (assume s ⟨s', hs', (h_s : f ⁻¹' s' ⊆ s)⟩, let ⟨t', hsub, ht', hin⟩ := mem_nhds_sets_iff.1 hs' in (@nhds α (induced f t) a).sets_of_superset begin simp [mem_nhds_sets_iff], exact ⟨preimage f t', preimage_mono hsub, is_open_induced ht', hin⟩ end h_s) (le_infi $ assume s, le_infi $ assume ⟨as, s', is_open_s', s_eq⟩, begin simp [comap, mem_nhds_sets_iff, s_eq], exact ⟨s', ⟨s', subset.refl _, is_open_s', by rwa [s_eq] at as⟩, subset.refl _⟩ end) lemma map_nhds_induced_eq {a : α} (h : image f univ ∈ (nhds (f a)).sets) : map f (@nhds α (induced f t) a) = nhds (f a) := le_antisymm (@continuous.tendsto α β (induced f t) _ _ continuous_induced_dom a) (assume s, assume hs : f ⁻¹' s ∈ (@nhds α (induced f t) a).sets, let ⟨t', t_subset, is_open_t, a_in_t⟩ := mem_nhds_sets_iff.mp h in let ⟨s', s'_subset, ⟨s'', is_open_s'', s'_eq⟩, a_in_s'⟩ := (@mem_nhds_sets_iff _ (induced f t) _ _).mp hs in by subst s'_eq; exact (mem_nhds_sets_iff.mpr $ ⟨t' ∩ s'', assume x ⟨h₁, h₂⟩, match x, h₂, t_subset h₁ with | x, h₂, ⟨y, _, y_eq⟩ := begin subst y_eq, exact s'_subset h₂ end end, is_open_inter is_open_t is_open_s'', ⟨a_in_t, a_in_s'⟩⟩)) lemma closure_induced [t : topological_space β] {f : α → β} {a : α} {s : set α} (hf : ∀x y, f x = f y → x = y) : a ∈ @closure α (topological_space.induced f t) s ↔ f a ∈ closure (f '' s) := have comap f (nhds (f a) ⊓ principal (f '' s)) ≠ ⊥ ↔ nhds (f a) ⊓ principal (f '' s) ≠ ⊥, from ⟨assume h₁ h₂, h₁ $ h₂.symm ▸ comap_bot, assume h, forall_sets_neq_empty_iff_neq_bot.mp $ assume s₁ ⟨s₂, hs₂, (hs : f ⁻¹' s₂ ⊆ s₁)⟩, have f '' s ∈ (nhds (f a) ⊓ principal (f '' s)).sets, from mem_inf_sets_of_right $ by simp [subset.refl], have s₂ ∩ f '' s ∈ (nhds (f a) ⊓ principal (f '' s)).sets, from inter_mem_sets hs₂ this, let ⟨b, hb₁, ⟨a, ha, ha₂⟩⟩ := inhabited_of_mem_sets h this in ne_empty_of_mem $ hs $ by rwa [←ha₂] at hb₁⟩, calc a ∈ @closure α (topological_space.induced f t) s ↔ (@nhds α (topological_space.induced f t) a) ⊓ principal s ≠ ⊥ : by rw [closure_eq_nhds]; refl ... ↔ comap f (nhds (f a)) ⊓ principal (f ⁻¹' (f '' s)) ≠ ⊥ : by rw [nhds_induced_eq_comap, preimage_image_eq _ hf] ... ↔ comap f (nhds (f a) ⊓ principal (f '' s)) ≠ ⊥ : by rw [comap_inf, ←comap_principal] ... ↔ _ : by rwa [closure_eq_nhds] end induced section embedding /-- A function between topological spaces is an embedding if it is injective, and for all `s : set α`, `s` is open iff it is the preimage of an open set. -/ def embedding [tα : topological_space α] [tβ : topological_space β] (f : α → β) : Prop := function.injective f ∧ tα = tβ.induced f variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] lemma embedding_id : embedding (@id α) := ⟨assume a₁ a₂ h, h, induced_id.symm⟩ lemma embedding_compose {f : α → β} {g : β → γ} (hf : embedding f) (hg : embedding g) : embedding (g ∘ f) := ⟨assume a₁ a₂ h, hf.left $ hg.left h, by rw [hf.right, hg.right, induced_compose]⟩ lemma embedding_prod_mk {f : α → β} {g : γ → δ} (hf : embedding f) (hg : embedding g) : embedding (λx:α×γ, (f x.1, g x.2)) := ⟨assume ⟨x₁, x₂⟩ ⟨y₁, y₂⟩, by simp; exact assume h₁ h₂, ⟨hf.left h₁, hg.left h₂⟩, by rw [prod.topological_space, prod.topological_space, hf.right, hg.right, induced_compose, induced_compose, induced_sup, induced_compose, induced_compose]⟩ lemma embedding_of_embedding_compose {f : α → β} {g : β → γ} (hf : continuous f) (hg : continuous g) (hgf : embedding (g ∘ f)) : embedding f := ⟨assume a₁ a₂ h, hgf.left $ by simp [h, (∘)], le_antisymm (by rw [hgf.right, ← continuous_iff_induced_le]; apply continuous_induced_dom.comp hg) (by rwa ← continuous_iff_induced_le)⟩ lemma embedding_open {f : α → β} {s : set α} (hf : embedding f) (h : is_open (range f)) (hs : is_open s) : is_open (f '' s) := let ⟨t, ht, h_eq⟩ := by rw [hf.right] at hs; exact hs in have is_open (t ∩ range f), from is_open_inter ht h, h_eq.symm ▸ by rwa [image_preimage_eq_inter_range] lemma embedding_is_closed {f : α → β} {s : set α} (hf : embedding f) (h : is_closed (range f)) (hs : is_closed s) : is_closed (f '' s) := let ⟨t, ht, h_eq⟩ := by rw [hf.right, is_closed_induced_iff] at hs; exact hs in have is_closed (t ∩ range f), from is_closed_inter ht h, h_eq.symm ▸ by rwa [image_preimage_eq_inter_range] lemma embedding.map_nhds_eq [topological_space α] [topological_space β] {f : α → β} (hf : embedding f) (a : α) (h : f '' univ ∈ (nhds (f a)).sets) : (nhds a).map f = nhds (f a) := by rw [hf.2]; exact map_nhds_induced_eq h lemma embedding.tendsto_nhds_iff {ι : Type*} {f : ι → β} {g : β → γ} {a : filter ι} {b : β} (hg : embedding g) : tendsto f a (nhds b) ↔ tendsto (g ∘ f) a (nhds (g b)) := by rw [tendsto, tendsto, hg.right, nhds_induced_eq_comap, ← map_le_iff_le_comap, filter.map_map] lemma embedding.continuous_iff {f : α → β} {g : β → γ} (hg : embedding g) : continuous f ↔ continuous (g ∘ f) := by simp [continuous_iff_tendsto, embedding.tendsto_nhds_iff hg] lemma embedding.continuous {f : α → β} (hf : embedding f) : continuous f := hf.continuous_iff.mp continuous_id lemma compact_iff_compact_image_of_embedding {s : set α} {f : α → β} (hf : embedding f) : compact s ↔ compact (f '' s) := iff.intro (assume h, compact_image h hf.continuous) $ assume h, begin rw compact_iff_ultrafilter_le_nhds at ⊢ h, intros u hu us', let u' : filter β := map f u, have : u' ≤ principal (f '' s), begin rw [map_le_iff_le_comap, comap_principal], convert us', exact preimage_image_eq _ hf.1 end, rcases h u' (ultrafilter_map hu) this with ⟨_, ⟨a, ha, ⟨⟩⟩, _⟩, refine ⟨a, ha, _⟩, rwa [hf.2, nhds_induced_eq_comap, ←map_le_iff_le_comap] end end embedding section quotient_map /-- A function between topological spaces is a quotient map if it is surjective, and for all `s : set β`, `s` is open iff its preimage is an open set. -/ def quotient_map [tα : topological_space α] [tβ : topological_space β] (f : α → β) : Prop := function.surjective f ∧ tβ = tα.coinduced f variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] lemma quotient_map_id : quotient_map (@id α) := ⟨assume a, ⟨a, rfl⟩, coinduced_id.symm⟩ lemma quotient_map_compose {f : α → β} {g : β → γ} (hf : quotient_map f) (hg : quotient_map g) : quotient_map (g ∘ f) := ⟨function.surjective_comp hg.left hf.left, by rw [hg.right, hf.right, coinduced_compose]⟩ lemma quotient_map_of_quotient_map_compose {f : α → β} {g : β → γ} (hf : continuous f) (hg : continuous g) (hgf : quotient_map (g ∘ f)) : quotient_map g := ⟨assume b, let ⟨a, h⟩ := hgf.left b in ⟨f a, h⟩, le_antisymm (by rwa ← continuous_iff_le_coinduced) (by rw [hgf.right, ← continuous_iff_le_coinduced]; apply hf.comp continuous_coinduced_rng)⟩ lemma quotient_map.continuous_iff {f : α → β} {g : β → γ} (hf : quotient_map f) : continuous g ↔ continuous (g ∘ f) := by rw [continuous_iff_le_coinduced, continuous_iff_le_coinduced, hf.right, coinduced_compose] lemma quotient_map.continuous {f : α → β} (hf : quotient_map f) : continuous f := hf.continuous_iff.mp continuous_id end quotient_map section sierpinski variables [topological_space α] @[simp] lemma is_open_singleton_true : is_open ({true} : set Prop) := topological_space.generate_open.basic _ (by simp) lemma continuous_Prop {p : α → Prop} : continuous p ↔ is_open {x | p x} := ⟨assume h : continuous p, have is_open (p ⁻¹' {true}), from h _ is_open_singleton_true, by simp [preimage, eq_true] at this; assumption, assume h : is_open {x | p x}, continuous_generated_from $ assume s (hs : s ∈ {{true}}), by simp at hs; simp [hs, preimage, eq_true, h]⟩ end sierpinski section prod open topological_space variables [topological_space α] [topological_space β] [topological_space γ] lemma continuous_fst : continuous (@prod.fst α β) := continuous_sup_dom_left continuous_induced_dom lemma continuous_snd : continuous (@prod.snd α β) := continuous_sup_dom_right continuous_induced_dom lemma continuous.prod_mk {f : γ → α} {g : γ → β} (hf : continuous f) (hg : continuous g) : continuous (λx, prod.mk (f x) (g x)) := continuous_sup_rng (continuous_induced_rng hf) (continuous_induced_rng hg) lemma continuous_swap : continuous (prod.swap : α × β → β × α) := continuous.prod_mk continuous_snd continuous_fst lemma is_open_prod {s : set α} {t : set β} (hs : is_open s) (ht : is_open t) : is_open (set.prod s t) := is_open_inter (continuous_fst s hs) (continuous_snd t ht) lemma nhds_prod_eq {a : α} {b : β} : nhds (a, b) = filter.prod (nhds a) (nhds b) := by rw [filter.prod, prod.topological_space, nhds_sup, nhds_induced_eq_comap, nhds_induced_eq_comap] lemma prod_mem_nhds_sets {s : set α} {t : set β} {a : α} {b : β} (ha : s ∈ (nhds a).sets) (hb : t ∈ (nhds b).sets) : set.prod s t ∈ (nhds (a, b)).sets := by rw [nhds_prod_eq]; exact prod_mem_prod ha hb lemma nhds_swap (a : α) (b : β) : nhds (a, b) = (nhds (b, a)).map prod.swap := by rw [nhds_prod_eq, filter.prod_comm, nhds_prod_eq]; refl lemma tendsto_prod_mk_nhds {γ} {a : α} {b : β} {f : filter γ} {ma : γ → α} {mb : γ → β} (ha : tendsto ma f (nhds a)) (hb : tendsto mb f (nhds b)) : tendsto (λc, (ma c, mb c)) f (nhds (a, b)) := by rw [nhds_prod_eq]; exact filter.tendsto.prod_mk ha hb lemma prod_generate_from_generate_from_eq {s : set (set α)} {t : set (set β)} (hs : ⋃₀ s = univ) (ht : ⋃₀ t = univ) : @prod.topological_space α β (generate_from s) (generate_from t) = generate_from {g | ∃u∈s, ∃v∈t, g = set.prod u v} := let G := generate_from {g | ∃u∈s, ∃v∈t, g = set.prod u v} in le_antisymm (sup_le (induced_le_iff_le_coinduced.mpr $ generate_from_le $ assume u hu, have (⋃v∈t, set.prod u v) = prod.fst ⁻¹' u, from calc (⋃v∈t, set.prod u v) = set.prod u univ : set.ext $ assume ⟨a, b⟩, by rw ← ht; simp [and.left_comm] {contextual:=tt} ... = prod.fst ⁻¹' u : by simp [set.prod, preimage], show G.is_open (prod.fst ⁻¹' u), from this ▸ @is_open_Union _ _ G _ $ assume v, @is_open_Union _ _ G _ $ assume hv, generate_open.basic _ ⟨_, hu, _, hv, rfl⟩) (induced_le_iff_le_coinduced.mpr $ generate_from_le $ assume v hv, have (⋃u∈s, set.prod u v) = prod.snd ⁻¹' v, from calc (⋃u∈s, set.prod u v) = set.prod univ v: set.ext $ assume ⟨a, b⟩, by rw [←hs]; by_cases b ∈ v; simp [h] {contextual:=tt} ... = prod.snd ⁻¹' v : by simp [set.prod, preimage], show G.is_open (prod.snd ⁻¹' v), from this ▸ @is_open_Union _ _ G _ $ assume u, @is_open_Union _ _ G _ $ assume hu, generate_open.basic _ ⟨_, hu, _, hv, rfl⟩)) (generate_from_le $ assume g ⟨u, hu, v, hv, g_eq⟩, g_eq.symm ▸ @is_open_prod _ _ (generate_from s) (generate_from t) _ _ (generate_open.basic _ hu) (generate_open.basic _ hv)) lemma prod_eq_generate_from [tα : topological_space α] [tβ : topological_space β] : prod.topological_space = generate_from {g | ∃(s:set α) (t:set β), is_open s ∧ is_open t ∧ g = set.prod s t} := le_antisymm (sup_le (assume s ⟨t, ht, s_eq⟩, have set.prod t univ = s, by simp [s_eq, preimage, set.prod], this ▸ (generate_open.basic _ ⟨t, univ, ht, is_open_univ, rfl⟩)) (assume s ⟨t, ht, s_eq⟩, have set.prod univ t = s, by simp [s_eq, preimage, set.prod], this ▸ (generate_open.basic _ ⟨univ, t, is_open_univ, ht, rfl⟩))) (generate_from_le $ assume g ⟨s, t, hs, ht, g_eq⟩, g_eq.symm ▸ is_open_prod hs ht) lemma is_open_prod_iff {s : set (α×β)} : is_open s ↔ (∀a b, (a, b) ∈ s → ∃u v, is_open u ∧ is_open v ∧ a ∈ u ∧ b ∈ v ∧ set.prod u v ⊆ s) := begin rw [is_open_iff_nhds], simp [nhds_prod_eq, mem_prod_iff], simp [mem_nhds_sets_iff], exact forall_congr (assume a, ball_congr $ assume b h, ⟨assume ⟨u', ⟨u, us, uo, au⟩, v', ⟨v, vs, vo, bv⟩, h⟩, ⟨u, uo, v, vo, au, bv, subset.trans (set.prod_mono us vs) h⟩, assume ⟨u, uo, v, vo, au, bv, h⟩, ⟨u, ⟨u, subset.refl u, uo, au⟩, v, ⟨v, subset.refl v, vo, bv⟩, h⟩⟩) end lemma closure_prod_eq {s : set α} {t : set β} : closure (set.prod s t) = set.prod (closure s) (closure t) := set.ext $ assume ⟨a, b⟩, have filter.prod (nhds a) (nhds b) ⊓ principal (set.prod s t) = filter.prod (nhds a ⊓ principal s) (nhds b ⊓ principal t), by rw [←prod_inf_prod, prod_principal_principal], by simp [closure_eq_nhds, nhds_prod_eq, this]; exact prod_neq_bot lemma is_closed_prod [topological_space α] [topological_space β] {s₁ : set α} {s₂ : set β} (h₁ : is_closed s₁) (h₂ : is_closed s₂) : is_closed (set.prod s₁ s₂) := closure_eq_iff_is_closed.mp $ by simp [h₁, h₂, closure_prod_eq, closure_eq_of_is_closed] section tube_lemma def nhds_contain_boxes (s : set α) (t : set β) : Prop := ∀ (n : set (α × β)) (hn : is_open n) (hp : set.prod s t ⊆ n), ∃ (u : set α) (v : set β), is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ set.prod u v ⊆ n lemma nhds_contain_boxes.symm {s : set α} {t : set β} : nhds_contain_boxes s t → nhds_contain_boxes t s := assume H n hn hp, let ⟨u, v, uo, vo, su, tv, p⟩ := H (prod.swap ⁻¹' n) (continuous_swap n hn) (by rwa [←image_subset_iff, prod.swap, image_swap_prod]) in ⟨v, u, vo, uo, tv, su, by rwa [←image_subset_iff, prod.swap, image_swap_prod] at p⟩ lemma nhds_contain_boxes.comm {s : set α} {t : set β} : nhds_contain_boxes s t ↔ nhds_contain_boxes t s := iff.intro nhds_contain_boxes.symm nhds_contain_boxes.symm lemma nhds_contain_boxes_of_singleton {x : α} {y : β} : nhds_contain_boxes ({x} : set α) ({y} : set β) := assume n hn hp, let ⟨u, v, uo, vo, xu, yv, hp'⟩ := is_open_prod_iff.mp hn x y (hp $ by simp) in ⟨u, v, uo, vo, by simpa, by simpa, hp'⟩ lemma nhds_contain_boxes_of_compact {s : set α} (hs : compact s) (t : set β) (H : ∀ x ∈ s, nhds_contain_boxes ({x} : set α) t) : nhds_contain_boxes s t := assume n hn hp, have ∀x : subtype s, ∃uv : set α × set β, is_open uv.1 ∧ is_open uv.2 ∧ {↑x} ⊆ uv.1 ∧ t ⊆ uv.2 ∧ set.prod uv.1 uv.2 ⊆ n, from assume ⟨x, hx⟩, have set.prod {x} t ⊆ n, from subset.trans (prod_mono (by simpa) (subset.refl _)) hp, let ⟨ux,vx,H1⟩ := H x hx n hn this in ⟨⟨ux,vx⟩,H1⟩, let ⟨uvs, h⟩ := classical.axiom_of_choice this in have us_cover : s ⊆ ⋃i, (uvs i).1, from assume x hx, set.subset_Union _ ⟨x,hx⟩ (by simpa using (h ⟨x,hx⟩).2.2.1), let ⟨s0, _, s0_fin, s0_cover⟩ := compact_elim_finite_subcover_image hs (λi _, (h i).1) $ by rw bUnion_univ; exact us_cover in let u := ⋃(i ∈ s0), (uvs i).1 in let v := ⋂(i ∈ s0), (uvs i).2 in have is_open u, from is_open_bUnion (λi _, (h i).1), have is_open v, from is_open_bInter s0_fin (λi _, (h i).2.1), have t ⊆ v, from subset_bInter (λi _, (h i).2.2.2.1), have set.prod u v ⊆ n, from assume ⟨x',y'⟩ ⟨hx',hy'⟩, have ∃i ∈ s0, x' ∈ (uvs i).1, by simpa using hx', let ⟨i,is0,hi⟩ := this in (h i).2.2.2.2 ⟨hi, (bInter_subset_of_mem is0 : v ⊆ (uvs i).2) hy'⟩, ⟨u, v, ‹is_open u›, ‹is_open v›, s0_cover, ‹t ⊆ v›, ‹set.prod u v ⊆ n›⟩ lemma generalized_tube_lemma {s : set α} (hs : compact s) {t : set β} (ht : compact t) {n : set (α × β)} (hn : is_open n) (hp : set.prod s t ⊆ n) : ∃ (u : set α) (v : set β), is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ set.prod u v ⊆ n := have _, from nhds_contain_boxes_of_compact hs t $ assume x _, nhds_contain_boxes.symm $ nhds_contain_boxes_of_compact ht {x} $ assume y _, nhds_contain_boxes_of_singleton, this n hn hp end tube_lemma lemma is_closed_diagonal [topological_space α] [t2_space α] : is_closed {p:α×α | p.1 = p.2} := is_closed_iff_nhds.mpr $ assume ⟨a₁, a₂⟩ h, eq_of_nhds_neq_bot $ assume : nhds a₁ ⊓ nhds a₂ = ⊥, h $ let ⟨t₁, ht₁, t₂, ht₂, (h' : t₁ ∩ t₂ ⊆ ∅)⟩ := by rw [←empty_in_sets_eq_bot, mem_inf_sets] at this; exact this in begin rw [nhds_prod_eq, ←empty_in_sets_eq_bot], apply filter.sets_of_superset, apply inter_mem_inf_sets (prod_mem_prod ht₁ ht₂) (mem_principal_sets.mpr (subset.refl _)), exact assume ⟨x₁, x₂⟩ ⟨⟨hx₁, hx₂⟩, (heq : x₁ = x₂)⟩, show false, from @h' x₁ ⟨hx₁, heq.symm ▸ hx₂⟩ end lemma is_closed_eq [topological_space α] [t2_space α] [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : is_closed {x:β | f x = g x} := continuous_iff_is_closed.mp (hf.prod_mk hg) _ is_closed_diagonal lemma diagonal_eq_range_diagonal_map : {p:α×α | p.1 = p.2} = range (λx, (x,x)) := ext $ assume p, iff.intro (assume h, ⟨p.1, prod.ext_iff.2 ⟨rfl, h⟩⟩) (assume ⟨x, hx⟩, show p.1 = p.2, by rw ←hx) lemma prod_subset_compl_diagonal_iff_disjoint {s t : set α} : set.prod s t ⊆ - {p:α×α | p.1 = p.2} ↔ s ∩ t = ∅ := by rw [eq_empty_iff_forall_not_mem, subset_compl_comm, diagonal_eq_range_diagonal_map, range_subset_iff]; simp lemma compact_compact_separated [t2_space α] {s t : set α} (hs : compact s) (ht : compact t) (hst : s ∩ t = ∅) : ∃u v : set α, is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ u ∩ v = ∅ := by simp only [prod_subset_compl_diagonal_iff_disjoint.symm] at ⊢ hst; exact generalized_tube_lemma hs ht is_closed_diagonal hst lemma closed_of_compact [t2_space α] (s : set α) (hs : compact s) : is_closed s := is_open_compl_iff.mpr $ is_open_iff_forall_mem_open.mpr $ assume x hx, let ⟨u, v, uo, vo, su, xv, uv⟩ := compact_compact_separated hs (compact_singleton : compact {x}) (by rwa [inter_comm, ←subset_compl_iff_disjoint, singleton_subset_iff]) in have v ⊆ -s, from subset_compl_comm.mp (subset.trans su (subset_compl_iff_disjoint.mpr uv)), ⟨v, this, vo, by simpa using xv⟩ /- TODO: more fine grained instances for first_countable_topology, separable_space, t2_space, ... -/ instance [second_countable_topology α] [second_countable_topology β] : second_countable_topology (α × β) := ⟨let ⟨a, ha₁, ha₂, ha₃, ha₄, ha₅⟩ := is_open_generated_countable_inter α in let ⟨b, hb₁, hb₂, hb₃, hb₄, hb₅⟩ := is_open_generated_countable_inter β in ⟨{g | ∃u∈a, ∃v∈b, g = set.prod u v}, have {g | ∃u∈a, ∃v∈b, g = set.prod u v} = (⋃u∈a, ⋃v∈b, {set.prod u v}), by apply set.ext; simp, by rw [this]; exact (countable_bUnion ha₁ $ assume u hu, countable_bUnion hb₁ $ by simp), by rw [ha₅, hb₅, prod_generate_from_generate_from_eq ha₄ hb₄]⟩⟩ end prod section locally_compact /-- There are various definitions of "locally compact space" in the literature, which agree for Hausdorff spaces but not in general. This one is the precise condition on X needed for the evaluation `map C(X, Y) × X → Y` to be continuous for all `Y` when `C(X, Y)` is given the compact-open topology. -/ class locally_compact_space (α : Type*) [topological_space α] := (local_compact_nhds : ∀ (x : α) (n ∈ (nhds x).sets), ∃ s ∈ (nhds x).sets, s ⊆ n ∧ compact s) lemma locally_compact_of_compact_nhds [topological_space α] [t2_space α] (h : ∀ x : α, ∃ s, s ∈ (nhds x).sets ∧ compact s) : locally_compact_space α := ⟨assume x n hn, let ⟨u, un, uo, xu⟩ := mem_nhds_sets_iff.mp hn in let ⟨k, kx, kc⟩ := h x in -- K is compact but not necessarily contained in N. -- K \ U is again compact and doesn't contain x, so -- we may find open sets V, W separating x from K \ U. -- Then K \ W is a compact neighborhood of x contained in U. let ⟨v, w, vo, wo, xv, kuw, vw⟩ := compact_compact_separated compact_singleton (compact_diff kc uo) (by rw [singleton_inter_eq_empty]; exact λ h, h.2 xu) in have wn : -w ∈ (nhds x).sets, from mem_nhds_sets_iff.mpr ⟨v, subset_compl_iff_disjoint.mpr vw, vo, singleton_subset_iff.mp xv⟩, ⟨k - w, filter.inter_mem_sets kx wn, subset.trans (diff_subset_comm.mp kuw) un, compact_diff kc wo⟩⟩ lemma locally_compact_of_compact [topological_space α] [t2_space α] (h : compact (univ : set α)) : locally_compact_space α := locally_compact_of_compact_nhds (assume x, ⟨univ, mem_nhds_sets is_open_univ trivial, h⟩) end locally_compact section sum variables [topological_space α] [topological_space β] [topological_space γ] lemma continuous_inl : continuous (@sum.inl α β) := continuous_inf_rng_left continuous_coinduced_rng lemma continuous_inr : continuous (@sum.inr α β) := continuous_inf_rng_right continuous_coinduced_rng lemma continuous_sum_rec {f : α → γ} {g : β → γ} (hf : continuous f) (hg : continuous g) : @continuous (α ⊕ β) γ _ _ (@sum.rec α β (λ_, γ) f g) := continuous_inf_dom hf hg end sum section subtype variables [topological_space α] [topological_space β] [topological_space γ] {p : α → Prop} lemma embedding_graph {f : α → β} (hf : continuous f) : embedding (λx, (x, f x)) := embedding_of_embedding_compose (continuous_id.prod_mk hf) continuous_fst embedding_id lemma embedding_subtype_val : embedding (@subtype.val α p) := ⟨assume a₁ a₂, subtype.eq, rfl⟩ lemma continuous_subtype_val : continuous (@subtype.val α p) := continuous_induced_dom lemma continuous_subtype_mk {f : β → α} (hp : ∀x, p (f x)) (h : continuous f) : continuous (λx, (⟨f x, hp x⟩ : subtype p)) := continuous_induced_rng h lemma embedding_inl : embedding (@sum.inl α β) := ⟨λ _ _, sum.inl.inj_iff.mp, begin unfold sum.topological_space, apply le_antisymm, { intros u hu, existsi (sum.inl '' u), change (is_open (sum.inl ⁻¹' (@sum.inl α β '' u)) ∧ is_open (sum.inr ⁻¹' (@sum.inl α β '' u))) ∧ u = sum.inl ⁻¹' (sum.inl '' u), have : sum.inl ⁻¹' (@sum.inl α β '' u) = u := preimage_image_eq u (λ _ _, sum.inl.inj_iff.mp), rw this, have : sum.inr ⁻¹' (@sum.inl α β '' u) = ∅ := eq_empty_iff_forall_not_mem.mpr (assume a ⟨b, _, h⟩, sum.inl_ne_inr h), rw this, exact ⟨⟨hu, is_open_empty⟩, rfl⟩ }, { rw induced_le_iff_le_coinduced, exact lattice.inf_le_left } end⟩ lemma embedding_inr : embedding (@sum.inr α β) := ⟨λ _ _, sum.inr.inj_iff.mp, begin unfold sum.topological_space, apply le_antisymm, { intros u hu, existsi (sum.inr '' u), change (is_open (sum.inl ⁻¹' (@sum.inr α β '' u)) ∧ is_open (sum.inr ⁻¹' (@sum.inr α β '' u))) ∧ u = sum.inr ⁻¹' (sum.inr '' u), have : sum.inl ⁻¹' (@sum.inr α β '' u) = ∅ := eq_empty_iff_forall_not_mem.mpr (assume b ⟨a, _, h⟩, sum.inr_ne_inl h), rw this, have : sum.inr ⁻¹' (@sum.inr α β '' u) = u := preimage_image_eq u (λ _ _, sum.inr.inj_iff.mp), rw this, exact ⟨⟨is_open_empty, hu⟩, rfl⟩ }, { rw induced_le_iff_le_coinduced, exact lattice.inf_le_right } end⟩ lemma map_nhds_subtype_val_eq {a : α} (ha : p a) (h : {a | p a} ∈ (nhds a).sets) : map (@subtype.val α p) (nhds ⟨a, ha⟩) = nhds a := map_nhds_induced_eq (by simp [subtype_val_image, h]) lemma nhds_subtype_eq_comap {a : α} {h : p a} : nhds (⟨a, h⟩ : subtype p) = comap subtype.val (nhds a) := nhds_induced_eq_comap lemma continuous_subtype_nhds_cover {ι : Sort*} {f : α → β} {c : ι → α → Prop} (c_cover : ∀x:α, ∃i, {x | c i x} ∈ (nhds x).sets) (f_cont : ∀i, continuous (λ(x : subtype (c i)), f x.val)) : continuous f := continuous_iff_tendsto.mpr $ assume x, let ⟨i, (c_sets : {x | c i x} ∈ (nhds x).sets)⟩ := c_cover x in let x' : subtype (c i) := ⟨x, mem_of_nhds c_sets⟩ in calc map f (nhds x) = map f (map subtype.val (nhds x')) : congr_arg (map f) (map_nhds_subtype_val_eq _ $ c_sets).symm ... = map (λx:subtype (c i), f x.val) (nhds x') : rfl ... ≤ nhds (f x) : continuous_iff_tendsto.mp (f_cont i) x' lemma continuous_subtype_is_closed_cover {ι : Sort*} {f : α → β} (c : ι → α → Prop) (h_lf : locally_finite (λi, {x | c i x})) (h_is_closed : ∀i, is_closed {x | c i x}) (h_cover : ∀x, ∃i, c i x) (f_cont : ∀i, continuous (λ(x : subtype (c i)), f x.val)) : continuous f := continuous_iff_is_closed.mpr $ assume s hs, have ∀i, is_closed (@subtype.val α {x | c i x} '' (f ∘ subtype.val ⁻¹' s)), from assume i, embedding_is_closed embedding_subtype_val (by simp [subtype_val_range]; exact h_is_closed i) (continuous_iff_is_closed.mp (f_cont i) _ hs), have is_closed (⋃i, @subtype.val α {x | c i x} '' (f ∘ subtype.val ⁻¹' s)), from is_closed_Union_of_locally_finite (locally_finite_subset h_lf $ assume i x ⟨⟨x', hx'⟩, _, heq⟩, heq ▸ hx') this, have f ⁻¹' s = (⋃i, @subtype.val α {x | c i x} '' (f ∘ subtype.val ⁻¹' s)), begin apply set.ext, have : ∀ (x : α), f x ∈ s ↔ ∃ (i : ι), c i x ∧ f x ∈ s := λ x, ⟨λ hx, let ⟨i, hi⟩ := h_cover x in ⟨i, hi, hx⟩, λ ⟨i, hi, hx⟩, hx⟩, simp [and.comm, and.left_comm], simpa [(∘)], end, by rwa [this] lemma closure_subtype {x : {a // p a}} {s : set {a // p a}}: x ∈ closure s ↔ x.val ∈ closure (subtype.val '' s) := closure_induced $ assume x y, subtype.eq lemma compact_iff_compact_in_subtype {s : set {a // p a}} : compact s ↔ compact (subtype.val '' s) := compact_iff_compact_image_of_embedding embedding_subtype_val lemma compact_iff_compact_univ {s : set α} : compact s ↔ compact (univ : set (subtype s)) := by rw [compact_iff_compact_in_subtype, image_univ, subtype_val_range]; refl end subtype section quotient variables [topological_space α] [topological_space β] [topological_space γ] variables {r : α → α → Prop} {s : setoid α} lemma quotient_map_quot_mk : quotient_map (@quot.mk α r) := ⟨quot.exists_rep, rfl⟩ lemma continuous_quot_mk : continuous (@quot.mk α r) := continuous_coinduced_rng lemma continuous_quot_lift {f : α → β} (hr : ∀ a b, r a b → f a = f b) (h : continuous f) : continuous (quot.lift f hr : quot r → β) := continuous_coinduced_dom h lemma quotient_map_quotient_mk : quotient_map (@quotient.mk α s) := quotient_map_quot_mk lemma continuous_quotient_mk : continuous (@quotient.mk α s) := continuous_coinduced_rng lemma continuous_quotient_lift {f : α → β} (hs : ∀ a b, a ≈ b → f a = f b) (h : continuous f) : continuous (quotient.lift f hs : quotient s → β) := continuous_coinduced_dom h end quotient section pi variables {ι : Type*} {π : ι → Type*} open topological_space lemma continuous_pi [topological_space α] [∀i, topological_space (π i)] {f : α → Πi:ι, π i} (h : ∀i, continuous (λa, f a i)) : continuous f := continuous_supr_rng $ assume i, continuous_induced_rng $ h i lemma continuous_apply [∀i, topological_space (π i)] (i : ι) : continuous (λp:Πi, π i, p i) := continuous_supr_dom continuous_induced_dom lemma nhds_pi [t : ∀i, topological_space (π i)] {a : Πi, π i} : nhds a = (⨅i, comap (λx, x i) (nhds (a i))) := calc nhds a = (⨅i, @nhds _ (@topological_space.induced _ _ (λx:Πi, π i, x i) (t i)) a) : nhds_supr ... = (⨅i, comap (λx, x i) (nhds (a i))) : by simp [nhds_induced_eq_comap] /-- Tychonoff's theorem -/ lemma compact_pi_infinite [∀i, topological_space (π i)] {s : Πi:ι, set (π i)} : (∀i, compact (s i)) → compact {x : Πi:ι, π i | ∀i, x i ∈ s i} := begin simp [compact_iff_ultrafilter_le_nhds, nhds_pi], exact assume h f hf hfs, let p : Πi:ι, filter (π i) := λi, map (λx:Πi:ι, π i, x i) f in have ∀i:ι, ∃a, a∈s i ∧ p i ≤ nhds a, from assume i, h i (p i) (ultrafilter_map hf) $ show (λx:Πi:ι, π i, x i) ⁻¹' s i ∈ f.sets, from mem_sets_of_superset hfs $ assume x (hx : ∀i, x i ∈ s i), hx i, let ⟨a, ha⟩ := classical.axiom_of_choice this in ⟨a, assume i, (ha i).left, assume i, map_le_iff_le_comap.mp $ (ha i).right⟩ end lemma is_open_set_pi [∀a, topological_space (π a)] {i : set ι} {s : Πa, set (π a)} (hi : finite i) (hs : ∀a∈i, is_open (s a)) : is_open (pi i s) := by rw [pi_def]; exact (is_open_bInter hi $ assume a ha, continuous_apply a _ $ hs a ha) lemma pi_eq_generate_from [∀a, topological_space (π a)] : Pi.topological_space = generate_from {g | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, is_open (s a)) ∧ g = pi ↑i s} := le_antisymm (supr_le $ assume a s ⟨t, ht, s_eq⟩, generate_open.basic _ $ ⟨function.update (λa, univ) a t, {a}, by simpa using ht, by ext f; simp [s_eq, pi]⟩) (generate_from_le $ assume g ⟨s, i, hi, eq⟩, eq.symm ▸ is_open_set_pi (finset.finite_to_set _) hi) lemma pi_generate_from_eq {g : Πa, set (set (π a))} : @Pi.topological_space ι π (λa, generate_from (g a)) = generate_from {t | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, s a ∈ g a) ∧ t = pi ↑i s} := let G := {t | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, s a ∈ g a) ∧ t = pi ↑i s} in begin rw [pi_eq_generate_from], refine le_antisymm (generate_from_le _) (generate_from_mono _), { rintros s ⟨t, i, hi, rfl⟩, rw [pi_def], apply is_open_bInter (finset.finite_to_set _), assume a ha, show ((generate_from G).coinduced (λf:Πa, π a, f a)).is_open (t a), refine generate_from_le _ _ (hi a ha), exact assume s hs, generate_open.basic _ ⟨function.update (λa, univ) a s, {a}, by simp [hs]⟩ }, exact assume s ⟨t, i, ht, eq⟩, ⟨t, i, assume a ha, generate_open.basic _ (ht a ha), eq⟩ end lemma pi_generate_from_eq_fintype {g : Πa, set (set (π a))} [fintype ι] (hg : ∀a, ⋃₀ g a = univ) : @Pi.topological_space ι π (λa, generate_from (g a)) = generate_from {t | ∃(s:Πa, set (π a)), (∀a, s a ∈ g a) ∧ t = pi univ s} := let G := {t | ∃(s:Πa, set (π a)), (∀a, s a ∈ g a) ∧ t = pi univ s} in begin rw [pi_generate_from_eq], refine le_antisymm (generate_from_le _) (generate_from_mono _), { rintros s ⟨t, i, ht, rfl⟩, apply is_open_iff_forall_mem_open.2 _, assume f hf, choose c hc using show ∀a, ∃s, s ∈ g a ∧ f a ∈ s, { assume a, have : f a ∈ ⋃₀ g a, { rw [hg], apply mem_univ }, simpa }, refine ⟨pi univ (λa, if a ∈ i then t a else (c : Πa, set (π a)) a), _, _, _⟩, { simp [pi_if] }, { refine generate_open.basic _ ⟨_, assume a, _, rfl⟩, by_cases a ∈ i; simp [*, pi] at * }, { have : f ∈ pi {a | a ∉ i} c, { simp [*, pi] at * }, simpa [pi_if, hf] } }, exact assume s ⟨t, ht, eq⟩, ⟨t, finset.univ, by simp [ht, eq]⟩ end instance second_countable_topology_fintype [fintype ι] [t : ∀a, topological_space (π a)] [sc : ∀a, second_countable_topology (π a)] : second_countable_topology (∀a, π a) := have ∀i, ∃b : set (set (π i)), countable b ∧ ∅ ∉ b ∧ is_topological_basis b, from assume a, @is_open_generated_countable_inter (π a) _ (sc a), let ⟨g, hg⟩ := classical.axiom_of_choice this in have t = (λa, generate_from (g a)), from funext $ assume a, (hg a).2.2.2.2, begin constructor, refine ⟨pi univ '' pi univ g, countable_image _ _, _⟩, { suffices : countable {f : Πa, set (π a) | ∀a, f a ∈ g a}, { simpa [pi] }, exact countable_pi (assume i, (hg i).1), }, rw [this, pi_generate_from_eq_fintype], { congr' 1, ext f, simp [pi, eq_comm] }, exact assume a, (hg a).2.2.2.1 end end pi -- TODO: use embeddings from above! structure dense_embedding [topological_space α] [topological_space β] (e : α → β) : Prop := (dense : ∀x, x ∈ closure (range e)) (inj : function.injective e) (induced : ∀a, comap e (nhds (e a)) = nhds a) theorem dense_embedding.mk' [topological_space α] [topological_space β] (e : α → β) (c : continuous e) (dense : ∀x, x ∈ closure (range e)) (inj : function.injective e) (H : ∀ (a:α) s ∈ (nhds a).sets, ∃t ∈ (nhds (e a)).sets, ∀ b, e b ∈ t → b ∈ s) : dense_embedding e := ⟨dense, inj, λ a, le_antisymm (by simpa [le_def] using H a) (tendsto_iff_comap.1 $ c.tendsto _)⟩ namespace dense_embedding variables [topological_space α] [topological_space β] variables {e : α → β} (de : dense_embedding e) protected lemma embedding (de : dense_embedding e) : embedding e := ⟨de.inj, eq_of_nhds_eq_nhds begin intro a, rw [← de.induced a, nhds_induced_eq_comap] end⟩ protected lemma tendsto (de : dense_embedding e) {a : α} : tendsto e (nhds a) (nhds (e a)) := by rw [←de.induced a]; exact tendsto_comap protected lemma continuous (de : dense_embedding e) {a : α} : continuous e := continuous_iff_tendsto.2 $ λ a, de.tendsto lemma inj_iff (de : dense_embedding e) {x y} : e x = e y ↔ x = y := de.inj.eq_iff lemma closure_range : closure (range e) = univ := let h := de.dense in set.ext $ assume x, ⟨assume _, trivial, assume _, @h x⟩ lemma self_sub_closure_image_preimage_of_open {s : set β} (de : dense_embedding e) : is_open s → s ⊆ closure (e '' (e ⁻¹' s)) := begin intros s_op b b_in_s, rw [image_preimage_eq_inter_range, mem_closure_iff], intros U U_op b_in, rw ←inter_assoc, have ne_e : U ∩ s ≠ ∅ := ne_empty_of_mem ⟨b_in, b_in_s⟩, exact (dense_iff_inter_open.1 de.closure_range) _ (is_open_inter U_op s_op) ne_e end lemma closure_image_nhds_of_nhds {s : set α} {a : α} (de : dense_embedding e) : s ∈ (nhds a).sets → closure (e '' s) ∈ (nhds (e a)).sets := begin rw [← de.induced a, mem_comap_sets], intro h, rcases h with ⟨t, t_nhd, sub⟩, rw mem_nhds_sets_iff at t_nhd, rcases t_nhd with ⟨U, U_sub, ⟨U_op, e_a_in_U⟩⟩, have := calc e ⁻¹' U ⊆ e⁻¹' t : preimage_mono U_sub ... ⊆ s : sub, have := calc U ⊆ closure (e '' (e ⁻¹' U)) : self_sub_closure_image_preimage_of_open de U_op ... ⊆ closure (e '' s) : closure_mono (image_subset e this), have U_nhd : U ∈ (nhds (e a)).sets := mem_nhds_sets U_op e_a_in_U, exact (nhds (e a)).sets_of_superset U_nhd this end variables [topological_space δ] {f : γ → α} {g : γ → δ} {h : δ → β} /-- γ -f→ α g↓ ↓e δ -h→ β -/ lemma tendsto_comap_nhds_nhds {d : δ} {a : α} (de : dense_embedding e) (H : tendsto h (nhds d) (nhds (e a))) (comm : h ∘ g = e ∘ f) : tendsto f (comap g (nhds d)) (nhds a) := begin have lim1 : map g (comap g (nhds d)) ≤ nhds d := map_comap_le, replace lim1 : map h (map g (comap g (nhds d))) ≤ map h (nhds d) := map_mono lim1, rw [filter.map_map, comm, ← filter.map_map, map_le_iff_le_comap] at lim1, have lim2 : comap e (map h (nhds d)) ≤ comap e (nhds (e a)) := comap_mono H, rw de.induced at lim2, exact le_trans lim1 lim2, end protected lemma nhds_inf_neq_bot (de : dense_embedding e) {b : β} : nhds b ⊓ principal (range e) ≠ ⊥ := begin have h := de.dense, simp [closure_eq_nhds] at h, exact h _ end lemma comap_nhds_neq_bot (de : dense_embedding e) {b : β} : comap e (nhds b) ≠ ⊥ := forall_sets_neq_empty_iff_neq_bot.mp $ assume s ⟨t, ht, (hs : e ⁻¹' t ⊆ s)⟩, have t ∩ range e ∈ (nhds b ⊓ principal (range e)).sets, from inter_mem_inf_sets ht (subset.refl _), let ⟨_, ⟨hx₁, y, rfl⟩⟩ := inhabited_of_mem_sets de.nhds_inf_neq_bot this in subset_ne_empty hs $ ne_empty_of_mem hx₁ variables [topological_space γ] /-- If `e : α → β` is a dense embedding, then any function `α → γ` extends to a function `β → γ`. -/ def extend (de : dense_embedding e) (f : α → γ) (b : β) : γ := have nonempty γ, from let ⟨_, ⟨_, a, _⟩⟩ := exists_mem_of_ne_empty (mem_closure_iff.1 (de.dense b) _ is_open_univ trivial) in ⟨f a⟩, @lim _ (classical.inhabited_of_nonempty this) _ (map f (comap e (nhds b))) lemma extend_eq [t2_space γ] {b : β} {c : γ} {f : α → γ} (hf : map f (comap e (nhds b)) ≤ nhds c) : de.extend f b = c := @lim_eq _ (id _) _ _ _ _ (by simp; exact comap_nhds_neq_bot de) hf lemma extend_e_eq [t2_space γ] {a : α} {f : α → γ} (de : dense_embedding e) (hf : map f (nhds a) ≤ nhds (f a)) : de.extend f (e a) = f a := de.extend_eq begin rw de.induced; exact hf end lemma tendsto_extend [regular_space γ] {b : β} {f : α → γ} (de : dense_embedding e) (hf : {b | ∃c, tendsto f (comap e $ nhds b) (nhds c)} ∈ (nhds b).sets) : tendsto (de.extend f) (nhds b) (nhds (de.extend f b)) := let φ := {b | tendsto f (comap e $ nhds b) (nhds $ de.extend f b)} in have hφ : φ ∈ (nhds b).sets, from (nhds b).sets_of_superset hf $ assume b ⟨c, hc⟩, show tendsto f (comap e (nhds b)) (nhds (de.extend f b)), from (de.extend_eq hc).symm ▸ hc, assume s hs, let ⟨s'', hs''₁, hs''₂, hs''₃⟩ := nhds_is_closed hs in let ⟨s', hs'₁, (hs'₂ : e ⁻¹' s' ⊆ f ⁻¹' s'')⟩ := mem_of_nhds hφ hs''₁ in let ⟨t, (ht₁ : t ⊆ φ ∩ s'), ht₂, ht₃⟩ := mem_nhds_sets_iff.mp $ inter_mem_sets hφ hs'₁ in have h₁ : closure (f '' (e ⁻¹' s')) ⊆ s'', by rw [closure_subset_iff_subset_of_is_closed hs''₃, image_subset_iff]; exact hs'₂, have h₂ : t ⊆ de.extend f ⁻¹' closure (f '' (e ⁻¹' t)), from assume b' hb', have nhds b' ≤ principal t, by simp; exact mem_nhds_sets ht₂ hb', have map f (comap e (nhds b')) ≤ nhds (de.extend f b') ⊓ principal (f '' (e ⁻¹' t)), from calc _ ≤ map f (comap e (nhds b' ⊓ principal t)) : map_mono $ comap_mono $ le_inf (le_refl _) this ... ≤ map f (comap e (nhds b')) ⊓ map f (comap e (principal t)) : le_inf (map_mono $ comap_mono $ inf_le_left) (map_mono $ comap_mono $ inf_le_right) ... ≤ map f (comap e (nhds b')) ⊓ principal (f '' (e ⁻¹' t)) : by simp [le_refl] ... ≤ _ : inf_le_inf ((ht₁ hb').left) (le_refl _), show de.extend f b' ∈ closure (f '' (e ⁻¹' t)), begin rw [closure_eq_nhds], apply neq_bot_of_le_neq_bot _ this, simp, exact de.comap_nhds_neq_bot end, (nhds b).sets_of_superset (show t ∈ (nhds b).sets, from mem_nhds_sets ht₂ ht₃) (calc t ⊆ de.extend f ⁻¹' closure (f '' (e ⁻¹' t)) : h₂ ... ⊆ de.extend f ⁻¹' closure (f '' (e ⁻¹' s')) : preimage_mono $ closure_mono $ image_subset f $ preimage_mono $ subset.trans ht₁ $ inter_subset_right _ _ ... ⊆ de.extend f ⁻¹' s'' : preimage_mono h₁ ... ⊆ de.extend f ⁻¹' s : preimage_mono hs''₂) lemma continuous_extend [regular_space γ] {f : α → γ} (de : dense_embedding e) (hf : ∀b, ∃c, tendsto f (comap e (nhds b)) (nhds c)) : continuous (de.extend f) := continuous_iff_tendsto.mpr $ assume b, de.tendsto_extend $ univ_mem_sets' hf end dense_embedding namespace dense_embedding variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] /-- The product of two dense embeddings is a dense embedding -/ protected def prod {e₁ : α → β} {e₂ : γ → δ} (de₁ : dense_embedding e₁) (de₂ : dense_embedding e₂) : dense_embedding (λ(p : α × γ), (e₁ p.1, e₂ p.2)) := { dense_embedding . dense := have closure (range (λ(p : α × γ), (e₁ p.1, e₂ p.2))) = set.prod (closure (range e₁)) (closure (range e₂)), by rw [←closure_prod_eq, prod_range_range_eq], assume ⟨b, d⟩, begin rw [this], simp, constructor, apply de₁.dense, apply de₂.dense end, inj := assume ⟨x₁, x₂⟩ ⟨y₁, y₂⟩, by simp; exact assume h₁ h₂, ⟨de₁.inj h₁, de₂.inj h₂⟩, induced := assume ⟨a, b⟩, by rw [nhds_prod_eq, nhds_prod_eq, ←prod_comap_comap_eq, de₁.induced, de₂.induced] } def subtype_emb (p : α → Prop) {e : α → β} (de : dense_embedding e) (x : {x // p x}) : {x // x ∈ closure (e '' {x | p x})} := ⟨e x.1, subset_closure $ mem_image_of_mem e x.2⟩ protected def subtype (p : α → Prop) {e : α → β} (de : dense_embedding e) : dense_embedding (de.subtype_emb p) := { dense_embedding . dense := assume ⟨x, hx⟩, closure_subtype.mpr $ have (λ (x : {x // p x}), e (x.val)) = e ∘ subtype.val, from rfl, begin rw ← image_univ, simp [(image_comp _ _ _).symm, (∘), subtype_emb, -image_univ], rw [this, image_comp, subtype_val_image], simp, assumption end, inj := assume ⟨x, hx⟩ ⟨y, hy⟩ h, subtype.eq $ de.inj $ @@congr_arg subtype.val h, induced := assume ⟨x, hx⟩, by simp [subtype_emb, nhds_subtype_eq_comap, comap_comap_comp, (∘), (de.induced x).symm] } end dense_embedding lemma is_closed_property [topological_space α] [topological_space β] {e : α → β} {p : β → Prop} (he : closure (range e) = univ) (hp : is_closed {x | p x}) (h : ∀a, p (e a)) : ∀b, p b := have univ ⊆ {b | p b}, from calc univ = closure (range e) : he.symm ... ⊆ closure {b | p b} : closure_mono $ range_subset_iff.mpr h ... = _ : closure_eq_of_is_closed hp, assume b, this trivial lemma is_closed_property2 [topological_space α] [topological_space β] {e : α → β} {p : β → β → Prop} (he : dense_embedding e) (hp : is_closed {q:β×β | p q.1 q.2}) (h : ∀a₁ a₂, p (e a₁) (e a₂)) : ∀b₁ b₂, p b₁ b₂ := have ∀q:β×β, p q.1 q.2, from is_closed_property (he.prod he).closure_range hp $ assume a, h _ _, assume b₁ b₂, this ⟨b₁, b₂⟩ lemma is_closed_property3 [topological_space α] [topological_space β] {e : α → β} {p : β → β → β → Prop} (he : dense_embedding e) (hp : is_closed {q:β×β×β | p q.1 q.2.1 q.2.2}) (h : ∀a₁ a₂ a₃, p (e a₁) (e a₂) (e a₃)) : ∀b₁ b₂ b₃, p b₁ b₂ b₃ := have ∀q:β×β×β, p q.1 q.2.1 q.2.2, from is_closed_property (he.prod $ he.prod he).closure_range hp $ assume ⟨a₁, a₂, a₃⟩, h _ _ _, assume b₁ b₂ b₃, this ⟨b₁, b₂, b₃⟩ lemma mem_closure_of_continuous [topological_space α] [topological_space β] {f : α → β} {a : α} {s : set α} {t : set β} (hf : continuous f) (ha : a ∈ closure s) (h : ∀a∈s, f a ∈ closure t) : f a ∈ closure t := calc f a ∈ f '' closure s : mem_image_of_mem _ ha ... ⊆ closure (f '' s) : image_closure_subset_closure_image hf ... ⊆ closure (closure t) : closure_mono $ image_subset_iff.mpr $ h ... ⊆ closure t : begin rw [closure_eq_of_is_closed], exact subset.refl _, exact is_closed_closure end lemma mem_closure_of_continuous2 [topological_space α] [topological_space β] [topological_space γ] {f : α → β → γ} {a : α} {b : β} {s : set α} {t : set β} {u : set γ} (hf : continuous (λp:α×β, f p.1 p.2)) (ha : a ∈ closure s) (hb : b ∈ closure t) (h : ∀a∈s, ∀b∈t, f a b ∈ closure u) : f a b ∈ closure u := have (a,b) ∈ closure (set.prod s t), by simp [closure_prod_eq, ha, hb], show f (a, b).1 (a, b).2 ∈ closure u, from @mem_closure_of_continuous (α×β) _ _ _ (λp:α×β, f p.1 p.2) (a,b) _ u hf this $ assume ⟨p₁, p₂⟩ ⟨h₁, h₂⟩, h p₁ h₁ p₂ h₂
812abacc7e96a352eae1bb756ea2eca084348ec6
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Lean/Elab/Tactic/Conv/Simp.lean
a3fdedbb967b10ea1e7f586e181dae5b7b0fd96a
[ "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
977
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.Tactic.Simp import Lean.Elab.Tactic.Split import Lean.Elab.Tactic.Conv.Basic namespace Lean.Elab.Tactic.Conv open Meta def applySimpResult (result : Simp.Result) : TacticM Unit := do if result.proof?.isNone then changeLhs result.expr else updateLhs result.expr (← result.getProof) @[builtinTactic Lean.Parser.Tactic.Conv.simp] def evalSimp : Tactic := fun stx => withMainContext do let { ctx, dischargeWrapper, .. } ← mkSimpContext stx (eraseLocal := false) let lhs ← getLhs let result ← dischargeWrapper.with fun d? => simp lhs ctx (discharge? := d?) applySimpResult result @[builtinTactic Lean.Parser.Tactic.Conv.simpMatch] def evalSimpMatch : Tactic := fun _ => withMainContext do applySimpResult (← Split.simpMatch (← getLhs)) end Lean.Elab.Tactic.Conv
d105242e127423bad9b12c007bef409d0d3d6153
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/algebra/group/default.lean
cbbc63b42ffcc8344f080acd5ad2f0cb8f2e0276
[ "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
433
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, Michael Howes -/ import algebra.group.type_tags import algebra.group.conj import algebra.group.with_one import algebra.group.units_hom /-! # Various multiplicative and additive structures. This file `import`s all files in this subdirectory except for `prod`. -/
16a387e36466e4dca913222c5344cef20d8d06ca
5d166a16ae129621cb54ca9dde86c275d7d2b483
/tests/lean/run/dunfold1.lean
9a60f44ed2008a4c1e514f37ea5d63345b8c473a
[ "Apache-2.0" ]
permissive
jcarlson23/lean
b00098763291397e0ac76b37a2dd96bc013bd247
8de88701247f54d325edd46c0eed57aeacb64baf
refs/heads/master
1,611,571,813,719
1,497,020,963,000
1,497,021,515,000
93,882,536
1
0
null
1,497,029,896,000
1,497,029,896,000
null
UTF-8
Lean
false
false
659
lean
open tactic set_option pp.all true def g : nat → nat := λ x, x + 5 example (a b : nat) (p : nat → Prop) (h : p (g (nat.succ (nat.succ a)))) : p (g (a + 2)) := by do t ← target, new_t ← dsimplify (λ e, failed) (λ e, do { new_e ← unfold_projection e, return (new_e, tt) } <|> do { guard ([`add, `nat.add, `one, `zero, `bit0, `bit1]^.any e^.is_app_of), new_e ← dunfold_expr e, trace e, trace "===>", trace new_e, trace "-------", return (new_e, tt) }) t, expected ← to_expr ```(p (g (nat.succ (nat.succ a)))), guard (new_t = expected), trace new_t, assumption
5436fdbb9a64c721782d05328fb6f5a2fdbba596
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/data/nat/gcd.lean
76a5d829e615fdab6f7f71b9da928f7b65ef9fdb
[ "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
18,315
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura -/ import data.nat.pow /-! # Definitions and properties of `gcd`, `lcm`, and `coprime` -/ namespace nat /-! ### `gcd` -/ theorem gcd_dvd (m n : ℕ) : (gcd m n ∣ m) ∧ (gcd m n ∣ n) := gcd.induction m n (λn, by rw gcd_zero_left; exact ⟨dvd_zero n, dvd_refl n⟩) (λm n npos, by rw ←gcd_rec; exact λ ⟨IH₁, IH₂⟩, ⟨IH₂, (dvd_mod_iff IH₂).1 IH₁⟩) theorem gcd_dvd_left (m n : ℕ) : gcd m n ∣ m := (gcd_dvd m n).left theorem gcd_dvd_right (m n : ℕ) : gcd m n ∣ n := (gcd_dvd m n).right theorem gcd_le_left {m} (n) (h : 0 < m) : gcd m n ≤ m := le_of_dvd h $ gcd_dvd_left m n theorem gcd_le_right (m) {n} (h : 0 < n) : gcd m n ≤ n := le_of_dvd h $ gcd_dvd_right m n theorem dvd_gcd {m n k : ℕ} : k ∣ m → k ∣ n → k ∣ gcd m n := gcd.induction m n (λn _ kn, by rw gcd_zero_left; exact kn) (λn m mpos IH H1 H2, by rw gcd_rec; exact IH ((dvd_mod_iff H1).2 H2) H1) theorem dvd_gcd_iff {m n k : ℕ} : k ∣ gcd m n ↔ k ∣ m ∧ k ∣ n := iff.intro (λ h, ⟨h.trans (gcd_dvd m n).left, h.trans (gcd_dvd m n).right⟩) (λ h, dvd_gcd h.left h.right) theorem gcd_comm (m n : ℕ) : gcd m n = gcd n m := dvd_antisymm (dvd_gcd (gcd_dvd_right m n) (gcd_dvd_left m n)) (dvd_gcd (gcd_dvd_right n m) (gcd_dvd_left n m)) theorem gcd_eq_left_iff_dvd {m n : ℕ} : m ∣ n ↔ gcd m n = m := ⟨λ h, by rw [gcd_rec, mod_eq_zero_of_dvd h, gcd_zero_left], λ h, h ▸ gcd_dvd_right m n⟩ theorem gcd_eq_right_iff_dvd {m n : ℕ} : m ∣ n ↔ gcd n m = m := by rw gcd_comm; apply gcd_eq_left_iff_dvd theorem gcd_assoc (m n k : ℕ) : gcd (gcd m n) k = gcd m (gcd n k) := dvd_antisymm (dvd_gcd ((gcd_dvd_left (gcd m n) k).trans (gcd_dvd_left m n)) (dvd_gcd ((gcd_dvd_left (gcd m n) k).trans (gcd_dvd_right m n)) (gcd_dvd_right (gcd m n) k))) (dvd_gcd (dvd_gcd (gcd_dvd_left m (gcd n k)) ((gcd_dvd_right m (gcd n k)).trans (gcd_dvd_left n k))) ((gcd_dvd_right m (gcd n k)).trans (gcd_dvd_right n k))) @[simp] theorem gcd_one_right (n : ℕ) : gcd n 1 = 1 := eq.trans (gcd_comm n 1) $ gcd_one_left n theorem gcd_mul_left (m n k : ℕ) : gcd (m * n) (m * k) = m * gcd n k := gcd.induction n k (λk, by repeat {rw mul_zero <|> rw gcd_zero_left}) (λk n H IH, by rwa [←mul_mod_mul_left, ←gcd_rec, ←gcd_rec] at IH) theorem gcd_mul_right (m n k : ℕ) : gcd (m * n) (k * n) = gcd m k * n := by rw [mul_comm m n, mul_comm k n, mul_comm (gcd m k) n, gcd_mul_left] theorem gcd_pos_of_pos_left {m : ℕ} (n : ℕ) (mpos : 0 < m) : 0 < gcd m n := pos_of_dvd_of_pos (gcd_dvd_left m n) mpos theorem gcd_pos_of_pos_right (m : ℕ) {n : ℕ} (npos : 0 < n) : 0 < gcd m n := pos_of_dvd_of_pos (gcd_dvd_right m n) npos theorem eq_zero_of_gcd_eq_zero_left {m n : ℕ} (H : gcd m n = 0) : m = 0 := or.elim (nat.eq_zero_or_pos m) id (assume H1 : 0 < m, absurd (eq.symm H) (ne_of_lt (gcd_pos_of_pos_left _ H1))) theorem eq_zero_of_gcd_eq_zero_right {m n : ℕ} (H : gcd m n = 0) : n = 0 := by rw gcd_comm at H; exact eq_zero_of_gcd_eq_zero_left H theorem gcd_div {m n k : ℕ} (H1 : k ∣ m) (H2 : k ∣ n) : gcd (m / k) (n / k) = gcd m n / k := or.elim (nat.eq_zero_or_pos k) (λk0, by rw [k0, nat.div_zero, nat.div_zero, nat.div_zero, gcd_zero_right]) (λH3, nat.eq_of_mul_eq_mul_right H3 $ by rw [ nat.div_mul_cancel (dvd_gcd H1 H2), ←gcd_mul_right, nat.div_mul_cancel H1, nat.div_mul_cancel H2]) theorem gcd_dvd_gcd_of_dvd_left {m k : ℕ} (n : ℕ) (H : m ∣ k) : gcd m n ∣ gcd k n := dvd_gcd ((gcd_dvd_left m n).trans H) (gcd_dvd_right m n) theorem gcd_dvd_gcd_of_dvd_right {m k : ℕ} (n : ℕ) (H : m ∣ k) : gcd n m ∣ gcd n k := dvd_gcd (gcd_dvd_left n m) ((gcd_dvd_right n m).trans H) theorem gcd_dvd_gcd_mul_left (m n k : ℕ) : gcd m n ∣ gcd (k * m) n := gcd_dvd_gcd_of_dvd_left _ (dvd_mul_left _ _) theorem gcd_dvd_gcd_mul_right (m n k : ℕ) : gcd m n ∣ gcd (m * k) n := gcd_dvd_gcd_of_dvd_left _ (dvd_mul_right _ _) theorem gcd_dvd_gcd_mul_left_right (m n k : ℕ) : gcd m n ∣ gcd m (k * n) := gcd_dvd_gcd_of_dvd_right _ (dvd_mul_left _ _) theorem gcd_dvd_gcd_mul_right_right (m n k : ℕ) : gcd m n ∣ gcd m (n * k) := gcd_dvd_gcd_of_dvd_right _ (dvd_mul_right _ _) theorem gcd_eq_left {m n : ℕ} (H : m ∣ n) : gcd m n = m := dvd_antisymm (gcd_dvd_left _ _) (dvd_gcd dvd_rfl H) theorem gcd_eq_right {m n : ℕ} (H : n ∣ m) : gcd m n = n := by rw [gcd_comm, gcd_eq_left H] @[simp] lemma gcd_mul_left_left (m n : ℕ) : gcd (m * n) n = n := dvd_antisymm (gcd_dvd_right _ _) (dvd_gcd (dvd_mul_left _ _) dvd_rfl) @[simp] lemma gcd_mul_left_right (m n : ℕ) : gcd n (m * n) = n := by rw [gcd_comm, gcd_mul_left_left] @[simp] lemma gcd_mul_right_left (m n : ℕ) : gcd (n * m) n = n := by rw [mul_comm, gcd_mul_left_left] @[simp] lemma gcd_mul_right_right (m n : ℕ) : gcd n (n * m) = n := by rw [gcd_comm, gcd_mul_right_left] @[simp] lemma gcd_gcd_self_right_left (m n : ℕ) : gcd m (gcd m n) = gcd m n := dvd_antisymm (gcd_dvd_right _ _) (dvd_gcd (gcd_dvd_left _ _) dvd_rfl) @[simp] lemma gcd_gcd_self_right_right (m n : ℕ) : gcd m (gcd n m) = gcd n m := by rw [gcd_comm n m, gcd_gcd_self_right_left] @[simp] lemma gcd_gcd_self_left_right (m n : ℕ) : gcd (gcd n m) m = gcd n m := by rw [gcd_comm, gcd_gcd_self_right_right] @[simp] lemma gcd_gcd_self_left_left (m n : ℕ) : gcd (gcd m n) m = gcd m n := by rw [gcd_comm m n, gcd_gcd_self_left_right] lemma gcd_add_mul_self (m n k : ℕ) : gcd m (n + k * m) = gcd m n := by simp [gcd_rec m (n + k * m), gcd_rec m n] theorem gcd_eq_zero_iff {i j : ℕ} : gcd i j = 0 ↔ i = 0 ∧ j = 0 := begin split, { intro h, exact ⟨eq_zero_of_gcd_eq_zero_left h, eq_zero_of_gcd_eq_zero_right h⟩, }, { intro h, rw [h.1, h.2], exact nat.gcd_zero_right _ } end /-! ### `lcm` -/ theorem lcm_comm (m n : ℕ) : lcm m n = lcm n m := by delta lcm; rw [mul_comm, gcd_comm] @[simp] theorem lcm_zero_left (m : ℕ) : lcm 0 m = 0 := by delta lcm; rw [zero_mul, nat.zero_div] @[simp] theorem lcm_zero_right (m : ℕ) : lcm m 0 = 0 := lcm_comm 0 m ▸ lcm_zero_left m @[simp] theorem lcm_one_left (m : ℕ) : lcm 1 m = m := by delta lcm; rw [one_mul, gcd_one_left, nat.div_one] @[simp] theorem lcm_one_right (m : ℕ) : lcm m 1 = m := lcm_comm 1 m ▸ lcm_one_left m @[simp] theorem lcm_self (m : ℕ) : lcm m m = m := or.elim (nat.eq_zero_or_pos m) (λh, by rw [h, lcm_zero_left]) (λh, by delta lcm; rw [gcd_self, nat.mul_div_cancel _ h]) theorem dvd_lcm_left (m n : ℕ) : m ∣ lcm m n := dvd.intro (n / gcd m n) (nat.mul_div_assoc _ $ gcd_dvd_right m n).symm theorem dvd_lcm_right (m n : ℕ) : n ∣ lcm m n := lcm_comm n m ▸ dvd_lcm_left n m theorem gcd_mul_lcm (m n : ℕ) : gcd m n * lcm m n = m * n := by delta lcm; rw [nat.mul_div_cancel' ((gcd_dvd_left m n).trans (dvd_mul_right m n))] theorem lcm_dvd {m n k : ℕ} (H1 : m ∣ k) (H2 : n ∣ k) : lcm m n ∣ k := or.elim (nat.eq_zero_or_pos k) (λh, by rw h; exact dvd_zero _) (λkpos, dvd_of_mul_dvd_mul_left (gcd_pos_of_pos_left n (pos_of_dvd_of_pos H1 kpos)) $ by rw [gcd_mul_lcm, ←gcd_mul_right, mul_comm n k]; exact dvd_gcd (mul_dvd_mul_left _ H2) (mul_dvd_mul_right H1 _)) lemma lcm_dvd_iff {m n k : ℕ} : lcm m n ∣ k ↔ m ∣ k ∧ n ∣ k := ⟨λ h, ⟨(dvd_lcm_left _ _).trans h, (dvd_lcm_right _ _).trans h⟩, and_imp.2 lcm_dvd⟩ theorem lcm_assoc (m n k : ℕ) : lcm (lcm m n) k = lcm m (lcm n k) := dvd_antisymm (lcm_dvd (lcm_dvd (dvd_lcm_left m (lcm n k)) ((dvd_lcm_left n k).trans (dvd_lcm_right m (lcm n k)))) ((dvd_lcm_right n k).trans (dvd_lcm_right m (lcm n k)))) (lcm_dvd ((dvd_lcm_left m n).trans (dvd_lcm_left (lcm m n) k)) (lcm_dvd ((dvd_lcm_right m n).trans (dvd_lcm_left (lcm m n) k)) (dvd_lcm_right (lcm m n) k))) theorem lcm_ne_zero {m n : ℕ} (hm : m ≠ 0) (hn : n ≠ 0) : lcm m n ≠ 0 := by { intro h, simpa [h, hm, hn] using gcd_mul_lcm m n, } /-! ### `coprime` See also `nat.coprime_of_dvd` and `nat.coprime_of_dvd'` to prove `nat.coprime m n`. -/ instance (m n : ℕ) : decidable (coprime m n) := by unfold coprime; apply_instance theorem coprime_iff_gcd_eq_one {m n : ℕ} : coprime m n ↔ gcd m n = 1 := iff.rfl theorem coprime.gcd_eq_one {m n : ℕ} (h : coprime m n) : gcd m n = 1 := h theorem coprime.lcm_eq_mul {m n : ℕ} (h : coprime m n) : lcm m n = m * n := by rw [←one_mul (lcm m n), ←h.gcd_eq_one, gcd_mul_lcm] theorem coprime.symm {m n : ℕ} : coprime n m → coprime m n := (gcd_comm m n).trans theorem coprime_comm {m n : ℕ} : coprime n m ↔ coprime m n := ⟨coprime.symm, coprime.symm⟩ theorem coprime.dvd_of_dvd_mul_right {m n k : ℕ} (H1 : coprime k n) (H2 : k ∣ m * n) : k ∣ m := let t := dvd_gcd (dvd_mul_left k m) H2 in by rwa [gcd_mul_left, H1.gcd_eq_one, mul_one] at t theorem coprime.dvd_of_dvd_mul_left {m n k : ℕ} (H1 : coprime k m) (H2 : k ∣ m * n) : k ∣ n := by rw mul_comm at H2; exact H1.dvd_of_dvd_mul_right H2 theorem coprime.dvd_mul_right {m n k : ℕ} (H : coprime k n) : k ∣ m * n ↔ k ∣ m := ⟨H.dvd_of_dvd_mul_right, λ h, dvd_mul_of_dvd_left h n⟩ theorem coprime.dvd_mul_left {m n k : ℕ} (H : coprime k m) : k ∣ m * n ↔ k ∣ n := ⟨H.dvd_of_dvd_mul_left, λ h, dvd_mul_of_dvd_right h m⟩ theorem coprime.gcd_mul_left_cancel {k : ℕ} (m : ℕ) {n : ℕ} (H : coprime k n) : gcd (k * m) n = gcd m n := have H1 : coprime (gcd (k * m) n) k, by rw [coprime, gcd_assoc, H.symm.gcd_eq_one, gcd_one_right], dvd_antisymm (dvd_gcd (H1.dvd_of_dvd_mul_left (gcd_dvd_left _ _)) (gcd_dvd_right _ _)) (gcd_dvd_gcd_mul_left _ _ _) theorem coprime.gcd_mul_right_cancel (m : ℕ) {k n : ℕ} (H : coprime k n) : gcd (m * k) n = gcd m n := by rw [mul_comm m k, H.gcd_mul_left_cancel m] theorem coprime.gcd_mul_left_cancel_right {k m : ℕ} (n : ℕ) (H : coprime k m) : gcd m (k * n) = gcd m n := by rw [gcd_comm m n, gcd_comm m (k * n), H.gcd_mul_left_cancel n] theorem coprime.gcd_mul_right_cancel_right {k m : ℕ} (n : ℕ) (H : coprime k m) : gcd m (n * k) = gcd m n := by rw [mul_comm n k, H.gcd_mul_left_cancel_right n] theorem coprime_div_gcd_div_gcd {m n : ℕ} (H : 0 < gcd m n) : coprime (m / gcd m n) (n / gcd m n) := by rw [coprime_iff_gcd_eq_one, gcd_div (gcd_dvd_left m n) (gcd_dvd_right m n), nat.div_self H] theorem not_coprime_of_dvd_of_dvd {m n d : ℕ} (dgt1 : 1 < d) (Hm : d ∣ m) (Hn : d ∣ n) : ¬ coprime m n := λ co, not_lt_of_ge (le_of_dvd zero_lt_one $ by rw [←co.gcd_eq_one]; exact dvd_gcd Hm Hn) dgt1 theorem exists_coprime {m n : ℕ} (H : 0 < gcd m n) : ∃ m' n', coprime m' n' ∧ m = m' * gcd m n ∧ n = n' * gcd m n := ⟨_, _, coprime_div_gcd_div_gcd H, (nat.div_mul_cancel (gcd_dvd_left m n)).symm, (nat.div_mul_cancel (gcd_dvd_right m n)).symm⟩ theorem exists_coprime' {m n : ℕ} (H : 0 < gcd m n) : ∃ g m' n', 0 < g ∧ coprime m' n' ∧ m = m' * g ∧ n = n' * g := let ⟨m', n', h⟩ := exists_coprime H in ⟨_, m', n', H, h⟩ theorem coprime.mul {m n k : ℕ} (H1 : coprime m k) (H2 : coprime n k) : coprime (m * n) k := (H1.gcd_mul_left_cancel n).trans H2 theorem coprime.mul_right {k m n : ℕ} (H1 : coprime k m) (H2 : coprime k n) : coprime k (m * n) := (H1.symm.mul H2.symm).symm theorem coprime.coprime_dvd_left {m k n : ℕ} (H1 : m ∣ k) (H2 : coprime k n) : coprime m n := eq_one_of_dvd_one (by delta coprime at H2; rw ← H2; exact gcd_dvd_gcd_of_dvd_left _ H1) theorem coprime.coprime_dvd_right {m k n : ℕ} (H1 : n ∣ m) (H2 : coprime k m) : coprime k n := (H2.symm.coprime_dvd_left H1).symm theorem coprime.coprime_mul_left {k m n : ℕ} (H : coprime (k * m) n) : coprime m n := H.coprime_dvd_left (dvd_mul_left _ _) theorem coprime.coprime_mul_right {k m n : ℕ} (H : coprime (m * k) n) : coprime m n := H.coprime_dvd_left (dvd_mul_right _ _) theorem coprime.coprime_mul_left_right {k m n : ℕ} (H : coprime m (k * n)) : coprime m n := H.coprime_dvd_right (dvd_mul_left _ _) theorem coprime.coprime_mul_right_right {k m n : ℕ} (H : coprime m (n * k)) : coprime m n := H.coprime_dvd_right (dvd_mul_right _ _) theorem coprime.coprime_div_left {m n a : ℕ} (cmn : coprime m n) (dvd : a ∣ m) : coprime (m / a) n := begin by_cases a_split : (a = 0), { subst a_split, rw zero_dvd_iff at dvd, simpa [dvd] using cmn, }, { rcases dvd with ⟨k, rfl⟩, rw nat.mul_div_cancel_left _ (nat.pos_of_ne_zero a_split), exact coprime.coprime_mul_left cmn, }, end theorem coprime.coprime_div_right {m n a : ℕ} (cmn : coprime m n) (dvd : a ∣ n) : coprime m (n / a) := (coprime.coprime_div_left cmn.symm dvd).symm lemma coprime_mul_iff_left {k m n : ℕ} : coprime (m * n) k ↔ coprime m k ∧ coprime n k := ⟨λ h, ⟨coprime.coprime_mul_right h, coprime.coprime_mul_left h⟩, λ ⟨h, _⟩, by rwa [coprime_iff_gcd_eq_one, coprime.gcd_mul_left_cancel n h]⟩ lemma coprime_mul_iff_right {k m n : ℕ} : coprime k (m * n) ↔ coprime k m ∧ coprime k n := by simpa only [coprime_comm] using coprime_mul_iff_left lemma coprime.gcd_left (k : ℕ) {m n : ℕ} (hmn : coprime m n) : coprime (gcd k m) n := hmn.coprime_dvd_left $ gcd_dvd_right k m lemma coprime.gcd_right (k : ℕ) {m n : ℕ} (hmn : coprime m n) : coprime m (gcd k n) := hmn.coprime_dvd_right $ gcd_dvd_right k n lemma coprime.gcd_both (k l : ℕ) {m n : ℕ} (hmn : coprime m n) : coprime (gcd k m) (gcd l n) := (hmn.gcd_left k).gcd_right l lemma coprime.mul_dvd_of_dvd_of_dvd {a n m : ℕ} (hmn : coprime m n) (hm : m ∣ a) (hn : n ∣ a) : m * n ∣ a := let ⟨k, hk⟩ := hm in hk.symm ▸ mul_dvd_mul_left _ (hmn.symm.dvd_of_dvd_mul_left (hk ▸ hn)) theorem coprime_one_left : ∀ n, coprime 1 n := gcd_one_left theorem coprime_one_right : ∀ n, coprime n 1 := gcd_one_right theorem coprime.pow_left {m k : ℕ} (n : ℕ) (H1 : coprime m k) : coprime (m ^ n) k := nat.rec_on n (coprime_one_left _) (λn IH, H1.mul IH) theorem coprime.pow_right {m k : ℕ} (n : ℕ) (H1 : coprime k m) : coprime k (m ^ n) := (H1.symm.pow_left n).symm theorem coprime.pow {k l : ℕ} (m n : ℕ) (H1 : coprime k l) : coprime (k ^ m) (l ^ n) := (H1.pow_left _).pow_right _ lemma coprime_pow_left_iff {n : ℕ} (hn : 0 < n) (a b : ℕ) : nat.coprime (a ^ n) b ↔ nat.coprime a b := begin obtain ⟨n, rfl⟩ := exists_eq_succ_of_ne_zero hn.ne', rw [pow_succ, nat.coprime_mul_iff_left], exact ⟨and.left, λ hab, ⟨hab, hab.pow_left _⟩⟩ end lemma coprime_pow_right_iff {n : ℕ} (hn : 0 < n) (a b : ℕ) : nat.coprime a (b ^ n) ↔ nat.coprime a b := by rw [nat.coprime_comm, coprime_pow_left_iff hn, nat.coprime_comm] theorem coprime.eq_one_of_dvd {k m : ℕ} (H : coprime k m) (d : k ∣ m) : k = 1 := by rw [← H.gcd_eq_one, gcd_eq_left d] @[simp] theorem coprime_zero_left (n : ℕ) : coprime 0 n ↔ n = 1 := by simp [coprime] @[simp] theorem coprime_zero_right (n : ℕ) : coprime n 0 ↔ n = 1 := by simp [coprime] theorem not_coprime_zero_zero : ¬ coprime 0 0 := by simp @[simp] theorem coprime_one_left_iff (n : ℕ) : coprime 1 n ↔ true := by simp [coprime] @[simp] theorem coprime_one_right_iff (n : ℕ) : coprime n 1 ↔ true := by simp [coprime] @[simp] theorem coprime_self (n : ℕ) : coprime n n ↔ n = 1 := by simp [coprime] lemma coprime.eq_of_mul_eq_zero {m n : ℕ} (h : m.coprime n) (hmn : m * n = 0) : m = 0 ∧ n = 1 ∨ m = 1 ∧ n = 0 := (nat.eq_zero_of_mul_eq_zero hmn).imp (λ hm, ⟨hm, n.coprime_zero_left.mp $ hm ▸ h⟩) (λ hn, ⟨m.coprime_zero_left.mp $ hn ▸ h.symm, hn⟩) /-- Represent a divisor of `m * n` as a product of a divisor of `m` and a divisor of `n`. -/ def prod_dvd_and_dvd_of_dvd_prod {m n k : ℕ} (H : k ∣ m * n) : { d : {m' // m' ∣ m} × {n' // n' ∣ n} // k = d.1 * d.2 } := begin cases h0 : (gcd k m), case nat.zero { have : k = 0 := eq_zero_of_gcd_eq_zero_left h0, subst this, have : m = 0 := eq_zero_of_gcd_eq_zero_right h0, subst this, exact ⟨⟨⟨0, dvd_refl 0⟩, ⟨n, dvd_refl n⟩⟩, (zero_mul n).symm⟩ }, case nat.succ : tmp { have hpos : 0 < gcd k m := h0.symm ▸ nat.zero_lt_succ _; clear h0 tmp, have hd : gcd k m * (k / gcd k m) = k := (nat.mul_div_cancel' (gcd_dvd_left k m)), refine ⟨⟨⟨gcd k m, gcd_dvd_right k m⟩, ⟨k / gcd k m, _⟩⟩, hd.symm⟩, apply dvd_of_mul_dvd_mul_left hpos, rw [hd, ← gcd_mul_right], exact dvd_gcd (dvd_mul_right _ _) H } end theorem gcd_mul_dvd_mul_gcd (k m n : ℕ) : gcd k (m * n) ∣ gcd k m * gcd k n := begin rcases (prod_dvd_and_dvd_of_dvd_prod $ gcd_dvd_right k (m * n)) with ⟨⟨⟨m', hm'⟩, ⟨n', hn'⟩⟩, h⟩, replace h : gcd k (m * n) = m' * n' := h, rw h, have hm'n' : m' * n' ∣ k := h ▸ gcd_dvd_left _ _, apply mul_dvd_mul, { have hm'k : m' ∣ k := (dvd_mul_right m' n').trans hm'n', exact dvd_gcd hm'k hm' }, { have hn'k : n' ∣ k := (dvd_mul_left n' m').trans hm'n', exact dvd_gcd hn'k hn' } end theorem coprime.gcd_mul (k : ℕ) {m n : ℕ} (h : coprime m n) : gcd k (m * n) = gcd k m * gcd k n := dvd_antisymm (gcd_mul_dvd_mul_gcd k m n) ((h.gcd_both k k).mul_dvd_of_dvd_of_dvd (gcd_dvd_gcd_mul_right_right _ _ _) (gcd_dvd_gcd_mul_left_right _ _ _)) theorem pow_dvd_pow_iff {a b n : ℕ} (n0 : 0 < n) : a ^ n ∣ b ^ n ↔ a ∣ b := begin refine ⟨λ h, _, λ h, pow_dvd_pow_of_dvd h _⟩, cases nat.eq_zero_or_pos (gcd a b) with g0 g0, { simp [eq_zero_of_gcd_eq_zero_right g0] }, rcases exists_coprime' g0 with ⟨g, a', b', g0', co, rfl, rfl⟩, rw [mul_pow, mul_pow] at h, replace h := dvd_of_mul_dvd_mul_right (pow_pos g0' _) h, have := pow_dvd_pow a' n0, rw [pow_one, (co.pow n n).eq_one_of_dvd h] at this, simp [eq_one_of_dvd_one this] end lemma gcd_mul_gcd_of_coprime_of_mul_eq_mul {a b c d : ℕ} (cop : c.coprime d) (h : a * b = c * d) : a.gcd c * b.gcd c = c := begin apply dvd_antisymm, { apply nat.coprime.dvd_of_dvd_mul_right (nat.coprime.mul (cop.gcd_left _) (cop.gcd_left _)), rw ← h, apply mul_dvd_mul (gcd_dvd _ _).1 (gcd_dvd _ _).1 }, { rw [gcd_comm a _, gcd_comm b _], transitivity c.gcd (a * b), rw [h, gcd_mul_right_right d c], apply gcd_mul_dvd_mul_gcd } end end nat
236f85ba878089fad2a928b27b6a5c81c57ee68e
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/analysis/normed_space/star.lean
9a2e48aee08c357821adb1567ecb70feb8180677
[ "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
3,411
lean
/- Copyright (c) 2021 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 analysis.normed_space.linear_isometry /-! # Normed star rings and algebras A normed star monoid is a `star_add_monoid` endowed with a norm such that the star operation is isometric. A C⋆-ring is a normed star monoid that is also a ring and that verifies the stronger condition `∥x⋆ * x∥ = ∥x∥^2` for all `x`. If a C⋆-ring is also a star algebra, then it is a C⋆-algebra. To get a C⋆-algebra `E` over field `𝕜`, use `[normed_field 𝕜] [star_ring 𝕜] [normed_ring E] [star_ring E] [cstar_ring E] [normed_algebra 𝕜 E] [star_module 𝕜 E]`. ## TODO - Show that `∥x⋆ * x∥ = ∥x∥^2` is equivalent to `∥x⋆ * x∥ = ∥x⋆∥ * ∥x∥`, which is used as the definition of C*-algebras in some sources (e.g. Wikipedia). -/ local postfix `⋆`:1000 := star /-- A normed star ring is a star ring endowed with a norm such that `star` is isometric. -/ class normed_star_monoid (E : Type*) [normed_group E] [star_add_monoid E] := (norm_star : ∀ {x : E}, ∥x⋆∥ = ∥x∥) export normed_star_monoid (norm_star) attribute [simp] norm_star /-- A C*-ring is a normed star ring that satifies the stronger condition `∥x⋆ * x∥ = ∥x∥^2` for every `x`. -/ class cstar_ring (E : Type*) [normed_ring E] [star_ring E] := (norm_star_mul_self : ∀ {x : E}, ∥x⋆ * x∥ = ∥x∥ * ∥x∥) variables {𝕜 E : Type*} open cstar_ring /-- In a C*-ring, star preserves the norm. -/ @[priority 100] -- see Note [lower instance priority] instance cstar_ring.to_normed_star_monoid {E : Type*} [normed_ring E] [star_ring E] [cstar_ring E] : normed_star_monoid E := ⟨begin intro x, by_cases htriv : x = 0, { simp only [htriv, star_zero] }, { have hnt : 0 < ∥x∥ := norm_pos_iff.mpr htriv, have hnt_star : 0 < ∥x⋆∥ := norm_pos_iff.mpr ((add_equiv.map_ne_zero_iff star_add_equiv).mpr htriv), have h₁ := calc ∥x∥ * ∥x∥ = ∥x⋆ * x∥ : norm_star_mul_self.symm ... ≤ ∥x⋆∥ * ∥x∥ : norm_mul_le _ _, have h₂ := calc ∥x⋆∥ * ∥x⋆∥ = ∥x * x⋆∥ : by rw [←norm_star_mul_self, star_star] ... ≤ ∥x∥ * ∥x⋆∥ : norm_mul_le _ _, exact le_antisymm (le_of_mul_le_mul_right h₂ hnt_star) (le_of_mul_le_mul_right h₁ hnt) }, end⟩ lemma cstar_ring.norm_self_mul_star [normed_ring E] [star_ring E] [cstar_ring E] {x : E} : ∥x * x⋆∥ = ∥x∥ * ∥x∥ := by { nth_rewrite 0 [←star_star x], simp only [norm_star_mul_self, norm_star] } lemma cstar_ring.norm_star_mul_self' [normed_ring E] [star_ring E] [cstar_ring E] {x : E} : ∥x⋆ * x∥ = ∥x⋆∥ * ∥x∥ := by rw [norm_star_mul_self, norm_star] section starₗᵢ variables [comm_semiring 𝕜] [star_ring 𝕜] [normed_ring E] [star_ring E] [normed_star_monoid E] variables [module 𝕜 E] [star_module 𝕜 E] variables (𝕜) /-- `star` bundled as a linear isometric equivalence -/ def starₗᵢ : E ≃ₗᵢ⋆[𝕜] E := { map_smul' := star_smul, norm_map' := λ x, norm_star, .. star_add_equiv } variables {𝕜} @[simp] lemma coe_starₗᵢ : (starₗᵢ 𝕜 : E → E) = star := rfl lemma starₗᵢ_apply {x : E} : starₗᵢ 𝕜 x = star x := rfl end starₗᵢ
c77a0f2e560ddeec85a3688ba65871f64b85a72d
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/data/option/defs.lean
ddfcba4db956985b201cd500902618341ff87798
[ "Apache-2.0" ]
permissive
keeferrowan/mathlib
f2818da875dbc7780830d09bd4c526b0764a4e50
aad2dfc40e8e6a7e258287a7c1580318e865817e
refs/heads/master
1,661,736,426,952
1,590,438,032,000
1,590,438,032,000
266,892,663
0
0
Apache-2.0
1,590,445,835,000
1,590,445,835,000
null
UTF-8
Lean
false
false
4,750
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Extra definitions on option. -/ namespace option variables {α : Type*} {β : Type*} attribute [inline] option.is_some option.is_none /-- An elimination principle for `option`. It is a nondependent version of `option.rec_on`. -/ protected def elim : option α → β → (α → β) → β | (some x) y f := f x | none y f := y instance has_mem : has_mem α (option α) := ⟨λ a b, b = some a⟩ @[simp] theorem mem_def {a : α} {b : option α} : a ∈ b ↔ b = some a := iff.rfl theorem is_none_iff_eq_none {o : option α} : o.is_none = tt ↔ o = none := ⟨option.eq_none_of_is_none, λ e, e.symm ▸ rfl⟩ theorem some_inj {a b : α} : some a = some b ↔ a = b := by simp /-- `o = none` is decidable even if the wrapped type does not have decidable equality. This is not an instance because it is not definitionally equal to `option.decidable_eq`. Try to use `o.is_none` or `o.is_some` instead. -/ @[inline] def decidable_eq_none {o : option α} : decidable (o = none) := decidable_of_decidable_of_iff (bool.decidable_eq _ _) is_none_iff_eq_none instance decidable_forall_mem {p : α → Prop} [decidable_pred p] : ∀ o : option α, decidable (∀ a ∈ o, p a) | none := is_true (by simp) | (some a) := if h : p a then is_true $ λ o e, some_inj.1 e ▸ h else is_false $ mt (λ H, H _ rfl) h instance decidable_exists_mem {p : α → Prop} [decidable_pred p] : ∀ o : option α, decidable (∃ a ∈ o, p a) | none := is_false (λ ⟨a, ⟨h, _⟩⟩, by cases h) | (some a) := if h : p a then is_true $ ⟨_, rfl, h⟩ else is_false $ λ ⟨_, ⟨rfl, hn⟩⟩, h hn /-- inhabited `get` function. Returns `a` if the input is `some a`, otherwise returns `default`. -/ @[reducible] def iget [inhabited α] : option α → α | (some x) := x | none := default α @[simp] theorem iget_some [inhabited α] {a : α} : (some a).iget = a := rfl /-- `guard p a` returns `some a` if `p a` holds, otherwise `none`. -/ def guard (p : α → Prop) [decidable_pred p] (a : α) : option α := if p a then some a else none /-- `filter p o` returns `some a` if `o` is `some a` and `p a` holds, otherwise `none`. -/ def filter (p : α → Prop) [decidable_pred p] (o : option α) : option α := o.bind (guard p) def to_list : option α → list α | none := [] | (some a) := [a] @[simp] theorem mem_to_list {a : α} {o : option α} : a ∈ to_list o ↔ a ∈ o := by cases o; simp [to_list, eq_comm] def lift_or_get (f : α → α → α) : option α → option α → option α | none none := none | (some a) none := some a -- get a | none (some b) := some b -- get b | (some a) (some b) := some (f a b) -- lift f instance lift_or_get_comm (f : α → α → α) [h : is_commutative α f] : is_commutative (option α) (lift_or_get f) := ⟨λ a b, by cases a; cases b; simp [lift_or_get, h.comm]⟩ instance lift_or_get_assoc (f : α → α → α) [h : is_associative α f] : is_associative (option α) (lift_or_get f) := ⟨λ a b c, by cases a; cases b; cases c; simp [lift_or_get, h.assoc]⟩ instance lift_or_get_idem (f : α → α → α) [h : is_idempotent α f] : is_idempotent (option α) (lift_or_get f) := ⟨λ a, by cases a; simp [lift_or_get, h.idempotent]⟩ instance lift_or_get_is_left_id (f : α → α → α) : is_left_id (option α) (lift_or_get f) none := ⟨λ a, by cases a; simp [lift_or_get]⟩ instance lift_or_get_is_right_id (f : α → α → α) : is_right_id (option α) (lift_or_get f) none := ⟨λ a, by cases a; simp [lift_or_get]⟩ inductive rel (r : α → β → Prop) : option α → option β → Prop | some {a b} : r a b → rel (some a) (some b) | none : rel none none protected def {u v} traverse {F : Type u → Type v} [applicative F] {α β : Type*} (f : α → F β) : option α → F (option β) | none := pure none | (some x) := some <$> f x /- By analogy with `monad.sequence` in `init/category/combinators.lean`. -/ /-- If you maybe have a monadic computation in a `[monad m]` which produces a term of type `α`, then there is a naturally associated way to always perform a computation in `m` which maybe produces a result. -/ def {u v} maybe {m : Type u → Type v} [monad m] {α : Type u} : option (m α) → m (option α) | none := return none | (some fn) := some <$> fn /-- Map a monadic function `f : α → m β` over an `o : option α`, maybe producing a result. -/ def {u v w} mmap {m : Type u → Type v} [monad m] {α : Type w} {β : Type u} (f : α → m β) (o : option α) : m (option β) := (o.map f).maybe end option
f9a659e5f96c7bf95031fb798a0ad0d63a21a5fb
9dc8cecdf3c4634764a18254e94d43da07142918
/src/probability/integration.lean
1612be45178b897ed33fcb17b83b1d8b0a26e09f
[ "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
17,839
lean
/- Copyright (c) 2021 Martin Zinkevich. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Martin Zinkevich, Vincent Beffara -/ import measure_theory.integral.set_integral import probability.independence /-! # Integration in Probability Theory Integration results for independent random variables. Specifically, for two independent random variables X and Y over the extended non-negative reals, `E[X * Y] = E[X] * E[Y]`, and similar results. ## Implementation notes Many lemmas in this file take two arguments of the same typeclass. It is worth remembering that lean will always pick the later typeclass in this situation, and does not care whether the arguments are `[]`, `{}`, or `()`. All of these use the `measurable_space` `M2` to define `μ`: ```lean example {M1 : measurable_space Ω} [M2 : measurable_space Ω] {μ : measure Ω} : sorry := sorry example [M1 : measurable_space Ω] {M2 : measurable_space Ω} {μ : measure Ω} : sorry := sorry ``` -/ noncomputable theory open set measure_theory open_locale ennreal measure_theory variables {Ω : Type*} {mΩ : measurable_space Ω} {μ : measure Ω} {f g : Ω → ℝ≥0∞} {X Y : Ω → ℝ} namespace probability_theory /-- If a random variable `f` in `ℝ≥0∞` is independent of an event `T`, then if you restrict the random variable to `T`, then `E[f * indicator T c 0]=E[f] * E[indicator T c 0]`. It is useful for `lintegral_mul_eq_lintegral_mul_lintegral_of_independent_measurable_space`. -/ lemma lintegral_mul_indicator_eq_lintegral_mul_lintegral_indicator {Mf mΩ : measurable_space Ω} {μ : measure Ω} (hMf : Mf ≤ mΩ) (c : ℝ≥0∞) {T : set Ω} (h_meas_T : measurable_set T) (h_ind : indep_sets {s | measurable_set[Mf] s} {T} μ) (h_meas_f : measurable[Mf] f) : ∫⁻ ω, f ω * T.indicator (λ _, c) ω ∂μ = ∫⁻ ω, f ω ∂μ * ∫⁻ ω, T.indicator (λ _, c) ω ∂μ := begin revert f, have h_mul_indicator : ∀ g, measurable g → measurable (λ a, g a * T.indicator (λ x, c) a), from λ g h_mg, h_mg.mul (measurable_const.indicator h_meas_T), apply measurable.ennreal_induction, { intros c' s' h_meas_s', simp_rw [← inter_indicator_mul], rw [lintegral_indicator _ (measurable_set.inter (hMf _ h_meas_s') (h_meas_T)), lintegral_indicator _ (hMf _ h_meas_s'), lintegral_indicator _ h_meas_T], simp only [measurable_const, lintegral_const, univ_inter, lintegral_const_mul, measurable_set.univ, measure.restrict_apply], ring_nf, congr, rw [mul_comm, h_ind s' T h_meas_s' (set.mem_singleton _)], }, { intros f' g h_univ h_meas_f' h_meas_g h_ind_f' h_ind_g, have h_measM_f' : measurable f', from h_meas_f'.mono hMf le_rfl, have h_measM_g : measurable g, from h_meas_g.mono hMf le_rfl, simp_rw [pi.add_apply, right_distrib], rw [lintegral_add_left (h_mul_indicator _ h_measM_f'), lintegral_add_left h_measM_f', right_distrib, h_ind_f', h_ind_g] }, { intros f h_meas_f h_mono_f h_ind_f, have h_measM_f : ∀ n, measurable (f n), from λ n, (h_meas_f n).mono hMf le_rfl, simp_rw [ennreal.supr_mul], rw [lintegral_supr h_measM_f h_mono_f, lintegral_supr, ennreal.supr_mul], { simp_rw [← h_ind_f] }, { exact λ n, h_mul_indicator _ (h_measM_f n) }, { exact λ m n h_le a, ennreal.mul_le_mul (h_mono_f h_le a) le_rfl, }, }, end /-- If `f` and `g` are independent random variables with values in `ℝ≥0∞`, then `E[f * g] = E[f] * E[g]`. However, instead of directly using the independence of the random variables, it uses the independence of measurable spaces for the domains of `f` and `g`. This is similar to the sigma-algebra approach to independence. See `lintegral_mul_eq_lintegral_mul_lintegral_of_independent_fn` for a more common variant of the product of independent variables. -/ lemma lintegral_mul_eq_lintegral_mul_lintegral_of_independent_measurable_space {Mf Mg mΩ : measurable_space Ω} {μ : measure Ω} (hMf : Mf ≤ mΩ) (hMg : Mg ≤ mΩ) (h_ind : indep Mf Mg μ) (h_meas_f : measurable[Mf] f) (h_meas_g : measurable[Mg] g) : ∫⁻ ω, f ω * g ω ∂μ = ∫⁻ ω, f ω ∂μ * ∫⁻ ω, g ω ∂μ := begin revert g, have h_measM_f : measurable f, from h_meas_f.mono hMf le_rfl, apply measurable.ennreal_induction, { intros c s h_s, apply lintegral_mul_indicator_eq_lintegral_mul_lintegral_indicator hMf _ (hMg _ h_s) _ h_meas_f, apply indep_sets_of_indep_sets_of_le_right h_ind, rwa singleton_subset_iff, }, { intros f' g h_univ h_measMg_f' h_measMg_g h_ind_f' h_ind_g', have h_measM_f' : measurable f', from h_measMg_f'.mono hMg le_rfl, have h_measM_g : measurable g, from h_measMg_g.mono hMg le_rfl, simp_rw [pi.add_apply, left_distrib], rw [lintegral_add_left h_measM_f', lintegral_add_left (h_measM_f.mul h_measM_f'), left_distrib, h_ind_f', h_ind_g'] }, { intros f' h_meas_f' h_mono_f' h_ind_f', have h_measM_f' : ∀ n, measurable (f' n), from λ n, (h_meas_f' n).mono hMg le_rfl, simp_rw [ennreal.mul_supr], rw [lintegral_supr, lintegral_supr h_measM_f' h_mono_f', ennreal.mul_supr], { simp_rw [← h_ind_f'], }, { exact λ n, h_measM_f.mul (h_measM_f' n), }, { exact λ n m (h_le : n ≤ m) a, ennreal.mul_le_mul le_rfl (h_mono_f' h_le a), }, } end /-- If `f` and `g` are independent random variables with values in `ℝ≥0∞`, then `E[f * g] = E[f] * E[g]`. -/ lemma lintegral_mul_eq_lintegral_mul_lintegral_of_indep_fun (h_meas_f : measurable f) (h_meas_g : measurable g) (h_indep_fun : indep_fun f g μ) : ∫⁻ ω, (f * g) ω ∂μ = ∫⁻ ω, f ω ∂μ * ∫⁻ ω, g ω ∂μ := lintegral_mul_eq_lintegral_mul_lintegral_of_independent_measurable_space (measurable_iff_comap_le.1 h_meas_f) (measurable_iff_comap_le.1 h_meas_g) h_indep_fun (measurable.of_comap_le le_rfl) (measurable.of_comap_le le_rfl) /-- If `f` and `g` with values in `ℝ≥0∞` are independent and almost everywhere measurable, then `E[f * g] = E[f] * E[g]` (slightly generalizing `lintegral_mul_eq_lintegral_mul_lintegral_of_indep_fun`). -/ lemma lintegral_mul_eq_lintegral_mul_lintegral_of_indep_fun' (h_meas_f : ae_measurable f μ) (h_meas_g : ae_measurable g μ) (h_indep_fun : indep_fun f g μ) : ∫⁻ ω, (f * g) ω ∂μ = ∫⁻ ω, f ω ∂μ * ∫⁻ ω, g ω ∂μ := begin have fg_ae : f * g =ᵐ[μ] (h_meas_f.mk _) * (h_meas_g.mk _), from h_meas_f.ae_eq_mk.mul h_meas_g.ae_eq_mk, rw [lintegral_congr_ae h_meas_f.ae_eq_mk, lintegral_congr_ae h_meas_g.ae_eq_mk, lintegral_congr_ae fg_ae], apply lintegral_mul_eq_lintegral_mul_lintegral_of_indep_fun h_meas_f.measurable_mk h_meas_g.measurable_mk, exact h_indep_fun.ae_eq h_meas_f.ae_eq_mk h_meas_g.ae_eq_mk end lemma lintegral_mul_eq_lintegral_mul_lintegral_of_indep_fun'' (h_meas_f : ae_measurable f μ) (h_meas_g : ae_measurable g μ) (h_indep_fun : indep_fun f g μ) : ∫⁻ ω, f ω * g ω ∂μ = ∫⁻ ω, f ω ∂μ * ∫⁻ ω, g ω ∂μ := lintegral_mul_eq_lintegral_mul_lintegral_of_indep_fun' h_meas_f h_meas_g h_indep_fun /-- The product of two independent, integrable, real_valued random variables is integrable. -/ lemma indep_fun.integrable_mul {β : Type*} [measurable_space β] {X Y : Ω → β} [normed_division_ring β] [borel_space β] (hXY : indep_fun X Y μ) (hX : integrable X μ) (hY : integrable Y μ) : integrable (X * Y) μ := begin let nX : Ω → ennreal := λ a, ∥X a∥₊, let nY : Ω → ennreal := λ a, ∥Y a∥₊, have hXY' : indep_fun (λ a, ∥X a∥₊) (λ a, ∥Y a∥₊) μ := hXY.comp measurable_nnnorm measurable_nnnorm, have hXY'' : indep_fun nX nY μ := hXY'.comp measurable_coe_nnreal_ennreal measurable_coe_nnreal_ennreal, have hnX : ae_measurable nX μ := hX.1.ae_measurable.nnnorm.coe_nnreal_ennreal, have hnY : ae_measurable nY μ := hY.1.ae_measurable.nnnorm.coe_nnreal_ennreal, have hmul : ∫⁻ a, nX a * nY a ∂μ = ∫⁻ a, nX a ∂μ * ∫⁻ a, nY a ∂μ := by convert lintegral_mul_eq_lintegral_mul_lintegral_of_indep_fun' hnX hnY hXY'', refine ⟨hX.1.mul hY.1, _⟩, simp_rw [has_finite_integral, pi.mul_apply, nnnorm_mul, ennreal.coe_mul, hmul], exact ennreal.mul_lt_top_iff.mpr (or.inl ⟨hX.2, hY.2⟩) end /-- If the product of two independent real_valued random variables is integrable and the second one is not almost everywhere zero, then the first one is integrable. -/ lemma indep_fun.integrable_left_of_integrable_mul {β : Type*} [measurable_space β] {X Y : Ω → β} [normed_division_ring β] [borel_space β] (hXY : indep_fun X Y μ) (h'XY : integrable (X * Y) μ) (hX : ae_strongly_measurable X μ) (hY : ae_strongly_measurable Y μ) (h'Y : ¬(Y =ᵐ[μ] 0)) : integrable X μ := begin refine ⟨hX, _⟩, have I : ∫⁻ ω, ∥Y ω∥₊ ∂μ ≠ 0, { assume H, have I : (λ ω, ↑∥Y ω∥₊) =ᵐ[μ] 0 := (lintegral_eq_zero_iff' hY.ennnorm).1 H, apply h'Y, filter_upwards [I] with ω hω, simpa using hω }, apply lt_top_iff_ne_top.2 (λ H, _), have J : indep_fun (λ ω, ↑∥X ω∥₊) (λ ω, ↑∥Y ω∥₊) μ, { have M : measurable (λ (x : β), (∥x∥₊ : ℝ≥0∞)) := measurable_nnnorm.coe_nnreal_ennreal, apply indep_fun.comp hXY M M }, have A : ∫⁻ ω, ∥X ω * Y ω∥₊ ∂μ < ∞ := h'XY.2, simp only [nnnorm_mul, ennreal.coe_mul] at A, rw [lintegral_mul_eq_lintegral_mul_lintegral_of_indep_fun'' hX.ennnorm hY.ennnorm J, H] at A, simpa [ennreal.top_mul, I] using A, end /-- If the product of two independent real_valued random variables is integrable and the first one is not almost everywhere zero, then the second one is integrable. -/ lemma indep_fun.integrable_right_of_integrable_mul {β : Type*} [measurable_space β] {X Y : Ω → β} [normed_division_ring β] [borel_space β] (hXY : indep_fun X Y μ) (h'XY : integrable (X * Y) μ) (hX : ae_strongly_measurable X μ) (hY : ae_strongly_measurable Y μ) (h'X : ¬(X =ᵐ[μ] 0)) : integrable Y μ := begin refine ⟨hY, _⟩, have I : ∫⁻ ω, ∥X ω∥₊ ∂μ ≠ 0, { assume H, have I : (λ ω, ↑∥X ω∥₊) =ᵐ[μ] 0 := (lintegral_eq_zero_iff' hX.ennnorm).1 H, apply h'X, filter_upwards [I] with ω hω, simpa using hω }, apply lt_top_iff_ne_top.2 (λ H, _), have J : indep_fun (λ ω, ↑∥X ω∥₊) (λ ω, ↑∥Y ω∥₊) μ, { have M : measurable (λ (x : β), (∥x∥₊ : ℝ≥0∞)) := measurable_nnnorm.coe_nnreal_ennreal, apply indep_fun.comp hXY M M }, have A : ∫⁻ ω, ∥X ω * Y ω∥₊ ∂μ < ∞ := h'XY.2, simp only [nnnorm_mul, ennreal.coe_mul] at A, rw [lintegral_mul_eq_lintegral_mul_lintegral_of_indep_fun'' hX.ennnorm hY.ennnorm J, H] at A, simpa [ennreal.top_mul, I] using A, end /-- The (Bochner) integral of the product of two independent, nonnegative random variables is the product of their integrals. The proof is just plumbing around `lintegral_mul_eq_lintegral_mul_lintegral_of_indep_fun'`. -/ lemma indep_fun.integral_mul_of_nonneg (hXY : indep_fun X Y μ) (hXp : 0 ≤ X) (hYp : 0 ≤ Y) (hXm : ae_measurable X μ) (hYm : ae_measurable Y μ) : integral μ (X * Y) = integral μ X * integral μ Y := begin have h1 : ae_measurable (λ a, ennreal.of_real (X a)) μ := ennreal.measurable_of_real.comp_ae_measurable hXm, have h2 : ae_measurable (λ a, ennreal.of_real (Y a)) μ := ennreal.measurable_of_real.comp_ae_measurable hYm, have h3 : ae_measurable (X * Y) μ := hXm.mul hYm, have h4 : 0 ≤ᵐ[μ] (X * Y) := ae_of_all _ (λ ω, mul_nonneg (hXp ω) (hYp ω)), rw [integral_eq_lintegral_of_nonneg_ae (ae_of_all _ hXp) hXm.ae_strongly_measurable, integral_eq_lintegral_of_nonneg_ae (ae_of_all _ hYp) hYm.ae_strongly_measurable, integral_eq_lintegral_of_nonneg_ae h4 h3.ae_strongly_measurable], simp_rw [←ennreal.to_real_mul, pi.mul_apply, ennreal.of_real_mul (hXp _)], congr, apply lintegral_mul_eq_lintegral_mul_lintegral_of_indep_fun' h1 h2, exact hXY.comp ennreal.measurable_of_real ennreal.measurable_of_real end /-- The (Bochner) integral of the product of two independent, integrable random variables is the product of their integrals. The proof is pedestrian decomposition into their positive and negative parts in order to apply `indep_fun.integral_mul_of_nonneg` four times. -/ theorem indep_fun.integral_mul_of_integrable (hXY : indep_fun X Y μ) (hX : integrable X μ) (hY : integrable Y μ) : integral μ (X * Y) = integral μ X * integral μ Y := begin let pos : ℝ → ℝ := (λ x, max x 0), let neg : ℝ → ℝ := (λ x, max (-x) 0), have posm : measurable pos := measurable_id'.max measurable_const, have negm : measurable neg := measurable_id'.neg.max measurable_const, let Xp := pos ∘ X, -- `X⁺` would look better but it makes `simp_rw` below fail let Xm := neg ∘ X, let Yp := pos ∘ Y, let Ym := neg ∘ Y, have hXpm : X = Xp - Xm := funext (λ ω, (max_zero_sub_max_neg_zero_eq_self (X ω)).symm), have hYpm : Y = Yp - Ym := funext (λ ω, (max_zero_sub_max_neg_zero_eq_self (Y ω)).symm), have hp1 : 0 ≤ Xm := λ ω, le_max_right _ _, have hp2 : 0 ≤ Xp := λ ω, le_max_right _ _, have hp3 : 0 ≤ Ym := λ ω, le_max_right _ _, have hp4 : 0 ≤ Yp := λ ω, le_max_right _ _, have hm1 : ae_measurable Xm μ := hX.1.ae_measurable.neg.max ae_measurable_const, have hm2 : ae_measurable Xp μ := hX.1.ae_measurable.max ae_measurable_const, have hm3 : ae_measurable Ym μ := hY.1.ae_measurable.neg.max ae_measurable_const, have hm4 : ae_measurable Yp μ := hY.1.ae_measurable.max ae_measurable_const, have hv1 : integrable Xm μ := hX.neg_part, have hv2 : integrable Xp μ := hX.pos_part, have hv3 : integrable Ym μ := hY.neg_part, have hv4 : integrable Yp μ := hY.pos_part, have hi1 : indep_fun Xm Ym μ := hXY.comp negm negm, have hi2 : indep_fun Xp Ym μ := hXY.comp posm negm, have hi3 : indep_fun Xm Yp μ := hXY.comp negm posm, have hi4 : indep_fun Xp Yp μ := hXY.comp posm posm, have hl1 : integrable (Xm * Ym) μ := hi1.integrable_mul hv1 hv3, have hl2 : integrable (Xp * Ym) μ := hi2.integrable_mul hv2 hv3, have hl3 : integrable (Xm * Yp) μ := hi3.integrable_mul hv1 hv4, have hl4 : integrable (Xp * Yp) μ := hi4.integrable_mul hv2 hv4, have hl5 : integrable (Xp * Yp - Xm * Yp) μ := hl4.sub hl3, have hl6 : integrable (Xp * Ym - Xm * Ym) μ := hl2.sub hl1, simp_rw [hXpm, hYpm, mul_sub, sub_mul], rw [integral_sub' hl5 hl6, integral_sub' hl4 hl3, integral_sub' hl2 hl1, integral_sub' hv2 hv1, integral_sub' hv4 hv3, hi1.integral_mul_of_nonneg hp1 hp3 hm1 hm3, hi2.integral_mul_of_nonneg hp2 hp3 hm2 hm3, hi3.integral_mul_of_nonneg hp1 hp4 hm1 hm4, hi4.integral_mul_of_nonneg hp2 hp4 hm2 hm4], ring end /-- The (Bochner) integral of the product of two independent random variables is the product of their integrals. -/ theorem indep_fun.integral_mul (hXY : indep_fun X Y μ) (hX : ae_strongly_measurable X μ) (hY : ae_strongly_measurable Y μ) : integral μ (X * Y) = integral μ X * integral μ Y := begin by_cases h'X : X =ᵐ[μ] 0, { have h' : X * Y =ᵐ[μ] 0, { filter_upwards [h'X] with ω hω, simp [hω] }, simp only [integral_congr_ae h'X, integral_congr_ae h', pi.zero_apply, integral_const, algebra.id.smul_eq_mul, mul_zero, zero_mul] }, by_cases h'Y : Y =ᵐ[μ] 0, { have h' : X * Y =ᵐ[μ] 0, { filter_upwards [h'Y] with ω hω, simp [hω] }, simp only [integral_congr_ae h'Y, integral_congr_ae h', pi.zero_apply, integral_const, algebra.id.smul_eq_mul, mul_zero, zero_mul] }, by_cases h : integrable (X * Y) μ, { have HX : integrable X μ := hXY.integrable_left_of_integrable_mul h hX hY h'Y, have HY : integrable Y μ := hXY.integrable_right_of_integrable_mul h hX hY h'X, exact hXY.integral_mul_of_integrable HX HY }, { have I : ¬(integrable X μ ∧ integrable Y μ), { rintros ⟨HX, HY⟩, exact h (hXY.integrable_mul HX HY) }, rw not_and_distrib at I, cases I; simp [integral_undef, I, h] } end theorem indep_fun.integral_mul' (hXY : indep_fun X Y μ) (hX : ae_strongly_measurable X μ) (hY : ae_strongly_measurable Y μ) : integral μ (λ ω, X ω * Y ω) = integral μ X * integral μ Y := hXY.integral_mul hX hY /-- Independence of functions `f` and `g` into arbitrary types is characterized by the relation `E[(φ ∘ f) * (ψ ∘ g)] = E[φ ∘ f] * E[ψ ∘ g]` for all measurable `φ` and `ψ` with values in `ℝ` satisfying appropriate integrability conditions. -/ theorem indep_fun_iff_integral_comp_mul [is_finite_measure μ] {β β' : Type*} {mβ : measurable_space β} {mβ' : measurable_space β'} {f : Ω → β} {g : Ω → β'} {hfm : measurable f} {hgm : measurable g} : indep_fun f g μ ↔ ∀ {φ : β → ℝ} {ψ : β' → ℝ}, measurable φ → measurable ψ → integrable (φ ∘ f) μ → integrable (ψ ∘ g) μ → integral μ ((φ ∘ f) * (ψ ∘ g)) = integral μ (φ ∘ f) * integral μ (ψ ∘ g) := begin refine ⟨λ hfg _ _ hφ hψ, indep_fun.integral_mul_of_integrable (hfg.comp hφ hψ), _⟩, rintro h _ _ ⟨A, hA, rfl⟩ ⟨B, hB, rfl⟩, specialize h (measurable_one.indicator hA) (measurable_one.indicator hB) ((integrable_const 1).indicator (hfm.comp measurable_id hA)) ((integrable_const 1).indicator (hgm.comp measurable_id hB)), rwa [← ennreal.to_real_eq_to_real (measure_ne_top μ _), ennreal.to_real_mul, ← integral_indicator_one ((hfm hA).inter (hgm hB)), ← integral_indicator_one (hfm hA), ← integral_indicator_one (hgm hB), set.inter_indicator_one], exact ennreal.mul_ne_top (measure_ne_top μ _) (measure_ne_top μ _) end end probability_theory
7228339632900267115b1cddab1348735fcfc593
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/prio_overloading.lean
cf27888dcd65c9ce0d308687576c680b62d3e24a
[ "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
487
lean
import algebra.group data.real open nat definition foo1 [instance] [priority 2] : inhabited nat := inhabited.mk 10 definition foo2 [instance] [priority 1] : inhabited nat := inhabited.mk 10 open algebra definition foo3 [instance] [priority 1] : inhabited nat := inhabited.mk 10 definition foo4 [unfold 2 3] (a b c : nat) := a + b + c definition natrec [recursor 4] {C : nat → Type} (H₁ : C 0) (H₂ : Π (n : nat), C n → C (succ n)) (n : nat) : C n := nat.rec_on n H₁ H₂
44a62f0ded92aeacd567c25847b42e6a7d7c603b
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/algebra/category/Mon/basic.lean
cd8a3b266e59c9d47c08c109672e5e03662799bd
[ "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
8,172
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 category_theory.concrete_category import algebra.punit_instances /-! # Category instances for monoid, add_monoid, comm_monoid, and add_comm_monoid. We introduce the bundled categories: * `Mon` * `AddMon` * `CommMon` * `AddCommMon` along with the relevant forgetful functors between them. ## Implementation notes See the note [locally reducible category instances]. -/ /-- We make SemiRing (and the other categories) locally reducible in order to define its instances. This is because writing, for example, ``` instance : concrete_category SemiRing := by { delta SemiRing, apply_instance } ``` results in an instance of the form `id (bundled_hom.concrete_category _)` and this `id`, not being [reducible], prevents a later instance search (once SemiRing is no longer reducible) from seeing that the morphisms of SemiRing are really semiring morphisms (`→+*`), and therefore have a coercion to functions, for example. It's especially important that the `has_coe_to_sort` instance not contain an extra `id` as we want the `semiring ↥R` instance to also apply to `semiring R.α` (it seems to be impractical to guarantee that we always access `R.α` through the coercion rather than directly). TODO: Probably @[derive] should be able to create instances of the required form (without `id`), and then we could use that instead of this obscure `local attribute [reducible]` method. -/ library_note "locally reducible category instances" universes u v open category_theory /-- The category of monoids and monoid morphisms. -/ @[to_additive AddMon] def Mon : Type (u+1) := bundled monoid /-- The category of additive monoids and monoid morphisms. -/ add_decl_doc AddMon namespace Mon /-- Construct a bundled `Mon` from the underlying type and typeclass. -/ @[to_additive] def of (M : Type u) [monoid M] : Mon := bundled.of M /-- Construct a bundled Mon from the underlying type and typeclass. -/ add_decl_doc AddMon.of @[to_additive] instance : inhabited Mon := -- The default instance for `monoid punit` is derived via `punit.comm_ring`, -- which breaks to_additive. ⟨@of punit $ @group.to_monoid _ $ @comm_group.to_group _ punit.comm_group⟩ local attribute [reducible] Mon @[to_additive] instance : has_coe_to_sort Mon := infer_instance -- short-circuit type class inference @[to_additive add_monoid] instance (M : Mon) : monoid M := M.str @[to_additive] instance bundled_hom : bundled_hom @monoid_hom := ⟨@monoid_hom.to_fun, @monoid_hom.id, @monoid_hom.comp, @monoid_hom.coe_inj⟩ @[to_additive] instance : category Mon := infer_instance -- short-circuit type class inference @[to_additive] instance : concrete_category Mon := infer_instance -- short-circuit type class inference end Mon /-- The category of commutative monoids and monoid morphisms. -/ @[to_additive AddCommMon] def CommMon : Type (u+1) := bundled comm_monoid /-- The category of additive commutative monoids and monoid morphisms. -/ add_decl_doc AddCommMon namespace CommMon @[to_additive] instance : bundled_hom.parent_projection comm_monoid.to_monoid := ⟨⟩ /-- Construct a bundled `CommMon` from the underlying type and typeclass. -/ @[to_additive] def of (M : Type u) [comm_monoid M] : CommMon := bundled.of M /-- Construct a bundled `AddCommMon` from the underlying type and typeclass. -/ add_decl_doc AddCommMon.of @[to_additive] instance : inhabited CommMon := -- The default instance for `comm_monoid punit` is derived via `punit.comm_ring`, -- which breaks to_additive. ⟨@of punit $ @comm_group.to_comm_monoid _ punit.comm_group⟩ local attribute [reducible] CommMon @[to_additive] instance : has_coe_to_sort CommMon := infer_instance -- short-circuit type class inference @[to_additive add_comm_monoid] instance (M : CommMon) : comm_monoid M := M.str @[to_additive] instance : category CommMon := infer_instance -- short-circuit type class inference @[to_additive] instance : concrete_category CommMon := infer_instance -- short-circuit type class inference @[to_additive has_forget_to_AddMon] instance has_forget_to_Mon : has_forget₂ CommMon Mon := bundled_hom.forget₂ _ _ end CommMon -- We verify that the coercions of morphisms to functions work correctly: example {R S : Mon} (f : R ⟶ S) : (R : Type) → (S : Type) := f example {R S : CommMon} (f : R ⟶ S) : (R : Type) → (S : Type) := f -- We verify that when constructing a morphism in `CommMon`, -- when we construct the `to_fun` field, the types are presented as `↥R`, -- rather than `R.α` or (as we used to have) `↥(bundled.map comm_monoid.to_monoid R)`. example (R : CommMon.{u}) : R ⟶ R := { to_fun := λ x, begin match_target (R : Type u), match_hyp x := (R : Type u), exact x * x end , map_one' := by simp, map_mul' := λ x y, begin rw [mul_assoc x y (x * y), ←mul_assoc y x y, mul_comm y x, mul_assoc, mul_assoc], end, } variables {X Y : Type u} section variables [monoid X] [monoid Y] /-- Build an isomorphism in the category `Mon` from a `mul_equiv` between `monoid`s. -/ @[to_additive add_equiv.to_AddMon_iso "Build an isomorphism in the category `AddMon` from an `add_equiv` between `add_monoid`s."] def mul_equiv.to_Mon_iso (e : X ≃* Y) : Mon.of X ≅ Mon.of Y := { hom := e.to_monoid_hom, inv := e.symm.to_monoid_hom } @[simp, to_additive add_equiv.to_AddMon_iso_hom] lemma mul_equiv.to_Mon_iso_hom {e : X ≃* Y} : e.to_Mon_iso.hom = e.to_monoid_hom := rfl @[simp, to_additive add_equiv.to_AddMon_iso_inv] lemma mul_equiv.to_Mon_iso_inv {e : X ≃* Y} : e.to_Mon_iso.inv = e.symm.to_monoid_hom := rfl end section variables [comm_monoid X] [comm_monoid Y] /-- Build an isomorphism in the category `CommMon` from a `mul_equiv` between `comm_monoid`s. -/ @[to_additive add_equiv.to_AddCommMon_iso "Build an isomorphism in the category `AddCommMon` from an `add_equiv` between `add_comm_monoid`s."] def mul_equiv.to_CommMon_iso (e : X ≃* Y) : CommMon.of X ≅ CommMon.of Y := { hom := e.to_monoid_hom, inv := e.symm.to_monoid_hom } @[simp, to_additive add_equiv.to_AddCommMon_iso_hom] lemma mul_equiv.to_CommMon_iso_hom {e : X ≃* Y} : e.to_CommMon_iso.hom = e.to_monoid_hom := rfl @[simp, to_additive add_equiv.to_AddCommMon_iso_inv] lemma mul_equiv.to_CommMon_iso_inv {e : X ≃* Y} : e.to_CommMon_iso.inv = e.symm.to_monoid_hom := rfl end namespace category_theory.iso /-- Build a `mul_equiv` from an isomorphism in the category `Mon`. -/ @[to_additive AddMond_iso_to_add_equiv "Build an `add_equiv` from an isomorphism in the category `AddMon`."] def Mon_iso_to_mul_equiv {X Y : Mon} (i : X ≅ Y) : X ≃* Y := { to_fun := i.hom, inv_fun := i.inv, left_inv := by tidy, right_inv := by tidy, map_mul' := by tidy }. /-- Build a `mul_equiv` from an isomorphism in the category `CommMon`. -/ @[to_additive AddCommMon_iso_to_add_equiv "Build an `add_equiv` from an isomorphism in the category `AddCommMon`."] def CommMon_iso_to_mul_equiv {X Y : CommMon} (i : X ≅ Y) : X ≃* Y := { to_fun := i.hom, inv_fun := i.inv, left_inv := by tidy, right_inv := by tidy, map_mul' := by tidy }. end category_theory.iso /-- multiplicative equivalences between `monoid`s are the same as (isomorphic to) isomorphisms in `Mon` -/ @[to_additive add_equiv_iso_AddMon_iso "additive equivalences between `add_monoid`s are the same as (isomorphic to) isomorphisms in `AddMon`"] def mul_equiv_iso_Mon_iso {X Y : Type u} [monoid X] [monoid Y] : (X ≃* Y) ≅ (Mon.of X ≅ Mon.of Y) := { hom := λ e, e.to_Mon_iso, inv := λ i, i.Mon_iso_to_mul_equiv, } /-- multiplicative equivalences between `comm_monoid`s are the same as (isomorphic to) isomorphisms in `CommMon` -/ @[to_additive add_equiv_iso_AddCommMon_iso "additive equivalences between `add_comm_monoid`s are the same as (isomorphic to) isomorphisms in `AddCommMon`"] def mul_equiv_iso_CommMon_iso {X Y : Type u} [comm_monoid X] [comm_monoid Y] : (X ≃* Y) ≅ (CommMon.of X ≅ CommMon.of Y) := { hom := λ e, e.to_CommMon_iso, inv := λ i, i.CommMon_iso_to_mul_equiv, }
626cab441db0b201a0a8d3dd35588463b9624bb5
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/list/indexes.lean
644b76bdefe778eed267fb7208a4d7291d548fe5
[]
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
4,996
lean
/- Copyright (c) 2020 Jannis Limperg. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jannis Limperg -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.list.basic import Mathlib.data.list.defs import Mathlib.logic.basic import Mathlib.PostPort universes u v u_1 namespace Mathlib namespace list /-- Specification of `foldr_with_index_aux`. -/ def foldr_with_index_aux_spec {α : Type u} {β : Type v} (f : ℕ → α → β → β) (start : ℕ) (b : β) (as : List α) : β := foldr (function.uncurry f) b (enum_from start as) theorem foldr_with_index_aux_spec_cons {α : Type u} {β : Type v} (f : ℕ → α → β → β) (start : ℕ) (b : β) (a : α) (as : List α) : foldr_with_index_aux_spec f start b (a :: as) = f start a (foldr_with_index_aux_spec f (start + 1) b as) := rfl theorem foldr_with_index_aux_eq_foldr_with_index_aux_spec {α : Type u} {β : Type v} (f : ℕ → α → β → β) (start : ℕ) (b : β) (as : List α) : foldr_with_index_aux f start b as = foldr_with_index_aux_spec f start b as := sorry theorem foldr_with_index_eq_foldr_enum {α : Type u} {β : Type v} (f : ℕ → α → β → β) (b : β) (as : List α) : foldr_with_index f b as = foldr (function.uncurry f) b (enum as) := sorry theorem indexes_values_eq_filter_enum {α : Type u} (p : α → Prop) [decidable_pred p] (as : List α) : indexes_values p as = filter (p ∘ prod.snd) (enum as) := sorry theorem find_indexes_eq_map_indexes_values {α : Type u} (p : α → Prop) [decidable_pred p] (as : List α) : find_indexes p as = map prod.fst (indexes_values p as) := sorry /-- Specification of `foldl_with_index_aux`. -/ def foldl_with_index_aux_spec {α : Type u} {β : Type v} (f : ℕ → α → β → α) (start : ℕ) (a : α) (bs : List β) : α := foldl (fun (a : α) (p : ℕ × β) => f (prod.fst p) a (prod.snd p)) a (enum_from start bs) theorem foldl_with_index_aux_spec_cons {α : Type u} {β : Type v} (f : ℕ → α → β → α) (start : ℕ) (a : α) (b : β) (bs : List β) : foldl_with_index_aux_spec f start a (b :: bs) = foldl_with_index_aux_spec f (start + 1) (f start a b) bs := rfl theorem foldl_with_index_aux_eq_foldl_with_index_aux_spec {α : Type u} {β : Type v} (f : ℕ → α → β → α) (start : ℕ) (a : α) (bs : List β) : foldl_with_index_aux f start a bs = foldl_with_index_aux_spec f start a bs := sorry theorem foldl_with_index_eq_foldl_enum {α : Type u} {β : Type v} (f : ℕ → α → β → α) (a : α) (bs : List β) : foldl_with_index f a bs = foldl (fun (a : α) (p : ℕ × β) => f (prod.fst p) a (prod.snd p)) a (enum bs) := sorry theorem mfoldr_with_index_eq_mfoldr_enum {m : Type u → Type v} [Monad m] {α : Type u_1} {β : Type u} (f : ℕ → α → β → m β) (b : β) (as : List α) : mfoldr_with_index f b as = mfoldr (function.uncurry f) b (enum as) := sorry theorem mfoldl_with_index_eq_mfoldl_enum {m : Type u → Type v} [Monad m] [is_lawful_monad m] {α : Type u_1} {β : Type u} (f : ℕ → β → α → m β) (b : β) (as : List α) : mfoldl_with_index f b as = mfoldl (fun (b : β) (p : ℕ × α) => f (prod.fst p) b (prod.snd p)) b (enum as) := sorry /-- Specification of `mmap_with_index_aux`. -/ def mmap_with_index_aux_spec {m : Type u → Type v} [Applicative m] {α : Type u_1} {β : Type u} (f : ℕ → α → m β) (start : ℕ) (as : List α) : m (List β) := list.traverse (function.uncurry f) (enum_from start as) -- Note: `traverse` the class method would require a less universe-polymorphic -- `m : Type u → Type u`. theorem mmap_with_index_aux_spec_cons {m : Type u → Type v} [Applicative m] {α : Type u_1} {β : Type u} (f : ℕ → α → m β) (start : ℕ) (a : α) (as : List α) : mmap_with_index_aux_spec f start (a :: as) = List.cons <$> f start a <*> mmap_with_index_aux_spec f (start + 1) as := rfl theorem mmap_with_index_aux_eq_mmap_with_index_aux_spec {m : Type u → Type v} [Applicative m] {α : Type u_1} {β : Type u} (f : ℕ → α → m β) (start : ℕ) (as : List α) : mmap_with_index_aux f start as = mmap_with_index_aux_spec f start as := sorry theorem mmap_with_index_eq_mmap_enum {m : Type u → Type v} [Applicative m] {α : Type u_1} {β : Type u} (f : ℕ → α → m β) (as : List α) : mmap_with_index f as = list.traverse (function.uncurry f) (enum as) := sorry theorem mmap_with_index'_aux_eq_mmap_with_index_aux {m : Type u → Type v} [Applicative m] [is_lawful_applicative m] {α : Type u_1} (f : ℕ → α → m PUnit) (start : ℕ) (as : List α) : mmap_with_index'_aux f start as = mmap_with_index_aux f start as *> pure PUnit.unit := sorry theorem mmap_with_index'_eq_mmap_with_index {m : Type u → Type v} [Applicative m] [is_lawful_applicative m] {α : Type u_1} (f : ℕ → α → m PUnit) (as : List α) : mmap_with_index' f as = mmap_with_index f as *> pure PUnit.unit := mmap_with_index'_aux_eq_mmap_with_index_aux f 0 as
b59a56cae92c4934d5c44984a68306d7295a3a73
f7315930643edc12e76c229a742d5446dad77097
/tests/lean/run/tactic24.lean
e64aca3d521b2fda0cc43af92c1629c3e7fe8b77
[ "Apache-2.0" ]
permissive
bmalehorn/lean
8f77b762a76c59afff7b7403f9eb5fc2c3ce70c1
53653c352643751c4b62ff63ec5e555f11dae8eb
refs/heads/master
1,610,945,684,489
1,429,681,220,000
1,429,681,449,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
548
lean
import logic open tactic definition my_tac1 := apply @eq.refl definition my_tac2 := repeat (apply @and.intro; assumption) tactic_hint my_tac1 tactic_hint my_tac2 theorem T1 {A : Type.{2}} (a : A) : a = a := _ theorem T2 {a b c : Prop} (Ha : a) (Hb : b) (Hc : c) : a ∧ b ∧ c := _ definition my_tac3 := fixpoint (λ f, (apply @or.intro_left; f | apply @or.intro_right; f | assumption)) tactic_hint my_tac3 theorem T3 {a b c : Prop} (Hb : b) : a ∨ b ∨ c := _
ba6cac088dcff0ff3c15ad394d394d7c382bcae5
437dc96105f48409c3981d46fb48e57c9ac3a3e4
/src/topology/metric_space/closeds.lean
d348536066d5c9cbf596c84c25e02f6be0886a74
[ "Apache-2.0" ]
permissive
dan-c-k/mathlib
08efec79bd7481ee6da9cc44c24a653bff4fbe0d
96efc220f6225bc7a5ed8349900391a33a38cc56
refs/heads/master
1,658,082,847,093
1,589,013,201,000
1,589,013,201,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
21,544
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Sébastien Gouëzel -/ import topology.metric_space.hausdorff_distance import analysis.specific_limits /-! # Closed subsets This file defines the metric and emetric space structure on the types of closed subsets and nonempty compact subsets of a metric or emetric space. The Hausdorff distance induces an emetric space structure on the type of closed subsets of an emetric space, called `closeds`. Its completeness, resp. compactness, resp. second-countability, follow from the corresponding properties of the original space. In a metric space, the type of nonempty compact subsets (called `nonempty_compacts`) also inherits a metric space structure from the Hausdorff distance, as the Hausdorff edistance is always finite in this context. -/ noncomputable theory open_locale classical open_locale topological_space universe u open classical set function topological_space filter namespace emetric section variables {α : Type u} [emetric_space α] {s : set α} /-- In emetric spaces, the Hausdorff edistance defines an emetric space structure on the type of closed subsets -/ instance closeds.emetric_space : emetric_space (closeds α) := { edist := λs t, Hausdorff_edist s.val t.val, edist_self := λs, Hausdorff_edist_self, edist_comm := λs t, Hausdorff_edist_comm, edist_triangle := λs t u, Hausdorff_edist_triangle, eq_of_edist_eq_zero := λs t h, subtype.eq ((Hausdorff_edist_zero_iff_eq_of_closed s.property t.property).1 h) } /-- The edistance to a closed set depends continuously on the point and the set -/ lemma continuous_inf_edist_Hausdorff_edist : continuous (λp : α × (closeds α), inf_edist p.1 (p.2).val) := begin refine continuous_of_le_add_edist 2 (by simp) _, rintros ⟨x, s⟩ ⟨y, t⟩, calc inf_edist x (s.val) ≤ inf_edist x (t.val) + Hausdorff_edist (t.val) (s.val) : inf_edist_le_inf_edist_add_Hausdorff_edist ... ≤ (inf_edist y (t.val) + edist x y) + Hausdorff_edist (t.val) (s.val) : add_le_add_right' inf_edist_le_inf_edist_add_edist ... = inf_edist y (t.val) + (edist x y + Hausdorff_edist (s.val) (t.val)) : by simp [add_comm, add_left_comm, Hausdorff_edist_comm] ... ≤ inf_edist y (t.val) + (edist (x, s) (y, t) + edist (x, s) (y, t)) : add_le_add_left' (add_le_add' (by simp [edist, le_refl]) (by simp [edist, le_refl])) ... = inf_edist y (t.val) + 2 * edist (x, s) (y, t) : by rw [← mul_two, mul_comm] end /-- Subsets of a given closed subset form a closed set -/ lemma is_closed_subsets_of_is_closed (hs : is_closed s) : is_closed {t : closeds α | t.val ⊆ s} := begin refine is_closed_of_closure_subset (λt ht x hx, _), -- t : closeds α, ht : t ∈ closure {t : closeds α | t.val ⊆ s}, -- x : α, hx : x ∈ t.val -- goal : x ∈ s have : x ∈ closure s, { refine mem_closure_iff.2 (λε εpos, _), rcases mem_closure_iff.1 ht ε εpos with ⟨u, hu, Dtu⟩, -- u : closeds α, hu : u ∈ {t : closeds α | t.val ⊆ s}, hu' : edist t u < ε rcases exists_edist_lt_of_Hausdorff_edist_lt hx Dtu with ⟨y, hy, Dxy⟩, -- y : α, hy : y ∈ u.val, Dxy : edist x y < ε exact ⟨y, hu hy, Dxy⟩ }, rwa closure_eq_of_is_closed hs at this, end /-- By definition, the edistance on `closeds α` is given by the Hausdorff edistance -/ lemma closeds.edist_eq {s t : closeds α} : edist s t = Hausdorff_edist s.val t.val := rfl /-- In a complete space, the type of closed subsets is complete for the Hausdorff edistance. -/ instance closeds.complete_space [complete_space α] : complete_space (closeds α) := begin /- We will show that, if a sequence of sets `s n` satisfies `edist (s n) (s (n+1)) < 2^{-n}`, then it converges. This is enough to guarantee completeness, by a standard completeness criterion. We use the shorthand `B n = 2^{-n}` in ennreal. -/ let B : ℕ → ennreal := λ n, (2⁻¹)^n, have B_pos : ∀ n, (0:ennreal) < B n, by simp [B, ennreal.pow_pos], have B_ne_top : ∀ n, B n ≠ ⊤, by simp [B, ennreal.div_def, ennreal.pow_ne_top], /- Consider a sequence of closed sets `s n` with `edist (s n) (s (n+1)) < B n`. We will show that it converges. The limit set is t0 = ⋂n, closure (⋃m≥n, s m). We will have to show that a point in `s n` is close to a point in `t0`, and a point in `t0` is close to a point in `s n`. The completeness then follows from a standard criterion. -/ refine complete_of_convergent_controlled_sequences B B_pos (λs hs, _), let t0 := ⋂n, closure (⋃m≥n, (s m).val), let t : closeds α := ⟨t0, is_closed_Inter (λ_, is_closed_closure)⟩, use t, -- The inequality is written this way to agree with `edist_le_of_edist_le_geometric_of_tendsto₀` have I1 : ∀n:ℕ, ∀x ∈ (s n).val, ∃y ∈ t0, edist x y ≤ 2 * B n, { /- This is the main difficulty of the proof. Starting from `x ∈ s n`, we want to find a point in `t0` which is close to `x`. Define inductively a sequence of points `z m` with `z n = x` and `z m ∈ s m` and `edist (z m) (z (m+1)) ≤ B m`. This is possible since the Hausdorff distance between `s m` and `s (m+1)` is at most `B m`. This sequence is a Cauchy sequence, therefore converging as the space is complete, to a limit which satisfies the required properties. -/ assume n x hx, obtain ⟨z, hz₀, hz⟩ : ∃ z : Π l, (s (n+l)).val, (z 0:α) = x ∧ ∀ k, edist (z k:α) (z (k+1):α) ≤ B n / 2^k, { -- We prove existence of the sequence by induction. have : ∀ (l : ℕ) (z : (s (n+l)).val), ∃ z' : (s (n+l+1)).val, edist (z:α) z' ≤ B n / 2^l, { assume l z, obtain ⟨z', z'_mem, hz'⟩ : ∃ z' ∈ (s (n+l+1)).val, edist (z:α) z' < B n / 2^l, { apply exists_edist_lt_of_Hausdorff_edist_lt z.2, simp only [B, ennreal.div_def, ennreal.inv_pow], rw [← pow_add], apply hs; simp }, exact ⟨⟨z', z'_mem⟩, le_of_lt hz'⟩ }, use [λ k, nat.rec_on k ⟨x, hx⟩ (λl z, some (this l z)), rfl], exact λ k, some_spec (this k _) }, -- it follows from the previous bound that `z` is a Cauchy sequence have : cauchy_seq (λ k, ((z k):α)), from cauchy_seq_of_edist_le_geometric_two (B n) (B_ne_top n) hz, -- therefore, it converges rcases cauchy_seq_tendsto_of_complete this with ⟨y, y_lim⟩, use y, -- the limit point `y` will be the desired point, in `t0` and close to our initial point `x`. -- First, we check it belongs to `t0`. have : y ∈ t0 := mem_Inter.2 (λk, mem_closure_of_tendsto (by simp) y_lim begin simp only [exists_prop, set.mem_Union, filter.mem_at_top_sets, set.mem_preimage, set.preimage_Union], exact ⟨k, λ m hm, ⟨n+m, zero_add k ▸ add_le_add (zero_le n) hm, (z m).2⟩⟩ end), use this, -- Then, we check that `y` is close to `x = z n`. This follows from the fact that `y` -- is the limit of `z k`, and the distance between `z n` and `z k` has already been estimated. rw [← hz₀], exact edist_le_of_edist_le_geometric_two_of_tendsto₀ (B n) hz y_lim }, have I2 : ∀n:ℕ, ∀x ∈ t0, ∃y ∈ (s n).val, edist x y ≤ 2 * B n, { /- For the (much easier) reverse inequality, we start from a point `x ∈ t0` and we want to find a point `y ∈ s n` which is close to `x`. `x` belongs to `t0`, the intersection of the closures. In particular, it is well approximated by a point `z` in `⋃m≥n, s m`, say in `s m`. Since `s m` and `s n` are close, this point is itself well approximated by a point `y` in `s n`, as required. -/ assume n x xt0, have : x ∈ closure (⋃m≥n, (s m).val), by apply mem_Inter.1 xt0 n, rcases mem_closure_iff.1 this (B n) (B_pos n) with ⟨z, hz, Dxz⟩, -- z : α, Dxz : edist x z < B n, simp only [exists_prop, set.mem_Union] at hz, rcases hz with ⟨m, ⟨m_ge_n, hm⟩⟩, -- m : ℕ, m_ge_n : m ≥ n, hm : z ∈ (s m).val have : Hausdorff_edist (s m).val (s n).val < B n := hs n m n m_ge_n (le_refl n), rcases exists_edist_lt_of_Hausdorff_edist_lt hm this with ⟨y, hy, Dzy⟩, -- y : α, hy : y ∈ (s n).val, Dzy : edist z y < B n exact ⟨y, hy, calc edist x y ≤ edist x z + edist z y : edist_triangle _ _ _ ... ≤ B n + B n : add_le_add' (le_of_lt Dxz) (le_of_lt Dzy) ... = 2 * B n : (two_mul _).symm ⟩ }, -- Deduce from the above inequalities that the distance between `s n` and `t0` is at most `2 B n`. have main : ∀n:ℕ, edist (s n) t ≤ 2 * B n := λn, Hausdorff_edist_le_of_mem_edist (I1 n) (I2 n), -- from this, the convergence of `s n` to `t0` follows. refine (tendsto_at_top _).2 (λε εpos, _), have : tendsto (λn, 2 * B n) at_top (𝓝 (2 * 0)), from ennreal.tendsto.const_mul (ennreal.tendsto_pow_at_top_nhds_0_of_lt_1 $ by simp [ennreal.one_lt_two]) (or.inr $ by simp), rw mul_zero at this, obtain ⟨N, hN⟩ : ∃ N, ∀ b ≥ N, ε > 2 * B b, from ((tendsto_order.1 this).2 ε εpos).exists_forall_of_at_top, exact ⟨N, λn hn, lt_of_le_of_lt (main n) (hN n hn)⟩ end /-- In a compact space, the type of closed subsets is compact. -/ instance closeds.compact_space [compact_space α] : compact_space (closeds α) := ⟨begin /- by completeness, it suffices to show that it is totally bounded, i.e., for all ε>0, there is a finite set which is ε-dense. start from a set `s` which is ε-dense in α. Then the subsets of `s` are finitely many, and ε-dense for the Hausdorff distance. -/ refine compact_of_totally_bounded_is_closed (emetric.totally_bounded_iff.2 (λε εpos, _)) is_closed_univ, rcases dense εpos with ⟨δ, δpos, δlt⟩, rcases emetric.totally_bounded_iff.1 (compact_iff_totally_bounded_complete.1 (@compact_univ α _ _)).1 δ δpos with ⟨s, fs, hs⟩, -- s : set α, fs : finite s, hs : univ ⊆ ⋃ (y : α) (H : y ∈ s), eball y δ -- we first show that any set is well approximated by a subset of `s`. have main : ∀ u : set α, ∃v ⊆ s, Hausdorff_edist u v ≤ δ, { assume u, let v := {x : α | x ∈ s ∧ ∃y∈u, edist x y < δ}, existsi [v, ((λx hx, hx.1) : v ⊆ s)], refine Hausdorff_edist_le_of_mem_edist _ _, { assume x hx, have : x ∈ ⋃y ∈ s, ball y δ := hs (by simp), rcases mem_bUnion_iff.1 this with ⟨y, ys, dy⟩, have : edist y x < δ := by simp at dy; rwa [edist_comm] at dy, exact ⟨y, ⟨ys, ⟨x, hx, this⟩⟩, le_of_lt dy⟩ }, { rintros x ⟨hx1, ⟨y, yu, hy⟩⟩, exact ⟨y, yu, le_of_lt hy⟩ }}, -- introduce the set F of all subsets of `s` (seen as members of `closeds α`). let F := {f : closeds α | f.val ⊆ s}, use F, split, -- `F` is finite { apply @finite_of_finite_image _ _ F (λf, f.val), { exact subtype.val_injective.inj_on F }, { refine finite_subset (finite_subsets_of_finite fs) (λb, _), simp only [and_imp, set.mem_image, set.mem_set_of_eq, exists_imp_distrib], assume x hx hx', rwa hx' at hx }}, -- `F` is ε-dense { assume u _, rcases main u.val with ⟨t0, t0s, Dut0⟩, have : is_closed t0 := closed_of_compact _ (finite_subset fs t0s).compact, let t : closeds α := ⟨t0, this⟩, have : t ∈ F := t0s, have : edist u t < ε := lt_of_le_of_lt Dut0 δlt, apply mem_bUnion_iff.2, exact ⟨t, ‹t ∈ F›, this⟩ } end⟩ /-- In an emetric space, the type of non-empty compact subsets is an emetric space, where the edistance is the Hausdorff edistance -/ instance nonempty_compacts.emetric_space : emetric_space (nonempty_compacts α) := { edist := λs t, Hausdorff_edist s.val t.val, edist_self := λs, Hausdorff_edist_self, edist_comm := λs t, Hausdorff_edist_comm, edist_triangle := λs t u, Hausdorff_edist_triangle, eq_of_edist_eq_zero := λs t h, subtype.eq $ begin have : closure (s.val) = closure (t.val) := Hausdorff_edist_zero_iff_closure_eq_closure.1 h, rwa [closure_eq_iff_is_closed.2 (closed_of_compact _ s.property.2), closure_eq_iff_is_closed.2 (closed_of_compact _ t.property.2)] at this, end } /-- `nonempty_compacts.to_closeds` is a uniform embedding (as it is an isometry) -/ lemma nonempty_compacts.to_closeds.uniform_embedding : uniform_embedding (@nonempty_compacts.to_closeds α _ _) := isometry.uniform_embedding $ λx y, rfl /-- The range of `nonempty_compacts.to_closeds` is closed in a complete space -/ lemma nonempty_compacts.is_closed_in_closeds [complete_space α] : is_closed (range $ @nonempty_compacts.to_closeds α _ _) := begin have : range nonempty_compacts.to_closeds = {s : closeds α | s.val.nonempty ∧ compact s.val}, from range_inclusion _, rw this, refine is_closed_of_closure_subset (λs hs, ⟨_, _⟩), { -- take a set set t which is nonempty and at a finite distance of s rcases mem_closure_iff.1 hs ⊤ ennreal.coe_lt_top with ⟨t, ht, Dst⟩, rw edist_comm at Dst, -- since `t` is nonempty, so is `s` exact nonempty_of_Hausdorff_edist_ne_top ht.1 (ne_of_lt Dst) }, { refine compact_iff_totally_bounded_complete.2 ⟨_, is_complete_of_is_closed s.property⟩, refine totally_bounded_iff.2 (λε εpos, _), -- we have to show that s is covered by finitely many eballs of radius ε -- pick a nonempty compact set t at distance at most ε/2 of s rcases mem_closure_iff.1 hs (ε/2) (ennreal.half_pos εpos) with ⟨t, ht, Dst⟩, -- cover this space with finitely many balls of radius ε/2 rcases totally_bounded_iff.1 (compact_iff_totally_bounded_complete.1 ht.2).1 (ε/2) (ennreal.half_pos εpos) with ⟨u, fu, ut⟩, refine ⟨u, ⟨fu, λx hx, _⟩⟩, -- u : set α, fu : finite u, ut : t.val ⊆ ⋃ (y : α) (H : y ∈ u), eball y (ε / 2) -- then s is covered by the union of the balls centered at u of radius ε rcases exists_edist_lt_of_Hausdorff_edist_lt hx Dst with ⟨z, hz, Dxz⟩, rcases mem_bUnion_iff.1 (ut hz) with ⟨y, hy, Dzy⟩, have : edist x y < ε := calc edist x y ≤ edist x z + edist z y : edist_triangle _ _ _ ... < ε/2 + ε/2 : ennreal.add_lt_add Dxz Dzy ... = ε : ennreal.add_halves _, exact mem_bUnion hy this }, end /-- In a complete space, the type of nonempty compact subsets is complete. This follows from the same statement for closed subsets -/ instance nonempty_compacts.complete_space [complete_space α] : complete_space (nonempty_compacts α) := (complete_space_iff_is_complete_range nonempty_compacts.to_closeds.uniform_embedding).2 $ is_complete_of_is_closed nonempty_compacts.is_closed_in_closeds /-- In a compact space, the type of nonempty compact subsets is compact. This follows from the same statement for closed subsets -/ instance nonempty_compacts.compact_space [compact_space α] : compact_space (nonempty_compacts α) := ⟨begin rw embedding.compact_iff_compact_image nonempty_compacts.to_closeds.uniform_embedding.embedding, rw [image_univ], exact nonempty_compacts.is_closed_in_closeds.compact end⟩ /-- In a second countable space, the type of nonempty compact subsets is second countable -/ instance nonempty_compacts.second_countable_topology [second_countable_topology α] : second_countable_topology (nonempty_compacts α) := begin haveI : separable_space (nonempty_compacts α) := begin /- To obtain a countable dense subset of `nonempty_compacts α`, start from a countable dense subset `s` of α, and then consider all its finite nonempty subsets. This set is countable and made of nonempty compact sets. It turns out to be dense: by total boundedness, any compact set `t` can be covered by finitely many small balls, and approximations in `s` of the centers of these balls give the required finite approximation of `t`. -/ have : separable_space α := by apply_instance, rcases this.exists_countable_closure_eq_univ with ⟨s, cs, s_dense⟩, let v0 := {t : set α | finite t ∧ t ⊆ s}, let v : set (nonempty_compacts α) := {t : nonempty_compacts α | t.val ∈ v0}, refine ⟨⟨v, ⟨_, _⟩⟩⟩, { have : countable (subtype.val '' v), { refine (countable_set_of_finite_subset cs).mono (λx hx, _), rcases (mem_image _ _ _).1 hx with ⟨y, ⟨hy, yx⟩⟩, rw ← yx, exact hy }, apply countable_of_injective_of_countable_image _ this, apply subtype.val_injective.inj_on }, { refine subset.antisymm (subset_univ _) (λt ht, mem_closure_iff.2 (λε εpos, _)), -- t is a compact nonempty set, that we have to approximate uniformly by a a set in `v`. rcases dense εpos with ⟨δ, δpos, δlt⟩, -- construct a map F associating to a point in α an approximating point in s, up to δ/2. have Exy : ∀x, ∃y, y ∈ s ∧ edist x y < δ/2, { assume x, have : x ∈ closure s := by rw s_dense; exact mem_univ _, rcases mem_closure_iff.1 this (δ/2) (ennreal.half_pos δpos) with ⟨y, ys, hy⟩, exact ⟨y, ⟨ys, hy⟩⟩ }, let F := λx, some (Exy x), have Fspec : ∀x, F x ∈ s ∧ edist x (F x) < δ/2 := λx, some_spec (Exy x), -- cover `t` with finitely many balls. Their centers form a set `a` have : totally_bounded t.val := (compact_iff_totally_bounded_complete.1 t.property.2).1, rcases totally_bounded_iff.1 this (δ/2) (ennreal.half_pos δpos) with ⟨a, af, ta⟩, -- a : set α, af : finite a, ta : t.val ⊆ ⋃ (y : α) (H : y ∈ a), eball y (δ / 2) -- replace each center by a nearby approximation in `s`, giving a new set `b` let b := F '' a, have : finite b := finite_image _ af, have tb : ∀x ∈ t.val, ∃y ∈ b, edist x y < δ, { assume x hx, rcases mem_bUnion_iff.1 (ta hx) with ⟨z, za, Dxz⟩, existsi [F z, mem_image_of_mem _ za], calc edist x (F z) ≤ edist x z + edist z (F z) : edist_triangle _ _ _ ... < δ/2 + δ/2 : ennreal.add_lt_add Dxz (Fspec z).2 ... = δ : ennreal.add_halves _ }, -- keep only the points in `b` that are close to point in `t`, yielding a new set `c` let c := {y ∈ b | ∃x∈t.val, edist x y < δ}, have : finite c := finite_subset ‹finite b› (λx hx, hx.1), -- points in `t` are well approximated by points in `c` have tc : ∀x ∈ t.val, ∃y ∈ c, edist x y ≤ δ, { assume x hx, rcases tb x hx with ⟨y, yv, Dxy⟩, have : y ∈ c := by simp [c, -mem_image]; exact ⟨yv, ⟨x, hx, Dxy⟩⟩, exact ⟨y, this, le_of_lt Dxy⟩ }, -- points in `c` are well approximated by points in `t` have ct : ∀y ∈ c, ∃x ∈ t.val, edist y x ≤ δ, { rintros y ⟨hy1, ⟨x, xt, Dyx⟩⟩, have : edist y x ≤ δ := calc edist y x = edist x y : edist_comm _ _ ... ≤ δ : le_of_lt Dyx, exact ⟨x, xt, this⟩ }, -- it follows that their Hausdorff distance is small have : Hausdorff_edist t.val c ≤ δ := Hausdorff_edist_le_of_mem_edist tc ct, have Dtc : Hausdorff_edist t.val c < ε := lt_of_le_of_lt this δlt, -- the set `c` is not empty, as it is well approximated by a nonempty set have hc : c.nonempty, from nonempty_of_Hausdorff_edist_ne_top t.property.1 (ne_top_of_lt Dtc), -- let `d` be the version of `c` in the type `nonempty_compacts α` let d : nonempty_compacts α := ⟨c, ⟨hc, ‹finite c›.compact⟩⟩, have : c ⊆ s, { assume x hx, rcases (mem_image _ _ _).1 hx.1 with ⟨y, ⟨ya, yx⟩⟩, rw ← yx, exact (Fspec y).1 }, have : d ∈ v := ⟨‹finite c›, this⟩, -- we have proved that `d` is a good approximation of `t` as requested exact ⟨d, ‹d ∈ v›, Dtc⟩ }, end, apply second_countable_of_separable, end end --section end emetric --namespace namespace metric section variables {α : Type u} [metric_space α] /-- `nonempty_compacts α` inherits a metric space structure, as the Hausdorff edistance between two such sets is finite. -/ instance nonempty_compacts.metric_space : metric_space (nonempty_compacts α) := emetric_space.to_metric_space $ λx y, Hausdorff_edist_ne_top_of_nonempty_of_bounded x.2.1 y.2.1 (bounded_of_compact x.2.2) (bounded_of_compact y.2.2) /-- The distance on `nonempty_compacts α` is the Hausdorff distance, by construction -/ lemma nonempty_compacts.dist_eq {x y : nonempty_compacts α} : dist x y = Hausdorff_dist x.val y.val := rfl lemma lipschitz_inf_dist_set (x : α) : lipschitz_with 1 (λ s : nonempty_compacts α, inf_dist x s.val) := lipschitz_with.of_le_add $ assume s t, by { rw dist_comm, exact inf_dist_le_inf_dist_add_Hausdorff_dist (edist_ne_top t s) } lemma lipschitz_inf_dist : lipschitz_with 2 (λ p : α × (nonempty_compacts α), inf_dist p.1 p.2.val) := @lipschitz_with.uncurry' _ _ _ _ _ _ (λ (x : α) (s : nonempty_compacts α), inf_dist x s.val) 1 1 (λ s, lipschitz_inf_dist_pt s.val) lipschitz_inf_dist_set lemma uniform_continuous_inf_dist_Hausdorff_dist : uniform_continuous (λp : α × (nonempty_compacts α), inf_dist p.1 (p.2).val) := lipschitz_inf_dist.uniform_continuous end --section end metric --namespace
3404e003fbb8136990ef6a1e0b88a6879b79d17c
367134ba5a65885e863bdc4507601606690974c1
/src/data/polynomial/induction.lean
1369f7b588ff02073e3ae769fed0d13d6d642495
[ "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,820
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 -/ import data.polynomial.coeff /-! # Theory of univariate polynomials The main results are `induction_on` and `as_sum`. -/ noncomputable theory open finsupp finset namespace polynomial universes u v w x y z variables {R : Type u} {S : Type v} {T : Type w} {ι : Type x} {k : Type y} {A : Type z} {a b : R} {m n : ℕ} section semiring variables [semiring R] {p q r : polynomial R} lemma sum_C_mul_X_eq (p : polynomial R) : p.sum (λn a, C a * X^n) = p := eq.trans (sum_congr rfl $ assume n hn, single_eq_C_mul_X.symm) (finsupp.sum_single _) lemma sum_monomial_eq (p : polynomial R) : p.sum (λn a, monomial n a) = p := by simp only [single_eq_C_mul_X, sum_C_mul_X_eq] @[elab_as_eliminator] protected lemma induction_on {M : polynomial R → Prop} (p : polynomial R) (h_C : ∀a, M (C a)) (h_add : ∀p q, M p → M q → M (p + q)) (h_monomial : ∀(n : ℕ) (a : R), M (C a * X^n) → M (C a * X^(n+1))) : M p := have ∀{n:ℕ} {a}, M (C a * X^n), begin assume n a, induction n with n ih, { simp only [pow_zero, mul_one, h_C] }, { exact h_monomial _ _ ih } end, finsupp.induction p (suffices M (C 0), by { convert this, exact single_zero.symm, }, h_C 0) (assume n a p _ _ hp, suffices M (C a * X^n + p), by { convert this, exact single_eq_C_mul_X }, h_add _ _ this hp) /-- To prove something about polynomials, it suffices to show the condition is closed under taking sums, and it holds for monomials. -/ @[elab_as_eliminator] protected lemma induction_on' {M : polynomial R → Prop} (p : polynomial R) (h_add : ∀p q, M p → M q → M (p + q)) (h_monomial : ∀(n : ℕ) (a : R), M (monomial n a)) : M p := polynomial.induction_on p (h_monomial 0) h_add (λ n a h, begin rw ← single_eq_C_mul_X at ⊢, exact h_monomial _ _, end) section coeff theorem coeff_mul_monomial (p : polynomial R) (n d : ℕ) (r : R) : coeff (p * monomial n r) (d + n) = coeff p d * r := by rw [single_eq_C_mul_X, ←X_pow_mul, ←mul_assoc, coeff_mul_C, coeff_mul_X_pow] theorem coeff_monomial_mul (p : polynomial R) (n d : ℕ) (r : R) : coeff (monomial n r * p) (d + n) = r * coeff p d := by rw [single_eq_C_mul_X, mul_assoc, coeff_C_mul, X_pow_mul, coeff_mul_X_pow] -- This can already be proved by `simp`. theorem coeff_mul_monomial_zero (p : polynomial R) (d : ℕ) (r : R) : coeff (p * monomial 0 r) d = coeff p d * r := coeff_mul_monomial p 0 d r -- This can already be proved by `simp`. theorem coeff_monomial_zero_mul (p : polynomial R) (d : ℕ) (r : R) : coeff (monomial 0 r * p) d = r * coeff p d := coeff_monomial_mul p 0 d r end coeff end semiring end polynomial
8e7ed442a5d2fe776a3857495a25e3748044a595
4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d
/src/Lean/Elab/ElabRules.lean
1c8214fcd76ed267db02490cca6a3589ef6ad941
[ "Apache-2.0" ]
permissive
subfish-zhou/leanprover-zh_CN.github.io
30b9fba9bd790720bd95764e61ae796697d2f603
8b2985d4a3d458ceda9361ac454c28168d920d3f
refs/heads/master
1,689,709,967,820
1,632,503,056,000
1,632,503,056,000
409,962,097
1
0
null
null
null
null
UTF-8
Lean
false
false
4,796
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.MacroArgUtil namespace Lean.Elab.Command open Lean.Syntax open Lean.Parser.Term hiding macroArg def withExpectedType (expectedType? : Option Expr) (x : Expr → TermElabM Expr) : TermElabM Expr := do Term.tryPostponeIfNoneOrMVar expectedType? let some expectedType ← pure expectedType? | throwError "expected type must be known" x expectedType def elabElabRulesAux (doc? : Option Syntax) (attrKind : Syntax) (k : SyntaxNodeKind) (cat? expty? : Option Syntax) (alts : Array Syntax) : CommandElabM Syntax := do let alts ← alts.mapM fun alt => match alt with | `(matchAltExpr| | $pats,* => $rhs) => do let pat := pats.elemsAndSeps[0] if !pat.isQuot then throwUnsupportedSyntax let quoted := getQuotContent pat let k' := quoted.getKind if checkRuleKind k' k then pure alt else if k' == choiceKind then match quoted.getArgs.find? fun quotAlt => checkRuleKind quotAlt.getKind k with | none => throwErrorAt alt "invalid elab_rules alternative, expected syntax node kind '{k}'" | some quoted => let pat := pat.setArg 1 quoted let pats := pats.elemsAndSeps.set! 0 pat `(matchAltExpr| | $pats,* => $rhs) else throwErrorAt alt "invalid elab_rules alternative, unexpected syntax node kind '{k'}'" | _ => throwUnsupportedSyntax let catName ← match cat?, expty? with | some cat, _ => cat.getId | _, some _ => `term -- TODO: infer category from quotation kind, possibly even kind of quoted syntax? | _, _ => throwError "invalid elab_rules command, specify category using `elab_rules : <cat> ...`" if let some expId := expty? then if catName == `term then `($[$doc?:docComment]? @[termElab $(← mkIdentFromRef k):ident] def elabFn : Lean.Elab.Term.TermElab := fun stx expectedType? => Lean.Elab.Command.withExpectedType expectedType? fun $expId => match stx with $alts:matchAlt* | _ => throwUnsupportedSyntax) else throwErrorAt expId "syntax category '{catName}' does not support expected type specification" else if catName == `term then `($[$doc?:docComment]? @[termElab $(← mkIdentFromRef k):ident] def elabFn : Lean.Elab.Term.TermElab := fun stx _ => match stx with $alts:matchAlt* | _ => throwUnsupportedSyntax) else if catName == `command then `($[$doc?:docComment]? @[commandElab $(← mkIdentFromRef k):ident] def elabFn : Lean.Elab.Command.CommandElab := fun $alts:matchAlt* | _ => throwUnsupportedSyntax) else if catName == `tactic then `($[$doc?:docComment]? @[tactic $(← mkIdentFromRef k):ident] def elabFn : Lean.Elab.Tactic.Tactic := fun $alts:matchAlt* | _ => throwUnsupportedSyntax) else -- We considered making the command extensible and support new user-defined categories. We think it is unnecessary. -- If users want this feature, they add their own `elab_rules` macro that uses this one as a fallback. throwError "unsupported syntax category '{catName}'" @[builtinCommandElab «elab_rules»] def elabElabRules : CommandElab := adaptExpander fun stx => match stx with | `($[$doc?:docComment]? $attrKind:attrKind elab_rules $[: $cat?]? $[<= $expty?]? $alts:matchAlt*) => expandNoKindMacroRulesAux alts "elab_rules" fun kind? alts => `($[$doc?:docComment]? $attrKind:attrKind elab_rules $[(kind := $(mkIdent <$> kind?))]? $[: $cat?]? $[<= $expty?]? $alts:matchAlt*) | `($[$doc?:docComment]? $attrKind:attrKind elab_rules (kind := $kind) $[: $cat?]? $[<= $expty?]? $alts:matchAlt*) => do elabElabRulesAux doc? attrKind (← resolveSyntaxKind kind.getId) cat? expty? alts | _ => throwUnsupportedSyntax @[builtinMacro Lean.Parser.Command.elab] def expandElab : Macro | `($[$doc?:docComment]? $attrKind:attrKind elab$[:$prec?]? $[(name := $name?)]? $[(priority := $prio?)]? $args:macroArg* : $cat $[<= $expectedType?]? => $rhs) => do let prio ← evalOptPrio prio? let catName := cat.getId let (stxParts, patArgs) := (← args.mapM expandMacroArg).unzip -- name let name ← match name? with | some name => pure name.getId | none => mkNameFromParserSyntax cat.getId (mkNullNode stxParts) let pat := Syntax.node ((← Macro.getCurrNamespace) ++ name) patArgs `($[$doc?:docComment]? $attrKind:attrKind syntax$[:$prec?]? (name := $(← mkIdentFromRef name)) (priority := $(quote prio)) $[$stxParts]* : $cat $[$doc?:docComment]? elab_rules : $cat $[<= $expectedType?]? | `($pat) => $rhs) | _ => Macro.throwUnsupported end Lean.Elab.Command
322cacc9f38a633192d5993f43715f45fc93a8e2
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/monoidal/coherence_lemmas.lean
0408bb098f37f11211ebb0491e4033ecbe4a934d
[ "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
2,592
lean
/- Copyright (c) 2018 Michael Jendrusch. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Michael Jendrusch, Scott Morrison, Bhavik Mehta, Jakob von Raumer -/ import category_theory.monoidal.coherence /-! # Lemmas which are consequences of monoidal coherence > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. These lemmas are all proved `by coherence`. ## Future work Investigate whether these lemmas are really needed, or if they can be replaced by use of the `coherence` tactic. -/ open category_theory open category_theory.category open category_theory.iso namespace category_theory.monoidal_category variables {C : Type*} [category C] [monoidal_category C] -- See Proposition 2.2.4 of <http://www-math.mit.edu/~etingof/egnobookfinal.pdf> @[reassoc] lemma left_unitor_tensor' (X Y : C) : ((α_ (𝟙_ C) X Y).hom) ≫ ((λ_ (X ⊗ Y)).hom) = ((λ_ X).hom ⊗ (𝟙 Y)) := by coherence @[reassoc, simp] lemma left_unitor_tensor (X Y : C) : ((λ_ (X ⊗ Y)).hom) = ((α_ (𝟙_ C) X Y).inv) ≫ ((λ_ X).hom ⊗ (𝟙 Y)) := by coherence @[reassoc] lemma left_unitor_tensor_inv (X Y : C) : (λ_ (X ⊗ Y)).inv = ((λ_ X).inv ⊗ (𝟙 Y)) ≫ (α_ (𝟙_ C) X Y).hom := by coherence @[reassoc] lemma id_tensor_right_unitor_inv (X Y : C) : 𝟙 X ⊗ (ρ_ Y).inv = (ρ_ _).inv ≫ (α_ _ _ _).hom := by coherence @[reassoc] lemma left_unitor_inv_tensor_id (X Y : C) : (λ_ X).inv ⊗ 𝟙 Y = (λ_ _).inv ≫ (α_ _ _ _).inv := by coherence @[reassoc] lemma pentagon_inv_inv_hom (W X Y Z : C) : (α_ W (X ⊗ Y) Z).inv ≫ ((α_ W X Y).inv ⊗ (𝟙 Z)) ≫ (α_ (W ⊗ X) Y Z).hom = ((𝟙 W) ⊗ (α_ X Y Z).hom) ≫ (α_ W X (Y ⊗ Z)).inv := by coherence @[simp, reassoc] lemma triangle_assoc_comp_right_inv (X Y : C) : ((ρ_ X).inv ⊗ 𝟙 Y) ≫ (α_ X (𝟙_ C) Y).hom = ((𝟙 X) ⊗ (λ_ Y).inv) := by coherence lemma unitors_equal : (λ_ (𝟙_ C)).hom = (ρ_ (𝟙_ C)).hom := by coherence lemma unitors_inv_equal : (λ_ (𝟙_ C)).inv = (ρ_ (𝟙_ C)).inv := by coherence @[reassoc] lemma pentagon_hom_inv {W X Y Z : C} : (α_ W X (Y ⊗ Z)).hom ≫ (𝟙 W ⊗ (α_ X Y Z).inv) = (α_ (W ⊗ X) Y Z).inv ≫ ((α_ W X Y).hom ⊗ 𝟙 Z) ≫ (α_ W (X ⊗ Y) Z).hom := by coherence @[reassoc] lemma pentagon_inv_hom (W X Y Z : C) : (α_ (W ⊗ X) Y Z).inv ≫ ((α_ W X Y).hom ⊗ 𝟙 Z) = (α_ W X (Y ⊗ Z)).hom ≫ (𝟙 W ⊗ (α_ X Y Z).inv) ≫ (α_ W (X ⊗ Y) Z).inv := by coherence end category_theory.monoidal_category
751a76801990235fc67958fbf3378d810f898c84
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/ring_theory/dedekind_domain/ideal.lean
bdc93ddfcbcf2e1d8e7005f6ca4b0c167c41329a
[ "Apache-2.0" ]
permissive
ramonfmir/mathlib
c5dc8b33155473fab97c38bd3aa6723dc289beaa
14c52e990c17f5a00c0cc9e09847af16fabbed25
refs/heads/master
1,661,979,343,526
1,660,830,384,000
1,660,830,384,000
182,072,989
0
0
null
1,555,585,876,000
1,555,585,876,000
null
UTF-8
Lean
false
false
53,293
lean
/- Copyright (c) 2020 Kenji Nakagawa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenji Nakagawa, Anne Baanen, Filippo A. E. Nuccio -/ import algebra.algebra.subalgebra.pointwise import algebraic_geometry.prime_spectrum.noetherian import order.hom.basic import ring_theory.dedekind_domain.basic import ring_theory.fractional_ideal import ring_theory.principal_ideal_domain /-! # Dedekind domains and ideals In this file, we show a ring is a Dedekind domain iff all fractional ideals are invertible. Then we prove some results on the unique factorization monoid structure of the ideals. ## Main definitions - `is_dedekind_domain_inv` alternatively defines a Dedekind domain as an integral domain where every nonzero fractional ideal is invertible. - `is_dedekind_domain_inv_iff` shows that this does note depend on the choice of field of fractions. - `is_dedekind_domain.height_one_spectrum` defines the type of nonzero prime ideals of `R`. ## Main results: - `is_dedekind_domain_iff_is_dedekind_domain_inv` - `ideal.unique_factorization_monoid` ## Implementation notes The definitions that involve a field of fractions choose a canonical field of fractions, but are independent of that choice. The `..._iff` lemmas express this independence. Often, definitions assume that Dedekind domains are not fields. We found it more practical to add a `(h : ¬ is_field A)` assumption whenever this is explicitly needed. ## References * [D. Marcus, *Number Fields*][marcus1977number] * [J.W.S. Cassels, A. Frölich, *Algebraic Number Theory*][cassels1967algebraic] * [J. Neukirch, *Algebraic Number Theory*][Neukirch1992] ## Tags dedekind domain, dedekind ring -/ variables (R A K : Type*) [comm_ring R] [comm_ring A] [field K] open_locale non_zero_divisors polynomial variables [is_domain A] section inverse namespace fractional_ideal variables {R₁ : Type*} [comm_ring R₁] [is_domain R₁] [algebra R₁ K] [is_fraction_ring R₁ K] variables {I J : fractional_ideal R₁⁰ K} noncomputable instance : has_inv (fractional_ideal R₁⁰ K) := ⟨λ I, 1 / I⟩ lemma inv_eq : I⁻¹ = 1 / I := rfl lemma inv_zero' : (0 : fractional_ideal R₁⁰ K)⁻¹ = 0 := fractional_ideal.div_zero lemma inv_nonzero {J : fractional_ideal R₁⁰ K} (h : J ≠ 0) : J⁻¹ = ⟨(1 : fractional_ideal R₁⁰ K) / J, fractional_ideal.fractional_div_of_nonzero h⟩ := fractional_ideal.div_nonzero _ lemma coe_inv_of_nonzero {J : fractional_ideal R₁⁰ K} (h : J ≠ 0) : (↑J⁻¹ : submodule R₁ K) = is_localization.coe_submodule K ⊤ / J := by { rwa inv_nonzero _, refl, assumption } variables {K} lemma mem_inv_iff (hI : I ≠ 0) {x : K} : x ∈ I⁻¹ ↔ ∀ y ∈ I, x * y ∈ (1 : fractional_ideal R₁⁰ K) := fractional_ideal.mem_div_iff_of_nonzero hI lemma inv_anti_mono (hI : I ≠ 0) (hJ : J ≠ 0) (hIJ : I ≤ J) : J⁻¹ ≤ I⁻¹ := λ x, by { simp only [mem_inv_iff hI, mem_inv_iff hJ], exact λ h y hy, h y (hIJ hy) } lemma le_self_mul_inv {I : fractional_ideal R₁⁰ K} (hI : I ≤ (1 : fractional_ideal R₁⁰ K)) : I ≤ I * I⁻¹ := fractional_ideal.le_self_mul_one_div hI variables (K) lemma coe_ideal_le_self_mul_inv (I : ideal R₁) : (I : fractional_ideal R₁⁰ K) ≤ I * I⁻¹ := le_self_mul_inv fractional_ideal.coe_ideal_le_one /-- `I⁻¹` is the inverse of `I` if `I` has an inverse. -/ theorem right_inverse_eq (I J : fractional_ideal R₁⁰ K) (h : I * J = 1) : J = I⁻¹ := begin have hI : I ≠ 0 := fractional_ideal.ne_zero_of_mul_eq_one I J h, suffices h' : I * (1 / I) = 1, { exact (congr_arg units.inv $ @units.ext _ _ (units.mk_of_mul_eq_one _ _ h) (units.mk_of_mul_eq_one _ _ h') rfl) }, apply le_antisymm, { apply fractional_ideal.mul_le.mpr _, intros x hx y hy, rw mul_comm, exact (fractional_ideal.mem_div_iff_of_nonzero hI).mp hy x hx }, rw ← h, apply fractional_ideal.mul_left_mono I, apply (fractional_ideal.le_div_iff_of_nonzero hI).mpr _, intros y hy x hx, rw mul_comm, exact fractional_ideal.mul_mem_mul hx hy end theorem mul_inv_cancel_iff {I : fractional_ideal R₁⁰ K} : I * I⁻¹ = 1 ↔ ∃ J, I * J = 1 := ⟨λ h, ⟨I⁻¹, h⟩, λ ⟨J, hJ⟩, by rwa ← right_inverse_eq K I J hJ⟩ lemma mul_inv_cancel_iff_is_unit {I : fractional_ideal R₁⁰ K} : I * I⁻¹ = 1 ↔ is_unit I := (mul_inv_cancel_iff K).trans is_unit_iff_exists_inv.symm variables {K' : Type*} [field K'] [algebra R₁ K'] [is_fraction_ring R₁ K'] @[simp] lemma map_inv (I : fractional_ideal R₁⁰ K) (h : K ≃ₐ[R₁] K') : (I⁻¹).map (h : K →ₐ[R₁] K') = (I.map h)⁻¹ := by rw [inv_eq, fractional_ideal.map_div, fractional_ideal.map_one, inv_eq] open submodule submodule.is_principal @[simp] lemma span_singleton_inv (x : K) : (fractional_ideal.span_singleton R₁⁰ x)⁻¹ = fractional_ideal.span_singleton _ (x⁻¹) := fractional_ideal.one_div_span_singleton x lemma mul_generator_self_inv {R₁ : Type*} [comm_ring R₁] [algebra R₁ K] [is_localization R₁⁰ K] (I : fractional_ideal R₁⁰ K) [submodule.is_principal (I : submodule R₁ K)] (h : I ≠ 0) : I * fractional_ideal.span_singleton _ (generator (I : submodule R₁ K))⁻¹ = 1 := begin -- Rewrite only the `I` that appears alone. conv_lhs { congr, rw fractional_ideal.eq_span_singleton_of_principal I }, rw [fractional_ideal.span_singleton_mul_span_singleton, mul_inv_cancel, fractional_ideal.span_singleton_one], intro generator_I_eq_zero, apply h, rw [fractional_ideal.eq_span_singleton_of_principal I, generator_I_eq_zero, fractional_ideal.span_singleton_zero] end lemma invertible_of_principal (I : fractional_ideal R₁⁰ K) [submodule.is_principal (I : submodule R₁ K)] (h : I ≠ 0) : I * I⁻¹ = 1 := (fractional_ideal.mul_div_self_cancel_iff).mpr ⟨fractional_ideal.span_singleton _ (generator (I : submodule R₁ K))⁻¹, mul_generator_self_inv _ I h⟩ lemma invertible_iff_generator_nonzero (I : fractional_ideal R₁⁰ K) [submodule.is_principal (I : submodule R₁ K)] : I * I⁻¹ = 1 ↔ generator (I : submodule R₁ K) ≠ 0 := begin split, { intros hI hg, apply fractional_ideal.ne_zero_of_mul_eq_one _ _ hI, rw [fractional_ideal.eq_span_singleton_of_principal I, hg, fractional_ideal.span_singleton_zero] }, { intro hg, apply invertible_of_principal, rw [fractional_ideal.eq_span_singleton_of_principal I], intro hI, have := fractional_ideal.mem_span_singleton_self _ (generator (I : submodule R₁ K)), rw [hI, fractional_ideal.mem_zero_iff] at this, contradiction } end lemma is_principal_inv (I : fractional_ideal R₁⁰ K) [submodule.is_principal (I : submodule R₁ K)] (h : I ≠ 0) : submodule.is_principal (I⁻¹).1 := begin rw [fractional_ideal.val_eq_coe, fractional_ideal.is_principal_iff], use (generator (I : submodule R₁ K))⁻¹, have hI : I * fractional_ideal.span_singleton _ ((generator (I : submodule R₁ K))⁻¹) = 1, apply mul_generator_self_inv _ I h, exact (right_inverse_eq _ I (fractional_ideal.span_singleton _ ((generator (I : submodule R₁ K))⁻¹)) hI).symm end @[simp] lemma inv_one : (1⁻¹ : fractional_ideal R₁⁰ K) = 1 := fractional_ideal.div_one end fractional_ideal /-- A Dedekind domain is an integral domain such that every fractional ideal has an inverse. This is equivalent to `is_dedekind_domain`. In particular we provide a `fractional_ideal.comm_group_with_zero` instance, assuming `is_dedekind_domain A`, which implies `is_dedekind_domain_inv`. For **integral** ideals, `is_dedekind_domain`(`_inv`) implies only `ideal.cancel_comm_monoid_with_zero`. -/ def is_dedekind_domain_inv : Prop := ∀ I ≠ (⊥ : fractional_ideal A⁰ (fraction_ring A)), I * I⁻¹ = 1 open fractional_ideal variables {R A K} lemma is_dedekind_domain_inv_iff [algebra A K] [is_fraction_ring A K] : is_dedekind_domain_inv A ↔ (∀ I ≠ (⊥ : fractional_ideal A⁰ K), I * I⁻¹ = 1) := begin let h := fractional_ideal.map_equiv (fraction_ring.alg_equiv A K), refine h.to_equiv.forall_congr (λ I, _), rw ← h.to_equiv.apply_eq_iff_eq, simp [is_dedekind_domain_inv, show ⇑h.to_equiv = h, from rfl], end lemma fractional_ideal.adjoin_integral_eq_one_of_is_unit [algebra A K] [is_fraction_ring A K] (x : K) (hx : is_integral A x) (hI : is_unit (adjoin_integral A⁰ x hx)) : adjoin_integral A⁰ x hx = 1 := begin set I := adjoin_integral A⁰ x hx, have mul_self : I * I = I, { apply fractional_ideal.coe_to_submodule_injective, simp }, convert congr_arg (* I⁻¹) mul_self; simp only [(mul_inv_cancel_iff_is_unit K).mpr hI, mul_assoc, mul_one], end namespace is_dedekind_domain_inv variables [algebra A K] [is_fraction_ring A K] (h : is_dedekind_domain_inv A) include h lemma mul_inv_eq_one {I : fractional_ideal A⁰ K} (hI : I ≠ 0) : I * I⁻¹ = 1 := is_dedekind_domain_inv_iff.mp h I hI lemma inv_mul_eq_one {I : fractional_ideal A⁰ K} (hI : I ≠ 0) : I⁻¹ * I = 1 := (mul_comm _ _).trans (h.mul_inv_eq_one hI) protected lemma is_unit {I : fractional_ideal A⁰ K} (hI : I ≠ 0) : is_unit I := is_unit_of_mul_eq_one _ _ (h.mul_inv_eq_one hI) lemma is_noetherian_ring : is_noetherian_ring A := begin refine is_noetherian_ring_iff.mpr ⟨λ (I : ideal A), _⟩, by_cases hI : I = ⊥, { rw hI, apply submodule.fg_bot }, have hI : (I : fractional_ideal A⁰ (fraction_ring A)) ≠ 0 := (coe_to_fractional_ideal_ne_zero (le_refl (non_zero_divisors A))).mpr hI, exact I.fg_of_is_unit (is_fraction_ring.injective A (fraction_ring A)) (h.is_unit hI) end lemma integrally_closed : is_integrally_closed A := begin -- It suffices to show that for integral `x`, -- `A[x]` (which is a fractional ideal) is in fact equal to `A`. refine ⟨λ x hx, _⟩, rw [← set.mem_range, ← algebra.mem_bot, ← subalgebra.mem_to_submodule, algebra.to_submodule_bot, ← coe_span_singleton A⁰ (1 : fraction_ring A), fractional_ideal.span_singleton_one, ← fractional_ideal.adjoin_integral_eq_one_of_is_unit x hx (h.is_unit _)], { exact mem_adjoin_integral_self A⁰ x hx }, { exact λ h, one_ne_zero (eq_zero_iff.mp h 1 (subalgebra.one_mem _)) }, end open ring lemma dimension_le_one : dimension_le_one A := begin -- We're going to show that `P` is maximal because any (maximal) ideal `M` -- that is strictly larger would be `⊤`. rintros P P_ne hP, refine ideal.is_maximal_def.mpr ⟨hP.ne_top, λ M hM, _⟩, -- We may assume `P` and `M` (as fractional ideals) are nonzero. have P'_ne : (P : fractional_ideal A⁰ (fraction_ring A)) ≠ 0 := (coe_to_fractional_ideal_ne_zero (le_refl (non_zero_divisors A))).mpr P_ne, have M'_ne : (M : fractional_ideal A⁰ (fraction_ring A)) ≠ 0 := (coe_to_fractional_ideal_ne_zero (le_refl (non_zero_divisors A))).mpr (lt_of_le_of_lt bot_le hM).ne', -- In particular, we'll show `M⁻¹ * P ≤ P` suffices : (M⁻¹ * P : fractional_ideal A⁰ (fraction_ring A)) ≤ P, { rw [eq_top_iff, ← coe_ideal_le_coe_ideal (fraction_ring A), fractional_ideal.coe_ideal_top], calc (1 : fractional_ideal A⁰ (fraction_ring A)) = _ * _ * _ : _ ... ≤ _ * _ : mul_right_mono (P⁻¹ * M : fractional_ideal A⁰ (fraction_ring A)) this ... = M : _, { rw [mul_assoc, ← mul_assoc ↑P, h.mul_inv_eq_one P'_ne, one_mul, h.inv_mul_eq_one M'_ne] }, { rw [← mul_assoc ↑P, h.mul_inv_eq_one P'_ne, one_mul] }, { apply_instance } }, -- Suppose we have `x ∈ M⁻¹ * P`, then in fact `x = algebra_map _ _ y` for some `y`. intros x hx, have le_one : (M⁻¹ * P : fractional_ideal A⁰ (fraction_ring A)) ≤ 1, { rw [← h.inv_mul_eq_one M'_ne], exact fractional_ideal.mul_left_mono _ ((coe_ideal_le_coe_ideal (fraction_ring A)).mpr hM.le) }, obtain ⟨y, hy, rfl⟩ := (mem_coe_ideal _).mp (le_one hx), -- Since `M` is strictly greater than `P`, let `z ∈ M \ P`. obtain ⟨z, hzM, hzp⟩ := set_like.exists_of_lt hM, -- We have `z * y ∈ M * (M⁻¹ * P) = P`. have zy_mem := fractional_ideal.mul_mem_mul (mem_coe_ideal_of_mem A⁰ hzM) hx, rw [← ring_hom.map_mul, ← mul_assoc, h.mul_inv_eq_one M'_ne, one_mul] at zy_mem, obtain ⟨zy, hzy, zy_eq⟩ := (mem_coe_ideal A⁰).mp zy_mem, rw is_fraction_ring.injective A (fraction_ring A) zy_eq at hzy, -- But `P` is a prime ideal, so `z ∉ P` implies `y ∈ P`, as desired. exact mem_coe_ideal_of_mem A⁰ (or.resolve_left (hP.mem_or_mem hzy) hzp) end /-- Showing one side of the equivalence between the definitions `is_dedekind_domain_inv` and `is_dedekind_domain` of Dedekind domains. -/ theorem is_dedekind_domain : is_dedekind_domain A := ⟨h.is_noetherian_ring, h.dimension_le_one, h.integrally_closed⟩ end is_dedekind_domain_inv variables [algebra A K] [is_fraction_ring A K] /-- Specialization of `exists_prime_spectrum_prod_le_and_ne_bot_of_domain` to Dedekind domains: Let `I : ideal A` be a nonzero ideal, where `A` is a Dedekind domain that is not a field. Then `exists_prime_spectrum_prod_le_and_ne_bot_of_domain` states we can find a product of prime ideals that is contained within `I`. This lemma extends that result by making the product minimal: let `M` be a maximal ideal that contains `I`, then the product including `M` is contained within `I` and the product excluding `M` is not contained within `I`. -/ lemma exists_multiset_prod_cons_le_and_prod_not_le [is_dedekind_domain A] (hNF : ¬ is_field A) {I M : ideal A} (hI0 : I ≠ ⊥) (hIM : I ≤ M) [hM : M.is_maximal] : ∃ (Z : multiset (prime_spectrum A)), (M ::ₘ (Z.map prime_spectrum.as_ideal)).prod ≤ I ∧ ¬ (multiset.prod (Z.map prime_spectrum.as_ideal) ≤ I) := begin -- Let `Z` be a minimal set of prime ideals such that their product is contained in `J`. obtain ⟨Z₀, hZ₀⟩ := prime_spectrum.exists_prime_spectrum_prod_le_and_ne_bot_of_domain hNF hI0, obtain ⟨Z, ⟨hZI, hprodZ⟩, h_eraseZ⟩ := multiset.well_founded_lt.has_min (λ Z, (Z.map prime_spectrum.as_ideal).prod ≤ I ∧ (Z.map prime_spectrum.as_ideal).prod ≠ ⊥) ⟨Z₀, hZ₀⟩, have hZM : multiset.prod (Z.map prime_spectrum.as_ideal) ≤ M := le_trans hZI hIM, have hZ0 : Z ≠ 0, { rintro rfl, simpa [hM.ne_top] using hZM }, obtain ⟨_, hPZ', hPM⟩ := (hM.is_prime.multiset_prod_le (mt multiset.map_eq_zero.mp hZ0)).mp hZM, -- Then in fact there is a `P ∈ Z` with `P ≤ M`. obtain ⟨P, hPZ, rfl⟩ := multiset.mem_map.mp hPZ', letI := classical.dec_eq (ideal A), have := multiset.map_erase prime_spectrum.as_ideal subtype.coe_injective P Z, obtain ⟨hP0, hZP0⟩ : P.as_ideal ≠ ⊥ ∧ ((Z.erase P).map prime_spectrum.as_ideal).prod ≠ ⊥, { rwa [ne.def, ← multiset.cons_erase hPZ', multiset.prod_cons, ideal.mul_eq_bot, not_or_distrib, ← this] at hprodZ }, -- By maximality of `P` and `M`, we have that `P ≤ M` implies `P = M`. have hPM' := (is_dedekind_domain.dimension_le_one _ hP0 P.is_prime).eq_of_le hM.ne_top hPM, substI hPM', -- By minimality of `Z`, erasing `P` from `Z` is exactly what we need. refine ⟨Z.erase P, _, _⟩, { convert hZI, rw [this, multiset.cons_erase hPZ'] }, { refine λ h, h_eraseZ (Z.erase P) ⟨h, _⟩ (multiset.erase_lt.mpr hPZ), exact hZP0 } end namespace fractional_ideal open ideal lemma exists_not_mem_one_of_ne_bot [is_dedekind_domain A] (hNF : ¬ is_field A) {I : ideal A} (hI0 : I ≠ ⊥) (hI1 : I ≠ ⊤) : ∃ x : K, x ∈ (I⁻¹ : fractional_ideal A⁰ K) ∧ x ∉ (1 : fractional_ideal A⁰ K) := begin -- WLOG, let `I` be maximal. suffices : ∀ {M : ideal A} (hM : M.is_maximal), ∃ x : K, x ∈ (M⁻¹ : fractional_ideal A⁰ K) ∧ x ∉ (1 : fractional_ideal A⁰ K), { obtain ⟨M, hM, hIM⟩ : ∃ (M : ideal A), is_maximal M ∧ I ≤ M := ideal.exists_le_maximal I hI1, resetI, have hM0 := (M.bot_lt_of_maximal hNF).ne', obtain ⟨x, hxM, hx1⟩ := this hM, refine ⟨x, inv_anti_mono _ _ ((coe_ideal_le_coe_ideal _).mpr hIM) hxM, hx1⟩; apply fractional_ideal.coe_ideal_ne_zero; assumption }, -- Let `a` be a nonzero element of `M` and `J` the ideal generated by `a`. intros M hM, resetI, obtain ⟨⟨a, haM⟩, ha0⟩ := submodule.nonzero_mem_of_bot_lt (M.bot_lt_of_maximal hNF), replace ha0 : a ≠ 0 := subtype.coe_injective.ne ha0, let J : ideal A := ideal.span {a}, have hJ0 : J ≠ ⊥ := mt ideal.span_singleton_eq_bot.mp ha0, have hJM : J ≤ M := ideal.span_le.mpr (set.singleton_subset_iff.mpr haM), have hM0 : ⊥ < M := M.bot_lt_of_maximal hNF, -- Then we can find a product of prime (hence maximal) ideals contained in `J`, -- such that removing element `M` from the product is not contained in `J`. obtain ⟨Z, hle, hnle⟩ := exists_multiset_prod_cons_le_and_prod_not_le hNF hJ0 hJM, -- Choose an element `b` of the product that is not in `J`. obtain ⟨b, hbZ, hbJ⟩ := set_like.not_le_iff_exists.mp hnle, have hnz_fa : algebra_map A K a ≠ 0 := mt ((injective_iff_map_eq_zero _).mp (is_fraction_ring.injective A K) a) ha0, have hb0 : algebra_map A K b ≠ 0 := mt ((injective_iff_map_eq_zero _).mp (is_fraction_ring.injective A K) b) (λ h, hbJ $ h.symm ▸ J.zero_mem), -- Then `b a⁻¹ : K` is in `M⁻¹` but not in `1`. refine ⟨algebra_map A K b * (algebra_map A K a)⁻¹, (mem_inv_iff _).mpr _, _⟩, { exact (fractional_ideal.coe_to_fractional_ideal_ne_zero le_rfl).mpr hM0.ne' }, { rintro y₀ hy₀, obtain ⟨y, h_Iy, rfl⟩ := (fractional_ideal.mem_coe_ideal _).mp hy₀, rw [mul_comm, ← mul_assoc, ← ring_hom.map_mul], have h_yb : y * b ∈ J, { apply hle, rw multiset.prod_cons, exact submodule.smul_mem_smul h_Iy hbZ }, rw ideal.mem_span_singleton' at h_yb, rcases h_yb with ⟨c, hc⟩, rw [← hc, ring_hom.map_mul, mul_assoc, mul_inv_cancel hnz_fa, mul_one], apply fractional_ideal.coe_mem_one }, { refine mt (fractional_ideal.mem_one_iff _).mp _, rintros ⟨x', h₂_abs⟩, rw [← div_eq_mul_inv, eq_div_iff_mul_eq hnz_fa, ← ring_hom.map_mul] at h₂_abs, have := ideal.mem_span_singleton'.mpr ⟨x', is_fraction_ring.injective A K h₂_abs⟩, contradiction }, end lemma one_mem_inv_coe_ideal {I : ideal A} (hI : I ≠ ⊥) : (1 : K) ∈ (I : fractional_ideal A⁰ K)⁻¹ := begin rw mem_inv_iff (fractional_ideal.coe_ideal_ne_zero hI), intros y hy, rw one_mul, exact coe_ideal_le_one hy, assumption end lemma mul_inv_cancel_of_le_one [h : is_dedekind_domain A] {I : ideal A} (hI0 : I ≠ ⊥) (hI : ((I * I⁻¹)⁻¹ : fractional_ideal A⁰ K) ≤ 1) : (I * I⁻¹ : fractional_ideal A⁰ K) = 1 := begin -- Handle a few trivial cases. by_cases hI1 : I = ⊤, { rw [hI1, coe_ideal_top, one_mul, fractional_ideal.inv_one] }, by_cases hNF : is_field A, { letI := hNF.to_field, rcases hI1 (I.eq_bot_or_top.resolve_left hI0) }, -- We'll show a contradiction with `exists_not_mem_one_of_ne_bot`: -- `J⁻¹ = (I * I⁻¹)⁻¹` cannot have an element `x ∉ 1`, so it must equal `1`. obtain ⟨J, hJ⟩ : ∃ (J : ideal A), (J : fractional_ideal A⁰ K) = I * I⁻¹ := le_one_iff_exists_coe_ideal.mp mul_one_div_le_one, by_cases hJ0 : J = ⊥, { subst hJ0, refine absurd _ hI0, rw [eq_bot_iff, ← coe_ideal_le_coe_ideal K, hJ], exact coe_ideal_le_self_mul_inv K I, apply_instance }, by_cases hJ1 : J = ⊤, { rw [← hJ, hJ1, coe_ideal_top] }, obtain ⟨x, hx, hx1⟩ : ∃ (x : K), x ∈ (J : fractional_ideal A⁰ K)⁻¹ ∧ x ∉ (1 : fractional_ideal A⁰ K) := exists_not_mem_one_of_ne_bot hNF hJ0 hJ1, contrapose! hx1 with h_abs, rw hJ at hx, exact hI hx, end /-- Nonzero integral ideals in a Dedekind domain are invertible. We will use this to show that nonzero fractional ideals are invertible, and finally conclude that fractional ideals in a Dedekind domain form a group with zero. -/ lemma coe_ideal_mul_inv [h : is_dedekind_domain A] (I : ideal A) (hI0 : I ≠ ⊥) : (I * I⁻¹ : fractional_ideal A⁰ K) = 1 := begin -- We'll show `1 ≤ J⁻¹ = (I * I⁻¹)⁻¹ ≤ 1`. apply mul_inv_cancel_of_le_one hI0, by_cases hJ0 : (I * I⁻¹ : fractional_ideal A⁰ K) = 0, { rw [hJ0, inv_zero'], exact fractional_ideal.zero_le _ }, intros x hx, -- In particular, we'll show all `x ∈ J⁻¹` are integral. suffices : x ∈ integral_closure A K, { rwa [is_integrally_closed.integral_closure_eq_bot, algebra.mem_bot, set.mem_range, ← fractional_ideal.mem_one_iff] at this; assumption }, -- For that, we'll find a subalgebra that is f.g. as a module and contains `x`. -- `A` is a noetherian ring, so we just need to find a subalgebra between `{x}` and `I⁻¹`. rw mem_integral_closure_iff_mem_fg, have x_mul_mem : ∀ b ∈ (I⁻¹ : fractional_ideal A⁰ K), x * b ∈ (I⁻¹ : fractional_ideal A⁰ K), { intros b hb, rw mem_inv_iff at ⊢ hx, swap, { exact fractional_ideal.coe_ideal_ne_zero hI0 }, swap, { exact hJ0 }, simp only [mul_assoc, mul_comm b] at ⊢ hx, intros y hy, exact hx _ (fractional_ideal.mul_mem_mul hy hb) }, -- It turns out the subalgebra consisting of all `p(x)` for `p : polynomial A` works. refine ⟨alg_hom.range (polynomial.aeval x : A[X] →ₐ[A] K), is_noetherian_submodule.mp (fractional_ideal.is_noetherian I⁻¹) _ (λ y hy, _), ⟨polynomial.X, polynomial.aeval_X x⟩⟩, obtain ⟨p, rfl⟩ := (alg_hom.mem_range _).mp hy, rw polynomial.aeval_eq_sum_range, refine submodule.sum_mem _ (λ i hi, submodule.smul_mem _ _ _), clear hi, induction i with i ih, { rw pow_zero, exact one_mem_inv_coe_ideal hI0 }, { show x ^ i.succ ∈ (I⁻¹ : fractional_ideal A⁰ K), rw pow_succ, exact x_mul_mem _ ih }, end /-- Nonzero fractional ideals in a Dedekind domain are units. This is also available as `_root_.mul_inv_cancel`, using the `comm_group_with_zero` instance defined below. -/ protected theorem mul_inv_cancel [is_dedekind_domain A] {I : fractional_ideal A⁰ K} (hne : I ≠ 0) : I * I⁻¹ = 1 := begin obtain ⟨a, J, ha, hJ⟩ : ∃ (a : A) (aI : ideal A), a ≠ 0 ∧ I = span_singleton A⁰ (algebra_map _ _ a)⁻¹ * aI := exists_eq_span_singleton_mul I, suffices h₂ : I * (span_singleton A⁰ (algebra_map _ _ a) * J⁻¹) = 1, { rw mul_inv_cancel_iff, exact ⟨span_singleton A⁰ (algebra_map _ _ a) * J⁻¹, h₂⟩ }, subst hJ, rw [mul_assoc, mul_left_comm (J : fractional_ideal A⁰ K), coe_ideal_mul_inv, mul_one, fractional_ideal.span_singleton_mul_span_singleton, inv_mul_cancel, fractional_ideal.span_singleton_one], { exact mt ((injective_iff_map_eq_zero (algebra_map A K)).mp (is_fraction_ring.injective A K) _) ha }, { exact fractional_ideal.coe_ideal_ne_zero_iff.mp (right_ne_zero_of_mul hne) } end lemma mul_right_le_iff [is_dedekind_domain A] {J : fractional_ideal A⁰ K} (hJ : J ≠ 0) : ∀ {I I'}, I * J ≤ I' * J ↔ I ≤ I' := begin intros I I', split, { intros h, convert mul_right_mono J⁻¹ h; rw [mul_assoc, fractional_ideal.mul_inv_cancel hJ, mul_one] }, { exact λ h, mul_right_mono J h } end lemma mul_left_le_iff [is_dedekind_domain A] {J : fractional_ideal A⁰ K} (hJ : J ≠ 0) {I I'} : J * I ≤ J * I' ↔ I ≤ I' := by convert fractional_ideal.mul_right_le_iff hJ using 1; simp only [mul_comm] lemma mul_right_strict_mono [is_dedekind_domain A] {I : fractional_ideal A⁰ K} (hI : I ≠ 0) : strict_mono (* I) := strict_mono_of_le_iff_le (λ _ _, (mul_right_le_iff hI).symm) lemma mul_left_strict_mono [is_dedekind_domain A] {I : fractional_ideal A⁰ K} (hI : I ≠ 0) : strict_mono ((*) I) := strict_mono_of_le_iff_le (λ _ _, (mul_left_le_iff hI).symm) /-- This is also available as `_root_.div_eq_mul_inv`, using the `comm_group_with_zero` instance defined below. -/ protected lemma div_eq_mul_inv [is_dedekind_domain A] (I J : fractional_ideal A⁰ K) : I / J = I * J⁻¹ := begin by_cases hJ : J = 0, { rw [hJ, div_zero, inv_zero', mul_zero] }, refine le_antisymm ((mul_right_le_iff hJ).mp _) ((le_div_iff_mul_le hJ).mpr _), { rw [mul_assoc, mul_comm J⁻¹, fractional_ideal.mul_inv_cancel hJ, mul_one, mul_le], intros x hx y hy, rw [mem_div_iff_of_nonzero hJ] at hx, exact hx y hy }, rw [mul_assoc, mul_comm J⁻¹, fractional_ideal.mul_inv_cancel hJ, mul_one], exact le_refl I end end fractional_ideal /-- `is_dedekind_domain` and `is_dedekind_domain_inv` are equivalent ways to express that an integral domain is a Dedekind domain. -/ theorem is_dedekind_domain_iff_is_dedekind_domain_inv : is_dedekind_domain A ↔ is_dedekind_domain_inv A := ⟨λ h I hI, by exactI fractional_ideal.mul_inv_cancel hI, λ h, h.is_dedekind_domain⟩ end inverse section is_dedekind_domain variables {R A} [is_dedekind_domain A] [algebra A K] [is_fraction_ring A K] open fractional_ideal open ideal noncomputable instance fractional_ideal.semifield : semifield (fractional_ideal A⁰ K) := { inv := λ I, I⁻¹, inv_zero := inv_zero' _, div := (/), div_eq_mul_inv := fractional_ideal.div_eq_mul_inv, exists_pair_ne := ⟨0, 1, (coe_to_fractional_ideal_injective le_rfl).ne (by simpa using @zero_ne_one (ideal A) _ _)⟩, mul_inv_cancel := λ I, fractional_ideal.mul_inv_cancel, .. fractional_ideal.comm_semiring } /-- Fractional ideals have cancellative multiplication in a Dedekind domain. Although this instance is a direct consequence of the instance `fractional_ideal.comm_group_with_zero`, we define this instance to provide a computable alternative. -/ instance fractional_ideal.cancel_comm_monoid_with_zero : cancel_comm_monoid_with_zero (fractional_ideal A⁰ K) := { .. fractional_ideal.comm_semiring, -- Project out the computable fields first. .. (by apply_instance : cancel_comm_monoid_with_zero (fractional_ideal A⁰ K)) } instance ideal.cancel_comm_monoid_with_zero : cancel_comm_monoid_with_zero (ideal A) := { .. ideal.comm_semiring, .. function.injective.cancel_comm_monoid_with_zero (coe_ideal_hom A⁰ (fraction_ring A)) coe_ideal_injective (ring_hom.map_zero _) (ring_hom.map_one _) (ring_hom.map_mul _) (ring_hom.map_pow _) } /-- For ideals in a Dedekind domain, to divide is to contain. -/ lemma ideal.dvd_iff_le {I J : ideal A} : (I ∣ J) ↔ J ≤ I := ⟨ideal.le_of_dvd, λ h, begin by_cases hI : I = ⊥, { have hJ : J = ⊥, { rwa [hI, ← eq_bot_iff] at h }, rw [hI, hJ] }, have hI' : (I : fractional_ideal A⁰ (fraction_ring A)) ≠ 0 := (fractional_ideal.coe_to_fractional_ideal_ne_zero (le_refl (non_zero_divisors A))).mpr hI, have : (I : fractional_ideal A⁰ (fraction_ring A))⁻¹ * J ≤ 1 := le_trans (fractional_ideal.mul_left_mono (↑I)⁻¹ ((coe_ideal_le_coe_ideal _).mpr h)) (le_of_eq (inv_mul_cancel hI')), obtain ⟨H, hH⟩ := fractional_ideal.le_one_iff_exists_coe_ideal.mp this, use H, refine coe_to_fractional_ideal_injective (le_refl (non_zero_divisors A)) (show (J : fractional_ideal A⁰ (fraction_ring A)) = _, from _), rw [fractional_ideal.coe_ideal_mul, hH, ← mul_assoc, mul_inv_cancel hI', one_mul] end⟩ lemma ideal.dvd_not_unit_iff_lt {I J : ideal A} : dvd_not_unit I J ↔ J < I := ⟨λ ⟨hI, H, hunit, hmul⟩, lt_of_le_of_ne (ideal.dvd_iff_le.mp ⟨H, hmul⟩) (mt (λ h, have H = 1, from mul_left_cancel₀ hI (by rw [← hmul, h, mul_one]), show is_unit H, from this.symm ▸ is_unit_one) hunit), λ h, dvd_not_unit_of_dvd_of_not_dvd (ideal.dvd_iff_le.mpr (le_of_lt h)) (mt ideal.dvd_iff_le.mp (not_le_of_lt h))⟩ instance : wf_dvd_monoid (ideal A) := { well_founded_dvd_not_unit := have well_founded ((>) : ideal A → ideal A → Prop) := is_noetherian_iff_well_founded.mp (is_noetherian_ring_iff.mp is_dedekind_domain.is_noetherian_ring), by { convert this, ext, rw ideal.dvd_not_unit_iff_lt } } instance ideal.unique_factorization_monoid : unique_factorization_monoid (ideal A) := { irreducible_iff_prime := λ P, ⟨λ hirr, ⟨hirr.ne_zero, hirr.not_unit, λ I J, begin have : P.is_maximal, { refine ⟨⟨mt ideal.is_unit_iff.mpr hirr.not_unit, _⟩⟩, intros J hJ, obtain ⟨J_ne, H, hunit, P_eq⟩ := ideal.dvd_not_unit_iff_lt.mpr hJ, exact ideal.is_unit_iff.mp ((hirr.is_unit_or_is_unit P_eq).resolve_right hunit) }, rw [ideal.dvd_iff_le, ideal.dvd_iff_le, ideal.dvd_iff_le, set_like.le_def, set_like.le_def, set_like.le_def], contrapose!, rintros ⟨⟨x, x_mem, x_not_mem⟩, ⟨y, y_mem, y_not_mem⟩⟩, exact ⟨x * y, ideal.mul_mem_mul x_mem y_mem, mt this.is_prime.mem_or_mem (not_or x_not_mem y_not_mem)⟩, end⟩, prime.irreducible⟩, .. ideal.wf_dvd_monoid } instance ideal.normalization_monoid : normalization_monoid (ideal A) := normalization_monoid_of_unique_units @[simp] lemma ideal.dvd_span_singleton {I : ideal A} {x : A} : I ∣ ideal.span {x} ↔ x ∈ I := ideal.dvd_iff_le.trans (ideal.span_le.trans set.singleton_subset_iff) lemma ideal.is_prime_of_prime {P : ideal A} (h : prime P) : is_prime P := begin refine ⟨_, λ x y hxy, _⟩, { unfreezingI { rintro rfl }, rw ← ideal.one_eq_top at h, exact h.not_unit is_unit_one }, { simp only [← ideal.dvd_span_singleton, ← ideal.span_singleton_mul_span_singleton] at ⊢ hxy, exact h.dvd_or_dvd hxy } end theorem ideal.prime_of_is_prime {P : ideal A} (hP : P ≠ ⊥) (h : is_prime P) : prime P := begin refine ⟨hP, mt ideal.is_unit_iff.mp h.ne_top, λ I J hIJ, _⟩, simpa only [ideal.dvd_iff_le] using (h.mul_le.mp (ideal.le_of_dvd hIJ)), end /-- In a Dedekind domain, the (nonzero) prime elements of the monoid with zero `ideal A` are exactly the prime ideals. -/ theorem ideal.prime_iff_is_prime {P : ideal A} (hP : P ≠ ⊥) : prime P ↔ is_prime P := ⟨ideal.is_prime_of_prime, ideal.prime_of_is_prime hP⟩ /-- In a Dedekind domain, the the prime ideals are the zero ideal together with the prime elements of the monoid with zero `ideal A`. -/ theorem ideal.is_prime_iff_bot_or_prime {P : ideal A} : is_prime P ↔ P = ⊥ ∨ prime P := ⟨λ hp, (eq_or_ne P ⊥).imp_right $ λ hp0, (ideal.prime_of_is_prime hp0 hp), λ hp, hp.elim (λ h, h.symm ▸ ideal.bot_prime) ideal.is_prime_of_prime⟩ lemma ideal.strict_anti_pow (I : ideal A) (hI0 : I ≠ ⊥) (hI1 : I ≠ ⊤) : strict_anti ((^) I : ℕ → ideal A) := strict_anti_nat_of_succ_lt $ λ e, ideal.dvd_not_unit_iff_lt.mp ⟨pow_ne_zero _ hI0, I, mt is_unit_iff.mp hI1, pow_succ' I e⟩ lemma ideal.pow_lt_self (I : ideal A) (hI0 : I ≠ ⊥) (hI1 : I ≠ ⊤) (e : ℕ) (he : 2 ≤ e) : I^e < I := by convert I.strict_anti_pow hI0 hI1 he; rw pow_one lemma ideal.exists_mem_pow_not_mem_pow_succ (I : ideal A) (hI0 : I ≠ ⊥) (hI1 : I ≠ ⊤) (e : ℕ) : ∃ x ∈ I^e, x ∉ I^(e+1) := set_like.exists_of_lt (I.strict_anti_pow hI0 hI1 e.lt_succ_self) lemma associates.le_singleton_iff (x : A) (n : ℕ) (I : ideal A) : associates.mk I^n ≤ associates.mk (ideal.span {x}) ↔ x ∈ I^n := begin rw [← associates.dvd_eq_le, ← associates.mk_pow, associates.mk_dvd_mk, ideal.dvd_span_singleton], end open fractional_ideal variables {A K} /-- Strengthening of `is_localization.exist_integer_multiples`: Let `J ≠ ⊤` be an ideal in a Dedekind domain `A`, and `f ≠ 0` a finite collection of elements of `K = Frac(A)`, then we can multiply the elements of `f` by some `a : K` to find a collection of elements of `A` that is not completely contained in `J`. -/ lemma ideal.exist_integer_multiples_not_mem {J : ideal A} (hJ : J ≠ ⊤) {ι : Type*} (s : finset ι) (f : ι → K) {j} (hjs : j ∈ s) (hjf : f j ≠ 0) : ∃ a : K, (∀ i ∈ s, is_localization.is_integer A (a * f i)) ∧ ∃ i ∈ s, (a * f i) ∉ (J : fractional_ideal A⁰ K) := begin -- Consider the fractional ideal `I` spanned by the `f`s. let I : fractional_ideal A⁰ K := fractional_ideal.span_finset A s f, have hI0 : I ≠ 0 := fractional_ideal.span_finset_ne_zero.mpr ⟨j, hjs, hjf⟩, -- We claim the multiplier `a` we're looking for is in `I⁻¹ \ (J / I)`. suffices : ↑J / I < I⁻¹, { obtain ⟨_, a, hI, hpI⟩ := set_like.lt_iff_le_and_exists.mp this, rw mem_inv_iff hI0 at hI, refine ⟨a, λ i hi, _, _⟩, -- By definition, `a ∈ I⁻¹` multiplies elements of `I` into elements of `1`, -- in other words, `a * f i` is an integer. { exact (mem_one_iff _).mp (hI (f i) (submodule.subset_span (set.mem_image_of_mem f hi))) }, { contrapose! hpI, -- And if all `a`-multiples of `I` are an element of `J`, -- then `a` is actually an element of `J / I`, contradiction. refine (mem_div_iff_of_nonzero hI0).mpr (λ y hy, submodule.span_induction hy _ _ _ _), { rintros _ ⟨i, hi, rfl⟩, exact hpI i hi }, { rw mul_zero, exact submodule.zero_mem _ }, { intros x y hx hy, rw mul_add, exact submodule.add_mem _ hx hy }, { intros b x hx, rw mul_smul_comm, exact submodule.smul_mem _ b hx } } }, -- To show the inclusion of `J / I` into `I⁻¹ = 1 / I`, note that `J < I`. calc ↑J / I = ↑J * I⁻¹ : div_eq_mul_inv ↑J I ... < 1 * I⁻¹ : mul_right_strict_mono (inv_ne_zero hI0) _ ... = I⁻¹ : one_mul _, { rw [← coe_ideal_top], -- And multiplying by `I⁻¹` is indeed strictly monotone. exact strict_mono_of_le_iff_le (λ _ _, (coe_ideal_le_coe_ideal K).symm) (lt_top_iff_ne_top.mpr hJ) }, end end is_dedekind_domain section is_dedekind_domain variables {T : Type*} [comm_ring T] [is_domain T] [is_dedekind_domain T] {I J : ideal T} open_locale classical open multiset unique_factorization_monoid ideal lemma prod_normalized_factors_eq_self (hI : I ≠ ⊥) : (normalized_factors I).prod = I := associated_iff_eq.1 (normalized_factors_prod hI) lemma count_le_of_ideal_ge {I J : ideal T} (h : I ≤ J) (hI : I ≠ ⊥) (K : ideal T) : count K (normalized_factors J) ≤ count K (normalized_factors I) := le_iff_count.1 ((dvd_iff_normalized_factors_le_normalized_factors (ne_bot_of_le_ne_bot hI h) hI).1 (dvd_iff_le.2 h)) _ lemma sup_eq_prod_inf_factors (hI : I ≠ ⊥) (hJ : J ≠ ⊥) : I ⊔ J = (normalized_factors I ∩ normalized_factors J).prod := begin have H : normalized_factors (normalized_factors I ∩ normalized_factors J).prod = normalized_factors I ∩ normalized_factors J, { apply normalized_factors_prod_of_prime, intros p hp, rw mem_inter at hp, exact prime_of_normalized_factor p hp.left }, have := (multiset.prod_ne_zero_of_prime (normalized_factors I ∩ normalized_factors J) (λ _ h, prime_of_normalized_factor _ (multiset.mem_inter.1 h).1)), apply le_antisymm, { rw [sup_le_iff, ← dvd_iff_le, ← dvd_iff_le], split, { rw [dvd_iff_normalized_factors_le_normalized_factors this hI, H], exact inf_le_left }, { rw [dvd_iff_normalized_factors_le_normalized_factors this hJ, H], exact inf_le_right } }, { rw [← dvd_iff_le, dvd_iff_normalized_factors_le_normalized_factors, normalized_factors_prod_of_prime, le_iff_count], { intro a, rw multiset.count_inter, exact le_min (count_le_of_ideal_ge le_sup_left hI a) (count_le_of_ideal_ge le_sup_right hJ a) }, { intros p hp, rw mem_inter at hp, exact prime_of_normalized_factor p hp.left }, { exact ne_bot_of_le_ne_bot hI le_sup_left }, { exact this } }, end lemma irreducible_pow_sup (hI : I ≠ ⊥) (hJ : irreducible J) (n : ℕ) : J^n ⊔ I = J^(min ((normalized_factors I).count J) n) := by rw [sup_eq_prod_inf_factors (pow_ne_zero n hJ.ne_zero) hI, ← inf_eq_inter, normalized_factors_of_irreducible_pow hJ, normalize_eq J, repeat_inf, prod_repeat] lemma irreducible_pow_sup_of_le (hJ : irreducible J) (n : ℕ) (hn : ↑n ≤ multiplicity J I) : J^n ⊔ I = J^n := begin by_cases hI : I = ⊥, { simp [*] at *, }, rw [irreducible_pow_sup hI hJ, min_eq_right], rwa [multiplicity_eq_count_normalized_factors hJ hI, part_enat.coe_le_coe, normalize_eq J] at hn end lemma irreducible_pow_sup_of_ge (hI : I ≠ ⊥) (hJ : irreducible J) (n : ℕ) (hn : multiplicity J I ≤ n) : J^n ⊔ I = J ^ (multiplicity J I).get (part_enat.dom_of_le_coe hn) := begin rw [irreducible_pow_sup hI hJ, min_eq_left], congr, { rw [← part_enat.coe_inj, part_enat.coe_get, multiplicity_eq_count_normalized_factors hJ hI, normalize_eq J] }, { rwa [multiplicity_eq_count_normalized_factors hJ hI, part_enat.coe_le_coe, normalize_eq J] at hn } end end is_dedekind_domain section height_one_spectrum /-! ### Height one spectrum of a Dedekind domain If `R` is a Dedekind domain of Krull dimension 1, the maximal ideals of `R` are exactly its nonzero prime ideals. We define `height_one_spectrum` and provide lemmas to recover the facts that prime ideals of height one are prime and irreducible. -/ namespace is_dedekind_domain variables [is_domain R] [is_dedekind_domain R] /-- The height one prime spectrum of a Dedekind domain `R` is the type of nonzero prime ideals of `R`. Note that this equals the maximal spectrum if `R` has Krull dimension 1. -/ @[ext, nolint has_nonempty_instance unused_arguments] structure height_one_spectrum := (as_ideal : ideal R) (is_prime : as_ideal.is_prime) (ne_bot : as_ideal ≠ ⊥) variables (v : height_one_spectrum R) {R} lemma height_one_spectrum.prime (v : height_one_spectrum R) : prime v.as_ideal := ideal.prime_of_is_prime v.ne_bot v.is_prime lemma height_one_spectrum.irreducible (v : height_one_spectrum R) : irreducible v.as_ideal := begin rw [unique_factorization_monoid.irreducible_iff_prime], apply v.prime, end lemma height_one_spectrum.associates_irreducible (v : height_one_spectrum R) : irreducible (associates.mk v.as_ideal) := begin rw [associates.irreducible_mk _], apply v.irreducible, end end is_dedekind_domain end height_one_spectrum section open ideal variables {R} {A} [is_dedekind_domain A] {I : ideal R} {J : ideal A} /-- The map from ideals of `R` dividing `I` to the ideals of `A` dividing `J` induced by a homomorphism `f : R/I →+* A/J` -/ @[simps] def ideal_factors_fun_of_quot_hom {f : R ⧸ I →+* A ⧸ J} (hf : function.surjective f ) : {p : ideal R | p ∣ I} →o {p : ideal A | p ∣ J} := { to_fun := λ X, ⟨comap J^.quotient.mk (map f (map I^.quotient.mk X)), begin have : (J^.quotient.mk).ker ≤ comap J^.quotient.mk (map f (map I^.quotient.mk X)), { exact ker_le_comap J^.quotient.mk }, rw mk_ker at this, exact dvd_iff_le.mpr this, end ⟩, monotone' := begin rintros ⟨X, hX⟩ ⟨Y, hY⟩ h, rw [← subtype.coe_le_coe, subtype.coe_mk, subtype.coe_mk] at h ⊢, rw [subtype.coe_mk, comap_le_comap_iff_of_surjective J^.quotient.mk quotient.mk_surjective, map_le_iff_le_comap, subtype.coe_mk, comap_map_of_surjective _ hf (map I^.quotient.mk Y)], suffices : map I^.quotient.mk X ≤ map I^.quotient.mk Y, { exact le_sup_of_le_left this }, rwa [map_le_iff_le_comap, comap_map_of_surjective I^.quotient.mk quotient.mk_surjective, ← ring_hom.ker_eq_comap_bot, mk_ker, sup_eq_left.mpr $ le_of_dvd hY], end } @[simp] lemma ideal_factors_fun_of_quot_hom_id : ideal_factors_fun_of_quot_hom (ring_hom.id (A ⧸ J)).is_surjective = order_hom.id := order_hom.ext _ _ (funext $ λ X, by simp only [ideal_factors_fun_of_quot_hom, map_id, order_hom.coe_fun_mk, order_hom.id_coe, id.def, comap_map_of_surjective J^.quotient.mk quotient.mk_surjective, ← ring_hom.ker_eq_comap_bot J^.quotient.mk, mk_ker, sup_eq_left.mpr (dvd_iff_le.mp X.prop), subtype.coe_eta] ) variables {B : Type*} [comm_ring B] [is_domain B] [is_dedekind_domain B] {L : ideal B} lemma ideal_factors_fun_of_quot_hom_comp {f : R ⧸ I →+* A ⧸ J} {g : A ⧸ J →+* B ⧸ L} (hf : function.surjective f) (hg : function.surjective g) : (ideal_factors_fun_of_quot_hom hg).comp (ideal_factors_fun_of_quot_hom hf) = ideal_factors_fun_of_quot_hom (show function.surjective (g.comp f), from hg.comp hf) := begin refine order_hom.ext _ _ (funext $ λ x, _), rw [ideal_factors_fun_of_quot_hom, ideal_factors_fun_of_quot_hom, order_hom.comp_coe, order_hom.coe_fun_mk, order_hom.coe_fun_mk, function.comp_app, ideal_factors_fun_of_quot_hom, order_hom.coe_fun_mk, subtype.mk_eq_mk, subtype.coe_mk, map_comap_of_surjective J^.quotient.mk quotient.mk_surjective, map_map], end variables [is_domain R] [is_dedekind_domain R] /-- The bijection between ideals of `R` dividing `I` and the ideals of `A` dividing `J` induced by an isomorphism `f : R/I ≅ A/J`. -/ @[simps] def ideal_factors_equiv_of_quot_equiv (f : R ⧸ I ≃+* A ⧸ J) : {p : ideal R | p ∣ I} ≃o {p : ideal A | p ∣ J} := order_iso.of_hom_inv (ideal_factors_fun_of_quot_hom (show function.surjective (f : R ⧸I →+* A ⧸ J), from f.surjective)) (ideal_factors_fun_of_quot_hom (show function.surjective (f.symm : A ⧸J →+* R ⧸ I), from f.symm.surjective)) (by simp only [← ideal_factors_fun_of_quot_hom_id, order_hom.coe_eq, order_hom.coe_eq, ideal_factors_fun_of_quot_hom_comp, ← ring_equiv.to_ring_hom_eq_coe, ← ring_equiv.to_ring_hom_eq_coe, ← ring_equiv.to_ring_hom_trans, ring_equiv.symm_trans_self, ring_equiv.to_ring_hom_refl]) (by simp only [← ideal_factors_fun_of_quot_hom_id, order_hom.coe_eq, order_hom.coe_eq, ideal_factors_fun_of_quot_hom_comp, ← ring_equiv.to_ring_hom_eq_coe, ← ring_equiv.to_ring_hom_eq_coe, ← ring_equiv.to_ring_hom_trans, ring_equiv.self_trans_symm, ring_equiv.to_ring_hom_refl]) end section chinese_remainder open ideal unique_factorization_monoid open_locale big_operators variables {R} lemma ring.dimension_le_one.prime_le_prime_iff_eq (h : ring.dimension_le_one R) {P Q : ideal R} [hP : P.is_prime] [hQ : Q.is_prime] (hP0 : P ≠ ⊥) : P ≤ Q ↔ P = Q := ⟨(h P hP0 hP).eq_of_le hQ.ne_top, eq.le⟩ lemma ideal.coprime_of_no_prime_ge {I J : ideal R} (h : ∀ P, I ≤ P → J ≤ P → ¬ is_prime P) : I ⊔ J = ⊤ := begin by_contra hIJ, obtain ⟨P, hP, hIJ⟩ := ideal.exists_le_maximal _ hIJ, exact h P (le_trans le_sup_left hIJ) (le_trans le_sup_right hIJ) hP.is_prime end section dedekind_domain variables {R} [is_domain R] [is_dedekind_domain R] lemma ideal.is_prime.mul_mem_pow (I : ideal R) [hI : I.is_prime] {a b : R} {n : ℕ} (h : a * b ∈ I^n) : a ∈ I ∨ b ∈ I^n := begin cases n, { simp }, by_cases hI0 : I = ⊥, { simpa [pow_succ, hI0] using h }, simp only [← submodule.span_singleton_le_iff_mem, ideal.submodule_span_eq, ← ideal.dvd_iff_le, ← ideal.span_singleton_mul_span_singleton] at h ⊢, by_cases ha : I ∣ span {a}, { exact or.inl ha }, rw mul_comm at h, exact or.inr (prime.pow_dvd_of_dvd_mul_right ((ideal.prime_iff_is_prime hI0).mpr hI) _ ha h), end section open_locale classical lemma ideal.count_normalized_factors_eq {p x : ideal R} [hp : p.is_prime] {n : ℕ} (hle : x ≤ p^n) (hlt : ¬ (x ≤ p^(n+1))) : (normalized_factors x).count p = n := count_normalized_factors_eq' ((ideal.is_prime_iff_bot_or_prime.mp hp).imp_right prime.irreducible) (by { haveI : unique (ideal R)ˣ := ideal.unique_units, apply normalize_eq }) (by convert ideal.dvd_iff_le.mpr hle) (by convert mt ideal.le_of_dvd hlt) /- Warning: even though a pure term-mode proof typechecks (the `by convert` can simply be removed), it's slower to the point of a possible timeout. -/ end lemma ideal.le_mul_of_no_prime_factors {I J K : ideal R} (coprime : ∀ P, J ≤ P → K ≤ P → ¬ is_prime P) (hJ : I ≤ J) (hK : I ≤ K) : I ≤ J * K := begin simp only [← ideal.dvd_iff_le] at coprime hJ hK ⊢, by_cases hJ0 : J = 0, { simpa only [hJ0, zero_mul] using hJ }, obtain ⟨I', rfl⟩ := hK, rw mul_comm, exact mul_dvd_mul_left K (unique_factorization_monoid.dvd_of_dvd_mul_right_of_no_prime_factors hJ0 (λ P hPJ hPK, mt ideal.is_prime_of_prime (coprime P hPJ hPK)) hJ) end lemma ideal.le_of_pow_le_prime {I P : ideal R} [hP : P.is_prime] {n : ℕ} (h : I^n ≤ P) : I ≤ P := begin by_cases hP0 : P = ⊥, { simp only [hP0, le_bot_iff] at ⊢ h, exact pow_eq_zero h }, rw ← ideal.dvd_iff_le at ⊢ h, exact ((ideal.prime_iff_is_prime hP0).mpr hP).dvd_of_dvd_pow h end lemma ideal.pow_le_prime_iff {I P : ideal R} [hP : P.is_prime] {n : ℕ} (hn : n ≠ 0) : I^n ≤ P ↔ I ≤ P := ⟨ideal.le_of_pow_le_prime, λ h, trans (ideal.pow_le_self hn) h⟩ lemma ideal.prod_le_prime {ι : Type*} {s : finset ι} {f : ι → ideal R} {P : ideal R} [hP : P.is_prime] : ∏ i in s, f i ≤ P ↔ ∃ i ∈ s, f i ≤ P := begin by_cases hP0 : P = ⊥, { simp only [hP0, le_bot_iff], rw [← ideal.zero_eq_bot, finset.prod_eq_zero_iff] }, simp only [← ideal.dvd_iff_le], exact ((ideal.prime_iff_is_prime hP0).mpr hP).dvd_finset_prod_iff _ end /-- The intersection of distinct prime powers in a Dedekind domain is the product of these prime powers. -/ lemma is_dedekind_domain.inf_prime_pow_eq_prod {ι : Type*} (s : finset ι) (f : ι → ideal R) (e : ι → ℕ) (prime : ∀ i ∈ s, prime (f i)) (coprime : ∀ i j ∈ s, i ≠ j → f i ≠ f j) : s.inf (λ i, f i ^ e i) = ∏ i in s, f i ^ e i := begin letI := classical.dec_eq ι, revert prime coprime, refine s.induction _ _, { simp }, intros a s ha ih prime coprime, specialize ih (λ i hi, prime i (finset.mem_insert_of_mem hi)) (λ i hi j hj, coprime i (finset.mem_insert_of_mem hi) j (finset.mem_insert_of_mem hj)), rw [finset.inf_insert, finset.prod_insert ha, ih], refine le_antisymm (ideal.le_mul_of_no_prime_factors _ inf_le_left inf_le_right) ideal.mul_le_inf, intros P hPa hPs hPp, haveI := hPp, obtain ⟨b, hb, hPb⟩ := ideal.prod_le_prime.mp hPs, haveI := ideal.is_prime_of_prime (prime a (finset.mem_insert_self a s)), haveI := ideal.is_prime_of_prime (prime b (finset.mem_insert_of_mem hb)), refine coprime a (finset.mem_insert_self a s) b (finset.mem_insert_of_mem hb) _ (((is_dedekind_domain.dimension_le_one.prime_le_prime_iff_eq _).mp (ideal.le_of_pow_le_prime hPa)).trans ((is_dedekind_domain.dimension_le_one.prime_le_prime_iff_eq _).mp (ideal.le_of_pow_le_prime hPb)).symm), { unfreezingI { rintro rfl }, contradiction }, { exact (prime a (finset.mem_insert_self a s)).ne_zero }, { exact (prime b (finset.mem_insert_of_mem hb)).ne_zero }, end /-- **Chinese remainder theorem** for a Dedekind domain: if the ideal `I` factors as `∏ i, P i ^ e i`, then `R ⧸ I` factors as `Π i, R ⧸ (P i ^ e i)`. -/ noncomputable def is_dedekind_domain.quotient_equiv_pi_of_prod_eq {ι : Type*} [fintype ι] (I : ideal R) (P : ι → ideal R) (e : ι → ℕ) (prime : ∀ i, prime (P i)) (coprime : ∀ i j, i ≠ j → P i ≠ P j) (prod_eq : (∏ i, P i ^ e i) = I) : R ⧸ I ≃+* Π i, R ⧸ (P i ^ e i) := (ideal.quot_equiv_of_eq (by { simp only [← prod_eq, finset.inf_eq_infi, finset.mem_univ, cinfi_pos, ← is_dedekind_domain.inf_prime_pow_eq_prod _ _ _ (λ i _, prime i) (λ i _ j _, coprime i j)] })) .trans $ ideal.quotient_inf_ring_equiv_pi_quotient _ (λ i j hij, ideal.coprime_of_no_prime_ge (begin intros P hPi hPj hPp, haveI := hPp, haveI := ideal.is_prime_of_prime (prime i), haveI := ideal.is_prime_of_prime (prime j), exact coprime i j hij (((is_dedekind_domain.dimension_le_one.prime_le_prime_iff_eq (prime i).ne_zero).mp (ideal.le_of_pow_le_prime hPi)).trans ((is_dedekind_domain.dimension_le_one.prime_le_prime_iff_eq (prime j).ne_zero).mp (ideal.le_of_pow_le_prime hPj)).symm) end)) open_locale classical /-- **Chinese remainder theorem** for a Dedekind domain: `R ⧸ I` factors as `Π i, R ⧸ (P i ^ e i)`, where `P i` ranges over the prime factors of `I` and `e i` over the multiplicities. -/ noncomputable def is_dedekind_domain.quotient_equiv_pi_factors {I : ideal R} (hI : I ≠ ⊥) : R ⧸ I ≃+* Π (P : (factors I).to_finset), R ⧸ ((P : ideal R) ^ (factors I).count P) := is_dedekind_domain.quotient_equiv_pi_of_prod_eq _ _ _ (λ (P : (factors I).to_finset), prime_of_factor _ (multiset.mem_to_finset.mp P.prop)) (λ i j hij, subtype.coe_injective.ne hij) (calc ∏ (P : (factors I).to_finset), (P : ideal R) ^ (factors I).count (P : ideal R) = ∏ P in (factors I).to_finset, P ^ (factors I).count P : (factors I).to_finset.prod_coe_sort (λ P, P ^ (factors I).count P) ... = ((factors I).map (λ P, P)).prod : (finset.prod_multiset_map_count (factors I) id).symm ... = (factors I).prod : by rw multiset.map_id' ... = I : (@associated_iff_eq (ideal R) _ ideal.unique_units _ _).mp (factors_prod hI)) @[simp] lemma is_dedekind_domain.quotient_equiv_pi_factors_mk {I : ideal R} (hI : I ≠ ⊥) (x : R) : is_dedekind_domain.quotient_equiv_pi_factors hI (ideal.quotient.mk I x) = λ P, ideal.quotient.mk _ x := rfl end dedekind_domain end chinese_remainder section PID open multiplicity unique_factorization_monoid ideal variables {R} [is_domain R] [is_principal_ideal_ring R] lemma span_singleton_dvd_span_singleton_iff_dvd {a b : R} : (ideal.span {a}) ∣ (ideal.span ({b} : set R)) ↔ a ∣ b := ⟨λ h, mem_span_singleton.mp (dvd_iff_le.mp h (mem_span_singleton.mpr (dvd_refl b))), λ h, dvd_iff_le.mpr (λ d hd, mem_span_singleton.mpr (dvd_trans h (mem_span_singleton.mp hd)))⟩ lemma singleton_span_mem_normalized_factors_of_mem_normalized_factors [normalization_monoid R] [decidable_eq R] [decidable_eq (ideal R)] {a b : R} (ha : a ∈ normalized_factors b) : ideal.span ({a} : set R) ∈ normalized_factors (ideal.span ({b} : set R)) := begin by_cases hb : b = 0, { rw [ideal.span_singleton_eq_bot.mpr hb, bot_eq_zero, normalized_factors_zero], rw [hb, normalized_factors_zero] at ha, simpa only [multiset.not_mem_zero] }, { suffices : prime (ideal.span ({a} : set R)), { obtain ⟨c, hc, hc'⟩ := exists_mem_normalized_factors_of_dvd _ this.irreducible (dvd_iff_le.mpr (span_singleton_le_span_singleton.mpr (dvd_of_mem_normalized_factors ha))), rwa associated_iff_eq.mp hc', { by_contra, exact hb (span_singleton_eq_bot.mp h) } }, rw prime_iff_is_prime, exact (span_singleton_prime (prime_of_normalized_factor a ha).ne_zero).mpr (prime_of_normalized_factor a ha), by_contra, exact (prime_of_normalized_factor a ha).ne_zero (span_singleton_eq_bot.mp h) }, end /-- The bijection between the (normalized) prime factors of `r` and the (normalized) prime factors of `span {r}` -/ @[simps] noncomputable def normalized_factors_equiv_span_normalized_factors [normalization_monoid R] [decidable_eq R] [decidable_eq (ideal R)] {r : R} (hr : r ≠ 0) : {d : R | d ∈ normalized_factors r} ≃ {I : ideal R | I ∈ normalized_factors (ideal.span ({r} : set R))} := equiv.of_bijective (λ d, ⟨ideal.span {↑d}, singleton_span_mem_normalized_factors_of_mem_normalized_factors d.prop⟩) begin split, { rintros ⟨a, ha⟩ ⟨b, hb⟩ h, rw [subtype.mk_eq_mk, ideal.span_singleton_eq_span_singleton, subtype.coe_mk, subtype.coe_mk] at h, exact subtype.mk_eq_mk.mpr (mem_normalized_factors_eq_of_associated ha hb h) }, { rintros ⟨i, hi⟩, letI : i.is_principal := infer_instance, letI : i.is_prime := is_prime_of_prime (prime_of_normalized_factor i hi), obtain ⟨a, ha, ha'⟩ := exists_mem_normalized_factors_of_dvd hr (submodule.is_principal.prime_generator_of_is_prime i (prime_of_normalized_factor i hi).ne_zero).irreducible _, { use ⟨a, ha⟩, simp only [subtype.coe_mk, subtype.mk_eq_mk, ← span_singleton_eq_span_singleton.mpr ha', ideal.span_singleton_generator] }, {exact (submodule.is_principal.mem_iff_generator_dvd i).mp (((show ideal.span {r} ≤ i, from dvd_iff_le.mp (dvd_of_mem_normalized_factors hi))) (mem_span_singleton.mpr (dvd_refl r))) } } end lemma multiplicity_eq_multiplicity_span [decidable_rel ((∣) : R → R → Prop)] [decidable_rel ((∣) : ideal R → ideal R → Prop)] {a b : R} : multiplicity (ideal.span {a}) (ideal.span ({b} : set R)) = multiplicity a b := begin by_cases h : finite a b, { rw ← part_enat.coe_get (finite_iff_dom.mp h), refine (multiplicity.unique (show (ideal.span {a})^(((multiplicity a b).get h)) ∣ (ideal.span {b}), from _) _).symm ; rw [ideal.span_singleton_pow, span_singleton_dvd_span_singleton_iff_dvd], exact pow_multiplicity_dvd h , { exact multiplicity.is_greatest ((part_enat.lt_coe_iff _ _).mpr (exists.intro (finite_iff_dom.mp h) (nat.lt_succ_self _))) } }, { suffices : ¬ (finite (ideal.span ({a} : set R)) (ideal.span ({b} : set R))), { rw [finite_iff_dom, part_enat.not_dom_iff_eq_top] at h this, rw [h, this] }, refine not_finite_iff_forall.mpr (λ n, by {rw [ideal.span_singleton_pow, span_singleton_dvd_span_singleton_iff_dvd], exact not_finite_iff_forall.mp h n }) } end end PID
6e4f9969f5eb9c8d8eb9211d3c0c100468e01d7b
dc253be9829b840f15d96d986e0c13520b085033
/homology/basic.hlean
e884723ca50d4057fd59a52ed39f10ceed63925b
[ "Apache-2.0" ]
permissive
cmu-phil/Spectral
4ce68e5c1ef2a812ffda5260e9f09f41b85ae0ea
3b078f5f1de251637decf04bd3fc8aa01930a6b3
refs/heads/master
1,685,119,195,535
1,684,169,772,000
1,684,169,772,000
46,450,197
42
13
null
1,505,516,767,000
1,447,883,921,000
Lean
UTF-8
Lean
false
false
11,237
hlean
/- Copyright (c) 2017 Yuri Sulyma, Favonia Released under Apache 2.0 license as described in the file LICENSE. Authors: Yuri Sulyma, Favonia, Floris van Doorn Reduced homology theories -/ import ..spectrum.smash ..homotopy.wedge open eq spectrum int pointed group algebra sphere nat equiv susp is_trunc function fwedge cofiber lift is_equiv choice algebra pi smash wedge namespace homology /- homology theory -/ structure homology_theory.{u} : Type.{u+1} := (HH : ℤ → pType.{u} → AbGroup.{u}) (Hh : Π(n : ℤ) {X Y : Type*} (f : X →* Y), HH n X →g HH n Y) (Hpid : Π(n : ℤ) {X : Type*} (x : HH n X), Hh n (pid X) x = x) (Hpcompose : Π(n : ℤ) {X Y Z : Type*} (f : Y →* Z) (g : X →* Y), Hh n (f ∘* g) ~ Hh n f ∘ Hh n g) (Hsusp : Π(n : ℤ) (X : Type*), HH (succ n) (susp X) ≃g HH n X) (Hsusp_natural : Π(n : ℤ) {X Y : Type*} (f : X →* Y), Hsusp n Y ∘ Hh (succ n) (susp_functor f) ~ Hh n f ∘ Hsusp n X) (Hexact : Π(n : ℤ) {X Y : Type*} (f : X →* Y), is_exact_g (Hh n f) (Hh n (pcod f))) (Hadditive : Π(n : ℤ) {I : Set.{u}} (X : I → Type*), is_equiv (dirsum_elim (λi, Hh n (pinl i)) : dirsum (λi, HH n (X i)) → HH n (⋁ X))) structure ordinary_homology_theory.{u} extends homology_theory.{u} : Type.{u+1} := (Hdimension : Π(n : ℤ), n ≠ 0 → is_contr (HH n (plift (sphere 0)))) section universe variable u parameter (theory : homology_theory.{u}) open homology_theory theorem HH_base_indep (n : ℤ) {A : Type} (a b : A) : HH theory n (pType.mk A a) ≃g HH theory n (pType.mk A b) := calc HH theory n (pType.mk A a) ≃g HH theory (int.succ n) (susp A) : by exact (Hsusp theory n (pType.mk A a)) ⁻¹ᵍ ... ≃g HH theory n (pType.mk A b) : by exact Hsusp theory n (pType.mk A b) theorem Hh_homotopy' (n : ℤ) {A B : Type*} (f : A → B) (p q : f pt = pt) : Hh theory n (pmap.mk f p) ~ Hh theory n (pmap.mk f q) := λ x, calc Hh theory n (pmap.mk f p) x = Hh theory n (pmap.mk f p) (Hsusp theory n A ((Hsusp theory n A)⁻¹ᵍ x)) : by exact ap (Hh theory n (pmap.mk f p)) (equiv.to_right_inv (equiv_of_isomorphism (Hsusp theory n A)) x)⁻¹ ... = Hsusp theory n B (Hh theory (succ n) (pmap.mk (susp_functor' f) !refl) ((Hsusp theory n A)⁻¹ x)) : by exact (Hsusp_natural theory n (pmap.mk f p) ((Hsusp theory n A)⁻¹ᵍ x))⁻¹ ... = Hh theory n (pmap.mk f q) (Hsusp theory n A ((Hsusp theory n A)⁻¹ x)) : by exact Hsusp_natural theory n (pmap.mk f q) ((Hsusp theory n A)⁻¹ x) ... = Hh theory n (pmap.mk f q) x : by exact ap (Hh theory n (pmap.mk f q)) (equiv.to_right_inv (equiv_of_isomorphism (Hsusp theory n A)) x) theorem Hh_homotopy (n : ℤ) {A B : Type*} (f g : A →* B) (h : f ~ g) : Hh theory n f ~ Hh theory n g := λ x, calc Hh theory n f x = Hh theory n (pmap.mk f (respect_pt f)) x : by exact ap (λ f, Hh theory n f x) (pmap_eta_eq f)⁻¹ ... = Hh theory n (pmap.mk f (h pt ⬝ respect_pt g)) x : by exact Hh_homotopy' n f (respect_pt f) (h pt ⬝ respect_pt g) x ... = Hh theory n g x : begin apply ap (λ f, Hh theory n f x), apply eq_of_phomotopy, fapply phomotopy.mk, { exact h }, reflexivity end definition HH_isomorphism (n : ℤ) {A B : Type*} (e : A ≃* B) : HH theory n A ≃g HH theory n B := begin fapply isomorphism.mk, { exact Hh theory n e }, fapply adjointify, { exact Hh theory n e⁻¹ᵉ* }, { intro x, exact calc Hh theory n e (Hh theory n e⁻¹ᵉ* x) = Hh theory n (e ∘* e⁻¹ᵉ*) x : by exact (Hpcompose theory n e e⁻¹ᵉ* x)⁻¹ ... = Hh theory n !pid x : by exact Hh_homotopy n (e ∘* e⁻¹ᵉ*) !pid (to_right_inv e) x ... = x : by exact Hpid theory n x }, { intro x, exact calc Hh theory n e⁻¹ᵉ* (Hh theory n e x) = Hh theory n (e⁻¹ᵉ* ∘* e) x : by exact (Hpcompose theory n e⁻¹ᵉ* e x)⁻¹ ... = Hh theory n !pid x : by exact Hh_homotopy n (e⁻¹ᵉ* ∘* e) !pid (to_left_inv e) x ... = x : by exact Hpid theory n x } end definition Hadditive_equiv (n : ℤ) {I : Type} [is_set I] (X : I → Type*) : dirsum (λi, HH theory n (X i)) ≃g HH theory n (⋁ X) := isomorphism.mk (dirsum_elim (λi, Hh theory n (fwedge.pinl i))) (Hadditive theory n X) definition Hadditive' (n : ℤ) {I : Type₀} [is_set I] (X : I → pType.{u}) : is_equiv (dirsum_elim (λi, Hh theory n (pinl i)) : dirsum (λi, HH theory n (X i)) → HH theory n (⋁ X)) := let iso3 := HH_isomorphism n (fwedge_down_left.{0 u} X) in let iso2 := Hadditive_equiv n (X ∘ down.{0 u}) in let iso1 := (dirsum_down_left.{0 u} (λ i, HH theory n (X i)))⁻¹ᵍ in let iso := calc dirsum (λ i, HH theory n (X i)) ≃g dirsum (λ i, HH theory n (X (down.{0 u} i))) : by exact iso1 ... ≃g HH theory n (⋁ (X ∘ down.{0 u})) : by exact iso2 ... ≃g HH theory n (⋁ X) : by exact iso3 in begin fapply is_equiv_of_equiv_of_homotopy, { exact equiv_of_isomorphism iso }, { refine dirsum_homotopy _, intro i y, refine homomorphism_compose_eq iso3 (iso2 ∘g iso1) _ ⬝ _, refine ap iso3 (homomorphism_compose_eq iso2 iso1 _) ⬝ _, refine ap (iso3 ∘ iso2) _ ⬝ _, { exact dirsum_incl (λ i, HH theory n (X (down i))) (up i) y }, { refine _ ⬝ dirsum_elim_compute (λi, dirsum_incl (λ i, HH theory n (X (down.{0 u} i))) (up i)) i y, reflexivity }, refine ap iso3 _ ⬝ _, { exact Hh theory n (fwedge.pinl (up i)) y }, { refine _ ⬝ dirsum_elim_compute (λi, Hh theory n (fwedge.pinl i)) (up i) y, reflexivity }, refine (Hpcompose theory n (fwedge_down_left X) (fwedge.pinl (up i)) y)⁻¹ ⬝ _, refine Hh_homotopy n (fwedge_down_left.{0 u} X ∘* fwedge.pinl (up i)) (fwedge.pinl i) (fwedge_pmap_beta (λ i, pinl (down i)) (up i)) y ⬝ _, refine (dirsum_elim_compute (λ i, Hh theory n (pinl i)) i y)⁻¹ } end definition Hadditive'_equiv (n : ℤ) {I : Type₀} [is_set I] (X : I → Type*) : dirsum (λi, HH theory n (X i)) ≃g HH theory n (⋁ X) := isomorphism.mk (dirsum_elim (λi, Hh theory n (fwedge.pinl i))) (Hadditive' n X) definition Hfwedge (n : ℤ) {I : Type} [is_set I] (X : I → Type*): HH theory n (⋁ X) ≃g dirsum (λi, HH theory n (X i)) := (isomorphism.mk _ (Hadditive theory n X))⁻¹ᵍ definition Hwedge (n : ℤ) (A B : Type*) : HH theory n (wedge A B) ≃g HH theory n A ×g HH theory n B := calc HH theory n (A ∨ B) ≃g HH theory n (⋁ (bool.rec A B)) : by exact HH_isomorphism n (wedge_pequiv_fwedge A B) ... ≃g dirsum (λb, HH theory n (bool.rec A B b)) : by exact (Hadditive'_equiv n (bool.rec A B))⁻¹ᵍ ... ≃g dirsum (bool.rec (HH theory n A) (HH theory n B)) : by exact dirsum_isomorphism (bool.rec !isomorphism.refl !isomorphism.refl) ... ≃g HH theory n A ×g HH theory n B : by exact binary_dirsum (HH theory n A) (HH theory n B) end section universe variables u v parameter (theory : homology_theory.{max u v}) open homology_theory definition Hplift_susp (n : ℤ) (A : Type*): HH theory (n + 1) (plift.{u v} (susp A)) ≃g HH theory n (plift.{u v} A) := calc HH theory (n + 1) (plift.{u v} (susp A)) ≃g HH theory (n + 1) (susp (plift.{u v} A)) : by exact HH_isomorphism theory (n + 1) (plift_susp _) ... ≃g HH theory n (plift.{u v} A) : by exact Hsusp theory n (plift.{u v} A) definition Hplift_wedge (n : ℤ) (A B : Type*): HH theory n (plift.{u v} (A ∨ B)) ≃g HH theory n (plift.{u v} A) ×g HH theory n (plift.{u v} B) := calc HH theory n (plift.{u v} (A ∨ B)) ≃g HH theory n (plift.{u v} A ∨ plift.{u v} B) : by exact HH_isomorphism theory n (plift_wedge A B) ... ≃g HH theory n (plift.{u v} A) ×g HH theory n (plift.{u v} B) : by exact Hwedge theory n (plift.{u v} A) (plift.{u v} B) definition Hplift_isomorphism (n : ℤ) {A B : Type*} (e : A ≃* B) : HH theory n (plift.{u v} A) ≃g HH theory n (plift.{u v} B) := HH_isomorphism theory n (!pequiv_plift⁻¹ᵉ* ⬝e* e ⬝e* !pequiv_plift) end /- homology theory associated to a prespectrum -/ definition homology (X : Type*) (E : prespectrum) (n : ℤ) : AbGroup := pshomotopy_group n (smash_prespectrum X E) /- an alternative definition, which might be a bit harder to work with -/ definition homology_spectrum (X : Type*) (E : spectrum) (n : ℤ) : AbGroup := shomotopy_group n (smash_spectrum X E) definition parametrized_homology {X : Type*} (E : X → spectrum) (n : ℤ) : AbGroup := sorry definition ordinary_homology [reducible] (X : Type*) (G : AbGroup) (n : ℤ) : AbGroup := homology X (EM_spectrum G) n definition ordinary_homology_Z [reducible] (X : Type*) (n : ℤ) : AbGroup := ordinary_homology X agℤ n notation `H_` n `[`:0 X:0 `, ` E:0 `]`:0 := homology X E n notation `H_` n `[`:0 X:0 `]`:0 := ordinary_homology_Z X n notation `pH_` n `[`:0 binders `, ` r:(scoped E, parametrized_homology E n) `]`:0 := r definition unpointed_homology (X : Type) (E : spectrum) (n : ℤ) : AbGroup := H_ n[X₊, E] definition homology_functor [constructor] {X Y : Type*} {E F : prespectrum} (f : X →* Y) (g : E →ₛ F) (n : ℤ) : homology X E n →g homology Y F n := pshomotopy_group_fun n (smash_prespectrum_fun f g) definition homology_theory_spectrum_is_exact.{u} (E : spectrum.{u}) (n : ℤ) {X Y : Type*} (f : X →* Y) : is_exact_g (homology_functor f (sid E) n) (homology_functor (pcod f) (sid E) n) := begin -- fconstructor, -- { intro a, exact sorry }, -- { intro a, exact sorry } exact sorry end definition homology_theory_spectrum.{u} [constructor] (E : spectrum.{u}) : homology_theory.{u} := begin fapply homology_theory.mk, exact (λn X, H_ n[X, E]), exact (λn X Y f, homology_functor f (sid E) n), exact sorry, -- Hid is uninteresting but potentially very hard to prove exact sorry, exact sorry, exact sorry, apply homology_theory_spectrum_is_exact, exact sorry -- sorry -- sorry -- sorry -- sorry -- sorry -- sorry -- (λn A, H^n[A, Y]) -- (λn A B f, cohomology_isomorphism f Y n) -- (λn A, cohomology_isomorphism_refl A Y n) -- (λn A B f, cohomology_functor f Y n) -- (λn A B f g p, cohomology_functor_phomotopy p Y n) -- (λn A B f x, cohomology_functor_phomotopy_refl f Y n x) -- (λn A x, cohomology_functor_pid A Y n x) -- (λn A B C g f x, cohomology_functor_pcompose g f Y n x) -- (λn A, cohomology_susp A Y n) -- (λn A B f, cohomology_susp_natural f Y n) -- (λn A B f, cohomology_exact f Y n) -- (λn I A H, spectrum_additive H A Y n) end end homology
869e7b9052bc3c7b4e036848e3ac5e5eb48ab35b
5749d8999a76f3a8fddceca1f6941981e33aaa96
/src/ring_theory/power_series.lean
a3069865993bd3477c50174775ab2d5742c69c66
[ "Apache-2.0" ]
permissive
jdsalchow/mathlib
13ab43ef0d0515a17e550b16d09bd14b76125276
497e692b946d93906900bb33a51fd243e7649406
refs/heads/master
1,585,819,143,348
1,580,072,892,000
1,580,072,892,000
154,287,128
0
0
Apache-2.0
1,540,281,610,000
1,540,281,609,000
null
UTF-8
Lean
false
false
56,750
lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Kenny Lau -/ import data.finsupp order.complete_lattice algebra.ordered_group data.mv_polynomial import algebra.order_functions import ring_theory.ideal_operations /-! # Formal power series This file defines (multivariate) formal power series and develops the basic properties of these objects. A formal power series is to a polynomial like an infinite sum is to a finite sum. We provide the natural inclusion from polynomials to formal power series. ## Generalities The file starts with setting up the (semi)ring structure on multivariate power series. `trunc n φ` truncates a formal power series to the polynomial that has the same coefficients as φ, for all m ≤ n, and 0 otherwise. If the constant coefficient of a formal power series is invertible, then this formal power series is invertible. Formal power series over a local ring form a local ring. ## Formal power series in one variable We prove that if the ring of coefficients is an integral domain, then formal power series in one variable form an integral domain. The `order` of a formal power series `φ` is the multiplicity of the variable `X` in `φ`. If the coefficients form an integral domain, then `order` is a valuation (`order_mul`, `order_add_ge`). ## Implementation notes In this file we define multivariate formal power series with variables indexed by `σ` and coefficients in `α` as mv_power_series σ α := (σ →₀ ℕ) → α. Unfortunately there is not yet enough API to show that they are the completion of the ring of multivariate polynomials. However, we provide most of the infrastructure that is needed to do this. Once I-adic completion (topological or algebraic) is available it should not be hard to fill in the details. Formal power series in one variable are defined as power_series α := mv_power_series unit α. This allows us to port a lot of proofs and properties from the multivariate case to the single variable case. However, it means that formal power series are indexed by (unit →₀ ℕ), which is of course canonically isomorphic to ℕ. We then build some glue to treat formal power series as if they are indexed by ℕ. Occasionally this leads to proofs that are uglier than expected. -/ noncomputable theory open_locale classical /-- Multivariate formal power series, where `σ` is the index set of the variables and `α` is the coefficient ring.-/ def mv_power_series (σ : Type*) (α : Type*) := (σ →₀ ℕ) → α namespace mv_power_series open finsupp variables {σ : Type*} {α : Type*} instance [has_zero α] : has_zero (mv_power_series σ α) := pi.has_zero instance [add_monoid α] : add_monoid (mv_power_series σ α) := pi.add_monoid instance [add_group α] : add_group (mv_power_series σ α) := pi.add_group instance [add_comm_monoid α] : add_comm_monoid (mv_power_series σ α) := pi.add_comm_monoid instance [add_comm_group α] : add_comm_group (mv_power_series σ α) := pi.add_comm_group section add_monoid variables [add_monoid α] variables (α) /-- The `n`th monomial with coefficient `a` as multivariate formal power series.-/ def monomial (n : σ →₀ ℕ) : α →+ mv_power_series σ α := { to_fun := λ a m, if m = n then a else 0, map_zero' := funext $ λ m, by { split_ifs; refl }, map_add' := λ a b, funext $ λ m, show (if m = n then a + b else 0) = (if m = n then a else 0) + (if m = n then b else 0), from if h : m = n then by simp only [if_pos h] else by simp only [if_neg h, add_zero] } /-- The `n`th coefficient of a multivariate formal power series.-/ def coeff (n : σ →₀ ℕ) : (mv_power_series σ α) →+ α := { to_fun := λ φ, φ n, map_zero' := rfl, map_add' := λ _ _, rfl } variables {α} /-- Two multivariate formal power series are equal if all their coefficients are equal.-/ @[ext] lemma ext {φ ψ} (h : ∀ (n : σ →₀ ℕ), coeff α n φ = coeff α n ψ) : φ = ψ := funext h /-- Two multivariate formal power series are equal if and only if all their coefficients are equal.-/ lemma ext_iff {φ ψ : mv_power_series σ α} : φ = ψ ↔ (∀ (n : σ →₀ ℕ), coeff α n φ = coeff α n ψ) := ⟨λ h n, congr_arg (coeff α n) h, ext⟩ lemma coeff_monomial (m n : σ →₀ ℕ) (a : α) : coeff α m (monomial α n a) = if m = n then a else 0 := rfl @[simp] lemma coeff_monomial' (n : σ →₀ ℕ) (a : α) : coeff α n (monomial α n a) = a := if_pos rfl @[simp] lemma coeff_comp_monomial (n : σ →₀ ℕ) : (coeff α n).comp (monomial α n) = add_monoid_hom.id α := add_monoid_hom.ext $ coeff_monomial' n @[simp] lemma coeff_zero (n : σ →₀ ℕ) : coeff α n (0 : mv_power_series σ α) = 0 := rfl end add_monoid section semiring variables [semiring α] (n : σ →₀ ℕ) (φ ψ : mv_power_series σ α) instance : has_one (mv_power_series σ α) := ⟨monomial α (0 : σ →₀ ℕ) 1⟩ lemma coeff_one : coeff α n (1 : mv_power_series σ α) = if n = 0 then 1 else 0 := rfl @[simp] lemma coeff_zero_one : coeff α (0 : σ →₀ ℕ) 1 = 1 := coeff_monomial' 0 1 instance : has_mul (mv_power_series σ α) := ⟨λ φ ψ n, (finsupp.antidiagonal n).support.sum (λ p, φ p.1 * ψ p.2)⟩ lemma coeff_mul : coeff α n (φ * ψ) = (finsupp.antidiagonal n).support.sum (λ p, coeff α p.1 φ * coeff α p.2 ψ) := rfl protected lemma zero_mul : (0 : mv_power_series σ α) * φ = 0 := ext $ λ n, by simp [coeff_mul] protected lemma mul_zero : φ * 0 = 0 := ext $ λ n, by simp [coeff_mul] protected lemma one_mul : (1 : mv_power_series σ α) * φ = φ := ext $ λ n, begin rw [coeff_mul, finset.sum_eq_single ((0 : σ →₀ ℕ), n)]; simp [mem_antidiagonal_support, coeff_one], show ∀ (i j : σ →₀ ℕ), i + j = n → (i = 0 → j ≠ n) → (if (i = 0) then 1 else 0) * (coeff α j) φ = 0, intros i j hij h, rw [if_neg, zero_mul], contrapose! h, simpa [h] using hij, end protected lemma mul_one : φ * 1 = φ := ext $ λ n, begin rw [coeff_mul, finset.sum_eq_single (n, (0 : σ →₀ ℕ))], rotate, { rintros ⟨i, j⟩ hij h, rw [coeff_one, if_neg, mul_zero], rw mem_antidiagonal_support at hij, contrapose! h, simpa [h] using hij }, all_goals { simp [mem_antidiagonal_support, coeff_one] } end protected lemma mul_add (φ₁ φ₂ φ₃ : mv_power_series σ α) : φ₁ * (φ₂ + φ₃) = φ₁ * φ₂ + φ₁ * φ₃ := ext $ λ n, by simp only [coeff_mul, mul_add, finset.sum_add_distrib, add_monoid_hom.map_add] protected lemma add_mul (φ₁ φ₂ φ₃ : mv_power_series σ α) : (φ₁ + φ₂) * φ₃ = φ₁ * φ₃ + φ₂ * φ₃ := ext $ λ n, by simp only [coeff_mul, add_mul, finset.sum_add_distrib, add_monoid_hom.map_add] protected lemma mul_assoc (φ₁ φ₂ φ₃ : mv_power_series σ α) : (φ₁ * φ₂) * φ₃ = φ₁ * (φ₂ * φ₃) := ext $ λ n, begin simp only [coeff_mul], have := @finset.sum_sigma ((σ →₀ ℕ) × (σ →₀ ℕ)) α _ _ (antidiagonal n).support (λ p, (antidiagonal (p.1)).support) (λ x, coeff α x.2.1 φ₁ * coeff α x.2.2 φ₂ * coeff α x.1.2 φ₃), convert this.symm using 1; clear this, { apply finset.sum_congr rfl, intros p hp, exact finset.sum_mul }, have := @finset.sum_sigma ((σ →₀ ℕ) × (σ →₀ ℕ)) α _ _ (antidiagonal n).support (λ p, (antidiagonal (p.2)).support) (λ x, coeff α x.1.1 φ₁ * (coeff α x.2.1 φ₂ * coeff α x.2.2 φ₃)), convert this.symm using 1; clear this, { apply finset.sum_congr rfl, intros p hp, rw finset.mul_sum }, apply finset.sum_bij, swap 5, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, exact ⟨(k, l+j), (l, j)⟩ }, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, simp only [finset.mem_sigma, mem_antidiagonal_support] at H ⊢, finish }, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, rw mul_assoc }, { rintros ⟨⟨a,b⟩, ⟨c,d⟩⟩ ⟨⟨i,j⟩, ⟨k,l⟩⟩ H₁ H₂, simp only [finset.mem_sigma, mem_antidiagonal_support, and_imp, prod.mk.inj_iff, add_comm, heq_iff_eq] at H₁ H₂ ⊢, finish }, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, refine ⟨⟨(i+k, l), (i, k)⟩, _, _⟩; { simp only [finset.mem_sigma, mem_antidiagonal_support] at H ⊢, finish } } end instance : semiring (mv_power_series σ α) := { mul_one := mv_power_series.mul_one, one_mul := mv_power_series.one_mul, mul_assoc := mv_power_series.mul_assoc, mul_zero := mv_power_series.mul_zero, zero_mul := mv_power_series.zero_mul, left_distrib := mv_power_series.mul_add, right_distrib := mv_power_series.add_mul, .. mv_power_series.has_one, .. mv_power_series.has_mul, .. mv_power_series.add_comm_monoid } end semiring instance [comm_semiring α] : comm_semiring (mv_power_series σ α) := { mul_comm := λ φ ψ, ext $ λ n, finset.sum_bij (λ p hp, p.swap) (λ p hp, swap_mem_antidiagonal_support hp) (λ p hp, mul_comm _ _) (λ p q hp hq H, by simpa using congr_arg prod.swap H) (λ p hp, ⟨p.swap, swap_mem_antidiagonal_support hp, p.swap_swap.symm⟩), .. mv_power_series.semiring } instance [ring α] : ring (mv_power_series σ α) := { .. mv_power_series.semiring, .. mv_power_series.add_comm_group } instance [comm_ring α] : comm_ring (mv_power_series σ α) := { .. mv_power_series.comm_semiring, .. mv_power_series.add_comm_group } section semiring variables [semiring α] lemma monomial_mul_monomial (m n : σ →₀ ℕ) (a b : α) : monomial α m a * monomial α n b = monomial α (m + n) (a * b) := begin ext k, rw [coeff_mul, coeff_monomial], split_ifs with h, { rw [h, finset.sum_eq_single (m,n)], { rw [coeff_monomial', coeff_monomial'] }, { rintros ⟨i,j⟩ hij hne, rw [ne.def, prod.mk.inj_iff, not_and] at hne, by_cases H : i = m, { rw [coeff_monomial j n b, if_neg (hne H), mul_zero] }, { rw [coeff_monomial, if_neg H, zero_mul] } }, { intro H, rw finsupp.mem_antidiagonal_support at H, exfalso, exact H rfl } }, { rw [finset.sum_eq_zero], rintros ⟨i,j⟩ hij, rw finsupp.mem_antidiagonal_support at hij, by_cases H : i = m, { subst i, have : j ≠ n, { rintro rfl, exact h hij.symm }, { rw [coeff_monomial j n b, if_neg this, mul_zero] } }, { rw [coeff_monomial, if_neg H, zero_mul] } } end variables (σ) (α) /-- The constant multivariate formal power series.-/ def C : α →+* mv_power_series σ α := { map_one' := rfl, map_mul' := λ a b, (monomial_mul_monomial 0 0 a b).symm, .. monomial α (0 : σ →₀ ℕ) } variables {σ} {α} @[simp] lemma monomial_zero_eq_C : monomial α (0 : σ →₀ ℕ) = C σ α := rfl @[simp] lemma monomial_zero_eq_C_apply (a : α) : monomial α (0 : σ →₀ ℕ) a = C σ α a := rfl lemma coeff_C (n : σ →₀ ℕ) (a : α) : coeff α n (C σ α a) = if n = 0 then a else 0 := rfl @[simp] lemma coeff_zero_C (a : α) : coeff α (0 : σ →₀ℕ) (C σ α a) = a := coeff_monomial' 0 a /-- The variables of the multivariate formal power series ring.-/ def X (s : σ) : mv_power_series σ α := monomial α (single s 1) 1 lemma coeff_X (n : σ →₀ ℕ) (s : σ) : coeff α n (X s : mv_power_series σ α) = if n = (single s 1) then 1 else 0 := rfl lemma coeff_index_single_X (s t : σ) : coeff α (single t 1) (X s : mv_power_series σ α) = if t = s then 1 else 0 := by { simp only [coeff_X, single_right_inj one_ne_zero], split_ifs; refl } @[simp] lemma coeff_index_single_self_X (s : σ) : coeff α (single s 1) (X s : mv_power_series σ α) = 1 := if_pos rfl @[simp] lemma coeff_zero_X (s : σ) : coeff α (0 : σ →₀ ℕ) (X s : mv_power_series σ α) = 0 := by { rw [coeff_X, if_neg], intro h, exact one_ne_zero (single_eq_zero.mp h.symm) } lemma X_def (s : σ) : X s = monomial α (single s 1) 1 := rfl lemma X_pow_eq (s : σ) (n : ℕ) : (X s : mv_power_series σ α)^n = monomial α (single s n) 1 := begin induction n with n ih, { rw [pow_zero, finsupp.single_zero], refl }, { rw [pow_succ', ih, nat.succ_eq_add_one, finsupp.single_add, X, monomial_mul_monomial, one_mul] } end lemma coeff_X_pow (m : σ →₀ ℕ) (s : σ) (n : ℕ) : coeff α m ((X s : mv_power_series σ α)^n) = if m = single s n then 1 else 0 := by rw [X_pow_eq s n, coeff_monomial] variables (σ) (α) /-- The constant coefficient of a formal power series.-/ def constant_coeff : (mv_power_series σ α) →+* α := { to_fun := coeff α (0 : σ →₀ ℕ), map_one' := coeff_zero_one, map_mul' := λ φ ψ, by simp [coeff_mul, support_single_ne_zero], .. coeff α (0 : σ →₀ ℕ) } variables {σ} {α} @[simp] lemma coeff_zero_eq_constant_coeff : coeff α (0 : σ →₀ ℕ) = constant_coeff σ α := rfl @[simp] lemma coeff_zero_eq_constant_coeff_apply (φ : mv_power_series σ α) : coeff α (0 : σ →₀ ℕ) φ = constant_coeff σ α φ := rfl @[simp] lemma constant_coeff_C (a : α) : constant_coeff σ α (C σ α a) = a := rfl @[simp] lemma constant_coeff_comp_C : (constant_coeff σ α).comp (C σ α) = ring_hom.id α := rfl @[simp] lemma constant_coeff_zero : constant_coeff σ α 0 = 0 := rfl @[simp] lemma constant_coeff_one : constant_coeff σ α 1 = 1 := rfl @[simp] lemma constant_coeff_X (s : σ) : constant_coeff σ α (X s) = 0 := coeff_zero_X s /-- If a multivariate formal power series is invertible, then so is its constant coefficient.-/ lemma is_unit_constant_coeff (φ : mv_power_series σ α) (h : is_unit φ) : is_unit (constant_coeff σ α φ) := h.map' (constant_coeff σ α) instance : semimodule α (mv_power_series σ α) := { smul := λ a φ, C σ α a * φ, one_smul := λ φ, one_mul _, mul_smul := λ a b φ, by simp [ring_hom.map_mul, mul_assoc], smul_add := λ a φ ψ, mul_add _ _ _, smul_zero := λ a, mul_zero _, add_smul := λ a b φ, by simp only [ring_hom.map_add, add_mul], zero_smul := λ φ, by simp only [zero_mul, ring_hom.map_zero] } end semiring instance [ring α] : module α (mv_power_series σ α) := { ..mv_power_series.semimodule } instance [comm_ring α] : algebra α (mv_power_series σ α) := { to_fun := C σ α, commutes' := λ _ _, mul_comm _ _, smul_def' := λ c p, rfl, .. mv_power_series.module } section map variables {β : Type*} {γ : Type*} [semiring α] [semiring β] [semiring γ] variables (f : α →+* β) (g : β →+* γ) variable (σ) /-- The map between multivariate formal power series induced by a map on the coefficients.-/ def map : mv_power_series σ α →+* mv_power_series σ β := { to_fun := λ φ n, f $ coeff α n φ, map_zero' := ext $ λ n, f.map_zero, map_one' := ext $ λ n, show f ((coeff α n) 1) = (coeff β n) 1, by { rw [coeff_one, coeff_one], split_ifs; simp [f.map_one, f.map_zero] }, map_add' := λ φ ψ, ext $ λ n, show f ((coeff α n) (φ + ψ)) = f ((coeff α n) φ) + f ((coeff α n) ψ), by simp, map_mul' := λ φ ψ, ext $ λ n, show f _ = _, begin rw [coeff_mul, ← finset.sum_hom _ f, coeff_mul, finset.sum_congr rfl], rintros ⟨i,j⟩ hij, rw [f.map_mul], refl, end } variable {σ} @[simp] lemma map_id : map σ (ring_hom.id α) = ring_hom.id _ := rfl lemma map_comp : map σ (g.comp f) = (map σ g).comp (map σ f) := rfl @[simp] lemma coeff_map (n : σ →₀ ℕ) (φ : mv_power_series σ α) : coeff β n (map σ f φ) = f (coeff α n φ) := rfl @[simp] lemma constant_coeff_map (φ : mv_power_series σ α) : constant_coeff σ β (map σ f φ) = f (constant_coeff σ α φ) := rfl end map section trunc variables [comm_semiring α] (n : σ →₀ ℕ) -- Auxiliary definition for the truncation function. def trunc_fun (φ : mv_power_series σ α) : mv_polynomial σ α := { support := (n.antidiagonal.support.image prod.fst).filter (λ m, coeff α m φ ≠ 0), to_fun := λ m, if m ≤ n then coeff α m φ else 0, mem_support_to_fun := λ m, begin suffices : m ∈ finset.image prod.fst ((antidiagonal n).support) ↔ m ≤ n, { rw [finset.mem_filter, this], split, { intro h, rw [if_pos h.1], exact h.2 }, { intro h, split_ifs at h with H H, { exact ⟨H, h⟩ }, { exfalso, exact h rfl } } }, rw finset.mem_image, split, { rintros ⟨⟨i,j⟩, h, rfl⟩ s, rw finsupp.mem_antidiagonal_support at h, rw ← h, exact nat.le_add_right _ _ }, { intro h, refine ⟨(m, n-m), _, rfl⟩, rw finsupp.mem_antidiagonal_support, ext s, exact nat.add_sub_of_le (h s) } end } variable (α) /-- The `n`th truncation of a multivariate formal power series to a multivariate polynomial -/ def trunc : mv_power_series σ α →+ mv_polynomial σ α := { to_fun := trunc_fun n, map_zero' := mv_polynomial.ext _ _ $ λ m, by { change ite _ _ _ = _, split_ifs; refl }, map_add' := λ φ ψ, mv_polynomial.ext _ _ $ λ m, begin rw mv_polynomial.coeff_add, change ite _ _ _ = ite _ _ _ + ite _ _ _, split_ifs with H, {refl}, {rw [zero_add]} end } variable {α} lemma coeff_trunc (m : σ →₀ ℕ) (φ : mv_power_series σ α) : mv_polynomial.coeff m (trunc α n φ) = if m ≤ n then coeff α m φ else 0 := rfl @[simp] lemma trunc_one : trunc α n 1 = 1 := mv_polynomial.ext _ _ $ λ m, begin rw [coeff_trunc, coeff_one], split_ifs with H H' H', { subst m, erw mv_polynomial.coeff_C 0, simp }, { symmetry, erw mv_polynomial.coeff_monomial, convert if_neg (ne.elim (ne.symm H')), }, { symmetry, erw mv_polynomial.coeff_monomial, convert if_neg _, intro H', apply H, subst m, intro s, exact nat.zero_le _ } end @[simp] lemma trunc_C (a : α) : trunc α n (C σ α a) = mv_polynomial.C a := mv_polynomial.ext _ _ $ λ m, begin rw [coeff_trunc, coeff_C, mv_polynomial.coeff_C], split_ifs with H; refl <|> try {simp * at *}, exfalso, apply H, subst m, intro s, exact nat.zero_le _ end end trunc section comm_semiring variable [comm_semiring α] lemma X_pow_dvd_iff {s : σ} {n : ℕ} {φ : mv_power_series σ α} : (X s : mv_power_series σ α)^n ∣ φ ↔ ∀ m : σ →₀ ℕ, m s < n → coeff α m φ = 0 := begin split, { rintros ⟨φ, rfl⟩ m h, rw [coeff_mul, finset.sum_eq_zero], rintros ⟨i,j⟩ hij, rw [coeff_X_pow, if_neg, zero_mul], contrapose! h, subst i, rw finsupp.mem_antidiagonal_support at hij, rw [← hij, finsupp.add_apply, finsupp.single_eq_same], exact nat.le_add_right n _ }, { intro h, refine ⟨λ m, coeff α (m + (single s n)) φ, _⟩, ext m, by_cases H : m - single s n + single s n = m, { rw [coeff_mul, finset.sum_eq_single (single s n, m - single s n)], { rw [coeff_X_pow, if_pos rfl, one_mul], simpa using congr_arg (λ (m : σ →₀ ℕ), coeff α m φ) H.symm }, { rintros ⟨i,j⟩ hij hne, rw finsupp.mem_antidiagonal_support at hij, rw coeff_X_pow, split_ifs with hi, { exfalso, apply hne, rw [← hij, ← hi, prod.mk.inj_iff], refine ⟨rfl, _⟩, ext t, simp only [nat.add_sub_cancel_left, finsupp.add_apply, finsupp.nat_sub_apply] }, { exact zero_mul _ } }, { intro hni, exfalso, apply hni, rwa [finsupp.mem_antidiagonal_support, add_comm] } }, { rw [h, coeff_mul, finset.sum_eq_zero], { rintros ⟨i,j⟩ hij, rw finsupp.mem_antidiagonal_support at hij, rw coeff_X_pow, split_ifs with hi, { exfalso, apply H, rw [← hij, hi], ext t, simp only [nat.add_sub_cancel_left, add_comm, finsupp.add_apply, add_right_inj, finsupp.nat_sub_apply] }, { exact zero_mul _ } }, { classical, contrapose! H, ext t, by_cases hst : s = t, { subst t, simpa using nat.add_sub_cancel' H }, { simp [finsupp.single_apply, hst] } } } } end lemma X_dvd_iff {s : σ} {φ : mv_power_series σ α} : (X s : mv_power_series σ α) ∣ φ ↔ ∀ m : σ →₀ ℕ, m s = 0 → coeff α m φ = 0 := begin rw [← pow_one (X s : mv_power_series σ α), X_pow_dvd_iff], split; intros h m hm, { exact h m (hm.symm ▸ zero_lt_one) }, { exact h m (nat.eq_zero_of_le_zero $ nat.le_of_succ_le_succ hm) } end end comm_semiring section ring variables [ring α] /- The inverse of a multivariate formal power series is defined by well-founded recursion on the coeffients of the inverse. -/ /-- Auxiliary definition that unifies the totalised inverse formal power series `(_)⁻¹` and the inverse formal power series that depends on an inverse of the constant coefficient `inv_of_unit`.-/ protected noncomputable def inv.aux (a : α) (φ : mv_power_series σ α) : mv_power_series σ α | n := if n = 0 then a else - a * n.antidiagonal.support.sum (λ (x : (σ →₀ ℕ) × (σ →₀ ℕ)), if h : x.2 < n then coeff α x.1 φ * inv.aux x.2 else 0) using_well_founded { rel_tac := λ _ _, `[exact ⟨_, finsupp.lt_wf σ⟩], dec_tac := tactic.assumption } lemma coeff_inv_aux (n : σ →₀ ℕ) (a : α) (φ : mv_power_series σ α) : coeff α n (inv.aux a φ) = if n = 0 then a else - a * n.antidiagonal.support.sum (λ (x : (σ →₀ ℕ) × (σ →₀ ℕ)), if x.2 < n then coeff α x.1 φ * coeff α x.2 (inv.aux a φ) else 0) := show inv.aux a φ n = _, by { rw inv.aux, refl } /-- A multivariate formal power series is invertible if the constant coefficient is invertible.-/ def inv_of_unit (φ : mv_power_series σ α) (u : units α) : mv_power_series σ α := inv.aux (↑u⁻¹) φ lemma coeff_inv_of_unit (n : σ →₀ ℕ) (φ : mv_power_series σ α) (u : units α) : coeff α n (inv_of_unit φ u) = if n = 0 then ↑u⁻¹ else - ↑u⁻¹ * n.antidiagonal.support.sum (λ (x : (σ →₀ ℕ) × (σ →₀ ℕ)), if x.2 < n then coeff α x.1 φ * coeff α x.2 (inv_of_unit φ u) else 0) := coeff_inv_aux n (↑u⁻¹) φ @[simp] lemma constant_coeff_inv_of_unit (φ : mv_power_series σ α) (u : units α) : constant_coeff σ α (inv_of_unit φ u) = ↑u⁻¹ := by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv_of_unit, if_pos rfl] lemma mul_inv_of_unit (φ : mv_power_series σ α) (u : units α) (h : constant_coeff σ α φ = u) : φ * inv_of_unit φ u = 1 := ext $ λ n, if H : n = 0 then by { rw H, simp [coeff_mul, support_single_ne_zero, h], } else begin have : ((0 : σ →₀ ℕ), n) ∈ n.antidiagonal.support, { rw [finsupp.mem_antidiagonal_support, zero_add] }, rw [coeff_one, if_neg H, coeff_mul, ← finset.insert_erase this, finset.sum_insert (finset.not_mem_erase _ _), coeff_zero_eq_constant_coeff_apply, h, coeff_inv_of_unit, if_neg H, neg_mul_eq_neg_mul_symm, mul_neg_eq_neg_mul_symm, units.mul_inv_cancel_left, ← finset.insert_erase this, finset.sum_insert (finset.not_mem_erase _ _), finset.insert_erase this, if_neg (not_lt_of_ge $ le_refl _), zero_add, add_comm, ← sub_eq_add_neg, sub_eq_zero, finset.sum_congr rfl], rintros ⟨i,j⟩ hij, rw [finset.mem_erase, finsupp.mem_antidiagonal_support] at hij, cases hij with h₁ h₂, subst n, rw if_pos, suffices : (0 : _) + j < i + j, {simpa}, apply add_lt_add_right, split, { intro s, exact nat.zero_le _ }, { intro H, apply h₁, suffices : i = 0, {simp [this]}, ext1 s, exact nat.eq_zero_of_le_zero (H s) } end end ring section comm_ring variable [comm_ring α] /-- Multivariate formal power series over a local ring form a local ring.-/ lemma is_local_ring (h : is_local_ring α) : is_local_ring (mv_power_series σ α) := begin split, { have H : (0:α) ≠ 1 := ‹is_local_ring α›.1, contrapose! H, simpa using congr_arg (constant_coeff σ α) H }, { intro φ, rcases ‹is_local_ring α›.2 (constant_coeff σ α φ) with ⟨u,h⟩|⟨u,h⟩; [left, right]; { refine is_unit_of_mul_one _ _ (mul_inv_of_unit _ u _), simpa using h } } end -- TODO(jmc): once adic topology lands, show that this is complete end comm_ring section nonzero_comm_ring variables [nonzero_comm_ring α] instance : nonzero_comm_ring (mv_power_series σ α) := { zero_ne_one := assume h, zero_ne_one $ show (0:α) = 1, from congr_arg (constant_coeff σ α) h, .. mv_power_series.comm_ring } lemma X_inj {s t : σ} : (X s : mv_power_series σ α) = X t ↔ s = t := ⟨begin intro h, replace h := congr_arg (coeff α (single s 1)) h, rw [coeff_X, if_pos rfl, coeff_X] at h, split_ifs at h with H, { rw finsupp.single_eq_single_iff at H, cases H, { exact H.1 }, { exfalso, exact one_ne_zero H.1 } }, { exfalso, exact one_ne_zero h } end, congr_arg X⟩ end nonzero_comm_ring section local_ring variables {β : Type*} [local_ring α] [local_ring β] (f : α →+* β) [is_local_ring_hom f] instance : local_ring (mv_power_series σ α) := local_of_is_local_ring $ is_local_ring ⟨zero_ne_one, local_ring.is_local⟩ instance map.is_local_ring_hom : is_local_ring_hom (map σ f : mv_power_series σ α → mv_power_series σ β) := { map_one := (map σ f).map_one, map_mul := (map σ f).map_mul, map_add := (map σ f).map_add, map_nonunit := begin rintros φ ⟨ψ, h⟩, replace h := congr_arg (constant_coeff σ β) h, rw constant_coeff_map at h, have : is_unit (constant_coeff σ β ↑ψ) := @is_unit_constant_coeff σ β _ (↑ψ) (is_unit_unit ψ), rw ← h at this, rcases is_unit_of_map_unit f _ this with ⟨c, hc⟩, exact is_unit_of_mul_one φ (inv_of_unit φ c) (mul_inv_of_unit φ c hc) end } end local_ring section discrete_field variables [discrete_field α] protected def inv (φ : mv_power_series σ α) : mv_power_series σ α := inv.aux (constant_coeff σ α φ)⁻¹ φ instance : has_inv (mv_power_series σ α) := ⟨mv_power_series.inv⟩ lemma coeff_inv (n : σ →₀ ℕ) (φ : mv_power_series σ α) : coeff α n (φ⁻¹) = if n = 0 then (constant_coeff σ α φ)⁻¹ else - (constant_coeff σ α φ)⁻¹ * n.antidiagonal.support.sum (λ (x : (σ →₀ ℕ) × (σ →₀ ℕ)), if x.2 < n then coeff α x.1 φ * coeff α x.2 (φ⁻¹) else 0) := coeff_inv_aux n _ φ @[simp] lemma constant_coeff_inv (φ : mv_power_series σ α) : constant_coeff σ α (φ⁻¹) = (constant_coeff σ α φ)⁻¹ := by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv, if_pos rfl] lemma inv_eq_zero {φ : mv_power_series σ α} : φ⁻¹ = 0 ↔ constant_coeff σ α φ = 0 := ⟨λ h, by simpa using congr_arg (constant_coeff σ α) h, λ h, ext $ λ n, by { rw coeff_inv, split_ifs; simp only [h, mv_power_series.coeff_zero, zero_mul, inv_zero, neg_zero] }⟩ @[simp] lemma inv_of_unit_eq (φ : mv_power_series σ α) (h : constant_coeff σ α φ ≠ 0) : inv_of_unit φ (units.mk0 _ h) = φ⁻¹ := rfl @[simp] lemma inv_of_unit_eq' (φ : mv_power_series σ α) (u : units α) (h : constant_coeff σ α φ = u) : inv_of_unit φ u = φ⁻¹ := begin rw ← inv_of_unit_eq φ (h.symm ▸ u.ne_zero), congr' 1, rw [units.ext_iff], exact h.symm, end @[simp] protected lemma mul_inv (φ : mv_power_series σ α) (h : constant_coeff σ α φ ≠ 0) : φ * φ⁻¹ = 1 := by rw [← inv_of_unit_eq φ h, mul_inv_of_unit φ (units.mk0 _ h) rfl] @[simp] protected lemma inv_mul (φ : mv_power_series σ α) (h : constant_coeff σ α φ ≠ 0) : φ⁻¹ * φ = 1 := by rw [mul_comm, φ.mul_inv h] end discrete_field end mv_power_series namespace mv_polynomial open finsupp variables {σ : Type*} {α : Type*} [comm_semiring α] /-- The natural inclusion from multivariate polynomials into multivariate formal power series.-/ instance coe_to_mv_power_series : has_coe (mv_polynomial σ α) (mv_power_series σ α) := ⟨λ φ n, coeff n φ⟩ @[simp, elim_cast] lemma coeff_coe (φ : mv_polynomial σ α) (n : σ →₀ ℕ) : mv_power_series.coeff α n ↑φ = coeff n φ := rfl @[simp, elim_cast] lemma coe_monomial (n : σ →₀ ℕ) (a : α) : (monomial n a : mv_power_series σ α) = mv_power_series.monomial α n a := mv_power_series.ext $ λ m, begin rw [coeff_coe, coeff_monomial, mv_power_series.coeff_monomial], split_ifs with h₁ h₂; refl <|> subst m; contradiction end @[simp, elim_cast] lemma coe_zero : ((0 : mv_polynomial σ α) : mv_power_series σ α) = 0 := rfl @[simp, elim_cast] lemma coe_one : ((1 : mv_polynomial σ α) : mv_power_series σ α) = 1 := coe_monomial _ _ @[simp, elim_cast] lemma coe_add (φ ψ : mv_polynomial σ α) : ((φ + ψ : mv_polynomial σ α) : mv_power_series σ α) = φ + ψ := rfl @[simp, elim_cast] lemma coe_mul (φ ψ : mv_polynomial σ α) : ((φ * ψ : mv_polynomial σ α) : mv_power_series σ α) = φ * ψ := mv_power_series.ext $ λ n, by simp only [coeff_coe, mv_power_series.coeff_mul, coeff_mul] @[simp, elim_cast] lemma coe_C (a : α) : ((C a : mv_polynomial σ α) : mv_power_series σ α) = mv_power_series.C σ α a := coe_monomial _ _ @[simp, elim_cast] lemma coe_X (s : σ) : ((X s : mv_polynomial σ α) : mv_power_series σ α) = mv_power_series.X s := coe_monomial _ _ namespace coe_to_mv_power_series instance : is_semiring_hom (coe : mv_polynomial σ α → mv_power_series σ α) := { map_zero := coe_zero, map_one := coe_one, map_add := coe_add, map_mul := coe_mul } end coe_to_mv_power_series end mv_polynomial /-- Formal power series over the coefficient ring `α`.-/ def power_series (α : Type*) := mv_power_series unit α namespace power_series open finsupp (single) variable {α : Type*} instance [add_monoid α] : add_monoid (power_series α) := by delta power_series; apply_instance instance [add_group α] : add_group (power_series α) := by delta power_series; apply_instance instance [add_comm_monoid α] : add_comm_monoid (power_series α) := by delta power_series; apply_instance instance [add_comm_group α] : add_comm_group (power_series α) := by delta power_series; apply_instance instance [semiring α] : semiring (power_series α) := by delta power_series; apply_instance instance [comm_semiring α] : comm_semiring (power_series α) := by delta power_series; apply_instance instance [ring α] : ring (power_series α) := by delta power_series; apply_instance instance [comm_ring α] : comm_ring (power_series α) := by delta power_series; apply_instance instance [nonzero_comm_ring α] : nonzero_comm_ring (power_series α) := by delta power_series; apply_instance instance [semiring α] : semimodule α (power_series α) := by delta power_series; apply_instance instance [ring α] : module α (power_series α) := by delta power_series; apply_instance instance [comm_ring α] : algebra α (power_series α) := by delta power_series; apply_instance section add_monoid variables (α) [add_monoid α] /-- The `n`th coefficient of a formal power series.-/ def coeff (n : ℕ) : power_series α →+ α := mv_power_series.coeff α (single () n) /-- The `n`th monomial with coefficient `a` as formal power series.-/ def monomial (n : ℕ) : α →+ power_series α := mv_power_series.monomial α (single () n) variables {α} lemma coeff_def {s : unit →₀ ℕ} {n : ℕ} (h : s () = n) : coeff α n = mv_power_series.coeff α s := by erw [coeff, ← h, ← finsupp.unique_single s] /-- Two formal power series are equal if all their coefficients are equal.-/ @[ext] lemma ext {φ ψ : power_series α} (h : ∀ n, coeff α n φ = coeff α n ψ) : φ = ψ := mv_power_series.ext $ λ n, by { rw ← coeff_def, { apply h }, refl } /-- Two formal power series are equal if all their coefficients are equal.-/ lemma ext_iff {φ ψ : power_series α} : φ = ψ ↔ (∀ n, coeff α n φ = coeff α n ψ) := ⟨λ h n, congr_arg (coeff α n) h, ext⟩ /-- Constructor for formal power series.-/ def mk (f : ℕ → α) : power_series α := λ s, f (s ()) @[simp] lemma coeff_mk (n : ℕ) (f : ℕ → α) : coeff α n (mk f) = f n := congr_arg f finsupp.single_eq_same lemma coeff_monomial (m n : ℕ) (a : α) : coeff α m (monomial α n a) = if m = n then a else 0 := calc coeff α m (monomial α n a) = _ : mv_power_series.coeff_monomial _ _ _ ... = if m = n then a else 0 : by { simp only [finsupp.unique_single_eq_iff], split_ifs; refl } lemma monomial_eq_mk (n : ℕ) (a : α) : monomial α n a = mk (λ m, if m = n then a else 0) := ext $ λ m, by { rw [coeff_monomial, coeff_mk] } @[simp] lemma coeff_monomial' (n : ℕ) (a : α) : coeff α n (monomial α n a) = a := by convert if_pos rfl @[simp] lemma coeff_comp_monomial (n : ℕ) : (coeff α n).comp (monomial α n) = add_monoid_hom.id α := add_monoid_hom.ext $ coeff_monomial' n end add_monoid section semiring variable [semiring α] variable (α) /--The constant coefficient of a formal power series. -/ def constant_coeff : power_series α →+* α := mv_power_series.constant_coeff unit α /-- The constant formal power series.-/ def C : α →+* power_series α := mv_power_series.C unit α variable {α} /-- The variable of the formal power series ring.-/ def X : power_series α := mv_power_series.X () @[simp] lemma coeff_zero_eq_constant_coeff : coeff α 0 = constant_coeff α := begin rw [constant_coeff, ← mv_power_series.coeff_zero_eq_constant_coeff, coeff_def], refl end @[simp] lemma coeff_zero_eq_constant_coeff_apply (φ : power_series α) : coeff α 0 φ = constant_coeff α φ := by rw [coeff_zero_eq_constant_coeff]; refl @[simp] lemma monomial_zero_eq_C : monomial α 0 = C α := by rw [monomial, finsupp.single_zero, mv_power_series.monomial_zero_eq_C, C] @[simp] lemma monomial_zero_eq_C_apply (a : α) : monomial α 0 a = C α a := by rw [monomial_zero_eq_C]; refl lemma coeff_C (n : ℕ) (a : α) : coeff α n (C α a : power_series α) = if n = 0 then a else 0 := by rw [← monomial_zero_eq_C_apply, coeff_monomial] @[simp] lemma coeff_zero_C (a : α) : coeff α 0 (C α a) = a := by rw [← monomial_zero_eq_C_apply, coeff_monomial' 0 a] lemma X_eq : (X : power_series α) = monomial α 1 1 := rfl lemma coeff_X (n : ℕ) : coeff α n (X : power_series α) = if n = 1 then 1 else 0 := by rw [X_eq, coeff_monomial] @[simp] lemma coeff_zero_X : coeff α 0 (X : power_series α) = 0 := by rw [coeff, finsupp.single_zero, X, mv_power_series.coeff_zero_X] @[simp] lemma coeff_one_X : coeff α 1 (X : power_series α) = 1 := by rw [coeff_X, if_pos rfl] lemma X_pow_eq (n : ℕ) : (X : power_series α)^n = monomial α n 1 := mv_power_series.X_pow_eq _ n lemma coeff_X_pow (m n : ℕ) : coeff α m ((X : power_series α)^n) = if m = n then 1 else 0 := by rw [X_pow_eq, coeff_monomial] @[simp] lemma coeff_X_pow_self (n : ℕ) : coeff α n ((X : power_series α)^n) = 1 := by rw [coeff_X_pow, if_pos rfl] @[simp] lemma coeff_one (n : ℕ) : coeff α n (1 : power_series α) = if n = 0 then 1 else 0 := calc coeff α n (1 : power_series α) = _ : mv_power_series.coeff_one _ ... = if n = 0 then 1 else 0 : by { simp only [finsupp.single_eq_zero], split_ifs; refl } @[simp] lemma coeff_zero_one : coeff α 0 (1 : power_series α) = 1 := coeff_zero_C 1 lemma coeff_mul (n : ℕ) (φ ψ : power_series α) : coeff α n (φ * ψ) = (finset.nat.antidiagonal n).sum (λ p, coeff α p.1 φ * coeff α p.2 ψ) := begin symmetry, apply finset.sum_bij (λ (p : ℕ × ℕ) h, (single () p.1, single () p.2)), { rintros ⟨i,j⟩ hij, rw finset.nat.mem_antidiagonal at hij, rw [finsupp.mem_antidiagonal_support, ← finsupp.single_add, hij], }, { rintros ⟨i,j⟩ hij, refl }, { rintros ⟨i,j⟩ ⟨k,l⟩ hij hkl, simpa only [prod.mk.inj_iff, finsupp.unique_single_eq_iff] using id }, { rintros ⟨f,g⟩ hfg, refine ⟨(f (), g ()), _, _⟩, { rw finsupp.mem_antidiagonal_support at hfg, rw [finset.nat.mem_antidiagonal, ← finsupp.add_apply, hfg, finsupp.single_eq_same] }, { rw prod.mk.inj_iff, dsimp, exact ⟨finsupp.unique_single f, finsupp.unique_single g⟩ } } end @[simp] lemma constant_coeff_C (a : α) : constant_coeff α (C α a) = a := rfl @[simp] lemma constant_coeff_comp_C : (constant_coeff α).comp (C α) = ring_hom.id α := rfl @[simp] lemma constant_coeff_zero : constant_coeff α 0 = 0 := rfl @[simp] lemma constant_coeff_one : constant_coeff α 1 = 1 := rfl @[simp] lemma constant_coeff_X : constant_coeff α X = 0 := mv_power_series.coeff_zero_X _ /-- If a formal power series is invertible, then so is its constant coefficient.-/ lemma is_unit_constant_coeff (φ : power_series α) (h : is_unit φ) : is_unit (constant_coeff α φ) := mv_power_series.is_unit_constant_coeff φ h section map variables {β : Type*} {γ : Type*} [semiring β] [semiring γ] variables (f : α →+* β) (g : β →+* γ) /-- The map between formal power series induced by a map on the coefficients.-/ def map : power_series α →+* power_series β := mv_power_series.map _ f @[simp] lemma map_id : (map (ring_hom.id α) : power_series α → power_series α) = id := rfl lemma map_comp : map (g.comp f) = (map g).comp (map f) := rfl @[simp] lemma coeff_map (n : ℕ) (φ : power_series α) : coeff β n (map f φ) = f (coeff α n φ) := rfl end map end semiring section comm_semiring variables [comm_semiring α] lemma X_pow_dvd_iff {n : ℕ} {φ : power_series α} : (X : power_series α)^n ∣ φ ↔ ∀ m, m < n → coeff α m φ = 0 := begin convert @mv_power_series.X_pow_dvd_iff unit α _ () n φ, apply propext, classical, split; intros h m hm, { rw finsupp.unique_single m, convert h _ hm }, { apply h, simpa only [finsupp.single_eq_same] using hm } end lemma X_dvd_iff {φ : power_series α} : (X : power_series α) ∣ φ ↔ constant_coeff α φ = 0 := begin rw [← pow_one (X : power_series α), X_pow_dvd_iff, ← coeff_zero_eq_constant_coeff_apply], split; intro h, { exact h 0 zero_lt_one }, { intros m hm, rwa nat.eq_zero_of_le_zero (nat.le_of_succ_le_succ hm) } end section trunc /-- The `n`th truncation of a formal power series to a polynomial -/ def trunc (n : ℕ) (φ : power_series α) : polynomial α := { support := ((finset.nat.antidiagonal n).image prod.fst).filter (λ m, coeff α m φ ≠ 0), to_fun := λ m, if m ≤ n then coeff α m φ else 0, mem_support_to_fun := λ m, begin suffices : m ∈ ((finset.nat.antidiagonal n).image prod.fst) ↔ m ≤ n, { rw [finset.mem_filter, this], split, { intro h, rw [if_pos h.1], exact h.2 }, { intro h, split_ifs at h with H H, { exact ⟨H, h⟩ }, { exfalso, exact h rfl } } }, rw finset.mem_image, split, { rintros ⟨⟨i,j⟩, h, rfl⟩, rw finset.nat.mem_antidiagonal at h, rw ← h, exact nat.le_add_right _ _ }, { intro h, refine ⟨(m, n-m), _, rfl⟩, rw finset.nat.mem_antidiagonal, exact nat.add_sub_of_le h } end } lemma coeff_trunc (m) (n) (φ : power_series α) : polynomial.coeff (trunc n φ) m = if m ≤ n then coeff α m φ else 0 := rfl @[simp] lemma trunc_zero (n) : trunc n (0 : power_series α) = 0 := polynomial.ext $ λ m, begin rw [coeff_trunc, add_monoid_hom.map_zero, polynomial.coeff_zero], split_ifs; refl end @[simp] lemma trunc_one (n) : trunc n (1 : power_series α) = 1 := polynomial.ext $ λ m, begin rw [coeff_trunc, coeff_one], split_ifs with H H' H'; rw [polynomial.coeff_one], { subst m, rw [if_pos rfl] }, { symmetry, exact if_neg (ne.elim (ne.symm H')) }, { symmetry, refine if_neg _, intro H', apply H, subst m, exact nat.zero_le _ } end @[simp] lemma trunc_C (n) (a : α) : trunc n (C α a) = polynomial.C a := polynomial.ext $ λ m, begin rw [coeff_trunc, coeff_C, polynomial.coeff_C], split_ifs with H; refl <|> try {simp * at *} end @[simp] lemma trunc_add (n) (φ ψ : power_series α) : trunc n (φ + ψ) = trunc n φ + trunc n ψ := polynomial.ext $ λ m, begin simp only [coeff_trunc, add_monoid_hom.map_add, polynomial.coeff_add], split_ifs with H, {refl}, {rw [zero_add]} end end trunc end comm_semiring section ring variables [ring α] protected def inv.aux : α → power_series α → power_series α := mv_power_series.inv.aux lemma coeff_inv_aux (n : ℕ) (a : α) (φ : power_series α) : coeff α n (inv.aux a φ) = if n = 0 then a else - a * (finset.nat.antidiagonal n).sum (λ (x : ℕ × ℕ), if x.2 < n then coeff α x.1 φ * coeff α x.2 (inv.aux a φ) else 0) := begin rw [coeff, inv.aux, mv_power_series.coeff_inv_aux], simp only [finsupp.single_eq_zero], split_ifs, {refl}, congr' 1, symmetry, apply finset.sum_bij (λ (p : ℕ × ℕ) h, (single () p.1, single () p.2)), { rintros ⟨i,j⟩ hij, rw finset.nat.mem_antidiagonal at hij, rw [finsupp.mem_antidiagonal_support, ← finsupp.single_add, hij], }, { rintros ⟨i,j⟩ hij, by_cases H : j < n, { rw [if_pos H, if_pos], {refl}, split, { rintro ⟨⟩, simpa [finsupp.single_eq_same] using le_of_lt H }, { intro hh, rw lt_iff_not_ge at H, apply H, simpa [finsupp.single_eq_same] using hh () } }, { rw [if_neg H, if_neg], rintro ⟨h₁, h₂⟩, apply h₂, rintro ⟨⟩, simpa [finsupp.single_eq_same] using not_lt.1 H } }, { rintros ⟨i,j⟩ ⟨k,l⟩ hij hkl, simpa only [prod.mk.inj_iff, finsupp.unique_single_eq_iff] using id }, { rintros ⟨f,g⟩ hfg, refine ⟨(f (), g ()), _, _⟩, { rw finsupp.mem_antidiagonal_support at hfg, rw [finset.nat.mem_antidiagonal, ← finsupp.add_apply, hfg, finsupp.single_eq_same] }, { rw prod.mk.inj_iff, dsimp, exact ⟨finsupp.unique_single f, finsupp.unique_single g⟩ } } end /-- A formal power series is invertible if the constant coefficient is invertible.-/ def inv_of_unit (φ : power_series α) (u : units α) : power_series α := mv_power_series.inv_of_unit φ u lemma coeff_inv_of_unit (n : ℕ) (φ : power_series α) (u : units α) : coeff α n (inv_of_unit φ u) = if n = 0 then ↑u⁻¹ else - ↑u⁻¹ * (finset.nat.antidiagonal n).sum (λ (x : ℕ × ℕ), if x.2 < n then coeff α x.1 φ * coeff α x.2 (inv_of_unit φ u) else 0) := coeff_inv_aux n ↑u⁻¹ φ @[simp] lemma constant_coeff_inv_of_unit (φ : power_series α) (u : units α) : constant_coeff α (inv_of_unit φ u) = ↑u⁻¹ := by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv_of_unit, if_pos rfl] lemma mul_inv_of_unit (φ : power_series α) (u : units α) (h : constant_coeff α φ = u) : φ * inv_of_unit φ u = 1 := mv_power_series.mul_inv_of_unit φ u $ h end ring section integral_domain variable [integral_domain α] lemma eq_zero_or_eq_zero_of_mul_eq_zero (φ ψ : power_series α) (h : φ * ψ = 0) : φ = 0 ∨ ψ = 0 := begin rw classical.or_iff_not_imp_left, intro H, have ex : ∃ m, coeff α m φ ≠ 0, { contrapose! H, exact ext H }, let P : ℕ → Prop := λ k, coeff α k φ ≠ 0, let m := nat.find ex, have hm₁ : coeff α m φ ≠ 0 := nat.find_spec ex, have hm₂ : ∀ k < m, ¬coeff α k φ ≠ 0 := λ k, nat.find_min ex, ext n, rw (coeff α n).map_zero, apply nat.strong_induction_on n, clear n, intros n ih, replace h := congr_arg (coeff α (m + n)) h, rw [add_monoid_hom.map_zero, coeff_mul, finset.sum_eq_single (m,n)] at h, { replace h := eq_zero_or_eq_zero_of_mul_eq_zero h, rw or_iff_not_imp_left at h, exact h hm₁ }, { rintro ⟨i,j⟩ hij hne, by_cases hj : j < n, { rw [ih j hj, mul_zero] }, by_cases hi : i < m, { specialize hm₂ _ hi, push_neg at hm₂, rw [hm₂, zero_mul] }, rw finset.nat.mem_antidiagonal at hij, push_neg at hi hj, suffices : m < i, { have : m + n < i + j := add_lt_add_of_lt_of_le this hj, exfalso, exact ne_of_lt this hij.symm }, contrapose! hne, have : i = m := le_antisymm hne hi, subst i, clear hi hne, simpa [ne.def, prod.mk.inj_iff] using (add_left_inj m).mp hij }, { contrapose!, intro h, rw finset.nat.mem_antidiagonal } end instance : integral_domain (power_series α) := { eq_zero_or_eq_zero_of_mul_eq_zero := eq_zero_or_eq_zero_of_mul_eq_zero, .. power_series.nonzero_comm_ring } /-- The ideal spanned by the variable in the power series ring over an integral domain is a prime ideal.-/ lemma span_X_is_prime : (ideal.span ({X} : set (power_series α))).is_prime := begin suffices : ideal.span ({X} : set (power_series α)) = is_ring_hom.ker (constant_coeff α), { rw this, exact is_ring_hom.ker_is_prime _ }, apply ideal.ext, intro φ, rw [is_ring_hom.mem_ker, ideal.mem_span_singleton, X_dvd_iff] end /-- The variable of the power series ring over an integral domain is prime.-/ lemma X_prime : prime (X : power_series α) := begin rw ← ideal.span_singleton_prime, { exact span_X_is_prime }, { intro h, simpa using congr_arg (coeff α 1) h } end end integral_domain section local_ring variables [comm_ring α] lemma is_local_ring (h : is_local_ring α) : is_local_ring (power_series α) := mv_power_series.is_local_ring h end local_ring section local_ring variables {β : Type*} [local_ring α] [local_ring β] (f : α →+* β) [is_local_ring_hom f] instance : local_ring (power_series α) := mv_power_series.local_ring instance map.is_local_ring_hom : is_local_ring_hom (map f) := mv_power_series.map.is_local_ring_hom f end local_ring section discrete_field variables [discrete_field α] protected def inv : power_series α → power_series α := mv_power_series.inv instance : has_inv (power_series α) := ⟨power_series.inv⟩ lemma inv_eq_inv_aux (φ : power_series α) : φ⁻¹ = inv.aux (constant_coeff α φ)⁻¹ φ := rfl lemma coeff_inv (n) (φ : power_series α) : coeff α n (φ⁻¹) = if n = 0 then (constant_coeff α φ)⁻¹ else - (constant_coeff α φ)⁻¹ * (finset.nat.antidiagonal n).sum (λ (x : ℕ × ℕ), if x.2 < n then coeff α x.1 φ * coeff α x.2 (φ⁻¹) else 0) := by rw [inv_eq_inv_aux, coeff_inv_aux n (constant_coeff α φ)⁻¹ φ] @[simp] lemma constant_coeff_inv (φ : power_series α) : constant_coeff α (φ⁻¹) = (constant_coeff α φ)⁻¹ := mv_power_series.constant_coeff_inv φ lemma inv_eq_zero {φ : power_series α} : φ⁻¹ = 0 ↔ constant_coeff α φ = 0 := mv_power_series.inv_eq_zero @[simp] lemma inv_of_unit_eq (φ : power_series α) (h : constant_coeff α φ ≠ 0) : inv_of_unit φ (units.mk0 _ h) = φ⁻¹ := mv_power_series.inv_of_unit_eq _ _ @[simp] lemma inv_of_unit_eq' (φ : power_series α) (u : units α) (h : constant_coeff α φ = u) : inv_of_unit φ u = φ⁻¹ := mv_power_series.inv_of_unit_eq' φ _ h @[simp] protected lemma mul_inv (φ : power_series α) (h : constant_coeff α φ ≠ 0) : φ * φ⁻¹ = 1 := mv_power_series.mul_inv φ h @[simp] protected lemma inv_mul (φ : power_series α) (h : constant_coeff α φ ≠ 0) : φ⁻¹ * φ = 1 := mv_power_series.inv_mul φ h end discrete_field end power_series namespace power_series variable {α : Type*} local attribute [instance, priority 1] classical.prop_decidable noncomputable theory section order_basic open multiplicity variables [comm_semiring α] /-- The order of a formal power series `φ` is the smallest `n : enat` such that `X^n` divides `φ`. The order is `⊤` if and only if `φ = 0`. -/ @[reducible] def order (φ : power_series α) : enat := multiplicity X φ lemma order_finite_of_coeff_ne_zero (φ : power_series α) (h : ∃ n, coeff α n φ ≠ 0) : (order φ).dom := begin cases h with n h, refine ⟨n, _⟩, rw X_pow_dvd_iff, push_neg, exact ⟨n, lt_add_one n, h⟩ end /-- If the order of a formal power series is finite, then the coefficient indexed by the order is nonzero.-/ lemma coeff_order (φ : power_series α) (h : (order φ).dom) : coeff α (φ.order.get h) φ ≠ 0 := begin have H := nat.find_spec h, contrapose! H, rw X_pow_dvd_iff, intros m hm, by_cases Hm : m < nat.find h, { have := nat.find_min h Hm, push_neg at this, rw X_pow_dvd_iff at this, exact this m (lt_add_one m) }, have : m = nat.find h, {linarith}, {rwa this} end /-- If the `n`th coefficient of a formal power series is nonzero, then the order of the power series is less than or equal to `n`.-/ lemma order_le (φ : power_series α) (n : ℕ) (h : coeff α n φ ≠ 0) : order φ ≤ n := begin have h : ¬ X^(n+1) ∣ φ, { rw X_pow_dvd_iff, push_neg, exact ⟨n, lt_add_one n, h⟩ }, have : (order φ).dom := ⟨n, h⟩, rw [← enat.coe_get this, enat.coe_le_coe], refine nat.find_min' this h end /-- The `n`th coefficient of a formal power series is `0` if `n` is strictly smaller than the order of the power series.-/ lemma coeff_of_lt_order (φ : power_series α) (n : ℕ) (h: ↑n < order φ) : coeff α n φ = 0 := by { contrapose! h, exact order_le _ _ h } /-- The `0` power series is the unique power series with infinite order.-/ lemma order_eq_top {φ : power_series α} : φ.order = ⊤ ↔ φ = 0 := begin rw eq_top_iff, split, { intro h, ext n, specialize h (n+1), rw X_pow_dvd_iff at h, exact h n (lt_add_one _) }, { rintros rfl n, exact dvd_zero _ } end /-- The order of the `0` power series is infinite.-/ @[simp] lemma order_zero : order (0 : power_series α) = ⊤ := multiplicity.zero _ /-- The order of a formal power series is at least `n` if the `i`th coefficient is `0` for all `i < n`.-/ lemma order_ge_nat (φ : power_series α) (n : ℕ) (h : ∀ i < n, coeff α i φ = 0) : order φ ≥ n := begin by_contra H, rw not_le at H, have : (order φ).dom := enat.dom_of_le_some (le_of_lt H), rw [← enat.coe_get this, enat.coe_lt_coe] at H, exact coeff_order _ this (h _ H) end /-- The order of a formal power series is at least `n` if the `i`th coefficient is `0` for all `i < n`.-/ lemma order_ge (φ : power_series α) (n : enat) (h : ∀ i : ℕ, ↑i < n → coeff α i φ = 0) : order φ ≥ n := begin induction n using enat.cases_on, { show _ ≤ _, rw [lattice.top_le_iff, order_eq_top], ext i, exact h _ (enat.coe_lt_top i) }, { apply order_ge_nat, simpa only [enat.coe_lt_coe] using h } end /-- The order of a formal power series is exactly `n` if the `n`th coefficient is nonzero, and the `i`th coefficient is `0` for all `i < n`.-/ lemma order_eq_nat {φ : power_series α} {n : ℕ} : order φ = n ↔ (coeff α n φ ≠ 0) ∧ (∀ i, i < n → coeff α i φ = 0) := begin simp only [eq_some_iff, X_pow_dvd_iff], push_neg, split, { rintros ⟨h₁, m, hm₁, hm₂⟩, refine ⟨_, h₁⟩, suffices : n = m, { rwa this }, suffices : m ≥ n, { linarith }, contrapose! hm₂, exact h₁ _ hm₂ }, { rintros ⟨h₁, h₂⟩, exact ⟨h₂, n, lt_add_one n, h₁⟩ } end /-- The order of a formal power series is exactly `n` if the `n`th coefficient is nonzero, and the `i`th coefficient is `0` for all `i < n`.-/ lemma order_eq {φ : power_series α} {n : enat} : order φ = n ↔ (∀ i:ℕ, ↑i = n → coeff α i φ ≠ 0) ∧ (∀ i:ℕ, ↑i < n → coeff α i φ = 0) := begin induction n using enat.cases_on, { rw order_eq_top, split, { rintro rfl, split; intros, { exfalso, exact enat.coe_ne_top ‹_› ‹_› }, { exact (coeff _ _).map_zero } }, { rintro ⟨h₁, h₂⟩, ext i, exact h₂ i (enat.coe_lt_top i) } }, { simpa [enat.coe_inj] using order_eq_nat } end /-- The order of the sum of two formal power series is at least the minimum of their orders.-/ lemma order_add_ge (φ ψ : power_series α) : order (φ + ψ) ≥ min (order φ) (order ψ) := multiplicity.min_le_multiplicity_add private lemma order_add_of_order_eq.aux (φ ψ : power_series α) (h : order φ ≠ order ψ) (H : order φ < order ψ) : order (φ + ψ) ≤ order φ ⊓ order ψ := begin suffices : order (φ + ψ) = order φ, { rw [lattice.le_inf_iff, this], exact ⟨le_refl _, le_of_lt H⟩ }, { rw order_eq, split, { intros i hi, rw [(coeff _ _).map_add, coeff_of_lt_order ψ i (hi.symm ▸ H), add_zero], exact (order_eq_nat.1 hi.symm).1 }, { intros i hi, rw [(coeff _ _).map_add, coeff_of_lt_order φ i hi, coeff_of_lt_order ψ i (lt_trans hi H), zero_add] } } end /-- The order of the sum of two formal power series is the minimum of their orders if their orders differ.-/ lemma order_add_of_order_eq (φ ψ : power_series α) (h : order φ ≠ order ψ) : order (φ + ψ) = order φ ⊓ order ψ := begin refine le_antisymm _ (order_add_ge _ _), by_cases H₁ : order φ < order ψ, { apply order_add_of_order_eq.aux _ _ h H₁ }, by_cases H₂ : order ψ < order φ, { simpa only [add_comm, lattice.inf_comm] using order_add_of_order_eq.aux _ _ h.symm H₂ }, exfalso, exact h (le_antisymm (not_lt.1 H₂) (not_lt.1 H₁)) end /-- The order of the product of two formal power series is at least the sum of their orders.-/ lemma order_mul_ge (φ ψ : power_series α) : order (φ * ψ) ≥ order φ + order ψ := begin apply order_ge, intros n hn, rw [coeff_mul, finset.sum_eq_zero], rintros ⟨i,j⟩ hij, by_cases hi : ↑i < order φ, { rw [coeff_of_lt_order φ i hi, zero_mul] }, by_cases hj : ↑j < order ψ, { rw [coeff_of_lt_order ψ j hj, mul_zero] }, rw not_lt at hi hj, rw finset.nat.mem_antidiagonal at hij, exfalso, apply ne_of_lt (lt_of_lt_of_le hn $ add_le_add' hi hj), rw [← enat.coe_add, hij] end /-- The order of the monomial `a*X^n` is infinite if `a = 0` and `n` otherwise.-/ lemma order_monomial (n : ℕ) (a : α) : order (monomial α n a) = if a = 0 then ⊤ else n := begin split_ifs with h, { rw [h, order_eq_top, add_monoid_hom.map_zero] }, { rw [order_eq], split; intros i hi, { rw [enat.coe_inj] at hi, rwa [hi, coeff_monomial'] }, { rw [enat.coe_lt_coe] at hi, rw [coeff_monomial, if_neg], exact ne_of_lt hi } } end /-- The order of the monomial `a*X^n` is `n` if `a ≠ 0`.-/ lemma order_monomial_of_ne_zero (n : ℕ) (a : α) (h : a ≠ 0) : order (monomial α n a) = n := by rw [order_monomial, if_neg h] end order_basic section order_zero_ne_one variables [nonzero_comm_ring α] /-- The order of the formal power series `1` is `0`.-/ @[simp] lemma order_one : order (1 : power_series α) = 0 := by simpa using order_monomial_of_ne_zero 0 (1:α) one_ne_zero /-- The order of the formal power series `X` is `1`.-/ @[simp] lemma order_X : order (X : power_series α) = 1 := order_monomial_of_ne_zero 1 (1:α) one_ne_zero /-- The order of the formal power series `X^n` is `n`.-/ @[simp] lemma order_X_pow (n : ℕ) : order ((X : power_series α)^n) = n := by { rw [X_pow_eq, order_monomial_of_ne_zero], exact one_ne_zero } end order_zero_ne_one section order_integral_domain variables [integral_domain α] /-- The order of the product of two formal power series over an integral domain is the sum of their orders.-/ lemma order_mul (φ ψ : power_series α) : order (φ * ψ) = order φ + order ψ := multiplicity.mul (X_prime) end order_integral_domain end power_series namespace polynomial open finsupp variables {σ : Type*} {α : Type*} [comm_semiring α] /-- The natural inclusion from polynomials into formal power series.-/ instance coe_to_power_series : has_coe (polynomial α) (power_series α) := ⟨λ φ, power_series.mk $ λ n, coeff φ n⟩ @[simp, elim_cast] lemma coeff_coe (φ : polynomial α) (n) : power_series.coeff α n φ = coeff φ n := congr_arg (coeff φ) (finsupp.single_eq_same) @[reducible] def monomial (n : ℕ) (a : α) : polynomial α := single n a @[simp, elim_cast] lemma coe_monomial (n : ℕ) (a : α) : (monomial n a : power_series α) = power_series.monomial α n a := power_series.ext $ λ m, begin rw [coeff_coe, power_series.coeff_monomial], simp only [@eq_comm _ m n], convert finsupp.single_apply, end @[simp, elim_cast] lemma coe_zero : ((0 : polynomial α) : power_series α) = 0 := rfl @[simp, elim_cast] lemma coe_one : ((1 : polynomial α) : power_series α) = 1 := begin have := coe_monomial 0 (1:α), rwa power_series.monomial_zero_eq_C_apply at this, end @[simp, elim_cast] lemma coe_add (φ ψ : polynomial α) : ((φ + ψ : polynomial α) : power_series α) = φ + ψ := rfl @[simp, elim_cast] lemma coe_mul (φ ψ : polynomial α) : ((φ * ψ : polynomial α) : power_series α) = φ * ψ := power_series.ext $ λ n, by simp only [coeff_coe, power_series.coeff_mul, coeff_mul] @[simp, elim_cast] lemma coe_C (a : α) : ((C a : polynomial α) : power_series α) = power_series.C α a := begin have := coe_monomial 0 a, rwa power_series.monomial_zero_eq_C_apply at this, end @[simp, elim_cast] lemma coe_X : ((X : polynomial α) : power_series α) = power_series.X := coe_monomial _ _ namespace coe_to_mv_power_series instance : is_semiring_hom (coe : polynomial α → power_series α) := { map_zero := coe_zero, map_one := coe_one, map_add := coe_add, map_mul := coe_mul } end coe_to_mv_power_series end polynomial
e504c0130e97daa0d9bc8088b1f278cc06f89838
592ee40978ac7604005a4e0d35bbc4b467389241
/Library/generated/mathscheme-lean/MoufangQuasiGroup.lean
02ea0e47542639b28b22cebffc32950a0558e03c
[]
no_license
ysharoda/Deriving-Definitions
3e149e6641fae440badd35ac110a0bd705a49ad2
dfecb27572022de3d4aa702cae8db19957523a59
refs/heads/master
1,679,127,857,700
1,615,939,007,000
1,615,939,007,000
229,785,731
4
0
null
null
null
null
UTF-8
Lean
false
false
12,529
lean
import init.data.nat.basic import init.data.fin.basic import data.vector import .Prelude open Staged open nat open fin open vector section MoufangQuasiGroup structure MoufangQuasiGroup (A : Type) : Type := (op : (A → (A → A))) (linv : (A → (A → A))) (leftCancel : (∀ {x y : A} , (op x (linv x y)) = y)) (lefCancelOp : (∀ {x y : A} , (linv x (op x y)) = y)) (rinv : (A → (A → A))) (rightCancel : (∀ {x y : A} , (op (rinv y x) x) = y)) (rightCancelOp : (∀ {x y : A} , (rinv (op y x) x) = y)) (moufangLaw : (∀ {e x y z : A} , ((op y e) = y → (op (op (op x y) z) x) = (op x (op y (op (op e z) x)))))) open MoufangQuasiGroup structure Sig (AS : Type) : Type := (opS : (AS → (AS → AS))) (linvS : (AS → (AS → AS))) (rinvS : (AS → (AS → AS))) structure Product (A : Type) : Type := (opP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (linvP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (rinvP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (leftCancelP : (∀ {xP yP : (Prod A A)} , (opP xP (linvP xP yP)) = yP)) (lefCancelOpP : (∀ {xP yP : (Prod A A)} , (linvP xP (opP xP yP)) = yP)) (rightCancelP : (∀ {xP yP : (Prod A A)} , (opP (rinvP yP xP) xP) = yP)) (rightCancelOpP : (∀ {xP yP : (Prod A A)} , (rinvP (opP yP xP) xP) = yP)) (moufangLawP : (∀ {eP xP yP zP : (Prod A A)} , ((opP yP eP) = yP → (opP (opP (opP xP yP) zP) xP) = (opP xP (opP yP (opP (opP eP zP) xP)))))) structure Hom {A1 : Type} {A2 : Type} (Mo1 : (MoufangQuasiGroup A1)) (Mo2 : (MoufangQuasiGroup A2)) : Type := (hom : (A1 → A2)) (pres_op : (∀ {x1 x2 : A1} , (hom ((op Mo1) x1 x2)) = ((op Mo2) (hom x1) (hom x2)))) (pres_linv : (∀ {x1 x2 : A1} , (hom ((linv Mo1) x1 x2)) = ((linv Mo2) (hom x1) (hom x2)))) (pres_rinv : (∀ {x1 x2 : A1} , (hom ((rinv Mo1) x1 x2)) = ((rinv Mo2) (hom x1) (hom x2)))) structure RelInterp {A1 : Type} {A2 : Type} (Mo1 : (MoufangQuasiGroup A1)) (Mo2 : (MoufangQuasiGroup A2)) : Type 1 := (interp : (A1 → (A2 → Type))) (interp_op : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((op Mo1) x1 x2) ((op Mo2) y1 y2)))))) (interp_linv : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((linv Mo1) x1 x2) ((linv Mo2) y1 y2)))))) (interp_rinv : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((rinv Mo1) x1 x2) ((rinv Mo2) y1 y2)))))) inductive MoufangQuasiGroupTerm : Type | opL : (MoufangQuasiGroupTerm → (MoufangQuasiGroupTerm → MoufangQuasiGroupTerm)) | linvL : (MoufangQuasiGroupTerm → (MoufangQuasiGroupTerm → MoufangQuasiGroupTerm)) | rinvL : (MoufangQuasiGroupTerm → (MoufangQuasiGroupTerm → MoufangQuasiGroupTerm)) open MoufangQuasiGroupTerm inductive ClMoufangQuasiGroupTerm (A : Type) : Type | sing : (A → ClMoufangQuasiGroupTerm) | opCl : (ClMoufangQuasiGroupTerm → (ClMoufangQuasiGroupTerm → ClMoufangQuasiGroupTerm)) | linvCl : (ClMoufangQuasiGroupTerm → (ClMoufangQuasiGroupTerm → ClMoufangQuasiGroupTerm)) | rinvCl : (ClMoufangQuasiGroupTerm → (ClMoufangQuasiGroupTerm → ClMoufangQuasiGroupTerm)) open ClMoufangQuasiGroupTerm inductive OpMoufangQuasiGroupTerm (n : ℕ) : Type | v : ((fin n) → OpMoufangQuasiGroupTerm) | opOL : (OpMoufangQuasiGroupTerm → (OpMoufangQuasiGroupTerm → OpMoufangQuasiGroupTerm)) | linvOL : (OpMoufangQuasiGroupTerm → (OpMoufangQuasiGroupTerm → OpMoufangQuasiGroupTerm)) | rinvOL : (OpMoufangQuasiGroupTerm → (OpMoufangQuasiGroupTerm → OpMoufangQuasiGroupTerm)) open OpMoufangQuasiGroupTerm inductive OpMoufangQuasiGroupTerm2 (n : ℕ) (A : Type) : Type | v2 : ((fin n) → OpMoufangQuasiGroupTerm2) | sing2 : (A → OpMoufangQuasiGroupTerm2) | opOL2 : (OpMoufangQuasiGroupTerm2 → (OpMoufangQuasiGroupTerm2 → OpMoufangQuasiGroupTerm2)) | linvOL2 : (OpMoufangQuasiGroupTerm2 → (OpMoufangQuasiGroupTerm2 → OpMoufangQuasiGroupTerm2)) | rinvOL2 : (OpMoufangQuasiGroupTerm2 → (OpMoufangQuasiGroupTerm2 → OpMoufangQuasiGroupTerm2)) open OpMoufangQuasiGroupTerm2 def simplifyCl {A : Type} : ((ClMoufangQuasiGroupTerm A) → (ClMoufangQuasiGroupTerm A)) | (opCl x1 x2) := (opCl (simplifyCl x1) (simplifyCl x2)) | (linvCl x1 x2) := (linvCl (simplifyCl x1) (simplifyCl x2)) | (rinvCl x1 x2) := (rinvCl (simplifyCl x1) (simplifyCl x2)) | (sing x1) := (sing x1) def simplifyOpB {n : ℕ} : ((OpMoufangQuasiGroupTerm n) → (OpMoufangQuasiGroupTerm n)) | (opOL x1 x2) := (opOL (simplifyOpB x1) (simplifyOpB x2)) | (linvOL x1 x2) := (linvOL (simplifyOpB x1) (simplifyOpB x2)) | (rinvOL x1 x2) := (rinvOL (simplifyOpB x1) (simplifyOpB x2)) | (v x1) := (v x1) def simplifyOp {n : ℕ} {A : Type} : ((OpMoufangQuasiGroupTerm2 n A) → (OpMoufangQuasiGroupTerm2 n A)) | (opOL2 x1 x2) := (opOL2 (simplifyOp x1) (simplifyOp x2)) | (linvOL2 x1 x2) := (linvOL2 (simplifyOp x1) (simplifyOp x2)) | (rinvOL2 x1 x2) := (rinvOL2 (simplifyOp x1) (simplifyOp x2)) | (v2 x1) := (v2 x1) | (sing2 x1) := (sing2 x1) def evalB {A : Type} : ((MoufangQuasiGroup A) → (MoufangQuasiGroupTerm → A)) | Mo (opL x1 x2) := ((op Mo) (evalB Mo x1) (evalB Mo x2)) | Mo (linvL x1 x2) := ((linv Mo) (evalB Mo x1) (evalB Mo x2)) | Mo (rinvL x1 x2) := ((rinv Mo) (evalB Mo x1) (evalB Mo x2)) def evalCl {A : Type} : ((MoufangQuasiGroup A) → ((ClMoufangQuasiGroupTerm A) → A)) | Mo (sing x1) := x1 | Mo (opCl x1 x2) := ((op Mo) (evalCl Mo x1) (evalCl Mo x2)) | Mo (linvCl x1 x2) := ((linv Mo) (evalCl Mo x1) (evalCl Mo x2)) | Mo (rinvCl x1 x2) := ((rinv Mo) (evalCl Mo x1) (evalCl Mo x2)) def evalOpB {A : Type} {n : ℕ} : ((MoufangQuasiGroup A) → ((vector A n) → ((OpMoufangQuasiGroupTerm n) → A))) | Mo vars (v x1) := (nth vars x1) | Mo vars (opOL x1 x2) := ((op Mo) (evalOpB Mo vars x1) (evalOpB Mo vars x2)) | Mo vars (linvOL x1 x2) := ((linv Mo) (evalOpB Mo vars x1) (evalOpB Mo vars x2)) | Mo vars (rinvOL x1 x2) := ((rinv Mo) (evalOpB Mo vars x1) (evalOpB Mo vars x2)) def evalOp {A : Type} {n : ℕ} : ((MoufangQuasiGroup A) → ((vector A n) → ((OpMoufangQuasiGroupTerm2 n A) → A))) | Mo vars (v2 x1) := (nth vars x1) | Mo vars (sing2 x1) := x1 | Mo vars (opOL2 x1 x2) := ((op Mo) (evalOp Mo vars x1) (evalOp Mo vars x2)) | Mo vars (linvOL2 x1 x2) := ((linv Mo) (evalOp Mo vars x1) (evalOp Mo vars x2)) | Mo vars (rinvOL2 x1 x2) := ((rinv Mo) (evalOp Mo vars x1) (evalOp Mo vars x2)) def inductionB {P : (MoufangQuasiGroupTerm → Type)} : ((∀ (x1 x2 : MoufangQuasiGroupTerm) , ((P x1) → ((P x2) → (P (opL x1 x2))))) → ((∀ (x1 x2 : MoufangQuasiGroupTerm) , ((P x1) → ((P x2) → (P (linvL x1 x2))))) → ((∀ (x1 x2 : MoufangQuasiGroupTerm) , ((P x1) → ((P x2) → (P (rinvL x1 x2))))) → (∀ (x : MoufangQuasiGroupTerm) , (P x))))) | popl plinvl prinvl (opL x1 x2) := (popl _ _ (inductionB popl plinvl prinvl x1) (inductionB popl plinvl prinvl x2)) | popl plinvl prinvl (linvL x1 x2) := (plinvl _ _ (inductionB popl plinvl prinvl x1) (inductionB popl plinvl prinvl x2)) | popl plinvl prinvl (rinvL x1 x2) := (prinvl _ _ (inductionB popl plinvl prinvl x1) (inductionB popl plinvl prinvl x2)) def inductionCl {A : Type} {P : ((ClMoufangQuasiGroupTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((∀ (x1 x2 : (ClMoufangQuasiGroupTerm A)) , ((P x1) → ((P x2) → (P (opCl x1 x2))))) → ((∀ (x1 x2 : (ClMoufangQuasiGroupTerm A)) , ((P x1) → ((P x2) → (P (linvCl x1 x2))))) → ((∀ (x1 x2 : (ClMoufangQuasiGroupTerm A)) , ((P x1) → ((P x2) → (P (rinvCl x1 x2))))) → (∀ (x : (ClMoufangQuasiGroupTerm A)) , (P x)))))) | psing popcl plinvcl prinvcl (sing x1) := (psing x1) | psing popcl plinvcl prinvcl (opCl x1 x2) := (popcl _ _ (inductionCl psing popcl plinvcl prinvcl x1) (inductionCl psing popcl plinvcl prinvcl x2)) | psing popcl plinvcl prinvcl (linvCl x1 x2) := (plinvcl _ _ (inductionCl psing popcl plinvcl prinvcl x1) (inductionCl psing popcl plinvcl prinvcl x2)) | psing popcl plinvcl prinvcl (rinvCl x1 x2) := (prinvcl _ _ (inductionCl psing popcl plinvcl prinvcl x1) (inductionCl psing popcl plinvcl prinvcl x2)) def inductionOpB {n : ℕ} {P : ((OpMoufangQuasiGroupTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((∀ (x1 x2 : (OpMoufangQuasiGroupTerm n)) , ((P x1) → ((P x2) → (P (opOL x1 x2))))) → ((∀ (x1 x2 : (OpMoufangQuasiGroupTerm n)) , ((P x1) → ((P x2) → (P (linvOL x1 x2))))) → ((∀ (x1 x2 : (OpMoufangQuasiGroupTerm n)) , ((P x1) → ((P x2) → (P (rinvOL x1 x2))))) → (∀ (x : (OpMoufangQuasiGroupTerm n)) , (P x)))))) | pv popol plinvol prinvol (v x1) := (pv x1) | pv popol plinvol prinvol (opOL x1 x2) := (popol _ _ (inductionOpB pv popol plinvol prinvol x1) (inductionOpB pv popol plinvol prinvol x2)) | pv popol plinvol prinvol (linvOL x1 x2) := (plinvol _ _ (inductionOpB pv popol plinvol prinvol x1) (inductionOpB pv popol plinvol prinvol x2)) | pv popol plinvol prinvol (rinvOL x1 x2) := (prinvol _ _ (inductionOpB pv popol plinvol prinvol x1) (inductionOpB pv popol plinvol prinvol x2)) def inductionOp {n : ℕ} {A : Type} {P : ((OpMoufangQuasiGroupTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((∀ (x1 x2 : (OpMoufangQuasiGroupTerm2 n A)) , ((P x1) → ((P x2) → (P (opOL2 x1 x2))))) → ((∀ (x1 x2 : (OpMoufangQuasiGroupTerm2 n A)) , ((P x1) → ((P x2) → (P (linvOL2 x1 x2))))) → ((∀ (x1 x2 : (OpMoufangQuasiGroupTerm2 n A)) , ((P x1) → ((P x2) → (P (rinvOL2 x1 x2))))) → (∀ (x : (OpMoufangQuasiGroupTerm2 n A)) , (P x))))))) | pv2 psing2 popol2 plinvol2 prinvol2 (v2 x1) := (pv2 x1) | pv2 psing2 popol2 plinvol2 prinvol2 (sing2 x1) := (psing2 x1) | pv2 psing2 popol2 plinvol2 prinvol2 (opOL2 x1 x2) := (popol2 _ _ (inductionOp pv2 psing2 popol2 plinvol2 prinvol2 x1) (inductionOp pv2 psing2 popol2 plinvol2 prinvol2 x2)) | pv2 psing2 popol2 plinvol2 prinvol2 (linvOL2 x1 x2) := (plinvol2 _ _ (inductionOp pv2 psing2 popol2 plinvol2 prinvol2 x1) (inductionOp pv2 psing2 popol2 plinvol2 prinvol2 x2)) | pv2 psing2 popol2 plinvol2 prinvol2 (rinvOL2 x1 x2) := (prinvol2 _ _ (inductionOp pv2 psing2 popol2 plinvol2 prinvol2 x1) (inductionOp pv2 psing2 popol2 plinvol2 prinvol2 x2)) def stageB : (MoufangQuasiGroupTerm → (Staged MoufangQuasiGroupTerm)) | (opL x1 x2) := (stage2 opL (codeLift2 opL) (stageB x1) (stageB x2)) | (linvL x1 x2) := (stage2 linvL (codeLift2 linvL) (stageB x1) (stageB x2)) | (rinvL x1 x2) := (stage2 rinvL (codeLift2 rinvL) (stageB x1) (stageB x2)) def stageCl {A : Type} : ((ClMoufangQuasiGroupTerm A) → (Staged (ClMoufangQuasiGroupTerm A))) | (sing x1) := (Now (sing x1)) | (opCl x1 x2) := (stage2 opCl (codeLift2 opCl) (stageCl x1) (stageCl x2)) | (linvCl x1 x2) := (stage2 linvCl (codeLift2 linvCl) (stageCl x1) (stageCl x2)) | (rinvCl x1 x2) := (stage2 rinvCl (codeLift2 rinvCl) (stageCl x1) (stageCl x2)) def stageOpB {n : ℕ} : ((OpMoufangQuasiGroupTerm n) → (Staged (OpMoufangQuasiGroupTerm n))) | (v x1) := (const (code (v x1))) | (opOL x1 x2) := (stage2 opOL (codeLift2 opOL) (stageOpB x1) (stageOpB x2)) | (linvOL x1 x2) := (stage2 linvOL (codeLift2 linvOL) (stageOpB x1) (stageOpB x2)) | (rinvOL x1 x2) := (stage2 rinvOL (codeLift2 rinvOL) (stageOpB x1) (stageOpB x2)) def stageOp {n : ℕ} {A : Type} : ((OpMoufangQuasiGroupTerm2 n A) → (Staged (OpMoufangQuasiGroupTerm2 n A))) | (sing2 x1) := (Now (sing2 x1)) | (v2 x1) := (const (code (v2 x1))) | (opOL2 x1 x2) := (stage2 opOL2 (codeLift2 opOL2) (stageOp x1) (stageOp x2)) | (linvOL2 x1 x2) := (stage2 linvOL2 (codeLift2 linvOL2) (stageOp x1) (stageOp x2)) | (rinvOL2 x1 x2) := (stage2 rinvOL2 (codeLift2 rinvOL2) (stageOp x1) (stageOp x2)) structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type := (opT : ((Repr A) → ((Repr A) → (Repr A)))) (linvT : ((Repr A) → ((Repr A) → (Repr A)))) (rinvT : ((Repr A) → ((Repr A) → (Repr A)))) end MoufangQuasiGroup