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
3607eb80229500b9b1fd63282e6ad409f0533031
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/topology/uniform_space/uniform_convergence.lean
a6d5ffd0721cc5cc6d7be97086f00ad2759e29ed
[ "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
16,715
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.uniform_space.basic /-! # Uniform convergence A sequence of functions `Fₙ` (with values in a metric space) converges uniformly on a set `s` to a function `f` if, for all `ε > 0`, for all large enough `n`, one has for all `y ∈ s` the inequality `dist (f y, Fₙ y) < ε`. Under uniform convergence, many properties of the `Fₙ` pass to the limit, most notably continuity. We prove this in the file, defining the notion of uniform convergence in the more general setting of uniform spaces, and with respect to an arbitrary indexing set endowed with a filter (instead of just `ℕ` with `at_top`). ## Main results Let `α` be a topological space, `β` a uniform space, `Fₙ` and `f` be functions from `α`to `β` (where the index `n` belongs to an indexing type `ι` endowed with a filter `p`). * `tendsto_uniformly_on F f p s`: the fact that `Fₙ` converges uniformly to `f` on `s`. This means that, for any entourage `u` of the diagonal, for large enough `n` (with respect to `p`), one has `(f y, Fₙ y) ∈ u` for all `y ∈ s`. * `tendsto_uniformly F f p`: same notion with `s = univ`. * `tendsto_uniformly_on.continuous_on`: a uniform limit on a set of functions which are continuous on this set is itself continuous on this set. * `tendsto_uniformly.continuous`: a uniform limit of continuous functions is continuous. * `tendsto_uniformly_on.tendsto_comp`: If `Fₙ` tends uniformly to `f` on a set `s`, and `gₙ` tends to `x` within `s`, then `Fₙ gₙ` tends to `f x` if `f` is continuous at `x` within `s`. * `tendsto_uniformly.tendsto_comp`: If `Fₙ` tends uniformly to `f`, and `gₙ` tends to `x`, then `Fₙ gₙ` tends to `f x`. We also define notions where the convergence is locally uniform, called `tendsto_locally_uniformly_on F f p s` and `tendsto_locally_uniformly F f p`. The previous theorems all have corresponding versions under locally uniform convergence. ## Implementation notes Most results hold under weaker assumptions of locally uniform approximation. In a first section, we prove the results under these weaker assumptions. Then, we derive the results on uniform convergence from them. ## Tags Uniform limit, uniform convergence, tends uniformly to -/ noncomputable theory open_locale topological_space classical uniformity open set filter universes u v w variables {α : Type u} {β : Type v} {γ : Type w} /-! ### Different notions of uniform convergence We define uniform convergence and locally uniform convergence, on a set or in the whole space. -/ variables {ι : Type*} [uniform_space β] {F : ι → α → β} {f : α → β} {s s' : set α} {x : α} {p : filter ι} {g : ι → α} /-- A sequence of functions `Fₙ` converges uniformly on a set `s` to a limiting function `f` with respect to the filter `p` if, for any entourage of the diagonal `u`, one has `p`-eventually `(f x, Fₙ x) ∈ u` for all `x ∈ s`. -/ def tendsto_uniformly_on (F : ι → α → β) (f : α → β) (p : filter ι) (s : set α) := ∀ u ∈ 𝓤 β, ∀ᶠ n in p, ∀ x ∈ s, (f x, F n x) ∈ u /-- A sequence of functions `Fₙ` converges uniformly to a limiting function `f` with respect to a filter `p` if, for any entourage of the diagonal `u`, one has `p`-eventually `(f x, Fₙ x) ∈ u` for all `x`. -/ def tendsto_uniformly (F : ι → α → β) (f : α → β) (p : filter ι) := ∀ u ∈ 𝓤 β, ∀ᶠ n in p, ∀ x, (f x, F n x) ∈ u lemma tendsto_uniformly_on_univ : tendsto_uniformly_on F f p univ ↔ tendsto_uniformly F f p := by simp [tendsto_uniformly_on, tendsto_uniformly] lemma tendsto_uniformly_on.mono {s' : set α} (h : tendsto_uniformly_on F f p s) (h' : s' ⊆ s) : tendsto_uniformly_on F f p s' := λ u hu, (h u hu).mono (λ n hn x hx, hn x (h' hx)) lemma tendsto_uniformly.tendsto_uniformly_on (h : tendsto_uniformly F f p) : tendsto_uniformly_on F f p s := (tendsto_uniformly_on_univ.2 h).mono (subset_univ s) /-- Composing on the right by a function preserves uniform convergence on a set -/ lemma tendsto_uniformly_on.comp (h : tendsto_uniformly_on F f p s) (g : γ → α) : tendsto_uniformly_on (λ n, F n ∘ g) (f ∘ g) p (g ⁻¹' s) := begin assume u hu, apply (h u hu).mono (λ n hn, _), exact λ x hx, hn _ hx end /-- Composing on the right by a function preserves uniform convergence -/ lemma tendsto_uniformly.comp (h : tendsto_uniformly F f p) (g : γ → α) : tendsto_uniformly (λ n, F n ∘ g) (f ∘ g) p := begin assume u hu, apply (h u hu).mono (λ n hn, _), exact λ x, hn _ end variable [topological_space α] /-- A sequence of functions `Fₙ` converges locally uniformly on a set `s` to a limiting function `f` with respect to a filter `p` if, for any entourage of the diagonal `u`, for any `x ∈ s`, one has `p`-eventually `(f x, Fₙ x) ∈ u` for all `y` in a neighborhood of `x` in `s`. -/ def tendsto_locally_uniformly_on (F : ι → α → β) (f : α → β) (p : filter ι) (s : set α) := ∀ u ∈ 𝓤 β, ∀ x ∈ s, ∃ t ∈ nhds_within x s, ∀ᶠ n in p, ∀ y ∈ t, (f y, F n y) ∈ u /-- A sequence of functions `Fₙ` converges locally uniformly to a limiting function `f` with respect to a filter `p` if, for any entourage of the diagonal `u`, for any `x`, one has `p`-eventually `(f x, Fₙ x) ∈ u` for all `y` in a neighborhood of `x`. -/ def tendsto_locally_uniformly (F : ι → α → β) (f : α → β) (p : filter ι) := ∀ u ∈ 𝓤 β, ∀ (x : α), ∃ t ∈ 𝓝 x, ∀ᶠ n in p, ∀ y ∈ t, (f y, F n y) ∈ u lemma tendsto_uniformly_on.tendsto_locally_uniformly_on (h : tendsto_uniformly_on F f p s) : tendsto_locally_uniformly_on F f p s := λ u hu x hx, ⟨s, self_mem_nhds_within, h u hu⟩ lemma tendsto_uniformly.tendsto_locally_uniformly (h : tendsto_uniformly F f p) : tendsto_locally_uniformly F f p := λ u hu x, ⟨univ, univ_mem_sets, by simpa using h u hu⟩ lemma tendsto_locally_uniformly_on.mono (h : tendsto_locally_uniformly_on F f p s) (h' : s' ⊆ s) : tendsto_locally_uniformly_on F f p s' := begin assume u hu x hx, rcases h u hu x (h' hx) with ⟨t, ht, H⟩, exact ⟨t, nhds_within_mono x h' ht, H.mono (λ n, id)⟩ end lemma tendsto_locally_uniformly_on_univ : tendsto_locally_uniformly_on F f p univ ↔ tendsto_locally_uniformly F f p := by simp [tendsto_locally_uniformly_on, tendsto_locally_uniformly, nhds_within_univ] lemma tendsto_locally_uniformly_on.comp [topological_space γ] {t : set γ} (h : tendsto_locally_uniformly_on F f p s) (g : γ → α) (hg : maps_to g t s) (cg : continuous_on g t) : tendsto_locally_uniformly_on (λ n, (F n) ∘ g) (f ∘ g) p t := begin assume u hu x hx, rcases h u hu (g x) (hg hx) with ⟨a, ha, H⟩, have : g⁻¹' a ∈ nhds_within x t := ((cg x hx).preimage_mem_nhds_within' (nhds_within_mono (g x) hg.image_subset ha)), exact ⟨g ⁻¹' a, this, H.mono (λ n hn y hy, hn _ hy)⟩ end lemma tendsto_locally_uniformly.comp [topological_space γ] (h : tendsto_locally_uniformly F f p) (g : γ → α) (cg : continuous g) : tendsto_locally_uniformly (λ n, (F n) ∘ g) (f ∘ g) p := begin rw ← tendsto_locally_uniformly_on_univ at h ⊢, rw continuous_iff_continuous_on_univ at cg, exact h.comp _ (maps_to_univ _ _) cg end /-! ### Uniform approximation In this section, we give lemmas ensuring that a function is continuous if it can be approximated uniformly by continuous functions. We give various versions, within a set or the whole space, at a single point or at all points, with locally uniform approximation or uniform approximation. All the statements are derived from a statement about locally uniform approximation within a set at a point, called `continuous_within_at_of_locally_uniform_approx_of_continuous_within_at`. -/ /-- A function which can be locally uniformly approximated by functions which are continuous within a set at a point is continuous within this set at this point. -/ lemma continuous_within_at_of_locally_uniform_approx_of_continuous_within_at (hx : x ∈ s) (L : ∀ u ∈ 𝓤 β, ∃ t ∈ nhds_within x s, ∃ n, ∀ y ∈ t, (f y, F n y) ∈ u) (C : ∀ n, continuous_within_at (F n) s x) : continuous_within_at f s x := begin apply uniform.continuous_within_at_iff'_left.2 (λ u₀ hu₀, _), obtain ⟨u₁, h₁, u₁₀⟩ : ∃ (u : set (β × β)) (H : u ∈ 𝓤 β), comp_rel u u ⊆ u₀ := comp_mem_uniformity_sets hu₀, obtain ⟨u₂, h₂, hsymm, u₂₁⟩ : ∃ (u : set (β × β)) (H : u ∈ 𝓤 β), (∀{a b}, (a, b) ∈ u → (b, a) ∈ u) ∧ comp_rel u u ⊆ u₁ := comp_symm_of_uniformity h₁, rcases L u₂ h₂ with ⟨t, tx, n, ht⟩, have A : ∀ᶠ y in nhds_within x s, (f y, F n y) ∈ u₂ := eventually.mono tx ht, have B : ∀ᶠ y in nhds_within x s, (F n y, F n x) ∈ u₂ := uniform.continuous_within_at_iff'_left.1 (C n) h₂, have C : ∀ᶠ y in nhds_within x s, (f y, F n x) ∈ u₁ := (A.and B).mono (λ y hy, u₂₁ (prod_mk_mem_comp_rel hy.1 hy.2)), have : (F n x, f x) ∈ u₁ := u₂₁ (prod_mk_mem_comp_rel (refl_mem_uniformity h₂) (hsymm (A.self_of_nhds_within hx))), exact C.mono (λ y hy, u₁₀ (prod_mk_mem_comp_rel hy this)) end /-- A function which can be locally uniformly approximated by functions which are continuous at a point is continuous at this point. -/ lemma continuous_at_of_locally_uniform_approx_of_continuous_at (L : ∀ u ∈ 𝓤 β, ∃ t ∈ 𝓝 x, ∃ n, ∀ y ∈ t, (f y, F n y) ∈ u) (C : ∀ n, continuous_at (F n) x) : continuous_at f x := begin simp only [← continuous_within_at_univ] at C ⊢, apply continuous_within_at_of_locally_uniform_approx_of_continuous_within_at (mem_univ _) _ C, simpa [nhds_within_univ] using L end /-- A function which can be locally uniformly approximated by functions which are continuous on a set is continuous on this set. -/ lemma continuous_on_of_locally_uniform_approx_of_continuous_on (L : ∀ (x ∈ s) (u ∈ 𝓤 β), ∃t ∈ nhds_within x s, ∃n, ∀ y ∈ t, (f y, F n y) ∈ u) (C : ∀ n, continuous_on (F n) s) : continuous_on f s := λ x hx, continuous_within_at_of_locally_uniform_approx_of_continuous_within_at hx (L x hx) (λ n, C n x hx) /-- A function which can be uniformly approximated by functions which are continuous on a set is continuous on this set. -/ lemma continuous_on_of_uniform_approx_of_continuous_on (L : ∀ u ∈ 𝓤 β, ∃ n, ∀ y ∈ s, (f y, F n y) ∈ u) : (∀ n, continuous_on (F n) s) → continuous_on f s := continuous_on_of_locally_uniform_approx_of_continuous_on (λ x hx u hu, ⟨s, self_mem_nhds_within, L u hu⟩) /-- A function which can be locally uniformly approximated by continuous functions is continuous. -/ lemma continuous_of_locally_uniform_approx_of_continuous (L : ∀ (x : α), ∀ u ∈ 𝓤 β, ∃ t ∈ 𝓝 x, ∃ n, ∀ y ∈ t, (f y, F n y) ∈ u) (C : ∀ n, continuous (F n)) : continuous f := begin simp only [continuous_iff_continuous_on_univ] at ⊢ C, apply continuous_on_of_locally_uniform_approx_of_continuous_on _ C, simpa [nhds_within_univ] using L end /-- A function which can be uniformly approximated by continuous functions is continuous. -/ lemma continuous_of_uniform_approx_of_continuous (L : ∀ u ∈ 𝓤 β, ∃ N, ∀ y, (f y, F N y) ∈ u) : (∀ n, continuous (F n)) → continuous f := continuous_of_locally_uniform_approx_of_continuous $ λx u hu, ⟨univ, by simpa [filter.univ_mem_sets] using L u hu⟩ /-! ### Uniform limits From the previous statements on uniform approximation, we deduce continuity results for uniform limits. -/ /-- A locally uniform limit on a set of functions which are continuous on this set is itself continuous on this set. -/ lemma tendsto_locally_uniformly_on.continuous_on (h : tendsto_locally_uniformly_on F f p s) (hc : ∀ n, continuous_on (F n) s) [ne_bot p] : continuous_on f s := begin apply continuous_on_of_locally_uniform_approx_of_continuous_on (λ x hx u hu, _) hc, rcases h u hu x hx with ⟨t, ht, H⟩, exact ⟨t, ht, H.exists⟩ end /-- A uniform limit on a set of functions which are continuous on this set is itself continuous on this set. -/ lemma tendsto_uniformly_on.continuous_on (h : tendsto_uniformly_on F f p s) (hc : ∀ n, continuous_on (F n) s) [ne_bot p] : continuous_on f s := h.tendsto_locally_uniformly_on.continuous_on hc /-- A locally uniform limit of continuous functions is continuous. -/ lemma tendsto_locally_uniformly.continuous (h : tendsto_locally_uniformly F f p) (hc : ∀ n, continuous (F n)) [ne_bot p] : continuous f := begin apply continuous_of_locally_uniform_approx_of_continuous (λ x u hu, _) hc, rcases h u hu x with ⟨t, ht, H⟩, exact ⟨t, ht, H.exists⟩ end /-- A uniform limit of continuous functions is continuous. -/ lemma tendsto_uniformly.continuous (h : tendsto_uniformly F f p) (hc : ∀ n, continuous (F n)) [ne_bot p] : continuous f := h.tendsto_locally_uniformly.continuous hc /-! ### Composing limits under uniform convergence In general, if `Fₙ` converges pointwise to a function `f`, and `gₙ` tends to `x`, it is not true that `Fₙ gₙ` tends to `f x`. It is true however if the convergence of `Fₙ` to `f` is uniform. In this paragraph, we prove variations around this statement. -/ /-- If `Fₙ` converges locally uniformly on a neighborhood of `x` within a set `s` to a function `f` which is continuous at `x` within `s `, and `gₙ` tends to `x` within `s`, then `Fₙ (gₙ)` tends to `f x`. -/ lemma tendsto_comp_of_locally_uniform_limit_within (h : continuous_within_at f s x) (hg : tendsto g p (nhds_within x s)) (hunif : ∀ u ∈ 𝓤 β, ∃ t ∈ nhds_within x s, ∀ᶠ n in p, ∀ y ∈ t, (f y, F n y) ∈ u) : tendsto (λ n, F n (g n)) p (𝓝 (f x)) := begin apply uniform.tendsto_nhds_right.2 (λ u₀ hu₀, _), obtain ⟨u₁, h₁, u₁₀⟩ : ∃ (u : set (β × β)) (H : u ∈ 𝓤 β), comp_rel u u ⊆ u₀ := comp_mem_uniformity_sets hu₀, rcases hunif u₁ h₁ with ⟨s, sx, hs⟩, have A : ∀ᶠ n in p, g n ∈ s := hg sx, have B : ∀ᶠ n in p, (f x, f (g n)) ∈ u₁ := hg (uniform.continuous_within_at_iff'_right.1 h h₁), refine ((hs.and A).and B).mono (λ y hy, _), rcases hy with ⟨⟨H1, H2⟩, H3⟩, exact u₁₀ (prod_mk_mem_comp_rel H3 (H1 _ H2)) end /-- If `Fₙ` converges locally uniformly on a neighborhood of `x` to a function `f` which is continuous at `x`, and `gₙ` tends to `x`, then `Fₙ (gₙ)` tends to `f x`. -/ lemma tendsto_comp_of_locally_uniform_limit (h : continuous_at f x) (hg : tendsto g p (𝓝 x)) (hunif : ∀ u ∈ 𝓤 β, ∃ t ∈ 𝓝 x, ∀ᶠ n in p, ∀ y ∈ t, (f y, F n y) ∈ u) : tendsto (λ n, F n (g n)) p (𝓝 (f x)) := begin rw ← continuous_within_at_univ at h, rw ← nhds_within_univ at hunif hg, exact tendsto_comp_of_locally_uniform_limit_within h hg hunif end /-- If `Fₙ` tends locally uniformly to `f` on a set `s`, and `gₙ` tends to `x` within `s`, then `Fₙ gₙ` tends to `f x` if `f` is continuous at `x` within `s` and `x ∈ s`. -/ lemma tendsto_locally_uniformly_on.tendsto_comp (h : tendsto_locally_uniformly_on F f p s) (hf : continuous_within_at f s x) (hx : x ∈ s) (hg : tendsto g p (nhds_within x s)) : tendsto (λ n, F n (g n)) p (𝓝 (f x)) := tendsto_comp_of_locally_uniform_limit_within hf hg (λ u hu, h u hu x hx) /-- If `Fₙ` tends uniformly to `f` on a set `s`, and `gₙ` tends to `x` within `s`, then `Fₙ gₙ` tends to `f x` if `f` is continuous at `x` within `s`. -/ lemma tendsto_uniformly_on.tendsto_comp (h : tendsto_uniformly_on F f p s) (hf : continuous_within_at f s x) (hg : tendsto g p (nhds_within x s)) : tendsto (λ n, F n (g n)) p (𝓝 (f x)) := tendsto_comp_of_locally_uniform_limit_within hf hg (λ u hu, ⟨s, self_mem_nhds_within, h u hu⟩) /-- If `Fₙ` tends locally uniformly to `f`, and `gₙ` tends to `x`, then `Fₙ gₙ` tends to `f x`. -/ lemma tendsto_locally_uniformly.tendsto_comp (h : tendsto_locally_uniformly F f p) (hf : continuous_at f x) (hg : tendsto g p (𝓝 x)) : tendsto (λ n, F n (g n)) p (𝓝 (f x)) := tendsto_comp_of_locally_uniform_limit hf hg (λ u hu, h u hu x) /-- If `Fₙ` tends uniformly to `f`, and `gₙ` tends to `x`, then `Fₙ gₙ` tends to `f x`. -/ lemma tendsto_uniformly.tendsto_comp (h : tendsto_uniformly F f p) (hf : continuous_at f x) (hg : tendsto g p (𝓝 x)) : tendsto (λ n, F n (g n)) p (𝓝 (f x)) := h.tendsto_locally_uniformly.tendsto_comp hf hg
4ac0b5bb6c66c2c88852a476422e48c7522eb2e6
aa5a655c05e5359a70646b7154e7cac59f0b4132
/stage0/src/Init/Data/UInt.lean
4a928faf822b44485b2798f04affec3c42f947e2
[ "Apache-2.0" ]
permissive
lambdaxymox/lean4
ae943c960a42247e06eff25c35338268d07454cb
278d47c77270664ef29715faab467feac8a0f446
refs/heads/master
1,677,891,867,340
1,612,500,005,000
1,612,500,005,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
12,114
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Data.Fin.Basic import Init.System.Platform open Nat @[extern "lean_uint8_of_nat"] def UInt8.ofNat (n : @& Nat) : UInt8 := ⟨Fin.ofNat n⟩ abbrev Nat.toUInt8 := UInt8.ofNat @[extern "lean_uint8_to_nat"] def UInt8.toNat (n : UInt8) : Nat := n.val.val @[extern c inline "#1 + #2"] def UInt8.add (a b : UInt8) : UInt8 := ⟨a.val + b.val⟩ @[extern c inline "#1 - #2"] def UInt8.sub (a b : UInt8) : UInt8 := ⟨a.val - b.val⟩ @[extern c inline "#1 * #2"] def UInt8.mul (a b : UInt8) : UInt8 := ⟨a.val * b.val⟩ @[extern c inline "#2 == 0 ? 0 : #1 / #2"] def UInt8.div (a b : UInt8) : UInt8 := ⟨a.val / b.val⟩ @[extern c inline "#2 == 0 ? 0 : #1 % #2"] def UInt8.mod (a b : UInt8) : UInt8 := ⟨a.val % b.val⟩ @[extern "lean_uint8_modn"] def UInt8.modn (a : UInt8) (n : @& Nat) : UInt8 := ⟨a.val % n⟩ @[extern c inline "#1 & #2"] def UInt8.land (a b : UInt8) : UInt8 := ⟨Fin.land a.val b.val⟩ @[extern c inline "#1 | #2"] def UInt8.lor (a b : UInt8) : UInt8 := ⟨Fin.lor a.val b.val⟩ def UInt8.lt (a b : UInt8) : Prop := a.val < b.val def UInt8.le (a b : UInt8) : Prop := a.val ≤ b.val instance : OfNat UInt8 n := ⟨UInt8.ofNat n⟩ instance : Add UInt8 := ⟨UInt8.add⟩ instance : Sub UInt8 := ⟨UInt8.sub⟩ instance : Mul UInt8 := ⟨UInt8.mul⟩ instance : Mod UInt8 := ⟨UInt8.mod⟩ instance : HMod UInt8 Nat UInt8 := ⟨UInt8.modn⟩ instance : Div UInt8 := ⟨UInt8.div⟩ instance : HasLess UInt8 := ⟨UInt8.lt⟩ instance : HasLessEq UInt8 := ⟨UInt8.le⟩ @[extern c inline "#1 << #2"] constant UInt8.shiftLeft (a b : UInt8) : UInt8 @[extern c inline "#1 >> #2"] constant UInt8.shiftRight (a b : UInt8) : UInt8 set_option bootstrap.genMatcherCode false in @[extern c inline "#1 < #2"] def UInt8.decLt (a b : UInt8) : Decidable (a < b) := match a, b with | ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (n < m)) set_option bootstrap.genMatcherCode false in @[extern c inline "#1 <= #2"] def UInt8.decLe (a b : UInt8) : Decidable (a ≤ b) := match a, b with | ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (n <= m)) instance (a b : UInt8) : Decidable (a < b) := UInt8.decLt a b instance (a b : UInt8) : Decidable (a ≤ b) := UInt8.decLe a b @[extern "lean_uint16_of_nat"] def UInt16.ofNat (n : @& Nat) : UInt16 := ⟨Fin.ofNat n⟩ abbrev Nat.toUInt16 := UInt16.ofNat @[extern "lean_uint16_to_nat"] def UInt16.toNat (n : UInt16) : Nat := n.val.val @[extern c inline "#1 + #2"] def UInt16.add (a b : UInt16) : UInt16 := ⟨a.val + b.val⟩ @[extern c inline "#1 - #2"] def UInt16.sub (a b : UInt16) : UInt16 := ⟨a.val - b.val⟩ @[extern c inline "#1 * #2"] def UInt16.mul (a b : UInt16) : UInt16 := ⟨a.val * b.val⟩ @[extern c inline "#2 == 0 ? 0 : #1 / #2"] def UInt16.div (a b : UInt16) : UInt16 := ⟨a.val / b.val⟩ @[extern c inline "#2 == 0 ? 0 : #1 % #2"] def UInt16.mod (a b : UInt16) : UInt16 := ⟨a.val % b.val⟩ @[extern "lean_uint16_modn"] def UInt16.modn (a : UInt16) (n : @& Nat) : UInt16 := ⟨a.val % n⟩ @[extern c inline "#1 & #2"] def UInt16.land (a b : UInt16) : UInt16 := ⟨Fin.land a.val b.val⟩ @[extern c inline "#1 | #2"] def UInt16.lor (a b : UInt16) : UInt16 := ⟨Fin.lor a.val b.val⟩ def UInt16.lt (a b : UInt16) : Prop := a.val < b.val def UInt16.le (a b : UInt16) : Prop := a.val ≤ b.val instance : OfNat UInt16 n := ⟨UInt16.ofNat n⟩ instance : Add UInt16 := ⟨UInt16.add⟩ instance : Sub UInt16 := ⟨UInt16.sub⟩ instance : Mul UInt16 := ⟨UInt16.mul⟩ instance : Mod UInt16 := ⟨UInt16.mod⟩ instance : HMod UInt16 Nat UInt16 := ⟨UInt16.modn⟩ instance : Div UInt16 := ⟨UInt16.div⟩ instance : HasLess UInt16 := ⟨UInt16.lt⟩ instance : HasLessEq UInt16 := ⟨UInt16.le⟩ @[extern c inline "#1 << #2"] constant UInt16.shiftLeft (a b : UInt16) : UInt16 @[extern c inline "#1 >> #2"] constant UInt16.shiftRight (a b : UInt16) : UInt16 set_option bootstrap.genMatcherCode false in @[extern c inline "#1 < #2"] def UInt16.decLt (a b : UInt16) : Decidable (a < b) := match a, b with | ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (n < m)) set_option bootstrap.genMatcherCode false in @[extern c inline "#1 <= #2"] def UInt16.decLe (a b : UInt16) : Decidable (a ≤ b) := match a, b with | ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (n <= m)) instance (a b : UInt16) : Decidable (a < b) := UInt16.decLt a b instance (a b : UInt16) : Decidable (a ≤ b) := UInt16.decLe a b @[extern "lean_uint32_of_nat"] def UInt32.ofNat (n : @& Nat) : UInt32 := ⟨Fin.ofNat n⟩ @[extern "lean_uint32_of_nat"] def UInt32.ofNat' (n : Nat) (h : n < UInt32.size) : UInt32 := ⟨⟨n, h⟩⟩ abbrev Nat.toUInt32 := UInt32.ofNat @[extern c inline "#1 + #2"] def UInt32.add (a b : UInt32) : UInt32 := ⟨a.val + b.val⟩ @[extern c inline "#1 - #2"] def UInt32.sub (a b : UInt32) : UInt32 := ⟨a.val - b.val⟩ @[extern c inline "#1 * #2"] def UInt32.mul (a b : UInt32) : UInt32 := ⟨a.val * b.val⟩ @[extern c inline "#2 == 0 ? 0 : #1 / #2"] def UInt32.div (a b : UInt32) : UInt32 := ⟨a.val / b.val⟩ @[extern c inline "#2 == 0 ? 0 : #1 % #2"] def UInt32.mod (a b : UInt32) : UInt32 := ⟨a.val % b.val⟩ @[extern "lean_uint32_modn"] def UInt32.modn (a : UInt32) (n : @& Nat) : UInt32 := ⟨a.val % n⟩ @[extern c inline "#1 & #2"] def UInt32.land (a b : UInt32) : UInt32 := ⟨Fin.land a.val b.val⟩ @[extern c inline "#1 | #2"] def UInt32.lor (a b : UInt32) : UInt32 := ⟨Fin.lor a.val b.val⟩ @[extern c inline "((uint8_t)#1)"] def UInt32.toUInt8 (a : UInt32) : UInt8 := a.toNat.toUInt8 @[extern c inline "((uint16_t)#1)"] def UInt32.toUInt16 (a : UInt32) : UInt16 := a.toNat.toUInt16 @[extern c inline "((uint32_t)#1)"] def UInt8.toUInt32 (a : UInt8) : UInt32 := a.toNat.toUInt32 instance : OfNat UInt32 n := ⟨UInt32.ofNat n⟩ instance : Add UInt32 := ⟨UInt32.add⟩ instance : Sub UInt32 := ⟨UInt32.sub⟩ instance : Mul UInt32 := ⟨UInt32.mul⟩ instance : Mod UInt32 := ⟨UInt32.mod⟩ instance : HMod UInt32 Nat UInt32 := ⟨UInt32.modn⟩ instance : Div UInt32 := ⟨UInt32.div⟩ @[extern c inline "#1 << #2"] constant UInt32.shiftLeft (a b : UInt32) : UInt32 @[extern c inline "#1 >> #2"] constant UInt32.shiftRight (a b : UInt32) : UInt32 @[extern "lean_uint64_of_nat"] def UInt64.ofNat (n : @& Nat) : UInt64 := ⟨Fin.ofNat n⟩ abbrev Nat.toUInt64 := UInt64.ofNat @[extern "lean_uint64_to_nat"] def UInt64.toNat (n : UInt64) : Nat := n.val.val @[extern c inline "#1 + #2"] def UInt64.add (a b : UInt64) : UInt64 := ⟨a.val + b.val⟩ @[extern c inline "#1 - #2"] def UInt64.sub (a b : UInt64) : UInt64 := ⟨a.val - b.val⟩ @[extern c inline "#1 * #2"] def UInt64.mul (a b : UInt64) : UInt64 := ⟨a.val * b.val⟩ @[extern c inline "#2 == 0 ? 0 : #1 / #2"] def UInt64.div (a b : UInt64) : UInt64 := ⟨a.val / b.val⟩ @[extern c inline "#2 == 0 ? 0 : #1 % #2"] def UInt64.mod (a b : UInt64) : UInt64 := ⟨a.val % b.val⟩ @[extern "lean_uint64_modn"] def UInt64.modn (a : UInt64) (n : @& Nat) : UInt64 := ⟨a.val % n⟩ @[extern c inline "#1 & #2"] def UInt64.land (a b : UInt64) : UInt64 := ⟨Fin.land a.val b.val⟩ @[extern c inline "#1 | #2"] def UInt64.lor (a b : UInt64) : UInt64 := ⟨Fin.lor a.val b.val⟩ def UInt64.lt (a b : UInt64) : Prop := a.val < b.val def UInt64.le (a b : UInt64) : Prop := a.val ≤ b.val @[extern c inline "((uint8_t)#1)"] def UInt64.toUInt8 (a : UInt64) : UInt8 := a.toNat.toUInt8 @[extern c inline "((uint16_t)#1)"] def UInt64.toUInt16 (a : UInt64) : UInt16 := a.toNat.toUInt16 @[extern c inline "((uint32_t)#1)"] def UInt64.toUInt32 (a : UInt64) : UInt32 := a.toNat.toUInt32 @[extern c inline "((uint64_t)#1)"] def UInt32.toUInt64 (a : UInt32) : UInt64 := a.toNat.toUInt64 -- TODO(Leo): give reference implementation for shiftLeft and shiftRight, and define them for other UInt types @[extern c inline "#1 << #2"] constant UInt64.shiftLeft (a b : UInt64) : UInt64 @[extern c inline "#1 >> #2"] constant UInt64.shiftRight (a b : UInt64) : UInt64 instance : OfNat UInt64 n := ⟨UInt64.ofNat n⟩ instance : Add UInt64 := ⟨UInt64.add⟩ instance : Sub UInt64 := ⟨UInt64.sub⟩ instance : Mul UInt64 := ⟨UInt64.mul⟩ instance : Mod UInt64 := ⟨UInt64.mod⟩ instance : HMod UInt64 Nat UInt64 := ⟨UInt64.modn⟩ instance : Div UInt64 := ⟨UInt64.div⟩ instance : HasLess UInt64 := ⟨UInt64.lt⟩ instance : HasLessEq UInt64 := ⟨UInt64.le⟩ @[extern c inline "(uint64_t)#1"] def Bool.toUInt64 (b : Bool) : UInt64 := if b then 1 else 0 set_option bootstrap.genMatcherCode false in @[extern c inline "#1 < #2"] def UInt64.decLt (a b : UInt64) : Decidable (a < b) := match a, b with | ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (n < m)) set_option bootstrap.genMatcherCode false in @[extern c inline "#1 <= #2"] def UInt64.decLe (a b : UInt64) : Decidable (a ≤ b) := match a, b with | ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (n <= m)) instance (a b : UInt64) : Decidable (a < b) := UInt64.decLt a b instance (a b : UInt64) : Decidable (a ≤ b) := UInt64.decLe a b theorem usizeSzGt0 : USize.size > 0 := Nat.posPowOfPos System.Platform.numBits (Nat.zeroLtSucc _) @[extern "lean_usize_of_nat"] def USize.ofNat (n : @& Nat) : USize := ⟨Fin.ofNat' n usizeSzGt0⟩ abbrev Nat.toUSize := USize.ofNat @[extern "lean_usize_to_nat"] def USize.toNat (n : USize) : Nat := n.val.val @[extern c inline "#1 + #2"] def USize.add (a b : USize) : USize := ⟨a.val + b.val⟩ @[extern c inline "#1 - #2"] def USize.sub (a b : USize) : USize := ⟨a.val - b.val⟩ @[extern c inline "#1 * #2"] def USize.mul (a b : USize) : USize := ⟨a.val * b.val⟩ @[extern c inline "#2 == 0 ? 0 : #1 / #2"] def USize.div (a b : USize) : USize := ⟨a.val / b.val⟩ @[extern c inline "#2 == 0 ? 0 : #1 % #2"] def USize.mod (a b : USize) : USize := ⟨a.val % b.val⟩ @[extern "lean_usize_modn"] def USize.modn (a : USize) (n : @& Nat) : USize := ⟨a.val % n⟩ @[extern c inline "#1 & #2"] def USize.land (a b : USize) : USize := ⟨Fin.land a.val b.val⟩ @[extern c inline "#1 | #2"] def USize.lor (a b : USize) : USize := ⟨Fin.lor a.val b.val⟩ @[extern c inline "#1"] def UInt32.toUSize (a : UInt32) : USize := a.toNat.toUSize @[extern c inline "((size_t)#1)"] def UInt64.toUSize (a : UInt64) : USize := a.toNat.toUSize @[extern c inline "(uint32_t)#1"] def USize.toUInt32 (a : USize) : UInt32 := a.toNat.toUInt32 -- TODO(Leo): give reference implementation for shiftLeft and shiftRight, and define them for other UInt types @[extern c inline "#1 << #2"] constant USize.shiftLeft (a b : USize) : USize @[extern c inline "#1 >> #2"] constant USize.shiftRight (a b : USize) : USize def USize.lt (a b : USize) : Prop := a.val < b.val def USize.le (a b : USize) : Prop := a.val ≤ b.val instance : OfNat USize n := ⟨USize.ofNat n⟩ instance : Add USize := ⟨USize.add⟩ instance : Sub USize := ⟨USize.sub⟩ instance : Mul USize := ⟨USize.mul⟩ instance : Mod USize := ⟨USize.mod⟩ instance : HMod USize Nat USize := ⟨USize.modn⟩ instance : Div USize := ⟨USize.div⟩ instance : HasLess USize := ⟨USize.lt⟩ instance : HasLessEq USize := ⟨USize.le⟩ set_option bootstrap.genMatcherCode false in @[extern c inline "#1 < #2"] def USize.decLt (a b : USize) : Decidable (a < b) := match a, b with | ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (n < m)) set_option bootstrap.genMatcherCode false in @[extern c inline "#1 <= #2"] def USize.decLe (a b : USize) : Decidable (a ≤ b) := match a, b with | ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (n <= m)) instance (a b : USize) : Decidable (a < b) := USize.decLt a b instance (a b : USize) : Decidable (a ≤ b) := USize.decLe a b theorem USize.modnLt {m : Nat} : ∀ (u : USize), m > 0 → USize.toNat (u % m) < m | ⟨u⟩, h => Fin.modnLt u h
d252f64391b9f7ea5a2c2d97f2e40fd0b65a526c
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/stage0/src/Init/WF.lean
8754bd3a94a28bb6922d317136f952f012f36715
[ "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
11,154
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import Init.SizeOf import Init.Data.Nat.Basic universes u v set_option codegen false inductive Acc {α : Sort u} (r : α → α → Prop) : α → Prop | intro (x : α) (h : (y : α) → r y x → Acc r y) : Acc r x abbrev Acc.ndrec.{u1, u2} {α : Sort u2} {r : α → α → Prop} {C : α → Sort u1} (m : (x : α) → ((y : α) → r y x → Acc r y) → ((y : α) → (a : r y x) → C y) → C x) {a : α} (n : Acc r a) : C a := Acc.rec (motive := fun α _ => C α) m n abbrev Acc.ndrecOn.{u1, u2} {α : Sort u2} {r : α → α → Prop} {C : α → Sort u1} {a : α} (n : Acc r a) (m : (x : α) → ((y : α) → r y x → Acc r y) → ((y : α) → (a : r y x) → C y) → C x) : C a := Acc.rec (motive := fun α _ => C α) m n namespace Acc variables {α : Sort u} {r : α → α → Prop} def inv {x y : α} (h₁ : Acc r x) (h₂ : r y x) : Acc r y := Acc.recOn (motive := fun (x : α) _ => r y x → Acc r y) h₁ (fun x₁ ac₁ ih h₂ => ac₁ y h₂) h₂ end Acc inductive WellFounded {α : Sort u} (r : α → α → Prop) : Prop | intro (h : ∀ a, Acc r a) : WellFounded r class WellFoundedRelation (α : Sort u) : Type u := (r : α → α → Prop) (wf : WellFounded r) namespace WellFounded def apply {α : Sort u} {r : α → α → Prop} (wf : WellFounded r) (a : α) : Acc r a := WellFounded.recOn (motive := fun x => (y : α) → Acc r y) wf (fun p => p) a section variables {α : Sort u} {r : α → α → Prop} (hwf : WellFounded r) theorem recursion {C : α → Sort v} (a : α) (h : ∀ x, (∀ y, r y x → C y) → C x) : C a := by induction (apply hwf a) | intro x₁ ac₁ ih => exact h x₁ ih theorem induction {C : α → Prop} (a : α) (h : ∀ x, (∀ y, r y x → C y) → C x) : C a := recursion hwf a h variable {C : α → Sort v} variable (F : ∀ x, (∀ y, r y x → C y) → C x) def fixF (x : α) (a : Acc r x) : C x := by induction a | intro x₁ ac₁ ih => exact F x₁ ih def fixFEq (x : α) (acx : Acc r x) : fixF F x acx = F x (fun (y : α) (p : r y x) => fixF F y (Acc.inv acx p)) := by induction acx | intro x r ih => exact rfl end variables {α : Sort u} {C : α → Sort v} {r : α → α → Prop} -- Well-founded fixpoint def fix (hwf : WellFounded r) (F : ∀ x, (∀ y, r y x → C y) → C x) (x : α) : C x := fixF F x (apply hwf x) -- Well-founded fixpoint satisfies fixpoint equation theorem fixEq (hwf : WellFounded r) (F : ∀ x, (∀ y, r y x → C y) → C x) (x : α) : fix hwf F x = F x (fun y h => fix hwf F y) := fixFEq F x (apply hwf x) end WellFounded open WellFounded -- Empty relation is well-founded def emptyWf {α : Sort u} : WellFounded (@emptyRelation α) := by apply WellFounded.intro intro a apply Acc.intro a intro b h cases h -- Subrelation of a well-founded relation is well-founded namespace Subrelation variables {α : Sort u} {r q : α → α → Prop} def accessible {a : α} (h₁ : Subrelation q r) (ac : Acc r a) : Acc q a := by induction ac | intro x ax ih => apply Acc.intro intro y h exact ih y (h₁ h) def wf (h₁ : Subrelation q r) (h₂ : WellFounded r) : WellFounded q := ⟨fun a => accessible @h₁ (apply h₂ a)⟩ end Subrelation -- The inverse image of a well-founded relation is well-founded namespace InvImage variables {α : Sort u} {β : Sort v} {r : β → β → Prop} private def accAux (f : α → β) {b : β} (ac : Acc r b) : (x : α) → f x = b → Acc (InvImage r f) x := by induction ac | intro x acx ih => intro z e apply Acc.intro intro y lt subst x apply ih (f y) lt y rfl def accessible {a : α} (f : α → β) (ac : Acc r (f a)) : Acc (InvImage r f) a := accAux f ac a rfl def wf (f : α → β) (h : WellFounded r) : WellFounded (InvImage r f) := ⟨fun a => accessible f (apply h (f a))⟩ end InvImage -- The transitive closure of a well-founded relation is well-founded namespace TC variables {α : Sort u} {r : α → α → Prop} def accessible {z : α} (ac : Acc r z) : Acc (TC r) z := by induction ac | intro x acx ih => apply Acc.intro x intro y rel induction rel generalizing acx ih | base a b rab => exact ih a rab | trans a b c rab rbc ih₁ ih₂ => apply Acc.inv (ih₂ acx ih) rab def wf (h : WellFounded r) : WellFounded (TC r) := ⟨fun a => accessible (apply h a)⟩ end TC -- less-than is well-founded def Nat.ltWf : WellFounded Nat.lt := by apply WellFounded.intro intro n induction n | zero => apply Acc.intro 0 intro _ h apply absurd h (Nat.notLtZero _) | succ n ih => apply Acc.intro (Nat.succ n) intro m h have m = n ∨ m < n from Nat.eqOrLtOfLe (Nat.leOfSuccLeSucc h) match this with | Or.inl e => subst e; assumption | Or.inr e => exact Acc.inv ih e def measure {α : Sort u} : (α → Nat) → α → α → Prop := InvImage (fun a b => a < b) def measureWf {α : Sort u} (f : α → Nat) : WellFounded (measure f) := InvImage.wf f Nat.ltWf def sizeofMeasure (α : Sort u) [SizeOf α] : α → α → Prop := measure sizeOf def sizeofMeasureWf (α : Sort u) [SizeOf α] : WellFounded (sizeofMeasure α) := measureWf sizeOf instance hasWellFoundedOfSizeOf (α : Sort u) [SizeOf α] : WellFoundedRelation α := { r := sizeofMeasure α, wf := sizeofMeasureWf α } namespace Prod open WellFounded section variables {α : Type u} {β : Type v} variable (ra : α → α → Prop) variable (rb : β → β → Prop) -- Lexicographical order based on ra and rb inductive Lex : α × β → α × β → Prop | left {a₁} (b₁) {a₂} (b₂) (h : ra a₁ a₂) : Lex (a₁, b₁) (a₂, b₂) | right (a) {b₁ b₂} (h : rb b₁ b₂) : Lex (a, b₁) (a, b₂) -- relational product based on ra and rb inductive Rprod : α × β → α × β → Prop | intro {a₁ b₁ a₂ b₂} (h₁ : ra a₁ a₂) (h₂ : rb b₁ b₂) : Rprod (a₁, b₁) (a₂, b₂) end section variables {α : Type u} {β : Type v} variables {ra : α → α → Prop} {rb : β → β → Prop} def lexAccessible (aca : (a : α) → Acc ra a) (acb : (b : β) → Acc rb b) (a : α) (b : β) : Acc (Lex ra rb) (a, b) := by induction (aca a) generalizing b | intro xa aca iha => induction (acb b) | intro xb acb ihb => apply Acc.intro (xa, xb) intro p lt cases lt | left a₁ b₁ a₂ b₂ h => apply iha a₁ h | right a b₁ b₂ h => apply ihb b₁ h -- The lexicographical order of well founded relations is well-founded def lexWf (ha : WellFounded ra) (hb : WellFounded rb) : WellFounded (Lex ra rb) := ⟨fun (a, b) => lexAccessible (WellFounded.apply ha) (WellFounded.apply hb) a b⟩ -- relational product is a Subrelation of the Lex def rprodSubLex (a : α × β) (b : α × β) (h : Rprod ra rb a b) : Lex ra rb a b := by cases h | intro a₁ b₁ a₂ b₂ h₁ h₂ => exact Lex.left b₁ b₂ h₁ -- The relational product of well founded relations is well-founded def rprodWf (ha : WellFounded ra) (hb : WellFounded rb) : WellFounded (Rprod ra rb) := by apply Subrelation.wf (r := Lex ra rb) (h₂ := lexWf ha hb) intro a b h exact rprodSubLex a b h end instance {α : Type u} {β : Type v} [s₁ : WellFoundedRelation α] [s₂ : WellFoundedRelation β] : WellFoundedRelation (α × β) := { r := Lex s₁.r s₂.r, wf := lexWf s₁.wf s₂.wf } end Prod namespace PSigma section variables {α : Sort u} {β : α → Sort v} variable (r : α → α → Prop) variable (s : ∀ a, β a → β a → Prop) -- Lexicographical order based on r and s inductive Lex : PSigma β → PSigma β → Prop | left : ∀ {a₁ : α} (b₁ : β a₁) {a₂ : α} (b₂ : β a₂), r a₁ a₂ → Lex ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ | right : ∀ (a : α) {b₁ b₂ : β a}, s a b₁ b₂ → Lex ⟨a, b₁⟩ ⟨a, b₂⟩ end section variables {α : Sort u} {β : α → Sort v} variables {r : α → α → Prop} {s : ∀ (a : α), β a → β a → Prop} def lexAccessible {a} (aca : Acc r a) (acb : (a : α) → WellFounded (s a)) (b : β a) : Acc (Lex r s) ⟨a, b⟩ := by induction aca generalizing b | intro xa aca iha => induction (WellFounded.apply (acb xa) b) | intro xb acb ihb => apply Acc.intro intro p lt cases lt | left => apply iha; assumption | right => apply ihb; assumption -- The lexicographical order of well founded relations is well-founded def lexWf (ha : WellFounded r) (hb : (x : α) → WellFounded (s x)) : WellFounded (Lex r s) := WellFounded.intro fun ⟨a, b⟩ => lexAccessible (WellFounded.apply ha a) hb b end section variables {α : Sort u} {β : Sort v} def lexNdep (r : α → α → Prop) (s : β → β → Prop) := Lex r (fun a => s) def lexNdepWf {r : α → α → Prop} {s : β → β → Prop} (ha : WellFounded r) (hb : WellFounded s) : WellFounded (lexNdep r s) := WellFounded.intro $ fun ⟨a, b⟩ => lexAccessible (WellFounded.apply ha a) (fun x => hb) b end section variables {α : Sort u} {β : Sort v} -- Reverse lexicographical order based on r and s inductive RevLex (r : α → α → Prop) (s : β → β → Prop) : @PSigma α (fun a => β) → @PSigma α (fun a => β) → Prop | left : {a₁ a₂ : α} → (b : β) → r a₁ a₂ → RevLex r s ⟨a₁, b⟩ ⟨a₂, b⟩ | right : (a₁ : α) → {b₁ : β} → (a₂ : α) → {b₂ : β} → s b₁ b₂ → RevLex r s ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ end section open WellFounded variables {α : Sort u} {β : Sort v} variables {r : α → α → Prop} {s : β → β → Prop} def revLexAccessible {b} (acb : Acc s b) (aca : (a : α) → Acc r a): (a : α) → Acc (RevLex r s) ⟨a, b⟩ := by induction acb | intro xb acb ihb => intro a induction (aca a) | intro xa aca iha => apply Acc.intro intro p lt cases lt | left => apply iha; assumption | right => apply ihb; assumption def revLexWf (ha : WellFounded r) (hb : WellFounded s) : WellFounded (RevLex r s) := WellFounded.intro $ fun ⟨a, b⟩ => revLexAccessible (apply hb b) (WellFounded.apply ha) a end section def skipLeft (α : Type u) {β : Type v} (s : β → β → Prop) : @PSigma α (fun a => β) → @PSigma α (fun a => β) → Prop := RevLex emptyRelation s def skipLeftWf (α : Type u) {β : Type v} {s : β → β → Prop} (hb : WellFounded s) : WellFounded (skipLeft α s) := revLexWf emptyWf hb def mkSkipLeft {α : Type u} {β : Type v} {b₁ b₂ : β} {s : β → β → Prop} (a₁ a₂ : α) (h : s b₁ b₂) : skipLeft α s ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ := RevLex.right _ _ h end instance WellFoundedRelation {α : Type u} {β : α → Type v} [s₁ : WellFoundedRelation α] [s₂ : ∀ a, WellFoundedRelation (β a)] : WellFoundedRelation (PSigma β) := { r := Lex s₁.r (fun a => (s₂ a).r), wf := lexWf s₁.wf (fun a => (s₂ a).wf) } end PSigma
d923004a02cc4f3d92349f5c3aebaa3b86a8fbb9
367134ba5a65885e863bdc4507601606690974c1
/src/data/multiset/powerset.lean
274c54058faf0fa883dafb5795702d9167ddaec8
[ "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
9,243
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.multiset.basic /-! # The powerset of a multiset -/ namespace multiset open list variables {α : Type*} /-! ### powerset -/ /-- A helper function for the powerset of a multiset. Given a list `l`, returns a list of sublists of `l` (using `sublists_aux`), as multisets. -/ def powerset_aux (l : list α) : list (multiset α) := 0 :: sublists_aux l (λ x y, x :: y) theorem powerset_aux_eq_map_coe {l : list α} : powerset_aux l = (sublists l).map coe := by simp [powerset_aux, sublists]; rw [← show @sublists_aux₁ α (multiset α) l (λ x, [↑x]) = sublists_aux l (λ x, list.cons ↑x), from sublists_aux₁_eq_sublists_aux _ _, sublists_aux_cons_eq_sublists_aux₁, ← bind_ret_eq_map, sublists_aux₁_bind]; refl @[simp] theorem mem_powerset_aux {l : list α} {s} : s ∈ powerset_aux l ↔ s ≤ ↑l := quotient.induction_on s $ by simp [powerset_aux_eq_map_coe, subperm, and.comm] /-- Helper function for the powerset of a multiset. Given a list `l`, returns a list of sublists of `l` (using `sublists'`), as multisets. -/ def powerset_aux' (l : list α) : list (multiset α) := (sublists' l).map coe theorem powerset_aux_perm_powerset_aux' {l : list α} : powerset_aux l ~ powerset_aux' l := by rw powerset_aux_eq_map_coe; exact (sublists_perm_sublists' _).map _ @[simp] theorem powerset_aux'_nil : powerset_aux' (@nil α) = [0] := rfl @[simp] theorem powerset_aux'_cons (a : α) (l : list α) : powerset_aux' (a::l) = powerset_aux' l ++ list.map (cons a) (powerset_aux' l) := by simp [powerset_aux']; refl theorem powerset_aux'_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) : powerset_aux' l₁ ~ powerset_aux' l₂ := begin induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp}, { simp, exact IH.append (IH.map _) }, { simp, apply perm.append_left, rw [← append_assoc, ← append_assoc, (by funext s; simp [cons_swap] : cons b ∘ cons a = cons a ∘ cons b)], exact perm_append_comm.append_right _ }, { exact IH₁.trans IH₂ } end theorem powerset_aux_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) : powerset_aux l₁ ~ powerset_aux l₂ := powerset_aux_perm_powerset_aux'.trans $ (powerset_aux'_perm p).trans powerset_aux_perm_powerset_aux'.symm /-- The power set of a multiset. -/ def powerset (s : multiset α) : multiset (multiset α) := quot.lift_on s (λ l, (powerset_aux l : multiset (multiset α))) (λ l₁ l₂ h, quot.sound (powerset_aux_perm h)) theorem powerset_coe (l : list α) : @powerset α l = ((sublists l).map coe : list (multiset α)) := congr_arg coe powerset_aux_eq_map_coe @[simp] theorem powerset_coe' (l : list α) : @powerset α l = ((sublists' l).map coe : list (multiset α)) := quot.sound powerset_aux_perm_powerset_aux' @[simp] theorem powerset_zero : @powerset α 0 = 0 ::ₘ 0 := rfl @[simp] theorem powerset_cons (a : α) (s) : powerset (a ::ₘ s) = powerset s + map (cons a) (powerset s) := quotient.induction_on s $ λ l, by simp; refl @[simp] theorem mem_powerset {s t : multiset α} : s ∈ powerset t ↔ s ≤ t := quotient.induction_on₂ s t $ by simp [subperm, and.comm] theorem map_single_le_powerset (s : multiset α) : s.map (λ a, a ::ₘ 0) ≤ powerset s := quotient.induction_on s $ λ l, begin simp [powerset_coe], show l.map (coe ∘ list.ret) <+~ (sublists l).map coe, rw ← list.map_map, exact ((map_ret_sublist_sublists _).map _).subperm end @[simp] theorem card_powerset (s : multiset α) : card (powerset s) = 2 ^ card s := quotient.induction_on s $ by simp theorem revzip_powerset_aux {l : list α} ⦃x⦄ (h : x ∈ revzip (powerset_aux l)) : x.1 + x.2 = ↑l := begin rw [revzip, powerset_aux_eq_map_coe, ← map_reverse, zip_map, ← revzip] at h, simp at h, rcases h with ⟨l₁, l₂, h, rfl, rfl⟩, exact quot.sound (revzip_sublists _ _ _ h) end theorem revzip_powerset_aux' {l : list α} ⦃x⦄ (h : x ∈ revzip (powerset_aux' l)) : x.1 + x.2 = ↑l := begin rw [revzip, powerset_aux', ← map_reverse, zip_map, ← revzip] at h, simp at h, rcases h with ⟨l₁, l₂, h, rfl, rfl⟩, exact quot.sound (revzip_sublists' _ _ _ h) end theorem revzip_powerset_aux_lemma [decidable_eq α] (l : list α) {l' : list (multiset α)} (H : ∀ ⦃x : _ × _⦄, x ∈ revzip l' → x.1 + x.2 = ↑l) : revzip l' = l'.map (λ x, (x, ↑l - x)) := begin have : forall₂ (λ (p : multiset α × multiset α) (s : multiset α), p = (s, ↑l - s)) (revzip l') ((revzip l').map prod.fst), { rw forall₂_map_right_iff, apply forall₂_same, rintro ⟨s, t⟩ h, dsimp, rw [← H h, add_sub_cancel_left] }, rw [← forall₂_eq_eq_eq, forall₂_map_right_iff], simpa end theorem revzip_powerset_aux_perm_aux' {l : list α} : revzip (powerset_aux l) ~ revzip (powerset_aux' l) := begin haveI := classical.dec_eq α, rw [revzip_powerset_aux_lemma l revzip_powerset_aux, revzip_powerset_aux_lemma l revzip_powerset_aux'], exact powerset_aux_perm_powerset_aux'.map _ end theorem revzip_powerset_aux_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) : revzip (powerset_aux l₁) ~ revzip (powerset_aux l₂) := begin haveI := classical.dec_eq α, simp [λ l:list α, revzip_powerset_aux_lemma l revzip_powerset_aux, coe_eq_coe.2 p], exact (powerset_aux_perm p).map _ end /-! ### powerset_len -/ /-- Helper function for `powerset_len`. Given a list `l`, `powerset_len_aux n l` is the list of sublists of length `n`, as multisets. -/ def powerset_len_aux (n : ℕ) (l : list α) : list (multiset α) := sublists_len_aux n l coe [] theorem powerset_len_aux_eq_map_coe {n} {l : list α} : powerset_len_aux n l = (sublists_len n l).map coe := by rw [powerset_len_aux, sublists_len_aux_eq, append_nil] @[simp] theorem mem_powerset_len_aux {n} {l : list α} {s} : s ∈ powerset_len_aux n l ↔ s ≤ ↑l ∧ card s = n := quotient.induction_on s $ by simp [powerset_len_aux_eq_map_coe, subperm]; exact λ l₁, ⟨λ ⟨l₂, ⟨s, e⟩, p⟩, ⟨⟨_, p, s⟩, p.symm.length_eq.trans e⟩, λ ⟨⟨l₂, p, s⟩, e⟩, ⟨_, ⟨s, p.length_eq.trans e⟩, p⟩⟩ @[simp] theorem powerset_len_aux_zero (l : list α) : powerset_len_aux 0 l = [0] := by simp [powerset_len_aux_eq_map_coe] @[simp] theorem powerset_len_aux_nil (n : ℕ) : powerset_len_aux (n+1) (@nil α) = [] := rfl @[simp] theorem powerset_len_aux_cons (n : ℕ) (a : α) (l : list α) : powerset_len_aux (n+1) (a::l) = powerset_len_aux (n+1) l ++ list.map (cons a) (powerset_len_aux n l) := by simp [powerset_len_aux_eq_map_coe]; refl theorem powerset_len_aux_perm {n} {l₁ l₂ : list α} (p : l₁ ~ l₂) : powerset_len_aux n l₁ ~ powerset_len_aux n l₂ := begin induction n with n IHn generalizing l₁ l₂, {simp}, induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {refl}, { simp, exact IH.append ((IHn p).map _) }, { simp, apply perm.append_left, cases n, {simp, apply perm.swap}, simp, rw [← append_assoc, ← append_assoc, (by funext s; simp [cons_swap] : cons b ∘ cons a = cons a ∘ cons b)], exact perm_append_comm.append_right _ }, { exact IH₁.trans IH₂ } end /-- `powerset_len n s` is the multiset of all submultisets of `s` of length `n`. -/ def powerset_len (n : ℕ) (s : multiset α) : multiset (multiset α) := quot.lift_on s (λ l, (powerset_len_aux n l : multiset (multiset α))) (λ l₁ l₂ h, quot.sound (powerset_len_aux_perm h)) theorem powerset_len_coe' (n) (l : list α) : @powerset_len α n l = powerset_len_aux n l := rfl theorem powerset_len_coe (n) (l : list α) : @powerset_len α n l = ((sublists_len n l).map coe : list (multiset α)) := congr_arg coe powerset_len_aux_eq_map_coe @[simp] theorem powerset_len_zero_left (s : multiset α) : powerset_len 0 s = 0 ::ₘ 0 := quotient.induction_on s $ λ l, by simp [powerset_len_coe']; refl @[simp] theorem powerset_len_zero_right (n : ℕ) : @powerset_len α (n + 1) 0 = 0 := rfl @[simp] theorem powerset_len_cons (n : ℕ) (a : α) (s) : powerset_len (n + 1) (a ::ₘ s) = powerset_len (n + 1) s + map (cons a) (powerset_len n s) := quotient.induction_on s $ λ l, by simp [powerset_len_coe']; refl @[simp] theorem mem_powerset_len {n : ℕ} {s t : multiset α} : s ∈ powerset_len n t ↔ s ≤ t ∧ card s = n := quotient.induction_on t $ λ l, by simp [powerset_len_coe'] @[simp] theorem card_powerset_len (n : ℕ) (s : multiset α) : card (powerset_len n s) = nat.choose (card s) n := quotient.induction_on s $ by simp [powerset_len_coe] theorem powerset_len_le_powerset (n : ℕ) (s : multiset α) : powerset_len n s ≤ powerset s := quotient.induction_on s $ λ l, by simp [powerset_len_coe]; exact ((sublists_len_sublist_sublists' _ _).map _).subperm theorem powerset_len_mono (n : ℕ) {s t : multiset α} (h : s ≤ t) : powerset_len n s ≤ powerset_len n t := le_induction_on h $ λ l₁ l₂ h, by simp [powerset_len_coe]; exact ((sublists_len_sublist_of_sublist _ h).map _).subperm end multiset
483ff2b167ead3f7a3728522c929da3519ed4d18
491068d2ad28831e7dade8d6dff871c3e49d9431
/library/init/priority.lean
27d67112923b10de2ad7cf02093d5ac5d330e51b
[ "Apache-2.0" ]
permissive
davidmueller13/lean
65a3ed141b4088cd0a268e4de80eb6778b21a0e9
c626e2e3c6f3771e07c32e82ee5b9e030de5b050
refs/heads/master
1,611,278,313,401
1,444,021,177,000
1,444,021,177,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
292
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.datatypes definition std.priority.default : num := 1000 definition std.priority.max : num := 4294967295
1907af7a53449d0edf834d8a39ad11179450886b
ed27983dd289b3bcad416f0b1927105d6ef19db8
/src/inClassNotes/langs/bool_exprs/bool_expr.lean
2091b32badc769a7c4c9036127157404dadab786
[]
no_license
liuxin-James/complogic-s21
0d55b76dbe25024473d31d98b5b83655c365f811
13e03e0114626643b44015c654151fb651603486
refs/heads/master
1,681,109,264,463
1,618,848,261,000
1,618,848,261,000
337,599,491
0
0
null
1,613,141,619,000
1,612,925,555,000
null
UTF-8
Lean
false
false
1,366
lean
/- true, false, true && false, (true && false) && true -/ inductive bool_expr : Type | lit_expr : bool → bool_expr | and_expr : bool_expr → bool_expr → bool_expr | or_expr : bool_expr → bool_expr → bool_expr | not_expr : bool_expr → bool_expr open bool_expr notation e1 && e2 := and_expr e1 e2 notation e1 || e2 := or_expr e1 e2 notation ¬ e1 := not_expr e1 notation `[` b `]` := lit_expr b def true_expr : bool_expr := [tt] def false_expr : bool_expr := [ff] def e3 := and_expr (lit_expr tt) [ff] def e4 := and_expr e3 [tt] def e3' := [tt] || [ff] def e4' := e3' || [tt] def e3'' := ¬ [ff] def e4'' := ¬ [tt] -- That's the syntax -- Now for the semantics def bool_eval : bool_expr → bool | (lit_expr b) := b | (and_expr e1 e2) := band (bool_eval e1) (bool_eval e2) | (or_expr e1 e2) := bor (bool_eval e1) (bool_eval e2) | (not_expr e1) := bnot (bool_eval e1) #eval bool_eval e4 #eval bool_eval e4' #eval bool_eval e4'' #eval bool_eval e3'' -- assert and prove the proposition that for *any* Boolean expressions, e1 and e2, in LLBE, e1 && e2 "means" the same thing as e2 && e1 example : ∀ (e1 e2: bool_expr), bool_eval (e1 && e2) = bool_eval (e2 && e1) := begin assume e1 e2, simp [bool_eval], cases (bool_eval e1), cases (bool_eval e2), apply rfl, apply rfl, cases (bool_eval e2), repeat {apply rfl}, end
ad3e9167d804fb4e081390e778d5cfa195c78b4d
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/stage0/src/Std/Data/AssocList.lean
25003c7963e713dd0ee4d8ab524622bfbff05c19
[ "Apache-2.0" ]
permissive
collares/lean4
861a9269c4592bce49b71059e232ff0bfe4594cc
52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee
refs/heads/master
1,691,419,031,324
1,618,678,138,000
1,618,678,138,000
358,989,750
0
0
Apache-2.0
1,618,696,333,000
1,618,696,333,000
null
UTF-8
Lean
false
false
3,351
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ universes u v w w' namespace Std /- List-like type to avoid extra level of indirection -/ inductive AssocList (α : Type u) (β : Type v) where | nil : AssocList α β | cons (key : α) (value : β) (tail : AssocList α β) : AssocList α β deriving Inhabited namespace AssocList variable {α : Type u} {β : Type v} {δ : Type w} {m : Type w → Type w} [Monad m] abbrev empty : AssocList α β := nil instance : EmptyCollection (AssocList α β) := ⟨empty⟩ abbrev insert (m : AssocList α β) (k : α) (v : β) : AssocList α β := m.cons k v def isEmpty : AssocList α β → Bool | nil => true | _ => false @[specialize] def foldlM (f : δ → α → β → m δ) : (init : δ) → AssocList α β → m δ | d, nil => pure d | d, cons a b es => do let d ← f d a b foldlM f d es @[inline] def foldl (f : δ → α → β → δ) (init : δ) (as : AssocList α β) : δ := Id.run (foldlM f init as) @[specialize] def forM (f : α → β → m PUnit) : AssocList α β → m PUnit | nil => pure ⟨⟩ | cons a b es => do f a b; forM f es def mapKey (f : α → δ) : AssocList α β → AssocList δ β | nil => nil | cons k v t => cons (f k) v (mapKey f t) def mapVal (f : β → δ) : AssocList α β → AssocList α δ | nil => nil | cons k v t => cons k (f v) (mapVal f t) def findEntry? [BEq α] (a : α) : AssocList α β → Option (α × β) | nil => none | cons k v es => match k == a with | true => some (k, v) | false => findEntry? a es def find? [BEq α] (a : α) : AssocList α β → Option β | nil => none | cons k v es => match k == a with | true => some v | false => find? a es def contains [BEq α] (a : α) : AssocList α β → Bool | nil => false | cons k v es => k == a || contains a es def replace [BEq α] (a : α) (b : β) : AssocList α β → AssocList α β | nil => nil | cons k v es => match k == a with | true => cons a b es | false => cons k v (replace a b es) def erase [BEq α] (a : α) : AssocList α β → AssocList α β | nil => nil | cons k v es => match k == a with | true => es | false => cons k v (erase a es) def any (p : α → β → Bool) : AssocList α β → Bool | nil => false | cons k v es => p k v || any p es def all (p : α → β → Bool) : AssocList α β → Bool | nil => true | cons k v es => p k v && all p es @[inline] protected def forIn {α : Type u} {β : Type v} {δ : Type w} {m : Type w → Type w'} [Monad m] (as : AssocList α β) (init : δ) (f : (α × β) → δ → m (ForInStep δ)) : m δ := let rec @[specialize] loop | d, nil => pure d | d, cons k v es => do match (← f (k, v) d) with | ForInStep.done d => pure d | ForInStep.yield d => loop d es loop init as instance : ForIn m (AssocList α β) (α × β) where forIn := AssocList.forIn end Std.AssocList def List.toAssocList {α : Type u} {β : Type v} : List (α × β) → Std.AssocList α β | [] => Std.AssocList.nil | (a,b) :: es => Std.AssocList.cons a b (toAssocList es)
8ebf201458abbb990e313ac04f214232681e472a
6df8d5ae3acf20ad0d7f0247d2cee1957ef96df1
/notes/12.5.19.lean
3f54e649dec2570026245653a9f58572119ad47a
[]
no_license
derekjohnsonva/CS2102
8ed45daa6658e6121bac0f6691eac6147d08246d
b3f507d4be824a2511838a1054d04fc9aef3304c
refs/heads/master
1,648,529,162,527
1,578,851,859,000
1,578,851,859,000
233,433,207
0
0
null
null
null
null
UTF-8
Lean
false
false
1,064
lean
axiom person : Type axiom Likes : person → person → Prop -- If there is a person everyone likes, then everyone likes someone example: (∃ (p : person), ∀(q : person), Likes q p) → (∀(p : person), ∃(q : person), Likes p q) := λ h, λ p, match h with | (exists.intro w pf) := exists.intro w (pf p) end -- The proof of a existentially qualified proposition is a pair example : (∃ (p : person), ∀(q : person), Likes q p) → (∀(p : person), ∃(q : person), Likes p q) := begin intros, cases a with w pf, exact exists.intro w (pf p), end def even : nat → Prop | n := n % 2 = 0 example : exists (n : nat), even n := begin apply exists.intro 2 _, unfold even, exact eq.refl 0, end example : ∀ (n : ℕ), (n = 0) ∨ (n ≠ 0) := λ n, match n with | nat.zero := or.inl (eq.refl 0) | (nat.succ n') := or.inr (λ h, match h with end) end
5e76c83fadfcdc18e3d288887b2fc5b4a3f1ba10
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/json.lean
8456b078e32a27c5e2ecd2e9de357c609dd519c2
[ "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
2,021
lean
import Lean.Data.Json.Parser import Lean.Data.Json.Printer import Lean.Data.Json import Lean def test (s : String) : String := match Lean.Json.parse s with | Except.ok res => toString res | Except.error err => err #eval test "null" #eval test "false" #eval test "true" #eval test "123.456e-7" #eval test "123.456e+7" #eval test "-0.01e8" #eval test "\"\"" #eval test "\"abc\"" #eval test "[true, 123, \"foo\", []]" #eval test "{\"a\": 1.2, \"b\": \"foo\", \"c\": null, \"d\": {\"foo\": \"bar\"}, \"e\": [{}]}" #eval test "[false_]" #eval test "[" #eval test "]" #eval test "{" #eval test "\"" #eval test "1." #eval test "{foo: 1}" #eval test " " #eval toString (Lean.Json.num ⟨20, 1⟩) #eval toString (Lean.Json.num ⟨-20, 1⟩) #eval toString (Lean.Json.num 0.1) #eval toString (Lean.Json.num <| -0.1) #eval toString (Lean.Json.num <| -0.01e8) #eval toString (Lean.Json.num <| 123.456e-7) #eval 123.456e-7 == Lean.JsonNumber.toFloat 123.456e-7 #eval -123.456e-7 == Lean.JsonNumber.toFloat (-123.456e-7) #eval 123.456e20 == Lean.JsonNumber.toFloat 123.456e20 #eval 0.0 == Lean.JsonNumber.toFloat 0 open Lean Json def floatRoundtrip (x : Float) : CoreM Unit := do let j := x |> toJson let y ← j |> fromJson? (α := Float) |> ofExcept dbg_trace "{y}" if y.isNaN && x.isNaN then -- [note] NaN ≠ NaN return () if y != x then throwError "failure {x} → {j} → {y}" return () #eval floatRoundtrip 0.0 #eval floatRoundtrip (-0.0) #eval floatRoundtrip 1.0 #eval floatRoundtrip (-1.0) #eval floatRoundtrip (1e100) #eval floatRoundtrip (123456789e-6) #eval floatRoundtrip (0.0 / 0.0) #eval floatRoundtrip (1.0 / 0.0) #eval floatRoundtrip (-1.0 / 0.0) structure Test1 where hello : String cheese? : Option Nat deriving ToJson, FromJson, Repr structure Test2 where jam: Test1 deriving ToJson, FromJson, Repr #eval fromJson? (α := Test2) <| Json.mkObj [("jam", Json.mkObj [("hello", "world")])] #eval fromJson? (α := Test2) <| Json.mkObj [("jam", Json.mkObj [("hello", 4)])]
5737d7f8de8a7924d0aae018ac252e0bb0a662ab
9dc8cecdf3c4634764a18254e94d43da07142918
/src/measure_theory/integral/average.lean
1e61e65b5d9cd49f93dd5f882da36edda9c9f97c
[ "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
8,015
lean
/- Copyright (c) 2022 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import measure_theory.integral.set_integral /-! # Integral average of a function In this file we define `measure_theory.average μ f` (notation: `⨍ x, f x ∂μ`) to be the average value of `f` with respect to measure `μ`. It is defined as `∫ x, f x ∂((μ univ)⁻¹ • μ)`, so it is equal to zero if `f` is not integrable or if `μ` is an infinite measure. If `μ` is a probability measure, then the average of any function is equal to its integral. For the average on a set, we use `⨍ x in s, f x ∂μ` (notation for `⨍ x, f x ∂(μ.restrict s)`). For average w.r.t. the volume, one can omit `∂volume`. ## Implementation notes The average is defined as an integral over `(μ univ)⁻¹ • μ` so that all theorems about Bochner integrals work for the average without modifications. For theorems that require integrability of a function, we provide a convenience lemma `measure_theory.integrable.to_average`. ## Tags integral, center mass, average value -/ open measure_theory measure_theory.measure metric set filter topological_space function open_locale topological_space big_operators ennreal convex variables {α E F : Type*} {m0 : measurable_space α} [normed_add_comm_group E] [normed_space ℝ E] [complete_space E] [normed_add_comm_group F] [normed_space ℝ F] [complete_space F] {μ : measure α} {s : set E} /-! ### Average value of a function w.r.t. a measure The average value of a function `f` w.r.t. a measure `μ` (notation: `⨍ x, f x ∂μ`) is defined as `(μ univ).to_real⁻¹ • ∫ x, f x ∂μ`, so it is equal to zero if `f` is not integrable or if `μ` is an infinite measure. If `μ` is a probability measure, then the average of any function is equal to its integral. -/ namespace measure_theory variable (μ) include m0 /-- Average value of a function `f` w.r.t. a measure `μ`, notation: `⨍ x, f x ∂μ`. It is defined as `(μ univ).to_real⁻¹ • ∫ x, f x ∂μ`, so it is equal to zero if `f` is not integrable or if `μ` is an infinite measure. If `μ` is a probability measure, then the average of any function is equal to its integral. For the average on a set, use `⨍ x in s, f x ∂μ` (defined as `⨍ x, f x ∂(μ.restrict s)`). For average w.r.t. the volume, one can omit `∂volume`. -/ noncomputable def average (f : α → E) := ∫ x, f x ∂((μ univ)⁻¹ • μ) notation `⨍` binders `, ` r:(scoped:60 f, f) ` ∂` μ:70 := average μ r notation `⨍` binders `, ` r:(scoped:60 f, average volume f) := r notation `⨍` binders ` in ` s `, ` r:(scoped:60 f, f) ` ∂` μ:70 := average (measure.restrict μ s) r notation `⨍` binders ` in ` s `, ` r:(scoped:60 f, average (measure.restrict volume s) f) := r @[simp] lemma average_zero : ⨍ x, (0 : E) ∂μ = 0 := by rw [average, integral_zero] @[simp] lemma average_zero_measure (f : α → E) : ⨍ x, f x ∂(0 : measure α) = 0 := by rw [average, smul_zero, integral_zero_measure] @[simp] lemma average_neg (f : α → E) : ⨍ x, -f x ∂μ = -⨍ x, f x ∂μ := integral_neg f lemma average_def (f : α → E) : ⨍ x, f x ∂μ = ∫ x, f x ∂((μ univ)⁻¹ • μ) := rfl lemma average_def' (f : α → E) : ⨍ x, f x ∂μ = (μ univ).to_real⁻¹ • ∫ x, f x ∂μ := by rw [average_def, integral_smul_measure, ennreal.to_real_inv] lemma average_eq_integral [is_probability_measure μ] (f : α → E) : ⨍ x, f x ∂μ = ∫ x, f x ∂μ := by rw [average, measure_univ, ennreal.inv_one, one_smul] @[simp] lemma measure_smul_average [is_finite_measure μ] (f : α → E) : (μ univ).to_real • ⨍ x, f x ∂μ = ∫ x, f x ∂μ := begin cases eq_or_ne μ 0 with hμ hμ, { rw [hμ, integral_zero_measure, average_zero_measure, smul_zero] }, { rw [average_def', smul_inv_smul₀], refine (ennreal.to_real_pos _ $ measure_ne_top _ _).ne', rwa [ne.def, measure_univ_eq_zero] } end lemma set_average_eq (f : α → E) (s : set α) : ⨍ x in s, f x ∂μ = (μ s).to_real⁻¹ • ∫ x in s, f x ∂μ := by rw [average_def', restrict_apply_univ] variable {μ} lemma average_congr {f g : α → E} (h : f =ᵐ[μ] g) : ⨍ x, f x ∂μ = ⨍ x, g x ∂μ := by simp only [average_def', integral_congr_ae h] lemma average_add_measure [is_finite_measure μ] {ν : measure α} [is_finite_measure ν] {f : α → E} (hμ : integrable f μ) (hν : integrable f ν) : ⨍ x, f x ∂(μ + ν) = ((μ univ).to_real / ((μ univ).to_real + (ν univ).to_real)) • ⨍ x, f x ∂μ + ((ν univ).to_real / ((μ univ).to_real + (ν univ).to_real)) • ⨍ x, f x ∂ν := begin simp only [div_eq_inv_mul, mul_smul, measure_smul_average, ← smul_add, ← integral_add_measure hμ hν, ← ennreal.to_real_add (measure_ne_top μ _) (measure_ne_top ν _)], rw [average_def', measure.add_apply] end lemma average_pair {f : α → E} {g : α → F} (hfi : integrable f μ) (hgi : integrable g μ) : ⨍ x, (f x, g x) ∂μ = (⨍ x, f x ∂μ, ⨍ x, g x ∂μ) := integral_pair hfi.to_average hgi.to_average lemma measure_smul_set_average (f : α → E) {s : set α} (h : μ s ≠ ∞) : (μ s).to_real • ⨍ x in s, f x ∂μ = ∫ x in s, f x ∂μ := by { haveI := fact.mk h.lt_top, rw [← measure_smul_average, restrict_apply_univ] } lemma average_union {f : α → E} {s t : set α} (hd : ae_disjoint μ s t) (ht : null_measurable_set t μ) (hsμ : μ s ≠ ∞) (htμ : μ t ≠ ∞) (hfs : integrable_on f s μ) (hft : integrable_on f t μ) : ⨍ x in s ∪ t, f x ∂μ = ((μ s).to_real / ((μ s).to_real + (μ t).to_real)) • ⨍ x in s, f x ∂μ + ((μ t).to_real / ((μ s).to_real + (μ t).to_real)) • ⨍ x in t, f x ∂μ := begin haveI := fact.mk hsμ.lt_top, haveI := fact.mk htμ.lt_top, rw [restrict_union₀ hd ht, average_add_measure hfs hft, restrict_apply_univ, restrict_apply_univ] end lemma average_union_mem_open_segment {f : α → E} {s t : set α} (hd : ae_disjoint μ s t) (ht : null_measurable_set t μ) (hs₀ : μ s ≠ 0) (ht₀ : μ t ≠ 0) (hsμ : μ s ≠ ∞) (htμ : μ t ≠ ∞) (hfs : integrable_on f s μ) (hft : integrable_on f t μ) : ⨍ x in s ∪ t, f x ∂μ ∈ open_segment ℝ (⨍ x in s, f x ∂μ) (⨍ x in t, f x ∂μ) := begin replace hs₀ : 0 < (μ s).to_real, from ennreal.to_real_pos hs₀ hsμ, replace ht₀ : 0 < (μ t).to_real, from ennreal.to_real_pos ht₀ htμ, refine mem_open_segment_iff_div.mpr ⟨(μ s).to_real, (μ t).to_real, hs₀, ht₀, (average_union hd ht hsμ htμ hfs hft).symm⟩ end lemma average_union_mem_segment {f : α → E} {s t : set α} (hd : ae_disjoint μ s t) (ht : null_measurable_set t μ) (hsμ : μ s ≠ ∞) (htμ : μ t ≠ ∞) (hfs : integrable_on f s μ) (hft : integrable_on f t μ) : ⨍ x in s ∪ t, f x ∂μ ∈ [⨍ x in s, f x ∂μ -[ℝ] ⨍ x in t, f x ∂μ] := begin by_cases hse : μ s = 0, { rw ← ae_eq_empty at hse, rw [restrict_congr_set (hse.union eventually_eq.rfl), empty_union], exact right_mem_segment _ _ _ }, { refine mem_segment_iff_div.mpr ⟨(μ s).to_real, (μ t).to_real, ennreal.to_real_nonneg, ennreal.to_real_nonneg, _, (average_union hd ht hsμ htμ hfs hft).symm⟩, calc 0 < (μ s).to_real : ennreal.to_real_pos hse hsμ ... ≤ _ : le_add_of_nonneg_right ennreal.to_real_nonneg } end lemma average_mem_open_segment_compl_self [is_finite_measure μ] {f : α → E} {s : set α} (hs : null_measurable_set s μ) (hs₀ : μ s ≠ 0) (hsc₀ : μ sᶜ ≠ 0) (hfi : integrable f μ) : ⨍ x, f x ∂μ ∈ open_segment ℝ (⨍ x in s, f x ∂μ) (⨍ x in sᶜ, f x ∂μ) := by simpa only [union_compl_self, restrict_univ] using average_union_mem_open_segment ae_disjoint_compl_right hs.compl hs₀ hsc₀ (measure_ne_top _ _) (measure_ne_top _ _) hfi.integrable_on hfi.integrable_on end measure_theory
8003a123fa316b86690d046c11d269e53a785339
9dc8cecdf3c4634764a18254e94d43da07142918
/src/group_theory/group_action/pi.lean
09a98569c69536b0629d0d69c4f4e747649f21d3
[ "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
8,311
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Patrick Massot -/ import algebra.group.pi import group_theory.group_action.defs /-! # Pi instances for multiplicative actions This file defines instances for mul_action and related structures on Pi types. ## See also * `group_theory.group_action.option` * `group_theory.group_action.prod` * `group_theory.group_action.sigma` * `group_theory.group_action.sum` -/ universes u v w variable {I : Type u} -- The indexing type variable {f : I → Type v} -- The family of types already equipped with instances variables (x y : Π i, f i) (i : I) namespace pi @[to_additive pi.has_vadd'] instance has_smul' {g : I → Type*} [Π i, has_smul (f i) (g i)] : has_smul (Π i, f i) (Π i : I, g i) := ⟨λ s x, λ i, (s i) • (x i)⟩ @[simp, to_additive] lemma smul_apply' {g : I → Type*} [∀ i, has_smul (f i) (g i)] (s : Π i, f i) (x : Π i, g i) : (s • x) i = s i • x i := rfl instance is_scalar_tower {α β : Type*} [has_smul α β] [Π i, has_smul β $ f i] [Π i, has_smul α $ f i] [Π i, is_scalar_tower α β (f i)] : is_scalar_tower α β (Π i : I, f i) := ⟨λ x y z, funext $ λ i, smul_assoc x y (z i)⟩ instance is_scalar_tower' {g : I → Type*} {α : Type*} [Π i, has_smul α $ f i] [Π i, has_smul (f i) (g i)] [Π i, has_smul α $ g i] [Π i, is_scalar_tower α (f i) (g i)] : is_scalar_tower α (Π i : I, f i) (Π i : I, g i) := ⟨λ x y z, funext $ λ i, smul_assoc x (y i) (z i)⟩ instance is_scalar_tower'' {g : I → Type*} {h : I → Type*} [Π i, has_smul (f i) (g i)] [Π i, has_smul (g i) (h i)] [Π i, has_smul (f i) (h i)] [Π i, is_scalar_tower (f i) (g i) (h i)] : is_scalar_tower (Π i, f i) (Π i, g i) (Π i, h i) := ⟨λ x y z, funext $ λ i, smul_assoc (x i) (y i) (z i)⟩ @[to_additive] instance smul_comm_class {α β : Type*} [Π i, has_smul α $ f i] [Π i, has_smul β $ f i] [∀ i, smul_comm_class α β (f i)] : smul_comm_class α β (Π i : I, f i) := ⟨λ x y z, funext $ λ i, smul_comm x y (z i)⟩ @[to_additive] instance smul_comm_class' {g : I → Type*} {α : Type*} [Π i, has_smul α $ g i] [Π i, has_smul (f i) (g i)] [∀ i, smul_comm_class α (f i) (g i)] : smul_comm_class α (Π i : I, f i) (Π i : I, g i) := ⟨λ x y z, funext $ λ i, smul_comm x (y i) (z i)⟩ @[to_additive] instance smul_comm_class'' {g : I → Type*} {h : I → Type*} [Π i, has_smul (g i) (h i)] [Π i, has_smul (f i) (h i)] [∀ i, smul_comm_class (f i) (g i) (h i)] : smul_comm_class (Π i, f i) (Π i, g i) (Π i, h i) := ⟨λ x y z, funext $ λ i, smul_comm (x i) (y i) (z i)⟩ instance {α : Type*} [Π i, has_smul α $ f i] [Π i, has_smul αᵐᵒᵖ $ f i] [∀ i, is_central_scalar α (f i)] : is_central_scalar α (Π i, f i) := ⟨λ r m, funext $ λ i, op_smul_eq_smul _ _⟩ /-- If `f i` has a faithful scalar action for a given `i`, then so does `Π i, f i`. This is not an instance as `i` cannot be inferred. -/ @[to_additive pi.has_faithful_vadd_at "If `f i` has a faithful additive action for a given `i`, then so does `Π i, f i`. This is not an instance as `i` cannot be inferred"] lemma has_faithful_smul_at {α : Type*} [Π i, has_smul α $ f i] [Π i, nonempty (f i)] (i : I) [has_faithful_smul α (f i)] : has_faithful_smul α (Π i, f i) := ⟨λ x y h, eq_of_smul_eq_smul $ λ a : f i, begin classical, have := congr_fun (h $ function.update (λ j, classical.choice (‹Π i, nonempty (f i)› j)) i a) i, simpa using this, end⟩ @[to_additive pi.has_faithful_vadd] instance has_faithful_smul {α : Type*} [nonempty I] [Π i, has_smul α $ f i] [Π i, nonempty (f i)] [Π i, has_faithful_smul α (f i)] : has_faithful_smul α (Π i, f i) := let ⟨i⟩ := ‹nonempty I› in has_faithful_smul_at i @[to_additive] instance mul_action (α) {m : monoid α} [Π i, mul_action α $ f i] : @mul_action α (Π i : I, f i) m := { smul := (•), mul_smul := λ r s f, funext $ λ i, mul_smul _ _ _, one_smul := λ f, funext $ λ i, one_smul α _ } @[to_additive] instance mul_action' {g : I → Type*} {m : Π i, monoid (f i)} [Π i, mul_action (f i) (g i)] : @mul_action (Π i, f i) (Π i : I, g i) (@pi.monoid I f m) := { smul := (•), mul_smul := λ r s f, funext $ λ i, mul_smul _ _ _, one_smul := λ f, funext $ λ i, one_smul _ _ } instance distrib_mul_action (α) {m : monoid α} {n : ∀ i, add_monoid $ f i} [∀ i, distrib_mul_action α $ f i] : @distrib_mul_action α (Π i : I, f i) m (@pi.add_monoid I f n) := { smul_zero := λ c, funext $ λ i, smul_zero _, smul_add := λ c f g, funext $ λ i, smul_add _ _ _, ..pi.mul_action _ } instance distrib_mul_action' {g : I → Type*} {m : Π i, monoid (f i)} {n : Π i, add_monoid $ g i} [Π i, distrib_mul_action (f i) (g i)] : @distrib_mul_action (Π i, f i) (Π i : I, g i) (@pi.monoid I f m) (@pi.add_monoid I g n) := { smul_add := by { intros, ext x, apply smul_add }, smul_zero := by { intros, ext x, apply smul_zero } } lemma single_smul {α} [monoid α] [Π i, add_monoid $ f i] [Π i, distrib_mul_action α $ f i] [decidable_eq I] (i : I) (r : α) (x : f i) : single i (r • x) = r • single i x := single_op (λ i : I, ((•) r : f i → f i)) (λ j, smul_zero _) _ _ /-- A version of `pi.single_smul` for non-dependent functions. It is useful in cases Lean fails to apply `pi.single_smul`. -/ lemma single_smul' {α β} [monoid α] [add_monoid β] [distrib_mul_action α β] [decidable_eq I] (i : I) (r : α) (x : β) : single i (r • x) = r • single i x := single_smul i r x lemma single_smul₀ {g : I → Type*} [Π i, monoid_with_zero (f i)] [Π i, add_monoid (g i)] [Π i, distrib_mul_action (f i) (g i)] [decidable_eq I] (i : I) (r : f i) (x : g i) : single i (r • x) = single i r • single i x := single_op₂ (λ i : I, ((•) : f i → g i → g i)) (λ j, smul_zero _) _ _ _ instance mul_distrib_mul_action (α) {m : monoid α} {n : Π i, monoid $ f i} [Π i, mul_distrib_mul_action α $ f i] : @mul_distrib_mul_action α (Π i : I, f i) m (@pi.monoid I f n) := { smul_one := λ c, funext $ λ i, smul_one _, smul_mul := λ c f g, funext $ λ i, smul_mul' _ _ _, ..pi.mul_action _ } instance mul_distrib_mul_action' {g : I → Type*} {m : Π i, monoid (f i)} {n : Π i, monoid $ g i} [Π i, mul_distrib_mul_action (f i) (g i)] : @mul_distrib_mul_action (Π i, f i) (Π i : I, g i) (@pi.monoid I f m) (@pi.monoid I g n) := { smul_mul := by { intros, ext x, apply smul_mul' }, smul_one := by { intros, ext x, apply smul_one } } end pi namespace function /-- Non-dependent version of `pi.has_smul`. Lean gets confused by the dependent instance if this is not present. -/ @[to_additive "Non-dependent version of `pi.has_vadd`. Lean gets confused by the dependent instance if this is not present."] instance has_smul {ι R M : Type*} [has_smul R M] : has_smul R (ι → M) := pi.has_smul /-- Non-dependent version of `pi.smul_comm_class`. Lean gets confused by the dependent instance if this is not present. -/ @[to_additive "Non-dependent version of `pi.vadd_comm_class`. Lean gets confused by the dependent instance if this is not present."] instance smul_comm_class {ι α β M : Type*} [has_smul α M] [has_smul β M] [smul_comm_class α β M] : smul_comm_class α β (ι → M) := pi.smul_comm_class @[to_additive] lemma update_smul {α : Type*} [Π i, has_smul α (f i)] [decidable_eq I] (c : α) (f₁ : Π i, f i) (i : I) (x₁ : f i) : update (c • f₁) i (c • x₁) = c • update f₁ i x₁ := funext $ λ j, (apply_update (λ i, (•) c) f₁ i x₁ j).symm end function namespace set @[to_additive] lemma piecewise_smul {α : Type*} [Π i, has_smul α (f i)] (s : set I) [Π i, decidable (i ∈ s)] (c : α) (f₁ g₁ : Π i, f i) : s.piecewise (c • f₁) (c • g₁) = c • s.piecewise f₁ g₁ := s.piecewise_op _ _ (λ _, (•) c) end set section extend @[to_additive] lemma function.extend_smul {R α β γ : Type*} [has_smul R γ] (r : R) (f : α → β) (g : α → γ) (e : β → γ) : function.extend f (r • g) (r • e) = r • function.extend f g e := funext $ λ _, by convert (apply_dite ((•) r) _ _ _).symm end extend
98ee4d2572285b340541311f693bc9d994c19a17
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/t10.lean
274b28fc003bf6f43c27d6c63da05bbee2fc69c9
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
593
lean
prelude constant N : Type.{1} definition B : Type.{1} := Type.{0} constant ite : B → N → N → N constant and : B → B → B constant f : N → N constant p : B constant q : B constant x : N constant y : N constant z : N infixr ` ∧ `:25 := and notation `if` c `then` t:45 `else` e:45 := ite c t e check if p ∧ q then f x else y check if p ∧ q then q else y constant list : Type.{1} constant nil : list constant cons : N → list → list -- Non empty lists notation `[` l:(foldr `, ` (h t, cons h t) nil) `]` := l check [x, y, z, x, y, y] check [x] notation `[` `]` := nil check []
4552421c148cd5ed9c6e6bc71bdb9685abcd8548
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/ring/boolean_ring.lean
2e892c98278e827bb16ad951bae2d0e01c26cdbf
[ "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
16,075
lean
/- Copyright (c) 2021 Bryan Gin-ge Chen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bryan Gin-ge Chen, Yaël Dillies -/ import algebra.punit_instances import tactic.abel import tactic.ring import order.hom.lattice /-! # Boolean rings > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. A Boolean ring is a ring where multiplication is idempotent. They are equivalent to Boolean algebras. ## Main declarations * `boolean_ring`: a typeclass for rings where multiplication is idempotent. * `boolean_ring.to_boolean_algebra`: Turn a Boolean ring into a Boolean algebra. * `boolean_algebra.to_boolean_ring`: Turn a Boolean algebra into a Boolean ring. * `as_boolalg`: Type-synonym for the Boolean algebra associated to a Boolean ring. * `as_boolring`: Type-synonym for the Boolean ring associated to a Boolean algebra. ## Implementation notes We provide two ways of turning a Boolean algebra/ring into a Boolean ring/algebra: * Instances on the same type accessible in locales `boolean_algebra_of_boolean_ring` and `boolean_ring_of_boolean_algebra`. * Type-synonyms `as_boolalg` and `as_boolring`. At this point in time, it is not clear the first way is useful, but we keep it for educational purposes and because it is easier than dealing with `of_boolalg`/`to_boolalg`/`of_boolring`/`to_boolring` explicitly. ## Tags boolean ring, boolean algebra -/ variables {α β γ : Type*} /-- A Boolean ring is a ring where multiplication is idempotent. -/ class boolean_ring α extends ring α := (mul_self : ∀ a : α, a * a = a) section boolean_ring variables [boolean_ring α] (a b : α) instance : is_idempotent α (*) := ⟨boolean_ring.mul_self⟩ @[simp] lemma mul_self : a * a = a := boolean_ring.mul_self _ @[simp] lemma add_self : a + a = 0 := have a + a = a + a + (a + a) := calc a + a = (a+a) * (a+a) : by rw mul_self ... = a*a + a*a + (a*a + a*a) : by rw [add_mul, mul_add] ... = a + a + (a + a) : by rw mul_self, by rwa self_eq_add_left at this @[simp] lemma neg_eq : -a = a := calc -a = -a + 0 : by rw add_zero ... = -a + -a + a : by rw [←neg_add_self, add_assoc] ... = a : by rw [add_self, zero_add] lemma add_eq_zero' : a + b = 0 ↔ a = b := calc a + b = 0 ↔ a = -b : add_eq_zero_iff_eq_neg ... ↔ a = b : by rw neg_eq @[simp] lemma mul_add_mul : a*b + b*a = 0 := have a + b = a + b + (a*b + b*a) := calc a + b = (a + b) * (a + b) : by rw mul_self ... = a*a + a*b + (b*a + b*b) : by rw [add_mul, mul_add, mul_add] ... = a + a*b + (b*a + b) : by simp only [mul_self] ... = a + b + (a*b + b*a) : by abel, by rwa self_eq_add_right at this @[simp] lemma sub_eq_add : a - b = a + b := by rw [sub_eq_add_neg, add_right_inj, neg_eq] @[simp] lemma mul_one_add_self : a * (1 + a) = 0 := by rw [mul_add, mul_one, mul_self, add_self] @[priority 100] -- Note [lower instance priority] instance boolean_ring.to_comm_ring : comm_ring α := { mul_comm := λ a b, by rw [←add_eq_zero', mul_add_mul], .. (infer_instance : boolean_ring α) } end boolean_ring instance : boolean_ring punit := ⟨λ _, subsingleton.elim _ _⟩ /-! ### Turning a Boolean ring into a Boolean algebra -/ section ring_to_algebra /-- Type synonym to view a Boolean ring as a Boolean algebra. -/ def as_boolalg (α : Type*) := α /-- The "identity" equivalence between `as_boolalg α` and `α`. -/ def to_boolalg : α ≃ as_boolalg α := equiv.refl _ /-- The "identity" equivalence between `α` and `as_boolalg α`. -/ def of_boolalg : as_boolalg α ≃ α := equiv.refl _ @[simp] lemma to_boolalg_symm_eq : (@to_boolalg α).symm = of_boolalg := rfl @[simp] lemma of_boolalg_symm_eq : (@of_boolalg α).symm = to_boolalg := rfl @[simp] lemma to_boolalg_of_boolalg (a : as_boolalg α) : to_boolalg (of_boolalg a) = a := rfl @[simp] lemma of_boolalg_to_boolalg (a : α) : of_boolalg (to_boolalg a) = a := rfl @[simp] lemma to_boolalg_inj {a b : α} : to_boolalg a = to_boolalg b ↔ a = b := iff.rfl @[simp] lemma of_boolalg_inj {a b : as_boolalg α} : of_boolalg a = of_boolalg b ↔ a = b := iff.rfl instance [inhabited α] : inhabited (as_boolalg α) := ‹inhabited α› variables [boolean_ring α] [boolean_ring β] [boolean_ring γ] namespace boolean_ring /-- The join operation in a Boolean ring is `x + y + x * y`. -/ def has_sup : has_sup α := ⟨λ x y, x + y + x * y⟩ /-- The meet operation in a Boolean ring is `x * y`. -/ def has_inf : has_inf α := ⟨(*)⟩ -- Note [lower instance priority] localized "attribute [instance, priority 100] boolean_ring.has_sup" in boolean_algebra_of_boolean_ring localized "attribute [instance, priority 100] boolean_ring.has_inf" in boolean_algebra_of_boolean_ring lemma sup_comm (a b : α) : a ⊔ b = b ⊔ a := by { dsimp only [(⊔)], ring } lemma inf_comm (a b : α) : a ⊓ b = b ⊓ a := by { dsimp only [(⊓)], ring } lemma sup_assoc (a b c : α) : a ⊔ b ⊔ c = a ⊔ (b ⊔ c) := by { dsimp only [(⊔)], ring } lemma inf_assoc (a b c : α) : a ⊓ b ⊓ c = a ⊓ (b ⊓ c) := by { dsimp only [(⊓)], ring } lemma sup_inf_self (a b : α) : a ⊔ a ⊓ b = a := by { dsimp only [(⊔), (⊓)], assoc_rw [mul_self, add_self, add_zero] } lemma inf_sup_self (a b : α) : a ⊓ (a ⊔ b) = a := begin dsimp only [(⊔), (⊓)], rw [mul_add, mul_add, mul_self, ←mul_assoc, mul_self, add_assoc, add_self, add_zero] end lemma le_sup_inf_aux (a b c : α) : (a + b + a * b) * (a + c + a * c) = a + b * c + a * (b * c) := calc (a + b + a * b) * (a + c + a * c) = a * a + b * c + a * (b * c) + (a * b + (a * a) * b) + (a * c + (a * a) * c) + (a * b * c + (a * a) * b * c) : by ring ... = a + b * c + a * (b * c) : by simp only [mul_self, add_self, add_zero] lemma le_sup_inf (a b c : α) : (a ⊔ b) ⊓ (a ⊔ c) ⊔ (a ⊔ b ⊓ c) = a ⊔ b ⊓ c := by { dsimp only [(⊔), (⊓)], rw [le_sup_inf_aux, add_self, mul_self, zero_add] } /-- The Boolean algebra structure on a Boolean ring. The data is defined so that: * `a ⊔ b` unfolds to `a + b + a * b` * `a ⊓ b` unfolds to `a * b` * `a ≤ b` unfolds to `a + b + a * b = b` * `⊥` unfolds to `0` * `⊤` unfolds to `1` * `aᶜ` unfolds to `1 + a` * `a \ b` unfolds to `a * (1 + b)` -/ def to_boolean_algebra : boolean_algebra α := { le_sup_inf := le_sup_inf, top := 1, le_top := λ a, show a + 1 + a * 1 = 1, by assoc_rw [mul_one, add_comm, add_self, add_zero], bot := 0, bot_le := λ a, show 0 + a + 0 * a = a, by rw [zero_mul, zero_add, add_zero], compl := λ a, 1 + a, inf_compl_le_bot := λ a, show a*(1+a) + 0 + a*(1+a)*0 = 0, by norm_num [mul_add, mul_self, add_self], top_le_sup_compl := λ a, begin change 1 + (a + (1+a) + a*(1+a)) + 1*(a + (1+a) + a*(1+a)) = a + (1+a) + a*(1+a), norm_num [mul_add, mul_self], rw [←add_assoc, add_self], end, .. lattice.mk' sup_comm sup_assoc inf_comm inf_assoc sup_inf_self inf_sup_self } localized "attribute [instance, priority 100] boolean_ring.to_boolean_algebra" in boolean_algebra_of_boolean_ring end boolean_ring instance : boolean_algebra (as_boolalg α) := @boolean_ring.to_boolean_algebra α _ @[simp] lemma of_boolalg_top : of_boolalg (⊤ : as_boolalg α) = 1 := rfl @[simp] lemma of_boolalg_bot : of_boolalg (⊥ : as_boolalg α) = 0 := rfl @[simp] lemma of_boolalg_sup (a b : as_boolalg α) : of_boolalg (a ⊔ b) = of_boolalg a + of_boolalg b + of_boolalg a * of_boolalg b := rfl @[simp] lemma of_boolalg_inf (a b : as_boolalg α) : of_boolalg (a ⊓ b) = of_boolalg a * of_boolalg b := rfl @[simp] lemma of_boolalg_compl (a : as_boolalg α) : of_boolalg aᶜ = 1 + of_boolalg a := rfl @[simp] lemma of_boolalg_sdiff (a b : as_boolalg α) : of_boolalg (a \ b) = of_boolalg a * (1 + of_boolalg b) := rfl private lemma of_boolalg_symm_diff_aux (a b : α) : (a + b + a * b) * (1 + a * b) = a + b := calc (a + b + a * b) * (1 + a * b) = a + b + (a * b + (a * b) * (a * b)) + (a * (b * b) + (a * a) * b) : by ring ... = a + b : by simp only [mul_self, add_self, add_zero] @[simp] lemma of_boolalg_symm_diff (a b : as_boolalg α) : of_boolalg (a ∆ b) = of_boolalg a + of_boolalg b := by { rw symm_diff_eq_sup_sdiff_inf, exact of_boolalg_symm_diff_aux _ _ } @[simp] lemma of_boolalg_mul_of_boolalg_eq_left_iff {a b : as_boolalg α} : of_boolalg a * of_boolalg b = of_boolalg a ↔ a ≤ b := @inf_eq_left (as_boolalg α) _ _ _ @[simp] lemma to_boolalg_zero : to_boolalg (0 : α) = ⊥ := rfl @[simp] lemma to_boolalg_one : to_boolalg (1 : α) = ⊤ := rfl @[simp] lemma to_boolalg_mul (a b : α) : to_boolalg (a * b) = to_boolalg a ⊓ to_boolalg b := rfl -- `to_boolalg_add` simplifies the LHS but this lemma is eligible to `dsimp` @[simp, nolint simp_nf] lemma to_boolalg_add_add_mul (a b : α) : to_boolalg (a + b + a * b) = to_boolalg a ⊔ to_boolalg b := rfl @[simp] lemma to_boolalg_add (a b : α) : to_boolalg (a + b) = to_boolalg a ∆ to_boolalg b := (of_boolalg_symm_diff _ _).symm /-- Turn a ring homomorphism from Boolean rings `α` to `β` into a bounded lattice homomorphism from `α` to `β` considered as Boolean algebras. -/ @[simps] protected def ring_hom.as_boolalg (f : α →+* β) : bounded_lattice_hom (as_boolalg α) (as_boolalg β) := { to_fun := to_boolalg ∘ f ∘ of_boolalg, map_sup' := λ a b, begin dsimp, simp_rw [map_add f, map_mul f], refl, end, map_inf' := f.map_mul', map_top' := f.map_one', map_bot' := f.map_zero' } @[simp] lemma ring_hom.as_boolalg_id : (ring_hom.id α).as_boolalg = bounded_lattice_hom.id _ := rfl @[simp] lemma ring_hom.as_boolalg_comp (g : β →+* γ) (f : α →+* β) : (g.comp f).as_boolalg = g.as_boolalg.comp f.as_boolalg := rfl end ring_to_algebra /-! ### Turning a Boolean algebra into a Boolean ring -/ section algebra_to_ring /-- Type synonym to view a Boolean ring as a Boolean algebra. -/ def as_boolring (α : Type*) := α /-- The "identity" equivalence between `as_boolring α` and `α`. -/ def to_boolring : α ≃ as_boolring α := equiv.refl _ /-- The "identity" equivalence between `α` and `as_boolring α`. -/ def of_boolring : as_boolring α ≃ α := equiv.refl _ @[simp] lemma to_boolring_symm_eq : (@to_boolring α).symm = of_boolring := rfl @[simp] lemma of_boolring_symm_eq : (@of_boolring α).symm = to_boolring := rfl @[simp] lemma to_boolring_of_boolring (a : as_boolring α) : to_boolring (of_boolring a) = a := rfl @[simp] lemma of_boolring_to_boolring (a : α) : of_boolring (to_boolring a) = a := rfl @[simp] lemma to_boolring_inj {a b : α} : to_boolring a = to_boolring b ↔ a = b := iff.rfl @[simp] lemma of_boolring_inj {a b : as_boolring α} : of_boolring a = of_boolring b ↔ a = b := iff.rfl instance [inhabited α] : inhabited (as_boolring α) := ‹inhabited α› /-- Every generalized Boolean algebra has the structure of a non unital commutative ring with the following data: * `a + b` unfolds to `a ∆ b` (symmetric difference) * `a * b` unfolds to `a ⊓ b` * `-a` unfolds to `a` * `0` unfolds to `⊥` -/ @[reducible] -- See note [reducible non-instances] def generalized_boolean_algebra.to_non_unital_comm_ring [generalized_boolean_algebra α] : non_unital_comm_ring α := { add := (∆), add_assoc := symm_diff_assoc, zero := ⊥, zero_add := bot_symm_diff, add_zero := symm_diff_bot, zero_mul := λ _, bot_inf_eq, mul_zero := λ _, inf_bot_eq, neg := id, add_left_neg := symm_diff_self, add_comm := symm_diff_comm, mul := (⊓), mul_assoc := λ _ _ _, inf_assoc, mul_comm := λ _ _, inf_comm, left_distrib := inf_symm_diff_distrib_left, right_distrib := inf_symm_diff_distrib_right } instance [generalized_boolean_algebra α] : non_unital_comm_ring (as_boolring α) := @generalized_boolean_algebra.to_non_unital_comm_ring α _ variables [boolean_algebra α] [boolean_algebra β] [boolean_algebra γ] /-- Every Boolean algebra has the structure of a Boolean ring with the following data: * `a + b` unfolds to `a ∆ b` (symmetric difference) * `a * b` unfolds to `a ⊓ b` * `-a` unfolds to `a` * `0` unfolds to `⊥` * `1` unfolds to `⊤` -/ @[reducible] -- See note [reducible non-instances] def boolean_algebra.to_boolean_ring : boolean_ring α := { one := ⊤, one_mul := λ _, top_inf_eq, mul_one := λ _, inf_top_eq, mul_self := λ b, inf_idem, ..generalized_boolean_algebra.to_non_unital_comm_ring } localized "attribute [instance, priority 100] generalized_boolean_algebra.to_non_unital_comm_ring boolean_algebra.to_boolean_ring" in boolean_ring_of_boolean_algebra instance : boolean_ring (as_boolring α) := @boolean_algebra.to_boolean_ring α _ @[simp] lemma of_boolring_zero : of_boolring (0 : as_boolring α) = ⊥ := rfl @[simp] lemma of_boolring_one : of_boolring (1 : as_boolring α) = ⊤ := rfl -- `sub_eq_add` proves this lemma but it is eligible for `dsimp` @[simp, nolint simp_nf] lemma of_boolring_neg (a : as_boolring α) : of_boolring (-a) = of_boolring a := rfl @[simp] lemma of_boolring_add (a b : as_boolring α) : of_boolring (a + b) = of_boolring a ∆ of_boolring b := rfl -- `sub_eq_add` simplifies the LHS but this lemma is eligible for `dsimp` @[simp, nolint simp_nf] lemma of_boolring_sub (a b : as_boolring α) : of_boolring (a - b) = of_boolring a ∆ of_boolring b := rfl @[simp] lemma of_boolring_mul (a b : as_boolring α) : of_boolring (a * b) = of_boolring a ⊓ of_boolring b := rfl @[simp] lemma of_boolring_le_of_boolring_iff {a b : as_boolring α} : of_boolring a ≤ of_boolring b ↔ a * b = a := inf_eq_left.symm @[simp] lemma to_boolring_bot : to_boolring (⊥ : α) = 0 := rfl @[simp] lemma to_boolring_top : to_boolring (⊤ : α) = 1 := rfl @[simp] lemma to_boolring_inf (a b : α) : to_boolring (a ⊓ b) = to_boolring a * to_boolring b := rfl @[simp] lemma to_boolring_symm_diff (a b : α) : to_boolring (a ∆ b) = to_boolring a + to_boolring b := rfl /-- Turn a bounded lattice homomorphism from Boolean algebras `α` to `β` into a ring homomorphism from `α` to `β` considered as Boolean rings. -/ @[simps] protected def bounded_lattice_hom.as_boolring (f : bounded_lattice_hom α β) : as_boolring α →+* as_boolring β := { to_fun := to_boolring ∘ f ∘ of_boolring, map_zero' := f.map_bot', map_one' := f.map_top', map_add' := map_symm_diff' f, map_mul' := f.map_inf' } @[simp] lemma bounded_lattice_hom.as_boolring_id : (bounded_lattice_hom.id α).as_boolring = ring_hom.id _ := rfl @[simp] lemma bounded_lattice_hom.as_boolring_comp (g : bounded_lattice_hom β γ) (f : bounded_lattice_hom α β) : (g.comp f).as_boolring = g.as_boolring.comp f.as_boolring := rfl end algebra_to_ring /-! ### Equivalence between Boolean rings and Boolean algebras -/ /-- Order isomorphism between `α` considered as a Boolean ring considered as a Boolean algebra and `α`. -/ @[simps] def order_iso.as_boolalg_as_boolring (α : Type*) [boolean_algebra α] : as_boolalg (as_boolring α) ≃o α := ⟨of_boolalg.trans of_boolring, λ a b, of_boolring_le_of_boolring_iff.trans of_boolalg_mul_of_boolalg_eq_left_iff⟩ /-- Ring isomorphism between `α` considered as a Boolean algebra considered as a Boolean ring and `α`. -/ @[simps] def ring_equiv.as_boolring_as_boolalg (α : Type*) [boolean_ring α] : as_boolring (as_boolalg α) ≃+* α := { map_mul' := λ a b, rfl, map_add' := of_boolalg_symm_diff, ..of_boolring.trans of_boolalg } open bool instance : boolean_ring bool := { add := bxor, add_assoc := bxor_assoc, zero := ff, zero_add := ff_bxor, add_zero := bxor_ff, neg := id, sub := bxor, sub_eq_add_neg := λ _ _, rfl, add_left_neg := bxor_self, add_comm := bxor_comm, one := tt, mul := band, mul_assoc := band_assoc, one_mul := tt_band, mul_one := band_tt, left_distrib := band_bxor_distrib_left, right_distrib := band_bxor_distrib_right, mul_self := band_self }
26c6728606fd878d7006c6102e53dbff643f6a3e
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/roadmap/todo.lean
c5490a91a03b2530f7ebd20f6d72d65da1cc9ac6
[ "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
743
lean
/- Copyright (c) 2020 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton -/ /-! This file adds an axiom `todo`, and a corresponding tactic, which can be used in place of `sorry`. It is only intended for use inside the roadmap subdirectory. -/ /-- Axiom used to skip proofs in formal roadmaps. (When working on a roadmap, you may prefer to prove new lemmas, rather than trying to solve an `exact todo` in-line. The tactic `extract_goal` is useful for this.) -/ axiom todo {p : Prop} : p namespace tactic namespace interactive /-- An axiomatic alternative to `sorry`, used in formal roadmaps. -/ meta def todo : tactic unit := `[exact todo] end interactive end tactic
9f59c416eb51af4e416bba874d73a4b771714da9
193da933cf42f2f9188bb47e3c973205bc2abc5c
/AA_Algebras/01_dm_bool/0_introduction.lean
752c718f12204348ea6cf8994f14a5157e40c320
[]
no_license
pandaman64/cs-dm
aa4e2621c7a19e2dae911bc237c33e02fcb0c7a3
bfd2f5fd2612472e15bd970c7870b5d0dd73bd1c
refs/heads/master
1,647,620,340,607
1,570,055,187,000
1,570,055,187,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,415
lean
/- In this chapter we explore the formal definition of the algebra called Boolean algebra. Boolean algebra is an algebra over a set of two values, usually called true and false, with a set of operators, such as "and," "or," and "not." It was invented by George Boole (thus it name) to capture the forms of logical human thought in a mathematical (algebraic!) form. Boolean algebra should already be familiar to you--though maybe not as "an algebra"--rom your study of the syntax and evaluation of Boolean expressions in your CS1 class. But whereas you took Boolean algebra as a built-in capability of the programming language you used in CS1, now we will actually build that algebra from scratch. In the process of doing this, we will encounter a number of concepts that are at the foundations of mathematics and mathematical logic. They include the following: - Boolean algebra as a case studing in defining algebras * the carrier set of Boolean values, { true, false } * the standard Boolean operations - implementing the carrier sets of algebras using inductive type definitions - implementing the operations of algebras as pure functional programs - asserting and proving properties of such an implementation - propositions and proofs * by simplification and reflexivity of equality * by exhaustive case analysis The overall contribution of this chapter is the definition (and a working implementation) of the algebra of Boolean values comprising an inductive definition of the set of Boolean values as a type, the definition of set of operators over this set in the form of pure functional programs, and the statements and proofs of a few simple expected properties of this algebra to provide some evidence that we got it right. Along the way, we will meet a few ancillary ideas that are needed for our implementation. These concepts are not unique to Lean but appear across a broad range of programming and verification languages and systems. - namespaces (common to most programming systems) - inductive type definitions (common across most functional languages) - the #check command in Lean (common across many proof assistants) - pure functional programming (a major category of programming languages) - type inference - function types - pattern matching (common to many functional programming languages) - propositions as types (common across constructive logic proof assistants) -/
064db1a068fb0bbcd51ce5b84c4a0bf8eb3626fd
8b9f17008684d796c8022dab552e42f0cb6fb347
/library/logic/examples/instances_test.lean
68b8ba8ab6f535adde5ffefe264a3e154c2f0afc
[ "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
1,269
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: logic.examples.instances_test Author: Jeremy Avigad Illustrates substitution and congruence with iff. -/ import ..instances open relation open relation.general_subst open relation.iff_ops open eq.ops example (a b : Prop) (H : a ↔ b) (H1 : a) : b := mp H H1 set_option class.conservative false example (a b c d e : Prop) (H1 : a ↔ b) (H2 : a ∨ c → ¬(d → a)) : b ∨ c → ¬(d → b) := subst iff H1 H2 exit example (a b c d e : Prop) (H1 : a ↔ b) (H2 : a ∨ c → ¬(d → a)) : b ∨ c → ¬(d → b) := H1 ▸ H2 example (a b c d e : Prop) (H1 : a ↔ b) : (a ∨ c → ¬(d → a)) ↔ (b ∨ c → ¬(d → b)) := is_congruence.congr iff (λa, (a ∨ c → ¬(d → a))) H1 example (T : Type) (a b c d : T) (H1 : a = b) (H2 : c = b) (H3 : c = d) : a = d := H1 ⬝ H2⁻¹ ⬝ H3 example (a b c d : Prop) (H1 : a ↔ b) (H2 : c ↔ b) (H3 : c ↔ d) : a ↔ d := H1 ⬝ (H2⁻¹ ⬝ H3) example (T : Type) (a b c d : T) (H1 : a = b) (H2 : c = b) (H3 : c = d) : a = d := H1 ⬝ H2⁻¹ ⬝ H3 example (a b c d : Prop) (H1 : a ↔ b) (H2 : c ↔ b) (H3 : c ↔ d) : a ↔ d := H1 ⬝ H2⁻¹ ⬝ H3
77dffca003ea57f66a07666c7626936659b9ce14
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/group_theory/congruence.lean
5ec3b43463613ce52a1e02b6f958c5c8167dbeb3
[ "Apache-2.0" ]
permissive
ayush1801/mathlib
78949b9f789f488148142221606bf15c02b960d2
ce164e28f262acbb3de6281b3b03660a9f744e3c
refs/heads/master
1,692,886,907,941
1,635,270,866,000
1,635,270,866,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
48,291
lean
/- Copyright (c) 2019 Amelia Livingston. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Amelia Livingston -/ import data.setoid.basic import algebra.group.pi import algebra.group.prod import data.equiv.mul_add import group_theory.submonoid.operations /-! # Congruence relations This file defines congruence relations: equivalence relations that preserve a binary operation, which in this case is multiplication or addition. The principal definition is a `structure` extending a `setoid` (an equivalence relation), and the inductive definition of the smallest congruence relation containing a binary relation is also given (see `con_gen`). The file also proves basic properties of the quotient of a type by a congruence relation, and the complete lattice of congruence relations on a type. We then establish an order-preserving bijection between the set of congruence relations containing a congruence relation `c` and the set of congruence relations on the quotient by `c`. The second half of the file concerns congruence relations on monoids, in which case the quotient by the congruence relation is also a monoid. There are results about the universal property of quotients of monoids, and the isomorphism theorems for monoids. ## Implementation notes The inductive definition of a congruence relation could be a nested inductive type, defined using the equivalence closure of a binary relation `eqv_gen`, but the recursor generated does not work. A nested inductive definition could conceivably shorten proofs, because they would allow invocation of the corresponding lemmas about `eqv_gen`. The lemmas `refl`, `symm` and `trans` are not tagged with `@[refl]`, `@[symm]`, and `@[trans]` respectively as these tags do not work on a structure coerced to a binary relation. There is a coercion from elements of a type to the element's equivalence class under a congruence relation. A congruence relation on a monoid `M` can be thought of as a submonoid of `M × M` for which membership is an equivalence relation, but whilst this fact is established in the file, it is not used, since this perspective adds more layers of definitional unfolding. ## Tags congruence, congruence relation, quotient, quotient by congruence relation, monoid, quotient monoid, isomorphism theorems -/ variables (M : Type*) {N : Type*} {P : Type*} open function setoid /-- A congruence relation on a type with an addition is an equivalence relation which preserves addition. -/ structure add_con [has_add M] extends setoid M := (add' : ∀ {w x y z}, r w x → r y z → r (w + y) (x + z)) /-- A congruence relation on a type with a multiplication is an equivalence relation which preserves multiplication. -/ @[to_additive add_con] structure con [has_mul M] extends setoid M := (mul' : ∀ {w x y z}, r w x → r y z → r (w * y) (x * z)) /-- The equivalence relation underlying an additive congruence relation. -/ add_decl_doc add_con.to_setoid /-- The equivalence relation underlying a multiplicative congruence relation. -/ add_decl_doc con.to_setoid variables {M} /-- The inductively defined smallest additive congruence relation containing a given binary relation. -/ inductive add_con_gen.rel [has_add M] (r : M → M → Prop) : M → M → Prop | of : Π x y, r x y → add_con_gen.rel x y | refl : Π x, add_con_gen.rel x x | symm : Π x y, add_con_gen.rel x y → add_con_gen.rel y x | trans : Π x y z, add_con_gen.rel x y → add_con_gen.rel y z → add_con_gen.rel x z | add : Π w x y z, add_con_gen.rel w x → add_con_gen.rel y z → add_con_gen.rel (w + y) (x + z) /-- The inductively defined smallest multiplicative congruence relation containing a given binary relation. -/ @[to_additive add_con_gen.rel] inductive con_gen.rel [has_mul M] (r : M → M → Prop) : M → M → Prop | of : Π x y, r x y → con_gen.rel x y | refl : Π x, con_gen.rel x x | symm : Π x y, con_gen.rel x y → con_gen.rel y x | trans : Π x y z, con_gen.rel x y → con_gen.rel y z → con_gen.rel x z | mul : Π w x y z, con_gen.rel w x → con_gen.rel y z → con_gen.rel (w * y) (x * z) /-- The inductively defined smallest multiplicative congruence relation containing a given binary relation. -/ @[to_additive add_con_gen "The inductively defined smallest additive congruence relation containing a given binary relation."] def con_gen [has_mul M] (r : M → M → Prop) : con M := ⟨⟨con_gen.rel r, ⟨con_gen.rel.refl, con_gen.rel.symm, con_gen.rel.trans⟩⟩, con_gen.rel.mul⟩ namespace con section variables [has_mul M] [has_mul N] [has_mul P] (c : con M) @[to_additive] instance : inhabited (con M) := ⟨con_gen empty_relation⟩ /-- A coercion from a congruence relation to its underlying binary relation. -/ @[to_additive "A coercion from an additive congruence relation to its underlying binary relation."] instance : has_coe_to_fun (con M) (λ _, M → M → Prop) := ⟨λ c, λ x y, @setoid.r _ c.to_setoid x y⟩ @[simp, to_additive] lemma rel_eq_coe (c : con M) : c.r = c := rfl /-- Congruence relations are reflexive. -/ @[to_additive "Additive congruence relations are reflexive."] protected lemma refl (x) : c x x := c.to_setoid.refl' x /-- Congruence relations are symmetric. -/ @[to_additive "Additive congruence relations are symmetric."] protected lemma symm : ∀ {x y}, c x y → c y x := λ _ _ h, c.to_setoid.symm' h /-- Congruence relations are transitive. -/ @[to_additive "Additive congruence relations are transitive."] protected lemma trans : ∀ {x y z}, c x y → c y z → c x z := λ _ _ _ h, c.to_setoid.trans' h /-- Multiplicative congruence relations preserve multiplication. -/ @[to_additive "Additive congruence relations preserve addition."] protected lemma mul : ∀ {w x y z}, c w x → c y z → c (w * y) (x * z) := λ _ _ _ _ h1 h2, c.mul' h1 h2 @[simp, to_additive] lemma rel_mk {s : setoid M} {h a b} : con.mk s h a b ↔ r a b := iff.rfl /-- Given a type `M` with a multiplication, a congruence relation `c` on `M`, and elements of `M` `x, y`, `(x, y) ∈ M × M` iff `x` is related to `y` by `c`. -/ @[to_additive "Given a type `M` with an addition, `x, y ∈ M`, and an additive congruence relation `c` on `M`, `(x, y) ∈ M × M` iff `x` is related to `y` by `c`."] instance : has_mem (M × M) (con M) := ⟨λ x c, c x.1 x.2⟩ variables {c} /-- The map sending a congruence relation to its underlying binary relation is injective. -/ @[to_additive "The map sending an additive congruence relation to its underlying binary relation is injective."] lemma ext' {c d : con M} (H : c.r = d.r) : c = d := by { rcases c with ⟨⟨⟩⟩, rcases d with ⟨⟨⟩⟩, cases H, congr, } /-- Extensionality rule for congruence relations. -/ @[ext, to_additive "Extensionality rule for additive congruence relations."] lemma ext {c d : con M} (H : ∀ x y, c x y ↔ d x y) : c = d := ext' $ by ext; apply H /-- The map sending a congruence relation to its underlying equivalence relation is injective. -/ @[to_additive "The map sending an additive congruence relation to its underlying equivalence relation is injective."] lemma to_setoid_inj {c d : con M} (H : c.to_setoid = d.to_setoid) : c = d := ext $ ext_iff.1 H /-- Iff version of extensionality rule for congruence relations. -/ @[to_additive "Iff version of extensionality rule for additive congruence relations."] lemma ext_iff {c d : con M} : (∀ x y, c x y ↔ d x y) ↔ c = d := ⟨ext, λ h _ _, h ▸ iff.rfl⟩ /-- Two congruence relations are equal iff their underlying binary relations are equal. -/ @[to_additive "Two additive congruence relations are equal iff their underlying binary relations are equal."] lemma ext'_iff {c d : con M} : c.r = d.r ↔ c = d := ⟨ext', λ h, h ▸ rfl⟩ /-- The kernel of a multiplication-preserving function as a congruence relation. -/ @[to_additive "The kernel of an addition-preserving function as an additive congruence relation."] def mul_ker (f : M → P) (h : ∀ x y, f (x * y) = f x * f y) : con M := { to_setoid := setoid.ker f, mul' := λ _ _ _ _ h1 h2, by { dsimp [setoid.ker] at *, rw [h, h1, h2, h], } } /-- Given types with multiplications `M, N`, the product of two congruence relations `c` on `M` and `d` on `N`: `(x₁, x₂), (y₁, y₂) ∈ M × N` are related by `c.prod d` iff `x₁` is related to `y₁` by `c` and `x₂` is related to `y₂` by `d`. -/ @[to_additive prod "Given types with additions `M, N`, the product of two congruence relations `c` on `M` and `d` on `N`: `(x₁, x₂), (y₁, y₂) ∈ M × N` are related by `c.prod d` iff `x₁` is related to `y₁` by `c` and `x₂` is related to `y₂` by `d`."] protected def prod (c : con M) (d : con N) : con (M × N) := { mul' := λ _ _ _ _ h1 h2, ⟨c.mul h1.1 h2.1, d.mul h1.2 h2.2⟩, ..c.to_setoid.prod d.to_setoid } /-- The product of an indexed collection of congruence relations. -/ @[to_additive "The product of an indexed collection of additive congruence relations."] def pi {ι : Type*} {f : ι → Type*} [Π i, has_mul (f i)] (C : Π i, con (f i)) : con (Π i, f i) := { mul' := λ _ _ _ _ h1 h2 i, (C i).mul (h1 i) (h2 i), ..@pi_setoid _ _ $ λ i, (C i).to_setoid } variables (c) -- Quotients /-- Defining the quotient by a congruence relation of a type with a multiplication. -/ @[to_additive "Defining the quotient by an additive congruence relation of a type with an addition."] protected def quotient := quotient $ c.to_setoid /-- Coercion from a type with a multiplication to its quotient by a congruence relation. See Note [use has_coe_t]. -/ @[to_additive "Coercion from a type with an addition to its quotient by an additive congruence relation", priority 0] instance : has_coe_t M c.quotient := ⟨@quotient.mk _ c.to_setoid⟩ /-- The quotient by a decidable congruence relation has decidable equality. -/ @[to_additive "The quotient by a decidable additive congruence relation has decidable equality.", priority 500] -- Lower the priority since it unifies with any quotient type. instance [d : ∀ a b, decidable (c a b)] : decidable_eq c.quotient := @quotient.decidable_eq M c.to_setoid d @[simp, to_additive] lemma quot_mk_eq_coe {M : Type*} [has_mul M] (c : con M) (x : M) : quot.mk c x = (x : c.quotient) := rfl /-- The function on the quotient by a congruence relation `c` induced by a function that is constant on `c`'s equivalence classes. -/ @[elab_as_eliminator, to_additive "The function on the quotient by a congruence relation `c` induced by a function that is constant on `c`'s equivalence classes."] protected def lift_on {β} {c : con M} (q : c.quotient) (f : M → β) (h : ∀ a b, c a b → f a = f b) : β := quotient.lift_on' q f h /-- The binary function on the quotient by a congruence relation `c` induced by a binary function that is constant on `c`'s equivalence classes. -/ @[elab_as_eliminator, to_additive "The binary function on the quotient by a congruence relation `c` induced by a binary function that is constant on `c`'s equivalence classes."] protected def lift_on₂ {β} {c : con M} (q r : c.quotient) (f : M → M → β) (h : ∀ a₁ a₂ b₁ b₂, c a₁ b₁ → c a₂ b₂ → f a₁ a₂ = f b₁ b₂) : β := quotient.lift_on₂' q r f h /-- A version of `quotient.hrec_on₂'` for quotients by `con`. -/ @[to_additive "A version of `quotient.hrec_on₂'` for quotients by `add_con`."] protected def hrec_on₂ {cM : con M} {cN : con N} {φ : cM.quotient → cN.quotient → Sort*} (a : cM.quotient) (b : cN.quotient) (f : Π (x : M) (y : N), φ x y) (h : ∀ x y x' y', cM x x' → cN y y' → f x y == f x' y') : φ a b := quotient.hrec_on₂' a b f h @[simp, to_additive] lemma hrec_on₂_coe {cM : con M} {cN : con N} {φ : cM.quotient → cN.quotient → Sort*} (a : M) (b : N) (f : Π (x : M) (y : N), φ x y) (h : ∀ x y x' y', cM x x' → cN y y' → f x y == f x' y') : con.hrec_on₂ ↑a ↑b f h = f a b := rfl variables {c} /-- The inductive principle used to prove propositions about the elements of a quotient by a congruence relation. -/ @[elab_as_eliminator, to_additive "The inductive principle used to prove propositions about the elements of a quotient by an additive congruence relation."] protected lemma induction_on {C : c.quotient → Prop} (q : c.quotient) (H : ∀ x : M, C x) : C q := quotient.induction_on' q H /-- A version of `con.induction_on` for predicates which take two arguments. -/ @[elab_as_eliminator, to_additive "A version of `add_con.induction_on` for predicates which take two arguments."] protected lemma induction_on₂ {d : con N} {C : c.quotient → d.quotient → Prop} (p : c.quotient) (q : d.quotient) (H : ∀ (x : M) (y : N), C x y) : C p q := quotient.induction_on₂' p q H variables (c) /-- Two elements are related by a congruence relation `c` iff they are represented by the same element of the quotient by `c`. -/ @[simp, to_additive "Two elements are related by an additive congruence relation `c` iff they are represented by the same element of the quotient by `c`."] protected lemma eq {a b : M} : (a : c.quotient) = b ↔ c a b := quotient.eq' /-- The multiplication induced on the quotient by a congruence relation on a type with a multiplication. -/ @[to_additive "The addition induced on the quotient by an additive congruence relation on a type with an addition."] instance has_mul : has_mul c.quotient := ⟨λ x y, quotient.lift_on₂' x y (λ w z, ((w * z : M) : c.quotient)) $ λ _ _ _ _ h1 h2, c.eq.2 $ c.mul h1 h2⟩ /-- The kernel of the quotient map induced by a congruence relation `c` equals `c`. -/ @[simp, to_additive "The kernel of the quotient map induced by an additive congruence relation `c` equals `c`."] lemma mul_ker_mk_eq : mul_ker (coe : M → c.quotient) (λ x y, rfl) = c := ext $ λ x y, quotient.eq' variables {c} /-- The coercion to the quotient of a congruence relation commutes with multiplication (by definition). -/ @[simp, to_additive "The coercion to the quotient of an additive congruence relation commutes with addition (by definition)."] lemma coe_mul (x y : M) : (↑(x * y) : c.quotient) = ↑x * ↑y := rfl /-- Definition of the function on the quotient by a congruence relation `c` induced by a function that is constant on `c`'s equivalence classes. -/ @[simp, to_additive "Definition of the function on the quotient by an additive congruence relation `c` induced by a function that is constant on `c`'s equivalence classes."] protected lemma lift_on_coe {β} (c : con M) (f : M → β) (h : ∀ a b, c a b → f a = f b) (x : M) : con.lift_on (x : c.quotient) f h = f x := rfl /-- Makes an isomorphism of quotients by two congruence relations, given that the relations are equal. -/ @[to_additive "Makes an additive isomorphism of quotients by two additive congruence relations, given that the relations are equal."] protected def congr {c d : con M} (h : c = d) : c.quotient ≃* d.quotient := { map_mul' := λ x y, by rcases x; rcases y; refl, ..quotient.congr (equiv.refl M) $ by apply ext_iff.2 h } -- The complete lattice of congruence relations on a type /-- For congruence relations `c, d` on a type `M` with a multiplication, `c ≤ d` iff `∀ x y ∈ M`, `x` is related to `y` by `d` if `x` is related to `y` by `c`. -/ @[to_additive "For additive congruence relations `c, d` on a type `M` with an addition, `c ≤ d` iff `∀ x y ∈ M`, `x` is related to `y` by `d` if `x` is related to `y` by `c`."] instance : has_le (con M) := ⟨λ c d, ∀ ⦃x y⦄, c x y → d x y⟩ /-- Definition of `≤` for congruence relations. -/ @[to_additive "Definition of `≤` for additive congruence relations."] theorem le_def {c d : con M} : c ≤ d ↔ ∀ {x y}, c x y → d x y := iff.rfl /-- The infimum of a set of congruence relations on a given type with a multiplication. -/ @[to_additive "The infimum of a set of additive congruence relations on a given type with an addition."] instance : has_Inf (con M) := ⟨λ S, ⟨⟨λ x y, ∀ c : con M, c ∈ S → c x y, ⟨λ x c hc, c.refl x, λ _ _ h c hc, c.symm $ h c hc, λ _ _ _ h1 h2 c hc, c.trans (h1 c hc) $ h2 c hc⟩⟩, λ _ _ _ _ h1 h2 c hc, c.mul (h1 c hc) $ h2 c hc⟩⟩ /-- The infimum of a set of congruence relations is the same as the infimum of the set's image under the map to the underlying equivalence relation. -/ @[to_additive "The infimum of a set of additive congruence relations is the same as the infimum of the set's image under the map to the underlying equivalence relation."] lemma Inf_to_setoid (S : set (con M)) : (Inf S).to_setoid = Inf (to_setoid '' S) := setoid.ext' $ λ x y, ⟨λ h r ⟨c, hS, hr⟩, by rw ←hr; exact h c hS, λ h c hS, h c.to_setoid ⟨c, hS, rfl⟩⟩ /-- The infimum of a set of congruence relations is the same as the infimum of the set's image under the map to the underlying binary relation. -/ @[to_additive "The infimum of a set of additive congruence relations is the same as the infimum of the set's image under the map to the underlying binary relation."] lemma Inf_def (S : set (con M)) : ⇑(Inf S) = Inf (@set.image (con M) (M → M → Prop) coe_fn S) := by { ext, simp only [Inf_image, infi_apply, infi_Prop_eq], refl } @[to_additive] instance : partial_order (con M) := { le := (≤), lt := λ c d, c ≤ d ∧ ¬d ≤ c, le_refl := λ c _ _, id, le_trans := λ c1 c2 c3 h1 h2 x y h, h2 $ h1 h, lt_iff_le_not_le := λ _ _, iff.rfl, le_antisymm := λ c d hc hd, ext $ λ x y, ⟨λ h, hc h, λ h, hd h⟩ } /-- The complete lattice of congruence relations on a given type with a multiplication. -/ @[to_additive "The complete lattice of additive congruence relations on a given type with an addition."] instance : complete_lattice (con M) := { inf := λ c d, ⟨(c.to_setoid ⊓ d.to_setoid), λ _ _ _ _ h1 h2, ⟨c.mul h1.1 h2.1, d.mul h1.2 h2.2⟩⟩, inf_le_left := λ _ _ _ _ h, h.1, inf_le_right := λ _ _ _ _ h, h.2, le_inf := λ _ _ _ hb hc _ _ h, ⟨hb h, hc h⟩, top := { mul' := by tauto, ..setoid.complete_lattice.top}, le_top := λ _ _ _ h, trivial, bot := { mul' := λ _ _ _ _ h1 h2, h1 ▸ h2 ▸ rfl, ..setoid.complete_lattice.bot}, bot_le := λ c x y h, h ▸ c.refl x, .. complete_lattice_of_Inf (con M) $ assume s, ⟨λ r hr x y h, (h : ∀ r ∈ s, (r : con M) x y) r hr, λ r hr x y h r' hr', hr hr' h⟩ } /-- The infimum of two congruence relations equals the infimum of the underlying binary operations. -/ @[to_additive "The infimum of two additive congruence relations equals the infimum of the underlying binary operations."] lemma inf_def {c d : con M} : (c ⊓ d).r = c.r ⊓ d.r := rfl /-- Definition of the infimum of two congruence relations. -/ @[to_additive "Definition of the infimum of two additive congruence relations."] theorem inf_iff_and {c d : con M} {x y} : (c ⊓ d) x y ↔ c x y ∧ d x y := iff.rfl /-- The inductively defined smallest congruence relation containing a binary relation `r` equals the infimum of the set of congruence relations containing `r`. -/ @[to_additive add_con_gen_eq "The inductively defined smallest additive congruence relation containing a binary relation `r` equals the infimum of the set of additive congruence relations containing `r`."] theorem con_gen_eq (r : M → M → Prop) : con_gen r = Inf {s : con M | ∀ x y, r x y → s x y} := le_antisymm (λ x y H, con_gen.rel.rec_on H (λ _ _ h _ hs, hs _ _ h) (con.refl _) (λ _ _ _, con.symm _) (λ _ _ _ _ _, con.trans _) $ λ w x y z _ _ h1 h2 c hc, c.mul (h1 c hc) $ h2 c hc) (Inf_le (λ _ _, con_gen.rel.of _ _)) /-- The smallest congruence relation containing a binary relation `r` is contained in any congruence relation containing `r`. -/ @[to_additive add_con_gen_le "The smallest additive congruence relation containing a binary relation `r` is contained in any additive congruence relation containing `r`."] theorem con_gen_le {r : M → M → Prop} {c : con M} (h : ∀ x y, r x y → @setoid.r _ c.to_setoid x y) : con_gen r ≤ c := by rw con_gen_eq; exact Inf_le h /-- Given binary relations `r, s` with `r` contained in `s`, the smallest congruence relation containing `s` contains the smallest congruence relation containing `r`. -/ @[to_additive add_con_gen_mono "Given binary relations `r, s` with `r` contained in `s`, the smallest additive congruence relation containing `s` contains the smallest additive congruence relation containing `r`."] theorem con_gen_mono {r s : M → M → Prop} (h : ∀ x y, r x y → s x y) : con_gen r ≤ con_gen s := con_gen_le $ λ x y hr, con_gen.rel.of _ _ $ h x y hr /-- Congruence relations equal the smallest congruence relation in which they are contained. -/ @[simp, to_additive add_con_gen_of_add_con "Additive congruence relations equal the smallest additive congruence relation in which they are contained."] lemma con_gen_of_con (c : con M) : con_gen c = c := le_antisymm (by rw con_gen_eq; exact Inf_le (λ _ _, id)) con_gen.rel.of /-- The map sending a binary relation to the smallest congruence relation in which it is contained is idempotent. -/ @[simp, to_additive add_con_gen_idem "The map sending a binary relation to the smallest additive congruence relation in which it is contained is idempotent."] lemma con_gen_idem (r : M → M → Prop) : con_gen (con_gen r) = con_gen r := con_gen_of_con _ /-- The supremum of congruence relations `c, d` equals the smallest congruence relation containing the binary relation '`x` is related to `y` by `c` or `d`'. -/ @[to_additive sup_eq_add_con_gen "The supremum of additive congruence relations `c, d` equals the smallest additive congruence relation containing the binary relation '`x` is related to `y` by `c` or `d`'."] lemma sup_eq_con_gen (c d : con M) : c ⊔ d = con_gen (λ x y, c x y ∨ d x y) := begin rw con_gen_eq, apply congr_arg Inf, simp only [le_def, or_imp_distrib, ← forall_and_distrib] end /-- The supremum of two congruence relations equals the smallest congruence relation containing the supremum of the underlying binary operations. -/ @[to_additive "The supremum of two additive congruence relations equals the smallest additive congruence relation containing the supremum of the underlying binary operations."] lemma sup_def {c d : con M} : c ⊔ d = con_gen (c.r ⊔ d.r) := by rw sup_eq_con_gen; refl /-- The supremum of a set of congruence relations `S` equals the smallest congruence relation containing the binary relation 'there exists `c ∈ S` such that `x` is related to `y` by `c`'. -/ @[to_additive Sup_eq_add_con_gen "The supremum of a set of additive congruence relations `S` equals the smallest additive congruence relation containing the binary relation 'there exists `c ∈ S` such that `x` is related to `y` by `c`'."] lemma Sup_eq_con_gen (S : set (con M)) : Sup S = con_gen (λ x y, ∃ c : con M, c ∈ S ∧ c x y) := begin rw con_gen_eq, apply congr_arg Inf, ext, exact ⟨λ h _ _ ⟨r, hr⟩, h hr.1 hr.2, λ h r hS _ _ hr, h _ _ ⟨r, hS, hr⟩⟩, end /-- The supremum of a set of congruence relations is the same as the smallest congruence relation containing the supremum of the set's image under the map to the underlying binary relation. -/ @[to_additive "The supremum of a set of additive congruence relations is the same as the smallest additive congruence relation containing the supremum of the set's image under the map to the underlying binary relation."] lemma Sup_def {S : set (con M)} : Sup S = con_gen (Sup (@set.image (con M) (M → M → Prop) coe_fn S)) := begin rw [Sup_eq_con_gen, Sup_image], congr' with x y, simp only [Sup_image, supr_apply, supr_Prop_eq, exists_prop, rel_eq_coe] end variables (M) /-- There is a Galois insertion of congruence relations on a type with a multiplication `M` into binary relations on `M`. -/ @[to_additive "There is a Galois insertion of additive congruence relations on a type with an addition `M` into binary relations on `M`."] protected noncomputable def gi : @galois_insertion (M → M → Prop) (con M) _ _ con_gen coe_fn := { choice := λ r h, con_gen r, gc := λ r c, ⟨λ H _ _ h, H $ con_gen.rel.of _ _ h, λ H, con_gen_of_con c ▸ con_gen_mono H⟩, le_l_u := λ x, (con_gen_of_con x).symm ▸ le_refl x, choice_eq := λ _ _, rfl } variables {M} (c) /-- Given a function `f`, the smallest congruence relation containing the binary relation on `f`'s image defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by a congruence relation `c`.' -/ @[to_additive "Given a function `f`, the smallest additive congruence relation containing the binary relation on `f`'s image defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by an additive congruence relation `c`.'"] def map_gen (f : M → N) : con N := con_gen $ λ x y, ∃ a b, f a = x ∧ f b = y ∧ c a b /-- Given a surjective multiplicative-preserving function `f` whose kernel is contained in a congruence relation `c`, the congruence relation on `f`'s codomain defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by `c`.' -/ @[to_additive "Given a surjective addition-preserving function `f` whose kernel is contained in an additive congruence relation `c`, the additive congruence relation on `f`'s codomain defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by `c`.'"] def map_of_surjective (f : M → N) (H : ∀ x y, f (x * y) = f x * f y) (h : mul_ker f H ≤ c) (hf : surjective f) : con N := { mul' := λ w x y z ⟨a, b, hw, hx, h1⟩ ⟨p, q, hy, hz, h2⟩, ⟨a * p, b * q, by rw [H, hw, hy], by rw [H, hx, hz], c.mul h1 h2⟩, ..c.to_setoid.map_of_surjective f h hf } /-- A specialization of 'the smallest congruence relation containing a congruence relation `c` equals `c`'. -/ @[to_additive "A specialization of 'the smallest additive congruence relation containing an additive congruence relation `c` equals `c`'."] lemma map_of_surjective_eq_map_gen {c : con M} {f : M → N} (H : ∀ x y, f (x * y) = f x * f y) (h : mul_ker f H ≤ c) (hf : surjective f) : c.map_gen f = c.map_of_surjective f H h hf := by rw ←con_gen_of_con (c.map_of_surjective f H h hf); refl /-- Given types with multiplications `M, N` and a congruence relation `c` on `N`, a multiplication-preserving map `f : M → N` induces a congruence relation on `f`'s domain defined by '`x ≈ y` iff `f(x)` is related to `f(y)` by `c`.' -/ @[to_additive "Given types with additions `M, N` and an additive congruence relation `c` on `N`, an addition-preserving map `f : M → N` induces an additive congruence relation on `f`'s domain defined by '`x ≈ y` iff `f(x)` is related to `f(y)` by `c`.' "] def comap (f : M → N) (H : ∀ x y, f (x * y) = f x * f y) (c : con N) : con M := { mul' := λ w x y z h1 h2, show c (f (w * y)) (f (x * z)), by rw [H, H]; exact c.mul h1 h2, ..c.to_setoid.comap f } @[simp, to_additive] lemma comap_rel {f : M → N} (H : ∀ x y, f (x * y) = f x * f y) {c : con N} {x y : M} : comap f H c x y ↔ c (f x) (f y) := iff.rfl section open _root_.quotient /-- Given a congruence relation `c` on a type `M` with a multiplication, the order-preserving bijection between the set of congruence relations containing `c` and the congruence relations on the quotient of `M` by `c`. -/ @[to_additive "Given an additive congruence relation `c` on a type `M` with an addition, the order-preserving bijection between the set of additive congruence relations containing `c` and the additive congruence relations on the quotient of `M` by `c`."] def correspondence : {d // c ≤ d} ≃o (con c.quotient) := { to_fun := λ d, d.1.map_of_surjective coe _ (by rw mul_ker_mk_eq; exact d.2) $ @exists_rep _ c.to_setoid, inv_fun := λ d, ⟨comap (coe : M → c.quotient) (λ x y, rfl) d, λ _ _ h, show d _ _, by rw c.eq.2 h; exact d.refl _ ⟩, left_inv := λ d, subtype.ext_iff_val.2 $ ext $ λ _ _, ⟨λ h, let ⟨a, b, hx, hy, H⟩ := h in d.1.trans (d.1.symm $ d.2 $ c.eq.1 hx) $ d.1.trans H $ d.2 $ c.eq.1 hy, λ h, ⟨_, _, rfl, rfl, h⟩⟩, right_inv := λ d, let Hm : mul_ker (coe : M → c.quotient) (λ x y, rfl) ≤ comap (coe : M → c.quotient) (λ x y, rfl) d := λ x y h, show d _ _, by rw mul_ker_mk_eq at h; exact c.eq.2 h ▸ d.refl _ in ext $ λ x y, ⟨λ h, let ⟨a, b, hx, hy, H⟩ := h in hx ▸ hy ▸ H, con.induction_on₂ x y $ λ w z h, ⟨w, z, rfl, rfl, h⟩⟩, map_rel_iff' := λ s t, ⟨λ h _ _ hs, let ⟨a, b, hx, hy, ht⟩ := h ⟨_, _, rfl, rfl, hs⟩ in t.1.trans (t.1.symm $ t.2 $ eq_rel.1 hx) $ t.1.trans ht $ t.2 $ eq_rel.1 hy, λ h _ _ hs, let ⟨a, b, hx, hy, Hs⟩ := hs in ⟨a, b, hx, hy, h Hs⟩⟩ } end end section mul_one_class variables {M} [mul_one_class M] [mul_one_class N] [mul_one_class P] (c : con M) /-- The quotient of a monoid by a congruence relation is a monoid. -/ @[to_additive "The quotient of an `add_monoid` by an additive congruence relation is an `add_monoid`."] instance mul_one_class : mul_one_class c.quotient := { one := ((1 : M) : c.quotient), mul := (*), mul_one := λ x, quotient.induction_on' x $ λ _, congr_arg coe $ mul_one _, one_mul := λ x, quotient.induction_on' x $ λ _, congr_arg coe $ one_mul _ } variables {c} /-- The 1 of the quotient of a monoid by a congruence relation is the equivalence class of the monoid's 1. -/ @[simp, to_additive "The 0 of the quotient of an `add_monoid` by an additive congruence relation is the equivalence class of the `add_monoid`'s 0."] lemma coe_one : ((1 : M) : c.quotient) = 1 := rfl variables (M c) /-- The submonoid of `M × M` defined by a congruence relation on a monoid `M`. -/ @[to_additive "The `add_submonoid` of `M × M` defined by an additive congruence relation on an `add_monoid` `M`."] protected def submonoid : submonoid (M × M) := { carrier := { x | c x.1 x.2 }, one_mem' := c.iseqv.1 1, mul_mem' := λ _ _, c.mul } variables {M c} /-- The congruence relation on a monoid `M` from a submonoid of `M × M` for which membership is an equivalence relation. -/ @[to_additive "The additive congruence relation on an `add_monoid` `M` from an `add_submonoid` of `M × M` for which membership is an equivalence relation."] def of_submonoid (N : submonoid (M × M)) (H : equivalence (λ x y, (x, y) ∈ N)) : con M := { r := λ x y, (x, y) ∈ N, iseqv := H, mul' := λ _ _ _ _, N.mul_mem } /-- Coercion from a congruence relation `c` on a monoid `M` to the submonoid of `M × M` whose elements are `(x, y)` such that `x` is related to `y` by `c`. -/ @[to_additive "Coercion from a congruence relation `c` on an `add_monoid` `M` to the `add_submonoid` of `M × M` whose elements are `(x, y)` such that `x` is related to `y` by `c`."] instance to_submonoid : has_coe (con M) (submonoid (M × M)) := ⟨λ c, c.submonoid M⟩ @[to_additive] lemma mem_coe {c : con M} {x y} : (x, y) ∈ (↑c : submonoid (M × M)) ↔ (x, y) ∈ c := iff.rfl @[to_additive] theorem to_submonoid_inj (c d : con M) (H : (c : submonoid (M × M)) = d) : c = d := ext $ λ x y, show (x, y) ∈ (c : submonoid (M × M)) ↔ (x, y) ∈ ↑d, by rw H @[to_additive] lemma le_iff {c d : con M} : c ≤ d ↔ (c : submonoid (M × M)) ≤ d := ⟨λ h x H, h H, λ h x y hc, h $ show (x, y) ∈ c, from hc⟩ /-- The kernel of a monoid homomorphism as a congruence relation. -/ @[to_additive "The kernel of an `add_monoid` homomorphism as an additive congruence relation."] def ker (f : M →* P) : con M := mul_ker f f.3 /-- The definition of the congruence relation defined by a monoid homomorphism's kernel. -/ @[simp, to_additive "The definition of the additive congruence relation defined by an `add_monoid` homomorphism's kernel."] lemma ker_rel (f : M →* P) {x y} : ker f x y ↔ f x = f y := iff.rfl /-- There exists an element of the quotient of a monoid by a congruence relation (namely 1). -/ @[to_additive "There exists an element of the quotient of an `add_monoid` by a congruence relation (namely 0)."] instance quotient.inhabited : inhabited c.quotient := ⟨((1 : M) : c.quotient)⟩ variables (c) /-- The natural homomorphism from a monoid to its quotient by a congruence relation. -/ @[to_additive "The natural homomorphism from an `add_monoid` to its quotient by an additive congruence relation."] def mk' : M →* c.quotient := ⟨coe, rfl, λ _ _, rfl⟩ variables (x y : M) /-- The kernel of the natural homomorphism from a monoid to its quotient by a congruence relation `c` equals `c`. -/ @[simp, to_additive "The kernel of the natural homomorphism from an `add_monoid` to its quotient by an additive congruence relation `c` equals `c`."] lemma mk'_ker : ker c.mk' = c := ext $ λ _ _, c.eq variables {c} /-- The natural homomorphism from a monoid to its quotient by a congruence relation is surjective. -/ @[to_additive "The natural homomorphism from an `add_monoid` to its quotient by a congruence relation is surjective."] lemma mk'_surjective : surjective c.mk' := quotient.surjective_quotient_mk' @[simp, to_additive] lemma coe_mk' : (c.mk' : M → c.quotient) = coe := rfl /-- The elements related to `x ∈ M`, `M` a monoid, by the kernel of a monoid homomorphism are those in the preimage of `f(x)` under `f`. -/ @[to_additive "The elements related to `x ∈ M`, `M` an `add_monoid`, by the kernel of an `add_monoid` homomorphism are those in the preimage of `f(x)` under `f`. "] lemma ker_apply_eq_preimage {f : M →* P} (x) : (ker f) x = f ⁻¹' {f x} := set.ext $ λ x, ⟨λ h, set.mem_preimage.2 $ set.mem_singleton_iff.2 h.symm, λ h, (set.mem_singleton_iff.1 $ set.mem_preimage.1 h).symm⟩ /-- Given a monoid homomorphism `f : N → M` and a congruence relation `c` on `M`, the congruence relation induced on `N` by `f` equals the kernel of `c`'s quotient homomorphism composed with `f`. -/ @[to_additive "Given an `add_monoid` homomorphism `f : N → M` and an additive congruence relation `c` on `M`, the additive congruence relation induced on `N` by `f` equals the kernel of `c`'s quotient homomorphism composed with `f`."] lemma comap_eq {f : N →* M} : comap f f.map_mul c = ker (c.mk'.comp f) := ext $ λ x y, show c _ _ ↔ c.mk' _ = c.mk' _, by rw ←c.eq; refl variables (c) (f : M →* P) /-- The homomorphism on the quotient of a monoid by a congruence relation `c` induced by a homomorphism constant on `c`'s equivalence classes. -/ @[to_additive "The homomorphism on the quotient of an `add_monoid` by an additive congruence relation `c` induced by a homomorphism constant on `c`'s equivalence classes."] def lift (H : c ≤ ker f) : c.quotient →* P := { to_fun := λ x, con.lift_on x f $ λ _ _ h, H h, map_one' := by rw ←f.map_one; refl, map_mul' := λ x y, con.induction_on₂ x y $ λ m n, f.map_mul m n ▸ rfl } variables {c f} /-- The diagram describing the universal property for quotients of monoids commutes. -/ @[to_additive "The diagram describing the universal property for quotients of `add_monoid`s commutes."] lemma lift_mk' (H : c ≤ ker f) (x) : c.lift f H (c.mk' x) = f x := rfl /-- The diagram describing the universal property for quotients of monoids commutes. -/ @[simp, to_additive "The diagram describing the universal property for quotients of `add_monoid`s commutes."] lemma lift_coe (H : c ≤ ker f) (x : M) : c.lift f H x = f x := rfl /-- The diagram describing the universal property for quotients of monoids commutes. -/ @[simp, to_additive "The diagram describing the universal property for quotients of `add_monoid`s commutes."] theorem lift_comp_mk' (H : c ≤ ker f) : (c.lift f H).comp c.mk' = f := by ext; refl /-- Given a homomorphism `f` from the quotient of a monoid by a congruence relation, `f` equals the homomorphism on the quotient induced by `f` composed with the natural map from the monoid to the quotient. -/ @[simp, to_additive "Given a homomorphism `f` from the quotient of an `add_monoid` by an additive congruence relation, `f` equals the homomorphism on the quotient induced by `f` composed with the natural map from the `add_monoid` to the quotient."] lemma lift_apply_mk' (f : c.quotient →* P) : c.lift (f.comp c.mk') (λ x y h, show f ↑x = f ↑y, by rw c.eq.2 h) = f := by ext; rcases x; refl /-- Homomorphisms on the quotient of a monoid by a congruence relation are equal if they are equal on elements that are coercions from the monoid. -/ @[to_additive "Homomorphisms on the quotient of an `add_monoid` by an additive congruence relation are equal if they are equal on elements that are coercions from the `add_monoid`."] lemma lift_funext (f g : c.quotient →* P) (h : ∀ a : M, f a = g a) : f = g := begin rw [←lift_apply_mk' f, ←lift_apply_mk' g], congr' 1, exact monoid_hom.ext_iff.2 h, end /-- The uniqueness part of the universal property for quotients of monoids. -/ @[to_additive "The uniqueness part of the universal property for quotients of `add_monoid`s."] theorem lift_unique (H : c ≤ ker f) (g : c.quotient →* P) (Hg : g.comp c.mk' = f) : g = c.lift f H := lift_funext g (c.lift f H) $ λ x, by { subst f, refl } /-- Given a congruence relation `c` on a monoid and a homomorphism `f` constant on `c`'s equivalence classes, `f` has the same image as the homomorphism that `f` induces on the quotient. -/ @[to_additive "Given an additive congruence relation `c` on an `add_monoid` and a homomorphism `f` constant on `c`'s equivalence classes, `f` has the same image as the homomorphism that `f` induces on the quotient."] theorem lift_range (H : c ≤ ker f) : (c.lift f H).mrange = f.mrange := submonoid.ext $ λ x, ⟨by rintros ⟨⟨y⟩, hy⟩; exact ⟨y, hy⟩, λ ⟨y, hy⟩, ⟨↑y, hy⟩⟩ /-- Surjective monoid homomorphisms constant on a congruence relation `c`'s equivalence classes induce a surjective homomorphism on `c`'s quotient. -/ @[to_additive "Surjective `add_monoid` homomorphisms constant on an additive congruence relation `c`'s equivalence classes induce a surjective homomorphism on `c`'s quotient."] lemma lift_surjective_of_surjective (h : c ≤ ker f) (hf : surjective f) : surjective (c.lift f h) := λ y, exists.elim (hf y) $ λ w hw, ⟨w, (lift_mk' h w).symm ▸ hw⟩ variables (c f) /-- Given a monoid homomorphism `f` from `M` to `P`, the kernel of `f` is the unique congruence relation on `M` whose induced map from the quotient of `M` to `P` is injective. -/ @[to_additive "Given an `add_monoid` homomorphism `f` from `M` to `P`, the kernel of `f` is the unique additive congruence relation on `M` whose induced map from the quotient of `M` to `P` is injective."] lemma ker_eq_lift_of_injective (H : c ≤ ker f) (h : injective (c.lift f H)) : ker f = c := to_setoid_inj $ ker_eq_lift_of_injective f H h variables {c} /-- The homomorphism induced on the quotient of a monoid by the kernel of a monoid homomorphism. -/ @[to_additive "The homomorphism induced on the quotient of an `add_monoid` by the kernel of an `add_monoid` homomorphism."] def ker_lift : (ker f).quotient →* P := (ker f).lift f $ λ _ _, id variables {f} /-- The diagram described by the universal property for quotients of monoids, when the congruence relation is the kernel of the homomorphism, commutes. -/ @[simp, to_additive "The diagram described by the universal property for quotients of `add_monoid`s, when the additive congruence relation is the kernel of the homomorphism, commutes."] lemma ker_lift_mk (x : M) : ker_lift f x = f x := rfl /-- Given a monoid homomorphism `f`, the induced homomorphism on the quotient by `f`'s kernel has the same image as `f`. -/ @[simp, to_additive "Given an `add_monoid` homomorphism `f`, the induced homomorphism on the quotient by `f`'s kernel has the same image as `f`."] lemma ker_lift_range_eq : (ker_lift f).mrange = f.mrange := lift_range $ λ _ _, id /-- A monoid homomorphism `f` induces an injective homomorphism on the quotient by `f`'s kernel. -/ @[to_additive "An `add_monoid` homomorphism `f` induces an injective homomorphism on the quotient by `f`'s kernel."] lemma ker_lift_injective (f : M →* P) : injective (ker_lift f) := λ x y, quotient.induction_on₂' x y $ λ _ _, (ker f).eq.2 /-- Given congruence relations `c, d` on a monoid such that `d` contains `c`, `d`'s quotient map induces a homomorphism from the quotient by `c` to the quotient by `d`. -/ @[to_additive "Given additive congruence relations `c, d` on an `add_monoid` such that `d` contains `c`, `d`'s quotient map induces a homomorphism from the quotient by `c` to the quotient by `d`."] def map (c d : con M) (h : c ≤ d) : c.quotient →* d.quotient := c.lift d.mk' $ λ x y hc, show (ker d.mk') x y, from (mk'_ker d).symm ▸ h hc /-- Given congruence relations `c, d` on a monoid such that `d` contains `c`, the definition of the homomorphism from the quotient by `c` to the quotient by `d` induced by `d`'s quotient map. -/ @[to_additive "Given additive congruence relations `c, d` on an `add_monoid` such that `d` contains `c`, the definition of the homomorphism from the quotient by `c` to the quotient by `d` induced by `d`'s quotient map."] lemma map_apply {c d : con M} (h : c ≤ d) (x) : c.map d h x = c.lift d.mk' (λ x y hc, d.eq.2 $ h hc) x := rfl variables (c) /-- The first isomorphism theorem for monoids. -/ @[to_additive "The first isomorphism theorem for `add_monoid`s."] noncomputable def quotient_ker_equiv_range (f : M →* P) : (ker f).quotient ≃* f.mrange := { map_mul' := monoid_hom.map_mul _, ..equiv.of_bijective ((@mul_equiv.to_monoid_hom (ker_lift f).mrange _ _ _ $ mul_equiv.submonoid_congr ker_lift_range_eq).comp (ker_lift f).mrange_restrict) $ (equiv.bijective _).comp ⟨λ x y h, ker_lift_injective f $ by rcases x; rcases y; injections, λ ⟨w, z, hz⟩, ⟨z, by rcases hz; rcases _x; refl⟩⟩ } /-- The first isomorphism theorem for monoids in the case of a homomorphism with right inverse. -/ @[to_additive "The first isomorphism theorem for `add_monoid`s in the case of a homomorphism with right inverse.", simps] def quotient_ker_equiv_of_right_inverse (f : M →* P) (g : P → M) (hf : function.right_inverse g f) : (ker f).quotient ≃* P := { to_fun := ker_lift f, inv_fun := coe ∘ g, left_inv := λ x, ker_lift_injective _ (by rw [function.comp_app, ker_lift_mk, hf]), right_inv := hf, .. ker_lift f } /-- The first isomorphism theorem for monoids in the case of a surjective homomorphism. For a `computable` version, see `con.quotient_ker_equiv_of_right_inverse`. -/ @[to_additive "The first isomorphism theorem for `add_monoid`s in the case of a surjective homomorphism. For a `computable` version, see `add_con.quotient_ker_equiv_of_right_inverse`. "] noncomputable def quotient_ker_equiv_of_surjective (f : M →* P) (hf : surjective f) : (ker f).quotient ≃* P := quotient_ker_equiv_of_right_inverse _ _ hf.has_right_inverse.some_spec /-- The second isomorphism theorem for monoids. -/ @[to_additive "The second isomorphism theorem for `add_monoid`s."] noncomputable def comap_quotient_equiv (f : N →* M) : (comap f f.map_mul c).quotient ≃* (c.mk'.comp f).mrange := (con.congr comap_eq).trans $ quotient_ker_equiv_range $ c.mk'.comp f /-- The third isomorphism theorem for monoids. -/ @[to_additive "The third isomorphism theorem for `add_monoid`s."] def quotient_quotient_equiv_quotient (c d : con M) (h : c ≤ d) : (ker (c.map d h)).quotient ≃* d.quotient := { map_mul' := λ x y, con.induction_on₂ x y $ λ w z, con.induction_on₂ w z $ λ a b, show _ = d.mk' a * d.mk' b, by rw ←d.mk'.map_mul; refl, ..quotient_quotient_equiv_quotient c.to_setoid d.to_setoid h } end mul_one_class section monoids /-- The quotient of a monoid by a congruence relation is a monoid. -/ @[to_additive "The quotient of an `add_monoid` by an additive congruence relation is an `add_monoid`."] instance monoid {M : Type*} [monoid M] (c : con M): monoid c.quotient := { one := ((1 : M) : c.quotient), mul := (*), mul_assoc := λ x y z, quotient.induction_on₃' x y z $ λ _ _ _, congr_arg coe $ mul_assoc _ _ _, .. c.mul_one_class } /-- The quotient of a `comm_monoid` by a congruence relation is a `comm_monoid`. -/ @[to_additive "The quotient of an `add_comm_monoid` by an additive congruence relation is an `add_comm_monoid`."] instance comm_monoid {M : Type*} [comm_monoid M] (c : con M) : comm_monoid c.quotient := { mul_comm := λ x y, con.induction_on₂ x y $ λ w z, by rw [←coe_mul, ←coe_mul, mul_comm], ..c.monoid} end monoids section groups variables {M} [group M] [group N] [group P] (c : con M) /-- Multiplicative congruence relations preserve inversion. -/ @[to_additive "Additive congruence relations preserve negation."] protected lemma inv : ∀ {w x}, c w x → c w⁻¹ x⁻¹ := λ x y h, by simpa using c.symm (c.mul (c.mul (c.refl x⁻¹) h) (c.refl y⁻¹)) /-- The inversion induced on the quotient by a congruence relation on a type with a inversion. -/ @[to_additive "The negation induced on the quotient by an additive congruence relation on a type with an negation."] instance has_inv : has_inv c.quotient := ⟨λ x, quotient.lift_on' x (λ w, ((w⁻¹ : M) : c.quotient)) $ λ x y h, c.eq.2 $ c.inv h⟩ /-- The quotient of a group by a congruence relation is a group. -/ @[to_additive "The quotient of an `add_group` by an additive congruence relation is an `add_group`."] instance group : group c.quotient := { inv := λ x, x⁻¹, mul_left_inv := λ x, show x⁻¹ * x = 1, from quotient.induction_on' x $ λ _, congr_arg coe $ mul_left_inv _, .. con.monoid c} end groups section units variables {α : Type*} [monoid M] {c : con M} /-- In order to define a function `units (con.quotient c) → α` on the units of `con.quotient c`, where `c : con M` is a multiplicative congruence on a monoid, it suffices to define a function `f` that takes elements `x y : M` with proofs of `c (x * y) 1` and `c (y * x) 1`, and returns an element of `α` provided that `f x y _ _ = f x' y' _ _` whenever `c x x'` and `c y y'`. -/ @[to_additive lift_on_add_units] def lift_on_units (u : units c.quotient) (f : Π (x y : M), c (x * y) 1 → c (y * x) 1 → α) (Hf : ∀ x y hxy hyx x' y' hxy' hyx', c x x' → c y y' → f x y hxy hyx = f x' y' hxy' hyx') : α := begin refine @con.hrec_on₂ M M _ _ c c (λ x y, x * y = 1 → y * x = 1 → α) (u : c.quotient) (↑u⁻¹ : c.quotient) (λ (x y : M) (hxy : (x * y : c.quotient) = 1) (hyx : (y * x : c.quotient) = 1), f x y (c.eq.1 hxy) (c.eq.1 hyx)) (λ x y x' y' hx hy, _) u.3 u.4, ext1, { rw [c.eq.2 hx, c.eq.2 hy] }, rintro Hxy Hxy' -, ext1, { rw [c.eq.2 hx, c.eq.2 hy] }, rintro Hyx Hyx' -, exact heq_of_eq (Hf _ _ _ _ _ _ _ _ hx hy) end /-- In order to define a function `units (con.quotient c) → α` on the units of `con.quotient c`, where `c : con M` is a multiplicative congruence on a monoid, it suffices to define a function `f` that takes elements `x y : M` with proofs of `c (x * y) 1` and `c (y * x) 1`, and returns an element of `α` provided that `f x y _ _ = f x' y' _ _` whenever `c x x'` and `c y y'`. -/ add_decl_doc add_con.lift_on_add_units @[simp, to_additive] lemma lift_on_units_mk (f : Π (x y : M), c (x * y) 1 → c (y * x) 1 → α) (Hf : ∀ x y hxy hyx x' y' hxy' hyx', c x x' → c y y' → f x y hxy hyx = f x' y' hxy' hyx') (x y : M) (hxy hyx) : lift_on_units ⟨(x : c.quotient), y, hxy, hyx⟩ f Hf = f x y (c.eq.1 hxy) (c.eq.1 hyx) := rfl @[elab_as_eliminator, to_additive induction_on_add_units] lemma induction_on_units {p : units c.quotient → Prop} (u : units c.quotient) (H : ∀ (x y : M) (hxy : c (x * y) 1) (hyx : c (y * x) 1), p ⟨x, y, c.eq.2 hxy, c.eq.2 hyx⟩) : p u := begin rcases u with ⟨⟨x⟩, ⟨y⟩, h₁, h₂⟩, exact H x y (c.eq.1 h₁) (c.eq.1 h₂) end end units end con
34cb1363b4f8842184d9fe6422b91d65d7393242
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/big_operators/order.lean
8c7030a2ecf0325a357c9936182f5816bdaf3581
[ "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
27,789
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import algebra.order.absolute_value import algebra.big_operators.basic /-! # Results about big operators with values in an ordered algebraic structure. Mostly monotonicity results for the `∏` and `∑` operations. -/ open function open_locale big_operators variables {ι α β M N G k R : Type*} namespace finset section ordered_comm_monoid variables [comm_monoid M] [ordered_comm_monoid N] /-- Let `{x | p x}` be a subsemigroup of a commutative monoid `M`. Let `f : M → N` be a map submultiplicative on `{x | p x}`, i.e., `p x → p y → f (x * y) ≤ f x * f y`. Let `g i`, `i ∈ s`, be a nonempty finite family of elements of `M` such that `∀ i ∈ s, p (g i)`. Then `f (∏ x in s, g x) ≤ ∏ x in s, f (g x)`. -/ @[to_additive le_sum_nonempty_of_subadditive_on_pred] lemma le_prod_nonempty_of_submultiplicative_on_pred (f : M → N) (p : M → Prop) (h_mul : ∀ x y, p x → p y → f (x * y) ≤ f x * f y) (hp_mul : ∀ x y, p x → p y → p (x * y)) (g : ι → M) (s : finset ι) (hs_nonempty : s.nonempty) (hs : ∀ i ∈ s, p (g i)) : f (∏ i in s, g i) ≤ ∏ i in s, f (g i) := begin refine le_trans (multiset.le_prod_nonempty_of_submultiplicative_on_pred f p h_mul hp_mul _ _ _) _, { simp [hs_nonempty.ne_empty], }, { exact multiset.forall_mem_map_iff.mpr hs, }, rw multiset.map_map, refl, end /-- Let `{x | p x}` be an additive subsemigroup of an additive commutative monoid `M`. Let `f : M → N` be a map subadditive on `{x | p x}`, i.e., `p x → p y → f (x + y) ≤ f x + f y`. Let `g i`, `i ∈ s`, be a nonempty finite family of elements of `M` such that `∀ i ∈ s, p (g i)`. Then `f (∑ i in s, g i) ≤ ∑ i in s, f (g i)`. -/ add_decl_doc le_sum_nonempty_of_subadditive_on_pred /-- If `f : M → N` is a submultiplicative function, `f (x * y) ≤ f x * f y` and `g i`, `i ∈ s`, is a nonempty finite family of elements of `M`, then `f (∏ i in s, g i) ≤ ∏ i in s, f (g i)`. -/ @[to_additive le_sum_nonempty_of_subadditive] lemma le_prod_nonempty_of_submultiplicative (f : M → N) (h_mul : ∀ x y, f (x * y) ≤ f x * f y) {s : finset ι} (hs : s.nonempty) (g : ι → M) : f (∏ i in s, g i) ≤ ∏ i in s, f (g i) := le_prod_nonempty_of_submultiplicative_on_pred f (λ i, true) (λ x y _ _, h_mul x y) (λ _ _ _ _, trivial) g s hs (λ _ _, trivial) /-- If `f : M → N` is a subadditive function, `f (x + y) ≤ f x + f y` and `g i`, `i ∈ s`, is a nonempty finite family of elements of `M`, then `f (∑ i in s, g i) ≤ ∑ i in s, f (g i)`. -/ add_decl_doc le_sum_nonempty_of_subadditive /-- Let `{x | p x}` be a subsemigroup of a commutative monoid `M`. Let `f : M → N` be a map such that `f 1 = 1` and `f` is submultiplicative on `{x | p x}`, i.e., `p x → p y → f (x * y) ≤ f x * f y`. Let `g i`, `i ∈ s`, be a finite family of elements of `M` such that `∀ i ∈ s, p (g i)`. Then `f (∏ i in s, g i) ≤ ∏ i in s, f (g i)`. -/ @[to_additive le_sum_of_subadditive_on_pred] lemma le_prod_of_submultiplicative_on_pred (f : M → N) (p : M → Prop) (h_one : f 1 = 1) (h_mul : ∀ x y, p x → p y → f (x * y) ≤ f x * f y) (hp_mul : ∀ x y, p x → p y → p (x * y)) (g : ι → M) {s : finset ι} (hs : ∀ i ∈ s, p (g i)) : f (∏ i in s, g i) ≤ ∏ i in s, f (g i) := begin rcases eq_empty_or_nonempty s with rfl|hs_nonempty, { simp [h_one] }, { exact le_prod_nonempty_of_submultiplicative_on_pred f p h_mul hp_mul g s hs_nonempty hs, }, end /-- Let `{x | p x}` be a subsemigroup of a commutative additive monoid `M`. Let `f : M → N` be a map such that `f 0 = 0` and `f` is subadditive on `{x | p x}`, i.e. `p x → p y → f (x + y) ≤ f x + f y`. Let `g i`, `i ∈ s`, be a finite family of elements of `M` such that `∀ i ∈ s, p (g i)`. Then `f (∑ x in s, g x) ≤ ∑ x in s, f (g x)`. -/ add_decl_doc le_sum_of_subadditive_on_pred /-- If `f : M → N` is a submultiplicative function, `f (x * y) ≤ f x * f y`, `f 1 = 1`, and `g i`, `i ∈ s`, is a finite family of elements of `M`, then `f (∏ i in s, g i) ≤ ∏ i in s, f (g i)`. -/ @[to_additive le_sum_of_subadditive] lemma le_prod_of_submultiplicative (f : M → N) (h_one : f 1 = 1) (h_mul : ∀ x y, f (x * y) ≤ f x * f y) (s : finset ι) (g : ι → M) : f (∏ i in s, g i) ≤ ∏ i in s, f (g i) := begin refine le_trans (multiset.le_prod_of_submultiplicative f h_one h_mul _) _, rw multiset.map_map, refl, end /-- If `f : M → N` is a subadditive function, `f (x + y) ≤ f x + f y`, `f 0 = 0`, and `g i`, `i ∈ s`, is a finite family of elements of `M`, then `f (∑ i in s, g i) ≤ ∑ i in s, f (g i)`. -/ add_decl_doc le_sum_of_subadditive variables {f g : ι → N} {s t : finset ι} /-- In an ordered commutative monoid, if each factor `f i` of one finite product is less than or equal to the corresponding factor `g i` of another finite product, then `∏ i in s, f i ≤ ∏ i in s, g i`. -/ @[to_additive sum_le_sum] lemma prod_le_prod'' (h : ∀ i ∈ s, f i ≤ g i) : ∏ i in s, f i ≤ ∏ i in s, g i := begin classical, induction s using finset.induction_on with i s hi ihs h, { refl }, { simp only [prod_insert hi], exact mul_le_mul' (h _ (mem_insert_self _ _)) (ihs $ λ j hj, h j (mem_insert_of_mem hj)) } end /-- In an ordered additive commutative monoid, if each summand `f i` of one finite sum is less than or equal to the corresponding summand `g i` of another finite sum, then `∑ i in s, f i ≤ ∑ i in s, g i`. -/ add_decl_doc sum_le_sum @[to_additive sum_nonneg] lemma one_le_prod' (h : ∀i ∈ s, 1 ≤ f i) : 1 ≤ (∏ i in s, f i) := le_trans (by rw prod_const_one) (prod_le_prod'' h) @[to_additive finset.sum_nonneg'] lemma one_le_prod'' (h : ∀ (i : ι), 1 ≤ f i) : 1 ≤ ∏ (i : ι) in s, f i := finset.one_le_prod' (λ i hi, h i) @[to_additive sum_nonpos] lemma prod_le_one' (h : ∀i ∈ s, f i ≤ 1) : (∏ i in s, f i) ≤ 1 := (prod_le_prod'' h).trans_eq (by rw prod_const_one) @[to_additive sum_le_sum_of_subset_of_nonneg] lemma prod_le_prod_of_subset_of_one_le' (h : s ⊆ t) (hf : ∀ i ∈ t, i ∉ s → 1 ≤ f i) : ∏ i in s, f i ≤ ∏ i in t, f i := by classical; calc (∏ i in s, f i) ≤ (∏ i in t \ s, f i) * (∏ i in s, f i) : le_mul_of_one_le_left' $ one_le_prod' $ by simpa only [mem_sdiff, and_imp] ... = ∏ i in t \ s ∪ s, f i : (prod_union sdiff_disjoint).symm ... = ∏ i in t, f i : by rw [sdiff_union_of_subset h] @[to_additive sum_mono_set_of_nonneg] lemma prod_mono_set_of_one_le' (hf : ∀ x, 1 ≤ f x) : monotone (λ s, ∏ x in s, f x) := λ s t hst, prod_le_prod_of_subset_of_one_le' hst $ λ x _ _, hf x @[to_additive sum_le_univ_sum_of_nonneg] lemma prod_le_univ_prod_of_one_le' [fintype ι] {s : finset ι} (w : ∀ x, 1 ≤ f x) : ∏ x in s, f x ≤ ∏ x, f x := prod_le_prod_of_subset_of_one_le' (subset_univ s) (λ a _ _, w a) @[to_additive sum_eq_zero_iff_of_nonneg] lemma prod_eq_one_iff_of_one_le' : (∀ i ∈ s, 1 ≤ f i) → (∏ i in s, f i = 1 ↔ ∀ i ∈ s, f i = 1) := begin classical, apply finset.induction_on s, exact λ _, ⟨λ _ _, false.elim, λ _, rfl⟩, assume a s ha ih H, have : ∀ i ∈ s, 1 ≤ f i, from λ _, H _ ∘ mem_insert_of_mem, rw [prod_insert ha, mul_eq_one_iff' (H _ $ mem_insert_self _ _) (one_le_prod' this), forall_mem_insert, ih this] end @[to_additive sum_eq_zero_iff_of_nonneg] lemma prod_eq_one_iff_of_le_one' : (∀ i ∈ s, f i ≤ 1) → (∏ i in s, f i = 1 ↔ ∀ i ∈ s, f i = 1) := @prod_eq_one_iff_of_one_le' _ Nᵒᵈ _ _ _ @[to_additive single_le_sum] lemma single_le_prod' (hf : ∀ i ∈ s, 1 ≤ f i) {a} (h : a ∈ s) : f a ≤ (∏ x in s, f x) := calc f a = ∏ i in {a}, f i : prod_singleton.symm ... ≤ ∏ i in s, f i : prod_le_prod_of_subset_of_one_le' (singleton_subset_iff.2 h) $ λ i hi _, hf i hi @[to_additive sum_le_card_nsmul] lemma prod_le_pow_card (s : finset ι) (f : ι → N) (n : N) (h : ∀ x ∈ s, f x ≤ n) : s.prod f ≤ n ^ s.card := begin refine (multiset.prod_le_pow_card (s.val.map f) n _).trans _, { simpa using h }, { simpa } end @[to_additive card_nsmul_le_sum] lemma pow_card_le_prod (s : finset ι) (f : ι → N) (n : N) (h : ∀ x ∈ s, n ≤ f x) : n ^ s.card ≤ s.prod f := @finset.prod_le_pow_card _ Nᵒᵈ _ _ _ _ h lemma card_bUnion_le_card_mul [decidable_eq β] (s : finset ι) (f : ι → finset β) (n : ℕ) (h : ∀ a ∈ s, (f a).card ≤ n) : (s.bUnion f).card ≤ s.card * n := card_bUnion_le.trans $ sum_le_card_nsmul _ _ _ h variables {ι' : Type*} [decidable_eq ι'] @[to_additive sum_fiberwise_le_sum_of_sum_fiber_nonneg] lemma prod_fiberwise_le_prod_of_one_le_prod_fiber' {t : finset ι'} {g : ι → ι'} {f : ι → N} (h : ∀ y ∉ t, (1 : N) ≤ ∏ x in s.filter (λ x, g x = y), f x) : ∏ y in t, ∏ x in s.filter (λ x, g x = y), f x ≤ ∏ x in s, f x := calc (∏ y in t, ∏ x in s.filter (λ x, g x = y), f x) ≤ (∏ y in t ∪ s.image g, ∏ x in s.filter (λ x, g x = y), f x) : prod_le_prod_of_subset_of_one_le' (subset_union_left _ _) $ λ y hyts, h y ... = ∏ x in s, f x : prod_fiberwise_of_maps_to (λ x hx, mem_union.2 $ or.inr $ mem_image_of_mem _ hx) _ @[to_additive sum_le_sum_fiberwise_of_sum_fiber_nonpos] lemma prod_le_prod_fiberwise_of_prod_fiber_le_one' {t : finset ι'} {g : ι → ι'} {f : ι → N} (h : ∀ y ∉ t, (∏ x in s.filter (λ x, g x = y), f x) ≤ 1) : (∏ x in s, f x) ≤ ∏ y in t, ∏ x in s.filter (λ x, g x = y), f x := @prod_fiberwise_le_prod_of_one_le_prod_fiber' _ Nᵒᵈ _ _ _ _ _ _ _ h end ordered_comm_monoid lemma abs_sum_le_sum_abs {G : Type*} [linear_ordered_add_comm_group G] (f : ι → G) (s : finset ι) : |∑ i in s, f i| ≤ ∑ i in s, |f i| := le_sum_of_subadditive _ abs_zero abs_add s f lemma abs_sum_of_nonneg {G : Type*} [linear_ordered_add_comm_group G] {f : ι → G} {s : finset ι} (hf : ∀ i ∈ s, 0 ≤ f i) : |∑ (i : ι) in s, f i| = ∑ (i : ι) in s, f i := by rw abs_of_nonneg (finset.sum_nonneg hf) lemma abs_sum_of_nonneg' {G : Type*} [linear_ordered_add_comm_group G] {f : ι → G} {s : finset ι} (hf : ∀ i, 0 ≤ f i) : |∑ (i : ι) in s, f i| = ∑ (i : ι) in s, f i := by rw abs_of_nonneg (finset.sum_nonneg' hf) lemma abs_prod {R : Type*} [linear_ordered_comm_ring R] {f : ι → R} {s : finset ι} : |∏ x in s, f x| = ∏ x in s, |f x| := (abs_hom.to_monoid_hom : R →* R).map_prod _ _ section pigeonhole variable [decidable_eq β] theorem card_le_mul_card_image_of_maps_to {f : α → β} {s : finset α} {t : finset β} (Hf : ∀ a ∈ s, f a ∈ t) (n : ℕ) (hn : ∀ a ∈ t, (s.filter (λ x, f x = a)).card ≤ n) : s.card ≤ n * t.card := calc s.card = (∑ a in t, (s.filter (λ x, f x = a)).card) : card_eq_sum_card_fiberwise Hf ... ≤ (∑ _ in t, n) : sum_le_sum hn ... = _ : by simp [mul_comm] theorem card_le_mul_card_image {f : α → β} (s : finset α) (n : ℕ) (hn : ∀ a ∈ s.image f, (s.filter (λ x, f x = a)).card ≤ n) : s.card ≤ n * (s.image f).card := card_le_mul_card_image_of_maps_to (λ x, mem_image_of_mem _) n hn theorem mul_card_image_le_card_of_maps_to {f : α → β} {s : finset α} {t : finset β} (Hf : ∀ a ∈ s, f a ∈ t) (n : ℕ) (hn : ∀ a ∈ t, n ≤ (s.filter (λ x, f x = a)).card) : n * t.card ≤ s.card := calc n * t.card = (∑ _ in t, n) : by simp [mul_comm] ... ≤ (∑ a in t, (s.filter (λ x, f x = a)).card) : sum_le_sum hn ... = s.card : by rw ← card_eq_sum_card_fiberwise Hf theorem mul_card_image_le_card {f : α → β} (s : finset α) (n : ℕ) (hn : ∀ a ∈ s.image f, n ≤ (s.filter (λ x, f x = a)).card) : n * (s.image f).card ≤ s.card := mul_card_image_le_card_of_maps_to (λ x, mem_image_of_mem _) n hn end pigeonhole section double_counting variables [decidable_eq α] {s : finset α} {B : finset (finset α)} {n : ℕ} /-- If every element belongs to at most `n` finsets, then the sum of their sizes is at most `n` times how many they are. -/ lemma sum_card_inter_le (h : ∀ a ∈ s, (B.filter $ (∈) a).card ≤ n) : ∑ t in B, (s ∩ t).card ≤ s.card * n := begin refine le_trans _ (s.sum_le_card_nsmul _ _ h), simp_rw [←filter_mem_eq_inter, card_eq_sum_ones, sum_filter], exact sum_comm.le, end /-- If every element belongs to at most `n` finsets, then the sum of their sizes is at most `n` times how many they are. -/ lemma sum_card_le [fintype α] (h : ∀ a, (B.filter $ (∈) a).card ≤ n) : ∑ s in B, s.card ≤ fintype.card α * n := calc ∑ s in B, s.card = ∑ s in B, (univ ∩ s).card : by simp_rw univ_inter ... ≤ fintype.card α * n : sum_card_inter_le (λ a _, h a) /-- If every element belongs to at least `n` finsets, then the sum of their sizes is at least `n` times how many they are. -/ lemma le_sum_card_inter (h : ∀ a ∈ s, n ≤ (B.filter $ (∈) a).card) : s.card * n ≤ ∑ t in B, (s ∩ t).card := begin apply (s.card_nsmul_le_sum _ _ h).trans, simp_rw [←filter_mem_eq_inter, card_eq_sum_ones, sum_filter], exact sum_comm.le, end /-- If every element belongs to at least `n` finsets, then the sum of their sizes is at least `n` times how many they are. -/ lemma le_sum_card [fintype α] (h : ∀ a, n ≤ (B.filter $ (∈) a).card) : fintype.card α * n ≤ ∑ s in B, s.card := calc fintype.card α * n ≤ ∑ s in B, (univ ∩ s).card : le_sum_card_inter (λ a _, h a) ... = ∑ s in B, s.card : by simp_rw univ_inter /-- If every element belongs to exactly `n` finsets, then the sum of their sizes is `n` times how many they are. -/ lemma sum_card_inter (h : ∀ a ∈ s, (B.filter $ (∈) a).card = n) : ∑ t in B, (s ∩ t).card = s.card * n := (sum_card_inter_le $ λ a ha, (h a ha).le).antisymm (le_sum_card_inter $ λ a ha, (h a ha).ge) /-- If every element belongs to exactly `n` finsets, then the sum of their sizes is `n` times how many they are. -/ lemma sum_card [fintype α] (h : ∀ a, (B.filter $ (∈) a).card = n) : ∑ s in B, s.card = fintype.card α * n := by simp_rw [fintype.card, ←sum_card_inter (λ a _, h a), univ_inter] lemma card_le_card_bUnion {s : finset ι} {f : ι → finset α} (hs : (s : set ι).pairwise_disjoint f) (hf : ∀ i ∈ s, (f i).nonempty) : s.card ≤ (s.bUnion f).card := by { rw [card_bUnion hs, card_eq_sum_ones], exact sum_le_sum (λ i hi, (hf i hi).card_pos) } lemma card_le_card_bUnion_add_card_fiber {s : finset ι} {f : ι → finset α} (hs : (s : set ι).pairwise_disjoint f) : s.card ≤ (s.bUnion f).card + (s.filter $ λ i, f i = ∅).card := begin rw [←finset.filter_card_add_filter_neg_card_eq_card (λ i, f i = ∅), add_comm], exact add_le_add_right ((card_le_card_bUnion (hs.subset $ filter_subset _ _) $ λ i hi, nonempty_of_ne_empty $ (mem_filter.1 hi).2).trans $ card_le_of_subset $ bUnion_subset_bUnion_of_subset_left _ $ filter_subset _ _) _, end lemma card_le_card_bUnion_add_one {s : finset ι} {f : ι → finset α} (hf : injective f) (hs : (s : set ι).pairwise_disjoint f) : s.card ≤ (s.bUnion f).card + 1 := (card_le_card_bUnion_add_card_fiber hs).trans $ add_le_add_left (card_le_one.2 $ λ i hi j hj, hf $ (mem_filter.1 hi).2.trans (mem_filter.1 hj).2.symm) _ end double_counting section canonically_ordered_monoid variables [canonically_ordered_monoid M] {f : ι → M} {s t : finset ι} @[simp, to_additive sum_eq_zero_iff] lemma prod_eq_one_iff' : ∏ x in s, f x = 1 ↔ ∀ x ∈ s, f x = 1 := prod_eq_one_iff_of_one_le' $ λ x hx, one_le (f x) @[to_additive sum_le_sum_of_subset] lemma prod_le_prod_of_subset' (h : s ⊆ t) : ∏ x in s, f x ≤ ∏ x in t, f x := prod_le_prod_of_subset_of_one_le' h $ assume x h₁ h₂, one_le _ @[to_additive sum_mono_set] lemma prod_mono_set' (f : ι → M) : monotone (λ s, ∏ x in s, f x) := λ s₁ s₂ hs, prod_le_prod_of_subset' hs @[to_additive sum_le_sum_of_ne_zero] lemma prod_le_prod_of_ne_one' (h : ∀ x ∈ s, f x ≠ 1 → x ∈ t) : ∏ x in s, f x ≤ ∏ x in t, f x := by classical; calc ∏ x in s, f x = (∏ x in s.filter (λ x, f x = 1), f x) * ∏ x in s.filter (λ x, f x ≠ 1), f x : by rw [← prod_union, filter_union_filter_neg_eq]; exact disjoint_filter.2 (assume _ _ h n_h, n_h h) ... ≤ (∏ x in t, f x) : mul_le_of_le_one_of_le (prod_le_one' $ by simp only [mem_filter, and_imp]; exact λ _ _, le_of_eq) (prod_le_prod_of_subset' $ by simpa only [subset_iff, mem_filter, and_imp]) end canonically_ordered_monoid section ordered_cancel_comm_monoid variables [ordered_cancel_comm_monoid M] {f g : ι → M} {s t : finset ι} @[to_additive sum_lt_sum] theorem prod_lt_prod' (Hle : ∀ i ∈ s, f i ≤ g i) (Hlt : ∃ i ∈ s, f i < g i) : ∏ i in s, f i < ∏ i in s, g i := begin classical, rcases Hlt with ⟨i, hi, hlt⟩, rw [← insert_erase hi, prod_insert (not_mem_erase _ _), prod_insert (not_mem_erase _ _)], exact mul_lt_mul_of_lt_of_le hlt (prod_le_prod'' $ λ j hj, Hle j $ mem_of_mem_erase hj) end @[to_additive sum_lt_sum_of_nonempty] lemma prod_lt_prod_of_nonempty' (hs : s.nonempty) (Hlt : ∀ i ∈ s, f i < g i) : ∏ i in s, f i < ∏ i in s, g i := begin apply prod_lt_prod', { intros i hi, apply le_of_lt (Hlt i hi) }, cases hs with i hi, exact ⟨i, hi, Hlt i hi⟩, end @[to_additive sum_lt_sum_of_subset] lemma prod_lt_prod_of_subset' (h : s ⊆ t) {i : ι} (ht : i ∈ t) (hs : i ∉ s) (hlt : 1 < f i) (hle : ∀ j ∈ t, j ∉ s → 1 ≤ f j) : ∏ j in s, f j < ∏ j in t, f j := by classical; calc ∏ j in s, f j < ∏ j in insert i s, f j : begin rw prod_insert hs, exact lt_mul_of_one_lt_left' (∏ j in s, f j) hlt, end ... ≤ ∏ j in t, f j : begin apply prod_le_prod_of_subset_of_one_le', { simp [finset.insert_subset, h, ht] }, { assume x hx h'x, simp only [mem_insert, not_or_distrib] at h'x, exact hle x hx h'x.2 } end @[to_additive single_lt_sum] lemma single_lt_prod' {i j : ι} (hij : j ≠ i) (hi : i ∈ s) (hj : j ∈ s) (hlt : 1 < f j) (hle : ∀ k ∈ s, k ≠ i → 1 ≤ f k) : f i < ∏ k in s, f k := calc f i = ∏ k in {i}, f k : prod_singleton.symm ... < ∏ k in s, f k : prod_lt_prod_of_subset' (singleton_subset_iff.2 hi) hj (mt mem_singleton.1 hij) hlt $ λ k hks hki, hle k hks (mt mem_singleton.2 hki) @[to_additive sum_pos] lemma one_lt_prod (h : ∀i ∈ s, 1 < f i) (hs : s.nonempty) : 1 < (∏ i in s, f i) := lt_of_le_of_lt (by rw prod_const_one) $ prod_lt_prod_of_nonempty' hs h @[to_additive] lemma prod_lt_one (h : ∀i ∈ s, f i < 1) (hs : s.nonempty) : (∏ i in s, f i) < 1 := (prod_lt_prod_of_nonempty' hs h).trans_le (by rw prod_const_one) @[to_additive] lemma prod_eq_prod_iff_of_le {f g : ι → M} (h : ∀ i ∈ s, f i ≤ g i) : ∏ i in s, f i = ∏ i in s, g i ↔ ∀ i ∈ s, f i = g i := begin classical, revert h, refine finset.induction_on s (λ _, ⟨λ _ _, false.elim, λ _, rfl⟩) (λ a s ha ih H, _), specialize ih (λ i, H i ∘ finset.mem_insert_of_mem), rw [finset.prod_insert ha, finset.prod_insert ha, finset.forall_mem_insert, ←ih], exact mul_eq_mul_iff_eq_and_eq (H a (s.mem_insert_self a)) (finset.prod_le_prod'' (λ i, H i ∘ finset.mem_insert_of_mem)), end end ordered_cancel_comm_monoid section linear_ordered_cancel_comm_monoid variables [linear_ordered_cancel_comm_monoid M] {f g : ι → M} {s t : finset ι} @[to_additive exists_lt_of_sum_lt] theorem exists_lt_of_prod_lt' (Hlt : ∏ i in s, f i < ∏ i in s, g i) : ∃ i ∈ s, f i < g i := begin contrapose! Hlt with Hle, exact prod_le_prod'' Hle end @[to_additive exists_le_of_sum_le] theorem exists_le_of_prod_le' (hs : s.nonempty) (Hle : ∏ i in s, f i ≤ ∏ i in s, g i) : ∃ i ∈ s, f i ≤ g i := begin contrapose! Hle with Hlt, exact prod_lt_prod_of_nonempty' hs Hlt end @[to_additive exists_pos_of_sum_zero_of_exists_nonzero] lemma exists_one_lt_of_prod_one_of_exists_ne_one' (f : ι → M) (h₁ : ∏ i in s, f i = 1) (h₂ : ∃ i ∈ s, f i ≠ 1) : ∃ i ∈ s, 1 < f i := begin contrapose! h₁, obtain ⟨i, m, i_ne⟩ : ∃ i ∈ s, f i ≠ 1 := h₂, apply ne_of_lt, calc ∏ j in s, f j < ∏ j in s, 1 : prod_lt_prod' h₁ ⟨i, m, (h₁ i m).lt_of_ne i_ne⟩ ... = 1 : prod_const_one end end linear_ordered_cancel_comm_monoid section ordered_comm_semiring variables [ordered_comm_semiring R] {f g : ι → R} {s t : finset ι} open_locale classical /- this is also true for a ordered commutative multiplicative monoid -/ lemma prod_nonneg (h0 : ∀ i ∈ s, 0 ≤ f i) : 0 ≤ ∏ i in s, f i := prod_induction f (λ i, 0 ≤ i) (λ _ _ ha hb, mul_nonneg ha hb) zero_le_one h0 /- this is also true for a ordered commutative multiplicative monoid -/ lemma prod_pos [nontrivial R] (h0 : ∀ i ∈ s, 0 < f i) : 0 < ∏ i in s, f i := prod_induction f (λ x, 0 < x) (λ _ _ ha hb, mul_pos ha hb) zero_lt_one h0 /-- If all `f i`, `i ∈ s`, are nonnegative and each `f i` is less than or equal to `g i`, then the product of `f i` is less than or equal to the product of `g i`. See also `finset.prod_le_prod''` for the case of an ordered commutative multiplicative monoid. -/ lemma prod_le_prod (h0 : ∀ i ∈ s, 0 ≤ f i) (h1 : ∀ i ∈ s, f i ≤ g i) : ∏ i in s, f i ≤ ∏ i in s, g i := begin induction s using finset.induction with a s has ih h, { simp }, { simp only [prod_insert has], apply mul_le_mul, { exact h1 a (mem_insert_self a s) }, { apply ih (λ x H, h0 _ _) (λ x H, h1 _ _); exact (mem_insert_of_mem H) }, { apply prod_nonneg (λ x H, h0 x (mem_insert_of_mem H)) }, { apply le_trans (h0 a (mem_insert_self a s)) (h1 a (mem_insert_self a s)) } } end /-- If each `f i`, `i ∈ s` belongs to `[0, 1]`, then their product is less than or equal to one. See also `finset.prod_le_one'` for the case of an ordered commutative multiplicative monoid. -/ lemma prod_le_one (h0 : ∀ i ∈ s, 0 ≤ f i) (h1 : ∀ i ∈ s, f i ≤ 1) : ∏ i in s, f i ≤ 1 := begin convert ← prod_le_prod h0 h1, exact finset.prod_const_one end /-- If `g, h ≤ f` and `g i + h i ≤ f i`, then the product of `f` over `s` is at least the sum of the products of `g` and `h`. This is the version for `ordered_comm_semiring`. -/ lemma prod_add_prod_le {i : ι} {f g h : ι → R} (hi : i ∈ s) (h2i : g i + h i ≤ f i) (hgf : ∀ j ∈ s, j ≠ i → g j ≤ f j) (hhf : ∀ j ∈ s, j ≠ i → h j ≤ f j) (hg : ∀ i ∈ s, 0 ≤ g i) (hh : ∀ i ∈ s, 0 ≤ h i) : ∏ i in s, g i + ∏ i in s, h i ≤ ∏ i in s, f i := begin simp_rw [prod_eq_mul_prod_diff_singleton hi], refine le_trans _ (mul_le_mul_of_nonneg_right h2i _), { rw [right_distrib], apply add_le_add; apply mul_le_mul_of_nonneg_left; try { apply_assumption; assumption }; apply prod_le_prod; simp * { contextual := tt } }, { apply prod_nonneg, simp only [and_imp, mem_sdiff, mem_singleton], intros j h1j h2j, exact le_trans (hg j h1j) (hgf j h1j h2j) } end end ordered_comm_semiring section canonically_ordered_comm_semiring variables [canonically_ordered_comm_semiring R] {f g h : ι → R} {s : finset ι} {i : ι} lemma prod_le_prod' (h : ∀ i ∈ s, f i ≤ g i) : ∏ i in s, f i ≤ ∏ i in s, g i := begin classical, induction s using finset.induction with a s has ih h, { simp }, { rw [finset.prod_insert has, finset.prod_insert has], apply mul_le_mul', { exact h _ (finset.mem_insert_self a s) }, { exact ih (λ i hi, h _ (finset.mem_insert_of_mem hi)) } } end /-- If `g, h ≤ f` and `g i + h i ≤ f i`, then the product of `f` over `s` is at least the sum of the products of `g` and `h`. This is the version for `canonically_ordered_comm_semiring`. -/ lemma prod_add_prod_le' (hi : i ∈ s) (h2i : g i + h i ≤ f i) (hgf : ∀ j ∈ s, j ≠ i → g j ≤ f j) (hhf : ∀ j ∈ s, j ≠ i → h j ≤ f j) : ∏ i in s, g i + ∏ i in s, h i ≤ ∏ i in s, f i := begin classical, simp_rw [prod_eq_mul_prod_diff_singleton hi], refine le_trans _ (mul_le_mul_right' h2i _), rw [right_distrib], apply add_le_add; apply mul_le_mul_left'; apply prod_le_prod'; simp only [and_imp, mem_sdiff, mem_singleton]; intros; apply_assumption; assumption end end canonically_ordered_comm_semiring end finset namespace fintype variables [fintype ι] @[to_additive sum_mono, mono] lemma prod_mono' [ordered_comm_monoid M] : monotone (λ f : ι → M, ∏ i, f i) := λ f g hfg, finset.prod_le_prod'' $ λ x _, hfg x attribute [mono] sum_mono @[to_additive sum_strict_mono] lemma prod_strict_mono' [ordered_cancel_comm_monoid M] : strict_mono (λ f : ι → M, ∏ x, f x) := λ f g hfg, let ⟨hle, i, hlt⟩ := pi.lt_def.mp hfg in finset.prod_lt_prod' (λ i _, hle i) ⟨i, finset.mem_univ i, hlt⟩ end fintype namespace with_top open finset /-- A product of finite numbers is still finite -/ lemma prod_lt_top [canonically_ordered_comm_semiring R] [nontrivial R] [decidable_eq R] {s : finset ι} {f : ι → with_top R} (h : ∀ i ∈ s, f i ≠ ⊤) : ∏ i in s, f i < ⊤ := prod_induction f (λ a, a < ⊤) (λ a b h₁ h₂, mul_lt_top h₁.ne h₂.ne) (coe_lt_top 1) $ λ a ha, lt_top_iff_ne_top.2 (h a ha) /-- A sum of finite numbers is still finite -/ lemma sum_lt_top [ordered_add_comm_monoid M] {s : finset ι} {f : ι → with_top M} (h : ∀ i ∈ s, f i ≠ ⊤) : (∑ i in s, f i) < ⊤ := sum_induction f (λ a, a < ⊤) (λ a b h₁ h₂, add_lt_top.2 ⟨h₁, h₂⟩) zero_lt_top $ λ i hi, lt_top_iff_ne_top.2 (h i hi) /-- A sum of numbers is infinite iff one of them is infinite -/ lemma sum_eq_top_iff [ordered_add_comm_monoid M] {s : finset ι} {f : ι → with_top M} : ∑ i in s, f i = ⊤ ↔ ∃ i ∈ s, f i = ⊤ := begin classical, split, { contrapose!, exact λ h, (sum_lt_top $ λ i hi, (h i hi)).ne }, { rintro ⟨i, his, hi⟩, rw [sum_eq_add_sum_diff_singleton his, hi, top_add] } end /-- A sum of finite numbers is still finite -/ lemma sum_lt_top_iff [ordered_add_comm_monoid M] {s : finset ι} {f : ι → with_top M} : ∑ i in s, f i < ⊤ ↔ ∀ i ∈ s, f i < ⊤ := by simp only [lt_top_iff_ne_top, ne.def, sum_eq_top_iff, not_exists] end with_top section absolute_value variables {S : Type*} lemma absolute_value.sum_le [semiring R] [ordered_semiring S] (abv : absolute_value R S) (s : finset ι) (f : ι → R) : abv (∑ i in s, f i) ≤ ∑ i in s, abv (f i) := begin letI := classical.dec_eq ι, refine finset.induction_on s _ (λ i s hi ih, _), { simp }, { simp only [finset.sum_insert hi], exact (abv.add_le _ _).trans (add_le_add le_rfl ih) }, end lemma is_absolute_value.abv_sum [semiring R] [ordered_semiring S] (abv : R → S) [is_absolute_value abv] (f : ι → R) (s : finset ι) : abv (∑ i in s, f i) ≤ ∑ i in s, abv (f i) := (is_absolute_value.to_absolute_value abv).sum_le _ _ lemma absolute_value.map_prod [comm_semiring R] [nontrivial R] [linear_ordered_comm_ring S] (abv : absolute_value R S) (f : ι → R) (s : finset ι) : abv (∏ i in s, f i) = ∏ i in s, abv (f i) := abv.to_monoid_hom.map_prod f s lemma is_absolute_value.map_prod [comm_semiring R] [nontrivial R] [linear_ordered_comm_ring S] (abv : R → S) [is_absolute_value abv] (f : ι → R) (s : finset ι) : abv (∏ i in s, f i) = ∏ i in s, abv (f i) := (is_absolute_value.to_absolute_value abv).map_prod _ _ end absolute_value
8034e72e93d7a00e224e664df6392a627efafa56
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/tests/lean/crash.lean
32ed4f4dd259e83779df9cd1a70a3e3f7835f583
[ "Apache-2.0" ]
permissive
codyroux/lean
7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3
0cca265db19f7296531e339192e9b9bae4a31f8b
refs/heads/master
1,610,909,964,159
1,407,084,399,000
1,416,857,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
143
lean
import logic context hypothesis P : Prop. theorem crash := assume H : P, have H' : ¬ P, from H, _.
dda76b62cc47961af31e91b51d76b061199ca122
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/shift.lean
ff7a393550a1e3fbb8879e722965b47d83c9e895
[]
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,280
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.limits.shapes.zero import Mathlib.PostPort universes v u l namespace Mathlib /-! # Shift A `shift` on a category is nothing more than an automorphism of the category. An example to keep in mind might be the category of complexes ⋯ → C_{n-1} → C_n → C_{n+1} → ⋯ with the shift operator re-indexing the terms, so the degree `n` term of `shift C` would be the degree `n+1` term of `C`. -/ namespace category_theory /-- A category has a shift, or translation, if it is equipped with an automorphism. -/ class has_shift (C : Type u) [category C] where shift : C ≌ C /-- The shift autoequivalence, moving objects and morphisms 'up'. -/ def shift (C : Type u) [category C] [has_shift C] : C ≌ C := has_shift.shift -- Any better notational suggestions? @[simp] theorem shift_zero_eq_zero (C : Type u) [category C] [has_shift C] [limits.has_zero_morphisms C] (X : C) (Y : C) (n : ℤ) : functor.map (equivalence.functor (shift C ^ n)) 0 = 0 := limits.equivalence_preserves_zero_morphisms C (shift C ^ n) X Y
4413f90329bcb8314383f056382ce83f4e9b5dc6
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/set_theory/cofinality.lean
b5fa445a47c0df3f9fbe8d5b783c63c0da694f5b
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
25,242
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Floris van Doorn -/ import set_theory.cardinal_ordinal /-! # Cofinality This file contains the definition of cofinality of a ordinal number and regular cardinals ## Main Definitions * `ordinal.cof o` is the cofinality of the ordinal `o`. If `o` is the order type of the relation `<` on `α`, then `o.cof` is the smallest cardinality of a subset `s` of α that is *cofinal* in `α`, i.e. `∀ x : α, ∃ y ∈ s, ¬ y < x`. * `cardinal.is_limit c` means that `c` is a (weak) limit cardinal: `c ≠ 0 ∧ ∀ x < c, succ x < c`. * `cardinal.is_strong_limit c` means that `c` is a strong limit cardinal: `c ≠ 0 ∧ ∀ x < c, 2 ^ x < c`. * `cardinal.is_regular c` means that `c` is a regular cardinal: `ω ≤ c ∧ c.ord.cof = c`. * `cardinal.is_inaccessible c` means that `c` is strongly inaccessible: `ω < c ∧ is_regular c ∧ is_strong_limit c`. ## Main Statements * `ordinal.infinite_pigeonhole_card`: the infinite pigeonhole principle * `cardinal.lt_power_cof`: A consequence of König's theorem stating that `c < c ^ c.ord.cof` for `c ≥ ω` * `cardinal.univ_inaccessible`: The type of ordinals in `Type u` form an inaccessible cardinal (in `Type v` with `v > u`). This shows (externally) that in `Type u` there are at least `u` inaccessible cardinals. ## Implementation Notes * The cofinality is defined for ordinals. If `c` is a cardinal number, its cofinality is `c.ord.cof`. ## Tags cofinality, regular cardinals, limits cardinals, inaccessible cardinals, infinite pigeonhole principle -/ noncomputable theory open function cardinal set open_locale classical cardinal universes u v w variables {α : Type*} {r : α → α → Prop} namespace order /-- Cofinality of a reflexive order `≼`. This is the smallest cardinality of a subset `S : set α` such that `∀ a, ∃ b ∈ S, a ≼ b`. -/ def cof (r : α → α → Prop) [is_refl α r] : cardinal := @cardinal.min {S : set α // ∀ a, ∃ b ∈ S, r a b} ⟨⟨set.univ, λ a, ⟨a, ⟨⟩, refl _⟩⟩⟩ (λ S, #S) lemma cof_le (r : α → α → Prop) [is_refl α r] {S : set α} (h : ∀a, ∃(b ∈ S), r a b) : order.cof r ≤ #S := le_trans (cardinal.min_le _ ⟨S, h⟩) (le_refl _) lemma le_cof {r : α → α → Prop} [is_refl α r] (c : cardinal) : c ≤ order.cof r ↔ ∀ {S : set α} (h : ∀a, ∃(b ∈ S), r a b) , c ≤ #S := by { rw [order.cof, cardinal.le_min], exact ⟨λ H S h, H ⟨S, h⟩, λ H ⟨S, h⟩, H h ⟩ } end order theorem rel_iso.cof.aux {α : Type u} {β : Type v} {r s} [is_refl α r] [is_refl β s] (f : r ≃r s) : cardinal.lift.{(max u v)} (order.cof r) ≤ cardinal.lift.{(max u v)} (order.cof s) := begin rw [order.cof, order.cof, lift_min, lift_min, cardinal.le_min], intro S, cases S with S H, simp only [comp, coe_sort_coe_base, subtype.coe_mk], refine le_trans (min_le _ _) _, { exact ⟨f ⁻¹' S, λ a, let ⟨b, bS, h⟩ := H (f a) in ⟨f.symm b, by simp [bS, ← f.map_rel_iff, h, -coe_fn_coe_base, -coe_fn_coe_trans, principal_seg.coe_coe_fn', initial_seg.coe_coe_fn]⟩⟩ }, { exact lift_mk_le.{u v (max u v)}.2 ⟨⟨λ ⟨x, h⟩, ⟨f x, h⟩, λ ⟨x, h₁⟩ ⟨y, h₂⟩ h₃, by congr; injection h₃ with h'; exact f.to_equiv.injective h'⟩⟩ } end theorem rel_iso.cof {α : Type u} {β : Type v} {r s} [is_refl α r] [is_refl β s] (f : r ≃r s) : cardinal.lift.{(max u v)} (order.cof r) = cardinal.lift.{(max u v)} (order.cof s) := le_antisymm (rel_iso.cof.aux f) (rel_iso.cof.aux f.symm) def strict_order.cof (r : α → α → Prop) [h : is_irrefl α r] : cardinal := @order.cof α (λ x y, ¬ r y x) ⟨h.1⟩ namespace ordinal /-- Cofinality of an ordinal. This is the smallest cardinal of a subset `S` of the ordinal which is unbounded, in the sense `∀ a, ∃ b ∈ S, ¬(b > a)`. It is defined for all ordinals, but `cof 0 = 0` and `cof (succ o) = 1`, so it is only really interesting on limit ordinals (when it is an infinite cardinal). -/ def cof (o : ordinal.{u}) : cardinal.{u} := quot.lift_on o (λ ⟨α, r, _⟩, by exactI strict_order.cof r) begin rintros ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨⟨f, hf⟩⟩, rw ← cardinal.lift_inj, apply rel_iso.cof ⟨f, _⟩, simp [hf] end lemma cof_type (r : α → α → Prop) [is_well_order α r] : (type r).cof = strict_order.cof r := rfl theorem le_cof_type [is_well_order α r] {c} : c ≤ cof (type r) ↔ ∀ S : set α, (∀ a, ∃ b ∈ S, ¬ r b a) → c ≤ #S := by dsimp [cof, strict_order.cof, order.cof, type, quotient.mk, quot.lift_on]; rw [cardinal.le_min, subtype.forall]; refl theorem cof_type_le [is_well_order α r] (S : set α) (h : ∀ a, ∃ b ∈ S, ¬ r b a) : cof (type r) ≤ #S := le_cof_type.1 (le_refl _) S h theorem lt_cof_type [is_well_order α r] (S : set α) (hl : #S < cof (type r)) : ∃ a, ∀ b ∈ S, r b a := not_forall_not.1 $ λ h, not_le_of_lt hl $ cof_type_le S (λ a, not_ball.1 (h a)) theorem cof_eq (r : α → α → Prop) [is_well_order α r] : ∃ S : set α, (∀ a, ∃ b ∈ S, ¬ r b a) ∧ #S = cof (type r) := begin have : ∃ i, cof (type r) = _, { dsimp [cof, order.cof, type, quotient.mk, quot.lift_on], apply cardinal.min_eq }, exact let ⟨⟨S, hl⟩, e⟩ := this in ⟨S, hl, e.symm⟩, end theorem ord_cof_eq (r : α → α → Prop) [is_well_order α r] : ∃ S : set α, (∀ a, ∃ b ∈ S, ¬ r b a) ∧ type (subrel r S) = (cof (type r)).ord := let ⟨S, hS, e⟩ := cof_eq r, ⟨s, _, e'⟩ := cardinal.ord_eq S, T : set α := {a | ∃ aS : a ∈ S, ∀ b : S, s b ⟨_, aS⟩ → r b a} in begin resetI, suffices, { refine ⟨T, this, le_antisymm _ (cardinal.ord_le.2 $ cof_type_le T this)⟩, rw [← e, e'], refine type_le'.2 ⟨rel_embedding.of_monotone (λ a, ⟨a, let ⟨aS, _⟩ := a.2 in aS⟩) (λ a b h, _)⟩, rcases a with ⟨a, aS, ha⟩, rcases b with ⟨b, bS, hb⟩, change s ⟨a, _⟩ ⟨b, _⟩, refine ((trichotomous_of s _ _).resolve_left (λ hn, _)).resolve_left _, { exact asymm h (ha _ hn) }, { intro e, injection e with e, subst b, exact irrefl _ h } }, { intro a, have : {b : S | ¬ r b a}.nonempty := let ⟨b, bS, ba⟩ := hS a in ⟨⟨b, bS⟩, ba⟩, let b := (is_well_order.wf).min _ this, have ba : ¬r b a := (is_well_order.wf).min_mem _ this, refine ⟨b, ⟨b.2, λ c, not_imp_not.1 $ λ h, _⟩, ba⟩, rw [show ∀b:S, (⟨b, b.2⟩:S) = b, by intro b; cases b; refl], exact (is_well_order.wf).not_lt_min _ this (is_order_connected.neg_trans h ba) } end theorem lift_cof (o) : (cof o).lift = cof o.lift := induction_on o $ begin introsI α r _, cases lift_type r with _ e, rw e, apply le_antisymm, { unfreezingI { refine le_cof_type.2 (λ S H, _) }, have : (#(ulift.up ⁻¹' S)).lift ≤ #S := ⟨⟨λ ⟨⟨x, h⟩⟩, ⟨⟨x⟩, h⟩, λ ⟨⟨x, h₁⟩⟩ ⟨⟨y, h₂⟩⟩ e, by simp at e; congr; injection e⟩⟩, refine le_trans (cardinal.lift_le.2 $ cof_type_le _ _) this, exact λ a, let ⟨⟨b⟩, bs, br⟩ := H ⟨a⟩ in ⟨b, bs, br⟩ }, { rcases cof_eq r with ⟨S, H, e'⟩, have : #(ulift.down ⁻¹' S) ≤ (#S).lift := ⟨⟨λ ⟨⟨x⟩, h⟩, ⟨⟨x, h⟩⟩, λ ⟨⟨x⟩, h₁⟩ ⟨⟨y⟩, h₂⟩ e, by simp at e; congr; injections⟩⟩, rw e' at this, unfreezingI { refine le_trans (cof_type_le _ _) this }, exact λ ⟨a⟩, let ⟨b, bs, br⟩ := H a in ⟨⟨b⟩, bs, br⟩ } end theorem cof_le_card (o) : cof o ≤ card o := induction_on o $ λ α r _, begin resetI, have : #(@set.univ α) = card (type r) := quotient.sound ⟨equiv.set.univ _⟩, rw ← this, exact cof_type_le set.univ (λ a, ⟨a, ⟨⟩, irrefl a⟩) end theorem cof_ord_le (c : cardinal) : cof c.ord ≤ c := by simpa using cof_le_card c.ord @[simp] theorem cof_zero : cof 0 = 0 := le_antisymm (by simpa using cof_le_card 0) (cardinal.zero_le _) @[simp] theorem cof_eq_zero {o} : cof o = 0 ↔ o = 0 := ⟨induction_on o $ λ α r _ z, by exactI let ⟨S, hl, e⟩ := cof_eq r in type_eq_zero_iff_is_empty.2 $ ⟨λ a, let ⟨b, h, _⟩ := hl a in (mk_eq_zero_iff.1 (e.trans z)).elim' ⟨_, h⟩⟩, λ e, by simp [e]⟩ @[simp] theorem cof_succ (o) : cof (succ o) = 1 := begin apply le_antisymm, { refine induction_on o (λ α r _, _), change cof (type _) ≤ _, rw [← (_ : #_ = 1)], apply cof_type_le, { refine λ a, ⟨sum.inr punit.star, set.mem_singleton _, _⟩, rcases a with a|⟨⟨⟨⟩⟩⟩; simp [empty_relation] }, { rw [cardinal.fintype_card, set.card_singleton], simp } }, { rw [← cardinal.succ_zero, cardinal.succ_le], simpa [lt_iff_le_and_ne, cardinal.zero_le] using λ h, succ_ne_zero o (cof_eq_zero.1 (eq.symm h)) } end @[simp] theorem cof_eq_one_iff_is_succ {o} : cof.{u} o = 1 ↔ ∃ a, o = succ a := ⟨induction_on o $ λ α r _ z, begin resetI, rcases cof_eq r with ⟨S, hl, e⟩, rw z at e, cases mk_ne_zero_iff.1 (by rw e; exact one_ne_zero) with a, refine ⟨typein r a, eq.symm $ quotient.sound ⟨rel_iso.of_surjective (rel_embedding.of_monotone _ (λ x y, _)) (λ x, _)⟩⟩, { apply sum.rec; [exact subtype.val, exact λ _, a] }, { rcases x with x|⟨⟨⟨⟩⟩⟩; rcases y with y|⟨⟨⟨⟩⟩⟩; simp [subrel, order.preimage, empty_relation], exact x.2 }, { suffices : r x a ∨ ∃ (b : punit), ↑a = x, {simpa}, rcases trichotomous_of r x a with h|h|h, { exact or.inl h }, { exact or.inr ⟨punit.star, h.symm⟩ }, { rcases hl x with ⟨a', aS, hn⟩, rw (_ : ↑a = a') at h, {exact absurd h hn}, refine congr_arg subtype.val (_ : a = ⟨a', aS⟩), haveI := le_one_iff_subsingleton.1 (le_of_eq e), apply subsingleton.elim } } end, λ ⟨a, e⟩, by simp [e]⟩ @[simp] theorem cof_add (a b : ordinal) : b ≠ 0 → cof (a + b) = cof b := induction_on a $ λ α r _, induction_on b $ λ β s _ b0, begin resetI, change cof (type _) = _, refine eq_of_forall_le_iff (λ c, _), rw [le_cof_type, le_cof_type], split; intros H S hS, { refine le_trans (H {a | sum.rec_on a (∅:set α) S} (λ a, _)) ⟨⟨_, _⟩⟩, { cases a with a b, { cases type_ne_zero_iff_nonempty.1 b0 with b, rcases hS b with ⟨b', bs, _⟩, exact ⟨sum.inr b', bs, by simp⟩ }, { rcases hS b with ⟨b', bs, h⟩, exact ⟨sum.inr b', bs, by simp [h]⟩ } }, { exact λ a, match a with ⟨sum.inr b, h⟩ := ⟨b, h⟩ end }, { exact λ a b, match a, b with ⟨sum.inr a, h₁⟩, ⟨sum.inr b, h₂⟩, h := by congr; injection h end } }, { refine le_trans (H (sum.inr ⁻¹' S) (λ a, _)) ⟨⟨_, _⟩⟩, { rcases hS (sum.inr a) with ⟨a'|b', bs, h⟩; simp at h, { cases h }, { exact ⟨b', bs, h⟩ } }, { exact λ ⟨a, h⟩, ⟨_, h⟩ }, { exact λ ⟨a, h₁⟩ ⟨b, h₂⟩ h, by injection h with h; congr; injection h } } end @[simp] theorem cof_cof (o : ordinal) : cof (cof o).ord= cof o := le_antisymm (le_trans (cof_le_card _) (by simp)) $ induction_on o $ λ α r _, by exactI let ⟨S, hS, e₁⟩ := ord_cof_eq r, ⟨T, hT, e₂⟩ := cof_eq (subrel r S) in begin rw e₁ at e₂, rw ← e₂, refine le_trans (cof_type_le {a | ∃ h, (subtype.mk a h : S) ∈ T} (λ a, _)) ⟨⟨_, _⟩⟩, { rcases hS a with ⟨b, bS, br⟩, rcases hT ⟨b, bS⟩ with ⟨⟨c, cS⟩, cT, cs⟩, exact ⟨c, ⟨cS, cT⟩, is_order_connected.neg_trans cs br⟩ }, { exact λ ⟨a, h⟩, ⟨⟨a, h.fst⟩, h.snd⟩ }, { exact λ ⟨a, ha⟩ ⟨b, hb⟩ h, by injection h with h; congr; injection h }, end theorem omega_le_cof {o} : ω ≤ cof o ↔ is_limit o := begin rcases zero_or_succ_or_limit o with rfl|⟨o,rfl⟩|l, { simp [not_zero_is_limit, cardinal.omega_ne_zero] }, { simp [not_succ_is_limit, cardinal.one_lt_omega] }, { simp [l], refine le_of_not_lt (λ h, _), cases cardinal.lt_omega.1 h with n e, have := cof_cof o, rw [e, ord_nat] at this, cases n, { simp at e, simpa [e, not_zero_is_limit] using l }, { rw [← nat_cast_succ, cof_succ] at this, rw [← this, cof_eq_one_iff_is_succ] at e, rcases e with ⟨a, rfl⟩, exact not_succ_is_limit _ l } } end @[simp] theorem cof_omega : cof omega = ω := le_antisymm (by rw ← card_omega; apply cof_le_card) (omega_le_cof.2 omega_is_limit) theorem cof_eq' (r : α → α → Prop) [is_well_order α r] (h : is_limit (type r)) : ∃ S : set α, (∀ a, ∃ b ∈ S, r a b) ∧ #S = cof (type r) := let ⟨S, H, e⟩ := cof_eq r in ⟨S, λ a, let a' := enum r _ (h.2 _ (typein_lt_type r a)) in let ⟨b, h, ab⟩ := H a' in ⟨b, h, (is_order_connected.conn a b a' $ (typein_lt_typein r).1 (by rw typein_enum; apply ordinal.lt_succ_self)).resolve_right ab⟩, e⟩ theorem cof_sup_le_lift {ι} (f : ι → ordinal) (H : ∀ i, f i < sup f) : cof (sup f) ≤ (#ι).lift := begin generalize e : sup f = o, refine ordinal.induction_on o _ e, introsI α r _ e', rw e' at H, refine le_trans (cof_type_le (set.range (λ i, enum r _ (H i))) _) ⟨embedding.of_surjective _ _⟩, { intro a, by_contra h, apply not_le_of_lt (typein_lt_type r a), rw [← e', sup_le], intro i, have h : ∀ (x : ι), r (enum r (f x) _) a, { simpa using h }, simpa only [typein_enum] using le_of_lt ((typein_lt_typein r).2 (h i)) }, { exact λ i, ⟨_, set.mem_range_self i.1⟩ }, { intro a, rcases a with ⟨_, i, rfl⟩, exact ⟨⟨i⟩, by simp⟩ } end theorem cof_sup_le {ι} (f : ι → ordinal) (H : ∀ i, f i < sup.{u u} f) : cof (sup.{u u} f) ≤ #ι := by simpa using cof_sup_le_lift.{u u} f H theorem cof_bsup_le_lift {o : ordinal} : ∀ (f : Π a < o, ordinal), (∀ i h, f i h < bsup o f) → cof (bsup o f) ≤ o.card.lift := induction_on o $ λ α r _ f H, by rw bsup_type; refine cof_sup_le_lift _ _; rw ← bsup_type; intro a; apply H theorem cof_bsup_le {o : ordinal} : ∀ (f : Π a < o, ordinal), (∀ i h, f i h < bsup.{u u} o f) → cof (bsup.{u u} o f) ≤ o.card := induction_on o $ λ α r _ f H, by simpa using cof_bsup_le_lift.{u u} f H @[simp] theorem cof_univ : cof univ.{u v} = cardinal.univ := le_antisymm (cof_le_card _) begin refine le_of_forall_lt (λ c h, _), rcases lt_univ'.1 h with ⟨c, rfl⟩, rcases @cof_eq ordinal.{u} (<) _ with ⟨S, H, Se⟩, rw [univ, ← lift_cof, ← cardinal.lift_lift, cardinal.lift_lt, ← Se], refine lt_of_not_ge (λ h, _), cases cardinal.lift_down h with a e, refine quotient.induction_on a (λ α e, _) e, cases quotient.exact e with f, have f := equiv.ulift.symm.trans f, let g := λ a, (f a).1, let o := succ (sup.{u u} g), rcases H o with ⟨b, h, l⟩, refine l (lt_succ.2 _), rw ← show g (f.symm ⟨b, h⟩) = b, by dsimp [g]; simp, apply le_sup end theorem sup_lt_ord {ι} (f : ι → ordinal) {c : ordinal} (H1 : #ι < c.cof) (H2 : ∀ i, f i < c) : sup.{u u} f < c := begin apply lt_of_le_of_ne, { rw [sup_le], exact λ i, le_of_lt (H2 i) }, rintro h, apply not_le_of_lt H1, simpa [sup_ord, H2, h] using cof_sup_le.{u} f end theorem sup_lt {ι} (f : ι → cardinal) {c : cardinal} (H1 : #ι < c.ord.cof) (H2 : ∀ i, f i < c) : cardinal.sup.{u u} f < c := by { rw [←ord_lt_ord, ←sup_ord], apply sup_lt_ord _ H1, intro i, rw ord_lt_ord, apply H2 } /-- If the union of s is unbounded and s is smaller than the cofinality, then s has an unbounded member -/ theorem unbounded_of_unbounded_sUnion (r : α → α → Prop) [wo : is_well_order α r] {s : set (set α)} (h₁ : unbounded r $ ⋃₀ s) (h₂ : #s < strict_order.cof r) : ∃(x ∈ s), unbounded r x := begin by_contra h, simp only [not_exists, exists_prop, not_and, not_unbounded_iff] at h, apply not_le_of_lt h₂, let f : s → α := λ x : s, wo.wf.sup x (h x.1 x.2), let t : set α := range f, have : #t ≤ #s, exact mk_range_le, refine le_trans _ this, have : unbounded r t, { intro x, rcases h₁ x with ⟨y, ⟨c, hc, hy⟩, hxy⟩, refine ⟨f ⟨c, hc⟩, mem_range_self _, _⟩, intro hxz, apply hxy, refine trans (wo.wf.lt_sup _ hy) hxz }, exact cardinal.min_le _ (subtype.mk t this) end /-- If the union of s is unbounded and s is smaller than the cofinality, then s has an unbounded member -/ theorem unbounded_of_unbounded_Union {α β : Type u} (r : α → α → Prop) [wo : is_well_order α r] (s : β → set α) (h₁ : unbounded r $ ⋃x, s x) (h₂ : #β < strict_order.cof r) : ∃x : β, unbounded r (s x) := begin rw [← sUnion_range] at h₁, have : #(range (λ (i : β), s i)) < strict_order.cof r := lt_of_le_of_lt mk_range_le h₂, rcases unbounded_of_unbounded_sUnion r h₁ this with ⟨_, ⟨x, rfl⟩, u⟩, exact ⟨x, u⟩ end /-- The infinite pigeonhole principle -/ theorem infinite_pigeonhole {β α : Type u} (f : β → α) (h₁ : ω ≤ #β) (h₂ : #α < (#β).ord.cof) : ∃a : α, #(f ⁻¹' {a}) = #β := begin have : ¬∀a, #(f ⁻¹' {a}) < #β, { intro h, apply not_lt_of_ge (ge_of_eq $ mk_univ), rw [←@preimage_univ _ _ f, ←Union_of_singleton, preimage_Union], apply lt_of_le_of_lt mk_Union_le_sum_mk, apply lt_of_le_of_lt (sum_le_sup _), apply mul_lt_of_lt h₁ (lt_of_lt_of_le h₂ $ cof_ord_le _), exact sup_lt _ h₂ h }, rw [not_forall] at this, cases this with x h, use x, apply le_antisymm _ (le_of_not_gt h), rw [le_mk_iff_exists_set], exact ⟨_, rfl⟩ end /-- pigeonhole principle for a cardinality below the cardinality of the domain -/ theorem infinite_pigeonhole_card {β α : Type u} (f : β → α) (θ : cardinal) (hθ : θ ≤ #β) (h₁ : ω ≤ θ) (h₂ : #α < θ.ord.cof) : ∃a : α, θ ≤ #(f ⁻¹' {a}) := begin rcases le_mk_iff_exists_set.1 hθ with ⟨s, rfl⟩, cases infinite_pigeonhole (f ∘ subtype.val : s → α) h₁ h₂ with a ha, use a, rw [←ha, @preimage_comp _ _ _ subtype.val f], apply mk_preimage_of_injective _ _ subtype.val_injective end theorem infinite_pigeonhole_set {β α : Type u} {s : set β} (f : s → α) (θ : cardinal) (hθ : θ ≤ #s) (h₁ : ω ≤ θ) (h₂ : #α < θ.ord.cof) : ∃(a : α) (t : set β) (h : t ⊆ s), θ ≤ #t ∧ ∀{{x}} (hx : x ∈ t), f ⟨x, h hx⟩ = a := begin cases infinite_pigeonhole_card f θ hθ h₁ h₂ with a ha, refine ⟨a, {x | ∃(h : x ∈ s), f ⟨x, h⟩ = a}, _, _, _⟩, { rintro x ⟨hx, hx'⟩, exact hx }, { refine le_trans ha _, apply ge_of_eq, apply quotient.sound, constructor, refine equiv.trans _ (equiv.subtype_subtype_equiv_subtype_exists _ _).symm, simp only [set_coe_eq_subtype, mem_singleton_iff, mem_preimage, mem_set_of_eq] }, rintro x ⟨hx, hx'⟩, exact hx' end end ordinal namespace cardinal open ordinal local infixr ^ := @pow cardinal.{u} cardinal cardinal.has_pow /-- A cardinal is a limit if it is not zero or a successor cardinal. Note that `ω` is a limit cardinal by this definition. -/ def is_limit (c : cardinal) : Prop := c ≠ 0 ∧ ∀ x < c, succ x < c /-- A cardinal is a strong limit if it is not zero and it is closed under powersets. Note that `ω` is a strong limit by this definition. -/ def is_strong_limit (c : cardinal) : Prop := c ≠ 0 ∧ ∀ x < c, 2 ^ x < c theorem is_strong_limit.is_limit {c} (H : is_strong_limit c) : is_limit c := ⟨H.1, λ x h, lt_of_le_of_lt (succ_le.2 $ cantor _) (H.2 _ h)⟩ /-- A cardinal is regular if it is infinite and it equals its own cofinality. -/ def is_regular (c : cardinal) : Prop := ω ≤ c ∧ c.ord.cof = c theorem cof_is_regular {o : ordinal} (h : o.is_limit) : is_regular o.cof := ⟨omega_le_cof.2 h, cof_cof _⟩ theorem omega_is_regular : is_regular ω := ⟨le_refl _, by simp⟩ theorem succ_is_regular {c : cardinal.{u}} (h : ω ≤ c) : is_regular (succ c) := ⟨le_trans h (le_of_lt $ lt_succ_self _), begin refine le_antisymm (cof_ord_le _) (succ_le.2 _), cases quotient.exists_rep (succ c) with α αe, simp at αe, rcases ord_eq α with ⟨r, wo, re⟩, resetI, have := ord_is_limit (le_trans h $ le_of_lt $ lt_succ_self _), rw [← αe, re] at this ⊢, rcases cof_eq' r this with ⟨S, H, Se⟩, rw [← Se], apply lt_imp_lt_of_le_imp_le (λ (h : #S ≤ c), mul_le_mul_right' h c), rw [mul_eq_self h, ← succ_le, ← αe, ← sum_const], refine le_trans _ (sum_le_sum (λ x:S, card (typein r x)) _ _), { simp [typein, sum_mk (λ x:S, {a//r a x})], refine ⟨embedding.of_surjective _ _⟩, { exact λ x, x.2.1 }, { exact λ a, let ⟨b, h, ab⟩ := H a in ⟨⟨⟨_, h⟩, _, ab⟩, rfl⟩ } }, { intro i, rw [← lt_succ, ← lt_ord, ← αe, re], apply typein_lt_type } end⟩ /-- A function whose codomain's cardinality is infinite but strictly smaller than its domain's has a fiber with cardinality strictly great than the codomain. -/ theorem infinite_pigeonhole_card_lt {β α : Type u} (f : β → α) (w : #α < #β) (w' : ω ≤ #α) : ∃ a : α, #α < #(f ⁻¹' {a}) := begin simp_rw [← succ_le], exact ordinal.infinite_pigeonhole_card f (#α).succ (succ_le.mpr w) (w'.trans (lt_succ_self _).le) ((lt_succ_self _).trans_le (succ_is_regular w').2.ge), end /-- A function whose codomain's cardinality is infinite but strictly smaller than its domain's has an infinite fiber. -/ theorem exists_infinite_fiber {β α : Type*} (f : β → α) (w : #α < #β) (w' : _root_.infinite α) : ∃ a : α, _root_.infinite (f ⁻¹' {a}) := begin simp_rw [cardinal.infinite_iff] at ⊢ w', cases infinite_pigeonhole_card_lt f w w' with a ha, exact ⟨a, w'.trans ha.le⟩, end /-- If an infinite type `β` can be expressed as a union of finite sets, then the cardinality of the collection of those finite sets must be at least the cardinality of `β`. -/ lemma le_range_of_union_finset_eq_top {α β : Type*} [infinite β] (f : α → finset β) (w : (⋃ a, (f a : set β)) = ⊤) : #β ≤ #(range f) := begin have k : _root_.infinite (range f), { rw infinite_coe_iff, apply mt (union_finset_finite_of_range_finite f), rw w, exact infinite_univ, }, by_contradiction h, simp only [not_le] at h, let u : Π b, ∃ a, b ∈ f a := λ b, by simpa using (w.ge : _) (set.mem_univ b), let u' : β → range f := λ b, ⟨f (u b).some, by simp⟩, have v' : ∀ a, u' ⁻¹' {⟨f a, by simp⟩} ≤ f a, begin rintros a p m, simp at m, rw ←m, apply (λ b, (u b).some_spec), end, obtain ⟨⟨-, ⟨a, rfl⟩⟩, p⟩ := exists_infinite_fiber u' h k, exact (@infinite.of_injective _ _ p (inclusion (v' a)) (inclusion_injective _)).false, end theorem sup_lt_ord_of_is_regular {ι} (f : ι → ordinal) {c} (hc : is_regular c) (H1 : #ι < c) (H2 : ∀ i, f i < c.ord) : ordinal.sup.{u u} f < c.ord := by { apply sup_lt_ord _ _ H2, rw [hc.2], exact H1 } theorem sup_lt_of_is_regular {ι} (f : ι → cardinal) {c} (hc : is_regular c) (H1 : #ι < c) (H2 : ∀ i, f i < c) : sup.{u u} f < c := by { apply sup_lt _ _ H2, rwa [hc.2] } theorem sum_lt_of_is_regular {ι} (f : ι → cardinal) {c} (hc : is_regular c) (H1 : #ι < c) (H2 : ∀ i, f i < c) : sum.{u u} f < c := lt_of_le_of_lt (sum_le_sup _) $ mul_lt_of_lt hc.1 H1 $ sup_lt_of_is_regular f hc H1 H2 /-- A cardinal is inaccessible if it is an uncountable regular strong limit cardinal. -/ def is_inaccessible (c : cardinal) := ω < c ∧ is_regular c ∧ is_strong_limit c theorem is_inaccessible.mk {c} (h₁ : ω < c) (h₂ : c ≤ c.ord.cof) (h₃ : ∀ x < c, 2 ^ x < c) : is_inaccessible c := ⟨h₁, ⟨le_of_lt h₁, le_antisymm (cof_ord_le _) h₂⟩, ne_of_gt (lt_trans omega_pos h₁), h₃⟩ /- Lean's foundations prove the existence of ω many inaccessible cardinals -/ theorem univ_inaccessible : is_inaccessible (univ.{u v}) := is_inaccessible.mk (by simpa using lift_lt_univ' ω) (by simp) (λ c h, begin rcases lt_univ'.1 h with ⟨c, rfl⟩, rw ← lift_two_power.{u (max (u+1) v)}, apply lift_lt_univ' end) theorem lt_power_cof {c : cardinal.{u}} : ω ≤ c → c < c ^ cof c.ord := quotient.induction_on c $ λ α h, begin rcases ord_eq α with ⟨r, wo, re⟩, resetI, have := ord_is_limit h, rw [mk_def, re] at this ⊢, rcases cof_eq' r this with ⟨S, H, Se⟩, have := sum_lt_prod (λ a:S, #{x // r x a}) (λ _, #α) (λ i, _), { simp [Se.symm] at this ⊢, refine lt_of_le_of_lt _ this, refine ⟨embedding.of_surjective _ _⟩, { exact λ x, x.2.1 }, { exact λ a, let ⟨b, h, ab⟩ := H a in ⟨⟨⟨_, h⟩, _, ab⟩, rfl⟩ } }, { have := typein_lt_type r i, rwa [← re, lt_ord] at this } end theorem lt_cof_power {a b : cardinal} (ha : ω ≤ a) (b1 : 1 < b) : a < cof (b ^ a).ord := begin have b0 : b ≠ 0 := ne_of_gt (lt_trans zero_lt_one b1), apply lt_imp_lt_of_le_imp_le (power_le_power_left $ power_ne_zero a b0), rw [← power_mul, mul_eq_self ha], exact lt_power_cof (le_trans ha $ le_of_lt $ cantor' _ b1), end end cardinal
34247cba092e378e714f88753dc1590e70c05fe5
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch5/ex0608.lean
edaab6a5e2a0a2da57a3d352ea12aa1fa4a7f36c
[]
no_license
Ailrun/Theorem_Proving_in_Lean
ae6a23f3c54d62d401314d6a771e8ff8b4132db2
2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68
refs/heads/master
1,609,838,270,467
1,586,846,743,000
1,586,846,743,000
240,967,761
1
0
null
null
null
null
UTF-8
Lean
false
false
312
lean
universe u example {α : Type u} [ring α] (a b c : α) : a * 0 + 0 * b + c * 0 + 0 * a = 0 := begin rw [mul_zero, mul_zero, zero_mul, zero_mul], repeat { rw add_zero } end example {α : Type u} [group α] {a b : α} (h : a * b = 1) : a⁻¹ = b := by rw [←(mul_one a⁻¹), ←h, inv_mul_cancel_left]
16c68e2960a51d9560830a956871cb77d5ad376d
9dc8cecdf3c4634764a18254e94d43da07142918
/src/topology/category/Top/epi_mono.lean
b113ee4df1355983bc7c93949f3af3c806de506a
[ "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
1,156
lean
/- Copyright (c) 2019 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton -/ import topology.category.Top.adjunctions import category_theory.epi_mono /-! # Epi- and monomorphisms in `Top` This file shows that a continuous function is an epimorphism in the category of topological spaces if and only if it is surjective, and that a continuous function is a monomorphism in the category of topological spaces if and only if it is injective. -/ universe u open category_theory open Top namespace Top lemma epi_iff_surjective {X Y : Top.{u}} (f : X ⟶ Y) : epi f ↔ function.surjective f := begin suffices : epi f ↔ epi ((forget Top).map f), { rw [this, category_theory.epi_iff_surjective], refl }, split, { introI, apply_instance }, { apply functor.epi_of_epi_map } end lemma mono_iff_injective {X Y : Top.{u}} (f : X ⟶ Y) : mono f ↔ function.injective f := begin suffices : mono f ↔ mono ((forget Top).map f), { rw [this, category_theory.mono_iff_injective], refl }, split, { introI, apply_instance }, { apply functor.mono_of_mono_map } end end Top
11f1e314e24d6e0f76ea13c1d068f58888071869
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/set_theory/game/nim.lean
93d6b3f894ccd4499b59689ac629b489957e8020
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
14,598
lean
/- Copyright (c) 2020 Fox Thomson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Fox Thomson, Markus Himmel -/ import data.nat.bitwise import set_theory.game.birthday import set_theory.game.impartial /-! # Nim and the Sprague-Grundy theorem > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file contains the definition for nim for any ordinal `o`. In the game of `nim o₁` both players may move to `nim o₂` for any `o₂ < o₁`. We also define a Grundy value for an impartial game `G` and prove the Sprague-Grundy theorem, that `G` is equivalent to `nim (grundy_value G)`. Finally, we compute the sum of finite Grundy numbers: if `G` and `H` have Grundy values `n` and `m`, where `n` and `m` are natural numbers, then `G + H` has the Grundy value `n xor m`. ## Implementation details The pen-and-paper definition of nim defines the possible moves of `nim o` to be `set.Iio o`. However, this definition does not work for us because it would make the type of nim `ordinal.{u} → pgame.{u + 1}`, which would make it impossible for us to state the Sprague-Grundy theorem, since that requires the type of `nim` to be `ordinal.{u} → pgame.{u}`. For this reason, we instead use `o.out.α` for the possible moves. You can use `to_left_moves_nim` and `to_right_moves_nim` to convert an ordinal less than `o` into a left or right move of `nim o`, and vice versa. -/ noncomputable theory universe u open_locale pgame namespace pgame /-- The definition of single-heap nim, which can be viewed as a pile of stones where each player can take a positive number of stones from it on their turn. -/ -- Uses `noncomputable!` to avoid `rec_fn_macro only allowed in meta definitions` VM error noncomputable! def nim : ordinal.{u} → pgame.{u} | o₁ := let f := λ o₂, have ordinal.typein o₁.out.r o₂ < o₁ := ordinal.typein_lt_self o₂, nim (ordinal.typein o₁.out.r o₂) in ⟨o₁.out.α, o₁.out.α, f, f⟩ using_well_founded { dec_tac := tactic.assumption } open ordinal lemma nim_def (o : ordinal) : nim o = pgame.mk o.out.α o.out.α (λ o₂, nim (ordinal.typein (<) o₂)) (λ o₂, nim (ordinal.typein (<) o₂)) := by { rw nim, refl } lemma left_moves_nim (o : ordinal) : (nim o).left_moves = o.out.α := by { rw nim_def, refl } lemma right_moves_nim (o : ordinal) : (nim o).right_moves = o.out.α := by { rw nim_def, refl } lemma move_left_nim_heq (o : ordinal) : (nim o).move_left == λ i : o.out.α, nim (typein (<) i) := by { rw nim_def, refl } lemma move_right_nim_heq (o : ordinal) : (nim o).move_right == λ i : o.out.α, nim (typein (<) i) := by { rw nim_def, refl } /-- Turns an ordinal less than `o` into a left move for `nim o` and viceversa. -/ noncomputable def to_left_moves_nim {o : ordinal} : set.Iio o ≃ (nim o).left_moves := (enum_iso_out o).to_equiv.trans (equiv.cast (left_moves_nim o).symm) /-- Turns an ordinal less than `o` into a right move for `nim o` and viceversa. -/ noncomputable def to_right_moves_nim {o : ordinal} : set.Iio o ≃ (nim o).right_moves := (enum_iso_out o).to_equiv.trans (equiv.cast (right_moves_nim o).symm) @[simp] theorem to_left_moves_nim_symm_lt {o : ordinal} (i : (nim o).left_moves) : ↑(to_left_moves_nim.symm i) < o := (to_left_moves_nim.symm i).prop @[simp] theorem to_right_moves_nim_symm_lt {o : ordinal} (i : (nim o).right_moves) : ↑(to_right_moves_nim.symm i) < o := (to_right_moves_nim.symm i).prop @[simp] lemma move_left_nim' {o : ordinal.{u}} (i) : (nim o).move_left i = nim (to_left_moves_nim.symm i).val := (congr_heq (move_left_nim_heq o).symm (cast_heq _ i)).symm lemma move_left_nim {o : ordinal} (i) : (nim o).move_left (to_left_moves_nim i) = nim i := by simp @[simp] lemma move_right_nim' {o : ordinal} (i) : (nim o).move_right i = nim (to_right_moves_nim.symm i).val := (congr_heq (move_right_nim_heq o).symm (cast_heq _ i)).symm lemma move_right_nim {o : ordinal} (i) : (nim o).move_right (to_right_moves_nim i) = nim i := by simp /-- A recursion principle for left moves of a nim game. -/ @[elab_as_eliminator] def left_moves_nim_rec_on {o : ordinal} {P : (nim o).left_moves → Sort*} (i : (nim o).left_moves) (H : ∀ a < o, P $ to_left_moves_nim ⟨a, H⟩) : P i := by { rw ←to_left_moves_nim.apply_symm_apply i, apply H } /-- A recursion principle for right moves of a nim game. -/ @[elab_as_eliminator] def right_moves_nim_rec_on {o : ordinal} {P : (nim o).right_moves → Sort*} (i : (nim o).right_moves) (H : ∀ a < o, P $ to_right_moves_nim ⟨a, H⟩) : P i := by { rw ←to_right_moves_nim.apply_symm_apply i, apply H } instance is_empty_nim_zero_left_moves : is_empty (nim 0).left_moves := by { rw nim_def, exact ordinal.is_empty_out_zero } instance is_empty_nim_zero_right_moves : is_empty (nim 0).right_moves := by { rw nim_def, exact ordinal.is_empty_out_zero } /-- `nim 0` has exactly the same moves as `0`. -/ def nim_zero_relabelling : nim 0 ≡r 0 := relabelling.is_empty _ theorem nim_zero_equiv : nim 0 ≈ 0 := equiv.is_empty _ noncomputable instance unique_nim_one_left_moves : unique (nim 1).left_moves := (equiv.cast $ left_moves_nim 1).unique noncomputable instance unique_nim_one_right_moves : unique (nim 1).right_moves := (equiv.cast $ right_moves_nim 1).unique @[simp] theorem default_nim_one_left_moves_eq : (default : (nim 1).left_moves) = @to_left_moves_nim 1 ⟨0, zero_lt_one⟩ := rfl @[simp] theorem default_nim_one_right_moves_eq : (default : (nim 1).right_moves) = @to_right_moves_nim 1 ⟨0, zero_lt_one⟩ := rfl @[simp] theorem to_left_moves_nim_one_symm (i) : (@to_left_moves_nim 1).symm i = ⟨0, zero_lt_one⟩ := by simp @[simp] theorem to_right_moves_nim_one_symm (i) : (@to_right_moves_nim 1).symm i = ⟨0, zero_lt_one⟩ := by simp theorem nim_one_move_left (x) : (nim 1).move_left x = nim 0 := by simp theorem nim_one_move_right (x) : (nim 1).move_right x = nim 0 := by simp /-- `nim 1` has exactly the same moves as `star`. -/ def nim_one_relabelling : nim 1 ≡r star := begin rw nim_def, refine ⟨_, _, λ i, _, λ j, _⟩, any_goals { dsimp, apply equiv.equiv_of_unique }, all_goals { simp, exact nim_zero_relabelling } end theorem nim_one_equiv : nim 1 ≈ star := nim_one_relabelling.equiv @[simp] lemma nim_birthday (o : ordinal) : (nim o).birthday = o := begin induction o using ordinal.induction with o IH, rw [nim_def, birthday_def], dsimp, rw max_eq_right le_rfl, convert lsub_typein o, exact funext (λ i, IH _ (typein_lt_self i)) end @[simp] lemma neg_nim (o : ordinal) : -nim o = nim o := begin induction o using ordinal.induction with o IH, rw nim_def, dsimp; congr; funext i; exact IH _ (ordinal.typein_lt_self i) end instance nim_impartial (o : ordinal) : impartial (nim o) := begin induction o using ordinal.induction with o IH, rw [impartial_def, neg_nim], refine ⟨equiv_rfl, λ i, _, λ i, _⟩; simpa using IH _ (typein_lt_self _) end lemma nim_fuzzy_zero_of_ne_zero {o : ordinal} (ho : o ≠ 0) : nim o ‖ 0 := begin rw [impartial.fuzzy_zero_iff_lf, nim_def, lf_zero_le], rw ←ordinal.pos_iff_ne_zero at ho, exact ⟨(ordinal.principal_seg_out ho).top, by simp⟩ end @[simp] lemma nim_add_equiv_zero_iff (o₁ o₂ : ordinal) : nim o₁ + nim o₂ ≈ 0 ↔ o₁ = o₂ := begin split, { refine not_imp_not.1 (λ (hne : _ ≠ _), (impartial.not_equiv_zero_iff _).2 _), wlog h : o₁ < o₂, { exact (fuzzy_congr_left add_comm_equiv).1 (this _ _ hne.symm (hne.lt_or_lt.resolve_left h)) }, rw [impartial.fuzzy_zero_iff_gf, zero_lf_le, nim_def o₂], refine ⟨to_left_moves_add (sum.inr _), _⟩, { exact (ordinal.principal_seg_out h).top }, { simpa using (impartial.add_self (nim o₁)).2 } }, { rintro rfl, exact impartial.add_self (nim o₁) } end @[simp] lemma nim_add_fuzzy_zero_iff {o₁ o₂ : ordinal} : nim o₁ + nim o₂ ‖ 0 ↔ o₁ ≠ o₂ := by rw [iff_not_comm, impartial.not_fuzzy_zero_iff, nim_add_equiv_zero_iff] @[simp] lemma nim_equiv_iff_eq {o₁ o₂ : ordinal} : nim o₁ ≈ nim o₂ ↔ o₁ = o₂ := by rw [impartial.equiv_iff_add_equiv_zero, nim_add_equiv_zero_iff] /-- The Grundy value of an impartial game, the ordinal which corresponds to the game of nim that the game is equivalent to -/ noncomputable def grundy_value : Π (G : pgame.{u}), ordinal.{u} | G := ordinal.mex.{u u} (λ i, grundy_value (G.move_left i)) using_well_founded { dec_tac := pgame_wf_tac } lemma grundy_value_eq_mex_left (G : pgame) : grundy_value G = ordinal.mex.{u u} (λ i, grundy_value (G.move_left i)) := by rw grundy_value /-- The Sprague-Grundy theorem which states that every impartial game is equivalent to a game of nim, namely the game of nim corresponding to the games Grundy value -/ theorem equiv_nim_grundy_value : ∀ (G : pgame.{u}) [G.impartial], G ≈ nim (grundy_value G) | G := begin introI hG, rw [impartial.equiv_iff_add_equiv_zero, ←impartial.forall_left_moves_fuzzy_iff_equiv_zero], intro i, apply left_moves_add_cases i, { intro i₁, rw add_move_left_inl, apply (fuzzy_congr_left (add_congr_left (equiv_nim_grundy_value (G.move_left i₁)).symm)).1, rw nim_add_fuzzy_zero_iff, intro heq, rw [eq_comm, grundy_value_eq_mex_left G] at heq, have h := ordinal.ne_mex _, rw heq at h, exact (h i₁).irrefl }, { intro i₂, rw [add_move_left_inr, ←impartial.exists_left_move_equiv_iff_fuzzy_zero], revert i₂, rw nim_def, intro i₂, have h' : ∃ i : G.left_moves, (grundy_value (G.move_left i)) = ordinal.typein (quotient.out (grundy_value G)).r i₂, { revert i₂, rw grundy_value_eq_mex_left, intros i₂, have hnotin : _ ∉ _ := λ hin, (le_not_le_of_lt (ordinal.typein_lt_self i₂)).2 (cInf_le' hin), simpa using hnotin}, cases h' with i hi, use to_left_moves_add (sum.inl i), rw [add_move_left_inl, move_left_mk], apply (add_congr_left (equiv_nim_grundy_value (G.move_left i))).trans, simpa only [hi] using impartial.add_self (nim (grundy_value (G.move_left i))) } end using_well_founded { dec_tac := pgame_wf_tac } lemma grundy_value_eq_iff_equiv_nim {G : pgame} [G.impartial] {o : ordinal} : grundy_value G = o ↔ G ≈ nim o := ⟨by { rintro rfl, exact equiv_nim_grundy_value G }, by { intro h, rw ←nim_equiv_iff_eq, exact (equiv_nim_grundy_value G).symm.trans h }⟩ @[simp] lemma nim_grundy_value (o : ordinal.{u}) : grundy_value (nim o) = o := grundy_value_eq_iff_equiv_nim.2 pgame.equiv_rfl lemma grundy_value_eq_iff_equiv (G H : pgame) [G.impartial] [H.impartial] : grundy_value G = grundy_value H ↔ G ≈ H := grundy_value_eq_iff_equiv_nim.trans (equiv_congr_left.1 (equiv_nim_grundy_value H) _).symm @[simp] lemma grundy_value_zero : grundy_value 0 = 0 := grundy_value_eq_iff_equiv_nim.2 nim_zero_equiv.symm lemma grundy_value_iff_equiv_zero (G : pgame) [G.impartial] : grundy_value G = 0 ↔ G ≈ 0 := by rw [←grundy_value_eq_iff_equiv, grundy_value_zero] @[simp] lemma grundy_value_star : grundy_value star = 1 := grundy_value_eq_iff_equiv_nim.2 nim_one_equiv.symm @[simp] lemma grundy_value_neg (G : pgame) [G.impartial] : grundy_value (-G) = grundy_value G := by rw [grundy_value_eq_iff_equiv_nim, neg_equiv_iff, neg_nim, ←grundy_value_eq_iff_equiv_nim] lemma grundy_value_eq_mex_right : ∀ (G : pgame) [G.impartial], grundy_value G = ordinal.mex.{u u} (λ i, grundy_value (G.move_right i)) | ⟨l, r, L, R⟩ := begin introI H, rw [←grundy_value_neg, grundy_value_eq_mex_left], congr, ext i, haveI : (R i).impartial := @impartial.move_right_impartial ⟨l, r, L, R⟩ _ i, apply grundy_value_neg end /-- The Grundy value of the sum of two nim games with natural numbers of piles equals their bitwise xor. -/ -- Todo: this actually generalizes to all ordinals, by defining `ordinal.lxor` as the pairwise -- `nat.lxor` of base `ω` Cantor normal forms. @[simp] lemma grundy_value_nim_add_nim (n m : ℕ) : grundy_value (nim.{u} n + nim.{u} m) = nat.lxor n m := begin -- We do strong induction on both variables. induction n using nat.strong_induction_on with n hn generalizing m, induction m using nat.strong_induction_on with m hm, rw grundy_value_eq_mex_left, apply (ordinal.mex_le_of_ne.{u u} (λ i, _)).antisymm (ordinal.le_mex_of_forall (λ ou hu, _)), -- The Grundy value `nat.lxor n m` can't be reached by left moves. { apply left_moves_add_cases i; { -- A left move leaves us with a Grundy value of `nat.lxor k m` for `k < n`, or `nat.lxor n k` -- for `k < m`. refine λ a, left_moves_nim_rec_on a (λ ok hk, _), obtain ⟨k, rfl⟩ := ordinal.lt_omega.1 (hk.trans (ordinal.nat_lt_omega _)), simp only [add_move_left_inl, add_move_left_inr, move_left_nim', equiv.symm_apply_apply], -- The inequality follows from injectivity. rw nat_cast_lt at hk, rw hn _ hk <|> rw hm _ hk, refine λ h, hk.ne _, rw ordinal.nat_cast_inj at h, rwa nat.lxor_left_inj at h <|> rwa nat.lxor_right_inj at h } }, -- Every other smaller Grundy value can be reached by left moves. { -- If `u < nat.lxor m n`, then either `nat.lxor u n < m` or `nat.lxor u m < n`. obtain ⟨u, rfl⟩ := ordinal.lt_omega.1 (hu.trans (ordinal.nat_lt_omega _)), replace hu := ordinal.nat_cast_lt.1 hu, cases nat.lt_lxor_cases hu with h h, -- In the first case, reducing the `m` pile to `nat.lxor u n` gives the desired Grundy value. { refine ⟨to_left_moves_add (sum.inl $ to_left_moves_nim ⟨_, ordinal.nat_cast_lt.2 h⟩), _⟩, simp [nat.lxor_cancel_right, hn _ h] }, -- In the second case, reducing the `n` pile to `nat.lxor u m` gives the desired Grundy value. { refine ⟨to_left_moves_add (sum.inr $ to_left_moves_nim ⟨_, ordinal.nat_cast_lt.2 h⟩), _⟩, have : n.lxor (u.lxor n) = u, rw [nat.lxor_comm u, nat.lxor_cancel_left], simpa [hm _ h] using this } } end lemma nim_add_nim_equiv {n m : ℕ} : nim n + nim m ≈ nim (nat.lxor n m) := by rw [←grundy_value_eq_iff_equiv_nim, grundy_value_nim_add_nim] lemma grundy_value_add (G H : pgame) [G.impartial] [H.impartial] {n m : ℕ} (hG : grundy_value G = n) (hH : grundy_value H = m) : grundy_value (G + H) = nat.lxor n m := begin rw [←nim_grundy_value (nat.lxor n m), grundy_value_eq_iff_equiv], refine equiv.trans _ nim_add_nim_equiv, convert add_congr (equiv_nim_grundy_value G) (equiv_nim_grundy_value H); simp only [hG, hH] end end pgame
d1e0be8d2eb9b1888d9c29eb40d91cb8c20366fb
7cef822f3b952965621309e88eadf618da0c8ae9
/src/topology/compact_open.lean
a74ad27d5a9a96445bdeec956b4dc19ccdb66db6
[ "Apache-2.0" ]
permissive
rmitta/mathlib
8d90aee30b4db2b013e01f62c33f297d7e64a43d
883d974b608845bad30ae19e27e33c285200bf84
refs/heads/master
1,585,776,832,544
1,576,874,096,000
1,576,874,096,000
153,663,165
0
2
Apache-2.0
1,544,806,490,000
1,539,884,365,000
Lean
UTF-8
Lean
false
false
4,103
lean
/- Copyright (c) 2018 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton Type of continuous maps and the compact-open topology on them. -/ import topology.subset_properties tactic.tidy open set open_locale topological_space universes u v w def continuous_map (α : Type u) (β : Type v) [topological_space α] [topological_space β] : Type (max u v) := subtype (continuous : (α → β) → Prop) local notation `C(` α `, ` β `)` := continuous_map α β namespace continuous_map section compact_open variables {α : Type u} {β : Type v} {γ : Type w} variables [topological_space α] [topological_space β] [topological_space γ] instance : has_coe_to_fun C(α, β) := ⟨λ_, α → β, λf, f.1⟩ def compact_open.gen (s : set α) (u : set β) : set C(α,β) := {f | f '' s ⊆ u} -- The compact-open topology on the space of continuous maps α → β. instance compact_open : topological_space C(α, β) := topological_space.generate_from {m | ∃ (s : set α) (hs : compact s) (u : set β) (hu : is_open u), m = compact_open.gen s u} private lemma is_open_gen {s : set α} (hs : 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 : β → γ} (hg : continuous g) def induced (f : C(α, β)) : C(α, γ) := ⟨g ∘ f, hg.comp f.property⟩ private lemma preimage_gen {s : set α} (hs : compact s) {u : set γ} (hu : is_open u) : continuous_map.induced hg ⁻¹' (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_induced : continuous (continuous_map.induced hg : C(α, β) → C(α, γ)) := continuous_generated_from $ assume m ⟨s, hs, u, hu, hm⟩, by rw [hm, preimage_gen hg hs hu]; exact is_open_gen hs (hg _ hu) end functorial section ev variables (α β) def ev (p : C(α, β) × α) : β := p.1 p.2 variables {α β} -- The evaluation map C(α, β) × α → β is continuous if α is locally compact. lemma continuous_ev [locally_compact_space α] : continuous (ev α β) := continuous_iff_continuous_at.mpr $ assume ⟨f, x⟩ n hn, let ⟨v, vn, vo, fxv⟩ := mem_nhds_sets_iff.mp hn in have v ∈ 𝓝 (f.val x), from mem_nhds_sets vo fxv, let ⟨s, hs, sv, sc⟩ := locally_compact_space.local_compact_nhds x (f.val ⁻¹' v) (f.property.tendsto x this) in let ⟨u, us, uo, xu⟩ := mem_nhds_sets_iff.mp hs in show (ev α β) ⁻¹' n ∈ 𝓝 (f, x), from let w := set.prod (compact_open.gen s v) u in have w ⊆ ev α β ⁻¹' n, from assume ⟨f', x'⟩ ⟨hf', hx'⟩, calc f'.val x' ∈ f'.val '' s : mem_image_of_mem f'.val (us hx') ... ⊆ v : hf' ... ⊆ n : vn, have is_open w, from is_open_prod (is_open_gen sc vo) uo, have (f, x) ∈ w, from ⟨image_subset_iff.mpr sv, xu⟩, mem_nhds_sets_iff.mpr ⟨w, by assumption, by assumption, by assumption⟩ end ev section coev variables (α β) def coev (b : β) : C(α, β × α) := ⟨λ a, (b, a), continuous.prod_mk continuous_const continuous_id⟩ variables {α β} lemma image_coev {y : β} (s : set α) : (coev α β y).val '' s = set.prod {y} s := by tidy -- The coevaluation map β → C(α, β × α) is continuous (always). lemma continuous_coev : continuous (coev α β) := continuous_generated_from $ begin rintros _ ⟨s, sc, u, uo, rfl⟩, rw is_open_iff_forall_mem_open, intros y hy, change (coev α β y).val '' s ⊆ u at hy, rw image_coev s at hy, rcases generalized_tube_lemma 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').val '' s ⊆ u, rw image_coev s, exact subset.trans (prod_mono (singleton_subset_iff.mpr hy') sw) vwu end end coev end compact_open end continuous_map
6d97f8487a72310720dbdab51e3c21552d34be1b
649957717d58c43b5d8d200da34bf374293fe739
/test/tactics.lean
3286d9b64e70eb980b6c267dfa850370ee96fa21
[ "Apache-2.0" ]
permissive
Vtec234/mathlib
b50c7b21edea438df7497e5ed6a45f61527f0370
fb1848bbbfce46152f58e219dc0712f3289d2b20
refs/heads/master
1,592,463,095,113
1,562,737,749,000
1,562,737,749,000
196,202,858
0
0
Apache-2.0
1,562,762,338,000
1,562,762,337,000
null
UTF-8
Lean
false
false
6,498
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Scott Morrison -/ import tactic.interactive tactic.finish tactic.ext example (m n p q : nat) (h : m + n = p) : true := begin have : m + n = q, { generalize_hyp h' : m + n = x at h, guard_hyp h' := m + n = x, guard_hyp h := x = p, guard_target m + n = q, admit }, have : m + n = q, { generalize_hyp h' : m + n = x at h ⊢, guard_hyp h' := m + n = x, guard_hyp h := x = p, guard_target x = q, admit }, trivial end example (α : Sort*) (L₁ L₂ L₃ : list α) (H : L₁ ++ L₂ = L₃) : true := begin have : L₁ ++ L₂ = L₂, { generalize_hyp h : L₁ ++ L₂ = L at H, induction L with hd tl ih, case list.nil { tactic.cleanup, change list.nil = L₃ at H, admit }, case list.cons { change list.cons hd tl = L₃ at H, admit } }, trivial end section apply_rules example {a b c d e : nat} (h1 : a ≤ b) (h2 : c ≤ d) (h3 : 0 ≤ e) : a + c * e + a + c + 0 ≤ b + d * e + b + d + e := add_le_add (add_le_add (add_le_add (add_le_add h1 (mul_le_mul_of_nonneg_right h2 h3)) h1 ) h2) h3 example {a b c d e : nat} (h1 : a ≤ b) (h2 : c ≤ d) (h3 : 0 ≤ e) : a + c * e + a + c + 0 ≤ b + d * e + b + d + e := by apply_rules [add_le_add, mul_le_mul_of_nonneg_right] @[user_attribute] meta def mono_rules : user_attribute := { name := `mono_rules, descr := "lemmas usable to prove monotonicity" } attribute [mono_rules] add_le_add mul_le_mul_of_nonneg_right example {a b c d e : nat} (h1 : a ≤ b) (h2 : c ≤ d) (h3 : 0 ≤ e) : a + c * e + a + c + 0 ≤ b + d * e + b + d + e := by apply_rules [mono_rules] example {a b c d e : nat} (h1 : a ≤ b) (h2 : c ≤ d) (h3 : 0 ≤ e) : a + c * e + a + c + 0 ≤ b + d * e + b + d + e := by apply_rules mono_rules end apply_rules section h_generalize variables {α β γ φ ψ : Type} (f : α → α → α → φ → γ) (x y : α) (a b : β) (z : φ) (h₀ : β = α) (h₁ : β = α) (h₂ : φ = β) (hx : x == a) (hy : y == b) (hz : z == a) include f x y z a b hx hy hz example : f x y x z = f (eq.rec_on h₀ a) (cast h₀ b) (eq.mpr h₁.symm a) (eq.mpr h₂ a) := begin guard_hyp_nums 16, h_generalize hp : a == p with hh, guard_hyp_nums 19, guard_hyp' hh := β = α, guard_target f x y x z = f p (cast h₀ b) p (eq.mpr h₂ a), h_generalize hq : _ == q, guard_hyp_nums 21, guard_target f x y x z = f p q p (eq.mpr h₂ a), h_generalize _ : _ == r, guard_hyp_nums 23, guard_target f x y x z = f p q p r, casesm* [_ == _, _ = _], refl end end h_generalize section h_generalize variables {α β γ φ ψ : Type} (f : list α → list α → γ) (x : list α) (a : list β) (z : φ) (h₀ : β = α) (h₁ : list β = list α) (hx : x == a) include f x z a hx h₀ h₁ example : true := begin have : f x x = f (eq.rec_on h₀ a) (cast h₁ a), { guard_hyp_nums 11, h_generalize : a == p with _, guard_hyp_nums 13, guard_hyp' h := β = α, guard_target f x x = f p (cast h₁ a), h_generalize! : a == q , guard_hyp_nums 13, guard_target ∀ q, f x x = f p q, casesm* [_ == _, _ = _], success_if_fail { refl }, admit }, trivial end end h_generalize -- section tfae -- example (p q r s : Prop) -- (h₀ : p ↔ q) -- (h₁ : q ↔ r) -- (h₂ : r ↔ s) : -- p ↔ s := -- begin -- scc, -- end -- example (p' p q r r' s s' : Prop) -- (h₀ : p' → p) -- (h₀ : p → q) -- (h₁ : q → r) -- (h₁ : r' → r) -- (h₂ : r ↔ s) -- (h₂ : s → p) -- (h₂ : s → s') : -- p ↔ s := -- begin -- scc, -- end -- example (p' p q r r' s s' : Prop) -- (h₀ : p' → p) -- (h₀ : p → q) -- (h₁ : q → r) -- (h₁ : r' → r) -- (h₂ : r ↔ s) -- (h₂ : s → p) -- (h₂ : s → s') : -- p ↔ s := -- begin -- scc', -- assumption -- end -- example : tfae [true, ∀ n : ℕ, 0 ≤ n * n, true, true] := begin -- tfae_have : 3 → 1, { intro h, constructor }, -- tfae_have : 2 → 3, { intro h, constructor }, -- tfae_have : 2 ← 1, { intros h n, apply nat.zero_le }, -- tfae_have : 4 ↔ 2, { tauto }, -- tfae_finish, -- end -- example : tfae [] := begin -- tfae_finish, -- end -- end tfae section clear_aux_decl example (n m : ℕ) (h₁ : n = m) (h₂ : ∃ a : ℕ, a = n ∧ a = m) : 2 * m = 2 * n := let ⟨a, ha⟩ := h₂ in begin clear_aux_decl, -- subst will fail without this line subst h₁ end example (x y : ℕ) (h₁ : ∃ n : ℕ, n * 1 = 2) (h₂ : 1 + 1 = 2 → x * 1 = y) : x = y := let ⟨n, hn⟩ := h₁ in begin clear_aux_decl, -- finish produces an error without this line finish end end clear_aux_decl section congr example (c : Prop → Prop → Prop → Prop) (x x' y z z' : Prop) (h₀ : x ↔ x') (h₁ : z ↔ z') : c x y z ↔ c x' y z' := begin congr', { guard_target x = x', ext, assumption }, { guard_target z = z', ext, assumption }, end end congr section convert_to example {a b c d : ℕ} (H : a = c) (H' : b = d) : a + b = d + c := by {convert_to c + d = _ using 2, from H, from H', rw[add_comm]} example {a b c d : ℕ} (H : a = c) (H' : b = d) : a + b = d + c := by {convert_to c + d = _ using 0, congr' 2, from H, from H', rw[add_comm]} example (a b c d e f g N : ℕ) : (a + b) + (c + d) + (e + f) + g ≤ a + d + e + f + c + g + b := by {ac_change a + d + e + f + c + g + b ≤ _, refl} end convert_to private meta def get_exception_message (t : lean.parser unit) : lean.parser string | s := match t s with | result.success a s' := result.success "No exception" s | result.exception none pos s' := result.success "Exception no msg" s | result.exception (some msg) pos s' := result.success (msg ()).to_string s end @[user_command] meta def test_parser1_fail_cmd (_ : interactive.parse (lean.parser.tk "test_parser1")) : lean.parser unit := do let msg := "oh, no!", let t : lean.parser unit := tactic.fail msg, s ← get_exception_message t, if s = msg then tactic.skip else interaction_monad.fail "Message was corrupted while being passed through `lean.parser.of_tactic`" . -- Due to `lean.parser.of_tactic'` priority, the following *should not* fail with -- a VM check error, and instead catch the error gracefully and just -- run and succeed silently. test_parser1
03a6701a7806fc32b00fc24b113af878509845eb
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/measure_theory/set_integral.lean
3afef7bb9166e736c8aa103f4db18b1ab96aeb8e
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
46,668
lean
/- Copyright (c) 2020 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou, Yury Kudryashov -/ import measure_theory.bochner_integration import analysis.normed_space.indicator_function /-! # Set integral In this file we prove some properties of `∫ x in s, f x ∂μ`. Recall that this notation is defined as `∫ x, f x ∂(μ.restrict s)`. In `integral_indicator` we prove that for a measurable function `f` and a measurable set `s` this definition coincides with another natural definition: `∫ x, indicator s f x ∂μ = ∫ x in s, f x ∂μ`, where `indicator s f x` is equal to `f x` for `x ∈ s` and is zero otherwise. Since `∫ x in s, f x ∂μ` is a notation, one can rewrite or apply any theorem about `∫ x, f x ∂μ` directly. In this file we prove some theorems about dependence of `∫ x in s, f x ∂μ` on `s`, e.g. `integral_union`, `integral_empty`, `integral_univ`. We also define `integrable_on f s μ := integrable f (μ.restrict s)` and prove theorems like `integrable_on_union : integrable_on f (s ∪ t) μ ↔ integrable_on f s μ ∧ integrable_on f t μ`. Next we define a predicate `integrable_at_filter (f : α → E) (l : filter α) (μ : measure α)` saying that `f` is integrable at some set `s ∈ l` and prove that a measurable function is integrable at `l` with respect to `μ` provided that `f` is bounded above at `l ⊓ μ.ae` and `μ` is finite at `l`. Finally, we prove a version of the [Fundamental theorem of calculus](https://en.wikipedia.org/wiki/Fundamental_theorem_of_calculus) for set integral, see `filter.tendsto.integral_sub_linear_is_o_ae` and its corollaries. Namely, consider a measurably generated filter `l`, a measure `μ` finite at this filter, and a function `f` that has a finite limit `c` at `l ⊓ μ.ae`. Then `∫ x in s, f x ∂μ = μ s • c + o(μ s)` as `s` tends to `l.lift' powerset`, i.e. for any `ε>0` there exists `t ∈ l` such that `∥∫ x in s, f x ∂μ - μ s • c∥ ≤ ε * μ s` whenever `s ⊆ t`. We also formulate a version of this theorem for a locally finite measure `μ` and a function `f` continuous at a point `a`. ## Notation We provide the following notations for expressing the integral of a function on a set : * `∫ a in s, f a ∂μ` is `measure_theory.integral (μ.restrict s) f` * `∫ a in s, f a` is `∫ a in s, f a ∂volume` Note that the set notations are defined in the file `measure_theory/bochner_integration`, but we reference them here because all theorems about set integrals are in this file. ## TODO The file ends with over a hundred lines of commented out code. This is the old contents of this file using the `indicator` approach to the definition of `∫ x in s, f x ∂μ`. This code should be migrated to the new definition. -/ noncomputable theory open set filter topological_space measure_theory function open_locale classical topological_space interval big_operators filter ennreal measure_theory variables {α β E F : Type*} [measurable_space α] section piecewise variables {μ : measure α} {s : set α} {f g : α → β} lemma piecewise_ae_eq_restrict (hs : measurable_set s) : piecewise s f g =ᵐ[μ.restrict s] f := begin rw [ae_restrict_eq hs], exact (piecewise_eq_on s f g).eventually_eq.filter_mono inf_le_right end lemma piecewise_ae_eq_restrict_compl (hs : measurable_set s) : piecewise s f g =ᵐ[μ.restrict sᶜ] g := begin rw [ae_restrict_eq hs.compl], exact (piecewise_eq_on_compl s f g).eventually_eq.filter_mono inf_le_right end end piecewise section indicator_function variables [has_zero β] {μ : measure α} {s : set α} {f : α → β} lemma indicator_ae_eq_restrict (hs : measurable_set s) : indicator s f =ᵐ[μ.restrict s] f := piecewise_ae_eq_restrict hs lemma indicator_ae_eq_restrict_compl (hs : measurable_set s) : indicator s f =ᵐ[μ.restrict sᶜ] 0 := piecewise_ae_eq_restrict_compl hs end indicator_function section variables [measurable_space β] {l l' : filter α} {f g : α → β} {μ ν : measure α} /-- A function `f` is measurable at filter `l` w.r.t. a measure `μ` if it is ae-measurable w.r.t. `μ.restrict s` for some `s ∈ l`. -/ def measurable_at_filter (f : α → β) (l : filter α) (μ : measure α . volume_tac) := ∃ s ∈ l, ae_measurable f (μ.restrict s) @[simp] lemma measurable_at_bot {f : α → β} : measurable_at_filter f ⊥ μ := ⟨∅, mem_bot_sets, by simp⟩ protected lemma measurable_at_filter.eventually (h : measurable_at_filter f l μ) : ∀ᶠ s in l.lift' powerset, ae_measurable f (μ.restrict s) := (eventually_lift'_powerset' $ λ s t, ae_measurable.mono_set).2 h protected lemma measurable_at_filter.filter_mono (h : measurable_at_filter f l μ) (h' : l' ≤ l) : measurable_at_filter f l' μ := let ⟨s, hsl, hs⟩ := h in ⟨s, h' hsl, hs⟩ protected lemma ae_measurable.measurable_at_filter (h : ae_measurable f μ) : measurable_at_filter f l μ := ⟨univ, univ_mem_sets, by rwa measure.restrict_univ⟩ lemma ae_measurable.measurable_at_filter_of_mem {s} (h : ae_measurable f (μ.restrict s)) (hl : s ∈ l): measurable_at_filter f l μ := ⟨s, hl, h⟩ protected lemma measurable.measurable_at_filter (h : measurable f) : measurable_at_filter f l μ := h.ae_measurable.measurable_at_filter end namespace measure_theory section normed_group lemma has_finite_integral_restrict_of_bounded [normed_group E] {f : α → E} {s : set α} {μ : measure α} {C} (hs : μ s < ∞) (hf : ∀ᵐ x ∂(μ.restrict s), ∥f x∥ ≤ C) : has_finite_integral f (μ.restrict s) := by haveI : finite_measure (μ.restrict s) := ⟨by rwa [measure.restrict_apply_univ]⟩; exact has_finite_integral_of_bounded hf variables [normed_group E] [measurable_space E] {f g : α → E} {s t : set α} {μ ν : measure α} /-- A function is `integrable_on` a set `s` if it is a measurable function and if the integral of its pointwise norm over `s` is less than infinity. -/ def integrable_on (f : α → E) (s : set α) (μ : measure α . volume_tac) : Prop := integrable f (μ.restrict s) lemma integrable_on.integrable (h : integrable_on f s μ) : integrable f (μ.restrict s) := h @[simp] lemma integrable_on_empty : integrable_on f ∅ μ := by simp [integrable_on, integrable_zero_measure] @[simp] lemma integrable_on_univ : integrable_on f univ μ ↔ integrable f μ := by rw [integrable_on, measure.restrict_univ] lemma integrable_on_zero : integrable_on (λ _, (0:E)) s μ := integrable_zero _ _ _ lemma integrable_on_const {C : E} : integrable_on (λ _, C) s μ ↔ C = 0 ∨ μ s < ∞ := integrable_const_iff.trans $ by rw [measure.restrict_apply_univ] lemma integrable_on.mono (h : integrable_on f t ν) (hs : s ⊆ t) (hμ : μ ≤ ν) : integrable_on f s μ := h.mono_measure $ measure.restrict_mono hs hμ lemma integrable_on.mono_set (h : integrable_on f t μ) (hst : s ⊆ t) : integrable_on f s μ := h.mono hst (le_refl _) lemma integrable_on.mono_measure (h : integrable_on f s ν) (hμ : μ ≤ ν) : integrable_on f s μ := h.mono (subset.refl _) hμ lemma integrable_on.mono_set_ae (h : integrable_on f t μ) (hst : s ≤ᵐ[μ] t) : integrable_on f s μ := h.integrable.mono_measure $ restrict_mono_ae hst lemma integrable.integrable_on (h : integrable f μ) : integrable_on f s μ := h.mono_measure $ measure.restrict_le_self lemma integrable.integrable_on' (h : integrable f (μ.restrict s)) : integrable_on f s μ := h lemma integrable_on.left_of_union (h : integrable_on f (s ∪ t) μ) : integrable_on f s μ := h.mono_set $ subset_union_left _ _ lemma integrable_on.right_of_union (h : integrable_on f (s ∪ t) μ) : integrable_on f t μ := h.mono_set $ subset_union_right _ _ lemma integrable_on.union (hs : integrable_on f s μ) (ht : integrable_on f t μ) : integrable_on f (s ∪ t) μ := (hs.add_measure ht).mono_measure $ measure.restrict_union_le _ _ @[simp] lemma integrable_on_union : integrable_on f (s ∪ t) μ ↔ integrable_on f s μ ∧ integrable_on f t μ := ⟨λ h, ⟨h.left_of_union, h.right_of_union⟩, λ h, h.1.union h.2⟩ @[simp] lemma integrable_on_finite_union {s : set β} (hs : finite s) {t : β → set α} : integrable_on f (⋃ i ∈ s, t i) μ ↔ ∀ i ∈ s, integrable_on f (t i) μ := begin apply hs.induction_on, { simp }, { intros a s ha hs hf, simp [hf, or_imp_distrib, forall_and_distrib] } end @[simp] lemma integrable_on_finset_union {s : finset β} {t : β → set α} : integrable_on f (⋃ i ∈ s, t i) μ ↔ ∀ i ∈ s, integrable_on f (t i) μ := integrable_on_finite_union s.finite_to_set lemma integrable_on.add_measure (hμ : integrable_on f s μ) (hν : integrable_on f s ν) : integrable_on f s (μ + ν) := by { delta integrable_on, rw measure.restrict_add, exact hμ.integrable.add_measure hν } @[simp] lemma integrable_on_add_measure : integrable_on f s (μ + ν) ↔ integrable_on f s μ ∧ integrable_on f s ν := ⟨λ h, ⟨h.mono_measure (measure.le_add_right (le_refl _)), h.mono_measure (measure.le_add_left (le_refl _))⟩, λ h, h.1.add_measure h.2⟩ lemma ae_measurable_indicator_iff (hs : measurable_set s) : ae_measurable f (μ.restrict s) ↔ ae_measurable (indicator s f) μ := begin split, { assume h, refine ⟨indicator s (h.mk f), h.measurable_mk.indicator hs, _⟩, have A : s.indicator f =ᵐ[μ.restrict s] s.indicator (ae_measurable.mk f h) := (indicator_ae_eq_restrict hs).trans (h.ae_eq_mk.trans $ (indicator_ae_eq_restrict hs).symm), have B : s.indicator f =ᵐ[μ.restrict sᶜ] s.indicator (ae_measurable.mk f h) := (indicator_ae_eq_restrict_compl hs).trans (indicator_ae_eq_restrict_compl hs).symm, have : s.indicator f =ᵐ[μ.restrict s + μ.restrict sᶜ] s.indicator (ae_measurable.mk f h) := ae_add_measure_iff.2 ⟨A, B⟩, simpa only [hs, measure.restrict_add_restrict_compl] using this }, { assume h, exact (h.mono_measure measure.restrict_le_self).congr (indicator_ae_eq_restrict hs) } end lemma integrable_indicator_iff (hs : measurable_set s) : integrable (indicator s f) μ ↔ integrable_on f s μ := by simp [integrable_on, integrable, has_finite_integral, nnnorm_indicator_eq_indicator_nnnorm, ennreal.coe_indicator, lintegral_indicator _ hs, ae_measurable_indicator_iff hs] lemma integrable_on.indicator (h : integrable_on f s μ) (hs : measurable_set s) : integrable (indicator s f) μ := (integrable_indicator_iff hs).2 h lemma integrable.indicator (h : integrable f μ) (hs : measurable_set s) : integrable (indicator s f) μ := h.integrable_on.indicator hs /-- We say that a function `f` is *integrable at filter* `l` if it is integrable on some set `s ∈ l`. Equivalently, it is eventually integrable on `s` in `l.lift' powerset`. -/ def integrable_at_filter (f : α → E) (l : filter α) (μ : measure α . volume_tac) := ∃ s ∈ l, integrable_on f s μ variables {l l' : filter α} protected lemma integrable_at_filter.eventually (h : integrable_at_filter f l μ) : ∀ᶠ s in l.lift' powerset, integrable_on f s μ := by { refine (eventually_lift'_powerset' $ λ s t hst ht, _).2 h, exact ht.mono_set hst } lemma integrable_at_filter.filter_mono (hl : l ≤ l') (hl' : integrable_at_filter f l' μ) : integrable_at_filter f l μ := let ⟨s, hs, hsf⟩ := hl' in ⟨s, hl hs, hsf⟩ lemma integrable_at_filter.inf_of_left (hl : integrable_at_filter f l μ) : integrable_at_filter f (l ⊓ l') μ := hl.filter_mono inf_le_left lemma integrable_at_filter.inf_of_right (hl : integrable_at_filter f l μ) : integrable_at_filter f (l' ⊓ l) μ := hl.filter_mono inf_le_right @[simp] lemma integrable_at_filter.inf_ae_iff {l : filter α} : integrable_at_filter f (l ⊓ μ.ae) μ ↔ integrable_at_filter f l μ := begin refine ⟨_, λ h, h.filter_mono inf_le_left⟩, rintros ⟨s, ⟨t, ht, u, hu, hs⟩, hf⟩, refine ⟨t, ht, _⟩, refine hf.integrable.mono_measure (λ v hv, _), simp only [measure.restrict_apply hv], refine measure_mono_ae (mem_sets_of_superset hu $ λ x hx, _), exact λ ⟨hv, ht⟩, ⟨hv, hs ⟨ht, hx⟩⟩ end alias integrable_at_filter.inf_ae_iff ↔ measure_theory.integrable_at_filter.of_inf_ae _ /-- If `μ` is a measure finite at filter `l` and `f` is a function such that its norm is bounded above at `l`, then `f` is integrable at `l`. -/ lemma measure.finite_at_filter.integrable_at_filter {l : filter α} [is_measurably_generated l] (hfm : measurable_at_filter f l μ) (hμ : μ.finite_at_filter l) (hf : l.is_bounded_under (≤) (norm ∘ f)) : integrable_at_filter f l μ := begin obtain ⟨C, hC⟩ : ∃ C, ∀ᶠ s in (l.lift' powerset), ∀ x ∈ s, ∥f x∥ ≤ C, from hf.imp (λ C hC, eventually_lift'_powerset.2 ⟨_, hC, λ t, id⟩), rcases (hfm.eventually.and (hμ.eventually.and hC)).exists_measurable_mem_of_lift' with ⟨s, hsl, hsm, hfm, hμ, hC⟩, refine ⟨s, hsl, ⟨hfm, has_finite_integral_restrict_of_bounded hμ _⟩⟩, exact C, rw [ae_restrict_eq hsm, eventually_inf_principal], exact eventually_of_forall hC end lemma measure.finite_at_filter.integrable_at_filter_of_tendsto_ae {l : filter α} [is_measurably_generated l] (hfm : measurable_at_filter f l μ) (hμ : μ.finite_at_filter l) {b} (hf : tendsto f (l ⊓ μ.ae) (𝓝 b)) : integrable_at_filter f l μ := (hμ.inf_of_left.integrable_at_filter (hfm.filter_mono inf_le_left) hf.norm.is_bounded_under_le).of_inf_ae alias measure.finite_at_filter.integrable_at_filter_of_tendsto_ae ← filter.tendsto.integrable_at_filter_ae lemma measure.finite_at_filter.integrable_at_filter_of_tendsto {l : filter α} [is_measurably_generated l] (hfm : measurable_at_filter f l μ) (hμ : μ.finite_at_filter l) {b} (hf : tendsto f l (𝓝 b)) : integrable_at_filter f l μ := hμ.integrable_at_filter hfm hf.norm.is_bounded_under_le alias measure.finite_at_filter.integrable_at_filter_of_tendsto ← filter.tendsto.integrable_at_filter variables [borel_space E] [second_countable_topology E] lemma integrable_add [opens_measurable_space E] {f g : α → E} (h : disjoint (support f) (support g)) (hf : measurable f) (hg : measurable g) : integrable (f + g) μ ↔ integrable f μ ∧ integrable g μ := begin refine ⟨λ hfg, ⟨_, _⟩, λ h, h.1.add h.2⟩, { rw ← indicator_add_eq_left h, exact hfg.indicator (measurable_set_support hf) }, { rw ← indicator_add_eq_right h, exact hfg.indicator (measurable_set_support hg) } end /-- To prove something for an arbitrary integrable function in a second countable Borel normed group, it suffices to show that * the property holds for (multiples of) characteristic functions; * is closed under addition; * the set of functions in the `L¹` space for which the property holds is closed. * the property is closed under the almost-everywhere equal relation. 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_add` 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] lemma integrable.induction (P : (α → E) → Prop) (h_ind : ∀ (c : E) ⦃s⦄, measurable_set s → μ s < ∞ → P (s.indicator (λ _, c))) (h_add : ∀ ⦃f g : α → E⦄, disjoint (support f) (support g) → integrable f μ → integrable g μ → P f → P g → P (f + g)) (h_closed : is_closed {f : α →₁[μ] E | P f} ) (h_ae : ∀ ⦃f g⦄, f =ᵐ[μ] g → integrable f μ → P f → P g) : ∀ ⦃f : α → E⦄ (hf : integrable f μ), P f := begin have : ∀ (f : simple_func α E), integrable f μ → P f, { refine simple_func.induction _ _, { intros c s hs h, dsimp only [simple_func.coe_const, simple_func.const_zero, piecewise_eq_indicator, simple_func.coe_zero, simple_func.coe_piecewise] at h ⊢, by_cases hc : c = 0, { subst hc, convert h_ind 0 measurable_set.empty (by simp) using 1, simp [const] }, apply h_ind c hs, have : (nnnorm c : ℝ≥0∞) * μ s < ∞, { have := @comp_indicator _ _ _ _ (λ x : E, (nnnorm x : ℝ≥0∞)) (const α c) s, dsimp only at this, have h' := h.has_finite_integral, simpa [has_finite_integral, this, lintegral_indicator, hs] using h' }, exact ennreal.lt_top_of_mul_lt_top_right this (by simp [hc]) }, { intros f g hfg hf hg int_fg, rw [simple_func.coe_add, integrable_add hfg f.measurable g.measurable] at int_fg, refine h_add hfg int_fg.1 int_fg.2 (hf int_fg.1) (hg int_fg.2) } }, have : ∀ (f : α →₁ₛ[μ] E), P f, { intro f, exact h_ae (L1.simple_func.to_simple_func_eq_to_fun f) (L1.simple_func.integrable f) (this (L1.simple_func.to_simple_func f) (L1.simple_func.integrable f)) }, have : ∀ (f : α →₁[μ] E), P f := λ f, L1.simple_func.dense_range.induction_on f h_closed this, exact λ f hf, h_ae hf.coe_fn_to_L1 (L1.integrable_coe_fn _) (this (hf.to_L1 f)), end variables [complete_space E] [normed_space ℝ E] lemma set_integral_congr_ae (hs : measurable_set s) (h : ∀ᵐ x ∂μ, x ∈ s → f x = g x) : ∫ x in s, f x ∂μ = ∫ x in s, g x ∂μ := integral_congr_ae ((ae_restrict_iff' hs).2 h) lemma set_integral_congr (hs : measurable_set s) (h : eq_on f g s) : ∫ x in s, f x ∂μ = ∫ x in s, g x ∂μ := set_integral_congr_ae hs $ eventually_of_forall h lemma integral_union (hst : disjoint s t) (hs : measurable_set s) (ht : measurable_set t) (hfs : integrable_on f s μ) (hft : integrable_on f t μ) : ∫ x in s ∪ t, f x ∂μ = ∫ x in s, f x ∂μ + ∫ x in t, f x ∂μ := by simp only [integrable_on, measure.restrict_union hst hs ht, integral_add_measure hfs hft] lemma integral_empty : ∫ x in ∅, f x ∂μ = 0 := by rw [measure.restrict_empty, integral_zero_measure] lemma integral_univ : ∫ x in univ, f x ∂μ = ∫ x, f x ∂μ := by rw [measure.restrict_univ] lemma integral_add_compl (hs : measurable_set s) (hfi : integrable f μ) : ∫ x in s, f x ∂μ + ∫ x in sᶜ, f x ∂μ = ∫ x, f x ∂μ := by rw [← integral_union (@disjoint_compl_right (set α) _ _) hs hs.compl hfi.integrable_on hfi.integrable_on, union_compl_self, integral_univ] /-- For a function `f` and a measurable set `s`, the integral of `indicator s f` over the whole space is equal to `∫ x in s, f x ∂μ` defined as `∫ x, f x ∂(μ.restrict s)`. -/ lemma integral_indicator (hs : measurable_set s) : ∫ x, indicator s f x ∂μ = ∫ x in s, f x ∂μ := begin by_cases hf : ae_measurable f (μ.restrict s), swap, { rw integral_non_ae_measurable hf, rw [ae_measurable_indicator_iff hs] at hf, exact integral_non_ae_measurable hf }, by_cases hfi : integrable_on f s μ, swap, { rwa [integral_undef, integral_undef], rwa integrable_indicator_iff hs }, calc ∫ x, indicator s f x ∂μ = ∫ x in s, indicator s f x ∂μ + ∫ x in sᶜ, indicator s f x ∂μ : (integral_add_compl hs (hfi.indicator hs)).symm ... = ∫ x in s, f x ∂μ + ∫ x in sᶜ, 0 ∂μ : congr_arg2 (+) (integral_congr_ae (indicator_ae_eq_restrict hs)) (integral_congr_ae (indicator_ae_eq_restrict_compl hs)) ... = ∫ x in s, f x ∂μ : by simp end lemma set_integral_const (c : E) : ∫ x in s, c ∂μ = (μ s).to_real • c := by rw [integral_const, measure.restrict_apply_univ] @[simp] lemma integral_indicator_const (e : E) ⦃s : set α⦄ (s_meas : measurable_set s) : ∫ (a : α), s.indicator (λ (x : α), e) a ∂μ = (μ s).to_real • e := by rw [integral_indicator s_meas, ← set_integral_const] lemma set_integral_map {β} [measurable_space β] {g : α → β} {f : β → E} {s : set β} (hs : measurable_set s) (hf : ae_measurable f (measure.map g μ)) (hg : measurable g) : ∫ y in s, f y ∂(measure.map g μ) = ∫ x in g ⁻¹' s, f (g x) ∂μ := begin rw [measure.restrict_map hg hs, integral_map hg (hf.mono_measure _)], exact measure.map_mono g measure.restrict_le_self end lemma set_integral_map_of_closed_embedding [topological_space α] [borel_space α] {β} [measurable_space β] [topological_space β] [borel_space β] {g : α → β} {f : β → E} {s : set β} (hs : measurable_set s) (hg : closed_embedding g) : ∫ y in s, f y ∂(measure.map g μ) = ∫ x in g ⁻¹' s, f (g x) ∂μ := by rw [measure.restrict_map hg.measurable hs, integral_map_of_closed_embedding hg] lemma norm_set_integral_le_of_norm_le_const_ae {C : ℝ} (hs : μ s < ∞) (hC : ∀ᵐ x ∂μ.restrict s, ∥f x∥ ≤ C) : ∥∫ x in s, f x ∂μ∥ ≤ C * (μ s).to_real := begin rw ← measure.restrict_apply_univ at *, haveI : finite_measure (μ.restrict s) := ⟨‹_›⟩, exact norm_integral_le_of_norm_le_const hC end lemma norm_set_integral_le_of_norm_le_const_ae' {C : ℝ} (hs : μ s < ∞) (hC : ∀ᵐ x ∂μ, x ∈ s → ∥f x∥ ≤ C) (hfm : ae_measurable f (μ.restrict s)) : ∥∫ x in s, f x ∂μ∥ ≤ C * (μ s).to_real := begin apply norm_set_integral_le_of_norm_le_const_ae hs, have A : ∀ᵐ (x : α) ∂μ, x ∈ s → ∥ae_measurable.mk f hfm x∥ ≤ C, { filter_upwards [hC, hfm.ae_mem_imp_eq_mk], assume a h1 h2 h3, rw [← h2 h3], exact h1 h3 }, have B : measurable_set {x | ∥(hfm.mk f) x∥ ≤ C} := hfm.measurable_mk.norm measurable_set_Iic, filter_upwards [hfm.ae_eq_mk, (ae_restrict_iff B).2 A], assume a h1 h2, rwa h1 end lemma norm_set_integral_le_of_norm_le_const_ae'' {C : ℝ} (hs : μ s < ∞) (hsm : measurable_set s) (hC : ∀ᵐ x ∂μ, x ∈ s → ∥f x∥ ≤ C) : ∥∫ x in s, f x ∂μ∥ ≤ C * (μ s).to_real := norm_set_integral_le_of_norm_le_const_ae hs $ by rwa [ae_restrict_eq hsm, eventually_inf_principal] lemma norm_set_integral_le_of_norm_le_const {C : ℝ} (hs : μ s < ∞) (hC : ∀ x ∈ s, ∥f x∥ ≤ C) (hfm : ae_measurable f (μ.restrict s)) : ∥∫ x in s, f x ∂μ∥ ≤ C * (μ s).to_real := norm_set_integral_le_of_norm_le_const_ae' hs (eventually_of_forall hC) hfm lemma norm_set_integral_le_of_norm_le_const' {C : ℝ} (hs : μ s < ∞) (hsm : measurable_set s) (hC : ∀ x ∈ s, ∥f x∥ ≤ C) : ∥∫ x in s, f x ∂μ∥ ≤ C * (μ s).to_real := norm_set_integral_le_of_norm_le_const_ae'' hs hsm $ eventually_of_forall hC lemma set_integral_eq_zero_iff_of_nonneg_ae {f : α → ℝ} (hf : 0 ≤ᵐ[μ.restrict s] f) (hfi : integrable_on f s μ) : ∫ x in s, f x ∂μ = 0 ↔ f =ᵐ[μ.restrict s] 0 := integral_eq_zero_iff_of_nonneg_ae hf hfi lemma set_integral_pos_iff_support_of_nonneg_ae {f : α → ℝ} (hf : 0 ≤ᵐ[μ.restrict s] f) (hfi : integrable_on f s μ) : 0 < ∫ x in s, f x ∂μ ↔ 0 < μ (support f ∩ s) := begin rw [integral_pos_iff_support_of_nonneg_ae hf hfi, restrict_apply_of_null_measurable_set], exact hfi.ae_measurable.null_measurable_set (measurable_set_singleton 0).compl end end normed_group section mono variables {μ : measure α} {f g : α → ℝ} {s : set α} (hf : integrable_on f s μ) (hg : integrable_on g s μ) lemma set_integral_mono_ae_restrict (h : f ≤ᵐ[μ.restrict s] g) : ∫ a in s, f a ∂μ ≤ ∫ a in s, g a ∂μ := integral_mono_ae hf hg h lemma set_integral_mono_ae (h : f ≤ᵐ[μ] g) : ∫ a in s, f a ∂μ ≤ ∫ a in s, g a ∂μ := set_integral_mono_ae_restrict hf hg (ae_restrict_of_ae h) lemma set_integral_mono_on (hs : measurable_set s) (h : ∀ x ∈ s, f x ≤ g x) : ∫ a in s, f a ∂μ ≤ ∫ a in s, g a ∂μ := set_integral_mono_ae_restrict hf hg (by simp [hs, eventually_le, eventually_inf_principal, ae_of_all _ h]) lemma set_integral_mono (h : f ≤ g) : ∫ a in s, f a ∂μ ≤ ∫ a in s, g a ∂μ := integral_mono hf hg h end mono section nonneg variables {μ : measure α} {f : α → ℝ} {s : set α} lemma set_integral_nonneg_of_ae_restrict (hf : 0 ≤ᵐ[μ.restrict s] f) : (0:ℝ) ≤ (∫ a in s, f a ∂μ) := integral_nonneg_of_ae hf lemma set_integral_nonneg_of_ae (hf : 0 ≤ᵐ[μ] f) : (0:ℝ) ≤ (∫ a in s, f a ∂μ) := set_integral_nonneg_of_ae_restrict (ae_restrict_of_ae hf) lemma set_integral_nonneg (hs : measurable_set s) (hf : ∀ a, a ∈ s → 0 ≤ f a) : (0:ℝ) ≤ (∫ a in s, f a ∂μ) := set_integral_nonneg_of_ae_restrict ((ae_restrict_iff' hs).mpr (ae_of_all μ hf)) end nonneg end measure_theory open measure_theory asymptotics metric variables {ι : Type*} [measurable_space E] [normed_group E] /-- Fundamental theorem of calculus for set integrals: if `μ` is a measure that is finite at a filter `l` and `f` is a measurable function that has a finite limit `b` at `l ⊓ μ.ae`, then `∫ x in s i, f x ∂μ = μ (s i) • b + o(μ (s i))` at a filter `li` provided that `s i` tends to `l.lift' powerset` along `li`. Since `μ (s i)` is an `ℝ≥0∞` number, we use `(μ (s i)).to_real` in the actual statement. Often there is a good formula for `(μ (s i)).to_real`, so the formalization can take an optional argument `m` with this formula and a proof `of `(λ i, (μ (s i)).to_real) =ᶠ[li] m`. Without these arguments, `m i = (μ (s i)).to_real` is used in the output. -/ lemma filter.tendsto.integral_sub_linear_is_o_ae [normed_space ℝ E] [second_countable_topology E] [complete_space E] [borel_space E] {μ : measure α} {l : filter α} [l.is_measurably_generated] {f : α → E} {b : E} (h : tendsto f (l ⊓ μ.ae) (𝓝 b)) (hfm : measurable_at_filter f l μ) (hμ : μ.finite_at_filter l) {s : ι → set α} {li : filter ι} (hs : tendsto s li (l.lift' powerset)) (m : ι → ℝ := λ i, (μ (s i)).to_real) (hsμ : (λ i, (μ (s i)).to_real) =ᶠ[li] m . tactic.interactive.refl) : is_o (λ i, ∫ x in s i, f x ∂μ - m i • b) m li := begin suffices : is_o (λ s, ∫ x in s, f x ∂μ - (μ s).to_real • b) (λ s, (μ s).to_real) (l.lift' powerset), from (this.comp_tendsto hs).congr' (hsμ.mono $ λ a ha, ha ▸ rfl) hsμ, refine is_o_iff.2 (λ ε ε₀, _), have : ∀ᶠ s in l.lift' powerset, ∀ᶠ x in μ.ae, x ∈ s → f x ∈ closed_ball b ε := eventually_lift'_powerset_eventually.2 (h.eventually $ closed_ball_mem_nhds _ ε₀), filter_upwards [hμ.eventually, (hμ.integrable_at_filter_of_tendsto_ae hfm h).eventually, hfm.eventually, this], simp only [mem_closed_ball, dist_eq_norm], intros s hμs h_integrable hfm h_norm, rw [← set_integral_const, ← integral_sub h_integrable (integrable_on_const.2 $ or.inr hμs), real.norm_eq_abs, abs_of_nonneg ennreal.to_real_nonneg], exact norm_set_integral_le_of_norm_le_const_ae' hμs h_norm (hfm.sub ae_measurable_const) end /-- Fundamental theorem of calculus for set integrals, `nhds_within` version: if `μ` is a locally finite measure and `f` is an almost everywhere measurable function that is continuous at a point `a` within a measurable set `t`, then `∫ x in s i, f x ∂μ = μ (s i) • f a + o(μ (s i))` at a filter `li` provided that `s i` tends to `(𝓝[t] a).lift' powerset` along `li`. Since `μ (s i)` is an `ℝ≥0∞` number, we use `(μ (s i)).to_real` in the actual statement. Often there is a good formula for `(μ (s i)).to_real`, so the formalization can take an optional argument `m` with this formula and a proof `of `(λ i, (μ (s i)).to_real) =ᶠ[li] m`. Without these arguments, `m i = (μ (s i)).to_real` is used in the output. -/ lemma continuous_within_at.integral_sub_linear_is_o_ae [topological_space α] [opens_measurable_space α] [normed_space ℝ E] [second_countable_topology E] [complete_space E] [borel_space E] {μ : measure α} [locally_finite_measure μ] {a : α} {t : set α} {f : α → E} (ha : continuous_within_at f t a) (ht : measurable_set t) (hfm : measurable_at_filter f (𝓝[t] a) μ) {s : ι → set α} {li : filter ι} (hs : tendsto s li ((𝓝[t] a).lift' powerset)) (m : ι → ℝ := λ i, (μ (s i)).to_real) (hsμ : (λ i, (μ (s i)).to_real) =ᶠ[li] m . tactic.interactive.refl) : is_o (λ i, ∫ x in s i, f x ∂μ - m i • f a) m li := by haveI : (𝓝[t] a).is_measurably_generated := ht.nhds_within_is_measurably_generated _; exact (ha.mono_left inf_le_left).integral_sub_linear_is_o_ae hfm (μ.finite_at_nhds_within a t) hs m hsμ /-- Fundamental theorem of calculus for set integrals, `nhds` version: if `μ` is a locally finite measure and `f` is an almost everywhere measurable function that is continuous at a point `a`, then `∫ x in s i, f x ∂μ = μ (s i) • f a + o(μ (s i))` at `li` provided that `s` tends to `(𝓝 a).lift' powerset` along `li. Since `μ (s i)` is an `ℝ≥0∞` number, we use `(μ (s i)).to_real` in the actual statement. Often there is a good formula for `(μ (s i)).to_real`, so the formalization can take an optional argument `m` with this formula and a proof `of `(λ i, (μ (s i)).to_real) =ᶠ[li] m`. Without these arguments, `m i = (μ (s i)).to_real` is used in the output. -/ lemma continuous_at.integral_sub_linear_is_o_ae [topological_space α] [opens_measurable_space α] [normed_space ℝ E] [second_countable_topology E] [complete_space E] [borel_space E] {μ : measure α} [locally_finite_measure μ] {a : α} {f : α → E} (ha : continuous_at f a) (hfm : measurable_at_filter f (𝓝 a) μ) {s : ι → set α} {li : filter ι} (hs : tendsto s li ((𝓝 a).lift' powerset)) (m : ι → ℝ := λ i, (μ (s i)).to_real) (hsμ : (λ i, (μ (s i)).to_real) =ᶠ[li] m . tactic.interactive.refl) : is_o (λ i, ∫ x in s i, f x ∂μ - m i • f a) m li := (ha.mono_left inf_le_left).integral_sub_linear_is_o_ae hfm (μ.finite_at_nhds a) hs m hsμ /-- If a function is integrable at `𝓝[s] x` for each point `x` of a compact set `s`, then it is integrable on `s`. -/ lemma is_compact.integrable_on_of_nhds_within [topological_space α] {μ : measure α} {s : set α} (hs : is_compact s) {f : α → E} (hf : ∀ x ∈ s, integrable_at_filter f (𝓝[s] x) μ) : integrable_on f s μ := is_compact.induction_on hs integrable_on_empty (λ s t hst ht, ht.mono_set hst) (λ s t hs ht, hs.union ht) hf /-- A function which is continuous on a set `s` is almost everywhere measurable with respect to `μ.restrict s`. -/ lemma continuous_on.ae_measurable [topological_space α] [opens_measurable_space α] [borel_space E] {f : α → E} {s : set α} {μ : measure α} (hf : continuous_on f s) (hs : measurable_set s) : ae_measurable f (μ.restrict s) := begin refine ⟨indicator s f, _, (indicator_ae_eq_restrict hs).symm⟩, apply measurable_of_is_open, assume t ht, obtain ⟨u, u_open, hu⟩ : ∃ (u : set α), is_open u ∧ f ⁻¹' t ∩ s = u ∩ s := _root_.continuous_on_iff'.1 hf t ht, rw [indicator_preimage, set.ite, hu], exact (u_open.measurable_set.inter hs).union ((measurable_zero ht.measurable_set).diff hs) end lemma continuous_on.integrable_at_nhds_within [topological_space α] [opens_measurable_space α] [borel_space E] {μ : measure α} [locally_finite_measure μ] {a : α} {t : set α} {f : α → E} (hft : continuous_on f t) (ht : measurable_set t) (ha : a ∈ t) : integrable_at_filter f (𝓝[t] a) μ := by haveI : (𝓝[t] a).is_measurably_generated := ht.nhds_within_is_measurably_generated _; exact (hft a ha).integrable_at_filter ⟨_, self_mem_nhds_within, hft.ae_measurable ht⟩ (μ.finite_at_nhds_within _ _) /-- Fundamental theorem of calculus for set integrals, `nhds_within` version: if `μ` is a locally finite measure, `f` is continuous on a measurable set `t`, and `a ∈ t`, then `∫ x in (s i), f x ∂μ = μ (s i) • f a + o(μ (s i))` at `li` provided that `s i` tends to `(𝓝[t] a).lift' powerset` along `li`. Since `μ (s i)` is an `ℝ≥0∞` number, we use `(μ (s i)).to_real` in the actual statement. Often there is a good formula for `(μ (s i)).to_real`, so the formalization can take an optional argument `m` with this formula and a proof `of `(λ i, (μ (s i)).to_real) =ᶠ[li] m`. Without these arguments, `m i = (μ (s i)).to_real` is used in the output. -/ lemma continuous_on.integral_sub_linear_is_o_ae [topological_space α] [opens_measurable_space α] [normed_space ℝ E] [second_countable_topology E] [complete_space E] [borel_space E] {μ : measure α} [locally_finite_measure μ] {a : α} {t : set α} {f : α → E} (hft : continuous_on f t) (ha : a ∈ t) (ht : measurable_set t) {s : ι → set α} {li : filter ι} (hs : tendsto s li ((𝓝[t] a).lift' powerset)) (m : ι → ℝ := λ i, (μ (s i)).to_real) (hsμ : (λ i, (μ (s i)).to_real) =ᶠ[li] m . tactic.interactive.refl) : is_o (λ i, ∫ x in s i, f x ∂μ - m i • f a) m li := (hft a ha).integral_sub_linear_is_o_ae ht ⟨t, self_mem_nhds_within, hft.ae_measurable ht⟩ hs m hsμ /-- A function `f` continuous on a compact set `s` is integrable on this set with respect to any locally finite measure. -/ lemma continuous_on.integrable_on_compact [topological_space α] [opens_measurable_space α] [borel_space E] [t2_space α] {μ : measure α} [locally_finite_measure μ] {s : set α} (hs : is_compact s) {f : α → E} (hf : continuous_on f s) : integrable_on f s μ := hs.integrable_on_of_nhds_within $ λ x hx, hf.integrable_at_nhds_within hs.measurable_set hx /-- A continuous function `f` is integrable on any compact set with respect to any locally finite measure. -/ lemma continuous.integrable_on_compact [topological_space α] [opens_measurable_space α] [t2_space α] [borel_space E] {μ : measure α} [locally_finite_measure μ] {s : set α} (hs : is_compact s) {f : α → E} (hf : continuous f) : integrable_on f s μ := hf.continuous_on.integrable_on_compact hs /-- A continuous function with compact closure of the support is integrable on the whole space. -/ lemma continuous.integrable_of_compact_closure_support [topological_space α] [opens_measurable_space α] [t2_space α] [borel_space E] {μ : measure α} [locally_finite_measure μ] {f : α → E} (hf : continuous f) (hfc : is_compact (closure $ support f)) : integrable f μ := begin rw [← indicator_eq_self.2 (@subset_closure _ _ (support f)), integrable_indicator_iff is_closed_closure.measurable_set], { exact hf.integrable_on_compact hfc }, { apply_instance } end section /-! ### Continuous linear maps composed with integration The goal of this section is to prove that integration commutes with continuous linear maps. This holds for simple functions. The general result follows from the continuity of all involved operations on the space `L¹`. Note that composition by a continuous linear map on `L¹` is not just the composition, as we are dealing with classes of functions, but it has already been defined as `continuous_linear_map.comp_Lp`. We take advantage of this construction here. -/ variables {μ : measure α} [normed_space ℝ E] variables [normed_group F] [normed_space ℝ F] variables {p : ennreal} local attribute [instance] fact_one_le_one_ennreal namespace continuous_linear_map variables [measurable_space F] [borel_space F] lemma integrable_comp [opens_measurable_space E] {φ : α → E} (L : E →L[ℝ] F) (φ_int : integrable φ μ) : integrable (λ (a : α), L (φ a)) μ := ((integrable.norm φ_int).const_mul ∥L∥).mono' (L.measurable.comp_ae_measurable φ_int.ae_measurable) (eventually_of_forall $ λ a, L.le_op_norm (φ a)) variables [second_countable_topology F] [complete_space F] [borel_space E] [second_countable_topology E] lemma integral_comp_Lp (L : E →L[ℝ] F) (φ : Lp E p μ) : ∫ a, (L.comp_Lp φ) a ∂μ = ∫ a, L (φ a) ∂μ := integral_congr_ae $ coe_fn_comp_Lp _ _ lemma continuous_integral_comp_L1 (L : E →L[ℝ] F) : continuous (λ (φ : α →₁[μ] E), ∫ (a : α), L (φ a) ∂μ) := begin rw ← funext L.integral_comp_Lp, exact continuous_integral.comp (L.comp_LpL 1 μ).continuous end variables [complete_space E] lemma integral_comp_comm (L : E →L[ℝ] F) {φ : α → E} (φ_int : integrable φ μ) : ∫ a, L (φ a) ∂μ = L (∫ a, φ a ∂μ) := begin apply integrable.induction (λ φ, ∫ a, L (φ a) ∂μ = L (∫ a, φ a ∂μ)), { intros e s s_meas s_finite, rw [integral_indicator_const e s_meas, continuous_linear_map.map_smul, ← integral_indicator_const (L e) s_meas], congr' 1 with a, rw set.indicator_comp_of_zero L.map_zero }, { intros f g H f_int g_int hf hg, simp [L.map_add, integral_add f_int g_int, integral_add (L.integrable_comp f_int) (L.integrable_comp g_int), hf, hg] }, { exact is_closed_eq L.continuous_integral_comp_L1 (L.continuous.comp continuous_integral) }, { intros f g hfg f_int hf, convert hf using 1 ; clear hf, { exact integral_congr_ae (hfg.fun_comp L).symm }, { rw integral_congr_ae hfg.symm } }, all_goals { assumption } end lemma integral_comp_comm' (L : E →L[ℝ] F) {K} (hL : antilipschitz_with K L) (φ : α → E) : ∫ a, L (φ a) ∂μ = L (∫ a, φ a ∂μ) := begin by_cases h : integrable φ μ, { exact integral_comp_comm L h }, have : ¬ (integrable (L ∘ φ) μ), by rwa lipschitz_with.integrable_comp_iff_of_antilipschitz L.lipschitz hL (L.map_zero), simp [integral_undef, h, this] end lemma integral_comp_L1_comm (L : E →L[ℝ] F) (φ : α →₁[μ] E) : ∫ a, L (φ a) ∂μ = L (∫ a, φ a ∂μ) := L.integral_comp_comm (L1.integrable_coe_fn φ) end continuous_linear_map namespace linear_isometry variables [measurable_space F] [borel_space F] [complete_space E] [second_countable_topology F] [complete_space F] [borel_space E] [second_countable_topology E] lemma integral_comp_comm (L : E →ₗᵢ[ℝ] F) (φ : α → E) : ∫ a, L (φ a) ∂μ = L (∫ a, φ a ∂μ) := L.to_continuous_linear_map.integral_comp_comm' L.antilipschitz _ end linear_isometry variables [borel_space E] [second_countable_topology E] [complete_space E] [measurable_space F] [borel_space F] [second_countable_topology F] [complete_space F] @[norm_cast] lemma integral_of_real {𝕜 : Type*} [is_R_or_C 𝕜] [measurable_space 𝕜] [borel_space 𝕜] {f : α → ℝ} : ∫ a, (f a : 𝕜) ∂μ = ↑∫ a, f a ∂μ := linear_isometry.integral_comp_comm is_R_or_C.of_real_li f lemma integral_conj {𝕜 : Type*} [is_R_or_C 𝕜] [measurable_space 𝕜] [borel_space 𝕜] {f : α → 𝕜} : ∫ a, is_R_or_C.conj (f a) ∂μ = is_R_or_C.conj ∫ a, f a ∂μ := linear_isometry.integral_comp_comm is_R_or_C.conj_li f lemma fst_integral {f : α → E × F} (hf : integrable f μ) : (∫ x, f x ∂μ).1 = ∫ x, (f x).1 ∂μ := ((continuous_linear_map.fst ℝ E F).integral_comp_comm hf).symm lemma snd_integral {f : α → E × F} (hf : integrable f μ) : (∫ x, f x ∂μ).2 = ∫ x, (f x).2 ∂μ := ((continuous_linear_map.snd ℝ E F).integral_comp_comm hf).symm lemma integral_pair {f : α → E} {g : α → F} (hf : integrable f μ) (hg : integrable g μ) : ∫ x, (f x, g x) ∂μ = (∫ x, f x ∂μ, ∫ x, g x ∂μ) := have _ := hf.prod_mk hg, prod.ext (fst_integral this) (snd_integral this) lemma integral_smul_const (f : α → ℝ) (c : E) : ∫ x, f x • c ∂μ = (∫ x, f x ∂μ) • c := begin by_cases hf : integrable f μ, { exact ((continuous_linear_map.id ℝ ℝ).smul_right c).integral_comp_comm hf }, { by_cases hc : c = 0, { simp only [hc, integral_zero, smul_zero] }, rw [integral_undef hf, integral_undef, zero_smul], simp_rw [integrable_smul_const hc, hf, not_false_iff] } end end /- namespace integrable variables [measurable_space α] [measurable_space β] [normed_group E] protected lemma measure_mono end integrable end measure_theory section integral_on variables [measurable_space α] [normed_group β] [second_countable_topology β] [normed_space ℝ β] [complete_space β] [measurable_space β] [borel_space β] {s t : set α} {f g : α → β} {μ : measure α} open set lemma integral_on_congr (hf : measurable f) (hg : measurable g) (hs : measurable_set s) (h : ∀ᵐ a ∂μ, a ∈ s → f a = g a) : ∫ a in s, f a ∂μ = ∫ a in s, g a ∂μ := integral_congr_ae hf hg $ _ lemma integral_on_congr_of_set (hsm : measurable_on s f) (htm : measurable_on t f) (h : ∀ᵐ a, a ∈ s ↔ a ∈ t) : (∫ a in s, f a) = (∫ a in t, f a) := integral_congr_ae hsm htm $ indicator_congr_of_set h lemma integral_on_add {s : set α} (hfm : measurable_on s f) (hfi : integrable_on s f) (hgm : measurable_on s g) (hgi : integrable_on s g) : (∫ a in s, f a + g a) = (∫ a in s, f a) + (∫ a in s, g a) := by { simp only [indicator_add], exact integral_add hfm hfi hgm hgi } lemma integral_on_sub (hfm : measurable_on s f) (hfi : integrable_on s f) (hgm : measurable_on s g) (hgi : integrable_on s g) : (∫ a in s, f a - g a) = (∫ a in s, f a) - (∫ a in s, g a) := by { simp only [indicator_sub], exact integral_sub hfm hfi hgm hgi } lemma integral_on_le_integral_on_ae {f g : α → ℝ} (hfm : measurable_on s f) (hfi : integrable_on s f) (hgm : measurable_on s g) (hgi : integrable_on s g) (h : ∀ᵐ a, a ∈ s → f a ≤ g a) : (∫ a in s, f a) ≤ (∫ a in s, g a) := begin apply integral_le_integral_ae hfm hfi hgm hgi, apply indicator_le_indicator_ae, exact h end lemma integral_on_le_integral_on {f g : α → ℝ} (hfm : measurable_on s f) (hfi : integrable_on s f) (hgm : measurable_on s g) (hgi : integrable_on s g) (h : ∀ a, a ∈ s → f a ≤ g a) : (∫ a in s, f a) ≤ (∫ a in s, g a) := integral_on_le_integral_on_ae hfm hfi hgm hgi $ by filter_upwards [] h lemma integral_on_union (hsm : measurable_on s f) (hsi : integrable_on s f) (htm : measurable_on t f) (hti : integrable_on t f) (h : disjoint s t) : (∫ a in (s ∪ t), f a) = (∫ a in s, f a) + (∫ a in t, f a) := by { rw [indicator_union_of_disjoint h, integral_add hsm hsi htm hti] } lemma integral_on_union_ae (hs : measurable_set s) (ht : measurable_set t) (hsm : measurable_on s f) (hsi : integrable_on s f) (htm : measurable_on t f) (hti : integrable_on t f) (h : ∀ᵐ a, a ∉ s ∩ t) : (∫ a in (s ∪ t), f a) = (∫ a in s, f a) + (∫ a in t, f a) := begin have := integral_congr_ae _ _ (indicator_union_ae h f), rw [this, integral_add hsm hsi htm hti], { exact hsm.union hs ht htm }, { exact measurable.add hsm htm } end lemma integral_on_nonneg_of_ae {f : α → ℝ} (hf : ∀ᵐ a, a ∈ s → 0 ≤ f a) : (0:ℝ) ≤ (∫ a in s, f a) := integral_nonneg_of_ae $ by { filter_upwards [hf] λ a h, indicator_nonneg' h } lemma integral_on_nonneg {f : α → ℝ} (hf : ∀ a, a ∈ s → 0 ≤ f a) : (0:ℝ) ≤ (∫ a in s, f a) := integral_on_nonneg_of_ae $ univ_mem_sets' hf lemma integral_on_nonpos_of_ae {f : α → ℝ} (hf : ∀ᵐ a, a ∈ s → f a ≤ 0) : (∫ a in s, f a) ≤ 0 := integral_nonpos_of_nonpos_ae $ by { filter_upwards [hf] λ a h, indicator_nonpos' h } lemma integral_on_nonpos {f : α → ℝ} (hf : ∀ a, a ∈ s → f a ≤ 0) : (∫ a in s, f a) ≤ 0 := integral_on_nonpos_of_ae $ univ_mem_sets' hf lemma tendsto_integral_on_of_monotone {s : ℕ → set α} {f : α → β} (hsm : ∀i, measurable_set (s i)) (h_mono : monotone s) (hfm : measurable_on (Union s) f) (hfi : integrable_on (Union s) f) : tendsto (λi, ∫ a in (s i), f a) at_top (nhds (∫ a in (Union s), f a)) := let bound : α → ℝ := indicator (Union s) (λa, ∥f a∥) in begin apply tendsto_integral_of_dominated_convergence, { assume i, exact hfm.subset (hsm i) (subset_Union _ _) }, { assumption }, { show integrable_on (Union s) (λa, ∥f a∥), rwa integrable_on_norm_iff }, { assume i, apply ae_of_all, assume a, rw [norm_indicator_eq_indicator_norm], exact indicator_le_indicator_of_subset (subset_Union _ _) (λa, norm_nonneg _) _ }, { filter_upwards [] λa, le_trans (tendsto_indicator_of_monotone _ h_mono _ _) (pure_le_nhds _) } end lemma tendsto_integral_on_of_antimono (s : ℕ → set α) (f : α → β) (hsm : ∀i, measurable_set (s i)) (h_mono : ∀i j, i ≤ j → s j ⊆ s i) (hfm : measurable_on (s 0) f) (hfi : integrable_on (s 0) f) : tendsto (λi, ∫ a in (s i), f a) at_top (nhds (∫ a in (Inter s), f a)) := let bound : α → ℝ := indicator (s 0) (λa, ∥f a∥) in begin apply tendsto_integral_of_dominated_convergence, { assume i, refine hfm.subset (hsm i) (h_mono _ _ (zero_le _)) }, { exact hfm.subset (measurable_set.Inter hsm) (Inter_subset _ _) }, { show integrable_on (s 0) (λa, ∥f a∥), rwa integrable_on_norm_iff }, { assume i, apply ae_of_all, assume a, rw [norm_indicator_eq_indicator_norm], refine indicator_le_indicator_of_subset (h_mono _ _ (zero_le _)) (λa, norm_nonneg _) _ }, { filter_upwards [] λa, le_trans (tendsto_indicator_of_antimono _ h_mono _ _) (pure_le_nhds _) } end -- TODO : prove this for an encodable type -- by proving an encodable version of `filter.is_countably_generated_at_top_finset_nat ` lemma integral_on_Union (s : ℕ → set α) (f : α → β) (hm : ∀i, measurable_set (s i)) (hd : ∀ i j, i ≠ j → s i ∩ s j = ∅) (hfm : measurable_on (Union s) f) (hfi : integrable_on (Union s) f) : (∫ a in (Union s), f a) = ∑'i, ∫ a in s i, f a := suffices h : tendsto (λn:finset ℕ, ∑ i in n, ∫ a in s i, f a) at_top (𝓝 $ (∫ a in (Union s), f a)), by { rwa has_sum.tsum_eq }, begin have : (λn:finset ℕ, ∑ i in n, ∫ a in s i, f a) = λn:finset ℕ, ∫ a in (⋃i∈n, s i), f a, { funext, rw [← integral_finset_sum, indicator_finset_bUnion], { assume i hi j hj hij, exact hd i j hij }, { assume i, refine hfm.subset (hm _) (subset_Union _ _) }, { assume i, refine hfi.subset (subset_Union _ _) } }, rw this, refine tendsto_integral_filter_of_dominated_convergence _ _ _ _ _ _ _, { exact indicator (Union s) (λ a, ∥f a∥) }, { exact is_countably_generated_at_top_finset_nat }, { refine univ_mem_sets' (λ n, _), simp only [mem_set_of_eq], refine hfm.subset (measurable_set.Union (λ i, measurable_set.Union_Prop (λh, hm _))) (bUnion_subset_Union _ _), }, { assumption }, { refine univ_mem_sets' (λ n, univ_mem_sets' $ _), simp only [mem_set_of_eq], assume a, rw ← norm_indicator_eq_indicator_norm, refine norm_indicator_le_of_subset (bUnion_subset_Union _ _) _ _ }, { rw [← integrable_on, integrable_on_norm_iff], assumption }, { filter_upwards [] λa, le_trans (tendsto_indicator_bUnion_finset _ _ _) (pure_le_nhds _) } end end integral_on -/
2243db8844f49802a54f62d99e59e9e9ff8b93ac
5d166a16ae129621cb54ca9dde86c275d7d2b483
/library/init/meta/converter.lean
d724fbf9d308d85ece3c220e5496c077cd9ea627
[ "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
8,966
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 Converter monad for building simplifiers. -/ prelude import init.meta.tactic init.meta.simp_tactic import init.meta.congr_lemma init.meta.match_tactic open tactic meta structure conv_result (α : Type) := (val : α) (rhs : expr) (proof : option expr) meta def conv (α : Type) : Type := name → expr → tactic (conv_result α) namespace conv meta def lhs : conv expr := λ r e, return ⟨e, e, none⟩ meta def change (new_p : pexpr) : conv unit := λ r e, do new_e ← to_expr new_p, unify e new_e, return ⟨(), new_e, none⟩ protected meta def pure {α : Type} : α → conv α := λ a r e, return ⟨a, e, none⟩ private meta def join_proofs (r : name) (o₁ o₂ : option expr) : tactic (option expr) := match o₁, o₂ with | none, _ := return o₂ | _, none := return o₁ | some p₁, some p₂ := do env ← get_env, match env.trans_for r with | some trans := do pr ← mk_app trans [p₁, p₂], return $ some pr | none := fail format!"converter failed, relation '{r}' is not transitive" end end protected meta def seq {α β : Type} (c₁ : conv (α → β)) (c₂ : conv α) : conv β := λ r e, do ⟨fn, e₁, pr₁⟩ ← c₁ r e, ⟨a, e₂, pr₂⟩ ← c₂ r e₁, pr ← join_proofs r pr₁ pr₂, return ⟨fn a, e₂, pr⟩ protected meta def fail {α : Type} : conv α := λ r e, failed protected meta def orelse {α : Type} (c₁ : conv α) (c₂ : conv α) : conv α := λ r e, c₁ r e <|> c₂ r e protected meta def map {α β : Type} (f : α → β) (c : conv α) : conv β := λ r e, do ⟨a, e₁, pr⟩ ← c r e, return ⟨f a, e₁, pr⟩ protected meta def bind {α β : Type} (c₁ : conv α) (c₂ : α → conv β) : conv β := λ r e, do ⟨a, e₁, pr₁⟩ ← c₁ r e, ⟨b, e₂, pr₂⟩ ← c₂ a r e₁, pr ← join_proofs r pr₁ pr₂, return ⟨b, e₂, pr⟩ meta instance : monad conv := { map := @conv.map, pure := @conv.pure, bind := @conv.bind, id_map := undefined, pure_bind := undefined, bind_assoc := undefined, bind_pure_comp_eq_map := undefined, bind_map_eq_seq := undefined } meta instance : alternative conv := { conv.monad with failure := @conv.fail, orelse := @conv.orelse } meta def whnf (md : transparency := reducible) : conv unit := λ r e, do n ← tactic.whnf e md, return ⟨(), n, none⟩ meta def dsimp : conv unit := λ r e, do s ← simp_lemmas.mk_default, n ← s.dsimplify e, return ⟨(), n, none⟩ meta def try (c : conv unit) : conv unit := c <|> return () meta def tryb (c : conv unit) : conv bool := (c >> return tt) <|> return ff meta def trace {α : Type} [has_to_tactic_format α] (a : α) : conv unit := λ r e, tactic.trace a >> return ⟨(), e, none⟩ meta def trace_lhs : conv unit := lhs >>= trace meta def apply_lemmas_core (s : simp_lemmas) (prove : tactic unit) : conv unit := λ r e, do (new_e, pr) ← s.rewrite prove r e, return ⟨(), new_e, some pr⟩ meta def apply_lemmas (s : simp_lemmas) : conv unit := apply_lemmas_core s failed /- αdapter for using iff-lemmas as eq-lemmas -/ meta def apply_propext_lemmas_core (s : simp_lemmas) (prove : tactic unit) : conv unit := λ r e, do guard (r = `eq), (new_e, pr) ← s.rewrite prove `iff e, new_pr ← mk_app `propext [pr], return ⟨(), new_e, some new_pr⟩ meta def apply_propext_lemmas (s : simp_lemmas) : conv unit := apply_propext_lemmas_core s failed private meta def mk_refl_proof (r : name) (e : expr) : tactic expr := do env ← get_env, match (environment.refl_for env r) with | (some refl) := do pr ← mk_app refl [e], return pr | none := fail format!"converter failed, relation '{r}' is not reflexive" end meta def to_tactic (c : conv unit) : name → expr → tactic (expr × expr) := λ r e, do ⟨u, e₁, o⟩ ← c r e, match o with | none := do p ← mk_refl_proof r e, return (e₁, p) | some p := return (e₁, p) end meta def lift_tactic {α : Type} (t : tactic α) : conv α := λ r e, do a ← t, return ⟨a, e, none⟩ meta def apply_simp_set (attr_name : name) : conv unit := lift_tactic (get_user_simp_lemmas attr_name) >>= apply_lemmas meta def apply_propext_simp_set (attr_name : name) : conv unit := lift_tactic (get_user_simp_lemmas attr_name) >>= apply_propext_lemmas meta def skip : conv unit := return () meta def repeat : conv unit → conv unit | c r lhs := (do ⟨_, rhs₁, pr₁⟩ ← c r lhs, guard (¬ lhs =ₐ rhs₁), ⟨_, rhs₂, pr₂⟩ ← repeat c r rhs₁, pr ← join_proofs r pr₁ pr₂, return ⟨(), rhs₂, pr⟩) <|> return ⟨(), lhs, none⟩ meta def first {α : Type} : list (conv α) → conv α | [] := conv.fail | (c::cs) := c <|> first cs meta def match_pattern (p : pattern) : conv unit := λ r e, tactic.match_pattern p e >> return ⟨(), e, none⟩ meta def mk_match_expr (p : pexpr) : tactic (conv unit) := do new_p ← pexpr_to_pattern p, return (λ r e, tactic.match_pattern new_p e >> return ⟨(), e, none⟩) meta def match_expr (p : pexpr) : conv unit := λ r e, do new_p ← pexpr_to_pattern p, tactic.match_pattern new_p e >> return ⟨(), e, none⟩ meta def funext (c : conv unit) : conv unit := λ r lhs, do guard (r = `eq), (expr.lam n bi d b) ← return lhs, let aux_type := expr.pi n bi d (expr.const `true []), (result, _) ← solve_aux aux_type $ do { x ← intro1, c_result ← c r (b.instantiate_var x), let rhs := expr.lam n bi d (c_result.rhs.abstract x), match c_result.proof : _ → tactic (conv_result unit) with | some pr := do let aux_pr := expr.lam n bi d (pr.abstract x), new_pr ← mk_app `funext [lhs, rhs, aux_pr], return ⟨(), rhs, some new_pr⟩ | none := return ⟨(), rhs, none⟩ end }, return result meta def congr_core (c_f c_a : conv unit) : conv unit := λ r lhs, do guard (r = `eq), (expr.app f a) ← return lhs, f_type ← infer_type f >>= tactic.whnf, guard (f_type.is_arrow), ⟨(), new_f, of⟩ ← try c_f r f, ⟨(), new_a, oa⟩ ← try c_a r a, rhs ← return $ new_f new_a, match of, oa with | none, none := return ⟨(), rhs, none⟩ | none, some pr_a := do pr ← mk_app `congr_arg [a, new_a, f, pr_a], return ⟨(), new_f new_a, some pr⟩ | some pr_f, none := do pr ← mk_app `congr_fun [f, new_f, pr_f, a], return ⟨(), rhs, some pr⟩ | some pr_f, some pr_a := do pr ← mk_app `congr [f, new_f, a, new_a, pr_f, pr_a], return ⟨(), rhs, some pr⟩ end meta def congr (c : conv unit) : conv unit := congr_core c c meta def bottom_up (c : conv unit) : conv unit := λ r e, do s ← simp_lemmas.mk_default, (a, new_e, pr) ← ext_simplify_core () {} s (λ u, return u) (λ a s r p e, failed) (λ a s r p e, do ⟨u, new_e, pr⟩ ← c r e, return ((), new_e, pr, tt)) r e, return ⟨(), new_e, some pr⟩ meta def top_down (c : conv unit) : conv unit := λ r e, do s ← simp_lemmas.mk_default, (a, new_e, pr) ← ext_simplify_core () {} s (λ u, return u) (λ a s r p e, do ⟨u, new_e, pr⟩ ← c r e, return ((), new_e, pr, tt)) (λ a s r p e, failed) r e, return ⟨(), new_e, some pr⟩ meta def find (c : conv unit) : conv unit := λ r e, do s ← simp_lemmas.mk_default, (a, new_e, pr) ← ext_simplify_core () {} s (λ u, return u) (λ a s r p e, (do ⟨u, new_e, pr⟩ ← c r e, return ((), new_e, pr, ff)) <|> return ((), e, none, tt)) (λ a s r p e, failed) r e, return ⟨(), new_e, some pr⟩ meta def find_pattern (pat : pattern) (c : conv unit) : conv unit := λ r e, do s ← simp_lemmas.mk_default, (a, new_e, pr) ← ext_simplify_core () {} s (λ u, return u) (λ a s r p e, do matched ← (tactic.match_pattern pat e >> return tt) <|> return ff, if matched then do ⟨u, new_e, pr⟩ ← c r e, return ((), new_e, pr, ff) else return ((), e, none, tt)) (λ a s r p e, failed) r e, return ⟨(), new_e, some pr⟩ meta def findp : pexpr → conv unit → conv unit := λ p c r e, do pat ← pexpr_to_pattern p, find_pattern pat c r e meta def conversion (c : conv unit) : tactic unit := do (r, lhs, rhs) ← (target_lhs_rhs <|> fail "conversion failed, target is not of the form 'lhs R rhs'"), (new_lhs, pr) ← to_tactic c r lhs, (unify new_lhs rhs <|> do new_lhs_fmt ← pp new_lhs, rhs_fmt ← pp rhs, fail (to_fmt "conversion failed, expected" ++ rhs_fmt.indent 4 ++ format.line ++ "provided" ++ new_lhs_fmt.indent 4)), exact pr end conv
7df6fd0155361c6febf3c4805b1ed5a998a528ca
2d34dfb0a1cc250584282618dc10ea03d3fa858e
/src/liquid.lean
f78dbd7d22a4cf93ab35a4eb112374d34376f2ff
[]
no_license
zeta1999/lean-liquid
61e294ec5adae959d8ee1b65d015775484ff58c2
96bb0fa3afc3b451bcd1fb7d974348de2f290541
refs/heads/master
1,676,579,150,248
1,610,771,445,000
1,610,771,445,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,696
lean
import breen_deligne import system_of_complexes import locally_constant.Vhat import Mbar.complex2 import by_exactI_hack /-! # Liquid Tensor Experiment This file is the entry point for this project. The first goal of the Liquid Tensor Experiment is to formalize a theorem by Clausen and Scholze stated below, namely a mix of Theorem 9.4 and Theorem 9.5 of [Analytic.pdf]: http://www.math.uni-bonn.de/people/scholze/Analytic.pdf **How to browse this project? See `README.md` in the root of the repository.** We will now state the main theorem. First we need to fix a package of data corresponding to the Breen--Deligne resolution. If you don't know the Breen--Deligne resolution, don't worry, we'll explain more about how to find out more about it below. Once we have fixed this data, we can state the theorem. -/ open_locale nnreal -- enable the notation `ℝ≥0` for the nonnegative real numbers. variables (BD : breen_deligne.package) variables (c' : ℕ → ℝ≥0) -- implicit constants, chosen once and for all -- see the sentence after that statement of Thm 9.5 /-- A mix of Theorems 9.4 and 9.5 in [Analytic.pdf] -/ theorem main [BD.suitable c'] (r r' : ℝ≥0) [fact (0 < r)] [fact (0 < r')] [fact (r < r')] [fact (r' ≤ 1)] : ∀ m : ℕ, ∃ (k : ℝ≥0) [fact (1 ≤ k)], ∃ c₀ : ℝ≥0, ∀ (S : Type) [fintype S], ∀ (V : NormedGroup) [normed_with_aut r V],​ (Mbar_system V S r r' BD c').is_bdd_exact_for_bdd_degree_above_idx k m c₀ := sorry /-! ## On the statement Most of the theorem should be fairly readable. We will now briefly explain some of the more peculiar syntax. * `[BD.suitable c']` assumes that the nonnegative reals `c' i` satisfy some suitable conditions with respect to the package of Breen--Deligne data `BD`. * `[fact (0 < r)]` records the "fact" `0 < r` as an assumption to whatever comes later. * `(S : Type) [fintype S]` is Lean's way of saying "`S` is a finite set". See also the "Brief note on type theory" in `README.md`. * `[normed_with_aut r V]` adds the assumption that `V` is endowed with an automorphism `T` that scales elements `v` of `V` by the positive scalar `r`: `∥T(v)∥ = r * ∥v∥`. * `Mbar_system` is the system of complexes of normed abelian groups occuring in Theorems 9.4/9.5 of [Analytic.pdf]. * `is_bdd_exact_for_bdd_degree_above_idx` is the assertion that a system of complexes of normed abelian groups satisfies a suitable exactness criterion of being `≤ k`-exact in degrees `≤ m` for `c ≥ c₀` (where `c` is an index to the system of complexes). * `sorry` tells Lean to accept this theorem without proof. We are working hard on removing it! -/
9aa78b06d138167e6c0d1d8060659e8dab11e60d
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Lean/Meta/Tactic/Assert.lean
89d7259e9496bba73c9943d1837b59bcfcf81de7
[ "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
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
4,938
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.Tactic.Util import Lean.Meta.Tactic.FVarSubst import Lean.Meta.Tactic.Intro import Lean.Meta.Tactic.Revert namespace Lean.Meta /-- Convert the given goal `Ctx |- target` into `Ctx |- type -> target`. It assumes `val` has type `type` -/ def assert (mvarId : MVarId) (name : Name) (type : Expr) (val : Expr) : MetaM MVarId := withMVarContext mvarId do checkNotAssigned mvarId `assert let tag ← getMVarTag mvarId let target ← getMVarType mvarId let newType := Lean.mkForall name BinderInfo.default type target let newMVar ← mkFreshExprSyntheticOpaqueMVar newType tag assignExprMVar mvarId (mkApp newMVar val) pure newMVar.mvarId! /-- Convert the given goal `Ctx |- target` into `Ctx |- let name : type := val; target`. It assumes `val` has type `type` -/ def define (mvarId : MVarId) (name : Name) (type : Expr) (val : Expr) : MetaM MVarId := do withMVarContext mvarId do checkNotAssigned mvarId `define let tag ← getMVarTag mvarId let target ← getMVarType mvarId let newType := Lean.mkLet name type val target let newMVar ← mkFreshExprSyntheticOpaqueMVar newType tag assignExprMVar mvarId newMVar pure newMVar.mvarId! /-- Convert the given goal `Ctx |- target` into `Ctx |- (hName : type) -> hName = val -> target`. It assumes `val` has type `type` -/ def assertExt (mvarId : MVarId) (name : Name) (type : Expr) (val : Expr) (hName : Name := `h) : MetaM MVarId := do withMVarContext mvarId do checkNotAssigned mvarId `assert let tag ← getMVarTag mvarId let target ← getMVarType mvarId let u ← getLevel type let hType := mkApp3 (mkConst `Eq [u]) type (mkBVar 0) val let newType := Lean.mkForall name BinderInfo.default type $ Lean.mkForall hName BinderInfo.default hType target let newMVar ← mkFreshExprSyntheticOpaqueMVar newType tag let rflPrf ← mkEqRefl val assignExprMVar mvarId (mkApp2 newMVar val rflPrf) pure newMVar.mvarId! structure AssertAfterResult where fvarId : FVarId mvarId : MVarId subst : FVarSubst /-- Convert the given goal `Ctx |- target` into a goal containing `(userName : type)` after the local declaration with if `fvarId`. It assumes `val` has type `type`, and that `type` is well-formed after `fvarId`. Note that `val` does not need to be well-formed after `fvarId`. That is, it may contain variables that are defined after `fvarId`. -/ def assertAfter (mvarId : MVarId) (fvarId : FVarId) (userName : Name) (type : Expr) (val : Expr) : MetaM AssertAfterResult := do withMVarContext mvarId do checkNotAssigned mvarId `assertAfter let tag ← getMVarTag mvarId let target ← getMVarType mvarId let localDecl ← getLocalDecl fvarId let lctx ← getLCtx let localInsts ← getLocalInstances let fvarIds := lctx.foldl (init := #[]) (start := localDecl.index+1) fun fvarIds decl => fvarIds.push decl.fvarId let xs := fvarIds.map mkFVar let targetNew ← mkForallFVars xs target (usedLetOnly := false) let targetNew := Lean.mkForall userName BinderInfo.default type targetNew let lctxNew := fvarIds.foldl (init := lctx) fun lctxNew fvarId => lctxNew.erase fvarId let localInstsNew := localInsts.filter fun inst => !fvarIds.contains inst.fvar.fvarId! let mvarNew ← mkFreshExprMVarAt lctxNew localInstsNew targetNew MetavarKind.syntheticOpaque tag let args := (fvarIds.filter fun fvarId => !(lctx.get! fvarId).isLet).map mkFVar let args := #[val] ++ args assignExprMVar mvarId (mkAppN mvarNew args) let (fvarIdNew, mvarIdNew) ← intro1P mvarNew.mvarId! let (fvarIdsNew, mvarIdNew) ← introNP mvarIdNew fvarIds.size let subst := fvarIds.size.fold (init := {}) fun i subst => subst.insert fvarIds[i] (mkFVar fvarIdsNew[i]) pure { fvarId := fvarIdNew, mvarId := mvarIdNew, subst := subst } structure Hypothesis where userName : Name type : Expr value : Expr /-- Convert the given goal `Ctx |- target` into `Ctx, (hs[0].userName : hs[0].type) ... |-target`. It assumes `hs[i].val` has type `hs[i].type`. -/ def assertHypotheses (mvarId : MVarId) (hs : Array Hypothesis) : MetaM (Array FVarId × MVarId) := do if hs.isEmpty then return (#[], mvarId) else withMVarContext mvarId do checkNotAssigned mvarId `assertHypotheses let tag ← getMVarTag mvarId let target ← getMVarType mvarId let targetNew := hs.foldr (init := target) fun h targetNew => mkForall h.userName BinderInfo.default h.type targetNew let mvarNew ← mkFreshExprSyntheticOpaqueMVar targetNew tag let val := hs.foldl (init := mvarNew) fun val h => mkApp val h.value assignExprMVar mvarId val introNP mvarNew.mvarId! hs.size end Lean.Meta
23847cd784b77333cbde57d79a0756d917342d43
f7315930643edc12e76c229a742d5446dad77097
/hott/algebra/precategory/nat_trans.hlean
5f7bed90d27be335443cbd7bce85f70999eaa55a
[ "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
4,712
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: algebra.precategory.nat_trans Author: Floris van Doorn, Jakob von Raumer -/ import .functor .iso open eq category functor is_trunc equiv sigma.ops sigma is_equiv function pi funext iso structure nat_trans {C D : Precategory} (F G : C ⇒ D) := (natural_map : Π (a : C), hom (F a) (G a)) (naturality : Π {a b : C} (f : hom a b), G f ∘ natural_map a = natural_map b ∘ F f) namespace nat_trans infixl `⟹`:25 := nat_trans -- \==> variables {C D E : Precategory} {F G H I : C ⇒ D} {F' G' : D ⇒ E} attribute natural_map [coercion] protected definition compose [reducible] (η : G ⟹ H) (θ : F ⟹ G) : F ⟹ H := nat_trans.mk (λ a, η a ∘ θ a) (λ a b f, calc H f ∘ (η a ∘ θ a) = (H f ∘ η a) ∘ θ a : by rewrite assoc ... = (η b ∘ G f) ∘ θ a : by rewrite naturality ... = η b ∘ (G f ∘ θ a) : by rewrite assoc ... = η b ∘ (θ b ∘ F f) : by rewrite naturality ... = (η b ∘ θ b) ∘ F f : by rewrite assoc) infixr `∘n`:60 := compose protected definition id [reducible] {C D : Precategory} {F : functor C D} : nat_trans F F := mk (λa, id) (λa b f, !id_right ⬝ !id_left⁻¹) protected definition ID [reducible] {C D : Precategory} (F : functor C D) : nat_trans F F := id definition nat_trans_eq_mk' {η₁ η₂ : Π (a : C), hom (F a) (G a)} (nat₁ : Π (a b : C) (f : hom a b), G f ∘ η₁ a = η₁ b ∘ F f) (nat₂ : Π (a b : C) (f : hom a b), G f ∘ η₂ a = η₂ b ∘ F f) (p : η₁ ∼ η₂) : nat_trans.mk η₁ nat₁ = nat_trans.mk η₂ nat₂ := apD011 nat_trans.mk (eq_of_homotopy p) !is_hprop.elim definition nat_trans_eq_mk {η₁ η₂ : F ⟹ G} : natural_map η₁ ∼ natural_map η₂ → η₁ = η₂ := nat_trans.rec_on η₁ (λf₁ nat₁, nat_trans.rec_on η₂ (λf₂ nat₂ p, !nat_trans_eq_mk' p)) protected definition assoc (η₃ : H ⟹ I) (η₂ : G ⟹ H) (η₁ : F ⟹ G) : η₃ ∘n (η₂ ∘n η₁) = (η₃ ∘n η₂) ∘n η₁ := nat_trans_eq_mk (λa, !assoc) protected definition id_left (η : F ⟹ G) : id ∘n η = η := nat_trans_eq_mk (λa, !id_left) protected definition id_right (η : F ⟹ G) : η ∘n id = η := nat_trans_eq_mk (λa, !id_right) protected definition sigma_char (F G : C ⇒ D) : (Σ (η : Π (a : C), hom (F a) (G a)), Π (a b : C) (f : hom a b), G f ∘ η a = η b ∘ F f) ≃ (F ⟹ G) := begin fapply equiv.mk, -- TODO(Leo): investigate why we need to use rexact in the following line {intro S, apply nat_trans.mk, rexact (S.2)}, fapply adjointify, intro H, fapply sigma.mk, intro a, exact (H a), intros [a, b, f], exact (naturality H f), intro η, apply nat_trans_eq_mk, intro a, apply idp, intro S, fapply sigma_eq, apply eq_of_homotopy, intro a, apply idp, apply is_hprop.elim, end set_option apply.class_instance false definition is_hset_nat_trans : is_hset (F ⟹ G) := begin apply is_trunc_is_equiv_closed, apply (equiv.to_is_equiv !sigma_char), apply is_trunc_sigma, apply is_trunc_pi, intro a, exact (@homH (Precategory.carrier D) _ (F a) (G a)), intro η, apply is_trunc_pi, intro a, apply is_trunc_pi, intro b, apply is_trunc_pi, intro f, apply is_trunc_eq, apply is_trunc_succ, exact (@homH (Precategory.carrier D) _ (F a) (G b)), end definition nat_trans_functor_compose [reducible] (η : G ⟹ H) (F : E ⇒ C) : G ∘f F ⟹ H ∘f F := nat_trans.mk (λ a, η (F a)) (λ a b f, naturality η (F f)) definition functor_nat_trans_compose [reducible] (F : D ⇒ E) (η : G ⟹ H) : F ∘f G ⟹ F ∘f H := nat_trans.mk (λ a, F (η a)) (λ a b f, calc F (H f) ∘ F (η a) = F (H f ∘ η a) : by rewrite respect_comp ... = F (η b ∘ G f) : by rewrite (naturality η f) ... = F (η b) ∘ F (G f) : by rewrite respect_comp) infixr `∘nf`:60 := nat_trans_functor_compose infixr `∘fn`:60 := functor_nat_trans_compose definition functor_nat_trans_compose_commute (η : F ⟹ G) (θ : F' ⟹ G') : (θ ∘nf G) ∘n (F' ∘fn η) = (G' ∘fn η) ∘n (θ ∘nf F) := nat_trans_eq_mk (λc, (naturality θ (η c))⁻¹) definition nat_trans_of_eq [reducible] (p : F = G) : F ⟹ G := nat_trans.mk (λc, hom_of_eq (ap010 to_fun_ob p c)) (λa b f, eq.rec_on p (!id_right ⬝ !id_left⁻¹)) end nat_trans
ae9912e822052b604ce35f489a14d2f4e18393cf
c777c32c8e484e195053731103c5e52af26a25d1
/src/number_theory/padics/padic_numbers.lean
fdd6b9baf34ce2ab498e0fa372d9594e3749c70d
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
39,106
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import number_theory.padics.padic_norm import analysis.normed.field.basic /-! # p-adic numbers This file defines the `p`-adic numbers (rationals) `ℚ_[p]` as the completion of `ℚ` with respect to the `p`-adic norm. We show that the `p`-adic norm on `ℚ` extends to `ℚ_[p]`, that `ℚ` is embedded in `ℚ_[p]`, and that `ℚ_[p]` is Cauchy complete. ## Important definitions * `padic` : the type of `p`-adic numbers * `padic_norm_e` : the rational valued `p`-adic norm on `ℚ_[p]` * `padic.add_valuation` : the additive `p`-adic valuation on `ℚ_[p]`, with values in `with_top ℤ` ## Notation We introduce the notation `ℚ_[p]` for the `p`-adic numbers. ## Implementation notes Much, but not all, of this file assumes that `p` is prime. This assumption is inferred automatically by taking `[fact p.prime]` as a type class argument. We use the same concrete Cauchy sequence construction that is used to construct `ℝ`. `ℚ_[p]` inherits a field structure from this construction. The extension of the norm on `ℚ` to `ℚ_[p]` is *not* analogous to extending the absolute value to `ℝ` and hence the proof that `ℚ_[p]` is complete is different from the proof that ℝ is complete. A small special-purpose simplification tactic, `padic_index_simp`, is used to manipulate sequence indices in the proof that the norm extends. `padic_norm_e` is the rational-valued `p`-adic norm on `ℚ_[p]`. To instantiate `ℚ_[p]` as a normed field, we must cast this into a `ℝ`-valued norm. The `ℝ`-valued norm, using notation `‖ ‖` from normed spaces, is the canonical representation of this norm. `simp` prefers `padic_norm` to `padic_norm_e` when possible. Since `padic_norm_e` and `‖ ‖` have different types, `simp` does not rewrite one to the other. Coercions from `ℚ` to `ℚ_[p]` are set up to work with the `norm_cast` tactic. ## References * [F. Q. Gouvêa, *p-adic numbers*][gouvea1997] * [R. Y. Lewis, *A formal proof of Hensel's lemma over the p-adic integers*][lewis2019] * <https://en.wikipedia.org/wiki/P-adic_number> ## Tags p-adic, p adic, padic, norm, valuation, cauchy, completion, p-adic completion -/ noncomputable theory open_locale classical open nat multiplicity padic_norm cau_seq cau_seq.completion metric /-- The type of Cauchy sequences of rationals with respect to the `p`-adic norm. -/ @[reducible] def padic_seq (p : ℕ) := cau_seq _ (padic_norm p) namespace padic_seq section variables {p : ℕ} [fact p.prime] /-- The `p`-adic norm of the entries of a nonzero Cauchy sequence of rationals is eventually constant. -/ lemma stationary {f : cau_seq ℚ (padic_norm p)} (hf : ¬ f ≈ 0) : ∃ N, ∀ m n, N ≤ m → N ≤ n → padic_norm p (f n) = padic_norm p (f m) := have ∃ ε > 0, ∃ N1, ∀ j ≥ N1, ε ≤ padic_norm p (f j), from cau_seq.abv_pos_of_not_lim_zero $ not_lim_zero_of_not_congr_zero hf, let ⟨ε, hε, N1, hN1⟩ := this, ⟨N2, hN2⟩ := cau_seq.cauchy₂ f hε in ⟨ max N1 N2, λ n m hn hm, have padic_norm p (f n - f m) < ε, from hN2 _ (max_le_iff.1 hn).2 _ (max_le_iff.1 hm).2, have padic_norm p (f n - f m) < padic_norm p (f n), from lt_of_lt_of_le this $ hN1 _ (max_le_iff.1 hn).1, have padic_norm p (f n - f m) < max (padic_norm p (f n)) (padic_norm p (f m)), from lt_max_iff.2 (or.inl this), begin by_contradiction hne, rw ← padic_norm.neg (f m) at hne, have hnam := add_eq_max_of_ne hne, rw [padic_norm.neg, max_comm] at hnam, rw [← hnam, sub_eq_add_neg, add_comm] at this, apply _root_.lt_irrefl _ this end ⟩ /-- For all `n ≥ stationary_point f hf`, the `p`-adic norm of `f n` is the same. -/ def stationary_point {f : padic_seq p} (hf : ¬ f ≈ 0) : ℕ := classical.some $ stationary hf lemma stationary_point_spec {f : padic_seq p} (hf : ¬ f ≈ 0) : ∀ {m n}, stationary_point hf ≤ m → stationary_point hf ≤ n → padic_norm p (f n) = padic_norm p (f m) := classical.some_spec $ stationary hf /-- Since the norm of the entries of a Cauchy sequence is eventually stationary, we can lift the norm to sequences. -/ def norm (f : padic_seq p) : ℚ := if hf : f ≈ 0 then 0 else padic_norm p (f (stationary_point hf)) lemma norm_zero_iff (f : padic_seq p) : f.norm = 0 ↔ f ≈ 0 := begin constructor, { intro h, by_contradiction hf, unfold norm at h, split_ifs at h, apply hf, intros ε hε, existsi stationary_point hf, intros j hj, have heq := stationary_point_spec hf le_rfl hj, simpa [h, heq] }, { intro h, simp [norm, h] } end end section embedding open cau_seq variables {p : ℕ} [fact p.prime] lemma equiv_zero_of_val_eq_of_equiv_zero {f g : padic_seq p} (h : ∀ k, padic_norm p (f k) = padic_norm p (g k)) (hf : f ≈ 0) : g ≈ 0 := λ ε hε, let ⟨i, hi⟩ := hf _ hε in ⟨i, λ j hj, by simpa [h] using hi _ hj⟩ lemma norm_nonzero_of_not_equiv_zero {f : padic_seq p} (hf : ¬ f ≈ 0) : f.norm ≠ 0 := hf ∘ f.norm_zero_iff.1 lemma norm_eq_norm_app_of_nonzero {f : padic_seq p} (hf : ¬ f ≈ 0) : ∃ k, f.norm = padic_norm p k ∧ k ≠ 0 := have heq : f.norm = padic_norm p (f $ stationary_point hf), by simp [norm, hf], ⟨f $ stationary_point hf, heq, λ h, norm_nonzero_of_not_equiv_zero hf (by simpa [h] using heq)⟩ lemma not_lim_zero_const_of_nonzero {q : ℚ} (hq : q ≠ 0) : ¬ lim_zero (const (padic_norm p) q) := λ h', hq $ const_lim_zero.1 h' lemma not_equiv_zero_const_of_nonzero {q : ℚ} (hq : q ≠ 0) : ¬ const (padic_norm p) q ≈ 0 := λ h : lim_zero (const (padic_norm p) q - 0), not_lim_zero_const_of_nonzero hq $ by simpa using h lemma norm_nonneg (f : padic_seq p) : 0 ≤ f.norm := if hf : f ≈ 0 then by simp [hf, norm] else by simp [norm, hf, padic_norm.nonneg] /-- An auxiliary lemma for manipulating sequence indices. -/ lemma lift_index_left_left {f : padic_seq p} (hf : ¬ f ≈ 0) (v2 v3 : ℕ) : padic_norm p (f (stationary_point hf)) = padic_norm p (f (max (stationary_point hf) (max v2 v3))) := begin apply stationary_point_spec hf, { apply le_max_left }, { exact le_rfl } end /-- An auxiliary lemma for manipulating sequence indices. -/ lemma lift_index_left {f : padic_seq p} (hf : ¬ f ≈ 0) (v1 v3 : ℕ) : padic_norm p (f (stationary_point hf)) = padic_norm p (f (max v1 (max (stationary_point hf) v3))) := begin apply stationary_point_spec hf, { apply le_trans, { apply le_max_left _ v3 }, { apply le_max_right } }, { exact le_rfl } end /-- An auxiliary lemma for manipulating sequence indices. -/ lemma lift_index_right {f : padic_seq p} (hf : ¬ f ≈ 0) (v1 v2 : ℕ) : padic_norm p (f (stationary_point hf)) = padic_norm p (f (max v1 (max v2 (stationary_point hf)))) := begin apply stationary_point_spec hf, { apply le_trans, { apply le_max_right v2 }, { apply le_max_right } }, { exact le_rfl } end end embedding section valuation open cau_seq variables {p : ℕ} [fact p.prime] /-! ### Valuation on `padic_seq` -/ /-- The `p`-adic valuation on `ℚ` lifts to `padic_seq p`. `valuation f` is defined to be the valuation of the (`ℚ`-valued) stationary point of `f`. -/ def valuation (f : padic_seq p) : ℤ := if hf : f ≈ 0 then 0 else padic_val_rat p (f (stationary_point hf)) lemma norm_eq_pow_val {f : padic_seq p} (hf : ¬ f ≈ 0) : f.norm = p ^ (-f.valuation : ℤ) := begin rw [norm, valuation, dif_neg hf, dif_neg hf, padic_norm, if_neg], intro H, apply cau_seq.not_lim_zero_of_not_congr_zero hf, intros ε hε, use (stationary_point hf), intros n hn, rw stationary_point_spec hf le_rfl hn, simpa [H] using hε end lemma val_eq_iff_norm_eq {f g : padic_seq p} (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) : f.valuation = g.valuation ↔ f.norm = g.norm := begin rw [norm_eq_pow_val hf, norm_eq_pow_val hg, ← neg_inj, zpow_inj], { exact_mod_cast (fact.out p.prime).pos }, { exact_mod_cast (fact.out p.prime).ne_one } end end valuation end padic_seq section open padic_seq private meta def index_simp_core (hh hf hg : expr) (at_ : interactive.loc := interactive.loc.ns [none]) : tactic unit := do [v1, v2, v3] ← [hh, hf, hg].mmap (λ n, tactic.mk_app ``stationary_point [n] <|> return n), e1 ← tactic.mk_app ``lift_index_left_left [hh, v2, v3] <|> return `(true), e2 ← tactic.mk_app ``lift_index_left [hf, v1, v3] <|> return `(true), e3 ← tactic.mk_app ``lift_index_right [hg, v1, v2] <|> return `(true), sl ← [e1, e2, e3].mfoldl (λ s e, simp_lemmas.add s e) simp_lemmas.mk, when at_.include_goal (tactic.simp_target sl >> tactic.skip), hs ← at_.get_locals, hs.mmap' (tactic.simp_hyp sl []) /-- This is a special-purpose tactic that lifts `padic_norm (f (stationary_point f))` to `padic_norm (f (max _ _ _))`. -/ meta def tactic.interactive.padic_index_simp (l : interactive.parse interactive.types.pexpr_list) (at_ : interactive.parse interactive.types.location) : tactic unit := do [h, f, g] ← l.mmap tactic.i_to_expr, index_simp_core h f g at_ end namespace padic_seq section embedding open cau_seq variables {p : ℕ} [hp : fact p.prime] include hp lemma norm_mul (f g : padic_seq p) : (f * g).norm = f.norm * g.norm := if hf : f ≈ 0 then have hg : f * g ≈ 0, from mul_equiv_zero' _ hf, by simp only [hf, hg, norm, dif_pos, zero_mul] else if hg : g ≈ 0 then have hf : f * g ≈ 0, from mul_equiv_zero _ hg, by simp only [hf, hg, norm, dif_pos, mul_zero] else have hfg : ¬ f * g ≈ 0, by apply mul_not_equiv_zero; assumption, begin unfold norm, split_ifs, padic_index_simp [hfg, hf, hg], apply padic_norm.mul end lemma eq_zero_iff_equiv_zero (f : padic_seq p) : mk f = 0 ↔ f ≈ 0 := mk_eq lemma ne_zero_iff_nequiv_zero (f : padic_seq p) : mk f ≠ 0 ↔ ¬ f ≈ 0 := not_iff_not.2 (eq_zero_iff_equiv_zero _) lemma norm_const (q : ℚ) : norm (const (padic_norm p) q) = padic_norm p q := if hq : q = 0 then have (const (padic_norm p) q) ≈ 0, by simp [hq]; apply setoid.refl (const (padic_norm p) 0), by subst hq; simp [norm, this] else have ¬ (const (padic_norm p) q) ≈ 0, from not_equiv_zero_const_of_nonzero hq, by simp [norm, this] lemma norm_values_discrete (a : padic_seq p) (ha : ¬ a ≈ 0) : ∃ z : ℤ, a.norm = p ^ -z := let ⟨k, hk, hk'⟩ := norm_eq_norm_app_of_nonzero ha in by simpa [hk] using padic_norm.values_discrete hk' lemma norm_one : norm (1 : padic_seq p) = 1 := have h1 : ¬ (1 : padic_seq p) ≈ 0, from one_not_equiv_zero _, by simp [h1, norm, hp.1.one_lt] private lemma norm_eq_of_equiv_aux {f g : padic_seq p} (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) (hfg : f ≈ g) (h : padic_norm p (f (stationary_point hf)) ≠ padic_norm p (g (stationary_point hg))) (hlt : padic_norm p (g (stationary_point hg)) < padic_norm p (f (stationary_point hf))) : false := begin have hpn : 0 < padic_norm p (f (stationary_point hf)) - padic_norm p (g (stationary_point hg)), from sub_pos_of_lt hlt, cases hfg _ hpn with N hN, let i := max N (max (stationary_point hf) (stationary_point hg)), have hi : N ≤ i, from le_max_left _ _, have hN' := hN _ hi, padic_index_simp [N, hf, hg] at hN' h hlt, have hpne : padic_norm p (f i) ≠ padic_norm p (-(g i)), by rwa [← padic_norm.neg (g i)] at h, let hpnem := add_eq_max_of_ne hpne, have hpeq : padic_norm p ((f - g) i) = max (padic_norm p (f i)) (padic_norm p (g i)), { rwa padic_norm.neg at hpnem }, rw [hpeq, max_eq_left_of_lt hlt] at hN', have : padic_norm p (f i) < padic_norm p (f i), { apply lt_of_lt_of_le hN', apply sub_le_self, apply padic_norm.nonneg }, exact lt_irrefl _ this end private lemma norm_eq_of_equiv {f g : padic_seq p} (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) (hfg : f ≈ g) : padic_norm p (f (stationary_point hf)) = padic_norm p (g (stationary_point hg)) := begin by_contradiction h, cases (decidable.em (padic_norm p (g (stationary_point hg)) < padic_norm p (f (stationary_point hf)))) with hlt hnlt, { exact norm_eq_of_equiv_aux hf hg hfg h hlt }, { apply norm_eq_of_equiv_aux hg hf (setoid.symm hfg) (ne.symm h), apply lt_of_le_of_ne, apply le_of_not_gt hnlt, apply h } end theorem norm_equiv {f g : padic_seq p} (hfg : f ≈ g) : f.norm = g.norm := if hf : f ≈ 0 then have hg : g ≈ 0, from setoid.trans (setoid.symm hfg) hf, by simp [norm, hf, hg] else have hg : ¬ g ≈ 0, from hf ∘ setoid.trans hfg, by unfold norm; split_ifs; exact norm_eq_of_equiv hf hg hfg private lemma norm_nonarchimedean_aux {f g : padic_seq p} (hfg : ¬ f + g ≈ 0) (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) : (f + g).norm ≤ max f.norm g.norm := begin unfold norm, split_ifs, padic_index_simp [hfg, hf, hg], apply padic_norm.nonarchimedean end theorem norm_nonarchimedean (f g : padic_seq p) : (f + g).norm ≤ max f.norm g.norm := if hfg : f + g ≈ 0 then have 0 ≤ max f.norm g.norm, from le_max_of_le_left (norm_nonneg _), by simpa only [hfg, norm, ne.def, le_max_iff, cau_seq.add_apply, not_true, dif_pos] else if hf : f ≈ 0 then have hfg' : f + g ≈ g, { change lim_zero (f - 0) at hf, show lim_zero (f + g - g), by simpa only [sub_zero, add_sub_cancel] using hf }, have hcfg : (f + g).norm = g.norm, from norm_equiv hfg', have hcl : f.norm = 0, from (norm_zero_iff f).2 hf, have max f.norm g.norm = g.norm, by rw hcl; exact max_eq_right (norm_nonneg _), by rw [this, hcfg] else if hg : g ≈ 0 then have hfg' : f + g ≈ f, { change lim_zero (g - 0) at hg, show lim_zero (f + g - f), by simpa only [add_sub_cancel', sub_zero] using hg }, have hcfg : (f + g).norm = f.norm, from norm_equiv hfg', have hcl : g.norm = 0, from (norm_zero_iff g).2 hg, have max f.norm g.norm = f.norm, by rw hcl; exact max_eq_left (norm_nonneg _), by rw [this, hcfg] else norm_nonarchimedean_aux hfg hf hg lemma norm_eq {f g : padic_seq p} (h : ∀ k, padic_norm p (f k) = padic_norm p (g k)) : f.norm = g.norm := if hf : f ≈ 0 then have hg : g ≈ 0, from equiv_zero_of_val_eq_of_equiv_zero h hf, by simp only [hf, hg, norm, dif_pos] else have hg : ¬ g ≈ 0, from λ hg, hf $ equiv_zero_of_val_eq_of_equiv_zero (by simp only [h, forall_const, eq_self_iff_true]) hg, begin simp only [hg, hf, norm, dif_neg, not_false_iff], let i := max (stationary_point hf) (stationary_point hg), have hpf : padic_norm p (f (stationary_point hf)) = padic_norm p (f i), { apply stationary_point_spec, apply le_max_left, exact le_rfl }, have hpg : padic_norm p (g (stationary_point hg)) = padic_norm p (g i), { apply stationary_point_spec, apply le_max_right, exact le_rfl }, rw [hpf, hpg, h] end lemma norm_neg (a : padic_seq p) : (-a).norm = a.norm := norm_eq $ by simp lemma norm_eq_of_add_equiv_zero {f g : padic_seq p} (h : f + g ≈ 0) : f.norm = g.norm := have lim_zero (f + g - 0), from h, have f ≈ -g, from show lim_zero (f - (-g)), by simpa only [sub_zero, sub_neg_eq_add], have f.norm = (-g).norm, from norm_equiv this, by simpa only [norm_neg] using this lemma add_eq_max_of_ne {f g : padic_seq p} (hfgne : f.norm ≠ g.norm) : (f + g).norm = max f.norm g.norm := have hfg : ¬f + g ≈ 0, from mt norm_eq_of_add_equiv_zero hfgne, if hf : f ≈ 0 then have lim_zero (f - 0), from hf, have f + g ≈ g, from show lim_zero ((f + g) - g), by simpa only [sub_zero, add_sub_cancel], have h1 : (f + g).norm = g.norm, from norm_equiv this, have h2 : f.norm = 0, from (norm_zero_iff _).2 hf, by rw [h1, h2]; rw max_eq_right (norm_nonneg _) else if hg : g ≈ 0 then have lim_zero (g - 0), from hg, have f + g ≈ f, from show lim_zero ((f + g) - f), by rw [add_sub_cancel']; simpa only [sub_zero], have h1 : (f + g).norm = f.norm, from norm_equiv this, have h2 : g.norm = 0, from (norm_zero_iff _).2 hg, by rw [h1, h2]; rw max_eq_left (norm_nonneg _) else begin unfold norm at ⊢ hfgne, split_ifs at ⊢ hfgne, padic_index_simp [hfg, hf, hg] at ⊢ hfgne, exact padic_norm.add_eq_max_of_ne hfgne end end embedding end padic_seq /-- The `p`-adic numbers `ℚ_[p]` are the Cauchy completion of `ℚ` with respect to the `p`-adic norm. -/ def padic (p : ℕ) [fact p.prime] := @cau_seq.completion.Cauchy _ _ _ _ (padic_norm p) _ notation `ℚ_[` p `]` := padic p namespace padic section completion variables {p : ℕ} [fact p.prime] instance : field (ℚ_[p]) := Cauchy.field instance : inhabited ℚ_[p] := ⟨0⟩ -- short circuits instance : comm_ring (ℚ_[p]) := Cauchy.comm_ring instance : ring (ℚ_[p]) := Cauchy.ring instance : has_zero ℚ_[p] := by apply_instance instance : has_one ℚ_[p] := by apply_instance instance : has_add ℚ_[p] := by apply_instance instance : has_mul ℚ_[p] := by apply_instance instance : has_sub ℚ_[p] := by apply_instance instance : has_neg ℚ_[p] := by apply_instance instance : has_div ℚ_[p] := by apply_instance instance : add_comm_group ℚ_[p] := by apply_instance /-- Builds the equivalence class of a Cauchy sequence of rationals. -/ def mk : padic_seq p → ℚ_[p] := quotient.mk variables (p) lemma zero_def : (0 : ℚ_[p]) = ⟦0⟧ := rfl lemma mk_eq {f g : padic_seq p} : mk f = mk g ↔ f ≈ g := quotient.eq lemma const_equiv {q r : ℚ} : const (padic_norm p) q ≈ const (padic_norm p) r ↔ q = r := ⟨ λ heq, eq_of_sub_eq_zero $ const_lim_zero.1 heq, λ heq, by rw heq; apply setoid.refl _ ⟩ @[norm_cast] lemma coe_inj {q r : ℚ} : (↑q : ℚ_[p]) = ↑r ↔ q = r := ⟨(const_equiv p).1 ∘ quotient.eq.1, λ h, by rw h⟩ instance : char_zero ℚ_[p] := ⟨λ m n, by { rw ← rat.cast_coe_nat, norm_cast, exact id }⟩ @[norm_cast] lemma coe_add : ∀ {x y : ℚ}, (↑(x + y) : ℚ_[p]) = ↑x + ↑y := rat.cast_add @[norm_cast] lemma coe_neg : ∀ {x : ℚ}, (↑(-x) : ℚ_[p]) = -↑x := rat.cast_neg @[norm_cast] lemma coe_mul : ∀ {x y : ℚ}, (↑(x * y) : ℚ_[p]) = ↑x * ↑y := rat.cast_mul @[norm_cast] lemma coe_sub : ∀ {x y : ℚ}, (↑(x - y) : ℚ_[p]) = ↑x - ↑y := rat.cast_sub @[norm_cast] lemma coe_div : ∀ {x y : ℚ}, (↑(x / y) : ℚ_[p]) = ↑x / ↑y := rat.cast_div @[norm_cast] lemma coe_one : (↑1 : ℚ_[p]) = 1 := rfl @[norm_cast] lemma coe_zero : (↑0 : ℚ_[p]) = 0 := rfl end completion end padic /-- The rational-valued `p`-adic norm on `ℚ_[p]` is lifted from the norm on Cauchy sequences. The canonical form of this function is the normed space instance, with notation `‖ ‖`. -/ def padic_norm_e {p : ℕ} [hp : fact p.prime] : absolute_value ℚ_[p] ℚ := { to_fun := quotient.lift padic_seq.norm $ @padic_seq.norm_equiv _ _, map_mul' := λ q r, quotient.induction_on₂ q r $ padic_seq.norm_mul, nonneg' := λ q, quotient.induction_on q $ padic_seq.norm_nonneg, eq_zero' := λ q, quotient.induction_on q $ by simpa only [padic.zero_def, quotient.eq] using padic_seq.norm_zero_iff, add_le' := λ q r, begin transitivity max ((quotient.lift padic_seq.norm $ @padic_seq.norm_equiv _ _) q) ((quotient.lift padic_seq.norm $ @padic_seq.norm_equiv _ _) r), exact (quotient.induction_on₂ q r $ padic_seq.norm_nonarchimedean), refine max_le_add_of_nonneg (quotient.induction_on q $ padic_seq.norm_nonneg) _, exact (quotient.induction_on r $ padic_seq.norm_nonneg) end } namespace padic_norm_e section embedding open padic_seq variables {p : ℕ} [fact p.prime] lemma defn (f : padic_seq p) {ε : ℚ} (hε : 0 < ε) : ∃ N, ∀ i ≥ N, padic_norm_e (⟦f⟧ - f i) < ε := begin dsimp [padic_norm_e], change ∃ N, ∀ i ≥ N, (f - const _ (f i)).norm < ε, by_contra' h, cases cauchy₂ f hε with N hN, rcases h N with ⟨i, hi, hge⟩, have hne : ¬ (f - const (padic_norm p) (f i)) ≈ 0, { intro h, unfold padic_seq.norm at hge; split_ifs at hge, exact not_lt_of_ge hge hε }, unfold padic_seq.norm at hge; split_ifs at hge, apply not_le_of_gt _ hge, cases em (N ≤ stationary_point hne) with hgen hngen, { apply hN _ hgen _ hi }, { have := stationary_point_spec hne le_rfl (le_of_not_le hngen), rw ← this, exact hN _ le_rfl _ hi } end /-- Theorems about `padic_norm_e` are named with a `'` so the names do not conflict with the equivalent theorems about `norm` (`‖ ‖`). -/ theorem nonarchimedean' (q r : ℚ_[p]) : padic_norm_e (q + r) ≤ max (padic_norm_e q) (padic_norm_e r) := quotient.induction_on₂ q r $ norm_nonarchimedean /-- Theorems about `padic_norm_e` are named with a `'` so the names do not conflict with the equivalent theorems about `norm` (`‖ ‖`). -/ theorem add_eq_max_of_ne' {q r : ℚ_[p]} : padic_norm_e q ≠ padic_norm_e r → padic_norm_e (q + r) = max (padic_norm_e q) (padic_norm_e r) := quotient.induction_on₂ q r $ λ _ _, padic_seq.add_eq_max_of_ne @[simp] lemma eq_padic_norm' (q : ℚ) : padic_norm_e (q : ℚ_[p]) = padic_norm p q := norm_const _ protected theorem image' {q : ℚ_[p]} : q ≠ 0 → ∃ n : ℤ, padic_norm_e q = p ^ -n := quotient.induction_on q $ λ f hf, have ¬ f ≈ 0, from (ne_zero_iff_nequiv_zero f).1 hf, norm_values_discrete f this end embedding end padic_norm_e namespace padic section complete open padic_seq padic variables {p : ℕ} [fact p.prime] (f : cau_seq _ (@padic_norm_e p _)) theorem rat_dense' (q : ℚ_[p]) {ε : ℚ} (hε : 0 < ε) : ∃ r : ℚ, padic_norm_e (q - r) < ε := quotient.induction_on q $ λ q', have ∃ N, ∀ m n ≥ N, padic_norm p (q' m - q' n) < ε, from cauchy₂ _ hε, let ⟨N, hN⟩ := this in ⟨q' N, begin dsimp [padic_norm_e], change padic_seq.norm (q' - const _ (q' N)) < ε, cases decidable.em ((q' - const (padic_norm p) (q' N)) ≈ 0) with heq hne', { simpa only [heq, padic_seq.norm, dif_pos] }, { simp only [padic_seq.norm, dif_neg hne'], change padic_norm p (q' _ - q' _) < ε, have := stationary_point_spec hne', cases decidable.em (stationary_point hne' ≤ N) with hle hle, { have := eq.symm (this le_rfl hle), simp only [const_apply, sub_apply, padic_norm.zero, sub_self] at this, simpa only [this] }, { exact hN _ (lt_of_not_ge hle).le _ le_rfl } } end⟩ open classical private lemma div_nat_pos (n : ℕ) : 0 < 1 / (n + 1 : ℚ) := div_pos zero_lt_one (by exact_mod_cast succ_pos _) /-- `lim_seq f`, for `f` a Cauchy sequence of `p`-adic numbers, is a sequence of rationals with the same limit point as `f`. -/ def lim_seq : ℕ → ℚ := λ n, classical.some (rat_dense' (f n) (div_nat_pos n)) lemma exi_rat_seq_conv {ε : ℚ} (hε : 0 < ε) : ∃ N, ∀ i ≥ N, padic_norm_e (f i - (lim_seq f i : ℚ_[p])) < ε := begin refine (exists_nat_gt (1 / ε)).imp (λ N hN i hi, _), have h := classical.some_spec (rat_dense' (f i) (div_nat_pos i)), refine lt_of_lt_of_le h ((div_le_iff' $ by exact_mod_cast succ_pos _).mpr _), rw right_distrib, apply le_add_of_le_of_nonneg, { exact (div_le_iff hε).mp (le_trans (le_of_lt hN) (by exact_mod_cast hi)) }, { apply le_of_lt, simpa } end lemma exi_rat_seq_conv_cauchy : is_cau_seq (padic_norm p) (lim_seq f) := assume ε hε, have hε3 : 0 < ε / 3, from div_pos hε (by norm_num), let ⟨N, hN⟩ := exi_rat_seq_conv f hε3, ⟨N2, hN2⟩ := f.cauchy₂ hε3 in begin existsi max N N2, intros j hj, suffices : padic_norm_e ((lim_seq f j - f (max N N2)) + (f (max N N2) - lim_seq f (max N N2))) < ε, { ring_nf at this ⊢, rw [← padic_norm_e.eq_padic_norm'], exact_mod_cast this }, { apply lt_of_le_of_lt, { apply padic_norm_e.add_le }, { have : (3 : ℚ) ≠ 0, by norm_num, have : ε = ε / 3 + ε / 3 + ε / 3, { field_simp [this], simp only [bit0, bit1, mul_add, mul_one] }, rw this, apply add_lt_add, { suffices : padic_norm_e ((lim_seq f j - f j) + (f j - f (max N N2))) < ε / 3 + ε / 3, by simpa only [sub_add_sub_cancel], apply lt_of_le_of_lt, { apply padic_norm_e.add_le }, { apply add_lt_add, { rw [padic_norm_e.map_sub], apply_mod_cast hN, exact le_of_max_le_left hj }, { exact hN2 _ (le_of_max_le_right hj) _ (le_max_right _ _) } } }, { apply_mod_cast hN, apply le_max_left }}} end private def lim' : padic_seq p := ⟨_, exi_rat_seq_conv_cauchy f⟩ private def lim : ℚ_[p] := ⟦lim' f⟧ theorem complete' : ∃ q : ℚ_[p], ∀ ε > 0, ∃ N, ∀ i ≥ N, padic_norm_e (q - f i) < ε := ⟨ lim f, λ ε hε, begin obtain ⟨N, hN⟩ := exi_rat_seq_conv f (half_pos hε), obtain ⟨N2, hN2⟩ := padic_norm_e.defn (lim' f) (half_pos hε), refine ⟨max N N2, λ i hi, _⟩, rw ←sub_add_sub_cancel _ (lim' f i : ℚ_[p]) _, refine (padic_norm_e.add_le _ _).trans_lt _, rw ←add_halves ε, apply add_lt_add, { apply hN2 _ (le_of_max_le_right hi) }, { rw [padic_norm_e.map_sub], exact hN _ (le_of_max_le_left hi) } end ⟩ end complete section normed_space variables (p : ℕ) [fact p.prime] instance : has_dist ℚ_[p] := ⟨λ x y, padic_norm_e (x - y)⟩ instance : metric_space ℚ_[p] := { dist_self := by simp [dist], dist := dist, dist_comm := λ x y, by simp [dist, ←padic_norm_e.map_neg (x - y)], dist_triangle := λ x y z, begin unfold dist, exact_mod_cast padic_norm_e.sub_le _ _ _, end, eq_of_dist_eq_zero := begin unfold dist, intros _ _ h, apply eq_of_sub_eq_zero, apply padic_norm_e.eq_zero.1, exact_mod_cast h end } instance : has_norm ℚ_[p] := ⟨λ x, padic_norm_e x⟩ instance : normed_field ℚ_[p] := { dist_eq := λ _ _, rfl, norm_mul' := by simp [has_norm.norm, map_mul], norm := norm, .. padic.field, .. padic.metric_space p } instance is_absolute_value : is_absolute_value (λ a : ℚ_[p], ‖a‖) := { abv_nonneg := norm_nonneg, abv_eq_zero := λ _, norm_eq_zero, abv_add := norm_add_le, abv_mul := by simp [has_norm.norm, map_mul] } theorem rat_dense (q : ℚ_[p]) {ε : ℝ} (hε : 0 < ε) : ∃ r : ℚ, ‖q - r‖ < ε := let ⟨ε', hε'l, hε'r⟩ := exists_rat_btwn hε, ⟨r, hr⟩ := rat_dense' q (by simpa using hε'l) in ⟨r, lt_trans (by simpa [has_norm.norm] using hr) hε'r⟩ end normed_space end padic namespace padic_norm_e section normed_space variables {p : ℕ} [hp : fact p.prime] include hp @[simp] protected lemma mul (q r : ℚ_[p]) : ‖q * r‖ = ‖q‖ * ‖r‖ := by simp [has_norm.norm, map_mul] protected lemma is_norm (q : ℚ_[p]) : ↑(padic_norm_e q) = ‖q‖ := rfl theorem nonarchimedean (q r : ℚ_[p]) : ‖q + r‖ ≤ max (‖q‖) (‖r‖) := begin unfold has_norm.norm, exact_mod_cast nonarchimedean' _ _ end theorem add_eq_max_of_ne {q r : ℚ_[p]} (h : ‖q‖ ≠ ‖r‖) : ‖q + r‖ = max (‖q‖) (‖r‖) := begin unfold has_norm.norm, apply_mod_cast add_eq_max_of_ne', intro h', apply h, unfold has_norm.norm, exact_mod_cast h' end @[simp] lemma eq_padic_norm (q : ℚ) : ‖(q : ℚ_[p])‖ = padic_norm p q := begin unfold has_norm.norm, rw [← padic_norm_e.eq_padic_norm'] end @[simp] lemma norm_p : ‖(p : ℚ_[p])‖ = p⁻¹ := begin have p₀ : p ≠ 0 := hp.1.ne_zero, have p₁ : p ≠ 1 := hp.1.ne_one, rw ← @rat.cast_coe_nat ℝ _ p, rw ← @rat.cast_coe_nat (ℚ_[p]) _ p, simp [p₀, p₁, norm, padic_norm, padic_val_rat, padic_val_int, zpow_neg, -rat.cast_coe_nat], end lemma norm_p_lt_one : ‖(p : ℚ_[p])‖ < 1 := begin rw norm_p, apply inv_lt_one, exact_mod_cast hp.1.one_lt end @[simp] lemma norm_p_zpow (n : ℤ) : ‖(p ^ n : ℚ_[p])‖ = p ^ -n := by rw [norm_zpow, norm_p, zpow_neg, inv_zpow] @[simp] lemma norm_p_pow (n : ℕ) : ‖(p ^ n : ℚ_[p])‖ = p ^ (-n : ℤ) := by rw [←norm_p_zpow, zpow_coe_nat] instance : nontrivially_normed_field ℚ_[p] := { non_trivial := ⟨p⁻¹, begin rw [norm_inv, norm_p, inv_inv], exact_mod_cast hp.1.one_lt end⟩, .. padic.normed_field p } protected theorem image {q : ℚ_[p]} : q ≠ 0 → ∃ n : ℤ, ‖q‖ = ↑((p : ℚ) ^ -n) := quotient.induction_on q $ λ f hf, have ¬ f ≈ 0, from (padic_seq.ne_zero_iff_nequiv_zero f).1 hf, let ⟨n, hn⟩ := padic_seq.norm_values_discrete f this in ⟨n, congr_arg coe hn⟩ protected lemma is_rat (q : ℚ_[p]) : ∃ q' : ℚ, ‖q‖ = q' := if h : q = 0 then ⟨0, by simp [h]⟩ else let ⟨n, hn⟩ := padic_norm_e.image h in ⟨_, hn⟩ /--`rat_norm q`, for a `p`-adic number `q` is the `p`-adic norm of `q`, as rational number. The lemma `padic_norm_e.eq_rat_norm` asserts `‖q‖ = rat_norm q`. -/ def rat_norm (q : ℚ_[p]) : ℚ := classical.some (padic_norm_e.is_rat q) lemma eq_rat_norm (q : ℚ_[p]) : ‖q‖ = rat_norm q := classical.some_spec (padic_norm_e.is_rat q) theorem norm_rat_le_one : ∀ {q : ℚ} (hq : ¬ p ∣ q.denom), ‖(q : ℚ_[p])‖ ≤ 1 | ⟨n, d, hn, hd⟩ := λ hq : ¬ p ∣ d, if hnz : n = 0 then have (⟨n, d, hn, hd⟩ : ℚ) = 0, from rat.zero_iff_num_zero.mpr hnz, by norm_num [this] else begin have hnz' : { rat . num := n, denom := d, pos := hn, cop := hd } ≠ 0, from mt rat.zero_iff_num_zero.1 hnz, rw [padic_norm_e.eq_padic_norm], norm_cast, rw [padic_norm.eq_zpow_of_nonzero hnz', padic_val_rat, neg_sub, padic_val_nat.eq_zero_of_not_dvd hq], norm_cast, rw [zero_sub, zpow_neg, zpow_coe_nat], apply inv_le_one, { norm_cast, apply one_le_pow, exact hp.1.pos } end theorem norm_int_le_one (z : ℤ) : ‖(z : ℚ_[p])‖ ≤ 1 := suffices ‖((z : ℚ) : ℚ_[p])‖ ≤ 1, by simpa, norm_rat_le_one $ by simp [hp.1.ne_one] lemma norm_int_lt_one_iff_dvd (k : ℤ) : ‖(k : ℚ_[p])‖ < 1 ↔ ↑p ∣ k := begin split, { intro h, contrapose! h, apply le_of_eq, rw eq_comm, calc ‖(k : ℚ_[p])‖ = ‖((k : ℚ) : ℚ_[p])‖ : by { norm_cast } ... = padic_norm p k : padic_norm_e.eq_padic_norm _ ... = 1 : _, rw padic_norm, split_ifs with H, { exfalso, apply h, norm_cast at H, rw H, apply dvd_zero }, { norm_cast at H ⊢, convert zpow_zero _, rw [neg_eq_zero, padic_val_rat.of_int], norm_cast, apply padic_val_int.eq_zero_of_not_dvd h } }, { rintro ⟨x, rfl⟩, push_cast, rw padic_norm_e.mul, calc _ ≤ ‖(p : ℚ_[p])‖ * 1 : mul_le_mul le_rfl (by simpa using norm_int_le_one _) (norm_nonneg _) (norm_nonneg _) ... < 1 : _, { rw [mul_one, padic_norm_e.norm_p], apply inv_lt_one, exact_mod_cast hp.1.one_lt } } end lemma norm_int_le_pow_iff_dvd (k : ℤ) (n : ℕ) : ‖(k : ℚ_[p])‖ ≤ ↑p ^ (-n : ℤ) ↔ ↑(p ^ n) ∣ k := begin have : (p : ℝ) ^ (-n : ℤ) = ↑(p ^ (-n : ℤ) : ℚ), {simp}, rw [show (k : ℚ_[p]) = ((k : ℚ) : ℚ_[p]), by norm_cast, eq_padic_norm, this], norm_cast, rw ← padic_norm.dvd_iff_norm_le end lemma eq_of_norm_add_lt_right {z1 z2 : ℚ_[p]} (h : ‖z1 + z2‖ < ‖z2‖) : ‖z1‖ = ‖z2‖ := by_contradiction $ λ hne, not_lt_of_ge (by rw padic_norm_e.add_eq_max_of_ne hne; apply le_max_right) h lemma eq_of_norm_add_lt_left {z1 z2 : ℚ_[p]} (h : ‖z1 + z2‖ < ‖z1‖) : ‖z1‖ = ‖z2‖ := by_contradiction $ λ hne, not_lt_of_ge (by rw padic_norm_e.add_eq_max_of_ne hne; apply le_max_left) h end normed_space end padic_norm_e namespace padic variables {p : ℕ} [hp : fact p.prime] include hp set_option eqn_compiler.zeta true instance complete : cau_seq.is_complete ℚ_[p] norm := begin split, intro f, have cau_seq_norm_e : is_cau_seq padic_norm_e f, { intros ε hε, let h := is_cau f ε (by exact_mod_cast hε), unfold norm at h, apply_mod_cast h }, cases padic.complete' ⟨f, cau_seq_norm_e⟩ with q hq, existsi q, intros ε hε, cases exists_rat_btwn hε with ε' hε', norm_cast at hε', cases hq ε' hε'.1 with N hN, existsi N, intros i hi, let h := hN i hi, unfold norm, rw_mod_cast [padic_norm_e.map_sub], refine lt_trans _ hε'.2, exact_mod_cast hN i hi end lemma padic_norm_e_lim_le {f : cau_seq ℚ_[p] norm} {a : ℝ} (ha : 0 < a) (hf : ∀ i, ‖f i‖ ≤ a) : ‖f.lim‖ ≤ a := let ⟨N, hN⟩ := setoid.symm (cau_seq.equiv_lim f) _ ha in calc ‖f.lim‖ = ‖f.lim - f N + f N‖ : by simp ... ≤ max (‖f.lim - f N‖) (‖f N‖) : padic_norm_e.nonarchimedean _ _ ... ≤ a : max_le (le_of_lt (hN _ le_rfl)) (hf _) open filter set instance : complete_space ℚ_[p] := begin apply complete_of_cauchy_seq_tendsto, intros u hu, let c : cau_seq ℚ_[p] norm := ⟨u, metric.cauchy_seq_iff'.mp hu⟩, refine ⟨c.lim, λ s h, _⟩, rcases metric.mem_nhds_iff.1 h with ⟨ε, ε0, hε⟩, have := c.equiv_lim ε ε0, simp only [mem_map, mem_at_top_sets, mem_set_of_eq], exact this.imp (λ N hN n hn, hε (hN n hn)) end /-! ### Valuation on `ℚ_[p]` -/ /-- `padic.valuation` lifts the `p`-adic valuation on rationals to `ℚ_[p]`. -/ def valuation : ℚ_[p] → ℤ := quotient.lift (@padic_seq.valuation p _) (λ f g h, begin by_cases hf : f ≈ 0, { have hg : g ≈ 0, from setoid.trans (setoid.symm h) hf, simp [hf, hg, padic_seq.valuation] }, { have hg : ¬ g ≈ 0, from (λ hg, hf (setoid.trans h hg)), rw padic_seq.val_eq_iff_norm_eq hf hg, exact padic_seq.norm_equiv h } end) @[simp] lemma valuation_zero : valuation (0 : ℚ_[p]) = 0 := dif_pos ((const_equiv p).2 rfl) @[simp] lemma valuation_one : valuation (1 : ℚ_[p]) = 0 := begin change dite (cau_seq.const (padic_norm p) 1 ≈ _) _ _ = _, have h : ¬ cau_seq.const (padic_norm p) 1 ≈ 0, { assume H, erw const_equiv p at H, exact one_ne_zero H }, rw dif_neg h, simp end lemma norm_eq_pow_val {x : ℚ_[p]} : x ≠ 0 → ‖x‖ = p ^ -x.valuation := begin apply quotient.induction_on' x, clear x, intros f hf, change (padic_seq.norm _ : ℝ) = (p : ℝ) ^ -padic_seq.valuation _, rw padic_seq.norm_eq_pow_val, change ↑((p : ℚ) ^ -padic_seq.valuation f) = (p : ℝ) ^ -padic_seq.valuation f, { rw [rat.cast_zpow, rat.cast_coe_nat] }, { apply cau_seq.not_lim_zero_of_not_congr_zero, contrapose! hf, apply quotient.sound, simpa using hf } end @[simp] lemma valuation_p : valuation (p : ℚ_[p]) = 1 := begin have h : (1 : ℝ) < p := by exact_mod_cast (fact.out p.prime).one_lt, refine neg_injective ((zpow_strict_mono h).injective $ (norm_eq_pow_val _).symm.trans _), { exact_mod_cast (fact.out p.prime).ne_zero }, { simp } end lemma valuation_map_add {x y : ℚ_[p]} (hxy : x + y ≠ 0) : min (valuation x) (valuation y) ≤ valuation (x + y) := begin by_cases hx : x = 0, { rw [hx, zero_add], exact min_le_right _ _ }, { by_cases hy : y = 0, { rw [hy, add_zero], exact min_le_left _ _ }, { have h_norm : ‖x + y‖ ≤ (max ‖x‖ ‖y‖) := padic_norm_e.nonarchimedean x y, have hp_one : (1 : ℝ) < p, { rw [← nat.cast_one, nat.cast_lt], exact nat.prime.one_lt hp.elim }, rwa [norm_eq_pow_val hx, norm_eq_pow_val hy, norm_eq_pow_val hxy, zpow_le_max_iff_min_le hp_one] at h_norm } } end @[simp] lemma valuation_map_mul {x y : ℚ_[p]} (hx : x ≠ 0) (hy : y ≠ 0) : valuation (x * y) = valuation x + valuation y := begin have h_norm : ‖x * y‖ = ‖x‖ * ‖y‖ := norm_mul x y, have hp_ne_one : (p : ℝ) ≠ 1, { rw [← nat.cast_one, ne.def, nat.cast_inj], exact nat.prime.ne_one hp.elim }, have hp_pos : (0 : ℝ) < p, { rw [← nat.cast_zero, nat.cast_lt], exact nat.prime.pos hp.elim }, rw [norm_eq_pow_val hx, norm_eq_pow_val hy, norm_eq_pow_val (mul_ne_zero hx hy), ← zpow_add₀ (ne_of_gt hp_pos), zpow_inj hp_pos hp_ne_one, ← neg_add, neg_inj] at h_norm, exact h_norm end /-- The additive `p`-adic valuation on `ℚ_[p]`, with values in `with_top ℤ`. -/ def add_valuation_def : ℚ_[p] → with_top ℤ := λ x, if x = 0 then ⊤ else x.valuation @[simp] lemma add_valuation.map_zero : add_valuation_def (0 : ℚ_[p]) = ⊤ := by simp only [add_valuation_def, if_pos (eq.refl _)] @[simp] lemma add_valuation.map_one : add_valuation_def (1 : ℚ_[p]) = 0 := by simp only [add_valuation_def, if_neg one_ne_zero, valuation_one, with_top.coe_zero] lemma add_valuation.map_mul (x y : ℚ_[p]) : add_valuation_def (x * y) = add_valuation_def x + add_valuation_def y := begin simp only [add_valuation_def], by_cases hx : x = 0, { rw [hx, if_pos (eq.refl _), zero_mul, if_pos (eq.refl _), with_top.top_add] }, { by_cases hy : y = 0, { rw [hy, if_pos (eq.refl _), mul_zero, if_pos (eq.refl _), with_top.add_top] }, { rw [if_neg hx, if_neg hy, if_neg (mul_ne_zero hx hy), ← with_top.coe_add, with_top.coe_eq_coe, valuation_map_mul hx hy] }} end lemma add_valuation.map_add (x y : ℚ_[p]) : min (add_valuation_def x) (add_valuation_def y) ≤ add_valuation_def (x + y) := begin simp only [add_valuation_def], by_cases hxy : x + y = 0, { rw [hxy, if_pos (eq.refl _)], exact le_top }, { by_cases hx : x = 0, { simp only [hx, if_pos (eq.refl _), min_eq_right, le_top, zero_add, le_refl] }, { by_cases hy : y = 0, { simp only [hy, if_pos (eq.refl _), min_eq_left, le_top, add_zero, le_refl] }, { rw [if_neg hx, if_neg hy, if_neg hxy, ← with_top.coe_min, with_top.coe_le_coe], exact valuation_map_add hxy }}} end /-- The additive `p`-adic valuation on `ℚ_[p]`, as an `add_valuation`. -/ def add_valuation : add_valuation ℚ_[p] (with_top ℤ) := add_valuation.of add_valuation_def add_valuation.map_zero add_valuation.map_one add_valuation.map_add add_valuation.map_mul @[simp] lemma add_valuation.apply {x : ℚ_[p]} (hx : x ≠ 0) : x.add_valuation = x.valuation := by simp only [add_valuation, add_valuation.of_apply, add_valuation_def, if_neg hx] section norm_le_iff /-! ### Various characterizations of open unit balls -/ lemma norm_le_pow_iff_norm_lt_pow_add_one (x : ℚ_[p]) (n : ℤ) : ‖x‖ ≤ p ^ n ↔ ‖x‖ < p ^ (n + 1) := begin have aux : ∀ n : ℤ, 0 < (p ^ n : ℝ), { apply nat.zpow_pos_of_pos, exact hp.1.pos }, by_cases hx0 : x = 0, { simp [hx0, norm_zero, aux, le_of_lt (aux _)] }, rw norm_eq_pow_val hx0, have h1p : 1 < (p : ℝ), { exact_mod_cast hp.1.one_lt }, have H := zpow_strict_mono h1p, rw [H.le_iff_le, H.lt_iff_lt, int.lt_add_one_iff] end lemma norm_lt_pow_iff_norm_le_pow_sub_one (x : ℚ_[p]) (n : ℤ) : ‖x‖ < p ^ n ↔ ‖x‖ ≤ p ^ (n - 1) := by rw [norm_le_pow_iff_norm_lt_pow_add_one, sub_add_cancel] lemma norm_le_one_iff_val_nonneg (x : ℚ_[p]) : ‖ x ‖ ≤ 1 ↔ 0 ≤ x.valuation := begin by_cases hx : x = 0, { simp only [hx, norm_zero, valuation_zero, zero_le_one, le_refl], }, { rw [norm_eq_pow_val hx, ← zpow_zero (p : ℝ), zpow_le_iff_le, right.neg_nonpos_iff], exact nat.one_lt_cast.2 (nat.prime.one_lt' p).1 } end end norm_le_iff end padic
ef7438c6515120242831f0a784bed3f45eef45bc
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/ring_theory/maps.lean
88267b0d0a57c47ac8bef609d8d7dd002f0c3cda
[ "Apache-2.0" ]
permissive
vaibhavkarve/mathlib
a574aaf68c0a431a47fa82ce0637f0f769826bfe
17f8340912468f49bdc30acdb9a9fa02eeb0473a
refs/heads/master
1,621,263,802,637
1,585,399,588,000
1,585,399,588,000
250,833,447
0
0
Apache-2.0
1,585,410,341,000
1,585,410,341,000
null
UTF-8
Lean
false
false
5,210
lean
/- Copyright (c) 2018 Andreas Swerdlow. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andreas Swerdlow, Kenny Lau -/ import data.equiv.ring /-! # Ring antihomomorphisms, isomorphisms, antiisomorphisms and involutions This file defines ring antihomomorphisms, antiisomorphism and involutions and proves basic properties of them. ## Notations All types defined in this file are given a coercion to the underlying function. ## References * <https://en.wikipedia.org/wiki/Antihomomorphism> * <https://en.wikipedia.org/wiki/Involution_(mathematics)#Ring_theory> ## Tags Ring isomorphism, automorphism, antihomomorphism, antiisomorphism, antiautomorphism, involution -/ variables {R : Type*} {F : Type*} /- The Proposition that a function from a ring to a ring is an antihomomorphism -/ class is_ring_anti_hom [ring R] [ring F] (f : R → F) : Prop := (map_one : f 1 = 1) (map_mul : ∀ {x y : R}, f (x * y) = f y * f x) (map_add : ∀ {x y : R}, f (x + y) = f x + f y) namespace is_ring_anti_hom variables [ring R] [ring F] (f : R → F) [is_ring_anti_hom f] @[priority 100] -- see Note [lower instance priority] instance : is_add_group_hom f := { to_is_add_hom := ⟨λ x y, is_ring_anti_hom.map_add f⟩ } lemma map_zero : f 0 = 0 := is_add_group_hom.map_zero f lemma map_neg {x} : f (-x) = -f x := is_add_group_hom.map_neg f x lemma map_sub {x y} : f (x - y) = f x - f y := is_add_group_hom.map_sub f x y end is_ring_anti_hom variables (R F) namespace ring_equiv open ring_equiv variables {R F} [ring R] [ring F] (Hs : R ≃+* F) (x y : R) lemma bijective : function.bijective Hs := Hs.to_equiv.bijective lemma map_zero_iff {x : R} : Hs x = 0 ↔ x = 0 := ⟨λ H, Hs.bijective.1 $ H.symm ▸ Hs.map_zero.symm, λ H, H.symm ▸ Hs.map_zero⟩ end ring_equiv /-- A ring antiisomorphism -/ structure ring_anti_equiv [ring R] [ring F] extends R ≃ F := [anti_hom : is_ring_anti_hom to_fun] namespace ring_anti_equiv variables {R F} [ring R] [ring F] (Hs : ring_anti_equiv R F) (x y : R) instance : has_coe_to_fun (ring_anti_equiv R F) := ⟨_, λ Hs, Hs.to_fun⟩ instance : is_ring_anti_hom Hs := Hs.anti_hom lemma map_add : Hs (x + y) = Hs x + Hs y := is_ring_anti_hom.map_add Hs lemma map_zero : Hs 0 = 0 := is_ring_anti_hom.map_zero Hs lemma map_neg : Hs (-x) = -Hs x := is_ring_anti_hom.map_neg Hs lemma map_sub : Hs (x - y) = Hs x - Hs y := is_ring_anti_hom.map_sub Hs lemma map_mul : Hs (x * y) = Hs y * Hs x := is_ring_anti_hom.map_mul Hs lemma map_one : Hs 1 = 1 := is_ring_anti_hom.map_one Hs lemma map_neg_one : Hs (-1) = -1 := Hs.map_one ▸ Hs.map_neg 1 lemma bijective : function.bijective Hs := Hs.to_equiv.bijective lemma map_zero_iff {x : R} : Hs x = 0 ↔ x = 0 := ⟨λ H, Hs.bijective.1 $ H.symm ▸ Hs.map_zero.symm, λ H, H.symm ▸ Hs.map_zero⟩ end ring_anti_equiv /-- A ring involution -/ structure ring_invo [ring R] := (to_fun : R → R) [anti_hom : is_ring_anti_hom to_fun] (to_fun_to_fun : ∀ x, to_fun (to_fun x) = x) open ring_invo namespace ring_invo variables {R} [ring R] (Hi : ring_invo R) (x y : R) instance : has_coe_to_fun (ring_invo R) := ⟨_, λ Hi, Hi.to_fun⟩ instance : is_ring_anti_hom Hi := Hi.anti_hom def to_ring_anti_equiv : ring_anti_equiv R R := { inv_fun := Hi, left_inv := Hi.to_fun_to_fun, right_inv := Hi.to_fun_to_fun, .. Hi } lemma map_add : Hi (x + y) = Hi x + Hi y := Hi.to_ring_anti_equiv.map_add x y lemma map_zero : Hi 0 = 0 := Hi.to_ring_anti_equiv.map_zero lemma map_neg : Hi (-x) = -Hi x := Hi.to_ring_anti_equiv.map_neg x lemma map_sub : Hi (x - y) = Hi x - Hi y := Hi.to_ring_anti_equiv.map_sub x y lemma map_mul : Hi (x * y) = Hi y * Hi x := Hi.to_ring_anti_equiv.map_mul x y lemma map_one : Hi 1 = 1 := Hi.to_ring_anti_equiv.map_one lemma map_neg_one : Hi (-1) = -1 := Hi.to_ring_anti_equiv.map_neg_one lemma bijective : function.bijective Hi := Hi.to_ring_anti_equiv.bijective lemma map_zero_iff {x : R} : Hi x = 0 ↔ x = 0 := Hi.to_ring_anti_equiv.map_zero_iff end ring_invo section comm_ring variables (R F) [comm_ring R] [comm_ring F] protected def ring_invo.id : ring_invo R := { anti_hom := ⟨rfl, mul_comm, λ _ _, rfl⟩, to_fun_to_fun := λ _, rfl, .. equiv.refl R } instance : inhabited (ring_invo R) := ⟨ring_invo.id _⟩ protected def ring_anti_equiv.refl : ring_anti_equiv R R := (ring_invo.id R).to_ring_anti_equiv variables {R F} theorem comm_ring.hom_to_anti_hom (f : R → F) [is_ring_hom f] : is_ring_anti_hom f := { map_add := λ _ _, is_ring_hom.map_add f, map_mul := λ _ _, by rw [is_ring_hom.map_mul f, mul_comm], map_one := is_ring_hom.map_one f } theorem comm_ring.anti_hom_to_hom (f : R → F) [is_ring_anti_hom f] : is_ring_hom f := { map_add := λ _ _, is_ring_anti_hom.map_add f, map_mul := λ _ _, by rw [is_ring_anti_hom.map_mul f, mul_comm], map_one := is_ring_anti_hom.map_one f } def comm_ring.equiv_to_anti_equiv (Hs : R ≃+* F) : ring_anti_equiv R F := { anti_hom := comm_ring.hom_to_anti_hom Hs, .. Hs } def comm_ring.anti_equiv_to_equiv (Hs : ring_anti_equiv R F) : R ≃+* F := @ring_equiv.of' _ _ _ _ Hs.to_equiv (comm_ring.anti_hom_to_hom Hs) end comm_ring
fa0fec20dcac63ce21a2248bb45d1e82017fff45
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/measure_theory/pi.lean
6265573e30756d2386334801de3d6f4e9179fa1f
[]
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
20,651
lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.measure_theory.prod import Mathlib.PostPort universes u_1 u_2 u_3 u_4 namespace Mathlib /-! # Product measures In this file we define and prove properties about finite products of measures (and at some point, countable products of measures). ## Main definition * `measure_theory.measure.pi`: The product of finitely many σ-finite measures. Given `μ : Π i : ι, measure (α i)` for `[fintype ι]` it has type `measure (Π i : ι, α i)`. ## Implementation Notes We define `measure_theory.outer_measure.pi`, the product of finitely many outer measures, as the maximal outer measure `n` with the property that `n (pi univ s) ≤ ∏ i, m i (s i)`, where `pi univ s` is the product of the sets `{ s i | i : ι }`. We then show that this induces a product of measures, called `measure_theory.measure.pi`. For a collection of σ-finite measures `μ` and a collection of measurable sets `s` we show that `measure.pi μ (pi univ s) = ∏ i, m i (s i)`. To do this, we follow the following steps: * We know that there is some ordering on `ι`, given by an element of `[encodable ι]`. * Using this, we have an equivalence `measurable_equiv.pi_measurable_equiv_tprod` between `Π ι, α i` and an iterated product of `α i`, called `list.tprod α l` for some list `l`. * On this iterated product we can easily define a product measure `measure_theory.measure.tprod` by iterating `measure_theory.measure.prod` * Using the previous two steps we construct `measure_theory.measure.pi'` on `Π ι, α i` for encodable `ι`. * We know that `measure_theory.measure.pi'` sends products of sets to products of measures, and since `measure_theory.measure.pi` is the maximal such measure (or at least, it comes from an outer measure which is the maximal such outer measure), we get the same rule for `measure_theory.measure.pi`. ## Tags finitary product measure -/ namespace measure_theory /-- An upper bound for the measure in a finite product space. It is defined to by taking the image of the set under all projections, and taking the product of the measures of these images. For measurable boxes it is equal to the correct measure. -/ @[simp] def pi_premeasure {ι : Type u_1} [fintype ι] {α : ι → Type u_2} (m : (i : ι) → outer_measure (α i)) (s : set ((i : ι) → α i)) : ennreal := finset.prod finset.univ fun (i : ι) => coe_fn (m i) (function.eval i '' s) theorem pi_premeasure_pi {ι : Type u_1} [fintype ι] {α : ι → Type u_2} {m : (i : ι) → outer_measure (α i)} {s : (i : ι) → set (α i)} (hs : set.nonempty (set.pi set.univ s)) : pi_premeasure m (set.pi set.univ s) = finset.prod finset.univ fun (i : ι) => coe_fn (m i) (s i) := sorry theorem pi_premeasure_pi' {ι : Type u_1} [fintype ι] {α : ι → Type u_2} {m : (i : ι) → outer_measure (α i)} [Nonempty ι] {s : (i : ι) → set (α i)} : pi_premeasure m (set.pi set.univ s) = finset.prod finset.univ fun (i : ι) => coe_fn (m i) (s i) := sorry theorem pi_premeasure_pi_mono {ι : Type u_1} [fintype ι] {α : ι → Type u_2} {m : (i : ι) → outer_measure (α i)} {s : set ((i : ι) → α i)} {t : set ((i : ι) → α i)} (h : s ⊆ t) : pi_premeasure m s ≤ pi_premeasure m t := finset.prod_le_prod' fun (i : ι) (_x : i ∈ finset.univ) => outer_measure.mono' (m i) (set.image_subset (function.eval i) h) theorem pi_premeasure_pi_eval {ι : Type u_1} [fintype ι] {α : ι → Type u_2} {m : (i : ι) → outer_measure (α i)} [Nonempty ι] {s : set ((i : ι) → α i)} : pi_premeasure m (set.pi set.univ fun (i : ι) => function.eval i '' s) = pi_premeasure m s := sorry namespace outer_measure /-- `outer_measure.pi m` is the finite product of the outer measures `{m i | i : ι}`. It is defined to be the maximal outer measure `n` with the property that `n (pi univ s) ≤ ∏ i, m i (s i)`, where `pi univ s` is the product of the sets `{ s i | i : ι }`. -/ protected def pi {ι : Type u_1} [fintype ι] {α : ι → Type u_2} (m : (i : ι) → outer_measure (α i)) : outer_measure ((i : ι) → α i) := bounded_by (pi_premeasure m) theorem pi_pi_le {ι : Type u_1} [fintype ι] {α : ι → Type u_2} (m : (i : ι) → outer_measure (α i)) (s : (i : ι) → set (α i)) : coe_fn (outer_measure.pi m) (set.pi set.univ s) ≤ finset.prod finset.univ fun (i : ι) => coe_fn (m i) (s i) := sorry theorem le_pi {ι : Type u_1} [fintype ι] {α : ι → Type u_2} {m : (i : ι) → outer_measure (α i)} {n : outer_measure ((i : ι) → α i)} : n ≤ outer_measure.pi m ↔ ∀ (s : (i : ι) → set (α i)), set.nonempty (set.pi set.univ s) → coe_fn n (set.pi set.univ s) ≤ finset.prod finset.univ fun (i : ι) => coe_fn (m i) (s i) := sorry end outer_measure namespace measure /-- A product of measures in `tprod α l`. -/ -- for some reason the equation compiler doesn't like this definition protected def tprod {δ : Type u_3} {π : δ → Type u_4} [(x : δ) → measurable_space (π x)] (l : List δ) (μ : (i : δ) → measure (π i)) : measure (list.tprod π l) := List.rec (dirac PUnit.unit) (fun (i : δ) (l : List δ) (ih : measure (list.tprod π l)) => measure.prod (μ i) ih) l @[simp] theorem tprod_nil {δ : Type u_3} {π : δ → Type u_4} [(x : δ) → measurable_space (π x)] (μ : (i : δ) → measure (π i)) : measure.tprod [] μ = dirac PUnit.unit := rfl @[simp] theorem tprod_cons {δ : Type u_3} {π : δ → Type u_4} [(x : δ) → measurable_space (π x)] (i : δ) (l : List δ) (μ : (i : δ) → measure (π i)) : measure.tprod (i :: l) μ = measure.prod (μ i) (measure.tprod l μ) := rfl protected instance sigma_finite_tprod {δ : Type u_3} {π : δ → Type u_4} [(x : δ) → measurable_space (π x)] (l : List δ) (μ : (i : δ) → measure (π i)) [∀ (i : δ), sigma_finite (μ i)] : sigma_finite (measure.tprod l μ) := List.rec (eq.mpr (id (Eq._oldrec (Eq.refl (sigma_finite (measure.tprod [] μ))) (tprod_nil μ))) (finite_measure.to_sigma_finite (dirac PUnit.unit))) (fun (i : δ) (l : List δ) (ih : sigma_finite (measure.tprod l μ)) => eq.mpr (id (Eq._oldrec (Eq.refl (sigma_finite (measure.tprod (i :: l) μ))) (tprod_cons i l μ))) prod.sigma_finite) l theorem tprod_tprod {δ : Type u_3} {π : δ → Type u_4} [(x : δ) → measurable_space (π x)] (l : List δ) (μ : (i : δ) → measure (π i)) [∀ (i : δ), sigma_finite (μ i)] {s : (i : δ) → set (π i)} (hs : ∀ (i : δ), is_measurable (s i)) : coe_fn (measure.tprod l μ) (set.tprod l s) = list.prod (list.map (fun (i : δ) => coe_fn (μ i) (s i)) l) := sorry theorem tprod_tprod_le {δ : Type u_3} {π : δ → Type u_4} [(x : δ) → measurable_space (π x)] (l : List δ) (μ : (i : δ) → measure (π i)) [∀ (i : δ), sigma_finite (μ i)] (s : (i : δ) → set (π i)) : coe_fn (measure.tprod l μ) (set.tprod l s) ≤ list.prod (list.map (fun (i : δ) => coe_fn (μ i) (s i)) l) := sorry /-- The product measure on an encodable finite type, defined by mapping `measure.tprod` along the equivalence `measurable_equiv.pi_measurable_equiv_tprod`. The definition `measure_theory.measure.pi` should be used instead of this one. -/ def pi' {ι : Type u_1} [fintype ι] {α : ι → Type u_2} [(i : ι) → measurable_space (α i)] (μ : (i : ι) → measure (α i)) [encodable ι] : measure ((i : ι) → α i) := coe_fn (map (list.tprod.elim' encodable.mem_sorted_univ)) (measure.tprod (encodable.sorted_univ ι) μ) theorem pi'_pi {ι : Type u_1} [fintype ι] {α : ι → Type u_2} [(i : ι) → measurable_space (α i)] (μ : (i : ι) → measure (α i)) [encodable ι] [∀ (i : ι), sigma_finite (μ i)] {s : (i : ι) → set (α i)} (hs : ∀ (i : ι), is_measurable (s i)) : coe_fn (pi' μ) (set.pi set.univ s) = finset.prod finset.univ fun (i : ι) => coe_fn (μ i) (s i) := sorry theorem pi'_pi_le {ι : Type u_1} [fintype ι] {α : ι → Type u_2} [(i : ι) → measurable_space (α i)] (μ : (i : ι) → measure (α i)) [encodable ι] [∀ (i : ι), sigma_finite (μ i)] {s : (i : ι) → set (α i)} : coe_fn (pi' μ) (set.pi set.univ s) ≤ finset.prod finset.univ fun (i : ι) => coe_fn (μ i) (s i) := sorry theorem pi_caratheodory {ι : Type u_1} [fintype ι] {α : ι → Type u_2} [(i : ι) → measurable_space (α i)] (μ : (i : ι) → measure (α i)) : measurable_space.pi ≤ outer_measure.caratheodory (outer_measure.pi fun (i : ι) => to_outer_measure (μ i)) := sorry /-- `measure.pi μ` is the finite product of the measures `{μ i | i : ι}`. It is defined to be measure corresponding to `measure_theory.outer_measure.pi`. -/ protected def pi {ι : Type u_1} [fintype ι] {α : ι → Type u_2} [(i : ι) → measurable_space (α i)] (μ : (i : ι) → measure (α i)) : measure ((i : ι) → α i) := outer_measure.to_measure (outer_measure.pi fun (i : ι) => to_outer_measure (μ i)) sorry theorem pi_pi {ι : Type u_1} [fintype ι] {α : ι → Type u_2} [(i : ι) → measurable_space (α i)] (μ : (i : ι) → measure (α i)) [∀ (i : ι), sigma_finite (μ i)] (s : (i : ι) → set (α i)) (hs : ∀ (i : ι), is_measurable (s i)) : coe_fn (measure.pi μ) (set.pi set.univ s) = finset.prod finset.univ fun (i : ι) => coe_fn (μ i) (s i) := sorry theorem pi_eval_preimage_null {ι : Type u_1} [fintype ι] {α : ι → Type u_2} [(i : ι) → measurable_space (α i)] (μ : (i : ι) → measure (α i)) [∀ (i : ι), sigma_finite (μ i)] {i : ι} {s : set (α i)} (hs : coe_fn (μ i) s = 0) : coe_fn (measure.pi μ) (function.eval i ⁻¹' s) = 0 := sorry theorem pi_hyperplane {ι : Type u_1} [fintype ι] {α : ι → Type u_2} [(i : ι) → measurable_space (α i)] (μ : (i : ι) → measure (α i)) [∀ (i : ι), sigma_finite (μ i)] (i : ι) [has_no_atoms (μ i)] (x : α i) : coe_fn (measure.pi μ) (set_of fun (f : (i : ι) → α i) => f i = x) = 0 := (fun (this : coe_fn (measure.pi μ) (function.eval i ⁻¹' singleton x) = 0) => this) (pi_eval_preimage_null μ (measure_singleton x)) theorem ae_eval_ne {ι : Type u_1} [fintype ι] {α : ι → Type u_2} [(i : ι) → measurable_space (α i)] (μ : (i : ι) → measure (α i)) [∀ (i : ι), sigma_finite (μ i)] (i : ι) [has_no_atoms (μ i)] (x : α i) : filter.eventually (fun (y : (i : ι) → α i) => y i ≠ x) (ae (measure.pi μ)) := iff.mpr compl_mem_ae_iff (pi_hyperplane μ i x) theorem tendsto_eval_ae_ae {ι : Type u_1} [fintype ι] {α : ι → Type u_2} [(i : ι) → measurable_space (α i)] {μ : (i : ι) → measure (α i)} [∀ (i : ι), sigma_finite (μ i)] {i : ι} : filter.tendsto (function.eval i) (ae (measure.pi μ)) (ae (μ i)) := fun (s : set (α i)) (hs : s ∈ ae (μ i)) => pi_eval_preimage_null μ hs -- TODO: should we introduce `filter.pi` and prove some basic facts about it? -- The same combinator appears here and in `nhds_pi` theorem ae_pi_le_infi_comap {ι : Type u_1} [fintype ι] {α : ι → Type u_2} [(i : ι) → measurable_space (α i)] {μ : (i : ι) → measure (α i)} [∀ (i : ι), sigma_finite (μ i)] : ae (measure.pi μ) ≤ infi fun (i : ι) => filter.comap (function.eval i) (ae (μ i)) := le_infi fun (i : ι) => filter.tendsto.le_comap tendsto_eval_ae_ae theorem ae_eq_pi {ι : Type u_1} [fintype ι] {α : ι → Type u_2} [(i : ι) → measurable_space (α i)] {μ : (i : ι) → measure (α i)} [∀ (i : ι), sigma_finite (μ i)] {β : ι → Type u_3} {f : (i : ι) → α i → β i} {f' : (i : ι) → α i → β i} (h : ∀ (i : ι), filter.eventually_eq (ae (μ i)) (f i) (f' i)) : filter.eventually_eq (ae (measure.pi μ)) (fun (x : (i : ι) → α i) (i : ι) => f i (x i)) fun (x : (i : ι) → α i) (i : ι) => f' i (x i) := filter.eventually.mono (iff.mpr filter.eventually_all fun (i : ι) => filter.tendsto.eventually tendsto_eval_ae_ae (h i)) fun (x : (x : ι) → α x) (hx : ∀ (i : ι), f i (function.eval i x) = f' i (function.eval i x)) => funext hx theorem ae_le_pi {ι : Type u_1} [fintype ι] {α : ι → Type u_2} [(i : ι) → measurable_space (α i)] {μ : (i : ι) → measure (α i)} [∀ (i : ι), sigma_finite (μ i)] {β : ι → Type u_3} [(i : ι) → preorder (β i)] {f : (i : ι) → α i → β i} {f' : (i : ι) → α i → β i} (h : ∀ (i : ι), filter.eventually_le (ae (μ i)) (f i) (f' i)) : filter.eventually_le (ae (measure.pi μ)) (fun (x : (i : ι) → α i) (i : ι) => f i (x i)) fun (x : (i : ι) → α i) (i : ι) => f' i (x i) := filter.eventually.mono (iff.mpr filter.eventually_all fun (i : ι) => filter.tendsto.eventually tendsto_eval_ae_ae (h i)) fun (x : (x : ι) → α x) (hx : ∀ (i : ι), f i (function.eval i x) ≤ f' i (function.eval i x)) => hx theorem ae_le_set_pi {ι : Type u_1} [fintype ι] {α : ι → Type u_2} [(i : ι) → measurable_space (α i)] {μ : (i : ι) → measure (α i)} [∀ (i : ι), sigma_finite (μ i)] {I : set ι} {s : (i : ι) → set (α i)} {t : (i : ι) → set (α i)} (h : ∀ (i : ι), i ∈ I → filter.eventually_le (ae (μ i)) (s i) (t i)) : filter.eventually_le (ae (measure.pi μ)) (set.pi I s) (set.pi I t) := sorry theorem ae_eq_set_pi {ι : Type u_1} [fintype ι] {α : ι → Type u_2} [(i : ι) → measurable_space (α i)] {μ : (i : ι) → measure (α i)} [∀ (i : ι), sigma_finite (μ i)] {I : set ι} {s : (i : ι) → set (α i)} {t : (i : ι) → set (α i)} (h : ∀ (i : ι), i ∈ I → filter.eventually_eq (ae (μ i)) (s i) (t i)) : filter.eventually_eq (ae (measure.pi μ)) (set.pi I s) (set.pi I t) := filter.eventually_le.antisymm (ae_le_set_pi fun (i : ι) (hi : i ∈ I) => filter.eventually_eq.le (h i hi)) (ae_le_set_pi fun (i : ι) (hi : i ∈ I) => filter.eventually_eq.le (filter.eventually_eq.symm (h i hi))) theorem pi_Iio_ae_eq_pi_Iic {ι : Type u_1} [fintype ι] {α : ι → Type u_2} [(i : ι) → measurable_space (α i)] {μ : (i : ι) → measure (α i)} [∀ (i : ι), sigma_finite (μ i)] [(i : ι) → partial_order (α i)] [∀ (i : ι), has_no_atoms (μ i)] {s : set ι} {f : (i : ι) → α i} : filter.eventually_eq (ae (measure.pi μ)) (set.pi s fun (i : ι) => set.Iio (f i)) (set.pi s fun (i : ι) => set.Iic (f i)) := ae_eq_set_pi fun (i : ι) (hi : i ∈ s) => Iio_ae_eq_Iic theorem pi_Ioi_ae_eq_pi_Ici {ι : Type u_1} [fintype ι] {α : ι → Type u_2} [(i : ι) → measurable_space (α i)] {μ : (i : ι) → measure (α i)} [∀ (i : ι), sigma_finite (μ i)] [(i : ι) → partial_order (α i)] [∀ (i : ι), has_no_atoms (μ i)] {s : set ι} {f : (i : ι) → α i} : filter.eventually_eq (ae (measure.pi μ)) (set.pi s fun (i : ι) => set.Ioi (f i)) (set.pi s fun (i : ι) => set.Ici (f i)) := ae_eq_set_pi fun (i : ι) (hi : i ∈ s) => Ioi_ae_eq_Ici theorem univ_pi_Iio_ae_eq_Iic {ι : Type u_1} [fintype ι] {α : ι → Type u_2} [(i : ι) → measurable_space (α i)] {μ : (i : ι) → measure (α i)} [∀ (i : ι), sigma_finite (μ i)] [(i : ι) → partial_order (α i)] [∀ (i : ι), has_no_atoms (μ i)] {f : (i : ι) → α i} : filter.eventually_eq (ae (measure.pi μ)) (set.pi set.univ fun (i : ι) => set.Iio (f i)) (set.Iic f) := sorry theorem univ_pi_Ioi_ae_eq_Ici {ι : Type u_1} [fintype ι] {α : ι → Type u_2} [(i : ι) → measurable_space (α i)] {μ : (i : ι) → measure (α i)} [∀ (i : ι), sigma_finite (μ i)] [(i : ι) → partial_order (α i)] [∀ (i : ι), has_no_atoms (μ i)] {f : (i : ι) → α i} : filter.eventually_eq (ae (measure.pi μ)) (set.pi set.univ fun (i : ι) => set.Ioi (f i)) (set.Ici f) := sorry theorem pi_Ioo_ae_eq_pi_Icc {ι : Type u_1} [fintype ι] {α : ι → Type u_2} [(i : ι) → measurable_space (α i)] {μ : (i : ι) → measure (α i)} [∀ (i : ι), sigma_finite (μ i)] [(i : ι) → partial_order (α i)] [∀ (i : ι), has_no_atoms (μ i)] {s : set ι} {f : (i : ι) → α i} {g : (i : ι) → α i} : filter.eventually_eq (ae (measure.pi μ)) (set.pi s fun (i : ι) => set.Ioo (f i) (g i)) (set.pi s fun (i : ι) => set.Icc (f i) (g i)) := ae_eq_set_pi fun (i : ι) (hi : i ∈ s) => Ioo_ae_eq_Icc theorem univ_pi_Ioo_ae_eq_Icc {ι : Type u_1} [fintype ι] {α : ι → Type u_2} [(i : ι) → measurable_space (α i)] {μ : (i : ι) → measure (α i)} [∀ (i : ι), sigma_finite (μ i)] [(i : ι) → partial_order (α i)] [∀ (i : ι), has_no_atoms (μ i)] {f : (i : ι) → α i} {g : (i : ι) → α i} : filter.eventually_eq (ae (measure.pi μ)) (set.pi set.univ fun (i : ι) => set.Ioo (f i) (g i)) (set.Icc f g) := sorry theorem pi_Ioc_ae_eq_pi_Icc {ι : Type u_1} [fintype ι] {α : ι → Type u_2} [(i : ι) → measurable_space (α i)] {μ : (i : ι) → measure (α i)} [∀ (i : ι), sigma_finite (μ i)] [(i : ι) → partial_order (α i)] [∀ (i : ι), has_no_atoms (μ i)] {s : set ι} {f : (i : ι) → α i} {g : (i : ι) → α i} : filter.eventually_eq (ae (measure.pi μ)) (set.pi s fun (i : ι) => set.Ioc (f i) (g i)) (set.pi s fun (i : ι) => set.Icc (f i) (g i)) := ae_eq_set_pi fun (i : ι) (hi : i ∈ s) => Ioc_ae_eq_Icc theorem univ_pi_Ioc_ae_eq_Icc {ι : Type u_1} [fintype ι] {α : ι → Type u_2} [(i : ι) → measurable_space (α i)] {μ : (i : ι) → measure (α i)} [∀ (i : ι), sigma_finite (μ i)] [(i : ι) → partial_order (α i)] [∀ (i : ι), has_no_atoms (μ i)] {f : (i : ι) → α i} {g : (i : ι) → α i} : filter.eventually_eq (ae (measure.pi μ)) (set.pi set.univ fun (i : ι) => set.Ioc (f i) (g i)) (set.Icc f g) := sorry theorem pi_Ico_ae_eq_pi_Icc {ι : Type u_1} [fintype ι] {α : ι → Type u_2} [(i : ι) → measurable_space (α i)] {μ : (i : ι) → measure (α i)} [∀ (i : ι), sigma_finite (μ i)] [(i : ι) → partial_order (α i)] [∀ (i : ι), has_no_atoms (μ i)] {s : set ι} {f : (i : ι) → α i} {g : (i : ι) → α i} : filter.eventually_eq (ae (measure.pi μ)) (set.pi s fun (i : ι) => set.Ico (f i) (g i)) (set.pi s fun (i : ι) => set.Icc (f i) (g i)) := ae_eq_set_pi fun (i : ι) (hi : i ∈ s) => Ico_ae_eq_Icc theorem univ_pi_Ico_ae_eq_Icc {ι : Type u_1} [fintype ι] {α : ι → Type u_2} [(i : ι) → measurable_space (α i)] {μ : (i : ι) → measure (α i)} [∀ (i : ι), sigma_finite (μ i)] [(i : ι) → partial_order (α i)] [∀ (i : ι), has_no_atoms (μ i)] {f : (i : ι) → α i} {g : (i : ι) → α i} : filter.eventually_eq (ae (measure.pi μ)) (set.pi set.univ fun (i : ι) => set.Ico (f i) (g i)) (set.Icc f g) := sorry /-- If one of the measures `μ i` has no atoms, them `measure.pi µ` has no atoms. The instance below assumes that all `μ i` have no atoms. -/ theorem pi_has_no_atoms {ι : Type u_1} [fintype ι] {α : ι → Type u_2} [(i : ι) → measurable_space (α i)] {μ : (i : ι) → measure (α i)} [∀ (i : ι), sigma_finite (μ i)] (i : ι) [has_no_atoms (μ i)] : has_no_atoms (measure.pi μ) := has_no_atoms.mk fun (x : (i : ι) → α i) => flip measure_mono_null (pi_hyperplane μ i (x i)) (iff.mpr set.singleton_subset_iff rfl) protected instance pi.measure_theory.has_no_atoms {ι : Type u_1} [fintype ι] {α : ι → Type u_2} [(i : ι) → measurable_space (α i)] {μ : (i : ι) → measure (α i)} [∀ (i : ι), sigma_finite (μ i)] [h : Nonempty ι] [∀ (i : ι), has_no_atoms (μ i)] : has_no_atoms (measure.pi μ) := nonempty.elim h fun (i : ι) => pi_has_no_atoms i protected instance pi.measure_theory.locally_finite_measure {ι : Type u_1} [fintype ι] {α : ι → Type u_2} [(i : ι) → measurable_space (α i)] {μ : (i : ι) → measure (α i)} [∀ (i : ι), sigma_finite (μ i)] [(i : ι) → topological_space (α i)] [∀ (i : ι), opens_measurable_space (α i)] [∀ (i : ι), locally_finite_measure (μ i)] : locally_finite_measure (measure.pi μ) := sorry end measure protected instance measure_space.pi {ι : Type u_1} [fintype ι] {α : ι → Type u_2} [(i : ι) → measure_space (α i)] : measure_space ((i : ι) → α i) := measure_space.mk (measure.pi fun (i : ι) => volume) theorem volume_pi {ι : Type u_1} [fintype ι] {α : ι → Type u_2} [(i : ι) → measure_space (α i)] : volume = measure.pi fun (i : ι) => volume := rfl theorem volume_pi_pi {ι : Type u_1} [fintype ι] {α : ι → Type u_2} [(i : ι) → measure_space (α i)] [ι → sigma_finite volume] (s : (i : ι) → set (α i)) (hs : ∀ (i : ι), is_measurable (s i)) : coe_fn volume (set.pi set.univ s) = finset.prod finset.univ fun (i : ι) => coe_fn volume (s i) := measure.pi_pi (fun (i : ι) => volume) s hs
0f91678fda569260b6305d4a5483a82515b7028f
00f20606b80ff481edcb3343798a879c6c568f6c
/Euclid/axioms.lean
7d1da47694a5270d273069193fe762c061327b05
[ "Apache-2.0" ]
permissive
SG4316/xena-UROP-2018
53c21afcc6909bde186e3d9b8e8bf4c888a5f32e
d20b155d317e210917e9ce88d91457a7c0f2efac
refs/heads/master
1,584,877,373,507
1,530,817,535,000
1,530,817,535,000
139,990,847
0
0
null
1,530,884,893,000
1,530,884,893,000
null
UTF-8
Lean
false
false
208
lean
structure Euclidean_plane := (Point : Type) (Line : Type) (is_on : Point → Line → Prop) (line_through_points : ∀ p q : Point, p ≠ q → ∃! L : Line, is_on p L ∧ is_on q L) (Line_segment : Type)
ac54d2c680d582904363c7482431d809c13a6999
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/group_power/lemmas_auto.lean
1f465a60d339074f4436d16a07fe12cfdec7ec8c
[]
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
28,270
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Robert Y. Lewis -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.group_power.basic import Mathlib.algebra.opposites import Mathlib.data.list.basic import Mathlib.data.int.cast import Mathlib.data.equiv.basic import Mathlib.data.equiv.mul_add import Mathlib.deprecated.group import Mathlib.PostPort universes y u w x z u₁ u_1 namespace Mathlib /-! # Lemmas about power operations on monoids and groups This file contains lemmas about `monoid.pow`, `group.pow`, `nsmul`, `gsmul` which require additional imports besides those available in `.basic`. -/ /-! ### (Additive) monoid -/ @[simp] theorem nsmul_one {A : Type y} [add_monoid A] [HasOne A] (n : ℕ) : n •ℕ 1 = ↑n := add_monoid_hom.eq_nat_cast (add_monoid_hom.mk (fun (n : ℕ) => n •ℕ 1) (zero_nsmul 1) fun (_x _x_1 : ℕ) => add_nsmul 1 _x _x_1) (one_nsmul 1) @[simp] theorem list.prod_repeat {M : Type u} [monoid M] (a : M) (n : ℕ) : list.prod (list.repeat a n) = a ^ n := sorry @[simp] theorem list.sum_repeat {A : Type y} [add_monoid A] (a : A) (n : ℕ) : list.sum (list.repeat a n) = n •ℕ a := list.prod_repeat @[simp] theorem units.coe_pow {M : Type u} [monoid M] (u : units M) (n : ℕ) : ↑(u ^ n) = ↑u ^ n := monoid_hom.map_pow (units.coe_hom M) u n theorem is_unit_of_pow_eq_one {M : Type u} [monoid M] (x : M) (n : ℕ) (hx : x ^ n = 1) (hn : 0 < n) : is_unit x := sorry theorem nat.nsmul_eq_mul (m : ℕ) (n : ℕ) : m •ℕ n = m * n := sorry theorem gsmul_one {A : Type y} [add_group A] [HasOne A] (n : ℤ) : n •ℤ 1 = ↑n := sorry theorem gpow_add_one {G : Type w} [group G] (a : G) (n : ℤ) : a ^ (n + 1) = a ^ n * a := sorry theorem add_one_gsmul {A : Type y} [add_group A] (a : A) (i : ℤ) : (i + 1) •ℤ a = i •ℤ a + a := gpow_add_one theorem gpow_sub_one {G : Type w} [group G] (a : G) (n : ℤ) : a ^ (n - 1) = a ^ n * (a⁻¹) := sorry theorem gpow_add {G : Type w} [group G] (a : G) (m : ℤ) (n : ℤ) : a ^ (m + n) = a ^ m * a ^ n := sorry theorem mul_self_gpow {G : Type w} [group G] (b : G) (m : ℤ) : b * b ^ m = b ^ (m + 1) := sorry theorem mul_gpow_self {G : Type w} [group G] (b : G) (m : ℤ) : b ^ m * b = b ^ (m + 1) := sorry theorem add_gsmul {A : Type y} [add_group A] (a : A) (i : ℤ) (j : ℤ) : (i + j) •ℤ a = i •ℤ a + j •ℤ a := gpow_add theorem gpow_sub {G : Type w} [group G] (a : G) (m : ℤ) (n : ℤ) : a ^ (m - n) = a ^ m * (a ^ n⁻¹) := sorry theorem sub_gsmul {A : Type y} [add_group A] (m : ℤ) (n : ℤ) (a : A) : (m - n) •ℤ a = m •ℤ a - n •ℤ a := sorry theorem gpow_one_add {G : Type w} [group G] (a : G) (i : ℤ) : a ^ (1 + i) = a * a ^ i := eq.mpr (id (Eq._oldrec (Eq.refl (a ^ (1 + i) = a * a ^ i)) (gpow_add a 1 i))) (eq.mpr (id (Eq._oldrec (Eq.refl (a ^ 1 * a ^ i = a * a ^ i)) (gpow_one a))) (Eq.refl (a * a ^ i))) theorem one_add_gsmul {A : Type y} [add_group A] (a : A) (i : ℤ) : (1 + i) •ℤ a = a + i •ℤ a := gpow_one_add theorem gpow_mul_comm {G : Type w} [group G] (a : G) (i : ℤ) (j : ℤ) : a ^ i * a ^ j = a ^ j * a ^ i := eq.mpr (id (Eq._oldrec (Eq.refl (a ^ i * a ^ j = a ^ j * a ^ i)) (Eq.symm (gpow_add a i j)))) (eq.mpr (id (Eq._oldrec (Eq.refl (a ^ (i + j) = a ^ j * a ^ i)) (Eq.symm (gpow_add a j i)))) (eq.mpr (id (Eq._oldrec (Eq.refl (a ^ (i + j) = a ^ (j + i))) (add_comm i j))) (Eq.refl (a ^ (j + i))))) theorem gsmul_add_comm {A : Type y} [add_group A] (a : A) (i : ℤ) (j : ℤ) : i •ℤ a + j •ℤ a = j •ℤ a + i •ℤ a := gpow_mul_comm theorem gpow_mul {G : Type w} [group G] (a : G) (m : ℤ) (n : ℤ) : a ^ (m * n) = (a ^ m) ^ n := sorry theorem gsmul_mul' {A : Type y} [add_group A] (a : A) (m : ℤ) (n : ℤ) : m * n •ℤ a = n •ℤ (m •ℤ a) := gpow_mul theorem gpow_mul' {G : Type w} [group G] (a : G) (m : ℤ) (n : ℤ) : a ^ (m * n) = (a ^ n) ^ m := eq.mpr (id (Eq._oldrec (Eq.refl (a ^ (m * n) = (a ^ n) ^ m)) (mul_comm m n))) (eq.mpr (id (Eq._oldrec (Eq.refl (a ^ (n * m) = (a ^ n) ^ m)) (gpow_mul a n m))) (Eq.refl ((a ^ n) ^ m))) theorem gsmul_mul {A : Type y} [add_group A] (a : A) (m : ℤ) (n : ℤ) : m * n •ℤ a = m •ℤ (n •ℤ a) := eq.mpr (id (Eq._oldrec (Eq.refl (m * n •ℤ a = m •ℤ (n •ℤ a))) (mul_comm m n))) (eq.mpr (id (Eq._oldrec (Eq.refl (n * m •ℤ a = m •ℤ (n •ℤ a))) (gsmul_mul' a n m))) (Eq.refl (m •ℤ (n •ℤ a)))) theorem gpow_bit0 {G : Type w} [group G] (a : G) (n : ℤ) : a ^ bit0 n = a ^ n * a ^ n := gpow_add a n n theorem bit0_gsmul {A : Type y} [add_group A] (a : A) (n : ℤ) : bit0 n •ℤ a = n •ℤ a + n •ℤ a := gpow_add a n n theorem gpow_bit1 {G : Type w} [group G] (a : G) (n : ℤ) : a ^ bit1 n = a ^ n * a ^ n * a := sorry theorem bit1_gsmul {A : Type y} [add_group A] (a : A) (n : ℤ) : bit1 n •ℤ a = n •ℤ a + n •ℤ a + a := gpow_bit1 @[simp] theorem monoid_hom.map_gpow {G : Type w} {H : Type x} [group G] [group H] (f : G →* H) (a : G) (n : ℤ) : coe_fn f (a ^ n) = coe_fn f a ^ n := int.cases_on n (fun (n : ℕ) => monoid_hom.map_pow f a n) fun (n : ℕ) => Eq.trans (monoid_hom.map_inv f (a ^ Nat.succ n)) (congr_arg has_inv.inv (monoid_hom.map_pow f a (Nat.succ n))) @[simp] theorem add_monoid_hom.map_gsmul {A : Type y} {B : Type z} [add_group A] [add_group B] (f : A →+ B) (a : A) (n : ℤ) : coe_fn f (n •ℤ a) = n •ℤ coe_fn f a := monoid_hom.map_gpow (coe_fn add_monoid_hom.to_multiplicative f) a n @[simp] theorem units.coe_gpow {G : Type w} [group G] (u : units G) (n : ℤ) : ↑(u ^ n) = ↑u ^ n := monoid_hom.map_gpow (units.coe_hom G) u n /-! Lemmas about `gsmul` under ordering, placed here (rather than in `algebra.group_power.basic` with their friends) because they require facts from `data.int.basic`-/ theorem gsmul_pos {A : Type y} [ordered_add_comm_group A] {a : A} (ha : 0 < a) {k : ℤ} (hk : 0 < k) : 0 < k •ℤ a := sorry theorem gsmul_le_gsmul {A : Type y} [ordered_add_comm_group A] {a : A} {n : ℤ} {m : ℤ} (ha : 0 ≤ a) (h : n ≤ m) : n •ℤ a ≤ m •ℤ a := sorry theorem gsmul_lt_gsmul {A : Type y} [ordered_add_comm_group A] {a : A} {n : ℤ} {m : ℤ} (ha : 0 < a) (h : n < m) : n •ℤ a < m •ℤ a := sorry theorem gsmul_le_gsmul_iff {A : Type y} [linear_ordered_add_comm_group A] {a : A} {n : ℤ} {m : ℤ} (ha : 0 < a) : n •ℤ a ≤ m •ℤ a ↔ n ≤ m := sorry theorem gsmul_lt_gsmul_iff {A : Type y} [linear_ordered_add_comm_group A] {a : A} {n : ℤ} {m : ℤ} (ha : 0 < a) : n •ℤ a < m •ℤ a ↔ n < m := sorry theorem nsmul_le_nsmul_iff {A : Type y} [linear_ordered_add_comm_group A] {a : A} {n : ℕ} {m : ℕ} (ha : 0 < a) : n •ℕ a ≤ m •ℕ a ↔ n ≤ m := sorry theorem nsmul_lt_nsmul_iff {A : Type y} [linear_ordered_add_comm_group A] {a : A} {n : ℕ} {m : ℕ} (ha : 0 < a) : n •ℕ a < m •ℕ a ↔ n < m := sorry @[simp] theorem with_bot.coe_nsmul {A : Type y} [add_monoid A] (a : A) (n : ℕ) : ↑(n •ℕ a) = n •ℕ ↑a := add_monoid_hom.map_nsmul (add_monoid_hom.mk coe with_bot.coe_zero with_bot.coe_add) a n theorem nsmul_eq_mul' {R : Type u₁} [semiring R] (a : R) (n : ℕ) : n •ℕ a = a * ↑n := sorry @[simp] theorem nsmul_eq_mul {R : Type u₁} [semiring R] (n : ℕ) (a : R) : n •ℕ a = ↑n * a := eq.mpr (id (Eq._oldrec (Eq.refl (n •ℕ a = ↑n * a)) (nsmul_eq_mul' a n))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * ↑n = ↑n * a)) (commute.eq (nat.cast_commute n a)))) (Eq.refl (a * ↑n))) theorem mul_nsmul_left {R : Type u₁} [semiring R] (a : R) (b : R) (n : ℕ) : n •ℕ (a * b) = a * (n •ℕ b) := eq.mpr (id (Eq._oldrec (Eq.refl (n •ℕ (a * b) = a * (n •ℕ b))) (nsmul_eq_mul' (a * b) n))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * b * ↑n = a * (n •ℕ b))) (nsmul_eq_mul' b n))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * b * ↑n = a * (b * ↑n))) (mul_assoc a b ↑n))) (Eq.refl (a * (b * ↑n))))) theorem mul_nsmul_assoc {R : Type u₁} [semiring R] (a : R) (b : R) (n : ℕ) : n •ℕ (a * b) = n •ℕ a * b := eq.mpr (id (Eq._oldrec (Eq.refl (n •ℕ (a * b) = n •ℕ a * b)) (nsmul_eq_mul n (a * b)))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑n * (a * b) = n •ℕ a * b)) (nsmul_eq_mul n a))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑n * (a * b) = ↑n * a * b)) (mul_assoc (↑n) a b))) (Eq.refl (↑n * (a * b))))) @[simp] theorem nat.cast_pow {R : Type u₁} [semiring R] (n : ℕ) (m : ℕ) : ↑(n ^ m) = ↑n ^ m := sorry @[simp] theorem int.coe_nat_pow (n : ℕ) (m : ℕ) : ↑(n ^ m) = ↑n ^ m := sorry theorem int.nat_abs_pow (n : ℤ) (k : ℕ) : int.nat_abs (n ^ k) = int.nat_abs n ^ k := sorry -- The next four lemmas allow us to replace multiplication by a numeral with a `gsmul` expression. -- They are used by the `noncomm_ring` tactic, to normalise expressions before passing to `abel`. theorem bit0_mul {R : Type u₁} [ring R] {n : R} {r : R} : bit0 n * r = bit0 1 •ℤ (n * r) := sorry theorem mul_bit0 {R : Type u₁} [ring R] {n : R} {r : R} : r * bit0 n = bit0 1 •ℤ (r * n) := sorry theorem bit1_mul {R : Type u₁} [ring R] {n : R} {r : R} : bit1 n * r = bit0 1 •ℤ (n * r) + r := sorry theorem mul_bit1 {R : Type u₁} [ring R] {n : R} {r : R} : r * bit1 n = bit0 1 •ℤ (r * n) + r := sorry @[simp] theorem gsmul_eq_mul {R : Type u₁} [ring R] (a : R) (n : ℤ) : n •ℤ a = ↑n * a := sorry theorem gsmul_eq_mul' {R : Type u₁} [ring R] (a : R) (n : ℤ) : n •ℤ a = a * ↑n := eq.mpr (id (Eq._oldrec (Eq.refl (n •ℤ a = a * ↑n)) (gsmul_eq_mul a n))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑n * a = a * ↑n)) (commute.eq (int.cast_commute n a)))) (Eq.refl (a * ↑n))) theorem mul_gsmul_left {R : Type u₁} [ring R] (a : R) (b : R) (n : ℤ) : n •ℤ (a * b) = a * (n •ℤ b) := eq.mpr (id (Eq._oldrec (Eq.refl (n •ℤ (a * b) = a * (n •ℤ b))) (gsmul_eq_mul' (a * b) n))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * b * ↑n = a * (n •ℤ b))) (gsmul_eq_mul' b n))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * b * ↑n = a * (b * ↑n))) (mul_assoc a b ↑n))) (Eq.refl (a * (b * ↑n))))) theorem mul_gsmul_assoc {R : Type u₁} [ring R] (a : R) (b : R) (n : ℤ) : n •ℤ (a * b) = n •ℤ a * b := eq.mpr (id (Eq._oldrec (Eq.refl (n •ℤ (a * b) = n •ℤ a * b)) (gsmul_eq_mul (a * b) n))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑n * (a * b) = n •ℤ a * b)) (gsmul_eq_mul a n))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑n * (a * b) = ↑n * a * b)) (mul_assoc (↑n) a b))) (Eq.refl (↑n * (a * b))))) @[simp] theorem gsmul_int_int (a : ℤ) (b : ℤ) : a •ℤ b = a * b := sorry theorem gsmul_int_one (n : ℤ) : n •ℤ 1 = n := sorry @[simp] theorem int.cast_pow {R : Type u₁} [ring R] (n : ℤ) (m : ℕ) : ↑(n ^ m) = ↑n ^ m := sorry theorem neg_one_pow_eq_pow_mod_two {R : Type u₁} [ring R] {n : ℕ} : (-1) ^ n = (-1) ^ (n % bit0 1) := sorry /-- Bernoulli's inequality. This version works for semirings but requires additional hypotheses `0 ≤ a * a` and `0 ≤ (1 + a) * (1 + a)`. -/ theorem one_add_mul_le_pow' {R : Type u₁} [ordered_semiring R] {a : R} (Hsqr : 0 ≤ a * a) (Hsqr' : 0 ≤ (1 + a) * (1 + a)) (H : 0 ≤ bit0 1 + a) (n : ℕ) : 1 + ↑n * a ≤ (1 + a) ^ n := sorry theorem pow_lt_pow_of_lt_one {R : Type u₁} [ordered_semiring R] {a : R} (h : 0 < a) (ha : a < 1) {i : ℕ} {j : ℕ} (hij : i < j) : a ^ j < a ^ i := sorry theorem pow_lt_pow_iff_of_lt_one {R : Type u₁} [ordered_semiring R] {a : R} {n : ℕ} {m : ℕ} (hpos : 0 < a) (h : a < 1) : a ^ m < a ^ n ↔ n < m := strict_mono.lt_iff_lt fun (m n : order_dual ℕ) => pow_lt_pow_of_lt_one hpos h theorem pow_le_pow_of_le_one {R : Type u₁} [ordered_semiring R] {a : R} (h : 0 ≤ a) (ha : a ≤ 1) {i : ℕ} {j : ℕ} (hij : i ≤ j) : a ^ j ≤ a ^ i := sorry theorem pow_le_one {R : Type u₁} [ordered_semiring R] {x : R} (n : ℕ) (h0 : 0 ≤ x) (h1 : x ≤ 1) : x ^ n ≤ 1 := sorry theorem sign_cases_of_C_mul_pow_nonneg {R : Type u₁} [linear_ordered_semiring R] {C : R} {r : R} (h : ∀ (n : ℕ), 0 ≤ C * r ^ n) : C = 0 ∨ 0 < C ∧ 0 ≤ r := sorry @[simp] theorem abs_pow {R : Type u₁} [linear_ordered_ring R] (a : R) (n : ℕ) : abs (a ^ n) = abs a ^ n := monoid_hom.map_pow (monoid_with_zero_hom.to_monoid_hom abs_hom) a n @[simp] theorem pow_bit1_neg_iff {R : Type u₁} [linear_ordered_ring R] {a : R} {n : ℕ} : a ^ bit1 n < 0 ↔ a < 0 := { mp := fun (h : a ^ bit1 n < 0) => iff.mp not_le fun (h' : 0 ≤ a) => iff.mpr not_le h (pow_nonneg h' (bit1 n)), mpr := fun (h : a < 0) => mul_neg_of_neg_of_pos h (pow_bit0_pos (has_lt.lt.ne h) n) } @[simp] theorem pow_bit1_nonneg_iff {R : Type u₁} [linear_ordered_ring R] {a : R} {n : ℕ} : 0 ≤ a ^ bit1 n ↔ 0 ≤ a := iff.mpr le_iff_le_iff_lt_iff_lt pow_bit1_neg_iff @[simp] theorem pow_bit1_nonpos_iff {R : Type u₁} [linear_ordered_ring R] {a : R} {n : ℕ} : a ^ bit1 n ≤ 0 ↔ a ≤ 0 := sorry @[simp] theorem pow_bit1_pos_iff {R : Type u₁} [linear_ordered_ring R] {a : R} {n : ℕ} : 0 < a ^ bit1 n ↔ 0 < a := lt_iff_lt_of_le_iff_le pow_bit1_nonpos_iff theorem strict_mono_pow_bit1 {R : Type u₁} [linear_ordered_ring R] (n : ℕ) : strict_mono fun (a : R) => a ^ bit1 n := sorry /-- Bernoulli's inequality for `n : ℕ`, `-2 ≤ a`. -/ theorem one_add_mul_le_pow {R : Type u₁} [linear_ordered_ring R] {a : R} (H : -bit0 1 ≤ a) (n : ℕ) : 1 + ↑n * a ≤ (1 + a) ^ n := one_add_mul_le_pow' (mul_self_nonneg a) (mul_self_nonneg (1 + a)) (iff.mp neg_le_iff_add_nonneg' H) n /-- Bernoulli's inequality reformulated to estimate `a^n`. -/ theorem one_add_mul_sub_le_pow {R : Type u₁} [linear_ordered_ring R] {a : R} (H : -1 ≤ a) (n : ℕ) : 1 + ↑n * (a - 1) ≤ a ^ n := sorry /-- Bernoulli's inequality reformulated to estimate `(n : K)`. -/ theorem nat.cast_le_pow_sub_div_sub {K : Type u_1} [linear_ordered_field K] {a : K} (H : 1 < a) (n : ℕ) : ↑n ≤ (a ^ n - 1) / (a - 1) := iff.mpr (le_div_iff (iff.mpr sub_pos H)) (le_sub_left_of_add_le (one_add_mul_sub_le_pow (has_le.le.trans (neg_le_self zero_le_one) (has_lt.lt.le H)) n)) /-- For any `a > 1` and a natural `n` we have `n ≤ a ^ n / (a - 1)`. See also `nat.cast_le_pow_sub_div_sub` for a stronger inequality with `a ^ n - 1` in the numerator. -/ theorem nat.cast_le_pow_div_sub {K : Type u_1} [linear_ordered_field K] {a : K} (H : 1 < a) (n : ℕ) : ↑n ≤ a ^ n / (a - 1) := has_le.le.trans (nat.cast_le_pow_sub_div_sub H n) (div_le_div_of_le (iff.mpr sub_nonneg (has_lt.lt.le H)) (sub_le_self (a ^ n) zero_le_one)) namespace int theorem units_pow_two (u : units ℤ) : u ^ bit0 1 = 1 := Eq.symm (pow_two u) ▸ units_mul_self u theorem units_pow_eq_pow_mod_two (u : units ℤ) (n : ℕ) : u ^ n = u ^ (n % bit0 1) := sorry @[simp] theorem nat_abs_pow_two (x : ℤ) : ↑(nat_abs x) ^ bit0 1 = x ^ bit0 1 := eq.mpr (id (Eq._oldrec (Eq.refl (↑(nat_abs x) ^ bit0 1 = x ^ bit0 1)) (pow_two ↑(nat_abs x)))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑(nat_abs x) * ↑(nat_abs x) = x ^ bit0 1)) (nat_abs_mul_self' x))) (eq.mpr (id (Eq._oldrec (Eq.refl (x * x = x ^ bit0 1)) (pow_two x))) (Eq.refl (x * x)))) theorem abs_le_self_pow_two (a : ℤ) : ↑(nat_abs a) ≤ a ^ bit0 1 := sorry theorem le_self_pow_two (b : ℤ) : b ≤ b ^ bit0 1 := le_trans le_nat_abs (abs_le_self_pow_two b) end int /-- Monoid homomorphisms from `multiplicative ℕ` are defined by the image of `multiplicative.of_add 1`. -/ def powers_hom (M : Type u) [monoid M] : M ≃ (multiplicative ℕ →* M) := equiv.mk (fun (x : M) => monoid_hom.mk (fun (n : multiplicative ℕ) => x ^ coe_fn multiplicative.to_add n) (pow_zero x) sorry) (fun (f : multiplicative ℕ →* M) => coe_fn f (coe_fn multiplicative.of_add 1)) pow_one sorry /-- Monoid homomorphisms from `multiplicative ℤ` are defined by the image of `multiplicative.of_add 1`. -/ def gpowers_hom (G : Type w) [group G] : G ≃ (multiplicative ℤ →* G) := equiv.mk (fun (x : G) => monoid_hom.mk (fun (n : multiplicative ℤ) => x ^ coe_fn multiplicative.to_add n) (gpow_zero x) sorry) (fun (f : multiplicative ℤ →* G) => coe_fn f (coe_fn multiplicative.of_add 1)) gpow_one sorry /-- Additive homomorphisms from `ℕ` are defined by the image of `1`. -/ def multiples_hom (A : Type y) [add_monoid A] : A ≃ (ℕ →+ A) := equiv.mk (fun (x : A) => add_monoid_hom.mk (fun (n : ℕ) => n •ℕ x) (zero_nsmul x) sorry) (fun (f : ℕ →+ A) => coe_fn f 1) one_nsmul sorry /-- Additive homomorphisms from `ℤ` are defined by the image of `1`. -/ def gmultiples_hom (A : Type y) [add_group A] : A ≃ (ℤ →+ A) := equiv.mk (fun (x : A) => add_monoid_hom.mk (fun (n : ℤ) => n •ℤ x) (zero_gsmul x) sorry) (fun (f : ℤ →+ A) => coe_fn f 1) one_gsmul sorry @[simp] theorem powers_hom_apply {M : Type u} [monoid M] (x : M) (n : multiplicative ℕ) : coe_fn (coe_fn (powers_hom M) x) n = x ^ coe_fn multiplicative.to_add n := rfl @[simp] theorem powers_hom_symm_apply {M : Type u} [monoid M] (f : multiplicative ℕ →* M) : coe_fn (equiv.symm (powers_hom M)) f = coe_fn f (coe_fn multiplicative.of_add 1) := rfl @[simp] theorem gpowers_hom_apply {G : Type w} [group G] (x : G) (n : multiplicative ℤ) : coe_fn (coe_fn (gpowers_hom G) x) n = x ^ coe_fn multiplicative.to_add n := rfl @[simp] theorem gpowers_hom_symm_apply {G : Type w} [group G] (f : multiplicative ℤ →* G) : coe_fn (equiv.symm (gpowers_hom G)) f = coe_fn f (coe_fn multiplicative.of_add 1) := rfl @[simp] theorem multiples_hom_apply {A : Type y} [add_monoid A] (x : A) (n : ℕ) : coe_fn (coe_fn (multiples_hom A) x) n = n •ℕ x := rfl @[simp] theorem multiples_hom_symm_apply {A : Type y} [add_monoid A] (f : ℕ →+ A) : coe_fn (equiv.symm (multiples_hom A)) f = coe_fn f 1 := rfl @[simp] theorem gmultiples_hom_apply {A : Type y} [add_group A] (x : A) (n : ℤ) : coe_fn (coe_fn (gmultiples_hom A) x) n = n •ℤ x := rfl @[simp] theorem gmultiples_hom_symm_apply {A : Type y} [add_group A] (f : ℤ →+ A) : coe_fn (equiv.symm (gmultiples_hom A)) f = coe_fn f 1 := rfl theorem monoid_hom.apply_mnat {M : Type u} [monoid M] (f : multiplicative ℕ →* M) (n : multiplicative ℕ) : coe_fn f n = coe_fn f (coe_fn multiplicative.of_add 1) ^ coe_fn multiplicative.to_add n := sorry theorem monoid_hom.ext_mnat {M : Type u} [monoid M] {f : multiplicative ℕ →* M} {g : multiplicative ℕ →* M} (h : coe_fn f (coe_fn multiplicative.of_add 1) = coe_fn g (coe_fn multiplicative.of_add 1)) : f = g := sorry theorem monoid_hom.apply_mint {M : Type u} [group M] (f : multiplicative ℤ →* M) (n : multiplicative ℤ) : coe_fn f n = coe_fn f (coe_fn multiplicative.of_add 1) ^ coe_fn multiplicative.to_add n := sorry theorem monoid_hom.ext_mint {M : Type u} [group M] {f : multiplicative ℤ →* M} {g : multiplicative ℤ →* M} (h : coe_fn f (coe_fn multiplicative.of_add 1) = coe_fn g (coe_fn multiplicative.of_add 1)) : f = g := sorry theorem add_monoid_hom.apply_nat {M : Type u} [add_monoid M] (f : ℕ →+ M) (n : ℕ) : coe_fn f n = n •ℕ coe_fn f 1 := sorry /-! `add_monoid_hom.ext_nat` is defined in `data.nat.cast` -/ theorem add_monoid_hom.apply_int {M : Type u} [add_group M] (f : ℤ →+ M) (n : ℤ) : coe_fn f n = n •ℤ coe_fn f 1 := sorry /-! `add_monoid_hom.ext_int` is defined in `data.int.cast` -/ /-- If `M` is commutative, `powers_hom` is a multiplicative equivalence. -/ def powers_mul_hom (M : Type u) [comm_monoid M] : M ≃* (multiplicative ℕ →* M) := mul_equiv.mk (equiv.to_fun (powers_hom M)) (equiv.inv_fun (powers_hom M)) sorry sorry sorry /-- If `M` is commutative, `gpowers_hom` is a multiplicative equivalence. -/ def gpowers_mul_hom (G : Type w) [comm_group G] : G ≃* (multiplicative ℤ →* G) := mul_equiv.mk (equiv.to_fun (gpowers_hom G)) (equiv.inv_fun (gpowers_hom G)) sorry sorry sorry /-- If `M` is commutative, `multiples_hom` is an additive equivalence. -/ def multiples_add_hom (A : Type y) [add_comm_monoid A] : A ≃+ (ℕ →+ A) := add_equiv.mk (equiv.to_fun (multiples_hom A)) (equiv.inv_fun (multiples_hom A)) sorry sorry sorry /-- If `M` is commutative, `gmultiples_hom` is an additive equivalence. -/ def gmultiples_add_hom (A : Type y) [add_comm_group A] : A ≃+ (ℤ →+ A) := add_equiv.mk (equiv.to_fun (gmultiples_hom A)) (equiv.inv_fun (gmultiples_hom A)) sorry sorry sorry @[simp] theorem powers_mul_hom_apply {M : Type u} [comm_monoid M] (x : M) (n : multiplicative ℕ) : coe_fn (coe_fn (powers_mul_hom M) x) n = x ^ coe_fn multiplicative.to_add n := rfl @[simp] theorem powers_mul_hom_symm_apply {M : Type u} [comm_monoid M] (f : multiplicative ℕ →* M) : coe_fn (mul_equiv.symm (powers_mul_hom M)) f = coe_fn f (coe_fn multiplicative.of_add 1) := rfl @[simp] theorem gpowers_mul_hom_apply {G : Type w} [comm_group G] (x : G) (n : multiplicative ℤ) : coe_fn (coe_fn (gpowers_mul_hom G) x) n = x ^ coe_fn multiplicative.to_add n := rfl @[simp] theorem gpowers_mul_hom_symm_apply {G : Type w} [comm_group G] (f : multiplicative ℤ →* G) : coe_fn (mul_equiv.symm (gpowers_mul_hom G)) f = coe_fn f (coe_fn multiplicative.of_add 1) := rfl @[simp] theorem multiples_add_hom_apply {A : Type y} [add_comm_monoid A] (x : A) (n : ℕ) : coe_fn (coe_fn (multiples_add_hom A) x) n = n •ℕ x := rfl @[simp] theorem multiples_add_hom_symm_apply {A : Type y} [add_comm_monoid A] (f : ℕ →+ A) : coe_fn (add_equiv.symm (multiples_add_hom A)) f = coe_fn f 1 := rfl @[simp] theorem gmultiples_add_hom_apply {A : Type y} [add_comm_group A] (x : A) (n : ℤ) : coe_fn (coe_fn (gmultiples_add_hom A) x) n = n •ℤ x := rfl @[simp] theorem gmultiples_add_hom_symm_apply {A : Type y} [add_comm_group A] (f : ℤ →+ A) : coe_fn (add_equiv.symm (gmultiples_add_hom A)) f = coe_fn f 1 := rfl /-! ### Commutativity (again) Facts about `semiconj_by` and `commute` that require `gpow` or `gsmul`, or the fact that integer multiplication equals semiring multiplication. -/ namespace semiconj_by @[simp] theorem cast_nat_mul_right {R : Type u₁} [semiring R] {a : R} {x : R} {y : R} (h : semiconj_by a x y) (n : ℕ) : semiconj_by a (↑n * x) (↑n * y) := mul_right (nat.commute_cast a n) h @[simp] theorem cast_nat_mul_left {R : Type u₁} [semiring R] {a : R} {x : R} {y : R} (h : semiconj_by a x y) (n : ℕ) : semiconj_by (↑n * a) x y := mul_left (nat.cast_commute n y) h @[simp] theorem cast_nat_mul_cast_nat_mul {R : Type u₁} [semiring R] {a : R} {x : R} {y : R} (h : semiconj_by a x y) (m : ℕ) (n : ℕ) : semiconj_by (↑m * a) (↑n * x) (↑n * y) := cast_nat_mul_right (cast_nat_mul_left h m) n @[simp] theorem units_gpow_right {M : Type u} [monoid M] {a : M} {x : units M} {y : units M} (h : semiconj_by a ↑x ↑y) (m : ℤ) : semiconj_by a ↑(x ^ m) ↑(y ^ m) := sorry @[simp] theorem cast_int_mul_right {R : Type u₁} [ring R] {a : R} {x : R} {y : R} (h : semiconj_by a x y) (m : ℤ) : semiconj_by a (↑m * x) (↑m * y) := mul_right (int.commute_cast a m) h @[simp] theorem cast_int_mul_left {R : Type u₁} [ring R] {a : R} {x : R} {y : R} (h : semiconj_by a x y) (m : ℤ) : semiconj_by (↑m * a) x y := mul_left (int.cast_commute m y) h @[simp] theorem cast_int_mul_cast_int_mul {R : Type u₁} [ring R] {a : R} {x : R} {y : R} (h : semiconj_by a x y) (m : ℤ) (n : ℤ) : semiconj_by (↑m * a) (↑n * x) (↑n * y) := cast_int_mul_right (cast_int_mul_left h m) n end semiconj_by namespace commute @[simp] theorem cast_nat_mul_right {R : Type u₁} [semiring R] {a : R} {b : R} (h : commute a b) (n : ℕ) : commute a (↑n * b) := semiconj_by.cast_nat_mul_right h n @[simp] theorem cast_nat_mul_left {R : Type u₁} [semiring R] {a : R} {b : R} (h : commute a b) (n : ℕ) : commute (↑n * a) b := semiconj_by.cast_nat_mul_left h n @[simp] theorem cast_nat_mul_cast_nat_mul {R : Type u₁} [semiring R] {a : R} {b : R} (h : commute a b) (m : ℕ) (n : ℕ) : commute (↑m * a) (↑n * b) := semiconj_by.cast_nat_mul_cast_nat_mul h m n @[simp] theorem self_cast_nat_mul {R : Type u₁} [semiring R] {a : R} (n : ℕ) : commute a (↑n * a) := cast_nat_mul_right (commute.refl a) n @[simp] theorem cast_nat_mul_self {R : Type u₁} [semiring R] {a : R} (n : ℕ) : commute (↑n * a) a := cast_nat_mul_left (commute.refl a) n @[simp] theorem self_cast_nat_mul_cast_nat_mul {R : Type u₁} [semiring R] {a : R} (m : ℕ) (n : ℕ) : commute (↑m * a) (↑n * a) := cast_nat_mul_cast_nat_mul (commute.refl a) m n @[simp] theorem units_gpow_right {M : Type u} [monoid M] {a : M} {u : units M} (h : commute a ↑u) (m : ℤ) : commute a ↑(u ^ m) := semiconj_by.units_gpow_right h m @[simp] theorem units_gpow_left {M : Type u} [monoid M] {u : units M} {a : M} (h : commute (↑u) a) (m : ℤ) : commute (↑(u ^ m)) a := commute.symm (units_gpow_right (commute.symm h) m) @[simp] theorem cast_int_mul_right {R : Type u₁} [ring R] {a : R} {b : R} (h : commute a b) (m : ℤ) : commute a (↑m * b) := semiconj_by.cast_int_mul_right h m @[simp] theorem cast_int_mul_left {R : Type u₁} [ring R] {a : R} {b : R} (h : commute a b) (m : ℤ) : commute (↑m * a) b := semiconj_by.cast_int_mul_left h m theorem cast_int_mul_cast_int_mul {R : Type u₁} [ring R] {a : R} {b : R} (h : commute a b) (m : ℤ) (n : ℤ) : commute (↑m * a) (↑n * b) := semiconj_by.cast_int_mul_cast_int_mul h m n @[simp] theorem self_cast_int_mul {R : Type u₁} [ring R] (a : R) (n : ℤ) : commute a (↑n * a) := cast_int_mul_right (commute.refl a) n @[simp] theorem cast_int_mul_self {R : Type u₁} [ring R] (a : R) (n : ℤ) : commute (↑n * a) a := cast_int_mul_left (commute.refl a) n theorem self_cast_int_mul_cast_int_mul {R : Type u₁} [ring R] (a : R) (m : ℤ) (n : ℤ) : commute (↑m * a) (↑n * a) := cast_int_mul_cast_int_mul (commute.refl a) m n end commute @[simp] theorem nat.to_add_pow (a : multiplicative ℕ) (b : ℕ) : coe_fn multiplicative.to_add (a ^ b) = coe_fn multiplicative.to_add a * b := sorry @[simp] theorem nat.of_add_mul (a : ℕ) (b : ℕ) : coe_fn multiplicative.of_add (a * b) = coe_fn multiplicative.of_add a ^ b := Eq.symm (nat.to_add_pow a b) @[simp] theorem int.to_add_pow (a : multiplicative ℤ) (b : ℕ) : coe_fn multiplicative.to_add (a ^ b) = coe_fn multiplicative.to_add a * ↑b := sorry @[simp] theorem int.to_add_gpow (a : multiplicative ℤ) (b : ℤ) : coe_fn multiplicative.to_add (a ^ b) = coe_fn multiplicative.to_add a * b := sorry @[simp] theorem int.of_add_mul (a : ℤ) (b : ℤ) : coe_fn multiplicative.of_add (a * b) = coe_fn multiplicative.of_add a ^ b := Eq.symm (int.to_add_gpow a b) namespace units theorem conj_pow {M : Type u} [monoid M] (u : units M) (x : M) (n : ℕ) : (↑u * x * ↑(u⁻¹)) ^ n = ↑u * x ^ n * ↑(u⁻¹) := Eq.symm (iff.mpr divp_eq_iff_mul_eq (Eq.symm (semiconj_by.eq (semiconj_by.pow_right (mk_semiconj_by u x) n)))) theorem conj_pow' {M : Type u} [monoid M] (u : units M) (x : M) (n : ℕ) : (↑(u⁻¹) * x * ↑u) ^ n = ↑(u⁻¹) * x ^ n * ↑u := conj_pow (u⁻¹) x n /-- Moving to the opposite monoid commutes with taking powers. -/ @[simp] theorem op_pow {M : Type u} [monoid M] (x : M) (n : ℕ) : opposite.op (x ^ n) = opposite.op x ^ n := sorry @[simp] theorem unop_pow {M : Type u} [monoid M] (x : Mᵒᵖ) (n : ℕ) : opposite.unop (x ^ n) = opposite.unop x ^ n := sorry end Mathlib
b40d02ccda81950f994c0ab7b43bedd5410f08c0
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Meta/ExprTraverse.lean
12aa04783380a656aad91e3b768d936e1059e34c
[ "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
4,472
lean
/- Copyright (c) 2022 E.W.Ayers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: E.W.Ayers -/ import Lean.Meta.Basic import Lean.SubExpr namespace Lean.Meta open Lean.SubExpr (Pos) open Lean.SubExpr.Pos variable {M} [Monad M] [MonadLiftT MetaM M] [MonadControlT MetaM M] /-- Convert a traversal function to a form without the `Pos` argument. -/ private def forgetPos (t : (Pos → Expr → M Expr) → (Pos → Expr → M Expr)) (visit : Expr → M Expr) (e : Expr) : M Expr := t (fun _ => visit) Pos.root e /-- Similar to `traverseLambda` but with an additional pos argument to track position. -/ def traverseLambdaWithPos (f : Pos → Expr → M Expr) (p : Pos) (e : Expr) : M Expr := visit #[] p e where visit (fvars : Array Expr) (p : Pos) : Expr → M Expr | (Expr.lam n d b c) => do let d ← f p.pushBindingDomain <| d.instantiateRev fvars withLocalDecl n c d fun x => visit (fvars.push x) p.pushBindingBody b | e => do let body ← f p <| e.instantiateRev fvars mkLambdaFVars fvars body /-- Similar to `traverseForall` but with an additional pos argument to track position. -/ def traverseForallWithPos (f : Pos → Expr → M Expr) (p : Pos) (e : Expr) : M Expr := visit #[] p e where visit fvars (p : Pos): Expr → M Expr | (Expr.forallE n d b c) => do let d ← f p.pushBindingDomain <| d.instantiateRev fvars withLocalDecl n c d fun x => visit (fvars.push x) p.pushBindingBody b | e => do let body ← f p <| e.instantiateRev fvars mkForallFVars fvars body /-- Similar to `traverseLet` but with an additional pos argument to track position. -/ def traverseLetWithPos (f : Pos → Expr → M Expr) (p : Pos) (e : Expr) : M Expr := visit #[] p e where visit fvars (p : Pos) | Expr.letE n t v b _ => do let type ← f p.pushLetVarType <| t.instantiateRev fvars let value ← f p.pushLetValue <| v.instantiateRev fvars withLetDecl n type value fun x => visit (fvars.push x) p.pushLetBody b | e => do let body ← f p <| e.instantiateRev fvars -- if usedLetOnly = true then let binders will be eliminated -- if their var doesn't appear in the body. mkLetFVars (usedLetOnly := false) fvars body /-- Similar to `Lean.Meta.traverseChildren` except that `visit` also includes a `Pos` argument so you can track the subexpression position. -/ def traverseChildrenWithPos (visit : Pos → Expr → M Expr) (p : Pos) (e: Expr) : M Expr := match e with | Expr.forallE .. => traverseForallWithPos visit p e | Expr.lam .. => traverseLambdaWithPos visit p e | Expr.letE .. => traverseLetWithPos visit p e | Expr.app .. => Expr.traverseAppWithPos visit p e | Expr.mdata _ b => e.updateMData! <$> visit p b | Expr.proj _ _ b => e.updateProj! <$> visit p.pushProj b | _ => pure e /-- Given an expression `fun (x₁ : α₁) ... (xₙ : αₙ) => b`, will run `f` on each of the variable types `αᵢ` and `b` with the correct MetaM context, replacing each expression with the output of `f` and creating a new lambda. (that is, correctly instantiating bound variables and repackaging them after) -/ def traverseLambda (visit : Expr → M Expr) := forgetPos traverseLambdaWithPos visit /-- Given an expression ` (x₁ : α₁) → ... → (xₙ : αₙ) → b`, will run `f` on each of the variable types `αᵢ` and `b` with the correct MetaM context, replacing the expression with the output of `f` and creating a new forall expression. (that is, correctly instantiating bound variables and repackaging them after) -/ def traverseForall (visit : Expr → M Expr) := forgetPos traverseForallWithPos visit /-- Similar to `traverseLambda` and `traverseForall` but with let binders. -/ def traverseLet (visit : Expr → M Expr) := forgetPos traverseLetWithPos visit /-- Maps `visit` on each child of the given expression. Applications, foralls, lambdas and let binders are bundled (as they are bundled in `Expr.traverseApp`, `traverseForall`, ...). So `traverseChildren f e` where ``e = `(fn a₁ ... aₙ)`` will return ``(← f `(fn)) (← f `(a₁)) ... (← f `(aₙ))`` rather than ``(← f `(fn a₁ ... aₙ₋₁)) (← f `(aₙ))`` See also `Lean.Core.traverseChildren`. -/ def traverseChildren (visit : Expr → M Expr) := forgetPos traverseChildrenWithPos visit end Lean.Meta
af680803cc095a36c55c93dee450b503ff77b746
4727251e0cd73359b15b664c3170e5d754078599
/src/ring_theory/localization/cardinality.lean
5bc32507eea44ddc3af0ae4f6941aebab7f070f6
[ "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
2,695
lean
/- Copyright (c) 2022 Eric Rodriguez. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Rodriguez -/ import ring_theory.integral_domain import ring_theory.localization.basic import set_theory.cardinal.ordinal /-! # Cardinality of localizations In this file, we establish the cardinality of localizations. In most cases, a localization has cardinality equal to the base ring. If there are zero-divisors, however, this is no longer true - for example, `zmod 6` localized at `{2, 4}` is equal to `zmod 3`, and if you have zero in your submonoid, then your localization is trivial (see `is_localization.unique_of_zero_mem`). ## Main statements * `is_localization.card_le`: A localization has cardinality no larger than the base ring. * `is_localization.card`: If you don't localize at zero-divisors, the localization of a ring has cardinality equal to its base ring, -/ open_locale cardinal non_zero_divisors universes u v namespace is_localization variables {R : Type u} [comm_ring R] (S : submonoid R) {L : Type u} [comm_ring L] [algebra R L] [is_localization S L] include S /-- Localizing a finite ring can only reduce the amount of elements. -/ lemma algebra_map_surjective_of_fintype [fintype R] : function.surjective (algebra_map R L) := begin classical, haveI : fintype L := is_localization.fintype' S L, intro x, obtain ⟨⟨r, s⟩, h : x * (algebra_map R L) ↑s = (algebra_map R L) r⟩ := is_localization.surj S x, obtain ⟨n, hn, hp⟩ := (is_of_fin_order_iff_pow_eq_one _).1 (exists_pow_eq_one (is_localization.map_units L s).unit), rw [units.ext_iff, units.coe_pow, is_unit.unit_spec, ←nat.succ_pred_eq_of_pos hn, pow_succ] at hp, exact ⟨r * s ^ (n - 1), by erw [map_mul, map_pow, ←h, mul_assoc, hp, mul_one]⟩ end /-- A localization always has cardinality less than or equal to the base ring. -/ lemma card_le : #L ≤ #R := begin classical, casesI fintype_or_infinite R, { exact cardinal.mk_le_of_surjective (algebra_map_surjective_of_fintype S) }, erw [←cardinal.mul_eq_self $ cardinal.omega_le_mk R], set f : R × R → L := λ aa, is_localization.mk' _ aa.1 (if h : aa.2 ∈ S then ⟨aa.2, h⟩ else 1), refine @cardinal.mk_le_of_surjective _ _ f (λ a, _), obtain ⟨x, y, h⟩ := is_localization.mk'_surjective S a, use (x, y), dsimp [f], rwa [dif_pos $ show ↑y ∈ S, from y.2, set_like.eta] end variables (L) /-- If you do not localize at any zero-divisors, localization preserves cardinality. -/ lemma card (hS : S ≤ R⁰) : #R = #L := (cardinal.mk_le_of_injective (is_localization.injective L hS)).antisymm (card_le S) end is_localization
8bbb82ee0e4a2e5bbf5b4d8e1de3f751d0d3c589
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/library/data/bv.lean
4c6c1ccb538b5481d5e15da92413ee1a9861bcf4
[ "Apache-2.0" ]
permissive
YHVHvx/lean
732bf0fb7a298cd7fe0f15d82f8e248c11db49e9
038369533e0136dd395dc252084d3c1853accbf2
refs/heads/master
1,610,701,080,210
1,449,128,595,000
1,449,128,595,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,018
lean
/- Copyright (c) 2015 Joe Hendrix. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Joe Hendrix Basic operations on bitvectors. This is a work-in-progress, and contains additions to other theories. -/ import data.list import data.tuple namespace bv open algebra open bool open eq.ops open list open nat open prod open subtype open tuple definition bv [reducible] (n : ℕ) := tuple bool n -- Create a zero bitvector definition bv_zero (n : ℕ) : bv n := replicate ff -- Create a bitvector with the constant one. definition bv_one : Π (n : ℕ), bv n | 0 := replicate ff | (succ n) := (replicate ff : bv n) ++ (tt :: nil) definition bv_cong {a b : ℕ} : (a = b) → bv a → bv b | c (tag x p) := tag x (c ▸ p) section shift -- shift left definition bv_shl {n:ℕ} : bv n → ℕ → bv n | x i := if le : i ≤ n then let r := dropn i x ++ replicate ff in let eq := calc (n-i) + i = n : nat.sub_add_cancel le in bv_cong eq r else bv_zero n -- unsigned shift right definition bv_ushr {n:ℕ} : bv n → ℕ → bv n | x i := if le : i ≤ n then let y : bv (n-i) := @firstn _ _ (n - i) (sub_le n i) x in let eq := calc (i+(n-i)) = (n - i) + i : add.comm ... = n : nat.sub_add_cancel le in bv_cong eq (replicate ff ++ y) else bv_zero n -- signed shift right definition bv_sshr {m:ℕ} : bv (succ m) → ℕ → bv (succ m) | x i := let n := succ m in if le : i ≤ n then let z : bv i := replicate (head x) in let y : bv (n-i) := @firstn _ _ (n - i) (sub_le n i) x in let eq := calc (i+(n-i)) = (n-i) + i : add.comm ... = n : nat.sub_add_cancel le in bv_cong eq (z ++ y) else bv_zero n end shift section bitwise variable { n : ℕ } definition bv_not : bv n → bv n := map bnot definition bv_and : bv n → bv n → bv n := map₂ band definition bv_or : bv n → bv n → bv n := map₂ bor definition bv_xor : bv n → bv n → bv n := map₂ bxor end bitwise section arith variable { n : ℕ } protected definition xor3 (x:bool) (y:bool) (c:bool) := bxor (bxor x y) c protected definition carry (x:bool) (y:bool) (c:bool) := x && y || x && c || y && c definition bv_neg : bv n → bv n | x := let f := λy c, (y || c, bxor y c) in pr₂ (mapAccumR f x ff) -- Add with carry (no overflow) definition bv_adc : bv n → bv n → bool → bv (n+1) | x y c := let f := λx y c, (bv.carry x y c, bv.xor3 x y c) in let z := tuple.mapAccumR₂ f x y c in (pr₁ z) :: (pr₂ z) definition bv_add : bv n → bv n → bv n | x y := tail (bv_adc x y ff) protected definition borrow (x:bool) (y:bool) (b:bool) := bnot x && y || bnot x && b || y && b -- Subtract with borrow definition bv_sbb : bv n → bv n → bool → bool × bv n | x y b := let f := λx y c, (bv.borrow x y c, bv.xor3 x y c) in tuple.mapAccumR₂ f x y b definition bv_sub : bv n → bv n → bv n | x y := pr₂ (bv_sbb x y ff) definition bv_has_zero [instance] : has_zero (bv n) := has_zero.mk (bv_zero n) definition bv_has_one [instance] : has_one (bv n) := has_one.mk (bv_one n) definition bv_has_add [instance] : has_add (bv n) := has_add.mk bv_add definition bv_has_sub [instance] : has_sub (bv n) := has_sub.mk bv_sub definition bv_has_neg [instance] : has_neg (bv n) := has_neg.mk bv_neg definition bv_mul : bv n → bv n → bv n | x y := let f := λr b, cond b (r + r + y) (r + r) in foldl f 0 (to_list x) definition bv_has_mul [instance] : has_mul (bv n) := has_mul.mk bv_mul definition bv_ult : bv n → bv n → bool := λx y, pr₁ (bv_sbb x y ff) definition bv_ugt : bv n → bv n → bool := λx y, bv_ult y x definition bv_ule : bv n → bv n → bool := λx y, bnot (bv_ult y x) definition bv_uge : bv n → bv n → bool := λx y, bv_ule y x definition bv_slt : bv (succ n) → bv (succ n) → bool := λx y, cond (head x) (cond (head y) (bv_ult (tail x) (tail y)) -- both negative tt) -- x is negative and y is not (cond (head y) ff -- y is negative and x is not (bv_ult (tail x) (tail y))) -- both positive definition bv_sgt : bv (succ n) → bv (succ n) → bool := λx y, bv_slt y x definition bv_sle : bv (succ n) → bv (succ n) → bool := λx y, bnot (bv_slt y x) definition bv_sge : bv (succ n) → bv (succ n) → bool := λx y, bv_sle y x end arith section from_bv variable {A : Type} -- Convert a bitvector to another number. definition from_bv [p : has_add A] [q0 : has_zero A] [q1 : has_one A] {n:nat} (v:bv n) : A := let f := λr b, cond b (r + r + 1) (r + r) in foldl f 0 (to_list v) end from_bv end bv
4d49bd0cb9b281080ead45d271761a333d69753a
fecda8e6b848337561d6467a1e30cf23176d6ad0
/src/data/nat/multiplicity.lean
30ebdb304fc7d635a3a48a46f743c5379ffe9030
[ "Apache-2.0" ]
permissive
spolu/mathlib
bacf18c3d2a561d00ecdc9413187729dd1f705ed
480c92cdfe1cf3c2d083abded87e82162e8814f4
refs/heads/master
1,671,684,094,325
1,600,736,045,000
1,600,736,045,000
297,564,749
1
0
null
1,600,758,368,000
1,600,758,367,000
null
UTF-8
Lean
false
false
9,414
lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import data.nat.choose.dvd import ring_theory.multiplicity import data.nat.modeq import algebra.gcd_monoid /-! # Natural number multiplicity This file contains lemmas about the multiplicity function (the maximum prime power divding a number). # Main results There are natural number versions of some basic lemmas about multiplicity. There are also lemmas about the multiplicity of primes in factorials and in binomial coefficients. -/ open finset nat multiplicity open_locale big_operators namespace nat /-- The multiplicity of a divisor `m` of `n`, is the cardinality of the set of positive natural numbers `i` such that `p ^ i` divides `n`. The set is expressed by filtering `Ico 1 b` where `b` is any bound at least `n` -/ lemma multiplicity_eq_card_pow_dvd {m n b : ℕ} (hm1 : m ≠ 1) (hn0 : 0 < n) (hb : n ≤ b): multiplicity m n = ↑((finset.Ico 1 b).filter (λ i, m ^ i ∣ n)).card := calc multiplicity m n = ↑(Ico 1 $ ((multiplicity m n).get (finite_nat_iff.2 ⟨hm1, hn0⟩) + 1)).card : by simp ... = ↑((finset.Ico 1 b).filter (λ i, m ^ i ∣ n)).card : congr_arg coe $ congr_arg card $ finset.ext $ λ i, have hmn : ¬ m ^ n ∣ n, from if hm0 : m = 0 then λ _, by cases n; simp [*, lt_irrefl, nat.pow_succ] at * else mt (le_of_dvd hn0) (not_le_of_gt $ lt_pow_self (lt_of_le_of_ne (nat.pos_of_ne_zero hm0) hm1.symm) _), ⟨λ hi, begin simp only [Ico.mem, mem_filter, lt_succ_iff] at *, exact ⟨⟨hi.1, lt_of_le_of_lt hi.2 $ lt_of_lt_of_le (by rw [← enat.coe_lt_coe, enat.coe_get, multiplicity_lt_iff_neg_dvd]; exact hmn) hb⟩, by rw [pow_dvd_iff_le_multiplicity]; rw [← @enat.coe_le_coe i, enat.coe_get] at hi; exact hi.2⟩ end, begin simp only [Ico.mem, mem_filter, lt_succ_iff, and_imp, true_and] { contextual := tt }, assume h1i hib hmin, rwa [← enat.coe_le_coe, enat.coe_get, ← pow_dvd_iff_le_multiplicity] end⟩ namespace prime lemma multiplicity_one {p : ℕ} (hp : p.prime) : multiplicity p 1 = 0 := by rw [multiplicity.one_right (mt nat.is_unit_iff.mp (ne_of_gt hp.one_lt))] lemma multiplicity_mul {p m n : ℕ} (hp : p.prime) : multiplicity p (m * n) = multiplicity p m + multiplicity p n := by rw [← int.coe_nat_multiplicity, ← int.coe_nat_multiplicity, ← int.coe_nat_multiplicity, int.coe_nat_mul, multiplicity.mul (nat.prime_iff_prime_int.1 hp)] lemma multiplicity_pow {p m n : ℕ} (hp : p.prime) : multiplicity p (m ^ n) = n •ℕ (multiplicity p m) := by induction n; simp [nat.pow_succ, hp.multiplicity_mul, *, hp.multiplicity_one, succ_nsmul, add_comm] lemma multiplicity_self {p : ℕ} (hp : p.prime) : multiplicity p p = 1 := have h₁ : ¬ is_unit (p : ℤ), from mt is_unit_int.1 (ne_of_gt hp.one_lt), have h₂ : (p : ℤ) ≠ 0, from int.coe_nat_ne_zero.2 hp.ne_zero, by rw [← int.coe_nat_multiplicity, multiplicity_self h₁ h₂] lemma multiplicity_pow_self {p n : ℕ} (hp : p.prime) : multiplicity p (p ^ n) = n := by induction n; simp [hp.multiplicity_one, nat.pow_succ, hp.multiplicity_mul, *, hp.multiplicity_self, succ_eq_add_one] /-- The multiplicity of a prime in `fact n` is the sum of the quotients `n / p ^ i`. This sum is expressed over the set `Ico 1 b` where `b` is any bound at least `n` -/ lemma multiplicity_fact {p : ℕ} (hp : p.prime) : ∀ {n b : ℕ}, n ≤ b → multiplicity p n.fact = (∑ i in Ico 1 b, n / p ^ i : ℕ) | 0 b hb := by simp [Ico, hp.multiplicity_one] | (n+1) b hb := calc multiplicity p (n+1).fact = multiplicity p n.fact + multiplicity p (n+1) : by rw [fact_succ, hp.multiplicity_mul, add_comm] ... = (∑ i in Ico 1 b, n / p ^ i : ℕ) + ((finset.Ico 1 b).filter (λ i, p ^ i ∣ n+1)).card : by rw [multiplicity_fact (le_of_succ_le hb), ← multiplicity_eq_card_pow_dvd (ne_of_gt hp.one_lt) (succ_pos _) hb] ... = (∑ i in Ico 1 b, (n / p ^ i + if p^i ∣ n+1 then 1 else 0) : ℕ) : by rw [sum_add_distrib, sum_boole]; simp ... = (∑ i in Ico 1 b, (n + 1) / p ^ i : ℕ) : congr_arg coe $ finset.sum_congr rfl (by intros; simp [nat.succ_div]; congr) /-- A prime power divides `fact n` iff it is at most the sum of the quotients `n / p ^ i`. This sum is expressed over the set `Ico 1 b` where `b` is any bound at least `n` -/ lemma pow_dvd_fact_iff {p : ℕ} {n r b : ℕ} (hp : p.prime) (hbn : n ≤ b) : p ^ r ∣ fact n ↔ r ≤ ∑ i in Ico 1 b, n / p ^ i := by rw [← enat.coe_le_coe, ← hp.multiplicity_fact hbn, ← pow_dvd_iff_le_multiplicity] lemma multiplicity_choose_aux {p n b k : ℕ} (hp : p.prime) (hkn : k ≤ n) : ∑ i in finset.Ico 1 b, n / p ^ i = ∑ i in finset.Ico 1 b, k / p ^ i + ∑ i in finset.Ico 1 b, (n - k) / p ^ i + ((finset.Ico 1 b).filter (λ i, p ^ i ≤ k % p ^ i + (n - k) % p ^ i)).card := calc ∑ i in finset.Ico 1 b, n / p ^ i = ∑ i in finset.Ico 1 b, (k + (n - k)) / p ^ i : by simp only [nat.add_sub_cancel' hkn] ... = ∑ i in finset.Ico 1 b, (k / p ^ i + (n - k) / p ^ i + if p ^ i ≤ k % p ^ i + (n - k) % p ^ i then 1 else 0) : by simp only [nat.add_div (nat.pow_pos hp.pos _)] ... = _ : begin simp only [sum_add_distrib], simp [sum_boole], end -- we have to use `sum_add_distrib` before `add_ite` fires. /-- The multiplity of `p` in `choose n k` is the number of carries when `k` and `n - k` are added in base `p`. The set is expressed by filtering `Ico 1 b` where `b` is any bound at least `n`. -/ lemma multiplicity_choose {p n k b : ℕ} (hp : p.prime) (hkn : k ≤ n) (hnb : n ≤ b) : multiplicity p (choose n k) = ((Ico 1 b).filter (λ i, p ^ i ≤ k % p ^ i + (n - k) % p ^ i)).card := have h₁ : multiplicity p (choose n k) + multiplicity p (k.fact * (n - k).fact) = ((finset.Ico 1 b).filter (λ i, p ^ i ≤ k % p ^ i + (n - k) % p ^ i)).card + multiplicity p (k.fact * (n - k).fact), begin rw [← hp.multiplicity_mul, ← mul_assoc, choose_mul_fact_mul_fact hkn, hp.multiplicity_fact hnb, hp.multiplicity_mul, hp.multiplicity_fact (le_trans hkn hnb), hp.multiplicity_fact (le_trans (nat.sub_le_self _ _) hnb), multiplicity_choose_aux hp hkn], simp [add_comm], end, (enat.add_right_cancel_iff (enat.ne_top_iff_dom.2 $ by exact finite_nat_iff.2 ⟨ne_of_gt hp.one_lt, mul_pos (fact_pos k) (fact_pos (n - k))⟩)).1 h₁ /-- A lower bound on the multiplicity of `p` in `choose n k`. -/ lemma multiplicity_le_multiplicity_choose_add {p : ℕ} (hp : p.prime) (n k : ℕ) : multiplicity p n ≤ multiplicity p (choose n k) + multiplicity p k := if hkn : n < k then by simp [choose_eq_zero_of_lt hkn] else if hk0 : k = 0 then by simp [hk0] else if hn0 : n = 0 then by cases k; simp [hn0, *] at * else begin rw [multiplicity_choose hp (le_of_not_gt hkn) (le_refl _), multiplicity_eq_card_pow_dvd (ne_of_gt hp.one_lt) (nat.pos_of_ne_zero hk0) (le_of_not_gt hkn), multiplicity_eq_card_pow_dvd (ne_of_gt hp.one_lt) (nat.pos_of_ne_zero hn0) (le_refl _), ← enat.coe_add, enat.coe_le_coe], calc ((Ico 1 n).filter (λ i, p ^ i ∣ n)).card ≤ ((Ico 1 n).filter (λ i, p ^ i ≤ k % p ^ i + (n - k) % p ^ i) ∪ (Ico 1 n).filter (λ i, p ^ i ∣ k) ).card : card_le_of_subset $ λ i, begin have := @le_mod_add_mod_of_dvd_add_of_not_dvd k (n - k) (p ^ i), simp [nat.add_sub_cancel' (le_of_not_gt hkn)] at * {contextual := tt}, tauto end ... ≤ ((Ico 1 n).filter (λ i, p ^ i ≤ k % p ^ i + (n - k) % p ^ i)).card + ((Ico 1 n).filter (λ i, p ^ i ∣ k)).card : card_union_le _ _ end lemma multiplicity_choose_prime_pow {p n k : ℕ} (hp : p.prime) (hkn : k ≤ p ^ n) (hk0 : 0 < k) : multiplicity p (choose (p ^ n) k) + multiplicity p k = n := le_antisymm (have hdisj : disjoint ((Ico 1 (p ^ n)).filter (λ i, p ^ i ≤ k % p ^ i + (p ^ n - k) % p ^ i)) ((Ico 1 (p ^ n)).filter (λ i, p ^ i ∣ k)), by simp [disjoint_right, *, dvd_iff_mod_eq_zero, nat.mod_lt _ (nat.pow_pos hp.pos _)] {contextual := tt}, have filter_subset_Ico : filter (λ i, p ^ i ≤ k % p ^ i + (p ^ n - k) % p ^ i ∨ p ^ i ∣ k) (Ico 1 (p ^ n)) ⊆ Ico 1 n.succ, from begin simp only [finset.subset_iff, Ico.mem, mem_filter, and_imp, true_and] {contextual := tt}, assume i h1i hip h, refine lt_succ_of_le (le_of_not_gt (λ hin, _)), have hpik : ¬ p ^ i ∣ k, from mt (le_of_dvd hk0) (not_le_of_gt (lt_of_le_of_lt hkn (pow_right_strict_mono hp.two_le hin))), have hpn : k % p ^ i + (p ^ n - k) % p ^ i < p ^ i, from calc k % p ^ i + (p ^ n - k) % p ^ i ≤ k + (p ^ n - k) : add_le_add (mod_le _ _) (mod_le _ _) ... = p ^ n : nat.add_sub_cancel' hkn ... < p ^ i : pow_right_strict_mono hp.two_le hin, simpa [hpik, not_le_of_gt hpn] using h end, begin rw [multiplicity_choose hp hkn (le_refl _), multiplicity_eq_card_pow_dvd (ne_of_gt hp.one_lt) hk0 hkn, ← enat.coe_add, enat.coe_le_coe, ← card_disjoint_union hdisj, filter_union_right], exact le_trans (card_le_of_subset filter_subset_Ico) (by simp) end) (by rw [← hp.multiplicity_pow_self]; exact multiplicity_le_multiplicity_choose_add hp _ _) end prime end nat
0061ad08f838288ab57218ae76ed584debb66f28
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/representation_theory/group_cohomology_resolution.lean
081d7f52935410dede56f4f2fb6722b5e8b61023
[ "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
23,852
lean
/- Copyright (c) 2022 Amelia Livingston. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Amelia Livingston -/ import algebra.category.Module.projective import algebraic_topology.extra_degeneracy import category_theory.abelian.ext import representation_theory.Rep /-! # The structure of the `k[G]`-module `k[Gⁿ]` This file contains facts about an important `k[G]`-module structure on `k[Gⁿ]`, where `k` is a commutative ring and `G` is a group. The module structure arises from the representation `G →* End(k[Gⁿ])` induced by the diagonal action of `G` on `Gⁿ.` In particular, we define an isomorphism of `k`-linear `G`-representations between `k[Gⁿ⁺¹]` and `k[G] ⊗ₖ k[Gⁿ]` (on which `G` acts by `ρ(g₁)(g₂ ⊗ x) = (g₁ * g₂) ⊗ x`). This allows us to define a `k[G]`-basis on `k[Gⁿ⁺¹]`, by mapping the natural `k[G]`-basis of `k[G] ⊗ₖ k[Gⁿ]` along the isomorphism. We then define the standard resolution of `k` as a trivial representation, by taking the alternating face map complex associated to an appropriate simplicial `k`-linear `G`-representation. This simplicial object is the `linearization` of the simplicial `G`-set given by the universal cover of the classifying space of `G`, `EG`. We prove this simplicial `G`-set `EG` is isomorphic to the Čech nerve of the natural arrow of `G`-sets `G ⟶ {pt}`. We then use this isomorphism to deduce that as a complex of `k`-modules, the standard resolution of `k` as a trivial `G`-representation is homotopy equivalent to the complex with `k` at 0 and 0 elsewhere. Putting this material together allows us to define `group_cohomology.ProjectiveResolution`, the standard projective resolution of `k` as a trivial `k`-linear `G`-representation. ## Main definitions * `group_cohomology.resolution.to_tensor` * `group_cohomology.resolution.of_tensor` * `Rep.of_mul_action` * `group_cohomology.resolution.equiv_tensor` * `group_cohomology.resolution.of_mul_action_basis` * `classifying_space_universal_cover` * `group_cohomology.resolution.forget₂_to_Module_homotopy_equiv` * `group_cohomology.ProjectiveResolution` ## Implementation notes We express `k[G]`-module structures on a module `k`-module `V` using the `representation` definition. We avoid using instances `module (G →₀ k) V` so that we do not run into possible scalar action diamonds. We also use the category theory library to bundle the type `k[Gⁿ]` - or more generally `k[H]` when `H` has `G`-action - and the representation together, as a term of type `Rep k G`, and call it `Rep.of_mul_action k G H.` This enables us to express the fact that certain maps are `G`-equivariant by constructing morphisms in the category `Rep k G`, i.e., representations of `G` over `k`. -/ noncomputable theory universes u v w variables {k G : Type u} [comm_ring k] {n : ℕ} open_locale tensor_product open category_theory local notation `Gⁿ` := fin n → G local notation `Gⁿ⁺¹` := fin (n + 1) → G namespace group_cohomology.resolution open finsupp (hiding lift) fin (partial_prod) representation section basis variables (k G n) [group G] /-- The `k`-linear map from `k[Gⁿ⁺¹]` to `k[G] ⊗ₖ k[Gⁿ]` sending `(g₀, ..., gₙ)` to `g₀ ⊗ (g₀⁻¹g₁, g₁⁻¹g₂, ..., gₙ₋₁⁻¹gₙ)`. -/ def to_tensor_aux : ((fin (n + 1) → G) →₀ k) →ₗ[k] (G →₀ k) ⊗[k] ((fin n → G) →₀ k) := finsupp.lift ((G →₀ k) ⊗[k] ((fin n → G) →₀ k)) k (fin (n + 1) → G) (λ x, single (x 0) 1 ⊗ₜ[k] single (λ i, (x i)⁻¹ * x i.succ) 1) /-- The `k`-linear map from `k[G] ⊗ₖ k[Gⁿ]` to `k[Gⁿ⁺¹]` sending `g ⊗ (g₁, ..., gₙ)` to `(g, gg₁, gg₁g₂, ..., gg₁...gₙ)`. -/ def of_tensor_aux : (G →₀ k) ⊗[k] ((fin n → G) →₀ k) →ₗ[k] ((fin (n + 1) → G) →₀ k) := tensor_product.lift (finsupp.lift _ _ _ $ λ g, finsupp.lift _ _ _ (λ f, single (g • partial_prod f) (1 : k))) variables {k G n} lemma to_tensor_aux_single (f : Gⁿ⁺¹) (m : k) : to_tensor_aux k G n (single f m) = single (f 0) m ⊗ₜ single (λ i, (f i)⁻¹ * f i.succ) 1 := begin simp only [to_tensor_aux, lift_apply, sum_single_index, tensor_product.smul_tmul'], { simp }, end lemma to_tensor_aux_of_mul_action (g : G) (x : Gⁿ⁺¹) : to_tensor_aux k G n (of_mul_action k G Gⁿ⁺¹ g (single x 1)) = tensor_product.map (of_mul_action k G G g) 1 (to_tensor_aux k G n (single x 1)) := by simp [of_mul_action_def, to_tensor_aux_single, mul_assoc, inv_mul_cancel_left] lemma of_tensor_aux_single (g : G) (m : k) (x : Gⁿ →₀ k) : of_tensor_aux k G n ((single g m) ⊗ₜ x) = finsupp.lift (Gⁿ⁺¹ →₀ k) k Gⁿ (λ f, single (g • partial_prod f) m) x := by simp [of_tensor_aux, sum_single_index, smul_sum, mul_comm m] lemma of_tensor_aux_comm_of_mul_action (g h : G) (x : Gⁿ) : of_tensor_aux k G n (tensor_product.map (of_mul_action k G G g) (1 : module.End k (Gⁿ →₀ k)) (single h (1 : k) ⊗ₜ single x (1 : k))) = of_mul_action k G Gⁿ⁺¹ g (of_tensor_aux k G n (single h 1 ⊗ₜ single x 1)) := begin simp [of_mul_action_def, of_tensor_aux_single, mul_smul], end lemma to_tensor_aux_left_inv (x : Gⁿ⁺¹ →₀ k) : of_tensor_aux _ _ _ (to_tensor_aux _ _ _ x) = x := begin refine linear_map.ext_iff.1 (@finsupp.lhom_ext _ _ _ k _ _ _ _ _ (linear_map.comp (of_tensor_aux _ _ _) (to_tensor_aux _ _ _)) linear_map.id (λ x y, _)) x, dsimp, rw [to_tensor_aux_single x y, of_tensor_aux_single, finsupp.lift_apply, finsupp.sum_single_index, one_smul, fin.partial_prod_left_inv], { rw zero_smul } end lemma to_tensor_aux_right_inv (x : (G →₀ k) ⊗[k] (Gⁿ →₀ k)) : to_tensor_aux _ _ _ (of_tensor_aux _ _ _ x) = x := begin refine tensor_product.induction_on x (by simp) (λ y z, _) (λ z w hz hw, by simp [hz, hw]), rw [←finsupp.sum_single y, finsupp.sum, tensor_product.sum_tmul], simp only [finset.smul_sum, linear_map.map_sum], refine finset.sum_congr rfl (λ f hf, _), simp only [of_tensor_aux_single, finsupp.lift_apply, finsupp.smul_single', linear_map.map_finsupp_sum, to_tensor_aux_single, fin.partial_prod_right_inv], dsimp, simp only [fin.partial_prod_zero, mul_one], conv_rhs {rw [←finsupp.sum_single z, finsupp.sum, tensor_product.tmul_sum]}, exact finset.sum_congr rfl (λ g hg, show _ ⊗ₜ _ = _, by rw [←finsupp.smul_single', tensor_product.smul_tmul, finsupp.smul_single_one]) end variables (k G n) /-- A hom of `k`-linear representations of `G` from `k[Gⁿ⁺¹]` to `k[G] ⊗ₖ k[Gⁿ]` (on which `G` acts by `ρ(g₁)(g₂ ⊗ x) = (g₁ * g₂) ⊗ x`) sending `(g₀, ..., gₙ)` to `g₀ ⊗ (g₀⁻¹g₁, g₁⁻¹g₂, ..., gₙ₋₁⁻¹gₙ)`. -/ def to_tensor : Rep.of_mul_action k G (fin (n + 1) → G) ⟶ Rep.of ((representation.of_mul_action k G G).tprod (1 : G →* module.End k ((fin n → G) →₀ k))) := { hom := to_tensor_aux k G n, comm' := λ g, by ext; exact to_tensor_aux_of_mul_action _ _ } /-- A hom of `k`-linear representations of `G` from `k[G] ⊗ₖ k[Gⁿ]` (on which `G` acts by `ρ(g₁)(g₂ ⊗ x) = (g₁ * g₂) ⊗ x`) to `k[Gⁿ⁺¹]` sending `g ⊗ (g₁, ..., gₙ)` to `(g, gg₁, gg₁g₂, ..., gg₁...gₙ)`. -/ def of_tensor : Rep.of ((representation.of_mul_action k G G).tprod (1 : G →* module.End k ((fin n → G) →₀ k))) ⟶ Rep.of_mul_action k G (fin (n + 1) → G) := { hom := of_tensor_aux k G n, comm' := λ g, by { ext, congr' 1, exact (of_tensor_aux_comm_of_mul_action _ _ _) }} variables {k G n} @[simp] lemma to_tensor_single (f : Gⁿ⁺¹) (m : k) : (to_tensor k G n).hom (single f m) = single (f 0) m ⊗ₜ single (λ i, (f i)⁻¹ * f i.succ) 1 := to_tensor_aux_single _ _ @[simp] lemma of_tensor_single (g : G) (m : k) (x : Gⁿ →₀ k) : (of_tensor k G n).hom ((single g m) ⊗ₜ x) = finsupp.lift (Rep.of_mul_action k G Gⁿ⁺¹) k Gⁿ (λ f, single (g • partial_prod f) m) x := of_tensor_aux_single _ _ _ lemma of_tensor_single' (g : G →₀ k) (x : Gⁿ) (m : k) : (of_tensor k G n).hom (g ⊗ₜ single x m) = finsupp.lift _ k G (λ a, single (a • partial_prod x) m) g := by simp [of_tensor, of_tensor_aux] variables (k G n) /-- An isomorphism of `k`-linear representations of `G` from `k[Gⁿ⁺¹]` to `k[G] ⊗ₖ k[Gⁿ]` (on which `G` acts by `ρ(g₁)(g₂ ⊗ x) = (g₁ * g₂) ⊗ x`) sending `(g₀, ..., gₙ)` to `g₀ ⊗ (g₀⁻¹g₁, g₁⁻¹g₂, ..., gₙ₋₁⁻¹gₙ)`. -/ def equiv_tensor : (Rep.of_mul_action k G (fin (n + 1) → G)) ≅ Rep.of ((representation.of_mul_action k G G).tprod (1 : representation k G ((fin n → G) →₀ k))) := Action.mk_iso (linear_equiv.to_Module_iso { inv_fun := of_tensor_aux k G n, left_inv := to_tensor_aux_left_inv, right_inv := λ x, by convert to_tensor_aux_right_inv x, ..to_tensor_aux k G n }) (to_tensor k G n).comm @[simp] lemma equiv_tensor_def : (equiv_tensor k G n).hom = to_tensor k G n := rfl @[simp] lemma equiv_tensor_inv_def : (equiv_tensor k G n).inv = of_tensor k G n := rfl /-- The `k[G]`-linear isomorphism `k[G] ⊗ₖ k[Gⁿ] ≃ k[Gⁿ⁺¹]`, where the `k[G]`-module structure on the lefthand side is `tensor_product.left_module`, whilst that of the righthand side comes from `representation.as_module`. Allows us to use `basis.algebra_tensor_product` to get a `k[G]`-basis of the righthand side. -/ def of_mul_action_basis_aux : (monoid_algebra k G ⊗[k] ((fin n → G) →₀ k)) ≃ₗ[monoid_algebra k G] (of_mul_action k G (fin (n + 1) → G)).as_module := { map_smul' := λ r x, begin rw [ring_hom.id_apply, linear_equiv.to_fun_eq_coe, ←linear_equiv.map_smul], congr' 1, refine x.induction_on _ (λ x y, _) (λ y z hy hz, _), { simp only [smul_zero] }, { simp only [tensor_product.smul_tmul'], show (r * x) ⊗ₜ y = _, rw [←of_mul_action_self_smul_eq_mul, smul_tprod_one_as_module] }, { rw [smul_add, hz, hy, smul_add], } end, .. ((Rep.equivalence_Module_monoid_algebra.1).map_iso (equiv_tensor k G n).symm).to_linear_equiv } /-- A `k[G]`-basis of `k[Gⁿ⁺¹]`, coming from the `k[G]`-linear isomorphism `k[G] ⊗ₖ k[Gⁿ] ≃ k[Gⁿ⁺¹].` -/ def of_mul_action_basis : basis (fin n → G) (monoid_algebra k G) (of_mul_action k G (fin (n + 1) → G)).as_module := @basis.map _ (monoid_algebra k G) (monoid_algebra k G ⊗[k] ((fin n → G) →₀ k)) _ _ _ _ _ _ (@algebra.tensor_product.basis k _ (monoid_algebra k G) _ _ ((fin n → G) →₀ k) _ _ (fin n → G) ⟨linear_equiv.refl k _⟩) (of_mul_action_basis_aux k G n) lemma of_mul_action_free : module.free (monoid_algebra k G) (of_mul_action k G (fin (n + 1) → G)).as_module := module.free.of_basis (of_mul_action_basis k G n) end basis end group_cohomology.resolution variables (G) /-- The simplicial `G`-set sending `[n]` to `Gⁿ⁺¹` equipped with the diagonal action of `G`. -/ def classifying_space_universal_cover [monoid G] : simplicial_object (Action (Type u) $ Mon.of G) := { obj := λ n, Action.of_mul_action G (fin (n.unop.len + 1) → G), map := λ m n f, { hom := λ x, x ∘ f.unop.to_order_hom, comm' := λ g, rfl }, map_id' := λ n, rfl, map_comp' := λ i j k f g, rfl } namespace classifying_space_universal_cover open category_theory category_theory.limits variables [monoid G] /-- When the category is `G`-Set, `cech_nerve_terminal_from` of `G` with the left regular action is isomorphic to `EG`, the universal cover of the classifying space of `G` as a simplicial `G`-set. -/ def cech_nerve_terminal_from_iso : cech_nerve_terminal_from (Action.of_mul_action G G) ≅ classifying_space_universal_cover G := nat_iso.of_components (λ n, limit.iso_limit_cone (Action.of_mul_action_limit_cone _ _)) $ λ m n f, begin refine is_limit.hom_ext (Action.of_mul_action_limit_cone.{u 0} _ _).2 (λ j, _), dunfold cech_nerve_terminal_from pi.lift, dsimp, rw [category.assoc, limit.iso_limit_cone_hom_π, limit.lift_π, category.assoc], exact (limit.iso_limit_cone_hom_π _ _).symm, end /-- As a simplicial set, `cech_nerve_terminal_from` of a monoid `G` is isomorphic to the universal cover of the classifying space of `G` as a simplicial set. -/ def cech_nerve_terminal_from_iso_comp_forget : cech_nerve_terminal_from G ≅ classifying_space_universal_cover G ⋙ forget _ := nat_iso.of_components (λ n, types.product_iso _) $ λ m n f, matrix.ext $ λ i j, types.limit.lift_π_apply _ _ _ _ variables (k G) open algebraic_topology simplicial_object.augmented simplicial_object category_theory.arrow /-- The universal cover of the classifying space of `G` as a simplicial set, augmented by the map from `fin 1 → G` to the terminal object in `Type u`. -/ def comp_forget_augmented : simplicial_object.augmented (Type u) := simplicial_object.augment (classifying_space_universal_cover G ⋙ forget _) (terminal _) (terminal.from _) $ λ i g h, subsingleton.elim _ _ /-- The augmented Čech nerve of the map from `fin 1 → G` to the terminal object in `Type u` has an extra degeneracy. -/ def extra_degeneracy_augmented_cech_nerve : extra_degeneracy (arrow.mk $ terminal.from G).augmented_cech_nerve := augmented_cech_nerve.extra_degeneracy (arrow.mk $ terminal.from G) ⟨λ x, (1 : G), @subsingleton.elim _ (@unique.subsingleton _ (limits.unique_to_terminal _)) _ _⟩ /-- The universal cover of the classifying space of `G` as a simplicial set, augmented by the map from `fin 1 → G` to the terminal object in `Type u`, has an extra degeneracy. -/ def extra_degeneracy_comp_forget_augmented : extra_degeneracy (comp_forget_augmented G) := begin refine extra_degeneracy.of_iso (_ : (arrow.mk $ terminal.from G).augmented_cech_nerve ≅ _) (extra_degeneracy_augmented_cech_nerve G), exact comma.iso_mk (cech_nerve_terminal_from.iso G ≪≫ cech_nerve_terminal_from_iso_comp_forget G) (iso.refl _) (by ext : 2; apply is_terminal.hom_ext terminal_is_terminal), end /-- The free functor `Type u ⥤ Module.{u} k` applied to the universal cover of the classifying space of `G` as a simplicial set, augmented by the map from `fin 1 → G` to the terminal object in `Type u`. -/ def comp_forget_augmented.to_Module : simplicial_object.augmented (Module.{u} k) := ((simplicial_object.augmented.whiskering _ _).obj (Module.free k)).obj (comp_forget_augmented G) /-- If we augment the universal cover of the classifying space of `G` as a simplicial set by the map from `fin 1 → G` to the terminal object in `Type u`, then apply the free functor `Type u ⥤ Module.{u} k`, the resulting augmented simplicial `k`-module has an extra degeneracy. -/ def extra_degeneracy_comp_forget_augmented_to_Module : extra_degeneracy (comp_forget_augmented.to_Module k G) := extra_degeneracy.map (extra_degeneracy_comp_forget_augmented G) (Module.free k) end classifying_space_universal_cover variables (k) /-- The standard resolution of `k` as a trivial representation, defined as the alternating face map complex of a simplicial `k`-linear `G`-representation. -/ def group_cohomology.resolution [monoid G] := (algebraic_topology.alternating_face_map_complex (Rep k G)).obj (classifying_space_universal_cover G ⋙ (Rep.linearization k G).1.1) namespace group_cohomology.resolution open classifying_space_universal_cover algebraic_topology category_theory category_theory.limits variables (k G) [monoid G] /-- The `k`-linear map underlying the differential in the standard resolution of `k` as a trivial `k`-linear `G`-representation. It sends `(g₀, ..., gₙ) ↦ ∑ (-1)ⁱ • (g₀, ..., ĝᵢ, ..., gₙ)`. -/ def d (G : Type u) (n : ℕ) : ((fin (n + 1) → G) →₀ k) →ₗ[k] ((fin n → G) →₀ k) := finsupp.lift ((fin n → G) →₀ k) k (fin (n + 1) → G) (λ g, (@finset.univ (fin (n + 1)) _).sum (λ p, finsupp.single (g ∘ p.succ_above) ((-1 : k) ^ (p : ℕ)))) variables {k G} @[simp] lemma d_of {G : Type u} {n : ℕ} (c : fin (n + 1) → G) : d k G n (finsupp.single c 1) = finset.univ.sum (λ p : fin (n + 1), finsupp.single (c ∘ p.succ_above) ((-1 : k) ^ (p : ℕ))) := by simp [d] variables (k G) /-- The `n`th object of the standard resolution of `k` is definitionally isomorphic to `k[Gⁿ⁺¹]` equipped with the representation induced by the diagonal action of `G`. -/ def X_iso (n : ℕ) : (group_cohomology.resolution k G).X n ≅ Rep.of_mul_action k G (fin (n + 1) → G) := iso.refl _ lemma X_projective (G : Type u) [group G] (n : ℕ) : projective ((group_cohomology.resolution k G).X n) := Rep.equivalence_Module_monoid_algebra.to_adjunction.projective_of_map_projective _ $ @Module.projective_of_free.{u} _ _ (Module.of (monoid_algebra k G) (representation.of_mul_action k G (fin (n + 1) → G)).as_module) _ (of_mul_action_basis k G n) /-- Simpler expression for the differential in the standard resolution of `k` as a `G`-representation. It sends `(g₀, ..., gₙ₊₁) ↦ ∑ (-1)ⁱ • (g₀, ..., ĝᵢ, ..., gₙ₊₁)`. -/ theorem d_eq (n : ℕ) : ((group_cohomology.resolution k G).d (n + 1) n).hom = d k G (n + 1) := begin ext x y, dsimp [group_cohomology.resolution], simpa [←@int_cast_smul k, simplicial_object.δ], end section exactness /-- The standard resolution of `k` as a trivial representation as a complex of `k`-modules. -/ def forget₂_to_Module := ((forget₂ (Rep k G) (Module.{u} k)).map_homological_complex _).obj (group_cohomology.resolution k G) /-- If we apply the free functor `Type u ⥤ Module.{u} k` to the universal cover of the classifying space of `G` as a simplicial set, then take the alternating face map complex, the result is isomorphic to the standard resolution of the trivial `G`-representation `k` as a complex of `k`-modules. -/ def comp_forget_augmented_iso : (alternating_face_map_complex.obj (simplicial_object.augmented.drop.obj (comp_forget_augmented.to_Module k G))) ≅ group_cohomology.resolution.forget₂_to_Module k G := eq_to_iso (functor.congr_obj (map_alternating_face_map_complex (forget₂ (Rep k G) (Module.{u} k))).symm (classifying_space_universal_cover G ⋙ (Rep.linearization k G).1.1)) /-- As a complex of `k`-modules, the standard resolution of the trivial `G`-representation `k` is homotopy equivalent to the complex which is `k` at 0 and 0 elsewhere. -/ def forget₂_to_Module_homotopy_equiv : homotopy_equiv (group_cohomology.resolution.forget₂_to_Module k G) ((chain_complex.single₀ (Module k)).obj ((forget₂ (Rep k G) _).obj $ Rep.of representation.trivial)) := (homotopy_equiv.of_iso (comp_forget_augmented_iso k G).symm).trans $ (simplicial_object.augmented.extra_degeneracy.homotopy_equiv (extra_degeneracy_comp_forget_augmented_to_Module k G)).trans (homotopy_equiv.of_iso $ (chain_complex.single₀ (Module.{u} k)).map_iso (@finsupp.linear_equiv.finsupp_unique k k _ _ _ (⊤_ (Type u)) types.terminal_iso.to_equiv.unique).to_Module_iso) /-- The hom of `k`-linear `G`-representations `k[G¹] → k` sending `∑ nᵢgᵢ ↦ ∑ nᵢ`. -/ def ε : Rep.of_mul_action k G (fin 1 → G) ⟶ Rep.of representation.trivial := { hom := finsupp.total _ _ _ (λ f, (1 : k)), comm' := λ g, begin ext, show finsupp.total (fin 1 → G) k k (λ f, (1 : k)) (finsupp.map_domain _ (finsupp.single _ _)) = finsupp.total _ _ _ _ (finsupp.single _ _), simp only [finsupp.map_domain_single, finsupp.total_single], end } /-- The homotopy equivalence of complexes of `k`-modules between the standard resolution of `k` as a trivial `G`-representation, and the complex which is `k` at 0 and 0 everywhere else, acts as `∑ nᵢgᵢ ↦ ∑ nᵢ : k[G¹] → k` at 0. -/ lemma forget₂_to_Module_homotopy_equiv_f_0_eq : (forget₂_to_Module_homotopy_equiv k G).1.f 0 = (forget₂ (Rep k G) _).map (ε k G) := begin show (homotopy_equiv.hom _ ≫ (homotopy_equiv.hom _ ≫ homotopy_equiv.hom _)).f 0 = _, simp only [homological_complex.comp_f], convert category.id_comp _, { dunfold homotopy_equiv.of_iso comp_forget_augmented_iso map_alternating_face_map_complex, simp only [iso.symm_hom, eq_to_iso.inv, homological_complex.eq_to_hom_f, eq_to_hom_refl] }, transitivity ((finsupp.total _ _ _ (λ f, (1 : k))).comp ((Module.free k).map (terminal.from _))), { dsimp, rw [@finsupp.lmap_domain_total (fin 1 → G) k k _ _ _ (⊤_ (Type u)) k _ _ (λ i, (1 : k)) (λ i, (1 : k)) (terminal.from ((classifying_space_universal_cover G).obj (opposite.op (simplex_category.mk 0))).V) linear_map.id (λ i, rfl), linear_map.id_comp], refl }, { congr, { ext, dsimp [homotopy_equiv.of_iso], rw [finsupp.total_single, one_smul, @unique.eq_default _ types.terminal_iso.to_equiv.unique a, finsupp.single_eq_same] }, { exact (@subsingleton.elim _ (@unique.subsingleton _ (limits.unique_to_terminal _)) _ _) }} end lemma d_comp_ε : (group_cohomology.resolution k G).d 1 0 ≫ ε k G = 0 := begin ext1, refine linear_map.ext (λ x, _), have : (forget₂_to_Module k G).d 1 0 ≫ (forget₂ (Rep k G) (Module.{u} k)).map (ε k G) = 0, by rw [←forget₂_to_Module_homotopy_equiv_f_0_eq, ←(forget₂_to_Module_homotopy_equiv k G).1.2 1 0 rfl]; exact comp_zero, exact linear_map.ext_iff.1 this _, end /-- The chain map from the standard resolution of `k` to `k[0]` given by `∑ nᵢgᵢ ↦ ∑ nᵢ` in degree zero. -/ def ε_to_single₀ : group_cohomology.resolution k G ⟶ (chain_complex.single₀ _).obj (Rep.of representation.trivial) := ((group_cohomology.resolution k G).to_single₀_equiv _).symm ⟨ε k G, d_comp_ε k G⟩ lemma ε_to_single₀_comp_eq : ((forget₂ _ (Module.{u} k)).map_homological_complex _).map (ε_to_single₀ k G) ≫ ((chain_complex.single₀_map_homological_complex _).hom.app _) = (forget₂_to_Module_homotopy_equiv k G).hom := begin refine chain_complex.to_single₀_ext _ _ _, dsimp, rw category.comp_id, exact (forget₂_to_Module_homotopy_equiv_f_0_eq k G).symm, end lemma quasi_iso_of_forget₂_ε_to_single₀ : quasi_iso (((forget₂ _ (Module.{u} k)).map_homological_complex _).map (ε_to_single₀ k G)) := begin have h : quasi_iso (forget₂_to_Module_homotopy_equiv k G).hom := homotopy_equiv.to_quasi_iso _, rw ← ε_to_single₀_comp_eq k G at h, haveI := h, exact quasi_iso_of_comp_right _ (((chain_complex.single₀_map_homological_complex _).hom.app _)), end instance : quasi_iso (ε_to_single₀ k G) := (forget₂ _ (Module.{u} k)).quasi_iso_of_map_quasi_iso _ (quasi_iso_of_forget₂_ε_to_single₀ k G) end exactness end group_cohomology.resolution open group_cohomology.resolution variables [group G] /-- The standard projective resolution of `k` as a trivial `k`-linear `G`-representation. -/ def group_cohomology.ProjectiveResolution : ProjectiveResolution (Rep.of (@representation.trivial k G _ _)) := (ε_to_single₀ k G).to_single₀_ProjectiveResolution (X_projective k G) instance : enough_projectives (Rep k G) := Rep.equivalence_Module_monoid_algebra.enough_projectives_iff.2 (Module.Module_enough_projectives.{u}) /-- Given a `k`-linear `G`-representation `V`, `Extⁿ(k, V)` (where `k` is a trivial `k`-linear `G`-representation) is isomorphic to the `n`th cohomology group of `Hom(P, V)`, where `P` is the standard resolution of `k` called `group_cohomology.resolution k G`. -/ def group_cohomology.Ext_iso (V : Rep k G) (n : ℕ) : ((Ext k (Rep k G) n).obj (opposite.op $ Rep.of representation.trivial)).obj V ≅ (((((linear_yoneda k (Rep k G)).obj V).right_op.map_homological_complex _).obj (group_cohomology.resolution k G)).homology n).unop := by let := (((linear_yoneda k (Rep k G)).obj V).right_op.left_derived_obj_iso n (group_cohomology.ProjectiveResolution k G)).unop.symm; exact this
3e51a20540b72f69fbb07c7a225160da4319d445
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/11_Tactic-Style_Proofs.org.5.lean
850830c8abf7ac07c2c7364a467589b8329982e3
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
175
lean
import standard theorem test (p q : Prop) (Hp : p) (Hq : q) : p ∧ q ∧ p := begin apply (and.intro Hp), exact (and.intro Hq Hp) end -- BEGIN reveal test print test -- END
387faf404c8c7fff285ce17c25d51c78328c9722
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/topology/category/Top/default_auto.lean
2f2f6e0830695f99e36676dcac84e29e2dab2026
[]
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
252
lean
import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.topology.category.Top.limits import Mathlib.topology.category.Top.epi_mono import Mathlib.topology.category.Top.open_nhds import Mathlib.PostPort namespace Mathlib end Mathlib
eb0e0938e96925bb0c3023298faee9eab51be90e
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/pp.lean
6090f21b6f92ae3d58d627212cbd5d52df8140e6
[ "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
396
lean
prelude set_option pp.beta false #check λ {A : Type} (B : Type) (a : A) (b : B), a #check λ {A : Type} {B : Type} (a : A) (b : B), a #check λ (A : Type) {B : Type} (a : A) (b : B), a #check λ (A : Type) (B : Type) (a : A) (b : B), a #check λ [A : Type] (B : Type) (a : A) (b : B), a #check λ {{A : Type}} {B : Type} (a : A) (b : B), a #check λ {{A : Type}} {{B : Type}} (a : A) (b : B), a
d09c256f5052294033acaf5211a5ce085a98936b
19cc34575500ee2e3d4586c15544632aa07a8e66
/src/data/mv_polynomial/basic.lean
acda806f9d6934066acfcb881df1fc44d63dabb6
[ "Apache-2.0" ]
permissive
LibertasSpZ/mathlib
b9fcd46625eb940611adb5e719a4b554138dade6
33f7870a49d7cc06d2f3036e22543e6ec5046e68
refs/heads/master
1,672,066,539,347
1,602,429,158,000
1,602,429,158,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
36,558
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, Johan Commelin, Mario Carneiro -/ import data.polynomial.eval /-! # Multivariate polynomials This file defines polynomial rings over a base ring (or even semiring), with variables from a general type `σ` (which could be infinite). ## Important definitions Let `R` be a commutative ring (or a semiring) and let `σ` be an arbitrary type. This file creates the type `mv_polynomial σ R`, which mathematicians might denote $R[X_i : i \in σ]$. It is the type of multivariate (a.k.a. multivariable) polynomials, with variables corresponding to the terms in `σ`, and coefficients in `R`. ### Notation In the definitions below, we use the following notation: + `σ : Type*` (indexing the variables) + `R : Type*` `[comm_semiring R]` (the coefficients) + `s : σ →₀ ℕ`, a function from `σ` to `ℕ` which is zero away from a finite set. This will give rise to a monomial in `mv_polynomial σ R` which mathematicians might call `X^s` + `a : R` + `i : σ`, with corresponding monomial `X i`, often denoted `X_i` by mathematicians + `p : mv_polynomial σ R` ### Definitions * `mv_polynomial σ R` : the type of polynomials with variables of type `σ` and coefficients in the commutative semiring `R` * `monomial s a` : the monomial which mathematically would be denoted `a * X^s` * `C a` : the constant polynomial with value `a` * `X i` : the degree one monomial corresponding to i; mathematically this might be denoted `Xᵢ`. * `coeff s p` : the coefficient of `s` in `p`. * `eval₂ (f : R → S₁) (g : σ → S₁) p` : given a semiring homomorphism from `R` to another semiring `S₁`, and a map `σ → S₁`, evaluates `p` at this valuation, returning a term of type `S₁`. Note that `eval₂` can be made using `eval` and `map` (see below), and it has been suggested that sticking to `eval` and `map` might make the code less brittle. * `eval (g : σ → R) p` : given a map `σ → R`, evaluates `p` at this valuation, returning a term of type `R` * `map (f : R → S₁) p` : returns the multivariate polynomial obtained from `p` by the change of coefficient semiring corresponding to `f` ## Implementation notes Recall that if `Y` has a zero, then `X →₀ Y` is the type of functions from `X` to `Y` with finite support, i.e. such that only finitely many elements of `X` get sent to non-zero terms in `Y`. The definition of `mv_polynomial σ R` is `(σ →₀ ℕ) →₀ R` ; here `σ →₀ ℕ` denotes the space of all monomials in the variables, and the function to `R` sends a monomial to its coefficient in the polynomial being represented. ## Tags polynomial, multivariate polynomial, multivariable polynomial S₁ S₂ S₃ -/ noncomputable theory open_locale classical big_operators open set function finsupp add_monoid_algebra open_locale big_operators universes u v w x variables {R : Type u} {S₁ : Type v} {S₂ : Type w} {S₃ : Type x} /-- Multivariate polynomial, where `σ` is the index set of the variables and `R` is the coefficient ring -/ def mv_polynomial (σ : Type*) (R : Type*) [comm_semiring R] := add_monoid_algebra R (σ →₀ ℕ) namespace mv_polynomial variables {σ : Type*} {a a' a₁ a₂ : R} {e : ℕ} {n m : σ} {s : σ →₀ ℕ} section comm_semiring variables [comm_semiring R] {p q : mv_polynomial σ R} instance decidable_eq_mv_polynomial [decidable_eq σ] [decidable_eq R] : decidable_eq (mv_polynomial σ R) := finsupp.decidable_eq instance : comm_semiring (mv_polynomial σ R) := add_monoid_algebra.comm_semiring instance : inhabited (mv_polynomial σ R) := ⟨0⟩ instance : has_scalar R (mv_polynomial σ R) := add_monoid_algebra.has_scalar instance : semimodule R (mv_polynomial σ R) := add_monoid_algebra.semimodule instance : algebra R (mv_polynomial σ R) := add_monoid_algebra.algebra /-- the coercion turning an `mv_polynomial` into the function which reports the coefficient of a given monomial -/ def coeff_coe_to_fun : has_coe_to_fun (mv_polynomial σ R) := finsupp.has_coe_to_fun local attribute [instance] coeff_coe_to_fun /-- `monomial s a` is the monomial `a * X^s` -/ def monomial (s : σ →₀ ℕ) (a : R) : mv_polynomial σ R := single s a /-- `C a` is the constant polynomial with value `a` -/ def C : R →+* mv_polynomial σ R := { to_fun := monomial 0, map_zero' := by simp [monomial], map_one' := rfl, map_add' := λ a a', single_add, map_mul' := λ a a', by simp [monomial, single_mul_single] } variables (R σ) theorem algebra_map_eq : algebra_map R (mv_polynomial σ R) = C := rfl variables {R σ} /-- `X n` is the degree `1` monomial $X_n$. -/ def X (n : σ) : mv_polynomial σ R := monomial (single n 1) 1 @[simp] lemma C_0 : C 0 = (0 : mv_polynomial σ R) := by simp [C, monomial]; refl @[simp] lemma C_1 : C 1 = (1 : mv_polynomial σ R) := rfl lemma C_mul_monomial : C a * monomial s a' = monomial s (a * a') := by simp [C, monomial, single_mul_single] @[simp] lemma C_add : (C (a + a') : mv_polynomial σ R) = C a + C a' := single_add @[simp] lemma C_mul : (C (a * a') : mv_polynomial σ R) = C a * C a' := C_mul_monomial.symm @[simp] lemma C_pow (a : R) (n : ℕ) : (C (a^n) : mv_polynomial σ R) = (C a)^n := by induction n; simp [pow_succ, *] lemma C_injective (σ : Type*) (R : Type*) [comm_semiring R] : function.injective (C : R → mv_polynomial σ R) := finsupp.single_injective _ @[simp] lemma C_inj {σ : Type*} (R : Type*) [comm_semiring R] (r s : R) : (C r : mv_polynomial σ R) = C s ↔ r = s := (C_injective σ R).eq_iff instance infinite_of_infinite (σ : Type*) (R : Type*) [comm_semiring R] [infinite R] : infinite (mv_polynomial σ R) := infinite.of_injective C (C_injective _ _) instance infinite_of_nonempty (σ : Type*) (R : Type*) [nonempty σ] [comm_semiring R] [nontrivial R] : infinite (mv_polynomial σ R) := infinite.of_injective (λ i : ℕ, monomial (single (classical.arbitrary σ) i) 1) begin intros m n h, have := (single_eq_single_iff _ _ _ _).mp h, simp only [and_true, eq_self_iff_true, or_false, one_ne_zero, and_self, single_eq_single_iff, eq_self_iff_true, true_and] at this, rcases this with (rfl|⟨rfl, rfl⟩); refl end lemma C_eq_coe_nat (n : ℕ) : (C ↑n : mv_polynomial σ R) = n := by induction n; simp [nat.succ_eq_add_one, *] theorem C_mul' : mv_polynomial.C a * p = a • p := begin apply finsupp.induction p, { exact (mul_zero $ mv_polynomial.C a).trans (@smul_zero R (mv_polynomial σ R) _ _ _ a).symm }, intros p b f haf hb0 ih, rw [mul_add, ih, @smul_add R (mv_polynomial σ R) _ _ _ a], congr' 1, rw [add_monoid_algebra.mul_def, finsupp.smul_single], simp only [mv_polynomial.C], dsimp [mv_polynomial.monomial], rw [finsupp.sum_single_index, finsupp.sum_single_index, zero_add], { rw [mul_zero, finsupp.single_zero] }, { rw finsupp.sum_single_index, all_goals { rw [zero_mul, finsupp.single_zero] }, } end lemma smul_eq_C_mul (p : mv_polynomial σ R) (a : R) : a • p = C a * p := C_mul'.symm lemma X_pow_eq_single : X n ^ e = monomial (single n e) (1 : R) := begin induction e, { simp [X], refl }, { simp [pow_succ, e_ih], simp [X, monomial, single_mul_single, nat.succ_eq_add_one, add_comm] } end lemma monomial_add_single : monomial (s + single n e) a = (monomial s a * X n ^ e) := by rw [X_pow_eq_single, monomial, monomial, monomial, single_mul_single]; simp lemma monomial_single_add : monomial (single n e + s) a = (X n ^ e * monomial s a) := by rw [X_pow_eq_single, monomial, monomial, monomial, single_mul_single]; simp lemma single_eq_C_mul_X {s : σ} {a : R} {n : ℕ} : monomial (single s n) a = C a * (X s)^n := by { rw [← zero_add (single s n), monomial_add_single, C], refl } @[simp] lemma monomial_add {s : σ →₀ ℕ} {a b : R} : monomial s a + monomial s b = monomial s (a + b) := by simp [monomial] @[simp] lemma monomial_mul {s s' : σ →₀ ℕ} {a b : R} : monomial s a * monomial s' b = monomial (s + s') (a * b) := by rw [monomial, monomial, monomial, add_monoid_algebra.single_mul_single] @[simp] lemma monomial_zero {s : σ →₀ ℕ}: monomial s (0 : R) = 0 := by rw [monomial, single_zero]; refl @[simp] lemma sum_monomial {A : Type*} [add_comm_monoid A] {u : σ →₀ ℕ} {r : R} {b : (σ →₀ ℕ) → R → A} (w : b u 0 = 0) : sum (monomial u r) b = b u r := sum_single_index w lemma monomial_eq : monomial s a = C a * (s.prod $ λn e, X n ^ e : mv_polynomial σ R) := begin apply @finsupp.induction σ ℕ _ _ s, { simp only [C, prod_zero_index]; exact (mul_one _).symm }, { assume n e s hns he ih, rw [monomial_single_add, ih, prod_add_index, prod_single_index, mul_left_comm], { simp only [pow_zero], }, { intro a, simp only [pow_zero], }, { intros, rw pow_add, }, } end @[recursor 5] lemma induction_on {M : mv_polynomial σ R → Prop} (p : mv_polynomial σ R) (h_C : ∀a, M (C a)) (h_add : ∀p q, M p → M q → M (p + q)) (h_X : ∀p n, M p → M (p * X n)) : M p := have ∀s a, M (monomial s a), begin assume s a, apply @finsupp.induction σ ℕ _ _ s, { show M (monomial 0 a), from h_C a, }, { assume n e p hpn he ih, have : ∀e:ℕ, M (monomial p a * X n ^ e), { intro e, induction e, { simp [ih] }, { simp [ih, pow_succ', (mul_assoc _ _ _).symm, h_X, e_ih] } }, simp [add_comm, monomial_add_single, this] } end, finsupp.induction p (by have : M (C 0) := h_C 0; rwa [C_0] at this) (assume s a p hsp ha hp, h_add _ _ (this s a) hp) theorem induction_on' {P : mv_polynomial σ R → Prop} (p : mv_polynomial σ R) (h1 : ∀ (u : σ →₀ ℕ) (a : R), P (monomial u a)) (h2 : ∀ (p q : mv_polynomial σ R), P p → P q → P (p + q)) : P p := finsupp.induction p (suffices P (monomial 0 0), by rwa monomial_zero at this, show P (monomial 0 0), from h1 0 0) (λ a b f ha hb hPf, h2 _ _ (h1 _ _) hPf) lemma hom_eq_hom [semiring S₂] (f g : mv_polynomial σ R →+* S₂) (hC : ∀a:R, f (C a) = g (C a)) (hX : ∀n:σ, f (X n) = g (X n)) (p : mv_polynomial σ R) : f p = g p := mv_polynomial.induction_on p hC begin assume p q hp hq, rw [is_semiring_hom.map_add f, is_semiring_hom.map_add g, hp, hq] end begin assume p n hp, rw [is_semiring_hom.map_mul f, is_semiring_hom.map_mul g, hp, hX] end lemma is_id (f : mv_polynomial σ R →+* mv_polynomial σ R) (hC : ∀a:R, f (C a) = (C a)) (hX : ∀n:σ, f (X n) = (X n)) (p : mv_polynomial σ R) : f p = p := hom_eq_hom f (ring_hom.id _) hC hX p lemma ring_hom_ext {A : Type*} [comm_semiring A] (f g : mv_polynomial σ R →+* A) (hC : ∀ r, f (C r) = g (C r)) (hX : ∀ i, f (X i) = g (X i)) : f = g := begin ext p : 1, apply mv_polynomial.induction_on' p, { intros m r, rw [monomial_eq, finsupp.prod], simp only [monomial_eq, ring_hom.map_mul, ring_hom.map_prod, ring_hom.map_pow, hC, hX], }, { intros p q hp hq, simp only [ring_hom.map_add, hp, hq] } end lemma alg_hom_ext {A : Type*} [comm_semiring A] [algebra R A] (f g : mv_polynomial σ R →ₐ[R] A) (hf : ∀ i : σ, f (X i) = g (X i)) : f = g := begin apply alg_hom.coe_ring_hom_injective, apply ring_hom_ext, { intro r, calc f (C r) = algebra_map R A r : f.commutes r ... = g (C r) : (g.commutes r).symm }, { simpa only [hf] }, end @[simp] lemma alg_hom_C (f : mv_polynomial σ R →ₐ[R] mv_polynomial σ R) (r : R) : f (C r) = C r := f.commutes r section coeff section -- While setting up `coeff`, we make `mv_polynomial` reducible so we can treat it as a function. local attribute [reducible] mv_polynomial /-- The coefficient of the monomial `m` in the multi-variable polynomial `p`. -/ def coeff (m : σ →₀ ℕ) (p : mv_polynomial σ R) : R := p m end lemma ext (p q : mv_polynomial σ R) : (∀ m, coeff m p = coeff m q) → p = q := ext lemma ext_iff (p q : mv_polynomial σ R) : p = q ↔ (∀ m, coeff m p = coeff m q) := ⟨ λ h m, by rw h, ext p q⟩ @[simp] lemma coeff_add (m : σ →₀ ℕ) (p q : mv_polynomial σ R) : coeff m (p + q) = coeff m p + coeff m q := add_apply @[simp] lemma coeff_zero (m : σ →₀ ℕ) : coeff m (0 : mv_polynomial σ R) = 0 := rfl @[simp] lemma coeff_zero_X (i : σ) : coeff 0 (X i : mv_polynomial σ R) = 0 := single_eq_of_ne (λ h, by cases single_eq_zero.1 h) instance coeff.is_add_monoid_hom (m : σ →₀ ℕ) : is_add_monoid_hom (coeff m : mv_polynomial σ R → R) := { map_add := coeff_add m, map_zero := coeff_zero m } lemma coeff_sum {X : Type*} (s : finset X) (f : X → mv_polynomial σ R) (m : σ →₀ ℕ) : coeff m (∑ x in s, f x) = ∑ x in s, coeff m (f x) := (s.sum_hom _).symm lemma monic_monomial_eq (m) : monomial m (1:R) = (m.prod $ λn e, X n ^ e : mv_polynomial σ R) := by simp [monomial_eq] @[simp] lemma coeff_monomial (m n) (a) : coeff m (monomial n a : mv_polynomial σ R) = if n = m then a else 0 := by convert single_apply @[simp] lemma coeff_C (m) (a) : coeff m (C a : mv_polynomial σ R) = if 0 = m then a else 0 := by convert single_apply lemma coeff_X_pow (i : σ) (m) (k : ℕ) : coeff m (X i ^ k : mv_polynomial σ R) = if single i k = m then 1 else 0 := begin have := coeff_monomial m (finsupp.single i k) (1:R), rwa [@monomial_eq _ _ (1:R) (finsupp.single i k) _, C_1, one_mul, finsupp.prod_single_index] at this, exact pow_zero _ end lemma coeff_X' (i : σ) (m) : coeff m (X i : mv_polynomial σ R) = if single i 1 = m then 1 else 0 := by rw [← coeff_X_pow, pow_one] @[simp] lemma coeff_X (i : σ) : coeff (single i 1) (X i : mv_polynomial σ R) = 1 := by rw [coeff_X', if_pos rfl] @[simp] lemma coeff_C_mul (m) (a : R) (p : mv_polynomial σ R) : coeff m (C a * p) = a * coeff m p := begin rw [mul_def], simp only [C, monomial], dsimp, rw [monomial], rw sum_single_index, { simp only [zero_add], convert sum_apply, simp only [single_apply, finsupp.sum], rw finset.sum_eq_single m, { rw if_pos rfl, refl }, { intros m' hm' H, apply if_neg, exact H }, { intros hm, rw if_pos rfl, rw not_mem_support_iff at hm, simp [hm] } }, simp only [zero_mul, single_zero, zero_add, sum_zero], end lemma coeff_mul (p q : mv_polynomial σ R) (n : σ →₀ ℕ) : coeff n (p * q) = ∑ x in (antidiagonal n).support, coeff x.1 p * coeff x.2 q := begin rw mul_def, -- We need to manipulate both sides into a shape to which we can apply `finset.sum_bij_ne_zero`, -- so we need to turn both sides into a sum over a sigma/product. have := @finset.sum_sigma (σ →₀ ℕ) R _ _ p.support (λ _, q.support) (λ x, if (x.1 + x.2 = n) then coeff x.1 p * coeff x.2 q else 0), convert this.symm using 1; clear this, { rw [coeff], iterate 2 { rw sum_apply, apply finset.sum_congr rfl, intros, dsimp only }, convert single_apply }, symmetry, -- We are now ready to show that both sums are equal using `finset.sum_bij_ne_zero`. apply finset.sum_bij_ne_zero (λ (x : Σ (a : σ →₀ ℕ), σ →₀ ℕ) _ _, (x.1, x.2)), { intros x hx hx', simp only [mem_antidiagonal_support, eq_self_iff_true, if_false, forall_true_iff], contrapose! hx', rw [if_neg hx'] }, { rintros ⟨i, j⟩ ⟨k, l⟩ hij hij' hkl hkl', simpa only [and_imp, prod.mk.inj_iff, heq_iff_eq] using and.intro }, { rintros ⟨i, j⟩ hij hij', refine ⟨⟨i, j⟩, _, _⟩, { simp only [mem_support_iff, finset.mem_sigma], contrapose! hij', exact mul_eq_zero_of_ne_zero_imp_eq_zero hij' }, { rw [mem_antidiagonal_support] at hij, simp only [exists_prop, and_true, eq_self_iff_true, ne.def, if_pos hij, hij', not_false_iff] } }, { intros x hx hx', simp only [ne.def] at hx' ⊢, split_ifs with H, { refl }, { rw if_neg H at hx', contradiction } } end @[simp] lemma coeff_mul_X (m) (s : σ) (p : mv_polynomial σ R) : coeff (m + single s 1) (p * X s) = coeff m p := begin have : (m, single s 1) ∈ (m + single s 1).antidiagonal.support := mem_antidiagonal_support.2 rfl, rw [coeff_mul, ← finset.insert_erase this, finset.sum_insert (finset.not_mem_erase _ _), finset.sum_eq_zero, add_zero, coeff_X, mul_one], rintros ⟨i,j⟩ hij, rw [finset.mem_erase, mem_antidiagonal_support] at hij, by_cases H : single s 1 = j, { subst j, simpa using hij }, { rw [coeff_X', if_neg H, mul_zero] }, end lemma coeff_mul_X' (m) (s : σ) (p : mv_polynomial σ R) : coeff m (p * X s) = if s ∈ m.support then coeff (m - single s 1) p else 0 := begin split_ifs with h h, { conv_rhs {rw ← coeff_mul_X _ s}, congr' with t, by_cases hj : s = t, { subst t, simp only [nat_sub_apply, add_apply, single_eq_same], refine (nat.sub_add_cancel $ nat.pos_of_ne_zero _).symm, rwa mem_support_iff at h }, { simp [single_eq_of_ne hj] } }, { delta coeff, rw ← not_mem_support_iff, intro hm, apply h, have H := support_mul _ _ hm, simp only [finset.mem_bind] at H, rcases H with ⟨j, hj, i', hi', H⟩, delta X monomial at hi', rw mem_support_single at hi', cases hi', subst i', erw finset.mem_singleton at H, subst m, rw [mem_support_iff, add_apply, single_apply, if_pos rfl], intro H, rw [_root_.add_eq_zero_iff] at H, exact one_ne_zero H.2 } end lemma eq_zero_iff {p : mv_polynomial σ R} : p = 0 ↔ ∀ d, coeff d p = 0 := by { rw ext_iff, simp only [coeff_zero], } lemma ne_zero_iff {p : mv_polynomial σ R} : p ≠ 0 ↔ ∃ d, coeff d p ≠ 0 := by { rw [ne.def, eq_zero_iff], push_neg, } lemma exists_coeff_ne_zero {p : mv_polynomial σ R} (h : p ≠ 0) : ∃ d, coeff d p ≠ 0 := ne_zero_iff.mp h lemma C_dvd_iff_dvd_coeff (r : R) (φ : mv_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 ψ : mv_polynomial σ R := ∑ i in φ.support, monomial i (c' i), use ψ, apply mv_polynomial.ext, intro i, simp only [coeff_C_mul, coeff_sum, coeff_monomial, finset.sum_ite_eq', c'], split_ifs with hi hi, { rw hc }, { rw finsupp.not_mem_support_iff at hi, rwa mul_zero } }, end end coeff section constant_coeff /-- `constant_coeff p` returns the constant term of the polynomial `p`, defined as `coeff 0 p`. This is a ring homomorphism. -/ def constant_coeff : mv_polynomial σ R →+* R := { to_fun := coeff 0, map_one' := by simp [coeff, add_monoid_algebra.one_def], map_mul' := by simp [coeff_mul, finsupp.support_single_ne_zero], map_zero' := coeff_zero _, map_add' := coeff_add _ } lemma constant_coeff_eq : (constant_coeff : mv_polynomial σ R → R) = coeff 0 := rfl @[simp] lemma constant_coeff_C (r : R) : constant_coeff (C r : mv_polynomial σ R) = r := by simp [constant_coeff_eq] @[simp] lemma constant_coeff_X (i : σ) : constant_coeff (X i : mv_polynomial σ R) = 0 := by simp [constant_coeff_eq] lemma constant_coeff_monomial (d : σ →₀ ℕ) (r : R) : constant_coeff (monomial d r) = if d = 0 then r else 0 := by rw [constant_coeff_eq, coeff_monomial] variables (σ R) @[simp] lemma constant_coeff_comp_C : constant_coeff.comp (C : R →+* mv_polynomial σ R) = ring_hom.id R := by { ext, apply constant_coeff_C } @[simp] lemma constant_coeff_comp_algebra_map : constant_coeff.comp (algebra_map R (mv_polynomial σ R)) = ring_hom.id R := constant_coeff_comp_C _ _ end constant_coeff section as_sum @[simp] lemma support_sum_monomial_coeff (p : mv_polynomial σ R) : ∑ v in p.support, monomial v (coeff v p) = p := finsupp.sum_single p lemma as_sum (p : mv_polynomial σ R) : p = ∑ v in p.support, monomial v (coeff v p) := (support_sum_monomial_coeff p).symm end as_sum section eval₂ variables [comm_semiring S₁] variables (f : R →+* S₁) (g : σ → S₁) /-- Evaluate a polynomial `p` given a valuation `g` of all the variables and a ring hom `f` from the scalar ring to the target -/ def eval₂ (p : mv_polynomial σ R) : S₁ := p.sum (λs a, f a * s.prod (λn e, g n ^ e)) lemma eval₂_eq (g : R →+* S₁) (x : σ → S₁) (f : mv_polynomial σ R) : f.eval₂ g x = ∑ d in f.support, g (f.coeff d) * ∏ i in d.support, x i ^ d i := rfl lemma eval₂_eq' [fintype σ] (g : R →+* S₁) (x : σ → S₁) (f : mv_polynomial σ R) : f.eval₂ g x = ∑ d in f.support, g (f.coeff d) * ∏ i, x i ^ d i := by { simp only [eval₂_eq, ← finsupp.prod_pow], refl } @[simp] lemma eval₂_zero : (0 : mv_polynomial σ R).eval₂ f g = 0 := finsupp.sum_zero_index section @[simp] lemma eval₂_add : (p + q).eval₂ f g = p.eval₂ f g + q.eval₂ f g := finsupp.sum_add_index (by simp [is_semiring_hom.map_zero f]) (by simp [add_mul, is_semiring_hom.map_add f]) @[simp] lemma eval₂_monomial : (monomial s a).eval₂ f g = f a * s.prod (λn e, g n ^ e) := finsupp.sum_single_index (by simp [is_semiring_hom.map_zero f]) @[simp] lemma eval₂_C (a) : (C a).eval₂ f g = f a := by simp [eval₂_monomial, C, prod_zero_index] @[simp] lemma eval₂_one : (1 : mv_polynomial σ R).eval₂ f g = 1 := (eval₂_C _ _ _).trans (is_semiring_hom.map_one f) @[simp] lemma eval₂_X (n) : (X n).eval₂ f g = g n := by simp [eval₂_monomial, is_semiring_hom.map_one f, X, prod_single_index, pow_one] lemma eval₂_mul_monomial : ∀{s a}, (p * monomial s a).eval₂ f g = p.eval₂ f g * f a * s.prod (λn e, g n ^ e) := begin apply mv_polynomial.induction_on p, { assume a' s a, simp [C_mul_monomial, eval₂_monomial, is_semiring_hom.map_mul f] }, { assume p q ih_p ih_q, simp [add_mul, eval₂_add, ih_p, ih_q] }, { assume p n ih s a, from calc (p * X n * monomial s a).eval₂ f g = (p * monomial (single n 1 + s) a).eval₂ f g : by simp [monomial_single_add, -add_comm, pow_one, mul_assoc] ... = (p * monomial (single n 1) 1).eval₂ f g * f a * s.prod (λn e, g n ^ e) : by simp [ih, prod_single_index, prod_add_index, pow_one, pow_add, mul_assoc, mul_left_comm, is_semiring_hom.map_one f, -add_comm] } end @[simp] lemma eval₂_mul : ∀{p}, (p * q).eval₂ f g = p.eval₂ f g * q.eval₂ f g := begin apply mv_polynomial.induction_on q, { simp [C, eval₂_monomial, eval₂_mul_monomial, prod_zero_index] }, { simp [mul_add, eval₂_add] {contextual := tt} }, { simp [X, eval₂_monomial, eval₂_mul_monomial, (mul_assoc _ _ _).symm] { contextual := tt} } end @[simp] lemma eval₂_pow {p:mv_polynomial σ R} : ∀{n:ℕ}, (p ^ n).eval₂ f g = (p.eval₂ f g)^n | 0 := eval₂_one _ _ | (n + 1) := by rw [pow_add, pow_one, pow_add, pow_one, eval₂_mul, eval₂_pow] instance eval₂.is_semiring_hom : is_semiring_hom (eval₂ f g) := { map_zero := eval₂_zero _ _, map_one := eval₂_one _ _, map_add := λ p q, eval₂_add _ _, map_mul := λ p q, eval₂_mul _ _ } /-- `mv_polynomial.eval₂` as a `ring_hom`. -/ def eval₂_hom (f : R →+* S₁) (g : σ → S₁) : mv_polynomial σ R →+* S₁ := ring_hom.of (eval₂ f g) @[simp] lemma coe_eval₂_hom (f : R →+* S₁) (g : σ → S₁) : ⇑(eval₂_hom f g) = eval₂ f g := rfl lemma eval₂_hom_congr {f₁ f₂ : R →+* S₁} {g₁ g₂ : σ → S₁} {p₁ p₂ : mv_polynomial σ R} : f₁ = f₂ → g₁ = g₂ → p₁ = p₂ → eval₂_hom f₁ g₁ p₁ = eval₂_hom f₂ g₂ p₂ := by rintros rfl rfl rfl; refl end @[simp] lemma eval₂_hom_C (f : R →+* S₁) (g : σ → S₁) (r : R) : eval₂_hom f g (C r) = f r := eval₂_C f g r @[simp] lemma eval₂_hom_X' (f : R →+* S₁) (g : σ → S₁) (i : σ) : eval₂_hom f g (X i) = g i := eval₂_X f g i @[simp] lemma comp_eval₂_hom [comm_semiring S₂] (f : R →+* S₁) (g : σ → S₁) (φ : S₁ →+* S₂) : φ.comp (eval₂_hom f g) = (eval₂_hom (φ.comp f) (λ i, φ (g i))) := begin apply mv_polynomial.ring_hom_ext, { intro r, rw [ring_hom.comp_apply, eval₂_hom_C, eval₂_hom_C, ring_hom.comp_apply] }, { intro i, rw [ring_hom.comp_apply, eval₂_hom_X', eval₂_hom_X'] } end lemma map_eval₂_hom [comm_semiring S₂] (f : R →+* S₁) (g : σ → S₁) (φ : S₁ →+* S₂) (p : mv_polynomial σ R) : φ (eval₂_hom f g p) = (eval₂_hom (φ.comp f) (λ i, φ (g i)) p) := by { rw ← comp_eval₂_hom, refl } lemma eval₂_hom_monomial (f : R →+* S₁) (g : σ → S₁) (d : σ →₀ ℕ) (r : R) : eval₂_hom f g (monomial d r) = f r * d.prod (λ i k, g i ^ k) := by simp only [monomial_eq, ring_hom.map_mul, eval₂_hom_C, finsupp.prod, ring_hom.map_prod, ring_hom.map_pow, eval₂_hom_X'] section local attribute [instance, priority 10] is_semiring_hom.comp lemma eval₂_comp_left {S₂} [comm_semiring S₂] (k : S₁ →+* S₂) (f : R →+* S₁) (g : σ → S₁) (p) : k (eval₂ f g p) = eval₂ (k.comp f) (k ∘ g) p := by apply mv_polynomial.induction_on p; simp [ eval₂_add, k.map_add, eval₂_mul, k.map_mul] {contextual := tt} end @[simp] lemma eval₂_eta (p : mv_polynomial σ R) : eval₂ C X p = p := by apply mv_polynomial.induction_on p; simp [eval₂_add, eval₂_mul] {contextual := tt} lemma eval₂_congr (g₁ g₂ : σ → S₁) (h : ∀ {i : σ} {c : σ →₀ ℕ}, i ∈ c.support → coeff c p ≠ 0 → g₁ i = g₂ i) : p.eval₂ f g₁ = p.eval₂ f g₂ := begin apply finset.sum_congr rfl, intros c hc, dsimp, congr' 1, apply finset.prod_congr rfl, intros i hi, dsimp, congr' 1, apply h hi, rwa finsupp.mem_support_iff at hc end @[simp] lemma eval₂_prod (s : finset S₂) (p : S₂ → mv_polynomial σ R) : eval₂ f g (∏ x in s, p x) = ∏ x in s, eval₂ f g (p x) := (s.prod_hom _).symm @[simp] lemma eval₂_sum (s : finset S₂) (p : S₂ → mv_polynomial σ R) : eval₂ f g (∑ x in s, p x) = ∑ x in s, eval₂ f g (p x) := (s.sum_hom _).symm attribute [to_additive] eval₂_prod lemma eval₂_assoc (q : S₂ → mv_polynomial σ R) (p : mv_polynomial S₂ R) : eval₂ f (λ t, eval₂ f g (q t)) p = eval₂ f g (eval₂ C q p) := begin show _ = eval₂_hom f g (eval₂ C q p), rw eval₂_comp_left (eval₂_hom f g), congr' with a, simp, end end eval₂ section eval variables {f : σ → R} /-- Evaluate a polynomial `p` given a valuation `f` of all the variables -/ def eval (f : σ → R) : mv_polynomial σ R →+* R := eval₂_hom (ring_hom.id _) f lemma eval_eq (x : σ → R) (f : mv_polynomial σ R) : eval x f = ∑ d in f.support, f.coeff d * ∏ i in d.support, x i ^ d i := rfl lemma eval_eq' [fintype σ] (x : σ → R) (f : mv_polynomial σ R) : eval x f = ∑ d in f.support, f.coeff d * ∏ i, x i ^ d i := eval₂_eq' (ring_hom.id R) x f lemma eval_monomial : eval f (monomial s a) = a * s.prod (λn e, f n ^ e) := eval₂_monomial _ _ @[simp] lemma eval_C : ∀ a, eval f (C a) = a := eval₂_C _ _ @[simp] lemma eval_X : ∀ n, eval f (X n) = f n := eval₂_X _ _ @[simp] lemma smul_eval (x) (p : mv_polynomial σ R) (s) : eval x (s • p) = s * eval x p := by rw [smul_eq_C_mul, (eval x).map_mul, eval_C] lemma eval_sum {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ R) (g : σ → R) : eval g (∑ i in s, f i) = ∑ i in s, eval g (f i) := (eval g).map_sum _ _ @[to_additive] lemma eval_prod {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ R) (g : σ → R) : eval g (∏ i in s, f i) = ∏ i in s, eval g (f i) := (eval g).map_prod _ _ theorem eval_assoc {τ} (f : σ → mv_polynomial τ R) (g : τ → R) (p : mv_polynomial σ R) : eval (eval g ∘ f) p = eval g (eval₂ C f p) := begin rw eval₂_comp_left (eval g), unfold eval, simp only [coe_eval₂_hom], congr' with a, simp end end eval section map variables [comm_semiring S₁] variables (f : R →+* S₁) /-- `map f p` maps a polynomial `p` across a ring hom `f` -/ def map : mv_polynomial σ R →+* mv_polynomial σ S₁ := eval₂_hom (C.comp f) X @[simp] theorem map_monomial (s : σ →₀ ℕ) (a : R) : map f (monomial s a) = monomial s (f a) := (eval₂_monomial _ _).trans monomial_eq.symm @[simp] theorem map_C : ∀ (a : R), map f (C a : mv_polynomial σ R) = C (f a) := map_monomial _ _ @[simp] theorem map_X : ∀ (n : σ), map f (X n : mv_polynomial σ R) = X n := eval₂_X _ _ theorem map_id : ∀ (p : mv_polynomial σ R), map (ring_hom.id R) p = p := eval₂_eta theorem map_map [comm_semiring S₂] (g : S₁ →+* S₂) (p : mv_polynomial σ R) : map g (map f p) = map (g.comp f) p := (eval₂_comp_left (map g) (C.comp f) X p).trans $ begin congr, { ext1 a, simp only [map_C, comp_app, ring_hom.coe_comp], }, { ext1 n, simp only [map_X, comp_app], } end theorem eval₂_eq_eval_map (g : σ → S₁) (p : mv_polynomial σ R) : p.eval₂ f g = eval g (map f p) := begin unfold map eval, simp only [coe_eval₂_hom], have h := eval₂_comp_left (eval₂_hom _ g), dsimp at h, rw h, congr, { ext1 a, simp only [coe_eval₂_hom, ring_hom.id_apply, comp_app, eval₂_C, ring_hom.coe_comp], }, { ext1 n, simp only [comp_app, eval₂_X], }, end lemma eval₂_comp_right {S₂} [comm_semiring S₂] (k : S₁ →+* S₂) (f : R →+* S₁) (g : σ → S₁) (p) : k (eval₂ f g p) = eval₂ k (k ∘ g) (map f p) := begin apply mv_polynomial.induction_on p, { intro r, rw [eval₂_C, map_C, eval₂_C] }, { intros p q hp hq, rw [eval₂_add, k.map_add, (map f).map_add, eval₂_add, hp, hq] }, { intros p s hp, rw [eval₂_mul, k.map_mul, (map f).map_mul, eval₂_mul, map_X, hp, eval₂_X, eval₂_X] } end lemma map_eval₂ (f : R →+* S₁) (g : S₂ → mv_polynomial S₃ R) (p : mv_polynomial S₂ R) : map f (eval₂ C g p) = eval₂ C (map f ∘ g) (map f p) := begin apply mv_polynomial.induction_on p, { intro r, rw [eval₂_C, map_C, map_C, eval₂_C] }, { intros p q hp hq, rw [eval₂_add, (map f).map_add, hp, hq, (map f).map_add, eval₂_add] }, { intros p s hp, rw [eval₂_mul, (map f).map_mul, hp, (map f).map_mul, map_X, eval₂_mul, eval₂_X, eval₂_X] } end lemma coeff_map (p : mv_polynomial σ R) : ∀ (m : σ →₀ ℕ), coeff m (map f p) = f (coeff m p) := begin apply mv_polynomial.induction_on p; clear p, { intros r m, rw [map_C], simp only [coeff_C], split_ifs, {refl}, rw f.map_zero }, { intros p q hp hq m, simp only [hp, hq, (map f).map_add, coeff_add], rw f.map_add }, { intros p i hp m, simp only [hp, (map f).map_mul, map_X], simp only [hp, mem_support_iff, coeff_mul_X'], split_ifs, {refl}, rw is_semiring_hom.map_zero f } end lemma map_injective (hf : function.injective f) : function.injective (map f : mv_polynomial σ R → mv_polynomial σ S₁) := begin intros p q h, simp only [ext_iff, coeff_map] at h ⊢, intro m, exact hf (h m), end @[simp] lemma eval_map (f : R →+* S₁) (g : σ → S₁) (p : mv_polynomial σ R) : eval g (map f p) = eval₂ f g p := by { apply mv_polynomial.induction_on p; { simp { contextual := tt } } } @[simp] lemma eval₂_map [comm_semiring S₂] (f : R →+* S₁) (g : σ → S₂) (φ : S₁ →+* S₂) (p : mv_polynomial σ R) : eval₂ φ g (map f p) = eval₂ (φ.comp f) g p := by { rw [← eval_map, ← eval_map, map_map], } @[simp] lemma eval₂_hom_map_hom [comm_semiring S₂] (f : R →+* S₁) (g : σ → S₂) (φ : S₁ →+* S₂) (p : mv_polynomial σ R) : eval₂_hom φ g (map f p) = eval₂_hom (φ.comp f) g p := eval₂_map f g φ p @[simp] lemma constant_coeff_map (f : R →+* S₁) (φ : mv_polynomial σ R) : constant_coeff (mv_polynomial.map f φ) = f (constant_coeff φ) := coeff_map f φ 0 lemma constant_coeff_comp_map (f : R →+* S₁) : (constant_coeff : mv_polynomial σ S₁ →+* S₁).comp (mv_polynomial.map f) = f.comp (constant_coeff) := by { ext, apply constant_coeff_map } lemma support_map_subset (p : mv_polynomial σ R) : (map f p).support ⊆ p.support := begin intro x, simp only [finsupp.mem_support_iff], contrapose!, change p.coeff x = 0 → (map f p).coeff x = 0, rw coeff_map, intro hx, rw hx, exact ring_hom.map_zero f end lemma support_map_of_injective (p : mv_polynomial σ R) {f : R →+* S₁} (hf : injective f) : (map f p).support = p.support := begin apply finset.subset.antisymm, { exact mv_polynomial.support_map_subset _ _ }, intros x hx, rw finsupp.mem_support_iff, contrapose! hx, simp only [not_not, finsupp.mem_support_iff], change (map f p).coeff x = 0 at hx, rw [coeff_map, ← f.map_zero] at hx, exact hf hx end lemma C_dvd_iff_map_hom_eq_zero (q : R →+* S₁) (r : R) (hr : ∀ r' : R, q r' = 0 ↔ r ∣ r') (φ : mv_polynomial σ R) : C r ∣ φ ↔ map q φ = 0 := begin rw [C_dvd_iff_dvd_coeff, mv_polynomial.ext_iff], simp only [coeff_map, ring_hom.coe_of, coeff_zero, hr], end lemma map_map_range_eq_iff (f : R →+* S₁) (g : S₁ → R) (hg : g 0 = 0) (φ : mv_polynomial σ S₁) : map f (finsupp.map_range g hg φ) = φ ↔ ∀ d, f (g (coeff d φ)) = coeff d φ := begin rw mv_polynomial.ext_iff, apply forall_congr, intro m, rw [coeff_map], apply eq_iff_eq_cancel_right.mpr, refl end end map section aeval /-! ### The algebra of multivariate polynomials -/ variables (f : σ → S₁) variables [comm_semiring S₁] [algebra R S₁] [comm_semiring S₂] /-- A map `σ → S₁` where `S₁` is an algebra over `R` generates an `R`-algebra homomorphism from multivariate polynomials over `σ` to `S₁`. -/ def aeval : mv_polynomial σ R →ₐ[R] S₁ := { commutes' := λ r, eval₂_C _ _ _ .. eval₂_hom (algebra_map R S₁) f } theorem aeval_def (p : mv_polynomial σ R) : aeval f p = eval₂ (algebra_map R S₁) f p := rfl lemma aeval_eq_eval₂_hom (p : mv_polynomial σ R) : aeval f p = eval₂_hom (algebra_map R S₁) f p := rfl @[simp] lemma aeval_X (s : σ) : aeval f (X s : mv_polynomial _ R) = f s := eval₂_X _ _ _ @[simp] lemma aeval_C (r : R) : aeval f (C r) = algebra_map R S₁ r := eval₂_C _ _ _ theorem eval_unique (φ : mv_polynomial σ R →ₐ[R] S₁) : φ = aeval (φ ∘ X) := begin ext p, apply mv_polynomial.induction_on p, { intro r, rw aeval_C, exact φ.commutes r }, { intros f g ih1 ih2, rw [φ.map_add, ih1, ih2, alg_hom.map_add] }, { intros p j ih, rw [φ.map_mul, alg_hom.map_mul, aeval_X, ih] } end lemma comp_aeval {B : Type*} [comm_semiring B] [algebra R B] (φ : S₁ →ₐ[R] B) : φ.comp (aeval f) = (aeval (λ i, φ (f i))) := begin apply mv_polynomial.alg_hom_ext, intros i, rw [alg_hom.comp_apply, aeval_X, aeval_X], end @[simp] lemma map_aeval {B : Type*} [comm_semiring B] (g : σ → S₁) (φ : S₁ →+* B) (p : mv_polynomial σ R) : φ (aeval g p) = (eval₂_hom (φ.comp (algebra_map R S₁)) (λ i, φ (g i)) p) := by { rw ← comp_eval₂_hom, refl } @[simp] lemma aeval_zero (p : mv_polynomial σ R) : aeval (0 : σ → S₁) p = algebra_map _ _ (constant_coeff p) := begin apply mv_polynomial.induction_on p, { simp only [aeval_C, forall_const, if_true, constant_coeff_C, eq_self_iff_true] }, { intros, simp only [*, alg_hom.map_add, ring_hom.map_add, coeff_add] }, { intros, simp only [ring_hom.map_mul, constant_coeff_X, pi.zero_apply, ring_hom.map_zero, eq_self_iff_true, mem_support_iff, not_true, aeval_X, if_false, ne.def, mul_zero, alg_hom.map_mul, zero_apply] } end @[simp] lemma aeval_zero' (p : mv_polynomial σ R) : aeval (λ _, 0 : σ → S₁) p = algebra_map _ _ (constant_coeff p) := aeval_zero p lemma aeval_monomial (g : σ → S₁) (d : σ →₀ ℕ) (r : R) : aeval g (monomial d r) = algebra_map _ _ r * d.prod (λ i k, g i ^ k) := eval₂_hom_monomial _ _ _ _ lemma eval₂_hom_eq_zero (f : R →+* S₂) (g : σ → S₂) (φ : mv_polynomial σ R) (h : ∀ d, φ.coeff d ≠ 0 → ∃ i ∈ d.support, g i = 0) : eval₂_hom f g φ = 0 := begin rw [φ.as_sum, ring_hom.map_sum, finset.sum_eq_zero], intros d hd, obtain ⟨i, hi, hgi⟩ : ∃ i ∈ d.support, g i = 0 := h d (finsupp.mem_support_iff.mp hd), rw [eval₂_hom_monomial, finsupp.prod, finset.prod_eq_zero hi, mul_zero], rw [hgi, zero_pow], rwa [nat.pos_iff_ne_zero, ← finsupp.mem_support_iff] end lemma aeval_eq_zero [algebra R S₂] (f : σ → S₂) (φ : mv_polynomial σ R) (h : ∀ d, φ.coeff d ≠ 0 → ∃ i ∈ d.support, f i = 0) : aeval f φ = 0 := eval₂_hom_eq_zero _ _ _ h end aeval end comm_semiring end mv_polynomial
82dcf661810278a18edbf15dede4ab7b12137467
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/calculus/fderiv/star.lean
4eaf7d6b21c338029233a5440b004568503204e5
[ "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
4,009
lean
/- Copyright (c) 2023 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import analysis.calculus.fderiv.linear import analysis.calculus.fderiv.comp import analysis.calculus.fderiv.equiv import analysis.normed_space.star.basic /-! # Star operations on derivatives > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. For detailed documentation of the Fréchet derivative, see the module docstring of `analysis/calculus/fderiv/basic.lean`. This file contains the usual formulas (and existence assertions) for the derivative of the star operation. Note that these only apply when the field that the derivative is respect to has a trivial star operation; which as should be expected rules out `𝕜 = ℂ`. -/ open_locale classical variables {𝕜 : Type*} [nontrivially_normed_field 𝕜] [star_ring 𝕜] [has_trivial_star 𝕜] variables {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] variables {F : Type*} [normed_add_comm_group F] [star_add_monoid F] [normed_space 𝕜 F] [star_module 𝕜 F] [has_continuous_star F] variables {f : E → F} variables {f' : E →L[𝕜] F} variables (e : E →L[𝕜] F) variables {x : E} variables {s : set E} variables {L : filter E} theorem has_strict_fderiv_at.star (h : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (λ x, star (f x)) (((starL' 𝕜 : F ≃L[𝕜] F) : F →L[𝕜] F) ∘L f') x := (starL' 𝕜 : F ≃L[𝕜] F).to_continuous_linear_map.has_strict_fderiv_at.comp x h theorem has_fderiv_at_filter.star (h : has_fderiv_at_filter f f' x L) : has_fderiv_at_filter (λ x, star (f x)) (((starL' 𝕜 : F ≃L[𝕜] F) : F →L[𝕜] F) ∘L f') x L := (starL' 𝕜 : F ≃L[𝕜] F).to_continuous_linear_map.has_fderiv_at_filter.comp x h filter.tendsto_map theorem has_fderiv_within_at.star (h : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ x, star (f x)) (((starL' 𝕜 : F ≃L[𝕜] F) : F →L[𝕜] F) ∘L f') s x := h.star theorem has_fderiv_at.star (h : has_fderiv_at f f' x) : has_fderiv_at (λ x, star (f x)) (((starL' 𝕜 : F ≃L[𝕜] F) : F →L[𝕜] F) ∘L f') x := h.star lemma differentiable_within_at.star (h : differentiable_within_at 𝕜 f s x) : differentiable_within_at 𝕜 (λ y, star (f y)) s x := h.has_fderiv_within_at.star.differentiable_within_at @[simp] lemma differentiable_within_at_star_iff : differentiable_within_at 𝕜 (λ y, star (f y)) s x ↔ differentiable_within_at 𝕜 f s x := (starL' 𝕜 : F ≃L[𝕜] F).comp_differentiable_within_at_iff lemma differentiable_at.star (h : differentiable_at 𝕜 f x) : differentiable_at 𝕜 (λ y, star (f y)) x := h.has_fderiv_at.star.differentiable_at @[simp] lemma differentiable_at_star_iff : differentiable_at 𝕜 (λ y, star (f y)) x ↔ differentiable_at 𝕜 f x := (starL' 𝕜 : F ≃L[𝕜] F).comp_differentiable_at_iff lemma differentiable_on.star (h : differentiable_on 𝕜 f s) : differentiable_on 𝕜 (λ y, star (f y)) s := λ x hx, (h x hx).star @[simp] lemma differentiable_on_star_iff : differentiable_on 𝕜 (λ y, star (f y)) s ↔ differentiable_on 𝕜 f s := (starL' 𝕜 : F ≃L[𝕜] F).comp_differentiable_on_iff lemma differentiable.star (h : differentiable 𝕜 f) : differentiable 𝕜 (λ y, star (f y)) := λx, (h x).star @[simp] lemma differentiable_star_iff : differentiable 𝕜 (λ y, star (f y)) ↔ differentiable 𝕜 f := (starL' 𝕜 : F ≃L[𝕜] F).comp_differentiable_iff lemma fderiv_within_star (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λ y, star (f y)) s x = ((starL' 𝕜 : F ≃L[𝕜] F) : F →L[𝕜] F) ∘L fderiv_within 𝕜 f s x := (starL' 𝕜 : F ≃L[𝕜] F).comp_fderiv_within hxs @[simp] lemma fderiv_star : fderiv 𝕜 (λ y, star (f y)) x = ((starL' 𝕜 : F ≃L[𝕜] F) : F →L[𝕜] F) ∘L fderiv 𝕜 f x := (starL' 𝕜 : F ≃L[𝕜] F).comp_fderiv
91eddd64f4654ef706fce57dcd5f24e6577e2b52
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/data/polynomial/monic.lean
4338f073cc2c42980fd6edcabc58201434de34e2
[ "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
9,088
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.degree import algebra.associated import tactic.omega /-! # Theory of monic polynomials We give several tools for proving that polynomials are monic, e.g. `monic_mul`, `monic_map`. -/ noncomputable theory local attribute [instance, priority 100] classical.prop_decidable open finset open_locale big_operators namespace polynomial universes u v y variables {R : Type u} {S : Type v} {a b : R} {m n : ℕ} {ι : Type y} section semiring variables [semiring R] {p q r : polynomial R} lemma monic.as_sum {p : polynomial R} (hp : p.monic) : p = X^(p.nat_degree) + (∑ i in finset.range p.nat_degree, C (p.coeff i) * X^i) := begin conv_lhs { rw [p.as_sum, finset.sum_range_succ] }, suffices : C (p.coeff p.nat_degree) = 1, { rw [this, one_mul] }, exact congr_arg C hp end lemma ne_zero_of_monic_of_zero_ne_one (hp : monic p) (h : (0 : R) ≠ 1) : p ≠ 0 := mt (congr_arg leading_coeff) $ by rw [monic.def.1 hp, leading_coeff_zero]; cc lemma ne_zero_of_ne_zero_of_monic (hp : p ≠ 0) (hq : monic q) : q ≠ 0 := begin intro h, rw [h, monic.def, leading_coeff_zero] at hq, rw [← mul_one p, ← C_1, ← hq, C_0, mul_zero] at hp, exact hp rfl end lemma monic_map [semiring S] (f : R →+* S) (hp : monic p) : monic (p.map f) := if h : (0 : S) = 1 then by haveI := subsingleton_of_zero_eq_one h; exact subsingleton.elim _ _ else have f (leading_coeff p) ≠ 0, by rwa [show _ = _, from hp, is_semiring_hom.map_one f, ne.def, eq_comm], by begin rw [monic, leading_coeff, coeff_map], suffices : p.coeff (map f p).nat_degree = 1, simp [this], suffices : (map f p).nat_degree = p.nat_degree, rw this, exact hp, rwa nat_degree_eq_of_degree_eq (degree_map_eq_of_leading_coeff_ne_zero _ _), end theorem monic_of_degree_le (n : ℕ) (H1 : degree p ≤ n) (H2 : coeff p n = 1) : monic p := decidable.by_cases (assume H : degree p < n, eq_of_zero_eq_one (H2 ▸ (coeff_eq_zero_of_degree_lt H).symm) _ _) (assume H : ¬degree p < n, by rwa [monic, leading_coeff, nat_degree, (lt_or_eq_of_le H1).resolve_left H]) theorem monic_X_pow_add {n : ℕ} (H : degree p ≤ n) : monic (X ^ (n+1) + p) := have H1 : degree p < n+1, from lt_of_le_of_lt H (with_bot.coe_lt_coe.2 (nat.lt_succ_self n)), monic_of_degree_le (n+1) (le_trans (degree_add_le _ _) (max_le (degree_X_pow_le _) (le_of_lt H1))) (by rw [coeff_add, coeff_X_pow, if_pos rfl, coeff_eq_zero_of_degree_lt H1, add_zero]) theorem monic_X_add_C (x : R) : monic (X + C x) := pow_one (X : polynomial R) ▸ monic_X_pow_add degree_C_le lemma monic_mul (hp : monic p) (hq : monic q) : monic (p * q) := if h0 : (0 : R) = 1 then by haveI := subsingleton_of_zero_eq_one h0; exact subsingleton.elim _ _ else have leading_coeff p * leading_coeff q ≠ 0, by simp [monic.def.1 hp, monic.def.1 hq, ne.symm h0], by rw [monic.def, leading_coeff_mul' this, monic.def.1 hp, monic.def.1 hq, one_mul] lemma monic_pow (hp : monic p) : ∀ (n : ℕ), monic (p ^ n) | 0 := monic_one | (n+1) := monic_mul hp (monic_pow n) end semiring section comm_semiring variables [comm_semiring R] {p : polynomial R} lemma monic_prod_of_monic (s : finset ι) (f : ι → polynomial R) (hs : ∀ i ∈ s, monic (f i)) : monic (∏ i in s, f i) := prod_induction _ _ (@monic_mul _ _) monic_one hs lemma is_unit_C {x : R} : is_unit (C x) ↔ is_unit x := begin rw [is_unit_iff_dvd_one, is_unit_iff_dvd_one], split, { rintros ⟨g, hg⟩, replace hg := congr_arg (eval 0) hg, rw [eval_one, eval_mul, eval_C] at hg, exact ⟨g.eval 0, hg⟩ }, { rintros ⟨y, hy⟩, exact ⟨C y, by rw [← C_mul, ← hy, C_1]⟩ } end lemma eq_one_of_is_unit_of_monic (hm : monic p) (hpu : is_unit p) : p = 1 := have degree p ≤ 0, from calc degree p ≤ degree (1 : polynomial R) : let ⟨u, hu⟩ := is_unit_iff_dvd_one.1 hpu in if hu0 : u = 0 then begin rw [hu0, mul_zero] at hu, rw [← mul_one p, hu, mul_zero], simp end else have p.leading_coeff * u.leading_coeff ≠ 0, by rw [hm.leading_coeff, one_mul, ne.def, leading_coeff_eq_zero]; exact hu0, by rw [hu, degree_mul' this]; exact le_add_of_nonneg_right (degree_nonneg_iff_ne_zero.2 hu0) ... ≤ 0 : degree_one_le, by rw [eq_C_of_degree_le_zero this, ← nat_degree_eq_zero_iff_degree_le_zero.2 this, ← leading_coeff, hm.leading_coeff, C_1] end comm_semiring section comm_ring variables [comm_ring R] namespace monic lemma coeff_nat_degree {p : polynomial R} (hp : p.monic) : p.coeff (p.nat_degree) = 1 := hp @[simp] lemma degree_eq_zero_iff_eq_one {p : polynomial R} (hp : p.monic) : p.nat_degree = 0 ↔ p = 1 := begin split; intro h, swap, { rw h, exact nat_degree_one }, have : p = C (p.coeff 0), { rw ← polynomial.degree_le_zero_iff, rwa polynomial.nat_degree_eq_zero_iff_degree_le_zero at h }, rw this, convert C_1, rw ← h, apply hp, end lemma nat_degree_mul [nontrivial R] {p q : polynomial R} (hp : p.monic) (hq : q.monic) : (p * q).nat_degree = p.nat_degree + q.nat_degree := by { apply nat_degree_mul', rw [hp.leading_coeff, hq.leading_coeff], simp } lemma next_coeff_mul {p q : polynomial R} (hp : monic p) (hq : monic q) : next_coeff (p * q) = next_coeff p + next_coeff q := begin classical, by_cases h : nontrivial R, swap, { rw nontrivial_iff at h, push_neg at h, apply h, }, haveI := h, clear h, have := monic.nat_degree_mul hp hq, dsimp [next_coeff], rw this, simp [hp, hq], clear this, split_ifs; try { tauto <|> simp [h_1, h_2] }, rename h_1 hp0, rename h_2 hq0, clear h, rw ← degree_eq_zero_iff_eq_one at hp0 hq0, assumption', -- we've reduced to the case where the degrees dp and dq are nonzero set dp := p.nat_degree, set dq := q.nat_degree, rw coeff_mul, have : {(dp, dq - 1), (dp - 1, dq)} ⊆ nat.antidiagonal (dp + dq - 1), { rw insert_subset, split, work_on_goal 0 { rw [nat.mem_antidiagonal, nat.add_sub_assoc] }, work_on_goal 1 { simp only [singleton_subset_iff, nat.mem_antidiagonal], apply nat.sub_add_eq_add_sub }, all_goals { apply nat.succ_le_of_lt, apply nat.pos_of_ne_zero, assumption } }, rw ← sum_subset this, { rw [sum_insert, sum_singleton], iterate 2 { rw coeff_nat_degree }, ring, assumption', suffices : dp ≠ dp - 1, { rw mem_singleton, simp [this] }, omega }, clear this, intros x hx hx1, simp only [nat.mem_antidiagonal] at hx, simp only [mem_insert, mem_singleton] at hx1, suffices : p.coeff x.fst = 0 ∨ q.coeff x.snd = 0, cases this; simp [this], suffices : dp < x.fst ∨ dq < x.snd, cases this, { left, apply coeff_eq_zero_of_nat_degree_lt, assumption }, { right, apply coeff_eq_zero_of_nat_degree_lt, assumption }, by_cases h : dp < x.fst, { tauto }, push_neg at h, right, have : x.fst ≠ dp - 1, { contrapose! hx1, right, ext, assumption, dsimp, omega }, have : x.fst ≠ dp, { contrapose! hx1, left, ext, assumption, dsimp, omega }, omega, end lemma next_coeff_prod (s : finset ι) (f : ι → polynomial R) (h : ∀ i ∈ s, monic (f i)) : next_coeff (∏ i in s, f i) = ∑ i in s, next_coeff (f i) := begin classical, revert h, apply finset.induction_on s, { simp only [finset.not_mem_empty, forall_prop_of_true, forall_prop_of_false, finset.sum_empty, finset.prod_empty, not_false_iff, forall_true_iff], rw ← C_1, rw next_coeff_C_eq_zero }, { intros a s ha hs monic, rw finset.prod_insert ha, rw finset.sum_insert ha, rw next_coeff_mul (monic a (finset.mem_insert_self a s)), swap, { apply monic_prod_of_monic, intros b bs, apply monic, apply finset.mem_insert_of_mem bs }, { refine congr rfl (hs _), intros b bs, apply monic, apply finset.mem_insert_of_mem bs }} end end monic end comm_ring section ring variables [ring R] {p : polynomial R} theorem monic_X_sub_C (x : R) : monic (X - C x) := by simpa only [C_neg] using monic_X_add_C (-x) theorem monic_X_pow_sub {n : ℕ} (H : degree p ≤ n) : monic (X ^ (n+1) - p) := monic_X_pow_add ((degree_neg p).symm ▸ H) section injective open function variables [semiring S] {f : R →+* S} (hf : injective f) include hf lemma leading_coeff_of_injective (p : polynomial R) : leading_coeff (p.map f) = f (leading_coeff p) := begin delta leading_coeff, rw [coeff_map f, nat_degree_map' hf p] end lemma monic_of_injective {p : polynomial R} (hp : (p.map f).monic) : p.monic := begin apply hf, rw [← leading_coeff_of_injective hf, hp.leading_coeff, is_semiring_hom.map_one f] end end injective end ring section nonzero_semiring variables [semiring R] [nontrivial R] {p q : polynomial R} @[simp] lemma not_monic_zero : ¬monic (0 : polynomial R) := by simpa only [monic, leading_coeff_zero] using (zero_ne_one : (0 : R) ≠ 1) lemma ne_zero_of_monic (h : monic p) : p ≠ 0 := λ h₁, @not_monic_zero R _ _ (h₁ ▸ h) end nonzero_semiring end polynomial
79e8c1ff935f8fc621ff002a505ceb8d9f3ffc12
9dc8cecdf3c4634764a18254e94d43da07142918
/src/number_theory/legendre_symbol/norm_num.lean
4d77458655448943990d31f61fd84ae8ac483a8b
[ "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
20,480
lean
/- Copyright (c) 2022 Michael Stoll. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Michael Stoll -/ import number_theory.legendre_symbol.jacobi_symbol /-! # A `norm_num` extension for Jacobi and Legendre symbols We extend the `tactic.interactive.norm_num` tactic so that it can be used to provably compute the value of the Jacobi symbol `J(a | b)` or the Legendre symbol `legendre_sym p a` when the arguments are numerals. ## Implementation notes We use the Law of Quadratic Reciprocity for the Jacobi symbol to compute the value of `J(a | b)` efficiently, roughly comparable in effort with the euclidean algorithm for the computation of the gcd of `a` and `b`. More precisely, the computation is done in the following steps. * Use `J(a | 0) = 1` (an artifact of the definition) and `J(a | 1) = 1` to deal with corner cases. * Use `J(a | b) = J(a % b | b)` to reduce to the case that `a` is a natural number. We define a version of the Jacobi symbol restricted to natural numbers for use in the following steps; see `norm_num.jacobi_sym_nat`. (But we'll continue to write `J(a | b)` in this description.) * Remove powers of two from `b`. This is done via `J(2a | 2b) = 0` and `J(2a+1 | 2b) = J(2a+1 | b)` (another artifact of the definition). * Now `0 ≤ a < b` and `b` is odd. If `b = 1`, then the value is `1`. If `a = 0` (and `b > 1`), then the value is `0`. Otherwise, we remove powers of two from `a` via `J(4a | b) = J(a | b)` and `J(2a | b) = ±J(a | b)`, where the sign is determined by the residue class of `b` mod 8, to reduce to `a` odd. * Once `a` is odd, we use Quadratic Reciprocity (QR) in the form `J(a | b) = ±J(b % a | a)`, where the sign is determined by the residue classes of `a` and `b` mod 4. We are then back in the previous case. We provide customized versions of these results for the various reduction steps, where we encode the residue classes mod 2, mod 4, or mod 8 by using terms like `bit1 (bit0 a)`. In this way, the only divisions we have to compute and prove are the ones occurring in the use of QR above. -/ section lemmas namespace norm_num /-- The Jacobi symbol restricted to natural numbers in both arguments. -/ def jacobi_sym_nat (a b : ℕ) : ℤ := jacobi_sym a b /-! ### API Lemmas We repeat part of the API for `jacobi_sym` with `norm_num.jacobi_sym_nat` and without implicit arguments, in a form that is suitable for constructing proofs in `norm_num`. -/ /-- Base cases: `b = 0`, `b = 1`, `a = 0`, `a = 1`. -/ lemma jacobi_sym_nat.zero_right (a : ℕ) : jacobi_sym_nat a 0 = 1 := by rwa [jacobi_sym_nat, jacobi_sym.zero_right] lemma jacobi_sym_nat.one_right (a : ℕ) : jacobi_sym_nat a 1 = 1 := by rwa [jacobi_sym_nat, jacobi_sym.one_right] lemma jacobi_sym_nat.zero_left_even (b : ℕ) (hb : b ≠ 0) : jacobi_sym_nat 0 (bit0 b) = 0 := by rw [jacobi_sym_nat, nat.cast_zero, jacobi_sym.zero_left (nat.one_lt_bit0 hb)] lemma jacobi_sym_nat.zero_left_odd (b : ℕ) (hb : b ≠ 0) : jacobi_sym_nat 0 (bit1 b) = 0 := by rw [jacobi_sym_nat, nat.cast_zero, jacobi_sym.zero_left (nat.one_lt_bit1 hb)] lemma jacobi_sym_nat.one_left_even (b : ℕ) : jacobi_sym_nat 1 (bit0 b) = 1 := by rw [jacobi_sym_nat, nat.cast_one, jacobi_sym.one_left] lemma jacobi_sym_nat.one_left_odd (b : ℕ) : jacobi_sym_nat 1 (bit1 b) = 1 := by rw [jacobi_sym_nat, nat.cast_one, jacobi_sym.one_left] /-- Turn a Legendre symbol into a Jacobi symbol. -/ lemma legendre_sym.to_jacobi_sym (p : ℕ) (pp : fact (p.prime)) (a r : ℤ) (hr : jacobi_sym a p = r) : legendre_sym p a = r := by rwa [@legendre_sym.to_jacobi_sym p pp a] /-- The value depends only on the residue class of `a` mod `b`. -/ lemma jacobi_sym.mod_left (a : ℤ) (b ab' : ℕ) (ab r b' : ℤ) (hb' : (b : ℤ) = b') (hab : a % b' = ab) (h : (ab' : ℤ) = ab) (hr : jacobi_sym_nat ab' b = r) : jacobi_sym a b = r := by rw [← hr, jacobi_sym_nat, jacobi_sym.mod_left, hb', hab, ← h] lemma jacobi_sym_nat.mod_left (a b ab : ℕ) (r : ℤ) (hab : a % b = ab) (hr : jacobi_sym_nat ab b = r) : jacobi_sym_nat a b = r := by { rw [← hr, jacobi_sym_nat, jacobi_sym_nat, _root_.jacobi_sym.mod_left a b, ← hab], refl, } /-- The symbol vanishes when both entries are even (and `b ≠ 0`). -/ lemma jacobi_sym_nat.even_even (a b : ℕ) (hb₀ : b ≠ 0) : jacobi_sym_nat (bit0 a) (bit0 b) = 0 := begin refine jacobi_sym.eq_zero_iff.mpr ⟨nat.bit0_ne_zero hb₀, λ hf, _⟩, have h : 2 ∣ (bit0 a).gcd (bit0 b) := nat.dvd_gcd two_dvd_bit0 two_dvd_bit0, change 2 ∣ (bit0 a : ℤ).gcd (bit0 b) at h, rw [← nat.cast_bit0, ← nat.cast_bit0, hf, ← even_iff_two_dvd] at h, exact nat.not_even_one h, end /-- When `a` is odd and `b` is even, we can replace `b` by `b / 2`. -/ lemma jacobi_sym_nat.odd_even (a b : ℕ) (r : ℤ) (hr : jacobi_sym_nat (bit1 a) b = r) : jacobi_sym_nat (bit1 a) (bit0 b) = r := begin have ha : legendre_sym 2 (bit1 a) = 1 := by simp only [legendre_sym, quadratic_char_apply, quadratic_char_fun_one, int.cast_bit1, char_two.bit1_eq_one, pi.one_apply], cases eq_or_ne b 0 with hb hb, { rw [← hr, hb, jacobi_sym_nat.zero_right], }, { haveI : ne_zero b := ⟨hb⟩, -- for `jacobi_sym.mul_right` rwa [bit0_eq_two_mul b, jacobi_sym_nat, jacobi_sym.mul_right, ← _root_.legendre_sym.to_jacobi_sym, nat.cast_bit1, ha, one_mul], } end /-- If `a` is divisible by `4` and `b` is odd, then we can remove the factor `4` from `a`. -/ lemma jacobi_sym_nat.double_even (a b : ℕ) (r : ℤ) (hr : jacobi_sym_nat a (bit1 b) = r) : jacobi_sym_nat (bit0 (bit0 a)) (bit1 b) = r := begin have : ((2 : ℕ) : ℤ).gcd ((bit1 b) : ℕ) = 1, { rw [int.coe_nat_gcd, nat.bit1_eq_succ_bit0, bit0_eq_two_mul b, nat.succ_eq_add_one, nat.gcd_mul_left_add_right, nat.gcd_one_right], }, rwa [bit0_eq_two_mul a, bit0_eq_two_mul (2 * a), ← mul_assoc, ← pow_two, jacobi_sym_nat, nat.cast_mul, nat.cast_pow, jacobi_sym.mul_left, jacobi_sym.sq_one' this, one_mul], end /-- If `a` is even and `b` is odd, then we can remove a factor `2` from `a`, but we may have to change the sign, depending on `b % 8`. We give one version for each of the four odd residue classes mod `8`. -/ lemma jacobi_sym_nat.even_odd₁ (a b : ℕ) (r : ℤ) (hr : jacobi_sym_nat a (bit1 (bit0 (bit0 b))) = r) : jacobi_sym_nat (bit0 a) (bit1 (bit0 (bit0 b))) = r := begin have hb : (bit1 (bit0 (bit0 b))) % 8 = 1, { rw [nat.bit1_mod_bit0, nat.bit0_mod_bit0, nat.bit0_mod_two], }, rw [jacobi_sym_nat, bit0_eq_two_mul a, nat.cast_mul, jacobi_sym.mul_left, nat.cast_two, jacobi_sym.at_two (odd_bit1 _), zmod.χ₈_nat_mod_eight, hb], norm_num, exact hr, end lemma jacobi_sym_nat.even_odd₇ (a b : ℕ) (r : ℤ) (hr : jacobi_sym_nat a (bit1 (bit1 (bit1 b))) = r) : jacobi_sym_nat (bit0 a) (bit1 (bit1 (bit1 b))) = r := begin have hb : (bit1 (bit1 (bit1 b))) % 8 = 7, { rw [nat.bit1_mod_bit0, nat.bit1_mod_bit0, nat.bit1_mod_two], }, rw [jacobi_sym_nat, bit0_eq_two_mul a, nat.cast_mul, jacobi_sym.mul_left, nat.cast_two, jacobi_sym.at_two (odd_bit1 _), zmod.χ₈_nat_mod_eight, hb], norm_num, exact hr, end lemma jacobi_sym_nat.even_odd₃ (a b : ℕ) (r : ℤ) (hr : jacobi_sym_nat a (bit1 (bit1 (bit0 b))) = r) : jacobi_sym_nat (bit0 a) (bit1 (bit1 (bit0 b))) = -r := begin have hb : (bit1 (bit1 (bit0 b))) % 8 = 3, { rw [nat.bit1_mod_bit0, nat.bit1_mod_bit0, nat.bit0_mod_two], }, rw [jacobi_sym_nat, bit0_eq_two_mul a, nat.cast_mul, jacobi_sym.mul_left, nat.cast_two, jacobi_sym.at_two (odd_bit1 _), zmod.χ₈_nat_mod_eight, hb], norm_num, exact hr, end lemma jacobi_sym_nat.even_odd₅ (a b : ℕ) (r : ℤ) (hr : jacobi_sym_nat a (bit1 (bit0 (bit1 b))) = r) : jacobi_sym_nat (bit0 a) (bit1 (bit0 (bit1 b))) = -r := begin have hb : (bit1 (bit0 (bit1 b))) % 8 = 5, { rw [nat.bit1_mod_bit0, nat.bit0_mod_bit0, nat.bit1_mod_two], }, rw [jacobi_sym_nat, bit0_eq_two_mul a, nat.cast_mul, jacobi_sym.mul_left, nat.cast_two, jacobi_sym.at_two (odd_bit1 _), zmod.χ₈_nat_mod_eight, hb], norm_num, exact hr, end /-- Use quadratic reciproity to reduce to smaller `b`. -/ lemma jacobi_sym_nat.qr₁ (a b : ℕ) (r : ℤ) (hr : jacobi_sym_nat (bit1 b) (bit1 (bit0 a)) = r) : jacobi_sym_nat (bit1 (bit0 a)) (bit1 b) = r := begin have ha : (bit1 (bit0 a)) % 4 = 1, { rw [nat.bit1_mod_bit0, nat.bit0_mod_two], }, have hb := nat.bit1_mod_two, rwa [jacobi_sym_nat, jacobi_sym.quadratic_reciprocity_one_mod_four ha (nat.odd_iff.mpr hb)], end lemma jacobi_sym_nat.qr₁_mod (a b ab : ℕ) (r : ℤ) (hab : (bit1 b) % (bit1 (bit0 a)) = ab) (hr : jacobi_sym_nat ab (bit1 (bit0 a)) = r) : jacobi_sym_nat (bit1 (bit0 a)) (bit1 b) = r := jacobi_sym_nat.qr₁ _ _ _ $ jacobi_sym_nat.mod_left _ _ ab r hab hr lemma jacobi_sym_nat.qr₁' (a b : ℕ) (r : ℤ) (hr : jacobi_sym_nat (bit1 (bit0 b)) (bit1 a) = r) : jacobi_sym_nat (bit1 a) (bit1 (bit0 b)) = r := begin have hb : (bit1 (bit0 b)) % 4 = 1, { rw [nat.bit1_mod_bit0, nat.bit0_mod_two], }, have ha := nat.bit1_mod_two, rwa [jacobi_sym_nat, ← jacobi_sym.quadratic_reciprocity_one_mod_four hb (nat.odd_iff.mpr ha)] end lemma jacobi_sym_nat.qr₁'_mod (a b ab : ℕ) (r : ℤ) (hab : (bit1 (bit0 b)) % (bit1 a) = ab) (hr : jacobi_sym_nat ab (bit1 a) = r) : jacobi_sym_nat (bit1 a) (bit1 (bit0 b)) = r := jacobi_sym_nat.qr₁' _ _ _ $ jacobi_sym_nat.mod_left _ _ ab r hab hr lemma jacobi_sym_nat.qr₃ (a b : ℕ) (r : ℤ) (hr : jacobi_sym_nat (bit1 (bit1 b)) (bit1 (bit1 a)) = r) : jacobi_sym_nat (bit1 (bit1 a)) (bit1 (bit1 b)) = -r := begin have hb : (bit1 (bit1 b)) % 4 = 3, { rw [nat.bit1_mod_bit0, nat.bit1_mod_two], }, have ha : (bit1 (bit1 a)) % 4 = 3, { rw [nat.bit1_mod_bit0, nat.bit1_mod_two], }, rwa [jacobi_sym_nat, jacobi_sym.quadratic_reciprocity_three_mod_four ha hb, neg_inj] end lemma jacobi_sym_nat.qr₃_mod (a b ab : ℕ) (r : ℤ) (hab : (bit1 (bit1 b)) % (bit1 (bit1 a)) = ab) (hr : jacobi_sym_nat ab (bit1 (bit1 a)) = r) : jacobi_sym_nat (bit1 (bit1 a)) (bit1 (bit1 b)) = -r := jacobi_sym_nat.qr₃ _ _ _ $ jacobi_sym_nat.mod_left _ _ ab r hab hr end norm_num end lemmas section evaluation -- The following is to prevent strange error messages from occurring. instance : ring ℚ := division_ring.to_ring ℚ /-! ### Certified evaluation of the Jacobi symbol The following functions recursively evaluate a Jacobi symbol and construct the corresponding proof term. -/ namespace norm_num open tactic /-- This evaluates `r := jacobi_sym_nat a b` recursively using quadratic reciprocity and produces a proof term for the equality, assuming that `a < b` and `b` is odd. -/ meta def prove_jacobi_sym_odd : instance_cache → instance_cache → expr → expr → tactic (instance_cache × instance_cache × expr × expr) | zc nc ea eb := do match match_numeral eb with | match_numeral_result.one := -- `b = 1`, result is `1` pure (zc, nc, `(1 : ℤ), `(jacobi_sym_nat.one_right).mk_app [ea]) | match_numeral_result.bit1 eb₁ := do -- `b > 1` (recall that `b` is odd) match match_numeral ea with | match_numeral_result.zero := do -- `a = 0`, result is `0` b ← eb₁.to_nat, (nc, phb₀) ← prove_ne nc eb₁ `(0 : ℕ) b 0, -- proof of `b ≠ 0` pure (zc, nc, `(0 : ℤ), `(jacobi_sym_nat.zero_left_odd).mk_app [eb₁, phb₀]) | match_numeral_result.one := do -- `a = 1`, result is `1` pure (zc, nc, `(1 : ℤ), `(jacobi_sym_nat.one_left_odd).mk_app [eb₁]) | match_numeral_result.bit0 ea₁ := do -- `a` is even; check if divisible by `4` match match_numeral ea₁ with | match_numeral_result.bit0 ea₂ := do (zc, nc, er, p) ← prove_jacobi_sym_odd zc nc ea₂ eb, -- compute `jacobi_sym_nat (a / 4) b` pure (zc, nc, er, `(jacobi_sym_nat.double_even).mk_app [ea₂, eb₁, er, p]) | _ := do -- reduce to `a / 2`; need to consider `b % 8` (zc, nc, er, p) ← prove_jacobi_sym_odd zc nc ea₁ eb, -- compute `jacobi_sym_nat (a / 2) b` match match_numeral eb₁ with -- | match_numeral_result.zero := -- `b = 1`, not reached | match_numeral_result.one := do -- `b = 3` r ← er.to_int, (zc, er') ← zc.of_int (- r), pure (zc, nc, er', `(jacobi_sym_nat.even_odd₃).mk_app [ea₁, `(0 : ℕ), er, p]) | match_numeral_result.bit0 eb₂ := do -- `b % 4 = 1` match match_numeral eb₂ with -- | match_numeral_result.zero := -- not reached | match_numeral_result.one := do -- `b = 5` r ← er.to_int, (zc, er') ← zc.of_int (- r), pure (zc, nc, er', `(jacobi_sym_nat.even_odd₅).mk_app [ea₁, `(0 : ℕ), er, p]) | match_numeral_result.bit0 eb₃ := do -- `b % 8 = 1` pure (zc, nc, er, `(jacobi_sym_nat.even_odd₁).mk_app [ea₁, eb₃, er, p]) | match_numeral_result.bit1 eb₃ := do -- `b % 8 = 5` r ← er.to_int, (zc, er') ← zc.of_int (- r), pure (zc, nc, er', `(jacobi_sym_nat.even_odd₅).mk_app [ea₁, eb₃, er, p]) | _ := failed end | match_numeral_result.bit1 eb₂ := do -- `b % 4 = 3` match match_numeral eb₂ with -- | match_numeral_result.zero := -- not reached | match_numeral_result.one := do -- `b = 7` pure (zc, nc, er, `(jacobi_sym_nat.even_odd₇).mk_app [ea₁, `(0 : ℕ), er, p]) | match_numeral_result.bit0 eb₃ := do -- `b % 8 = 3` r ← er.to_int, (zc, er') ← zc.of_int (- r), pure (zc, nc, er', `(jacobi_sym_nat.even_odd₃).mk_app [ea₁, eb₃, er, p]) | match_numeral_result.bit1 eb₃ := do -- `b % 8 = 7` pure (zc, nc, er, `(jacobi_sym_nat.even_odd₇).mk_app [ea₁, eb₃, er, p]) | _ := failed end | _ := failed end end | match_numeral_result.bit1 ea₁ := do -- `a` is odd -- use Quadratic Reciprocity; look at `a` and `b` mod `4` (nc, bma, phab) ← prove_div_mod nc eb ea tt, -- compute `b % a` (zc, nc, er, p) ← prove_jacobi_sym_odd zc nc bma ea, -- compute `jacobi_sym_nat (b % a) a` match match_numeral ea₁ with -- | match_numeral_result.zero := -- `a = 1`, not reached | match_numeral_result.one := do -- `a = 3`; need to consider `b` match match_numeral eb₁ with -- | match_numeral_result.zero := -- `b = 1`, not reached -- | match_numeral_result.one := -- `b = 3`, not reached, since `a < b` | match_numeral_result.bit0 eb₂ := do -- `b % 4 = 1` pure (zc, nc, er, `(jacobi_sym_nat.qr₁'_mod).mk_app [ea₁, eb₂, bma, er, phab, p]) | match_numeral_result.bit1 eb₂ := do -- `b % 4 = 3` r ← er.to_int, (zc, er') ← zc.of_int (- r), pure (zc, nc, er', `(jacobi_sym_nat.qr₃_mod).mk_app [`(0 : ℕ), eb₂, bma, er, phab, p]) | _ := failed end | match_numeral_result.bit0 ea₂ := do -- `a % 4 = 1` pure (zc, nc, er, `(jacobi_sym_nat.qr₁_mod).mk_app [ea₂, eb₁, bma, er, phab, p]) | match_numeral_result.bit1 ea₂ := do -- `a % 4 = 3`; need to consider `b` match match_numeral eb₁ with -- | match_numeral_result.zero := do -- `b = 1`, not reached -- | match_numeral_result.one := do -- `b = 3`, not reached, since `a < b` | match_numeral_result.bit0 eb₂ := do -- `b % 4 = 1` pure (zc, nc, er, `(jacobi_sym_nat.qr₁'_mod).mk_app [ea₁, eb₂, bma, er, phab, p]) | match_numeral_result.bit1 eb₂ := do -- `b % 4 = 3` r ← er.to_int, (zc, er') ← zc.of_int (- r), pure (zc, nc, er', `(jacobi_sym_nat.qr₃_mod).mk_app [ea₂, eb₂, bma, er, phab, p]) | _ := failed end | _ := failed end | _ := failed end | _ := failed end /-- This evaluates `r := jacobi_sym_nat a b` and produces a proof term for the equality by removing powers of `2` from `b` and then calling `prove_jacobi_sym_odd`. -/ meta def prove_jacobi_sym_nat : instance_cache → instance_cache → expr → expr → tactic (instance_cache × instance_cache × expr × expr) | zc nc ea eb := do match match_numeral eb with | match_numeral_result.zero := -- `b = 0`, result is `1` pure (zc, nc, `(1 : ℤ), `(jacobi_sym_nat.zero_right).mk_app [ea]) | match_numeral_result.one := -- `b = 1`, result is `1` pure (zc, nc, `(1 : ℤ), `(jacobi_sym_nat.one_right).mk_app [ea]) | match_numeral_result.bit0 eb₁ := -- `b` is even and nonzero match match_numeral ea with | match_numeral_result.zero := do -- `a = 0`, result is `0` b ← eb₁.to_nat, (nc, phb₀) ← prove_ne nc eb₁ `(0 : ℕ) b 0, -- proof of `b ≠ 0` pure (zc, nc, `(0 : ℤ), `(jacobi_sym_nat.zero_left_even).mk_app [eb₁, phb₀]) | match_numeral_result.one := do -- `a = 1`, result is `1` pure (zc, nc, `(1 : ℤ), `(jacobi_sym_nat.one_left_even).mk_app [eb₁]) | match_numeral_result.bit0 ea₁ := do -- `a` is even, result is `0` b ← eb₁.to_nat, (nc, phb₀) ← prove_ne nc eb₁ `(0 : ℕ) b 0, -- proof of `b ≠ 0` let er : expr := `(0 : ℤ), pure (zc, nc, er, `(jacobi_sym_nat.even_even).mk_app [ea₁, eb₁, phb₀]) | match_numeral_result.bit1 ea₁ := do -- `a` is odd, reduce to `b / 2` (zc, nc, er, p) ← prove_jacobi_sym_nat zc nc ea eb₁, pure (zc, nc, er, `(jacobi_sym_nat.odd_even).mk_app [ea₁, eb₁, er, p]) | _ := failed end | match_numeral_result.bit1 eb₁ := do -- `b` is odd a ← ea.to_nat, b ← eb.to_nat, if b ≤ a then do -- reduce to `jacobi_sym_nat (a % b) b` (nc, amb, phab) ← prove_div_mod nc ea eb tt, -- compute `a % b` (zc, nc, er, p) ← prove_jacobi_sym_odd zc nc amb eb, -- compute `jacobi_sym_nat (a % b) b` pure (zc, nc, er, `(jacobi_sym_nat.mod_left).mk_app [ea, eb, amb, er, phab, p]) else prove_jacobi_sym_odd zc nc ea eb | _ := failed end /-- This evaluates `r := jacobi_sym a b` and produces a proof term for the equality. This is done by reducing to `r := jacobi_sym_nat (a % b) b`. -/ meta def prove_jacobi_sym : instance_cache → instance_cache → expr → expr → tactic (instance_cache × instance_cache × expr × expr) | zc nc ea eb := do match match_numeral eb with -- deal with simple cases right away | match_numeral_result.zero := pure (zc, nc, `(1 : ℤ), `(jacobi_sym.zero_right).mk_app [ea]) | match_numeral_result.one := pure (zc, nc, `(1 : ℤ), `(jacobi_sym.one_right).mk_app [ea]) | _ := do -- Now `1 < b`. Compute `jacobi_sym_nat (a % b) b` instead. b ← eb.to_nat, (zc, eb') ← zc.of_int (b : ℤ), -- Get the proof that `(b : ℤ) = b'` (where `eb'` is the numeral representing `b'`). -- This is important to avoid inefficient matching between the two. (zc, nc, eb₁, pb') ← prove_nat_uncast zc nc eb', (zc, amb, phab) ← prove_div_mod zc ea eb' tt, -- compute `a % b` (zc, nc, amb', phab') ← prove_nat_uncast zc nc amb, -- `a % b` as a natural number (zc, nc, er, p) ← prove_jacobi_sym_nat zc nc amb' eb₁, -- compute `jacobi_sym_nat (a % b) b` pure (zc, nc, er, `(jacobi_sym.mod_left).mk_app [ea, eb₁, amb', amb, er, eb', pb', phab, phab', p]) end end norm_num end evaluation section tactic /-! ### The `norm_num` plug-in -/ namespace tactic namespace norm_num /-- This is the `norm_num` plug-in that evaluates Jacobi and Legendre symbols. -/ @[norm_num] meta def eval_jacobi_sym : expr → tactic (expr × expr) | `(jacobi_sym %%ea %%eb) := do -- Jacobi symbol zc ← mk_instance_cache `(ℤ), nc ← mk_instance_cache `(ℕ), (prod.snd ∘ prod.snd) <$> norm_num.prove_jacobi_sym zc nc ea eb | `(norm_num.jacobi_sym_nat %%ea %%eb) := do -- Jacobi symbol on natural numbers zc ← mk_instance_cache `(ℤ), nc ← mk_instance_cache `(ℕ), (prod.snd ∘ prod.snd) <$> norm_num.prove_jacobi_sym_nat zc nc ea eb | `(@legendre_sym %%ep %%inst %%ea) := do -- Legendre symbol zc ← mk_instance_cache `(ℤ), nc ← mk_instance_cache `(ℕ), (zc, nc, er, pf) ← norm_num.prove_jacobi_sym zc nc ea ep, pure (er, `(norm_num.legendre_sym.to_jacobi_sym).mk_app [ep, inst, ea, er, pf]) | _ := failed end norm_num end tactic end tactic
5e64dab6e143d4394b6ee5db066e9ea089f0f641
947b78d97130d56365ae2ec264df196ce769371a
/stage0/src/Lean/Class.lean
bba81364a6316d202fdecab5d8382f079cd0839b
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,135
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Attributes namespace Lean inductive ClassEntry | «class» (name : Name) (hasOutParam : Bool) | «instance» (name : Name) (ofClass : Name) -- TODO: remove after we remove old type class resolution namespace ClassEntry @[inline] def getName : ClassEntry → Name | «class» n _ => n | «instance» n _ => n def lt (a b : ClassEntry) : Bool := Name.quickLt a.getName b.getName end ClassEntry structure ClassState := (classToInstances : SMap Name (List Name) := SMap.empty) -- TODO: delete (hasOutParam : SMap Name Bool := SMap.empty) -- We should keep only this one (instances : SMap Name Unit := SMap.empty) -- TODO: delete namespace ClassState instance : Inhabited ClassState := ⟨{}⟩ def addEntry (s : ClassState) (entry : ClassEntry) : ClassState := match entry with | ClassEntry.«class» clsName hasOutParam => { s with hasOutParam := s.hasOutParam.insert clsName hasOutParam } | ClassEntry.«instance» instName clsName => { s with instances := s.instances.insert instName (), classToInstances := match s.classToInstances.find? clsName with | some insts => s.classToInstances.insert clsName (instName :: insts) | none => s.classToInstances.insert clsName [instName] } def switch : ClassState → ClassState | ⟨m₁, m₂, m₃⟩ => ⟨m₁.switch, m₂.switch, m₃.switch⟩ end ClassState /- TODO: add support for scoped instances -/ def mkClassExtension : IO (SimplePersistentEnvExtension ClassEntry ClassState) := registerSimplePersistentEnvExtension { name := `classExt, addEntryFn := ClassState.addEntry, addImportedFn := fun es => (mkStateFromImportedEntries ClassState.addEntry {} es).switch } @[init mkClassExtension] constant classExtension : SimplePersistentEnvExtension ClassEntry ClassState := arbitrary _ @[export lean_is_class] def isClass (env : Environment) (n : Name) : Bool := (classExtension.getState env).hasOutParam.contains n @[export lean_is_instance] def isInstance (env : Environment) (n : Name) : Bool := (classExtension.getState env).instances.contains n @[export lean_get_class_instances] def getClassInstances (env : Environment) (n : Name) : List Name := match (classExtension.getState env).classToInstances.find? n with | some insts => insts | none => [] @[export lean_has_out_params] def hasOutParams (env : Environment) (n : Name) : Bool := match (classExtension.getState env).hasOutParam.find? n with | some b => b | none => false @[export lean_is_out_param] def isOutParam (e : Expr) : Bool := e.isAppOfArity `outParam 1 /-- Auxiliary function for checking whether a class has `outParam`, and whether they are being correctly used. A regular (i.e., non `outParam`) must not depend on an `outParam`. Reason for this restriction: When performing type class resolution, we replace arguments that are `outParam`s with fresh metavariables. If regular parameters could depend on `outParam`s, then we would also have to replace them with fresh metavariables. Otherwise, the resulting expression could be type incorrect. This transformation would be counterintuitive to users since we would implicitly treat these regular parameters as `outParam`s. -/ private partial def checkOutParam : Nat → Array FVarId → Expr → Except String Bool | i, outParams, Expr.forallE _ d b _ => if isOutParam d then let fvarId := mkNameNum `_fvar outParams.size; let outParams := outParams.push fvarId; let fvar := mkFVar fvarId; let b := b.instantiate1 fvar; checkOutParam (i+1) outParams b else if d.hasAnyFVar (fun fvarId => outParams.contains fvarId) then Except.error $ "invalid class, parameter #" ++ toString i ++ " depends on `outParam`, but it is not an `outParam`" else checkOutParam (i+1) outParams b | i, outParams, e => pure (outParams.size > 0) def addClass (env : Environment) (clsName : Name) : Except String Environment := if isClass env clsName then Except.error ("class has already been declared '" ++ toString clsName ++ "'") else match env.find? clsName with | none => Except.error ("unknown declaration '" ++ toString clsName ++ "'") | some decl@(ConstantInfo.inductInfo _) => do b ← checkOutParam 1 #[] decl.type; Except.ok (classExtension.addEntry env (ClassEntry.«class» clsName b)) | some _ => Except.error ("invalid 'class', declaration '" ++ toString clsName ++ "' must be inductive datatype or structure") private def consumeNLambdas : Nat → Expr → Option Expr | 0, e => some e | i+1, Expr.lam _ _ b _ => consumeNLambdas i b | _, _ => none partial def getClassName (env : Environment) : Expr → Option Name | Expr.forallE _ _ b _ => getClassName b | e => do Expr.const c _ _ ← pure e.getAppFn | none; info ← env.find? c; match info.value? with | some val => do body ← consumeNLambdas e.getAppNumArgs val; getClassName body | none => if isClass env c then some c else none @[init] def registerClassAttr : IO Unit := registerBuiltinAttribute { name := `class, descr := "type class", add := fun decl args persistent => do env ← getEnv; when args.hasArgs $ throwError "invalid attribute 'class', unexpected argument"; unless persistent $ throwError "invalid attribute 'class', must be persistent"; env ← ofExcept (addClass env decl); setEnv env } -- TODO: delete @[export lean_add_instance_old] def addGlobalInstanceOld (env : Environment) (instName : Name) : Except String Environment := match env.find? instName with | none => Except.error ("unknown declaration '" ++ toString instName ++ "'") | some decl => match getClassName env decl.type with | none => Except.error ("invalid instance '" ++ toString instName ++ "', failed to retrieve class") | some clsName => Except.ok (classExtension.addEntry env (ClassEntry.«instance» instName clsName)) end Lean
e03cfdccf9f6d418bb22a195fc17dfc8c955b042
957a80ea22c5abb4f4670b250d55534d9db99108
/library/init/data/bool/basic.lean
7099eabb197e01adc7fc16e9c90b54cfda923d70
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
658
lean
-- Copyright (c) 2014 Microsoft Corporation. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Author: Leonardo de Moura prelude import init.core @[inline] def {u} cond {a : Type u} : bool → a → a → a | tt x y := x | ff x y := y @[inline] def bor : bool → bool → bool | tt _ := tt | ff tt := tt | ff ff := ff @[inline] def band : bool → bool → bool | ff _ := ff | tt ff := ff | tt tt := tt @[inline] def bnot : bool → bool | tt := ff | ff := tt @[inline] def bxor : bool → bool → bool | tt ff := tt | ff tt := tt | _ _ := ff notation x || y := bor x y notation x && y := band x y
6de2486b7436ff6ff3d0dce0cacdd25f16d6ad89
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/category_theory/filtered.lean
9bf5d95420563fd0aba1a10a85518560467d7579
[ "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
19,769
lean
/- Copyright (c) 2019 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.fin_category import category_theory.limits.cones import category_theory.adjunction.basic import order.bounded_lattice /-! # Filtered categories A category is filtered if every finite diagram admits a cocone. We give a simple characterisation of this condition as 1. for every pair of objects there exists another object "to the right", 2. for every pair of parallel morphisms there exists a morphism to the right so the compositions are equal, and 3. there exists some object. Filtered colimits are often better behaved than arbitrary colimits. See `category_theory/limits/types` for some details. Filtered categories are nice because colimits indexed by filtered categories tend to be easier to describe than general colimits (and more often preserved by functors). In this file we show that any functor from a finite category to a filtered category admits a cocone: * `cocone_nonempty [fin_category J] [is_filtered C] (F : J ⥤ C) : nonempty (cocone F)` More generally, for any finite collection of objects and morphisms between them in a filtered category (even if not closed under composition) there exists some object `Z` receiving maps from all of them, so that all the triangles (one edge from the finite set, two from morphisms to `Z`) commute. This formulation is often more useful in practice and is available via `sup_exists`, which takes a finset of objects, and an indexed family (indexed by source and target) of finsets of morphisms. We also provide all of the above API for cofiltered categories. ## See also In `category_theory.limits.filtered_colimit_commutes_finite_limit` we show that filtered colimits commute with finite limits. ## Future work * Forgetful functors for algebraic categories typically preserve filtered colimits. -/ universes v v₁ u u₁-- declare the `v`'s first; see `category_theory.category` for an explanation namespace category_theory variables (C : Type u) [category.{v} C] /-- A category `is_filtered_or_empty` if 1. for every pair of objects there exists another object "to the right", and 2. for every pair of parallel morphisms there exists a morphism to the right so the compositions are equal. -/ class is_filtered_or_empty : Prop := (cocone_objs : ∀ (X Y : C), ∃ Z (f : X ⟶ Z) (g : Y ⟶ Z), true) (cocone_maps : ∀ ⦃X Y : C⦄ (f g : X ⟶ Y), ∃ Z (h : Y ⟶ Z), f ≫ h = g ≫ h) /-- A category `is_filtered` if 1. for every pair of objects there exists another object "to the right", 2. for every pair of parallel morphisms there exists a morphism to the right so the compositions are equal, and 3. there exists some object. See https://stacks.math.columbia.edu/tag/002V. (They also define a diagram being filtered.) -/ class is_filtered extends is_filtered_or_empty C : Prop := [nonempty : nonempty C] @[priority 100] instance is_filtered_or_empty_of_semilattice_sup (α : Type u) [semilattice_sup α] : is_filtered_or_empty α := { cocone_objs := λ X Y, ⟨X ⊔ Y, hom_of_le le_sup_left, hom_of_le le_sup_right, trivial⟩, cocone_maps := λ X Y f g, ⟨Y, 𝟙 _, (by ext)⟩, } @[priority 100] instance is_filtered_of_semilattice_sup_nonempty (α : Type u) [semilattice_sup α] [nonempty α] : is_filtered α := {} -- TODO: Define `codirected_order` and provide the dual to this instance. @[priority 100] instance is_filtered_or_empty_of_directed_order (α : Type u) [directed_order α] : is_filtered_or_empty α := { cocone_objs := λ X Y, let ⟨Z,h1,h2⟩ := directed_order.directed X Y in ⟨Z, hom_of_le h1, hom_of_le h2, trivial⟩, cocone_maps := λ X Y f g, ⟨Y, 𝟙 _, by simp⟩ } -- TODO: Define `codirected_order` and provide the dual to this instance. @[priority 100] instance is_filtered_of_directed_order_nonempty (α : Type u) [directed_order α] [nonempty α] : is_filtered α := {} -- Sanity checks example (α : Type u) [semilattice_sup_bot α] : is_filtered α := by apply_instance example (α : Type u) [semilattice_sup_top α] : is_filtered α := by apply_instance namespace is_filtered variables {C} [is_filtered C] /-- `max j j'` is an arbitrary choice of object to the right of both `j` and `j'`, whose existence is ensured by `is_filtered`. -/ noncomputable def max (j j' : C) : C := (is_filtered_or_empty.cocone_objs j j').some /-- `left_to_max j j'` is an arbitrarily choice of morphism from `j` to `max j j'`, whose existence is ensured by `is_filtered`. -/ noncomputable def left_to_max (j j' : C) : j ⟶ max j j' := (is_filtered_or_empty.cocone_objs j j').some_spec.some /-- `right_to_max j j'` is an arbitrarily choice of morphism from `j'` to `max j j'`, whose existence is ensured by `is_filtered`. -/ noncomputable def right_to_max (j j' : C) : j' ⟶ max j j' := (is_filtered_or_empty.cocone_objs j j').some_spec.some_spec.some /-- `coeq f f'`, for morphisms `f f' : j ⟶ j'`, is an arbitrary choice of object which admits a morphism `coeq_hom f f' : j' ⟶ coeq f f'` such that `coeq_condition : f ≫ coeq_hom f f' = f' ≫ coeq_hom f f'`. Its existence is ensured by `is_filtered`. -/ noncomputable def coeq {j j' : C} (f f' : j ⟶ j') : C := (is_filtered_or_empty.cocone_maps f f').some /-- `coeq_hom f f'`, for morphisms `f f' : j ⟶ j'`, is an arbitrary choice of morphism `coeq_hom f f' : j' ⟶ coeq f f'` such that `coeq_condition : f ≫ coeq_hom f f' = f' ≫ coeq_hom f f'`. Its existence is ensured by `is_filtered`. -/ noncomputable def coeq_hom {j j' : C} (f f' : j ⟶ j') : j' ⟶ coeq f f' := (is_filtered_or_empty.cocone_maps f f').some_spec.some /-- `coeq_condition f f'`, for morphisms `f f' : j ⟶ j'`, is the proof that `f ≫ coeq_hom f f' = f' ≫ coeq_hom f f'`. -/ @[simp, reassoc] lemma coeq_condition {j j' : C} (f f' : j ⟶ j') : f ≫ coeq_hom f f' = f' ≫ coeq_hom f f' := (is_filtered_or_empty.cocone_maps f f').some_spec.some_spec open category_theory.limits /-- Any finite collection of objects in a filtered category has an object "to the right". -/ lemma sup_objs_exists (O : finset C) : ∃ (S : C), ∀ {X}, X ∈ O → _root_.nonempty (X ⟶ S) := begin classical, apply finset.induction_on O, { exact ⟨is_filtered.nonempty.some, (by rintros - ⟨⟩)⟩, }, { rintros X O' nm ⟨S', w'⟩, use max X S', rintros Y mY, by_cases h : X = Y, { subst h, exact ⟨left_to_max _ _⟩, }, { exact ⟨(w' (by finish)).some ≫ right_to_max _ _⟩, }, } end variables (O : finset C) (H : finset (Σ' (X Y : C) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y)) /-- Given any `finset` of objects `{X, ...}` and indexed collection of `finset`s of morphisms `{f, ...}` in `C`, there exists an object `S`, with a morphism `T X : X ⟶ S` from each `X`, such that the triangles commute: `f ≫ T Y = T X`, for `f : X ⟶ Y` in the `finset`. -/ lemma sup_exists : ∃ (S : C) (T : Π {X : C}, X ∈ O → (X ⟶ S)), ∀ {X Y : C} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟶ Y}, (⟨X, Y, mX, mY, f⟩ : (Σ' (X Y : C) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y)) ∈ H → f ≫ T mY = T mX := begin classical, apply finset.induction_on H, { obtain ⟨S, f⟩ := sup_objs_exists O, refine ⟨S, λ X mX, (f mX).some, _⟩, rintros - - - - - ⟨⟩, }, { rintros ⟨X, Y, mX, mY, f⟩ H' nmf ⟨S', T', w'⟩, refine ⟨coeq (f ≫ T' mY) (T' mX), λ Z mZ, T' mZ ≫ coeq_hom (f ≫ T' mY) (T' mX), _⟩, intros X' Y' mX' mY' f' mf', rw [←category.assoc], by_cases h : X = X' ∧ Y = Y', { rcases h with ⟨rfl, rfl⟩, by_cases hf : f = f', { subst hf, apply coeq_condition, }, { rw @w' _ _ mX mY f' (by simpa [hf ∘ eq.symm] using mf') }, }, { rw @w' _ _ mX' mY' f' (by finish), }, }, end /-- An arbitrary choice of object "to the right" of a finite collection of objects `O` and morphisms `H`, making all the triangles commute. -/ noncomputable def sup : C := (sup_exists O H).some /-- The morphisms to `sup O H`. -/ noncomputable def to_sup {X : C} (m : X ∈ O) : X ⟶ sup O H := (sup_exists O H).some_spec.some m /-- The triangles of consisting of a morphism in `H` and the maps to `sup O H` commute. -/ lemma to_sup_commutes {X Y : C} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟶ Y} (mf : (⟨X, Y, mX, mY, f⟩ : Σ' (X Y : C) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y) ∈ H) : f ≫ to_sup O H mY = to_sup O H mX := (sup_exists O H).some_spec.some_spec mX mY mf variables {J : Type v} [small_category J] [fin_category J] /-- If we have `is_filtered C`, then for any functor `F : J ⥤ C` with `fin_category J`, there exists a cocone over `F`. -/ lemma cocone_nonempty (F : J ⥤ C) : _root_.nonempty (cocone F) := begin classical, let O := (finset.univ.image F.obj), let H : finset (Σ' (X Y : C) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y) := finset.univ.bUnion (λ X : J, finset.univ.bUnion (λ Y : J, finset.univ.image (λ f : X ⟶ Y, ⟨F.obj X, F.obj Y, by simp, by simp, F.map f⟩))), obtain ⟨Z, f, w⟩ := sup_exists O H, refine ⟨⟨Z, ⟨λ X, f (by simp), _⟩⟩⟩, intros j j' g, dsimp, simp only [category.comp_id], apply w, simp only [finset.mem_univ, finset.mem_bUnion, exists_and_distrib_left, exists_prop_of_true, finset.mem_image], exact ⟨j, rfl, j', g, (by simp)⟩, end /-- An arbitrary choice of cocone over `F : J ⥤ C`, for `fin_category J` and `is_filtered C`. -/ noncomputable def cocone (F : J ⥤ C) : cocone F := (cocone_nonempty F).some variables {D : Type u₁} [category.{v₁} D] /-- If `C` is filtered, and we have a functor `R : C ⥤ D` with a left adjoint, then `D` is filtered. -/ lemma of_right_adjoint {L : D ⥤ C} {R : C ⥤ D} (h : L ⊣ R) : is_filtered D := { cocone_objs := λ X Y, ⟨_, h.hom_equiv _ _ (left_to_max _ _), h.hom_equiv _ _ (right_to_max _ _), ⟨⟩⟩, cocone_maps := λ X Y f g, ⟨_, h.hom_equiv _ _ (coeq_hom _ _), by rw [← h.hom_equiv_naturality_left, ← h.hom_equiv_naturality_left, coeq_condition]⟩, nonempty := is_filtered.nonempty.map R.obj } /-- If `C` is filtered, and we have a right adjoint functor `R : C ⥤ D`, then `D` is filtered. -/ lemma of_is_right_adjoint (R : C ⥤ D) [is_right_adjoint R] : is_filtered D := of_right_adjoint (adjunction.of_right_adjoint R) /-- Being filtered is preserved by equivalence of categories. -/ lemma of_equivalence (h : C ≌ D) : is_filtered D := of_right_adjoint h.symm.to_adjunction end is_filtered /-- A category `is_cofiltered_or_empty` if 1. for every pair of objects there exists another object "to the left", and 2. for every pair of parallel morphisms there exists a morphism to the left so the compositions are equal. -/ class is_cofiltered_or_empty : Prop := (cocone_objs : ∀ (X Y : C), ∃ W (f : W ⟶ X) (g : W ⟶ Y), true) (cocone_maps : ∀ ⦃X Y : C⦄ (f g : X ⟶ Y), ∃ W (h : W ⟶ X), h ≫ f = h ≫ g) /-- A category `is_cofiltered` if 1. for every pair of objects there exists another object "to the left", 2. for every pair of parallel morphisms there exists a morphism to the left so the compositions are equal, and 3. there exists some object. See https://stacks.math.columbia.edu/tag/04AZ. -/ class is_cofiltered extends is_cofiltered_or_empty C : Prop := [nonempty : nonempty C] @[priority 100] instance is_cofiltered_or_empty_of_semilattice_inf (α : Type u) [semilattice_inf α] : is_cofiltered_or_empty α := { cocone_objs := λ X Y, ⟨X ⊓ Y, hom_of_le inf_le_left, hom_of_le inf_le_right, trivial⟩, cocone_maps := λ X Y f g, ⟨X, 𝟙 _, (by ext)⟩, } @[priority 100] instance is_cofiltered_of_semilattice_inf_nonempty (α : Type u) [semilattice_inf α] [nonempty α] : is_cofiltered α := {} -- Sanity checks example (α : Type u) [semilattice_inf_bot α] : is_cofiltered α := by apply_instance example (α : Type u) [semilattice_inf_top α] : is_cofiltered α := by apply_instance namespace is_cofiltered variables {C} [is_cofiltered C] /-- `min j j'` is an arbitrary choice of object to the left of both `j` and `j'`, whose existence is ensured by `is_cofiltered`. -/ noncomputable def min (j j' : C) : C := (is_cofiltered_or_empty.cocone_objs j j').some /-- `min_to_left j j'` is an arbitrarily choice of morphism from `min j j'` to `j`, whose existence is ensured by `is_cofiltered`. -/ noncomputable def min_to_left (j j' : C) : min j j' ⟶ j := (is_cofiltered_or_empty.cocone_objs j j').some_spec.some /-- `min_to_right j j'` is an arbitrarily choice of morphism from `min j j'` to `j'`, whose existence is ensured by `is_cofiltered`. -/ noncomputable def min_to_right (j j' : C) : min j j' ⟶ j' := (is_cofiltered_or_empty.cocone_objs j j').some_spec.some_spec.some /-- `eq f f'`, for morphisms `f f' : j ⟶ j'`, is an arbitrary choice of object which admits a morphism `eq_hom f f' : eq f f' ⟶ j` such that `eq_condition : eq_hom f f' ≫ f = eq_hom f f' ≫ f'`. Its existence is ensured by `is_cofiltered`. -/ noncomputable def eq {j j' : C} (f f' : j ⟶ j') : C := (is_cofiltered_or_empty.cocone_maps f f').some /-- `eq_hom f f'`, for morphisms `f f' : j ⟶ j'`, is an arbitrary choice of morphism `eq_hom f f' : eq f f' ⟶ j` such that `eq_condition : eq_hom f f' ≫ f = eq_hom f f' ≫ f'`. Its existence is ensured by `is_cofiltered`. -/ noncomputable def eq_hom {j j' : C} (f f' : j ⟶ j') : eq f f' ⟶ j := (is_cofiltered_or_empty.cocone_maps f f').some_spec.some /-- `eq_condition f f'`, for morphisms `f f' : j ⟶ j'`, is the proof that `eq_hom f f' ≫ f = eq_hom f f' ≫ f'`. -/ @[simp, reassoc] lemma eq_condition {j j' : C} (f f' : j ⟶ j') : eq_hom f f' ≫ f = eq_hom f f' ≫ f' := (is_cofiltered_or_empty.cocone_maps f f').some_spec.some_spec open category_theory.limits /-- Any finite collection of objects in a cofiltered category has an object "to the left". -/ lemma inf_objs_exists (O : finset C) : ∃ (S : C), ∀ {X}, X ∈ O → _root_.nonempty (S ⟶ X) := begin classical, apply finset.induction_on O, { exact ⟨is_cofiltered.nonempty.some, (by rintros - ⟨⟩)⟩, }, { rintros X O' nm ⟨S', w'⟩, use min X S', rintros Y mY, by_cases h : X = Y, { subst h, exact ⟨min_to_left _ _⟩, }, { exact ⟨min_to_right _ _ ≫ (w' (by finish)).some⟩, }, } end variables (O : finset C) (H : finset (Σ' (X Y : C) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y)) /-- Given any `finset` of objects `{X, ...}` and indexed collection of `finset`s of morphisms `{f, ...}` in `C`, there exists an object `S`, with a morphism `T X : S ⟶ X` from each `X`, such that the triangles commute: `T X ≫ f = T Y`, for `f : X ⟶ Y` in the `finset`. -/ lemma inf_exists : ∃ (S : C) (T : Π {X : C}, X ∈ O → (S ⟶ X)), ∀ {X Y : C} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟶ Y}, (⟨X, Y, mX, mY, f⟩ : (Σ' (X Y : C) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y)) ∈ H → T mX ≫ f = T mY := begin classical, apply finset.induction_on H, { obtain ⟨S, f⟩ := inf_objs_exists O, refine ⟨S, λ X mX, (f mX).some, _⟩, rintros - - - - - ⟨⟩, }, { rintros ⟨X, Y, mX, mY, f⟩ H' nmf ⟨S', T', w'⟩, refine ⟨eq (T' mX ≫ f) (T' mY), λ Z mZ, eq_hom (T' mX ≫ f) (T' mY) ≫ T' mZ, _⟩, intros X' Y' mX' mY' f' mf', rw [category.assoc], by_cases h : X = X' ∧ Y = Y', { rcases h with ⟨rfl, rfl⟩, by_cases hf : f = f', { subst hf, apply eq_condition, }, { rw @w' _ _ mX mY f' (by simpa [hf ∘ eq.symm] using mf') }, }, { rw @w' _ _ mX' mY' f' (by finish), }, }, end /-- An arbitrary choice of object "to the left" of a finite collection of objects `O` and morphisms `H`, making all the triangles commute. -/ noncomputable def inf : C := (inf_exists O H).some /-- The morphisms from `inf O H`. -/ noncomputable def inf_to {X : C} (m : X ∈ O) : inf O H ⟶ X := (inf_exists O H).some_spec.some m /-- The triangles consisting of a morphism in `H` and the maps from `inf O H` commute. -/ lemma inf_to_commutes {X Y : C} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟶ Y} (mf : (⟨X, Y, mX, mY, f⟩ : Σ' (X Y : C) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y) ∈ H) : inf_to O H mX ≫ f = inf_to O H mY := (inf_exists O H).some_spec.some_spec mX mY mf variables {J : Type v} [small_category J] [fin_category J] /-- If we have `is_cofiltered C`, then for any functor `F : J ⥤ C` with `fin_category J`, there exists a cone over `F`. -/ lemma cone_nonempty (F : J ⥤ C) : _root_.nonempty (cone F) := begin classical, let O := (finset.univ.image F.obj), let H : finset (Σ' (X Y : C) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y) := finset.univ.bUnion (λ X : J, finset.univ.bUnion (λ Y : J, finset.univ.image (λ f : X ⟶ Y, ⟨F.obj X, F.obj Y, by simp, by simp, F.map f⟩))), obtain ⟨Z, f, w⟩ := inf_exists O H, refine ⟨⟨Z, ⟨λ X, f (by simp), _⟩⟩⟩, intros j j' g, dsimp, simp only [category.id_comp], symmetry, apply w, simp only [finset.mem_univ, finset.mem_bUnion, exists_and_distrib_left, exists_prop_of_true, finset.mem_image], exact ⟨j, rfl, j', g, (by simp)⟩, end /-- An arbitrary choice of cone over `F : J ⥤ C`, for `fin_category J` and `is_cofiltered C`. -/ noncomputable def cone (F : J ⥤ C) : cone F := (cone_nonempty F).some variables {D : Type u₁} [category.{v₁} D] /-- If `C` is cofiltered, and we have a functor `L : C ⥤ D` with a right adjoint, then `D` is cofiltered. -/ lemma of_left_adjoint {L : C ⥤ D} {R : D ⥤ C} (h : L ⊣ R) : is_cofiltered D := { cocone_objs := λ X Y, ⟨L.obj (min (R.obj X) (R.obj Y)), (h.hom_equiv _ X).symm (min_to_left _ _), (h.hom_equiv _ Y).symm (min_to_right _ _), ⟨⟩⟩, cocone_maps := λ X Y f g, ⟨L.obj (eq (R.map f) (R.map g)), (h.hom_equiv _ _).symm (eq_hom _ _), by rw [← h.hom_equiv_naturality_right_symm, ← h.hom_equiv_naturality_right_symm, eq_condition]⟩, nonempty := is_cofiltered.nonempty.map L.obj } /-- If `C` is cofiltered, and we have a left adjoint functor `L : C ⥤ D`, then `D` is cofiltered. -/ lemma of_is_left_adjoint (L : C ⥤ D) [is_left_adjoint L] : is_cofiltered D := of_left_adjoint (adjunction.of_left_adjoint L) /-- Being cofiltered is preserved by equivalence of categories. -/ lemma of_equivalence (h : C ≌ D) : is_cofiltered D := of_left_adjoint h.to_adjunction end is_cofiltered section opposite open opposite instance is_cofiltered_op_of_is_filtered [is_filtered C] : is_cofiltered Cᵒᵖ := { cocone_objs := λ X Y, ⟨op (is_filtered.max X.unop Y.unop), (is_filtered.left_to_max _ _).op, (is_filtered.right_to_max _ _).op, trivial⟩, cocone_maps := λ X Y f g, ⟨op (is_filtered.coeq f.unop g.unop), (is_filtered.coeq_hom _ _).op, begin rw [(show f = f.unop.op, by simp), (show g = g.unop.op, by simp), ← op_comp, ← op_comp], congr' 1, exact is_filtered.coeq_condition f.unop g.unop, end⟩, nonempty := ⟨op is_filtered.nonempty.some⟩ } instance is_filtered_op_of_is_cofiltered [is_cofiltered C] : is_filtered Cᵒᵖ := { cocone_objs := λ X Y, ⟨op (is_cofiltered.min X.unop Y.unop), (is_cofiltered.min_to_left X.unop Y.unop).op, (is_cofiltered.min_to_right X.unop Y.unop).op, trivial⟩, cocone_maps := λ X Y f g, ⟨op (is_cofiltered.eq f.unop g.unop), (is_cofiltered.eq_hom f.unop g.unop).op, begin rw [(show f = f.unop.op, by simp), (show g = g.unop.op, by simp), ← op_comp, ← op_comp], congr' 1, exact is_cofiltered.eq_condition f.unop g.unop, end⟩, nonempty := ⟨op is_cofiltered.nonempty.some⟩ } end opposite end category_theory
e50a978955d9a7a1041e67977915450443307b12
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/stage0/src/Init/Data/Fin/Basic.lean
8bee150c287464686b21e7b544091a348ab2ba0f
[ "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
3,192
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.Nat.Div import Init.Data.Nat.Bitwise open Nat structure Fin (n : Nat) := (val : Nat) (isLt : val < n) namespace Fin protected def lt {n} (a b : Fin n) : Prop := a.val < b.val protected def le {n} (a b : Fin n) : Prop := a.val ≤ b.val instance {n} : HasLess (Fin n) := ⟨Fin.lt⟩ instance {n} : HasLessEq (Fin n) := ⟨Fin.le⟩ instance decLt {n} (a b : Fin n) : Decidable (a < b) := Nat.decLt _ _ instance decLe {n} (a b : Fin n) : Decidable (a ≤ b) := Nat.decLe _ _ def elim0.{u} {α : Sort u} : Fin 0 → α | ⟨_, h⟩ => absurd h (notLtZero _) variable {n : Nat} def ofNat {n : Nat} (a : Nat) : Fin (succ n) := ⟨a % succ n, Nat.modLt _ (Nat.zeroLtSucc _)⟩ def ofNat' {n : Nat} (a : Nat) (h : n > 0) : Fin n := ⟨a % n, Nat.modLt _ h⟩ private theorem mlt {n b : Nat} : ∀ {a}, n > a → b % n < n | 0, h => Nat.modLt _ h | a+1, h => have n > 0 from Nat.ltTrans (Nat.zeroLtSucc _) h; Nat.modLt _ this protected def add : Fin n → Fin n → Fin n | ⟨a, h⟩, ⟨b, _⟩ => ⟨(a + b) % n, mlt h⟩ protected def mul : Fin n → Fin n → Fin n | ⟨a, h⟩, ⟨b, _⟩ => ⟨(a * b) % n, mlt h⟩ protected def sub : Fin n → Fin n → Fin n | ⟨a, h⟩, ⟨b, _⟩ => ⟨(a + (n - b)) % n, mlt h⟩ /- Remark: mod/div/modn/land/lor can be defined without using (% n), but we are trying to minimize the number of Nat theorems needed to boostrap Lean. -/ protected def mod : Fin n → Fin n → Fin n | ⟨a, h⟩, ⟨b, _⟩ => ⟨(a % b) % n, mlt h⟩ protected def div : Fin n → Fin n → Fin n | ⟨a, h⟩, ⟨b, _⟩ => ⟨(a / b) % n, mlt h⟩ protected def modn : Fin n → Nat → Fin n | ⟨a, h⟩, m => ⟨(a % m) % n, mlt h⟩ def land : Fin n → Fin n → Fin n | ⟨a, h⟩, ⟨b, _⟩ => ⟨(Nat.land a b) % n, mlt h⟩ def lor : Fin n → Fin n → Fin n | ⟨a, h⟩, ⟨b, _⟩ => ⟨(Nat.lor a b) % n, mlt h⟩ instance : HasZero (Fin (succ n)) := ⟨⟨0, succPos n⟩⟩ instance : HasOne (Fin (succ n)) := ⟨ofNat 1⟩ instance : HasAdd (Fin n) := ⟨Fin.add⟩ instance : HasSub (Fin n) := ⟨Fin.sub⟩ instance : HasMul (Fin n) := ⟨Fin.mul⟩ instance : HasMod (Fin n) := ⟨Fin.mod⟩ instance : HasDiv (Fin n) := ⟨Fin.div⟩ instance : HasModN (Fin n) := ⟨Fin.modn⟩ theorem eqOfVeq : ∀ {i j : Fin n}, (val i) = (val j) → i = j | ⟨iv, ilt₁⟩, ⟨.(iv), ilt₂⟩, rfl => rfl theorem veqOfEq : ∀ {i j : Fin n}, i = j → (val i) = (val j) | ⟨iv, ilt⟩, .(_), rfl => rfl theorem neOfVne {i j : Fin n} (h : val i ≠ val j) : i ≠ j := fun h' => absurd (veqOfEq h') h theorem vneOfNe {i j : Fin n} (h : i ≠ j) : val i ≠ val j := fun h' => absurd (eqOfVeq h') h theorem modnLt : ∀ {m : Nat} (i : Fin n), m > 0 → (i %ₙ m).val < m | m, ⟨a, h⟩, hp => Nat.ltOfLeOfLt (modLe _ _) (modLt _ hp) end Fin open Fin instance (n : Nat) : DecidableEq (Fin n) := fun i j => decidableOfDecidableOfIff (decEq i.val j.val) ⟨eqOfVeq, veqOfEq⟩
d970f3e2ebb8e344c2ce05d5f9fad1b3a9a92fc7
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/field_theory/finite/basic.lean
505d9e97e807c15102b950ae8ba53d03bc048a8e
[ "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
19,864
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Joey van Langen, Casper Putz -/ import field_theory.separable import ring_theory.integral_domain import tactic.apply_fun /-! # Finite fields > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file contains basic results about finite fields. Throughout most of this file, `K` denotes a finite field and `q` is notation for the cardinality of `K`. See `ring_theory.integral_domain` for the fact that the unit group of a finite field is a cyclic group, as well as the fact that every finite integral domain is a field (`fintype.field_of_domain`). ## Main results 1. `fintype.card_units`: The unit group of a finite field is has cardinality `q - 1`. 2. `sum_pow_units`: The sum of `x^i`, where `x` ranges over the units of `K`, is - `q-1` if `q-1 ∣ i` - `0` otherwise 3. `finite_field.card`: The cardinality `q` is a power of the characteristic of `K`. See `card'` for a variant. ## Notation Throughout most of this file, `K` denotes a finite field and `q` is notation for the cardinality of `K`. ## Implementation notes While `fintype Kˣ` can be inferred from `fintype K` in the presence of `decidable_eq K`, in this file we take the `fintype Kˣ` argument directly to reduce the chance of typeclass diamonds, as `fintype` carries data. -/ variables {K : Type*} {R : Type*} local notation `q` := fintype.card K open finset function open_locale big_operators polynomial namespace finite_field section polynomial variables [comm_ring R] [is_domain R] open polynomial /-- The cardinality of a field is at most `n` times the cardinality of the image of a degree `n` polynomial -/ lemma card_image_polynomial_eval [decidable_eq R] [fintype R] {p : R[X]} (hp : 0 < p.degree) : fintype.card R ≤ nat_degree p * (univ.image (λ x, eval x p)).card := finset.card_le_mul_card_image _ _ (λ a _, calc _ = (p - C a).roots.to_finset.card : congr_arg card (by simp [finset.ext_iff, mem_roots_sub_C hp]) ... ≤ (p - C a).roots.card : multiset.to_finset_card_le _ ... ≤ _ : card_roots_sub_C' hp) /-- If `f` and `g` are quadratic polynomials, then the `f.eval a + g.eval b = 0` has a solution. -/ lemma exists_root_sum_quadratic [fintype R] {f g : R[X]} (hf2 : degree f = 2) (hg2 : degree g = 2) (hR : fintype.card R % 2 = 1) : ∃ a b, f.eval a + g.eval b = 0 := by letI := classical.dec_eq R; exact suffices ¬ disjoint (univ.image (λ x : R, eval x f)) (univ.image (λ x : R, eval x (-g))), begin simp only [disjoint_left, mem_image] at this, push_neg at this, rcases this with ⟨x, ⟨a, _, ha⟩, ⟨b, _, hb⟩⟩, exact ⟨a, b, by rw [ha, ← hb, eval_neg, neg_add_self]⟩ end, assume hd : disjoint _ _, lt_irrefl (2 * ((univ.image (λ x : R, eval x f)) ∪ (univ.image (λ x : R, eval x (-g)))).card) $ calc 2 * ((univ.image (λ x : R, eval x f)) ∪ (univ.image (λ x : R, eval x (-g)))).card ≤ 2 * fintype.card R : nat.mul_le_mul_left _ (finset.card_le_univ _) ... = fintype.card R + fintype.card R : two_mul _ ... < nat_degree f * (univ.image (λ x : R, eval x f)).card + nat_degree (-g) * (univ.image (λ x : R, eval x (-g))).card : add_lt_add_of_lt_of_le (lt_of_le_of_ne (card_image_polynomial_eval (by rw hf2; exact dec_trivial)) (mt (congr_arg (%2)) (by simp [nat_degree_eq_of_degree_eq_some hf2, hR]))) (card_image_polynomial_eval (by rw [degree_neg, hg2]; exact dec_trivial)) ... = 2 * (univ.image (λ x : R, eval x f) ∪ univ.image (λ x : R, eval x (-g))).card : by rw [card_disjoint_union hd]; simp [nat_degree_eq_of_degree_eq_some hf2, nat_degree_eq_of_degree_eq_some hg2, bit0, mul_add] end polynomial lemma prod_univ_units_id_eq_neg_one [comm_ring K] [is_domain K] [fintype Kˣ] : (∏ x : Kˣ, x) = (-1 : Kˣ) := begin classical, have : (∏ x in (@univ Kˣ _).erase (-1), x) = 1, from prod_involution (λ x _, x⁻¹) (by simp) (λ a, by simp [units.inv_eq_self_iff] {contextual := tt}) (λ a, by simp [@inv_eq_iff_eq_inv _ _ a]) (by simp), rw [← insert_erase (mem_univ (-1 : Kˣ)), prod_insert (not_mem_erase _ _), this, mul_one] end section variables [group_with_zero K] [fintype K] lemma pow_card_sub_one_eq_one (a : K) (ha : a ≠ 0) : a ^ (q - 1) = 1 := calc a ^ (fintype.card K - 1) = (units.mk0 a ha ^ (fintype.card K - 1) : Kˣ) : by rw [units.coe_pow, units.coe_mk0] ... = 1 : by { classical, rw [← fintype.card_units, pow_card_eq_one], refl } lemma pow_card (a : K) : a ^ q = a := begin have hp : 0 < fintype.card K := lt_trans zero_lt_one fintype.one_lt_card, by_cases h : a = 0, { rw h, apply zero_pow hp }, rw [← nat.succ_pred_eq_of_pos hp, pow_succ, nat.pred_eq_sub_one, pow_card_sub_one_eq_one a h, mul_one], end lemma pow_card_pow (n : ℕ) (a : K) : a ^ q ^ n = a := begin induction n with n ih, { simp, }, { simp [pow_succ, pow_mul, ih, pow_card], }, end end variables (K) [field K] [fintype K] theorem card (p : ℕ) [char_p K p] : ∃ (n : ℕ+), nat.prime p ∧ q = p^(n : ℕ) := begin haveI hp : fact p.prime := ⟨char_p.char_is_prime K p⟩, letI : module (zmod p) K := { .. (zmod.cast_hom dvd_rfl K : zmod p →+* _).to_module }, obtain ⟨n, h⟩ := vector_space.card_fintype (zmod p) K, rw zmod.card at h, refine ⟨⟨n, _⟩, hp.1, h⟩, apply or.resolve_left (nat.eq_zero_or_pos n), rintro rfl, rw pow_zero at h, have : (0 : K) = 1, { apply fintype.card_le_one_iff.mp (le_of_eq h) }, exact absurd this zero_ne_one, end -- this statement doesn't use `q` because we want `K` to be an explicit parameter theorem card' : ∃ (p : ℕ) (n : ℕ+), nat.prime p ∧ fintype.card K = p^(n : ℕ) := let ⟨p, hc⟩ := char_p.exists K in ⟨p, @finite_field.card K _ _ p hc⟩ @[simp] lemma cast_card_eq_zero : (q : K) = 0 := begin rcases char_p.exists K with ⟨p, _char_p⟩, resetI, rcases card K p with ⟨n, hp, hn⟩, simp only [char_p.cast_eq_zero_iff K p, hn], conv { congr, rw [← pow_one p] }, exact pow_dvd_pow _ n.2, end lemma forall_pow_eq_one_iff (i : ℕ) : (∀ x : Kˣ, x ^ i = 1) ↔ q - 1 ∣ i := begin classical, obtain ⟨x, hx⟩ := is_cyclic.exists_generator Kˣ, rw [←fintype.card_units, ←order_of_eq_card_of_forall_mem_zpowers hx, order_of_dvd_iff_pow_eq_one], split, { intro h, apply h }, { intros h y, simp_rw ← mem_powers_iff_mem_zpowers at hx, rcases hx y with ⟨j, rfl⟩, rw [← pow_mul, mul_comm, pow_mul, h, one_pow], } end /-- The sum of `x ^ i` as `x` ranges over the units of a finite field of cardinality `q` is equal to `0` unless `(q - 1) ∣ i`, in which case the sum is `q - 1`. -/ lemma sum_pow_units [fintype Kˣ] (i : ℕ) : ∑ x : Kˣ, (x ^ i : K) = if (q - 1) ∣ i then -1 else 0 := begin let φ : Kˣ →* K := { to_fun := λ x, x ^ i, map_one' := by rw [units.coe_one, one_pow], map_mul' := by { intros, rw [units.coe_mul, mul_pow] } }, haveI : decidable (φ = 1), { classical, apply_instance }, calc ∑ x : Kˣ, φ x = if φ = 1 then fintype.card Kˣ else 0 : sum_hom_units φ ... = if (q - 1) ∣ i then -1 else 0 : _, suffices : (q - 1) ∣ i ↔ φ = 1, { simp only [this], split_ifs with h h, swap, refl, rw [fintype.card_units, nat.cast_sub, cast_card_eq_zero, nat.cast_one, zero_sub], show 1 ≤ q, from fintype.card_pos_iff.mpr ⟨0⟩ }, rw [← forall_pow_eq_one_iff, monoid_hom.ext_iff], apply forall_congr, intro x, rw [units.ext_iff, units.coe_pow, units.coe_one, monoid_hom.one_apply], refl, end /-- The sum of `x ^ i` as `x` ranges over a finite field of cardinality `q` is equal to `0` if `i < q - 1`. -/ lemma sum_pow_lt_card_sub_one (i : ℕ) (h : i < q - 1) : ∑ x : K, x ^ i = 0 := begin by_cases hi : i = 0, { simp only [hi, nsmul_one, sum_const, pow_zero, card_univ, cast_card_eq_zero], }, classical, have hiq : ¬ (q - 1) ∣ i, { contrapose! h, exact nat.le_of_dvd (nat.pos_of_ne_zero hi) h }, let φ : Kˣ ↪ K := ⟨coe, units.ext⟩, have : univ.map φ = univ \ {0}, { ext x, simp only [true_and, embedding.coe_fn_mk, mem_sdiff, units.exists_iff_ne_zero, mem_univ, mem_map, exists_prop_of_true, mem_singleton] }, calc ∑ x : K, x ^ i = ∑ x in univ \ {(0 : K)}, x ^ i : by rw [← sum_sdiff ({0} : finset K).subset_univ, sum_singleton, zero_pow (nat.pos_of_ne_zero hi), add_zero] ... = ∑ x : Kˣ, x ^ i : by { rw [← this, univ.sum_map φ], refl } ... = 0 : by { rw [sum_pow_units K i, if_neg], exact hiq, } end open polynomial section variables (K' : Type*) [field K'] {p n : ℕ} lemma X_pow_card_sub_X_nat_degree_eq (hp : 1 < p) : (X ^ p - X : K'[X]).nat_degree = p := begin have h1 : (X : K'[X]).degree < (X ^ p : K'[X]).degree, { rw [degree_X_pow, degree_X], exact_mod_cast hp }, rw [nat_degree_eq_of_degree_eq (degree_sub_eq_left_of_degree_lt h1), nat_degree_X_pow], end lemma X_pow_card_pow_sub_X_nat_degree_eq (hn : n ≠ 0) (hp : 1 < p) : (X ^ p ^ n - X : K'[X]).nat_degree = p ^ n := X_pow_card_sub_X_nat_degree_eq K' $ nat.one_lt_pow _ _ (nat.pos_of_ne_zero hn) hp lemma X_pow_card_sub_X_ne_zero (hp : 1 < p) : (X ^ p - X : K'[X]) ≠ 0 := ne_zero_of_nat_degree_gt $ calc 1 < _ : hp ... = _ : (X_pow_card_sub_X_nat_degree_eq K' hp).symm lemma X_pow_card_pow_sub_X_ne_zero (hn : n ≠ 0) (hp : 1 < p) : (X ^ p ^ n - X : K'[X]) ≠ 0 := X_pow_card_sub_X_ne_zero K' $ nat.one_lt_pow _ _ (nat.pos_of_ne_zero hn) hp end variables (p : ℕ) [fact p.prime] [algebra (zmod p) K] lemma roots_X_pow_card_sub_X : roots (X^q - X : K[X]) = finset.univ.val := begin classical, have aux : (X^q - X : K[X]) ≠ 0 := X_pow_card_sub_X_ne_zero K fintype.one_lt_card, have : (roots (X^q - X : K[X])).to_finset = finset.univ, { rw eq_univ_iff_forall, intro x, rw [multiset.mem_to_finset, mem_roots aux, is_root.def, eval_sub, eval_pow, eval_X, sub_eq_zero, pow_card] }, rw [←this, multiset.to_finset_val, eq_comm, multiset.dedup_eq_self], apply nodup_roots, rw separable_def, convert is_coprime_one_right.neg_right using 1, { rw [derivative_sub, derivative_X, derivative_X_pow, char_p.cast_card_eq_zero K, C_0, zero_mul, zero_sub] }, end variables {K} theorem frobenius_pow {p : ℕ} [fact p.prime] [char_p K p] {n : ℕ} (hcard : q = p^n) : (frobenius K p) ^ n = 1 := begin ext, conv_rhs { rw [ring_hom.one_def, ring_hom.id_apply, ← pow_card x, hcard], }, clear hcard, induction n, {simp}, rw [pow_succ, pow_succ', pow_mul, ring_hom.mul_def, ring_hom.comp_apply, frobenius_def, n_ih] end open polynomial lemma expand_card (f : K[X]) : expand K q f = f ^ q := begin cases char_p.exists K with p hp, letI := hp, rcases finite_field.card K p with ⟨⟨n, npos⟩, ⟨hp, hn⟩⟩, haveI : fact p.prime := ⟨hp⟩, dsimp at hn, rw [hn, ← map_expand_pow_char, frobenius_pow hn, ring_hom.one_def, map_id] end end finite_field namespace zmod open finite_field polynomial lemma sq_add_sq (p : ℕ) [hp : fact p.prime] (x : zmod p) : ∃ a b : zmod p, a^2 + b^2 = x := begin cases hp.1.eq_two_or_odd with hp2 hp_odd, { substI p, change fin 2 at x, fin_cases x, { use 0, simp }, { use [0, 1], simp } }, let f : (zmod p)[X] := X^2, let g : (zmod p)[X] := X^2 - C x, obtain ⟨a, b, hab⟩ : ∃ a b, f.eval a + g.eval b = 0 := @exists_root_sum_quadratic _ _ _ _ f g (degree_X_pow 2) (degree_X_pow_sub_C dec_trivial _) (by rw [zmod.card, hp_odd]), refine ⟨a, b, _⟩, rw ← sub_eq_zero, simpa only [eval_C, eval_X, eval_pow, eval_sub, ← add_sub_assoc] using hab, end end zmod namespace char_p lemma sq_add_sq (R : Type*) [comm_ring R] [is_domain R] (p : ℕ) [ne_zero p] [char_p R p] (x : ℤ) : ∃ a b : ℕ, (a^2 + b^2 : R) = x := begin haveI := char_is_prime_of_pos R p, obtain ⟨a, b, hab⟩ := zmod.sq_add_sq p x, refine ⟨a.val, b.val, _⟩, simpa using congr_arg (zmod.cast_hom dvd_rfl R) hab end end char_p open_locale nat open zmod /-- The **Fermat-Euler totient theorem**. `nat.modeq.pow_totient` is an alternative statement of the same theorem. -/ @[simp] lemma zmod.pow_totient {n : ℕ} (x : (zmod n)ˣ) : x ^ φ n = 1 := begin cases n, { rw [nat.totient_zero, pow_zero] }, { rw [← card_units_eq_totient, pow_card_eq_one] } end /-- The **Fermat-Euler totient theorem**. `zmod.pow_totient` is an alternative statement of the same theorem. -/ lemma nat.modeq.pow_totient {x n : ℕ} (h : nat.coprime x n) : x ^ φ n ≡ 1 [MOD n] := begin rw ← zmod.eq_iff_modeq_nat, let x' : units (zmod n) := zmod.unit_of_coprime _ h, have := zmod.pow_totient x', apply_fun (coe : units (zmod n) → zmod n) at this, simpa only [-zmod.pow_totient, nat.succ_eq_add_one, nat.cast_pow, units.coe_one, nat.cast_one, coe_unit_of_coprime, units.coe_pow], end section variables {V : Type*} [fintype K] [division_ring K] [add_comm_group V] [module K V] -- should this go in a namespace? -- finite_dimensional would be natural, -- but we don't assume it... lemma card_eq_pow_finrank [fintype V] : fintype.card V = q ^ (finite_dimensional.finrank K V) := begin let b := is_noetherian.finset_basis K V, rw [module.card_fintype b, ← finite_dimensional.finrank_eq_card_basis b], end end open finite_field namespace zmod /-- A variation on Fermat's little theorem. See `zmod.pow_card_sub_one_eq_one` -/ @[simp] lemma pow_card {p : ℕ} [fact p.prime] (x : zmod p) : x ^ p = x := by { have h := finite_field.pow_card x, rwa zmod.card p at h } @[simp] lemma pow_card_pow {n p : ℕ} [fact p.prime] (x : zmod p) : x ^ p ^ n = x := begin induction n with n ih, { simp, }, { simp [pow_succ, pow_mul, ih, pow_card], }, end @[simp] lemma frobenius_zmod (p : ℕ) [fact p.prime] : frobenius (zmod p) p = ring_hom.id _ := by { ext a, rw [frobenius_def, zmod.pow_card, ring_hom.id_apply] } @[simp] lemma card_units (p : ℕ) [fact p.prime] : fintype.card ((zmod p)ˣ) = p - 1 := by rw [fintype.card_units, card] /-- **Fermat's Little Theorem**: for every unit `a` of `zmod p`, we have `a ^ (p - 1) = 1`. -/ theorem units_pow_card_sub_one_eq_one (p : ℕ) [fact p.prime] (a : (zmod p)ˣ) : a ^ (p - 1) = 1 := by rw [← card_units p, pow_card_eq_one] /-- **Fermat's Little Theorem**: for all nonzero `a : zmod p`, we have `a ^ (p - 1) = 1`. -/ theorem pow_card_sub_one_eq_one {p : ℕ} [fact p.prime] {a : zmod p} (ha : a ≠ 0) : a ^ (p - 1) = 1 := by { have h := pow_card_sub_one_eq_one a ha, rwa zmod.card p at h } theorem order_of_units_dvd_card_sub_one {p : ℕ} [fact p.prime] (u : (zmod p)ˣ) : order_of u ∣ p - 1 := order_of_dvd_of_pow_eq_one $ units_pow_card_sub_one_eq_one _ _ theorem order_of_dvd_card_sub_one {p : ℕ} [fact p.prime] {a : zmod p} (ha : a ≠ 0) : order_of a ∣ p - 1 := order_of_dvd_of_pow_eq_one $ pow_card_sub_one_eq_one ha open polynomial lemma expand_card {p : ℕ} [fact p.prime] (f : polynomial (zmod p)) : expand (zmod p) p f = f ^ p := by { have h := finite_field.expand_card f, rwa zmod.card p at h } end zmod /-- **Fermat's Little Theorem**: for all `a : ℤ` coprime to `p`, we have `a ^ (p - 1) ≡ 1 [ZMOD p]`. -/ lemma int.modeq.pow_card_sub_one_eq_one {p : ℕ} (hp : nat.prime p) {n : ℤ} (hpn : is_coprime n p) : n ^ (p - 1) ≡ 1 [ZMOD p] := begin haveI : fact p.prime := ⟨hp⟩, have : ¬ (n : zmod p) = 0, { rw [char_p.int_cast_eq_zero_iff _ p, ← (nat.prime_iff_prime_int.mp hp).coprime_iff_not_dvd], { exact hpn.symm }, exact zmod.char_p p }, simpa [← zmod.int_coe_eq_int_coe_iff] using zmod.pow_card_sub_one_eq_one this end section namespace finite_field variables {F : Type*} [field F] section finite variables [finite F] /-- In a finite field of characteristic `2`, all elements are squares. -/ lemma is_square_of_char_two (hF : ring_char F = 2) (a : F) : is_square a := begin haveI hF' : char_p F 2 := ring_char.of_eq hF, exact is_square_of_char_two' a, end /-- In a finite field of odd characteristic, not every element is a square. -/ lemma exists_nonsquare (hF : ring_char F ≠ 2) : ∃ (a : F), ¬ is_square a := begin -- Idea: the squaring map on `F` is not injective, hence not surjective let sq : F → F := λ x, x ^ 2, have h : ¬ injective sq, { simp only [injective, not_forall, exists_prop], refine ⟨-1, 1, _, ring.neg_one_ne_one_of_char_ne_two hF⟩, simp only [sq, one_pow, neg_one_sq] }, rw finite.injective_iff_surjective at h, -- sq not surjective simp_rw [is_square, ←pow_two, @eq_comm _ _ (_ ^ 2)], push_neg at ⊢ h, exact h, end end finite variables [fintype F] /-- The finite field `F` has even cardinality iff it has characteristic `2`. -/ lemma even_card_iff_char_two : ring_char F = 2 ↔ fintype.card F % 2 = 0 := begin rcases finite_field.card F (ring_char F) with ⟨n, hp, h⟩, rw [h, nat.pow_mod], split, { intro hF, rw hF, simp only [nat.bit0_mod_two, zero_pow', ne.def, pnat.ne_zero, not_false_iff, nat.zero_mod], }, { rw [← nat.even_iff, nat.even_pow], rintros ⟨hev, hnz⟩, rw [nat.even_iff, nat.mod_mod] at hev, exact (nat.prime.eq_two_or_odd hp).resolve_right (ne_of_eq_of_ne hev zero_ne_one), }, end lemma even_card_of_char_two (hF : ring_char F = 2) : fintype.card F % 2 = 0 := even_card_iff_char_two.mp hF lemma odd_card_of_char_ne_two (hF : ring_char F ≠ 2) : fintype.card F % 2 = 1 := nat.mod_two_ne_zero.mp (mt even_card_iff_char_two.mpr hF) /-- If `F` has odd characteristic, then for nonzero `a : F`, we have that `a ^ (#F / 2) = ±1`. -/ lemma pow_dichotomy (hF : ring_char F ≠ 2) {a : F} (ha : a ≠ 0) : a ^ (fintype.card F / 2) = 1 ∨ a ^ (fintype.card F / 2) = -1 := begin have h₁ := finite_field.pow_card_sub_one_eq_one a ha, rw [← nat.two_mul_odd_div_two (finite_field.odd_card_of_char_ne_two hF), mul_comm, pow_mul, pow_two] at h₁, exact mul_self_eq_one_iff.mp h₁, end /-- A unit `a` of a finite field `F` of odd characteristic is a square if and only if `a ^ (#F / 2) = 1`. -/ lemma unit_is_square_iff (hF : ring_char F ≠ 2) (a : Fˣ) : is_square a ↔ a ^ (fintype.card F / 2) = 1 := begin classical, obtain ⟨g, hg⟩ := is_cyclic.exists_generator Fˣ, obtain ⟨n, hn⟩ : a ∈ submonoid.powers g, { rw mem_powers_iff_mem_zpowers, apply hg }, have hodd := nat.two_mul_odd_div_two (finite_field.odd_card_of_char_ne_two hF), split, { rintro ⟨y, rfl⟩, rw [← pow_two, ← pow_mul, hodd], apply_fun (@coe Fˣ F _) using units.ext, { push_cast, exact finite_field.pow_card_sub_one_eq_one (y : F) (units.ne_zero y), }, }, { subst a, assume h, have key : 2 * (fintype.card F / 2) ∣ n * (fintype.card F / 2), { rw [← pow_mul] at h, rw [hodd, ← fintype.card_units, ← order_of_eq_card_of_forall_mem_zpowers hg], apply order_of_dvd_of_pow_eq_one h }, have : 0 < fintype.card F / 2 := nat.div_pos fintype.one_lt_card (by norm_num), obtain ⟨m, rfl⟩ := nat.dvd_of_mul_dvd_mul_right this key, refine ⟨g ^ m, _⟩, rw [mul_comm, pow_mul, pow_two], }, end /-- A non-zero `a : F` is a square if and only if `a ^ (#F / 2) = 1`. -/ lemma is_square_iff (hF : ring_char F ≠ 2) {a : F} (ha : a ≠ 0) : is_square a ↔ a ^ (fintype.card F / 2) = 1 := begin apply (iff_congr _ (by simp [units.ext_iff])).mp (finite_field.unit_is_square_iff hF (units.mk0 a ha)), simp only [is_square, units.ext_iff, units.coe_mk0, units.coe_mul], split, { rintro ⟨y, hy⟩, exact ⟨y, hy⟩ }, { rintro ⟨y, rfl⟩, have hy : y ≠ 0, { rintro rfl, simpa [zero_pow] using ha, }, refine ⟨units.mk0 y hy, _⟩, simp, } end end finite_field end
7f10aab67f2f95531b758f9199190b88b6966cd2
367134ba5a65885e863bdc4507601606690974c1
/src/category_theory/category/default.lean
e6a2d432f11ed064cebdac5f6619a63ed9d986f8
[ "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
10,997
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Stephen Morgan, Scott Morrison, Johannes Hölzl, Reid Barton -/ import tactic.basic /-! # Categories Defines a category, as a type class parametrised by the type of objects. ## Notations Introduces notations * `X ⟶ Y` for the morphism spaces, * `f ≫ g` for composition in the 'arrows' convention. Users may like to add `f ⊚ g` for composition in the standard convention, using ```lean local notation f ` ⊚ `:80 g:80 := category.comp g f -- type as \oo ``` -/ -- The order in this declaration matters: v often needs to be explicitly specified while u often -- can be omitted universes v u namespace category_theory /-- A 'notation typeclass' on the way to defining a category. -/ class has_hom (obj : Type u) : Type (max u (v+1)) := (hom : obj → obj → Type v) infixr ` ⟶ `:10 := has_hom.hom -- type as \h /-- A preliminary structure on the way to defining a category, containing the data, but none of the axioms. -/ class category_struct (obj : Type u) extends has_hom.{v} obj : Type (max u (v+1)) := (id : Π X : obj, hom X X) (comp : Π {X Y Z : obj}, (X ⟶ Y) → (Y ⟶ Z) → (X ⟶ Z)) notation `𝟙` := category_struct.id -- type as \b1 infixr ` ≫ `:80 := category_struct.comp -- type as \gg /-- The typeclass `category C` describes morphisms associated to objects of type `C`. The universe levels of the objects and morphisms are unconstrained, and will often need to be specified explicitly, as `category.{v} C`. (See also `large_category` and `small_category`.) See https://stacks.math.columbia.edu/tag/0014. -/ class category (obj : Type u) extends category_struct.{v} obj : Type (max u (v+1)) := (id_comp' : ∀ {X Y : obj} (f : hom X Y), 𝟙 X ≫ f = f . obviously) (comp_id' : ∀ {X Y : obj} (f : hom X Y), f ≫ 𝟙 Y = f . obviously) (assoc' : ∀ {W X Y Z : obj} (f : hom W X) (g : hom X Y) (h : hom Y Z), (f ≫ g) ≫ h = f ≫ (g ≫ h) . obviously) -- `restate_axiom` is a command that creates a lemma from a structure field, -- discarding any auto_param wrappers from the type. -- (It removes a backtick from the name, if it finds one, and otherwise adds "_lemma".) restate_axiom category.id_comp' restate_axiom category.comp_id' restate_axiom category.assoc' attribute [simp] category.id_comp category.comp_id category.assoc attribute [trans] category_struct.comp /-- A `large_category` has objects in one universe level higher than the universe level of the morphisms. It is useful for examples such as the category of types, or the category of groups, etc. -/ abbreviation large_category (C : Type (u+1)) : Type (u+1) := category.{u} C /-- A `small_category` has objects and morphisms in the same universe level. -/ abbreviation small_category (C : Type u) : Type (u+1) := category.{u} C section variables {C : Type u} [category.{v} C] {X Y Z : C} /-- postcompose an equation between morphisms by another morphism -/ lemma eq_whisker {f g : X ⟶ Y} (w : f = g) (h : Y ⟶ Z) : f ≫ h = g ≫ h := by rw w /-- precompose an equation between morphisms by another morphism -/ lemma whisker_eq (f : X ⟶ Y) {g h : Y ⟶ Z} (w : g = h) : f ≫ g = f ≫ h := by rw w infixr ` =≫ `:80 := eq_whisker infixr ` ≫= `:80 := whisker_eq lemma eq_of_comp_left_eq {f g : X ⟶ Y} (w : ∀ {Z : C} (h : Y ⟶ Z), f ≫ h = g ≫ h) : f = g := by { convert w (𝟙 Y), tidy } lemma eq_of_comp_right_eq {f g : Y ⟶ Z} (w : ∀ {X : C} (h : X ⟶ Y), h ≫ f = h ≫ g) : f = g := by { convert w (𝟙 Y), tidy } lemma eq_of_comp_left_eq' (f g : X ⟶ Y) (w : (λ {Z : C} (h : Y ⟶ Z), f ≫ h) = (λ {Z : C} (h : Y ⟶ Z), g ≫ h)) : f = g := eq_of_comp_left_eq (λ Z h, by convert congr_fun (congr_fun w Z) h) lemma eq_of_comp_right_eq' (f g : Y ⟶ Z) (w : (λ {X : C} (h : X ⟶ Y), h ≫ f) = (λ {X : C} (h : X ⟶ Y), h ≫ g)) : f = g := eq_of_comp_right_eq (λ X h, by convert congr_fun (congr_fun w X) h) lemma id_of_comp_left_id (f : X ⟶ X) (w : ∀ {Y : C} (g : X ⟶ Y), f ≫ g = g) : f = 𝟙 X := by { convert w (𝟙 X), tidy } lemma id_of_comp_right_id (f : X ⟶ X) (w : ∀ {Y : C} (g : Y ⟶ X), g ≫ f = g) : f = 𝟙 X := by { convert w (𝟙 X), tidy } lemma comp_dite {P : Prop} [decidable P] {X Y Z : C} (f : X ⟶ Y) (g : P → (Y ⟶ Z)) (g' : ¬P → (Y ⟶ Z)) : (f ≫ if h : P then g h else g' h) = (if h : P then f ≫ g h else f ≫ g' h) := by { split_ifs; refl } lemma dite_comp {P : Prop} [decidable P] {X Y Z : C} (f : P → (X ⟶ Y)) (f' : ¬P → (X ⟶ Y)) (g : Y ⟶ Z) : (if h : P then f h else f' h) ≫ g = (if h : P then f h ≫ g else f' h ≫ g) := by { split_ifs; refl } /-- A morphism `f` is an epimorphism if it can be "cancelled" when precomposed: `f ≫ g = f ≫ h` implies `g = h`. See https://stacks.math.columbia.edu/tag/003B. -/ class epi (f : X ⟶ Y) : Prop := (left_cancellation : Π {Z : C} (g h : Y ⟶ Z) (w : f ≫ g = f ≫ h), g = h) /-- A morphism `f` is a monomorphism if it can be "cancelled" when postcomposed: `g ≫ f = h ≫ f` implies `g = h`. See https://stacks.math.columbia.edu/tag/003B. -/ class mono (f : X ⟶ Y) : Prop := (right_cancellation : Π {Z : C} (g h : Z ⟶ X) (w : g ≫ f = h ≫ f), g = h) instance (X : C) : epi (𝟙 X) := ⟨λ Z g h w, by simpa using w⟩ instance (X : C) : mono (𝟙 X) := ⟨λ Z g h w, by simpa using w⟩ lemma cancel_epi (f : X ⟶ Y) [epi f] {g h : Y ⟶ Z} : (f ≫ g = f ≫ h) ↔ g = h := ⟨ λ p, epi.left_cancellation g h p, begin intro a, subst a end ⟩ lemma cancel_mono (f : X ⟶ Y) [mono f] {g h : Z ⟶ X} : (g ≫ f = h ≫ f) ↔ g = h := ⟨ λ p, mono.right_cancellation g h p, begin intro a, subst a end ⟩ lemma cancel_epi_id (f : X ⟶ Y) [epi f] {h : Y ⟶ Y} : (f ≫ h = f) ↔ h = 𝟙 Y := by { convert cancel_epi f, simp, } lemma cancel_mono_id (f : X ⟶ Y) [mono f] {g : X ⟶ X} : (g ≫ f = f) ↔ g = 𝟙 X := by { convert cancel_mono f, simp, } lemma epi_comp {X Y Z : C} (f : X ⟶ Y) [epi f] (g : Y ⟶ Z) [epi g] : epi (f ≫ g) := begin split, intros Z a b w, apply (cancel_epi g).1, apply (cancel_epi f).1, simpa using w, end lemma mono_comp {X Y Z : C} (f : X ⟶ Y) [mono f] (g : Y ⟶ Z) [mono g] : mono (f ≫ g) := begin split, intros Z a b w, apply (cancel_mono f).1, apply (cancel_mono g).1, simpa using w, end lemma mono_of_mono {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) [mono (f ≫ g)] : mono f := begin split, intros Z a b w, replace w := congr_arg (λ k, k ≫ g) w, dsimp at w, rw [category.assoc, category.assoc] at w, exact (cancel_mono _).1 w, end lemma mono_of_mono_fac {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} {h : X ⟶ Z} [mono h] (w : f ≫ g = h) : mono f := by { substI h, exact mono_of_mono f g, } lemma epi_of_epi {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) [epi (f ≫ g)] : epi g := begin split, intros Z a b w, replace w := congr_arg (λ k, f ≫ k) w, dsimp at w, rw [←category.assoc, ←category.assoc] at w, exact (cancel_epi _).1 w, end lemma epi_of_epi_fac {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} {h : X ⟶ Z} [epi h] (w : f ≫ g = h) : epi g := by substI h; exact epi_of_epi f g end section variable (C : Type u) variable [category.{v} C] universe u' instance ulift_category : category.{v} (ulift.{u'} C) := { hom := λ X Y, (X.down ⟶ Y.down), id := λ X, 𝟙 X.down, comp := λ _ _ _ f g, f ≫ g } -- We verify that this previous instance can lift small categories to large categories. example (D : Type u) [small_category D] : large_category (ulift.{u+1} D) := by apply_instance end end category_theory open category_theory /-! We now put a category instance on any preorder. Because we do not allow the morphisms of a category to live in `Prop`, unfortunately we need to use `plift` and `ulift` when defining the morphisms. As convenience functions, we provide `hom_of_le` and `le_of_hom` to wrap and unwrap inequalities. -/ namespace preorder variables (α : Type u) /-- The category structure coming from a preorder. There is a morphism `X ⟶ Y` if and only if `X ≤ Y`. Because we don't allow morphisms to live in `Prop`, we have to define `X ⟶ Y` as `ulift (plift (X ≤ Y))`. See `category_theory.hom_of_le` and `category_theory.le_of_hom`. See https://stacks.math.columbia.edu/tag/00D3. -/ @[priority 100] -- see Note [lower instance priority] instance small_category [preorder α] : small_category α := { hom := λ U V, ulift (plift (U ≤ V)), id := λ X, ⟨ ⟨ le_refl X ⟩ ⟩, comp := λ X Y Z f g, ⟨ ⟨ le_trans _ _ _ f.down.down g.down.down ⟩ ⟩ } end preorder namespace category_theory variables {α : Type u} [preorder α] /-- Express an inequality as a morphism in the corresponding preorder category. -/ def hom_of_le {U V : α} (h : U ≤ V) : U ⟶ V := ulift.up (plift.up h) @[simp] lemma hom_of_le_refl {U : α} : hom_of_le (le_refl U) = 𝟙 U := rfl @[simp] lemma hom_of_le_comp {U V W : α} (h : U ≤ V) (k : V ≤ W) : hom_of_le h ≫ hom_of_le k = hom_of_le (h.trans k) := rfl /-- Extract the underlying inequality from a morphism in a preorder category. -/ lemma le_of_hom {U V : α} (h : U ⟶ V) : U ≤ V := h.down.down @[simp] lemma le_of_hom_hom_of_le {a b : α} (h : a ≤ b) : le_of_hom (hom_of_le h) = h := rfl @[simp] lemma hom_of_le_le_of_hom {a b : α} (h : a ⟶ b) : hom_of_le (le_of_hom h) = h := by { cases h, cases h, refl, } end category_theory /-- Many proofs in the category theory library use the `dsimp, simp` pattern, which typically isn't necessary elsewhere. One would usually hope that the same effect could be achieved simply with `simp`. The essential issue is that composition of morphisms involves dependent types. When you have a chain of morphisms being composed, say `f : X ⟶ Y` and `g : Y ⟶ Z`, then `simp` can operate succesfully on the morphisms (e.g. if `f` is the identity it can strip that off). However if we have an equality of objects, say `Y = Y'`, then `simp` can't operate because it would break the typing of the composition operations. We rarely have interesting equalities of objects (because that would be "evil" --- anything interesting should be expressed as an isomorphism and tracked explicitly), except of course that we have plenty of definitional equalities of objects. `dsimp` can apply these safely, even inside a composition. After `dsimp` has cleared up the object level, `simp` can resume work on the morphism level --- but without the `dsimp` step, because `simp` looks at expressions syntactically, the relevant lemmas might not fire. There's no bound on how many times you potentially could have to switch back and forth, if the `simp` introduced new objects we again need to `dsimp`. In practice this does occur, but only rarely, because `simp` tends to shorten chains of compositions (i.e. not introduce new objects at all). -/ library_note "dsimp, simp"
4c89497833c9211164b19b384f7f620fd8de5356
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/ring_theory/ideal/over.lean
38431e07bfd8971b7f4f4db6cc47dfcbf815c643
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,667
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import ring_theory.algebraic import ring_theory.localization /-! # Ideals over/under ideals This file concerns ideals lying over other ideals. Let `f : R →+* S` be a ring homomorphism (typically a ring extension), `I` an ideal of `R` and `J` an ideal of `S`. We say `J` lies over `I` (and `I` under `J`) if `I` is the `f`-preimage of `J`. This is expressed here by writing `I = J.comap f`. ## Implementation notes The proofs of the `comap_ne_bot` and `comap_lt_comap` families use an approach specific for their situation: we construct an element in `I.comap f` from the coefficients of a minimal polynomial. Once mathlib has more material on the localization at a prime ideal, the results can be proven using more general going-up/going-down theory. -/ variables {R : Type*} [comm_ring R] namespace ideal open polynomial open submodule section comm_ring variables {S : Type*} [comm_ring S] {f : R →+* S} {I J : ideal S} lemma coeff_zero_mem_comap_of_root_mem_of_eval_mem {r : S} (hr : r ∈ I) {p : polynomial R} (hp : p.eval₂ f r ∈ I) : p.coeff 0 ∈ I.comap f := begin rw [←p.div_X_mul_X_add, eval₂_add, eval₂_C, eval₂_mul, eval₂_X] at hp, refine mem_comap.mpr ((I.add_mem_iff_right _).mp hp), exact I.mul_mem_left _ hr end lemma coeff_zero_mem_comap_of_root_mem {r : S} (hr : r ∈ I) {p : polynomial R} (hp : p.eval₂ f r = 0) : p.coeff 0 ∈ I.comap f := coeff_zero_mem_comap_of_root_mem_of_eval_mem hr (hp.symm ▸ I.zero_mem) lemma exists_coeff_ne_zero_mem_comap_of_non_zero_divisor_root_mem {r : S} (r_non_zero_divisor : ∀ {x}, x * r = 0 → x = 0) (hr : r ∈ I) {p : polynomial R} : ∀ (p_ne_zero : p ≠ 0) (hp : p.eval₂ f r = 0), ∃ i, p.coeff i ≠ 0 ∧ p.coeff i ∈ I.comap f := begin refine p.rec_on_horner _ _ _, { intro h, contradiction }, { intros p a coeff_eq_zero a_ne_zero ih p_ne_zero hp, refine ⟨0, _, coeff_zero_mem_comap_of_root_mem hr hp⟩, simp [coeff_eq_zero, a_ne_zero] }, { intros p p_nonzero ih mul_nonzero hp, rw [eval₂_mul, eval₂_X] at hp, obtain ⟨i, hi, mem⟩ := ih p_nonzero (r_non_zero_divisor hp), refine ⟨i + 1, _, _⟩; simp [hi, mem] } end /-- Let `P` be an ideal in `R[x]`. The map `R[x]/P → (R / (P ∩ R))[x] / (P / (P ∩ R))` is injective. -/ lemma injective_quotient_le_comap_map (P : ideal (polynomial R)) : function.injective ((map (map_ring_hom (quotient.mk (P.comap C))) P).quotient_map (map_ring_hom (quotient.mk (P.comap C))) le_comap_map) := begin refine quotient_map_injective' (le_of_eq _), rw comap_map_of_surjective (map_ring_hom (quotient.mk (P.comap C))) (map_surjective _ quotient.mk_surjective), refine le_antisymm (sup_le le_rfl _) (le_sup_of_le_left le_rfl), refine λ p hp, polynomial_mem_ideal_of_coeff_mem_ideal P p (λ n, quotient.eq_zero_iff_mem.mp _), simpa only [coeff_map, coe_map_ring_hom] using ext_iff.mp (ideal.mem_bot.mp (mem_comap.mp hp)) n, end /-- The identity in this lemma asserts that the "obvious" square ``` R → (R / (P ∩ R)) ↓ ↓ R[x] / P → (R / (P ∩ R))[x] / (P / (P ∩ R)) ``` commutes. It is used, for instance, in the proof of `quotient_mk_comp_C_is_integral_of_jacobson`, in the file `ring_theory/jacobson`. -/ lemma quotient_mk_maps_eq (P : ideal (polynomial R)) : ((quotient.mk (map (map_ring_hom (quotient.mk (P.comap C))) P)).comp C).comp (quotient.mk (P.comap C)) = ((map (map_ring_hom (quotient.mk (P.comap C))) P).quotient_map (map_ring_hom (quotient.mk (P.comap C))) le_comap_map).comp ((quotient.mk P).comp C) := begin refine ring_hom.ext (λ x, _), repeat { rw [ring_hom.coe_comp, function.comp_app] }, rw [quotient_map_mk, coe_map_ring_hom, map_C], end /-- This technical lemma asserts the existence of a polynomial `p` in an ideal `P ⊂ R[x]` that is non-zero in the quotient `R / (P ∩ R) [x]`. The assumptions are equivalent to `P ≠ 0` and `P ∩ R = (0)`. -/ lemma exists_nonzero_mem_of_ne_bot {P : ideal (polynomial R)} (Pb : P ≠ ⊥) (hP : ∀ (x : R), C x ∈ P → x = 0) : ∃ p : polynomial R, p ∈ P ∧ (polynomial.map (quotient.mk (P.comap C)) p) ≠ 0 := begin obtain ⟨m, hm⟩ := submodule.nonzero_mem_of_bot_lt (bot_lt_iff_ne_bot.mpr Pb), refine ⟨m, submodule.coe_mem m, λ pp0, hm (submodule.coe_eq_zero.mp _)⟩, refine (ring_hom.injective_iff (polynomial.map_ring_hom (quotient.mk (P.comap C)))).mp _ _ pp0, refine map_injective _ ((quotient.mk (P.comap C)).injective_iff_ker_eq_bot.mpr _), rw [mk_ker], exact (submodule.eq_bot_iff _).mpr (λ x hx, hP x (mem_comap.mp hx)), end end comm_ring section integral_domain variables {S : Type*} [comm_ring S] {f : R →+* S} {I J : ideal S} lemma exists_coeff_ne_zero_mem_comap_of_root_mem [integral_domain S] {r : S} (r_ne_zero : r ≠ 0) (hr : r ∈ I) {p : polynomial R} : ∀ (p_ne_zero : p ≠ 0) (hp : p.eval₂ f r = 0), ∃ i, p.coeff i ≠ 0 ∧ p.coeff i ∈ I.comap f := exists_coeff_ne_zero_mem_comap_of_non_zero_divisor_root_mem (λ _ h, or.resolve_right (mul_eq_zero.mp h) r_ne_zero) hr lemma exists_coeff_mem_comap_sdiff_comap_of_root_mem_sdiff [is_prime I] (hIJ : I ≤ J) {r : S} (hr : r ∈ (J : set S) \ I) {p : polynomial R} (p_ne_zero : p.map (quotient.mk (I.comap f)) ≠ 0) (hpI : p.eval₂ f r ∈ I) : ∃ i, p.coeff i ∈ (J.comap f : set R) \ (I.comap f) := begin obtain ⟨hrJ, hrI⟩ := hr, have rbar_ne_zero : quotient.mk I r ≠ 0 := mt (quotient.mk_eq_zero I).mp hrI, have rbar_mem_J : quotient.mk I r ∈ J.map (quotient.mk I) := mem_map_of_mem _ hrJ, have quotient_f : ∀ x ∈ I.comap f, (quotient.mk I).comp f x = 0, { simp [quotient.eq_zero_iff_mem] }, have rbar_root : (p.map (quotient.mk (I.comap f))).eval₂ (quotient.lift (I.comap f) _ quotient_f) (quotient.mk I r) = 0, { convert quotient.eq_zero_iff_mem.mpr hpI, exact trans (eval₂_map _ _ _) (hom_eval₂ p f (quotient.mk I) r).symm }, obtain ⟨i, ne_zero, mem⟩ := exists_coeff_ne_zero_mem_comap_of_root_mem rbar_ne_zero rbar_mem_J p_ne_zero rbar_root, rw coeff_map at ne_zero mem, refine ⟨i, (mem_quotient_iff_mem hIJ).mp _, mt _ ne_zero⟩, { simpa using mem }, simp [quotient.eq_zero_iff_mem], end lemma comap_lt_comap_of_root_mem_sdiff [I.is_prime] (hIJ : I ≤ J) {r : S} (hr : r ∈ (J : set S) \ I) {p : polynomial R} (p_ne_zero : p.map (quotient.mk (I.comap f)) ≠ 0) (hp : p.eval₂ f r ∈ I) : I.comap f < J.comap f := let ⟨i, hJ, hI⟩ := exists_coeff_mem_comap_sdiff_comap_of_root_mem_sdiff hIJ hr p_ne_zero hp in set_like.lt_iff_le_and_exists.mpr ⟨comap_mono hIJ, p.coeff i, hJ, hI⟩ lemma mem_of_one_mem (h : (1 : S) ∈ I) (x) : x ∈ I := (I.eq_top_iff_one.mpr h).symm ▸ mem_top lemma comap_lt_comap_of_integral_mem_sdiff [algebra R S] [hI : I.is_prime] (hIJ : I ≤ J) {x : S} (mem : x ∈ (J : set S) \ I) (integral : is_integral R x) : I.comap (algebra_map R S) < J.comap (algebra_map _ _) := begin obtain ⟨p, p_monic, hpx⟩ := integral, refine comap_lt_comap_of_root_mem_sdiff hIJ mem _ _, swap, { apply map_monic_ne_zero p_monic, apply quotient.nontrivial, apply mt comap_eq_top_iff.mp, apply hI.1 }, convert I.zero_mem end lemma comap_ne_bot_of_root_mem [integral_domain S] {r : S} (r_ne_zero : r ≠ 0) (hr : r ∈ I) {p : polynomial R} (p_ne_zero : p ≠ 0) (hp : p.eval₂ f r = 0) : I.comap f ≠ ⊥ := λ h, let ⟨i, hi, mem⟩ := exists_coeff_ne_zero_mem_comap_of_root_mem r_ne_zero hr p_ne_zero hp in absurd (mem_bot.mp (eq_bot_iff.mp h mem)) hi lemma is_maximal_of_is_integral_of_is_maximal_comap [algebra R S] (hRS : algebra.is_integral R S) (I : ideal S) [I.is_prime] (hI : is_maximal (I.comap (algebra_map R S))) : is_maximal I := ⟨⟨mt comap_eq_top_iff.mpr hI.1.1, λ J I_lt_J, let ⟨I_le_J, x, hxJ, hxI⟩ := set_like.lt_iff_le_and_exists.mp I_lt_J in comap_eq_top_iff.1 $ hI.1.2 _ (comap_lt_comap_of_integral_mem_sdiff I_le_J ⟨hxJ, hxI⟩ (hRS x))⟩⟩ lemma is_maximal_of_is_integral_of_is_maximal_comap' (f : R →+* S) (hf : f.is_integral) (I : ideal S) [hI' : I.is_prime] (hI : is_maximal (I.comap f)) : is_maximal I := @is_maximal_of_is_integral_of_is_maximal_comap R _ S _ f.to_algebra hf I hI' hI variables [algebra R S] lemma comap_ne_bot_of_algebraic_mem [integral_domain S] {x : S} (x_ne_zero : x ≠ 0) (x_mem : x ∈ I) (hx : is_algebraic R x) : I.comap (algebra_map R S) ≠ ⊥ := let ⟨p, p_ne_zero, hp⟩ := hx in comap_ne_bot_of_root_mem x_ne_zero x_mem p_ne_zero hp lemma comap_ne_bot_of_integral_mem [nontrivial R] [integral_domain S] {x : S} (x_ne_zero : x ≠ 0) (x_mem : x ∈ I) (hx : is_integral R x) : I.comap (algebra_map R S) ≠ ⊥ := comap_ne_bot_of_algebraic_mem x_ne_zero x_mem (hx.is_algebraic R) lemma eq_bot_of_comap_eq_bot [nontrivial R] [integral_domain S] (hRS : algebra.is_integral R S) (hI : I.comap (algebra_map R S) = ⊥) : I = ⊥ := begin refine eq_bot_iff.2 (λ x hx, _), by_cases hx0 : x = 0, { exact hx0.symm ▸ ideal.zero_mem ⊥ }, { exact absurd hI (comap_ne_bot_of_integral_mem hx0 hx (hRS x)) } end lemma is_maximal_comap_of_is_integral_of_is_maximal (hRS : algebra.is_integral R S) (I : ideal S) [hI : I.is_maximal] : is_maximal (I.comap (algebra_map R S)) := begin refine quotient.maximal_of_is_field _ _, haveI : is_prime (I.comap (algebra_map R S)) := comap_is_prime _ _, exact is_field_of_is_integral_of_is_field (is_integral_quotient_of_is_integral hRS) algebra_map_quotient_injective (by rwa ← quotient.maximal_ideal_iff_is_field_quotient), end lemma is_maximal_comap_of_is_integral_of_is_maximal' {R S : Type*} [comm_ring R] [comm_ring S] (f : R →+* S) (hf : f.is_integral) (I : ideal S) (hI : I.is_maximal) : is_maximal (I.comap f) := @is_maximal_comap_of_is_integral_of_is_maximal R _ S _ f.to_algebra hf I hI section is_integral_closure variables (S) {A : Type*} [comm_ring A] variables [algebra R A] [algebra A S] [is_scalar_tower R A S] [is_integral_closure A R S] lemma is_integral_closure.comap_lt_comap {I J : ideal A} [I.is_prime] (I_lt_J : I < J) : I.comap (algebra_map R A) < J.comap (algebra_map _ _) := let ⟨I_le_J, x, hxJ, hxI⟩ := set_like.lt_iff_le_and_exists.mp I_lt_J in comap_lt_comap_of_integral_mem_sdiff I_le_J ⟨hxJ, hxI⟩ (is_integral_closure.is_integral R S x) lemma is_integral_closure.is_maximal_of_is_maximal_comap (I : ideal A) [I.is_prime] (hI : is_maximal (I.comap (algebra_map R A))) : is_maximal I := is_maximal_of_is_integral_of_is_maximal_comap (λ x, is_integral_closure.is_integral R S x) I hI variables [integral_domain A] lemma is_integral_closure.comap_ne_bot [nontrivial R] {I : ideal A} (I_ne_bot : I ≠ ⊥) : I.comap (algebra_map R A) ≠ ⊥ := let ⟨x, x_mem, x_ne_zero⟩ := I.ne_bot_iff.mp I_ne_bot in comap_ne_bot_of_integral_mem x_ne_zero x_mem (is_integral_closure.is_integral R S x) lemma is_integral_closure.eq_bot_of_comap_eq_bot [nontrivial R] {I : ideal A} : I.comap (algebra_map R A) = ⊥ → I = ⊥ := imp_of_not_imp_not _ _ (is_integral_closure.comap_ne_bot S) end is_integral_closure lemma integral_closure.comap_lt_comap {I J : ideal (integral_closure R S)} [I.is_prime] (I_lt_J : I < J) : I.comap (algebra_map R (integral_closure R S)) < J.comap (algebra_map _ _) := is_integral_closure.comap_lt_comap S I_lt_J lemma integral_closure.is_maximal_of_is_maximal_comap (I : ideal (integral_closure R S)) [I.is_prime] (hI : is_maximal (I.comap (algebra_map R (integral_closure R S)))) : is_maximal I := is_integral_closure.is_maximal_of_is_maximal_comap S I hI section variables [integral_domain S] lemma integral_closure.comap_ne_bot [nontrivial R] {I : ideal (integral_closure R S)} (I_ne_bot : I ≠ ⊥) : I.comap (algebra_map R (integral_closure R S)) ≠ ⊥ := is_integral_closure.comap_ne_bot S I_ne_bot lemma integral_closure.eq_bot_of_comap_eq_bot [nontrivial R] {I : ideal (integral_closure R S)} : I.comap (algebra_map R (integral_closure R S)) = ⊥ → I = ⊥ := is_integral_closure.eq_bot_of_comap_eq_bot S /-- `comap (algebra_map R S)` is a surjection from the prime spec of `R` to prime spec of `S`. `hP : (algebra_map R S).ker ≤ P` is a slight generalization of the extension being injective -/ lemma exists_ideal_over_prime_of_is_integral' (H : algebra.is_integral R S) (P : ideal R) [is_prime P] (hP : (algebra_map R S).ker ≤ P) : ∃ (Q : ideal S), is_prime Q ∧ Q.comap (algebra_map R S) = P := begin have hP0 : (0 : S) ∉ algebra.algebra_map_submonoid S P.prime_compl, { rintro ⟨x, ⟨hx, x0⟩⟩, exact absurd (hP x0) hx }, let Rₚ := localization P.prime_compl, let Sₚ := localization (algebra.algebra_map_submonoid S P.prime_compl), letI : integral_domain (localization (algebra.algebra_map_submonoid S P.prime_compl)) := is_localization.integral_domain_localization (le_non_zero_divisors_of_no_zero_divisors hP0), obtain ⟨Qₚ : ideal Sₚ, Qₚ_maximal⟩ := exists_maximal Sₚ, haveI Qₚ_max : is_maximal (comap _ Qₚ) := @is_maximal_comap_of_is_integral_of_is_maximal Rₚ _ Sₚ _ (localization_algebra P.prime_compl S) (is_integral_localization H) _ Qₚ_maximal, refine ⟨comap (algebra_map S Sₚ) Qₚ, ⟨comap_is_prime _ Qₚ, _⟩⟩, convert localization.at_prime.comap_maximal_ideal, rw [comap_comap, ← local_ring.eq_maximal_ideal Qₚ_max, ← is_localization.map_comp _], refl end end /-- More general going-up theorem than `exists_ideal_over_prime_of_is_integral'`. TODO: Version of going-up theorem with arbitrary length chains (by induction on this)? Not sure how best to write an ascending chain in Lean -/ theorem exists_ideal_over_prime_of_is_integral (H : algebra.is_integral R S) (P : ideal R) [is_prime P] (I : ideal S) [is_prime I] (hIP : I.comap (algebra_map R S) ≤ P) : ∃ Q ≥ I, is_prime Q ∧ Q.comap (algebra_map R S) = P := begin obtain ⟨Q' : ideal I.quotient, ⟨Q'_prime, hQ'⟩⟩ := @exists_ideal_over_prime_of_is_integral' (I.comap (algebra_map R S)).quotient _ I.quotient _ ideal.quotient_algebra _ (is_integral_quotient_of_is_integral H) (map (quotient.mk (I.comap (algebra_map R S))) P) (map_is_prime_of_surjective quotient.mk_surjective (by simp [hIP])) (le_trans (le_of_eq ((ring_hom.injective_iff_ker_eq_bot _).1 algebra_map_quotient_injective)) bot_le), haveI := Q'_prime, refine ⟨Q'.comap _, le_trans (le_of_eq mk_ker.symm) (ker_le_comap _), ⟨comap_is_prime _ Q', _⟩⟩, rw comap_comap, refine trans _ (trans (congr_arg (comap (quotient.mk (comap (algebra_map R S) I))) hQ') _), { simpa [comap_comap] }, { refine trans (comap_map_of_surjective _ quotient.mk_surjective _) (sup_eq_left.2 _), simpa [← ring_hom.ker_eq_comap_bot] using hIP}, end /-- `comap (algebra_map R S)` is a surjection from the max spec of `S` to max spec of `R`. `hP : (algebra_map R S).ker ≤ P` is a slight generalization of the extension being injective -/ lemma exists_ideal_over_maximal_of_is_integral [integral_domain S] (H : algebra.is_integral R S) (P : ideal R) [P_max : is_maximal P] (hP : (algebra_map R S).ker ≤ P) : ∃ (Q : ideal S), is_maximal Q ∧ Q.comap (algebra_map R S) = P := begin obtain ⟨Q, ⟨Q_prime, hQ⟩⟩ := exists_ideal_over_prime_of_is_integral' H P hP, haveI : Q.is_prime := Q_prime, exact ⟨Q, is_maximal_of_is_integral_of_is_maximal_comap H _ (hQ.symm ▸ P_max), hQ⟩, end end integral_domain end ideal
6113776b68fd4c8df75de77fd5ed245152c25a4f
2c096fdfecf64e46ea7bc6ce5521f142b5926864
/src/Lean/Meta/SynthInstance.lean
7c04e2f4db62bed4e9650cb5d618c074c313b4cc
[ "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
Kha/lean4
1005785d2c8797ae266a303968848e5f6ce2fe87
b99e11346948023cd6c29d248cd8f3e3fb3474cf
refs/heads/master
1,693,355,498,027
1,669,080,461,000
1,669,113,138,000
184,748,176
0
0
Apache-2.0
1,665,995,520,000
1,556,884,930,000
Lean
UTF-8
Lean
false
false
34,706
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Daniel Selsam, Leonardo de Moura Type class instance synthesizer using tabled resolution. -/ import Lean.Meta.Basic import Lean.Meta.Instances import Lean.Meta.AbstractMVars import Lean.Meta.WHNF import Lean.Meta.Check import Lean.Util.Profile namespace Lean.Meta register_builtin_option synthInstance.maxHeartbeats : Nat := { defValue := 20000 descr := "maximum amount of heartbeats per typeclass resolution problem. A heartbeat is number of (small) memory allocations (in thousands), 0 means no limit" } register_builtin_option synthInstance.maxSize : Nat := { defValue := 128 descr := "maximum number of instances used to construct a solution in the type class instance synthesis procedure" } namespace SynthInstance def getMaxHeartbeats (opts : Options) : Nat := synthInstance.maxHeartbeats.get opts * 1000 builtin_initialize inferTCGoalsRLAttr : TagAttribute ← registerTagAttribute `infer_tc_goals_rl "instruct type class resolution procedure to solve goals from right to left for this instance" def hasInferTCGoalsRLAttribute (env : Environment) (constName : Name) : Bool := inferTCGoalsRLAttr.hasTag env constName structure GeneratorNode where mvar : Expr key : Expr mctx : MetavarContext instances : Array Expr currInstanceIdx : Nat deriving Inhabited structure ConsumerNode where mvar : Expr key : Expr mctx : MetavarContext subgoals : List Expr size : Nat -- instance size so far deriving Inhabited inductive Waiter where | consumerNode : ConsumerNode → Waiter | root : Waiter def Waiter.isRoot : Waiter → Bool | Waiter.consumerNode _ => false | Waiter.root => true /-! In tabled resolution, we creating a mapping from goals (e.g., `Coe Nat ?x`) to answers and waiters. Waiters are consumer nodes that are waiting for answers for a particular node. We implement this mapping using a `HashMap` where the keys are normalized expressions. That is, we replace assignable metavariables with auxiliary free variables of the form `_tc.<idx>`. We do not declare these free variables in any local context, and we should view them as "normalized names" for metavariables. For example, the term `f ?m ?m ?n` is normalized as `f _tc.0 _tc.0 _tc.1`. This approach is structural, and we may visit the same goal more than once if the different occurrences are just definitionally equal, but not structurally equal. Remark: a metavariable is assignable only if its depth is equal to the metavar context depth. -/ namespace MkTableKey structure State where nextIdx : Nat := 0 lmap : HashMap LMVarId Level := {} emap : HashMap MVarId Expr := {} mctx : MetavarContext abbrev M := StateM State @[always_inline] instance : MonadMCtx M where getMCtx := return (← get).mctx modifyMCtx f := modify fun s => { s with mctx := f s.mctx } partial def normLevel (u : Level) : M Level := do if !u.hasMVar then return u else match u with | Level.succ v => return u.updateSucc! (← normLevel v) | Level.max v w => return u.updateMax! (← normLevel v) (← normLevel w) | Level.imax v w => return u.updateIMax! (← normLevel v) (← normLevel w) | Level.mvar mvarId => if !(← isLevelMVarAssignable mvarId) then return u else let s ← get match (← get).lmap.find? mvarId with | some u' => pure u' | none => let u' := mkLevelParam <| Name.mkNum `_tc s.nextIdx modify fun s => { s with nextIdx := s.nextIdx + 1, lmap := s.lmap.insert mvarId u' } return u' | u => return u partial def normExpr (e : Expr) : M Expr := do if !e.hasMVar then pure e else match e with | Expr.const _ us => return e.updateConst! (← us.mapM normLevel) | Expr.sort u => return e.updateSort! (← normLevel u) | Expr.app f a => return e.updateApp! (← normExpr f) (← normExpr a) | Expr.letE _ t v b _ => return e.updateLet! (← normExpr t) (← normExpr v) (← normExpr b) | Expr.forallE _ d b _ => return e.updateForallE! (← normExpr d) (← normExpr b) | Expr.lam _ d b _ => return e.updateLambdaE! (← normExpr d) (← normExpr b) | Expr.mdata _ b => return e.updateMData! (← normExpr b) | Expr.proj _ _ b => return e.updateProj! (← normExpr b) | Expr.mvar mvarId => if !(← mvarId.isAssignable) then return e else let s ← get match s.emap.find? mvarId with | some e' => pure e' | none => do let e' := mkFVar { name := Name.mkNum `_tc s.nextIdx } modify fun s => { s with nextIdx := s.nextIdx + 1, emap := s.emap.insert mvarId e' } return e' | _ => return e end MkTableKey /-- Remark: `mkTableKey` assumes `e` does not contain assigned metavariables. -/ def mkTableKey [Monad m] [MonadMCtx m] (e : Expr) : m Expr := do let (r, s) := MkTableKey.normExpr e |>.run { mctx := (← getMCtx) } setMCtx s.mctx return r structure Answer where result : AbstractMVarsResult resultType : Expr size : Nat deriving Inhabited structure TableEntry where waiters : Array Waiter answers : Array Answer := #[] structure Context where maxResultSize : Nat maxHeartbeats : Nat /-- Remark: the SynthInstance.State is not really an extension of `Meta.State`. The field `postponed` is not needed, and the field `mctx` is misleading since `synthInstance` methods operate over different `MetavarContext`s simultaneously. That being said, we still use `extends` because it makes it simpler to move from `M` to `MetaM`. -/ structure State where result? : Option AbstractMVarsResult := none generatorStack : Array GeneratorNode := #[] resumeStack : Array (ConsumerNode × Answer) := #[] tableEntries : HashMap Expr TableEntry := {} abbrev SynthM := ReaderT Context $ StateRefT State MetaM def checkMaxHeartbeats : SynthM Unit := do Core.checkMaxHeartbeatsCore "typeclass" `synthInstance.maxHeartbeats (← read).maxHeartbeats @[inline] def mapMetaM (f : forall {α}, MetaM α → MetaM α) {α} : SynthM α → SynthM α := monadMap @f instance : Inhabited (SynthM α) where default := fun _ _ => default /-- Return globals and locals instances that may unify with `type` -/ def getInstances (type : Expr) : MetaM (Array Expr) := do -- We must retrieve `localInstances` before we use `forallTelescopeReducing` because it will update the set of local instances let localInstances ← getLocalInstances forallTelescopeReducing type fun _ type => do let className? ← isClass? type match className? with | none => throwError "type class instance expected{indentExpr type}" | some className => let globalInstances ← getGlobalInstancesIndex let result ← globalInstances.getUnify type -- Using insertion sort because it is stable and the array `result` should be mostly sorted. -- Most instances have default priority. let result := result.insertionSort fun e₁ e₂ => e₁.priority < e₂.priority let erasedInstances ← getErasedInstances let result ← result.filterMapM fun e => match e.val with | Expr.const constName us => if erasedInstances.contains constName then return none else return some <| e.val.updateConst! (← us.mapM (fun _ => mkFreshLevelMVar)) | _ => panic! "global instance is not a constant" let result := localInstances.foldl (init := result) fun (result : Array Expr) linst => if linst.className == className then result.push linst.fvar else result trace[Meta.synthInstance.instances] result return result def mkGeneratorNode? (key mvar : Expr) : MetaM (Option GeneratorNode) := do let mvarType ← inferType mvar let mvarType ← instantiateMVars mvarType let instances ← getInstances mvarType if instances.isEmpty then return none else let mctx ← getMCtx return some { mvar, key, mctx, instances currInstanceIdx := instances.size } /-- Create a new generator node for `mvar` and add `waiter` as its waiter. `key` must be `mkTableKey mctx mvarType`. -/ def newSubgoal (mctx : MetavarContext) (key : Expr) (mvar : Expr) (waiter : Waiter) : SynthM Unit := withMCtx mctx do withTraceNode' `Meta.synthInstance do match (← mkGeneratorNode? key mvar) with | none => pure ((), m!"no instances for {key}") | some node => let entry : TableEntry := { waiters := #[waiter] } modify fun s => { s with generatorStack := s.generatorStack.push node tableEntries := s.tableEntries.insert key entry } pure ((), m!"new goal {key}") def findEntry? (key : Expr) : SynthM (Option TableEntry) := do return (← get).tableEntries.find? key def getEntry (key : Expr) : SynthM TableEntry := do match (← findEntry? key) with | none => panic! "invalid key at synthInstance" | some entry => pure entry /-- Create a `key` for the goal associated with the given metavariable. That is, we create a key for the type of the metavariable. We must instantiate assigned metavariables before we invoke `mkTableKey`. -/ def mkTableKeyFor (mctx : MetavarContext) (mvar : Expr) : SynthM Expr := withMCtx mctx do let mvarType ← inferType mvar let mvarType ← instantiateMVars mvarType mkTableKey mvarType /-- See `getSubgoals` and `getSubgoalsAux` We use the parameter `j` to reduce the number of `instantiate*` invocations. It is the same approach we use at `forallTelescope` and `lambdaTelescope`. Given `getSubgoalsAux args j subgoals instVal type`, we have that `type.instantiateRevRange j args.size args` does not have loose bound variables. -/ structure SubgoalsResult where subgoals : List Expr instVal : Expr instTypeBody : Expr private partial def getSubgoalsAux (lctx : LocalContext) (localInsts : LocalInstances) (xs : Array Expr) : Array Expr → Nat → List Expr → Expr → Expr → MetaM SubgoalsResult | args, j, subgoals, instVal, Expr.forallE _ d b bi => do let d := d.instantiateRevRange j args.size args let mvarType ← mkForallFVars xs d let mvar ← mkFreshExprMVarAt lctx localInsts mvarType let arg := mkAppN mvar xs let instVal := mkApp instVal arg let subgoals := if bi.isInstImplicit then mvar::subgoals else subgoals let args := args.push (mkAppN mvar xs) getSubgoalsAux lctx localInsts xs args j subgoals instVal b | args, j, subgoals, instVal, type => do let type := type.instantiateRevRange j args.size args let type ← whnf type if type.isForall then getSubgoalsAux lctx localInsts xs args args.size subgoals instVal type else return ⟨subgoals, instVal, type⟩ /-- `getSubgoals lctx localInsts xs inst` creates the subgoals for the instance `inst`. The subgoals are in the context of the free variables `xs`, and `(lctx, localInsts)` is the local context and instances before we added the free variables to it. This extra complication is required because 1- We want all metavariables created by `synthInstance` to share the same local context. 2- We want to ensure that applications such as `mvar xs` are higher order patterns. The method `getGoals` create a new metavariable for each parameter of `inst`. For example, suppose the type of `inst` is `forall (x_1 : A_1) ... (x_n : A_n), B x_1 ... x_n`. Then, we create the metavariables `?m_i : forall xs, A_i`, and return the subset of these metavariables that are instance implicit arguments, and the expressions: - `inst (?m_1 xs) ... (?m_n xs)` (aka `instVal`) - `B (?m_1 xs) ... (?m_n xs)` -/ def getSubgoals (lctx : LocalContext) (localInsts : LocalInstances) (xs : Array Expr) (inst : Expr) : MetaM SubgoalsResult := do let instType ← inferType inst let result ← getSubgoalsAux lctx localInsts xs #[] 0 [] inst instType match inst.getAppFn with | Expr.const constName _ => let env ← getEnv if hasInferTCGoalsRLAttribute env constName then return result else return { result with subgoals := result.subgoals.reverse } | _ => return result /-- Try to synthesize metavariable `mvar` using the instance `inst`. Remark: `mctx` is set using `withMCtx`. If it succeeds, the result is a new updated metavariable context and a new list of subgoals. A subgoal is created for each instance implicit parameter of `inst`. -/ def tryResolve (mvar : Expr) (inst : Expr) : MetaM (Option (MetavarContext × List Expr)) := do let mvar ← instantiateMVars mvar if !(← hasAssignableMVar mvar) then /- The metavariable `mvar` may have been assigned when solving typing constraints. This may happen when a local instance type depends on other local instances. For example, in Mathlib, we have ``` @Submodule.setLike : {R : Type u_1} → {M : Type u_2} → [_inst_1 : Semiring R] → [_inst_2 : AddCommMonoid M] → [_inst_3 : @ModuleS R M _inst_1 _inst_2] → SetLike (@Submodule R M _inst_1 _inst_2 _inst_3) M ``` TODO: discuss what is the correct behavior here. There are other possibilities. 1) We could try to synthesize the instances `_inst_1` and `_inst_2` and check whether it is defeq to the one inferred by typing constraints. That is, we remove this `if`-statement. We discarded this one because some Mathlib theorems failed to be elaborated using it. 2) Generate an error/warning message when instances such as `Submodule.setLike` are declared, and instruct user to use `{}` binder annotation for `_inst_1` `_inst_2`. -/ return some ((← getMCtx), []) let mvarType ← inferType mvar let lctx ← getLCtx let localInsts ← getLocalInstances forallTelescopeReducing mvarType fun xs mvarTypeBody => do let ⟨subgoals, instVal, instTypeBody⟩ ← getSubgoals lctx localInsts xs inst withTraceNode `Meta.synthInstance.tryResolve (withMCtx (← getMCtx) do return m!"{exceptOptionEmoji ·} {← instantiateMVars mvarTypeBody} ≟ {← instantiateMVars instTypeBody}") do if (← isDefEq mvarTypeBody instTypeBody) then let instVal ← mkLambdaFVars xs instVal if (← isDefEq mvar instVal) then return some ((← getMCtx), subgoals) return none /-- Assign a precomputed answer to `mvar`. If it succeeds, the result is a new updated metavariable context and a new list of subgoals. -/ def tryAnswer (mctx : MetavarContext) (mvar : Expr) (answer : Answer) : SynthM (Option MetavarContext) := withMCtx mctx do let (_, _, val) ← openAbstractMVarsResult answer.result if (← isDefEq mvar val) then return some (← getMCtx) else return none /-- Move waiters that are waiting for the given answer to the resume stack. -/ def wakeUp (answer : Answer) : Waiter → SynthM Unit | Waiter.root => do /- Recall that we now use `ignoreLevelMVarDepth := true`. Thus, we should allow solutions containing universe metavariables, and not check `answer.result.paramNames.isEmpty`. We use `openAbstractMVarsResult` to construct the universe metavariables at the correct depth. -/ if answer.result.numMVars == 0 then modify fun s => { s with result? := answer.result } else let (_, _, answerExpr) ← openAbstractMVarsResult answer.result trace[Meta.synthInstance] "skip answer containing metavariables {answerExpr}" | Waiter.consumerNode cNode => modify fun s => { s with resumeStack := s.resumeStack.push (cNode, answer) } def isNewAnswer (oldAnswers : Array Answer) (answer : Answer) : Bool := oldAnswers.all fun oldAnswer => -- Remark: isDefEq here is too expensive. TODO: if `==` is too imprecise, add some light normalization to `resultType` at `addAnswer` -- iseq ← isDefEq oldAnswer.resultType answer.resultType; pure (!iseq) oldAnswer.resultType != answer.resultType private def mkAnswer (cNode : ConsumerNode) : MetaM Answer := withMCtx cNode.mctx do let val ← instantiateMVars cNode.mvar trace[Meta.synthInstance.newAnswer] "size: {cNode.size}, val: {val}" let result ← abstractMVars val -- assignable metavariables become parameters let resultType ← inferType result.expr return { result, resultType, size := cNode.size + 1 } /-- Create a new answer after `cNode` resolved all subgoals. That is, `cNode.subgoals == []`. And then, store it in the tabled entries map, and wakeup waiters. -/ def addAnswer (cNode : ConsumerNode) : SynthM Unit := do withMCtx cNode.mctx do if cNode.size ≥ (← read).maxResultSize then trace[Meta.synthInstance.answer] "{crossEmoji} {← instantiateMVars (← inferType cNode.mvar)}{Format.line}(size: {cNode.size} ≥ {(← read).maxResultSize})" else withTraceNode `Meta.synthInstance.answer (fun _ => return m!"{checkEmoji} {← instantiateMVars (← inferType cNode.mvar)}") do let answer ← mkAnswer cNode -- Remark: `answer` does not contain assignable or assigned metavariables. let key := cNode.key let entry ← getEntry key if isNewAnswer entry.answers answer then let newEntry := { entry with answers := entry.answers.push answer } modify fun s => { s with tableEntries := s.tableEntries.insert key newEntry } entry.waiters.forM (wakeUp answer) /-- Return `true` if a type of the form `(a_1 : A_1) → ... → (a_n : A_n) → B` has an unused argument `a_i`. Remark: This is syntactic check and no reduction is performed. -/ private def hasUnusedArguments : Expr → Bool | Expr.forallE _ _ b _ => !b.hasLooseBVar 0 || hasUnusedArguments b | _ => false /-- If the type of the metavariable `mvar` has unused argument, return a pair `(α, transformer)` where `α` is a new type without the unused arguments and the `transformer` is a function for coverting a solution with type `α` into a value that can be assigned to `mvar`. Example: suppose `mvar` has type `(a : A) → (b : B a) → (c : C a) → D a c`, the result is the pair ``` ((a : A) → (c : C a) → D a c, fun (f : (a : A) → (c : C a) → D a c) (a : A) (b : B a) (c : C a) => f a c ) ``` This method is used to improve the effectiveness of the TC resolution procedure. It was suggested and prototyped by Tomas Skrivan. It improves the support for instances of type `a : A → C` where `a` does not appear in class `C`. When we look for such an instance it is enough to look for an instance `c : C` and then return `fun _ => c`. Tomas' approach makes sure that instance of a type like `a : A → C` never gets tabled/cached. More on that later. At the core is this method. it takes an expression E and does two things: The modification to TC resolution works this way: We are looking for an instance of `E`, if it is tabled just get it as normal, but if not first remove all unused arguments producing `E'`. Now we look up the table again but for `E'`. If it exists, use the transformer to create E. If it does not exists, create a new goal `E'`. -/ private def removeUnusedArguments? (mctx : MetavarContext) (mvar : Expr) : MetaM (Option (Expr × Expr)) := withMCtx mctx do let mvarType ← instantiateMVars (← inferType mvar) if !hasUnusedArguments mvarType then return none else forallTelescope mvarType fun xs body => do let ys ← xs.foldrM (init := []) fun x ys => do if body.containsFVar x.fvarId! then return x :: ys else if (← ys.anyM fun y => return (← inferType y).containsFVar x.fvarId!) then return x :: ys else return ys let ys := ys.toArray let mvarType' ← mkForallFVars ys body withLocalDeclD `redf mvarType' fun f => do let transformer ← mkLambdaFVars #[f] (← mkLambdaFVars xs (mkAppN f ys)) trace[Meta.synthInstance.unusedArgs] "{mvarType}\nhas unused arguments, reduced type{indentExpr mvarType'}\nTransformer{indentExpr transformer}" return some (mvarType', transformer) /-- Process the next subgoal in the given consumer node. -/ def consume (cNode : ConsumerNode) : SynthM Unit := do match cNode.subgoals with | [] => addAnswer cNode | mvar::_ => let waiter := Waiter.consumerNode cNode let key ← mkTableKeyFor cNode.mctx mvar let entry? ← findEntry? key match entry? with | none => -- Remove unused arguments and try again, see comment at `removeUnusedArguments?` match (← removeUnusedArguments? cNode.mctx mvar) with | none => newSubgoal cNode.mctx key mvar waiter | some (mvarType', transformer) => let key' ← withMCtx cNode.mctx <| mkTableKey mvarType' match (← findEntry? key') with | none => let (mctx', mvar') ← withMCtx cNode.mctx do let mvar' ← mkFreshExprMVar mvarType' return (← getMCtx, mvar') newSubgoal mctx' key' mvar' (Waiter.consumerNode { cNode with mctx := mctx', subgoals := mvar'::cNode.subgoals }) | some entry' => let answers' ← entry'.answers.mapM fun a => withMCtx cNode.mctx do let trAnswr := Expr.betaRev transformer #[← instantiateMVars a.result.expr] let trAnswrType ← inferType trAnswr pure { a with result.expr := trAnswr, resultType := trAnswrType } modify fun s => { s with resumeStack := answers'.foldl (fun s answer => s.push (cNode, answer)) s.resumeStack, tableEntries := s.tableEntries.insert key' { entry' with waiters := entry'.waiters.push waiter } } | some entry => modify fun s => { s with resumeStack := entry.answers.foldl (fun s answer => s.push (cNode, answer)) s.resumeStack, tableEntries := s.tableEntries.insert key { entry with waiters := entry.waiters.push waiter } } def getTop : SynthM GeneratorNode := return (← get).generatorStack.back @[inline] def modifyTop (f : GeneratorNode → GeneratorNode) : SynthM Unit := modify fun s => { s with generatorStack := s.generatorStack.modify (s.generatorStack.size - 1) f } /-- Try the next instance in the node on the top of the generator stack. -/ def generate : SynthM Unit := do let gNode ← getTop if gNode.currInstanceIdx == 0 then modify fun s => { s with generatorStack := s.generatorStack.pop } else let key := gNode.key let idx := gNode.currInstanceIdx - 1 let inst := gNode.instances.get! idx let mctx := gNode.mctx let mvar := gNode.mvar discard do withMCtx mctx do withTraceNode `Meta.synthInstance (return m!"{exceptOptionEmoji ·} apply {inst} to {← instantiateMVars (← inferType mvar)}") do modifyTop fun gNode => { gNode with currInstanceIdx := idx } if let some (mctx, subgoals) ← tryResolve mvar inst then consume { key, mvar, subgoals, mctx, size := 0 } return some () return none def getNextToResume : SynthM (ConsumerNode × Answer) := do let r := (← get).resumeStack.back modify fun s => { s with resumeStack := s.resumeStack.pop } return r /-- Given `(cNode, answer)` on the top of the resume stack, continue execution by using `answer` to solve the next subgoal. -/ def resume : SynthM Unit := do let (cNode, answer) ← getNextToResume match cNode.subgoals with | [] => panic! "resume found no remaining subgoals" | mvar::rest => match (← tryAnswer cNode.mctx mvar answer) with | none => return () | some mctx => withMCtx mctx do let goal ← inferType cNode.mvar let subgoal ← inferType mvar withTraceNode `Meta.synthInstance.resume (fun _ => withMCtx cNode.mctx do return m!"propagating {← instantiateMVars answer.resultType} to subgoal {← instantiateMVars subgoal} of {← instantiateMVars goal}") do trace[Meta.synthInstance.resume] "size: {cNode.size + answer.size}" consume { key := cNode.key, mvar := cNode.mvar, subgoals := rest, mctx, size := cNode.size + answer.size } def step : SynthM Bool := do checkMaxHeartbeats let s ← get if !s.resumeStack.isEmpty then resume return true else if !s.generatorStack.isEmpty then generate return true else return false def getResult : SynthM (Option AbstractMVarsResult) := return (← get).result? partial def synth : SynthM (Option AbstractMVarsResult) := do if (← step) then match (← getResult) with | none => synth | some result => return result else return none def main (type : Expr) (maxResultSize : Nat) : MetaM (Option AbstractMVarsResult) := withCurrHeartbeats do let mvar ← mkFreshExprMVar type let key ← mkTableKey type let action : SynthM (Option AbstractMVarsResult) := do newSubgoal (← getMCtx) key mvar Waiter.root synth try action.run { maxResultSize := maxResultSize, maxHeartbeats := getMaxHeartbeats (← getOptions) } |>.run' {} catch ex => if ex.isMaxHeartbeat then throwError "failed to synthesize{indentExpr type}\n{ex.toMessageData}" else throw ex end SynthInstance /-! Type class parameters can be annotated with `outParam` annotations. Given `C a_1 ... a_n`, we replace `a_i` with a fresh metavariable `?m_i` IF `a_i` is an `outParam`. The result is type correct because we reject type class declarations IF it contains a regular parameter X that depends on an `out` parameter Y. Then, we execute type class resolution as usual. If it succeeds, and metavariables ?m_i have been assigned, we try to unify the original type `C a_1 ... a_n` witht the normalized one. -/ private def preprocess (type : Expr) : MetaM Expr := forallTelescopeReducing type fun xs type => do let type ← whnf type mkForallFVars xs type private def preprocessLevels (us : List Level) : MetaM (List Level × Bool) := do let mut r := #[] let mut modified := false for u in us do let u ← instantiateLevelMVars u if u.hasMVar then r := r.push (← mkFreshLevelMVar) modified := true else r := r.push u return (r.toList, modified) private partial def preprocessArgs (type : Expr) (i : Nat) (args : Array Expr) : MetaM (Array Expr) := do if h : i < args.size then let type ← whnf type match type with | Expr.forallE _ d b _ => do let arg := args.get ⟨i, h⟩ let arg ← if d.isOutParam then mkFreshExprMVar d else pure arg let args := args.set ⟨i, h⟩ arg preprocessArgs (b.instantiate1 arg) (i+1) args | _ => throwError "type class resolution failed, insufficient number of arguments" -- TODO improve error message else return args private def preprocessOutParam (type : Expr) : MetaM Expr := forallTelescope type fun xs typeBody => do match typeBody.getAppFn with | c@(Expr.const constName _) => let env ← getEnv if !hasOutParams env constName then return type else let args := typeBody.getAppArgs let cType ← inferType c let args ← preprocessArgs cType 0 args mkForallFVars xs (mkAppN c args) | _ => return type /-! Remark: when `maxResultSize? == none`, the configuration option `synthInstance.maxResultSize` is used. Remark: we use a different option for controlling the maximum result size for coercions. -/ def synthInstance? (type : Expr) (maxResultSize? : Option Nat := none) : MetaM (Option Expr) := do profileitM Exception "typeclass inference" (← getOptions) do let opts ← getOptions let maxResultSize := maxResultSize?.getD (synthInstance.maxSize.get opts) /- We disable eta for structures that are not classes during TC resolution because it allows us to find unintended solutions. See discussion at https://leanprover.zulipchat.com/#narrow/stream/270676-lean4/topic/.60constructor.60.20and.20.60Applicative.60/near/279984801 -/ withConfig (fun config => { config with isDefEqStuckEx := true, transparency := TransparencyMode.instances, foApprox := true, ctxApprox := true, constApprox := false, etaStruct := .notClasses }) do let type ← instantiateMVars type let type ← preprocess type let s ← get match s.cache.synthInstance.find? type with | some result => pure result | none => withTraceNode `Meta.synthInstance (return m!"{exceptOptionEmoji ·} {← instantiateMVars type}") do let result? ← withNewMCtxDepth do let normType ← preprocessOutParam type SynthInstance.main normType maxResultSize let resultHasUnivMVars := if let some result := result? then !result.paramNames.isEmpty else false let result? ← match result? with | none => pure none | some result => do let (_, _, result) ← openAbstractMVarsResult result trace[Meta.synthInstance] "result {result}" let resultType ← inferType result /- Output parameters of local instances may be marked as `syntheticOpaque` by the application-elaborator. We use `withAssignableSyntheticOpaque` to make sure this kind of parameter can be assigned by the following `isDefEq`. TODO: rewrite this check to avoid `withAssignableSyntheticOpaque`. -/ if (← withDefault <| withAssignableSyntheticOpaque <| isDefEq type resultType) then let result ← instantiateMVars result /- We use `check` to propogate universe constraints implied by the `result`. Recall that we use `ignoreLevelMVarDepth := true` which allows universe metavariables in the current depth to be assigned, but these assignments are discarded by `withNewMCtxDepth`. TODO: If this `check` is a performance bottleneck, we can improve performance by tracking whether a universe metavariable from previous universe levels have been assigned or not during TC resolution. We only need to perform the `check` if this kind of assignment have been performed. The example in the issue #796 exposed this issue. ``` structure A class B (a : outParam A) (α : Sort u) class C {a : A} (α : Sort u) [B a α] class D {a : A} (α : Sort u) [B a α] [c : C α] class E (a : A) where [c (α : Sort u) [B a α] : C α] instance c {a : A} [e : E a] (α : Sort u) [B a α] : C α := e.c α def d {a : A} [e : E a] (α : Sort u) [b : B a α] : D α := ⟨⟩ ``` The term `D α` has two instance implicit arguments. The second one has type `C α`, and TC resolution produces the result `@c.{u} a e α b`. Note that the `e` has type `E.{?v} a`, and `E` is universe polymorphic, but the universe does not occur in the parameter `a`. We have that `?v := u` is implied by `@c.{u} a e α b`, but this assignment is lost. -/ check result pure (some result) else trace[Meta.synthInstance] "{crossEmoji} result type{indentExpr resultType}\nis not definitionally equal to{indentExpr type}" pure none if type.hasMVar || resultHasUnivMVars then pure result? else do modify fun s => { s with cache.synthInstance := s.cache.synthInstance.insert type result? } pure result? /-- Return `LOption.some r` if succeeded, `LOption.none` if it failed, and `LOption.undef` if instance cannot be synthesized right now because `type` contains metavariables. -/ def trySynthInstance (type : Expr) (maxResultSize? : Option Nat := none) : MetaM (LOption Expr) := do catchInternalId isDefEqStuckExceptionId (toLOptionM <| synthInstance? type maxResultSize?) (fun _ => pure LOption.undef) def synthInstance (type : Expr) (maxResultSize? : Option Nat := none) : MetaM Expr := catchInternalId isDefEqStuckExceptionId (do let result? ← synthInstance? type maxResultSize? match result? with | some result => pure result | none => throwError "failed to synthesize{indentExpr type}") (fun _ => throwError "failed to synthesize{indentExpr type}") @[export lean_synth_pending] private def synthPendingImp (mvarId : MVarId) : MetaM Bool := withIncRecDepth <| mvarId.withContext do let mvarDecl ← mvarId.getDecl match mvarDecl.kind with | MetavarKind.syntheticOpaque => return false | _ => /- Check whether the type of the given metavariable is a class or not. If yes, then try to synthesize it using type class resolution. We only do it for `synthetic` and `natural` metavariables. -/ match (← isClass? mvarDecl.type) with | none => return false | some _ => /- TODO: use a configuration option instead of the hard-coded limit `1`. -/ if (← read).synthPendingDepth > 1 then trace[Meta.synthPending] "too many nested synthPending invocations" return false else withReader (fun ctx => { ctx with synthPendingDepth := ctx.synthPendingDepth + 1 }) do trace[Meta.synthPending] "synthPending {mkMVar mvarId}" let val? ← catchInternalId isDefEqStuckExceptionId (synthInstance? mvarDecl.type (maxResultSize? := none)) (fun _ => pure none) match val? with | none => return false | some val => if (← mvarId.isAssigned) then return false else mvarId.assign val return true builtin_initialize registerTraceClass `Meta.synthPending registerTraceClass `Meta.synthInstance registerTraceClass `Meta.synthInstance.instances (inherited := true) registerTraceClass `Meta.synthInstance.tryResolve (inherited := true) registerTraceClass `Meta.synthInstance.resume (inherited := true) registerTraceClass `Meta.synthInstance.unusedArgs registerTraceClass `Meta.synthInstance.newAnswer end Lean.Meta
3f0aa667a409e2e85b153ae361fe071ac8275836
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/model_theory/finitely_generated.lean
dc9e22e225e22d627826a36d34f2b3203dcda290
[ "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
9,377
lean
/- Copyright (c) 2022 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import model_theory.substructures /-! # Finitely Generated First-Order Structures This file defines what it means for a first-order (sub)structure to be finitely or countably generated, similarly to other finitely-generated objects in the algebra library. ## Main Definitions * `first_order.language.substructure.fg` indicates that a substructure is finitely generated. * `first_order.language.Structure.fg` indicates that a structure is finitely generated. * `first_order.language.substructure.cg` indicates that a substructure is countably generated. * `first_order.language.Structure.cg` indicates that a structure is countably generated. ## TODO Develop a more unified definition of finite generation using the theory of closure operators, or use this definition of finite generation to define the others. -/ open_locale first_order open set namespace first_order namespace language open Structure variables {L : language} {M : Type*} [L.Structure M] namespace substructure /-- A substructure of `M` is finitely generated if it is the closure of a finite subset of `M`. -/ def fg (N : L.substructure M) : Prop := ∃ S : finset M, closure L ↑S = N theorem fg_def {N : L.substructure M} : N.fg ↔ ∃ S : set M, S.finite ∧ closure L S = N := ⟨λ ⟨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⟩ lemma fg_iff_exists_fin_generating_family {N : L.substructure M} : N.fg ↔ ∃ (n : ℕ) (s : fin n → M), closure L (range s) = N := begin rw fg_def, split, { rintros ⟨S, Sfin, hS⟩, obtain ⟨n, f, rfl⟩ := Sfin.fin_embedding, exact ⟨n, f, hS⟩, }, { rintros ⟨n, s, hs⟩, refine ⟨range s, finite_range s, hs⟩ }, end theorem fg_bot : (⊥ : L.substructure M).fg := ⟨∅, by rw [finset.coe_empty, closure_empty]⟩ theorem fg_closure {s : set M} (hs : s.finite) : fg (closure L s) := ⟨hs.to_finset, by rw [hs.coe_to_finset]⟩ theorem fg_closure_singleton (x : M) : fg (closure L ({x} : set M)) := fg_closure (finite_singleton x) theorem fg.sup {N₁ N₂ : L.substructure M} (hN₁ : N₁.fg) (hN₂ : N₂.fg) : (N₁ ⊔ N₂).fg := let ⟨t₁, ht₁⟩ := fg_def.1 hN₁, ⟨t₂, ht₂⟩ := fg_def.1 hN₂ in fg_def.2 ⟨t₁ ∪ t₂, ht₁.1.union ht₂.1, by rw [closure_union, ht₁.2, ht₂.2]⟩ theorem fg.map {N : Type*} [L.Structure N] (f : M →[L] N) {s : L.substructure M} (hs : s.fg) : (s.map f).fg := let ⟨t, ht⟩ := fg_def.1 hs in fg_def.2 ⟨f '' t, ht.1.image _, by rw [closure_image, ht.2]⟩ theorem fg.of_map_embedding {N : Type*} [L.Structure N] (f : M ↪[L] N) {s : L.substructure M} (hs : (s.map f.to_hom).fg) : s.fg := begin rcases hs with ⟨t, h⟩, rw fg_def, refine ⟨f ⁻¹' t, t.finite_to_set.preimage (f.injective.inj_on _), _⟩, have hf : function.injective f.to_hom := f.injective, refine map_injective_of_injective hf _, rw [← h, map_closure, embedding.coe_to_hom, image_preimage_eq_of_subset], intros x hx, have h' := subset_closure hx, rw h at h', exact hom.map_le_range h' end /-- A substructure of `M` is countably generated if it is the closure of a countable subset of `M`. -/ def cg (N : L.substructure M) : Prop := ∃ S : set M, S.countable ∧ closure L S = N theorem cg_def {N : L.substructure M} : N.cg ↔ ∃ S : set M, S.countable ∧ closure L S = N := iff.refl _ theorem fg.cg {N : L.substructure M} (h : N.fg) : N.cg := begin obtain ⟨s, hf, rfl⟩ := fg_def.1 h, refine ⟨s, hf.countable, rfl⟩, end lemma cg_iff_empty_or_exists_nat_generating_family {N : L.substructure M} : N.cg ↔ (↑N = (∅ : set M)) ∨ ∃ (s : ℕ → M), closure L (range s) = N := begin rw cg_def, split, { rintros ⟨S, Scount, hS⟩, cases eq_empty_or_nonempty ↑N with h h, { exact or.intro_left _ h }, obtain ⟨f, h'⟩ := (Scount.union (set.countable_singleton h.some)).exists_eq_range (singleton_nonempty h.some).inr, refine or.intro_right _ ⟨f, _⟩, rw [← h', closure_union, hS, sup_eq_left, closure_le], exact singleton_subset_iff.2 h.some_mem }, { intro h, cases h with h h, { refine ⟨∅, countable_empty, closure_eq_of_le (empty_subset _) _⟩, rw [← set_like.coe_subset_coe, h], exact empty_subset _ }, { obtain ⟨f, rfl⟩ := h, exact ⟨range f, countable_range _, rfl⟩ } }, end theorem cg_bot : (⊥ : L.substructure M).cg := fg_bot.cg theorem cg_closure {s : set M} (hs : s.countable) : cg (closure L s) := ⟨s, hs, rfl⟩ theorem cg_closure_singleton (x : M) : cg (closure L ({x} : set M)) := (fg_closure_singleton x).cg theorem cg.sup {N₁ N₂ : L.substructure M} (hN₁ : N₁.cg) (hN₂ : N₂.cg) : (N₁ ⊔ N₂).cg := let ⟨t₁, ht₁⟩ := cg_def.1 hN₁, ⟨t₂, ht₂⟩ := cg_def.1 hN₂ in cg_def.2 ⟨t₁ ∪ t₂, ht₁.1.union ht₂.1, by rw [closure_union, ht₁.2, ht₂.2]⟩ theorem cg.map {N : Type*} [L.Structure N] (f : M →[L] N) {s : L.substructure M} (hs : s.cg) : (s.map f).cg := let ⟨t, ht⟩ := cg_def.1 hs in cg_def.2 ⟨f '' t, ht.1.image _, by rw [closure_image, ht.2]⟩ theorem cg.of_map_embedding {N : Type*} [L.Structure N] (f : M ↪[L] N) {s : L.substructure M} (hs : (s.map f.to_hom).cg) : s.cg := begin rcases hs with ⟨t, h1, h2⟩, rw cg_def, refine ⟨f ⁻¹' t, h1.preimage f.injective, _⟩, have hf : function.injective f.to_hom := f.injective, refine map_injective_of_injective hf _, rw [← h2, map_closure, embedding.coe_to_hom, image_preimage_eq_of_subset], intros x hx, have h' := subset_closure hx, rw h2 at h', exact hom.map_le_range h' end theorem cg_iff_countable [L.countable_functions] {s : L.substructure M} : s.cg ↔ nonempty (encodable s) := begin refine ⟨_, λ h, ⟨s, h, s.closure_eq⟩⟩, rintro ⟨s, h, rfl⟩, exact h.substructure_closure L end end substructure open substructure namespace Structure variables (L) (M) /-- A structure is finitely generated if it is the closure of a finite subset. -/ class fg : Prop := (out : (⊤ : L.substructure M).fg) /-- A structure is countably generated if it is the closure of a countable subset. -/ class cg : Prop := (out : (⊤ : L.substructure M).cg) variables {L M} lemma fg_def : fg L M ↔ (⊤ : L.substructure M).fg := ⟨λ h, h.1, λ h, ⟨h⟩⟩ /-- An equivalent expression of `Structure.fg` in terms of `set.finite` instead of `finset`. -/ lemma fg_iff : fg L M ↔ ∃ S : set M, S.finite ∧ closure L S = (⊤ : L.substructure M) := by rw [fg_def, substructure.fg_def] lemma fg.range {N : Type*} [L.Structure N] (h : fg L M) (f : M →[L] N) : f.range.fg := begin rw [hom.range_eq_map], exact (fg_def.1 h).map f, end lemma fg.map_of_surjective {N : Type*} [L.Structure N] (h : fg L M) (f : M →[L] N) (hs : function.surjective f) : fg L N := begin rw ← hom.range_eq_top at hs, rw [fg_def, ← hs], exact h.range f, end lemma cg_def : cg L M ↔ (⊤ : L.substructure M).cg := ⟨λ h, h.1, λ h, ⟨h⟩⟩ /-- An equivalent expression of `Structure.cg`. -/ lemma cg_iff : cg L M ↔ ∃ S : set M, S.countable ∧ closure L S = (⊤ : L.substructure M) := by rw [cg_def, substructure.cg_def] lemma cg.range {N : Type*} [L.Structure N] (h : cg L M) (f : M →[L] N) : f.range.cg := begin rw [hom.range_eq_map], exact (cg_def.1 h).map f, end lemma cg.map_of_surjective {N : Type*} [L.Structure N] (h : cg L M) (f : M →[L] N) (hs : function.surjective f) : cg L N := begin rw ← hom.range_eq_top at hs, rw [cg_def, ← hs], exact h.range f, end lemma cg_iff_countable [L.countable_functions] : cg L M ↔ nonempty (encodable M) := by rw [cg_def, cg_iff_countable, cardinal.encodable_iff, cardinal.encodable_iff, top_equiv.to_equiv.cardinal_eq] lemma fg.cg (h : fg L M) : cg L M := cg_def.2 (fg_def.1 h).cg @[priority 100] instance cg_of_fg [h : fg L M] : cg L M := h.cg end Structure lemma equiv.fg_iff {N : Type*} [L.Structure N] (f : M ≃[L] N) : Structure.fg L M ↔ Structure.fg L N := ⟨λ h, h.map_of_surjective f.to_hom f.to_equiv.surjective, λ h, h.map_of_surjective f.symm.to_hom f.to_equiv.symm.surjective⟩ lemma substructure.fg_iff_Structure_fg (S : L.substructure M) : S.fg ↔ Structure.fg L S := begin rw Structure.fg_def, refine ⟨λ h, fg.of_map_embedding S.subtype _, λ h, _⟩, { rw [← hom.range_eq_map, range_subtype], exact h }, { have h := h.map S.subtype.to_hom, rw [← hom.range_eq_map, range_subtype] at h, exact h } end lemma equiv.cg_iff {N : Type*} [L.Structure N] (f : M ≃[L] N) : Structure.cg L M ↔ Structure.cg L N := ⟨λ h, h.map_of_surjective f.to_hom f.to_equiv.surjective, λ h, h.map_of_surjective f.symm.to_hom f.to_equiv.symm.surjective⟩ lemma substructure.cg_iff_Structure_cg (S : L.substructure M) : S.cg ↔ Structure.cg L S := begin rw Structure.cg_def, refine ⟨λ h, cg.of_map_embedding S.subtype _, λ h, _⟩, { rw [← hom.range_eq_map, range_subtype], exact h }, { have h := h.map S.subtype.to_hom, rw [← hom.range_eq_map, range_subtype] at h, exact h } end end language end first_order
383c9533da8716deb4d7c1850a52d223691c241c
969dbdfed67fda40a6f5a2b4f8c4a3c7dc01e0fb
/src/field_theory/intermediate_field.lean
7b9a9b853773bf72a5cf448933f8308006d9c872
[ "Apache-2.0" ]
permissive
SAAluthwela/mathlib
62044349d72dd63983a8500214736aa7779634d3
83a4b8b990907291421de54a78988c024dc8a552
refs/heads/master
1,679,433,873,417
1,615,998,031,000
1,615,998,031,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,823
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import field_theory.subfield import field_theory.tower import ring_theory.algebraic /-! # Intermediate fields Let `L / K` be a field extension, given as an instance `algebra K L`. This file defines the type of fields in between `K` and `L`, `intermediate_field K L`. An `intermediate_field K L` is a subfield of `L` which contains (the image of) `K`, i.e. it is a `subfield L` and a `subalgebra K L`. ## Main definitions * `intermediate_field K L` : the type of intermediate fields between `K` and `L`. * `subalgebra.to_intermediate_field`: turns a subalgebra closed under `⁻¹` into an intermediate field * `subfield.to_intermediate_field`: turns a subfield containing the image of `K` into an intermediate field * `intermediate_field.map`: map an intermediate field along an `alg_hom` ## Implementation notes Intermediate fields are defined with a structure extending `subfield` and `subalgebra`. A `subalgebra` is closed under all operations except `⁻¹`, ## Tags intermediate field, field extension -/ open finite_dimensional open_locale big_operators variables (K L : Type*) [field K] [field L] [algebra K L] section set_option old_structure_cmd true /-- `S : intermediate_field K L` is a subset of `L` such that there is a field tower `L / S / K`. -/ structure intermediate_field extends subalgebra K L, subfield L /-- Reinterpret an `intermediate_field` as a `subalgebra`. -/ add_decl_doc intermediate_field.to_subalgebra /-- Reinterpret an `intermediate_field` as a `subfield`. -/ add_decl_doc intermediate_field.to_subfield end variables {K L} (S : intermediate_field K L) namespace intermediate_field instance : has_coe (intermediate_field K L) (set L) := ⟨intermediate_field.carrier⟩ @[simp] lemma coe_to_subalgebra : (S.to_subalgebra : set L) = S := rfl @[simp] lemma coe_to_subfield : (S.to_subfield : set L) = S := rfl instance : has_coe_to_sort (intermediate_field K L) := ⟨Type*, λ S, S.carrier⟩ instance : has_mem L (intermediate_field K L) := ⟨λ m S, m ∈ (S : set L)⟩ @[simp] lemma mem_mk (s : set L) (hK : ∀ x, algebra_map K L x ∈ s) (ho hm hz ha hn hi) (x : L) : x ∈ intermediate_field.mk s ho hm hz ha hK hn hi ↔ x ∈ s := iff.rfl @[simp] lemma mem_coe (x : L) : x ∈ (S : set L) ↔ x ∈ S := iff.rfl @[simp] lemma mem_to_subalgebra (s : intermediate_field K L) (x : L) : x ∈ s.to_subalgebra ↔ x ∈ s := iff.rfl @[simp] lemma mem_to_subfield (s : intermediate_field K L) (x : L) : x ∈ s.to_subfield ↔ x ∈ s := iff.rfl /-- Two intermediate fields are equal if the underlying subsets are equal. -/ theorem ext' ⦃s t : intermediate_field K L⦄ (h : (s : set L) = t) : s = t := by { cases s, cases t, congr' } /-- Two intermediate fields are equal if and only if the underlying subsets are equal. -/ protected theorem ext'_iff {s t : intermediate_field K L} : s = t ↔ (s : set L) = t := ⟨λ h, h ▸ rfl, λ h, ext' h⟩ /-- Two intermediate fields are equal if they have the same elements. -/ @[ext] theorem ext {S T : intermediate_field K L} (h : ∀ x, x ∈ S ↔ x ∈ T) : S = T := ext' $ set.ext h /-- An intermediate field contains the image of the smaller field. -/ theorem algebra_map_mem (x : K) : algebra_map K L x ∈ S := S.algebra_map_mem' x /-- An intermediate field contains the ring's 1. -/ theorem one_mem : (1 : L) ∈ S := S.one_mem' /-- An intermediate field contains the ring's 0. -/ theorem zero_mem : (0 : L) ∈ S := S.zero_mem' /-- An intermediate field is closed under multiplication. -/ theorem mul_mem : ∀ {x y : L}, x ∈ S → y ∈ S → x * y ∈ S := S.mul_mem' /-- An intermediate field is closed under scalar multiplication. -/ theorem smul_mem {y : L} : y ∈ S → ∀ {x : K}, x • y ∈ S := S.to_subalgebra.smul_mem /-- An intermediate field is closed under addition. -/ theorem add_mem : ∀ {x y : L}, x ∈ S → y ∈ S → x + y ∈ S := S.add_mem' /-- An intermediate field is closed under subtraction -/ theorem sub_mem {x y : L} (hx : x ∈ S) (hy : y ∈ S) : x - y ∈ S := S.to_subfield.sub_mem hx hy /-- An intermediate field is closed under negation. -/ theorem neg_mem : ∀ {x : L}, x ∈ S → -x ∈ S := S.neg_mem' /-- An intermediate field is closed under inverses. -/ theorem inv_mem : ∀ {x : L}, x ∈ S → x⁻¹ ∈ S := S.inv_mem' /-- An intermediate field is closed under division. -/ theorem div_mem {x y : L} (hx : x ∈ S) (hy : y ∈ S) : x / y ∈ S := S.to_subfield.div_mem hx hy /-- Product of a list of elements in an intermediate_field is in the intermediate_field. -/ lemma list_prod_mem {l : list L} : (∀ x ∈ l, x ∈ S) → l.prod ∈ S := S.to_subfield.list_prod_mem /-- Sum of a list of elements in an intermediate field is in the intermediate_field. -/ lemma list_sum_mem {l : list L} : (∀ x ∈ l, x ∈ S) → l.sum ∈ S := S.to_subfield.list_sum_mem /-- Product of a multiset of elements in an intermediate field is in the intermediate_field. -/ lemma multiset_prod_mem (m : multiset L) : (∀ a ∈ m, a ∈ S) → m.prod ∈ S := S.to_subfield.multiset_prod_mem m /-- Sum of a multiset of elements in a `intermediate_field` is in the `intermediate_field`. -/ lemma multiset_sum_mem (m : multiset L) : (∀ a ∈ m, a ∈ S) → m.sum ∈ S := S.to_subfield.multiset_sum_mem m /-- Product of elements of an intermediate field indexed by a `finset` is in the intermediate_field. -/ lemma prod_mem {ι : Type*} {t : finset ι} {f : ι → L} (h : ∀ c ∈ t, f c ∈ S) : ∏ i in t, f i ∈ S := S.to_subfield.prod_mem h /-- Sum of elements in a `intermediate_field` indexed by a `finset` is in the `intermediate_field`. -/ lemma sum_mem {ι : Type*} {t : finset ι} {f : ι → L} (h : ∀ c ∈ t, f c ∈ S) : ∑ i in t, f i ∈ S := S.to_subfield.sum_mem h lemma pow_mem {x : L} (hx : x ∈ S) (n : ℤ) : x^n ∈ S := begin cases n, { exact @is_submonoid.pow_mem L _ S.to_subfield.to_submonoid x _ hx n, }, { have h := @is_submonoid.pow_mem L _ S.to_subfield.to_submonoid x _ hx _, exact subfield.inv_mem S.to_subfield h, }, end lemma gsmul_mem {x : L} (hx : x ∈ S) (n : ℤ) : n •ℤ x ∈ S := S.to_subfield.gsmul_mem hx n lemma coe_int_mem (n : ℤ) : (n : L) ∈ S := by simp only [← gsmul_one, gsmul_mem, one_mem] end intermediate_field /-- Turn a subalgebra closed under inverses into an intermediate field -/ def subalgebra.to_intermediate_field (S : subalgebra K L) (inv_mem : ∀ x ∈ S, x⁻¹ ∈ S) : intermediate_field K L := { neg_mem' := λ x, S.neg_mem, inv_mem' := inv_mem, .. S } @[simp] lemma to_subalgebra_to_intermediate_field (S : subalgebra K L) (inv_mem : ∀ x ∈ S, x⁻¹ ∈ S) : (S.to_intermediate_field inv_mem).to_subalgebra = S := by { ext, refl } @[simp] lemma to_intermediate_field_to_subalgebra (S : intermediate_field K L) (inv_mem : ∀ x ∈ S.to_subalgebra, x⁻¹ ∈ S) : S.to_subalgebra.to_intermediate_field inv_mem = S := by { ext, refl } /-- Turn a subfield of `L` containing the image of `K` into an intermediate field -/ def subfield.to_intermediate_field (S : subfield L) (algebra_map_mem : ∀ x, algebra_map K L x ∈ S) : intermediate_field K L := { algebra_map_mem' := algebra_map_mem, .. S } namespace intermediate_field /-- An intermediate field inherits a field structure -/ instance to_field : field S := S.to_subfield.to_field @[simp, norm_cast] lemma coe_add (x y : S) : (↑(x + y) : L) = ↑x + ↑y := rfl @[simp, norm_cast] lemma coe_neg (x : S) : (↑(-x) : L) = -↑x := rfl @[simp, norm_cast] lemma coe_mul (x y : S) : (↑(x * y) : L) = ↑x * ↑y := rfl @[simp, norm_cast] lemma coe_inv (x : S) : (↑(x⁻¹) : L) = (↑x)⁻¹ := rfl @[simp, norm_cast] lemma coe_zero : ((0 : S) : L) = 0 := rfl @[simp, norm_cast] lemma coe_one : ((1 : S) : L) = 1 := rfl @[simp, norm_cast] lemma coe_pow (x : S) (n : ℕ) : (↑(x ^ n) : L) = ↑x ^ n := @nat.rec (λ n, (↑(x ^ n) : L) = ↑x ^ n) rfl (λ _ h, congr_arg (has_mul.mul ↑x) h) n instance algebra : algebra K S := S.to_subalgebra.algebra instance to_algebra : algebra S L := S.to_subalgebra.to_algebra instance : is_scalar_tower K S L := is_scalar_tower.subalgebra' _ _ _ S.to_subalgebra variables {L' : Type*} [field L'] [algebra K L'] /-- If `f : L →+* L'` fixes `K`, `S.map f` is the intermediate field between `L'` and `K` such that `x ∈ S ↔ f x ∈ S.map f`. -/ def map (f : L →ₐ[K] L') : intermediate_field K L' := { inv_mem' := by { rintros _ ⟨x, hx, rfl⟩, exact ⟨x⁻¹, S.inv_mem hx, f.map_inv x⟩ }, neg_mem' := λ x hx, (S.to_subalgebra.map f).neg_mem hx, .. S.to_subalgebra.map f} /-- The embedding from an intermediate field of `L / K` to `L`. -/ def val : S →ₐ[K] L := S.to_subalgebra.val @[simp] theorem coe_val : ⇑S.val = coe := rfl @[simp] lemma val_mk {x : L} (hx : x ∈ S) : S.val ⟨x, hx⟩ = x := rfl variables {S} lemma to_subalgebra_injective {S S' : intermediate_field K L} (h : S.to_subalgebra = S'.to_subalgebra) : S = S' := by { ext, rw [← mem_to_subalgebra, ← mem_to_subalgebra, h] } instance : partial_order (intermediate_field K L) := { le := λ S T, (S : set L) ⊆ T, le_refl := λ S, set.subset.refl S, le_trans := λ _ _ _, set.subset.trans, le_antisymm := λ S T hst hts, ext $ λ x, ⟨@hst x, @hts x⟩ } variables (S) lemma set_range_subset : set.range (algebra_map K L) ⊆ S := S.to_subalgebra.range_subset lemma field_range_le : (algebra_map K L).field_range ≤ S.to_subfield := λ x hx, S.to_subalgebra.range_subset (by rwa [set.mem_range, ← ring_hom.mem_field_range]) @[simp] lemma to_subalgebra_le_to_subalgebra {S S' : intermediate_field K L} : S.to_subalgebra ≤ S'.to_subalgebra ↔ S ≤ S' := iff.rfl @[simp] lemma to_subalgebra_lt_to_subalgebra {S S' : intermediate_field K L} : S.to_subalgebra < S'.to_subalgebra ↔ S < S' := iff.rfl variables {S} section tower /-- Lift an intermediate_field of an intermediate_field -/ def lift1 {F : intermediate_field K L} (E : intermediate_field K F) : intermediate_field K L := map E (val F) /-- Lift an intermediate_field of an intermediate_field -/ def lift2 {F : intermediate_field K L} (E : intermediate_field F L) : intermediate_field K L := { carrier := E.carrier, zero_mem' := zero_mem E, add_mem' := λ x y, add_mem E, neg_mem' := λ x, neg_mem E, one_mem' := one_mem E, mul_mem' := λ x y, mul_mem E, inv_mem' := λ x, inv_mem E, algebra_map_mem' := λ x, algebra_map_mem E (algebra_map K F x) } instance has_lift1 {F : intermediate_field K L} : has_lift_t (intermediate_field K F) (intermediate_field K L) := ⟨lift1⟩ instance has_lift2 {F : intermediate_field K L} : has_lift_t (intermediate_field F L) (intermediate_field K L) := ⟨lift2⟩ @[simp] lemma mem_lift2 {F : intermediate_field K L} {E : intermediate_field F L} {x : L} : x ∈ (↑E : intermediate_field K L) ↔ x ∈ E := iff.rfl instance lift2_alg {F : intermediate_field K L} {E : intermediate_field F L} : algebra K E := { to_fun := (algebra_map F E).comp (algebra_map K F), map_zero' := ((algebra_map F E).comp (algebra_map K F)).map_zero, map_one' := ((algebra_map F E).comp (algebra_map K F)).map_one, map_add' := ((algebra_map F E).comp (algebra_map K F)).map_add, map_mul' := ((algebra_map F E).comp (algebra_map K F)).map_mul, smul := λ a b, (((algebra_map F E).comp (algebra_map K F)) a) * b, smul_def' := λ _ _, rfl, commutes' := λ a b, mul_comm (((algebra_map F E).comp (algebra_map K F)) a) b } instance lift2_tower {F : intermediate_field K L} {E : intermediate_field F L} : is_scalar_tower K F E := ⟨λ a b c, by { simp only [algebra.smul_def, ring_hom.map_mul, mul_assoc], refl }⟩ /-- `lift2` is isomorphic to the original `intermediate_field`. -/ def lift2_alg_equiv {F : intermediate_field K L} (E : intermediate_field F L) : (↑E : intermediate_field K L) ≃ₐ[K] E := { to_fun := λ x, x, inv_fun := λ x, x, left_inv := λ x, rfl, right_inv := λ x, rfl, map_add' := λ x y, rfl, map_mul' := λ x y, rfl, commutes' := λ x, rfl } end tower section finite_dimensional variables (F E : intermediate_field K L) instance finite_dimensional_left [finite_dimensional K L] : finite_dimensional K F := finite_dimensional.finite_dimensional_submodule F.to_subalgebra.to_submodule instance finite_dimensional_right [finite_dimensional K L] : finite_dimensional F L := right K F L @[simp] lemma dim_eq_dim_subalgebra : vector_space.dim K F.to_subalgebra = vector_space.dim K F := rfl @[simp] lemma findim_eq_findim_subalgebra : findim K F.to_subalgebra = findim K F := rfl variables {F} {E} @[simp] lemma to_subalgebra_eq_iff : F.to_subalgebra = E.to_subalgebra ↔ F = E := by { rw [subalgebra.ext_iff, intermediate_field.ext'_iff, set.ext_iff], refl } lemma eq_of_le_of_findim_le [finite_dimensional K L] (h_le : F ≤ E) (h_findim : findim K E ≤ findim K F) : F = E := intermediate_field.ext'_iff.mpr (submodule.ext'_iff.mp (eq_of_le_of_findim_le (show F.to_subalgebra.to_submodule ≤ E.to_subalgebra.to_submodule, by exact h_le) h_findim)) lemma eq_of_le_of_findim_eq [finite_dimensional K L] (h_le : F ≤ E) (h_findim : findim K F = findim K E) : F = E := eq_of_le_of_findim_le h_le h_findim.ge lemma eq_of_le_of_findim_le' [finite_dimensional K L] (h_le : F ≤ E) (h_findim : findim F L ≤ findim E L) : F = E := begin apply eq_of_le_of_findim_le h_le, have h1 := findim_mul_findim K F L, have h2 := findim_mul_findim K E L, have h3 : 0 < findim E L := findim_pos, nlinarith, end lemma eq_of_le_of_findim_eq' [finite_dimensional K L] (h_le : F ≤ E) (h_findim : findim F L = findim E L) : F = E := eq_of_le_of_findim_le' h_le h_findim.le end finite_dimensional end intermediate_field /-- If `L/K` is algebraic, the `K`-subalgebras of `L` are all fields. -/ def subalgebra_equiv_intermediate_field (alg : algebra.is_algebraic K L) : subalgebra K L ≃o intermediate_field K L := { to_fun := λ S, S.to_intermediate_field (λ x hx, S.inv_mem_of_algebraic (alg (⟨x, hx⟩ : S))), inv_fun := λ S, S.to_subalgebra, left_inv := λ S, to_subalgebra_to_intermediate_field _ _, right_inv := λ S, to_intermediate_field_to_subalgebra _ _, map_rel_iff' := λ S S', iff.rfl } @[simp] lemma mem_subalgebra_equiv_intermediate_field (alg : algebra.is_algebraic K L) {S : subalgebra K L} {x : L} : x ∈ subalgebra_equiv_intermediate_field alg S ↔ x ∈ S := iff.rfl @[simp] lemma mem_subalgebra_equiv_intermediate_field_symm (alg : algebra.is_algebraic K L) {S : intermediate_field K L} {x : L} : x ∈ (subalgebra_equiv_intermediate_field alg).symm S ↔ x ∈ S := iff.rfl
94e07bb6e68977e4db00599fe0078feb67c6ac15
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/lean/fail/failed_lemma.lean
2164758419fa743fea159cdd26ee2c3fc9da4ea4
[ "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
40
lean
lemma wrong : False := by tactic.failed
4eac77a360ec407f13f14f38b9236dc30c4ed027
4727251e0cd73359b15b664c3170e5d754078599
/src/data/matrix/basis.lean
cb40e55b8f0b427750fb7e0545fbe45875296762
[ "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
5,373
lean
/- Copyright (c) 2020 Jalex Stark. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jalex Stark, Scott Morrison, Eric Wieser, Oliver Nash -/ import data.matrix.basic import linear_algebra.matrix.trace /-! # Matrices with a single non-zero element. This file provides `matrix.std_basis_matrix`. The matrix `matrix.std_basis_matrix i j c` has `c` at position `(i, j)`, and zeroes elsewhere. -/ variables {l m n : Type*} variables {R α : Type*} namespace matrix open_locale matrix open_locale big_operators variables [decidable_eq l] [decidable_eq m] [decidable_eq n] variables [semiring α] /-- `std_basis_matrix i j a` is the matrix with `a` in the `i`-th row, `j`-th column, and zeroes elsewhere. -/ def std_basis_matrix (i : m) (j : n) (a : α) : matrix m n α := (λ i' j', if i = i' ∧ j = j' then a else 0) @[simp] lemma smul_std_basis_matrix (i : m) (j : n) (a b : α) : b • std_basis_matrix i j a = std_basis_matrix i j (b • a) := by { unfold std_basis_matrix, ext, simp } @[simp] lemma std_basis_matrix_zero (i : m) (j : n) : std_basis_matrix i j (0 : α) = 0 := by { unfold std_basis_matrix, ext, simp } lemma std_basis_matrix_add (i : m) (j : n) (a b : α) : std_basis_matrix i j (a + b) = std_basis_matrix i j a + std_basis_matrix i j b := begin unfold std_basis_matrix, ext, split_ifs with h; simp [h], end lemma matrix_eq_sum_std_basis [fintype m] [fintype n] (x : matrix m n α) : x = ∑ (i : m) (j : n), std_basis_matrix i j (x i j) := begin ext, symmetry, iterate 2 { rw finset.sum_apply }, convert fintype.sum_eq_single i _, { simp [std_basis_matrix] }, { intros j hj, simp [std_basis_matrix, hj], } end -- TODO: tie this up with the `basis` machinery of linear algebra -- this is not completely trivial because we are indexing by two types, instead of one -- TODO: add `std_basis_vec` lemma std_basis_eq_basis_mul_basis (i : m) (j : n) : std_basis_matrix i j 1 = vec_mul_vec (λ i', ite (i = i') 1 0) (λ j', ite (j = j') 1 0) := begin ext, norm_num [std_basis_matrix, vec_mul_vec], exact ite_and _ _ _ _, end -- todo: the old proof used fintypes, I don't know `finsupp` but this feels generalizable @[elab_as_eliminator] protected lemma induction_on' [fintype m] [fintype n] {P : matrix m n α → Prop} (M : matrix m n α) (h_zero : P 0) (h_add : ∀ p q, P p → P q → P (p + q)) (h_std_basis : ∀ (i : m) (j : n) (x : α), P (std_basis_matrix i j x)) : P M := begin rw [matrix_eq_sum_std_basis M, ← finset.sum_product'], apply finset.sum_induction _ _ h_add h_zero, { intros, apply h_std_basis, } end @[elab_as_eliminator] protected lemma induction_on [fintype m] [fintype n] [nonempty m] [nonempty n] {P : matrix m n α → Prop} (M : matrix m n α) (h_add : ∀ p q, P p → P q → P (p + q)) (h_std_basis : ∀ i j x, P (std_basis_matrix i j x)) : P M := matrix.induction_on' M begin inhabit m, inhabit n, simpa using h_std_basis default default 0 end h_add h_std_basis namespace std_basis_matrix section variables (i : m) (j : n) (c : α) (i' : m) (j' : n) @[simp] lemma apply_same : std_basis_matrix i j c i j = c := if_pos (and.intro rfl rfl) @[simp] lemma apply_of_ne (h : ¬((i = i') ∧ (j = j'))) : std_basis_matrix i j c i' j' = 0 := by { simp only [std_basis_matrix, and_imp, ite_eq_right_iff], tauto } @[simp] lemma apply_of_row_ne {i i' : m} (hi : i ≠ i') (j j' : n) (a : α) : std_basis_matrix i j a i' j' = 0 := by simp [hi] @[simp] lemma apply_of_col_ne (i i' : m) {j j' : n} (hj : j ≠ j') (a : α) : std_basis_matrix i j a i' j' = 0 := by simp [hj] end section variables (i j : n) (c : α) (i' j' : n) @[simp] lemma diag_zero (h : j ≠ i) : diag (std_basis_matrix i j c) = 0 := funext $ λ k, if_neg $ λ ⟨e₁, e₂⟩, h (e₂.trans e₁.symm) @[simp] lemma diag_same : diag (std_basis_matrix i i c) = pi.single i c := by { ext j, by_cases hij : i = j; try {rw hij}; simp [hij] } variable [fintype n] @[simp] lemma trace_zero (h : j ≠ i) : trace (std_basis_matrix i j c) = 0 := by simp [trace, h] @[simp] lemma trace_eq : trace (std_basis_matrix i i c) = c := by simp [trace] @[simp] lemma mul_left_apply_same (b : n) (M : matrix n n α) : (std_basis_matrix i j c ⬝ M) i b = c * M j b := by simp [mul_apply, std_basis_matrix] @[simp] lemma mul_right_apply_same (a : n) (M : matrix n n α) : (M ⬝ std_basis_matrix i j c) a j = M a i * c := by simp [mul_apply, std_basis_matrix, mul_comm] @[simp] lemma mul_left_apply_of_ne (a b : n) (h : a ≠ i) (M : matrix n n α) : (std_basis_matrix i j c ⬝ M) a b = 0 := by simp [mul_apply, h.symm] @[simp] lemma mul_right_apply_of_ne (a b : n) (hbj : b ≠ j) (M : matrix n n α) : (M ⬝ std_basis_matrix i j c) a b = 0 := by simp [mul_apply, hbj.symm] @[simp] lemma mul_same (k : n) (d : α) : std_basis_matrix i j c ⬝ std_basis_matrix j k d = std_basis_matrix i k (c * d) := begin ext a b, simp only [mul_apply, std_basis_matrix, boole_mul], by_cases h₁ : i = a; by_cases h₂ : k = b; simp [h₁, h₂], end @[simp] lemma mul_of_ne {k l : n} (h : j ≠ k) (d : α) : std_basis_matrix i j c ⬝ std_basis_matrix k l d = 0 := begin ext a b, simp only [mul_apply, boole_mul, std_basis_matrix], by_cases h₁ : i = a; simp [h₁, h, h.symm], end end end std_basis_matrix end matrix
5b687b4c2103ebb498659d7082369dd8bf8f39f8
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/topology/omega_complete_partial_order.lean
ab5e7b5c03cd3cab50486d6e4b3f55828342b7c7
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
5,202
lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: 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 } _, { simpa using h₀ }, { simp only [flip, set.mem_image] at *, rcases ht with ⟨x,h₀,h₁⟩, subst h₁, simpa, } 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_iff_imp], 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_iff_imp, 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 dsimp [_root_.continuous, (⁻¹')] 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_iff_imp] at hf, by_contradiction, apply hf a (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, 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 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
2f4fb89ececc42eb4325b6d6754e5e03200dec3f
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/bicategory/End.lean
f677e134b87f8016d21839da59d67d6d6f453a22
[ "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
1,140
lean
/- Copyright (c) 2022 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.bicategory.basic import category_theory.monoidal.category /-! # Endomorphisms of an object in a bicategory, as a monoidal category. -/ namespace category_theory variables {C : Type*} [bicategory C] /-- The endomorphisms of an object in a bicategory can be considered as a monoidal category. -/ @[derive category] def End_monoidal (X : C) := X ⟶ X instance (X : C) : inhabited (End_monoidal X) := ⟨𝟙 X⟩ open_locale bicategory open monoidal_category open bicategory instance (X : C) : monoidal_category (End_monoidal X) := { tensor_obj := λ f g, f ≫ g, tensor_hom := λ f g h i η θ, (η ▷ h) ≫ (g ◁ θ), tensor_unit := 𝟙 _, associator := λ f g h, α_ f g h, left_unitor := λ f, λ_ f, right_unitor := λ f, ρ_ f, tensor_comp' := begin intros, rw [bicategory.whisker_left_comp, bicategory.comp_whisker_right, category.assoc, category.assoc, bicategory.whisker_exchange_assoc], end } end category_theory
fa84e317109ed6322b65bbfbf2ce9f5f2963819a
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/ring_theory/fractional_ideal.lean
6d0f711fc3613a8d8e4b7f656ed36b94346dea95
[ "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
24,194
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import ring_theory.localization import ring_theory.principal_ideal_domain /-! # Fractional ideals This file defines fractional ideals of an integral domain and proves basic facts about them. ## Main definitions Let `S` be a submonoid of an integral domain `R`, `P` the localization of `R` at `S`, and `f` the natural ring hom from `R` to `P`. * `is_fractional` defines which `R`-submodules of `P` are fractional ideals * `fractional_ideal f` is the type of fractional ideals in `P` * `has_coe (ideal R) (fractional_ideal f)` instance * `comm_semiring (fractional_ideal f)` instance: the typical ideal operations generalized to fractional ideals * `lattice (fractional_ideal f)` instance * `map` is the pushforward of a fractional ideal along an algebra morphism Let `K` be the localization of `R` at `R \ {0}` and `g` the natural ring hom from `R` to `K`. * `has_div (fractional_ideal g)` instance: the ideal quotient `I / J` (typically written $I : J$, but a `:` operator cannot be defined) ## Main statements * `mul_left_mono` and `mul_right_mono` state that ideal multiplication is monotone * `right_inverse_eq` states that `1 / I` is the inverse of `I` if one exists ## Implementation notes Fractional ideals are considered equal when they contain the same elements, independent of the denominator `a : R` such that `a I ⊆ R`. Thus, we define `fractional_ideal` to be the subtype of the predicate `is_fractional`, instead of having `fractional_ideal` be a structure of which `a` is a field. Most definitions in this file specialize operations from submodules to fractional ideals, proving that the result of this operation is fractional if the input is fractional. Exceptions to this rule are defining `(+) := (⊔)` and `⊥ := 0`, in order to re-use their respective proof terms. We can still use `simp` to show `I.1 + J.1 = (I + J).1` and `⊥.1 = 0.1`. In `ring_theory.localization`, we define a copy of the localization map `f`'s codomain `P` (`f.codomain`) so that the `R`-algebra instance on `P` can 'know' the map needed to induce the `R`-algebra structure. We don't assume that the localization is a field until we need it to define ideal quotients. When this assumption is needed, we replace `S` with `non_zero_divisors R`, making the localization a field. ## References * https://en.wikipedia.org/wiki/Fractional_ideal ## Tags fractional ideal, fractional ideals, invertible ideal -/ open localization_map namespace ring section defs variables {R : Type*} [integral_domain R] {S : submonoid R} {P : Type*} [comm_ring P] (f : localization_map S P) /-- A submodule `I` is a fractional ideal if `a I ⊆ R` for some `a ≠ 0`. -/ def is_fractional (I : submodule R f.codomain) := ∃ a ∈ S, ∀ b ∈ I, f.is_integer (f.to_map a * b) /-- The fractional ideals of a domain `R` are ideals of `R` divided by some `a ∈ R`. More precisely, let `P` be a localization of `R` at some submonoid `S`, then a fractional ideal `I ⊆ P` is an `R`-submodule of `P`, such that there is a nonzero `a : R` with `a I ⊆ R`. -/ def fractional_ideal := {I : submodule R f.codomain // is_fractional f I} end defs namespace fractional_ideal open set open submodule variables {R : Type*} [integral_domain R] {S : submonoid R} {P : Type*} [comm_ring P] {f : localization_map S P} instance : has_coe (fractional_ideal f) (submodule R f.codomain) := ⟨λ I, I.val⟩ @[simp] lemma val_eq_coe (I : fractional_ideal f) : I.val = I := rfl instance : has_mem P (fractional_ideal f) := ⟨λ x I, x ∈ (I : submodule R f.codomain)⟩ /-- Fractional ideals are equal if their submodules are equal. Combined with `submodule.ext` this gives that fractional ideals are equal if they have the same elements. -/ @[ext] lemma ext {I J : fractional_ideal f} : (I : submodule R f.codomain) = J → I = J := subtype.ext_iff_val.mpr lemma fractional_of_subset_one (I : submodule R f.codomain) (h : I ≤ (submodule.span R {1})) : is_fractional f I := begin use [1, S.one_mem], intros b hb, rw [f.to_map.map_one, one_mul], rw ←submodule.one_eq_span at h, obtain ⟨b', b'_mem, b'_eq_b⟩ := h hb, rw (show b = f.to_map b', from b'_eq_b.symm), exact set.mem_range_self b', end instance coe_to_fractional_ideal : has_coe (ideal R) (fractional_ideal f) := ⟨ λ I, ⟨↑I, fractional_of_subset_one _ $ λ x ⟨y, hy, h⟩, submodule.mem_span_singleton.2 ⟨y, by rw ←h; exact mul_one _⟩⟩ ⟩ @[simp] lemma coe_coe_ideal (I : ideal R) : ((I : fractional_ideal f) : submodule R f.codomain) = I := rfl @[simp] lemma mem_coe {x : f.codomain} {I : ideal R} : x ∈ (I : fractional_ideal f) ↔ ∃ (x' ∈ I), f.to_map x' = x := ⟨ λ ⟨x', hx', hx⟩, ⟨x', hx', hx⟩, λ ⟨x', hx', hx⟩, ⟨x', hx', hx⟩ ⟩ instance : has_zero (fractional_ideal f) := ⟨(0 : ideal R)⟩ @[simp] lemma mem_zero_iff {x : P} : x ∈ (0 : fractional_ideal f) ↔ x = 0 := ⟨ (λ ⟨x', x'_mem_zero, x'_eq_x⟩, have x'_eq_zero : x' = 0 := x'_mem_zero, by simp [x'_eq_x.symm, x'_eq_zero]), (λ hx, ⟨0, rfl, by simp [hx]⟩) ⟩ @[simp] lemma coe_zero : ↑(0 : fractional_ideal f) = (⊥ : submodule R f.codomain) := submodule.ext $ λ _, mem_zero_iff lemma coe_ne_bot_iff_nonzero {I : fractional_ideal f} : ↑I ≠ (⊥ : submodule R f.codomain) ↔ I ≠ 0 := ⟨ λ h h', h (by simp [h']), λ h h', h (ext (by simp [h'])) ⟩ instance : inhabited (fractional_ideal f) := ⟨0⟩ instance : has_one (fractional_ideal f) := ⟨(1 : ideal R)⟩ lemma mem_one_iff {x : P} : x ∈ (1 : fractional_ideal f) ↔ ∃ x' : R, f.to_map x' = x := iff.intro (λ ⟨x', _, h⟩, ⟨x', h⟩) (λ ⟨x', h⟩, ⟨x', ⟨x', set.mem_univ _, rfl⟩, h⟩) lemma coe_mem_one (x : R) : f.to_map x ∈ (1 : fractional_ideal f) := mem_one_iff.mpr ⟨x, rfl⟩ lemma one_mem_one : (1 : P) ∈ (1 : fractional_ideal f) := mem_one_iff.mpr ⟨1, f.to_map.map_one⟩ @[simp] lemma coe_one : ↑(1 : fractional_ideal f) = ((1 : ideal R) : submodule R f.codomain) := rfl section lattice /-! ### `lattice` section Defines the order on fractional ideals as inclusion of their underlying sets, and ports the lattice structure on submodules to fractional ideals. -/ instance : partial_order (fractional_ideal f) := { le := λ I J, I.1 ≤ J.1, le_refl := λ I, le_refl I.1, le_antisymm := λ ⟨I, hI⟩ ⟨J, hJ⟩ hIJ hJI, by { congr, exact le_antisymm hIJ hJI }, le_trans := λ _ _ _ hIJ hJK, le_trans hIJ hJK } lemma le_iff {I J : fractional_ideal f} : I ≤ J ↔ (∀ x ∈ I, x ∈ J) := iff.refl _ lemma zero_le (I : fractional_ideal f) : 0 ≤ I := begin intros x hx, convert submodule.zero_mem _, simpa using hx end instance order_bot : order_bot (fractional_ideal f) := { bot := 0, bot_le := zero_le, ..fractional_ideal.partial_order } @[simp] lemma bot_eq_zero : (⊥ : fractional_ideal f) = 0 := rfl lemma eq_zero_iff {I : fractional_ideal f} : I = 0 ↔ (∀ x ∈ I, x = (0 : P)) := ⟨ (λ h x hx, by simpa [h, mem_zero_iff] using hx), (λ h, le_bot_iff.mp (λ x hx, mem_zero_iff.mpr (h x hx))) ⟩ lemma fractional_sup (I J : fractional_ideal f) : is_fractional f (I.1 ⊔ J.1) := begin rcases I.2 with ⟨aI, haI, hI⟩, rcases J.2 with ⟨aJ, haJ, hJ⟩, use aI * aJ, use S.mul_mem haI haJ, intros b hb, rcases mem_sup.mp hb with ⟨bI, hbI, bJ, hbJ, hbIJ⟩, rw [←hbIJ, mul_add], apply is_integer_add, { rw [mul_comm aI, f.to_map.map_mul, mul_assoc], apply is_integer_smul (hI bI hbI), }, { rw [f.to_map.map_mul, mul_assoc], apply is_integer_smul (hJ bJ hbJ) } end lemma fractional_inf (I J : fractional_ideal f) : is_fractional f (I.1 ⊓ J.1) := begin rcases I.2 with ⟨aI, haI, hI⟩, use aI, use haI, intros b hb, rcases mem_inf.mp hb with ⟨hbI, hbJ⟩, exact (hI b hbI) end instance lattice : lattice (fractional_ideal f) := { inf := λ I J, ⟨I.1 ⊓ J.1, fractional_inf I J⟩, sup := λ I J, ⟨I.1 ⊔ J.1, fractional_sup I J⟩, inf_le_left := λ I J, show I.1 ⊓ J.1 ≤ I.1, from inf_le_left, inf_le_right := λ I J, show I.1 ⊓ J.1 ≤ J.1, from inf_le_right, le_inf := λ I J K hIJ hIK, show I.1 ≤ (J.1 ⊓ K.1), from le_inf hIJ hIK, le_sup_left := λ I J, show I.1 ≤ I.1 ⊔ J.1, from le_sup_left, le_sup_right := λ I J, show J.1 ≤ I.1 ⊔ J.1, from le_sup_right, sup_le := λ I J K hIK hJK, show (I.1 ⊔ J.1) ≤ K.1, from sup_le hIK hJK, ..fractional_ideal.partial_order } instance : semilattice_sup_bot (fractional_ideal f) := { ..fractional_ideal.order_bot, ..fractional_ideal.lattice } end lattice section semiring instance : has_add (fractional_ideal f) := ⟨(⊔)⟩ @[simp] lemma sup_eq_add (I J : fractional_ideal f) : I ⊔ J = I + J := rfl @[simp] lemma coe_add (I J : fractional_ideal f) : (↑(I + J) : submodule R f.codomain) = I + J := rfl lemma fractional_mul (I J : fractional_ideal f) : is_fractional f (I.1 * J.1) := begin rcases I with ⟨I, aI, haI, hI⟩, rcases J with ⟨I, aJ, haJ, hJ⟩, use aI * aJ, use S.mul_mem haI haJ, intros b hb, apply submodule.mul_induction_on hb, { intros m hm n hn, obtain ⟨n', hn'⟩ := hJ n hn, rw [f.to_map.map_mul, mul_comm m, ←mul_assoc, mul_assoc _ _ n], erw ←hn', rw mul_assoc, apply hI, exact submodule.smul_mem _ _ hm }, { rw [mul_zero], exact ⟨0, f.to_map.map_zero⟩ }, { intros x y hx hy, rw [mul_add], apply is_integer_add hx hy }, { intros r x hx, show f.is_integer (_ * (f.to_map r * x)), rw [←mul_assoc, ←f.to_map.map_mul, mul_comm _ r, f.to_map.map_mul, mul_assoc], apply is_integer_smul hx }, end instance : has_mul (fractional_ideal f) := ⟨λ I J, ⟨I.1 * J.1, fractional_mul I J⟩⟩ @[simp] lemma coe_mul (I J : fractional_ideal f) : (↑(I * J) : submodule R f.codomain) = I * J := rfl lemma mul_left_mono (I : fractional_ideal f) : monotone ((*) I) := λ J J' h, mul_le.mpr (λ x hx y hy, mul_mem_mul hx (h hy)) lemma mul_right_mono (I : fractional_ideal f) : monotone (λ J, J * I) := λ J J' h, mul_le.mpr (λ x hx y hy, mul_mem_mul (h hx) hy) instance add_comm_monoid : add_comm_monoid (fractional_ideal f) := { add_assoc := λ I J K, sup_assoc, add_comm := λ I J, sup_comm, add_zero := λ I, sup_bot_eq, zero_add := λ I, bot_sup_eq, ..fractional_ideal.has_zero, ..fractional_ideal.has_add } instance comm_monoid : comm_monoid (fractional_ideal f) := { mul_assoc := λ I J K, ext (submodule.mul_assoc _ _ _), mul_comm := λ I J, ext (submodule.mul_comm _ _), mul_one := λ I, begin ext, split; intro h, { apply mul_le.mpr _ h, rintros x hx y ⟨y', y'_mem_R, y'_eq_y⟩, rw [←y'_eq_y, mul_comm], exact submodule.smul_mem _ _ hx }, { have : x * 1 ∈ (I * 1) := mul_mem_mul h one_mem_one, rwa [mul_one] at this } end, one_mul := λ I, begin ext, split; intro h, { apply mul_le.mpr _ h, rintros x ⟨x', x'_mem_R, x'_eq_x⟩ y hy, rw ←x'_eq_x, exact submodule.smul_mem _ _ hy }, { have : 1 * x ∈ (1 * I) := mul_mem_mul one_mem_one h, rwa [one_mul] at this } end, ..fractional_ideal.has_mul, ..fractional_ideal.has_one } instance comm_semiring : comm_semiring (fractional_ideal f) := { mul_zero := λ I, eq_zero_iff.mpr (λ x hx, submodule.mul_induction_on hx (λ x hx y hy, by simp [mem_zero_iff.mp hy]) rfl (λ x y hx hy, by simp [hx, hy]) (λ r x hx, by simp [hx])), zero_mul := λ I, eq_zero_iff.mpr (λ x hx, submodule.mul_induction_on hx (λ x hx y hy, by simp [mem_zero_iff.mp hx]) rfl (λ x y hx hy, by simp [hx, hy]) (λ r x hx, by simp [hx])), left_distrib := λ I J K, ext (mul_add _ _ _), right_distrib := λ I J K, ext (add_mul _ _ _), ..fractional_ideal.add_comm_monoid, ..fractional_ideal.comm_monoid } variables {P' : Type*} [comm_ring P'] {f' : localization_map S P'} variables {P'' : Type*} [comm_ring P''] {f'' : localization_map S P''} lemma fractional_map (g : f.codomain →ₐ[R] f'.codomain) (I : fractional_ideal f) : is_fractional f' (submodule.map g.to_linear_map I.1) := begin rcases I with ⟨I, a, a_nonzero, hI⟩, use [a, a_nonzero], intros b hb, obtain ⟨b', b'_mem, hb'⟩ := submodule.mem_map.mp hb, obtain ⟨x, hx⟩ := hI b' b'_mem, use x, erw [←g.commutes, hx, g.map_smul, hb'], refl end /-- `I.map g` is the pushforward of the fractional ideal `I` along the algebra morphism `g` -/ def map (g : f.codomain →ₐ[R] f'.codomain) : fractional_ideal f → fractional_ideal f' := λ I, ⟨submodule.map g.to_linear_map I.1, fractional_map g I⟩ @[simp] lemma coe_map (g : f.codomain →ₐ[R] f'.codomain) (I : fractional_ideal f) : ↑(map g I) = submodule.map g.to_linear_map I := rfl @[simp] lemma map_id (I : fractional_ideal f) : I.map (alg_hom.id _ _) = I := ext (submodule.map_id I.1) @[simp] lemma map_comp (g : f.codomain →ₐ[R] f'.codomain) (g' : f'.codomain →ₐ[R] f''.codomain) (I : fractional_ideal f) : I.map (g'.comp g) = (I.map g).map g' := ext (submodule.map_comp g.to_linear_map g'.to_linear_map I.1) @[simp] lemma map_add (I J : fractional_ideal f) (g : f.codomain →ₐ[R] f'.codomain) : (I + J).map g = I.map g + J.map g := ext (submodule.map_sup _ _ _) @[simp] lemma map_mul (I J : fractional_ideal f) (g : f.codomain →ₐ[R] f'.codomain) : (I * J).map g = I.map g * J.map g := ext (submodule.map_mul _ _ _) /-- If `g` is an equivalence, `map g` is an isomorphism -/ def map_equiv (g : f.codomain ≃ₐ[R] f'.codomain) : fractional_ideal f ≃+* fractional_ideal f' := { to_fun := map g, inv_fun := map g.symm, map_add' := λ I J, map_add I J _, map_mul' := λ I J, map_mul I J _, left_inv := λ I, by { rw [←map_comp, alg_equiv.symm_comp, map_id] }, right_inv := λ I, by { rw [←map_comp, alg_equiv.comp_symm, map_id] } } @[simp] lemma map_equiv_apply (g : f.codomain ≃ₐ[R] f'.codomain) (I : fractional_ideal f) : map_equiv g I = map ↑g I := rfl @[simp] lemma map_equiv_refl : map_equiv alg_equiv.refl = ring_equiv.refl (fractional_ideal f) := ring_equiv.ext (λ x, by simp) /-- `canonical_equiv f f'` is the canonical equivalence between the fractional ideals in `f.codomain` and in `f'.codomain` -/ noncomputable def canonical_equiv (f f' : localization_map S P) : fractional_ideal f ≃+* fractional_ideal f' := map_equiv { commutes' := λ r, ring_equiv_of_ring_equiv_eq _ _ _, ..ring_equiv_of_ring_equiv f f' (ring_equiv.refl R) (by rw [ring_equiv.to_monoid_hom_refl, submonoid.map_id]) } end semiring section quotient /-! ### `quotient` section This section defines the ideal quotient of fractional ideals. In this section we need that each non-zero `y : R` has an inverse in the localization, i.e. that the localization is a field. We satisfy this assumption by taking `S = non_zero_divisors R`, `R`'s localization at which is a field because `R` is a domain. -/ open_locale classical variables {K : Type*} [field K] {g : fraction_map R K} instance : nonzero (fractional_ideal g) := { zero_ne_one := λ h, have this : (1 : K) ∈ (0 : fractional_ideal g) := by rw ←g.to_map.map_one; convert coe_mem_one _, one_ne_zero (mem_zero_iff.mp this) } lemma fractional_div_of_nonzero {I J : fractional_ideal g} (h : J ≠ 0) : is_fractional g (I.1 / J.1) := begin rcases I with ⟨I, aI, haI, hI⟩, rcases J with ⟨J, aJ, haJ, hJ⟩, obtain ⟨y, mem_J, not_mem_zero⟩ := exists_of_lt (bot_lt_iff_ne_bot.mpr h), obtain ⟨y', hy'⟩ := hJ y mem_J, use (aI * y'), split, { apply (non_zero_divisors R).mul_mem haI (mem_non_zero_divisors_iff_ne_zero.mpr _), intro y'_eq_zero, have : g.to_map aJ * y = 0 := by rw [←hy', y'_eq_zero, g.to_map.map_zero], obtain aJ_zero | y_zero := mul_eq_zero.mp this, { have : aJ = 0 := g.to_map.injective_iff.1 g.injective _ aJ_zero, have : aJ ≠ 0 := mem_non_zero_divisors_iff_ne_zero.mp haJ, contradiction }, { exact not_mem_zero (mem_zero_iff.mpr y_zero) } }, intros b hb, rw [g.to_map.map_mul, mul_assoc, mul_comm _ b, hy'], exact hI _ (hb _ (submodule.smul_mem _ aJ mem_J)), end noncomputable instance fractional_ideal_has_div : has_div (fractional_ideal g) := ⟨ λ I J, if h : J = 0 then 0 else ⟨I.1 / J.1, fractional_div_of_nonzero h⟩ ⟩ noncomputable instance : has_inv (fractional_ideal g) := ⟨λ I, 1 / I⟩ lemma div_nonzero {I J : fractional_ideal g} (h : J ≠ 0) : (I / J) = ⟨I.1 / J.1, fractional_div_of_nonzero h⟩ := dif_neg h lemma inv_nonzero {I : fractional_ideal g} (h : I ≠ 0) : I⁻¹ = ⟨(1 : fractional_ideal g) / I, fractional_div_of_nonzero h⟩ := div_nonzero h lemma coe_inv_of_nonzero {I : fractional_ideal g} (h : I ≠ 0) : (↑(I⁻¹) : submodule R g.codomain) = (1 : ideal R) / I := by { rw inv_nonzero h, refl } @[simp] lemma div_one {I : fractional_ideal g} : I / 1 = I := begin rw [div_nonzero (@one_ne_zero (fractional_ideal g) _ _ _)], ext, split; intro h, { convert mem_div_iff_forall_mul_mem.mp h 1 (g.to_map.map_one ▸ coe_mem_one 1), simp }, { apply mem_div_iff_forall_mul_mem.mpr, rintros y ⟨y', _, y_eq_y'⟩, rw [mul_comm], convert submodule.smul_mem _ y' h, rw ←y_eq_y', refl } end lemma ne_zero_of_mul_eq_one (I J : fractional_ideal g) (h : I * J = 1) : I ≠ 0 := λ hI, @zero_ne_one (fractional_ideal g) _ _ _ (by { convert h, simp [hI], }) /-- `I⁻¹` is the inverse of `I` if `I` has an inverse. -/ theorem right_inverse_eq (I J : fractional_ideal g) (h : I * J = 1) : J = I⁻¹ := begin have hI : I ≠ 0 := 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) }, rw [div_nonzero hI], apply le_antisymm, { apply submodule.mul_le.mpr _, intros x hx y hy, rw [mul_comm], exact mem_div_iff_forall_mul_mem.mp hy x hx }, rw [←h], apply mul_left_mono I, apply submodule.le_div_iff.mpr _, intros y hy x hx, rw [mul_comm], exact mul_mem_mul hx hy end theorem mul_inv_cancel_iff {I : fractional_ideal g} : I * I⁻¹ = 1 ↔ ∃ J, I * J = 1 := ⟨λ h, ⟨I⁻¹, h⟩, λ ⟨J, hJ⟩, by rwa [←right_inverse_eq I J hJ]⟩ end quotient section principal_ideal_ring variables {K : Type*} [field K] {g : fraction_map R K} open_locale classical open submodule submodule.is_principal lemma span_fractional_iff {s : set f.codomain} : is_fractional f (span R s) ↔ ∃ a ∈ S, ∀ (b : P), b ∈ s → f.is_integer (f.to_map a * b) := ⟨ λ ⟨a, a_mem, h⟩, ⟨a, a_mem, λ b hb, h b (subset_span hb)⟩, λ ⟨a, a_mem, h⟩, ⟨a, a_mem, λ b hb, span_induction hb h (is_integer_smul ⟨0, f.to_map.map_zero⟩) (λ x y hx hy, by { rw mul_add, exact is_integer_add hx hy }) (λ s x hx, by { rw algebra.mul_smul_comm, exact is_integer_smul hx }) ⟩ ⟩ lemma span_singleton_fractional (x : f.codomain) : is_fractional f (span R {x}) := let ⟨a, ha⟩ := f.exists_integer_multiple x in span_fractional_iff.mpr ⟨ a.1, a.2, λ x hx, (mem_singleton_iff.mp hx).symm ▸ ha⟩ /-- `span_singleton x` is the fractional ideal generated by `x` if `0 ∉ S` -/ def span_singleton (x : f.codomain) : fractional_ideal f := ⟨span R {x}, span_singleton_fractional x⟩ @[simp] lemma coe_span_singleton (x : f.codomain) : (span_singleton x : submodule R f.codomain) = span R {x} := rfl lemma eq_span_singleton_of_principal (I : fractional_ideal f) [is_principal I.1] : I = span_singleton (generator I.1) := ext (span_singleton_generator I.1).symm lemma is_principal_iff (I : fractional_ideal f) : is_principal I.1 ↔ ∃ x, I = span_singleton x := ⟨ λ h, ⟨@generator _ _ _ _ _ I.1 h, @eq_span_singleton_of_principal _ _ _ _ _ _ I h⟩, λ ⟨x, hx⟩, { principal := ⟨x, trans (congr_arg _ hx) (coe_span_singleton x)⟩ } ⟩ @[simp] lemma span_singleton_zero : span_singleton (0 : f.codomain) = 0 := by { ext, simp [submodule.mem_span_singleton, eq_comm] } lemma span_singleton_eq_zero_iff {y : f.codomain} : span_singleton y = 0 ↔ y = 0 := ⟨ λ h, span_eq_bot.mp (by simpa using congr_arg subtype.val h) y (mem_singleton y), λ h, by simp [h] ⟩ @[simp] lemma span_singleton_one : span_singleton (1 : f.codomain) = 1 := begin ext, refine mem_span_singleton.trans ((exists_congr _).trans mem_one_iff.symm), intro x', refine eq.congr (mul_one _) rfl, end @[simp] lemma span_singleton_mul_span_singleton (x y : f.codomain) : span_singleton x * span_singleton y = span_singleton (x * y) := begin ext, simp_rw [coe_mul, coe_span_singleton, span_mul_span, singleton.is_mul_hom.map_mul] end @[simp] lemma coe_ideal_span_singleton (x : R) : (↑(span R {x} : ideal R) : fractional_ideal f) = span_singleton (f.to_map x) := begin ext y, refine mem_coe.trans (iff.trans _ mem_span_singleton.symm), split, { rintros ⟨y', hy', rfl⟩, obtain ⟨x', rfl⟩ := mem_span_singleton.mp hy', use x', rw [smul_eq_mul, f.to_map.map_mul], refl }, { rintros ⟨y', rfl⟩, exact ⟨y' * x, mem_span_singleton.mpr ⟨y', rfl⟩, f.to_map.map_mul _ _⟩ } end lemma mem_singleton_mul {x y : f.codomain} {I : fractional_ideal f} : y ∈ span_singleton x * I ↔ ∃ y' ∈ I, y = x * y' := begin split, { intro h, apply submodule.mul_induction_on h, { intros x' hx' y' hy', obtain ⟨a, ha⟩ := mem_span_singleton.mp hx', use [a • y', I.1.smul_mem a hy'], rw [←ha, algebra.mul_smul_comm, algebra.smul_mul_assoc] }, { exact ⟨0, I.1.zero_mem, (mul_zero x).symm⟩ }, { rintros _ _ ⟨y, hy, rfl⟩ ⟨y', hy', rfl⟩, exact ⟨y + y', I.1.add_mem hy hy', (mul_add _ _ _).symm⟩ }, { rintros r _ ⟨y', hy', rfl⟩, exact ⟨r • y', I.1.smul_mem r hy', (algebra.mul_smul_comm _ _ _).symm ⟩ } }, { rintros ⟨y', hy', rfl⟩, exact mul_mem_mul (mem_span_singleton.mpr ⟨1, one_smul _ _⟩) hy' } end lemma mul_generator_self_inv (I : fractional_ideal g) [submodule.is_principal I.1] (h : I ≠ 0) : I * span_singleton (generator I.1)⁻¹ = 1 := begin -- Rewrite only the `I` that appears alone. conv_lhs { congr, rw eq_span_singleton_of_principal I }, rw [span_singleton_mul_span_singleton, mul_inv_cancel, span_singleton_one], intro generator_I_eq_zero, apply h, rw [eq_span_singleton_of_principal I, generator_I_eq_zero, span_singleton_zero] end lemma exists_eq_span_singleton_mul (I : fractional_ideal g) : ∃ (a : K) (aI : ideal R), I = span_singleton a * aI := begin obtain ⟨a_inv, nonzero, ha⟩ := I.2, have nonzero := mem_non_zero_divisors_iff_ne_zero.mp nonzero, have map_a_nonzero := mt g.to_map_eq_zero_iff.mpr nonzero, use (g.to_map a_inv)⁻¹, use (span_singleton (g.to_map a_inv) * I).1.comap g.lin_coe, ext, refine iff.trans _ mem_singleton_mul.symm, split, { intro hx, obtain ⟨x', hx'⟩ := ha x hx, refine ⟨g.to_map x', mem_coe.mpr ⟨x', (mem_singleton_mul.mpr ⟨x, hx, hx'⟩), rfl⟩, _⟩, erw [hx', ←mul_assoc, inv_mul_cancel map_a_nonzero, one_mul] }, { rintros ⟨y, hy, rfl⟩, obtain ⟨x', hx', rfl⟩ := mem_coe.mp hy, obtain ⟨y', hy', hx'⟩ := mem_singleton_mul.mp hx', rw lin_coe_apply at hx', erw [hx', ←mul_assoc, inv_mul_cancel map_a_nonzero, one_mul], exact hy' } end instance is_principal {R} [integral_domain R] [is_principal_ideal_ring R] {f : fraction_map R K} (I : fractional_ideal f) : (I : submodule R f.codomain).is_principal := ⟨ begin obtain ⟨a, aI, ha⟩ := exists_eq_span_singleton_mul I, have := a * f.to_map (generator aI), use a * f.to_map (generator aI), suffices : I = span_singleton (a * f.to_map (generator aI)), { exact congr_arg subtype.val this }, conv_lhs { rw [ha, ←span_singleton_generator aI] }, rw [coe_ideal_span_singleton (generator aI), span_singleton_mul_span_singleton] end ⟩ end principal_ideal_ring end fractional_ideal end ring
af627e4db10b193efd71f61c36eb19978993dc11
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/run/core.lean
eb66c366f1e91ab6105c401da17c6ac69fcd39e8
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
282
lean
import Lean.CoreM new_frontend open Lean open Lean.Core def f : CoreM Nat := do let env ← getEnv; let cinfo ← getConstInfo `Nat.add; trace! `Elab "trace message"; IO.println $ toString cinfo.type; IO.println "testing..."; pure 10; #eval f set_option trace.Elab true #eval f
e73f3b814de2344f1ff9895d586900331e700e39
ad3e8f15221a986da27c99f371922c0b3f5792b6
/src/week-03/e01-languages.lean
44fc5688b21f6352b47af52f15a06f335b31eff5
[]
no_license
VArtem/lean-itmo
a0e1424c8cc4c2de2ac85ab6fd4a12d80e9b85f1
dc44cd06f9f5b984d051831b3aaa7364e64c2dc4
refs/heads/main
1,683,761,214,467
1,622,821,295,000
1,622,821,295,000
357,236,048
12
0
null
null
null
null
UTF-8
Lean
false
false
7,001
lean
import data.set.basic import data.list.basic import tactic open set list -- Будем рассматривать языкы над алфавитом α -- Язык это просто set (list α) namespace languages variables {α : Type} {L M : set (list α)} -- Несколько удобных сокращений: ε = пустой список, 0 = ∅, 1 = {ε}, A + B = A ∪ B def ε {α} : list α := [] instance : has_zero (set (list α)) := ⟨(∅ : set _)⟩ instance : has_one (set (list α)) := ⟨({[]} : set _)⟩ instance : has_add (set (list α)) := ⟨set.union⟩ -- Конкатенация языков состоит из таких слов `w`, что существуют слова `left ∈ L` и `right ∈ M`, что `w = left ++ right`) def append (L M: set (list α)) := { w : list α | ∃ (left ∈ L) (right ∈ M), w = left ++ right} -- Будем обозначать умножение как `L * M` instance : has_mul (set (list α)) := ⟨append⟩ -- И вспомогательные леммы def zero_def : (0 : set (list α)) = ∅ := rfl def one_def : (1 : set (list α)) = {[]} := rfl @[simp] def mem_zero {w : list α} : w ∉ (0 : set (list α)) := by simp @[simp] def mem_one {w : list α} : w ∈ (1 : set (list α)) ↔ w = [] := by refl @[simp] def nil_mem_one : [] ∈ (1 : set (list α)) := by simp -- Умелое использование `rcases` и `rintro` сильно вам поможет! @[simp] lemma zero_mul (L : set (list α)) : 0 * L = 0 := begin sorry, end @[simp] lemma mul_zero (L : set (list α)) : L * 0 = 0 := begin sorry, end @[simp] lemma append_one (A : set (list α)) : A * 1 = A := begin apply subset.antisymm, { sorry, }, { sorry, }, end @[simp] lemma one_append (A : set (list α)) : 1 * A = A := begin sorry, end lemma append_assoc (A B C : set (list α)): (A * B) * C = A * (B * C) := begin sorry, end lemma left_distrib (A B C : set (list α)) : A * (B + C) = A * B + A * C := begin sorry, end lemma right_distrib (A B C : set (list α)) : (A + B) * C = A * C + B * C := begin sorry, end -- Докажем, что множество языков с операциями + = ∪ и * = append образуют полукольцо: -- A + B - коммутативный моноид: 0, ассоциативность, коммутативность -- A * B - полугруппа: 1, ассоциативность -- Дистрибутивность и умножение на 0 -- Свойства (+) можно достать из стандартной библиотеки про `set.union`, а свойства (*) пришлось доказать instance : semiring (set (list α)) := { add := (+), add_assoc := set.union_assoc, zero := 0, zero_add := set.empty_union, add_zero := set.union_empty, add_comm := set.union_comm, mul := (*), mul_assoc := append_assoc, zero_mul := zero_mul, mul_zero := mul_zero, one := 1, one_mul := one_append, mul_one := append_one, left_distrib := left_distrib, right_distrib := right_distrib, } -- Теперь можно использовать L^n = L * L * ... * L (n раз) -- Полезные леммы: `pow_zero`, `pow_succ`, `pow_add`, ... lemma append_subset_of_subset {A B C D : set (list α)} : A ⊆ C → B ⊆ D → A * B ⊆ C * D := begin sorry, end lemma pow_subset_of_subset {A B : set (list α)} {n : ℕ} : A ⊆ B → A^n ⊆ B^n := begin sorry, end lemma contain_eps_subset_power {A : set (list α)} {n : ℕ} (h : 1 ⊆ A) : A ⊆ A^(n.succ) := begin sorry, end -- Замыкание Клини языка L равно объединению L^n по всем натуральным n def star (L : set (list α)) := {w : list α | ∃ (n : ℕ), w ∈ L^n} @[simp] lemma mem_star {w : list α} : w ∈ star L ↔ ∃ (n : ℕ), w ∈ L^n := by refl lemma star_eq_Union : star L = ⋃ (n : ℕ), L^n := begin ext w, simp only [mem_Union, mem_star], end @[simp] lemma nil_mem_star : [] ∈ star L := begin sorry, end @[simp] lemma one_subset_star : 1 ⊆ star L := begin simp, end @[simp] lemma pow_subset_star (n : ℕ) : L^n ⊆ star L := begin sorry, end @[simp] lemma subset_star : L ⊆ star L := begin sorry, end lemma star_subset_star : L ⊆ M → star L ⊆ star M := begin sorry, end lemma append_subset_star {A B L : set (list α)} : A ⊆ star L → B ⊆ star L → (A * B) ⊆ star L := begin sorry, end lemma star_append_star_eq_star : star L * star L = star L := begin sorry, end lemma pow_star_eq_star (n : ℕ) : (star L)^n.succ = star L := begin sorry, end -- Это было в ДЗ по дискретке! theorem star_star_eq_star : star (star L) = star L := begin sorry, end -- L^n равен множеству слов, которые можно получить, как конкатенацию `n` слов из `L`. -- Как записать, что `w` представляется как конкатенация `n` слов из `L`? -- `∃ (l : list (list α)) (h : ∀ x ∈ l, x ∈ L), w = list.join l ∧ l.length = n` -- Буквально: существует список слов `l`, что все слова в `l` принадлежат `L`, `w` равен `list.join l`, и длина `l` равна `n` -- Начались сложные задания! Изучите подробнее API `list`, `list.has_mem`, `list.join` и прочие полезные вещи, или увереннее используйте `simp` :) #check list.mem #check mem_cons_self #check list.join #check join_eq_nil lemma pow_eq_list_join {n : ℕ} : L^n = {w | ∃ (l : list (list α)) (h : ∀ x ∈ l, x ∈ L), w = list.join l ∧ l.length = n} := begin sorry, end lemma mem_pow_iff_list_join {w : list α} {n : ℕ} : w ∈ L^n ↔ ∃ l (h : ∀ x ∈ l, x ∈ L), w = list.join l ∧ l.length = n := begin rw pow_eq_list_join, refl, end -- Замыкание Клини - все слова, которые можно представить как конкатенацию слов из L (без ограничения на количество) lemma star_eq_list_join : star L = {w | ∃ l (h : ∀ x, x ∈ l → x ∈ L), w = list.join l} := begin sorry, end lemma mem_star_iff_list_join {w : list α} : w ∈ star L ↔ ∃ l (h : ∀ x ∈ l, x ∈ L), w = list.join l := begin rw star_eq_list_join, refl, end -- Еще одно ДЗ из курса формальных языков lemma union_star_eq_star_mul_star_star : star (L + M) = star (star L * star M) := begin sorry, end lemma mul_star_subset_star : L * star L ⊆ star L := begin sorry, end -- Решаем уравнения в языках: если [] ∉ A, то L = A * L + B ↔ L = star A * b lemma linear_eq_iff {A B : set (list α)} (hnil : [] ∉ A) : L = A * L + B ↔ L = star A * B := begin sorry, end end languages
b176c9577c77a1dae35821f86ec82c69f83eb843
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/meta/well_founded_tactics_auto.lean
6cde3423a7b8792f1af5e594849a6a4077cfa12f
[]
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,544
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 -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.meta.default import Mathlib.Lean3Lib.init.data.sigma.lex import Mathlib.Lean3Lib.init.data.nat.lemmas import Mathlib.Lean3Lib.init.data.list.instances import Mathlib.Lean3Lib.init.data.list.qsort universes u v namespace Mathlib /- TODO(Leo): move this lemma, or delete it after we add algebraic normalizer. -/ theorem nat.lt_add_of_zero_lt_left (a : ℕ) (b : ℕ) (h : 0 < b) : a < a + b := (fun (this : a + 0 < a + b) => this) (nat.add_lt_add_left h a) /- TODO(Leo): move this lemma, or delete it after we add algebraic normalizer. -/ theorem nat.zero_lt_one_add (a : ℕ) : 0 < 1 + a := sorry /- TODO(Leo): move this lemma, or delete it after we add algebraic normalizer. -/ theorem nat.lt_add_right (a : ℕ) (b : ℕ) (c : ℕ) : a < b → a < b + c := fun (h : a < b) => lt_of_lt_of_le h (nat.le_add_right b c) /- TODO(Leo): move this lemma, or delete it after we add algebraic normalizer. -/ theorem nat.lt_add_left (a : ℕ) (b : ℕ) (c : ℕ) : a < b → a < c + b := fun (h : a < b) => lt_of_lt_of_le h (nat.le_add_left b c) protected def psum.alt.sizeof {α : Type u} {β : Type v} [SizeOf α] [SizeOf β] : psum α β → ℕ := sorry protected def psum.has_sizeof_alt (α : Type u) (β : Type v) [SizeOf α] [SizeOf β] : SizeOf (psum α β) := { sizeOf := psum.alt.sizeof } end Mathlib
69fc9eec864a462a800588ee31c43246857dc141
8e2026ac8a0660b5a490dfb895599fb445bb77a0
/library/init/category/monad.lean
3065e1df1716dcc0f89616385899391328b21b57
[ "Apache-2.0" ]
permissive
pcmoritz/lean
6a8575115a724af933678d829b4f791a0cb55beb
35eba0107e4cc8a52778259bb5392300267bfc29
refs/heads/master
1,607,896,326,092
1,490,752,175,000
1,490,752,175,000
86,612,290
0
0
null
1,490,809,641,000
1,490,809,641,000
null
UTF-8
Lean
false
false
4,300
lean
/- Copyright (c) Luke Nelson and Jared Roesch. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Luke Nelson, Jared Roesch, Sebastian Ullrich -/ prelude import init.category.applicative universes u v open function class has_bind (m : Type u → Type v) := (bind : Π {α β : Type u}, m α → (α → m β) → m β) @[inline] def bind {m : Type u → Type v} [has_bind m] {α β : Type u} : m α → (α → m β) → m β := has_bind.bind @[inline] def has_bind.and_then {α β : Type u} {m : Type u → Type v} [has_bind m] (x : m α) (y : m β) : m β := do x, y infixl ` >>= `:55 := bind infixl ` >> `:55 := has_bind.and_then section set_option auto_param.check_exists false class monad (m : Type u → Type v) extends applicative m, has_bind m : Type (max u+1 v) := (infixr ` <$> `:100 := map) (infixl ` <*> `:60 := seq) (infixl ` >>= `:55 := bind) (map := λ α β f x, x >>= pure ∘ f) (seq := λ α β f x, f >>= (<$> x)) (bind_pure_comp_eq_map : ∀ {α β : Type u} (f : α → β) (x : m α), x >>= pure ∘ f = f <$> x . control_laws_tac) (bind_map_eq_seq : ∀ {α β : Type u} (f : m (α → β)) (x : m α), f >>= (<$> x) = f <*> x . control_laws_tac) -- monad laws (pure_bind : ∀ {α β : Type u} (x : α) (f : α → m β), pure x >>= f = f x) (bind_assoc : ∀ {α β γ : Type u} (x : m α) (f : α → m β) (g : β → m γ), x >>= f >>= g = x >>= λ x, f x >>= g) -- all applicative laws are derivable from the monad laws + id_map (pure_seq_eq_map := λ α β g x, eq.trans (eq.symm $ bind_map_eq_seq _ _) (pure_bind _ _)) (map_pure := λ α β g x, eq.trans (eq.symm $ bind_pure_comp_eq_map _ _) (pure_bind _ _)) (seq_pure := λ α β g x, calc g <*> pure x = g >>= (<$> pure x) : eq.symm $ bind_map_eq_seq _ _ ... = g >>= λ g : α → β, pure (g x) : congr_arg _ $ funext $ λ g, map_pure _ _ ... = (λ g : α → β, g x) <$> g : bind_pure_comp_eq_map _ _) (seq_assoc := λ α β γ x g h, calc h <*> (g <*> x) = h >>= (<$> g <*> x) : eq.symm $ bind_map_eq_seq _ _ ... = h >>= λ h, pure (@comp α β γ h) >>= (<$> g) >>= (<$> x) : congr_arg _ $ funext $ λ h, (calc h <$> (g <*> x) = g <*> x >>= pure ∘ h : eq.symm $ bind_pure_comp_eq_map _ _ ... = g >>= (<$> x) >>= pure ∘ h : eq.rec rfl $ eq.symm $ bind_map_eq_seq g x ... = g >>= λ g, g <$> x >>= pure ∘ h : bind_assoc _ _ _ ... = g >>= λ g, pure (h ∘ g) >>= (<$> x) : congr_arg _ $ funext $ λ g, (calc g <$> x >>= pure ∘ h = x >>= pure ∘ g >>= pure ∘ h : eq.rec rfl $ eq.symm $ bind_pure_comp_eq_map g x ... = x >>= λ x, pure (g x) >>= pure ∘ h : bind_assoc _ _ _ ... = x >>= λ x, pure (h (g x)) : congr_arg _ $ funext $ λ x, pure_bind _ _ ... = (h ∘ g) <$> x : bind_pure_comp_eq_map _ _ ... = pure (h ∘ g) >>= (<$> x) : eq.symm $ pure_bind _ _) ... = g >>= pure ∘ (@comp α β γ h) >>= (<$> x) : eq.symm $ bind_assoc _ _ _ ... = @comp α β γ h <$> g >>= (<$> x) : eq.rec rfl $ bind_pure_comp_eq_map (comp h) g ... = pure (@comp α β γ h) >>= (<$> g) >>= (<$> x) : eq.rec rfl $ eq.symm $ pure_bind (@comp α β γ h) (<$> g)) ... = h >>= (λ h, pure (@comp α β γ h) >>= (<$> g)) >>= (<$> x) : eq.symm $ bind_assoc _ _ _ ... = h >>= pure ∘ @comp α β γ >>= (<$> g) >>= (<$> x) : eq.rec rfl $ eq.symm $ bind_assoc h (pure ∘ @comp α β γ) (<$> g) ... = (@comp α β γ <$> h) >>= (<$> g) >>= (<$> x) : eq.rec rfl $ bind_pure_comp_eq_map (@comp α β γ) h ... = ((@comp α β γ <$> h) >>= (<$> g)) <*> x : bind_map_eq_seq _ _ ... = (@comp α β γ <$> h) <*> g <*> x : eq.rec rfl $ bind_map_eq_seq (@comp α β γ <$> h) g) end @[reducible] def return {m : Type u → Type v} [monad m] {α : Type u} : α → m α := pure /- Identical to has_bind.and_then, but it is not inlined. -/ def has_bind.seq {α β : Type u} {m : Type u → Type v} [has_bind m] (x : m α) (y : m β) : m β := do x, y -- monad "law" derivable from other laws theorem monad.bind_pure {α β : Type u} {m : Type u → Type v} [monad m] (x : m α) : x >>= pure = x := eq.trans (monad.bind_pure_comp_eq_map _ _ _) (functor.id_map _)
7e8b03953b38557219c68f530b0f2bab9d4458ca
07c76fbd96ea1786cc6392fa834be62643cea420
/hott/algebra/group.hlean
2c21669e8863d32c23ae7df63496e605e68f02a8
[ "Apache-2.0" ]
permissive
fpvandoorn/lean2
5a430a153b570bf70dc8526d06f18fc000a60ad9
0889cf65b7b3cebfb8831b8731d89c2453dd1e9f
refs/heads/master
1,592,036,508,364
1,545,093,958,000
1,545,093,958,000
75,436,854
0
0
null
1,480,718,780,000
1,480,718,780,000
null
UTF-8
Lean
false
false
7,511
hlean
/- 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, Floris van Doorn Various multiplicative and additive structures. Partially modeled on Isabelle's library. -/ import algebra.inf_group open eq eq.ops -- note: ⁻¹ will be overloaded open binary algebra is_trunc set_option class.force_new true variable {A : Type} /- semigroup -/ namespace algebra structure is_set_structure [class] (A : Type) := (is_set_carrier : is_set A) attribute is_set_structure.is_set_carrier [instance] [priority 950] structure semigroup [class] (A : Type) extends is_set_structure A, inf_semigroup A structure comm_semigroup [class] (A : Type) extends semigroup A, comm_inf_semigroup A structure left_cancel_semigroup [class] (A : Type) extends semigroup A, left_cancel_inf_semigroup A structure right_cancel_semigroup [class] (A : Type) extends semigroup A, right_cancel_inf_semigroup A /- additive semigroup -/ definition add_semigroup [class] : Type → Type := semigroup definition add_semigroup.is_set_carrier [instance] [priority 900] (A : Type) [H : add_semigroup A] : is_set A := @is_set_structure.is_set_carrier A (@semigroup.to_is_set_structure A H) definition add_inf_semigroup_of_add_semigroup [reducible] [trans_instance] (A : Type) [H : add_semigroup A] : add_inf_semigroup A := @semigroup.to_inf_semigroup A H definition add_comm_semigroup [class] : Type → Type := comm_semigroup definition add_semigroup_of_add_comm_semigroup [reducible] [trans_instance] (A : Type) [H : add_comm_semigroup A] : add_semigroup A := @comm_semigroup.to_semigroup A H definition add_comm_inf_semigroup_of_add_comm_semigroup [reducible] [trans_instance] (A : Type) [H : add_comm_semigroup A] : add_comm_inf_semigroup A := @comm_semigroup.to_comm_inf_semigroup A H definition add_left_cancel_semigroup [class] : Type → Type := left_cancel_semigroup definition add_semigroup_of_add_left_cancel_semigroup [reducible] [trans_instance] (A : Type) [H : add_left_cancel_semigroup A] : add_semigroup A := @left_cancel_semigroup.to_semigroup A H definition add_left_cancel_inf_semigroup_of_add_left_cancel_semigroup [reducible] [trans_instance] (A : Type) [H : add_left_cancel_semigroup A] : add_left_cancel_inf_semigroup A := @left_cancel_semigroup.to_left_cancel_inf_semigroup A H definition add_right_cancel_semigroup [class] : Type → Type := right_cancel_semigroup definition add_semigroup_of_add_right_cancel_semigroup [reducible] [trans_instance] (A : Type) [H : add_right_cancel_semigroup A] : add_semigroup A := @right_cancel_semigroup.to_semigroup A H definition add_right_cancel_inf_semigroup_of_add_right_cancel_semigroup [reducible] [trans_instance] (A : Type) [H : add_right_cancel_semigroup A] : add_right_cancel_inf_semigroup A := @right_cancel_semigroup.to_right_cancel_inf_semigroup A H /- monoid -/ structure monoid [class] (A : Type) extends semigroup A, inf_monoid A structure comm_monoid [class] (A : Type) extends monoid A, comm_semigroup A, comm_inf_monoid A /- additive monoid -/ definition add_monoid [class] : Type → Type := monoid definition add_semigroup_of_add_monoid [reducible] [trans_instance] (A : Type) [H : add_monoid A] : add_semigroup A := @monoid.to_semigroup A H definition add_inf_monoid_of_add_monoid [reducible] [trans_instance] (A : Type) [H : add_monoid A] : add_inf_monoid A := @monoid.to_inf_monoid A H definition add_comm_monoid [class] : Type → Type := comm_monoid definition add_monoid_of_add_comm_monoid [reducible] [trans_instance] (A : Type) [H : add_comm_monoid A] : add_monoid A := @comm_monoid.to_monoid A H definition add_comm_semigroup_of_add_comm_monoid [reducible] [trans_instance] (A : Type) [H : add_comm_monoid A] : add_comm_semigroup A := @comm_monoid.to_comm_semigroup A H definition add_comm_inf_monoid_of_add_comm_monoid [reducible] [trans_instance] (A : Type) [H : add_comm_monoid A] : add_comm_inf_monoid A := @comm_monoid.to_comm_inf_monoid A H definition add_monoid.to_monoid {A : Type} [s : add_monoid A] : monoid A := s definition add_comm_monoid.to_comm_monoid {A : Type} [s : add_comm_monoid A] : comm_monoid A := s definition monoid.to_add_monoid {A : Type} [s : monoid A] : add_monoid A := s definition comm_monoid.to_add_comm_monoid {A : Type} [s : comm_monoid A] : add_comm_monoid A := s /- group -/ structure group [class] (A : Type) extends monoid A, inf_group A definition group_of_inf_group (A : Type) [s : inf_group A] [is_set A] : group A := ⦃group, s, is_set_carrier := _⦄ section group variable [s : group A] include s definition group.to_left_cancel_semigroup [trans_instance] : left_cancel_semigroup A := ⦃ left_cancel_semigroup, s, mul_left_cancel := @mul_left_cancel A _ ⦄ definition group.to_right_cancel_semigroup [trans_instance] : right_cancel_semigroup A := ⦃ right_cancel_semigroup, s, mul_right_cancel := @mul_right_cancel A _ ⦄ end group structure ab_group [class] (A : Type) extends group A, comm_monoid A, ab_inf_group A definition ab_group_of_ab_inf_group (A : Type) [s : ab_inf_group A] [is_set A] : ab_group A := ⦃ab_group, s, is_set_carrier := _⦄ /- additive group -/ definition add_group [class] : Type → Type := group definition add_semigroup_of_add_group [reducible] [trans_instance] (A : Type) [H : add_group A] : add_monoid A := @group.to_monoid A H definition add_inf_group_of_add_group [reducible] [trans_instance] (A : Type) [H : add_group A] : add_inf_group A := @group.to_inf_group A H definition add_group.to_group {A : Type} [s : add_group A] : group A := s definition group.to_add_group {A : Type} [s : group A] : add_group A := s definition add_group_of_add_inf_group (A : Type) [s : add_inf_group A] [is_set A] : add_group A := ⦃group, s, is_set_carrier := _⦄ section add_group variables [s : add_group A] include s definition add_group.to_add_left_cancel_semigroup [reducible] [trans_instance] : add_left_cancel_semigroup A := @group.to_left_cancel_semigroup A s definition add_group.to_add_right_cancel_semigroup [reducible] [trans_instance] : add_right_cancel_semigroup A := @group.to_right_cancel_semigroup A s end add_group definition add_ab_group [class] : Type → Type := ab_group definition add_group_of_add_ab_group [reducible] [trans_instance] (A : Type) [H : add_ab_group A] : add_group A := @ab_group.to_group A H definition add_comm_monoid_of_add_ab_group [reducible] [trans_instance] (A : Type) [H : add_ab_group A] : add_comm_monoid A := @ab_group.to_comm_monoid A H definition add_ab_inf_group_of_add_ab_group [reducible] [trans_instance] (A : Type) [H : add_ab_group A] : add_ab_inf_group A := @ab_group.to_ab_inf_group A H definition add_ab_group.to_ab_group {A : Type} [s : add_ab_group A] : ab_group A := s definition ab_group.to_add_ab_group {A : Type} [s : ab_group A] : add_ab_group A := s definition add_ab_group_of_add_ab_inf_group (A : Type) [s : add_ab_inf_group A] [is_set A] : add_ab_group A := ⦃ab_group, s, is_set_carrier := _⦄ definition group_of_add_group (A : Type) [G : add_group A] : group A := ⦃group, mul := has_add.add, mul_assoc := add.assoc, one := !has_zero.zero, one_mul := zero_add, mul_one := add_zero, inv := has_neg.neg, mul_left_inv := add.left_inv, is_set_carrier := _⦄ end algebra open algebra
3b13fefbe6af7ab22ee1738d667d75776179d71f
798dd332c1ad790518589a09bc82459fb12e5156
/data/set/finite.lean
0b0f0961f4323f9a9113a20170e65937c9931683
[ "Apache-2.0" ]
permissive
tobiasgrosser/mathlib
b040b7eb42d5942206149371cf92c61404de3c31
120635628368ec261e031cefc6d30e0304088b03
refs/heads/master
1,644,803,442,937
1,536,663,752,000
1,536,663,907,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,997
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 Finite sets. -/ import data.set.lattice data.nat.basic logic.function data.fintype open set lattice function universes u v w variables {α : Type u} {β : Type v} {ι : Sort w} namespace set /-- A set is finite if the subtype is a fintype, i.e. there is a list that enumerates its members. -/ def finite (s : set α) : Prop := nonempty (fintype s) /-- A set is infinite if it is not finite. -/ def infinite (s : set α) : Prop := ¬ finite s /-- Construct a fintype from a finset with the same elements. -/ def fintype_of_finset {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) : fintype p := fintype.subtype s H @[simp] theorem card_fintype_of_finset {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) : @fintype.card p (fintype_of_finset s H) = s.card := fintype.subtype_card s H theorem card_fintype_of_finset' {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) [fintype p] : fintype.card p = s.card := by rw ← card_fintype_of_finset s H; congr /-- Construct a finset enumerating a set `s`, given a `fintype` instance. -/ def to_finset (s : set α) [fintype s] : finset α := ⟨(@finset.univ s _).1.map subtype.val, multiset.nodup_map (λ a b, subtype.eq) finset.univ.2⟩ @[simp] theorem mem_to_finset {s : set α} [fintype s] {a : α} : a ∈ s.to_finset ↔ a ∈ s := by simp [to_finset] @[simp] theorem mem_to_finset_val {s : set α} [fintype s] {a : α} : a ∈ s.to_finset.1 ↔ a ∈ s := mem_to_finset noncomputable instance finite.fintype {s : set α} (h : finite s) : fintype s := classical.choice h /-- Get a finset from a finite set -/ noncomputable def finite.to_finset {s : set α} (h : finite s) : finset α := @set.to_finset _ _ (finite.fintype h) @[simp] theorem finite.mem_to_finset {s : set α} {h : finite s} {a : α} : a ∈ h.to_finset ↔ a ∈ s := @mem_to_finset _ _ (finite.fintype h) _ theorem finite.exists_finset {s : set α} : finite s → ∃ s' : finset α, ∀ a : α, a ∈ s' ↔ a ∈ s | ⟨h⟩ := by exactI ⟨to_finset s, λ _, mem_to_finset⟩ theorem finite.exists_finset_coe {s : set α} (hs : finite s) : ∃ s' : finset α, ↑s' = s := let ⟨s', h⟩ := hs.exists_finset in ⟨s', set.ext h⟩ theorem finite_mem_finset (s : finset α) : finite {a | a ∈ s} := ⟨fintype_of_finset s (λ _, iff.rfl)⟩ instance decidable_mem_of_fintype [decidable_eq α] (s : set α) [fintype s] (a) : decidable (a ∈ s) := decidable_of_iff _ mem_to_finset instance fintype_empty : fintype (∅ : set α) := fintype_of_finset ∅ $ by simp theorem empty_card : fintype.card (∅ : set α) = 0 := rfl @[simp] theorem empty_card' {h : fintype.{u} (∅ : set α)} : @fintype.card (∅ : set α) h = 0 := eq.trans (by congr) empty_card @[simp] theorem finite_empty : @finite α ∅ := ⟨set.fintype_empty⟩ def fintype_insert' {a : α} (s : set α) [fintype s] (h : a ∉ s) : fintype (insert a s : set α) := fintype_of_finset ⟨a :: s.to_finset.1, multiset.nodup_cons_of_nodup (by simp [h]) s.to_finset.2⟩ $ by simp theorem card_fintype_insert' {a : α} (s : set α) [fintype s] (h : a ∉ s) : @fintype.card _ (fintype_insert' s h) = fintype.card s + 1 := by rw [fintype_insert', card_fintype_of_finset]; simp [finset.card, to_finset]; refl @[simp] theorem card_insert {a : α} (s : set α) [fintype s] (h : a ∉ s) {d : fintype.{u} (insert a s : set α)} : @fintype.card _ d = fintype.card s + 1 := by rw ← card_fintype_insert' s h; congr lemma card_image_of_inj_on {s : set α} [fintype s] {f : α → β} [fintype (f '' s)] (H : ∀x∈s, ∀y∈s, f x = f y → x = y) : fintype.card (f '' s) = fintype.card s := by haveI := classical.prop_decidable; exact calc fintype.card (f '' s) = (s.to_finset.image f).card : card_fintype_of_finset' _ (by simp) ... = s.to_finset.card : finset.card_image_of_inj_on (λ x hx y hy hxy, H x (mem_to_finset.1 hx) y (mem_to_finset.1 hy) hxy) ... = fintype.card s : (card_fintype_of_finset' _ (λ a, mem_to_finset)).symm lemma card_image_of_injective (s : set α) [fintype s] {f : α → β} [fintype (f '' s)] (H : function.injective f) : fintype.card (f '' s) = fintype.card s := card_image_of_inj_on $ λ _ _ _ _ h, H h instance fintype_insert [decidable_eq α] (a : α) (s : set α) [fintype s] : fintype (insert a s : set α) := if h : a ∈ s then by rwa [insert_eq, union_eq_self_of_subset_left (singleton_subset_iff.2 h)] else fintype_insert' _ h @[simp] theorem finite_insert (a : α) {s : set α} : finite s → finite (insert a s) | ⟨h⟩ := ⟨@set.fintype_insert _ (classical.dec_eq α) _ _ h⟩ lemma to_finset_insert [decidable_eq α] {a : α} {s : set α} (hs : finite s) : (finite_insert a hs).to_finset = insert a hs.to_finset := finset.ext.mpr $ by simp @[elab_as_eliminator] theorem finite.induction_on {C : set α → Prop} {s : set α} (h : finite s) (H0 : C ∅) (H1 : ∀ {a s}, a ∉ s → finite s → C s → C (insert a s)) : C s := let ⟨t⟩ := h in by exactI match s.to_finset, @mem_to_finset _ s _ with | ⟨l, nd⟩, al := begin change ∀ a, a ∈ l ↔ a ∈ s at al, clear _let_match _match t h, revert s nd al, refine multiset.induction_on l _ (λ a l IH, _); intros s nd al, { rw show s = ∅, from eq_empty_iff_forall_not_mem.2 (by simpa using al), exact H0 }, { rw ← show insert a {x | x ∈ l} = s, from set.ext (by simpa using al), cases multiset.nodup_cons.1 nd with m nd', refine H1 _ ⟨finset.subtype.fintype ⟨l, nd'⟩⟩ (IH nd' (λ _, iff.rfl)), exact m } end end @[elab_as_eliminator] theorem finite.dinduction_on {C : ∀s:set α, finite s → Prop} {s : set α} (h : finite s) (H0 : C ∅ finite_empty) (H1 : ∀ {a s}, a ∉ s → ∀h:finite s, C s h → C (insert a s) (finite_insert a h)) : C s h := have ∀h:finite s, C s h, from finite.induction_on h (assume h, H0) (assume a s has hs ih h, H1 has hs (ih _)), this h instance fintype_singleton (a : α) : fintype ({a} : set α) := fintype_insert' _ (not_mem_empty _) @[simp] theorem card_singleton (a : α) : fintype.card ({a} : set α) = 1 := by rw [show fintype.card ({a} : set α) = _, from card_fintype_insert' ∅ (not_mem_empty a)]; refl @[simp] theorem finite_singleton (a : α) : finite ({a} : set α) := ⟨set.fintype_singleton _⟩ instance fintype_union [decidable_eq α] (s t : set α) [fintype s] [fintype t] : fintype (s ∪ t : set α) := fintype_of_finset (s.to_finset ∪ t.to_finset) $ by simp theorem finite_union {s t : set α} : finite s → finite t → finite (s ∪ t) | ⟨hs⟩ ⟨ht⟩ := ⟨@set.fintype_union _ (classical.dec_eq α) _ _ hs ht⟩ instance fintype_sep (s : set α) (p : α → Prop) [fintype s] [decidable_pred p] : fintype ({a ∈ s | p a} : set α) := fintype_of_finset (s.to_finset.filter p) $ by simp instance fintype_inter (s t : set α) [fintype s] [decidable_pred t] : fintype (s ∩ t : set α) := set.fintype_sep s t def fintype_subset (s : set α) {t : set α} [fintype s] [decidable_pred t] (h : t ⊆ s) : fintype t := by rw ← inter_eq_self_of_subset_right h; apply_instance theorem finite_subset {s : set α} : finite s → ∀ {t : set α}, t ⊆ s → finite t | ⟨hs⟩ t h := ⟨@set.fintype_subset _ _ _ hs (classical.dec_pred t) h⟩ instance fintype_image [decidable_eq β] (s : set α) (f : α → β) [fintype s] : fintype (f '' s) := fintype_of_finset (s.to_finset.image f) $ by simp instance fintype_range [decidable_eq β] (f : α → β) [fintype α] : fintype (range f) := fintype_of_finset (finset.univ.image f) $ by simp [range] theorem finite_image {s : set α} (f : α → β) : finite s → finite (f '' s) | ⟨h⟩ := ⟨@set.fintype_image _ _ (classical.dec_eq β) _ _ h⟩ def fintype_of_fintype_image [decidable_eq β] (s : set α) {f : α → β} {g} (I : is_partial_inv f g) [fintype (f '' s)] : fintype s := fintype_of_finset ⟨_, @multiset.nodup_filter_map β α g _ (@injective_of_partial_inv_right _ _ f g I) (f '' s).to_finset.2⟩ $ λ a, begin suffices : (∃ b x, f x = b ∧ g b = some a ∧ x ∈ s) ↔ a ∈ s, by simpa [exists_and_distrib_left.symm, and.comm, and.left_comm, and.assoc], rw exists_swap, suffices : (∃ x, x ∈ s ∧ g (f x) = some a) ↔ a ∈ s, {simpa [and.comm, and.left_comm, and.assoc]}, simp [I _, (injective_of_partial_inv I).eq_iff] end theorem finite_of_finite_image {s : set α} {f : α → β} (I : injective f) : finite (f '' s) → finite s | ⟨hs⟩ := by haveI := classical.dec_eq β; exact ⟨fintype_of_fintype_image _ (partial_inv_of_injective I)⟩ theorem finite_preimage {s : set β} {f : α → β} (I : injective f) (h : finite s) : finite (f ⁻¹' s) := finite_of_finite_image I (finite_subset h (image_preimage_subset f s)) instance fintype_Union [decidable_eq α] {ι : Type*} [fintype ι] (f : ι → set α) [∀ i, fintype (f i)] : fintype (⋃ i, f i) := fintype_of_finset (finset.univ.bind (λ i, (f i).to_finset)) $ by simp theorem finite_Union {ι : Type*} [fintype ι] {f : ι → set α} (H : ∀i, finite (f i)) : finite (⋃ i, f i) := ⟨@set.fintype_Union _ (classical.dec_eq α) _ _ _ (λ i, finite.fintype (H i))⟩ theorem finite_sUnion {s : set (set α)} (h : finite s) (H : ∀t∈s, finite t) : finite (⋃₀ s) := by rw sUnion_eq_Union; haveI := finite.fintype h; apply finite_Union; simpa using H instance fintype_lt_nat (n : ℕ) : fintype {i | i < n} := fintype_of_finset (finset.range n) $ by simp instance fintype_le_nat (n : ℕ) : fintype {i | i ≤ n} := by simpa [nat.lt_succ_iff] using set.fintype_lt_nat (n+1) lemma finite_le_nat (n : ℕ) : finite {i | i ≤ n} := ⟨set.fintype_le_nat _⟩ instance fintype_prod (s : set α) (t : set β) [fintype s] [fintype t] : fintype (set.prod s t) := fintype_of_finset (s.to_finset.product t.to_finset) $ by simp lemma finite_prod {s : set α} {t : set β} : finite s → finite t → finite (set.prod s t) | ⟨hs⟩ ⟨ht⟩ := by exactI ⟨set.fintype_prod s t⟩ end set namespace finset variables [decidable_eq β] variables {s t u : finset α} {f : α → β} {a : α} lemma finite_to_set (s : finset α) : set.finite (↑s : set α) := set.finite_mem_finset s @[simp] lemma coe_bind {f : α → finset β} : ↑(s.bind f) = (⋃x ∈ (↑s : set α), ↑(f x) : set β) := by simp [set.ext_iff] @[simp] lemma coe_to_finset {s : set α} {hs : set.finite s} : ↑(hs.to_finset) = s := by simp [set.ext_iff] @[simp] lemma coe_to_finset' [decidable_eq α] (s : set α) [fintype s] : (↑s.to_finset : set α) = s := by ext; simp end finset namespace set lemma infinite_univ_nat : infinite (univ : set ℕ) := assume (h : finite (univ : set ℕ)), let ⟨n, hn⟩ := finset.exists_nat_subset_range h.to_finset in have n ∈ finset.range n, from finset.subset_iff.mpr hn $ by simp, by simp * at * lemma not_injective_nat_fintype [fintype α] [decidable_eq α] {f : ℕ → α} : ¬ injective f := assume (h : injective f), have finite (f '' univ), from finite_subset (finset.finite_to_set $ fintype.elems α) (assume a h, fintype.complete a), have finite (univ : set ℕ), from finite_of_finite_image h this, infinite_univ_nat this lemma not_injective_int_fintype [fintype α] [decidable_eq α] {f : ℤ → α} : ¬ injective f := assume hf, have injective (f ∘ (coe : ℕ → ℤ)), from injective_comp hf $ assume i j, int.of_nat_inj, not_injective_nat_fintype this lemma card_lt_card {s t : set α} [fintype s] [fintype t] (h : s ⊂ t) : fintype.card s < fintype.card t := begin haveI := classical.prop_decidable, rw [← finset.coe_to_finset' s, ← finset.coe_to_finset' t, finset.coe_ssubset] at h, rw [card_fintype_of_finset' _ (λ x, mem_to_finset), card_fintype_of_finset' _ (λ x, mem_to_finset)], exact finset.card_lt_card h, end end set
5cd19b202f649b54e07504bc077951ca3067470d
1fbca480c1574e809ae95a3eda58188ff42a5e41
/src/util/function.lean
6916d8fa20c80f1f7c136c17492e4ca40d0cb4d6
[]
no_license
unitb/lean-lib
560eea0acf02b1fd4bcaac9986d3d7f1a4290e7e
439b80e606b4ebe4909a08b1d77f4f5c0ee3dee9
refs/heads/master
1,610,706,025,400
1,570,144,245,000
1,570,144,245,000
99,579,229
5
0
null
null
null
null
UTF-8
Lean
false
false
797
lean
import util.classical universes u v namespace function variables {α : Type u} {β : Type v} variables [nonempty α] variables (f : α → β) noncomputable def inv (y : β) : α := ε x, f x = y variable {f} lemma inv_is_left_inverse_of_injective (H : injective f) : left_inverse (inv f) f := begin simp [left_inverse,inv], intro, apply_epsilon_spec, end lemma inv_eq (x : α) (y : β) (H : injective f) (h : y = f x) : inv f y = x := by rw [h,inv_is_left_inverse_of_injective H] lemma injective_of_left_inverse_inv (h : left_inverse (inv f) f) : injective f := injective_of_left_inverse h lemma inv_is_right_inverse_of_surjective (H : surjective f) : right_inverse (inv f) f := begin simp [right_inverse,left_inverse,inv], intro, apply_epsilon_spec, end end function
48e4b8ac5c98916c6cb5cd6c19b7457113900b27
4b846d8dabdc64e7ea03552bad8f7fa74763fc67
/library/init/data/list/basic.lean
8f01340f502d65a2f5ded8adc5b64e882d8c8460
[ "Apache-2.0" ]
permissive
pacchiano/lean
9324b33f3ac3b5c5647285160f9f6ea8d0d767dc
fdadada3a970377a6df8afcd629a6f2eab6e84e8
refs/heads/master
1,611,357,380,399
1,489,870,101,000
1,489,870,101,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,943
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import init.logic init.data.nat.basic init.category.monad open decidable list universes u v w instance (α : Type u) : inhabited (list α) := ⟨list.nil⟩ variables {α : Type u} {β : Type v} {γ : Type w} namespace list protected def append : list α → list α → list α | [] l := l | (h :: s) t := h :: (append s t) instance : has_append (list α) := ⟨list.append⟩ protected def mem : α → list α → Prop | a [] := false | a (b :: l) := a = b ∨ mem a l instance : has_mem α (list α) := ⟨list.mem⟩ instance decidable_mem [decidable_eq α] (a : α) : ∀ (l : list α), decidable (a ∈ l) | [] := is_false not_false | (b::l) := if h₁ : a = b then is_true (or.inl h₁) else match decidable_mem l with | is_true h₂ := is_true (or.inr h₂) | is_false h₂ := is_false (not_or h₁ h₂) end def concat : list α → α → list α | [] a := [a] | (b::l) a := b :: concat l a instance : has_emptyc (list α) := ⟨list.nil⟩ protected def insert [decidable_eq α] (a : α) (l : list α) : list α := if a ∈ l then l else concat l a instance [decidable_eq α] : has_insert α (list α) := ⟨list.insert⟩ protected def union [decidable_eq α] : list α → list α → list α | l₁ [] := l₁ | l₁ (a::l₂) := union (insert a l₁) l₂ instance [decidable_eq α] : has_union (list α) := ⟨list.union⟩ protected def inter [decidable_eq α] : list α → list α → list α | [] l₂ := [] | (a::l₁) l₂ := if a ∈ l₂ then a :: inter l₁ l₂ else inter l₁ l₂ instance [decidable_eq α] : has_inter (list α) := ⟨list.inter⟩ def length : list α → nat | [] := 0 | (a :: l) := length l + 1 def empty : list α → bool | [] := tt | (_ :: _) := ff open option nat def nth : list α → nat → option α | [] n := none | (a :: l) 0 := some a | (a :: l) (n+1) := nth l n def update_nth : list α → ℕ → α → list α | (x::xs) 0 a := a :: xs | (x::xs) (i+1) a := x :: update_nth xs i a | [] _ _ := [] def remove_nth : list α → ℕ → list α | [] _ := [] | (x::xs) 0 := xs | (x::xs) (i+1) := x :: remove_nth xs i def remove_all [decidable_eq α] : list α → list α → list α | (x :: xs) ys := (if x ∈ ys then remove_all xs ys else x :: remove_all xs ys) | [] ys := [] def head [inhabited α] : list α → α | [] := default α | (a :: l) := a def tail : list α → list α | [] := [] | (a :: l) := l def reverse_core : list α → list α → list α | [] r := r | (a::l) r := reverse_core l (a::r) def reverse : list α → list α := λ l, reverse_core l [] def map (f : α → β) : list α → list β | [] := [] | (a :: l) := f a :: map l def for : list α → (α → β) → list β := flip map def map₂ (f : α → β → γ) : list α → list β → list γ | [] _ := [] | _ [] := [] | (x::xs) (y::ys) := f x y :: map₂ xs ys def join : list (list α) → list α | [] := [] | (l :: ls) := append l (join ls) def filter (p : α → Prop) [decidable_pred p] : list α → list α | [] := [] | (a::l) := if p a then a :: filter l else filter l def find [decidable_eq α] : α → list α → nat | a [] := 0 | a (b :: l) := if a = b then 0 else succ (find a l) def dropn : ℕ → list α → list α | 0 a := a | (succ n) [] := [] | (succ n) (x::r) := dropn n r def taken : ℕ → list α → list α | 0 a := [] | (succ n) [] := [] | (succ n) (x :: r) := x :: taken n r def foldl (f : α → β → α) : α → list β → α | a [] := a | a (b :: l) := foldl (f a b) l def foldr (f : α → β → β) : β → list α → β | b [] := b | b (a :: l) := f a (foldr b l) def any (l : list α) (p : α → bool) : bool := foldr (λ a r, p a || r) ff l def all (l : list α) (p : α → bool) : bool := foldr (λ a r, p a && r) tt l def bor (l : list bool) : bool := any l id def band (l : list bool) : bool := all l id def zip_with (f : α → β → γ) : list α → list β → list γ | (x::xs) (y::ys) := f x y :: zip_with xs ys | _ _ := [] def zip : list α → list β → list (prod α β) := zip_with prod.mk def unzip : list (α × β) → list α × list β | [] := ([], []) | ((a, b) :: t) := match unzip t with (al, bl) := (a::al, b::bl) end def repeat (a : α) : ℕ → list α | 0 := [] | (succ n) := a :: repeat n def range_core : ℕ → list ℕ → list ℕ | 0 l := l | (succ n) l := range_core n (n :: l) def range (n : ℕ) : list ℕ := range_core n [] def iota_core : ℕ → list ℕ → list ℕ | 0 l := reverse l | (succ n) l := iota_core n (succ n :: l) def iota : ℕ → list ℕ := λ n, iota_core n [] def enum_from : ℕ → list α → list (ℕ × α) | n [] := nil | n (x :: xs) := (n, x) :: enum_from (n + 1) xs def enum : list α → list (ℕ × α) := enum_from 0 def sum [has_add α] [has_zero α] : list α → α := foldl add zero def last : Π l : list α, l ≠ [] → α | [] h := absurd rfl h | [a] h := a | (a::b::l) h := last (b::l) (λ h, list.no_confusion h) def ilast [inhabited α] : list α → α | [] := arbitrary α | [a] := a | [a, b] := b | (a::b::l) := ilast l def intersperse (sep : α) : list α → list α | [] := [] | [x] := [x] | (x::xs) := x::sep::intersperse xs def intercalate (sep : list α) (xs : list (list α)) : list α := join (intersperse sep xs) @[inline] def bind {α : Type u} {β : Type v} (a : list α) (b : α → list β) : list β := join (map b a) @[inline] def ret {α : Type u} (a : α) : list α := [a] end list instance : monad list := {map := @list.map, pure := @list.ret, bind := @list.bind}
c710304dfbd37691738adf9f5d521f9e0fbb0895
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/group_theory/perm/cycle_type.lean
937023ffb9d9a83db729238758c0d72459c36426
[ "Apache-2.0" ]
permissive
JLimperg/aesop3
306cc6570c556568897ed2e508c8869667252e8a
a4a116f650cc7403428e72bd2e2c4cda300fe03f
refs/heads/master
1,682,884,916,368
1,620,320,033,000
1,620,320,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
18,374
lean
/- Copyright (c) 2020 Thomas Browning. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning -/ import combinatorics.partition import data.multiset.gcd import tactic.linarith import group_theory.perm.cycles import group_theory.sylow /-! # Cycle Types In this file we define the cycle type of a partition. ## Main definitions - `σ.cycle_type` where `σ` is a permutation of a `fintype` - `σ.partition` where `σ` is a permutation of a `fintype` ## Main results - `sum_cycle_type` : The sum of `σ.cycle_type` equals `σ.support.card` - `lcm_cycle_type` : The lcm of `σ.cycle_type` equals `order_of σ` - `is_conj_iff_cycle_type_eq` : Two permutations are conjugate if and only if they have the same cycle type. -/ namespace equiv.perm open equiv list multiset variables {α : Type*} [fintype α] section cycle_type lemma mem_list_cycles_iff {l : list (perm α)} (h1 : ∀ σ : perm α, σ ∈ l → σ.is_cycle) (h2 : l.pairwise disjoint) {σ : perm α} (h3 : σ.is_cycle) {a : α} (h4 : σ a ≠ a) : σ ∈ l ↔ ∀ k : ℕ, (σ ^ k) a = (l.prod ^ k) a := begin induction l with τ l ih, { exact ⟨false.elim, λ h, h4 (h 1)⟩ }, { rw [mem_cons_iff, list.prod_cons, ih (λ σ hσ, h1 σ (list.mem_cons_of_mem τ hσ)) (pairwise_of_pairwise_cons h2)], have key := disjoint_prod_list_of_disjoint (pairwise_cons.mp h2).1, cases key a, { simp_rw [key.mul_comm, commute.mul_pow key.mul_comm.symm, mul_apply, pow_apply_eq_self_of_apply_eq_self h, or_iff_right_iff_imp], rintro rfl, exact (h4 h).elim }, { simp_rw [commute.mul_pow key.mul_comm, mul_apply, pow_apply_eq_self_of_apply_eq_self h], rw [or_iff_left_of_imp (λ h : (∀ k : ℕ, (σ ^ k) a = a), (h4 (h 1)).elim)], split, { exact λ h k, by rw h }, { intro h5, have hτa : τ a ≠ a := ne_of_eq_of_ne (h5 1).symm h4, ext b, by_cases hσb : σ b = b, { by_cases hτb : τ b = b, { rw [hσb, hτb] }, { obtain ⟨n, rfl⟩ := ((h1 τ (list.mem_cons_self τ l))).exists_pow_eq hτa hτb, rw [←mul_apply τ, ←pow_succ, ←h5, ←h5, pow_succ, mul_apply] } }, { obtain ⟨n, rfl⟩ := h3.exists_pow_eq h4 hσb, rw [←mul_apply, ←pow_succ, h5, h5, pow_succ, mul_apply] } } } }, end lemma list_cycles_perm_list_cycles {l₁ l₂ : list (perm α)} (h₀ : l₁.prod = l₂.prod) (h₁l₁ : ∀ σ : perm α, σ ∈ l₁ → σ.is_cycle) (h₁l₂ : ∀ σ : perm α, σ ∈ l₂ → σ.is_cycle) (h₂l₁ : l₁.pairwise disjoint) (h₂l₂ : l₂.pairwise disjoint) : l₁ ~ l₂ := begin classical, have h₃l₁ : (1 : perm α) ∉ l₁ := λ h, (h₁l₁ 1 h).ne_one rfl, have h₃l₂ : (1 : perm α) ∉ l₂ := λ h, (h₁l₂ 1 h).ne_one rfl, refine (perm_ext (nodup_of_pairwise_disjoint h₃l₁ h₂l₁) (nodup_of_pairwise_disjoint h₃l₂ h₂l₂)).mpr (λ σ, _), by_cases hσ : σ.is_cycle, { obtain ⟨a, ha⟩ := not_forall.mp (mt ext hσ.ne_one), rw [mem_list_cycles_iff h₁l₁ h₂l₁ hσ ha, mem_list_cycles_iff h₁l₂ h₂l₂ hσ ha, h₀] }, { exact iff_of_false (mt (h₁l₁ σ) hσ) (mt (h₁l₂ σ) hσ) }, end variables [decidable_eq α] /-- The cycle type of a permutation -/ def cycle_type (σ : perm α) : multiset ℕ := σ.trunc_cycle_factors.lift (λ l, l.1.map (finset.card ∘ support)) (λ ⟨l₁, h₁l₁, h₂l₁, h₃l₁⟩ ⟨l₂, h₁l₂, h₂l₂, h₃l₂⟩, coe_eq_coe.mpr (perm.map _ (list_cycles_perm_list_cycles (h₁l₁.trans h₁l₂.symm) h₂l₁ h₂l₂ h₃l₁ h₃l₂))) lemma two_le_of_mem_cycle_type {σ : perm α} {n : ℕ} (h : n ∈ σ.cycle_type) : 2 ≤ n := begin rw [cycle_type, ←σ.trunc_cycle_factors.out_eq] at h, obtain ⟨τ, hτ, rfl⟩ := list.mem_map.mp h, exact (σ.trunc_cycle_factors.out.2.2.1 τ hτ).two_le_card_support, end lemma one_lt_of_mem_cycle_type {σ : perm α} {n : ℕ} (h : n ∈ σ.cycle_type) : 1 < n := two_le_of_mem_cycle_type h lemma cycle_type_eq {σ : perm α} (l : list (perm α)) (h0 : l.prod = σ) (h1 : ∀ σ : perm α, σ ∈ l → σ.is_cycle) (h2 : l.pairwise disjoint) : σ.cycle_type = l.map (finset.card ∘ support) := by rw [cycle_type, trunc.eq σ.trunc_cycle_factors (trunc.mk ⟨l, h0, h1, h2⟩), trunc.lift_mk] lemma cycle_type_one : (1 : perm α).cycle_type = 0 := cycle_type_eq [] rfl (λ _, false.elim) pairwise.nil lemma cycle_type_eq_zero {σ : perm α} : σ.cycle_type = 0 ↔ σ = 1 := begin split, { intro h, obtain ⟨l, h₁l, h₂l, h₃l⟩ := σ.trunc_cycle_factors.out, rw [cycle_type_eq l h₁l h₂l h₃l, coe_eq_zero, map_eq_nil] at h, exact h₁l.symm.trans (congr_arg _ h) }, { exact λ h, by rw [h, cycle_type_one] }, end lemma card_cycle_type_eq_zero {σ : perm α} : σ.cycle_type.card = 0 ↔ σ = 1 := by rw [card_eq_zero, cycle_type_eq_zero] lemma is_cycle.cycle_type {σ : perm α} (hσ : is_cycle σ) : σ.cycle_type = [σ.support.card] := cycle_type_eq [σ] (mul_one σ) (λ τ hτ, (congr_arg is_cycle (list.mem_singleton.mp hτ)).mpr hσ) (pairwise_singleton disjoint σ) lemma card_cycle_type_eq_one {σ : perm α} : σ.cycle_type.card = 1 ↔ σ.is_cycle := begin split, { intro hσ, obtain ⟨l, h₁l, h₂l, h₃l⟩ := σ.trunc_cycle_factors.out, rw [cycle_type_eq l h₁l h₂l h₃l, coe_card, length_map] at hσ, obtain ⟨τ, hτ⟩ := length_eq_one.mp hσ, rw [←h₁l, hτ, list.prod_singleton], apply h₂l, rw [hτ, list.mem_singleton] }, { exact λ hσ, by rw [hσ.cycle_type, coe_card, length_singleton] }, end lemma disjoint.cycle_type {σ τ : perm α} (h : disjoint σ τ) : (σ * τ).cycle_type = σ.cycle_type + τ.cycle_type := begin obtain ⟨l₁, h₁l₁, h₂l₁, h₃l₁⟩ := σ.trunc_cycle_factors.out, obtain ⟨l₂, h₁l₂, h₂l₂, h₃l₂⟩ := τ.trunc_cycle_factors.out, rw [cycle_type_eq l₁ h₁l₁ h₂l₁ h₃l₁, cycle_type_eq l₂ h₁l₂ h₂l₂ h₃l₂, cycle_type_eq (l₁ ++ l₂) _ _ _, map_append, ←coe_add], { rw [prod_append, h₁l₁, h₁l₂] }, { exact λ f hf, (mem_append.mp hf).elim (h₂l₁ f) (h₂l₂ f) }, { refine pairwise_append.mpr ⟨h₃l₁, h₃l₂, λ f hf g hg a, by_contra (λ H, _)⟩, rw not_or_distrib at H, exact ((congr_arg2 disjoint h₁l₁ h₁l₂).mpr h a).elim (ne_of_eq_of_ne ((mem_list_cycles_iff h₂l₁ h₃l₁ (h₂l₁ f hf) H.1).1 hf 1).symm H.1) (ne_of_eq_of_ne ((mem_list_cycles_iff h₂l₂ h₃l₂ (h₂l₂ g hg) H.2).1 hg 1).symm H.2) } end lemma cycle_type_inv (σ : perm α) : σ⁻¹.cycle_type = σ.cycle_type := cycle_induction_on (λ τ : perm α, τ⁻¹.cycle_type = τ.cycle_type) σ rfl (λ σ hσ, by rw [hσ.cycle_type, hσ.inv.cycle_type, support_inv]) (λ σ τ hστ hc hσ hτ, by rw [mul_inv_rev, hστ.cycle_type, ←hσ, ←hτ, add_comm, disjoint.cycle_type (λ x, or.imp (λ h : τ x = x, inv_eq_iff_eq.mpr h.symm) (λ h : σ x = x, inv_eq_iff_eq.mpr h.symm) (hστ x).symm)]) lemma cycle_type_conj {σ τ : perm α} : (τ * σ * τ⁻¹).cycle_type = σ.cycle_type := begin revert τ, apply cycle_induction_on _ σ, { intro, simp }, { intros σ hσ τ, rw [hσ.cycle_type, hσ.is_cycle_conj.cycle_type, card_support_conj] }, { intros σ τ hd hc hσ hτ π, rw [← conj_mul, hd.cycle_type, disjoint.cycle_type, hσ, hτ], intro a, apply (hd (π⁻¹ a)).imp _ _; { intro h, rw [perm.mul_apply, perm.mul_apply, h, apply_inv_self] } } end lemma sum_cycle_type (σ : perm α) : σ.cycle_type.sum = σ.support.card := cycle_induction_on (λ τ : perm α, τ.cycle_type.sum = τ.support.card) σ (by rw [cycle_type_one, sum_zero, support_one, finset.card_empty]) (λ σ hσ, by rw [hσ.cycle_type, coe_sum, list.sum_singleton]) (λ σ τ hστ hc hσ hτ, by rw [hστ.cycle_type, sum_add, hσ, hτ, hστ.card_support_mul]) lemma sign_of_cycle_type (σ : perm α) : sign σ = (σ.cycle_type.map (λ n, -(-1 : units ℤ) ^ n)).prod := cycle_induction_on (λ τ : perm α, sign τ = (τ.cycle_type.map (λ n, -(-1 : units ℤ) ^ n)).prod) σ (by rw [sign_one, cycle_type_one, map_zero, prod_zero]) (λ σ hσ, by rw [hσ.sign, hσ.cycle_type, coe_map, coe_prod, list.map_singleton, list.prod_singleton]) (λ σ τ hστ hc hσ hτ, by rw [sign_mul, hσ, hτ, hστ.cycle_type, map_add, prod_add]) lemma lcm_cycle_type (σ : perm α) : σ.cycle_type.lcm = order_of σ := cycle_induction_on (λ τ : perm α, τ.cycle_type.lcm = order_of τ) σ (by rw [cycle_type_one, lcm_zero, order_of_one]) (λ σ hσ, by rw [hσ.cycle_type, ←singleton_coe, lcm_singleton, order_of_is_cycle hσ, nat.normalize_eq]) (λ σ τ hστ hc hσ hτ, by rw [hστ.cycle_type, lcm_add, nat.lcm_eq_lcm, hστ.order_of, hσ, hτ]) lemma dvd_of_mem_cycle_type {σ : perm α} {n : ℕ} (h : n ∈ σ.cycle_type) : n ∣ order_of σ := begin rw ← lcm_cycle_type, exact dvd_lcm h, end lemma cycle_type_prime_order {σ : perm α} (hσ : (order_of σ).prime) : ∃ n : ℕ, σ.cycle_type = repeat (order_of σ) (n + 1) := begin rw eq_repeat_of_mem (λ n hn, or_iff_not_imp_left.mp (hσ.2 n (dvd_of_mem_cycle_type hn)) (ne_of_gt (one_lt_of_mem_cycle_type hn))), use σ.cycle_type.card - 1, rw nat.sub_add_cancel, rw [nat.succ_le_iff, pos_iff_ne_zero, ne, card_cycle_type_eq_zero], rintro rfl, rw order_of_one at hσ, exact hσ.ne_one rfl, end lemma is_cycle_of_prime_order {σ : perm α} (h1 : (order_of σ).prime) (h2 : σ.support.card < 2 * (order_of σ)) : σ.is_cycle := begin obtain ⟨n, hn⟩ := cycle_type_prime_order h1, rw [←σ.sum_cycle_type, hn, multiset.sum_repeat, nsmul_eq_mul, nat.cast_id, mul_lt_mul_right (order_of_pos σ), nat.succ_lt_succ_iff, nat.lt_succ_iff, nat.le_zero_iff] at h2, rw [←card_cycle_type_eq_one, hn, card_repeat, h2], end theorem is_conj_of_cycle_type_eq {σ τ : perm α} (h : cycle_type σ = cycle_type τ) : is_conj σ τ := begin revert τ, apply cycle_induction_on _ σ, { intros τ h, rw [cycle_type_one, eq_comm, cycle_type_eq_zero] at h, rw h }, { intros σ hσ τ hστ, have hτ := card_cycle_type_eq_one.2 hσ, rw [hστ, card_cycle_type_eq_one] at hτ, apply hσ.is_conj hτ, rw [hσ.cycle_type, hτ.cycle_type, coe_eq_coe, singleton_perm] at hστ, simp only [and_true, eq_self_iff_true] at hστ, exact hστ }, { intros σ τ hστ hσ h1 h2 π hπ, obtain ⟨l, rfl, hl1, hl2⟩ := trunc_cycle_factors π, rw [hστ.cycle_type, hσ.cycle_type, cycle_type_eq _ rfl hl1 hl2] at hπ, have h : σ.support.card ∈ map (finset.card ∘ perm.support) l, { rw [← multiset.mem_coe, ← hπ], simp }, obtain ⟨σ', hσ'l, hσ'⟩ := list.mem_map.1 h, rw [(list.perm_cons_erase hσ'l).prod_eq' (hl2.imp (λ _ _, disjoint.mul_comm)), list.prod_cons], refine hστ.is_conj_mul (h1 _) (h2 _) _, { simp only [hσ.cycle_type, (hl1 _ hσ'l).cycle_type, ←hσ'] }, { rw [← coe_map, coe_eq_coe.2 (list.perm_cons_erase hσ'l), singleton_add, ← cons_coe, multiset.map_cons, hσ', cons_inj_right, coe_map] at hπ, rw [hπ, cycle_type_eq (l.erase σ') rfl (λ f hf, hl1 f (list.erase_subset _ _ hf)) (list.pairwise_of_sublist (list.erase_sublist _ _) hl2)] }, { refine disjoint_prod_list_of_disjoint (λ g hg, list.rel_of_pairwise_cons _ hg), refine (list.perm.pairwise_iff _ (list.perm_cons_erase hσ'l).symm).2 hl2, exact (λ _ _, disjoint.symm) } } end theorem is_conj_iff_cycle_type_eq {σ τ : perm α} : is_conj σ τ ↔ σ.cycle_type = τ.cycle_type := ⟨λ h, begin obtain ⟨π, rfl⟩ := is_conj_iff.1 h, rw cycle_type_conj, end, is_conj_of_cycle_type_eq⟩ end cycle_type lemma is_cycle_of_prime_order' {σ : perm α} (h1 : (order_of σ).prime) (h2 : fintype.card α < 2 * (order_of σ)) : σ.is_cycle := begin classical, exact is_cycle_of_prime_order h1 (lt_of_le_of_lt σ.support.card_le_univ h2), end lemma is_cycle_of_prime_order'' {σ : perm α} (h1 : (fintype.card α).prime) (h2 : order_of σ = fintype.card α) : σ.is_cycle := is_cycle_of_prime_order' ((congr_arg nat.prime h2).mpr h1) begin classical, rw [←one_mul (fintype.card α), ←h2, mul_lt_mul_right (order_of_pos σ)], exact one_lt_two, end lemma subgroup_eq_top_of_swap_mem [decidable_eq α] {H : subgroup (perm α)} [d : decidable_pred (∈ H)] {τ : perm α} (h0 : (fintype.card α).prime) (h1 : fintype.card α ∣ fintype.card H) (h2 : τ ∈ H) (h3 : is_swap τ) : H = ⊤ := begin haveI : fact (fintype.card α).prime := ⟨h0⟩, obtain ⟨σ, hσ⟩ := sylow.exists_prime_order_of_dvd_card (fintype.card α) h1, have hσ1 : order_of (σ : perm α) = fintype.card α := (order_of_subgroup σ).trans hσ, have hσ2 : is_cycle ↑σ := is_cycle_of_prime_order'' h0 hσ1, have hσ3 : (σ : perm α).support = ⊤ := finset.eq_univ_of_card (σ : perm α).support ((order_of_is_cycle hσ2).symm.trans hσ1), have hσ4 : subgroup.closure {↑σ, τ} = ⊤ := closure_prime_cycle_swap h0 hσ2 hσ3 h3, rw [eq_top_iff, ←hσ4, subgroup.closure_le, set.insert_subset, set.singleton_subset_iff], exact ⟨subtype.mem σ, h2⟩, end section partition variables [decidable_eq α] /-- The partition corresponding to a permutation -/ def partition (σ : perm α) : partition (fintype.card α) := { parts := σ.cycle_type + repeat 1 (fintype.card α - σ.support.card), parts_pos := λ n hn, begin cases mem_add.mp hn with hn hn, { exact zero_lt_one.trans (one_lt_of_mem_cycle_type hn) }, { exact lt_of_lt_of_le zero_lt_one (ge_of_eq (multiset.eq_of_mem_repeat hn)) }, end, parts_sum := by rw [sum_add, sum_cycle_type, multiset.sum_repeat, nsmul_eq_mul, nat.cast_id, mul_one, nat.add_sub_cancel' σ.support.card_le_univ] } lemma parts_partition {σ : perm α} : σ.partition.parts = σ.cycle_type + repeat 1 (fintype.card α - σ.support.card) := rfl lemma filter_parts_partition_eq_cycle_type {σ : perm α} : (partition σ).parts.filter (λ n, 2 ≤ n) = σ.cycle_type := begin rw [parts_partition, filter_add, multiset.filter_eq_self.2 (λ _, two_le_of_mem_cycle_type), multiset.filter_eq_nil.2 (λ a h, _), add_zero], rw multiset.eq_of_mem_repeat h, dec_trivial end lemma partition_eq_of_is_conj {σ τ : perm α} : is_conj σ τ ↔ σ.partition = τ.partition := begin rw [is_conj_iff_cycle_type_eq], refine ⟨λ h, _, λ h, _⟩, { rw [partition.ext_iff, parts_partition, parts_partition, ← sum_cycle_type, ← sum_cycle_type, h] }, { rw [← filter_parts_partition_eq_cycle_type, ← filter_parts_partition_eq_cycle_type, h] } end end partition /-! ### 3-cycles -/ /-- A three-cycle is a cycle of length 3. -/ def is_three_cycle [decidable_eq α] (σ : perm α) : Prop := σ.cycle_type = {3} namespace is_three_cycle variables [decidable_eq α] {σ : perm α} lemma cycle_type (h : is_three_cycle σ) : σ.cycle_type = {3} := h lemma card_support (h : is_three_cycle σ) : σ.support.card = 3 := by rw [←sum_cycle_type, h.cycle_type, singleton_eq_singleton, multiset.sum_cons, sum_zero] lemma _root_.card_support_eq_three_iff : σ.support.card = 3 ↔ σ.is_three_cycle := begin refine ⟨λ h, _, is_three_cycle.card_support⟩, by_cases h0 : σ.cycle_type = 0, { rw [←sum_cycle_type, h0, sum_zero] at h, exact (ne_of_lt zero_lt_three h).elim }, obtain ⟨n, hn⟩ := exists_mem_of_ne_zero h0, by_cases h1 : σ.cycle_type.erase n = 0, { rw [←sum_cycle_type, ←cons_erase hn, h1, multiset.sum_singleton] at h, rw [is_three_cycle, ←cons_erase hn, h1, h, singleton_eq_singleton] }, obtain ⟨m, hm⟩ := exists_mem_of_ne_zero h1, rw [←sum_cycle_type, ←cons_erase hn, ←cons_erase hm, multiset.sum_cons, multiset.sum_cons] at h, linarith [two_le_of_mem_cycle_type hn, two_le_of_mem_cycle_type (mem_of_mem_erase hm)], end lemma is_cycle (h : is_three_cycle σ) : is_cycle σ := by rw [←card_cycle_type_eq_one, h.cycle_type, singleton_eq_singleton, card_singleton] lemma sign (h : is_three_cycle σ) : sign σ = 1 := begin rw [sign_of_cycle_type, h.cycle_type], refl, end lemma inv {f : perm α} (h : is_three_cycle f) : is_three_cycle (f⁻¹) := by rwa [is_three_cycle, cycle_type_inv] @[simp] lemma inv_iff {f : perm α} : is_three_cycle (f⁻¹) ↔ is_three_cycle f := ⟨by { rw ← inv_inv f, apply inv }, inv⟩ end is_three_cycle section variable [decidable_eq α] lemma is_three_cycle_swap_mul_swap_same {a b c : α} (ab : a ≠ b) (ac : a ≠ c) (bc : b ≠ c) : is_three_cycle (swap a b * swap a c) := begin suffices h : support (swap a b * swap a c) = {a, b, c}, { rw [←card_support_eq_three_iff, h], simp [ab, ac, bc] }, apply le_antisymm ((support_mul_le _ _).trans (λ x, _)) (λ x hx, _), { simp [ab, ac, bc] }, { simp only [finset.mem_insert, finset.mem_singleton] at hx, rw mem_support, simp only [perm.coe_mul, function.comp_app, ne.def], obtain rfl | rfl | rfl := hx, { rw [swap_apply_left, swap_apply_of_ne_of_ne ac.symm bc.symm], exact ac.symm }, { rw [swap_apply_of_ne_of_ne ab.symm bc, swap_apply_right], exact ab }, { rw [swap_apply_right, swap_apply_left], exact bc } } end open subgroup lemma swap_mul_swap_same_mem_closure_three_cycles {a b c : α} (ab : a ≠ b) (ac : a ≠ c) : (swap a b * swap a c) ∈ closure {σ : perm α | is_three_cycle σ } := begin by_cases bc : b = c, { subst bc, simp [one_mem] }, exact subset_closure (is_three_cycle_swap_mul_swap_same ab ac bc) end lemma is_swap.mul_mem_closure_three_cycles {σ τ : perm α} (hσ : is_swap σ) (hτ : is_swap τ) : σ * τ ∈ closure {σ : perm α | is_three_cycle σ } := begin obtain ⟨a, b, ab, rfl⟩ := hσ, obtain ⟨c, d, cd, rfl⟩ := hτ, by_cases ac : a = c, { subst ac, exact swap_mul_swap_same_mem_closure_three_cycles ab cd }, have h' : swap a b * swap c d = swap a b * swap a c * (swap c a * swap c d), { simp [swap_comm c a, mul_assoc] }, rw h', exact mul_mem _ (swap_mul_swap_same_mem_closure_three_cycles ab ac) (swap_mul_swap_same_mem_closure_three_cycles (ne.symm ac) cd), end end end equiv.perm
4b614a622715a80cec1ee86f5015ceadd1eaca44
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/algebra/continued_fractions/computation/approximation_corollaries.lean
1d467ef9ddc76f09e35f288ec5411fc30aeee1fe
[ "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
6,590
lean
/- Copyright (c) 2021 Kevin Kappelmann. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Kappelmann -/ import algebra.continued_fractions.computation.approximations import algebra.continued_fractions.convergents_equiv import topology.algebra.ordered.basic /-! # Corollaries From Approximation Lemmas (`algebra.continued_fractions.computation.approximations`) ## Summary We show that the generalized_continued_fraction given by `generalized_continued_fraction.of` in fact is a (regular) continued fraction. Using the equivalence of the convergents computations (`generalized_continued_fraction.convergents` and `generalized_continued_fraction.convergents'`) for continued fractions (see `algebra.continued_fractions.convergents_equiv`), it follows that the convergents computations for `generalized_continued_fraction.of` are equivalent. Moreover, we show the convergence of the continued fractions computations, that is `(generalized_continued_fraction.of v).convergents` indeed computes `v` in the limit. ## Main Definitions - `continued_fraction.of` returns the (regular) continued fraction of a value. ## Main Theorems - `generalized_continued_fraction.of_convergents_eq_convergents'` shows that the convergents computations for `generalized_continued_fraction.of` are equivalent. - `generalized_continued_fraction.of_convergence` shows that `(generalized_continued_fraction.of v).convergents` converges to `v`. ## Tags convergence, fractions -/ variables {K : Type*} (v : K) [linear_ordered_field K] [floor_ring K] open generalized_continued_fraction as gcf lemma generalized_continued_fraction.of_is_simple_continued_fraction : (gcf.of v).is_simple_continued_fraction := (λ _ _ nth_part_num_eq, gcf.of_part_num_eq_one nth_part_num_eq) /-- Creates the simple continued fraction of a value. -/ def simple_continued_fraction.of : simple_continued_fraction K := ⟨gcf.of v, generalized_continued_fraction.of_is_simple_continued_fraction v⟩ lemma simple_continued_fraction.of_is_continued_fraction : (simple_continued_fraction.of v).is_continued_fraction := (λ _ denom nth_part_denom_eq, lt_of_lt_of_le zero_lt_one(gcf.of_one_le_nth_part_denom nth_part_denom_eq)) /-- Creates the continued fraction of a value. -/ def continued_fraction.of : continued_fraction K := ⟨simple_continued_fraction.of v, simple_continued_fraction.of_is_continued_fraction v⟩ namespace generalized_continued_fraction open continued_fraction as cf lemma of_convergents_eq_convergents' : (gcf.of v).convergents = (gcf.of v).convergents' := @cf.convergents_eq_convergents' _ _ (continued_fraction.of v) section convergence /-! ### Convergence We next show that `(generalized_continued_fraction.of v).convergents v` converges to `v`. -/ variable [archimedean K] local notation `|` x `|` := abs x open nat theorem of_convergence_epsilon : ∀ (ε > (0 : K)), ∃ (N : ℕ), ∀ (n ≥ N), |v - (gcf.of v).convergents n| < ε := begin assume ε ε_pos, -- use the archemidean property to obtian a suitable N rcases (exists_nat_gt (1 / ε) : ∃ (N' : ℕ), 1 / ε < N') with ⟨N', one_div_ε_lt_N'⟩, let N := max N' 5, -- set minimum to 5 to have N ≤ fib N work existsi N, assume n n_ge_N, let g := gcf.of v, cases decidable.em (g.terminated_at n) with terminated_at_n not_terminated_at_n, { have : v = g.convergents n, from of_correctness_of_terminated_at terminated_at_n, have : v - g.convergents n = 0, from sub_eq_zero.elim_right this, rw [this], exact_mod_cast ε_pos }, { let B := g.denominators n, let nB := g.denominators (n + 1), have abs_v_sub_conv_le : |v - g.convergents n| ≤ 1 / (B * nB), from abs_sub_convergents_le not_terminated_at_n, suffices : 1 / (B * nB) < ε, from lt_of_le_of_lt abs_v_sub_conv_le this, -- show that `0 < (B * nB)` and then multiply by `B * nB` to get rid of the division have nB_ineq : (fib (n + 2) : K) ≤ nB, by { have : ¬g.terminated_at (n + 1 - 1), from not_terminated_at_n, exact (succ_nth_fib_le_of_nth_denom (or.inr this)) }, have B_ineq : (fib (n + 1) : K) ≤ B, by { have : ¬g.terminated_at (n - 1), from mt (terminated_stable n.pred_le) not_terminated_at_n, exact (succ_nth_fib_le_of_nth_denom (or.inr this)) }, have zero_lt_B : 0 < B, by { have : (0 : K) < fib (n + 1), by exact_mod_cast fib_pos n.zero_lt_succ, exact (lt_of_lt_of_le this B_ineq) }, have zero_lt_mul_conts : 0 < B * nB, by { have : 0 < nB, by { have : (0 : K) < fib (n + 2), by exact_mod_cast fib_pos (n + 1).zero_lt_succ, exact (lt_of_lt_of_le this nB_ineq) }, solve_by_elim [mul_pos] }, suffices : 1 < ε * (B * nB), from (div_lt_iff zero_lt_mul_conts).elim_right this, -- use that `N ≥ n` was obtained from the archimedian property to show the following have one_lt_ε_mul_N : 1 < ε * n, by { have one_lt_ε_mul_N' : 1 < ε * (N' : K), from (div_lt_iff' ε_pos).elim_left one_div_ε_lt_N', have : (N' : K) ≤ N, by exact_mod_cast (le_max_left _ _), have : ε * N' ≤ ε * n, from (mul_le_mul_left ε_pos).elim_right (le_trans this (by exact_mod_cast n_ge_N)), exact (lt_of_lt_of_le one_lt_ε_mul_N' this) }, suffices : ε * n ≤ ε * (B * nB), from lt_of_lt_of_le one_lt_ε_mul_N this, -- cancel `ε` suffices : (n : K) ≤ B * nB, from (mul_le_mul_left ε_pos).elim_right this, show (n : K) ≤ B * nB, calc (n : K) ≤ fib n : by exact_mod_cast (le_fib_self $ le_trans (le_max_right N' 5) n_ge_N) ... ≤ fib (n + 1) : by exact_mod_cast fib_le_fib_succ ... ≤ fib (n + 1) * fib (n + 1) : by exact_mod_cast ((fib (n + 1)).le_mul_self) ... ≤ fib (n + 1) * fib (n + 2) : mul_le_mul_of_nonneg_left (by exact_mod_cast fib_le_fib_succ) (by exact_mod_cast (fib (n + 1)).zero_le) ... ≤ B * nB : mul_le_mul B_ineq nB_ineq (by exact_mod_cast (fib (n + 2)).zero_le) (le_of_lt zero_lt_B) } end local attribute [instance] preorder.topology theorem of_convergence [order_topology K] : filter.tendsto ((gcf.of v).convergents) filter.at_top $ nhds v := by simpa [linear_ordered_add_comm_group.tendsto_nhds, abs_sub] using (of_convergence_epsilon v) end convergence end generalized_continued_fraction
a410041db6daf0df1fcd4d4354ea4a4127678093
94e33a31faa76775069b071adea97e86e218a8ee
/src/ring_theory/localization/basic.lean
add077631c9bf935f9245e088dd8b75e0244e42a
[ "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
44,337
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Mario Carneiro, Johan Commelin, Amelia Livingston, Anne Baanen -/ import algebra.algebra.basic import algebra.ring.equiv import group_theory.monoid_localization import ring_theory.ideal.basic import ring_theory.non_zero_divisors import tactic.ring_exp /-! # Localizations of commutative rings We characterize the localization of a commutative ring `R` at a submonoid `M` up to isomorphism; that is, a commutative ring `S` is the localization of `R` at `M` iff we can find a ring homomorphism `f : R →+* S` satisfying 3 properties: 1. For all `y ∈ M`, `f y` is a unit; 2. For all `z : S`, there exists `(x, y) : R × M` such that `z * f y = f x`; 3. For all `x, y : R`, `f x = f y` iff there exists `c ∈ M` such that `x * c = y * c`. In the following, let `R, P` be commutative rings, `S, Q` be `R`- and `P`-algebras and `M, T` be submonoids of `R` and `P` respectively, e.g.: ``` variables (R S P Q : Type*) [comm_ring R] [comm_ring S] [comm_ring P] [comm_ring Q] variables [algebra R S] [algebra P Q] (M : submonoid R) (T : submonoid P) ``` ## Main definitions * `is_localization (M : submonoid R) (S : Type*)` is a typeclass expressing that `S` is a localization of `R` at `M`, i.e. the canonical map `algebra_map R S : R →+* S` is a localization map (satisfying the above properties). * `is_localization.mk' S` is a surjection sending `(x, y) : R × M` to `f x * (f y)⁻¹` * `is_localization.lift` is the ring homomorphism from `S` induced by a homomorphism from `R` which maps elements of `M` to invertible elements of the codomain. * `is_localization.map S Q` is the ring homomorphism from `S` to `Q` which maps elements of `M` to elements of `T` * `is_localization.ring_equiv_of_ring_equiv`: if `R` and `P` are isomorphic by an isomorphism sending `M` to `T`, then `S` and `Q` are isomorphic * `is_localization.alg_equiv`: if `Q` is another localization of `R` at `M`, then `S` and `Q` are isomorphic as `R`-algebras ## Main results * `localization M S`, a construction of the localization as a quotient type, defined in `group_theory.monoid_localization`, has `comm_ring`, `algebra R` and `is_localization M` instances if `R` is a ring. `localization.away`, `localization.at_prime` and `fraction_ring` are abbreviations for `localization`s and have their corresponding `is_localization` instances ## Implementation notes In maths it is natural to reason up to isomorphism, but in Lean we cannot naturally `rewrite` one structure with an isomorphic one; one way around this is to isolate a predicate characterizing a structure up to isomorphism, and reason about things that satisfy the predicate. A previous version of this file used a fully bundled type of ring localization maps, then used a type synonym `f.codomain` for `f : localization_map M S` to instantiate the `R`-algebra structure on `S`. This results in defining ad-hoc copies for everything already defined on `S`. By making `is_localization` a predicate on the `algebra_map R S`, we can ensure the localization map commutes nicely with other `algebra_map`s. To prove most lemmas about a localization map `algebra_map R S` in this file we invoke the corresponding proof for the underlying `comm_monoid` localization map `is_localization.to_localization_map M S`, which can be found in `group_theory.monoid_localization` and the namespace `submonoid.localization_map`. To reason about the localization as a quotient type, use `mk_eq_of_mk'` and associated lemmas. These show the quotient map `mk : R → M → localization M` equals the surjection `localization_map.mk'` induced by the map `algebra_map : R →+* localization M`. The lemma `mk_eq_of_mk'` hence gives you access to the results in the rest of the file, which are about the `localization_map.mk'` induced by any localization map. The proof that "a `comm_ring` `K` which is the localization of an integral domain `R` at `R \ {0}` is a field" is a `def` rather than an `instance`, so if you want to reason about a field of fractions `K`, assume `[field K]` instead of just `[comm_ring K]`. ## Tags localization, ring localization, commutative ring localization, characteristic predicate, commutative ring, field of fractions -/ open function open_locale big_operators section comm_semiring variables {R : Type*} [comm_semiring R] (M : submonoid R) (S : Type*) [comm_semiring S] variables [algebra R S] {P : Type*} [comm_semiring P] /-- The typeclass `is_localization (M : submodule R) S` where `S` is an `R`-algebra expresses that `S` is isomorphic to the localization of `R` at `M`. -/ class is_localization : Prop := (map_units [] : ∀ y : M, is_unit (algebra_map R S y)) (surj [] : ∀ z : S, ∃ x : R × M, z * algebra_map R S x.2 = algebra_map R S x.1) (eq_iff_exists [] : ∀ {x y}, algebra_map R S x = algebra_map R S y ↔ ∃ c : M, x * c = y * c) variables {M S} namespace is_localization section is_localization variables [is_localization M S] section variables (M) lemma of_le (N : submonoid R) (h₁ : M ≤ N) (h₂ : ∀ r ∈ N, is_unit (algebra_map R S r)) : is_localization N S := { map_units := λ r, h₂ r r.2, surj := λ s, by { obtain ⟨⟨x, y, hy⟩, H⟩ := is_localization.surj M s, exact ⟨⟨x, y, h₁ hy⟩, H⟩ }, eq_iff_exists := λ x y, begin split, { rw is_localization.eq_iff_exists M, rintro ⟨c, hc⟩, exact ⟨⟨c, h₁ c.2⟩, hc⟩ }, { rintro ⟨c, h⟩, simpa only [set_like.coe_mk, map_mul, (h₂ c c.2).mul_left_inj] using congr_arg (algebra_map R S) h } end } variables (S) /-- `is_localization.to_localization_with_zero_map M S` shows `S` is the monoid localization of `R` at `M`. -/ @[simps] def to_localization_with_zero_map : submonoid.localization_with_zero_map M S := { to_fun := algebra_map R S, map_units' := is_localization.map_units _, surj' := is_localization.surj _, eq_iff_exists' := λ _ _, is_localization.eq_iff_exists _ _, .. algebra_map R S } /-- `is_localization.to_localization_map M S` shows `S` is the monoid localization of `R` at `M`. -/ abbreviation to_localization_map : submonoid.localization_map M S := (to_localization_with_zero_map M S).to_localization_map @[simp] lemma to_localization_map_to_map : (to_localization_map M S).to_map = (algebra_map R S : R →*₀ S) := rfl lemma to_localization_map_to_map_apply (x) : (to_localization_map M S).to_map x = algebra_map R S x := rfl end variables (M) /-- Given a localization map `f : M →* N`, a section function sending `z : N` to some `(x, y) : M × S` such that `f x * (f y)⁻¹ = z`. -/ noncomputable def sec (z : S) : R × M := classical.some $ is_localization.surj _ z @[simp] lemma to_localization_map_sec : (to_localization_map M S).sec = sec M := rfl /-- Given `z : S`, `is_localization.sec M z` is defined to be a pair `(x, y) : R × M` such that `z * f y = f x` (so this lemma is true by definition). -/ lemma sec_spec (z : S) : z * algebra_map R S (is_localization.sec M z).2 = algebra_map R S (is_localization.sec M z).1 := classical.some_spec $ is_localization.surj _ z /-- Given `z : S`, `is_localization.sec M z` is defined to be a pair `(x, y) : R × M` such that `z * f y = f x`, so this lemma is just an application of `S`'s commutativity. -/ lemma sec_spec' (z : S) : algebra_map R S (is_localization.sec M z).1 = algebra_map R S (is_localization.sec M z).2 * z := by rw [mul_comm, sec_spec] variables {R M} lemma map_right_cancel {x y} {c : M} (h : algebra_map R S (c * x) = algebra_map R S (c * y)) : algebra_map R S x = algebra_map R S y := (to_localization_map M S).map_right_cancel h lemma map_left_cancel {x y} {c : M} (h : algebra_map R S (x * c) = algebra_map R S (y * c)) : algebra_map R S x = algebra_map R S y := (to_localization_map M S).map_left_cancel h lemma eq_zero_of_fst_eq_zero {z x} {y : M} (h : z * algebra_map R S y = algebra_map R S x) (hx : x = 0) : z = 0 := by { rw [hx, (algebra_map R S).map_zero] at h, exact (is_unit.mul_left_eq_zero (is_localization.map_units S y)).1 h} variables (M S) lemma map_eq_zero_iff (r : R) : algebra_map R S r = 0 ↔ ∃ m : M, r * m = 0 := begin split, intro h, { obtain ⟨m, hm⟩ := (is_localization.eq_iff_exists M S).mp ((algebra_map R S).map_zero.trans h.symm), exact ⟨m, by simpa using hm.symm⟩ }, { rintro ⟨m, hm⟩, rw [← (is_localization.map_units S m).mul_left_inj, zero_mul, ← ring_hom.map_mul, hm, ring_hom.map_zero] } end variables {M} /-- `is_localization.mk' S` is the surjection sending `(x, y) : R × M` to `f x * (f y)⁻¹`. -/ noncomputable def mk' (x : R) (y : M) : S := (to_localization_map M S).mk' x y @[simp] lemma mk'_sec (z : S) : mk' S (is_localization.sec M z).1 (is_localization.sec M z).2 = z := (to_localization_map M S).mk'_sec _ lemma mk'_mul (x₁ x₂ : R) (y₁ y₂ : M) : mk' S (x₁ * x₂) (y₁ * y₂) = mk' S x₁ y₁ * mk' S x₂ y₂ := (to_localization_map M S).mk'_mul _ _ _ _ lemma mk'_one (x) : mk' S x (1 : M) = algebra_map R S x := (to_localization_map M S).mk'_one _ @[simp] lemma mk'_spec (x) (y : M) : mk' S x y * algebra_map R S y = algebra_map R S x := (to_localization_map M S).mk'_spec _ _ @[simp] lemma mk'_spec' (x) (y : M) : algebra_map R S y * mk' S x y = algebra_map R S x := (to_localization_map M S).mk'_spec' _ _ @[simp] lemma mk'_spec_mk (x) (y : R) (hy : y ∈ M) : mk' S x ⟨y, hy⟩ * algebra_map R S y = algebra_map R S x := mk'_spec S x ⟨y, hy⟩ @[simp] lemma mk'_spec'_mk (x) (y : R) (hy : y ∈ M) : algebra_map R S y * mk' S x ⟨y, hy⟩ = algebra_map R S x := mk'_spec' S x ⟨y, hy⟩ variables {S} theorem eq_mk'_iff_mul_eq {x} {y : M} {z} : z = mk' S x y ↔ z * algebra_map R S y = algebra_map R S x := (to_localization_map M S).eq_mk'_iff_mul_eq theorem mk'_eq_iff_eq_mul {x} {y : M} {z} : mk' S x y = z ↔ algebra_map R S x = z * algebra_map R S y := (to_localization_map M S).mk'_eq_iff_eq_mul theorem mk'_add_eq_iff_add_mul_eq_mul {x} {y : M} {z₁ z₂} : mk' S x y + z₁ = z₂ ↔ algebra_map R S x + z₁ * algebra_map R S y = z₂ * algebra_map R S y := by rw [←mk'_spec S x y, ←is_unit.mul_left_inj (is_localization.map_units S y), right_distrib] variables (M) lemma mk'_surjective (z : S) : ∃ x (y : M), mk' S x y = z := let ⟨r, hr⟩ := is_localization.surj _ z in ⟨r.1, r.2, (eq_mk'_iff_mul_eq.2 hr).symm⟩ variables (S) include M /-- The localization of a `fintype` is a `fintype`. Cannot be an instance. -/ noncomputable def fintype' [fintype R] : fintype S := have _ := classical.prop_decidable, by exactI fintype.of_surjective (function.uncurry $ is_localization.mk' S) (λ a, prod.exists'.mpr $ is_localization.mk'_surjective M a) omit M variables {M S} /-- Localizing at a submonoid with 0 inside it leads to the trivial ring. -/ def unique_of_zero_mem (h : (0 : R) ∈ M) : unique S := unique_of_zero_eq_one $ by simpa using is_localization.map_units S ⟨0, h⟩ lemma mk'_eq_iff_eq {x₁ x₂} {y₁ y₂ : M} : mk' S x₁ y₁ = mk' S x₂ y₂ ↔ algebra_map R S (x₁ * y₂) = algebra_map R S (x₂ * y₁) := (to_localization_map M S).mk'_eq_iff_eq lemma mk'_mem_iff {x} {y : M} {I : ideal S} : mk' S x y ∈ I ↔ algebra_map R S x ∈ I := begin split; intro h, { rw [← mk'_spec S x y, mul_comm], exact I.mul_mem_left ((algebra_map R S) y) h }, { rw ← mk'_spec S x y at h, obtain ⟨b, hb⟩ := is_unit_iff_exists_inv.1 (map_units S y), have := I.mul_mem_left b h, rwa [mul_comm, mul_assoc, hb, mul_one] at this } end protected lemma eq {a₁ b₁} {a₂ b₂ : M} : mk' S a₁ a₂ = mk' S b₁ b₂ ↔ ∃ c : M, a₁ * b₂ * c = b₁ * a₂ * c := (to_localization_map M S).eq lemma mk'_eq_zero_iff (x : R) (s : M) : mk' S x s = 0 ↔ ∃ (m : M), x * m = 0 := by rw [← (map_units S s).mul_left_inj, mk'_spec, zero_mul, map_eq_zero_iff M] @[simp] lemma mk'_zero (s : M) : is_localization.mk' S 0 s = 0 := by rw [eq_comm, is_localization.eq_mk'_iff_mul_eq, zero_mul, map_zero] lemma ne_zero_of_mk'_ne_zero {x : R} {y : M} (hxy : is_localization.mk' S x y ≠ 0) : x ≠ 0 := begin rintro rfl, exact hxy (is_localization.mk'_zero _) end section ext variables [algebra R P] [is_localization M P] lemma eq_iff_eq {x y} : algebra_map R S x = algebra_map R S y ↔ algebra_map R P x = algebra_map R P y := (to_localization_map M S).eq_iff_eq (to_localization_map M P) lemma mk'_eq_iff_mk'_eq {x₁ x₂} {y₁ y₂ : M} : mk' S x₁ y₁ = mk' S x₂ y₂ ↔ mk' P x₁ y₁ = mk' P x₂ y₂ := (to_localization_map M S).mk'_eq_iff_mk'_eq (to_localization_map M P) lemma mk'_eq_of_eq {a₁ b₁ : R} {a₂ b₂ : M} (H : b₁ * a₂ = a₁ * b₂) : mk' S a₁ a₂ = mk' S b₁ b₂ := (to_localization_map M S).mk'_eq_of_eq H variables (S) @[simp] lemma mk'_self {x : R} (hx : x ∈ M) : mk' S x ⟨x, hx⟩ = 1 := (to_localization_map M S).mk'_self _ hx @[simp] lemma mk'_self' {x : M} : mk' S (x : R) x = 1 := (to_localization_map M S).mk'_self' _ lemma mk'_self'' {x : M} : mk' S x.1 x = 1 := mk'_self' _ end ext lemma mul_mk'_eq_mk'_of_mul (x y : R) (z : M) : (algebra_map R S) x * mk' S y z = mk' S (x * y) z := (to_localization_map M S).mul_mk'_eq_mk'_of_mul _ _ _ lemma mk'_eq_mul_mk'_one (x : R) (y : M) : mk' S x y = (algebra_map R S) x * mk' S 1 y := ((to_localization_map M S).mul_mk'_one_eq_mk' _ _).symm @[simp] lemma mk'_mul_cancel_left (x : R) (y : M) : mk' S (y * x : R) y = (algebra_map R S) x := (to_localization_map M S).mk'_mul_cancel_left _ _ lemma mk'_mul_cancel_right (x : R) (y : M) : mk' S (x * y) y = (algebra_map R S) x := (to_localization_map M S).mk'_mul_cancel_right _ _ @[simp] lemma mk'_mul_mk'_eq_one (x y : M) : mk' S (x : R) y * mk' S (y : R) x = 1 := by rw [←mk'_mul, mul_comm]; exact mk'_self _ _ lemma mk'_mul_mk'_eq_one' (x : R) (y : M) (h : x ∈ M) : mk' S x y * mk' S (y : R) ⟨x, h⟩ = 1 := mk'_mul_mk'_eq_one ⟨x, h⟩ _ section variables (M) lemma is_unit_comp (j : S →+* P) (y : M) : is_unit (j.comp (algebra_map R S) y) := (to_localization_map M S).is_unit_comp j.to_monoid_hom _ end /-- Given a localization map `f : R →+* S` for a submonoid `M ⊆ R` and a map of `comm_semiring`s `g : R →+* P` such that `g(M) ⊆ units P`, `f x = f y → g x = g y` for all `x y : R`. -/ lemma eq_of_eq {g : R →+* P} (hg : ∀ y : M, is_unit (g y)) {x y} (h : (algebra_map R S) x = (algebra_map R S) y) : g x = g y := @submonoid.localization_map.eq_of_eq _ _ _ _ _ _ _ (to_localization_map M S) g.to_monoid_hom hg _ _ h lemma mk'_add (x₁ x₂ : R) (y₁ y₂ : M) : mk' S (x₁ * y₂ + x₂ * y₁) (y₁ * y₂) = mk' S x₁ y₁ + mk' S x₂ y₂ := mk'_eq_iff_eq_mul.2 $ eq.symm begin rw [mul_comm (_ + _), mul_add, mul_mk'_eq_mk'_of_mul, mk'_add_eq_iff_add_mul_eq_mul, mul_comm (_ * _), ←mul_assoc, add_comm, ←map_mul, mul_mk'_eq_mk'_of_mul, mk'_add_eq_iff_add_mul_eq_mul], simp only [map_add, submonoid.coe_mul, map_mul], ring end lemma mul_add_inv_left {g : R →+* P} (h : ∀ y : M, is_unit (g y)) (y : M) (w z₁ z₂ : P) : w * ↑(is_unit.lift_right (g.to_monoid_hom.restrict M) h y)⁻¹ + z₁ = z₂ ↔ w + g y * z₁ = g y * z₂ := begin rw [mul_comm, ←one_mul z₁, ←units.inv_mul (is_unit.lift_right (g.to_monoid_hom.restrict M) h y), mul_assoc, ←mul_add, units.inv_mul_eq_iff_eq_mul, units.inv_mul_cancel_left, is_unit.coe_lift_right], simp only [ring_hom.to_monoid_hom_eq_coe, monoid_hom.restrict_apply, ring_hom.coe_monoid_hom] end lemma lift_spec_mul_add {g : R →+* P} (hg : ∀ y : M, is_unit (g y)) (z w w' v) : ((to_localization_with_zero_map M S).lift g.to_monoid_with_zero_hom hg) z * w + w' = v ↔ g ((to_localization_map M S).sec z).1 * w + g ((to_localization_map M S).sec z).2 * w' = g ((to_localization_map M S).sec z).2 * v := begin show (_ * _) * _ + _ = _ ↔ _ = _, erw [mul_comm, ←mul_assoc, mul_add_inv_left hg, mul_comm], refl end /-- Given a localization map `f : R →+* S` for a submonoid `M ⊆ R` and a map of `comm_semiring`s `g : R →+* P` such that `g y` is invertible for all `y : M`, the homomorphism induced from `S` to `P` sending `z : S` to `g x * (g y)⁻¹`, where `(x, y) : R × M` are such that `z = f x * (f y)⁻¹`. -/ noncomputable def lift {g : R →+* P} (hg : ∀ y : M, is_unit (g y)) : S →+* P := { map_add' := begin intros x y, erw [(to_localization_map M S).lift_spec, mul_add, mul_comm, eq_comm, lift_spec_mul_add, add_comm, mul_comm,mul_assoc,mul_comm,mul_assoc, lift_spec_mul_add], simp_rw ←mul_assoc, show g _ * g _ * g _ + g _ * g _ * g _ = g _ * g _ * g _, simp_rw [←map_mul g, ←map_add g], apply @eq_of_eq _ _ _ S _ _ _ _ _ g hg, simp only [sec_spec', to_localization_map_sec, map_add, map_mul], ring end, .. @submonoid.localization_with_zero_map.lift _ _ _ _ _ _ _ (to_localization_with_zero_map M S) g.to_monoid_with_zero_hom hg } variables {g : R →+* P} (hg : ∀ y : M, is_unit (g y)) /-- Given a localization map `f : R →+* S` for a submonoid `M ⊆ R` and a map of `comm_semiring`s `g : R →* P` such that `g y` is invertible for all `y : M`, the homomorphism induced from `S` to `P` maps `f x * (f y)⁻¹` to `g x * (g y)⁻¹` for all `x : R, y ∈ M`. -/ lemma lift_mk' (x y) : lift hg (mk' S x y) = g x * ↑(is_unit.lift_right (g.to_monoid_hom.restrict M) hg y)⁻¹ := (to_localization_map M S).lift_mk' _ _ _ lemma lift_mk'_spec (x v) (y : M) : lift hg (mk' S x y) = v ↔ g x = g y * v := (to_localization_map M S).lift_mk'_spec _ _ _ _ @[simp] lemma lift_eq (x : R) : lift hg ((algebra_map R S) x) = g x := (to_localization_map M S).lift_eq _ _ lemma lift_eq_iff {x y : R × M} : lift hg (mk' S x.1 x.2) = lift hg (mk' S y.1 y.2) ↔ g (x.1 * y.2) = g (y.1 * x.2) := (to_localization_map M S).lift_eq_iff _ @[simp] lemma lift_comp : (lift hg).comp (algebra_map R S) = g := ring_hom.ext $ monoid_hom.ext_iff.1 $ (to_localization_map M S).lift_comp _ @[simp] lemma lift_of_comp (j : S →+* P) : lift (is_unit_comp M j) = j := ring_hom.ext $ monoid_hom.ext_iff.1 $ (to_localization_map M S).lift_of_comp j.to_monoid_hom variables (M) /-- See note [partially-applied ext lemmas] -/ lemma monoid_hom_ext ⦃j k : S →* P⦄ (h : j.comp (algebra_map R S : R →* S) = k.comp (algebra_map R S)) : j = k := submonoid.localization_map.epic_of_localization_map (to_localization_map M S) $ monoid_hom.congr_fun h /-- See note [partially-applied ext lemmas] -/ lemma ring_hom_ext ⦃j k : S →+* P⦄ (h : j.comp (algebra_map R S) = k.comp (algebra_map R S)) : j = k := ring_hom.coe_monoid_hom_injective $ monoid_hom_ext M $ monoid_hom.ext $ ring_hom.congr_fun h /-- To show `j` and `k` agree on the whole localization, it suffices to show they agree on the image of the base ring, if they preserve `1` and `*`. -/ protected lemma ext (j k : S → P) (hj1 : j 1 = 1) (hk1 : k 1 = 1) (hjm : ∀ a b, j (a * b) = j a * j b) (hkm : ∀ a b, k (a * b) = k a * k b) (h : ∀ a, j (algebra_map R S a) = k (algebra_map R S a)) : j = k := monoid_hom.mk.inj (monoid_hom_ext M $ monoid_hom.ext h : (⟨j, hj1, hjm⟩ : S →* P) = ⟨k, hk1, hkm⟩) variables {M} lemma lift_unique {j : S →+* P} (hj : ∀ x, j ((algebra_map R S) x) = g x) : lift hg = j := ring_hom.ext $ monoid_hom.ext_iff.1 $ @submonoid.localization_map.lift_unique _ _ _ _ _ _ _ (to_localization_map M S) g.to_monoid_hom hg j.to_monoid_hom hj @[simp] lemma lift_id (x) : lift (map_units S : ∀ y : M, is_unit _) x = x := (to_localization_map M S).lift_id _ lemma lift_surjective_iff : surjective (lift hg : S → P) ↔ ∀ v : P, ∃ x : R × M, v * g x.2 = g x.1 := (to_localization_map M S).lift_surjective_iff hg lemma lift_injective_iff : injective (lift hg : S → P) ↔ ∀ x y, algebra_map R S x = algebra_map R S y ↔ g x = g y := (to_localization_map M S).lift_injective_iff hg section map variables {T : submonoid P} {Q : Type*} [comm_semiring Q] (hy : M ≤ T.comap g) variables [algebra P Q] [is_localization T Q] section variables (Q) /-- Map a homomorphism `g : R →+* P` to `S →+* Q`, where `S` and `Q` are localizations of `R` and `P` at `M` and `T` respectively, such that `g(M) ⊆ T`. We send `z : S` to `algebra_map P Q (g x) * (algebra_map P Q (g y))⁻¹`, where `(x, y) : R × M` are such that `z = f x * (f y)⁻¹`. -/ noncomputable def map (g : R →+* P) (hy : M ≤ T.comap g) : S →+* Q := @lift R _ M _ _ _ _ _ _ ((algebra_map P Q).comp g) (λ y, map_units _ ⟨g y, hy y.2⟩) end lemma map_eq (x) : map Q g hy ((algebra_map R S) x) = algebra_map P Q (g x) := lift_eq (λ y, map_units _ ⟨g y, hy y.2⟩) x @[simp] lemma map_comp : (map Q g hy).comp (algebra_map R S) = (algebra_map P Q).comp g := lift_comp $ λ y, map_units _ ⟨g y, hy y.2⟩ lemma map_mk' (x) (y : M) : map Q g hy (mk' S x y) = mk' Q (g x) ⟨g y, hy y.2⟩ := @submonoid.localization_map.map_mk' _ _ _ _ _ _ _ (to_localization_map M S) g.to_monoid_hom _ (λ y, hy y.2) _ _ (to_localization_map T Q) _ _ @[simp] lemma map_id (z : S) (h : M ≤ M.comap (ring_hom.id R) := le_refl M) : map S (ring_hom.id _) h z = z := lift_id _ lemma map_unique (j : S →+* Q) (hj : ∀ x : R, j (algebra_map R S x) = algebra_map P Q (g x)) : map Q g hy = j := lift_unique (λ y, map_units _ ⟨g y, hy y.2⟩) hj /-- If `comm_semiring` homs `g : R →+* P, l : P →+* A` induce maps of localizations, the composition of the induced maps equals the map of localizations induced by `l ∘ g`. -/ lemma map_comp_map {A : Type*} [comm_semiring A] {U : submonoid A} {W} [comm_semiring W] [algebra A W] [is_localization U W] {l : P →+* A} (hl : T ≤ U.comap l) : (map W l hl).comp (map Q g hy : S →+* _) = map W (l.comp g) (λ x hx, hl (hy hx)) := ring_hom.ext $ λ x, @submonoid.localization_map.map_map _ _ _ _ _ P _ (to_localization_map M S) g _ _ _ _ _ _ _ _ _ _ (to_localization_map U W) l _ x /-- If `comm_semiring` homs `g : R →+* P, l : P →+* A` induce maps of localizations, the composition of the induced maps equals the map of localizations induced by `l ∘ g`. -/ lemma map_map {A : Type*} [comm_semiring A] {U : submonoid A} {W} [comm_semiring W] [algebra A W] [is_localization U W] {l : P →+* A} (hl : T ≤ U.comap l) (x : S) : map W l hl (map Q g hy x) = map W (l.comp g) (λ x hx, hl (hy hx)) x := by rw ←map_comp_map hy hl; refl lemma map_smul (x : S) (z : R) : map Q g hy (z • x : S) = g z • map Q g hy x := by rw [algebra.smul_def, algebra.smul_def, ring_hom.map_mul, map_eq] section variables (S Q) /-- If `S`, `Q` are localizations of `R` and `P` at submonoids `M, T` respectively, an isomorphism `j : R ≃+* P` such that `j(M) = T` induces an isomorphism of localizations `S ≃+* Q`. -/ @[simps] noncomputable def ring_equiv_of_ring_equiv (h : R ≃+* P) (H : M.map h.to_monoid_hom = T) : S ≃+* Q := have H' : T.map h.symm.to_monoid_hom = M, by { rw [← M.map_id, ← H, submonoid.map_map], congr, ext, apply h.symm_apply_apply }, { to_fun := map Q (h : R →+* P) (M.le_comap_of_map_le (le_of_eq H)), inv_fun := map S (h.symm : P →+* R) (T.le_comap_of_map_le (le_of_eq H')), left_inv := λ x, by { rw [map_map, map_unique _ (ring_hom.id _), ring_hom.id_apply], intro x, convert congr_arg (algebra_map R S) (h.symm_apply_apply x).symm }, right_inv := λ x, by { rw [map_map, map_unique _ (ring_hom.id _), ring_hom.id_apply], intro x, convert congr_arg (algebra_map P Q) (h.apply_symm_apply x).symm }, .. map Q (h : R →+* P) _ } end lemma ring_equiv_of_ring_equiv_eq_map {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) : (ring_equiv_of_ring_equiv S Q j H : S →+* Q) = map Q (j : R →+* P) (M.le_comap_of_map_le (le_of_eq H)) := rfl @[simp] lemma ring_equiv_of_ring_equiv_eq {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) (x) : ring_equiv_of_ring_equiv S Q j H ((algebra_map R S) x) = algebra_map P Q (j x) := map_eq _ _ lemma ring_equiv_of_ring_equiv_mk' {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) (x : R) (y : M) : ring_equiv_of_ring_equiv S Q j H (mk' S x y) = mk' Q (j x) ⟨j y, show j y ∈ T, from H ▸ set.mem_image_of_mem j y.2⟩ := map_mk' _ _ _ end map section alg_equiv variables {Q : Type*} [comm_semiring Q] [algebra R Q] [is_localization M Q] section variables (M S Q) /-- If `S`, `Q` are localizations of `R` at the submonoid `M` respectively, there is an isomorphism of localizations `S ≃ₐ[R] Q`. -/ @[simps] noncomputable def alg_equiv : S ≃ₐ[R] Q := { commutes' := ring_equiv_of_ring_equiv_eq _, .. ring_equiv_of_ring_equiv S Q (ring_equiv.refl R) M.map_id } end @[simp] lemma alg_equiv_mk' (x : R) (y : M) : alg_equiv M S Q (mk' S x y) = mk' Q x y:= map_mk' _ _ _ @[simp] lemma alg_equiv_symm_mk' (x : R) (y : M) : (alg_equiv M S Q).symm (mk' Q x y) = mk' S x y:= map_mk' _ _ _ end alg_equiv end is_localization section variables (M) lemma is_localization_of_alg_equiv [algebra R P] [is_localization M S] (h : S ≃ₐ[R] P) : is_localization M P := begin constructor, { intro y, convert (is_localization.map_units S y).map h.to_alg_hom.to_ring_hom.to_monoid_hom, exact (h.commutes y).symm }, { intro y, obtain ⟨⟨x, s⟩, e⟩ := is_localization.surj M (h.symm y), apply_fun h at e, simp only [h.map_mul, h.apply_symm_apply, h.commutes] at e, exact ⟨⟨x, s⟩, e⟩ }, { intros x y, rw [← h.symm.to_equiv.injective.eq_iff, ← is_localization.eq_iff_exists M S, ← h.symm.commutes, ← h.symm.commutes], refl } end lemma is_localization_iff_of_alg_equiv [algebra R P] (h : S ≃ₐ[R] P) : is_localization M S ↔ is_localization M P := ⟨λ _, by exactI is_localization_of_alg_equiv M h, λ _, by exactI is_localization_of_alg_equiv M h.symm⟩ lemma is_localization_iff_of_ring_equiv (h : S ≃+* P) : is_localization M S ↔ @@is_localization _ M P _ (h.to_ring_hom.comp $ algebra_map R S).to_algebra := begin letI := (h.to_ring_hom.comp $ algebra_map R S).to_algebra, exact is_localization_iff_of_alg_equiv M { commutes' := λ _, rfl, ..h }, end variable (S) lemma is_localization_of_base_ring_equiv [is_localization M S] (h : R ≃+* P) : @@is_localization _ (M.map h.to_monoid_hom) S _ ((algebra_map R S).comp h.symm.to_ring_hom).to_algebra := begin constructor, { rintros ⟨_, ⟨y, hy, rfl⟩⟩, convert is_localization.map_units S ⟨y, hy⟩, dsimp only [ring_hom.algebra_map_to_algebra, ring_hom.comp_apply], exact congr_arg _ (h.symm_apply_apply _) }, { intro y, obtain ⟨⟨x, s⟩, e⟩ := is_localization.surj M y, refine ⟨⟨h x, _, _, s.prop, rfl⟩, _⟩, dsimp only [ring_hom.algebra_map_to_algebra, ring_hom.comp_apply] at ⊢ e, convert e; exact h.symm_apply_apply _ }, { intros x y, rw [ring_hom.algebra_map_to_algebra, ring_hom.comp_apply, ring_hom.comp_apply, is_localization.eq_iff_exists M S], simp_rw ← h.to_equiv.apply_eq_iff_eq, change (∃ (c : M), h (h.symm x * c) = h (h.symm y * c)) ↔ _, simp only [ring_equiv.apply_symm_apply, ring_equiv.map_mul], exact ⟨λ ⟨c, e⟩, ⟨⟨_, _, c.prop, rfl⟩, e⟩, λ ⟨⟨_, c, h, e₁⟩, e₂⟩, ⟨⟨_, h⟩, e₁.symm ▸ e₂⟩⟩ } end lemma is_localization_iff_of_base_ring_equiv (h : R ≃+* P) : is_localization M S ↔ @@is_localization _ (M.map h.to_monoid_hom) S _ ((algebra_map R S).comp h.symm.to_ring_hom).to_algebra := begin refine ⟨λ _, by exactI is_localization_of_base_ring_equiv _ _ h, _⟩, letI := ((algebra_map R S).comp h.symm.to_ring_hom).to_algebra, intro H, convert @@is_localization_of_base_ring_equiv _ _ _ _ _ _ H h.symm, { erw [submonoid.map_equiv_eq_comap_symm, submonoid.comap_map_eq_of_injective], exact h.to_equiv.injective }, rw [ring_hom.algebra_map_to_algebra, ring_hom.comp_assoc], simp only [ring_hom.comp_id, ring_equiv.symm_symm, ring_equiv.symm_to_ring_hom_comp_to_ring_hom], apply algebra.algebra_ext, intro r, rw ring_hom.algebra_map_to_algebra end end variables (M S) include M lemma non_zero_divisors_le_comap [is_localization M S] : non_zero_divisors R ≤ (non_zero_divisors S).comap (algebra_map R S) := begin rintros a ha b (e : b * algebra_map R S a = 0), obtain ⟨x, s, rfl⟩ := mk'_surjective M b, rw [← @mk'_one R _ M, ← mk'_mul, ← (algebra_map R S).map_zero, ← @mk'_one R _ M, is_localization.eq] at e, obtain ⟨c, e⟩ := e, rw [zero_mul, zero_mul, submonoid.coe_one, mul_one, mul_comm x a, mul_assoc, mul_comm] at e, rw mk'_eq_zero_iff, exact ⟨c, ha _ e⟩ end lemma map_non_zero_divisors_le [is_localization M S] : (non_zero_divisors R).map (algebra_map R S).to_monoid_hom ≤ non_zero_divisors S := submonoid.map_le_iff_le_comap.mpr (non_zero_divisors_le_comap M S) end is_localization namespace localization open is_localization /-! ### Constructing a localization at a given submonoid -/ variables {M} section instance [subsingleton R] : unique (localization M) := ⟨⟨1⟩, begin intro a, induction a, induction default, congr, refl, refl end⟩ /-- Addition in a ring localization is defined as `⟨a, b⟩ + ⟨c, d⟩ = ⟨b * c + d * a, b * d⟩`. Should not be confused with `add_localization.add`, which is defined as `⟨a, b⟩ + ⟨c, d⟩ = ⟨a + c, b + d⟩`. -/ @[irreducible] protected def add (z w : localization M) : localization M := localization.lift_on₂ z w (λ a b c d, mk ((b : R) * c + d * a) (b * d)) $ λ a a' b b' c c' d d' h1 h2, mk_eq_mk_iff.2 begin rw r_eq_r' at h1 h2 ⊢, cases h1 with t₅ ht₅, cases h2 with t₆ ht₆, use t₆ * t₅, calc ((b : R) * c + d * a) * (b' * d') * (t₆ * t₅) = (c * d' * t₆) * (b * b' * t₅) + (a * b' * t₅) * (d * d' * t₆) : by ring ... = (b' * c' + d' * a') * (b * d) * (t₆ * t₅) : by rw [ht₆, ht₅]; ring end instance : has_add (localization M) := ⟨localization.add⟩ lemma add_mk (a b c d) : (mk a b : localization M) + mk c d = mk (b * c + d * a) (b * d) := by { unfold has_add.add localization.add, apply lift_on₂_mk } lemma add_mk_self (a b c) : (mk a b : localization M) + mk c b = mk (a + c) b := begin rw [add_mk, mk_eq_mk_iff, r_eq_r'], refine (r' M).symm ⟨1, _⟩, simp only [submonoid.coe_one, submonoid.coe_mul], ring end private meta def tac := `[ { intros, simp only [add_mk, localization.mk_mul, ← localization.mk_zero 1], refine mk_eq_mk_iff.mpr (r_of_eq _), simp only [submonoid.coe_mul], ring }] instance : comm_semiring (localization M) := { zero := 0, one := 1, add := (+), mul := (*), npow := localization.npow _, nsmul := (•), nsmul_zero' := λ x, localization.induction_on x (λ x, by simp only [smul_mk, zero_nsmul, mk_zero]), nsmul_succ' := λ n x, localization.induction_on x (λ x, by simp only [smul_mk, succ_nsmul, add_mk_self]), add_assoc := λ m n k, localization.induction_on₃ m n k (by tac), zero_add := λ y, localization.induction_on y (by tac), add_zero := λ y, localization.induction_on y (by tac), add_comm := λ y z, localization.induction_on₂ z y (by tac), left_distrib := λ m n k, localization.induction_on₃ m n k (by tac), right_distrib := λ m n k, localization.induction_on₃ m n k (by tac), .. localization.comm_monoid_with_zero M } /--For any given denominator `b : M`, the map `a ↦ a / b` is an `add_monoid_hom` from `R` to `localization M`-/ @[simps] def mk_add_monoid_hom (b : M) : R →+ localization M := { to_fun := λ a, mk a b, map_zero' := mk_zero _, map_add' := λ x y, (add_mk_self _ _ _).symm } lemma mk_sum {ι : Type*} (f : ι → R) (s : finset ι) (b : M) : mk (∑ i in s, f i) b = ∑ i in s, mk (f i) b := (mk_add_monoid_hom b).map_sum f s lemma mk_list_sum (l : list R) (b : M) : mk l.sum b = (l.map $ λ a, mk a b).sum := (mk_add_monoid_hom b).map_list_sum l lemma mk_multiset_sum (l : multiset R) (b : M) : mk l.sum b = (l.map $ λ a, mk a b).sum := (mk_add_monoid_hom b).map_multiset_sum l instance {S : Type*} [monoid S] [distrib_mul_action S R] [is_scalar_tower S R R] : distrib_mul_action S (localization M) := { smul_zero := λ s, by simp only [←localization.mk_zero 1, localization.smul_mk, smul_zero], smul_add := λ s x y, localization.induction_on₂ x y $ prod.rec $ by exact λ r₁ x₁, prod.rec $ by exact λ r₂ x₂, by simp only [localization.smul_mk, localization.add_mk, smul_add, mul_comm _ (s • _), mul_comm _ r₁, mul_comm _ r₂, smul_mul_assoc] } instance {S : Type*} [semiring S] [mul_semiring_action S R] [is_scalar_tower S R R] : mul_semiring_action S (localization M) := { ..localization.mul_distrib_mul_action } instance {S : Type*} [semiring S] [module S R] [is_scalar_tower S R R] : module S (localization M) := { zero_smul := localization.ind $ prod.rec $ by { intros, simp only [localization.smul_mk, zero_smul, mk_zero] }, add_smul := λ s₁ s₂, localization.ind $ prod.rec $ by { intros, simp only [localization.smul_mk, add_smul, add_mk_self] }, ..localization.distrib_mul_action } instance {S : Type*} [comm_semiring S] [algebra S R] : algebra S (localization M) := { to_ring_hom := ring_hom.comp { to_fun := (monoid_of M).to_map, map_zero' := by rw [← mk_zero (1 : M), mk_one_eq_monoid_of_mk], map_add' := λ x y, by simp only [← mk_one_eq_monoid_of_mk, add_mk, submonoid.coe_one, one_mul, add_comm], .. localization.monoid_of M } (algebra_map S R), smul_def' := λ s, localization.ind $ prod.rec $ begin intros r x, dsimp, simp only [←mk_one_eq_monoid_of_mk, mk_mul, localization.smul_mk, one_mul, algebra.smul_def], end, commutes' := λ s, localization.ind $ prod.rec $ begin intros r x, dsimp, simp only [←mk_one_eq_monoid_of_mk, mk_mul, localization.smul_mk, one_mul, mul_one, algebra.commutes], end } instance : is_localization M (localization M) := { map_units := (localization.monoid_of M).map_units, surj := (localization.monoid_of M).surj, eq_iff_exists := λ _ _, (localization.monoid_of M).eq_iff_exists } end @[simp] lemma to_localization_map_eq_monoid_of : to_localization_map M (localization M) = monoid_of M := rfl lemma monoid_of_eq_algebra_map (x) : (monoid_of M).to_map x = algebra_map R (localization M) x := rfl lemma mk_one_eq_algebra_map (x) : mk x 1 = algebra_map R (localization M) x := rfl lemma mk_eq_mk'_apply (x y) : mk x y = is_localization.mk' (localization M) x y := by rw [mk_eq_monoid_of_mk'_apply, mk', to_localization_map_eq_monoid_of] @[simp] lemma mk_eq_mk' : (mk : R → M → localization M) = is_localization.mk' (localization M) := mk_eq_monoid_of_mk' lemma mk_algebra_map {A : Type*} [comm_semiring A] [algebra A R] (m : A) : mk (algebra_map A R m) 1 = algebra_map A (localization M) m := by rw [mk_eq_mk', mk'_eq_iff_eq_mul, submonoid.coe_one, map_one, mul_one]; refl lemma mk_nat_cast (m : ℕ) : (mk m 1 : localization M) = m := by simpa using @mk_algebra_map R _ M ℕ _ _ m variables [is_localization M S] section variables (M S) /-- The localization of `R` at `M` as a quotient type is isomorphic to any other localization. -/ @[simps] noncomputable def alg_equiv : localization M ≃ₐ[R] S := is_localization.alg_equiv M _ _ /-- The localization of a singleton is a singleton. Cannot be an instance due to metavariables. -/ noncomputable def _root_.is_localization.unique (R Rₘ) [comm_semiring R] [comm_semiring Rₘ] (M : submonoid R) [subsingleton R] [algebra R Rₘ] [is_localization M Rₘ] : unique Rₘ := have inhabited Rₘ := ⟨1⟩, by exactI (alg_equiv M Rₘ).symm.injective.unique end @[simp] lemma alg_equiv_mk' (x : R) (y : M) : alg_equiv M S (mk' (localization M) x y) = mk' S x y := alg_equiv_mk' _ _ @[simp] lemma alg_equiv_symm_mk' (x : R) (y : M) : (alg_equiv M S).symm (mk' S x y) = mk' (localization M) x y := alg_equiv_symm_mk' _ _ lemma alg_equiv_mk (x y) : alg_equiv M S (mk x y) = mk' S x y := by rw [mk_eq_mk', alg_equiv_mk'] lemma alg_equiv_symm_mk (x : R) (y : M) : (alg_equiv M S).symm (mk' S x y) = mk x y := by rw [mk_eq_mk', alg_equiv_symm_mk'] end localization end comm_semiring section comm_ring variables {R : Type*} [comm_ring R] {M : submonoid R} (S : Type*) [comm_ring S] variables [algebra R S] {P : Type*} [comm_ring P] namespace localization /-- Negation in a ring localization is defined as `-⟨a, b⟩ = ⟨-a, b⟩`. -/ @[irreducible] protected def neg (z : localization M) : localization M := localization.lift_on z (λ a b, mk (-a) b) $ λ a b c d h, mk_eq_mk_iff.2 begin rw r_eq_r' at h ⊢, cases h with t ht, use t, rw [neg_mul, neg_mul, ht], ring_nf, end instance : has_neg (localization M) := ⟨localization.neg⟩ lemma neg_mk (a b) : -(mk a b : localization M) = mk (-a) b := by { unfold has_neg.neg localization.neg, apply lift_on_mk } instance : comm_ring (localization M) := { zsmul := (•), zsmul_zero' := λ x, localization.induction_on x (λ x, by simp only [smul_mk, zero_zsmul, mk_zero]), zsmul_succ' := λ n x, localization.induction_on x (λ x, by simp [smul_mk, add_mk_self, -mk_eq_monoid_of_mk', add_comm (n : ℤ) 1, add_smul]), zsmul_neg' := λ n x, localization.induction_on x (λ x, by { rw [smul_mk, smul_mk, neg_mk, ← neg_smul], refl }), neg := has_neg.neg, sub := λ x y, x + -y, sub_eq_add_neg := λ x y, rfl, add_left_neg := λ y, by exact localization.induction_on y begin intros, simp only [add_mk, localization.mk_mul, neg_mk, ← mk_zero 1], refine mk_eq_mk_iff.mpr (r_of_eq _), simp only [submonoid.coe_mul], ring end, .. localization.comm_semiring } lemma sub_mk (a c) (b d) : (mk a b : localization M) - mk c d = mk (d * a - b * c) (b * d) := calc mk a b - mk c d = mk a b + (- mk c d) : sub_eq_add_neg _ _ ... = mk a b + (mk (-c) d) : by rw neg_mk ... = mk (b * (-c) + d * a) (b * d) : add_mk _ _ _ _ ... = mk (d * a - b * c) (b * d) : by congr'; ring lemma mk_int_cast (m : ℤ) : (mk m 1 : localization M) = m := by simpa using @mk_algebra_map R _ M ℤ _ _ m end localization namespace is_localization variables {R M} (S) {K : Type*} [is_localization M S] lemma to_map_eq_zero_iff {x : R} (hM : M ≤ non_zero_divisors R) : algebra_map R S x = 0 ↔ x = 0 := begin rw ← (algebra_map R S).map_zero, split; intro h, { cases (eq_iff_exists M S).mp h with c hc, rw zero_mul at hc, exact hM c.2 x hc }, { rw h }, end protected lemma injective (hM : M ≤ non_zero_divisors R) : injective (algebra_map R S) := begin rw injective_iff_map_eq_zero (algebra_map R S), intros a ha, rwa to_map_eq_zero_iff S hM at ha end protected lemma to_map_ne_zero_of_mem_non_zero_divisors [nontrivial R] (hM : M ≤ non_zero_divisors R) {x : R} (hx : x ∈ non_zero_divisors R) : algebra_map R S x ≠ 0 := show (algebra_map R S).to_monoid_with_zero_hom x ≠ 0, from map_ne_zero_of_mem_non_zero_divisors (algebra_map R S) (is_localization.injective S hM) hx variables (S M) (Q : Type*) [comm_ring Q] {g : R →+* P} [algebra P Q] /-- Injectivity of a map descends to the map induced on localizations. -/ lemma map_injective_of_injective (hg : function.injective g) [is_localization (M.map g : submonoid P) Q] : function.injective (map Q g M.le_comap_map : S → Q) := begin rw injective_iff_map_eq_zero, intros z hz, obtain ⟨a, b, rfl⟩ := mk'_surjective M z, rw [map_mk', mk'_eq_zero_iff] at hz, obtain ⟨⟨m', hm'⟩, hm⟩ := hz, rw submonoid.mem_map at hm', obtain ⟨n, hn, hnm⟩ := hm', rw [subtype.coe_mk, ← hnm, ← map_mul, ← map_zero g] at hm, rw [mk'_eq_zero_iff], exact ⟨⟨n, hn⟩, hg hm⟩, end variables {S Q M} variables (A : Type*) [comm_ring A] [is_domain A] /-- A `comm_ring` `S` which is the localization of an integral domain `R` at a subset of non-zero elements is an integral domain. See note [reducible non-instances]. -/ @[reducible] theorem is_domain_of_le_non_zero_divisors [algebra A S] {M : submonoid A} [is_localization M S] (hM : M ≤ non_zero_divisors A) : is_domain S := { eq_zero_or_eq_zero_of_mul_eq_zero := begin intros z w h, cases surj M z with x hx, cases surj M w with y hy, have : z * w * algebra_map A S y.2 * algebra_map A S x.2 = algebra_map A S x.1 * algebra_map A S y.1, by rw [mul_assoc z, hy, ←hx]; ring, rw [h, zero_mul, zero_mul, ← (algebra_map A S).map_mul] at this, cases eq_zero_or_eq_zero_of_mul_eq_zero ((to_map_eq_zero_iff S hM).mp this.symm) with H H, { exact or.inl (eq_zero_of_fst_eq_zero hx H) }, { exact or.inr (eq_zero_of_fst_eq_zero hy H) }, end, exists_pair_ne := ⟨(algebra_map A S) 0, (algebra_map A S) 1, λ h, zero_ne_one (is_localization.injective S hM h)⟩, } variables {A} /-- The localization at of an integral domain to a set of non-zero elements is an integral domain. See note [reducible non-instances]. -/ @[reducible] theorem is_domain_localization {M : submonoid A} (hM : M ≤ non_zero_divisors A) : is_domain (localization M) := is_domain_of_le_non_zero_divisors _ hM end is_localization open is_localization /-- If `R` is a field, then localizing at a submonoid not containing `0` adds no new elements. -/ lemma is_field.localization_map_bijective {R Rₘ : Type*} [comm_ring R] [comm_ring Rₘ] {M : submonoid R} (hM : (0 : R) ∉ M) (hR : is_field R) [algebra R Rₘ] [is_localization M Rₘ] : function.bijective (algebra_map R Rₘ) := begin letI := hR.to_field, replace hM := le_non_zero_divisors_of_no_zero_divisors hM, refine ⟨is_localization.injective _ hM, λ x, _⟩, obtain ⟨r, ⟨m, hm⟩, rfl⟩ := mk'_surjective M x, obtain ⟨n, hn⟩ := hR.mul_inv_cancel (non_zero_divisors.ne_zero $ hM hm), exact ⟨r * n, by erw [eq_mk'_iff_mul_eq, ←map_mul, mul_assoc, mul_comm n, hn, mul_one]⟩ end /-- If `R` is a field, then localizing at a submonoid not containing `0` adds no new elements. -/ lemma field.localization_map_bijective {K Kₘ : Type*} [field K] [comm_ring Kₘ] {M : submonoid K} (hM : (0 : K) ∉ M) [algebra K Kₘ] [is_localization M Kₘ] : function.bijective (algebra_map K Kₘ) := (field.to_is_field K).localization_map_bijective hM -- this looks weird due to the `letI` inside the above lemma, but trying to do it the other -- way round causes issues with defeq of instances, so this is actually easier. section algebra variables {R S} {Rₘ Sₘ : Type*} [comm_ring Rₘ] [comm_ring Sₘ] variables [algebra R Rₘ] [is_localization M Rₘ] variables [algebra S Sₘ] [is_localization (algebra.algebra_map_submonoid S M) Sₘ] section variables (S M) /-- Definition of the natural algebra induced by the localization of an algebra. Given an algebra `R → S`, a submonoid `R` of `M`, and a localization `Rₘ` for `M`, let `Sₘ` be the localization of `S` to the image of `M` under `algebra_map R S`. Then this is the natural algebra structure on `Rₘ → Sₘ`, such that the entire square commutes, where `localization_map.map_comp` gives the commutativity of the underlying maps -/ noncomputable def localization_algebra : algebra Rₘ Sₘ := (map Sₘ (algebra_map R S) (show _ ≤ (algebra.algebra_map_submonoid S M).comap _, from M.le_comap_map) : Rₘ →+* Sₘ).to_algebra end lemma algebra_map_mk' (r : R) (m : M) : (@algebra_map Rₘ Sₘ _ _ (localization_algebra M S)) (mk' Rₘ r m) = mk' Sₘ (algebra_map R S r) ⟨algebra_map R S m, algebra.mem_algebra_map_submonoid_of_mem m⟩ := map_mk' _ _ _ variables (Rₘ Sₘ) /-- Injectivity of the underlying `algebra_map` descends to the algebra induced by localization. -/ lemma localization_algebra_injective (hRS : function.injective (algebra_map R S)) : function.injective (@algebra_map Rₘ Sₘ _ _ (localization_algebra M S)) := is_localization.map_injective_of_injective M Rₘ Sₘ hRS end algebra end comm_ring
2d21f57ddca10a78cfab7a67ff131f4a254141a8
f3849be5d845a1cb97680f0bbbe03b85518312f0
/library/tools/super/prover.lean
a015871df4e782246f7f54b9ce4213598a536197
[ "Apache-2.0" ]
permissive
bjoeris/lean
0ed95125d762b17bfcb54dad1f9721f953f92eeb
4e496b78d5e73545fa4f9a807155113d8e6b0561
refs/heads/master
1,611,251,218,281
1,495,337,658,000
1,495,337,658,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,675
lean
/- Copyright (c) 2016 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ import .clause .prover_state import .misc_preprocessing import .selection import .trim -- default inferences -- 0 import .clausifier -- 10 import .demod import .inhabited import .datatypes -- 20 import .subsumption -- 30 import .splitting -- 40 import .factoring import .resolution import .superposition import .equality import .simp import .defs open monad tactic expr declare_trace super namespace super meta def trace_clauses : prover unit := do state ← state_t.read, trace state meta def run_prover_loop (literal_selection : selection_strategy) (clause_selection : clause_selection_strategy) (preprocessing_rules : list (prover unit)) (inference_rules : list inference) : ℕ → prover (option expr) | i := do sequence' preprocessing_rules, new ← take_newly_derived, for' new register_as_passive, when (is_trace_enabled_for `super) $ for' new $ λn, tactic.trace { n with c := { (n.c) with proof := const (mk_simple_name "derived") [] } }, needs_sat_run ← flip monad.lift state_t.read (λst, st.needs_sat_run), if needs_sat_run then do res ← do_sat_run, match res with | some proof := return (some proof) | none := do model ← flip monad.lift state_t.read (λst, st.current_model), when (is_trace_enabled_for `super) (do pp_model ← pp (model.to_list.map (λlit, if lit.2 = tt then lit.1 else `(not %%lit.1))), trace $ to_fmt "sat model: " ++ pp_model), run_prover_loop i end else do passive ← get_passive, if rb_map.size passive = 0 then return none else do given_name ← clause_selection i, given ← option.to_monad (rb_map.find passive given_name), -- trace_clauses, remove_passive given_name, given ← literal_selection given, when (is_trace_enabled_for `super) (do fmt ← pp given, trace (to_fmt "given: " ++ fmt)), add_active given, seq_inferences inference_rules given, run_prover_loop (i+1) meta def default_preprocessing : list (prover unit) := [ clausify_pre, clause_normalize_pre, factor_dup_lits_pre, remove_duplicates_pre, refl_r_pre, diff_constr_eq_l_pre, tautology_removal_pre, subsumption_interreduction_pre, forward_subsumption_pre, return () ] end super open super meta def super (sos_lemmas : list expr) : tactic unit := with_trim $ do as_refutation, local_false ← target, clauses ← clauses_of_context, sos_clauses ← monad.for sos_lemmas (clause.of_proof local_false), initial_state ← prover_state.initial local_false (clauses ++ sos_clauses), inf_names ← attribute.get_instances `super.inf, infs ← for inf_names $ λn, eval_expr inf_decl (const n []), infs ← return $ list.map inf_decl.inf $ list.sort_on inf_decl.prio infs, res ← run_prover_loop selection21 (age_weight_clause_selection 3 4) default_preprocessing infs 0 initial_state, match res with | (some empty_clause, st) := apply empty_clause | (none, saturation) := do sat_fmt ← pp saturation, fail $ to_fmt "saturation:" ++ format.line ++ sat_fmt end namespace tactic.interactive open lean.parser open interactive open interactive.types meta def with_lemmas (ls : parse $ many ident) : tactic unit := monad.for' ls $ λl, do p ← mk_const l, t ← infer_type p, n ← get_unused_name p.get_app_fn.const_name none, tactic.assertv n t p meta def super (extra_clause_names : parse $ many ident) (extra_lemma_names : parse with_ident_list) : tactic unit := do with_lemmas extra_clause_names, extra_lemmas ← monad.for extra_lemma_names mk_const, _root_.super extra_lemmas end tactic.interactive
e9fbd425516d3cd27826f21ccaefa9a9692a5c62
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/run/tc_inout1.lean
b74616b3ed620cc37c2fcc58825ade3ae0a3968c
[ "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
2,147
lean
universe variables u v /- Type class parameter can be annotated with out_param. Given (C a_1 ... a_n), we replace a_i with a temporary metavariable ?m_i IF 1- a_i is an out_param and it contains metavariables. 3- a_i depends on a_j for j < i, and a_j was replaced with a temporary metavariable ?m_j. This case is needed to make sure the new C-application is type correct. Then, we execute type class resolution as usual. If it succeeds, and metavariables ?m_i have been assigned, we solve the unification constraints ?m_i =?= a_i. If we succeed, we return the result. Otherwise, we fail. We also fail if ?m_i is not assigned. Remark: we do not cache results when temporary metavariables ?m_i are used. -/ class is_monoid (α : Type) (op : out_param (α → α → α)) (e : out_param α) := (op_assoc : associative op) (left_neutral : ∀ a : α, op e a = a) (right_neutral : ∀ a : α, op a e = a) lemma assoc {α : Type} {op : α → α → α} {e : α} [is_monoid α op e] : ∀ a b c : α, op (op a b) c = op a (op b c) := @is_monoid.op_assoc α op e _ instance nat_add_monoid : is_monoid nat nat.add 0 := sorry instance nat_mul_monoid : is_monoid nat nat.mul 1 := sorry instance int_mul_monoid : is_monoid int int.mul 1 := sorry open tactic run_command do M ← to_expr `(is_monoid nat), m₁ ← mk_mvar, m₂ ← mk_mvar, i ← mk_instance (M m₁ m₂), /- found nat_mul_monoid -/ trace i, instantiate_mvars (M m₁ m₂) >>= trace run_command do M ← to_expr `(is_monoid nat nat.add), m₁ ← mk_mvar, i ← mk_instance (M m₁), /- found nat_add_monoid -/ trace i, instantiate_mvars (M m₁) >>= trace section local infix + := nat.add example (a b c : nat) : (a + b) + c = a + (b + c) := assoc a b c end section class has_mem2 (α : out_param (Type u)) (γ : Type v) := (mem : α → γ → Prop) def mem2 {α : Type u} {γ : Type v} [has_mem2 α γ] : α → γ → Prop := has_mem2.mem local infix ∈ := mem2 instance (α : Type u) : has_mem2 α (list α) := ⟨list.mem⟩ check λ a (s : list nat), a ∈ s set_option pp.notation false check ∀ a ∈ [1, 2, 3], a > 0 end
aeacd1b25ac28bc161155a7bd68eb6cb247533b1
82e44445c70db0f03e30d7be725775f122d72f3e
/src/algebra/lie/cartan_matrix.lean
7d9ddfa3a879ec8cf4aef2598ff62bb353f68087
[ "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
9,571
lean
/- Copyright (c) 2021 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import algebra.lie.free import algebra.lie.quotient import data.matrix.notation /-! # Lie algebras from Cartan matrices Split semi-simple Lie algebras are uniquely determined by their Cartan matrix. Indeed, if `A` is an `l × l` Cartan matrix, the corresponding Lie algebra may be obtained as the Lie algebra on `3l` generators: $H_1, H_2, \ldots H_l, E_1, E_2, \ldots, E_l, F_1, F_2, \ldots, F_l$ subject to the following relations: $$ \begin{align} [H_i, H_j] &= 0\\ [E_i, F_i] &= H_i\\ [E_i, F_j] &= 0 \quad\text{if $i \ne j$}\\ [H_i, E_j] &= A_{ij}E_j\\ [H_i, F_j] &= -A_{ij}F_j\\ ad(E_i)^{1 - A_{ij}}(E_j) &= 0 \quad\text{if $i \ne j$}\\ ad(F_i)^{1 - A_{ij}}(F_j) &= 0 \quad\text{if $i \ne j$}\\ \end{align} $$ In this file we provide the above construction. It is defined for any square matrix of integers but the results for non-Cartan matrices should be regarded as junk. Recall that a Cartan matrix is a square matrix of integers `A` such that: * For diagonal values we have: `A i i = 2`. * For off-diagonal values (`i ≠ j`) we have: `A i j ∈ {-3, -2, -1, 0}`. * `A i j = 0 ↔ A j i = 0`. * There exists a diagonal matrix `D` over ℝ such that `D ⬝ A ⬝ D⁻¹` is symmetric positive definite. ## Alternative construction This construction is sometimes performed within the free unital associative algebra `free_algebra R X`, rather than within the free Lie algebra `free_lie_algebra R X`, as we do here. However the difference is illusory since the construction stays inside the Lie subalgebra of `free_algebra R X` generated by `X`, and this is naturally isomorphic to `free_lie_algebra R X` (though the proof of this seems to require Poincaré–Birkhoff–Witt). ## Definitions of exceptional Lie algebras This file also contains the Cartan matrices of the exceptional Lie algebras. By using these in the above construction, it thus provides definitions of the exceptional Lie algebras. These definitions make sense over any commutative ring. When the ring is ℝ, these are the split real forms of the exceptional semisimple Lie algebras. ## References * [N. Bourbaki, *Lie Groups and Lie Algebras, Chapters 4--6*](bourbaki1968) plates V -- IX, pages 275--290 * [N. Bourbaki, *Lie Groups and Lie Algebras, Chapters 7--9*](bourbaki1975b) chapter VIII, §4.3 * [J.P. Serre, *Complex Semisimple Lie Algebras*](serre1965) chapter VI, appendix ## Main definitions * `matrix.to_lie_algebra` * `cartan_matrix.E₆` * `cartan_matrix.E₇` * `cartan_matrix.E₈` * `cartan_matrix.F₄` * `cartan_matrix.G₂` * `lie_algebra.e₆` * `lie_algebra.e₇` * `lie_algebra.e₈` * `lie_algebra.f₄` * `lie_algebra.g₂` ## Tags lie algebra, semi-simple, cartan matrix -/ universes u v w noncomputable theory variables (R : Type u) {B : Type v} [comm_ring R] [decidable_eq B] [fintype B] variables (A : matrix B B ℤ) namespace cartan_matrix variables (B) /-- The generators of the free Lie algebra from which we construct the Lie algebra of a Cartan matrix as a quotient. -/ inductive generators | H : B → generators | E : B → generators | F : B → generators instance [inhabited B] : inhabited (generators B) := ⟨generators.H $ default B⟩ variables {B} namespace relations open function local notation `H` := free_lie_algebra.of R ∘ generators.H local notation `E` := free_lie_algebra.of R ∘ generators.E local notation `F` := free_lie_algebra.of R ∘ generators.F local notation `ad` := lie_algebra.ad R (free_lie_algebra R (generators B)) /-- The terms correpsonding to the `⁅H, H⁆`-relations. -/ def HH : B × B → free_lie_algebra R (generators B) := uncurry $ λ i j, ⁅H i, H j⁆ /-- The terms correpsonding to the `⁅E, F⁆`-relations. -/ def EF : B × B → free_lie_algebra R (generators B) := uncurry $ λ i j, if i = j then ⁅E i, F i⁆ - H i else ⁅E i, F j⁆ /-- The terms correpsonding to the `⁅H, E⁆`-relations. -/ def HE : B × B → free_lie_algebra R (generators B) := uncurry $ λ i j, ⁅H i, E j⁆ - (A i j) • E j /-- The terms correpsonding to the `⁅H, F⁆`-relations. -/ def HF : B × B → free_lie_algebra R (generators B) := uncurry $ λ i j, ⁅H i, F j⁆ + (A i j) • F j /-- The terms correpsonding to the `ad E`-relations. Note that we use `int.to_nat` so that we can take the power and that we do not bother restricting to the case `i ≠ j` since these relations are zero anyway. We also defensively ensure this with `ad_E_of_eq_eq_zero`. -/ def ad_E : B × B → free_lie_algebra R (generators B) := uncurry $ λ i j, (ad (E i))^(-A i j).to_nat $ ⁅E i, E j⁆ /-- The terms correpsonding to the `ad F`-relations. See also `ad_E` docstring. -/ def ad_F : B × B → free_lie_algebra R (generators B) := uncurry $ λ i j, (ad (F i))^(-A i j).to_nat $ ⁅F i, F j⁆ private lemma ad_E_of_eq_eq_zero (i : B) (h : A i i = 2) : ad_E R A ⟨i, i⟩ = 0 := have h' : (-2 : ℤ).to_nat = 0, { refl, }, by simp [ad_E, h, h'] private lemma ad_F_of_eq_eq_zero (i : B) (h : A i i = 2) : ad_F R A ⟨i, i⟩ = 0 := have h' : (-2 : ℤ).to_nat = 0, { refl, }, by simp [ad_F, h, h'] /-- The union of all the relations as a subset of the free Lie algebra. -/ def to_set : set (free_lie_algebra R (generators B)) := (set.range $ HH R) ∪ (set.range $ EF R) ∪ (set.range $ HE R A) ∪ (set.range $ HF R A) ∪ (set.range $ ad_E R A) ∪ (set.range $ ad_F R A) /-- The ideal of the free Lie algebra generated by the relations. -/ def to_ideal : lie_ideal R (free_lie_algebra R (generators B)) := lie_submodule.lie_span R _ $ to_set R A end relations end cartan_matrix /-- The Lie algebra corresponding to a Cartan matrix. Note that it is defined for any matrix of integers. Its value for non-Cartan matrices should be regarded as junk. -/ @[derive [inhabited, lie_ring, lie_algebra R]] def matrix.to_lie_algebra := (cartan_matrix.relations.to_ideal R A).quotient namespace cartan_matrix /-- The Cartan matrix of type e₆. See [bourbaki1968] plate V, page 277. The corresponding Dynkin diagram is: ``` o | o --- o --- o --- o --- o ``` -/ def E₆ : matrix (fin 6) (fin 6) ℤ := ![![ 2, 0, -1, 0, 0, 0], ![ 0, 2, 0, -1, 0, 0], ![-1, 0, 2, -1, 0, 0], ![ 0, -1, -1, 2, -1, 0], ![ 0, 0, 0, -1, 2, -1], ![ 0, 0, 0, 0, -1, 2]] /-- The Cartan matrix of type e₇. See [bourbaki1968] plate VI, page 281. The corresponding Dynkin diagram is: ``` o | o --- o --- o --- o --- o --- o ``` -/ def E₇ : matrix (fin 7) (fin 7) ℤ := ![![ 2, 0, -1, 0, 0, 0, 0], ![ 0, 2, 0, -1, 0, 0, 0], ![-1, 0, 2, -1, 0, 0, 0], ![ 0, -1, -1, 2, -1, 0, 0], ![ 0, 0, 0, -1, 2, -1, 0], ![ 0, 0, 0, 0, -1, 2, -1], ![ 0, 0, 0, 0, 0, -1, 2]] /-- The Cartan matrix of type e₈. See [bourbaki1968] plate VII, page 285. The corresponding Dynkin diagram is: ``` o | o --- o --- o --- o --- o --- o --- o ``` -/ def E₈ : matrix (fin 8) (fin 8) ℤ := ![![ 2, 0, -1, 0, 0, 0, 0, 0], ![ 0, 2, 0, -1, 0, 0, 0, 0], ![-1, 0, 2, -1, 0, 0, 0, 0], ![ 0, -1, -1, 2, -1, 0, 0, 0], ![ 0, 0, 0, -1, 2, -1, 0, 0], ![ 0, 0, 0, 0, -1, 2, -1, 0], ![ 0, 0, 0, 0, 0, -1, 2, -1], ![ 0, 0, 0, 0, 0, 0, -1, 2]] /-- The Cartan matrix of type f₄. See [bourbaki1968] plate VIII, page 288. The corresponding Dynkin diagram is: ``` o --- o =>= o --- o ``` -/ def F₄ : matrix (fin 4) (fin 4) ℤ := ![![ 2, -1, 0, 0], ![-1, 2, -2, 0], ![ 0, -1, 2, -1], ![ 0, 0, -1, 2]] /-- The Cartan matrix of type g₂. See [bourbaki1968] plate IX, page 290. The corresponding Dynkin diagram is: ``` o ≡>≡ o ``` Actually we are using the transpose of Bourbaki's matrix. This is to make this matrix consistent with `cartan_matrix.F₄`, in the sense that all non-zero values below the diagonal are -1. -/ def G₂ : matrix (fin 2) (fin 2) ℤ := ![![ 2, -3], ![-1, 2]] end cartan_matrix namespace lie_algebra /-- The exceptional split Lie algebra of type e₆. -/ abbreviation e₆ := cartan_matrix.E₆.to_lie_algebra R /-- The exceptional split Lie algebra of type e₇. -/ abbreviation e₇ := cartan_matrix.E₇.to_lie_algebra R /-- The exceptional split Lie algebra of type e₈. -/ abbreviation e₈ := cartan_matrix.E₈.to_lie_algebra R /-- The exceptional split Lie algebra of type f₄. -/ abbreviation f₄ := cartan_matrix.F₄.to_lie_algebra R /-- The exceptional split Lie algebra of type g₂. -/ abbreviation g₂ := cartan_matrix.G₂.to_lie_algebra R end lie_algebra
fed0b1cdce533871b748252fa16053b66c455490
6fca17f8d5025f89be1b2d9d15c9e0c4b4900cbf
/src/game/world7/level1.lean
c57d211a0f1a7b95db41cf53843639e57711826c
[ "Apache-2.0" ]
permissive
arolihas/natural_number_game
4f0c93feefec93b8824b2b96adff8b702b8b43ce
8e4f7b4b42888a3b77429f90cce16292bd288138
refs/heads/master
1,621,872,426,808
1,586,270,467,000
1,586,270,467,000
253,648,466
0
0
null
1,586,219,694,000
1,586,219,694,000
null
UTF-8
Lean
false
false
1,580
lean
-- World name : Advanced Proposition world /- # Advanced proposition world. In this world we will learn five key tactics needed to solve all the levels of the Natural Number Game, namely `split`, `cases`, `left`, `right`, and `exfalso`. These, and `use` (which we'll get to in Inequality World) are all the tactics you will need to beat all the levels of the game. ## Level 1: the `split` tactic. The logical symbol `∧` means "and". If $P$ and $Q$ are propositions, then $P\land Q$ is the proposition "$P$ and $Q$". If your *goal* is `P ∧ Q` then you can make progress with the `split` tactic, which turns one goal `⊢ P ∧ Q` into two goals, namely `⊢ P` and `⊢ Q`. In the level below, after a `split`, you will be able to finish off the goals with the `exact` tactic. -/ /- Lemma : no-side-bar If $P$ and $Q$ are true, then $P\land Q$ is true. -/ example (P Q : Prop) (p : P) (q : Q) : P ∧ Q := begin end /- Tactic : split ## Summary: If the goal is `P ∧ Q` or `P ↔ Q` then `split` will break it into two goals. ## Details If `P Q : Prop` and the goal is `⊢ P ∧ Q`, then `split` will change it into two goals, namely `⊢ P` and `⊢ Q`. If `P Q : Prop` and the goal is `⊢ P ↔ Q`, then `split` will change it into two goals, namely `⊢ P → Q` and `⊢ Q → P`. ## Example: If your local context (the top right window) looks like this ``` a b : mynat, ⊢ a = b ↔ a + 3 = b + 3 ``` then after `split,` it will look like this: ``` 2 goals a b : mynat ⊢ a = b → a + 3 = b + 3 a b : mynat ⊢ a + 3 = b + 3 → a = b -/
d2664c7c50a6d9a730ffb3dc62dfc91d132df3ea
df7bb3acd9623e489e95e85d0bc55590ab0bc393
/lean/love10_denotational_semantics_homework_sheet.lean
5c87a2b37b422a18b0744baec9a0daed6f840e9e
[]
no_license
MaschavanderMarel/logical_verification_2020
a41c210b9237c56cb35f6cd399e3ac2fe42e775d
7d562ef174cc6578ca6013f74db336480470b708
refs/heads/master
1,692,144,223,196
1,634,661,675,000
1,634,661,675,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,821
lean
import .love10_denotational_semantics_demo /- # LoVe Homework 10: Denotational Semantics Homework must be done individually. -/ set_option pp.beta true set_option pp.generalized_field_notation false namespace LoVe /- ## Question 1 (7 points): Denotational Semantics of DOWHILE -/ namespace do_while /- Consider the following DOWHILE language: -/ inductive stmt : Type | skip : stmt | assign : string → (state → ℕ) → stmt | seq : stmt → stmt → stmt | unless : stmt → (state → Prop) → stmt | while : (state → Prop) → stmt → stmt | do_while : stmt → (state → Prop) → stmt infixr ` ;; ` : 90 := stmt.seq /- The `skip`, `assign`, `seq`, and `while constructs are as for the WHILE language. `unless S b` executes `S` if `b` is false in the current state; otherwise, it does nothing. This statement is inspired by Perl's `unless` conditional. `do_while S b` first executes `S`. Then, if `b` is true in the resulting state, it re-enters the loop and executes `S` again, and continues executing `S` until `b` becomes `false`. The semantics is almost the same as `while b S`, except that `p` is always executed at least once, even if the condition is not true initially. This statement is inspired by C's and Java's `do { … } while (…)` loop. 1.1 (2 points). Give a denotational semantics of DOWHILE. Hint: Your definition should make it easy to prove lemma `do_while_while` in question 1.2. -/ def denote : stmt → set (state × state) | stmt.skip := Id -- enter the missing cases here notation `⟦` S `⟧`:= denote S /- 1.2 (1 point). Prove the following correspondence between `do_while` and `while`. -/ lemma do_while_while (S : stmt) (b : state → Prop) : ⟦stmt.do_while S b⟧ = ⟦S⟧ ◯ ⟦stmt.while b S⟧ := sorry /- 1.3 (4 points). Prove the following lemmas. Hint: For all of these, short proofs are possible. -/ lemma lfp_const {α : Type} [complete_lattice α] (a : α) : lfp (λX, a) = a := sorry lemma while_false (S : stmt) : ⟦stmt.while (λ_, false) S⟧ = Id := sorry lemma comp_Id {α : Type} (r : set (α × α)) : r ◯ Id = r := sorry lemma do_while_false (S : stmt) : ⟦stmt.do_while S (λ_, false)⟧ = ⟦S⟧ := sorry end do_while /- ## Question 2 (2 points + 2 bonus points): Kleene's Theorem We can compute the fixpoint by iteration by taking the union of all finite iterations of `f`: `lfp f = ⋃i, (f ^^ i) ∅` where `f ^^ i = f ∘ ⋯ ∘ f` iterates the function `f` `i` times. However, the above characterization of `lfp` only holds for continuous functions, a concept we will introduce below. -/ def iterate {α : Type} (f : α → α) : ℕ → α → α | 0 a := a | (n + 1) a := f (iterate n a) notation f`^^`n := iterate f n /- 2.1 (2 points). Fill in the missing proofs below. -/ def Union {α : Type} (s : ℕ → set α) : set α := {a | ∃n, a ∈ s n} lemma Union_le {α : Type} {s : ℕ → set α} (A : set α) (h : ∀i, s i ≤ A) : Union s ≤ A := sorry /- A continuous function `f` is a function that commutes with the union of any monotone sequence `s`: -/ def continuous {α : Type} (f : set α → set α) : Prop := ∀s : ℕ → set α, monotone s → f (Union s) = Union (λi, f (s i)) /- We need to prove that each continuous function is monotone. To achieve this, we will need the following sequence: -/ def bi_seq {α : Type} (A B : set α) : ℕ → set α | 0 := A | (n + 1) := B /- For example, `bi_seq A B` is the sequence A, B, B, B, …. -/ lemma monotone_bi_seq {α : Type} (A B : set α) (h : A ≤ B) : monotone (bi_seq A B) | 0 0 _ := le_refl _ | 0 (n + 1) _ := h | (n + 1) (m + 1) _ := le_refl _ lemma Union_bi_seq {α : Type} (A B : set α) (ha : A ≤ B) : Union (bi_seq A B) = B := begin apply le_antisymm, { sorry }, { sorry } end lemma monotone_of_continuous {α : Type} (f : set α → set α) (hf : continuous f) : monotone f := sorry /- 2.2 (1 bonus point). Provide the following proof, using a similar case distinction as for `monotone_bi_seq` above. -/ lemma monotone_iterate {α : Type} (f : set α → set α) (hf : monotone f) : monotone (λi, (f ^^ i) ∅) := sorry /- 2.3 (1 bonus point). Prove the main theorem. A proof sketch is given below. We break the proof into two proofs of inclusion. Case 1. `lfp f ≤ Union (λi, (f ^^ i) ∅)`: The key is to use the lemma `lfp_le` together with continuity of `f`. Case 2. `Union (λi, (f ^^ i) ∅) ≤ lfp f`: The lemma `Union_le` gives us a natural number `i`, on which you can perform induction. We also need the lemma `lfp_eq` to unfold one iteration of `lfp f`. -/ lemma lfp_Kleene {α : Type} (f : set α → set α) (hf : continuous f) : lfp f = Union (λi, (f ^^ i) ∅) := sorry end LoVe
ace831aa7a15cfdf2cbfd74d303439d7d49a707b
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/multiset/powerset.lean
b9a2e6a6d12dba58eef70a887799b5efe12c86cf
[ "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
9,959
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.multiset.basic /-! # The powerset of a multiset -/ namespace multiset open list variables {α : Type*} /-! ### powerset -/ /-- A helper function for the powerset of a multiset. Given a list `l`, returns a list of sublists of `l` (using `sublists_aux`), as multisets. -/ def powerset_aux (l : list α) : list (multiset α) := 0 :: sublists_aux l (λ x y, x :: y) theorem powerset_aux_eq_map_coe {l : list α} : powerset_aux l = (sublists l).map coe := by simp [powerset_aux, sublists]; rw [← show @sublists_aux₁ α (multiset α) l (λ x, [↑x]) = sublists_aux l (λ x, list.cons ↑x), from sublists_aux₁_eq_sublists_aux _ _, sublists_aux_cons_eq_sublists_aux₁, ← bind_ret_eq_map, sublists_aux₁_bind]; refl @[simp] theorem mem_powerset_aux {l : list α} {s} : s ∈ powerset_aux l ↔ s ≤ ↑l := quotient.induction_on s $ by simp [powerset_aux_eq_map_coe, subperm, and.comm] /-- Helper function for the powerset of a multiset. Given a list `l`, returns a list of sublists of `l` (using `sublists'`), as multisets. -/ def powerset_aux' (l : list α) : list (multiset α) := (sublists' l).map coe theorem powerset_aux_perm_powerset_aux' {l : list α} : powerset_aux l ~ powerset_aux' l := by rw powerset_aux_eq_map_coe; exact (sublists_perm_sublists' _).map _ @[simp] theorem powerset_aux'_nil : powerset_aux' (@nil α) = [0] := rfl @[simp] theorem powerset_aux'_cons (a : α) (l : list α) : powerset_aux' (a::l) = powerset_aux' l ++ list.map (cons a) (powerset_aux' l) := by simp [powerset_aux']; refl theorem powerset_aux'_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) : powerset_aux' l₁ ~ powerset_aux' l₂ := begin induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp}, { simp, exact IH.append (IH.map _) }, { simp, apply perm.append_left, rw [← append_assoc, ← append_assoc, (by funext s; simp [cons_swap] : cons b ∘ cons a = cons a ∘ cons b)], exact perm_append_comm.append_right _ }, { exact IH₁.trans IH₂ } end theorem powerset_aux_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) : powerset_aux l₁ ~ powerset_aux l₂ := powerset_aux_perm_powerset_aux'.trans $ (powerset_aux'_perm p).trans powerset_aux_perm_powerset_aux'.symm /-- The power set of a multiset. -/ def powerset (s : multiset α) : multiset (multiset α) := quot.lift_on s (λ l, (powerset_aux l : multiset (multiset α))) (λ l₁ l₂ h, quot.sound (powerset_aux_perm h)) theorem powerset_coe (l : list α) : @powerset α l = ((sublists l).map coe : list (multiset α)) := congr_arg coe powerset_aux_eq_map_coe @[simp] theorem powerset_coe' (l : list α) : @powerset α l = ((sublists' l).map coe : list (multiset α)) := quot.sound powerset_aux_perm_powerset_aux' @[simp] theorem powerset_zero : @powerset α 0 = {0} := rfl @[simp] theorem powerset_cons (a : α) (s) : powerset (a ::ₘ s) = powerset s + map (cons a) (powerset s) := quotient.induction_on s $ λ l, by simp; refl @[simp] theorem mem_powerset {s t : multiset α} : s ∈ powerset t ↔ s ≤ t := quotient.induction_on₂ s t $ by simp [subperm, and.comm] theorem map_single_le_powerset (s : multiset α) : s.map singleton ≤ powerset s := quotient.induction_on s $ λ l, begin simp only [powerset_coe, quot_mk_to_coe, coe_le, coe_map], show l.map (coe ∘ list.ret) <+~ (sublists l).map coe, rw ← list.map_map, exact ((map_ret_sublist_sublists _).map _).subperm end @[simp] theorem card_powerset (s : multiset α) : card (powerset s) = 2 ^ card s := quotient.induction_on s $ by simp theorem revzip_powerset_aux {l : list α} ⦃x⦄ (h : x ∈ revzip (powerset_aux l)) : x.1 + x.2 = ↑l := begin rw [revzip, powerset_aux_eq_map_coe, ← map_reverse, zip_map, ← revzip] at h, simp at h, rcases h with ⟨l₁, l₂, h, rfl, rfl⟩, exact quot.sound (revzip_sublists _ _ _ h) end theorem revzip_powerset_aux' {l : list α} ⦃x⦄ (h : x ∈ revzip (powerset_aux' l)) : x.1 + x.2 = ↑l := begin rw [revzip, powerset_aux', ← map_reverse, zip_map, ← revzip] at h, simp at h, rcases h with ⟨l₁, l₂, h, rfl, rfl⟩, exact quot.sound (revzip_sublists' _ _ _ h) end theorem revzip_powerset_aux_lemma [decidable_eq α] (l : list α) {l' : list (multiset α)} (H : ∀ ⦃x : _ × _⦄, x ∈ revzip l' → x.1 + x.2 = ↑l) : revzip l' = l'.map (λ x, (x, ↑l - x)) := begin have : forall₂ (λ (p : multiset α × multiset α) (s : multiset α), p = (s, ↑l - s)) (revzip l') ((revzip l').map prod.fst), { rw forall₂_map_right_iff, apply forall₂_same, rintro ⟨s, t⟩ h, dsimp, rw [← H h, add_tsub_cancel_left] }, rw [← forall₂_eq_eq_eq, forall₂_map_right_iff], simpa end theorem revzip_powerset_aux_perm_aux' {l : list α} : revzip (powerset_aux l) ~ revzip (powerset_aux' l) := begin haveI := classical.dec_eq α, rw [revzip_powerset_aux_lemma l revzip_powerset_aux, revzip_powerset_aux_lemma l revzip_powerset_aux'], exact powerset_aux_perm_powerset_aux'.map _ end theorem revzip_powerset_aux_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) : revzip (powerset_aux l₁) ~ revzip (powerset_aux l₂) := begin haveI := classical.dec_eq α, simp [λ l:list α, revzip_powerset_aux_lemma l revzip_powerset_aux, coe_eq_coe.2 p], exact (powerset_aux_perm p).map _ end /-! ### powerset_len -/ /-- Helper function for `powerset_len`. Given a list `l`, `powerset_len_aux n l` is the list of sublists of length `n`, as multisets. -/ def powerset_len_aux (n : ℕ) (l : list α) : list (multiset α) := sublists_len_aux n l coe [] theorem powerset_len_aux_eq_map_coe {n} {l : list α} : powerset_len_aux n l = (sublists_len n l).map coe := by rw [powerset_len_aux, sublists_len_aux_eq, append_nil] @[simp] theorem mem_powerset_len_aux {n} {l : list α} {s} : s ∈ powerset_len_aux n l ↔ s ≤ ↑l ∧ card s = n := quotient.induction_on s $ by simp [powerset_len_aux_eq_map_coe, subperm]; exact λ l₁, ⟨λ ⟨l₂, ⟨s, e⟩, p⟩, ⟨⟨_, p, s⟩, p.symm.length_eq.trans e⟩, λ ⟨⟨l₂, p, s⟩, e⟩, ⟨_, ⟨s, p.length_eq.trans e⟩, p⟩⟩ @[simp] theorem powerset_len_aux_zero (l : list α) : powerset_len_aux 0 l = [0] := by simp [powerset_len_aux_eq_map_coe] @[simp] theorem powerset_len_aux_nil (n : ℕ) : powerset_len_aux (n+1) (@nil α) = [] := rfl @[simp] theorem powerset_len_aux_cons (n : ℕ) (a : α) (l : list α) : powerset_len_aux (n+1) (a::l) = powerset_len_aux (n+1) l ++ list.map (cons a) (powerset_len_aux n l) := by simp [powerset_len_aux_eq_map_coe]; refl theorem powerset_len_aux_perm {n} {l₁ l₂ : list α} (p : l₁ ~ l₂) : powerset_len_aux n l₁ ~ powerset_len_aux n l₂ := begin induction n with n IHn generalizing l₁ l₂, {simp}, induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {refl}, { simp, exact IH.append ((IHn p).map _) }, { simp, apply perm.append_left, cases n, {simp, apply perm.swap}, simp, rw [← append_assoc, ← append_assoc, (by funext s; simp [cons_swap] : cons b ∘ cons a = cons a ∘ cons b)], exact perm_append_comm.append_right _ }, { exact IH₁.trans IH₂ } end /-- `powerset_len n s` is the multiset of all submultisets of `s` of length `n`. -/ def powerset_len (n : ℕ) (s : multiset α) : multiset (multiset α) := quot.lift_on s (λ l, (powerset_len_aux n l : multiset (multiset α))) (λ l₁ l₂ h, quot.sound (powerset_len_aux_perm h)) theorem powerset_len_coe' (n) (l : list α) : @powerset_len α n l = powerset_len_aux n l := rfl theorem powerset_len_coe (n) (l : list α) : @powerset_len α n l = ((sublists_len n l).map coe : list (multiset α)) := congr_arg coe powerset_len_aux_eq_map_coe @[simp] theorem powerset_len_zero_left (s : multiset α) : powerset_len 0 s = {0} := quotient.induction_on s $ λ l, by simp [powerset_len_coe']; refl theorem powerset_len_zero_right (n : ℕ) : @powerset_len α (n + 1) 0 = 0 := rfl @[simp] theorem powerset_len_cons (n : ℕ) (a : α) (s) : powerset_len (n + 1) (a ::ₘ s) = powerset_len (n + 1) s + map (cons a) (powerset_len n s) := quotient.induction_on s $ λ l, by simp [powerset_len_coe']; refl @[simp] theorem mem_powerset_len {n : ℕ} {s t : multiset α} : s ∈ powerset_len n t ↔ s ≤ t ∧ card s = n := quotient.induction_on t $ λ l, by simp [powerset_len_coe'] @[simp] theorem card_powerset_len (n : ℕ) (s : multiset α) : card (powerset_len n s) = nat.choose (card s) n := quotient.induction_on s $ by simp [powerset_len_coe] theorem powerset_len_le_powerset (n : ℕ) (s : multiset α) : powerset_len n s ≤ powerset s := quotient.induction_on s $ λ l, by simp [powerset_len_coe]; exact ((sublists_len_sublist_sublists' _ _).map _).subperm theorem powerset_len_mono (n : ℕ) {s t : multiset α} (h : s ≤ t) : powerset_len n s ≤ powerset_len n t := le_induction_on h $ λ l₁ l₂ h, by simp [powerset_len_coe]; exact ((sublists_len_sublist_of_sublist _ h).map _).subperm @[simp] theorem powerset_len_empty {α : Type*} (n : ℕ) {s : multiset α} (h : s.card < n) : powerset_len n s = 0 := card_eq_zero.mp (nat.choose_eq_zero_of_lt h ▸ card_powerset_len _ _) @[simp] lemma powerset_len_card_add (s : multiset α) {i : ℕ} (hi : 0 < i) : s.powerset_len (s.card + i) = 0 := powerset_len_empty _ (lt_add_of_pos_right (card s) hi) theorem powerset_len_map {β : Type*} (f : α → β) (n : ℕ) (s : multiset α) : powerset_len n (s.map f) = (powerset_len n s).map (map f) := begin induction s using multiset.induction with t s ih generalizing n, { cases n; simp [powerset_len_zero_left, powerset_len_zero_right], }, { cases n; simp [ih, map_comp_cons], }, end end multiset
a077005f32b1aaf0f417451b43fcb2ee85b7c72b
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/category_theory/comma.lean
97e7e3a113c9609c7dc1a65cdb0362f210e4cb66
[ "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
8,512
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Johan Commelin, Bhavik Mehta -/ import category_theory.natural_isomorphism /-! # Comma categories A comma category is a construction in category theory, which builds a category out of two functors with a common codomain. Specifically, for functors `L : A ⥤ T` and `R : B ⥤ T`, an object in `comma L R` is a morphism `hom : L.obj left ⟶ R.obj right` for some objects `left : A` and `right : B`, and a morphism in `comma L R` between `hom : L.obj left ⟶ R.obj right` and `hom' : L.obj left' ⟶ R.obj right'` is a commutative square ``` L.obj left ⟶ L.obj left' | | hom | | hom' ↓ ↓ R.obj right ⟶ R.obj right', ``` where the top and bottom morphism come from morphisms `left ⟶ left'` and `right ⟶ right'`, respectively. ## Main definitions * `comma L R`: the comma category of the functors `L` and `R`. * `over X`: the over category of the object `X` (developed in `over.lean`). * `under X`: the under category of the object `X` (also developed in `over.lean`). * `arrow T`: the arrow category of the category `T` (developed in `arrow.lean`). ## References * <https://ncatlab.org/nlab/show/comma+category> ## Tags comma, slice, coslice, over, under, arrow -/ namespace category_theory -- declare the `v`'s first; see `category_theory.category` for an explanation universes v₁ v₂ v₃ v₄ v₅ u₁ u₂ u₃ u₄ u₅ variables {A : Type u₁} [category.{v₁} A] variables {B : Type u₂} [category.{v₂} B] variables {T : Type u₃} [category.{v₃} T] /-- The objects of the comma category are triples of an object `left : A`, an object `right : B` and a morphism `hom : L.obj left ⟶ R.obj right`. -/ structure comma (L : A ⥤ T) (R : B ⥤ T) : Type (max u₁ u₂ v₃) := (left : A . obviously) (right : B . obviously) (hom : L.obj left ⟶ R.obj right) -- Satisfying the inhabited linter instance comma.inhabited [inhabited T] : inhabited (comma (𝟭 T) (𝟭 T)) := { default := { left := default T, right := default T, hom := 𝟙 (default T) } } variables {L : A ⥤ T} {R : B ⥤ T} /-- A morphism between two objects in the comma category is a commutative square connecting the morphisms coming from the two objects using morphisms in the image of the functors `L` and `R`. -/ @[ext] structure comma_morphism (X Y : comma L R) := (left : X.left ⟶ Y.left . obviously) (right : X.right ⟶ Y.right . obviously) (w' : L.map left ≫ Y.hom = X.hom ≫ R.map right . obviously) -- Satisfying the inhabited linter instance comma_morphism.inhabited [inhabited (comma L R)] : inhabited (comma_morphism (default (comma L R)) (default (comma L R))) := { default := { left := 𝟙 _, right := 𝟙 _ } } restate_axiom comma_morphism.w' attribute [simp, reassoc] comma_morphism.w instance comma_category : category (comma L R) := { hom := comma_morphism, id := λ X, { left := 𝟙 X.left, right := 𝟙 X.right }, comp := λ X Y Z f g, { left := f.left ≫ g.left, right := f.right ≫ g.right } } namespace comma section variables {X Y Z : comma L R} {f : X ⟶ Y} {g : Y ⟶ Z} @[simp] lemma id_left : ((𝟙 X) : comma_morphism X X).left = 𝟙 X.left := rfl @[simp] lemma id_right : ((𝟙 X) : comma_morphism X X).right = 𝟙 X.right := rfl @[simp] lemma comp_left : (f ≫ g).left = f.left ≫ g.left := rfl @[simp] lemma comp_right : (f ≫ g).right = f.right ≫ g.right := rfl end variables (L) (R) /-- The functor sending an object `X` in the comma category to `X.left`. -/ @[simps] def fst : comma L R ⥤ A := { obj := λ X, X.left, map := λ _ _ f, f.left } /-- The functor sending an object `X` in the comma category to `X.right`. -/ @[simps] def snd : comma L R ⥤ B := { obj := λ X, X.right, map := λ _ _ f, f.right } /-- We can interpret the commutative square constituting a morphism in the comma category as a natural transformation between the functors `fst ⋙ L` and `snd ⋙ R` from the comma category to `T`, where the components are given by the morphism that constitutes an object of the comma category. -/ @[simps] def nat_trans : fst L R ⋙ L ⟶ snd L R ⋙ R := { app := λ X, X.hom } section variables {L₁ L₂ L₃ : A ⥤ T} {R₁ R₂ R₃ : B ⥤ T} /-- Construct an isomorphism in the comma category given isomorphisms of the objects whose forward directions give a commutative square. -/ @[simps] def iso_mk {X Y : comma L₁ R₁} (l : X.left ≅ Y.left) (r : X.right ≅ Y.right) (h : L₁.map l.hom ≫ Y.hom = X.hom ≫ R₁.map r.hom) : X ≅ Y := { hom := { left := l.hom, right := r.hom }, inv := { left := l.inv, right := r.inv, w' := begin rw [←L₁.map_iso_inv l, iso.inv_comp_eq, L₁.map_iso_hom, reassoc_of h, ← R₁.map_comp], simp end, } } /-- A natural transformation `L₁ ⟶ L₂` induces a functor `comma L₂ R ⥤ comma L₁ R`. -/ @[simps] def map_left (l : L₁ ⟶ L₂) : comma L₂ R ⥤ comma L₁ R := { obj := λ X, { left := X.left, right := X.right, hom := l.app X.left ≫ X.hom }, map := λ X Y f, { left := f.left, right := f.right } } /-- The functor `comma L R ⥤ comma L R` induced by the identity natural transformation on `L` is naturally isomorphic to the identity functor. -/ @[simps] def map_left_id : map_left R (𝟙 L) ≅ 𝟭 _ := { hom := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } }, inv := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } } } /-- The functor `comma L₁ R ⥤ comma L₃ R` induced by the composition of two natural transformations `l : L₁ ⟶ L₂` and `l' : L₂ ⟶ L₃` is naturally isomorphic to the composition of the two functors induced by these natural transformations. -/ @[simps] def map_left_comp (l : L₁ ⟶ L₂) (l' : L₂ ⟶ L₃) : (map_left R (l ≫ l')) ≅ (map_left R l') ⋙ (map_left R l) := { hom := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } }, inv := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } } } /-- A natural transformation `R₁ ⟶ R₂` induces a functor `comma L R₁ ⥤ comma L R₂`. -/ @[simps] def map_right (r : R₁ ⟶ R₂) : comma L R₁ ⥤ comma L R₂ := { obj := λ X, { left := X.left, right := X.right, hom := X.hom ≫ r.app X.right }, map := λ X Y f, { left := f.left, right := f.right } } /-- The functor `comma L R ⥤ comma L R` induced by the identity natural transformation on `R` is naturally isomorphic to the identity functor. -/ @[simps] def map_right_id : map_right L (𝟙 R) ≅ 𝟭 _ := { hom := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } }, inv := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } } } /-- The functor `comma L R₁ ⥤ comma L R₃` induced by the composition of the natural transformations `r : R₁ ⟶ R₂` and `r' : R₂ ⟶ R₃` is naturally isomorphic to the composition of the functors induced by these natural transformations. -/ @[simps] def map_right_comp (r : R₁ ⟶ R₂) (r' : R₂ ⟶ R₃) : (map_right L (r ≫ r')) ≅ (map_right L r) ⋙ (map_right L r') := { hom := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } }, inv := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } } } end section variables {C : Type u₄} [category.{v₄} C] {D : Type u₅} [category.{v₅} D] /-- The functor `(F ⋙ L, R) ⥤ (L, R)` -/ @[simps] def pre_left (F: C ⥤ A) (L : A ⥤ T) (R : B ⥤ T) : comma (F ⋙ L) R ⥤ comma L R := { obj := λ X, { left := F.obj X.left, right := X.right, hom := X.hom }, map := λ X Y f, { left := F.map f.left, right := f.right, w' := by simpa using f.w } } /-- The functor `(F ⋙ L, R) ⥤ (L, R)` -/ @[simps] def pre_right (L : A ⥤ T) (F: C ⥤ B) (R : B ⥤ T) : comma L (F ⋙ R) ⥤ comma L R := { obj := λ X, { left := X.left, right := F.obj X.right, hom := X.hom }, map := λ X Y f, { left := f.left, right := F.map f.right, w' := by simp } } /-- The functor `(L, R) ⥤ (L ⋙ F, R ⋙ F)` -/ @[simps] def post (L : A ⥤ T) (R : B ⥤ T) (F: T ⥤ C) : comma L R ⥤ comma (L ⋙ F) (R ⋙ F) := { obj := λ X, { left := X.left, right := X.right, hom := F.map X.hom }, map := λ X Y f, { left := f.left, right := f.right, w' := by { simp only [functor.comp_map, ←F.map_comp, f.w] } } } end end comma end category_theory
856b3fd966b1f5835b068814a24c4cb233aef5b4
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/ring_theory/valuation/valuation_ring.lean
9cc608de0f3bbc2428179156a2b3145824fe3678
[ "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,321
lean
/- Copyright (c) 2022 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz -/ import ring_theory.valuation.integers import ring_theory.ideal.local_ring import ring_theory.localization.fraction_ring import ring_theory.localization.integer import ring_theory.discrete_valuation_ring.basic import ring_theory.bezout import tactic.field_simp /-! # Valuation Rings > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. A valuation ring is a domain such that for every pair of elements `a b`, either `a` divides `b` or vice-versa. Any valuation ring induces a natural valuation on its fraction field, as we show in this file. Namely, given the following instances: `[comm_ring A] [is_domain A] [valuation_ring A] [field K] [algebra A K] [is_fraction_ring A K]`, there is a natural valuation `valuation A K` on `K` with values in `value_group A K` where the image of `A` under `algebra_map A K` agrees with `(valuation A K).integer`. We also provide the equivalence of the following notions for a domain `R` in `valuation_ring.tfae`. 1. `R` is a valuation ring. 2. For each `x : fraction_ring K`, either `x` or `x⁻¹` is in `R`. 3. "divides" is a total relation on the elements of `R`. 4. "contains" is a total relation on the ideals of `R`. 5. `R` is a local bezout domain. -/ universes u v w /-- An integral domain is called a `valuation ring` provided that for any pair of elements `a b : A`, either `a` divides `b` or vice versa. -/ class valuation_ring (A : Type u) [comm_ring A] [is_domain A] : Prop := (cond [] : ∀ a b : A, ∃ c : A, a * c = b ∨ b * c = a) namespace valuation_ring section variables (A : Type u) [comm_ring A] variables (K : Type v) [field K] [algebra A K] /-- The value group of the valuation ring `A`. Note: this is actually a group with zero. -/ def value_group : Type v := quotient (mul_action.orbit_rel Aˣ K) instance : inhabited (value_group A K) := ⟨quotient.mk' 0⟩ instance : has_le (value_group A K) := has_le.mk $ λ x y, quotient.lift_on₂' x y (λ a b, ∃ c : A, c • b = a) begin rintros _ _ a b ⟨c,rfl⟩ ⟨d,rfl⟩, ext, split, { rintros ⟨e,he⟩, use ((c⁻¹ : Aˣ) * e * d), apply_fun (λ t, c⁻¹ • t) at he, simpa [mul_smul] using he }, { rintros ⟨e,he⟩, dsimp, use (d⁻¹ : Aˣ) * c * e, erw [← he, ← mul_smul, ← mul_smul], congr' 1, rw mul_comm, simp only [← mul_assoc, ← units.coe_mul, mul_inv_self, one_mul] } end instance : has_zero (value_group A K) := ⟨quotient.mk' 0⟩ instance : has_one (value_group A K) := ⟨quotient.mk' 1⟩ instance : has_mul (value_group A K) := has_mul.mk $ λ x y, quotient.lift_on₂' x y (λ a b, quotient.mk' $ a * b) begin rintros _ _ a b ⟨c,rfl⟩ ⟨d,rfl⟩, apply quotient.sound', dsimp, use c * d, simp only [mul_smul, algebra.smul_def, units.smul_def, ring_hom.map_mul, units.coe_mul], ring, end instance : has_inv (value_group A K) := has_inv.mk $ λ x, quotient.lift_on' x (λ a, quotient.mk' a⁻¹) begin rintros _ a ⟨b,rfl⟩, apply quotient.sound', use b⁻¹, dsimp, rw [units.smul_def, units.smul_def, algebra.smul_def, algebra.smul_def, mul_inv, map_units_inv], end variables [is_domain A] [valuation_ring A] [is_fraction_ring A K] protected lemma le_total (a b : value_group A K) : a ≤ b ∨ b ≤ a := begin rcases a with ⟨a⟩, rcases b with ⟨b⟩, obtain ⟨xa,ya,hya,rfl⟩ : ∃ (a b : A), _ := is_fraction_ring.div_surjective a, obtain ⟨xb,yb,hyb,rfl⟩ : ∃ (a b : A), _ := is_fraction_ring.div_surjective b, have : (algebra_map A K) ya ≠ 0 := is_fraction_ring.to_map_ne_zero_of_mem_non_zero_divisors hya, have : (algebra_map A K) yb ≠ 0 := is_fraction_ring.to_map_ne_zero_of_mem_non_zero_divisors hyb, obtain ⟨c,(h|h)⟩ := valuation_ring.cond (xa * yb) (xb * ya), { right, use c, rw algebra.smul_def, field_simp, simp only [← ring_hom.map_mul, ← h], congr' 1, ring }, { left, use c, rw algebra.smul_def, field_simp, simp only [← ring_hom.map_mul, ← h], congr' 1, ring } end noncomputable instance : linear_ordered_comm_group_with_zero (value_group A K) := { le_refl := by { rintro ⟨⟩, use 1, rw one_smul }, le_trans := by { rintros ⟨a⟩ ⟨b⟩ ⟨c⟩ ⟨e,rfl⟩ ⟨f,rfl⟩, use (e * f), rw mul_smul }, le_antisymm := begin rintros ⟨a⟩ ⟨b⟩ ⟨e,rfl⟩ ⟨f,hf⟩, by_cases hb : b = 0, { simp [hb] }, have : is_unit e, { apply is_unit_of_dvd_one, use f, rw mul_comm, rw [← mul_smul, algebra.smul_def] at hf, nth_rewrite 1 ← one_mul b at hf, rw ← (algebra_map A K).map_one at hf, exact is_fraction_ring.injective _ _ (mul_right_cancel₀ hb hf).symm }, apply quotient.sound', use [this.unit, rfl], end, le_total := valuation_ring.le_total _ _, decidable_le := by { classical, apply_instance }, mul_assoc := by { rintros ⟨a⟩ ⟨b⟩ ⟨c⟩, apply quotient.sound', rw mul_assoc, apply setoid.refl' }, one_mul := by { rintros ⟨a⟩, apply quotient.sound', rw one_mul, apply setoid.refl' }, mul_one := by { rintros ⟨a⟩, apply quotient.sound', rw mul_one, apply setoid.refl' }, mul_comm := by { rintros ⟨a⟩ ⟨b⟩, apply quotient.sound', rw mul_comm, apply setoid.refl' }, mul_le_mul_left := begin rintros ⟨a⟩ ⟨b⟩ ⟨c,rfl⟩ ⟨d⟩, use c, simp only [algebra.smul_def], ring, end, zero_mul := by { rintros ⟨a⟩, apply quotient.sound', rw zero_mul, apply setoid.refl' }, mul_zero := by { rintros ⟨a⟩, apply quotient.sound', rw mul_zero, apply setoid.refl' }, zero_le_one := ⟨0, by rw zero_smul⟩, exists_pair_ne := begin use [0,1], intro c, obtain ⟨d,hd⟩ := quotient.exact' c, apply_fun (λ t, d⁻¹ • t) at hd, simpa using hd, end, inv_zero := by { apply quotient.sound', rw inv_zero, apply setoid.refl' }, mul_inv_cancel := begin rintros ⟨a⟩ ha, apply quotient.sound', use 1, simp only [one_smul], apply (mul_inv_cancel _).symm, contrapose ha, simp only [not_not] at ha ⊢, rw ha, refl, end, ..(infer_instance : has_le (value_group A K)), ..(infer_instance : has_mul (value_group A K)), ..(infer_instance : has_inv (value_group A K)), ..(infer_instance : has_zero (value_group A K)), ..(infer_instance : has_one (value_group A K)) } /-- Any valuation ring induces a valuation on its fraction field. -/ def valuation : valuation K (value_group A K) := { to_fun := quotient.mk', map_zero' := rfl, map_one' := rfl, map_mul' := λ _ _, rfl, map_add_le_max' := begin intros a b, obtain ⟨xa,ya,hya,rfl⟩ : ∃ (a b : A), _ := is_fraction_ring.div_surjective a, obtain ⟨xb,yb,hyb,rfl⟩ : ∃ (a b : A), _ := is_fraction_ring.div_surjective b, have : (algebra_map A K) ya ≠ 0 := is_fraction_ring.to_map_ne_zero_of_mem_non_zero_divisors hya, have : (algebra_map A K) yb ≠ 0 := is_fraction_ring.to_map_ne_zero_of_mem_non_zero_divisors hyb, obtain ⟨c,(h|h)⟩ := valuation_ring.cond (xa * yb) (xb * ya), dsimp, { apply le_trans _ (le_max_left _ _), use (c + 1), rw algebra.smul_def, field_simp, simp only [← ring_hom.map_mul, ← ring_hom.map_add, ← (algebra_map A K).map_one, ← h], congr' 1, ring }, { apply le_trans _ (le_max_right _ _), use (c + 1), rw algebra.smul_def, field_simp, simp only [← ring_hom.map_mul, ← ring_hom.map_add, ← (algebra_map A K).map_one, ← h], congr' 1, ring } end } lemma mem_integer_iff (x : K) : x ∈ (valuation A K).integer ↔ ∃ a : A, algebra_map A K a = x := begin split, { rintros ⟨c,rfl⟩, use c, rw [algebra.smul_def, mul_one] }, { rintro ⟨c,rfl⟩, use c, rw [algebra.smul_def, mul_one] } end /-- The valuation ring `A` is isomorphic to the ring of integers of its associated valuation. -/ noncomputable def equiv_integer : A ≃+* (valuation A K).integer := ring_equiv.of_bijective (show A →ₙ+* (valuation A K).integer, from { to_fun := λ a, ⟨algebra_map A K a, (mem_integer_iff _ _ _).mpr ⟨a,rfl⟩⟩, map_mul' := λ _ _, by { ext1, exact (algebra_map A K).map_mul _ _ }, map_zero' := by { ext1, exact (algebra_map A K).map_zero }, map_add' := λ _ _, by { ext1, exact (algebra_map A K).map_add _ _ } }) begin split, { intros x y h, apply_fun (coe : _ → K) at h, dsimp at h, exact is_fraction_ring.injective _ _ h }, { rintros ⟨a,(ha : a ∈ (valuation A K).integer)⟩, rw mem_integer_iff at ha, obtain ⟨a,rfl⟩ := ha, use [a, rfl] } end @[simp] lemma coe_equiv_integer_apply (a : A) : (equiv_integer A K a : K) = algebra_map A K a := rfl lemma range_algebra_map_eq : (valuation A K).integer = (algebra_map A K).range := by { ext, exact mem_integer_iff _ _ _ } end section variables (A : Type u) [comm_ring A] [is_domain A] [valuation_ring A] @[priority 100] instance : local_ring A := local_ring.of_is_unit_or_is_unit_one_sub_self begin intros a, obtain ⟨c,(h|h)⟩ := valuation_ring.cond a (1-a), { left, apply is_unit_of_mul_eq_one _ (c+1), simp [mul_add, h] }, { right, apply is_unit_of_mul_eq_one _ (c+1), simp [mul_add, h] } end instance [decidable_rel ((≤) : ideal A → ideal A → Prop)] : linear_order (ideal A) := { le_total := begin intros α β, by_cases h : α ≤ β, { exact or.inl h }, erw not_forall at h, push_neg at h, obtain ⟨a,h₁,h₂⟩ := h, right, intros b hb, obtain ⟨c,(h|h)⟩ := valuation_ring.cond a b, { rw ← h, exact ideal.mul_mem_right _ _ h₁ }, { exfalso, apply h₂, rw ← h, apply ideal.mul_mem_right _ _ hb }, end, decidable_le := infer_instance, ..(infer_instance : complete_lattice (ideal A)) } end section variables {R : Type*} [comm_ring R] [is_domain R] {K : Type*} variables [field K] [algebra R K] [is_fraction_ring R K] lemma iff_dvd_total : valuation_ring R ↔ is_total R (∣) := begin classical, refine ⟨λ H, ⟨λ a b, _⟩, λ H, ⟨λ a b, _⟩⟩; resetI, { obtain ⟨c,rfl|rfl⟩ := @@valuation_ring.cond _ _ H a b; simp }, { obtain (⟨c, rfl⟩|⟨c, rfl⟩) := @is_total.total _ _ H a b; use c; simp } end lemma iff_ideal_total : valuation_ring R ↔ is_total (ideal R) (≤) := begin classical, refine ⟨λ _, by exactI ⟨le_total⟩, λ H, iff_dvd_total.mpr ⟨λ a b, _⟩⟩, have := @is_total.total _ _ H (ideal.span {a}) (ideal.span {b}), simp_rw ideal.span_singleton_le_span_singleton at this, exact this.symm end variables {R} (K) lemma dvd_total [h : valuation_ring R] (x y : R) : x ∣ y ∨ y ∣ x := @@is_total.total _ (iff_dvd_total.mp h) x y lemma unique_irreducible [valuation_ring R] ⦃p q : R⦄ (hp : irreducible p) (hq : irreducible q) : associated p q := begin have := dvd_total p q, rw [irreducible.dvd_comm hp hq, or_self] at this, exact associated_of_dvd_dvd (irreducible.dvd_symm hq hp this) this, end variable (R) lemma iff_is_integer_or_is_integer : valuation_ring R ↔ ∀ x : K, is_localization.is_integer R x ∨ is_localization.is_integer R x⁻¹ := begin split, { introsI H x, obtain ⟨x : R, y, hy, rfl⟩ := is_fraction_ring.div_surjective x, any_goals { apply_instance }, have := (map_ne_zero_iff _ (is_fraction_ring.injective R K)).mpr (non_zero_divisors.ne_zero hy), obtain ⟨s, rfl|rfl⟩ := valuation_ring.cond x y, { exact or.inr ⟨s, eq_inv_of_mul_eq_one_left $ by rwa [mul_div, div_eq_one_iff_eq, map_mul, mul_comm]⟩ }, { exact or.inl ⟨s, by rwa [eq_div_iff, map_mul, mul_comm]⟩ } }, { intro H, constructor, intros a b, by_cases ha : a = 0, { subst ha, exact ⟨0, or.inr $ mul_zero b⟩ }, by_cases hb : b = 0, { subst hb, exact ⟨0, or.inl $ mul_zero a⟩ }, replace ha := (map_ne_zero_iff _ (is_fraction_ring.injective R K)).mpr ha, replace hb := (map_ne_zero_iff _ (is_fraction_ring.injective R K)).mpr hb, obtain ⟨c, e⟩|⟨c, e⟩ := H (algebra_map R K a / algebra_map R K b), { rw [eq_div_iff hb, ← map_mul, (is_fraction_ring.injective R K).eq_iff, mul_comm] at e, exact ⟨c, or.inr e⟩ }, { rw [inv_div, eq_div_iff ha, ← map_mul, (is_fraction_ring.injective R K).eq_iff, mul_comm c] at e, exact ⟨c, or.inl e⟩ } } end variable {K} lemma is_integer_or_is_integer [h : valuation_ring R] (x : K) : is_localization.is_integer R x ∨ is_localization.is_integer R x⁻¹ := (iff_is_integer_or_is_integer R K).mp h x variable {R} -- This implies that valuation rings are integrally closed through typeclass search. @[priority 100] instance [valuation_ring R] : is_bezout R := begin classical, rw is_bezout.iff_span_pair_is_principal, intros x y, rw ideal.span_insert, cases le_total (ideal.span {x} : ideal R) (ideal.span {y}), { erw sup_eq_right.mpr h, exact ⟨⟨_, rfl⟩⟩ }, { erw sup_eq_left.mpr h, exact ⟨⟨_, rfl⟩⟩ } end lemma iff_local_bezout_domain : valuation_ring R ↔ local_ring R ∧ is_bezout R := begin classical, refine ⟨λ H, by exactI ⟨infer_instance, infer_instance⟩, _⟩, rintro ⟨h₁, h₂⟩, resetI, refine iff_dvd_total.mpr ⟨λ a b, _⟩, obtain ⟨g, e : _ = ideal.span _⟩ := is_bezout.span_pair_is_principal a b, obtain ⟨a, rfl⟩ := ideal.mem_span_singleton'.mp (show a ∈ ideal.span {g}, by { rw [← e], exact ideal.subset_span (by simp) }), obtain ⟨b, rfl⟩ := ideal.mem_span_singleton'.mp (show b ∈ ideal.span {g}, by { rw [← e], exact ideal.subset_span (by simp) }), obtain ⟨x, y, e'⟩ := ideal.mem_span_pair.mp (show g ∈ ideal.span {a * g, b * g}, by { rw e, exact ideal.subset_span (by simp) }), cases eq_or_ne g 0 with h h, { simp [h] }, have : x * a + y * b = 1, { apply mul_left_injective₀ h, convert e'; ring_nf }, cases local_ring.is_unit_or_is_unit_of_add_one this with h' h', left, swap, right, all_goals { exact mul_dvd_mul_right (is_unit_iff_forall_dvd.mp (is_unit_of_mul_is_unit_right h') _) _ }, end protected lemma tfae (R : Type u) [comm_ring R] [is_domain R] : tfae [valuation_ring R, ∀ x : fraction_ring R, is_localization.is_integer R x ∨ is_localization.is_integer R x⁻¹, is_total R (∣), is_total (ideal R) (≤), local_ring R ∧ is_bezout R] := begin tfae_have : 1 ↔ 2, { exact iff_is_integer_or_is_integer R _ }, tfae_have : 1 ↔ 3, { exact iff_dvd_total }, tfae_have : 1 ↔ 4, { exact iff_ideal_total }, tfae_have : 1 ↔ 5, { exact iff_local_bezout_domain }, tfae_finish end end lemma _root_.function.surjective.valuation_ring {R S : Type*} [comm_ring R] [is_domain R] [valuation_ring R] [comm_ring S] [is_domain S] (f : R →+* S) (hf : function.surjective f) : valuation_ring S := ⟨λ a b, begin obtain ⟨⟨a, rfl⟩, ⟨b, rfl⟩⟩ := ⟨hf a, hf b⟩, obtain ⟨c, rfl|rfl⟩ := valuation_ring.cond a b, exacts [⟨f c, or.inl $ (map_mul _ _ _).symm⟩, ⟨f c, or.inr $ (map_mul _ _ _).symm⟩], end⟩ section variables {𝒪 : Type u} {K : Type v} {Γ : Type w} [comm_ring 𝒪] [is_domain 𝒪] [field K] [algebra 𝒪 K] [linear_ordered_comm_group_with_zero Γ] (v : _root_.valuation K Γ) (hh : v.integers 𝒪) include hh /-- If `𝒪` satisfies `v.integers 𝒪` where `v` is a valuation on a field, then `𝒪` is a valuation ring. -/ lemma of_integers : valuation_ring 𝒪 := begin constructor, intros a b, cases le_total (v (algebra_map 𝒪 K a)) (v (algebra_map 𝒪 K b)), { obtain ⟨c,hc⟩ := valuation.integers.dvd_of_le hh h, use c, exact or.inr hc.symm }, { obtain ⟨c,hc⟩ := valuation.integers.dvd_of_le hh h, use c, exact or.inl hc.symm } end end section variables (K : Type u) [field K] /-- A field is a valuation ring. -/ @[priority 100] instance of_field : valuation_ring K := begin constructor, intros a b, by_cases b = 0, { use 0, left, simp [h] }, { use a * b⁻¹, right, field_simp, rw mul_comm } end end section variables (A : Type u) [comm_ring A] [is_domain A] [discrete_valuation_ring A] /-- A DVR is a valuation ring. -/ @[priority 100] instance of_discrete_valuation_ring : valuation_ring A := begin constructor, intros a b, by_cases ha : a = 0, { use 0, right, simp [ha] }, by_cases hb : b = 0, { use 0, left, simp [hb] }, obtain ⟨ϖ,hϖ⟩ := discrete_valuation_ring.exists_irreducible A, obtain ⟨m,u,rfl⟩ := discrete_valuation_ring.eq_unit_mul_pow_irreducible ha hϖ, obtain ⟨n,v,rfl⟩ := discrete_valuation_ring.eq_unit_mul_pow_irreducible hb hϖ, cases le_total m n with h h, { use (u⁻¹ * v : Aˣ) * ϖ^(n-m), left, simp_rw [mul_comm (u : A), units.coe_mul, ← mul_assoc, mul_assoc _ (u : A)], simp only [units.mul_inv, mul_one, mul_comm _ (v : A), mul_assoc, ← pow_add], congr' 2, linarith }, { use (v⁻¹ * u : Aˣ) * ϖ^(m-n), right, simp_rw [mul_comm (v : A), units.coe_mul, ← mul_assoc, mul_assoc _ (v : A)], simp only [units.mul_inv, mul_one, mul_comm _ (u : A), mul_assoc, ← pow_add], congr' 2, linarith } end end end valuation_ring
89756ed4f44cb2a297f20e197387fcfc00213cf0
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/13_More_Tactics.org.2.lean
1e3393ad813c41050c03ab18b72342fe22dc11bd
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
540
lean
import standard import data.finset data.nat open finset nat variables (A : Type) [deceqA : decidable_eq A] include deceqA theorem card_add_card (s₁ s₂ : finset A) : card s₁ + card s₂ = card (s₁ ∪ s₂) + card (s₁ ∩ s₂) := begin induction s₂ with a s₂ hs₂ ih, show card s₁ + card (∅:finset A) = card (s₁ ∪ ∅) + card (s₁ ∩ ∅), by rewrite [union_empty, card_empty, inter_empty], show card s₁ + card (insert a s₂) = card (s₁ ∪ (insert a s₂)) + card (s₁ ∩ (insert a s₂)), from sorry end
a6f16c947fa9ab576e5276f0d36a4cfe305bab7a
37a833c924892ee3ecb911484775a6d6ebb8984d
/src/category_theory/presheaves/stalk.lean
72751954526562bc2419859fc3494171dfcc2826
[]
no_license
silky/lean-category-theory
28126e80564a1f99e9c322d86b3f7d750da0afa1
0f029a2364975f56ac727d31d867a18c95c22fd8
refs/heads/master
1,589,555,811,646
1,554,673,665,000
1,554,673,665,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
900
lean
import category_theory.presheaves import category_theory.limits.limits universes u v open category_theory open category_theory.examples open category_theory.limits open category_theory.presheaves open topological_space namespace category_theory.presheaves instance has_mem_open_set_op (X : Top) : has_mem X.α ((opens X)ᵒᵖ) := (by apply_instance : has_mem X.α (opens X)) variables {C : Type u} [𝒞 : category.{u v} C] include 𝒞 variable [has_colimits.{u v} C] namespace Presheaf def near (F : Presheaf.{u v} C) (x : F) : { U : (opens F.X)ᵒᵖ // x ∈ U } ⥤ C := (full_subcategory_inclusion (λ U : (opens F.X)ᵒᵖ, x ∈ U)) ⋙ F.𝒪 def stalk_at (F : Presheaf.{u v} C) (x : F.X) : C := colimit (F.near x) end Presheaf def stalk_at {X : Top.{v}} (𝒪 : (opens X)ᵒᵖ ⥤ C) (x : X) : C := { Presheaf . X := X, 𝒪 := 𝒪 }.stalk_at x end category_theory.presheaves
db2fbed4e032335428fb521a87ce930713197fb2
c777c32c8e484e195053731103c5e52af26a25d1
/src/topology/algebra/monoid.lean
5dbee1af0e36388442ef9339df08740db3c13afb
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
30,841
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 -/ import algebra.big_operators.finprod import order.filter.pointwise import topology.algebra.mul_action import algebra.big_operators.pi import topology.continuous_function.basic /-! # Theory of topological monoids > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we define mixin classes `has_continuous_mul` and `has_continuous_add`. While in many applications the underlying type is a monoid (multiplicative or additive), we do not require this in the definitions. -/ universes u v open classical set filter topological_space open_locale classical topology big_operators pointwise variables {ι α X M N : Type*} [topological_space X] @[to_additive] lemma continuous_one [topological_space M] [has_one M] : continuous (1 : X → M) := @continuous_const _ _ _ _ 1 /-- Basic hypothesis to talk about a topological additive monoid or a topological additive semigroup. A topological additive monoid over `M`, for example, is obtained by requiring both the instances `add_monoid M` and `has_continuous_add M`. Continuity in only the left/right argument can be stated using `has_continuous_const_vadd α α`/`has_continuous_const_vadd αᵐᵒᵖ α`. -/ class has_continuous_add (M : Type u) [topological_space M] [has_add M] : Prop := (continuous_add : continuous (λ p : M × M, p.1 + p.2)) /-- Basic hypothesis to talk about a topological monoid or a topological semigroup. A topological monoid over `M`, for example, is obtained by requiring both the instances `monoid M` and `has_continuous_mul M`. Continuity in only the left/right argument can be stated using `has_continuous_const_smul α α`/`has_continuous_const_smul αᵐᵒᵖ α`. -/ @[to_additive] class has_continuous_mul (M : Type u) [topological_space M] [has_mul M] : Prop := (continuous_mul : continuous (λ p : M × M, p.1 * p.2)) section has_continuous_mul variables [topological_space M] [has_mul M] [has_continuous_mul M] @[to_additive] instance : has_continuous_mul Mᵒᵈ := ‹has_continuous_mul M› @[to_additive] lemma continuous_mul : continuous (λp:M×M, p.1 * p.2) := has_continuous_mul.continuous_mul @[to_additive] instance has_continuous_mul.to_has_continuous_smul : has_continuous_smul M M := ⟨continuous_mul⟩ @[to_additive] instance has_continuous_mul.to_has_continuous_smul_op : has_continuous_smul Mᵐᵒᵖ M := ⟨show continuous ((λ p : M × M, p.1 * p.2) ∘ prod.swap ∘ prod.map mul_opposite.unop id), from continuous_mul.comp $ continuous_swap.comp $ continuous.prod_map mul_opposite.continuous_unop continuous_id⟩ @[continuity, to_additive] lemma continuous.mul {f g : X → M} (hf : continuous f) (hg : continuous g) : continuous (λx, f x * g x) := continuous_mul.comp (hf.prod_mk hg : _) @[to_additive] lemma continuous_mul_left (a : M) : continuous (λ b:M, a * b) := continuous_const.mul continuous_id @[to_additive] lemma continuous_mul_right (a : M) : continuous (λ b:M, b * a) := continuous_id.mul continuous_const @[to_additive] lemma continuous_on.mul {f g : X → M} {s : set X} (hf : continuous_on f s) (hg : continuous_on g s) : continuous_on (λx, f x * g x) s := (continuous_mul.comp_continuous_on (hf.prod hg) : _) @[to_additive] lemma tendsto_mul {a b : M} : tendsto (λp:M×M, p.fst * p.snd) (𝓝 (a, b)) (𝓝 (a * b)) := continuous_iff_continuous_at.mp has_continuous_mul.continuous_mul (a, b) @[to_additive] lemma filter.tendsto.mul {f g : α → M} {x : filter α} {a b : M} (hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) : tendsto (λx, f x * g x) x (𝓝 (a * b)) := tendsto_mul.comp (hf.prod_mk_nhds hg) @[to_additive] lemma filter.tendsto.const_mul (b : M) {c : M} {f : α → M} {l : filter α} (h : tendsto (λ (k:α), f k) l (𝓝 c)) : tendsto (λ (k:α), b * f k) l (𝓝 (b * c)) := tendsto_const_nhds.mul h @[to_additive] lemma filter.tendsto.mul_const (b : M) {c : M} {f : α → M} {l : filter α} (h : tendsto (λ (k:α), f k) l (𝓝 c)) : tendsto (λ (k:α), f k * b) l (𝓝 (c * b)) := h.mul tendsto_const_nhds @[to_additive] lemma le_nhds_mul (a b : M) : 𝓝 a * 𝓝 b ≤ 𝓝 (a * b) := by { rw [← map₂_mul, ← map_uncurry_prod, ← nhds_prod_eq], exact continuous_mul.tendsto _ } @[simp, to_additive] lemma nhds_one_mul_nhds {M} [mul_one_class M] [topological_space M] [has_continuous_mul M] (a : M) : 𝓝 (1 : M) * 𝓝 a = 𝓝 a := ((le_nhds_mul _ _).trans_eq $ congr_arg _ (one_mul a)).antisymm $ le_mul_of_one_le_left' $ pure_le_nhds 1 @[simp, to_additive] lemma nhds_mul_nhds_one {M} [mul_one_class M] [topological_space M] [has_continuous_mul M] (a : M) : 𝓝 a * 𝓝 1 = 𝓝 a := ((le_nhds_mul _ _).trans_eq $ congr_arg _ (mul_one a)).antisymm $ le_mul_of_one_le_right' $ pure_le_nhds 1 section tendsto_nhds variables {𝕜 : Type*} [preorder 𝕜] [has_zero 𝕜] [has_mul 𝕜] [topological_space 𝕜] [has_continuous_mul 𝕜] {l : filter α} {f : α → 𝕜} {b c : 𝕜} (hb : 0 < b) lemma filter.tendsto_nhds_within_Ioi.const_mul [pos_mul_strict_mono 𝕜] [pos_mul_reflect_lt 𝕜] (h : tendsto f l (𝓝[>] c)) : tendsto (λ a, b * f a) l (𝓝[>] (b * c)) := tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ ((tendsto_nhds_of_tendsto_nhds_within h).const_mul b) $ (tendsto_nhds_within_iff.mp h).2.mono (λ j, (mul_lt_mul_left hb).mpr) lemma filter.tendsto_nhds_within_Iio.const_mul [pos_mul_strict_mono 𝕜] [pos_mul_reflect_lt 𝕜] (h : tendsto f l (𝓝[<] c)) : tendsto (λ a, b * f a) l (𝓝[<] (b * c)) := tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ ((tendsto_nhds_of_tendsto_nhds_within h).const_mul b) $ (tendsto_nhds_within_iff.mp h).2.mono (λ j, (mul_lt_mul_left hb).mpr) lemma filter.tendsto_nhds_within_Ioi.mul_const [mul_pos_strict_mono 𝕜] [mul_pos_reflect_lt 𝕜] (h : tendsto f l (𝓝[>] c)) : tendsto (λ a, f a * b) l (𝓝[>] (c * b)) := tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ ((tendsto_nhds_of_tendsto_nhds_within h).mul_const b) $ (tendsto_nhds_within_iff.mp h).2.mono (λ j, (mul_lt_mul_right hb).mpr) lemma filter.tendsto_nhds_within_Iio.mul_const [mul_pos_strict_mono 𝕜] [mul_pos_reflect_lt 𝕜] (h : tendsto f l (𝓝[<] c)) : tendsto (λ a, f a * b) l (𝓝[<] (c * b)) := tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ ((tendsto_nhds_of_tendsto_nhds_within h).mul_const b) $ (tendsto_nhds_within_iff.mp h).2.mono (λ j, (mul_lt_mul_right hb).mpr) end tendsto_nhds /-- Construct a unit from limits of units and their inverses. -/ @[to_additive filter.tendsto.add_units "Construct an additive unit from limits of additive units and their negatives.", simps] def filter.tendsto.units [topological_space N] [monoid N] [has_continuous_mul N] [t2_space N] {f : ι → Nˣ} {r₁ r₂ : N} {l : filter ι} [l.ne_bot] (h₁ : tendsto (λ x, ↑(f x)) l (𝓝 r₁)) (h₂ : tendsto (λ x, ↑(f x)⁻¹) l (𝓝 r₂)) : Nˣ := { val := r₁, inv := r₂, val_inv := by { symmetry, simpa using h₁.mul h₂ }, inv_val := by { symmetry, simpa using h₂.mul h₁ } } @[to_additive] lemma continuous_at.mul {f g : X → M} {x : X} (hf : continuous_at f x) (hg : continuous_at g x) : continuous_at (λx, f x * g x) x := hf.mul hg @[to_additive] lemma continuous_within_at.mul {f g : X → M} {s : set X} {x : X} (hf : continuous_within_at f s x) (hg : continuous_within_at g s x) : continuous_within_at (λx, f x * g x) s x := hf.mul hg @[to_additive] instance [topological_space N] [has_mul N] [has_continuous_mul N] : has_continuous_mul (M × N) := ⟨(continuous_fst.fst'.mul continuous_fst.snd').prod_mk (continuous_snd.fst'.mul continuous_snd.snd')⟩ @[to_additive] instance pi.has_continuous_mul {C : ι → Type*} [∀ i, topological_space (C i)] [∀ i, has_mul (C i)] [∀ i, has_continuous_mul (C i)] : has_continuous_mul (Π i, C i) := { continuous_mul := continuous_pi (λ i, (continuous_apply i).fst'.mul (continuous_apply i).snd') } /-- A version of `pi.has_continuous_mul` for non-dependent functions. It is needed because sometimes Lean fails to use `pi.has_continuous_mul` for non-dependent functions. -/ @[to_additive "A version of `pi.has_continuous_add` for non-dependent functions. It is needed because sometimes Lean fails to use `pi.has_continuous_add` for non-dependent functions."] instance pi.has_continuous_mul' : has_continuous_mul (ι → M) := pi.has_continuous_mul @[priority 100, to_additive] instance has_continuous_mul_of_discrete_topology [topological_space N] [has_mul N] [discrete_topology N] : has_continuous_mul N := ⟨continuous_of_discrete_topology⟩ open_locale filter open function @[to_additive] lemma has_continuous_mul.of_nhds_one {M : Type u} [monoid M] [topological_space M] (hmul : tendsto (uncurry ((*) : M → M → M)) (𝓝 1 ×ᶠ 𝓝 1) $ 𝓝 1) (hleft : ∀ x₀ : M, 𝓝 x₀ = map (λ x, x₀*x) (𝓝 1)) (hright : ∀ x₀ : M, 𝓝 x₀ = map (λ x, x*x₀) (𝓝 1)) : has_continuous_mul M := ⟨begin rw continuous_iff_continuous_at, rintros ⟨x₀, y₀⟩, have key : (λ p : M × M, x₀ * p.1 * (p.2 * y₀)) = ((λ x, x₀*x) ∘ (λ x, x*y₀)) ∘ (uncurry (*)), { ext p, simp [uncurry, mul_assoc] }, have key₂ : (λ x, x₀*x) ∘ (λ x, y₀*x) = λ x, (x₀ *y₀)*x, { ext x, simp }, calc map (uncurry (*)) (𝓝 (x₀, y₀)) = map (uncurry (*)) (𝓝 x₀ ×ᶠ 𝓝 y₀) : by rw nhds_prod_eq ... = map (λ (p : M × M), x₀ * p.1 * (p.2 * y₀)) ((𝓝 1) ×ᶠ (𝓝 1)) : by rw [uncurry, hleft x₀, hright y₀, prod_map_map_eq, filter.map_map] ... = map ((λ x, x₀ * x) ∘ λ x, x * y₀) (map (uncurry (*)) (𝓝 1 ×ᶠ 𝓝 1)) : by { rw [key, ← filter.map_map], } ... ≤ map ((λ (x : M), x₀ * x) ∘ λ x, x * y₀) (𝓝 1) : map_mono hmul ... = 𝓝 (x₀*y₀) : by rw [← filter.map_map, ← hright, hleft y₀, filter.map_map, key₂, ← hleft] end⟩ @[to_additive] lemma has_continuous_mul_of_comm_of_nhds_one (M : Type u) [comm_monoid M] [topological_space M] (hmul : tendsto (uncurry ((*) : M → M → M)) (𝓝 1 ×ᶠ 𝓝 1) (𝓝 1)) (hleft : ∀ x₀ : M, 𝓝 x₀ = map (λ x, x₀*x) (𝓝 1)) : has_continuous_mul M := begin apply has_continuous_mul.of_nhds_one hmul hleft, intros x₀, simp_rw [mul_comm, hleft x₀] end end has_continuous_mul section pointwise_limits variables (M₁ M₂ : Type*) [topological_space M₂] [t2_space M₂] @[to_additive] lemma is_closed_set_of_map_one [has_one M₁] [has_one M₂] : is_closed {f : M₁ → M₂ | f 1 = 1} := is_closed_eq (continuous_apply 1) continuous_const @[to_additive] lemma is_closed_set_of_map_mul [has_mul M₁] [has_mul M₂] [has_continuous_mul M₂] : is_closed {f : M₁ → M₂ | ∀ x y, f (x * y) = f x * f y} := begin simp only [set_of_forall], exact is_closed_Inter (λ x, is_closed_Inter (λ y, is_closed_eq (continuous_apply _) ((continuous_apply _).mul (continuous_apply _)))) end variables {M₁ M₂} [mul_one_class M₁] [mul_one_class M₂] [has_continuous_mul M₂] {F : Type*} [monoid_hom_class F M₁ M₂] {l : filter α} /-- Construct a bundled monoid homomorphism `M₁ →* M₂` from a function `f` and a proof that it belongs to the closure of the range of the coercion from `M₁ →* M₂` (or another type of bundled homomorphisms that has a `monoid_hom_class` instance) to `M₁ → M₂`. -/ @[to_additive "Construct a bundled additive monoid homomorphism `M₁ →+ M₂` from a function `f` and a proof that it belongs to the closure of the range of the coercion from `M₁ →+ M₂` (or another type of bundled homomorphisms that has a `add_monoid_hom_class` instance) to `M₁ → M₂`.", simps { fully_applied := ff }] def monoid_hom_of_mem_closure_range_coe (f : M₁ → M₂) (hf : f ∈ closure (range (λ (f : F) (x : M₁), f x))) : M₁ →* M₂ := { to_fun := f, map_one' := (is_closed_set_of_map_one M₁ M₂).closure_subset_iff.2 (range_subset_iff.2 map_one) hf, map_mul' := (is_closed_set_of_map_mul M₁ M₂).closure_subset_iff.2 (range_subset_iff.2 map_mul) hf } /-- Construct a bundled monoid homomorphism from a pointwise limit of monoid homomorphisms. -/ @[to_additive "Construct a bundled additive monoid homomorphism from a pointwise limit of additive monoid homomorphisms", simps { fully_applied := ff }] def monoid_hom_of_tendsto (f : M₁ → M₂) (g : α → F) [l.ne_bot] (h : tendsto (λ a x, g a x) l (𝓝 f)) : M₁ →* M₂ := monoid_hom_of_mem_closure_range_coe f $ mem_closure_of_tendsto h $ eventually_of_forall $ λ a, mem_range_self _ variables (M₁ M₂) @[to_additive] lemma monoid_hom.is_closed_range_coe : is_closed (range (coe_fn : (M₁ →* M₂) → (M₁ → M₂))) := is_closed_of_closure_subset $ λ f hf, ⟨monoid_hom_of_mem_closure_range_coe f hf, rfl⟩ end pointwise_limits @[to_additive] lemma inducing.has_continuous_mul {M N F : Type*} [has_mul M] [has_mul N] [mul_hom_class F M N] [topological_space M] [topological_space N] [has_continuous_mul N] (f : F) (hf : inducing f) : has_continuous_mul M := ⟨hf.continuous_iff.2 $ by simpa only [(∘), map_mul f] using (hf.continuous.fst'.mul hf.continuous.snd')⟩ @[to_additive] lemma has_continuous_mul_induced {M N F : Type*} [has_mul M] [has_mul N] [mul_hom_class F M N] [topological_space N] [has_continuous_mul N] (f : F) : @has_continuous_mul M (induced f ‹_›) _ := by { letI := induced f ‹_›, exact inducing.has_continuous_mul f ⟨rfl⟩ } @[to_additive] instance subsemigroup.has_continuous_mul [topological_space M] [semigroup M] [has_continuous_mul M] (S : subsemigroup M) : has_continuous_mul S := inducing.has_continuous_mul (⟨coe, λ _ _, rfl⟩ : mul_hom S M) ⟨rfl⟩ @[to_additive] instance submonoid.has_continuous_mul [topological_space M] [monoid M] [has_continuous_mul M] (S : submonoid M) : has_continuous_mul S := S.to_subsemigroup.has_continuous_mul section has_continuous_mul variables [topological_space M] [monoid M] [has_continuous_mul M] @[to_additive] lemma submonoid.top_closure_mul_self_subset (s : submonoid M) : closure (s : set M) * closure s ⊆ closure s := image2_subset_iff.2 $ λ x hx y hy, map_mem_closure₂ continuous_mul hx hy $ λ a ha b hb, s.mul_mem ha hb @[to_additive] lemma submonoid.top_closure_mul_self_eq (s : submonoid M) : closure (s : set M) * closure s = closure s := subset.antisymm s.top_closure_mul_self_subset (λ x hx, ⟨x, 1, hx, subset_closure s.one_mem, mul_one _⟩) /-- The (topological-space) closure of a submonoid of a space `M` with `has_continuous_mul` is itself a submonoid. -/ @[to_additive "The (topological-space) closure of an additive submonoid of a space `M` with `has_continuous_add` is itself an additive submonoid."] def submonoid.topological_closure (s : submonoid M) : submonoid M := { carrier := closure (s : set M), one_mem' := subset_closure s.one_mem, mul_mem' := λ a b ha hb, s.top_closure_mul_self_subset ⟨a, b, ha, hb, rfl⟩ } @[to_additive] lemma submonoid.le_topological_closure (s : submonoid M) : s ≤ s.topological_closure := subset_closure @[to_additive] lemma submonoid.is_closed_topological_closure (s : submonoid M) : is_closed (s.topological_closure : set M) := by convert is_closed_closure @[to_additive] lemma submonoid.topological_closure_minimal (s : submonoid M) {t : submonoid M} (h : s ≤ t) (ht : is_closed (t : set M)) : s.topological_closure ≤ t := closure_minimal h ht /-- If a submonoid of a topological monoid is commutative, then so is its topological closure. -/ @[to_additive "If a submonoid of an additive topological monoid is commutative, then so is its topological closure."] def submonoid.comm_monoid_topological_closure [t2_space M] (s : submonoid M) (hs : ∀ (x y : s), x * y = y * x) : comm_monoid s.topological_closure := { mul_comm := have ∀ (x ∈ s) (y ∈ s), x * y = y * x, from λ x hx y hy, congr_arg subtype.val (hs ⟨x, hx⟩ ⟨y, hy⟩), λ ⟨x, hx⟩ ⟨y, hy⟩, subtype.ext $ eq_on_closure₂ this continuous_mul (continuous_snd.mul continuous_fst) x hx y hy, ..s.topological_closure.to_monoid } @[to_additive exists_open_nhds_zero_half] lemma exists_open_nhds_one_split {s : set M} (hs : s ∈ 𝓝 (1 : M)) : ∃ V : set M, is_open V ∧ (1 : M) ∈ V ∧ ∀ (v ∈ V) (w ∈ V), v * w ∈ s := have ((λa:M×M, a.1 * a.2) ⁻¹' s) ∈ 𝓝 ((1, 1) : M × M), from tendsto_mul (by simpa only [one_mul] using hs), by simpa only [prod_subset_iff] using exists_nhds_square this @[to_additive exists_nhds_zero_half] lemma exists_nhds_one_split {s : set M} (hs : s ∈ 𝓝 (1 : M)) : ∃ V ∈ 𝓝 (1 : M), ∀ (v ∈ V) (w ∈ V), v * w ∈ s := let ⟨V, Vo, V1, hV⟩ := exists_open_nhds_one_split hs in ⟨V, is_open.mem_nhds Vo V1, hV⟩ @[to_additive exists_nhds_zero_quarter] lemma exists_nhds_one_split4 {u : set M} (hu : u ∈ 𝓝 (1 : M)) : ∃ V ∈ 𝓝 (1 : M), ∀ {v w s t}, v ∈ V → w ∈ V → s ∈ V → t ∈ V → v * w * s * t ∈ u := begin rcases exists_nhds_one_split hu with ⟨W, W1, h⟩, rcases exists_nhds_one_split W1 with ⟨V, V1, h'⟩, use [V, V1], intros v w s t v_in w_in s_in t_in, simpa only [mul_assoc] using h _ (h' v v_in w w_in) _ (h' s s_in t t_in) end /-- Given a neighborhood `U` of `1` there is an open neighborhood `V` of `1` such that `VV ⊆ U`. -/ @[to_additive "Given a open neighborhood `U` of `0` there is a open neighborhood `V` of `0` such that `V + V ⊆ U`."] lemma exists_open_nhds_one_mul_subset {U : set M} (hU : U ∈ 𝓝 (1 : M)) : ∃ V : set M, is_open V ∧ (1 : M) ∈ V ∧ V * V ⊆ U := begin rcases exists_open_nhds_one_split hU with ⟨V, Vo, V1, hV⟩, use [V, Vo, V1], rintros _ ⟨x, y, hx, hy, rfl⟩, exact hV _ hx _ hy end @[to_additive] lemma is_compact.mul {s t : set M} (hs : is_compact s) (ht : is_compact t) : is_compact (s * t) := by { rw [← image_mul_prod], exact (hs.prod ht).image continuous_mul } @[to_additive] lemma tendsto_list_prod {f : ι → α → M} {x : filter α} {a : ι → M} : ∀ l:list ι, (∀i∈l, tendsto (f i) x (𝓝 (a i))) → tendsto (λb, (l.map (λc, f c b)).prod) x (𝓝 ((l.map a).prod)) | [] _ := by simp [tendsto_const_nhds] | (f :: l) h := begin simp only [list.map_cons, list.prod_cons], exact (h f (list.mem_cons_self _ _)).mul (tendsto_list_prod l (assume c hc, h c (list.mem_cons_of_mem _ hc))) end @[to_additive] lemma continuous_list_prod {f : ι → X → M} (l : list ι) (h : ∀ i ∈ l, continuous (f i)) : continuous (λ a, (l.map (λ i, f i a)).prod) := continuous_iff_continuous_at.2 $ assume x, tendsto_list_prod l $ assume c hc, continuous_iff_continuous_at.1 (h c hc) x @[to_additive] lemma continuous_on_list_prod {f : ι → X → M} (l : list ι) {t : set X} (h : ∀ i ∈ l, continuous_on (f i) t) : continuous_on (λ a, (l.map (λ i, f i a)).prod) t := begin intros x hx, rw continuous_within_at_iff_continuous_at_restrict _ hx, refine tendsto_list_prod _ (λ i hi, _), specialize h i hi x hx, rw continuous_within_at_iff_continuous_at_restrict _ hx at h, exact h, end @[continuity, to_additive] lemma continuous_pow : ∀ n : ℕ, continuous (λ a : M, a ^ n) | 0 := by simpa using continuous_const | (k+1) := by { simp only [pow_succ], exact continuous_id.mul (continuous_pow _) } instance add_monoid.has_continuous_const_smul_nat {A} [add_monoid A] [topological_space A] [has_continuous_add A] : has_continuous_const_smul ℕ A := ⟨continuous_nsmul⟩ instance add_monoid.has_continuous_smul_nat {A} [add_monoid A] [topological_space A] [has_continuous_add A] : has_continuous_smul ℕ A := ⟨continuous_uncurry_of_discrete_topology continuous_nsmul⟩ @[continuity, to_additive continuous.nsmul] lemma continuous.pow {f : X → M} (h : continuous f) (n : ℕ) : continuous (λ b, (f b) ^ n) := (continuous_pow n).comp h @[to_additive] lemma continuous_on_pow {s : set M} (n : ℕ) : continuous_on (λ x, x ^ n) s := (continuous_pow n).continuous_on @[to_additive] lemma continuous_at_pow (x : M) (n : ℕ) : continuous_at (λ x, x ^ n) x := (continuous_pow n).continuous_at @[to_additive filter.tendsto.nsmul] lemma filter.tendsto.pow {l : filter α} {f : α → M} {x : M} (hf : tendsto f l (𝓝 x)) (n : ℕ) : tendsto (λ x, f x ^ n) l (𝓝 (x ^ n)) := (continuous_at_pow _ _).tendsto.comp hf @[to_additive continuous_within_at.nsmul] lemma continuous_within_at.pow {f : X → M} {x : X} {s : set X} (hf : continuous_within_at f s x) (n : ℕ) : continuous_within_at (λ x, f x ^ n) s x := hf.pow n @[to_additive continuous_at.nsmul] lemma continuous_at.pow {f : X → M} {x : X} (hf : continuous_at f x) (n : ℕ) : continuous_at (λ x, f x ^ n) x := hf.pow n @[to_additive continuous_on.nsmul] lemma continuous_on.pow {f : X → M} {s : set X} (hf : continuous_on f s) (n : ℕ) : continuous_on (λ x, f x ^ n) s := λ x hx, (hf x hx).pow n /-- Left-multiplication by a left-invertible element of a topological monoid is proper, i.e., inverse images of compact sets are compact. -/ lemma filter.tendsto_cocompact_mul_left {a b : M} (ha : b * a = 1) : filter.tendsto (λ x : M, a * x) (filter.cocompact M) (filter.cocompact M) := begin refine filter.tendsto.of_tendsto_comp _ (filter.comap_cocompact_le (continuous_mul_left b)), convert filter.tendsto_id, ext x, simp [ha], end /-- Right-multiplication by a right-invertible element of a topological monoid is proper, i.e., inverse images of compact sets are compact. -/ lemma filter.tendsto_cocompact_mul_right {a b : M} (ha : a * b = 1) : filter.tendsto (λ x : M, x * a) (filter.cocompact M) (filter.cocompact M) := begin refine filter.tendsto.of_tendsto_comp _ (filter.comap_cocompact_le (continuous_mul_right b)), convert filter.tendsto_id, ext x, simp [ha], end /-- If `R` acts on `A` via `A`, then continuous multiplication implies continuous scalar multiplication by constants. Notably, this instances applies when `R = A`, or when `[algebra R A]` is available. -/ @[priority 100, to_additive "If `R` acts on `A` via `A`, then continuous addition implies continuous affine addition by constants."] instance is_scalar_tower.has_continuous_const_smul {R A : Type*} [monoid A] [has_smul R A] [is_scalar_tower R A A] [topological_space A] [has_continuous_mul A] : has_continuous_const_smul R A := { continuous_const_smul := λ q, begin simp only [←smul_one_mul q (_ : A)] { single_pass := tt }, exact continuous_const.mul continuous_id, end } /-- If the action of `R` on `A` commutes with left-multiplication, then continuous multiplication implies continuous scalar multiplication by constants. Notably, this instances applies when `R = Aᵐᵒᵖ` -/ @[priority 100, to_additive "If the action of `R` on `A` commutes with left-addition, then continuous addition implies continuous affine addition by constants. Notably, this instances applies when `R = Aᵃᵒᵖ`. "] instance smul_comm_class.has_continuous_const_smul {R A : Type*} [monoid A] [has_smul R A] [smul_comm_class R A A] [topological_space A] [has_continuous_mul A] : has_continuous_const_smul R A := { continuous_const_smul := λ q, begin simp only [←mul_smul_one q (_ : A)] { single_pass := tt }, exact continuous_id.mul continuous_const, end } end has_continuous_mul namespace mul_opposite /-- If multiplication is continuous in `α`, then it also is in `αᵐᵒᵖ`. -/ @[to_additive "If addition is continuous in `α`, then it also is in `αᵃᵒᵖ`."] instance [topological_space α] [has_mul α] [has_continuous_mul α] : has_continuous_mul αᵐᵒᵖ := ⟨continuous_op.comp (continuous_unop.snd'.mul continuous_unop.fst')⟩ end mul_opposite namespace units open mul_opposite variables [topological_space α] [monoid α] [has_continuous_mul α] /-- If multiplication on a monoid is continuous, then multiplication on the units of the monoid, with respect to the induced topology, is continuous. Inversion is also continuous, but we register this in a later file, `topology.algebra.group`, because the predicate `has_continuous_inv` has not yet been defined. -/ @[to_additive "If addition on an additive monoid is continuous, then addition on the additive units of the monoid, with respect to the induced topology, is continuous. Negation is also continuous, but we register this in a later file, `topology.algebra.group`, because the predicate `has_continuous_neg` has not yet been defined."] instance : has_continuous_mul αˣ := inducing_embed_product.has_continuous_mul (embed_product α) end units @[to_additive] lemma continuous.units_map [monoid M] [monoid N] [topological_space M] [topological_space N] (f : M →* N) (hf : continuous f) : continuous (units.map f) := units.continuous_iff.2 ⟨hf.comp units.continuous_coe, hf.comp units.continuous_coe_inv⟩ section variables [topological_space M] [comm_monoid M] @[to_additive] lemma submonoid.mem_nhds_one (S : submonoid M) (oS : is_open (S : set M)) : (S : set M) ∈ 𝓝 (1 : M) := is_open.mem_nhds oS S.one_mem variable [has_continuous_mul M] @[to_additive] lemma tendsto_multiset_prod {f : ι → α → M} {x : filter α} {a : ι → M} (s : multiset ι) : (∀ i ∈ s, tendsto (f i) x (𝓝 (a i))) → tendsto (λb, (s.map (λc, f c b)).prod) x (𝓝 ((s.map a).prod)) := by { rcases s with ⟨l⟩, simpa using tendsto_list_prod l } @[to_additive] lemma tendsto_finset_prod {f : ι → α → M} {x : filter α} {a : ι → M} (s : finset ι) : (∀ i ∈ s, tendsto (f i) x (𝓝 (a i))) → tendsto (λb, ∏ c in s, f c b) x (𝓝 (∏ c in s, a c)) := tendsto_multiset_prod _ @[continuity, to_additive] lemma continuous_multiset_prod {f : ι → X → M} (s : multiset ι) : (∀ i ∈ s, continuous (f i)) → continuous (λ a, (s.map (λ i, f i a)).prod) := by { rcases s with ⟨l⟩, simpa using continuous_list_prod l } @[to_additive] lemma continuous_on_multiset_prod {f : ι → X → M} (s : multiset ι) {t : set X} : (∀i ∈ s, continuous_on (f i) t) → continuous_on (λ a, (s.map (λ i, f i a)).prod) t := by { rcases s with ⟨l⟩, simpa using continuous_on_list_prod l } @[continuity, to_additive] lemma continuous_finset_prod {f : ι → X → M} (s : finset ι) : (∀ i ∈ s, continuous (f i)) → continuous (λ a, ∏ i in s, f i a) := continuous_multiset_prod _ @[to_additive] lemma continuous_on_finset_prod {f : ι → X → M} (s : finset ι) {t : set X} : (∀ i ∈ s, continuous_on (f i) t) → continuous_on (λ a, ∏ i in s, f i a) t := continuous_on_multiset_prod _ @[to_additive] lemma eventually_eq_prod {X M : Type*} [comm_monoid M] {s : finset ι} {l : filter X} {f g : ι → X → M} (hs : ∀ i ∈ s, f i =ᶠ[l] g i) : ∏ i in s, f i =ᶠ[l] ∏ i in s, g i := begin replace hs: ∀ᶠ x in l, ∀ i ∈ s, f i x = g i x, { rwa eventually_all_finset }, filter_upwards [hs] with x hx, simp only [finset.prod_apply, finset.prod_congr rfl hx], end open function @[to_additive] lemma locally_finite.exists_finset_mul_support {M : Type*} [comm_monoid M] {f : ι → X → M} (hf : locally_finite (λ i, mul_support $ f i)) (x₀ : X) : ∃ I : finset ι, ∀ᶠ x in 𝓝 x₀, mul_support (λ i, f i x) ⊆ I := begin rcases hf x₀ with ⟨U, hxU, hUf⟩, refine ⟨hUf.to_finset, mem_of_superset hxU $ λ y hy i hi, _⟩, rw [hUf.coe_to_finset], exact ⟨y, hi, hy⟩ end @[to_additive] lemma finprod_eventually_eq_prod {M : Type*} [comm_monoid M] {f : ι → X → M} (hf : locally_finite (λ i, mul_support (f i))) (x : X) : ∃ s : finset ι, ∀ᶠ y in 𝓝 x, (∏ᶠ i, f i y) = ∏ i in s, f i y := let ⟨I, hI⟩ := hf.exists_finset_mul_support x in ⟨I, hI.mono (λ y hy, finprod_eq_prod_of_mul_support_subset _ $ λ i hi, hy hi)⟩ @[to_additive] lemma continuous_finprod {f : ι → X → M} (hc : ∀ i, continuous (f i)) (hf : locally_finite (λ i, mul_support (f i))) : continuous (λ x, ∏ᶠ i, f i x) := begin refine continuous_iff_continuous_at.2 (λ x, _), rcases finprod_eventually_eq_prod hf x with ⟨s, hs⟩, refine continuous_at.congr _ (eventually_eq.symm hs), exact tendsto_finset_prod _ (λ i hi, (hc i).continuous_at), end @[to_additive] lemma continuous_finprod_cond {f : ι → X → M} {p : ι → Prop} (hc : ∀ i, p i → continuous (f i)) (hf : locally_finite (λ i, mul_support (f i))) : continuous (λ x, ∏ᶠ i (hi : p i), f i x) := begin simp only [← finprod_subtype_eq_finprod_cond], exact continuous_finprod (λ i, hc i i.2) (hf.comp_injective subtype.coe_injective) end end instance [topological_space M] [has_mul M] [has_continuous_mul M] : has_continuous_add (additive M) := { continuous_add := @continuous_mul M _ _ _ } instance [topological_space M] [has_add M] [has_continuous_add M] : has_continuous_mul (multiplicative M) := { continuous_mul := @continuous_add M _ _ _ } section lattice_ops variables {ι' : Sort*} [has_mul M] @[to_additive] lemma has_continuous_mul_Inf {ts : set (topological_space M)} (h : Π t ∈ ts, @has_continuous_mul M t _) : @has_continuous_mul M (Inf ts) _ := { continuous_mul := continuous_Inf_rng.2 (λ t ht, continuous_Inf_dom₂ ht ht (@has_continuous_mul.continuous_mul M t _ (h t ht))) } @[to_additive] lemma has_continuous_mul_infi {ts : ι' → topological_space M} (h' : Π i, @has_continuous_mul M (ts i) _) : @has_continuous_mul M (⨅ i, ts i) _ := by { rw ← Inf_range, exact has_continuous_mul_Inf (set.forall_range_iff.mpr h') } @[to_additive] lemma has_continuous_mul_inf {t₁ t₂ : topological_space M} (h₁ : @has_continuous_mul M t₁ _) (h₂ : @has_continuous_mul M t₂ _) : @has_continuous_mul M (t₁ ⊓ t₂) _ := by { rw inf_eq_infi, refine has_continuous_mul_infi (λ b, _), cases b; assumption } end lattice_ops namespace continuous_map variables [has_mul X] [has_continuous_mul X] /-- The continuous map `λ y, y * x` -/ @[to_additive "The continuous map `λ y, y + x"] protected def mul_right (x : X) : C(X, X) := mk _ (continuous_mul_right x) @[to_additive, simp] lemma coe_mul_right (x : X) : ⇑(continuous_map.mul_right x) = λ y, y * x := rfl /-- The continuous map `λ y, x * y` -/ @[to_additive "The continuous map `λ y, x + y"] protected def mul_left (x : X) : C(X, X) := mk _ (continuous_mul_left x) @[to_additive, simp] lemma coe_mul_left (x : X) : ⇑(continuous_map.mul_left x) = λ y, x * y := rfl end continuous_map
c5051981a7119f484947fac869d29901a0258c50
0005a183d2afe3c7d097776749c13513cae91b66
/src/tests.lean
a6cf53d14c736dbb980b79d7f45475fbf450528e
[]
no_license
PatrickMassot/bigop
9f85014752aa632c270bafbd96400512839220eb
af53ad615b619e3c05fe119f98f939ff010f7e6d
refs/heads/master
1,584,009,287,023
1,562,778,117,000
1,562,778,117,000
130,576,309
1
1
null
null
null
null
UTF-8
Lean
false
false
422
lean
import bigop import data.nat.prime open list #eval big[(*)/1]_(i ∈ (range' 1 5) | true) i #eval big[(*)/1]_(i ∈ (range' 1 5)) i #eval big[(*)/1]_(i = 1 .. 5) int.to_nat i #eval big[(*)/1]_(i=1..5) int.to_nat i #eval Π_(i = 1..5) int.to_nat i #eval Π_(i ∈ (range' 1 5) | true) i #eval Σ_(i ∈ range 5 | nat.prime i) i #eval Σ_(i = 1..5 | nat.prime $ int.to_nat i) int.to_nat i #eval Σ_(i = 1..5) int.to_nat i
daf75b0bc7a4e9d12b66e05c9aa2bd9a5eeb3945
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/field_theory/adjoin.lean
a7e58649a90112c00f2ee0788f0c62f753c32f65
[ "Apache-2.0" ]
permissive
troyjlee/mathlib
e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5
45e7eb8447555247246e3fe91c87066506c14875
refs/heads/master
1,689,248,035,046
1,629,470,528,000
1,629,470,528,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
33,326
lean
/- Copyright (c) 2020 Thomas Browning, Patrick Lutz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning, Patrick Lutz -/ import field_theory.intermediate_field import field_theory.splitting_field import field_theory.separable import ring_theory.adjoin_root import ring_theory.power_basis /-! # Adjoining Elements to Fields In this file we introduce the notion of adjoining elements to fields. This isn't quite the same as adjoining elements to rings. For example, `algebra.adjoin K {x}` might not include `x⁻¹`. ## Main results - `adjoin_adjoin_left`: adjoining S and then T is the same as adjoining `S ∪ T`. - `bot_eq_top_of_dim_adjoin_eq_one`: if `F⟮x⟯` has dimension `1` over `F` for every `x` in `E` then `F = E` ## Notation - `F⟮α⟯`: adjoin a single element `α` to `F`. -/ open finite_dimensional polynomial open_locale classical namespace intermediate_field section adjoin_def variables (F : Type*) [field F] {E : Type*} [field E] [algebra F E] (S : set E) /-- `adjoin F S` extends a field `F` by adjoining a set `S ⊆ E`. -/ def adjoin : intermediate_field F E := { algebra_map_mem' := λ x, subfield.subset_closure (or.inl (set.mem_range_self x)), ..subfield.closure (set.range (algebra_map F E) ∪ S) } end adjoin_def section lattice variables {F : Type*} [field F] {E : Type*} [field E] [algebra F E] @[simp] lemma adjoin_le_iff {S : set E} {T : intermediate_field F E} : adjoin F S ≤ T ↔ S ≤ T := ⟨λ H, le_trans (le_trans (set.subset_union_right _ _) subfield.subset_closure) H, λ H, (@subfield.closure_le E _ (set.range (algebra_map F E) ∪ S) T.to_subfield).mpr (set.union_subset (intermediate_field.set_range_subset T) H)⟩ lemma gc : galois_connection (adjoin F : set E → intermediate_field F E) coe := λ _ _, adjoin_le_iff /-- Galois insertion between `adjoin` and `coe`. -/ def gi : galois_insertion (adjoin F : set E → intermediate_field F E) coe := { choice := λ S _, adjoin F S, gc := intermediate_field.gc, le_l_u := λ S, (intermediate_field.gc (S : set E) (adjoin F S)).1 $ le_refl _, choice_eq := λ _ _, rfl } instance : complete_lattice (intermediate_field F E) := galois_insertion.lift_complete_lattice intermediate_field.gi instance : inhabited (intermediate_field F E) := ⟨⊤⟩ lemma mem_bot {x : E} : x ∈ (⊥ : intermediate_field F E) ↔ x ∈ set.range (algebra_map F E) := begin suffices : set.range (algebra_map F E) = (⊥ : intermediate_field F E), { rw this, refl }, { change set.range (algebra_map F E) = subfield.closure (set.range (algebra_map F E) ∪ ∅), simp [←set.image_univ, ←ring_hom.map_field_closure] } end lemma mem_top {x : E} : x ∈ (⊤ : intermediate_field F E) := subfield.subset_closure $ or.inr trivial @[simp] lemma bot_to_subalgebra : (⊥ : intermediate_field F E).to_subalgebra = ⊥ := by { ext, rw [mem_to_subalgebra, algebra.mem_bot, mem_bot] } @[simp] lemma top_to_subalgebra : (⊤ : intermediate_field F E).to_subalgebra = ⊤ := by { ext, rw [mem_to_subalgebra, iff_true_right algebra.mem_top], exact mem_top } /-- Construct an algebra isomorphism from an equality of intermediate fields -/ @[simps apply] def equiv_of_eq {S T : intermediate_field F E} (h : S = T) : S ≃ₐ[F] T := by refine { to_fun := λ x, ⟨x, _⟩, inv_fun := λ x, ⟨x, _⟩, .. }; tidy @[simp] lemma equiv_of_eq_symm {S T : intermediate_field F E} (h : S = T) : (equiv_of_eq h).symm = equiv_of_eq h.symm := rfl @[simp] lemma equiv_of_eq_rfl (S : intermediate_field F E) : equiv_of_eq (rfl : S = S) = alg_equiv.refl := by { ext, refl } @[simp] lemma equiv_of_eq_trans {S T U : intermediate_field F E} (hST : S = T) (hTU : T = U) : (equiv_of_eq hST).trans (equiv_of_eq hTU) = equiv_of_eq (trans hST hTU) := rfl variables (F E) /-- The bottom intermediate_field is isomorphic to the field. -/ noncomputable def bot_equiv : (⊥ : intermediate_field F E) ≃ₐ[F] F := (subalgebra.equiv_of_eq _ _ bot_to_subalgebra).trans (algebra.bot_equiv F E) variables {F E} @[simp] lemma bot_equiv_def (x : F) : bot_equiv F E (algebra_map F (⊥ : intermediate_field F E) x) = x := alg_equiv.commutes (bot_equiv F E) x noncomputable instance algebra_over_bot : algebra (⊥ : intermediate_field F E) F := (intermediate_field.bot_equiv F E).to_alg_hom.to_ring_hom.to_algebra instance is_scalar_tower_over_bot : is_scalar_tower (⊥ : intermediate_field F E) F E := is_scalar_tower.of_algebra_map_eq begin intro x, let ϕ := algebra.of_id F (⊥ : subalgebra F E), let ψ := alg_equiv.of_bijective ϕ ((algebra.bot_equiv F E).symm.bijective), change (↑x : E) = ↑(ψ (ψ.symm ⟨x, _⟩)), rw alg_equiv.apply_symm_apply ψ ⟨x, _⟩, refl end /-- The top intermediate_field is isomorphic to the field. -/ noncomputable def top_equiv : (⊤ : intermediate_field F E) ≃ₐ[F] E := (subalgebra.equiv_of_eq _ _ top_to_subalgebra).trans algebra.top_equiv @[simp] lemma top_equiv_def (x : (⊤ : intermediate_field F E)) : top_equiv x = ↑x := begin suffices : algebra.to_top (top_equiv x) = algebra.to_top (x : E), { rwa subtype.ext_iff at this }, exact alg_equiv.apply_symm_apply (alg_equiv.of_bijective algebra.to_top ⟨λ _ _, subtype.mk.inj, λ x, ⟨x.val, by { ext, refl }⟩⟩ : E ≃ₐ[F] (⊤ : subalgebra F E)) (subalgebra.equiv_of_eq _ _ top_to_subalgebra x), end @[simp] lemma coe_bot_eq_self (K : intermediate_field F E) : ↑(⊥ : intermediate_field K E) = K := by { ext, rw [mem_lift2, mem_bot], exact set.ext_iff.mp subtype.range_coe x } @[simp] lemma coe_top_eq_top (K : intermediate_field F E) : ↑(⊤ : intermediate_field K E) = (⊤ : intermediate_field F E) := set_like.ext_iff.mpr $ λ _, mem_lift2.trans (iff_of_true mem_top mem_top) end lattice section adjoin_def variables (F : Type*) [field F] {E : Type*} [field E] [algebra F E] (S : set E) lemma adjoin_eq_range_algebra_map_adjoin : (adjoin F S : set E) = set.range (algebra_map (adjoin F S) E) := (subtype.range_coe).symm lemma adjoin.algebra_map_mem (x : F) : algebra_map F E x ∈ adjoin F S := intermediate_field.algebra_map_mem (adjoin F S) x lemma adjoin.range_algebra_map_subset : set.range (algebra_map F E) ⊆ adjoin F S := begin intros x hx, cases hx with f hf, rw ← hf, exact adjoin.algebra_map_mem F S f, end instance adjoin.field_coe : has_coe_t F (adjoin F S) := {coe := λ x, ⟨algebra_map F E x, adjoin.algebra_map_mem F S x⟩} lemma subset_adjoin : S ⊆ adjoin F S := λ x hx, subfield.subset_closure (or.inr hx) instance adjoin.set_coe : has_coe_t S (adjoin F S) := {coe := λ x, ⟨x,subset_adjoin F S (subtype.mem x)⟩} @[mono] lemma adjoin.mono (T : set E) (h : S ⊆ T) : adjoin F S ≤ adjoin F T := galois_connection.monotone_l gc h lemma adjoin_contains_field_as_subfield (F : subfield E) : (F : set E) ⊆ adjoin F S := λ x hx, adjoin.algebra_map_mem F S ⟨x, hx⟩ lemma subset_adjoin_of_subset_left {F : subfield E} {T : set E} (HT : T ⊆ F) : T ⊆ adjoin F S := λ x hx, (adjoin F S).algebra_map_mem ⟨x, HT hx⟩ lemma subset_adjoin_of_subset_right {T : set E} (H : T ⊆ S) : T ⊆ adjoin F S := λ x hx, subset_adjoin F S (H hx) @[simp] lemma adjoin_empty (F E : Type*) [field F] [field E] [algebra F E] : adjoin F (∅ : set E) = ⊥ := eq_bot_iff.mpr (adjoin_le_iff.mpr (set.empty_subset _)) /-- If `K` is a field with `F ⊆ K` and `S ⊆ K` then `adjoin F S ≤ K`. -/ lemma adjoin_le_subfield {K : subfield E} (HF : set.range (algebra_map F E) ⊆ K) (HS : S ⊆ K) : (adjoin F S).to_subfield ≤ K := begin apply subfield.closure_le.mpr, rw set.union_subset_iff, exact ⟨HF, HS⟩, end lemma adjoin_subset_adjoin_iff {F' : Type*} [field F'] [algebra F' E] {S S' : set E} : (adjoin F S : set E) ⊆ adjoin F' S' ↔ set.range (algebra_map F E) ⊆ adjoin F' S' ∧ S ⊆ adjoin F' S' := ⟨λ h, ⟨trans (adjoin.range_algebra_map_subset _ _) h, trans (subset_adjoin _ _) h⟩, λ ⟨hF, hS⟩, subfield.closure_le.mpr (set.union_subset hF hS)⟩ /-- `F[S][T] = F[S ∪ T]` -/ lemma adjoin_adjoin_left (T : set E) : ↑(adjoin (adjoin F S) T) = adjoin F (S ∪ T) := begin rw set_like.ext'_iff, change ↑(adjoin (adjoin F S) T) = _, apply set.eq_of_subset_of_subset; rw adjoin_subset_adjoin_iff; split, { rintros _ ⟨⟨x, hx⟩, rfl⟩, exact adjoin.mono _ _ _ (set.subset_union_left _ _) hx }, { exact subset_adjoin_of_subset_right _ _ (set.subset_union_right _ _) }, { exact subset_adjoin_of_subset_left _ (adjoin.range_algebra_map_subset _ _) }, { exact set.union_subset (subset_adjoin_of_subset_left _ (subset_adjoin _ _)) (subset_adjoin _ _) }, end @[simp] lemma adjoin_insert_adjoin (x : E) : adjoin F (insert x (adjoin F S : set E)) = adjoin F (insert x S) := le_antisymm (adjoin_le_iff.mpr (set.insert_subset.mpr ⟨subset_adjoin _ _ (set.mem_insert _ _), adjoin_le_iff.mpr (subset_adjoin_of_subset_right _ _ (set.subset_insert _ _))⟩)) (adjoin.mono _ _ _ (set.insert_subset_insert (subset_adjoin _ _))) /-- `F[S][T] = F[T][S]` -/ lemma adjoin_adjoin_comm (T : set E) : ↑(adjoin (adjoin F S) T) = (↑(adjoin (adjoin F T) S) : (intermediate_field F E)) := by rw [adjoin_adjoin_left, adjoin_adjoin_left, set.union_comm] lemma adjoin_map {E' : Type*} [field E'] [algebra F E'] (f : E →ₐ[F] E') : (adjoin F S).map f = adjoin F (f '' S) := begin ext x, show x ∈ (subfield.closure (set.range (algebra_map F E) ∪ S)).map (f : E →+* E') ↔ x ∈ subfield.closure (set.range (algebra_map F E') ∪ f '' S), rw [ring_hom.map_field_closure, set.image_union, ← set.range_comp, ← ring_hom.coe_comp, f.comp_algebra_map], refl, end lemma algebra_adjoin_le_adjoin : algebra.adjoin F S ≤ (adjoin F S).to_subalgebra := algebra.adjoin_le (subset_adjoin _ _) lemma adjoin_eq_algebra_adjoin (inv_mem : ∀ x ∈ algebra.adjoin F S, x⁻¹ ∈ algebra.adjoin F S) : (adjoin F S).to_subalgebra = algebra.adjoin F S := le_antisymm (show adjoin F S ≤ { neg_mem' := λ x, (algebra.adjoin F S).neg_mem, inv_mem' := inv_mem, .. algebra.adjoin F S}, from adjoin_le_iff.mpr (algebra.subset_adjoin)) (algebra_adjoin_le_adjoin _ _) lemma eq_adjoin_of_eq_algebra_adjoin (K : intermediate_field F E) (h : K.to_subalgebra = algebra.adjoin F S) : K = adjoin F S := begin apply to_subalgebra_injective, rw h, refine (adjoin_eq_algebra_adjoin _ _ _).symm, intros x, convert K.inv_mem, rw ← h, refl end @[elab_as_eliminator] lemma adjoin_induction {s : set E} {p : E → Prop} {x} (h : x ∈ adjoin F s) (Hs : ∀ x ∈ s, p x) (Hmap : ∀ x, p (algebra_map F E x)) (Hadd : ∀ x y, p x → p y → p (x + y)) (Hneg : ∀ x, p x → p (-x)) (Hinv : ∀ x, p x → p x⁻¹) (Hmul : ∀ x y, p x → p y → p (x * y)) : p x := subfield.closure_induction h (λ x hx, or.cases_on hx (λ ⟨x, hx⟩, hx ▸ Hmap x) (Hs x)) ((algebra_map F E).map_one ▸ Hmap 1) Hadd Hneg Hinv Hmul /-- Variation on `set.insert` to enable good notation for adjoining elements to fields. Used to preferentially use `singleton` rather than `insert` when adjoining one element. -/ --this definition of notation is courtesy of Kyle Miller on zulip class insert {α : Type*} (s : set α) := (insert : α → set α) @[priority 1000] instance insert_empty {α : Type*} : insert (∅ : set α) := { insert := λ x, @singleton _ _ set.has_singleton x } @[priority 900] instance insert_nonempty {α : Type*} (s : set α) : insert s := { insert := λ x, set.insert x s } notation K`⟮`:std.prec.max_plus l:(foldr `, ` (h t, insert.insert t h) ∅) `⟯` := adjoin K l section adjoin_simple variables (α : E) lemma mem_adjoin_simple_self : α ∈ F⟮α⟯ := subset_adjoin F {α} (set.mem_singleton α) /-- generator of `F⟮α⟯` -/ def adjoin_simple.gen : F⟮α⟯ := ⟨α, mem_adjoin_simple_self F α⟩ @[simp] lemma adjoin_simple.algebra_map_gen : algebra_map F⟮α⟯ E (adjoin_simple.gen F α) = α := rfl @[simp] lemma adjoin_simple.is_integral_gen : is_integral F (adjoin_simple.gen F α) ↔ is_integral F α := by { conv_rhs { rw ← adjoin_simple.algebra_map_gen F α }, rw is_integral_algebra_map_iff (algebra_map F⟮α⟯ E).injective, apply_instance } lemma adjoin_simple_adjoin_simple (β : E) : ↑F⟮α⟯⟮β⟯ = F⟮α, β⟯ := adjoin_adjoin_left _ _ _ lemma adjoin_simple_comm (β : E) : ↑F⟮α⟯⟮β⟯ = (↑F⟮β⟯⟮α⟯ : intermediate_field F E) := adjoin_adjoin_comm _ _ _ -- TODO: develop the API for `subalgebra.is_field_of_algebraic` so it can be used here lemma adjoin_simple_to_subalgebra_of_integral (hα : is_integral F α) : (F⟮α⟯).to_subalgebra = algebra.adjoin F {α} := begin apply adjoin_eq_algebra_adjoin, intros x hx, by_cases x = 0, { rw [h, inv_zero], exact subalgebra.zero_mem (algebra.adjoin F {α}) }, let ϕ := alg_equiv.adjoin_singleton_equiv_adjoin_root_minpoly F α, haveI := minpoly.irreducible hα, suffices : ϕ ⟨x, hx⟩ * (ϕ ⟨x, hx⟩)⁻¹ = 1, { convert subtype.mem (ϕ.symm (ϕ ⟨x, hx⟩)⁻¹), refine (eq_inv_of_mul_right_eq_one _).symm, apply_fun ϕ.symm at this, rw [alg_equiv.map_one, alg_equiv.map_mul, alg_equiv.symm_apply_apply] at this, rw [←subsemiring.coe_one, ←this, subsemiring.coe_mul, subtype.coe_mk] }, rw mul_inv_cancel (mt (λ key, _) h), rw ← ϕ.map_zero at key, change ↑(⟨x, hx⟩ : algebra.adjoin F {α}) = _, rw [ϕ.injective key, subalgebra.coe_zero] end end adjoin_simple end adjoin_def section adjoin_intermediate_field_lattice variables {F : Type*} [field F] {E : Type*} [field E] [algebra F E] {α : E} {S : set E} @[simp] lemma adjoin_eq_bot_iff : adjoin F S = ⊥ ↔ S ⊆ (⊥ : intermediate_field F E) := by { rw [eq_bot_iff, adjoin_le_iff], refl, } @[simp] lemma adjoin_simple_eq_bot_iff : F⟮α⟯ = ⊥ ↔ α ∈ (⊥ : intermediate_field F E) := by { rw adjoin_eq_bot_iff, exact set.singleton_subset_iff } @[simp] lemma adjoin_zero : F⟮(0 : E)⟯ = ⊥ := adjoin_simple_eq_bot_iff.mpr (zero_mem ⊥) @[simp] lemma adjoin_one : F⟮(1 : E)⟯ = ⊥ := adjoin_simple_eq_bot_iff.mpr (one_mem ⊥) @[simp] lemma adjoin_int (n : ℤ) : F⟮(n : E)⟯ = ⊥ := adjoin_simple_eq_bot_iff.mpr (coe_int_mem ⊥ n) @[simp] lemma adjoin_nat (n : ℕ) : F⟮(n : E)⟯ = ⊥ := adjoin_simple_eq_bot_iff.mpr (coe_int_mem ⊥ n) section adjoin_dim open finite_dimensional module variables {K L : intermediate_field F E} @[simp] lemma dim_eq_one_iff : module.rank F K = 1 ↔ K = ⊥ := by rw [← to_subalgebra_eq_iff, ← dim_eq_dim_subalgebra, subalgebra.dim_eq_one_iff, bot_to_subalgebra] @[simp] lemma finrank_eq_one_iff : finrank F K = 1 ↔ K = ⊥ := by rw [← to_subalgebra_eq_iff, ← finrank_eq_finrank_subalgebra, subalgebra.finrank_eq_one_iff, bot_to_subalgebra] lemma dim_adjoin_eq_one_iff : module.rank F (adjoin F S) = 1 ↔ S ⊆ (⊥ : intermediate_field F E) := iff.trans dim_eq_one_iff adjoin_eq_bot_iff lemma dim_adjoin_simple_eq_one_iff : module.rank F F⟮α⟯ = 1 ↔ α ∈ (⊥ : intermediate_field F E) := by { rw dim_adjoin_eq_one_iff, exact set.singleton_subset_iff } lemma finrank_adjoin_eq_one_iff : finrank F (adjoin F S) = 1 ↔ S ⊆ (⊥ : intermediate_field F E) := iff.trans finrank_eq_one_iff adjoin_eq_bot_iff lemma finrank_adjoin_simple_eq_one_iff : finrank F F⟮α⟯ = 1 ↔ α ∈ (⊥ : intermediate_field F E) := by { rw [finrank_adjoin_eq_one_iff], exact set.singleton_subset_iff } /-- If `F⟮x⟯` has dimension `1` over `F` for every `x ∈ E` then `F = E`. -/ lemma bot_eq_top_of_dim_adjoin_eq_one (h : ∀ x : E, module.rank F F⟮x⟯ = 1) : (⊥ : intermediate_field F E) = ⊤ := begin ext, rw iff_true_right intermediate_field.mem_top, exact dim_adjoin_simple_eq_one_iff.mp (h x), end lemma bot_eq_top_of_finrank_adjoin_eq_one (h : ∀ x : E, finrank F F⟮x⟯ = 1) : (⊥ : intermediate_field F E) = ⊤ := begin ext, rw iff_true_right intermediate_field.mem_top, exact finrank_adjoin_simple_eq_one_iff.mp (h x), end lemma subsingleton_of_dim_adjoin_eq_one (h : ∀ x : E, module.rank F F⟮x⟯ = 1) : subsingleton (intermediate_field F E) := subsingleton_of_bot_eq_top (bot_eq_top_of_dim_adjoin_eq_one h) lemma subsingleton_of_finrank_adjoin_eq_one (h : ∀ x : E, finrank F F⟮x⟯ = 1) : subsingleton (intermediate_field F E) := subsingleton_of_bot_eq_top (bot_eq_top_of_finrank_adjoin_eq_one h) /-- If `F⟮x⟯` has dimension `≤1` over `F` for every `x ∈ E` then `F = E`. -/ lemma bot_eq_top_of_finrank_adjoin_le_one [finite_dimensional F E] (h : ∀ x : E, finrank F F⟮x⟯ ≤ 1) : (⊥ : intermediate_field F E) = ⊤ := begin apply bot_eq_top_of_finrank_adjoin_eq_one, exact λ x, by linarith [h x, show 0 < finrank F F⟮x⟯, from finrank_pos], end lemma subsingleton_of_finrank_adjoin_le_one [finite_dimensional F E] (h : ∀ x : E, finrank F F⟮x⟯ ≤ 1) : subsingleton (intermediate_field F E) := subsingleton_of_bot_eq_top (bot_eq_top_of_finrank_adjoin_le_one h) end adjoin_dim end adjoin_intermediate_field_lattice section adjoin_integral_element variables {F : Type*} [field F] {E : Type*} [field E] [algebra F E] {α : E} variables {K : Type*} [field K] [algebra F K] lemma minpoly_gen {α : E} (h : is_integral F α) : minpoly F (adjoin_simple.gen F α) = minpoly F α := begin rw ← adjoin_simple.algebra_map_gen F α at h, have inj := (algebra_map F⟮α⟯ E).injective, exact minpoly.eq_of_algebra_map_eq inj ((is_integral_algebra_map_iff inj).mp h) (adjoin_simple.algebra_map_gen _ _).symm end variables (F) lemma aeval_gen_minpoly (α : E) : aeval (adjoin_simple.gen F α) (minpoly F α) = 0 := begin ext, convert minpoly.aeval F α, conv in (aeval α) { rw [← adjoin_simple.algebra_map_gen F α] }, exact is_scalar_tower.algebra_map_aeval F F⟮α⟯ E _ _ end /-- algebra isomorphism between `adjoin_root` and `F⟮α⟯` -/ noncomputable def adjoin_root_equiv_adjoin (h : is_integral F α) : adjoin_root (minpoly F α) ≃ₐ[F] F⟮α⟯ := alg_equiv.of_bijective (alg_hom.mk (adjoin_root.lift (algebra_map F F⟮α⟯) (adjoin_simple.gen F α) (aeval_gen_minpoly F α)) (ring_hom.map_one _) (λ x y, ring_hom.map_mul _ x y) (ring_hom.map_zero _) (λ x y, ring_hom.map_add _ x y) (by { exact λ _, adjoin_root.lift_of })) (begin set f := adjoin_root.lift _ _ (aeval_gen_minpoly F α : _), haveI := minpoly.irreducible h, split, { exact ring_hom.injective f }, { suffices : F⟮α⟯.to_subfield ≤ ring_hom.field_range ((F⟮α⟯.to_subfield.subtype).comp f), { exact λ x, Exists.cases_on (this (subtype.mem x)) (λ y hy, ⟨y, subtype.ext hy⟩) }, exact subfield.closure_le.mpr (set.union_subset (λ x hx, Exists.cases_on hx (λ y hy, ⟨y, by { rw [ring_hom.comp_apply, adjoin_root.lift_of], exact hy }⟩)) (set.singleton_subset_iff.mpr ⟨adjoin_root.root (minpoly F α), by { rw [ring_hom.comp_apply, adjoin_root.lift_root], refl }⟩)) } end) lemma adjoin_root_equiv_adjoin_apply_root (h : is_integral F α) : adjoin_root_equiv_adjoin F h (adjoin_root.root (minpoly F α)) = adjoin_simple.gen F α := begin refine adjoin_root.lift_root, { exact minpoly F α }, { exact aeval_gen_minpoly F α } end section power_basis variables {L : Type*} [field L] [algebra K L] /-- The elements `1, x, ..., x ^ (d - 1)` form a basis for `K⟮x⟯`, where `d` is the degree of the minimal polynomial of `x`. -/ noncomputable def power_basis_aux {x : L} (hx : is_integral K x) : basis (fin (minpoly K x).nat_degree) K K⟮x⟯ := (adjoin_root.power_basis (minpoly.ne_zero hx)).basis.map (adjoin_root_equiv_adjoin K hx).to_linear_equiv /-- The power basis `1, x, ..., x ^ (d - 1)` for `K⟮x⟯`, where `d` is the degree of the minimal polynomial of `x`. -/ @[simps] noncomputable def adjoin.power_basis {x : L} (hx : is_integral K x) : power_basis K K⟮x⟯ := { gen := adjoin_simple.gen K x, dim := (minpoly K x).nat_degree, basis := power_basis_aux hx, basis_eq_pow := λ i, by rw [power_basis_aux, basis.map_apply, power_basis.basis_eq_pow, alg_equiv.to_linear_equiv_apply, alg_equiv.map_pow, adjoin_root.power_basis_gen, adjoin_root_equiv_adjoin_apply_root] } lemma adjoin.finite_dimensional {x : L} (hx : is_integral K x) : finite_dimensional K K⟮x⟯ := power_basis.finite_dimensional (adjoin.power_basis hx) lemma adjoin.finrank {x : L} (hx : is_integral K x) : finite_dimensional.finrank K K⟮x⟯ = (minpoly K x).nat_degree := begin rw power_basis.finrank (adjoin.power_basis hx : _), refl end end power_basis /-- Algebra homomorphism `F⟮α⟯ →ₐ[F] K` are in bijection with the set of roots of `minpoly α` in `K`. -/ noncomputable def alg_hom_adjoin_integral_equiv (h : is_integral F α) : (F⟮α⟯ →ₐ[F] K) ≃ {x // x ∈ ((minpoly F α).map (algebra_map F K)).roots} := (adjoin.power_basis h).lift_equiv'.trans ((equiv.refl _).subtype_equiv (λ x, by rw [adjoin.power_basis_gen, minpoly_gen h, equiv.refl_apply])) /-- Fintype of algebra homomorphism `F⟮α⟯ →ₐ[F] K` -/ noncomputable def fintype_of_alg_hom_adjoin_integral (h : is_integral F α) : fintype (F⟮α⟯ →ₐ[F] K) := power_basis.alg_hom.fintype (adjoin.power_basis h) lemma card_alg_hom_adjoin_integral (h : is_integral F α) (h_sep : (minpoly F α).separable) (h_splits : (minpoly F α).splits (algebra_map F K)) : @fintype.card (F⟮α⟯ →ₐ[F] K) (fintype_of_alg_hom_adjoin_integral F h) = (minpoly F α).nat_degree := by { rw alg_hom.card_of_power_basis, all_goals { rwa [adjoin.power_basis_gen, minpoly_gen h] } } end adjoin_integral_element section induction variables {F : Type*} [field F] {E : Type*} [field E] [algebra F E] /-- An intermediate field `S` is finitely generated if there exists `t : finset E` such that `intermediate_field.adjoin F t = S`. -/ def fg (S : intermediate_field F E) : Prop := ∃ (t : finset E), adjoin F ↑t = S lemma fg_adjoin_finset (t : finset E) : (adjoin F (↑t : set E)).fg := ⟨t, rfl⟩ theorem fg_def {S : intermediate_field F E} : S.fg ↔ ∃ t : set E, set.finite t ∧ adjoin F t = S := ⟨λ ⟨t, ht⟩, ⟨↑t, set.finite_mem_finset t, ht⟩, λ ⟨t, ht1, ht2⟩, ⟨ht1.to_finset, by rwa set.finite.coe_to_finset⟩⟩ theorem fg_bot : (⊥ : intermediate_field F E).fg := ⟨∅, adjoin_empty F E⟩ lemma fg_of_fg_to_subalgebra (S : intermediate_field F E) (h : S.to_subalgebra.fg) : S.fg := begin cases h with t ht, exact ⟨t, (eq_adjoin_of_eq_algebra_adjoin _ _ _ ht.symm).symm⟩ end lemma fg_of_noetherian (S : intermediate_field F E) [is_noetherian F E] : S.fg := S.fg_of_fg_to_subalgebra S.to_subalgebra.fg_of_noetherian lemma induction_on_adjoin_finset (S : finset E) (P : intermediate_field F E → Prop) (base : P ⊥) (ih : ∀ (K : intermediate_field F E) (x ∈ S), P K → P ↑K⟮x⟯) : P (adjoin F ↑S) := begin apply finset.induction_on' S, { exact base }, { intros a s h1 _ _ h4, rw [finset.coe_insert, set.insert_eq, set.union_comm, ←adjoin_adjoin_left], exact ih (adjoin F s) a h1 h4 } end lemma induction_on_adjoin_fg (P : intermediate_field F E → Prop) (base : P ⊥) (ih : ∀ (K : intermediate_field F E) (x : E), P K → P ↑K⟮x⟯) (K : intermediate_field F E) (hK : K.fg) : P K := begin obtain ⟨S, rfl⟩ := hK, exact induction_on_adjoin_finset S P base (λ K x _ hK, ih K x hK), end lemma induction_on_adjoin [fd : finite_dimensional F E] (P : intermediate_field F E → Prop) (base : P ⊥) (ih : ∀ (K : intermediate_field F E) (x : E), P K → P ↑K⟮x⟯) (K : intermediate_field F E) : P K := induction_on_adjoin_fg P base ih K K.fg_of_noetherian end induction section alg_hom_mk_adjoin_splits variables (F E K : Type*) [field F] [field E] [field K] [algebra F E] [algebra F K] {S : set E} /-- Lifts `L → K` of `F → K` -/ def lifts := Σ (L : intermediate_field F E), (L →ₐ[F] K) variables {F E K} noncomputable instance : order_bot (lifts F E K) := { le := λ x y, x.1 ≤ y.1 ∧ (∀ (s : x.1) (t : y.1), (s : E) = t → x.2 s = y.2 t), le_refl := λ x, ⟨le_refl x.1, λ s t hst, congr_arg x.2 (subtype.ext hst)⟩, le_trans := λ x y z hxy hyz, ⟨le_trans hxy.1 hyz.1, λ s u hsu, eq.trans (hxy.2 s ⟨s, hxy.1 s.mem⟩ rfl) (hyz.2 ⟨s, hxy.1 s.mem⟩ u hsu)⟩, le_antisymm := begin rintros ⟨x1, x2⟩ ⟨y1, y2⟩ ⟨hxy1, hxy2⟩ ⟨hyx1, hyx2⟩, have : x1 = y1 := le_antisymm hxy1 hyx1, subst this, congr, exact alg_hom.ext (λ s, hxy2 s s rfl), end, bot := ⟨⊥, (algebra.of_id F K).comp (bot_equiv F E).to_alg_hom⟩, bot_le := λ x, ⟨bot_le, λ s t hst, begin cases intermediate_field.mem_bot.mp s.mem with u hu, rw [show s = (algebra_map F _) u, from subtype.ext hu.symm, alg_hom.commutes], rw [show t = (algebra_map F _) u, from subtype.ext (eq.trans hu hst).symm, alg_hom.commutes], end⟩ } noncomputable instance : inhabited (lifts F E K) := ⟨⊥⟩ lemma lifts.eq_of_le {x y : lifts F E K} (hxy : x ≤ y) (s : x.1) : x.2 s = y.2 ⟨s, hxy.1 s.mem⟩ := hxy.2 s ⟨s, hxy.1 s.mem⟩ rfl lemma lifts.exists_max_two {c : set (lifts F E K)} {x y : lifts F E K} (hc : zorn.chain (≤) c) (hx : x ∈ set.insert ⊥ c) (hy : y ∈ set.insert ⊥ c) : ∃ z : lifts F E K, z ∈ set.insert ⊥ c ∧ x ≤ z ∧ y ≤ z := begin cases (zorn.chain_insert hc (λ _ _ _, or.inl bot_le)).total_of_refl hx hy with hxy hyx, { exact ⟨y, hy, hxy, le_refl y⟩ }, { exact ⟨x, hx, le_refl x, hyx⟩ }, end lemma lifts.exists_max_three {c : set (lifts F E K)} {x y z : lifts F E K} (hc : zorn.chain (≤) c) (hx : x ∈ set.insert ⊥ c) (hy : y ∈ set.insert ⊥ c) (hz : z ∈ set.insert ⊥ c) : ∃ w : lifts F E K, w ∈ set.insert ⊥ c ∧ x ≤ w ∧ y ≤ w ∧ z ≤ w := begin obtain ⟨v, hv, hxv, hyv⟩ := lifts.exists_max_two hc hx hy, obtain ⟨w, hw, hzw, hvw⟩ := lifts.exists_max_two hc hz hv, exact ⟨w, hw, le_trans hxv hvw, le_trans hyv hvw, hzw⟩, end /-- An upper bound on a chain of lifts -/ def lifts.upper_bound_intermediate_field {c : set (lifts F E K)} (hc : zorn.chain (≤) c) : intermediate_field F E := { carrier := λ s, ∃ x : (lifts F E K), x ∈ set.insert ⊥ c ∧ (s ∈ x.1 : Prop), zero_mem' := ⟨⊥, set.mem_insert ⊥ c, zero_mem ⊥⟩, one_mem' := ⟨⊥, set.mem_insert ⊥ c, one_mem ⊥⟩, neg_mem' := by { rintros _ ⟨x, y, h⟩, exact ⟨x, ⟨y, x.1.neg_mem h⟩⟩ }, inv_mem' := by { rintros _ ⟨x, y, h⟩, exact ⟨x, ⟨y, x.1.inv_mem h⟩⟩ }, add_mem' := by { rintros _ _ ⟨x, hx, ha⟩ ⟨y, hy, hb⟩, obtain ⟨z, hz, hxz, hyz⟩ := lifts.exists_max_two hc hx hy, exact ⟨z, hz, z.1.add_mem (hxz.1 ha) (hyz.1 hb)⟩ }, mul_mem' := by { rintros _ _ ⟨x, hx, ha⟩ ⟨y, hy, hb⟩, obtain ⟨z, hz, hxz, hyz⟩ := lifts.exists_max_two hc hx hy, exact ⟨z, hz, z.1.mul_mem (hxz.1 ha) (hyz.1 hb)⟩ }, algebra_map_mem' := λ s, ⟨⊥, set.mem_insert ⊥ c, algebra_map_mem ⊥ s⟩ } /-- The lift on the upper bound on a chain of lifts -/ noncomputable def lifts.upper_bound_alg_hom {c : set (lifts F E K)} (hc : zorn.chain (≤) c) : lifts.upper_bound_intermediate_field hc →ₐ[F] K := { to_fun := λ s, (classical.some s.mem).2 ⟨s, (classical.some_spec s.mem).2⟩, map_zero' := alg_hom.map_zero _, map_one' := alg_hom.map_one _, map_add' := λ s t, begin obtain ⟨w, hw, hxw, hyw, hzw⟩ := lifts.exists_max_three hc (classical.some_spec s.mem).1 (classical.some_spec t.mem).1 (classical.some_spec (s + t).mem).1, rw [lifts.eq_of_le hxw, lifts.eq_of_le hyw, lifts.eq_of_le hzw, ←w.2.map_add], refl, end, map_mul' := λ s t, begin obtain ⟨w, hw, hxw, hyw, hzw⟩ := lifts.exists_max_three hc (classical.some_spec s.mem).1 (classical.some_spec t.mem).1 (classical.some_spec (s * t).mem).1, rw [lifts.eq_of_le hxw, lifts.eq_of_le hyw, lifts.eq_of_le hzw, ←w.2.map_mul], refl, end, commutes' := λ _, alg_hom.commutes _ _ } /-- An upper bound on a chain of lifts -/ noncomputable def lifts.upper_bound {c : set (lifts F E K)} (hc : zorn.chain (≤) c) : lifts F E K := ⟨lifts.upper_bound_intermediate_field hc, lifts.upper_bound_alg_hom hc⟩ lemma lifts.exists_upper_bound (c : set (lifts F E K)) (hc : zorn.chain (≤) c) : ∃ ub, ∀ a ∈ c, a ≤ ub := ⟨lifts.upper_bound hc, begin intros x hx, split, { exact λ s hs, ⟨x, set.mem_insert_of_mem ⊥ hx, hs⟩ }, { intros s t hst, change x.2 s = (classical.some t.mem).2 ⟨t, (classical.some_spec t.mem).2⟩, obtain ⟨z, hz, hxz, hyz⟩ := lifts.exists_max_two hc (set.mem_insert_of_mem ⊥ hx) (classical.some_spec t.mem).1, rw [lifts.eq_of_le hxz, lifts.eq_of_le hyz], exact congr_arg z.2 (subtype.ext hst) }, end⟩ /-- Extend a lift `x : lifts F E K` to an element `s : E` whose conjugates are all in `K` -/ noncomputable def lifts.lift_of_splits (x : lifts F E K) {s : E} (h1 : is_integral F s) (h2 : (minpoly F s).splits (algebra_map F K)) : lifts F E K := let h3 : is_integral x.1 s := is_integral_of_is_scalar_tower s h1 in let key : (minpoly x.1 s).splits x.2.to_ring_hom := splits_of_splits_of_dvd _ (map_ne_zero (minpoly.ne_zero h1)) ((splits_map_iff _ _).mpr (by {convert h2, exact ring_hom.ext (λ y, x.2.commutes y)})) (minpoly.dvd_map_of_is_scalar_tower _ _ _) in ⟨↑x.1⟮s⟯, (@alg_hom_equiv_sigma F x.1 (↑x.1⟮s⟯ : intermediate_field F E) K _ _ _ _ _ _ _ (intermediate_field.algebra x.1⟮s⟯) (is_scalar_tower.of_algebra_map_eq (λ _, rfl))).inv_fun ⟨x.2, (@alg_hom_adjoin_integral_equiv x.1 _ E _ _ s K _ x.2.to_ring_hom.to_algebra h3).inv_fun ⟨root_of_splits x.2.to_ring_hom key (ne_of_gt (minpoly.degree_pos h3)), by { simp_rw [mem_roots (map_ne_zero (minpoly.ne_zero h3)), is_root, ←eval₂_eq_eval_map], exact map_root_of_splits x.2.to_ring_hom key (ne_of_gt (minpoly.degree_pos h3)) }⟩⟩⟩ lemma lifts.le_lifts_of_splits (x : lifts F E K) {s : E} (h1 : is_integral F s) (h2 : (minpoly F s).splits (algebra_map F K)) : x ≤ x.lift_of_splits h1 h2 := ⟨λ z hz, algebra_map_mem x.1⟮s⟯ ⟨z, hz⟩, λ t u htu, eq.symm begin rw [←(show algebra_map x.1 x.1⟮s⟯ t = u, from subtype.ext htu)], letI : algebra x.1 K := x.2.to_ring_hom.to_algebra, exact (alg_hom.commutes _ t), end⟩ lemma lifts.mem_lifts_of_splits (x : lifts F E K) {s : E} (h1 : is_integral F s) (h2 : (minpoly F s).splits (algebra_map F K)) : s ∈ (x.lift_of_splits h1 h2).1 := mem_adjoin_simple_self x.1 s lemma lifts.exists_lift_of_splits (x : lifts F E K) {s : E} (h1 : is_integral F s) (h2 : (minpoly F s).splits (algebra_map F K)) : ∃ y, x ≤ y ∧ s ∈ y.1 := ⟨x.lift_of_splits h1 h2, x.le_lifts_of_splits h1 h2, x.mem_lifts_of_splits h1 h2⟩ lemma alg_hom_mk_adjoin_splits (hK : ∀ s ∈ S, is_integral F (s : E) ∧ (minpoly F s).splits (algebra_map F K)) : nonempty (adjoin F S →ₐ[F] K) := begin obtain ⟨x : lifts F E K, hx⟩ := zorn.zorn_partial_order lifts.exists_upper_bound, refine ⟨alg_hom.mk (λ s, x.2 ⟨s, adjoin_le_iff.mpr (λ s hs, _) s.mem⟩) x.2.map_one (λ s t, x.2.map_mul ⟨s, _⟩ ⟨t, _⟩) x.2.map_zero (λ s t, x.2.map_add ⟨s, _⟩ ⟨t, _⟩) x.2.commutes⟩, rcases (x.exists_lift_of_splits (hK s hs).1 (hK s hs).2) with ⟨y, h1, h2⟩, rwa hx y h1 at h2 end lemma alg_hom_mk_adjoin_splits' (hS : adjoin F S = ⊤) (hK : ∀ x ∈ S, is_integral F (x : E) ∧ (minpoly F x).splits (algebra_map F K)) : nonempty (E →ₐ[F] K) := begin cases alg_hom_mk_adjoin_splits hK with ϕ, rw hS at ϕ, exact ⟨ϕ.comp top_equiv.symm.to_alg_hom⟩, end end alg_hom_mk_adjoin_splits end intermediate_field section power_basis variables {K L : Type*} [field K] [field L] [algebra K L] namespace power_basis open intermediate_field /-- `pb.equiv_adjoin_simple` is the equivalence between `K⟮pb.gen⟯` and `L` itself. -/ noncomputable def equiv_adjoin_simple (pb : power_basis K L) : K⟮pb.gen⟯ ≃ₐ[K] L := (adjoin.power_basis pb.is_integral_gen).equiv pb (minpoly.eq_of_algebra_map_eq (algebra_map K⟮pb.gen⟯ L).injective (adjoin.power_basis pb.is_integral_gen).is_integral_gen (by rw [adjoin.power_basis_gen, adjoin_simple.algebra_map_gen])) @[simp] lemma equiv_adjoin_simple_aeval (pb : power_basis K L) (f : polynomial K) : pb.equiv_adjoin_simple (aeval (adjoin_simple.gen K pb.gen) f) = aeval pb.gen f := equiv_aeval _ pb _ f @[simp] lemma equiv_adjoin_simple_gen (pb : power_basis K L) : pb.equiv_adjoin_simple (adjoin_simple.gen K pb.gen) = pb.gen := equiv_gen _ pb _ @[simp] lemma equiv_adjoin_simple_symm_aeval (pb : power_basis K L) (f : polynomial K) : pb.equiv_adjoin_simple.symm (aeval pb.gen f) = aeval (adjoin_simple.gen K pb.gen) f := by rw [equiv_adjoin_simple, equiv_symm, equiv_aeval, adjoin.power_basis_gen] @[simp] lemma equiv_adjoin_simple_symm_gen (pb : power_basis K L) : pb.equiv_adjoin_simple.symm pb.gen = (adjoin_simple.gen K pb.gen) := by rw [equiv_adjoin_simple, equiv_symm, equiv_gen, adjoin.power_basis_gen] end power_basis end power_basis
16507c3d52662a2fd23b810baea2d705bc2001e4
9bb72db9297f7837f673785604fb89b3184e13f8
/library/init/logic.lean
0cc7cd4b07387803ad45550bec54ffa26d9bb90c
[ "Apache-2.0" ]
permissive
dselsam/lean
ec83d7592199faa85687d884bbaaa570b62c1652
6b0bd5bc2e07e13880d332c89093fe3032bb2469
refs/heads/master
1,621,807,064,966
1,611,454,685,000
1,611,975,642,000
42,734,348
3
3
null
1,498,748,560,000
1,442,594,289,000
C++
UTF-8
Lean
false
false
38,969
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad, Floris van Doorn -/ prelude import init.core universes u v w @[simp] lemma opt_param_eq (α : Sort u) (default : α) : opt_param α default = α := rfl @[inline] def id {α : Sort u} (a : α) : α := a def flip {α : Sort u} {β : Sort v} {φ : Sort w} (f : α → β → φ) : β → α → φ := λ b a, f a b /- implication -/ def implies (a b : Prop) := a → b /-- Implication `→` is transitive. If `P → Q` and `Q → R` then `P → R`. -/ @[trans] lemma implies.trans {p q r : Prop} (h₁ : implies p q) (h₂ : implies q r) : implies p r := assume hp, h₂ (h₁ hp) def trivial : true := ⟨⟩ /-- We can't have `a` and `¬a`, that would be absurd!-/ @[inline] def absurd {a : Prop} {b : Sort v} (h₁ : a) (h₂ : ¬a) : b := false.rec b (h₂ h₁) lemma not.intro {a : Prop} (h : a → false) : ¬ a := h /-- Modus tollens. If an implication is true, then so is its contrapositive. -/ lemma mt {a b : Prop} (h₁ : a → b) (h₂ : ¬b) : ¬a := assume ha : a, h₂ (h₁ ha) /- not -/ lemma not_false : ¬false := id def non_contradictory (a : Prop) : Prop := ¬¬a lemma non_contradictory_intro {a : Prop} (ha : a) : ¬¬a := assume hna : ¬a, absurd ha hna /- false -/ @[inline] def false.elim {C : Sort u} (h : false) : C := false.rec C h /- eq -/ -- proof irrelevance is built in lemma proof_irrel {a : Prop} (h₁ h₂ : a) : h₁ = h₂ := rfl @[simp] lemma id.def {α : Sort u} (a : α) : id a = a := rfl @[inline] def eq.mp {α β : Sort u} : (α = β) → α → β := eq.rec_on @[inline] def eq.mpr {α β : Sort u} : (α = β) → β → α := λ h₁ h₂, eq.rec_on (eq.symm h₁) h₂ @[elab_as_eliminator] lemma eq.substr {α : Sort u} {p : α → Prop} {a b : α} (h₁ : b = a) : p a → p b := eq.subst (eq.symm h₁) lemma congr {α : Sort u} {β : Sort v} {f₁ f₂ : α → β} {a₁ a₂ : α} (h₁ : f₁ = f₂) (h₂ : a₁ = a₂) : f₁ a₁ = f₂ a₂ := eq.subst h₁ (eq.subst h₂ rfl) lemma congr_fun {α : Sort u} {β : α → Sort v} {f g : Π x, β x} (h : f = g) (a : α) : f a = g a := eq.subst h (eq.refl (f a)) lemma congr_arg {α : Sort u} {β : Sort v} {a₁ a₂ : α} (f : α → β) : a₁ = a₂ → f a₁ = f a₂ := congr rfl lemma trans_rel_left {α : Sort u} {a b c : α} (r : α → α → Prop) (h₁ : r a b) (h₂ : b = c) : r a c := h₂ ▸ h₁ lemma trans_rel_right {α : Sort u} {a b c : α} (r : α → α → Prop) (h₁ : a = b) (h₂ : r b c) : r a c := h₁.symm ▸ h₂ lemma of_eq_true {p : Prop} (h : p = true) : p := h.symm ▸ trivial lemma not_of_eq_false {p : Prop} (h : p = false) : ¬p := assume hp, h ▸ hp @[inline] def cast {α β : Sort u} (h : α = β) (a : α) : β := eq.rec a h lemma cast_proof_irrel {α β : Sort u} (h₁ h₂ : α = β) (a : α) : cast h₁ a = cast h₂ a := rfl lemma cast_eq {α : Sort u} (h : α = α) (a : α) : cast h a = a := rfl /- ne -/ @[reducible] def ne {α : Sort u} (a b : α) := ¬(a = b) notation a ≠ b := ne a b @[simp] lemma ne.def {α : Sort u} (a b : α) : a ≠ b = ¬ (a = b) := rfl namespace ne variable {α : Sort u} variables {a b : α} lemma intro (h : a = b → false) : a ≠ b := h lemma elim (h : a ≠ b) : a = b → false := h lemma irrefl (h : a ≠ a) : false := h rfl lemma symm (h : a ≠ b) : b ≠ a := assume (h₁ : b = a), h (h₁.symm) end ne lemma false_of_ne {α : Sort u} {a : α} : a ≠ a → false := ne.irrefl section variables {p : Prop} lemma ne_false_of_self : p → p ≠ false := assume (hp : p) (heq : p = false), heq ▸ hp lemma ne_true_of_not : ¬p → p ≠ true := assume (hnp : ¬p) (heq : p = true), (heq ▸ hnp) trivial lemma true_ne_false : ¬true = false := ne_false_of_self trivial end attribute [refl] heq.refl section variables {α β φ : Sort u} {a a' : α} {b b' : β} {c : φ} lemma heq.elim {α : Sort u} {a : α} {p : α → Sort v} {b : α} (h₁ : a == b) : p a → p b := eq.rec_on (eq_of_heq h₁) lemma heq.subst {p : ∀ T : Sort u, T → Prop} : a == b → p α a → p β b := heq.rec_on @[symm] lemma heq.symm (h : a == b) : b == a := heq.rec_on h (heq.refl a) lemma heq_of_eq (h : a = a') : a == a' := eq.subst h (heq.refl a) @[trans] lemma heq.trans (h₁ : a == b) (h₂ : b == c) : a == c := heq.subst h₂ h₁ @[trans] lemma heq_of_heq_of_eq (h₁ : a == b) (h₂ : b = b') : a == b' := heq.trans h₁ (heq_of_eq h₂) @[trans] lemma heq_of_eq_of_heq (h₁ : a = a') (h₂ : a' == b) : a == b := heq.trans (heq_of_eq h₁) h₂ def type_eq_of_heq (h : a == b) : α = β := heq.rec_on h (eq.refl α) end lemma eq_rec_heq {α : Sort u} {φ : α → Sort v} : ∀ {a a' : α} (h : a = a') (p : φ a), (eq.rec_on h p : φ a') == p | a _ rfl p := heq.refl p lemma heq_of_eq_rec_left {α : Sort u} {φ : α → Sort v} : ∀ {a a' : α} {p₁ : φ a} {p₂ : φ a'} (e : a = a') (h₂ : (eq.rec_on e p₁ : φ a') = p₂), p₁ == p₂ | a _ p₁ p₂ rfl h := eq.rec_on h (heq.refl p₁) lemma heq_of_eq_rec_right {α : Sort u} {φ : α → Sort v} : ∀ {a a' : α} {p₁ : φ a} {p₂ : φ a'} (e : a' = a) (h₂ : p₁ = eq.rec_on e p₂), p₁ == p₂ | a _ p₁ p₂ rfl h := have p₁ = p₂, from h, this ▸ heq.refl p₁ lemma of_heq_true {a : Prop} (h : a == true) : a := of_eq_true (eq_of_heq h) lemma eq_rec_compose : ∀ {α β φ : Sort u} (p₁ : β = φ) (p₂ : α = β) (a : α), (eq.rec_on p₁ (eq.rec_on p₂ a : β) : φ) = eq.rec_on (eq.trans p₂ p₁) a | α _ _ rfl rfl a := rfl lemma cast_heq : ∀ {α β : Sort u} (h : α = β) (a : α), cast h a == a | α _ rfl a := heq.refl a /- and -/ notation a /\ b := and a b notation a ∧ b := and a b variables {a b c d : Prop} lemma and.elim (h₁ : a ∧ b) (h₂ : a → b → c) : c := and.rec h₂ h₁ lemma and.swap : a ∧ b → b ∧ a := assume ⟨ha, hb⟩, ⟨hb, ha⟩ def and.symm := @and.swap /- or -/ notation a \/ b := or a b notation a ∨ b := or a b namespace or lemma elim (h₁ : a ∨ b) (h₂ : a → c) (h₃ : b → c) : c := or.rec h₂ h₃ h₁ end or lemma non_contradictory_em (a : Prop) : ¬¬(a ∨ ¬a) := assume not_em : ¬(a ∨ ¬a), have neg_a : ¬a, from assume pos_a : a, absurd (or.inl pos_a) not_em, absurd (or.inr neg_a) not_em def not_not_em := non_contradictory_em lemma or.swap : a ∨ b → b ∨ a := or.rec or.inr or.inl def or.symm := @or.swap /- xor -/ def xor (a b : Prop) := (a ∧ ¬ b) ∨ (b ∧ ¬ a) /- iff -/ /-- `iff P Q`, with notation `P ↔ Q`, is the proposition asserting that `P` and `Q` are equivalent, that is, have the same truth value. -/ structure iff (a b : Prop) : Prop := intro :: (mp : a → b) (mpr : b → a) notation a <-> b := iff a b notation a ↔ b := iff a b lemma iff.elim : ((a → b) → (b → a) → c) → (a ↔ b) → c := iff.rec attribute [recursor 5] iff.elim lemma iff.elim_left : (a ↔ b) → a → b := iff.mp lemma iff.elim_right : (a ↔ b) → b → a := iff.mpr lemma iff_iff_implies_and_implies (a b : Prop) : (a ↔ b) ↔ (a → b) ∧ (b → a) := iff.intro (λ h, and.intro h.mp h.mpr) (λ h, iff.intro h.left h.right) @[refl] lemma iff.refl (a : Prop) : a ↔ a := iff.intro (assume h, h) (assume h, h) lemma iff.rfl {a : Prop} : a ↔ a := iff.refl a @[trans] lemma iff.trans (h₁ : a ↔ b) (h₂ : b ↔ c) : a ↔ c := iff.intro (assume ha, iff.mp h₂ (iff.mp h₁ ha)) (assume hc, iff.mpr h₁ (iff.mpr h₂ hc)) @[symm] lemma iff.symm (h : a ↔ b) : b ↔ a := iff.intro (iff.elim_right h) (iff.elim_left h) lemma iff.comm : (a ↔ b) ↔ (b ↔ a) := iff.intro iff.symm iff.symm lemma eq.to_iff {a b : Prop} (h : a = b) : a ↔ b := eq.rec_on h iff.rfl lemma neq_of_not_iff {a b : Prop} : ¬(a ↔ b) → a ≠ b := λ h₁ h₂, have a ↔ b, from eq.subst h₂ (iff.refl a), absurd this h₁ lemma not_iff_not_of_iff (h₁ : a ↔ b) : ¬a ↔ ¬b := iff.intro (assume (hna : ¬ a) (hb : b), hna (iff.elim_right h₁ hb)) (assume (hnb : ¬ b) (ha : a), hnb (iff.elim_left h₁ ha)) lemma of_iff_true (h : a ↔ true) : a := iff.mp (iff.symm h) trivial lemma not_of_iff_false : (a ↔ false) → ¬a := iff.mp lemma iff_true_intro (h : a) : a ↔ true := iff.intro (λ hl, trivial) (λ hr, h) lemma iff_false_intro (h : ¬a) : a ↔ false := iff.intro h (false.rec a) lemma not_non_contradictory_iff_absurd (a : Prop) : ¬¬¬a ↔ ¬a := iff.intro (λ (hl : ¬¬¬a) (ha : a), hl (non_contradictory_intro ha)) absurd def not_not_not_iff := not_non_contradictory_iff_absurd lemma imp_congr (h₁ : a ↔ c) (h₂ : b ↔ d) : (a → b) ↔ (c → d) := iff.intro (λ hab hc, iff.mp h₂ (hab (iff.mpr h₁ hc))) (λ hcd ha, iff.mpr h₂ (hcd (iff.mp h₁ ha))) lemma imp_congr_ctx (h₁ : a ↔ c) (h₂ : c → (b ↔ d)) : (a → b) ↔ (c → d) := iff.intro (λ hab hc, have ha : a, from iff.mpr h₁ hc, have hb : b, from hab ha, iff.mp (h₂ hc) hb) (λ hcd ha, have hc : c, from iff.mp h₁ ha, have hd : d, from hcd hc, iff.mpr (h₂ hc) hd) lemma imp_congr_right (h : a → (b ↔ c)) : (a → b) ↔ (a → c) := iff.intro (assume hab ha, iff.elim_left (h ha) (hab ha)) (assume hab ha, iff.elim_right (h ha) (hab ha)) lemma not_not_intro (ha : a) : ¬¬a := assume hna : ¬a, hna ha lemma not_of_not_not_not (h : ¬¬¬a) : ¬a := λ ha, absurd (not_not_intro ha) h @[simp] lemma not_true : (¬ true) ↔ false := iff_false_intro (not_not_intro trivial) def not_true_iff := not_true @[simp] lemma not_false_iff : (¬ false) ↔ true := iff_true_intro not_false @[congr] lemma not_congr (h : a ↔ b) : ¬a ↔ ¬b := iff.intro (λ h₁ h₂, h₁ (iff.mpr h h₂)) (λ h₁ h₂, h₁ (iff.mp h h₂)) @[simp] lemma ne_self_iff_false {α : Sort u} (a : α) : (not (a = a)) ↔ false := iff.intro false_of_ne false.elim @[simp] lemma eq_self_iff_true {α : Sort u} (a : α) : (a = a) ↔ true := iff_true_intro rfl @[simp] lemma heq_self_iff_true {α : Sort u} (a : α) : (a == a) ↔ true := iff_true_intro (heq.refl a) @[simp] lemma iff_not_self (a : Prop) : (a ↔ ¬a) ↔ false := iff_false_intro (λ h, have h' : ¬a, from (λ ha, (iff.mp h ha) ha), h' (iff.mpr h h')) @[simp] lemma not_iff_self (a : Prop) : (¬a ↔ a) ↔ false := iff_false_intro (λ h, have h' : ¬a, from (λ ha, (iff.mpr h ha) ha), h' (iff.mp h h')) @[simp] lemma true_iff_false : (true ↔ false) ↔ false := iff_false_intro (λ h, iff.mp h trivial) @[simp] lemma false_iff_true : (false ↔ true) ↔ false := iff_false_intro (λ h, iff.mpr h trivial) lemma false_of_true_iff_false : (true ↔ false) → false := assume h, iff.mp h trivial lemma false_of_true_eq_false : (true = false) → false := assume h, h ▸ trivial lemma true_eq_false_of_false : false → (true = false) := false.elim lemma eq_comm {α : Sort u} {a b : α} : a = b ↔ b = a := ⟨eq.symm, eq.symm⟩ /- and simp rules -/ lemma and.imp (hac : a → c) (hbd : b → d) : a ∧ b → c ∧ d := assume ⟨ha, hb⟩, ⟨hac ha, hbd hb⟩ def and_implies := @and.imp @[congr] lemma and_congr (h₁ : a ↔ c) (h₂ : b ↔ d) : (a ∧ b) ↔ (c ∧ d) := iff.intro (and.imp (iff.mp h₁) (iff.mp h₂)) (and.imp (iff.mpr h₁) (iff.mpr h₂)) lemma and_congr_right (h : a → (b ↔ c)) : (a ∧ b) ↔ (a ∧ c) := iff.intro (assume ⟨ha, hb⟩, ⟨ha, iff.elim_left (h ha) hb⟩) (assume ⟨ha, hc⟩, ⟨ha, iff.elim_right (h ha) hc⟩) lemma and.comm : a ∧ b ↔ b ∧ a := iff.intro and.swap and.swap lemma and_comm (a b : Prop) : a ∧ b ↔ b ∧ a := and.comm lemma and.assoc : (a ∧ b) ∧ c ↔ a ∧ (b ∧ c) := iff.intro (assume ⟨⟨ha, hb⟩, hc⟩, ⟨ha, ⟨hb, hc⟩⟩) (assume ⟨ha, ⟨hb, hc⟩⟩, ⟨⟨ha, hb⟩, hc⟩) lemma and_assoc (a b : Prop) : (a ∧ b) ∧ c ↔ a ∧ (b ∧ c) := and.assoc lemma and.left_comm : a ∧ (b ∧ c) ↔ b ∧ (a ∧ c) := iff.trans (iff.symm and.assoc) (iff.trans (and_congr and.comm (iff.refl c)) and.assoc) lemma and_iff_left {a b : Prop} (hb : b) : (a ∧ b) ↔ a := iff.intro and.left (λ ha, ⟨ha, hb⟩) lemma and_iff_right {a b : Prop} (ha : a) : (a ∧ b) ↔ b := iff.intro and.right (and.intro ha) @[simp] lemma and_true (a : Prop) : a ∧ true ↔ a := and_iff_left trivial @[simp] lemma true_and (a : Prop) : true ∧ a ↔ a := and_iff_right trivial @[simp] lemma and_false (a : Prop) : a ∧ false ↔ false := iff_false_intro and.right @[simp] lemma false_and (a : Prop) : false ∧ a ↔ false := iff_false_intro and.left @[simp] lemma not_and_self (a : Prop) : (¬a ∧ a) ↔ false := iff_false_intro (λ h, and.elim h (λ h₁ h₂, absurd h₂ h₁)) @[simp] lemma and_not_self (a : Prop) : (a ∧ ¬a) ↔ false := iff_false_intro (assume ⟨h₁, h₂⟩, absurd h₁ h₂) @[simp] lemma and_self (a : Prop) : a ∧ a ↔ a := iff.intro and.left (assume h, ⟨h, h⟩) /- or simp rules -/ lemma or.imp (h₂ : a → c) (h₃ : b → d) : a ∨ b → c ∨ d := or.rec (λ h, or.inl (h₂ h)) (λ h, or.inr (h₃ h)) lemma or.imp_left (h : a → b) : a ∨ c → b ∨ c := or.imp h id lemma or.imp_right (h : a → b) : c ∨ a → c ∨ b := or.imp id h @[congr] lemma or_congr (h₁ : a ↔ c) (h₂ : b ↔ d) : (a ∨ b) ↔ (c ∨ d) := iff.intro (or.imp (iff.mp h₁) (iff.mp h₂)) (or.imp (iff.mpr h₁) (iff.mpr h₂)) lemma or.comm : a ∨ b ↔ b ∨ a := iff.intro or.swap or.swap lemma or_comm (a b : Prop) : a ∨ b ↔ b ∨ a := or.comm lemma or.assoc : (a ∨ b) ∨ c ↔ a ∨ (b ∨ c) := iff.intro (or.rec (or.imp_right or.inl) (λ h, or.inr (or.inr h))) (or.rec (λ h, or.inl (or.inl h)) (or.imp_left or.inr)) lemma or_assoc (a b : Prop) : (a ∨ b) ∨ c ↔ a ∨ (b ∨ c) := or.assoc lemma or.left_comm : a ∨ (b ∨ c) ↔ b ∨ (a ∨ c) := iff.trans (iff.symm or.assoc) (iff.trans (or_congr or.comm (iff.refl c)) or.assoc) theorem or_iff_right_of_imp (ha : a → b) : (a ∨ b) ↔ b := iff.intro (or.rec ha id) or.inr theorem or_iff_left_of_imp (hb : b → a) : (a ∨ b) ↔ a := iff.intro (or.rec id hb) or.inl @[simp] lemma or_true (a : Prop) : a ∨ true ↔ true := iff_true_intro (or.inr trivial) @[simp] lemma true_or (a : Prop) : true ∨ a ↔ true := iff_true_intro (or.inl trivial) @[simp] lemma or_false (a : Prop) : a ∨ false ↔ a := iff.intro (or.rec id false.elim) or.inl @[simp] lemma false_or (a : Prop) : false ∨ a ↔ a := iff.trans or.comm (or_false a) @[simp] lemma or_self (a : Prop) : a ∨ a ↔ a := iff.intro (or.rec id id) or.inl lemma not_or {a b : Prop} : ¬ a → ¬ b → ¬ (a ∨ b) | hna hnb (or.inl ha) := absurd ha hna | hna hnb (or.inr hb) := absurd hb hnb /- or resolution rulse -/ def or.resolve_left {a b : Prop} (h : a ∨ b) (na : ¬ a) : b := or.elim h (λ ha, absurd ha na) id def or.neg_resolve_left {a b : Prop} (h : ¬ a ∨ b) (ha : a) : b := or.elim h (λ na, absurd ha na) id def or.resolve_right {a b : Prop} (h : a ∨ b) (nb : ¬ b) : a := or.elim h id (λ hb, absurd hb nb) def or.neg_resolve_right {a b : Prop} (h : a ∨ ¬ b) (hb : b) : a := or.elim h id (λ nb, absurd hb nb) /- iff simp rules -/ @[simp] lemma iff_true (a : Prop) : (a ↔ true) ↔ a := iff.intro (assume h, iff.mpr h trivial) iff_true_intro @[simp] lemma true_iff (a : Prop) : (true ↔ a) ↔ a := iff.trans iff.comm (iff_true a) @[simp] lemma iff_false (a : Prop) : (a ↔ false) ↔ ¬ a := iff.intro iff.mp iff_false_intro @[simp] lemma false_iff (a : Prop) : (false ↔ a) ↔ ¬ a := iff.trans iff.comm (iff_false a) @[simp] lemma iff_self (a : Prop) : (a ↔ a) ↔ true := iff_true_intro iff.rfl @[congr] lemma iff_congr (h₁ : a ↔ c) (h₂ : b ↔ d) : (a ↔ b) ↔ (c ↔ d) := (iff_iff_implies_and_implies a b).trans ((and_congr (imp_congr h₁ h₂) (imp_congr h₂ h₁)).trans (iff_iff_implies_and_implies c d).symm) /- implies simp rule -/ @[simp] lemma implies_true_iff (α : Sort u) : (α → true) ↔ true := iff.intro (λ h, trivial) (λ ha h, trivial) @[simp] lemma false_implies_iff (a : Prop) : (false → a) ↔ true := iff.intro (λ h, trivial) (λ ha h, false.elim h) @[simp] theorem true_implies_iff (α : Prop) : (true → α) ↔ α := iff.intro (λ h, h trivial) (λ h h', h) /-- The existential quantifier. To prove a goal of the form `⊢ ∃ x, p x`, you can provide a witness `y` with the tactic `existsi y`. If you are working in a project that depends on mathlib, then we recommend the `use` tactic instead. You'll then be left with the goal `⊢ p y`. To extract a witness `x` and proof `hx : p x` from a hypothesis `h : ∃ x, p x`, use the tactic `cases h with x hx`. See also the mathlib tactics `obtain` and `rcases`. -/ inductive Exists {α : Sort u} (p : α → Prop) : Prop | intro (w : α) (h : p w) : Exists attribute [intro] Exists.intro @[pattern] def exists.intro := @Exists.intro notation `exists` binders `, ` r:(scoped P, Exists P) := r notation `∃` binders `, ` r:(scoped P, Exists P) := r lemma exists.elim {α : Sort u} {p : α → Prop} {b : Prop} (h₁ : ∃ x, p x) (h₂ : ∀ (a : α), p a → b) : b := Exists.rec h₂ h₁ /- exists unique -/ def exists_unique {α : Sort u} (p : α → Prop) := ∃ x, p x ∧ ∀ y, p y → y = x notation `∃!` binders `, ` r:(scoped P, exists_unique P) := r @[intro] lemma exists_unique.intro {α : Sort u} {p : α → Prop} (w : α) (h₁ : p w) (h₂ : ∀ y, p y → y = w) : ∃! x, p x := exists.intro w ⟨h₁, h₂⟩ attribute [recursor 4] lemma exists_unique.elim {α : Sort u} {p : α → Prop} {b : Prop} (h₂ : ∃! x, p x) (h₁ : ∀ x, p x → (∀ y, p y → y = x) → b) : b := exists.elim h₂ (λ w hw, h₁ w (and.left hw) (and.right hw)) lemma exists_unique_of_exists_of_unique {α : Type u} {p : α → Prop} (hex : ∃ x, p x) (hunique : ∀ y₁ y₂, p y₁ → p y₂ → y₁ = y₂) : ∃! x, p x := exists.elim hex (λ x px, exists_unique.intro x px (assume y, assume : p y, hunique y x this px)) lemma exists_of_exists_unique {α : Sort u} {p : α → Prop} (h : ∃! x, p x) : ∃ x, p x := exists.elim h (λ x hx, ⟨x, and.left hx⟩) lemma unique_of_exists_unique {α : Sort u} {p : α → Prop} (h : ∃! x, p x) {y₁ y₂ : α} (py₁ : p y₁) (py₂ : p y₂) : y₁ = y₂ := exists_unique.elim h (assume x, assume : p x, assume unique : ∀ y, p y → y = x, show y₁ = y₂, from eq.trans (unique _ py₁) (eq.symm (unique _ py₂))) /- exists, forall, exists unique congruences -/ @[congr] lemma forall_congr {α : Sort u} {p q : α → Prop} (h : ∀ a, (p a ↔ q a)) : (∀ a, p a) ↔ ∀ a, q a := iff.intro (λ p a, iff.mp (h a) (p a)) (λ q a, iff.mpr (h a) (q a)) lemma exists_imp_exists {α : Sort u} {p q : α → Prop} (h : ∀ a, (p a → q a)) (p : ∃ a, p a) : ∃ a, q a := exists.elim p (λ a hp, ⟨a, h a hp⟩) @[congr] lemma exists_congr {α : Sort u} {p q : α → Prop} (h : ∀ a, (p a ↔ q a)) : (Exists p) ↔ ∃ a, q a := iff.intro (exists_imp_exists (λ a, iff.mp (h a))) (exists_imp_exists (λ a, iff.mpr (h a))) @[congr] lemma exists_unique_congr {α : Sort u} {p₁ p₂ : α → Prop} (h : ∀ x, p₁ x ↔ p₂ x) : (exists_unique p₁) ↔ (∃! x, p₂ x) := -- exists_congr (λ x, and_congr (h x) (forall_congr (λ y, imp_congr (h y) iff.rfl))) lemma forall_not_of_not_exists {α : Sort u} {p : α → Prop} : ¬(∃ x, p x) → (∀ x, ¬p x) := λ hne x hp, hne ⟨x, hp⟩ /- decidable -/ def decidable.to_bool (p : Prop) [h : decidable p] : bool := decidable.cases_on h (λ h₁, bool.ff) (λ h₂, bool.tt) export decidable (is_true is_false to_bool) @[simp] lemma to_bool_true_eq_tt (h : decidable true) : @to_bool true h = tt := decidable.cases_on h (λ h, false.elim (iff.mp not_true h)) (λ _, rfl) @[simp] lemma to_bool_false_eq_ff (h : decidable false) : @to_bool false h = ff := decidable.cases_on h (λ h, rfl) (λ h, false.elim h) instance decidable.true : decidable true := is_true trivial instance decidable.false : decidable false := is_false not_false -- We use "dependent" if-then-else to be able to communicate the if-then-else condition -- to the branches @[inline] def dite (c : Prop) [h : decidable c] {α : Sort u} : (c → α) → (¬ c → α) → α := λ t e, decidable.rec_on h e t /- if-then-else -/ @[inline] def ite (c : Prop) [h : decidable c] {α : Sort u} (t e : α) : α := decidable.rec_on h (λ hnc, e) (λ hc, t) namespace decidable variables {p q : Prop} def rec_on_true [h : decidable p] {h₁ : p → Sort u} {h₂ : ¬p → Sort u} (h₃ : p) (h₄ : h₁ h₃) : decidable.rec_on h h₂ h₁ := decidable.rec_on h (λ h, false.rec _ (h h₃)) (λ h, h₄) def rec_on_false [h : decidable p] {h₁ : p → Sort u} {h₂ : ¬p → Sort u} (h₃ : ¬p) (h₄ : h₂ h₃) : decidable.rec_on h h₂ h₁ := decidable.rec_on h (λ h, h₄) (λ h, false.rec _ (h₃ h)) def by_cases {q : Sort u} [φ : decidable p] : (p → q) → (¬p → q) → q := dite _ /-- Law of Excluded Middle. -/ lemma em (p : Prop) [decidable p] : p ∨ ¬p := by_cases or.inl or.inr lemma by_contradiction [decidable p] (h : ¬p → false) : p := if h₁ : p then h₁ else false.rec _ (h h₁) lemma of_not_not [decidable p] : ¬ ¬ p → p := λ hnn, by_contradiction (λ hn, absurd hn hnn) lemma not_not_iff (p) [decidable p] : (¬ ¬ p) ↔ p := iff.intro of_not_not not_not_intro lemma not_and_iff_or_not (p q : Prop) [d₁ : decidable p] [d₂ : decidable q] : ¬ (p ∧ q) ↔ ¬ p ∨ ¬ q := iff.intro (λ h, match d₁ with | is_true h₁ := match d₂ with | is_true h₂ := absurd (and.intro h₁ h₂) h | is_false h₂ := or.inr h₂ end | is_false h₁ := or.inl h₁ end) (λ h ⟨hp, hq⟩, or.elim h (λ h, h hp) (λ h, h hq)) lemma not_or_iff_and_not (p q) [d₁ : decidable p] [d₂ : decidable q] : ¬ (p ∨ q) ↔ ¬ p ∧ ¬ q := iff.intro (λ h, match d₁ with | is_true h₁ := false.elim $ h (or.inl h₁) | is_false h₁ := match d₂ with | is_true h₂ := false.elim $ h (or.inr h₂) | is_false h₂ := ⟨h₁, h₂⟩ end end) (λ ⟨np, nq⟩ h, or.elim h np nq) end decidable section variables {p q : Prop} def decidable_of_decidable_of_iff (hp : decidable p) (h : p ↔ q) : decidable q := if hp : p then is_true (iff.mp h hp) else is_false (iff.mp (not_iff_not_of_iff h) hp) def decidable_of_decidable_of_eq (hp : decidable p) (h : p = q) : decidable q := decidable_of_decidable_of_iff hp h.to_iff protected def or.by_cases [decidable p] [decidable q] {α : Sort u} (h : p ∨ q) (h₁ : p → α) (h₂ : q → α) : α := if hp : p then h₁ hp else if hq : q then h₂ hq else false.rec _ (or.elim h hp hq) end section variables {p q : Prop} instance [decidable p] [decidable q] : decidable (p ∧ q) := if hp : p then if hq : q then is_true ⟨hp, hq⟩ else is_false (assume h : p ∧ q, hq (and.right h)) else is_false (assume h : p ∧ q, hp (and.left h)) instance [decidable p] [decidable q] : decidable (p ∨ q) := if hp : p then is_true (or.inl hp) else if hq : q then is_true (or.inr hq) else is_false (or.rec hp hq) instance [decidable p] : decidable (¬p) := if hp : p then is_false (absurd hp) else is_true hp instance implies.decidable [decidable p] [decidable q] : decidable (p → q) := if hp : p then if hq : q then is_true (assume h, hq) else is_false (assume h : p → q, absurd (h hp) hq) else is_true (assume h, absurd h hp) instance [decidable p] [decidable q] : decidable (p ↔ q) := if hp : p then if hq : q then is_true ⟨λ_, hq, λ_, hp⟩ else is_false $ λh, hq (h.1 hp) else if hq : q then is_false $ λh, hp (h.2 hq) else is_true $ ⟨λh, absurd h hp, λh, absurd h hq⟩ instance [decidable p] [decidable q] : decidable (xor p q) := if hp : p then if hq : q then is_false (or.rec (λ ⟨_, h⟩, h hq : ¬(p ∧ ¬ q)) (λ ⟨_, h⟩, h hp : ¬(q ∧ ¬ p))) else is_true $ or.inl ⟨hp, hq⟩ else if hq : q then is_true $ or.inr ⟨hq, hp⟩ else is_false (or.rec (λ ⟨h, _⟩, hp h : ¬(p ∧ ¬ q)) (λ ⟨h, _⟩, hq h : ¬(q ∧ ¬ p))) instance exists_prop_decidable {p} (P : p → Prop) [Dp : decidable p] [DP : ∀ h, decidable (P h)] : decidable (∃ h, P h) := if h : p then decidable_of_decidable_of_iff (DP h) ⟨λ h2, ⟨h, h2⟩, λ⟨h', h2⟩, h2⟩ else is_false (mt (λ⟨h, _⟩, h) h) instance forall_prop_decidable {p} (P : p → Prop) [Dp : decidable p] [DP : ∀ h, decidable (P h)] : decidable (∀ h, P h) := if h : p then decidable_of_decidable_of_iff (DP h) ⟨λ h2 _, h2, λal, al h⟩ else is_true (λ h2, absurd h2 h) end instance {α : Sort u} [decidable_eq α] (a b : α) : decidable (a ≠ b) := implies.decidable lemma bool.ff_ne_tt : ff = tt → false . def is_dec_eq {α : Sort u} (p : α → α → bool) : Prop := ∀ ⦃x y : α⦄, p x y = tt → x = y def is_dec_refl {α : Sort u} (p : α → α → bool) : Prop := ∀ x, p x x = tt open decidable instance : decidable_eq bool | ff ff := is_true rfl | ff tt := is_false bool.ff_ne_tt | tt ff := is_false (ne.symm bool.ff_ne_tt) | tt tt := is_true rfl def decidable_eq_of_bool_pred {α : Sort u} {p : α → α → bool} (h₁ : is_dec_eq p) (h₂ : is_dec_refl p) : decidable_eq α := assume x y : α, if hp : p x y = tt then is_true (h₁ hp) else is_false (assume hxy : x = y, absurd (h₂ y) (@eq.rec_on _ _ (λ z, ¬p z y = tt) _ hxy hp)) lemma decidable_eq_inl_refl {α : Sort u} [h : decidable_eq α] (a : α) : h a a = is_true (eq.refl a) := match (h a a) with | (is_true e) := rfl | (is_false n) := absurd rfl n end lemma decidable_eq_inr_neg {α : Sort u} [h : decidable_eq α] {a b : α} : Π n : a ≠ b, h a b = is_false n := assume n, match (h a b) with | (is_true e) := absurd e n | (is_false n₁) := proof_irrel n n₁ ▸ eq.refl (is_false n) end /- inhabited -/ class inhabited (α : Sort u) := (default [] : α) export inhabited (default) @[inline, irreducible] def arbitrary (α : Sort u) [inhabited α] : α := default α instance prop.inhabited : inhabited Prop := ⟨true⟩ instance pi.inhabited (α : Sort u) {β : α → Sort v} [Π x, inhabited (β x)] : inhabited (Π x, β x) := ⟨λ a, default (β a)⟩ instance : inhabited bool := ⟨ff⟩ instance : inhabited true := ⟨trivial⟩ class inductive nonempty (α : Sort u) : Prop | intro (val : α) : nonempty protected def nonempty.elim {α : Sort u} {p : Prop} (h₁ : nonempty α) (h₂ : α → p) : p := nonempty.rec h₂ h₁ instance nonempty_of_inhabited {α : Sort u} [inhabited α] : nonempty α := ⟨default α⟩ lemma nonempty_of_exists {α : Sort u} {p : α → Prop} : (∃ x, p x) → nonempty α | ⟨w, h⟩ := ⟨w⟩ /- subsingleton -/ class inductive subsingleton (α : Sort u) : Prop | intro (h : ∀ a b : α, a = b) : subsingleton protected def subsingleton.elim {α : Sort u} [h : subsingleton α] : ∀ (a b : α), a = b := subsingleton.rec (λ p, p) h protected def subsingleton.helim {α β : Sort u} [h : subsingleton α] (h : α = β) : ∀ (a : α) (b : β), a == b := eq.rec_on h (λ a b : α, heq_of_eq (subsingleton.elim a b)) instance subsingleton_prop (p : Prop) : subsingleton p := ⟨λ a b, proof_irrel a b⟩ instance (p : Prop) : subsingleton (decidable p) := subsingleton.intro (λ d₁, match d₁ with | (is_true t₁) := (λ d₂, match d₂ with | (is_true t₂) := eq.rec_on (proof_irrel t₁ t₂) rfl | (is_false f₂) := absurd t₁ f₂ end) | (is_false f₁) := (λ d₂, match d₂ with | (is_true t₂) := absurd t₂ f₁ | (is_false f₂) := eq.rec_on (proof_irrel f₁ f₂) rfl end) end) protected lemma rec_subsingleton {p : Prop} [h : decidable p] {h₁ : p → Sort u} {h₂ : ¬p → Sort u} [h₃ : Π (h : p), subsingleton (h₁ h)] [h₄ : Π (h : ¬p), subsingleton (h₂ h)] : subsingleton (decidable.rec_on h h₂ h₁) := match h with | (is_true h) := h₃ h | (is_false h) := h₄ h end lemma if_pos {c : Prop} [h : decidable c] (hc : c) {α : Sort u} {t e : α} : (ite c t e) = t := match h with | (is_true hc) := rfl | (is_false hnc) := absurd hc hnc end lemma if_neg {c : Prop} [h : decidable c] (hnc : ¬c) {α : Sort u} {t e : α} : (ite c t e) = e := match h with | (is_true hc) := absurd hc hnc | (is_false hnc) := rfl end @[simp] lemma if_t_t (c : Prop) [h : decidable c] {α : Sort u} (t : α) : (ite c t t) = t := match h with | (is_true hc) := rfl | (is_false hnc) := rfl end lemma implies_of_if_pos {c t e : Prop} [decidable c] (h : ite c t e) : c → t := assume hc, eq.rec_on (if_pos hc : ite c t e = t) h lemma implies_of_if_neg {c t e : Prop} [decidable c] (h : ite c t e) : ¬c → e := assume hnc, eq.rec_on (if_neg hnc : ite c t e = e) h lemma if_ctx_congr {α : Sort u} {b c : Prop} [dec_b : decidable b] [dec_c : decidable c] {x y u v : α} (h_c : b ↔ c) (h_t : c → x = u) (h_e : ¬c → y = v) : ite b x y = ite c u v := match dec_b, dec_c with | (is_false h₁), (is_false h₂) := h_e h₂ | (is_true h₁), (is_true h₂) := h_t h₂ | (is_false h₁), (is_true h₂) := absurd h₂ (iff.mp (not_iff_not_of_iff h_c) h₁) | (is_true h₁), (is_false h₂) := absurd h₁ (iff.mpr (not_iff_not_of_iff h_c) h₂) end @[congr] lemma if_congr {α : Sort u} {b c : Prop} [dec_b : decidable b] [dec_c : decidable c] {x y u v : α} (h_c : b ↔ c) (h_t : x = u) (h_e : y = v) : ite b x y = ite c u v := @if_ctx_congr α b c dec_b dec_c x y u v h_c (λ h, h_t) (λ h, h_e) @[simp] lemma if_true {α : Sort u} {h : decidable true} (t e : α) : (@ite true h α t e) = t := if_pos trivial @[simp] lemma if_false {α : Sort u} {h : decidable false} (t e : α) : (@ite false h α t e) = e := if_neg not_false lemma if_ctx_congr_prop {b c x y u v : Prop} [dec_b : decidable b] [dec_c : decidable c] (h_c : b ↔ c) (h_t : c → (x ↔ u)) (h_e : ¬c → (y ↔ v)) : ite b x y ↔ ite c u v := match dec_b, dec_c with | (is_false h₁), (is_false h₂) := h_e h₂ | (is_true h₁), (is_true h₂) := h_t h₂ | (is_false h₁), (is_true h₂) := absurd h₂ (iff.mp (not_iff_not_of_iff h_c) h₁) | (is_true h₁), (is_false h₂) := absurd h₁ (iff.mpr (not_iff_not_of_iff h_c) h₂) end @[congr] lemma if_congr_prop {b c x y u v : Prop} [dec_b : decidable b] [dec_c : decidable c] (h_c : b ↔ c) (h_t : x ↔ u) (h_e : y ↔ v) : ite b x y ↔ ite c u v := if_ctx_congr_prop h_c (λ h, h_t) (λ h, h_e) lemma if_ctx_simp_congr_prop {b c x y u v : Prop} [dec_b : decidable b] (h_c : b ↔ c) (h_t : c → (x ↔ u)) (h_e : ¬c → (y ↔ v)) : ite b x y ↔ (@ite c (decidable_of_decidable_of_iff dec_b h_c) Prop u v) := @if_ctx_congr_prop b c x y u v dec_b (decidable_of_decidable_of_iff dec_b h_c) h_c h_t h_e @[congr] lemma if_simp_congr_prop {b c x y u v : Prop} [dec_b : decidable b] (h_c : b ↔ c) (h_t : x ↔ u) (h_e : y ↔ v) : ite b x y ↔ (@ite c (decidable_of_decidable_of_iff dec_b h_c) Prop u v) := @if_ctx_simp_congr_prop b c x y u v dec_b h_c (λ h, h_t) (λ h, h_e) @[simp] lemma dif_pos {c : Prop} [h : decidable c] (hc : c) {α : Sort u} {t : c → α} {e : ¬ c → α} : dite c t e = t hc := match h with | (is_true hc) := rfl | (is_false hnc) := absurd hc hnc end @[simp] lemma dif_neg {c : Prop} [h : decidable c] (hnc : ¬c) {α : Sort u} {t : c → α} {e : ¬ c → α} : dite c t e = e hnc := match h with | (is_true hc) := absurd hc hnc | (is_false hnc) := rfl end @[congr] lemma dif_ctx_congr {α : Sort u} {b c : Prop} [dec_b : decidable b] [dec_c : decidable c] {x : b → α} {u : c → α} {y : ¬b → α} {v : ¬c → α} (h_c : b ↔ c) (h_t : ∀ (h : c), x (iff.mpr h_c h) = u h) (h_e : ∀ (h : ¬c), y (iff.mpr (not_iff_not_of_iff h_c) h) = v h) : (@dite b dec_b α x y) = (@dite c dec_c α u v) := match dec_b, dec_c with | (is_false h₁), (is_false h₂) := h_e h₂ | (is_true h₁), (is_true h₂) := h_t h₂ | (is_false h₁), (is_true h₂) := absurd h₂ (iff.mp (not_iff_not_of_iff h_c) h₁) | (is_true h₁), (is_false h₂) := absurd h₁ (iff.mpr (not_iff_not_of_iff h_c) h₂) end lemma dif_ctx_simp_congr {α : Sort u} {b c : Prop} [dec_b : decidable b] {x : b → α} {u : c → α} {y : ¬b → α} {v : ¬c → α} (h_c : b ↔ c) (h_t : ∀ (h : c), x (iff.mpr h_c h) = u h) (h_e : ∀ (h : ¬c), y (iff.mpr (not_iff_not_of_iff h_c) h) = v h) : (@dite b dec_b α x y) = (@dite c (decidable_of_decidable_of_iff dec_b h_c) α u v) := @dif_ctx_congr α b c dec_b (decidable_of_decidable_of_iff dec_b h_c) x u y v h_c h_t h_e -- Remark: dite and ite are "defally equal" when we ignore the proofs. lemma dif_eq_if (c : Prop) [h : decidable c] {α : Sort u} (t : α) (e : α) : dite c (λ h, t) (λ h, e) = ite c t e := match h with | (is_true hc) := rfl | (is_false hnc) := rfl end instance {c t e : Prop} [d_c : decidable c] [d_t : decidable t] [d_e : decidable e] : decidable (if c then t else e) := match d_c with | (is_true hc) := d_t | (is_false hc) := d_e end instance {c : Prop} {t : c → Prop} {e : ¬c → Prop} [d_c : decidable c] [d_t : ∀ h, decidable (t h)] [d_e : ∀ h, decidable (e h)] : decidable (if h : c then t h else e h) := match d_c with | (is_true hc) := d_t hc | (is_false hc) := d_e hc end def as_true (c : Prop) [decidable c] : Prop := if c then true else false def as_false (c : Prop) [decidable c] : Prop := if c then false else true def of_as_true {c : Prop} [h₁ : decidable c] (h₂ : as_true c) : c := match h₁, h₂ with | (is_true h_c), h₂ := h_c | (is_false h_c), h₂ := false.elim h₂ end /-- Universe lifting operation -/ structure {r s} ulift (α : Type s) : Type (max s r) := up :: (down : α) namespace ulift /- Bijection between α and ulift.{v} α -/ lemma up_down {α : Type u} : ∀ (b : ulift.{v} α), up (down b) = b | (up a) := rfl lemma down_up {α : Type u} (a : α) : down (up.{v} a) = a := rfl end ulift /-- Universe lifting operation from Sort to Type -/ structure plift (α : Sort u) : Type u := up :: (down : α) namespace plift /- Bijection between α and plift α -/ lemma up_down {α : Sort u} : ∀ (b : plift α), up (down b) = b | (up a) := rfl lemma down_up {α : Sort u} (a : α) : down (up a) = a := rfl end plift /- Equalities for rewriting let-expressions -/ lemma let_value_eq {α : Sort u} {β : Sort v} {a₁ a₂ : α} (b : α → β) : a₁ = a₂ → (let x : α := a₁ in b x) = (let x : α := a₂ in b x) := λ h, eq.rec_on h rfl lemma let_value_heq {α : Sort v} {β : α → Sort u} {a₁ a₂ : α} (b : Π x : α, β x) : a₁ = a₂ → (let x : α := a₁ in b x) == (let x : α := a₂ in b x) := λ h, eq.rec_on h (heq.refl (b a₁)) lemma let_body_eq {α : Sort v} {β : α → Sort u} (a : α) {b₁ b₂ : Π x : α, β x} : (∀ x, b₁ x = b₂ x) → (let x : α := a in b₁ x) = (let x : α := a in b₂ x) := λ h, h a lemma let_eq {α : Sort v} {β : Sort u} {a₁ a₂ : α} {b₁ b₂ : α → β} : a₁ = a₂ → (∀ x, b₁ x = b₂ x) → (let x : α := a₁ in b₁ x) = (let x : α := a₂ in b₂ x) := λ h₁ h₂, eq.rec_on h₁ (h₂ a₁) section relation variables {α : Sort u} {β : Sort v} (r : β → β → Prop) local infix `≺`:50 := r def reflexive := ∀ x, x ≺ x def symmetric := ∀ ⦃x y⦄, x ≺ y → y ≺ x def transitive := ∀ ⦃x y z⦄, x ≺ y → y ≺ z → x ≺ z def equivalence := reflexive r ∧ symmetric r ∧ transitive r def total := ∀ x y, x ≺ y ∨ y ≺ x def mk_equivalence (rfl : reflexive r) (symm : symmetric r) (trans : transitive r) : equivalence r := ⟨rfl, symm, trans⟩ def irreflexive := ∀ x, ¬ x ≺ x def anti_symmetric := ∀ ⦃x y⦄, x ≺ y → y ≺ x → x = y def empty_relation := λ a₁ a₂ : α, false def subrelation (q r : β → β → Prop) := ∀ ⦃x y⦄, q x y → r x y def inv_image (f : α → β) : α → α → Prop := λ a₁ a₂, f a₁ ≺ f a₂ lemma inv_image.trans (f : α → β) (h : transitive r) : transitive (inv_image r f) := λ (a₁ a₂ a₃ : α) (h₁ : inv_image r f a₁ a₂) (h₂ : inv_image r f a₂ a₃), h h₁ h₂ lemma inv_image.irreflexive (f : α → β) (h : irreflexive r) : irreflexive (inv_image r f) := λ (a : α) (h₁ : inv_image r f a a), h (f a) h₁ inductive tc {α : Sort u} (r : α → α → Prop) : α → α → Prop | base : ∀ a b, r a b → tc a b | trans : ∀ a b c, tc a b → tc b c → tc a c end relation section binary variables {α : Type u} {β : Type v} variable f : α → α → α variable inv : α → α variable one : α local notation a * b := f a b local notation a ⁻¹ := inv a variable g : α → α → α local notation a + b := g a b def commutative := ∀ a b, a * b = b * a def associative := ∀ a b c, (a * b) * c = a * (b * c) def left_identity := ∀ a, one * a = a def right_identity := ∀ a, a * one = a def right_inverse := ∀ a, a * a⁻¹ = one def left_cancelative := ∀ a b c, a * b = a * c → b = c def right_cancelative := ∀ a b c, a * b = c * b → a = c def left_distributive := ∀ a b c, a * (b + c) = a * b + a * c def right_distributive := ∀ a b c, (a + b) * c = a * c + b * c def right_commutative (h : β → α → β) := ∀ b a₁ a₂, h (h b a₁) a₂ = h (h b a₂) a₁ def left_commutative (h : α → β → β) := ∀ a₁ a₂ b, h a₁ (h a₂ b) = h a₂ (h a₁ b) lemma left_comm : commutative f → associative f → left_commutative f := assume hcomm hassoc, assume a b c, calc a*(b*c) = (a*b)*c : eq.symm (hassoc a b c) ... = (b*a)*c : hcomm a b ▸ rfl ... = b*(a*c) : hassoc b a c lemma right_comm : commutative f → associative f → right_commutative f := assume hcomm hassoc, assume a b c, calc (a*b)*c = a*(b*c) : hassoc a b c ... = a*(c*b) : hcomm b c ▸ rfl ... = (a*c)*b : eq.symm (hassoc a c b) end binary
b99f0ab64aacec9cd3a1d43485d87e4e84a9a8a8
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Elab/Declaration.lean
f1cf91a4fc8958fe9a2664faabe8790e6b6d296d
[ "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
16,709
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.Util.CollectLevelParams import Lean.Elab.DeclUtil import Lean.Elab.DefView import Lean.Elab.Inductive import Lean.Elab.Structure import Lean.Elab.MutualDef import Lean.Elab.DeclarationRange namespace Lean.Elab.Command open Meta private def ensureValidNamespace (name : Name) : MacroM Unit := do match name with | .str p s => if s == "_root_" then Macro.throwError s!"invalid namespace '{name}', '_root_' is a reserved namespace" ensureValidNamespace p | .num .. => Macro.throwError s!"invalid namespace '{name}', it must not contain numeric parts" | .anonymous => return () private def setDeclIdName (declId : Syntax) (nameNew : Name) : Syntax := let (id, _) := expandDeclIdCore declId -- We should not update the name of `def _root_.` declarations assert! !(`_root_).isPrefixOf id let idStx := mkIdent nameNew |>.raw.setInfo declId.getHeadInfo if declId.isIdent then idStx else declId.setArg 0 idStx /-- Return `true` if `stx` is a `Command.declaration`, and it is a definition that always has a name. -/ private def isNamedDef (stx : Syntax) : Bool := if !stx.isOfKind ``Lean.Parser.Command.declaration then false else let decl := stx[1] let k := decl.getKind k == ``Lean.Parser.Command.abbrev || k == ``Lean.Parser.Command.def || k == ``Lean.Parser.Command.theorem || k == ``Lean.Parser.Command.opaque || k == ``Lean.Parser.Command.axiom || k == ``Lean.Parser.Command.inductive || k == ``Lean.Parser.Command.classInductive || k == ``Lean.Parser.Command.structure /-- Return `true` if `stx` is an `instance` declaration command -/ private def isInstanceDef (stx : Syntax) : Bool := stx.isOfKind ``Lean.Parser.Command.declaration && stx[1].getKind == ``Lean.Parser.Command.instance /-- Return `some name` if `stx` is a definition named `name` -/ private def getDefName? (stx : Syntax) : Option Name := do if isNamedDef stx then let (id, _) := expandDeclIdCore stx[1][1] some id else if isInstanceDef stx then let optDeclId := stx[1][3] if optDeclId.isNone then none else let (id, _) := expandDeclIdCore optDeclId[0] some id else none /-- Update the name of the given definition. This function assumes `stx` is not a nameless instance. -/ private def setDefName (stx : Syntax) (name : Name) : Syntax := if isNamedDef stx then stx.setArg 1 <| stx[1].setArg 1 <| setDeclIdName stx[1][1] name else if isInstanceDef stx then -- We never set the name of nameless instance declarations assert! !stx[1][3].isNone stx.setArg 1 <| stx[1].setArg 3 <| stx[1][3].setArg 0 <| setDeclIdName stx[1][3][0] name else stx /-- Given declarations such as `@[...] def Foo.Bla.f ...` return `some (Foo.Bla, @[...] def f ...)` Remark: if the id starts with `_root_`, we return `none`. -/ private def expandDeclNamespace? (stx : Syntax) : MacroM (Option (Name × Syntax)) := do let some name := getDefName? stx | return none if (`_root_).isPrefixOf name then ensureValidNamespace (name.replacePrefix `_root_ Name.anonymous) return none let scpView := extractMacroScopes name match scpView.name with | .str .anonymous _ => return none | .str pre shortName => return some (pre, setDefName stx { scpView with name := shortName }.review) | _ => return none def elabAxiom (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := do -- leading_parser "axiom " >> declId >> declSig let declId := stx[1] let (binders, typeStx) := expandDeclSig stx[2] let scopeLevelNames ← getLevelNames let ⟨_, declName, allUserLevelNames⟩ ← expandDeclId declId modifiers addDeclarationRanges declName stx runTermElabM fun vars => Term.withDeclName declName <| Term.withLevelNames allUserLevelNames <| Term.elabBinders binders.getArgs fun xs => do Term.applyAttributesAt declName modifiers.attrs AttributeApplicationTime.beforeElaboration let type ← Term.elabType typeStx Term.synthesizeSyntheticMVarsNoPostponing let type ← instantiateMVars type let type ← mkForallFVars xs type let type ← mkForallFVars vars type (usedOnly := true) let type ← Term.levelMVarToParam type let usedParams := collectLevelParams {} type |>.params match sortDeclLevelParams scopeLevelNames allUserLevelNames usedParams with | Except.error msg => throwErrorAt stx msg | Except.ok levelParams => let type ← instantiateMVars type let decl := Declaration.axiomDecl { name := declName, levelParams := levelParams, type := type, isUnsafe := modifiers.isUnsafe } trace[Elab.axiom] "{declName} : {type}" Term.ensureNoUnassignedMVars decl addDecl decl withSaveInfoContext do -- save new env Term.addTermInfo' declId (← mkConstWithLevelParams declName) (isBinder := true) Term.applyAttributesAt declName modifiers.attrs AttributeApplicationTime.afterTypeChecking if isExtern (← getEnv) declName then compileDecl decl Term.applyAttributesAt declName modifiers.attrs AttributeApplicationTime.afterCompilation /- leading_parser "inductive " >> declId >> optDeclSig >> optional ":=" >> many ctor leading_parser atomic (group ("class " >> "inductive ")) >> declId >> optDeclSig >> optional ":=" >> many ctor >> optDeriving -/ private def inductiveSyntaxToView (modifiers : Modifiers) (decl : Syntax) : CommandElabM InductiveView := do checkValidInductiveModifier modifiers let (binders, type?) := expandOptDeclSig decl[2] let declId := decl[1] let ⟨name, declName, levelNames⟩ ← expandDeclId declId modifiers addDeclarationRanges declName decl let ctors ← decl[4].getArgs.mapM fun ctor => withRef ctor do -- def ctor := leading_parser optional docComment >> "\n| " >> declModifiers >> rawIdent >> optDeclSig let mut ctorModifiers ← elabModifiers ctor[2] if let some leadingDocComment := ctor[0].getOptional? then if ctorModifiers.docString?.isSome then logErrorAt leadingDocComment "duplicate doc string" ctorModifiers := { ctorModifiers with docString? := TSyntax.getDocString ⟨leadingDocComment⟩ } if ctorModifiers.isPrivate && modifiers.isPrivate then throwError "invalid 'private' constructor in a 'private' inductive datatype" if ctorModifiers.isProtected && modifiers.isPrivate then throwError "invalid 'protected' constructor in a 'private' inductive datatype" checkValidCtorModifier ctorModifiers let ctorName := ctor.getIdAt 3 let ctorName := declName ++ ctorName let ctorName ← withRef ctor[3] <| applyVisibility ctorModifiers.visibility ctorName let (binders, type?) := expandOptDeclSig ctor[4] addDocString' ctorName ctorModifiers.docString? addAuxDeclarationRanges ctorName ctor ctor[3] return { ref := ctor, modifiers := ctorModifiers, declName := ctorName, binders := binders, type? := type? : CtorView } let computedFields ← (decl[5].getOptional?.map (·[1].getArgs) |>.getD #[]).mapM fun cf => withRef cf do return { ref := cf, modifiers := cf[0], fieldId := cf[1].getId, type := ⟨cf[3]⟩, matchAlts := ⟨cf[4]⟩ } let classes ← getOptDerivingClasses decl[6] return { ref := decl shortDeclName := name derivingClasses := classes declId, modifiers, declName, levelNames binders, type?, ctors computedFields } private def classInductiveSyntaxToView (modifiers : Modifiers) (decl : Syntax) : CommandElabM InductiveView := inductiveSyntaxToView modifiers decl def elabInductive (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := do let v ← inductiveSyntaxToView modifiers stx elabInductiveViews #[v] def elabClassInductive (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := do let modifiers := modifiers.addAttribute { name := `class } let v ← classInductiveSyntaxToView modifiers stx elabInductiveViews #[v] def getTerminationHints (stx : Syntax) : TerminationHints := let decl := stx[1] let k := decl.getKind if k == ``Parser.Command.def || k == ``Parser.Command.abbrev || k == ``Parser.Command.theorem || k == ``Parser.Command.instance then let args := decl.getArgs { terminationBy? := args[args.size - 2]!.getOptional?, decreasingBy? := args[args.size - 1]!.getOptional? } else {} @[builtin_command_elab declaration] def elabDeclaration : CommandElab := fun stx => do match (← liftMacroM <| expandDeclNamespace? stx) with | some (ns, newStx) => do let ns := mkIdentFrom stx ns let newStx ← `(namespace $ns $(⟨newStx⟩) end $ns) withMacroExpansion stx newStx <| elabCommand newStx | none => do let decl := stx[1] let declKind := decl.getKind if declKind == ``Lean.Parser.Command.«axiom» then let modifiers ← elabModifiers stx[0] elabAxiom modifiers decl else if declKind == ``Lean.Parser.Command.«inductive» then let modifiers ← elabModifiers stx[0] elabInductive modifiers decl else if declKind == ``Lean.Parser.Command.classInductive then let modifiers ← elabModifiers stx[0] elabClassInductive modifiers decl else if declKind == ``Lean.Parser.Command.«structure» then let modifiers ← elabModifiers stx[0] elabStructure modifiers decl else if isDefLike decl then elabMutualDef #[stx] (getTerminationHints stx) else throwError "unexpected declaration" /-- Return true if all elements of the mutual-block are inductive declarations. -/ private def isMutualInductive (stx : Syntax) : Bool := stx[1].getArgs.all fun elem => let decl := elem[1] let declKind := decl.getKind declKind == `Lean.Parser.Command.inductive private def elabMutualInductive (elems : Array Syntax) : CommandElabM Unit := do let views ← elems.mapM fun stx => do let modifiers ← elabModifiers stx[0] inductiveSyntaxToView modifiers stx[1] elabInductiveViews views /-- Return true if all elements of the mutual-block are definitions/theorems/abbrevs. -/ private def isMutualDef (stx : Syntax) : Bool := stx[1].getArgs.all fun elem => let decl := elem[1] isDefLike decl private def isMutualPreambleCommand (stx : Syntax) : Bool := let k := stx.getKind k == ``Lean.Parser.Command.variable || k == ``Lean.Parser.Command.universe || k == ``Lean.Parser.Command.check || k == ``Lean.Parser.Command.set_option || k == ``Lean.Parser.Command.open private partial def splitMutualPreamble (elems : Array Syntax) : Option (Array Syntax × Array Syntax) := let rec loop (i : Nat) : Option (Array Syntax × Array Syntax) := if h : i < elems.size then let elem := elems.get ⟨i, h⟩ if isMutualPreambleCommand elem then loop (i+1) else if i == 0 then none -- `mutual` block does not contain any preamble commands else some (elems[0:i], elems[i:elems.size]) else none -- a `mutual` block containing only preamble commands is not a valid `mutual` block loop 0 /-- Find the common namespace for the given names. Example: ``` findCommonPrefix [`Lean.Elab.eval, `Lean.mkConst, `Lean.Elab.Tactic.evalTactic] -- `Lean ``` -/ def findCommonPrefix (ns : List Name) : Name := match ns with | [] => .anonymous | n :: ns => go n ns where go (n : Name) (ns : List Name) : Name := match n with | .anonymous => .anonymous | _ => match ns with | [] => n | n' :: ns => go (findCommon n.components n'.components) ns findCommon (as bs : List Name) : Name := match as, bs with | a :: as, b :: bs => if a == b then a ++ findCommon as bs else .anonymous | _, _ => .anonymous @[builtin_macro Lean.Parser.Command.mutual] def expandMutualNamespace : Macro := fun stx => do let mut nss := #[] for elem in stx[1].getArgs do match (← expandDeclNamespace? elem) with | none => Macro.throwUnsupported | some (n, _) => nss := nss.push n let common := findCommonPrefix nss.toList if common.isAnonymous then Macro.throwUnsupported let elemsNew ← stx[1].getArgs.mapM fun elem => do let some name := getDefName? elem | unreachable! let view := extractMacroScopes name let nameNew := { view with name := view.name.replacePrefix common .anonymous }.review return setDefName elem nameNew let ns := mkIdentFrom stx common let stxNew := stx.setArg 1 (mkNullNode elemsNew) `(namespace $ns $(⟨stxNew⟩) end $ns) @[builtin_macro Lean.Parser.Command.mutual] def expandMutualElement : Macro := fun stx => do let mut elemsNew := #[] let mut modified := false for elem in stx[1].getArgs do match (← expandMacro? elem) with | some elemNew => elemsNew := elemsNew.push elemNew; modified := true | none => elemsNew := elemsNew.push elem if modified then return stx.setArg 1 (mkNullNode elemsNew) else Macro.throwUnsupported @[builtin_macro Lean.Parser.Command.mutual] def expandMutualPreamble : Macro := fun stx => match splitMutualPreamble stx[1].getArgs with | none => Macro.throwUnsupported | some (preamble, rest) => do let secCmd ← `(section) let newMutual := stx.setArg 1 (mkNullNode rest) let endCmd ← `(end) return mkNullNode (#[secCmd] ++ preamble ++ #[newMutual] ++ #[endCmd]) @[builtin_command_elab «mutual»] def elabMutual : CommandElab := fun stx => do let hints := { terminationBy? := stx[3].getOptional?, decreasingBy? := stx[4].getOptional? } if isMutualInductive stx then if let some bad := hints.terminationBy? then throwErrorAt bad "invalid 'termination_by' in mutually inductive datatype declaration" if let some bad := hints.decreasingBy? then throwErrorAt bad "invalid 'decreasing_by' in mutually inductive datatype declaration" elabMutualInductive stx[1].getArgs else if isMutualDef stx then for arg in stx[1].getArgs do let argHints := getTerminationHints arg if let some bad := argHints.terminationBy? then throwErrorAt bad "invalid 'termination_by' in 'mutual' block, it must be used after the 'end' keyword" if let some bad := argHints.decreasingBy? then throwErrorAt bad "invalid 'decreasing_by' in 'mutual' block, it must be used after the 'end' keyword" elabMutualDef stx[1].getArgs hints else throwError "invalid mutual block" /- leading_parser "attribute " >> "[" >> sepBy1 (eraseAttr <|> Term.attrInstance) ", " >> "]" >> many1 ident -/ @[builtin_command_elab «attribute»] def elabAttr : CommandElab := fun stx => do let mut attrInsts := #[] let mut toErase := #[] for attrKindStx in stx[2].getSepArgs do if attrKindStx.getKind == ``Lean.Parser.Command.eraseAttr then let attrName := attrKindStx[1].getId.eraseMacroScopes if isAttribute (← getEnv) attrName then toErase := toErase.push attrName else logErrorAt attrKindStx m!"unknown attribute [{attrName}]" else attrInsts := attrInsts.push attrKindStx let attrs ← elabAttrs attrInsts let idents := stx[4].getArgs for ident in idents do withRef ident <| liftTermElabM do let declName ← resolveGlobalConstNoOverloadWithInfo ident Term.applyAttributes declName attrs for attrName in toErase do Attribute.erase declName attrName @[builtin_macro Lean.Parser.Command.«initialize»] def expandInitialize : Macro | stx@`($declModifiers:declModifiers $kw:initializeKeyword $[$id? : $type? ←]? $doSeq) => do let attrId := mkIdentFrom stx <| if kw.raw[0].isToken "initialize" then `init else `builtin_init if let (some id, some type) := (id?, type?) then let `(Parser.Command.declModifiersT| $[$doc?:docComment]? $[@[$attrs?,*]]? $(vis?)? $[unsafe%$unsafe?]?) := stx[0] | Macro.throwErrorAt declModifiers "invalid initialization command, unexpected modifiers" `($[unsafe%$unsafe?]? def initFn : IO $type := with_decl_name% ?$id do $doSeq $[$doc?:docComment]? @[$attrId:ident initFn, $(attrs?.getD ∅),*] $(vis?)? opaque $id : $type) else let `(Parser.Command.declModifiersT| $[$doc?:docComment]? ) := declModifiers | Macro.throwErrorAt declModifiers "invalid initialization command, unexpected modifiers" `($[$doc?:docComment]? @[$attrId:ident] def initFn : IO Unit := do $doSeq) | _ => Macro.throwUnsupported builtin_initialize registerTraceClass `Elab.axiom end Lean.Elab.Command
6278079cbc31a500fd4a224ba0a30fc77d781654
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch2/ex0307.lean
1abec6d9d473eb87c12ae465d4f849eb52d3b6eb
[]
no_license
Ailrun/Theorem_Proving_in_Lean
ae6a23f3c54d62d401314d6a771e8ff8b4132db2
2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68
refs/heads/master
1,609,838,270,467
1,586,846,743,000
1,586,846,743,000
240,967,761
1
0
null
null
null
null
UTF-8
Lean
false
false
385
lean
constants α β γ : Type constant f : α → β constant g : β → γ constant h : α → α constants (a : α) (b : β) #reduce (λ x : α, x) a #reduce (λ x : α, b) a #reduce (λ x : α, b) (h a) #reduce (λ x : α, g (f x)) a #reduce (λ (v : β → γ) (u : α → β) x, v (u x)) g f a #reduce (λ (Q R S : Type) (v : R → S) (u : Q → R) (x : Q), v (u x)) α β γ g f a
a93d7ad68e173b110a98ead8beb101294c8d9724
9ad8d18fbe5f120c22b5e035bc240f711d2cbd7e
/src/commutative_algebra/nilpotents.lean
955c0b02ececea877559b7be900b19b7beb88f62
[]
no_license
agusakov/lean_lib
c0e9cc29fc7d2518004e224376adeb5e69b5cc1a
f88d162da2f990b87c4d34f5f46bbca2bbc5948e
refs/heads/master
1,642,141,461,087
1,557,395,798,000
1,557,395,798,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,058
lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Neil Strickland This is about the ideal of nilpotent elements in a commutative ring. There is another version in nilpotents.doc.lean with voluminous comments aimed at Lean beginners. -/ import algebra.ring import algebra.group_power import ring_theory.ideals import data.nat.choose import data.zmod.basic import tactic.squeeze open nat finset universe u namespace comm_ring variables {R : Type u} [comm_ring R] def next_pow_zero (x : R) (n : ℕ) := (x ^ (n + 1)) = 0 def is_nilpotent (x : R) : Prop := ∃ n : ℕ, (next_pow_zero x n) lemma npz_zero : next_pow_zero (0 : R) (0 : ℕ) := by {rw[next_pow_zero,_root_.pow_one],} lemma npz_shift {x : R} {n m : ℕ} : (next_pow_zero x n) → (n + 1 ≤ m) → x ^ m = 0 := by {rintros hx hn, dsimp[next_pow_zero] at hx, rw[← (nat.add_sub_of_le hn),_root_.pow_add,hx,zero_mul]} lemma npz_add {x y : R} {n m : ℕ} : (next_pow_zero x n) → (next_pow_zero y m) → next_pow_zero (x + y) (n + m) := λ hx hy, begin unfold next_pow_zero at *, let p := n + m + 1, suffices : ∀ (k : ℕ) (h : k ∈ (range (succ p))), x ^ k * y ^ (p - k) * ↑(choose p k) = 0, {rw[add_pow,sum_congr rfl this,sum_const_zero],}, intros k hk, have k_le : k ≤ p := le_of_lt_succ (mem_range.mp hk), rcases le_or_gt (n + 1) k with n_le | n_gt, {rw[← congr_arg ((^) x) (add_sub_of_le n_le), _root_.pow_add,hx,zero_mul,zero_mul,zero_mul]}, {have : p = k + ((n - k) + (m + 1)) := by {dsimp[p], rw[← nat.add_assoc k,add_sub_of_le (lt_succ_iff.mp n_gt),nat.add_assoc],}, rw[nat.sub_eq_of_eq_add this,_root_.pow_add,hy,mul_zero,mul_zero,zero_mul]} end lemma npz_mul_left (x : R) {y : R} {m : ℕ} : (next_pow_zero y m) → (next_pow_zero (x * y) m) := λ hy, by {unfold next_pow_zero at *,rw[_root_.mul_pow,hy,mul_zero]} lemma npz_mul_right {x : R} {n : ℕ} : (next_pow_zero x n) → ∀ y, (next_pow_zero (x * y) n) := λ hx y, by {unfold next_pow_zero at *,rw[_root_.mul_pow,hx,zero_mul],} lemma npz_chain {x : R} {n m : ℕ} : (next_pow_zero (x ^ (n + 1)) m) → next_pow_zero x (n * m + n + m) := λ hx, begin unfold next_pow_zero at *, have : (n * m + n + m) + 1 = (n + 1) * (m + 1) := by rw[add_mul,mul_add,nat.mul_one,nat.one_mul,nat.add_assoc], rw[this,pow_mul,hx] end lemma nilpotent_zero : is_nilpotent (0 : R) := ⟨0,npz_zero⟩ lemma nilpotent_add {x y : R} : is_nilpotent x → is_nilpotent y → is_nilpotent (x + y) | ⟨n,hx⟩ ⟨m,hy⟩ := ⟨n+m,npz_add hx hy⟩ lemma nilpotent_mul_left (x : R) {y : R} : is_nilpotent y → is_nilpotent (x * y) | ⟨m,hy⟩ := ⟨m,npz_mul_left x hy⟩ lemma nilpotent_mul_right : ∀ {x : R} (xN : is_nilpotent x) (y : R), (is_nilpotent (x * y)) | x ⟨m,hx⟩ y := ⟨m,npz_mul_right hx y⟩ lemma unit_not_nilpotent (x y : R) : (x * y = 1) → ((1 : R) ≠ 0) → ¬ is_nilpotent x := λ hxy hz ⟨m,hx⟩, hz (by {rw[← _root_.one_pow (m + 1),← hxy],exact npz_mul_right hx y}) lemma nilpotent_chain {x : R} {n : ℕ} : is_nilpotent (x ^ (n + 1)) → is_nilpotent x | ⟨m,hx⟩ := ⟨n*m+n+m,npz_chain hx⟩ variable (R) def is_reduced: Prop := ∀ x : R, (is_nilpotent x) → (x = 0) def nilradical : ideal R := { carrier := is_nilpotent, zero := nilpotent_zero, add := @nilpotent_add _ _ , smul := nilpotent_mul_left } def reduced_quotient := (nilradical R).quotient namespace reduced_quotient instance : comm_ring (reduced_quotient R) := by { dsimp[reduced_quotient]; apply_instance } variable {R} def mk : R → reduced_quotient R := ideal.quotient.mk (nilradical R) instance : is_ring_hom mk := ideal.quotient.is_ring_hom_mk (nilradical R) lemma mk_eq_zero_iff {x : R} : mk x = 0 ↔ (is_nilpotent x) := ideal.quotient.eq_zero_iff_mem lemma is_reduced : is_reduced (reduced_quotient R) := begin rintros ⟨x0⟩ ⟨n,e0⟩, apply mk_eq_zero_iff.mpr, have := (is_semiring_hom.map_pow mk x0 (n + 1)).trans e0, have := mk_eq_zero_iff.mp this, exact nilpotent_chain this end end reduced_quotient lemma mem_nilradical (x : R) : x ∈ nilradical R ↔ is_nilpotent x := by {refl} section Z_is_reduced lemma N_reduced (n k : ℕ) : n^(k+1) = 0 → n = 0 := begin cases n with n0, {intro,refl}, {exact λ h0, ((ne_of_lt (nat.pow_pos (nat.zero_lt_succ n0) (k + 1))).symm h0).elim, } end lemma nat_abs_pow : ∀ (n : ℤ) (k : ℕ), int.nat_abs (n ^ k) = (int.nat_abs n) ^ k | n 0 := rfl | n (k + 1) := begin let na := int.nat_abs n, exact calc int.nat_abs (n ^ (k + 1)) = int.nat_abs (n * n^k) : rfl ... = na * (int.nat_abs (n ^ k)) : by rw[int.nat_abs_mul] ... = na * na ^ k : by rw[nat_abs_pow n k] ... = na ^ k * na : by rw[nat.mul_comm] ... = na ^ (k + 1) : rfl end lemma Z_reduced : is_reduced ℤ := begin rintros x ⟨k,e⟩, let x0 := int.nat_abs x, have : (int.nat_abs x)^(k + 1) = 0 := (nat_abs_pow x k.succ).symm.trans (congr_arg int.nat_abs e), have : x0 = 0 := N_reduced (int.nat_abs x) k this, exact int.eq_zero_of_nat_abs_eq_zero this, end end Z_is_reduced section Z4_nilpotents lemma zmod.pow_val {n : ℕ+} (a : zmod n) (m : ℕ) : (a ^ m).val = (a.val ^ m) % n := begin induction m with m0 ih, {simp[has_one.one,monoid.one,ring.one,has_mod.mod,comm_ring.one],}, {exact calc (a ^ (m0 + 1)).val = (a * a^m0).val : rfl ... = (a.val * (a^m0).val) % n : by rw[zmod.mul_val] ... = (a.val * ((a.val ^ m0) % n)) % n : by rw[ih] ... = (a.val * a.val ^ m0) % n : modeq.modeq_mul (modeq.refl a.val) (mod_mod (a.val ^ m0) n) ... = (a.val ^ m0 * a.val) % n : by rw[nat.mul_comm] ... = (a.val ^ (m0 + 1)) % n : rfl } end lemma zmod.nilpotent_iff (n : ℕ+) (k : ℕ) (k_is_lt : k < n) : @is_nilpotent (zmod n) _ ⟨k,k_is_lt⟩ ↔ ∃ m : ℕ, k ^ (m + 1) % n = 0 := begin split, {exact λ ⟨m,h1⟩,⟨m, (@zmod.pow_val n ⟨k,k_is_lt⟩ (m + 1)).symm.trans (congr_arg fin.val h1)⟩, },{ exact λ ⟨m,h1⟩,⟨m,by {apply fin.eq_of_veq,rw[zmod.pow_val],exact h1,}⟩ } end lemma Z4_nilpotents : (nilradical (zmod 4)).carrier = {0,2} := begin have h0 : is_nilpotent (0 : zmod 4) := ⟨0,rfl⟩, have h2 : is_nilpotent (2 : zmod 4) := ⟨1,rfl⟩, have nt : (1 : zmod 4) ≠ 0 := dec_trivial, have h1 : ¬ is_nilpotent (1 : zmod 4) := unit_not_nilpotent 1 1 dec_trivial nt, have h3 : ¬ is_nilpotent (3 : zmod 4) := unit_not_nilpotent 3 3 dec_trivial nt, have h4 : ∀ (i : zmod 4), i ∈ ({0,2} : set (zmod 4)) ↔ i = 2 ∨ i = 0 := λ i, by {simp}, have e1 : ∀ j0 : ℕ, ¬ (j0.succ.succ.succ.succ < 4) := λ j0, dec_trivial, ext j,rw[h4 j],dsimp[nilradical], split, {intro j_nil, rcases j; rcases j_val with _ | _ | _ | _ | j0, {exact dec_trivial}, {exfalso,exact h1 j_nil}, {exact dec_trivial}, {exfalso,exact h3 j_nil}, {exfalso,exact e1 j0 j_is_lt} }, {rintro (j_eq | j_eq) ; rw[j_eq], exact h2,exact h0,} end end Z4_nilpotents end comm_ring
662e403d2f7720a506a3cb425b0d76eb7ac16d84
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/monoidal/of_chosen_finite_products.lean
4eacbff009e52917f0e350eca557e7da0e66e362
[]
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
17,444
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Simon Hudon -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.monoidal.braided import Mathlib.category_theory.limits.shapes.binary_products import Mathlib.category_theory.limits.shapes.terminal import Mathlib.category_theory.pempty import Mathlib.PostPort universes v u namespace Mathlib /-! # The monoidal structure on a category with chosen finite products. This is a variant of the development in `category_theory.monoidal.of_has_finite_products`, which uses specified choices of the terminal object and binary product, enabling the construction of a cartesian category with specific definitions of the tensor unit and tensor product. (Because the construction in `category_theory.monoidal.of_has_finite_products` uses `has_limit` classes, the actual definitions there are opaque behind `classical.choice`.) We use this in `category_theory.monoidal.types` to construct the monoidal category of types so that the tensor product is the usual cartesian product of types. For now we only do the construction from products, and not from coproducts, which seems less often useful. -/ namespace category_theory namespace limits /-- Swap the two sides of a `binary_fan`. -/ def binary_fan.swap {C : Type u} [category C] {P : C} {Q : C} (t : binary_fan P Q) : binary_fan Q P := binary_fan.mk (binary_fan.snd t) (binary_fan.fst t) @[simp] theorem binary_fan.swap_fst {C : Type u} [category C] {P : C} {Q : C} (t : binary_fan P Q) : binary_fan.fst (binary_fan.swap t) = binary_fan.snd t := rfl @[simp] theorem binary_fan.swap_snd {C : Type u} [category C] {P : C} {Q : C} (t : binary_fan P Q) : binary_fan.snd (binary_fan.swap t) = binary_fan.fst t := rfl /-- If a cone `t` over `P Q` is a limit cone, then `t.swap` is a limit cone over `Q P`. -/ @[simp] theorem is_limit.swap_binary_fan_lift {C : Type u} [category C] {P : C} {Q : C} {t : binary_fan P Q} (I : is_limit t) (s : cone (pair Q P)) : is_limit.lift (is_limit.swap_binary_fan I) s = is_limit.lift I (binary_fan.swap s) := Eq.refl (is_limit.lift (is_limit.swap_binary_fan I) s) /-- Construct `has_binary_product Q P` from `has_binary_product P Q`. This can't be an instance, as it would cause a loop in typeclass search. -/ theorem has_binary_product.swap {C : Type u} [category C] (P : C) (Q : C) [has_binary_product P Q] : has_binary_product Q P := has_limit.mk (limit_cone.mk (binary_fan.swap (limit.cone (pair P Q))) (is_limit.swap_binary_fan (limit.is_limit (pair P Q)))) /-- Given a limit cone over `X` and `Y`, and another limit cone over `Y` and `X`, we can construct an isomorphism between the cone points. Relative to some fixed choice of limits cones for every pair, these isomorphisms constitute a braiding. -/ def binary_fan.braiding {C : Type u} [category C] {X : C} {Y : C} {s : binary_fan X Y} (P : is_limit s) {t : binary_fan Y X} (Q : is_limit t) : cone.X s ≅ cone.X t := is_limit.cone_point_unique_up_to_iso P (is_limit.swap_binary_fan Q) /-- Given binary fans `sXY` over `X Y`, and `sYZ` over `Y Z`, and `s` over `sXY.X Z`, if `sYZ` is a limit cone we can construct a binary fan over `X sYZ.X`. This is an ingredient of building the associator for a cartesian category. -/ def binary_fan.assoc {C : Type u} [category C] {X : C} {Y : C} {Z : C} {sXY : binary_fan X Y} {sYZ : binary_fan Y Z} (Q : is_limit sYZ) (s : binary_fan (cone.X sXY) Z) : binary_fan X (cone.X sYZ) := binary_fan.mk (binary_fan.fst s ≫ binary_fan.fst sXY) (is_limit.lift Q (binary_fan.mk (binary_fan.fst s ≫ binary_fan.snd sXY) (binary_fan.snd s))) @[simp] theorem binary_fan.assoc_fst {C : Type u} [category C] {X : C} {Y : C} {Z : C} {sXY : binary_fan X Y} {sYZ : binary_fan Y Z} (Q : is_limit sYZ) (s : binary_fan (cone.X sXY) Z) : binary_fan.fst (binary_fan.assoc Q s) = binary_fan.fst s ≫ binary_fan.fst sXY := rfl @[simp] theorem binary_fan.assoc_snd {C : Type u} [category C] {X : C} {Y : C} {Z : C} {sXY : binary_fan X Y} {sYZ : binary_fan Y Z} (Q : is_limit sYZ) (s : binary_fan (cone.X sXY) Z) : binary_fan.snd (binary_fan.assoc Q s) = is_limit.lift Q (binary_fan.mk (binary_fan.fst s ≫ binary_fan.snd sXY) (binary_fan.snd s)) := rfl /-- Given binary fans `sXY` over `X Y`, and `sYZ` over `Y Z`, and `s` over `X sYZ.X`, if `sYZ` is a limit cone we can construct a binary fan over `sXY.X Z`. This is an ingredient of building the associator for a cartesian category. -/ def binary_fan.assoc_inv {C : Type u} [category C] {X : C} {Y : C} {Z : C} {sXY : binary_fan X Y} (P : is_limit sXY) {sYZ : binary_fan Y Z} (s : binary_fan X (cone.X sYZ)) : binary_fan (cone.X sXY) Z := binary_fan.mk (is_limit.lift P (binary_fan.mk (binary_fan.fst s) (binary_fan.snd s ≫ binary_fan.fst sYZ))) (binary_fan.snd s ≫ binary_fan.snd sYZ) @[simp] theorem binary_fan.assoc_inv_fst {C : Type u} [category C] {X : C} {Y : C} {Z : C} {sXY : binary_fan X Y} (P : is_limit sXY) {sYZ : binary_fan Y Z} (s : binary_fan X (cone.X sYZ)) : binary_fan.fst (binary_fan.assoc_inv P s) = is_limit.lift P (binary_fan.mk (binary_fan.fst s) (binary_fan.snd s ≫ binary_fan.fst sYZ)) := rfl @[simp] theorem binary_fan.assoc_inv_snd {C : Type u} [category C] {X : C} {Y : C} {Z : C} {sXY : binary_fan X Y} (P : is_limit sXY) {sYZ : binary_fan Y Z} (s : binary_fan X (cone.X sYZ)) : binary_fan.snd (binary_fan.assoc_inv P s) = binary_fan.snd s ≫ binary_fan.snd sYZ := rfl /-- If all the binary fans involved a limit cones, `binary_fan.assoc` produces another limit cone. -/ def is_limit.assoc {C : Type u} [category C] {X : C} {Y : C} {Z : C} {sXY : binary_fan X Y} (P : is_limit sXY) {sYZ : binary_fan Y Z} (Q : is_limit sYZ) {s : binary_fan (cone.X sXY) Z} (R : is_limit s) : is_limit (binary_fan.assoc Q s) := is_limit.mk fun (t : cone (pair X (cone.X sYZ))) => is_limit.lift R (binary_fan.assoc_inv P t) /-- Given two pairs of limit cones corresponding to the parenthesisations of `X × Y × Z`, we obtain an isomorphism between the cone points. -/ def binary_fan.associator {C : Type u} [category C] {X : C} {Y : C} {Z : C} {sXY : binary_fan X Y} (P : is_limit sXY) {sYZ : binary_fan Y Z} (Q : is_limit sYZ) {s : binary_fan (cone.X sXY) Z} (R : is_limit s) {t : binary_fan X (cone.X sYZ)} (S : is_limit t) : cone.X s ≅ cone.X t := is_limit.cone_point_unique_up_to_iso (is_limit.assoc P Q R) S /-- Given a fixed family of limit data for every pair `X Y`, we obtain an associator. -/ def binary_fan.associator_of_limit_cone {C : Type u} [category C] (L : (X Y : C) → limit_cone (pair X Y)) (X : C) (Y : C) (Z : C) : cone.X (limit_cone.cone (L (cone.X (limit_cone.cone (L X Y))) Z)) ≅ cone.X (limit_cone.cone (L X (cone.X (limit_cone.cone (L Y Z))))) := binary_fan.associator (limit_cone.is_limit (L X Y)) (limit_cone.is_limit (L Y Z)) (limit_cone.is_limit (L (cone.X (limit_cone.cone (L X Y))) Z)) (limit_cone.is_limit (L X (cone.X (limit_cone.cone (L Y Z))))) /-- Construct a left unitor from specified limit cones. -/ def binary_fan.left_unitor {C : Type u} [category C] {X : C} {s : cone (functor.empty C)} (P : is_limit s) {t : binary_fan (cone.X s) X} (Q : is_limit t) : cone.X t ≅ X := iso.mk (binary_fan.snd t) (is_limit.lift Q (binary_fan.mk (is_limit.lift P (cone.mk X (nat_trans.mk (pempty.rec fun (n : pempty) => functor.obj (functor.obj (functor.const (discrete pempty)) X) n ⟶ functor.obj (functor.empty C) n)))) 𝟙)) /-- Construct a right unitor from specified limit cones. -/ def binary_fan.right_unitor {C : Type u} [category C] {X : C} {s : cone (functor.empty C)} (P : is_limit s) {t : binary_fan X (cone.X s)} (Q : is_limit t) : cone.X t ≅ X := iso.mk (binary_fan.fst t) (is_limit.lift Q (binary_fan.mk 𝟙 (is_limit.lift P (cone.mk X (nat_trans.mk (pempty.rec fun (n : pempty) => functor.obj (functor.obj (functor.const (discrete pempty)) X) n ⟶ functor.obj (functor.empty C) n)))))) end limits namespace monoidal_of_chosen_finite_products /-- Implementation of the tensor product for `monoidal_of_chosen_finite_products`. -/ def tensor_obj {C : Type u} [category C] (ℬ : (X Y : C) → limits.limit_cone (limits.pair X Y)) (X : C) (Y : C) : C := limits.cone.X (limits.limit_cone.cone (ℬ X Y)) /-- Implementation of the tensor product of morphisms for `monoidal_of_chosen_finite_products`. -/ def tensor_hom {C : Type u} [category C] (ℬ : (X Y : C) → limits.limit_cone (limits.pair X Y)) {W : C} {X : C} {Y : C} {Z : C} (f : W ⟶ X) (g : Y ⟶ Z) : tensor_obj ℬ W Y ⟶ tensor_obj ℬ X Z := subtype.val (limits.binary_fan.is_limit.lift' (limits.limit_cone.is_limit (ℬ X Z)) (nat_trans.app (limits.cone.π (limits.limit_cone.cone (ℬ W Y))) limits.walking_pair.left ≫ f) (nat_trans.app (limits.cone.π (limits.limit_cone.cone (ℬ W Y))) limits.walking_pair.right ≫ g)) theorem tensor_id {C : Type u} [category C] (ℬ : (X Y : C) → limits.limit_cone (limits.pair X Y)) (X₁ : C) (X₂ : C) : tensor_hom ℬ 𝟙 𝟙 = 𝟙 := sorry theorem tensor_comp {C : Type u} [category C] (ℬ : (X Y : C) → limits.limit_cone (limits.pair X Y)) {X₁ : C} {Y₁ : C} {Z₁ : C} {X₂ : C} {Y₂ : C} {Z₂ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (g₁ : Y₁ ⟶ Z₁) (g₂ : Y₂ ⟶ Z₂) : tensor_hom ℬ (f₁ ≫ g₁) (f₂ ≫ g₂) = tensor_hom ℬ f₁ f₂ ≫ tensor_hom ℬ g₁ g₂ := sorry theorem pentagon {C : Type u} [category C] (ℬ : (X Y : C) → limits.limit_cone (limits.pair X Y)) (W : C) (X : C) (Y : C) (Z : C) : tensor_hom ℬ (iso.hom (limits.binary_fan.associator_of_limit_cone ℬ W X Y)) 𝟙 ≫ iso.hom (limits.binary_fan.associator_of_limit_cone ℬ W (tensor_obj ℬ X Y) Z) ≫ tensor_hom ℬ 𝟙 (iso.hom (limits.binary_fan.associator_of_limit_cone ℬ X Y Z)) = iso.hom (limits.binary_fan.associator_of_limit_cone ℬ (tensor_obj ℬ W X) Y Z) ≫ iso.hom (limits.binary_fan.associator_of_limit_cone ℬ W X (tensor_obj ℬ Y Z)) := sorry theorem triangle {C : Type u} [category C] (𝒯 : limits.limit_cone (functor.empty C)) (ℬ : (X Y : C) → limits.limit_cone (limits.pair X Y)) (X : C) (Y : C) : iso.hom (limits.binary_fan.associator_of_limit_cone ℬ X (limits.cone.X (limits.limit_cone.cone 𝒯)) Y) ≫ tensor_hom ℬ 𝟙 (iso.hom (limits.binary_fan.left_unitor (limits.limit_cone.is_limit 𝒯) (limits.limit_cone.is_limit (ℬ (limits.cone.X (limits.limit_cone.cone 𝒯)) Y)))) = tensor_hom ℬ (iso.hom (limits.binary_fan.right_unitor (limits.limit_cone.is_limit 𝒯) (limits.limit_cone.is_limit (ℬ X (limits.cone.X (limits.limit_cone.cone 𝒯)))))) 𝟙 := sorry theorem left_unitor_naturality {C : Type u} [category C] (𝒯 : limits.limit_cone (functor.empty C)) (ℬ : (X Y : C) → limits.limit_cone (limits.pair X Y)) {X₁ : C} {X₂ : C} (f : X₁ ⟶ X₂) : tensor_hom ℬ 𝟙 f ≫ iso.hom (limits.binary_fan.left_unitor (limits.limit_cone.is_limit 𝒯) (limits.limit_cone.is_limit (ℬ (limits.cone.X (limits.limit_cone.cone 𝒯)) X₂))) = iso.hom (limits.binary_fan.left_unitor (limits.limit_cone.is_limit 𝒯) (limits.limit_cone.is_limit (ℬ (limits.cone.X (limits.limit_cone.cone 𝒯)) X₁))) ≫ f := sorry theorem right_unitor_naturality {C : Type u} [category C] (𝒯 : limits.limit_cone (functor.empty C)) (ℬ : (X Y : C) → limits.limit_cone (limits.pair X Y)) {X₁ : C} {X₂ : C} (f : X₁ ⟶ X₂) : tensor_hom ℬ f 𝟙 ≫ iso.hom (limits.binary_fan.right_unitor (limits.limit_cone.is_limit 𝒯) (limits.limit_cone.is_limit (ℬ X₂ (limits.cone.X (limits.limit_cone.cone 𝒯))))) = iso.hom (limits.binary_fan.right_unitor (limits.limit_cone.is_limit 𝒯) (limits.limit_cone.is_limit (ℬ X₁ (limits.cone.X (limits.limit_cone.cone 𝒯))))) ≫ f := sorry theorem associator_naturality {C : Type u} [category C] (ℬ : (X Y : C) → limits.limit_cone (limits.pair X Y)) {X₁ : C} {X₂ : C} {X₃ : C} {Y₁ : C} {Y₂ : C} {Y₃ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (f₃ : X₃ ⟶ Y₃) : tensor_hom ℬ (tensor_hom ℬ f₁ f₂) f₃ ≫ iso.hom (limits.binary_fan.associator_of_limit_cone ℬ Y₁ Y₂ Y₃) = iso.hom (limits.binary_fan.associator_of_limit_cone ℬ X₁ X₂ X₃) ≫ tensor_hom ℬ f₁ (tensor_hom ℬ f₂ f₃) := sorry end monoidal_of_chosen_finite_products /-- A category with a terminal object and binary products has a natural monoidal structure. -/ def monoidal_of_chosen_finite_products {C : Type u} [category C] (𝒯 : limits.limit_cone (functor.empty C)) (ℬ : (X Y : C) → limits.limit_cone (limits.pair X Y)) : monoidal_category C := monoidal_category.mk (fun (X Y : C) => sorry) (fun (_x _x_1 _x_2 _x_3 : C) (f : _x ⟶ _x_1) (g : _x_2 ⟶ _x_3) => sorry) (limits.cone.X (limits.limit_cone.cone 𝒯)) (fun (X Y Z : C) => limits.binary_fan.associator_of_limit_cone ℬ X Y Z) (fun (X : C) => limits.binary_fan.left_unitor (limits.limit_cone.is_limit 𝒯) (limits.limit_cone.is_limit (ℬ (limits.cone.X (limits.limit_cone.cone 𝒯)) X))) fun (X : C) => limits.binary_fan.right_unitor (limits.limit_cone.is_limit 𝒯) (limits.limit_cone.is_limit (ℬ X (limits.cone.X (limits.limit_cone.cone 𝒯)))) namespace monoidal_of_chosen_finite_products /-- A type synonym for `C` carrying a monoidal category structure corresponding to a fixed choice of limit data for the empty functor, and for `pair X Y` for every `X Y : C`. This is an implementation detail for `symmetric_of_chosen_finite_products`. -/ def monoidal_of_chosen_finite_products_synonym {C : Type u} [category C] (𝒯 : limits.limit_cone (functor.empty C)) (ℬ : (X Y : C) → limits.limit_cone (limits.pair X Y)) := C protected instance monoidal_of_chosen_finite_products_synonym.category_theory.monoidal_category {C : Type u} [category C] (𝒯 : limits.limit_cone (functor.empty C)) (ℬ : (X Y : C) → limits.limit_cone (limits.pair X Y)) : monoidal_category (monoidal_of_chosen_finite_products_synonym 𝒯 ℬ) := monoidal_of_chosen_finite_products 𝒯 ℬ theorem braiding_naturality {C : Type u} [category C] (ℬ : (X Y : C) → limits.limit_cone (limits.pair X Y)) {X : C} {X' : C} {Y : C} {Y' : C} (f : X ⟶ Y) (g : X' ⟶ Y') : tensor_hom ℬ f g ≫ iso.hom (limits.binary_fan.braiding (limits.limit_cone.is_limit (ℬ Y Y')) (limits.limit_cone.is_limit (ℬ Y' Y))) = iso.hom (limits.binary_fan.braiding (limits.limit_cone.is_limit (ℬ X X')) (limits.limit_cone.is_limit (ℬ X' X))) ≫ tensor_hom ℬ g f := sorry theorem hexagon_forward {C : Type u} [category C] (ℬ : (X Y : C) → limits.limit_cone (limits.pair X Y)) (X : C) (Y : C) (Z : C) : iso.hom (limits.binary_fan.associator_of_limit_cone ℬ X Y Z) ≫ iso.hom (limits.binary_fan.braiding (limits.limit_cone.is_limit (ℬ X (tensor_obj ℬ Y Z))) (limits.limit_cone.is_limit (ℬ (tensor_obj ℬ Y Z) X))) ≫ iso.hom (limits.binary_fan.associator_of_limit_cone ℬ Y Z X) = tensor_hom ℬ (iso.hom (limits.binary_fan.braiding (limits.limit_cone.is_limit (ℬ X Y)) (limits.limit_cone.is_limit (ℬ Y X)))) 𝟙 ≫ iso.hom (limits.binary_fan.associator_of_limit_cone ℬ Y X Z) ≫ tensor_hom ℬ 𝟙 (iso.hom (limits.binary_fan.braiding (limits.limit_cone.is_limit (ℬ X Z)) (limits.limit_cone.is_limit (ℬ Z X)))) := sorry theorem hexagon_reverse {C : Type u} [category C] (ℬ : (X Y : C) → limits.limit_cone (limits.pair X Y)) (X : C) (Y : C) (Z : C) : iso.inv (limits.binary_fan.associator_of_limit_cone ℬ X Y Z) ≫ iso.hom (limits.binary_fan.braiding (limits.limit_cone.is_limit (ℬ (tensor_obj ℬ X Y) Z)) (limits.limit_cone.is_limit (ℬ Z (tensor_obj ℬ X Y)))) ≫ iso.inv (limits.binary_fan.associator_of_limit_cone ℬ Z X Y) = tensor_hom ℬ 𝟙 (iso.hom (limits.binary_fan.braiding (limits.limit_cone.is_limit (ℬ Y Z)) (limits.limit_cone.is_limit (ℬ Z Y)))) ≫ iso.inv (limits.binary_fan.associator_of_limit_cone ℬ X Z Y) ≫ tensor_hom ℬ (iso.hom (limits.binary_fan.braiding (limits.limit_cone.is_limit (ℬ X Z)) (limits.limit_cone.is_limit (ℬ Z X)))) 𝟙 := sorry theorem symmetry {C : Type u} [category C] (ℬ : (X Y : C) → limits.limit_cone (limits.pair X Y)) (X : C) (Y : C) : iso.hom (limits.binary_fan.braiding (limits.limit_cone.is_limit (ℬ X Y)) (limits.limit_cone.is_limit (ℬ Y X))) ≫ iso.hom (limits.binary_fan.braiding (limits.limit_cone.is_limit (ℬ Y X)) (limits.limit_cone.is_limit (ℬ X Y))) = 𝟙 := sorry end monoidal_of_chosen_finite_products /-- The monoidal structure coming from finite products is symmetric. -/ def symmetric_of_chosen_finite_products {C : Type u} [category C] (𝒯 : limits.limit_cone (functor.empty C)) (ℬ : (X Y : C) → limits.limit_cone (limits.pair X Y)) : symmetric_category (monoidal_of_chosen_finite_products.monoidal_of_chosen_finite_products_synonym 𝒯 ℬ) := symmetric_category.mk
3dcd20d951502b7d8d74d9a6ed1b3889bb561cf1
d72901cc240bd78b8b0384565e4f4dee8abd3a86
/src/data/set/lattice.lean
745ce9c58b360a11c9fa45269b9d791674d63e3e
[ "Apache-2.0" ]
permissive
leon-volq/mathlib
513b24765349bb5187df9d898b92beadf96124d9
0cc93a137e9b2e243f8ae1f808fa7225ce0fe143
refs/heads/master
1,676,294,376,990
1,610,838,688,000
1,610,838,688,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
49,513
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Johannes Hölzl, Mario Carneiro -- QUESTION: can make the first argument in ∀ x ∈ a, ... implicit? -/ import order.complete_boolean_algebra import data.sigma.basic import order.galois_connection import order.directed open function tactic set auto universes u v w x y variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} {ι' : Sort y} namespace set instance lattice_set : complete_lattice (set α) := { Sup := λs, {a | ∃ t ∈ s, a ∈ t }, Inf := λs, {a | ∀ t ∈ s, a ∈ t }, le_Sup := assume s t t_in a a_in, ⟨t, ⟨t_in, a_in⟩⟩, Sup_le := assume s t h a ⟨t', ⟨t'_in, a_in⟩⟩, h t' t'_in a_in, le_Inf := assume s t h a a_in t' t'_in, h t' t'_in a_in, Inf_le := assume s t t_in a h, h _ t_in, .. set.boolean_algebra, .. (infer_instance : complete_lattice (α → Prop)) } /-- Image is monotone. See `set.image_image` for the statement in terms of `⊆`. -/ lemma monotone_image {f : α → β} : monotone (image f) := assume s t, assume h : s ⊆ t, image_subset _ h theorem monotone_inter [preorder β] {f g : β → set α} (hf : monotone f) (hg : monotone g) : monotone (λx, f x ∩ g x) := assume b₁ b₂ h, inter_subset_inter (hf h) (hg h) theorem monotone_union [preorder β] {f g : β → set α} (hf : monotone f) (hg : monotone g) : monotone (λx, f x ∪ g x) := assume b₁ b₂ h, union_subset_union (hf h) (hg h) theorem monotone_set_of [preorder α] {p : α → β → Prop} (hp : ∀b, monotone (λa, p a b)) : monotone (λa, {b | p a b}) := assume a a' h b, hp b h section galois_connection variables {f : α → β} protected lemma image_preimage : galois_connection (image f) (preimage f) := assume a b, image_subset_iff /-- `kern_image f s` is the set of `y` such that `f ⁻¹ y ⊆ s` -/ def kern_image (f : α → β) (s : set α) : set β := {y | ∀ ⦃x⦄, f x = y → x ∈ s} protected lemma preimage_kern_image : galois_connection (preimage f) (kern_image f) := assume a b, ⟨ assume h x hx y hy, have f y ∈ a, from hy.symm ▸ hx, h this, assume h x (hx : f x ∈ a), h hx rfl⟩ end galois_connection /- union and intersection over a family of sets indexed by a type -/ /-- Indexed union of a family of sets -/ @[reducible] def Union (s : ι → set β) : set β := supr s /-- Indexed intersection of a family of sets -/ @[reducible] def Inter (s : ι → set β) : set β := infi s notation `⋃` binders `, ` r:(scoped f, Union f) := r notation `⋂` binders `, ` r:(scoped f, Inter f) := r @[simp] theorem mem_Union {x : β} {s : ι → set β} : x ∈ Union s ↔ ∃ i, x ∈ s i := ⟨assume ⟨t, ⟨⟨a, (t_eq : s a = t)⟩, (h : x ∈ t)⟩⟩, ⟨a, t_eq.symm ▸ h⟩, assume ⟨a, h⟩, ⟨s a, ⟨⟨a, rfl⟩, h⟩⟩⟩ /- alternative proof: dsimp [Union, supr, Sup]; simp -/ -- TODO: more rewrite rules wrt forall / existentials and logical connectives -- TODO: also eliminate ∃i, ... ∧ i = t ∧ ... theorem set_of_exists (p : ι → β → Prop) : {x | ∃ i, p i x} = ⋃ i, {x | p i x} := ext $ λ i, mem_Union.symm @[simp] theorem mem_Inter {x : β} {s : ι → set β} : x ∈ Inter s ↔ ∀ i, x ∈ s i := ⟨assume (h : ∀a ∈ {a : set β | ∃i, s i = a}, x ∈ a) a, h (s a) ⟨a, rfl⟩, assume h t ⟨a, (eq : s a = t)⟩, eq ▸ h a⟩ theorem set_of_forall (p : ι → β → Prop) : {x | ∀ i, p i x} = ⋂ i, {x | p i x} := ext $ λ i, mem_Inter.symm theorem Union_subset {s : ι → set β} {t : set β} (h : ∀ i, s i ⊆ t) : (⋃ i, s i) ⊆ t := -- TODO: should be simpler when sets' order is based on lattices @supr_le (set β) _ set.lattice_set _ _ h theorem Union_subset_iff {s : ι → set β} {t : set β} : (⋃ i, s i) ⊆ t ↔ (∀ i, s i ⊆ t) := ⟨assume h i, subset.trans (le_supr s _) h, Union_subset⟩ theorem mem_Inter_of_mem {x : β} {s : ι → set β} : (∀ i, x ∈ s i) → (x ∈ ⋂ i, s i) := mem_Inter.2 theorem subset_Inter {t : set β} {s : ι → set β} (h : ∀ i, t ⊆ s i) : t ⊆ ⋂ i, s i := -- TODO: should be simpler when sets' order is based on lattices @le_infi (set β) _ set.lattice_set _ _ h theorem subset_Inter_iff {t : set β} {s : ι → set β} : t ⊆ (⋂ i, s i) ↔ ∀ i, t ⊆ s i := @le_infi_iff (set β) _ set.lattice_set _ _ theorem subset_Union : ∀ (s : ι → set β) (i : ι), s i ⊆ (⋃ i, s i) := le_supr -- This rather trivial consequence is convenient with `apply`, -- and has `i` explicit for this use case. theorem subset_subset_Union {A : set β} {s : ι → set β} (i : ι) (h : A ⊆ s i) : A ⊆ ⋃ (i : ι), s i := subset.trans h (subset_Union s i) theorem Inter_subset : ∀ (s : ι → set β) (i : ι), (⋂ i, s i) ⊆ s i := infi_le lemma Inter_subset_of_subset {s : ι → set α} {t : set α} (i : ι) (h : s i ⊆ t) : (⋂ i, s i) ⊆ t := set.subset.trans (set.Inter_subset s i) h lemma Inter_subset_Inter {s t : ι → set α} (h : ∀ i, s i ⊆ t i) : (⋂ i, s i) ⊆ (⋂ i, t i) := set.subset_Inter $ λ i, set.Inter_subset_of_subset i (h i) lemma Inter_subset_Inter2 {s : ι → set α} {t : ι' → set α} (h : ∀ j, ∃ i, s i ⊆ t j) : (⋂ i, s i) ⊆ (⋂ j, t j) := set.subset_Inter $ λ j, let ⟨i, hi⟩ := h j in Inter_subset_of_subset i hi lemma Inter_set_of (P : ι → α → Prop) : (⋂ i, {x : α | P i x }) = {x : α | ∀ i, P i x} := by { ext, simp } theorem Union_const [nonempty ι] (s : set β) : (⋃ i:ι, s) = s := ext $ by simp theorem Inter_const [nonempty ι] (s : set β) : (⋂ i:ι, s) = s := ext $ by simp @[simp] -- complete_boolean_algebra theorem compl_Union (s : ι → set β) : (⋃ i, s i)ᶜ = (⋂ i, (s i)ᶜ) := ext (by simp) -- classical -- complete_boolean_algebra theorem compl_Inter (s : ι → set β) : (⋂ i, s i)ᶜ = (⋃ i, (s i)ᶜ) := ext (λ x, by simp [not_forall]) -- classical -- complete_boolean_algebra theorem Union_eq_comp_Inter_comp (s : ι → set β) : (⋃ i, s i) = (⋂ i, (s i)ᶜ)ᶜ := by simp [compl_Inter, compl_compl] -- classical -- complete_boolean_algebra theorem Inter_eq_comp_Union_comp (s : ι → set β) : (⋂ i, s i) = (⋃ i, (s i)ᶜ)ᶜ := by simp [compl_compl] theorem inter_Union (s : set β) (t : ι → set β) : s ∩ (⋃ i, t i) = ⋃ i, s ∩ t i := ext $ by simp theorem Union_inter (s : set β) (t : ι → set β) : (⋃ i, t i) ∩ s = ⋃ i, t i ∩ s := ext $ by simp theorem Union_union_distrib (s : ι → set β) (t : ι → set β) : (⋃ i, s i ∪ t i) = (⋃ i, s i) ∪ (⋃ i, t i) := ext $ by simp [exists_or_distrib] theorem Inter_inter_distrib (s : ι → set β) (t : ι → set β) : (⋂ i, s i ∩ t i) = (⋂ i, s i) ∩ (⋂ i, t i) := ext $ by simp [forall_and_distrib] theorem union_Union [nonempty ι] (s : set β) (t : ι → set β) : s ∪ (⋃ i, t i) = ⋃ i, s ∪ t i := by rw [Union_union_distrib, Union_const] theorem Union_union [nonempty ι] (s : set β) (t : ι → set β) : (⋃ i, t i) ∪ s = ⋃ i, t i ∪ s := by rw [Union_union_distrib, Union_const] theorem inter_Inter [nonempty ι] (s : set β) (t : ι → set β) : s ∩ (⋂ i, t i) = ⋂ i, s ∩ t i := by rw [Inter_inter_distrib, Inter_const] theorem Inter_inter [nonempty ι] (s : set β) (t : ι → set β) : (⋂ i, t i) ∩ s = ⋂ i, t i ∩ s := by rw [Inter_inter_distrib, Inter_const] -- classical theorem union_Inter (s : set β) (t : ι → set β) : s ∪ (⋂ i, t i) = ⋂ i, s ∪ t i := ext $ assume x, by simp [forall_or_distrib_left] theorem Union_diff (s : set β) (t : ι → set β) : (⋃ i, t i) \ s = ⋃ i, t i \ s := Union_inter _ _ theorem diff_Union [nonempty ι] (s : set β) (t : ι → set β) : s \ (⋃ i, t i) = ⋂ i, s \ t i := by rw [diff_eq, compl_Union, inter_Inter]; refl theorem diff_Inter (s : set β) (t : ι → set β) : s \ (⋂ i, t i) = ⋃ i, s \ t i := by rw [diff_eq, compl_Inter, inter_Union]; refl lemma directed_on_Union {r} {ι : Sort v} {f : ι → set α} (hd : directed (⊆) f) (h : ∀x, directed_on r (f x)) : directed_on r (⋃x, f x) := by simp only [directed_on, exists_prop, mem_Union, exists_imp_distrib]; exact assume a₁ b₁ fb₁ a₂ b₂ fb₂, let ⟨z, zb₁, zb₂⟩ := hd b₁ b₂, ⟨x, xf, xa₁, xa₂⟩ := h z a₁ (zb₁ fb₁) a₂ (zb₂ fb₂) in ⟨x, ⟨z, xf⟩, xa₁, xa₂⟩ lemma Union_inter_subset {ι α} {s t : ι → set α} : (⋃ i, s i ∩ t i) ⊆ (⋃ i, s i) ∩ (⋃ i, t i) := by { rintro x ⟨_, ⟨i, rfl⟩, ⟨xs, xt⟩⟩, exact ⟨⟨_, ⟨i, rfl⟩, xs⟩, ⟨_, ⟨i, rfl⟩, xt⟩⟩ } lemma Union_inter_of_monotone {ι α} [semilattice_sup ι] {s t : ι → set α} (hs : monotone s) (ht : monotone t) : (⋃ i, s i ∩ t i) = (⋃ i, s i) ∩ (⋃ i, t i) := begin ext x, refine ⟨λ hx, Union_inter_subset hx, _⟩, rintro ⟨⟨_, ⟨i, rfl⟩, xs⟩, ⟨_, ⟨j, rfl⟩, xt⟩⟩, exact ⟨_, ⟨i ⊔ j, rfl⟩, ⟨hs le_sup_left xs, ht le_sup_right xt⟩⟩ end /-- An equality version of this lemma is `Union_Inter_of_monotone` in `data.set.finite`. -/ lemma Union_Inter_subset {ι ι' α} {s : ι → ι' → set α} : (⋃ j, ⋂ i, s i j) ⊆ ⋂ i, ⋃ j, s i j := by { rintro x ⟨_, ⟨i, rfl⟩, hx⟩ _ ⟨j, rfl⟩, exact ⟨_, ⟨i, rfl⟩, hx _ ⟨j, rfl⟩⟩ } /- bounded unions and intersections -/ theorem mem_bUnion_iff {s : set α} {t : α → set β} {y : β} : y ∈ (⋃ x ∈ s, t x) ↔ ∃ x ∈ s, y ∈ t x := by simp theorem mem_bInter_iff {s : set α} {t : α → set β} {y : β} : y ∈ (⋂ x ∈ s, t x) ↔ ∀ x ∈ s, y ∈ t x := by simp theorem mem_bUnion {s : set α} {t : α → set β} {x : α} {y : β} (xs : x ∈ s) (ytx : y ∈ t x) : y ∈ ⋃ x ∈ s, t x := by simp; exact ⟨x, ⟨xs, ytx⟩⟩ theorem mem_bInter {s : set α} {t : α → set β} {y : β} (h : ∀ x ∈ s, y ∈ t x) : y ∈ ⋂ x ∈ s, t x := by simp; assumption theorem bUnion_subset {s : set α} {t : set β} {u : α → set β} (h : ∀ x ∈ s, u x ⊆ t) : (⋃ x ∈ s, u x) ⊆ t := show (⨆ x ∈ s, u x) ≤ t, -- TODO: should not be necessary when sets' order is based on lattices from supr_le $ assume x, supr_le (h x) theorem subset_bInter {s : set α} {t : set β} {u : α → set β} (h : ∀ x ∈ s, t ⊆ u x) : t ⊆ (⋂ x ∈ s, u x) := subset_Inter $ assume x, subset_Inter $ h x theorem subset_bUnion_of_mem {s : set α} {u : α → set β} {x : α} (xs : x ∈ s) : u x ⊆ (⋃ x ∈ s, u x) := show u x ≤ (⨆ x ∈ s, u x), from le_supr_of_le x $ le_supr _ xs theorem bInter_subset_of_mem {s : set α} {t : α → set β} {x : α} (xs : x ∈ s) : (⋂ x ∈ s, t x) ⊆ t x := show (⨅x ∈ s, t x) ≤ t x, from infi_le_of_le x $ infi_le _ xs theorem bUnion_subset_bUnion_left {s s' : set α} {t : α → set β} (h : s ⊆ s') : (⋃ x ∈ s, t x) ⊆ (⋃ x ∈ s', t x) := bUnion_subset (λ x xs, subset_bUnion_of_mem (h xs)) theorem bInter_subset_bInter_left {s s' : set α} {t : α → set β} (h : s' ⊆ s) : (⋂ x ∈ s, t x) ⊆ (⋂ x ∈ s', t x) := subset_bInter (λ x xs, bInter_subset_of_mem (h xs)) theorem bUnion_subset_bUnion_right {s : set α} {t1 t2 : α → set β} (h : ∀ x ∈ s, t1 x ⊆ t2 x) : (⋃ x ∈ s, t1 x) ⊆ (⋃ x ∈ s, t2 x) := bUnion_subset (λ x xs, subset.trans (h x xs) (subset_bUnion_of_mem xs)) theorem bInter_subset_bInter_right {s : set α} {t1 t2 : α → set β} (h : ∀ x ∈ s, t1 x ⊆ t2 x) : (⋂ x ∈ s, t1 x) ⊆ (⋂ x ∈ s, t2 x) := subset_bInter (λ x xs, subset.trans (bInter_subset_of_mem xs) (h x xs)) theorem bUnion_subset_bUnion {γ : Type*} {s : set α} {t : α → set β} {s' : set γ} {t' : γ → set β} (h : ∀ x ∈ s, ∃ y ∈ s', t x ⊆ t' y) : (⋃ x ∈ s, t x) ⊆ (⋃ y ∈ s', t' y) := begin intros x, simp only [mem_Union], rintros ⟨a, a_in, ha⟩, rcases h a a_in with ⟨c, c_in, hc⟩, exact ⟨c, c_in, hc ha⟩ end theorem bInter_mono' {s s' : set α} {t t' : α → set β} (hs : s ⊆ s') (h : ∀ x ∈ s, t x ⊆ t' x) : (⋂ x ∈ s', t x) ⊆ (⋂ x ∈ s, t' x) := begin intros x x_in, simp only [mem_Inter] at *, exact λ a a_in, h a a_in $ x_in _ (hs a_in) end theorem bInter_mono {s : set α} {t t' : α → set β} (h : ∀ x ∈ s, t x ⊆ t' x) : (⋂ x ∈ s, t x) ⊆ (⋂ x ∈ s, t' x) := bInter_mono' (subset.refl s) h theorem bUnion_mono {s : set α} {t t' : α → set β} (h : ∀ x ∈ s, t x ⊆ t' x) : (⋃ x ∈ s, t x) ⊆ (⋃ x ∈ s, t' x) := bUnion_subset_bUnion (λ x x_in, ⟨x, x_in, h x x_in⟩) theorem bUnion_eq_Union (s : set α) (t : Π x ∈ s, set β) : (⋃ x ∈ s, t x ‹_›) = (⋃ x : s, t x x.2) := supr_subtype' theorem bInter_eq_Inter (s : set α) (t : Π x ∈ s, set β) : (⋂ x ∈ s, t x ‹_›) = (⋂ x : s, t x x.2) := infi_subtype' theorem bInter_empty (u : α → set β) : (⋂ x ∈ (∅ : set α), u x) = univ := show (⨅x ∈ (∅ : set α), u x) = ⊤, -- simplifier should be able to rewrite x ∈ ∅ to false. from infi_emptyset theorem bInter_univ (u : α → set β) : (⋂ x ∈ @univ α, u x) = ⋂ x, u x := infi_univ -- TODO(Jeremy): here is an artifact of the the encoding of bounded intersection: -- without dsimp, the next theorem fails to type check, because there is a lambda -- in a type that needs to be contracted. Using simp [eq_of_mem_singleton xa] also works. @[simp] theorem bInter_singleton (a : α) (s : α → set β) : (⋂ x ∈ ({a} : set α), s x) = s a := show (⨅ x ∈ ({a} : set α), s x) = s a, by simp theorem bInter_union (s t : set α) (u : α → set β) : (⋂ x ∈ s ∪ t, u x) = (⋂ x ∈ s, u x) ∩ (⋂ x ∈ t, u x) := show (⨅ x ∈ s ∪ t, u x) = (⨅ x ∈ s, u x) ⊓ (⨅ x ∈ t, u x), from infi_union -- TODO(Jeremy): simp [insert_eq, bInter_union] doesn't work @[simp] theorem bInter_insert (a : α) (s : set α) (t : α → set β) : (⋂ x ∈ insert a s, t x) = t a ∩ (⋂ x ∈ s, t x) := begin rw insert_eq, simp [bInter_union] end -- TODO(Jeremy): another example of where an annotation is needed theorem bInter_pair (a b : α) (s : α → set β) : (⋂ x ∈ ({a, b} : set α), s x) = s a ∩ s b := by simp [inter_comm] theorem bUnion_empty (s : α → set β) : (⋃ x ∈ (∅ : set α), s x) = ∅ := supr_emptyset theorem bUnion_univ (s : α → set β) : (⋃ x ∈ @univ α, s x) = ⋃ x, s x := supr_univ @[simp] theorem bUnion_singleton (a : α) (s : α → set β) : (⋃ x ∈ ({a} : set α), s x) = s a := supr_singleton @[simp] theorem bUnion_of_singleton (s : set α) : (⋃ x ∈ s, {x}) = s := ext $ by simp theorem bUnion_union (s t : set α) (u : α → set β) : (⋃ x ∈ s ∪ t, u x) = (⋃ x ∈ s, u x) ∪ (⋃ x ∈ t, u x) := supr_union -- TODO(Jeremy): once again, simp doesn't do it alone. @[simp] theorem bUnion_insert (a : α) (s : set α) (t : α → set β) : (⋃ x ∈ insert a s, t x) = t a ∪ (⋃ x ∈ s, t x) := begin rw [insert_eq], simp [bUnion_union] end theorem bUnion_pair (a b : α) (s : α → set β) : (⋃ x ∈ ({a, b} : set α), s x) = s a ∪ s b := by simp [union_comm] @[simp] -- complete_boolean_algebra theorem compl_bUnion (s : set α) (t : α → set β) : (⋃ i ∈ s, t i)ᶜ = (⋂ i ∈ s, (t i)ᶜ) := ext (λ x, by simp) -- classical -- complete_boolean_algebra theorem compl_bInter (s : set α) (t : α → set β) : (⋂ i ∈ s, t i)ᶜ = (⋃ i ∈ s, (t i)ᶜ) := ext (λ x, by simp [not_forall]) theorem inter_bUnion (s : set α) (t : α → set β) (u : set β) : u ∩ (⋃ i ∈ s, t i) = ⋃ i ∈ s, u ∩ t i := begin ext x, simp only [exists_prop, mem_Union, mem_inter_eq], exact ⟨λ ⟨hx, ⟨i, is, xi⟩⟩, ⟨i, is, hx, xi⟩, λ ⟨i, is, hx, xi⟩, ⟨hx, ⟨i, is, xi⟩⟩⟩ end theorem bUnion_inter (s : set α) (t : α → set β) (u : set β) : (⋃ i ∈ s, t i) ∩ u = (⋃ i ∈ s, t i ∩ u) := by simp [@inter_comm _ _ u, inter_bUnion] /-- Intersection of a set of sets. -/ @[reducible] def sInter (S : set (set α)) : set α := Inf S prefix `⋂₀`:110 := sInter theorem mem_sUnion_of_mem {x : α} {t : set α} {S : set (set α)} (hx : x ∈ t) (ht : t ∈ S) : x ∈ ⋃₀ S := ⟨t, ⟨ht, hx⟩⟩ theorem mem_sUnion {x : α} {S : set (set α)} : x ∈ ⋃₀ S ↔ ∃t ∈ S, x ∈ t := iff.rfl -- is this theorem really necessary? theorem not_mem_of_not_mem_sUnion {x : α} {t : set α} {S : set (set α)} (hx : x ∉ ⋃₀ S) (ht : t ∈ S) : x ∉ t := λ h, hx ⟨t, ht, h⟩ @[simp] theorem mem_sInter {x : α} {S : set (set α)} : x ∈ ⋂₀ S ↔ ∀ t ∈ S, x ∈ t := iff.rfl theorem sInter_subset_of_mem {S : set (set α)} {t : set α} (tS : t ∈ S) : ⋂₀ S ⊆ t := Inf_le tS theorem subset_sUnion_of_mem {S : set (set α)} {t : set α} (tS : t ∈ S) : t ⊆ ⋃₀ S := le_Sup tS lemma subset_sUnion_of_subset {s : set α} (t : set (set α)) (u : set α) (h₁ : s ⊆ u) (h₂ : u ∈ t) : s ⊆ ⋃₀ t := subset.trans h₁ (subset_sUnion_of_mem h₂) theorem sUnion_subset {S : set (set α)} {t : set α} (h : ∀t' ∈ S, t' ⊆ t) : (⋃₀ S) ⊆ t := Sup_le h theorem sUnion_subset_iff {s : set (set α)} {t : set α} : ⋃₀ s ⊆ t ↔ ∀t' ∈ s, t' ⊆ t := ⟨assume h t' ht', subset.trans (subset_sUnion_of_mem ht') h, sUnion_subset⟩ theorem subset_sInter {S : set (set α)} {t : set α} (h : ∀t' ∈ S, t ⊆ t') : t ⊆ (⋂₀ S) := le_Inf h theorem sUnion_subset_sUnion {S T : set (set α)} (h : S ⊆ T) : ⋃₀ S ⊆ ⋃₀ T := sUnion_subset $ λ s hs, subset_sUnion_of_mem (h hs) theorem sInter_subset_sInter {S T : set (set α)} (h : S ⊆ T) : ⋂₀ T ⊆ ⋂₀ S := subset_sInter $ λ s hs, sInter_subset_of_mem (h hs) @[simp] theorem sUnion_empty : ⋃₀ ∅ = (∅ : set α) := Sup_empty @[simp] theorem sInter_empty : ⋂₀ ∅ = (univ : set α) := Inf_empty @[simp] theorem sUnion_singleton (s : set α) : ⋃₀ {s} = s := Sup_singleton @[simp] theorem sInter_singleton (s : set α) : ⋂₀ {s} = s := Inf_singleton @[simp] theorem sUnion_eq_empty {S : set (set α)} : (⋃₀ S) = ∅ ↔ ∀ s ∈ S, s = ∅ := Sup_eq_bot @[simp] theorem sInter_eq_univ {S : set (set α)} : (⋂₀ S) = univ ↔ ∀ s ∈ S, s = univ := Inf_eq_top @[simp] theorem nonempty_sUnion {S : set (set α)} : (⋃₀ S).nonempty ↔ ∃ s ∈ S, set.nonempty s := by simp [← ne_empty_iff_nonempty] lemma nonempty.of_sUnion {s : set (set α)} (h : (⋃₀ s).nonempty) : s.nonempty := let ⟨s, hs, _⟩ := nonempty_sUnion.1 h in ⟨s, hs⟩ lemma nonempty.of_sUnion_eq_univ [nonempty α] {s : set (set α)} (h : ⋃₀ s = univ) : s.nonempty := nonempty.of_sUnion $ h.symm ▸ univ_nonempty theorem sUnion_union (S T : set (set α)) : ⋃₀ (S ∪ T) = ⋃₀ S ∪ ⋃₀ T := Sup_union theorem sInter_union (S T : set (set α)) : ⋂₀ (S ∪ T) = ⋂₀ S ∩ ⋂₀ T := Inf_union theorem sInter_Union (s : ι → set (set α)) : ⋂₀ (⋃ i, s i) = ⋂ i, ⋂₀ s i := begin ext x, simp only [mem_Union, mem_Inter, mem_sInter, exists_imp_distrib], split ; tauto end @[simp] theorem sUnion_insert (s : set α) (T : set (set α)) : ⋃₀ (insert s T) = s ∪ ⋃₀ T := Sup_insert @[simp] theorem sInter_insert (s : set α) (T : set (set α)) : ⋂₀ (insert s T) = s ∩ ⋂₀ T := Inf_insert theorem sUnion_pair (s t : set α) : ⋃₀ {s, t} = s ∪ t := Sup_pair theorem sInter_pair (s t : set α) : ⋂₀ {s, t} = s ∩ t := Inf_pair @[simp] theorem sUnion_image (f : α → set β) (s : set α) : ⋃₀ (f '' s) = ⋃ x ∈ s, f x := Sup_image @[simp] theorem sInter_image (f : α → set β) (s : set α) : ⋂₀ (f '' s) = ⋂ x ∈ s, f x := Inf_image @[simp] theorem sUnion_range (f : ι → set β) : ⋃₀ (range f) = ⋃ x, f x := rfl @[simp] theorem sInter_range (f : ι → set β) : ⋂₀ (range f) = ⋂ x, f x := rfl lemma sUnion_eq_univ_iff {c : set (set α)} : ⋃₀ c = @set.univ α ↔ ∀ a, ∃ b ∈ c, a ∈ b := ⟨λ H a, let ⟨b, hm, hb⟩ := mem_sUnion.1 $ by rw H; exact mem_univ a in ⟨b, hm, hb⟩, λ H, set.univ_subset_iff.1 $ λ x hx, let ⟨b, hm, hb⟩ := H x in set.mem_sUnion_of_mem hb hm⟩ theorem compl_sUnion (S : set (set α)) : (⋃₀ S)ᶜ = ⋂₀ (compl '' S) := ext $ λ x, by simp -- classical theorem sUnion_eq_compl_sInter_compl (S : set (set α)) : ⋃₀ S = (⋂₀ (compl '' S))ᶜ := by rw [←compl_compl (⋃₀ S), compl_sUnion] -- classical theorem compl_sInter (S : set (set α)) : (⋂₀ S)ᶜ = ⋃₀ (compl '' S) := by rw [sUnion_eq_compl_sInter_compl, compl_compl_image] -- classical theorem sInter_eq_comp_sUnion_compl (S : set (set α)) : ⋂₀ S = (⋃₀ (compl '' S))ᶜ := by rw [←compl_compl (⋂₀ S), compl_sInter] theorem inter_empty_of_inter_sUnion_empty {s t : set α} {S : set (set α)} (hs : t ∈ S) (h : s ∩ ⋃₀ S = ∅) : s ∩ t = ∅ := eq_empty_of_subset_empty $ by rw ← h; exact inter_subset_inter_right _ (subset_sUnion_of_mem hs) theorem range_sigma_eq_Union_range {γ : α → Type*} (f : sigma γ → β) : range f = ⋃ a, range (λ b, f ⟨a, b⟩) := set.ext $ by simp theorem Union_eq_range_sigma (s : α → set β) : (⋃ i, s i) = range (λ a : Σ i, s i, a.2) := by simp [set.ext_iff] theorem Union_image_preimage_sigma_mk_eq_self {ι : Type*} {σ : ι → Type*} (s : set (sigma σ)) : (⋃ i, sigma.mk i '' (sigma.mk i ⁻¹' s)) = s := begin ext x, simp only [mem_Union, mem_image, mem_preimage], split, { rintros ⟨i, a, h, rfl⟩, exact h }, { intro h, cases x with i a, exact ⟨i, a, h, rfl⟩ } end lemma sUnion_mono {s t : set (set α)} (h : s ⊆ t) : (⋃₀ s) ⊆ (⋃₀ t) := sUnion_subset $ assume t' ht', subset_sUnion_of_mem $ h ht' lemma Union_subset_Union {s t : ι → set α} (h : ∀i, s i ⊆ t i) : (⋃i, s i) ⊆ (⋃i, t i) := @supr_le_supr (set α) ι _ s t h lemma Union_subset_Union2 {ι₂ : Sort*} {s : ι → set α} {t : ι₂ → set α} (h : ∀i, ∃j, s i ⊆ t j) : (⋃i, s i) ⊆ (⋃i, t i) := @supr_le_supr2 (set α) ι ι₂ _ s t h lemma Union_subset_Union_const {ι₂ : Sort x} {s : set α} (h : ι → ι₂) : (⋃ i:ι, s) ⊆ (⋃ j:ι₂, s) := @supr_le_supr_const (set α) ι ι₂ _ s h @[simp] lemma Union_of_singleton (α : Type u) : (⋃(x : α), {x}) = @set.univ α := ext $ λ x, ⟨λ h, ⟨⟩, λ h, ⟨{x}, ⟨⟨x, rfl⟩, mem_singleton x⟩⟩⟩ theorem bUnion_subset_Union (s : set α) (t : α → set β) : (⋃ x ∈ s, t x) ⊆ (⋃ x, t x) := Union_subset_Union $ λ i, Union_subset $ λ h, by refl lemma sUnion_eq_bUnion {s : set (set α)} : (⋃₀ s) = (⋃ (i : set α) (h : i ∈ s), i) := by rw [← sUnion_image, image_id'] lemma sInter_eq_bInter {s : set (set α)} : (⋂₀ s) = (⋂ (i : set α) (h : i ∈ s), i) := by rw [← sInter_image, image_id'] lemma sUnion_eq_Union {s : set (set α)} : (⋃₀ s) = (⋃ (i : s), i) := by simp only [←sUnion_range, subtype.range_coe] lemma sInter_eq_Inter {s : set (set α)} : (⋂₀ s) = (⋂ (i : s), i) := by simp only [←sInter_range, subtype.range_coe] lemma union_eq_Union {s₁ s₂ : set α} : s₁ ∪ s₂ = ⋃ b : bool, cond b s₁ s₂ := set.ext $ λ x, by simp [bool.exists_bool, or_comm] lemma inter_eq_Inter {s₁ s₂ : set α} : s₁ ∩ s₂ = ⋂ b : bool, cond b s₁ s₂ := set.ext $ λ x, by simp [bool.forall_bool, and_comm] instance : complete_boolean_algebra (set α) := { compl := compl, sdiff := (\), infi_sup_le_sup_Inf := assume s t x, show x ∈ (⋂ b ∈ t, s ∪ b) → x ∈ s ∪ (⋂₀ t), by simp; exact assume h, or.imp_right (assume hn : x ∉ s, assume i hi, or.resolve_left (h i hi) hn) (classical.em $ x ∈ s), inf_Sup_le_supr_inf := assume s t x, show x ∈ s ∩ (⋃₀ t) → x ∈ (⋃ b ∈ t, s ∩ b), by simp [-and_imp, and.left_comm], .. set.boolean_algebra, .. set.lattice_set } lemma sInter_union_sInter {S T : set (set α)} : (⋂₀S) ∪ (⋂₀T) = (⋂p ∈ S.prod T, (p : (set α) × (set α)).1 ∪ p.2) := Inf_sup_Inf lemma sUnion_inter_sUnion {s t : set (set α)} : (⋃₀s) ∩ (⋃₀t) = (⋃p ∈ s.prod t, (p : (set α) × (set α )).1 ∩ p.2) := Sup_inf_Sup /-- If `S` is a set of sets, and each `s ∈ S` can be represented as an intersection of sets `T s hs`, then `⋂₀ S` is the intersection of the union of all `T s hs`. -/ lemma sInter_bUnion {S : set (set α)} {T : Π s ∈ S, set (set α)} (hT : ∀s∈S, s = ⋂₀ T s ‹s ∈ S›) : ⋂₀ (⋃s∈S, T s ‹_›) = ⋂₀ S := begin ext, simp only [and_imp, exists_prop, set.mem_sInter, set.mem_Union, exists_imp_distrib], split, { assume H s sS, rw [hT s sS, mem_sInter], assume t tTs, exact H t s sS tTs }, { assume H t s sS tTs, suffices : s ⊆ t, exact this (H s sS), rw [hT s sS, sInter_eq_bInter], exact bInter_subset_of_mem tTs } end /-- If `S` is a set of sets, and each `s ∈ S` can be represented as an union of sets `T s hs`, then `⋃₀ S` is the union of the union of all `T s hs`. -/ lemma sUnion_bUnion {S : set (set α)} {T : Π s ∈ S, set (set α)} (hT : ∀s∈S, s = ⋃₀ T s ‹_›) : ⋃₀ (⋃s∈S, T s ‹_›) = ⋃₀ S := begin ext, simp only [exists_prop, set.mem_Union, set.mem_set_of_eq], split, { rintros ⟨t, ⟨⟨s, ⟨sS, tTs⟩⟩, xt⟩⟩, refine ⟨s, ⟨sS, _⟩⟩, rw hT s sS, exact subset_sUnion_of_mem tTs xt }, { rintros ⟨s, ⟨sS, xs⟩⟩, rw hT s sS at xs, rcases mem_sUnion.1 xs with ⟨t, tTs, xt⟩, exact ⟨t, ⟨⟨s, ⟨sS, tTs⟩⟩, xt⟩⟩ } end lemma Union_range_eq_sUnion {α β : Type*} (C : set (set α)) {f : ∀(s : C), β → s} (hf : ∀(s : C), surjective (f s)) : (⋃(y : β), range (λ(s : C), (f s y).val)) = ⋃₀ C := begin ext x, split, { rintro ⟨s, ⟨y, rfl⟩, ⟨⟨s, hs⟩, rfl⟩⟩, refine ⟨_, hs, _⟩, exact (f ⟨s, hs⟩ y).2 }, { rintro ⟨s, hs, hx⟩, cases hf ⟨s, hs⟩ ⟨x, hx⟩ with y hy, refine ⟨_, ⟨y, rfl⟩, ⟨⟨s, hs⟩, _⟩⟩, exact congr_arg subtype.val hy } end lemma Union_range_eq_Union {ι α β : Type*} (C : ι → set α) {f : ∀(x : ι), β → C x} (hf : ∀(x : ι), surjective (f x)) : (⋃(y : β), range (λ(x : ι), (f x y).val)) = ⋃x, C x := begin ext x, rw [mem_Union, mem_Union], split, { rintro ⟨y, ⟨i, rfl⟩⟩, exact ⟨i, (f i y).2⟩ }, { rintro ⟨i, hx⟩, cases hf i ⟨x, hx⟩ with y hy, refine ⟨y, ⟨i, congr_arg subtype.val hy⟩⟩ } end lemma union_distrib_Inter_right {ι : Type*} (s : ι → set α) (t : set α) : (⋂ i, s i) ∪ t = (⋂ i, s i ∪ t) := begin ext x, rw [mem_union_eq, mem_Inter], split ; finish end lemma union_distrib_Inter_left {ι : Type*} (s : ι → set α) (t : set α) : t ∪ (⋂ i, s i) = (⋂ i, t ∪ s i) := begin rw [union_comm, union_distrib_Inter_right], simp [union_comm] end section function /-! ### `maps_to` -/ lemma maps_to_sUnion {S : set (set α)} {t : set β} {f : α → β} (H : ∀ s ∈ S, maps_to f s t) : maps_to f (⋃₀ S) t := λ x ⟨s, hs, hx⟩, H s hs hx lemma maps_to_Union {s : ι → set α} {t : set β} {f : α → β} (H : ∀ i, maps_to f (s i) t) : maps_to f (⋃ i, s i) t := maps_to_sUnion $ forall_range_iff.2 H lemma maps_to_bUnion {p : ι → Prop} {s : Π (i : ι) (hi : p i), set α} {t : set β} {f : α → β} (H : ∀ i hi, maps_to f (s i hi) t) : maps_to f (⋃ i hi, s i hi) t := maps_to_Union $ λ i, maps_to_Union (H i) lemma maps_to_Union_Union {s : ι → set α} {t : ι → set β} {f : α → β} (H : ∀ i, maps_to f (s i) (t i)) : maps_to f (⋃ i, s i) (⋃ i, t i) := maps_to_Union $ λ i, (H i).mono (subset.refl _) (subset_Union t i) lemma maps_to_bUnion_bUnion {p : ι → Prop} {s : Π i (hi : p i), set α} {t : Π i (hi : p i), set β} {f : α → β} (H : ∀ i hi, maps_to f (s i hi) (t i hi)) : maps_to f (⋃ i hi, s i hi) (⋃ i hi, t i hi) := maps_to_Union_Union $ λ i, maps_to_Union_Union (H i) lemma maps_to_sInter {s : set α} {T : set (set β)} {f : α → β} (H : ∀ t ∈ T, maps_to f s t) : maps_to f s (⋂₀ T) := λ x hx t ht, H t ht hx lemma maps_to_Inter {s : set α} {t : ι → set β} {f : α → β} (H : ∀ i, maps_to f s (t i)) : maps_to f s (⋂ i, t i) := λ x hx, mem_Inter.2 $ λ i, H i hx lemma maps_to_bInter {p : ι → Prop} {s : set α} {t : Π i (hi : p i), set β} {f : α → β} (H : ∀ i hi, maps_to f s (t i hi)) : maps_to f s (⋂ i hi, t i hi) := maps_to_Inter $ λ i, maps_to_Inter (H i) lemma maps_to_Inter_Inter {s : ι → set α} {t : ι → set β} {f : α → β} (H : ∀ i, maps_to f (s i) (t i)) : maps_to f (⋂ i, s i) (⋂ i, t i) := maps_to_Inter $ λ i, (H i).mono (Inter_subset s i) (subset.refl _) lemma maps_to_bInter_bInter {p : ι → Prop} {s : Π i (hi : p i), set α} {t : Π i (hi : p i), set β} {f : α → β} (H : ∀ i hi, maps_to f (s i hi) (t i hi)) : maps_to f (⋂ i hi, s i hi) (⋂ i hi, t i hi) := maps_to_Inter_Inter $ λ i, maps_to_Inter_Inter (H i) lemma image_Inter_subset (s : ι → set α) (f : α → β) : f '' (⋂ i, s i) ⊆ ⋂ i, f '' (s i) := (maps_to_Inter_Inter $ λ i, maps_to_image f (s i)).image_subset lemma image_bInter_subset {p : ι → Prop} (s : Π i (hi : p i), set α) (f : α → β) : f '' (⋂ i hi, s i hi) ⊆ ⋂ i hi, f '' (s i hi) := (maps_to_bInter_bInter $ λ i hi, maps_to_image f (s i hi)).image_subset lemma image_sInter_subset (S : set (set α)) (f : α → β) : f '' (⋂₀ S) ⊆ ⋂ s ∈ S, f '' s := by { rw sInter_eq_bInter, apply image_bInter_subset } /-! ### `inj_on` -/ lemma inj_on.image_Inter_eq [nonempty ι] {s : ι → set α} {f : α → β} (h : inj_on f (⋃ i, s i)) : f '' (⋂ i, s i) = ⋂ i, f '' (s i) := begin inhabit ι, refine subset.antisymm (image_Inter_subset s f) (λ y hy, _), simp only [mem_Inter, mem_image_iff_bex] at hy, choose x hx hy using hy, refine ⟨x (default ι), mem_Inter.2 $ λ i, _, hy _⟩, suffices : x (default ι) = x i, { rw this, apply hx }, replace hx : ∀ i, x i ∈ ⋃ j, s j := λ i, (subset_Union _ _) (hx i), apply h (hx _) (hx _), simp only [hy] end lemma inj_on.image_bInter_eq {p : ι → Prop} {s : Π i (hi : p i), set α} (hp : ∃ i, p i) {f : α → β} (h : inj_on f (⋃ i hi, s i hi)) : f '' (⋂ i hi, s i hi) = ⋂ i hi, f '' (s i hi) := begin simp only [Inter, infi_subtype'], haveI : nonempty {i // p i} := nonempty_subtype.2 hp, apply inj_on.image_Inter_eq, simpa only [Union, supr_subtype'] using h end lemma inj_on_Union_of_directed {s : ι → set α} (hs : directed (⊆) s) {f : α → β} (hf : ∀ i, inj_on f (s i)) : inj_on f (⋃ i, s i) := begin intros x hx y hy hxy, rcases mem_Union.1 hx with ⟨i, hx⟩, rcases mem_Union.1 hy with ⟨j, hy⟩, rcases hs i j with ⟨k, hi, hj⟩, exact hf k (hi hx) (hj hy) hxy end /-! ### `surj_on` -/ lemma surj_on_sUnion {s : set α} {T : set (set β)} {f : α → β} (H : ∀ t ∈ T, surj_on f s t) : surj_on f s (⋃₀ T) := λ x ⟨t, ht, hx⟩, H t ht hx lemma surj_on_Union {s : set α} {t : ι → set β} {f : α → β} (H : ∀ i, surj_on f s (t i)) : surj_on f s (⋃ i, t i) := surj_on_sUnion $ forall_range_iff.2 H lemma surj_on_Union_Union {s : ι → set α} {t : ι → set β} {f : α → β} (H : ∀ i, surj_on f (s i) (t i)) : surj_on f (⋃ i, s i) (⋃ i, t i) := surj_on_Union $ λ i, (H i).mono (subset_Union _ _) (subset.refl _) lemma surj_on_bUnion {p : ι → Prop} {s : set α} {t : Π i (hi : p i), set β} {f : α → β} (H : ∀ i hi, surj_on f s (t i hi)) : surj_on f s (⋃ i hi, t i hi) := surj_on_Union $ λ i, surj_on_Union (H i) lemma surj_on_bUnion_bUnion {p : ι → Prop} {s : Π i (hi : p i), set α} {t : Π i (hi : p i), set β} {f : α → β} (H : ∀ i hi, surj_on f (s i hi) (t i hi)) : surj_on f (⋃ i hi, s i hi) (⋃ i hi, t i hi) := surj_on_Union_Union $ λ i, surj_on_Union_Union (H i) lemma surj_on_Inter [hi : nonempty ι] {s : ι → set α} {t : set β} {f : α → β} (H : ∀ i, surj_on f (s i) t) (Hinj : inj_on f (⋃ i, s i)) : surj_on f (⋂ i, s i) t := begin intros y hy, rw [Hinj.image_Inter_eq, mem_Inter], exact λ i, H i hy end lemma surj_on_Inter_Inter [hi : nonempty ι] {s : ι → set α} {t : ι → set β} {f : α → β} (H : ∀ i, surj_on f (s i) (t i)) (Hinj : inj_on f (⋃ i, s i)) : surj_on f (⋂ i, s i) (⋂ i, t i) := surj_on_Inter (λ i, (H i).mono (subset.refl _) (Inter_subset _ _)) Hinj /-! ### `bij_on` -/ lemma bij_on_Union {s : ι → set α} {t : ι → set β} {f : α → β} (H : ∀ i, bij_on f (s i) (t i)) (Hinj : inj_on f (⋃ i, s i)) : bij_on f (⋃ i, s i) (⋃ i, t i) := ⟨maps_to_Union_Union $ λ i, (H i).maps_to, Hinj, surj_on_Union_Union $ λ i, (H i).surj_on⟩ lemma bij_on_Inter [hi :nonempty ι] {s : ι → set α} {t : ι → set β} {f : α → β} (H : ∀ i, bij_on f (s i) (t i)) (Hinj : inj_on f (⋃ i, s i)) : bij_on f (⋂ i, s i) (⋂ i, t i) := ⟨maps_to_Inter_Inter $ λ i, (H i).maps_to, hi.elim $ λ i, (H i).inj_on.mono (Inter_subset _ _), surj_on_Inter_Inter (λ i, (H i).surj_on) Hinj⟩ lemma bij_on_Union_of_directed {s : ι → set α} (hs : directed (⊆) s) {t : ι → set β} {f : α → β} (H : ∀ i, bij_on f (s i) (t i)) : bij_on f (⋃ i, s i) (⋃ i, t i) := bij_on_Union H $ inj_on_Union_of_directed hs (λ i, (H i).inj_on) lemma bij_on_Inter_of_directed [nonempty ι] {s : ι → set α} (hs : directed (⊆) s) {t : ι → set β} {f : α → β} (H : ∀ i, bij_on f (s i) (t i)) : bij_on f (⋂ i, s i) (⋂ i, t i) := bij_on_Inter H $ inj_on_Union_of_directed hs (λ i, (H i).inj_on) end function section variables {p : Prop} {μ : p → set α} @[simp] lemma Inter_pos (hp : p) : (⋂h:p, μ h) = μ hp := infi_pos hp @[simp] lemma Inter_neg (hp : ¬ p) : (⋂h:p, μ h) = univ := infi_neg hp @[simp] lemma Union_pos (hp : p) : (⋃h:p, μ h) = μ hp := supr_pos hp @[simp] lemma Union_neg (hp : ¬ p) : (⋃h:p, μ h) = ∅ := supr_neg hp @[simp] lemma Union_empty : (⋃i:ι, ∅:set α) = ∅ := supr_bot @[simp] lemma Inter_univ : (⋂i:ι, univ:set α) = univ := infi_top variables {s : ι → set α} @[simp] lemma Union_eq_empty : (⋃ i, s i) = ∅ ↔ ∀ i, s i = ∅ := supr_eq_bot @[simp] lemma Inter_eq_univ : (⋂ i, s i) = univ ↔ ∀ i, s i = univ := infi_eq_top @[simp] lemma nonempty_Union : (⋃ i, s i).nonempty ↔ ∃ i, (s i).nonempty := by simp [← ne_empty_iff_nonempty] end section image lemma image_Union {f : α → β} {s : ι → set α} : f '' (⋃ i, s i) = (⋃i, f '' s i) := begin apply set.ext, intro x, simp [image, exists_and_distrib_right.symm, -exists_and_distrib_right], exact exists_swap end lemma univ_subtype {p : α → Prop} : (univ : set (subtype p)) = (⋃x (h : p x), {⟨x, h⟩}) := set.ext $ assume ⟨x, h⟩, by simp [h] lemma range_eq_Union {ι} (f : ι → α) : range f = (⋃i, {f i}) := set.ext $ assume a, by simp [@eq_comm α a] lemma image_eq_Union (f : α → β) (s : set α) : f '' s = (⋃i∈s, {f i}) := set.ext $ assume b, by simp [@eq_comm β b] @[simp] lemma bUnion_range {f : ι → α} {g : α → set β} : (⋃x ∈ range f, g x) = (⋃y, g (f y)) := supr_range @[simp] lemma bInter_range {f : ι → α} {g : α → set β} : (⋂x ∈ range f, g x) = (⋂y, g (f y)) := infi_range variables {s : set γ} {f : γ → α} {g : α → set β} @[simp] lemma bUnion_image : (⋃x∈ (f '' s), g x) = (⋃y ∈ s, g (f y)) := supr_image @[simp] lemma bInter_image : (⋂x∈ (f '' s), g x) = (⋂y ∈ s, g (f y)) := infi_image end image section image2 variables (f : α → β → γ) {s : set α} {t : set β} lemma Union_image_left : (⋃ a ∈ s, f a '' t) = image2 f s t := by { ext y, split; simp only [mem_Union]; rintros ⟨a, ha, x, hx, ax⟩; exact ⟨a, x, ha, hx, ax⟩ } lemma Union_image_right : (⋃ b ∈ t, (λ a, f a b) '' s) = image2 f s t := by { ext y, split; simp only [mem_Union]; rintros ⟨a, b, c, d, e⟩, exact ⟨c, a, d, b, e⟩, exact ⟨b, d, a, c, e⟩ } end image2 section preimage theorem monotone_preimage {f : α → β} : monotone (preimage f) := assume a b h, preimage_mono h @[simp] theorem preimage_Union {ι : Sort w} {f : α → β} {s : ι → set β} : preimage f (⋃i, s i) = (⋃i, preimage f (s i)) := set.ext $ by simp [preimage] theorem preimage_bUnion {ι} {f : α → β} {s : set ι} {t : ι → set β} : f ⁻¹' (⋃i ∈ s, t i) = (⋃i ∈ s, f ⁻¹' (t i)) := by simp @[simp] theorem preimage_sUnion {f : α → β} {s : set (set β)} : f ⁻¹' (⋃₀ s) = (⋃t ∈ s, f ⁻¹' t) := set.ext $ by simp [preimage] lemma preimage_Inter {ι : Sort*} {s : ι → set β} {f : α → β} : f ⁻¹' (⋂ i, s i) = (⋂ i, f ⁻¹' s i) := by ext; simp lemma preimage_bInter {s : γ → set β} {t : set γ} {f : α → β} : f ⁻¹' (⋂ i∈t, s i) = (⋂ i∈t, f ⁻¹' s i) := by ext; simp @[simp] lemma bUnion_preimage_singleton (f : α → β) (s : set β) : (⋃ y ∈ s, f ⁻¹' {y}) = f ⁻¹' s := by rw [← preimage_bUnion, bUnion_of_singleton] lemma bUnion_range_preimage_singleton (f : α → β) : (⋃ y ∈ range f, f ⁻¹' {y}) = univ := by simp end preimage section prod theorem monotone_prod [preorder α] {f : α → set β} {g : α → set γ} (hf : monotone f) (hg : monotone g) : monotone (λx, (f x).prod (g x)) := assume a b h, prod_mono (hf h) (hg h) alias monotone_prod ← monotone.set_prod lemma prod_Union {ι} {s : set α} {t : ι → set β} : s.prod (⋃ i, t i) = ⋃ i, s.prod (t i) := by { ext, simp } lemma prod_bUnion {ι} {u : set ι} {s : set α} {t : ι → set β} : s.prod (⋃ i ∈ u, t i) = ⋃ i ∈ u, s.prod (t i) := by simp_rw [prod_Union] lemma prod_sUnion {s : set α} {C : set (set β)} : s.prod (⋃₀ C) = ⋃₀ ((λ t, s.prod t) '' C) := by { simp only [sUnion_eq_bUnion, prod_bUnion, bUnion_image] } lemma Union_prod {ι} {s : ι → set α} {t : set β} : (⋃ i, s i).prod t = ⋃ i, (s i).prod t := by { ext, simp } lemma bUnion_prod {ι} {u : set ι} {s : ι → set α} {t : set β} : (⋃ i ∈ u, s i).prod t = ⋃ i ∈ u, (s i).prod t := by simp_rw [Union_prod] lemma sUnion_prod {C : set (set α)} {t : set β} : (⋃₀ C).prod t = ⋃₀ ((λ s : set α, s.prod t) '' C) := by { simp only [sUnion_eq_bUnion, bUnion_prod, bUnion_image] } lemma Union_prod_of_monotone [semilattice_sup α] {s : α → set β} {t : α → set γ} (hs : monotone s) (ht : monotone t) : (⋃ x, (s x).prod (t x)) = (⋃ x, (s x)).prod (⋃ x, (t x)) := begin ext ⟨z, w⟩, simp only [mem_prod, mem_Union, exists_imp_distrib, and_imp, iff_def], split, { intros x hz hw, exact ⟨⟨x, hz⟩, ⟨x, hw⟩⟩ }, { intros x hz x' hw, exact ⟨x ⊔ x', hs le_sup_left hz, ht le_sup_right hw⟩ } end end prod section seq /-- Given a set `s` of functions `α → β` and `t : set α`, `seq s t` is the union of `f '' t` over all `f ∈ s`. -/ def seq (s : set (α → β)) (t : set α) : set β := {b | ∃f∈s, ∃a∈t, (f : α → β) a = b} lemma seq_def {s : set (α → β)} {t : set α} : seq s t = ⋃f∈s, f '' t := set.ext $ by simp [seq] @[simp] lemma mem_seq_iff {s : set (α → β)} {t : set α} {b : β} : b ∈ seq s t ↔ ∃ (f ∈ s) (a ∈ t), (f : α → β) a = b := iff.rfl lemma seq_subset {s : set (α → β)} {t : set α} {u : set β} : seq s t ⊆ u ↔ (∀f∈s, ∀a∈t, (f : α → β) a ∈ u) := iff.intro (assume h f hf a ha, h ⟨f, hf, a, ha, rfl⟩) (assume h b ⟨f, hf, a, ha, eq⟩, eq ▸ h f hf a ha) lemma seq_mono {s₀ s₁ : set (α → β)} {t₀ t₁ : set α} (hs : s₀ ⊆ s₁) (ht : t₀ ⊆ t₁) : seq s₀ t₀ ⊆ seq s₁ t₁ := assume b ⟨f, hf, a, ha, eq⟩, ⟨f, hs hf, a, ht ha, eq⟩ lemma singleton_seq {f : α → β} {t : set α} : set.seq {f} t = f '' t := set.ext $ by simp lemma seq_singleton {s : set (α → β)} {a : α} : set.seq s {a} = (λf:α→β, f a) '' s := set.ext $ by simp lemma seq_seq {s : set (β → γ)} {t : set (α → β)} {u : set α} : seq s (seq t u) = seq (seq ((∘) '' s) t) u := begin refine set.ext (assume c, iff.intro _ _), { rintros ⟨f, hfs, b, ⟨g, hg, a, hau, rfl⟩, rfl⟩, exact ⟨f ∘ g, ⟨(∘) f, mem_image_of_mem _ hfs, g, hg, rfl⟩, a, hau, rfl⟩ }, { rintros ⟨fg, ⟨fc, ⟨f, hfs, rfl⟩, g, hgt, rfl⟩, a, ha, rfl⟩, exact ⟨f, hfs, g a, ⟨g, hgt, a, ha, rfl⟩, rfl⟩ } end lemma image_seq {f : β → γ} {s : set (α → β)} {t : set α} : f '' seq s t = seq ((∘) f '' s) t := by rw [← singleton_seq, ← singleton_seq, seq_seq, image_singleton] lemma prod_eq_seq {s : set α} {t : set β} : s.prod t = (prod.mk '' s).seq t := begin ext ⟨a, b⟩, split, { rintros ⟨ha, hb⟩, exact ⟨prod.mk a, ⟨a, ha, rfl⟩, b, hb, rfl⟩ }, { rintros ⟨f, ⟨x, hx, rfl⟩, y, hy, eq⟩, rw ← eq, exact ⟨hx, hy⟩ } end lemma prod_image_seq_comm (s : set α) (t : set β) : (prod.mk '' s).seq t = seq ((λb a, (a, b)) '' t) s := by rw [← prod_eq_seq, ← image_swap_prod, prod_eq_seq, image_seq, ← image_comp, prod.swap] lemma image2_eq_seq (f : α → β → γ) (s : set α) (t : set β) : image2 f s t = seq (f '' s) t := by { ext, simp } end seq instance : monad set := { pure := λ(α : Type u) a, {a}, bind := λ(α β : Type u) s f, ⋃i∈s, f i, seq := λ(α β : Type u), set.seq, map := λ(α β : Type u), set.image } section monad variables {α' β' : Type u} {s : set α'} {f : α' → set β'} {g : set (α' → β')} @[simp] lemma bind_def : s >>= f = ⋃i∈s, f i := rfl @[simp] lemma fmap_eq_image (f : α' → β') : f <$> s = f '' s := rfl @[simp] lemma seq_eq_set_seq {α β : Type*} (s : set (α → β)) (t : set α) : s <*> t = s.seq t := rfl @[simp] lemma pure_def (a : α) : (pure a : set α) = {a} := rfl end monad instance : is_lawful_monad set := { pure_bind := assume α β x f, by simp, bind_assoc := assume α β γ s f g, set.ext $ assume a, by simp [exists_and_distrib_right.symm, -exists_and_distrib_right, exists_and_distrib_left.symm, -exists_and_distrib_left, and_assoc]; exact exists_swap, id_map := assume α, id_map, bind_pure_comp_eq_map := assume α β f s, set.ext $ by simp [set.image, eq_comm], bind_map_eq_seq := assume α β s t, by simp [seq_def] } instance : is_comm_applicative (set : Type u → Type u) := ⟨ assume α β s t, prod_image_seq_comm s t ⟩ section pi variables {π : α → Type*} lemma pi_def (i : set α) (s : Πa, set (π a)) : pi i s = (⋂ a ∈ i, eval a ⁻¹' s a) := by { ext, simp } lemma pi_diff_pi_subset (i : set α) (s t : Πa, set (π a)) : pi i s \ pi i t ⊆ ⋃ a ∈ i, (eval a ⁻¹' (s a \ t a)) := begin refine diff_subset_comm.2 (λ x hx a ha, _), simp only [mem_diff, mem_pi, mem_Union, not_exists, mem_preimage, not_and, not_not, eval_apply] at hx, exact hx.2 _ ha (hx.1 _ ha) end end pi end set /-! ### Disjoint sets -/ section disjoint variables {s t u : set α} namespace disjoint /-! We define some lemmas in the `disjoint` namespace to be able to use projection notation. -/ theorem union_left (hs : disjoint s u) (ht : disjoint t u) : disjoint (s ∪ t) u := hs.sup_left ht theorem union_right (ht : disjoint s t) (hu : disjoint s u) : disjoint s (t ∪ u) := ht.sup_right hu lemma preimage {α β} (f : α → β) {s t : set β} (h : disjoint s t) : disjoint (f ⁻¹' s) (f ⁻¹' t) := λ x hx, h hx end disjoint namespace set protected theorem disjoint_iff : disjoint s t ↔ s ∩ t ⊆ ∅ := iff.rfl theorem disjoint_iff_inter_eq_empty : disjoint s t ↔ s ∩ t = ∅ := disjoint_iff lemma not_disjoint_iff : ¬disjoint s t ↔ ∃x, x ∈ s ∧ x ∈ t := not_forall.trans $ exists_congr $ λ x, not_not lemma disjoint_left : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t := show (∀ x, ¬(x ∈ s ∩ t)) ↔ _, from ⟨λ h a, not_and.1 $ h a, λ h a, not_and.2 $ h a⟩ theorem disjoint_right : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s := by rw [disjoint.comm, disjoint_left] theorem disjoint_of_subset_left (h : s ⊆ u) (d : disjoint u t) : disjoint s t := d.mono_left h theorem disjoint_of_subset_right (h : t ⊆ u) (d : disjoint s u) : disjoint s t := d.mono_right h theorem disjoint_of_subset {s t u v : set α} (h1 : s ⊆ u) (h2 : t ⊆ v) (d : disjoint u v) : disjoint s t := d.mono h1 h2 @[simp] theorem disjoint_union_left : disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u := disjoint_sup_left @[simp] theorem disjoint_union_right : disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u := disjoint_sup_right theorem disjoint_diff {a b : set α} : disjoint a (b \ a) := disjoint_iff.2 (inter_diff_self _ _) @[simp] theorem disjoint_empty (s : set α) : disjoint s ∅ := disjoint_bot_right @[simp] theorem empty_disjoint (s : set α) : disjoint ∅ s := disjoint_bot_left @[simp] lemma univ_disjoint {s : set α}: disjoint univ s ↔ s = ∅ := top_disjoint @[simp] lemma disjoint_univ {s : set α} : disjoint s univ ↔ s = ∅ := disjoint_top @[simp] theorem disjoint_singleton_left {a : α} {s : set α} : disjoint {a} s ↔ a ∉ s := by simp [set.disjoint_iff, subset_def]; exact iff.rfl @[simp] theorem disjoint_singleton_right {a : α} {s : set α} : disjoint s {a} ↔ a ∉ s := by rw [disjoint.comm]; exact disjoint_singleton_left theorem disjoint_image_image {f : β → α} {g : γ → α} {s : set β} {t : set γ} (h : ∀b∈s, ∀c∈t, f b ≠ g c) : disjoint (f '' s) (g '' t) := by rintros a ⟨⟨b, hb, eq⟩, ⟨c, hc, rfl⟩⟩; exact h b hb c hc eq theorem pairwise_on_disjoint_fiber (f : α → β) (s : set β) : pairwise_on s (disjoint on (λ y, f ⁻¹' {y})) := λ y₁ _ y₂ _ hy x ⟨hx₁, hx₂⟩, hy (eq.trans (eq.symm hx₁) hx₂) lemma preimage_eq_empty {f : α → β} {s : set β} (h : disjoint s (range f)) : f ⁻¹' s = ∅ := by simpa using h.preimage f lemma preimage_eq_empty_iff {f : α → β} {s : set β} : disjoint s (range f) ↔ f ⁻¹' s = ∅ := ⟨preimage_eq_empty, λ h, by { simp [eq_empty_iff_forall_not_mem, set.disjoint_iff_inter_eq_empty] at h ⊢, finish }⟩ end set end disjoint namespace set /-- A collection of sets is `pairwise_disjoint`, if any two different sets in this collection are disjoint. -/ def pairwise_disjoint (s : set (set α)) : Prop := pairwise_on s disjoint lemma pairwise_disjoint.subset {s t : set (set α)} (h : s ⊆ t) (ht : pairwise_disjoint t) : pairwise_disjoint s := pairwise_on.mono h ht lemma pairwise_disjoint.range {s : set (set α)} (f : s → set α) (hf : ∀(x : s), f x ⊆ x.1) (ht : pairwise_disjoint s) : pairwise_disjoint (range f) := begin rintro _ ⟨x, rfl⟩ _ ⟨y, rfl⟩ hxy, refine (ht _ x.2 _ y.2 _).mono (hf x) (hf y), intro h, apply hxy, apply congr_arg f, exact subtype.eq h end /- classical -/ lemma pairwise_disjoint.elim {s : set (set α)} (h : pairwise_disjoint s) {x y : set α} (hx : x ∈ s) (hy : y ∈ s) (z : α) (hzx : z ∈ x) (hzy : z ∈ y) : x = y := not_not.1 $ λ h', h x hx y hy h' ⟨hzx, hzy⟩ end set namespace set variables (t : α → set β) lemma subset_diff {s t u : set α} : s ⊆ t \ u ↔ s ⊆ t ∧ disjoint s u := ⟨λ h, ⟨λ x hxs, (h hxs).1, λ x ⟨hxs, hxu⟩, (h hxs).2 hxu⟩, λ ⟨h1, h2⟩ x hxs, ⟨h1 hxs, λ hxu, h2 ⟨hxs, hxu⟩⟩⟩ /-- If `t` is an indexed family of sets, then there is a natural map from `Σ i, t i` to `⋃ i, t i` sending `⟨i, x⟩` to `x`. -/ def sigma_to_Union (x : Σi, t i) : (⋃i, t i) := ⟨x.2, mem_Union.2 ⟨x.1, x.2.2⟩⟩ lemma sigma_to_Union_surjective : surjective (sigma_to_Union t) | ⟨b, hb⟩ := have ∃a, b ∈ t a, by simpa using hb, let ⟨a, hb⟩ := this in ⟨⟨a, ⟨b, hb⟩⟩, rfl⟩ lemma sigma_to_Union_injective (h : ∀i j, i ≠ j → disjoint (t i) (t j)) : injective (sigma_to_Union t) | ⟨a₁, ⟨b₁, h₁⟩⟩ ⟨a₂, ⟨b₂, h₂⟩⟩ eq := have b_eq : b₁ = b₂, from congr_arg subtype.val eq, have a_eq : a₁ = a₂, from classical.by_contradiction $ assume ne, have b₁ ∈ t a₁ ∩ t a₂, from ⟨h₁, b_eq.symm ▸ h₂⟩, h _ _ ne this, sigma.eq a_eq $ subtype.eq $ by subst b_eq; subst a_eq lemma sigma_to_Union_bijective (h : ∀i j, i ≠ j → disjoint (t i) (t j)) : bijective (sigma_to_Union t) := ⟨sigma_to_Union_injective t h, sigma_to_Union_surjective t⟩ /-- Equivalence between a disjoint union and a dependent sum. -/ noncomputable def Union_eq_sigma_of_disjoint {t : α → set β} (h : ∀i j, i ≠ j → disjoint (t i) (t j)) : (⋃i, t i) ≃ (Σi, t i) := (equiv.of_bijective _ $ sigma_to_Union_bijective t h).symm /-- Equivalence between a disjoint bounded union and a dependent sum. -/ noncomputable def bUnion_eq_sigma_of_disjoint {s : set α} {t : α → set β} (h : pairwise_on s (disjoint on t)) : (⋃i∈s, t i) ≃ (Σi:s, t i.val) := equiv.trans (equiv.set_congr (bUnion_eq_Union _ _)) $ Union_eq_sigma_of_disjoint $ assume ⟨i, hi⟩ ⟨j, hj⟩ ne, h _ hi _ hj $ assume eq, ne $ subtype.eq eq end set
766b63e64f8621a668e5bcbebefbaccc455a47b0
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/logic/basic.lean
e9b75d9e8948921c7fdc2740c945b1a131e97e44
[ "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
68,868
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 import tactic.reserved_notation /-! # Basic logic properties > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > https://github.com/leanprover-community/mathlib4/pull/484 > Any changes to this file require a corresponding PR to mathlib4. 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. -/ open function local attribute [instance, priority 10] classical.prop_decidable 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 cast_heq variables {α : Type*} {β : Type*} /-- An identity function with its main argument implicit. This will be printed as `hidden` even if it is applied to a large term, so it can be used for elision, as done in the `elide` and `unelide` tactics. -/ @[reducible] def hidden {α : Sort*} {a : α} := a /-- Ex falso, the nondependent eliminator for the `empty` type. -/ 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 := ⟨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 {α : Sort*} [subsingleton α] (x y : α) : x = y ↔ true := by cc /-- If all points are equal to a given point `x`, then `α` is a subsingleton. -/ lemma subsingleton_of_forall_eq {α : Sort*} (x : α) (h : ∀ y, y = x) : subsingleton α := ⟨λ a b, (h a).symm ▸ (h b).symm ▸ rfl⟩ lemma subsingleton_iff_forall_eq {α : Sort*} (x : α) : subsingleton α ↔ ∀ y, y = x := ⟨λ h y, @subsingleton.elim _ h y x, subsingleton_of_forall_eq x⟩ instance subtype.subsingleton (α : Sort*) [subsingleton α] (p : α → Prop) : subsingleton (subtype p) := ⟨λ ⟨x,_⟩ ⟨y,_⟩, have x = y, from subsingleton.elim _ _, by { cases this, refl }⟩ /-- 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 /-- Non-dependent version of `coe_fn_coe_trans`, helps `rw` figure out the argument. -/ theorem coe_fn_coe_trans' {α β γ} {δ : out_param $ _} [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 /-- Non-dependent version of `coe_fn_coe_base`, helps `rw` figure out the argument. -/ theorem coe_fn_coe_base' {α β} {γ : out_param $ _} [has_coe α β] [has_coe_to_fun β (λ _, γ)] (x : α) : @coe_fn α _ _ x = @coe_fn β _ _ x := rfl -- This instance should have low priority, to ensure we follow the chain -- `set_like → has_coe_to_sort` attribute [instance, priority 10] coe_sort_trans 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 /-- Ex falso, the nondependent eliminator for the `pempty` type. -/ 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 lemma congr_heq {α β γ : Sort*} {f : α → γ} {g : β → γ} {x : α} {y : β} (h₁ : f == g) (h₂ : x == y) : f x = g y := by { cases h₂, cases h₁, refl } lemma congr_arg_heq {α} {β : α → Sort*} (f : ∀ a, β a) : ∀ {a₁ a₂ : α}, a₁ = a₂ → f a₁ == f a₂ | a _ rfl := heq.rfl lemma ulift.down_injective {α : Sort*} : function.injective (@ulift.down α) | ⟨a⟩ ⟨b⟩ rfl := rfl @[simp] lemma ulift.down_inj {α : Sort*} {a b : ulift α} : a.down = b.down ↔ a = b := ⟨λ h, ulift.down_injective h, λ h, by rw h⟩ lemma plift.down_injective {α : Sort*} : function.injective (@plift.down α) | ⟨a⟩ ⟨b⟩ rfl := rfl @[simp] lemma plift.down_inj {α : Sort*} {a b : plift α} : a.down = b.down ↔ a = b := ⟨λ h, plift.down_injective h, λ h, by rw h⟩ -- 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 fact (p : Prop) : Prop := (out [] : p) /-- In most cases, we should not have global instances of `fact`; typeclass search only reads the head symbol and then tries any instances, which means that adding any such instance will cause slowdowns everywhere. We instead make them as lemmata and make them local instances as required. -/ library_note "fact non-instances" lemma fact.elim {p : Prop} (h : fact p) : p := h.1 lemma fact_iff {p : Prop} : fact p ↔ p := ⟨λ h, h.1, λ h, ⟨h⟩⟩ /-- Swaps two pairs of arguments to a function. -/ @[reducible] def function.swap₂ {ι₁ ι₂ : Sort*} {κ₁ : ι₁ → Sort*} {κ₂ : ι₂ → Sort*} {φ : Π i₁, κ₁ i₁ → Π i₂, κ₂ i₂ → Sort*} (f : Π i₁ j₁ i₂ j₂, φ i₁ j₁ i₂ j₂) : Π i₂ j₂ i₁ j₁, φ i₁ j₁ i₂ j₂ := λ i₂ j₂ i₁ j₁, f i₁ j₁ i₂ j₂ /-- If `x : α . tac_name` then `x.out : α`. These are definitionally equal, but this can nevertheless be useful for various reasons, e.g. to apply further projection notation or in an argument to `simp`. -/ def auto_param.out {α : Sort*} {n : name} (x : auto_param α n) : α := x /-- If `x : α := d` then `x.out : α`. These are definitionally equal, but this can nevertheless be useful for various reasons, e.g. to apply further projection notation or in an argument to `simp`. -/ def opt_param.out {α : Sort*} {d : α} (x : α := d) : α := x end miscellany open function /-! ### Declarations about propositional connectives -/ theorem false_ne_true : false ≠ true | h := h.symm ▸ trivial theorem eq_true_iff {a : Prop} : (a = true) = a := have (a ↔ true) = a, from propext (iff_true a), eq.subst (@iff_eq_eq a true) this section propositional variables {a b c d e f : Prop} /-! ### Declarations about `implies` -/ instance : is_refl Prop iff := ⟨iff.refl⟩ instance : is_trans Prop iff := ⟨λ _ _ _, iff.trans⟩ 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 lemma iff.imp (h₁ : a ↔ b) (h₂ : c ↔ d) : (a → c) ↔ (b → d) := imp_congr h₁ h₂ @[simp] lemma eq_true_eq_id : eq true = id := by { funext, simp only [true_iff, id.def, iff_self, eq_iff_iff], } 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 theorem imp_iff_right (ha : a) : (a → b) ↔ b := ⟨λf, f ha, imp_intro⟩ lemma imp_iff_not (hb : ¬ b) : a → b ↔ ¬ a := imp_congr_right $ λ _, iff_false_intro hb theorem decidable.imp_iff_right_iff [decidable a] : ((a → b) ↔ b) ↔ (a ∨ b) := ⟨λ H, (decidable.em a).imp_right $ λ ha', H.1 $ λ ha, (ha' ha).elim, λ H, H.elim imp_iff_right $ λ hb, ⟨λ hab, hb, λ _ _, hb⟩⟩ @[simp] theorem imp_iff_right_iff : ((a → b) ↔ b) ↔ (a ∨ b) := decidable.imp_iff_right_iff lemma decidable.and_or_imp [decidable a] : (a ∧ b) ∨ (a → c) ↔ a → (b ∨ c) := if ha : a then by simp only [ha, true_and, true_implies_iff] else by simp only [ha, false_or, false_and, false_implies_iff] @[simp] theorem and_or_imp : (a ∧ b) ∨ (a → c) ↔ a → (b ∨ c) := decidable.and_or_imp /-- Provide modus tollens (`mt`) as dot notation for implications. -/ protected lemma function.mt : (a → b) → ¬ b → ¬ a := mt /-! ### Declarations about `not` -/ /-- Ex falso for negation. From `¬ a` and `a` anything follows. This is the same as `absurd` with the arguments flipped, but it is in the `not` namespace so that projection notation can be used. -/ 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 dec_em' (p : Prop) [decidable p] : ¬p ∨ p := (dec_em p).swap theorem em (p : Prop) : p ∨ ¬p := classical.em _ theorem em' (p : Prop) : ¬p ∨ p := (em p).swap theorem or_not {p : Prop} : p ∨ ¬p := em _ section eq_or_ne variables {α : Sort*} (x y : α) theorem decidable.eq_or_ne [decidable (x = y)] : x = y ∨ x ≠ y := dec_em $ x = y theorem decidable.ne_or_eq [decidable (x = y)] : x ≠ y ∨ x = y := dec_em' $ x = y theorem eq_or_ne : x = y ∨ x ≠ y := em $ x = y theorem ne_or_eq : x ≠ y ∨ x = y := em' $ x = y end eq_or_ne theorem by_contradiction {p} : (¬p → false) → p := decidable.by_contradiction -- alias by_contradiction ← by_contra theorem by_contra {p} : (¬p → false) → p := decidable.by_contradiction /-- In most of mathlib, we use the law of excluded middle (LEM) and the axiom of choice (AC) freely. The `decidable` namespace contains versions of lemmas from the root namespace that explicitly attempt to avoid the axiom of choice, usually by adding decidability assumptions on the inputs. You can check if a lemma uses the axiom of choice by using `#print axioms foo` and seeing if `classical.choice` appears in the list. -/ library_note "decidable namespace" /-- As mathlib is primarily classical, if the type signature of a `def` or `lemma` does not require any `decidable` instances to state, it is preferable not to introduce any `decidable` instances that are needed in the proof as arguments, but rather to use the `classical` tactic as needed. In the other direction, when `decidable` instances do appear in the type signature, it is better to use explicitly introduced ones rather than allowing Lean to automatically infer classical ones, as these may cause instance mismatch errors later. -/ library_note "decidable arguments" -- See Note [decidable namespace] protected theorem decidable.not_not [decidable a] : ¬¬a ↔ a := iff.intro decidable.by_contradiction not_not_intro /-- The Double Negation Theorem: `¬ ¬ P` is equivalent to `P`. The left-to-right direction, double negation elimination (DNE), is classically true but not constructively. -/ @[simp] theorem not_not : ¬¬a ↔ a := decidable.not_not theorem of_not_not : ¬¬a → a := by_contra lemma not_ne_iff {α : Sort*} {a b : α} : ¬ a ≠ b ↔ a = b := not_not -- See Note [decidable namespace] protected theorem decidable.of_not_imp [decidable a] (h : ¬ (a → b)) : a := decidable.by_contradiction (not_not_of_not_imp h) theorem of_not_imp : ¬ (a → b) → a := decidable.of_not_imp -- See Note [decidable namespace] protected theorem decidable.not_imp_symm [decidable a] (h : ¬a → b) (hb : ¬b) : a := decidable.by_contradiction $ hb ∘ h theorem not.decidable_imp_symm [decidable a] : (¬a → b) → ¬b → a := decidable.not_imp_symm theorem not.imp_symm : (¬a → b) → ¬b → a := not.decidable_imp_symm -- See Note [decidable namespace] protected theorem decidable.not_imp_comm [decidable a] [decidable b] : (¬a → b) ↔ (¬b → a) := ⟨not.decidable_imp_symm, not.decidable_imp_symm⟩ theorem not_imp_comm : (¬a → b) ↔ (¬b → a) := decidable.not_imp_comm @[simp] theorem imp_not_self : (a → ¬a) ↔ ¬a := ⟨λ h ha, h ha ha, λ h _, h⟩ theorem decidable.not_imp_self [decidable a] : (¬a → a) ↔ a := by { have := @imp_not_self (¬a), rwa decidable.not_not at this } @[simp] theorem not_imp_self : (¬a → a) ↔ a := decidable.not_imp_self theorem imp.swap : (a → b → c) ↔ (b → a → c) := ⟨swap, swap⟩ theorem imp_not_comm : (a → ¬b) ↔ (b → ¬a) := imp.swap lemma iff.not (h : a ↔ b) : ¬ a ↔ ¬ b := not_congr h lemma iff.not_left (h : a ↔ ¬ b) : ¬ a ↔ b := h.not.trans not_not lemma iff.not_right (h : ¬ a ↔ b) : a ↔ ¬ b := not_not.symm.trans h.not /-! ### Declarations about `xor` -/ @[simp] theorem xor_true : xor true = not := funext $ λ a, by simp [xor] @[simp] theorem xor_false : xor false = id := funext $ λ a, by simp [xor] theorem xor_comm (a b) : xor a b ↔ xor b a := or_comm _ _ instance : is_commutative Prop xor := ⟨λ a b, propext $ xor_comm a b⟩ @[simp] theorem xor_self (a : Prop) : xor a a = false := by simp [xor] @[simp] theorem xor_not_left : xor (¬a) b ↔ (a ↔ b) := by by_cases a; simp * @[simp] theorem xor_not_right : xor a (¬b) ↔ (a ↔ b) := by by_cases a; simp * theorem xor_not_not : xor (¬a) (¬b) ↔ xor a b := by simp [xor, or_comm, and_comm] protected theorem xor.or (h : xor a b) : a ∨ b := h.imp and.left and.left /-! ### Declarations about `and` -/ lemma iff.and (h₁ : a ↔ b) (h₂ : c ↔ d) : a ∧ c ↔ b ∧ d := and_congr h₁ h₂ theorem and_congr_left (h : c → (a ↔ b)) : a ∧ c ↔ b ∧ c := and.comm.trans $ (and_congr_right h).trans and.comm theorem and_congr_left' (h : a ↔ b) : a ∧ c ↔ b ∧ c := h.and iff.rfl theorem and_congr_right' (h : b ↔ c) : a ∧ b ↔ a ∧ c := iff.rfl.and h 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 only [and.left_comm, and.comm] lemma and_and_and_comm (a b c d : Prop) : (a ∧ b) ∧ c ∧ d ↔ (a ∧ c) ∧ b ∧ d := by rw [←and_assoc, @and.right_comm a, and_assoc] lemma and_and_distrib_left (a b c : Prop) : a ∧ (b ∧ c) ↔ (a ∧ b) ∧ (a ∧ c) := by rw [and_and_and_comm, and_self] lemma and_and_distrib_right (a b c : Prop) : (a ∧ b) ∧ c ↔ (a ∧ c) ∧ (b ∧ c) := by rw [and_and_and_comm, and_self] lemma and_rotate : a ∧ b ∧ c ↔ b ∧ c ∧ a := by simp only [and.left_comm, and.comm] lemma and.rotate : a ∧ b ∧ c → b ∧ c ∧ a := and_rotate.1 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 ne_and_eq_iff_right {α : Sort*} {a b c : α} (h : b ≠ c) : a ≠ b ∧ a = c ↔ a = c := and_iff_right_of_imp (λ h2, h2.symm ▸ h.symm) @[simp] theorem and_iff_left_iff_imp {a b : Prop} : ((a ∧ b) ↔ a) ↔ (a → b) := ⟨λ h ha, (h.2 ha).2, and_iff_left_of_imp⟩ @[simp] theorem and_iff_right_iff_imp {a b : Prop} : ((a ∧ b) ↔ b) ↔ (b → a) := ⟨λ h ha, (h.2 ha).1, and_iff_right_of_imp⟩ @[simp] lemma iff_self_and {p q : Prop} : (p ↔ p ∧ q) ↔ (p → q) := by rw [@iff.comm p, and_iff_left_iff_imp] @[simp] lemma iff_and_self {p q : Prop} : (p ↔ q ∧ p) ↔ (p → q) := by rw [and_comm, iff_self_and] @[simp] 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.congr_left_iff : (a ∧ c ↔ b ∧ c) ↔ c → (a ↔ b) := by simp only [and.comm, ← and.congr_right_iff] @[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` -/ lemma iff.or (h₁ : a ↔ b) (h₂ : c ↔ d) : a ∨ c ↔ b ∨ d := or_congr h₁ h₂ lemma or_congr_left' (h : a ↔ b) : a ∨ c ↔ b ∨ c := h.or iff.rfl lemma or_congr_right' (h : b ↔ c) : a ∨ b ↔ a ∨ c := iff.rfl.or h theorem or.right_comm : (a ∨ b) ∨ c ↔ (a ∨ c) ∨ b := by rw [or_assoc, or_assoc, or_comm b] lemma or_or_or_comm (a b c d : Prop) : (a ∨ b) ∨ c ∨ d ↔ (a ∨ c) ∨ b ∨ d := by rw [←or_assoc, @or.right_comm a, or_assoc] lemma or_or_distrib_left (a b c : Prop) : a ∨ (b ∨ c) ↔ (a ∨ b) ∨ (a ∨ c) := by rw [or_or_or_comm, or_self] lemma or_or_distrib_right (a b c : Prop) : (a ∨ b) ∨ c ↔ (a ∨ c) ∨ (b ∨ c) := by rw [or_or_or_comm, or_self] lemma or_rotate : a ∨ b ∨ c ↔ b ∨ c ∨ a := by simp only [or.left_comm, or.comm] lemma or.rotate : a ∨ b ∨ c → b ∨ c ∨ a := or_rotate.1 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) lemma or.imp3 (had : a → d) (hbe : b → e) (hcf : c → f) : a ∨ b ∨ c → d ∨ e ∨ f := or.imp had $ or.imp hbe hcf 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⟩ -- See Note [decidable namespace] protected theorem decidable.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_left : a ∨ b ↔ (¬ a → b) := decidable.or_iff_not_imp_left -- See Note [decidable namespace] protected theorem decidable.or_iff_not_imp_right [decidable b] : a ∨ b ↔ (¬ b → a) := or.comm.trans decidable.or_iff_not_imp_left theorem or_iff_not_imp_right : a ∨ b ↔ (¬ b → a) := decidable.or_iff_not_imp_right -- See Note [decidable namespace] protected lemma decidable.not_or_of_imp [decidable a] (h : a → b) : ¬ a ∨ b := dite _ (or.inr ∘ h) or.inl lemma not_or_of_imp : (a → b) → ¬ a ∨ b := decidable.not_or_of_imp -- See Note [decidable namespace] protected lemma decidable.or_not_of_imp [decidable a] (h : a → b) : b ∨ ¬ a := dite _ (or.inl ∘ h) or.inr lemma or_not_of_imp : (a → b) → b ∨ ¬ a := decidable.or_not_of_imp -- See Note [decidable namespace] protected lemma decidable.imp_iff_not_or [decidable a] : a → b ↔ ¬ a ∨ b := ⟨decidable.not_or_of_imp, or.neg_resolve_left⟩ lemma imp_iff_not_or : a → b ↔ ¬ a ∨ b := decidable.imp_iff_not_or -- See Note [decidable namespace] protected lemma decidable.imp_iff_or_not [decidable b] : b → a ↔ a ∨ ¬ b := decidable.imp_iff_not_or.trans or.comm lemma imp_iff_or_not : b → a ↔ a ∨ ¬ b := decidable.imp_iff_or_not -- See Note [decidable namespace] protected theorem decidable.not_imp_not [decidable a] : (¬ a → ¬ b) ↔ (b → a) := ⟨assume h hb, decidable.by_contradiction $ assume na, h na hb, mt⟩ theorem not_imp_not : (¬ a → ¬ b) ↔ (b → a) := decidable.not_imp_not /-- Provide the reverse of modus tollens (`mt`) as dot notation for implications. -/ protected theorem function.mtr : (¬ a → ¬ b) → (b → a) := not_imp_not.mp -- See Note [decidable namespace] protected lemma decidable.or_congr_left [decidable c] (h : ¬ c → (a ↔ b)) : a ∨ c ↔ b ∨ c := by { rw [decidable.or_iff_not_imp_right, decidable.or_iff_not_imp_right], exact imp_congr_right h } lemma or_congr_left (h : ¬ c → (a ↔ b)) : a ∨ c ↔ b ∨ c := decidable.or_congr_left h -- See Note [decidable namespace] protected lemma decidable.or_congr_right [decidable a] (h : ¬ a → (b ↔ c)) : a ∨ b ↔ a ∨ c := by { rw [decidable.or_iff_not_imp_left, decidable.or_iff_not_imp_left], exact imp_congr_right h } lemma or_congr_right (h : ¬ a → (b ↔ c)) : a ∨ b ↔ a ∨ c := decidable.or_congr_right h @[simp] theorem or_iff_left_iff_imp : (a ∨ b ↔ a) ↔ (b → a) := ⟨λ h hb, h.1 (or.inr hb), or_iff_left_of_imp⟩ @[simp] theorem or_iff_right_iff_imp : (a ∨ b ↔ b) ↔ (a → b) := by rw [or_comm, or_iff_left_iff_imp] lemma or_iff_left (hb : ¬ b) : a ∨ b ↔ a := ⟨λ h, h.resolve_right hb, or.inl⟩ lemma or_iff_right (ha : ¬ a) : a ∨ b ↔ b := ⟨λ h, h.resolve_left ha, or.inr⟩ /-! ### Declarations about distributivity -/ /-- `∧` distributes over `∨` (on the left). -/ 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)⟩ /-- `∧` distributes over `∨` (on the right). -/ theorem or_and_distrib_right : (a ∨ b) ∧ c ↔ (a ∧ c) ∨ (b ∧ c) := (and.comm.trans and_or_distrib_left).trans (and.comm.or and.comm) /-- `∨` distributes over `∧` (on the left). -/ 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)⟩ /-- `∨` distributes over `∧` (on the right). -/ theorem and_or_distrib_right : (a ∧ b) ∨ c ↔ (a ∨ c) ∧ (b ∨ c) := (or.comm.trans or_and_distrib_left).trans (or.comm.and 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` -/ lemma iff.iff (h₁ : a ↔ b) (h₂ : c ↔ d) : (a ↔ c) ↔ (b ↔ d) := iff_congr h₁ h₂ 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) @[simp] lemma iff_mpr_iff_true_intro {P : Prop} (h : P) : iff.mpr (iff_true_intro h) true.intro = h := rfl -- See Note [decidable namespace] protected theorem decidable.imp_or_distrib [decidable a] : (a → b ∨ c) ↔ (a → b) ∨ (a → c) := by simp [decidable.imp_iff_not_or, or.comm, or.left_comm] theorem imp_or_distrib : (a → b ∨ c) ↔ (a → b) ∨ (a → c) := decidable.imp_or_distrib -- See Note [decidable namespace] protected theorem decidable.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 imp_or_distrib' : (a → b ∨ c) ↔ (a → b) ∨ (a → c) := decidable.imp_or_distrib' theorem not_imp_of_and_not : a ∧ ¬ b → ¬ (a → b) | ⟨ha, hb⟩ h := hb $ h ha -- See Note [decidable namespace] protected theorem decidable.not_imp [decidable a] : ¬(a → b) ↔ a ∧ ¬b := ⟨λ h, ⟨decidable.of_not_imp h, not_of_not_imp h⟩, not_imp_of_and_not⟩ theorem not_imp : ¬(a → b) ↔ a ∧ ¬b := decidable.not_imp -- for monotonicity lemma imp_imp_imp (h₀ : c → a) (h₁ : b → d) : (a → b) → (c → d) := assume (h₂ : a → b), h₁ ∘ h₂ ∘ h₀ -- See Note [decidable namespace] protected theorem decidable.peirce (a b : Prop) [decidable a] : ((a → b) → a) → a := if ha : a then λ h, ha else λ h, h ha.elim theorem peirce (a b : Prop) : ((a → b) → a) → a := decidable.peirce _ _ theorem peirce' {a : Prop} (H : ∀ b : Prop, (a → b) → a) : a := H _ id -- See Note [decidable namespace] protected theorem decidable.not_iff_not [decidable a] [decidable b] : (¬ a ↔ ¬ b) ↔ (a ↔ b) := by rw [@iff_def (¬ a), @iff_def' a]; exact decidable.not_imp_not.and decidable.not_imp_not theorem not_iff_not : (¬ a ↔ ¬ b) ↔ (a ↔ b) := decidable.not_iff_not -- See Note [decidable namespace] protected theorem decidable.not_iff_comm [decidable a] [decidable b] : (¬ a ↔ b) ↔ (¬ b ↔ a) := by rw [@iff_def (¬ a), @iff_def (¬ b)]; exact decidable.not_imp_comm.and imp_not_comm theorem not_iff_comm : (¬ a ↔ b) ↔ (¬ b ↔ a) := decidable.not_iff_comm -- See Note [decidable namespace] protected theorem decidable.not_iff : ∀ [decidable b], ¬ (a ↔ b) ↔ (¬ a ↔ b) := by intro h; cases h; simp only [h, iff_true, iff_false] theorem not_iff : ¬ (a ↔ b) ↔ (¬ a ↔ b) := decidable.not_iff -- See Note [decidable namespace] protected theorem decidable.iff_not_comm [decidable a] [decidable b] : (a ↔ ¬ b) ↔ (b ↔ ¬ a) := by rw [@iff_def a, @iff_def b]; exact imp_not_comm.and decidable.not_imp_comm theorem iff_not_comm : (a ↔ ¬ b) ↔ (b ↔ ¬ a) := decidable.iff_not_comm -- See Note [decidable namespace] protected theorem decidable.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 iff_iff_and_or_not_and_not : (a ↔ b) ↔ (a ∧ b) ∨ (¬ a ∧ ¬ b) := decidable.iff_iff_and_or_not_and_not lemma decidable.iff_iff_not_or_and_or_not [decidable a] [decidable b] : (a ↔ b) ↔ ((¬a ∨ b) ∧ (a ∨ ¬b)) := begin rw [iff_iff_implies_and_implies a b], simp only [decidable.imp_iff_not_or, or.comm] end lemma iff_iff_not_or_and_or_not : (a ↔ b) ↔ ((¬a ∨ b) ∧ (a ∨ ¬b)) := decidable.iff_iff_not_or_and_or_not -- See Note [decidable namespace] protected theorem decidable.not_and_not_right [decidable b] : ¬(a ∧ ¬b) ↔ (a → b) := ⟨λ h ha, h.decidable_imp_symm $ and.intro ha, λ h ⟨ha, hb⟩, hb $ h ha⟩ theorem not_and_not_right : ¬(a ∧ ¬b) ↔ (a → b) := decidable.not_and_not_right /-- Transfer decidability of `a` to decidability of `b`, if the propositions are equivalent. **Important**: this function should be used instead of `rw` on `decidable b`, because the kernel will get stuck reducing the usage of `propext` otherwise, and `dec_trivial` will not work. -/ @[inline] def decidable_of_iff (a : Prop) (h : a ↔ b) [D : decidable a] : decidable b := decidable_of_decidable_of_iff D h /-- Transfer decidability of `b` to decidability of `a`, if the propositions are equivalent. This is the same as `decidable_of_iff` but the iff is flipped. -/ @[inline] def decidable_of_iff' (b : Prop) (h : a ↔ b) [D : decidable b] : decidable a := decidable_of_decidable_of_iff D h.symm /-- Prove that `a` is decidable by constructing a boolean `b` and a proof that `b ↔ a`. (This is sometimes taken as an alternate definition of decidability.) -/ 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) -- See Note [decidable namespace] protected theorem decidable.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⟩ -- See Note [decidable namespace] protected theorem decidable.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⟩ /-- One of de Morgan's laws: the negation of a conjunction is logically equivalent to the disjunction of the negations. -/ theorem not_and_distrib : ¬ (a ∧ b) ↔ ¬a ∨ ¬b := decidable.not_and_distrib @[simp] theorem not_and : ¬ (a ∧ b) ↔ (a → ¬ b) := and_imp theorem not_and' : ¬ (a ∧ b) ↔ b → ¬a := not_and.trans imp_not_comm /-- One of de Morgan's laws: the negation of a disjunction is logically equivalent to the conjunction of the negations. -/ 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₂⟩ -- See Note [decidable namespace] protected theorem decidable.or_iff_not_and_not [decidable a] [decidable b] : a ∨ b ↔ ¬ (¬a ∧ ¬b) := by rw [← not_or_distrib, decidable.not_not] theorem or_iff_not_and_not : a ∨ b ↔ ¬ (¬a ∧ ¬b) := decidable.or_iff_not_and_not -- See Note [decidable namespace] protected theorem decidable.and_iff_not_or_not [decidable a] [decidable b] : a ∧ b ↔ ¬ (¬ a ∨ ¬ b) := by rw [← decidable.not_and_distrib, decidable.not_not] theorem and_iff_not_or_not : a ∧ b ↔ ¬ (¬ a ∨ ¬ b) := decidable.and_iff_not_or_not @[simp] theorem not_xor (P Q : Prop) : ¬ xor P Q ↔ (P ↔ Q) := by simp only [not_and, xor, not_or_distrib, not_not, ← iff_iff_implies_and_implies] theorem xor_iff_not_iff (P Q : Prop) : xor P Q ↔ ¬ (P ↔ Q) := (not_xor P Q).not_right theorem xor_iff_iff_not : xor a b ↔ (a ↔ ¬b) := by simp only [← @xor_not_right a, not_not] theorem xor_iff_not_iff' : xor a b ↔ (¬a ↔ b) := by simp only [← @xor_not_left _ b, not_not] end propositional /-! ### Declarations about equality -/ section mem variables {α β : Type*} [has_mem α β] {s t : β} {a b : α} lemma ne_of_mem_of_not_mem (h : a ∈ s) : b ∉ s → a ≠ b := mt $ λ e, e ▸ h lemma ne_of_mem_of_not_mem' (h : a ∈ s) : a ∉ t → s ≠ t := mt $ λ e, e ▸ h /-- **Alias** of `ne_of_mem_of_not_mem`. -/ lemma has_mem.mem.ne_of_not_mem : a ∈ s → b ∉ s → a ≠ b := ne_of_mem_of_not_mem /-- **Alias** of `ne_of_mem_of_not_mem'`. -/ lemma has_mem.mem.ne_of_not_mem' : a ∈ s → a ∉ t → s ≠ t := ne_of_mem_of_not_mem' end mem 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 -- todo: change name lemma ball_cond_comm {α} {s : α → Prop} {p : α → α → Prop} : (∀ a, s a → ∀ b, s b → p a b) ↔ (∀ a b, s a → s b → p a b) := ⟨λ h a b ha hb, h a ha b hb, λ h a ha b hb, h a b ha hb⟩ lemma ball_mem_comm {α β} [has_mem α β] {s : β} {p : α → α → Prop} : (∀ a b ∈ s, p a b) ↔ (∀ a b, a ∈ s → b ∈ s → p a b) := ball_cond_comm lemma ne_of_apply_ne {α β : Sort*} (f : α → β) {x y : α} (h : f x ≠ f y) : x ≠ y := λ (w : x = y), h (congr_arg f w) 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_eq_cast {α β : Sort*} (h : α = β) : eq.mp h = cast h := rfl @[simp] lemma eq_mpr_eq_cast {α β : Sort*} (h : α = β) : eq.mpr h = cast h.symm := rfl @[simp] lemma cast_cast : ∀ {α β γ : Sort*} (ha : α = β) (hb : β = γ) (a : α), cast hb (cast ha a) = cast (ha.trans hb) a | _ _ _ rfl rfl a := rfl @[simp] lemma congr_refl_left {α β : Sort*} (f : α → β) {a b : α} (h : a = b) : congr (eq.refl f) h = congr_arg f h := rfl @[simp] lemma congr_refl_right {α β : Sort*} {f g : α → β} (h : f = g) (a : α) : congr h (eq.refl a) = congr_fun h a := rfl @[simp] lemma congr_arg_refl {α β : Sort*} (f : α → β) (a : α) : congr_arg f (eq.refl a) = eq.refl (f a) := rfl @[simp] lemma congr_fun_rfl {α β : Sort*} (f : α → β) (a : α) : congr_fun (eq.refl f) a = eq.refl (f a) := rfl @[simp] lemma congr_fun_congr_arg {α β γ : Sort*} (f : α → β → γ) {a a' : α} (p : a = a') (b : β) : congr_fun (congr_arg f p) b = congr_arg (λ a, f a b) p := rfl lemma heq_of_cast_eq : ∀ {α β : Sort*} {a : α} {a' : β} (e : α = β) (h₂ : cast e a = a'), a == a' | α ._ a a' rfl h := eq.rec_on h (heq.refl _) lemma cast_eq_iff_heq {α β : Sort*} {a : α} {a' : β} {e : α = β} : cast e a = a' ↔ a == a' := ⟨heq_of_cast_eq _, λ h, by cases h; 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 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 {α β γ : Sort*} (f : α → β → γ) {x x' : α} {y y' : β} (hx : x = x') (hy : y = y') : f x y = f x' y' := by { subst hx, subst hy } variables {β : α → Sort*} {γ : Π a, β a → Sort*} {δ : Π a b, γ a b → Sort*} lemma congr_fun₂ {f g : Π a b, γ a b} (h : f = g) (a : α) (b : β a) : f a b = g a b := congr_fun (congr_fun h _) _ lemma congr_fun₃ {f g : Π a b c, δ a b c} (h : f = g) (a : α) (b : β a) (c : γ a b) : f a b c = g a b c := congr_fun₂ (congr_fun h _) _ _ lemma funext₂ {f g : Π a b, γ a b} (h : ∀ a b, f a b = g a b) : f = g := funext $ λ _, funext $ h _ lemma funext₃ {f g : Π a b c, δ a b c} (h : ∀ a b c, f a b c = g a b c) : f = g := funext $ λ _, funext₂ $ h _ end equality /-! ### Declarations about quantifiers -/ section quantifiers variables {α : Sort*} section dependent variables {β : α → Sort*} {γ : Π a, β a → Sort*} {δ : Π a b, γ a b → Sort*} {ε : Π a b c, δ a b c → Sort*} lemma pi_congr {β' : α → Sort*} (h : ∀ a, β a = β' a) : (Π a, β a) = Π a, β' a := (funext h : β = β') ▸ rfl lemma forall₂_congr {p q : Π a, β a → Prop} (h : ∀ a b, p a b ↔ q a b) : (∀ a b, p a b) ↔ ∀ a b, q a b := forall_congr $ λ a, forall_congr $ h a lemma forall₃_congr {p q : Π a b, γ a b → Prop} (h : ∀ a b c, p a b c ↔ q a b c) : (∀ a b c, p a b c) ↔ ∀ a b c, q a b c := forall_congr $ λ a, forall₂_congr $ h a lemma forall₄_congr {p q : Π a b c, δ a b c → Prop} (h : ∀ a b c d, p a b c d ↔ q a b c d) : (∀ a b c d, p a b c d) ↔ ∀ a b c d, q a b c d := forall_congr $ λ a, forall₃_congr $ h a lemma forall₅_congr {p q : Π a b c d, ε a b c d → Prop} (h : ∀ a b c d e, p a b c d e ↔ q a b c d e) : (∀ a b c d e, p a b c d e) ↔ ∀ a b c d e, q a b c d e := forall_congr $ λ a, forall₄_congr $ h a lemma exists₂_congr {p q : Π a, β a → Prop} (h : ∀ a b, p a b ↔ q a b) : (∃ a b, p a b) ↔ ∃ a b, q a b := exists_congr $ λ a, exists_congr $ h a lemma exists₃_congr {p q : Π a b, γ a b → Prop} (h : ∀ a b c, p a b c ↔ q a b c) : (∃ a b c, p a b c) ↔ ∃ a b c, q a b c := exists_congr $ λ a, exists₂_congr $ h a lemma exists₄_congr {p q : Π a b c, δ a b c → Prop} (h : ∀ a b c d, p a b c d ↔ q a b c d) : (∃ a b c d, p a b c d) ↔ ∃ a b c d, q a b c d := exists_congr $ λ a, exists₃_congr $ h a lemma exists₅_congr {p q : Π a b c d, ε a b c d → Prop} (h : ∀ a b c d e, p a b c d e ↔ q a b c d e) : (∃ a b c d e, p a b c d e) ↔ ∃ a b c d e, q a b c d e := exists_congr $ λ a, exists₄_congr $ h a lemma forall_imp {p q : α → Prop} (h : ∀ a, p a → q a) : (∀ a, p a) → ∀ a, q a := λ h' a, h a (h' a) lemma forall₂_imp {p q : Π a, β a → Prop} (h : ∀ a b, p a b → q a b) : (∀ a b, p a b) → ∀ a b, q a b := forall_imp $ λ i, forall_imp $ h i lemma forall₃_imp {p q : Π a b, γ a b → Prop} (h : ∀ a b c, p a b c → q a b c) : (∀ a b c, p a b c) → ∀ a b c, q a b c := forall_imp $ λ a, forall₂_imp $ h a lemma Exists.imp {p q : α → Prop} (h : ∀ a, (p a → q a)) : (∃ a, p a) → ∃ a, q a := exists_imp_exists h lemma Exists₂.imp {p q : Π a, β a → Prop} (h : ∀ a b, p a b → q a b) : (∃ a b, p a b) → ∃ a b, q a b := Exists.imp $ λ a, Exists.imp $ h a lemma Exists₃.imp {p q : Π a b, γ a b → Prop} (h : ∀ a b c, p a b c → q a b c) : (∃ a b c, p a b c) → ∃ a b c, q a b c := Exists.imp $ λ a, Exists₂.imp $ h a end dependent variables {ι β : Sort*} {κ : ι → Sort*} {p q : α → Prop} {b : Prop} 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 := ⟨swap, swap⟩ lemma forall₂_swap {ι₁ ι₂ : Sort*} {κ₁ : ι₁ → Sort*} {κ₂ : ι₂ → Sort*} {p : Π i₁, κ₁ i₁ → Π i₂, κ₂ i₂ → Prop} : (∀ i₁ j₁ i₂ j₂, p i₁ j₁ i₂ j₂) ↔ ∀ i₂ j₂ i₁ j₁, p i₁ j₁ i₂ j₂ := ⟨swap₂, swap₂⟩ /-- We intentionally restrict the type of `α` in this lemma so that this is a safer to use in simp than `forall_swap`. -/ lemma imp_forall_iff {α : Type*} {p : Prop} {q : α → Prop} : (p → ∀ x, q x) ↔ (∀ x, p → q x) := forall_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 forall_exists_index {q : (∃ x, p x) → Prop} : (∀ h, q h) ↔ ∀ x (h : p x), q ⟨x, h⟩ := ⟨λ h x hpx, h ⟨x, hpx⟩, λ h ⟨x, hpx⟩, h x hpx⟩ theorem exists_imp_distrib : ((∃ x, p x) → b) ↔ ∀ x, p x → b := forall_exists_index /-- 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) -- See Note [decidable namespace] protected theorem decidable.not_forall {p : α → Prop} [decidable (∃ x, ¬ p x)] [∀ x, decidable (p x)] : (¬ ∀ x, p x) ↔ ∃ x, ¬ p x := ⟨not.decidable_imp_symm $ λ nx x, nx.decidable_imp_symm $ λ h, ⟨x, h⟩, not_forall_of_exists_not⟩ @[simp] theorem not_forall {p : α → Prop} : (¬ ∀ x, p x) ↔ ∃ x, ¬ p x := decidable.not_forall -- See Note [decidable namespace] protected theorem decidable.not_forall_not [decidable (∃ x, p x)] : (¬ ∀ x, ¬ p x) ↔ ∃ x, p x := (@decidable.not_iff_comm _ _ _ (decidable_of_iff (¬ ∃ x, p x) not_exists)).1 not_exists theorem not_forall_not : (¬ ∀ x, ¬ p x) ↔ ∃ x, p x := decidable.not_forall_not -- See Note [decidable namespace] protected theorem decidable.not_exists_not [∀ x, decidable (p x)] : (¬ ∃ x, ¬ p x) ↔ ∀ x, p x := by simp [decidable.not_not] @[simp] theorem not_exists_not : (¬ ∃ x, ¬ p x) ↔ ∀ x, p x := decidable.not_exists_not theorem forall_imp_iff_exists_imp [ha : nonempty α] : ((∀ x, p x) → b) ↔ ∃ x, p x → b := let ⟨a⟩ := ha in ⟨λ h, not_forall_not.1 $ λ h', classical.by_cases (λ hb : b, h' a $ λ _, hb) (λ hb, hb $ h $ λ x, (not_imp.1 (h' x)).1), λ ⟨x, hx⟩ h, hx (h x)⟩ -- TODO: duplicate of a lemma in core theorem forall_true_iff : (α → true) ↔ true := implies_true_iff α -- 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 lemma exists_unique.exists {α : Sort*} {p : α → Prop} (h : ∃! x, p x) : ∃ x, p x := exists.elim h (λ x hx, ⟨x, and.left hx⟩) @[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⟩⟩ @[simp] theorem forall_const (α : Sort*) [i : nonempty α] : (α → b) ↔ b := ⟨i.elim, λ hb x, hb⟩ /-- For some reason simp doesn't use `forall_const` to simplify in this case. -/ @[simp] lemma forall_forall_const {α β : Type*} (p : β → Prop) [nonempty α] : (∀ x, α → p x) ↔ ∀ x, p x := forall_congr $ λ x, forall_const α @[simp] theorem exists_const (α : Sort*) [i : nonempty α] : (∃ x : α, b) ↔ b := ⟨λ ⟨x, h⟩, h, i.elim exists.intro⟩ theorem exists_unique_const (α : Sort*) [i : nonempty α] [subsingleton α] : (∃! x : α, b) ↔ b := by simp 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 forall_eq' {a' : α} : (∀a, a' = a → p a) ↔ p a' := by simp [@eq_comm _ a'] theorem and_forall_ne (a : α) : (p a ∧ ∀ b ≠ a, p b) ↔ ∀ b, p b := by simp only [← @forall_eq _ p a, ← forall_and_distrib, ← or_imp_distrib, classical.em, forall_const] -- this lemma is needed to simplify the output of `list.mem_cons_iff` @[simp] theorem forall_eq_or_imp {a' : α} : (∀ a, a = a' ∨ q a → p a) ↔ p a' ∧ ∀ a, q a → p a := by simp only [or_imp_distrib, forall_and_distrib, forall_eq] lemma ne.ne_or_ne {x y : α} (z : α) (h : x ≠ y) : x ≠ z ∨ y ≠ z := not_and_distrib.1 $ mt (and_imp.2 eq.substr) h.symm theorem exists_eq {a' : α} : ∃ a, a = a' := ⟨_, rfl⟩ @[simp] theorem exists_eq' {a' : α} : ∃ a, a' = a := ⟨_, rfl⟩ @[simp] theorem exists_unique_eq {a' : α} : ∃! a, a = a' := by simp only [eq_comm, exists_unique, and_self, forall_eq', exists_eq'] @[simp] theorem exists_unique_eq' {a' : α} : ∃! a, a' = a := by simp only [exists_unique, and_self, forall_eq', exists_eq'] @[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_eq_right_right {a' : α} : (∃ (a : α), p a ∧ q a ∧ a = a') ↔ p a' ∧ q a' := ⟨λ ⟨_, hp, hq, rfl⟩, ⟨hp, hq⟩, λ ⟨hp, hq⟩, ⟨a', hp, hq, rfl⟩⟩ @[simp] theorem exists_eq_right_right' {a' : α} : (∃ (a : α), p a ∧ q a ∧ a' = a) ↔ p a' ∧ q a' := ⟨λ ⟨_, hp, hq, rfl⟩, ⟨hp, hq⟩, λ ⟨hp, hq⟩, ⟨a', hp, hq, rfl⟩⟩ @[simp] theorem exists_apply_eq_apply (f : α → β) (a' : α) : ∃ a, f a = f a' := ⟨a', rfl⟩ @[simp] theorem exists_apply_eq_apply' (f : α → β) (a' : α) : ∃ a, f a' = f a := ⟨a', rfl⟩ @[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] lemma exists_or_eq_left (y : α) (p : α → Prop) : ∃ (x : α), x = y ∨ p x := ⟨y, or.inl rfl⟩ @[simp] lemma exists_or_eq_right (y : α) (p : α → Prop) : ∃ (x : α), p x ∨ x = y := ⟨y, or.inr rfl⟩ @[simp] lemma exists_or_eq_left' (y : α) (p : α → Prop) : ∃ (x : α), y = x ∨ p x := ⟨y, or.inl rfl⟩ @[simp] lemma exists_or_eq_right' (y : α) (p : α → Prop) : ∃ (x : α), p x ∨ y = x := ⟨y, or.inr rfl⟩ @[simp] theorem forall_apply_eq_imp_iff {f : α → β} {p : β → Prop} : (∀ a, ∀ b, f a = b → p b) ↔ (∀ a, p (f a)) := ⟨λ h a, h a (f a) rfl, λ h a b hab, hab ▸ h a⟩ @[simp] theorem forall_apply_eq_imp_iff' {f : α → β} {p : β → Prop} : (∀ b, ∀ a, f a = b → p b) ↔ (∀ a, p (f a)) := by { rw forall_swap, simp } @[simp] theorem forall_eq_apply_imp_iff {f : α → β} {p : β → Prop} : (∀ a, ∀ b, b = f a → p b) ↔ (∀ a, p (f a)) := by simp [@eq_comm _ _ (f _)] @[simp] theorem forall_eq_apply_imp_iff' {f : α → β} {p : β → Prop} : (∀ b, ∀ a, b = f a → p b) ↔ (∀ a, p (f a)) := by { rw forall_swap, simp } @[simp] theorem forall_apply_eq_imp_iff₂ {f : α → β} {p : α → Prop} {q : β → Prop} : (∀ b, ∀ a, p a → f a = b → q b) ↔ ∀ a, p a → q (f a) := ⟨λ h a ha, h (f a) a ha rfl, λ h b a ha hb, hb ▸ h a ha⟩ @[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⟩⟩ lemma exists₂_comm {ι₁ ι₂ : Sort*} {κ₁ : ι₁ → Sort*} {κ₂ : ι₂ → Sort*} {p : Π i₁, κ₁ i₁ → Π i₂, κ₂ i₂ → Prop} : (∃ i₁ j₁ i₂ j₂, p i₁ j₁ i₂ j₂) ↔ ∃ i₂ j₂ i₁ j₁, p i₁ j₁ i₂ j₂ := by simp only [@exists_comm (κ₁ _), @exists_comm ι₁] theorem and.exists {p q : Prop} {f : p ∧ q → Prop} : (∃ h, f h) ↔ ∃ hp hq, f ⟨hp, hq⟩ := ⟨λ ⟨h, H⟩, ⟨h.1, h.2, H⟩, λ ⟨hp, hq, H⟩, ⟨⟨hp, hq⟩, H⟩⟩ theorem forall_or_of_or_forall (h : b ∨ ∀x, p x) (x) : b ∨ p x := h.imp_right $ λ h₂, h₂ x -- See Note [decidable namespace] protected theorem decidable.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_left {q : Prop} {p : α → Prop} : (∀x, q ∨ p x) ↔ q ∨ (∀x, p x) := decidable.forall_or_distrib_left -- See Note [decidable namespace] protected theorem decidable.forall_or_distrib_right {q : Prop} {p : α → Prop} [decidable q] : (∀x, p x ∨ q) ↔ (∀x, p x) ∨ q := by simp [or_comm, decidable.forall_or_distrib_left] theorem forall_or_distrib_right {q : Prop} {p : α → Prop} : (∀x, p x ∨ q) ↔ (∀x, p x) ∨ q := decidable.forall_or_distrib_right @[simp] theorem exists_prop {p q : Prop} : (∃ h : p, q) ↔ p ∧ q := ⟨λ ⟨h₁, h₂⟩, ⟨h₁, h₂⟩, λ ⟨h₁, h₂⟩, ⟨h₁, h₂⟩⟩ theorem exists_unique_prop {p q : Prop} : (∃! h : p, q) ↔ p ∧ q := by simp @[simp] theorem exists_false : ¬ (∃a:α, false) := assume ⟨a, h⟩, h @[simp] lemma exists_unique_false : ¬ (∃! (a : α), false) := assume ⟨a, h, 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 theorem forall_prop_of_true {p : Prop} {q : p → Prop} (h : p) : (∀ h' : p, q h') ↔ q h := @forall_const (q h) p ⟨h⟩ theorem exists_prop_of_true {p : Prop} {q : p → Prop} (h : p) : (∃ h' : p, q h') ↔ q h := @exists_const (q h) p ⟨h⟩ lemma exists_iff_of_forall {p : Prop} {q : p → Prop} (h : ∀ h, q h) : (∃ h, q h) ↔ p := ⟨Exists.fst, λ H, ⟨H, h H⟩⟩ theorem exists_unique_prop_of_true {p : Prop} {q : p → Prop} (h : p) : (∃! h' : p, q h') ↔ q h := @exists_unique_const (q h) p ⟨h⟩ _ theorem forall_prop_of_false {p : Prop} {q : p → Prop} (hn : ¬ p) : (∀ h' : p, q h') ↔ true := iff_true_intro $ λ h, hn.elim h theorem exists_prop_of_false {p : Prop} {q : p → Prop} : ¬ p → ¬ (∃ h' : p, q h') := mt Exists.fst @[congr] lemma exists_prop_congr {p p' : Prop} {q q' : p → Prop} (hq : ∀ h, q h ↔ q' h) (hp : p ↔ p') : Exists q ↔ ∃ h : p', q' (hp.2 h) := ⟨λ ⟨_, _⟩, ⟨hp.1 ‹_›, (hq _).1 ‹_›⟩, λ ⟨_, _⟩, ⟨_, (hq _).2 ‹_›⟩⟩ @[congr] lemma exists_prop_congr' {p p' : Prop} {q q' : p → Prop} (hq : ∀ h, q h ↔ q' h) (hp : p ↔ p') : Exists q = ∃ h : p', q' (hp.2 h) := propext (exists_prop_congr hq _) /-- See `is_empty.exists_iff` for the `false` version. -/ @[simp] lemma exists_true_left (p : true → Prop) : (∃ x, p x) ↔ p true.intro := exists_prop_of_true _ 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₂ @[congr] lemma forall_prop_congr {p p' : Prop} {q q' : p → Prop} (hq : ∀ h, q h ↔ q' h) (hp : p ↔ p') : (∀ h, q h) ↔ ∀ h : p', q' (hp.2 h) := ⟨λ h1 h2, (hq _).1 (h1 (hp.2 _)), λ h1 h2, (hq _).2 (h1 (hp.1 h2))⟩ @[congr] lemma forall_prop_congr' {p p' : Prop} {q q' : p → Prop} (hq : ∀ h, q h ↔ q' h) (hp : p ↔ p') : (∀ h, q h) = ∀ h : p', q' (hp.2 h) := propext (forall_prop_congr hq _) /-- See `is_empty.forall_iff` for the `false` version. -/ @[simp] lemma forall_true_left (p : true → Prop) : (∀ x, p x) ↔ p true.intro := forall_prop_of_true _ 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 lemmas -/ namespace classical variables {α : Sort*} {p : α → Prop} theorem cases {p : Prop → Prop} (h1 : p true) (h2 : p false) : ∀a, p a := assume a, cases_on a h1 h2 /- use shortened names to avoid conflict when classical namespace is open. -/ /-- Any prop `p` is decidable classically. A shorthand for `classical.prop_decidable`. -/ noncomputable def dec (p : Prop) : decidable p := by apply_instance /-- Any predicate `p` is decidable classically. -/ noncomputable def dec_pred (p : α → Prop) : decidable_pred p := by apply_instance /-- Any relation `p` is decidable classically. -/ noncomputable def dec_rel (p : α → α → Prop) : decidable_rel p := by apply_instance /-- Any type `α` has decidable equality classically. -/ noncomputable def dec_eq (α : Sort*) : decidable_eq α := by apply_instance /-- Construct a function from a default value `H0`, and a function to use if there exists a value satisfying the predicate. -/ @[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⟩ /-- A version of `by_contradiction` that uses types instead of propositions. -/ protected noncomputable def by_contradiction' {α : Sort*} (H : ¬ (α → false)) : α := classical.choice $ peirce _ false $ λ h, (H $ λ a, h ⟨a⟩).elim /-- `classical.by_contradiction'` is equivalent to lean's axiom `classical.choice`. -/ def choice_of_by_contradiction' {α : Sort*} (contra : ¬ (α → false) → α) : nonempty α → α := λ H, contra H.elim end classical /-- This function has the same type as `exists.rec_on`, and can be used to case on an equality, but `exists.rec_on` can only eliminate into Prop, while this version eliminates into any universe using the axiom of choice. -/ @[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 bex_eq_left {a : α} : (∃ x (_ : x = a), p x) ↔ p a := by simp only [exists_prop, exists_eq_left] 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 -- See Note [decidable namespace] protected theorem decidable.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.decidable_imp_symm $ λ nx x h, nx.decidable_imp_symm $ λ h', ⟨x, h, h'⟩, not_ball_of_bex_not⟩ theorem not_ball : (¬ ∀ x h, P x h) ↔ (∃ x h, ¬ P x h) := decidable.not_ball 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 theorem ball_or_left_distrib : (∀ x, p x ∨ q x → r x) ↔ (∀ x, p x → r x) ∧ (∀ x, q x → r x) := iff.trans (forall_congr $ λ x, or_imp_distrib) forall_and_distrib theorem bex_or_left_distrib : (∃ x (_ : p x ∨ q x), r x) ↔ (∃ x (_ : p x), r x) ∨ (∃ x (_ : q x), r x) := by simp only [exists_prop]; exact iff.trans (exists_congr $ λ x, or_and_distrib_right) 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 section ite variables {α β γ : Sort*} {σ : α → Sort*} (f : α → β) {P Q : Prop} [decidable P] [decidable Q] {a b c : α} {A : P → α} {B : ¬ P → α} lemma dite_eq_iff : dite P A B = c ↔ (∃ h, A h = c) ∨ ∃ h, B h = c := by by_cases P; simp [*, exists_prop_of_false not_false] lemma ite_eq_iff : ite P a b = c ↔ P ∧ a = c ∨ ¬ P ∧ b = c := dite_eq_iff.trans $ by rw [exists_prop, exists_prop] lemma dite_eq_iff' : dite P A B = c ↔ (∀ h, A h = c) ∧ (∀ h, B h = c) := ⟨λ he, ⟨λ h, (dif_pos h).symm.trans he, λ h, (dif_neg h).symm.trans he⟩, λ he, (em P).elim (λ h, (dif_pos h).trans $ he.1 h) (λ h, (dif_neg h).trans $ he.2 h)⟩ lemma ite_eq_iff' : ite P a b = c ↔ (P → a = c) ∧ (¬ P → b = c) := dite_eq_iff' @[simp] lemma dite_eq_left_iff : dite P (λ _, a) B = a ↔ ∀ h, B h = a := by by_cases P; simp [*, forall_prop_of_false not_false] @[simp] lemma dite_eq_right_iff : dite P A (λ _, b) = b ↔ ∀ h, A h = b := by by_cases P; simp [*, forall_prop_of_false not_false] @[simp] lemma ite_eq_left_iff : ite P a b = a ↔ (¬ P → b = a) := dite_eq_left_iff @[simp] lemma ite_eq_right_iff : ite P a b = b ↔ (P → a = b) := dite_eq_right_iff lemma dite_ne_left_iff : dite P (λ _, a) B ≠ a ↔ ∃ h, a ≠ B h := by { rw [ne.def, dite_eq_left_iff, not_forall], exact exists_congr (λ h, by rw ne_comm) } lemma dite_ne_right_iff : dite P A (λ _, b) ≠ b ↔ ∃ h, A h ≠ b := by simp only [ne.def, dite_eq_right_iff, not_forall] lemma ite_ne_left_iff : ite P a b ≠ a ↔ ¬ P ∧ a ≠ b := dite_ne_left_iff.trans $ by rw exists_prop lemma ite_ne_right_iff : ite P a b ≠ b ↔ P ∧ a ≠ b := dite_ne_right_iff.trans $ by rw exists_prop protected lemma ne.dite_eq_left_iff (h : ∀ h, a ≠ B h) : dite P (λ _, a) B = a ↔ P := dite_eq_left_iff.trans $ ⟨λ H, of_not_not $ λ h', h h' (H h').symm, λ h H, (H h).elim⟩ protected lemma ne.dite_eq_right_iff (h : ∀ h, A h ≠ b) : dite P A (λ _, b) = b ↔ ¬ P := dite_eq_right_iff.trans $ ⟨λ H h', h h' (H h'), λ h' H, (h' H).elim⟩ protected lemma ne.ite_eq_left_iff (h : a ≠ b) : ite P a b = a ↔ P := ne.dite_eq_left_iff $ λ _, h protected lemma ne.ite_eq_right_iff (h : a ≠ b) : ite P a b = b ↔ ¬ P := ne.dite_eq_right_iff $ λ _, h protected lemma ne.dite_ne_left_iff (h : ∀ h, a ≠ B h) : dite P (λ _, a) B ≠ a ↔ ¬ P := dite_ne_left_iff.trans $ exists_iff_of_forall h protected lemma ne.dite_ne_right_iff (h : ∀ h, A h ≠ b) : dite P A (λ _, b) ≠ b ↔ P := dite_ne_right_iff.trans $ exists_iff_of_forall h protected lemma ne.ite_ne_left_iff (h : a ≠ b) : ite P a b ≠ a ↔ ¬ P := ne.dite_ne_left_iff $ λ _, h protected lemma ne.ite_ne_right_iff (h : a ≠ b) : ite P a b ≠ b ↔ P := ne.dite_ne_right_iff $ λ _, h variables (P Q) (a b) /-- A `dite` whose results do not actually depend on the condition may be reduced to an `ite`. -/ @[simp] lemma dite_eq_ite : dite P (λ h, a) (λ h, b) = ite P a b := rfl lemma dite_eq_or_eq : (∃ h, dite P A B = A h) ∨ ∃ h, dite P A B = B h := decidable.by_cases (λ h, or.inl ⟨h, dif_pos h⟩) (λ h, or.inr ⟨h, dif_neg h⟩) lemma ite_eq_or_eq : ite P a b = a ∨ ite P a b = b := decidable.by_cases (λ h, or.inl (if_pos h)) (λ h, or.inr (if_neg h)) /-- A function applied to a `dite` is a `dite` of that function applied to each of the branches. -/ lemma apply_dite (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] /-- A function applied to a `ite` is a `ite` of that function applied to each of the branches. -/ lemma apply_ite : f (ite P a b) = ite P (f a) (f b) := apply_dite f P (λ _, a) (λ _, b) /-- A two-argument function applied to two `dite`s is a `dite` of that two-argument function applied to each of the branches. -/ lemma apply_dite2 (f : α → β → γ) (P : Prop) [decidable P] (a : P → α) (b : ¬P → α) (c : P → β) (d : ¬P → β) : f (dite P a b) (dite P c d) = dite P (λ h, f (a h) (c h)) (λ h, f (b h) (d h)) := by by_cases h : P; simp [h] /-- A two-argument function applied to two `ite`s is a `ite` of that two-argument function applied to each of the branches. -/ lemma apply_ite2 (f : α → β → γ) (P : Prop) [decidable P] (a b : α) (c d : β) : f (ite P a b) (ite P c d) = ite P (f a c) (f b d) := apply_dite2 f P (λ _, a) (λ _, b) (λ _, c) (λ _, d) /-- A 'dite' producing a `Pi` type `Π a, σ a`, applied to a value `a : α` is a `dite` that applies either branch to `a`. -/ lemma dite_apply (f : P → Π a, σ a) (g : ¬ P → Π a, σ a) (a : α) : (dite P f g) a = dite P (λ h, f h a) (λ h, g h a) := by by_cases h : P; simp [h] /-- A 'ite' producing a `Pi` type `Π a, σ a`, applied to a value `a : α` is a `ite` that applies either branch to `a`. -/ lemma ite_apply (f g : Π a, σ a) (a : α) : (ite P f g) a = ite P (f a) (g a) := dite_apply P (λ _, f) (λ _, g) a /-- Negation of the condition `P : Prop` in a `dite` is the same as swapping the branches. -/ @[simp] lemma dite_not (x : ¬ P → α) (y : ¬¬ P → α) : dite (¬ P) x y = dite P (λ h, y (not_not_intro h)) x := by by_cases h : P; simp [h] /-- Negation of the condition `P : Prop` in a `ite` is the same as swapping the branches. -/ @[simp] lemma ite_not : ite (¬ P) a b = ite P b a := dite_not P (λ _, a) (λ _, b) lemma ite_and : ite (P ∧ Q) a b = ite P (ite Q a b) b := by by_cases hp : P; by_cases hq : Q; simp [hp, hq] lemma dite_dite_comm {B : Q → α} {C : ¬P → ¬Q → α} (h : P → ¬Q) : (if p : P then A p else if q : Q then B q else C p q) = (if q : Q then B q else if p : P then A p else C p q) := dite_eq_iff'.2 ⟨λ p, by rw [dif_neg (h p), dif_pos p], λ np, by { congr, funext, rw dif_neg np }⟩ lemma ite_ite_comm (h : P → ¬Q) : (if P then a else if Q then b else c) = (if Q then b else if P then a else c) := dite_dite_comm P Q h end ite
c0b779f2968e2c5ef9486ef9f0a3cbd58c9100ce
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/data/int/interval.lean
f44ee6ce0d92de42103b394e9848d9f529b019ae
[ "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
5,754
lean
/- Copyright (c) 2021 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import algebra.char_zero import data.int.basic import data.nat.interval /-! # Finite intervals of integers This file proves that `ℤ` is a `locally_finite_order` and calculates the cardinality of its intervals as finsets and fintypes. -/ open finset int instance : locally_finite_order ℤ := { finset_Icc := λ a b, (finset.range (b + 1 - a).to_nat).map $ nat.cast_embedding.trans $ add_left_embedding a, finset_Ico := λ a b, (finset.range (b - a).to_nat).map $ nat.cast_embedding.trans $ add_left_embedding a, finset_Ioc := λ a b, (finset.range (b - a).to_nat).map $ nat.cast_embedding.trans $ add_left_embedding (a + 1), finset_Ioo := λ a b, (finset.range (b - a - 1).to_nat).map $ nat.cast_embedding.trans $ add_left_embedding (a + 1), finset_mem_Icc := λ a b x, begin simp_rw [mem_map, exists_prop, mem_range, int.lt_to_nat, function.embedding.trans_apply, nat.cast_embedding_apply, add_left_embedding_apply, nat_cast_eq_coe_nat], split, { rintro ⟨a, h, rfl⟩, rw [lt_sub_iff_add_lt, int.lt_add_one_iff, add_comm] at h, exact ⟨int.le.intro rfl, h⟩ }, { rintro ⟨ha, hb⟩, use (x - a).to_nat, rw ←lt_add_one_iff at hb, rw to_nat_sub_of_le ha, exact ⟨sub_lt_sub_right hb _, add_sub_cancel'_right _ _⟩ } end, finset_mem_Ico := λ a b x, begin simp_rw [mem_map, exists_prop, mem_range, int.lt_to_nat, function.embedding.trans_apply, nat.cast_embedding_apply, add_left_embedding_apply, nat_cast_eq_coe_nat], split, { rintro ⟨a, h, rfl⟩, exact ⟨int.le.intro rfl, lt_sub_iff_add_lt'.mp h⟩ }, { rintro ⟨ha, hb⟩, use (x - a).to_nat, rw to_nat_sub_of_le ha, exact ⟨sub_lt_sub_right hb _, add_sub_cancel'_right _ _⟩ } end, finset_mem_Ioc := λ a b x, begin simp_rw [mem_map, exists_prop, mem_range, int.lt_to_nat, function.embedding.trans_apply, nat.cast_embedding_apply, add_left_embedding_apply, nat_cast_eq_coe_nat], split, { rintro ⟨a, h, rfl⟩, rw [←add_one_le_iff, le_sub_iff_add_le', add_comm _ (1 : ℤ), ←add_assoc] at h, exact ⟨int.le.intro rfl, h⟩ }, { rintro ⟨ha, hb⟩, use (x - (a + 1)).to_nat, rw [to_nat_sub_of_le ha, ←add_one_le_iff, sub_add, add_sub_cancel], exact ⟨sub_le_sub_right hb _, add_sub_cancel'_right _ _⟩ } end, finset_mem_Ioo := λ a b x, begin simp_rw [mem_map, exists_prop, mem_range, int.lt_to_nat, function.embedding.trans_apply, nat.cast_embedding_apply, add_left_embedding_apply, nat_cast_eq_coe_nat], split, { rintro ⟨a, h, rfl⟩, rw [sub_sub, lt_sub_iff_add_lt'] at h, exact ⟨int.le.intro rfl, h⟩ }, { rintro ⟨ha, hb⟩, use (x - (a + 1)).to_nat, rw [to_nat_sub_of_le ha, sub_sub], exact ⟨sub_lt_sub_right hb _, add_sub_cancel'_right _ _⟩ } end } namespace int variables (a b : ℤ) lemma Icc_eq_finset_map : Icc a b = (finset.range (b + 1 - a).to_nat).map (nat.cast_embedding.trans $ add_left_embedding a) := rfl lemma Ico_eq_finset_map : Ico a b = (finset.range (b - a).to_nat).map (nat.cast_embedding.trans $ add_left_embedding a) := rfl lemma Ioc_eq_finset_map : Ioc a b = (finset.range (b - a).to_nat).map (nat.cast_embedding.trans $ add_left_embedding (a + 1)) := rfl lemma Ioo_eq_finset_map : Ioo a b = (finset.range (b - a - 1).to_nat).map (nat.cast_embedding.trans $ add_left_embedding (a + 1)) := rfl @[simp] lemma card_Icc : (Icc a b).card = (b + 1 - a).to_nat := by { change (finset.map _ _).card = _, rw [finset.card_map, finset.card_range] } @[simp] lemma card_Ico : (Ico a b).card = (b - a).to_nat := by { change (finset.map _ _).card = _, rw [finset.card_map, finset.card_range] } @[simp] lemma card_Ioc : (Ioc a b).card = (b - a).to_nat := by { change (finset.map _ _).card = _, rw [finset.card_map, finset.card_range] } @[simp] lemma card_Ioo : (Ioo a b).card = (b - a - 1).to_nat := by { change (finset.map _ _).card = _, rw [finset.card_map, finset.card_range] } lemma card_Icc_of_le (h : a ≤ b + 1) : ((Icc a b).card : ℤ) = b + 1 - a := by rw [card_Icc, to_nat_sub_of_le h] lemma card_Ico_of_le (h : a ≤ b) : ((Ico a b).card : ℤ) = b - a := by rw [card_Ico, to_nat_sub_of_le h] lemma card_Ioc_of_le (h : a ≤ b) : ((Ioc a b).card : ℤ) = b - a := by rw [card_Ioc, to_nat_sub_of_le h] lemma card_Ioo_of_lt (h : a < b) : ((Ioo a b).card : ℤ) = b - a - 1 := by rw [card_Ioo, sub_sub, to_nat_sub_of_le h] @[simp] lemma card_fintype_Icc : fintype.card (set.Icc a b) = (b + 1 - a).to_nat := by rw [←card_Icc, fintype.card_of_finset] @[simp] lemma card_fintype_Ico : fintype.card (set.Ico a b) = (b - a).to_nat := by rw [←card_Ico, fintype.card_of_finset] @[simp] lemma card_fintype_Ioc : fintype.card (set.Ioc a b) = (b - a).to_nat := by rw [←card_Ioc, fintype.card_of_finset] @[simp] lemma card_fintype_Ioo : fintype.card (set.Ioo a b) = (b - a - 1).to_nat := by rw [←card_Ioo, fintype.card_of_finset] lemma card_fintype_Icc_of_le (h : a ≤ b + 1) : (fintype.card (set.Icc a b) : ℤ) = b + 1 - a := by rw [card_fintype_Icc, to_nat_sub_of_le h] lemma card_fintype_Ico_of_le (h : a ≤ b) : (fintype.card (set.Ico a b) : ℤ) = b - a := by rw [card_fintype_Ico, to_nat_sub_of_le h] lemma card_fintype_Ioc_of_le (h : a ≤ b) : (fintype.card (set.Ioc a b) : ℤ) = b - a := by rw [card_fintype_Ioc, to_nat_sub_of_le h] lemma card_fintype_Ioo_of_lt (h : a < b) : (fintype.card (set.Ioo a b) : ℤ) = b - a - 1 := by rw [card_fintype_Ioo, sub_sub, to_nat_sub_of_le h] end int
6ad5117c8e0d8b519bdbe6386536a1e11cb333de
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/hott/types/pointed.hlean
2111309695a5f6087f3864e56cb16d933f7355e0
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
12,963
hlean
/- Copyright (c) 2014 Jakob von Raumer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jakob von Raumer, Floris van Doorn Ported from Coq HoTT -/ import arity .eq .bool .unit .sigma .nat.basic open is_trunc eq prod sigma nat equiv option is_equiv bool unit algebra structure pointed [class] (A : Type) := (point : A) structure Pointed := {carrier : Type} (Point : carrier) open Pointed notation `Type*` := Pointed namespace pointed attribute Pointed.carrier [coercion] variables {A B : Type} definition pt [unfold 2] [H : pointed A] := point A protected definition Mk [constructor] := @Pointed.mk protected definition MK [constructor] (A : Type) (a : A) := Pointed.mk a protected definition mk' [constructor] (A : Type) [H : pointed A] : Type* := Pointed.mk (point A) definition pointed_carrier [instance] [constructor] (A : Type*) : pointed A := pointed.mk (Point A) -- Any contractible type is pointed definition pointed_of_is_contr [instance] [priority 800] [constructor] (A : Type) [H : is_contr A] : pointed A := pointed.mk !center -- A pi type with a pointed target is pointed definition pointed_pi [instance] [constructor] (P : A → Type) [H : Πx, pointed (P x)] : pointed (Πx, P x) := pointed.mk (λx, pt) -- A sigma type of pointed components is pointed definition pointed_sigma [instance] [constructor] (P : A → Type) [G : pointed A] [H : pointed (P pt)] : pointed (Σx, P x) := pointed.mk ⟨pt,pt⟩ definition pointed_prod [instance] [constructor] (A B : Type) [H1 : pointed A] [H2 : pointed B] : pointed (A × B) := pointed.mk (pt,pt) definition pointed_loop [instance] [constructor] (a : A) : pointed (a = a) := pointed.mk idp definition pointed_bool [instance] [constructor] : pointed bool := pointed.mk ff definition Prod [constructor] (A B : Type*) : Type* := pointed.mk' (A × B) infixr ` ×* `:35 := Prod definition Bool [constructor] : Type* := pointed.mk' bool definition Unit [constructor] : Type* := Pointed.mk unit.star definition pointed_fun_closed [constructor] (f : A → B) [H : pointed A] : pointed B := pointed.mk (f pt) definition Loop_space [reducible] [constructor] (A : Type*) : Type* := pointed.mk' (point A = point A) definition Iterated_loop_space [unfold 1] [reducible] : ℕ → Type* → Type* | Iterated_loop_space 0 X := X | Iterated_loop_space (n+1) X := Loop_space (Iterated_loop_space n X) prefix `Ω`:(max+5) := Loop_space notation `Ω[`:95 n:0 `] `:0 A:95 := Iterated_loop_space n A definition rfln [constructor] [reducible] {A : Type*} {n : ℕ} : Ω[n] A := pt definition refln [constructor] [reducible] (A : Type*) (n : ℕ) : Ω[n] A := pt definition refln_eq_refl (A : Type*) (n : ℕ) : rfln = rfl :> Ω[succ n] A := rfl definition iterated_loop_space [unfold 3] (A : Type) [H : pointed A] (n : ℕ) : Type := Ω[n] (pointed.mk' A) open equiv.ops definition Pointed_eq {A B : Type*} (f : A ≃ B) (p : f pt = pt) : A = B := begin cases A with A a, cases B with B b, esimp at *, fapply apd011 @Pointed.mk, { apply ua f}, { rewrite [cast_ua,p]}, end protected definition Pointed.sigma_char.{u} : Pointed.{u} ≃ Σ(X : Type.{u}), X := begin fapply equiv.MK, { intro x, induction x with X x, exact ⟨X, x⟩}, { intro x, induction x with X x, exact pointed.MK X x}, { intro x, induction x with X x, reflexivity}, { intro x, induction x with X x, reflexivity}, end definition add_point [constructor] (A : Type) : Type* := Pointed.mk (none : option A) postfix `₊`:(max+1) := add_point -- the inclusion A → A₊ is called "some", the extra point "pt" or "none" ("@none A") end pointed open pointed structure pmap (A B : Type*) := (map : A → B) (resp_pt : map (Point A) = Point B) open pmap namespace pointed abbreviation respect_pt [unfold 3] := @pmap.resp_pt notation `map₊` := pmap infix ` →* `:30 := pmap attribute pmap.map [coercion] variables {A B C D : Type*} {f g h : A →* B} definition pmap_eq (r : Πa, f a = g a) (s : respect_pt f = (r pt) ⬝ respect_pt g) : f = g := begin cases f with f p, cases g with g q, esimp at *, fapply apo011 pmap.mk, { exact eq_of_homotopy r}, { apply concato_eq, apply pathover_eq_Fl, apply inv_con_eq_of_eq_con, rewrite [ap_eq_ap10,↑ap10,apd10_eq_of_homotopy,s]} end definition pid [constructor] (A : Type*) : A →* A := pmap.mk id idp definition pcompose [constructor] (g : B →* C) (f : A →* B) : A →* C := pmap.mk (λa, g (f a)) (ap g (respect_pt f) ⬝ respect_pt g) infixr ` ∘* `:60 := pcompose -- The constant pointed map between any two types definition pconst [constructor] (A B : Type*) : A →* B := pmap.mk (λ a, Point B) idp structure phomotopy (f g : A →* B) := (homotopy : f ~ g) (homotopy_pt : homotopy pt ⬝ respect_pt g = respect_pt f) infix ` ~* `:50 := phomotopy abbreviation to_homotopy_pt [unfold 5] := @phomotopy.homotopy_pt abbreviation to_homotopy [coercion] [unfold 5] (p : f ~* g) : Πa, f a = g a := phomotopy.homotopy p definition passoc (h : C →* D) (g : B →* C) (f : A →* B) : (h ∘* g) ∘* f ~* h ∘* (g ∘* f) := begin fconstructor, intro a, reflexivity, cases A, cases B, cases C, cases D, cases f with f pf, cases g with g pg, cases h with h ph, esimp at *, induction pf, induction pg, induction ph, reflexivity end definition pid_comp (f : A →* B) : pid B ∘* f ~* f := begin fconstructor, { intro a, reflexivity}, { esimp, exact !idp_con ⬝ !ap_id⁻¹} end definition comp_pid (f : A →* B) : f ∘* pid A ~* f := begin fconstructor, { intro a, reflexivity}, { reflexivity} end definition pmap_equiv_left (A : Type) (B : Type*) : A₊ →* B ≃ (A → B) := begin fapply equiv.MK, { intro f a, cases f with f p, exact f (some a)}, { intro f, fconstructor, intro a, cases a, exact pt, exact f a, reflexivity}, { intro f, reflexivity}, { intro f, cases f with f p, esimp, fapply pmap_eq, { intro a, cases a; all_goals (esimp at *), exact p⁻¹}, { esimp, exact !con.left_inv⁻¹}}, end -- set_option pp.notation false -- definition pmap_equiv_right (A : Type*) (B : Type) -- : (Σ(b : B), map₊ A (pointed.Mk b)) ≃ (A → B) := -- begin -- fapply equiv.MK, -- { intro u a, cases u with b f, cases f with f p, esimp at f, exact f a}, -- { intro f, refine ⟨f pt, _⟩, fapply pmap.mk, -- intro a, esimp, exact f a, -- reflexivity}, -- { intro f, reflexivity}, -- { intro u, cases u with b f, cases f with f p, esimp at *, apply sigma_eq p, -- esimp, apply sorry -- } -- end definition pmap_bool_equiv (B : Type*) : map₊ Bool B ≃ B := begin fapply equiv.MK, { intro f, cases f with f p, exact f tt}, { intro b, fconstructor, intro u, cases u, exact pt, exact b, reflexivity}, { intro b, reflexivity}, { intro f, cases f with f p, esimp, fapply pmap_eq, { intro a, cases a; all_goals (esimp at *), exact p⁻¹}, { esimp, exact !con.left_inv⁻¹}}, end definition ap1 [constructor] (f : A →* B) : Ω A →* Ω B := begin fconstructor, { intro p, exact !respect_pt⁻¹ ⬝ ap f p ⬝ !respect_pt}, { esimp, apply con.left_inv} end definition apn [unfold 3] (n : ℕ) (f : map₊ A B) : Ω[n] A →* Ω[n] B := begin induction n with n IH, { exact f}, { esimp [Iterated_loop_space], exact ap1 IH} end variable (A) definition loop_space_succ_eq_in (n : ℕ) : Ω[succ n] A = Ω[n] (Ω A) := begin induction n with n IH, { reflexivity}, { exact ap Loop_space IH} end definition loop_space_add (n m : ℕ) : Ω[n] (Ω[m] A) = Ω[m+n] (A) := begin induction n with n IH, { reflexivity}, { exact ap Loop_space IH} end definition loop_space_succ_eq_out (n : ℕ) : Ω[succ n] A = Ω(Ω[n] A) := idp variable {A} /- the equality [loop_space_succ_eq_in] preserves concatenation -/ theorem loop_space_succ_eq_in_concat {n : ℕ} (p q : Ω[succ (succ n)] A) : transport carrier (ap Loop_space (loop_space_succ_eq_in A n)) (p ⬝ q) = transport carrier (ap Loop_space (loop_space_succ_eq_in A n)) p ⬝ transport carrier (ap Loop_space (loop_space_succ_eq_in A n)) q := begin rewrite [-+tr_compose, ↑function.compose], rewrite [+@transport_eq_FlFr_D _ _ _ _ Point Point, +con.assoc], apply whisker_left, rewrite [-+con.assoc], apply whisker_right, rewrite [con_inv_cancel_right, ▸*, -ap_con] end definition loop_space_loop_irrel (p : point A = point A) : Ω(Pointed.mk p) = Ω[2] A := begin intros, fapply Pointed_eq, { esimp, transitivity _, apply eq_equiv_fn_eq_of_equiv (equiv_eq_closed_right _ p⁻¹), esimp, apply eq_equiv_eq_closed, apply con.right_inv, apply con.right_inv}, { esimp, apply con.left_inv} end definition iterated_loop_space_loop_irrel (n : ℕ) (p : point A = point A) : Ω[succ n](Pointed.mk p) = Ω[succ (succ n)] A :> Pointed := calc Ω[succ n](Pointed.mk p) = Ω[n](Ω (Pointed.mk p)) : loop_space_succ_eq_in ... = Ω[n] (Ω[2] A) : loop_space_loop_irrel ... = Ω[2+n] A : loop_space_add ... = Ω[n+2] A : by rewrite [algebra.add.comm] -- TODO: -- definition apn_compose (n : ℕ) (g : B →* C) (f : A →* B) : apn n (g ∘* f) ~* apn n g ∘* apn n f := -- _ definition ap1_compose (g : B →* C) (f : A →* B) : ap1 (g ∘* f) ~* ap1 g ∘* ap1 f := begin induction B, induction C, induction g with g pg, induction f with f pf, esimp at *, induction pg, induction pf, fconstructor, { intro p, esimp, apply whisker_left, exact ap_compose g f p ⬝ ap (ap g) !idp_con⁻¹}, { reflexivity} end protected definition phomotopy.refl [refl] (f : A →* B) : f ~* f := begin fconstructor, { intro a, exact idp}, { apply idp_con} end protected definition phomotopy.trans [trans] (p : f ~* g) (q : g ~* h) : f ~* h := begin fconstructor, { intro a, exact p a ⬝ q a}, { induction f, induction g, induction p with p p', induction q with q q', esimp at *, induction p', induction q', esimp, apply con.assoc} end protected definition phomotopy.symm [symm] (p : f ~* g) : g ~* f := begin fconstructor, { intro a, exact (p a)⁻¹}, { induction f, induction p with p p', esimp at *, induction p', esimp, apply inv_con_cancel_left} end infix ` ⬝* `:75 := phomotopy.trans postfix `⁻¹*`:(max+1) := phomotopy.symm definition eq_of_phomotopy (p : f ~* g) : f = g := begin fapply pmap_eq, { intro a, exact p a}, { exact !to_homotopy_pt⁻¹} end definition pwhisker_left (h : B →* C) (p : f ~* g) : h ∘* f ~* h ∘* g := begin fconstructor, { intro a, exact ap h (p a)}, { induction A, induction B, induction C, induction f with f pf, induction g with g pg, induction h with h ph, induction p with p p', esimp at *, induction ph, induction pg, induction p', reflexivity} end definition pwhisker_right (h : C →* A) (p : f ~* g) : f ∘* h ~* g ∘* h := begin fconstructor, { intro a, exact p (h a)}, { induction A, induction B, induction C, induction f with f pf, induction g with g pg, induction h with h ph, induction p with p p', esimp at *, induction ph, induction pg, induction p', esimp, exact !idp_con⁻¹} end structure pequiv (A B : Type*) := (to_pmap : A →* B) (is_equiv_to_pmap : is_equiv to_pmap) infix ` ≃* `:25 := pequiv attribute pequiv.to_pmap [coercion] attribute pequiv.is_equiv_to_pmap [instance] definition pequiv.mk' (to_pmap : A →* B) [is_equiv_to_pmap : is_equiv to_pmap] : pequiv A B := pequiv.mk to_pmap is_equiv_to_pmap definition pequiv_of_equiv [constructor] (eqv : A ≃ B) (resp : equiv.to_fun eqv (point A) = point B) : A ≃* B := pequiv.mk' (pmap.mk (equiv.to_fun eqv) resp) definition equiv_of_pequiv [constructor] (f : A ≃* B) : A ≃ B := equiv.mk f _ definition to_pinv [constructor] (f : A ≃* B) : B →* A := pmap.mk f⁻¹ (ap f⁻¹ (respect_pt f)⁻¹ ⬝ !left_inv) definition pua {A B : Type*} (f : A ≃* B) : A = B := Pointed_eq (equiv_of_pequiv f) !respect_pt definition pequiv_refl [refl] [constructor] : A ≃* A := pequiv.mk !pid !is_equiv_id definition pequiv_symm [symm] (f : A ≃* B) : B ≃* A := pequiv.mk (to_pinv f) !is_equiv_inv definition pequiv_trans [trans] (f : A ≃* B) (g : B ≃*C) : A ≃* C := pequiv.mk (pcompose g f) !is_equiv_compose end pointed
928c5f1aab73bea2053e52a04d42c4ad14f17680
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/order/filter/basic.lean
80ac4cf02762096172ada29a50d610828ab150d3
[ "Apache-2.0" ]
permissive
hjvromen/lewis
40b035973df7c77ebf927afab7878c76d05ff758
105b675f73630f028ad5d890897a51b3c1146fb0
refs/heads/master
1,677,944,636,343
1,676,555,301,000
1,676,555,301,000
327,553,599
0
0
null
null
null
null
UTF-8
Lean
false
false
102,832
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jeremy Avigad -/ import order.zorn import order.copy import data.set.finite import tactic.monotonicity /-! # Theory of filters on sets ## Main definitions * `filter` : filters on a set; * `at_top`, `at_bot`, `cofinite`, `principal` : specific filters; * `map`, `comap`, `prod` : operations on filters; * `tendsto` : limit with respect to filters; * `eventually` : `f.eventually p` means `{x | p x} ∈ f`; * `frequently` : `f.frequently p` means `{x | ¬p x} ∉ f`; * `filter_upwards [h₁, ..., hₙ]` : takes a list of proofs `hᵢ : sᵢ ∈ f`, and replaces a goal `s ∈ f` with `∀ x, x ∈ s₁ → ... → x ∈ sₙ → x ∈ s`; * `ne_bot f` : an utility class stating that `f` is a non-trivial filter. Filters on a type `X` are sets of sets of `X` satisfying three conditions. They are mostly used to abstract two related kinds of ideas: * *limits*, including finite or infinite limits of sequences, finite or infinite limits of functions at a point or at infinity, etc... * *things happening eventually*, including things happening for large enough `n : ℕ`, or near enough a point `x`, or for close enough pairs of points, or things happening almost everywhere in the sense of measure theory. Dually, filters can also express the idea of *things happening often*: for arbitrarily large `n`, or at a point in any neighborhood of given a point etc... In this file, we define the type `filter X` of filters on `X`, and endow it with a complete lattice structure. This structure is lifted from the lattice structure on `set (set X)` using the Galois insertion which maps a filter to its elements in one direction, and an arbitrary set of sets to the smallest filter containing it in the other direction. We also prove `filter` is a monadic functor, with a push-forward operation `filter.map` and a pull-back operation `filter.comap` that form a Galois connections for the order on filters. Finally we describe a product operation `filter X → filter Y → filter (X × Y)`. The examples of filters appearing in the description of the two motivating ideas are: * `(at_top : filter ℕ)` : made of sets of `ℕ` containing `{n | n ≥ N}` for some `N` * `𝓝 x` : made of neighborhoods of `x` in a topological space (defined in topology.basic) * `𝓤 X` : made of entourages of a uniform space (those space are generalizations of metric spaces defined in topology.uniform_space.basic) * `μ.ae` : made of sets whose complement has zero measure with respect to `μ` (defined in `measure_theory.measure_space`) The general notion of limit of a map with respect to filters on the source and target types is `filter.tendsto`. It is defined in terms of the order and the push-forward operation. The predicate "happening eventually" is `filter.eventually`, and "happening often" is `filter.frequently`, whose definitions are immediate after `filter` is defined (but they come rather late in this file in order to immediately relate them to the lattice structure). For instance, anticipating on topology.basic, the statement: "if a sequence `u` converges to some `x` and `u n` belongs to a set `M` for `n` large enough then `x` is in the closure of `M`" is formalized as: `tendsto u at_top (𝓝 x) → (∀ᶠ n in at_top, u n ∈ M) → x ∈ closure M`, which is a special case of `mem_closure_of_tendsto` from topology.basic. ## Notations * `∀ᶠ x in f, p x` : `f.eventually p`; * `∃ᶠ x in f, p x` : `f.frequently p`; * `f =ᶠ[l] g` : `∀ᶠ x in l, f x = g x`; * `f ≤ᶠ[l] g` : `∀ᶠ x in l, f x ≤ g x`; * `f ×ᶠ g` : `filter.prod f g`, localized in `filter`; * `𝓟 s` : `principal s`, localized in `filter`. ## References * [N. Bourbaki, *General Topology*][bourbaki1966] Important note: Bourbaki requires that a filter on `X` cannot contain all sets of `X`, which we do *not* require. This gives `filter X` better formal properties, in particular a bottom element `⊥` for its lattice structure, at the cost of including the assumption `[ne_bot f]` in a number of lemmas and definitions. -/ open set universes u v w x y open_locale classical /-- A filter `F` on a type `α` is a collection of sets of `α` which contains the whole `α`, is upwards-closed, and is stable under intersection. We do not forbid this collection to be all sets of `α`. -/ structure filter (α : Type*) := (sets : set (set α)) (univ_sets : set.univ ∈ sets) (sets_of_superset {x y} : x ∈ sets → x ⊆ y → y ∈ sets) (inter_sets {x y} : x ∈ sets → y ∈ sets → x ∩ y ∈ sets) /-- If `F` is a filter on `α`, and `U` a subset of `α` then we can write `U ∈ F` as on paper. -/ instance {α : Type*}: has_mem (set α) (filter α) := ⟨λ U F, U ∈ F.sets⟩ namespace filter variables {α : Type u} {f g : filter α} {s t : set α} @[simp] protected lemma mem_mk {t : set (set α)} {h₁ h₂ h₃} : s ∈ mk t h₁ h₂ h₃ ↔ s ∈ t := iff.rfl @[simp] protected lemma mem_sets : s ∈ f.sets ↔ s ∈ f := iff.rfl instance inhabited_mem : inhabited {s : set α // s ∈ f} := ⟨⟨univ, f.univ_sets⟩⟩ lemma filter_eq : ∀{f g : filter α}, f.sets = g.sets → f = g | ⟨a, _, _, _⟩ ⟨._, _, _, _⟩ rfl := rfl lemma filter_eq_iff : f = g ↔ f.sets = g.sets := ⟨congr_arg _, filter_eq⟩ protected lemma ext_iff : f = g ↔ ∀ s, s ∈ f ↔ s ∈ g := by simp only [filter_eq_iff, ext_iff, filter.mem_sets] @[ext] protected lemma ext : (∀ s, s ∈ f ↔ s ∈ g) → f = g := filter.ext_iff.2 @[simp] lemma univ_mem_sets : univ ∈ f := f.univ_sets lemma mem_sets_of_superset : ∀{x y : set α}, x ∈ f → x ⊆ y → y ∈ f := f.sets_of_superset lemma inter_mem_sets : ∀{s t}, s ∈ f → t ∈ f → s ∩ t ∈ f := f.inter_sets @[simp] lemma inter_mem_sets_iff {s t} : s ∩ t ∈ f ↔ s ∈ f ∧ t ∈ f := ⟨λ h, ⟨mem_sets_of_superset h (inter_subset_left s t), mem_sets_of_superset h (inter_subset_right s t)⟩, and_imp.2 inter_mem_sets⟩ lemma univ_mem_sets' (h : ∀ a, a ∈ s) : s ∈ f := mem_sets_of_superset univ_mem_sets (assume x _, h x) lemma mp_sets (hs : s ∈ f) (h : {x | x ∈ s → x ∈ t} ∈ f) : t ∈ f := mem_sets_of_superset (inter_mem_sets hs h) $ assume x ⟨h₁, h₂⟩, h₂ h₁ lemma congr_sets (h : {x | x ∈ s ↔ x ∈ t} ∈ f) : s ∈ f ↔ t ∈ f := ⟨λ hs, mp_sets hs (mem_sets_of_superset h (λ x, iff.mp)), λ hs, mp_sets hs (mem_sets_of_superset h (λ x, iff.mpr))⟩ @[simp] lemma bInter_mem_sets {β : Type v} {s : β → set α} {is : set β} (hf : finite is) : (⋂ i ∈ is, s i) ∈ f ↔ ∀ i ∈ is, s i ∈ f := finite.induction_on hf (by simp) (λ i s hi _ hs, by simp [hs]) @[simp] lemma bInter_finset_mem_sets {β : Type v} {s : β → set α} (is : finset β) : (⋂ i ∈ is, s i) ∈ f ↔ ∀ i ∈ is, s i ∈ f := bInter_mem_sets is.finite_to_set alias bInter_finset_mem_sets ← finset.Inter_mem_sets attribute [protected] finset.Inter_mem_sets @[simp] lemma sInter_mem_sets {s : set (set α)} (hfin : finite s) : ⋂₀ s ∈ f ↔ ∀ U ∈ s, U ∈ f := by rw [sInter_eq_bInter, bInter_mem_sets hfin] @[simp] lemma Inter_mem_sets {β : Type v} {s : β → set α} [fintype β] : (⋂ i, s i) ∈ f ↔ ∀ i, s i ∈ f := by simpa using bInter_mem_sets finite_univ lemma exists_sets_subset_iff : (∃t ∈ f, t ⊆ s) ↔ s ∈ f := ⟨assume ⟨t, ht, ts⟩, mem_sets_of_superset ht ts, assume hs, ⟨s, hs, subset.refl _⟩⟩ lemma monotone_mem_sets {f : filter α} : monotone (λs, s ∈ f) := assume s t hst h, mem_sets_of_superset h hst end filter namespace tactic.interactive open tactic interactive /-- `filter_upwards [h1, ⋯, hn]` replaces a goal of the form `s ∈ f` and terms `h1 : t1 ∈ f, ⋯, hn : tn ∈ f` with `∀x, x ∈ t1 → ⋯ → x ∈ tn → x ∈ s`. `filter_upwards [h1, ⋯, hn] e` is a short form for `{ filter_upwards [h1, ⋯, hn], exact e }`. -/ meta def filter_upwards (s : parse types.pexpr_list) (e' : parse $ optional types.texpr) : tactic unit := do s.reverse.mmap (λ e, eapplyc `filter.mp_sets >> eapply e), eapplyc `filter.univ_mem_sets', `[dsimp only [set.mem_set_of_eq]], match e' with | some e := interactive.exact e | none := skip end add_tactic_doc { name := "filter_upwards", category := doc_category.tactic, decl_names := [`tactic.interactive.filter_upwards], tags := ["goal management", "lemma application"] } end tactic.interactive namespace filter variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} section principal /-- The principal filter of `s` is the collection of all supersets of `s`. -/ def principal (s : set α) : filter α := { sets := {t | s ⊆ t}, univ_sets := subset_univ s, sets_of_superset := assume x y hx hy, subset.trans hx hy, inter_sets := assume x y, subset_inter } localized "notation `𝓟` := filter.principal" in filter instance : inhabited (filter α) := ⟨𝓟 ∅⟩ @[simp] lemma mem_principal_sets {s t : set α} : s ∈ 𝓟 t ↔ t ⊆ s := iff.rfl lemma mem_principal_self (s : set α) : s ∈ 𝓟 s := subset.refl _ end principal open_locale filter section join /-- The join of a filter of filters is defined by the relation `s ∈ join f ↔ {t | s ∈ t} ∈ f`. -/ def join (f : filter (filter α)) : filter α := { sets := {s | {t : filter α | s ∈ t} ∈ f}, univ_sets := by simp only [mem_set_of_eq, univ_sets, ← filter.mem_sets, set_of_true], sets_of_superset := assume x y hx xy, mem_sets_of_superset hx $ assume f h, mem_sets_of_superset h xy, inter_sets := assume x y hx hy, mem_sets_of_superset (inter_mem_sets hx hy) $ assume f ⟨h₁, h₂⟩, inter_mem_sets h₁ h₂ } @[simp] lemma mem_join_sets {s : set α} {f : filter (filter α)} : s ∈ join f ↔ {t | s ∈ t} ∈ f := iff.rfl end join section lattice instance : partial_order (filter α) := { le := λf g, ∀ ⦃U : set α⦄, U ∈ g → U ∈ f, le_antisymm := assume a b h₁ h₂, filter_eq $ subset.antisymm h₂ h₁, le_refl := assume a, subset.refl _, le_trans := assume a b c h₁ h₂, subset.trans h₂ h₁ } theorem le_def {f g : filter α} : f ≤ g ↔ ∀ x ∈ g, x ∈ f := iff.rfl /-- `generate_sets g s`: `s` is in the filter closure of `g`. -/ inductive generate_sets (g : set (set α)) : set α → Prop | basic {s : set α} : s ∈ g → generate_sets s | univ : generate_sets univ | superset {s t : set α} : generate_sets s → s ⊆ t → generate_sets t | inter {s t : set α} : generate_sets s → generate_sets t → generate_sets (s ∩ t) /-- `generate g` is the smallest filter containing the sets `g`. -/ def generate (g : set (set α)) : filter α := { sets := generate_sets g, univ_sets := generate_sets.univ, sets_of_superset := assume x y, generate_sets.superset, inter_sets := assume s t, generate_sets.inter } lemma sets_iff_generate {s : set (set α)} {f : filter α} : f ≤ filter.generate s ↔ s ⊆ f.sets := iff.intro (assume h u hu, h $ generate_sets.basic $ hu) (assume h u hu, hu.rec_on h univ_mem_sets (assume x y _ hxy hx, mem_sets_of_superset hx hxy) (assume x y _ _ hx hy, inter_mem_sets hx hy)) lemma mem_generate_iff {s : set $ set α} {U : set α} : U ∈ generate s ↔ ∃ t ⊆ s, finite t ∧ ⋂₀ t ⊆ U := begin split ; intro h, { induction h with V V_in V W V_in hVW hV V W V_in W_in hV hW, { use {V}, simp [V_in] }, { use ∅, simp [subset.refl, univ] }, { rcases hV with ⟨t, hts, htfin, hinter⟩, exact ⟨t, hts, htfin, subset.trans hinter hVW⟩ }, { rcases hV with ⟨t, hts, htfin, htinter⟩, rcases hW with ⟨z, hzs, hzfin, hzinter⟩, refine ⟨t ∪ z, union_subset hts hzs, htfin.union hzfin, _⟩, rw sInter_union, exact inter_subset_inter htinter hzinter } }, { rcases h with ⟨t, ts, tfin, h⟩, apply generate_sets.superset _ h, revert ts, apply finite.induction_on tfin, { intro h, rw sInter_empty, exact generate_sets.univ }, { intros V r hV rfin hinter h, cases insert_subset.mp h with V_in r_sub, rw [insert_eq V r, sInter_union], apply generate_sets.inter _ (hinter r_sub), rw sInter_singleton, exact generate_sets.basic V_in } }, end /-- `mk_of_closure s hs` constructs a filter on `α` whose elements set is exactly `s : set (set α)`, provided one gives the assumption `hs : (generate s).sets = s`. -/ protected def mk_of_closure (s : set (set α)) (hs : (generate s).sets = s) : filter α := { sets := s, univ_sets := hs ▸ (univ_mem_sets : univ ∈ generate s), sets_of_superset := λ x y, hs ▸ (mem_sets_of_superset : x ∈ generate s → x ⊆ y → y ∈ generate s), inter_sets := λ x y, hs ▸ (inter_mem_sets : x ∈ generate s → y ∈ generate s → x ∩ y ∈ generate s) } lemma mk_of_closure_sets {s : set (set α)} {hs : (generate s).sets = s} : filter.mk_of_closure s hs = generate s := filter.ext $ assume u, show u ∈ (filter.mk_of_closure s hs).sets ↔ u ∈ (generate s).sets, from hs.symm ▸ iff.rfl /-- Galois insertion from sets of sets into filters. -/ def gi_generate (α : Type*) : @galois_insertion (set (set α)) (order_dual (filter α)) _ _ filter.generate filter.sets := { gc := assume s f, sets_iff_generate, le_l_u := assume f u h, generate_sets.basic h, choice := λs hs, filter.mk_of_closure s (le_antisymm hs $ sets_iff_generate.1 $ le_refl _), choice_eq := assume s hs, mk_of_closure_sets } /-- The infimum of filters is the filter generated by intersections of elements of the two filters. -/ instance : has_inf (filter α) := ⟨λf g : filter α, { sets := {s | ∃ (a ∈ f) (b ∈ g), a ∩ b ⊆ s }, univ_sets := ⟨_, univ_mem_sets, _, univ_mem_sets, inter_subset_left _ _⟩, sets_of_superset := assume x y ⟨a, ha, b, hb, h⟩ xy, ⟨a, ha, b, hb, subset.trans h xy⟩, inter_sets := assume x y ⟨a, ha, b, hb, hx⟩ ⟨c, hc, d, hd, hy⟩, ⟨_, inter_mem_sets ha hc, _, inter_mem_sets hb hd, calc a ∩ c ∩ (b ∩ d) = (a ∩ b) ∩ (c ∩ d) : by ac_refl ... ⊆ x ∩ y : inter_subset_inter hx hy⟩ }⟩ @[simp] lemma mem_inf_sets {f g : filter α} {s : set α} : s ∈ f ⊓ g ↔ ∃t₁∈f, ∃t₂∈g, t₁ ∩ t₂ ⊆ s := iff.rfl lemma mem_inf_sets_of_left {f g : filter α} {s : set α} (h : s ∈ f) : s ∈ f ⊓ g := ⟨s, h, univ, univ_mem_sets, inter_subset_left _ _⟩ lemma mem_inf_sets_of_right {f g : filter α} {s : set α} (h : s ∈ g) : s ∈ f ⊓ g := ⟨univ, univ_mem_sets, s, h, inter_subset_right _ _⟩ lemma inter_mem_inf_sets {α : Type u} {f g : filter α} {s t : set α} (hs : s ∈ f) (ht : t ∈ g) : s ∩ t ∈ f ⊓ g := inter_mem_sets (mem_inf_sets_of_left hs) (mem_inf_sets_of_right ht) instance : has_top (filter α) := ⟨{ sets := {s | ∀x, x ∈ s}, univ_sets := assume x, mem_univ x, sets_of_superset := assume x y hx hxy a, hxy (hx a), inter_sets := assume x y hx hy a, mem_inter (hx _) (hy _) }⟩ lemma mem_top_sets_iff_forall {s : set α} : s ∈ (⊤ : filter α) ↔ (∀x, x ∈ s) := iff.rfl @[simp] lemma mem_top_sets {s : set α} : s ∈ (⊤ : filter α) ↔ s = univ := by rw [mem_top_sets_iff_forall, eq_univ_iff_forall] section complete_lattice /- We lift the complete lattice along the Galois connection `generate` / `sets`. Unfortunately, we want to have different definitional equalities for the lattice operations. So we define them upfront and change the lattice operations for the complete lattice instance. -/ private def original_complete_lattice : complete_lattice (filter α) := @order_dual.complete_lattice _ (gi_generate α).lift_complete_lattice local attribute [instance] original_complete_lattice instance : complete_lattice (filter α) := original_complete_lattice.copy /- le -/ filter.partial_order.le rfl /- top -/ (filter.has_top).1 (top_unique $ assume s hs, by simp [mem_top_sets.1 hs]) /- bot -/ _ rfl /- sup -/ _ rfl /- inf -/ (filter.has_inf).1 begin ext f g : 2, exact le_antisymm (le_inf (assume s, mem_inf_sets_of_left) (assume s, mem_inf_sets_of_right)) (assume s ⟨a, ha, b, hb, hs⟩, show s ∈ complete_lattice.inf f g, from mem_sets_of_superset (inter_mem_sets (@inf_le_left (filter α) _ _ _ _ ha) (@inf_le_right (filter α) _ _ _ _ hb)) hs) end /- Sup -/ (join ∘ 𝓟) (by ext s x; exact (@mem_bInter_iff _ _ s filter.sets x).symm) /- Inf -/ _ rfl end complete_lattice /-- A filter is `ne_bot` if it is not equal to `⊥`, or equivalently the empty set does not belong to the filter. Bourbaki include this assumption in the definition of a filter but we prefer to have a `complete_lattice` structure on filter, so we use a typeclass argument in lemmas instead. -/ @[class] def ne_bot (f : filter α) := f ≠ ⊥ lemma ne_bot.ne {f : filter α} (hf : ne_bot f) : f ≠ ⊥ := hf @[simp] lemma not_ne_bot {α : Type*} {f : filter α} : ¬ f.ne_bot ↔ f = ⊥ := not_not lemma ne_bot.mono {f g : filter α} (hf : ne_bot f) (hg : f ≤ g) : ne_bot g := ne_bot_of_le_ne_bot hf hg lemma ne_bot_of_le {f g : filter α} [hf : ne_bot f] (hg : f ≤ g) : ne_bot g := hf.mono hg lemma bot_sets_eq : (⊥ : filter α).sets = univ := rfl lemma sup_sets_eq {f g : filter α} : (f ⊔ g).sets = f.sets ∩ g.sets := (gi_generate α).gc.u_inf lemma Sup_sets_eq {s : set (filter α)} : (Sup s).sets = (⋂f∈s, (f:filter α).sets) := (gi_generate α).gc.u_Inf lemma supr_sets_eq {f : ι → filter α} : (supr f).sets = (⋂i, (f i).sets) := (gi_generate α).gc.u_infi lemma generate_empty : filter.generate ∅ = (⊤ : filter α) := (gi_generate α).gc.l_bot lemma generate_univ : filter.generate univ = (⊥ : filter α) := mk_of_closure_sets.symm lemma generate_union {s t : set (set α)} : filter.generate (s ∪ t) = filter.generate s ⊓ filter.generate t := (gi_generate α).gc.l_sup lemma generate_Union {s : ι → set (set α)} : filter.generate (⋃ i, s i) = (⨅ i, filter.generate (s i)) := (gi_generate α).gc.l_supr @[simp] lemma mem_bot_sets {s : set α} : s ∈ (⊥ : filter α) := trivial @[simp] lemma mem_sup_sets {f g : filter α} {s : set α} : s ∈ f ⊔ g ↔ s ∈ f ∧ s ∈ g := iff.rfl lemma union_mem_sup {f g : filter α} {s t : set α} (hs : s ∈ f) (ht : t ∈ g) : s ∪ t ∈ f ⊔ g := ⟨mem_sets_of_superset hs (subset_union_left s t), mem_sets_of_superset ht (subset_union_right s t)⟩ @[simp] lemma mem_Sup_sets {x : set α} {s : set (filter α)} : x ∈ Sup s ↔ (∀f∈s, x ∈ (f:filter α)) := iff.rfl @[simp] lemma mem_supr_sets {x : set α} {f : ι → filter α} : x ∈ supr f ↔ (∀i, x ∈ f i) := by simp only [← filter.mem_sets, supr_sets_eq, iff_self, mem_Inter] lemma infi_eq_generate (s : ι → filter α) : infi s = generate (⋃ i, (s i).sets) := show generate _ = generate _, from congr_arg _ supr_range lemma mem_infi_iff {ι} {s : ι → filter α} {U : set α} : (U ∈ ⨅ i, s i) ↔ ∃ I : set ι, finite I ∧ ∃ V : {i | i ∈ I} → set α, (∀ i, V i ∈ s i) ∧ (⋂ i, V i) ⊆ U := begin rw [infi_eq_generate, mem_generate_iff], split, { rintro ⟨t, tsub, tfin, tinter⟩, rcases eq_finite_Union_of_finite_subset_Union tfin tsub with ⟨I, Ifin, σ, σfin, σsub, rfl⟩, rw sInter_Union at tinter, let V := λ i, ⋂₀ σ i, have V_in : ∀ i, V i ∈ s i, { rintro ⟨i, i_in⟩, rw sInter_mem_sets (σfin _), apply σsub }, exact ⟨I, Ifin, V, V_in, tinter⟩ }, { rintro ⟨I, Ifin, V, V_in, h⟩, refine ⟨range V, _, _, h⟩, { rintro _ ⟨i, rfl⟩, rw mem_Union, use [i, V_in i] }, { haveI : fintype {i : ι | i ∈ I} := finite.fintype Ifin, exact finite_range _ } }, end @[simp] lemma le_principal_iff {s : set α} {f : filter α} : f ≤ 𝓟 s ↔ s ∈ f := show (∀{t}, s ⊆ t → t ∈ f) ↔ s ∈ f, from ⟨assume h, h (subset.refl s), assume hs t ht, mem_sets_of_superset hs ht⟩ lemma principal_mono {s t : set α} : 𝓟 s ≤ 𝓟 t ↔ s ⊆ t := by simp only [le_principal_iff, iff_self, mem_principal_sets] @[mono] lemma monotone_principal : monotone (𝓟 : set α → filter α) := λ _ _, principal_mono.2 @[simp] lemma principal_eq_iff_eq {s t : set α} : 𝓟 s = 𝓟 t ↔ s = t := by simp only [le_antisymm_iff, le_principal_iff, mem_principal_sets]; refl @[simp] lemma join_principal_eq_Sup {s : set (filter α)} : join (𝓟 s) = Sup s := rfl @[simp] lemma principal_univ : 𝓟 (univ : set α) = ⊤ := top_unique $ by simp only [le_principal_iff, mem_top_sets, eq_self_iff_true] @[simp] lemma principal_empty : 𝓟 (∅ : set α) = ⊥ := bot_unique $ assume s _, empty_subset _ /-! ### Lattice equations -/ lemma empty_in_sets_eq_bot {f : filter α} : ∅ ∈ f ↔ f = ⊥ := ⟨assume h, bot_unique $ assume s _, mem_sets_of_superset h (empty_subset s), assume : f = ⊥, this.symm ▸ mem_bot_sets⟩ lemma nonempty_of_mem_sets {f : filter α} [hf : ne_bot f] {s : set α} (hs : s ∈ f) : s.nonempty := s.eq_empty_or_nonempty.elim (λ h, absurd hs (h.symm ▸ mt empty_in_sets_eq_bot.mp hf)) id lemma ne_bot.nonempty_of_mem {f : filter α} (hf : ne_bot f) {s : set α} (hs : s ∈ f) : s.nonempty := @nonempty_of_mem_sets α f hf s hs @[simp] lemma empty_nmem_sets (f : filter α) [ne_bot f] : ¬(∅ ∈ f) := λ h, (nonempty_of_mem_sets h).ne_empty rfl lemma nonempty_of_ne_bot (f : filter α) [ne_bot f] : nonempty α := nonempty_of_exists $ nonempty_of_mem_sets (univ_mem_sets : univ ∈ f) lemma compl_not_mem_sets {f : filter α} {s : set α} [ne_bot f] (h : s ∈ f) : sᶜ ∉ f := λ hsc, (nonempty_of_mem_sets (inter_mem_sets h hsc)).ne_empty $ inter_compl_self s lemma filter_eq_bot_of_not_nonempty (f : filter α) (ne : ¬ nonempty α) : f = ⊥ := empty_in_sets_eq_bot.mp $ univ_mem_sets' $ assume x, false.elim (ne ⟨x⟩) lemma forall_sets_nonempty_iff_ne_bot {f : filter α} : (∀ (s : set α), s ∈ f → s.nonempty) ↔ ne_bot f := ⟨λ h hf, empty_not_nonempty (h ∅ $ hf.symm ▸ mem_bot_sets), @nonempty_of_mem_sets _ _⟩ lemma nontrivial_iff_nonempty : nontrivial (filter α) ↔ nonempty α := ⟨λ ⟨⟨f, g, hfg⟩⟩, by_contra $ λ h, hfg $ (filter_eq_bot_of_not_nonempty f h).trans (filter_eq_bot_of_not_nonempty g h).symm, λ ⟨x⟩, ⟨⟨⊤, ⊥, forall_sets_nonempty_iff_ne_bot.1 $ λ s hs, by rwa [mem_top_sets.1 hs, ← nonempty_iff_univ_nonempty]⟩⟩⟩ lemma mem_sets_of_eq_bot {f : filter α} {s : set α} (h : f ⊓ 𝓟 sᶜ = ⊥) : s ∈ f := have ∅ ∈ f ⊓ 𝓟 sᶜ, from h.symm ▸ mem_bot_sets, let ⟨s₁, hs₁, s₂, (hs₂ : sᶜ ⊆ s₂), (hs : s₁ ∩ s₂ ⊆ ∅)⟩ := this in by filter_upwards [hs₁] assume a ha, classical.by_contradiction $ assume ha', hs ⟨ha, hs₂ ha'⟩ lemma eq_Inf_of_mem_sets_iff_exists_mem {S : set (filter α)} {l : filter α} (h : ∀ {s}, s ∈ l ↔ ∃ f ∈ S, s ∈ f) : l = Inf S := le_antisymm (le_Inf $ λ f hf s hs, h.2 ⟨f, hf, hs⟩) (λ s hs, let ⟨f, hf, hs⟩ := h.1 hs in (Inf_le hf : Inf S ≤ f) hs) lemma eq_infi_of_mem_sets_iff_exists_mem {f : ι → filter α} {l : filter α} (h : ∀ {s}, s ∈ l ↔ ∃ i, s ∈ f i) : l = infi f := eq_Inf_of_mem_sets_iff_exists_mem $ λ s, h.trans exists_range_iff.symm lemma eq_binfi_of_mem_sets_iff_exists_mem {f : ι → filter α} {p : ι → Prop} {l : filter α} (h : ∀ {s}, s ∈ l ↔ ∃ i (_ : p i), s ∈ f i) : l = ⨅ i (_ : p i), f i := begin rw [infi_subtype'], apply eq_infi_of_mem_sets_iff_exists_mem, intro s, exact h.trans ⟨λ ⟨i, pi, si⟩, ⟨⟨i, pi⟩, si⟩, λ ⟨⟨i, pi⟩, si⟩, ⟨i, pi, si⟩⟩ end lemma infi_sets_eq {f : ι → filter α} (h : directed (≥) f) [ne : nonempty ι] : (infi f).sets = (⋃ i, (f i).sets) := let ⟨i⟩ := ne, u := { filter . sets := (⋃ i, (f i).sets), univ_sets := by simp only [mem_Union]; exact ⟨i, univ_mem_sets⟩, sets_of_superset := by simp only [mem_Union, exists_imp_distrib]; intros x y i hx hxy; exact ⟨i, mem_sets_of_superset hx hxy⟩, inter_sets := begin simp only [mem_Union, exists_imp_distrib], assume x y a hx b hy, rcases h a b with ⟨c, ha, hb⟩, exact ⟨c, inter_mem_sets (ha hx) (hb hy)⟩ end } in have u = infi f, from eq_infi_of_mem_sets_iff_exists_mem (λ s, by simp only [filter.mem_mk, mem_Union, filter.mem_sets]), congr_arg filter.sets this.symm lemma mem_infi {f : ι → filter α} (h : directed (≥) f) [nonempty ι] (s) : s ∈ infi f ↔ ∃ i, s ∈ f i := by simp only [← filter.mem_sets, infi_sets_eq h, mem_Union] lemma mem_binfi {f : β → filter α} {s : set β} (h : directed_on (f ⁻¹'o (≥)) s) (ne : s.nonempty) {t : set α} : t ∈ (⨅ i∈s, f i) ↔ ∃ i ∈ s, t ∈ f i := by haveI : nonempty {x // x ∈ s} := ne.to_subtype; erw [infi_subtype', mem_infi h.directed_coe, subtype.exists]; refl lemma binfi_sets_eq {f : β → filter α} {s : set β} (h : directed_on (f ⁻¹'o (≥)) s) (ne : s.nonempty) : (⨅ i∈s, f i).sets = (⋃ i ∈ s, (f i).sets) := ext $ λ t, by simp [mem_binfi h ne] lemma infi_sets_eq_finite {ι : Type*} (f : ι → filter α) : (⨅i, f i).sets = (⋃t:finset ι, (⨅i∈t, f i).sets) := begin rw [infi_eq_infi_finset, infi_sets_eq], exact (directed_of_sup $ λs₁ s₂ hs, infi_le_infi $ λi, infi_le_infi_const $ λh, hs h), end lemma infi_sets_eq_finite' (f : ι → filter α) : (⨅i, f i).sets = (⋃t:finset (plift ι), (⨅i∈t, f (plift.down i)).sets) := by rw [← infi_sets_eq_finite, ← equiv.plift.surjective.infi_comp]; refl lemma mem_infi_finite {ι : Type*} {f : ι → filter α} (s) : s ∈ infi f ↔ ∃ t:finset ι, s ∈ ⨅i∈t, f i := (set.ext_iff.1 (infi_sets_eq_finite f) s).trans mem_Union lemma mem_infi_finite' {f : ι → filter α} (s) : s ∈ infi f ↔ ∃ t:finset (plift ι), s ∈ ⨅i∈t, f (plift.down i) := (set.ext_iff.1 (infi_sets_eq_finite' f) s).trans mem_Union @[simp] lemma sup_join {f₁ f₂ : filter (filter α)} : (join f₁ ⊔ join f₂) = join (f₁ ⊔ f₂) := filter.ext $ λ x, by simp only [mem_sup_sets, mem_join_sets] @[simp] lemma supr_join {ι : Sort w} {f : ι → filter (filter α)} : (⨆x, join (f x)) = join (⨆x, f x) := filter.ext $ assume x, by simp only [mem_supr_sets, mem_join_sets] instance : bounded_distrib_lattice (filter α) := { le_sup_inf := begin assume x y z s, simp only [and_assoc, mem_inf_sets, mem_sup_sets, exists_prop, exists_imp_distrib, and_imp], intros hs t₁ ht₁ t₂ ht₂ hts, exact ⟨s ∪ t₁, x.sets_of_superset hs $ subset_union_left _ _, y.sets_of_superset ht₁ $ subset_union_right _ _, s ∪ t₂, x.sets_of_superset hs $ subset_union_left _ _, z.sets_of_superset ht₂ $ subset_union_right _ _, subset.trans (@le_sup_inf (set α) _ _ _ _) (union_subset (subset.refl _) hts)⟩ end, ..filter.complete_lattice } /- the complementary version with ⨆i, f ⊓ g i does not hold! -/ lemma infi_sup_left {f : filter α} {g : ι → filter α} : (⨅ x, f ⊔ g x) = f ⊔ infi g := begin refine le_antisymm _ (le_infi $ assume i, sup_le_sup_left (infi_le _ _) _), rintros t ⟨h₁, h₂⟩, rw [infi_sets_eq_finite'] at h₂, simp only [mem_Union, (finset.inf_eq_infi _ _).symm] at h₂, rcases h₂ with ⟨s, hs⟩, suffices : (⨅i, f ⊔ g i) ≤ f ⊔ s.inf (λi, g i.down), { exact this ⟨h₁, hs⟩ }, refine finset.induction_on s _ _, { exact le_sup_right_of_le le_top }, { rintros ⟨i⟩ s his ih, rw [finset.inf_insert, sup_inf_left], exact le_inf (infi_le _ _) ih } end lemma infi_sup_right {f : filter α} {g : ι → filter α} : (⨅ x, g x ⊔ f) = infi g ⊔ f := by simp [sup_comm, ← infi_sup_left] lemma binfi_sup_right (p : ι → Prop) (f : ι → filter α) (g : filter α) : (⨅ i (h : p i), (f i ⊔ g)) = (⨅ i (h : p i), f i) ⊔ g := by rw [infi_subtype', infi_sup_right, infi_subtype'] lemma binfi_sup_left (p : ι → Prop) (f : ι → filter α) (g : filter α) : (⨅ i (h : p i), (g ⊔ f i)) = g ⊔ (⨅ i (h : p i), f i) := by rw [infi_subtype', infi_sup_left, infi_subtype'] lemma mem_infi_sets_finset {s : finset α} {f : α → filter β} : ∀t, t ∈ (⨅a∈s, f a) ↔ (∃p:α → set β, (∀a∈s, p a ∈ f a) ∧ (⋂a∈s, p a) ⊆ t) := show ∀t, t ∈ (⨅a∈s, f a) ↔ (∃p:α → set β, (∀a∈s, p a ∈ f a) ∧ (⨅a∈s, p a) ≤ t), begin simp only [(finset.inf_eq_infi _ _).symm], refine finset.induction_on s _ _, { simp only [finset.not_mem_empty, false_implies_iff, finset.inf_empty, top_le_iff, imp_true_iff, mem_top_sets, true_and, exists_const], intros; refl }, { intros a s has ih t, simp only [ih, finset.forall_mem_insert, finset.inf_insert, mem_inf_sets, exists_prop, iff_iff_implies_and_implies, exists_imp_distrib, and_imp, and_assoc] {contextual := tt}, split, { intros t₁ ht₁ t₂ p hp ht₂ ht, existsi function.update p a t₁, have : ∀a'∈s, function.update p a t₁ a' = p a', from assume a' ha', have a' ≠ a, from assume h, has $ h ▸ ha', function.update_noteq this _ _, have eq : s.inf (λj, function.update p a t₁ j) = s.inf (λj, p j) := finset.inf_congr rfl this, simp only [this, ht₁, hp, function.update_same, true_and, imp_true_iff, eq] {contextual := tt}, exact subset.trans (inter_subset_inter (subset.refl _) ht₂) ht }, assume p hpa hp ht, exact ⟨p a, hpa, (s.inf p), ⟨⟨p, hp, le_refl _⟩, ht⟩⟩ } end /-- If `f : ι → filter α` is directed, `ι` is not empty, and `∀ i, f i ≠ ⊥`, then `infi f ≠ ⊥`. See also `infi_ne_bot_of_directed` for a version assuming `nonempty α` instead of `nonempty ι`. -/ lemma infi_ne_bot_of_directed' {f : ι → filter α} [nonempty ι] (hd : directed (≥) f) (hb : ∀i, ne_bot (f i)) : ne_bot (infi f) := begin intro h, have he: ∅ ∈ (infi f), from h.symm ▸ (mem_bot_sets : ∅ ∈ (⊥ : filter α)), obtain ⟨i, hi⟩ : ∃i, ∅ ∈ f i, from (mem_infi hd ∅).1 he, exact hb i (empty_in_sets_eq_bot.1 hi) end /-- If `f : ι → filter α` is directed, `α` is not empty, and `∀ i, f i ≠ ⊥`, then `infi f ≠ ⊥`. See also `infi_ne_bot_of_directed'` for a version assuming `nonempty ι` instead of `nonempty α`. -/ lemma infi_ne_bot_of_directed {f : ι → filter α} [hn : nonempty α] (hd : directed (≥) f) (hb : ∀i, ne_bot (f i)) : ne_bot (infi f) := if hι : nonempty ι then @infi_ne_bot_of_directed' _ _ _ hι hd hb else assume h : infi f = ⊥, have univ ⊆ (∅ : set α), begin rw [←principal_mono, principal_univ, principal_empty, ←h], exact (le_infi $ assume i, false.elim $ hι ⟨i⟩) end, let ⟨x⟩ := hn in this (mem_univ x) lemma infi_ne_bot_iff_of_directed' {f : ι → filter α} [nonempty ι] (hd : directed (≥) f) : ne_bot (infi f) ↔ ∀i, ne_bot (f i) := ⟨assume H i, H.mono (infi_le _ i), infi_ne_bot_of_directed' hd⟩ lemma infi_ne_bot_iff_of_directed {f : ι → filter α} [nonempty α] (hd : directed (≥) f) : ne_bot (infi f) ↔ (∀i, ne_bot (f i)) := ⟨assume H i, H.mono (infi_le _ i), infi_ne_bot_of_directed hd⟩ lemma mem_infi_sets {f : ι → filter α} (i : ι) : ∀{s}, s ∈ f i → s ∈ ⨅i, f i := show (⨅i, f i) ≤ f i, from infi_le _ _ @[elab_as_eliminator] lemma infi_sets_induct {f : ι → filter α} {s : set α} (hs : s ∈ infi f) {p : set α → Prop} (uni : p univ) (ins : ∀{i s₁ s₂}, s₁ ∈ f i → p s₂ → p (s₁ ∩ s₂)) (upw : ∀{s₁ s₂}, s₁ ⊆ s₂ → p s₁ → p s₂) : p s := begin rw [mem_infi_finite'] at hs, simp only [← finset.inf_eq_infi] at hs, rcases hs with ⟨is, his⟩, revert s, refine finset.induction_on is _ _, { assume s hs, rwa [mem_top_sets.1 hs] }, { rintros ⟨i⟩ js his ih s hs, rw [finset.inf_insert, mem_inf_sets] at hs, rcases hs with ⟨s₁, hs₁, s₂, hs₂, hs⟩, exact upw hs (ins hs₁ (ih hs₂)) } end /- principal equations -/ @[simp] lemma inf_principal {s t : set α} : 𝓟 s ⊓ 𝓟 t = 𝓟 (s ∩ t) := le_antisymm (by simp; exact ⟨s, subset.refl s, t, subset.refl t, by simp⟩) (by simp [le_inf_iff, inter_subset_left, inter_subset_right]) @[simp] lemma sup_principal {s t : set α} : 𝓟 s ⊔ 𝓟 t = 𝓟 (s ∪ t) := filter.ext $ λ u, by simp only [union_subset_iff, mem_sup_sets, mem_principal_sets] @[simp] lemma supr_principal {ι : Sort w} {s : ι → set α} : (⨆x, 𝓟 (s x)) = 𝓟 (⋃i, s i) := filter.ext $ assume x, by simp only [mem_supr_sets, mem_principal_sets, Union_subset_iff] @[simp] lemma principal_eq_bot_iff {s : set α} : 𝓟 s = ⊥ ↔ s = ∅ := empty_in_sets_eq_bot.symm.trans $ mem_principal_sets.trans subset_empty_iff @[simp] lemma principal_ne_bot_iff {s : set α} : ne_bot (𝓟 s) ↔ s.nonempty := (not_congr principal_eq_bot_iff).trans ne_empty_iff_nonempty lemma is_compl_principal (s : set α) : is_compl (𝓟 s) (𝓟 sᶜ) := ⟨by simp only [inf_principal, inter_compl_self, principal_empty, le_refl], by simp only [sup_principal, union_compl_self, principal_univ, le_refl]⟩ lemma inf_principal_eq_bot {f : filter α} {s : set α} (hs : sᶜ ∈ f) : f ⊓ 𝓟 s = ⊥ := empty_in_sets_eq_bot.mp ⟨_, hs, s, mem_principal_self s, assume x ⟨h₁, h₂⟩, h₁ h₂⟩ theorem mem_inf_principal {f : filter α} {s t : set α} : s ∈ f ⊓ 𝓟 t ↔ {x | x ∈ t → x ∈ s} ∈ f := begin simp only [← le_principal_iff, (is_compl_principal s).le_left_iff, disjoint, inf_assoc, inf_principal, imp_iff_not_or], rw [← disjoint, ← (is_compl_principal (t ∩ sᶜ)).le_right_iff, compl_inter, compl_compl], refl end lemma diff_mem_inf_principal_compl {f : filter α} {s : set α} (hs : s ∈ f) (t : set α) : s \ t ∈ f ⊓ 𝓟 tᶜ := begin rw mem_inf_principal, filter_upwards [hs], intros a has hat, exact ⟨has, hat⟩ end lemma principal_le_iff {s : set α} {f : filter α} : 𝓟 s ≤ f ↔ ∀ V ∈ f, s ⊆ V := begin change (∀ V, V ∈ f → V ∈ _) ↔ _, simp_rw mem_principal_sets, end @[simp] lemma infi_principal_finset {ι : Type w} (s : finset ι) (f : ι → set α) : (⨅i∈s, 𝓟 (f i)) = 𝓟 (⋂i∈s, f i) := begin ext t, simp [mem_infi_sets_finset], split, { rintros ⟨p, hp, ht⟩, calc (⋂ (i : ι) (H : i ∈ s), f i) ≤ (⋂ (i : ι) (H : i ∈ s), p i) : infi_le_infi (λi, infi_le_infi (λhi, mem_principal_sets.1 (hp i hi))) ... ≤ t : ht }, { assume h, exact ⟨f, λi hi, subset.refl _, h⟩ } end @[simp] lemma infi_principal_fintype {ι : Type w} [fintype ι] (f : ι → set α) : (⨅i, 𝓟 (f i)) = 𝓟 (⋂i, f i) := by simpa using infi_principal_finset finset.univ f end lattice @[mono] lemma join_mono {f₁ f₂ : filter (filter α)} (h : f₁ ≤ f₂) : join f₁ ≤ join f₂ := λ s hs, h hs /-! ### Eventually -/ /-- `f.eventually p` or `∀ᶠ x in f, p x` mean that `{x | p x} ∈ f`. E.g., `∀ᶠ x in at_top, p x` means that `p` holds true for sufficiently large `x`. -/ protected def eventually (p : α → Prop) (f : filter α) : Prop := {x | p x} ∈ f notation `∀ᶠ` binders ` in ` f `, ` r:(scoped p, filter.eventually p f) := r lemma eventually_iff {f : filter α} {P : α → Prop} : (∀ᶠ x in f, P x) ↔ {x | P x} ∈ f := iff.rfl protected lemma ext' {f₁ f₂ : filter α} (h : ∀ p : α → Prop, (∀ᶠ x in f₁, p x) ↔ (∀ᶠ x in f₂, p x)) : f₁ = f₂ := filter.ext h lemma eventually.filter_mono {f₁ f₂ : filter α} (h : f₁ ≤ f₂) {p : α → Prop} (hp : ∀ᶠ x in f₂, p x) : ∀ᶠ x in f₁, p x := h hp lemma eventually_of_mem {f : filter α} {P : α → Prop} {U : set α} (hU : U ∈ f) (h : ∀ x ∈ U, P x) : ∀ᶠ x in f, P x := mem_sets_of_superset hU h protected lemma eventually.and {p q : α → Prop} {f : filter α} : f.eventually p → f.eventually q → ∀ᶠ x in f, p x ∧ q x := inter_mem_sets @[simp] lemma eventually_true (f : filter α) : ∀ᶠ x in f, true := univ_mem_sets lemma eventually_of_forall {p : α → Prop} {f : filter α} (hp : ∀ x, p x) : ∀ᶠ x in f, p x := univ_mem_sets' hp @[simp] lemma eventually_false_iff_eq_bot {f : filter α} : (∀ᶠ x in f, false) ↔ f = ⊥ := empty_in_sets_eq_bot @[simp] lemma eventually_const {f : filter α} [ne_bot f] {p : Prop} : (∀ᶠ x in f, p) ↔ p := classical.by_cases (λ h : p, by simp [h]) (λ h, by simpa [h]) lemma eventually_iff_exists_mem {p : α → Prop} {f : filter α} : (∀ᶠ x in f, p x) ↔ ∃ v ∈ f, ∀ y ∈ v, p y := exists_sets_subset_iff.symm lemma eventually.exists_mem {p : α → Prop} {f : filter α} (hp : ∀ᶠ x in f, p x) : ∃ v ∈ f, ∀ y ∈ v, p y := eventually_iff_exists_mem.1 hp lemma eventually.mp {p q : α → Prop} {f : filter α} (hp : ∀ᶠ x in f, p x) (hq : ∀ᶠ x in f, p x → q x) : ∀ᶠ x in f, q x := mp_sets hp hq lemma eventually.mono {p q : α → Prop} {f : filter α} (hp : ∀ᶠ x in f, p x) (hq : ∀ x, p x → q x) : ∀ᶠ x in f, q x := hp.mp (eventually_of_forall hq) @[simp] lemma eventually_and {p q : α → Prop} {f : filter α} : (∀ᶠ x in f, p x ∧ q x) ↔ (∀ᶠ x in f, p x) ∧ (∀ᶠ x in f, q x) := inter_mem_sets_iff lemma eventually.congr {f : filter α} {p q : α → Prop} (h' : ∀ᶠ x in f, p x) (h : ∀ᶠ x in f, p x ↔ q x) : ∀ᶠ x in f, q x := h'.mp (h.mono $ λ x hx, hx.mp) lemma eventually_congr {f : filter α} {p q : α → Prop} (h : ∀ᶠ x in f, p x ↔ q x) : (∀ᶠ x in f, p x) ↔ (∀ᶠ x in f, q x) := ⟨λ hp, hp.congr h, λ hq, hq.congr $ by simpa only [iff.comm] using h⟩ @[simp] lemma eventually_all {ι} [fintype ι] {l} {p : ι → α → Prop} : (∀ᶠ x in l, ∀ i, p i x) ↔ ∀ i, ∀ᶠ x in l, p i x := by simpa only [filter.eventually, set_of_forall] using Inter_mem_sets @[simp] lemma eventually_all_finite {ι} {I : set ι} (hI : I.finite) {l} {p : ι → α → Prop} : (∀ᶠ x in l, ∀ i ∈ I, p i x) ↔ (∀ i ∈ I, ∀ᶠ x in l, p i x) := by simpa only [filter.eventually, set_of_forall] using bInter_mem_sets hI alias eventually_all_finite ← set.finite.eventually_all attribute [protected] set.finite.eventually_all @[simp] lemma eventually_all_finset {ι} (I : finset ι) {l} {p : ι → α → Prop} : (∀ᶠ x in l, ∀ i ∈ I, p i x) ↔ ∀ i ∈ I, ∀ᶠ x in l, p i x := I.finite_to_set.eventually_all alias eventually_all_finset ← finset.eventually_all attribute [protected] finset.eventually_all @[simp] lemma eventually_or_distrib_left {f : filter α} {p : Prop} {q : α → Prop} : (∀ᶠ x in f, p ∨ q x) ↔ (p ∨ ∀ᶠ x in f, q x) := classical.by_cases (λ h : p, by simp [h]) (λ h, by simp [h]) @[simp] lemma eventually_or_distrib_right {f : filter α} {p : α → Prop} {q : Prop} : (∀ᶠ x in f, p x ∨ q) ↔ ((∀ᶠ x in f, p x) ∨ q) := by simp only [or_comm _ q, eventually_or_distrib_left] @[simp] lemma eventually_imp_distrib_left {f : filter α} {p : Prop} {q : α → Prop} : (∀ᶠ x in f, p → q x) ↔ (p → ∀ᶠ x in f, q x) := by simp only [imp_iff_not_or, eventually_or_distrib_left] @[simp] lemma eventually_bot {p : α → Prop} : ∀ᶠ x in ⊥, p x := ⟨⟩ @[simp] lemma eventually_top {p : α → Prop} : (∀ᶠ x in ⊤, p x) ↔ (∀ x, p x) := iff.rfl @[simp] lemma eventually_sup {p : α → Prop} {f g : filter α} : (∀ᶠ x in f ⊔ g, p x) ↔ (∀ᶠ x in f, p x) ∧ (∀ᶠ x in g, p x) := iff.rfl @[simp] lemma eventually_Sup {p : α → Prop} {fs : set (filter α)} : (∀ᶠ x in Sup fs, p x) ↔ (∀ f ∈ fs, ∀ᶠ x in f, p x) := iff.rfl @[simp] lemma eventually_supr {p : α → Prop} {fs : β → filter α} : (∀ᶠ x in (⨆ b, fs b), p x) ↔ (∀ b, ∀ᶠ x in fs b, p x) := mem_supr_sets @[simp] lemma eventually_principal {a : set α} {p : α → Prop} : (∀ᶠ x in 𝓟 a, p x) ↔ (∀ x ∈ a, p x) := iff.rfl theorem eventually_inf_principal {f : filter α} {p : α → Prop} {s : set α} : (∀ᶠ x in f ⊓ 𝓟 s, p x) ↔ ∀ᶠ x in f, x ∈ s → p x := mem_inf_principal /-! ### Frequently -/ /-- `f.frequently p` or `∃ᶠ x in f, p x` mean that `{x | ¬p x} ∉ f`. E.g., `∃ᶠ x in at_top, p x` means that there exist arbitrarily large `x` for which `p` holds true. -/ protected def frequently (p : α → Prop) (f : filter α) : Prop := ¬∀ᶠ x in f, ¬p x notation `∃ᶠ` binders ` in ` f `, ` r:(scoped p, filter.frequently p f) := r lemma eventually.frequently {f : filter α} [ne_bot f] {p : α → Prop} (h : ∀ᶠ x in f, p x) : ∃ᶠ x in f, p x := compl_not_mem_sets h lemma frequently_of_forall {f : filter α} [ne_bot f] {p : α → Prop} (h : ∀ x, p x) : ∃ᶠ x in f, p x := eventually.frequently (eventually_of_forall h) lemma frequently.mp {p q : α → Prop} {f : filter α} (h : ∃ᶠ x in f, p x) (hpq : ∀ᶠ x in f, p x → q x) : ∃ᶠ x in f, q x := mt (λ hq, hq.mp $ hpq.mono $ λ x, mt) h lemma frequently.mono {p q : α → Prop} {f : filter α} (h : ∃ᶠ x in f, p x) (hpq : ∀ x, p x → q x) : ∃ᶠ x in f, q x := h.mp (eventually_of_forall hpq) lemma frequently.and_eventually {p q : α → Prop} {f : filter α} (hp : ∃ᶠ x in f, p x) (hq : ∀ᶠ x in f, q x) : ∃ᶠ x in f, p x ∧ q x := begin refine mt (λ h, hq.mp $ h.mono _) hp, assume x hpq hq hp, exact hpq ⟨hp, hq⟩ end lemma frequently.exists {p : α → Prop} {f : filter α} (hp : ∃ᶠ x in f, p x) : ∃ x, p x := begin by_contradiction H, replace H : ∀ᶠ x in f, ¬ p x, from eventually_of_forall (not_exists.1 H), exact hp H end lemma eventually.exists {p : α → Prop} {f : filter α} [ne_bot f] (hp : ∀ᶠ x in f, p x) : ∃ x, p x := hp.frequently.exists lemma frequently_iff_forall_eventually_exists_and {p : α → Prop} {f : filter α} : (∃ᶠ x in f, p x) ↔ ∀ {q : α → Prop}, (∀ᶠ x in f, q x) → ∃ x, p x ∧ q x := ⟨assume hp q hq, (hp.and_eventually hq).exists, assume H hp, by simpa only [and_not_self, exists_false] using H hp⟩ lemma frequently_iff {f : filter α} {P : α → Prop} : (∃ᶠ x in f, P x) ↔ ∀ {U}, U ∈ f → ∃ x ∈ U, P x := begin rw frequently_iff_forall_eventually_exists_and, split ; intro h, { intros U U_in, simpa [exists_prop, and_comm] using h U_in }, { intros H H', simpa [and_comm] using h H' }, end @[simp] lemma not_eventually {p : α → Prop} {f : filter α} : (¬ ∀ᶠ x in f, p x) ↔ (∃ᶠ x in f, ¬ p x) := by simp [filter.frequently] @[simp] lemma not_frequently {p : α → Prop} {f : filter α} : (¬ ∃ᶠ x in f, p x) ↔ (∀ᶠ x in f, ¬ p x) := by simp only [filter.frequently, not_not] @[simp] lemma frequently_true_iff_ne_bot (f : filter α) : (∃ᶠ x in f, true) ↔ ne_bot f := by simp [filter.frequently, -not_eventually, eventually_false_iff_eq_bot, ne_bot] @[simp] lemma frequently_false (f : filter α) : ¬ ∃ᶠ x in f, false := by simp @[simp] lemma frequently_const {f : filter α} [ne_bot f] {p : Prop} : (∃ᶠ x in f, p) ↔ p := classical.by_cases (λ h : p, by simpa [h]) (λ h, by simp [h]) @[simp] lemma frequently_or_distrib {f : filter α} {p q : α → Prop} : (∃ᶠ x in f, p x ∨ q x) ↔ (∃ᶠ x in f, p x) ∨ (∃ᶠ x in f, q x) := by simp only [filter.frequently, ← not_and_distrib, not_or_distrib, eventually_and] lemma frequently_or_distrib_left {f : filter α} [ne_bot f] {p : Prop} {q : α → Prop} : (∃ᶠ x in f, p ∨ q x) ↔ (p ∨ ∃ᶠ x in f, q x) := by simp lemma frequently_or_distrib_right {f : filter α} [ne_bot f] {p : α → Prop} {q : Prop} : (∃ᶠ x in f, p x ∨ q) ↔ (∃ᶠ x in f, p x) ∨ q := by simp @[simp] lemma frequently_imp_distrib {f : filter α} {p q : α → Prop} : (∃ᶠ x in f, p x → q x) ↔ ((∀ᶠ x in f, p x) → ∃ᶠ x in f, q x) := by simp [imp_iff_not_or, not_eventually, frequently_or_distrib] lemma frequently_imp_distrib_left {f : filter α} [ne_bot f] {p : Prop} {q : α → Prop} : (∃ᶠ x in f, p → q x) ↔ (p → ∃ᶠ x in f, q x) := by simp lemma frequently_imp_distrib_right {f : filter α} [ne_bot f] {p : α → Prop} {q : Prop} : (∃ᶠ x in f, p x → q) ↔ ((∀ᶠ x in f, p x) → q) := by simp @[simp] lemma eventually_imp_distrib_right {f : filter α} {p : α → Prop} {q : Prop} : (∀ᶠ x in f, p x → q) ↔ ((∃ᶠ x in f, p x) → q) := by simp only [imp_iff_not_or, eventually_or_distrib_right, not_frequently] @[simp] lemma frequently_bot {p : α → Prop} : ¬ ∃ᶠ x in ⊥, p x := by simp @[simp] lemma frequently_top {p : α → Prop} : (∃ᶠ x in ⊤, p x) ↔ (∃ x, p x) := by simp [filter.frequently] @[simp] lemma frequently_principal {a : set α} {p : α → Prop} : (∃ᶠ x in 𝓟 a, p x) ↔ (∃ x ∈ a, p x) := by simp [filter.frequently, not_forall] lemma frequently_sup {p : α → Prop} {f g : filter α} : (∃ᶠ x in f ⊔ g, p x) ↔ (∃ᶠ x in f, p x) ∨ (∃ᶠ x in g, p x) := by simp only [filter.frequently, eventually_sup, not_and_distrib] @[simp] lemma frequently_Sup {p : α → Prop} {fs : set (filter α)} : (∃ᶠ x in Sup fs, p x) ↔ (∃ f ∈ fs, ∃ᶠ x in f, p x) := by simp [filter.frequently, -not_eventually, not_forall] @[simp] lemma frequently_supr {p : α → Prop} {fs : β → filter α} : (∃ᶠ x in (⨆ b, fs b), p x) ↔ (∃ b, ∃ᶠ x in fs b, p x) := by simp [filter.frequently, -not_eventually, not_forall] /-! ### Relation “eventually equal” -/ /-- Two functions `f` and `g` are *eventually equal* along a filter `l` if the set of `x` such that `f x = g x` belongs to `l`. -/ def eventually_eq (l : filter α) (f g : α → β) : Prop := ∀ᶠ x in l, f x = g x notation f ` =ᶠ[`:50 l:50 `] `:0 g:50 := eventually_eq l f g lemma eventually_eq.eventually {l : filter α} {f g : α → β} (h : f =ᶠ[l] g) : ∀ᶠ x in l, f x = g x := h lemma eventually_eq.rw {l : filter α} {f g : α → β} (h : f =ᶠ[l] g) (p : α → β → Prop) (hf : ∀ᶠ x in l, p x (f x)) : ∀ᶠ x in l, p x (g x) := hf.congr $ h.mono $ λ x hx, hx ▸ iff.rfl lemma eventually_eq_set {s t : set α} {l : filter α} : s =ᶠ[l] t ↔ ∀ᶠ x in l, x ∈ s ↔ x ∈ t := eventually_congr $ eventually_of_forall $ λ x, ⟨eq.to_iff, iff.to_eq⟩ alias eventually_eq_set ↔ filter.eventually_eq.mem_iff filter.eventually.set_eq lemma eventually_eq.exists_mem {l : filter α} {f g : α → β} (h : f =ᶠ[l] g) : ∃ s ∈ l, eq_on f g s := h.exists_mem lemma eventually_eq_of_mem {l : filter α} {f g : α → β} {s : set α} (hs : s ∈ l) (h : eq_on f g s) : f =ᶠ[l] g := eventually_of_mem hs h lemma eventually_eq_iff_exists_mem {l : filter α} {f g : α → β} : (f =ᶠ[l] g) ↔ ∃ s ∈ l, eq_on f g s := eventually_iff_exists_mem lemma eventually_eq.filter_mono {l l' : filter α} {f g : α → β} (h₁ : f =ᶠ[l] g) (h₂ : l' ≤ l) : f =ᶠ[l'] g := h₂ h₁ @[refl] lemma eventually_eq.refl (l : filter α) (f : α → β) : f =ᶠ[l] f := eventually_of_forall $ λ x, rfl @[symm] lemma eventually_eq.symm {f g : α → β} {l : filter α} (H : f =ᶠ[l] g) : g =ᶠ[l] f := H.mono $ λ _, eq.symm @[trans] lemma eventually_eq.trans {f g h : α → β} {l : filter α} (H₁ : f =ᶠ[l] g) (H₂ : g =ᶠ[l] h) : f =ᶠ[l] h := H₂.rw (λ x y, f x = y) H₁ lemma eventually_eq.prod_mk {l} {f f' : α → β} (hf : f =ᶠ[l] f') {g g' : α → γ} (hg : g =ᶠ[l] g') : (λ x, (f x, g x)) =ᶠ[l] (λ x, (f' x, g' x)) := hf.mp $ hg.mono $ by { intros, simp only * } lemma eventually_eq.fun_comp {f g : α → β} {l : filter α} (H : f =ᶠ[l] g) (h : β → γ) : (h ∘ f) =ᶠ[l] (h ∘ g) := H.mono $ λ x hx, congr_arg h hx lemma eventually_eq.comp₂ {δ} {f f' : α → β} {g g' : α → γ} {l} (Hf : f =ᶠ[l] f') (h : β → γ → δ) (Hg : g =ᶠ[l] g') : (λ x, h (f x) (g x)) =ᶠ[l] (λ x, h (f' x) (g' x)) := (Hf.prod_mk Hg).fun_comp (function.uncurry h) @[to_additive] lemma eventually_eq.mul [has_mul β] {f f' g g' : α → β} {l : filter α} (h : f =ᶠ[l] g) (h' : f' =ᶠ[l] g') : ((λ x, f x * f' x) =ᶠ[l] (λ x, g x * g' x)) := h.comp₂ (*) h' @[to_additive] lemma eventually_eq.inv [has_inv β] {f g : α → β} {l : filter α} (h : f =ᶠ[l] g) : ((λ x, (f x)⁻¹) =ᶠ[l] (λ x, (g x)⁻¹)) := h.fun_comp has_inv.inv lemma eventually_eq.div [group_with_zero β] {f f' g g' : α → β} {l : filter α} (h : f =ᶠ[l] g) (h' : f' =ᶠ[l] g') : ((λ x, f x / f' x) =ᶠ[l] (λ x, g x / g' x)) := by simpa only [div_eq_mul_inv] using h.mul h'.inv lemma eventually_eq.sub [add_group β] {f f' g g' : α → β} {l : filter α} (h : f =ᶠ[l] g) (h' : f' =ᶠ[l] g') : ((λ x, f x - f' x) =ᶠ[l] (λ x, g x - g' x)) := by simpa only [sub_eq_add_neg] using h.add h'.neg lemma eventually_eq.inter {s t s' t' : set α} {l : filter α} (h : s =ᶠ[l] t) (h' : s' =ᶠ[l] t') : (s ∩ s' : set α) =ᶠ[l] (t ∩ t' : set α) := h.comp₂ (∧) h' lemma eventually_eq.union {s t s' t' : set α} {l : filter α} (h : s =ᶠ[l] t) (h' : s' =ᶠ[l] t') : (s ∪ s' : set α) =ᶠ[l] (t ∪ t' : set α) := h.comp₂ (∨) h' lemma eventually_eq.compl {s t : set α} {l : filter α} (h : s =ᶠ[l] t) : (sᶜ : set α) =ᶠ[l] (tᶜ : set α) := h.fun_comp not lemma eventually_eq.diff {s t s' t' : set α} {l : filter α} (h : s =ᶠ[l] t) (h' : s' =ᶠ[l] t') : (s \ s' : set α) =ᶠ[l] (t \ t' : set α) := h.inter h'.compl lemma eventually_eq_empty {s : set α} {l : filter α} : s =ᶠ[l] (∅ : set α) ↔ ∀ᶠ x in l, x ∉ s := eventually_eq_set.trans $ by simp @[simp] lemma eventually_eq_principal {s : set α} {f g : α → β} : f =ᶠ[𝓟 s] g ↔ eq_on f g s := iff.rfl lemma eventually_eq_inf_principal_iff {F : filter α} {s : set α} {f g : α → β} : (f =ᶠ[F ⊓ 𝓟 s] g) ↔ ∀ᶠ x in F, x ∈ s → f x = g x := eventually_inf_principal section has_le variables [has_le β] {l : filter α} /-- A function `f` is eventually less than or equal to a function `g` at a filter `l`. -/ def eventually_le (l : filter α) (f g : α → β) : Prop := ∀ᶠ x in l, f x ≤ g x notation f ` ≤ᶠ[`:50 l:50 `] `:0 g:50 := eventually_le l f g lemma eventually_le.congr {f f' g g' : α → β} (H : f ≤ᶠ[l] g) (hf : f =ᶠ[l] f') (hg : g =ᶠ[l] g') : f' ≤ᶠ[l] g' := H.mp $ hg.mp $ hf.mono $ λ x hf hg H, by rwa [hf, hg] at H lemma eventually_le_congr {f f' g g' : α → β} (hf : f =ᶠ[l] f') (hg : g =ᶠ[l] g') : f ≤ᶠ[l] g ↔ f' ≤ᶠ[l] g' := ⟨λ H, H.congr hf hg, λ H, H.congr hf.symm hg.symm⟩ end has_le section preorder variables [preorder β] {l : filter α} {f g h : α → β} lemma eventually_eq.le (h : f =ᶠ[l] g) : f ≤ᶠ[l] g := h.mono $ λ x, le_of_eq @[refl] lemma eventually_le.refl (l : filter α) (f : α → β) : f ≤ᶠ[l] f := (eventually_eq.refl l f).le @[trans] lemma eventually_le.trans (H₁ : f ≤ᶠ[l] g) (H₂ : g ≤ᶠ[l] h) : f ≤ᶠ[l] h := H₂.mp $ H₁.mono $ λ x, le_trans @[trans] lemma eventually_eq.trans_le (H₁ : f =ᶠ[l] g) (H₂ : g ≤ᶠ[l] h) : f ≤ᶠ[l] h := H₁.le.trans H₂ @[trans] lemma eventually_le.trans_eq (H₁ : f ≤ᶠ[l] g) (H₂ : g =ᶠ[l] h) : f ≤ᶠ[l] h := H₁.trans H₂.le end preorder lemma eventually_le.antisymm [partial_order β] {l : filter α} {f g : α → β} (h₁ : f ≤ᶠ[l] g) (h₂ : g ≤ᶠ[l] f) : f =ᶠ[l] g := h₂.mp $ h₁.mono $ λ x, le_antisymm lemma eventually_le_antisymm_iff [partial_order β] {l : filter α} {f g : α → β} : f =ᶠ[l] g ↔ f ≤ᶠ[l] g ∧ g ≤ᶠ[l] f := by simp only [eventually_eq, eventually_le, le_antisymm_iff, eventually_and] lemma eventually_le.le_iff_eq [partial_order β] {l : filter α} {f g : α → β} (h : f ≤ᶠ[l] g) : g ≤ᶠ[l] f ↔ g =ᶠ[l] f := ⟨λ h', h'.antisymm h, eventually_eq.le⟩ @[mono] lemma eventually_le.inter {s t s' t' : set α} {l : filter α} (h : s ≤ᶠ[l] t) (h' : s' ≤ᶠ[l] t') : (s ∩ s' : set α) ≤ᶠ[l] (t ∩ t' : set α) := h'.mp $ h.mono $ λ x, and.imp @[mono] lemma eventually_le.union {s t s' t' : set α} {l : filter α} (h : s ≤ᶠ[l] t) (h' : s' ≤ᶠ[l] t') : (s ∪ s' : set α) ≤ᶠ[l] (t ∪ t' : set α) := h'.mp $ h.mono $ λ x, or.imp @[mono] lemma eventually_le.compl {s t : set α} {l : filter α} (h : s ≤ᶠ[l] t) : (tᶜ : set α) ≤ᶠ[l] (sᶜ : set α) := h.mono $ λ x, mt @[mono] lemma eventually_le.diff {s t s' t' : set α} {l : filter α} (h : s ≤ᶠ[l] t) (h' : t' ≤ᶠ[l] s') : (s \ s' : set α) ≤ᶠ[l] (t \ t' : set α) := h.inter h'.compl lemma join_le {f : filter (filter α)} {l : filter α} (h : ∀ᶠ m in f, m ≤ l) : join f ≤ l := λ s hs, h.mono $ λ m hm, hm hs /-! ### Push-forwards, pull-backs, and the monad structure -/ section map /-- The forward map of a filter -/ def map (m : α → β) (f : filter α) : filter β := { sets := preimage m ⁻¹' f.sets, univ_sets := univ_mem_sets, sets_of_superset := assume s t hs st, mem_sets_of_superset hs $ preimage_mono st, inter_sets := assume s t hs ht, inter_mem_sets hs ht } @[simp] lemma map_principal {s : set α} {f : α → β} : map f (𝓟 s) = 𝓟 (set.image f s) := filter_eq $ set.ext $ assume a, image_subset_iff.symm variables {f : filter α} {m : α → β} {m' : β → γ} {s : set α} {t : set β} @[simp] lemma eventually_map {P : β → Prop} : (∀ᶠ b in map m f, P b) ↔ ∀ᶠ a in f, P (m a) := iff.rfl @[simp] lemma frequently_map {P : β → Prop} : (∃ᶠ b in map m f, P b) ↔ ∃ᶠ a in f, P (m a) := iff.rfl @[simp] lemma mem_map : t ∈ map m f ↔ {x | m x ∈ t} ∈ f := iff.rfl lemma image_mem_map (hs : s ∈ f) : m '' s ∈ map m f := f.sets_of_superset hs $ subset_preimage_image m s lemma image_mem_map_iff (hf : function.injective m) : m '' s ∈ map m f ↔ s ∈ f := ⟨λ h, by rwa [← preimage_image_eq s hf], image_mem_map⟩ lemma range_mem_map : range m ∈ map m f := by rw ←image_univ; exact image_mem_map univ_mem_sets lemma mem_map_sets_iff : t ∈ map m f ↔ (∃s∈f, m '' s ⊆ t) := iff.intro (assume ht, ⟨m ⁻¹' t, ht, image_preimage_subset _ _⟩) (assume ⟨s, hs, ht⟩, mem_sets_of_superset (image_mem_map hs) ht) @[simp] lemma map_id : filter.map id f = f := filter_eq $ rfl @[simp] lemma map_compose : filter.map m' ∘ filter.map m = filter.map (m' ∘ m) := funext $ assume _, filter_eq $ rfl @[simp] lemma map_map : filter.map m' (filter.map m f) = filter.map (m' ∘ m) f := congr_fun (@@filter.map_compose m m') f /-- If functions `m₁` and `m₂` are eventually equal at a filter `f`, then they map this filter to the same filter. -/ lemma map_congr {m₁ m₂ : α → β} {f : filter α} (h : m₁ =ᶠ[f] m₂) : map m₁ f = map m₂ f := filter.ext' $ λ p, by { simp only [eventually_map], exact eventually_congr (h.mono $ λ x hx, hx ▸ iff.rfl) } end map section comap /-- The inverse map of a filter -/ def comap (m : α → β) (f : filter β) : filter α := { sets := { s | ∃t∈ f, m ⁻¹' t ⊆ s }, univ_sets := ⟨univ, univ_mem_sets, by simp only [subset_univ, preimage_univ]⟩, sets_of_superset := assume a b ⟨a', ha', ma'a⟩ ab, ⟨a', ha', subset.trans ma'a ab⟩, inter_sets := assume a b ⟨a', ha₁, ha₂⟩ ⟨b', hb₁, hb₂⟩, ⟨a' ∩ b', inter_mem_sets ha₁ hb₁, inter_subset_inter ha₂ hb₂⟩ } @[simp] lemma eventually_comap {f : filter β} {φ : α → β} {P : α → Prop} : (∀ᶠ a in comap φ f, P a) ↔ ∀ᶠ b in f, ∀ a, φ a = b → P a := begin split ; intro h, { rcases h with ⟨t, t_in, ht⟩, apply mem_sets_of_superset t_in, rintros y y_in _ rfl, apply ht y_in }, { exact ⟨_, h, λ _ x_in, x_in _ rfl⟩ } end @[simp] lemma frequently_comap {f : filter β} {φ : α → β} {P : α → Prop} : (∃ᶠ a in comap φ f, P a) ↔ ∃ᶠ b in f, ∃ a, φ a = b ∧ P a := begin classical, erw [← not_iff_not, not_not, not_not, filter.eventually_comap], simp only [not_exists, not_and], end end comap /-- The monadic bind operation on filter is defined the usual way in terms of `map` and `join`. Unfortunately, this `bind` does not result in the expected applicative. See `filter.seq` for the applicative instance. -/ def bind (f : filter α) (m : α → filter β) : filter β := join (map m f) /-- The applicative sequentiation operation. This is not induced by the bind operation. -/ def seq (f : filter (α → β)) (g : filter α) : filter β := ⟨{ s | ∃u∈ f, ∃t∈ g, (∀m∈u, ∀x∈t, (m : α → β) x ∈ s) }, ⟨univ, univ_mem_sets, univ, univ_mem_sets, by simp only [forall_prop_of_true, mem_univ, forall_true_iff]⟩, assume s₀ s₁ ⟨t₀, t₁, h₀, h₁, h⟩ hst, ⟨t₀, t₁, h₀, h₁, assume x hx y hy, hst $ h _ hx _ hy⟩, assume s₀ s₁ ⟨t₀, ht₀, t₁, ht₁, ht⟩ ⟨u₀, hu₀, u₁, hu₁, hu⟩, ⟨t₀ ∩ u₀, inter_mem_sets ht₀ hu₀, t₁ ∩ u₁, inter_mem_sets ht₁ hu₁, assume x ⟨hx₀, hx₁⟩ x ⟨hy₀, hy₁⟩, ⟨ht _ hx₀ _ hy₀, hu _ hx₁ _ hy₁⟩⟩⟩ /-- `pure x` is the set of sets that contain `x`. It is equal to `𝓟 {x}` but with this definition we have `s ∈ pure a` defeq `a ∈ s`. -/ instance : has_pure filter := ⟨λ (α : Type u) x, { sets := {s | x ∈ s}, inter_sets := λ s t, and.intro, sets_of_superset := λ s t hs hst, hst hs, univ_sets := trivial }⟩ instance : has_bind filter := ⟨@filter.bind⟩ instance : has_seq filter := ⟨@filter.seq⟩ instance : functor filter := { map := @filter.map } lemma pure_sets (a : α) : (pure a : filter α).sets = {s | a ∈ s} := rfl @[simp] lemma mem_pure_sets {a : α} {s : set α} : s ∈ (pure a : filter α) ↔ a ∈ s := iff.rfl @[simp] lemma eventually_pure {a : α} {p : α → Prop} : (∀ᶠ x in pure a, p x) ↔ p a := iff.rfl @[simp] lemma principal_singleton (a : α) : 𝓟 {a} = pure a := filter.ext $ λ s, by simp only [mem_pure_sets, mem_principal_sets, singleton_subset_iff] @[simp] lemma map_pure (f : α → β) (a : α) : map f (pure a) = pure (f a) := rfl @[simp] lemma join_pure (f : filter α) : join (pure f) = f := filter.ext $ λ s, iff.rfl @[simp] lemma pure_bind (a : α) (m : α → filter β) : bind (pure a) m = m a := by simp only [has_bind.bind, bind, map_pure, join_pure] section -- this section needs to be before applicative, otherwise the wrong instance will be chosen /-- The monad structure on filters. -/ protected def monad : monad filter := { map := @filter.map } local attribute [instance] filter.monad protected lemma is_lawful_monad : is_lawful_monad filter := { id_map := assume α f, filter_eq rfl, pure_bind := assume α β, pure_bind, bind_assoc := assume α β γ f m₁ m₂, filter_eq rfl, bind_pure_comp_eq_map := assume α β f x, filter.ext $ λ s, by simp only [has_bind.bind, bind, functor.map, mem_map, mem_join_sets, mem_set_of_eq, function.comp, mem_pure_sets] } end instance : applicative filter := { map := @filter.map, seq := @filter.seq } instance : alternative filter := { failure := λα, ⊥, orelse := λα x y, x ⊔ y } @[simp] lemma map_def {α β} (m : α → β) (f : filter α) : m <$> f = map m f := rfl @[simp] lemma bind_def {α β} (f : filter α) (m : α → filter β) : f >>= m = bind f m := rfl /- map and comap equations -/ section map variables {f f₁ f₂ : filter α} {g g₁ g₂ : filter β} {m : α → β} {m' : β → γ} {s : set α} {t : set β} @[simp] theorem mem_comap_sets : s ∈ comap m g ↔ ∃t∈ g, m ⁻¹' t ⊆ s := iff.rfl theorem preimage_mem_comap (ht : t ∈ g) : m ⁻¹' t ∈ comap m g := ⟨t, ht, subset.refl _⟩ lemma comap_id : comap id f = f := le_antisymm (assume s, preimage_mem_comap) (assume s ⟨t, ht, hst⟩, mem_sets_of_superset ht hst) lemma comap_const_of_not_mem {x : α} {f : filter α} {V : set α} (hV : V ∈ f) (hx : x ∉ V) : comap (λ y : α, x) f = ⊥ := begin ext W, suffices : ∃ t ∈ f, (λ (y : α), x) ⁻¹' t ⊆ W, by simpa, use [V, hV], simp [preimage_const_of_not_mem hx], end lemma comap_const_of_mem {x : α} {f : filter α} (h : ∀ V ∈ f, x ∈ V) : comap (λ y : α, x) f = ⊤ := begin ext W, suffices : (∃ (t : set α), t ∈ f.sets ∧ (λ (y : α), x) ⁻¹' t ⊆ W) ↔ W = univ, by simpa, split, { rintros ⟨V, V_in, hW⟩, simpa [preimage_const_of_mem (h V V_in), univ_subset_iff] using hW }, { rintro rfl, use univ, simp [univ_mem_sets] }, end lemma comap_comap {m : γ → β} {n : β → α} : comap m (comap n f) = comap (n ∘ m) f := le_antisymm (assume c ⟨b, hb, (h : preimage (n ∘ m) b ⊆ c)⟩, ⟨preimage n b, preimage_mem_comap hb, h⟩) (assume c ⟨b, ⟨a, ha, (h₁ : preimage n a ⊆ b)⟩, (h₂ : preimage m b ⊆ c)⟩, ⟨a, ha, show preimage m (preimage n a) ⊆ c, from subset.trans (preimage_mono h₁) h₂⟩) @[simp] theorem comap_principal {t : set β} : comap m (𝓟 t) = 𝓟 (m ⁻¹' t) := filter_eq $ set.ext $ assume s, ⟨assume ⟨u, (hu : t ⊆ u), (b : preimage m u ⊆ s)⟩, subset.trans (preimage_mono hu) b, assume : preimage m t ⊆ s, ⟨t, subset.refl t, this⟩⟩ @[simp] theorem comap_pure {b : β} : comap m (pure b) = 𝓟 (m ⁻¹' {b}) := by rw [← principal_singleton, comap_principal] lemma map_le_iff_le_comap : map m f ≤ g ↔ f ≤ comap m g := ⟨assume h s ⟨t, ht, hts⟩, mem_sets_of_superset (h ht) hts, assume h s ht, h ⟨_, ht, subset.refl _⟩⟩ lemma gc_map_comap (m : α → β) : galois_connection (map m) (comap m) := assume f g, map_le_iff_le_comap @[mono] lemma map_mono : monotone (map m) := (gc_map_comap m).monotone_l @[mono] lemma comap_mono : monotone (comap m) := (gc_map_comap m).monotone_u @[simp] lemma map_bot : map m ⊥ = ⊥ := (gc_map_comap m).l_bot @[simp] lemma map_sup : map m (f₁ ⊔ f₂) = map m f₁ ⊔ map m f₂ := (gc_map_comap m).l_sup @[simp] lemma map_supr {f : ι → filter α} : map m (⨆i, f i) = (⨆i, map m (f i)) := (gc_map_comap m).l_supr @[simp] lemma comap_top : comap m ⊤ = ⊤ := (gc_map_comap m).u_top @[simp] lemma comap_inf : comap m (g₁ ⊓ g₂) = comap m g₁ ⊓ comap m g₂ := (gc_map_comap m).u_inf @[simp] lemma comap_infi {f : ι → filter β} : comap m (⨅i, f i) = (⨅i, comap m (f i)) := (gc_map_comap m).u_infi lemma le_comap_top (f : α → β) (l : filter α) : l ≤ comap f ⊤ := by rw [comap_top]; exact le_top lemma map_comap_le : map m (comap m g) ≤ g := (gc_map_comap m).l_u_le _ lemma le_comap_map : f ≤ comap m (map m f) := (gc_map_comap m).le_u_l _ @[simp] lemma comap_bot : comap m ⊥ = ⊥ := bot_unique $ assume s _, ⟨∅, by simp only [mem_bot_sets], by simp only [empty_subset, preimage_empty]⟩ lemma comap_supr {ι} {f : ι → filter β} {m : α → β} : comap m (supr f) = (⨆i, comap m (f i)) := le_antisymm (assume s hs, have ∀i, ∃t, t ∈ f i ∧ m ⁻¹' t ⊆ s, by simpa only [mem_comap_sets, exists_prop, mem_supr_sets] using mem_supr_sets.1 hs, let ⟨t, ht⟩ := classical.axiom_of_choice this in ⟨⋃i, t i, mem_supr_sets.2 $ assume i, (f i).sets_of_superset (ht i).1 (subset_Union _ _), begin rw [preimage_Union, Union_subset_iff], assume i, exact (ht i).2 end⟩) (supr_le $ assume i, comap_mono $ le_supr _ _) lemma comap_Sup {s : set (filter β)} {m : α → β} : comap m (Sup s) = (⨆f∈s, comap m f) := by simp only [Sup_eq_supr, comap_supr, eq_self_iff_true] lemma comap_sup : comap m (g₁ ⊔ g₂) = comap m g₁ ⊔ comap m g₂ := le_antisymm (assume s ⟨⟨t₁, ht₁, hs₁⟩, ⟨t₂, ht₂, hs₂⟩⟩, ⟨t₁ ∪ t₂, ⟨g₁.sets_of_superset ht₁ (subset_union_left _ _), g₂.sets_of_superset ht₂ (subset_union_right _ _)⟩, union_subset hs₁ hs₂⟩) ((@comap_mono _ _ m).le_map_sup _ _) lemma map_comap {f : filter β} {m : α → β} (hf : range m ∈ f) : (f.comap m).map m = f := le_antisymm map_comap_le (assume t' ⟨t, ht, sub⟩, by filter_upwards [ht, hf]; rintros x hxt ⟨y, rfl⟩; exact sub hxt) lemma image_mem_sets {f : filter α} {c : β → α} (h : range c ∈ f) {W : set β} (W_in : W ∈ comap c f) : c '' W ∈ f := begin rw ← map_comap h, exact image_mem_map W_in end lemma image_coe_mem_sets {f : filter α} {U : set α} (h : U ∈ f) {W : set U} (W_in : W ∈ comap (coe : U → α) f) : coe '' W ∈ f := image_mem_sets (by simp [h]) W_in lemma comap_map {f : filter α} {m : α → β} (h : function.injective m) : comap m (map m f) = f := le_antisymm (assume s hs, mem_sets_of_superset (preimage_mem_comap $ image_mem_map hs) $ by simp only [preimage_image_eq s h]) le_comap_map lemma mem_comap_iff {f : filter β} {m : α → β} (inj : function.injective m) (large : set.range m ∈ f) {S : set α} : S ∈ comap m f ↔ m '' S ∈ f := by rw [← image_mem_map_iff inj, map_comap large] lemma le_of_map_le_map_inj' {f g : filter α} {m : α → β} {s : set α} (hsf : s ∈ f) (hsg : s ∈ g) (hm : ∀x∈s, ∀y∈s, m x = m y → x = y) (h : map m f ≤ map m g) : f ≤ g := assume t ht, by filter_upwards [hsf, h $ image_mem_map (inter_mem_sets hsg ht)] assume a has ⟨b, ⟨hbs, hb⟩, h⟩, have b = a, from hm _ hbs _ has h, this ▸ hb lemma le_of_map_le_map_inj_iff {f g : filter α} {m : α → β} {s : set α} (hsf : s ∈ f) (hsg : s ∈ g) (hm : ∀x∈s, ∀y∈s, m x = m y → x = y) : map m f ≤ map m g ↔ f ≤ g := iff.intro (le_of_map_le_map_inj' hsf hsg hm) (λ h, map_mono h) lemma eq_of_map_eq_map_inj' {f g : filter α} {m : α → β} {s : set α} (hsf : s ∈ f) (hsg : s ∈ g) (hm : ∀x∈s, ∀y∈s, m x = m y → x = y) (h : map m f = map m g) : f = g := le_antisymm (le_of_map_le_map_inj' hsf hsg hm $ le_of_eq h) (le_of_map_le_map_inj' hsg hsf hm $ le_of_eq h.symm) lemma map_inj {f g : filter α} {m : α → β} (hm : ∀ x y, m x = m y → x = y) (h : map m f = map m g) : f = g := have comap m (map m f) = comap m (map m g), by rw h, by rwa [comap_map hm, comap_map hm] at this theorem le_map_comap_of_surjective' {f : α → β} {l : filter β} {u : set β} (ul : u ∈ l) (hf : ∀ y ∈ u, ∃ x, f x = y) : l ≤ map f (comap f l) := assume s ⟨t, tl, ht⟩, have t ∩ u ⊆ s, from assume x ⟨xt, xu⟩, exists.elim (hf x xu) $ λ a faeq, by { rw ←faeq, apply ht, change f a ∈ t, rw faeq, exact xt }, mem_sets_of_superset (inter_mem_sets tl ul) this theorem map_comap_of_surjective' {f : α → β} {l : filter β} {u : set β} (ul : u ∈ l) (hf : ∀ y ∈ u, ∃ x, f x = y) : map f (comap f l) = l := le_antisymm map_comap_le (le_map_comap_of_surjective' ul hf) theorem le_map_comap_of_surjective {f : α → β} (hf : function.surjective f) (l : filter β) : l ≤ map f (comap f l) := le_map_comap_of_surjective' univ_mem_sets (λ y _, hf y) theorem map_comap_of_surjective {f : α → β} (hf : function.surjective f) (l : filter β) : map f (comap f l) = l := le_antisymm map_comap_le (le_map_comap_of_surjective hf l) lemma subtype_coe_map_comap (s : set α) (f : filter α) : map (coe : s → α) (comap (coe : s → α) f) = f ⊓ 𝓟 s := begin apply le_antisymm, { rw [map_le_iff_le_comap, comap_inf, comap_principal], have : (coe : s → α) ⁻¹' s = univ, by { ext x, simp }, rw [this, principal_univ], simp [le_refl _] }, { intros V V_in, rcases V_in with ⟨W, W_in, H⟩, rw mem_inf_sets, use [W, W_in, s, mem_principal_self s], erw [← image_subset_iff, subtype.image_preimage_coe] at H, exact H } end lemma subtype_coe_map_comap_prod (s : set α) (f : filter (α × α)) : map (coe : s × s → α × α) (comap (coe : s × s → α × α) f) = f ⊓ 𝓟 (s.prod s) := let φ (x : s × s) : s.prod s := ⟨⟨x.1.1, x.2.1⟩, ⟨x.1.2, x.2.2⟩⟩ in begin rw show (coe : s × s → α × α) = coe ∘ φ, by ext x; cases x; refl, rw [← filter.map_map, ← filter.comap_comap], rw map_comap_of_surjective, exact subtype_coe_map_comap _ _, exact λ ⟨⟨a, b⟩, ⟨ha, hb⟩⟩, ⟨⟨⟨a, ha⟩, ⟨b, hb⟩⟩, rfl⟩ end lemma comap_ne_bot_iff {f : filter β} {m : α → β} : ne_bot (comap m f) ↔ ∀ t ∈ f, ∃ a, m a ∈ t := begin rw ← forall_sets_nonempty_iff_ne_bot, exact ⟨λ h t t_in, h (m ⁻¹' t) ⟨t, t_in, subset.refl _⟩, λ h s ⟨u, u_in, hu⟩, let ⟨x, hx⟩ := h u u_in in ⟨x, hu hx⟩⟩, end lemma comap_ne_bot {f : filter β} {m : α → β} (hm : ∀t∈ f, ∃a, m a ∈ t) : ne_bot (comap m f) := comap_ne_bot_iff.mpr hm lemma comap_ne_bot_iff_frequently {f : filter β} {m : α → β} : ne_bot (comap m f) ↔ ∃ᶠ y in f, y ∈ range m := by simp [comap_ne_bot_iff, frequently_iff, ← exists_and_distrib_left, and.comm] lemma comap_ne_bot_iff_compl_range {f : filter β} {m : α → β} : ne_bot (comap m f) ↔ (range m)ᶜ ∉ f := comap_ne_bot_iff_frequently lemma ne_bot.comap_of_range_mem {f : filter β} {m : α → β} (hf : ne_bot f) (hm : range m ∈ f) : ne_bot (comap m f) := comap_ne_bot_iff_frequently.2 $ eventually.frequently hm lemma comap_inf_principal_ne_bot_of_image_mem {f : filter β} {m : α → β} (hf : ne_bot f) {s : set α} (hs : m '' s ∈ f) : ne_bot (comap m f ⊓ 𝓟 s) := begin refine compl_compl s ▸ mt mem_sets_of_eq_bot _, rintros ⟨t, ht, hts⟩, rcases hf.nonempty_of_mem (inter_mem_sets hs ht) with ⟨_, ⟨x, hxs, rfl⟩, hxt⟩, exact absurd hxs (hts hxt) end lemma ne_bot.comap_of_surj {f : filter β} {m : α → β} (hf : ne_bot f) (hm : function.surjective m) : ne_bot (comap m f) := hf.comap_of_range_mem $ univ_mem_sets' hm lemma ne_bot.comap_of_image_mem {f : filter β} {m : α → β} (hf : ne_bot f) {s : set α} (hs : m '' s ∈ f) : ne_bot (comap m f) := hf.comap_of_range_mem $ mem_sets_of_superset hs (image_subset_range _ _) @[simp] lemma map_eq_bot_iff : map m f = ⊥ ↔ f = ⊥ := ⟨by rw [←empty_in_sets_eq_bot, ←empty_in_sets_eq_bot]; exact id, assume h, by simp only [h, eq_self_iff_true, map_bot]⟩ lemma map_ne_bot_iff (f : α → β) {F : filter α} : ne_bot (map f F) ↔ ne_bot F := not_congr map_eq_bot_iff lemma ne_bot.map (hf : ne_bot f) (m : α → β) : ne_bot (map m f) := (map_ne_bot_iff m).2 hf instance map_ne_bot [hf : ne_bot f] : ne_bot (f.map m) := hf.map m lemma sInter_comap_sets (f : α → β) (F : filter β) : ⋂₀ (comap f F).sets = ⋂ U ∈ F, f ⁻¹' U := begin ext x, suffices : (∀ (A : set α) (B : set β), B ∈ F → f ⁻¹' B ⊆ A → x ∈ A) ↔ ∀ (B : set β), B ∈ F → f x ∈ B, by simp only [mem_sInter, mem_Inter, filter.mem_sets, mem_comap_sets, this, and_imp, mem_comap_sets, exists_prop, mem_sInter, mem_Inter, mem_preimage, exists_imp_distrib], split, { intros h U U_in, simpa only [set.subset.refl, forall_prop_of_true, mem_preimage] using h (f ⁻¹' U) U U_in }, { intros h V U U_in f_U_V, exact f_U_V (h U U_in) }, end end map -- this is a generic rule for monotone functions: lemma map_infi_le {f : ι → filter α} {m : α → β} : map m (infi f) ≤ (⨅ i, map m (f i)) := le_infi $ assume i, map_mono $ infi_le _ _ lemma map_infi_eq {f : ι → filter α} {m : α → β} (hf : directed (≥) f) [nonempty ι] : map m (infi f) = (⨅ i, map m (f i)) := le_antisymm map_infi_le (assume s (hs : preimage m s ∈ infi f), have ∃i, preimage m s ∈ f i, by simp only [mem_infi hf, mem_Union] at hs; assumption, let ⟨i, hi⟩ := this in have (⨅ i, map m (f i)) ≤ 𝓟 s, from infi_le_of_le i $ by simp only [le_principal_iff, mem_map]; assumption, by simp only [filter.le_principal_iff] at this; assumption) lemma map_binfi_eq {ι : Type w} {f : ι → filter α} {m : α → β} {p : ι → Prop} (h : directed_on (f ⁻¹'o (≥)) {x | p x}) (ne : ∃i, p i) : map m (⨅i (h : p i), f i) = (⨅i (h: p i), map m (f i)) := begin haveI := nonempty_subtype.2 ne, simp only [infi_subtype'], exact map_infi_eq h.directed_coe end lemma map_inf_le {f g : filter α} {m : α → β} : map m (f ⊓ g) ≤ map m f ⊓ map m g := (@map_mono _ _ m).map_inf_le f g lemma map_inf' {f g : filter α} {m : α → β} {t : set α} (htf : t ∈ f) (htg : t ∈ g) (h : ∀x∈t, ∀y∈t, m x = m y → x = y) : map m (f ⊓ g) = map m f ⊓ map m g := begin refine le_antisymm map_inf_le (assume s hs, _), simp only [mem_inf_sets, exists_prop, mem_map, mem_preimage, mem_inf_sets] at hs ⊢, rcases hs with ⟨t₁, h₁, t₂, h₂, hs⟩, refine ⟨m '' (t₁ ∩ t), _, m '' (t₂ ∩ t), _, _⟩, { filter_upwards [h₁, htf] assume a h₁ h₂, mem_image_of_mem _ ⟨h₁, h₂⟩ }, { filter_upwards [h₂, htg] assume a h₁ h₂, mem_image_of_mem _ ⟨h₁, h₂⟩ }, { rw [image_inter_on], { refine image_subset_iff.2 _, exact λ x ⟨⟨h₁, _⟩, h₂, _⟩, hs ⟨h₁, h₂⟩ }, { exact λ x ⟨_, hx⟩ y ⟨_, hy⟩, h x hx y hy } } end lemma map_inf {f g : filter α} {m : α → β} (h : function.injective m) : map m (f ⊓ g) = map m f ⊓ map m g := map_inf' univ_mem_sets univ_mem_sets (assume x _ y _ hxy, h hxy) lemma map_eq_comap_of_inverse {f : filter α} {m : α → β} {n : β → α} (h₁ : m ∘ n = id) (h₂ : n ∘ m = id) : map m f = comap n f := le_antisymm (assume b ⟨a, ha, (h : preimage n a ⊆ b)⟩, f.sets_of_superset ha $ calc a = preimage (n ∘ m) a : by simp only [h₂, preimage_id, eq_self_iff_true] ... ⊆ preimage m b : preimage_mono h) (assume b (hb : preimage m b ∈ f), ⟨preimage m b, hb, show preimage (m ∘ n) b ⊆ b, by simp only [h₁]; apply subset.refl⟩) lemma map_swap_eq_comap_swap {f : filter (α × β)} : prod.swap <$> f = comap prod.swap f := map_eq_comap_of_inverse prod.swap_swap_eq prod.swap_swap_eq lemma le_map {f : filter α} {m : α → β} {g : filter β} (h : ∀s∈ f, m '' s ∈ g) : g ≤ f.map m := assume s hs, mem_sets_of_superset (h _ hs) $ image_preimage_subset _ _ protected lemma push_pull (f : α → β) (F : filter α) (G : filter β) : map f (F ⊓ comap f G) = map f F ⊓ G := begin apply le_antisymm, { calc map f (F ⊓ comap f G) ≤ map f F ⊓ (map f $ comap f G) : map_inf_le ... ≤ map f F ⊓ G : inf_le_inf_left (map f F) map_comap_le }, { rintros U ⟨V, V_in, W, ⟨Z, Z_in, hZ⟩, h⟩, rw ← image_subset_iff at h, use [f '' V, image_mem_map V_in, Z, Z_in], refine subset.trans _ h, have : f '' (V ∩ f ⁻¹' Z) ⊆ f '' (V ∩ W), from image_subset _ (inter_subset_inter_right _ ‹_›), rwa image_inter_preimage at this } end protected lemma push_pull' (f : α → β) (F : filter α) (G : filter β) : map f (comap f G ⊓ F) = G ⊓ map f F := by simp only [filter.push_pull, inf_comm] section applicative lemma singleton_mem_pure_sets {a : α} : {a} ∈ (pure a : filter α) := mem_singleton a lemma pure_injective : function.injective (pure : α → filter α) := assume a b hab, (filter.ext_iff.1 hab {x | a = x}).1 rfl instance pure_ne_bot {α : Type u} {a : α} : ne_bot (pure a) := mt empty_in_sets_eq_bot.2 $ not_mem_empty a @[simp] lemma le_pure_iff {f : filter α} {a : α} : f ≤ pure a ↔ {a} ∈ f := ⟨λ h, h singleton_mem_pure_sets, λ h s hs, mem_sets_of_superset h $ singleton_subset_iff.2 hs⟩ lemma mem_seq_sets_def {f : filter (α → β)} {g : filter α} {s : set β} : s ∈ f.seq g ↔ (∃u ∈ f, ∃t ∈ g, ∀x∈u, ∀y∈t, (x : α → β) y ∈ s) := iff.rfl lemma mem_seq_sets_iff {f : filter (α → β)} {g : filter α} {s : set β} : s ∈ f.seq g ↔ (∃u ∈ f, ∃t ∈ g, set.seq u t ⊆ s) := by simp only [mem_seq_sets_def, seq_subset, exists_prop, iff_self] lemma mem_map_seq_iff {f : filter α} {g : filter β} {m : α → β → γ} {s : set γ} : s ∈ (f.map m).seq g ↔ (∃t u, t ∈ g ∧ u ∈ f ∧ ∀x∈u, ∀y∈t, m x y ∈ s) := iff.intro (assume ⟨t, ht, s, hs, hts⟩, ⟨s, m ⁻¹' t, hs, ht, assume a, hts _⟩) (assume ⟨t, s, ht, hs, hts⟩, ⟨m '' s, image_mem_map hs, t, ht, assume f ⟨a, has, eq⟩, eq ▸ hts _ has⟩) lemma seq_mem_seq_sets {f : filter (α → β)} {g : filter α} {s : set (α → β)} {t : set α} (hs : s ∈ f) (ht : t ∈ g) : s.seq t ∈ f.seq g := ⟨s, hs, t, ht, assume f hf a ha, ⟨f, hf, a, ha, rfl⟩⟩ lemma le_seq {f : filter (α → β)} {g : filter α} {h : filter β} (hh : ∀t ∈ f, ∀u ∈ g, set.seq t u ∈ h) : h ≤ seq f g := assume s ⟨t, ht, u, hu, hs⟩, mem_sets_of_superset (hh _ ht _ hu) $ assume b ⟨m, hm, a, ha, eq⟩, eq ▸ hs _ hm _ ha @[mono] lemma seq_mono {f₁ f₂ : filter (α → β)} {g₁ g₂ : filter α} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁.seq g₁ ≤ f₂.seq g₂ := le_seq $ assume s hs t ht, seq_mem_seq_sets (hf hs) (hg ht) @[simp] lemma pure_seq_eq_map (g : α → β) (f : filter α) : seq (pure g) f = f.map g := begin refine le_antisymm (le_map $ assume s hs, _) (le_seq $ assume s hs t ht, _), { rw ← singleton_seq, apply seq_mem_seq_sets _ hs, exact singleton_mem_pure_sets }, { refine sets_of_superset (map g f) (image_mem_map ht) _, rintros b ⟨a, ha, rfl⟩, exact ⟨g, hs, a, ha, rfl⟩ } end @[simp] lemma seq_pure (f : filter (α → β)) (a : α) : seq f (pure a) = map (λg:α → β, g a) f := begin refine le_antisymm (le_map $ assume s hs, _) (le_seq $ assume s hs t ht, _), { rw ← seq_singleton, exact seq_mem_seq_sets hs singleton_mem_pure_sets }, { refine sets_of_superset (map (λg:α→β, g a) f) (image_mem_map hs) _, rintros b ⟨g, hg, rfl⟩, exact ⟨g, hg, a, ht, rfl⟩ } end @[simp] lemma seq_assoc (x : filter α) (g : filter (α → β)) (h : filter (β → γ)) : seq h (seq g x) = seq (seq (map (∘) h) g) x := begin refine le_antisymm (le_seq $ assume s hs t ht, _) (le_seq $ assume s hs t ht, _), { rcases mem_seq_sets_iff.1 hs with ⟨u, hu, v, hv, hs⟩, rcases mem_map_sets_iff.1 hu with ⟨w, hw, hu⟩, refine mem_sets_of_superset _ (set.seq_mono (subset.trans (set.seq_mono hu (subset.refl _)) hs) (subset.refl _)), rw ← set.seq_seq, exact seq_mem_seq_sets hw (seq_mem_seq_sets hv ht) }, { rcases mem_seq_sets_iff.1 ht with ⟨u, hu, v, hv, ht⟩, refine mem_sets_of_superset _ (set.seq_mono (subset.refl _) ht), rw set.seq_seq, exact seq_mem_seq_sets (seq_mem_seq_sets (image_mem_map hs) hu) hv } end lemma prod_map_seq_comm (f : filter α) (g : filter β) : (map prod.mk f).seq g = seq (map (λb a, (a, b)) g) f := begin refine le_antisymm (le_seq $ assume s hs t ht, _) (le_seq $ assume s hs t ht, _), { rcases mem_map_sets_iff.1 hs with ⟨u, hu, hs⟩, refine mem_sets_of_superset _ (set.seq_mono hs (subset.refl _)), rw ← set.prod_image_seq_comm, exact seq_mem_seq_sets (image_mem_map ht) hu }, { rcases mem_map_sets_iff.1 hs with ⟨u, hu, hs⟩, refine mem_sets_of_superset _ (set.seq_mono hs (subset.refl _)), rw set.prod_image_seq_comm, exact seq_mem_seq_sets (image_mem_map ht) hu } end instance : is_lawful_functor (filter : Type u → Type u) := { id_map := assume α f, map_id, comp_map := assume α β γ f g a, map_map.symm } instance : is_lawful_applicative (filter : Type u → Type u) := { pure_seq_eq_map := assume α β, pure_seq_eq_map, map_pure := assume α β, map_pure, seq_pure := assume α β, seq_pure, seq_assoc := assume α β γ, seq_assoc } instance : is_comm_applicative (filter : Type u → Type u) := ⟨assume α β f g, prod_map_seq_comm f g⟩ lemma {l} seq_eq_filter_seq {α β : Type l} (f : filter (α → β)) (g : filter α) : f <*> g = seq f g := rfl end applicative /- bind equations -/ section bind @[simp] lemma eventually_bind {f : filter α} {m : α → filter β} {p : β → Prop} : (∀ᶠ y in bind f m, p y) ↔ ∀ᶠ x in f, ∀ᶠ y in m x, p y := iff.rfl @[simp] lemma eventually_eq_bind {f : filter α} {m : α → filter β} {g₁ g₂ : β → γ} : (g₁ =ᶠ[bind f m] g₂) ↔ ∀ᶠ x in f, g₁ =ᶠ[m x] g₂ := iff.rfl @[simp] lemma eventually_le_bind [has_le γ] {f : filter α} {m : α → filter β} {g₁ g₂ : β → γ} : (g₁ ≤ᶠ[bind f m] g₂) ↔ ∀ᶠ x in f, g₁ ≤ᶠ[m x] g₂ := iff.rfl lemma mem_bind_sets' {s : set β} {f : filter α} {m : α → filter β} : s ∈ bind f m ↔ {a | s ∈ m a} ∈ f := iff.rfl @[simp] lemma mem_bind_sets {s : set β} {f : filter α} {m : α → filter β} : s ∈ bind f m ↔ ∃t ∈ f, ∀x ∈ t, s ∈ m x := calc s ∈ bind f m ↔ {a | s ∈ m a} ∈ f : iff.rfl ... ↔ (∃t ∈ f, t ⊆ {a | s ∈ m a}) : exists_sets_subset_iff.symm ... ↔ (∃t ∈ f, ∀x ∈ t, s ∈ m x) : iff.rfl lemma bind_le {f : filter α} {g : α → filter β} {l : filter β} (h : ∀ᶠ x in f, g x ≤ l) : f.bind g ≤ l := join_le $ eventually_map.2 h @[mono] lemma bind_mono {f₁ f₂ : filter α} {g₁ g₂ : α → filter β} (hf : f₁ ≤ f₂) (hg : g₁ ≤ᶠ[f₁] g₂) : bind f₁ g₁ ≤ bind f₂ g₂ := begin refine le_trans (λ s hs, _) (join_mono $ map_mono hf), simp only [mem_join_sets, mem_bind_sets', mem_map] at hs ⊢, filter_upwards [hg, hs], exact λ x hx hs, hx hs end lemma bind_inf_principal {f : filter α} {g : α → filter β} {s : set β} : f.bind (λ x, g x ⊓ 𝓟 s) = (f.bind g) ⊓ 𝓟 s := filter.ext $ λ s, by simp only [mem_bind_sets, mem_inf_principal] lemma sup_bind {f g : filter α} {h : α → filter β} : bind (f ⊔ g) h = bind f h ⊔ bind g h := by simp only [bind, sup_join, map_sup, eq_self_iff_true] lemma principal_bind {s : set α} {f : α → filter β} : (bind (𝓟 s) f) = (⨆x ∈ s, f x) := show join (map f (𝓟 s)) = (⨆x ∈ s, f x), by simp only [Sup_image, join_principal_eq_Sup, map_principal, eq_self_iff_true] end bind section list_traverse /- This is a separate section in order to open `list`, but mostly because of universe equality requirements in `traverse` -/ open list lemma sequence_mono : ∀(as bs : list (filter α)), forall₂ (≤) as bs → sequence as ≤ sequence bs | [] [] forall₂.nil := le_refl _ | (a::as) (b::bs) (forall₂.cons h hs) := seq_mono (map_mono h) (sequence_mono as bs hs) variables {α' β' γ' : Type u} {f : β' → filter α'} {s : γ' → set α'} lemma mem_traverse_sets : ∀(fs : list β') (us : list γ'), forall₂ (λb c, s c ∈ f b) fs us → traverse s us ∈ traverse f fs | [] [] forall₂.nil := mem_pure_sets.2 $ mem_singleton _ | (f::fs) (u::us) (forall₂.cons h hs) := seq_mem_seq_sets (image_mem_map h) (mem_traverse_sets fs us hs) lemma mem_traverse_sets_iff (fs : list β') (t : set (list α')) : t ∈ traverse f fs ↔ (∃us:list (set α'), forall₂ (λb (s : set α'), s ∈ f b) fs us ∧ sequence us ⊆ t) := begin split, { induction fs generalizing t, case nil { simp only [sequence, mem_pure_sets, imp_self, forall₂_nil_left_iff, exists_eq_left, set.pure_def, singleton_subset_iff, traverse_nil] }, case cons : b fs ih t { assume ht, rcases mem_seq_sets_iff.1 ht with ⟨u, hu, v, hv, ht⟩, rcases mem_map_sets_iff.1 hu with ⟨w, hw, hwu⟩, rcases ih v hv with ⟨us, hus, hu⟩, exact ⟨w :: us, forall₂.cons hw hus, subset.trans (set.seq_mono hwu hu) ht⟩ } }, { rintros ⟨us, hus, hs⟩, exact mem_sets_of_superset (mem_traverse_sets _ _ hus) hs } end end list_traverse /-! ### Limits -/ /-- `tendsto` is the generic "limit of a function" predicate. `tendsto f l₁ l₂` asserts that for every `l₂` neighborhood `a`, the `f`-preimage of `a` is an `l₁` neighborhood. -/ def tendsto (f : α → β) (l₁ : filter α) (l₂ : filter β) := l₁.map f ≤ l₂ lemma tendsto_def {f : α → β} {l₁ : filter α} {l₂ : filter β} : tendsto f l₁ l₂ ↔ ∀ s ∈ l₂, f ⁻¹' s ∈ l₁ := iff.rfl lemma tendsto_iff_eventually {f : α → β} {l₁ : filter α} {l₂ : filter β} : tendsto f l₁ l₂ ↔ ∀ ⦃p : β → Prop⦄, (∀ᶠ y in l₂, p y) → ∀ᶠ x in l₁, p (f x) := iff.rfl lemma tendsto.eventually {f : α → β} {l₁ : filter α} {l₂ : filter β} {p : β → Prop} (hf : tendsto f l₁ l₂) (h : ∀ᶠ y in l₂, p y) : ∀ᶠ x in l₁, p (f x) := hf h lemma tendsto.frequently {f : α → β} {l₁ : filter α} {l₂ : filter β} {p : β → Prop} (hf : tendsto f l₁ l₂) (h : ∃ᶠ x in l₁, p (f x)) : ∃ᶠ y in l₂, p y := mt hf.eventually h @[simp] lemma tendsto_bot {f : α → β} {l : filter β} : tendsto f ⊥ l := by simp [tendsto] @[simp] lemma tendsto_top {f : α → β} {l : filter α} : tendsto f l ⊤ := le_top lemma tendsto_of_not_nonempty {f : α → β} {la : filter α} {lb : filter β} (h : ¬nonempty α) : tendsto f la lb := by simp only [filter_eq_bot_of_not_nonempty la h, tendsto_bot] lemma eventually_eq_of_left_inv_of_right_inv {f : α → β} {g₁ g₂ : β → α} {fa : filter α} {fb : filter β} (hleft : ∀ᶠ x in fa, g₁ (f x) = x) (hright : ∀ᶠ y in fb, f (g₂ y) = y) (htendsto : tendsto g₂ fb fa) : g₁ =ᶠ[fb] g₂ := (htendsto.eventually hleft).mp $ hright.mono $ λ y hr hl, (congr_arg g₁ hr.symm).trans hl lemma tendsto_iff_comap {f : α → β} {l₁ : filter α} {l₂ : filter β} : tendsto f l₁ l₂ ↔ l₁ ≤ l₂.comap f := map_le_iff_le_comap alias tendsto_iff_comap ↔ filter.tendsto.le_comap _ lemma tendsto_congr' {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (hl : f₁ =ᶠ[l₁] f₂) : tendsto f₁ l₁ l₂ ↔ tendsto f₂ l₁ l₂ := by rw [tendsto, tendsto, map_congr hl] lemma tendsto.congr' {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (hl : f₁ =ᶠ[l₁] f₂) (h : tendsto f₁ l₁ l₂) : tendsto f₂ l₁ l₂ := (tendsto_congr' hl).1 h theorem tendsto_congr {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (h : ∀ x, f₁ x = f₂ x) : tendsto f₁ l₁ l₂ ↔ tendsto f₂ l₁ l₂ := tendsto_congr' (univ_mem_sets' h) theorem tendsto.congr {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (h : ∀ x, f₁ x = f₂ x) : tendsto f₁ l₁ l₂ → tendsto f₂ l₁ l₂ := (tendsto_congr h).1 lemma tendsto_id' {x y : filter α} : x ≤ y → tendsto id x y := by simp only [tendsto, map_id, forall_true_iff] {contextual := tt} lemma tendsto_id {x : filter α} : tendsto id x x := tendsto_id' $ le_refl x lemma tendsto.comp {f : α → β} {g : β → γ} {x : filter α} {y : filter β} {z : filter γ} (hg : tendsto g y z) (hf : tendsto f x y) : tendsto (g ∘ f) x z := calc map (g ∘ f) x = map g (map f x) : by rw [map_map] ... ≤ map g y : map_mono hf ... ≤ z : hg lemma tendsto.mono_left {f : α → β} {x y : filter α} {z : filter β} (hx : tendsto f x z) (h : y ≤ x) : tendsto f y z := le_trans (map_mono h) hx lemma tendsto.mono_right {f : α → β} {x : filter α} {y z : filter β} (hy : tendsto f x y) (hz : y ≤ z) : tendsto f x z := le_trans hy hz lemma tendsto.ne_bot {f : α → β} {x : filter α} {y : filter β} (h : tendsto f x y) [hx : ne_bot x] : ne_bot y := (hx.map _).mono h lemma tendsto_map {f : α → β} {x : filter α} : tendsto f x (map f x) := le_refl (map f x) lemma tendsto_map' {f : β → γ} {g : α → β} {x : filter α} {y : filter γ} (h : tendsto (f ∘ g) x y) : tendsto f (map g x) y := by rwa [tendsto, map_map] lemma tendsto_map'_iff {f : β → γ} {g : α → β} {x : filter α} {y : filter γ} : tendsto f (map g x) y ↔ tendsto (f ∘ g) x y := by rw [tendsto, map_map]; refl lemma tendsto_comap {f : α → β} {x : filter β} : tendsto f (comap f x) x := map_comap_le lemma tendsto_comap_iff {f : α → β} {g : β → γ} {a : filter α} {c : filter γ} : tendsto f a (c.comap g) ↔ tendsto (g ∘ f) a c := ⟨assume h, tendsto_comap.comp h, assume h, map_le_iff_le_comap.mp $ by rwa [map_map]⟩ lemma tendsto_comap'_iff {m : α → β} {f : filter α} {g : filter β} {i : γ → α} (h : range i ∈ f) : tendsto (m ∘ i) (comap i f) g ↔ tendsto m f g := by rw [tendsto, ← map_compose]; simp only [(∘), map_comap h, tendsto] lemma comap_eq_of_inverse {f : filter α} {g : filter β} {φ : α → β} (ψ : β → α) (eq : ψ ∘ φ = id) (hφ : tendsto φ f g) (hψ : tendsto ψ g f) : comap φ g = f := begin refine le_antisymm (le_trans (comap_mono $ map_le_iff_le_comap.1 hψ) _) (map_le_iff_le_comap.1 hφ), rw [comap_comap, eq, comap_id], exact le_refl _ end lemma map_eq_of_inverse {f : filter α} {g : filter β} {φ : α → β} (ψ : β → α) (eq : φ ∘ ψ = id) (hφ : tendsto φ f g) (hψ : tendsto ψ g f) : map φ f = g := begin refine le_antisymm hφ (le_trans _ (map_mono hψ)), rw [map_map, eq, map_id], exact le_refl _ end lemma tendsto_inf {f : α → β} {x : filter α} {y₁ y₂ : filter β} : tendsto f x (y₁ ⊓ y₂) ↔ tendsto f x y₁ ∧ tendsto f x y₂ := by simp only [tendsto, le_inf_iff, iff_self] lemma tendsto_inf_left {f : α → β} {x₁ x₂ : filter α} {y : filter β} (h : tendsto f x₁ y) : tendsto f (x₁ ⊓ x₂) y := le_trans (map_mono inf_le_left) h lemma tendsto_inf_right {f : α → β} {x₁ x₂ : filter α} {y : filter β} (h : tendsto f x₂ y) : tendsto f (x₁ ⊓ x₂) y := le_trans (map_mono inf_le_right) h lemma tendsto.inf {f : α → β} {x₁ x₂ : filter α} {y₁ y₂ : filter β} (h₁ : tendsto f x₁ y₁) (h₂ : tendsto f x₂ y₂) : tendsto f (x₁ ⊓ x₂) (y₁ ⊓ y₂) := tendsto_inf.2 ⟨tendsto_inf_left h₁, tendsto_inf_right h₂⟩ @[simp] lemma tendsto_infi {f : α → β} {x : filter α} {y : ι → filter β} : tendsto f x (⨅i, y i) ↔ ∀i, tendsto f x (y i) := by simp only [tendsto, iff_self, le_infi_iff] lemma tendsto_infi' {f : α → β} {x : ι → filter α} {y : filter β} (i : ι) (hi : tendsto f (x i) y) : tendsto f (⨅i, x i) y := hi.mono_left $ infi_le _ _ lemma tendsto_sup {f : α → β} {x₁ x₂ : filter α} {y : filter β} : tendsto f (x₁ ⊔ x₂) y ↔ tendsto f x₁ y ∧ tendsto f x₂ y := by simp only [tendsto, map_sup, sup_le_iff] lemma tendsto.sup {f : α → β} {x₁ x₂ : filter α} {y : filter β} : tendsto f x₁ y → tendsto f x₂ y → tendsto f (x₁ ⊔ x₂) y := λ h₁ h₂, tendsto_sup.mpr ⟨ h₁, h₂ ⟩ @[simp] lemma tendsto_principal {f : α → β} {l : filter α} {s : set β} : tendsto f l (𝓟 s) ↔ ∀ᶠ a in l, f a ∈ s := by simp only [tendsto, le_principal_iff, mem_map, filter.eventually] @[simp] lemma tendsto_principal_principal {f : α → β} {s : set α} {t : set β} : tendsto f (𝓟 s) (𝓟 t) ↔ ∀a∈s, f a ∈ t := by simp only [tendsto_principal, eventually_principal] @[simp] lemma tendsto_pure {f : α → β} {a : filter α} {b : β} : tendsto f a (pure b) ↔ ∀ᶠ x in a, f x = b := by simp only [tendsto, le_pure_iff, mem_map, mem_singleton_iff, filter.eventually] lemma tendsto_pure_pure (f : α → β) (a : α) : tendsto f (pure a) (pure (f a)) := tendsto_pure.2 rfl lemma tendsto_const_pure {a : filter α} {b : β} : tendsto (λx, b) a (pure b) := tendsto_pure.2 $ univ_mem_sets' $ λ _, rfl lemma pure_le_iff {a : α} {l : filter α} : pure a ≤ l ↔ ∀ s ∈ l, a ∈ s := iff.rfl lemma tendsto_pure_left {f : α → β} {a : α} {l : filter β} : tendsto f (pure a) l ↔ ∀ s ∈ l, f a ∈ s := iff.rfl /-- If two filters are disjoint, then a function cannot tend to both of them along a non-trivial filter. -/ lemma tendsto.not_tendsto {f : α → β} {a : filter α} {b₁ b₂ : filter β} (hf : tendsto f a b₁) [ne_bot a] (hb : disjoint b₁ b₂) : ¬ tendsto f a b₂ := λ hf', (tendsto_inf.2 ⟨hf, hf'⟩).ne_bot hb.eq_bot lemma tendsto_if {l₁ : filter α} {l₂ : filter β} {f g : α → β} {p : α → Prop} [decidable_pred p] (h₀ : tendsto f (l₁ ⊓ 𝓟 p) l₂) (h₁ : tendsto g (l₁ ⊓ 𝓟 { x | ¬ p x }) l₂) : tendsto (λ x, if p x then f x else g x) l₁ l₂ := begin revert h₀ h₁, simp only [tendsto_def, mem_inf_principal], intros h₀ h₁ s hs, apply mem_sets_of_superset (inter_mem_sets (h₀ s hs) (h₁ s hs)), rintros x ⟨hp₀, hp₁⟩, simp only [mem_preimage], by_cases h : p x, { rw if_pos h, exact hp₀ h }, rw if_neg h, exact hp₁ h end /-! ### Products of filters -/ section prod variables {s : set α} {t : set β} {f : filter α} {g : filter β} /- The product filter cannot be defined using the monad structure on filters. For example: F := do {x ← seq, y ← top, return (x, y)} hence: s ∈ F ↔ ∃n, [n..∞] × univ ⊆ s G := do {y ← top, x ← seq, return (x, y)} hence: s ∈ G ↔ ∀i:ℕ, ∃n, [n..∞] × {i} ⊆ s Now ⋃i, [i..∞] × {i} is in G but not in F. As product filter we want to have F as result. -/ /-- Product of filters. This is the filter generated by cartesian products of elements of the component filters. -/ protected def prod (f : filter α) (g : filter β) : filter (α × β) := f.comap prod.fst ⊓ g.comap prod.snd localized "infix ` ×ᶠ `:60 := filter.prod" in filter lemma prod_mem_prod {s : set α} {t : set β} {f : filter α} {g : filter β} (hs : s ∈ f) (ht : t ∈ g) : set.prod s t ∈ f ×ᶠ g := inter_mem_inf_sets (preimage_mem_comap hs) (preimage_mem_comap ht) lemma mem_prod_iff {s : set (α×β)} {f : filter α} {g : filter β} : s ∈ f ×ᶠ g ↔ (∃ t₁ ∈ f, ∃ t₂ ∈ g, set.prod t₁ t₂ ⊆ s) := begin simp only [filter.prod], split, exact assume ⟨t₁, ⟨s₁, hs₁, hts₁⟩, t₂, ⟨s₂, hs₂, hts₂⟩, h⟩, ⟨s₁, hs₁, s₂, hs₂, subset.trans (inter_subset_inter hts₁ hts₂) h⟩, exact assume ⟨t₁, ht₁, t₂, ht₂, h⟩, ⟨prod.fst ⁻¹' t₁, ⟨t₁, ht₁, subset.refl _⟩, prod.snd ⁻¹' t₂, ⟨t₂, ht₂, subset.refl _⟩, h⟩ end lemma comap_prod (f : α → β × γ) (b : filter β) (c : filter γ) : comap f (b ×ᶠ c) = (comap (prod.fst ∘ f) b) ⊓ (comap (prod.snd ∘ f) c) := by erw [comap_inf, filter.comap_comap, filter.comap_comap] lemma eventually_prod_iff {p : α × β → Prop} {f : filter α} {g : filter β} : (∀ᶠ x in f ×ᶠ g, p x) ↔ ∃ (pa : α → Prop) (ha : ∀ᶠ x in f, pa x) (pb : β → Prop) (hb : ∀ᶠ y in g, pb y), ∀ {x}, pa x → ∀ {y}, pb y → p (x, y) := by simpa only [set.prod_subset_iff] using @mem_prod_iff α β p f g lemma tendsto_fst {f : filter α} {g : filter β} : tendsto prod.fst (f ×ᶠ g) f := tendsto_inf_left tendsto_comap lemma tendsto_snd {f : filter α} {g : filter β} : tendsto prod.snd (f ×ᶠ g) g := tendsto_inf_right tendsto_comap lemma tendsto.prod_mk {f : filter α} {g : filter β} {h : filter γ} {m₁ : α → β} {m₂ : α → γ} (h₁ : tendsto m₁ f g) (h₂ : tendsto m₂ f h) : tendsto (λx, (m₁ x, m₂ x)) f (g ×ᶠ h) := tendsto_inf.2 ⟨tendsto_comap_iff.2 h₁, tendsto_comap_iff.2 h₂⟩ lemma eventually.prod_inl {la : filter α} {p : α → Prop} (h : ∀ᶠ x in la, p x) (lb : filter β) : ∀ᶠ x in la ×ᶠ lb, p (x : α × β).1 := tendsto_fst.eventually h lemma eventually.prod_inr {lb : filter β} {p : β → Prop} (h : ∀ᶠ x in lb, p x) (la : filter α) : ∀ᶠ x in la ×ᶠ lb, p (x : α × β).2 := tendsto_snd.eventually h lemma eventually.prod_mk {la : filter α} {pa : α → Prop} (ha : ∀ᶠ x in la, pa x) {lb : filter β} {pb : β → Prop} (hb : ∀ᶠ y in lb, pb y) : ∀ᶠ p in la ×ᶠ lb, pa (p : α × β).1 ∧ pb p.2 := (ha.prod_inl lb).and (hb.prod_inr la) lemma eventually.curry {la : filter α} {lb : filter β} {p : α × β → Prop} (h : ∀ᶠ x in la ×ᶠ lb, p x) : ∀ᶠ x in la, ∀ᶠ y in lb, p (x, y) := begin rcases eventually_prod_iff.1 h with ⟨pa, ha, pb, hb, h⟩, exact ha.mono (λ a ha, hb.mono $ λ b hb, h ha hb) end lemma prod_infi_left [nonempty ι] {f : ι → filter α} {g : filter β}: (⨅i, f i) ×ᶠ g = (⨅i, (f i) ×ᶠ g) := by rw [filter.prod, comap_infi, infi_inf]; simp only [filter.prod, eq_self_iff_true] lemma prod_infi_right [nonempty ι] {f : filter α} {g : ι → filter β} : f ×ᶠ (⨅i, g i) = (⨅i, f ×ᶠ (g i)) := by rw [filter.prod, comap_infi, inf_infi]; simp only [filter.prod, eq_self_iff_true] @[mono] lemma prod_mono {f₁ f₂ : filter α} {g₁ g₂ : filter β} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁ ×ᶠ g₁ ≤ f₂ ×ᶠ g₂ := inf_le_inf (comap_mono hf) (comap_mono hg) lemma prod_comap_comap_eq {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x} {f₁ : filter α₁} {f₂ : filter α₂} {m₁ : β₁ → α₁} {m₂ : β₂ → α₂} : (comap m₁ f₁) ×ᶠ (comap m₂ f₂) = comap (λp:β₁×β₂, (m₁ p.1, m₂ p.2)) (f₁ ×ᶠ f₂) := by simp only [filter.prod, comap_comap, eq_self_iff_true, comap_inf] lemma prod_comm' : f ×ᶠ g = comap (prod.swap) (g ×ᶠ f) := by simp only [filter.prod, comap_comap, (∘), inf_comm, prod.fst_swap, eq_self_iff_true, prod.snd_swap, comap_inf] lemma prod_comm : f ×ᶠ g = map (λp:β×α, (p.2, p.1)) (g ×ᶠ f) := by rw [prod_comm', ← map_swap_eq_comap_swap]; refl lemma prod_map_map_eq {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x} {f₁ : filter α₁} {f₂ : filter α₂} {m₁ : α₁ → β₁} {m₂ : α₂ → β₂} : (map m₁ f₁) ×ᶠ (map m₂ f₂) = map (λp:α₁×α₂, (m₁ p.1, m₂ p.2)) (f₁ ×ᶠ f₂) := le_antisymm (assume s hs, let ⟨s₁, hs₁, s₂, hs₂, h⟩ := mem_prod_iff.mp hs in filter.sets_of_superset _ (prod_mem_prod (image_mem_map hs₁) (image_mem_map hs₂)) $ calc set.prod (m₁ '' s₁) (m₂ '' s₂) = (λp:α₁×α₂, (m₁ p.1, m₂ p.2)) '' set.prod s₁ s₂ : set.prod_image_image_eq ... ⊆ _ : by rwa [image_subset_iff]) ((tendsto.comp (le_refl _) tendsto_fst).prod_mk (tendsto.comp (le_refl _) tendsto_snd)) lemma prod_map_map_eq' {α₁ : Type*} {α₂ : Type*} {β₁ : Type*} {β₂ : Type*} (f : α₁ → α₂) (g : β₁ → β₂) (F : filter α₁) (G : filter β₁) : (map f F) ×ᶠ (map g G) = map (prod.map f g) (F ×ᶠ G) := by { rw filter.prod_map_map_eq, refl } lemma tendsto.prod_map {δ : Type*} {f : α → γ} {g : β → δ} {a : filter α} {b : filter β} {c : filter γ} {d : filter δ} (hf : tendsto f a c) (hg : tendsto g b d) : tendsto (prod.map f g) (a ×ᶠ b) (c ×ᶠ d) := begin erw [tendsto, ← prod_map_map_eq], exact filter.prod_mono hf hg, end lemma map_prod (m : α × β → γ) (f : filter α) (g : filter β) : map m (f ×ᶠ g) = (f.map (λa b, m (a, b))).seq g := begin simp [filter.ext_iff, mem_prod_iff, mem_map_seq_iff], assume s, split, exact assume ⟨t, ht, s, hs, h⟩, ⟨s, hs, t, ht, assume x hx y hy, @h ⟨x, y⟩ ⟨hx, hy⟩⟩, exact assume ⟨s, hs, t, ht, h⟩, ⟨t, ht, s, hs, assume ⟨x, y⟩ ⟨hx, hy⟩, h x hx y hy⟩ end lemma prod_eq {f : filter α} {g : filter β} : f ×ᶠ g = (f.map prod.mk).seq g := have h : _ := map_prod id f g, by rwa [map_id] at h lemma prod_inf_prod {f₁ f₂ : filter α} {g₁ g₂ : filter β} : (f₁ ×ᶠ g₁) ⊓ (f₂ ×ᶠ g₂) = (f₁ ⊓ f₂) ×ᶠ (g₁ ⊓ g₂) := by simp only [filter.prod, comap_inf, inf_comm, inf_assoc, inf_left_comm] @[simp] lemma prod_bot {f : filter α} : f ×ᶠ (⊥ : filter β) = ⊥ := by simp [filter.prod] @[simp] lemma bot_prod {g : filter β} : (⊥ : filter α) ×ᶠ g = ⊥ := by simp [filter.prod] @[simp] lemma prod_principal_principal {s : set α} {t : set β} : (𝓟 s) ×ᶠ (𝓟 t) = 𝓟 (set.prod s t) := by simp only [filter.prod, comap_principal, principal_eq_iff_eq, comap_principal, inf_principal]; refl @[simp] lemma pure_prod {a : α} {f : filter β} : pure a ×ᶠ f = map (prod.mk a) f := by rw [prod_eq, map_pure, pure_seq_eq_map] @[simp] lemma prod_pure {f : filter α} {b : β} : f ×ᶠ pure b = map (λ a, (a, b)) f := by rw [prod_eq, seq_pure, map_map] lemma prod_pure_pure {a : α} {b : β} : (pure a) ×ᶠ (pure b) = pure (a, b) := by simp lemma prod_eq_bot {f : filter α} {g : filter β} : f ×ᶠ g = ⊥ ↔ (f = ⊥ ∨ g = ⊥) := begin split, { assume h, rcases mem_prod_iff.1 (empty_in_sets_eq_bot.2 h) with ⟨s, hs, t, ht, hst⟩, rw [subset_empty_iff, set.prod_eq_empty_iff] at hst, cases hst with s_eq t_eq, { left, exact empty_in_sets_eq_bot.1 (s_eq ▸ hs) }, { right, exact empty_in_sets_eq_bot.1 (t_eq ▸ ht) } }, { rintros (rfl | rfl), exact bot_prod, exact prod_bot } end lemma prod_ne_bot {f : filter α} {g : filter β} : ne_bot (f ×ᶠ g) ↔ (ne_bot f ∧ ne_bot g) := (not_congr prod_eq_bot).trans not_or_distrib lemma ne_bot.prod {f : filter α} {g : filter β} (hf : ne_bot f) (hg : ne_bot g) : ne_bot (f ×ᶠ g) := prod_ne_bot.2 ⟨hf, hg⟩ instance prod_ne_bot' {f : filter α} {g : filter β} [hf : ne_bot f] [hg : ne_bot g] : ne_bot (f ×ᶠ g) := hf.prod hg lemma tendsto_prod_iff {f : α × β → γ} {x : filter α} {y : filter β} {z : filter γ} : filter.tendsto f (x ×ᶠ y) z ↔ ∀ W ∈ z, ∃ U ∈ x, ∃ V ∈ y, ∀ x y, x ∈ U → y ∈ V → f (x, y) ∈ W := by simp only [tendsto_def, mem_prod_iff, prod_sub_preimage_iff, exists_prop, iff_self] end prod end filter open_locale filter lemma set.eq_on.eventually_eq {α β} {s : set α} {f g : α → β} (h : eq_on f g s) : f =ᶠ[𝓟 s] g := h lemma set.eq_on.eventually_eq_of_mem {α β} {s : set α} {l : filter α} {f g : α → β} (h : eq_on f g s) (hl : s ∈ l) : f =ᶠ[l] g := h.eventually_eq.filter_mono $ filter.le_principal_iff.2 hl
0dca95ca536396e82e12fd9ee72d30fa888f2e83
3c9dc4ea6cc92e02634ef557110bde9eae393338
/stage0/src/Lean/Environment.lean
8dfd9dbec907d6f1134cb7e87c08619f3d3c3bf9
[ "Apache-2.0" ]
permissive
shingtaklam1324/lean4
3d7efe0c8743a4e33d3c6f4adbe1300df2e71492
351285a2e8ad0cef37af05851cfabf31edfb5970
refs/heads/master
1,676,827,679,740
1,610,462,623,000
1,610,552,340,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
30,210
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Std.Data.HashMap import Lean.Data.SMap import Lean.Declaration import Lean.LocalContext import Lean.Util.Path import Lean.Util.FindExpr import Lean.Util.Profile namespace Lean /- Opaque environment extension state. -/ constant EnvExtensionStateSpec : PointedType.{0} def EnvExtensionState : Type := EnvExtensionStateSpec.type instance : Inhabited EnvExtensionState where default := EnvExtensionStateSpec.val def ModuleIdx := Nat instance : Inhabited ModuleIdx := inferInstanceAs (Inhabited Nat) abbrev ConstMap := SMap Name ConstantInfo structure Import where module : Name runtimeOnly : Bool := false instance : ToString Import := ⟨fun imp => toString imp.module ++ if imp.runtimeOnly then " (runtime)" else ""⟩ /-- A compacted region holds multiple Lean objects in a contiguous memory region, which can be read/written to/from disk. Objects inside the region do not have reference counters and cannot be freed individually. The contents of .olean files are compacted regions. -/ def CompactedRegion := USize /-- Free a compacted region and its contents. No live references to the contents may exist at the time of invocation. -/ @[extern 2 "lean_compacted_region_free"] unsafe constant CompactedRegion.free : CompactedRegion → IO Unit /- Environment fields that are not used often. -/ structure EnvironmentHeader where trustLevel : UInt32 := 0 quotInit : Bool := false mainModule : Name := arbitrary imports : Array Import := #[] -- direct imports regions : Array CompactedRegion := #[] -- compacted regions of all imported modules moduleNames : Array Name := #[] -- names of all imported modules deriving Inhabited open Std (HashMap) structure Environment where const2ModIdx : HashMap Name ModuleIdx constants : ConstMap extensions : Array EnvExtensionState header : EnvironmentHeader := {} deriving Inhabited namespace Environment def addAux (env : Environment) (cinfo : ConstantInfo) : Environment := { env with constants := env.constants.insert cinfo.name cinfo } @[export lean_environment_find] def find? (env : Environment) (n : Name) : Option ConstantInfo := /- It is safe to use `find'` because we never overwrite imported declarations. -/ env.constants.find?' n def contains (env : Environment) (n : Name) : Bool := env.constants.contains n def imports (env : Environment) : Array Import := env.header.imports def allImportedModuleNames (env : Environment) : Array Name := env.header.moduleNames @[export lean_environment_set_main_module] def setMainModule (env : Environment) (m : Name) : Environment := { env with header := { env.header with mainModule := m } } @[export lean_environment_main_module] def mainModule (env : Environment) : Name := env.header.mainModule @[export lean_environment_mark_quot_init] private def markQuotInit (env : Environment) : Environment := { env with header := { env.header with quotInit := true } } @[export lean_environment_quot_init] private def isQuotInit (env : Environment) : Bool := env.header.quotInit @[export lean_environment_trust_level] private def getTrustLevel (env : Environment) : UInt32 := env.header.trustLevel def getModuleIdxFor? (env : Environment) (c : Name) : Option ModuleIdx := env.const2ModIdx.find? c def isConstructor (env : Environment) (c : Name) : Bool := match env.find? c with | ConstantInfo.ctorInfo _ => true | _ => false end Environment inductive KernelException where | unknownConstant (env : Environment) (name : Name) | alreadyDeclared (env : Environment) (name : Name) | declTypeMismatch (env : Environment) (decl : Declaration) (givenType : Expr) | declHasMVars (env : Environment) (name : Name) (expr : Expr) | declHasFVars (env : Environment) (name : Name) (expr : Expr) | funExpected (env : Environment) (lctx : LocalContext) (expr : Expr) | typeExpected (env : Environment) (lctx : LocalContext) (expr : Expr) | letTypeMismatch (env : Environment) (lctx : LocalContext) (name : Name) (givenType : Expr) (expectedType : Expr) | exprTypeMismatch (env : Environment) (lctx : LocalContext) (expr : Expr) (expectedType : Expr) | appTypeMismatch (env : Environment) (lctx : LocalContext) (app : Expr) (funType : Expr) (argType : Expr) | invalidProj (env : Environment) (lctx : LocalContext) (proj : Expr) | other (msg : String) namespace Environment /- Type check given declaration and add it to the environment -/ @[extern "lean_add_decl"] constant addDecl (env : Environment) (decl : @& Declaration) : Except KernelException Environment /- Compile the given declaration, it assumes the declaration has already been added to the environment using `addDecl`. -/ @[extern "lean_compile_decl"] constant compileDecl (env : Environment) (opt : @& Options) (decl : @& Declaration) : Except KernelException Environment def addAndCompile (env : Environment) (opt : Options) (decl : Declaration) : Except KernelException Environment := do let env ← addDecl env decl compileDecl env opt decl end Environment /- Interface for managing environment extensions. -/ structure EnvExtensionInterface where ext : Type → Type inhabitedExt {σ} : Inhabited σ → Inhabited (ext σ) registerExt {σ} (mkInitial : IO σ) : IO (ext σ) setState {σ} (e : ext σ) (env : Environment) : σ → Environment modifyState {σ} (e : ext σ) (env : Environment) : (σ → σ) → Environment getState {σ} (e : ext σ) (env : Environment) : σ mkInitialExtStates : IO (Array EnvExtensionState) instance : Inhabited EnvExtensionInterface where default := { ext := id, inhabitedExt := id, registerExt := fun mk => mk, setState := fun _ env _ => env, modifyState := fun _ env _ => env, getState := fun ext _ => ext, mkInitialExtStates := pure #[] } /- Unsafe implementation of `EnvExtensionInterface` -/ namespace EnvExtensionInterfaceUnsafe structure Ext (σ : Type) where idx : Nat mkInitial : IO σ deriving Inhabited private def mkEnvExtensionsRef : IO (IO.Ref (Array (Ext EnvExtensionState))) := IO.mkRef #[] @[builtinInit mkEnvExtensionsRef] private constant envExtensionsRef : IO.Ref (Array (Ext EnvExtensionState)) unsafe def setState {σ} (ext : Ext σ) (env : Environment) (s : σ) : Environment := { env with extensions := env.extensions.set! ext.idx (unsafeCast s) } @[inline] unsafe def modifyState {σ : Type} (ext : Ext σ) (env : Environment) (f : σ → σ) : Environment := { env with extensions := env.extensions.modify ext.idx fun s => let s : σ := unsafeCast s; let s : σ := f s; unsafeCast s } unsafe def getState {σ} (ext : Ext σ) (env : Environment) : σ := let s : EnvExtensionState := env.extensions.get! ext.idx unsafeCast s unsafe def registerExt {σ} (mkInitial : IO σ) : IO (Ext σ) := do let initializing ← IO.initializing unless initializing do throw (IO.userError "failed to register environment, extensions can only be registered during initialization") let exts ← envExtensionsRef.get let idx := exts.size let ext : Ext σ := { idx := idx, mkInitial := mkInitial, } envExtensionsRef.modify fun exts => exts.push (unsafeCast ext) pure ext def mkInitialExtStates : IO (Array EnvExtensionState) := do let exts ← envExtensionsRef.get exts.mapM fun ext => ext.mkInitial unsafe def imp : EnvExtensionInterface := { ext := Ext, inhabitedExt := fun _ => ⟨arbitrary⟩, registerExt := registerExt, setState := setState, modifyState := modifyState, getState := getState, mkInitialExtStates := mkInitialExtStates } end EnvExtensionInterfaceUnsafe @[implementedBy EnvExtensionInterfaceUnsafe.imp] constant EnvExtensionInterfaceImp : EnvExtensionInterface def EnvExtension (σ : Type) : Type := EnvExtensionInterfaceImp.ext σ namespace EnvExtension instance {σ} [s : Inhabited σ] : Inhabited (EnvExtension σ) := EnvExtensionInterfaceImp.inhabitedExt s def setState {σ : Type} (ext : EnvExtension σ) (env : Environment) (s : σ) : Environment := EnvExtensionInterfaceImp.setState ext env s def modifyState {σ : Type} (ext : EnvExtension σ) (env : Environment) (f : σ → σ) : Environment := EnvExtensionInterfaceImp.modifyState ext env f def getState {σ : Type} (ext : EnvExtension σ) (env : Environment) : σ := EnvExtensionInterfaceImp.getState ext env end EnvExtension /- Environment extensions can only be registered during initialization. Reasons: 1- Our implementation assumes the number of extensions does not change after an environment object is created. 2- We do not use any synchronization primitive to access `envExtensionsRef`. -/ def registerEnvExtension {σ : Type} (mkInitial : IO σ) : IO (EnvExtension σ) := EnvExtensionInterfaceImp.registerExt mkInitial private def mkInitialExtensionStates : IO (Array EnvExtensionState) := EnvExtensionInterfaceImp.mkInitialExtStates @[export lean_mk_empty_environment] def mkEmptyEnvironment (trustLevel : UInt32 := 0) : IO Environment := do let initializing ← IO.initializing if initializing then throw (IO.userError "environment objects cannot be created during initialization") let exts ← mkInitialExtensionStates pure { const2ModIdx := {}, constants := {}, header := { trustLevel := trustLevel }, extensions := exts } structure PersistentEnvExtensionState (α : Type) (σ : Type) where importedEntries : Array (Array α) -- entries per imported module state : σ structure ImportM.Context where env : Environment opts : Options abbrev ImportM := ReaderT Lean.ImportM.Context IO /- An environment extension with support for storing/retrieving entries from a .olean file. - α is the type of the entries that are stored in .olean files. - β is the type of values used to update the state. - σ is the actual state. Remark: for most extensions α and β coincide. Note that `addEntryFn` is not in `IO`. This is intentional, and allows us to write simple functions such as ``` def addAlias (env : Environment) (a : Name) (e : Name) : Environment := aliasExtension.addEntry env (a, e) ``` without using `IO`. We have many functions like `addAlias`. `α` and ‵β` do not coincide for extensions where the data used to update the state contains, for example, closures which we currently cannot store in files. -/ structure PersistentEnvExtension (α : Type) (β : Type) (σ : Type) where toEnvExtension : EnvExtension (PersistentEnvExtensionState α σ) name : Name addImportedFn : Array (Array α) → ImportM σ addEntryFn : σ → β → σ exportEntriesFn : σ → Array α statsFn : σ → Format /- Opaque persistent environment extension entry. -/ constant EnvExtensionEntrySpec : PointedType.{0} def EnvExtensionEntry : Type := EnvExtensionEntrySpec.type instance : Inhabited EnvExtensionEntry := ⟨EnvExtensionEntrySpec.val⟩ instance {α σ} [Inhabited σ] : Inhabited (PersistentEnvExtensionState α σ) := ⟨{importedEntries := #[], state := arbitrary }⟩ instance {α β σ} [Inhabited σ] : Inhabited (PersistentEnvExtension α β σ) where default := { toEnvExtension := arbitrary, name := arbitrary, addImportedFn := fun _ => arbitrary, addEntryFn := fun s _ => s, exportEntriesFn := fun _ => #[], statsFn := fun _ => Format.nil } namespace PersistentEnvExtension def getModuleEntries {α β σ : Type} (ext : PersistentEnvExtension α β σ) (env : Environment) (m : ModuleIdx) : Array α := (ext.toEnvExtension.getState env).importedEntries.get! m def addEntry {α β σ : Type} (ext : PersistentEnvExtension α β σ) (env : Environment) (b : β) : Environment := ext.toEnvExtension.modifyState env fun s => let state := ext.addEntryFn s.state b; { s with state := state } def getState {α β σ : Type} (ext : PersistentEnvExtension α β σ) (env : Environment) : σ := (ext.toEnvExtension.getState env).state def setState {α β σ : Type} (ext : PersistentEnvExtension α β σ) (env : Environment) (s : σ) : Environment := ext.toEnvExtension.modifyState env $ fun ps => { ps with state := s } def modifyState {α β σ : Type} (ext : PersistentEnvExtension α β σ) (env : Environment) (f : σ → σ) : Environment := ext.toEnvExtension.modifyState env $ fun ps => { ps with state := f (ps.state) } end PersistentEnvExtension builtin_initialize persistentEnvExtensionsRef : IO.Ref (Array (PersistentEnvExtension EnvExtensionEntry EnvExtensionEntry EnvExtensionState)) ← IO.mkRef #[] structure PersistentEnvExtensionDescr (α β σ : Type) where name : Name mkInitial : IO σ addImportedFn : Array (Array α) → ImportM σ addEntryFn : σ → β → σ exportEntriesFn : σ → Array α statsFn : σ → Format := fun _ => Format.nil unsafe def registerPersistentEnvExtensionUnsafe {α β σ : Type} [Inhabited σ] (descr : PersistentEnvExtensionDescr α β σ) : IO (PersistentEnvExtension α β σ) := do let pExts ← persistentEnvExtensionsRef.get if pExts.any (fun ext => ext.name == descr.name) then throw (IO.userError s!"invalid environment extension, '{descr.name}' has already been used") let ext ← registerEnvExtension do let initial ← descr.mkInitial let s : PersistentEnvExtensionState α σ := { importedEntries := #[], state := initial } pure s let pExt : PersistentEnvExtension α β σ := { toEnvExtension := ext, name := descr.name, addImportedFn := descr.addImportedFn, addEntryFn := descr.addEntryFn, exportEntriesFn := descr.exportEntriesFn, statsFn := descr.statsFn } persistentEnvExtensionsRef.modify fun pExts => pExts.push (unsafeCast pExt) return pExt @[implementedBy registerPersistentEnvExtensionUnsafe] constant registerPersistentEnvExtension {α β σ : Type} [Inhabited σ] (descr : PersistentEnvExtensionDescr α β σ) : IO (PersistentEnvExtension α β σ) /- Simple PersistentEnvExtension that implements exportEntriesFn using a list of entries. -/ def SimplePersistentEnvExtension (α σ : Type) := PersistentEnvExtension α α (List α × σ) @[specialize] def mkStateFromImportedEntries {α σ : Type} (addEntryFn : σ → α → σ) (initState : σ) (as : Array (Array α)) : σ := as.foldl (fun r es => es.foldl (fun r e => addEntryFn r e) r) initState structure SimplePersistentEnvExtensionDescr (α σ : Type) where name : Name addEntryFn : σ → α → σ addImportedFn : Array (Array α) → σ toArrayFn : List α → Array α := fun es => es.toArray def registerSimplePersistentEnvExtension {α σ : Type} [Inhabited σ] (descr : SimplePersistentEnvExtensionDescr α σ) : IO (SimplePersistentEnvExtension α σ) := registerPersistentEnvExtension { name := descr.name, mkInitial := pure ([], descr.addImportedFn #[]), addImportedFn := fun as => pure ([], descr.addImportedFn as), addEntryFn := fun s e => match s with | (entries, s) => (e::entries, descr.addEntryFn s e), exportEntriesFn := fun s => descr.toArrayFn s.1.reverse, statsFn := fun s => format "number of local entries: " ++ format s.1.length } namespace SimplePersistentEnvExtension instance {α σ : Type} [Inhabited σ] : Inhabited (SimplePersistentEnvExtension α σ) := inferInstanceAs (Inhabited (PersistentEnvExtension α α (List α × σ))) def getEntries {α σ : Type} (ext : SimplePersistentEnvExtension α σ) (env : Environment) : List α := (PersistentEnvExtension.getState ext env).1 def getState {α σ : Type} (ext : SimplePersistentEnvExtension α σ) (env : Environment) : σ := (PersistentEnvExtension.getState ext env).2 def setState {α σ : Type} (ext : SimplePersistentEnvExtension α σ) (env : Environment) (s : σ) : Environment := PersistentEnvExtension.modifyState ext env (fun ⟨entries, _⟩ => (entries, s)) def modifyState {α σ : Type} (ext : SimplePersistentEnvExtension α σ) (env : Environment) (f : σ → σ) : Environment := PersistentEnvExtension.modifyState ext env (fun ⟨entries, s⟩ => (entries, f s)) end SimplePersistentEnvExtension /-- Environment extension for tagging declarations. Declarations must only be tagged in the module where they were declared. -/ def TagDeclarationExtension := SimplePersistentEnvExtension Name NameSet def mkTagDeclarationExtension (name : Name) : IO TagDeclarationExtension := registerSimplePersistentEnvExtension { name := name, addImportedFn := fun as => {}, addEntryFn := fun s n => s.insert n, toArrayFn := fun es => es.toArray.qsort Name.quickLt } namespace TagDeclarationExtension instance : Inhabited TagDeclarationExtension := inferInstanceAs (Inhabited (SimplePersistentEnvExtension Name NameSet)) def tag (ext : TagDeclarationExtension) (env : Environment) (n : Name) : Environment := ext.addEntry env n def isTagged (ext : TagDeclarationExtension) (env : Environment) (n : Name) : Bool := match env.getModuleIdxFor? n with | some modIdx => (ext.getModuleEntries env modIdx).binSearchContains n Name.quickLt | none => (ext.getState env).contains n end TagDeclarationExtension /-- Environment extension for mapping declarations to values. -/ def MapDeclarationExtension (α : Type) := SimplePersistentEnvExtension (Name × α) (NameMap α) def mkMapDeclarationExtension [Inhabited α] (name : Name) : IO (MapDeclarationExtension α) := registerSimplePersistentEnvExtension { name := name, addImportedFn := fun as => {}, addEntryFn := fun s n => s.insert n.1 n.2 , toArrayFn := fun es => es.toArray.qsort (fun a b => Name.quickLt a.1 b.1) } namespace MapDeclarationExtension instance : Inhabited (MapDeclarationExtension α) := inferInstanceAs (Inhabited (SimplePersistentEnvExtension ..)) def insert (ext : MapDeclarationExtension α) (env : Environment) (declName : Name) (val : α) : Environment := ext.addEntry env (declName, val) def find? [Inhabited α] (ext : MapDeclarationExtension α) (env : Environment) (declName : Name) : Option α := match env.getModuleIdxFor? declName with | some modIdx => match (ext.getModuleEntries env modIdx).binSearch (declName, arbitrary) (fun a b => Name.quickLt a.1 b.1) with | some e => some e.2 | none => none | none => (ext.getState env).find? declName def contains [Inhabited α] (ext : MapDeclarationExtension α) (env : Environment) (declName : Name) : Bool := match env.getModuleIdxFor? declName with | some modIdx => (ext.getModuleEntries env modIdx).binSearchContains (declName, arbitrary) (fun a b => Name.quickLt a.1 b.1) | none => (ext.getState env).contains declName end MapDeclarationExtension /- Content of a .olean file. We use `compact.cpp` to generate the image of this object in disk. -/ structure ModuleData where imports : Array Import constants : Array ConstantInfo entries : Array (Name × Array EnvExtensionEntry) instance : Inhabited ModuleData := ⟨{imports := arbitrary, constants := arbitrary, entries := arbitrary }⟩ @[extern 3 "lean_save_module_data"] constant saveModuleData (fname : @& String) (m : ModuleData) : IO Unit @[extern 2 "lean_read_module_data"] constant readModuleData (fname : @& String) : IO (ModuleData × CompactedRegion) /-- Free compacted regions of imports. No live references to imported objects may exist at the time of invocation; in particular, `env` should be the last reference to any `Environment` derived from these imports. -/ @[noinline, export lean_environment_free_regions] unsafe def Environment.freeRegions (env : Environment) : IO Unit := /- NOTE: This assumes `env` is not inferred as a borrowed parameter, and is freed after extracting the `header` field. Otherwise, we would encounter undefined behavior when the constant map in `env`, which may reference objects in compacted regions, is freed after the regions. In the currently produced IR, we indeed see: ``` def Lean.Environment.freeRegions (x_1 : obj) (x_2 : obj) : obj := let x_3 : obj := proj[3] x_1; inc x_3; dec x_1; ... ``` TODO: statically check for this. -/ env.header.regions.forM CompactedRegion.free def mkModuleData (env : Environment) : IO ModuleData := do let pExts ← persistentEnvExtensionsRef.get let entries : Array (Name × Array EnvExtensionEntry) := pExts.size.fold (fun i result => let state := (pExts.get! i).getState env let exportEntriesFn := (pExts.get! i).exportEntriesFn let extName := (pExts.get! i).name result.push (extName, exportEntriesFn state)) #[] pure { imports := env.header.imports, constants := env.constants.foldStage2 (fun cs _ c => cs.push c) #[], entries := entries } @[export lean_write_module] def writeModule (env : Environment) (fname : String) : IO Unit := do let modData ← mkModuleData env; saveModuleData fname modData private partial def getEntriesFor (mod : ModuleData) (extId : Name) (i : Nat) : Array EnvExtensionEntry := if i < mod.entries.size then let curr := mod.entries.get! i; if curr.1 == extId then curr.2 else getEntriesFor mod extId (i+1) else #[] private def setImportedEntries (env : Environment) (mods : Array ModuleData) : IO Environment := do let mut env := env let pExtDescrs ← persistentEnvExtensionsRef.get for mod in mods do for extDescr in pExtDescrs do let entries := getEntriesFor mod extDescr.name 0 env ← extDescr.toEnvExtension.modifyState env fun s => { s with importedEntries := s.importedEntries.push entries } return env private def finalizePersistentExtensions (env : Environment) (opts : Options) : IO Environment := do let mut env := env let pExtDescrs ← persistentEnvExtensionsRef.get for extDescr in pExtDescrs do let s := extDescr.toEnvExtension.getState env let newState ← extDescr.addImportedFn s.importedEntries { env := env, opts := opts } env ← extDescr.toEnvExtension.setState env { s with state := newState } return env structure ImportState where moduleNameSet : NameSet := {} moduleNames : Array Name := #[] moduleData : Array ModuleData := #[] regions : Array CompactedRegion := #[] @[export lean_import_modules] partial def importModules (imports : List Import) (opts : Options) (trustLevel : UInt32 := 0) : IO Environment := profileitIO "import" ⟨0, 0⟩ do let (_, s) ← importMods imports |>.run {} -- (moduleNames, mods, regions) let mut modIdx : Nat := 0 let mut const2ModIdx : HashMap Name ModuleIdx := {} let mut constants : ConstMap := SMap.empty for mod in s.moduleData do for cinfo in mod.constants do const2ModIdx := const2ModIdx.insert cinfo.name modIdx if constants.contains cinfo.name then throw (IO.userError s!"import failed, environment already contains '{cinfo.name}'") constants := constants.insert cinfo.name cinfo modIdx := modIdx + 1 constants := constants.switch let exts ← mkInitialExtensionStates let env : Environment := { const2ModIdx := const2ModIdx, constants := constants, extensions := exts, header := { quotInit := !imports.isEmpty, -- We assume `core.lean` initializes quotient module trustLevel := trustLevel, imports := imports.toArray, regions := s.regions, moduleNames := s.moduleNames } } let env ← setImportedEntries env s.moduleData let env ← finalizePersistentExtensions env opts pure env where importMods : List Import → StateRefT ImportState IO Unit | [] => pure () | i::is => do if i.runtimeOnly || (← get).moduleNameSet.contains i.module then importMods is else do modify fun s => { s with moduleNameSet := s.moduleNameSet.insert i.module } let mFile ← findOLean i.module unless (← IO.fileExists mFile) do throw $ IO.userError s!"object file '{mFile}' of module {i.module} does not exist" let (mod, region) ← readModuleData mFile importMods mod.imports.toList modify fun s => { s with moduleData := s.moduleData.push mod regions := s.regions.push region moduleNames := s.moduleNames.push i.module } importMods is /-- Create environment object from imports and free compacted regions after calling `act`. No live references to the environment object or imported objects may exist after `act` finishes. -/ unsafe def withImportModules {α : Type} (imports : List Import) (opts : Options) (trustLevel : UInt32 := 0) (x : Environment → IO α) : IO α := do let env ← importModules imports opts trustLevel try x env finally env.freeRegions builtin_initialize namespacesExt : SimplePersistentEnvExtension Name NameSet ← registerSimplePersistentEnvExtension { name := `namespaces, addImportedFn := fun as => mkStateFromImportedEntries NameSet.insert {} as, addEntryFn := fun s n => s.insert n } namespace Environment def registerNamespace (env : Environment) (n : Name) : Environment := if (namespacesExt.getState env).contains n then env else namespacesExt.addEntry env n def isNamespace (env : Environment) (n : Name) : Bool := (namespacesExt.getState env).contains n def getNamespaceSet (env : Environment) : NameSet := namespacesExt.getState env private def isNamespaceName : Name → Bool | Name.str Name.anonymous _ _ => true | Name.str p _ _ => isNamespaceName p | _ => false private def registerNamePrefixes : Environment → Name → Environment | env, Name.str p _ _ => if isNamespaceName p then registerNamePrefixes (registerNamespace env p) p else env | env, _ => env @[export lean_environment_add] def add (env : Environment) (cinfo : ConstantInfo) : Environment := let env := registerNamePrefixes env cinfo.name env.addAux cinfo @[export lean_display_stats] def displayStats (env : Environment) : IO Unit := do let pExtDescrs ← persistentEnvExtensionsRef.get let numModules := ((pExtDescrs.get! 0).toEnvExtension.getState env).importedEntries.size; IO.println ("direct imports: " ++ toString env.header.imports); IO.println ("number of imported modules: " ++ toString numModules); IO.println ("number of consts: " ++ toString env.constants.size); IO.println ("number of imported consts: " ++ toString env.constants.stageSizes.1); IO.println ("number of local consts: " ++ toString env.constants.stageSizes.2); IO.println ("number of buckets for imported consts: " ++ toString env.constants.numBuckets); IO.println ("trust level: " ++ toString env.header.trustLevel); IO.println ("number of extensions: " ++ toString env.extensions.size); pExtDescrs.forM $ fun extDescr => do IO.println ("extension '" ++ toString extDescr.name ++ "'") let s := extDescr.toEnvExtension.getState env let fmt := extDescr.statsFn s.state unless fmt.isNil do IO.println (" " ++ toString (Format.nest 2 (extDescr.statsFn s.state))) IO.println (" number of imported entries: " ++ toString (s.importedEntries.foldl (fun sum es => sum + es.size) 0)) @[extern "lean_eval_const"] unsafe constant evalConst (α) (env : @& Environment) (opts : @& Options) (constName : @& Name) : Except String α private def throwUnexpectedType {α} (typeName : Name) (constName : Name) : ExceptT String Id α := throw ("unexpected type at '" ++ toString constName ++ "', `" ++ toString typeName ++ "` expected") /-- Like `evalConst`, but first check that `constName` indeed is a declaration of type `typeName`. This function is still unsafe because it cannot guarantee that `typeName` is in fact the name of the type `α`. -/ unsafe def evalConstCheck (α) (env : Environment) (opts : Options) (typeName : Name) (constName : Name) : ExceptT String Id α := match env.find? constName with | none => throw ("unknow constant '" ++ toString constName ++ "'") | some info => match info.type with | Expr.const c _ _ => if c != typeName then throwUnexpectedType typeName constName else env.evalConst α opts constName | _ => throwUnexpectedType typeName constName def hasUnsafe (env : Environment) (e : Expr) : Bool := let c? := e.find? $ fun e => match e with | Expr.const c _ _ => match env.find? c with | some cinfo => cinfo.isUnsafe | none => false | _ => false; c?.isSome end Environment namespace Kernel /- Kernel API -/ /-- Kernel isDefEq predicate. We use it mainly for debugging purposes. Recall that the Kernel type checker does not support metavariables. When implementing automation, consider using the `MetaM` methods. -/ @[extern "lean_kernel_is_def_eq"] constant isDefEq (env : Environment) (lctx : LocalContext) (a b : Expr) : Bool /-- Kernel WHNF function. We use it mainly for debugging purposes. Recall that the Kernel type checker does not support metavariables. When implementing automation, consider using the `MetaM` methods. -/ @[extern "lean_kernel_whnf"] constant whnf (env : Environment) (lctx : LocalContext) (a : Expr) : Expr end Kernel class MonadEnv (m : Type → Type) where getEnv : m Environment modifyEnv : (Environment → Environment) → m Unit export MonadEnv (getEnv modifyEnv) instance (m n) [MonadEnv m] [MonadLift m n] : MonadEnv n := { getEnv := liftM (getEnv : m Environment), modifyEnv := fun f => liftM (modifyEnv f : m Unit) } end Lean
b0c081dc9bfb22c4953144bbb21eb747c544cd95
b00eb947a9c4141624aa8919e94ce6dcd249ed70
/src/Std/Data/PersistentArray.lean
bbefc522facb42585abdf5df5e1a17c12dfd44a9
[ "Apache-2.0" ]
permissive
gebner/lean4-old
a4129a041af2d4d12afb3a8d4deedabde727719b
ee51cdfaf63ee313c914d83264f91f414a0e3b6e
refs/heads/master
1,683,628,606,745
1,622,651,300,000
1,622,654,405,000
142,608,821
1
0
null
null
null
null
UTF-8
Lean
false
false
13,822
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ universes u v w namespace Std inductive PersistentArrayNode (α : Type u) where | node (cs : Array (PersistentArrayNode α)) : PersistentArrayNode α | leaf (vs : Array α) : PersistentArrayNode α deriving Inhabited namespace PersistentArrayNode def isNode {α} : PersistentArrayNode α → Bool | node _ => true | leaf _ => false end PersistentArrayNode abbrev PersistentArray.initShift : USize := 5 abbrev PersistentArray.branching : USize := USize.ofNat (2 ^ PersistentArray.initShift.toNat) structure PersistentArray (α : Type u) where /- Recall that we run out of memory if we have more than `usizeSz/8` elements. So, we can stop adding elements at `root` after `size > usizeSz`, and keep growing the `tail`. This modification allow us to use `USize` instead of `Nat` when traversing `root`. -/ root : PersistentArrayNode α := PersistentArrayNode.node (Array.mkEmpty PersistentArray.branching.toNat) tail : Array α := Array.mkEmpty PersistentArray.branching.toNat size : Nat := 0 shift : USize := PersistentArray.initShift tailOff : Nat := 0 deriving Inhabited abbrev PArray (α : Type u) := PersistentArray α namespace PersistentArray /- TODO: use proofs for showing that array accesses are not out of bounds. We can do it after we reimplement the tactic framework. -/ variable {α : Type u} open Std.PersistentArrayNode def empty : PersistentArray α := {} def isEmpty (a : PersistentArray α) : Bool := a.size == 0 def mkEmptyArray : Array α := Array.mkEmpty branching.toNat abbrev mul2Shift (i : USize) (shift : USize) : USize := i.shiftLeft shift abbrev div2Shift (i : USize) (shift : USize) : USize := i.shiftRight shift abbrev mod2Shift (i : USize) (shift : USize) : USize := USize.land i ((USize.shiftLeft 1 shift) - 1) partial def getAux [Inhabited α] : PersistentArrayNode α → USize → USize → α | node cs, i, shift => getAux (cs.get! (div2Shift i shift).toNat) (mod2Shift i shift) (shift - initShift) | leaf cs, i, _ => cs.get! i.toNat def get! [Inhabited α] (t : PersistentArray α) (i : Nat) : α := if i >= t.tailOff then t.tail.get! (i - t.tailOff) else getAux t.root (USize.ofNat i) t.shift def getOp [Inhabited α] (self : PersistentArray α) (idx : Nat) : α := self.get! idx partial def setAux : PersistentArrayNode α → USize → USize → α → PersistentArrayNode α | node cs, i, shift, a => let j := div2Shift i shift let i := mod2Shift i shift let shift := shift - initShift node $ cs.modify j.toNat $ fun c => setAux c i shift a | leaf cs, i, _, a => leaf (cs.set! i.toNat a) def set (t : PersistentArray α) (i : Nat) (a : α) : PersistentArray α := if i >= t.tailOff then { t with tail := t.tail.set! (i - t.tailOff) a } else { t with root := setAux t.root (USize.ofNat i) t.shift a } @[specialize] partial def modifyAux [Inhabited α] (f : α → α) : PersistentArrayNode α → USize → USize → PersistentArrayNode α | node cs, i, shift => let j := div2Shift i shift let i := mod2Shift i shift let shift := shift - initShift node $ cs.modify j.toNat $ fun c => modifyAux f c i shift | leaf cs, i, _ => leaf (cs.modify i.toNat f) @[specialize] def modify [Inhabited α] (t : PersistentArray α) (i : Nat) (f : α → α) : PersistentArray α := if i >= t.tailOff then { t with tail := t.tail.modify (i - t.tailOff) f } else { t with root := modifyAux f t.root (USize.ofNat i) t.shift } partial def mkNewPath (shift : USize) (a : Array α) : PersistentArrayNode α := if shift == 0 then leaf a else node (mkEmptyArray.push (mkNewPath (shift - initShift) a)) partial def insertNewLeaf : PersistentArrayNode α → USize → USize → Array α → PersistentArrayNode α | node cs, i, shift, a => if i < branching then node (cs.push (leaf a)) else let j := div2Shift i shift let i := mod2Shift i shift let shift := shift - initShift if j.toNat < cs.size then node $ cs.modify j.toNat fun c => insertNewLeaf c i shift a else node $ cs.push $ mkNewPath shift a | n, _, _, _ => n -- unreachable def mkNewTail (t : PersistentArray α) : PersistentArray α := if t.size <= (mul2Shift 1 (t.shift + initShift)).toNat then { t with tail := mkEmptyArray, root := insertNewLeaf t.root (USize.ofNat (t.size - 1)) t.shift t.tail, tailOff := t.size } else { t with tail := #[], root := let n := mkEmptyArray.push t.root; node (n.push (mkNewPath t.shift t.tail)), shift := t.shift + initShift, tailOff := t.size } def tooBig : Nat := USize.size / 8 def push (t : PersistentArray α) (a : α) : PersistentArray α := let r := { t with tail := t.tail.push a, size := t.size + 1 } if r.tail.size < branching.toNat || t.size >= tooBig then r else mkNewTail r private def emptyArray {α : Type u} : Array (PersistentArrayNode α) := Array.mkEmpty PersistentArray.branching.toNat partial def popLeaf : PersistentArrayNode α → Option (Array α) × Array (PersistentArrayNode α) | n@(node cs) => if h : cs.size ≠ 0 then let idx : Fin cs.size := ⟨cs.size - 1, by exact Nat.predLt h⟩ let last := cs.get idx let cs' := cs.set idx arbitrary match popLeaf last with | (none, _) => (none, emptyArray) | (some l, newLast) => if newLast.size == 0 then let cs' := cs'.pop if cs'.isEmpty then (some l, emptyArray) else (some l, cs') else (some l, cs'.set (Array.size_set cs idx _ ▸ idx) (node newLast)) else (none, emptyArray) | leaf vs => (some vs, emptyArray) def pop (t : PersistentArray α) : PersistentArray α := if t.tail.size > 0 then { t with tail := t.tail.pop, size := t.size - 1 } else match popLeaf t.root with | (none, _) => t | (some last, newRoots) => let last := last.pop let newSize := t.size - 1 let newTailOff := newSize - last.size if newRoots.size == 1 && (newRoots.get! 0).isNode then { root := newRoots.get! 0, shift := t.shift - initShift, size := newSize, tail := last, tailOff := newTailOff } else { t with root := node newRoots, size := newSize, tail := last, tailOff := newTailOff } section variable {m : Type v → Type w} [Monad m] variable {β : Type v} @[specialize] private partial def foldlMAux (f : β → α → m β) : PersistentArrayNode α → β → m β | node cs, b => cs.foldlM (fun b c => foldlMAux f c b) b | leaf vs, b => vs.foldlM f b @[specialize] private partial def foldlFromMAux (f : β → α → m β) : PersistentArrayNode α → USize → USize → β → m β | node cs, i, shift, b => do let j := (div2Shift i shift).toNat let b ← foldlFromMAux f (cs.get! j) (mod2Shift i shift) (shift - initShift) b cs.foldlM (init := b) (start := j+1) fun b c => foldlMAux f c b | leaf vs, i, _, b => vs.foldlM (init := b) (start := i.toNat) f @[specialize] def foldlM (t : PersistentArray α) (f : β → α → m β) (init : β) (start : Nat := 0) : m β := do if start == 0 then let b ← foldlMAux f t.root init t.tail.foldlM f b else if start >= t.tailOff then t.tail.foldlM (init := init) (start := start - t.tailOff) f else do let b ← foldlFromMAux f t.root (USize.ofNat start) t.shift init; t.tail.foldlM f b @[specialize] partial def forInAux {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] [inh : Inhabited β] (f : α → β → m (ForInStep β)) (n : PersistentArrayNode α) (b : β) : m (ForInStep β) := do let mut b := b match n with | leaf vs => for v in vs do match (← f v b) with | r@(ForInStep.done _) => return r | ForInStep.yield bNew => b := bNew return ForInStep.yield b | node cs => for c in cs do match (← forInAux f c b) with | r@(ForInStep.done _) => return r | ForInStep.yield bNew => b := bNew return ForInStep.yield b @[specialize] protected def forIn (t : PersistentArray α) (init : β) (f : α → β → m (ForInStep β)) : m β := do match (← forInAux (inh := ⟨init⟩) f t.root init) with | ForInStep.done b => pure b | ForInStep.yield b => let mut b := b for v in t.tail do match (← f v b) with | ForInStep.done r => return r | ForInStep.yield bNew => b := bNew return b instance : ForIn m (PersistentArray α) α where forIn := PersistentArray.forIn @[specialize] partial def findSomeMAux (f : α → m (Option β)) : PersistentArrayNode α → m (Option β) | node cs => cs.findSomeM? (fun c => findSomeMAux f c) | leaf vs => vs.findSomeM? f @[specialize] def findSomeM? (t : PersistentArray α) (f : α → m (Option β)) : m (Option β) := do match (← findSomeMAux f t.root) with | none => t.tail.findSomeM? f | some b => pure (some b) @[specialize] partial def findSomeRevMAux (f : α → m (Option β)) : PersistentArrayNode α → m (Option β) | node cs => cs.findSomeRevM? (fun c => findSomeRevMAux f c) | leaf vs => vs.findSomeRevM? f @[specialize] def findSomeRevM? (t : PersistentArray α) (f : α → m (Option β)) : m (Option β) := do match (← t.tail.findSomeRevM? f) with | none => findSomeRevMAux f t.root | some b => pure (some b) @[specialize] partial def forMAux (f : α → m PUnit) : PersistentArrayNode α → m PUnit | node cs => cs.forM (fun c => forMAux f c) | leaf vs => vs.forM f @[specialize] def forM (t : PersistentArray α) (f : α → m PUnit) : m PUnit := forMAux f t.root *> t.tail.forM f end @[inline] def foldl {β} (t : PersistentArray α) (f : β → α → β) (init : β) (start : Nat := 0) : β := Id.run $ t.foldlM f init start @[inline] def filter (as : PersistentArray α) (p : α → Bool) : PersistentArray α := as.foldl (init := {}) fun asNew a => if p a then asNew.push a else asNew def toArray (t : PersistentArray α) : Array α := t.foldl Array.push #[] def append (t₁ t₂ : PersistentArray α) : PersistentArray α := if t₁.isEmpty then t₂ else t₂.foldl PersistentArray.push t₁ instance : Append (PersistentArray α) := ⟨append⟩ @[inline] def findSome? {β} (t : PersistentArray α) (f : α → (Option β)) : Option β := Id.run $ t.findSomeM? f @[inline] def findSomeRev? {β} (t : PersistentArray α) (f : α → (Option β)) : Option β := Id.run $ t.findSomeRevM? f def toList (t : PersistentArray α) : List α := (t.foldl (init := []) fun xs x => x :: xs).reverse section variable {m : Type → Type w} [Monad m] @[specialize] partial def anyMAux (p : α → m Bool) : PersistentArrayNode α → m Bool | node cs => cs.anyM fun c => anyMAux p c | leaf vs => vs.anyM p @[specialize] def anyM (t : PersistentArray α) (p : α → m Bool) : m Bool := anyMAux p t.root <||> t.tail.anyM p @[inline] def allM (a : PersistentArray α) (p : α → m Bool) : m Bool := do let b ← anyM a (fun v => do let b ← p v; pure (not b)) pure (not b) end @[inline] def any (a : PersistentArray α) (p : α → Bool) : Bool := Id.run $ anyM a p @[inline] def all (a : PersistentArray α) (p : α → Bool) : Bool := !any a fun v => !p v section variable {m : Type u → Type v} [Monad m] variable {β : Type u} @[specialize] partial def mapMAux (f : α → m β) : PersistentArrayNode α → m (PersistentArrayNode β) | node cs => node <$> cs.mapM (fun c => mapMAux f c) | leaf vs => leaf <$> vs.mapM f @[specialize] def mapM (f : α → m β) (t : PersistentArray α) : m (PersistentArray β) := do let root ← mapMAux f t.root let tail ← t.tail.mapM f pure { t with tail := tail, root := root } end @[inline] def map {β} (f : α → β) (t : PersistentArray α) : PersistentArray β := Id.run $ t.mapM f structure Stats where numNodes : Nat depth : Nat tailSize : Nat partial def collectStats : PersistentArrayNode α → Stats → Nat → Stats | node cs, s, d => cs.foldl (fun s c => collectStats c s (d+1)) { s with numNodes := s.numNodes + 1, depth := Nat.max d s.depth } | leaf vs, s, d => { s with numNodes := s.numNodes + 1, depth := Nat.max d s.depth } def stats (r : PersistentArray α) : Stats := collectStats r.root { numNodes := 0, depth := 0, tailSize := r.tail.size } 0 def Stats.toString (s : Stats) : String := s!"\{nodes := {s.numNodes}, depth := {s.depth}, tail size := {s.tailSize}}" instance : ToString Stats := ⟨Stats.toString⟩ end PersistentArray def mkPersistentArray {α : Type u} (n : Nat) (v : α) : PArray α := n.fold (init := PersistentArray.empty) fun i p => p.push v @[inline] def mkPArray {α : Type u} (n : Nat) (v : α) : PArray α := mkPersistentArray n v end Std open Std (PersistentArray PersistentArray.empty) def List.toPersistentArrayAux {α : Type u} : List α → PersistentArray α → PersistentArray α | [], t => t | x::xs, t => toPersistentArrayAux xs (t.push x) def List.toPersistentArray {α : Type u} (xs : List α) : PersistentArray α := xs.toPersistentArrayAux {} def Array.toPersistentArray {α : Type u} (xs : Array α) : PersistentArray α := xs.foldl (init := PersistentArray.empty) fun p x => p.push x @[inline] def Array.toPArray {α : Type u} (xs : Array α) : PersistentArray α := xs.toPersistentArray
cceee47b705df2ab861fe057f53f1772132987e7
27a31d06bcfc7c5d379fd04a08a9f5ed3f5302d4
/src/Lean/Elab/App.lean
da3744dc18d879eeb5cf612bd1750b9dcdaf2ec1
[ "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
joehendrix/lean4
0d1486945f7ca9fe225070374338f4f7e74bab03
1221bdd3c7d5395baa451ce8fdd2c2f8a00cbc8f
refs/heads/master
1,640,573,727,861
1,639,662,710,000
1,639,665,515,000
198,893,504
0
0
Apache-2.0
1,564,084,645,000
1,564,084,644,000
null
UTF-8
Lean
false
false
44,950
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Util.FindMVar import Lean.Parser.Term import Lean.Elab.Term import Lean.Elab.Binders import Lean.Elab.SyntheticMVars import Lean.Elab.Arg namespace Lean.Elab.Term open Meta builtin_initialize elabWithoutExpectedTypeAttr : TagAttribute ← registerTagAttribute `elabWithoutExpectedType "mark that applications of the given declaration should be elaborated without the expected type" def hasElabWithoutExpectedType (env : Environment) (declName : Name) : Bool := elabWithoutExpectedTypeAttr.hasTag env declName instance : ToString Arg := ⟨fun | Arg.stx val => toString val | Arg.expr val => toString val⟩ instance : ToString NamedArg where toString s := "(" ++ toString s.name ++ " := " ++ toString s.val ++ ")" def throwInvalidNamedArg {α} (namedArg : NamedArg) (fn? : Option Name) : TermElabM α := withRef namedArg.ref <| match fn? with | some fn => throwError "invalid argument name '{namedArg.name}' for function '{fn}'" | none => throwError "invalid argument name '{namedArg.name}' for function" private def ensureArgType (f : Expr) (arg : Expr) (expectedType : Expr) : TermElabM Expr := do let argType ← inferType arg ensureHasTypeAux expectedType argType arg f /- Relevant definitions: ``` class CoeFun (α : Sort u) (γ : α → outParam (Sort v)) abbrev coeFun {α : Sort u} {γ : α → Sort v} (a : α) [CoeFun α γ] : γ a ``` -/ private def tryCoeFun? (α : Expr) (a : Expr) : TermElabM (Option Expr) := do let v ← mkFreshLevelMVar let type ← mkArrow α (mkSort v) let γ ← mkFreshExprMVar type let u ← getLevel α let coeFunInstType := mkAppN (Lean.mkConst ``CoeFun [u, v]) #[α, γ] let mvar ← mkFreshExprMVar coeFunInstType MetavarKind.synthetic let mvarId := mvar.mvarId! try if (← synthesizeCoeInstMVarCore mvarId) then expandCoe <| mkAppN (Lean.mkConst ``coeFun [u, v]) #[α, γ, a, mvar] else return none catch _ => return none def synthesizeAppInstMVars (instMVars : Array MVarId) (app : Expr) : TermElabM Unit := for mvarId in instMVars do unless (← synthesizeInstMVarCore mvarId) do registerSyntheticMVarWithCurrRef mvarId SyntheticMVarKind.typeClass registerMVarErrorImplicitArgInfo mvarId (← getRef) app namespace ElabAppArgs /- Auxiliary structure for elaborating the application `f args namedArgs`. -/ structure State where explicit : Bool -- true if `@` modifier was used f : Expr fType : Expr args : List Arg -- remaining regular arguments namedArgs : List NamedArg -- remaining named arguments to be processed ellipsis : Bool := false expectedType? : Option Expr etaArgs : Array Expr := #[] toSetErrorCtx : Array MVarId := #[] -- metavariables that we need the set the error context using the application being built instMVars : Array MVarId := #[] -- metavariables for the instance implicit arguments that have already been processed -- The following field is used to implement the `propagateExpectedType` heuristic. propagateExpected : Bool -- true when expectedType has not been propagated yet abbrev M := StateRefT State TermElabM /- Add the given metavariable to the collection of metavariables associated with instance-implicit arguments. -/ private def addInstMVar (mvarId : MVarId) : M Unit := modify fun s => { s with instMVars := s.instMVars.push mvarId } /- Try to synthesize metavariables are `instMVars` using type class resolution. The ones that cannot be synthesized yet are registered. Remark: we use this method before trying to apply coercions to function. -/ def synthesizeAppInstMVars : M Unit := do let s ← get let instMVars := s.instMVars modify fun s => { s with instMVars := #[] } Lean.Elab.Term.synthesizeAppInstMVars instMVars s.f /- fType may become a forallE after we synthesize pending metavariables. -/ private def synthesizePendingAndNormalizeFunType : M Unit := do synthesizeAppInstMVars synthesizeSyntheticMVars let s ← get let fType ← whnfForall s.fType if fType.isForall then modify fun s => { s with fType := fType } else match (← tryCoeFun? fType s.f) with | some f => let fType ← inferType f modify fun s => { s with f := f, fType := fType } | none => for namedArg in s.namedArgs do let f := s.f.getAppFn if f.isConst then throwInvalidNamedArg namedArg f.constName! else throwInvalidNamedArg namedArg none throwError "function expected at{indentExpr s.f}\nterm has type{indentExpr fType}" /- Normalize and return the function type. -/ private def normalizeFunType : M Expr := do let s ← get let fType ← whnfForall s.fType modify fun s => { s with fType := fType } pure fType /- Return the binder name at `fType`. This method assumes `fType` is a function type. -/ private def getBindingName : M Name := return (← get).fType.bindingName! /- Return the next argument expected type. This method assumes `fType` is a function type. -/ private def getArgExpectedType : M Expr := return (← get).fType.bindingDomain! def eraseNamedArgCore (namedArgs : List NamedArg) (binderName : Name) : List NamedArg := namedArgs.filter (·.name != binderName) /- Remove named argument with name `binderName` from `namedArgs`. -/ def eraseNamedArg (binderName : Name) : M Unit := modify fun s => { s with namedArgs := eraseNamedArgCore s.namedArgs binderName } /- Add a new argument to the result. That is, `f := f arg`, update `fType`. This method assumes `fType` is a function type. -/ private def addNewArg (argName : Name) (arg : Expr) : M Unit := do modify fun s => { s with f := mkApp s.f arg, fType := s.fType.bindingBody!.instantiate1 arg } if arg.isMVar then let mvarId := arg.mvarId! if let some mvarErrorInfo ← getMVarErrorInfo? mvarId then registerMVarErrorInfo { mvarErrorInfo with argName? := argName } /- Elaborate the given `Arg` and add it to the result. See `addNewArg`. Recall that, `Arg` may be wrapping an already elaborated `Expr`. -/ private def elabAndAddNewArg (argName : Name) (arg : Arg) : M Unit := do let s ← get let expectedType ← getArgExpectedType match arg with | Arg.expr val => let arg ← ensureArgType s.f val expectedType addNewArg argName arg | Arg.stx val => let val ← elabTerm val expectedType let arg ← ensureArgType s.f val expectedType addNewArg argName arg /- Return true if the given type contains `OptParam` or `AutoParams` -/ private def hasOptAutoParams (type : Expr) : M Bool := do forallTelescopeReducing type fun xs type => xs.anyM fun x => do let xType ← inferType x return xType.getOptParamDefault?.isSome || xType.getAutoParamTactic?.isSome /- Return true if `fType` contains `OptParam` or `AutoParams` -/ private def fTypeHasOptAutoParams : M Bool := do hasOptAutoParams (← get).fType /- Auxiliary function for retrieving the resulting type of a function application. See `propagateExpectedType`. Remark: `(explicit : Bool) == true` when `@` modifier is used. -/ private partial def getForallBody (explicit : Bool) : Nat → List NamedArg → Expr → Option Expr | i, namedArgs, type@(Expr.forallE n d b c) => match namedArgs.find? fun (namedArg : NamedArg) => namedArg.name == n with | some _ => getForallBody explicit i (eraseNamedArgCore namedArgs n) b | none => if !explicit && !c.binderInfo.isExplicit then getForallBody explicit i namedArgs b else if i > 0 then getForallBody explicit (i-1) namedArgs b else if d.isAutoParam || d.isOptParam then getForallBody explicit i namedArgs b else some type | 0, [], type => some type | _, _, _ => none private def shouldPropagateExpectedTypeFor (nextArg : Arg) : Bool := match nextArg with | Arg.expr _ => false -- it has already been elaborated | Arg.stx stx => -- TODO: make this configurable? stx.getKind != ``Lean.Parser.Term.hole && stx.getKind != ``Lean.Parser.Term.syntheticHole && stx.getKind != ``Lean.Parser.Term.byTactic /- Auxiliary method for propagating the expected type. We call it as soon as we find the first explict argument. The goal is to propagate the expected type in applications of functions such as ```lean Add.add {α : Type u} : α → α → α List.cons {α : Type u} : α → List α → List α ``` This is particularly useful when there applicable coercions. For example, assume we have a coercion from `Nat` to `Int`, and we have `(x : Nat)` and the expected type is `List Int`. Then, if we don't use this function, the elaborator will fail to elaborate ``` List.cons x [] ``` First, the elaborator creates a new metavariable `?α` for the implicit argument `{α : Type u}`. Then, when it processes `x`, it assigns `?α := Nat`, and then obtain the resultant type `List Nat` which is **not** definitionally equal to `List Int`. We solve the problem by executing this method before we elaborate the first explicit argument (`x` in this example). This method infers that the resultant type is `List ?α` and unifies it with `List Int`. Then, when we elaborate `x`, the elaborate realizes the coercion from `Nat` to `Int` must be used, and the term ``` @List.cons Int (coe x) (@List.nil Int) ``` is produced. The method will do nothing if 1- The resultant type depends on the remaining arguments (i.e., `!eTypeBody.hasLooseBVars`). 2- The resultant type contains optional/auto params. We have considered adding the following extra conditions a) The resultant type does not contain any type metavariable. b) The resultant type contains a nontype metavariable. These two conditions would restrict the method to simple functions that are "morally" in the Hindley&Milner fragment. If users need to disable expected type propagation, we can add an attribute `[elabWithoutExpectedType]`. -/ private def propagateExpectedType (arg : Arg) : M Unit := do if shouldPropagateExpectedTypeFor arg then let s ← get -- TODO: handle s.etaArgs.size > 0 unless !s.etaArgs.isEmpty || !s.propagateExpected do match s.expectedType? with | none => pure () | some expectedType => /- We don't propagate `Prop` because we often use `Prop` as a more general "Bool" (e.g., `if-then-else`). If we propagate `expectedType == Prop` in the following examples, the elaborator would fail ``` def f1 (s : Nat × Bool) : Bool := if s.2 then false else true def f2 (s : List Bool) : Bool := if s.head! then false else true def f3 (s : List Bool) : Bool := if List.head! (s.map not) then false else true ``` They would all fail for the same reason. So, let's focus on the first one. We would elaborate `s.2` with `expectedType == Prop`. Before we elaborate `s`, this method would be invoked, and `s.fType` is `?α × ?β → ?β` and after propagation we would have `?α × Prop → Prop`. Then, when we would try to elaborate `s`, and get a type error because `?α × Prop` cannot be unified with `Nat × Bool` Most users would have a hard time trying to understand why these examples failed. Here is a possible alternative workarounds. We give up the idea of using `Prop` at `if-then-else`. Drawback: users use `if-then-else` with conditions that are not Decidable. So, users would have to embrace `propDecidable` and `choice`. This may not be that bad since the developers and users don't seem to care about constructivism. We currently use a different workaround, we just don't propagate the expected type when it is `Prop`. -/ if expectedType.isProp then modify fun s => { s with propagateExpected := false } else let numRemainingArgs := s.args.length trace[Elab.app.propagateExpectedType] "etaArgs.size: {s.etaArgs.size}, numRemainingArgs: {numRemainingArgs}, fType: {s.fType}" match getForallBody s.explicit numRemainingArgs s.namedArgs s.fType with | none => pure () | some fTypeBody => unless fTypeBody.hasLooseBVars do unless (← hasOptAutoParams fTypeBody) do trace[Elab.app.propagateExpectedType] "{expectedType} =?= {fTypeBody}" if (← isDefEq expectedType fTypeBody) then /- Note that we only set `propagateExpected := false` when propagation has succeeded. -/ modify fun s => { s with propagateExpected := false } /- This method execute after all application arguments have been processed. -/ private def finalize : M Expr := do let s ← get let mut e := s.f -- all user explicit arguments have been consumed trace[Elab.app.finalize] e let ref ← getRef -- Register the error context of implicits for mvarId in s.toSetErrorCtx do registerMVarErrorImplicitArgInfo mvarId ref e if !s.etaArgs.isEmpty then e ← mkLambdaFVars s.etaArgs e /- Remark: we should not use `s.fType` as `eType` even when `s.etaArgs.isEmpty`. Reason: it may have been unfolded. -/ let eType ← inferType e trace[Elab.app.finalize] "after etaArgs, {e} : {eType}" match s.expectedType? with | none => pure () | some expectedType => trace[Elab.app.finalize] "expected type: {expectedType}" -- Try to propagate expected type. Ignore if types are not definitionally equal, caller must handle it. discard <| isDefEq expectedType eType synthesizeAppInstMVars pure e /- Return true if there is a named argument that depends on the next argument. -/ private def anyNamedArgDependsOnCurrent : M Bool := do let s ← get if s.namedArgs.isEmpty then return false else forallTelescopeReducing s.fType fun xs _ => do let curr := xs[0] for i in [1:xs.size] do let xDecl ← getLocalDecl xs[i].fvarId! if s.namedArgs.any fun arg => arg.name == xDecl.userName then if (← getMCtx).localDeclDependsOn xDecl curr.fvarId! then return true return false /- Return true if there are regular or named arguments to be processed. -/ private def hasArgsToProcess : M Bool := do let s ← get return !s.args.isEmpty || !s.namedArgs.isEmpty /- Return true if the next argument at `args` is of the form `_` -/ private def isNextArgHole : M Bool := do match (← get).args with | Arg.stx (Syntax.node _ ``Lean.Parser.Term.hole _) :: _ => pure true | _ => pure false mutual /- Create a fresh local variable with the current binder name and argument type, add it to `etaArgs` and `f`, and then execute the main loop.-/ private partial def addEtaArg (argName : Name) : M Expr := do let n ← getBindingName let type ← getArgExpectedType withLocalDeclD n type fun x => do modify fun s => { s with etaArgs := s.etaArgs.push x } addNewArg argName x main private partial def addImplicitArg (argName : Name) : M Expr := do let argType ← getArgExpectedType let arg ← mkFreshExprMVar argType modify fun s => { s with toSetErrorCtx := s.toSetErrorCtx.push arg.mvarId! } addNewArg argName arg main /- Process a `fType` of the form `(x : A) → B x`. This method assume `fType` is a function type -/ private partial def processExplictArg (argName : Name) : M Expr := do let s ← get match s.args with | arg::args => propagateExpectedType arg modify fun s => { s with args := args } elabAndAddNewArg argName arg main | _ => let argType ← getArgExpectedType match s.explicit, argType.getOptParamDefault?, argType.getAutoParamTactic? with | false, some defVal, _ => addNewArg argName defVal; main | false, _, some (Expr.const tacticDecl _ _) => let env ← getEnv let opts ← getOptions match evalSyntaxConstant env opts tacticDecl with | Except.error err => throwError err | Except.ok tacticSyntax => -- TODO(Leo): does this work correctly for tactic sequences? let tacticBlock ← `(by $tacticSyntax) let argType := argType.getArg! 0 -- `autoParam type := by tactic` ==> `type` let argNew := Arg.stx tacticBlock propagateExpectedType argNew elabAndAddNewArg argName argNew main | false, _, some _ => throwError "invalid autoParam, argument must be a constant" | _, _, _ => if !s.namedArgs.isEmpty then if (← anyNamedArgDependsOnCurrent) then addImplicitArg argName else addEtaArg argName else if !s.explicit then if (← fTypeHasOptAutoParams) then addEtaArg argName else if (← get).ellipsis then addImplicitArg argName else finalize else finalize /- Process a `fType` of the form `{x : A} → B x`. This method assume `fType` is a function type -/ private partial def processImplicitArg (argName : Name) : M Expr := do if (← get).explicit then processExplictArg argName else addImplicitArg argName /- Process a `fType` of the form `{{x : A}} → B x`. This method assume `fType` is a function type -/ private partial def processStrictImplicitArg (argName : Name) : M Expr := do if (← get).explicit then processExplictArg argName else if (← hasArgsToProcess) then addImplicitArg argName else finalize /- Process a `fType` of the form `[x : A] → B x`. This method assume `fType` is a function type -/ private partial def processInstImplicitArg (argName : Name) : M Expr := do if (← get).explicit then if (← isNextArgHole) then /- Recall that if '@' has been used, and the argument is '_', then we still use type class resolution -/ let arg ← mkFreshExprMVar (← getArgExpectedType) MetavarKind.synthetic modify fun s => { s with args := s.args.tail! } addInstMVar arg.mvarId! addNewArg argName arg main else processExplictArg argName else let arg ← mkFreshExprMVar (← getArgExpectedType) MetavarKind.synthetic addInstMVar arg.mvarId! addNewArg argName arg main /- Elaborate function application arguments. -/ partial def main : M Expr := do let s ← get let fType ← normalizeFunType if fType.isForall then let binderName := fType.bindingName! let binfo := fType.bindingInfo! let s ← get match s.namedArgs.find? fun (namedArg : NamedArg) => namedArg.name == binderName with | some namedArg => propagateExpectedType namedArg.val eraseNamedArg binderName elabAndAddNewArg binderName namedArg.val main | none => match binfo with | BinderInfo.implicit => processImplicitArg binderName | BinderInfo.instImplicit => processInstImplicitArg binderName | BinderInfo.strictImplicit => processStrictImplicitArg binderName | _ => processExplictArg binderName else if (← hasArgsToProcess) then synthesizePendingAndNormalizeFunType main else finalize end end ElabAppArgs private def propagateExpectedTypeFor (f : Expr) : TermElabM Bool := match f.getAppFn.constName? with | some declName => return !hasElabWithoutExpectedType (← getEnv) declName | _ => return true def elabAppArgs (f : Expr) (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit ellipsis : Bool) : TermElabM Expr := do let fType ← inferType f let fType ← instantiateMVars fType trace[Elab.app.args] "explicit: {explicit}, {f} : {fType}" unless namedArgs.isEmpty && args.isEmpty do tryPostponeIfMVar fType ElabAppArgs.main.run' { args := args.toList, expectedType? := expectedType?, explicit := explicit, ellipsis := ellipsis, namedArgs := namedArgs.toList, f := f, fType := fType propagateExpected := (← propagateExpectedTypeFor f) } /-- Auxiliary inductive datatype that represents the resolution of an `LVal`. -/ inductive LValResolution where | projFn (baseStructName : Name) (structName : Name) (fieldName : Name) | projIdx (structName : Name) (idx : Nat) | const (baseStructName : Name) (structName : Name) (constName : Name) | localRec (baseName : Name) (fullName : Name) (fvar : Expr) | getOp (fullName : Name) (idx : Syntax) private def throwLValError {α} (e : Expr) (eType : Expr) (msg : MessageData) : TermElabM α := throwError "{msg}{indentExpr e}\nhas type{indentExpr eType}" /-- `findMethod? env S fName`. 1- If `env` contains `S ++ fName`, return `(S, S++fName)` 2- Otherwise if `env` contains private name `prv` for `S ++ fName`, return `(S, prv)`, o 3- Otherwise for each parent structure `S'` of `S`, we try `findMethod? env S' fname` -/ private partial def findMethod? (env : Environment) (structName fieldName : Name) : Option (Name × Name) := let fullName := structName ++ fieldName match env.find? fullName with | some _ => some (structName, fullName) | none => let fullNamePrv := mkPrivateName env fullName match env.find? fullNamePrv with | some _ => some (structName, fullNamePrv) | none => if isStructure env structName then (getParentStructures env structName).findSome? fun parentStructName => findMethod? env parentStructName fieldName else none private def resolveLValAux (e : Expr) (eType : Expr) (lval : LVal) : TermElabM LValResolution := do match eType.getAppFn.constName?, lval with | some structName, LVal.fieldIdx _ idx => if idx == 0 then throwError "invalid projection, index must be greater than 0" let env ← getEnv unless isStructureLike env structName do throwLValError e eType "invalid projection, structure expected" let numFields := getStructureLikeNumFields env structName if idx - 1 < numFields then if isStructure env structName then let fieldNames := getStructureFields env structName return LValResolution.projFn structName structName fieldNames[idx - 1] else /- `structName` was declared using `inductive` command. So, we don't projection functions for it. Thus, we use `Expr.proj` -/ return LValResolution.projIdx structName (idx - 1) else throwLValError e eType m!"invalid projection, structure has only {numFields} field(s)" | some structName, LVal.fieldName _ fieldName _ _ => let env ← getEnv let searchEnv : Unit → TermElabM LValResolution := fun _ => do match findMethod? env structName (Name.mkSimple fieldName) with | some (baseStructName, fullName) => pure $ LValResolution.const baseStructName structName fullName | none => throwLValError e eType m!"invalid field '{fieldName}', the environment does not contain '{Name.mkStr structName fieldName}'" -- search local context first, then environment let searchCtx : Unit → TermElabM LValResolution := fun _ => do let fullName := Name.mkStr structName fieldName let currNamespace ← getCurrNamespace let localName := fullName.replacePrefix currNamespace Name.anonymous let lctx ← getLCtx match lctx.findFromUserName? localName with | some localDecl => if localDecl.binderInfo == BinderInfo.auxDecl then /- LVal notation is being used to make a "local" recursive call. -/ pure $ LValResolution.localRec structName fullName localDecl.toExpr else searchEnv () | none => searchEnv () if isStructure env structName then match findField? env structName (Name.mkSimple fieldName) with | some baseStructName => pure $ LValResolution.projFn baseStructName structName (Name.mkSimple fieldName) | none => searchCtx () else searchCtx () | some structName, LVal.getOp _ idx => let env ← getEnv let fullName := Name.mkStr structName "getOp" match env.find? fullName with | some _ => pure $ LValResolution.getOp fullName idx | none => throwLValError e eType m!"invalid [..] notation because environment does not contain '{fullName}'" | none, LVal.fieldName _ _ (some suffix) _ => if e.isConst then throwUnknownConstant (e.constName! ++ suffix) else throwLValError e eType "invalid field notation, type is not of the form (C ...) where C is a constant" | _, LVal.getOp _ idx => throwLValError e eType "invalid [..] notation, type is not of the form (C ...) where C is a constant" | _, _ => throwLValError e eType "invalid field notation, type is not of the form (C ...) where C is a constant" /- whnfCore + implicit consumption. Example: given `e` with `eType := {α : Type} → (fun β => List β) α `, it produces `(e ?m, List ?m)` where `?m` is fresh metavariable. -/ private partial def consumeImplicits (stx : Syntax) (e eType : Expr) (hasArgs : Bool) : TermElabM (Expr × Expr) := do let eType ← whnfCore eType match eType with | Expr.forallE n d b c => if c.binderInfo.isImplicit || (hasArgs && c.binderInfo.isStrictImplicit) then let mvar ← mkFreshExprMVar d registerMVarErrorHoleInfo mvar.mvarId! stx consumeImplicits stx (mkApp e mvar) (b.instantiate1 mvar) hasArgs else if c.binderInfo.isInstImplicit then let mvar ← mkInstMVar d let r := mkApp e mvar registerMVarErrorImplicitArgInfo mvar.mvarId! stx r consumeImplicits stx r (b.instantiate1 mvar) hasArgs else match d.getOptParamDefault? with | some defVal => consumeImplicits stx (mkApp e defVal) (b.instantiate1 defVal) hasArgs -- TODO: we do not handle autoParams here. | _ => pure (e, eType) | _ => pure (e, eType) private partial def resolveLValLoop (lval : LVal) (e eType : Expr) (previousExceptions : Array Exception) (hasArgs : Bool) : TermElabM (Expr × LValResolution) := do let (e, eType) ← consumeImplicits lval.getRef e eType hasArgs tryPostponeIfMVar eType try let lvalRes ← resolveLValAux e eType lval pure (e, lvalRes) catch | ex@(Exception.error _ _) => let eType? ← unfoldDefinition? eType match eType? with | some eType => resolveLValLoop lval e eType (previousExceptions.push ex) hasArgs | none => previousExceptions.forM fun ex => logException ex throw ex | ex@(Exception.internal _ _) => throw ex private def resolveLVal (e : Expr) (lval : LVal) (hasArgs : Bool) : TermElabM (Expr × LValResolution) := do let eType ← inferType e resolveLValLoop lval e eType #[] hasArgs private partial def mkBaseProjections (baseStructName : Name) (structName : Name) (e : Expr) : TermElabM Expr := do let env ← getEnv match getPathToBaseStructure? env baseStructName structName with | none => throwError "failed to access field in parent structure" | some path => let mut e := e for projFunName in path do let projFn ← mkConst projFunName e ← elabAppArgs projFn #[{ name := `self, val := Arg.expr e }] (args := #[]) (expectedType? := none) (explicit := false) (ellipsis := false) return e /- Auxiliary method for field notation. It tries to add `e` as a new argument to `args` or `namedArgs`. This method first finds the parameter with a type of the form `(baseName ...)`. When the parameter is found, if it an explicit one and `args` is big enough, we add `e` to `args`. Otherwise, if there isn't another parameter with the same name, we add `e` to `namedArgs`. Remark: `fullName` is the name of the resolved "field" access function. It is used for reporting errors -/ private def addLValArg (baseName : Name) (fullName : Name) (e : Expr) (args : Array Arg) (namedArgs : Array NamedArg) (fType : Expr) : TermElabM (Array Arg × Array NamedArg) := forallTelescopeReducing fType fun xs _ => do let mut argIdx := 0 -- position of the next explicit argument let mut remainingNamedArgs := namedArgs for i in [:xs.size] do let x := xs[i] let xDecl ← getLocalDecl x.fvarId! /- If there is named argument with name `xDecl.userName`, then we skip it. -/ match remainingNamedArgs.findIdx? (fun namedArg => namedArg.name == xDecl.userName) with | some idx => remainingNamedArgs := remainingNamedArgs.eraseIdx idx | none => let mut foundIt := false let type := xDecl.type if type.consumeMData.isAppOf baseName then foundIt := true if !foundIt then /- Normalize type and try again -/ let type ← withReducible $ whnf type if type.consumeMData.isAppOf baseName then foundIt := true if foundIt then /- We found a type of the form (baseName ...). First, we check if the current argument is an explicit one, and the current explicit position "fits" at `args` (i.e., it must be ≤ arg.size) -/ if argIdx ≤ args.size && xDecl.binderInfo.isExplicit then /- We insert `e` as an explicit argument -/ return (args.insertAt argIdx (Arg.expr e), namedArgs) /- If we can't add `e` to `args`, we try to add it using a named argument, but this is only possible if there isn't an argument with the same name occurring before it. -/ for j in [:i] do let prev := xs[j] let prevDecl ← getLocalDecl prev.fvarId! if prevDecl.userName == xDecl.userName then throwError "invalid field notation, function '{fullName}' has argument with the expected type{indentExpr type}\nbut it cannot be used" return (args, namedArgs.push { name := xDecl.userName, val := Arg.expr e }) if xDecl.binderInfo.isExplicit then -- advance explicit argument position argIdx := argIdx + 1 throwError "invalid field notation, function '{fullName}' does not have argument with type ({baseName} ...) that can be used, it must be explicit or implicit with an unique name" private def elabAppLValsAux (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit ellipsis : Bool) (f : Expr) (lvals : List LVal) : TermElabM Expr := let rec loop : Expr → List LVal → TermElabM Expr | f, [] => elabAppArgs f namedArgs args expectedType? explicit ellipsis | f, lval::lvals => do if let LVal.fieldName (ref := fieldStx) (targetStx := targetStx) .. := lval then addDotCompletionInfo targetStx f expectedType? fieldStx let hasArgs := !namedArgs.isEmpty || !args.isEmpty let (f, lvalRes) ← resolveLVal f lval hasArgs match lvalRes with | LValResolution.projIdx structName idx => let f := mkProj structName idx f addTermInfo lval.getRef f loop f lvals | LValResolution.projFn baseStructName structName fieldName => let f ← mkBaseProjections baseStructName structName f if let some info := getFieldInfo? (← getEnv) baseStructName fieldName then if isPrivateNameFromImportedModule (← getEnv) info.projFn then throwError "field '{fieldName}' from structure '{structName}' is private" let projFn ← mkConst info.projFn addTermInfo lval.getRef projFn if lvals.isEmpty then let namedArgs ← addNamedArg namedArgs { name := `self, val := Arg.expr f } elabAppArgs projFn namedArgs args expectedType? explicit ellipsis else let f ← elabAppArgs projFn #[{ name := `self, val := Arg.expr f }] #[] (expectedType? := none) (explicit := false) (ellipsis := false) loop f lvals else unreachable! | LValResolution.const baseStructName structName constName => let f ← if baseStructName != structName then mkBaseProjections baseStructName structName f else pure f let projFn ← mkConst constName addTermInfo lval.getRef projFn if lvals.isEmpty then let projFnType ← inferType projFn let (args, namedArgs) ← addLValArg baseStructName constName f args namedArgs projFnType elabAppArgs projFn namedArgs args expectedType? explicit ellipsis else let f ← elabAppArgs projFn #[] #[Arg.expr f] (expectedType? := none) (explicit := false) (ellipsis := false) loop f lvals | LValResolution.localRec baseName fullName fvar => addTermInfo lval.getRef fvar if lvals.isEmpty then let fvarType ← inferType fvar let (args, namedArgs) ← addLValArg baseName fullName f args namedArgs fvarType elabAppArgs fvar namedArgs args expectedType? explicit ellipsis else let f ← elabAppArgs fvar #[] #[Arg.expr f] (expectedType? := none) (explicit := false) (ellipsis := false) loop f lvals | LValResolution.getOp fullName idx => let getOpFn ← mkConst fullName addTermInfo lval.getRef getOpFn if lvals.isEmpty then let namedArgs ← addNamedArg namedArgs { name := `self, val := Arg.expr f } let namedArgs ← addNamedArg namedArgs { name := `idx, val := Arg.stx idx } elabAppArgs getOpFn namedArgs args expectedType? explicit ellipsis else let f ← elabAppArgs getOpFn #[{ name := `self, val := Arg.expr f }, { name := `idx, val := Arg.stx idx }] #[] (expectedType? := none) (explicit := false) (ellipsis := false) loop f lvals loop f lvals private def elabAppLVals (f : Expr) (lvals : List LVal) (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit ellipsis : Bool) : TermElabM Expr := do if !lvals.isEmpty && explicit then throwError "invalid use of field notation with `@` modifier" elabAppLValsAux namedArgs args expectedType? explicit ellipsis f lvals def elabExplicitUnivs (lvls : Array Syntax) : TermElabM (List Level) := do lvls.foldrM (fun stx lvls => do pure ((← elabLevel stx)::lvls)) [] /- Interaction between `errToSorry` and `observing`. - The method `elabTerm` catches exceptions, log them, and returns a synthetic sorry (IF `ctx.errToSorry` == true). - When we elaborate choice nodes (and overloaded identifiers), we track multiple results using the `observing x` combinator. The `observing x` executes `x` and returns a `TermElabResult`. `observing `x does not check for synthetic sorry's, just an exception. Thus, it may think `x` worked when it didn't if a synthetic sorry was introduced. We decided that checking for synthetic sorrys at `observing` is not a good solution because it would not be clear to decide what the "main" error message for the alternative is. When the result contains a synthetic `sorry`, it is not clear which error message corresponds to the `sorry`. Moreover, while executing `x`, many error messages may have been logged. Recall that we need an error per alternative at `mergeFailures`. Thus, we decided to set `errToSorry` to `false` whenever processing choice nodes and overloaded symbols. Important: we rely on the property that after `errToSorry` is set to false, no elaboration function executed by `x` will reset it to `true`. -/ private partial def elabAppFnId (fIdent : Syntax) (fExplicitUnivs : List Level) (lvals : List LVal) (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit ellipsis overloaded : Bool) (acc : Array (TermElabResult Expr)) : TermElabM (Array (TermElabResult Expr)) := do let funLVals ← withRef fIdent <| resolveName' fIdent fExplicitUnivs expectedType? let overloaded := overloaded || funLVals.length > 1 -- Set `errToSorry` to `false` if `funLVals` > 1. See comment above about the interaction between `errToSorry` and `observing`. withReader (fun ctx => { ctx with errToSorry := funLVals.length == 1 && ctx.errToSorry }) do funLVals.foldlM (init := acc) fun acc (f, fIdent, fields) => do let lvals' := toLVals fields (first := true) let s ← observing do addTermInfo fIdent f expectedType? let e ← elabAppLVals f (lvals' ++ lvals) namedArgs args expectedType? explicit ellipsis if overloaded then ensureHasType expectedType? e else pure e return acc.push s where toName : List Syntax → Name | [] => Name.anonymous | field :: fields => Name.mkStr (toName fields) field.getId.toString toLVals : List Syntax → (first : Bool) → List LVal | [], _ => [] | field::fields, true => LVal.fieldName field field.getId.toString (toName (field::fields)) fIdent :: toLVals fields false | field::fields, false => LVal.fieldName field field.getId.toString none fIdent :: toLVals fields false private partial def elabAppFn (f : Syntax) (lvals : List LVal) (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit ellipsis overloaded : Bool) (acc : Array (TermElabResult Expr)) : TermElabM (Array (TermElabResult Expr)) := if f.getKind == choiceKind then -- Set `errToSorry` to `false` when processing choice nodes. See comment above about the interaction between `errToSorry` and `observing`. withReader (fun ctx => { ctx with errToSorry := false }) do f.getArgs.foldlM (fun acc f => elabAppFn f lvals namedArgs args expectedType? explicit ellipsis true acc) acc else let elabFieldName (e field : Syntax) := do let newLVals := field.identComponents.map fun comp => -- We use `none` in `suffix?` since `field` can't be part of a composite name LVal.fieldName comp (toString comp.getId) none e elabAppFn e (newLVals ++ lvals) namedArgs args expectedType? explicit ellipsis overloaded acc let elabFieldIdx (e idxStx : Syntax) := do let idx := idxStx.isFieldIdx?.get! elabAppFn e (LVal.fieldIdx idxStx idx :: lvals) namedArgs args expectedType? explicit ellipsis overloaded acc match f with | `($(e).$idx:fieldIdx) => elabFieldIdx e idx | `($e |>.$idx:fieldIdx) => elabFieldIdx e idx | `($(e).$field:ident) => elabFieldName e field | `($e |>.$field:ident) => elabFieldName e field | `($e[%$bracket $idx]) => elabAppFn e (LVal.getOp bracket idx :: lvals) namedArgs args expectedType? explicit ellipsis overloaded acc | `($id:ident@$t:term) => throwError "unexpected occurrence of named pattern" | `($id:ident) => do elabAppFnId id [] lvals namedArgs args expectedType? explicit ellipsis overloaded acc | `($id:ident.{$us,*}) => do let us ← elabExplicitUnivs us elabAppFnId id us lvals namedArgs args expectedType? explicit ellipsis overloaded acc | `(@$id:ident) => elabAppFn id lvals namedArgs args expectedType? (explicit := true) ellipsis overloaded acc | `(@$id:ident.{$us,*}) => elabAppFn (f.getArg 1) lvals namedArgs args expectedType? (explicit := true) ellipsis overloaded acc | `(@$t) => throwUnsupportedSyntax -- invalid occurrence of `@` | `(_) => throwError "placeholders '_' cannot be used where a function is expected" | _ => do let catchPostpone := !overloaded /- If we are processing a choice node, then we should use `catchPostpone == false` when elaborating terms. Recall that `observing` does not catch `postponeExceptionId`. -/ if lvals.isEmpty && namedArgs.isEmpty && args.isEmpty then /- Recall that elabAppFn is used for elaborating atomics terms **and** choice nodes that may contain arbitrary terms. If they are not being used as a function, we should elaborate using the expectedType. -/ let s ← if overloaded then observing <| elabTermEnsuringType f expectedType? catchPostpone else observing <| elabTerm f expectedType? return acc.push s else let s ← observing do let f ← elabTerm f none catchPostpone let e ← elabAppLVals f lvals namedArgs args expectedType? explicit ellipsis if overloaded then ensureHasType expectedType? e else pure e return acc.push s private def isSuccess (candidate : TermElabResult Expr) : Bool := match candidate with | EStateM.Result.ok _ _ => true | _ => false private def getSuccess (candidates : Array (TermElabResult Expr)) : Array (TermElabResult Expr) := candidates.filter isSuccess private def toMessageData (ex : Exception) : TermElabM MessageData := do let pos ← getRefPos match ex.getRef.getPos? with | none => return ex.toMessageData | some exPos => if pos == exPos then return ex.toMessageData else let exPosition := (← getFileMap).toPosition exPos return m!"{exPosition.line}:{exPosition.column} {ex.toMessageData}" private def toMessageList (msgs : Array MessageData) : MessageData := indentD (MessageData.joinSep msgs.toList m!"\n\n") private def mergeFailures {α} (failures : Array (TermElabResult Expr)) : TermElabM α := do let msgs ← failures.mapM fun failure => match failure with | EStateM.Result.ok _ _ => unreachable! | EStateM.Result.error ex _ => toMessageData ex throwError "overloaded, errors {toMessageList msgs}" private def elabAppAux (f : Syntax) (namedArgs : Array NamedArg) (args : Array Arg) (ellipsis : Bool) (expectedType? : Option Expr) : TermElabM Expr := do let candidates ← elabAppFn f [] namedArgs args expectedType? (explicit := false) (ellipsis := ellipsis) (overloaded := false) #[] if candidates.size == 1 then applyResult candidates[0] else let successes := getSuccess candidates if successes.size == 1 then applyResult successes[0] else if successes.size > 1 then let lctx ← getLCtx let opts ← getOptions let msgs : Array MessageData := successes.map fun success => match success with | EStateM.Result.ok e s => MessageData.withContext { env := s.meta.core.env, mctx := s.meta.meta.mctx, lctx := lctx, opts := opts } e | _ => unreachable! throwErrorAt f "ambiguous, possible interpretations {toMessageList msgs}" else withRef f <| mergeFailures candidates @[builtinTermElab app] def elabApp : TermElab := fun stx expectedType? => withoutPostponingUniverseConstraints do let (f, namedArgs, args, ellipsis) ← expandApp stx elabAppAux f namedArgs args (ellipsis := ellipsis) expectedType? private def elabAtom : TermElab := fun stx expectedType? => elabAppAux stx #[] #[] (ellipsis := false) expectedType? @[builtinTermElab ident] def elabIdent : TermElab := elabAtom /-- `x@e` matches the pattern `e` and binds its value to the identifier `x`. -/ @[builtinTermElab namedPattern] def elabNamedPattern : TermElab := elabAtom /-- `x.{u, ...}` explicitly specifies the universes `u, ...` of the constant `x`. -/ @[builtinTermElab explicitUniv] def elabExplicitUniv : TermElab := elabAtom /-- `e |>.x` is a shorthand for `(e).x`. It is especially useful for avoiding parentheses with repeated applications. -/ @[builtinTermElab pipeProj] def elabPipeProj : TermElab | `($e |>.$f $args*), expectedType? => withoutPostponingUniverseConstraints do let (namedArgs, args, ellipsis) ← expandArgs args elabAppAux (← `($e |>.$f)) namedArgs args (ellipsis := ellipsis) expectedType? | _, _ => throwUnsupportedSyntax /-- `@x` disables automatic insertion of implicit parameters of the constant `x`. `@e` for any term `e` also disables the insertion of implicit lambdas at this position. -/ @[builtinTermElab explicit] def elabExplicit : TermElab := fun stx expectedType? => match stx with | `(@$id:ident) => elabAtom stx expectedType? -- Recall that `elabApp` also has support for `@` | `(@$id:ident.{$us,*}) => elabAtom stx expectedType? | `(@($t)) => elabTerm t expectedType? (implicitLambda := false) -- `@` is being used just to disable implicit lambdas | `(@$t) => elabTerm t expectedType? (implicitLambda := false) -- `@` is being used just to disable implicit lambdas | _ => throwUnsupportedSyntax @[builtinTermElab choice] def elabChoice : TermElab := elabAtom @[builtinTermElab proj] def elabProj : TermElab := elabAtom @[builtinTermElab arrayRef] def elabArrayRef : TermElab := elabAtom builtin_initialize registerTraceClass `Elab.app end Lean.Elab.Term