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
a9296505fcd6c4cb86ee0998a9834b646952329c
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Data/PrefixTree.lean
a5088b8c6f6e341e4c0f38e0d8b53eb4d8a9cfec
[ "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
3,812
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.Data.RBMap namespace Lean /- Similar to trie, but for arbitrary keys -/ inductive PrefixTreeNode (α : Type u) (β : Type v) where | Node : Option β → RBNode α (fun _ => PrefixTreeNode α β) → PrefixTreeNode α β instance : Inhabited (PrefixTreeNode α β) where default := PrefixTreeNode.Node none RBNode.leaf namespace PrefixTreeNode def empty : PrefixTreeNode α β := PrefixTreeNode.Node none RBNode.leaf @[specialize] partial def insert (t : PrefixTreeNode α β) (cmp : α → α → Ordering) (k : List α) (val : β) : PrefixTreeNode α β := let rec insertEmpty (k : List α) : PrefixTreeNode α β := match k with | [] => PrefixTreeNode.Node (some val) RBNode.leaf | k :: ks => let t := insertEmpty ks PrefixTreeNode.Node none (RBNode.singleton k t) let rec loop | PrefixTreeNode.Node _ m, [] => PrefixTreeNode.Node (some val) m -- overrides old value | PrefixTreeNode.Node v m, k :: ks => let t := match RBNode.find cmp m k with | none => insertEmpty ks | some t => loop t ks PrefixTreeNode.Node v (RBNode.insert cmp m k t) loop t k @[specialize] partial def find? (t : PrefixTreeNode α β) (cmp : α → α → Ordering) (k : List α) : Option β := let rec loop | PrefixTreeNode.Node val _, [] => val | PrefixTreeNode.Node _ m, k :: ks => match RBNode.find cmp m k with | none => none | some t => loop t ks loop t k @[specialize] partial def foldMatchingM [Monad m] (t : PrefixTreeNode α β) (cmp : α → α → Ordering) (k : List α) (init : σ) (f : β → σ → m σ) : m σ := let rec fold : PrefixTreeNode α β → σ → m σ | PrefixTreeNode.Node b? n, d => do let d ← match b? with | none => pure d | some b => f b d n.foldM (init := d) fun d _ t => fold t d let rec find : List α → PrefixTreeNode α β → σ → m σ | [], t, d => fold t d | k::ks, PrefixTreeNode.Node _ m, d => match RBNode.find cmp m k with | none => pure init | some t => find ks t d find k t init inductive WellFormed (cmp : α → α → Ordering) : PrefixTreeNode α β → Prop where | emptyWff : WellFormed cmp empty | insertWff : WellFormed cmp t → WellFormed cmp (insert t cmp k val) end PrefixTreeNode def PrefixTree (α : Type u) (β : Type v) (cmp : α → α → Ordering) : Type (max u v) := { t : PrefixTreeNode α β // t.WellFormed cmp } open PrefixTreeNode def PrefixTree.empty : PrefixTree α β p := ⟨PrefixTreeNode.empty, WellFormed.emptyWff⟩ instance : Inhabited (PrefixTree α β p) where default := PrefixTree.empty instance : EmptyCollection (PrefixTree α β p) where emptyCollection := PrefixTree.empty @[inline] def PrefixTree.insert (t : PrefixTree α β p) (k : List α) (v : β) : PrefixTree α β p := ⟨t.val.insert p k v, WellFormed.insertWff t.property⟩ @[inline] def PrefixTree.find? (t : PrefixTree α β p) (k : List α) : Option β := t.val.find? p k @[inline] def PrefixTree.foldMatchingM [Monad m] (t : PrefixTree α β p) (k : List α) (init : σ) (f : β → σ → m σ) : m σ := t.val.foldMatchingM p k init f @[inline] def PrefixTree.foldM [Monad m] (t : PrefixTree α β p) (init : σ) (f : β → σ → m σ) : m σ := t.foldMatchingM [] init f @[inline] def PrefixTree.forMatchingM [Monad m] (t : PrefixTree α β p) (k : List α) (f : β → m Unit) : m Unit := t.val.foldMatchingM p k () (fun b _ => f b) @[inline] def PrefixTree.forM [Monad m] (t : PrefixTree α β p) (f : β → m Unit) : m Unit := t.forMatchingM [] f end Lean
91663b6a6dae86f59d55f60593014a51b0320931
947b78d97130d56365ae2ec264df196ce769371a
/src/Lean/Meta/Match/CaseValues.lean
0423e4a06acb93ae7b49a68d5ea479788402184b
[ "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
4,539
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.Subst import Lean.Meta.Tactic.Clear namespace Lean namespace Meta structure CaseValueSubgoal := (mvarId : MVarId) (newH : FVarId) (subst : FVarSubst := {}) instance CaseValueSubgoal.inhabited : Inhabited CaseValueSubgoal := ⟨{ mvarId := arbitrary _, newH := arbitrary _ }⟩ /-- Split goal `... |- C x` into two subgoals `..., (h : x = value) |- C value` `..., (h : x != value) |- C x` where `fvarId` is `x`s id. The type of `x` must have decidable equality. Remark: `subst` field of the second subgoal is equal to the input `subst`. -/ def caseValueAux (mvarId : MVarId) (fvarId : FVarId) (value : Expr) (hName : Name := `h) (subst : FVarSubst := {}) : MetaM (CaseValueSubgoal × CaseValueSubgoal) := withMVarContext mvarId $ do tag ← getMVarTag mvarId; checkNotAssigned mvarId `caseValue; target ← getMVarType mvarId; xEqValue ← mkEq (mkFVar fvarId) value; let xNeqValue := mkApp (mkConst `Not) xEqValue; let thenTarget := Lean.mkForall hName BinderInfo.default xEqValue target; let elseTarget := Lean.mkForall hName BinderInfo.default xNeqValue target; thenMVar ← mkFreshExprSyntheticOpaqueMVar thenTarget tag; elseMVar ← mkFreshExprSyntheticOpaqueMVar elseTarget tag; val ← mkAppOptM `dite #[none, xEqValue, none, thenMVar, elseMVar]; assignExprMVar mvarId val; (elseH, elseMVarId) ← intro1P elseMVar.mvarId!; let elseSubgoal := { mvarId := elseMVarId, newH := elseH, subst := subst : CaseValueSubgoal }; (thenH, thenMVarId) ← intro1P thenMVar.mvarId!; let symm := false; let clearH := false; (thenSubst, thenMVarId) ← substCore thenMVarId thenH symm subst clearH; withMVarContext thenMVarId do { trace! `Meta ("subst domain: " ++ toString thenSubst.domain); let thenH := (thenSubst.get thenH).fvarId!; trace! `Meta "searching for decl"; decl ← getLocalDecl thenH; trace! `Meta "found decl" }; let thenSubgoal := { mvarId := thenMVarId, newH := (thenSubst.get thenH).fvarId!, subst := thenSubst : CaseValueSubgoal }; pure (thenSubgoal, elseSubgoal) def caseValue (mvarId : MVarId) (fvarId : FVarId) (value : Expr) : MetaM (CaseValueSubgoal × CaseValueSubgoal) := do s ← caseValueAux mvarId fvarId value; appendTagSuffix s.1.mvarId `thenBranch; appendTagSuffix s.2.mvarId `elseBranch; pure s structure CaseValuesSubgoal := (mvarId : MVarId) (newHs : Array FVarId := #[]) (subst : FVarSubst := {}) instance CaseValueSubgoals.inhabited : Inhabited CaseValuesSubgoal := ⟨{ mvarId := arbitrary _ }⟩ private def caseValuesAux (hNamePrefix : Name) (fvarId : FVarId) : Nat → MVarId → List Expr → Array FVarId → Array CaseValuesSubgoal → MetaM (Array CaseValuesSubgoal) | i, mvarId, [], hs, subgoals => throwTacticEx `caseValues mvarId "list of values must not be empty" | i, mvarId, v::vs, hs, subgoals => do (thenSubgoal, elseSubgoal) ← caseValueAux mvarId fvarId v (hNamePrefix.appendIndexAfter i) {}; appendTagSuffix thenSubgoal.mvarId ((`case).appendIndexAfter i); thenMVarId ← hs.foldlM (fun thenMVarId h => match thenSubgoal.subst.get h with | Expr.fvar fvarId _ => tryClear thenMVarId fvarId | _ => pure thenMVarId) thenSubgoal.mvarId; let subgoals := subgoals.push { mvarId := thenMVarId, newHs := #[thenSubgoal.newH], subst := thenSubgoal.subst }; match vs with | [] => do appendTagSuffix elseSubgoal.mvarId ((`case).appendIndexAfter (i+1)); pure $ subgoals.push { mvarId := elseSubgoal.mvarId, newHs := hs.push elseSubgoal.newH, subst := {} } | _ => caseValuesAux (i+1) elseSubgoal.mvarId vs (hs.push elseSubgoal.newH) subgoals /-- Split goal `... |- C x` into values.size + 1 subgoals 1) `..., (h_1 : x = value[0]) |- C value[0]` ... n) `..., (h_n : x = value[n - 1]) |- C value[n - 1]` n+1) `..., (h_1 : x != value[0]) ... (h_n : x != value[n-1]) |- C x` where `n = values.size` where `fvarId` is `x`s id. The type of `x` must have decidable equality. Remark: the last subgoal is for the "else" catchall case, and its `subst` is `{}`. Remark: the fiels `newHs` has size 1 forall but the last subgoal. -/ def caseValues (mvarId : MVarId) (fvarId : FVarId) (values : Array Expr) (hNamePrefix := `h) : MetaM (Array CaseValuesSubgoal) := caseValuesAux hNamePrefix fvarId 1 mvarId values.toList #[] #[] end Meta end Lean
d9844a38b0058345898a248f733ba739bc6991c4
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/subterminal.lean
8b93e141b5b258c1f68b95e52b8a9bed80ee2246
[ "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
6,036
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.limits.shapes.binary_products import category_theory.limits.shapes.terminal import category_theory.subobject.mono_over /-! # Subterminal objects Subterminal objects are the objects which can be thought of as subobjects of the terminal object. In fact, the definition can be constructed to not require a terminal object, by defining `A` to be subterminal iff for any `Z`, there is at most one morphism `Z ⟶ A`. An alternate definition is that the diagonal morphism `A ⟶ A ⨯ A` is an isomorphism. In this file we define subterminal objects and show the equivalence of these three definitions. We also construct the subcategory of subterminal objects. ## TODO * Define exponential ideals, and show this subcategory is an exponential ideal. * Use the above to show that in a locally cartesian closed category, every subobject lattice is cartesian closed (equivalently, a Heyting algebra). -/ universes v₁ v₂ u₁ u₂ noncomputable theory namespace category_theory open limits category variables {C : Type u₁} [category.{v₁} C] {A : C} /-- An object `A` is subterminal iff for any `Z`, there is at most one morphism `Z ⟶ A`. -/ def is_subterminal (A : C) : Prop := ∀ ⦃Z : C⦄ (f g : Z ⟶ A), f = g lemma is_subterminal.def : is_subterminal A ↔ ∀ ⦃Z : C⦄ (f g : Z ⟶ A), f = g := iff.rfl /-- If `A` is subterminal, the unique morphism from it to a terminal object is a monomorphism. The converse of `is_subterminal_of_mono_is_terminal_from`. -/ lemma is_subterminal.mono_is_terminal_from (hA : is_subterminal A) {T : C} (hT : is_terminal T) : mono (hT.from A) := { right_cancellation := λ Z g h _, hA _ _ } /-- If `A` is subterminal, the unique morphism from it to the terminal object is a monomorphism. The converse of `is_subterminal_of_mono_terminal_from`. -/ lemma is_subterminal.mono_terminal_from [has_terminal C] (hA : is_subterminal A) : mono (terminal.from A) := hA.mono_is_terminal_from terminal_is_terminal /-- If the unique morphism from `A` to a terminal object is a monomorphism, `A` is subterminal. The converse of `is_subterminal.mono_is_terminal_from`. -/ lemma is_subterminal_of_mono_is_terminal_from {T : C} (hT : is_terminal T) [mono (hT.from A)] : is_subterminal A := λ Z f g, by { rw ← cancel_mono (hT.from A), apply hT.hom_ext } /-- If the unique morphism from `A` to the terminal object is a monomorphism, `A` is subterminal. The converse of `is_subterminal.mono_terminal_from`. -/ lemma is_subterminal_of_mono_terminal_from [has_terminal C] [mono (terminal.from A)] : is_subterminal A := λ Z f g, by { rw ← cancel_mono (terminal.from A), apply subsingleton.elim } lemma is_subterminal_of_is_terminal {T : C} (hT : is_terminal T) : is_subterminal T := λ Z f g, hT.hom_ext _ _ lemma is_subterminal_of_terminal [has_terminal C] : is_subterminal (⊤_ C) := λ Z f g, subsingleton.elim _ _ /-- If `A` is subterminal, its diagonal morphism is an isomorphism. The converse of `is_subterminal_of_is_iso_diag`. -/ lemma is_subterminal.is_iso_diag (hA : is_subterminal A) [has_binary_product A A] : is_iso (diag A) := ⟨⟨limits.prod.fst, ⟨by simp, by { rw is_subterminal.def at hA, tidy }⟩⟩⟩ /-- If the diagonal morphism of `A` is an isomorphism, then it is subterminal. The converse of `is_subterminal.is_iso_diag`. -/ lemma is_subterminal_of_is_iso_diag [has_binary_product A A] [is_iso (diag A)] : is_subterminal A := λ Z f g, begin have : (limits.prod.fst : A ⨯ A ⟶ _) = limits.prod.snd, { simp [←cancel_epi (diag A)] }, rw [←prod.lift_fst f g, this, prod.lift_snd], end /-- If `A` is subterminal, it is isomorphic to `A ⨯ A`. -/ @[simps] def is_subterminal.iso_diag (hA : is_subterminal A) [has_binary_product A A] : A ⨯ A ≅ A := begin letI := is_subterminal.is_iso_diag hA, apply (as_iso (diag A)).symm, end variables (C) /-- The (full sub)category of subterminal objects. TODO: If `C` is the category of sheaves on a topological space `X`, this category is equivalent to the lattice of open subsets of `X`. More generally, if `C` is a topos, this is the lattice of "external truth values". -/ @[derive category] def subterminals (C : Type u₁) [category.{v₁} C] := {A : C // is_subterminal A} instance [has_terminal C] : inhabited (subterminals C) := ⟨⟨⊤_ C, is_subterminal_of_terminal⟩⟩ /-- The inclusion of the subterminal objects into the original category. -/ @[derive [full, faithful], simps] def subterminal_inclusion : subterminals C ⥤ C := full_subcategory_inclusion _ instance subterminals_thin (X Y : subterminals C) : subsingleton (X ⟶ Y) := ⟨λ f g, Y.2 f g⟩ /-- The category of subterminal objects is equivalent to the category of monomorphisms to the terminal object (which is in turn equivalent to the subobjects of the terminal object). -/ @[simps] def subterminals_equiv_mono_over_terminal [has_terminal C] : subterminals C ≌ mono_over (⊤_ C) := { functor := { obj := λ X, ⟨over.mk (terminal.from X.1), X.2.mono_terminal_from⟩, map := λ X Y f, mono_over.hom_mk f (by ext1 ⟨⟩) }, inverse := { obj := λ X, ⟨X.val.left, λ Z f g, by { rw ← cancel_mono X.arrow, apply subsingleton.elim }⟩, map := λ X Y f, f.1 }, unit_iso := { hom := { app := λ X, 𝟙 _ }, inv := { app := λ X, 𝟙 _ } }, counit_iso := { hom := { app := λ X, over.hom_mk (𝟙 _) }, inv := { app := λ X, over.hom_mk (𝟙 _) } } } @[simp] lemma subterminals_to_mono_over_terminal_comp_forget [has_terminal C] : (subterminals_equiv_mono_over_terminal C).functor ⋙ mono_over.forget _ ⋙ over.forget _ = subterminal_inclusion C := rfl @[simp] lemma mono_over_terminal_to_subterminals_comp [has_terminal C] : (subterminals_equiv_mono_over_terminal C).inverse ⋙ subterminal_inclusion C = mono_over.forget _ ⋙ over.forget _ := rfl end category_theory
059decb82556686c3ea9d20970eca548966bbe60
c777c32c8e484e195053731103c5e52af26a25d1
/src/analysis/inner_product_space/orientation.lean
d962ce8bfe730e86f72b25470bc790586a1fc8ba
[ "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
14,717
lean
/- Copyright (c) 2022 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers, Heather Macbeth -/ import analysis.inner_product_space.gram_schmidt_ortho import linear_algebra.orientation /-! # Orientations of real inner product spaces. This file provides definitions and proves lemmas about orientations of real inner product spaces. ## Main definitions * `orthonormal_basis.adjust_to_orientation` takes an orthonormal basis and an orientation, and returns an orthonormal basis with that orientation: either the original orthonormal basis, or one constructed by negating a single (arbitrary) basis vector. * `orientation.fin_orthonormal_basis` is an orthonormal basis, indexed by `fin n`, with the given orientation. * `orientation.volume_form` is a nonvanishing top-dimensional alternating form on an oriented real inner product space, uniquely defined by compatibility with the orientation and inner product structure. ## Main theorems * `orientation.volume_form_apply_le` states that the result of applying the volume form to a set of `n` vectors, where `n` is the dimension the inner product space, is bounded by the product of the lengths of the vectors. * `orientation.abs_volume_form_apply_of_pairwise_orthogonal` states that the result of applying the volume form to a set of `n` orthogonal vectors, where `n` is the dimension the inner product space, is equal up to sign to the product of the lengths of the vectors. -/ noncomputable theory variables {E : Type*} [normed_add_comm_group E] [inner_product_space ℝ E] open finite_dimensional open_locale big_operators real_inner_product_space namespace orthonormal_basis variables {ι : Type*} [fintype ι] [decidable_eq ι] [ne : nonempty ι] (e f : orthonormal_basis ι ℝ E) (x : orientation ℝ E ι) /-- The change-of-basis matrix between two orthonormal bases with the same orientation has determinant 1. -/ lemma det_to_matrix_orthonormal_basis_of_same_orientation (h : e.to_basis.orientation = f.to_basis.orientation) : e.to_basis.det f = 1 := begin apply (e.det_to_matrix_orthonormal_basis_real f).resolve_right, have : 0 < e.to_basis.det f, { rw e.to_basis.orientation_eq_iff_det_pos at h, simpa using h }, linarith, end /-- The change-of-basis matrix between two orthonormal bases with the opposite orientations has determinant -1. -/ lemma det_to_matrix_orthonormal_basis_of_opposite_orientation (h : e.to_basis.orientation ≠ f.to_basis.orientation) : e.to_basis.det f = -1 := begin contrapose! h, simp [e.to_basis.orientation_eq_iff_det_pos, (e.det_to_matrix_orthonormal_basis_real f).resolve_right h], end variables {e f} /-- Two orthonormal bases with the same orientation determine the same "determinant" top-dimensional form on `E`, and conversely. -/ lemma same_orientation_iff_det_eq_det : e.to_basis.det = f.to_basis.det ↔ e.to_basis.orientation = f.to_basis.orientation := begin split, { intros h, dsimp [basis.orientation], congr' }, { intros h, rw e.to_basis.det.eq_smul_basis_det f.to_basis, simp [e.det_to_matrix_orthonormal_basis_of_same_orientation f h], }, end variables (e f) /-- Two orthonormal bases with opposite orientations determine opposite "determinant" top-dimensional forms on `E`. -/ lemma det_eq_neg_det_of_opposite_orientation (h : e.to_basis.orientation ≠ f.to_basis.orientation) : e.to_basis.det = -f.to_basis.det := begin rw e.to_basis.det.eq_smul_basis_det f.to_basis, simp [e.det_to_matrix_orthonormal_basis_of_opposite_orientation f h], end section adjust_to_orientation include ne /-- `orthonormal_basis.adjust_to_orientation`, applied to an orthonormal basis, preserves the property of orthonormality. -/ lemma orthonormal_adjust_to_orientation : orthonormal ℝ (e.to_basis.adjust_to_orientation x) := begin apply e.orthonormal.orthonormal_of_forall_eq_or_eq_neg, simpa using e.to_basis.adjust_to_orientation_apply_eq_or_eq_neg x end /-- Given an orthonormal basis and an orientation, return an orthonormal basis giving that orientation: either the original basis, or one constructed by negating a single (arbitrary) basis vector. -/ def adjust_to_orientation : orthonormal_basis ι ℝ E := (e.to_basis.adjust_to_orientation x).to_orthonormal_basis (e.orthonormal_adjust_to_orientation x) lemma to_basis_adjust_to_orientation : (e.adjust_to_orientation x).to_basis = e.to_basis.adjust_to_orientation x := (e.to_basis.adjust_to_orientation x).to_basis_to_orthonormal_basis _ /-- `adjust_to_orientation` gives an orthonormal basis with the required orientation. -/ @[simp] lemma orientation_adjust_to_orientation : (e.adjust_to_orientation x).to_basis.orientation = x := begin rw e.to_basis_adjust_to_orientation, exact e.to_basis.orientation_adjust_to_orientation x, end /-- Every basis vector from `adjust_to_orientation` is either that from the original basis or its negation. -/ lemma adjust_to_orientation_apply_eq_or_eq_neg (i : ι) : e.adjust_to_orientation x i = e i ∨ e.adjust_to_orientation x i = -(e i) := by simpa [← e.to_basis_adjust_to_orientation] using e.to_basis.adjust_to_orientation_apply_eq_or_eq_neg x i lemma det_adjust_to_orientation : (e.adjust_to_orientation x).to_basis.det = e.to_basis.det ∨ (e.adjust_to_orientation x).to_basis.det = -e.to_basis.det := by simpa using e.to_basis.det_adjust_to_orientation x lemma abs_det_adjust_to_orientation (v : ι → E) : |(e.adjust_to_orientation x).to_basis.det v| = |e.to_basis.det v| := by simp [to_basis_adjust_to_orientation] end adjust_to_orientation end orthonormal_basis namespace orientation variables {n : ℕ} open orthonormal_basis /-- An orthonormal basis, indexed by `fin n`, with the given orientation. -/ protected def fin_orthonormal_basis (hn : 0 < n) (h : finrank ℝ E = n) (x : orientation ℝ E (fin n)) : orthonormal_basis (fin n) ℝ E := begin haveI := fin.pos_iff_nonempty.1 hn, haveI := finite_dimensional_of_finrank (h.symm ▸ hn : 0 < finrank ℝ E), exact ((std_orthonormal_basis _ _).reindex $ fin_congr h).adjust_to_orientation x end /-- `orientation.fin_orthonormal_basis` gives a basis with the required orientation. -/ @[simp] lemma fin_orthonormal_basis_orientation (hn : 0 < n) (h : finrank ℝ E = n) (x : orientation ℝ E (fin n)) : (x.fin_orthonormal_basis hn h).to_basis.orientation = x := begin haveI := fin.pos_iff_nonempty.1 hn, haveI := finite_dimensional_of_finrank (h.symm ▸ hn : 0 < finrank ℝ E), exact ((std_orthonormal_basis _ _).reindex $ fin_congr h).orientation_adjust_to_orientation x end section volume_form variables [_i : fact (finrank ℝ E = n)] (o : orientation ℝ E (fin n)) include _i o /-- The volume form on an oriented real inner product space, a nonvanishing top-dimensional alternating form uniquely defined by compatibility with the orientation and inner product structure. -/ @[irreducible] def volume_form : alternating_map ℝ E ℝ (fin n) := begin classical, unfreezingI { cases n }, { let opos : alternating_map ℝ E ℝ (fin 0) := alternating_map.const_of_is_empty ℝ E (1:ℝ), exact o.eq_or_eq_neg_of_is_empty.by_cases (λ _, opos) (λ _, -opos) }, { exact (o.fin_orthonormal_basis n.succ_pos _i.out).to_basis.det } end omit _i o @[simp] lemma volume_form_zero_pos [_i : fact (finrank ℝ E = 0)] : orientation.volume_form (positive_orientation : orientation ℝ E (fin 0)) = alternating_map.const_linear_equiv_of_is_empty 1 := by simp [volume_form, or.by_cases, if_pos] lemma volume_form_zero_neg [_i : fact (finrank ℝ E = 0)] : orientation.volume_form (-positive_orientation : orientation ℝ E (fin 0)) = - alternating_map.const_linear_equiv_of_is_empty 1 := begin dsimp [volume_form, or.by_cases, positive_orientation], apply if_neg, rw [ray_eq_iff, same_ray_comm], intros h, simpa using congr_arg alternating_map.const_linear_equiv_of_is_empty.symm (eq_zero_of_same_ray_self_neg h), end include _i o /-- The volume form on an oriented real inner product space can be evaluated as the determinant with respect to any orthonormal basis of the space compatible with the orientation. -/ lemma volume_form_robust (b : orthonormal_basis (fin n) ℝ E) (hb : b.to_basis.orientation = o) : o.volume_form = b.to_basis.det := begin unfreezingI { cases n }, { classical, have : o = positive_orientation := hb.symm.trans b.to_basis.orientation_is_empty, simp [volume_form, or.by_cases, dif_pos this] }, { dsimp [volume_form], rw [same_orientation_iff_det_eq_det, hb], exact o.fin_orthonormal_basis_orientation _ _ }, end /-- The volume form on an oriented real inner product space can be evaluated as the determinant with respect to any orthonormal basis of the space compatible with the orientation. -/ lemma volume_form_robust_neg (b : orthonormal_basis (fin n) ℝ E) (hb : b.to_basis.orientation ≠ o) : o.volume_form = - b.to_basis.det := begin unfreezingI { cases n }, { classical, have : positive_orientation ≠ o := by rwa b.to_basis.orientation_is_empty at hb, simp [volume_form, or.by_cases, dif_neg this.symm] }, let e : orthonormal_basis (fin n.succ) ℝ E := o.fin_orthonormal_basis n.succ_pos (fact.out _), dsimp [volume_form], apply e.det_eq_neg_det_of_opposite_orientation b, convert hb.symm, exact o.fin_orthonormal_basis_orientation _ _, end @[simp] lemma volume_form_neg_orientation : (-o).volume_form = - o.volume_form := begin unfreezingI { cases n }, { refine o.eq_or_eq_neg_of_is_empty.elim _ _; rintros rfl; simp [volume_form_zero_neg] }, let e : orthonormal_basis (fin n.succ) ℝ E := o.fin_orthonormal_basis n.succ_pos (fact.out _), have h₁ : e.to_basis.orientation = o := o.fin_orthonormal_basis_orientation _ _, have h₂ : e.to_basis.orientation ≠ -o, { symmetry, rw [e.to_basis.orientation_ne_iff_eq_neg, h₁] }, rw [o.volume_form_robust e h₁, (-o).volume_form_robust_neg e h₂], end lemma volume_form_robust' (b : orthonormal_basis (fin n) ℝ E) (v : fin n → E) : |o.volume_form v| = |b.to_basis.det v| := begin unfreezingI { cases n }, { refine o.eq_or_eq_neg_of_is_empty.elim _ _; rintros rfl; simp }, { rw [o.volume_form_robust (b.adjust_to_orientation o) (b.orientation_adjust_to_orientation o), b.abs_det_adjust_to_orientation] }, end /-- Let `v` be an indexed family of `n` vectors in an oriented `n`-dimensional real inner product space `E`. The output of the volume form of `E` when evaluated on `v` is bounded in absolute value by the product of the norms of the vectors `v i`. -/ lemma abs_volume_form_apply_le (v : fin n → E) : |o.volume_form v| ≤ ∏ i : fin n, ‖v i‖ := begin unfreezingI { cases n }, { refine o.eq_or_eq_neg_of_is_empty.elim _ _; rintros rfl; simp }, haveI : finite_dimensional ℝ E := fact_finite_dimensional_of_finrank_eq_succ n, have : finrank ℝ E = fintype.card (fin n.succ) := by simpa using _i.out, let b : orthonormal_basis (fin n.succ) ℝ E := gram_schmidt_orthonormal_basis this v, have hb : b.to_basis.det v = ∏ i, ⟪b i, v i⟫ := gram_schmidt_orthonormal_basis_det this v, rw [o.volume_form_robust' b, hb, finset.abs_prod], apply finset.prod_le_prod, { intros i hi, positivity }, intros i hi, convert abs_real_inner_le_norm (b i) (v i), simp [b.orthonormal.1 i], end lemma volume_form_apply_le (v : fin n → E) : o.volume_form v ≤ ∏ i : fin n, ‖v i‖ := (le_abs_self _).trans (o.abs_volume_form_apply_le v) /-- Let `v` be an indexed family of `n` orthogonal vectors in an oriented `n`-dimensional real inner product space `E`. The output of the volume form of `E` when evaluated on `v` is, up to sign, the product of the norms of the vectors `v i`. -/ lemma abs_volume_form_apply_of_pairwise_orthogonal {v : fin n → E} (hv : pairwise (λ i j, ⟪v i, v j⟫ = 0)) : |o.volume_form v| = ∏ i : fin n, ‖v i‖ := begin unfreezingI { cases n }, { refine o.eq_or_eq_neg_of_is_empty.elim _ _; rintros rfl; simp }, haveI : finite_dimensional ℝ E := fact_finite_dimensional_of_finrank_eq_succ n, have hdim : finrank ℝ E = fintype.card (fin n.succ) := by simpa using _i.out, let b : orthonormal_basis (fin n.succ) ℝ E := gram_schmidt_orthonormal_basis hdim v, have hb : b.to_basis.det v = ∏ i, ⟪b i, v i⟫ := gram_schmidt_orthonormal_basis_det hdim v, rw [o.volume_form_robust' b, hb, finset.abs_prod], by_cases h : ∃ i, v i = 0, obtain ⟨i, hi⟩ := h, { rw [finset.prod_eq_zero (finset.mem_univ i), finset.prod_eq_zero (finset.mem_univ i)]; simp [hi] }, push_neg at h, congr, ext i, have hb : b i = ‖v i‖⁻¹ • v i := gram_schmidt_orthonormal_basis_apply_of_orthogonal hdim hv (h i), simp only [hb, inner_smul_left, real_inner_self_eq_norm_mul_norm, is_R_or_C.conj_to_real], rw abs_of_nonneg, { have : ‖v i‖ ≠ 0 := by simpa using h i, field_simp }, { positivity }, end /-- The output of the volume form of an oriented real inner product space `E` when evaluated on an orthonormal basis is ±1. -/ lemma abs_volume_form_apply_of_orthonormal (v : orthonormal_basis (fin n) ℝ E) : |o.volume_form v| = 1 := by simpa [o.volume_form_robust' v v] using congr_arg abs v.to_basis.det_self lemma volume_form_map {F : Type*} [normed_add_comm_group F] [inner_product_space ℝ F] [fact (finrank ℝ F = n)] (φ : E ≃ₗᵢ[ℝ] F) (x : fin n → F) : (orientation.map (fin n) φ.to_linear_equiv o).volume_form x = o.volume_form (φ.symm ∘ x) := begin unfreezingI { cases n }, { refine o.eq_or_eq_neg_of_is_empty.elim _ _; rintros rfl; simp }, let e : orthonormal_basis (fin n.succ) ℝ E := o.fin_orthonormal_basis n.succ_pos (fact.out _), have he : e.to_basis.orientation = o := (o.fin_orthonormal_basis_orientation n.succ_pos (fact.out _)), have heφ : (e.map φ).to_basis.orientation = orientation.map (fin n.succ) φ.to_linear_equiv o, { rw ← he, exact (e.to_basis.orientation_map φ.to_linear_equiv) }, rw (orientation.map (fin n.succ) φ.to_linear_equiv o).volume_form_robust (e.map φ) heφ, rw o.volume_form_robust e he, simp, end /-- The volume form is invariant under pullback by a positively-oriented isometric automorphism. -/ lemma volume_form_comp_linear_isometry_equiv (φ : E ≃ₗᵢ[ℝ] E) (hφ : 0 < (φ.to_linear_equiv : E →ₗ[ℝ] E).det) (x : fin n → E) : o.volume_form (φ ∘ x) = o.volume_form x := begin convert o.volume_form_map φ (φ ∘ x), { symmetry, rwa ← o.map_eq_iff_det_pos φ.to_linear_equiv at hφ, rw [_i.out, fintype.card_fin] }, { ext, simp } end end volume_form end orientation
9157d4f835a79650f1c512b620530a41e132c81c
26ac254ecb57ffcb886ff709cf018390161a9225
/src/measure_theory/measure_space.lean
095d8784bc092aeab313667daacf61ac6082391b
[ "Apache-2.0" ]
permissive
eric-wieser/mathlib
42842584f584359bbe1fc8b88b3ff937c8acd72d
d0df6b81cd0920ad569158c06a3fd5abb9e63301
refs/heads/master
1,669,546,404,255
1,595,254,668,000
1,595,254,668,000
281,173,504
0
0
Apache-2.0
1,595,263,582,000
1,595,263,581,000
null
UTF-8
Lean
false
false
54,363
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 measure_theory.outer_measure import order.filter.countable_Inter /-! # Measure spaces Given a measurable space `α`, a measure on `α` is a function that sends measurable sets to the extended nonnegative reals that satisfies the following conditions: 1. `μ ∅ = 0`; 2. `μ` is countably additive. This means that the measure of a countable union of pairwise disjoint sets is equal to the measure of the individual sets. Every measure can be canonically extended to an outer measure, so that it assigns values to all subsets, not just the measurable subsets. On the other hand, a measure that is countably additive on measurable sets can be restricted to measurable sets to obtain a measure. In this file a measure is defined to be an outer measure that is countably additive on measurable sets, with the additional assumption that the outer measure is the canonical extension of the restricted measure. In the first part of the file we define operations on arbitrary functions defined on measurable sets. Measures on `α` form a complete lattice, and are closed under scalar multiplication with `ennreal`. Given a measure, the null sets are the sets where `μ s = 0`, where `μ` denotes the corresponding outer measure (so `s` might not be measurable). We can then define the completion of `μ` as the measure on the least `σ`-algebra that also contains all null sets, by defining the measure to be `0` on the null sets. ## Main statements * `completion` is the completion of a measure to all null measurable sets. * `measure.of_measurable` and `outer_measure.to_measure` are two important ways to define a measure. ## Implementation notes Given `μ : measure α`, `μ s` is the value of the *outer measure* applied to `s`. This conveniently allows us to apply the measure to sets without proving that they are measurable. We get countable subadditivity for all sets, but only countable additivity for measurable sets. You often don't want to define a measure via its constructor. Two ways that are sometimes more convenient: * `measure.of_measurable` is a way to define a measure by only giving its value on measurable sets and proving the properties (1) and (2) mentioned above. * `outer_measure.to_measure` is a way of obtaining a measure from an outer measure by showing that all measurable sets in the measurable space are Carathéodory measurable. A `measure_space` is a class that is a measurable space with a canonical measure. The measure is denoted `volume`. ## References * <https://en.wikipedia.org/wiki/Measure_(mathematics)> * <https://en.wikipedia.org/wiki/Complete_measure> * <https://en.wikipedia.org/wiki/Almost_everywhere> ## Tags measure, almost everywhere, measure space, completion, null set, null measurable set -/ noncomputable theory open classical set filter finset function open_locale classical topological_space big_operators filter universes u v w x namespace measure_theory /- We first consider operations on arbitrary functions defined on measurable sets. -/ section of_measurable parameters {α : Type*} [measurable_space α] parameters (m : Π (s : set α), is_measurable s → ennreal) parameters (m0 : m ∅ is_measurable.empty = 0) include m0 /-- We can trivially extend a function defined on measurable sets to all sets by defining it to be `∞` on the non-measurable sets. `measure'` is mainly used to derive the outer measure, for the main `measure` projection. -/ def measure' (s : set α) : ennreal := ⨅ h : is_measurable s, m s h lemma measure'_eq {s} (h : is_measurable s) : measure' s = m s h := by simp [measure', h] lemma measure'_empty : measure' ∅ = 0 := (measure'_eq is_measurable.empty).trans m0 lemma measure'_Union_nat {f : ℕ → set α} (hm : ∀i, is_measurable (f i)) (mU : m (⋃i, f i) (is_measurable.Union hm) = (∑'i, m (f i) (hm i))) : measure' (⋃i, f i) = (∑'i, measure' (f i)) := (measure'_eq _).trans $ mU.trans $ by congr; funext i; rw measure'_eq /-- Given an arbitrary function on measurable sets, we can define the outer measure corresponding to it (this is the unique maximal outer measure that is at most `m` on measurable sets). -/ def outer_measure' : outer_measure α := outer_measure.of_function measure' measure'_empty lemma measure'_Union_le_tsum_nat' (mU : ∀ {f : ℕ → set α} (hm : ∀i, is_measurable (f i)), m (⋃i, f i) (is_measurable.Union hm) ≤ (∑'i, m (f i) (hm i))) (s : ℕ → set α) : measure' (⋃i, s i) ≤ (∑'i, measure' (s i)) := begin by_cases h : ∀i, is_measurable (s i), { rw [measure'_eq _ _ (is_measurable.Union h), congr_arg tsum _], {apply mU h}, funext i, apply measure'_eq _ _ (h i) }, { cases not_forall.1 h with i hi, exact le_trans (le_infi $ λ h, hi.elim h) (ennreal.le_tsum i) } end parameter (mU : ∀ {f : ℕ → set α} (hm : ∀i, is_measurable (f i)), pairwise (disjoint on f) → m (⋃i, f i) (is_measurable.Union hm) = (∑'i, m (f i) (hm i))) include mU lemma measure'_Union {β} [encodable β] {f : β → set α} (hd : pairwise (disjoint on f)) (hm : ∀i, is_measurable (f i)) : measure' (⋃i, f i) = (∑'i, measure' (f i)) := begin rw [← encodable.Union_decode2, ← tsum_Union_decode2], { exact measure'_Union_nat _ _ (λ n, encodable.Union_decode2_cases is_measurable.empty hm) (mU _ (encodable.Union_decode2_disjoint_on hd)) }, { apply measure'_empty }, end lemma measure'_union {s₁ s₂ : set α} (hd : disjoint s₁ s₂) (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) : measure' (s₁ ∪ s₂) = measure' s₁ + measure' s₂ := begin rw [union_eq_Union, measure'_Union _ _ @mU (pairwise_disjoint_on_bool.2 hd) (bool.forall_bool.2 ⟨h₂, h₁⟩), tsum_fintype], change _+_ = _, simp end lemma measure'_mono {s₁ s₂ : set α} (h₁ : is_measurable s₁) (hs : s₁ ⊆ s₂) : measure' s₁ ≤ measure' s₂ := le_infi $ λ h₂, begin have := measure'_union _ _ @mU disjoint_diff h₁ (h₂.diff h₁), rw union_diff_cancel hs at this, rw ← measure'_eq m m0 _, exact le_iff_exists_add.2 ⟨_, this⟩ end lemma measure'_Union_le_tsum_nat : ∀ (s : ℕ → set α), measure' (⋃i, s i) ≤ (∑'i, measure' (s i)) := measure'_Union_le_tsum_nat' $ λ f h, begin simp [Union_disjointed.symm] {single_pass := tt}, rw [mU (is_measurable.disjointed h) disjoint_disjointed], refine ennreal.tsum_le_tsum (λ i, _), rw [← measure'_eq m m0, ← measure'_eq m m0], exact measure'_mono _ _ @mU (is_measurable.disjointed h _) (inter_subset_left _ _) end lemma outer_measure'_eq {s : set α} (hs : is_measurable s) : outer_measure' s = m s hs := by rw ← measure'_eq m m0 hs; exact (le_antisymm (outer_measure.of_function_le _ _ _) $ le_infi $ λ f, le_infi $ λ hf, le_trans (measure'_mono _ _ @mU hs hf) $ measure'_Union_le_tsum_nat _ _ @mU _) lemma outer_measure'_eq_measure' {s : set α} (hs : is_measurable s) : outer_measure' s = measure' s := by rw [measure'_eq m m0 hs, outer_measure'_eq m m0 @mU hs] end of_measurable namespace outer_measure variables {α : Type*} [measurable_space α] (m : outer_measure α) /-- Given an outer measure `m` we can forget its value on non-measurable sets, and then consider `m.trim`, the unique maximal outer measure less than that function. -/ def trim : outer_measure α := outer_measure' (λ s _, m s) m.empty theorem trim_ge : m ≤ m.trim := λ s, le_infi $ λ f, le_infi $ λ hs, le_trans (m.mono hs) $ le_trans (m.Union_nat f) $ ennreal.tsum_le_tsum $ λ i, le_infi $ λ hf, le_refl _ theorem trim_eq {s : set α} (hs : is_measurable s) : m.trim s = m s := le_antisymm (le_trans (of_function_le _ _ _) (infi_le _ hs)) (trim_ge _ _) theorem trim_congr {m₁ m₂ : outer_measure α} (H : ∀ {s : set α}, is_measurable s → m₁ s = m₂ s) : m₁.trim = m₂.trim := by unfold trim; congr; funext s hs; exact H hs theorem trim_le_trim {m₁ m₂ : outer_measure α} (H : m₁ ≤ m₂) : m₁.trim ≤ m₂.trim := λ s, infi_le_infi $ λ f, infi_le_infi $ λ hs, ennreal.tsum_le_tsum $ λ b, infi_le_infi $ λ hf, H _ theorem le_trim_iff {m₁ m₂ : outer_measure α} : m₁ ≤ m₂.trim ↔ ∀ s, is_measurable s → m₁ s ≤ m₂ s := le_of_function.trans $ forall_congr $ λ s, le_infi_iff theorem trim_eq_infi (s : set α) : m.trim s = ⨅ t (st : s ⊆ t) (ht : is_measurable t), m t := begin refine le_antisymm (le_infi $ λ t, le_infi $ λ st, le_infi $ λ ht, _) (le_infi $ λ f, le_infi $ λ hf, _), { rw ← trim_eq m ht, exact (trim m).mono st }, { by_cases h : ∀i, is_measurable (f i), { refine infi_le_of_le _ (infi_le_of_le hf $ infi_le_of_le (is_measurable.Union h) _), rw congr_arg tsum _, {exact m.Union_nat _}, funext i, exact measure'_eq _ _ (h i) }, { cases not_forall.1 h with i hi, exact le_trans (le_infi $ λ h, hi.elim h) (ennreal.le_tsum i) } } end theorem trim_eq_infi' (s : set α) : m.trim s = ⨅ t : {t // s ⊆ t ∧ is_measurable t}, m t := by simp [infi_subtype, infi_and, trim_eq_infi] theorem trim_trim (m : outer_measure α) : m.trim.trim = m.trim := le_antisymm (le_trim_iff.2 $ λ s hs, by simp [trim_eq _ hs, le_refl]) (trim_ge _) @[simp] theorem trim_zero : (0 : outer_measure α).trim = 0 := ext $ λ s, le_antisymm (le_trans ((trim 0).mono (subset_univ s)) $ le_of_eq $ trim_eq _ is_measurable.univ) (zero_le _) theorem trim_add (m₁ m₂ : outer_measure α) : (m₁ + m₂).trim = m₁.trim + m₂.trim := ext $ λ s, begin simp only [trim_eq_infi', add_apply], rw ennreal.infi_add_infi, rintro ⟨t₁, st₁, ht₁⟩ ⟨t₂, st₂, ht₂⟩, exact ⟨⟨_, subset_inter_iff.2 ⟨st₁, st₂⟩, ht₁.inter ht₂⟩, add_le_add (m₁.mono' (inter_subset_left _ _)) (m₂.mono' (inter_subset_right _ _))⟩, end theorem trim_sum_ge {ι} (m : ι → outer_measure α) : sum (λ i, (m i).trim) ≤ (sum m).trim := λ s, by simp [trim_eq_infi]; exact λ t st ht, ennreal.tsum_le_tsum (λ i, infi_le_of_le t $ infi_le_of_le st $ infi_le _ ht) lemma exists_is_measurable_superset_of_trim_eq_zero {m : outer_measure α} {s : set α} (h : m.trim s = 0) : ∃t, s ⊆ t ∧ is_measurable t ∧ m t = 0 := begin erw [trim_eq_infi, infi_eq_bot] at h, choose t ht using show ∀n:ℕ, ∃t, s ⊆ t ∧ is_measurable t ∧ m t < n⁻¹, { assume n, have : (0 : ennreal) < n⁻¹ := (ennreal.inv_pos.2 $ ennreal.nat_ne_top _), rcases h _ this with ⟨t, ht⟩, use [t], simpa only [infi_lt_iff, exists_prop] using ht }, refine ⟨⋂n, t n, subset_Inter (λn, (ht n).1), is_measurable.Inter (λn, (ht n).2.1), _⟩, refine le_antisymm _ (zero_le _), refine le_of_tendsto_of_tendsto tendsto_const_nhds ennreal.tendsto_inv_nat_nhds_zero (eventually_of_forall $ assume n, _), exact le_trans (m.mono' $ Inter_subset _ _) (le_of_lt (ht n).2.2) end theorem trim_smul (c : ennreal) (m : outer_measure α) : (c • m).trim = c • m.trim := begin ext1 s, simp only [trim_eq_infi', smul_apply], haveI : nonempty {t // s ⊆ t ∧ is_measurable t} := ⟨⟨univ, subset_univ _, is_measurable.univ⟩⟩, refine ennreal.infi_mul_left (assume hc hs, _), rw ← trim_eq_infi' at hs, simpa [and_assoc] using exists_is_measurable_superset_of_trim_eq_zero hs end end outer_measure /-- A measure is defined to be an outer measure that is countably additive on measurable sets, with the additional assumption that the outer measure is the canonical extension of the restricted measure. -/ structure measure (α : Type*) [measurable_space α] extends outer_measure α := (m_Union {f : ℕ → set α} : (∀i, is_measurable (f i)) → pairwise (disjoint on f) → measure_of (⋃i, f i) = (∑'i, measure_of (f i))) (trimmed : to_outer_measure.trim = to_outer_measure) /-- Measure projections for a measure space. For measurable sets this returns the measure assigned by the `measure_of` field in `measure`. But we can extend this to _all_ sets, but using the outer measure. This gives us monotonicity and subadditivity for all sets. -/ instance measure.has_coe_to_fun {α} [measurable_space α] : has_coe_to_fun (measure α) := ⟨λ _, set α → ennreal, λ m, m.to_outer_measure⟩ namespace measure /-- Obtain a measure by giving a countably additive function that sends `∅` to `0`. -/ def of_measurable {α} [measurable_space α] (m : Π (s : set α), is_measurable s → ennreal) (m0 : m ∅ is_measurable.empty = 0) (mU : ∀ {f : ℕ → set α} (h : ∀i, is_measurable (f i)), pairwise (disjoint on f) → m (⋃i, f i) (is_measurable.Union h) = (∑'i, m (f i) (h i))) : measure α := { m_Union := λ f hf hd, show outer_measure' m m0 (Union f) = ∑' i, outer_measure' m m0 (f i), begin rw [outer_measure'_eq m m0 @mU, mU hf hd], congr, funext n, rw outer_measure'_eq m m0 @mU end, trimmed := show (outer_measure' m m0).trim = outer_measure' m m0, begin unfold outer_measure.trim, congr, funext s hs, exact outer_measure'_eq m m0 @mU hs end, ..outer_measure' m m0 } lemma of_measurable_apply {α} [measurable_space α] {m : Π (s : set α), is_measurable s → ennreal} {m0 : m ∅ is_measurable.empty = 0} {mU : ∀ {f : ℕ → set α} (h : ∀i, is_measurable (f i)), pairwise (disjoint on f) → m (⋃i, f i) (is_measurable.Union h) = (∑'i, m (f i) (h i))} (s : set α) (hs : is_measurable s) : of_measurable m m0 @mU s = m s hs := outer_measure'_eq m m0 @mU hs lemma to_outer_measure_injective {α} [measurable_space α] : injective (to_outer_measure : measure α → outer_measure α) := λ ⟨m₁, u₁, h₁⟩ ⟨m₂, u₂, h₂⟩ h, by { congr, exact h } @[ext] lemma ext {α} [measurable_space α] {μ₁ μ₂ : measure α} (h : ∀s, is_measurable s → μ₁ s = μ₂ s) : μ₁ = μ₂ := to_outer_measure_injective $ by rw [← trimmed, outer_measure.trim_congr h, trimmed] end measure section variables {α : Type*} {β : Type*} {ι : Type*} [measurable_space α] {μ μ₁ μ₂ : measure α} {s s₁ s₂ : set α} @[simp] lemma coe_to_outer_measure : ⇑μ.to_outer_measure = μ := rfl lemma to_outer_measure_apply (s) : μ.to_outer_measure s = μ s := rfl lemma measure_eq_trim (s) : μ s = μ.to_outer_measure.trim s := by rw μ.trimmed; refl lemma measure_eq_infi (s) : μ s = ⨅ t (st : s ⊆ t) (ht : is_measurable t), μ t := by rw [measure_eq_trim, outer_measure.trim_eq_infi]; refl lemma measure_eq_outer_measure' : μ s = outer_measure' (λ s _, μ s) μ.empty s := measure_eq_trim _ lemma to_outer_measure_eq_outer_measure' : μ.to_outer_measure = outer_measure' (λ s _, μ s) μ.empty := μ.trimmed.symm lemma measure_eq_measure' (hs : is_measurable s) : μ s = measure' (λ s _, μ s) μ.empty s := by rw [measure_eq_outer_measure', outer_measure'_eq_measure' (λ s _, μ s) _ μ.m_Union hs] @[simp] lemma measure_empty : μ ∅ = 0 := μ.empty lemma nonempty_of_measure_ne_zero (h : μ s ≠ 0) : s.nonempty := ne_empty_iff_nonempty.1 $ λ h', h $ h'.symm ▸ measure_empty lemma measure_mono (h : s₁ ⊆ s₂) : μ s₁ ≤ μ s₂ := μ.mono h lemma measure_mono_null (h : s₁ ⊆ s₂) (h₂ : μ s₂ = 0) : μ s₁ = 0 := by rw [← le_zero_iff_eq, ← h₂]; exact measure_mono h lemma exists_is_measurable_superset_of_measure_eq_zero {s : set α} (h : μ s = 0) : ∃t, s ⊆ t ∧ is_measurable t ∧ μ t = 0 := outer_measure.exists_is_measurable_superset_of_trim_eq_zero (by rw [← measure_eq_trim, h]) lemma exists_is_measurable_superset_iff_measure_eq_zero {s : set α} : (∃ t, s ⊆ t ∧ is_measurable t ∧ μ t = 0) ↔ μ s = 0 := ⟨λ ⟨t, hst, _, ht⟩, measure_mono_null hst ht, exists_is_measurable_superset_of_measure_eq_zero⟩ theorem measure_Union_le {β} [encodable β] (s : β → set α) : μ (⋃i, s i) ≤ (∑'i, μ (s i)) := μ.to_outer_measure.Union _ lemma measure_bUnion_le {s : set β} (hs : countable s) (f : β → set α) : μ (⋃b∈s, f b) ≤ ∑'p:s, μ (f p) := begin haveI := hs.to_encodable, rw [bUnion_eq_Union], apply measure_Union_le end lemma measure_bUnion_finset_le (s : finset β) (f : β → set α) : μ (⋃b∈s, f b) ≤ ∑ p in s, μ (f p) := begin rw [← finset.sum_attach, finset.attach_eq_univ, ← tsum_fintype], exact measure_bUnion_le s.countable_to_set f end lemma measure_Union_null {β} [encodable β] {s : β → set α} : (∀ i, μ (s i) = 0) → μ (⋃i, s i) = 0 := μ.to_outer_measure.Union_null theorem measure_union_le (s₁ s₂ : set α) : μ (s₁ ∪ s₂) ≤ μ s₁ + μ s₂ := μ.to_outer_measure.union _ _ lemma measure_union_null {s₁ s₂ : set α} : μ s₁ = 0 → μ s₂ = 0 → μ (s₁ ∪ s₂) = 0 := μ.to_outer_measure.union_null lemma measure_Union {β} [encodable β] {f : β → set α} (hn : pairwise (disjoint on f)) (h : ∀i, is_measurable (f i)) : μ (⋃i, f i) = (∑'i, μ (f i)) := by rw [measure_eq_measure' (is_measurable.Union h), measure'_Union (λ s _, μ s) _ μ.m_Union hn h]; simp [measure_eq_measure', h] lemma measure_union (hd : disjoint s₁ s₂) (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) : μ (s₁ ∪ s₂) = μ s₁ + μ s₂ := by rw [measure_eq_measure' (h₁.union h₂), measure'_union (λ s _, μ s) _ μ.m_Union hd h₁ h₂]; simp [measure_eq_measure', h₁, h₂] lemma measure_bUnion {s : set β} {f : β → set α} (hs : countable s) (hd : pairwise_on s (disjoint on f)) (h : ∀b∈s, is_measurable (f b)) : μ (⋃b∈s, f b) = ∑'p:s, μ (f p) := begin haveI := hs.to_encodable, rw [← measure_Union, bUnion_eq_Union], { rintro ⟨i, hi⟩ ⟨j, hj⟩ ij x ⟨h₁, h₂⟩, exact hd i hi j hj (mt subtype.ext_val ij:_) ⟨h₁, h₂⟩ }, { simpa } end lemma measure_sUnion {S : set (set α)} (hs : countable S) (hd : pairwise_on S disjoint) (h : ∀s∈S, is_measurable s) : μ (⋃₀ S) = ∑' s:S, μ s := by rw [sUnion_eq_bUnion, measure_bUnion hs hd h] lemma measure_bUnion_finset {s : finset ι} {f : ι → set α} (hd : pairwise_on ↑s (disjoint on f)) (hm : ∀b∈s, is_measurable (f b)) : μ (⋃b∈s, f b) = ∑ p in s, μ (f p) := begin rw [← finset.sum_attach, finset.attach_eq_univ, ← tsum_fintype], exact measure_bUnion s.countable_to_set hd hm end /-- If `s` is a countable set, then the measure of its preimage can be found as the sum of measures of the fibers `f ⁻¹' {y}`. -/ lemma tsum_measure_preimage_singleton {s : set β} (hs : countable s) {f : α → β} (hf : ∀ y ∈ s, is_measurable (f ⁻¹' {y})) : (∑' b : s, μ (f ⁻¹' {↑b})) = μ (f ⁻¹' s) := by rw [← set.bUnion_preimage_singleton, measure_bUnion hs (pairwise_on_disjoint_fiber _ _) hf] /-- If `s` is a `finset`, then the measure of its preimage can be found as the sum of measures of the fibers `f ⁻¹' {y}`. -/ lemma sum_measure_preimage_singleton (s : finset β) {f : α → β} (hf : ∀ y ∈ s, is_measurable (f ⁻¹' {y})) : ∑ b in s, μ (f ⁻¹' {b}) = μ (f ⁻¹' ↑s) := by simp only [← measure_bUnion_finset (pairwise_on_disjoint_fiber _ _) hf, finset.bUnion_preimage_singleton] lemma measure_diff {s₁ s₂ : set α} (h : s₂ ⊆ s₁) (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) (h_fin : μ s₂ < ⊤) : μ (s₁ \ s₂) = μ s₁ - μ s₂ := begin refine (ennreal.add_sub_self' h_fin).symm.trans _, rw [← measure_union disjoint_diff h₂ (h₁.diff h₂), union_diff_cancel h] end lemma sum_measure_le_measure_univ {s : finset ι} {t : ι → set α} (h : ∀ i ∈ s, is_measurable (t i)) (H : pairwise_on ↑s (disjoint on t)) : ∑ i in s, μ (t i) ≤ μ (univ : set α) := by { rw ← measure_bUnion_finset H h, exact measure_mono (subset_univ _) } lemma tsum_measure_le_measure_univ {s : ι → set α} (hs : ∀ i, is_measurable (s i)) (H : pairwise (disjoint on s)) : (∑' i, μ (s i)) ≤ μ (univ : set α) := begin rw [ennreal.tsum_eq_supr_sum], exact supr_le (λ s, sum_measure_le_measure_univ (λ i hi, hs i) (λ i hi j hj hij, H i j hij)) end /-- Pigeonhole principle for measure spaces: if `∑' i, μ (s i) > μ univ`, then one of the intersections `s i ∩ s j` is not empty. -/ lemma exists_nonempty_inter_of_measure_univ_lt_tsum_measure (μ : measure α) {s : ι → set α} (hs : ∀ i, is_measurable (s i)) (H : μ (univ : set α) < ∑' i, μ (s i)) : ∃ i j (h : i ≠ j), (s i ∩ s j).nonempty := begin contrapose! H, apply tsum_measure_le_measure_univ hs, exact λ i j hij x hx, H i j hij ⟨x, hx⟩ end /-- Pigeonhole principle for measure spaces: if `s` is a `finset` and `∑ i in s, μ (t i) > μ univ`, then one of the intersections `t i ∩ t j` is not empty. -/ lemma exists_nonempty_inter_of_measure_univ_lt_sum_measure (μ : measure α) {s : finset ι} {t : ι → set α} (h : ∀ i ∈ s, is_measurable (t i)) (H : μ (univ : set α) < ∑ i in s, μ (t i)) : ∃ (i ∈ s) (j ∈ s) (h : i ≠ j), (t i ∩ t j).nonempty := begin contrapose! H, apply sum_measure_le_measure_univ h, exact λ i hi j hj hij x hx, H i hi j hj hij ⟨x, hx⟩ end lemma measure_Union_eq_supr_nat {s : ℕ → set α} (h : ∀i, is_measurable (s i)) (hs : monotone s) : μ (⋃i, s i) = (⨆i, μ (s i)) := begin have : ∀ t : finset ℕ, ∃ n, t ⊆ finset.range (n + 1), from λ t, (finset.exists_nat_subset_range t).imp (λ n hn, finset.subset.trans hn $ finset.range_mono $ (le_add_iff_nonneg_right _).2 (zero_le 1)), rw [← Union_disjointed, measure_Union disjoint_disjointed (is_measurable.disjointed h), ennreal.tsum_eq_supr_sum' _ this], congr' 1, ext1 n, rw [← measure_bUnion_finset (disjoint_disjointed.pairwise_on _) (λ n _, is_measurable.disjointed h n)], convert congr_arg μ (Union_disjointed_of_mono hs n), ext, simp end lemma measure_Inter_eq_infi_nat {s : ℕ → set α} (h : ∀i, is_measurable (s i)) (hs : ∀i j, i ≤ j → s j ⊆ s i) (hfin : ∃i, μ (s i) < ⊤) : μ (⋂i, s i) = (⨅i, μ (s i)) := begin rcases hfin with ⟨k, hk⟩, rw [← ennreal.sub_sub_cancel (by exact hk) (infi_le _ k), ennreal.sub_infi, ← ennreal.sub_sub_cancel (by exact hk) (measure_mono (Inter_subset _ k)), ← measure_diff (Inter_subset _ k) (h k) (is_measurable.Inter h) (lt_of_le_of_lt (measure_mono (Inter_subset _ k)) hk), diff_Inter, measure_Union_eq_supr_nat], { congr, funext i, cases le_total k i with ik ik, { exact measure_diff (hs _ _ ik) (h k) (h i) (lt_of_le_of_lt (measure_mono (hs _ _ ik)) hk) }, { rw [diff_eq_empty.2 (hs _ _ ik), measure_empty, ennreal.sub_eq_zero_of_le (measure_mono (hs _ _ ik))] } }, { exact λ i, (h k).diff (h i) }, { exact λ i j ij, diff_subset_diff_right (hs _ _ ij) } end lemma measure_eq_inter_diff {μ : measure α} {s t : set α} (hs : is_measurable s) (ht : is_measurable t) : μ s = μ (s ∩ t) + μ (s \ t) := have hd : disjoint (s ∩ t) (s \ t) := assume a ⟨⟨_, hs⟩, _, hns⟩, hns hs , by rw [← measure_union hd (hs.inter ht) (hs.diff ht), inter_union_diff s t] lemma tendsto_measure_Union {μ : measure α} {s : ℕ → set α} (hs : ∀n, is_measurable (s n)) (hm : monotone s) : tendsto (μ ∘ s) at_top (𝓝 (μ (⋃n, s n))) := begin rw measure_Union_eq_supr_nat hs hm, exact tendsto_at_top_supr_nat (μ ∘ s) (assume n m hnm, measure_mono $ hm $ hnm) end lemma tendsto_measure_Inter {μ : measure α} {s : ℕ → set α} (hs : ∀n, is_measurable (s n)) (hm : ∀n m, n ≤ m → s m ⊆ s n) (hf : ∃i, μ (s i) < ⊤) : tendsto (μ ∘ s) at_top (𝓝 (μ (⋂n, s n))) := begin rw measure_Inter_eq_infi_nat hs hm hf, exact tendsto_at_top_infi_nat (μ ∘ s) (assume n m hnm, measure_mono $ hm _ _ $ hnm), end end /-- Obtain a measure by giving an outer measure where all sets in the σ-algebra are Carathéodory measurable. -/ def outer_measure.to_measure {α} (m : outer_measure α) [ms : measurable_space α] (h : ms ≤ m.caratheodory) : measure α := measure.of_measurable (λ s _, m s) m.empty (λ f hf hd, m.Union_eq_of_caratheodory (λ i, h _ (hf i)) hd) lemma le_to_outer_measure_caratheodory {α} [ms : measurable_space α] (μ : measure α) : ms ≤ μ.to_outer_measure.caratheodory := begin assume s hs, rw to_outer_measure_eq_outer_measure', refine outer_measure.caratheodory_is_measurable (λ t, le_infi $ λ ht, _), rw [← measure_eq_measure' (ht.inter hs), ← measure_eq_measure' (ht.diff hs), ← measure_union _ (ht.inter hs) (ht.diff hs), inter_union_diff], exact le_refl _, exact λ x ⟨⟨_, h₁⟩, _, h₂⟩, h₂ h₁ end @[simp] lemma to_measure_to_outer_measure {α} (m : outer_measure α) [ms : measurable_space α] (h : ms ≤ m.caratheodory) : (m.to_measure h).to_outer_measure = m.trim := rfl @[simp] lemma to_measure_apply {α} (m : outer_measure α) [ms : measurable_space α] (h : ms ≤ m.caratheodory) {s : set α} (hs : is_measurable s) : m.to_measure h s = m s := m.trim_eq hs lemma le_to_measure_apply {α} (m : outer_measure α) [ms : measurable_space α] (h : ms ≤ m.caratheodory) (s : set α) : m s ≤ m.to_measure h s := m.trim_ge s @[simp] lemma to_outer_measure_to_measure {α : Type*} [ms : measurable_space α] {μ : measure α} : μ.to_outer_measure.to_measure (le_to_outer_measure_caratheodory _) = μ := measure.ext $ λ s, μ.to_outer_measure.trim_eq namespace measure variables {α : Type*} {β : Type*} {γ : Type*} [measurable_space α] [measurable_space β] [measurable_space γ] instance : has_zero (measure α) := ⟨{ to_outer_measure := 0, m_Union := λ f hf hd, tsum_zero.symm, trimmed := outer_measure.trim_zero }⟩ @[simp] theorem zero_to_outer_measure : (0 : measure α).to_outer_measure = 0 := rfl @[simp, norm_cast] theorem coe_zero : ⇑(0 : measure α) = 0 := rfl lemma eq_zero_of_not_nonempty (h : ¬nonempty α) (μ : measure α) : μ = 0 := ext $ λ s hs, by simp only [eq_empty_of_not_nonempty h s, measure_empty] instance : inhabited (measure α) := ⟨0⟩ instance : has_add (measure α) := ⟨λμ₁ μ₂, { to_outer_measure := μ₁.to_outer_measure + μ₂.to_outer_measure, m_Union := λs hs hd, show μ₁ (⋃ i, s i) + μ₂ (⋃ i, s i) = ∑' i, μ₁ (s i) + μ₂ (s i), by rw [ennreal.tsum_add, measure_Union hd hs, measure_Union hd hs], trimmed := by rw [outer_measure.trim_add, μ₁.trimmed, μ₂.trimmed] }⟩ @[simp] theorem add_to_outer_measure (μ₁ μ₂ : measure α) : (μ₁ + μ₂).to_outer_measure = μ₁.to_outer_measure + μ₂.to_outer_measure := rfl @[simp, norm_cast] theorem coe_add (μ₁ μ₂ : measure α) : ⇑(μ₁ + μ₂) = μ₁ + μ₂ := rfl theorem add_apply (μ₁ μ₂ : measure α) (s) : (μ₁ + μ₂) s = μ₁ s + μ₂ s := rfl instance add_comm_monoid : add_comm_monoid (measure α) := to_outer_measure_injective.add_comm_monoid to_outer_measure zero_to_outer_measure add_to_outer_measure instance : has_scalar ennreal (measure α) := ⟨λ c μ, { to_outer_measure := c • μ.to_outer_measure, m_Union := λ s hs hd, by simp [measure_Union, *, ennreal.tsum_mul_left], trimmed := by rw [outer_measure.trim_smul, μ.trimmed] }⟩ @[simp] theorem smul_to_outer_measure (c : ennreal) (μ : measure α) : (c • μ).to_outer_measure = c • μ.to_outer_measure := rfl @[simp, norm_cast] theorem coe_smul (c : ennreal) (μ : measure α) : ⇑(c • μ) = c • μ := rfl instance : semimodule ennreal (measure α) := injective.semimodule ennreal ⟨to_outer_measure, zero_to_outer_measure, add_to_outer_measure⟩ to_outer_measure_injective smul_to_outer_measure instance : partial_order (measure α) := { le := λm₁ m₂, ∀ s, is_measurable s → m₁ s ≤ m₂ s, le_refl := assume m s hs, le_refl _, le_trans := assume m₁ m₂ m₃ h₁ h₂ s hs, le_trans (h₁ s hs) (h₂ s hs), le_antisymm := assume m₁ m₂ h₁ h₂, ext $ assume s hs, le_antisymm (h₁ s hs) (h₂ s hs) } theorem le_iff {μ₁ μ₂ : measure α} : μ₁ ≤ μ₂ ↔ ∀ s, is_measurable s → μ₁ s ≤ μ₂ s := iff.rfl theorem to_outer_measure_le {μ₁ μ₂ : measure α} : μ₁.to_outer_measure ≤ μ₂.to_outer_measure ↔ μ₁ ≤ μ₂ := by rw [← μ₂.trimmed, outer_measure.le_trim_iff]; refl theorem le_iff' {μ₁ μ₂ : measure α} : μ₁ ≤ μ₂ ↔ ∀ s, μ₁ s ≤ μ₂ s := to_outer_measure_le.symm theorem lt_iff {μ ν : measure α} : μ < ν ↔ μ ≤ ν ∧ ∃ s, is_measurable s ∧ μ s < ν s := lt_iff_le_not_le.trans $ and_congr iff.rfl $ by simp only [le_iff, not_forall, not_le, exists_prop] theorem lt_iff' {μ ν : measure α} : μ < ν ↔ μ ≤ ν ∧ ∃ s, μ s < ν s := lt_iff_le_not_le.trans $ and_congr iff.rfl $ by simp only [le_iff', not_forall, not_le] section variables {m : set (measure α)} {μ : measure α} lemma Inf_caratheodory (s : set α) (hs : is_measurable s) : (Inf (measure.to_outer_measure '' m)).caratheodory.is_measurable s := begin rw [outer_measure.Inf_eq_of_function_Inf_gen], refine outer_measure.caratheodory_is_measurable (assume t, _), cases t.eq_empty_or_nonempty with ht ht, by simp [ht], simp only [outer_measure.Inf_gen_nonempty1 _ _ ht, le_infi_iff, ball_image_iff, coe_to_outer_measure, measure_eq_infi t], assume μ hμ u htu hu, have hm : ∀{s t}, s ⊆ t → outer_measure.Inf_gen (to_outer_measure '' m) s ≤ μ t, { assume s t hst, rw [outer_measure.Inf_gen_nonempty2 _ _ (mem_image_of_mem _ hμ)], refine infi_le_of_le (μ.to_outer_measure) (infi_le_of_le (mem_image_of_mem _ hμ) _), rw [to_outer_measure_apply], refine measure_mono hst }, rw [measure_eq_inter_diff hu hs], refine add_le_add (hm $ inter_subset_inter_left _ htu) (hm $ diff_subset_diff_left htu) end instance : has_Inf (measure α) := ⟨λm, (Inf (to_outer_measure '' m)).to_measure $ Inf_caratheodory⟩ lemma Inf_apply {m : set (measure α)} {s : set α} (hs : is_measurable s) : Inf m s = Inf (to_outer_measure '' m) s := to_measure_apply _ _ hs private lemma Inf_le (h : μ ∈ m) : Inf m ≤ μ := have Inf (to_outer_measure '' m) ≤ μ.to_outer_measure := Inf_le (mem_image_of_mem _ h), assume s hs, by rw [Inf_apply hs, ← to_outer_measure_apply]; exact this s private lemma le_Inf (h : ∀μ' ∈ m, μ ≤ μ') : μ ≤ Inf m := have μ.to_outer_measure ≤ Inf (to_outer_measure '' m) := le_Inf $ ball_image_of_ball $ assume μ hμ, to_outer_measure_le.2 $ h _ hμ, assume s hs, by rw [Inf_apply hs, ← to_outer_measure_apply]; exact this s instance : complete_lattice (measure α) := { bot := 0, bot_le := assume a s hs, by exact bot_le, /- Adding an explicit `top` makes `leanchecker` fail, see lean#364, disable for now top := (⊤ : outer_measure α).to_measure (by rw [outer_measure.top_caratheodory]; exact le_top), le_top := assume a s hs, by cases s.eq_empty_or_nonempty with h h; simp [h, to_measure_apply ⊤ _ hs, outer_measure.top_apply], -/ .. complete_lattice_of_Inf (measure α) (λ ms, ⟨λ _, Inf_le, λ _, le_Inf⟩) } -- TODO: add typeclasses for `∀ c, monotone ((*) c)` and `∀ c, monotone ((+) c)` protected lemma add_le_add_left {μ₁ μ₂ : measure α} (ν : measure α) (hμ : μ₁ ≤ μ₂) : ν + μ₁ ≤ ν + μ₂ := λ s hs, add_le_add_left (hμ s hs) _ protected lemma add_le_add_right {μ₁ μ₂ : measure α} (hμ : μ₁ ≤ μ₂) (ν : measure α) : μ₁ + ν ≤ μ₂ + ν := λ s hs, add_le_add_right (hμ s hs) _ protected lemma add_le_add {μ₁ μ₂ : measure α} (hμ : μ₁ ≤ μ₂) {ν₁ ν₂ : measure α} (hν : ν₁ ≤ ν₂) : μ₁ + ν₁ ≤ μ₂ + ν₂ := λ s hs, add_le_add (hμ s hs) (hν s hs) protected lemma zero_le (μ : measure α) : 0 ≤ μ := bot_le protected lemma le_add_left {ν ν' : measure α} (h : μ ≤ ν) : μ ≤ ν' + ν := λ s hs, le_add_left (h s hs) protected lemma le_add_right {ν ν' : measure α} (h : μ ≤ ν) : μ ≤ ν + ν' := λ s hs, le_add_right (h s hs) end /-- Lift a linear map between `outer_measure` spaces such that for each measure `μ` every measurable set is caratheodory-measurable w.r.t. `f μ` to a linear map between `measure` spaces. -/ def lift_linear (f : outer_measure α →ₗ[ennreal] outer_measure β) (hf : ∀ μ : measure α, ‹_› ≤ (f μ.to_outer_measure).caratheodory) : measure α →ₗ[ennreal] measure β := { to_fun := λ μ, (f μ.to_outer_measure).to_measure (hf μ), map_add' := λ μ₁ μ₂, ext $ λ s hs, by simp [hs], map_smul' := λ c μ, ext $ λ s hs, by simp [hs] } @[simp] lemma lift_linear_apply {f : outer_measure α →ₗ[ennreal] outer_measure β} (hf) {μ : measure α} {s : set β} (hs : is_measurable s) : lift_linear f hf μ s = f μ.to_outer_measure s := to_measure_apply _ _ hs lemma le_lift_linear_apply {f : outer_measure α →ₗ[ennreal] outer_measure β} (hf) {μ : measure α} (s : set β) : f μ.to_outer_measure s ≤ lift_linear f hf μ s := le_to_measure_apply _ _ s /-- The pushforward of a measure. It is defined to be `0` if `f` is not a measurable function. -/ def map (f : α → β) : measure α →ₗ[ennreal] measure β := if hf : measurable f then lift_linear (outer_measure.map f) $ λ μ s hs t, le_to_outer_measure_caratheodory μ _ (hf hs) (f ⁻¹' t) else 0 variables {μ ν : measure α} @[simp] theorem map_apply {f : α → β} (hf : measurable f) {s : set β} (hs : is_measurable s) : map f μ s = μ (f ⁻¹' s) := by simp [map, dif_pos hf, hs] @[simp] lemma map_id : map id μ = μ := ext $ λ s, map_apply measurable_id lemma map_map {g : β → γ} {f : α → β} (hg : measurable g) (hf : measurable f) : map g (map f μ) = map (g ∘ f) μ := ext $ λ s hs, by simp [hf, hg, hs, hg hs, hg.comp hf, ← preimage_comp] /-- Pullback of a `measure`. If `f` sends each `measurable` set to a `measurable` set, then for each measurable set `s` we have `comap f μ s = μ (f '' s)`. -/ def comap (f : α → β) : measure β →ₗ[ennreal] measure α := if hf : injective f ∧ ∀ s, is_measurable s → is_measurable (f '' s) then lift_linear (outer_measure.comap f) $ λ μ s hs t, begin simp only [coe_to_outer_measure, outer_measure.comap_apply, ← image_inter hf.1, image_diff hf.1], apply le_to_outer_measure_caratheodory, exact hf.2 s hs end else 0 lemma comap_apply (f : α → β) (hfi : injective f) (hf : ∀ s, is_measurable s → is_measurable (f '' s)) (μ : measure β) {s : set α} (hs : is_measurable s) : comap f μ s = μ (f '' s) := begin rw [comap, dif_pos, lift_linear_apply _ hs, outer_measure.comap_apply, coe_to_outer_measure], exact ⟨hfi, hf⟩ end /-- Restrict a measure `μ` to a set `s` as an `ennreal`-linear map. -/ def restrictₗ (s : set α) : measure α →ₗ[ennreal] measure α := lift_linear (outer_measure.restrict s) $ λ μ s' hs' t, begin suffices : μ (s ∩ t) = μ (s ∩ t ∩ s') + μ (s ∩ t \ s'), { simpa [← set.inter_assoc, set.inter_comm _ s, ← inter_diff_assoc] }, exact le_to_outer_measure_caratheodory _ _ hs' _, end /-- Restrict a measure `μ` to a set `s`. -/ def restrict (μ : measure α) (s : set α) : measure α := restrictₗ s μ @[simp] lemma restrictₗ_apply (s : set α) (μ : measure α) : restrictₗ s μ = μ.restrict s := rfl @[simp] lemma restrict_apply {s t : set α} (ht : is_measurable t) : μ.restrict s t = μ (t ∩ s) := by simp [← restrictₗ_apply, restrictₗ, ht] lemma le_restrict_apply (s t : set α) : μ (t ∩ s) ≤ μ.restrict s t := by { rw [restrict, restrictₗ], convert le_lift_linear_apply _ t, simp } @[simp] lemma restrict_add (μ ν : measure α) (s : set α) : (μ + ν).restrict s = μ.restrict s + ν.restrict s := (restrictₗ s).map_add μ ν @[simp] lemma restrict_zero (s : set α) : (0 : measure α).restrict s = 0 := (restrictₗ s).map_zero @[simp] lemma restrict_smul (c : ennreal) (μ : measure α) (s : set α) : (c • μ).restrict s = c • μ.restrict s := (restrictₗ s).map_smul c μ lemma restrict_apply_eq_zero {s t : set α} (ht : is_measurable t) : μ.restrict s t = 0 ↔ μ (t ∩ s) = 0 := by rw [restrict_apply ht] lemma restrict_apply_eq_zero' {s t : set α} (hs : is_measurable s) : μ.restrict s t = 0 ↔ μ (t ∩ s) = 0 := begin refine ⟨λ h, le_zero_iff_eq.1 (h ▸ le_restrict_apply _ _), λ h, _⟩, rcases exists_is_measurable_superset_of_measure_eq_zero h with ⟨t', htt', ht', ht'0⟩, apply measure_mono_null ((inter_subset _ _ _).1 htt'), rw [restrict_apply (hs.compl.union ht'), union_inter_distrib_right, compl_inter_self, set.empty_union], exact measure_mono_null (inter_subset_left _ _) ht'0 end @[simp] lemma restrict_empty : μ.restrict ∅ = 0 := ext $ λ s hs, by simp [hs] @[simp] lemma restrict_univ : μ.restrict univ = μ := ext $ λ s hs, by simp [hs] lemma restrict_union_apply {s s' t : set α} (h : disjoint (t ∩ s) (t ∩ s')) (hs : is_measurable s) (hs' : is_measurable s') (ht : is_measurable t) : μ.restrict (s ∪ s') t = μ.restrict s t + μ.restrict s' t := begin simp only [restrict_apply, ht, set.inter_union_distrib_left], exact measure_union h (ht.inter hs) (ht.inter hs'), end lemma restrict_union {s t : set α} (h : disjoint s t) (hs : is_measurable s) (ht : is_measurable t) : μ.restrict (s ∪ t) = μ.restrict s + μ.restrict t := ext $ λ t' ht', restrict_union_apply (h.mono inf_le_right inf_le_right) hs ht ht' lemma restrict_union_le (s s' : set α) : μ.restrict (s ∪ s') ≤ μ.restrict s + μ.restrict s' := begin intros t ht, suffices : μ (t ∩ s ∪ t ∩ s') ≤ μ (t ∩ s) + μ (t ∩ s'), by simpa [ht, inter_union_distrib_left], apply measure_union_le end lemma restrict_Union_apply {ι} [encodable ι] {s : ι → set α} (hd : pairwise (disjoint on s)) (hm : ∀ i, is_measurable (s i)) {t : set α} (ht : is_measurable t) : μ.restrict (⋃ i, s i) t = ∑' i, μ.restrict (s i) t := begin simp only [restrict_apply, ht, inter_Union], exact measure_Union (λ i j hij, (hd i j hij).mono inf_le_right inf_le_right) (λ i, ht.inter (hm i)) end lemma map_comap_subtype_coe {s : set α} (hs : is_measurable s) : (map (coe : s → α)).comp (comap coe) = restrictₗ s := linear_map.ext $ λ μ, ext $ λ t ht, by rw [restrictₗ_apply, restrict_apply ht, linear_map.comp_apply, map_apply measurable_subtype_coe ht, comap_apply (coe : s → α) subtype.val_injective (λ _, hs.subtype_image) _ (measurable_subtype_coe ht), subtype.image_preimage_coe] /-- Restriction of a measure to a subset is monotone both in set and in measure. -/ @[mono] lemma restrict_mono ⦃s s' : set α⦄ (hs : s ⊆ s') ⦃μ ν : measure α⦄ (hμν : μ ≤ ν) : μ.restrict s ≤ ν.restrict s' := assume t ht, calc μ.restrict s t = μ (t ∩ s) : restrict_apply ht ... ≤ μ (t ∩ s') : measure_mono $ inter_subset_inter_right _ hs ... ≤ ν (t ∩ s') : le_iff'.1 hμν (t ∩ s') ... = ν.restrict s' t : (restrict_apply ht).symm /-- The dirac measure. -/ def dirac (a : α) : measure α := (outer_measure.dirac a).to_measure (by simp) lemma dirac_apply' (a : α) {s : set α} (hs : is_measurable s) : dirac a s = ⨆ h : a ∈ s, 1 := to_measure_apply _ _ hs @[simp] lemma dirac_apply (a : α) {s : set α} (hs : is_measurable s) : dirac a s = s.indicator 1 a := (dirac_apply' a hs).trans $ by { by_cases h : a ∈ s; simp [h] } lemma dirac_apply_of_mem {a : α} {s : set α} (h : a ∈ s) : dirac a s = 1 := begin rw [measure_eq_infi, infi_subtype', infi_subtype'], convert infi_const, { ext1 ⟨⟨t, hst⟩, ht⟩, simp only [dirac_apply _ ht, indicator_of_mem (hst h), pi.one_apply] }, { exact ⟨⟨⟨set.univ, subset_univ _⟩, is_measurable.univ⟩⟩ } end /-- Sum of an indexed family of measures. -/ def sum {ι : Type*} (f : ι → measure α) : measure α := (outer_measure.sum (λ i, (f i).to_outer_measure)).to_measure $ le_trans (by exact le_infi (λ i, le_to_outer_measure_caratheodory _)) (outer_measure.le_sum_caratheodory _) @[simp] lemma sum_apply {ι : Type*} (f : ι → measure α) {s : set α} (hs : is_measurable s) : sum f s = ∑' i, f i s := to_measure_apply _ _ hs lemma restrict_Union {ι} [encodable ι] {s : ι → set α} (hd : pairwise (disjoint on s)) (hm : ∀ i, is_measurable (s i)) : μ.restrict (⋃ i, s i) = sum (λ i, μ.restrict (s i)) := ext $ λ t ht, by simp only [sum_apply _ ht, restrict_Union_apply hd hm ht] lemma restrict_Union_le {ι} [encodable ι] {s : ι → set α} : μ.restrict (⋃ i, s i) ≤ sum (λ i, μ.restrict (s i)) := begin intros t ht, suffices : μ (⋃ i, t ∩ s i) ≤ ∑' i, μ (t ∩ s i), by simpa [ht, inter_Union], apply measure_Union_le end @[simp] lemma sum_bool (f : bool → measure α) : sum f = f tt + f ff := ext $ λ s hs, by simp [hs, tsum_fintype] @[simp] lemma restrict_sum {ι : Type*} (μ : ι → measure α) {s : set α} (hs : is_measurable s) : (sum μ).restrict s = sum (λ i, (μ i).restrict s) := ext $ λ t ht, by simp only [sum_apply, restrict_apply, ht, ht.inter hs] /-- Counting measure on any measurable space. -/ def count : measure α := sum dirac lemma count_apply {s : set α} (hs : is_measurable s) : count s = ∑' i : s, 1 := by simp only [count, sum_apply, hs, dirac_apply, ← tsum_subtype s 1, pi.one_apply] @[simp] lemma count_apply_finset [measurable_singleton_class α] (s : finset α) : count (↑s : set α) = s.card := calc count (↑s : set α) = ∑' i : (↑s : set α), (1 : α → ennreal) i : count_apply s.is_measurable ... = ∑ i in s, 1 : s.tsum_subtype 1 ... = s.card : by simp /-- A measure is complete if every null set is also measurable. A null set is a subset of a measurable set with measure `0`. Since every measure is defined as a special case of an outer measure, we can more simply state that a set `s` is null if `μ s = 0`. -/ @[class] def is_complete {α} {_:measurable_space α} (μ : measure α) : Prop := ∀ s, μ s = 0 → is_measurable s /-- The "almost everywhere" filter of co-null sets. -/ def ae (μ : measure α) : filter α := { sets := {s | μ sᶜ = 0}, univ_sets := by simp, inter_sets := λ s t hs ht, by simp only [compl_inter, mem_set_of_eq]; exact measure_union_null hs ht, sets_of_superset := λ s t hs hst, measure_mono_null (set.compl_subset_compl.2 hst) hs } /-- The filter of sets `s` such that `sᶜ` has finite measure. -/ def cofinite (μ : measure α) : filter α := { sets := {s | μ sᶜ < ⊤}, univ_sets := by simp, inter_sets := λ s t hs ht, by { simp only [compl_inter, mem_set_of_eq], calc μ (sᶜ ∪ tᶜ) ≤ μ sᶜ + μ tᶜ : measure_union_le _ _ ... < ⊤ : ennreal.add_lt_top.2 ⟨hs, ht⟩ }, sets_of_superset := λ s t hs hst, lt_of_le_of_lt (measure_mono $ compl_subset_compl.2 hst) hs } lemma mem_cofinite {s : set α} : s ∈ μ.cofinite ↔ μ sᶜ < ⊤ := iff.rfl lemma eventually_cofinite {p : α → Prop} : (∀ᶠ x in μ.cofinite, p x) ↔ μ {x | ¬p x} < ⊤ := iff.rfl end measure variables {α : Type*} {β : Type*} [measurable_space α] {μ : measure α} notation `∀ᵐ` binders `∂` μ `, ` r:(scoped P, μ.ae.eventually P) := r notation f ` =ᵐ[`:50 μ:50 `] `:0 g:50 := f =ᶠ[μ.ae] g notation f ` ≤ᵐ[`:50 μ:50 `] `:0 g:50 := f ≤ᶠ[μ.ae] g lemma mem_ae_iff {s : set α} : s ∈ μ.ae ↔ μ sᶜ = 0 := iff.rfl lemma ae_iff {p : α → Prop} : (∀ᵐ a ∂ μ, p a) ↔ μ { a | ¬ p a } = 0 := iff.rfl lemma measure_zero_iff_ae_nmem {s : set α} : μ s = 0 ↔ ∀ᵐ a ∂ μ, a ∉ s := by simp only [ae_iff, not_not, set_of_mem_eq] lemma ae_of_all {p : α → Prop} (μ : measure α) : (∀a, p a) → ∀ᵐ a ∂ μ, p a := eventually_of_forall instance : countable_Inter_filter μ.ae := ⟨begin intros S hSc hS, simp only [mem_ae_iff, compl_sInter, sUnion_image, bUnion_eq_Union] at hS ⊢, haveI := hSc.to_encodable, exact measure_Union_null (subtype.forall.2 hS) end⟩ lemma ae_all_iff {ι : Type*} [encodable ι] {p : α → ι → Prop} : (∀ᵐ a ∂ μ, ∀i, p a i) ↔ (∀i, ∀ᵐ a ∂ μ, p a i) := eventually_countable_forall lemma ae_ball_iff {ι} {S : set ι} (hS : countable S) {p : Π (x : α) (i ∈ S), Prop} : (∀ᵐ x ∂ μ, ∀ i ∈ S, p x i ‹_›) ↔ ∀ i ∈ S, ∀ᵐ x ∂ μ, p x i ‹_› := eventually_countable_ball hS lemma ae_eq_refl (f : α → β) : f =ᵐ[μ] f := eventually_eq.refl _ _ lemma ae_eq_symm {f g : α → β} (h : f =ᵐ[μ] g) : g =ᵐ[μ] f := h.symm lemma ae_eq_trans {f g h: α → β} (h₁ : f =ᵐ[μ] g) (h₂ : g =ᵐ[μ] h) : f =ᵐ[μ] h := h₁.trans h₂ lemma mem_ae_map_iff [measurable_space β] {f : α → β} (hf : measurable f) {s : set β} (hs : is_measurable s) : s ∈ (measure.map f μ).ae ↔ (f ⁻¹' s) ∈ μ.ae := by simp only [mem_ae_iff, measure.map_apply hf hs.compl, preimage_compl] lemma ae_map_iff [measurable_space β] {f : α → β} (hf : measurable f) {p : β → Prop} (hp : is_measurable {x | p x}) : (∀ᵐ y ∂ (measure.map f μ), p y) ↔ ∀ᵐ x ∂ μ, p (f x) := mem_ae_map_iff hf hp @[simp] lemma ae_restrict_eq {s : set α} (hs : is_measurable s): (μ.restrict s).ae = μ.ae ⊓ 𝓟 s := begin ext t, simp only [mem_inf_principal, mem_ae_iff, measure.restrict_apply_eq_zero' hs, compl_set_of, not_imp, and_comm (_ ∈ s)], refl end lemma mem_dirac_ae_iff {a : α} {s : set α} (hs : is_measurable s) : s ∈ (measure.dirac a).ae ↔ a ∈ s := by by_cases a ∈ s; simp [mem_ae_iff, measure.dirac_apply, hs.compl, indicator_apply, *] lemma eventually_dirac {a : α} {p : α → Prop} (hp : is_measurable {x | p x}) : (∀ᵐ x ∂(measure.dirac a), p x) ↔ p a := mem_dirac_ae_iff hp lemma eventually_eq_dirac [measurable_space β] [measurable_singleton_class β] {a : α} {f : α → β} (hf : measurable f) : f =ᵐ[measure.dirac a] const α (f a) := (eventually_dirac $ show is_measurable (f ⁻¹' {f a}), from hf $ is_measurable_singleton _).2 rfl lemma dirac_ae_eq [measurable_singleton_class α] (a : α) : (measure.dirac a).ae = pure a := begin ext s, simp only [mem_ae_iff, mem_pure_sets], by_cases ha : a ∈ s, { simp only [ha, iff_true], rw [← set.singleton_subset_iff, ← compl_subset_compl] at ha, refine measure_mono_null ha _, simp [measure.dirac_apply a (is_measurable_singleton a).compl] }, { simp only [ha, iff_false, measure.dirac_apply_of_mem (mem_compl ha)], exact one_ne_zero } end lemma eventually_eq_dirac' [measurable_singleton_class α] {a : α} (f : α → β) : f =ᵐ[measure.dirac a] const α (f a) := by { rw [dirac_ae_eq], show f a = f a, refl } lemma measure_diff_of_ae_imp {s t : set α} (H : ∀ᵐ x ∂μ, x ∈ s → x ∈ t) : μ (s \ t) = 0 := flip measure_mono_null H $ λ x hx H, hx.2 (H hx.1) /-- If `s ⊆ t` modulo a set of measure `0`, then `μ s ≤ μ t`. -/ lemma measure_le_of_ae_imp {s t : set α} (H : ∀ᵐ x ∂μ, x ∈ s → x ∈ t) : μ s ≤ μ t := calc μ s ≤ μ (s ∪ t) : measure_mono $ subset_union_left s t ... = μ (t ∪ s \ t) : by rw [union_diff_self, set.union_comm] ... ≤ μ t + μ (s \ t) : measure_union_le _ _ ... = μ t : by rw [measure_diff_of_ae_imp H, add_zero] /-- If two sets are equal modulo a set of measure zero, then `μ s = μ t`. -/ lemma measure_congr {s t : set α} (H : ∀ᵐ x ∂μ, x ∈ s ↔ x ∈ t) : μ s = μ t := le_antisymm (measure_le_of_ae_imp $ H.mono $ λ x, iff.mp) (measure_le_of_ae_imp $ H.mono $ λ x, iff.mpr) end measure_theory section is_complete open measure_theory variables {α : Type*} [measurable_space α] (μ : measure α) /-- A set is null measurable if it is the union of a null set and a measurable set. -/ def is_null_measurable (s : set α) : Prop := ∃ t z, s = t ∪ z ∧ is_measurable t ∧ μ z = 0 theorem is_null_measurable_iff {μ : measure α} {s : set α} : is_null_measurable μ s ↔ ∃ t, t ⊆ s ∧ is_measurable t ∧ μ (s \ t) = 0 := begin split, { rintro ⟨t, z, rfl, ht, hz⟩, refine ⟨t, set.subset_union_left _ _, ht, measure_mono_null _ hz⟩, simp [union_diff_left, diff_subset] }, { rintro ⟨t, st, ht, hz⟩, exact ⟨t, _, (union_diff_cancel st).symm, ht, hz⟩ } end theorem is_null_measurable_measure_eq {μ : measure α} {s t : set α} (st : t ⊆ s) (hz : μ (s \ t) = 0) : μ s = μ t := begin refine le_antisymm _ (measure_mono st), have := measure_union_le t (s \ t), rw [union_diff_cancel st, hz] at this, simpa end theorem is_measurable.is_null_measurable {s : set α} (hs : is_measurable s) : is_null_measurable μ s := ⟨s, ∅, by simp, hs, μ.empty⟩ theorem is_null_measurable_of_complete [c : μ.is_complete] {s : set α} : is_null_measurable μ s ↔ is_measurable s := ⟨by rintro ⟨t, z, rfl, ht, hz⟩; exact is_measurable.union ht (c _ hz), λ h, h.is_null_measurable _⟩ variables {μ} theorem is_null_measurable.union_null {s z : set α} (hs : is_null_measurable μ s) (hz : μ z = 0) : is_null_measurable μ (s ∪ z) := begin rcases hs with ⟨t, z', rfl, ht, hz'⟩, exact ⟨t, z' ∪ z, set.union_assoc _ _ _, ht, le_zero_iff_eq.1 (le_trans (measure_union_le _ _) $ by simp [hz, hz'])⟩ end theorem null_is_null_measurable {z : set α} (hz : μ z = 0) : is_null_measurable μ z := by simpa using (is_measurable.empty.is_null_measurable _).union_null hz theorem is_null_measurable.Union_nat {s : ℕ → set α} (hs : ∀ i, is_null_measurable μ (s i)) : is_null_measurable μ (Union s) := begin choose t ht using assume i, is_null_measurable_iff.1 (hs i), simp [forall_and_distrib] at ht, rcases ht with ⟨st, ht, hz⟩, refine is_null_measurable_iff.2 ⟨Union t, Union_subset_Union st, is_measurable.Union ht, measure_mono_null _ (measure_Union_null hz)⟩, rw [diff_subset_iff, ← Union_union_distrib], exact Union_subset_Union (λ i, by rw ← diff_subset_iff) end theorem is_measurable.diff_null {s z : set α} (hs : is_measurable s) (hz : μ z = 0) : is_null_measurable μ (s \ z) := begin rw measure_eq_infi at hz, choose f hf using show ∀ q : {q:ℚ//q>0}, ∃ t:set α, z ⊆ t ∧ is_measurable t ∧ μ t < (nnreal.of_real q.1 : ennreal), { rintro ⟨ε, ε0⟩, have : 0 < (nnreal.of_real ε : ennreal), { simpa using ε0 }, rw ← hz at this, simpa [infi_lt_iff] }, refine is_null_measurable_iff.2 ⟨s \ Inter f, diff_subset_diff_right (subset_Inter (λ i, (hf i).1)), hs.diff (is_measurable.Inter (λ i, (hf i).2.1)), measure_mono_null _ (le_zero_iff_eq.1 $ le_of_not_lt $ λ h, _)⟩, { exact Inter f }, { rw [diff_subset_iff, diff_union_self], exact subset.trans (diff_subset _ _) (subset_union_left _ _) }, rcases ennreal.lt_iff_exists_rat_btwn.1 h with ⟨ε, ε0', ε0, h⟩, simp at ε0, apply not_le_of_lt (lt_trans (hf ⟨ε, ε0⟩).2.2 h), exact measure_mono (Inter_subset _ _) end theorem is_null_measurable.diff_null {s z : set α} (hs : is_null_measurable μ s) (hz : μ z = 0) : is_null_measurable μ (s \ z) := begin rcases hs with ⟨t, z', rfl, ht, hz'⟩, rw [set.union_diff_distrib], exact (ht.diff_null hz).union_null (measure_mono_null (diff_subset _ _) hz') end theorem is_null_measurable.compl {s : set α} (hs : is_null_measurable μ s) : is_null_measurable μ sᶜ := begin rcases hs with ⟨t, z, rfl, ht, hz⟩, rw compl_union, exact ht.compl.diff_null hz end /-- The measurable space of all null measurable sets. -/ def null_measurable {α : Type u} [measurable_space α] (μ : measure α) : measurable_space α := { is_measurable := is_null_measurable μ, is_measurable_empty := is_measurable.empty.is_null_measurable _, is_measurable_compl := λ s hs, hs.compl, is_measurable_Union := λ f, is_null_measurable.Union_nat } /-- Given a measure we can complete it to a (complete) measure on all null measurable sets. -/ def completion {α : Type u} [measurable_space α] (μ : measure α) : @measure_theory.measure α (null_measurable μ) := { to_outer_measure := μ.to_outer_measure, m_Union := λ s hs hd, show μ (Union s) = ∑' i, μ (s i), begin choose t ht using assume i, is_null_measurable_iff.1 (hs i), simp [forall_and_distrib] at ht, rcases ht with ⟨st, ht, hz⟩, rw is_null_measurable_measure_eq (Union_subset_Union st), { rw measure_Union _ ht, { congr, funext i, exact (is_null_measurable_measure_eq (st i) (hz i)).symm }, { rintro i j ij x ⟨h₁, h₂⟩, exact hd i j ij ⟨st i h₁, st j h₂⟩ } }, { refine measure_mono_null _ (measure_Union_null hz), rw [diff_subset_iff, ← Union_union_distrib], exact Union_subset_Union (λ i, by rw ← diff_subset_iff) } end, trimmed := begin letI := null_measurable μ, refine le_antisymm (λ s, _) (outer_measure.trim_ge _), rw outer_measure.trim_eq_infi, dsimp, clear _inst, resetI, rw measure_eq_infi s, exact infi_le_infi (λ t, infi_le_infi $ λ st, infi_le_infi2 $ λ ht, ⟨ht.is_null_measurable _, le_refl _⟩) end } instance completion.is_complete {α : Type u} [measurable_space α] (μ : measure α) : (completion μ).is_complete := λ z hz, null_is_null_measurable hz end is_complete namespace measure_theory section prio set_option default_priority 100 -- see Note [default priority] /-- A measure space is a measurable space equipped with a measure, referred to as `volume`. -/ class measure_space (α : Type*) extends measurable_space α := (volume : measure α) end prio export measure_space (volume) /-- `volume` is the canonical measure on `α`. -/ add_decl_doc volume section measure_space variables {α : Type*} {ι : Type*} [measure_space α] {s₁ s₂ : set α} notation `∀ᵐ` binders `, ` r:(scoped P, volume.ae.eventually P) := r end measure_space end measure_theory
71670146abb508911994dcacb276735efea470c4
4727251e0cd73359b15b664c3170e5d754078599
/src/topology/hom/open.lean
67ad4a5d027fda09afa9096aeb20aecef3e11276
[ "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
4,098
lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import topology.continuous_function.basic /-! # Continuous open maps This file defines bundled continuous open maps. We use the `fun_like` design, so each type of morphisms has a companion typeclass which is meant to be satisfied by itself and all stricter types. ## Types of morphisms * `continuous_open_map`: Continuous open maps. ## Typeclasses * `continuous_open_map_class` -/ open function variables {F α β γ δ : Type*} /-- The type of continuous open maps from `α` to `β`, aka Priestley homomorphisms. -/ structure continuous_open_map (α β : Type*) [topological_space α] [topological_space β] extends continuous_map α β := (map_open' : is_open_map to_fun) infixr ` →CO `:25 := continuous_open_map /-- `continuous_open_map_class F α β` states that `F` is a type of continuous open maps. You should extend this class when you extend `continuous_open_map`. -/ class continuous_open_map_class (F : Type*) (α β : out_param $ Type*) [topological_space α] [topological_space β] extends continuous_map_class F α β := (map_open (f : F) : is_open_map f) export continuous_open_map_class (map_open) instance [topological_space α] [topological_space β] [continuous_open_map_class F α β] : has_coe_t F (α →CO β) := ⟨λ f, ⟨f, map_open f⟩⟩ /-! ### Continuous open maps -/ namespace continuous_open_map variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] instance : continuous_open_map_class (α →CO β) α β := { coe := λ f, f.to_fun, coe_injective' := λ f g h, by { obtain ⟨⟨_, _⟩, _⟩ := f, obtain ⟨⟨_, _⟩, _⟩ := g, congr' }, map_continuous := λ f, f.continuous_to_fun, map_open := λ f, f.map_open' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (α →CO β) (λ _, α → β) := fun_like.has_coe_to_fun @[simp] lemma to_fun_eq_coe {f : α →CO β} : f.to_fun = (f : α → β) := rfl @[ext] lemma ext {f g : α →CO β} (h : ∀ a, f a = g a) : f = g := fun_like.ext f g h /-- Copy of a `continuous_open_map` with a new `continuous_map` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : α →CO β) (f' : α → β) (h : f' = f) : α →CO β := ⟨f.to_continuous_map.copy f' $ by exact h, h.symm.subst f.map_open'⟩ variables (α) /-- `id` as a `continuous_open_map`. -/ protected def id : α →CO α := ⟨continuous_map.id _, is_open_map.id⟩ instance : inhabited (α →CO α) := ⟨continuous_open_map.id _⟩ @[simp] lemma coe_id : ⇑(continuous_open_map.id α) = id := rfl variables {α} @[simp] lemma id_apply (a : α) : continuous_open_map.id α a = a := rfl /-- Composition of `continuous_open_map`s as a `continuous_open_map`. -/ def comp (f : β →CO γ) (g : α →CO β) : continuous_open_map α γ := ⟨f.to_continuous_map.comp g.to_continuous_map, f.map_open'.comp g.map_open'⟩ @[simp] lemma coe_comp (f : β →CO γ) (g : α →CO β) : (f.comp g : α → γ) = f ∘ g := rfl @[simp] lemma comp_apply (f : β →CO γ) (g : α →CO β) (a : α) : (f.comp g) a = f (g a) := rfl @[simp] lemma comp_assoc (f : γ →CO δ) (g : β →CO γ) (h : α →CO β) : (f.comp g).comp h = f.comp (g.comp h) := rfl @[simp] lemma comp_id (f : α →CO β) : f.comp (continuous_open_map.id α) = f := ext $ λ a, rfl @[simp] lemma id_comp (f : α →CO β) : (continuous_open_map.id β).comp f = f := ext $ λ a, rfl lemma cancel_right {g₁ g₂ : β →CO γ} {f : α →CO β} (hf : surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, ext $ hf.forall.2 $ fun_like.ext_iff.1 h, congr_arg _⟩ lemma cancel_left {g : β →CO γ} {f₁ f₂ : α →CO β} (hg : injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, ext $ λ a, hg $ by rw [←comp_apply, h, comp_apply], congr_arg _⟩ end continuous_open_map
74ef270a800fdbcd8526fe607ecf0773e3f4a046
618003631150032a5676f229d13a079ac875ff77
/src/ring_theory/algebra.lean
c2b781106de4e963ae5ee0b5c17b908aafdae1b0
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
31,719
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Yury Kudryashov -/ import data.matrix.basic import linear_algebra.tensor_product import algebra.commute import data.equiv.ring /-! # Algebra over Commutative Semiring (under category) In this file we define algebra over commutative (semi)rings, algebra homomorphisms `alg_hom`, algebra equivalences `alg_equiv`, and `subalgebra`s. We also define usual operations on `alg_hom`s (`id`, `comp`) and subalgebras (`map`, `comap`). ## Notations * `A →ₐ[R] B` : `R`-algebra homomorphism from `A` to `B`. * `A ≃ₐ[R] B` : `R`-algebra equivalence from `A` to `B`. -/ noncomputable theory universes u v w u₁ v₁ open_locale tensor_product section prio -- We set this priority to 0 later in this file set_option default_priority 200 -- see Note [default priority] /-- The category of R-algebras where R is a commutative ring is the under category R ↓ CRing. In the categorical setting we have a forgetful functor R-Alg ⥤ R-Mod. However here it extends module in order to preserve definitional equality in certain cases. -/ @[nolint has_inhabited_instance] class algebra (R : Type u) (A : Type v) [comm_semiring R] [semiring A] extends has_scalar R A, R →+* A := (commutes' : ∀ r x, to_fun r * x = x * to_fun r) (smul_def' : ∀ r x, r • x = to_fun r * x) end prio /-- Embedding `R →+* A` given by `algebra` structure. -/ def algebra_map (R : Type u) (A : Type v) [comm_semiring R] [semiring A] [algebra R A] : R →+* A := algebra.to_ring_hom /-- Creating an algebra from a morphism to the center of a semiring. -/ def ring_hom.to_algebra' {R S} [comm_semiring R] [semiring S] (i : R →+* S) (h : ∀ c x, i c * x = x * i c) : algebra R S := { smul := λ c x, i c * x, commutes' := h, smul_def' := λ c x, rfl, .. i} /-- Creating an algebra from a morphism to a commutative semiring. -/ def ring_hom.to_algebra {R S} [comm_semiring R] [comm_semiring S] (i : R →+* S) : algebra R S := i.to_algebra' $ λ _, mul_comm _ namespace algebra variables {R : Type u} {S : Type v} {A : Type w} /-- Let `R` be a commutative semiring, let `A` be a semiring with a `semimodule R` structure. If `(r • 1) * x = x * (r • 1) = r • x` for all `r : R` and `x : A`, then `A` is an `algebra` over `R`. -/ def of_semimodule' [comm_semiring R] [semiring A] [semimodule R A] (h₁ : ∀ (r : R) (x : A), (r • 1) * x = r • x) (h₂ : ∀ (r : R) (x : A), x * (r • 1) = r • x) : algebra R A := { to_fun := λ r, r • 1, map_one' := one_smul _ _, map_mul' := λ r₁ r₂, by rw [h₁, mul_smul], map_zero' := zero_smul _ _, map_add' := λ r₁ r₂, add_smul r₁ r₂ 1, commutes' := λ r x, by simp only [h₁, h₂], smul_def' := λ r x, by simp only [h₁] } /-- Let `R` be a commutative semiring, let `A` be a semiring with a `semimodule R` structure. If `(r • x) * y = x * (r • y) = r • (x * y)` for all `r : R` and `x y : A`, then `A` is an `algebra` over `R`. -/ def of_semimodule [comm_semiring R] [semiring A] [semimodule R A] (h₁ : ∀ (r : R) (x y : A), (r • x) * y = r • (x * y)) (h₂ : ∀ (r : R) (x y : A), x * (r • y) = r • (x * y)) : algebra R A := of_semimodule' (λ r x, by rw [h₁, one_mul]) (λ r x, by rw [h₂, mul_one]) section semiring variables [comm_semiring R] [comm_semiring S] [semiring A] [algebra R A] lemma smul_def'' (r : R) (x : A) : r • x = algebra_map R A r * x := algebra.smul_def' r x @[priority 200] -- see Note [lower instance priority] instance to_semimodule : semimodule R A := { one_smul := by simp [smul_def''], mul_smul := by simp [smul_def'', mul_assoc], smul_add := by simp [smul_def'', mul_add], smul_zero := by simp [smul_def''], add_smul := by simp [smul_def'', add_mul], zero_smul := by simp [smul_def''] } -- from now on, we don't want to use the following instance anymore attribute [instance, priority 0] algebra.to_has_scalar lemma smul_def (r : R) (x : A) : r • x = algebra_map R A r * x := algebra.smul_def' r x theorem commutes (r : R) (x : A) : algebra_map R A r * x = x * algebra_map R A r := algebra.commutes' r x theorem left_comm (r : R) (x y : A) : x * (algebra_map R A r * y) = algebra_map R A r * (x * y) := by rw [← mul_assoc, ← commutes, mul_assoc] @[simp] lemma mul_smul_comm (s : R) (x y : A) : x * (s • y) = s • (x * y) := by rw [smul_def, smul_def, left_comm] @[simp] lemma smul_mul_assoc (r : R) (x y : A) : (r • x) * y = r • (x * y) := by rw [smul_def, smul_def, mul_assoc] end semiring -- TODO (semimodule linear maps): once we have them, port next section to semirings section ring variables [comm_ring R] [ring A] [algebra R A] /-- Creating an algebra from a subring. This is the dual of ring extension. -/ instance of_subring (S : set R) [is_subring S] : algebra S R := ring_hom.to_algebra ⟨coe, rfl, λ _ _, rfl, rfl, λ _ _, rfl⟩ variables (R A) /-- The multiplication in an algebra is a bilinear map. -/ def lmul : A →ₗ A →ₗ A := linear_map.mk₂ R (*) (λ x y z, add_mul x y z) (λ c x y, by rw [smul_def, smul_def, mul_assoc _ x y]) (λ x y z, mul_add x y z) (λ c x y, by rw [smul_def, smul_def, left_comm]) /-- The multiplication on the left in an algebra is a linear map. -/ def lmul_left (r : A) : A →ₗ A := lmul R A r /-- The multiplication on the right in an algebra is a linear map. -/ def lmul_right (r : A) : A →ₗ A := (lmul R A).flip r variables {R A} @[simp] lemma lmul_apply (p q : A) : lmul R A p q = p * q := rfl @[simp] lemma lmul_left_apply (p q : A) : lmul_left R A p q = p * q := rfl @[simp] lemma lmul_right_apply (p q : A) : lmul_right R A p q = q * p := rfl end ring end algebra instance module.endomorphism_algebra (R : Type u) (M : Type v) [comm_ring R] [add_comm_group M] [module R M] : algebra R (M →ₗ[R] M) := { to_fun := λ r, r • linear_map.id, map_one' := one_smul _ _, map_zero' := zero_smul _ _, map_add' := λ r₁ r₂, add_smul _ _ _, map_mul' := λ r₁ r₂, by { ext x, simp [mul_smul] }, commutes' := by { intros, ext, simp }, smul_def' := by { intros, ext, simp } } instance matrix_algebra (n : Type u) (R : Type v) [fintype n] [decidable_eq n] [comm_semiring R] : algebra R (matrix n n R) := { to_fun := λ r, r • 1, map_one' := one_smul _ _, map_mul' := λ r₁ r₂, by { ext, simp [mul_assoc] }, map_zero' := zero_smul _ _, map_add' := λ _ _, add_smul _ _ _, commutes' := by { intros, simp }, smul_def' := by { intros, simp } } set_option old_structure_cmd true /-- Defining the homomorphism in the category R-Alg. -/ @[nolint has_inhabited_instance] structure alg_hom (R : Type u) (A : Type v) (B : Type w) [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] extends ring_hom A B := (commutes' : ∀ r : R, to_fun (algebra_map R A r) = algebra_map R B r) run_cmd tactic.add_doc_string `alg_hom.to_ring_hom "Reinterpret an `alg_hom` as a `ring_hom`" infixr ` →ₐ `:25 := alg_hom _ notation A ` →ₐ[`:25 R `] ` B := alg_hom R A B namespace alg_hom variables {R : Type u} {A : Type v} {B : Type w} {C : Type u₁} {D : Type v₁} section semiring variables [comm_semiring R] [semiring A] [semiring B] [semiring C] [semiring D] variables [algebra R A] [algebra R B] [algebra R C] [algebra R D] instance : has_coe_to_fun (A →ₐ[R] B) := ⟨_, λ f, f.to_fun⟩ instance coe_ring_hom : has_coe (A →ₐ[R] B) (A →+* B) := ⟨alg_hom.to_ring_hom⟩ instance coe_monoid_hom : has_coe (A →ₐ[R] B) (A →* B) := ⟨λ f, ↑(f : A →+* B)⟩ instance coe_add_monoid_hom : has_coe (A →ₐ[R] B) (A →+ B) := ⟨λ f, ↑(f : A →+* B)⟩ @[simp, norm_cast] lemma coe_mk {f : A → B} (h₁ h₂ h₃ h₄ h₅) : ⇑(⟨f, h₁, h₂, h₃, h₄, h₅⟩ : A →ₐ[R] B) = f := rfl @[simp, norm_cast] lemma coe_to_ring_hom (f : A →ₐ[R] B) : ⇑(f : A →+* B) = f := rfl @[norm_cast] lemma coe_to_monoid_hom (f : A →ₐ[R] B) : ⇑(f : A →* B) = f := rfl @[norm_cast] lemma coe_to_add_monoid_hom (f : A →ₐ[R] B) : ⇑(f : A →+ B) = f := rfl variables (φ : A →ₐ[R] B) theorem coe_fn_inj ⦃φ₁ φ₂ : A →ₐ[R] B⦄ (H : ⇑φ₁ = φ₂) : φ₁ = φ₂ := by { cases φ₁, cases φ₂, congr, exact H } theorem coe_ring_hom_inj : function.injective (coe : (A →ₐ[R] B) → (A →+* B)) := λ φ₁ φ₂ H, coe_fn_inj $ show ((φ₁ : (A →+* B)) : A → B) = ((φ₂ : (A →+* B)) : A → B), from congr_arg _ H theorem coe_monoid_hom_inj : function.injective (coe : (A →ₐ[R] B) → (A →* B)) := ring_hom.coe_monoid_hom_inj.comp coe_ring_hom_inj theorem coe_add_monoid_hom_inj : function.injective (coe : (A →ₐ[R] B) → (A →+ B)) := ring_hom.coe_add_monoid_hom_inj.comp coe_ring_hom_inj @[ext] theorem ext ⦃φ₁ φ₂ : A →ₐ[R] B⦄ (H : ∀ x, φ₁ x = φ₂ x) : φ₁ = φ₂ := coe_fn_inj $ funext H theorem commutes (r : R) : φ (algebra_map R A r) = algebra_map R B r := φ.commutes' r theorem comp_algebra_map : φ.to_ring_hom.comp (algebra_map R A) = algebra_map R B := ring_hom.ext $ φ.commutes @[simp] lemma map_add (r s : A) : φ (r + s) = φ r + φ s := φ.to_ring_hom.map_add r s @[simp] lemma map_zero : φ 0 = 0 := φ.to_ring_hom.map_zero @[simp] lemma map_mul (x y) : φ (x * y) = φ x * φ y := φ.to_ring_hom.map_mul x y @[simp] lemma map_one : φ 1 = 1 := φ.to_ring_hom.map_one @[simp] lemma map_smul (r : R) (x : A) : φ (r • x) = r • φ x := by simp only [algebra.smul_def, map_mul, commutes] @[simp] lemma map_pow (x : A) (n : ℕ) : φ (x ^ n) = (φ x) ^ n := φ.to_ring_hom.map_pow x n lemma map_sum {ι : Type*} (f : ι → A) (s : finset ι) : φ (s.sum f) = s.sum (λx, φ (f x)) := φ.to_ring_hom.map_sum f s section variables (R A) /-- Identity map as an `alg_hom`. -/ protected def id : A →ₐ[R] A := { commutes' := λ _, rfl, ..ring_hom.id A } end @[simp] lemma id_apply (p : A) : alg_hom.id R A p = p := rfl /-- Composition of algebra homeomorphisms. -/ def comp (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) : A →ₐ[R] C := { commutes' := λ r : R, by rw [← φ₁.commutes, ← φ₂.commutes]; refl, .. φ₁.to_ring_hom.comp ↑φ₂ } @[simp] lemma comp_apply (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) (p : A) : φ₁.comp φ₂ p = φ₁ (φ₂ p) := rfl @[simp] theorem comp_id : φ.comp (alg_hom.id R A) = φ := ext $ λ x, rfl @[simp] theorem id_comp : (alg_hom.id R B).comp φ = φ := ext $ λ x, rfl theorem comp_assoc (φ₁ : C →ₐ[R] D) (φ₂ : B →ₐ[R] C) (φ₃ : A →ₐ[R] B) : (φ₁.comp φ₂).comp φ₃ = φ₁.comp (φ₂.comp φ₃) := ext $ λ x, rfl end semiring section comm_semiring variables [comm_semiring R] [comm_semiring A] [comm_semiring B] variables [algebra R A] [algebra R B] variables (φ : A →ₐ[R] B) lemma map_prod {ι : Type*} (f : ι → A) (s : finset ι) : φ (s.prod f) = s.prod (λx, φ (f x)) := φ.to_ring_hom.map_prod f s end comm_semiring variables [comm_ring R] [ring A] [ring B] [ring C] variables [algebra R A] [algebra R B] [algebra R C] (φ : A →ₐ[R] B) @[simp] lemma map_neg (x) : φ (-x) = -φ x := φ.to_ring_hom.map_neg x @[simp] lemma map_sub (x y) : φ (x - y) = φ x - φ y := φ.to_ring_hom.map_sub x y /-- R-Alg ⥤ R-Mod -/ def to_linear_map : A →ₗ B := { to_fun := φ, add := φ.map_add, smul := φ.map_smul } @[simp] lemma to_linear_map_apply (p : A) : φ.to_linear_map p = φ p := rfl theorem to_linear_map_inj {φ₁ φ₂ : A →ₐ[R] B} (H : φ₁.to_linear_map = φ₂.to_linear_map) : φ₁ = φ₂ := ext $ λ x, show φ₁.to_linear_map x = φ₂.to_linear_map x, by rw H @[simp] lemma comp_to_linear_map (f : A →ₐ[R] B) (g : B →ₐ[R] C) : (g.comp f).to_linear_map = g.to_linear_map.comp f.to_linear_map := rfl end alg_hom set_option old_structure_cmd true /-- An equivalence of algebras is an equivalence of rings commuting with the actions of scalars. -/ structure alg_equiv (R : Type u) (A : Type v) (B : Type w) [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] extends A ≃ B, A ≃* B, A ≃+ B, A ≃+* B := (commutes' : ∀ r : R, to_fun (algebra_map R A r) = algebra_map R B r) attribute [nolint doc_blame] alg_equiv.to_ring_equiv attribute [nolint doc_blame] alg_equiv.to_equiv attribute [nolint doc_blame] alg_equiv.to_add_equiv attribute [nolint doc_blame] alg_equiv.to_mul_equiv notation A ` ≃ₐ[`:50 R `] ` A' := alg_equiv R A A' namespace alg_equiv variables {R : Type u} {A₁ : Type v} {A₂ : Type w} {A₃ : Type u₁} variables [comm_semiring R] [semiring A₁] [semiring A₂] [semiring A₃] variables [algebra R A₁] [algebra R A₂] [algebra R A₃] instance : has_coe_to_fun (A₁ ≃ₐ[R] A₂) := ⟨_, alg_equiv.to_fun⟩ instance has_coe_to_ring_equiv : has_coe (A₁ ≃ₐ[R] A₂) (A₁ ≃+* A₂) := ⟨alg_equiv.to_ring_equiv⟩ @[simp, norm_cast] lemma coe_ring_equiv (e : A₁ ≃ₐ[R] A₂) : ((e : A₁ ≃+* A₂) : A₁ → A₂) = e := rfl @[simp] lemma map_add (e : A₁ ≃ₐ[R] A₂) : ∀ x y, e (x + y) = e x + e y := e.to_add_equiv.map_add @[simp] lemma map_zero (e : A₁ ≃ₐ[R] A₂) : e 0 = 0 := e.to_add_equiv.map_zero @[simp] lemma map_mul (e : A₁ ≃ₐ[R] A₂) : ∀ x y, e (x * y) = (e x) * (e y) := e.to_mul_equiv.map_mul @[simp] lemma map_one (e : A₁ ≃ₐ[R] A₂) : e 1 = 1 := e.to_mul_equiv.map_one @[simp] lemma commutes (e : A₁ ≃ₐ[R] A₂) : ∀ (r : R), e (algebra_map R A₁ r) = algebra_map R A₂ r := e.commutes' @[simp] lemma map_neg {A₁ : Type v} {A₂ : Type w} [ring A₁] [ring A₂] [algebra R A₁] [algebra R A₂] (e : A₁ ≃ₐ[R] A₂) : ∀ x, e (-x) = -(e x) := e.to_add_equiv.map_neg @[simp] lemma map_sub {A₁ : Type v} {A₂ : Type w} [ring A₁] [ring A₂] [algebra R A₁] [algebra R A₂] (e : A₁ ≃ₐ[R] A₂) : ∀ x y, e (x - y) = e x - e y := e.to_add_equiv.map_sub instance has_coe_to_alg_hom : has_coe (A₁ ≃ₐ[R] A₂) (A₁ →ₐ[R] A₂) := ⟨λ e, { map_one' := e.map_one, map_zero' := e.map_zero, ..e }⟩ @[simp, norm_cast] lemma coe_to_alg_equiv (e : A₁ ≃ₐ[R] A₂) : ((e : A₁ →ₐ[R] A₂) : A₁ → A₂) = e := rfl lemma injective (e : A₁ ≃ₐ[R] A₂) : function.injective e := e.to_equiv.injective lemma surjective (e : A₁ ≃ₐ[R] A₂) : function.surjective e := e.to_equiv.surjective lemma bijective (e : A₁ ≃ₐ[R] A₂) : function.bijective e := e.to_equiv.bijective instance : has_one (A₁ ≃ₐ[R] A₁) := ⟨{commutes' := λ r, rfl, ..(1 : A₁ ≃+* A₁)}⟩ instance : inhabited (A₁ ≃ₐ[R] A₁) := ⟨1⟩ /-- Algebra equivalences are reflexive. -/ @[refl] def refl : A₁ ≃ₐ[R] A₁ := 1 /-- Algebra equivalences are symmetric. -/ @[symm] def symm (e : A₁ ≃ₐ[R] A₂) : A₂ ≃ₐ[R] A₁ := { commutes' := λ r, by { rw ←e.to_ring_equiv.symm_apply_apply (algebra_map R A₁ r), congr, change _ = e _, rw e.commutes, }, ..e.to_ring_equiv.symm, } /-- Algebra equivalences are transitive. -/ @[trans] def trans (e₁ : A₁ ≃ₐ[R] A₂) (e₂ : A₂ ≃ₐ[R] A₃) : A₁ ≃ₐ[R] A₃ := { commutes' := λ r, show e₂.to_fun (e₁.to_fun _) = _, by rw [e₁.commutes', e₂.commutes'], ..(e₁.to_ring_equiv.trans e₂.to_ring_equiv), } @[simp] lemma apply_symm_apply (e : A₁ ≃ₐ[R] A₂) : ∀ x, e (e.symm x) = x := e.to_equiv.apply_symm_apply @[simp] lemma symm_apply_apply (e : A₁ ≃ₐ[R] A₂) : ∀ x, e.symm (e x) = x := e.to_equiv.symm_apply_apply end alg_equiv namespace algebra variables (R : Type u) (S : Type v) (A : Type w) include R S A /-- `comap R S A` is a type alias for `A`, and has an R-algebra structure defined on it when `algebra R S` and `algebra S A`. -/ /- This is done to avoid a type class search with meta-variables `algebra R ?m_1` and `algebra ?m_1 A -/ /- The `nolint` attribute is added because it has unused arguments `R` and `S`, but these are necessary for synthesizing the appropriate type classes -/ @[nolint unused_arguments] def comap : Type w := A instance comap.inhabited [h : inhabited A] : inhabited (comap R S A) := h instance comap.semiring [h : semiring A] : semiring (comap R S A) := h instance comap.ring [h : ring A] : ring (comap R S A) := h instance comap.comm_semiring [h : comm_semiring A] : comm_semiring (comap R S A) := h instance comap.comm_ring [h : comm_ring A] : comm_ring (comap R S A) := h instance comap.algebra' [comm_semiring S] [semiring A] [h : algebra S A] : algebra S (comap R S A) := h /-- Identity homomorphism `A →ₐ[S] comap R S A`. -/ def comap.to_comap [comm_semiring S] [semiring A] [algebra S A] : A →ₐ[S] comap R S A := alg_hom.id S A /-- Identity homomorphism `comap R S A →ₐ[S] A`. -/ def comap.of_comap [comm_semiring S] [semiring A] [algebra S A] : comap R S A →ₐ[S] A := alg_hom.id S A variables [comm_semiring R] [comm_semiring S] [semiring A] [algebra R S] [algebra S A] /-- `R ⟶ S` induces `S-Alg ⥤ R-Alg` -/ instance comap.algebra : algebra R (comap R S A) := { smul := λ r x, (algebra_map R S r • x : A), commutes' := λ r x, algebra.commutes _ _, smul_def' := λ _ _, algebra.smul_def _ _, .. (algebra_map S A).comp (algebra_map R S) } /-- Embedding of `S` into `comap R S A`. -/ def to_comap : S →ₐ[R] comap R S A := { commutes' := λ r, rfl, .. algebra_map S A } theorem to_comap_apply (x) : to_comap R S A x = algebra_map S A x := rfl end algebra namespace alg_hom variables {R : Type u} {S : Type v} {A : Type w} {B : Type u₁} variables [comm_semiring R] [comm_semiring S] [semiring A] [semiring B] variables [algebra R S] [algebra S A] [algebra S B] (φ : A →ₐ[S] B) include R /-- R ⟶ S induces S-Alg ⥤ R-Alg -/ def comap : algebra.comap R S A →ₐ[R] algebra.comap R S B := { commutes' := λ r, φ.commutes (algebra_map R S r) ..φ } end alg_hom namespace rat instance algebra_rat {α} [division_ring α] [char_zero α] : algebra ℚ α := (rat.cast_hom α).to_algebra' $ λ r x, (commute.cast_int_left x r.1).div_left (commute.cast_nat_left x r.2) end rat /-- A subalgebra is a subring that includes the range of `algebra_map`. -/ structure subalgebra (R : Type u) (A : Type v) [comm_ring R] [ring A] [algebra R A] : Type v := (carrier : set A) [subring : is_subring carrier] (range_le' : set.range (algebra_map R A) ≤ carrier) namespace subalgebra variables {R : Type u} {A : Type v} variables [comm_ring R] [ring A] [algebra R A] include R instance : has_coe (subalgebra R A) (set A) := ⟨λ S, S.carrier⟩ lemma range_le (S : subalgebra R A) : set.range (algebra_map R A) ≤ S := S.range_le' instance : has_mem A (subalgebra R A) := ⟨λ x S, x ∈ (S : set A)⟩ variables {A} theorem mem_coe {x : A} {s : subalgebra R A} : x ∈ (s : set A) ↔ x ∈ s := iff.rfl @[ext] theorem ext {S T : subalgebra R A} (h : ∀ x : A, x ∈ S ↔ x ∈ T) : S = T := by cases S; cases T; congr; ext x; exact h x theorem ext_iff {S T : subalgebra R A} : S = T ↔ ∀ x : A, x ∈ S ↔ x ∈ T := ⟨λ h x, by rw h, ext⟩ variables (S : subalgebra R A) instance : is_subring (S : set A) := S.subring instance : ring S := @@subtype.ring _ S.is_subring instance : inhabited S := ⟨0⟩ instance (R : Type u) (A : Type v) [comm_ring R] [comm_ring A] [algebra R A] (S : subalgebra R A) : comm_ring S := @@subtype.comm_ring _ S.is_subring instance algebra : algebra R S := { smul := λ (c:R) x, ⟨c • x.1, by rw algebra.smul_def; exact @@is_submonoid.mul_mem _ S.2.2 (S.3 ⟨c, rfl⟩) x.2⟩, commutes' := λ c x, subtype.eq $ algebra.commutes _ _, smul_def' := λ c x, subtype.eq $ algebra.smul_def _ _, .. (algebra_map R A).cod_restrict S $ λ x, S.range_le ⟨x, rfl⟩ } instance to_algebra (R : Type u) (A : Type v) [comm_ring R] [comm_ring A] [algebra R A] (S : subalgebra R A) : algebra S A := algebra.of_subring _ /-- Embedding of a subalgebra into the algebra. -/ def val : S →ₐ[R] A := by refine_struct { to_fun := subtype.val }; intros; refl /-- Convert a `subalgebra` to `submodule` -/ def to_submodule : submodule R A := { carrier := S, zero := (0:S).2, add := λ x y hx hy, (⟨x, hx⟩ + ⟨y, hy⟩ : S).2, smul := λ c x hx, (algebra.smul_def c x).symm ▸ (⟨algebra_map R A c, S.range_le ⟨c, rfl⟩⟩ * ⟨x, hx⟩:S).2 } instance coe_to_submodule : has_coe (subalgebra R A) (submodule R A) := ⟨to_submodule⟩ instance to_submodule.is_subring : is_subring ((S : submodule R A) : set A) := S.2 instance : partial_order (subalgebra R A) := { le := λ S T, (S : set A) ≤ (T : set A), le_refl := λ _, le_refl _, le_trans := λ _ _ _, le_trans, le_antisymm := λ S T hst hts, ext $ λ x, ⟨@hst x, @hts x⟩ } /-- Reinterpret an `S`-subalgebra as an `R`-subalgebra in `comap R S A`. -/ def comap {R : Type u} {S : Type v} {A : Type w} [comm_ring R] [comm_ring S] [ring A] [algebra R S] [algebra S A] (iSB : subalgebra S A) : subalgebra R (algebra.comap R S A) := { carrier := (iSB : set A), subring := iSB.is_subring, range_le' := λ a ⟨r, hr⟩, hr ▸ iSB.range_le ⟨_, rfl⟩ } /-- If `S` is an `R`-subalgebra of `A` and `T` is an `S`-subalgebra of `A`, then `T` is an `R`-subalgebra of `A`. -/ def under {R : Type u} {A : Type v} [comm_ring R] [comm_ring A] {i : algebra R A} (S : subalgebra R A) (T : subalgebra S A) : subalgebra R A := { carrier := T, range_le' := (λ a ⟨r, hr⟩, hr ▸ T.range_le ⟨⟨algebra_map R A r, S.range_le ⟨r, rfl⟩⟩, rfl⟩) } lemma mul_mem (A' : subalgebra R A) (x y : A) : x ∈ A' → y ∈ A' → x * y ∈ A' := @is_submonoid.mul_mem A _ A' _ x y end subalgebra namespace alg_hom variables {R : Type u} {A : Type v} {B : Type w} variables [comm_ring R] [ring A] [ring B] [algebra R A] [algebra R B] variables (φ : A →ₐ[R] B) /-- Range of an `alg_hom` as a subalgebra. -/ protected def range (φ : A →ₐ[R] B) : subalgebra R B := begin haveI : is_subring (set.range φ) := show is_subring (set.range φ.to_ring_hom), by apply_instance, exact ⟨set.range φ, λ y ⟨r, hr⟩, ⟨algebra_map R A r, hr ▸ φ.commutes r⟩⟩ end end alg_hom namespace algebra variables (R : Type u) (A : Type v) variables [comm_semiring R] [semiring A] [algebra R A] instance id : algebra R R := (ring_hom.id R).to_algebra namespace id @[simp] lemma map_eq_self (x : R) : algebra_map R R x = x := rfl @[simp] lemma smul_eq_mul (x y : R) : x • y = x * y := rfl end id /-- `algebra_map` as an `alg_hom`. -/ def of_id : R →ₐ[R] A := { commutes' := λ _, rfl, .. algebra_map R A } variables {R} theorem of_id_apply (r) : of_id R A r = algebra_map R A r := rfl end algebra namespace algebra variables (R : Type u) {A : Type v} [comm_ring R] [ring A] [algebra R A] /-- The minimal subalgebra that includes `s`. -/ def adjoin (s : set A) : subalgebra R A := { carrier := ring.closure (set.range (algebra_map R A) ∪ s), range_le' := le_trans (set.subset_union_left _ _) ring.subset_closure } variables {R} protected lemma gc : galois_connection (adjoin R : set A → subalgebra R A) coe := λ s S, ⟨λ H, le_trans (le_trans (set.subset_union_right _ _) ring.subset_closure) H, λ H, ring.closure_subset $ set.union_subset S.range_le H⟩ /-- Galois insertion between `adjoin` and `coe`. -/ protected def gi : galois_insertion (adjoin R : set A → subalgebra R A) coe := { choice := λ s hs, adjoin R s, gc := algebra.gc, le_l_u := λ S, (algebra.gc (S : set A) (adjoin R S)).1 $ le_refl _, choice_eq := λ _ _, rfl } instance : complete_lattice (subalgebra R A) := galois_insertion.lift_complete_lattice algebra.gi instance : inhabited (subalgebra R A) := ⟨⊥⟩ theorem mem_bot {x : A} : x ∈ (⊥ : subalgebra R A) ↔ x ∈ set.range (algebra_map R A) := suffices (⊥ : subalgebra R A) = (of_id R A).range, by rw this; refl, le_antisymm bot_le $ subalgebra.range_le _ theorem mem_top {x : A} : x ∈ (⊤ : subalgebra R A) := ring.mem_closure $ or.inr trivial theorem eq_top_iff {S : subalgebra R A} : S = ⊤ ↔ ∀ x : A, x ∈ S := ⟨λ h x, by rw h; exact mem_top, λ h, by ext x; exact ⟨λ _, mem_top, λ _, h x⟩⟩ /-- `alg_hom` to `⊤ : subalgebra R A`. -/ def to_top : A →ₐ[R] (⊤ : subalgebra R A) := by refine_struct { to_fun := λ x, (⟨x, mem_top⟩ : (⊤ : subalgebra R A)) }; intros; refl end algebra section int variables (R : Type*) [ring R] /-- Reinterpret a `ring_hom` as a `ℤ`-algebra homomorphism. -/ def alg_hom_int {R : Type u} [comm_ring R] [algebra ℤ R] {S : Type v} [comm_ring S] [algebra ℤ S] (f : R →+* S) : R →ₐ[ℤ] S := { commutes' := λ i, show f _ = _, by simp, .. f } /-- CRing ⥤ ℤ-Alg -/ instance algebra_int : algebra ℤ R := { commutes' := λ x y, commute.cast_int_left _ _, smul_def' := λ _ _, gsmul_eq_mul _ _, .. int.cast_ring_hom R } variables {R} /-- A subring is a `ℤ`-subalgebra. -/ def subalgebra_of_subring (S : set R) [is_subring S] : subalgebra ℤ R := { carrier := S, range_le' := by { rintros _ ⟨i, rfl⟩, rw [ring_hom.eq_int_cast, ← gsmul_one], exact is_add_subgroup.gsmul_mem is_submonoid.one_mem } } @[simp] lemma mem_subalgebra_of_subring {x : R} {S : set R} [is_subring S] : x ∈ subalgebra_of_subring S ↔ x ∈ S := iff.rfl section span_int open submodule lemma span_int_eq_add_group_closure (s : set R) : ↑(span ℤ s) = add_group.closure s := set.subset.antisymm (λ x hx, span_induction hx (λ _, add_group.mem_closure) is_add_submonoid.zero_mem (λ a b ha hb, is_add_submonoid.add_mem ha hb) (λ n a ha, by { exact is_add_subgroup.gsmul_mem ha })) (add_group.closure_subset subset_span) @[simp] lemma span_int_eq (s : set R) [is_add_subgroup s] : (↑(span ℤ s) : set R) = s := by rw [span_int_eq_add_group_closure, add_group.closure_add_subgroup] end span_int end int section restrict_scalars /- In this section, we describe restriction of scalars: if `S` is an algebra over `R`, then `S`-modules are also `R`-modules. -/ variables (R : Type*) [comm_ring R] (S : Type*) [ring S] [algebra R S] variables (E : Type*) [add_comm_group E] [module S E] {F : Type*} [add_comm_group F] [module S F] /-- When `E` is a module over a ring `S`, and `S` is an algebra over `R`, then `E` inherits a module structure over `R`, called `module.restrict_scalars' R S E`. We do not register this as an instance as `S` can not be inferred. -/ def module.restrict_scalars' : module R E := { smul := λ c x, (algebra_map R S c) • x, one_smul := by simp, mul_smul := by simp [mul_smul], smul_add := by simp [smul_add], smul_zero := by simp [smul_zero], add_smul := by simp [add_smul], zero_smul := by simp [zero_smul] } /-- When `E` is a module over a ring `S`, and `S` is an algebra over `R`, then `E` inherits a module structure over `R`, provided as a type synonym `module.restrict_scalars R S E := E`. -/ @[nolint unused_arguments] def module.restrict_scalars (R : Type*) (S : Type*) (E : Type*) : Type* := E instance (R : Type*) (S : Type*) (E : Type*) [I : inhabited E] : inhabited (module.restrict_scalars R S E) := I instance (R : Type*) (S : Type*) (E : Type*) [I : add_comm_group E] : add_comm_group (module.restrict_scalars R S E) := I instance : module R (module.restrict_scalars R S E) := (module.restrict_scalars' R S E : module R E) lemma module.restrict_scalars_smul_def (c : R) (x : module.restrict_scalars R S E) : c • x = ((algebra_map R S c) • x : E) := rfl /-- `module.restrict_scalars R S S` is `R`-linearly equivalent to the original algebra `S`. Unfortunately these structures are not generally definitionally equal: the `R`-module structure on `S` is part of the data of `S`, while the `R`-module structure on `module.restrict_scalars R S S` comes from the ring homomorphism `R →+* S`, which is a separate part of the data of `S`. The field `algebra.smul_def'` gives the equation we need here. -/ def algebra.restrict_scalars_equiv : (module.restrict_scalars R S S) ≃ₗ[R] S := { to_fun := λ s, s, inv_fun := λ s, s, left_inv := λ s, rfl, right_inv := λ s, rfl, add := λ x y, rfl, smul := λ c x, (algebra.smul_def' _ _).symm, } @[simp] lemma algebra.restrict_scalars_equiv_apply (s : S) : algebra.restrict_scalars_equiv R S s = s := rfl @[simp] lemma algebra.restrict_scalars_equiv_symm_apply (s : S) : (algebra.restrict_scalars_equiv R S).symm s = s := rfl variables {S E} open module /-- `V.restrict_scalars R` is the `R`-submodule of the `R`-module given by restriction of scalars, corresponding to `V`, an `S`-submodule of the original `S`-module. -/ @[simps] def submodule.restrict_scalars (V : submodule S E) : submodule R (restrict_scalars R S E) := { carrier := V.carrier, zero := V.zero, smul := λ c e h, V.smul _ h, add := λ x y hx hy, V.add hx hy, } @[simp] lemma submodule.restrict_scalars_mem (V : submodule S E) (e : E) : e ∈ V.restrict_scalars R ↔ e ∈ V := iff.refl _ @[simp] lemma submodule.restrict_scalars_bot : submodule.restrict_scalars R (⊥ : submodule S E) = ⊥ := rfl @[simp] lemma submodule.restrict_scalars_top : submodule.restrict_scalars R (⊤ : submodule S E) = ⊤ := rfl /-- The `R`-linear map induced by an `S`-linear map when `S` is an algebra over `R`. -/ def linear_map.restrict_scalars (f : E →ₗ[S] F) : (restrict_scalars R S E) →ₗ[R] (restrict_scalars R S F) := { to_fun := f.to_fun, add := λx y, f.map_add x y, smul := λc x, f.map_smul (algebra_map R S c) x } @[simp, norm_cast squash] lemma linear_map.coe_restrict_scalars_eq_coe (f : E →ₗ[S] F) : (f.restrict_scalars R : E → F) = f := rfl @[simp] lemma restrict_scalars_ker (f : E →ₗ[S] F) : (f.restrict_scalars R).ker = submodule.restrict_scalars R f.ker := rfl end restrict_scalars /-! When `V` and `W` are `S`-modules, for some `R`-algebra `S`, the collection of `S`-linear maps from `V` to `W` forms an `R`-module. (But not generally an `S`-module, because `S` may be non-commutative.) -/ section module_of_linear_maps variables (R : Type*) [comm_ring R] (S : Type*) [ring S] [algebra R S] (V : Type*) [add_comm_group V] [module S V] (W : Type*) [add_comm_group W] [module S W] /-- For `r : R`, and `f : V →ₗ[S] W` (where `S` is an `R`-algebra) we define `(r • f) v = f (r • v)`. -/ def linear_map_algebra_has_scalar : has_scalar R (V →ₗ[S] W) := { smul := λ r f, { to_fun := λ v, f ((algebra_map R S r) • v), add := λ x y, by simp [smul_add], smul := λ s v, by simp [smul_smul, algebra.commutes], } } local attribute [instance] linear_map_algebra_has_scalar /-- The `R`-module structure on `S`-linear maps, for `S` an `R`-algebra. -/ def linear_map_algebra_module : module R (V →ₗ[S] W) := { one_smul := λ f, begin ext v, dsimp [(•)], simp, end, mul_smul := λ r r' f, begin ext v, dsimp [(•)], rw [linear_map.map_smul, linear_map.map_smul, linear_map.map_smul, ring_hom.map_mul, smul_smul, algebra.commutes], end, smul_zero := λ r, by { ext v, dsimp [(•)], refl, }, smul_add := λ r f g, by { ext v, dsimp [(•)], simp [linear_map.map_add], }, zero_smul := λ f, by { ext v, dsimp [(•)], simp, }, add_smul := λ r r' f, by { ext v, dsimp [(•)], simp [add_smul], }, } local attribute [instance] linear_map_algebra_module variables {R S V W} @[simp] lemma linear_map_algebra_module.smul_apply (c : R) (f : V →ₗ[S] W) (v : V) : (c • f) v = (c • (f v) : module.restrict_scalars R S W) := begin erw [linear_map.map_smul], refl, end end module_of_linear_maps
f331493cfe8a9589b2be09f1290f78a1db6866da
07c76fbd96ea1786cc6392fa834be62643cea420
/hott/hit/colimit.hlean
bedebd957f784594931501ad6f6cfc57d9950a3c
[ "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,888
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn Definition of general colimits and sequential colimits. -/ /- definition of a general colimit -/ open eq nat quotient sigma equiv is_trunc namespace colimit section parameters {I J : Type} (A : I → Type) (dom cod : J → I) (f : Π(j : J), A (dom j) → A (cod j)) variables {i : I} (a : A i) (j : J) (b : A (dom j)) local abbreviation B := Σ(i : I), A i inductive colim_rel : B → B → Type := | Rmk : Π{j : J} (a : A (dom j)), colim_rel ⟨cod j, f j a⟩ ⟨dom j, a⟩ open colim_rel local abbreviation R := colim_rel -- TODO: define this in root namespace definition colimit : Type := quotient colim_rel definition incl : colimit := class_of R ⟨i, a⟩ abbreviation ι := @incl definition cglue : ι (f j b) = ι b := eq_of_rel colim_rel (Rmk f b) protected definition rec {P : colimit → Type} (Pincl : Π⦃i : I⦄ (x : A i), P (ι x)) (Pglue : Π(j : J) (x : A (dom j)), Pincl (f j x) =[cglue j x] Pincl x) (y : colimit) : P y := begin fapply (quotient.rec_on y), { intro a, cases a, apply Pincl}, { intro a a' H, cases H, apply Pglue} end protected definition rec_on [reducible] {P : colimit → Type} (y : colimit) (Pincl : Π⦃i : I⦄ (x : A i), P (ι x)) (Pglue : Π(j : J) (x : A (dom j)), Pincl (f j x) =[cglue j x] Pincl x) : P y := rec Pincl Pglue y theorem rec_cglue {P : colimit → Type} (Pincl : Π⦃i : I⦄ (x : A i), P (ι x)) (Pglue : Π(j : J) (x : A (dom j)), Pincl (f j x) =[cglue j x] Pincl x) {j : J} (x : A (dom j)) : apd (rec Pincl Pglue) (cglue j x) = Pglue j x := !rec_eq_of_rel protected definition elim {P : Type} (Pincl : Π⦃i : I⦄ (x : A i), P) (Pglue : Π(j : J) (x : A (dom j)), Pincl (f j x) = Pincl x) (y : colimit) : P := rec Pincl (λj a, pathover_of_eq _ (Pglue j a)) y protected definition elim_on [reducible] {P : Type} (y : colimit) (Pincl : Π⦃i : I⦄ (x : A i), P) (Pglue : Π(j : J) (x : A (dom j)), Pincl (f j x) = Pincl x) : P := elim Pincl Pglue y theorem elim_cglue {P : Type} (Pincl : Π⦃i : I⦄ (x : A i), P) (Pglue : Π(j : J) (x : A (dom j)), Pincl (f j x) = Pincl x) {j : J} (x : A (dom j)) : ap (elim Pincl Pglue) (cglue j x) = Pglue j x := begin apply inj_inv !(pathover_constant (cglue j x)), rewrite [▸*,-apd_eq_pathover_of_eq_ap,↑elim,rec_cglue], end protected definition elim_type (Pincl : Π⦃i : I⦄ (x : A i), Type) (Pglue : Π(j : J) (x : A (dom j)), Pincl (f j x) ≃ Pincl x) (y : colimit) : Type := elim Pincl (λj a, ua (Pglue j a)) y protected definition elim_type_on [reducible] (y : colimit) (Pincl : Π⦃i : I⦄ (x : A i), Type) (Pglue : Π(j : J) (x : A (dom j)), Pincl (f j x) ≃ Pincl x) : Type := elim_type Pincl Pglue y theorem elim_type_cglue (Pincl : Π⦃i : I⦄ (x : A i), Type) (Pglue : Π(j : J) (x : A (dom j)), Pincl (f j x) ≃ Pincl x) {j : J} (x : A (dom j)) : transport (elim_type Pincl Pglue) (cglue j x) = Pglue j x := by rewrite [tr_eq_cast_ap_fn,↑elim_type,elim_cglue];apply cast_ua_fn protected definition rec_prop {P : colimit → Type} [H : Πx, is_prop (P x)] (Pincl : Π⦃i : I⦄ (x : A i), P (ι x)) (y : colimit) : P y := rec Pincl (λa b, !is_prop.elimo) y protected definition elim_prop {P : Type} [H : is_prop P] (Pincl : Π⦃i : I⦄ (x : A i), P) (y : colimit) : P := elim Pincl (λa b, !is_prop.elim) y end end colimit /- definition of a sequential colimit -/ namespace seq_colim section /- we define it directly in terms of quotients. An alternative definition could be definition seq_colim := colimit.colimit A id succ f -/ parameters {A : ℕ → Type} (f : Π⦃n⦄, A n → A (succ n)) variables {n : ℕ} (a : A n) local abbreviation B := Σ(n : ℕ), A n inductive seq_rel : B → B → Type := | Rmk : Π{n : ℕ} (a : A n), seq_rel ⟨succ n, f a⟩ ⟨n, a⟩ open seq_rel local abbreviation R := seq_rel -- TODO: define this in root namespace definition seq_colim : Type := quotient seq_rel definition inclusion : seq_colim := class_of R ⟨n, a⟩ abbreviation sι := @inclusion definition glue : sι (f a) = sι a := eq_of_rel seq_rel (Rmk f a) protected definition rec {P : seq_colim → Type} (Pincl : Π⦃n : ℕ⦄ (a : A n), P (sι a)) (Pglue : Π(n : ℕ) (a : A n), Pincl (f a) =[glue a] Pincl a) (aa : seq_colim) : P aa := begin fapply (quotient.rec_on aa), { intro a, cases a, apply Pincl}, { intro a a' H, cases H, apply Pglue} end protected definition rec_on [reducible] {P : seq_colim → Type} (aa : seq_colim) (Pincl : Π⦃n : ℕ⦄ (a : A n), P (sι a)) (Pglue : Π⦃n : ℕ⦄ (a : A n), Pincl (f a) =[glue a] Pincl a) : P aa := rec Pincl Pglue aa theorem rec_glue {P : seq_colim → Type} (Pincl : Π⦃n : ℕ⦄ (a : A n), P (sι a)) (Pglue : Π⦃n : ℕ⦄ (a : A n), Pincl (f a) =[glue a] Pincl a) {n : ℕ} (a : A n) : apd (rec Pincl Pglue) (glue a) = Pglue a := !rec_eq_of_rel protected definition elim {P : Type} (Pincl : Π⦃n : ℕ⦄ (a : A n), P) (Pglue : Π⦃n : ℕ⦄ (a : A n), Pincl (f a) = Pincl a) : seq_colim → P := rec Pincl (λn a, pathover_of_eq _ (Pglue a)) protected definition elim_on [reducible] {P : Type} (aa : seq_colim) (Pincl : Π⦃n : ℕ⦄ (a : A n), P) (Pglue : Π⦃n : ℕ⦄ (a : A n), Pincl (f a) = Pincl a) : P := elim Pincl Pglue aa theorem elim_glue {P : Type} (Pincl : Π⦃n : ℕ⦄ (a : A n), P) (Pglue : Π⦃n : ℕ⦄ (a : A n), Pincl (f a) = Pincl a) {n : ℕ} (a : A n) : ap (elim Pincl Pglue) (glue a) = Pglue a := begin apply inj_inv !(pathover_constant (glue a)), rewrite [▸*,-apd_eq_pathover_of_eq_ap,↑elim,rec_glue], end protected definition elim_type (Pincl : Π⦃n : ℕ⦄ (a : A n), Type) (Pglue : Π⦃n : ℕ⦄ (a : A n), Pincl (f a) ≃ Pincl a) : seq_colim → Type := elim Pincl (λn a, ua (Pglue a)) protected definition elim_type_on [reducible] (aa : seq_colim) (Pincl : Π⦃n : ℕ⦄ (a : A n), Type) (Pglue : Π⦃n : ℕ⦄ (a : A n), Pincl (f a) ≃ Pincl a) : Type := elim_type Pincl Pglue aa theorem elim_type_glue (Pincl : Π⦃n : ℕ⦄ (a : A n), Type) (Pglue : Π⦃n : ℕ⦄ (a : A n), Pincl (f a) ≃ Pincl a) {n : ℕ} (a : A n) : transport (elim_type Pincl Pglue) (glue a) = Pglue a := by rewrite [tr_eq_cast_ap_fn,↑elim_type,elim_glue]; apply cast_ua_fn theorem elim_type_glue_inv (Pincl : Π⦃n : ℕ⦄ (a : A n), Type) (Pglue : Π⦃n : ℕ⦄ (a : A n), Pincl (f a) ≃ Pincl a) {n : ℕ} (a : A n) : transport (seq_colim.elim_type f Pincl Pglue) (glue a)⁻¹ = to_inv (Pglue a) := by rewrite [tr_eq_cast_ap_fn, ↑seq_colim.elim_type, ap_inv, elim_glue]; apply cast_ua_inv_fn protected definition rec_prop {P : seq_colim → Type} [H : Πx, is_prop (P x)] (Pincl : Π⦃n : ℕ⦄ (a : A n), P (sι a)) (aa : seq_colim) : P aa := rec Pincl (λa b, !is_prop.elimo) aa protected definition elim_prop {P : Type} [H : is_prop P] (Pincl : Π⦃n : ℕ⦄ (a : A n), P) : seq_colim → P := elim Pincl (λa b, !is_prop.elim) end end seq_colim attribute colimit.incl seq_colim.inclusion [constructor] attribute colimit.rec colimit.elim [unfold 10] [recursor 10] attribute colimit.elim_type [unfold 9] attribute colimit.rec_on colimit.elim_on [unfold 8] attribute colimit.elim_type_on [unfold 7] attribute seq_colim.rec seq_colim.elim [unfold 6] [recursor 6] attribute seq_colim.elim_type [unfold 5] attribute seq_colim.rec_on seq_colim.elim_on [unfold 4] attribute seq_colim.elim_type_on [unfold 3]
1a9e7e266fef364faa0163485543324228d5c548
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/zipper.lean
3ec9be78eca66ba0a4fef338364be6438ea4f3c7
[ "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
1,421
lean
new_frontend structure ListZipper (α : Type) := (xs : List α) (bs : List α) -- set_option trace.compiler.ir.rc true variables {α : Type} namespace ListZipper def goForward : ListZipper α → ListZipper α | ⟨[], bs⟩ => ⟨[], bs⟩ | ⟨x::xs, bs⟩ => ⟨xs, x::bs⟩ def goBackward : ListZipper α → ListZipper α | ⟨xs, []⟩ => ⟨xs, []⟩ | ⟨xs, b::bs⟩ => ⟨b::xs, bs⟩ def insert : ListZipper α → α → ListZipper α | ⟨xs, bs⟩, x => ⟨xs, x::bs⟩ def erase : ListZipper α → ListZipper α | ⟨[], bs⟩ => ⟨[], bs⟩ | ⟨x::xs, bs⟩ => ⟨xs, bs⟩ def curr [Inhabited α] : ListZipper α → α | ⟨[], bs⟩ => arbitrary _ | ⟨x::xs, bs⟩ => x def currOpt : ListZipper α → Option α | ⟨[], bs⟩ => none | ⟨x::xs, bs⟩ => some x def toList : ListZipper α → List α | ⟨xs, bs⟩ => bs.reverse ++ xs def atEnd (z : ListZipper α) : Bool := z.xs.isEmpty end ListZipper def List.toListZipper (xs : List α) : ListZipper α := ⟨xs, []⟩ partial def testAux : ListZipper Nat → ListZipper Nat | z => if z.atEnd then z else if z.curr % 2 == 0 then testAux (z.goForward.insert 0) else if z.curr > 20 then testAux z.erase else testAux z.goForward -- testAux z.goForward def test (xs : List Nat) : List Nat := (testAux xs.toListZipper).toList #eval (IO.println (test [10, 11, 13, 20, 22, 40, 41, 11]) : IO Unit)
081b76a6204257050f3ec242885f33da59fe77cc
38bf3fd2bb651ab70511408fcf70e2029e2ba310
/src/algebra/category/Mon/colimits.lean
61499a1494b1fd7a86b909a97ea7a68379cb3fd0
[ "Apache-2.0" ]
permissive
JaredCorduan/mathlib
130392594844f15dad65a9308c242551bae6cd2e
d5de80376088954d592a59326c14404f538050a1
refs/heads/master
1,595,862,206,333
1,570,816,457,000
1,570,816,457,000
209,134,499
0
0
Apache-2.0
1,568,746,811,000
1,568,746,811,000
null
UTF-8
Lean
false
false
6,524
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebra.category.Mon.basic import category_theory.limits.limits /-! # The category of monoids has all colimits. We do this construction knowing nothing about monoids. In particular, I want to claim that this file could be produced by a python script that just looks at the output of `#print monoid`: -- structure monoid : Type u → Type u -- fields: -- monoid.mul : Π {α : Type u} [c : monoid α], α → α → α -- monoid.mul_assoc : ∀ {α : Type u} [c : monoid α] (a b c_1 : α), a * b * c_1 = a * (b * c_1) -- monoid.one : Π (α : Type u) [c : monoid α], α -- monoid.one_mul : ∀ {α : Type u} [c : monoid α] (a : α), 1 * a = a -- monoid.mul_one : ∀ {α : Type u} [c : monoid α] (a : α), a * 1 = a and if we'd fed it the output of `#print comm_ring`, this file would instead build colimits of commutative rings. A slightly bolder claim is that we could do this with tactics, as well. Because this file is "pre-automated", it doesn't meet current documentation standards. Hopefully eventually most of it will be automatically synthesised. -/ universes v open category_theory open category_theory.limits namespace Mon.colimits variables {J : Type v} [small_category J] (F : J ⥤ Mon.{v}) inductive prequotient -- There's always `of` | of : Π (j : J) (x : (F.obj j).α), prequotient -- Then one generator for each operation | one {} : prequotient | mul : prequotient → prequotient → prequotient open prequotient inductive relation : prequotient F → prequotient F → Prop -- Make it an equivalence relation: | refl : Π (x), relation x x | symm : Π (x y) (h : relation x y), relation y x | trans : Π (x y z) (h : relation x y) (k : relation y z), relation x z -- There's always a `map` relation | map : Π (j j' : J) (f : j ⟶ j') (x : (F.obj j).α), relation (of j' ((F.map f) x)) (of j x) -- Then one relation per operation, describing the interaction with `of` | mul : Π (j) (x y : (F.obj j).α), relation (of j (x * y)) (mul (of j x) (of j y)) | one : Π (j), relation (of j 1) one -- Then one relation per argument of each operation | mul_1 : Π (x x' y) (r : relation x x'), relation (mul x y) (mul x' y) | mul_2 : Π (x y y') (r : relation y y'), relation (mul x y) (mul x y') -- And one relation per axiom | mul_assoc : Π (x y z), relation (mul (mul x y) z) (mul x (mul y z)) | one_mul : Π (x), relation (mul one x) x | mul_one : Π (x), relation (mul x one) x def colimit_setoid : setoid (prequotient F) := { r := relation F, iseqv := ⟨relation.refl, relation.symm, relation.trans⟩ } attribute [instance] colimit_setoid def colimit_type : Type v := quotient (colimit_setoid F) instance monoid_colimit_type : monoid (colimit_type F) := { mul := begin fapply @quot.lift _ _ ((colimit_type F) → (colimit_type F)), { intro x, fapply @quot.lift, { intro y, exact quot.mk _ (mul x y) }, { intros y y' r, apply quot.sound, exact relation.mul_2 _ _ _ r } }, { intros x x' r, funext y, induction y, dsimp, apply quot.sound, { exact relation.mul_1 _ _ _ r }, { refl } }, end, one := begin exact quot.mk _ one end, mul_assoc := λ x y z, begin induction x, induction y, induction z, dsimp, apply quot.sound, apply relation.mul_assoc, refl, refl, refl, end, one_mul := λ x, begin induction x, dsimp, apply quot.sound, apply relation.one_mul, refl, end, mul_one := λ x, begin induction x, dsimp, apply quot.sound, apply relation.mul_one, refl, end } @[simp] lemma quot_one : quot.mk setoid.r one = (1 : colimit_type F) := rfl @[simp] lemma quot_mul (x y) : quot.mk setoid.r (mul x y) = ((quot.mk setoid.r x) * (quot.mk setoid.r y) : colimit_type F) := rfl def colimit : Mon := ⟨colimit_type F, by apply_instance⟩ def cocone_fun (j : J) (x : (F.obj j).α) : colimit_type F := quot.mk _ (of j x) def cocone_morphism (j : J) : F.obj j ⟶ colimit F := { to_fun := cocone_fun F j, map_one' := quot.sound (relation.one _ _), map_mul' := λ x y, quot.sound (relation.mul _ _ _) } @[simp] lemma cocone_naturality {j j' : J} (f : j ⟶ j') : F.map f ≫ (cocone_morphism F j') = cocone_morphism F j := begin ext, apply quot.sound, apply relation.map, end @[simp] lemma cocone_naturality_components (j j' : J) (f : j ⟶ j') (x : F.obj j): (cocone_morphism F j') (F.map f x) = (cocone_morphism F j) x := by { rw ←cocone_naturality F f, refl } def colimit_cocone : cocone F := { X := colimit F, ι := { app := cocone_morphism F, } }. @[simp] def desc_fun_lift (s : cocone F) : prequotient F → s.X | (of j x) := (s.ι.app j) x | one := 1 | (mul x y) := desc_fun_lift x * desc_fun_lift y def desc_fun (s : cocone F) : colimit_type F → s.X := begin fapply quot.lift, { exact desc_fun_lift F s }, { intros x y r, induction r; try { dsimp }, -- refl { refl }, -- symm { exact r_ih.symm }, -- trans { exact eq.trans r_ih_h r_ih_k }, -- map { rw cocone.naturality_bundled, }, -- mul { rw is_monoid_hom.map_mul ⇑((s.ι).app r_j) }, -- one { erw is_monoid_hom.map_one ⇑((s.ι).app r), refl }, -- mul_1 { rw r_ih, }, -- mul_2 { rw r_ih, }, -- mul_assoc { rw mul_assoc, }, -- one_mul { rw one_mul, }, -- mul_one { rw mul_one, } } end @[simp] def desc_morphism (s : cocone F) : colimit F ⟶ s.X := { to_fun := desc_fun F s, map_one' := rfl, map_mul' := λ x y, by { induction x; induction y; refl }, } def colimit_is_colimit : is_colimit (colimit_cocone F) := { desc := λ s, desc_morphism F s, uniq' := λ s m w, begin ext, induction x, induction x, { have w' := congr_fun (congr_arg (λ f : F.obj x_j ⟶ s.X, (f : F.obj x_j → s.X)) (w x_j)) x_x, erw w', refl, }, { simp only [desc_morphism, quot_one], erw is_monoid_hom.map_one ⇑m, refl, }, { simp only [desc_morphism, quot_mul], erw is_monoid_hom.map_mul ⇑m, rw [x_ih_a, x_ih_a_1], refl, }, refl end }. instance has_colimits_Mon : has_colimits.{v} Mon.{v} := { has_colimits_of_shape := λ J 𝒥, { has_colimit := λ F, by exactI { cocone := colimit_cocone F, is_colimit := colimit_is_colimit F } } } end Mon.colimits
daa9a0cd1f0c6a815170631e0a99ef6f9fdaca52
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/test/finish2.lean
b7d71fcce0122b0460d4afc0bb1c154700cdcdce
[ "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
12,726
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Nathaniel Thomas -/ import tactic.finish /-! # More examples to test `finish` Shamelessly stolen by Jeremy from Nathaniel's `tauto`. -/ open nat section variables (a b c d e f : Prop) variable even : ℕ → Prop variable P : ℕ → Prop -- these next five are things that tauto doesn't get example : (∀ x, P x) ∧ b → (∀ y, P y) ∧ P 0 ∨ b ∧ P 0 := by finish example : (∀ A, A ∨ ¬A) → ∀ x y : ℕ, x = y ∨ x ≠ y := by finish example : ∀ b1 b2, b1 = b2 ↔ (b1 = tt ↔ b2 = tt) := begin intro b1, cases b1; finish [iff_def] end example : ∀ (P Q : nat → Prop), (∀ n, Q n → P n) → (∀ n, Q n) → P 2 := by finish example (a b c : Prop) : ¬ true ∨ false ∨ b ↔ b := by finish example : true := by finish example : false → a := by finish example : a → a := by finish example : (a → b) → a → b := by finish example : ¬ a → ¬ a := by finish example : a → (false ∨ a) := by finish example : (a → b → c) → (a → b) → a → c := by finish example : a → ¬ a → (a → b) → (a ∨ b) → (a ∧ b) → a → false := by finish example : ((a ∧ b) ∧ c) → b := by finish example : ((a → b) → c) → b → c := by finish example : (a ∨ b) → (b ∨ a) := by finish example : (a → b ∧ c) → (a → b) ∨ (a → c) := by finish example : ∀ (x0 : a ∨ b) (x1 : b ∧ c), a → b := by finish example : a → b → (c ∨ b) := by finish example : (a ∧ b → c) → b → a → c := by finish example : (a ∨ b → c) → a → c := by finish example : (a ∨ b → c) → b → c := by finish example : (a ∧ b) → (b ∧ a) := by finish example : (a ↔ b) → a → b := by finish example : a → ¬¬a := by finish example : ¬¬(a ∨ ¬a) := by finish example : ¬¬(a ∨ b → a ∨ b) := by finish example : ¬¬((∀ n, even n) ∨ ¬(∀ m, even m)) := by finish example : (¬¬b → b) → (a → b) → ¬¬a → b := by finish example : (¬¬b → b) → (¬b → ¬ a) → ¬¬a → b := by finish example : ((a → b → false) → false) → (b → false) → false := by finish example : ((((c → false) → a) → ((b → false) → a) → false) → false) → (((c → b → false) → false) → false) → ¬a → a := by finish example (p q r : Prop) (a b : nat) : true → a = a → q → q → p → p := by finish example : ∀ (F F' : Prop), F ∧ F' → F := by finish example : ∀ (F1 F2 F3 : Prop), ((¬F1 ∧ F3) ∨ (F2 ∧ ¬F3)) → (F2 → F1) → (F2 → F3) → ¬F2 := by finish example : ∀ (f : nat → Prop), f 2 → ∃ x, f x := by finish example : true ∧ true ∧ true ∧ true ∧ true ∧ true ∧ true := by finish example : ∀ (P : nat → Prop), P 0 → (P 0 → P 1) → (P 1 → P 2) → (P 2) := by finish example : ¬¬¬¬¬a → ¬¬¬¬¬¬¬¬a → false := by finish example : ∀ n, ¬¬(even n ∨ ¬even n) := by finish example : ∀ (p q r s : Prop) (a b : nat), r ∨ s → p ∨ q → a = b → q ∨ p := by finish example : (∀ x, P x) → (∀ y, P y) := by finish /- TODO(Jeremy): reinstate after simp * at * bug is fixed. example : ((a ↔ b) → (b ↔ c)) → ((b ↔ c) → (c ↔ a)) → ((c ↔ a) → (a ↔ b)) → (a ↔ b) := by finish [iff_def] -/ example : ((¬a ∨ b) ∧ (¬b ∨ b) ∧ (¬a ∨ ¬b) ∧ (¬b ∨ ¬b) → false) → ¬((a → b) → b) → false := by finish example : ¬((a → b) → b) → ((¬b ∨ ¬b) ∧ (¬b ∨ ¬a) ∧ (b ∨ ¬b) ∧ (b ∨ ¬a) → false) → false := by finish example : (¬a ↔ b) → (¬b ↔ a) → (¬¬a ↔ a) := by finish example : (¬ a ↔ b) → (¬ (c ∨ e) ↔ d ∧ f) → (¬ (c ∨ a ∨ e) ↔ d ∧ b ∧ f) := by finish example {A : Type} (p q : A → Prop) (a b : A) : q a → p b → ∃ x, (p x ∧ x = b) ∨ q x := by finish example {A : Type} (p q : A → Prop) (a b : A) : p b → ∃ x, q x ∨ (p x ∧ x = b) := by finish example : ¬ a → b → a → c := by finish example : a → b → b → ¬ a → c := by finish example (a b : nat) : a = b → b = a := by finish -- good examples of things we don't get, even using the simplifier example (a b c : nat) : a = b → a = c → b = c := by finish example (p : nat → Prop) (a b c : nat) : a = b → a = c → p b → p c := by finish example (p : Prop) (a b : nat) : a = b → p → p := by finish -- safe should look for contradictions with constructors example (a : nat) : (0 : ℕ) = succ a → a = a → false := by finish example (p : Prop) (a b c : nat) : [a, b, c] = [] → p := by finish example (a b c : nat) : succ (succ a) = succ (succ b) → c = c := by finish example (p : Prop) (a b : nat) : a = b → b ≠ a → p := by finish example : (a ↔ b) → ((b ↔ a) ↔ (a ↔ b)) := by finish example (a b c : nat) : b = c → (a = b ↔ c = a) := by finish [iff_def] example : ¬¬¬¬¬¬¬¬a → ¬¬¬¬¬a → false := by finish example (a b c : Prop) : a ∧ b ∧ c ↔ c ∧ b ∧ a := by finish example (a b c : Prop) : a ∧ false ∧ c ↔ false := by finish example (a b c : Prop) : a ∨ false ∨ b ↔ b ∨ a := by finish example : a ∧ not a ↔ false := by finish example : a ∧ b ∧ true → b ∧ a := by finish example (A : Type) (a₁ a₂ : A) : a₁ = a₂ → (λ (B : Type) (f : A → B), f a₁) = (λ (B : Type) (f : A → B), f a₂) := by finish example (a : nat) : ¬ a = a → false := by finish example (A : Type) (p : Prop) (a b c : A) : a = b → b ≠ a → p := by finish example (p q r s : Prop) : r ∧ s → p ∧ q → q ∧ p := by finish example (p q : Prop) : p ∧ p ∧ q ∧ q → q ∧ p := by finish example (p : nat → Prop) (q : nat → nat → Prop) : (∃ x y, p x ∧ q x y) → q 0 0 ∧ q 1 1 → (∃ x, p x) := by finish example (p q r s : Prop) (a b : nat) : r ∨ s → p ∨ q → a = b → q ∨ p := by finish example (p q r : Prop) (a b : nat) : true → a = a → q → q → p → p := by finish example (a b : Prop) : a → b → a := by finish example (p q : nat → Prop) (a b : nat) : p a → q b → ∃ x, p x := by finish example : ∀ b1 b2, b1 && b2 = ff ↔ (b1 = ff ∨ b2 = ff) := by finish example : ∀ b1 b2, b1 && b2 = tt ↔ (b1 = tt ∧ b2 = tt) := by finish example : ∀ b1 b2, b1 || b2 = ff ↔ (b1 = ff ∧ b2 = ff) := by finish example : ∀ b1 b2, b1 || b2 = tt ↔ (b1 = tt ∨ b2 = tt) := by finish example : ∀ b, bnot b = tt ↔ b = ff := by finish example : ∀ b, bnot b = ff ↔ b = tt := by finish example : ∀ b c, b = c ↔ ¬ (b = bnot c) := by intros b c; cases b; cases c; finish [iff_def] inductive and3 (a b c : Prop) : Prop | mk : a → b → c → and3 example (h : and3 a b c) : and3 b c a := by cases h; split; finish inductive or3 (a b c : Prop) : Prop | in1 : a → or3 | in2 : b → or3 | in3 : c → or3 /- TODO(Jeremy): write a tactic that tries all constructors example (h : a) : or3 a b c := sorry example (h : b) : or3 a b c := sorry example (h : c) : or3 a b c := sorry -/ variables (A₁ A₂ A₃ A₄ B₁ B₂ B₃ B₄ : Prop) -- H first, all pos example (H1 : A₁ → A₂ → A₃ → B₁ ∨ B₂ ∨ B₃ ∨ B₄) (a1 : A₁) (a2 : A₂) (a3 : A₃) (n1 : ¬B₁) (n2 : ¬B₂) (n3 : ¬B₃) : B₄ := by finish example (H1 : A₁ → A₂ → A₃ → B₁ ∨ B₂ ∨ B₃ ∨ B₄) (a1 : A₁) (a2 : A₂) (a3 : A₃) (n1 : ¬B₁) (n2 : ¬B₂) (n3 : ¬B₄) : B₃ := by finish example (H1 : A₁ → A₂ → A₃ → B₁ ∨ B₂ ∨ B₃ ∨ B₄) (a1 : A₁) (a2 : A₂) (a3 : A₃) (n1 : ¬B₁) (n3 : ¬B₃) (n3 : ¬B₄) : B₂ := by finish example (H1 : A₁ → A₂ → A₃ → B₁ ∨ B₂ ∨ B₃ ∨ B₄) (a1 : A₁) (a2 : A₂) (a3 : A₃) (n2 : ¬B₂) (n3 : ¬B₃) (n3 : ¬B₄) : B₁ := by finish example (H : A₁ → A₂ → A₃ → B₁ ∨ B₂ ∨ B₃ ∨ B₄) (a1 : A₁) (a2 : A₂) (n1 : ¬B₁) (n2 : ¬B₂) (n3 : ¬B₃) (n3 : ¬B₄) : ¬A₃ := by finish example (H : A₁ → A₂ → A₃ → B₁ ∨ B₂ ∨ B₃ ∨ B₄) (a1 : A₁) (a3 : A₃) (n1 : ¬B₁) (n2 : ¬B₂) (n3 : ¬B₃) (n3 : ¬B₄) : ¬A₂ := by finish example (H : A₁ → A₂ → A₃ → B₁ ∨ B₂ ∨ B₃ ∨ B₄) (a2 : A₂) (a3 : A₃) (n1 : ¬B₁) (n2 : ¬B₂) (n3 : ¬B₃) (n3 : ¬B₄) : ¬A₁ := by finish -- H last, all pos example (a1 : A₁) (a2 : A₂) (a3 : A₃) (n1 : ¬B₁) (n2 : ¬B₂) (n3 : ¬B₃) (H : A₁ → A₂ → A₃ → B₁ ∨ B₂ ∨ B₃ ∨ B₄) : B₄ := by finish example (a1 : A₁) (a2 : A₂) (a3 : A₃) (n1 : ¬B₁) (n2 : ¬B₂) (n3 : ¬B₄) (H : A₁ → A₂ → A₃ → B₁ ∨ B₂ ∨ B₃ ∨ B₄) : B₃ := by finish example (a1 : A₁) (a2 : A₂) (a3 : A₃) (n1 : ¬B₁) (n3 : ¬B₃) (n3 : ¬B₄) (H : A₁ → A₂ → A₃ → B₁ ∨ B₂ ∨ B₃ ∨ B₄) : B₂ := by finish example (a1 : A₁) (a2 : A₂) (a3 : A₃) (n2 : ¬B₂) (n3 : ¬B₃) (n3 : ¬B₄) (H : A₁ → A₂ → A₃ → B₁ ∨ B₂ ∨ B₃ ∨ B₄) : B₁ := by finish example (a1 : A₁) (a2 : A₂) (n1 : ¬B₁) (n2 : ¬B₂) (n3 : ¬B₃) (n3 : ¬B₄) (H : A₁ → A₂ → A₃ → B₁ ∨ B₂ ∨ B₃ ∨ B₄) : ¬A₃ := by finish example (a1 : A₁) (a3 : A₃) (n1 : ¬B₁) (n2 : ¬B₂) (n3 : ¬B₃) (n3 : ¬B₄) (H : A₁ → A₂ → A₃ → B₁ ∨ B₂ ∨ B₃ ∨ B₄) : ¬A₂ := by finish example (a2 : A₂) (a3 : A₃) (n1 : ¬B₁) (n2 : ¬B₂) (n3 : ¬B₃) (n3 : ¬B₄) (H : A₁ → A₂ → A₃ → B₁ ∨ B₂ ∨ B₃ ∨ B₄) : ¬A₁ := by finish -- H first, all neg example (H : ¬A₁ → ¬A₂ → ¬A₃ → ¬B₁ ∨ ¬B₂ ∨ ¬B₃ ∨ ¬B₄) (n1 : ¬A₁) (n2 : ¬A₂) (n3 : ¬A₃) (b1 : B₁) (b2 : B₂) (b3 : B₃) : ¬B₄ := by finish example (H : ¬A₁ → ¬A₂ → ¬A₃ → ¬B₁ ∨ ¬B₂ ∨ ¬B₃ ∨ ¬B₄) (n1 : ¬A₁) (n2 : ¬A₂) (n3 : ¬A₃) (b1 : B₁) (b2 : B₂) (b4 : B₄) : ¬B₃ := by finish example (H : ¬A₁ → ¬A₂ → ¬A₃ → ¬B₁ ∨ ¬B₂ ∨ ¬B₃ ∨ ¬B₄) (n1 : ¬A₁) (n2 : ¬A₂) (n3 : ¬A₃) (b1 : B₁) (b3 : B₃) (b4 : B₄) : ¬B₂ := by finish example (H : ¬A₁ → ¬A₂ → ¬A₃ → ¬B₁ ∨ ¬B₂ ∨ ¬B₃ ∨ ¬B₄) (n1 : ¬A₁) (n2 : ¬A₂) (n3 : ¬A₃) (b2 : B₂) (b3 : B₃) (b4 : B₄) : ¬B₁ := by finish example (H : ¬A₁ → ¬A₂ → ¬A₃ → ¬B₁ ∨ ¬B₂ ∨ ¬B₃ ∨ ¬B₄) (n1 : ¬A₁) (n2 : ¬A₂) (b1 : B₁) (b2 : B₂) (b3 : B₃) (b4 : B₄) : ¬¬A₃ := by finish example (H : ¬A₁ → ¬A₂ → ¬A₃ → ¬B₁ ∨ ¬B₂ ∨ ¬B₃ ∨ ¬B₄) (n1 : ¬A₁) (n3 : ¬A₃) (b1 : B₁) (b2 : B₂) (b3 : B₃) (b4 : B₄) : ¬¬A₂ := by finish example (H : ¬A₁ → ¬A₂ → ¬A₃ → ¬B₁ ∨ ¬B₂ ∨ ¬B₃ ∨ ¬B₄) (n2 : ¬A₂) (n3 : ¬A₃) (b1 : B₁) (b2 : B₂) (b3 : B₃) (b4 : B₄) : ¬¬A₁ := by finish -- H last, all neg example (n1 : ¬A₁) (n2 : ¬A₂) (n3 : ¬A₃) (b1 : B₁) (b2 : B₂) (b3 : B₃) (H : ¬A₁ → ¬A₂ → ¬A₃ → ¬B₁ ∨ ¬B₂ ∨ ¬B₃ ∨ ¬B₄) : ¬B₄ := by finish example (n1 : ¬A₁) (n2 : ¬A₂) (n3 : ¬A₃) (b1 : B₁) (b2 : B₂) (b4 : B₄) (H : ¬A₁ → ¬A₂ → ¬A₃ → ¬B₁ ∨ ¬B₂ ∨ ¬B₃ ∨ ¬B₄) : ¬B₃ := by finish example (n1 : ¬A₁) (n2 : ¬A₂) (n3 : ¬A₃) (b1 : B₁) (b3 : B₃) (b4 : B₄) (H : ¬A₁ → ¬A₂ → ¬A₃ → ¬B₁ ∨ ¬B₂ ∨ ¬B₃ ∨ ¬B₄) : ¬B₂ := by finish example (n1 : ¬A₁) (n2 : ¬A₂) (n3 : ¬A₃) (b2 : B₂) (b3 : B₃) (b4 : B₄) (H : ¬A₁ → ¬A₂ → ¬A₃ → ¬B₁ ∨ ¬B₂ ∨ ¬B₃ ∨ ¬B₄) : ¬B₁ := by finish example (n1 : ¬A₁) (n2 : ¬A₂) (b1 : B₁) (b2 : B₂) (b3 : B₃) (b4 : B₄) (H : ¬A₁ → ¬A₂ → ¬A₃ → ¬B₁ ∨ ¬B₂ ∨ ¬B₃ ∨ ¬B₄) : ¬¬A₃ := by finish example (n1 : ¬A₁) (n3 : ¬A₃) (b1 : B₁) (b2 : B₂) (b3 : B₃) (b4 : B₄) (H : ¬A₁ → ¬A₂ → ¬A₃ → ¬B₁ ∨ ¬B₂ ∨ ¬B₃ ∨ ¬B₄) : ¬¬A₂ := by finish example (n2 : ¬A₂) (n3 : ¬A₃) (b1 : B₁) (b2 : B₂) (b3 : B₃) (b4 : B₄) (H : ¬A₁ → ¬A₂ → ¬A₃ → ¬B₁ ∨ ¬B₂ ∨ ¬B₃ ∨ ¬B₄) : ¬¬A₁ := by finish section club variables Scottish RedSocks WearKilt Married GoOutSunday : Prop theorem NoMember : (¬Scottish → RedSocks) → (WearKilt ∨ ¬RedSocks) → (Married → ¬GoOutSunday) → (GoOutSunday ↔ Scottish) → (WearKilt → Scottish ∧ Married) → (Scottish → WearKilt) → false := by finish end club end
e31b04b9ed010cc6b0a8ffa7ab43cc2ad403b2c1
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/limits/presheaf.lean
166e034b49100d84b752bab52fb868e8715ea06f
[ "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,082
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.adjunction.limits import category_theory.adjunction.opposites import category_theory.elements import category_theory.limits.functor_category import category_theory.limits.kan_extension import category_theory.limits.shapes.terminal import category_theory.limits.types /-! # Colimit of representables > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file constructs an adjunction `yoneda_adjunction` between `(Cᵒᵖ ⥤ Type u)` and `ℰ` given a functor `A : C ⥤ ℰ`, where the right adjoint sends `(E : ℰ)` to `c ↦ (A.obj c ⟶ E)` (provided `ℰ` has colimits). This adjunction is used to show that every presheaf is a colimit of representables. Further, the left adjoint `colimit_adj.extend_along_yoneda : (Cᵒᵖ ⥤ Type u) ⥤ ℰ` satisfies `yoneda ⋙ L ≅ A`, that is, an extension of `A : C ⥤ ℰ` to `(Cᵒᵖ ⥤ Type u) ⥤ ℰ` through `yoneda : C ⥤ Cᵒᵖ ⥤ Type u`. It is the left Kan extension of `A` along the yoneda embedding, sometimes known as the Yoneda extension, as proved in `extend_along_yoneda_iso_Kan`. `unique_extension_along_yoneda` shows `extend_along_yoneda` is unique amongst cocontinuous functors with this property, establishing the presheaf category as the free cocompletion of a small category. ## Tags colimit, representable, presheaf, free cocompletion ## References * [S. MacLane, I. Moerdijk, *Sheaves in Geometry and Logic*][MM92] * https://ncatlab.org/nlab/show/Yoneda+extension -/ namespace category_theory noncomputable theory open category limits universes u₁ u₂ variables {C : Type u₁} [small_category C] variables {ℰ : Type u₂} [category.{u₁} ℰ] variable (A : C ⥤ ℰ) namespace colimit_adj /-- The functor taking `(E : ℰ) (c : Cᵒᵖ)` to the homset `(A.obj C ⟶ E)`. It is shown in `L_adjunction` that this functor has a left adjoint (provided `E` has colimits) given by taking colimits over categories of elements. In the case where `ℰ = Cᵒᵖ ⥤ Type u` and `A = yoneda`, this functor is isomorphic to the identity. Defined as in [MM92], Chapter I, Section 5, Theorem 2. -/ @[simps] def restricted_yoneda : ℰ ⥤ (Cᵒᵖ ⥤ Type u₁) := yoneda ⋙ (whiskering_left _ _ (Type u₁)).obj (functor.op A) /-- The functor `restricted_yoneda` is isomorphic to the identity functor when evaluated at the yoneda embedding. -/ def restricted_yoneda_yoneda : restricted_yoneda (yoneda : C ⥤ Cᵒᵖ ⥤ Type u₁) ≅ 𝟭 _ := nat_iso.of_components (λ P, nat_iso.of_components (λ X, yoneda_sections_small X.unop _) (λ X Y f, funext $ λ x, begin dsimp, rw ← functor_to_types.naturality _ _ x f (𝟙 _), dsimp, simp, end)) (λ _ _ _, rfl) /-- (Implementation). The equivalence of homsets which helps construct the left adjoint to `colimit_adj.restricted_yoneda`. It is shown in `restrict_yoneda_hom_equiv_natural` that this is a natural bijection. -/ def restrict_yoneda_hom_equiv (P : Cᵒᵖ ⥤ Type u₁) (E : ℰ) {c : cocone ((category_of_elements.π P).left_op ⋙ A)} (t : is_colimit c) : (c.X ⟶ E) ≃ (P ⟶ (restricted_yoneda A).obj E) := ((ulift_trivial _).symm ≪≫ t.hom_iso' E).to_equiv.trans { to_fun := λ k, { app := λ c p, k.1 (opposite.op ⟨_, p⟩), naturality' := λ c c' f, funext $ λ p, (k.2 (quiver.hom.op ⟨f, rfl⟩ : (opposite.op ⟨c', P.map f p⟩ : P.elementsᵒᵖ) ⟶ opposite.op ⟨c, p⟩)).symm }, inv_fun := λ τ, { val := λ p, τ.app p.unop.1 p.unop.2, property := λ p p' f, begin simp_rw [← f.unop.2], apply (congr_fun (τ.naturality f.unop.1) p'.unop.2).symm, end }, left_inv := begin rintro ⟨k₁, k₂⟩, ext, dsimp, congr' 1, simp, end, right_inv := begin rintro ⟨_, _⟩, refl, end } /-- (Implementation). Show that the bijection in `restrict_yoneda_hom_equiv` is natural (on the right). -/ lemma restrict_yoneda_hom_equiv_natural (P : Cᵒᵖ ⥤ Type u₁) (E₁ E₂ : ℰ) (g : E₁ ⟶ E₂) {c : cocone _} (t : is_colimit c) (k : c.X ⟶ E₁) : restrict_yoneda_hom_equiv A P E₂ t (k ≫ g) = restrict_yoneda_hom_equiv A P E₁ t k ≫ (restricted_yoneda A).map g := begin ext _ X p, apply (assoc _ _ _).symm, end variables [has_colimits ℰ] /-- The left adjoint to the functor `restricted_yoneda` (shown in `yoneda_adjunction`). It is also an extension of `A` along the yoneda embedding (shown in `is_extension_along_yoneda`), in particular it is the left Kan extension of `A` through the yoneda embedding. -/ def extend_along_yoneda : (Cᵒᵖ ⥤ Type u₁) ⥤ ℰ := adjunction.left_adjoint_of_equiv (λ P E, restrict_yoneda_hom_equiv A P E (colimit.is_colimit _)) (λ P E E' g, restrict_yoneda_hom_equiv_natural A P E E' g _) @[simp] lemma extend_along_yoneda_obj (P : Cᵒᵖ ⥤ Type u₁) : (extend_along_yoneda A).obj P = colimit ((category_of_elements.π P).left_op ⋙ A) := rfl lemma extend_along_yoneda_map {X Y : Cᵒᵖ ⥤ Type u₁} (f : X ⟶ Y) : (extend_along_yoneda A).map f = colimit.pre ((category_of_elements.π Y).left_op ⋙ A) (category_of_elements.map f).op := begin ext J, erw colimit.ι_pre ((category_of_elements.π Y).left_op ⋙ A) (category_of_elements.map f).op, dsimp only [extend_along_yoneda, restrict_yoneda_hom_equiv, is_colimit.hom_iso', is_colimit.hom_iso, ulift_trivial], simpa end /-- Show `extend_along_yoneda` is left adjoint to `restricted_yoneda`. The construction of [MM92], Chapter I, Section 5, Theorem 2. -/ def yoneda_adjunction : extend_along_yoneda A ⊣ restricted_yoneda A := adjunction.adjunction_of_equiv_left _ _ /-- The initial object in the category of elements for a representable functor. In `is_initial` it is shown that this is initial. -/ def elements.initial (A : C) : (yoneda.obj A).elements := ⟨opposite.op A, 𝟙 _⟩ /-- Show that `elements.initial A` is initial in the category of elements for the `yoneda` functor. -/ def is_initial (A : C) : is_initial (elements.initial A) := { desc := λ s, ⟨s.X.2.op, comp_id _⟩, uniq' := λ s m w, begin simp_rw ← m.2, dsimp [elements.initial], simp, end, fac' := by rintros s ⟨⟨⟩⟩, } /-- `extend_along_yoneda A` is an extension of `A` to the presheaf category along the yoneda embedding. `unique_extension_along_yoneda` shows it is unique among functors preserving colimits with this property (up to isomorphism). The first part of [MM92], Chapter I, Section 5, Corollary 4. See Property 1 of <https://ncatlab.org/nlab/show/Yoneda+extension#properties>. -/ def is_extension_along_yoneda : (yoneda : C ⥤ Cᵒᵖ ⥤ Type u₁) ⋙ extend_along_yoneda A ≅ A := nat_iso.of_components (λ X, (colimit.is_colimit _).cocone_point_unique_up_to_iso (colimit_of_diagram_terminal (terminal_op_of_initial (is_initial _)) _)) begin intros X Y f, change (colimit.desc _ ⟨_, _⟩ ≫ colimit.desc _ _) = colimit.desc _ _ ≫ _, apply colimit.hom_ext, intro j, rw [colimit.ι_desc_assoc, colimit.ι_desc_assoc], change (colimit.ι _ _ ≫ 𝟙 _) ≫ colimit.desc _ _ = _, rw [comp_id, colimit.ι_desc], dsimp, rw ← A.map_comp, congr' 1, end /-- See Property 2 of https://ncatlab.org/nlab/show/Yoneda+extension#properties. -/ instance : preserves_colimits (extend_along_yoneda A) := (yoneda_adjunction A).left_adjoint_preserves_colimits /-- Show that the images of `X` after `extend_along_yoneda` and `Lan yoneda` are indeed isomorphic. This follows from `category_theory.category_of_elements.costructured_arrow_yoneda_equivalence`. -/ @[simps] def extend_along_yoneda_iso_Kan_app (X) : (extend_along_yoneda A).obj X ≅ ((Lan yoneda : (_ ⥤ ℰ) ⥤ _).obj A).obj X := let eq := category_of_elements.costructured_arrow_yoneda_equivalence X in { hom := colimit.pre (Lan.diagram (yoneda : C ⥤ _ ⥤ Type u₁) A X) eq.functor, inv := colimit.pre ((category_of_elements.π X).left_op ⋙ A) eq.inverse, hom_inv_id' := begin erw colimit.pre_pre ((category_of_elements.π X).left_op ⋙ A) eq.inverse, transitivity colimit.pre ((category_of_elements.π X).left_op ⋙ A) (𝟭 _), congr, { exact congr_arg functor.op (category_of_elements.from_to_costructured_arrow_eq X) }, { ext, simp only [colimit.ι_pre], erw category.comp_id, congr } end, inv_hom_id' := begin erw colimit.pre_pre (Lan.diagram (yoneda : C ⥤ _ ⥤ Type u₁) A X) eq.functor, transitivity colimit.pre (Lan.diagram (yoneda : C ⥤ _ ⥤ Type u₁) A X) (𝟭 _), congr, { exact category_of_elements.to_from_costructured_arrow_eq X }, { ext, simp only [colimit.ι_pre], erw category.comp_id, congr } end } /-- Verify that `extend_along_yoneda` is indeed the left Kan extension along the yoneda embedding. -/ @[simps] def extend_along_yoneda_iso_Kan : extend_along_yoneda A ≅ (Lan yoneda : (_ ⥤ ℰ) ⥤ _).obj A := nat_iso.of_components (extend_along_yoneda_iso_Kan_app A) begin intros X Y f, simp, rw extend_along_yoneda_map, erw colimit.pre_pre (Lan.diagram (yoneda : C ⥤ _ ⥤ Type u₁) A Y) (costructured_arrow.map f), erw colimit.pre_pre (Lan.diagram (yoneda : C ⥤ _ ⥤ Type u₁) A Y) (category_of_elements.costructured_arrow_yoneda_equivalence Y).functor, congr' 1, apply category_of_elements.costructured_arrow_yoneda_equivalence_naturality, end /-- extending `F ⋙ yoneda` along the yoneda embedding is isomorphic to `Lan F.op`. -/ @[simps] def extend_of_comp_yoneda_iso_Lan {D : Type u₁} [small_category D] (F : C ⥤ D) : extend_along_yoneda (F ⋙ yoneda) ≅ Lan F.op := adjunction.nat_iso_of_right_adjoint_nat_iso (yoneda_adjunction (F ⋙ yoneda)) (Lan.adjunction (Type u₁) F.op) (iso_whisker_right curried_yoneda_lemma' ((whiskering_left Cᵒᵖ Dᵒᵖ (Type u₁)).obj F.op : _)) end colimit_adj open colimit_adj /-- `F ⋙ yoneda` is naturally isomorphic to `yoneda ⋙ Lan F.op`. -/ @[simps] def comp_yoneda_iso_yoneda_comp_Lan {D : Type u₁} [small_category D] (F : C ⥤ D) : F ⋙ yoneda ≅ yoneda ⋙ Lan F.op := (is_extension_along_yoneda (F ⋙ yoneda)).symm ≪≫ iso_whisker_left yoneda (extend_of_comp_yoneda_iso_Lan F) /-- Since `extend_along_yoneda A` is adjoint to `restricted_yoneda A`, if we use `A = yoneda` then `restricted_yoneda A` is isomorphic to the identity, and so `extend_along_yoneda A` is as well. -/ def extend_along_yoneda_yoneda : extend_along_yoneda (yoneda : C ⥤ _) ≅ 𝟭 _ := adjunction.nat_iso_of_right_adjoint_nat_iso (yoneda_adjunction _) adjunction.id restricted_yoneda_yoneda /-- A functor to the presheaf category in which everything in the image is representable (witnessed by the fact that it factors through the yoneda embedding). `cocone_of_representable` gives a cocone for this functor which is a colimit and has point `P`. -/ -- Maybe this should be reducible or an abbreviation? def functor_to_representables (P : Cᵒᵖ ⥤ Type u₁) : (P.elements)ᵒᵖ ⥤ Cᵒᵖ ⥤ Type u₁ := (category_of_elements.π P).left_op ⋙ yoneda /-- This is a cocone with point `P` for the functor `functor_to_representables P`. It is shown in `colimit_of_representable P` that this cocone is a colimit: that is, we have exhibited an arbitrary presheaf `P` as a colimit of representables. The construction of [MM92], Chapter I, Section 5, Corollary 3. -/ def cocone_of_representable (P : Cᵒᵖ ⥤ Type u₁) : cocone (functor_to_representables P) := cocone.extend (colimit.cocone _) (extend_along_yoneda_yoneda.hom.app P) @[simp] lemma cocone_of_representable_X (P : Cᵒᵖ ⥤ Type u₁) : (cocone_of_representable P).X = P := rfl /-- An explicit formula for the legs of the cocone `cocone_of_representable`. -/ -- Marking this as a simp lemma seems to make things more awkward. lemma cocone_of_representable_ι_app (P : Cᵒᵖ ⥤ Type u₁) (j : (P.elements)ᵒᵖ): (cocone_of_representable P).ι.app j = (yoneda_sections_small _ _).inv j.unop.2 := colimit.ι_desc _ _ /-- The legs of the cocone `cocone_of_representable` are natural in the choice of presheaf. -/ lemma cocone_of_representable_naturality {P₁ P₂ : Cᵒᵖ ⥤ Type u₁} (α : P₁ ⟶ P₂) (j : (P₁.elements)ᵒᵖ) : (cocone_of_representable P₁).ι.app j ≫ α = (cocone_of_representable P₂).ι.app ((category_of_elements.map α).op.obj j) := begin ext T f, simpa [cocone_of_representable_ι_app] using functor_to_types.naturality _ _ α f.op _, end /-- The cocone with point `P` given by `the_cocone` is a colimit: that is, we have exhibited an arbitrary presheaf `P` as a colimit of representables. The result of [MM92], Chapter I, Section 5, Corollary 3. -/ def colimit_of_representable (P : Cᵒᵖ ⥤ Type u₁) : is_colimit (cocone_of_representable P) := begin apply is_colimit.of_point_iso (colimit.is_colimit (functor_to_representables P)), change is_iso (colimit.desc _ (cocone.extend _ _)), rw [colimit.desc_extend, colimit.desc_cocone], apply_instance, end /-- Given two functors L₁ and L₂ which preserve colimits, if they agree when restricted to the representable presheaves then they agree everywhere. -/ def nat_iso_of_nat_iso_on_representables (L₁ L₂ : (Cᵒᵖ ⥤ Type u₁) ⥤ ℰ) [preserves_colimits L₁] [preserves_colimits L₂] (h : yoneda ⋙ L₁ ≅ yoneda ⋙ L₂) : L₁ ≅ L₂ := begin apply nat_iso.of_components _ _, { intro P, refine (is_colimit_of_preserves L₁ (colimit_of_representable P)).cocone_points_iso_of_nat_iso (is_colimit_of_preserves L₂ (colimit_of_representable P)) _, apply functor.associator _ _ _ ≪≫ _, exact iso_whisker_left (category_of_elements.π P).left_op h }, { intros P₁ P₂ f, apply (is_colimit_of_preserves L₁ (colimit_of_representable P₁)).hom_ext, intro j, dsimp only [id.def, is_colimit.cocone_points_iso_of_nat_iso_hom, iso_whisker_left_hom], have : (L₁.map_cocone (cocone_of_representable P₁)).ι.app j ≫ L₁.map f = (L₁.map_cocone (cocone_of_representable P₂)).ι.app ((category_of_elements.map f).op.obj j), { dsimp, rw [← L₁.map_comp, cocone_of_representable_naturality], refl }, rw [reassoc_of this, is_colimit.ι_map_assoc, is_colimit.ι_map], dsimp, rw [← L₂.map_comp, cocone_of_representable_naturality], refl } end variable [has_colimits ℰ] /-- Show that `extend_along_yoneda` is the unique colimit-preserving functor which extends `A` to the presheaf category. The second part of [MM92], Chapter I, Section 5, Corollary 4. See Property 3 of https://ncatlab.org/nlab/show/Yoneda+extension#properties. -/ def unique_extension_along_yoneda (L : (Cᵒᵖ ⥤ Type u₁) ⥤ ℰ) (hL : yoneda ⋙ L ≅ A) [preserves_colimits L] : L ≅ extend_along_yoneda A := nat_iso_of_nat_iso_on_representables _ _ (hL ≪≫ (is_extension_along_yoneda _).symm) /-- If `L` preserves colimits and `ℰ` has them, then it is a left adjoint. This is a special case of `is_left_adjoint_of_preserves_colimits` used to prove that. -/ def is_left_adjoint_of_preserves_colimits_aux (L : (Cᵒᵖ ⥤ Type u₁) ⥤ ℰ) [preserves_colimits L] : is_left_adjoint L := { right := restricted_yoneda (yoneda ⋙ L), adj := (yoneda_adjunction _).of_nat_iso_left ((unique_extension_along_yoneda _ L (iso.refl _)).symm) } /-- If `L` preserves colimits and `ℰ` has them, then it is a left adjoint. Note this is a (partial) converse to `left_adjoint_preserves_colimits`. -/ def is_left_adjoint_of_preserves_colimits (L : (C ⥤ Type u₁) ⥤ ℰ) [preserves_colimits L] : is_left_adjoint L := let e : (_ ⥤ Type u₁) ≌ (_ ⥤ Type u₁) := (op_op_equivalence C).congr_left, t := is_left_adjoint_of_preserves_colimits_aux (e.functor ⋙ L : _) in by exactI adjunction.left_adjoint_of_nat_iso (e.inv_fun_id_assoc _) end category_theory
ddb74af8862517c877f77be14546f38df3d4d1ad
aa5a655c05e5359a70646b7154e7cac59f0b4132
/stage0/src/Lean/Meta/AppBuilder.lean
d65e599167e2d89b707fac0f9f1aa10132c02614
[ "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
19,205
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.Structure import Lean.Util.Recognizers import Lean.Meta.SynthInstance import Lean.Meta.Check namespace Lean.Meta /-- Return `id e` -/ def mkId (e : Expr) : MetaM Expr := do let type ← inferType e let u ← getLevel type return mkApp2 (mkConst ``id [u]) type e /-- Return `idRhs e` -/ def mkIdRhs (e : Expr) : MetaM Expr := do let type ← inferType e let u ← getLevel type return mkApp2 (mkConst ``idRhs [u]) type e /-- Given `e` s.t. `inferType e` is definitionally equal to `expectedType`, return term `@id expectedType e`. -/ def mkExpectedTypeHint (e : Expr) (expectedType : Expr) : MetaM Expr := do let u ← getLevel expectedType return mkApp2 (mkConst ``id [u]) expectedType e def mkEq (a b : Expr) : MetaM Expr := do let aType ← inferType a let u ← getLevel aType return mkApp3 (mkConst ``Eq [u]) aType a b def mkHEq (a b : Expr) : MetaM Expr := do let aType ← inferType a let bType ← inferType b let u ← getLevel aType return mkApp4 (mkConst ``HEq [u]) aType a bType b def mkEqRefl (a : Expr) : MetaM Expr := do let aType ← inferType a let u ← getLevel aType return mkApp2 (mkConst ``Eq.refl [u]) aType a def mkHEqRefl (a : Expr) : MetaM Expr := do let aType ← inferType a let u ← getLevel aType return mkApp2 (mkConst ``HEq.refl [u]) aType a private def infer (h : Expr) : MetaM Expr := do let hType ← inferType h whnfD hType private def hasTypeMsg (e type : Expr) : MessageData := m!"{indentExpr e}\nhas type{indentExpr type}" private def throwAppBuilderException {α} (op : Name) (msg : MessageData) : MetaM α := throwError! "AppBuilder for '{op}', {msg}" def mkEqSymm (h : Expr) : MetaM Expr := do if h.isAppOf ``Eq.refl then return h else let hType ← infer h match hType.eq? with | some (α, a, b) => let u ← getLevel α return mkApp4 (mkConst ``Eq.symm [u]) α a b h | none => throwAppBuilderException ``Eq.symm ("equality proof expected" ++ hasTypeMsg h hType) def mkEqTrans (h₁ h₂ : Expr) : MetaM Expr := do if h₁.isAppOf ``Eq.refl then return h₂ else if h₂.isAppOf ``Eq.refl then return h₁ else let hType₁ ← infer h₁ let hType₂ ← infer h₂ match hType₁.eq?, hType₂.eq? with | some (α, a, b), some (_, _, c) => let u ← getLevel α return mkApp6 (mkConst ``Eq.trans [u]) α a b c h₁ h₂ | none, _ => throwAppBuilderException ``Eq.trans ("equality proof expected" ++ hasTypeMsg h₁ hType₁) | _, none => throwAppBuilderException ``Eq.trans ("equality proof expected" ++ hasTypeMsg h₂ hType₂) def mkHEqSymm (h : Expr) : MetaM Expr := do if h.isAppOf ``HEq.refl then return h else let hType ← infer h match hType.heq? with | some (α, a, β, b) => let u ← getLevel α return mkApp5 (mkConst ``HEq.symm [u]) α β a b h | none => throwAppBuilderException ``HEq.symm ("heterogeneous equality proof expected" ++ hasTypeMsg h hType) def mkHEqTrans (h₁ h₂ : Expr) : MetaM Expr := do if h₁.isAppOf ``HEq.refl then return h₂ else if h₂.isAppOf ``HEq.refl then return h₁ else let hType₁ ← infer h₁ let hType₂ ← infer h₂ match hType₁.heq?, hType₂.heq? with | some (α, a, β, b), some (_, _, γ, c) => let u ← getLevel α return mkApp8 (mkConst ``HEq.trans [u]) α β γ a b c h₁ h₂ | none, _ => throwAppBuilderException ``HEq.trans ("heterogeneous equality proof expected" ++ hasTypeMsg h₁ hType₁) | _, none => throwAppBuilderException ``HEq.trans ("heterogeneous equality proof expected" ++ hasTypeMsg h₂ hType₂) def mkEqOfHEq (h : Expr) : MetaM Expr := do let hType ← infer h match hType.heq? with | some (α, a, β, b) => unless (← isDefEq α β) do throwAppBuilderException ``eqOfHEq m!"heterogeneous equality types are not definitionally equal{indentExpr α}\nis not definitionally equal to{indentExpr β}" let u ← getLevel α return mkApp4 (mkConst ``eqOfHEq [u]) α a b h | _ => throwAppBuilderException ``HEq.trans m!"heterogeneous equality proof expected{indentExpr h}" def mkCongrArg (f h : Expr) : MetaM Expr := do if h.isAppOf ``Eq.refl then mkEqRefl (mkApp f h.appArg!) else let hType ← infer h let fType ← infer f match fType.arrow?, hType.eq? with | some (α, β), some (_, a, b) => let u ← getLevel α let v ← getLevel β return mkApp6 (mkConst ``congrArg [u, v]) α β a b f h | none, _ => throwAppBuilderException ``congrArg ("non-dependent function expected" ++ hasTypeMsg f fType) | _, none => throwAppBuilderException ``congrArg ("equality proof expected" ++ hasTypeMsg h hType) def mkCongrFun (h a : Expr) : MetaM Expr := do if h.isAppOf ``Eq.refl then mkEqRefl (mkApp h.appArg! a) else let hType ← infer h match hType.eq? with | some (ρ, f, g) => do let ρ ← whnfD ρ match ρ with | Expr.forallE n α β _ => let β' := Lean.mkLambda n BinderInfo.default α β let u ← getLevel α let v ← getLevel (mkApp β' a) return mkApp6 (mkConst ``congrFun [u, v]) α β' f g h a | _ => throwAppBuilderException ``congrFun ("equality proof between functions expected" ++ hasTypeMsg h hType) | _ => throwAppBuilderException ``congrFun ("equality proof expected" ++ hasTypeMsg h hType) def mkCongr (h₁ h₂ : Expr) : MetaM Expr := do if h₁.isAppOf ``Eq.refl then mkCongrArg h₁.appArg! h₂ else if h₂.isAppOf ``Eq.refl then mkCongrFun h₁ h₂.appArg! else let hType₁ ← infer h₁ let hType₂ ← infer h₂ match hType₁.eq?, hType₂.eq? with | some (ρ, f, g), some (α, a, b) => let ρ ← whnfD ρ match ρ.arrow? with | some (_, β) => do let u ← getLevel α let v ← getLevel β return mkApp8 (mkConst ``congr [u, v]) α β f g a b h₁ h₂ | _ => throwAppBuilderException ``congr ("non-dependent function expected" ++ hasTypeMsg h₁ hType₁) | none, _ => throwAppBuilderException ``congr ("equality proof expected" ++ hasTypeMsg h₁ hType₁) | _, none => throwAppBuilderException ``congr ("equality proof expected" ++ hasTypeMsg h₂ hType₂) private def mkAppMFinal (methodName : Name) (f : Expr) (args : Array Expr) (instMVars : Array MVarId) : MetaM Expr := do instMVars.forM fun mvarId => do let mvarDecl ← getMVarDecl mvarId let mvarVal ← synthInstance mvarDecl.type assignExprMVar mvarId mvarVal let result ← instantiateMVars (mkAppN f args) if (← hasAssignableMVar result) then throwAppBuilderException methodName ("result contains metavariables" ++ indentExpr result) return result private partial def mkAppMArgs (f : Expr) (fType : Expr) (xs : Array Expr) : MetaM Expr := let rec loop (type : Expr) (i : Nat) (j : Nat) (args : Array Expr) (instMVars : Array MVarId) : MetaM Expr := do if i >= xs.size then mkAppMFinal `mkAppM f args instMVars else match type with | Expr.forallE n d b c => let d := d.instantiateRevRange j args.size args match c.binderInfo with | BinderInfo.implicit => let mvar ← mkFreshExprMVar d MetavarKind.natural n loop b i j (args.push mvar) instMVars | BinderInfo.instImplicit => let mvar ← mkFreshExprMVar d MetavarKind.synthetic n loop b i j (args.push mvar) (instMVars.push mvar.mvarId!) | _ => let x := xs[i] let xType ← inferType x if (← isDefEq d xType) then loop b (i+1) j (args.push x) instMVars else throwAppTypeMismatch (mkAppN f args) x | type => let type := type.instantiateRevRange j args.size args let type ← whnfD type if type.isForall then loop type i args.size args instMVars else throwAppBuilderException `mkAppM m!"too many explicit arguments provided to{indentExpr f}\narguments{indentD xs}" loop fType 0 0 #[] #[] private def mkFun (constName : Name) : MetaM (Expr × Expr) := do let cinfo ← getConstInfo constName let us ← cinfo.lparams.mapM fun _ => mkFreshLevelMVar let f := mkConst constName us let fType := cinfo.instantiateTypeLevelParams us return (f, fType) /-- Return the application `constName xs`. It tries to fill the implicit arguments before the last element in `xs`. Remark: ``mkAppM `arbitrary #[α]`` returns `@arbitrary.{u} α` without synthesizing the implicit argument occurring after `α`. Given a `x : (([Decidable p] → Bool) × Nat`, ``mkAppM `Prod.fst #[x]`` returns `@Prod.fst ([Decidable p] → Bool) Nat x` -/ def mkAppM (constName : Name) (xs : Array Expr) : MetaM Expr := do traceCtx `Meta.appBuilder <| withNewMCtxDepth do let (f, fType) ← mkFun constName let r ← mkAppMArgs f fType xs trace[Meta.appBuilder]! "constName: {constName}, xs: {xs}, result: {r}" return r private partial def mkAppOptMAux (f : Expr) (xs : Array (Option Expr)) : Nat → Array Expr → Nat → Array MVarId → Expr → MetaM Expr | i, args, j, instMVars, Expr.forallE n d b c => do let d := d.instantiateRevRange j args.size args if h : i < xs.size then match xs.get ⟨i, h⟩ with | none => match c.binderInfo with | BinderInfo.instImplicit => do let mvar ← mkFreshExprMVar d MetavarKind.synthetic n mkAppOptMAux f xs (i+1) (args.push mvar) j (instMVars.push mvar.mvarId!) b | _ => do let mvar ← mkFreshExprMVar d MetavarKind.natural n mkAppOptMAux f xs (i+1) (args.push mvar) j instMVars b | some x => let xType ← inferType x if (← isDefEq d xType) then mkAppOptMAux f xs (i+1) (args.push x) j instMVars b else throwAppTypeMismatch (mkAppN f args) x else mkAppMFinal `mkAppOptM f args instMVars | i, args, j, instMVars, type => do let type := type.instantiateRevRange j args.size args let type ← whnfD type if type.isForall then mkAppOptMAux f xs i args args.size instMVars type else if i == xs.size then mkAppMFinal `mkAppOptM f args instMVars else do let xs : Array Expr := xs.foldl (fun r x? => match x? with | none => r | some x => r.push x) #[] throwAppBuilderException `mkAppOptM ("too many arguments provided to" ++ indentExpr f ++ Format.line ++ "arguments" ++ xs) /-- Similar to `mkAppM`, but it allows us to specify which arguments are provided explicitly using `Option` type. Example: Given `Pure.pure {m : Type u → Type v} [Pure m] {α : Type u} (a : α) : m α`, ``` mkAppOptM `Pure.pure #[m, none, none, a] ``` returns a `Pure.pure` application if the instance `Pure m` can be synthesized, and the universes match. Note that, ``` mkAppM `Pure.pure #[a] ``` fails because the only explicit argument `(a : α)` is not sufficient for inferring the remaining arguments, we would need the expected type. -/ def mkAppOptM (constName : Name) (xs : Array (Option Expr)) : MetaM Expr := do traceCtx `Meta.appBuilder <| withNewMCtxDepth do let (f, fType) ← mkFun constName mkAppOptMAux f xs 0 #[] 0 #[] fType def mkEqNDRec (motive h1 h2 : Expr) : MetaM Expr := do if h2.isAppOf ``Eq.refl then return h1 else let h2Type ← infer h2 match h2Type.eq? with | none => throwAppBuilderException ``Eq.ndrec ("equality proof expected" ++ hasTypeMsg h2 h2Type) | some (α, a, b) => let u2 ← getLevel α let motiveType ← infer motive match motiveType with | Expr.forallE _ _ (Expr.sort u1 _) _ => return mkAppN (mkConst ``Eq.ndrec [u1, u2]) #[α, a, motive, h1, b, h2] | _ => throwAppBuilderException ``Eq.ndrec ("invalid motive" ++ indentExpr motive) def mkEqRec (motive h1 h2 : Expr) : MetaM Expr := do if h2.isAppOf ``Eq.refl then return h1 else let h2Type ← infer h2 match h2Type.eq? with | none => throwAppBuilderException ``Eq.rec ("equality proof expected" ++ indentExpr h2) | some (α, a, b) => let u2 ← getLevel α let motiveType ← infer motive match motiveType with | Expr.forallE _ _ (Expr.forallE _ _ (Expr.sort u1 _) _) _ => return mkAppN (mkConst ``Eq.rec [u1, u2]) #[α, a, motive, h1, b, h2] | _ => throwAppBuilderException ``Eq.rec ("invalid motive" ++ indentExpr motive) def mkEqMP (eqProof pr : Expr) : MetaM Expr := mkAppM ``Eq.mp #[eqProof, pr] def mkEqMPR (eqProof pr : Expr) : MetaM Expr := mkAppM ``Eq.mpr #[eqProof, pr] def mkNoConfusion (target : Expr) (h : Expr) : MetaM Expr := do let type ← inferType h let type ← whnf type match type.eq? with | none => throwAppBuilderException `noConfusion ("equality expected" ++ hasTypeMsg h type) | some (α, a, b) => let α ← whnf α matchConstInduct α.getAppFn (fun _ => throwAppBuilderException `noConfusion ("inductive type expected" ++ indentExpr α)) fun v us => do let u ← getLevel target return mkAppN (mkConst (Name.mkStr v.name "noConfusion") (u :: us)) (α.getAppArgs ++ #[target, a, b, h]) def mkPure (monad : Expr) (e : Expr) : MetaM Expr := mkAppOptM ``Pure.pure #[monad, none, none, e] /-- `mkProjection s fieldName` return an expression for accessing field `fieldName` of the structure `s`. Remark: `fieldName` may be a subfield of `s`. -/ partial def mkProjection : Expr → Name → MetaM Expr | s, fieldName => do let type ← inferType s let type ← whnf type match type.getAppFn with | Expr.const structName us _ => let env ← getEnv unless isStructureLike env structName do throwAppBuilderException `mkProjection ("structure expected" ++ hasTypeMsg s type) match getProjFnForField? env structName fieldName with | some projFn => let params := type.getAppArgs return mkApp (mkAppN (mkConst projFn us) params) s | none => let fields := getStructureFields env structName let r? ← fields.findSomeM? fun fieldName' => do match isSubobjectField? env structName fieldName' with | none => pure none | some _ => let parent ← mkProjection s fieldName' (do let r ← mkProjection parent fieldName; return some r) <|> pure none match r? with | some r => pure r | none => throwAppBuilderException `mkProjectionn ("invalid field name '" ++ toString fieldName ++ "' for" ++ hasTypeMsg s type) | _ => throwAppBuilderException `mkProjectionn ("structure expected" ++ hasTypeMsg s type) private def mkListLitAux (nil : Expr) (cons : Expr) : List Expr → Expr | [] => nil | x::xs => mkApp (mkApp cons x) (mkListLitAux nil cons xs) def mkListLit (type : Expr) (xs : List Expr) : MetaM Expr := do let u ← getDecLevel type let nil := mkApp (mkConst ``List.nil [u]) type match xs with | [] => return nil | _ => let cons := mkApp (mkConst ``List.cons [u]) type return mkListLitAux nil cons xs def mkArrayLit (type : Expr) (xs : List Expr) : MetaM Expr := do let u ← getDecLevel type let listLit ← mkListLit type xs return mkApp (mkApp (mkConst ``List.toArray [u]) type) listLit def mkSorry (type : Expr) (synthetic : Bool) : MetaM Expr := do let u ← getLevel type return mkApp2 (mkConst ``sorryAx [u]) type (toExpr synthetic) /-- Return `Decidable.decide p` -/ def mkDecide (p : Expr) : MetaM Expr := mkAppOptM ``Decidable.decide #[p, none] /-- Return a proof for `p : Prop` using `decide p` -/ def mkDecideProof (p : Expr) : MetaM Expr := do let decP ← mkDecide p let decEqTrue ← mkEq decP (mkConst ``Bool.true) let h ← mkEqRefl (mkConst ``Bool.true) let h ← mkExpectedTypeHint h decEqTrue mkAppM ``ofDecideEqTrue #[h] /-- Return `a < b` -/ def mkLt (a b : Expr) : MetaM Expr := mkAppM ``HasLess.Less #[a, b] /-- Return `a <= b` -/ def mkLe (a b : Expr) : MetaM Expr := mkAppM ``HasLessEq.LessEq #[a, b] /-- Return `arbitrary α` -/ def mkArbitrary (α : Expr) : MetaM Expr := mkAppOptM ``arbitrary #[α, none] /-- Return `sorryAx type` -/ def mkSyntheticSorry (type : Expr) : MetaM Expr := return mkApp2 (mkConst ``sorryAx [← getLevel type]) type (mkConst ``Bool.true) /-- Return `funext h` -/ def mkFunExt (h : Expr) : MetaM Expr := mkAppM ``funext #[h] /-- Return `propext h` -/ def mkPropExt (h : Expr) : MetaM Expr := mkAppM ``propext #[h] /-- Return `eqTrue h` -/ def mkEqTrue (h : Expr) : MetaM Expr := mkAppM ``eqTrue #[h] /-- Return `eqFalse h` -/ def mkEqFalse (h : Expr) : MetaM Expr := mkAppM ``eqFalse #[h] def mkImpCongr (h₁ h₂ : Expr) : MetaM Expr := mkAppM ``impCongr #[h₁, h₂] def mkImpCongrCtx (h₁ h₂ : Expr) : MetaM Expr := mkAppM ``impCongrCtx #[h₁, h₂] def mkForallCongr (h : Expr) : MetaM Expr := mkAppM ``forallCongr #[h] /-- Return instance for `[Monad m]` if there is one -/ def isMonad? (m : Expr) : MetaM (Option Expr) := try let monadType ← mkAppM `Monad #[m] let result ← trySynthInstance monadType match result with | LOption.some inst => pure inst | _ => pure none catch _ => pure none /-- Return `(n : type)`, a numeric literal of type `type`. The method fails if we don't have an instance `OfNat type n` -/ def mkNumeral (type : Expr) (n : Nat) : MetaM Expr := do let u ← getDecLevel type let inst ← synthInstance (mkApp2 (mkConst ``OfNat [u]) type (mkNatLit n)) return mkApp3 (mkConst ``OfNat.ofNat [u]) type (mkNatLit n) inst /-- Return `a op b`, where `op` has name `opName` and is implemented using the typeclass `className`. This method assumes `a` and `b` have the same type, and typeclass `className` is heterogeneous. Examples of supported clases: `HAdd`, `HSub`, `HMul`. We use heterogeneous operators to ensure we have a uniform representation. -/ private def mkBinaryOp (className : Name) (opName : Name) (a b : Expr) : MetaM Expr := do let aType ← inferType a let u ← getDecLevel aType let inst ← synthInstance (mkApp3 (mkConst className [u, u, u]) aType aType aType) return mkApp6 (mkConst opName [u, u, u]) aType aType aType inst a b /-- Return `a + b` using a heterogeneous `+`. This method assumes `a` and `b` have the same type. -/ def mkAdd (a b : Expr) : MetaM Expr := mkBinaryOp ``HAdd ``HAdd.hAdd a b /-- Return `a - b` using a heterogeneous `-`. This method assumes `a` and `b` have the same type. -/ def mkSub (a b : Expr) : MetaM Expr := mkBinaryOp ``HSub ``HSub.hSub a b /-- Return `a * b` using a heterogeneous `*`. This method assumes `a` and `b` have the same type. -/ def mkMul (a b : Expr) : MetaM Expr := mkBinaryOp ``HMul ``HMul.hMul a b builtin_initialize registerTraceClass `Meta.appBuilder end Lean.Meta
d2a757bd8748c19b0ddb05ce0c076313a97103ef
1136b4d61007050cc632ede270de45a662f8dba4
/library/init/data/nat/lemmas.lean
af1be34191249a1a179264fedd90b39a851f21af
[ "Apache-2.0" ]
permissive
zk744750315/lean
7fe895f16cc0ef1869238a01cae903bbd623b4a9
c17e5b913b2db687ab38f53285326b9dbb2b1b6e
refs/heads/master
1,618,208,425,413
1,521,520,544,000
1,521,520,936,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
49,541
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, Jeremy Avigad -/ prelude import init.data.nat.basic init.data.nat.div init.meta init.algebra.functions universes u namespace nat attribute [pre_smt] nat_zero_eq_zero protected lemma add_comm : ∀ n m : ℕ, n + m = m + n | n 0 := eq.symm (nat.zero_add n) | n (m+1) := suffices succ (n + m) = succ (m + n), from eq.symm (succ_add m n) ▸ this, congr_arg succ (add_comm n m) protected lemma add_assoc : ∀ n m k : ℕ, (n + m) + k = n + (m + k) | n m 0 := rfl | n m (succ k) := by rw [add_succ, add_succ, add_assoc] protected lemma add_left_comm : ∀ (n m k : ℕ), n + (m + k) = m + (n + k) := left_comm nat.add nat.add_comm nat.add_assoc protected lemma add_left_cancel : ∀ {n m k : ℕ}, n + m = n + k → m = k | 0 m k := by simp [nat.zero_add] {contextual := tt} | (succ n) m k := λ h, have n+m = n+k, by { simp [succ_add] at h, assumption }, add_left_cancel this protected lemma add_right_cancel {n m k : ℕ} (h : n + m = k + m) : n = k := have m + n = m + k, by rwa [nat.add_comm n m, nat.add_comm k m] at h, nat.add_left_cancel this lemma succ_ne_zero (n : ℕ) : succ n ≠ 0 := assume h, nat.no_confusion h lemma succ_ne_self : ∀ n : ℕ, succ n ≠ n | 0 h := absurd h (nat.succ_ne_zero 0) | (n+1) h := succ_ne_self n (nat.no_confusion h (λ h, h)) protected lemma one_ne_zero : 1 ≠ (0 : ℕ) := assume h, nat.no_confusion h protected lemma zero_ne_one : 0 ≠ (1 : ℕ) := assume h, nat.no_confusion h instance : zero_ne_one_class ℕ := { zero := 0, one := 1, zero_ne_one := nat.zero_ne_one } lemma eq_zero_of_add_eq_zero_right : ∀ {n m : ℕ}, n + m = 0 → n = 0 | 0 m := by simp [nat.zero_add] | (n+1) m := λ h, begin exfalso, rw [add_one, succ_add] at h, apply succ_ne_zero _ h end lemma eq_zero_of_add_eq_zero_left {n m : ℕ} (h : n + m = 0) : m = 0 := @eq_zero_of_add_eq_zero_right m n (nat.add_comm n m ▸ h) @[simp] lemma pred_zero : pred 0 = 0 := rfl @[simp] lemma pred_succ (n : ℕ) : pred (succ n) = n := rfl protected lemma mul_zero (n : ℕ) : n * 0 = 0 := rfl lemma mul_succ (n m : ℕ) : n * succ m = n * m + n := rfl protected theorem zero_mul : ∀ (n : ℕ), 0 * n = 0 | 0 := rfl | (succ n) := by rw [mul_succ, zero_mul] private meta def sort_add := `[simp [nat.add_assoc, nat.add_comm, nat.add_left_comm]] lemma succ_mul : ∀ (n m : ℕ), (succ n) * m = (n * m) + m | n 0 := rfl | n (succ m) := begin simp [mul_succ, add_succ, succ_mul n m], sort_add end protected lemma right_distrib : ∀ (n m k : ℕ), (n + m) * k = n * k + m * k | n m 0 := rfl | n m (succ k) := begin simp [mul_succ, right_distrib n m k], sort_add end protected lemma left_distrib : ∀ (n m k : ℕ), n * (m + k) = n * m + n * k | 0 m k := by simp [nat.zero_mul] | (succ n) m k := begin simp [succ_mul, left_distrib n m k], sort_add end protected lemma mul_comm : ∀ (n m : ℕ), n * m = m * n | n 0 := by rw [nat.zero_mul, nat.mul_zero] | n (succ m) := by simp [mul_succ, succ_mul, mul_comm n m] protected lemma mul_assoc : ∀ (n m k : ℕ), (n * m) * k = n * (m * k) | n m 0 := rfl | n m (succ k) := by simp [mul_succ, nat.left_distrib, mul_assoc n m k] protected lemma mul_one : ∀ (n : ℕ), n * 1 = n := nat.zero_add protected lemma one_mul (n : ℕ) : 1 * n = n := by rw [nat.mul_comm, nat.mul_one] instance : comm_semiring nat := {add := nat.add, add_assoc := nat.add_assoc, zero := nat.zero, zero_add := nat.zero_add, add_zero := nat.add_zero, add_comm := nat.add_comm, mul := nat.mul, mul_assoc := nat.mul_assoc, one := nat.succ nat.zero, one_mul := nat.one_mul, mul_one := nat.mul_one, left_distrib := nat.left_distrib, right_distrib := nat.right_distrib, zero_mul := nat.zero_mul, mul_zero := nat.mul_zero, mul_comm := nat.mul_comm} /- properties of inequality -/ protected lemma le_of_eq {n m : ℕ} (p : n = m) : n ≤ m := p ▸ less_than_or_equal.refl n lemma le_succ_of_le {n m : ℕ} (h : n ≤ m) : n ≤ succ m := nat.le_trans h (le_succ m) lemma le_of_succ_le {n m : ℕ} (h : succ n ≤ m) : n ≤ m := nat.le_trans (le_succ n) h protected lemma le_of_lt {n m : ℕ} (h : n < m) : n ≤ m := le_of_succ_le h def lt.step {n m : ℕ} : n < m → n < succ m := less_than_or_equal.step lemma eq_zero_or_pos (n : ℕ) : n = 0 ∨ n > 0 := by {cases n, exact or.inl rfl, exact or.inr (succ_pos _)} protected lemma pos_of_ne_zero {n : nat} : n ≠ 0 → n > 0 := or.resolve_left (eq_zero_or_pos n) protected lemma lt_trans {n m k : ℕ} (h₁ : n < m) : m < k → n < k := nat.le_trans (less_than_or_equal.step h₁) protected lemma lt_of_le_of_lt {n m k : ℕ} (h₁ : n ≤ m) : m < k → n < k := nat.le_trans (succ_le_succ h₁) def lt.base (n : ℕ) : n < succ n := nat.le_refl (succ n) lemma lt_succ_self (n : ℕ) : n < succ n := lt.base n protected lemma le_antisymm {n m : ℕ} (h₁ : n ≤ m) : m ≤ n → n = m := less_than_or_equal.cases_on h₁ (λ a, rfl) (λ a b c, absurd (nat.lt_of_le_of_lt b c) (nat.lt_irrefl n)) protected lemma lt_or_ge : ∀ (a b : ℕ), a < b ∨ a ≥ b | a 0 := or.inr (zero_le a) | a (b+1) := match lt_or_ge a b with | or.inl h := or.inl (le_succ_of_le h) | or.inr h := match nat.eq_or_lt_of_le h with | or.inl h1 := or.inl (h1 ▸ lt_succ_self b) | or.inr h1 := or.inr h1 end end protected lemma le_total {m n : ℕ} : m ≤ n ∨ n ≤ m := or.imp_left nat.le_of_lt (nat.lt_or_ge m n) protected lemma lt_of_le_and_ne {m n : ℕ} (h1 : m ≤ n) : m ≠ n → m < n := or.resolve_right (or.swap (nat.eq_or_lt_of_le h1)) protected lemma lt_iff_le_not_le {m n : ℕ} : m < n ↔ (m ≤ n ∧ ¬ n ≤ m) := ⟨λ hmn, ⟨nat.le_of_lt hmn, λ hnm, nat.lt_irrefl _ (nat.lt_of_le_of_lt hnm hmn)⟩, λ ⟨hmn, hnm⟩, nat.lt_of_le_and_ne hmn (λ heq, hnm (heq ▸ nat.le_refl _))⟩ instance : linear_order ℕ := { le := nat.less_than_or_equal, le_refl := @nat.le_refl, le_trans := @nat.le_trans, le_antisymm := @nat.le_antisymm, le_total := @nat.le_total, lt := nat.lt, lt_iff_le_not_le := @nat.lt_iff_le_not_le } lemma eq_zero_of_le_zero {n : nat} (h : n ≤ 0) : n = 0 := le_antisymm h (zero_le _) lemma succ_lt_succ {a b : ℕ} : a < b → succ a < succ b := succ_le_succ lemma lt_of_succ_lt {a b : ℕ} : succ a < b → a < b := le_of_succ_le lemma lt_of_succ_lt_succ {a b : ℕ} : succ a < succ b → a < b := le_of_succ_le_succ lemma pred_lt_pred : ∀ {n m : ℕ}, n ≠ 0 → n < m → pred n < pred m | 0 _ h₁ h := absurd rfl h₁ | _ 0 h₁ h := absurd h (not_lt_zero _) | (succ n) (succ m) _ h := lt_of_succ_lt_succ h lemma lt_of_succ_le {a b : ℕ} (h : succ a ≤ b) : a < b := h lemma succ_le_of_lt {a b : ℕ} (h : a < b) : succ a ≤ b := h lemma le_add_right : ∀ (n k : ℕ), n ≤ n + k | n 0 := nat.le_refl n | n (k+1) := le_succ_of_le (le_add_right n k) lemma le_add_left (n m : ℕ): n ≤ m + n := nat.add_comm n m ▸ le_add_right n m lemma le.dest : ∀ {n m : ℕ}, n ≤ m → ∃ k, n + k = m | n ._ (less_than_or_equal.refl ._) := ⟨0, rfl⟩ | n ._ (@less_than_or_equal.step ._ m h) := match le.dest h with | ⟨w, hw⟩ := ⟨succ w, hw ▸ add_succ n w⟩ end lemma le.intro {n m k : ℕ} (h : n + k = m) : n ≤ m := h ▸ le_add_right n k protected lemma add_le_add_left {n m : ℕ} (h : n ≤ m) (k : ℕ) : k + n ≤ k + m := match le.dest h with | ⟨w, hw⟩ := @le.intro _ _ w begin rw [nat.add_assoc, hw] end end protected lemma add_le_add_right {n m : ℕ} (h : n ≤ m) (k : ℕ) : n + k ≤ m + k := begin rw [nat.add_comm n k, nat.add_comm m k], apply nat.add_le_add_left h end protected lemma le_of_add_le_add_left {k n m : ℕ} (h : k + n ≤ k + m) : n ≤ m := match le.dest h with | ⟨w, hw⟩ := @le.intro _ _ w begin rw [nat.add_assoc] at hw, apply nat.add_left_cancel hw end end protected lemma le_of_add_le_add_right {k n m : ℕ} : n + k ≤ m + k → n ≤ m := begin rw [nat.add_comm _ k, nat.add_comm _ k], apply nat.le_of_add_le_add_left end protected lemma add_le_add_iff_le_right (k n m : ℕ) : n + k ≤ m + k ↔ n ≤ m := ⟨ nat.le_of_add_le_add_right , assume h, nat.add_le_add_right h _ ⟩ protected theorem lt_of_add_lt_add_left {k n m : ℕ} (h : k + n < k + m) : n < m := let h' := nat.le_of_lt h in nat.lt_of_le_and_ne (nat.le_of_add_le_add_left h') (λ heq, nat.lt_irrefl (k + m) begin rw heq at h, assumption end) protected lemma add_lt_add_left {n m : ℕ} (h : n < m) (k : ℕ) : k + n < k + m := lt_of_succ_le (add_succ k n ▸ nat.add_le_add_left (succ_le_of_lt h) k) protected lemma add_lt_add_right {n m : ℕ} (h : n < m) (k : ℕ) : n + k < m + k := nat.add_comm k m ▸ nat.add_comm k n ▸ nat.add_lt_add_left h k protected lemma lt_add_of_pos_right {n k : ℕ} (h : k > 0) : n < n + k := nat.add_lt_add_left h n protected lemma lt_add_of_pos_left {n k : ℕ} (h : k > 0) : n < k + n := by rw add_comm; exact nat.lt_add_of_pos_right h protected lemma zero_lt_one : 0 < (1:nat) := zero_lt_succ 0 lemma mul_le_mul_left {n m : ℕ} (k : ℕ) (h : n ≤ m) : k * n ≤ k * m := match le.dest h with | ⟨l, hl⟩ := have k * n + k * l = k * m, by rw [← left_distrib, hl], le.intro this end lemma mul_le_mul_right {n m : ℕ} (k : ℕ) (h : n ≤ m) : n * k ≤ m * k := mul_comm k m ▸ mul_comm k n ▸ mul_le_mul_left k h protected lemma mul_lt_mul_of_pos_left {n m k : ℕ} (h : n < m) (hk : k > 0) : k * n < k * m := nat.lt_of_lt_of_le (nat.lt_add_of_pos_right hk) (mul_succ k n ▸ nat.mul_le_mul_left k (succ_le_of_lt h)) protected lemma mul_lt_mul_of_pos_right {n m k : ℕ} (h : n < m) (hk : k > 0) : n * k < m * k := mul_comm k m ▸ mul_comm k n ▸ nat.mul_lt_mul_of_pos_left h hk instance : decidable_linear_ordered_semiring nat := { add_left_cancel := @nat.add_left_cancel, add_right_cancel := @nat.add_right_cancel, lt := nat.lt, le := nat.le, le_refl := nat.le_refl, le_trans := @nat.le_trans, le_antisymm := @nat.le_antisymm, le_total := @nat.le_total, lt_iff_le_not_le := @lt_iff_le_not_le _ _, add_le_add_left := @nat.add_le_add_left, le_of_add_le_add_left := @nat.le_of_add_le_add_left, zero_lt_one := zero_lt_succ 0, mul_le_mul_of_nonneg_left := assume a b c h₁ h₂, nat.mul_le_mul_left c h₁, mul_le_mul_of_nonneg_right := assume a b c h₁ h₂, nat.mul_le_mul_right c h₁, mul_lt_mul_of_pos_left := @nat.mul_lt_mul_of_pos_left, mul_lt_mul_of_pos_right := @nat.mul_lt_mul_of_pos_right, decidable_lt := nat.decidable_lt, decidable_le := nat.decidable_le, decidable_eq := nat.decidable_eq, ..nat.comm_semiring } -- all the fields are already included in the decidable_linear_ordered_semiring instance instance : decidable_linear_ordered_cancel_comm_monoid ℕ := { add_left_cancel := @nat.add_left_cancel, ..nat.decidable_linear_ordered_semiring } lemma le_of_lt_succ {m n : nat} : m < succ n → m ≤ n := le_of_succ_le_succ theorem eq_of_mul_eq_mul_left {m k n : ℕ} (Hn : n > 0) (H : n * m = n * k) : m = k := le_antisymm (le_of_mul_le_mul_left (le_of_eq H) Hn) (le_of_mul_le_mul_left (le_of_eq H.symm) Hn) theorem eq_of_mul_eq_mul_right {n m k : ℕ} (Hm : m > 0) (H : n * m = k * m) : n = k := by rw [mul_comm n m, mul_comm k m] at H; exact eq_of_mul_eq_mul_left Hm H /- sub properties -/ @[simp] protected lemma zero_sub : ∀ a : ℕ, 0 - a = 0 | 0 := rfl | (a+1) := congr_arg pred (zero_sub a) lemma sub_lt_succ (a b : ℕ) : a - b < succ a := lt_succ_of_le (sub_le a b) protected theorem sub_le_sub_right {n m : ℕ} (h : n ≤ m) : ∀ k, n - k ≤ m - k | 0 := h | (succ z) := pred_le_pred (sub_le_sub_right z) /- bit0/bit1 properties -/ protected lemma bit1_eq_succ_bit0 (n : ℕ) : bit1 n = succ (bit0 n) := rfl protected lemma bit1_succ_eq (n : ℕ) : bit1 (succ n) = succ (succ (bit1 n)) := eq.trans (nat.bit1_eq_succ_bit0 (succ n)) (congr_arg succ (nat.bit0_succ_eq n)) protected lemma bit1_ne_one : ∀ {n : ℕ}, n ≠ 0 → bit1 n ≠ 1 | 0 h h1 := absurd rfl h | (n+1) h h1 := nat.no_confusion h1 (λ h2, absurd h2 (succ_ne_zero _)) protected lemma bit0_ne_one : ∀ n : ℕ, bit0 n ≠ 1 | 0 h := absurd h (ne.symm nat.one_ne_zero) | (n+1) h := have h1 : succ (succ (n + n)) = 1, from succ_add n n ▸ h, nat.no_confusion h1 (λ h2, absurd h2 (succ_ne_zero (n + n))) protected lemma add_self_ne_one : ∀ (n : ℕ), n + n ≠ 1 | 0 h := nat.no_confusion h | (n+1) h := have h1 : succ (succ (n + n)) = 1, from succ_add n n ▸ h, nat.no_confusion h1 (λ h2, absurd h2 (nat.succ_ne_zero (n + n))) protected lemma bit1_ne_bit0 : ∀ (n m : ℕ), bit1 n ≠ bit0 m | 0 m h := absurd h (ne.symm (nat.add_self_ne_one m)) | (n+1) 0 h := have h1 : succ (bit0 (succ n)) = 0, from h, absurd h1 (nat.succ_ne_zero _) | (n+1) (m+1) h := have h1 : succ (succ (bit1 n)) = succ (succ (bit0 m)), from nat.bit0_succ_eq m ▸ nat.bit1_succ_eq n ▸ h, have h2 : bit1 n = bit0 m, from nat.no_confusion h1 (λ h2', nat.no_confusion h2' (λ h2'', h2'')), absurd h2 (bit1_ne_bit0 n m) protected lemma bit0_ne_bit1 : ∀ (n m : ℕ), bit0 n ≠ bit1 m := λ n m : nat, ne.symm (nat.bit1_ne_bit0 m n) protected lemma bit0_inj : ∀ {n m : ℕ}, bit0 n = bit0 m → n = m | 0 0 h := rfl | 0 (m+1) h := by contradiction | (n+1) 0 h := by contradiction | (n+1) (m+1) h := have succ (succ (n + n)) = succ (succ (m + m)), begin unfold bit0 at h, simp [add_one, add_succ, succ_add] at h, rw h end, have n + n = m + m, by iterate { injection this with this }, have n = m, from bit0_inj this, by rw this protected lemma bit1_inj : ∀ {n m : ℕ}, bit1 n = bit1 m → n = m := λ n m h, have succ (bit0 n) = succ (bit0 m), begin simp [nat.bit1_eq_succ_bit0] at h, rw h end, have bit0 n = bit0 m, by injection this, nat.bit0_inj this protected lemma bit0_ne {n m : ℕ} : n ≠ m → bit0 n ≠ bit0 m := λ h₁ h₂, absurd (nat.bit0_inj h₂) h₁ protected lemma bit1_ne {n m : ℕ} : n ≠ m → bit1 n ≠ bit1 m := λ h₁ h₂, absurd (nat.bit1_inj h₂) h₁ protected lemma zero_ne_bit0 {n : ℕ} : n ≠ 0 → 0 ≠ bit0 n := λ h, ne.symm (nat.bit0_ne_zero h) protected lemma zero_ne_bit1 (n : ℕ) : 0 ≠ bit1 n := ne.symm (nat.bit1_ne_zero n) protected lemma one_ne_bit0 (n : ℕ) : 1 ≠ bit0 n := ne.symm (nat.bit0_ne_one n) protected lemma one_ne_bit1 {n : ℕ} : n ≠ 0 → 1 ≠ bit1 n := λ h, ne.symm (nat.bit1_ne_one h) protected lemma one_lt_bit1 : ∀ {n : nat}, n ≠ 0 → 1 < bit1 n | 0 h := by contradiction | (succ n) h := begin rw nat.bit1_succ_eq, apply succ_lt_succ, apply zero_lt_succ end protected lemma one_lt_bit0 : ∀ {n : nat}, n ≠ 0 → 1 < bit0 n | 0 h := by contradiction | (succ n) h := begin rw nat.bit0_succ_eq, apply succ_lt_succ, apply zero_lt_succ end protected lemma bit0_lt {n m : nat} (h : n < m) : bit0 n < bit0 m := add_lt_add h h protected lemma bit1_lt {n m : nat} (h : n < m) : bit1 n < bit1 m := succ_lt_succ (add_lt_add h h) protected lemma bit0_lt_bit1 {n m : nat} (h : n ≤ m) : bit0 n < bit1 m := lt_succ_of_le (add_le_add h h) protected lemma bit1_lt_bit0 : ∀ {n m : nat}, n < m → bit1 n < bit0 m | n 0 h := absurd h (not_lt_zero _) | n (succ m) h := have n ≤ m, from le_of_lt_succ h, have succ (n + n) ≤ succ (m + m), from succ_le_succ (add_le_add this this), have succ (n + n) ≤ succ m + m, {rw succ_add, assumption}, show succ (n + n) < succ (succ m + m), from lt_succ_of_le this protected lemma one_le_bit1 (n : ℕ) : 1 ≤ bit1 n := show 1 ≤ succ (bit0 n), from succ_le_succ (zero_le (bit0 n)) protected lemma one_le_bit0 : ∀ (n : ℕ), n ≠ 0 → 1 ≤ bit0 n | 0 h := absurd rfl h | (n+1) h := suffices 1 ≤ succ (succ (bit0 n)), from eq.symm (nat.bit0_succ_eq n) ▸ this, succ_le_succ (zero_le (succ (bit0 n))) /- Extra instances to short-circuit type class resolution -/ instance : add_comm_monoid nat := by apply_instance instance : add_monoid nat := by apply_instance instance : monoid nat := by apply_instance instance : comm_monoid nat := by apply_instance instance : comm_semigroup nat := by apply_instance instance : semigroup nat := by apply_instance instance : add_comm_semigroup nat := by apply_instance instance : add_semigroup nat := by apply_instance instance : distrib nat := by apply_instance instance : semiring nat := by apply_instance instance : ordered_semiring nat := by apply_instance /- subtraction -/ @[simp] protected theorem sub_zero (n : ℕ) : n - 0 = n := rfl theorem sub_succ (n m : ℕ) : n - succ m = pred (n - m) := rfl theorem succ_sub_succ (n m : ℕ) : succ n - succ m = n - m := succ_sub_succ_eq_sub n m protected theorem sub_self : ∀ (n : ℕ), n - n = 0 | 0 := by rw nat.sub_zero | (succ n) := by rw [succ_sub_succ, sub_self n] /- TODO(Leo): remove the following ematch annotations as soon as we have arithmetic theory in the smt_stactic -/ @[ematch_lhs] protected theorem add_sub_add_right : ∀ (n k m : ℕ), (n + k) - (m + k) = n - m | n 0 m := by rw [add_zero, add_zero] | n (succ k) m := by rw [add_succ, add_succ, succ_sub_succ, add_sub_add_right n k m] @[ematch_lhs] protected theorem add_sub_add_left (k n m : ℕ) : (k + n) - (k + m) = n - m := by rw [add_comm k n, add_comm k m, nat.add_sub_add_right] @[ematch_lhs] protected theorem add_sub_cancel (n m : ℕ) : n + m - m = n := suffices n + m - (0 + m) = n, from by rwa [zero_add] at this, by rw [nat.add_sub_add_right, nat.sub_zero] @[ematch_lhs] protected theorem add_sub_cancel_left (n m : ℕ) : n + m - n = m := show n + m - (n + 0) = m, from by rw [nat.add_sub_add_left, nat.sub_zero] protected theorem sub_sub : ∀ (n m k : ℕ), n - m - k = n - (m + k) | n m 0 := by rw [add_zero, nat.sub_zero] | n m (succ k) := by rw [add_succ, nat.sub_succ, nat.sub_succ, sub_sub n m k] theorem le_of_le_of_sub_le_sub_right {n m k : ℕ} (h₀ : k ≤ m) (h₁ : n - k ≤ m - k) : n ≤ m := begin revert k m, induction n with n ; intros k m h₀ h₁, { apply zero_le }, { cases k with k, { apply h₁ }, cases m with m, { cases not_succ_le_zero _ h₀ }, { simp [succ_sub_succ] at h₁, apply succ_le_succ, apply n_ih _ h₁, apply le_of_succ_le_succ h₀ }, } end protected theorem sub_le_sub_right_iff (n m k : ℕ) (h : k ≤ m) : n - k ≤ m - k ↔ n ≤ m := ⟨ le_of_le_of_sub_le_sub_right h , assume h, nat.sub_le_sub_right h k ⟩ theorem sub_self_add (n m : ℕ) : n - (n + m) = 0 := show (n + 0) - (n + m) = 0, from by rw [nat.add_sub_add_left, nat.zero_sub] theorem add_le_to_le_sub (x : ℕ) {y k : ℕ} (h : k ≤ y) : x + k ≤ y ↔ x ≤ y - k := by rw [← nat.add_sub_cancel x k, nat.sub_le_sub_right_iff _ _ _ h, nat.add_sub_cancel] lemma sub_lt_of_pos_le (a b : ℕ) (h₀ : 0 < a) (h₁ : a ≤ b) : b - a < b := begin apply sub_lt _ h₀, apply lt_of_lt_of_le h₀ h₁ end theorem sub_one (n : ℕ) : n - 1 = pred n := rfl theorem succ_sub_one (n : ℕ) : succ n - 1 = n := rfl theorem succ_pred_eq_of_pos : ∀ {n : ℕ}, n > 0 → succ (pred n) = n | 0 h := absurd h (lt_irrefl 0) | (succ k) h := rfl theorem sub_eq_zero_of_le {n m : ℕ} (h : n ≤ m) : n - m = 0 := exists.elim (nat.le.dest h) (assume k, assume hk : n + k = m, by rw [← hk, sub_self_add]) protected theorem le_of_sub_eq_zero : ∀{n m : ℕ}, n - m = 0 → n ≤ m | n 0 H := begin rw [nat.sub_zero] at H, simp [H] end | 0 (m+1) H := zero_le _ | (n+1) (m+1) H := add_le_add_right (le_of_sub_eq_zero begin simp [nat.add_sub_add_right] at H, exact H end) _ protected theorem sub_eq_zero_iff_le {n m : ℕ} : n - m = 0 ↔ n ≤ m := ⟨nat.le_of_sub_eq_zero, nat.sub_eq_zero_of_le⟩ theorem add_sub_of_le {n m : ℕ} (h : n ≤ m) : n + (m - n) = m := exists.elim (nat.le.dest h) (assume k, assume hk : n + k = m, by rw [← hk, nat.add_sub_cancel_left]) protected theorem sub_add_cancel {n m : ℕ} (h : n ≥ m) : n - m + m = n := by rw [add_comm, add_sub_of_le h] protected theorem add_sub_assoc {m k : ℕ} (h : k ≤ m) (n : ℕ) : n + m - k = n + (m - k) := exists.elim (nat.le.dest h) (assume l, assume hl : k + l = m, by rw [← hl, nat.add_sub_cancel_left, add_comm k, ← add_assoc, nat.add_sub_cancel]) protected lemma sub_eq_iff_eq_add {a b c : ℕ} (ab : b ≤ a) : a - b = c ↔ a = c + b := ⟨assume c_eq, begin rw [c_eq.symm, nat.sub_add_cancel ab] end, assume a_eq, begin rw [a_eq, nat.add_sub_cancel] end⟩ protected lemma lt_of_sub_eq_succ {m n l : ℕ} (H : m - n = nat.succ l) : n < m := lt_of_not_ge (assume (H' : n ≥ m), begin simp [nat.sub_eq_zero_of_le H'] at H, contradiction end) @[simp] lemma zero_min (a : ℕ) : min 0 a = 0 := min_eq_left (zero_le a) @[simp] lemma min_zero (a : ℕ) : min a 0 = 0 := min_eq_right (zero_le a) -- Distribute succ over min theorem min_succ_succ (x y : ℕ) : min (succ x) (succ y) = succ (min x y) := have f : x ≤ y → min (succ x) (succ y) = succ (min x y), from λp, calc min (succ x) (succ y) = succ x : if_pos (succ_le_succ p) ... = succ (min x y) : congr_arg succ (eq.symm (if_pos p)), have g : ¬ (x ≤ y) → min (succ x) (succ y) = succ (min x y), from λp, calc min (succ x) (succ y) = succ y : if_neg (λeq, p (pred_le_pred eq)) ... = succ (min x y) : congr_arg succ (eq.symm (if_neg p)), decidable.by_cases f g theorem sub_eq_sub_min (n m : ℕ) : n - m = n - min n m := if h : n ≥ m then by rewrite [min_eq_right h] else by rewrite [sub_eq_zero_of_le (le_of_not_ge h), min_eq_left (le_of_not_ge h), nat.sub_self] @[simp] theorem sub_add_min_cancel (n m : ℕ) : n - m + min n m = n := by rw [sub_eq_sub_min, nat.sub_add_cancel (min_le_left n m)] /- TODO(Leo): sub + inequalities -/ protected def strong_rec_on {p : nat → Sort u} (n : nat) (h : ∀ n, (∀ m, m < n → p m) → p n) : p n := suffices ∀ n m, m < n → p m, from this (succ n) n (lt_succ_self _), begin intros n, induction n with n ih, {intros m h₁, exact absurd h₁ (not_lt_zero _)}, {intros m h₁, apply or.by_cases (lt_or_eq_of_le (le_of_lt_succ h₁)), {intros, apply ih, assumption}, {intros, subst m, apply h _ ih}} end protected lemma strong_induction_on {p : nat → Prop} (n : nat) (h : ∀ n, (∀ m, m < n → p m) → p n) : p n := nat.strong_rec_on n h protected lemma case_strong_induction_on {p : nat → Prop} (a : nat) (hz : p 0) (hi : ∀ n, (∀ m, m ≤ n → p m) → p (succ n)) : p a := nat.strong_induction_on a $ λ n, match n with | 0 := λ _, hz | (n+1) := λ h₁, hi n (λ m h₂, h₁ _ (lt_succ_of_le h₂)) end /- mod -/ lemma mod_def (x y : nat) : x % y = if 0 < y ∧ y ≤ x then (x - y) % y else x := by have h := mod_def_aux x y; rwa [dif_eq_if] at h @[simp] lemma mod_zero (a : nat) : a % 0 = a := begin rw mod_def, have h : ¬ (0 < 0 ∧ 0 ≤ a), simp [lt_irrefl], simp [if_neg, h] end lemma mod_eq_of_lt {a b : nat} (h : a < b) : a % b = a := begin rw mod_def, have h' : ¬(0 < b ∧ b ≤ a), simp [not_le_of_gt h], simp [if_neg, h'] end @[simp] lemma zero_mod (b : nat) : 0 % b = 0 := begin rw mod_def, have h : ¬(0 < b ∧ b ≤ 0), {intro hn, cases hn with l r, exact absurd (lt_of_lt_of_le l r) (lt_irrefl 0)}, simp [if_neg, h] end lemma mod_eq_sub_mod {a b : nat} (h : a ≥ b) : a % b = (a - b) % b := or.elim (eq_zero_or_pos b) (λb0, by rw [b0, nat.sub_zero]) (λh₂, by rw [mod_def, if_pos (and.intro h₂ h)]) lemma mod_lt (x : nat) {y : nat} (h : y > 0) : x % y < y := begin induction x using nat.case_strong_induction_on with x ih, {rw zero_mod, assumption}, {apply or.elim (decidable.em (succ x < y)), {intro h₁, rwa [mod_eq_of_lt h₁]}, {intro h₁, have h₁ : succ x % y = (succ x - y) % y, {exact mod_eq_sub_mod (le_of_not_gt h₁)}, have this : succ x - y ≤ x, {exact le_of_lt_succ (sub_lt (succ_pos x) h)}, have h₂ : (succ x - y) % y < y, {exact ih _ this}, rwa [← h₁] at h₂}} end @[simp] theorem mod_self (n : nat) : n % n = 0 := by rw [mod_eq_sub_mod (le_refl _), nat.sub_self, zero_mod] @[simp] lemma mod_one (n : ℕ) : n % 1 = 0 := have n % 1 < 1, from (mod_lt n) (succ_pos 0), eq_zero_of_le_zero (le_of_lt_succ this) lemma mod_two_eq_zero_or_one (n : ℕ) : n % 2 = 0 ∨ n % 2 = 1 := match n % 2, @nat.mod_lt n 2 dec_trivial with | 0, _ := or.inl rfl | 1, _ := or.inr rfl | k+2, h := absurd h dec_trivial end /- div & mod -/ lemma div_def (x y : nat) : x / y = if 0 < y ∧ y ≤ x then (x - y) / y + 1 else 0 := by have h := div_def_aux x y; rwa dif_eq_if at h lemma mod_add_div (m k : ℕ) : m % k + k * (m / k) = m := begin apply nat.strong_induction_on m, clear m, intros m IH, cases decidable.em (0 < k ∧ k ≤ m) with h h', -- 0 < k ∧ k ≤ m { have h' : m - k < m, { apply nat.sub_lt _ h.left, apply lt_of_lt_of_le h.left h.right }, rw [div_def, mod_def, if_pos h, if_pos h], simp [left_distrib, IH _ h'], rw [← nat.add_sub_assoc h.right, nat.add_sub_cancel_left] }, -- ¬ (0 < k ∧ k ≤ m) { rw [div_def, mod_def, if_neg h', if_neg h'], simp }, end /- div -/ @[simp] protected lemma div_one (n : ℕ) : n / 1 = n := have n % 1 + 1 * (n / 1) = n, from mod_add_div _ _, by simp [mod_one] at this; assumption @[simp] protected lemma div_zero (n : ℕ) : n / 0 = 0 := begin rw [div_def], simp [lt_irrefl] end @[simp] protected lemma zero_div (b : ℕ) : 0 / b = 0 := eq.trans (div_def 0 b) $ if_neg (and.rec not_le_of_gt) protected lemma div_le_of_le_mul {m n : ℕ} : ∀ {k}, m ≤ k * n → m / k ≤ n | 0 h := by simp [nat.div_zero]; apply zero_le | (succ k) h := suffices succ k * (m / succ k) ≤ succ k * n, from le_of_mul_le_mul_left this (zero_lt_succ _), calc succ k * (m / succ k) ≤ m % succ k + succ k * (m / succ k) : le_add_left _ _ ... = m : by rw mod_add_div ... ≤ succ k * n : h protected lemma div_le_self : ∀ (m n : ℕ), m / n ≤ m | m 0 := by simp [nat.div_zero]; apply zero_le | m (succ n) := have m ≤ succ n * m, from calc m = 1 * m : by simp ... ≤ succ n * m : mul_le_mul_right _ (succ_le_succ (zero_le _)), nat.div_le_of_le_mul this lemma div_eq_sub_div {a b : nat} (h₁ : b > 0) (h₂ : a ≥ b) : a / b = (a - b) / b + 1 := begin rw [div_def a, if_pos], split ; assumption end lemma div_eq_of_lt {a b : ℕ} (h₀ : a < b) : a / b = 0 := begin rw [div_def a, if_neg], intro h₁, apply not_le_of_gt h₀ h₁.right end -- this is a Galois connection -- f x ≤ y ↔ x ≤ g y -- with -- f x = x * k -- g y = y / k theorem le_div_iff_mul_le (x y : ℕ) {k : ℕ} (Hk : k > 0) : x ≤ y / k ↔ x * k ≤ y := begin -- Hk is needed because, despite div being made total, y / 0 := 0 -- x * 0 ≤ y ↔ x ≤ y / 0 -- ↔ 0 ≤ y ↔ x ≤ 0 -- ↔ true ↔ x = 0 -- ↔ x = 0 revert x, apply nat.strong_induction_on y _, clear y, intros y IH x, cases lt_or_ge y k with h h, -- base case: y < k { rw [div_eq_of_lt h], cases x with x, { simp [zero_mul, zero_le] }, { simp [succ_mul, not_succ_le_zero], apply not_le_of_gt, apply lt_of_lt_of_le h, apply le_add_right } }, -- step: k ≤ y { rw [div_eq_sub_div Hk h], cases x with x, { simp [zero_mul, zero_le] }, { have Hlt : y - k < y, { apply sub_lt_of_pos_le ; assumption }, rw [ ← add_one , nat.add_le_add_iff_le_right , IH (y - k) Hlt x , add_one , succ_mul, add_le_to_le_sub _ h ] } } end theorem div_lt_iff_lt_mul (x y : ℕ) {k : ℕ} (Hk : k > 0) : x / k < y ↔ x < y * k := begin simp [lt_iff_not_ge], apply not_iff_not_of_iff, apply le_div_iff_mul_le _ _ Hk end def iterate {α : Sort u} (op : α → α) : ℕ → α → α | 0 a := a | (succ k) a := iterate k (op a) notation f`^[`n`]` := iterate f n /- successor and predecessor -/ theorem add_one_ne_zero (n : ℕ) : n + 1 ≠ 0 := succ_ne_zero _ theorem eq_zero_or_eq_succ_pred (n : ℕ) : n = 0 ∨ n = succ (pred n) := by cases n; simp theorem exists_eq_succ_of_ne_zero {n : ℕ} (H : n ≠ 0) : ∃k : ℕ, n = succ k := ⟨_, (eq_zero_or_eq_succ_pred _).resolve_left H⟩ theorem succ_inj {n m : ℕ} (H : succ n = succ m) : n = m := nat.succ.inj_arrow H id theorem discriminate {B : Sort u} {n : ℕ} (H1: n = 0 → B) (H2 : ∀m, n = succ m → B) : B := by induction h : n; [exact H1 h, exact H2 _ h] theorem one_succ_zero : 1 = succ 0 := rfl theorem two_step_induction {P : ℕ → Sort u} (H1 : P 0) (H2 : P 1) (H3 : ∀ (n : ℕ) (IH1 : P n) (IH2 : P (succ n)), P (succ (succ n))) : Π (a : ℕ), P a | 0 := H1 | 1 := H2 | (succ (succ n)) := H3 _ (two_step_induction _) (two_step_induction _) theorem sub_induction {P : ℕ → ℕ → Sort u} (H1 : ∀m, P 0 m) (H2 : ∀n, P (succ n) 0) (H3 : ∀n m, P n m → P (succ n) (succ m)) : Π (n m : ℕ), P n m | 0 m := H1 _ | (succ n) 0 := H2 _ | (succ n) (succ m) := H3 _ _ (sub_induction n m) /- addition -/ theorem succ_add_eq_succ_add (n m : ℕ) : succ n + m = n + succ m := by simp [succ_add, add_succ] theorem one_add (n : ℕ) : 1 + n = succ n := by simp protected theorem add_right_comm : ∀ (n m k : ℕ), n + m + k = n + k + m := right_comm nat.add nat.add_comm nat.add_assoc theorem eq_zero_of_add_eq_zero {n m : ℕ} (H : n + m = 0) : n = 0 ∧ m = 0 := ⟨nat.eq_zero_of_add_eq_zero_right H, nat.eq_zero_of_add_eq_zero_left H⟩ theorem eq_zero_of_mul_eq_zero : ∀ {n m : ℕ}, n * m = 0 → n = 0 ∨ m = 0 | 0 m := λ h, or.inl rfl | (succ n) m := begin rw succ_mul, intro h, exact or.inr (eq_zero_of_add_eq_zero_left h) end /- properties of inequality -/ theorem le_succ_of_pred_le {n m : ℕ} : pred n ≤ m → n ≤ succ m := nat.cases_on n less_than_or_equal.step (λ a, succ_le_succ) theorem le_lt_antisymm {n m : ℕ} (h₁ : n ≤ m) (h₂ : m < n) : false := nat.lt_irrefl n (nat.lt_of_le_of_lt h₁ h₂) theorem lt_le_antisymm {n m : ℕ} (h₁ : n < m) (h₂ : m ≤ n) : false := le_lt_antisymm h₂ h₁ protected theorem nat.lt_asymm {n m : ℕ} (h₁ : n < m) : ¬ m < n := le_lt_antisymm (nat.le_of_lt h₁) protected def lt_ge_by_cases {a b : ℕ} {C : Sort u} (h₁ : a < b → C) (h₂ : a ≥ b → C) : C := decidable.by_cases h₁ (λ h, h₂ (or.elim (nat.lt_or_ge a b) (λ a, absurd a h) (λ a, a))) protected def lt_by_cases {a b : ℕ} {C : Sort u} (h₁ : a < b → C) (h₂ : a = b → C) (h₃ : b < a → C) : C := nat.lt_ge_by_cases h₁ (λ h₁, nat.lt_ge_by_cases h₃ (λ h, h₂ (nat.le_antisymm h h₁))) protected theorem lt_trichotomy (a b : ℕ) : a < b ∨ a = b ∨ b < a := nat.lt_by_cases (λ h, or.inl h) (λ h, or.inr (or.inl h)) (λ h, or.inr (or.inr h)) protected theorem eq_or_lt_of_not_lt {a b : ℕ} (hnlt : ¬ a < b) : a = b ∨ b < a := (nat.lt_trichotomy a b).resolve_left hnlt theorem lt_succ_of_lt {a b : nat} (h : a < b) : a < succ b := le_succ_of_le h def one_pos := nat.zero_lt_one theorem mul_self_le_mul_self {n m : ℕ} (h : n ≤ m) : n * n ≤ m * m := mul_le_mul h h (zero_le _) (zero_le _) theorem mul_self_lt_mul_self : Π {n m : ℕ}, n < m → n * n < m * m | 0 m h := mul_pos h h | (succ n) m h := mul_lt_mul h (le_of_lt h) (succ_pos _) (zero_le _) theorem mul_self_le_mul_self_iff {n m : ℕ} : n ≤ m ↔ n * n ≤ m * m := ⟨mul_self_le_mul_self, λh, decidable.by_contradiction $ λhn, not_lt_of_ge h $ mul_self_lt_mul_self $ lt_of_not_ge hn⟩ theorem mul_self_lt_mul_self_iff {n m : ℕ} : n < m ↔ n * n < m * m := iff.trans (lt_iff_not_ge _ _) $ iff.trans (not_iff_not_of_iff mul_self_le_mul_self_iff) $ iff.symm (lt_iff_not_ge _ _) theorem le_mul_self : Π (n : ℕ), n ≤ n * n | 0 := le_refl _ | (n+1) := let t := mul_le_mul_left (n+1) (succ_pos n) in by simp at t; exact t /- subtraction -/ protected theorem sub_le_sub_left {n m : ℕ} (k) (h : n ≤ m) : k - m ≤ k - n := by induction h; [refl, exact le_trans (pred_le _) h_ih] theorem succ_sub_sub_succ (n m k : ℕ) : succ n - m - succ k = n - m - k := by rw [nat.sub_sub, nat.sub_sub, add_succ, succ_sub_succ] protected theorem sub.right_comm (m n k : ℕ) : m - n - k = m - k - n := by rw [nat.sub_sub, nat.sub_sub, add_comm] theorem mul_pred_left : ∀ (n m : ℕ), pred n * m = n * m - m | 0 m := by simp [nat.zero_sub, pred_zero, zero_mul] | (succ n) m := by rw [pred_succ, succ_mul, nat.add_sub_cancel] theorem mul_pred_right (n m : ℕ) : n * pred m = n * m - n := by rw [mul_comm, mul_pred_left, mul_comm] protected theorem mul_sub_right_distrib : ∀ (n m k : ℕ), (n - m) * k = n * k - m * k | n 0 k := by simp [nat.sub_zero] | n (succ m) k := by rw [nat.sub_succ, mul_pred_left, mul_sub_right_distrib, succ_mul, nat.sub_sub] protected theorem mul_sub_left_distrib (n m k : ℕ) : n * (m - k) = n * m - n * k := by rw [mul_comm, nat.mul_sub_right_distrib, mul_comm m n, mul_comm n k] protected theorem mul_self_sub_mul_self_eq (a b : nat) : a * a - b * b = (a + b) * (a - b) := by rw [nat.mul_sub_left_distrib, right_distrib, right_distrib, mul_comm b a, add_comm (a*a) (a*b), nat.add_sub_add_left] theorem succ_mul_succ_eq (a b : nat) : succ a * succ b = a*b + a + b + 1 := begin rw [← add_one, ← add_one], simp [right_distrib, left_distrib] end theorem succ_sub {m n : ℕ} (h : m ≥ n) : succ m - n = succ (m - n) := exists.elim (nat.le.dest h) (assume k, assume hk : n + k = m, by rw [← hk, nat.add_sub_cancel_left, ← add_succ, nat.add_sub_cancel_left]) protected theorem sub_pos_of_lt {m n : ℕ} (h : m < n) : n - m > 0 := have 0 + m < n - m + m, begin rw [zero_add, nat.sub_add_cancel (le_of_lt h)], exact h end, lt_of_add_lt_add_right this protected theorem sub_sub_self {n m : ℕ} (h : m ≤ n) : n - (n - m) = m := (nat.sub_eq_iff_eq_add (nat.sub_le _ _)).2 (eq.symm (add_sub_of_le h)) protected theorem sub_add_comm {n m k : ℕ} (h : k ≤ n) : n + m - k = n - k + m := (nat.sub_eq_iff_eq_add (nat.le_trans h (nat.le_add_right _ _))).2 (by rwa [nat.add_right_comm, nat.sub_add_cancel]) theorem sub_one_sub_lt {n i} (h : i < n) : n - 1 - i < n := begin rw nat.sub_sub, apply nat.sub_lt, apply lt_of_lt_of_le (nat.zero_lt_succ _) h, rw add_comm, apply nat.zero_lt_succ end theorem pred_inj : ∀ {a b : nat}, a > 0 → b > 0 → nat.pred a = nat.pred b → a = b | (succ a) (succ b) ha hb h := have a = b, from h, by rw this | (succ a) 0 ha hb h := absurd hb (lt_irrefl _) | 0 (succ b) ha hb h := absurd ha (lt_irrefl _) | 0 0 ha hb h := rfl /- find -/ section find parameter {p : ℕ → Prop} private def lbp (m n : ℕ) : Prop := m = n + 1 ∧ ∀ k ≤ n, ¬p k parameters [decidable_pred p] (H : ∃n, p n) private def wf_lbp : well_founded lbp := ⟨let ⟨n, pn⟩ := H in suffices ∀m k, n ≤ k + m → acc lbp k, from λa, this _ _ (nat.le_add_left _ _), λm, nat.rec_on m (λk kn, ⟨_, λy r, match y, r with ._, ⟨rfl, a⟩ := absurd pn (a _ kn) end⟩) (λm IH k kn, ⟨_, λy r, match y, r with ._, ⟨rfl, a⟩ := IH _ (by rw nat.add_right_comm; exact kn) end⟩)⟩ protected def find_x : {n // p n ∧ ∀m < n, ¬p m} := @well_founded.fix _ (λk, (∀n < k, ¬p n) → {n // p n ∧ ∀m < n, ¬p m}) lbp wf_lbp (λm IH al, if pm : p m then ⟨m, pm, al⟩ else have ∀ n ≤ m, ¬p n, from λn h, or.elim (lt_or_eq_of_le h) (al n) (λe, by rw e; exact pm), IH _ ⟨rfl, this⟩ (λn h, this n $ nat.le_of_succ_le_succ h)) 0 (λn h, absurd h (nat.not_lt_zero _)) protected def find : ℕ := nat.find_x.1 protected theorem find_spec : p nat.find := nat.find_x.2.left protected theorem find_min : ∀ {m : ℕ}, m < nat.find → ¬p m := nat.find_x.2.right protected theorem find_min' {m : ℕ} (h : p m) : nat.find ≤ m := le_of_not_gt (λ l, find_min l h) end find /- mod -/ theorem mod_le (x y : ℕ) : x % y ≤ x := or.elim (lt_or_ge x y) (λxlty, by rw mod_eq_of_lt xlty; refl) (λylex, or.elim (eq_zero_or_pos y) (λy0, by rw [y0, mod_zero]; refl) (λypos, le_trans (le_of_lt (mod_lt _ ypos)) ylex)) @[simp] theorem add_mod_right (x z : ℕ) : (x + z) % z = x % z := by rw [mod_eq_sub_mod (nat.le_add_left _ _), nat.add_sub_cancel] @[simp] theorem add_mod_left (x z : ℕ) : (x + z) % x = z % x := by rw [add_comm, add_mod_right] @[simp] theorem add_mul_mod_self_left (x y z : ℕ) : (x + y * z) % y = x % y := by {induction z with z ih, simp, rw[mul_succ, ← add_assoc, add_mod_right, ih]} @[simp] theorem add_mul_mod_self_right (x y z : ℕ) : (x + y * z) % z = x % z := by rw [mul_comm, add_mul_mod_self_left] @[simp] theorem mul_mod_right (m n : ℕ) : (m * n) % m = 0 := by rw [← zero_add (m*n), add_mul_mod_self_left, zero_mod] @[simp] theorem mul_mod_left (m n : ℕ) : (m * n) % n = 0 := by rw [mul_comm, mul_mod_right] theorem mul_mod_mul_left (z x y : ℕ) : (z * x) % (z * y) = z * (x % y) := if y0 : y = 0 then by rw [y0, mul_zero, mod_zero, mod_zero] else if z0 : z = 0 then by rw [z0, zero_mul, zero_mul, zero_mul, mod_zero] else x.strong_induction_on $ λn IH, have y0 : y > 0, from nat.pos_of_ne_zero y0, have z0 : z > 0, from nat.pos_of_ne_zero z0, or.elim (le_or_gt y n) (λyn, by rw [ mod_eq_sub_mod yn, mod_eq_sub_mod (mul_le_mul_left z yn), ← nat.mul_sub_left_distrib]; exact IH _ (sub_lt (lt_of_lt_of_le y0 yn) y0)) (λyn, by rw [mod_eq_of_lt yn, mod_eq_of_lt (mul_lt_mul_of_pos_left yn z0)]) theorem mul_mod_mul_right (z x y : ℕ) : (x * z) % (y * z) = (x % y) * z := by rw [mul_comm x z, mul_comm y z, mul_comm (x % y) z]; apply mul_mod_mul_left theorem cond_to_bool_mod_two (x : ℕ) [d : decidable (x % 2 = 1)] : cond (@to_bool (x % 2 = 1) d) 1 0 = x % 2 := begin by_cases h : x % 2 = 1, { simp! [*] }, { cases mod_two_eq_zero_or_one x; simp! [*] } end theorem sub_mul_mod (x k n : ℕ) (h₁ : n*k ≤ x) : (x - n*k) % n = x % n := begin induction k with k, { simp }, { have h₂ : n * k ≤ x, { rw [mul_succ] at h₁, apply nat.le_trans _ h₁, apply le_add_right _ n }, have h₄ : x - n * k ≥ n, { apply @nat.le_of_add_le_add_right (n*k), rw [nat.sub_add_cancel h₂], simp [mul_succ] at h₁, simp [h₁] }, rw [mul_succ, ← nat.sub_sub, ← mod_eq_sub_mod h₄, k_ih h₂] } end /- div -/ theorem sub_mul_div (x n p : ℕ) (h₁ : n*p ≤ x) : (x - n*p) / n = x / n - p := begin cases eq_zero_or_pos n with h₀ h₀, { rw [h₀, nat.div_zero, nat.div_zero, nat.zero_sub] }, { induction p with p, { simp }, { have h₂ : n*p ≤ x, { transitivity, { apply nat.mul_le_mul_left, apply le_succ }, { apply h₁ } }, have h₃ : x - n * p ≥ n, { apply le_of_add_le_add_right, rw [nat.sub_add_cancel h₂, add_comm], rw [mul_succ] at h₁, apply h₁ }, rw [sub_succ, ← p_ih h₂], rw [@div_eq_sub_div (x - n*p) _ h₀ h₃], simp [add_one, pred_succ, mul_succ, nat.sub_sub] } } end theorem div_mul_le_self : ∀ (m n : ℕ), m / n * n ≤ m | m 0 := by simp; apply zero_le | m (succ n) := (le_div_iff_mul_le _ _ (nat.succ_pos _)).1 (le_refl _) @[simp] theorem add_div_right (x : ℕ) {z : ℕ} (H : z > 0) : (x + z) / z = succ (x / z) := by rw [div_eq_sub_div H (nat.le_add_left _ _), nat.add_sub_cancel] @[simp] theorem add_div_left (x : ℕ) {z : ℕ} (H : z > 0) : (z + x) / z = succ (x / z) := by rw [add_comm, add_div_right x H] @[simp] theorem mul_div_right (n : ℕ) {m : ℕ} (H : m > 0) : m * n / m = n := by {induction n; simp [*, mul_succ, -mul_comm]} @[simp] theorem mul_div_left (m : ℕ) {n : ℕ} (H : n > 0) : m * n / n = m := by rw [mul_comm, mul_div_right _ H] protected theorem div_self {n : ℕ} (H : n > 0) : n / n = 1 := let t := add_div_right 0 H in by rwa [zero_add, nat.zero_div] at t theorem add_mul_div_left (x z : ℕ) {y : ℕ} (H : y > 0) : (x + y * z) / y = x / y + z := by {induction z with z ih, simp, rw [mul_succ, ← add_assoc, add_div_right _ H, ih]} theorem add_mul_div_right (x y : ℕ) {z : ℕ} (H : z > 0) : (x + y * z) / z = x / z + y := by rw [mul_comm, add_mul_div_left _ _ H] protected theorem mul_div_cancel (m : ℕ) {n : ℕ} (H : n > 0) : m * n / n = m := let t := add_mul_div_right 0 m H in by rwa [zero_add, nat.zero_div, zero_add] at t protected theorem mul_div_cancel_left (m : ℕ) {n : ℕ} (H : n > 0) : n * m / n = m := by rw [mul_comm, nat.mul_div_cancel _ H] protected theorem div_eq_of_eq_mul_left {m n k : ℕ} (H1 : n > 0) (H2 : m = k * n) : m / n = k := by rw [H2, nat.mul_div_cancel _ H1] protected theorem div_eq_of_eq_mul_right {m n k : ℕ} (H1 : n > 0) (H2 : m = n * k) : m / n = k := by rw [H2, nat.mul_div_cancel_left _ H1] protected theorem div_eq_of_lt_le {m n k : ℕ} (lo : k * n ≤ m) (hi : m < succ k * n) : m / n = k := have npos : n > 0, from (eq_zero_or_pos _).resolve_left $ λ hn, by rw [hn, mul_zero] at hi lo; exact absurd lo (not_le_of_gt hi), le_antisymm (le_of_lt_succ ((nat.div_lt_iff_lt_mul _ _ npos).2 hi)) ((nat.le_div_iff_mul_le _ _ npos).2 lo) theorem mul_sub_div (x n p : ℕ) (h₁ : x < n*p) : (n * p - succ x) / n = p - succ (x / n) := begin have npos : n > 0 := (eq_zero_or_pos _).resolve_left (λ n0, by rw [n0, zero_mul] at h₁; exact not_lt_zero _ h₁), apply nat.div_eq_of_lt_le, { rw [nat.mul_sub_right_distrib, mul_comm], apply nat.sub_le_sub_left, exact (div_lt_iff_lt_mul _ _ npos).1 (lt_succ_self _) }, { change succ (pred (n * p - x)) ≤ (succ (pred (p - x / n))) * n, rw [succ_pred_eq_of_pos (nat.sub_pos_of_lt h₁), succ_pred_eq_of_pos (nat.sub_pos_of_lt _)], { rw [nat.mul_sub_right_distrib, mul_comm], apply nat.sub_le_sub_left, apply div_mul_le_self }, { apply (div_lt_iff_lt_mul _ _ npos).2, rwa mul_comm } } end protected theorem div_div_eq_div_mul (m n k : ℕ) : m / n / k = m / (n * k) := begin cases eq_zero_or_pos k with k0 kpos, {rw [k0, mul_zero, nat.div_zero, nat.div_zero]}, cases eq_zero_or_pos n with n0 npos, {rw [n0, zero_mul, nat.div_zero, nat.zero_div]}, apply le_antisymm, { apply (le_div_iff_mul_le _ _ (mul_pos npos kpos)).2, rw [mul_comm n k, ← mul_assoc], apply (le_div_iff_mul_le _ _ npos).1, apply (le_div_iff_mul_le _ _ kpos).1, refl }, { apply (le_div_iff_mul_le _ _ kpos).2, apply (le_div_iff_mul_le _ _ npos).2, rw [mul_assoc, mul_comm n k], apply (le_div_iff_mul_le _ _ (mul_pos kpos npos)).1, refl } end protected theorem mul_div_mul {m : ℕ} (n k : ℕ) (H : m > 0) : m * n / (m * k) = n / k := by rw [← nat.div_div_eq_div_mul, nat.mul_div_cancel_left _ H] /- dvd -/ protected theorem dvd_add_iff_right {k m n : ℕ} (h : k ∣ m) : k ∣ n ↔ k ∣ m + n := ⟨dvd_add h, dvd.elim h $ λd hd, match m, hd with | ._, rfl := λh₂, dvd.elim h₂ $ λe he, ⟨e - d, by rw [nat.mul_sub_left_distrib, ← he, nat.add_sub_cancel_left]⟩ end⟩ protected theorem dvd_add_iff_left {k m n : ℕ} (h : k ∣ n) : k ∣ m ↔ k ∣ m + n := by rw add_comm; exact nat.dvd_add_iff_right h theorem dvd_sub {k m n : ℕ} (H : n ≤ m) (h₁ : k ∣ m) (h₂ : k ∣ n) : k ∣ m - n := (nat.dvd_add_iff_left h₂).2 $ by rw nat.sub_add_cancel H; exact h₁ theorem dvd_mod_iff {k m n : ℕ} (h : k ∣ n) : k ∣ m % n ↔ k ∣ m := let t := @nat.dvd_add_iff_left _ (m % n) _ (dvd_trans h (dvd_mul_right n (m / n))) in by rwa mod_add_div at t theorem le_of_dvd {m n : ℕ} (h : n > 0) : m ∣ n → m ≤ n := λ⟨k, e⟩, by { revert h, rw e, refine k.cases_on _ _, exact λhn, absurd hn (lt_irrefl _), exact λk _, let t := mul_le_mul_left m (succ_pos k) in by rwa mul_one at t } theorem dvd_antisymm : Π {m n : ℕ}, m ∣ n → n ∣ m → m = n | m 0 h₁ h₂ := eq_zero_of_zero_dvd h₂ | 0 n h₁ h₂ := (eq_zero_of_zero_dvd h₁).symm | (succ m) (succ n) h₁ h₂ := le_antisymm (le_of_dvd (succ_pos _) h₁) (le_of_dvd (succ_pos _) h₂) theorem pos_of_dvd_of_pos {m n : ℕ} (H1 : m ∣ n) (H2 : n > 0) : m > 0 := nat.pos_of_ne_zero $ λm0, by rw m0 at H1; rw eq_zero_of_zero_dvd H1 at H2; exact lt_irrefl _ H2 theorem eq_one_of_dvd_one {n : ℕ} (H : n ∣ 1) : n = 1 := le_antisymm (le_of_dvd dec_trivial H) (pos_of_dvd_of_pos H dec_trivial) theorem dvd_of_mod_eq_zero {m n : ℕ} (H : n % m = 0) : m ∣ n := dvd.intro (n / m) $ let t := mod_add_div n m in by simp [H] at t; exact t theorem mod_eq_zero_of_dvd {m n : ℕ} (H : m ∣ n) : n % m = 0 := dvd.elim H (λ z H1, by rw [H1, mul_mod_right]) theorem dvd_iff_mod_eq_zero (m n : ℕ) : m ∣ n ↔ n % m = 0 := ⟨mod_eq_zero_of_dvd, dvd_of_mod_eq_zero⟩ instance decidable_dvd : @decidable_rel ℕ (∣) := λm n, decidable_of_decidable_of_iff (by apply_instance) (dvd_iff_mod_eq_zero _ _).symm protected theorem mul_div_cancel' {m n : ℕ} (H : n ∣ m) : n * (m / n) = m := let t := mod_add_div m n in by rwa [mod_eq_zero_of_dvd H, zero_add] at t protected theorem div_mul_cancel {m n : ℕ} (H : n ∣ m) : m / n * n = m := by rw [mul_comm, nat.mul_div_cancel' H] protected theorem mul_div_assoc (m : ℕ) {n k : ℕ} (H : k ∣ n) : m * n / k = m * (n / k) := or.elim (eq_zero_or_pos k) (λh, by rw [h, nat.div_zero, nat.div_zero, mul_zero]) (λh, have m * n / k = m * (n / k * k) / k, by rw nat.div_mul_cancel H, by rw[this, ← mul_assoc, nat.mul_div_cancel _ h]) theorem dvd_of_mul_dvd_mul_left {m n k : ℕ} (kpos : k > 0) (H : k * m ∣ k * n) : m ∣ n := dvd.elim H (λl H1, by rw mul_assoc at H1; exact ⟨_, eq_of_mul_eq_mul_left kpos H1⟩) theorem dvd_of_mul_dvd_mul_right {m n k : ℕ} (kpos : k > 0) (H : m * k ∣ n * k) : m ∣ n := by rw [mul_comm m k, mul_comm n k] at H; exact dvd_of_mul_dvd_mul_left kpos H /- pow -/ @[simp] theorem pow_one (b : ℕ) : b^1 = b := by simp [pow_succ] theorem pow_le_pow_of_le_left {x y : ℕ} (H : x ≤ y) : ∀ i, x^i ≤ y^i | 0 := le_refl _ | (succ i) := mul_le_mul (pow_le_pow_of_le_left i) H (zero_le _) (zero_le _) theorem pow_le_pow_of_le_right {x : ℕ} (H : x > 0) {i} : ∀ {j}, i ≤ j → x^i ≤ x^j | 0 h := by rw eq_zero_of_le_zero h; apply le_refl | (succ j) h := (lt_or_eq_of_le h).elim (λhl, by rw [pow_succ, ← mul_one (x^i)]; exact mul_le_mul (pow_le_pow_of_le_right $ le_of_lt_succ hl) H (zero_le _) (zero_le _)) (λe, by rw e; refl) theorem pos_pow_of_pos {b : ℕ} (n : ℕ) (h : 0 < b) : 0 < b^n := pow_le_pow_of_le_right h (zero_le _) theorem zero_pow {n : ℕ} (h : 0 < n) : 0^n = 0 := by rw [← succ_pred_eq_of_pos h, pow_succ, mul_zero] theorem pow_lt_pow_of_lt_left {x y : ℕ} (H : x < y) {i} (h : i > 0) : x^i < y^i := begin cases i with i, { exact absurd h (not_lt_zero _) }, rw [pow_succ, pow_succ], exact mul_lt_mul' (pow_le_pow_of_le_left (le_of_lt H) _) H (zero_le _) (pos_pow_of_pos _ $ lt_of_le_of_lt (zero_le _) H) end theorem pow_lt_pow_of_lt_right {x : ℕ} (H : x > 1) {i j} (h : i < j) : x^i < x^j := begin have xpos := lt_of_succ_lt H, refine lt_of_lt_of_le _ (pow_le_pow_of_le_right xpos h), rw [← mul_one (x^i), pow_succ], exact nat.mul_lt_mul_of_pos_left H (pos_pow_of_pos _ xpos) end /- mod / div / pow -/ local attribute [simp] mul_comm theorem mod_pow_succ {b : ℕ} (b_pos : b > 0) (w m : ℕ) : m % (b^succ w) = b * (m/b % b^w) + m % b := begin apply nat.strong_induction_on m, clear m, intros p IH, cases lt_or_ge p (b^succ w) with h₁ h₁, -- base case: p < b^succ w { have h₂ : p / b < b^w, { rw [div_lt_iff_lt_mul p _ b_pos], simp [pow_succ] at h₁, simp [h₁] }, rw [mod_eq_of_lt h₁, mod_eq_of_lt h₂], simp [mod_add_div] }, -- step: p ≥ b^succ w { -- Generate condiition for induction principal have h₂ : p - b^succ w < p, { apply sub_lt_of_pos_le _ _ (pos_pow_of_pos _ b_pos) h₁ }, -- Apply induction rw [mod_eq_sub_mod h₁, IH _ h₂], -- Normalize goal and h1 simp [pow_succ], simp [ge, pow_succ] at h₁, -- Pull subtraction outside mod and div rw [sub_mul_mod _ _ _ h₁, sub_mul_div _ _ _ h₁], -- Cancel subtraction inside mod b^w have p_b_ge : b^w ≤ p / b, { rw [le_div_iff_mul_le _ _ b_pos], simp [h₁] }, rw [eq.symm (mod_eq_sub_mod p_b_ge)] } end lemma div_lt_self {n m : nat} : n > 0 → m > 1 → n / m < n := begin intros h₁ h₂, have m_pos : m > 0, { apply lt_trans _ h₂, comp_val }, suffices : 1 * n < m * n, { simp at this, exact iff.mpr (div_lt_iff_lt_mul n n m_pos) this }, exact mul_lt_mul h₂ (le_refl _) h₁ (nat.zero_le _) end end nat
9d6e94c61ad0bd778a8af548944d3b5776e9985b
07c6143268cfb72beccd1cc35735d424ebcb187b
/src/data/nat/basic.lean
72cdd2ff3679ce53d17e783fff42f6e002a3d0c3
[ "Apache-2.0" ]
permissive
khoek/mathlib
bc49a842910af13a3c372748310e86467d1dc766
aa55f8b50354b3e11ba64792dcb06cccb2d8ee28
refs/heads/master
1,588,232,063,837
1,587,304,803,000
1,587,304,803,000
176,688,517
0
0
Apache-2.0
1,553,070,585,000
1,553,070,585,000
null
UTF-8
Lean
false
false
59,981
lean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Leonardo de Moura, Jeremy Avigad, Mario Carneiro -/ import logic.basic algebra.ordered_ring data.option.basic algebra.order_functions /-! # Basic operations on the natural numbers This files has some basic lemmas about natural numbers, definition of the `choice` function, and extra recursors: * `le_rec_on`, `le_induction`: recursion and induction principles starting at non-zero numbers. * `decreasing_induction` : recursion growing downwards. * `strong_rec'` : recursion based on strong inequalities. -/ universes u v namespace nat variables {m n k : ℕ} -- Sometimes a bare `nat.add` or similar appears as a consequence of unfolding -- during pattern matching. These lemmas package them back up as typeclass -- mediated operations. @[simp] theorem add_def {a b : ℕ} : nat.add a b = a + b := rfl @[simp] theorem mul_def {a b : ℕ} : nat.mul a b = a * b := rfl attribute [simp] nat.add_sub_cancel nat.add_sub_cancel_left attribute [simp] nat.sub_self @[simp] lemma succ_pos' {n : ℕ} : 0 < succ n := succ_pos n theorem succ_inj' {n m : ℕ} : succ n = succ m ↔ n = m := ⟨succ_inj, congr_arg _⟩ theorem succ_le_succ_iff {m n : ℕ} : succ m ≤ succ n ↔ m ≤ n := ⟨le_of_succ_le_succ, succ_le_succ⟩ lemma zero_max {m : nat} : max 0 m = m := max_eq_right (zero_le _) theorem max_succ_succ {m n : ℕ} : max (succ m) (succ n) = succ (max m n) := begin by_cases h1 : m ≤ n, rw [max_eq_right h1, max_eq_right (succ_le_succ h1)], { rw not_le at h1, have h2 := le_of_lt h1, rw [max_eq_left h2, max_eq_left (succ_le_succ h2)] } end lemma not_succ_lt_self {n : ℕ} : ¬succ n < n := not_lt_of_ge (nat.le_succ _) theorem lt_succ_iff {m n : ℕ} : m < succ n ↔ m ≤ n := succ_le_succ_iff lemma succ_le_iff {m n : ℕ} : succ m ≤ n ↔ m < n := ⟨lt_of_succ_le, succ_le_of_lt⟩ lemma lt_iff_add_one_le {m n : ℕ} : m < n ↔ m + 1 ≤ n := by rw succ_le_iff -- Just a restatement of `nat.lt_succ_iff` using `+1`. lemma lt_add_one_iff {a b : ℕ} : a < b + 1 ↔ a ≤ b := lt_succ_iff -- A flipped version of `lt_add_one_iff`. lemma lt_one_add_iff {a b : ℕ} : a < 1 + b ↔ a ≤ b := by simp only [add_comm, lt_succ_iff] -- This is true reflexively, by the definition of `≤` on ℕ, -- but it's still useful to have, to convince Lean to change the syntactic type. lemma add_one_le_iff {a b : ℕ} : a + 1 ≤ b ↔ a < b := iff.refl _ lemma one_add_le_iff {a b : ℕ} : 1 + a ≤ b ↔ a < b := by simp only [add_comm, add_one_le_iff] theorem of_le_succ {n m : ℕ} (H : n ≤ m.succ) : n ≤ m ∨ n = m.succ := (lt_or_eq_of_le H).imp le_of_lt_succ id /-- Recursion starting at a non-zero number: given a map `C k → C (k+1)` for each `k`, there is a map from `C n` to each `C m`, `n ≤ m`. -/ @[elab_as_eliminator] def le_rec_on {C : ℕ → Sort u} {n : ℕ} : Π {m : ℕ}, n ≤ m → (Π {k}, C k → C (k+1)) → C n → C m | 0 H next x := eq.rec_on (eq_zero_of_le_zero H) x | (m+1) H next x := or.by_cases (of_le_succ H) (λ h : n ≤ m, next $ le_rec_on h @next x) (λ h : n = m + 1, eq.rec_on h x) theorem le_rec_on_self {C : ℕ → Sort u} {n} {h : n ≤ n} {next} (x : C n) : (le_rec_on h next x : C n) = x := by cases n; unfold le_rec_on or.by_cases; rw [dif_neg n.not_succ_le_self, dif_pos rfl] theorem le_rec_on_succ {C : ℕ → Sort u} {n m} (h1 : n ≤ m) {h2 : n ≤ m+1} {next} (x : C n) : (le_rec_on h2 @next x : C (m+1)) = next (le_rec_on h1 @next x : C m) := by conv { to_lhs, rw [le_rec_on, or.by_cases, dif_pos h1] } theorem le_rec_on_succ' {C : ℕ → Sort u} {n} {h : n ≤ n+1} {next} (x : C n) : (le_rec_on h next x : C (n+1)) = next x := by rw [le_rec_on_succ (le_refl n), le_rec_on_self] theorem le_rec_on_trans {C : ℕ → Sort u} {n m k} (hnm : n ≤ m) (hmk : m ≤ k) {next} (x : C n) : (le_rec_on (le_trans hnm hmk) @next x : C k) = le_rec_on hmk @next (le_rec_on hnm @next x) := begin induction hmk with k hmk ih, { rw le_rec_on_self }, rw [le_rec_on_succ (le_trans hnm hmk), ih, le_rec_on_succ] end theorem le_rec_on_succ_left {C : ℕ → Sort u} {n m} (h1 : n ≤ m) (h2 : n+1 ≤ m) {next : Π{{k}}, C k → C (k+1)} (x : C n) : (le_rec_on h2 next (next x) : C m) = (le_rec_on h1 next x : C m) := begin rw [subsingleton.elim h1 (le_trans (le_succ n) h2), le_rec_on_trans (le_succ n) h2, le_rec_on_succ'] end theorem le_rec_on_injective {C : ℕ → Sort u} {n m} (hnm : n ≤ m) (next : Π n, C n → C (n+1)) (Hnext : ∀ n, function.injective (next n)) : function.injective (le_rec_on hnm next) := begin induction hnm with m hnm ih, { intros x y H, rwa [le_rec_on_self, le_rec_on_self] at H }, intros x y H, rw [le_rec_on_succ hnm, le_rec_on_succ hnm] at H, exact ih (Hnext _ H) end theorem le_rec_on_surjective {C : ℕ → Sort u} {n m} (hnm : n ≤ m) (next : Π n, C n → C (n+1)) (Hnext : ∀ n, function.surjective (next n)) : function.surjective (le_rec_on hnm next) := begin induction hnm with m hnm ih, { intros x, use x, rw le_rec_on_self }, intros x, rcases Hnext _ x with ⟨w, rfl⟩, rcases ih w with ⟨x, rfl⟩, use x, rw le_rec_on_succ end theorem pred_eq_of_eq_succ {m n : ℕ} (H : m = n.succ) : m.pred = n := by simp [H] @[simp] lemma pred_eq_succ_iff {n m : ℕ} : pred n = succ m ↔ n = m + 2 := by cases n; split; rintro ⟨⟩; refl theorem pred_sub (n m : ℕ) : pred n - m = pred (n - m) := by rw [← sub_one, nat.sub_sub, one_add]; refl @[simp] lemma add_succ_sub_one (n m : ℕ) : (n + succ m) - 1 = n + m := by rw [add_succ, succ_sub_one] @[simp] lemma succ_add_sub_one (n m : ℕ) : (succ n + m) - 1 = n + m := by rw [succ_add, succ_sub_one] lemma pred_eq_sub_one (n : ℕ) : pred n = n - 1 := rfl lemma one_le_of_lt {n m : ℕ} (h : n < m) : 1 ≤ m := lt_of_le_of_lt (nat.zero_le _) h lemma le_pred_of_lt {n m : ℕ} (h : m < n) : m ≤ n - 1 := nat.sub_le_sub_right h 1 lemma le_of_pred_lt {m n : ℕ} : pred m < n → m ≤ n := match m with | 0 := le_of_lt | m+1 := id end /-- This ensures that `simp` succeeds on `pred (n + 1) = n`. -/ @[simp] lemma pred_one_add (n : ℕ) : pred (1 + n) = n := by rw [add_comm, add_one, pred_succ] theorem pos_iff_ne_zero : 0 < n ↔ n ≠ 0 := ⟨ne_of_gt, nat.pos_of_ne_zero⟩ lemma one_lt_iff_ne_zero_and_ne_one : ∀ {n : ℕ}, 1 < n ↔ n ≠ 0 ∧ n ≠ 1 | 0 := dec_trivial | 1 := dec_trivial | (n+2) := dec_trivial theorem eq_of_lt_succ_of_not_lt {a b : ℕ} (h1 : a < b + 1) (h2 : ¬ a < b) : a = b := have h3 : a ≤ b, from le_of_lt_succ h1, or.elim (eq_or_lt_of_not_lt h2) (λ h, h) (λ h, absurd h (not_lt_of_ge h3)) protected theorem le_sub_add (n m : ℕ) : n ≤ n - m + m := or.elim (le_total n m) (assume : n ≤ m, begin rw [sub_eq_zero_of_le this, zero_add], exact this end) (assume : m ≤ n, begin rw (nat.sub_add_cancel this) end) theorem sub_add_eq_max (n m : ℕ) : n - m + m = max n m := eq_max (nat.le_sub_add _ _) (le_add_left _ _) $ λ k h₁ h₂, by rw ← nat.sub_add_cancel h₂; exact add_le_add_right (nat.sub_le_sub_right h₁ _) _ theorem sub_add_min (n m : ℕ) : n - m + min n m = n := (le_total n m).elim (λ h, by rw [min_eq_left h, sub_eq_zero_of_le h, zero_add]) (λ h, by rw [min_eq_right h, nat.sub_add_cancel h]) protected theorem add_sub_cancel' {n m : ℕ} (h : m ≤ n) : m + (n - m) = n := by rw [add_comm, nat.sub_add_cancel h] protected theorem sub_eq_of_eq_add (h : k = m + n) : k - m = n := begin rw [h, nat.add_sub_cancel_left] end theorem sub_cancel {a b c : ℕ} (h₁ : a ≤ b) (h₂ : a ≤ c) (w : b - a = c - a) : b = c := by rw [←nat.sub_add_cancel h₁, ←nat.sub_add_cancel h₂, w] lemma sub_sub_sub_cancel_right {a b c : ℕ} (h₂ : c ≤ b) : (a - c) - (b - c) = a - b := by rw [nat.sub_sub, ←nat.add_sub_assoc h₂, nat.add_sub_cancel_left] lemma add_sub_cancel_right (n m k : ℕ) : n + (m + k) - k = n + m := by { rw [nat.add_sub_assoc, nat.add_sub_cancel], apply k.le_add_left } protected lemma sub_add_eq_add_sub {a b c : ℕ} (h : b ≤ a) : (a - b) + c = (a + c) - b := by rw [add_comm a, nat.add_sub_assoc h, add_comm] theorem sub_min (n m : ℕ) : n - min n m = n - m := nat.sub_eq_of_eq_add $ by rw [add_comm, sub_add_min] theorem sub_sub_assoc {a b c : ℕ} (h₁ : b ≤ a) (h₂ : c ≤ b) : a - (b - c) = a - b + c := (nat.sub_eq_iff_eq_add (le_trans (nat.sub_le _ _) h₁)).2 $ by rw [add_right_comm, add_assoc, nat.sub_add_cancel h₂, nat.sub_add_cancel h₁] protected theorem lt_of_sub_pos (h : 0 < n - m) : m < n := lt_of_not_ge (assume : n ≤ m, have n - m = 0, from sub_eq_zero_of_le this, begin rw this at h, exact lt_irrefl _ h end) protected theorem lt_of_sub_lt_sub_right : m - k < n - k → m < n := lt_imp_lt_of_le_imp_le (λ h, nat.sub_le_sub_right h _) protected theorem lt_of_sub_lt_sub_left : m - n < m - k → k < n := lt_imp_lt_of_le_imp_le (nat.sub_le_sub_left _) protected theorem sub_lt_self (h₁ : 0 < m) (h₂ : 0 < n) : m - n < m := calc m - n = succ (pred m) - succ (pred n) : by rw [succ_pred_eq_of_pos h₁, succ_pred_eq_of_pos h₂] ... = pred m - pred n : by rw succ_sub_succ ... ≤ pred m : sub_le _ _ ... < succ (pred m) : lt_succ_self _ ... = m : succ_pred_eq_of_pos h₁ protected theorem le_sub_right_of_add_le (h : m + k ≤ n) : m ≤ n - k := by rw ← nat.add_sub_cancel m k; exact nat.sub_le_sub_right h k protected theorem le_sub_left_of_add_le (h : k + m ≤ n) : m ≤ n - k := nat.le_sub_right_of_add_le (by rwa add_comm at h) protected theorem lt_sub_right_of_add_lt (h : m + k < n) : m < n - k := lt_of_succ_le $ nat.le_sub_right_of_add_le $ by rw succ_add; exact succ_le_of_lt h protected theorem lt_sub_left_of_add_lt (h : k + m < n) : m < n - k := nat.lt_sub_right_of_add_lt (by rwa add_comm at h) protected theorem add_lt_of_lt_sub_right (h : m < n - k) : m + k < n := @nat.lt_of_sub_lt_sub_right _ _ k (by rwa nat.add_sub_cancel) protected theorem add_lt_of_lt_sub_left (h : m < n - k) : k + m < n := by rw add_comm; exact nat.add_lt_of_lt_sub_right h protected theorem le_add_of_sub_le_right : n - k ≤ m → n ≤ m + k := le_imp_le_of_lt_imp_lt nat.lt_sub_right_of_add_lt protected theorem le_add_of_sub_le_left : n - k ≤ m → n ≤ k + m := le_imp_le_of_lt_imp_lt nat.lt_sub_left_of_add_lt protected theorem lt_add_of_sub_lt_right : n - k < m → n < m + k := lt_imp_lt_of_le_imp_le nat.le_sub_right_of_add_le protected theorem lt_add_of_sub_lt_left : n - k < m → n < k + m := lt_imp_lt_of_le_imp_le nat.le_sub_left_of_add_le protected theorem sub_le_left_of_le_add : n ≤ k + m → n - k ≤ m := le_imp_le_of_lt_imp_lt nat.add_lt_of_lt_sub_left protected theorem sub_le_right_of_le_add : n ≤ m + k → n - k ≤ m := le_imp_le_of_lt_imp_lt nat.add_lt_of_lt_sub_right protected theorem sub_lt_left_iff_lt_add (H : n ≤ k) : k - n < m ↔ k < n + m := ⟨nat.lt_add_of_sub_lt_left, λ h₁, have succ k ≤ n + m, from succ_le_of_lt h₁, have succ (k - n) ≤ m, from calc succ (k - n) = succ k - n : by rw (succ_sub H) ... ≤ n + m - n : nat.sub_le_sub_right this n ... = m : by rw nat.add_sub_cancel_left, lt_of_succ_le this⟩ protected theorem le_sub_left_iff_add_le (H : m ≤ k) : n ≤ k - m ↔ m + n ≤ k := le_iff_le_iff_lt_iff_lt.2 (nat.sub_lt_left_iff_lt_add H) protected theorem le_sub_right_iff_add_le (H : n ≤ k) : m ≤ k - n ↔ m + n ≤ k := by rw [nat.le_sub_left_iff_add_le H, add_comm] protected theorem lt_sub_left_iff_add_lt : n < k - m ↔ m + n < k := ⟨nat.add_lt_of_lt_sub_left, nat.lt_sub_left_of_add_lt⟩ protected theorem lt_sub_right_iff_add_lt : m < k - n ↔ m + n < k := by rw [nat.lt_sub_left_iff_add_lt, add_comm] theorem sub_le_left_iff_le_add : m - n ≤ k ↔ m ≤ n + k := le_iff_le_iff_lt_iff_lt.2 nat.lt_sub_left_iff_add_lt theorem sub_le_right_iff_le_add : m - k ≤ n ↔ m ≤ n + k := by rw [nat.sub_le_left_iff_le_add, add_comm] protected theorem sub_lt_right_iff_lt_add (H : k ≤ m) : m - k < n ↔ m < n + k := by rw [nat.sub_lt_left_iff_lt_add H, add_comm] protected theorem sub_le_sub_left_iff (H : k ≤ m) : m - n ≤ m - k ↔ k ≤ n := ⟨λ h, have k + (m - k) - n ≤ m - k, by rwa nat.add_sub_cancel' H, nat.le_of_add_le_add_right (nat.le_add_of_sub_le_left this), nat.sub_le_sub_left _⟩ protected theorem sub_lt_sub_right_iff (H : k ≤ m) : m - k < n - k ↔ m < n := lt_iff_lt_of_le_iff_le (nat.sub_le_sub_right_iff _ _ _ H) protected theorem sub_lt_sub_left_iff (H : n ≤ m) : m - n < m - k ↔ k < n := lt_iff_lt_of_le_iff_le (nat.sub_le_sub_left_iff H) protected theorem sub_le_iff : m - n ≤ k ↔ m - k ≤ n := nat.sub_le_left_iff_le_add.trans nat.sub_le_right_iff_le_add.symm protected lemma sub_le_self (n m : ℕ) : n - m ≤ n := nat.sub_le_left_of_le_add (nat.le_add_left _ _) protected theorem sub_lt_iff (h₁ : n ≤ m) (h₂ : k ≤ m) : m - n < k ↔ m - k < n := (nat.sub_lt_left_iff_lt_add h₁).trans (nat.sub_lt_right_iff_lt_add h₂).symm lemma pred_le_iff {n m : ℕ} : pred n ≤ m ↔ n ≤ succ m := @nat.sub_le_right_iff_le_add n m 1 lemma lt_pred_iff {n m : ℕ} : n < pred m ↔ succ n < m := @nat.lt_sub_right_iff_add_lt n 1 m lemma lt_of_lt_pred {a b : ℕ} (h : a < b - 1) : a < b := lt_of_succ_lt (lt_pred_iff.1 h) protected theorem mul_ne_zero {n m : ℕ} (n0 : n ≠ 0) (m0 : m ≠ 0) : n * m ≠ 0 | nm := (eq_zero_of_mul_eq_zero nm).elim n0 m0 @[simp] protected theorem mul_eq_zero {a b : ℕ} : a * b = 0 ↔ a = 0 ∨ b = 0 := iff.intro eq_zero_of_mul_eq_zero (by simp [or_imp_distrib] {contextual := tt}) @[simp] protected theorem zero_eq_mul {a b : ℕ} : 0 = a * b ↔ a = 0 ∨ b = 0 := by rw [eq_comm, nat.mul_eq_zero] lemma eq_zero_of_double_le {a : ℕ} (h : 2 * a ≤ a) : a = 0 := nat.eq_zero_of_le_zero $ by rwa [two_mul, nat.add_le_to_le_sub, nat.sub_self] at h; refl lemma eq_zero_of_mul_le {a b : ℕ} (hb : 2 ≤ b) (h : b * a ≤ a) : a = 0 := eq_zero_of_double_le $ le_trans (nat.mul_le_mul_right _ hb) h lemma le_mul_of_pos_left {m n : ℕ} (h : 0 < n) : m ≤ n * m := begin conv {to_lhs, rw [← one_mul(m)]}, exact mul_le_mul_of_nonneg_right (nat.succ_le_of_lt h) dec_trivial, end lemma le_mul_of_pos_right {m n : ℕ} (h : 0 < n) : m ≤ m * n := begin conv {to_lhs, rw [← mul_one(m)]}, exact mul_le_mul_of_nonneg_left (nat.succ_le_of_lt h) dec_trivial, end theorem two_mul_ne_two_mul_add_one {n m} : 2 * n ≠ 2 * m + 1 := mt (congr_arg (%2)) (by rw [add_comm, add_mul_mod_self_left, mul_mod_right]; exact dec_trivial) /-- Recursion principle based on `<`. -/ @[elab_as_eliminator] protected def strong_rec' {p : ℕ → Sort u} (H : ∀ n, (∀ m, m < n → p m) → p n) : ∀ (n : ℕ), p n | n := H n (λ m hm, strong_rec' m) attribute [simp] nat.div_self protected lemma div_le_of_le_mul' {m n : ℕ} {k} (h : m ≤ k * n) : m / k ≤ n := (eq_zero_or_pos k).elim (λ k0, by rw [k0, nat.div_zero]; apply zero_le) (λ k0, (decidable.mul_le_mul_left k0).1 $ calc k * (m / k) ≤ m % k + k * (m / k) : le_add_left _ _ ... = m : mod_add_div _ _ ... ≤ k * n : h) protected lemma div_le_self' (m n : ℕ) : m / n ≤ m := (eq_zero_or_pos n).elim (λ n0, by rw [n0, nat.div_zero]; apply zero_le) (λ n0, nat.div_le_of_le_mul' $ calc m = 1 * m : (one_mul _).symm ... ≤ n * m : mul_le_mul_right _ n0) theorem le_div_iff_mul_le' {x y : ℕ} {k : ℕ} (k0 : 0 < k) : x ≤ y / k ↔ x * k ≤ y := begin revert x, refine nat.strong_rec' _ y, clear y, intros y IH x, cases decidable.lt_or_le y k with h h, { rw [div_eq_of_lt h], cases x with x, { simp [zero_mul, zero_le] }, { rw succ_mul, exact iff_of_false (not_succ_le_zero _) (not_le_of_lt $ lt_of_lt_of_le h (le_add_left _ _)) } }, { rw [div_eq_sub_div k0 h], cases x with x, { simp [zero_mul, zero_le] }, { rw [← add_one, nat.add_le_add_iff_le_right, succ_mul, IH _ (sub_lt_of_pos_le _ _ k0 h), add_le_to_le_sub _ h] } } end theorem div_mul_le_self' (m n : ℕ) : m / n * n ≤ m := (nat.eq_zero_or_pos n).elim (λ n0, by simp [n0, zero_le]) $ λ n0, (le_div_iff_mul_le' n0).1 (le_refl _) theorem div_lt_iff_lt_mul' {x y : ℕ} {k : ℕ} (k0 : 0 < k) : x / k < y ↔ x < y * k := lt_iff_lt_of_le_iff_le $ le_div_iff_mul_le' k0 protected theorem div_le_div_right {n m : ℕ} (h : n ≤ m) {k : ℕ} : n / k ≤ m / k := (nat.eq_zero_or_pos k).elim (λ k0, by simp [k0]) $ λ hk, (le_div_iff_mul_le' hk).2 $ le_trans (nat.div_mul_le_self' _ _) h lemma lt_of_div_lt_div {m n k : ℕ} (h : m / k < n / k) : m < n := by_contradiction $ λ h₁, absurd h (not_lt_of_ge (nat.div_le_div_right (not_lt.1 h₁))) protected theorem eq_mul_of_div_eq_right {a b c : ℕ} (H1 : b ∣ a) (H2 : a / b = c) : a = b * c := by rw [← H2, nat.mul_div_cancel' H1] protected theorem div_eq_iff_eq_mul_right {a b c : ℕ} (H : 0 < b) (H' : b ∣ a) : a / b = c ↔ a = b * c := ⟨nat.eq_mul_of_div_eq_right H', nat.div_eq_of_eq_mul_right H⟩ protected theorem div_eq_iff_eq_mul_left {a b c : ℕ} (H : 0 < b) (H' : b ∣ a) : a / b = c ↔ a = c * b := by rw mul_comm; exact nat.div_eq_iff_eq_mul_right H H' protected theorem eq_mul_of_div_eq_left {a b c : ℕ} (H1 : b ∣ a) (H2 : a / b = c) : a = c * b := by rw [mul_comm, nat.eq_mul_of_div_eq_right H1 H2] protected theorem mul_div_cancel_left' {a b : ℕ} (Hd : a ∣ b) : a * (b / a) = b := by rw [mul_comm,nat.div_mul_cancel Hd] protected theorem div_mod_unique {n k m d : ℕ} (h : 0 < k) : n / k = d ∧ n % k = m ↔ m + k * d = n ∧ m < k := ⟨λ ⟨e₁, e₂⟩, e₁ ▸ e₂ ▸ ⟨mod_add_div _ _, mod_lt _ h⟩, λ ⟨h₁, h₂⟩, h₁ ▸ by rw [add_mul_div_left _ _ h, add_mul_mod_self_left]; simp [div_eq_of_lt, mod_eq_of_lt, h₂]⟩ lemma two_mul_odd_div_two {n : ℕ} (hn : n % 2 = 1) : 2 * (n / 2) = n - 1 := by conv {to_rhs, rw [← nat.mod_add_div n 2, hn, nat.add_sub_cancel_left]} lemma div_dvd_of_dvd {a b : ℕ} (h : b ∣ a) : (a / b) ∣ a := ⟨b, (nat.div_mul_cancel h).symm⟩ protected lemma div_pos {a b : ℕ} (hba : b ≤ a) (hb : 0 < b) : 0 < a / b := nat.pos_of_ne_zero (λ h, lt_irrefl a (calc a = a % b : by simpa [h] using (mod_add_div a b).symm ... < b : nat.mod_lt a hb ... ≤ a : hba)) protected theorem mul_right_inj {a b c : ℕ} (ha : 0 < a) : b * a = c * a ↔ b = c := ⟨nat.eq_of_mul_eq_mul_right ha, λ e, e ▸ rfl⟩ protected theorem mul_left_inj {a b c : ℕ} (ha : 0 < a) : a * b = a * c ↔ b = c := ⟨nat.eq_of_mul_eq_mul_left ha, λ e, e ▸ rfl⟩ protected lemma div_div_self : ∀ {a b : ℕ}, b ∣ a → 0 < a → a / (a / b) = b | a 0 h₁ h₂ := by rw eq_zero_of_zero_dvd h₁; refl | 0 b h₁ h₂ := absurd h₂ dec_trivial | (a+1) (b+1) h₁ h₂ := (nat.mul_right_inj (nat.div_pos (le_of_dvd (succ_pos a) h₁) (succ_pos b))).1 $ by rw [nat.div_mul_cancel (div_dvd_of_dvd h₁), nat.mul_div_cancel' h₁] protected lemma div_lt_of_lt_mul {m n k : ℕ} (h : m < n * k) : m / n < k := lt_of_mul_lt_mul_left (calc n * (m / n) ≤ m % n + n * (m / n) : nat.le_add_left _ _ ... = m : mod_add_div _ _ ... < n * k : h) (nat.zero_le n) lemma lt_mul_of_div_lt {a b c : ℕ} (h : a / c < b) (w : 0 < c) : a < b * c := lt_of_not_ge $ not_le_of_gt h ∘ (nat.le_div_iff_mul_le _ _ w).2 protected lemma div_eq_zero_iff {a b : ℕ} (hb : 0 < b) : a / b = 0 ↔ a < b := ⟨λ h, by rw [← mod_add_div a b, h, mul_zero, add_zero]; exact mod_lt _ hb, λ h, by rw [← nat.mul_left_inj hb, ← @add_left_cancel_iff _ _ (a % b), mod_add_div, mod_eq_of_lt h, mul_zero, add_zero]⟩ lemma eq_zero_of_le_div {a b : ℕ} (hb : 2 ≤ b) (h : a ≤ a / b) : a = 0 := eq_zero_of_mul_le hb $ by rw mul_comm; exact (nat.le_div_iff_mul_le' (lt_of_lt_of_le dec_trivial hb)).1 h lemma mul_div_le_mul_div_assoc (a b c : ℕ) : a * (b / c) ≤ (a * b) / c := if hc0 : c = 0 then by simp [hc0] else (nat.le_div_iff_mul_le _ _ (nat.pos_of_ne_zero hc0)).2 (by rw [mul_assoc]; exact mul_le_mul_left _ (nat.div_mul_le_self _ _)) lemma div_mul_div_le_div (a b c : ℕ) : ((a / c) * b) / a ≤ b / c := if ha0 : a = 0 then by simp [ha0] else calc a / c * b / a ≤ b * a / c / a : nat.div_le_div_right (by rw [mul_comm]; exact mul_div_le_mul_div_assoc _ _ _) ... = b / c : by rw [nat.div_div_eq_div_mul, mul_comm b, mul_comm c, nat.mul_div_mul _ _ (nat.pos_of_ne_zero ha0)] lemma eq_zero_of_le_half {a : ℕ} (h : a ≤ a / 2) : a = 0 := eq_zero_of_le_div (le_refl _) h lemma mod_mul_right_div_self (a b c : ℕ) : a % (b * c) / b = (a / b) % c := if hb : b = 0 then by simp [hb] else if hc : c = 0 then by simp [hc] else by conv {to_rhs, rw ← mod_add_div a (b * c)}; rw [mul_assoc, nat.add_mul_div_left _ _ (nat.pos_of_ne_zero hb), add_mul_mod_self_left, mod_eq_of_lt (nat.div_lt_of_lt_mul (mod_lt _ (mul_pos (nat.pos_of_ne_zero hb) (nat.pos_of_ne_zero hc))))] lemma mod_mul_left_div_self (a b c : ℕ) : a % (c * b) / b = (a / b) % c := by rw [mul_comm c, mod_mul_right_div_self] /- The `n+1`-st triangle number is `n` more than the `n`-th triangle number -/ lemma triangle_succ (n : ℕ) : (n + 1) * ((n + 1) - 1) / 2 = n * (n - 1) / 2 + n := begin rw [← add_mul_div_left, mul_comm 2 n, ← mul_add, nat.add_sub_cancel, mul_comm], cases n; refl, apply zero_lt_succ end @[simp] protected theorem dvd_one {n : ℕ} : n ∣ 1 ↔ n = 1 := ⟨eq_one_of_dvd_one, λ e, e.symm ▸ dvd_refl _⟩ protected theorem dvd_add_left {k m n : ℕ} (h : k ∣ n) : k ∣ m + n ↔ k ∣ m := (nat.dvd_add_iff_left h).symm protected theorem dvd_add_right {k m n : ℕ} (h : k ∣ m) : k ∣ m + n ↔ k ∣ n := (nat.dvd_add_iff_right h).symm /-- A natural number m divides the sum m + n if and only if m divides b.-/ @[simp] protected lemma dvd_add_self_left {m n : ℕ} : m ∣ m + n ↔ m ∣ n := nat.dvd_add_right (dvd_refl m) /-- A natural number m divides the sum n + m if and only if m divides b.-/ @[simp] protected lemma dvd_add_self_right {m n : ℕ} : m ∣ n + m ↔ m ∣ n := nat.dvd_add_left (dvd_refl m) protected theorem mul_dvd_mul_iff_left {a b c : ℕ} (ha : 0 < a) : a * b ∣ a * c ↔ b ∣ c := exists_congr $ λ d, by rw [mul_assoc, nat.mul_left_inj ha] protected theorem mul_dvd_mul_iff_right {a b c : ℕ} (hc : 0 < c) : a * c ∣ b * c ↔ a ∣ b := exists_congr $ λ d, by rw [mul_right_comm, nat.mul_right_inj hc] lemma succ_div : ∀ (a b : ℕ), (a + 1) / b = a / b + if b ∣ a + 1 then 1 else 0 | a 0 := by simp | 0 1 := rfl | 0 (b+2) := have hb2 : b + 2 > 1, from dec_trivial, by simp [ne_of_gt hb2, div_eq_of_lt hb2] | (a+1) (b+1) := begin rw [nat.div_def], conv_rhs { rw nat.div_def }, by_cases hb_eq_a : b = a + 1, { simp [hb_eq_a, le_refl] }, by_cases hb_le_a1 : b ≤ a + 1, { have hb_le_a : b ≤ a, from le_of_lt_succ (lt_of_le_of_ne hb_le_a1 hb_eq_a), have h₁ : (0 < b + 1 ∧ b + 1 ≤ a + 1 + 1), from ⟨succ_pos _, (add_le_add_iff_right _).2 hb_le_a1⟩, have h₂ : (0 < b + 1 ∧ b + 1 ≤ a + 1), from ⟨succ_pos _, (add_le_add_iff_right _).2 hb_le_a⟩, have dvd_iff : b + 1 ∣ a - b + 1 ↔ b + 1 ∣ a + 1 + 1, { rw [nat.dvd_add_iff_left (dvd_refl (b + 1)), ← nat.add_sub_add_right a 1 b, add_comm (_ - _), add_assoc, nat.sub_add_cancel (succ_le_succ hb_le_a), add_comm 1] }, have wf : a - b < a + 1, from lt_succ_of_le (nat.sub_le_self _ _), rw [if_pos h₁, if_pos h₂, nat.add_sub_add_right, nat.sub_add_comm hb_le_a, by exact have _ := wf, succ_div (a - b), nat.add_sub_add_right], simp [dvd_iff, succ_eq_add_one, add_comm 1] }, { have hba : ¬ b ≤ a, from not_le_of_gt (lt_trans (lt_succ_self a) (lt_of_not_ge hb_le_a1)), have hb_dvd_a : ¬ b + 1 ∣ a + 2, from λ h, hb_le_a1 (le_of_succ_le_succ (le_of_dvd (succ_pos _) h)), simp [hba, hb_le_a1, hb_dvd_a], } end lemma succ_div_of_dvd {a b : ℕ} (hba : b ∣ a + 1) : (a + 1) / b = a / b + 1 := by rw [succ_div, if_pos hba] lemma succ_div_of_not_dvd {a b : ℕ} (hba : ¬ b ∣ a + 1) : (a + 1) / b = a / b := by rw [succ_div, if_neg hba, add_zero] @[simp] theorem mod_mod_of_dvd (n : nat) {m k : nat} (h : m ∣ k) : n % k % m = n % m := begin conv { to_rhs, rw ←mod_add_div n k }, rcases h with ⟨t, rfl⟩, rw [mul_assoc, add_mul_mod_self_left] end @[simp] theorem mod_mod (a n : ℕ) : (a % n) % n = a % n := (eq_zero_or_pos n).elim (λ n0, by simp [n0]) (λ npos, mod_eq_of_lt (mod_lt _ npos)) theorem add_pos_left {m : ℕ} (h : 0 < m) (n : ℕ) : 0 < m + n := calc m + n > 0 + n : nat.add_lt_add_right h n ... = n : nat.zero_add n ... ≥ 0 : zero_le n theorem add_pos_right (m : ℕ) {n : ℕ} (h : 0 < n) : 0 < m + n := begin rw add_comm, exact add_pos_left h m end theorem add_pos_iff_pos_or_pos (m n : ℕ) : 0 < m + n ↔ 0 < m ∨ 0 < n := iff.intro begin intro h, cases m with m, {simp [zero_add] at h, exact or.inr h}, exact or.inl (succ_pos _) end begin intro h, cases h with mpos npos, { apply add_pos_left mpos }, apply add_pos_right _ npos end lemma add_eq_one_iff : ∀ {a b : ℕ}, a + b = 1 ↔ (a = 0 ∧ b = 1) ∨ (a = 1 ∧ b = 0) | 0 0 := dec_trivial | 0 1 := dec_trivial | 1 0 := dec_trivial | 1 1 := dec_trivial | (a+2) _ := by rw add_right_comm; exact dec_trivial | _ (b+2) := by rw [← add_assoc]; simp only [nat.succ_inj', nat.succ_ne_zero]; simp lemma mul_eq_one_iff : ∀ {a b : ℕ}, a * b = 1 ↔ a = 1 ∧ b = 1 | 0 0 := dec_trivial | 0 1 := dec_trivial | 1 0 := dec_trivial | (a+2) 0 := by simp | 0 (b+2) := by simp | (a+1) (b+1) := ⟨λ h, by simp only [add_mul, mul_add, mul_add, one_mul, mul_one, (add_assoc _ _ _).symm, nat.succ_inj', add_eq_zero_iff] at h; simp [h.1.2, h.2], by clear_aux_decl; finish⟩ lemma mul_right_eq_self_iff {a b : ℕ} (ha : 0 < a) : a * b = a ↔ b = 1 := suffices a * b = a * 1 ↔ b = 1, by rwa mul_one at this, nat.mul_left_inj ha lemma mul_left_eq_self_iff {a b : ℕ} (hb : 0 < b) : a * b = b ↔ a = 1 := by rw [mul_comm, nat.mul_right_eq_self_iff hb] lemma lt_succ_iff_lt_or_eq {n i : ℕ} : n < i.succ ↔ (n < i ∨ n = i) := lt_succ_iff.trans le_iff_lt_or_eq theorem le_zero_iff {i : ℕ} : i ≤ 0 ↔ i = 0 := ⟨nat.eq_zero_of_le_zero, assume h, h ▸ le_refl i⟩ theorem le_add_one_iff {i j : ℕ} : i ≤ j + 1 ↔ (i ≤ j ∨ i = j + 1) := ⟨assume h, match nat.eq_or_lt_of_le h with | or.inl h := or.inr h | or.inr h := or.inl $ nat.le_of_succ_le_succ h end, or.rec (assume h, le_trans h $ nat.le_add_right _ _) le_of_eq⟩ theorem mul_self_inj {n m : ℕ} : n * n = m * m ↔ n = m := le_antisymm_iff.trans (le_antisymm_iff.trans (and_congr mul_self_le_mul_self_iff mul_self_le_mul_self_iff)).symm instance decidable_ball_lt (n : nat) (P : Π k < n, Prop) : ∀ [H : ∀ n h, decidable (P n h)], decidable (∀ n h, P n h) := begin induction n with n IH; intro; resetI, { exact is_true (λ n, dec_trivial) }, cases IH (λ k h, P k (lt_succ_of_lt h)) with h, { refine is_false (mt _ h), intros hn k h, apply hn }, by_cases p : P n (lt_succ_self n), { exact is_true (λ k h', (lt_or_eq_of_le $ le_of_lt_succ h').elim (h _) (λ e, match k, e, h' with _, rfl, h := p end)) }, { exact is_false (mt (λ hn, hn _ _) p) } end instance decidable_forall_fin {n : ℕ} (P : fin n → Prop) [H : decidable_pred P] : decidable (∀ i, P i) := decidable_of_iff (∀ k h, P ⟨k, h⟩) ⟨λ a ⟨k, h⟩, a k h, λ a k h, a ⟨k, h⟩⟩ instance decidable_ball_le (n : ℕ) (P : Π k ≤ n, Prop) [H : ∀ n h, decidable (P n h)] : decidable (∀ n h, P n h) := decidable_of_iff (∀ k (h : k < succ n), P k (le_of_lt_succ h)) ⟨λ a k h, a k (lt_succ_of_le h), λ a k h, a k _⟩ instance decidable_lo_hi (lo hi : ℕ) (P : ℕ → Prop) [H : decidable_pred P] : decidable (∀x, lo ≤ x → x < hi → P x) := decidable_of_iff (∀ x < hi - lo, P (lo + x)) ⟨λal x hl hh, by have := al (x - lo) (lt_of_not_ge $ (not_congr (nat.sub_le_sub_right_iff _ _ _ hl)).2 $ not_le_of_gt hh); rwa [nat.add_sub_of_le hl] at this, λal x h, al _ (nat.le_add_right _ _) (nat.add_lt_of_lt_sub_left h)⟩ instance decidable_lo_hi_le (lo hi : ℕ) (P : ℕ → Prop) [H : decidable_pred P] : decidable (∀x, lo ≤ x → x ≤ hi → P x) := decidable_of_iff (∀x, lo ≤ x → x < hi + 1 → P x) $ ball_congr $ λ x hl, imp_congr lt_succ_iff iff.rfl protected theorem bit0_le {n m : ℕ} (h : n ≤ m) : bit0 n ≤ bit0 m := add_le_add h h protected theorem bit1_le {n m : ℕ} (h : n ≤ m) : bit1 n ≤ bit1 m := succ_le_succ (add_le_add h h) theorem bit_le : ∀ (b : bool) {n m : ℕ}, n ≤ m → bit b n ≤ bit b m | tt n m h := nat.bit1_le h | ff n m h := nat.bit0_le h theorem bit_ne_zero (b) {n} (h : n ≠ 0) : bit b n ≠ 0 := by cases b; [exact nat.bit0_ne_zero h, exact nat.bit1_ne_zero _] theorem bit0_le_bit : ∀ (b) {m n : ℕ}, m ≤ n → bit0 m ≤ bit b n | tt m n h := le_of_lt $ nat.bit0_lt_bit1 h | ff m n h := nat.bit0_le h theorem bit_le_bit1 : ∀ (b) {m n : ℕ}, m ≤ n → bit b m ≤ bit1 n | ff m n h := le_of_lt $ nat.bit0_lt_bit1 h | tt m n h := nat.bit1_le h theorem bit_lt_bit0 : ∀ (b) {n m : ℕ}, n < m → bit b n < bit0 m | tt n m h := nat.bit1_lt_bit0 h | ff n m h := nat.bit0_lt h theorem bit_lt_bit (a b) {n m : ℕ} (h : n < m) : bit a n < bit b m := lt_of_lt_of_le (bit_lt_bit0 _ h) (bit0_le_bit _ (le_refl _)) @[simp] lemma bit0_le_bit1_iff : bit0 k ≤ bit1 n ↔ k ≤ n := ⟨λ h, by rwa [← nat.lt_succ_iff, n.bit1_eq_succ_bit0, ← n.bit0_succ_eq, bit0_lt_bit0, nat.lt_succ_iff] at h, λ h, le_of_lt (nat.bit0_lt_bit1 h)⟩ @[simp] lemma bit0_lt_bit1_iff : bit0 k < bit1 n ↔ k ≤ n := ⟨λ h, bit0_le_bit1_iff.1 (le_of_lt h), nat.bit0_lt_bit1⟩ @[simp] lemma bit1_le_bit0_iff : bit1 k ≤ bit0 n ↔ k < n := ⟨λ h, by rwa [k.bit1_eq_succ_bit0, succ_le_iff, bit0_lt_bit0] at h, λ h, le_of_lt (nat.bit1_lt_bit0 h)⟩ @[simp] lemma bit1_lt_bit0_iff : bit1 k < bit0 n ↔ k < n := ⟨λ h, bit1_le_bit0_iff.1 (le_of_lt h), nat.bit1_lt_bit0⟩ @[simp] lemma one_le_bit0_iff : 1 ≤ bit0 n ↔ 0 < n := by { convert bit1_le_bit0_iff, refl, } @[simp] lemma one_lt_bit0_iff : 1 < bit0 n ↔ 1 ≤ n := by { convert bit1_lt_bit0_iff, refl, } @[simp] lemma bit_le_bit_iff : ∀ {b : bool}, bit b k ≤ bit b n ↔ k ≤ n | ff := bit0_le_bit0 | tt := bit1_le_bit1 @[simp] lemma bit_lt_bit_iff : ∀ {b : bool}, bit b k < bit b n ↔ k < n | ff := bit0_lt_bit0 | tt := bit1_lt_bit1 @[simp] lemma bit_le_bit1_iff : ∀ {b : bool}, bit b k ≤ bit1 n ↔ k ≤ n | ff := bit0_le_bit1_iff | tt := bit1_le_bit1 lemma pos_of_bit0_pos {n : ℕ} (h : 0 < bit0 n) : 0 < n := by { cases n, cases h, apply succ_pos, } /-- Define a function on `ℕ` depending on parity of the argument. -/ @[elab_as_eliminator] def bit_cases {C : ℕ → Sort u} (H : Π b n, C (bit b n)) (n : ℕ) : C n := eq.rec_on n.bit_decomp (H (bodd n) (div2 n)) /- partial subtraction -/ /-- Partial predecessor operation. Returns `ppred n = some m` if `n = m + 1`, otherwise `none`. -/ @[simp] def ppred : ℕ → option ℕ | 0 := none | (n+1) := some n /-- Partial subtraction operation. Returns `psub m n = some k` if `m = n + k`, otherwise `none`. -/ @[simp] def psub (m : ℕ) : ℕ → option ℕ | 0 := some m | (n+1) := psub n >>= ppred theorem pred_eq_ppred (n : ℕ) : pred n = (ppred n).get_or_else 0 := by cases n; refl theorem sub_eq_psub (m : ℕ) : ∀ n, m - n = (psub m n).get_or_else 0 | 0 := rfl | (n+1) := (pred_eq_ppred (m-n)).trans $ by rw [sub_eq_psub, psub]; cases psub m n; refl @[simp] theorem ppred_eq_some {m : ℕ} : ∀ {n}, ppred n = some m ↔ succ m = n | 0 := by split; intro h; contradiction | (n+1) := by dsimp; split; intro h; injection h; subst n @[simp] theorem ppred_eq_none : ∀ {n : ℕ}, ppred n = none ↔ n = 0 | 0 := by simp | (n+1) := by dsimp; split; contradiction theorem psub_eq_some {m : ℕ} : ∀ {n k}, psub m n = some k ↔ k + n = m | 0 k := by simp [eq_comm] | (n+1) k := begin dsimp, apply option.bind_eq_some.trans, simp [psub_eq_some, add_comm, add_left_comm, nat.succ_eq_add_one] end theorem psub_eq_none (m n : ℕ) : psub m n = none ↔ m < n := begin cases s : psub m n; simp [eq_comm], { show m < n, refine lt_of_not_ge (λ h, _), cases le.dest h with k e, injection s.symm.trans (psub_eq_some.2 $ (add_comm _ _).trans e) }, { show n ≤ m, rw ← psub_eq_some.1 s, apply le_add_left } end theorem ppred_eq_pred {n} (h : 0 < n) : ppred n = some (pred n) := ppred_eq_some.2 $ succ_pred_eq_of_pos h theorem psub_eq_sub {m n} (h : n ≤ m) : psub m n = some (m - n) := psub_eq_some.2 $ nat.sub_add_cancel h theorem psub_add (m n k) : psub m (n + k) = do x ← psub m n, psub x k := by induction k; simp [*, add_succ, bind_assoc] /- pow -/ attribute [simp] nat.pow_zero nat.pow_one @[simp] lemma one_pow : ∀ n : ℕ, 1 ^ n = 1 | 0 := rfl | (k+1) := show 1^k * 1 = 1, by rw [mul_one, one_pow] theorem pow_add (a m n : ℕ) : a^(m + n) = a^m * a^n := by induction n; simp [*, pow_succ, mul_assoc] theorem pow_two (a : ℕ) : a ^ 2 = a * a := show (1 * a) * a = _, by rw one_mul theorem pow_dvd_pow (a : ℕ) {m n : ℕ} (h : m ≤ n) : a^m ∣ a^n := by rw [← nat.add_sub_cancel' h, pow_add]; apply dvd_mul_right theorem pow_dvd_pow_of_dvd {a b : ℕ} (h : a ∣ b) : ∀ n:ℕ, a^n ∣ b^n | 0 := dvd_refl _ | (n+1) := mul_dvd_mul (pow_dvd_pow_of_dvd n) h theorem mul_pow (a b n : ℕ) : (a * b) ^ n = a ^ n * b ^ n := by induction n; simp [*, nat.pow_succ, mul_comm, mul_assoc, mul_left_comm] protected theorem pow_mul (a b n : ℕ) : n ^ (a * b) = (n ^ a) ^ b := by induction b; simp [*, nat.succ_eq_add_one, nat.pow_add, mul_add, mul_comm] theorem pow_pos {p : ℕ} (hp : 0 < p) : ∀ n : ℕ, 0 < p ^ n | 0 := by simp | (k+1) := mul_pos (pow_pos _) hp lemma pow_eq_mul_pow_sub (p : ℕ) {m n : ℕ} (h : m ≤ n) : p ^ m * p ^ (n - m) = p ^ n := by rw [←nat.pow_add, nat.add_sub_cancel' h] lemma pow_lt_pow_succ {p : ℕ} (h : 1 < p) (n : ℕ) : p^n < p^(n+1) := suffices p^n*1 < p^n*p, by simpa, nat.mul_lt_mul_of_pos_left h (nat.pow_pos (lt_of_succ_lt h) n) lemma lt_pow_self {p : ℕ} (h : 1 < p) : ∀ n : ℕ, n < p ^ n | 0 := by simp [zero_lt_one] | (n+1) := calc n + 1 < p^n + 1 : nat.add_lt_add_right (lt_pow_self _) _ ... ≤ p ^ (n+1) : pow_lt_pow_succ h _ lemma pow_right_strict_mono {x : ℕ} (k : 2 ≤ x) : strict_mono (nat.pow x) := λ _ _, pow_lt_pow_of_lt_right k lemma pow_le_iff_le_right {x m n : ℕ} (k : 2 ≤ x) : x^m ≤ x^n ↔ m ≤ n := strict_mono.le_iff_le (pow_right_strict_mono k) lemma pow_lt_iff_lt_right {x m n : ℕ} (k : 2 ≤ x) : x^m < x^n ↔ m < n := strict_mono.lt_iff_lt (pow_right_strict_mono k) lemma pow_right_injective {x : ℕ} (k : 2 ≤ x) : function.injective (nat.pow x) := strict_mono.injective (pow_right_strict_mono k) lemma pow_left_strict_mono {m : ℕ} (k : 1 ≤ m) : strict_mono (λ (x : ℕ), x^m) := λ _ _ h, pow_lt_pow_of_lt_left h k lemma pow_le_iff_le_left {m x y : ℕ} (k : 1 ≤ m) : x^m ≤ y^m ↔ x ≤ y := strict_mono.le_iff_le (pow_left_strict_mono k) lemma pow_lt_iff_lt_left {m x y : ℕ} (k : 1 ≤ m) : x^m < y^m ↔ x < y := strict_mono.lt_iff_lt (pow_left_strict_mono k) lemma pow_left_injective {m : ℕ} (k : 1 ≤ m) : function.injective (λ (x : ℕ), x^m) := strict_mono.injective (pow_left_strict_mono k) lemma not_pos_pow_dvd : ∀ {p k : ℕ} (hp : 1 < p) (hk : 1 < k), ¬ p^k ∣ p | (succ p) (succ k) hp hk h := have (succ p)^k * succ p ∣ 1 * succ p, by simpa, have (succ p) ^ k ∣ 1, from dvd_of_mul_dvd_mul_right (succ_pos _) this, have he : (succ p) ^ k = 1, from eq_one_of_dvd_one this, have k < (succ p) ^ k, from lt_pow_self hp k, have k < 1, by rwa [he] at this, have k = 0, from eq_zero_of_le_zero $ le_of_lt_succ this, have 1 < 1, by rwa [this] at hk, absurd this dec_trivial @[simp] theorem bodd_div2_eq (n : ℕ) : bodd_div2 n = (bodd n, div2 n) := by unfold bodd div2; cases bodd_div2 n; refl @[simp] lemma bodd_bit0 (n) : bodd (bit0 n) = ff := bodd_bit ff n @[simp] lemma bodd_bit1 (n) : bodd (bit1 n) = tt := bodd_bit tt n @[simp] lemma div2_bit0 (n) : div2 (bit0 n) = n := div2_bit ff n @[simp] lemma div2_bit1 (n) : div2 (bit1 n) = n := div2_bit tt n /- iterate -/ section variables {α : Sort*} (op : α → α) @[simp] theorem iterate_zero (a : α) : op^[0] a = a := rfl @[simp] theorem iterate_succ (n : ℕ) (a : α) : op^[succ n] a = (op^[n]) (op a) := rfl theorem iterate_add : ∀ (m n : ℕ) (a : α), op^[m + n] a = (op^[m]) (op^[n] a) | m 0 a := rfl | m (succ n) a := iterate_add m n _ theorem iterate_succ' (n : ℕ) (a : α) : op^[succ n] a = op (op^[n] a) := by rw [← one_add, iterate_add]; refl theorem iterate₀ {α : Type u} {op : α → α} {x : α} (H : op x = x) {n : ℕ} : op^[n] x = x := by induction n; [simp only [iterate_zero], simp only [iterate_succ', H, *]] theorem iterate₁ {α : Type u} {β : Type v} {op : α → α} {op' : β → β} {op'' : α → β} (H : ∀ x, op' (op'' x) = op'' (op x)) {n : ℕ} {x : α} : op'^[n] (op'' x) = op'' (op^[n] x) := by induction n; [simp only [iterate_zero], simp only [iterate_succ', H, *]] theorem iterate₂ {α : Type u} {op : α → α} {op' : α → α → α} (H : ∀ x y, op (op' x y) = op' (op x) (op y)) {n : ℕ} {x y : α} : op^[n] (op' x y) = op' (op^[n] x) (op^[n] y) := by induction n; [simp only [iterate_zero], simp only [iterate_succ', H, *]] theorem iterate_cancel {α : Type u} {op op' : α → α} (H : ∀ x, op (op' x) = x) {n : ℕ} {x : α} : op^[n] (op'^[n] x) = x := by induction n; [refl, rwa [iterate_succ, iterate_succ', H]] theorem iterate_inj {α : Type u} {op : α → α} (Hinj : function.injective op) (n : ℕ) (x y : α) (H : (op^[n] x) = (op^[n] y)) : x = y := by induction n with n ih; simp only [iterate_zero, iterate_succ'] at H; [exact H, exact ih (Hinj H)] end /- size and shift -/ theorem shiftl'_ne_zero_left (b) {m} (h : m ≠ 0) (n) : shiftl' b m n ≠ 0 := by induction n; simp [shiftl', bit_ne_zero, *] theorem shiftl'_tt_ne_zero (m) : ∀ {n} (h : n ≠ 0), shiftl' tt m n ≠ 0 | 0 h := absurd rfl h | (succ n) _ := nat.bit1_ne_zero _ @[simp] theorem size_zero : size 0 = 0 := rfl @[simp] theorem size_bit {b n} (h : bit b n ≠ 0) : size (bit b n) = succ (size n) := begin rw size, conv { to_lhs, rw [binary_rec], simp [h] }, rw div2_bit, end @[simp] theorem size_bit0 {n} (h : n ≠ 0) : size (bit0 n) = succ (size n) := @size_bit ff n (nat.bit0_ne_zero h) @[simp] theorem size_bit1 (n) : size (bit1 n) = succ (size n) := @size_bit tt n (nat.bit1_ne_zero n) @[simp] theorem size_one : size 1 = 1 := by apply size_bit1 0 @[simp] theorem size_shiftl' {b m n} (h : shiftl' b m n ≠ 0) : size (shiftl' b m n) = size m + n := begin induction n with n IH; simp [shiftl'] at h ⊢, rw [size_bit h, nat.add_succ], by_cases s0 : shiftl' b m n = 0; [skip, rw [IH s0]], rw s0 at h ⊢, cases b, {exact absurd rfl h}, have : shiftl' tt m n + 1 = 1 := congr_arg (+1) s0, rw [shiftl'_tt_eq_mul_pow] at this, have m0 := succ_inj (eq_one_of_dvd_one ⟨_, this.symm⟩), subst m0, simp at this, have : n = 0 := eq_zero_of_le_zero (le_of_not_gt $ λ hn, ne_of_gt (pow_lt_pow_of_lt_right dec_trivial hn) this), subst n, refl end @[simp] theorem size_shiftl {m} (h : m ≠ 0) (n) : size (shiftl m n) = size m + n := size_shiftl' (shiftl'_ne_zero_left _ h _) theorem lt_size_self (n : ℕ) : n < 2^size n := begin rw [← one_shiftl], have : ∀ {n}, n = 0 → n < shiftl 1 (size n) := λ n e, by subst e; exact dec_trivial, apply binary_rec _ _ n, {apply this rfl}, intros b n IH, by_cases bit b n = 0, {apply this h}, rw [size_bit h, shiftl_succ], exact bit_lt_bit0 _ IH end theorem size_le {m n : ℕ} : size m ≤ n ↔ m < 2^n := ⟨λ h, lt_of_lt_of_le (lt_size_self _) (pow_le_pow_of_le_right dec_trivial h), begin rw [← one_shiftl], revert n, apply binary_rec _ _ m, { intros n h, apply zero_le }, { intros b m IH n h, by_cases e : bit b m = 0, { rw e, apply zero_le }, rw [size_bit e], cases n with n, { exact e.elim (eq_zero_of_le_zero (le_of_lt_succ h)) }, { apply succ_le_succ (IH _), apply lt_imp_lt_of_le_imp_le (λ h', bit0_le_bit _ h') h } } end⟩ theorem lt_size {m n : ℕ} : m < size n ↔ 2^m ≤ n := by rw [← not_lt, iff_not_comm, not_lt, size_le] theorem size_pos {n : ℕ} : 0 < size n ↔ 0 < n := by rw lt_size; refl theorem size_eq_zero {n : ℕ} : size n = 0 ↔ n = 0 := by have := @size_pos n; simp [pos_iff_ne_zero] at this; exact not_iff_not.1 this theorem size_pow {n : ℕ} : size (2^n) = n+1 := le_antisymm (size_le.2 $ pow_lt_pow_of_lt_right dec_trivial (lt_succ_self _)) (lt_size.2 $ le_refl _) theorem size_le_size {m n : ℕ} (h : m ≤ n) : size m ≤ size n := size_le.2 $ lt_of_le_of_lt h (lt_size_self _) /- factorial -/ /-- `fact n` is the factorial of `n`. -/ @[simp] def fact : nat → nat | 0 := 1 | (succ n) := succ n * fact n @[simp] theorem fact_zero : fact 0 = 1 := rfl @[simp] theorem fact_succ (n) : fact (succ n) = succ n * fact n := rfl @[simp] theorem fact_one : fact 1 = 1 := rfl theorem fact_pos : ∀ n, 0 < fact n | 0 := zero_lt_one | (succ n) := mul_pos (succ_pos _) (fact_pos n) theorem fact_ne_zero (n : ℕ) : fact n ≠ 0 := ne_of_gt (fact_pos _) theorem fact_dvd_fact {m n} (h : m ≤ n) : fact m ∣ fact n := begin induction n with n IH; simp, { have := eq_zero_of_le_zero h, subst m, simp }, { cases eq_or_lt_of_le h with he hl, { subst m, simp }, { apply dvd_mul_of_dvd_right (IH (le_of_lt_succ hl)) } } end theorem dvd_fact : ∀ {m n}, 0 < m → m ≤ n → m ∣ fact n | (succ m) n _ h := dvd_of_mul_right_dvd (fact_dvd_fact h) theorem fact_le {m n} (h : m ≤ n) : fact m ≤ fact n := le_of_dvd (fact_pos _) (fact_dvd_fact h) lemma fact_mul_pow_le_fact : ∀ {m n : ℕ}, m.fact * m.succ ^ n ≤ (m + n).fact | m 0 := by simp | m (n+1) := by rw [← add_assoc, nat.fact_succ, mul_comm (nat.succ _), nat.pow_succ, ← mul_assoc]; exact mul_le_mul fact_mul_pow_le_fact (nat.succ_le_succ (nat.le_add_right _ _)) (nat.zero_le _) (nat.zero_le _) lemma monotone_fact : monotone fact := λ n m, fact_le lemma fact_lt (h0 : 0 < n) : n.fact < m.fact ↔ n < m := begin split; intro h, { rw [← not_le], intro hmn, apply not_le_of_lt h (fact_le hmn) }, { have : ∀(n : ℕ), 0 < n → n.fact < n.succ.fact, { intros k hk, rw [fact_succ, succ_mul, lt_add_iff_pos_left], apply mul_pos hk (fact_pos k) }, induction h generalizing h0, { exact this _ h0, }, { refine lt_trans (h_ih h0) (this _ _), exact lt_trans h0 (lt_of_succ_le h_a) }} end lemma one_lt_fact : 1 < n.fact ↔ 1 < n := by { convert fact_lt _, refl, exact one_pos } lemma fact_eq_one : n.fact = 1 ↔ n ≤ 1 := begin split; intro h, { rw [← not_lt, ← one_lt_fact, h], apply lt_irrefl }, { cases h with h h, refl, cases h, refl } end lemma fact_inj (h0 : 1 < n.fact) : n.fact = m.fact ↔ n = m := begin split; intro h, { rcases lt_trichotomy n m with hnm|hnm|hnm, { exfalso, rw [← fact_lt, h] at hnm, exact lt_irrefl _ hnm, rw [one_lt_fact] at h0, exact lt_trans one_pos h0 }, { exact hnm }, { exfalso, rw [← fact_lt, h] at hnm, exact lt_irrefl _ hnm, rw [h, one_lt_fact] at h0, exact lt_trans one_pos h0 }}, { rw h } end /- choose -/ /-- `choose n k` is the number of `k`-element subsets in an `n`-element set. Also known as binomial coefficients. -/ def choose : ℕ → ℕ → ℕ | _ 0 := 1 | 0 (k + 1) := 0 | (n + 1) (k + 1) := choose n k + choose n (k + 1) @[simp] lemma choose_zero_right (n : ℕ) : choose n 0 = 1 := by cases n; refl @[simp] lemma choose_zero_succ (k : ℕ) : choose 0 (succ k) = 0 := rfl lemma choose_succ_succ (n k : ℕ) : choose (succ n) (succ k) = choose n k + choose n (succ k) := rfl lemma choose_eq_zero_of_lt : ∀ {n k}, n < k → choose n k = 0 | _ 0 hk := absurd hk dec_trivial | 0 (k + 1) hk := choose_zero_succ _ | (n + 1) (k + 1) hk := have hnk : n < k, from lt_of_succ_lt_succ hk, have hnk1 : n < k + 1, from lt_of_succ_lt hk, by rw [choose_succ_succ, choose_eq_zero_of_lt hnk, choose_eq_zero_of_lt hnk1] @[simp] lemma choose_self (n : ℕ) : choose n n = 1 := by induction n; simp [*, choose, choose_eq_zero_of_lt (lt_succ_self _)] @[simp] lemma choose_succ_self (n : ℕ) : choose n (succ n) = 0 := choose_eq_zero_of_lt (lt_succ_self _) @[simp] lemma choose_one_right (n : ℕ) : choose n 1 = n := by induction n; simp [*, choose, add_comm] /-- `choose n 2` is the `n`-th triangle number. -/ lemma choose_two_right (n : ℕ) : choose n 2 = n * (n - 1) / 2 := begin induction n with n ih, simp, {rw triangle_succ n, simp [choose, ih], rw add_comm}, end lemma choose_pos : ∀ {n k}, k ≤ n → 0 < choose n k | 0 _ hk := by rw [eq_zero_of_le_zero hk]; exact dec_trivial | (n + 1) 0 hk := by simp; exact dec_trivial | (n + 1) (k + 1) hk := by rw choose_succ_succ; exact add_pos_of_pos_of_nonneg (choose_pos (le_of_succ_le_succ hk)) (nat.zero_le _) lemma succ_mul_choose_eq : ∀ n k, succ n * choose n k = choose (succ n) (succ k) * succ k | 0 0 := dec_trivial | 0 (k + 1) := by simp [choose] | (n + 1) 0 := by simp | (n + 1) (k + 1) := by rw [choose_succ_succ (succ n) (succ k), add_mul, ←succ_mul_choose_eq, mul_succ, ←succ_mul_choose_eq, add_right_comm, ←mul_add, ←choose_succ_succ, ←succ_mul] lemma choose_mul_fact_mul_fact : ∀ {n k}, k ≤ n → choose n k * fact k * fact (n - k) = fact n | 0 _ hk := by simp [eq_zero_of_le_zero hk] | (n + 1) 0 hk := by simp | (n + 1) (succ k) hk := begin cases lt_or_eq_of_le hk with hk₁ hk₁, { have h : choose n k * fact (succ k) * fact (n - k) = succ k * fact n := by rw ← choose_mul_fact_mul_fact (le_of_succ_le_succ hk); simp [fact_succ, mul_comm, mul_left_comm], have h₁ : fact (n - k) = (n - k) * fact (n - succ k) := by rw [← succ_sub_succ, succ_sub (le_of_lt_succ hk₁), fact_succ], have h₂ : choose n (succ k) * fact (succ k) * ((n - k) * fact (n - succ k)) = (n - k) * fact n := by rw ← choose_mul_fact_mul_fact (le_of_lt_succ hk₁); simp [fact_succ, mul_comm, mul_left_comm, mul_assoc], have h₃ : k * fact n ≤ n * fact n := mul_le_mul_right _ (le_of_succ_le_succ hk), rw [choose_succ_succ, add_mul, add_mul, succ_sub_succ, h, h₁, h₂, ← add_one, add_mul, nat.mul_sub_right_distrib, fact_succ, ← nat.add_sub_assoc h₃, add_assoc, ← add_mul, nat.add_sub_cancel_left, add_comm] }, { simp [hk₁, mul_comm, choose, nat.sub_self] } end theorem choose_eq_fact_div_fact {n k : ℕ} (hk : k ≤ n) : choose n k = fact n / (fact k * fact (n - k)) := begin have : fact n = choose n k * (fact k * fact (n - k)) := by rw ← mul_assoc; exact (choose_mul_fact_mul_fact hk).symm, exact (nat.div_eq_of_eq_mul_left (mul_pos (fact_pos _) (fact_pos _)) this).symm end theorem fact_mul_fact_dvd_fact {n k : ℕ} (hk : k ≤ n) : fact k * fact (n - k) ∣ fact n := by rw [←choose_mul_fact_mul_fact hk, mul_assoc]; exact dvd_mul_left _ _ @[simp] lemma choose_symm {n k : ℕ} (hk : k ≤ n) : choose n (n-k) = choose n k := by rw [choose_eq_fact_div_fact hk, choose_eq_fact_div_fact (sub_le _ _), nat.sub_sub_self hk, mul_comm] lemma choose_symm_of_eq_add {n a b : ℕ} (h : n = a + b) : nat.choose n a = nat.choose n b := by { convert nat.choose_symm (nat.le_add_left _ _), rw nat.add_sub_cancel} lemma choose_symm_add {a b : ℕ} : choose (a+b) a = choose (a+b) b := choose_symm_of_eq_add rfl lemma choose_succ_right_eq (n k : ℕ) : choose n (k + 1) * (k + 1) = choose n k * (n - k) := begin have e : (n+1) * choose n k = choose n k * (k+1) + choose n (k+1) * (k+1), rw [← right_distrib, ← choose_succ_succ, succ_mul_choose_eq], rw [← nat.sub_eq_of_eq_add e, mul_comm, ← nat.mul_sub_left_distrib, nat.add_sub_add_right] end @[simp] lemma choose_succ_self_right : ∀ (n:ℕ), (n+1).choose n = n+1 | 0 := rfl | (n+1) := by rw [choose_succ_succ, choose_succ_self_right, choose_self] lemma choose_mul_succ_eq (n k : ℕ) : (n.choose k) * (n + 1) = ((n+1).choose k) * (n + 1 - k) := begin induction k with k ih, { simp }, by_cases hk : n < k + 1, { rw [choose_eq_zero_of_lt hk, sub_eq_zero_of_le hk, zero_mul, mul_zero] }, push_neg at hk, replace hk : k + 1 ≤ n + 1 := _root_.le_add_right hk, rw [choose_succ_succ], rw [add_mul, succ_sub_succ], rw [← choose_succ_right_eq], rw [← succ_sub_succ, nat.mul_sub_left_distrib], symmetry, apply nat.add_sub_cancel', exact mul_le_mul_left _ hk, end section find_greatest /-- `find_greatest P b` is the largest `i ≤ bound` such that `P i` holds, or `0` if no such `i` exists -/ protected def find_greatest (P : ℕ → Prop) [decidable_pred P] : ℕ → ℕ | 0 := 0 | (n + 1) := if P (n + 1) then n + 1 else find_greatest n variables {P : ℕ → Prop} [decidable_pred P] @[simp] lemma find_greatest_zero : nat.find_greatest P 0 = 0 := rfl @[simp] lemma find_greatest_eq : ∀{b}, P b → nat.find_greatest P b = b | 0 h := rfl | (n + 1) h := by simp [nat.find_greatest, h] @[simp] lemma find_greatest_of_not {b} (h : ¬ P (b + 1)) : nat.find_greatest P (b + 1) = nat.find_greatest P b := by simp [nat.find_greatest, h] lemma find_greatest_spec_and_le : ∀{b m}, m ≤ b → P m → P (nat.find_greatest P b) ∧ m ≤ nat.find_greatest P b | 0 m hm hP := have m = 0, from le_antisymm hm (nat.zero_le _), show P 0 ∧ m ≤ 0, from this ▸ ⟨hP, le_refl _⟩ | (b + 1) m hm hP := begin by_cases h : P (b + 1), { simp [h, hm] }, { have : m ≠ b + 1 := assume this, h $ this ▸ hP, have : m ≤ b := (le_of_not_gt $ assume h : b + 1 ≤ m, this $ le_antisymm hm h), have : P (nat.find_greatest P b) ∧ m ≤ nat.find_greatest P b := find_greatest_spec_and_le this hP, simp [h, this] } end lemma find_greatest_spec {b} : (∃m, m ≤ b ∧ P m) → P (nat.find_greatest P b) | ⟨m, hmb, hm⟩ := (find_greatest_spec_and_le hmb hm).1 lemma find_greatest_le : ∀ {b}, nat.find_greatest P b ≤ b | 0 := le_refl _ | (b + 1) := have nat.find_greatest P b ≤ b + 1, from le_trans find_greatest_le (nat.le_succ b), by by_cases P (b + 1); simp [h, this] lemma le_find_greatest {b m} (hmb : m ≤ b) (hm : P m) : m ≤ nat.find_greatest P b := (find_greatest_spec_and_le hmb hm).2 lemma find_greatest_is_greatest {P : ℕ → Prop} [decidable_pred P] {b} : (∃ m, m ≤ b ∧ P m) → ∀ k, nat.find_greatest P b < k ∧ k ≤ b → ¬ P k | ⟨m, hmb, hP⟩ k ⟨hk, hkb⟩ hPk := lt_irrefl k $ lt_of_le_of_lt (le_find_greatest hkb hPk) hk lemma find_greatest_eq_zero {P : ℕ → Prop} [decidable_pred P] : ∀ {b}, (∀ n ≤ b, ¬ P n) → nat.find_greatest P b = 0 | 0 h := find_greatest_zero | (n + 1) h := begin have := nat.find_greatest_of_not (h (n + 1) (le_refl _)), rw this, exact find_greatest_eq_zero (assume k hk, h k (le_trans hk $ nat.le_succ _)) end lemma find_greatest_of_ne_zero {P : ℕ → Prop} [decidable_pred P] : ∀ {b m}, nat.find_greatest P b = m → m ≠ 0 → P m | 0 m rfl h := by { have := @find_greatest_zero P _, contradiction } | (b + 1) m rfl h := decidable.by_cases (assume hb : P (b + 1), by { have := find_greatest_eq hb, rw this, exact hb }) (assume hb : ¬ P (b + 1), find_greatest_of_ne_zero (find_greatest_of_not hb).symm h) end find_greatest section div lemma dvd_div_of_mul_dvd {a b c : ℕ} (h : a * b ∣ c) : b ∣ c / a := if ha : a = 0 then by simp [ha] else have ha : 0 < a, from nat.pos_of_ne_zero ha, have h1 : ∃ d, c = a * b * d, from h, let ⟨d, hd⟩ := h1 in have hac : a ∣ c, from dvd_of_mul_right_dvd h, have h2 : c / a = b * d, from nat.div_eq_of_eq_mul_right ha (by simpa [mul_assoc] using hd), show ∃ d, c / a = b * d, from ⟨d, h2⟩ lemma mul_dvd_of_dvd_div {a b c : ℕ} (hab : c ∣ b) (h : a ∣ b / c) : c * a ∣ b := have h1 : ∃ d, b / c = a * d, from h, have h2 : ∃ e, b = c * e, from hab, let ⟨d, hd⟩ := h1, ⟨e, he⟩ := h2 in have h3 : b = a * d * c, from nat.eq_mul_of_div_eq_left hab hd, show ∃ d, b = c * a * d, from ⟨d, by cc⟩ lemma div_mul_div {a b c d : ℕ} (hab : b ∣ a) (hcd : d ∣ c) : (a / b) * (c / d) = (a * c) / (b * d) := have exi1 : ∃ x, a = b * x, from hab, have exi2 : ∃ y, c = d * y, from hcd, if hb : b = 0 then by simp [hb] else have 0 < b, from nat.pos_of_ne_zero hb, if hd : d = 0 then by simp [hd] else have 0 < d, from nat.pos_of_ne_zero hd, begin cases exi1 with x hx, cases exi2 with y hy, rw [hx, hy, nat.mul_div_cancel_left, nat.mul_div_cancel_left], symmetry, apply nat.div_eq_of_eq_mul_left, apply mul_pos, repeat {assumption}, cc end lemma pow_dvd_of_le_of_pow_dvd {p m n k : ℕ} (hmn : m ≤ n) (hdiv : p ^ n ∣ k) : p ^ m ∣ k := have p ^ m ∣ p ^ n, from pow_dvd_pow _ hmn, dvd_trans this hdiv lemma dvd_of_pow_dvd {p k m : ℕ} (hk : 1 ≤ k) (hpk : p^k ∣ m) : p ∣ m := by rw ←nat.pow_one p; exact pow_dvd_of_le_of_pow_dvd hk hpk lemma eq_of_dvd_of_div_eq_one {a b : ℕ} (w : a ∣ b) (h : b / a = 1) : a = b := by rw [←nat.div_mul_cancel w, h, one_mul] lemma eq_zero_of_dvd_of_div_eq_zero {a b : ℕ} (w : a ∣ b) (h : b / a = 0) : b = 0 := by rw [←nat.div_mul_cancel w, h, zero_mul] lemma div_le_div_left {a b c : ℕ} (h₁ : c ≤ b) (h₂ : 0 < c) : a / b ≤ a / c := (nat.le_div_iff_mul_le _ _ h₂).2 $ le_trans (mul_le_mul_left _ h₁) (div_mul_le_self _ _) lemma div_eq_self {a b : ℕ} : a / b = a ↔ a = 0 ∨ b = 1 := begin split, { intro, cases b, { simp * at * }, { cases b, { right, refl }, { left, have : a / (b + 2) ≤ a / 2 := div_le_div_left (by simp) dec_trivial, refine eq_zero_of_le_half _, simp * at * } } }, { rintros (rfl|rfl); simp } end end div lemma exists_eq_add_of_le : ∀ {m n : ℕ}, m ≤ n → ∃ k : ℕ, n = m + k | 0 0 h := ⟨0, by simp⟩ | 0 (n+1) h := ⟨n+1, by simp⟩ | (m+1) (n+1) h := let ⟨k, hk⟩ := exists_eq_add_of_le (nat.le_of_succ_le_succ h) in ⟨k, by simp [hk, add_comm, add_left_comm]⟩ lemma exists_eq_add_of_lt : ∀ {m n : ℕ}, m < n → ∃ k : ℕ, n = m + k + 1 | 0 0 h := false.elim $ lt_irrefl _ h | 0 (n+1) h := ⟨n, by simp⟩ | (m+1) (n+1) h := let ⟨k, hk⟩ := exists_eq_add_of_le (nat.le_of_succ_le_succ h) in ⟨k, by simp [hk]⟩ lemma with_bot.add_eq_zero_iff : ∀ {n m : with_bot ℕ}, n + m = 0 ↔ n = 0 ∧ m = 0 | none m := iff_of_false dec_trivial (λ h, absurd h.1 dec_trivial) | n none := iff_of_false (by cases n; exact dec_trivial) (λ h, absurd h.2 dec_trivial) | (some n) (some m) := show (n + m : with_bot ℕ) = (0 : ℕ) ↔ (n : with_bot ℕ) = (0 : ℕ) ∧ (m : with_bot ℕ) = (0 : ℕ), by rw [← with_bot.coe_add, with_bot.coe_eq_coe, with_bot.coe_eq_coe, with_bot.coe_eq_coe, add_eq_zero_iff' (nat.zero_le _) (nat.zero_le _)] lemma with_bot.add_eq_one_iff : ∀ {n m : with_bot ℕ}, n + m = 1 ↔ (n = 0 ∧ m = 1) ∨ (n = 1 ∧ m = 0) | none none := dec_trivial | none (some m) := dec_trivial | (some n) none := iff_of_false dec_trivial (λ h, h.elim (λ h, absurd h.2 dec_trivial) (λ h, absurd h.2 dec_trivial)) | (some n) (some 0) := by erw [with_bot.coe_eq_coe, with_bot.coe_eq_coe, with_bot.coe_eq_coe, with_bot.coe_eq_coe]; simp | (some n) (some (m + 1)) := by erw [with_bot.coe_eq_coe, with_bot.coe_eq_coe, with_bot.coe_eq_coe, with_bot.coe_eq_coe, with_bot.coe_eq_coe]; simp [nat.add_succ, nat.succ_inj', nat.succ_ne_zero] -- induction /-- Induction principle starting at a non-zero number. For maps to a `Sort*` see `le_rec_on`. -/ @[elab_as_eliminator] lemma le_induction {P : nat → Prop} {m} (h0 : P m) (h1 : ∀ n, m ≤ n → P n → P (n + 1)) : ∀ n, m ≤ n → P n := by apply nat.less_than_or_equal.rec h0; exact h1 /-- Decreasing induction: if `P (k+1)` implies `P k`, then `P n` implies `P m` for all `m ≤ n`. Also works for functions to `Sort*`. -/ @[elab_as_eliminator] def decreasing_induction {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n : ℕ} (mn : m ≤ n) (hP : P n) : P m := le_rec_on mn (λ k ih hsk, ih $ h k hsk) (λ h, h) hP @[simp] lemma decreasing_induction_self {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {n : ℕ} (nn : n ≤ n) (hP : P n) : (decreasing_induction h nn hP : P n) = hP := by { dunfold decreasing_induction, rw [le_rec_on_self] } lemma decreasing_induction_succ {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n : ℕ} (mn : m ≤ n) (msn : m ≤ n + 1) (hP : P (n+1)) : (decreasing_induction h msn hP : P m) = decreasing_induction h mn (h n hP) := by { dunfold decreasing_induction, rw [le_rec_on_succ] } @[simp] lemma decreasing_induction_succ' {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m : ℕ} (msm : m ≤ m + 1) (hP : P (m+1)) : (decreasing_induction h msm hP : P m) = h m hP := by { dunfold decreasing_induction, rw [le_rec_on_succ'] } lemma decreasing_induction_trans {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n k : ℕ} (mn : m ≤ n) (nk : n ≤ k) (hP : P k) : (decreasing_induction h (le_trans mn nk) hP : P m) = decreasing_induction h mn (decreasing_induction h nk hP) := by { induction nk with k nk ih, rw [decreasing_induction_self], rw [decreasing_induction_succ h (le_trans mn nk), ih, decreasing_induction_succ] } lemma decreasing_induction_succ_left {P : ℕ → Sort*} (h : ∀n, P (n+1) → P n) {m n : ℕ} (smn : m + 1 ≤ n) (mn : m ≤ n) (hP : P n) : (decreasing_induction h mn hP : P m) = h m (decreasing_induction h smn hP) := by { rw [subsingleton.elim mn (le_trans (le_succ m) smn), decreasing_induction_trans, decreasing_induction_succ'] } end nat namespace monoid_hom variables {M : Type*} {G : Type*} [monoid M] [group G] @[simp, to_additive] theorem iterate_map_one (f : M →* M) (n : ℕ) : f^[n] 1 = 1 := nat.iterate₀ f.map_one @[simp, to_additive] theorem iterate_map_mul (f : M →* M) (n : ℕ) (x y) : f^[n] (x * y) = (f^[n] x) * (f^[n] y) := nat.iterate₂ f.map_mul @[simp, to_additive] theorem iterate_map_inv (f : G →* G) (n : ℕ) (x) : f^[n] (x⁻¹) = (f^[n] x)⁻¹ := nat.iterate₁ f.map_inv @[simp] theorem iterate_map_sub {A : Type*} [add_group A] (f : A →+ A) (n : ℕ) (x y) : f^[n] (x - y) = (f^[n] x) - (f^[n] y) := nat.iterate₂ f.map_sub end monoid_hom namespace ring_hom variables {R : Type*} [semiring R] {S : Type*} [ring S] @[simp] theorem iterate_map_one (f : R →+* R) (n : ℕ) : f^[n] 1 = 1 := nat.iterate₀ f.map_one @[simp] theorem iterate_map_zero (f : R →+* R) (n : ℕ) : f^[n] 0 = 0 := nat.iterate₀ f.map_zero @[simp] theorem iterate_map_mul (f : R →+* R) (n : ℕ) (x y) : f^[n] (x * y) = (f^[n] x) * (f^[n] y) := nat.iterate₂ f.map_mul @[simp] theorem iterate_map_add (f : R →+* R) (n : ℕ) (x y) : f^[n] (x + y) = (f^[n] x) + (f^[n] y) := nat.iterate₂ f.map_add @[simp] theorem iterate_map_neg (f : S →+* S) (n : ℕ) (x) : f^[n] (-x) = -(f^[n] x) := nat.iterate₁ f.map_neg @[simp] theorem iterate_map_sub (f : S →+* S) (n : ℕ) (x y) : f^[n] (x - y) = (f^[n] x) - (f^[n] y) := nat.iterate₂ f.map_sub end ring_hom
3fe959f85974aa9c7f8d705d20abfca8117db3bf
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/topology/algebra/affine.lean
4f1934a0067c81d3671dba02d622c5fac97359ee
[ "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
2,304
lean
/- Copyright (c) 2020 Frédéric Dupuis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Frédéric Dupuis -/ import linear_algebra.affine_space.affine_map import topology.algebra.group.basic import topology.algebra.mul_action /-! # Topological properties of affine spaces and maps For now, this contains only a few facts regarding the continuity of affine maps in the special case when the point space and vector space are the same. TODO: Deal with the case where the point spaces are different from the vector spaces. Note that we do have some results in this direction under the assumption that the topologies are induced by (semi)norms. -/ namespace affine_map variables {R E F : Type*} variables [add_comm_group E] [topological_space E] variables [add_comm_group F] [topological_space F] [topological_add_group F] section ring variables [ring R] [module R E] [module R F] /-- An affine map is continuous iff its underlying linear map is continuous. See also `affine_map.continuous_linear_iff`. -/ lemma continuous_iff {f : E →ᵃ[R] F} : continuous f ↔ continuous f.linear := begin split, { intro hc, rw decomp' f, have := hc.sub continuous_const, exact this, }, { intro hc, rw decomp f, have := hc.add continuous_const, exact this } end /-- The line map is continuous. -/ @[continuity] lemma line_map_continuous [topological_space R] [has_continuous_smul R F] {p v : F} : continuous ⇑(line_map p v : R →ᵃ[R] F) := continuous_iff.mpr $ (continuous_id.smul continuous_const).add $ @continuous_const _ _ _ _ (0 : F) end ring section comm_ring variables [comm_ring R] [module R F] [has_continuous_const_smul R F] @[continuity] lemma homothety_continuous (x : F) (t : R) : continuous $ homothety x t := begin suffices : ⇑(homothety x t) = λ y, t • (y - x) + x, { rw this, continuity, }, ext y, simp [homothety_apply], end end comm_ring section field variables [field R] [module R F] [has_continuous_const_smul R F] lemma homothety_is_open_map (x : F) (t : R) (ht : t ≠ 0) : is_open_map $ homothety x t := begin apply is_open_map.of_inverse (homothety_continuous x t⁻¹); intros e; simp [← affine_map.comp_apply, ← homothety_mul, ht], end end field end affine_map
700c84fa9141fdcb440a19a082cd6f63d4521719
037dba89703a79cd4a4aec5e959818147f97635d
/src/2020/functions/injective_comp.lean
0294887033f626114827149f8654081216c97781
[]
no_license
ImperialCollegeLondon/M40001_lean
3a6a09298da395ab51bc220a535035d45bbe919b
62a76fa92654c855af2b2fc2bef8e60acd16ccec
refs/heads/master
1,666,750,403,259
1,665,771,117,000
1,665,771,117,000
209,141,835
115
12
null
1,640,270,596,000
1,568,749,174,000
Lean
UTF-8
Lean
false
false
584
lean
import tactic open function variables (X Y Z : Type) (f : X → Y) (g : Y → Z) example : (injective f) ∧ (injective g) → injective (g ∘ f) := begin -- Assume that f and g are injective. rintro ⟨hf, hg⟩, -- We need to prove `g ∘ f` is injective. -- So say `a`, `b` are in `X`, and `(g ∘ f)(a) = (g ∘ f)(b)` rintro a b hab, -- We need to prove that `a = b`. -- By injectivity of `f`, it suffices to prove that `f(a) = f(b)`. apply hf, -- But this follows immediately from our assumption -- `g(f(a))=g(f(b))`,and injectivity. exact hg hab, end
6cff58e08cce90bd91a5c4b8e5bf8aa4975b39d3
7cef822f3b952965621309e88eadf618da0c8ae9
/src/set_theory/surreal.lean
ee2bda66bcce43471e09927d51349a22a583c175
[ "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
14,907
lean
/- Copyright (c) 2019 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Scott Morrison -/ import set_theory.pgame /-! # Surreal numbers The basic theory of surreal numbers, built on top of the theory of combinatorial (pre-)games. A pregame is `numeric` if all the Left options are strictly smaller than all the Right options, and all those options are themselves numeric. In terms of combinatorial games, the numeric games have "frozen"; you can only make your position worse by playing, and Left is some definite "number" of moves ahead (or behind) Right. A surreal number is an equivalence class of numeric pregames. In fact, the surreals form a complete ordered field, containing a copy of the reals (and much else besides!) but we do not yet have a complete development. ## Order properties Surreal numbers inherit the relations `≤` and `<` from games, and these relations satisfy the axioms of a partial order (recall that `x < y ↔ x ≤ y ∧ ¬ y ≤ x` did not hold for games). ## Algebraic operations At this point, we have defined addition and negation (from pregames), and shown that surreals form an additive semigroup. It would be very little work to finish showing that the surreals form an ordered commutative group. We define the operations of multiplication and inverse on surreals, but do not yet establish any of the necessary properties to show the surreals form an ordered field. ## Embeddings It would be nice projects to define the group homomorphism `surreal → game`, and also `ℤ → surreal`, and then the homomorphic inclusion of the dyadic rationals into surreals, and finally via dyadic Dedekind cuts the homomorphic inclusion of the reals into the surreals. One can also map all the cardinals into the surreals! ## References * [Conway, *On numbers and games*][conway2001] -/ universes u namespace pgame /- Multiplicative operations can be defined at the level of pre-games, but as they are only useful on surreal numbers, we define them here. -/ /-- The product of `x = {xL | xR}` and `y = {yL | yR}` is `{xL*y + x*yL - xL*yL, xR*y + x*yR - xR*yR | xL*y + x*yR - xL*yR, x*yL + xR*y - xR*yL }`. -/ def mul (x y : pgame) : pgame := begin induction x with xl xr xL xR IHxl IHxr generalizing y, induction y with yl yr yL yR IHyl IHyr, have y := mk yl yr yL yR, refine ⟨xl × yl ⊕ xr × yr, xl × yr ⊕ xr × yl, _, _⟩; rintro (⟨i, j⟩ | ⟨i, j⟩), { exact IHxl i y + IHyl j - IHxl i (yL j) }, { exact IHxr i y + IHyr j - IHxr i (yR j) }, { exact IHxl i y + IHyr j - IHxl i (yR j) }, { exact IHxr i y + IHyl j - IHxr i (yL j) } end instance : has_mul pgame := ⟨mul⟩ /-- Because the two halves of the definition of inv produce more elements of each side, we have to define the two families inductively. This is the indexing set for the function, and `inv_val` is the function part. -/ inductive inv_ty (l r : Type u) : bool → Type u | zero {} : inv_ty ff | left₁ : r → inv_ty ff → inv_ty ff | left₂ : l → inv_ty tt → inv_ty ff | right₁ : l → inv_ty ff → inv_ty tt | right₂ : r → inv_ty tt → inv_ty tt /-- Because the two halves of the definition of inv produce more elements of each side, we have to define the two families inductively. This is the function part, defined by recursion on `inv_ty`. -/ def inv_val {l r} (L : l → pgame) (R : r → pgame) (IHl : l → pgame) (IHr : r → pgame) : ∀ {b}, inv_ty l r b → pgame | _ inv_ty.zero := 0 | _ (inv_ty.left₁ i j) := (1 + (R i - mk l r L R) * inv_val j) * IHr i | _ (inv_ty.left₂ i j) := (1 + (L i - mk l r L R) * inv_val j) * IHl i | _ (inv_ty.right₁ i j) := (1 + (L i - mk l r L R) * inv_val j) * IHl i | _ (inv_ty.right₂ i j) := (1 + (R i - mk l r L R) * inv_val j) * IHr i /-- The inverse of a positive surreal number `x = {L | R}` is given by `x⁻¹ = {0, (1 + (R - x) * x⁻¹L) * R, (1 + (L - x) * x⁻¹R) * L | (1 + (L - x) * x⁻¹L) * L, (1 + (R - x) * x⁻¹R) * R}`. Because the two halves `x⁻¹L, x⁻¹R` of `x⁻¹` are used in their own definition, the sets and elements are inductively generated. -/ def inv' : pgame → pgame | ⟨l, r, L, R⟩ := let l' := {i // 0 < L i}, L' : l' → pgame := λ i, L i.1, IHl' : l' → pgame := λ i, inv' (L i.1), IHr := λ i, inv' (R i) in ⟨inv_ty l' r ff, inv_ty l' r tt, inv_val L' R IHl' IHr, inv_val L' R IHl' IHr⟩ /-- The inverse of a surreal number in terms of the inverse on positive surreals. -/ noncomputable def inv (x : pgame) : pgame := by classical; exact if x = 0 then 0 else if 0 < x then inv' x else inv' (-x) noncomputable instance : has_inv pgame := ⟨inv⟩ noncomputable instance : has_div pgame := ⟨λ x y, x * y⁻¹⟩ /-- A pre-game is numeric if everything in the L set is less than everything in the R set, and all the elements of L and R are also numeric. -/ def numeric : pgame → Prop | ⟨l, r, L, R⟩ := (∀ i j, L i < R j) ∧ (∀ i, numeric (L i)) ∧ (∀ i, numeric (R i)) lemma numeric.move_left {x : pgame} (o : numeric x) (i : x.left_moves) : numeric (x.move_left i) := begin cases x with xl xr xL xR, exact o.2.1 i, end lemma numeric.move_right {x : pgame} (o : numeric x) (j : x.right_moves) : numeric (x.move_right j) := begin cases x with xl xr xL xR, exact o.2.2 j, end @[elab_as_eliminator] theorem numeric_rec {C : pgame → Prop} (H : ∀ l r (L : l → pgame) (R : r → pgame), (∀ i j, L i < R j) → (∀ i, numeric (L i)) → (∀ i, numeric (R i)) → (∀ i, C (L i)) → (∀ i, C (R i)) → C ⟨l, r, L, R⟩) : ∀ x, numeric x → C x | ⟨l, r, L, R⟩ ⟨h, hl, hr⟩ := H _ _ _ _ h hl hr (λ i, numeric_rec _ (hl i)) (λ i, numeric_rec _ (hr i)) theorem lt_asymm {x y : pgame} (ox : numeric x) (oy : numeric y) : x < y → ¬ y < x := begin refine numeric_rec (λ xl xr xL xR hx oxl oxr IHxl IHxr, _) x ox y oy, refine numeric_rec (λ yl yr yL yR hy oyl oyr IHyl IHyr, _), rw [mk_lt_mk, mk_lt_mk], rintro (⟨i, h₁⟩ | ⟨j, h₁⟩) (⟨i, h₂⟩ | ⟨j, h₂⟩), { exact IHxl _ _ (oyl _) (lt_of_le_mk h₁) (lt_of_le_mk h₂) }, { exact not_lt.2 (le_trans h₂ h₁) (hy _ _) }, { exact not_lt.2 (le_trans h₁ h₂) (hx _ _) }, { exact IHxr _ _ (oyr _) (lt_of_mk_le h₁) (lt_of_mk_le h₂) }, end theorem le_of_lt {x y : pgame} (ox : numeric x) (oy : numeric y) (h : x < y) : x ≤ y := not_lt.1 (lt_asymm ox oy h) /-- On numeric pre-games, `<` and `≤` satisfy the axioms of a partial order (even though they don't on all pre-games). -/ theorem lt_iff_le_not_le {x y : pgame} (ox : numeric x) (oy : numeric y) : x < y ↔ x ≤ y ∧ ¬ y ≤ x := ⟨λ h, ⟨le_of_lt ox oy h, not_le.2 h⟩, λ h, not_le.1 h.2⟩ theorem numeric_zero : numeric 0 := ⟨by rintros ⟨⟩ ⟨⟩, ⟨by rintros ⟨⟩, by rintros ⟨⟩⟩⟩ theorem numeric_one : numeric 1 := ⟨by rintros ⟨⟩ ⟨⟩, ⟨λ x, numeric_zero, by rintros ⟨⟩⟩⟩ theorem numeric_neg : Π {x : pgame} (o : numeric x), numeric (-x) | ⟨l, r, L, R⟩ o := ⟨λ j i, lt_iff_neg_gt.1 (o.1 i j), ⟨λ j, numeric_neg (o.2.2 j), λ i, numeric_neg (o.2.1 i)⟩⟩ theorem numeric.move_left_lt {x : pgame.{u}} (o : numeric x) (i : x.left_moves) : x.move_left i < x := begin rw lt_def_le, left, use i, end theorem numeric.move_left_le {x : pgame} (o : numeric x) (i : x.left_moves) : x.move_left i ≤ x := le_of_lt (o.move_left i) o (o.move_left_lt i) theorem numeric.lt_move_right {x : pgame} (o : numeric x) (j : x.right_moves) : x < x.move_right j := begin rw lt_def_le, right, use j, end theorem numeric.le_move_right {x : pgame} (o : numeric x) (j : x.right_moves) : x ≤ x.move_right j := le_of_lt o (o.move_right j) (o.lt_move_right j) theorem add_lt_add {w x y z : pgame.{u}} (ow : numeric w) (ox : numeric x) (oy : numeric y) (oz : numeric z) (hwx : w < x) (hyz : y < z) : w + y < x + z := begin rw lt_def_le at *, rcases hwx with ⟨ix, hix⟩|⟨jw, hjw⟩; rcases hyz with ⟨iz, hiz⟩|⟨jy, hjy⟩, { left, use (left_moves_add x z).symm (sum.inl ix), simp only [add_move_left_inl], calc w + y ≤ move_left x ix + y : add_le_add_right hix ... ≤ move_left x ix + move_left z iz : add_le_add_left hiz ... ≤ move_left x ix + z : add_le_add_left (oz.move_left_le iz) }, { left, use (left_moves_add x z).symm (sum.inl ix), simp only [add_move_left_inl], calc w + y ≤ move_left x ix + y : add_le_add_right hix ... ≤ move_left x ix + move_right y jy : add_le_add_left (oy.le_move_right jy) ... ≤ move_left x ix + z : add_le_add_left hjy }, { right, use (right_moves_add w y).symm (sum.inl jw), simp only [add_move_right_inl], calc move_right w jw + y ≤ x + y : add_le_add_right hjw ... ≤ x + move_left z iz : add_le_add_left hiz ... ≤ x + z : add_le_add_left (oz.move_left_le iz), }, { right, use (right_moves_add w y).symm (sum.inl jw), simp only [add_move_right_inl], calc move_right w jw + y ≤ x + y : add_le_add_right hjw ... ≤ x + move_right y jy : add_le_add_left (oy.le_move_right jy) ... ≤ x + z : add_le_add_left hjy, }, end theorem numeric_add : Π {x y : pgame} (ox : numeric x) (oy : numeric y), numeric (x + y) | ⟨xl, xr, xL, xR⟩ ⟨yl, yr, yL, yR⟩ ox oy := ⟨begin rintros (ix|iy) (jx|jy), { show xL ix + ⟨yl, yr, yL, yR⟩ < xR jx + ⟨yl, yr, yL, yR⟩, exact add_lt_add_right (ox.1 ix jx), }, { show xL ix + ⟨yl, yr, yL, yR⟩ < ⟨xl, xr, xL, xR⟩ + yR jy, apply add_lt_add (ox.move_left ix) ox oy (oy.move_right jy), apply ox.move_left_lt, apply oy.lt_move_right }, { -- show ⟨xl, xr, xL, xR⟩ + yL iy < xR jx + ⟨yl, yr, yL, yR⟩, -- fails? apply add_lt_add ox (ox.move_right jx) (oy.move_left iy) oy, apply ox.lt_move_right, apply oy.move_left_lt, }, { -- show ⟨xl, xr, xL, xR⟩ + yL iy < ⟨xl, xr, xL, xR⟩ + yR jy, -- fails? exact @add_lt_add_left ⟨xl, xr, xL, xR⟩ _ _ (oy.1 iy jy), } end, begin split, { rintros (ix|iy), { apply numeric_add (ox.move_left ix) oy, }, { apply numeric_add ox (oy.move_left iy), }, }, { rintros (jx|jy), { apply numeric_add (ox.move_right jx) oy, }, { apply numeric_add ox (oy.move_right jy), }, }, end⟩ using_well_founded { dec_tac := pgame_wf_tac } -- TODO prove -- theorem numeric_nat (n : ℕ) : numeric n := sorry -- theorem numeric_omega : numeric omega := sorry end pgame /-- The equivalence on numeric pre-games. -/ def surreal.equiv (x y : {x // pgame.numeric x}) : Prop := x.1.equiv y.1 local infix ` ≈ ` := surreal.equiv instance surreal.setoid : setoid {x // pgame.numeric x} := ⟨λ x y, x.1.equiv y.1, λ x, pgame.equiv_refl _, λ x y, pgame.equiv_symm, λ x y z, pgame.equiv_trans⟩ /-- The type of surreal numbers. These are the numeric pre-games quotiented by the equivalence relation `x ≈ y ↔ x ≤ y ∧ y ≤ x`. In the quotient, the order becomes a total order. -/ def surreal := quotient surreal.setoid namespace surreal open pgame /-- Construct a surreal number from a numeric pre-game. -/ def mk (x : pgame) (h : x.numeric) : surreal := quotient.mk ⟨x, h⟩ instance : has_zero surreal := { zero := ⟦⟨0, numeric_zero⟩⟧ } instance : has_one surreal := { one := ⟦⟨1, numeric_one⟩⟧ } /-- Lift an equivalence-respecting function on pre-games to surreals. -/ def lift {α} (f : ∀ x, numeric x → α) (H : ∀ {x y} (hx : numeric x) (hy : numeric y), x.equiv y → f x hx = f y hy) : surreal → α := quotient.lift (λ x : {x // numeric x}, f x.1 x.2) (λ x y, H x.2 y.2) /-- Lift a binary equivalence-respecting function on pre-games to surreals. -/ def lift₂ {α} (f : ∀ x y, numeric x → numeric y → α) (H : ∀ {x₁ y₁ x₂ y₂} (ox₁ : numeric x₁) (oy₁ : numeric y₁) (ox₂ : numeric x₂) (oy₂ : numeric y₂), x₁.equiv x₂ → y₁.equiv y₂ → f x₁ y₁ ox₁ oy₁ = f x₂ y₂ ox₂ oy₂) : surreal → surreal → α := lift (λ x ox, lift (λ y oy, f x y ox oy) (λ y₁ y₂ oy₁ oy₂ h, H _ _ _ _ (equiv_refl _) h)) (λ x₁ x₂ ox₁ ox₂ h, funext $ quotient.ind $ by exact λ ⟨y, oy⟩, H _ _ _ _ h (equiv_refl _)) /-- The relation `x ≤ y` on surreals. -/ def le : surreal → surreal → Prop := lift₂ (λ x y _ _, x ≤ y) (λ x₁ y₁ x₂ y₂ _ _ _ _ hx hy, propext (le_congr hx hy)) /-- The relation `x < y` on surreals. -/ def lt : surreal → surreal → Prop := lift₂ (λ x y _ _, x < y) (λ x₁ y₁ x₂ y₂ _ _ _ _ hx hy, propext (lt_congr hx hy)) theorem not_le : ∀ {x y : surreal}, ¬ le x y ↔ lt y x := by rintro ⟨⟨x, ox⟩⟩ ⟨⟨y, oy⟩⟩; exact not_le instance : preorder surreal := { le := le, lt := lt, le_refl := by rintro ⟨⟨x, ox⟩⟩; exact le_refl _, le_trans := by rintro ⟨⟨x, ox⟩⟩ ⟨⟨y, oy⟩⟩ ⟨⟨z, oz⟩⟩; exact le_trans, lt_iff_le_not_le := by rintro ⟨⟨x, ox⟩⟩ ⟨⟨y, oy⟩⟩; exact lt_iff_le_not_le ox oy } instance : partial_order surreal := { le_antisymm := by rintro ⟨⟨x, ox⟩⟩ ⟨⟨y, oy⟩⟩ h₁ h₂; exact quot.sound ⟨h₁, h₂⟩, ..surreal.preorder } instance : linear_order surreal := { le_total := by rintro ⟨⟨x, ox⟩⟩ ⟨⟨y, oy⟩⟩; classical; exact or_iff_not_imp_left.2 (λ h, le_of_lt oy ox (pgame.not_le.1 h)), ..surreal.partial_order } def add : surreal → surreal → surreal := surreal.lift₂ (λ (x y : pgame) (ox) (oy), ⟦⟨x + y, numeric_add ox oy⟩⟧) (λ x₁ y₁ x₂ y₂ _ _ _ _ hx hy, quot.sound (pgame.add_congr hx hy)) instance : has_add surreal := ⟨add⟩ theorem add_assoc : ∀ (x y z : surreal), (x + y) + z = x + (y + z) := begin rintros ⟨x⟩ ⟨y⟩ ⟨z⟩, apply quot.sound, exact add_assoc_equiv, end instance : add_semigroup surreal := { add_assoc := add_assoc, ..(by apply_instance : has_add surreal) } -- We conclude with some ideas for further work on surreals; these would make fun projects. -- TODO construct the remaining instances: -- add_monoid, add_group, add_comm_semigroup, add_comm_group, ordered_comm_group, -- as per the instances for `game` -- TODO define the inclusion of groups `surreal → game` -- TODO define the dyadic rationals, and show they map into the surreals via the formula -- m / 2^n ↦ { (m-1) / 2^n | (m+1) / 2^n } -- TODO show this is a group homomorphism, and injective -- TODO map the reals into the surreals, using dyadic Dedekind cuts -- TODO show this is a group homomorphism, and injective -- TODO define the field structure on the surreals -- TODO show the maps from the dyadic rationals and from the reals into the surreals are multiplicative end surreal
60e08d6985f23b68179454522336802344e31cb3
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/ring_theory/principal_ideal_domain.lean
c0dc297759a69aed8363e7c2357d323227d537cd
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
9,354
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Morenikeji Neri -/ import ring_theory.noetherian import ring_theory.unique_factorization_domain /-! # Principal ideal rings and principal ideal domains A principal ideal ring (PIR) is a commutative ring in which all ideals are principal. A principal ideal domain (PID) is an integral domain which is a principal ideal ring. # Main definitions Note that for principal ideal domains, one should use `[integral_domain R] [is_principal_ideal_ring R]`. There is no explicit definition of a PID. Theorems about PID's are in the `principal_ideal_ring` namespace. - `is_principal_ideal_ring`: a predicate on commutative rings, saying that every ideal is principal. - `generator`: a generator of a principal ideal (or more generally submodule) - `to_unique_factorization_monoid`: a PID is a unique factorization domain # Main results - `to_maximal_ideal`: a non-zero prime ideal in a PID is maximal. - `euclidean_domain.to_principal_ideal_domain` : a Euclidean domain is a PID. -/ universes u v variables {R : Type u} {M : Type v} open set function open submodule open_locale classical /-- An `R`-submodule of `M` is principal if it is generated by one element. -/ class submodule.is_principal [ring R] [add_comm_group M] [module R M] (S : submodule R M) : Prop := (principal [] : ∃ a, S = span R {a}) /-- A commutative ring is a principal ideal ring if all ideals are principal. -/ class is_principal_ideal_ring (R : Type u) [comm_ring R] : Prop := (principal : ∀ (S : ideal R), S.is_principal) attribute [instance] is_principal_ideal_ring.principal namespace submodule.is_principal variables [comm_ring R] [add_comm_group M] [module R M] /-- `generator I`, if `I` is a principal submodule, is an `x ∈ M` such that `span R {x} = I` -/ noncomputable def generator (S : submodule R M) [S.is_principal] : M := classical.some (principal S) lemma span_singleton_generator (S : submodule R M) [S.is_principal] : span R {generator S} = S := eq.symm (classical.some_spec (principal S)) @[simp] lemma generator_mem (S : submodule R M) [S.is_principal] : generator S ∈ S := by { conv_rhs { rw ← span_singleton_generator S }, exact subset_span (mem_singleton _) } lemma mem_iff_eq_smul_generator (S : submodule R M) [S.is_principal] {x : M} : x ∈ S ↔ ∃ s : R, x = s • generator S := by simp_rw [@eq_comm _ x, ← mem_span_singleton, span_singleton_generator] lemma mem_iff_generator_dvd (S : ideal R) [S.is_principal] {x : R} : x ∈ S ↔ generator S ∣ x := (mem_iff_eq_smul_generator S).trans (exists_congr (λ a, by simp only [mul_comm, smul_eq_mul])) lemma eq_bot_iff_generator_eq_zero (S : submodule R M) [S.is_principal] : S = ⊥ ↔ generator S = 0 := by rw [← @span_singleton_eq_bot R M, span_singleton_generator] lemma prime_generator_of_is_prime (S : ideal R) [submodule.is_principal S] [is_prime : S.is_prime] (ne_bot : S ≠ ⊥) : prime (generator S) := ⟨λ h, ne_bot ((eq_bot_iff_generator_eq_zero S).2 h), λ h, is_prime.ne_top (S.eq_top_of_is_unit_mem (generator_mem S) h), by simpa only [← mem_iff_generator_dvd S] using is_prime.2⟩ end submodule.is_principal namespace is_prime open submodule.is_principal ideal -- TODO -- for a non-ID one could perhaps prove that if p < q are prime then q maximal; -- 0 isn't prime in a non-ID PIR but the Krull dimension is still <= 1. -- The below result follows from this, but we could also use the below result to -- prove this (quotient out by p). lemma to_maximal_ideal [integral_domain R] [is_principal_ideal_ring R] {S : ideal R} [hpi : is_prime S] (hS : S ≠ ⊥) : is_maximal S := is_maximal_iff.2 ⟨(ne_top_iff_one S).1 hpi.1, begin assume T x hST hxS hxT, cases (mem_iff_generator_dvd _).1 (hST $ generator_mem S) with z hz, cases hpi.mem_or_mem (show generator T * z ∈ S, from hz ▸ generator_mem S), { have hTS : T ≤ S, rwa [← span_singleton_generator T, submodule.span_le, singleton_subset_iff], exact (hxS $ hTS hxT).elim }, cases (mem_iff_generator_dvd _).1 h with y hy, have : generator S ≠ 0 := mt (eq_bot_iff_generator_eq_zero _).2 hS, rw [← mul_one (generator S), hy, mul_left_comm, mul_right_inj' this] at hz, exact hz.symm ▸ T.mul_mem_right _ (generator_mem T) end⟩ end is_prime section open euclidean_domain variable [euclidean_domain R] lemma mod_mem_iff {S : ideal R} {x y : R} (hy : y ∈ S) : x % y ∈ S ↔ x ∈ S := ⟨λ hxy, div_add_mod x y ▸ S.add_mem (S.mul_mem_right _ hy) hxy, λ hx, (mod_eq_sub_mul_div x y).symm ▸ S.sub_mem hx (S.mul_mem_right _ hy)⟩ @[priority 100] -- see Note [lower instance priority] instance euclidean_domain.to_principal_ideal_domain : is_principal_ideal_ring R := { principal := λ S, by exactI ⟨if h : {x : R | x ∈ S ∧ x ≠ 0}.nonempty then have wf : well_founded (euclidean_domain.r : R → R → Prop) := euclidean_domain.r_well_founded, have hmin : well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h ∈ S ∧ well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h ≠ 0, from well_founded.min_mem wf {x : R | x ∈ S ∧ x ≠ 0} h, ⟨well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h, submodule.ext $ λ x, ⟨λ hx, div_add_mod x (well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h) ▸ (ideal.mem_span_singleton.2 $ dvd_add (dvd_mul_right _ _) $ have (x % (well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h) ∉ {x : R | x ∈ S ∧ x ≠ 0}), from λ h₁, well_founded.not_lt_min wf _ h h₁ (mod_lt x hmin.2), have x % well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h = 0, by finish [(mod_mem_iff hmin.1).2 hx], by simp *), λ hx, let ⟨y, hy⟩ := ideal.mem_span_singleton.1 hx in hy.symm ▸ S.mul_mem_right _ hmin.1⟩⟩ else ⟨0, submodule.ext $ λ a, by rw [← @submodule.bot_coe R R _ _ _, span_eq, submodule.mem_bot]; exact ⟨λ haS, by_contradiction $ λ ha0, h ⟨a, ⟨haS, ha0⟩⟩, λ h₁, h₁.symm ▸ S.zero_mem⟩⟩⟩ } end namespace principal_ideal_ring open is_principal_ideal_ring variables [integral_domain R] [is_principal_ideal_ring R] @[priority 100] -- see Note [lower instance priority] instance is_noetherian_ring : is_noetherian_ring R := is_noetherian_ring_iff.2 ⟨assume s : ideal R, begin rcases (is_principal_ideal_ring.principal s).principal with ⟨a, rfl⟩, rw [← finset.coe_singleton], exact ⟨{a}, set_like.coe_injective rfl⟩ end⟩ lemma is_maximal_of_irreducible {p : R} (hp : irreducible p) : ideal.is_maximal (span R ({p} : set R)) := ⟨⟨mt ideal.span_singleton_eq_top.1 hp.1, λ I hI, begin rcases principal I with ⟨a, rfl⟩, erw ideal.span_singleton_eq_top, unfreezingI { rcases ideal.span_singleton_le_span_singleton.1 (le_of_lt hI) with ⟨b, rfl⟩ }, refine (of_irreducible_mul hp).resolve_right (mt (λ hb, _) (not_le_of_lt hI)), erw [ideal.span_singleton_le_span_singleton, is_unit.mul_right_dvd hb] end⟩⟩ lemma irreducible_iff_prime {p : R} : irreducible p ↔ prime p := ⟨λ hp, (ideal.span_singleton_prime hp.ne_zero).1 $ (is_maximal_of_irreducible hp).is_prime, irreducible_of_prime⟩ lemma associates_irreducible_iff_prime : ∀{p : associates R}, irreducible p ↔ prime p := associates.irreducible_iff_prime_iff.1 (λ _, irreducible_iff_prime) section open_locale classical /-- `factors a` is a multiset of irreducible elements whose product is `a`, up to units -/ noncomputable def factors (a : R) : multiset R := if h : a = 0 then ∅ else classical.some (wf_dvd_monoid.exists_factors a h) lemma factors_spec (a : R) (h : a ≠ 0) : (∀b∈factors a, irreducible b) ∧ associated (factors a).prod a := begin unfold factors, rw [dif_neg h], exact classical.some_spec (wf_dvd_monoid.exists_factors a h) end lemma ne_zero_of_mem_factors {R : Type v} [integral_domain R] [is_principal_ideal_ring R] {a b : R} (ha : a ≠ 0) (hb : b ∈ factors a) : b ≠ 0 := irreducible.ne_zero ((factors_spec a ha).1 b hb) lemma mem_submonoid_of_factors_subset_of_units_subset (s : submonoid R) {a : R} (ha : a ≠ 0) (hfac : ∀ b ∈ factors a, b ∈ s) (hunit : ∀ c : units R, (c : R) ∈ s) : a ∈ s := begin rcases ((factors_spec a ha).2) with ⟨c, hc⟩, rw [← hc], exact submonoid.mul_mem _ (submonoid.multiset_prod_mem _ _ hfac) (hunit _), end /-- If a `ring_hom` maps all units and all factors of an element `a` into a submonoid `s`, then it also maps `a` into that submonoid. -/ lemma ring_hom_mem_submonoid_of_factors_subset_of_units_subset {R S : Type*} [integral_domain R] [is_principal_ideal_ring R] [semiring S] (f : R →+* S) (s : submonoid S) (a : R) (ha : a ≠ 0) (h : ∀ b ∈ factors a, f b ∈ s) (hf: ∀ c : units R, f c ∈ s) : f a ∈ s := mem_submonoid_of_factors_subset_of_units_subset (s.comap f.to_monoid_hom) ha h hf /-- A principal ideal domain has unique factorization -/ @[priority 100] -- see Note [lower instance priority] instance to_unique_factorization_monoid : unique_factorization_monoid R := { irreducible_iff_prime := λ _, principal_ideal_ring.irreducible_iff_prime .. (is_noetherian_ring.wf_dvd_monoid : wf_dvd_monoid R) } end end principal_ideal_ring
63de7efb03db18502cc3c233e3192d8ca7466aa7
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/lean/interactive/863.lean
88a41eeb717655105b8e491802f167e066599411
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
153
lean
import Lean open Lean in #check getRe --^ textDocument/completion namespace Lean #check getRe --^ textDocument/completion end Lean
cebd17571bd8eb654c540f8852ff1efe093807cd
957a80ea22c5abb4f4670b250d55534d9db99108
/library/init/category/default.lean
7af8c46e9aadfa3e25b84ca297b65e6bd0836149
[ "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
327
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.category.applicative init.category.functor init.category.alternative import init.category.monad init.category.state init.category.transformers
e4d75ad700f538a1e16a1303322273393a65be9c
8cb37a089cdb4af3af9d8bf1002b417e407a8e9e
/library/init/data/list/basic.lean
a904d56ce77420d6cd6e75666c2ef4ed65676a89
[ "Apache-2.0" ]
permissive
kbuzzard/lean
ae3c3db4bb462d750dbf7419b28bafb3ec983ef7
ed1788fd674bb8991acffc8fca585ec746711928
refs/heads/master
1,620,983,366,617
1,618,937,600,000
1,618,937,600,000
359,886,396
1
0
Apache-2.0
1,618,936,987,000
1,618,936,987,000
null
UTF-8
Lean
false
false
11,072
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.data.bool.basic init.propext 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 has_dec_eq [s : decidable_eq α] : decidable_eq (list α) | [] [] := is_true rfl | (a::as) [] := is_false (λ h, list.no_confusion h) | [] (b::bs) := is_false (λ h, list.no_confusion h) | (a::as) (b::bs) := match s a b with | is_true hab := match has_dec_eq as bs with | is_true habs := is_true (eq.subst hab (eq.subst habs rfl)) | is_false nabs := is_false (λ h, list.no_confusion h (λ _ habs, absurd habs nabs)) end | is_false nab := is_false (λ h, list.no_confusion h (λ hab _, absurd hab nab)) end instance [decidable_eq α] : decidable_eq (list α) := list.has_dec_eq @[simp] 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 instance : has_emptyc (list α) := ⟨list.nil⟩ protected def erase {α} [decidable_eq α] : list α → α → list α | [] b := [] | (a::l) b := if a = b then l else a :: erase l b protected def bag_inter {α} [decidable_eq α] : list α → list α → list α | [] _ := [] | _ [] := [] | (a::l₁) l₂ := if a ∈ l₂ then a :: bag_inter l₁ (l₂.erase a) else bag_inter l₁ l₂ protected def diff {α} [decidable_eq α] : list α → list α → list α | l [] := l | l₁ (a::l₂) := if a ∈ l₁ then diff (l₁.erase a) l₂ else diff l₁ l₂ @[simp] def length : list α → nat | [] := 0 | (a :: l) := length l + 1 def empty : list α → bool | [] := tt | (_ :: _) := ff open option nat @[simp] def nth : list α → nat → option α | [] n := none | (a :: l) 0 := some a | (a :: l) (n+1) := nth l n @[simp] def nth_le : Π (l : list α) (n), n < l.length → α | [] n h := absurd h (not_lt_zero n) | (a :: l) 0 h := a | (a :: l) (n+1) h := nth_le l n (le_of_succ_le_succ h) @[simp] def head [inhabited α] : list α → α | [] := default α | (a :: l) := a @[simp] 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 [] @[simp] def map (f : α → β) : list α → list β | [] := [] | (a :: l) := f a :: map l @[simp] def map₂ (f : α → β → γ) : list α → list β → list γ | [] _ := [] | _ [] := [] | (x::xs) (y::ys) := f x y :: map₂ xs ys def map_with_index_core (f : ℕ → α → β) : ℕ → list α → list β | k [] := [] | k (a::as) := f k a::(map_with_index_core (k+1) as) /-- Given a function `f : ℕ → α → β` and `as : list α`, `as = [a₀, a₁, ...]`, returns the list `[f 0 a₀, f 1 a₁, ...]`. -/ def map_with_index (f : ℕ → α → β) (as : list α) : list β := map_with_index_core f 0 as def join : list (list α) → list α | [] := [] | (l :: ls) := l ++ join ls def filter_map (f : α → option β) : list α → list β | [] := [] | (a::l) := match f a with | none := filter_map l | some b := b :: filter_map l end def filter (p : α → Prop) [decidable_pred p] : list α → list α | [] := [] | (a::l) := if p a then a :: filter l else filter l def partition (p : α → Prop) [decidable_pred p] : list α → list α × list α | [] := ([], []) | (a::l) := let (l₁, l₂) := partition l in if p a then (a :: l₁, l₂) else (l₁, a :: l₂) def drop_while (p : α → Prop) [decidable_pred p] : list α → list α | [] := [] | (a::l) := if p a then drop_while l else a::l /-- `after p xs` is the suffix of `xs` after the first element that satisfies `p`, not including that element. ```lean after (eq 1) [0, 1, 2, 3] = [2, 3] drop_while (not ∘ eq 1) [0, 1, 2, 3] = [1, 2, 3] ``` -/ def after (p : α → Prop) [decidable_pred p] : list α → list α | [] := [] | (x :: xs) := if p x then xs else after xs def span (p : α → Prop) [decidable_pred p] : list α → list α × list α | [] := ([], []) | (a::xs) := if p a then let (l, r) := span xs in (a :: l, r) else ([], a::xs) def find_index (p : α → Prop) [decidable_pred p] : list α → nat | [] := 0 | (a::l) := if p a then 0 else succ (find_index l) def index_of [decidable_eq α] (a : α) : list α → nat := find_index (eq a) def remove_all [decidable_eq α] (xs ys : list α) : list α := filter (∉ ys) xs 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 @[simp] def drop : ℕ → list α → list α | 0 a := a | (succ n) [] := [] | (succ n) (x::r) := drop n r @[simp] def take : ℕ → list α → list α | 0 a := [] | (succ n) [] := [] | (succ n) (x :: r) := x :: take n r @[simp] def foldl (f : α → β → α) : α → list β → α | a [] := a | a (b :: l) := foldl (f a b) l @[simp] def foldr (f : α → β → β) (b : β) : list α → β | [] := b | (a :: l) := f a (foldr 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 protected def insert [decidable_eq α] (a : α) (l : list α) : list α := if a ∈ l then l else a :: l instance [decidable_eq α] : has_insert α (list α) := ⟨list.insert⟩ instance : has_singleton α (list α) := ⟨λ x, [x]⟩ instance [decidable_eq α] : is_lawful_singleton α (list α) := ⟨λ x, show (if x ∈ ([] : list α) then [] else [x]) = [x], from if_neg not_false⟩ protected def union [decidable_eq α] (l₁ l₂ : list α) : list α := foldr insert l₂ l₁ instance [decidable_eq α] : has_union (list α) := ⟨list.union⟩ protected def inter [decidable_eq α] (l₁ l₂ : list α) : list α := filter (∈ l₂) l₁ instance [decidable_eq α] : has_inter (list α) := ⟨list.inter⟩ @[simp] 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 : ℕ → list ℕ | 0 := [] | (succ n) := succ n :: iota 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 @[simp] 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 init : list α → list α | [] := [] | [a] := [] | (a::l) := a::init 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] protected def bind {α : Type u} {β : Type v} (a : list α) (b : α → list β) : list β := join (map b a) @[inline] protected def ret {α : Type u} (a : α) : list α := [a] protected def lt [has_lt α] : list α → list α → Prop | [] [] := false | [] (b::bs) := true | (a::as) [] := false | (a::as) (b::bs) := a < b ∨ (¬ b < a ∧ lt as bs) instance [has_lt α] : has_lt (list α) := ⟨list.lt⟩ instance has_decidable_lt [has_lt α] [h : decidable_rel ((<) : α → α → Prop)] : Π l₁ l₂ : list α, decidable (l₁ < l₂) | [] [] := is_false not_false | [] (b::bs) := is_true trivial | (a::as) [] := is_false not_false | (a::as) (b::bs) := match h a b with | is_true h₁ := is_true (or.inl h₁) | is_false h₁ := match h b a with | is_true h₂ := is_false (λ h, or.elim h (λ h, absurd h h₁) (λ ⟨h, _⟩, absurd h₂ h)) | is_false h₂ := match has_decidable_lt as bs with | is_true h₃ := is_true (or.inr ⟨h₂, h₃⟩) | is_false h₃ := is_false (λ h, or.elim h (λ h, absurd h h₁) (λ ⟨_, h⟩, absurd h h₃)) end end end @[reducible] protected def le [has_lt α] (a b : list α) : Prop := ¬ b < a instance [has_lt α] : has_le (list α) := ⟨list.le⟩ instance has_decidable_le [has_lt α] [h : decidable_rel ((<) : α → α → Prop)] : Π l₁ l₂ : list α, decidable (l₁ ≤ l₂) := λ a b, not.decidable lemma le_eq_not_gt [has_lt α] : ∀ l₁ l₂ : list α, (l₁ ≤ l₂) = ¬ (l₂ < l₁) := λ l₁ l₂, rfl lemma lt_eq_not_ge [has_lt α] [decidable_rel ((<) : α → α → Prop)] : ∀ l₁ l₂ : list α, (l₁ < l₂) = ¬ (l₂ ≤ l₁) := λ l₁ l₂, show (l₁ < l₂) = ¬ ¬ (l₁ < l₂), from eq.subst (propext (not_not_iff (l₁ < l₂))).symm rfl /-- `is_prefix_of l₁ l₂` returns `tt` iff `l₁` is a prefix of `l₂`. -/ def is_prefix_of [decidable_eq α] : list α → list α → bool | [] _ := tt | _ [] := ff | (a::as) (b::bs) := to_bool (a = b) && is_prefix_of as bs /-- `is_suffix_of l₁ l₂` returns `tt` iff `l₁` is a suffix of `l₂`. -/ def is_suffix_of [decidable_eq α] (l₁ l₂ : list α) : bool := is_prefix_of l₁.reverse l₂.reverse end list namespace bin_tree private def to_list_aux : bin_tree α → list α → list α | empty as := as | (leaf a) as := a::as | (node l r) as := to_list_aux l (to_list_aux r as) def to_list (t : bin_tree α) : list α := to_list_aux t [] end bin_tree
775cdd27b5cc4cb0af528fcfd61dfab5ed4bd364
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/finsupp/basic.lean
9215aed0674c7bbf41b2459ae1b7e2446f04080c
[ "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
107,538
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, Scott Morrison -/ import data.finset.preimage import algebra.indicator_function import algebra.group_action_hom /-! # Type of functions with finite support For any type `α` and a type `M` with zero, we define the type `finsupp α M` (notation: `α →₀ M`) of finitely supported functions from `α` to `M`, i.e. the functions which are zero everywhere on `α` except on a finite set. Functions with finite support are used (at least) in the following parts of the library: * `monoid_algebra R M` and `add_monoid_algebra R M` are defined as `M →₀ R`; * polynomials and multivariate polynomials are defined as `add_monoid_algebra`s, hence they use `finsupp` under the hood; * the linear combination of a family of vectors `v i` with coefficients `f i` (as used, e.g., to define linearly independent family `linear_independent`) is defined as a map `finsupp.total : (ι → M) → (ι →₀ R) →ₗ[R] M`. Some other constructions are naturally equivalent to `α →₀ M` with some `α` and `M` but are defined in a different way in the library: * `multiset α ≃+ α →₀ ℕ`; * `free_abelian_group α ≃+ α →₀ ℤ`. Most of the theory assumes that the range is a commutative additive monoid. This gives us the big sum operator as a powerful way to construct `finsupp` elements. Many constructions based on `α →₀ M` use `semireducible` type tags to avoid reusing unwanted type instances. E.g., `monoid_algebra`, `add_monoid_algebra`, and types based on these two have non-pointwise multiplication. ## Main declarations * `finsupp`: The type of finitely supported functions from `α` to `β`. * `finsupp.single`: The `finsupp` which is nonzero in exactly one point. * `finsupp.update`: Changes one value of a `finsupp`. * `finsupp.erase`: Replaces one value of a `finsupp` by `0`. * `finsupp.on_finset`: The restriction of a function to a `finset` as a `finsupp`. * `finsupp.map_range`: Composition of a `zero_hom` with a`finsupp`. * `finsupp.emb_domain`: Maps the domain of a `finsupp` by an embedding. * `finsupp.map_domain`: Maps the domain of a `finsupp` by a function and by summing. * `finsupp.comap_domain`: Postcomposition of a `finsupp` with a function injective on the preimage of its support. * `finsupp.zip_with`: Postcomposition of two `finsupp`s with a function `f` such that `f 0 0 = 0`. * `finsupp.sum`: Sum of the values of a `finsupp`. * `finsupp.prod`: Product of the nonzero values of a `finsupp`. ## Notations This file adds `α →₀ M` as a global notation for `finsupp α M`. We also use the following convention for `Type*` variables in this file * `α`, `β`, `γ`: types with no additional structure that appear as the first argument to `finsupp` somewhere in the statement; * `ι` : an auxiliary index type; * `M`, `M'`, `N`, `P`: types with `has_zero` or `(add_)(comm_)monoid` structure; `M` is also used for a (semi)module over a (semi)ring. * `G`, `H`: groups (commutative or not, multiplicative or additive); * `R`, `S`: (semi)rings. ## Implementation notes This file is a `noncomputable theory` and uses classical logic throughout. ## TODO * This file is currently ~2.7K lines long, so it should be splitted into smaller chunks. One option would be to move all the sum and product stuff to `algebra.big_operators.finsupp` and move the definitions that depend on it to new files under `data.finsupp.`. * Expand the list of definitions and important lemmas to the module docstring. -/ noncomputable theory open finset function open_locale classical big_operators variables {α β γ ι M M' N P G H R S : Type*} /-- `finsupp α M`, denoted `α →₀ M`, is the type of functions `f : α → M` such that `f x = 0` for all but finitely many `x`. -/ structure finsupp (α : Type*) (M : Type*) [has_zero M] := (support : finset α) (to_fun : α → M) (mem_support_to_fun : ∀a, a ∈ support ↔ to_fun a ≠ 0) infixr ` →₀ `:25 := finsupp namespace finsupp /-! ### Basic declarations about `finsupp` -/ section basic variable [has_zero M] instance fun_like : fun_like (α →₀ M) α (λ _, M) := ⟨to_fun, begin rintro ⟨s, f, hf⟩ ⟨t, g, hg⟩ (rfl : f = g), congr', ext a, exact (hf _).trans (hg _).symm, end⟩ /-- Helper instance for when there are too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (α →₀ M) (λ _, α → M) := fun_like.has_coe_to_fun @[ext] lemma ext {f g : α →₀ M} (h : ∀ a, f a = g a) : f = g := fun_like.ext _ _ h /-- Deprecated. Use `fun_like.ext_iff` instead. -/ lemma ext_iff {f g : α →₀ M} : f = g ↔ ∀ a, f a = g a := fun_like.ext_iff /-- Deprecated. Use `fun_like.coe_fn_eq` instead. -/ lemma coe_fn_inj {f g : α →₀ M} : (f : α → M) = g ↔ f = g := fun_like.coe_fn_eq /-- Deprecated. Use `fun_like.coe_injective` instead. -/ lemma coe_fn_injective : @function.injective (α →₀ M) (α → M) coe_fn := fun_like.coe_injective /-- Deprecated. Use `fun_like.congr_fun` instead. -/ lemma congr_fun {f g : α →₀ M} (h : f = g) (a : α) : f a = g a := fun_like.congr_fun h _ @[simp] lemma coe_mk (f : α → M) (s : finset α) (h : ∀ a, a ∈ s ↔ f a ≠ 0) : ⇑(⟨s, f, h⟩ : α →₀ M) = f := rfl instance : has_zero (α →₀ M) := ⟨⟨∅, 0, λ _, ⟨false.elim, λ H, H rfl⟩⟩⟩ @[simp] lemma coe_zero : ⇑(0 : α →₀ M) = 0 := rfl lemma zero_apply {a : α} : (0 : α →₀ M) a = 0 := rfl @[simp] lemma support_zero : (0 : α →₀ M).support = ∅ := rfl instance : inhabited (α →₀ M) := ⟨0⟩ @[simp] lemma mem_support_iff {f : α →₀ M} : ∀{a:α}, a ∈ f.support ↔ f a ≠ 0 := f.mem_support_to_fun @[simp, norm_cast] lemma fun_support_eq (f : α →₀ M) : function.support f = f.support := set.ext $ λ x, mem_support_iff.symm lemma not_mem_support_iff {f : α →₀ M} {a} : a ∉ f.support ↔ f a = 0 := not_iff_comm.1 mem_support_iff.symm @[simp, norm_cast] lemma coe_eq_zero {f : α →₀ M} : (f : α → M) = 0 ↔ f = 0 := by rw [← coe_zero, coe_fn_inj] lemma ext_iff' {f g : α →₀ M} : f = g ↔ f.support = g.support ∧ ∀ x ∈ f.support, f x = g x := ⟨λ h, h ▸ ⟨rfl, λ _ _, rfl⟩, λ ⟨h₁, h₂⟩, ext $ λ a, if h : a ∈ f.support then h₂ a h else have hf : f a = 0, from not_mem_support_iff.1 h, have hg : g a = 0, by rwa [h₁, not_mem_support_iff] at h, by rw [hf, hg]⟩ @[simp] lemma support_eq_empty {f : α →₀ M} : f.support = ∅ ↔ f = 0 := by exact_mod_cast @function.support_eq_empty_iff _ _ _ f lemma support_nonempty_iff {f : α →₀ M} : f.support.nonempty ↔ f ≠ 0 := by simp only [finsupp.support_eq_empty, finset.nonempty_iff_ne_empty, ne.def] lemma nonzero_iff_exists {f : α →₀ M} : f ≠ 0 ↔ ∃ a : α, f a ≠ 0 := by simp [← finsupp.support_eq_empty, finset.eq_empty_iff_forall_not_mem] lemma card_support_eq_zero {f : α →₀ M} : card f.support = 0 ↔ f = 0 := by simp instance [decidable_eq α] [decidable_eq M] : decidable_eq (α →₀ M) := assume f g, decidable_of_iff (f.support = g.support ∧ (∀a∈f.support, f a = g a)) ext_iff'.symm lemma finite_support (f : α →₀ M) : set.finite (function.support f) := f.fun_support_eq.symm ▸ f.support.finite_to_set lemma support_subset_iff {s : set α} {f : α →₀ M} : ↑f.support ⊆ s ↔ (∀a∉s, f a = 0) := by simp only [set.subset_def, mem_coe, mem_support_iff]; exact forall_congr (assume a, not_imp_comm) /-- Given `fintype α`, `equiv_fun_on_fintype` is the `equiv` between `α →₀ β` and `α → β`. (All functions on a finite type are finitely supported.) -/ @[simps] def equiv_fun_on_fintype [fintype α] : (α →₀ M) ≃ (α → M) := ⟨λf a, f a, λf, mk (finset.univ.filter $ λa, f a ≠ 0) f (by simp only [true_and, finset.mem_univ, iff_self, finset.mem_filter, finset.filter_congr_decidable, forall_true_iff]), begin intro f, ext a, refl end, begin intro f, ext a, refl end⟩ @[simp] lemma equiv_fun_on_fintype_symm_coe {α} [fintype α] (f : α →₀ M) : equiv_fun_on_fintype.symm f = f := by { ext, simp [equiv_fun_on_fintype], } end basic /-! ### Declarations about `single` -/ section single variables [has_zero M] {a a' : α} {b : M} /-- `single a b` is the finitely supported function which has value `b` at `a` and zero otherwise. -/ def single (a : α) (b : M) : α →₀ M := ⟨if b = 0 then ∅ else {a}, λ a', if a = a' then b else 0, λ a', begin by_cases hb : b = 0; by_cases a = a'; simp only [hb, h, if_pos, if_false, mem_singleton], { exact ⟨false.elim, λ H, H rfl⟩ }, { exact ⟨false.elim, λ H, H rfl⟩ }, { exact ⟨λ _, hb, λ _, rfl⟩ }, { exact ⟨λ H _, h H.symm, λ H, (H rfl).elim⟩ } end⟩ lemma single_apply [decidable (a = a')] : single a b a' = if a = a' then b else 0 := by convert rfl lemma single_eq_indicator : ⇑(single a b) = set.indicator {a} (λ _, b) := by { ext, simp [single_apply, set.indicator, @eq_comm _ a] } @[simp] lemma single_eq_same : (single a b : α →₀ M) a = b := if_pos rfl @[simp] lemma single_eq_of_ne (h : a ≠ a') : (single a b : α →₀ M) a' = 0 := if_neg h lemma single_eq_update [decidable_eq α] : ⇑(single a b) = function.update 0 a b := by rw [single_eq_indicator, ← set.piecewise_eq_indicator, set.piecewise_singleton] lemma single_eq_pi_single [decidable_eq α] : ⇑(single a b) = pi.single a b := single_eq_update @[simp] lemma single_zero : (single a 0 : α →₀ M) = 0 := coe_fn_injective $ by simpa only [single_eq_update, coe_zero] using function.update_eq_self a (0 : α → M) lemma single_of_single_apply (a a' : α) (b : M) : single a ((single a' b) a) = single a' (single a' b) a := begin rw [single_apply, single_apply], ext, split_ifs, { rw h, }, { rw [zero_apply, single_apply, if_t_t], }, end lemma support_single_ne_zero (hb : b ≠ 0) : (single a b).support = {a} := if_neg hb lemma support_single_subset : (single a b).support ⊆ {a} := show ite _ _ _ ⊆ _, by split_ifs; [exact empty_subset _, exact subset.refl _] lemma single_apply_mem (x) : single a b x ∈ ({0, b} : set M) := by rcases em (a = x) with (rfl|hx); [simp, simp [single_eq_of_ne hx]] lemma range_single_subset : set.range (single a b) ⊆ {0, b} := set.range_subset_iff.2 single_apply_mem /-- `finsupp.single a b` is injective in `b`. For the statement that it is injective in `a`, see `finsupp.single_left_injective` -/ lemma single_injective (a : α) : function.injective (single a : M → α →₀ M) := assume b₁ b₂ eq, have (single a b₁ : α →₀ M) a = (single a b₂ : α →₀ M) a, by rw eq, by rwa [single_eq_same, single_eq_same] at this lemma single_apply_eq_zero {a x : α} {b : M} : single a b x = 0 ↔ (x = a → b = 0) := by simp [single_eq_indicator] lemma mem_support_single (a a' : α) (b : M) : a ∈ (single a' b).support ↔ a = a' ∧ b ≠ 0 := by simp [single_apply_eq_zero, not_or_distrib] lemma eq_single_iff {f : α →₀ M} {a b} : f = single a b ↔ f.support ⊆ {a} ∧ f a = b := begin refine ⟨λ h, h.symm ▸ ⟨support_single_subset, single_eq_same⟩, _⟩, rintro ⟨h, rfl⟩, ext x, by_cases hx : a = x; simp only [hx, single_eq_same, single_eq_of_ne, ne.def, not_false_iff], exact not_mem_support_iff.1 (mt (λ hx, (mem_singleton.1 (h hx)).symm) hx) end lemma single_eq_single_iff (a₁ a₂ : α) (b₁ b₂ : M) : single a₁ b₁ = single a₂ b₂ ↔ ((a₁ = a₂ ∧ b₁ = b₂) ∨ (b₁ = 0 ∧ b₂ = 0)) := begin split, { assume eq, by_cases a₁ = a₂, { refine or.inl ⟨h, _⟩, rwa [h, (single_injective a₂).eq_iff] at eq }, { rw [ext_iff] at eq, have h₁ := eq a₁, have h₂ := eq a₂, simp only [single_eq_same, single_eq_of_ne h, single_eq_of_ne (ne.symm h)] at h₁ h₂, exact or.inr ⟨h₁, h₂.symm⟩ } }, { rintros (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩), { refl }, { rw [single_zero, single_zero] } } end /-- `finsupp.single a b` is injective in `a`. For the statement that it is injective in `b`, see `finsupp.single_injective` -/ lemma single_left_injective (h : b ≠ 0) : function.injective (λ a : α, single a b) := λ a a' H, (((single_eq_single_iff _ _ _ _).mp H).resolve_right $ λ hb, h hb.1).left lemma single_left_inj (h : b ≠ 0) : single a b = single a' b ↔ a = a' := (single_left_injective h).eq_iff lemma support_single_ne_bot (i : α) (h : b ≠ 0) : (single i b).support ≠ ⊥ := begin have : i ∈ (single i b).support := by simpa using h, intro H, simpa [H] end lemma support_single_disjoint [decidable_eq α] {b' : M} (hb : b ≠ 0) (hb' : b' ≠ 0) {i j : α} : disjoint (single i b).support (single j b').support ↔ i ≠ j := by rw [support_single_ne_zero hb, support_single_ne_zero hb', disjoint_singleton] @[simp] lemma single_eq_zero : single a b = 0 ↔ b = 0 := by simp [ext_iff, single_eq_indicator] lemma single_swap (a₁ a₂ : α) (b : M) : single a₁ b a₂ = single a₂ b a₁ := by simp only [single_apply]; ac_refl instance [nonempty α] [nontrivial M] : nontrivial (α →₀ M) := begin inhabit α, rcases exists_ne (0 : M) with ⟨x, hx⟩, exact nontrivial_of_ne (single default x) 0 (mt single_eq_zero.1 hx) end lemma unique_single [unique α] (x : α →₀ M) : x = single default (x default) := ext $ unique.forall_iff.2 single_eq_same.symm lemma unique_ext [unique α] {f g : α →₀ M} (h : f default = g default) : f = g := ext $ λ a, by rwa [unique.eq_default a] lemma unique_ext_iff [unique α] {f g : α →₀ M} : f = g ↔ f default = g default := ⟨λ h, h ▸ rfl, unique_ext⟩ @[simp] lemma unique_single_eq_iff [unique α] {b' : M} : single a b = single a' b' ↔ b = b' := by rw [unique_ext_iff, unique.eq_default a, unique.eq_default a', single_eq_same, single_eq_same] lemma support_eq_singleton {f : α →₀ M} {a : α} : f.support = {a} ↔ f a ≠ 0 ∧ f = single a (f a) := ⟨λ h, ⟨mem_support_iff.1 $ h.symm ▸ finset.mem_singleton_self a, eq_single_iff.2 ⟨subset_of_eq h, rfl⟩⟩, λ h, h.2.symm ▸ support_single_ne_zero h.1⟩ lemma support_eq_singleton' {f : α →₀ M} {a : α} : f.support = {a} ↔ ∃ b ≠ 0, f = single a b := ⟨λ h, let h := support_eq_singleton.1 h in ⟨_, h.1, h.2⟩, λ ⟨b, hb, hf⟩, hf.symm ▸ support_single_ne_zero hb⟩ lemma card_support_eq_one {f : α →₀ M} : card f.support = 1 ↔ ∃ a, f a ≠ 0 ∧ f = single a (f a) := by simp only [card_eq_one, support_eq_singleton] lemma card_support_eq_one' {f : α →₀ M} : card f.support = 1 ↔ ∃ a (b ≠ 0), f = single a b := by simp only [card_eq_one, support_eq_singleton'] lemma support_subset_singleton {f : α →₀ M} {a : α} : f.support ⊆ {a} ↔ f = single a (f a) := ⟨λ h, eq_single_iff.mpr ⟨h, rfl⟩, λ h, (eq_single_iff.mp h).left⟩ lemma support_subset_singleton' {f : α →₀ M} {a : α} : f.support ⊆ {a} ↔ ∃ b, f = single a b := ⟨λ h, ⟨f a, support_subset_singleton.mp h⟩, λ ⟨b, hb⟩, by rw [hb, support_subset_singleton, single_eq_same]⟩ lemma card_support_le_one [nonempty α] {f : α →₀ M} : card f.support ≤ 1 ↔ ∃ a, f = single a (f a) := by simp only [card_le_one_iff_subset_singleton, support_subset_singleton] lemma card_support_le_one' [nonempty α] {f : α →₀ M} : card f.support ≤ 1 ↔ ∃ a b, f = single a b := by simp only [card_le_one_iff_subset_singleton, support_subset_singleton'] @[simp] lemma equiv_fun_on_fintype_single [decidable_eq α] [fintype α] (x : α) (m : M) : (@finsupp.equiv_fun_on_fintype α M _ _) (finsupp.single x m) = pi.single x m := by { ext, simp [finsupp.single_eq_pi_single, finsupp.equiv_fun_on_fintype], } @[simp] lemma equiv_fun_on_fintype_symm_single [decidable_eq α] [fintype α] (x : α) (m : M) : (@finsupp.equiv_fun_on_fintype α M _ _).symm (pi.single x m) = finsupp.single x m := by { ext, simp [finsupp.single_eq_pi_single, finsupp.equiv_fun_on_fintype], } end single /-! ### Declarations about `update` -/ section update variables [has_zero M] (f : α →₀ M) (a : α) (b : M) (i : α) /-- Replace the value of a `α →₀ M` at a given point `a : α` by a given value `b : M`. If `b = 0`, this amounts to removing `a` from the `finsupp.support`. Otherwise, if `a` was not in the `finsupp.support`, it is added to it. This is the finitely-supported version of `function.update`. -/ def update : α →₀ M := ⟨if b = 0 then f.support.erase a else insert a f.support, function.update f a b, λ i, begin simp only [function.update_apply, ne.def], split_ifs with hb ha ha hb; simp [ha, hb] end⟩ @[simp] lemma coe_update [decidable_eq α] : (f.update a b : α → M) = function.update f a b := by convert rfl @[simp] lemma update_self : f.update a (f a) = f := by { ext, simp } lemma support_update [decidable_eq α] : support (f.update a b) = if b = 0 then f.support.erase a else insert a f.support := by convert rfl @[simp] lemma support_update_zero [decidable_eq α] : support (f.update a 0) = f.support.erase a := by convert if_pos rfl variables {b} lemma support_update_ne_zero [decidable_eq α] (h : b ≠ 0) : support (f.update a b) = insert a f.support := by convert if_neg h end update /-! ### Declarations about `on_finset` -/ section on_finset variables [has_zero M] /-- `on_finset s f hf` is the finsupp function representing `f` restricted to the finset `s`. The function needs to be `0` outside of `s`. Use this when the set needs to be filtered anyways, otherwise a better set representation is often available. -/ def on_finset (s : finset α) (f : α → M) (hf : ∀a, f a ≠ 0 → a ∈ s) : α →₀ M := ⟨s.filter (λa, f a ≠ 0), f, by simpa⟩ @[simp] lemma on_finset_apply {s : finset α} {f : α → M} {hf a} : (on_finset s f hf : α →₀ M) a = f a := rfl @[simp] lemma support_on_finset_subset {s : finset α} {f : α → M} {hf} : (on_finset s f hf).support ⊆ s := filter_subset _ _ @[simp] lemma mem_support_on_finset {s : finset α} {f : α → M} (hf : ∀ (a : α), f a ≠ 0 → a ∈ s) {a : α} : a ∈ (finsupp.on_finset s f hf).support ↔ f a ≠ 0 := by rw [finsupp.mem_support_iff, finsupp.on_finset_apply] lemma support_on_finset {s : finset α} {f : α → M} (hf : ∀ (a : α), f a ≠ 0 → a ∈ s) : (finsupp.on_finset s f hf).support = s.filter (λ a, f a ≠ 0) := rfl end on_finset section of_support_finite variables [has_zero M] /-- The natural `finsupp` induced by the function `f` given that it has finite support. -/ noncomputable def of_support_finite (f : α → M) (hf : (function.support f).finite) : α →₀ M := { support := hf.to_finset, to_fun := f, mem_support_to_fun := λ _, hf.mem_to_finset } lemma of_support_finite_coe {f : α → M} {hf : (function.support f).finite} : (of_support_finite f hf : α → M) = f := rfl instance : can_lift (α → M) (α →₀ M) := { coe := coe_fn, cond := λ f, (function.support f).finite, prf := λ f hf, ⟨of_support_finite f hf, rfl⟩ } end of_support_finite /-! ### Declarations about `map_range` -/ section map_range variables [has_zero M] [has_zero N] [has_zero P] /-- The composition of `f : M → N` and `g : α →₀ M` is `map_range f hf g : α →₀ N`, well-defined when `f 0 = 0`. This preserves the structure on `f`, and exists in various bundled forms for when `f` is itself bundled: * `finsupp.map_range.equiv` * `finsupp.map_range.zero_hom` * `finsupp.map_range.add_monoid_hom` * `finsupp.map_range.add_equiv` * `finsupp.map_range.linear_map` * `finsupp.map_range.linear_equiv` -/ def map_range (f : M → N) (hf : f 0 = 0) (g : α →₀ M) : α →₀ N := on_finset g.support (f ∘ g) $ assume a, by rw [mem_support_iff, not_imp_not]; exact λ H, (congr_arg f H).trans hf @[simp] lemma map_range_apply {f : M → N} {hf : f 0 = 0} {g : α →₀ M} {a : α} : map_range f hf g a = f (g a) := rfl @[simp] lemma map_range_zero {f : M → N} {hf : f 0 = 0} : map_range f hf (0 : α →₀ M) = 0 := ext $ λ a, by simp only [hf, zero_apply, map_range_apply] @[simp] lemma map_range_id (g : α →₀ M) : map_range id rfl g = g := ext $ λ _, rfl lemma map_range_comp (f : N → P) (hf : f 0 = 0) (f₂ : M → N) (hf₂ : f₂ 0 = 0) (h : (f ∘ f₂) 0 = 0) (g : α →₀ M) : map_range (f ∘ f₂) h g = map_range f hf (map_range f₂ hf₂ g) := ext $ λ _, rfl lemma support_map_range {f : M → N} {hf : f 0 = 0} {g : α →₀ M} : (map_range f hf g).support ⊆ g.support := support_on_finset_subset @[simp] lemma map_range_single {f : M → N} {hf : f 0 = 0} {a : α} {b : M} : map_range f hf (single a b) = single a (f b) := ext $ λ a', show f (ite _ _ _) = ite _ _ _, by split_ifs; [refl, exact hf] end map_range /-! ### Declarations about `emb_domain` -/ section emb_domain variables [has_zero M] [has_zero N] /-- Given `f : α ↪ β` and `v : α →₀ M`, `emb_domain f v : β →₀ M` is the finitely supported function whose value at `f a : β` is `v a`. For a `b : β` outside the range of `f`, it is zero. -/ def emb_domain (f : α ↪ β) (v : α →₀ M) : β →₀ M := begin refine ⟨v.support.map f, λa₂, if h : a₂ ∈ v.support.map f then v (v.support.choose (λa₁, f a₁ = a₂) _) else 0, _⟩, { rcases finset.mem_map.1 h with ⟨a, ha, rfl⟩, exact exists_unique.intro a ⟨ha, rfl⟩ (assume b ⟨_, hb⟩, f.injective hb) }, { assume a₂, split_ifs, { simp only [h, true_iff, ne.def], rw [← not_mem_support_iff, not_not], apply finset.choose_mem }, { simp only [h, ne.def, ne_self_iff_false] } } end @[simp] lemma support_emb_domain (f : α ↪ β) (v : α →₀ M) : (emb_domain f v).support = v.support.map f := rfl @[simp] lemma emb_domain_zero (f : α ↪ β) : (emb_domain f 0 : β →₀ M) = 0 := rfl @[simp] lemma emb_domain_apply (f : α ↪ β) (v : α →₀ M) (a : α) : emb_domain f v (f a) = v a := begin change dite _ _ _ = _, split_ifs; rw [finset.mem_map' f] at h, { refine congr_arg (v : α → M) (f.inj' _), exact finset.choose_property (λa₁, f a₁ = f a) _ _ }, { exact (not_mem_support_iff.1 h).symm } end lemma emb_domain_notin_range (f : α ↪ β) (v : α →₀ M) (a : β) (h : a ∉ set.range f) : emb_domain f v a = 0 := begin refine dif_neg (mt (assume h, _) h), rcases finset.mem_map.1 h with ⟨a, h, rfl⟩, exact set.mem_range_self a end lemma emb_domain_injective (f : α ↪ β) : function.injective (emb_domain f : (α →₀ M) → (β →₀ M)) := λ l₁ l₂ h, ext $ λ a, by simpa only [emb_domain_apply] using ext_iff.1 h (f a) @[simp] lemma emb_domain_inj {f : α ↪ β} {l₁ l₂ : α →₀ M} : emb_domain f l₁ = emb_domain f l₂ ↔ l₁ = l₂ := (emb_domain_injective f).eq_iff @[simp] lemma emb_domain_eq_zero {f : α ↪ β} {l : α →₀ M} : emb_domain f l = 0 ↔ l = 0 := (emb_domain_injective f).eq_iff' $ emb_domain_zero f lemma emb_domain_map_range (f : α ↪ β) (g : M → N) (p : α →₀ M) (hg : g 0 = 0) : emb_domain f (map_range g hg p) = map_range g hg (emb_domain f p) := begin ext a, by_cases a ∈ set.range f, { rcases h with ⟨a', rfl⟩, rw [map_range_apply, emb_domain_apply, emb_domain_apply, map_range_apply] }, { rw [map_range_apply, emb_domain_notin_range, emb_domain_notin_range, ← hg]; assumption } end lemma single_of_emb_domain_single (l : α →₀ M) (f : α ↪ β) (a : β) (b : M) (hb : b ≠ 0) (h : l.emb_domain f = single a b) : ∃ x, l = single x b ∧ f x = a := begin have h_map_support : finset.map f (l.support) = {a}, by rw [←support_emb_domain, h, support_single_ne_zero hb]; refl, have ha : a ∈ finset.map f (l.support), by simp only [h_map_support, finset.mem_singleton], rcases finset.mem_map.1 ha with ⟨c, hc₁, hc₂⟩, use c, split, { ext d, rw [← emb_domain_apply f l, h], by_cases h_cases : c = d, { simp only [eq.symm h_cases, hc₂, single_eq_same] }, { rw [single_apply, single_apply, if_neg, if_neg h_cases], by_contra hfd, exact h_cases (f.injective (hc₂.trans hfd)) } }, { exact hc₂ } end @[simp] lemma emb_domain_single (f : α ↪ β) (a : α) (m : M) : emb_domain f (single a m) = single (f a) m := begin ext b, by_cases h : b ∈ set.range f, { rcases h with ⟨a', rfl⟩, simp [single_apply], }, { simp only [emb_domain_notin_range, h, single_apply, not_false_iff], rw if_neg, rintro rfl, simpa using h, }, end end emb_domain /-! ### Declarations about `zip_with` -/ section zip_with variables [has_zero M] [has_zero N] [has_zero P] /-- `zip_with f hf g₁ g₂` is the finitely supported function satisfying `zip_with f hf g₁ g₂ a = f (g₁ a) (g₂ a)`, and it is well-defined when `f 0 0 = 0`. -/ def zip_with (f : M → N → P) (hf : f 0 0 = 0) (g₁ : α →₀ M) (g₂ : α →₀ N) : α →₀ P := on_finset (g₁.support ∪ g₂.support) (λa, f (g₁ a) (g₂ a)) $ λ a H, begin simp only [mem_union, mem_support_iff, ne], rw [← not_and_distrib], rintro ⟨h₁, h₂⟩, rw [h₁, h₂] at H, exact H hf end @[simp] lemma zip_with_apply {f : M → N → P} {hf : f 0 0 = 0} {g₁ : α →₀ M} {g₂ : α →₀ N} {a : α} : zip_with f hf g₁ g₂ a = f (g₁ a) (g₂ a) := rfl lemma support_zip_with [D : decidable_eq α] {f : M → N → P} {hf : f 0 0 = 0} {g₁ : α →₀ M} {g₂ : α →₀ N} : (zip_with f hf g₁ g₂).support ⊆ g₁.support ∪ g₂.support := by rw subsingleton.elim D; exact support_on_finset_subset end zip_with /-! ### Declarations about `erase` -/ section erase variables [has_zero M] /-- `erase a f` is the finitely supported function equal to `f` except at `a` where it is equal to `0`. -/ def erase (a : α) (f : α →₀ M) : α →₀ M := ⟨f.support.erase a, (λa', if a' = a then 0 else f a'), assume a', by rw [mem_erase, mem_support_iff]; split_ifs; [exact ⟨λ H _, H.1 h, λ H, (H rfl).elim⟩, exact and_iff_right h]⟩ @[simp] lemma support_erase [decidable_eq α] {a : α} {f : α →₀ M} : (f.erase a).support = f.support.erase a := by convert rfl @[simp] lemma erase_same {a : α} {f : α →₀ M} : (f.erase a) a = 0 := if_pos rfl @[simp] lemma erase_ne {a a' : α} {f : α →₀ M} (h : a' ≠ a) : (f.erase a) a' = f a' := if_neg h @[simp] lemma erase_single {a : α} {b : M} : (erase a (single a b)) = 0 := begin ext s, by_cases hs : s = a, { rw [hs, erase_same], refl }, { rw [erase_ne hs], exact single_eq_of_ne (ne.symm hs) } end lemma erase_single_ne {a a' : α} {b : M} (h : a ≠ a') : (erase a (single a' b)) = single a' b := begin ext s, by_cases hs : s = a, { rw [hs, erase_same, single_eq_of_ne (h.symm)] }, { rw [erase_ne hs] } end @[simp] lemma erase_of_not_mem_support {f : α →₀ M} {a} (haf : a ∉ f.support) : erase a f = f := begin ext b, by_cases hab : b = a, { rwa [hab, erase_same, eq_comm, ←not_mem_support_iff] }, { rw erase_ne hab } end @[simp] lemma erase_zero (a : α) : erase a (0 : α →₀ M) = 0 := by rw [← support_eq_empty, support_erase, support_zero, erase_empty] end erase /-! ### Declarations about `sum` and `prod` In most of this section, the domain `β` is assumed to be an `add_monoid`. -/ section sum_prod /-- `prod f g` is the product of `g a (f a)` over the support of `f`. -/ @[to_additive "`sum f g` is the sum of `g a (f a)` over the support of `f`. "] def prod [has_zero M] [comm_monoid N] (f : α →₀ M) (g : α → M → N) : N := ∏ a in f.support, g a (f a) variables [has_zero M] [has_zero M'] [comm_monoid N] @[to_additive] lemma prod_of_support_subset (f : α →₀ M) {s : finset α} (hs : f.support ⊆ s) (g : α → M → N) (h : ∀ i ∈ s, g i 0 = 1) : f.prod g = ∏ x in s, g x (f x) := finset.prod_subset hs $ λ x hxs hx, h x hxs ▸ congr_arg (g x) $ not_mem_support_iff.1 hx @[to_additive] lemma prod_fintype [fintype α] (f : α →₀ M) (g : α → M → N) (h : ∀ i, g i 0 = 1) : f.prod g = ∏ i, g i (f i) := f.prod_of_support_subset (subset_univ _) g (λ x _, h x) @[simp, to_additive] lemma prod_single_index {a : α} {b : M} {h : α → M → N} (h_zero : h a 0 = 1) : (single a b).prod h = h a b := calc (single a b).prod h = ∏ x in {a}, h x (single a b x) : prod_of_support_subset _ support_single_subset h $ λ x hx, (mem_singleton.1 hx).symm ▸ h_zero ... = h a b : by simp @[to_additive] lemma prod_map_range_index {f : M → M'} {hf : f 0 = 0} {g : α →₀ M} {h : α → M' → N} (h0 : ∀a, h a 0 = 1) : (map_range f hf g).prod h = g.prod (λa b, h a (f b)) := finset.prod_subset support_map_range $ λ _ _ H, by rw [not_mem_support_iff.1 H, h0] @[simp, to_additive] lemma prod_zero_index {h : α → M → N} : (0 : α →₀ M).prod h = 1 := rfl @[to_additive] lemma prod_comm (f : α →₀ M) (g : β →₀ M') (h : α → M → β → M' → N) : f.prod (λ x v, g.prod (λ x' v', h x v x' v')) = g.prod (λ x' v', f.prod (λ x v, h x v x' v')) := finset.prod_comm @[simp, to_additive] lemma prod_ite_eq [decidable_eq α] (f : α →₀ M) (a : α) (b : α → M → N) : f.prod (λ x v, ite (a = x) (b x v) 1) = ite (a ∈ f.support) (b a (f a)) 1 := by { dsimp [finsupp.prod], rw f.support.prod_ite_eq, } @[simp] lemma sum_ite_self_eq [decidable_eq α] {N : Type*} [add_comm_monoid N] (f : α →₀ N) (a : α) : f.sum (λ x v, ite (a = x) v 0) = f a := by { convert f.sum_ite_eq a (λ x, id), simp [ite_eq_right_iff.2 eq.symm] } /-- A restatement of `prod_ite_eq` with the equality test reversed. -/ @[simp, to_additive "A restatement of `sum_ite_eq` with the equality test reversed."] lemma prod_ite_eq' [decidable_eq α] (f : α →₀ M) (a : α) (b : α → M → N) : f.prod (λ x v, ite (x = a) (b x v) 1) = ite (a ∈ f.support) (b a (f a)) 1 := by { dsimp [finsupp.prod], rw f.support.prod_ite_eq', } @[simp] lemma sum_ite_self_eq' [decidable_eq α] {N : Type*} [add_comm_monoid N] (f : α →₀ N) (a : α) : f.sum (λ x v, ite (x = a) v 0) = f a := by { convert f.sum_ite_eq' a (λ x, id), simp [ite_eq_right_iff.2 eq.symm] } @[simp] lemma prod_pow [fintype α] (f : α →₀ ℕ) (g : α → N) : f.prod (λ a b, g a ^ b) = ∏ a, g a ^ (f a) := f.prod_fintype _ $ λ a, pow_zero _ /-- If `g` maps a second argument of 0 to 1, then multiplying it over the result of `on_finset` is the same as multiplying it over the original `finset`. -/ @[to_additive "If `g` maps a second argument of 0 to 0, summing it over the result of `on_finset` is the same as summing it over the original `finset`."] lemma on_finset_prod {s : finset α} {f : α → M} {g : α → M → N} (hf : ∀a, f a ≠ 0 → a ∈ s) (hg : ∀ a, g a 0 = 1) : (on_finset s f hf).prod g = ∏ a in s, g a (f a) := finset.prod_subset support_on_finset_subset $ by simp [*] { contextual := tt } /-- Taking a product over `f : α →₀ M` is the same as multiplying the value on a single element `y ∈ f.support` by the product over `erase y f`. -/ @[to_additive /-" Taking a sum over over `f : α →₀ M` is the same as adding the value on a single element `y ∈ f.support` to the sum over `erase y f`. "-/] lemma mul_prod_erase (f : α →₀ M) (y : α) (g : α → M → N) (hyf : y ∈ f.support) : g y (f y) * (erase y f).prod g = f.prod g := begin rw [finsupp.prod, finsupp.prod, ←finset.mul_prod_erase _ _ hyf, finsupp.support_erase, finset.prod_congr rfl], intros h hx, rw finsupp.erase_ne (ne_of_mem_erase hx), end /-- Generalization of `finsupp.mul_prod_erase`: if `g` maps a second argument of 0 to 1, then its product over `f : α →₀ M` is the same as multiplying the value on any element `y : α` by the product over `erase y f`. -/ @[to_additive /-" Generalization of `finsupp.add_sum_erase`: if `g` maps a second argument of 0 to 0, then its sum over `f : α →₀ M` is the same as adding the value on any element `y : α` to the sum over `erase y f`. "-/] lemma mul_prod_erase' (f : α →₀ M) (y : α) (g : α → M → N) (hg : ∀ (i : α), g i 0 = 1) : g y (f y) * (erase y f).prod g = f.prod g := begin classical, by_cases hyf : y ∈ f.support, { exact finsupp.mul_prod_erase f y g hyf }, { rw [not_mem_support_iff.mp hyf, hg y, erase_of_not_mem_support hyf, one_mul] }, end @[to_additive] lemma _root_.submonoid.finsupp_prod_mem (S : submonoid N) (f : α →₀ M) (g : α → M → N) (h : ∀ c, f c ≠ 0 → g c (f c) ∈ S) : f.prod g ∈ S := S.prod_mem $ λ i hi, h _ (finsupp.mem_support_iff.mp hi) @[to_additive] lemma prod_congr {f : α →₀ M} {g1 g2 : α → M → N} (h : ∀ x ∈ f.support, g1 x (f x) = g2 x (f x)) : f.prod g1 = f.prod g2 := finset.prod_congr rfl h end sum_prod /-! ### Additive monoid structure on `α →₀ M` -/ section add_zero_class variables [add_zero_class M] instance : has_add (α →₀ M) := ⟨zip_with (+) (add_zero 0)⟩ @[simp] lemma coe_add (f g : α →₀ M) : ⇑(f + g) = f + g := rfl lemma add_apply (g₁ g₂ : α →₀ M) (a : α) : (g₁ + g₂) a = g₁ a + g₂ a := rfl lemma support_add [decidable_eq α] {g₁ g₂ : α →₀ M} : (g₁ + g₂).support ⊆ g₁.support ∪ g₂.support := support_zip_with lemma support_add_eq [decidable_eq α] {g₁ g₂ : α →₀ M} (h : disjoint g₁.support g₂.support) : (g₁ + g₂).support = g₁.support ∪ g₂.support := le_antisymm support_zip_with $ assume a ha, (finset.mem_union.1 ha).elim (assume ha, have a ∉ g₂.support, from disjoint_left.1 h ha, by simp only [mem_support_iff, not_not] at *; simpa only [add_apply, this, add_zero]) (assume ha, have a ∉ g₁.support, from disjoint_right.1 h ha, by simp only [mem_support_iff, not_not] at *; simpa only [add_apply, this, zero_add]) @[simp] lemma single_add {a : α} {b₁ b₂ : M} : single a (b₁ + b₂) = single a b₁ + single a b₂ := ext $ assume a', begin by_cases h : a = a', { rw [h, add_apply, single_eq_same, single_eq_same, single_eq_same] }, { rw [add_apply, single_eq_of_ne h, single_eq_of_ne h, single_eq_of_ne h, zero_add] } end instance : add_zero_class (α →₀ M) := { zero := 0, add := (+), zero_add := assume ⟨s, f, hf⟩, ext $ assume a, zero_add _, add_zero := assume ⟨s, f, hf⟩, ext $ assume a, add_zero _ } /-- `finsupp.single` as an `add_monoid_hom`. See `finsupp.lsingle` for the stronger version as a linear map. -/ @[simps] def single_add_hom (a : α) : M →+ α →₀ M := ⟨single a, single_zero, λ _ _, single_add⟩ /-- Evaluation of a function `f : α →₀ M` at a point as an additive monoid homomorphism. See `finsupp.lapply` for the stronger version as a linear map. -/ @[simps apply] def apply_add_hom (a : α) : (α →₀ M) →+ M := ⟨λ g, g a, zero_apply, λ _ _, add_apply _ _ _⟩ /-- Coercion from a `finsupp` to a function type is an `add_monoid_hom`. -/ @[simps] noncomputable def coe_fn_add_hom : (α →₀ M) →+ (α → M) := { to_fun := coe_fn, map_zero' := coe_zero, map_add' := coe_add } lemma update_eq_single_add_erase (f : α →₀ M) (a : α) (b : M) : f.update a b = single a b + f.erase a := begin ext j, rcases eq_or_ne a j with rfl|h, { simp }, { simp [function.update_noteq h.symm, single_apply, h, erase_ne, h.symm] } end lemma update_eq_erase_add_single (f : α →₀ M) (a : α) (b : M) : f.update a b = f.erase a + single a b := begin ext j, rcases eq_or_ne a j with rfl|h, { simp }, { simp [function.update_noteq h.symm, single_apply, h, erase_ne, h.symm] } end lemma single_add_erase (a : α) (f : α →₀ M) : single a (f a) + f.erase a = f := by rw [←update_eq_single_add_erase, update_self] lemma erase_add_single (a : α) (f : α →₀ M) : f.erase a + single a (f a) = f := by rw [←update_eq_erase_add_single, update_self] @[simp] lemma erase_add (a : α) (f f' : α →₀ M) : erase a (f + f') = erase a f + erase a f' := begin ext s, by_cases hs : s = a, { rw [hs, add_apply, erase_same, erase_same, erase_same, add_zero] }, rw [add_apply, erase_ne hs, erase_ne hs, erase_ne hs, add_apply], end /-- `finsupp.erase` as an `add_monoid_hom`. -/ @[simps] def erase_add_hom (a : α) : (α →₀ M) →+ (α →₀ M) := { to_fun := erase a, map_zero' := erase_zero a, map_add' := erase_add a } @[elab_as_eliminator] protected theorem induction {p : (α →₀ M) → Prop} (f : α →₀ M) (h0 : p 0) (ha : ∀a b (f : α →₀ M), a ∉ f.support → b ≠ 0 → p f → p (single a b + f)) : p f := suffices ∀s (f : α →₀ M), f.support = s → p f, from this _ _ rfl, assume s, finset.induction_on s (λ f hf, by rwa [support_eq_empty.1 hf]) $ assume a s has ih f hf, suffices p (single a (f a) + f.erase a), by rwa [single_add_erase] at this, begin apply ha, { rw [support_erase, mem_erase], exact λ H, H.1 rfl }, { rw [← mem_support_iff, hf], exact mem_insert_self _ _ }, { apply ih _ _, rw [support_erase, hf, finset.erase_insert has] } end lemma induction₂ {p : (α →₀ M) → Prop} (f : α →₀ M) (h0 : p 0) (ha : ∀a b (f : α →₀ M), a ∉ f.support → b ≠ 0 → p f → p (f + single a b)) : p f := suffices ∀s (f : α →₀ M), f.support = s → p f, from this _ _ rfl, assume s, finset.induction_on s (λ f hf, by rwa [support_eq_empty.1 hf]) $ assume a s has ih f hf, suffices p (f.erase a + single a (f a)), by rwa [erase_add_single] at this, begin apply ha, { rw [support_erase, mem_erase], exact λ H, H.1 rfl }, { rw [← mem_support_iff, hf], exact mem_insert_self _ _ }, { apply ih _ _, rw [support_erase, hf, finset.erase_insert has] } end lemma induction_linear {p : (α →₀ M) → Prop} (f : α →₀ M) (h0 : p 0) (hadd : ∀ f g : α →₀ M, p f → p g → p (f + g)) (hsingle : ∀ a b, p (single a b)) : p f := induction₂ f h0 (λ a b f _ _ w, hadd _ _ w (hsingle _ _)) @[simp] lemma add_closure_set_of_eq_single : add_submonoid.closure {f : α →₀ M | ∃ a b, f = single a b} = ⊤ := top_unique $ λ x hx, finsupp.induction x (add_submonoid.zero_mem _) $ λ a b f ha hb hf, add_submonoid.add_mem _ (add_submonoid.subset_closure $ ⟨a, b, rfl⟩) hf /-- If two additive homomorphisms from `α →₀ M` are equal on each `single a b`, then they are equal. -/ lemma add_hom_ext [add_zero_class N] ⦃f g : (α →₀ M) →+ N⦄ (H : ∀ x y, f (single x y) = g (single x y)) : f = g := begin refine add_monoid_hom.eq_of_eq_on_mdense add_closure_set_of_eq_single _, rintro _ ⟨x, y, rfl⟩, apply H end /-- If two additive homomorphisms from `α →₀ M` are equal on each `single a b`, then they are equal. We formulate this using equality of `add_monoid_hom`s so that `ext` tactic can apply a type-specific extensionality lemma after this one. E.g., if the fiber `M` is `ℕ` or `ℤ`, then it suffices to verify `f (single a 1) = g (single a 1)`. -/ @[ext] lemma add_hom_ext' [add_zero_class N] ⦃f g : (α →₀ M) →+ N⦄ (H : ∀ x, f.comp (single_add_hom x) = g.comp (single_add_hom x)) : f = g := add_hom_ext $ λ x, add_monoid_hom.congr_fun (H x) lemma mul_hom_ext [mul_one_class N] ⦃f g : multiplicative (α →₀ M) →* N⦄ (H : ∀ x y, f (multiplicative.of_add $ single x y) = g (multiplicative.of_add $ single x y)) : f = g := monoid_hom.ext $ add_monoid_hom.congr_fun $ @add_hom_ext α M (additive N) _ _ f.to_additive'' g.to_additive'' H @[ext] lemma mul_hom_ext' [mul_one_class N] {f g : multiplicative (α →₀ M) →* N} (H : ∀ x, f.comp (single_add_hom x).to_multiplicative = g.comp (single_add_hom x).to_multiplicative) : f = g := mul_hom_ext $ λ x, monoid_hom.congr_fun (H x) lemma map_range_add [add_zero_class N] {f : M → N} {hf : f 0 = 0} (hf' : ∀ x y, f (x + y) = f x + f y) (v₁ v₂ : α →₀ M) : map_range f hf (v₁ + v₂) = map_range f hf v₁ + map_range f hf v₂ := ext $ λ a, by simp only [hf', add_apply, map_range_apply] /-- Bundle `emb_domain f` as an additive map from `α →₀ M` to `β →₀ M`. -/ @[simps] def emb_domain.add_monoid_hom (f : α ↪ β) : (α →₀ M) →+ β →₀ M := { to_fun := λ v, emb_domain f v, map_zero' := by simp, map_add' := λ v w, begin ext b, by_cases h : b ∈ set.range f, { rcases h with ⟨a, rfl⟩, simp, }, { simp [emb_domain_notin_range, h], }, end, } @[simp] lemma emb_domain_add (f : α ↪ β) (v w : α →₀ M) : emb_domain f (v + w) = emb_domain f v + emb_domain f w := (emb_domain.add_monoid_hom f).map_add v w end add_zero_class section add_monoid variables [add_monoid M] instance : add_monoid (α →₀ M) := { add_monoid . zero := 0, add := (+), add_assoc := assume ⟨s, f, hf⟩ ⟨t, g, hg⟩ ⟨u, h, hh⟩, ext $ assume a, add_assoc _ _ _, nsmul := λ n v, v.map_range ((•) n) (nsmul_zero _), nsmul_zero' := λ v, by { ext i, simp }, nsmul_succ' := λ n v, by { ext i, simp [nat.succ_eq_one_add, add_nsmul] }, .. finsupp.add_zero_class } end add_monoid end finsupp @[to_additive] lemma mul_equiv.map_finsupp_prod [has_zero M] [comm_monoid N] [comm_monoid P] (h : N ≃* P) (f : α →₀ M) (g : α → M → N) : h (f.prod g) = f.prod (λ a b, h (g a b)) := h.map_prod _ _ @[to_additive] lemma monoid_hom.map_finsupp_prod [has_zero M] [comm_monoid N] [comm_monoid P] (h : N →* P) (f : α →₀ M) (g : α → M → N) : h (f.prod g) = f.prod (λ a b, h (g a b)) := h.map_prod _ _ lemma ring_hom.map_finsupp_sum [has_zero M] [semiring R] [semiring S] (h : R →+* S) (f : α →₀ M) (g : α → M → R) : h (f.sum g) = f.sum (λ a b, h (g a b)) := h.map_sum _ _ lemma ring_hom.map_finsupp_prod [has_zero M] [comm_semiring R] [comm_semiring S] (h : R →+* S) (f : α →₀ M) (g : α → M → R) : h (f.prod g) = f.prod (λ a b, h (g a b)) := h.map_prod _ _ @[to_additive] lemma monoid_hom.coe_finsupp_prod [has_zero β] [monoid N] [comm_monoid P] (f : α →₀ β) (g : α → β → N →* P) : ⇑(f.prod g) = f.prod (λ i fi, g i fi) := monoid_hom.coe_prod _ _ @[simp, to_additive] lemma monoid_hom.finsupp_prod_apply [has_zero β] [monoid N] [comm_monoid P] (f : α →₀ β) (g : α → β → N →* P) (x : N) : f.prod g x = f.prod (λ i fi, g i fi x) := monoid_hom.finset_prod_apply _ _ _ namespace finsupp instance [add_comm_monoid M] : add_comm_monoid (α →₀ M) := { add_comm := assume ⟨s, f, _⟩ ⟨t, g, _⟩, ext $ assume a, add_comm _ _, .. finsupp.add_monoid } instance [add_group G] : has_sub (α →₀ G) := ⟨zip_with has_sub.sub (sub_zero _)⟩ instance [add_group G] : add_group (α →₀ G) := { neg := map_range (has_neg.neg) neg_zero, sub := has_sub.sub, sub_eq_add_neg := λ x y, ext (λ i, sub_eq_add_neg _ _), add_left_neg := assume ⟨s, f, _⟩, ext $ assume x, add_left_neg _, zsmul := λ n v, v.map_range ((•) n) (zsmul_zero _), zsmul_zero' := λ v, by { ext i, simp }, zsmul_succ' := λ n v, by { ext i, simp [nat.succ_eq_one_add, add_zsmul] }, zsmul_neg' := λ n v, by { ext i, simp only [nat.succ_eq_add_one, map_range_apply, zsmul_neg_succ_of_nat, int.coe_nat_succ, neg_inj, add_zsmul, add_nsmul, one_zsmul, coe_nat_zsmul, one_nsmul] }, .. finsupp.add_monoid } instance [add_comm_group G] : add_comm_group (α →₀ G) := { add_comm := add_comm, ..finsupp.add_group } lemma single_multiset_sum [add_comm_monoid M] (s : multiset M) (a : α) : single a s.sum = (s.map (single a)).sum := multiset.induction_on s single_zero $ λ a s ih, by rw [multiset.sum_cons, single_add, ih, multiset.map_cons, multiset.sum_cons] lemma single_finset_sum [add_comm_monoid M] (s : finset ι) (f : ι → M) (a : α) : single a (∑ b in s, f b) = ∑ b in s, single a (f b) := begin transitivity, apply single_multiset_sum, rw [multiset.map_map], refl end lemma single_sum [has_zero M] [add_comm_monoid N] (s : ι →₀ M) (f : ι → M → N) (a : α) : single a (s.sum f) = s.sum (λd c, single a (f d c)) := single_finset_sum _ _ _ @[to_additive] lemma prod_neg_index [add_group G] [comm_monoid M] {g : α →₀ G} {h : α → G → M} (h0 : ∀a, h a 0 = 1) : (-g).prod h = g.prod (λa b, h a (- b)) := prod_map_range_index h0 @[simp] lemma coe_neg [add_group G] (g : α →₀ G) : ⇑(-g) = -g := rfl lemma neg_apply [add_group G] (g : α →₀ G) (a : α) : (- g) a = - g a := rfl @[simp] lemma coe_sub [add_group G] (g₁ g₂ : α →₀ G) : ⇑(g₁ - g₂) = g₁ - g₂ := rfl lemma sub_apply [add_group G] (g₁ g₂ : α →₀ G) (a : α) : (g₁ - g₂) a = g₁ a - g₂ a := rfl @[simp] lemma support_neg [add_group G] (f : α →₀ G) : support (-f) = support f := finset.subset.antisymm support_map_range (calc support f = support (- (- f)) : congr_arg support (neg_neg _).symm ... ⊆ support (- f) : support_map_range) lemma support_sub [decidable_eq α] [add_group G] {f g : α →₀ G} : support (f - g) ⊆ support f ∪ support g := begin rw [sub_eq_add_neg, ←support_neg g], exact support_add, end lemma erase_eq_sub_single [add_group G] (f : α →₀ G) (a : α) : f.erase a = f - single a (f a) := begin ext a', rcases eq_or_ne a a' with rfl|h, { simp }, { simp [erase_ne h.symm, single_eq_of_ne h] } end lemma update_eq_sub_add_single [add_group G] (f : α →₀ G) (a : α) (b : G) : f.update a b = f - single a (f a) + single a b := by rw [update_eq_erase_add_single, erase_eq_sub_single] lemma finset_sum_apply [add_comm_monoid N] (S : finset ι) (f : ι → α →₀ N) (a : α) : (∑ i in S, f i) a = ∑ i in S, f i a := (apply_add_hom a : (α →₀ N) →+ _).map_sum _ _ @[simp] lemma sum_apply [has_zero M] [add_comm_monoid N] {f : α →₀ M} {g : α → M → β →₀ N} {a₂ : β} : (f.sum g) a₂ = f.sum (λa₁ b, g a₁ b a₂) := finset_sum_apply _ _ _ lemma coe_finset_sum [add_comm_monoid N] (S : finset ι) (f : ι → α →₀ N) : ⇑(∑ i in S, f i) = ∑ i in S, f i := (coe_fn_add_hom : (α →₀ N) →+ _).map_sum _ _ lemma coe_sum [has_zero M] [add_comm_monoid N] (f : α →₀ M) (g : α → M → β →₀ N) : ⇑(f.sum g) = f.sum (λ a₁ b, g a₁ b) := coe_finset_sum _ _ lemma support_sum [decidable_eq β] [has_zero M] [add_comm_monoid N] {f : α →₀ M} {g : α → M → (β →₀ N)} : (f.sum g).support ⊆ f.support.bUnion (λa, (g a (f a)).support) := have ∀ c, f.sum (λ a b, g a b c) ≠ 0 → (∃ a, f a ≠ 0 ∧ ¬ (g a (f a)) c = 0), from assume a₁ h, let ⟨a, ha, ne⟩ := finset.exists_ne_zero_of_sum_ne_zero h in ⟨a, mem_support_iff.mp ha, ne⟩, by simpa only [finset.subset_iff, mem_support_iff, finset.mem_bUnion, sum_apply, exists_prop] lemma support_finset_sum [decidable_eq β] [add_comm_monoid M] {s : finset α} {f : α → (β →₀ M)} : (finset.sum s f).support ⊆ s.bUnion (λ x, (f x).support) := begin rw ←finset.sup_eq_bUnion, induction s using finset.cons_induction_on with a s ha ih, { refl }, { rw [finset.sum_cons, finset.sup_cons], exact support_add.trans (finset.union_subset_union (finset.subset.refl _) ih), }, end @[simp] lemma sum_zero [has_zero M] [add_comm_monoid N] {f : α →₀ M} : f.sum (λa b, (0 : N)) = 0 := finset.sum_const_zero @[simp, to_additive] lemma prod_mul [has_zero M] [comm_monoid N] {f : α →₀ M} {h₁ h₂ : α → M → N} : f.prod (λa b, h₁ a b * h₂ a b) = f.prod h₁ * f.prod h₂ := finset.prod_mul_distrib @[simp, to_additive] lemma prod_inv [has_zero M] [comm_group G] {f : α →₀ M} {h : α → M → G} : f.prod (λa b, (h a b)⁻¹) = (f.prod h)⁻¹ := (((monoid_hom.id G)⁻¹).map_prod _ _).symm @[simp] lemma sum_sub [has_zero M] [add_comm_group G] {f : α →₀ M} {h₁ h₂ : α → M → G} : f.sum (λa b, h₁ a b - h₂ a b) = f.sum h₁ - f.sum h₂ := finset.sum_sub_distrib @[to_additive] lemma prod_add_index [add_comm_monoid M] [comm_monoid N] {f g : α →₀ M} {h : α → M → N} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) : (f + g).prod h = f.prod h * g.prod h := have hf : f.prod h = ∏ a in f.support ∪ g.support, h a (f a), from f.prod_of_support_subset (subset_union_left _ _) _ $ λ a ha, h_zero a, have hg : g.prod h = ∏ a in f.support ∪ g.support, h a (g a), from g.prod_of_support_subset (subset_union_right _ _) _ $ λ a ha, h_zero a, have hfg : (f + g).prod h = ∏ a in f.support ∪ g.support, h a ((f + g) a), from (f + g).prod_of_support_subset support_add _ $ λ a ha, h_zero a, by simp only [*, add_apply, prod_mul_distrib] @[simp] lemma sum_add_index' [add_comm_monoid M] [add_comm_monoid N] {f g : α →₀ M} (h : α → M →+ N) : (f + g).sum (λ x, h x) = f.sum (λ x, h x) + g.sum (λ x, h x) := sum_add_index (λ a, (h a).map_zero) (λ a, (h a).map_add) @[simp] lemma prod_add_index' [add_comm_monoid M] [comm_monoid N] {f g : α →₀ M} (h : α → multiplicative M →* N) : (f + g).prod (λ a b, h a (multiplicative.of_add b)) = f.prod (λ a b, h a (multiplicative.of_add b)) * g.prod (λ a b, h a (multiplicative.of_add b)) := prod_add_index (λ a, (h a).map_one) (λ a, (h a).map_mul) /-- The canonical isomorphism between families of additive monoid homomorphisms `α → (M →+ N)` and monoid homomorphisms `(α →₀ M) →+ N`. -/ def lift_add_hom [add_comm_monoid M] [add_comm_monoid N] : (α → M →+ N) ≃+ ((α →₀ M) →+ N) := { to_fun := λ F, { to_fun := λ f, f.sum (λ x, F x), map_zero' := finset.sum_empty, map_add' := λ _ _, sum_add_index (λ x, (F x).map_zero) (λ x, (F x).map_add) }, inv_fun := λ F x, F.comp $ single_add_hom x, left_inv := λ F, by { ext, simp }, right_inv := λ F, by { ext, simp }, map_add' := λ F G, by { ext, simp } } @[simp] lemma lift_add_hom_apply [add_comm_monoid M] [add_comm_monoid N] (F : α → M →+ N) (f : α →₀ M) : lift_add_hom F f = f.sum (λ x, F x) := rfl @[simp] lemma lift_add_hom_symm_apply [add_comm_monoid M] [add_comm_monoid N] (F : (α →₀ M) →+ N) (x : α) : lift_add_hom.symm F x = F.comp (single_add_hom x) := rfl lemma lift_add_hom_symm_apply_apply [add_comm_monoid M] [add_comm_monoid N] (F : (α →₀ M) →+ N) (x : α) (y : M) : lift_add_hom.symm F x y = F (single x y) := rfl @[simp] lemma lift_add_hom_single_add_hom [add_comm_monoid M] : lift_add_hom (single_add_hom : α → M →+ α →₀ M) = add_monoid_hom.id _ := lift_add_hom.to_equiv.apply_eq_iff_eq_symm_apply.2 rfl @[simp] lemma sum_single [add_comm_monoid M] (f : α →₀ M) : f.sum single = f := add_monoid_hom.congr_fun lift_add_hom_single_add_hom f @[simp] lemma lift_add_hom_apply_single [add_comm_monoid M] [add_comm_monoid N] (f : α → M →+ N) (a : α) (b : M) : lift_add_hom f (single a b) = f a b := sum_single_index (f a).map_zero @[simp] lemma lift_add_hom_comp_single [add_comm_monoid M] [add_comm_monoid N] (f : α → M →+ N) (a : α) : (lift_add_hom f).comp (single_add_hom a) = f a := add_monoid_hom.ext $ λ b, lift_add_hom_apply_single f a b lemma comp_lift_add_hom [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] (g : N →+ P) (f : α → M →+ N) : g.comp (lift_add_hom f) = lift_add_hom (λ a, g.comp (f a)) := lift_add_hom.symm_apply_eq.1 $ funext $ λ a, by rw [lift_add_hom_symm_apply, add_monoid_hom.comp_assoc, lift_add_hom_comp_single] lemma sum_sub_index [add_comm_group β] [add_comm_group γ] {f g : α →₀ β} {h : α → β → γ} (h_sub : ∀a b₁ b₂, h a (b₁ - b₂) = h a b₁ - h a b₂) : (f - g).sum h = f.sum h - g.sum h := (lift_add_hom (λ a, add_monoid_hom.of_map_sub (h a) (h_sub a))).map_sub f g @[to_additive] lemma prod_emb_domain [has_zero M] [comm_monoid N] {v : α →₀ M} {f : α ↪ β} {g : β → M → N} : (v.emb_domain f).prod g = v.prod (λ a b, g (f a) b) := begin rw [prod, prod, support_emb_domain, finset.prod_map], simp_rw emb_domain_apply, end @[to_additive] lemma prod_finset_sum_index [add_comm_monoid M] [comm_monoid N] {s : finset ι} {g : ι → α →₀ M} {h : α → M → N} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) : ∏ i in s, (g i).prod h = (∑ i in s, g i).prod h := finset.induction_on s rfl $ λ a s has ih, by rw [prod_insert has, ih, sum_insert has, prod_add_index h_zero h_add] @[to_additive] lemma prod_sum_index [add_comm_monoid M] [add_comm_monoid N] [comm_monoid P] {f : α →₀ M} {g : α → M → β →₀ N} {h : β → N → P} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) : (f.sum g).prod h = f.prod (λa b, (g a b).prod h) := (prod_finset_sum_index h_zero h_add).symm lemma multiset_sum_sum_index [add_comm_monoid M] [add_comm_monoid N] (f : multiset (α →₀ M)) (h : α → M → N) (h₀ : ∀a, h a 0 = 0) (h₁ : ∀ (a : α) (b₁ b₂ : M), h a (b₁ + b₂) = h a b₁ + h a b₂) : (f.sum.sum h) = (f.map $ λg:α →₀ M, g.sum h).sum := multiset.induction_on f rfl $ assume a s ih, by rw [multiset.sum_cons, multiset.map_cons, multiset.sum_cons, sum_add_index h₀ h₁, ih] lemma support_sum_eq_bUnion {α : Type*} {ι : Type*} {M : Type*} [add_comm_monoid M] {g : ι → α →₀ M} (s : finset ι) (h : ∀ i₁ i₂, i₁ ≠ i₂ → disjoint (g i₁).support (g i₂).support) : (∑ i in s, g i).support = s.bUnion (λ i, (g i).support) := begin apply finset.induction_on s, { simp }, { intros i s hi, simp only [hi, sum_insert, not_false_iff, bUnion_insert], intro hs, rw [finsupp.support_add_eq, hs], rw [hs], intros x hx, simp only [mem_bUnion, exists_prop, inf_eq_inter, ne.def, mem_inter] at hx, obtain ⟨hxi, j, hj, hxj⟩ := hx, have hn : i ≠ j := λ H, hi (H.symm ▸ hj), apply h _ _ hn, simp [hxi, hxj] } end lemma multiset_map_sum [has_zero M] {f : α →₀ M} {m : β → γ} {h : α → M → multiset β} : multiset.map m (f.sum h) = f.sum (λa b, (h a b).map m) := (multiset.map_add_monoid_hom m).map_sum _ f.support lemma multiset_sum_sum [has_zero M] [add_comm_monoid N] {f : α →₀ M} {h : α → M → multiset N} : multiset.sum (f.sum h) = f.sum (λa b, multiset.sum (h a b)) := (multiset.sum_add_monoid_hom : multiset N →+ N).map_sum _ f.support /-- For disjoint `f1` and `f2`, and function `g`, the product of the products of `g` over `f1` and `f2` equals the product of `g` over `f1 + f2` -/ lemma prod_add_index_of_disjoint [add_comm_monoid M] {f1 f2 : α →₀ M} (hd : disjoint f1.support f2.support) {β : Type*} [comm_monoid β] (g : α → M → β) : (f1 + f2).prod g = f1.prod g * f2.prod g := have ∀ {f1 f2 : α →₀ M}, disjoint f1.support f2.support → ∏ x in f1.support, g x (f1 x + f2 x) = f1.prod g := λ f1 f2 hd, finset.prod_congr rfl (λ x hx, by simp only [not_mem_support_iff.mp (disjoint_left.mp hd hx), add_zero]), by simp_rw [← this hd, ← this hd.symm, add_comm (f2 _), finsupp.prod, support_add_eq hd, prod_union hd, add_apply] section map_range section equiv variables [has_zero M] [has_zero N] [has_zero P] /-- `finsupp.map_range` as an equiv. -/ @[simps apply] def map_range.equiv (f : M ≃ N) (hf : f 0 = 0) (hf' : f.symm 0 = 0) : (α →₀ M) ≃ (α →₀ N) := { to_fun := (map_range f hf : (α →₀ M) → (α →₀ N)), inv_fun := (map_range f.symm hf' : (α →₀ N) → (α →₀ M)), left_inv := λ x, begin rw ←map_range_comp _ _ _ _; simp_rw equiv.symm_comp_self, { exact map_range_id _ }, { refl }, end, right_inv := λ x, begin rw ←map_range_comp _ _ _ _; simp_rw equiv.self_comp_symm, { exact map_range_id _ }, { refl }, end } @[simp] lemma map_range.equiv_refl : map_range.equiv (equiv.refl M) rfl rfl = equiv.refl (α →₀ M) := equiv.ext map_range_id lemma map_range.equiv_trans (f : M ≃ N) (hf : f 0 = 0) (hf') (f₂ : N ≃ P) (hf₂ : f₂ 0 = 0) (hf₂') : (map_range.equiv (f.trans f₂) (by rw [equiv.trans_apply, hf, hf₂]) (by rw [equiv.symm_trans_apply, hf₂', hf']) : (α →₀ _) ≃ _) = (map_range.equiv f hf hf').trans (map_range.equiv f₂ hf₂ hf₂') := equiv.ext $ map_range_comp _ _ _ _ _ @[simp] lemma map_range.equiv_symm (f : M ≃ N) (hf hf') : ((map_range.equiv f hf hf').symm : (α →₀ _) ≃ _) = map_range.equiv f.symm hf' hf := equiv.ext $ λ x, rfl end equiv section zero_hom variables [has_zero M] [has_zero N] [has_zero P] /-- Composition with a fixed zero-preserving homomorphism is itself an zero-preserving homomorphism on functions. -/ @[simps] def map_range.zero_hom (f : zero_hom M N) : zero_hom (α →₀ M) (α →₀ N) := { to_fun := (map_range f f.map_zero : (α →₀ M) → (α →₀ N)), map_zero' := map_range_zero } @[simp] lemma map_range.zero_hom_id : map_range.zero_hom (zero_hom.id M) = zero_hom.id (α →₀ M) := zero_hom.ext map_range_id lemma map_range.zero_hom_comp (f : zero_hom N P) (f₂ : zero_hom M N) : (map_range.zero_hom (f.comp f₂) : zero_hom (α →₀ _) _) = (map_range.zero_hom f).comp (map_range.zero_hom f₂) := zero_hom.ext $ map_range_comp _ _ _ _ _ end zero_hom section add_monoid_hom variables [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] /-- Composition with a fixed additive homomorphism is itself an additive homomorphism on functions. -/ @[simps] def map_range.add_monoid_hom (f : M →+ N) : (α →₀ M) →+ (α →₀ N) := { to_fun := (map_range f f.map_zero : (α →₀ M) → (α →₀ N)), map_zero' := map_range_zero, map_add' := λ a b, map_range_add f.map_add _ _ } @[simp] lemma map_range.add_monoid_hom_id : map_range.add_monoid_hom (add_monoid_hom.id M) = add_monoid_hom.id (α →₀ M) := add_monoid_hom.ext map_range_id lemma map_range.add_monoid_hom_comp (f : N →+ P) (f₂ : M →+ N) : (map_range.add_monoid_hom (f.comp f₂) : (α →₀ _) →+ _) = (map_range.add_monoid_hom f).comp (map_range.add_monoid_hom f₂) := add_monoid_hom.ext $ map_range_comp _ _ _ _ _ @[simp] lemma map_range.add_monoid_hom_to_zero_hom (f : M →+ N) : (map_range.add_monoid_hom f).to_zero_hom = (map_range.zero_hom f.to_zero_hom : zero_hom (α →₀ _) _) := zero_hom.ext $ λ _, rfl lemma map_range_multiset_sum (f : M →+ N) (m : multiset (α →₀ M)) : map_range f f.map_zero m.sum = (m.map $ λx, map_range f f.map_zero x).sum := (map_range.add_monoid_hom f : (α →₀ _) →+ _).map_multiset_sum _ lemma map_range_finset_sum (f : M →+ N) (s : finset ι) (g : ι → (α →₀ M)) : map_range f f.map_zero (∑ x in s, g x) = ∑ x in s, map_range f f.map_zero (g x) := (map_range.add_monoid_hom f : (α →₀ _) →+ _).map_sum _ _ /-- `finsupp.map_range.add_monoid_hom` as an equiv. -/ @[simps apply] def map_range.add_equiv (f : M ≃+ N) : (α →₀ M) ≃+ (α →₀ N) := { to_fun := (map_range f f.map_zero : (α →₀ M) → (α →₀ N)), inv_fun := (map_range f.symm f.symm.map_zero : (α →₀ N) → (α →₀ M)), left_inv := λ x, begin rw ←map_range_comp _ _ _ _; simp_rw add_equiv.symm_comp_self, { exact map_range_id _ }, { refl }, end, right_inv := λ x, begin rw ←map_range_comp _ _ _ _; simp_rw add_equiv.self_comp_symm, { exact map_range_id _ }, { refl }, end, ..(map_range.add_monoid_hom f.to_add_monoid_hom) } @[simp] lemma map_range.add_equiv_refl : map_range.add_equiv (add_equiv.refl M) = add_equiv.refl (α →₀ M) := add_equiv.ext map_range_id lemma map_range.add_equiv_trans (f : M ≃+ N) (f₂ : N ≃+ P) : (map_range.add_equiv (f.trans f₂) : (α →₀ _) ≃+ _) = (map_range.add_equiv f).trans (map_range.add_equiv f₂) := add_equiv.ext $ map_range_comp _ _ _ _ _ @[simp] lemma map_range.add_equiv_symm (f : M ≃+ N) : ((map_range.add_equiv f).symm : (α →₀ _) ≃+ _) = map_range.add_equiv f.symm := add_equiv.ext $ λ x, rfl @[simp] lemma map_range.add_equiv_to_add_monoid_hom (f : M ≃+ N) : (map_range.add_equiv f : (α →₀ _) ≃+ _).to_add_monoid_hom = (map_range.add_monoid_hom f.to_add_monoid_hom : (α →₀ _) →+ _) := add_monoid_hom.ext $ λ _, rfl @[simp] lemma map_range.add_equiv_to_equiv (f : M ≃+ N) : (map_range.add_equiv f).to_equiv = (map_range.equiv f.to_equiv f.map_zero f.symm.map_zero : (α →₀ _) ≃ _) := equiv.ext $ λ _, rfl end add_monoid_hom end map_range /-! ### Declarations about `map_domain` -/ section map_domain variables [add_comm_monoid M] {v v₁ v₂ : α →₀ M} /-- Given `f : α → β` and `v : α →₀ M`, `map_domain f v : β →₀ M` is the finitely supported function whose value at `a : β` is the sum of `v x` over all `x` such that `f x = a`. -/ def map_domain (f : α → β) (v : α →₀ M) : β →₀ M := v.sum $ λa, single (f a) lemma map_domain_apply {f : α → β} (hf : function.injective f) (x : α →₀ M) (a : α) : map_domain f x (f a) = x a := begin rw [map_domain, sum_apply, sum, finset.sum_eq_single a, single_eq_same], { assume b _ hba, exact single_eq_of_ne (hf.ne hba) }, { assume h, rw [not_mem_support_iff.1 h, single_zero, zero_apply] } end lemma map_domain_notin_range {f : α → β} (x : α →₀ M) (a : β) (h : a ∉ set.range f) : map_domain f x a = 0 := begin rw [map_domain, sum_apply, sum], exact finset.sum_eq_zero (assume a' h', single_eq_of_ne $ assume eq, h $ eq ▸ set.mem_range_self _) end @[simp] lemma map_domain_id : map_domain id v = v := sum_single _ lemma map_domain_comp {f : α → β} {g : β → γ} : map_domain (g ∘ f) v = map_domain g (map_domain f v) := begin refine ((sum_sum_index _ _).trans _).symm, { intros, exact single_zero }, { intros, exact single_add }, refine sum_congr (λ _ _, sum_single_index _), { exact single_zero } end @[simp] lemma map_domain_single {f : α → β} {a : α} {b : M} : map_domain f (single a b) = single (f a) b := sum_single_index single_zero @[simp] lemma map_domain_zero {f : α → β} : map_domain f (0 : α →₀ M) = (0 : β →₀ M) := sum_zero_index lemma map_domain_congr {f g : α → β} (h : ∀x∈v.support, f x = g x) : v.map_domain f = v.map_domain g := finset.sum_congr rfl $ λ _ H, by simp only [h _ H] lemma map_domain_add {f : α → β} : map_domain f (v₁ + v₂) = map_domain f v₁ + map_domain f v₂ := sum_add_index (λ _, single_zero) (λ _ _ _, single_add) @[simp] lemma map_domain_equiv_apply {f : α ≃ β} (x : α →₀ M) (a : β) : map_domain f x a = x (f.symm a) := begin conv_lhs { rw ←f.apply_symm_apply a }, exact map_domain_apply f.injective _ _, end /-- `finsupp.map_domain` is an `add_monoid_hom`. -/ @[simps] def map_domain.add_monoid_hom (f : α → β) : (α →₀ M) →+ (β →₀ M) := { to_fun := map_domain f, map_zero' := map_domain_zero, map_add' := λ _ _, map_domain_add} @[simp] lemma map_domain.add_monoid_hom_id : map_domain.add_monoid_hom id = add_monoid_hom.id (α →₀ M) := add_monoid_hom.ext $ λ _, map_domain_id lemma map_domain.add_monoid_hom_comp (f : β → γ) (g : α → β) : (map_domain.add_monoid_hom (f ∘ g) : (α →₀ M) →+ (γ →₀ M)) = (map_domain.add_monoid_hom f).comp (map_domain.add_monoid_hom g) := add_monoid_hom.ext $ λ _, map_domain_comp lemma map_domain_finset_sum {f : α → β} {s : finset ι} {v : ι → α →₀ M} : map_domain f (∑ i in s, v i) = ∑ i in s, map_domain f (v i) := (map_domain.add_monoid_hom f : (α →₀ M) →+ β →₀ M).map_sum _ _ lemma map_domain_sum [has_zero N] {f : α → β} {s : α →₀ N} {v : α → N → α →₀ M} : map_domain f (s.sum v) = s.sum (λa b, map_domain f (v a b)) := (map_domain.add_monoid_hom f : (α →₀ M) →+ β →₀ M).map_finsupp_sum _ _ lemma map_domain_support [decidable_eq β] {f : α → β} {s : α →₀ M} : (s.map_domain f).support ⊆ s.support.image f := finset.subset.trans support_sum $ finset.subset.trans (finset.bUnion_mono $ assume a ha, support_single_subset) $ by rw [finset.bUnion_singleton]; exact subset.refl _ lemma map_domain_apply' (S : set α) {f : α → β} (x : α →₀ M) (hS : (x.support : set α) ⊆ S) (hf : set.inj_on f S) {a : α} (ha : a ∈ S) : map_domain f x (f a) = x a := begin rw [map_domain, sum_apply, sum], simp_rw single_apply, have : ∀ (b : α) (ha1 : b ∈ x.support), (if f b = f a then x b else 0) = if f b = f a then x a else 0, { intros b hb, refine if_ctx_congr iff.rfl (λ hh, _) (λ _, rfl), rw hf (hS hb) ha hh, }, conv in (ite _ _ _) { rw [this _ H], }, by_cases ha : a ∈ x.support, { rw [← finset.add_sum_erase _ _ ha, if_pos rfl], convert add_zero _, have : ∀ i ∈ x.support.erase a, f i ≠ f a, { intros i hi, exact (finset.ne_of_mem_erase hi) ∘ (hf (hS $ finset.mem_of_mem_erase hi) (hS ha)), }, conv in (ite _ _ _) { rw if_neg (this x H), }, exact finset.sum_const_zero, }, { rw [mem_support_iff, not_not] at ha, simp [ha], } end lemma map_domain_support_of_inj_on [decidable_eq β] {f : α → β} (s : α →₀ M) (hf : set.inj_on f s.support) : (map_domain f s).support = finset.image f s.support := finset.subset.antisymm map_domain_support $ begin intros x hx, simp only [mem_image, exists_prop, mem_support_iff, ne.def] at hx, rcases hx with ⟨hx_w, hx_h_left, rfl⟩, simp only [mem_support_iff, ne.def], rw map_domain_apply' (↑s.support : set _) _ _ hf, { exact hx_h_left, }, { simp only [mem_coe, mem_support_iff, ne.def], exact hx_h_left, }, { exact subset.refl _, }, end lemma map_domain_support_of_injective [decidable_eq β] {f : α → β} (hf : function.injective f) (s : α →₀ M) : (map_domain f s).support = finset.image f s.support := map_domain_support_of_inj_on s (hf.inj_on _) @[to_additive] lemma prod_map_domain_index [comm_monoid N] {f : α → β} {s : α →₀ M} {h : β → M → N} (h_zero : ∀b, h b 0 = 1) (h_add : ∀b m₁ m₂, h b (m₁ + m₂) = h b m₁ * h b m₂) : (map_domain f s).prod h = s.prod (λa m, h (f a) m) := (prod_sum_index h_zero h_add).trans $ prod_congr $ λ _ _, prod_single_index (h_zero _) /-- A version of `sum_map_domain_index` that takes a bundled `add_monoid_hom`, rather than separate linearity hypotheses. -/ -- Note that in `prod_map_domain_index`, `M` is still an additive monoid, -- so there is no analogous version in terms of `monoid_hom`. @[simp] lemma sum_map_domain_index_add_monoid_hom [add_comm_monoid N] {f : α → β} {s : α →₀ M} (h : β → M →+ N) : (map_domain f s).sum (λ b m, h b m) = s.sum (λ a m, h (f a) m) := @sum_map_domain_index _ _ _ _ _ _ _ _ (λ b m, h b m) (λ b, (h b).map_zero) (λ b m₁ m₂, (h b).map_add _ _) lemma emb_domain_eq_map_domain (f : α ↪ β) (v : α →₀ M) : emb_domain f v = map_domain f v := begin ext a, by_cases a ∈ set.range f, { rcases h with ⟨a, rfl⟩, rw [map_domain_apply f.injective, emb_domain_apply] }, { rw [map_domain_notin_range, emb_domain_notin_range]; assumption } end @[to_additive] lemma prod_map_domain_index_inj [comm_monoid N] {f : α → β} {s : α →₀ M} {h : β → M → N} (hf : function.injective f) : (s.map_domain f).prod h = s.prod (λa b, h (f a) b) := by rw [←function.embedding.coe_fn_mk f hf, ←emb_domain_eq_map_domain, prod_emb_domain] lemma map_domain_injective {f : α → β} (hf : function.injective f) : function.injective (map_domain f : (α →₀ M) → (β →₀ M)) := begin assume v₁ v₂ eq, ext a, have : map_domain f v₁ (f a) = map_domain f v₂ (f a), { rw eq }, rwa [map_domain_apply hf, map_domain_apply hf] at this, end /-- When `f` is an embedding we have an embedding `(α →₀ ℕ) ↪ (β →₀ ℕ)` given by `map_domain`. -/ @[simps] def map_domain_embedding {α β : Type*} (f : α ↪ β) : (α →₀ ℕ) ↪ β →₀ ℕ := ⟨finsupp.map_domain f, finsupp.map_domain_injective f.injective⟩ lemma map_domain.add_monoid_hom_comp_map_range [add_comm_monoid N] (f : α → β) (g : M →+ N) : (map_domain.add_monoid_hom f).comp (map_range.add_monoid_hom g) = (map_range.add_monoid_hom g).comp (map_domain.add_monoid_hom f) := by { ext, simp } /-- When `g` preserves addition, `map_range` and `map_domain` commute. -/ lemma map_domain_map_range [add_comm_monoid N] (f : α → β) (v : α →₀ M) (g : M → N) (h0 : g 0 = 0) (hadd : ∀ x y, g (x + y) = g x + g y) : map_domain f (map_range g h0 v) = map_range g h0 (map_domain f v) := let g' : M →+ N := { to_fun := g, map_zero' := h0, map_add' := hadd} in add_monoid_hom.congr_fun (map_domain.add_monoid_hom_comp_map_range f g') v lemma sum_update_add [add_comm_monoid α] [add_comm_monoid β] (f : ι →₀ α) (i : ι) (a : α) (g : ι → α → β) (hg : ∀ i, g i 0 = 0) (hgg : ∀ (j : ι) (a₁ a₂ : α), g j (a₁ + a₂) = g j a₁ + g j a₂) : (f.update i a).sum g + g i (f i) = f.sum g + g i a := begin rw [update_eq_erase_add_single, sum_add_index hg hgg], conv_rhs { rw ← finsupp.update_self f i }, rw [update_eq_erase_add_single, sum_add_index hg hgg, add_assoc, add_assoc], congr' 1, rw [add_comm, sum_single_index (hg _), sum_single_index (hg _)], end lemma map_domain_inj_on (S : set α) {f : α → β} (hf : set.inj_on f S) : set.inj_on (map_domain f : (α →₀ M) → (β →₀ M)) {w | (w.support : set α) ⊆ S} := begin intros v₁ hv₁ v₂ hv₂ eq, ext a, by_cases h : a ∈ v₁.support ∪ v₂.support, { rw [← map_domain_apply' S _ hv₁ hf _, ← map_domain_apply' S _ hv₂ hf _, eq]; { apply set.union_subset hv₁ hv₂, exact_mod_cast h, }, }, { simp only [decidable.not_or_iff_and_not, mem_union, not_not, mem_support_iff] at h, simp [h], }, end end map_domain /-! ### Declarations about `comap_domain` -/ section comap_domain /-- Given `f : α → β`, `l : β →₀ M` and a proof `hf` that `f` is injective on the preimage of `l.support`, `comap_domain f l hf` is the finitely supported function from `α` to `M` given by composing `l` with `f`. -/ def comap_domain [has_zero M] (f : α → β) (l : β →₀ M) (hf : set.inj_on f (f ⁻¹' ↑l.support)) : α →₀ M := { support := l.support.preimage f hf, to_fun := (λ a, l (f a)), mem_support_to_fun := begin intros a, simp only [finset.mem_def.symm, finset.mem_preimage], exact l.mem_support_to_fun (f a), end } @[simp] lemma comap_domain_apply [has_zero M] (f : α → β) (l : β →₀ M) (hf : set.inj_on f (f ⁻¹' ↑l.support)) (a : α) : comap_domain f l hf a = l (f a) := rfl lemma sum_comap_domain [has_zero M] [add_comm_monoid N] (f : α → β) (l : β →₀ M) (g : β → M → N) (hf : set.bij_on f (f ⁻¹' ↑l.support) ↑l.support) : (comap_domain f l hf.inj_on).sum (g ∘ f) = l.sum g := begin simp only [sum, comap_domain_apply, (∘)], simp [comap_domain, finset.sum_preimage_of_bij f _ _ (λ x, g x (l x))], end lemma eq_zero_of_comap_domain_eq_zero [add_comm_monoid M] (f : α → β) (l : β →₀ M) (hf : set.bij_on f (f ⁻¹' ↑l.support) ↑l.support) : comap_domain f l hf.inj_on = 0 → l = 0 := begin rw [← support_eq_empty, ← support_eq_empty, comap_domain], simp only [finset.ext_iff, finset.not_mem_empty, iff_false, mem_preimage], assume h a ha, cases hf.2.2 ha with b hb, exact h b (hb.2.symm ▸ ha) end lemma map_domain_comap_domain [add_comm_monoid M] (f : α → β) (l : β →₀ M) (hf : function.injective f) (hl : ↑l.support ⊆ set.range f): map_domain f (comap_domain f l (hf.inj_on _)) = l := begin ext a, by_cases h_cases: a ∈ set.range f, { rcases set.mem_range.1 h_cases with ⟨b, hb⟩, rw [hb.symm, map_domain_apply hf, comap_domain_apply] }, { rw map_domain_notin_range _ _ h_cases, by_contra h_contr, apply h_cases (hl $ finset.mem_coe.2 $ mem_support_iff.2 $ λ h, h_contr h.symm) } end end comap_domain section option /-- Restrict a finitely supported function on `option α` to a finitely supported function on `α`. -/ def some [has_zero M] (f : option α →₀ M) : α →₀ M := f.comap_domain option.some (λ _, by simp) @[simp] lemma some_apply [has_zero M] (f : option α →₀ M) (a : α) : f.some a = f (option.some a) := rfl @[simp] lemma some_zero [has_zero M] : (0 : option α →₀ M).some = 0 := by { ext, simp, } @[simp] lemma some_add [add_comm_monoid M] (f g : option α →₀ M) : (f + g).some = f.some + g.some := by { ext, simp, } @[simp] lemma some_single_none [has_zero M] (m : M) : (single none m : option α →₀ M).some = 0 := by { ext, simp, } @[simp] lemma some_single_some [has_zero M] (a : α) (m : M) : (single (option.some a) m : option α →₀ M).some = single a m := by { ext b, simp [single_apply], } @[to_additive] lemma prod_option_index [add_comm_monoid M] [comm_monoid N] (f : option α →₀ M) (b : option α → M → N) (h_zero : ∀ o, b o 0 = 1) (h_add : ∀ o m₁ m₂, b o (m₁ + m₂) = b o m₁ * b o m₂) : f.prod b = b none (f none) * f.some.prod (λ a, b (option.some a)) := begin apply induction_linear f, { simp [h_zero], }, { intros f₁ f₂ h₁ h₂, rw [finsupp.prod_add_index, h₁, h₂, some_add, finsupp.prod_add_index], simp only [h_add, pi.add_apply, finsupp.coe_add], rw mul_mul_mul_comm, all_goals { simp [h_zero, h_add], }, }, { rintros (_|a) m; simp [h_zero, h_add], } end lemma sum_option_index_smul [semiring R] [add_comm_monoid M] [module R M] (f : option α →₀ R) (b : option α → M) : f.sum (λ o r, r • b o) = f none • b none + f.some.sum (λ a r, r • b (option.some a)) := f.sum_option_index _ (λ _, zero_smul _ _) (λ _ _ _, add_smul _ _ _) end option /-! ### Declarations about `equiv_congr_left` -/ section equiv_congr_left variable [has_zero M] /-- Given `f : α ≃ β`, we can map `l : α →₀ M` to `equiv_map_domain f l : β →₀ M` (computably) by mapping the support forwards and the function backwards. -/ def equiv_map_domain (f : α ≃ β) (l : α →₀ M) : β →₀ M := { support := l.support.map f.to_embedding, to_fun := λ a, l (f.symm a), mem_support_to_fun := λ a, by simp only [finset.mem_map_equiv, mem_support_to_fun]; refl } @[simp] lemma equiv_map_domain_apply (f : α ≃ β) (l : α →₀ M) (b : β) : equiv_map_domain f l b = l (f.symm b) := rfl lemma equiv_map_domain_symm_apply (f : α ≃ β) (l : β →₀ M) (a : α) : equiv_map_domain f.symm l a = l (f a) := rfl @[simp] lemma equiv_map_domain_refl (l : α →₀ M) : equiv_map_domain (equiv.refl _) l = l := by ext x; refl lemma equiv_map_domain_refl' : equiv_map_domain (equiv.refl _) = @id (α →₀ M) := by ext x; refl lemma equiv_map_domain_trans (f : α ≃ β) (g : β ≃ γ) (l : α →₀ M) : equiv_map_domain (f.trans g) l = equiv_map_domain g (equiv_map_domain f l) := by ext x; refl lemma equiv_map_domain_trans' (f : α ≃ β) (g : β ≃ γ) : @equiv_map_domain _ _ M _ (f.trans g) = equiv_map_domain g ∘ equiv_map_domain f := by ext x; refl @[simp] lemma equiv_map_domain_single (f : α ≃ β) (a : α) (b : M) : equiv_map_domain f (single a b) = single (f a) b := by ext x; simp only [single_apply, equiv.apply_eq_iff_eq_symm_apply, equiv_map_domain_apply]; congr @[simp] lemma equiv_map_domain_zero {f : α ≃ β} : equiv_map_domain f (0 : α →₀ M) = (0 : β →₀ M) := by ext x; simp only [equiv_map_domain_apply, coe_zero, pi.zero_apply] lemma equiv_map_domain_eq_map_domain {M} [add_comm_monoid M] (f : α ≃ β) (l : α →₀ M) : equiv_map_domain f l = map_domain f l := by ext x; simp [map_domain_equiv_apply] /-- Given `f : α ≃ β`, the finitely supported function spaces are also in bijection: `(α →₀ M) ≃ (β →₀ M)`. This is the finitely-supported version of `equiv.Pi_congr_left`. -/ def equiv_congr_left (f : α ≃ β) : (α →₀ M) ≃ (β →₀ M) := by refine ⟨equiv_map_domain f, equiv_map_domain f.symm, λ f, _, λ f, _⟩; ext x; simp only [equiv_map_domain_apply, equiv.symm_symm, equiv.symm_apply_apply, equiv.apply_symm_apply] @[simp] lemma equiv_congr_left_apply (f : α ≃ β) (l : α →₀ M) : equiv_congr_left f l = equiv_map_domain f l := rfl @[simp] lemma equiv_congr_left_symm (f : α ≃ β) : (@equiv_congr_left _ _ M _ f).symm = equiv_congr_left f.symm := rfl end equiv_congr_left /-! ### Declarations about `filter` -/ section filter section has_zero variables [has_zero M] (p : α → Prop) (f : α →₀ M) /-- `filter p f` is the function which is `f a` if `p a` is true and 0 otherwise. -/ def filter (p : α → Prop) (f : α →₀ M) : α →₀ M := { to_fun := λ a, if p a then f a else 0, support := f.support.filter (λ a, p a), mem_support_to_fun := λ a, by split_ifs; { simp only [h, mem_filter, mem_support_iff], tauto } } lemma filter_apply (a : α) [D : decidable (p a)] : f.filter p a = if p a then f a else 0 := by rw subsingleton.elim D; refl lemma filter_eq_indicator : ⇑(f.filter p) = set.indicator {x | p x} f := rfl @[simp] lemma filter_apply_pos {a : α} (h : p a) : f.filter p a = f a := if_pos h @[simp] lemma filter_apply_neg {a : α} (h : ¬ p a) : f.filter p a = 0 := if_neg h @[simp] lemma support_filter [D : decidable_pred p] : (f.filter p).support = f.support.filter p := by rw subsingleton.elim D; refl lemma filter_zero : (0 : α →₀ M).filter p = 0 := by rw [← support_eq_empty, support_filter, support_zero, finset.filter_empty] @[simp] lemma filter_single_of_pos {a : α} {b : M} (h : p a) : (single a b).filter p = single a b := coe_fn_injective $ by simp [filter_eq_indicator, set.subset_def, mem_support_single, h] @[simp] lemma filter_single_of_neg {a : α} {b : M} (h : ¬ p a) : (single a b).filter p = 0 := ext $ by simp [filter_eq_indicator, single_apply_eq_zero, @imp.swap (p _), h] end has_zero lemma filter_pos_add_filter_neg [add_zero_class M] (f : α →₀ M) (p : α → Prop) : f.filter p + f.filter (λa, ¬ p a) = f := coe_fn_injective $ set.indicator_self_add_compl {x | p x} f end filter /-! ### Declarations about `frange` -/ section frange variables [has_zero M] /-- `frange f` is the image of `f` on the support of `f`. -/ def frange (f : α →₀ M) : finset M := finset.image f f.support theorem mem_frange {f : α →₀ M} {y : M} : y ∈ f.frange ↔ y ≠ 0 ∧ ∃ x, f x = y := finset.mem_image.trans ⟨λ ⟨x, hx1, hx2⟩, ⟨hx2 ▸ mem_support_iff.1 hx1, x, hx2⟩, λ ⟨hy, x, hx⟩, ⟨x, mem_support_iff.2 (hx.symm ▸ hy), hx⟩⟩ theorem zero_not_mem_frange {f : α →₀ M} : (0:M) ∉ f.frange := λ H, (mem_frange.1 H).1 rfl theorem frange_single {x : α} {y : M} : frange (single x y) ⊆ {y} := λ r hr, let ⟨t, ht1, ht2⟩ := mem_frange.1 hr in ht2 ▸ (by rw single_apply at ht2 ⊢; split_ifs at ht2 ⊢; [exact finset.mem_singleton_self _, cc]) end frange /-! ### Declarations about `subtype_domain` -/ section subtype_domain section zero variables [has_zero M] {p : α → Prop} /-- `subtype_domain p f` is the restriction of the finitely supported function `f` to the subtype `p`. -/ def subtype_domain (p : α → Prop) (f : α →₀ M) : (subtype p →₀ M) := ⟨f.support.subtype p, f ∘ coe, λ a, by simp only [mem_subtype, mem_support_iff]⟩ @[simp] lemma support_subtype_domain [D : decidable_pred p] {f : α →₀ M} : (subtype_domain p f).support = f.support.subtype p := by rw subsingleton.elim D; refl @[simp] lemma subtype_domain_apply {a : subtype p} {v : α →₀ M} : (subtype_domain p v) a = v (a.val) := rfl @[simp] lemma subtype_domain_zero : subtype_domain p (0 : α →₀ M) = 0 := rfl lemma subtype_domain_eq_zero_iff' {f : α →₀ M} : f.subtype_domain p = 0 ↔ ∀ x, p x → f x = 0 := by simp_rw [← support_eq_empty, support_subtype_domain, subtype_eq_empty, not_mem_support_iff] lemma subtype_domain_eq_zero_iff {f : α →₀ M} (hf : ∀ x ∈ f.support , p x) : f.subtype_domain p = 0 ↔ f = 0 := subtype_domain_eq_zero_iff'.trans ⟨λ H, ext $ λ x, if hx : p x then H x hx else not_mem_support_iff.1 $ mt (hf x) hx, λ H x _, by simp [H]⟩ @[to_additive] lemma prod_subtype_domain_index [comm_monoid N] {v : α →₀ M} {h : α → M → N} (hp : ∀x∈v.support, p x) : (v.subtype_domain p).prod (λa b, h a b) = v.prod h := prod_bij (λp _, p.val) (λ _, mem_subtype.1) (λ _ _, rfl) (λ _ _ _ _, subtype.eq) (λ b hb, ⟨⟨b, hp b hb⟩, mem_subtype.2 hb, rfl⟩) end zero section add_zero_class variables [add_zero_class M] {p : α → Prop} {v v' : α →₀ M} @[simp] lemma subtype_domain_add {v v' : α →₀ M} : (v + v').subtype_domain p = v.subtype_domain p + v'.subtype_domain p := ext $ λ _, rfl /-- `subtype_domain` but as an `add_monoid_hom`. -/ def subtype_domain_add_monoid_hom : (α →₀ M) →+ subtype p →₀ M := { to_fun := subtype_domain p, map_zero' := subtype_domain_zero, map_add' := λ _ _, subtype_domain_add } /-- `finsupp.filter` as an `add_monoid_hom`. -/ def filter_add_hom (p : α → Prop) : (α →₀ M) →+ (α →₀ M) := { to_fun := filter p, map_zero' := filter_zero p, map_add' := λ f g, coe_fn_injective $ set.indicator_add {x | p x} f g } @[simp] lemma filter_add {v v' : α →₀ M} : (v + v').filter p = v.filter p + v'.filter p := (filter_add_hom p).map_add v v' end add_zero_class section comm_monoid variables [add_comm_monoid M] {p : α → Prop} lemma subtype_domain_sum {s : finset ι} {h : ι → α →₀ M} : (∑ c in s, h c).subtype_domain p = ∑ c in s, (h c).subtype_domain p := (subtype_domain_add_monoid_hom : _ →+ subtype p →₀ M).map_sum _ s lemma subtype_domain_finsupp_sum [has_zero N] {s : β →₀ N} {h : β → N → α →₀ M} : (s.sum h).subtype_domain p = s.sum (λc d, (h c d).subtype_domain p) := subtype_domain_sum lemma filter_sum (s : finset ι) (f : ι → α →₀ M) : (∑ a in s, f a).filter p = ∑ a in s, filter p (f a) := (filter_add_hom p : (α →₀ M) →+ _).map_sum f s lemma filter_eq_sum (p : α → Prop) [D : decidable_pred p] (f : α →₀ M) : f.filter p = ∑ i in f.support.filter p, single i (f i) := (f.filter p).sum_single.symm.trans $ finset.sum_congr (by rw subsingleton.elim D; refl) $ λ x hx, by rw [filter_apply_pos _ _ (mem_filter.1 hx).2] end comm_monoid section group variables [add_group G] {p : α → Prop} {v v' : α →₀ G} @[simp] lemma subtype_domain_neg : (- v).subtype_domain p = - v.subtype_domain p := ext $ λ _, rfl @[simp] lemma subtype_domain_sub : (v - v').subtype_domain p = v.subtype_domain p - v'.subtype_domain p := ext $ λ _, rfl @[simp] lemma single_neg {a : α} {b : G} : single a (-b) = -single a b := (single_add_hom a : G →+ _).map_neg b @[simp] lemma single_sub {a : α} {b₁ b₂ : G} : single a (b₁ - b₂) = single a b₁ - single a b₂ := (single_add_hom a : G →+ _).map_sub b₁ b₂ @[simp] lemma erase_neg (a : α) (f : α →₀ G) : erase a (-f) = -erase a f := (erase_add_hom a : (_ →₀ G) →+ _).map_neg f @[simp] lemma erase_sub (a : α) (f₁ f₂ : α →₀ G) : erase a (f₁ - f₂) = erase a f₁ - erase a f₂ := (erase_add_hom a : (_ →₀ G) →+ _).map_sub f₁ f₂ @[simp] lemma filter_neg (p : α → Prop) (f : α →₀ G) : filter p (-f) = -filter p f := (filter_add_hom p : (_ →₀ G) →+ _).map_neg f @[simp] lemma filter_sub (p : α → Prop) (f₁ f₂ : α →₀ G) : filter p (f₁ - f₂) = filter p f₁ - filter p f₂ := (filter_add_hom p : (_ →₀ G) →+ _).map_sub f₁ f₂ end group end subtype_domain lemma mem_support_multiset_sum [add_comm_monoid M] {s : multiset (α →₀ M)} (a : α) : a ∈ s.sum.support → ∃f∈s, a ∈ (f : α →₀ M).support := multiset.induction_on s false.elim begin assume f s ih ha, by_cases a ∈ f.support, { exact ⟨f, multiset.mem_cons_self _ _, h⟩ }, { simp only [multiset.sum_cons, mem_support_iff, add_apply, not_mem_support_iff.1 h, zero_add] at ha, rcases ih (mem_support_iff.2 ha) with ⟨f', h₀, h₁⟩, exact ⟨f', multiset.mem_cons_of_mem h₀, h₁⟩ } end lemma mem_support_finset_sum [add_comm_monoid M] {s : finset ι} {h : ι → α →₀ M} (a : α) (ha : a ∈ (∑ c in s, h c).support) : ∃ c ∈ s, a ∈ (h c).support := let ⟨f, hf, hfa⟩ := mem_support_multiset_sum a ha in let ⟨c, hc, eq⟩ := multiset.mem_map.1 hf in ⟨c, hc, eq.symm ▸ hfa⟩ /-! ### Declarations about `curry` and `uncurry` -/ section curry_uncurry variables [add_comm_monoid M] [add_comm_monoid N] /-- Given a finitely supported function `f` from a product type `α × β` to `γ`, `curry f` is the "curried" finitely supported function from `α` to the type of finitely supported functions from `β` to `γ`. -/ protected def curry (f : (α × β) →₀ M) : α →₀ (β →₀ M) := f.sum $ λp c, single p.1 (single p.2 c) @[simp] lemma curry_apply (f : (α × β) →₀ M) (x : α) (y : β) : f.curry x y = f (x, y) := begin have : ∀ (b : α × β), single b.fst (single b.snd (f b)) x y = if b = (x, y) then f b else 0, { rintros ⟨b₁, b₂⟩, simp [single_apply, ite_apply, prod.ext_iff, ite_and], split_ifs; simp [single_apply, *] }, rw [finsupp.curry, sum_apply, sum_apply, finsupp.sum, finset.sum_eq_single, this, if_pos rfl], { intros b hb b_ne, rw [this b, if_neg b_ne] }, { intros hxy, rw [this (x, y), if_pos rfl, not_mem_support_iff.mp hxy] } end lemma sum_curry_index (f : (α × β) →₀ M) (g : α → β → M → N) (hg₀ : ∀ a b, g a b 0 = 0) (hg₁ : ∀a b c₀ c₁, g a b (c₀ + c₁) = g a b c₀ + g a b c₁) : f.curry.sum (λa f, f.sum (g a)) = f.sum (λp c, g p.1 p.2 c) := begin rw [finsupp.curry], transitivity, { exact sum_sum_index (assume a, sum_zero_index) (assume a b₀ b₁, sum_add_index (assume a, hg₀ _ _) (assume c d₀ d₁, hg₁ _ _ _ _)) }, congr, funext p c, transitivity, { exact sum_single_index sum_zero_index }, exact sum_single_index (hg₀ _ _) end /-- Given a finitely supported function `f` from `α` to the type of finitely supported functions from `β` to `M`, `uncurry f` is the "uncurried" finitely supported function from `α × β` to `M`. -/ protected def uncurry (f : α →₀ (β →₀ M)) : (α × β) →₀ M := f.sum $ λa g, g.sum $ λb c, single (a, b) c /-- `finsupp_prod_equiv` defines the `equiv` between `((α × β) →₀ M)` and `(α →₀ (β →₀ M))` given by currying and uncurrying. -/ def finsupp_prod_equiv : ((α × β) →₀ M) ≃ (α →₀ (β →₀ M)) := by refine ⟨finsupp.curry, finsupp.uncurry, λ f, _, λ f, _⟩; simp only [ finsupp.curry, finsupp.uncurry, sum_sum_index, sum_zero_index, sum_add_index, sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, prod.mk.eta, (single_sum _ _ _).symm, sum_single] lemma filter_curry (f : α × β →₀ M) (p : α → Prop) : (f.filter (λa:α×β, p a.1)).curry = f.curry.filter p := begin rw [finsupp.curry, finsupp.curry, finsupp.sum, finsupp.sum, filter_sum, support_filter, sum_filter], refine finset.sum_congr rfl _, rintros ⟨a₁, a₂⟩ ha, dsimp only, split_ifs, { rw [filter_apply_pos, filter_single_of_pos]; exact h }, { rwa [filter_single_of_neg] } end lemma support_curry [decidable_eq α] (f : α × β →₀ M) : f.curry.support ⊆ f.support.image prod.fst := begin rw ← finset.bUnion_singleton, refine finset.subset.trans support_sum _, refine finset.bUnion_mono (assume a _, support_single_subset) end end curry_uncurry section sum /-- `finsupp.sum_elim f g` maps `inl x` to `f x` and `inr y` to `g y`. -/ def sum_elim {α β γ : Type*} [has_zero γ] (f : α →₀ γ) (g : β →₀ γ) : α ⊕ β →₀ γ := on_finset ((f.support.map ⟨_, sum.inl_injective⟩) ∪ g.support.map ⟨_, sum.inr_injective⟩) (sum.elim f g) (λ ab h, by { cases ab with a b; simp only [sum.elim_inl, sum.elim_inr] at h; simpa }) @[simp] lemma coe_sum_elim {α β γ : Type*} [has_zero γ] (f : α →₀ γ) (g : β →₀ γ) : ⇑(sum_elim f g) = sum.elim f g := rfl lemma sum_elim_apply {α β γ : Type*} [has_zero γ] (f : α →₀ γ) (g : β →₀ γ) (x : α ⊕ β) : sum_elim f g x = sum.elim f g x := rfl lemma sum_elim_inl {α β γ : Type*} [has_zero γ] (f : α →₀ γ) (g : β →₀ γ) (x : α) : sum_elim f g (sum.inl x) = f x := rfl lemma sum_elim_inr {α β γ : Type*} [has_zero γ] (f : α →₀ γ) (g : β →₀ γ) (x : β) : sum_elim f g (sum.inr x) = g x := rfl /-- The equivalence between `(α ⊕ β) →₀ γ` and `(α →₀ γ) × (β →₀ γ)`. This is the `finsupp` version of `equiv.sum_arrow_equiv_prod_arrow`. -/ @[simps apply symm_apply] def sum_finsupp_equiv_prod_finsupp {α β γ : Type*} [has_zero γ] : ((α ⊕ β) →₀ γ) ≃ (α →₀ γ) × (β →₀ γ) := { to_fun := λ f, ⟨f.comap_domain sum.inl (sum.inl_injective.inj_on _), f.comap_domain sum.inr (sum.inr_injective.inj_on _)⟩, inv_fun := λ fg, sum_elim fg.1 fg.2, left_inv := λ f, by { ext ab, cases ab with a b; simp }, right_inv := λ fg, by { ext; simp } } lemma fst_sum_finsupp_equiv_prod_finsupp {α β γ : Type*} [has_zero γ] (f : (α ⊕ β) →₀ γ) (x : α) : (sum_finsupp_equiv_prod_finsupp f).1 x = f (sum.inl x) := rfl lemma snd_sum_finsupp_equiv_prod_finsupp {α β γ : Type*} [has_zero γ] (f : (α ⊕ β) →₀ γ) (y : β) : (sum_finsupp_equiv_prod_finsupp f).2 y = f (sum.inr y) := rfl lemma sum_finsupp_equiv_prod_finsupp_symm_inl {α β γ : Type*} [has_zero γ] (fg : (α →₀ γ) × (β →₀ γ)) (x : α) : (sum_finsupp_equiv_prod_finsupp.symm fg) (sum.inl x) = fg.1 x := rfl lemma sum_finsupp_equiv_prod_finsupp_symm_inr {α β γ : Type*} [has_zero γ] (fg : (α →₀ γ) × (β →₀ γ)) (y : β) : (sum_finsupp_equiv_prod_finsupp.symm fg) (sum.inr y) = fg.2 y := rfl variables [add_monoid M] /-- The additive equivalence between `(α ⊕ β) →₀ M` and `(α →₀ M) × (β →₀ M)`. This is the `finsupp` version of `equiv.sum_arrow_equiv_prod_arrow`. -/ @[simps apply symm_apply] def sum_finsupp_add_equiv_prod_finsupp {α β : Type*} : ((α ⊕ β) →₀ M) ≃+ (α →₀ M) × (β →₀ M) := { map_add' := by { intros, ext; simp only [equiv.to_fun_as_coe, prod.fst_add, prod.snd_add, add_apply, snd_sum_finsupp_equiv_prod_finsupp, fst_sum_finsupp_equiv_prod_finsupp] }, .. sum_finsupp_equiv_prod_finsupp } lemma fst_sum_finsupp_add_equiv_prod_finsupp {α β : Type*} (f : (α ⊕ β) →₀ M) (x : α) : (sum_finsupp_add_equiv_prod_finsupp f).1 x = f (sum.inl x) := rfl lemma snd_sum_finsupp_add_equiv_prod_finsupp {α β : Type*} (f : (α ⊕ β) →₀ M) (y : β) : (sum_finsupp_add_equiv_prod_finsupp f).2 y = f (sum.inr y) := rfl lemma sum_finsupp_add_equiv_prod_finsupp_symm_inl {α β : Type*} (fg : (α →₀ M) × (β →₀ M)) (x : α) : (sum_finsupp_add_equiv_prod_finsupp.symm fg) (sum.inl x) = fg.1 x := rfl lemma sum_finsupp_add_equiv_prod_finsupp_symm_inr {α β : Type*} (fg : (α →₀ M) × (β →₀ M)) (y : β) : (sum_finsupp_add_equiv_prod_finsupp.symm fg) (sum.inr y) = fg.2 y := rfl end sum section variables [group G] [mul_action G α] [add_comm_monoid M] /-- Scalar multiplication by a group element g, given by precomposition with the action of g⁻¹ on the domain. -/ def comap_has_scalar : has_scalar G (α →₀ M) := { smul := λ g f, f.comap_domain (λ a, g⁻¹ • a) (λ a a' m m' h, by simpa [←mul_smul] using (congr_arg (λ a, g • a) h)) } local attribute [instance] comap_has_scalar /-- Scalar multiplication by a group element, given by precomposition with the action of g⁻¹ on the domain, is multiplicative in g. -/ def comap_mul_action : mul_action G (α →₀ M) := { one_smul := λ f, by { ext, dsimp [(•)], simp, }, mul_smul := λ g g' f, by { ext, dsimp [(•)], simp [mul_smul], }, } local attribute [instance] comap_mul_action /-- Scalar multiplication by a group element, given by precomposition with the action of g⁻¹ on the domain, is additive in the second argument. -/ def comap_distrib_mul_action : distrib_mul_action G (α →₀ M) := { smul_zero := λ g, by { ext, dsimp [(•)], simp, }, smul_add := λ g f f', by { ext, dsimp [(•)], simp, }, } /-- Scalar multiplication by a group element on finitely supported functions on a group, given by precomposition with the action of g⁻¹. -/ def comap_distrib_mul_action_self : distrib_mul_action G (G →₀ M) := @finsupp.comap_distrib_mul_action G M G _ (monoid.to_mul_action G) _ @[simp] lemma comap_smul_single (g : G) (a : α) (b : M) : g • single a b = single (g • a) b := begin ext a', dsimp [(•)], by_cases h : g • a = a', { subst h, simp [←mul_smul], }, { simp [single_eq_of_ne h], rw [single_eq_of_ne], rintro rfl, simpa [←mul_smul] using h, } end @[simp] lemma comap_smul_apply (g : G) (f : α →₀ M) (a : α) : (g • f) a = f (g⁻¹ • a) := rfl end section instance [monoid R] [add_monoid M] [distrib_mul_action R M] : has_scalar R (α →₀ M) := ⟨λa v, v.map_range ((•) a) (smul_zero _)⟩ /-! Throughout this section, some `monoid` and `semiring` arguments are specified with `{}` instead of `[]`. See note [implicit instance arguments]. -/ @[simp] lemma coe_smul {_ : monoid R} [add_monoid M] [distrib_mul_action R M] (b : R) (v : α →₀ M) : ⇑(b • v) = b • v := rfl lemma smul_apply {_ : monoid R} [add_monoid M] [distrib_mul_action R M] (b : R) (v : α →₀ M) (a : α) : (b • v) a = b • (v a) := rfl lemma _root_.is_smul_regular.finsupp {_ : monoid R} [add_monoid M] [distrib_mul_action R M] {k : R} (hk : is_smul_regular M k) : is_smul_regular (α →₀ M) k := λ _ _ h, ext $ λ i, hk (congr_fun h i) instance [monoid R] [nonempty α] [add_monoid M] [distrib_mul_action R M] [has_faithful_scalar R M] : has_faithful_scalar R (α →₀ M) := { eq_of_smul_eq_smul := λ r₁ r₂ h, let ⟨a⟩ := ‹nonempty α› in eq_of_smul_eq_smul $ λ m : M, by simpa using congr_fun (h (single a m)) a } variables (α M) instance [monoid R] [add_monoid M] [distrib_mul_action R M] : distrib_mul_action R (α →₀ M) := { smul := (•), smul_add := λ a x y, ext $ λ _, smul_add _ _ _, one_smul := λ x, ext $ λ _, one_smul _ _, mul_smul := λ r s x, ext $ λ _, mul_smul _ _ _, smul_zero := λ x, ext $ λ _, smul_zero _ } instance [monoid R] [monoid S] [add_monoid M] [distrib_mul_action R M] [distrib_mul_action S M] [has_scalar R S] [is_scalar_tower R S M] : is_scalar_tower R S (α →₀ M) := { smul_assoc := λ r s a, ext $ λ _, smul_assoc _ _ _ } instance [monoid R] [monoid S] [add_monoid M] [distrib_mul_action R M] [distrib_mul_action S M] [smul_comm_class R S M] : smul_comm_class R S (α →₀ M) := { smul_comm := λ r s a, ext $ λ _, smul_comm _ _ _ } instance [monoid R] [add_monoid M] [distrib_mul_action R M] [distrib_mul_action Rᵐᵒᵖ M] [is_central_scalar R M] : is_central_scalar R (α →₀ M) := { op_smul_eq_smul := λ r a, ext $ λ _, op_smul_eq_smul _ _ } instance [semiring R] [add_comm_monoid M] [module R M] : module R (α →₀ M) := { smul := (•), zero_smul := λ x, ext $ λ _, zero_smul _ _, add_smul := λ a x y, ext $ λ _, add_smul _ _ _, .. finsupp.distrib_mul_action α M } variables {α M} {R} lemma support_smul {_ : monoid R} [add_monoid M] [distrib_mul_action R M] {b : R} {g : α →₀ M} : (b • g).support ⊆ g.support := λ a, by { simp only [smul_apply, mem_support_iff, ne.def], exact mt (λ h, h.symm ▸ smul_zero _) } @[simp] lemma support_smul_eq [semiring R] [add_comm_monoid M] [module R M] [no_zero_smul_divisors R M] {b : R} (hb : b ≠ 0) {g : α →₀ M} : (b • g).support = g.support := finset.ext (λ a, by simp [finsupp.smul_apply, hb]) section variables {p : α → Prop} @[simp] lemma filter_smul {_ : monoid R} [add_monoid M] [distrib_mul_action R M] {b : R} {v : α →₀ M} : (b • v).filter p = b • v.filter p := coe_fn_injective $ set.indicator_smul {x | p x} b v end lemma map_domain_smul {_ : monoid R} [add_comm_monoid M] [distrib_mul_action R M] {f : α → β} (b : R) (v : α →₀ M) : map_domain f (b • v) = b • map_domain f v := map_domain_map_range _ _ _ _ (smul_add b) @[simp] lemma smul_single {_ : monoid R} [add_monoid M] [distrib_mul_action R M] (c : R) (a : α) (b : M) : c • finsupp.single a b = finsupp.single a (c • b) := map_range_single @[simp] lemma smul_single' {_ : semiring R} (c : R) (a : α) (b : R) : c • finsupp.single a b = finsupp.single a (c * b) := smul_single _ _ _ lemma map_range_smul {_ : monoid R} [add_monoid M] [distrib_mul_action R M] [add_monoid N] [distrib_mul_action R N] {f : M → N} {hf : f 0 = 0} (c : R) (v : α →₀ M) (hsmul : ∀ x, f (c • x) = c • f x) : map_range f hf (c • v) = c • map_range f hf v := begin erw ←map_range_comp, have : (f ∘ (•) c) = ((•) c ∘ f) := funext hsmul, simp_rw this, apply map_range_comp, rw [function.comp_apply, smul_zero, hf], end lemma smul_single_one [semiring R] (a : α) (b : R) : b • single a 1 = single a b := by rw [smul_single, smul_eq_mul, mul_one] end lemma sum_smul_index [semiring R] [add_comm_monoid M] {g : α →₀ R} {b : R} {h : α → R → M} (h0 : ∀i, h i 0 = 0) : (b • g).sum h = g.sum (λi a, h i (b * a)) := finsupp.sum_map_range_index h0 lemma sum_smul_index' [monoid R] [add_monoid M] [distrib_mul_action R M] [add_comm_monoid N] {g : α →₀ M} {b : R} {h : α → M → N} (h0 : ∀i, h i 0 = 0) : (b • g).sum h = g.sum (λi c, h i (b • c)) := finsupp.sum_map_range_index h0 /-- A version of `finsupp.sum_smul_index'` for bundled additive maps. -/ lemma sum_smul_index_add_monoid_hom [monoid R] [add_monoid M] [add_comm_monoid N] [distrib_mul_action R M] {g : α →₀ M} {b : R} {h : α → M →+ N} : (b • g).sum (λ a, h a) = g.sum (λ i c, h i (b • c)) := sum_map_range_index (λ i, (h i).map_zero) instance [semiring R] [add_comm_monoid M] [module R M] {ι : Type*} [no_zero_smul_divisors R M] : no_zero_smul_divisors R (ι →₀ M) := ⟨λ c f h, or_iff_not_imp_left.mpr (λ hc, finsupp.ext (λ i, (smul_eq_zero.mp (finsupp.ext_iff.mp h i)).resolve_left hc))⟩ section distrib_mul_action_hom variables [semiring R] variables [add_comm_monoid M] [add_comm_monoid N] [distrib_mul_action R M] [distrib_mul_action R N] /-- `finsupp.single` as a `distrib_mul_action_hom`. See also `finsupp.lsingle` for the version as a linear map. -/ def distrib_mul_action_hom.single (a : α) : M →+[R] (α →₀ M) := { map_smul' := λ k m, by simp only [add_monoid_hom.to_fun_eq_coe, single_add_hom_apply, smul_single], .. single_add_hom a } lemma distrib_mul_action_hom_ext {f g : (α →₀ M) →+[R] N} (h : ∀ (a : α) (m : M), f (single a m) = g (single a m)) : f = g := distrib_mul_action_hom.to_add_monoid_hom_injective $ add_hom_ext h /-- See note [partially-applied ext lemmas]. -/ @[ext] lemma distrib_mul_action_hom_ext' {f g : (α →₀ M) →+[R] N} (h : ∀ (a : α), f.comp (distrib_mul_action_hom.single a) = g.comp (distrib_mul_action_hom.single a)) : f = g := distrib_mul_action_hom_ext $ λ a, distrib_mul_action_hom.congr_fun (h a) end distrib_mul_action_hom section variables [has_zero R] /-- The `finsupp` version of `pi.unique`. -/ instance unique_of_right [subsingleton R] : unique (α →₀ R) := { uniq := λ l, ext $ λ i, subsingleton.elim _ _, .. finsupp.inhabited } /-- The `finsupp` version of `pi.unique_of_is_empty`. -/ instance unique_of_left [is_empty α] : unique (α →₀ R) := { uniq := λ l, ext is_empty_elim, .. finsupp.inhabited } end /-- Given an `add_comm_monoid M` and `s : set α`, `restrict_support_equiv s M` is the `equiv` between the subtype of finitely supported functions with support contained in `s` and the type of finitely supported functions from `s`. -/ def restrict_support_equiv (s : set α) (M : Type*) [add_comm_monoid M] : {f : α →₀ M // ↑f.support ⊆ s } ≃ (s →₀ M) := begin refine ⟨λf, subtype_domain (λx, x ∈ s) f.1, λ f, ⟨f.map_domain subtype.val, _⟩, _, _⟩, { refine set.subset.trans (finset.coe_subset.2 map_domain_support) _, rw [finset.coe_image, set.image_subset_iff], exact assume x hx, x.2 }, { rintros ⟨f, hf⟩, apply subtype.eq, ext a, dsimp only, refine classical.by_cases (assume h : a ∈ set.range (subtype.val : s → α), _) (assume h, _), { rcases h with ⟨x, rfl⟩, rw [map_domain_apply subtype.val_injective, subtype_domain_apply] }, { convert map_domain_notin_range _ _ h, rw [← not_mem_support_iff], refine mt _ h, exact assume ha, ⟨⟨a, hf ha⟩, rfl⟩ } }, { assume f, ext ⟨a, ha⟩, dsimp only, rw [subtype_domain_apply, map_domain_apply subtype.val_injective] } end /-- Given `add_comm_monoid M` and `e : α ≃ β`, `dom_congr e` is the corresponding `equiv` between `α →₀ M` and `β →₀ M`. This is `finsupp.equiv_congr_left` as an `add_equiv`. -/ @[simps apply] protected def dom_congr [add_comm_monoid M] (e : α ≃ β) : (α →₀ M) ≃+ (β →₀ M) := { to_fun := equiv_map_domain e, inv_fun := equiv_map_domain e.symm, left_inv := λ v, begin simp only [← equiv_map_domain_trans, equiv.self_trans_symm], exact equiv_map_domain_refl _ end, right_inv := begin assume v, simp only [← equiv_map_domain_trans, equiv.symm_trans_self], exact equiv_map_domain_refl _ end, map_add' := λ a b, by simp only [equiv_map_domain_eq_map_domain]; exact map_domain_add } @[simp] lemma dom_congr_refl [add_comm_monoid M] : finsupp.dom_congr (equiv.refl α) = add_equiv.refl (α →₀ M) := add_equiv.ext $ λ _, equiv_map_domain_refl _ @[simp] lemma dom_congr_symm [add_comm_monoid M] (e : α ≃ β) : (finsupp.dom_congr e).symm = (finsupp.dom_congr e.symm : (β →₀ M) ≃+ (α →₀ M)):= add_equiv.ext $ λ _, rfl @[simp] lemma dom_congr_trans [add_comm_monoid M] (e : α ≃ β) (f : β ≃ γ) : (finsupp.dom_congr e).trans (finsupp.dom_congr f) = (finsupp.dom_congr (e.trans f) : (α →₀ M) ≃+ _) := add_equiv.ext $ λ _, (equiv_map_domain_trans _ _ _).symm end finsupp namespace finsupp /-! ### Declarations about sigma types -/ section sigma variables {αs : ι → Type*} [has_zero M] (l : (Σ i, αs i) →₀ M) /-- Given `l`, a finitely supported function from the sigma type `Σ (i : ι), αs i` to `M` and an index element `i : ι`, `split l i` is the `i`th component of `l`, a finitely supported function from `as i` to `M`. This is the `finsupp` version of `sigma.curry`. -/ def split (i : ι) : αs i →₀ M := l.comap_domain (sigma.mk i) (λ x1 x2 _ _ hx, heq_iff_eq.1 (sigma.mk.inj hx).2) lemma split_apply (i : ι) (x : αs i) : split l i x = l ⟨i, x⟩ := begin dunfold split, rw comap_domain_apply end /-- Given `l`, a finitely supported function from the sigma type `Σ (i : ι), αs i` to `β`, `split_support l` is the finset of indices in `ι` that appear in the support of `l`. -/ def split_support : finset ι := l.support.image sigma.fst lemma mem_split_support_iff_nonzero (i : ι) : i ∈ split_support l ↔ split l i ≠ 0 := begin rw [split_support, mem_image, ne.def, ← support_eq_empty, ← ne.def, ← finset.nonempty_iff_ne_empty, split, comap_domain, finset.nonempty], simp only [exists_prop, finset.mem_preimage, exists_and_distrib_right, exists_eq_right, mem_support_iff, sigma.exists, ne.def] end /-- Given `l`, a finitely supported function from the sigma type `Σ i, αs i` to `β` and an `ι`-indexed family `g` of functions from `(αs i →₀ β)` to `γ`, `split_comp` defines a finitely supported function from the index type `ι` to `γ` given by composing `g i` with `split l i`. -/ def split_comp [has_zero N] (g : Π i, (αs i →₀ M) → N) (hg : ∀ i x, x = 0 ↔ g i x = 0) : ι →₀ N := { support := split_support l, to_fun := λ i, g i (split l i), mem_support_to_fun := begin intros i, rw [mem_split_support_iff_nonzero, not_iff_not, hg], end } lemma sigma_support : l.support = l.split_support.sigma (λ i, (l.split i).support) := by simp only [finset.ext_iff, split_support, split, comap_domain, mem_image, mem_preimage, sigma.forall, mem_sigma]; tauto lemma sigma_sum [add_comm_monoid N] (f : (Σ (i : ι), αs i) → M → N) : l.sum f = ∑ i in split_support l, (split l i).sum (λ (a : αs i) b, f ⟨i, a⟩ b) := by simp only [sum, sigma_support, sum_sigma, split_apply] variables {η : Type*} [fintype η] {ιs : η → Type*} [has_zero α] /-- On a `fintype η`, `finsupp.split` is an equivalence between `(Σ (j : η), ιs j) →₀ α` and `Π j, (ιs j →₀ α)`. This is the `finsupp` version of `equiv.Pi_curry`. -/ noncomputable def sigma_finsupp_equiv_pi_finsupp : ((Σ j, ιs j) →₀ α) ≃ Π j, (ιs j →₀ α) := { to_fun := split, inv_fun := λ f, on_finset (finset.univ.sigma (λ j, (f j).support)) (λ ji, f ji.1 ji.2) (λ g hg, finset.mem_sigma.mpr ⟨finset.mem_univ _, mem_support_iff.mpr hg⟩), left_inv := λ f, by { ext, simp [split] }, right_inv := λ f, by { ext, simp [split] } } @[simp] lemma sigma_finsupp_equiv_pi_finsupp_apply (f : (Σ j, ιs j) →₀ α) (j i) : sigma_finsupp_equiv_pi_finsupp f j i = f ⟨j, i⟩ := rfl /-- On a `fintype η`, `finsupp.split` is an additive equivalence between `(Σ (j : η), ιs j) →₀ α` and `Π j, (ιs j →₀ α)`. This is the `add_equiv` version of `finsupp.sigma_finsupp_equiv_pi_finsupp`. -/ noncomputable def sigma_finsupp_add_equiv_pi_finsupp {α : Type*} {ιs : η → Type*} [add_monoid α] : ((Σ j, ιs j) →₀ α) ≃+ Π j, (ιs j →₀ α) := { map_add' := λ f g, by { ext, simp }, .. sigma_finsupp_equiv_pi_finsupp } @[simp] lemma sigma_finsupp_add_equiv_pi_finsupp_apply {α : Type*} {ιs : η → Type*} [add_monoid α] (f : (Σ j, ιs j) →₀ α) (j i) : sigma_finsupp_add_equiv_pi_finsupp f j i = f ⟨j, i⟩ := rfl end sigma end finsupp section cast_finsupp variables [has_zero M] (f : α →₀ M) namespace nat @[simp, norm_cast] lemma cast_finsupp_prod [comm_semiring R] (g : α → M → ℕ) : (↑(f.prod g) : R) = f.prod (λ a b, ↑(g a b)) := nat.cast_prod _ _ @[simp, norm_cast] lemma cast_finsupp_sum [comm_semiring R] (g : α → M → ℕ) : (↑(f.sum g) : R) = f.sum (λ a b, ↑(g a b)) := nat.cast_sum _ _ end nat namespace int @[simp, norm_cast] lemma cast_finsupp_prod [comm_ring R] (g : α → M → ℤ) : (↑(f.prod g) : R) = f.prod (λ a b, ↑(g a b)) := int.cast_prod _ _ @[simp, norm_cast] lemma cast_finsupp_sum [comm_ring R] (g : α → M → ℤ) : (↑(f.sum g) : R) = f.sum (λ a b, ↑(g a b)) := int.cast_sum _ _ end int end cast_finsupp
068ac42cfc30e48c870dfc2b0f208c88bf182b59
c3f2fcd060adfa2ca29f924839d2d925e8f2c685
/tests/lean/run/section4.lean
72b2b1a6c6eb2d4a0648de7a0d8ac0e4007bfaa7
[ "Apache-2.0" ]
permissive
respu/lean
6582d19a2f2838a28ecd2b3c6f81c32d07b5341d
8c76419c60b63d0d9f7bc04ebb0b99812d0ec654
refs/heads/master
1,610,882,451,231
1,427,747,084,000
1,427,747,429,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
630
lean
import logic set_option pp.universes true set_option pp.implicit true context universe k parameter A : Type context universe l universe u parameter B : Type definition foo (a : A) (b : B) := b inductive mypair := mk : A → B → mypair definition pr1' (p : mypair) : A := mypair.rec (λ a b, a) p definition pr2' (p : mypair) : B := mypair.rec (λ a b, b) p check mypair.rec end check mypair.rec variable a : A check foo num a 0 definition pr1 (p : mypair num) : A := mypair.rec (λ a b, a) p definition pr2 (p : mypair num) : num := mypair.rec (λ a b, b) p end
dfd66f5bea547acaa4dcab377e51d849426a710c
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/set/pointwise/smul.lean
2b807aa3215b2aa9901572020689b0661f75be22
[ "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
29,281
lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Floris van Doorn -/ import algebra.module.basic import data.set.pairwise.lattice import data.set.pointwise.basic import tactic.by_contra /-! # Pointwise operations of sets > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines pointwise algebraic operations on sets. ## Main declarations For sets `s` and `t` and scalar `a`: * `s • t`: Scalar multiplication, set of all `x • y` where `x ∈ s` and `y ∈ t`. * `s +ᵥ t`: Scalar addition, set of all `x +ᵥ y` where `x ∈ s` and `y ∈ t`. * `s -ᵥ t`: Scalar subtraction, set of all `x -ᵥ y` where `x ∈ s` and `y ∈ t`. * `a • s`: Scaling, set of all `a • x` where `x ∈ s`. * `a +ᵥ s`: Translation, set of all `a +ᵥ x` where `x ∈ s`. For `α` a semigroup/monoid, `set α` is a semigroup/monoid. Appropriate definitions and results are also transported to the additive theory via `to_additive`. ## Implementation notes * We put all instances in the locale `pointwise`, so that these instances are not available by default. Note that we do not mark them as reducible (as argued by note [reducible non-instances]) since we expect the locale to be open whenever the instances are actually used (and making the instances reducible changes the behavior of `simp`. -/ open function mul_opposite variables {F α β γ : Type*} namespace set open_locale pointwise /-! ### Translation/scaling of sets -/ section smul /-- The dilation of set `x • s` is defined as `{x • y | y ∈ s}` in locale `pointwise`. -/ @[to_additive "The translation of set `x +ᵥ s` is defined as `{x +ᵥ y | y ∈ s}` in locale `pointwise`."] protected def has_smul_set [has_smul α β] : has_smul α (set β) := ⟨λ a, image (has_smul.smul a)⟩ /-- The pointwise scalar multiplication of sets `s • t` is defined as `{x • y | x ∈ s, y ∈ t}` in locale `pointwise`. -/ @[to_additive "The pointwise scalar addition of sets `s +ᵥ t` is defined as `{x +ᵥ y | x ∈ s, y ∈ t}` in locale `pointwise`."] protected def has_smul [has_smul α β] : has_smul (set α) (set β) := ⟨image2 has_smul.smul⟩ localized "attribute [instance] set.has_smul_set set.has_smul" in pointwise localized "attribute [instance] set.has_vadd_set set.has_vadd" in pointwise section has_smul variables {ι : Sort*} {κ : ι → Sort*} [has_smul α β] {s s₁ s₂ : set α} {t t₁ t₂ u : set β} {a : α} {b : β} @[simp, to_additive] lemma image2_smul : image2 has_smul.smul s t = s • t := rfl @[to_additive add_image_prod] lemma image_smul_prod : (λ x : α × β, x.fst • x.snd) '' s ×ˢ t = s • t := image_prod _ @[to_additive] lemma mem_smul : b ∈ s • t ↔ ∃ x y, x ∈ s ∧ y ∈ t ∧ x • y = b := iff.rfl @[to_additive] lemma smul_mem_smul : a ∈ s → b ∈ t → a • b ∈ s • t := mem_image2_of_mem @[simp, to_additive] lemma empty_smul : (∅ : set α) • t = ∅ := image2_empty_left @[simp, to_additive] lemma smul_empty : s • (∅ : set β) = ∅ := image2_empty_right @[simp, to_additive] lemma smul_eq_empty : s • t = ∅ ↔ s = ∅ ∨ t = ∅ := image2_eq_empty_iff @[simp, to_additive] lemma smul_nonempty : (s • t).nonempty ↔ s.nonempty ∧ t.nonempty := image2_nonempty_iff @[to_additive] lemma nonempty.smul : s.nonempty → t.nonempty → (s • t).nonempty := nonempty.image2 @[to_additive] lemma nonempty.of_smul_left : (s • t).nonempty → s.nonempty := nonempty.of_image2_left @[to_additive] lemma nonempty.of_smul_right : (s • t).nonempty → t.nonempty := nonempty.of_image2_right @[simp, to_additive] lemma smul_singleton : s • {b} = (• b) '' s := image2_singleton_right @[simp, to_additive] lemma singleton_smul : ({a} : set α) • t = a • t := image2_singleton_left @[simp, to_additive] lemma singleton_smul_singleton : ({a} : set α) • ({b} : set β) = {a • b} := image2_singleton @[to_additive, mono] lemma smul_subset_smul : s₁ ⊆ s₂ → t₁ ⊆ t₂ → s₁ • t₁ ⊆ s₂ • t₂ := image2_subset @[to_additive] lemma smul_subset_smul_left : t₁ ⊆ t₂ → s • t₁ ⊆ s • t₂ := image2_subset_left @[to_additive] lemma smul_subset_smul_right : s₁ ⊆ s₂ → s₁ • t ⊆ s₂ • t := image2_subset_right @[to_additive] lemma smul_subset_iff : s • t ⊆ u ↔ ∀ (a ∈ s) (b ∈ t), a • b ∈ u := image2_subset_iff attribute [mono] vadd_subset_vadd @[to_additive] lemma union_smul : (s₁ ∪ s₂) • t = s₁ • t ∪ s₂ • t := image2_union_left @[to_additive] lemma smul_union : s • (t₁ ∪ t₂) = s • t₁ ∪ s • t₂ := image2_union_right @[to_additive] lemma inter_smul_subset : (s₁ ∩ s₂) • t ⊆ s₁ • t ∩ s₂ • t := image2_inter_subset_left @[to_additive] lemma smul_inter_subset : s • (t₁ ∩ t₂) ⊆ s • t₁ ∩ s • t₂ := image2_inter_subset_right @[to_additive] lemma inter_smul_union_subset_union : (s₁ ∩ s₂) • (t₁ ∪ t₂) ⊆ (s₁ • t₁) ∪ (s₂ • t₂) := image2_inter_union_subset_union @[to_additive] lemma union_smul_inter_subset_union : (s₁ ∪ s₂) • (t₁ ∩ t₂) ⊆ (s₁ • t₁) ∪ (s₂ • t₂) := image2_union_inter_subset_union @[to_additive] lemma Union_smul_left_image : (⋃ a ∈ s, a • t) = s • t := Union_image_left _ @[to_additive] lemma Union_smul_right_image : (⋃ a ∈ t, (• a) '' s) = s • t := Union_image_right _ @[to_additive] lemma Union_smul (s : ι → set α) (t : set β) : (⋃ i, s i) • t = ⋃ i, s i • t := image2_Union_left _ _ _ @[to_additive] lemma smul_Union (s : set α) (t : ι → set β) : s • (⋃ i, t i) = ⋃ i, s • t i := image2_Union_right _ _ _ @[to_additive] lemma Union₂_smul (s : Π i, κ i → set α) (t : set β) : (⋃ i j, s i j) • t = ⋃ i j, s i j • t := image2_Union₂_left _ _ _ @[to_additive] lemma smul_Union₂ (s : set α) (t : Π i, κ i → set β) : s • (⋃ i j, t i j) = ⋃ i j, s • t i j := image2_Union₂_right _ _ _ @[to_additive] lemma Inter_smul_subset (s : ι → set α) (t : set β) : (⋂ i, s i) • t ⊆ ⋂ i, s i • t := image2_Inter_subset_left _ _ _ @[to_additive] lemma smul_Inter_subset (s : set α) (t : ι → set β) : s • (⋂ i, t i) ⊆ ⋂ i, s • t i := image2_Inter_subset_right _ _ _ @[to_additive] lemma Inter₂_smul_subset (s : Π i, κ i → set α) (t : set β) : (⋂ i j, s i j) • t ⊆ ⋂ i j, s i j • t := image2_Inter₂_subset_left _ _ _ @[to_additive] lemma smul_Inter₂_subset (s : set α) (t : Π i, κ i → set β) : s • (⋂ i j, t i j) ⊆ ⋂ i j, s • t i j := image2_Inter₂_subset_right _ _ _ @[to_additive] lemma smul_set_subset_smul {s : set α} : a ∈ s → a • t ⊆ s • t := image_subset_image2_right @[simp, to_additive] lemma bUnion_smul_set (s : set α) (t : set β) : (⋃ a ∈ s, a • t) = s • t := Union_image_left _ end has_smul section has_smul_set variables {ι : Sort*} {κ : ι → Sort*} [has_smul α β] {s t t₁ t₂ : set β} {a : α} {b : β} {x y : β} @[simp, to_additive] lemma image_smul : (λ x, a • x) '' t = a • t := rfl @[to_additive] lemma mem_smul_set : x ∈ a • t ↔ ∃ y, y ∈ t ∧ a • y = x := iff.rfl @[to_additive] lemma smul_mem_smul_set : b ∈ s → a • b ∈ a • s := mem_image_of_mem _ @[simp, to_additive] lemma smul_set_empty : a • (∅ : set β) = ∅ := image_empty _ @[simp, to_additive] lemma smul_set_eq_empty : a • s = ∅ ↔ s = ∅ := image_eq_empty @[simp, to_additive] lemma smul_set_nonempty : (a • s).nonempty ↔ s.nonempty := nonempty_image_iff @[simp, to_additive] lemma smul_set_singleton : a • ({b} : set β) = {a • b} := image_singleton @[to_additive] lemma smul_set_mono : s ⊆ t → a • s ⊆ a • t := image_subset _ @[to_additive] lemma smul_set_subset_iff : a • s ⊆ t ↔ ∀ ⦃b⦄, b ∈ s → a • b ∈ t := image_subset_iff @[to_additive] lemma smul_set_union : a • (t₁ ∪ t₂) = a • t₁ ∪ a • t₂ := image_union _ _ _ @[to_additive] lemma smul_set_inter_subset : a • (t₁ ∩ t₂) ⊆ a • t₁ ∩ (a • t₂) := image_inter_subset _ _ _ @[to_additive] lemma smul_set_Union (a : α) (s : ι → set β) : a • (⋃ i, s i) = ⋃ i, a • s i := image_Union @[to_additive] lemma smul_set_Union₂ (a : α) (s : Π i, κ i → set β) : a • (⋃ i j, s i j) = ⋃ i j, a • s i j := image_Union₂ _ _ @[to_additive] lemma smul_set_Inter_subset (a : α) (t : ι → set β) : a • (⋂ i, t i) ⊆ ⋂ i, a • t i := image_Inter_subset _ _ @[to_additive] lemma smul_set_Inter₂_subset (a : α) (t : Π i, κ i → set β) : a • (⋂ i j, t i j) ⊆ ⋂ i j, a • t i j := image_Inter₂_subset _ _ @[to_additive] lemma nonempty.smul_set : s.nonempty → (a • s).nonempty := nonempty.image _ end has_smul_set section has_mul variables [has_mul α] {s t u : set α} {a : α} @[to_additive] lemma op_smul_set_subset_mul : a ∈ t → op a • s ⊆ s * t := image_subset_image2_left @[simp, to_additive] lemma bUnion_op_smul_set (s t : set α) : (⋃ a ∈ t, op a • s) = s * t := Union_image_right _ @[to_additive] lemma mul_subset_iff_left : s * t ⊆ u ↔ ∀ a ∈ s, a • t ⊆ u := image2_subset_iff_left @[to_additive] lemma mul_subset_iff_right : s * t ⊆ u ↔ ∀ b ∈ t, op b • s ⊆ u := image2_subset_iff_right end has_mul variables {s s₁ s₂ : set α} {t t₁ t₂ : set β} {a : α} {b : β} @[to_additive] theorem range_smul_range {ι κ : Type*} [has_smul α β] (b : ι → α) (c : κ → β) : range b • range c = range (λ p : ι × κ, b p.1 • c p.2) := ext $ λ x, ⟨λ hx, let ⟨p, q, ⟨i, hi⟩, ⟨j, hj⟩, hpq⟩ := set.mem_smul.1 hx in ⟨(i, j), hpq ▸ hi ▸ hj ▸ rfl⟩, λ ⟨⟨i, j⟩, h⟩, set.mem_smul.2 ⟨b i, c j, ⟨i, rfl⟩, ⟨j, rfl⟩, h⟩⟩ @[to_additive] lemma smul_set_range [has_smul α β] {ι : Sort*} {f : ι → β} : a • range f = range (λ i, a • f i) := (range_comp _ _).symm @[to_additive] instance smul_comm_class_set [has_smul α γ] [has_smul β γ] [smul_comm_class α β γ] : smul_comm_class α β (set γ) := ⟨λ _ _, commute.set_image $ smul_comm _ _⟩ @[to_additive] instance smul_comm_class_set' [has_smul α γ] [has_smul β γ] [smul_comm_class α β γ] : smul_comm_class α (set β) (set γ) := ⟨λ _ _ _, image_image2_distrib_right $ smul_comm _⟩ @[to_additive] instance smul_comm_class_set'' [has_smul α γ] [has_smul β γ] [smul_comm_class α β γ] : smul_comm_class (set α) β (set γ) := by haveI := smul_comm_class.symm α β γ; exact smul_comm_class.symm _ _ _ @[to_additive] instance smul_comm_class [has_smul α γ] [has_smul β γ] [smul_comm_class α β γ] : smul_comm_class (set α) (set β) (set γ) := ⟨λ _ _ _, image2_left_comm smul_comm⟩ @[to_additive] instance is_scalar_tower [has_smul α β] [has_smul α γ] [has_smul β γ] [is_scalar_tower α β γ] : is_scalar_tower α β (set γ) := { smul_assoc := λ a b T, by simp only [←image_smul, image_image, smul_assoc] } @[to_additive] instance is_scalar_tower' [has_smul α β] [has_smul α γ] [has_smul β γ] [is_scalar_tower α β γ] : is_scalar_tower α (set β) (set γ) := ⟨λ _ _ _, image2_image_left_comm $ smul_assoc _⟩ @[to_additive] instance is_scalar_tower'' [has_smul α β] [has_smul α γ] [has_smul β γ] [is_scalar_tower α β γ] : is_scalar_tower (set α) (set β) (set γ) := { smul_assoc := λ T T' T'', image2_assoc smul_assoc } @[to_additive] instance is_central_scalar [has_smul α β] [has_smul αᵐᵒᵖ β] [is_central_scalar α β] : is_central_scalar α (set β) := ⟨λ a S, congr_arg (λ f, f '' S) $ by exact funext (λ _, op_smul_eq_smul _ _)⟩ /-- A multiplicative action of a monoid `α` on a type `β` gives a multiplicative action of `set α` on `set β`. -/ @[to_additive "An additive action of an additive monoid `α` on a type `β` gives an additive action of `set α` on `set β`"] protected def mul_action [monoid α] [mul_action α β] : mul_action (set α) (set β) := { mul_smul := λ _ _ _, image2_assoc mul_smul, one_smul := λ s, image2_singleton_left.trans $ by simp_rw [one_smul, image_id'] } /-- A multiplicative action of a monoid on a type `β` gives a multiplicative action on `set β`. -/ @[to_additive "An additive action of an additive monoid on a type `β` gives an additive action on `set β`."] protected def mul_action_set [monoid α] [mul_action α β] : mul_action α (set β) := { mul_smul := by { intros, simp only [← image_smul, image_image, ← mul_smul] }, one_smul := by { intros, simp only [← image_smul, one_smul, image_id'] } } localized "attribute [instance] set.mul_action_set set.add_action_set set.mul_action set.add_action" in pointwise /-- A distributive multiplicative action of a monoid on an additive monoid `β` gives a distributive multiplicative action on `set β`. -/ protected def distrib_mul_action_set [monoid α] [add_monoid β] [distrib_mul_action α β] : distrib_mul_action α (set β) := { smul_add := λ _ _ _, image_image2_distrib $ smul_add _, smul_zero := λ _, image_singleton.trans $ by rw [smul_zero, singleton_zero] } /-- A multiplicative action of a monoid on a monoid `β` gives a multiplicative action on `set β`. -/ protected def mul_distrib_mul_action_set [monoid α] [monoid β] [mul_distrib_mul_action α β] : mul_distrib_mul_action α (set β) := { smul_mul := λ _ _ _, image_image2_distrib $ smul_mul' _, smul_one := λ _, image_singleton.trans $ by rw [smul_one, singleton_one] } localized "attribute [instance] set.distrib_mul_action_set set.mul_distrib_mul_action_set" in pointwise instance [has_zero α] [has_zero β] [has_smul α β] [no_zero_smul_divisors α β] : no_zero_smul_divisors (set α) (set β) := ⟨λ s t h, begin by_contra' H, have hst : (s • t).nonempty := h.symm.subst zero_nonempty, simp_rw [←hst.of_smul_left.subset_zero_iff, ←hst.of_smul_right.subset_zero_iff, not_subset, mem_zero] at H, obtain ⟨⟨a, hs, ha⟩, b, ht, hb⟩ := H, exact (eq_zero_or_eq_zero_of_smul_eq_zero $ h.subset $ smul_mem_smul hs ht).elim ha hb, end⟩ instance no_zero_smul_divisors_set [has_zero α] [has_zero β] [has_smul α β] [no_zero_smul_divisors α β] : no_zero_smul_divisors α (set β) := ⟨λ a s h, begin by_contra' H, have hst : (a • s).nonempty := h.symm.subst zero_nonempty, simp_rw [←hst.of_image.subset_zero_iff, not_subset, mem_zero] at H, obtain ⟨ha, b, ht, hb⟩ := H, exact (eq_zero_or_eq_zero_of_smul_eq_zero $ h.subset $ smul_mem_smul_set ht).elim ha hb, end⟩ instance [has_zero α] [has_mul α] [no_zero_divisors α] : no_zero_divisors (set α) := ⟨λ s t h, eq_zero_or_eq_zero_of_smul_eq_zero h⟩ end smul section vsub variables {ι : Sort*} {κ : ι → Sort*} [has_vsub α β] {s s₁ s₂ t t₁ t₂ : set β} {u : set α} {a : α} {b c : β} include α instance has_vsub : has_vsub (set α) (set β) := ⟨image2 (-ᵥ)⟩ @[simp] lemma image2_vsub : (image2 has_vsub.vsub s t : set α) = s -ᵥ t := rfl lemma image_vsub_prod : (λ x : β × β, x.fst -ᵥ x.snd) '' s ×ˢ t = s -ᵥ t := image_prod _ lemma mem_vsub : a ∈ s -ᵥ t ↔ ∃ x y, x ∈ s ∧ y ∈ t ∧ x -ᵥ y = a := iff.rfl lemma vsub_mem_vsub (hb : b ∈ s) (hc : c ∈ t) : b -ᵥ c ∈ s -ᵥ t := mem_image2_of_mem hb hc @[simp] lemma empty_vsub (t : set β) : ∅ -ᵥ t = ∅ := image2_empty_left @[simp] lemma vsub_empty (s : set β) : s -ᵥ ∅ = ∅ := image2_empty_right @[simp] lemma vsub_eq_empty : s -ᵥ t = ∅ ↔ s = ∅ ∨ t = ∅ := image2_eq_empty_iff @[simp] lemma vsub_nonempty : (s -ᵥ t : set α).nonempty ↔ s.nonempty ∧ t.nonempty := image2_nonempty_iff lemma nonempty.vsub : s.nonempty → t.nonempty → (s -ᵥ t : set α).nonempty := nonempty.image2 lemma nonempty.of_vsub_left : (s -ᵥ t :set α).nonempty → s.nonempty := nonempty.of_image2_left lemma nonempty.of_vsub_right : (s -ᵥ t : set α).nonempty → t.nonempty := nonempty.of_image2_right @[simp] lemma vsub_singleton (s : set β) (b : β) : s -ᵥ {b} = (-ᵥ b) '' s := image2_singleton_right @[simp] lemma singleton_vsub (t : set β) (b : β) : {b} -ᵥ t = ((-ᵥ) b) '' t := image2_singleton_left @[simp] lemma singleton_vsub_singleton : ({b} : set β) -ᵥ {c} = {b -ᵥ c} := image2_singleton @[mono] lemma vsub_subset_vsub : s₁ ⊆ s₂ → t₁ ⊆ t₂ → s₁ -ᵥ t₁ ⊆ s₂ -ᵥ t₂ := image2_subset lemma vsub_subset_vsub_left : t₁ ⊆ t₂ → s -ᵥ t₁ ⊆ s -ᵥ t₂ := image2_subset_left lemma vsub_subset_vsub_right : s₁ ⊆ s₂ → s₁ -ᵥ t ⊆ s₂ -ᵥ t := image2_subset_right lemma vsub_subset_iff : s -ᵥ t ⊆ u ↔ ∀ (x ∈ s) (y ∈ t), x -ᵥ y ∈ u := image2_subset_iff lemma vsub_self_mono (h : s ⊆ t) : s -ᵥ s ⊆ t -ᵥ t := vsub_subset_vsub h h lemma union_vsub : (s₁ ∪ s₂) -ᵥ t = s₁ -ᵥ t ∪ (s₂ -ᵥ t) := image2_union_left lemma vsub_union : s -ᵥ (t₁ ∪ t₂) = s -ᵥ t₁ ∪ (s -ᵥ t₂) := image2_union_right lemma inter_vsub_subset : s₁ ∩ s₂ -ᵥ t ⊆ (s₁ -ᵥ t) ∩ (s₂ -ᵥ t) := image2_inter_subset_left lemma vsub_inter_subset : s -ᵥ t₁ ∩ t₂ ⊆ (s -ᵥ t₁) ∩ (s -ᵥ t₂) := image2_inter_subset_right lemma inter_vsub_union_subset_union : (s₁ ∩ s₂) -ᵥ (t₁ ∪ t₂) ⊆ (s₁ -ᵥ t₁) ∪ (s₂ -ᵥ t₂) := image2_inter_union_subset_union lemma union_vsub_inter_subset_union : (s₁ ∪ s₂) -ᵥ (t₁ ∩ t₂) ⊆ (s₁ -ᵥ t₁) ∪ (s₂ -ᵥ t₂) := image2_union_inter_subset_union lemma Union_vsub_left_image : (⋃ a ∈ s, ((-ᵥ) a) '' t) = s -ᵥ t := Union_image_left _ lemma Union_vsub_right_image : (⋃ a ∈ t, (-ᵥ a) '' s) = s -ᵥ t := Union_image_right _ lemma Union_vsub (s : ι → set β) (t : set β) : (⋃ i, s i) -ᵥ t = ⋃ i, s i -ᵥ t := image2_Union_left _ _ _ lemma vsub_Union (s : set β) (t : ι → set β) : s -ᵥ (⋃ i, t i) = ⋃ i, s -ᵥ t i := image2_Union_right _ _ _ lemma Union₂_vsub (s : Π i, κ i → set β) (t : set β) : (⋃ i j, s i j) -ᵥ t = ⋃ i j, s i j -ᵥ t := image2_Union₂_left _ _ _ lemma vsub_Union₂ (s : set β) (t : Π i, κ i → set β) : s -ᵥ (⋃ i j, t i j) = ⋃ i j, s -ᵥ t i j := image2_Union₂_right _ _ _ lemma Inter_vsub_subset (s : ι → set β) (t : set β) : (⋂ i, s i) -ᵥ t ⊆ ⋂ i, s i -ᵥ t := image2_Inter_subset_left _ _ _ lemma vsub_Inter_subset (s : set β) (t : ι → set β) : s -ᵥ (⋂ i, t i) ⊆ ⋂ i, s -ᵥ t i := image2_Inter_subset_right _ _ _ lemma Inter₂_vsub_subset (s : Π i, κ i → set β) (t : set β) : (⋂ i j, s i j) -ᵥ t ⊆ ⋂ i j, s i j -ᵥ t := image2_Inter₂_subset_left _ _ _ lemma vsub_Inter₂_subset (s : set β) (t : Π i, κ i → set β) : s -ᵥ (⋂ i j, t i j) ⊆ ⋂ i j, s -ᵥ t i j := image2_Inter₂_subset_right _ _ _ end vsub open_locale pointwise @[to_additive] lemma image_smul_comm [has_smul α β] [has_smul α γ] (f : β → γ) (a : α) (s : set β) : (∀ b, f (a • b) = a • f b) → f '' (a • s) = a • f '' s := image_comm @[to_additive] lemma image_smul_distrib [mul_one_class α] [mul_one_class β] [monoid_hom_class F α β] (f : F) (a : α) (s : set α) : f '' (a • s) = f a • f '' s := image_comm $ map_mul _ _ section has_smul variables[has_smul αᵐᵒᵖ β] [has_smul β γ] [has_smul α γ] -- TODO: replace hypothesis and conclusion with a typeclass @[to_additive] lemma op_smul_set_smul_eq_smul_smul_set (a : α) (s : set β) (t : set γ) (h : ∀ (a : α) (b : β) (c : γ), (op a • b) • c = b • a • c) : (op a • s) • t = s • a • t := by { ext, simp [mem_smul, mem_smul_set, h] } end has_smul section smul_with_zero variables [has_zero α] [has_zero β] [smul_with_zero α β] {s : set α} {t : set β} /-! Note that we have neither `smul_with_zero α (set β)` nor `smul_with_zero (set α) (set β)` because `0 * ∅ ≠ 0`. -/ lemma smul_zero_subset (s : set α) : s • (0 : set β) ⊆ 0 := by simp [subset_def, mem_smul] lemma zero_smul_subset (t : set β) : (0 : set α) • t ⊆ 0 := by simp [subset_def, mem_smul] lemma nonempty.smul_zero (hs : s.nonempty) : s • (0 : set β) = 0 := s.smul_zero_subset.antisymm $ by simpa [mem_smul] using hs lemma nonempty.zero_smul (ht : t.nonempty) : (0 : set α) • t = 0 := t.zero_smul_subset.antisymm $ by simpa [mem_smul] using ht /-- A nonempty set is scaled by zero to the singleton set containing 0. -/ lemma zero_smul_set {s : set β} (h : s.nonempty) : (0 : α) • s = (0 : set β) := by simp only [← image_smul, image_eta, zero_smul, h.image_const, singleton_zero] lemma zero_smul_set_subset (s : set β) : (0 : α) • s ⊆ 0 := image_subset_iff.2 $ λ x _, zero_smul α x lemma subsingleton_zero_smul_set (s : set β) : ((0 : α) • s).subsingleton := subsingleton_singleton.anti $ zero_smul_set_subset s lemma zero_mem_smul_set {t : set β} {a : α} (h : (0 : β) ∈ t) : (0 : β) ∈ a • t := ⟨0, h, smul_zero _⟩ variables [no_zero_smul_divisors α β] {a : α} lemma zero_mem_smul_iff : (0 : β) ∈ s • t ↔ (0 : α) ∈ s ∧ t.nonempty ∨ (0 : β) ∈ t ∧ s.nonempty := begin split, { rintro ⟨a, b, ha, hb, h⟩, obtain rfl | rfl := eq_zero_or_eq_zero_of_smul_eq_zero h, { exact or.inl ⟨ha, b, hb⟩ }, { exact or.inr ⟨hb, a, ha⟩ } }, { rintro (⟨hs, b, hb⟩ | ⟨ht, a, ha⟩), { exact ⟨0, b, hs, hb, zero_smul _ _⟩ }, { exact ⟨a, 0, ha, ht, smul_zero _⟩ } } end lemma zero_mem_smul_set_iff (ha : a ≠ 0) : (0 : β) ∈ a • t ↔ (0 : β) ∈ t := begin refine ⟨_, zero_mem_smul_set⟩, rintro ⟨b, hb, h⟩, rwa (eq_zero_or_eq_zero_of_smul_eq_zero h).resolve_left ha at hb, end end smul_with_zero section semigroup variables [semigroup α] @[to_additive] lemma op_smul_set_mul_eq_mul_smul_set (a : α) (s : set α) (t : set α) : (op a • s) * t = s * a • t := op_smul_set_smul_eq_smul_smul_set _ _ _ $ λ _ _ _, mul_assoc _ _ _ end semigroup section left_cancel_semigroup variables [left_cancel_semigroup α] {s t : set α} @[to_additive] lemma pairwise_disjoint_smul_iff : s.pairwise_disjoint (• t) ↔ (s ×ˢ t).inj_on (λ p, p.1 * p.2) := pairwise_disjoint_image_right_iff $ λ _ _, mul_right_injective _ end left_cancel_semigroup section group variables [group α] [mul_action α β] {s t A B : set β} {a : α} {x : β} @[simp, to_additive] lemma smul_mem_smul_set_iff : a • x ∈ a • s ↔ x ∈ s := (mul_action.injective _).mem_set_image @[to_additive] lemma mem_smul_set_iff_inv_smul_mem : x ∈ a • A ↔ a⁻¹ • x ∈ A := show x ∈ mul_action.to_perm a '' A ↔ _, from mem_image_equiv @[to_additive] lemma mem_inv_smul_set_iff : x ∈ a⁻¹ • A ↔ a • x ∈ A := by simp only [← image_smul, mem_image, inv_smul_eq_iff, exists_eq_right] @[to_additive] lemma preimage_smul (a : α) (t : set β) : (λ x, a • x) ⁻¹' t = a⁻¹ • t := ((mul_action.to_perm a).symm.image_eq_preimage _).symm @[to_additive] lemma preimage_smul_inv (a : α) (t : set β) : (λ x, a⁻¹ • x) ⁻¹' t = a • t := preimage_smul (to_units a)⁻¹ t @[simp, to_additive] lemma set_smul_subset_set_smul_iff : a • A ⊆ a • B ↔ A ⊆ B := image_subset_image_iff $ mul_action.injective _ @[to_additive] lemma set_smul_subset_iff : a • A ⊆ B ↔ A ⊆ a⁻¹ • B := (image_subset_iff).trans $ iff_of_eq $ congr_arg _ $ preimage_equiv_eq_image_symm _ $ mul_action.to_perm _ @[to_additive] lemma subset_set_smul_iff : A ⊆ a • B ↔ a⁻¹ • A ⊆ B := iff.symm $ (image_subset_iff).trans $ iff.symm $ iff_of_eq $ congr_arg _ $ image_equiv_eq_preimage_symm _ $ mul_action.to_perm _ @[to_additive] lemma smul_set_inter : a • (s ∩ t) = a • s ∩ a • t := image_inter $ mul_action.injective a @[to_additive] lemma smul_set_sdiff : a • (s \ t) = a • s \ a • t := image_diff (mul_action.injective a) _ _ @[to_additive] lemma smul_set_symm_diff : a • (s ∆ t) = (a • s) ∆ (a • t) := image_symm_diff (mul_action.injective a) _ _ @[simp, to_additive] lemma smul_set_univ : a • (univ : set β) = univ := image_univ_of_surjective $ mul_action.surjective a @[simp, to_additive] lemma smul_univ {s : set α} (hs : s.nonempty) : s • (univ : set β) = univ := let ⟨a, ha⟩ := hs in eq_univ_of_forall $ λ b, ⟨a, a⁻¹ • b, ha, trivial, smul_inv_smul _ _⟩ @[to_additive] lemma smul_inter_ne_empty_iff {s t : set α} {x : α} : x • s ∩ t ≠ ∅ ↔ ∃ a b, (a ∈ t ∧ b ∈ s) ∧ a * b⁻¹ = x := begin rw ←nonempty_iff_ne_empty, split, { rintros ⟨a, h, ha⟩, obtain ⟨b, hb, rfl⟩ := mem_smul_set.mp h, exact ⟨x • b, b, ⟨ha, hb⟩, by simp⟩, }, { rintros ⟨a, b, ⟨ha, hb⟩, rfl⟩, exact ⟨a, mem_inter (mem_smul_set.mpr ⟨b, hb, by simp⟩) ha⟩, }, end @[to_additive] lemma smul_inter_ne_empty_iff' {s t : set α} {x : α} : x • s ∩ t ≠ ∅ ↔ ∃ a b, (a ∈ t ∧ b ∈ s) ∧ a / b = x := by simp_rw [smul_inter_ne_empty_iff, div_eq_mul_inv] @[to_additive] lemma op_smul_inter_ne_empty_iff {s t : set α} {x : αᵐᵒᵖ} : x • s ∩ t ≠ ∅ ↔ ∃ a b, (a ∈ s ∧ b ∈ t) ∧ a⁻¹ * b = mul_opposite.unop x := begin rw ←nonempty_iff_ne_empty, split, { rintros ⟨a, h, ha⟩, obtain ⟨b, hb, rfl⟩ := mem_smul_set.mp h, exact ⟨b, x • b, ⟨hb, ha⟩, by simp⟩, }, { rintros ⟨a, b, ⟨ha, hb⟩, H⟩, have : mul_opposite.op (a⁻¹ * b) = x := congr_arg mul_opposite.op H, exact ⟨b, mem_inter (mem_smul_set.mpr ⟨a, ha, by simp [← this]⟩) hb⟩, }, end @[simp, to_additive] lemma Union_inv_smul : (⋃ (g : α), g⁻¹ • s) = (⋃ (g : α), g • s) := function.surjective.supr_congr _ inv_surjective $ λ g, rfl @[to_additive] lemma Union_smul_eq_set_of_exists {s : set β} : (⋃ (g : α), g • s) = {a | ∃ (g : α), g • a ∈ s} := by simp_rw [← Union_set_of, ← Union_inv_smul, ← preimage_smul, preimage] end group section group_with_zero variables [group_with_zero α] [mul_action α β] {s t : set β} {a : α} @[simp] lemma smul_mem_smul_set_iff₀ (ha : a ≠ 0) (A : set β) (x : β) : a • x ∈ a • A ↔ x ∈ A := show units.mk0 a ha • _ ∈ _ ↔ _, from smul_mem_smul_set_iff lemma mem_smul_set_iff_inv_smul_mem₀ (ha : a ≠ 0) (A : set β) (x : β) : x ∈ a • A ↔ a⁻¹ • x ∈ A := show _ ∈ units.mk0 a ha • _ ↔ _, from mem_smul_set_iff_inv_smul_mem lemma mem_inv_smul_set_iff₀ (ha : a ≠ 0) (A : set β) (x : β) : x ∈ a⁻¹ • A ↔ a • x ∈ A := show _ ∈ (units.mk0 a ha)⁻¹ • _ ↔ _, from mem_inv_smul_set_iff lemma preimage_smul₀ (ha : a ≠ 0) (t : set β) : (λ x, a • x) ⁻¹' t = a⁻¹ • t := preimage_smul (units.mk0 a ha) t lemma preimage_smul_inv₀ (ha : a ≠ 0) (t : set β) : (λ x, a⁻¹ • x) ⁻¹' t = a • t := preimage_smul ((units.mk0 a ha)⁻¹) t @[simp] lemma set_smul_subset_set_smul_iff₀ (ha : a ≠ 0) {A B : set β} : a • A ⊆ a • B ↔ A ⊆ B := show units.mk0 a ha • _ ⊆ _ ↔ _, from set_smul_subset_set_smul_iff lemma set_smul_subset_iff₀ (ha : a ≠ 0) {A B : set β} : a • A ⊆ B ↔ A ⊆ a⁻¹ • B := show units.mk0 a ha • _ ⊆ _ ↔ _, from set_smul_subset_iff lemma subset_set_smul_iff₀ (ha : a ≠ 0) {A B : set β} : A ⊆ a • B ↔ a⁻¹ • A ⊆ B := show _ ⊆ units.mk0 a ha • _ ↔ _, from subset_set_smul_iff lemma smul_set_inter₀ (ha : a ≠ 0) : a • (s ∩ t) = a • s ∩ a • t := show units.mk0 a ha • _ = _, from smul_set_inter lemma smul_set_sdiff₀ (ha : a ≠ 0) : a • (s \ t) = a • s \ a • t := image_diff (mul_action.injective₀ ha) _ _ lemma smul_set_symm_diff₀ (ha : a ≠ 0) : a • (s ∆ t) = (a • s) ∆ (a • t) := image_symm_diff (mul_action.injective₀ ha) _ _ lemma smul_set_univ₀ (ha : a ≠ 0) : a • (univ : set β) = univ := image_univ_of_surjective $ mul_action.surjective₀ ha lemma smul_univ₀ {s : set α} (hs : ¬ s ⊆ 0) : s • (univ : set β) = univ := let ⟨a, ha, ha₀⟩ := not_subset.1 hs in eq_univ_of_forall $ λ b, ⟨a, a⁻¹ • b, ha, trivial, smul_inv_smul₀ ha₀ _⟩ lemma smul_univ₀' {s : set α} (hs : s.nontrivial) : s • (univ : set β) = univ := smul_univ₀ hs.not_subset_singleton end group_with_zero section monoid variables [monoid α] [add_group β] [distrib_mul_action α β] (a : α) (s : set α) (t : set β) @[simp] lemma smul_set_neg : a • -t = -(a • t) := by simp_rw [←image_smul, ←image_neg, image_image, smul_neg] @[simp] protected lemma smul_neg : s • -t = -(s • t) := by { simp_rw ←image_neg, exact image_image2_right_comm smul_neg } end monoid section ring variables [ring α] [add_comm_group β] [module α β] (a : α) (s : set α) (t : set β) @[simp] lemma neg_smul_set : -a • t = -(a • t) := by simp_rw [←image_smul, ←image_neg, image_image, neg_smul] @[simp] protected lemma neg_smul : -s • t = -(s • t) := by { simp_rw ←image_neg, exact image2_image_left_comm neg_smul } end ring end set
904c27d7b90e07ac1af0f521d1f22b123b231e31
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/linear_algebra/dimension.lean
28d5a4a806be0c0f8c3b7351c2a7a624dd12c080
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
48,790
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Johannes Hölzl, Sander Dahmen, Scott Morrison -/ import linear_algebra.basis import linear_algebra.std_basis import set_theory.cofinality import linear_algebra.invariant_basis_number /-! # Dimension of modules and vector spaces ## Main definitions * The rank of a module is defined as `module.rank : cardinal`. This is defined as the supremum of the cardinalities of linearly independent subsets. * The rank of a linear map is defined as the rank of its range. ## Main statements * `linear_map.dim_le_of_injective`: the source of an injective linear map has dimension at most that of the target. * `linear_map.dim_le_of_surjective`: the target of a surjective linear map has dimension at most that of that source. * `basis_fintype_of_finite_spans`: the existence of a finite spanning set implies that any basis is finite. * `infinite_basis_le_maximal_linear_independent`: if `b` is an infinite basis for a module `M`, and `s` is a maximal linearly independent set, then the cardinality of `b` is bounded by the cardinality of `s`. For modules over rings satisfying the rank condition * `basis.le_span`: the cardinality of a basis is bounded by the cardinality of any spanning set For modules over rings satisfying the strong rank condition * `linear_independent_le_span`: For any linearly independent family `v : ι → M` and any finite spanning set `w : set M`, the cardinality of `ι` is bounded by the cardinality of `w`. * `linear_independent_le_basis`: If `b` is a basis for a module `M`, and `s` is a linearly independent set, then the cardinality of `s` is bounded by the cardinality of `b`. For modules over rings with invariant basis number (including all commutative rings and all noetherian rings) * `mk_eq_mk_of_basis`: the dimension theorem, any two bases of the same vector space have the same cardinality. For vector spaces (i.e. modules over a field), we have * `dim_quotient_add_dim`: if `V₁` is a submodule of `V`, then `module.rank (V/V₁) + module.rank V₁ = module.rank V`. * `dim_range_add_dim_ker`: the rank-nullity theorem. ## Implementation notes There is a naming discrepancy: most of the theorem names refer to `dim`, even though the definition is of `module.rank`. This reflects that `module.rank` was originally called `dim`, and only defined for vector spaces. Many theorems in this file are not universe-generic when they relate dimensions in different universes. They should be as general as they can be without inserting `lift`s. The types `V`, `V'`, ... all live in different universes, and `V₁`, `V₂`, ... all live in the same universe. -/ noncomputable theory universes u v v' v'' u₁' w w' variables {K : Type u} {V V₁ V₂ V₃ : Type v} {V' V'₁ : Type v'} {V'' : Type v''} variables {ι : Type w} {ι' : Type w'} {η : Type u₁'} {φ : η → Type*} open_locale classical big_operators open basis submodule function set section module section variables [semiring K] [add_comm_monoid V] [module K V] include K variables (K V) /-- The rank of a module, defined as a term of type `cardinal`. We define this as the supremum of the cardinalities of linearly independent subsets. For a free module over any ring satisfying the strong rank condition (e.g. left-noetherian rings, commutative rings, and in particular division rings and fields), this is the same as the dimension of the space (i.e. the cardinality of any basis). In particular this agrees with the usual notion of the dimension of a vector space. The definition is marked as protected to avoid conflicts with `_root_.rank`, the rank of a linear map. -/ protected def module.rank : cardinal := cardinal.sup.{v v} (λ ι : {s : set V // linear_independent K (coe : s → V)}, cardinal.mk ι.1) end section variables {R : Type u} [ring R] variables {M : Type v} [add_comm_group M] [module R M] variables {M' : Type v'} [add_comm_group M'] [module R M'] variables {M₁ : Type v} [add_comm_group M₁] [module R M₁] theorem linear_map.lift_dim_le_of_injective (f : M →ₗ[R] M') (i : injective f) : cardinal.lift.{v v'} (module.rank R M) ≤ cardinal.lift.{v' v} (module.rank R M') := begin dsimp [module.rank], fapply cardinal.lift_sup_le_lift_sup', { rintro ⟨s, li⟩, use f '' s, convert (li.map' f (linear_map.ker_eq_bot.mpr i)).comp (equiv.set.image ⇑f s i).symm (equiv.injective _), ext ⟨-, ⟨x, ⟨h, rfl⟩⟩⟩, simp, }, { rintro ⟨s, li⟩, exact cardinal.lift_mk_le'.mpr ⟨(equiv.set.image f s i).to_embedding⟩, } end theorem linear_map.dim_le_of_injective (f : M →ₗ[R] M₁) (i : injective f) : module.rank R M ≤ module.rank R M₁ := cardinal.lift_le.1 (f.lift_dim_le_of_injective i) theorem dim_le {n : ℕ} (H : ∀ s : finset M, linear_independent R (λ i : s, (i : M)) → s.card ≤ n) : module.rank R M ≤ n := begin apply cardinal.sup_le.mpr, rintro ⟨s, li⟩, exact linear_independent_bounded_of_finset_linear_independent_bounded H _ li, end lemma lift_dim_range_le (f : M →ₗ[R] M') : cardinal.lift.{v' v} (module.rank R f.range) ≤ cardinal.lift.{v v'} (module.rank R M) := begin dsimp [module.rank], apply cardinal.lift_sup_le, rintro ⟨s, li⟩, apply le_trans, swap 2, apply cardinal.lift_le.mpr, refine (cardinal.le_sup _ ⟨range_splitting f '' s, _⟩), { apply linear_independent.of_comp f.range_restrict, convert li.comp (equiv.set.range_splitting_image_equiv f s) (equiv.injective _) using 1, }, { exact (cardinal.lift_mk_eq'.mpr ⟨equiv.set.range_splitting_image_equiv f s⟩).ge, }, end lemma dim_range_le (f : M →ₗ[R] M₁) : module.rank R f.range ≤ module.rank R M := by simpa using lift_dim_range_le f lemma lift_dim_map_le (f : M →ₗ[R] M') (p : submodule R M) : cardinal.lift.{v' v} (module.rank R (p.map f)) ≤ cardinal.lift.{v v'} (module.rank R p) := begin have h := lift_dim_range_le (f.comp (submodule.subtype p)), rwa [linear_map.range_comp, range_subtype] at h, end lemma dim_map_le (f : M →ₗ[R] M₁) (p : submodule R M) : module.rank R (p.map f) ≤ module.rank R p := by simpa using lift_dim_map_le f p lemma dim_le_of_submodule (s t : submodule R M) (h : s ≤ t) : module.rank R s ≤ module.rank R t := (of_le h).dim_le_of_injective $ assume ⟨x, hx⟩ ⟨y, hy⟩ eq, subtype.eq $ show x = y, from subtype.ext_iff_val.1 eq /-- Two linearly equivalent vector spaces have the same dimension, a version with different universes. -/ theorem linear_equiv.lift_dim_eq (f : M ≃ₗ[R] M') : cardinal.lift.{v v'} (module.rank R M) = cardinal.lift.{v' v} (module.rank R M') := begin apply le_antisymm, { exact f.to_linear_map.lift_dim_le_of_injective f.injective, }, { exact f.symm.to_linear_map.lift_dim_le_of_injective f.symm.injective, }, end /-- Two linearly equivalent vector spaces have the same dimension. -/ theorem linear_equiv.dim_eq (f : M ≃ₗ[R] M₁) : module.rank R M = module.rank R M₁ := cardinal.lift_inj.1 f.lift_dim_eq lemma dim_eq_of_injective (f : M →ₗ[R] M₁) (h : injective f) : module.rank R M = module.rank R f.range := (linear_equiv.of_injective f h).dim_eq /-- Pushforwards of submodules along a `linear_equiv` have the same dimension. -/ lemma linear_equiv.dim_map_eq (f : M ≃ₗ[R] M₁) (p : submodule R M) : module.rank R (p.map (f : M →ₗ[R] M₁)) = module.rank R p := (f.of_submodule p).dim_eq.symm variables (R M) @[simp] lemma dim_top : module.rank R (⊤ : submodule R M) = module.rank R M := begin have : (⊤ : submodule R M) ≃ₗ[R] M := linear_equiv.of_top ⊤ rfl, rw this.dim_eq, end variables {R M} lemma dim_range_of_surjective (f : M →ₗ[R] M') (h : surjective f) : module.rank R f.range = module.rank R M' := by rw [linear_map.range_eq_top.2 h, dim_top] lemma dim_submodule_le (s : submodule R M) : module.rank R s ≤ module.rank R M := begin rw ←dim_top R M, exact dim_le_of_submodule _ _ le_top, end lemma linear_map.dim_le_of_surjective (f : M →ₗ[R] M₁) (h : surjective f) : module.rank R M₁ ≤ module.rank R M := begin rw ←dim_range_of_surjective f h, apply dim_range_le, end theorem dim_quotient_le (p : submodule R M) : module.rank R p.quotient ≤ module.rank R M := (mkq p).dim_le_of_surjective (surjective_quot_mk _) variables [nontrivial R] lemma {m} cardinal_lift_le_dim_of_linear_independent {ι : Type w} {v : ι → M} (hv : linear_independent R v) : cardinal.lift.{w (max v m)} (cardinal.mk ι) ≤ cardinal.lift.{v (max w m)} (module.rank R M) := begin apply le_trans, { exact cardinal.lift_mk_le.mpr ⟨(equiv.of_injective _ hv.injective).to_embedding⟩, }, { simp only [cardinal.lift_le], apply le_trans, swap, exact cardinal.le_sup _ ⟨range v, hv.coe_range⟩, exact le_refl _, }, end lemma cardinal_le_dim_of_linear_independent {ι : Type v} {v : ι → M} (hv : linear_independent R v) : cardinal.mk ι ≤ module.rank R M := by simpa using cardinal_lift_le_dim_of_linear_independent hv lemma cardinal_le_dim_of_linear_independent' {s : set M} (hs : linear_independent R (λ x, x : s → M)) : cardinal.mk s ≤ module.rank R M := cardinal_le_dim_of_linear_independent hs variables (R M) @[simp] lemma dim_punit : module.rank R punit = 0 := begin apply le_bot_iff.mp, apply cardinal.sup_le.mpr, rintro ⟨s, li⟩, apply le_bot_iff.mpr, apply cardinal.mk_emptyc_iff.mpr, simp only [subtype.coe_mk], by_contradiction h, have ne : s.nonempty := ne_empty_iff_nonempty.mp h, simpa using linear_independent.ne_zero (⟨_, ne.some_mem⟩ : s) li, end @[simp] lemma dim_bot : module.rank R (⊥ : submodule R M) = 0 := begin have : (⊥ : submodule R M) ≃ₗ[R] punit := bot_equiv_punit, rw [this.dim_eq, dim_punit], end variables {R M} /-- Over any nontrivial ring, the existence of a finite spanning set implies that any basis is finite. -/ -- One might hope that a finite spanning set implies that any linearly independent set is finite. -- While this is true over a division ring -- (simply because any linearly independent set can be extended to a basis), -- I'm not certain what more general statements are possible. def basis_fintype_of_finite_spans (w : set M) [fintype w] (s : span R w = ⊤) {ι : Type w} (b : basis ι R M) : fintype ι := begin -- We'll work by contradiction, assuming `ι` is infinite. apply fintype_of_not_infinite _, introI i, -- Let `S` be the union of the supports of `x ∈ w` expressed as linear combinations of `b`. -- This is a finite set since `w` is finite. let S : finset ι := finset.univ.sup (λ x : w, (b.repr x).support), let bS : set M := b '' S, have h : ∀ x ∈ w, x ∈ span R bS, { intros x m, rw [←b.total_repr x, finsupp.span_image_eq_map_total, submodule.mem_map], use b.repr x, simp only [and_true, eq_self_iff_true, finsupp.mem_supported], change (b.repr x).support ≤ S, convert (finset.le_sup (by simp : (⟨x, m⟩ : w) ∈ finset.univ)), refl, }, -- Thus this finite subset of the basis elements spans the entire module. have k : span R bS = ⊤ := eq_top_iff.2 (le_trans s.ge (span_le.2 h)), -- Now there is some `x : ι` not in `S`, since `ι` is infinite. obtain ⟨x, nm⟩ := infinite.exists_not_mem_finset S, -- However it must be in the span of the finite subset, have k' : b x ∈ span R bS, { rw k, exact mem_top, }, -- giving the desire contradiction. refine b.linear_independent.not_mem_span_image _ k', exact nm, end /-- Over any ring `R`, if `b` is a basis for a module `M`, and `s` is a maximal linearly independent set, then the union of the supports of `x ∈ s` (when written out in the basis `b`) is all of `b`. -/ -- From [Les familles libres maximales d'un module ont-elles le meme cardinal?][lazarus1973] lemma union_support_maximal_linear_independent_eq_range_basis {ι : Type w} (b : basis ι R M) {κ : Type w'} (v : κ → M) (i : linear_independent R v) (m : i.maximal) : (⋃ k, ((b.repr (v k)).support : set ι)) = univ := begin -- If that's not the case, by_contradiction h, simp only [←ne.def, ne_univ_iff_exists_not_mem, mem_Union, not_exists_not, finsupp.mem_support_iff, finset.mem_coe] at h, -- We have some basis element `b b'` which is not in the support of any of the `v i`. obtain ⟨b', w⟩ := h, -- Using this, we'll construct a linearly independent family strictly larger than `v`, -- by also using this `b b'`. let v' : option κ → M := λ o, o.elim (b b') v, have r : range v ⊆ range v', { rintro - ⟨k, rfl⟩, use some k, refl, }, have r' : b b' ∉ range v, { rintro ⟨k, p⟩, simpa [w] using congr_arg (λ m, (b.repr m) b') p, }, have r'' : range v ≠ range v', { intro e, have p : b b' ∈ range v', { use none, refl, }, rw ←e at p, exact r' p, }, have inj' : injective v', { rintros (_|k) (_|k) z, { refl, }, { exfalso, exact r' ⟨k, z.symm⟩, }, { exfalso, exact r' ⟨k, z⟩, }, { congr, exact i.injective z, }, }, -- The key step in the proof is checking that this strictly larger family is linearly independent. have i' : linear_independent R (coe : range v' → M), { rw [linear_independent_subtype_range inj', linear_independent_iff], intros l z, rw [finsupp.total_option] at z, simp only [v', option.elim] at z, change _ + finsupp.total κ M R v l.some = 0 at z, -- We have some linear combination of `b b'` and the `v i`, which we want to show is trivial. -- We'll first show the coefficient of `b b'` is zero, -- by expressing the `v i` in the basis `b`, and using that the `v i` have no `b b'` term. have l₀ : l none = 0, { rw ←eq_neg_iff_add_eq_zero at z, replace z := eq_neg_of_eq_neg z, apply_fun (λ x, b.repr x b') at z, simp only [repr_self, linear_equiv.map_smul, mul_one, finsupp.single_eq_same, pi.neg_apply, finsupp.smul_single', linear_equiv.map_neg, finsupp.coe_neg] at z, erw finsupp.congr_fun (finsupp.apply_total R (b.repr : M →ₗ[R] ι →₀ R) v l.some) b' at z, simpa [finsupp.total_apply, w] using z, }, -- Then all the other coefficients are zero, because `v` is linear independent. have l₁ : l.some = 0, { rw [l₀, zero_smul, zero_add] at z, exact linear_independent_iff.mp i _ z, }, -- Finally we put those facts together to show the linear combination is trivial. ext (_|a), { simp only [l₀, finsupp.coe_zero, pi.zero_apply], }, { erw finsupp.congr_fun l₁ a, simp only [finsupp.coe_zero, pi.zero_apply], }, }, dsimp [linear_independent.maximal] at m, specialize m (range v') i' r, exact r'' m, end /-- Over any ring `R`, if `b` is an infinite basis for a module `M`, and `s` is a maximal linearly independent set, then the cardinality of `b` is bounded by the cardinality of `s`. -/ lemma infinite_basis_le_maximal_linear_independent' {ι : Type w} (b : basis ι R M) [infinite ι] {κ : Type w'} (v : κ → M) (i : linear_independent R v) (m : i.maximal) : cardinal.lift.{w w'} (cardinal.mk ι) ≤ cardinal.lift.{w' w} (cardinal.mk κ) := begin let Φ := λ k : κ, (b.repr (v k)).support, have w₁ : cardinal.mk ι ≤ cardinal.mk (set.range Φ), { apply cardinal.le_range_of_union_finset_eq_top, exact union_support_maximal_linear_independent_eq_range_basis b v i m, }, have w₂ : cardinal.lift.{w w'} (cardinal.mk (set.range Φ)) ≤ cardinal.lift.{w' w} (cardinal.mk κ) := cardinal.mk_range_le_lift, exact (cardinal.lift_le.mpr w₁).trans w₂, end /-- Over any ring `R`, if `b` is an infinite basis for a module `M`, and `s` is a maximal linearly independent set, then the cardinality of `b` is bounded by the cardinality of `s`. -/ -- (See `infinite_basis_le_maximal_linear_independent'` for the more general version -- where the index types can live in different universes.) lemma infinite_basis_le_maximal_linear_independent {ι : Type w} (b : basis ι R M) [infinite ι] {κ : Type w} (v : κ → M) (i : linear_independent R v) (m : i.maximal) : cardinal.mk ι ≤ cardinal.mk κ := cardinal.lift_le.mp (infinite_basis_le_maximal_linear_independent' b v i m) end section invariant_basis_number variables {R : Type u} [ring R] [nontrivial R] [invariant_basis_number R] variables {M : Type v} [add_comm_group M] [module R M] /-- The dimension theorem: if `v` and `v'` are two bases, their index types have the same cardinalities. -/ theorem mk_eq_mk_of_basis (v : basis ι R M) (v' : basis ι' R M) : cardinal.lift.{w w'} (cardinal.mk ι) = cardinal.lift.{w' w} (cardinal.mk ι') := begin by_cases h : cardinal.mk ι < cardinal.omega, { -- `v` is a finite basis, so by `basis_fintype_of_finite_spans` so is `v'`. haveI : fintype ι := (cardinal.lt_omega_iff_fintype.mp h).some, haveI : fintype (range v) := set.fintype_range ⇑v, haveI := basis_fintype_of_finite_spans _ v.span_eq v', -- We clean up a little: rw [cardinal.fintype_card, cardinal.fintype_card], simp only [cardinal.lift_nat_cast, cardinal.nat_cast_inj], -- Now we can use invariant basis number to show they have the same cardinality. apply card_eq_of_lequiv R, exact (((finsupp.linear_equiv_fun_on_fintype R R ι).symm.trans v.repr.symm) ≪≫ₗ v'.repr) ≪≫ₗ (finsupp.linear_equiv_fun_on_fintype R R ι'), }, { -- `v` is an infinite basis, -- so by `infinite_basis_le_maximal_linear_independent`, `v'` is at least as big, -- and then applying `infinite_basis_le_maximal_linear_independent` again -- we see they have the same cardinality. simp only [not_lt] at h, haveI : infinite ι := cardinal.infinite_iff.mpr h, have w₁ := infinite_basis_le_maximal_linear_independent' v _ v'.linear_independent v'.maximal, haveI : infinite ι' := cardinal.infinite_iff.mpr (begin apply cardinal.lift_le.{w' w}.mp, have p := (cardinal.lift_le.mpr h).trans w₁, rw cardinal.lift_omega at ⊢ p, exact p, end), have w₂ := infinite_basis_le_maximal_linear_independent' v' _ v.linear_independent v.maximal, exact le_antisymm w₁ w₂, } end theorem mk_eq_mk_of_basis' {ι' : Type w} (v : basis ι R M) (v' : basis ι' R M) : cardinal.mk ι = cardinal.mk ι' := cardinal.lift_inj.1 $ mk_eq_mk_of_basis v v' end invariant_basis_number section rank_condition variables {R : Type u} [ring R] [rank_condition R] variables {M : Type v} [add_comm_group M] [module R M] /-- An auxiliary lemma for `basis.le_span`. If `R` satisfies the rank condition, then for any finite basis `b : basis ι R M`, and any finite spanning set `w : set M`, the cardinality of `ι` is bounded by the cardinality of `w`. -/ lemma basis.le_span'' {ι : Type*} [fintype ι] (b : basis ι R M) {w : set M} [fintype w] (s : span R w = ⊤) : fintype.card ι ≤ fintype.card w := begin -- We construct an surjective linear map `(w → R) →ₗ[R] (ι → R)`, -- by expressing a linear combination in `w` as a linear combination in `ι`. fapply card_le_of_surjective' R, { exact b.repr.to_linear_map.comp (finsupp.total w M R coe), }, { apply surjective.comp, apply linear_equiv.surjective, rw [←linear_map.range_eq_top, finsupp.range_total], simpa using s, }, end variables [nontrivial R] /-- Another auxiliary lemma for `basis.le_span`, which does not require assuming the basis is finite, but still assumes we have a finite spanning set. -/ lemma basis_le_span' {ι : Type*} (b : basis ι R M) {w : set M} [fintype w] (s : span R w = ⊤) : cardinal.mk ι ≤ fintype.card w := begin haveI := basis_fintype_of_finite_spans w s b, rw cardinal.fintype_card ι, simp only [cardinal.nat_cast_le], exact basis.le_span'' b s, end /-- If `R` satisfies the rank condition, then the cardinality of any basis is bounded by the cardinality of any spanning set. -/ -- Note that if `R` satisfies the strong rank condition, -- this also follows from `linear_independent_le_span` below. theorem basis.le_span {J : set M} (v : basis ι R M) (hJ : span R J = ⊤) : cardinal.mk (range v) ≤ cardinal.mk J := begin cases le_or_lt cardinal.omega (cardinal.mk J) with oJ oJ, { have := cardinal.mk_range_eq_of_injective v.injective, let S : J → set ι := λ j, ↑(v.repr j).support, let S' : J → set M := λ j, v '' S j, have hs : range v ⊆ ⋃ j, S' j, { intros b hb, rcases mem_range.1 hb with ⟨i, hi⟩, have : span R J ≤ comap v.repr.to_linear_map (finsupp.supported R R (⋃ j, S j)) := span_le.2 (λ j hj x hx, ⟨_, ⟨⟨j, hj⟩, rfl⟩, hx⟩), rw hJ at this, replace : v.repr (v i) ∈ (finsupp.supported R R (⋃ j, S j)) := this trivial, rw [v.repr_self, finsupp.mem_supported, finsupp.support_single_ne_zero one_ne_zero] at this, { subst b, rcases mem_Union.1 (this (finset.mem_singleton_self _)) with ⟨j, hj⟩, exact mem_Union.2 ⟨j, (mem_image _ _ _).2 ⟨i, hj, rfl⟩⟩ }, { apply_instance } }, refine le_of_not_lt (λ IJ, _), suffices : cardinal.mk (⋃ j, S' j) < cardinal.mk (range v), { exact not_le_of_lt this ⟨set.embedding_of_subset _ _ hs⟩ }, refine lt_of_le_of_lt (le_trans cardinal.mk_Union_le_sum_mk (cardinal.sum_le_sum _ (λ _, cardinal.omega) _)) _, { exact λ j, le_of_lt (cardinal.lt_omega_iff_finite.2 $ (finset.finite_to_set _).image _) }, { rwa [cardinal.sum_const, cardinal.mul_eq_max oJ (le_refl _), max_eq_left oJ] } }, { haveI : fintype J := (cardinal.lt_omega_iff_fintype.mp oJ).some, rw [←cardinal.lift_le, cardinal.mk_range_eq_of_injective v.injective, cardinal.fintype_card J], convert cardinal.lift_le.{w v}.2 (basis_le_span' v hJ), simp, }, end end rank_condition section strong_rank_condition variables {R : Type u} [ring R] [strong_rank_condition R] variables {M : Type v} [add_comm_group M] [module R M] open submodule -- An auxiliary lemma for `linear_independent_le_span'`, -- with the additional assumption that the linearly independent family is finite. lemma linear_independent_le_span_aux' {ι : Type*} [fintype ι] (v : ι → M) (i : linear_independent R v) (w : set M) [fintype w] (s : range v ≤ span R w) : fintype.card ι ≤ fintype.card w := begin -- We construct an injective linear map `(ι → R) →ₗ[R] (w → R)`, -- by thinking of `f : ι → R` as a linear combination of the finite family `v`, -- and expressing that (using the axiom of choice) as a linear combination over `w`. -- We can do this linearly by constructing the map on a basis. fapply card_le_of_injective' R, { apply finsupp.total, exact λ i, span.repr R w ⟨v i, s (mem_range_self i)⟩, }, { intros f g h, apply_fun finsupp.total w M R coe at h, simp only [finsupp.total_total, submodule.coe_mk, span.finsupp_total_repr] at h, rw [←sub_eq_zero, ←linear_map.map_sub] at h, exact sub_eq_zero.mp (linear_independent_iff.mp i _ h), }, end /-- If `R` satisfies the strong rank condition, then any linearly independent family `v : ι → M` contained in the span of some finite `w : set M`, is itself finite. -/ def linear_independent_fintype_of_le_span_fintype {ι : Type*} (v : ι → M) (i : linear_independent R v) (w : set M) [fintype w] (s : range v ≤ span R w) : fintype ι := fintype_of_finset_card_le (fintype.card w) (λ t, begin let v' := λ x : (t : set ι), v x, have i' : linear_independent R v' := i.comp _ subtype.val_injective, have s' : range v' ≤ span R w := (range_comp_subset_range _ _).trans s, simpa using linear_independent_le_span_aux' v' i' w s', end) /-- If `R` satisfies the strong rank condition, then for any linearly independent family `v : ι → M` contained in the span of some finite `w : set M`, the cardinality of `ι` is bounded by the cardinality of `w`. -/ lemma linear_independent_le_span' {ι : Type*} (v : ι → M) (i : linear_independent R v) (w : set M) [fintype w] (s : range v ≤ span R w) : cardinal.mk ι ≤ fintype.card w := begin haveI : fintype ι := linear_independent_fintype_of_le_span_fintype v i w s, rw cardinal.fintype_card, simp only [cardinal.nat_cast_le], exact linear_independent_le_span_aux' v i w s, end /-- If `R` satisfies the strong rank condition, then for any linearly independent family `v : ι → M` and any finite spanning set `w : set M`, the cardinality of `ι` is bounded by the cardinality of `w`. -/ lemma linear_independent_le_span {ι : Type*} (v : ι → M) (i : linear_independent R v) (w : set M) [fintype w] (s : span R w = ⊤) : cardinal.mk ι ≤ fintype.card w := begin apply linear_independent_le_span' v i w, rw s, exact le_top, end /-- An auxiliary lemma for `linear_independent_le_basis`: we handle the case where the basis `b` is infinite. -/ lemma linear_independent_le_infinite_basis {ι : Type*} (b : basis ι R M) [infinite ι] {κ : Type*} (v : κ → M) (i : linear_independent R v) : cardinal.mk κ ≤ cardinal.mk ι := begin by_contradiction, simp only [not_le] at h, have w : cardinal.mk (finset ι) = cardinal.mk ι := cardinal.mk_finset_eq_mk (cardinal.infinite_iff.mp ‹infinite ι›), rw ←w at h, let Φ := λ k : κ, (b.repr (v k)).support, obtain ⟨s, w : infinite ↥(Φ ⁻¹' {s})⟩ := cardinal.exists_infinite_fiber Φ h (by { rw [cardinal.infinite_iff, w], exact (cardinal.infinite_iff.mp ‹infinite ι›), }), let v' := λ k : Φ ⁻¹' {s}, v k, have i' : linear_independent R v' := i.comp _ subtype.val_injective, have w' : fintype (Φ ⁻¹' {s}), { apply linear_independent_fintype_of_le_span_fintype v' i' (s.image b), rintros m ⟨⟨p,⟨rfl⟩⟩,rfl⟩, simp only [set_like.mem_coe, subtype.coe_mk, finset.coe_image], apply basis.mem_span_repr_support, }, exactI w.false, end /-- Over any ring `R` satisfying the strong rank condition, if `b` is a basis for a module `M`, and `s` is a linearly independent set, then the cardinality of `s` is bounded by the cardinality of `b`. -/ lemma linear_independent_le_basis {ι : Type*} (b : basis ι R M) {κ : Type*} (v : κ → M) (i : linear_independent R v) : cardinal.mk κ ≤ cardinal.mk ι := begin -- We split into cases depending on whether `ι` is infinite. cases fintype_or_infinite ι; resetI, { -- When `ι` is finite, we have `linear_independent_le_span`, rw cardinal.fintype_card ι, haveI : nontrivial R := nontrivial_of_invariant_basis_number R, rw fintype.card_congr (equiv.of_injective b b.injective), exact linear_independent_le_span v i (range b) b.span_eq, }, { -- and otherwise we have `linear_indepedent_le_infinite_basis`. exact linear_independent_le_infinite_basis b v i, }, end /-- Over any ring `R` satisfying the strong rank condition, if `b` is an infinite basis for a module `M`, then every maximal linearly independent set has the same cardinality as `b`. This proof (along with some of the lemmas above) comes from [Les familles libres maximales d'un module ont-elles le meme cardinal?][lazarus1973] -/ -- When the basis is not infinite this need not be true! lemma maximal_linear_independent_eq_infinite_basis {ι : Type*} (b : basis ι R M) [infinite ι] {κ : Type*} (v : κ → M) (i : linear_independent R v) (m : i.maximal) : cardinal.mk κ = cardinal.mk ι := begin apply le_antisymm, { exact linear_independent_le_basis b v i, }, { haveI : nontrivial R := nontrivial_of_invariant_basis_number R, exact infinite_basis_le_maximal_linear_independent b v i m, } end variables [nontrivial R] theorem basis.mk_eq_dim'' {ι : Type v} (v : basis ι R M) : cardinal.mk ι = module.rank R M := begin apply le_antisymm, { transitivity, swap, apply cardinal.le_sup, exact ⟨set.range v, by { convert v.reindex_range.linear_independent, ext, simp }⟩, exact (cardinal.eq_congr (equiv.of_injective v v.injective)).le, }, { apply cardinal.sup_le.mpr, rintro ⟨s, li⟩, apply linear_independent_le_basis v _ li, }, end -- By this stage we want to have a complete API for `module.rank`, -- so we set it `irreducible` here, to keep ourselves honest. attribute [irreducible] module.rank theorem basis.mk_range_eq_dim (v : basis ι R M) : cardinal.mk (range v) = module.rank R M := v.reindex_range.mk_eq_dim'' /-- If a vector space has a finite basis, then its dimension (seen as a cardinal) is equal to the cardinality of the basis. -/ lemma dim_eq_card_basis {ι : Type w} [fintype ι] (h : basis ι R M) : module.rank R M = fintype.card ι := by rw [←h.mk_range_eq_dim, cardinal.fintype_card, set.card_range_of_injective h.injective] theorem basis.mk_eq_dim (v : basis ι R M) : cardinal.lift.{w v} (cardinal.mk ι) = cardinal.lift.{v w} (module.rank R M) := by rw [←v.mk_range_eq_dim, cardinal.mk_range_eq_of_injective v.injective] theorem {m} basis.mk_eq_dim' (v : basis ι R M) : cardinal.lift.{w (max v m)} (cardinal.mk ι) = cardinal.lift.{v (max w m)} (module.rank R M) := by simpa using v.mk_eq_dim /-- If a module has a finite dimension, all bases are indexed by a finite type. -/ lemma basis.nonempty_fintype_index_of_dim_lt_omega {ι : Type*} (b : basis ι R M) (h : module.rank R M < cardinal.omega) : nonempty (fintype ι) := by rwa [← cardinal.lift_lt, ← b.mk_eq_dim, -- ensure `omega` has the correct universe cardinal.lift_omega, ← cardinal.lift_omega.{u_1 v}, cardinal.lift_lt, cardinal.lt_omega_iff_fintype] at h /-- If a module has a finite dimension, all bases are indexed by a finite type. -/ noncomputable def basis.fintype_index_of_dim_lt_omega {ι : Type*} (b : basis ι R M) (h : module.rank R M < cardinal.omega) : fintype ι := classical.choice (b.nonempty_fintype_index_of_dim_lt_omega h) /-- If a module has a finite dimension, all bases are indexed by a finite set. -/ lemma basis.finite_index_of_dim_lt_omega {ι : Type*} {s : set ι} (b : basis s R M) (h : module.rank R M < cardinal.omega) : s.finite := b.nonempty_fintype_index_of_dim_lt_omega h lemma dim_span {v : ι → M} (hv : linear_independent R v) : module.rank R ↥(span R (range v)) = cardinal.mk (range v) := by rw [←cardinal.lift_inj, ← (basis.span hv).mk_eq_dim, cardinal.mk_range_eq_of_injective (@linear_independent.injective ι R M v _ _ _ _ hv)] lemma dim_span_set {s : set M} (hs : linear_independent R (λ x, x : s → M)) : module.rank R ↥(span R s) = cardinal.mk s := by { rw [← @set_of_mem_eq _ s, ← subtype.range_coe_subtype], exact dim_span hs } variables (R) lemma dim_self : module.rank R R = 1 := by rw [←cardinal.lift_inj, ← (basis.singleton punit R).mk_eq_dim, cardinal.mk_punit] end strong_rank_condition section division_ring variables [division_ring K] [add_comm_group V] [module K V] [add_comm_group V₁] [module K V₁] variables {K V} /-- If a vector space has a finite dimension, the index set of `basis.of_vector_space` is finite. -/ lemma basis.finite_of_vector_space_index_of_dim_lt_omega (h : module.rank K V < cardinal.omega) : (basis.of_vector_space_index K V).finite := (basis.of_vector_space K V).nonempty_fintype_index_of_dim_lt_omega h variables [add_comm_group V'] [module K V'] /-- Two vector spaces are isomorphic if they have the same dimension. -/ theorem nonempty_linear_equiv_of_lift_dim_eq (cond : cardinal.lift.{v v'} (module.rank K V) = cardinal.lift.{v' v} (module.rank K V')) : nonempty (V ≃ₗ[K] V') := begin let B := basis.of_vector_space K V, let B' := basis.of_vector_space K V', have : cardinal.lift.{v v'} (cardinal.mk _) = cardinal.lift.{v' v} (cardinal.mk _), by rw [B.mk_eq_dim'', cond, B'.mk_eq_dim''], exact (cardinal.lift_mk_eq.{v v' 0}.1 this).map (B.equiv B') end /-- Two vector spaces are isomorphic if they have the same dimension. -/ theorem nonempty_linear_equiv_of_dim_eq (cond : module.rank K V = module.rank K V₁) : nonempty (V ≃ₗ[K] V₁) := nonempty_linear_equiv_of_lift_dim_eq $ congr_arg _ cond section variables (V V' V₁) /-- Two vector spaces are isomorphic if they have the same dimension. -/ def linear_equiv.of_lift_dim_eq (cond : cardinal.lift.{v v'} (module.rank K V) = cardinal.lift.{v' v} (module.rank K V')) : V ≃ₗ[K] V' := classical.choice (nonempty_linear_equiv_of_lift_dim_eq cond) /-- Two vector spaces are isomorphic if they have the same dimension. -/ def linear_equiv.of_dim_eq (cond : module.rank K V = module.rank K V₁) : V ≃ₗ[K] V₁ := classical.choice (nonempty_linear_equiv_of_dim_eq cond) end /-- Two vector spaces are isomorphic if and only if they have the same dimension. -/ theorem linear_equiv.nonempty_equiv_iff_lift_dim_eq : nonempty (V ≃ₗ[K] V') ↔ cardinal.lift.{v v'} (module.rank K V) = cardinal.lift.{v' v} (module.rank K V') := ⟨λ ⟨h⟩, linear_equiv.lift_dim_eq h, λ h, nonempty_linear_equiv_of_lift_dim_eq h⟩ /-- Two vector spaces are isomorphic if and only if they have the same dimension. -/ theorem linear_equiv.nonempty_equiv_iff_dim_eq : nonempty (V ≃ₗ[K] V₁) ↔ module.rank K V = module.rank K V₁ := ⟨λ ⟨h⟩, linear_equiv.dim_eq h, λ h, nonempty_linear_equiv_of_dim_eq h⟩ -- TODO how far can we generalise this? -- When `s` is finite, we could prove this for any ring satisfying the strong rank condition -- using `linear_independent_le_span'` lemma dim_span_le (s : set V) : module.rank K (span K s) ≤ cardinal.mk s := begin classical, rcases exists_linear_independent (linear_independent_empty K V) (set.empty_subset s) with ⟨b, hb, _, hsb, hlib⟩, have hsab : span K s = span K b, from span_eq_of_le _ hsb (span_le.2 (λ x hx, subset_span (hb hx))), convert cardinal.mk_le_mk_of_subset hb, rw [hsab, dim_span_set hlib] end lemma dim_span_of_finset (s : finset V) : module.rank K (span K (↑s : set V)) < cardinal.omega := calc module.rank K (span K (↑s : set V)) ≤ cardinal.mk (↑s : set V) : dim_span_le ↑s ... = s.card : by rw [cardinal.finset_card, finset.coe_sort_coe] ... < cardinal.omega : cardinal.nat_lt_omega _ theorem dim_prod : module.rank K (V × V₁) = module.rank K V + module.rank K V₁ := begin let b := basis.of_vector_space K V, let c := basis.of_vector_space K V₁, rw [← cardinal.lift_inj, ← (basis.prod b c).mk_eq_dim, cardinal.lift_add, cardinal.lift_mk, ← b.mk_eq_dim, ← c.mk_eq_dim, cardinal.lift_mk, cardinal.lift_mk, cardinal.add_def (ulift _)], exact cardinal.lift_inj.1 (cardinal.lift_mk_eq.2 ⟨equiv.ulift.trans (equiv.sum_congr equiv.ulift equiv.ulift).symm ⟩), end -- TODO the remainder of this section should generalize beyond division rings. lemma dim_zero_iff_forall_zero : module.rank K V = 0 ↔ ∀ x : V, x = 0 := begin split, { intros h x, have card_mk_range := (basis.of_vector_space K V).mk_range_eq_dim, rw [h, cardinal.mk_emptyc_iff, coe_of_vector_space, subtype.range_coe] at card_mk_range, simpa [card_mk_range] using (of_vector_space K V).mem_span x }, { intro h, have : (⊤ : submodule K V) = ⊥, { ext x, simp [h x] }, rw [←dim_top, this, dim_bot] } end lemma dim_zero_iff : module.rank K V = 0 ↔ subsingleton V := dim_zero_iff_forall_zero.trans (subsingleton_iff_forall_eq 0).symm lemma dim_pos_iff_exists_ne_zero : 0 < module.rank K V ↔ ∃ x : V, x ≠ 0 := begin rw ←not_iff_not, simpa using dim_zero_iff_forall_zero end lemma dim_pos_iff_nontrivial : 0 < module.rank K V ↔ nontrivial V := dim_pos_iff_exists_ne_zero.trans (nontrivial_iff_exists_ne 0).symm lemma dim_pos [h : nontrivial V] : 0 < module.rank K V := dim_pos_iff_nontrivial.2 h section fintype variable [fintype η] variables [∀i, add_comm_group (φ i)] [∀i, module K (φ i)] open linear_map lemma dim_pi : module.rank K (Πi, φ i) = cardinal.sum (λi, module.rank K (φ i)) := begin let b := assume i, basis.of_vector_space K (φ i), let this : basis (Σ j, _) K (Π j, φ j) := pi.basis b, rw [←cardinal.lift_inj, ← this.mk_eq_dim], simp [λ i, (b i).mk_range_eq_dim.symm, cardinal.sum_mk] end lemma dim_fun {V η : Type u} [fintype η] [add_comm_group V] [module K V] : module.rank K (η → V) = fintype.card η * module.rank K V := by rw [dim_pi, cardinal.sum_const, cardinal.fintype_card] lemma dim_fun_eq_lift_mul : module.rank K (η → V) = (fintype.card η : cardinal.{max u₁' v}) * cardinal.lift.{v u₁'} (module.rank K V) := by rw [dim_pi, cardinal.sum_const_eq_lift_mul, cardinal.fintype_card, cardinal.lift_nat_cast] lemma dim_fun' : module.rank K (η → K) = fintype.card η := by rw [dim_fun_eq_lift_mul, dim_self, cardinal.lift_one, mul_one, cardinal.nat_cast_inj] lemma dim_fin_fun (n : ℕ) : module.rank K (fin n → K) = n := by simp [dim_fun'] end fintype end division_ring section field variables [field K] [add_comm_group V] [module K V] [add_comm_group V₁] [module K V₁] variables [add_comm_group V'] [module K V'] variables {K V} theorem dim_quotient_add_dim (p : submodule K V) : module.rank K p.quotient + module.rank K p = module.rank K V := by classical; exact let ⟨f⟩ := quotient_prod_linear_equiv p in dim_prod.symm.trans f.dim_eq /-- rank-nullity theorem -/ theorem dim_range_add_dim_ker (f : V →ₗ[K] V₁) : module.rank K f.range + module.rank K f.ker = module.rank K V := begin haveI := λ (p : submodule K V), classical.dec_eq p.quotient, rw [← f.quot_ker_equiv_range.dim_eq, dim_quotient_add_dim] end lemma dim_eq_of_surjective (f : V →ₗ[K] V₁) (h : surjective f) : module.rank K V = module.rank K V₁ + module.rank K f.ker := by rw [← dim_range_add_dim_ker f, ← dim_range_of_surjective f h] section variables [add_comm_group V₂] [module K V₂] variables [add_comm_group V₃] [module K V₃] open linear_map /-- This is mostly an auxiliary lemma for `dim_sup_add_dim_inf_eq`. -/ lemma dim_add_dim_split (db : V₂ →ₗ[K] V) (eb : V₃ →ₗ[K] V) (cd : V₁ →ₗ[K] V₂) (ce : V₁ →ₗ[K] V₃) (hde : ⊤ ≤ db.range ⊔ eb.range) (hgd : ker cd = ⊥) (eq : db.comp cd = eb.comp ce) (eq₂ : ∀d e, db d = eb e → (∃c, cd c = d ∧ ce c = e)) : module.rank K V + module.rank K V₁ = module.rank K V₂ + module.rank K V₃ := have hf : surjective (coprod db eb), begin refine (range_eq_top.1 $ top_unique $ _), rwa [← map_top, ← prod_top, map_coprod_prod, ←range_eq_map, ←range_eq_map] end, begin conv {to_rhs, rw [← dim_prod, dim_eq_of_surjective _ hf] }, congr' 1, apply linear_equiv.dim_eq, refine linear_equiv.of_bijective _ _ _, { refine cod_restrict _ (prod cd (- ce)) _, { assume c, simp only [add_eq_zero_iff_eq_neg, linear_map.prod_apply, mem_ker, coprod_apply, neg_neg, map_neg, neg_apply], exact linear_map.ext_iff.1 eq c } }, { rw [← ker_eq_bot, ker_cod_restrict, ker_prod, hgd, bot_inf_eq] }, { rw [← range_eq_top, eq_top_iff, range_cod_restrict, ← map_le_iff_le_comap, map_top, range_subtype], rintros ⟨d, e⟩, have h := eq₂ d (-e), simp only [add_eq_zero_iff_eq_neg, linear_map.prod_apply, mem_ker, set_like.mem_coe, prod.mk.inj_iff, coprod_apply, map_neg, neg_apply, linear_map.mem_range] at ⊢ h, assume hde, rcases h hde with ⟨c, h₁, h₂⟩, refine ⟨c, h₁, _⟩, rw [h₂, _root_.neg_neg] } end lemma dim_sup_add_dim_inf_eq (s t : submodule K V) : module.rank K (s ⊔ t : submodule K V) + module.rank K (s ⊓ t : submodule K V) = module.rank K s + module.rank K t := dim_add_dim_split (of_le le_sup_left) (of_le le_sup_right) (of_le inf_le_left) (of_le inf_le_right) begin rw [← map_le_map_iff' (ker_subtype $ s ⊔ t), map_sup, map_top, ← linear_map.range_comp, ← linear_map.range_comp, subtype_comp_of_le, subtype_comp_of_le, range_subtype, range_subtype, range_subtype], exact le_refl _ end (ker_of_le _ _ _) begin ext ⟨x, hx⟩, refl end begin rintros ⟨b₁, hb₁⟩ ⟨b₂, hb₂⟩ eq, have : b₁ = b₂ := congr_arg subtype.val eq, subst this, exact ⟨⟨b₁, hb₁, hb₂⟩, rfl, rfl⟩ end lemma dim_add_le_dim_add_dim (s t : submodule K V) : module.rank K (s ⊔ t : submodule K V) ≤ module.rank K s + module.rank K t := by { rw [← dim_sup_add_dim_inf_eq], exact self_le_add_right _ _ } end lemma exists_mem_ne_zero_of_ne_bot {s : submodule K V} (h : s ≠ ⊥) : ∃ b : V, b ∈ s ∧ b ≠ 0 := begin classical, by_contradiction hex, have : ∀x∈s, (x:V) = 0, { simpa only [not_exists, not_and, not_not, ne.def] using hex }, exact (h $ bot_unique $ assume s hs, (submodule.mem_bot K).2 $ this s hs) end lemma exists_mem_ne_zero_of_dim_pos {s : submodule K V} (h : 0 < module.rank K s) : ∃ b : V, b ∈ s ∧ b ≠ 0 := exists_mem_ne_zero_of_ne_bot $ assume eq, by rw [eq, dim_bot] at h; exact lt_irrefl _ h section rank -- TODO This definition, and some of the results about it, could be generalized to arbitrary rings. /-- `rank f` is the rank of a `linear_map f`, defined as the dimension of `f.range`. -/ def rank (f : V →ₗ[K] V') : cardinal := module.rank K f.range lemma rank_le_domain (f : V →ₗ[K] V₁) : rank f ≤ module.rank K V := by { rw [← dim_range_add_dim_ker f], exact self_le_add_right _ _ } lemma rank_le_range (f : V →ₗ[K] V₁) : rank f ≤ module.rank K V₁ := dim_submodule_le _ lemma rank_add_le (f g : V →ₗ[K] V') : rank (f + g) ≤ rank f + rank g := calc rank (f + g) ≤ module.rank K (f.range ⊔ g.range : submodule K V') : begin refine dim_le_of_submodule _ _ _, exact (linear_map.range_le_iff_comap.2 $ eq_top_iff'.2 $ assume x, show f x + g x ∈ (f.range ⊔ g.range : submodule K V'), from mem_sup.2 ⟨_, ⟨x, rfl⟩, _, ⟨x, rfl⟩, rfl⟩) end ... ≤ rank f + rank g : dim_add_le_dim_add_dim _ _ @[simp] lemma rank_zero : rank (0 : V →ₗ[K] V') = 0 := by rw [rank, linear_map.range_zero, dim_bot] lemma rank_finset_sum_le {η} (s : finset η) (f : η → V →ₗ[K] V') : rank (∑ d in s, f d) ≤ ∑ d in s, rank (f d) := @finset.sum_hom_rel _ _ _ _ _ (λa b, rank a ≤ b) f (λ d, rank (f d)) s (le_of_eq rank_zero) (λ i g c h, le_trans (rank_add_le _ _) (add_le_add_left h _)) variables [add_comm_group V''] [module K V''] lemma rank_comp_le1 (g : V →ₗ[K] V') (f : V' →ₗ[K] V'') : rank (f.comp g) ≤ rank f := begin refine dim_le_of_submodule _ _ _, rw [linear_map.range_comp], exact linear_map.map_le_range, end variables [add_comm_group V'₁] [module K V'₁] lemma rank_comp_le2 (g : V →ₗ[K] V') (f : V' →ₗ[K] V'₁) : rank (f.comp g) ≤ rank g := by rw [rank, rank, linear_map.range_comp]; exact dim_map_le _ _ end rank -- TODO The remainder of this file could be generalized to arbitrary rings. /-- The `ι` indexed basis on `V`, where `ι` is an empty type and `V` is zero-dimensional. See also `finite_dimensional.fin_basis`. -/ def basis.of_dim_eq_zero {ι : Type*} [is_empty ι] (hV : module.rank K V = 0) : basis ι K V := begin haveI : subsingleton V := dim_zero_iff.1 hV, exact basis.empty _ end @[simp] lemma basis.of_dim_eq_zero_apply {ι : Type*} [is_empty ι] (hV : module.rank K V = 0) (i : ι) : basis.of_dim_eq_zero hV i = 0 := rfl lemma le_dim_iff_exists_linear_independent {c : cardinal} : c ≤ module.rank K V ↔ ∃ s : set V, cardinal.mk s = c ∧ linear_independent K (coe : s → V) := begin split, { intro h, let t := basis.of_vector_space K V, rw [← t.mk_eq_dim'', cardinal.le_mk_iff_exists_subset] at h, rcases h with ⟨s, hst, hsc⟩, exact ⟨s, hsc, (of_vector_space_index.linear_independent K V).mono hst⟩ }, { rintro ⟨s, rfl, si⟩, exact cardinal_le_dim_of_linear_independent si } end lemma le_dim_iff_exists_linear_independent_finset {n : ℕ} : ↑n ≤ module.rank K V ↔ ∃ s : finset V, s.card = n ∧ linear_independent K (coe : (s : set V) → V) := begin simp only [le_dim_iff_exists_linear_independent, cardinal.mk_eq_nat_iff_finset], split, { rintro ⟨s, ⟨t, rfl, rfl⟩, si⟩, exact ⟨t, rfl, si⟩ }, { rintro ⟨s, rfl, si⟩, exact ⟨s, ⟨s, rfl, rfl⟩, si⟩ } end lemma le_rank_iff_exists_linear_independent {c : cardinal} {f : V →ₗ[K] V'} : c ≤ rank f ↔ ∃ s : set V, cardinal.lift.{v v'} (cardinal.mk s) = cardinal.lift.{v' v} c ∧ linear_independent K (λ x : s, f x) := begin rcases f.range_restrict.exists_right_inverse_of_surjective f.range_range_restrict with ⟨g, hg⟩, have fg : left_inverse f.range_restrict g, from linear_map.congr_fun hg, refine ⟨λ h, _, _⟩, { rcases le_dim_iff_exists_linear_independent.1 h with ⟨s, rfl, si⟩, refine ⟨g '' s, cardinal.mk_image_eq_lift _ _ fg.injective, _⟩, replace fg : ∀ x, f (g x) = x, by { intro x, convert congr_arg subtype.val (fg x) }, replace si : linear_independent K (λ x : s, f (g x)), by simpa only [fg] using si.map' _ (ker_subtype _), exact si.image_of_comp s g f }, { rintro ⟨s, hsc, si⟩, have : linear_independent K (λ x : s, f.range_restrict x), from linear_independent.of_comp (f.range.subtype) (by convert si), convert cardinal_le_dim_of_linear_independent this.image, rw [← cardinal.lift_inj, ← hsc, cardinal.mk_image_eq_of_inj_on_lift], exact inj_on_iff_injective.2 this.injective } end lemma le_rank_iff_exists_linear_independent_finset {n : ℕ} {f : V →ₗ[K] V'} : ↑n ≤ rank f ↔ ∃ s : finset V, s.card = n ∧ linear_independent K (λ x : (s : set V), f x) := begin simp only [le_rank_iff_exists_linear_independent, cardinal.lift_nat_cast, cardinal.lift_eq_nat_iff, cardinal.mk_eq_nat_iff_finset], split, { rintro ⟨s, ⟨t, rfl, rfl⟩, si⟩, exact ⟨t, rfl, si⟩ }, { rintro ⟨s, rfl, si⟩, exact ⟨s, ⟨s, rfl, rfl⟩, si⟩ } end /-- A vector space has dimension at most `1` if and only if there is a single vector of which all vectors are multiples. -/ lemma dim_le_one_iff : module.rank K V ≤ 1 ↔ ∃ v₀ : V, ∀ v, ∃ r : K, r • v₀ = v := begin let b := basis.of_vector_space K V, split, { intro hd, rw [← b.mk_eq_dim'', cardinal.le_one_iff_subsingleton, subsingleton_coe] at hd, rcases eq_empty_or_nonempty (of_vector_space_index K V) with hb | ⟨⟨v₀, hv₀⟩⟩, { use 0, have h' : ∀ v : V, v = 0, { simpa [hb, submodule.eq_bot_iff] using b.span_eq.symm }, intro v, simp [h' v] }, { use v₀, have h' : (K ∙ v₀) = ⊤, { simpa [hd.eq_singleton_of_mem hv₀] using b.span_eq }, intro v, have hv : v ∈ (⊤ : submodule K V) := mem_top, rwa [←h', mem_span_singleton] at hv } }, { rintros ⟨v₀, hv₀⟩, have h : (K ∙ v₀) = ⊤, { ext, simp [mem_span_singleton, hv₀] }, rw [←dim_top, ←h], convert dim_span_le _, simp } end /-- A submodule has dimension at most `1` if and only if there is a single vector in the submodule such that the submodule is contained in its span. -/ lemma dim_submodule_le_one_iff (s : submodule K V) : module.rank K s ≤ 1 ↔ ∃ v₀ ∈ s, s ≤ K ∙ v₀ := begin simp_rw [dim_le_one_iff, le_span_singleton_iff], split, { rintro ⟨⟨v₀, hv₀⟩, h⟩, use [v₀, hv₀], intros v hv, obtain ⟨r, hr⟩ := h ⟨v, hv⟩, use r, simp_rw [subtype.ext_iff, coe_smul, submodule.coe_mk] at hr, exact hr }, { rintro ⟨v₀, hv₀, h⟩, use ⟨v₀, hv₀⟩, rintro ⟨v, hv⟩, obtain ⟨r, hr⟩ := h v hv, use r, simp_rw [subtype.ext_iff, coe_smul, submodule.coe_mk], exact hr } end /-- A submodule has dimension at most `1` if and only if there is a single vector, not necessarily in the submodule, such that the submodule is contained in its span. -/ lemma dim_submodule_le_one_iff' (s : submodule K V) : module.rank K s ≤ 1 ↔ ∃ v₀, s ≤ K ∙ v₀ := begin rw dim_submodule_le_one_iff, split, { rintros ⟨v₀, hv₀, h⟩, exact ⟨v₀, h⟩ }, { rintros ⟨v₀, h⟩, by_cases hw : ∃ w : V, w ∈ s ∧ w ≠ 0, { rcases hw with ⟨w, hw, hw0⟩, use [w, hw], rcases mem_span_singleton.1 (h hw) with ⟨r', rfl⟩, have h0 : r' ≠ 0, { rintro rfl, simpa using hw0 }, rwa span_singleton_smul_eq _ h0 }, { push_neg at hw, rw ←submodule.eq_bot_iff at hw, simp [hw] } } end end field end module
c5f272234c347ed25f08a6e78441305ba491f81e
4727251e0cd73359b15b664c3170e5d754078599
/src/ring_theory/principal_ideal_domain.lean
4aeb34fc49dc69f0eaafa08d60ea5962bd67fb5d
[ "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
16,413
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Morenikeji Neri -/ import ring_theory.unique_factorization_domain /-! # Principal ideal rings and principal ideal domains A principal ideal ring (PIR) is a ring in which all left ideals are principal. A principal ideal domain (PID) is an integral domain which is a principal ideal ring. # Main definitions Note that for principal ideal domains, one should use `[is_domain R] [is_principal_ideal_ring R]`. There is no explicit definition of a PID. Theorems about PID's are in the `principal_ideal_ring` namespace. - `is_principal_ideal_ring`: a predicate on rings, saying that every left ideal is principal. - `generator`: a generator of a principal ideal (or more generally submodule) - `to_unique_factorization_monoid`: a PID is a unique factorization domain # Main results - `to_maximal_ideal`: a non-zero prime ideal in a PID is maximal. - `euclidean_domain.to_principal_ideal_domain` : a Euclidean domain is a PID. -/ universes u v variables {R : Type u} {M : Type v} open set function open submodule open_locale classical section variables [ring R] [add_comm_group M] [module R M] /-- An `R`-submodule of `M` is principal if it is generated by one element. -/ class submodule.is_principal (S : submodule R M) : Prop := (principal [] : ∃ a, S = span R {a}) instance bot_is_principal : (⊥ : submodule R M).is_principal := ⟨⟨0, by simp⟩⟩ instance top_is_principal : (⊤ : submodule R R).is_principal := ⟨⟨1, ideal.span_singleton_one.symm⟩⟩ variables (R) /-- A ring is a principal ideal ring if all (left) ideals are principal. -/ class is_principal_ideal_ring (R : Type u) [ring R] : Prop := (principal : ∀ (S : ideal R), S.is_principal) attribute [instance] is_principal_ideal_ring.principal @[priority 100] instance division_ring.is_principal_ideal_ring (K : Type u) [division_ring K] : is_principal_ideal_ring K := { principal := λ S, by rcases ideal.eq_bot_or_top S with (rfl|rfl); apply_instance } end namespace submodule.is_principal variables [add_comm_group M] section ring variables [ring R] [module R M] /-- `generator I`, if `I` is a principal submodule, is an `x ∈ M` such that `span R {x} = I` -/ noncomputable def generator (S : submodule R M) [S.is_principal] : M := classical.some (principal S) lemma span_singleton_generator (S : submodule R M) [S.is_principal] : span R {generator S} = S := eq.symm (classical.some_spec (principal S)) lemma _root_.ideal.span_singleton_generator (I : ideal R) [I.is_principal] : ideal.span ({generator I} : set R) = I := eq.symm (classical.some_spec (principal I)) @[simp] lemma generator_mem (S : submodule R M) [S.is_principal] : generator S ∈ S := by { conv_rhs { rw ← span_singleton_generator S }, exact subset_span (mem_singleton _) } lemma mem_iff_eq_smul_generator (S : submodule R M) [S.is_principal] {x : M} : x ∈ S ↔ ∃ s : R, x = s • generator S := by simp_rw [@eq_comm _ x, ← mem_span_singleton, span_singleton_generator] lemma eq_bot_iff_generator_eq_zero (S : submodule R M) [S.is_principal] : S = ⊥ ↔ generator S = 0 := by rw [← @span_singleton_eq_bot R M, span_singleton_generator] end ring section comm_ring variables [comm_ring R] [module R M] lemma mem_iff_generator_dvd (S : ideal R) [S.is_principal] {x : R} : x ∈ S ↔ generator S ∣ x := (mem_iff_eq_smul_generator S).trans (exists_congr (λ a, by simp only [mul_comm, smul_eq_mul])) lemma prime_generator_of_is_prime (S : ideal R) [submodule.is_principal S] [is_prime : S.is_prime] (ne_bot : S ≠ ⊥) : prime (generator S) := ⟨λ h, ne_bot ((eq_bot_iff_generator_eq_zero S).2 h), λ h, is_prime.ne_top (S.eq_top_of_is_unit_mem (generator_mem S) h), by simpa only [← mem_iff_generator_dvd S] using is_prime.2⟩ -- Note that the converse may not hold if `ϕ` is not injective. lemma generator_map_dvd_of_mem {N : submodule R M} (ϕ : M →ₗ[R] R) [(N.map ϕ).is_principal] {x : M} (hx : x ∈ N) : generator (N.map ϕ) ∣ ϕ x := by { rw [← mem_iff_generator_dvd, submodule.mem_map], exact ⟨x, hx, rfl⟩ } -- Note that the converse may not hold if `ϕ` is not injective. lemma generator_submodule_image_dvd_of_mem {N O : submodule R M} (hNO : N ≤ O) (ϕ : O →ₗ[R] R) [(ϕ.submodule_image N).is_principal] {x : M} (hx : x ∈ N) : generator (ϕ.submodule_image N) ∣ ϕ ⟨x, hNO hx⟩ := by { rw [← mem_iff_generator_dvd, linear_map.mem_submodule_image_of_le hNO], exact ⟨x, hx, rfl⟩ } end comm_ring end submodule.is_principal namespace is_prime open submodule.is_principal ideal -- TODO -- for a non-ID one could perhaps prove that if p < q are prime then q maximal; -- 0 isn't prime in a non-ID PIR but the Krull dimension is still <= 1. -- The below result follows from this, but we could also use the below result to -- prove this (quotient out by p). lemma to_maximal_ideal [comm_ring R] [is_domain R] [is_principal_ideal_ring R] {S : ideal R} [hpi : is_prime S] (hS : S ≠ ⊥) : is_maximal S := is_maximal_iff.2 ⟨(ne_top_iff_one S).1 hpi.1, begin assume T x hST hxS hxT, cases (mem_iff_generator_dvd _).1 (hST $ generator_mem S) with z hz, cases hpi.mem_or_mem (show generator T * z ∈ S, from hz ▸ generator_mem S), { have hTS : T ≤ S, rwa [← T.span_singleton_generator, ideal.span_le, singleton_subset_iff], exact (hxS $ hTS hxT).elim }, cases (mem_iff_generator_dvd _).1 h with y hy, have : generator S ≠ 0 := mt (eq_bot_iff_generator_eq_zero _).2 hS, rw [← mul_one (generator S), hy, mul_left_comm, mul_right_inj' this] at hz, exact hz.symm ▸ T.mul_mem_right _ (generator_mem T) end⟩ end is_prime section open euclidean_domain variable [euclidean_domain R] lemma mod_mem_iff {S : ideal R} {x y : R} (hy : y ∈ S) : x % y ∈ S ↔ x ∈ S := ⟨λ hxy, div_add_mod x y ▸ S.add_mem (S.mul_mem_right _ hy) hxy, λ hx, (mod_eq_sub_mul_div x y).symm ▸ S.sub_mem hx (S.mul_mem_right _ hy)⟩ @[priority 100] -- see Note [lower instance priority] instance euclidean_domain.to_principal_ideal_domain : is_principal_ideal_ring R := { principal := λ S, by exactI ⟨if h : {x : R | x ∈ S ∧ x ≠ 0}.nonempty then have wf : well_founded (euclidean_domain.r : R → R → Prop) := euclidean_domain.r_well_founded, have hmin : well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h ∈ S ∧ well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h ≠ 0, from well_founded.min_mem wf {x : R | x ∈ S ∧ x ≠ 0} h, ⟨well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h, submodule.ext $ λ x, ⟨λ hx, div_add_mod x (well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h) ▸ (ideal.mem_span_singleton.2 $ dvd_add (dvd_mul_right _ _) $ have (x % (well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h) ∉ {x : R | x ∈ S ∧ x ≠ 0}), from λ h₁, well_founded.not_lt_min wf _ h h₁ (mod_lt x hmin.2), have x % well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h = 0, by { simp only [not_and_distrib, set.mem_set_of_eq, not_ne_iff] at this, cases this, cases this ((mod_mem_iff hmin.1).2 hx), exact this }, by simp *), λ hx, let ⟨y, hy⟩ := ideal.mem_span_singleton.1 hx in hy.symm ▸ S.mul_mem_right _ hmin.1⟩⟩ else ⟨0, submodule.ext $ λ a, by rw [← @submodule.bot_coe R R _ _ _, span_eq, submodule.mem_bot]; exact ⟨λ haS, by_contradiction $ λ ha0, h ⟨a, ⟨haS, ha0⟩⟩, λ h₁, h₁.symm ▸ S.zero_mem⟩⟩⟩ } end lemma is_field.is_principal_ideal_ring {R : Type*} [comm_ring R] (h : is_field R) : is_principal_ideal_ring R := @euclidean_domain.to_principal_ideal_domain R (@field.to_euclidean_domain R h.to_field) namespace principal_ideal_ring open is_principal_ideal_ring @[priority 100] -- see Note [lower instance priority] instance is_noetherian_ring [ring R] [is_principal_ideal_ring R] : is_noetherian_ring R := is_noetherian_ring_iff.2 ⟨assume s : ideal R, begin rcases (is_principal_ideal_ring.principal s).principal with ⟨a, rfl⟩, rw [← finset.coe_singleton], exact ⟨{a}, set_like.coe_injective rfl⟩ end⟩ lemma is_maximal_of_irreducible [comm_ring R] [is_principal_ideal_ring R] {p : R} (hp : irreducible p) : ideal.is_maximal (span R ({p} : set R)) := ⟨⟨mt ideal.span_singleton_eq_top.1 hp.1, λ I hI, begin rcases principal I with ⟨a, rfl⟩, erw ideal.span_singleton_eq_top, unfreezingI { rcases ideal.span_singleton_le_span_singleton.1 (le_of_lt hI) with ⟨b, rfl⟩ }, refine (of_irreducible_mul hp).resolve_right (mt (λ hb, _) (not_le_of_lt hI)), erw [ideal.span_singleton_le_span_singleton, is_unit.mul_right_dvd hb] end⟩⟩ variables [comm_ring R] [is_domain R] [is_principal_ideal_ring R] lemma irreducible_iff_prime {p : R} : irreducible p ↔ prime p := ⟨λ hp, (ideal.span_singleton_prime hp.ne_zero).1 $ (is_maximal_of_irreducible hp).is_prime, prime.irreducible⟩ lemma associates_irreducible_iff_prime : ∀{p : associates R}, irreducible p ↔ prime p := associates.irreducible_iff_prime_iff.1 (λ _, irreducible_iff_prime) section open_locale classical /-- `factors a` is a multiset of irreducible elements whose product is `a`, up to units -/ noncomputable def factors (a : R) : multiset R := if h : a = 0 then ∅ else classical.some (wf_dvd_monoid.exists_factors a h) lemma factors_spec (a : R) (h : a ≠ 0) : (∀b∈factors a, irreducible b) ∧ associated (factors a).prod a := begin unfold factors, rw [dif_neg h], exact classical.some_spec (wf_dvd_monoid.exists_factors a h) end lemma ne_zero_of_mem_factors {R : Type v} [comm_ring R] [is_domain R] [is_principal_ideal_ring R] {a b : R} (ha : a ≠ 0) (hb : b ∈ factors a) : b ≠ 0 := irreducible.ne_zero ((factors_spec a ha).1 b hb) lemma mem_submonoid_of_factors_subset_of_units_subset (s : submonoid R) {a : R} (ha : a ≠ 0) (hfac : ∀ b ∈ factors a, b ∈ s) (hunit : ∀ c : Rˣ, (c : R) ∈ s) : a ∈ s := begin rcases ((factors_spec a ha).2) with ⟨c, hc⟩, rw [← hc], exact mul_mem (multiset_prod_mem _ hfac) (hunit _) end /-- If a `ring_hom` maps all units and all factors of an element `a` into a submonoid `s`, then it also maps `a` into that submonoid. -/ lemma ring_hom_mem_submonoid_of_factors_subset_of_units_subset {R S : Type*} [comm_ring R] [is_domain R] [is_principal_ideal_ring R] [semiring S] (f : R →+* S) (s : submonoid S) (a : R) (ha : a ≠ 0) (h : ∀ b ∈ factors a, f b ∈ s) (hf: ∀ c : Rˣ, f c ∈ s) : f a ∈ s := mem_submonoid_of_factors_subset_of_units_subset (s.comap f.to_monoid_hom) ha h hf /-- A principal ideal domain has unique factorization -/ @[priority 100] -- see Note [lower instance priority] instance to_unique_factorization_monoid : unique_factorization_monoid R := { irreducible_iff_prime := λ _, principal_ideal_ring.irreducible_iff_prime .. (is_noetherian_ring.wf_dvd_monoid : wf_dvd_monoid R) } end end principal_ideal_ring section surjective open submodule variables {S N : Type*} [ring R] [add_comm_group M] [add_comm_group N] [ring S] variables [module R M] [module R N] lemma submodule.is_principal.of_comap (f : M →ₗ[R] N) (hf : function.surjective f) (S : submodule R N) [hI : is_principal (S.comap f)] : is_principal S := ⟨⟨f (is_principal.generator (S.comap f)), by rw [← set.image_singleton, ← submodule.map_span, is_principal.span_singleton_generator, submodule.map_comap_eq_of_surjective hf]⟩⟩ lemma ideal.is_principal.of_comap (f : R →+* S) (hf : function.surjective f) (I : ideal S) [hI : is_principal (I.comap f)] : is_principal I := ⟨⟨f (is_principal.generator (I.comap f)), by rw [ideal.submodule_span_eq, ← set.image_singleton, ← ideal.map_span, ideal.span_singleton_generator, ideal.map_comap_of_surjective f hf]⟩⟩ /-- The surjective image of a principal ideal ring is again a principal ideal ring. -/ lemma is_principal_ideal_ring.of_surjective [is_principal_ideal_ring R] (f : R →+* S) (hf : function.surjective f) : is_principal_ideal_ring S := ⟨λ I, ideal.is_principal.of_comap f hf I⟩ end surjective section open ideal variables [comm_ring R] [is_domain R] [is_principal_ideal_ring R] [gcd_monoid R] theorem span_gcd (x y : R) : span ({gcd x y} : set R) = span ({x, y} : set R) := begin obtain ⟨d, hd⟩ := is_principal_ideal_ring.principal (span ({x, y} : set R)), rw submodule_span_eq at hd, rw [hd], suffices : associated d (gcd x y), { obtain ⟨D, HD⟩ := this, rw ←HD, exact (span_singleton_mul_right_unit D.is_unit _) }, apply associated_of_dvd_dvd, { rw dvd_gcd_iff, split; rw [←ideal.mem_span_singleton, ←hd, mem_span_pair], { use [1, 0], rw [one_mul, zero_mul, add_zero] }, { use [0, 1], rw [one_mul, zero_mul, zero_add] } }, { obtain ⟨r, s, rfl⟩ : ∃ r s, r * x + s * y = d, { rw [←mem_span_pair, hd, ideal.mem_span_singleton] }, apply dvd_add; apply dvd_mul_of_dvd_right, exacts [gcd_dvd_left x y, gcd_dvd_right x y] }, end theorem gcd_dvd_iff_exists (a b : R) {z} : gcd a b ∣ z ↔ ∃ x y, z = a * x + b * y := by simp_rw [mul_comm a, mul_comm b, @eq_comm _ z, ←mem_span_pair, ←span_gcd, ideal.mem_span_singleton] /-- **Bézout's lemma** -/ theorem exists_gcd_eq_mul_add_mul (a b : R) : ∃ x y, gcd a b = a * x + b * y := by rw [←gcd_dvd_iff_exists] theorem gcd_is_unit_iff (x y : R) : is_unit (gcd x y) ↔ is_coprime x y := by rw [is_coprime, ←mem_span_pair, ←span_gcd, ←span_singleton_eq_top, eq_top_iff_one] -- this should be proved for UFDs surely? theorem is_coprime_of_dvd (x y : R) (nonzero : ¬ (x = 0 ∧ y = 0)) (H : ∀ z ∈ nonunits R, z ≠ 0 → z ∣ x → ¬ z ∣ y) : is_coprime x y := begin rw [← gcd_is_unit_iff], by_contra h, refine H _ h _ (gcd_dvd_left _ _) (gcd_dvd_right _ _), rwa [ne, gcd_eq_zero_iff] end -- this should be proved for UFDs surely? theorem dvd_or_coprime (x y : R) (h : irreducible x) : x ∣ y ∨ is_coprime x y := begin refine or_iff_not_imp_left.2 (λ h', _), apply is_coprime_of_dvd, { unfreezingI { rintro ⟨rfl, rfl⟩ }, simpa using h }, { unfreezingI { rintro z nu nz ⟨w, rfl⟩ dy }, refine h' (dvd_trans _ dy), simpa using mul_dvd_mul_left z (is_unit_iff_dvd_one.1 $ (of_irreducible_mul h).resolve_left nu) } end theorem is_coprime_of_irreducible_dvd {x y : R} (nonzero : ¬ (x = 0 ∧ y = 0)) (H : ∀ z : R, irreducible z → z ∣ x → ¬ z ∣ y) : is_coprime x y := begin apply is_coprime_of_dvd x y nonzero, intros z znu znz zx zy, obtain ⟨i, h1, h2⟩ := wf_dvd_monoid.exists_irreducible_factor znu znz, apply H i h1; { apply dvd_trans h2, assumption }, end theorem is_coprime_of_prime_dvd {x y : R} (nonzero : ¬ (x = 0 ∧ y = 0)) (H : ∀ z : R, prime z → z ∣ x → ¬ z ∣ y) : is_coprime x y := is_coprime_of_irreducible_dvd nonzero $ λ z zi, H z $ gcd_monoid.prime_of_irreducible zi theorem irreducible.coprime_iff_not_dvd {p n : R} (pp : irreducible p) : is_coprime p n ↔ ¬ p ∣ n := begin split, { intros co H, apply pp.not_unit, rw is_unit_iff_dvd_one, apply is_coprime.dvd_of_dvd_mul_left co, rw mul_one n, exact H }, { intro nd, apply is_coprime_of_irreducible_dvd, { rintro ⟨hp, -⟩, exact pp.ne_zero hp }, rintro z zi zp zn, exact nd (((zi.associated_of_dvd pp zp).symm.dvd).trans zn) }, end theorem prime.coprime_iff_not_dvd {p n : R} (pp : prime p) : is_coprime p n ↔ ¬ p ∣ n := pp.irreducible.coprime_iff_not_dvd theorem irreducible.dvd_iff_not_coprime {p n : R} (hp : irreducible p) : p ∣ n ↔ ¬ is_coprime p n := iff_not_comm.2 hp.coprime_iff_not_dvd theorem irreducible.coprime_pow_of_not_dvd {p a : R} (m : ℕ) (hp : irreducible p) (h : ¬ p ∣ a) : is_coprime a (p ^ m) := (hp.coprime_iff_not_dvd.2 h).symm.pow_right theorem irreducible.coprime_or_dvd {p : R} (hp : irreducible p) (i : R) : is_coprime p i ∨ p ∣ i := (em _).imp_right hp.dvd_iff_not_coprime.2 theorem exists_associated_pow_of_mul_eq_pow' {a b c : R} (hab : is_coprime a b) {k : ℕ} (h : a * b = c ^ k) : ∃ d, associated (d ^ k) a := exists_associated_pow_of_mul_eq_pow ((gcd_is_unit_iff _ _).mpr hab) h end
c327d067033b4a0367c05518a3af0d187643b474
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/06_Inductive_Types.org.47.lean
61db74e1d3412528e97f55b48fbfb6bd599ba86e
[]
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
152
lean
/- page 93 -/ import standard namespace hide -- BEGIN inductive heq {A : Type} (a : A) : Π {B : Type}, B → Prop := refl : heq a a -- END end hide
0f3d9f0ff79a39eda30b225a6ae864d94c133018
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Std/Data/Stack.lean
95a4b20d592584dbabf9756a38b2658b96768239
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
900
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Daniel Selsam Simple stack API implemented using an array. -/ namespace Std universe u v w structure Stack (α : Type u) where vals : Array α := #[] namespace Stack variable {α : Type u} def empty : Stack α := {} def isEmpty (s : Stack α) : Bool := s.vals.isEmpty def push (v : α) (s : Stack α) : Stack α := { s with vals := s.vals.push v } def peek? (s : Stack α) : Option α := if s.vals.isEmpty then none else s.vals.get? (s.vals.size-1) def peek! [Inhabited α] (s : Stack α) : α := s.vals.back def pop [Inhabited α] (s : Stack α) : Stack α := { s with vals := s.vals.pop } def modify [Inhabited α] (s : Stack α) (f : α → α) : Stack α := { s with vals := s.vals.modify (s.vals.size-1) f } end Stack end Std
7d800884253d67e682d201c94f3e5f5c7dd9b82b
9dc8cecdf3c4634764a18254e94d43da07142918
/src/analysis/normed_space/add_torsor.lean
6beb40bab3293b878408a26cb356577c7b06d4eb
[ "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
7,272
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers, Yury Kudryashov -/ import analysis.normed_space.basic import analysis.normed.group.add_torsor import linear_algebra.affine_space.midpoint import linear_algebra.affine_space.affine_subspace import topology.instances.real_vector_space /-! # Torsors of normed space actions. This file contains lemmas about normed additive torsors over normed spaces. -/ noncomputable theory open_locale nnreal topological_space open filter variables {α V P W Q : Type*} [seminormed_add_comm_group V] [pseudo_metric_space P] [normed_add_torsor V P] [normed_add_comm_group W] [metric_space Q] [normed_add_torsor W Q] section normed_space variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 V] [normed_space 𝕜 W] open affine_map lemma affine_subspace.is_closed_direction_iff (s : affine_subspace 𝕜 Q) : is_closed (s.direction : set W) ↔ is_closed (s : set Q) := begin rcases s.eq_bot_or_nonempty with rfl|⟨x, hx⟩, { simp [is_closed_singleton] }, rw [← (isometric.vadd_const x).to_homeomorph.symm.is_closed_image, affine_subspace.coe_direction_eq_vsub_set_right hx], refl end include V @[simp] lemma dist_center_homothety (p₁ p₂ : P) (c : 𝕜) : dist p₁ (homothety p₁ c p₂) = ∥c∥ * dist p₁ p₂ := by simp [homothety_def, norm_smul, ← dist_eq_norm_vsub, dist_comm] @[simp] lemma dist_homothety_center (p₁ p₂ : P) (c : 𝕜) : dist (homothety p₁ c p₂) p₁ = ∥c∥ * dist p₁ p₂ := by rw [dist_comm, dist_center_homothety] @[simp] lemma dist_line_map_line_map (p₁ p₂ : P) (c₁ c₂ : 𝕜) : dist (line_map p₁ p₂ c₁) (line_map p₁ p₂ c₂) = dist c₁ c₂ * dist p₁ p₂ := begin rw dist_comm p₁ p₂, simp only [line_map_apply, dist_eq_norm_vsub, vadd_vsub_vadd_cancel_right, ← sub_smul, norm_smul, vsub_eq_sub], end lemma lipschitz_with_line_map (p₁ p₂ : P) : lipschitz_with (nndist p₁ p₂) (line_map p₁ p₂ : 𝕜 → P) := lipschitz_with.of_dist_le_mul $ λ c₁ c₂, ((dist_line_map_line_map p₁ p₂ c₁ c₂).trans (mul_comm _ _)).le @[simp] lemma dist_line_map_left (p₁ p₂ : P) (c : 𝕜) : dist (line_map p₁ p₂ c) p₁ = ∥c∥ * dist p₁ p₂ := by simpa only [line_map_apply_zero, dist_zero_right] using dist_line_map_line_map p₁ p₂ c 0 @[simp] lemma dist_left_line_map (p₁ p₂ : P) (c : 𝕜) : dist p₁ (line_map p₁ p₂ c) = ∥c∥ * dist p₁ p₂ := (dist_comm _ _).trans (dist_line_map_left _ _ _) @[simp] lemma dist_line_map_right (p₁ p₂ : P) (c : 𝕜) : dist (line_map p₁ p₂ c) p₂ = ∥1 - c∥ * dist p₁ p₂ := by simpa only [line_map_apply_one, dist_eq_norm'] using dist_line_map_line_map p₁ p₂ c 1 @[simp] lemma dist_right_line_map (p₁ p₂ : P) (c : 𝕜) : dist p₂ (line_map p₁ p₂ c) = ∥1 - c∥ * dist p₁ p₂ := (dist_comm _ _).trans (dist_line_map_right _ _ _) @[simp] lemma dist_homothety_self (p₁ p₂ : P) (c : 𝕜) : dist (homothety p₁ c p₂) p₂ = ∥1 - c∥ * dist p₁ p₂ := by rw [homothety_eq_line_map, dist_line_map_right] @[simp] lemma dist_self_homothety (p₁ p₂ : P) (c : 𝕜) : dist p₂ (homothety p₁ c p₂) = ∥1 - c∥ * dist p₁ p₂ := by rw [dist_comm, dist_homothety_self] section invertible_two variables [invertible (2:𝕜)] @[simp] lemma dist_left_midpoint (p₁ p₂ : P) : dist p₁ (midpoint 𝕜 p₁ p₂) = ∥(2:𝕜)∥⁻¹ * dist p₁ p₂ := by rw [midpoint, dist_comm, dist_line_map_left, inv_of_eq_inv, ← norm_inv] @[simp] lemma dist_midpoint_left (p₁ p₂ : P) : dist (midpoint 𝕜 p₁ p₂) p₁ = ∥(2:𝕜)∥⁻¹ * dist p₁ p₂ := by rw [dist_comm, dist_left_midpoint] @[simp] lemma dist_midpoint_right (p₁ p₂ : P) : dist (midpoint 𝕜 p₁ p₂) p₂ = ∥(2:𝕜)∥⁻¹ * dist p₁ p₂ := by rw [midpoint_comm, dist_midpoint_left, dist_comm] @[simp] lemma dist_right_midpoint (p₁ p₂ : P) : dist p₂ (midpoint 𝕜 p₁ p₂) = ∥(2:𝕜)∥⁻¹ * dist p₁ p₂ := by rw [dist_comm, dist_midpoint_right] lemma dist_midpoint_midpoint_le' (p₁ p₂ p₃ p₄ : P) : dist (midpoint 𝕜 p₁ p₂) (midpoint 𝕜 p₃ p₄) ≤ (dist p₁ p₃ + dist p₂ p₄) / ∥(2 : 𝕜)∥ := begin rw [dist_eq_norm_vsub V, dist_eq_norm_vsub V, dist_eq_norm_vsub V, midpoint_vsub_midpoint]; try { apply_instance }, rw [midpoint_eq_smul_add, norm_smul, inv_of_eq_inv, norm_inv, ← div_eq_inv_mul], exact div_le_div_of_le_of_nonneg (norm_add_le _ _) (norm_nonneg _), end end invertible_two omit V include W lemma antilipschitz_with_line_map {p₁ p₂ : Q} (h : p₁ ≠ p₂) : antilipschitz_with (nndist p₁ p₂)⁻¹ (line_map p₁ p₂ : 𝕜 → Q) := antilipschitz_with.of_le_mul_dist $ λ c₁ c₂, by rw [dist_line_map_line_map, nnreal.coe_inv, ← dist_nndist, mul_left_comm, inv_mul_cancel (dist_ne_zero.2 h), mul_one] variables (𝕜) lemma eventually_homothety_mem_of_mem_interior (x : Q) {s : set Q} {y : Q} (hy : y ∈ interior s) : ∀ᶠ δ in 𝓝 (1 : 𝕜), homothety x δ y ∈ s := begin rw (normed_add_comm_group.nhds_basis_norm_lt (1 : 𝕜)).eventually_iff, cases eq_or_ne y x with h h, { use 1, simp [h.symm, interior_subset hy], }, have hxy : 0 < ∥y -ᵥ x∥, { rwa [norm_pos_iff, vsub_ne_zero], }, obtain ⟨u, hu₁, hu₂, hu₃⟩ := mem_interior.mp hy, obtain ⟨ε, hε, hyε⟩ := metric.is_open_iff.mp hu₂ y hu₃, refine ⟨ε / ∥y -ᵥ x∥, div_pos hε hxy, λ δ (hδ : ∥δ - 1∥ < ε / ∥y -ᵥ x∥), hu₁ (hyε _)⟩, rw [lt_div_iff hxy, ← norm_smul, sub_smul, one_smul] at hδ, rwa [homothety_apply, metric.mem_ball, dist_eq_norm_vsub W, vadd_vsub_eq_sub_vsub], end lemma eventually_homothety_image_subset_of_finite_subset_interior (x : Q) {s : set Q} {t : set Q} (ht : t.finite) (h : t ⊆ interior s) : ∀ᶠ δ in 𝓝 (1 : 𝕜), homothety x δ '' t ⊆ s := begin suffices : ∀ y ∈ t, ∀ᶠ δ in 𝓝 (1 : 𝕜), homothety x δ y ∈ s, { simp_rw set.image_subset_iff, exact (filter.eventually_all_finite ht).mpr this, }, intros y hy, exact eventually_homothety_mem_of_mem_interior 𝕜 x (h hy), end end normed_space variables [normed_space ℝ V] [normed_space ℝ W] lemma dist_midpoint_midpoint_le (p₁ p₂ p₃ p₄ : V) : dist (midpoint ℝ p₁ p₂) (midpoint ℝ p₃ p₄) ≤ (dist p₁ p₃ + dist p₂ p₄) / 2 := by simpa using dist_midpoint_midpoint_le' p₁ p₂ p₃ p₄ include V W /-- A continuous map between two normed affine spaces is an affine map provided that it sends midpoints to midpoints. -/ def affine_map.of_map_midpoint (f : P → Q) (h : ∀ x y, f (midpoint ℝ x y) = midpoint ℝ (f x) (f y)) (hfc : continuous f) : P →ᵃ[ℝ] Q := affine_map.mk' f ↑((add_monoid_hom.of_map_midpoint ℝ ℝ ((affine_equiv.vadd_const ℝ (f $ classical.arbitrary P)).symm ∘ f ∘ (affine_equiv.vadd_const ℝ (classical.arbitrary P))) (by simp) (λ x y, by simp [h])).to_real_linear_map $ by apply_rules [continuous.vadd, continuous.vsub, continuous_const, hfc.comp, continuous_id]) (classical.arbitrary P) (λ p, by simp)
f0dfcaaa8a8186d45aa470cae20f73d374e0216f
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/elab_meta1.lean
451cf1464736d7e1c8563c0e8a5ef2918f5822f1
[ "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
226
lean
meta definition f : nat → nat | n := if n / 2 = 0 then n + 1 else f (n / 2) + 1 meta definition g : nat × nat → nat | (0, b) := b | (a+1, b+1) := g (a/2 - 1, a + b) | (a+1, 0) := 2*a #eval f 200 #eval g (10, 20)
146a05a074920346aa7a2153f269d29751f65217
5719a16e23dfc08cdea7a5bf035b81690f307965
/src/Init/Control/Except.lean
8cd89a207e463515bbbef66ccb129ea302fd1046
[ "Apache-2.0" ]
permissive
postmasters/lean4
488b03969a371e1507e1e8a4df9ebf63c7cbe7ac
f3976fc53a883ac7606fc59357d43f4b51016ca7
refs/heads/master
1,655,582,707,480
1,588,682,595,000
1,588,682,595,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,097
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jared Roesch, Sebastian Ullrich The Except monad transformer. -/ prelude import Init.Control.Alternative import Init.Control.Lift import Init.Data.ToString universes u v w inductive Except (ε : Type u) (α : Type v) | error {} : ε → Except | ok {} : α → Except attribute [unbox] Except instance {ε : Type u} {α : Type v} [Inhabited ε] : Inhabited (Except ε α) := ⟨Except.error (arbitrary ε)⟩ section variables {ε : Type u} {α : Type v} protected def Except.toString [HasToString ε] [HasToString α] : Except ε α → String | Except.error e => "(error " ++ toString e ++ ")" | Except.ok a => "(ok " ++ toString a ++ ")" protected def Except.repr [HasRepr ε] [HasRepr α] : Except ε α → String | Except.error e => "(error " ++ repr e ++ ")" | Except.ok a => "(ok " ++ repr a ++ ")" instance [HasToString ε] [HasToString α] : HasToString (Except ε α) := ⟨Except.toString⟩ instance [HasRepr ε] [HasRepr α] : HasRepr (Except ε α) := ⟨Except.repr⟩ end namespace Except variables {ε : Type u} @[inline] protected def return {α : Type v} (a : α) : Except ε α := Except.ok a @[inline] protected def map {α β : Type v} (f : α → β) : Except ε α → Except ε β | Except.error err => Except.error err | Except.ok v => Except.ok $ f v @[inline] protected def mapError {ε' : Type u} {α : Type v} (f : ε → ε') : Except ε α → Except ε' α | Except.error err => Except.error $ f err | Except.ok v => Except.ok v @[inline] protected def bind {α β : Type v} (ma : Except ε α) (f : α → Except ε β) : Except ε β := match ma with | (Except.error err) => Except.error err | (Except.ok v) => f v @[inline] protected def toBool {α : Type v} : Except ε α → Bool | Except.ok _ => true | Except.error _ => false @[inline] protected def toOption {α : Type v} : Except ε α → Option α | Except.ok a => some a | Except.error _ => none @[inline] protected def catch {α : Type u} (ma : Except ε α) (handle : ε → Except ε α) : Except ε α := match ma with | Except.ok a => Except.ok a | Except.error e => handle e instance : Monad (Except ε) := { pure := @Except.return _, bind := @Except.bind _, map := @Except.map _ } end Except def ExceptT (ε : Type u) (m : Type u → Type v) (α : Type u) : Type v := m (Except ε α) @[inline] def ExceptT.mk {ε : Type u} {m : Type u → Type v} {α : Type u} (x : m (Except ε α)) : ExceptT ε m α := x @[inline] def ExceptT.run {ε : Type u} {m : Type u → Type v} {α : Type u} (x : ExceptT ε m α) : m (Except ε α) := x namespace ExceptT variables {ε : Type u} {m : Type u → Type v} [Monad m] @[inline] protected def pure {α : Type u} (a : α) : ExceptT ε m α := ExceptT.mk $ pure (Except.ok a) @[inline] protected def bindCont {α β : Type u} (f : α → ExceptT ε m β) : Except ε α → m (Except ε β) | Except.ok a => f a | Except.error e => pure (Except.error e) @[inline] protected def bind {α β : Type u} (ma : ExceptT ε m α) (f : α → ExceptT ε m β) : ExceptT ε m β := ExceptT.mk $ ma >>= ExceptT.bindCont f @[inline] protected def map {α β : Type u} (f : α → β) (x : ExceptT ε m α) : ExceptT ε m β := ExceptT.mk $ x >>= fun a => match a with | (Except.ok a) => pure $ Except.ok (f a) | (Except.error e) => pure $ Except.error e @[inline] protected def lift {α : Type u} (t : m α) : ExceptT ε m α := ExceptT.mk $ Except.ok <$> t instance exceptTOfExcept : HasMonadLift (Except ε) (ExceptT ε m) := ⟨fun α e => ExceptT.mk $ pure e⟩ instance : HasMonadLift m (ExceptT ε m) := ⟨@ExceptT.lift _ _ _⟩ @[inline] protected def catch {α : Type u} (ma : ExceptT ε m α) (handle : ε → ExceptT ε m α) : ExceptT ε m α := ExceptT.mk $ ma >>= fun res => match res with | Except.ok a => pure (Except.ok a) | Except.error e => (handle e) instance (m') [Monad m'] : MonadFunctor m m' (ExceptT ε m) (ExceptT ε m') := ⟨fun _ f x => f x⟩ instance : Monad (ExceptT ε m) := { pure := @ExceptT.pure _ _ _, bind := @ExceptT.bind _ _ _, map := @ExceptT.map _ _ _ } @[inline] protected def adapt {ε' α : Type u} (f : ε → ε') : ExceptT ε m α → ExceptT ε' m α := fun x => ExceptT.mk $ Except.mapError f <$> x end ExceptT /-- An implementation of [MonadError](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Except.html#t:MonadError) -/ class MonadExcept (ε : outParam (Type u)) (m : Type v → Type w) := (throw {} {α : Type v} : ε → m α) (catch {} {α : Type v} : m α → (ε → m α) → m α) namespace MonadExcept variables {ε : Type u} {m : Type v → Type w} @[inline] protected def orelse [MonadExcept ε m] {α : Type v} (t₁ t₂ : m α) : m α := catch t₁ $ fun _ => t₂ instance [MonadExcept ε m] {α : Type v} : HasOrelse (m α) := ⟨MonadExcept.orelse⟩ /-- Alternative orelse operator that allows to select which exception should be used. The default is to use the first exception since the standard `orelse` uses the second. -/ @[inline] def orelse' [MonadExcept ε m] {α : Type v} (t₁ t₂ : m α) (useFirstEx := true) : m α := catch t₁ $ fun e₁ => catch t₂ $ fun e₂ => throw (if useFirstEx then e₁ else e₂) end MonadExcept export MonadExcept (throw catch) instance (m : Type u → Type v) (ε : Type u) [Monad m] : MonadExcept ε (ExceptT ε m) := { throw := fun α e => ExceptT.mk $ pure (Except.error e), catch := @ExceptT.catch ε _ _ } instance (ε) : MonadExcept ε (Except ε) := { throw := fun α => Except.error, catch := @Except.catch _ } /-- Adapt a Monad stack, changing its top-most error Type. Note: This class can be seen as a simplification of the more "principled" definition ``` class MonadExceptFunctor (ε ε' : outParam (Type u)) (n n' : Type u → Type u) := (map {} {α : Type u} : (∀ {m : Type u → Type u} [Monad m], ExceptT ε m α → ExceptT ε' m α) → n α → n' α) ``` -/ class MonadExceptAdapter (ε ε' : outParam (Type u)) (m m' : Type u → Type v) := (adaptExcept {} {α : Type u} : (ε → ε') → m α → m' α) export MonadExceptAdapter (adaptExcept) section variables {ε ε' : Type u} {m m' : Type u → Type v} instance monadExceptAdapterTrans {n n' : Type u → Type v} [MonadExceptAdapter ε ε' m m'] [MonadFunctor m m' n n'] : MonadExceptAdapter ε ε' n n' := ⟨fun α f => monadMap (fun α => (adaptExcept f : m α → m' α))⟩ instance [Monad m] : MonadExceptAdapter ε ε' (ExceptT ε m) (ExceptT ε' m) := ⟨fun α => ExceptT.adapt⟩ end instance (ε m out) [MonadRun out m] : MonadRun (fun α => out (Except ε α)) (ExceptT ε m) := ⟨fun α => run⟩ /-- Execute `x` and then execute `finalizer` even if `x` threw an exception -/ @[inline] def finally {ε α : Type u} {m : Type u → Type v} [Monad m] [MonadExcept ε m] (x : m α) (finalizer : m PUnit) : m α := catch (do a ← x; finalizer; pure a) (fun e => do finalizer; throw e)
e1457ebcb74454daf251f85ab12082d61e5cb23a
2d041ea7f2e9b29093ffd7c99b11decfaa8b20ca
/ch4.lean
d3a517ac44b651ddd677a78839c43c5a4887941e
[]
no_license
0xpr/lean_tutorial
1a66577602baa9a52c2b01130b9d70089653ea37
56ef609d8df9e392916012db5354bf182cbbb8d8
refs/heads/master
1,606,955,421,810
1,499,014,388,000
1,499,014,388,000
96,036,899
1
0
null
null
null
null
UTF-8
Lean
false
false
6,656
lean
variables (A : Type) (p q : A → Prop) example : (∀ x, p x ∧ q x) ↔ (∀ x, p x) ∧ (∀ x, q x) := iff.intro (λ H : ∀ x, p x ∧ q x, and.intro (λ x : A, and.elim_left (H x)) (λ x : A, and.elim_right (H x))) (λ H : (∀ x, p x) ∧ (∀ x, q x), (λ x : A, and.intro ((and.elim_left H) x) ((and.elim_right H) x))) example : (∀ x, p x → q x) → (∀ x, p x) → (∀ x, q x) := (λ H1 : (∀ x, p x → q x), (λ H2 : (∀ x, p x), (λ x : A, (H1 x) (H2 x)))) example : (∀ x, p x) ∨ (∀ x, q x) → ∀ x, p x ∨ q x := (λ H : (∀ x, p x) ∨ (∀ x, q x), (λ x : A, or.elim H (λ h : (∀ x, p x), or.inl (h x)) (λ h : (∀ x, q x), or.inr (h x)))) open classical variable r : Prop variable a : A example : A → ((∀ x : A, r) ↔ r) := (λ x : A, iff.intro (λ H : (∀ x : A, r), H x) (λ Hr : r, (λ x : A, Hr))) example : (∀ x, p x ∨ r) ↔ (∀ x, p x) ∨ r := iff.intro (λ H : (∀ x, p x ∨ r), or.elim (em r) (λ Hr : r, or.inr Hr) (λ Hnr : ¬r, or.inl (λ x : A, or.elim (H x) (λ h : p x, h) (λ Hr : r, absurd Hr Hnr)))) (λ H : (∀ x, p x) ∨ r, (λ x : A, or.elim H (λ h : (∀ x, p x), or.inl (h x)) (λ Hr : r, or.inr Hr))) example : (∀ x, r → p x) ↔ (r → ∀ x, p x) := iff.intro (λ H : (∀ x, r → p x), (λ Hr : r, (λ x : A, (H x) Hr))) (λ H : (r → ∀ x, p x), (λ x : A, (λ Hr : r, (H Hr) x))) variables (men : Type) (barber : men) (shaves : men → men → Prop) example (H : ∀ x : men, shaves barber x ↔ ¬shaves x x) : false := let Hn := (λ h : shaves barber barber, (iff.elim_left(H barber) h) h) in Hn (iff.elim_right(H barber) Hn) open classical example : (∃ x : A, r) → r := assume H : (∃ x : A, r), obtain (w : A) (Hr : r), from H, Hr example : r → (∃ x : A, r) := assume Hr : r, exists.intro a Hr example : (∃ x, p x ∧ r) ↔ (∃ x, p x) ∧ r := iff.intro (assume H : (∃ x, p x ∧ r), and.intro (obtain w px_r, from H, exists.intro w (and.elim_left px_r)) (obtain w px_r, from H, and.elim_right px_r)) (assume H : (∃ x, p x) ∧ r, have Hr : r, from and.elim_right H, obtain w px, from and.elim_left H, exists.intro w (and.intro px Hr)) example : (∃ x, p x ∨ q x) ↔ (∃ x, p x) ∨ (∃ x, q x) := iff.intro (assume H : (∃ x, p x ∨ q x), obtain w pw_qw, from H, or.elim pw_qw (assume Hp : p w, or.inl (exists.intro w Hp)) (assume Hq : q w, or.inr (exists.intro w Hq))) (assume H : (∃ x, p x) ∨ (∃ x, q x), or.elim H (assume H : (∃ x, p x), obtain w pw, from H, exists.intro w (or.inl pw)) (assume H : (∃ x, q x), obtain w qw, from H, exists.intro w (or.inr qw))) example : (∀ x, p x) ↔ ¬ (∃ x, ¬ p x) := iff.intro (assume H : (∀ x, p x), assume H1 : (∃ x, ¬ p x), obtain w npw, from H1, npw (H w)) (assume H : ¬ (∃ x, ¬ p x), take x, or.elim (em (p x)) (assume Hp : p x, Hp) (assume Hnp : ¬ p x, absurd (exists.intro x Hnp) H)) example : (∃ x, p x) ↔ ¬ (∀ x, ¬ p x) := iff.intro (assume H : (∃ x, p x), assume H1 : (∀ x, ¬ p x), obtain w pw, from H, (H1 w) pw) (assume H : ¬ (∀ x, ¬ p x), by_contradiction (assume H1 : ¬ (∃ x, p x), H (take x, or.elim (em (p x)) (assume px : p x, absurd (exists.intro x px) H1) (assume pnx : ¬ (p x), pnx)))) example : (¬ ∃ x, p x) ↔ (∀ x, ¬ p x) := iff.intro (assume H : (¬ ∃ x, p x), take x, (λ px : p x, H (exists.intro x px))) (assume H : ∀ x, ¬ p x, (λ H1 : (∃ x, p x), obtain w pw, from H1, (H w) pw)) example : (¬ ∀ x, p x) ↔ (∃ x, ¬ p x) := iff.intro (assume H : (¬ ∀ x, p x), by_contradiction (assume H1 : ¬(∃ x, ¬ p x), H (take x, or.elim (em (p x)) (λ px : p x, px) (λ pnx : ¬ p x, absurd (exists.intro x pnx) H1)))) (assume H : (∃ x, ¬ p x), obtain w pnw, from H, (assume H: (∀ x, p x), pnw (H w))) example : (∀ x, p x → r) ↔ (∃ x, p x) → r := iff.intro (assume H : (∀ x, p x → r), assume H1 : (∃ x, p x), obtain w pw, from H1, (H w) pw) (assume H : (∃ x, p x) → r, take x, (λ px : p x, H (exists.intro x px))) example : (∃ x, p x → r) ↔ (∀ x, p x) → r := iff.intro (assume H : (∃ x, p x → r), (assume H1 : (∀ x, p x), obtain w pw_r, from H, pw_r (H1 w))) (assume H : (∀ x, p x) → r, by_cases (assume Hap : (∀ x, p x), exists.intro a (λ pa : p a, H Hap)) (assume Hnap : ¬(∀ x, p x), by_contradiction (assume Hnex : ¬(∃ x, p x → r), have Hap : (∀ x, p x), from take x, by_contradiction (assume Hnpx : ¬ p x, Hnex (exists.intro x (λ Hpx : p x, absurd Hpx Hnpx))), Hnap Hap))) example : (∃ x, r → p x) ↔ (r → ∃ x, p x) := iff.intro (assume H : (∃ x, r → p x), assume Hr : r, obtain w r_pw, from H, exists.intro w (r_pw Hr)) (assume H : (r → ∃ x, p x), by_cases (λ Hr : r, obtain w pw, from H Hr, exists.intro w (λ Hr : r, pw)) (λ Hnr : ¬ r, exists.intro a (λ Hr : r, absurd Hr Hnr)))
0d2d78617f450867d26f7799124b14b99fa8779d
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/field_theory/cardinality.lean
e01d6b48ab64b9eefe967e3d495eb5ad37514b3e
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
3,596
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 algebra.field.ulift import data.mv_polynomial.cardinal import data.nat.factorization.prime_pow import data.rat.denumerable import field_theory.finite.galois_field import logic.equiv.transfer_instance import ring_theory.localization.cardinality import set_theory.cardinal.divisibility /-! # Cardinality of Fields > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we show all the possible cardinalities of fields. All infinite cardinals can harbour a field structure, and so can all types with prime power cardinalities, and this is sharp. ## Main statements * `fintype.nonempty_field_iff`: A `fintype` can be given a field structure iff its cardinality is a prime power. * `infinite.nonempty_field` : Any infinite type can be endowed a field structure. * `field.nonempty_iff` : There is a field structure on type iff its cardinality is a prime power. -/ local notation `‖` x `‖` := fintype.card x open_locale cardinal non_zero_divisors universe u /-- A finite field has prime power cardinality. -/ lemma fintype.is_prime_pow_card_of_field {α} [fintype α] [field α] : is_prime_pow (‖α‖) := begin -- TODO: `algebra` version of `char_p.exists`, of type `Σ p, algebra (zmod p) α` casesI char_p.exists α with p _, haveI hp := fact.mk (char_p.char_is_prime α p), letI : algebra (zmod p) α := zmod.algebra _ _, let b := is_noetherian.finset_basis (zmod p) α, rw [module.card_fintype b, zmod.card, is_prime_pow_pow_iff], { exact hp.1.is_prime_pow }, rw ←finite_dimensional.finrank_eq_card_basis b, exact finite_dimensional.finrank_pos.ne' end /-- A `fintype` can be given a field structure iff its cardinality is a prime power. -/ lemma fintype.nonempty_field_iff {α} [fintype α] : nonempty (field α) ↔ is_prime_pow (‖α‖) := begin refine ⟨λ ⟨h⟩, by exactI fintype.is_prime_pow_card_of_field, _⟩, rintros ⟨p, n, hp, hn, hα⟩, haveI := fact.mk hp.nat_prime, exact ⟨(fintype.equiv_of_card_eq ((galois_field.card p n hn.ne').trans hα)).symm.field⟩, end lemma fintype.not_is_field_of_card_not_prime_pow {α} [fintype α] [ring α] : ¬ is_prime_pow (‖α‖) → ¬ is_field α := mt $ λ h, fintype.nonempty_field_iff.mp ⟨h.to_field⟩ /-- Any infinite type can be endowed a field structure. -/ lemma infinite.nonempty_field {α : Type u} [infinite α] : nonempty (field α) := begin letI K := fraction_ring (mv_polynomial α $ ulift.{u} ℚ), suffices : #α = #K, { obtain ⟨e⟩ := cardinal.eq.1 this, exact ⟨e.field⟩ }, rw ←is_localization.card (mv_polynomial α $ ulift.{u} ℚ)⁰ K le_rfl, apply le_antisymm, { refine ⟨⟨λ a, mv_polynomial.monomial (finsupp.single a 1) (1 : ulift.{u} ℚ), λ x y h, _⟩⟩, simpa [mv_polynomial.monomial_eq_monomial_iff, finsupp.single_eq_single_iff] using h }, { simp } end /-- There is a field structure on type if and only if its cardinality is a prime power. -/ lemma field.nonempty_iff {α : Type u} : nonempty (field α) ↔ is_prime_pow (#α) := begin rw cardinal.is_prime_pow_iff, casesI fintype_or_infinite α with h h, { simpa only [cardinal.mk_fintype, nat.cast_inj, exists_eq_left', (cardinal.nat_lt_aleph_0 _).not_le, false_or] using fintype.nonempty_field_iff }, { simpa only [← cardinal.infinite_iff, h, true_or, iff_true] using infinite.nonempty_field }, end
a0a6b6d04cbb961f33c65b18a7bb04ee3c821bdc
3f7026ea8bef0825ca0339a275c03b911baef64d
/test/sanity_check.lean
271c2ce85ed43b74666c1124caf655cc5f646ac7
[ "Apache-2.0" ]
permissive
rspencer01/mathlib
b1e3afa5c121362ef0881012cc116513ab09f18c
c7d36292c6b9234dc40143c16288932ae38fdc12
refs/heads/master
1,595,010,346,708
1,567,511,503,000
1,567,511,503,000
206,071,681
0
0
Apache-2.0
1,567,513,643,000
1,567,513,643,000
null
UTF-8
Lean
false
false
914
lean
import tactic.sanity_check def foo1 (n m : ℕ) : ℕ := n + 1 def foo2 (n m : ℕ) : m = m := by refl lemma foo3 (n m : ℕ) : ℕ := n - m lemma foo4 (n m : ℕ) : n ≤ n := by refl run_cmd do let t := name × list ℕ, e ← fold_over_with_cond (λ d, d.in_current_file >>= λ b, if b then return (check_unused_arguments d) else return none), guard $ e.length = 3, let e2 : list t := e.map $ λ x, ⟨x.1.to_name, x.2⟩, guard $ (⟨`foo1, [2]⟩ : t) ∈ e2, guard $ (⟨`foo2, [1]⟩ : t) ∈ e2, guard $ (⟨`foo4, [2]⟩ : t) ∈ e2 run_cmd do e ← fold_over_with_cond (λ d, d.in_current_file >>= λ b, if b then incorrect_def_lemma d else return none), guard $ e.length = 2, let e2 : list (name × _) := e.map $ λ x, ⟨x.1.to_name, x.2⟩, guard $ ∃(x ∈ e2), (x : name × _).1 = `foo2, guard $ ∃(x ∈ e2), (x : name × _).1 = `foo3 -- #sanity_check_mathlib
311e1acff9035c8d38cb52dab908ca1eb3b5d915
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/lean/run/generalize.lean
6765a5d24e35afc59579fb98db8bfd8a8dea9ae6
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
638
lean
theorem tst0 (x : Nat) : x + 0 = x + 0 := by { generalize x + 0 = y; exact (Eq.refl y) } theorem tst1 (x : Nat) : x + 0 = x + 0 := by { generalize h : x + 0 = y; exact (Eq.refl y) } theorem tst2 (x y w : Nat) (h : y = w) : (x + x) + w = (x + x) + y := by { generalize h' : x + x = z; subst y; exact Eq.refl $ z + w } theorem tst3 (x y w : Nat) (h : x + x = y) : (x + x) + (x+x) = (x + x) + y := by { generalize h' : x + x = z; subst z; subst y; exact rfl } theorem tst4 (x y w : Nat) (h : y = w) : (x + x) + w = (x + x) + y := by { generalize h' : x + y = z; -- just add equality subst h; exact rfl }
b2e3ddf4ec6a2a64ea3168ec2276b9f35cacd03c
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/data/finset/sort.lean
ff5ff884d8249420259f3366ae9f9c974c078d5b
[ "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
10,667
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.fintype.basic import data.multiset.sort import data.list.nodup_equiv_fin /-! # Construct a sorted list from a finset. -/ namespace finset open multiset nat variables {α β : Type*} /-! ### sort -/ section sort variables (r : α → α → Prop) [decidable_rel r] [is_trans α r] [is_antisymm α r] [is_total α r] /-- `sort s` constructs a sorted list from the unordered set `s`. (Uses merge sort algorithm.) -/ def sort (s : finset α) : list α := sort r s.1 @[simp] theorem sort_sorted (s : finset α) : list.sorted r (sort r s) := sort_sorted _ _ @[simp] theorem sort_eq (s : finset α) : ↑(sort r s) = s.1 := sort_eq _ _ @[simp] theorem sort_nodup (s : finset α) : (sort r s).nodup := (by rw sort_eq; exact s.2 : @multiset.nodup α (sort r s)) @[simp] theorem sort_to_finset [decidable_eq α] (s : finset α) : (sort r s).to_finset = s := list.to_finset_eq (sort_nodup r s) ▸ eq_of_veq (sort_eq r s) @[simp] theorem mem_sort {s : finset α} {a : α} : a ∈ sort r s ↔ a ∈ s := multiset.mem_sort _ @[simp] theorem length_sort {s : finset α} : (sort r s).length = s.card := multiset.length_sort _ @[simp] theorem sort_empty : sort r ∅ = [] := multiset.sort_zero r @[simp] theorem sort_singleton (a : α) : sort r {a} = [a] := multiset.sort_singleton r a lemma sort_perm_to_list (s : finset α) : sort r s ~ s.to_list := by { rw ←multiset.coe_eq_coe, simp only [coe_to_list, sort_eq] } end sort section sort_linear_order variables [linear_order α] theorem sort_sorted_lt (s : finset α) : list.sorted (<) (sort (≤) s) := (sort_sorted _ _).imp₂ (@lt_of_le_of_ne _ _) (sort_nodup _ _) lemma sorted_zero_eq_min'_aux (s : finset α) (h : 0 < (s.sort (≤)).length) (H : s.nonempty) : (s.sort (≤)).nth_le 0 h = s.min' H := begin let l := s.sort (≤), apply le_antisymm, { have : s.min' H ∈ l := (finset.mem_sort (≤)).mpr (s.min'_mem H), obtain ⟨i, i_lt, hi⟩ : ∃ i (hi : i < l.length), l.nth_le i hi = s.min' H := list.mem_iff_nth_le.1 this, rw ← hi, exact (s.sort_sorted (≤)).rel_nth_le_of_le _ _ (nat.zero_le i) }, { have : l.nth_le 0 h ∈ s := (finset.mem_sort (≤)).1 (list.nth_le_mem l 0 h), exact s.min'_le _ this } end lemma sorted_zero_eq_min' {s : finset α} {h : 0 < (s.sort (≤)).length} : (s.sort (≤)).nth_le 0 h = s.min' (card_pos.1 $ by rwa length_sort at h) := sorted_zero_eq_min'_aux _ _ _ lemma min'_eq_sorted_zero {s : finset α} {h : s.nonempty} : s.min' h = (s.sort (≤)).nth_le 0 (by { rw length_sort, exact card_pos.2 h }) := (sorted_zero_eq_min'_aux _ _ _).symm lemma sorted_last_eq_max'_aux (s : finset α) (h : (s.sort (≤)).length - 1 < (s.sort (≤)).length) (H : s.nonempty) : (s.sort (≤)).nth_le ((s.sort (≤)).length - 1) h = s.max' H := begin let l := s.sort (≤), apply le_antisymm, { have : l.nth_le ((s.sort (≤)).length - 1) h ∈ s := (finset.mem_sort (≤)).1 (list.nth_le_mem l _ h), exact s.le_max' _ this }, { have : s.max' H ∈ l := (finset.mem_sort (≤)).mpr (s.max'_mem H), obtain ⟨i, i_lt, hi⟩ : ∃ i (hi : i < l.length), l.nth_le i hi = s.max' H := list.mem_iff_nth_le.1 this, rw ← hi, have : i ≤ l.length - 1 := nat.le_pred_of_lt i_lt, exact (s.sort_sorted (≤)).rel_nth_le_of_le _ _ (nat.le_pred_of_lt i_lt) }, end lemma sorted_last_eq_max' {s : finset α} {h : (s.sort (≤)).length - 1 < (s.sort (≤)).length} : (s.sort (≤)).nth_le ((s.sort (≤)).length - 1) h = s.max' (by { rw length_sort at h, exact card_pos.1 (lt_of_le_of_lt bot_le h) }) := sorted_last_eq_max'_aux _ _ _ lemma max'_eq_sorted_last {s : finset α} {h : s.nonempty} : s.max' h = (s.sort (≤)).nth_le ((s.sort (≤)).length - 1) (by simpa using nat.sub_lt (card_pos.mpr h) zero_lt_one) := (sorted_last_eq_max'_aux _ _ _).symm /-- Given a finset `s` of cardinality `k` in a linear order `α`, the map `order_iso_of_fin s h` is the increasing bijection between `fin k` and `s` as an `order_iso`. Here, `h` is a proof that the cardinality of `s` is `k`. We use this instead of an iso `fin s.card ≃o s` to avoid casting issues in further uses of this function. -/ def order_iso_of_fin (s : finset α) {k : ℕ} (h : s.card = k) : fin k ≃o s := order_iso.trans (fin.cast ((length_sort (≤)).trans h).symm) $ (s.sort_sorted_lt.nth_le_iso _).trans $ order_iso.set_congr _ _ $ set.ext $ λ x, mem_sort _ /-- Given a finset `s` of cardinality `k` in a linear order `α`, the map `order_emb_of_fin s h` is the increasing bijection between `fin k` and `s` as an order embedding into `α`. Here, `h` is a proof that the cardinality of `s` is `k`. We use this instead of an embedding `fin s.card ↪o α` to avoid casting issues in further uses of this function. -/ def order_emb_of_fin (s : finset α) {k : ℕ} (h : s.card = k) : fin k ↪o α := (order_iso_of_fin s h).to_order_embedding.trans (order_embedding.subtype _) @[simp] lemma coe_order_iso_of_fin_apply (s : finset α) {k : ℕ} (h : s.card = k) (i : fin k) : ↑(order_iso_of_fin s h i) = order_emb_of_fin s h i := rfl lemma order_iso_of_fin_symm_apply (s : finset α) {k : ℕ} (h : s.card = k) (x : s) : ↑((s.order_iso_of_fin h).symm x) = (s.sort (≤)).index_of x := rfl lemma order_emb_of_fin_apply (s : finset α) {k : ℕ} (h : s.card = k) (i : fin k) : s.order_emb_of_fin h i = (s.sort (≤)).nth_le i (by { rw [length_sort, h], exact i.2 }) := rfl @[simp] lemma order_emb_of_fin_mem (s : finset α) {k : ℕ} (h : s.card = k) (i : fin k) : s.order_emb_of_fin h i ∈ s := (s.order_iso_of_fin h i).2 @[simp] lemma range_order_emb_of_fin (s : finset α) {k : ℕ} (h : s.card = k) : set.range (s.order_emb_of_fin h) = s := by simp [order_emb_of_fin, set.range_comp coe (s.order_iso_of_fin h)] /-- The bijection `order_emb_of_fin s h` sends `0` to the minimum of `s`. -/ lemma order_emb_of_fin_zero {s : finset α} {k : ℕ} (h : s.card = k) (hz : 0 < k) : order_emb_of_fin s h ⟨0, hz⟩ = s.min' (card_pos.mp (h.symm ▸ hz)) := by simp only [order_emb_of_fin_apply, subtype.coe_mk, sorted_zero_eq_min'] /-- The bijection `order_emb_of_fin s h` sends `k-1` to the maximum of `s`. -/ lemma order_emb_of_fin_last {s : finset α} {k : ℕ} (h : s.card = k) (hz : 0 < k) : order_emb_of_fin s h ⟨k-1, buffer.lt_aux_2 hz⟩ = s.max' (card_pos.mp (h.symm ▸ hz)) := by simp [order_emb_of_fin_apply, max'_eq_sorted_last, h] /-- `order_emb_of_fin {a} h` sends any argument to `a`. -/ @[simp] lemma order_emb_of_fin_singleton (a : α) (i : fin 1) : order_emb_of_fin {a} (card_singleton a) i = a := by rw [subsingleton.elim i ⟨0, zero_lt_one⟩, order_emb_of_fin_zero _ zero_lt_one, min'_singleton] /-- Any increasing map `f` from `fin k` to a finset of cardinality `k` has to coincide with the increasing bijection `order_emb_of_fin s h`. -/ lemma order_emb_of_fin_unique {s : finset α} {k : ℕ} (h : s.card = k) {f : fin k → α} (hfs : ∀ x, f x ∈ s) (hmono : strict_mono f) : f = s.order_emb_of_fin h := begin apply fin.strict_mono_unique hmono (s.order_emb_of_fin h).strict_mono, rw [range_order_emb_of_fin, ← set.image_univ, ← coe_univ, ← coe_image, coe_inj], refine eq_of_subset_of_card_le (λ x hx, _) _, { rcases mem_image.1 hx with ⟨x, hx, rfl⟩, exact hfs x }, { rw [h, card_image_of_injective _ hmono.injective, card_univ, fintype.card_fin] } end /-- An order embedding `f` from `fin k` to a finset of cardinality `k` has to coincide with the increasing bijection `order_emb_of_fin s h`. -/ lemma order_emb_of_fin_unique' {s : finset α} {k : ℕ} (h : s.card = k) {f : fin k ↪o α} (hfs : ∀ x, f x ∈ s) : f = s.order_emb_of_fin h := rel_embedding.ext $ function.funext_iff.1 $ order_emb_of_fin_unique h hfs f.strict_mono /-- Two parametrizations `order_emb_of_fin` of the same set take the same value on `i` and `j` if and only if `i = j`. Since they can be defined on a priori not defeq types `fin k` and `fin l` (although necessarily `k = l`), the conclusion is rather written `(i : ℕ) = (j : ℕ)`. -/ @[simp] lemma order_emb_of_fin_eq_order_emb_of_fin_iff {k l : ℕ} {s : finset α} {i : fin k} {j : fin l} {h : s.card = k} {h' : s.card = l} : s.order_emb_of_fin h i = s.order_emb_of_fin h' j ↔ (i : ℕ) = (j : ℕ) := begin substs k l, exact (s.order_emb_of_fin rfl).eq_iff_eq.trans (fin.ext_iff _ _) end /-- Given a finset `s` of size at least `k` in a linear order `α`, the map `order_emb_of_card_le` is an order embedding from `fin k` to `α` whose image is contained in `s`. Specifically, it maps `fin k` to an initial segment of `s`. -/ def order_emb_of_card_le (s : finset α) {k : ℕ} (h : k ≤ s.card) : fin k ↪o α := (fin.cast_le h).trans (s.order_emb_of_fin rfl) lemma order_emb_of_card_le_mem (s : finset α) {k : ℕ} (h : k ≤ s.card) (a) : order_emb_of_card_le s h a ∈ s := by simp only [order_emb_of_card_le, rel_embedding.coe_trans, finset.order_emb_of_fin_mem] lemma card_le_of_interleaved {s t : finset α} (h : ∀ x y ∈ s, x < y → ∃ z ∈ t, x < z ∧ z < y) : s.card ≤ t.card + 1 := begin have h1 : ∀ i : fin (s.card - 1), ↑i + 1 < (s.sort (≤)).length, { intro i, rw [finset.length_sort, ←lt_tsub_iff_right], exact i.2 }, have h0 : ∀ i : fin (s.card - 1), ↑i < (s.sort (≤)).length := λ i, lt_of_le_of_lt (nat.le_succ i) (h1 i), have p := λ i : fin (s.card - 1), h ((s.sort (≤)).nth_le i (h0 i)) ((finset.mem_sort (≤)).mp (list.nth_le_mem _ _ (h0 i))) ((s.sort (≤)).nth_le (i + 1) (h1 i)) ((finset.mem_sort (≤)).mp (list.nth_le_mem _ _ (h1 i))) (s.sort_sorted_lt.rel_nth_le_of_lt (h0 i) (h1 i) (nat.lt_succ_self i)), let f : fin (s.card - 1) → t := λ i, ⟨classical.some (p i), (exists_prop.mp (classical.some_spec (p i))).1⟩, have hf : ∀ i j : fin (s.card - 1), i < j → f i < f j := λ i j hij, subtype.coe_lt_coe.mp ((exists_prop.mp (classical.some_spec (p i))).2.2.trans (lt_of_le_of_lt ((s.sort_sorted (≤)).rel_nth_le_of_le (h1 i) (h0 j) (nat.succ_le_iff.mpr hij)) (exists_prop.mp (classical.some_spec (p j))).2.1)), have key := fintype.card_le_of_embedding (function.embedding.mk f (λ i j hij, le_antisymm (not_lt.mp (mt (hf j i) (not_lt.mpr (le_of_eq hij)))) (not_lt.mp (mt (hf i j) (not_lt.mpr (ge_of_eq hij)))))), rwa [fintype.card_fin, fintype.card_coe, tsub_le_iff_right] at key, end end sort_linear_order instance [has_repr α] : has_repr (finset α) := ⟨λ s, repr s.1⟩ end finset
ea0009b20e1238d878dd9767d8ce46ac5911a7bc
9dc8cecdf3c4634764a18254e94d43da07142918
/src/algebra/order/invertible.lean
77460f8c5b6afcb74674b0773310725f1d0098e6
[ "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,246
lean
/- Copyright (c) 2021 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import algebra.order.ring import algebra.invertible /-! # Lemmas about `inv_of` in ordered (semi)rings. -/ variables {α : Type*} [linear_ordered_semiring α] {a : α} @[simp] lemma inv_of_pos [invertible a] : 0 < ⅟a ↔ 0 < a := begin have : 0 < a * ⅟a, by simp only [mul_inv_of_self, zero_lt_one], exact ⟨λ h, pos_of_mul_pos_left this h.le, λ h, pos_of_mul_pos_right this h.le⟩ end @[simp] lemma inv_of_nonpos [invertible a] : ⅟a ≤ 0 ↔ a ≤ 0 := by simp only [← not_lt, inv_of_pos] @[simp] lemma inv_of_nonneg [invertible a] : 0 ≤ ⅟a ↔ 0 ≤ a := begin have : 0 < a * ⅟a, by simp only [mul_inv_of_self, zero_lt_one], exact ⟨λ h, (pos_of_mul_pos_left this h).le, λ h, (pos_of_mul_pos_right this h).le⟩ end @[simp] lemma inv_of_lt_zero [invertible a] : ⅟a < 0 ↔ a < 0 := by simp only [← not_le, inv_of_nonneg] @[simp] lemma inv_of_le_one [invertible a] (h : 1 ≤ a) : ⅟a ≤ 1 := by haveI := @linear_order.decidable_le α _; exact mul_inv_of_self a ▸ decidable.le_mul_of_one_le_left (inv_of_nonneg.2 $ zero_le_one.trans h) h
d6b7d3f8660313815155e3b0288c257f6d256584
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/number_theory/padics/padic_integers.lean
da2ebab776c8d1ab3fccbfb589cc32ce518ad4a0
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
21,100
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, Mario Carneiro, Johan Commelin -/ import data.int.modeq import data.zmod.basic import number_theory.padics.padic_numbers import ring_theory.discrete_valuation_ring import topology.metric_space.cau_seq_filter /-! # p-adic integers This file defines the p-adic integers `ℤ_p` as the subtype of `ℚ_p` with norm `≤ 1`. We show that `ℤ_p` * is complete * is nonarchimedean * is a normed ring * is a local ring * is a discrete valuation ring The relation between `ℤ_[p]` and `zmod p` is established in another file. ## Important definitions * `padic_int` : the type of p-adic numbers ## Notation We introduce the notation `ℤ_[p]` for the p-adic integers. ## Implementation notes Much, but not all, of this file assumes that `p` is prime. This assumption is inferred automatically by taking `[fact (nat.prime p)] as a type class argument. Coercions into `ℤ_p` are set up to work with the `norm_cast` tactic. ## References * [F. Q. Gouêva, *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, p-adic integer -/ open padic metric local_ring noncomputable theory open_locale classical /-- The p-adic integers ℤ_p are the p-adic numbers with norm ≤ 1. -/ def padic_int (p : ℕ) [fact p.prime] := {x : ℚ_[p] // ∥x∥ ≤ 1} notation `ℤ_[`p`]` := padic_int p namespace padic_int /-! ### Ring structure and coercion to `ℚ_[p]` -/ variables {p : ℕ} [fact p.prime] instance : has_coe ℤ_[p] ℚ_[p] := ⟨subtype.val⟩ lemma ext {x y : ℤ_[p]} : (x : ℚ_[p]) = y → x = y := subtype.ext_iff_val.2 /-- Addition on ℤ_p is inherited from ℚ_p. -/ instance : has_add ℤ_[p] := ⟨λ ⟨x, hx⟩ ⟨y, hy⟩, ⟨x+y, le_trans (padic_norm_e.nonarchimedean _ _) (max_le_iff.2 ⟨hx,hy⟩)⟩⟩ /-- Multiplication on ℤ_p is inherited from ℚ_p. -/ instance : has_mul ℤ_[p] := ⟨λ ⟨x, hx⟩ ⟨y, hy⟩, ⟨x*y, begin rw padic_norm_e.mul, apply mul_le_one; {assumption <|> apply norm_nonneg} end⟩⟩ /-- Negation on ℤ_p is inherited from ℚ_p. -/ instance : has_neg ℤ_[p] := ⟨λ ⟨x, hx⟩, ⟨-x, by simpa⟩⟩ /-- Subtraction on ℤ_p is inherited from ℚ_p. -/ instance : has_sub ℤ_[p] := ⟨λ ⟨x, hx⟩ ⟨y, hy⟩, ⟨x - y, by { rw sub_eq_add_neg, rw ← norm_neg at hy, exact le_trans (padic_norm_e.nonarchimedean _ _) (max_le_iff.2 ⟨hx, hy⟩) }⟩⟩ /-- Zero on ℤ_p is inherited from ℚ_p. -/ instance : has_zero ℤ_[p] := ⟨⟨0, by norm_num⟩⟩ instance : inhabited ℤ_[p] := ⟨0⟩ /-- One on ℤ_p is inherited from ℚ_p. -/ instance : has_one ℤ_[p] := ⟨⟨1, by norm_num⟩⟩ @[simp] lemma mk_zero {h} : (⟨0, h⟩ : ℤ_[p]) = (0 : ℤ_[p]) := rfl @[simp] lemma val_eq_coe (z : ℤ_[p]) : z.val = z := rfl @[simp, norm_cast] lemma coe_add : ∀ (z1 z2 : ℤ_[p]), ((z1 + z2 : ℤ_[p]) : ℚ_[p]) = z1 + z2 | ⟨_, _⟩ ⟨_, _⟩ := rfl @[simp, norm_cast] lemma coe_mul : ∀ (z1 z2 : ℤ_[p]), ((z1 * z2 : ℤ_[p]) : ℚ_[p]) = z1 * z2 | ⟨_, _⟩ ⟨_, _⟩ := rfl @[simp, norm_cast] lemma coe_neg : ∀ (z1 : ℤ_[p]), ((-z1 : ℤ_[p]) : ℚ_[p]) = -z1 | ⟨_, _⟩ := rfl @[simp, norm_cast] lemma coe_sub : ∀ (z1 z2 : ℤ_[p]), ((z1 - z2 : ℤ_[p]) : ℚ_[p]) = z1 - z2 | ⟨_, _⟩ ⟨_, _⟩ := rfl @[simp, norm_cast] lemma coe_one : ((1 : ℤ_[p]) : ℚ_[p]) = 1 := rfl @[simp, norm_cast] lemma coe_coe : ∀ n : ℕ, ((n : ℤ_[p]) : ℚ_[p]) = n | 0 := rfl | (k+1) := by simp [coe_coe] @[simp, norm_cast] lemma coe_coe_int : ∀ (z : ℤ), ((z : ℤ_[p]) : ℚ_[p]) = z | (int.of_nat n) := by simp | -[1+n] := by simp @[simp, norm_cast] lemma coe_zero : ((0 : ℤ_[p]) : ℚ_[p]) = 0 := rfl instance : ring ℤ_[p] := by refine_struct { add := (+), mul := (*), neg := has_neg.neg, zero := (0 : ℤ_[p]), one := 1, sub := has_sub.sub, npow := @npow_rec _ ⟨1⟩ ⟨(*)⟩, nsmul := @nsmul_rec _ ⟨0⟩ ⟨(+)⟩, gsmul := @gsmul_rec _ ⟨0⟩ ⟨(+)⟩ ⟨has_neg.neg⟩ }; intros; try { refl }; ext; simp; ring /-- The coercion from ℤ[p] to ℚ[p] as a ring homomorphism. -/ def coe.ring_hom : ℤ_[p] →+* ℚ_[p] := { to_fun := (coe : ℤ_[p] → ℚ_[p]), map_zero' := rfl, map_one' := rfl, map_mul' := coe_mul, map_add' := coe_add } @[simp, norm_cast] lemma coe_pow (x : ℤ_[p]) (n : ℕ) : (↑(x^n) : ℚ_[p]) = (↑x : ℚ_[p])^n := coe.ring_hom.map_pow x n @[simp] lemma mk_coe : ∀ (k : ℤ_[p]), (⟨k, k.2⟩ : ℤ_[p]) = k | ⟨_, _⟩ := rfl /-- The inverse of a p-adic integer with norm equal to 1 is also a p-adic integer. Otherwise, the inverse is defined to be 0. -/ def inv : ℤ_[p] → ℤ_[p] | ⟨k, _⟩ := if h : ∥k∥ = 1 then ⟨1/k, by simp [h]⟩ else 0 instance : char_zero ℤ_[p] := { cast_injective := λ m n h, nat.cast_injective $ show (m:ℚ_[p]) = n, by { rw subtype.ext_iff at h, norm_cast at h, exact h } } @[simp, norm_cast] lemma coe_int_eq (z1 z2 : ℤ) : (z1 : ℤ_[p]) = z2 ↔ z1 = z2 := suffices (z1 : ℚ_[p]) = z2 ↔ z1 = z2, from iff.trans (by norm_cast) this, by norm_cast /-- A sequence of integers that is Cauchy with respect to the `p`-adic norm converges to a `p`-adic integer. -/ def of_int_seq (seq : ℕ → ℤ) (h : is_cau_seq (padic_norm p) (λ n, seq n)) : ℤ_[p] := ⟨⟦⟨_, h⟩⟧, show ↑(padic_seq.norm _) ≤ (1 : ℝ), begin rw padic_seq.norm, split_ifs with hne; norm_cast, { exact zero_le_one }, { apply padic_norm.of_int } end ⟩ end padic_int namespace padic_int /-! ### Instances We now show that `ℤ_[p]` is a * complete metric space * normed ring * integral domain -/ variables (p : ℕ) [fact p.prime] instance : metric_space ℤ_[p] := subtype.metric_space instance complete_space : complete_space ℤ_[p] := have is_closed {x : ℚ_[p] | ∥x∥ ≤ 1}, from is_closed_le continuous_norm continuous_const, this.complete_space_coe instance : has_norm ℤ_[p] := ⟨λ z, ∥(z : ℚ_[p])∥⟩ variables {p} protected lemma mul_comm : ∀ z1 z2 : ℤ_[p], z1*z2 = z2*z1 | ⟨q1, h1⟩ ⟨q2, h2⟩ := show (⟨q1*q2, _⟩ : ℤ_[p]) = ⟨q2*q1, _⟩, by simp [_root_.mul_comm] protected lemma zero_ne_one : (0 : ℤ_[p]) ≠ 1 := show (⟨(0 : ℚ_[p]), _⟩ : ℤ_[p]) ≠ ⟨(1 : ℚ_[p]), _⟩, from mt subtype.ext_iff_val.1 zero_ne_one protected lemma eq_zero_or_eq_zero_of_mul_eq_zero : ∀ (a b : ℤ_[p]), a * b = 0 → a = 0 ∨ b = 0 | ⟨a, ha⟩ ⟨b, hb⟩ := λ h : (⟨a * b, _⟩ : ℤ_[p]) = ⟨0, _⟩, have a * b = 0, from subtype.ext_iff_val.1 h, (mul_eq_zero.1 this).elim (λ h1, or.inl (by simp [h1]; refl)) (λ h2, or.inr (by simp [h2]; refl)) lemma norm_def {z : ℤ_[p]} : ∥z∥ = ∥(z : ℚ_[p])∥ := rfl variables (p) instance : normed_comm_ring ℤ_[p] := { dist_eq := λ ⟨_, _⟩ ⟨_, _⟩, rfl, norm_mul := λ ⟨_, _⟩ ⟨_, _⟩, norm_mul_le _ _, mul_comm := padic_int.mul_comm } instance : norm_one_class ℤ_[p] := ⟨norm_def.trans norm_one⟩ instance is_absolute_value : is_absolute_value (λ z : ℤ_[p], ∥z∥) := { abv_nonneg := norm_nonneg, abv_eq_zero := λ ⟨_, _⟩, by simp [norm_eq_zero], abv_add := λ ⟨_,_⟩ ⟨_, _⟩, norm_add_le _ _, abv_mul := λ _ _, by simp only [norm_def, padic_norm_e.mul, padic_int.coe_mul]} variables {p} instance : integral_domain ℤ_[p] := { eq_zero_or_eq_zero_of_mul_eq_zero := λ x y, padic_int.eq_zero_or_eq_zero_of_mul_eq_zero x y, exists_pair_ne := ⟨0, 1, padic_int.zero_ne_one⟩, .. padic_int.normed_comm_ring p } end padic_int namespace padic_int /-! ### Norm -/ variables {p : ℕ} [fact p.prime] lemma norm_le_one : ∀ z : ℤ_[p], ∥z∥ ≤ 1 | ⟨_, h⟩ := h @[simp] lemma norm_mul (z1 z2 : ℤ_[p]) : ∥z1 * z2∥ = ∥z1∥ * ∥z2∥ := by simp [norm_def] @[simp] lemma norm_pow (z : ℤ_[p]) : ∀ n : ℕ, ∥z^n∥ = ∥z∥^n | 0 := by simp | (k+1) := by { rw [pow_succ, pow_succ, norm_mul], congr, apply norm_pow } theorem nonarchimedean : ∀ (q r : ℤ_[p]), ∥q + r∥ ≤ max (∥q∥) (∥r∥) | ⟨_, _⟩ ⟨_, _⟩ := padic_norm_e.nonarchimedean _ _ theorem norm_add_eq_max_of_ne : ∀ {q r : ℤ_[p]}, ∥q∥ ≠ ∥r∥ → ∥q+r∥ = max (∥q∥) (∥r∥) | ⟨_, _⟩ ⟨_, _⟩ := padic_norm_e.add_eq_max_of_ne lemma norm_eq_of_norm_add_lt_right {z1 z2 : ℤ_[p]} (h : ∥z1 + z2∥ < ∥z2∥) : ∥z1∥ = ∥z2∥ := by_contradiction $ λ hne, not_lt_of_ge (by rw norm_add_eq_max_of_ne hne; apply le_max_right) h lemma norm_eq_of_norm_add_lt_left {z1 z2 : ℤ_[p]} (h : ∥z1 + z2∥ < ∥z1∥) : ∥z1∥ = ∥z2∥ := by_contradiction $ λ hne, not_lt_of_ge (by rw norm_add_eq_max_of_ne hne; apply le_max_left) h @[simp] lemma padic_norm_e_of_padic_int (z : ℤ_[p]) : ∥(↑z : ℚ_[p])∥ = ∥z∥ := by simp [norm_def] lemma norm_int_cast_eq_padic_norm (z : ℤ) : ∥(z : ℤ_[p])∥ = ∥(z : ℚ_[p])∥ := by simp [norm_def] @[simp] lemma norm_eq_padic_norm {q : ℚ_[p]} (hq : ∥q∥ ≤ 1) : @norm ℤ_[p] _ ⟨q, hq⟩ = ∥q∥ := rfl @[simp] lemma norm_p : ∥(p : ℤ_[p])∥ = p⁻¹ := show ∥((p : ℤ_[p]) : ℚ_[p])∥ = p⁻¹, by exact_mod_cast padic_norm_e.norm_p @[simp] lemma norm_p_pow (n : ℕ) : ∥(p : ℤ_[p])^n∥ = p^(-n:ℤ) := show ∥((p^n : ℤ_[p]) : ℚ_[p])∥ = p^(-n:ℤ), by { convert padic_norm_e.norm_p_pow n, simp, } private def cau_seq_to_rat_cau_seq (f : cau_seq ℤ_[p] norm) : cau_seq ℚ_[p] (λ a, ∥a∥) := ⟨ λ n, f n, λ _ hε, by simpa [norm, norm_def] using f.cauchy hε ⟩ variables (p) instance complete : cau_seq.is_complete ℤ_[p] norm := ⟨ λ f, have hqn : ∥cau_seq.lim (cau_seq_to_rat_cau_seq f)∥ ≤ 1, from padic_norm_e_lim_le zero_lt_one (λ _, norm_le_one _), ⟨ ⟨_, hqn⟩, λ ε, by simpa [norm, norm_def] using cau_seq.equiv_lim (cau_seq_to_rat_cau_seq f) ε⟩⟩ end padic_int namespace padic_int variables (p : ℕ) [hp_prime : fact p.prime] include hp_prime lemma exists_pow_neg_lt {ε : ℝ} (hε : 0 < ε) : ∃ (k : ℕ), ↑p ^ -((k : ℕ) : ℤ) < ε := begin obtain ⟨k, hk⟩ := exists_nat_gt ε⁻¹, use k, rw ← inv_lt_inv hε (_root_.fpow_pos_of_pos _ _), { rw [fpow_neg, inv_inv', gpow_coe_nat], apply lt_of_lt_of_le hk, norm_cast, apply le_of_lt, convert nat.lt_pow_self _ _ using 1, exact hp_prime.1.one_lt }, { exact_mod_cast hp_prime.1.pos } end lemma exists_pow_neg_lt_rat {ε : ℚ} (hε : 0 < ε) : ∃ (k : ℕ), ↑p ^ -((k : ℕ) : ℤ) < ε := begin obtain ⟨k, hk⟩ := @exists_pow_neg_lt p _ ε (by exact_mod_cast hε), use k, rw (show (p : ℝ) = (p : ℚ), by simp) at hk, exact_mod_cast hk end variable {p} lemma norm_int_lt_one_iff_dvd (k : ℤ) : ∥(k : ℤ_[p])∥ < 1 ↔ ↑p ∣ k := suffices ∥(k : ℚ_[p])∥ < 1 ↔ ↑p ∣ k, by rwa norm_int_cast_eq_padic_norm, padic_norm_e.norm_int_lt_one_iff_dvd k lemma norm_int_le_pow_iff_dvd {k : ℤ} {n : ℕ} : ∥(k : ℤ_[p])∥ ≤ ((↑p)^(-n : ℤ)) ↔ ↑p^n ∣ k := suffices ∥(k : ℚ_[p])∥ ≤ ((↑p)^(-n : ℤ)) ↔ ↑(p^n) ∣ k, by simpa [norm_int_cast_eq_padic_norm], padic_norm_e.norm_int_le_pow_iff_dvd _ _ /-! ### Valuation on `ℤ_[p]` -/ /-- `padic_int.valuation` lifts the p-adic valuation on `ℚ` to `ℤ_[p]`. -/ def valuation (x : ℤ_[p]) := padic.valuation (x : ℚ_[p]) lemma norm_eq_pow_val {x : ℤ_[p]} (hx : x ≠ 0) : ∥x∥ = p^(-x.valuation) := begin convert padic.norm_eq_pow_val _, contrapose! hx, exact subtype.val_injective hx end @[simp] lemma valuation_zero : valuation (0 : ℤ_[p]) = 0 := padic.valuation_zero @[simp] lemma valuation_one : valuation (1 : ℤ_[p]) = 0 := padic.valuation_one @[simp] lemma valuation_p : valuation (p : ℤ_[p]) = 1 := by simp [valuation, -cast_eq_of_rat_of_nat] lemma valuation_nonneg (x : ℤ_[p]) : 0 ≤ x.valuation := begin by_cases hx : x = 0, { simp [hx] }, have h : (1 : ℝ) < p := by exact_mod_cast hp_prime.1.one_lt, rw [← neg_nonpos, ← (fpow_strict_mono h).le_iff_le], show (p : ℝ) ^ -valuation x ≤ p ^ 0, rw [← norm_eq_pow_val hx], simpa using x.property, end @[simp] lemma valuation_p_pow_mul (n : ℕ) (c : ℤ_[p]) (hc : c ≠ 0) : (↑p ^ n * c).valuation = n + c.valuation := begin have : ∥↑p ^ n * c∥ = ∥(p ^ n : ℤ_[p])∥ * ∥c∥, { exact norm_mul _ _ }, have aux : ↑p ^ n * c ≠ 0, { contrapose! hc, rw mul_eq_zero at hc, cases hc, { refine (hp_prime.1.ne_zero _).elim, exact_mod_cast (pow_eq_zero hc) }, { exact hc } }, rwa [norm_eq_pow_val aux, norm_p_pow, norm_eq_pow_val hc, ← fpow_add, ← neg_add, fpow_inj, neg_inj] at this, { exact_mod_cast hp_prime.1.pos }, { exact_mod_cast hp_prime.1.ne_one }, { exact_mod_cast hp_prime.1.ne_zero }, end section units /-! ### Units of `ℤ_[p]` -/ local attribute [reducible] padic_int lemma mul_inv : ∀ {z : ℤ_[p]}, ∥z∥ = 1 → z * z.inv = 1 | ⟨k, _⟩ h := begin have hk : k ≠ 0, from λ h', @zero_ne_one ℚ_[p] _ _ (by simpa [h'] using h), unfold padic_int.inv, split_ifs, { change (⟨k * (1/k), _⟩ : ℤ_[p]) = 1, simp [hk], refl }, { apply subtype.ext_iff_val.2, simp [mul_inv_cancel hk] } end lemma inv_mul {z : ℤ_[p]} (hz : ∥z∥ = 1) : z.inv * z = 1 := by rw [mul_comm, mul_inv hz] lemma is_unit_iff {z : ℤ_[p]} : is_unit z ↔ ∥z∥ = 1 := ⟨λ h, begin rcases is_unit_iff_dvd_one.1 h with ⟨w, eq⟩, refine le_antisymm (norm_le_one _) _, have := mul_le_mul_of_nonneg_left (norm_le_one w) (norm_nonneg z), rwa [mul_one, ← norm_mul, ← eq, norm_one] at this end, λ h, ⟨⟨z, z.inv, mul_inv h, inv_mul h⟩, rfl⟩⟩ lemma norm_lt_one_add {z1 z2 : ℤ_[p]} (hz1 : ∥z1∥ < 1) (hz2 : ∥z2∥ < 1) : ∥z1 + z2∥ < 1 := lt_of_le_of_lt (nonarchimedean _ _) (max_lt hz1 hz2) lemma norm_lt_one_mul {z1 z2 : ℤ_[p]} (hz2 : ∥z2∥ < 1) : ∥z1 * z2∥ < 1 := calc ∥z1 * z2∥ = ∥z1∥ * ∥z2∥ : by simp ... < 1 : mul_lt_one_of_nonneg_of_lt_one_right (norm_le_one _) (norm_nonneg _) hz2 @[simp] lemma mem_nonunits {z : ℤ_[p]} : z ∈ nonunits ℤ_[p] ↔ ∥z∥ < 1 := by rw lt_iff_le_and_ne; simp [norm_le_one z, nonunits, is_unit_iff] /-- A `p`-adic number `u` with `∥u∥ = 1` is a unit of `ℤ_[p]`. -/ def mk_units {u : ℚ_[p]} (h : ∥u∥ = 1) : units ℤ_[p] := let z : ℤ_[p] := ⟨u, le_of_eq h⟩ in ⟨z, z.inv, mul_inv h, inv_mul h⟩ @[simp] lemma mk_units_eq {u : ℚ_[p]} (h : ∥u∥ = 1) : ((mk_units h : ℤ_[p]) : ℚ_[p]) = u := rfl @[simp] lemma norm_units (u : units ℤ_[p]) : ∥(u : ℤ_[p])∥ = 1 := is_unit_iff.mp $ by simp /-- `unit_coeff hx` is the unit `u` in the unique representation `x = u * p ^ n`. See `unit_coeff_spec`. -/ def unit_coeff {x : ℤ_[p]} (hx : x ≠ 0) : units ℤ_[p] := let u : ℚ_[p] := x*p^(-x.valuation) in have hu : ∥u∥ = 1, by simp [hx, nat.fpow_ne_zero_of_pos (by exact_mod_cast hp_prime.1.pos) x.valuation, norm_eq_pow_val, fpow_neg, inv_mul_cancel, -cast_eq_of_rat_of_nat], mk_units hu @[simp] lemma unit_coeff_coe {x : ℤ_[p]} (hx : x ≠ 0) : (unit_coeff hx : ℚ_[p]) = x * p ^ (-x.valuation) := rfl lemma unit_coeff_spec {x : ℤ_[p]} (hx : x ≠ 0) : x = (unit_coeff hx : ℤ_[p]) * p ^ int.nat_abs (valuation x) := begin apply subtype.coe_injective, push_cast, have repr : (x : ℚ_[p]) = (unit_coeff hx) * p ^ x.valuation, { rw [unit_coeff_coe, mul_assoc, ← fpow_add], { simp }, { exact_mod_cast hp_prime.1.ne_zero } }, convert repr using 2, rw [← gpow_coe_nat, int.nat_abs_of_nonneg (valuation_nonneg x)], end end units section norm_le_iff /-! ### Various characterizations of open unit balls -/ lemma norm_le_pow_iff_le_valuation (x : ℤ_[p]) (hx : x ≠ 0) (n : ℕ) : ∥x∥ ≤ p ^ (-n : ℤ) ↔ ↑n ≤ x.valuation := begin rw norm_eq_pow_val hx, lift x.valuation to ℕ using x.valuation_nonneg with k hk, simp only [int.coe_nat_le, fpow_neg, gpow_coe_nat], have aux : ∀ n : ℕ, 0 < (p ^ n : ℝ), { apply pow_pos, exact_mod_cast hp_prime.1.pos }, rw [inv_le_inv (aux _) (aux _)], have : p ^ n ≤ p ^ k ↔ n ≤ k := (strict_mono_pow hp_prime.1.one_lt).le_iff_le, rw [← this], norm_cast, end lemma mem_span_pow_iff_le_valuation (x : ℤ_[p]) (hx : x ≠ 0) (n : ℕ) : x ∈ (ideal.span {p ^ n} : ideal ℤ_[p]) ↔ ↑n ≤ x.valuation := begin rw [ideal.mem_span_singleton], split, { rintro ⟨c, rfl⟩, suffices : c ≠ 0, { rw [valuation_p_pow_mul _ _ this, le_add_iff_nonneg_right], apply valuation_nonneg, }, contrapose! hx, rw [hx, mul_zero], }, { rw [unit_coeff_spec hx] { occs := occurrences.pos [2] }, lift x.valuation to ℕ using x.valuation_nonneg with k hk, simp only [int.nat_abs_of_nat, units.is_unit, is_unit.dvd_mul_left, int.coe_nat_le], intro H, obtain ⟨k, rfl⟩ := nat.exists_eq_add_of_le H, simp only [pow_add, dvd_mul_right], } end lemma norm_le_pow_iff_mem_span_pow (x : ℤ_[p]) (n : ℕ) : ∥x∥ ≤ p ^ (-n : ℤ) ↔ x ∈ (ideal.span {p ^ n} : ideal ℤ_[p]) := begin by_cases hx : x = 0, { subst hx, simp only [norm_zero, fpow_neg, gpow_coe_nat, inv_nonneg, iff_true, submodule.zero_mem], exact_mod_cast nat.zero_le _ }, rw [norm_le_pow_iff_le_valuation x hx, mem_span_pow_iff_le_valuation x hx], end 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.fpow_pos_of_pos, exact hp_prime.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_prime.1.one_lt }, have H := fpow_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_lt_one_iff_dvd (x : ℤ_[p]) : ∥x∥ < 1 ↔ ↑p ∣ x := begin have := norm_le_pow_iff_mem_span_pow x 1, rw [ideal.mem_span_singleton, pow_one] at this, rw [← this, norm_le_pow_iff_norm_lt_pow_add_one], simp only [gpow_zero, int.coe_nat_zero, int.coe_nat_succ, add_left_neg, zero_add], end @[simp] lemma pow_p_dvd_int_iff (n : ℕ) (a : ℤ) : (p ^ n : ℤ_[p]) ∣ a ↔ ↑p ^ n ∣ a := by rw [← norm_int_le_pow_iff_dvd, norm_le_pow_iff_mem_span_pow, ideal.mem_span_singleton] end norm_le_iff section dvr /-! ### Discrete valuation ring -/ instance : local_ring ℤ_[p] := local_of_nonunits_ideal zero_ne_one $ λ x y, by simp; exact norm_lt_one_add lemma p_nonnunit : (p : ℤ_[p]) ∈ nonunits ℤ_[p] := have (p : ℝ)⁻¹ < 1, from inv_lt_one $ by exact_mod_cast hp_prime.1.one_lt, by simp [this] lemma maximal_ideal_eq_span_p : maximal_ideal ℤ_[p] = ideal.span {p} := begin apply le_antisymm, { intros x hx, rw ideal.mem_span_singleton, simp only [local_ring.mem_maximal_ideal, mem_nonunits] at hx, rwa ← norm_lt_one_iff_dvd, }, { rw [ideal.span_le, set.singleton_subset_iff], exact p_nonnunit } end lemma prime_p : prime (p : ℤ_[p]) := begin rw [← ideal.span_singleton_prime, ← maximal_ideal_eq_span_p], { apply_instance }, { exact_mod_cast hp_prime.1.ne_zero } end lemma irreducible_p : irreducible (p : ℤ_[p]) := prime.irreducible prime_p instance : discrete_valuation_ring ℤ_[p] := discrete_valuation_ring.of_has_unit_mul_pow_irreducible_factorization ⟨p, irreducible_p, λ x hx, ⟨x.valuation.nat_abs, unit_coeff hx, by rw [mul_comm, ← unit_coeff_spec hx]⟩⟩ lemma ideal_eq_span_pow_p {s : ideal ℤ_[p]} (hs : s ≠ ⊥) : ∃ n : ℕ, s = ideal.span {p ^ n} := discrete_valuation_ring.ideal_eq_span_pow_irreducible hs irreducible_p open cau_seq instance : is_adic_complete (maximal_ideal ℤ_[p]) ℤ_[p] := { prec' := λ x hx, begin simp only [← ideal.one_eq_top, smul_eq_mul, mul_one, smodeq.sub_mem, maximal_ideal_eq_span_p, ideal.span_singleton_pow, ← norm_le_pow_iff_mem_span_pow] at hx ⊢, let x' : cau_seq ℤ_[p] norm := ⟨x, _⟩, swap, { intros ε hε, obtain ⟨m, hm⟩ := exists_pow_neg_lt p hε, refine ⟨m, λ n hn, lt_of_le_of_lt _ hm⟩, rw [← neg_sub, norm_neg], exact hx hn }, { refine ⟨x'.lim, λ n, _⟩, have : (0:ℝ) < p ^ (-n : ℤ), { apply fpow_pos_of_pos, exact_mod_cast hp_prime.1.pos }, obtain ⟨i, hi⟩ := equiv_def₃ (equiv_lim x') this, by_cases hin : i ≤ n, { exact (hi i le_rfl n hin).le, }, { push_neg at hin, specialize hi i le_rfl i le_rfl, specialize hx hin.le, have := nonarchimedean (x n - x i) (x i - x'.lim), rw [sub_add_sub_cancel] at this, refine this.trans (max_le_iff.mpr ⟨hx, hi.le⟩), } }, end } end dvr end padic_int
65af6d561fa080e3f90e4777e47f2d5b5276787d
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/W_auto.lean
236d492eed2c830b43d38baaff7fb572b449965d
[]
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
3,421
lean
/- Copyright (c) 2019 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.equiv.list import Mathlib.PostPort universes u_1 u_2 l namespace Mathlib /-! # W types Given `α : Type` and `β : α → Type`, the W type determined by this data, `W_type β`, is the inductively defined type of trees where the nodes are labeled by elements of `α` and the children of a node labeled `a` are indexed by elements of `β a`. This file is currently a stub, awaiting a full development of the theory. Currently, the main result is that if `α` is an encodable fintype and `β a` is encodable for every `a : α`, then `W_type β` is encodable. This can be used to show the encodability of other inductive types, such as those that are commonly used to formalize syntax, e.g. terms and expressions in a given language. The strategy is illustrated in the example found in the file `prop_encodable` in the `archive/examples` folder of mathlib. ## Implementation details While the name `W_type` is somewhat verbose, it is preferable to putting a single character identifier `W` in the root namespace. -/ /-- Given `β : α → Type*`, `W_type β` is the type of finitely branching trees where nodes are labeled by elements of `α` and the children of a node labeled `a` are indexed by elements of `β a`. -/ inductive W_type {α : Type u_1} (β : α → Type u_2) where | mk : (a : α) → (β a → W_type β) → W_type β protected instance W_type.inhabited : Inhabited (W_type fun (_x : Unit) => empty) := { default := W_type.mk Unit.unit empty.elim } namespace W_type /-- The depth of a finitely branching tree. -/ def depth {α : Type u_1} {β : α → Type u_2} [(a : α) → fintype (β a)] : W_type β → ℕ := sorry theorem depth_pos {α : Type u_1} {β : α → Type u_2} [(a : α) → fintype (β a)] (t : W_type β) : 0 < depth t := W_type.cases_on t fun (t_a : α) (t_f : β t_a → W_type β) => nat.succ_pos (finset.sup finset.univ fun (n : β t_a) => depth (t_f n)) theorem depth_lt_depth_mk {α : Type u_1} {β : α → Type u_2} [(a : α) → fintype (β a)] (a : α) (f : β a → W_type β) (i : β a) : depth (f i) < depth (mk a f) := nat.lt_succ_of_le (finset.le_sup (finset.mem_univ i)) end W_type /- Show that W types are encodable when `α` is an encodable fintype and for every `a : α`, `β a` is encodable. We define an auxiliary type `W_type' β n` of trees of depth at most `n`, and then we show by induction on `n` that these are all encodable. These auxiliary constructions are not interesting in and of themselves, so we mark them as `private`. -/ namespace encodable /-- `W_type` is encodable when `α` is an encodable fintype and for every `a : α`, `β a` is encodable. -/ protected instance W_type.encodable {α : Type u_1} {β : α → Type u_2} [(a : α) → fintype (β a)] [(a : α) → encodable (β a)] [encodable α] : encodable (W_type β) := let f : W_type β → sigma fun (n : ℕ) => W_type' β n := fun (t : W_type β) => sigma.mk (W_type.depth t) { val := t, property := sorry }; let finv : (sigma fun (n : ℕ) => W_type' β n) → W_type β := fun (p : sigma fun (n : ℕ) => W_type' β n) => subtype.val (sigma.snd p); of_left_inverse f finv sorry end Mathlib
eb8716a33081b876db0ecf3043d54d9f45b1393c
592ee40978ac7604005a4e0d35bbc4b467389241
/Library/generated/mathscheme-lean/RightCancellative.lean
336f9dfa6a969281e3daee065d36c1e5a18a15f6
[]
no_license
ysharoda/Deriving-Definitions
3e149e6641fae440badd35ac110a0bd705a49ad2
dfecb27572022de3d4aa702cae8db19957523a59
refs/heads/master
1,679,127,857,700
1,615,939,007,000
1,615,939,007,000
229,785,731
4
0
null
null
null
null
UTF-8
Lean
false
false
8,920
lean
import init.data.nat.basic import init.data.fin.basic import data.vector import .Prelude open Staged open nat open fin open vector section RightCancellative structure RightCancellative (A : Type) : Type := (op : (A → (A → A))) (rinv : (A → (A → A))) (rightCancel : (∀ {x y : A} , (op (rinv y x) x) = y)) open RightCancellative structure Sig (AS : Type) : Type := (opS : (AS → (AS → AS))) (rinvS : (AS → (AS → AS))) structure Product (A : Type) : Type := (opP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (rinvP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (rightCancelP : (∀ {xP yP : (Prod A A)} , (opP (rinvP yP xP) xP) = yP)) structure Hom {A1 : Type} {A2 : Type} (Ri1 : (RightCancellative A1)) (Ri2 : (RightCancellative A2)) : Type := (hom : (A1 → A2)) (pres_op : (∀ {x1 x2 : A1} , (hom ((op Ri1) x1 x2)) = ((op Ri2) (hom x1) (hom x2)))) (pres_rinv : (∀ {x1 x2 : A1} , (hom ((rinv Ri1) x1 x2)) = ((rinv Ri2) (hom x1) (hom x2)))) structure RelInterp {A1 : Type} {A2 : Type} (Ri1 : (RightCancellative A1)) (Ri2 : (RightCancellative A2)) : Type 1 := (interp : (A1 → (A2 → Type))) (interp_op : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((op Ri1) x1 x2) ((op Ri2) y1 y2)))))) (interp_rinv : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((rinv Ri1) x1 x2) ((rinv Ri2) y1 y2)))))) inductive RightCancellativeTerm : Type | opL : (RightCancellativeTerm → (RightCancellativeTerm → RightCancellativeTerm)) | rinvL : (RightCancellativeTerm → (RightCancellativeTerm → RightCancellativeTerm)) open RightCancellativeTerm inductive ClRightCancellativeTerm (A : Type) : Type | sing : (A → ClRightCancellativeTerm) | opCl : (ClRightCancellativeTerm → (ClRightCancellativeTerm → ClRightCancellativeTerm)) | rinvCl : (ClRightCancellativeTerm → (ClRightCancellativeTerm → ClRightCancellativeTerm)) open ClRightCancellativeTerm inductive OpRightCancellativeTerm (n : ℕ) : Type | v : ((fin n) → OpRightCancellativeTerm) | opOL : (OpRightCancellativeTerm → (OpRightCancellativeTerm → OpRightCancellativeTerm)) | rinvOL : (OpRightCancellativeTerm → (OpRightCancellativeTerm → OpRightCancellativeTerm)) open OpRightCancellativeTerm inductive OpRightCancellativeTerm2 (n : ℕ) (A : Type) : Type | v2 : ((fin n) → OpRightCancellativeTerm2) | sing2 : (A → OpRightCancellativeTerm2) | opOL2 : (OpRightCancellativeTerm2 → (OpRightCancellativeTerm2 → OpRightCancellativeTerm2)) | rinvOL2 : (OpRightCancellativeTerm2 → (OpRightCancellativeTerm2 → OpRightCancellativeTerm2)) open OpRightCancellativeTerm2 def simplifyCl {A : Type} : ((ClRightCancellativeTerm A) → (ClRightCancellativeTerm A)) | (opCl x1 x2) := (opCl (simplifyCl x1) (simplifyCl x2)) | (rinvCl x1 x2) := (rinvCl (simplifyCl x1) (simplifyCl x2)) | (sing x1) := (sing x1) def simplifyOpB {n : ℕ} : ((OpRightCancellativeTerm n) → (OpRightCancellativeTerm n)) | (opOL x1 x2) := (opOL (simplifyOpB x1) (simplifyOpB x2)) | (rinvOL x1 x2) := (rinvOL (simplifyOpB x1) (simplifyOpB x2)) | (v x1) := (v x1) def simplifyOp {n : ℕ} {A : Type} : ((OpRightCancellativeTerm2 n A) → (OpRightCancellativeTerm2 n A)) | (opOL2 x1 x2) := (opOL2 (simplifyOp x1) (simplifyOp x2)) | (rinvOL2 x1 x2) := (rinvOL2 (simplifyOp x1) (simplifyOp x2)) | (v2 x1) := (v2 x1) | (sing2 x1) := (sing2 x1) def evalB {A : Type} : ((RightCancellative A) → (RightCancellativeTerm → A)) | Ri (opL x1 x2) := ((op Ri) (evalB Ri x1) (evalB Ri x2)) | Ri (rinvL x1 x2) := ((rinv Ri) (evalB Ri x1) (evalB Ri x2)) def evalCl {A : Type} : ((RightCancellative A) → ((ClRightCancellativeTerm A) → A)) | Ri (sing x1) := x1 | Ri (opCl x1 x2) := ((op Ri) (evalCl Ri x1) (evalCl Ri x2)) | Ri (rinvCl x1 x2) := ((rinv Ri) (evalCl Ri x1) (evalCl Ri x2)) def evalOpB {A : Type} {n : ℕ} : ((RightCancellative A) → ((vector A n) → ((OpRightCancellativeTerm n) → A))) | Ri vars (v x1) := (nth vars x1) | Ri vars (opOL x1 x2) := ((op Ri) (evalOpB Ri vars x1) (evalOpB Ri vars x2)) | Ri vars (rinvOL x1 x2) := ((rinv Ri) (evalOpB Ri vars x1) (evalOpB Ri vars x2)) def evalOp {A : Type} {n : ℕ} : ((RightCancellative A) → ((vector A n) → ((OpRightCancellativeTerm2 n A) → A))) | Ri vars (v2 x1) := (nth vars x1) | Ri vars (sing2 x1) := x1 | Ri vars (opOL2 x1 x2) := ((op Ri) (evalOp Ri vars x1) (evalOp Ri vars x2)) | Ri vars (rinvOL2 x1 x2) := ((rinv Ri) (evalOp Ri vars x1) (evalOp Ri vars x2)) def inductionB {P : (RightCancellativeTerm → Type)} : ((∀ (x1 x2 : RightCancellativeTerm) , ((P x1) → ((P x2) → (P (opL x1 x2))))) → ((∀ (x1 x2 : RightCancellativeTerm) , ((P x1) → ((P x2) → (P (rinvL x1 x2))))) → (∀ (x : RightCancellativeTerm) , (P x)))) | popl prinvl (opL x1 x2) := (popl _ _ (inductionB popl prinvl x1) (inductionB popl prinvl x2)) | popl prinvl (rinvL x1 x2) := (prinvl _ _ (inductionB popl prinvl x1) (inductionB popl prinvl x2)) def inductionCl {A : Type} {P : ((ClRightCancellativeTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((∀ (x1 x2 : (ClRightCancellativeTerm A)) , ((P x1) → ((P x2) → (P (opCl x1 x2))))) → ((∀ (x1 x2 : (ClRightCancellativeTerm A)) , ((P x1) → ((P x2) → (P (rinvCl x1 x2))))) → (∀ (x : (ClRightCancellativeTerm A)) , (P x))))) | psing popcl prinvcl (sing x1) := (psing x1) | psing popcl prinvcl (opCl x1 x2) := (popcl _ _ (inductionCl psing popcl prinvcl x1) (inductionCl psing popcl prinvcl x2)) | psing popcl prinvcl (rinvCl x1 x2) := (prinvcl _ _ (inductionCl psing popcl prinvcl x1) (inductionCl psing popcl prinvcl x2)) def inductionOpB {n : ℕ} {P : ((OpRightCancellativeTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((∀ (x1 x2 : (OpRightCancellativeTerm n)) , ((P x1) → ((P x2) → (P (opOL x1 x2))))) → ((∀ (x1 x2 : (OpRightCancellativeTerm n)) , ((P x1) → ((P x2) → (P (rinvOL x1 x2))))) → (∀ (x : (OpRightCancellativeTerm n)) , (P x))))) | pv popol prinvol (v x1) := (pv x1) | pv popol prinvol (opOL x1 x2) := (popol _ _ (inductionOpB pv popol prinvol x1) (inductionOpB pv popol prinvol x2)) | pv popol prinvol (rinvOL x1 x2) := (prinvol _ _ (inductionOpB pv popol prinvol x1) (inductionOpB pv popol prinvol x2)) def inductionOp {n : ℕ} {A : Type} {P : ((OpRightCancellativeTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((∀ (x1 x2 : (OpRightCancellativeTerm2 n A)) , ((P x1) → ((P x2) → (P (opOL2 x1 x2))))) → ((∀ (x1 x2 : (OpRightCancellativeTerm2 n A)) , ((P x1) → ((P x2) → (P (rinvOL2 x1 x2))))) → (∀ (x : (OpRightCancellativeTerm2 n A)) , (P x)))))) | pv2 psing2 popol2 prinvol2 (v2 x1) := (pv2 x1) | pv2 psing2 popol2 prinvol2 (sing2 x1) := (psing2 x1) | pv2 psing2 popol2 prinvol2 (opOL2 x1 x2) := (popol2 _ _ (inductionOp pv2 psing2 popol2 prinvol2 x1) (inductionOp pv2 psing2 popol2 prinvol2 x2)) | pv2 psing2 popol2 prinvol2 (rinvOL2 x1 x2) := (prinvol2 _ _ (inductionOp pv2 psing2 popol2 prinvol2 x1) (inductionOp pv2 psing2 popol2 prinvol2 x2)) def stageB : (RightCancellativeTerm → (Staged RightCancellativeTerm)) | (opL x1 x2) := (stage2 opL (codeLift2 opL) (stageB x1) (stageB x2)) | (rinvL x1 x2) := (stage2 rinvL (codeLift2 rinvL) (stageB x1) (stageB x2)) def stageCl {A : Type} : ((ClRightCancellativeTerm A) → (Staged (ClRightCancellativeTerm A))) | (sing x1) := (Now (sing x1)) | (opCl x1 x2) := (stage2 opCl (codeLift2 opCl) (stageCl x1) (stageCl x2)) | (rinvCl x1 x2) := (stage2 rinvCl (codeLift2 rinvCl) (stageCl x1) (stageCl x2)) def stageOpB {n : ℕ} : ((OpRightCancellativeTerm n) → (Staged (OpRightCancellativeTerm n))) | (v x1) := (const (code (v x1))) | (opOL x1 x2) := (stage2 opOL (codeLift2 opOL) (stageOpB x1) (stageOpB x2)) | (rinvOL x1 x2) := (stage2 rinvOL (codeLift2 rinvOL) (stageOpB x1) (stageOpB x2)) def stageOp {n : ℕ} {A : Type} : ((OpRightCancellativeTerm2 n A) → (Staged (OpRightCancellativeTerm2 n A))) | (sing2 x1) := (Now (sing2 x1)) | (v2 x1) := (const (code (v2 x1))) | (opOL2 x1 x2) := (stage2 opOL2 (codeLift2 opOL2) (stageOp x1) (stageOp x2)) | (rinvOL2 x1 x2) := (stage2 rinvOL2 (codeLift2 rinvOL2) (stageOp x1) (stageOp x2)) structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type := (opT : ((Repr A) → ((Repr A) → (Repr A)))) (rinvT : ((Repr A) → ((Repr A) → (Repr A)))) end RightCancellative
8b5038cb3adff20e7c9383748433e5dfe9a65c78
159fed64bfae88f3b6a6166836d6278f953bcbf9
/Structure/Generic/Axioms/AbstractTrivialTypes.lean
a6497a94342958c0701ba8f73690d894c6131341
[ "MIT" ]
permissive
SReichelt/lean4-experiments
3e56830c8b2fbe3814eda071c48e3c8810d254a8
ff55357a01a34a91bf670d712637480089085ee4
refs/heads/main
1,683,977,454,907
1,622,991,121,000
1,622,991,121,000
340,765,677
2
0
null
null
null
null
UTF-8
Lean
false
false
1,844
lean
import Structure.Generic.Axioms.Universes import Structure.Generic.Axioms.AbstractFunctors import mathlib4_experiments.Data.Equiv.Basic set_option autoBoundImplicitLocal false --set_option pp.universes true class HasEmptyType (U : Universe) [h : HasExternalFunctors U U] where (Empty : U) (emptyIsEmpty : ⌈Empty⌉ → False) (emptyElimIsFun (α : U) : h.IsFun (λ e : Empty => @False.elim ⌈α⌉ (emptyIsEmpty e))) namespace HasEmptyType variable {U : Universe} def emptyElimFun' [HasExternalFunctors U U] [h : HasEmptyType U] (α : U) : h.Empty ⟶' α := BundledFunctor.mkFun (h.emptyElimIsFun α) def emptyElimFun [HasInternalFunctors U] [h : HasEmptyType U] (α : U) : h.Empty ⟶ α := HasInternalFunctors.fromBundled (emptyElimFun' α) def Not [HasInternalFunctors U] [h : HasEmptyType U] (α : U) := α ⟶ h.Empty end HasEmptyType -- TODO: Can we prove `α ⟶ Not α ⟶ β`? class HasClassicalLogic (U : Universe) [HasInternalFunctors U] [h : HasEmptyType U] where (byContradiction (α : U) : HasEmptyType.Not (HasEmptyType.Not α) ⟶ α) class HasUnitType (U : Universe) [h : HasExternalFunctors U U] where (Unit : U) (unit : Unit) (unitIntroIsFun (α : U) : h.IsFun (λ a : α => unit)) namespace HasUnitType variable {U : Universe} def unitIntroFun' [HasExternalFunctors U U] [h : HasUnitType U] (α : U) : α ⟶' h.Unit := BundledFunctor.mkFun (h.unitIntroIsFun α) def unitIntroFun [HasInternalFunctors U] [h : HasUnitType U] (α : U) : α ⟶ h.Unit := HasInternalFunctors.fromBundled (unitIntroFun' α) @[simp] theorem unitIntroFun.eff [HasInternalFunctors U] [h : HasUnitType U] (α : U) (a : α) : (unitIntroFun α) a = h.unit := by apply HasInternalFunctors.fromBundled.eff end HasUnitType
e6b894393635fbea1acdfeccf6eca7efd0de0b3e
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Lean/Elab/Tactic/Location.lean
84979e858489bdfd1b869a988e2443846aafd53a
[ "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
1,689
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.Tactic.Basic import Lean.Elab.Tactic.ElabTerm namespace Lean.Elab.Tactic inductive Location where | wildcard | targets (hypotheses : Array Syntax) (type : Bool) /- Recall that ``` syntax locationWildcard := "*" syntax locationHyp := (colGt term:max)+ ("⊢" <|> "|-")? syntax location := withPosition("at " locationWildcard <|> locationHyp) ``` -/ def expandLocation (stx : Syntax) : Location := let arg := stx[1] if arg.getKind == ``Parser.Tactic.locationWildcard then Location.wildcard else Location.targets arg[0].getArgs (!arg[1].isNone) def expandOptLocation (stx : Syntax) : Location := if stx.isNone then Location.targets #[] true else expandLocation stx[0] open Meta def withLocation (loc : Location) (atLocal : FVarId → TacticM Unit) (atTarget : TacticM Unit) (failed : MVarId → TacticM Unit) : TacticM Unit := do match loc with | Location.targets hyps type => hyps.forM fun hyp => withMainContext do let fvarId ← getFVarId hyp atLocal fvarId if type then atTarget | Location.wildcard => let worked ← tryTactic <| withMainContext <| atTarget withMainContext do let mut worked := worked -- We must traverse backwards because the given `atLocal` may use the revert/intro idiom for fvarId in (← getLCtx).getFVarIds.reverse do worked := worked || (← tryTactic <| withMainContext <| atLocal fvarId) unless worked do failed (← getMainGoal) end Lean.Elab.Tactic
52759b7e55e06b4c4a3d37764fabf641b81349a4
618003631150032a5676f229d13a079ac875ff77
/src/tactic/simp_command.lean
2287b252f6ac23f4b7fc040d7b57574272894723
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
4,718
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Keeley Hoek, Scott Morrison -/ import tactic.core /-! ## #simp A user command to run the simplifier. -/ namespace tactic /-- Strip all annotations of non local constants in the passed `expr`. (This is required in an incantation later on in order to make the C++ simplifier happy.) -/ private meta def strip_annotations_from_all_non_local_consts {elab : bool} (e : expr elab) : expr elab := expr.unsafe_cast $ e.unsafe_cast.replace $ λ e n, match e.is_annotation with | some (_, expr.local_const _ _ _ _) := none | some (_, _) := e.erase_annotations | _ := none end /-- `simp_arg_type.to_pexpr` retrieves the `pexpr` underlying the given `simp_arg_type`, if there is one. -/ meta def simp_arg_type.to_pexpr : simp_arg_type → option pexpr | sat@(simp_arg_type.expr e) := e | sat@(simp_arg_type.symm_expr e) := e | sat := none /-- Incantation which prepares a `pexpr` in a `simp_arg_type` for use by the simplifier after `expr.replace_subexprs` as been called to replace some of its local variables. -/ private meta def replace_subexprs_for_simp_arg (e : pexpr) (rules : list (expr × expr)) : pexpr := strip_annotations_from_all_non_local_consts $ pexpr.of_expr $ e.unsafe_cast.replace_subexprs rules /-- `simp_arg_type.replace_subexprs` calls `expr.replace_subexprs` on the underlying `pexpr`, if there is one, and then prepares the result for use by the simplifier. -/ meta def simp_arg_type.replace_subexprs : simp_arg_type → list (expr × expr) → simp_arg_type | (simp_arg_type.expr e) rules := simp_arg_type.expr $ replace_subexprs_for_simp_arg e rules | (simp_arg_type.symm_expr e) rules := simp_arg_type.symm_expr $ replace_subexprs_for_simp_arg e rules | sat rules := sat setup_tactic_parser /-- The basic usage is `#simp e`, where `e` is an expression, which will print the simplified form of `e`. You can specify additional simp lemmas as usual for example using `#simp [f, g] : e`, or `#simp with attr : e`. (The colon is optional, but helpful for the parser.) `#simp` understands local variables, so you can use them to introduce parameters. -/ @[user_command] meta def simp_cmd (_ : parse $ tk "#simp") : lean.parser unit := do no_dflt ← only_flag, hs ← simp_arg_list, attr_names ← with_ident_list, o ← optional (tk ":"), e ← types.texpr, /- Retrieve the `pexpr`s parsed as part of the simp args, and collate them into a big list. -/ let hs_es := list.join $ hs.map $ option.to_list ∘ simp_arg_type.to_pexpr, /- Synthesize a `tactic_state` including local variables as hypotheses under which `expr.simp` may be safely called with expected behaviour given the `variables` in the environment. -/ (ts, mappings) ← synthesize_tactic_state_with_variables_as_hyps (e :: hs_es), /- Enter the `tactic` monad, *critically* using the synthesized tactic state `ts`. -/ simp_result ← lean.parser.of_tactic $ λ _, do { /- Resolve the local variables added by the parser to `e` (when it was parsed) against the local hypotheses added to the `ts : tactic_state` which we are using. -/ e ← to_expr e, /- Replace the variables referenced in the passed `simp_arg_list` with the `expr`s corresponding to the local hypotheses we created. We would prefer to just elaborate the `pexpr`s encoded in the `simp_arg_list` against the tactic state we have created (as we could with `e` above), but the simplifier expects `pexpr`s and not `expr`s. Thus, we just modify the `pexpr`s now and let `simp` do the elaboration when the time comes. You might think that we could just examine each of these `pexpr`s, call `to_expr` on them, and then call `to_pexpr` afterward and save the results over the original `pexprs`. Due to how functions like `simp_lemmas.add_pexpr` are implemented in the core library, the `simp` framework is not robust enough to handle this method. When pieces of expressions like annotation macros are injected, the direct patten matches in the `simp_lemmas.*` codebase fail, and the lemmas we want don't get added. -/ let hs := hs.map $ λ sat, sat.replace_subexprs mappings, /- Finally, call `expr.simp` with `e` and return the result. -/ prod.fst <$> e.simp {} failed no_dflt attr_names hs } ts, /- Trace the result. -/ trace simp_result add_tactic_doc { name := "#simp", category := doc_category.cmd, decl_names := [`tactic.simp_cmd], tags := ["simplification"] } end tactic
0a55a35cb9ce4718e66590f7c43bfc6e918e80d5
491068d2ad28831e7dade8d6dff871c3e49d9431
/library/data/nat/find.lean
3a9c859e1b4901da013ef26d0ae9afc0963ee668
[ "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
3,598
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura Choice function for decidable predicates on natural numbers. This module provides the following two declarations: choose {p : nat → Prop} [d : decidable_pred p] : (∃ x, p x) → nat choose_spec {p : nat → Prop} [d : decidable_pred p] (ex : ∃ x, p x) : p (choose ex) -/ import data.nat.basic data.nat.order open nat subtype decidable well_founded namespace nat section find_x parameter {p : nat → Prop} private definition lbp (x : nat) : Prop := ∀ y, y < x → ¬ p y private lemma lbp_zero : lbp 0 := λ y h, absurd h (not_lt_zero y) private lemma lbp_succ {x : nat} : lbp x → ¬ p x → lbp (succ x) := λ lx npx y yltsx, or.elim (eq_or_lt_of_le (le_of_succ_le_succ yltsx)) (suppose y = x, by substvars; assumption) (suppose y < x, lx y this) private definition gtb (a b : nat) : Prop := a > b ∧ lbp a local infix ` ≺ `:50 := gtb private lemma acc_of_px {x : nat} : p x → acc gtb x := assume h, acc.intro x (λ (y : nat) (l : y ≺ x), obtain (h₁ : y > x) (h₂ : ∀ a, a < y → ¬ p a), from l, absurd h (h₂ x h₁)) private lemma acc_of_acc_succ {x : nat} : acc gtb (succ x) → acc gtb x := assume h, acc.intro x (λ (y : nat) (l : y ≺ x), by_cases (suppose y = succ x, by substvars; assumption) (suppose y ≠ succ x, have x < y, from and.elim_left l, have succ x < y, from lt_of_le_and_ne this (ne.symm `y ≠ succ x`), acc.inv h (and.intro this (and.elim_right l)))) private lemma acc_of_px_of_gt {x y : nat} : p x → y > x → acc gtb y := assume px ygtx, acc.intro y (λ (z : nat) (l : z ≺ y), obtain (zgty : z > y) (h : ∀ a, a < z → ¬ p a), from l, absurd px (h x (lt.trans ygtx zgty))) private lemma acc_of_acc_of_lt : ∀ {x y : nat}, acc gtb x → y < x → acc gtb y | 0 y a0 ylt0 := absurd ylt0 !not_lt_zero | (succ x) y asx yltsx := assert acc gtb x, from acc_of_acc_succ asx, by_cases (suppose y = x, by substvars; assumption) (suppose y ≠ x, acc_of_acc_of_lt `acc gtb x` (lt_of_le_and_ne (le_of_lt_succ yltsx) this)) parameter (ex : ∃ a, p a) parameter [dp : decidable_pred p] include dp private lemma acc_of_ex (x : nat) : acc gtb x := obtain (w : nat) (pw : p w), from ex, lt.by_cases (suppose x < w, acc_of_acc_of_lt (acc_of_px pw) this) (suppose x = w, by subst x; exact (acc_of_px pw)) (suppose x > w, acc_of_px_of_gt pw this) private lemma wf_gtb : well_founded gtb := well_founded.intro acc_of_ex private definition find.F (x : nat) : (Π x₁, x₁ ≺ x → lbp x₁ → {a : nat | p a}) → lbp x → {a : nat | p a} := match x with | 0 := λ f l0, by_cases (λ p0 : p 0, tag 0 p0) (suppose ¬ p 0, have lbp 1, from lbp_succ l0 this, have 1 ≺ 0, from and.intro (lt.base 0) `lbp 1`, f 1 `1 ≺ 0` `lbp 1`) | (succ n) := λ f lsn, by_cases (suppose p (succ n), tag (succ n) this) (suppose ¬ p (succ n), have lss : lbp (succ (succ n)), from lbp_succ lsn this, have succ (succ n) ≺ succ n, from and.intro (lt.base (succ n)) lss, f (succ (succ n)) this lss) end private definition find_x : {x : nat | p x} := @fix _ _ _ wf_gtb find.F 0 lbp_zero end find_x protected definition find {p : nat → Prop} [d : decidable_pred p] : (∃ x, p x) → nat := assume h, elt_of (find_x h) protected theorem find_spec {p : nat → Prop} [d : decidable_pred p] (ex : ∃ x, p x) : p (nat.find ex) := has_property (find_x ex) end nat
bbeea298f5029dc70e6b78b4e6ba355a68a389c4
f41725a360d902d3c7939fdf81a5acaf0d0467f0
/src/separable.lean
f85c6aae62a28b2f0c9675f49d812dbe2e8556bc
[]
no_license
pglutz/galois_theory
978765d82b7586c21fd719b84b21d5eea030b25d
4561c2c97d4c49377356e1d7a2051dedc87d30ba
refs/heads/master
1,671,472,063,361
1,603,597,360,000
1,603,597,360,000
281,502,125
0
0
null
null
null
null
UTF-8
Lean
false
false
2,761
lean
import ring_theory.algebra import field_theory.minimal_polynomial import field_theory.separable import adjoin variables (F : Type*) [field F] {E : Type*} [field E] [algebra F E] instance subfield_subset_subfield_algebra (J K : set E) [is_subfield J] [is_subfield K] (h : J ⊆ K) : algebra J K := { to_fun := λ x, ⟨↑x,begin cases x with x hx, exact h hx, end⟩, smul := λ x y, ⟨↑x,begin cases x with x hx, exact h hx, end⟩ * y, map_zero' := rfl, map_add' := λ x y, rfl, map_one' := rfl, map_mul' := λ x y, rfl, commutes' := λ x y, mul_comm _ _, smul_def' := λ x y, rfl, } instance subfield_subset_subfield_scalar (J K : set E) [is_subfield J] [is_subfield K] (h : J ⊆ K) : has_scalar J K := { smul := λ x y, ⟨↑x,begin cases x with x hx, exact h hx, end⟩ * y, } instance subfield_subset_subfield_scalar_tower (J K : set E) [is_subfield J] [is_subfield K] (h : J ⊆ K) : @is_scalar_tower J K E (subfield_subset_subfield_scalar J K h) _ _ := { smul_assoc := begin intros x y z, change ↑(_ * y) * z = x * (y * z), rw ←mul_assoc, refl, end, } lemma subfield_composition (J K : set E) [is_subfield J] [is_subfield K] (h : J ⊆ K) : (algebra_map K E).comp(@algebra_map J K _ _ (subfield_subset_subfield_algebra J K h)) = algebra_map J E := begin ext, refl, end lemma separable.subfield_aux (J K : set E) [is_subfield J] [is_subfield K] (h : J ⊆ K) (h_sep : is_separable J E) : is_separable K E := begin intro x, cases h_sep x with hx hs, have key := @is_integral_of_is_scalar_tower J K E _ _ _ (subfield_subset_subfield_algebra _ _ h) _ _ _ x hx, use key, set f := @algebra_map J K _ _ (subfield_subset_subfield_algebra J K h), set p := (minimal_polynomial hx).map f, have key' : (minimal_polynomial key) ∣ p, apply minimal_polynomial.dvd, dsimp[polynomial.aeval], rw polynomial.eval₂_map, rw subfield_composition J K h, apply minimal_polynomial.aeval, cases key' with q hq, have hp : p.separable := polynomial.separable.map hs, rw hq at hp, exact polynomial.separable.of_mul_left hp, end lemma separable.subfield (K : set E) [is_subfield K] (F_sep : is_separable F E) (h : set.range (algebra_map F E) ⊆ K) : is_separable K E := separable.subfield_aux (set.range (algebra_map F E)) K h (inclusion.separable F_sep) lemma adjoin_is_separable (F_sep : is_separable F E) (S : set E) : is_separable (adjoin F S) E := separable.subfield F (adjoin F S) F_sep (field_subset_adjoin F S) lemma adjoin_simple_is_separable (F_sep : is_separable F E) (α : E) : is_separable (F[α]) E := adjoin_is_separable F F_sep {α}
d6bfd78b5683efbb23f52cba5055add934204d4f
bb31430994044506fa42fd667e2d556327e18dfe
/src/field_theory/separable.lean
ffbe6f49b93205d3d8ac53d89730f375f81ae8ef
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
21,007
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.squarefree import data.polynomial.expand import data.polynomial.splits import field_theory.minpoly.field import ring_theory.power_basis /-! # Separable polynomials We define a polynomial to be separable if it is coprime with its derivative. We prove basic properties about separable polynomials here. ## Main definitions * `polynomial.separable f`: a polynomial `f` is separable iff it is coprime with its derivative. -/ universes u v w open_locale classical big_operators polynomial open finset namespace polynomial section comm_semiring variables {R : Type u} [comm_semiring R] {S : Type v} [comm_semiring S] /-- A polynomial is separable iff it is coprime with its derivative. -/ def separable (f : R[X]) : Prop := is_coprime f f.derivative lemma separable_def (f : R[X]) : f.separable ↔ is_coprime f f.derivative := iff.rfl lemma separable_def' (f : R[X]) : f.separable ↔ ∃ a b : R[X], a * f + b * f.derivative = 1 := iff.rfl lemma not_separable_zero [nontrivial R] : ¬ separable (0 : R[X]) := begin rintro ⟨x, y, h⟩, simpa only [derivative_zero, mul_zero, add_zero, zero_ne_one] using h, end lemma separable_one : (1 : R[X]).separable := is_coprime_one_left @[nontriviality] lemma separable_of_subsingleton [subsingleton R] (f : R[X]) : f.separable := by simp [separable] lemma separable_X_add_C (a : R) : (X + C a).separable := by { rw [separable_def, derivative_add, derivative_X, derivative_C, add_zero], exact is_coprime_one_right } lemma separable_X : (X : R[X]).separable := by { rw [separable_def, derivative_X], exact is_coprime_one_right } lemma separable_C (r : R) : (C r).separable ↔ is_unit r := by rw [separable_def, derivative_C, is_coprime_zero_right, is_unit_C] lemma separable.of_mul_left {f g : R[X]} (h : (f * g).separable) : f.separable := begin have := h.of_mul_left_left, rw derivative_mul at this, exact is_coprime.of_mul_right_left (is_coprime.of_add_mul_left_right this) end lemma separable.of_mul_right {f g : R[X]} (h : (f * g).separable) : g.separable := by { rw mul_comm at h, exact h.of_mul_left } lemma separable.of_dvd {f g : R[X]} (hf : f.separable) (hfg : g ∣ f) : g.separable := by { rcases hfg with ⟨f', rfl⟩, exact separable.of_mul_left hf } lemma separable_gcd_left {F : Type*} [field F] {f : F[X]} (hf : f.separable) (g : F[X]) : (euclidean_domain.gcd f g).separable := separable.of_dvd hf (euclidean_domain.gcd_dvd_left f g) lemma separable_gcd_right {F : Type*} [field F] {g : F[X]} (f : F[X]) (hg : g.separable) : (euclidean_domain.gcd f g).separable := separable.of_dvd hg (euclidean_domain.gcd_dvd_right f g) lemma separable.is_coprime {f g : R[X]} (h : (f * g).separable) : is_coprime f g := begin have := h.of_mul_left_left, rw derivative_mul at this, exact is_coprime.of_mul_right_right (is_coprime.of_add_mul_left_right this) end theorem separable.of_pow' {f : R[X]} : ∀ {n : ℕ} (h : (f ^ n).separable), is_unit f ∨ (f.separable ∧ n = 1) ∨ n = 0 | 0 := λ h, or.inr $ or.inr rfl | 1 := λ h, or.inr $ or.inl ⟨pow_one f ▸ h, rfl⟩ | (n+2) := λ h, by { rw [pow_succ, pow_succ] at h, exact or.inl (is_coprime_self.1 h.is_coprime.of_mul_right_left) } theorem separable.of_pow {f : R[X]} (hf : ¬is_unit f) {n : ℕ} (hn : n ≠ 0) (hfs : (f ^ n).separable) : f.separable ∧ n = 1 := (hfs.of_pow'.resolve_left hf).resolve_right hn theorem separable.map {p : R[X]} (h : p.separable) {f : R →+* S} : (p.map f).separable := let ⟨a, b, H⟩ := h in ⟨a.map f, b.map f, by rw [derivative_map, ← polynomial.map_mul, ← polynomial.map_mul, ← polynomial.map_add, H, polynomial.map_one]⟩ variables (p q : ℕ) lemma is_unit_of_self_mul_dvd_separable {p q : R[X]} (hp : p.separable) (hq : q * q ∣ p) : is_unit q := begin obtain ⟨p, rfl⟩ := hq, apply is_coprime_self.mp, have : is_coprime (q * (q * p)) (q * (q.derivative * p + q.derivative * p + q * p.derivative)), { simp only [← mul_assoc, mul_add], convert hp, rw [derivative_mul, derivative_mul], ring }, exact is_coprime.of_mul_right_left (is_coprime.of_mul_left_left this) end lemma multiplicity_le_one_of_separable {p q : R[X]} (hq : ¬ is_unit q) (hsep : separable p) : multiplicity q p ≤ 1 := begin contrapose! hq, apply is_unit_of_self_mul_dvd_separable hsep, rw ← sq, apply multiplicity.pow_dvd_of_le_multiplicity, simpa only [nat.cast_one, nat.cast_bit0] using part_enat.add_one_le_of_lt hq end lemma separable.squarefree {p : R[X]} (hsep : separable p) : squarefree p := begin rw multiplicity.squarefree_iff_multiplicity_le_one p, intro f, by_cases hunit : is_unit f, { exact or.inr hunit }, exact or.inl (multiplicity_le_one_of_separable hunit hsep) end end comm_semiring section comm_ring variables {R : Type u} [comm_ring R] lemma separable_X_sub_C {x : R} : separable (X - C x) := by simpa only [sub_eq_add_neg, C_neg] using separable_X_add_C (-x) lemma separable.mul {f g : R[X]} (hf : f.separable) (hg : g.separable) (h : is_coprime f g) : (f * g).separable := by { rw [separable_def, derivative_mul], exact ((hf.mul_right h).add_mul_left_right _).mul_left ((h.symm.mul_right hg).mul_add_right_right _) } lemma separable_prod' {ι : Sort*} {f : ι → R[X]} {s : finset ι} : (∀x∈s, ∀y∈s, x ≠ y → is_coprime (f x) (f y)) → (∀x∈s, (f x).separable) → (∏ x in s, f x).separable := finset.induction_on s (λ _ _, separable_one) $ λ a s has ih h1 h2, begin simp_rw [finset.forall_mem_insert, forall_and_distrib] at h1 h2, rw prod_insert has, exact h2.1.mul (ih h1.2.2 h2.2) (is_coprime.prod_right $ λ i his, h1.1.2 i his $ ne.symm $ ne_of_mem_of_not_mem his has) end lemma separable_prod {ι : Sort*} [fintype ι] {f : ι → R[X]} (h1 : pairwise (is_coprime on f)) (h2 : ∀ x, (f x).separable) : (∏ x, f x).separable := separable_prod' (λ x hx y hy hxy, h1 hxy) (λ x hx, h2 x) lemma separable.inj_of_prod_X_sub_C [nontrivial R] {ι : Sort*} {f : ι → R} {s : finset ι} (hfs : (∏ i in s, (X - C (f i))).separable) {x y : ι} (hx : x ∈ s) (hy : y ∈ s) (hfxy : f x = f y) : x = y := begin by_contra hxy, rw [← insert_erase hx, prod_insert (not_mem_erase _ _), ← insert_erase (mem_erase_of_ne_of_mem (ne.symm hxy) hy), prod_insert (not_mem_erase _ _), ← mul_assoc, hfxy, ← sq] at hfs, cases (hfs.of_mul_left.of_pow (by exact not_is_unit_X_sub_C _) two_ne_zero).2 end lemma separable.injective_of_prod_X_sub_C [nontrivial R] {ι : Sort*} [fintype ι] {f : ι → R} (hfs : (∏ i, (X - C (f i))).separable) : function.injective f := λ x y hfxy, hfs.inj_of_prod_X_sub_C (mem_univ _) (mem_univ _) hfxy lemma nodup_of_separable_prod [nontrivial R] {s : multiset R} (hs : separable (multiset.map (λ a, X - C a) s).prod) : s.nodup := begin rw multiset.nodup_iff_ne_cons_cons, rintros a t rfl, refine not_is_unit_X_sub_C a (is_unit_of_self_mul_dvd_separable hs _), simpa only [multiset.map_cons, multiset.prod_cons] using mul_dvd_mul_left _ (dvd_mul_right _ _) end /--If `is_unit n` in a `comm_ring R`, then `X ^ n - u` is separable for any unit `u`. -/ lemma separable_X_pow_sub_C_unit {n : ℕ} (u : Rˣ) (hn : is_unit (n : R)) : separable (X ^ n - C (u : R)) := begin nontriviality R, rcases n.eq_zero_or_pos with rfl | hpos, { simpa using hn }, apply (separable_def' (X ^ n - C (u : R))).2, obtain ⟨n', hn'⟩ := hn.exists_left_inv, refine ⟨-C ↑u⁻¹, C ↑u⁻¹ * C n' * X, _⟩, rw [derivative_sub, derivative_C, sub_zero, derivative_pow X n, derivative_X, mul_one], calc - C ↑u⁻¹ * (X ^ n - C ↑u) + C ↑u⁻¹ * C n' * X * (↑n * X ^ (n - 1)) = C (↑u⁻¹ * ↑ u) - C ↑u⁻¹ * X^n + C ↑ u ⁻¹ * C (n' * ↑n) * (X * X ^ (n - 1)) : by { simp only [C.map_mul, C_eq_nat_cast], ring } ... = 1 : by simp only [units.inv_mul, hn', C.map_one, mul_one, ← pow_succ, nat.sub_add_cancel (show 1 ≤ n, from hpos), sub_add_cancel] end lemma root_multiplicity_le_one_of_separable [nontrivial R] {p : R[X]} (hsep : separable p) (x : R) : root_multiplicity x p ≤ 1 := begin by_cases hp : p = 0, { simp [hp], }, rw [root_multiplicity_eq_multiplicity, dif_neg hp, ← part_enat.coe_le_coe, part_enat.coe_get, nat.cast_one], exact multiplicity_le_one_of_separable (not_is_unit_X_sub_C _) hsep end end comm_ring section is_domain variables {R : Type u} [comm_ring R] [is_domain R] lemma count_roots_le_one {p : R[X]} (hsep : separable p) (x : R) : p.roots.count x ≤ 1 := begin rw count_roots p, exact root_multiplicity_le_one_of_separable hsep x end lemma nodup_roots {p : R[X]} (hsep : separable p) : p.roots.nodup := multiset.nodup_iff_count_le_one.mpr (count_roots_le_one hsep) end is_domain section field variables {F : Type u} [field F] {K : Type v} [field K] theorem separable_iff_derivative_ne_zero {f : F[X]} (hf : irreducible f) : f.separable ↔ f.derivative ≠ 0 := ⟨λ h1 h2, hf.not_unit $ is_coprime_zero_right.1 $ h2 ▸ h1, λ h, euclidean_domain.is_coprime_of_dvd (mt and.right h) $ λ g hg1 hg2 ⟨p, hg3⟩ hg4, let ⟨u, hu⟩ := (hf.is_unit_or_is_unit hg3).resolve_left hg1 in have f ∣ f.derivative, by { conv_lhs { rw [hg3, ← hu] }, rwa units.mul_right_dvd }, not_lt_of_le (nat_degree_le_of_dvd this h) $ nat_degree_derivative_lt $ mt derivative_of_nat_degree_zero h⟩ theorem separable_map (f : F →+* K) {p : F[X]} : (p.map f).separable ↔ p.separable := by simp_rw [separable_def, derivative_map, is_coprime_map] lemma separable_prod_X_sub_C_iff' {ι : Sort*} {f : ι → F} {s : finset ι} : (∏ i in s, (X - C (f i))).separable ↔ (∀ (x ∈ s) (y ∈ s), f x = f y → x = y) := ⟨λ hfs x hx y hy hfxy, hfs.inj_of_prod_X_sub_C hx hy hfxy, λ H, by { rw ← prod_attach, exact separable_prod' (λ x hx y hy hxy, @pairwise_coprime_X_sub_C _ _ { x // x ∈ s } (λ x, f x) (λ x y hxy, subtype.eq $ H x.1 x.2 y.1 y.2 hxy) _ _ hxy) (λ _ _, separable_X_sub_C) }⟩ lemma separable_prod_X_sub_C_iff {ι : Sort*} [fintype ι] {f : ι → F} : (∏ i, (X - C (f i))).separable ↔ function.injective f := separable_prod_X_sub_C_iff'.trans $ by simp_rw [mem_univ, true_implies_iff, function.injective] section char_p variables (p : ℕ) [HF : char_p F p] include HF theorem separable_or {f : F[X]} (hf : irreducible f) : f.separable ∨ ¬f.separable ∧ ∃ g : F[X], irreducible g ∧ expand F p g = f := if H : f.derivative = 0 then begin unfreezingI { rcases p.eq_zero_or_pos with rfl | hp }, { haveI := char_p.char_p_to_char_zero F, have := nat_degree_eq_zero_of_derivative_eq_zero H, have := (nat_degree_pos_iff_degree_pos.mpr $ degree_pos_of_irreducible hf).ne', contradiction }, haveI := is_local_ring_hom_expand F hp, exact or.inr ⟨by rw [separable_iff_derivative_ne_zero hf, not_not, H], contract p f, of_irreducible_map ↑(expand F p) (by rwa ← expand_contract p H hp.ne' at hf), expand_contract p H hp.ne'⟩ end else or.inl $ (separable_iff_derivative_ne_zero hf).2 H theorem exists_separable_of_irreducible {f : F[X]} (hf : irreducible f) (hp : p ≠ 0) : ∃ (n : ℕ) (g : F[X]), g.separable ∧ expand F (p ^ n) g = f := begin replace hp : p.prime := (char_p.char_is_prime_or_zero F p).resolve_right hp, unfreezingI { induction hn : f.nat_degree using nat.strong_induction_on with N ih generalizing f }, rcases separable_or p hf with h | ⟨h1, g, hg, hgf⟩, { refine ⟨0, f, h, _⟩, rw [pow_zero, expand_one] }, { cases N with N, { rw [nat_degree_eq_zero_iff_degree_le_zero, degree_le_zero_iff] at hn, rw [hn, separable_C, is_unit_iff_ne_zero, not_not] at h1, have hf0 : f ≠ 0 := hf.ne_zero, rw [h1, C_0] at hn, exact absurd hn hf0 }, have hg1 : g.nat_degree * p = N.succ, { rwa [← nat_degree_expand, hgf] }, have hg2 : g.nat_degree ≠ 0, { intro this, rw [this, zero_mul] at hg1, cases hg1 }, have hg3 : g.nat_degree < N.succ, { rw [← mul_one g.nat_degree, ← hg1], exact nat.mul_lt_mul_of_pos_left hp.one_lt hg2.bot_lt }, rcases ih _ hg3 hg rfl with ⟨n, g, hg4, rfl⟩, refine ⟨n+1, g, hg4, _⟩, rw [← hgf, expand_expand, pow_succ] } end theorem is_unit_or_eq_zero_of_separable_expand {f : F[X]} (n : ℕ) (hp : 0 < p) (hf : (expand F (p ^ n) f).separable) : is_unit f ∨ n = 0 := begin rw or_iff_not_imp_right, rintro hn : n ≠ 0, have hf2 : (expand F (p ^ n) f).derivative = 0, { rw [derivative_expand, nat.cast_pow, char_p.cast_eq_zero, zero_pow hn.bot_lt, zero_mul, mul_zero] }, rw [separable_def, hf2, is_coprime_zero_right, is_unit_iff] at hf, rcases hf with ⟨r, hr, hrf⟩, rw [eq_comm, expand_eq_C (pow_pos hp _)] at hrf, rwa [hrf, is_unit_C] end theorem unique_separable_of_irreducible {f : F[X]} (hf : irreducible f) (hp : 0 < p) (n₁ : ℕ) (g₁ : F[X]) (hg₁ : g₁.separable) (hgf₁ : expand F (p ^ n₁) g₁ = f) (n₂ : ℕ) (g₂ : F[X]) (hg₂ : g₂.separable) (hgf₂ : expand F (p ^ n₂) g₂ = f) : n₁ = n₂ ∧ g₁ = g₂ := begin revert g₁ g₂, wlog hn : n₁ ≤ n₂ := le_total n₁ n₂ using [n₁ n₂, n₂ n₁], have hf0 : f ≠ 0 := hf.ne_zero, unfreezingI { intros, rw le_iff_exists_add at hn, rcases hn with ⟨k, rfl⟩, rw [← hgf₁, pow_add, expand_mul, expand_inj (pow_pos hp n₁)] at hgf₂, subst hgf₂, subst hgf₁, rcases is_unit_or_eq_zero_of_separable_expand p k hp hg₁ with h | rfl, { rw is_unit_iff at h, rcases h with ⟨r, hr, rfl⟩, simp_rw expand_C at hf, exact absurd (is_unit_C.2 hr) hf.1 }, { rw [add_zero, pow_zero, expand_one], split; refl } }, obtain ⟨hn, hg⟩ := this g₂ g₁ hg₂ hgf₂ hg₁ hgf₁, exact ⟨hn.symm, hg.symm⟩ end end char_p /--If `n ≠ 0` in `F`, then ` X ^ n - a` is separable for any `a ≠ 0`. -/ lemma separable_X_pow_sub_C {n : ℕ} (a : F) (hn : (n : F) ≠ 0) (ha : a ≠ 0) : separable (X ^ n - C a) := separable_X_pow_sub_C_unit (units.mk0 a ha) (is_unit.mk0 n hn) -- this can possibly be strengthened to making `separable_X_pow_sub_C_unit` a -- bi-implication, but it is nontrivial! /-- In a field `F`, `X ^ n - 1` is separable iff `↑n ≠ 0`. -/ lemma X_pow_sub_one_separable_iff {n : ℕ} : (X ^ n - 1 : F[X]).separable ↔ (n : F) ≠ 0 := begin refine ⟨_, λ h, separable_X_pow_sub_C_unit 1 (is_unit.mk0 ↑n h)⟩, rw [separable_def', derivative_sub, derivative_X_pow, derivative_one, sub_zero], -- Suppose `(n : F) = 0`, then the derivative is `0`, so `X ^ n - 1` is a unit, contradiction. rintro (h : is_coprime _ _) hn', rw [hn', C_0, zero_mul, is_coprime_zero_right] at h, exact not_is_unit_X_pow_sub_one F n h end section splits lemma card_root_set_eq_nat_degree [algebra F K] {p : F[X]} (hsep : p.separable) (hsplit : splits (algebra_map F K) p) : fintype.card (p.root_set K) = p.nat_degree := begin simp_rw [root_set_def, finset.coe_sort_coe, fintype.card_coe], rw [multiset.to_finset_card_of_nodup, ←nat_degree_eq_card_roots hsplit], exact nodup_roots hsep.map, end variable {i : F →+* K} lemma eq_X_sub_C_of_separable_of_root_eq {x : F} {h : F[X]} (h_sep : h.separable) (h_root : h.eval x = 0) (h_splits : splits i h) (h_roots : ∀ y ∈ (h.map i).roots, y = i x) : h = (C (leading_coeff h)) * (X - C x) := begin have h_ne_zero : h ≠ 0 := by { rintro rfl, exact not_separable_zero h_sep }, apply polynomial.eq_X_sub_C_of_splits_of_single_root i h_splits, apply finset.mk.inj, { change _ = {i x}, rw finset.eq_singleton_iff_unique_mem, split, { apply finset.mem_mk.mpr, rw mem_roots (show h.map i ≠ 0, by exact map_ne_zero h_ne_zero), rw [is_root.def,←eval₂_eq_eval_map,eval₂_hom,h_root], exact ring_hom.map_zero i }, { exact h_roots } }, { exact nodup_roots (separable.map h_sep) }, end lemma exists_finset_of_splits (i : F →+* K) {f : F[X]} (sep : separable f) (sp : splits i f) : ∃ (s : finset K), f.map i = C (i f.leading_coeff) * (s.prod (λ a : K, X - C a)) := begin obtain ⟨s, h⟩ := (splits_iff_exists_multiset _).1 sp, use s.to_finset, rw [h, finset.prod_eq_multiset_prod, ←multiset.to_finset_eq], apply nodup_of_separable_prod, apply separable.of_mul_right, rw ←h, exact sep.map, end end splits theorem _root_.irreducible.separable [char_zero F] {f : F[X]} (hf : irreducible f) : f.separable := begin rw [separable_iff_derivative_ne_zero hf, ne, ← degree_eq_bot, degree_derivative_eq], { rintro ⟨⟩ }, rw [pos_iff_ne_zero, ne, nat_degree_eq_zero_iff_degree_le_zero, degree_le_zero_iff], refine λ hf1, hf.not_unit _, rw [hf1, is_unit_C, is_unit_iff_ne_zero], intro hf2, rw [hf2, C_0] at hf1, exact absurd hf1 hf.ne_zero end end field end polynomial open polynomial section comm_ring variables (F K : Type*) [comm_ring F] [ring K] [algebra F K] -- TODO: refactor to allow transcendental extensions? -- See: https://en.wikipedia.org/wiki/Separable_extension#Separability_of_transcendental_extensions -- Note that right now a Galois extension (class `is_galois`) is defined to be an extension which -- is separable and normal, so if the definition of separable changes here at some point -- to allow non-algebraic extensions, then the definition of `is_galois` must also be changed. /-- Typeclass for separable field extension: `K` is a separable field extension of `F` iff the minimal polynomial of every `x : K` is separable. We define this for general (commutative) rings and only assume `F` and `K` are fields if this is needed for a proof. -/ class is_separable : Prop := (is_integral' (x : K) : is_integral F x) (separable' (x : K) : (minpoly F x).separable) variables (F) {K} theorem is_separable.is_integral [is_separable F K] : ∀ x : K, is_integral F x := is_separable.is_integral' theorem is_separable.separable [is_separable F K] : ∀ x : K, (minpoly F x).separable := is_separable.separable' variables {F K} theorem is_separable_iff : is_separable F K ↔ ∀ x : K, is_integral F x ∧ (minpoly F x).separable := ⟨λ h x, ⟨@@is_separable.is_integral F _ _ _ h x, @@is_separable.separable F _ _ _ h x⟩, λ h, ⟨λ x, (h x).1, λ x, (h x).2⟩⟩ end comm_ring instance is_separable_self (F : Type*) [field F] : is_separable F F := ⟨λ x, is_integral_algebra_map, λ x, by { rw minpoly.eq_X_sub_C', exact separable_X_sub_C }⟩ /-- A finite field extension in characteristic 0 is separable. -/ @[priority 100] -- See note [lower instance priority] instance is_separable.of_finite (F K : Type*) [field F] [field K] [algebra F K] [finite_dimensional F K] [char_zero F] : is_separable F K := have ∀ (x : K), is_integral F x, from λ x, algebra.is_integral_of_finite _ _ _, ⟨this, λ x, (minpoly.irreducible (this x)).separable⟩ section is_separable_tower variables (F K E : Type*) [field F] [field K] [field E] [algebra F K] [algebra F E] [algebra K E] [is_scalar_tower F K E] lemma is_separable_tower_top_of_is_separable [is_separable F E] : is_separable K E := ⟨λ x, is_integral_of_is_scalar_tower (is_separable.is_integral F x), λ x, (is_separable.separable F x).map.of_dvd (minpoly.dvd_map_of_is_scalar_tower _ _ _)⟩ lemma is_separable_tower_bot_of_is_separable [h : is_separable F E] : is_separable F K := is_separable_iff.2 $ λ x, begin refine (is_separable_iff.1 h (algebra_map K E x)).imp is_integral_tower_bot_of_is_integral_field (λ hs, _), obtain ⟨q, hq⟩ := minpoly.dvd F x ((aeval_algebra_map_eq_zero_iff _ _ _).mp (minpoly.aeval F ((algebra_map K E) x))), rw hq at hs, exact hs.of_mul_left end variables {E} lemma is_separable.of_alg_hom (E' : Type*) [field E'] [algebra F E'] (f : E →ₐ[F] E') [is_separable F E'] : is_separable F E := begin letI : algebra E E' := ring_hom.to_algebra f.to_ring_hom, haveI : is_scalar_tower F E E' := is_scalar_tower.of_algebra_map_eq (λ x, (f.commutes x).symm), exact is_separable_tower_bot_of_is_separable F E E', end end is_separable_tower section card_alg_hom variables {R S T : Type*} [comm_ring S] variables {K L F : Type*} [field K] [field L] [field F] variables [algebra K S] [algebra K L] lemma alg_hom.card_of_power_basis (pb : power_basis K S) (h_sep : (minpoly K pb.gen).separable) (h_splits : (minpoly K pb.gen).splits (algebra_map K L)) : @fintype.card (S →ₐ[K] L) (power_basis.alg_hom.fintype pb) = pb.dim := begin let s := ((minpoly K pb.gen).map (algebra_map K L)).roots.to_finset, have H := λ x, multiset.mem_to_finset, rw [fintype.card_congr pb.lift_equiv', fintype.card_of_subtype s H, ← pb.nat_degree_minpoly, nat_degree_eq_card_roots h_splits, multiset.to_finset_card_of_nodup], exact nodup_roots ((separable_map (algebra_map K L)).mpr h_sep) end end card_alg_hom
cd7526655e69f7c9a2553ee183e9cbd2d4da51c0
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/qpf/multivariate/constructions/fix.lean
ef1470eae2ebb88d53f3d71b6ae2fc061fd745a6
[ "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
12,886
lean
/- Copyright (c) 2018 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Simon Hudon -/ import data.pfunctor.multivariate.W import data.qpf.multivariate.basic /-! # The initial algebra of a multivariate qpf is again a qpf. For a `(n+1)`-ary QPF `F (α₀,..,αₙ)`, we take the least fixed point of `F` with regards to its last argument `αₙ`. The result is a `n`-ary functor: `fix F (α₀,..,αₙ₋₁)`. Making `fix F` into a functor allows us to take the fixed point, compose with other functors and take a fixed point again. ## Main definitions * `fix.mk` - constructor * `fix.dest - destructor * `fix.rec` - recursor: basis for defining functions by structural recursion on `fix F α` * `fix.drec` - dependent recursor: generalization of `fix.rec` where the result type of the function is allowed to depend on the `fix F α` value * `fix.rec_eq` - defining equation for `recursor` * `fix.ind` - induction principle for `fix F α` ## Implementation notes For `F` a QPF`, we define `fix F α` in terms of the W-type of the polynomial functor `P` of `F`. We define the relation `Wequiv` and take its quotient as the definition of `fix F α`. ```lean inductive Wequiv {α : typevec n} : q.P.W α → q.P.W α → Prop | ind (a : q.P.A) (f' : q.P.drop.B a ⟹ α) (f₀ f₁ : q.P.last.B a → q.P.W α) : (∀ x, Wequiv (f₀ x) (f₁ x)) → Wequiv (q.P.W_mk a f' f₀) (q.P.W_mk a f' f₁) | abs (a₀ : q.P.A) (f'₀ : q.P.drop.B a₀ ⟹ α) (f₀ : q.P.last.B a₀ → q.P.W α) (a₁ : q.P.A) (f'₁ : q.P.drop.B a₁ ⟹ α) (f₁ : q.P.last.B a₁ → q.P.W α) : abs ⟨a₀, q.P.append_contents f'₀ f₀⟩ = abs ⟨a₁, q.P.append_contents f'₁ f₁⟩ → Wequiv (q.P.W_mk a₀ f'₀ f₀) (q.P.W_mk a₁ f'₁ f₁) | trans (u v w : q.P.W α) : Wequiv u v → Wequiv v w → Wequiv u w ``` See [avigad-carneiro-hudon2019] for more details. ## Reference * Jeremy Avigad, Mario M. Carneiro and Simon Hudon. [*Data Types as Quotients of Polynomial Functors*][avigad-carneiro-hudon2019] -/ universes u v namespace mvqpf open typevec open mvfunctor (liftp liftr) open_locale mvfunctor variables {n : ℕ} {F : typevec.{u} (n+1) → Type u} [mvfunctor F] [q : mvqpf F] include q /-- `recF` is used as a basis for defining the recursor on `fix F α`. `recF` traverses recursively the W-type generated by `q.P` using a function on `F` as a recursive step -/ def recF {α : typevec n} {β : Type*} (g : F (α.append1 β) → β) : q.P.W α → β := q.P.W_rec (λ a f' f rec, g (abs ⟨a, split_fun f' rec⟩)) theorem recF_eq {α : typevec n} {β : Type*} (g : F (α.append1 β) → β) (a : q.P.A) (f' : q.P.drop.B a ⟹ α) (f : q.P.last.B a → q.P.W α) : recF g (q.P.W_mk a f' f) = g (abs ⟨a, split_fun f' (recF g ∘ f)⟩) := by rw [recF, mvpfunctor.W_rec_eq]; refl theorem recF_eq' {α : typevec n} {β : Type*} (g : F (α.append1 β) → β) (x : q.P.W α) : recF g x = g (abs ((append_fun id (recF g)) <$$> q.P.W_dest' x)) := begin apply q.P.W_cases _ x, intros a f' f, rw [recF_eq, q.P.W_dest'_W_mk, mvpfunctor.map_eq, append_fun_comp_split_fun, typevec.id_comp] end /-- Equivalence relation on W-types that represent the same `fix F` value -/ inductive Wequiv {α : typevec n} : q.P.W α → q.P.W α → Prop | ind (a : q.P.A) (f' : q.P.drop.B a ⟹ α) (f₀ f₁ : q.P.last.B a → q.P.W α) : (∀ x, Wequiv (f₀ x) (f₁ x)) → Wequiv (q.P.W_mk a f' f₀) (q.P.W_mk a f' f₁) | abs (a₀ : q.P.A) (f'₀ : q.P.drop.B a₀ ⟹ α) (f₀ : q.P.last.B a₀ → q.P.W α) (a₁ : q.P.A) (f'₁ : q.P.drop.B a₁ ⟹ α) (f₁ : q.P.last.B a₁ → q.P.W α) : abs ⟨a₀, q.P.append_contents f'₀ f₀⟩ = abs ⟨a₁, q.P.append_contents f'₁ f₁⟩ → Wequiv (q.P.W_mk a₀ f'₀ f₀) (q.P.W_mk a₁ f'₁ f₁) | trans (u v w : q.P.W α) : Wequiv u v → Wequiv v w → Wequiv u w theorem recF_eq_of_Wequiv (α : typevec n) {β : Type*} (u : F (α.append1 β) → β) (x y : q.P.W α) : Wequiv x y → recF u x = recF u y := begin apply q.P.W_cases _ x, intros a₀ f'₀ f₀, apply q.P.W_cases _ y, intros a₁ f'₁ f₁, intro h, induction h, case mvqpf.Wequiv.ind : a f' f₀ f₁ h ih { simp only [recF_eq, function.comp, ih] }, case mvqpf.Wequiv.abs : a₀ f'₀ f₀ a₁ f'₁ f₁ h { simp only [recF_eq', abs_map, mvpfunctor.W_dest'_W_mk, h] }, case mvqpf.Wequiv.trans : x y z e₁ e₂ ih₁ ih₂ { exact eq.trans ih₁ ih₂ } end theorem Wequiv.abs' {α : typevec n} (x y : q.P.W α) (h : abs (q.P.W_dest' x) = abs (q.P.W_dest' y)) : Wequiv x y := begin revert h, apply q.P.W_cases _ x, intros a₀ f'₀ f₀, apply q.P.W_cases _ y, intros a₁ f'₁ f₁, apply Wequiv.abs end theorem Wequiv.refl {α : typevec n} (x : q.P.W α) : Wequiv x x := by apply q.P.W_cases _ x; intros a f' f; exact Wequiv.abs a f' f a f' f rfl theorem Wequiv.symm {α : typevec n} (x y : q.P.W α) : Wequiv x y → Wequiv y x := begin intro h, induction h, case mvqpf.Wequiv.ind : a f' f₀ f₁ h ih { exact Wequiv.ind _ _ _ _ ih }, case mvqpf.Wequiv.abs : a₀ f'₀ f₀ a₁ f'₁ f₁ h { exact Wequiv.abs _ _ _ _ _ _ h.symm }, case mvqpf.Wequiv.trans : x y z e₁ e₂ ih₁ ih₂ { exact mvqpf.Wequiv.trans _ _ _ ih₂ ih₁} end /-- maps every element of the W type to a canonical representative -/ def Wrepr {α : typevec n} : q.P.W α → q.P.W α := recF (q.P.W_mk' ∘ repr) theorem Wrepr_W_mk {α : typevec n} (a : q.P.A) (f' : q.P.drop.B a ⟹ α) (f : q.P.last.B a → q.P.W α) : Wrepr (q.P.W_mk a f' f) = q.P.W_mk' (repr (abs ((append_fun id Wrepr) <$$> ⟨a, q.P.append_contents f' f⟩))) := by rw [Wrepr, recF_eq', q.P.W_dest'_W_mk]; refl theorem Wrepr_equiv {α : typevec n} (x : q.P.W α) : Wequiv (Wrepr x) x := begin apply q.P.W_ind _ x, intros a f' f ih, apply Wequiv.trans _ (q.P.W_mk' ((append_fun id Wrepr) <$$> ⟨a, q.P.append_contents f' f⟩)), { apply Wequiv.abs', rw [Wrepr_W_mk, q.P.W_dest'_W_mk', q.P.W_dest'_W_mk', abs_repr] }, rw [q.P.map_eq, mvpfunctor.W_mk', append_fun_comp_split_fun, id_comp], apply Wequiv.ind, exact ih end theorem Wequiv_map {α β : typevec n} (g : α ⟹ β) (x y : q.P.W α) : Wequiv x y → Wequiv (g <$$> x) (g <$$> y) := begin intro h, induction h, case mvqpf.Wequiv.ind : a f' f₀ f₁ h ih { rw [q.P.W_map_W_mk, q.P.W_map_W_mk], apply Wequiv.ind, apply ih }, case mvqpf.Wequiv.abs : a₀ f'₀ f₀ a₁ f'₁ f₁ h { rw [q.P.W_map_W_mk, q.P.W_map_W_mk], apply Wequiv.abs, show abs (q.P.obj_append1 a₀ (g ⊚ f'₀) (λ x, q.P.W_map g (f₀ x))) = abs (q.P.obj_append1 a₁ (g ⊚ f'₁) (λ x, q.P.W_map g (f₁ x))), rw [←q.P.map_obj_append1, ←q.P.map_obj_append1, abs_map, abs_map, h] }, case mvqpf.Wequiv.trans : x y z e₁ e₂ ih₁ ih₂ { apply mvqpf.Wequiv.trans, apply ih₁, apply ih₂ } end /-- Define the fixed point as the quotient of trees under the equivalence relation. -/ def W_setoid (α : typevec n) : setoid (q.P.W α) := ⟨Wequiv, @Wequiv.refl _ _ _ _ _, @Wequiv.symm _ _ _ _ _, @Wequiv.trans _ _ _ _ _⟩ local attribute [instance] W_setoid /-- Least fixed point of functor F. The result is a functor with one fewer parameters than the input. For `F a b c` a ternary functor, fix F is a binary functor such that ```lean fix F a b = F a b (fix F a b) ``` -/ def fix {n : ℕ} (F : typevec (n+1) → Type*) [mvfunctor F] [q : mvqpf F] (α : typevec n) := quotient (W_setoid α : setoid (q.P.W α)) attribute [nolint has_nonempty_instance] fix /-- `fix F` is a functor -/ def fix.map {α β : typevec n} (g : α ⟹ β) : fix F α → fix F β := quotient.lift (λ x : q.P.W α, ⟦q.P.W_map g x⟧) (λ a b h, quot.sound (Wequiv_map _ _ _ h)) instance fix.mvfunctor : mvfunctor (fix F) := { map := @fix.map _ _ _ _} variable {α : typevec.{u} n} /-- Recursor for `fix F` -/ def fix.rec {β : Type u} (g : F (α ::: β) → β) : fix F α → β := quot.lift (recF g) (recF_eq_of_Wequiv α g) /-- Access W-type underlying `fix F` -/ def fix_to_W : fix F α → q.P.W α := quotient.lift Wrepr (recF_eq_of_Wequiv α (λ x, q.P.W_mk' (repr x))) /-- Constructor for `fix F` -/ def fix.mk (x : F (append1 α (fix F α))) : fix F α := quot.mk _ (q.P.W_mk' (append_fun id fix_to_W <$$> repr x)) /-- Destructor for `fix F` -/ def fix.dest : fix F α → F (append1 α (fix F α)) := fix.rec (mvfunctor.map (append_fun id fix.mk)) theorem fix.rec_eq {β : Type u} (g : F (append1 α β) → β) (x : F (append1 α (fix F α))) : fix.rec g (fix.mk x) = g (append_fun id (fix.rec g) <$$> x) := have recF g ∘ fix_to_W = fix.rec g, by { apply funext, apply quotient.ind, intro x, apply recF_eq_of_Wequiv, apply Wrepr_equiv }, begin conv { to_lhs, rw [fix.rec, fix.mk], dsimp }, cases h : repr x with a f, rw [mvpfunctor.map_eq, recF_eq', ←mvpfunctor.map_eq, mvpfunctor.W_dest'_W_mk'], rw [←mvpfunctor.comp_map, abs_map, ←h, abs_repr, ←append_fun_comp, id_comp, this] end theorem fix.ind_aux (a : q.P.A) (f' : q.P.drop.B a ⟹ α) (f : q.P.last.B a → q.P.W α) : fix.mk (abs ⟨a, q.P.append_contents f' (λ x, ⟦f x⟧)⟩) = ⟦q.P.W_mk a f' f⟧ := have fix.mk (abs ⟨a, q.P.append_contents f' (λ x, ⟦f x⟧)⟩) = ⟦Wrepr (q.P.W_mk a f' f)⟧, begin apply quot.sound, apply Wequiv.abs', rw [mvpfunctor.W_dest'_W_mk', abs_map, abs_repr, ←abs_map, mvpfunctor.map_eq], conv { to_rhs, rw [Wrepr_W_mk, q.P.W_dest'_W_mk', abs_repr, mvpfunctor.map_eq] }, congr' 2, rw [mvpfunctor.append_contents, mvpfunctor.append_contents], rw [append_fun, append_fun, ←split_fun_comp, ←split_fun_comp], reflexivity end, by { rw this, apply quot.sound, apply Wrepr_equiv } theorem fix.ind_rec {β : Type*} (g₁ g₂ : fix F α → β) (h : ∀ x : F (append1 α (fix F α)), (append_fun id g₁) <$$> x = (append_fun id g₂) <$$> x → g₁ (fix.mk x) = g₂ (fix.mk x)) : ∀ x, g₁ x = g₂ x := begin apply quot.ind, intro x, apply q.P.W_ind _ x, intros a f' f ih, show g₁ ⟦q.P.W_mk a f' f⟧ = g₂ ⟦q.P.W_mk a f' f⟧, rw [←fix.ind_aux a f' f], apply h, rw [←abs_map, ←abs_map, mvpfunctor.map_eq, mvpfunctor.map_eq], congr' 2, rw [mvpfunctor.append_contents, append_fun, append_fun, ←split_fun_comp, ←split_fun_comp], have : g₁ ∘ (λ x, ⟦f x⟧) = g₂ ∘ (λ x, ⟦f x⟧), { ext x, exact ih x }, rw this end theorem fix.rec_unique {β : Type*} (g : F (append1 α β) → β) (h : fix F α → β) (hyp : ∀ x, h (fix.mk x) = g (append_fun id h <$$> x)) : fix.rec g = h := begin ext x, apply fix.ind_rec, intros x hyp', rw [hyp, ←hyp', fix.rec_eq] end theorem fix.mk_dest (x : fix F α) : fix.mk (fix.dest x) = x := begin change (fix.mk ∘ fix.dest) x = x, apply fix.ind_rec, intro x, dsimp, rw [fix.dest, fix.rec_eq, ←comp_map, ←append_fun_comp, id_comp], intro h, rw h, show fix.mk (append_fun id id <$$> x) = fix.mk x, rw [append_fun_id_id, mvfunctor.id_map] end theorem fix.dest_mk (x : F (append1 α (fix F α))) : fix.dest (fix.mk x) = x := begin unfold fix.dest, rw [fix.rec_eq, ←fix.dest, ←comp_map], conv { to_rhs, rw ←(mvfunctor.id_map x) }, rw [←append_fun_comp, id_comp], have : fix.mk ∘ fix.dest = id, {ext x, apply fix.mk_dest }, rw [this, append_fun_id_id] end theorem fix.ind {α : typevec n} (p : fix F α → Prop) (h : ∀ x : F (α.append1 (fix F α)), liftp (pred_last α p) x → p (fix.mk x)) : ∀ x, p x := begin apply quot.ind, intro x, apply q.P.W_ind _ x, intros a f' f ih, change p ⟦q.P.W_mk a f' f⟧, rw [←fix.ind_aux a f' f], apply h, rw mvqpf.liftp_iff, refine ⟨_, _, rfl, _⟩, intros i j, cases i, { apply ih }, { trivial }, end instance mvqpf_fix : mvqpf (fix F) := { P := q.P.Wp, abs := λ α, quot.mk Wequiv, repr := λ α, fix_to_W, abs_repr := by { intros α, apply quot.ind, intro a, apply quot.sound, apply Wrepr_equiv }, abs_map := begin intros α β g x, conv { to_rhs, dsimp [mvfunctor.map]}, rw fix.map, apply quot.sound, apply Wequiv.refl end } /-- Dependent recursor for `fix F` -/ def fix.drec {β : fix F α → Type u} (g : Π x : F (α ::: sigma β), β (fix.mk $ (id ::: sigma.fst) <$$> x)) (x : fix F α) : β x := let y := @fix.rec _ F _ _ α (sigma β) (λ i, ⟨_,g i⟩) x in have x = y.1, by { symmetry, dsimp [y], apply fix.ind_rec _ id _ x, intros x' ih, rw fix.rec_eq, dsimp, simp [append_fun_id_id] at ih, congr, conv { to_rhs, rw [← ih] }, rw [mvfunctor.map_map,← append_fun_comp,id_comp], }, cast (by rw this) y.2 end mvqpf
1d7bcd6b66ac0788ca8a427b954516c143c1709e
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/order/filter/ultrafilter.lean
fba9849333928e2df65d15d95f94bda4620d64d9
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
17,080
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jeremy Avigad, Yury Kudryashov -/ import order.filter.cofinite import order.zorn_atoms /-! # Ultrafilters An ultrafilter is a minimal (maximal in the set order) proper filter. In this file we define * `ultrafilter.of`: an ultrafilter that is less than or equal to a given filter; * `ultrafilter`: subtype of ultrafilters; * `ultrafilter.pure`: `pure x` as an `ultrafiler`; * `ultrafilter.map`, `ultrafilter.bind`, `ultrafilter.comap` : operations on ultrafilters; * `hyperfilter`: the ultrafilter extending the cofinite filter. -/ universes u v variables {α : Type u} {β : Type v} {γ : Type*} open set filter function open_locale classical filter /-- `filter α` is an atomic type: for every filter there exists an ultrafilter that is less than or equal to this filter. -/ instance : is_atomic (filter α) := is_atomic.of_is_chain_bounded $ λ c hc hne hb, ⟨Inf c, (Inf_ne_bot_of_directed' hne (show is_chain (≥) c, from hc.symm).directed_on hb).ne, λ x hx, Inf_le hx⟩ /-- An ultrafilter is a minimal (maximal in the set order) proper filter. -/ @[protect_proj] structure ultrafilter (α : Type*) extends filter α := (ne_bot' : ne_bot to_filter) (le_of_le : ∀ g, filter.ne_bot g → g ≤ to_filter → to_filter ≤ g) namespace ultrafilter variables {f g : ultrafilter α} {s t : set α} {p q : α → Prop} instance : has_coe_t (ultrafilter α) (filter α) := ⟨ultrafilter.to_filter⟩ instance : has_mem (set α) (ultrafilter α) := ⟨λ s f, s ∈ (f : filter α)⟩ lemma unique (f : ultrafilter α) {g : filter α} (h : g ≤ f) (hne : ne_bot g . tactic.apply_instance) : g = f := le_antisymm h $ f.le_of_le g hne h instance ne_bot (f : ultrafilter α) : ne_bot (f : filter α) := f.ne_bot' protected lemma is_atom (f : ultrafilter α) : is_atom (f : filter α) := ⟨f.ne_bot.ne, λ g hgf, by_contra $ λ hg, hgf.ne $ f.unique hgf.le ⟨hg⟩⟩ @[simp, norm_cast] lemma mem_coe : s ∈ (f : filter α) ↔ s ∈ f := iff.rfl lemma coe_injective : injective (coe : ultrafilter α → filter α) | ⟨f, h₁, h₂⟩ ⟨g, h₃, h₄⟩ rfl := by congr lemma eq_of_le {f g : ultrafilter α} (h : (f : filter α) ≤ g) : f = g := coe_injective (g.unique h) @[simp, norm_cast] lemma coe_le_coe {f g : ultrafilter α} : (f : filter α) ≤ g ↔ f = g := ⟨λ h, eq_of_le h, λ h, h ▸ le_rfl⟩ @[simp, norm_cast] lemma coe_inj : (f : filter α) = g ↔ f = g := coe_injective.eq_iff @[ext] lemma ext ⦃f g : ultrafilter α⦄ (h : ∀ s, s ∈ f ↔ s ∈ g) : f = g := coe_injective $ filter.ext h lemma le_of_inf_ne_bot (f : ultrafilter α) {g : filter α} (hg : ne_bot (↑f ⊓ g)) : ↑f ≤ g := le_of_inf_eq (f.unique inf_le_left hg) lemma le_of_inf_ne_bot' (f : ultrafilter α) {g : filter α} (hg : ne_bot (g ⊓ f)) : ↑f ≤ g := f.le_of_inf_ne_bot $ by rwa inf_comm lemma inf_ne_bot_iff {f : ultrafilter α} {g : filter α} : ne_bot (↑f ⊓ g) ↔ ↑f ≤ g := ⟨le_of_inf_ne_bot f, λ h, (inf_of_le_left h).symm ▸ f.ne_bot⟩ lemma disjoint_iff_not_le {f : ultrafilter α} {g : filter α} : disjoint ↑f g ↔ ¬↑f ≤ g := by rw [← inf_ne_bot_iff, ne_bot_iff, ne.def, not_not, disjoint_iff] @[simp] lemma compl_not_mem_iff : sᶜ ∉ f ↔ s ∈ f := ⟨λ hsc, le_principal_iff.1 $ f.le_of_inf_ne_bot ⟨λ h, hsc $ mem_of_eq_bot$ by rwa compl_compl⟩, compl_not_mem⟩ @[simp] lemma frequently_iff_eventually : (∃ᶠ x in f, p x) ↔ ∀ᶠ x in f, p x := compl_not_mem_iff alias frequently_iff_eventually ↔ _root_.filter.frequently.eventually _ lemma compl_mem_iff_not_mem : sᶜ ∈ f ↔ s ∉ f := by rw [← compl_not_mem_iff, compl_compl] lemma diff_mem_iff (f : ultrafilter α) : s \ t ∈ f ↔ s ∈ f ∧ t ∉ f := inter_mem_iff.trans $ and_congr iff.rfl compl_mem_iff_not_mem /-- If `sᶜ ∉ f ↔ s ∈ f`, then `f` is an ultrafilter. The other implication is given by `ultrafilter.compl_not_mem_iff`. -/ def of_compl_not_mem_iff (f : filter α) (h : ∀ s, sᶜ ∉ f ↔ s ∈ f) : ultrafilter α := { to_filter := f, ne_bot' := ⟨λ hf, by simpa [hf] using h⟩, le_of_le := λ g hg hgf s hs, (h s).1 $ λ hsc, by exactI compl_not_mem hs (hgf hsc) } /-- If `f : filter α` is an atom, then it is an ultrafilter. -/ def of_atom (f : filter α) (hf : is_atom f) : ultrafilter α := { to_filter := f, ne_bot' := ⟨hf.1⟩, le_of_le := λ g hg, (_root_.is_atom_iff.1 hf).2 g hg.ne } lemma nonempty_of_mem (hs : s ∈ f) : s.nonempty := nonempty_of_mem hs lemma ne_empty_of_mem (hs : s ∈ f) : s ≠ ∅ := (nonempty_of_mem hs).ne_empty @[simp] lemma empty_not_mem : ∅ ∉ f := empty_not_mem f @[simp] lemma le_sup_iff {u : ultrafilter α} {f g : filter α} : ↑u ≤ f ⊔ g ↔ ↑u ≤ f ∨ ↑u ≤ g := not_iff_not.1 $ by simp only [← disjoint_iff_not_le, not_or_distrib, disjoint_sup_right] @[simp] lemma union_mem_iff : s ∪ t ∈ f ↔ s ∈ f ∨ t ∈ f := by simp only [← mem_coe, ← le_principal_iff, ← sup_principal, le_sup_iff] lemma mem_or_compl_mem (f : ultrafilter α) (s : set α) : s ∈ f ∨ sᶜ ∈ f := or_iff_not_imp_left.2 compl_mem_iff_not_mem.2 protected lemma em (f : ultrafilter α) (p : α → Prop) : (∀ᶠ x in f, p x) ∨ ∀ᶠ x in f, ¬p x := f.mem_or_compl_mem {x | p x} lemma eventually_or : (∀ᶠ x in f, p x ∨ q x) ↔ (∀ᶠ x in f, p x) ∨ ∀ᶠ x in f, q x := union_mem_iff lemma eventually_not : (∀ᶠ x in f, ¬p x) ↔ ¬∀ᶠ x in f, p x := compl_mem_iff_not_mem lemma eventually_imp : (∀ᶠ x in f, p x → q x) ↔ (∀ᶠ x in f, p x) → ∀ᶠ x in f, q x := by simp only [imp_iff_not_or, eventually_or, eventually_not] lemma finite_sUnion_mem_iff {s : set (set α)} (hs : s.finite) : ⋃₀ s ∈ f ↔ ∃t∈s, t ∈ f := finite.induction_on hs (by simp) $ λ a s ha hs his, by simp [union_mem_iff, his, or_and_distrib_right, exists_or_distrib] lemma finite_bUnion_mem_iff {is : set β} {s : β → set α} (his : is.finite) : (⋃i∈is, s i) ∈ f ↔ ∃i∈is, s i ∈ f := by simp only [← sUnion_image, finite_sUnion_mem_iff (his.image s), bex_image_iff] /-- Pushforward for ultrafilters. -/ def map (m : α → β) (f : ultrafilter α) : ultrafilter β := of_compl_not_mem_iff (map m f) $ λ s, @compl_not_mem_iff _ f (m ⁻¹' s) @[simp, norm_cast] lemma coe_map (m : α → β) (f : ultrafilter α) : (map m f : filter β) = filter.map m ↑f := rfl @[simp] lemma mem_map {m : α → β} {f : ultrafilter α} {s : set β} : s ∈ map m f ↔ m ⁻¹' s ∈ f := iff.rfl @[simp] lemma map_id (f : ultrafilter α) : f.map id = f := coe_injective map_id @[simp] lemma map_id' (f : ultrafilter α) : f.map (λ x, x) = f := map_id _ @[simp] lemma map_map (f : ultrafilter α) (m : α → β) (n : β → γ) : (f.map m).map n = f.map (n ∘ m) := coe_injective map_map /-- The pullback of an ultrafilter along an injection whose range is large with respect to the given ultrafilter. -/ def comap {m : α → β} (u : ultrafilter β) (inj : injective m) (large : set.range m ∈ u) : ultrafilter α := { to_filter := comap m u, ne_bot' := u.ne_bot'.comap_of_range_mem large, le_of_le := λ g hg hgu, by { resetI, simp only [← u.unique (map_le_iff_le_comap.2 hgu), comap_map inj, le_rfl] } } @[simp] lemma mem_comap {m : α → β} (u : ultrafilter β) (inj : injective m) (large : set.range m ∈ u) {s : set α} : s ∈ u.comap inj large ↔ m '' s ∈ u := mem_comap_iff inj large @[simp, norm_cast] lemma coe_comap {m : α → β} (u : ultrafilter β) (inj : injective m) (large : set.range m ∈ u) : (u.comap inj large : filter α) = filter.comap m u := rfl @[simp] lemma comap_id (f : ultrafilter α) (h₀ : injective (id : α → α) := injective_id) (h₁ : range id ∈ f := by { rw range_id, exact univ_mem}) : f.comap h₀ h₁ = f := coe_injective comap_id @[simp] lemma comap_comap (f : ultrafilter γ) {m : α → β} {n : β → γ} (inj₀ : injective n) (large₀ : range n ∈ f) (inj₁ : injective m) (large₁ : range m ∈ f.comap inj₀ large₀) (inj₂ : injective (n ∘ m) := inj₀.comp inj₁) (large₂ : range (n ∘ m) ∈ f := by { rw range_comp, exact image_mem_of_mem_comap large₀ large₁ }) : (f.comap inj₀ large₀).comap inj₁ large₁ = f.comap inj₂ large₂ := coe_injective comap_comap /-- The principal ultrafilter associated to a point `x`. -/ instance : has_pure ultrafilter := ⟨λ α a, of_compl_not_mem_iff (pure a) $ λ s, by simp⟩ @[simp] lemma mem_pure {a : α} {s : set α} : s ∈ (pure a : ultrafilter α) ↔ a ∈ s := iff.rfl @[simp] lemma coe_pure (a : α) : ↑(pure a : ultrafilter α) = (pure a : filter α) := rfl @[simp] lemma map_pure (m : α → β) (a : α) : map m (pure a) = pure (m a) := rfl @[simp] lemma comap_pure {m : α → β} (a : α) (inj : injective m) (large) : comap (pure $ m a) inj large = pure a := coe_injective $ comap_pure.trans $ by rw [coe_pure, ←principal_singleton, ←image_singleton, preimage_image_eq _ inj] lemma pure_injective : injective (pure : α → ultrafilter α) := λ a b h, filter.pure_injective (congr_arg ultrafilter.to_filter h : _) instance [inhabited α] : inhabited (ultrafilter α) := ⟨pure default⟩ instance [nonempty α] : nonempty (ultrafilter α) := nonempty.map pure infer_instance lemma eq_pure_of_finite_mem (h : s.finite) (h' : s ∈ f) : ∃ x ∈ s, f = pure x := begin rw ← bUnion_of_singleton s at h', rcases (ultrafilter.finite_bUnion_mem_iff h).mp h' with ⟨a, has, haf⟩, exact ⟨a, has, eq_of_le (filter.le_pure_iff.2 haf)⟩ end lemma eq_pure_of_finite [finite α] (f : ultrafilter α) : ∃ a, f = pure a := (eq_pure_of_finite_mem finite_univ univ_mem).imp $ λ a ⟨_, ha⟩, ha lemma le_cofinite_or_eq_pure (f : ultrafilter α) : (f : filter α) ≤ cofinite ∨ ∃ a, f = pure a := or_iff_not_imp_left.2 $ λ h, let ⟨s, hs, hfin⟩ := filter.disjoint_cofinite_right.1 (disjoint_iff_not_le.2 h), ⟨a, has, hf⟩ := eq_pure_of_finite_mem hfin hs in ⟨a, hf⟩ /-- Monadic bind for ultrafilters, coming from the one on filters defined in terms of map and join.-/ def bind (f : ultrafilter α) (m : α → ultrafilter β) : ultrafilter β := of_compl_not_mem_iff (bind ↑f (λ x, ↑(m x))) $ λ s, by simp only [mem_bind', mem_coe, ← compl_mem_iff_not_mem, compl_set_of, compl_compl] instance has_bind : has_bind ultrafilter := ⟨@ultrafilter.bind⟩ instance functor : functor ultrafilter := { map := @ultrafilter.map } instance monad : monad ultrafilter := { map := @ultrafilter.map } section local attribute [instance] filter.monad filter.is_lawful_monad instance is_lawful_monad : is_lawful_monad ultrafilter := { id_map := assume α f, coe_injective (id_map f.1), pure_bind := assume α β a f, coe_injective (pure_bind a (coe ∘ f)), bind_assoc := assume α β γ f m₁ m₂, coe_injective (filter_eq rfl), bind_pure_comp_eq_map := assume α β f x, coe_injective (bind_pure_comp_eq_map f x.1) } end /-- The ultrafilter lemma: Any proper filter is contained in an ultrafilter. -/ lemma exists_le (f : filter α) [h : ne_bot f] : ∃ u : ultrafilter α, ↑u ≤ f := let ⟨u, hu, huf⟩ := (eq_bot_or_exists_atom_le f).resolve_left h.ne in ⟨of_atom u hu, huf⟩ alias exists_le ← _root_.filter.exists_ultrafilter_le /-- Construct an ultrafilter extending a given filter. The ultrafilter lemma is the assertion that such a filter exists; we use the axiom of choice to pick one. -/ noncomputable def of (f : filter α) [ne_bot f] : ultrafilter α := classical.some (exists_le f) lemma of_le (f : filter α) [ne_bot f] : ↑(of f) ≤ f := classical.some_spec (exists_le f) lemma of_coe (f : ultrafilter α) : of ↑f = f := coe_inj.1 $ f.unique (of_le f) lemma exists_ultrafilter_of_finite_inter_nonempty (S : set (set α)) (cond : ∀ T : finset (set α), (↑T : set (set α)) ⊆ S → (⋂₀ (↑T : set (set α))).nonempty) : ∃ F : ultrafilter α, S ⊆ F.sets := begin haveI : ne_bot (generate S) := generate_ne_bot_iff.2 (λ t hts ht, ht.coe_to_finset ▸ cond ht.to_finset (ht.coe_to_finset.symm ▸ hts)), exact ⟨of (generate S), λ t ht, (of_le $ generate S) $ generate_sets.basic ht⟩ end end ultrafilter namespace filter variables {f : filter α} {s : set α} {a : α} open ultrafilter lemma is_atom_pure : is_atom (pure a : filter α) := (pure a : ultrafilter α).is_atom protected lemma ne_bot.le_pure_iff (hf : f.ne_bot) : f ≤ pure a ↔ f = pure a := ⟨ultrafilter.unique (pure a), le_of_eq⟩ @[simp] lemma lt_pure_iff : f < pure a ↔ f = ⊥ := is_atom_pure.lt_iff lemma le_pure_iff' : f ≤ pure a ↔ f = ⊥ ∨ f = pure a := is_atom_pure.le_iff @[simp] lemma Iic_pure (a : α) : Iic (pure a : filter α) = {⊥, pure a} := is_atom_pure.Iic_eq lemma mem_iff_ultrafilter : s ∈ f ↔ ∀ g : ultrafilter α, ↑g ≤ f → s ∈ g := begin refine ⟨λ hf g hg, hg hf, λ H, by_contra $ λ hf, _⟩, set g : filter ↥sᶜ := comap coe f, haveI : ne_bot g := comap_ne_bot_iff_compl_range.2 (by simpa [compl_set_of]), simpa using H ((of g).map coe) (map_le_iff_le_comap.mpr (of_le g)) end lemma le_iff_ultrafilter {f₁ f₂ : filter α} : f₁ ≤ f₂ ↔ ∀ g : ultrafilter α, ↑g ≤ f₁ → ↑g ≤ f₂ := ⟨λ h g h₁, h₁.trans h, λ h s hs, mem_iff_ultrafilter.2 $ λ g hg, h g hg hs⟩ /-- A filter equals the intersection of all the ultrafilters which contain it. -/ lemma supr_ultrafilter_le_eq (f : filter α) : (⨆ (g : ultrafilter α) (hg : ↑g ≤ f), (g : filter α)) = f := eq_of_forall_ge_iff $ λ f', by simp only [supr_le_iff, ← le_iff_ultrafilter] /-- The `tendsto` relation can be checked on ultrafilters. -/ lemma tendsto_iff_ultrafilter (f : α → β) (l₁ : filter α) (l₂ : filter β) : tendsto f l₁ l₂ ↔ ∀ g : ultrafilter α, ↑g ≤ l₁ → tendsto f g l₂ := by simpa only [tendsto_iff_comap] using le_iff_ultrafilter lemma exists_ultrafilter_iff {f : filter α} : (∃ (u : ultrafilter α), ↑u ≤ f) ↔ ne_bot f := ⟨λ ⟨u, uf⟩, ne_bot_of_le uf, λ h, @exists_ultrafilter_le _ _ h⟩ lemma forall_ne_bot_le_iff {g : filter α} {p : filter α → Prop} (hp : monotone p) : (∀ f : filter α, ne_bot f → f ≤ g → p f) ↔ ∀ f : ultrafilter α, ↑f ≤ g → p f := begin refine ⟨λ H f hf, H f f.ne_bot hf, _⟩, introsI H f hf hfg, exact hp (of_le f) (H _ ((of_le f).trans hfg)) end section hyperfilter variables (α) [infinite α] /-- The ultrafilter extending the cofinite filter. -/ noncomputable def hyperfilter : ultrafilter α := ultrafilter.of cofinite variable {α} lemma hyperfilter_le_cofinite : ↑(hyperfilter α) ≤ @cofinite α := ultrafilter.of_le cofinite @[simp] lemma bot_ne_hyperfilter : (⊥ : filter α) ≠ hyperfilter α := (by apply_instance : ne_bot ↑(hyperfilter α)).1.symm theorem nmem_hyperfilter_of_finite {s : set α} (hf : s.finite) : s ∉ hyperfilter α := λ hy, compl_not_mem hy $ hyperfilter_le_cofinite hf.compl_mem_cofinite alias nmem_hyperfilter_of_finite ← _root_.set.finite.nmem_hyperfilter theorem compl_mem_hyperfilter_of_finite {s : set α} (hf : set.finite s) : sᶜ ∈ hyperfilter α := compl_mem_iff_not_mem.2 hf.nmem_hyperfilter alias compl_mem_hyperfilter_of_finite ← _root_.set.finite.compl_mem_hyperfilter theorem mem_hyperfilter_of_finite_compl {s : set α} (hf : set.finite sᶜ) : s ∈ hyperfilter α := compl_compl s ▸ hf.compl_mem_hyperfilter end hyperfilter end filter namespace ultrafilter open filter variables {m : α → β} {s : set α} {g : ultrafilter β} lemma comap_inf_principal_ne_bot_of_image_mem (h : m '' s ∈ g) : (filter.comap m g ⊓ 𝓟 s).ne_bot := filter.comap_inf_principal_ne_bot_of_image_mem g.ne_bot h /-- Ultrafilter extending the inf of a comapped ultrafilter and a principal ultrafilter. -/ noncomputable def of_comap_inf_principal (h : m '' s ∈ g) : ultrafilter α := @of _ (filter.comap m g ⊓ 𝓟 s) (comap_inf_principal_ne_bot_of_image_mem h) lemma of_comap_inf_principal_mem (h : m '' s ∈ g) : s ∈ of_comap_inf_principal h := begin let f := filter.comap m g ⊓ 𝓟 s, haveI : f.ne_bot := comap_inf_principal_ne_bot_of_image_mem h, have : s ∈ f := mem_inf_of_right (mem_principal_self s), exact le_def.mp (of_le _) s this end lemma of_comap_inf_principal_eq_of_map (h : m '' s ∈ g) : (of_comap_inf_principal h).map m = g := begin let f := filter.comap m g ⊓ 𝓟 s, haveI : f.ne_bot := comap_inf_principal_ne_bot_of_image_mem h, apply eq_of_le, calc filter.map m (of f) ≤ filter.map m f : map_mono (of_le _) ... ≤ (filter.map m $ filter.comap m g) ⊓ filter.map m (𝓟 s) : map_inf_le ... = (filter.map m $ filter.comap m g) ⊓ (𝓟 $ m '' s) : by rw map_principal ... ≤ g ⊓ (𝓟 $ m '' s) : inf_le_inf_right _ map_comap_le ... = g : inf_of_le_left (le_principal_iff.mpr h) end end ultrafilter
8989f3245daf932e273a85f4cdb9d8def2b657b5
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/ring_theory/roots_of_unity.lean
34227ce168ade13463e87461b0f1bd925aefcbdc
[ "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
46,989
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import algebra.char_p.two import algebra.ne_zero import data.polynomial.ring_division import field_theory.finite.basic import field_theory.separable import group_theory.specific_groups.cyclic import number_theory.divisors import ring_theory.integral_domain import tactic.zify /-! # Roots of unity and primitive roots of unity We define roots of unity in the context of an arbitrary commutative monoid, as a subgroup of the group of units. We also define a predicate `is_primitive_root` on commutative monoids, expressing that an element is a primitive root of unity. ## Main definitions * `roots_of_unity n M`, for `n : ℕ+` is the subgroup of the units of a commutative monoid `M` consisting of elements `x` that satisfy `x ^ n = 1`. * `is_primitive_root ζ k`: an element `ζ` is a primitive `k`-th root of unity if `ζ ^ k = 1`, and if `l` satisfies `ζ ^ l = 1` then `k ∣ l`. * `primitive_roots k R`: the finset of primitive `k`-th roots of unity in an integral domain `R`. * `is_primitive_root.aut_to_pow`: the monoid hom that takes an automorphism of a ring to the power it sends that specific primitive root, as a member of `(zmod n)ˣ`. ## Main results * `roots_of_unity.is_cyclic`: the roots of unity in an integral domain form a cyclic group. * `is_primitive_root.zmod_equiv_zpowers`: `zmod k` is equivalent to the subgroup generated by a primitive `k`-th root of unity. * `is_primitive_root.zpowers_eq`: in an integral domain, the subgroup generated by a primitive `k`-th root of unity is equal to the `k`-th roots of unity. * `is_primitive_root.card_primitive_roots`: if an integral domain has a primitive `k`-th root of unity, then it has `φ k` of them. ## Implementation details It is desirable that `roots_of_unity` is a subgroup, and it will mainly be applied to rings (e.g. the ring of integers in a number field) and fields. We therefore implement it as a subgroup of the units of a commutative monoid. We have chosen to define `roots_of_unity n` for `n : ℕ+`, instead of `n : ℕ`, because almost all lemmas need the positivity assumption, and in particular the type class instances for `fintype` and `is_cyclic`. On the other hand, for primitive roots of unity, it is desirable to have a predicate not just on units, but directly on elements of the ring/field. For example, we want to say that `exp (2 * pi * I / n)` is a primitive `n`-th root of unity in the complex numbers, without having to turn that number into a unit first. This creates a little bit of friction, but lemmas like `is_primitive_root.is_unit` and `is_primitive_root.coe_units_iff` should provide the necessary glue. -/ open_locale classical big_operators polynomial noncomputable theory open polynomial open finset variables {M N G R S F : Type*} variables [comm_monoid M] [comm_monoid N] [division_comm_monoid G] section roots_of_unity variables {k l : ℕ+} /-- `roots_of_unity k M` is the subgroup of elements `m : Mˣ` that satisfy `m ^ k = 1` -/ def roots_of_unity (k : ℕ+) (M : Type*) [comm_monoid M] : subgroup Mˣ := { carrier := { ζ | ζ ^ (k : ℕ) = 1 }, one_mem' := one_pow _, mul_mem' := λ ζ ξ hζ hξ, by simp only [*, set.mem_set_of_eq, mul_pow, one_mul] at *, inv_mem' := λ ζ hζ, by simp only [*, set.mem_set_of_eq, inv_pow, inv_one] at * } @[simp] lemma mem_roots_of_unity (k : ℕ+) (ζ : Mˣ) : ζ ∈ roots_of_unity k M ↔ ζ ^ (k : ℕ) = 1 := iff.rfl lemma mem_roots_of_unity' (k : ℕ+) (ζ : Mˣ) : ζ ∈ roots_of_unity k M ↔ (ζ : M) ^ (k : ℕ) = 1 := by { rw [mem_roots_of_unity], norm_cast } lemma roots_of_unity.coe_injective {n : ℕ+} : function.injective (coe : (roots_of_unity n M) → M) := units.ext.comp (λ x y, subtype.ext) /-- Make an element of `roots_of_unity` from a member of the base ring, and a proof that it has a positive power equal to one. -/ @[simps coe_coe] def roots_of_unity.mk_of_pow_eq (ζ : M) {n : ℕ+} (h : ζ ^ (n : ℕ) = 1) : roots_of_unity n M := ⟨units.mk_of_mul_eq_one ζ (ζ ^ n.nat_pred) $ by rwa [←pow_one ζ, ←pow_mul, ←pow_add, one_mul, pnat.one_add_nat_pred], units.ext $ by simpa⟩ @[simp] lemma roots_of_unity.coe_mk_of_pow_eq {ζ : M} {n : ℕ+} (h : ζ ^ (n : ℕ) = 1) : (roots_of_unity.mk_of_pow_eq _ h : M) = ζ := rfl lemma roots_of_unity_le_of_dvd (h : k ∣ l) : roots_of_unity k M ≤ roots_of_unity l M := begin obtain ⟨d, rfl⟩ := h, intros ζ h, simp only [mem_roots_of_unity, pnat.mul_coe, pow_mul, one_pow, *] at *, end lemma map_roots_of_unity (f : Mˣ →* Nˣ) (k : ℕ+) : (roots_of_unity k M).map f ≤ roots_of_unity k N := begin rintros _ ⟨ζ, h, rfl⟩, simp only [←map_pow, *, mem_roots_of_unity, set_like.mem_coe, monoid_hom.map_one] at * end @[norm_cast] lemma roots_of_unity.coe_pow [comm_monoid R] (ζ : roots_of_unity k R) (m : ℕ) : ↑(ζ ^ m) = (ζ ^ m : R) := begin change ↑(↑(ζ ^ m) : Rˣ) = ↑(ζ : Rˣ) ^ m, rw [subgroup.coe_pow, units.coe_pow], end section comm_semiring variables [comm_semiring R] [comm_semiring S] /-- Restrict a ring homomorphism to the nth roots of unity -/ def restrict_roots_of_unity [ring_hom_class F R S] (σ : F) (n : ℕ+) : roots_of_unity n R →* roots_of_unity n S := let h : ∀ ξ : roots_of_unity n R, (σ ξ) ^ (n : ℕ) = 1 := λ ξ, by { change (σ (ξ : Rˣ)) ^ (n : ℕ) = 1, rw [←map_pow, ←units.coe_pow, show ((ξ : Rˣ) ^ (n : ℕ) = 1), from ξ.2, units.coe_one, map_one σ] } in { to_fun := λ ξ, ⟨@unit_of_invertible _ _ _ (invertible_of_pow_eq_one _ _ (h ξ) n.2), by { ext, rw units.coe_pow, exact h ξ }⟩, map_one' := by { ext, exact map_one σ }, map_mul' := λ ξ₁ ξ₂, by { ext, rw [subgroup.coe_mul, units.coe_mul], exact map_mul σ _ _ } } @[simp] lemma restrict_roots_of_unity_coe_apply [ring_hom_class F R S] (σ : F) (ζ : roots_of_unity k R) : ↑(restrict_roots_of_unity σ k ζ) = σ ↑ζ := rfl /-- Restrict a ring isomorphism to the nth roots of unity -/ def ring_equiv.restrict_roots_of_unity (σ : R ≃+* S) (n : ℕ+) : roots_of_unity n R ≃* roots_of_unity n S := { to_fun := restrict_roots_of_unity σ.to_ring_hom n, inv_fun :=restrict_roots_of_unity σ.symm.to_ring_hom n, left_inv := λ ξ, by { ext, exact σ.symm_apply_apply ξ }, right_inv := λ ξ, by { ext, exact σ.apply_symm_apply ξ }, map_mul' := (restrict_roots_of_unity _ n).map_mul } @[simp] lemma ring_equiv.restrict_roots_of_unity_coe_apply (σ : R ≃+* S) (ζ : roots_of_unity k R) : ↑(σ.restrict_roots_of_unity k ζ) = σ ↑ζ := rfl @[simp] lemma ring_equiv.restrict_roots_of_unity_symm (σ : R ≃+* S) : (σ.restrict_roots_of_unity k).symm = σ.symm.restrict_roots_of_unity k := rfl end comm_semiring section is_domain variables [comm_ring R] [is_domain R] lemma mem_roots_of_unity_iff_mem_nth_roots {ζ : Rˣ} : ζ ∈ roots_of_unity k R ↔ (ζ : R) ∈ nth_roots k (1 : R) := by simp only [mem_roots_of_unity, mem_nth_roots k.pos, units.ext_iff, units.coe_one, units.coe_pow] variables (k R) /-- Equivalence between the `k`-th roots of unity in `R` and the `k`-th roots of `1`. This is implemented as equivalence of subtypes, because `roots_of_unity` is a subgroup of the group of units, whereas `nth_roots` is a multiset. -/ def roots_of_unity_equiv_nth_roots : roots_of_unity k R ≃ {x // x ∈ nth_roots k (1 : R)} := begin refine { to_fun := λ x, ⟨x, mem_roots_of_unity_iff_mem_nth_roots.mp x.2⟩, inv_fun := λ x, ⟨⟨x, x ^ (k - 1 : ℕ), _, _⟩, _⟩, left_inv := _, right_inv := _ }, swap 4, { rintro ⟨x, hx⟩, ext, refl }, swap 4, { rintro ⟨x, hx⟩, ext, refl }, all_goals { rcases x with ⟨x, hx⟩, rw [mem_nth_roots k.pos] at hx, simp only [subtype.coe_mk, ← pow_succ, ← pow_succ', hx, tsub_add_cancel_of_le (show 1 ≤ (k : ℕ), from k.one_le)] }, { show (_ : Rˣ) ^ (k : ℕ) = 1, simp only [units.ext_iff, hx, units.coe_mk, units.coe_one, subtype.coe_mk, units.coe_pow] } end variables {k R} @[simp] lemma roots_of_unity_equiv_nth_roots_apply (x : roots_of_unity k R) : (roots_of_unity_equiv_nth_roots R k x : R) = x := rfl @[simp] lemma roots_of_unity_equiv_nth_roots_symm_apply (x : {x // x ∈ nth_roots k (1 : R)}) : ((roots_of_unity_equiv_nth_roots R k).symm x : R) = x := rfl variables (k R) instance roots_of_unity.fintype : fintype (roots_of_unity k R) := fintype.of_equiv {x // x ∈ nth_roots k (1 : R)} $ (roots_of_unity_equiv_nth_roots R k).symm instance roots_of_unity.is_cyclic : is_cyclic (roots_of_unity k R) := is_cyclic_of_subgroup_is_domain ((units.coe_hom R).comp (roots_of_unity k R).subtype) (units.ext.comp subtype.val_injective) lemma card_roots_of_unity : fintype.card (roots_of_unity k R) ≤ k := calc fintype.card (roots_of_unity k R) = fintype.card {x // x ∈ nth_roots k (1 : R)} : fintype.card_congr (roots_of_unity_equiv_nth_roots R k) ... ≤ (nth_roots k (1 : R)).attach.card : multiset.card_le_of_le (multiset.dedup_le _) ... = (nth_roots k (1 : R)).card : multiset.card_attach ... ≤ k : card_nth_roots k 1 variables {k R} lemma map_root_of_unity_eq_pow_self [ring_hom_class F R R] (σ : F) (ζ : roots_of_unity k R) : ∃ m : ℕ, σ ζ = ζ ^ m := begin obtain ⟨m, hm⟩ := monoid_hom.map_cyclic (restrict_roots_of_unity σ k), rw [←restrict_roots_of_unity_coe_apply, hm, zpow_eq_mod_order_of, ←int.to_nat_of_nonneg (m.mod_nonneg (int.coe_nat_ne_zero.mpr (pos_iff_ne_zero.mp (order_of_pos ζ)))), zpow_coe_nat, roots_of_unity.coe_pow], exact ⟨(m % (order_of ζ)).to_nat, rfl⟩, end end is_domain section reduced variables (R) [comm_ring R] [is_reduced R] @[simp] lemma mem_roots_of_unity_prime_pow_mul_iff (p k : ℕ) (m : ℕ+) [hp : fact p.prime] [char_p R p] {ζ : Rˣ} : ζ ∈ roots_of_unity (⟨p, hp.1.pos⟩ ^ k * m) R ↔ ζ ∈ roots_of_unity m R := by simp [mem_roots_of_unity'] end reduced end roots_of_unity /-- An element `ζ` is a primitive `k`-th root of unity if `ζ ^ k = 1`, and if `l` satisfies `ζ ^ l = 1` then `k ∣ l`. -/ structure is_primitive_root (ζ : M) (k : ℕ) : Prop := (pow_eq_one : ζ ^ (k : ℕ) = 1) (dvd_of_pow_eq_one : ∀ l : ℕ, ζ ^ l = 1 → k ∣ l) /-- Turn a primitive root μ into a member of the `roots_of_unity` subgroup. -/ @[simps] def is_primitive_root.to_roots_of_unity {μ : M} {n : ℕ+} (h : is_primitive_root μ n) : roots_of_unity n M := roots_of_unity.mk_of_pow_eq μ h.pow_eq_one section primitive_roots variables {k : ℕ} /-- `primitive_roots k R` is the finset of primitive `k`-th roots of unity in the integral domain `R`. -/ def primitive_roots (k : ℕ) (R : Type*) [comm_ring R] [is_domain R] : finset R := (nth_roots k (1 : R)).to_finset.filter (λ ζ, is_primitive_root ζ k) variables [comm_ring R] [is_domain R] @[simp] lemma mem_primitive_roots {ζ : R} (h0 : 0 < k) : ζ ∈ primitive_roots k R ↔ is_primitive_root ζ k := begin rw [primitive_roots, mem_filter, multiset.mem_to_finset, mem_nth_roots h0, and_iff_right_iff_imp], exact is_primitive_root.pow_eq_one end end primitive_roots namespace is_primitive_root variables {k l : ℕ} lemma iff_def (ζ : M) (k : ℕ) : is_primitive_root ζ k ↔ (ζ ^ k = 1) ∧ (∀ l : ℕ, ζ ^ l = 1 → k ∣ l) := ⟨λ ⟨h1, h2⟩, ⟨h1, h2⟩, λ ⟨h1, h2⟩, ⟨h1, h2⟩⟩ lemma mk_of_lt (ζ : M) (hk : 0 < k) (h1 : ζ ^ k = 1) (h : ∀ l : ℕ, 0 < l → l < k → ζ ^ l ≠ 1) : is_primitive_root ζ k := begin refine ⟨h1, _⟩, intros l hl, apply dvd_trans _ (k.gcd_dvd_right l), suffices : k.gcd l = k, { rw this }, rw eq_iff_le_not_lt, refine ⟨nat.le_of_dvd hk (k.gcd_dvd_left l), _⟩, intro h', apply h _ (nat.gcd_pos_of_pos_left _ hk) h', exact pow_gcd_eq_one _ h1 hl end section comm_monoid variables {ζ : M} {f : F} (h : is_primitive_root ζ k) @[nontriviality] lemma of_subsingleton [subsingleton M] (x : M) : is_primitive_root x 1 := ⟨subsingleton.elim _ _, λ _ _, one_dvd _⟩ lemma pow_eq_one_iff_dvd (l : ℕ) : ζ ^ l = 1 ↔ k ∣ l := ⟨h.dvd_of_pow_eq_one l, by { rintro ⟨i, rfl⟩, simp only [pow_mul, h.pow_eq_one, one_pow, pnat.mul_coe] }⟩ lemma is_unit (h : is_primitive_root ζ k) (h0 : 0 < k) : is_unit ζ := begin apply is_unit_of_mul_eq_one ζ (ζ ^ (k - 1)), rw [← pow_succ, tsub_add_cancel_of_le h0.nat_succ_le, h.pow_eq_one] end lemma pow_ne_one_of_pos_of_lt (h0 : 0 < l) (hl : l < k) : ζ ^ l ≠ 1 := mt (nat.le_of_dvd h0 ∘ h.dvd_of_pow_eq_one _) $ not_le_of_lt hl lemma pow_inj (h : is_primitive_root ζ k) ⦃i j : ℕ⦄ (hi : i < k) (hj : j < k) (H : ζ ^ i = ζ ^ j) : i = j := begin wlog hij : i ≤ j, apply le_antisymm hij, rw ← tsub_eq_zero_iff_le, apply nat.eq_zero_of_dvd_of_lt _ (lt_of_le_of_lt tsub_le_self hj), apply h.dvd_of_pow_eq_one, rw [← ((h.is_unit (lt_of_le_of_lt (nat.zero_le _) hi)).pow i).mul_left_inj, ← pow_add, tsub_add_cancel_of_le hij, H, one_mul] end lemma one : is_primitive_root (1 : M) 1 := { pow_eq_one := pow_one _, dvd_of_pow_eq_one := λ l hl, one_dvd _ } @[simp] lemma one_right_iff : is_primitive_root ζ 1 ↔ ζ = 1 := begin split, { intro h, rw [← pow_one ζ, h.pow_eq_one] }, { rintro rfl, exact one } end @[simp] lemma coe_submonoid_class_iff {M B : Type*} [comm_monoid M] [set_like B M] [submonoid_class B M] {N : B} {ζ : N} : is_primitive_root (ζ : M) k ↔ is_primitive_root ζ k := by simp [iff_def, ← submonoid_class.coe_pow] @[simp] lemma coe_units_iff {ζ : Mˣ} : is_primitive_root (ζ : M) k ↔ is_primitive_root ζ k := by simp only [iff_def, units.ext_iff, units.coe_pow, units.coe_one] lemma pow_of_coprime (h : is_primitive_root ζ k) (i : ℕ) (hi : i.coprime k) : is_primitive_root (ζ ^ i) k := begin by_cases h0 : k = 0, { subst k, simp only [*, pow_one, nat.coprime_zero_right] at * }, rcases h.is_unit (nat.pos_of_ne_zero h0) with ⟨ζ, rfl⟩, rw [← units.coe_pow], rw coe_units_iff at h ⊢, refine { pow_eq_one := by rw [← pow_mul', pow_mul, h.pow_eq_one, one_pow], dvd_of_pow_eq_one := _ }, intros l hl, apply h.dvd_of_pow_eq_one, rw [← pow_one ζ, ← zpow_coe_nat ζ, ← hi.gcd_eq_one, nat.gcd_eq_gcd_ab, zpow_add, mul_pow, ← zpow_coe_nat, ← zpow_mul, mul_right_comm], simp only [zpow_mul, hl, h.pow_eq_one, one_zpow, one_pow, one_mul, zpow_coe_nat] end lemma pow_of_prime (h : is_primitive_root ζ k) {p : ℕ} (hprime : nat.prime p) (hdiv : ¬ p ∣ k) : is_primitive_root (ζ ^ p) k := h.pow_of_coprime p (hprime.coprime_iff_not_dvd.2 hdiv) lemma pow_iff_coprime (h : is_primitive_root ζ k) (h0 : 0 < k) (i : ℕ) : is_primitive_root (ζ ^ i) k ↔ i.coprime k := begin refine ⟨_, h.pow_of_coprime i⟩, intro hi, obtain ⟨a, ha⟩ := i.gcd_dvd_left k, obtain ⟨b, hb⟩ := i.gcd_dvd_right k, suffices : b = k, { rwa [this, ← one_mul k, nat.mul_left_inj h0, eq_comm] at hb { occs := occurrences.pos [1] } }, rw [ha] at hi, rw [mul_comm] at hb, apply nat.dvd_antisymm ⟨i.gcd k, hb⟩ (hi.dvd_of_pow_eq_one b _), rw [← pow_mul', ← mul_assoc, ← hb, pow_mul, h.pow_eq_one, one_pow] end protected lemma order_of (ζ : M) : is_primitive_root ζ (order_of ζ) := ⟨pow_order_of_eq_one ζ, λ l, order_of_dvd_of_pow_eq_one⟩ lemma unique {ζ : M} (hk : is_primitive_root ζ k) (hl : is_primitive_root ζ l) : k = l := begin wlog hkl : k ≤ l, rcases hkl.eq_or_lt with rfl | hkl, { refl }, rcases k.eq_zero_or_pos with rfl | hk', { exact (zero_dvd_iff.mp $ hk.dvd_of_pow_eq_one l hl.pow_eq_one).symm }, exact absurd hk.pow_eq_one (hl.pow_ne_one_of_pos_of_lt hk' hkl) end lemma eq_order_of : k = order_of ζ := h.unique (is_primitive_root.order_of ζ) protected lemma iff (hk : 0 < k) : is_primitive_root ζ k ↔ ζ ^ k = 1 ∧ ∀ l : ℕ, 0 < l → l < k → ζ ^ l ≠ 1 := begin refine ⟨λ h, ⟨h.pow_eq_one, λ l hl' hl, _⟩, λ ⟨hζ, hl⟩, is_primitive_root.mk_of_lt ζ hk hζ hl⟩, rw h.eq_order_of at hl, exact pow_ne_one_of_lt_order_of' hl'.ne' hl, end protected lemma not_iff : ¬ is_primitive_root ζ k ↔ order_of ζ ≠ k := ⟨λ h hk, h $ hk ▸ is_primitive_root.order_of ζ, λ h hk, h.symm $ hk.unique $ is_primitive_root.order_of ζ⟩ lemma pow_of_dvd (h : is_primitive_root ζ k) {p : ℕ} (hp : p ≠ 0) (hdiv : p ∣ k) : is_primitive_root (ζ ^ p) (k / p) := begin suffices : order_of (ζ ^ p) = k / p, { exact this ▸ is_primitive_root.order_of (ζ ^ p) }, rw [order_of_pow' _ hp, ← eq_order_of h, nat.gcd_eq_right hdiv] end protected lemma mem_roots_of_unity {ζ : Mˣ} {n : ℕ+} (h : is_primitive_root ζ n) : ζ ∈ roots_of_unity n M := h.pow_eq_one /-- If there is a `n`-th primitive root of unity in `R` and `b` divides `n`, then there is a `b`-th primitive root of unity in `R`. -/ lemma pow {n : ℕ} {a b : ℕ} (hn : 0 < n) (h : is_primitive_root ζ n) (hprod : n = a * b) : is_primitive_root (ζ ^ a) b := begin subst n, simp only [iff_def, ← pow_mul, h.pow_eq_one, eq_self_iff_true, true_and], intros l hl, have ha0 : a ≠ 0, { rintro rfl, simpa only [nat.not_lt_zero, zero_mul] using hn }, rwa ← mul_dvd_mul_iff_left ha0, exact h.dvd_of_pow_eq_one _ hl end section maps open function lemma map_of_injective [monoid_hom_class F M N] (h : is_primitive_root ζ k) (hf : injective f) : is_primitive_root (f ζ) k := { pow_eq_one := by rw [←map_pow, h.pow_eq_one, _root_.map_one], dvd_of_pow_eq_one := begin rw h.eq_order_of, intros l hl, rw [←map_pow, ←map_one f] at hl, exact order_of_dvd_of_pow_eq_one (hf hl) end } lemma of_map_of_injective [monoid_hom_class F M N] (h : is_primitive_root (f ζ) k) (hf : injective f) : is_primitive_root ζ k := { pow_eq_one := by { apply_fun f, rw [map_pow, _root_.map_one, h.pow_eq_one] }, dvd_of_pow_eq_one := begin rw h.eq_order_of, intros l hl, apply_fun f at hl, rw [map_pow, _root_.map_one] at hl, exact order_of_dvd_of_pow_eq_one hl end } lemma map_iff_of_injective [monoid_hom_class F M N] (hf : injective f) : is_primitive_root (f ζ) k ↔ is_primitive_root ζ k := ⟨λ h, h.of_map_of_injective hf, λ h, h.map_of_injective hf⟩ end maps end comm_monoid section comm_monoid_with_zero variables {M₀ : Type*} [comm_monoid_with_zero M₀] lemma zero [nontrivial M₀] : is_primitive_root (0 : M₀) 0 := ⟨pow_zero 0, λ l hl, by simpa [zero_pow_eq, show ∀ p, ¬p → false ↔ p, from @not_not] using hl⟩ protected lemma ne_zero [nontrivial M₀] {ζ : M₀} (h : is_primitive_root ζ k) : k ≠ 0 → ζ ≠ 0 := mt $ λ hn, h.unique (hn.symm ▸ is_primitive_root.zero) end comm_monoid_with_zero section division_comm_monoid variables {ζ : G} lemma zpow_eq_one (h : is_primitive_root ζ k) : ζ ^ (k : ℤ) = 1 := by { rw zpow_coe_nat, exact h.pow_eq_one } lemma zpow_eq_one_iff_dvd (h : is_primitive_root ζ k) (l : ℤ) : ζ ^ l = 1 ↔ (k : ℤ) ∣ l := begin by_cases h0 : 0 ≤ l, { lift l to ℕ using h0, rw [zpow_coe_nat], norm_cast, exact h.pow_eq_one_iff_dvd l }, { have : 0 ≤ -l, { simp only [not_le, neg_nonneg] at h0 ⊢, exact le_of_lt h0 }, lift -l to ℕ using this with l' hl', rw [← dvd_neg, ← hl'], norm_cast, rw [← h.pow_eq_one_iff_dvd, ← inv_inj, ← zpow_neg, ← hl', zpow_coe_nat, inv_one] } end lemma inv (h : is_primitive_root ζ k) : is_primitive_root ζ⁻¹ k := { pow_eq_one := by simp only [h.pow_eq_one, inv_one, eq_self_iff_true, inv_pow], dvd_of_pow_eq_one := begin intros l hl, apply h.dvd_of_pow_eq_one l, rw [← inv_inj, ← inv_pow, hl, inv_one] end } @[simp] lemma inv_iff : is_primitive_root ζ⁻¹ k ↔ is_primitive_root ζ k := by { refine ⟨_, λ h, inv h⟩, intro h, rw [← inv_inv ζ], exact inv h } lemma zpow_of_gcd_eq_one (h : is_primitive_root ζ k) (i : ℤ) (hi : i.gcd k = 1) : is_primitive_root (ζ ^ i) k := begin by_cases h0 : 0 ≤ i, { lift i to ℕ using h0, rw zpow_coe_nat, exact h.pow_of_coprime i hi }, have : 0 ≤ -i, { simp only [not_le, neg_nonneg] at h0 ⊢, exact le_of_lt h0 }, lift -i to ℕ using this with i' hi', rw [← inv_iff, ← zpow_neg, ← hi', zpow_coe_nat], apply h.pow_of_coprime, rw [int.gcd, ← int.nat_abs_neg, ← hi'] at hi, exact hi end end division_comm_monoid section is_domain variables {ζ : R} variables [comm_ring R] [is_domain R] @[simp] lemma primitive_roots_zero : primitive_roots 0 R = ∅ := begin rw [← finset.val_eq_zero, ← multiset.subset_zero, ← nth_roots_zero (1 : R), primitive_roots], simp only [finset.not_mem_empty, forall_const, forall_prop_of_false, multiset.to_finset_zero, finset.filter_true_of_mem, finset.empty_val, not_false_iff, multiset.zero_subset, nth_roots_zero] end @[simp] lemma primitive_roots_one : primitive_roots 1 R = {(1 : R)} := begin apply finset.eq_singleton_iff_unique_mem.2, split, { simp only [is_primitive_root.one_right_iff, mem_primitive_roots zero_lt_one] }, { intros x hx, rw [mem_primitive_roots zero_lt_one, is_primitive_root.one_right_iff] at hx, exact hx } end lemma ne_zero' {n : ℕ+} (hζ : is_primitive_root ζ n) : ne_zero ((n : ℕ) : R) := begin let p := ring_char R, have hfin := (multiplicity.finite_nat_iff.2 ⟨char_p.char_ne_one R p, n.pos⟩), obtain ⟨m, hm⟩ := multiplicity.exists_eq_pow_mul_and_not_dvd hfin, by_cases hp : p ∣ n, { obtain ⟨k, hk⟩ := nat.exists_eq_succ_of_ne_zero (multiplicity.pos_of_dvd hfin hp).ne', haveI hpri : fact p.prime := @char_p.char_is_prime_of_pos R _ _ _ p ⟨nat.pos_of_dvd_of_pos hp n.pos⟩ _, have := hζ.pow_eq_one, rw [hm.1, hk, pow_succ, mul_assoc, pow_mul', ← frobenius_def, ← frobenius_one p] at this, exfalso, have hpos : 0 < p ^ k * m, { refine (mul_pos (pow_pos hpri.1.pos _) (nat.pos_of_ne_zero (λ h, _))), have H := hm.1, rw [h] at H, simpa using H }, refine hζ.pow_ne_one_of_pos_of_lt hpos _ (frobenius_inj R p this), { rw [hm.1, hk, pow_succ, mul_assoc, mul_comm p], exact lt_mul_of_one_lt_right hpos hpri.1.one_lt } }, { exact ne_zero.of_not_dvd R hp } end end is_domain section is_domain variables [comm_ring R] variables {ζ : Rˣ} (h : is_primitive_root ζ k) lemma eq_neg_one_of_two_right [no_zero_divisors R] {ζ : R} (h : is_primitive_root ζ 2) : ζ = -1 := begin apply (eq_or_eq_neg_of_sq_eq_sq ζ 1 _).resolve_left, { rw [← pow_one ζ], apply h.pow_ne_one_of_pos_of_lt; dec_trivial }, { simp only [h.pow_eq_one, one_pow] } end lemma neg_one (p : ℕ) [nontrivial R] [h : char_p R p] (hp : p ≠ 2) : is_primitive_root (-1 : R) 2 := begin convert is_primitive_root.order_of (-1 : R), rw [order_of_neg_one, if_neg], rwa ring_char.eq_iff.mpr h end /-- The (additive) monoid equivalence between `zmod k` and the powers of a primitive root of unity `ζ`. -/ def zmod_equiv_zpowers (h : is_primitive_root ζ k) : zmod k ≃+ additive (subgroup.zpowers ζ) := add_equiv.of_bijective (add_monoid_hom.lift_of_right_inverse (int.cast_add_hom $ zmod k) _ zmod.int_cast_right_inverse ⟨{ to_fun := λ i, additive.of_mul (⟨_, i, rfl⟩ : subgroup.zpowers ζ), map_zero' := by { simp only [zpow_zero], refl }, map_add' := by { intros i j, simp only [zpow_add], refl } }, (λ i hi, begin simp only [add_monoid_hom.mem_ker, char_p.int_cast_eq_zero_iff (zmod k) k, add_monoid_hom.coe_mk, int.coe_cast_add_hom] at hi ⊢, obtain ⟨i, rfl⟩ := hi, simp only [zpow_mul, h.pow_eq_one, one_zpow, zpow_coe_nat], refl end)⟩) begin split, { rw injective_iff_map_eq_zero, intros i hi, rw subtype.ext_iff at hi, have := (h.zpow_eq_one_iff_dvd _).mp hi, rw [← (char_p.int_cast_eq_zero_iff (zmod k) k _).mpr this, eq_comm], exact zmod.int_cast_right_inverse i }, { rintro ⟨ξ, i, rfl⟩, refine ⟨int.cast_add_hom _ i, _⟩, rw [add_monoid_hom.lift_of_right_inverse_comp_apply], refl } end @[simp] lemma zmod_equiv_zpowers_apply_coe_int (i : ℤ) : h.zmod_equiv_zpowers i = additive.of_mul (⟨ζ ^ i, i, rfl⟩ : subgroup.zpowers ζ) := add_monoid_hom.lift_of_right_inverse_comp_apply _ _ zmod.int_cast_right_inverse _ _ @[simp] lemma zmod_equiv_zpowers_apply_coe_nat (i : ℕ) : h.zmod_equiv_zpowers i = additive.of_mul (⟨ζ ^ i, i, rfl⟩ : subgroup.zpowers ζ) := begin have : (i : zmod k) = (i : ℤ), by norm_cast, simp only [this, zmod_equiv_zpowers_apply_coe_int, zpow_coe_nat], refl end @[simp] lemma zmod_equiv_zpowers_symm_apply_zpow (i : ℤ) : h.zmod_equiv_zpowers.symm (additive.of_mul (⟨ζ ^ i, i, rfl⟩ : subgroup.zpowers ζ)) = i := by rw [← h.zmod_equiv_zpowers.symm_apply_apply i, zmod_equiv_zpowers_apply_coe_int] @[simp] lemma zmod_equiv_zpowers_symm_apply_zpow' (i : ℤ) : h.zmod_equiv_zpowers.symm ⟨ζ ^ i, i, rfl⟩ = i := h.zmod_equiv_zpowers_symm_apply_zpow i @[simp] lemma zmod_equiv_zpowers_symm_apply_pow (i : ℕ) : h.zmod_equiv_zpowers.symm (additive.of_mul (⟨ζ ^ i, i, rfl⟩ : subgroup.zpowers ζ)) = i := by rw [← h.zmod_equiv_zpowers.symm_apply_apply i, zmod_equiv_zpowers_apply_coe_nat] @[simp] lemma zmod_equiv_zpowers_symm_apply_pow' (i : ℕ) : h.zmod_equiv_zpowers.symm ⟨ζ ^ i, i, rfl⟩ = i := h.zmod_equiv_zpowers_symm_apply_pow i variables [is_domain R] lemma zpowers_eq {k : ℕ+} {ζ : Rˣ} (h : is_primitive_root ζ k) : subgroup.zpowers ζ = roots_of_unity k R := begin apply set_like.coe_injective, haveI : fact (0 < (k : ℕ)) := ⟨k.pos⟩, haveI F : fintype (subgroup.zpowers ζ) := fintype.of_equiv _ (h.zmod_equiv_zpowers).to_equiv, refine @set.eq_of_subset_of_card_le Rˣ (subgroup.zpowers ζ) (roots_of_unity k R) F (roots_of_unity.fintype R k) (subgroup.zpowers_subset $ show ζ ∈ roots_of_unity k R, from h.pow_eq_one) _, calc fintype.card (roots_of_unity k R) ≤ k : card_roots_of_unity R k ... = fintype.card (zmod k) : (zmod.card k).symm ... = fintype.card (subgroup.zpowers ζ) : fintype.card_congr (h.zmod_equiv_zpowers).to_equiv end lemma eq_pow_of_mem_roots_of_unity {k : ℕ+} {ζ ξ : Rˣ} (h : is_primitive_root ζ k) (hξ : ξ ∈ roots_of_unity k R) : ∃ (i : ℕ) (hi : i < k), ζ ^ i = ξ := begin obtain ⟨n, rfl⟩ : ∃ n : ℤ, ζ ^ n = ξ, by rwa [← h.zpowers_eq] at hξ, have hk0 : (0 : ℤ) < k := by exact_mod_cast k.pos, let i := n % k, have hi0 : 0 ≤ i := int.mod_nonneg _ (ne_of_gt hk0), lift i to ℕ using hi0 with i₀ hi₀, refine ⟨i₀, _, _⟩, { zify, rw [hi₀], exact int.mod_lt_of_pos _ hk0 }, { have aux := h.zpow_eq_one, rw [← coe_coe] at aux, rw [← zpow_coe_nat, hi₀, ← int.mod_add_div n k, zpow_add, zpow_mul, aux, one_zpow, mul_one] } end lemma eq_pow_of_pow_eq_one {k : ℕ} {ζ ξ : R} (h : is_primitive_root ζ k) (hξ : ξ ^ k = 1) (h0 : 0 < k) : ∃ i < k, ζ ^ i = ξ := begin obtain ⟨ζ, rfl⟩ := h.is_unit h0, obtain ⟨ξ, rfl⟩ := is_unit_of_pow_eq_one ξ k hξ h0, obtain ⟨k, rfl⟩ : ∃ k' : ℕ+, k = k' := ⟨⟨k, h0⟩, rfl⟩, simp only [← units.coe_pow, ← units.ext_iff], rw coe_units_iff at h, apply h.eq_pow_of_mem_roots_of_unity, rw [mem_roots_of_unity, units.ext_iff, units.coe_pow, hξ, units.coe_one] end lemma is_primitive_root_iff' {k : ℕ+} {ζ ξ : Rˣ} (h : is_primitive_root ζ k) : is_primitive_root ξ k ↔ ∃ (i < (k : ℕ)) (hi : i.coprime k), ζ ^ i = ξ := begin split, { intro hξ, obtain ⟨i, hik, rfl⟩ := h.eq_pow_of_mem_roots_of_unity hξ.pow_eq_one, rw h.pow_iff_coprime k.pos at hξ, exact ⟨i, hik, hξ, rfl⟩ }, { rintro ⟨i, -, hi, rfl⟩, exact h.pow_of_coprime i hi } end lemma is_primitive_root_iff {k : ℕ} {ζ ξ : R} (h : is_primitive_root ζ k) (h0 : 0 < k) : is_primitive_root ξ k ↔ ∃ (i < k) (hi : i.coprime k), ζ ^ i = ξ := begin split, { intro hξ, obtain ⟨i, hik, rfl⟩ := h.eq_pow_of_pow_eq_one hξ.pow_eq_one h0, rw h.pow_iff_coprime h0 at hξ, exact ⟨i, hik, hξ, rfl⟩ }, { rintro ⟨i, -, hi, rfl⟩, exact h.pow_of_coprime i hi } end lemma card_roots_of_unity' {n : ℕ+} (h : is_primitive_root ζ n) : fintype.card (roots_of_unity n R) = n := begin haveI : fact (0 < ↑n) := ⟨n.pos⟩, let e := h.zmod_equiv_zpowers, haveI F : fintype (subgroup.zpowers ζ) := fintype.of_equiv _ e.to_equiv, calc fintype.card (roots_of_unity n R) = fintype.card (subgroup.zpowers ζ) : fintype.card_congr $ by rw h.zpowers_eq ... = fintype.card (zmod n) : fintype.card_congr e.to_equiv.symm ... = n : zmod.card n end lemma card_roots_of_unity {ζ : R} {n : ℕ+} (h : is_primitive_root ζ n) : fintype.card (roots_of_unity n R) = n := begin obtain ⟨ζ, hζ⟩ := h.is_unit n.pos, rw [← hζ, is_primitive_root.coe_units_iff] at h, exact h.card_roots_of_unity' end /-- The cardinality of the multiset `nth_roots ↑n (1 : R)` is `n` if there is a primitive root of unity in `R`. -/ lemma card_nth_roots {ζ : R} {n : ℕ} (h : is_primitive_root ζ n) : (nth_roots n (1 : R)).card = n := begin cases nat.eq_zero_or_pos n with hzero hpos, { simp only [hzero, multiset.card_zero, nth_roots_zero] }, rw eq_iff_le_not_lt, use card_nth_roots n 1, { rw [not_lt], have hcard : fintype.card {x // x ∈ nth_roots n (1 : R)} ≤ (nth_roots n (1 : R)).attach.card := multiset.card_le_of_le (multiset.dedup_le _), rw multiset.card_attach at hcard, rw ← pnat.to_pnat'_coe hpos at hcard h ⊢, set m := nat.to_pnat' n, rw [← fintype.card_congr (roots_of_unity_equiv_nth_roots R m), card_roots_of_unity h] at hcard, exact hcard } end /-- The multiset `nth_roots ↑n (1 : R)` has no repeated elements if there is a primitive root of unity in `R`. -/ lemma nth_roots_nodup {ζ : R} {n : ℕ} (h : is_primitive_root ζ n) : (nth_roots n (1 : R)).nodup := begin cases nat.eq_zero_or_pos n with hzero hpos, { simp only [hzero, multiset.nodup_zero, nth_roots_zero] }, apply (@multiset.dedup_eq_self R _ _).1, rw eq_iff_le_not_lt, split, { exact multiset.dedup_le (nth_roots n (1 : R)) }, { by_contra ha, replace ha := multiset.card_lt_of_lt ha, rw card_nth_roots h at ha, have hrw : (nth_roots n (1 : R)).dedup.card = fintype.card {x // x ∈ (nth_roots n (1 : R))}, { set fs := (⟨(nth_roots n (1 : R)).dedup, multiset.nodup_dedup _⟩ : finset R), rw [← finset.card_mk, ← fintype.card_of_subtype fs _], intro x, simp only [multiset.mem_dedup, finset.mem_mk] }, rw ← pnat.to_pnat'_coe hpos at h hrw ha, set m := nat.to_pnat' n, rw [hrw, ← fintype.card_congr (roots_of_unity_equiv_nth_roots R m), card_roots_of_unity h] at ha, exact nat.lt_asymm ha ha } end @[simp] lemma card_nth_roots_finset {ζ : R} {n : ℕ} (h : is_primitive_root ζ n) : (nth_roots_finset n R).card = n := by rw [nth_roots_finset, ← multiset.to_finset_eq (nth_roots_nodup h), card_mk, h.card_nth_roots] open_locale nat /-- If an integral domain has a primitive `k`-th root of unity, then it has `φ k` of them. -/ lemma card_primitive_roots {ζ : R} {k : ℕ} (h : is_primitive_root ζ k) : (primitive_roots k R).card = φ k := begin by_cases h0 : k = 0, { simp [h0], }, symmetry, refine finset.card_congr (λ i _, ζ ^ i) _ _ _, { simp only [true_and, and_imp, mem_filter, mem_range, mem_univ], rintro i - hi, rw mem_primitive_roots (nat.pos_of_ne_zero h0), exact h.pow_of_coprime i hi.symm }, { simp only [true_and, and_imp, mem_filter, mem_range, mem_univ], rintro i j hi - hj - H, exact h.pow_inj hi hj H }, { simp only [exists_prop, true_and, mem_filter, mem_range, mem_univ], intros ξ hξ, rw [mem_primitive_roots (nat.pos_of_ne_zero h0), h.is_primitive_root_iff (nat.pos_of_ne_zero h0)] at hξ, rcases hξ with ⟨i, hin, hi, H⟩, exact ⟨i, ⟨hin, hi.symm⟩, H⟩ } end /-- The sets `primitive_roots k R` are pairwise disjoint. -/ lemma disjoint {k l : ℕ} (h : k ≠ l) : disjoint (primitive_roots k R) (primitive_roots l R) := begin by_cases hk : k = 0, { simp [hk], }, by_cases hl : l = 0, { simp [hl], }, intro z, simp only [finset.inf_eq_inter, finset.mem_inter, mem_primitive_roots, nat.pos_of_ne_zero hk, nat.pos_of_ne_zero hl, iff_def], rintro ⟨⟨hzk, Hzk⟩, ⟨hzl, Hzl⟩⟩, apply_rules [h, nat.dvd_antisymm, Hzk, Hzl, hzk, hzl] end /-- `nth_roots n` as a `finset` is equal to the union of `primitive_roots i R` for `i ∣ n` if there is a primitive root of unity in `R`. This holds for any `nat`, not just `pnat`, see `nth_roots_one_eq_bUnion_primitive_roots`. -/ lemma nth_roots_one_eq_bUnion_primitive_roots' {ζ : R} {n : ℕ+} (h : is_primitive_root ζ n) : nth_roots_finset n R = (nat.divisors ↑n).bUnion (λ i, (primitive_roots i R)) := begin symmetry, apply finset.eq_of_subset_of_card_le, { intros x, simp only [nth_roots_finset, ← multiset.to_finset_eq (nth_roots_nodup h), exists_prop, finset.mem_bUnion, finset.mem_filter, finset.mem_range, mem_nth_roots, finset.mem_mk, nat.mem_divisors, and_true, ne.def, pnat.ne_zero, pnat.pos, not_false_iff], rintro ⟨a, ⟨d, hd⟩, ha⟩, have hazero : 0 < a, { contrapose! hd with ha0, simp only [nonpos_iff_eq_zero, zero_mul, *] at *, exact n.ne_zero }, rw mem_primitive_roots hazero at ha, rw [hd, pow_mul, ha.pow_eq_one, one_pow] }, { apply le_of_eq, rw [h.card_nth_roots_finset, finset.card_bUnion], { nth_rewrite_lhs 0 ← nat.sum_totient n, refine sum_congr rfl _, simp only [nat.mem_divisors], rintro k ⟨⟨d, hd⟩, -⟩, rw mul_comm at hd, rw (h.pow n.pos hd).card_primitive_roots }, { intros i hi j hj hdiff, exact disjoint hdiff } } end /-- `nth_roots n` as a `finset` is equal to the union of `primitive_roots i R` for `i ∣ n` if there is a primitive root of unity in `R`. -/ lemma nth_roots_one_eq_bUnion_primitive_roots {ζ : R} {n : ℕ} (h : is_primitive_root ζ n) : nth_roots_finset n R = (nat.divisors n).bUnion (λ i, (primitive_roots i R)) := begin by_cases hn : n = 0, { simp [hn], }, exact @nth_roots_one_eq_bUnion_primitive_roots' _ _ _ _ ⟨n, nat.pos_of_ne_zero hn⟩ h end end is_domain section minpoly open minpoly section comm_ring variables {n : ℕ} {K : Type*} [comm_ring K] {μ : K} (h : is_primitive_root μ n) (hpos : 0 < n) include n μ h hpos /--`μ` is integral over `ℤ`. -/ lemma is_integral : is_integral ℤ μ := begin use (X ^ n - 1), split, { exact (monic_X_pow_sub_C 1 (ne_of_lt hpos).symm) }, { simp only [((is_primitive_root.iff_def μ n).mp h).left, eval₂_one, eval₂_X_pow, eval₂_sub, sub_self] } end section is_domain variables [is_domain K] [char_zero K] omit hpos /--The minimal polynomial of a root of unity `μ` divides `X ^ n - 1`. -/ lemma minpoly_dvd_X_pow_sub_one : minpoly ℤ μ ∣ X ^ n - 1 := begin rcases n.eq_zero_or_pos with rfl | hpos, { simp }, apply minpoly.gcd_domain_dvd (is_integral h hpos) (monic_X_pow_sub_C 1 hpos.ne').ne_zero, simp only [((is_primitive_root.iff_def μ n).mp h).left, aeval_X_pow, ring_hom.eq_int_cast, int.cast_one, aeval_one, alg_hom.map_sub, sub_self] end /-- The reduction modulo `p` of the minimal polynomial of a root of unity `μ` is separable. -/ lemma separable_minpoly_mod {p : ℕ} [fact p.prime] (hdiv : ¬p ∣ n) : separable (map (int.cast_ring_hom (zmod p)) (minpoly ℤ μ)) := begin have hdvd : (map (int.cast_ring_hom (zmod p)) (minpoly ℤ μ)) ∣ X ^ n - 1, { simpa [polynomial.map_pow, map_X, polynomial.map_one, polynomial.map_sub] using ring_hom.map_dvd (map_ring_hom (int.cast_ring_hom (zmod p))) (minpoly_dvd_X_pow_sub_one h) }, refine separable.of_dvd (separable_X_pow_sub_C 1 _ one_ne_zero) hdvd, by_contra hzero, exact hdiv ((zmod.nat_coe_zmod_eq_zero_iff_dvd n p).1 hzero) end /-- The reduction modulo `p` of the minimal polynomial of a root of unity `μ` is squarefree. -/ lemma squarefree_minpoly_mod {p : ℕ} [fact p.prime] (hdiv : ¬ p ∣ n) : squarefree (map (int.cast_ring_hom (zmod p)) (minpoly ℤ μ)) := (separable_minpoly_mod h hdiv).squarefree /- Let `P` be the minimal polynomial of a root of unity `μ` and `Q` be the minimal polynomial of `μ ^ p`, where `p` is a prime that does not divide `n`. Then `P` divides `expand ℤ p Q`. -/ lemma minpoly_dvd_expand {p : ℕ} (hprime : nat.prime p) (hdiv : ¬ p ∣ n) : minpoly ℤ μ ∣ expand ℤ p (minpoly ℤ (μ ^ p)) := begin rcases n.eq_zero_or_pos with rfl | hpos, { simp * at *, }, refine minpoly.gcd_domain_dvd (h.is_integral hpos) _ _, { apply monic.ne_zero, rw [polynomial.monic, leading_coeff, nat_degree_expand, mul_comm, coeff_expand_mul' (nat.prime.pos hprime), ← leading_coeff, ← polynomial.monic], exact minpoly.monic (is_integral (pow_of_prime h hprime hdiv) hpos) }, { rw [aeval_def, coe_expand, ← comp, eval₂_eq_eval_map, map_comp, polynomial.map_pow, map_X, eval_comp, eval_pow, eval_X, ← eval₂_eq_eval_map, ← aeval_def], exact minpoly.aeval _ _ } end /- Let `P` be the minimal polynomial of a root of unity `μ` and `Q` be the minimal polynomial of `μ ^ p`, where `p` is a prime that does not divide `n`. Then `P` divides `Q ^ p` modulo `p`. -/ lemma minpoly_dvd_pow_mod {p : ℕ} [hprime : fact p.prime] (hdiv : ¬ p ∣ n) : map (int.cast_ring_hom (zmod p)) (minpoly ℤ μ) ∣ map (int.cast_ring_hom (zmod p)) (minpoly ℤ (μ ^ p)) ^ p := begin set Q := minpoly ℤ (μ ^ p), have hfrob : map (int.cast_ring_hom (zmod p)) Q ^ p = map (int.cast_ring_hom (zmod p)) (expand ℤ p Q), by rw [← zmod.expand_card, map_expand], rw [hfrob], apply ring_hom.map_dvd (map_ring_hom (int.cast_ring_hom (zmod p))), exact minpoly_dvd_expand h hprime.1 hdiv end /- Let `P` be the minimal polynomial of a root of unity `μ` and `Q` be the minimal polynomial of `μ ^ p`, where `p` is a prime that does not divide `n`. Then `P` divides `Q` modulo `p`. -/ lemma minpoly_dvd_mod_p {p : ℕ} [hprime : fact p.prime] (hdiv : ¬ p ∣ n) : map (int.cast_ring_hom (zmod p)) (minpoly ℤ μ) ∣ map (int.cast_ring_hom (zmod p)) (minpoly ℤ (μ ^ p)) := (unique_factorization_monoid.dvd_pow_iff_dvd_of_squarefree (squarefree_minpoly_mod h hdiv) hprime.1.ne_zero).1 (minpoly_dvd_pow_mod h hdiv) /-- If `p` is a prime that does not divide `n`, then the minimal polynomials of a primitive `n`-th root of unity `μ` and of `μ ^ p` are the same. -/ lemma minpoly_eq_pow {p : ℕ} [hprime : fact p.prime] (hdiv : ¬ p ∣ n) : minpoly ℤ μ = minpoly ℤ (μ ^ p) := begin by_cases hn : n = 0, { simp * at *, }, have hpos := nat.pos_of_ne_zero hn, by_contra hdiff, set P := minpoly ℤ μ, set Q := minpoly ℤ (μ ^ p), have Pmonic : P.monic := minpoly.monic (h.is_integral hpos), have Qmonic : Q.monic := minpoly.monic ((h.pow_of_prime hprime.1 hdiv).is_integral hpos), have Pirr : irreducible P := minpoly.irreducible (h.is_integral hpos), have Qirr : irreducible Q := minpoly.irreducible ((h.pow_of_prime hprime.1 hdiv).is_integral hpos), have PQprim : is_primitive (P * Q) := Pmonic.is_primitive.mul Qmonic.is_primitive, have prod : P * Q ∣ X ^ n - 1, { rw [(is_primitive.int.dvd_iff_map_cast_dvd_map_cast (P * Q) (X ^ n - 1) PQprim (monic_X_pow_sub_C (1 : ℤ) (ne_of_gt hpos)).is_primitive), polynomial.map_mul], refine is_coprime.mul_dvd _ _ _, { have aux := is_primitive.int.irreducible_iff_irreducible_map_cast Pmonic.is_primitive, refine (dvd_or_coprime _ _ (aux.1 Pirr)).resolve_left _, rw map_dvd_map (int.cast_ring_hom ℚ) int.cast_injective Pmonic, intro hdiv, refine hdiff (eq_of_monic_of_associated Pmonic Qmonic _), exact associated_of_dvd_dvd hdiv (Pirr.dvd_symm Qirr hdiv) }, { apply (map_dvd_map (int.cast_ring_hom ℚ) int.cast_injective Pmonic).2, exact minpoly_dvd_X_pow_sub_one h }, { apply (map_dvd_map (int.cast_ring_hom ℚ) int.cast_injective Qmonic).2, exact minpoly_dvd_X_pow_sub_one (pow_of_prime h hprime.1 hdiv) } }, replace prod := ring_hom.map_dvd ((map_ring_hom (int.cast_ring_hom (zmod p)))) prod, rw [coe_map_ring_hom, polynomial.map_mul, polynomial.map_sub, polynomial.map_one, polynomial.map_pow, map_X] at prod, obtain ⟨R, hR⟩ := minpoly_dvd_mod_p h hdiv, rw [hR, ← mul_assoc, ← polynomial.map_mul, ← sq, polynomial.map_pow] at prod, have habs : map (int.cast_ring_hom (zmod p)) P ^ 2 ∣ map (int.cast_ring_hom (zmod p)) P ^ 2 * R, { use R }, replace habs := lt_of_lt_of_le (part_enat.coe_lt_coe.2 one_lt_two) (multiplicity.le_multiplicity_of_pow_dvd (dvd_trans habs prod)), have hfree : squarefree (X ^ n - 1 : (zmod p)[X]), { exact (separable_X_pow_sub_C 1 (λ h, hdiv $ (zmod.nat_coe_zmod_eq_zero_iff_dvd n p).1 h) one_ne_zero).squarefree }, cases (multiplicity.squarefree_iff_multiplicity_le_one (X ^ n - 1)).1 hfree (map (int.cast_ring_hom (zmod p)) P) with hle hunit, { rw nat.cast_one at habs, exact hle.not_lt habs }, { replace hunit := degree_eq_zero_of_is_unit hunit, rw degree_map_eq_of_leading_coeff_ne_zero (int.cast_ring_hom (zmod p)) _ at hunit, { exact (minpoly.degree_pos (is_integral h hpos)).ne' hunit }, simp only [Pmonic, ring_hom.eq_int_cast, monic.leading_coeff, int.cast_one, ne.def, not_false_iff, one_ne_zero] } end /-- If `m : ℕ` is coprime with `n`, then the minimal polynomials of a primitive `n`-th root of unity `μ` and of `μ ^ m` are the same. -/ lemma minpoly_eq_pow_coprime {m : ℕ} (hcop : nat.coprime m n) : minpoly ℤ μ = minpoly ℤ (μ ^ m) := begin revert n hcop, refine unique_factorization_monoid.induction_on_prime m _ _ _, { intros n hn h, congr, simpa [(nat.coprime_zero_left n).mp hn] using h }, { intros u hunit n hcop h, congr, simp [nat.is_unit_iff.mp hunit] }, { intros a p ha hprime hind n hcop h, rw hind (nat.coprime.coprime_mul_left hcop) h, clear hind, replace hprime := nat.prime_iff.2 hprime, have hdiv := (nat.prime.coprime_iff_not_dvd hprime).1 (nat.coprime.coprime_mul_right hcop), haveI := fact.mk hprime, rw [minpoly_eq_pow (h.pow_of_coprime a (nat.coprime.coprime_mul_left hcop)) hdiv], congr' 1, ring_exp } end /-- If `m : ℕ` is coprime with `n`, then the minimal polynomial of a primitive `n`-th root of unity `μ` has `μ ^ m` as root. -/ lemma pow_is_root_minpoly {m : ℕ} (hcop : nat.coprime m n) : is_root (map (int.cast_ring_hom K) (minpoly ℤ μ)) (μ ^ m) := by simpa [minpoly_eq_pow_coprime h hcop, eval_map, aeval_def (μ ^ m) _] using minpoly.aeval ℤ (μ ^ m) /-- `primitive_roots n K` is a subset of the roots of the minimal polynomial of a primitive `n`-th root of unity `μ`. -/ lemma is_roots_of_minpoly : primitive_roots n K ⊆ (map (int.cast_ring_hom K) (minpoly ℤ μ)).roots.to_finset := begin by_cases hn : n = 0, { simp * at *, }, have hpos := nat.pos_of_ne_zero hn, intros x hx, obtain ⟨m, hle, hcop, rfl⟩ := (is_primitive_root_iff h hpos).1 ((mem_primitive_roots hpos).1 hx), simpa [multiset.mem_to_finset, mem_roots (map_monic_ne_zero $ minpoly.monic $ is_integral h hpos)] using pow_is_root_minpoly h hcop end /-- The degree of the minimal polynomial of `μ` is at least `totient n`. -/ lemma totient_le_degree_minpoly : nat.totient n ≤ (minpoly ℤ μ).nat_degree := let P : ℤ[X] := minpoly ℤ μ,-- minimal polynomial of `μ` P_K : K[X] := map (int.cast_ring_hom K) P -- minimal polynomial of `μ` sent to `K[X]` in calc n.totient = (primitive_roots n K).card : h.card_primitive_roots.symm ... ≤ P_K.roots.to_finset.card : finset.card_le_of_subset (is_roots_of_minpoly h) ... ≤ P_K.roots.card : multiset.to_finset_card_le _ ... ≤ P_K.nat_degree : card_roots' _ ... ≤ P.nat_degree : nat_degree_map_le _ _ end is_domain end comm_ring end minpoly section automorphisms variables {S} [comm_ring S] [is_domain S] {μ : S} {n : ℕ+} (hμ : is_primitive_root μ n) (R) [comm_ring R] [algebra R S] /-- The `monoid_hom` that takes an automorphism to the power of μ that μ gets mapped to under it. -/ @[simps {attrs := []}] noncomputable def aut_to_pow : (S ≃ₐ[R] S) →* (zmod n)ˣ := let μ' := hμ.to_roots_of_unity in have ho : order_of μ' = n := by rw [hμ.eq_order_of, ←hμ.coe_to_roots_of_unity_coe, order_of_units, order_of_subgroup], monoid_hom.to_hom_units { to_fun := λ σ, (map_root_of_unity_eq_pow_self σ.to_alg_hom μ').some, map_one' := begin generalize_proofs h1, have h := h1.some_spec, dsimp only [alg_equiv.one_apply, alg_equiv.to_ring_equiv_eq_coe, ring_equiv.to_ring_hom_eq_coe, ring_equiv.coe_to_ring_hom, alg_equiv.coe_ring_equiv] at *, replace h : μ' = μ' ^ h1.some := roots_of_unity.coe_injective (by simpa only [roots_of_unity.coe_pow] using h), rw ←pow_one μ' at h {occs := occurrences.pos [1]}, rw [←@nat.cast_one $ zmod n, zmod.nat_coe_eq_nat_coe_iff, ←ho, ←pow_eq_pow_iff_modeq μ', h] end, map_mul' := begin generalize_proofs hxy' hx' hy', have hxy := hxy'.some_spec, have hx := hx'.some_spec, have hy := hy'.some_spec, dsimp only [alg_equiv.to_ring_equiv_eq_coe, ring_equiv.to_ring_hom_eq_coe, ring_equiv.coe_to_ring_hom, alg_equiv.coe_ring_equiv, alg_equiv.mul_apply] at *, replace hxy : x (↑μ' ^ hy'.some) = ↑μ' ^ hxy'.some := hy ▸ hxy, rw x.map_pow at hxy, replace hxy : ((μ' : S) ^ hx'.some) ^ hy'.some = μ' ^ hxy'.some := hx ▸ hxy, rw ←pow_mul at hxy, replace hxy : μ' ^ (hx'.some * hy'.some) = μ' ^ hxy'.some := roots_of_unity.coe_injective (by simpa only [roots_of_unity.coe_pow] using hxy), rw [←nat.cast_mul, zmod.nat_coe_eq_nat_coe_iff, ←ho, ←pow_eq_pow_iff_modeq μ', hxy] end } @[simp] lemma aut_to_pow_spec (f : S ≃ₐ[R] S) : μ ^ (hμ.aut_to_pow R f : zmod n).val = f μ := begin rw is_primitive_root.coe_aut_to_pow_apply, generalize_proofs h, have := h.some_spec, dsimp only [alg_equiv.to_alg_hom_eq_coe, alg_equiv.coe_alg_hom] at this, refine (_ : ↑hμ.to_roots_of_unity ^ _ = _).trans this.symm, rw [←roots_of_unity.coe_pow, ←roots_of_unity.coe_pow], congr' 1, rw [pow_eq_pow_iff_modeq, ←order_of_subgroup, ←order_of_units, hμ.coe_to_roots_of_unity_coe, ←hμ.eq_order_of, zmod.val_nat_cast], exact nat.mod_modeq _ _ end end automorphisms end is_primitive_root
e57b57b2261a60e229e756fd2bc8aaed30aebebd
a4673261e60b025e2c8c825dfa4ab9108246c32e
/src/Lean/HeadIndex.lean
d68d71cd987acee3f455bfa0052010b104d118ef
[ "Apache-2.0" ]
permissive
jcommelin/lean4
c02dec0cc32c4bccab009285475f265f17d73228
2909313475588cc20ac0436e55548a4502050d0a
refs/heads/master
1,674,129,550,893
1,606,415,348,000
1,606,415,348,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,579
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ import Lean.Expr namespace Lean inductive HeadIndex := | fvar (fvarId : FVarId) | mvar (mvarId : MVarId) | const (constName : Name) | proj (structName : Name) (idx : Nat) | lit (litVal : Literal) | sort | lam | forallE namespace HeadIndex instance : Inhabited HeadIndex := ⟨sort⟩ protected def HeadIndex.hash : HeadIndex → USize | fvar fvarId => mixHash 11 $ hash fvarId | mvar mvarId => mixHash 13 $ hash mvarId | const constName => mixHash 17 $ hash constName | proj structName idx => mixHash 19 $ mixHash (hash structName) (hash idx) | lit litVal => mixHash 23 $ hash litVal | sort => 29 | lam => 31 | forallE => 37 instance : Hashable HeadIndex := ⟨HeadIndex.hash⟩ protected def HeadIndex.beq : HeadIndex → HeadIndex → Bool | fvar id₁, fvar id₂ => id₁ == id₂ | mvar id₁, mvar id₂ => id₁ == id₂ | const id₁, const id₂ => id₁ == id₂ | proj s₁ i₁, proj s₂ i₂ => s₁ == s₂ && i₁ == i₂ | lit v₁, lit v₂ => v₁ == v₂ | sort, sort => true | lam, lam => true | forallE, forallE => true | _, _ => false instance : BEq HeadIndex := ⟨HeadIndex.beq⟩ end HeadIndex namespace Expr def head : Expr → Expr | app f _ _ => head f | letE _ _ _ b _ => head b | mdata _ e _ => head e | e => e private def headNumArgsAux : Expr → Nat → Nat | app f _ _, n => headNumArgsAux f (n + 1) | letE _ _ _ b _, n => headNumArgsAux b n | mdata _ e _, n => headNumArgsAux e n | _, n => n def headNumArgs (e : Expr) : Nat := headNumArgsAux e 0 def toHeadIndex : Expr → HeadIndex | mvar mvarId _ => HeadIndex.mvar mvarId | fvar fvarId _ => HeadIndex.fvar fvarId | const constName _ _ => HeadIndex.const constName | proj structName idx _ _ => HeadIndex.proj structName idx | sort _ _ => HeadIndex.sort | lam _ _ _ _ => HeadIndex.lam | forallE _ _ _ _ => HeadIndex.forallE | lit v _ => HeadIndex.lit v | app f _ _ => toHeadIndex f | letE _ _ _ b _ => toHeadIndex b | mdata _ e _ => toHeadIndex e | _ => panic! "unexpected expression kind" end Expr end Lean
98c1a2cbd23b1560a12b6b18ce05a6b3a1fb266e
4727251e0cd73359b15b664c3170e5d754078599
/src/group_theory/finiteness.lean
0523b90f69ccfa8a96368e88b80fc39456c44de6
[ "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
11,979
lean
/- Copyright (c) 2021 Riccardo Brasca. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Riccardo Brasca -/ import data.set.finite import data.finset import group_theory.quotient_group import group_theory.submonoid.operations import group_theory.subgroup.basic /-! # Finitely generated monoids and groups We define finitely generated monoids and groups. See also `submodule.fg` and `module.finite` for finitely-generated modules. ## Main definition * `submonoid.fg S`, `add_submonoid.fg S` : A submonoid `S` is finitely generated. * `monoid.fg M`, `add_monoid.fg M` : A typeclass indicating a type `M` is finitely generated as a monoid. * `subgroup.fg S`, `add_subgroup.fg S` : A subgroup `S` is finitely generated. * `group.fg M`, `add_group.fg M` : A typeclass indicating a type `M` is finitely generated as a group. -/ /-! ### Monoids and submonoids -/ open_locale pointwise variables {M N : Type*} [monoid M] [add_monoid N] section submonoid /-- A submonoid of `M` is finitely generated if it is the closure of a finite subset of `M`. -/ @[to_additive] def submonoid.fg (P : submonoid M) : Prop := ∃ S : finset M, submonoid.closure ↑S = P /-- An additive submonoid of `N` is finitely generated if it is the closure of a finite subset of `M`. -/ add_decl_doc add_submonoid.fg /-- An equivalent expression of `submonoid.fg` in terms of `set.finite` instead of `finset`. -/ @[to_additive "An equivalent expression of `add_submonoid.fg` in terms of `set.finite` instead of `finset`."] lemma submonoid.fg_iff (P : submonoid M) : submonoid.fg P ↔ ∃ S : set M, submonoid.closure S = P ∧ S.finite := ⟨λ ⟨S, hS⟩, ⟨S, hS, finset.finite_to_set S⟩, λ ⟨S, hS, hf⟩, ⟨set.finite.to_finset hf, by simp [hS]⟩⟩ lemma submonoid.fg_iff_add_fg (P : submonoid M) : P.fg ↔ P.to_add_submonoid.fg := ⟨λ h, let ⟨S, hS, hf⟩ := (submonoid.fg_iff _).1 h in (add_submonoid.fg_iff _).mpr ⟨additive.to_mul ⁻¹' S, by simp [← submonoid.to_add_submonoid_closure, hS], hf⟩, λ h, let ⟨T, hT, hf⟩ := (add_submonoid.fg_iff _).1 h in (submonoid.fg_iff _).mpr ⟨multiplicative.of_add ⁻¹' T, by simp [← add_submonoid.to_submonoid'_closure, hT], hf⟩⟩ lemma add_submonoid.fg_iff_mul_fg (P : add_submonoid N) : P.fg ↔ P.to_submonoid.fg := begin convert (submonoid.fg_iff_add_fg P.to_submonoid).symm, exact set_like.ext' rfl end end submonoid section monoid variables (M N) /-- A monoid is finitely generated if it is finitely generated as a submonoid of itself. -/ class monoid.fg : Prop := (out : (⊤ : submonoid M).fg) /-- An additive monoid is finitely generated if it is finitely generated as an additive submonoid of itself. -/ class add_monoid.fg : Prop := (out : (⊤ : add_submonoid N).fg) attribute [to_additive] monoid.fg variables {M N} lemma monoid.fg_def : monoid.fg M ↔ (⊤ : submonoid M).fg := ⟨λ h, h.1, λ h, ⟨h⟩⟩ lemma add_monoid.fg_def : add_monoid.fg N ↔ (⊤ : add_submonoid N).fg := ⟨λ h, h.1, λ h, ⟨h⟩⟩ /-- An equivalent expression of `monoid.fg` in terms of `set.finite` instead of `finset`. -/ @[to_additive "An equivalent expression of `add_monoid.fg` in terms of `set.finite` instead of `finset`."] lemma monoid.fg_iff : monoid.fg M ↔ ∃ S : set M, submonoid.closure S = (⊤ : submonoid M) ∧ S.finite := ⟨λ h, (submonoid.fg_iff ⊤).1 h.out, λ h, ⟨(submonoid.fg_iff ⊤).2 h⟩⟩ lemma monoid.fg_iff_add_fg : monoid.fg M ↔ add_monoid.fg (additive M) := ⟨λ h, ⟨(submonoid.fg_iff_add_fg ⊤).1 h.out⟩, λ h, ⟨(submonoid.fg_iff_add_fg ⊤).2 h.out⟩⟩ lemma add_monoid.fg_iff_mul_fg : add_monoid.fg N ↔ monoid.fg (multiplicative N) := ⟨λ h, ⟨(add_submonoid.fg_iff_mul_fg ⊤).1 h.out⟩, λ h, ⟨(add_submonoid.fg_iff_mul_fg ⊤).2 h.out⟩⟩ instance add_monoid.fg_of_monoid_fg [monoid.fg M] : add_monoid.fg (additive M) := monoid.fg_iff_add_fg.1 ‹_› instance monoid.fg_of_add_monoid_fg [add_monoid.fg N] : monoid.fg (multiplicative N) := add_monoid.fg_iff_mul_fg.1 ‹_› end monoid @[to_additive] lemma submonoid.fg.map {M' : Type*} [monoid M'] {P : submonoid M} (h : P.fg) (e : M →* M') : (P.map e).fg := begin classical, obtain ⟨s, rfl⟩ := h, exact ⟨s.image e, by rw [finset.coe_image, monoid_hom.map_mclosure]⟩ end @[to_additive] lemma submonoid.fg.map_injective {M' : Type*} [monoid M'] {P : submonoid M} (e : M →* M') (he : function.injective e) (h : (P.map e).fg) : P.fg := begin obtain ⟨s, hs⟩ := h, use s.preimage e (he.inj_on _), apply submonoid.map_injective_of_injective he, rw [← hs, e.map_mclosure, finset.coe_preimage], congr, rw [set.image_preimage_eq_iff, ← e.coe_mrange, ← submonoid.closure_le, hs, e.mrange_eq_map], exact submonoid.monotone_map le_top end @[simp, to_additive] lemma monoid.fg_iff_submonoid_fg (N : submonoid M) : monoid.fg N ↔ N.fg := begin conv_rhs { rw [← N.range_subtype, monoid_hom.mrange_eq_map] }, exact ⟨λ h, h.out.map N.subtype, λ h, ⟨h.map_injective N.subtype subtype.coe_injective⟩⟩ end @[to_additive] lemma monoid.fg_of_surjective {M' : Type*} [monoid M'] [monoid.fg M] (f : M →* M') (hf : function.surjective f) : monoid.fg M' := begin classical, obtain ⟨s, hs⟩ := monoid.fg_def.mp ‹_›, use s.image f, rwa [finset.coe_image, ← monoid_hom.map_mclosure, hs, ← monoid_hom.mrange_eq_map, monoid_hom.mrange_top_iff_surjective], end @[to_additive] instance monoid.fg_range {M' : Type*} [monoid M'] [monoid.fg M] (f : M →* M') : monoid.fg f.mrange := monoid.fg_of_surjective f.mrange_restrict f.mrange_restrict_surjective @[to_additive add_submonoid.multiples_fg] lemma submonoid.powers_fg (r : M) : (submonoid.powers r).fg := ⟨{r}, (finset.coe_singleton r).symm ▸ (submonoid.powers_eq_closure r).symm⟩ @[to_additive add_monoid.multiples_fg] instance monoid.powers_fg (r : M) : monoid.fg (submonoid.powers r) := (monoid.fg_iff_submonoid_fg _).mpr (submonoid.powers_fg r) /-! ### Groups and subgroups -/ variables {G H : Type*} [group G] [add_group H] section subgroup /-- A subgroup of `G` is finitely generated if it is the closure of a finite subset of `G`. -/ @[to_additive] def subgroup.fg (P : subgroup G) : Prop := ∃ S : finset G, subgroup.closure ↑S = P /-- An additive subgroup of `H` is finitely generated if it is the closure of a finite subset of `H`. -/ add_decl_doc add_subgroup.fg /-- An equivalent expression of `subgroup.fg` in terms of `set.finite` instead of `finset`. -/ @[to_additive "An equivalent expression of `add_subgroup.fg` in terms of `set.finite` instead of `finset`."] lemma subgroup.fg_iff (P : subgroup G) : subgroup.fg P ↔ ∃ S : set G, subgroup.closure S = P ∧ S.finite := ⟨λ⟨S, hS⟩, ⟨S, hS, finset.finite_to_set S⟩, λ⟨S, hS, hf⟩, ⟨set.finite.to_finset hf, by simp [hS]⟩⟩ /-- A subgroup is finitely generated if and only if it is finitely generated as a submonoid. -/ @[to_additive add_subgroup.fg_iff_add_submonoid.fg "An additive subgroup is finitely generated if and only if it is finitely generated as an additive submonoid."] lemma subgroup.fg_iff_submonoid_fg (P : subgroup G) : P.fg ↔ P.to_submonoid.fg := begin split, { rintro ⟨S, rfl⟩, rw submonoid.fg_iff, refine ⟨S ∪ S⁻¹, _, S.finite_to_set.union S.finite_to_set.inv⟩, exact (subgroup.closure_to_submonoid _).symm }, { rintro ⟨S, hS⟩, refine ⟨S, le_antisymm _ _⟩, { rw [subgroup.closure_le, ←subgroup.coe_to_submonoid, ←hS], exact submonoid.subset_closure }, { rw [← subgroup.to_submonoid_le, ← hS, submonoid.closure_le], exact subgroup.subset_closure } } end lemma subgroup.fg_iff_add_fg (P : subgroup G) : P.fg ↔ P.to_add_subgroup.fg := begin rw [subgroup.fg_iff_submonoid_fg, add_subgroup.fg_iff_add_submonoid.fg], exact (subgroup.to_submonoid P).fg_iff_add_fg end lemma add_subgroup.fg_iff_mul_fg (P : add_subgroup H) : P.fg ↔ P.to_subgroup.fg := begin rw [add_subgroup.fg_iff_add_submonoid.fg, subgroup.fg_iff_submonoid_fg], exact add_submonoid.fg_iff_mul_fg (add_subgroup.to_add_submonoid P) end end subgroup section group variables (G H) /-- A group is finitely generated if it is finitely generated as a submonoid of itself. -/ class group.fg : Prop := (out : (⊤ : subgroup G).fg) /-- An additive group is finitely generated if it is finitely generated as an additive submonoid of itself. -/ class add_group.fg : Prop := (out : (⊤ : add_subgroup H).fg) attribute [to_additive] group.fg variables {G H} lemma group.fg_def : group.fg G ↔ (⊤ : subgroup G).fg := ⟨λ h, h.1, λ h, ⟨h⟩⟩ lemma add_group.fg_def : add_group.fg H ↔ (⊤ : add_subgroup H).fg := ⟨λ h, h.1, λ h, ⟨h⟩⟩ /-- An equivalent expression of `group.fg` in terms of `set.finite` instead of `finset`. -/ @[to_additive "An equivalent expression of `add_group.fg` in terms of `set.finite` instead of `finset`."] lemma group.fg_iff : group.fg G ↔ ∃ S : set G, subgroup.closure S = (⊤ : subgroup G) ∧ S.finite := ⟨λ h, (subgroup.fg_iff ⊤).1 h.out, λ h, ⟨(subgroup.fg_iff ⊤).2 h⟩⟩ @[to_additive] lemma group.fg_iff' : group.fg G ↔ ∃ n (S : finset G), S.card = n ∧ subgroup.closure (S : set G) = ⊤ := group.fg_def.trans ⟨λ ⟨S, hS⟩, ⟨S.card, S, rfl, hS⟩, λ ⟨n, S, hn, hS⟩, ⟨S, hS⟩⟩ /-- A group is finitely generated if and only if it is finitely generated as a monoid. -/ @[to_additive add_group.fg_iff_add_monoid.fg "An additive group is finitely generated if and only if it is finitely generated as an additive monoid."] lemma group.fg_iff_monoid.fg : group.fg G ↔ monoid.fg G := ⟨λ h, monoid.fg_def.2 $ (subgroup.fg_iff_submonoid_fg ⊤).1 (group.fg_def.1 h), λ h, group.fg_def.2 $ (subgroup.fg_iff_submonoid_fg ⊤).2 (monoid.fg_def.1 h)⟩ lemma group_fg.iff_add_fg : group.fg G ↔ add_group.fg (additive G) := ⟨λ h, ⟨(subgroup.fg_iff_add_fg ⊤).1 h.out⟩, λ h, ⟨(subgroup.fg_iff_add_fg ⊤).2 h.out⟩⟩ lemma add_group.fg_iff_mul_fg : add_group.fg H ↔ group.fg (multiplicative H) := ⟨λ h, ⟨(add_subgroup.fg_iff_mul_fg ⊤).1 h.out⟩, λ h, ⟨(add_subgroup.fg_iff_mul_fg ⊤).2 h.out⟩⟩ instance add_group.fg_of_group_fg [group.fg G] : add_group.fg (additive G) := group_fg.iff_add_fg.1 ‹_› instance group.fg_of_mul_group_fg [add_group.fg H] : group.fg (multiplicative H) := add_group.fg_iff_mul_fg.1 ‹_› @[to_additive] lemma group.fg_of_surjective {G' : Type*} [group G'] [hG : group.fg G] {f : G →* G'} (hf : function.surjective f) : group.fg G' := group.fg_iff_monoid.fg.mpr $ @monoid.fg_of_surjective G _ G' _ (group.fg_iff_monoid.fg.mp hG) f hf @[to_additive] instance group.fg_range {G' : Type*} [group G'] [group.fg G] (f : G →* G') : group.fg f.range := group.fg_of_surjective f.range_restrict_surjective variables (G) /-- The minimum number of generators of a group. -/ @[to_additive "The minimum number of generators of an additive group"] def group.rank [h : group.fg G] [decidable_pred (λ n, ∃ (S : finset G), S.card = n ∧ subgroup.closure (S : set G) = ⊤)] := nat.find (group.fg_iff'.mp h) @[to_additive] lemma group.rank_spec [h : group.fg G] [decidable_pred (λ n, ∃ (S : finset G), S.card = n ∧ subgroup.closure (S : set G) = ⊤)] : ∃ S : finset G, S.card = group.rank G ∧ subgroup.closure (S : set G) = ⊤ := nat.find_spec (group.fg_iff'.mp h) @[to_additive] lemma group.rank_le [group.fg G] [decidable_pred (λ n, ∃ (S : finset G), S.card = n ∧ subgroup.closure (S : set G) = ⊤)] {S : finset G} (hS : subgroup.closure (S : set G) = ⊤) : group.rank G ≤ S.card := nat.find_le ⟨S, rfl, hS⟩ end group section quotient_group @[to_additive] instance quotient_group.fg [group.fg G] (N : subgroup G) [subgroup.normal N] : group.fg $ G ⧸ N := group.fg_of_surjective $ quotient_group.mk'_surjective N end quotient_group
d3f010a794fe2cf04a66f7b64090eedfa2206315
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/init/meta/match_tactic.lean
fb27fc78a92a4b9ec3f53fa434c8a5e356c65f25
[ "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
4,038
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.tactic init.function namespace tactic structure pattern := /- Term to match. -/ (target : expr) /- Set of terms that is instantiated for each successful match. -/ (output : list expr) /- Number of (temporary) universe meta-variables in this pattern. -/ (nuvars : nat) /- Number of (temporary) meta-variables in this pattern. -/ (nmvars : nat) /- (mk_pattern ls es t o) creates a new pattern with (length ls) universe meta-variables and (length es) meta-variables. In the produced pattern p, we have that - (pattern.target p) is the term t where the universes ls and expressions es have been replaced with temporary meta-variables. - (pattern.output p) is the list o where the universes ls and expressions es have been replaced with temporary meta-variables. - (pattern.nuvars p) = length ls - (pattern.nmvars p) = length es The tactic fails if o and the types of es do not contain all universes ls and expressions es. -/ meta_constant mk_pattern : list level → list expr → expr → list expr → tactic pattern /- (mk_pattern_core m p e) matches (pattern.target p) and e using transparency m. If the matching is successful, then return the instantiation of (pattern.output p). The tactic fails if not all (temporary) meta-variables are assigned. -/ meta_constant match_pattern_core : transparency → pattern → expr → tactic (list expr) meta_definition match_pattern : pattern → expr → tactic (list expr) := match_pattern_core semireducible open expr /- Helper function for converting a term (λ x_1 ... x_n, t) into a pattern where x_1 ... x_n are metavariables -/ private meta_definition to_pattern_core : expr → tactic (expr × list expr) | (lam n bi d b) := do id ← mk_fresh_name, x ← return $ local_const id n bi d, new_b ← return $ instantiate_var b x, (p, xs) ← to_pattern_core new_b, return (p, x::xs) | e := return (e, []) /- Given a pre-term of the form (λ x_1 ... x_n, t[x_1, ..., x_n]), converts it into the pattern t[?x_1, ..., ?x_n] -/ meta_definition pexpr_to_pattern (p : pexpr) : tactic pattern := do e ← to_expr p, (new_p, xs) ← to_pattern_core e, mk_pattern [] xs new_p xs /- Convert pre-term into a pattern and try to match e. Given p of the form (λ x_1 ... x_n, t[x_1, ..., x_n]), a successful match will produce a list of length n. -/ meta_definition match_expr (p : pexpr) (e : expr) : tactic (list expr) := do new_p ← pexpr_to_pattern p, match_pattern new_p e private meta_definition match_subexpr_core : pattern → list expr → tactic (list expr) | p [] := failed | p (e::es) := match_pattern p e <|> match_subexpr_core p es <|> if (is_app e = tt) then match_subexpr_core p (get_app_args e) else failed /- Similar to match_expr, but it tries to match a subexpression of e. Remark: the procedure does not go inside binders. -/ meta_definition match_subexpr (p : pexpr) (e : expr) : tactic (list expr) := do new_p ← pexpr_to_pattern p, match_subexpr_core new_p [e] /- Match the main goal target. -/ meta_definition match_target (p : pexpr) : tactic (list expr) := target >>= match_expr p /- Match a subterm in the main goal target. -/ meta_definition match_target_subexpr (p : pexpr) : tactic (list expr) := target >>= match_subexpr p private meta_definition match_hypothesis_core : pattern → list expr → tactic (expr × list expr) | p [] := failed | p (h::hs) := do h_type ← infer_type h, (do r ← match_pattern p h_type, return (h, r)) <|> match_hypothesis_core p hs /- Match hypothesis in the main goal target. The result is pair (hypothesis, substitution). -/ meta_definition match_hypothesis (p : pexpr) : tactic (expr × list expr) := do ctx ← local_context, new_p ← pexpr_to_pattern p, match_hypothesis_core new_p ctx end tactic
b5ca43f9df515508ab221bfdcaff66b4f6b3b26e
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/order/zorn.lean
e01e9eba7c937009b417f021cfb20a05a4e3a69a
[ "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
16,760
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 data.set.pairwise /-! # Chains and Zorn's lemmas This file defines chains for an arbitrary relation and proves several formulations of Zorn's Lemma, along with Hausdorff's Maximality Principle. ## Main declarations * `chain c`: A chain `c` is a set of comparable elements. * `max_chain_spec`: Hausdorff's Maximality Principle. * `exists_maximal_of_chains_bounded`: Zorn's Lemma. Many variants are offered. ## Variants The primary statement of Zorn's lemma is `exists_maximal_of_chains_bounded`. Then it is specialized to particular relations: * `(≤)` with `zorn_partial_order` * `(⊆)` with `zorn_subset` * `(⊇)` with `zorn_superset` Lemma names carry modifiers: * `₀`: Quantifies over a set, as opposed to over a type. * `_nonempty`: Doesn't ask to prove that the empty chain is bounded and lets you give an element that will be smaller than the maximal element found (the maximal element is no smaller than any other element, but it can also be incomparable to some). ## How-to This file comes across as confusing to those who haven't yet used it, so here is a detailed walkthrough: 1. Know what relation on which type/set you're looking for. See Variants above. You can discharge some conditions to Zorn's lemma directly using a `_nonempty` variant. 2. Write down the definition of your type/set, put a `suffices : ∃ m, ∀ a, m ≺ a → a ≺ m, { ... },` (or whatever you actually need) followed by a `apply some_version_of_zorn`. 3. Fill in the details. This is where you start talking about chains. A typical proof using Zorn could look like this ```lean lemma zorny_lemma : zorny_statement := begin let s : set α := {x | whatever x}, suffices : ∃ x ∈ s, ∀ y ∈ s, y ⊆ x → y = x, -- or with another operator { exact proof_post_zorn }, apply zorn.zorn_subset, -- or another variant rintro c hcs hc, obtain rfl | hcnemp := c.eq_empty_or_nonempty, -- you might need to disjunct on c empty or not { exact ⟨edge_case_construction, proof_that_edge_case_construction_respects_whatever, proof_that_edge_case_construction_contains_all_stuff_in_c⟩ }, exact ⟨construction, proof_that_construction_respects_whatever, proof_that_construction_contains_all_stuff_in_c⟩, end ``` ## Notes Originally ported from Isabelle/HOL. The [original file](https://isabelle.in.tum.de/dist/library/HOL/HOL/Zorn.html) was written by Jacques D. Fleuriot, Tobias Nipkow, Christian Sternagel. -/ noncomputable theory universes u open set classical open_locale classical namespace zorn section chain parameters {α : Type u} (r : α → α → Prop) local infix ` ≺ `:50 := r /-- A chain is a subset `c` satisfying `x ≺ y ∨ x = y ∨ y ≺ x` for all `x y ∈ c`. -/ def chain (c : set α) := c.pairwise (λ x y, x ≺ y ∨ y ≺ x) parameters {r} lemma chain.total_of_refl [is_refl α r] {c} (H : chain c) {x y} (hx : x ∈ c) (hy : y ∈ c) : x ≺ y ∨ y ≺ x := if e : x = y then or.inl (e ▸ refl _) else H _ hx _ hy e lemma chain.mono {c c'} : c' ⊆ c → chain c → chain c' := set.pairwise.mono lemma chain_of_trichotomous [is_trichotomous α r] (s : set α) : chain s := begin intros a _ b _ hab, obtain h | h | h := @trichotomous _ r _ a b, { exact or.inl h }, { exact (hab h).elim }, { exact or.inr h } end lemma chain_univ_iff : chain (univ : set α) ↔ is_trichotomous α r := begin refine ⟨λ h, ⟨λ a b , _⟩, λ h, @chain_of_trichotomous _ _ h univ⟩, rw [or.left_comm, or_iff_not_imp_left], exact h a trivial b trivial, end lemma chain.directed_on [is_refl α r] {c} (H : chain c) : directed_on (≺) c := λ x hx y hy, match H.total_of_refl hx hy with | or.inl h := ⟨y, hy, h, refl _⟩ | or.inr h := ⟨x, hx, refl _, h⟩ end lemma chain_insert {c : set α} {a : α} (hc : chain c) (ha : ∀ b ∈ c, b ≠ a → a ≺ b ∨ b ≺ a) : chain (insert a c) := forall_insert_of_forall (λ x hx, forall_insert_of_forall (hc x hx) (λ hneq, (ha x hx hneq).symm)) (forall_insert_of_forall (λ x hx hneq, ha x hx $ λ h', hneq h'.symm) (λ h, (h rfl).rec _)) /-- `super_chain c₁ c₂` means that `c₂` is a chain that strictly includes `c₁`. -/ def super_chain (c₁ c₂ : set α) : Prop := chain c₂ ∧ c₁ ⊂ c₂ /-- A chain `c` is a maximal chain if there does not exists a chain strictly including `c`. -/ def is_max_chain (c : set α) := chain c ∧ ¬ (∃ c', super_chain c c') /-- Given a set `c`, if there exists a chain `c'` strictly including `c`, then `succ_chain c` is one of these chains. Otherwise it is `c`. -/ def succ_chain (c : set α) : set α := if h : ∃ c', chain c ∧ super_chain c c' then some h else c lemma succ_spec {c : set α} (h : ∃ c', chain c ∧ super_chain c c') : super_chain c (succ_chain c) := let ⟨c', hc'⟩ := h in have chain c ∧ super_chain c (some h), from @some_spec _ (λ c', chain c ∧ super_chain c c') _, by simp [succ_chain, dif_pos, h, this.right] lemma chain_succ {c : set α} (hc : chain c) : chain (succ_chain c) := if h : ∃ c', chain c ∧ super_chain c c' then (succ_spec h).left else by simp [succ_chain, dif_neg, h]; exact hc lemma super_of_not_max {c : set α} (hc₁ : chain c) (hc₂ : ¬ is_max_chain c) : super_chain c (succ_chain c) := begin simp [is_max_chain, not_and_distrib, not_forall_not] at hc₂, cases hc₂.neg_resolve_left hc₁ with c' hc', exact succ_spec ⟨c', hc₁, hc'⟩ end lemma succ_increasing {c : set α} : c ⊆ succ_chain c := if h : ∃ c', chain c ∧ super_chain c c' then have super_chain c (succ_chain c), from succ_spec h, this.right.left else by simp [succ_chain, dif_neg, h, subset.refl] /-- Set of sets reachable from `∅` using `succ_chain` and `⋃₀`. -/ inductive chain_closure : set (set α) | succ : ∀ {s}, chain_closure s → chain_closure (succ_chain s) | union : ∀ {s}, (∀ a ∈ s, chain_closure a) → chain_closure (⋃₀ s) lemma chain_closure_empty : ∅ ∈ chain_closure := have chain_closure (⋃₀ ∅), from chain_closure.union $ λ a h, h.rec _, by simp at this; assumption lemma chain_closure_closure : ⋃₀ chain_closure ∈ chain_closure := chain_closure.union $ λ s hs, hs variables {c c₁ c₂ c₃ : set α} private lemma chain_closure_succ_total_aux (hc₁ : c₁ ∈ chain_closure) (hc₂ : c₂ ∈ chain_closure) (h : ∀ {c₃}, c₃ ∈ chain_closure → c₃ ⊆ c₂ → c₂ = c₃ ∨ succ_chain c₃ ⊆ c₂) : c₁ ⊆ c₂ ∨ succ_chain c₂ ⊆ c₁ := begin induction hc₁, case succ : c₃ hc₃ ih { cases ih with ih ih, { have h := h hc₃ ih, cases h with h h, { exact or.inr (h ▸ subset.refl _) }, { exact or.inl h } }, { exact or.inr (subset.trans ih succ_increasing) } }, case union : s hs ih { refine (or_iff_not_imp_right.2 $ λ hn, sUnion_subset $ λ a ha, _), apply (ih a ha).resolve_right, apply mt (λ h, _) hn, exact subset.trans h (subset_sUnion_of_mem ha) } end private lemma chain_closure_succ_total (hc₁ : c₁ ∈ chain_closure) (hc₂ : c₂ ∈ chain_closure) (h : c₁ ⊆ c₂) : c₂ = c₁ ∨ succ_chain c₁ ⊆ c₂ := begin induction hc₂ generalizing c₁ hc₁ h, case succ : c₂ hc₂ ih { have h₁ : c₁ ⊆ c₂ ∨ @succ_chain α r c₂ ⊆ c₁ := (chain_closure_succ_total_aux hc₁ hc₂ $ λ c₁, ih), cases h₁ with h₁ h₁, { have h₂ := ih hc₁ h₁, cases h₂ with h₂ h₂, { exact (or.inr $ h₂ ▸ subset.refl _) }, { exact (or.inr $ subset.trans h₂ succ_increasing) } }, { exact (or.inl $ subset.antisymm h₁ h) } }, case union : s hs ih { apply or.imp_left (λ h', subset.antisymm h' h), apply classical.by_contradiction, simp [not_or_distrib, sUnion_subset_iff, not_forall], intros c₃ hc₃ h₁ h₂, have h := chain_closure_succ_total_aux hc₁ (hs c₃ hc₃) (λ c₄, ih _ hc₃), cases h with h h, { have h' := ih c₃ hc₃ hc₁ h, cases h' with h' h', { exact (h₁ $ h' ▸ subset.refl _) }, { exact (h₂ $ subset.trans h' $ subset_sUnion_of_mem hc₃) } }, { exact (h₁ $ subset.trans succ_increasing h) } } end lemma chain_closure_total (hc₁ : c₁ ∈ chain_closure) (hc₂ : c₂ ∈ chain_closure) : c₁ ⊆ c₂ ∨ c₂ ⊆ c₁ := or.imp_right succ_increasing.trans $ chain_closure_succ_total_aux hc₁ hc₂ $ λ c₃ hc₃, chain_closure_succ_total hc₃ hc₂ lemma chain_closure_succ_fixpoint (hc₁ : c₁ ∈ chain_closure) (hc₂ : c₂ ∈ chain_closure) (h_eq : succ_chain c₂ = c₂) : c₁ ⊆ c₂ := begin induction hc₁, case succ : c₁ hc₁ h { exact or.elim (chain_closure_succ_total hc₁ hc₂ h) (λ h, h ▸ h_eq.symm ▸ subset.refl c₂) id }, case union : s hs ih { exact (sUnion_subset $ λ c₁ hc₁, ih c₁ hc₁) } end lemma chain_closure_succ_fixpoint_iff (hc : c ∈ chain_closure) : succ_chain c = c ↔ c = ⋃₀ chain_closure := ⟨λ h, (subset_sUnion_of_mem hc).antisymm (chain_closure_succ_fixpoint chain_closure_closure hc h), λ h, subset.antisymm (calc succ_chain c ⊆ ⋃₀{c : set α | c ∈ chain_closure} : subset_sUnion_of_mem $ chain_closure.succ hc ... = c : h.symm) succ_increasing⟩ lemma chain_chain_closure (hc : c ∈ chain_closure) : chain c := begin induction hc, case succ : c hc h { exact chain_succ h }, case union : s hs h { have h : ∀ c ∈ s, zorn.chain c := h, exact λ c₁ ⟨t₁, ht₁, (hc₁ : c₁ ∈ t₁)⟩ c₂ ⟨t₂, ht₂, (hc₂ : c₂ ∈ t₂)⟩ hneq, have t₁ ⊆ t₂ ∨ t₂ ⊆ t₁, from chain_closure_total (hs _ ht₁) (hs _ ht₂), or.elim this (λ ht, h t₂ ht₂ c₁ (ht hc₁) c₂ hc₂ hneq) (λ ht, h t₁ ht₁ c₁ hc₁ c₂ (ht hc₂) hneq) } end /-- An explicit maximal chain. `max_chain` is taken to be the union of all sets in `chain_closure`. -/ def max_chain := ⋃₀ chain_closure /-- Hausdorff's maximality principle There exists a maximal totally ordered subset of `α`. Note that we do not require `α` to be partially ordered by `r`. -/ theorem max_chain_spec : is_max_chain max_chain := classical.by_contradiction $ λ h, begin obtain ⟨h₁, H⟩ := super_of_not_max (chain_chain_closure chain_closure_closure) h, obtain ⟨h₂, h₃⟩ := ssubset_iff_subset_ne.1 H, exact h₃ ((chain_closure_succ_fixpoint_iff chain_closure_closure).mpr rfl).symm, end /-- Zorn's lemma If every chain has an upper bound, then there exists a maximal element. -/ theorem exists_maximal_of_chains_bounded (h : ∀ c, chain c → ∃ ub, ∀ a ∈ c, a ≺ ub) (trans : ∀ {a b c}, a ≺ b → b ≺ c → a ≺ c) : ∃ m, ∀ a, m ≺ a → a ≺ m := have ∃ ub, ∀ a ∈ max_chain, a ≺ ub, from h _ $ max_chain_spec.left, let ⟨ub, (hub : ∀ a ∈ max_chain, a ≺ ub)⟩ := this in ⟨ub, λ a ha, have chain (insert a max_chain), from chain_insert max_chain_spec.left $ λ b hb _, or.inr $ trans (hub b hb) ha, have a ∈ max_chain, from classical.by_contradiction $ λ h : a ∉ max_chain, max_chain_spec.right $ ⟨insert a max_chain, this, ssubset_insert h⟩, hub a this⟩ /-- A variant of Zorn's lemma. If every nonempty chain of a nonempty type has an upper bound, then there is a maximal element. -/ theorem exists_maximal_of_nonempty_chains_bounded [nonempty α] (h : ∀ c, chain c → c.nonempty → ∃ ub, ∀ a ∈ c, a ≺ ub) (trans : ∀ {a b c}, a ≺ b → b ≺ c → a ≺ c) : ∃ m, ∀ a, m ≺ a → a ≺ m := exists_maximal_of_chains_bounded (λ c hc, (eq_empty_or_nonempty c).elim (λ h, ⟨classical.arbitrary α, λ x hx, (h ▸ hx : x ∈ (∅ : set α)).elim⟩) (h c hc)) (λ a b c, trans) end chain --This lemma isn't under section `chain` because `parameters` messes up with it. Feel free to fix it /-- This can be used to turn `zorn.chain (≥)` into `zorn.chain (≤)` and vice-versa. -/ lemma chain.symm {α : Type u} {s : set α} {q : α → α → Prop} (h : chain q s) : chain (flip q) s := h.mono' (λ _ _, or.symm) theorem zorn_partial_order {α : Type u} [partial_order α] (h : ∀ c : set α, chain (≤) c → ∃ ub, ∀ a ∈ c, a ≤ ub) : ∃ m : α, ∀ a, m ≤ a → a = m := let ⟨m, hm⟩ := @exists_maximal_of_chains_bounded α (≤) h (λ a b c, le_trans) in ⟨m, λ a ha, le_antisymm (hm a ha) ha⟩ theorem zorn_nonempty_partial_order {α : Type u} [partial_order α] [nonempty α] (h : ∀ (c : set α), chain (≤) c → c.nonempty → ∃ ub, ∀ a ∈ c, a ≤ ub) : ∃ (m : α), ∀ a, m ≤ a → a = m := let ⟨m, hm⟩ := @exists_maximal_of_nonempty_chains_bounded α (≤) _ h (λ a b c, le_trans) in ⟨m, λ a ha, le_antisymm (hm a ha) ha⟩ theorem zorn_partial_order₀ {α : Type u} [partial_order α] (s : set α) (ih : ∀ c ⊆ s, chain (≤) c → ∃ ub ∈ s, ∀ z ∈ c, z ≤ ub) : ∃ m ∈ s, ∀ z ∈ s, m ≤ z → z = m := let ⟨⟨m, hms⟩, h⟩ := @zorn_partial_order {m // m ∈ s} _ (λ c hc, let ⟨ub, hubs, hub⟩ := ih (subtype.val '' c) (λ _ ⟨⟨x, hx⟩, _, h⟩, h ▸ hx) (by { rintro _ ⟨p, hpc, rfl⟩ _ ⟨q, hqc, rfl⟩ hpq; refine hc _ hpc _ hqc (λ t, hpq (subtype.ext_iff.1 t)) }) in ⟨⟨ub, hubs⟩, λ ⟨y, hy⟩ hc, hub _ ⟨_, hc, rfl⟩⟩) in ⟨m, hms, λ z hzs hmz, congr_arg subtype.val (h ⟨z, hzs⟩ hmz)⟩ theorem zorn_nonempty_partial_order₀ {α : Type u} [partial_order α] (s : set α) (ih : ∀ c ⊆ s, chain (≤) c → ∀ y ∈ c, ∃ ub ∈ s, ∀ z ∈ c, z ≤ ub) (x : α) (hxs : x ∈ s) : ∃ m ∈ s, x ≤ m ∧ ∀ z ∈ s, m ≤ z → z = m := let ⟨⟨m, hms, hxm⟩, h⟩ := @zorn_partial_order {m // m ∈ s ∧ x ≤ m} _ (λ c hc, c.eq_empty_or_nonempty.elim (λ hce, hce.symm ▸ ⟨⟨x, hxs, le_refl _⟩, λ _, false.elim⟩) (λ ⟨m, hmc⟩, let ⟨ub, hubs, hub⟩ := ih (subtype.val '' c) (image_subset_iff.2 $ λ z hzc, z.2.1) (by rintro _ ⟨p, hpc, rfl⟩ _ ⟨q, hqc, rfl⟩ hpq; exact hc p hpc q hqc (mt (by rintro rfl; refl) hpq)) m.1 (mem_image_of_mem _ hmc) in ⟨⟨ub, hubs, le_trans m.2.2 $ hub m.1 $ mem_image_of_mem _ hmc⟩, λ a hac, hub a.1 ⟨a, hac, rfl⟩⟩)) in ⟨m, hms, hxm, λ z hzs hmz, congr_arg subtype.val $ h ⟨z, hzs, le_trans hxm hmz⟩ hmz⟩ theorem zorn_subset {α : Type u} (S : set (set α)) (h : ∀ c ⊆ S, chain (⊆) c → ∃ ub ∈ S, ∀ s ∈ c, s ⊆ ub) : ∃ m ∈ S, ∀ a ∈ S, m ⊆ a → a = m := zorn_partial_order₀ S h theorem zorn_subset_nonempty {α : Type u} (S : set (set α)) (H : ∀ c ⊆ S, chain (⊆) c → c.nonempty → ∃ ub ∈ S, ∀ s ∈ c, s ⊆ ub) (x) (hx : x ∈ S) : ∃ m ∈ S, x ⊆ m ∧ ∀ a ∈ S, m ⊆ a → a = m := zorn_nonempty_partial_order₀ _ (λ c cS hc y yc, H _ cS hc ⟨y, yc⟩) _ hx theorem zorn_superset {α : Type u} (S : set (set α)) (h : ∀ c ⊆ S, chain (⊆) c → ∃ lb ∈ S, ∀ s ∈ c, lb ⊆ s) : ∃ m ∈ S, ∀ a ∈ S, a ⊆ m → a = m := @zorn_partial_order₀ (order_dual (set α)) _ S $ λ c cS hc, h c cS hc.symm theorem zorn_superset_nonempty {α : Type u} (S : set (set α)) (H : ∀ c ⊆ S, chain (⊆) c → c.nonempty → ∃ lb ∈ S, ∀ s ∈ c, lb ⊆ s) (x) (hx : x ∈ S) : ∃ m ∈ S, m ⊆ x ∧ ∀ a ∈ S, a ⊆ m → a = m := @zorn_nonempty_partial_order₀ (order_dual (set α)) _ S (λ c cS hc y yc, H _ cS hc.symm ⟨y, yc⟩) _ hx lemma chain.total {α : Type u} [preorder α] {c : set α} (H : chain (≤) c) : ∀ {x y}, x ∈ c → y ∈ c → x ≤ y ∨ y ≤ x := λ x y, H.total_of_refl lemma chain.image {α β : Type*} (r : α → α → Prop) (s : β → β → Prop) (f : α → β) (h : ∀ x y, r x y → s (f x) (f y)) {c : set α} (hrc : chain r c) : chain s (f '' c) := λ x ⟨a, ha₁, ha₂⟩ y ⟨b, hb₁, hb₂⟩, ha₂ ▸ hb₂ ▸ λ hxy, (hrc a ha₁ b hb₁ (mt (congr_arg f) $ hxy)).elim (or.inl ∘ h _ _) (or.inr ∘ h _ _) end zorn lemma directed_of_chain {α β r} [is_refl β r] {f : α → β} {c : set α} (h : zorn.chain (f ⁻¹'o r) c) : directed r (λ x : {a : α // a ∈ c}, f x) := λ ⟨a, ha⟩ ⟨b, hb⟩, classical.by_cases (λ hab : a = b, by simp only [hab, exists_prop, and_self, subtype.exists]; exact ⟨b, hb, refl _⟩) (λ hab, (h a ha b hb hab).elim (λ h : r (f a) (f b), ⟨⟨b, hb⟩, h, refl _⟩) (λ h : r (f b) (f a), ⟨⟨a, ha⟩, refl _, h⟩))
56f700d286a1da2212ba573f3e50084eef21c701
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/pkg/user_ext/UserExt/BlaExt.lean
318692f11e107ef5a94b1cc7adf104cd550a85e4
[ "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
728
lean
import Lean open Lean initialize blaExtension : SimplePersistentEnvExtension Name NameSet ← registerSimplePersistentEnvExtension { addEntryFn := NameSet.insert addImportedFn := fun es => mkStateFromImportedEntries NameSet.insert {} es } syntax (name := insertBla) "insert_bla " ident : command syntax (name := showBla) "show_bla_set" : command open Lean.Elab open Lean.Elab.Command @[command_elab insertBla] def elabInsertBla : CommandElab := fun stx => do IO.println s!"inserting {stx[1].getId}" modifyEnv fun env => blaExtension.addEntry env stx[1].getId @[command_elab showBla] def elabShowBla : CommandElab := fun stx => do IO.println s!"bla set: {blaExtension.getState (← getEnv) |>.toList}"
883bc733c65d0e38f9d6e8d95fffc6e082a44490
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/monadControl.lean
a421c23668067a05c8fd32e582c994fe00094c29
[ "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
1,220
lean
@[inline] def f {α} (s : String) (x : IO α) : IO α := do IO.println "started"; IO.println s; let a ← x; IO.println ("ended"); pure a @[inline] def f'' {α m} [MonadControlT IO m] [Monad m] (msg : String) (x : m α) : m α := do controlAt IO fun runInBase => f msg (runInBase x) abbrev M := StateT Bool $ ExceptT String $ StateT String $ ReaderT Nat $ StateT Nat IO def tst : M Nat := do let a ← f'' "hello" do { let s ← getThe Nat; let ctx ← read; modifyThe Nat fun s => s + ctx; if s > 10 then { throw "ERROR" }; getThe Nat }; modifyThe Nat Nat.succ; pure a #eval (((tst.run true).run "world").run 1000).run 11 @[inline] def g {α} (s : String) (x : Nat → IO α) : IO α := do IO.println "started"; IO.println s; let a ← x s.length; IO.println ("ended"); pure a @[inline] def g' {α m} [MonadControlT IO m] [Monad m] (msg : String) (x : Nat → m α) : m α := do controlAt IO fun runInBase => g msg (fun n => runInBase (x n)) def tst2 : M Nat := do let a ← g' "hello" fun x => do { let s ← getThe Nat; let ctx ← read; modifyThe Nat fun s => s + ctx + x; if s > 10 then { throw "ERROR" }; getThe Nat }; modifyThe Nat Nat.succ; pure a #eval (((tst2.run true).run "world").run 1000).run 10
e16e949cca9c53f0301f4c6c176690087f685b7b
0003047346476c031128723dfd16fe273c6bc605
/src/number_theory/sum_two_squares.lean
7f65a3c420f5b80300499b85ddd25542b1d7b49f
[ "Apache-2.0" ]
permissive
ChandanKSingh/mathlib
d2bf4724ccc670bf24915c12c475748281d3fb73
d60d1616958787ccb9842dc943534f90ea0bab64
refs/heads/master
1,588,238,823,679
1,552,867,469,000
1,552,867,469,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,147
lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Chris Hughes Proof of Fermat's theorem on the sum of two squares. Every prime congruent to 1 mod 4 is the sum of two squares -/ import data.gaussian_int data.zmod.quadratic_reciprocity ring_theory.principal_ideal_domain open gaussian_int principal_ideal_domain zsqrtd local notation `ℤ[i]` := gaussian_int namespace nat namespace prime lemma sum_two_squares {p : ℕ} (hp : p.prime) (hp1 : p % 4 = 1) : ∃ a b : ℕ, a ^ 2 + b ^ 2 = p := let ⟨k, hk⟩ := (zmodp.exists_pow_two_eq_neg_one_iff_mod_four_ne_three hp).2 $ by rw hp1; exact dec_trivial in have hpk : p ∣ k.val ^ 2 + 1, by rw [← zmodp.eq_zero_iff_dvd_nat hp]; simp *, have hkmul : (k.val ^ 2 + 1 : ℤ[i]) = ⟨k.val, 1⟩ * ⟨k.val, -1⟩ := by simp [_root_.pow_two, zsqrtd.ext], have hpne1 : p ≠ 1, from (ne_of_lt (hp.gt_one)).symm, have hkltp : 1 + k.val * k.val < p * p, from calc 1 + k.val * k.val ≤ k.val + k.val * k.val : add_le_add_right (nat.pos_of_ne_zero (λ hk0, by clear_aux_decl; simp [*, nat.pow_succ] at *)) _ ... = k.val * (k.val + 1) : by simp [mul_add] ... < p * p : mul_lt_mul k.2 k.2 (nat.succ_pos _) (nat.zero_le _), have hpk₁ : ¬ (p : ℤ[i]) ∣ ⟨k.val, -1⟩ := λ ⟨x, hx⟩, lt_irrefl (p * x : ℤ[i]).norm.nat_abs $ calc (norm (p * x : ℤ[i])).nat_abs = (norm ⟨k.val, -1⟩).nat_abs : by rw hx ... < (norm (p : ℤ[i])).nat_abs : by simpa [norm] using hkltp ... ≤ (norm (p * x : ℤ[i])).nat_abs : norm_le_norm_mul_left _ (λ hx0, (show (-1 : ℤ) ≠ 0, from dec_trivial) $ by simpa [hx0] using congr_arg zsqrtd.im hx), have hpk₂ : ¬ (p : ℤ[i]) ∣ ⟨k.val, 1⟩ := λ ⟨x, hx⟩, lt_irrefl (p * x : ℤ[i]).norm.nat_abs $ calc (norm (p * x : ℤ[i])).nat_abs = (norm ⟨k.val, 1⟩).nat_abs : by rw hx ... < (norm (p : ℤ[i])).nat_abs : by simpa [norm] using hkltp ... ≤ (norm (p * x : ℤ[i])).nat_abs : norm_le_norm_mul_left _ (λ hx0, (show (1 : ℤ) ≠ 0, from dec_trivial) $ by simpa [hx0] using congr_arg zsqrtd.im hx), have hpu : ¬ is_unit (p : ℤ[i]), from mt norm_eq_one_iff.2 $ by rw [norm_nat_cast, int.nat_abs_mul, nat.mul_eq_one_iff]; exact λ h, (ne_of_lt hp.gt_one).symm h.1, let ⟨y, hy⟩ := hpk in have hpi : ¬ irreducible (p : ℤ[i]), from mt irreducible_iff_prime.1 (λ hp, by have := hp.2.2 ⟨k.val, 1⟩ ⟨k.val, -1⟩ ⟨y, by rw [← hkmul, ← nat.cast_mul p, ← hy]; simp⟩; clear_aux_decl; tauto), have hab : ∃ a b, (p : ℤ[i]) = a * b ∧ ¬ is_unit a ∧ ¬ is_unit b, by simpa [irreducible, hpu, classical.not_forall, not_or_distrib] using hpi, let ⟨a, b, hpab, hau, hbu⟩ := hab in have hnap : (norm a).nat_abs = p, from ((hp.mul_eq_prime_pow_two_iff (mt norm_eq_one_iff.1 hau) (mt norm_eq_one_iff.1 hbu)).1 $ by rw [← int.coe_nat_inj', int.coe_nat_pow, _root_.pow_two, ← @norm_nat_cast (-1), hpab]; simp).1, ⟨a.re.nat_abs, a.im.nat_abs, by simpa [nat_abs_norm_eq, pow_two] using hnap⟩ end prime end nat
9b59d7588c60b49983a9496cd2996778620de986
07c76fbd96ea1786cc6392fa834be62643cea420
/hott/algebra/default.hlean
1ab8558abd8318c883e2616a3c1f3f4ac56ca09f
[ "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
219
hlean
/- Copyright (c) 2016 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import .homotopy_group .ordered_field .lattice .group_power
027695b7a9a34f259db693eaa0fc3d49f1db84d4
94e33a31faa76775069b071adea97e86e218a8ee
/src/analysis/calculus/formal_multilinear_series.lean
0bd5f0927c5e01895ed0a50a76ee1c5f198dae7a
[ "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
6,950
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.normed_space.multilinear /-! # Formal multilinear series In this file we define `formal_multilinear_series 𝕜 E F` to be a family of `n`-multilinear maps for all `n`, designed to model the sequence of derivatives of a function. In other files we use this notion to define `C^n` functions (called `cont_diff` in `mathlib`) and analytic functions. ## Notations We use the notation `E [×n]→L[𝕜] F` for the space of continuous multilinear maps on `E^n` with values in `F`. This is the space in which the `n`-th derivative of a function from `E` to `F` lives. ## Tags multilinear, formal series -/ noncomputable theory open set fin open_locale topological_space variables {𝕜 𝕜' E F G : Type*} section variables [comm_ring 𝕜] [add_comm_group E] [module 𝕜 E] [topological_space E] [topological_add_group E] [has_continuous_const_smul 𝕜 E] [add_comm_group F] [module 𝕜 F] [topological_space F] [topological_add_group F] [has_continuous_const_smul 𝕜 F] [add_comm_group G] [module 𝕜 G] [topological_space G] [topological_add_group G] [has_continuous_const_smul 𝕜 G] /-- A formal multilinear series over a field `𝕜`, from `E` to `F`, is given by a family of multilinear maps from `E^n` to `F` for all `n`. -/ @[derive add_comm_group, nolint unused_arguments] def formal_multilinear_series (𝕜 : Type*) (E : Type*) (F : Type*) [ring 𝕜] [add_comm_group E] [module 𝕜 E] [topological_space E] [topological_add_group E] [has_continuous_const_smul 𝕜 E] [add_comm_group F] [module 𝕜 F] [topological_space F] [topological_add_group F] [has_continuous_const_smul 𝕜 F] := Π (n : ℕ), (E [×n]→L[𝕜] F) instance : inhabited (formal_multilinear_series 𝕜 E F) := ⟨0⟩ section module /- `derive` is not able to find the module structure, probably because Lean is confused by the dependent types. We register it explicitly. -/ instance : module 𝕜 (formal_multilinear_series 𝕜 E F) := begin letI : Π n, module 𝕜 (continuous_multilinear_map 𝕜 (λ (i : fin n), E) F) := λ n, by apply_instance, refine pi.module _ _ _, end end module namespace formal_multilinear_series /-- Killing the zeroth coefficient in a formal multilinear series -/ def remove_zero (p : formal_multilinear_series 𝕜 E F) : formal_multilinear_series 𝕜 E F | 0 := 0 | (n + 1) := p (n + 1) @[simp] lemma remove_zero_coeff_zero (p : formal_multilinear_series 𝕜 E F) : p.remove_zero 0 = 0 := rfl @[simp] lemma remove_zero_coeff_succ (p : formal_multilinear_series 𝕜 E F) (n : ℕ) : p.remove_zero (n+1) = p (n+1) := rfl lemma remove_zero_of_pos (p : formal_multilinear_series 𝕜 E F) {n : ℕ} (h : 0 < n) : p.remove_zero n = p n := by { rw ← nat.succ_pred_eq_of_pos h, refl } /-- Convenience congruence lemma stating in a dependent setting that, if the arguments to a formal multilinear series are equal, then the values are also equal. -/ lemma congr (p : formal_multilinear_series 𝕜 E F) {m n : ℕ} {v : fin m → E} {w : fin n → E} (h1 : m = n) (h2 : ∀ (i : ℕ) (him : i < m) (hin : i < n), v ⟨i, him⟩ = w ⟨i, hin⟩) : p m v = p n w := by { cases h1, congr' with ⟨i, hi⟩, exact h2 i hi hi } /-- Composing each term `pₙ` in a formal multilinear series with `(u, ..., u)` where `u` is a fixed continuous linear map, gives a new formal multilinear series `p.comp_continuous_linear_map u`. -/ def comp_continuous_linear_map (p : formal_multilinear_series 𝕜 F G) (u : E →L[𝕜] F) : formal_multilinear_series 𝕜 E G := λ n, (p n).comp_continuous_linear_map (λ (i : fin n), u) @[simp] lemma comp_continuous_linear_map_apply (p : formal_multilinear_series 𝕜 F G) (u : E →L[𝕜] F) (n : ℕ) (v : fin n → E) : (p.comp_continuous_linear_map u) n v = p n (u ∘ v) := rfl variables (𝕜) [comm_ring 𝕜'] [has_smul 𝕜 𝕜'] variables [module 𝕜' E] [has_continuous_const_smul 𝕜' E] [is_scalar_tower 𝕜 𝕜' E] variables [module 𝕜' F] [has_continuous_const_smul 𝕜' F] [is_scalar_tower 𝕜 𝕜' F] /-- Reinterpret a formal `𝕜'`-multilinear series as a formal `𝕜`-multilinear series. -/ @[simp] protected def restrict_scalars (p : formal_multilinear_series 𝕜' E F) : formal_multilinear_series 𝕜 E F := λ n, (p n).restrict_scalars 𝕜 end formal_multilinear_series end namespace formal_multilinear_series variables [nondiscrete_normed_field 𝕜] [normed_group E] [normed_space 𝕜 E] [normed_group F] [normed_space 𝕜 F] [normed_group G] [normed_space 𝕜 G] variables (p : formal_multilinear_series 𝕜 E F) /-- Forgetting the zeroth term in a formal multilinear series, and interpreting the following terms as multilinear maps into `E →L[𝕜] F`. If `p` corresponds to the Taylor series of a function, then `p.shift` is the Taylor series of the derivative of the function. -/ def shift : formal_multilinear_series 𝕜 E (E →L[𝕜] F) := λn, (p n.succ).curry_right /-- Adding a zeroth term to a formal multilinear series taking values in `E →L[𝕜] F`. This corresponds to starting from a Taylor series for the derivative of a function, and building a Taylor series for the function itself. -/ def unshift (q : formal_multilinear_series 𝕜 E (E →L[𝕜] F)) (z : F) : formal_multilinear_series 𝕜 E F | 0 := (continuous_multilinear_curry_fin0 𝕜 E F).symm z | (n + 1) := continuous_multilinear_curry_right_equiv' 𝕜 n E F (q n) end formal_multilinear_series namespace continuous_linear_map variables [comm_ring 𝕜] [add_comm_group E] [module 𝕜 E] [topological_space E] [topological_add_group E] [has_continuous_const_smul 𝕜 E] [add_comm_group F] [module 𝕜 F] [topological_space F] [topological_add_group F] [has_continuous_const_smul 𝕜 F] [add_comm_group G] [module 𝕜 G] [topological_space G] [topological_add_group G] [has_continuous_const_smul 𝕜 G] /-- Composing each term `pₙ` in a formal multilinear series with a continuous linear map `f` on the left gives a new formal multilinear series `f.comp_formal_multilinear_series p` whose general term is `f ∘ pₙ`. -/ def comp_formal_multilinear_series (f : F →L[𝕜] G) (p : formal_multilinear_series 𝕜 E F) : formal_multilinear_series 𝕜 E G := λ n, f.comp_continuous_multilinear_map (p n) @[simp] lemma comp_formal_multilinear_series_apply (f : F →L[𝕜] G) (p : formal_multilinear_series 𝕜 E F) (n : ℕ) : (f.comp_formal_multilinear_series p) n = f.comp_continuous_multilinear_map (p n) := rfl lemma comp_formal_multilinear_series_apply' (f : F →L[𝕜] G) (p : formal_multilinear_series 𝕜 E F) (n : ℕ) (v : fin n → E) : (f.comp_formal_multilinear_series p) n v = f (p n v) := rfl end continuous_linear_map
3eacf94d542be3cd3558ebc2b378cc4eebead2a0
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/data/int/interval.lean
02996fc040fbfd4e25bfa030bcbfc48b5dace53d
[ "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
5,729
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 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
042af46d929c9e4bf68cf0fc15e41c1c90e15a7c
32da3d0f92cab08875472ef6cacc1931c2b3eafa
/src/algebra/linear_ordered_comm_group_with_zero.lean
ad07979d3443e76576f45428d421d9d6814ccf3a
[ "Apache-2.0" ]
permissive
karthiknadig/mathlib
b6073c3748860bfc9a3e55da86afcddba62dc913
33a86cfff12d7f200d0010cd03b95e9b69a6c1a5
refs/heads/master
1,676,389,371,851
1,610,061,127,000
1,610,061,127,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,948
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Johan Commelin, Patrick Massot -/ import algebra.ordered_group import algebra.group_with_zero import algebra.group_with_zero.power import tactic.abel /-! # Linearly ordered commutative groups with a zero element adjoined This file sets up a special class of linearly ordered commutative monoids that show up as the target of so-called “valuations” in algebraic number theory. Usually, in the informal literature, these objects are constructed by taking a linearly ordered commutative group Γ and formally adjoining a zero element: Γ ∪ {0}. The disadvantage is that a type such as `nnreal` is not of that form, whereas it is a very common target for valuations. The solutions is to use a typeclass, and that is exactly what we do in this file. -/ set_option old_structure_cmd true /-- A linearly ordered commutative group with a zero element. -/ class linear_ordered_comm_group_with_zero (α : Type*) extends linear_order α, comm_group_with_zero α := (mul_le_mul_left : ∀ {a b : α}, a ≤ b → ∀ c : α, c * a ≤ c * b) (zero_le_one : (0:α) ≤ 1) variables {α : Type*} [linear_ordered_comm_group_with_zero α] variables {a b c d x y z : α} local attribute [instance] classical.prop_decidable /-- Every linearly ordered commutative group with zero is an ordered commutative monoid.-/ @[priority 100] -- see Note [lower instance priority] instance linear_ordered_comm_group_with_zero.to_ordered_comm_monoid : ordered_comm_monoid α := { lt_of_mul_lt_mul_left := λ a b c h, by { contrapose! h, exact linear_ordered_comm_group_with_zero.mul_le_mul_left h a } .. ‹linear_ordered_comm_group_with_zero α› } section linear_ordered_comm_monoid /- The following facts are true more generally in a (linearly) ordered commutative monoid. -/ lemma one_le_pow_of_one_le' {n : ℕ} (H : 1 ≤ x) : 1 ≤ x^n := begin induction n with n ih, { exact le_refl 1 }, { exact one_le_mul H ih } end lemma pow_le_one_of_le_one {n : ℕ} (H : x ≤ 1) : x^n ≤ 1 := begin induction n with n ih, { exact le_refl 1 }, { exact mul_le_one' H ih } end lemma eq_one_of_pow_eq_one {n : ℕ} (hn : n ≠ 0) (H : x ^ n = 1) : x = 1 := begin rcases nat.exists_eq_succ_of_ne_zero hn with ⟨n, rfl⟩, clear hn, induction n with n ih, { simpa using H }, { cases le_total x 1 with h, all_goals { have h1 := mul_le_mul_right' h (x ^ (n + 1)), rw pow_succ at H, rw [H, one_mul] at h1 }, { have h2 := pow_le_one_of_le_one h, exact ih (le_antisymm h2 h1) }, { have h2 := one_le_pow_of_one_le' h, exact ih (le_antisymm h1 h2) } } end lemma pow_eq_one_iff {n : ℕ} (hn : n ≠ 0) : x ^ n = 1 ↔ x = 1 := ⟨eq_one_of_pow_eq_one hn, by { rintro rfl, exact one_pow _ }⟩ lemma one_le_pow_iff {n : ℕ} (hn : n ≠ 0) : 1 ≤ x^n ↔ 1 ≤ x := begin refine ⟨_, one_le_pow_of_one_le'⟩, contrapose!, intro h, apply lt_of_le_of_ne (pow_le_one_of_le_one (le_of_lt h)), rw [ne.def, pow_eq_one_iff hn], exact ne_of_lt h, end lemma pow_le_one_iff {n : ℕ} (hn : n ≠ 0) : x^n ≤ 1 ↔ x ≤ 1 := begin refine ⟨_, pow_le_one_of_le_one⟩, contrapose!, intro h, apply lt_of_le_of_ne (one_le_pow_of_one_le' (le_of_lt h)), rw [ne.def, eq_comm, pow_eq_one_iff hn], exact ne_of_gt h, end end linear_ordered_comm_monoid lemma zero_le_one' : (0 : α) ≤ 1 := linear_ordered_comm_group_with_zero.zero_le_one lemma zero_lt_one'' : (0 : α) < 1 := lt_of_le_of_ne zero_le_one' zero_ne_one @[simp] lemma zero_le' : 0 ≤ a := by simpa only [mul_zero, mul_one] using mul_le_mul_left' (@zero_le_one' α _) a @[simp] lemma not_lt_zero' : ¬a < 0 := not_lt_of_le zero_le' @[simp] lemma le_zero_iff : a ≤ 0 ↔ a = 0 := ⟨λ h, le_antisymm h zero_le', λ h, h ▸ le_refl _⟩ lemma zero_lt_iff : 0 < a ↔ a ≠ 0 := ⟨ne_of_gt, λ h, lt_of_le_of_ne zero_le' h.symm⟩ lemma le_of_le_mul_right (h : c ≠ 0) (hab : a * c ≤ b * c) : a ≤ b := by simpa only [mul_inv_cancel_right' h] using (mul_le_mul_right' hab c⁻¹) lemma le_mul_inv_of_mul_le (h : c ≠ 0) (hab : a * c ≤ b) : a ≤ b * c⁻¹ := le_of_le_mul_right h (by simpa [h] using hab) lemma mul_inv_le_of_le_mul (h : c ≠ 0) (hab : a ≤ b * c) : a * c⁻¹ ≤ b := le_of_le_mul_right h (by simpa [h] using hab) lemma div_le_div' (a b c d : α) (hb : b ≠ 0) (hd : d ≠ 0) : a * b⁻¹ ≤ c * d⁻¹ ↔ a * d ≤ c * b := begin by_cases ha : a = 0, { simp [ha] }, by_cases hc : c = 0, { simp [inv_ne_zero hb, hc, hd], }, exact @div_le_div_iff' _ _ (units.mk0 a ha) (units.mk0 b hb) (units.mk0 c hc) (units.mk0 d hd) end lemma ne_zero_of_lt (h : b < a) : a ≠ 0 := λ h1, not_lt_zero' $ show b < 0, from h1 ▸ h @[simp] lemma units.zero_lt (u : units α) : (0 : α) < u := zero_lt_iff.2 $ u.ne_zero lemma mul_lt_mul'''' (hab : a < b) (hcd : c < d) : a * c < b * d := have hb : b ≠ 0 := ne_zero_of_lt hab, have hd : d ≠ 0 := ne_zero_of_lt hcd, if ha : a = 0 then by { rw [ha, zero_mul, zero_lt_iff], exact mul_ne_zero hb hd } else if hc : c = 0 then by { rw [hc, mul_zero, zero_lt_iff], exact mul_ne_zero hb hd } else @mul_lt_mul''' _ _ (units.mk0 a ha) (units.mk0 b hb) (units.mk0 c hc) (units.mk0 d hd) hab hcd lemma mul_inv_lt_of_lt_mul' (h : x < y * z) : x * z⁻¹ < y := have hz : z ≠ 0 := (mul_ne_zero_iff.1 $ ne_zero_of_lt h).2, by { contrapose! h, simpa only [inv_inv'] using mul_inv_le_of_le_mul (inv_ne_zero hz) h } lemma mul_lt_right' (c : α) (h : a < b) (hc : c ≠ 0) : a * c < b * c := by { contrapose! h, exact le_of_le_mul_right hc h } lemma pow_lt_pow_succ {x : α} {n : ℕ} (hx : 1 < x) : x ^ n < x ^ n.succ := by { rw ← one_mul (x ^ n), exact mul_lt_right' _ hx (pow_ne_zero _ $ ne_of_gt (lt_trans zero_lt_one'' hx)) } lemma pow_lt_pow' {x : α} {m n : ℕ} (hx : 1 < x) (hmn : m < n) : x ^ m < x ^ n := by { induction hmn with n hmn ih, exacts [pow_lt_pow_succ hx, lt_trans ih (pow_lt_pow_succ hx)] } lemma inv_lt_inv'' (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ < b⁻¹ ↔ b < a := @inv_lt_inv_iff _ _ (units.mk0 a ha) (units.mk0 b hb) lemma inv_le_inv'' (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ ≤ b⁻¹ ↔ b ≤ a := @inv_le_inv_iff _ _ (units.mk0 a ha) (units.mk0 b hb) namespace monoid_hom variables {R : Type*} [ring R] (f : R →* α) theorem map_neg_one : f (-1) = 1 := begin apply eq_one_of_pow_eq_one (nat.succ_ne_zero 1) (_ : _ ^ 2 = _), rw [pow_two, ← f.map_mul, neg_one_mul, neg_neg, f.map_one], end @[simp] lemma map_neg (x : R) : f (-x) = f x := calc f (-x) = f (-1 * x) : by rw [neg_one_mul] ... = f (-1) * f x : map_mul _ _ _ ... = f x : by rw [f.map_neg_one, one_mul] lemma map_sub_swap (x y : R) : f (x - y) = f (y - x) := calc f (x - y) = f (-(y - x)) : by rw show x - y = -(y-x), by abel ... = _ : map_neg _ _ end monoid_hom
1326834965eb8d0b662814f4dc31863d6101828d
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/run/coeSort1.lean
176c8ed3a2c1668f8af0859821eabd50656cfe50
[ "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
288
lean
-- universe u def Below (n : Nat) : Nat → Prop := (· < n) def f {n : Nat} (v : Subtype (Below n)) : Nat := (coe v) + 1 instance pred2subtype {α : Type u} : CoeSort (α → Prop) (Type u) := CoeSort.mk (fun p => Subtype p) def g {n : Nat} (v : Below n) : Nat := v.val + 1
3fb085bef63fb6091e47ebb1f7440c001c6856c5
ad0c7d243dc1bd563419e2767ed42fb323d7beea
/tests/tidy.lean
0e29b9da3d4a1cc7a43ee063c404445dadf91f26
[ "Apache-2.0" ]
permissive
sebzim4500/mathlib
e0b5a63b1655f910dee30badf09bd7e191d3cf30
6997cafbd3a7325af5cb318561768c316ceb7757
refs/heads/master
1,585,549,958,618
1,538,221,723,000
1,538,221,723,000
150,869,076
0
0
Apache-2.0
1,538,229,323,000
1,538,229,323,000
null
UTF-8
Lean
false
false
1,097
lean
-- Copyright (c) 2018 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison import tactic.tidy open tactic namespace tidy.test meta def interactive_simp := `[simp] def tidy_test_0 : ∀ x : unit, x = unit.star := begin success_if_fail { chain [ interactive_simp ] }, intro1, induction x, refl end def tidy_test_1 (a : string): ∀ x : unit, x = unit.star := begin tidy -- intros x, exact dec_trivial end structure A := (z : ℕ) structure B := (a : A) (aa : a.z = 0) structure C := (a : A) (b : B) (ab : a.z = b.a.z) structure D := (a : B) (b : C) (ab : a.a.z = b.a.z) open tactic def d : D := begin tidy, -- /- obviously says -/ fsplit, work_on_goal 0 { fsplit, work_on_goal 0 { fsplit }, work_on_goal 1 { refl } }, work_on_goal 0 { fsplit, work_on_goal 0 { fsplit }, work_on_goal 1 { fsplit, work_on_goal 0 { fsplit }, work_on_goal 1 { refl } }, work_on_goal 1 { refl } }, refl end. def f : unit → unit → unit := by tidy -- intros a a_1, cases a_1, cases a, fsplit end tidy.test
beb096dbb2fd5c1e001282bd32c03f123fe5d06a
8e2026ac8a0660b5a490dfb895599fb445bb77a0
/tests/lean/run/io_process_echo.lean
5aa496957e03a7849af9b6a990f75ef21464d131
[ "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
188
lean
import system.io import system.process open process variable [io.interface] def main : io unit := do out ← io.cmd "echo" ["Hello World!"], io.put_str out, return () #eval main
b4bba59fbc3ec5215b034ff7aa0a84632b4a9479
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/idempotents/biproducts.lean
d7b432b0525ef85b10f5ab318fa7e8ffd90d4dd4
[ "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
6,089
lean
/- Copyright (c) 2022 Joël Riou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joël Riou -/ import category_theory.idempotents.karoubi import category_theory.additive.basic /-! # Biproducts in the idempotent completion of a preadditive category In this file, we define an instance expressing that if `C` is an additive category, then `karoubi C` is also an additive category. We also obtain that for all `P : karoubi C` where `C` is a preadditive category `C`, there is a canonical isomorphism `P ⊞ P.complement ≅ (to_karoubi C).obj P.X` in the category `karoubi C` where `P.complement` is the formal direct factor of `P.X` corresponding to the idempotent endomorphism `𝟙 P.X - P.p`. -/ noncomputable theory open category_theory.category open category_theory.limits open category_theory.preadditive universes v namespace category_theory namespace idempotents namespace karoubi variables {C : Type*} [category.{v} C] [preadditive C] namespace biproducts /-- The `bicone` used in order to obtain the existence of the biproduct of a functor `J ⥤ karoubi C` when the category `C` is additive. -/ @[simps] def bicone [has_finite_biproducts C] {J : Type v} [decidable_eq J] [fintype J] (F : J → karoubi C) : bicone F := { X := { X := biproduct (λ j, (F j).X), p := biproduct.map (λ j, (F j).p), idem := begin ext j, simp only [biproduct.ι_map_assoc, biproduct.ι_map], slice_lhs 1 2 { rw (F j).idem, }, end, }, π := λ j, { f := biproduct.map (λ j, (F j).p) ≫ bicone.π _ j, comm := by simp only [assoc, biproduct.bicone_π, biproduct.map_π, biproduct.map_π_assoc, (F j).idem], }, ι := λ j, { f := (by exact bicone.ι _ j) ≫ biproduct.map (λ j, (F j).p), comm := by rw [biproduct.ι_map, ← assoc, ← assoc, (F j).idem, assoc, biproduct.ι_map, ← assoc, (F j).idem], }, ι_π := λ j j', begin split_ifs, { subst h, simp only [biproduct.bicone_ι, biproduct.ι_map, biproduct.bicone_π, biproduct.ι_π_self_assoc, comp, category.assoc, eq_to_hom_refl, id_eq, biproduct.map_π, (F j).idem], }, { simpa only [hom_ext, biproduct.ι_π_ne_assoc _ h, assoc, biproduct.map_π, biproduct.map_π_assoc, zero_comp, comp], }, end, } end biproducts lemma karoubi_has_finite_biproducts [has_finite_biproducts C] : has_finite_biproducts (karoubi C) := { has_biproducts_of_shape := λ J hJ₁ hJ₂, { has_biproduct := λ F, begin letI := hJ₂, apply has_biproduct_of_total (biproducts.bicone F), ext1, ext1, simp only [id_eq, comp_id, biproducts.bicone_X_p, biproduct.ι_map], rw [sum_hom, comp_sum, finset.sum_eq_single j], rotate, { intros j' h1 h2, simp only [biproduct.ι_map, biproducts.bicone_ι_f, biproducts.bicone_π_f, assoc, comp, biproduct.map_π], slice_lhs 1 2 { rw biproduct.ι_π, }, split_ifs, { exfalso, exact h2 h.symm, }, { simp only [zero_comp], } }, { intro h, exfalso, simpa only [finset.mem_univ, not_true] using h, }, { simp only [biproducts.bicone_π_f, comp, biproduct.ι_map, assoc, biproducts.bicone_ι_f, biproduct.map_π], slice_lhs 1 2 { rw biproduct.ι_π, }, split_ifs, swap, { exfalso, exact h rfl, }, simp only [eq_to_hom_refl, id_comp, (F j).idem], }, end, } } instance {D : Type*} [category D] [additive_category D] : additive_category (karoubi D) := { to_preadditive := infer_instance, to_has_finite_biproducts := karoubi_has_finite_biproducts } /-- `P.complement` is the formal direct factor of `P.X` given by the idempotent endomorphism `𝟙 P.X - P.p` -/ @[simps] def complement (P : karoubi C) : karoubi C := { X := P.X, p := 𝟙 _ - P.p, idem := idem_of_id_sub_idem P.p P.idem, } instance (P : karoubi C) : has_binary_biproduct P P.complement := has_binary_biproduct_of_total { X := P.X, fst := P.decomp_id_p, snd := P.complement.decomp_id_p, inl := P.decomp_id_i, inr := P.complement.decomp_id_i, inl_fst' := P.decomp_id.symm, inl_snd' := begin simp only [decomp_id_i_f, decomp_id_p_f, complement_p, comp_sub, comp, hom_ext, quiver.hom.add_comm_group_zero_f, P.idem], erw [comp_id, sub_self], end, inr_fst' := begin simp only [decomp_id_i_f, complement_p, decomp_id_p_f, sub_comp, comp, hom_ext, quiver.hom.add_comm_group_zero_f, P.idem], erw [id_comp, sub_self], end, inr_snd' := P.complement.decomp_id.symm, } (by simp only [hom_ext, ← decomp_p, quiver.hom.add_comm_group_add_f, to_karoubi_map_f, id_eq, coe_p, complement_p, add_sub_cancel'_right]) /-- A formal direct factor `P : karoubi C` of an object `P.X : C` in a preadditive category is actually a direct factor of the image `(to_karoubi C).obj P.X` of `P.X` in the category `karoubi C` -/ def decomposition (P : karoubi C) : P ⊞ P.complement ≅ (to_karoubi _).obj P.X := { hom := biprod.desc P.decomp_id_i P.complement.decomp_id_i, inv := biprod.lift P.decomp_id_p P.complement.decomp_id_p, hom_inv_id' := begin ext1, { simp only [← assoc, biprod.inl_desc, comp_id, biprod.lift_eq, comp_add, ← decomp_id, id_comp, add_right_eq_self], convert zero_comp, ext, simp only [decomp_id_i_f, decomp_id_p_f, complement_p, comp_sub, comp, quiver.hom.add_comm_group_zero_f, P.idem], erw [comp_id, sub_self], }, { simp only [← assoc, biprod.inr_desc, biprod.lift_eq, comp_add, ← decomp_id, comp_id, id_comp, add_left_eq_self], convert zero_comp, ext, simp only [decomp_id_i_f, decomp_id_p_f, complement_p, sub_comp, comp, quiver.hom.add_comm_group_zero_f, P.idem], erw [id_comp, sub_self], } end, inv_hom_id' := begin rw biprod.lift_desc, simp only [← decomp_p], ext, dsimp only [complement, to_karoubi], simp only [quiver.hom.add_comm_group_add_f, add_sub_cancel'_right, id_eq], end, } end karoubi end idempotents end category_theory
0a6db6283eec603f490caca8739489ed8d5ac9fb
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch5/ex0202.lean
0384ec85796996a1accb131e66fb95de1c240e06
[]
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
149
lean
example (α : Type) : α → α := begin intro a, exact a end example (α : Type) : ∀ x : α, x = x := begin intro x, exact eq.refl x end
8b4f53f6ff2151d3642792e2daf5e83934c8db25
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/ring_theory/noetherian.lean
a9257710ef233b529b2e624b67c2e5739320568f
[ "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
34,740
lean
/- Copyright (c) 2018 Mario Carneiro, Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kevin Buzzard -/ import algebraic_geometry.prime_spectrum import data.multiset.finset_ops import linear_algebra.linear_independent import order.order_iso_nat import order.compactly_generated import ring_theory.ideal.operations import group_theory.finiteness /-! # Noetherian rings and modules The following are equivalent for a module M over a ring R: 1. Every increasing chain of submodules M₁ ⊆ M₂ ⊆ M₃ ⊆ ⋯ eventually stabilises. 2. Every submodule is finitely generated. A module satisfying these equivalent conditions is said to be a *Noetherian* R-module. A ring is a *Noetherian ring* if it is Noetherian as a module over itself. (Note that we do not assume yet that our rings are commutative, so perhaps this should be called "left Noetherian". To avoid cumbersome names once we specialize to the commutative case, we don't make this explicit in the declaration names.) ## Main definitions Let `R` be a ring and let `M` and `P` be `R`-modules. Let `N` be an `R`-submodule of `M`. * `fg N : Prop` is the assertion that `N` is finitely generated as an `R`-module. * `is_noetherian R M` is the proposition that `M` is a Noetherian `R`-module. It is a class, implemented as the predicate that all `R`-submodules of `M` are finitely generated. ## Main statements * `exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul` is Nakayama's lemma, in the following form: if N is a finitely generated submodule of an ambient R-module M and I is an ideal of R such that N ⊆ IN, then there exists r ∈ 1 + I such that rN = 0. * `is_noetherian_iff_well_founded` is the theorem that an R-module M is Noetherian iff `>` is well-founded on `submodule R M`. Note that the Hilbert basis theorem, that if a commutative ring R is Noetherian then so is R[X], is proved in `ring_theory.polynomial`. ## References * [M. F. Atiyah and I. G. Macdonald, *Introduction to commutative algebra*][atiyah-macdonald] * [samuel] ## Tags Noetherian, noetherian, Noetherian ring, Noetherian module, noetherian ring, noetherian module -/ open set open_locale big_operators namespace submodule variables {R : Type*} {M : Type*} [semiring R] [add_comm_monoid M] [module R M] /-- A submodule of `M` is finitely generated if it is the span of a finite subset of `M`. -/ def fg (N : submodule R M) : Prop := ∃ S : finset M, submodule.span R ↑S = N theorem fg_def {N : submodule R M} : N.fg ↔ ∃ S : set M, finite S ∧ span R 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_add_submonoid_fg (P : submodule ℕ M) : P.fg ↔ P.to_add_submonoid.fg := ⟨λ ⟨S, hS⟩, ⟨S, by simpa [← span_nat_eq_add_submonoid_closure] using hS⟩, λ ⟨S, hS⟩, ⟨S, by simpa [← span_nat_eq_add_submonoid_closure] using hS⟩⟩ lemma fg_iff_add_subgroup_fg {G : Type*} [add_comm_group G] (P : submodule ℤ G) : P.fg ↔ P.to_add_subgroup.fg := ⟨λ ⟨S, hS⟩, ⟨S, by simpa [← span_int_eq_add_subgroup_closure] using hS⟩, λ ⟨S, hS⟩, ⟨S, by simpa [← span_int_eq_add_subgroup_closure] using hS⟩⟩ lemma fg_iff_exists_fin_generating_family {N : submodule R M} : N.fg ↔ ∃ (n : ℕ) (s : fin n → M), span R (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 /-- Nakayama's Lemma. Atiyah-Macdonald 2.5, Eisenbud 4.7, Matsumura 2.2, Stacks 00DV -/ theorem exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul {R : Type*} [comm_ring R] {M : Type*} [add_comm_group M] [module R M] (I : ideal R) (N : submodule R M) (hn : N.fg) (hin : N ≤ I • N) : ∃ r : R, r - 1 ∈ I ∧ ∀ n ∈ N, r • n = (0 : M) := begin rw fg_def at hn, rcases hn with ⟨s, hfs, hs⟩, have : ∃ r : R, r - 1 ∈ I ∧ N ≤ (I • span R s).comap (linear_map.lsmul R M r) ∧ s ⊆ N, { refine ⟨1, _, _, _⟩, { rw sub_self, exact I.zero_mem }, { rw [hs], intros n hn, rw [mem_comap], change (1:R) • n ∈ I • N, rw one_smul, exact hin hn }, { rw [← span_le, hs], exact le_refl N } }, clear hin hs, revert this, refine set.finite.dinduction_on hfs (λ H, _) (λ i s his hfs ih H, _), { rcases H with ⟨r, hr1, hrn, hs⟩, refine ⟨r, hr1, λ n hn, _⟩, specialize hrn hn, rwa [mem_comap, span_empty, smul_bot, mem_bot] at hrn }, apply ih, rcases H with ⟨r, hr1, hrn, hs⟩, rw [← set.singleton_union, span_union, smul_sup] at hrn, rw [set.insert_subset] at hs, have : ∃ c : R, c - 1 ∈ I ∧ c • i ∈ I • span R s, { specialize hrn hs.1, rw [mem_comap, mem_sup] at hrn, rcases hrn with ⟨y, hy, z, hz, hyz⟩, change y + z = r • i at hyz, rw mem_smul_span_singleton at hy, rcases hy with ⟨c, hci, rfl⟩, use r-c, split, { rw [sub_right_comm], exact I.sub_mem hr1 hci }, { rw [sub_smul, ← hyz, add_sub_cancel'], exact hz } }, rcases this with ⟨c, hc1, hci⟩, refine ⟨c * r, _, _, hs.2⟩, { rw [← ideal.quotient.eq, ring_hom.map_one] at hr1 hc1 ⊢, rw [ring_hom.map_mul, hc1, hr1, mul_one] }, { intros n hn, specialize hrn hn, rw [mem_comap, mem_sup] at hrn, rcases hrn with ⟨y, hy, z, hz, hyz⟩, change y + z = r • n at hyz, rw mem_smul_span_singleton at hy, rcases hy with ⟨d, hdi, rfl⟩, change _ • _ ∈ I • span R s, rw [mul_smul, ← hyz, smul_add, smul_smul, mul_comm, mul_smul], exact add_mem _ (smul_mem _ _ hci) (smul_mem _ _ hz) } end theorem fg_bot : (⊥ : submodule R M).fg := ⟨∅, by rw [finset.coe_empty, span_empty]⟩ theorem fg_span {s : set M} (hs : finite s) : fg (span R s) := ⟨hs.to_finset, by rw [hs.coe_to_finset]⟩ theorem fg_span_singleton (x : M) : fg (R ∙ x) := fg_span (finite_singleton x) theorem fg_sup {N₁ N₂ : submodule R 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 [span_union, ht₁.2, ht₂.2]⟩ variables {P : Type*} [add_comm_monoid P] [module R P] variables {f : M →ₗ[R] P} theorem fg_map {N : submodule R M} (hs : N.fg) : (N.map f).fg := let ⟨t, ht⟩ := fg_def.1 hs in fg_def.2 ⟨f '' t, ht.1.image _, by rw [span_image, ht.2]⟩ lemma fg_of_fg_map {R M P : Type*} [ring R] [add_comm_group M] [module R M] [add_comm_group P] [module R P] (f : M →ₗ[R] P) (hf : f.ker = ⊥) {N : submodule R M} (hfn : (N.map f).fg) : N.fg := let ⟨t, ht⟩ := hfn in ⟨t.preimage f $ λ x _ y _ h, linear_map.ker_eq_bot.1 hf h, linear_map.map_injective hf $ by { rw [f.map_span, finset.coe_preimage, set.image_preimage_eq_inter_range, set.inter_eq_self_of_subset_left, ht], rw [← linear_map.range_coe, ← span_le, ht, ← map_top], exact map_mono le_top }⟩ lemma fg_top {R M : Type*} [ring R] [add_comm_group M] [module R M] (N : submodule R M) : (⊤ : submodule R N).fg ↔ N.fg := ⟨λ h, N.range_subtype ▸ map_top N.subtype ▸ fg_map h, λ h, fg_of_fg_map N.subtype N.ker_subtype $ by rwa [map_top, range_subtype]⟩ lemma fg_of_linear_equiv (e : M ≃ₗ[R] P) (h : (⊤ : submodule R P).fg) : (⊤ : submodule R M).fg := e.symm.range ▸ map_top (e.symm : P →ₗ[R] M) ▸ fg_map h theorem fg_prod {sb : submodule R M} {sc : submodule R P} (hsb : sb.fg) (hsc : sc.fg) : (sb.prod sc).fg := let ⟨tb, htb⟩ := fg_def.1 hsb, ⟨tc, htc⟩ := fg_def.1 hsc in fg_def.2 ⟨linear_map.inl R M P '' tb ∪ linear_map.inr R M P '' tc, (htb.1.image _).union (htc.1.image _), by rw [linear_map.span_inl_union_inr, htb.2, htc.2]⟩ /-- If 0 → M' → M → M'' → 0 is exact and M' and M'' are finitely generated then so is M. -/ theorem fg_of_fg_map_of_fg_inf_ker {R M P : Type*} [ring R] [add_comm_group M] [module R M] [add_comm_group P] [module R P] (f : M →ₗ[R] P) {s : submodule R M} (hs1 : (s.map f).fg) (hs2 : (s ⊓ f.ker).fg) : s.fg := begin haveI := classical.dec_eq R, haveI := classical.dec_eq M, haveI := classical.dec_eq P, cases hs1 with t1 ht1, cases hs2 with t2 ht2, have : ∀ y ∈ t1, ∃ x ∈ s, f x = y, { intros y hy, have : y ∈ map f s, { rw ← ht1, exact subset_span hy }, rcases mem_map.1 this with ⟨x, hx1, hx2⟩, exact ⟨x, hx1, hx2⟩ }, have : ∃ g : P → M, ∀ y ∈ t1, g y ∈ s ∧ f (g y) = y, { choose g hg1 hg2, existsi λ y, if H : y ∈ t1 then g y H else 0, intros y H, split, { simp only [dif_pos H], apply hg1 }, { simp only [dif_pos H], apply hg2 } }, cases this with g hg, clear this, existsi t1.image g ∪ t2, rw [finset.coe_union, span_union, finset.coe_image], apply le_antisymm, { refine sup_le (span_le.2 $ image_subset_iff.2 _) (span_le.2 _), { intros y hy, exact (hg y hy).1 }, { intros x hx, have := subset_span hx, rw ht2 at this, exact this.1 } }, intros x hx, have : f x ∈ map f s, { rw mem_map, exact ⟨x, hx, rfl⟩ }, rw [← ht1,← set.image_id ↑t1, finsupp.mem_span_image_iff_total] at this, rcases this with ⟨l, hl1, hl2⟩, refine mem_sup.2 ⟨(finsupp.total M M R id).to_fun ((finsupp.lmap_domain R R g : (P →₀ R) → M →₀ R) l), _, x - finsupp.total M M R id ((finsupp.lmap_domain R R g : (P →₀ R) → M →₀ R) l), _, add_sub_cancel'_right _ _⟩, { rw [← set.image_id (g '' ↑t1), finsupp.mem_span_image_iff_total], refine ⟨_, _, rfl⟩, haveI : inhabited P := ⟨0⟩, rw [← finsupp.lmap_domain_supported _ _ g, mem_map], refine ⟨l, hl1, _⟩, refl, }, rw [ht2, mem_inf], split, { apply s.sub_mem hx, rw [finsupp.total_apply, finsupp.lmap_domain_apply, finsupp.sum_map_domain_index], refine s.sum_mem _, { intros y hy, exact s.smul_mem _ (hg y (hl1 hy)).1 }, { exact zero_smul _ }, { exact λ _ _ _, add_smul _ _ _ } }, { rw [linear_map.mem_ker, f.map_sub, ← hl2], rw [finsupp.total_apply, finsupp.total_apply, finsupp.lmap_domain_apply], rw [finsupp.sum_map_domain_index, finsupp.sum, finsupp.sum, f.map_sum], rw sub_eq_zero, refine finset.sum_congr rfl (λ y hy, _), unfold id, rw [f.map_smul, (hg y (hl1 hy)).2], { exact zero_smul _ }, { exact λ _ _ _, add_smul _ _ _ } } end /-- The image of a finitely generated ideal is finitely generated. -/ lemma map_fg_of_fg {R S : Type*} [comm_ring R] [comm_ring S] (I : ideal R) (h : I.fg) (f : R →+* S) : (I.map f).fg := begin obtain ⟨X, hXfin, hXgen⟩ := fg_def.1 h, apply fg_def.2, refine ⟨set.image f X, finite.image ⇑f hXfin, _⟩, rw [ideal.map, ideal.span, ← hXgen], refine le_antisymm (submodule.span_mono (image_subset _ ideal.subset_span)) _, rw [submodule.span_le, image_subset_iff], intros i hi, refine submodule.span_induction hi (λ x hx, _) _ (λ x y hx hy, _) (λ r x hx, _), { simp only [set_like.mem_coe, mem_preimage], suffices : f x ∈ f '' X, { exact ideal.subset_span this }, exact mem_image_of_mem ⇑f hx }, { simp only [set_like.mem_coe, ring_hom.map_zero, mem_preimage, zero_mem] }, { simp only [set_like.mem_coe, mem_preimage] at hx hy, simp only [ring_hom.map_add, set_like.mem_coe, mem_preimage], exact submodule.add_mem _ hx hy }, { simp only [set_like.mem_coe, mem_preimage] at hx, simp only [algebra.id.smul_eq_mul, set_like.mem_coe, mem_preimage, ring_hom.map_mul], exact submodule.smul_mem _ _ hx } end /-- The kernel of the composition of two linear maps is finitely generated if both kernels are and the first morphism is surjective. -/ lemma fg_ker_comp {R M N P : Type*} [ring R] [add_comm_group M] [module R M] [add_comm_group N] [module R N] [add_comm_group P] [module R P] (f : M →ₗ[R] N) (g : N →ₗ[R] P) (hf1 : f.ker.fg) (hf2 : g.ker.fg) (hsur : function.surjective f) : (g.comp f).ker.fg := begin rw linear_map.ker_comp, apply fg_of_fg_map_of_fg_inf_ker f, { rwa [linear_map.map_comap_eq, linear_map.range_eq_top.2 hsur, top_inf_eq] }, { rwa [inf_of_le_right (show f.ker ≤ (comap f g.ker), from comap_mono (@bot_le _ _ g.ker))] } end lemma fg_restrict_scalars {R S M : Type*} [comm_ring R] [comm_ring S] [algebra R S] [add_comm_group M] [module S M] [module R M] [is_scalar_tower R S M] (N : submodule S M) (hfin : N.fg) (h : function.surjective (algebra_map R S)) : (submodule.restrict_scalars R N).fg := begin obtain ⟨X, rfl⟩ := hfin, use X, exact submodule.span_eq_restrict_scalars R S M X h end lemma fg_ker_ring_hom_comp {R S A : Type*} [comm_ring R] [comm_ring S] [comm_ring A] (f : R →+* S) (g : S →+* A) (hf : f.ker.fg) (hg : g.ker.fg) (hsur : function.surjective f) : (g.comp f).ker.fg := begin letI : algebra R S := ring_hom.to_algebra f, letI : algebra R A := ring_hom.to_algebra (g.comp f), letI : algebra S A := ring_hom.to_algebra g, letI : is_scalar_tower R S A := restrict_scalars.is_scalar_tower R S A, let f₁ := algebra.linear_map R S, let g₁ := (is_scalar_tower.to_alg_hom R S A).to_linear_map, exact fg_ker_comp f₁ g₁ hf (fg_restrict_scalars g.ker hg hsur) hsur end /-- Finitely generated submodules are precisely compact elements in the submodule lattice. -/ theorem fg_iff_compact (s : submodule R M) : s.fg ↔ complete_lattice.is_compact_element s := begin classical, -- Introduce shorthand for span of an element let sp : M → submodule R M := λ a, span R {a}, -- Trivial rewrite lemma; a small hack since simp (only) & rw can't accomplish this smoothly. have supr_rw : ∀ t : finset M, (⨆ x ∈ t, sp x) = (⨆ x ∈ (↑t : set M), sp x), from λ t, by refl, split, { rintro ⟨t, rfl⟩, rw [span_eq_supr_of_singleton_spans, ←supr_rw, ←(finset.sup_eq_supr t sp)], apply complete_lattice.finset_sup_compact_of_compact, exact λ n _, singleton_span_is_compact_element n, }, { intro h, -- s is the Sup of the spans of its elements. have sSup : s = Sup (sp '' ↑s), by rw [Sup_eq_supr, supr_image, ←span_eq_supr_of_singleton_spans, eq_comm, span_eq], -- by h, s is then below (and equal to) the sup of the spans of finitely many elements. obtain ⟨u, ⟨huspan, husup⟩⟩ := h (sp '' ↑s) (le_of_eq sSup), have ssup : s = u.sup id, { suffices : u.sup id ≤ s, from le_antisymm husup this, rw [sSup, finset.sup_id_eq_Sup], exact Sup_le_Sup huspan, }, obtain ⟨t, ⟨hts, rfl⟩⟩ := finset.subset_image_iff.mp huspan, rw [finset.sup_finset_image, function.comp.left_id, finset.sup_eq_supr, supr_rw, ←span_eq_supr_of_singleton_spans, eq_comm] at ssup, exact ⟨t, ssup⟩, }, end end submodule /-- `is_noetherian R M` is the proposition that `M` is a Noetherian `R`-module, implemented as the predicate that all `R`-submodules of `M` are finitely generated. -/ class is_noetherian (R M) [semiring R] [add_comm_monoid M] [module R M] : Prop := (noetherian : ∀ (s : submodule R M), s.fg) section variables {R : Type*} {M : Type*} {P : Type*} variables [ring R] [add_comm_group M] [add_comm_group P] variables [module R M] [module R P] open is_noetherian include R theorem is_noetherian_submodule {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, s ≤ N → s.fg := ⟨λ ⟨hn⟩, λ s hs, have s ≤ N.subtype.range, from (N.range_subtype).symm ▸ hs, linear_map.map_comap_eq_self this ▸ submodule.fg_map (hn _), λ h, ⟨λ s, submodule.fg_of_fg_map_of_fg_inf_ker N.subtype (h _ $ submodule.map_subtype_le _ _) $ by rw [submodule.ker_subtype, inf_bot_eq]; exact submodule.fg_bot⟩⟩ theorem is_noetherian_submodule_left {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, (N ⊓ s).fg := is_noetherian_submodule.trans ⟨λ H s, H _ inf_le_left, λ H s hs, (inf_of_le_right hs) ▸ H _⟩ theorem is_noetherian_submodule_right {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, (s ⊓ N).fg := is_noetherian_submodule.trans ⟨λ H s, H _ inf_le_right, λ H s hs, (inf_of_le_left hs) ▸ H _⟩ instance is_noetherian_submodule' [is_noetherian R M] (N : submodule R M) : is_noetherian R N := is_noetherian_submodule.2 $ λ _ _, is_noetherian.noetherian _ variable (M) theorem is_noetherian_of_surjective (f : M →ₗ[R] P) (hf : f.range = ⊤) [is_noetherian R M] : is_noetherian R P := ⟨λ s, have (s.comap f).map f = s, from linear_map.map_comap_eq_self $ hf.symm ▸ le_top, this ▸ submodule.fg_map $ noetherian _⟩ variable {M} theorem is_noetherian_of_linear_equiv (f : M ≃ₗ[R] P) [is_noetherian R M] : is_noetherian R P := is_noetherian_of_surjective _ f.to_linear_map f.range lemma is_noetherian_of_injective [is_noetherian R P] (f : M →ₗ[R] P) (hf : f.ker = ⊥) : is_noetherian R M := is_noetherian_of_linear_equiv (linear_equiv.of_injective f hf).symm lemma fg_of_injective [is_noetherian R P] {N : submodule R M} (f : M →ₗ[R] P) (hf : f.ker = ⊥) : N.fg := @@is_noetherian.noetherian _ _ _ (is_noetherian_of_injective f hf) N instance is_noetherian_prod [is_noetherian R M] [is_noetherian R P] : is_noetherian R (M × P) := ⟨λ s, submodule.fg_of_fg_map_of_fg_inf_ker (linear_map.snd R M P) (noetherian _) $ have s ⊓ linear_map.ker (linear_map.snd R M P) ≤ linear_map.range (linear_map.inl R M P), from λ x ⟨hx1, hx2⟩, ⟨x.1, prod.ext rfl $ eq.symm $ linear_map.mem_ker.1 hx2⟩, linear_map.map_comap_eq_self this ▸ submodule.fg_map (noetherian _)⟩ instance is_noetherian_pi {R ι : Type*} {M : ι → Type*} [ring R] [Π i, add_comm_group (M i)] [Π i, module R (M i)] [fintype ι] [∀ i, is_noetherian R (M i)] : is_noetherian R (Π i, M i) := begin haveI := classical.dec_eq ι, suffices on_finset : ∀ s : finset ι, is_noetherian R (Π i : s, M i), { let coe_e := equiv.subtype_univ_equiv finset.mem_univ, letI : is_noetherian R (Π i : finset.univ, M (coe_e i)) := on_finset finset.univ, exact is_noetherian_of_linear_equiv (linear_equiv.Pi_congr_left R M coe_e), }, intro s, induction s using finset.induction with a s has ih, { split, intro s, convert submodule.fg_bot, apply eq_bot_iff.2, intros x hx, refine (submodule.mem_bot R).2 _, ext i, cases i.2 }, refine @is_noetherian_of_linear_equiv _ _ _ _ _ _ _ _ _ (@is_noetherian_prod _ (M a) _ _ _ _ _ _ _ ih), fconstructor, { exact λ f i, or.by_cases (finset.mem_insert.1 i.2) (λ h : i.1 = a, show M i.1, from (eq.rec_on h.symm f.1)) (λ h : i.1 ∈ s, show M i.1, from f.2 ⟨i.1, h⟩) }, { intros f g, ext i, unfold or.by_cases, cases i with i hi, rcases finset.mem_insert.1 hi with rfl | h, { change _ = _ + _, simp only [dif_pos], refl }, { change _ = _ + _, have : ¬i = a, { rintro rfl, exact has h }, simp only [dif_neg this, dif_pos h], refl } }, { intros c f, ext i, unfold or.by_cases, cases i with i hi, rcases finset.mem_insert.1 hi with rfl | h, { change _ = c • _, simp only [dif_pos], refl }, { change _ = c • _, have : ¬i = a, { rintro rfl, exact has h }, simp only [dif_neg this, dif_pos h], refl } }, { exact λ f, (f ⟨a, finset.mem_insert_self _ _⟩, λ i, f ⟨i.1, finset.mem_insert_of_mem i.2⟩) }, { intro f, apply prod.ext, { simp only [or.by_cases, dif_pos] }, { ext ⟨i, his⟩, have : ¬i = a, { rintro rfl, exact has his }, dsimp only [or.by_cases], change i ∈ s at his, rw [dif_neg this, dif_pos his] } }, { intro f, ext ⟨i, hi⟩, rcases finset.mem_insert.1 hi with rfl | h, { simp only [or.by_cases, dif_pos], }, { have : ¬i = a, { rintro rfl, exact has h }, simp only [or.by_cases, dif_neg this, dif_pos h], } } end end open is_noetherian submodule function section variables {R M : Type*} [ring R] [add_comm_group M] [module R M] theorem is_noetherian_iff_well_founded : is_noetherian R M ↔ well_founded ((>) : submodule R M → submodule R M → Prop) := begin rw (complete_lattice.well_founded_characterisations $ submodule R M).out 0 3, exact ⟨λ ⟨h⟩, λ k, (fg_iff_compact k).mp (h k), λ h, ⟨λ k, (fg_iff_compact k).mpr (h k)⟩⟩, end variables (R M) lemma well_founded_submodule_gt (R M) [ring R] [add_comm_group M] [module R M] : ∀ [is_noetherian R M], well_founded ((>) : submodule R M → submodule R M → Prop) := is_noetherian_iff_well_founded.mp variables {R M} lemma finite_of_linear_independent [nontrivial R] [is_noetherian R M] {s : set M} (hs : linear_independent R (coe : s → M)) : s.finite := begin refine classical.by_contradiction (λ hf, rel_embedding.well_founded_iff_no_descending_seq.1 (well_founded_submodule_gt R M) ⟨_⟩), have f : ℕ ↪ s, from @infinite.nat_embedding s ⟨λ f, hf ⟨f⟩⟩, have : ∀ n, (coe ∘ f) '' {m | m ≤ n} ⊆ s, { rintros n x ⟨y, hy₁, hy₂⟩, subst hy₂, exact (f y).2 }, have : ∀ a b : ℕ, a ≤ b ↔ span R ((coe ∘ f) '' {m | m ≤ a}) ≤ span R ((coe ∘ f) '' {m | m ≤ b}), { assume a b, rw [span_le_span_iff hs (this a) (this b), set.image_subset_image_iff (subtype.coe_injective.comp f.injective), set.subset_def], exact ⟨λ hab x (hxa : x ≤ a), le_trans hxa hab, λ hx, hx a (le_refl a)⟩ }, exact ⟨⟨λ n, span R ((coe ∘ f) '' {m | m ≤ n}), λ x y, by simp [le_antisymm_iff, (this _ _).symm] {contextual := tt}⟩, by dsimp [gt]; simp only [lt_iff_le_not_le, (this _ _).symm]; tauto⟩ end /-- A module is Noetherian iff every nonempty set of submodules has a maximal submodule among them. -/ theorem set_has_maximal_iff_noetherian : (∀ a : set $ submodule R M, a.nonempty → ∃ M' ∈ a, ∀ I ∈ a, M' ≤ I → I = M') ↔ is_noetherian R M := by rw [is_noetherian_iff_well_founded, well_founded.well_founded_iff_has_max'] /-- A module is Noetherian iff every increasing chain of submodules stabilizes. -/ theorem monotone_stabilizes_iff_noetherian : (∀ (f : ℕ →ₘ submodule R M), ∃ n, ∀ m, n ≤ m → f n = f m) ↔ is_noetherian R M := by rw [is_noetherian_iff_well_founded, well_founded.monotone_chain_condition] /-- If `∀ I > J, P I` implies `P J`, then `P` holds for all submodules. -/ lemma is_noetherian.induction [is_noetherian R M] {P : submodule R M → Prop} (hgt : ∀ I, (∀ J > I, P J) → P I) (I : submodule R M) : P I := well_founded.recursion (well_founded_submodule_gt R M) I hgt /-- For any endomorphism of a Noetherian module, there is some nontrivial iterate with disjoint kernel and range. -/ theorem is_noetherian.exists_endomorphism_iterate_ker_inf_range_eq_bot [I : is_noetherian R M] (f : M →ₗ[R] M) : ∃ n : ℕ, n ≠ 0 ∧ (f ^ n).ker ⊓ (f ^ n).range = ⊥ := begin obtain ⟨n, w⟩ := monotone_stabilizes_iff_noetherian.mpr I (f.iterate_ker.comp ⟨λ n, n+1, λ n m w, by linarith⟩), specialize w (2 * n + 1) (by linarith), dsimp at w, refine ⟨n+1, nat.succ_ne_zero _, _⟩, rw eq_bot_iff, rintros - ⟨h, ⟨y, rfl⟩⟩, rw [mem_bot, ←linear_map.mem_ker, w], erw linear_map.mem_ker at h ⊢, change ((f ^ (n + 1)) * (f ^ (n + 1))) y = 0 at h, rw ←pow_add at h, convert h using 3, linarith, end /-- Any surjective endomorphism of a Noetherian module is injective. -/ theorem is_noetherian.injective_of_surjective_endomorphism [is_noetherian R M] (f : M →ₗ[R] M) (s : surjective f) : injective f := begin obtain ⟨n, ne, w⟩ := is_noetherian.exists_endomorphism_iterate_ker_inf_range_eq_bot f, rw [linear_map.range_eq_top.mpr (linear_map.iterate_surjective s n), inf_top_eq, linear_map.ker_eq_bot] at w, exact linear_map.injective_of_iterate_injective ne w, end /-- Any surjective endomorphism of a Noetherian module is bijective. -/ theorem is_noetherian.bijective_of_surjective_endomorphism [is_noetherian R M] (f : M →ₗ[R] M) (s : surjective f) : bijective f := ⟨is_noetherian.injective_of_surjective_endomorphism f s, s⟩ /-- A sequence `f` of submodules of a noetherian module, with `f (n+1)` disjoint from the supremum of `f 0`, ..., `f n`, is eventually zero. -/ lemma is_noetherian.disjoint_partial_sups_eventually_bot [I : is_noetherian R M] (f : ℕ → submodule R M) (h : ∀ n, disjoint (partial_sups f n) (f (n+1))) : ∃ n : ℕ, ∀ m, n ≤ m → f m = ⊥ := begin -- A little off-by-one cleanup first: suffices t : ∃ n : ℕ, ∀ m, n ≤ m → f (m+1) = ⊥, { obtain ⟨n, w⟩ := t, use n+1, rintros (_|m) p, { cases p, }, { apply w, exact nat.succ_le_succ_iff.mp p }, }, obtain ⟨n, w⟩ := monotone_stabilizes_iff_noetherian.mpr I (partial_sups f), exact ⟨n, (λ m p, eq_bot_of_disjoint_absorbs (h m) ((eq.symm (w (m + 1) (le_add_right p))).trans (w m p)))⟩ end universe w variables {N : Type w} [add_comm_group N] [module R N] /-- If `M ⊕ N` embeds into `M`, for `M` noetherian over `R`, then `N` is trivial. -/ noncomputable def is_noetherian.equiv_punit_of_prod_injective [is_noetherian R M] (f : M × N →ₗ[R] M) (i : injective f) : N ≃ₗ[R] punit.{w+1} := begin apply nonempty.some, obtain ⟨n, w⟩ := is_noetherian.disjoint_partial_sups_eventually_bot (f.tailing i) (f.tailings_disjoint_tailing i), specialize w n (le_refl n), apply nonempty.intro, refine (f.tailing_linear_equiv i n).symm.trans _, rw w, exact submodule.bot_equiv_punit, end end /-- A ring is Noetherian if it is Noetherian as a module over itself, i.e. all its ideals are finitely generated. -/ class is_noetherian_ring (R) [ring R] extends is_noetherian R R : Prop theorem is_noetherian_ring_iff {R} [ring R] : is_noetherian_ring R ↔ is_noetherian R R := ⟨λ h, h.1, @is_noetherian_ring.mk _ _⟩ @[priority 80] -- see Note [lower instance priority] instance ring.is_noetherian_of_fintype (R M) [fintype M] [ring R] [add_comm_group M] [module R M] : is_noetherian R M := by letI := classical.dec; exact ⟨assume s, ⟨to_finset s, by rw [set.coe_to_finset, submodule.span_eq]⟩⟩ theorem ring.is_noetherian_of_zero_eq_one {R} [ring R] (h01 : (0 : R) = 1) : is_noetherian_ring R := by haveI := subsingleton_of_zero_eq_one h01; haveI := fintype.of_subsingleton (0:R); exact is_noetherian_ring_iff.2 (ring.is_noetherian_of_fintype R R) theorem is_noetherian_of_submodule_of_noetherian (R M) [ring R] [add_comm_group M] [module R M] (N : submodule R M) (h : is_noetherian R M) : is_noetherian R N := begin rw is_noetherian_iff_well_founded at h ⊢, exact order_embedding.well_founded (submodule.map_subtype.order_embedding N).dual h, end theorem is_noetherian_of_quotient_of_noetherian (R) [ring R] (M) [add_comm_group M] [module R M] (N : submodule R M) (h : is_noetherian R M) : is_noetherian R N.quotient := begin rw is_noetherian_iff_well_founded at h ⊢, exact order_embedding.well_founded (submodule.comap_mkq.order_embedding N).dual h, end theorem is_noetherian_of_fg_of_noetherian {R M} [ring R] [add_comm_group M] [module R M] (N : submodule R M) [is_noetherian_ring R] (hN : N.fg) : is_noetherian R N := let ⟨s, hs⟩ := hN in begin haveI := classical.dec_eq M, haveI := classical.dec_eq R, letI : is_noetherian R R := by apply_instance, have : ∀ x ∈ s, x ∈ N, from λ x hx, hs ▸ submodule.subset_span hx, refine @@is_noetherian_of_surjective ((↑s : set M) → R) _ _ _ (pi.module _ _ _) _ _ _ is_noetherian_pi, { fapply linear_map.mk, { exact λ f, ⟨∑ i in s.attach, f i • i.1, N.sum_mem (λ c _, N.smul_mem _ $ this _ c.2)⟩ }, { intros f g, apply subtype.eq, change ∑ i in s.attach, (f i + g i) • _ = _, simp only [add_smul, finset.sum_add_distrib], refl }, { intros c f, apply subtype.eq, change ∑ i in s.attach, (c • f i) • _ = _, simp only [smul_eq_mul, mul_smul], exact finset.smul_sum.symm } }, rw linear_map.range_eq_top, rintro ⟨n, hn⟩, change n ∈ N at hn, rw [← hs, ← set.image_id ↑s, finsupp.mem_span_image_iff_total] at hn, rcases hn with ⟨l, hl1, hl2⟩, refine ⟨λ x, l x, subtype.ext _⟩, change ∑ i in s.attach, l i • (i : M) = n, rw [@finset.sum_attach M M s _ (λ i, l i • i), ← hl2, finsupp.total_apply, finsupp.sum, eq_comm], refine finset.sum_subset hl1 (λ x _ hx, _), rw [finsupp.not_mem_support_iff.1 hx, zero_smul] end lemma is_noetherian_of_fg_of_noetherian' {R M} [ring R] [add_comm_group M] [module R M] [is_noetherian_ring R] (h : (⊤ : submodule R M).fg) : is_noetherian R M := have is_noetherian R (⊤ : submodule R M), from is_noetherian_of_fg_of_noetherian _ h, by exactI is_noetherian_of_linear_equiv (linear_equiv.of_top (⊤ : submodule R M) rfl) /-- In a module over a noetherian ring, the submodule generated by finitely many vectors is noetherian. -/ theorem is_noetherian_span_of_finite (R) {M} [ring R] [add_comm_group M] [module R M] [is_noetherian_ring R] {A : set M} (hA : finite A) : is_noetherian R (submodule.span R A) := is_noetherian_of_fg_of_noetherian _ (submodule.fg_def.mpr ⟨A, hA, rfl⟩) theorem is_noetherian_ring_of_surjective (R) [comm_ring R] (S) [comm_ring S] (f : R →+* S) (hf : function.surjective f) [H : is_noetherian_ring R] : is_noetherian_ring S := begin rw [is_noetherian_ring_iff, is_noetherian_iff_well_founded] at H ⊢, exact order_embedding.well_founded (ideal.order_embedding_of_surjective f hf).dual H, end section local attribute [instance] subset.comm_ring instance is_noetherian_ring_set_range {R} [comm_ring R] {S} [comm_ring S] (f : R →+* S) [is_noetherian_ring R] : is_noetherian_ring (set.range f) := is_noetherian_ring_of_surjective R (set.range f) (f.cod_restrict (set.range f) set.mem_range_self) set.surjective_onto_range end instance is_noetherian_ring_range {R} [comm_ring R] {S} [comm_ring S] (f : R →+* S) [is_noetherian_ring R] : is_noetherian_ring f.range := is_noetherian_ring_of_surjective R f.range f.range_restrict f.range_restrict_surjective theorem is_noetherian_ring_of_ring_equiv (R) [comm_ring R] {S} [comm_ring S] (f : R ≃+* S) [is_noetherian_ring R] : is_noetherian_ring S := is_noetherian_ring_of_surjective R S f.to_ring_hom f.to_equiv.surjective namespace submodule variables {R : Type*} {A : Type*} [comm_ring R] [ring A] [algebra R A] variables (M N : submodule R A) theorem fg_mul (hm : M.fg) (hn : N.fg) : (M * N).fg := let ⟨m, hfm, hm⟩ := fg_def.1 hm, ⟨n, hfn, hn⟩ := fg_def.1 hn in fg_def.2 ⟨m * n, hfm.mul hfn, span_mul_span R m n ▸ hm ▸ hn ▸ rfl⟩ lemma fg_pow (h : M.fg) (n : ℕ) : (M ^ n).fg := nat.rec_on n (⟨{1}, by simp [one_eq_span]⟩) (λ n ih, by simpa [pow_succ] using fg_mul _ _ h ih) end submodule section primes variables {R : Type*} [comm_ring R] [is_noetherian_ring R] /--In a noetherian ring, every ideal contains a product of prime ideals ([samuel, § 3.3, Lemma 3])-/ lemma exists_prime_spectrum_prod_le (I : ideal R) : ∃ (Z : multiset (prime_spectrum R)), multiset.prod (Z.map (coe : subtype _ → ideal R)) ≤ I := begin refine is_noetherian.induction (λ (M : ideal R) hgt, _) I, by_cases h_prM : M.is_prime, { use {⟨M, h_prM⟩}, rw [multiset.map_singleton, multiset.singleton_eq_singleton, multiset.prod_singleton, subtype.coe_mk], exact le_rfl }, by_cases htop : M = ⊤, { rw htop, exact ⟨0, le_top⟩ }, have lt_add : ∀ z ∉ M, M < M + span R {z}, { intros z hz, refine lt_of_le_of_ne le_sup_left (λ m_eq, hz _), rw m_eq, exact mem_sup_right (mem_span_singleton_self z) }, obtain ⟨x, hx, y, hy, hxy⟩ := (ideal.not_is_prime_iff.mp h_prM).resolve_left htop, obtain ⟨Wx, h_Wx⟩ := hgt (M + span R {x}) (lt_add _ hx), obtain ⟨Wy, h_Wy⟩ := hgt (M + span R {y}) (lt_add _ hy), use Wx + Wy, rw [multiset.map_add, multiset.prod_add], apply le_trans (submodule.mul_le_mul h_Wx h_Wy), rw add_mul, apply sup_le (show M * (M + span R {y}) ≤ M, from ideal.mul_le_right), rw mul_add, apply sup_le (show span R {x} * M ≤ M, from ideal.mul_le_left), rwa [span_mul_span, singleton_mul_singleton, span_singleton_le_iff_mem], end variables {A : Type*} [integral_domain A] [is_noetherian_ring A] /--In a noetherian integral domain which is not a field, every non-zero ideal contains a non-zero product of prime ideals; in a field, the whole ring is a non-zero ideal containing only 0 as product or prime ideals ([samuel, § 3.3, Lemma 3]) -/ lemma exists_prime_spectrum_prod_le_and_ne_bot_of_domain (h_fA : ¬ is_field A) {I : ideal A} (h_nzI: I ≠ ⊥) : ∃ (Z : multiset (prime_spectrum A)), multiset.prod (Z.map (coe : subtype _ → ideal A)) ≤ I ∧ multiset.prod (Z.map (coe : subtype _ → ideal A)) ≠ ⊥ := begin revert h_nzI, refine is_noetherian.induction (λ (M : ideal A) hgt, _) I, intro h_nzM, have hA_nont : nontrivial A, apply is_integral_domain.to_nontrivial (integral_domain.to_is_integral_domain A), by_cases h_topM : M = ⊤, { rcases h_topM with rfl, obtain ⟨p_id, h_nzp, h_pp⟩ : ∃ (p : ideal A), p ≠ ⊥ ∧ p.is_prime, { apply ring.not_is_field_iff_exists_prime.mp h_fA }, use [({⟨p_id, h_pp⟩} : multiset (prime_spectrum A)), le_top], rwa [multiset.map_singleton, multiset.singleton_eq_singleton, multiset.prod_singleton, subtype.coe_mk] }, by_cases h_prM : M.is_prime, { use ({⟨M, h_prM⟩} : multiset (prime_spectrum A)), rw [multiset.map_singleton, multiset.singleton_eq_singleton, multiset.prod_singleton, subtype.coe_mk], exact ⟨le_rfl, h_nzM⟩ }, obtain ⟨x, hx, y, hy, h_xy⟩ := (ideal.not_is_prime_iff.mp h_prM).resolve_left h_topM, have lt_add : ∀ z ∉ M, M < M + span A {z}, { intros z hz, refine lt_of_le_of_ne le_sup_left (λ m_eq, hz _), rw m_eq, exact mem_sup_right (mem_span_singleton_self z) }, obtain ⟨Wx, h_Wx_le, h_Wx_ne⟩ := hgt (M + span A {x}) (lt_add _ hx) (ne_bot_of_gt (lt_add _ hx)), obtain ⟨Wy, h_Wy_le, h_Wx_ne⟩ := hgt (M + span A {y}) (lt_add _ hy) (ne_bot_of_gt (lt_add _ hy)), use Wx + Wy, rw [multiset.map_add, multiset.prod_add], refine ⟨le_trans (submodule.mul_le_mul h_Wx_le h_Wy_le) _, mt ideal.mul_eq_bot.mp _⟩, { rw add_mul, apply sup_le (show M * (M + span A {y}) ≤ M, from ideal.mul_le_right), rw mul_add, apply sup_le (show span A {x} * M ≤ M, from ideal.mul_le_left), rwa [span_mul_span, singleton_mul_singleton, span_singleton_le_iff_mem] }, { rintro (hx | hy); contradiction }, end end primes
7f077122b65349eec947473e27a2df0151eea588
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/number_theory/padics/ring_homs.lean
e8153eb6910c8466df3d9634a5addf12957fdefa
[ "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
24,060
lean
/- Copyright (c) 2020 Johan Commelin, Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Robert Y. Lewis -/ import data.zmod.basic import number_theory.padics.padic_integers /-! # Relating `ℤ_[p]` to `zmod (p ^ n)` In this file we establish connections between the `p`-adic integers $\mathbb{Z}_p$ and the integers modulo powers of `p`, $\mathbb{Z}/p^n\mathbb{Z}$. ## Main declarations We show that $\mathbb{Z}_p$ has a ring hom to $\mathbb{Z}/p^n\mathbb{Z}$ for each `n`. The case for `n = 1` is handled separately, since it is used in the general construction and we may want to use it without the `^1` getting in the way. * `padic_int.to_zmod`: ring hom to `zmod p` * `padic_int.to_zmod_pow`: ring hom to `zmod (p^n)` * `padic_int.ker_to_zmod` / `padic_int.ker_to_zmod_pow`: the kernels of these maps are the ideals generated by `p^n` We also establish the universal property of $\mathbb{Z}_p$ as a projective limit. Given a family of compatible ring homs $f_k : R \to \mathbb{Z}/p^n\mathbb{Z}$, there is a unique limit $R \to \mathbb{Z}_p$. * `padic_int.lift`: the limit function * `padic_int.lift_spec` / `padic_int.lift_unique`: the universal property ## Implementation notes The ring hom constructions go through an auxiliary constructor `padic_int.to_zmod_hom`, which removes some boilerplate code. -/ noncomputable theory open_locale classical open nat local_ring padic namespace padic_int variables {p : ℕ} [hp_prime : fact p.prime] include hp_prime section ring_homs /-! ### Ring homomorphisms to `zmod p` and `zmod (p ^ n)` -/ variables (p) (r : ℚ) omit hp_prime /-- `mod_part p r` is an integer that satisfies `‖(r - mod_part p r : ℚ_[p])‖ < 1` when `‖(r : ℚ_[p])‖ ≤ 1`, see `padic_int.norm_sub_mod_part`. It is the unique non-negative integer that is `< p` with this property. (Note that this definition assumes `r : ℚ`. See `padic_int.zmod_repr` for a version that takes values in `ℕ` and works for arbitrary `x : ℤ_[p]`.) -/ def mod_part : ℤ := (r.num * gcd_a r.denom p) % p include hp_prime variable {p} lemma mod_part_lt_p : mod_part p r < p := begin convert int.mod_lt _ _, { simp }, { exact_mod_cast hp_prime.1.ne_zero } end lemma mod_part_nonneg : 0 ≤ mod_part p r := int.mod_nonneg _ $ by exact_mod_cast hp_prime.1.ne_zero lemma is_unit_denom (r : ℚ) (h : ‖(r : ℚ_[p])‖ ≤ 1) : is_unit (r.denom : ℤ_[p]) := begin rw is_unit_iff, apply le_antisymm (r.denom : ℤ_[p]).2, rw [← not_lt, val_eq_coe, coe_nat_cast], intro norm_denom_lt, have hr : ‖(r * r.denom : ℚ_[p])‖ = ‖(r.num : ℚ_[p])‖, { rw_mod_cast @rat.mul_denom_eq_num r, refl, }, rw padic_norm_e.mul at hr, have key : ‖(r.num : ℚ_[p])‖ < 1, { calc _ = _ : hr.symm ... < 1 * 1 : mul_lt_mul' h norm_denom_lt (norm_nonneg _) zero_lt_one ... = 1 : mul_one 1 }, have : ↑p ∣ r.num ∧ (p : ℤ) ∣ r.denom, { simp only [← norm_int_lt_one_iff_dvd, ← padic_norm_e_of_padic_int], norm_cast, exact ⟨key, norm_denom_lt⟩ }, apply hp_prime.1.not_dvd_one, rwa [← r.cop.gcd_eq_one, nat.dvd_gcd_iff, ← int.coe_nat_dvd_left, ← int.coe_nat_dvd], end lemma norm_sub_mod_part_aux (r : ℚ) (h : ‖(r : ℚ_[p])‖ ≤ 1) : ↑p ∣ r.num - r.num * r.denom.gcd_a p % p * ↑(r.denom) := begin rw ← zmod.int_coe_zmod_eq_zero_iff_dvd, simp only [int.cast_coe_nat, zmod.nat_cast_mod, int.cast_mul, int.cast_sub], have := congr_arg (coe : ℤ → zmod p) (gcd_eq_gcd_ab r.denom p), simp only [int.cast_coe_nat, add_zero, int.cast_add, zmod.nat_cast_self, int.cast_mul, zero_mul] at this, push_cast, rw [mul_right_comm, mul_assoc, ←this], suffices rdcp : r.denom.coprime p, { rw rdcp.gcd_eq_one, simp only [mul_one, cast_one, sub_self], }, apply coprime.symm, apply (coprime_or_dvd_of_prime hp_prime.1 _).resolve_right, rw [← int.coe_nat_dvd, ← norm_int_lt_one_iff_dvd, not_lt], apply ge_of_eq, rw ← is_unit_iff, exact is_unit_denom r h, end lemma norm_sub_mod_part (h : ‖(r : ℚ_[p])‖ ≤ 1) : ‖(⟨r,h⟩ - mod_part p r : ℤ_[p])‖ < 1 := begin let n := mod_part p r, rw [norm_lt_one_iff_dvd, ← (is_unit_denom r h).dvd_mul_right], suffices : ↑p ∣ r.num - n * r.denom, { convert (int.cast_ring_hom ℤ_[p]).map_dvd this, simp only [sub_mul, int.cast_coe_nat, eq_int_cast, int.cast_mul, sub_left_inj, int.cast_sub], apply subtype.coe_injective, simp only [coe_mul, subtype.coe_mk, coe_nat_cast], rw_mod_cast @rat.mul_denom_eq_num r, refl }, exact norm_sub_mod_part_aux r h end lemma exists_mem_range_of_norm_rat_le_one (h : ‖(r : ℚ_[p])‖ ≤ 1) : ∃ n : ℤ, 0 ≤ n ∧ n < p ∧ ‖(⟨r,h⟩ - n : ℤ_[p])‖ < 1 := ⟨mod_part p r, mod_part_nonneg _, mod_part_lt_p _, norm_sub_mod_part _ h⟩ lemma zmod_congr_of_sub_mem_span_aux (n : ℕ) (x : ℤ_[p]) (a b : ℤ) (ha : x - a ∈ (ideal.span {p ^ n} : ideal ℤ_[p])) (hb : x - b ∈ (ideal.span {p ^ n} : ideal ℤ_[p])) : (a : zmod (p ^ n)) = b := begin rw [ideal.mem_span_singleton] at ha hb, rw [← sub_eq_zero, ← int.cast_sub, zmod.int_coe_zmod_eq_zero_iff_dvd, int.coe_nat_pow], rw [← dvd_neg, neg_sub] at ha, have := dvd_add ha hb, rwa [sub_eq_add_neg, sub_eq_add_neg, add_assoc, neg_add_cancel_left, ← sub_eq_add_neg, ← int.cast_sub, pow_p_dvd_int_iff] at this, end lemma zmod_congr_of_sub_mem_span (n : ℕ) (x : ℤ_[p]) (a b : ℕ) (ha : x - a ∈ (ideal.span {p ^ n} : ideal ℤ_[p])) (hb : x - b ∈ (ideal.span {p ^ n} : ideal ℤ_[p])) : (a : zmod (p ^ n)) = b := by simpa using zmod_congr_of_sub_mem_span_aux n x a b ha hb lemma zmod_congr_of_sub_mem_max_ideal (x : ℤ_[p]) (m n : ℕ) (hm : x - m ∈ maximal_ideal ℤ_[p]) (hn : x - n ∈ maximal_ideal ℤ_[p]) : (m : zmod p) = n := begin rw maximal_ideal_eq_span_p at hm hn, have := zmod_congr_of_sub_mem_span_aux 1 x m n, simp only [pow_one] at this, specialize this hm hn, apply_fun zmod.cast_hom (show p ∣ p ^ 1, by rw pow_one) (zmod p) at this, simp only [map_int_cast] at this, simpa only [int.cast_coe_nat] using this end variable (x : ℤ_[p]) lemma exists_mem_range : ∃ n : ℕ, n < p ∧ (x - n ∈ maximal_ideal ℤ_[p]) := begin simp only [maximal_ideal_eq_span_p, ideal.mem_span_singleton, ← norm_lt_one_iff_dvd], obtain ⟨r, hr⟩ := rat_dense p (x : ℚ_[p]) zero_lt_one, have H : ‖(r : ℚ_[p])‖ ≤ 1, { rw norm_sub_rev at hr, calc _ = ‖(r : ℚ_[p]) - x + x‖ : by ring_nf ... ≤ _ : padic_norm_e.nonarchimedean _ _ ... ≤ _ : max_le (le_of_lt hr) x.2 }, obtain ⟨n, hzn, hnp, hn⟩ := exists_mem_range_of_norm_rat_le_one r H, lift n to ℕ using hzn, use n, split, {exact_mod_cast hnp}, simp only [norm_def, coe_sub, subtype.coe_mk, coe_nat_cast] at hn ⊢, rw show (x - n : ℚ_[p]) = (x - r) + (r - n), by ring, apply lt_of_le_of_lt (padic_norm_e.nonarchimedean _ _), apply max_lt hr, simpa using hn end /-- `zmod_repr x` is the unique natural number smaller than `p` satisfying `‖(x - zmod_repr x : ℤ_[p])‖ < 1`. -/ def zmod_repr : ℕ := classical.some (exists_mem_range x) lemma zmod_repr_spec : zmod_repr x < p ∧ (x - zmod_repr x ∈ maximal_ideal ℤ_[p]) := classical.some_spec (exists_mem_range x) lemma zmod_repr_lt_p : zmod_repr x < p := (zmod_repr_spec _).1 lemma sub_zmod_repr_mem : (x - zmod_repr x ∈ maximal_ideal ℤ_[p]) := (zmod_repr_spec _).2 /-- `to_zmod_hom` is an auxiliary constructor for creating ring homs from `ℤ_[p]` to `zmod v`. -/ def to_zmod_hom (v : ℕ) (f : ℤ_[p] → ℕ) (f_spec : ∀ x, x - f x ∈ (ideal.span {v} : ideal ℤ_[p])) (f_congr : ∀ (x : ℤ_[p]) (a b : ℕ), x - a ∈ (ideal.span {v} : ideal ℤ_[p]) → x - b ∈ (ideal.span {v} : ideal ℤ_[p]) → (a : zmod v) = b) : ℤ_[p] →+* zmod v := { to_fun := λ x, f x, map_zero' := begin rw [f_congr (0 : ℤ_[p]) _ 0, cast_zero], { exact f_spec _ }, { simp only [sub_zero, cast_zero, submodule.zero_mem], } end, map_one' := begin rw [f_congr (1 : ℤ_[p]) _ 1, cast_one], { exact f_spec _ }, { simp only [sub_self, cast_one, submodule.zero_mem], } end, map_add' := begin intros x y, rw [f_congr (x + y) _ (f x + f y), cast_add], { exact f_spec _ }, { convert ideal.add_mem _ (f_spec x) (f_spec y), rw cast_add, ring, } end, map_mul' := begin intros x y, rw [f_congr (x * y) _ (f x * f y), cast_mul], { exact f_spec _ }, { let I : ideal ℤ_[p] := ideal.span {v}, convert I.add_mem (I.mul_mem_left x (f_spec y)) (I.mul_mem_right (f y) (f_spec x)), rw cast_mul, ring, } end, } /-- `to_zmod` is a ring hom from `ℤ_[p]` to `zmod p`, with the equality `to_zmod x = (zmod_repr x : zmod p)`. -/ def to_zmod : ℤ_[p] →+* zmod p := to_zmod_hom p zmod_repr (by { rw ←maximal_ideal_eq_span_p, exact sub_zmod_repr_mem }) (by { rw ←maximal_ideal_eq_span_p, exact zmod_congr_of_sub_mem_max_ideal } ) /-- `z - (to_zmod z : ℤ_[p])` is contained in the maximal ideal of `ℤ_[p]`, for every `z : ℤ_[p]`. The coercion from `zmod p` to `ℤ_[p]` is `zmod.has_coe_t`, which coerces `zmod p` into artibrary rings. This is unfortunate, but a consequence of the fact that we allow `zmod p` to coerce to rings of arbitrary characteristic, instead of only rings of characteristic `p`. This coercion is only a ring homomorphism if it coerces into a ring whose characteristic divides `p`. While this is not the case here we can still make use of the coercion. -/ lemma to_zmod_spec (z : ℤ_[p]) : z - (to_zmod z : ℤ_[p]) ∈ maximal_ideal ℤ_[p] := begin convert sub_zmod_repr_mem z using 2, dsimp [to_zmod, to_zmod_hom], unfreezingI { rcases (exists_eq_add_of_lt (hp_prime.1.pos)) with ⟨p', rfl⟩ }, change ↑(zmod.val _) = _, simp only [zmod.val_nat_cast, add_zero, add_def, nat.cast_inj, zero_add], apply mod_eq_of_lt, simpa only [zero_add] using zmod_repr_lt_p z, end lemma ker_to_zmod : (to_zmod : ℤ_[p] →+* zmod p).ker = maximal_ideal ℤ_[p] := begin ext x, rw ring_hom.mem_ker, split, { intro h, simpa only [h, zmod.cast_zero, sub_zero] using to_zmod_spec x, }, { intro h, rw ← sub_zero x at h, dsimp [to_zmod, to_zmod_hom], convert zmod_congr_of_sub_mem_max_ideal x _ 0 _ h, norm_cast, apply sub_zmod_repr_mem, } end /-- `appr n x` gives a value `v : ℕ` such that `x` and `↑v : ℤ_p` are congruent mod `p^n`. See `appr_spec`. -/ noncomputable def appr : ℤ_[p] → ℕ → ℕ | x 0 := 0 | x (n+1) := let y := x - appr x n in if hy : y = 0 then appr x n else let u := unit_coeff hy in appr x n + p ^ n * (to_zmod ((u : ℤ_[p]) * (p ^ (y.valuation - n).nat_abs))).val lemma appr_lt (x : ℤ_[p]) (n : ℕ) : x.appr n < p ^ n := begin induction n with n ih generalizing x, { simp only [appr, succ_pos', pow_zero], }, simp only [appr, map_nat_cast, zmod.nat_cast_self, ring_hom.map_pow, int.nat_abs, ring_hom.map_mul], have hp : p ^ n < p ^ (n + 1), { apply pow_lt_pow hp_prime.1.one_lt (lt_add_one n) }, split_ifs with h, { apply lt_trans (ih _) hp, }, { calc _ < p ^ n + p ^ n * (p - 1) : _ ... = p ^ (n + 1) : _, { apply add_lt_add_of_lt_of_le (ih _), apply nat.mul_le_mul_left, apply le_pred_of_lt, apply zmod.val_lt }, { rw [mul_tsub, mul_one, ← pow_succ'], apply add_tsub_cancel_of_le (le_of_lt hp) } } end lemma appr_mono (x : ℤ_[p]) : monotone x.appr := begin apply monotone_nat_of_le_succ, intro n, dsimp [appr], split_ifs, { refl, }, apply nat.le_add_right, end lemma dvd_appr_sub_appr (x : ℤ_[p]) (m n : ℕ) (h : m ≤ n) : p ^ m ∣ x.appr n - x.appr m := begin obtain ⟨k, rfl⟩ := nat.exists_eq_add_of_le h, clear h, induction k with k ih, { simp only [add_zero, tsub_self, dvd_zero], }, rw [nat.succ_eq_add_one, ← add_assoc], dsimp [appr], split_ifs with h, { exact ih }, rw [add_comm, add_tsub_assoc_of_le (appr_mono _ (nat.le_add_right m k))], apply dvd_add _ ih, apply dvd_mul_of_dvd_left, apply pow_dvd_pow _ (nat.le_add_right m k), end lemma appr_spec (n : ℕ) : ∀ (x : ℤ_[p]), x - appr x n ∈ (ideal.span {p^n} : ideal ℤ_[p]) := begin simp only [ideal.mem_span_singleton], induction n with n ih, { simp only [is_unit_one, is_unit.dvd, pow_zero, forall_true_iff], }, intro x, dsimp only [appr], split_ifs with h, { rw h, apply dvd_zero }, push_cast, rw sub_add_eq_sub_sub, obtain ⟨c, hc⟩ := ih x, simp only [map_nat_cast, zmod.nat_cast_self, ring_hom.map_pow, ring_hom.map_mul, zmod.nat_cast_val], have hc' : c ≠ 0, { rintro rfl, simp only [mul_zero] at hc, contradiction }, conv_rhs { congr, simp only [hc], }, rw show (x - ↑(appr x n)).valuation = (↑p ^ n * c).valuation, { rw hc }, rw [valuation_p_pow_mul _ _ hc', add_sub_cancel', pow_succ', ← mul_sub], apply mul_dvd_mul_left, obtain hc0 | hc0 := c.valuation.nat_abs.eq_zero_or_pos, { simp only [hc0, mul_one, pow_zero], rw [mul_comm, unit_coeff_spec h] at hc, suffices : c = unit_coeff h, { rw [← this, ← ideal.mem_span_singleton, ← maximal_ideal_eq_span_p], apply to_zmod_spec }, obtain ⟨c, rfl⟩ : is_unit c, -- TODO: write a can_lift instance for units { rw int.nat_abs_eq_zero at hc0, rw [is_unit_iff, norm_eq_pow_val hc', hc0, neg_zero, zpow_zero], }, rw discrete_valuation_ring.unit_mul_pow_congr_unit _ _ _ _ _ hc, exact irreducible_p }, { rw zero_pow hc0, simp only [sub_zero, zmod.cast_zero, mul_zero], rw unit_coeff_spec hc', exact (dvd_pow_self (p : ℤ_[p]) hc0.ne').mul_left _, }, end attribute [irreducible] appr /-- A ring hom from `ℤ_[p]` to `zmod (p^n)`, with underlying function `padic_int.appr n`. -/ def to_zmod_pow (n : ℕ) : ℤ_[p] →+* zmod (p ^ n) := to_zmod_hom (p^n) (λ x, appr x n) (by { intros, convert appr_spec n _ using 1, simp }) (by { intros x a b ha hb, apply zmod_congr_of_sub_mem_span n x a b, { simpa using ha }, { simpa using hb } }) lemma ker_to_zmod_pow (n : ℕ) : (to_zmod_pow n : ℤ_[p] →+* zmod (p ^ n)).ker = ideal.span {p ^ n} := begin ext x, rw ring_hom.mem_ker, split, { intro h, suffices : x.appr n = 0, { convert appr_spec n x, simp only [this, sub_zero, cast_zero], }, dsimp [to_zmod_pow, to_zmod_hom] at h, rw zmod.nat_coe_zmod_eq_zero_iff_dvd at h, apply eq_zero_of_dvd_of_lt h (appr_lt _ _), }, { intro h, rw ← sub_zero x at h, dsimp [to_zmod_pow, to_zmod_hom], rw [zmod_congr_of_sub_mem_span n x _ 0 _ h, cast_zero], apply appr_spec, } end @[simp] lemma zmod_cast_comp_to_zmod_pow (m n : ℕ) (h : m ≤ n) : (zmod.cast_hom (pow_dvd_pow p h) (zmod (p ^ m))).comp (to_zmod_pow n) = to_zmod_pow m := begin apply zmod.ring_hom_eq_of_ker_eq, ext x, rw [ring_hom.mem_ker, ring_hom.mem_ker], simp only [function.comp_app, zmod.cast_hom_apply, ring_hom.coe_comp], simp only [to_zmod_pow, to_zmod_hom, ring_hom.coe_mk], rw [zmod.cast_nat_cast (pow_dvd_pow p h), zmod_congr_of_sub_mem_span m (x.appr n) (x.appr n) (x.appr m)], { rw [sub_self], apply ideal.zero_mem _, }, { rw ideal.mem_span_singleton, rcases dvd_appr_sub_appr x m n h with ⟨c, hc⟩, use c, rw [← nat.cast_sub (appr_mono _ h), hc, nat.cast_mul, nat.cast_pow], }, { apply_instance } end @[simp] lemma cast_to_zmod_pow (m n : ℕ) (h : m ≤ n) (x : ℤ_[p]) : ↑(to_zmod_pow n x) = to_zmod_pow m x := by { rw ← zmod_cast_comp_to_zmod_pow _ _ h, refl } lemma dense_range_nat_cast : dense_range (nat.cast : ℕ → ℤ_[p]) := begin intro x, rw metric.mem_closure_range_iff, intros ε hε, obtain ⟨n, hn⟩ := exists_pow_neg_lt p hε, use (x.appr n), rw dist_eq_norm, apply lt_of_le_of_lt _ hn, rw norm_le_pow_iff_mem_span_pow, apply appr_spec, end lemma dense_range_int_cast : dense_range (int.cast : ℤ → ℤ_[p]) := begin intro x, apply dense_range_nat_cast.induction_on x, { exact is_closed_closure, }, { intro a, change (a.cast : ℤ_[p]) with (a : ℤ).cast, apply subset_closure, exact set.mem_range_self _ } end end ring_homs section lift /-! ### Universal property as projective limit -/ open cau_seq padic_seq variables {R : Type*} [non_assoc_semiring R] (f : Π k : ℕ, R →+* zmod (p^k)) (f_compat : ∀ k1 k2 (hk : k1 ≤ k2), (zmod.cast_hom (pow_dvd_pow p hk) _).comp (f k2) = f k1) omit hp_prime /-- Given a family of ring homs `f : Π n : ℕ, R →+* zmod (p ^ n)`, `nth_hom f r` is an integer-valued sequence whose `n`th value is the unique integer `k` such that `0 ≤ k < p ^ n` and `f n r = (k : zmod (p ^ n))`. -/ def nth_hom (r : R) : ℕ → ℤ := λ n, (f n r : zmod (p^n)).val @[simp] lemma nth_hom_zero : nth_hom f 0 = 0 := by simp [nth_hom]; refl variable {f} include hp_prime include f_compat lemma pow_dvd_nth_hom_sub (r : R) (i j : ℕ) (h : i ≤ j) : ↑p ^ i ∣ nth_hom f r j - nth_hom f r i := begin specialize f_compat i j h, rw [← int.coe_nat_pow, ← zmod.int_coe_zmod_eq_zero_iff_dvd, int.cast_sub], dsimp [nth_hom], rw [← f_compat, ring_hom.comp_apply], simp only [zmod.cast_id, zmod.cast_hom_apply, sub_self, zmod.nat_cast_val, zmod.int_cast_cast], end lemma is_cau_seq_nth_hom (r : R): is_cau_seq (padic_norm p) (λ n, nth_hom f r n) := begin intros ε hε, obtain ⟨k, hk⟩ : ∃ k : ℕ, (p ^ - (↑(k : ℕ) : ℤ) : ℚ) < ε := exists_pow_neg_lt_rat p hε, use k, intros j hj, refine lt_of_le_of_lt _ hk, norm_cast, rw ← padic_norm.dvd_iff_norm_le, exact_mod_cast pow_dvd_nth_hom_sub f_compat r k j hj end /-- `nth_hom_seq f_compat r` bundles `padic_int.nth_hom f r` as a Cauchy sequence of rationals with respect to the `p`-adic norm. The `n`th value of the sequence is `((f n r).val : ℚ)`. -/ def nth_hom_seq (r : R) : padic_seq p := ⟨λ n, nth_hom f r n, is_cau_seq_nth_hom f_compat r⟩ -- this lemma ran into issues after changing to `ne_zero` and I'm not sure why. lemma nth_hom_seq_one : nth_hom_seq f_compat 1 ≈ 1 := begin intros ε hε, change _ < _ at hε, use 1, intros j hj, haveI : fact (1 < p ^ j) := ⟨nat.one_lt_pow _ _ (by linarith) hp_prime.1.one_lt⟩, suffices : ((1 : zmod (p ^ j)) : ℚ) = 1, by simp [nth_hom_seq, nth_hom, this, hε], rw [zmod.cast_eq_val, zmod.val_one, nat.cast_one] end lemma nth_hom_seq_add (r s : R) : nth_hom_seq f_compat (r + s) ≈ nth_hom_seq f_compat r + nth_hom_seq f_compat s := begin intros ε hε, obtain ⟨n, hn⟩ := exists_pow_neg_lt_rat p hε, use n, intros j hj, dsimp [nth_hom_seq], apply lt_of_le_of_lt _ hn, rw [← int.cast_add, ← int.cast_sub, ← padic_norm.dvd_iff_norm_le, ← zmod.int_coe_zmod_eq_zero_iff_dvd], dsimp [nth_hom], simp only [zmod.nat_cast_val, ring_hom.map_add, int.cast_sub, zmod.int_cast_cast, int.cast_add], rw [zmod.cast_add (show p^n ∣ p^j, from pow_dvd_pow _ hj), sub_self], { apply_instance }, end lemma nth_hom_seq_mul (r s : R) : nth_hom_seq f_compat (r * s) ≈ nth_hom_seq f_compat r * nth_hom_seq f_compat s := begin intros ε hε, obtain ⟨n, hn⟩ := exists_pow_neg_lt_rat p hε, use n, intros j hj, dsimp [nth_hom_seq], apply lt_of_le_of_lt _ hn, rw [← int.cast_mul, ← int.cast_sub, ← padic_norm.dvd_iff_norm_le, ← zmod.int_coe_zmod_eq_zero_iff_dvd], dsimp [nth_hom], simp only [zmod.nat_cast_val, ring_hom.map_mul, int.cast_sub, zmod.int_cast_cast, int.cast_mul], rw [zmod.cast_mul (show p^n ∣ p^j, from pow_dvd_pow _ hj), sub_self], { apply_instance }, end /-- `lim_nth_hom f_compat r` is the limit of a sequence `f` of compatible ring homs `R →+* zmod (p^k)`. This is itself a ring hom: see `padic_int.lift`. -/ def lim_nth_hom (r : R) : ℤ_[p] := of_int_seq (nth_hom f r) (is_cau_seq_nth_hom f_compat r) lemma lim_nth_hom_spec (r : R) : ∀ ε : ℝ, 0 < ε → ∃ N : ℕ, ∀ n ≥ N, ‖lim_nth_hom f_compat r - nth_hom f r n‖ < ε := begin intros ε hε, obtain ⟨ε', hε'0, hε'⟩ : ∃ v : ℚ, (0 : ℝ) < v ∧ ↑v < ε := exists_rat_btwn hε, norm_cast at hε'0, obtain ⟨N, hN⟩ := padic_norm_e.defn (nth_hom_seq f_compat r) hε'0, use N, intros n hn, apply lt_trans _ hε', change ↑(padic_norm_e _) < _, norm_cast, exact hN _ hn, end lemma lim_nth_hom_zero : lim_nth_hom f_compat 0 = 0 := by simp [lim_nth_hom]; refl lemma lim_nth_hom_one : lim_nth_hom f_compat 1 = 1 := subtype.ext $ quot.sound $ nth_hom_seq_one _ lemma lim_nth_hom_add (r s : R) : lim_nth_hom f_compat (r + s) = lim_nth_hom f_compat r + lim_nth_hom f_compat s := subtype.ext $ quot.sound $ nth_hom_seq_add _ _ _ lemma lim_nth_hom_mul (r s : R) : lim_nth_hom f_compat (r * s) = lim_nth_hom f_compat r * lim_nth_hom f_compat s := subtype.ext $ quot.sound $ nth_hom_seq_mul _ _ _ -- TODO: generalize this to arbitrary complete discrete valuation rings /-- `lift f_compat` is the limit of a sequence `f` of compatible ring homs `R →+* zmod (p^k)`, with the equality `lift f_compat r = padic_int.lim_nth_hom f_compat r`. -/ def lift : R →+* ℤ_[p] := { to_fun := lim_nth_hom f_compat, map_one' := lim_nth_hom_one f_compat, map_mul' := lim_nth_hom_mul f_compat, map_zero' := lim_nth_hom_zero f_compat, map_add' := lim_nth_hom_add f_compat } omit f_compat lemma lift_sub_val_mem_span (r : R) (n : ℕ) : (lift f_compat r - (f n r).val) ∈ (ideal.span {↑p ^ n} : ideal ℤ_[p]) := begin obtain ⟨k, hk⟩ := lim_nth_hom_spec f_compat r _ (show (0 : ℝ) < p ^ (-n : ℤ), from nat.zpow_pos_of_pos hp_prime.1.pos _), have := le_of_lt (hk (max n k) (le_max_right _ _)), rw norm_le_pow_iff_mem_span_pow at this, dsimp [lift], rw sub_eq_sub_add_sub (lim_nth_hom f_compat r) _ ↑(nth_hom f r (max n k)), apply ideal.add_mem _ _ this, rw [ideal.mem_span_singleton], simpa only [eq_int_cast, ring_hom.map_pow, int.cast_sub] using (int.cast_ring_hom ℤ_[p]).map_dvd (pow_dvd_nth_hom_sub f_compat r n (max n k) (le_max_left _ _)), end /-- One part of the universal property of `ℤ_[p]` as a projective limit. See also `padic_int.lift_unique`. -/ lemma lift_spec (n : ℕ) : (to_zmod_pow n).comp (lift f_compat) = f n := begin ext r, rw [ring_hom.comp_apply, ← zmod.nat_cast_zmod_val (f n r), ← map_nat_cast $ to_zmod_pow n, ← sub_eq_zero, ← ring_hom.map_sub, ← ring_hom.mem_ker, ker_to_zmod_pow], apply lift_sub_val_mem_span, end /-- One part of the universal property of `ℤ_[p]` as a projective limit. See also `padic_int.lift_spec`. -/ lemma lift_unique (g : R →+* ℤ_[p]) (hg : ∀ n, (to_zmod_pow n).comp g = f n) : lift f_compat = g := begin ext1 r, apply eq_of_forall_dist_le, intros ε hε, obtain ⟨n, hn⟩ := exists_pow_neg_lt p hε, apply le_trans _ (le_of_lt hn), rw [dist_eq_norm, norm_le_pow_iff_mem_span_pow, ← ker_to_zmod_pow, ring_hom.mem_ker, ring_hom.map_sub, ← ring_hom.comp_apply, ← ring_hom.comp_apply, lift_spec, hg, sub_self], end @[simp] lemma lift_self (z : ℤ_[p]) : @lift p _ ℤ_[p] _ to_zmod_pow zmod_cast_comp_to_zmod_pow z = z := begin show _ = ring_hom.id _ z, rw @lift_unique p _ ℤ_[p] _ _ zmod_cast_comp_to_zmod_pow (ring_hom.id ℤ_[p]), intro, rw ring_hom.comp_id, end end lift lemma ext_of_to_zmod_pow {x y : ℤ_[p]} : (∀ n, to_zmod_pow n x = to_zmod_pow n y) ↔ x = y := begin split, { intro h, rw [← lift_self x, ← lift_self y], simp [lift, lim_nth_hom, nth_hom, h] }, { rintro rfl _, refl } end lemma to_zmod_pow_eq_iff_ext {R : Type*} [non_assoc_semiring R] {g g' : R →+* ℤ_[p]} : (∀ n, (to_zmod_pow n).comp g = (to_zmod_pow n).comp g') ↔ g = g' := begin split, { intro hg, ext x : 1, apply ext_of_to_zmod_pow.mp, intro n, show (to_zmod_pow n).comp g x = (to_zmod_pow n).comp g' x, rw hg n }, { rintro rfl _, refl } end end padic_int
36544a4313b151b204367675139d842f4c02eb4c
56af0912bd25910f5caae91d6dd0603b0c032989
/src/complex/kb_solutions/Level_04_norm_sq.lean
8939b7092ed744bd0ee9d32af6dc16b48a1f96e7
[ "Apache-2.0" ]
permissive
isabella232/complex-number-game
ae36e0b1df9761d9df07049ca29c91ae44dbdc2d
3d767f14041f9002e435bed3a3527fdd297c166d
refs/heads/master
1,679,305,953,116
1,606,397,567,000
1,606,397,567,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,620
lean
/- Copyright (c) 2020 The Xena project. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard. Thanks: Imperial College London, leanprover-community -/ -- Import levels 1 to 3 import complex.kb_solutions.Level_03_conj /-! # Level 4: Norms Define `norm_sq : ℂ → ℝ` by defining `norm_sq(z)` to be `re(z)*re(z)+im(z)*im(z)` and see what you can prove about it. -/ namespace complex /-- The real number which is the squared norm of z -/ def norm_sq (z : ℂ) : ℝ := re(z)*re(z)+im(z)*im(z) local attribute [simp] ext_iff -- next few proofs are are all mostl simp [norm_sq] so let's locally -- tell simp about it for this section only section simp_knows_norm_sq local attribute [simp] norm_sq /-! ## Behaviour with respect to 0, 1 and I -/ @[simp] lemma norm_sq_zero : norm_sq 0 = 0 := by simp @[simp] lemma norm_sq_one : norm_sq 1 = 1 := by simp @[simp] lemma norm_sq_I : norm_sq I = 1 := by simp /-! ## Behaviour with respect to *, + and - -/ @[simp] lemma norm_sq_mul (z w : ℂ) : norm_sq (z * w) = norm_sq z * norm_sq w := by simp; ring lemma norm_sq_add (z w : ℂ) : norm_sq (z + w) = norm_sq z + norm_sq w + 2 * (z * conj w).re := by simp; ring @[simp] lemma norm_sq_neg (z : ℂ) : norm_sq (-z) = norm_sq z := by simp /-! ## Behaviour with respect to `conj` -/ @[simp] lemma norm_sq_conj (z : ℂ) : norm_sq (conj z) = norm_sq z := by simp /-! ## Behaviour with respect to real numbers` -/ @[simp] lemma norm_sq_of_real (r : ℝ) : norm_sq r = r * r := by simp theorem mul_conj (z : ℂ) : z * conj z = norm_sq z := by simp; ring -- time to end the section; simp no longer knows about norm_sq end simp_knows_norm_sq /-! ## Behaviour with respect to real 0, ≤, < and so on -/ -- Warning: you will have to know something about Lean's API for -- real numbers to solve these ones. If you turn the statements about -- complex numbers into statements about real numbers, you'll find -- they're of the form "prove $$x^2+y^2\geq0$$" with `x` and `y` real. example (y : ℝ) : 0 ≤ y * y := mul_self_nonneg y namespace realtac lemma norm_nonneg (x y : ℝ) : 0 ≤ x * x + y * y := begin nlinarith, end lemma norm_eq_zero_iff {x y : ℝ} : x * x + y * y = 0 ↔ x = 0 ∧ y = 0 := begin split, { intro h, rw add_eq_zero_iff' at h, { simp * at *}, { apply mul_self_nonneg}, { apply mul_self_nonneg}}, { rintros ⟨rfl, rfl⟩, simp, } end lemma norm_nonpos_right {x y : ℝ} (h1 : x * x + y * y ≤ 0) : y = 0 := begin suffices : x = 0 ∧ y = 0, simp [this], rw ←norm_eq_zero_iff, linarith [norm_nonneg x y], end lemma norm_nonpos_left (x y : ℝ) (h1 : x * x + y * y ≤ 0) : x = 0 := begin rw add_comm at h1, apply norm_nonpos_right h1, end end realtac -- back to the levels lemma norm_sq_nonneg (z : ℂ) : 0 ≤ norm_sq z := begin cases z with x y, simp [norm_sq], apply realtac.norm_nonneg, end @[simp] lemma norm_sq_eq_zero (z : ℂ) : norm_sq z = 0 ↔ z = 0 := begin cases z with x y, simp [norm_sq], exact realtac.norm_eq_zero_iff end @[simp] lemma norm_sq_ne_zero {z : ℂ} : norm_sq z ≠ 0 ↔ z ≠ 0 := begin have h := norm_sq_eq_zero z, tauto! end @[simp] lemma norm_sq_pos {z : ℂ} : 0 < norm_sq z ↔ z ≠ 0 := begin rw lt_iff_le_and_ne, rw ne_comm, simp [norm_sq_nonneg], end lemma re_sq_le_norm_sq (z : ℂ) : z.re * z.re ≤ norm_sq z := begin simp [norm_sq], apply mul_self_nonneg, end lemma im_sq_le_norm_sq (z : ℂ) : z.im * z.im ≤ norm_sq z := begin simp [norm_sq], apply mul_self_nonneg end end complex
e743c6bf71bfa46f8695df388a89ef0ebcd074c3
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/finsupp/multiset.lean
f9d687b13f87f2c739db3a483e4c5d73beb3bc8d
[ "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
7,397
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import data.finsupp.basic import data.finsupp.order /-! # Equivalence between `multiset` and `ℕ`-valued finitely supported functions > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This defines `finsupp.to_multiset` the equivalence between `α →₀ ℕ` and `multiset α`, along with `multiset.to_finsupp` the reverse equivalence and `finsupp.order_iso_multiset` the equivalence promoted to an order isomorphism. -/ open finset open_locale big_operators classical noncomputable theory variables {α β ι : Type*} namespace finsupp /-- Given `f : α →₀ ℕ`, `f.to_multiset` is the multiset with multiplicities given by the values of `f` on the elements of `α`. We define this function as an `add_equiv`. -/ def to_multiset : (α →₀ ℕ) ≃+ multiset α := { to_fun := λ f, f.sum (λa n, n • {a}), inv_fun := λ s, ⟨s.to_finset, λ a, s.count a, λ a, by simp⟩, left_inv := λ f, ext $ λ a, by { simp only [sum, multiset.count_sum', multiset.count_singleton, mul_boole, coe_mk, mem_support_iff, multiset.count_nsmul, finset.sum_ite_eq, ite_not, ite_eq_right_iff], exact eq.symm }, right_inv := λ s, by simp only [sum, coe_mk, multiset.to_finset_sum_count_nsmul_eq], map_add' := λ f g, sum_add_index' (λ a, zero_nsmul _) (λ a, add_nsmul _) } lemma to_multiset_zero : (0 : α →₀ ℕ).to_multiset = 0 := rfl lemma to_multiset_add (m n : α →₀ ℕ) : (m + n).to_multiset = m.to_multiset + n.to_multiset := to_multiset.map_add m n lemma to_multiset_apply (f : α →₀ ℕ) : f.to_multiset = f.sum (λ a n, n • {a}) := rfl @[simp] lemma to_multiset_symm_apply [decidable_eq α] (s : multiset α) (x : α) : finsupp.to_multiset.symm s x = s.count x := by convert rfl @[simp] lemma to_multiset_single (a : α) (n : ℕ) : to_multiset (single a n) = n • {a} := by rw [to_multiset_apply, sum_single_index]; apply zero_nsmul lemma to_multiset_sum {f : ι → α →₀ ℕ} (s : finset ι) : finsupp.to_multiset (∑ i in s, f i) = ∑ i in s, finsupp.to_multiset (f i) := add_equiv.map_sum _ _ _ lemma to_multiset_sum_single (s : finset ι) (n : ℕ) : finsupp.to_multiset (∑ i in s, single i n) = n • s.val := by simp_rw [to_multiset_sum, finsupp.to_multiset_single, sum_nsmul, sum_multiset_singleton] lemma card_to_multiset (f : α →₀ ℕ) : f.to_multiset.card = f.sum (λ a, id) := by simp [to_multiset_apply, add_monoid_hom.map_finsupp_sum, function.id_def] lemma to_multiset_map (f : α →₀ ℕ) (g : α → β) : f.to_multiset.map g = (f.map_domain g).to_multiset := begin refine f.induction _ _, { rw [to_multiset_zero, multiset.map_zero, map_domain_zero, to_multiset_zero] }, { assume a n f _ _ ih, rw [to_multiset_add, multiset.map_add, ih, map_domain_add, map_domain_single, to_multiset_single, to_multiset_add, to_multiset_single, ← multiset.coe_map_add_monoid_hom, (multiset.map_add_monoid_hom g).map_nsmul], refl } end @[simp] lemma prod_to_multiset [comm_monoid α] (f : α →₀ ℕ) : f.to_multiset.prod = f.prod (λ a n, a ^ n) := begin refine f.induction _ _, { rw [to_multiset_zero, multiset.prod_zero, finsupp.prod_zero_index] }, { assume a n f _ _ ih, rw [to_multiset_add, multiset.prod_add, ih, to_multiset_single, multiset.prod_nsmul, finsupp.prod_add_index' pow_zero pow_add, finsupp.prod_single_index, multiset.prod_singleton], { exact pow_zero a } } end @[simp] lemma to_finset_to_multiset [decidable_eq α] (f : α →₀ ℕ) : f.to_multiset.to_finset = f.support := begin refine f.induction _ _, { rw [to_multiset_zero, multiset.to_finset_zero, support_zero] }, { assume a n f ha hn ih, rw [to_multiset_add, multiset.to_finset_add, ih, to_multiset_single, support_add_eq, support_single_ne_zero _ hn, multiset.to_finset_nsmul _ _ hn, multiset.to_finset_singleton], refine disjoint.mono_left support_single_subset _, rwa [finset.disjoint_singleton_left] } end @[simp] lemma count_to_multiset [decidable_eq α] (f : α →₀ ℕ) (a : α) : f.to_multiset.count a = f a := calc f.to_multiset.count a = f.sum (λx n, (n • {x} : multiset α).count a) : (multiset.count_add_monoid_hom a).map_sum _ f.support ... = f.sum (λx n, n * ({x} : multiset α).count a) : by simp only [multiset.count_nsmul] ... = f a * ({a} : multiset α).count a : sum_eq_single _ (λ a' _ H, by simp only [multiset.count_singleton, if_false, H.symm, mul_zero]) (λ H, by simp only [not_mem_support_iff.1 H, zero_mul]) ... = f a : by rw [multiset.count_singleton_self, mul_one] @[simp] lemma mem_to_multiset (f : α →₀ ℕ) (i : α) : i ∈ f.to_multiset ↔ i ∈ f.support := by rw [←multiset.count_ne_zero, finsupp.count_to_multiset, finsupp.mem_support_iff] end finsupp namespace multiset /-- Given a multiset `s`, `s.to_finsupp` returns the finitely supported function on `ℕ` given by the multiplicities of the elements of `s`. -/ def to_finsupp : multiset α ≃+ (α →₀ ℕ) := finsupp.to_multiset.symm @[simp] lemma to_finsupp_support [decidable_eq α] (s : multiset α) : s.to_finsupp.support = s.to_finset := by convert rfl @[simp] lemma to_finsupp_apply [decidable_eq α] (s : multiset α) (a : α) : to_finsupp s a = s.count a := by convert rfl lemma to_finsupp_zero : to_finsupp (0 : multiset α) = 0 := add_equiv.map_zero _ lemma to_finsupp_add (s t : multiset α) : to_finsupp (s + t) = to_finsupp s + to_finsupp t := to_finsupp.map_add s t @[simp] lemma to_finsupp_singleton (a : α) : to_finsupp ({a} : multiset α) = finsupp.single a 1 := finsupp.to_multiset.symm_apply_eq.2 $ by simp @[simp] lemma to_finsupp_to_multiset (s : multiset α) : s.to_finsupp.to_multiset = s := finsupp.to_multiset.apply_symm_apply s lemma to_finsupp_eq_iff {s : multiset α} {f : α →₀ ℕ} : s.to_finsupp = f ↔ s = f.to_multiset := finsupp.to_multiset.symm_apply_eq end multiset @[simp] lemma finsupp.to_multiset_to_finsupp (f : α →₀ ℕ) : f.to_multiset.to_finsupp = f := finsupp.to_multiset.symm_apply_apply f /-! ### As an order isomorphism -/ namespace finsupp /-- `finsupp.to_multiset` as an order isomorphism. -/ def order_iso_multiset : (ι →₀ ℕ) ≃o multiset ι := { to_equiv := to_multiset.to_equiv, map_rel_iff' := λ f g, by simp [multiset.le_iff_count, le_def] } @[simp] lemma coe_order_iso_multiset : ⇑(@order_iso_multiset ι) = to_multiset := rfl @[simp] lemma coe_order_iso_multiset_symm : ⇑(@order_iso_multiset ι).symm = multiset.to_finsupp := rfl lemma to_multiset_strict_mono : strict_mono (@to_multiset ι) := (@order_iso_multiset ι).strict_mono lemma sum_id_lt_of_lt (m n : ι →₀ ℕ) (h : m < n) : m.sum (λ _, id) < n.sum (λ _, id) := begin rw [←card_to_multiset, ←card_to_multiset], apply multiset.card_lt_of_lt, exact to_multiset_strict_mono h end variable (ι) /-- The order on `ι →₀ ℕ` is well-founded. -/ lemma lt_wf : well_founded (@has_lt.lt (ι →₀ ℕ) _) := subrelation.wf (sum_id_lt_of_lt) $ inv_image.wf _ nat.lt_wf end finsupp lemma multiset.to_finsupp_strict_mono : strict_mono (@multiset.to_finsupp ι) := (@finsupp.order_iso_multiset ι).symm.strict_mono
47d1c85a03da6dbfd137f6d0926476e0d5fc68d5
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/let1.lean
e988e596d347703e3b2ff5178f81e8327b7a8d87
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
444
lean
import Int. print let a : Nat := 10, b : Nat := 20, c : Nat := 30, d : Nat := 10 in a + b + c + d print let a : Nat := 1000000000000000000, b : Nat := 20000000000000000000, c : Nat := 3000000000000000000, d : Nat := 4000000000000000000 in a + b + c + d check let a : Nat := 10 in a + 1 eval let a : Nat := 20 in a + 10 eval let a := 20 in a + 10 check let a : Int := 20 in a + 10 set_option pp::coercion true print let a : Int := 20 in a + 10
907cebf01fcaf3e505074e5ed5df57f19b050f3c
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Init/Data/Array/Subarray.lean
02c8c2893109bd32b904a5ceebdeced2dc937c28
[ "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
6,099
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Data.Array.Basic universe u v w structure Subarray (α : Type u) where as : Array α start : Nat stop : Nat h₁ : start ≤ stop h₂ : stop ≤ as.size namespace Subarray def size (s : Subarray α) : Nat := s.stop - s.start def get (s : Subarray α) (i : Fin s.size) : α := have : s.start + i.val < s.as.size := by apply Nat.lt_of_lt_of_le _ s.h₂ have := i.isLt simp [size] at this rw [Nat.add_comm] exact Nat.add_lt_of_lt_sub this s.as[s.start + i.val] instance : GetElem (Subarray α) Nat α fun xs i => i < xs.size where getElem xs i h := xs.get ⟨i, h⟩ @[inline] def getD (s : Subarray α) (i : Nat) (v₀ : α) : α := if h : i < s.size then s.get ⟨i, h⟩ else v₀ abbrev get! [Inhabited α] (s : Subarray α) (i : Nat) : α := getD s i default def popFront (s : Subarray α) : Subarray α := if h : s.start < s.stop then { s with start := s.start + 1, h₁ := Nat.le_of_lt_succ (Nat.add_lt_add_right h 1) } else s @[inline] unsafe def forInUnsafe {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (s : Subarray α) (b : β) (f : α → β → m (ForInStep β)) : m β := let sz := USize.ofNat s.stop let rec @[specialize] loop (i : USize) (b : β) : m β := do if i < sz then let a := s.as.uget i lcProof match (← f a b) with | ForInStep.done b => pure b | ForInStep.yield b => loop (i+1) b else pure b loop (USize.ofNat s.start) b -- TODO: provide reference implementation @[implemented_by Subarray.forInUnsafe] protected opaque forIn {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (s : Subarray α) (b : β) (f : α → β → m (ForInStep β)) : m β := pure b instance : ForIn m (Subarray α) α where forIn := Subarray.forIn @[inline] def foldlM {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (f : β → α → m β) (init : β) (as : Subarray α) : m β := as.as.foldlM f (init := init) (start := as.start) (stop := as.stop) @[inline] def foldrM {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (f : α → β → m β) (init : β) (as : Subarray α) : m β := as.as.foldrM f (init := init) (start := as.stop) (stop := as.start) @[inline] def anyM {α : Type u} {m : Type → Type w} [Monad m] (p : α → m Bool) (as : Subarray α) : m Bool := as.as.anyM p (start := as.start) (stop := as.stop) @[inline] def allM {α : Type u} {m : Type → Type w} [Monad m] (p : α → m Bool) (as : Subarray α) : m Bool := as.as.allM p (start := as.start) (stop := as.stop) @[inline] def forM {α : Type u} {m : Type v → Type w} [Monad m] (f : α → m PUnit) (as : Subarray α) : m PUnit := as.as.forM f (start := as.start) (stop := as.stop) @[inline] def forRevM {α : Type u} {m : Type v → Type w} [Monad m] (f : α → m PUnit) (as : Subarray α) : m PUnit := as.as.forRevM f (start := as.stop) (stop := as.start) @[inline] def foldl {α : Type u} {β : Type v} (f : β → α → β) (init : β) (as : Subarray α) : β := Id.run <| as.foldlM f (init := init) @[inline] def foldr {α : Type u} {β : Type v} (f : α → β → β) (init : β) (as : Subarray α) : β := Id.run <| as.foldrM f (init := init) @[inline] def any {α : Type u} (p : α → Bool) (as : Subarray α) : Bool := Id.run <| as.anyM p @[inline] def all {α : Type u} (p : α → Bool) (as : Subarray α) : Bool := Id.run <| as.allM p @[inline] def findSomeRevM? {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (as : Subarray α) (f : α → m (Option β)) : m (Option β) := let rec @[specialize] find : (i : Nat) → i ≤ as.size → m (Option β) | 0, _ => pure none | i+1, h => do have : i < as.size := Nat.lt_of_lt_of_le (Nat.lt_succ_self _) h let r ← f as[i] match r with | some _ => pure r | none => have : i ≤ as.size := Nat.le_of_lt this find i this find as.size (Nat.le_refl _) @[inline] def findRevM? {α : Type} {m : Type → Type w} [Monad m] (as : Subarray α) (p : α → m Bool) : m (Option α) := as.findSomeRevM? fun a => return if (← p a) then some a else none @[inline] def findRev? {α : Type} (as : Subarray α) (p : α → Bool) : Option α := Id.run <| as.findRevM? p end Subarray namespace Array variable {α : Type u} def toSubarray (as : Array α) (start : Nat := 0) (stop : Nat := as.size) : Subarray α := if h₂ : stop ≤ as.size then if h₁ : start ≤ stop then { as := as, start := start, stop := stop, h₁ := h₁, h₂ := h₂ } else { as := as, start := stop, stop := stop, h₁ := Nat.le_refl _, h₂ := h₂ } else if h₁ : start ≤ as.size then { as := as, start := start, stop := as.size, h₁ := h₁, h₂ := Nat.le_refl _ } else { as := as, start := as.size, stop := as.size, h₁ := Nat.le_refl _, h₂ := Nat.le_refl _ } def ofSubarray (s : Subarray α) : Array α := Id.run do let mut as := mkEmpty (s.stop - s.start) for a in s do as := as.push a return as instance : Coe (Subarray α) (Array α) := ⟨ofSubarray⟩ syntax:max term noWs "[" withoutPosition(term ":" term) "]" : term syntax:max term noWs "[" withoutPosition(term ":") "]" : term syntax:max term noWs "[" withoutPosition(":" term) "]" : term macro_rules | `($a[$start : $stop]) => `(Array.toSubarray $a $start $stop) | `($a[ : $stop]) => `(Array.toSubarray $a 0 $stop) | `($a[$start : ]) => `(let a := $a; Array.toSubarray a $start a.size) end Array def Subarray.toArray (s : Subarray α) : Array α := Array.ofSubarray s instance : Append (Subarray α) where append x y := let a := x.toArray ++ y.toArray a.toSubarray 0 a.size instance [Repr α] : Repr (Subarray α) where reprPrec s _ := repr s.toArray ++ ".toSubarray" instance [ToString α] : ToString (Subarray α) where toString s := toString s.toArray
b01838a6d0399512c8b533048490be74ba485f86
63abd62053d479eae5abf4951554e1064a4c45b4
/src/geometry/manifold/algebra/lie_group.lean
4f22467a7d48c155b4a67a8af941f651659b4ecb
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
10,461
lean
/- Copyright © 2020 Nicolò Cavalleri. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Nicolò Cavalleri. -/ import geometry.manifold.algebra.monoid /-! # Lie groups A Lie group is a group that is also a smooth manifold, in which the group operations of multiplication and inversion are smooth maps. Smoothness of the group multiplication means that multiplication is a smooth mapping of the product manifold `G` × `G` into `G`. Note that, since a manifold here is not second-countable and Hausdorff a Lie group here is not guaranteed to be second-countable (even though it can be proved it is Hausdorff). Note also that Lie groups here are not necessarily finite dimensional. ## Main definitions and statements * `lie_add_group I G` : a Lie additive group where `G` is a manifold on the model with corners `I`. * `lie_group I G` : a Lie multiplicative group where `G` is a manifold on the model with corners `I`. * `lie_add_group_morphism I I' G G'` : morphism of addittive Lie groups * `lie_group_morphism I I' G G'` : morphism of Lie groups * `lie_add_group_core I G` : allows to define a Lie additive group without first proving it is a topological additive group. * `lie_group_core I G` : allows to define a Lie group without first proving it is a topological group. * `reals_lie_group` : real numbers are a Lie group ## Implementation notes A priori, a Lie group here is a manifold with corners. The definition of Lie group cannot require `I : model_with_corners 𝕜 E E` with the same space as the model space and as the model vector space, as one might hope, beause in the product situation, the model space is `model_prod E E'` and the model vector space is `E × E'`, which are not the same, so the definition does not apply. Hence the definition should be more general, allowing `I : model_with_corners 𝕜 E H`. -/ noncomputable theory section set_option old_structure_cmd true /-- A Lie (additive) group is a group and a smooth manifold at the same time in which the addition and negation operations are smooth. -/ @[ancestor has_smooth_add] class lie_add_group {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {H : Type*} [topological_space H] {E : Type*} [normed_group E] [normed_space 𝕜 E] (I : model_with_corners 𝕜 E H) (G : Type*) [add_group G] [topological_space G] [topological_add_group G] [charted_space H G] extends has_smooth_add I G : Prop := (smooth_neg : smooth I I (λ a:G, -a)) /-- A Lie group is a group and a smooth manifold at the same time in which the multiplication and inverse operations are smooth. -/ @[ancestor has_smooth_mul, to_additive] class lie_group {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {H : Type*} [topological_space H] {E : Type*} [normed_group E] [normed_space 𝕜 E] (I : model_with_corners 𝕜 E H) (G : Type*) [group G] [topological_space G] [topological_group G] [charted_space H G] extends has_smooth_mul I G : Prop := (smooth_inv : smooth I I (λ a:G, a⁻¹)) end section lie_group variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {H : Type*} [topological_space H] {E : Type*} [normed_group E] [normed_space 𝕜 E] {I : model_with_corners 𝕜 E H} {F : Type*} [normed_group F] [normed_space 𝕜 F] {J : model_with_corners 𝕜 F F} {G : Type*} [topological_space G] [charted_space H G] [group G] [topological_group G] [lie_group I G] {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {H' : Type*} [topological_space H'] {I' : model_with_corners 𝕜 E' H'} {M : Type*} [topological_space M] [charted_space H' M] [smooth_manifold_with_corners I' M] {E'' : Type*} [normed_group E''] [normed_space 𝕜 E''] {H'' : Type*} [topological_space H''] {I'' : model_with_corners 𝕜 E'' H''} {M' : Type*} [topological_space M'] [charted_space H'' M'] [smooth_manifold_with_corners I'' M'] localized "notation `L_add` := left_add" in lie_group localized "notation `R_add` := right_add" in lie_group localized "notation `L` := left_mul" in lie_group localized "notation `R` := right_mul" in lie_group lemma smooth_pow : ∀ n : ℕ, smooth I I (λ a : G, a ^ n) | 0 := by { simp only [pow_zero], exact smooth_const } | (k+1) := show smooth I I (λ (a : G), a * a ^ k), from smooth_id.mul (smooth_pow _) @[to_additive] lemma smooth_inv : smooth I I (λ x : G, x⁻¹) := lie_group.smooth_inv @[to_additive] lemma smooth.inv {f : M → G} (hf : smooth I' I f) : smooth I' I (λx, (f x)⁻¹) := lie_group.smooth_inv.comp hf @[to_additive] lemma smooth_on.inv {f : M → G} {s : set M} (hf : smooth_on I' I f s) : smooth_on I' I (λx, (f x)⁻¹) s := smooth_inv.comp_smooth_on hf end lie_group section prod_lie_group /- Instance of product group -/ @[to_additive] instance {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {H : Type*} [topological_space H] {E : Type*} [normed_group E] [normed_space 𝕜 E] {I : model_with_corners 𝕜 E H} {G : Type*} [topological_space G] [charted_space H G] [group G] [topological_group G] [lie_group I G] {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {H' : Type*} [topological_space H'] {I' : model_with_corners 𝕜 E' H'} {G' : Type*} [topological_space G'] [charted_space H' G'] [group G'] [topological_group G'] [lie_group I' G'] : lie_group (I.prod I') (G×G') := { smooth_inv := smooth_fst.inv.prod_mk smooth_snd.inv, ..has_smooth_mul.prod _ _ _ _ } end prod_lie_group section lie_group_morphism variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] /-- Morphism of additive Lie groups. -/ structure lie_add_group_morphism (I : model_with_corners 𝕜 E E) (I' : model_with_corners 𝕜 E' E') (G : Type*) [topological_space G] [charted_space E G] [add_group G] [topological_add_group G] [lie_add_group I G] (G' : Type*) [topological_space G'] [charted_space E' G'] [add_group G'] [topological_add_group G'] [lie_add_group I' G'] extends smooth_add_monoid_morphism I I' G G' /-- Morphism of Lie groups. -/ @[to_additive] structure lie_group_morphism (I : model_with_corners 𝕜 E E) (I' : model_with_corners 𝕜 E' E') (G : Type*) [topological_space G] [charted_space E G] [group G] [topological_group G] [lie_group I G] (G' : Type*) [topological_space G'] [charted_space E' G'] [group G'] [topological_group G'] [lie_group I' G'] extends smooth_monoid_morphism I I' G G' variables {I : model_with_corners 𝕜 E E} {I' : model_with_corners 𝕜 E' E'} {G : Type*} [topological_space G] [charted_space E G] [group G] [topological_group G] [lie_group I G] {G' : Type*} [topological_space G'] [charted_space E' G'] [group G'] [topological_group G'] [lie_group I' G'] @[to_additive] instance : has_one (lie_group_morphism I I' G G') := ⟨{ ..(1 : smooth_monoid_morphism I I' G G') }⟩ @[to_additive] instance : inhabited (lie_group_morphism I I' G G') := ⟨1⟩ @[to_additive] instance : has_coe_to_fun (lie_group_morphism I I' G G') := ⟨_, λ a, a.to_fun⟩ end lie_group_morphism section lie_group_core section set_option old_structure_cmd true /-- Sometimes one might want to define a Lie additive group `G` without having proved previously that `G` is a topological additive group. In such case it is possible to use `lie_add_group_core` that does not require such instance, and then get a Lie group by invoking `to_lie_add_group`. -/ @[ancestor smooth_manifold_with_corner] structure lie_add_group_core {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] (I : model_with_corners 𝕜 E E) (G : Type*) [add_group G] [topological_space G] [charted_space E G] extends smooth_manifold_with_corners I G : Prop := (smooth_add : smooth (I.prod I) I (λ p : G×G, p.1 + p.2)) (smooth_neg : smooth I I (λ a:G, -a)) /-- Sometimes one might want to define a Lie group `G` without having proved previously that `G` is a topological group. In such case it is possible to use `lie_group_core` that does not require such instance, and then get a Lie group by invoking `to_lie_group` defined below. -/ @[ancestor smooth_manifold_with_corner, to_additive] structure lie_group_core {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] (I : model_with_corners 𝕜 E E) (G : Type*) [group G] [topological_space G] [charted_space E G] extends smooth_manifold_with_corners I G : Prop := (smooth_mul : smooth (I.prod I) I (λ p : G×G, p.1 * p.2)) (smooth_inv : smooth I I (λ a:G, a⁻¹)) -- The linter does not recognize that the followings are structure projections, disable it attribute [nolint def_lemma doc_blame] lie_add_group_core.to_smooth_manifold_with_corners lie_group_core.to_smooth_manifold_with_corners end variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {I : model_with_corners 𝕜 E E} {F : Type*} [normed_group F] [normed_space 𝕜 F] {J : model_with_corners 𝕜 F F} {G : Type*} [topological_space G] [charted_space E G] [group G] namespace lie_group_core variables (c : lie_group_core I G) @[to_additive] protected lemma to_topological_group : topological_group G := { continuous_mul := c.smooth_mul.continuous, continuous_inv := c.smooth_inv.continuous, } @[to_additive] protected lemma to_lie_group : @lie_group 𝕜 _ _ _ E _ _ I G _ _ c.to_topological_group _ := { smooth_mul := c.smooth_mul, smooth_inv := c.smooth_inv, .. c.to_smooth_manifold_with_corners } end lie_group_core end lie_group_core section normed_space_lie_group /-! ### Normed spaces are Lie groups -/ instance normed_space_lie_group {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] : lie_add_group (model_with_corners_self 𝕜 E) E := { smooth_add := begin rw smooth_iff, refine ⟨continuous_add, λ x y, _⟩, simp only [prod.mk.eta] with mfld_simps, rw times_cont_diff_on_univ, exact times_cont_diff_add, end, smooth_neg := begin rw smooth_iff, refine ⟨continuous_neg, λ x y, _⟩, simp only [prod.mk.eta] with mfld_simps, rw times_cont_diff_on_univ, exact times_cont_diff_neg, end, .. model_space_smooth } end normed_space_lie_group
56896d3b5094cb2ed3aab0b9aeb0c652eabbb416
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/order/filter/extr.lean
9b582559657d6f3d2ea0a74fc501d0e73fb36bd1
[ "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
20,916
lean
/- Copyright (c) 2019 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import order.filter.basic /-! # Minimum and maximum w.r.t. a filter and on a aet ## Main Definitions This file defines six predicates of the form `is_A_B`, where `A` is `min`, `max`, or `extr`, and `B` is `filter` or `on`. * `is_min_filter f l a` means that `f a ≤ f x` in some `l`-neighborhood of `a`; * `is_max_filter f l a` means that `f x ≤ f a` in some `l`-neighborhood of `a`; * `is_extr_filter f l a` means `is_min_filter f l a` or `is_max_filter f l a`. Similar predicates with `_on` suffix are particular cases for `l = 𝓟 s`. ## Main statements ### Change of the filter (set) argument * `is_*_filter.filter_mono` : replace the filter with a smaller one; * `is_*_filter.filter_inf` : replace a filter `l` with `l ⊓ l'`; * `is_*_on.on_subset` : restrict to a smaller set; * `is_*_on.inter` : replace a set `s` wtih `s ∩ t`. ### Composition * `is_*_*.comp_mono` : if `x` is an extremum for `f` and `g` is a monotone function, then `x` is an extremum for `g ∘ f`; * `is_*_*.comp_antimono` : similarly for the case of monotonically decreasing `g`; * `is_*_*.bicomp_mono` : if `x` is an extremum of the same type for `f` and `g` and a binary operation `op` is monotone in both arguments, then `x` is an extremum of the same type for `λ x, op (f x) (g x)`. * `is_*_filter.comp_tendsto` : if `g x` is an extremum for `f` w.r.t. `l'` and `tendsto g l l'`, then `x` is an extremum for `f ∘ g` w.r.t. `l`. * `is_*_on.on_preimage` : if `g x` is an extremum for `f` on `s`, then `x` is an extremum for `f ∘ g` on `g ⁻¹' s`. ### Algebraic operations * `is_*_*.add` : if `x` is an extremum of the same type for two functions, then it is an extremum of the same type for their sum; * `is_*_*.neg` : if `x` is an extremum for `f`, then it is an extremum of the opposite type for `-f`; * `is_*_*.sub` : if `x` is an a minimum for `f` and a maximum for `g`, then it is a minimum for `f - g` and a maximum for `g - f`; * `is_*_*.max`, `is_*_*.min`, `is_*_*.sup`, `is_*_*.inf` : similarly for `is_*_*.add` for pointwise `max`, `min`, `sup`, `inf`, respectively. ### Miscellaneous definitions * `is_*_*_const` : any point is both a minimum and maximum for a constant function; * `is_min/max_*.is_ext` : any minimum/maximum point is an extremum; * `is_*_*.dual`, `is_*_*.undual`: conversion between codomains `α` and `dual α`; ## Missing features (TODO) * Multiplication and division; * `is_*_*.bicompl` : if `x` is a minimum for `f`, `y` is a minimum for `g`, and `op` is a monotone binary operation, then `(x, y)` is a minimum for `uncurry (bicompl op f g)`. From this point of view, `is_*_*.bicomp` is a composition * It would be nice to have a tactic that specializes `comp_(anti)mono` or `bicomp_mono` based on a proof of monotonicity of a given (binary) function. The tactic should maintain a `meta` list of known (anti)monotone (binary) functions with their names, as well as a list of special types of filters, and define the missing lemmas once one of these two lists grows. -/ universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} open set filter open_locale filter section preorder variables [preorder β] [preorder γ] variables (f : α → β) (s : set α) (l : filter α) (a : α) /-! ### Definitions -/ /-- `is_min_filter f l a` means that `f a ≤ f x` in some `l`-neighborhood of `a` -/ def is_min_filter : Prop := ∀ᶠ x in l, f a ≤ f x /-- `is_max_filter f l a` means that `f x ≤ f a` in some `l`-neighborhood of `a` -/ def is_max_filter : Prop := ∀ᶠ x in l, f x ≤ f a /-- `is_extr_filter f l a` means `is_min_filter f l a` or `is_max_filter f l a` -/ def is_extr_filter : Prop := is_min_filter f l a ∨ is_max_filter f l a /-- `is_min_on f s a` means that `f a ≤ f x` for all `x ∈ a`. Note that we do not assume `a ∈ s`. -/ def is_min_on := is_min_filter f (𝓟 s) a /-- `is_max_on f s a` means that `f x ≤ f a` for all `x ∈ a`. Note that we do not assume `a ∈ s`. -/ def is_max_on := is_max_filter f (𝓟 s) a /-- `is_extr_on f s a` means `is_min_on f s a` or `is_max_on f s a` -/ def is_extr_on : Prop := is_extr_filter f (𝓟 s) a variables {f s a l} {t : set α} {l' : filter α} lemma is_extr_on.elim {p : Prop} : is_extr_on f s a → (is_min_on f s a → p) → (is_max_on f s a → p) → p := or.elim lemma is_min_on_iff : is_min_on f s a ↔ ∀ x ∈ s, f a ≤ f x := iff.rfl lemma is_max_on_iff : is_max_on f s a ↔ ∀ x ∈ s, f x ≤ f a := iff.rfl lemma is_min_on_univ_iff : is_min_on f univ a ↔ ∀ x, f a ≤ f x := univ_subset_iff.trans eq_univ_iff_forall lemma is_max_on_univ_iff : is_max_on f univ a ↔ ∀ x, f x ≤ f a := univ_subset_iff.trans eq_univ_iff_forall /-! ### Conversion to `is_extr_*` -/ lemma is_min_filter.is_extr : is_min_filter f l a → is_extr_filter f l a := or.inl lemma is_max_filter.is_extr : is_max_filter f l a → is_extr_filter f l a := or.inr lemma is_min_on.is_extr (h : is_min_on f s a) : is_extr_on f s a := h.is_extr lemma is_max_on.is_extr (h : is_max_on f s a) : is_extr_on f s a := h.is_extr /-! ### Constant function -/ lemma is_min_filter_const {b : β} : is_min_filter (λ _, b) l a := univ_mem_sets' $ λ _, le_refl _ lemma is_max_filter_const {b : β} : is_max_filter (λ _, b) l a := univ_mem_sets' $ λ _, le_refl _ lemma is_extr_filter_const {b : β} : is_extr_filter (λ _, b) l a := is_min_filter_const.is_extr lemma is_min_on_const {b : β} : is_min_on (λ _, b) s a := is_min_filter_const lemma is_max_on_const {b : β} : is_max_on (λ _, b) s a := is_max_filter_const lemma is_extr_on_const {b : β} : is_extr_on (λ _, b) s a := is_extr_filter_const /-! ### Order dual -/ lemma is_min_filter_dual_iff : @is_min_filter α (order_dual β) _ f l a ↔ is_max_filter f l a := iff.rfl lemma is_max_filter_dual_iff : @is_max_filter α (order_dual β) _ f l a ↔ is_min_filter f l a := iff.rfl lemma is_extr_filter_dual_iff : @is_extr_filter α (order_dual β) _ f l a ↔ is_extr_filter f l a := or_comm _ _ alias is_min_filter_dual_iff ↔ is_min_filter.undual is_max_filter.dual alias is_max_filter_dual_iff ↔ is_max_filter.undual is_min_filter.dual alias is_extr_filter_dual_iff ↔ is_extr_filter.undual is_extr_filter.dual lemma is_min_on_dual_iff : @is_min_on α (order_dual β) _ f s a ↔ is_max_on f s a := iff.rfl lemma is_max_on_dual_iff : @is_max_on α (order_dual β) _ f s a ↔ is_min_on f s a := iff.rfl lemma is_extr_on_dual_iff : @is_extr_on α (order_dual β) _ f s a ↔ is_extr_on f s a := or_comm _ _ alias is_min_on_dual_iff ↔ is_min_on.undual is_max_on.dual alias is_max_on_dual_iff ↔ is_max_on.undual is_min_on.dual alias is_extr_on_dual_iff ↔ is_extr_on.undual is_extr_on.dual /-! ### Operations on the filter/set -/ lemma is_min_filter.filter_mono (h : is_min_filter f l a) (hl : l' ≤ l) : is_min_filter f l' a := hl h lemma is_max_filter.filter_mono (h : is_max_filter f l a) (hl : l' ≤ l) : is_max_filter f l' a := hl h lemma is_extr_filter.filter_mono (h : is_extr_filter f l a) (hl : l' ≤ l) : is_extr_filter f l' a := h.elim (λ h, (h.filter_mono hl).is_extr) (λ h, (h.filter_mono hl).is_extr) lemma is_min_filter.filter_inf (h : is_min_filter f l a) (l') : is_min_filter f (l ⊓ l') a := h.filter_mono inf_le_left lemma is_max_filter.filter_inf (h : is_max_filter f l a) (l') : is_max_filter f (l ⊓ l') a := h.filter_mono inf_le_left lemma is_extr_filter.filter_inf (h : is_extr_filter f l a) (l') : is_extr_filter f (l ⊓ l') a := h.filter_mono inf_le_left lemma is_min_on.on_subset (hf : is_min_on f t a) (h : s ⊆ t) : is_min_on f s a := hf.filter_mono $ principal_mono.2 h lemma is_max_on.on_subset (hf : is_max_on f t a) (h : s ⊆ t) : is_max_on f s a := hf.filter_mono $ principal_mono.2 h lemma is_extr_on.on_subset (hf : is_extr_on f t a) (h : s ⊆ t) : is_extr_on f s a := hf.filter_mono $ principal_mono.2 h lemma is_min_on.inter (hf : is_min_on f s a) (t) : is_min_on f (s ∩ t) a := hf.on_subset (inter_subset_left s t) lemma is_max_on.inter (hf : is_max_on f s a) (t) : is_max_on f (s ∩ t) a := hf.on_subset (inter_subset_left s t) lemma is_extr_on.inter (hf : is_extr_on f s a) (t) : is_extr_on f (s ∩ t) a := hf.on_subset (inter_subset_left s t) /-! ### Composition with (anti)monotone functions -/ lemma is_min_filter.comp_mono (hf : is_min_filter f l a) {g : β → γ} (hg : monotone g) : is_min_filter (g ∘ f) l a := mem_sets_of_superset hf $ λ x hx, hg hx lemma is_max_filter.comp_mono (hf : is_max_filter f l a) {g : β → γ} (hg : monotone g) : is_max_filter (g ∘ f) l a := mem_sets_of_superset hf $ λ x hx, hg hx lemma is_extr_filter.comp_mono (hf : is_extr_filter f l a) {g : β → γ} (hg : monotone g) : is_extr_filter (g ∘ f) l a := hf.elim (λ hf, (hf.comp_mono hg).is_extr) (λ hf, (hf.comp_mono hg).is_extr) lemma is_min_filter.comp_antimono (hf : is_min_filter f l a) {g : β → γ} (hg : ∀ ⦃x y⦄, x ≤ y → g y ≤ g x) : is_max_filter (g ∘ f) l a := hf.dual.comp_mono (λ x y h, hg h) lemma is_max_filter.comp_antimono (hf : is_max_filter f l a) {g : β → γ} (hg : ∀ ⦃x y⦄, x ≤ y → g y ≤ g x) : is_min_filter (g ∘ f) l a := hf.dual.comp_mono (λ x y h, hg h) lemma is_extr_filter.comp_antimono (hf : is_extr_filter f l a) {g : β → γ} (hg : ∀ ⦃x y⦄, x ≤ y → g y ≤ g x) : is_extr_filter (g ∘ f) l a := hf.dual.comp_mono (λ x y h, hg h) lemma is_min_on.comp_mono (hf : is_min_on f s a) {g : β → γ} (hg : monotone g) : is_min_on (g ∘ f) s a := hf.comp_mono hg lemma is_max_on.comp_mono (hf : is_max_on f s a) {g : β → γ} (hg : monotone g) : is_max_on (g ∘ f) s a := hf.comp_mono hg lemma is_extr_on.comp_mono (hf : is_extr_on f s a) {g : β → γ} (hg : monotone g) : is_extr_on (g ∘ f) s a := hf.comp_mono hg lemma is_min_on.comp_antimono (hf : is_min_on f s a) {g : β → γ} (hg : ∀ ⦃x y⦄, x ≤ y → g y ≤ g x) : is_max_on (g ∘ f) s a := hf.comp_antimono hg lemma is_max_on.comp_antimono (hf : is_max_on f s a) {g : β → γ} (hg : ∀ ⦃x y⦄, x ≤ y → g y ≤ g x) : is_min_on (g ∘ f) s a := hf.comp_antimono hg lemma is_extr_on.comp_antimono (hf : is_extr_on f s a) {g : β → γ} (hg : ∀ ⦃x y⦄, x ≤ y → g y ≤ g x) : is_extr_on (g ∘ f) s a := hf.comp_antimono hg lemma is_min_filter.bicomp_mono [preorder δ] {op : β → γ → δ} (hop : ((≤) ⇒ (≤) ⇒ (≤)) op op) (hf : is_min_filter f l a) {g : α → γ} (hg : is_min_filter g l a) : is_min_filter (λ x, op (f x) (g x)) l a := mem_sets_of_superset (inter_mem_sets hf hg) $ λ x ⟨hfx, hgx⟩, hop hfx hgx lemma is_max_filter.bicomp_mono [preorder δ] {op : β → γ → δ} (hop : ((≤) ⇒ (≤) ⇒ (≤)) op op) (hf : is_max_filter f l a) {g : α → γ} (hg : is_max_filter g l a) : is_max_filter (λ x, op (f x) (g x)) l a := mem_sets_of_superset (inter_mem_sets hf hg) $ λ x ⟨hfx, hgx⟩, hop hfx hgx -- No `extr` version because we need `hf` and `hg` to be of the same kind lemma is_min_on.bicomp_mono [preorder δ] {op : β → γ → δ} (hop : ((≤) ⇒ (≤) ⇒ (≤)) op op) (hf : is_min_on f s a) {g : α → γ} (hg : is_min_on g s a) : is_min_on (λ x, op (f x) (g x)) s a := hf.bicomp_mono hop hg lemma is_max_on.bicomp_mono [preorder δ] {op : β → γ → δ} (hop : ((≤) ⇒ (≤) ⇒ (≤)) op op) (hf : is_max_on f s a) {g : α → γ} (hg : is_max_on g s a) : is_max_on (λ x, op (f x) (g x)) s a := hf.bicomp_mono hop hg /-! ### Composition with `tendsto` -/ lemma is_min_filter.comp_tendsto {g : δ → α} {l' : filter δ} {b : δ} (hf : is_min_filter f l (g b)) (hg : tendsto g l' l) : is_min_filter (f ∘ g) l' b := hg hf lemma is_max_filter.comp_tendsto {g : δ → α} {l' : filter δ} {b : δ} (hf : is_max_filter f l (g b)) (hg : tendsto g l' l) : is_max_filter (f ∘ g) l' b := hg hf lemma is_extr_filter.comp_tendsto {g : δ → α} {l' : filter δ} {b : δ} (hf : is_extr_filter f l (g b)) (hg : tendsto g l' l) : is_extr_filter (f ∘ g) l' b := hf.elim (λ hf, (hf.comp_tendsto hg).is_extr) (λ hf, (hf.comp_tendsto hg).is_extr) lemma is_min_on.on_preimage (g : δ → α) {b : δ} (hf : is_min_on f s (g b)) : is_min_on (f ∘ g) (g ⁻¹' s) b := hf.comp_tendsto (tendsto_principal_principal.mpr $ subset.refl _) lemma is_max_on.on_preimage (g : δ → α) {b : δ} (hf : is_max_on f s (g b)) : is_max_on (f ∘ g) (g ⁻¹' s) b := hf.comp_tendsto (tendsto_principal_principal.mpr $ subset.refl _) lemma is_extr_on.on_preimage (g : δ → α) {b : δ} (hf : is_extr_on f s (g b)) : is_extr_on (f ∘ g) (g ⁻¹' s) b := hf.elim (λ hf, (hf.on_preimage g).is_extr) (λ hf, (hf.on_preimage g).is_extr) end preorder /-! ### Pointwise addition -/ section ordered_add_comm_monoid variables [ordered_add_comm_monoid β] {f g : α → β} {a : α} {s : set α} {l : filter α} lemma is_min_filter.add (hf : is_min_filter f l a) (hg : is_min_filter g l a) : is_min_filter (λ x, f x + g x) l a := show is_min_filter (λ x, f x + g x) l a, from hf.bicomp_mono (λ x x' hx y y' hy, add_le_add hx hy) hg lemma is_max_filter.add (hf : is_max_filter f l a) (hg : is_max_filter g l a) : is_max_filter (λ x, f x + g x) l a := show is_max_filter (λ x, f x + g x) l a, from hf.bicomp_mono (λ x x' hx y y' hy, add_le_add hx hy) hg lemma is_min_on.add (hf : is_min_on f s a) (hg : is_min_on g s a) : is_min_on (λ x, f x + g x) s a := hf.add hg lemma is_max_on.add (hf : is_max_on f s a) (hg : is_max_on g s a) : is_max_on (λ x, f x + g x) s a := hf.add hg end ordered_add_comm_monoid /-! ### Pointwise negation and subtraction -/ section ordered_add_comm_group variables [ordered_add_comm_group β] {f g : α → β} {a : α} {s : set α} {l : filter α} lemma is_min_filter.neg (hf : is_min_filter f l a) : is_max_filter (λ x, -f x) l a := hf.comp_antimono (λ x y hx, neg_le_neg hx) lemma is_max_filter.neg (hf : is_max_filter f l a) : is_min_filter (λ x, -f x) l a := hf.comp_antimono (λ x y hx, neg_le_neg hx) lemma is_extr_filter.neg (hf : is_extr_filter f l a) : is_extr_filter (λ x, -f x) l a := hf.elim (λ hf, hf.neg.is_extr) (λ hf, hf.neg.is_extr) lemma is_min_on.neg (hf : is_min_on f s a) : is_max_on (λ x, -f x) s a := hf.comp_antimono (λ x y hx, neg_le_neg hx) lemma is_max_on.neg (hf : is_max_on f s a) : is_min_on (λ x, -f x) s a := hf.comp_antimono (λ x y hx, neg_le_neg hx) lemma is_extr_on.neg (hf : is_extr_on f s a) : is_extr_on (λ x, -f x) s a := hf.elim (λ hf, hf.neg.is_extr) (λ hf, hf.neg.is_extr) lemma is_min_filter.sub (hf : is_min_filter f l a) (hg : is_max_filter g l a) : is_min_filter (λ x, f x - g x) l a := hf.add hg.neg lemma is_max_filter.sub (hf : is_max_filter f l a) (hg : is_min_filter g l a) : is_max_filter (λ x, f x - g x) l a := hf.add hg.neg lemma is_min_on.sub (hf : is_min_on f s a) (hg : is_max_on g s a) : is_min_on (λ x, f x - g x) s a := hf.add hg.neg lemma is_max_on.sub (hf : is_max_on f s a) (hg : is_min_on g s a) : is_max_on (λ x, f x - g x) s a := hf.add hg.neg end ordered_add_comm_group /-! ### Pointwise `sup`/`inf` -/ section semilattice_sup variables [semilattice_sup β] {f g : α → β} {a : α} {s : set α} {l : filter α} lemma is_min_filter.sup (hf : is_min_filter f l a) (hg : is_min_filter g l a) : is_min_filter (λ x, f x ⊔ g x) l a := show is_min_filter (λ x, f x ⊔ g x) l a, from hf.bicomp_mono (λ x x' hx y y' hy, sup_le_sup hx hy) hg lemma is_max_filter.sup (hf : is_max_filter f l a) (hg : is_max_filter g l a) : is_max_filter (λ x, f x ⊔ g x) l a := show is_max_filter (λ x, f x ⊔ g x) l a, from hf.bicomp_mono (λ x x' hx y y' hy, sup_le_sup hx hy) hg lemma is_min_on.sup (hf : is_min_on f s a) (hg : is_min_on g s a) : is_min_on (λ x, f x ⊔ g x) s a := hf.sup hg lemma is_max_on.sup (hf : is_max_on f s a) (hg : is_max_on g s a) : is_max_on (λ x, f x ⊔ g x) s a := hf.sup hg end semilattice_sup section semilattice_inf variables [semilattice_inf β] {f g : α → β} {a : α} {s : set α} {l : filter α} lemma is_min_filter.inf (hf : is_min_filter f l a) (hg : is_min_filter g l a) : is_min_filter (λ x, f x ⊓ g x) l a := show is_min_filter (λ x, f x ⊓ g x) l a, from hf.bicomp_mono (λ x x' hx y y' hy, inf_le_inf hx hy) hg lemma is_max_filter.inf (hf : is_max_filter f l a) (hg : is_max_filter g l a) : is_max_filter (λ x, f x ⊓ g x) l a := show is_max_filter (λ x, f x ⊓ g x) l a, from hf.bicomp_mono (λ x x' hx y y' hy, inf_le_inf hx hy) hg lemma is_min_on.inf (hf : is_min_on f s a) (hg : is_min_on g s a) : is_min_on (λ x, f x ⊓ g x) s a := hf.inf hg lemma is_max_on.inf (hf : is_max_on f s a) (hg : is_max_on g s a) : is_max_on (λ x, f x ⊓ g x) s a := hf.inf hg end semilattice_inf /-! ### Pointwise `min`/`max` -/ section decidable_linear_order variables [decidable_linear_order β] {f g : α → β} {a : α} {s : set α} {l : filter α} lemma is_min_filter.min (hf : is_min_filter f l a) (hg : is_min_filter g l a) : is_min_filter (λ x, min (f x) (g x)) l a := show is_min_filter (λ x, min (f x) (g x)) l a, from hf.bicomp_mono (λ x x' hx y y' hy, min_le_min hx hy) hg lemma is_max_filter.min (hf : is_max_filter f l a) (hg : is_max_filter g l a) : is_max_filter (λ x, min (f x) (g x)) l a := show is_max_filter (λ x, min (f x) (g x)) l a, from hf.bicomp_mono (λ x x' hx y y' hy, min_le_min hx hy) hg lemma is_min_on.min (hf : is_min_on f s a) (hg : is_min_on g s a) : is_min_on (λ x, min (f x) (g x)) s a := hf.min hg lemma is_max_on.min (hf : is_max_on f s a) (hg : is_max_on g s a) : is_max_on (λ x, min (f x) (g x)) s a := hf.min hg lemma is_min_filter.max (hf : is_min_filter f l a) (hg : is_min_filter g l a) : is_min_filter (λ x, max (f x) (g x)) l a := show is_min_filter (λ x, max (f x) (g x)) l a, from hf.bicomp_mono (λ x x' hx y y' hy, max_le_max hx hy) hg lemma is_max_filter.max (hf : is_max_filter f l a) (hg : is_max_filter g l a) : is_max_filter (λ x, max (f x) (g x)) l a := show is_max_filter (λ x, max (f x) (g x)) l a, from hf.bicomp_mono (λ x x' hx y y' hy, max_le_max hx hy) hg lemma is_min_on.max (hf : is_min_on f s a) (hg : is_min_on g s a) : is_min_on (λ x, max (f x) (g x)) s a := hf.max hg lemma is_max_on.max (hf : is_max_on f s a) (hg : is_max_on g s a) : is_max_on (λ x, max (f x) (g x)) s a := hf.max hg end decidable_linear_order section eventually /-! ### Relation with `eventually` comparisons of two functions -/ lemma filter.eventually_le.is_max_filter {α β : Type*} [preorder β] {f g : α → β} {a : α} {l : filter α} (hle : g ≤ᶠ[l] f) (hfga : f a = g a) (h : is_max_filter f l a) : is_max_filter g l a := begin refine hle.mp (h.mono $ λ x hf hgf, _), rw ← hfga, exact le_trans hgf hf end lemma is_max_filter.congr {α β : Type*} [preorder β] {f g : α → β} {a : α} {l : filter α} (h : is_max_filter f l a) (heq : f =ᶠ[l] g) (hfga : f a = g a) : is_max_filter g l a := heq.symm.le.is_max_filter hfga h lemma filter.eventually_eq.is_max_filter_iff {α β : Type*} [preorder β] {f g : α → β} {a : α} {l : filter α} (heq : f =ᶠ[l] g) (hfga : f a = g a) : is_max_filter f l a ↔ is_max_filter g l a := ⟨λ h, h.congr heq hfga, λ h, h.congr heq.symm hfga.symm⟩ lemma filter.eventually_le.is_min_filter {α β : Type*} [preorder β] {f g : α → β} {a : α} {l : filter α} (hle : f ≤ᶠ[l] g) (hfga : f a = g a) (h : is_min_filter f l a) : is_min_filter g l a := @filter.eventually_le.is_max_filter _ (order_dual β) _ _ _ _ _ hle hfga h lemma is_min_filter.congr {α β : Type*} [preorder β] {f g : α → β} {a : α} {l : filter α} (h : is_min_filter f l a) (heq : f =ᶠ[l] g) (hfga : f a = g a) : is_min_filter g l a := heq.le.is_min_filter hfga h lemma filter.eventually_eq.is_min_filter_iff {α β : Type*} [preorder β] {f g : α → β} {a : α} {l : filter α} (heq : f =ᶠ[l] g) (hfga : f a = g a) : is_min_filter f l a ↔ is_min_filter g l a := ⟨λ h, h.congr heq hfga, λ h, h.congr heq.symm hfga.symm⟩ lemma is_extr_filter.congr {α β : Type*} [preorder β] {f g : α → β} {a : α} {l : filter α} (h : is_extr_filter f l a) (heq : f =ᶠ[l] g) (hfga : f a = g a) : is_extr_filter g l a := begin rw is_extr_filter at *, rwa [← heq.is_max_filter_iff hfga, ← heq.is_min_filter_iff hfga], end lemma filter.eventually_eq.is_extr_filter_iff {α β : Type*} [preorder β] {f g : α → β} {a : α} {l : filter α} (heq : f =ᶠ[l] g) (hfga : f a = g a) : is_extr_filter f l a ↔ is_extr_filter g l a := ⟨λ h, h.congr heq hfga, λ h, h.congr heq.symm hfga.symm⟩ end eventually
06a10d61efd84e3fdce1d2d9984b19da45f3fb4e
c777c32c8e484e195053731103c5e52af26a25d1
/src/ring_theory/discrete_valuation_ring/basic.lean
5c2df165d347ad0a811cfee8299f4fbbbf09fbea
[ "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
17,484
lean
/- Copyright (c) 2020 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard -/ import ring_theory.principal_ideal_domain import ring_theory.ideal.local_ring import ring_theory.multiplicity import ring_theory.valuation.basic import linear_algebra.adic_completion /-! # Discrete valuation rings This file defines discrete valuation rings (DVRs) and develops a basic interface for them. ## Important definitions There are various definitions of a DVR in the literature; we define a DVR to be a local PID which is not a field (the first definition in Wikipedia) and prove that this is equivalent to being a PID with a unique non-zero prime ideal (the definition in Serre's book "Local Fields"). Let R be an integral domain, assumed to be a principal ideal ring and a local ring. * `discrete_valuation_ring R` : a predicate expressing that R is a DVR ### Definitions * `add_val R : add_valuation R part_enat` : the additive valuation on a DVR. ## Implementation notes It's a theorem that an element of a DVR is a uniformizer if and only if it's irreducible. We do not hence define `uniformizer` at all, because we can use `irreducible` instead. ## Tags discrete valuation ring -/ open_locale classical universe u open ideal local_ring /-- An integral domain is a *discrete valuation ring* (DVR) if it's a local PID which is not a field. -/ class discrete_valuation_ring (R : Type u) [comm_ring R] [is_domain R] extends is_principal_ideal_ring R, local_ring R : Prop := (not_a_field' : maximal_ideal R ≠ ⊥) namespace discrete_valuation_ring variables (R : Type u) [comm_ring R] [is_domain R] [discrete_valuation_ring R] lemma not_a_field : maximal_ideal R ≠ ⊥ := not_a_field' /-- A discrete valuation ring `R` is not a field. -/ lemma not_is_field : ¬ is_field R := local_ring.is_field_iff_maximal_ideal_eq.not.mpr (not_a_field R) variable {R} open principal_ideal_ring theorem irreducible_of_span_eq_maximal_ideal {R : Type*} [comm_ring R] [local_ring R] [is_domain R] (ϖ : R) (hϖ : ϖ ≠ 0) (h : maximal_ideal R = ideal.span {ϖ}) : irreducible ϖ := begin have h2 : ¬(is_unit ϖ) := show ϖ ∈ maximal_ideal R, from h.symm ▸ submodule.mem_span_singleton_self ϖ, refine ⟨h2, _⟩, intros a b hab, by_contra' h, obtain ⟨ha : a ∈ maximal_ideal R, hb : b ∈ maximal_ideal R⟩ := h, rw [h, mem_span_singleton'] at ha hb, rcases ha with ⟨a, rfl⟩, rcases hb with ⟨b, rfl⟩, rw (show a * ϖ * (b * ϖ) = ϖ * (ϖ * (a * b)), by ring) at hab, apply hϖ, apply eq_zero_of_mul_eq_self_right _ hab.symm, exact λ hh, h2 (is_unit_of_dvd_one ϖ ⟨_, hh.symm⟩) end /-- An element of a DVR is irreducible iff it is a uniformizer, that is, generates the maximal ideal of R -/ theorem irreducible_iff_uniformizer (ϖ : R) : irreducible ϖ ↔ maximal_ideal R = ideal.span {ϖ} := ⟨λ hϖ, (eq_maximal_ideal (is_maximal_of_irreducible hϖ)).symm, λ h, irreducible_of_span_eq_maximal_ideal ϖ (λ e, not_a_field R $ by rwa [h, span_singleton_eq_bot]) h⟩ lemma _root_.irreducible.maximal_ideal_eq {ϖ : R} (h : irreducible ϖ) : maximal_ideal R = ideal.span {ϖ} := (irreducible_iff_uniformizer _).mp h variable (R) /-- Uniformisers exist in a DVR -/ theorem exists_irreducible : ∃ ϖ : R, irreducible ϖ := by {simp_rw [irreducible_iff_uniformizer], exact (is_principal_ideal_ring.principal $ maximal_ideal R).principal} /-- Uniformisers exist in a DVR -/ theorem exists_prime : ∃ ϖ : R, prime ϖ := (exists_irreducible R).imp (λ _, principal_ideal_ring.irreducible_iff_prime.1) /-- an integral domain is a DVR iff it's a PID with a unique non-zero prime ideal -/ theorem iff_pid_with_one_nonzero_prime (R : Type u) [comm_ring R] [is_domain R] : discrete_valuation_ring R ↔ is_principal_ideal_ring R ∧ ∃! P : ideal R, P ≠ ⊥ ∧ is_prime P := begin split, { intro RDVR, rcases id RDVR with ⟨Rlocal⟩, split, assumption, resetI, use local_ring.maximal_ideal R, split, split, { assumption }, { apply_instance } , { rintro Q ⟨hQ1, hQ2⟩, obtain ⟨q, rfl⟩ := (is_principal_ideal_ring.principal Q).1, have hq : q ≠ 0, { rintro rfl, apply hQ1, simp }, erw span_singleton_prime hq at hQ2, replace hQ2 := hQ2.irreducible, rw irreducible_iff_uniformizer at hQ2, exact hQ2.symm } }, { rintro ⟨RPID, Punique⟩, haveI : local_ring R := local_ring.of_unique_nonzero_prime Punique, refine {not_a_field' := _}, rcases Punique with ⟨P, ⟨hP1, hP2⟩, hP3⟩, have hPM : P ≤ maximal_ideal R := le_maximal_ideal (hP2.1), intro h, rw [h, le_bot_iff] at hPM, exact hP1 hPM } end lemma associated_of_irreducible {a b : R} (ha : irreducible a) (hb : irreducible b) : associated a b := begin rw irreducible_iff_uniformizer at ha hb, rw [←span_singleton_eq_span_singleton, ←ha, hb], end end discrete_valuation_ring namespace discrete_valuation_ring variable (R : Type*) /-- Alternative characterisation of discrete valuation rings. -/ def has_unit_mul_pow_irreducible_factorization [comm_ring R] : Prop := ∃ p : R, irreducible p ∧ ∀ {x : R}, x ≠ 0 → ∃ (n : ℕ), associated (p ^ n) x namespace has_unit_mul_pow_irreducible_factorization variables {R} [comm_ring R] (hR : has_unit_mul_pow_irreducible_factorization R) include hR lemma unique_irreducible ⦃p q : R⦄ (hp : irreducible p) (hq : irreducible q) : associated p q := begin rcases hR with ⟨ϖ, hϖ, hR⟩, suffices : ∀ {p : R} (hp : irreducible p), associated p ϖ, { apply associated.trans (this hp) (this hq).symm, }, clear hp hq p q, intros p hp, obtain ⟨n, hn⟩ := hR hp.ne_zero, have : irreducible (ϖ ^ n) := hn.symm.irreducible hp, rcases lt_trichotomy n 1 with (H|rfl|H), { obtain rfl : n = 0, { clear hn this, revert H n, exact dec_trivial }, simpa only [not_irreducible_one, pow_zero] using this, }, { simpa only [pow_one] using hn.symm, }, { obtain ⟨n, rfl⟩ : ∃ k, n = 1 + k + 1 := nat.exists_eq_add_of_lt H, rw pow_succ at this, rcases this.is_unit_or_is_unit rfl with H0|H0, { exact (hϖ.not_unit H0).elim, }, { rw [add_comm, pow_succ] at H0, exact (hϖ.not_unit (is_unit_of_mul_is_unit_left H0)).elim } } end variables [is_domain R] /-- An integral domain in which there is an irreducible element `p` such that every nonzero element is associated to a power of `p` is a unique factorization domain. See `discrete_valuation_ring.of_has_unit_mul_pow_irreducible_factorization`. -/ theorem to_unique_factorization_monoid : unique_factorization_monoid R := let p := classical.some hR in let spec := classical.some_spec hR in unique_factorization_monoid.of_exists_prime_factors $ λ x hx, begin use multiset.replicate (classical.some (spec.2 hx)) p, split, { intros q hq, have hpq := multiset.eq_of_mem_replicate hq, rw hpq, refine ⟨spec.1.ne_zero, spec.1.not_unit, _⟩, intros a b h, by_cases ha : a = 0, { rw ha, simp only [true_or, dvd_zero], }, obtain ⟨m, u, rfl⟩ := spec.2 ha, rw [mul_assoc, mul_left_comm, is_unit.dvd_mul_left _ _ _ (units.is_unit _)] at h, rw is_unit.dvd_mul_right (units.is_unit _), by_cases hm : m = 0, { simp only [hm, one_mul, pow_zero] at h ⊢, right, exact h }, left, obtain ⟨m, rfl⟩ := nat.exists_eq_succ_of_ne_zero hm, rw pow_succ, apply dvd_mul_of_dvd_left dvd_rfl _ }, { rw [multiset.prod_replicate], exact (classical.some_spec (spec.2 hx)), } end omit hR lemma of_ufd_of_unique_irreducible [unique_factorization_monoid R] (h₁ : ∃ p : R, irreducible p) (h₂ : ∀ ⦃p q : R⦄, irreducible p → irreducible q → associated p q) : has_unit_mul_pow_irreducible_factorization R := begin obtain ⟨p, hp⟩ := h₁, refine ⟨p, hp, _⟩, intros x hx, cases wf_dvd_monoid.exists_factors x hx with fx hfx, refine ⟨fx.card, _⟩, have H := hfx.2, rw ← associates.mk_eq_mk_iff_associated at H ⊢, rw [← H, ← associates.prod_mk, associates.mk_pow, ← multiset.prod_replicate], congr' 1, symmetry, rw multiset.eq_replicate, simp only [true_and, and_imp, multiset.card_map, eq_self_iff_true, multiset.mem_map, exists_imp_distrib], rintros _ q hq rfl, rw associates.mk_eq_mk_iff_associated, apply h₂ (hfx.1 _ hq) hp, end end has_unit_mul_pow_irreducible_factorization lemma aux_pid_of_ufd_of_unique_irreducible (R : Type u) [comm_ring R] [is_domain R] [unique_factorization_monoid R] (h₁ : ∃ p : R, irreducible p) (h₂ : ∀ ⦃p q : R⦄, irreducible p → irreducible q → associated p q) : is_principal_ideal_ring R := begin constructor, intro I, by_cases I0 : I = ⊥, { rw I0, use 0, simp only [set.singleton_zero, submodule.span_zero], }, obtain ⟨x, hxI, hx0⟩ : ∃ x ∈ I, x ≠ (0:R) := I.ne_bot_iff.mp I0, obtain ⟨p, hp, H⟩ := has_unit_mul_pow_irreducible_factorization.of_ufd_of_unique_irreducible h₁ h₂, have ex : ∃ n : ℕ, p ^ n ∈ I, { obtain ⟨n, u, rfl⟩ := H hx0, refine ⟨n, _⟩, simpa only [units.mul_inv_cancel_right] using I.mul_mem_right ↑u⁻¹ hxI, }, constructor, use p ^ (nat.find ex), show I = ideal.span _, apply le_antisymm, { intros r hr, by_cases hr0 : r = 0, { simp only [hr0, submodule.zero_mem], }, obtain ⟨n, u, rfl⟩ := H hr0, simp only [mem_span_singleton, units.is_unit, is_unit.dvd_mul_right], apply pow_dvd_pow, apply nat.find_min', simpa only [units.mul_inv_cancel_right] using I.mul_mem_right ↑u⁻¹ hr, }, { erw submodule.span_singleton_le_iff_mem, exact nat.find_spec ex, }, end /-- A unique factorization domain with at least one irreducible element in which all irreducible elements are associated is a discrete valuation ring. -/ lemma of_ufd_of_unique_irreducible {R : Type u} [comm_ring R] [is_domain R] [unique_factorization_monoid R] (h₁ : ∃ p : R, irreducible p) (h₂ : ∀ ⦃p q : R⦄, irreducible p → irreducible q → associated p q) : discrete_valuation_ring R := begin rw iff_pid_with_one_nonzero_prime, haveI PID : is_principal_ideal_ring R := aux_pid_of_ufd_of_unique_irreducible R h₁ h₂, obtain ⟨p, hp⟩ := h₁, refine ⟨PID, ⟨ideal.span {p}, ⟨_, _⟩, _⟩⟩, { rw submodule.ne_bot_iff, refine ⟨p, ideal.mem_span_singleton.mpr (dvd_refl p), hp.ne_zero⟩, }, { rwa [ideal.span_singleton_prime hp.ne_zero, ← unique_factorization_monoid.irreducible_iff_prime], }, { intro I, rw ← submodule.is_principal.span_singleton_generator I, rintro ⟨I0, hI⟩, apply span_singleton_eq_span_singleton.mpr, apply h₂ _ hp, erw [ne.def, span_singleton_eq_bot] at I0, rwa [unique_factorization_monoid.irreducible_iff_prime, ← ideal.span_singleton_prime I0], apply_instance, }, end /-- An integral domain in which there is an irreducible element `p` such that every nonzero element is associated to a power of `p` is a discrete valuation ring. -/ lemma of_has_unit_mul_pow_irreducible_factorization {R : Type u} [comm_ring R] [is_domain R] (hR : has_unit_mul_pow_irreducible_factorization R) : discrete_valuation_ring R := begin letI : unique_factorization_monoid R := hR.to_unique_factorization_monoid, apply of_ufd_of_unique_irreducible _ hR.unique_irreducible, unfreezingI { obtain ⟨p, hp, H⟩ := hR, exact ⟨p, hp⟩, }, end section variables [comm_ring R] [is_domain R] [discrete_valuation_ring R] variable {R} lemma associated_pow_irreducible {x : R} (hx : x ≠ 0) {ϖ : R} (hirr : irreducible ϖ) : ∃ (n : ℕ), associated x (ϖ ^ n) := begin have : wf_dvd_monoid R := is_noetherian_ring.wf_dvd_monoid, cases wf_dvd_monoid.exists_factors x hx with fx hfx, unfreezingI { use fx.card }, have H := hfx.2, rw ← associates.mk_eq_mk_iff_associated at H ⊢, rw [← H, ← associates.prod_mk, associates.mk_pow, ← multiset.prod_replicate], congr' 1, rw multiset.eq_replicate, simp only [true_and, and_imp, multiset.card_map, eq_self_iff_true, multiset.mem_map, exists_imp_distrib], rintros _ _ _ rfl, rw associates.mk_eq_mk_iff_associated, refine associated_of_irreducible _ _ hirr, apply hfx.1, assumption end lemma eq_unit_mul_pow_irreducible {x : R} (hx : x ≠ 0) {ϖ : R} (hirr : irreducible ϖ) : ∃ (n : ℕ) (u : Rˣ), x = u * ϖ ^ n := begin obtain ⟨n, hn⟩ := associated_pow_irreducible hx hirr, obtain ⟨u, rfl⟩ := hn.symm, use [n, u], apply mul_comm, end open submodule.is_principal lemma ideal_eq_span_pow_irreducible {s : ideal R} (hs : s ≠ ⊥) {ϖ : R} (hirr : irreducible ϖ) : ∃ n : ℕ, s = ideal.span {ϖ ^ n} := begin have gen_ne_zero : generator s ≠ 0, { rw [ne.def, ← eq_bot_iff_generator_eq_zero], assumption }, rcases associated_pow_irreducible gen_ne_zero hirr with ⟨n, u, hnu⟩, use n, have : span _ = _ := span_singleton_generator s, rw [← this, ← hnu, span_singleton_eq_span_singleton], use u end lemma unit_mul_pow_congr_pow {p q : R} (hp : irreducible p) (hq : irreducible q) (u v : Rˣ) (m n : ℕ) (h : ↑u * p ^ m = v * q ^ n) : m = n := begin have key : associated (multiset.replicate m p).prod (multiset.replicate n q).prod, { rw [multiset.prod_replicate, multiset.prod_replicate, associated], refine ⟨u * v⁻¹, _⟩, simp only [units.coe_mul], rw [mul_left_comm, ← mul_assoc, h, mul_right_comm, units.mul_inv, one_mul], }, have := multiset.card_eq_card_of_rel (unique_factorization_monoid.factors_unique _ _ key), { simpa only [multiset.card_replicate] }, all_goals { intros x hx, unfreezingI { obtain rfl := multiset.eq_of_mem_replicate hx, assumption } }, end lemma unit_mul_pow_congr_unit {ϖ : R} (hirr : irreducible ϖ) (u v : Rˣ) (m n : ℕ) (h : ↑u * ϖ ^ m = v * ϖ ^ n) : u = v := begin obtain rfl : m = n := unit_mul_pow_congr_pow hirr hirr u v m n h, rw ← sub_eq_zero at h, rw [← sub_mul, mul_eq_zero] at h, cases h, { rw sub_eq_zero at h, exact_mod_cast h }, { apply (hirr.ne_zero (pow_eq_zero h)).elim, } end /-! ## The additive valuation on a DVR -/ open multiplicity /-- The `part_enat`-valued additive valuation on a DVR -/ noncomputable def add_val (R : Type u) [comm_ring R] [is_domain R] [discrete_valuation_ring R] : add_valuation R part_enat := add_valuation (classical.some_spec (exists_prime R)) lemma add_val_def (r : R) (u : Rˣ) {ϖ : R} (hϖ : irreducible ϖ) (n : ℕ) (hr : r = u * ϖ ^ n) : add_val R r = n := by rw [add_val, add_valuation_apply, hr, eq_of_associated_left (associated_of_irreducible R hϖ (classical.some_spec (exists_prime R)).irreducible), eq_of_associated_right (associated.symm ⟨u, mul_comm _ _⟩), multiplicity_pow_self_of_prime (principal_ideal_ring.irreducible_iff_prime.1 hϖ)] lemma add_val_def' (u : Rˣ) {ϖ : R} (hϖ : irreducible ϖ) (n : ℕ) : add_val R ((u : R) * ϖ ^ n) = n := add_val_def _ u hϖ n rfl @[simp] lemma add_val_zero : add_val R 0 = ⊤ := (add_val R).map_zero @[simp] lemma add_val_one : add_val R 1 = 0 := (add_val R).map_one @[simp] lemma add_val_uniformizer {ϖ : R} (hϖ : irreducible ϖ) : add_val R ϖ = 1 := by simpa only [one_mul, eq_self_iff_true, units.coe_one, pow_one, forall_true_left, nat.cast_one] using add_val_def ϖ 1 hϖ 1 @[simp] lemma add_val_mul {a b : R} : add_val R (a * b) = add_val R a + add_val R b := (add_val R).map_mul _ _ lemma add_val_pow (a : R) (n : ℕ) : add_val R (a ^ n) = n • add_val R a := (add_val R).map_pow _ _ lemma _root_.irreducible.add_val_pow {ϖ : R} (h : irreducible ϖ) (n : ℕ) : add_val R (ϖ ^ n) = n := by rw [add_val_pow, add_val_uniformizer h, nsmul_one] lemma add_val_eq_top_iff {a : R} : add_val R a = ⊤ ↔ a = 0 := begin have hi := (classical.some_spec (exists_prime R)).irreducible, split, { contrapose, intro h, obtain ⟨n, ha⟩ := associated_pow_irreducible h hi, obtain ⟨u, rfl⟩ := ha.symm, rw [mul_comm, add_val_def' u hi n], exact part_enat.coe_ne_top _ }, { rintro rfl, exact add_val_zero } end lemma add_val_le_iff_dvd {a b : R} : add_val R a ≤ add_val R b ↔ a ∣ b := begin have hp := classical.some_spec (exists_prime R), split; intro h, { by_cases ha0 : a = 0, { rw [ha0, add_val_zero, top_le_iff, add_val_eq_top_iff] at h, rw h, apply dvd_zero }, obtain ⟨n, ha⟩ := associated_pow_irreducible ha0 hp.irreducible, rw [add_val, add_valuation_apply, add_valuation_apply, multiplicity_le_multiplicity_iff] at h, exact ha.dvd.trans (h n ha.symm.dvd), }, { rw [add_val, add_valuation_apply, add_valuation_apply], exact multiplicity_le_multiplicity_of_dvd_right h } end lemma add_val_add {a b : R} : min (add_val R a) (add_val R b) ≤ add_val R (a + b) := (add_val R).map_add _ _ end instance (R : Type*) [comm_ring R] [is_domain R] [discrete_valuation_ring R] : is_Hausdorff (maximal_ideal R) R := { haus' := λ x hx, begin obtain ⟨ϖ, hϖ⟩ := exists_irreducible R, simp only [← ideal.one_eq_top, smul_eq_mul, mul_one, smodeq.zero, hϖ.maximal_ideal_eq, ideal.span_singleton_pow, ideal.mem_span_singleton, ← add_val_le_iff_dvd, hϖ.add_val_pow] at hx, rwa [← add_val_eq_top_iff, part_enat.eq_top_iff_forall_le], end } end discrete_valuation_ring
5d55214a59eae3b32ecd98ae90f615562a79f6ae
64874bd1010548c7f5a6e3e8902efa63baaff785
/tests/lean/hott/sig_noc.hlean
63735732c1495478788ae3f183cf8e4db5101c58
[ "Apache-2.0" ]
permissive
tjiaqi/lean
4634d729795c164664d10d093f3545287c76628f
d0ce4cf62f4246b0600c07e074d86e51f2195e30
refs/heads/master
1,622,323,796,480
1,422,643,069,000
1,422,643,069,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,129
hlean
namespace sigma open lift open sigma.ops sigma variables {A : Type} {B : A → Type} variables {a₁ a₂ : A} {b₁ : B a₁} {b₂ : B a₂} definition dpair.inj (H : ⟨a₁, b₁⟩ = ⟨a₂, b₂⟩) : Σ (e₁ : a₁ = a₂), eq.rec b₁ e₁ = b₂ := down (no_confusion H (λ e₁ e₂, ⟨e₁, e₂⟩)) definition dpair.inj₁ (H : ⟨a₁, b₁⟩ = ⟨a₂, b₂⟩) : a₁ = a₂ := (dpair.inj H).1 definition dpair.inj₂ (H : ⟨a₁, b₁⟩ = ⟨a₂, b₂⟩) : eq.rec b₁ (dpair.inj₁ H) = b₂ := (dpair.inj H).2 end sigma structure foo := mk :: (A : Type) (B : A → Type) (a : A) (b : B a) set_option pp.implicit true namespace foo open lift sigma sigma.ops universe variables l₁ l₂ variables {A₁ : Type.{l₁}} {B₁ : A₁ → Type.{l₂}} {a₁ : A₁} {b₁ : B₁ a₁} variables {A₂ : Type.{l₁}} {B₂ : A₂ → Type.{l₂}} {a₂ : A₂} {b₂ : B₂ a₂} definition foo.inj (H : mk A₁ B₁ a₁ b₁ = mk A₂ B₂ a₂ b₂) : Σ (e₁ : A₁ = A₂) (e₂ : eq.rec B₁ e₁ = B₂) (e₃ : eq.rec a₁ e₁ = a₂), eq.rec (eq.rec (eq.rec b₁ e₁) e₂) e₃ = b₂ := down (no_confusion H (λ e₁ e₂ e₃ e₄, ⟨e₁, e₂, e₃, e₄⟩)) definition foo.inj₁ (H : mk A₁ B₁ a₁ b₁ = mk A₂ B₂ a₂ b₂) : A₁ = A₂ := (foo.inj H).1 definition foo.inj₂ (H : mk A₁ B₁ a₁ b₁ = mk A₂ B₂ a₂ b₂) : eq.rec B₁ (foo.inj₁ H) = B₂ := (foo.inj H).2.1 definition foo.inj₃ (H : mk A₁ B₁ a₁ b₁ = mk A₂ B₂ a₂ b₂) : eq.rec a₁ (foo.inj₁ H) = a₂ := (foo.inj H).2.2.1 definition foo.inj₄ (H : mk A₁ B₁ a₁ b₁ = mk A₂ B₂ a₂ b₂) : eq.rec (eq.rec (eq.rec b₁ (foo.inj₁ H)) (foo.inj₂ H)) (foo.inj₃ H) = b₂ := (foo.inj H).2.2.2 definition foo.inj_inv (e₁ : A₁ = A₂) (e₂ : eq.rec B₁ e₁ = B₂) (e₃ : eq.rec a₁ e₁ = a₂) (e₄ : eq.rec (eq.rec (eq.rec b₁ e₁) e₂) e₃ = b₂) : mk A₁ B₁ a₁ b₁ = mk A₂ B₂ a₂ b₂ := eq.rec_on e₄ (eq.rec_on e₃ (eq.rec_on e₂ (eq.rec_on e₁ rfl))) end foo
d095e47bd564674e23e1fbf963065647d20928ab
271e26e338b0c14544a889c31c30b39c989f2e0f
/stage0/src/Init/Lean/Elab/TermBinders.lean
e4e543c9325758275eda4ba15f9211989aab7083
[ "Apache-2.0" ]
permissive
dgorokho/lean4
805f99b0b60c545b64ac34ab8237a8504f89d7d4
e949a052bad59b1c7b54a82d24d516a656487d8a
refs/heads/master
1,607,061,363,851
1,578,006,086,000
1,578,006,086,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
12,324
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 -/ prelude import Init.Lean.Elab.Term namespace Lean namespace Elab namespace Term /-- Given syntax of the forms a) (`:` term)? b) `:` term return `term` if it is present, or a hole if not. -/ private def expandBinderType (stx : Syntax) : Syntax := if stx.getNumArgs == 0 then mkHole stx else stx.getArg 1 /-- Given syntax of the form `ident <|> hole`, return `ident`. If `hole`, then we create a new anonymous name. -/ private def expandBinderIdent (stx : Syntax) : TermElabM Syntax := match_syntax stx with | `(_) => mkFreshAnonymousIdent stx | _ => pure stx /-- Given syntax of the form `(ident >> " : ")?`, return `ident`, or a new instance name. -/ private def expandOptIdent (stx : Syntax) : TermElabM Syntax := if stx.getNumArgs == 0 then do id ← mkFreshInstanceName; pure $ mkIdentFrom stx id else pure $ stx.getArg 0 structure BinderView := (id : Syntax) (type : Syntax) (bi : BinderInfo) private def matchBinder (stx : Syntax) : TermElabM (Array BinderView) := withNode stx $ fun node => do let k := node.getKind; if k == `Lean.Parser.Term.simpleBinder then -- binderIdent+ let ids := (node.getArg 0).getArgs; let type := mkHole stx; ids.mapM $ fun id => do id ← expandBinderIdent id; pure { id := id, type := type, bi := BinderInfo.default } else if k == `Lean.Parser.Term.explicitBinder then -- `(` binderIdent+ binderType (binderDefault <|> binderTactic)? `)` let ids := (node.getArg 1).getArgs; let type := expandBinderType (node.getArg 2); -- TODO handle `binderDefault` and `binderTactic` ids.mapM $ fun id => do id ← expandBinderIdent id; pure { id := id, type := type, bi := BinderInfo.default } else if k == `Lean.Parser.Term.implicitBinder then -- `{` binderIdent+ binderType `}` let ids := (node.getArg 1).getArgs; let type := expandBinderType (node.getArg 2); ids.mapM $ fun id => do id ← expandBinderIdent id; pure { id := id, type := type, bi := BinderInfo.implicit } else if k == `Lean.Parser.Term.instBinder then do -- `[` optIdent type `]` id ← expandOptIdent (node.getArg 1); let type := node.getArg 2; pure #[ { id := id, type := type, bi := BinderInfo.instImplicit } ] else throwError stx "term elaborator failed, unexpected binder syntax" def mkFreshFVarId : TermElabM Name := do s ← get; let id := s.ngen.curr; modify $ fun s => { ngen := s.ngen.next, .. s }; pure id private partial def elabBinderViews (binderViews : Array BinderView) : Nat → Array Expr → LocalContext → LocalInstances → TermElabM (Array Expr × LocalContext × LocalInstances) | i, fvars, lctx, localInsts => if h : i < binderViews.size then let binderView := binderViews.get ⟨i, h⟩; withLCtx lctx localInsts $ do type ← elabType binderView.type; fvarId ← mkFreshFVarId; let fvar := mkFVar fvarId; let fvars := fvars.push fvar; -- dbgTrace (toString binderView.id.getId ++ " : " ++ toString type); let lctx := lctx.mkLocalDecl fvarId binderView.id.getId type binderView.bi; className? ← isClass binderView.type type; match className? with | none => elabBinderViews (i+1) fvars lctx localInsts | some className => do resetSynthInstanceCache; let localInsts := localInsts.push { className := className, fvar := mkFVar fvarId }; elabBinderViews (i+1) fvars lctx localInsts else pure (fvars, lctx, localInsts) private partial def elabBindersAux (binders : Array Syntax) : Nat → Array Expr → LocalContext → LocalInstances → TermElabM (Array Expr × LocalContext × LocalInstances) | i, fvars, lctx, localInsts => if h : i < binders.size then do binderViews ← matchBinder (binders.get ⟨i, h⟩); (fvars, lctx, localInsts) ← elabBinderViews binderViews 0 fvars lctx localInsts; elabBindersAux (i+1) fvars lctx localInsts else pure (fvars, lctx, localInsts) /-- Elaborate the given binders (i.e., `Syntax` objects for `simpleBinder <|> bracktedBinder`), update the local context, set of local instances, reset instance chache (if needed), and then execute `x` with the updated context. -/ def elabBinders {α} (binders : Array Syntax) (x : Array Expr → TermElabM α) : TermElabM α := if binders.isEmpty then x #[] else do lctx ← getLCtx; localInsts ← getLocalInsts; (fvars, lctx, newLocalInsts) ← elabBindersAux binders 0 #[] lctx localInsts; resettingSynthInstanceCacheWhen (newLocalInsts.size > localInsts.size) $ withLCtx lctx newLocalInsts $ x fvars @[inline] def elabBinder {α} (binder : Syntax) (x : Expr → TermElabM α) : TermElabM α := elabBinders #[binder] (fun fvars => x (fvars.get! 1)) @[builtinTermElab «forall»] def elabForall : TermElab := fun stx _ => match_syntax stx.val with | `(forall $binders*, $term) => elabBinders binders $ fun xs => do e ← elabType term; mkForall stx.val xs e | _ => throwUnexpectedSyntax stx.val "forall" @[builtinTermElab arrow] def elabArrow : TermElab := adaptExpander $ fun stx => match_syntax stx with | `($dom:term -> $rng) => `(forall (a : $dom), $rng) | _ => throwUnexpectedSyntax stx "->" @[builtinTermElab depArrow] def elabDepArrow : TermElab := fun stx _ => -- bracktedBinder `->` term let binder := stx.getArg 0; let term := stx.getArg 2; elabBinders #[binder] $ fun xs => do e ← elabType term; mkForall stx.val xs e /-- Main loop `getFunBinderIds?` -/ private partial def getFunBinderIdsAux? : Bool → Syntax → Array Syntax → TermElabM (Option (Array Syntax)) | idOnly, stx, acc => match_syntax stx with | `($f $a) => if idOnly then pure none else do (some acc) ← getFunBinderIdsAux? false f acc | pure none; getFunBinderIdsAux? true a acc | `(_) => do ident ← mkFreshAnonymousIdent stx; pure (some (acc.push ident)) | stx => match stx.isSimpleTermId? with | some id => pure (some (acc.push id)) | _ => pure none /-- Auxiliary functions for converting `Term.app ... (Term.app id_1 id_2) ... id_n` into `#[id_1, ..., id_m]` It is used at `expandFunBinders`. -/ private def getFunBinderIds? (stx : Syntax) : TermElabM (Option (Array Syntax)) := getFunBinderIdsAux? false stx #[] /-- Main loop for `expandFunBinders`. -/ private partial def expandFunBindersAux (binders : Array Syntax) : Syntax → Nat → Array Syntax → TermElabM (Array Syntax × Syntax) | body, i, newBinders => if h : i < binders.size then let binder := binders.get ⟨i, h⟩; let processAsPattern : Unit → TermElabM (Array Syntax × Syntax) := fun _ => do { let pattern := binder; ident ← mkFreshAnonymousIdent binder; (binders, newBody) ← expandFunBindersAux body (i+1) (newBinders.push $ mkExplicitBinder ident (mkHole binder)); let major := mkTermIdFromIdent ident; newBody ← `(match $major with | $pattern => $newBody); pure (binders, newBody) }; match binder with | Syntax.node `Lean.Parser.Term.hole _ => do ident ← mkFreshAnonymousIdent binder; let type := binder; expandFunBindersAux body (i+1) (newBinders.push $ mkExplicitBinder ident type) | Syntax.node `Lean.Parser.Term.paren args => -- `(` (termParser >> parenSpecial)? `)` -- parenSpecial := (tupleTail <|> typeAscription)? let binderBody := binder.getArg 1; if binderBody.isNone then processAsPattern () else let idents := binderBody.getArg 0; let special := binderBody.getArg 1; if special.isNone then processAsPattern () else if (special.getArg 0).getKind != `Lean.Parser.Term.typeAscription then processAsPattern () else do -- typeAscription := `:` term let type := ((special.getArg 0).getArg 1); idents? ← getFunBinderIds? idents; match idents? with | some idents => expandFunBindersAux body (i+1) (newBinders ++ idents.map (fun ident => mkExplicitBinder ident type)) | none => processAsPattern () | binder => match binder.isTermId? with | some (ident, extra) => do unless extra.isNone $ throwError binder "invalid binder, simple identifier expected"; let type := mkHole binder; expandFunBindersAux body (i+1) (newBinders.push $ mkExplicitBinder ident type) | none => processAsPattern () else pure (newBinders, body) /-- Auxiliary function for expanding `fun` notation binders. Recall that `fun` parser is defined as ``` parser! unicodeSymbol "λ" "fun" >> many1 (termParser appPrec) >> unicodeSymbol "⇒" "=>" >> termParser ``` to allow notation such as `fun (a, b) => a + b`, where `(a, b)` should be treated as a pattern. The result is a pair `(explicitBinders, newBody)`, where `explicitBinders` is syntax of the form ``` `(` ident `:` term `)` ``` which can be elaborated using `elabBinders`, and `newBody` is the updated `body` syntax. We update the `body` syntax when expanding the pattern notation. Example: `fun (a, b) => a + b` expands into `fun _a_1 => match _a_1 with | (a, b) => a + b`. See local function `processAsPattern` at `expandFunBindersAux`. -/ private def expandFunBinders (binders : Array Syntax) (body : Syntax) : TermElabM (Array Syntax × Syntax) := expandFunBindersAux binders body 0 #[] @[builtinTermElab «fun»] def elabFun : TermElab := fun stx expectedType? => do -- `fun` term+ `=>` term let binders := (stx.getArg 1).getArgs; let body := stx.getArg 3; (binders, body) ← expandFunBinders binders body; elabBinders binders $ fun xs => do -- TODO: expected type e ← elabTerm body none; mkLambda stx.val xs e def withLetDecl {α} (ref : Syntax) (n : Name) (type : Expr) (val : Expr) (k : Expr → TermElabM α) : TermElabM α := do fvarId ← mkFreshFVarId; ctx ← read; let lctx := ctx.lctx.mkLetDecl fvarId n type val; let localInsts := ctx.localInstances; let fvar := mkFVar fvarId; c? ← isClass ref type; match c? with | some c => adaptReader (fun (ctx : Context) => { lctx := lctx, localInstances := localInsts.push { className := c, fvar := fvar }, .. ctx }) $ k fvar | none => adaptReader (fun (ctx : Context) => { lctx := lctx, .. ctx }) $ k fvar def expandOptType (ref : Syntax) (optType : Syntax) : Syntax := if optType.isNone then mkHole ref else optType.getArg 1 def elabLetIdDecl (ref : Syntax) (decl body : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do -- `decl` is of the form: ident bracktedBinder+ (`:` term)? `:=` term let n := decl.getIdAt 0; let binders := (decl.getArg 1).getArgs; let type := expandOptType ref (decl.getArg 2); let val := decl.getArg 4; (type, val) ← elabBinders binders $ fun xs => do { type ← elabType type; val ← elabTerm val type; type ← mkForall ref xs type; val ← mkLambda ref xs val; pure (type, val) }; trace `Elab.let.decl ref $ fun _ => n ++ " : " ++ type ++ " := " ++ val; withLetDecl ref n type val $ fun x => do body ← elabTerm body expectedType?; body ← instantiateMVars ref body; mkLet ref x body def elabLetEqnsDecl (ref : Syntax) (decl body : Syntax) (expectedType? : Option Expr) : TermElabM Expr := throwError decl "not implemented yet" def elabLetPatDecl (ref : Syntax) (decl body : Syntax) (expectedType? : Option Expr) : TermElabM Expr := throwError decl "not implemented yet" @[builtinTermElab «let»] def elabLet : TermElab := fun stx expectedType? => do -- `let` decl `;` body let ref := stx.val; let decl := stx.getArg 1; let body := stx.getArg 3; let declKind := decl.getKind; if declKind == `Lean.Parser.Term.letIdDecl then elabLetIdDecl ref decl body expectedType? else if declKind == `Lean.Parser.Term.letEqns then elabLetEqnsDecl ref decl body expectedType? else if declKind == `Lean.Parser.Term.letPatDecl then elabLetPatDecl ref decl body expectedType? else throwError ref "unknown let-declaration kind" @[init] private def regTraceClasses : IO Unit := do registerTraceClass `Elab.let; pure () end Term end Elab end Lean
5de25458a15d6fc2ff2f3a9787e45a0a986fa820
9dc8cecdf3c4634764a18254e94d43da07142918
/src/algebra/order/field.lean
b04e1c3153d83a26f0f735c605d0397ecaf0c8bf
[ "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
39,089
lean
/- Copyright (c) 2014 Robert Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Lewis, Leonardo de Moura, Mario Carneiro, Floris van Doorn -/ import algebra.order.field_defs import algebra.order.with_zero /-! # Linear ordered (semi)fields A linear ordered (semi)field is a (semi)field equipped with a linear order such that * addition respects the order: `a ≤ b → c + a ≤ c + b`; * multiplication of positives is positive: `0 < a → 0 < b → 0 < a * b`; * `0 < 1`. ## Main Definitions * `linear_ordered_semifield`: Typeclass for linear order semifields. * `linear_ordered_field`: Typeclass for linear ordered fields. -/ set_option old_structure_cmd true open function order_dual variables {α β : Type*} namespace function /-- Pullback a `linear_ordered_semifield` under an injective map. -/ @[reducible] -- See note [reducible non-instances] def injective.linear_ordered_semifield [linear_ordered_semifield α] [has_zero β] [has_one β] [has_add β] [has_mul β] [has_pow β ℕ] [has_smul ℕ β] [has_nat_cast β] [has_inv β] [has_div β] [has_pow β ℤ] [has_sup β] [has_inf β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f (x⁻¹) = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) (nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n) (zpow : ∀ x (n : ℤ), f (x ^ n) = f x ^ n) (nat_cast : ∀ n : ℕ, f n = n) (hsup : ∀ x y, f (x ⊔ y) = max (f x) (f y)) (hinf : ∀ x y, f (x ⊓ y) = min (f x) (f y)) : linear_ordered_semifield β := { ..hf.linear_ordered_semiring f zero one add mul nsmul npow nat_cast hsup hinf, ..hf.semifield f zero one add mul inv div nsmul npow zpow nat_cast } /-- Pullback a `linear_ordered_field` under an injective map. -/ @[reducible] -- See note [reducible non-instances] def injective.linear_ordered_field [linear_ordered_field α] [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β] [has_pow β ℕ] [has_smul ℕ β] [has_smul ℤ β] [has_smul ℚ β] [has_nat_cast β] [has_int_cast β] [has_rat_cast β] [has_inv β] [has_div β] [has_pow β ℤ] [has_sup β] [has_inf β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) (inv : ∀ x, f (x⁻¹) = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) (nsmul : ∀ x (n : ℕ), f (n • x) = n • f x) (zsmul : ∀ x (n : ℤ), f (n • x) = n • f x) (qsmul : ∀ x (n : ℚ), f (n • x) = n • f x) (npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n) (zpow : ∀ x (n : ℤ), f (x ^ n) = f x ^ n) (nat_cast : ∀ n : ℕ, f n = n) (int_cast : ∀ n : ℤ, f n = n) (rat_cast : ∀ n : ℚ, f n = n) (hsup : ∀ x y, f (x ⊔ y) = max (f x) (f y)) (hinf : ∀ x y, f (x ⊓ y) = min (f x) (f y)) : linear_ordered_field β := { .. hf.linear_ordered_ring f zero one add mul neg sub nsmul zsmul npow nat_cast int_cast hsup hinf, .. hf.field f zero one add mul neg sub inv div nsmul zsmul qsmul npow zpow nat_cast int_cast rat_cast } end function section linear_ordered_semifield variables [linear_ordered_semifield α] {a b c d e : α} {m n : ℤ} /-- `equiv.mul_left₀` as an order_iso. -/ @[simps {simp_rhs := tt}] def order_iso.mul_left₀ (a : α) (ha : 0 < a) : α ≃o α := { map_rel_iff' := λ _ _, mul_le_mul_left ha, ..equiv.mul_left₀ a ha.ne' } /-- `equiv.mul_right₀` as an order_iso. -/ @[simps {simp_rhs := tt}] def order_iso.mul_right₀ (a : α) (ha : 0 < a) : α ≃o α := { map_rel_iff' := λ _ _, mul_le_mul_right ha, ..equiv.mul_right₀ a ha.ne' } /-! ### Lemmas about pos, nonneg, nonpos, neg -/ @[simp] lemma inv_pos : 0 < a⁻¹ ↔ 0 < a := suffices ∀ a : α, 0 < a → 0 < a⁻¹, from ⟨λ h, inv_inv a ▸ this _ h, this a⟩, assume a ha, flip lt_of_mul_lt_mul_left ha.le $ by simp [ne_of_gt ha, zero_lt_one] alias inv_pos ↔ _ inv_pos_of_pos @[simp] lemma inv_nonneg : 0 ≤ a⁻¹ ↔ 0 ≤ a := by simp only [le_iff_eq_or_lt, inv_pos, zero_eq_inv] alias inv_nonneg ↔ _ inv_nonneg_of_nonneg @[simp] lemma inv_lt_zero : a⁻¹ < 0 ↔ a < 0 := by simp only [← not_le, inv_nonneg] @[simp] lemma inv_nonpos : a⁻¹ ≤ 0 ↔ a ≤ 0 := by simp only [← not_lt, inv_pos] lemma one_div_pos : 0 < 1 / a ↔ 0 < a := inv_eq_one_div a ▸ inv_pos lemma one_div_neg : 1 / a < 0 ↔ a < 0 := inv_eq_one_div a ▸ inv_lt_zero lemma one_div_nonneg : 0 ≤ 1 / a ↔ 0 ≤ a := inv_eq_one_div a ▸ inv_nonneg lemma one_div_nonpos : 1 / a ≤ 0 ↔ a ≤ 0 := inv_eq_one_div a ▸ inv_nonpos lemma div_pos (ha : 0 < a) (hb : 0 < b) : 0 < a / b := by { rw div_eq_mul_inv, exact mul_pos ha (inv_pos.2 hb) } lemma div_nonneg (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a / b := by { rw div_eq_mul_inv, exact mul_nonneg ha (inv_nonneg.2 hb) } lemma div_nonpos_of_nonpos_of_nonneg (ha : a ≤ 0) (hb : 0 ≤ b) : a / b ≤ 0 := by { rw div_eq_mul_inv, exact mul_nonpos_of_nonpos_of_nonneg ha (inv_nonneg.2 hb) } lemma div_nonpos_of_nonneg_of_nonpos (ha : 0 ≤ a) (hb : b ≤ 0) : a / b ≤ 0 := by { rw div_eq_mul_inv, exact mul_nonpos_of_nonneg_of_nonpos ha (inv_nonpos.2 hb) } lemma zpow_nonneg (ha : 0 ≤ a) : ∀ n : ℤ, 0 ≤ a ^ n | (n : ℕ) := by { rw zpow_coe_nat, exact pow_nonneg ha _ } | -[1+n] := by { rw zpow_neg_succ_of_nat, exact inv_nonneg.2 (pow_nonneg ha _) } lemma zpow_pos_of_pos (ha : 0 < a) : ∀ n : ℤ, 0 < a ^ n | (n : ℕ) := by { rw zpow_coe_nat, exact pow_pos ha _ } | -[1+n] := by { rw zpow_neg_succ_of_nat, exact inv_pos.2 (pow_pos ha _) } /-! ### Relating one division with another term. -/ lemma le_div_iff (hc : 0 < c) : a ≤ b / c ↔ a * c ≤ b := ⟨λ h, div_mul_cancel b (ne_of_lt hc).symm ▸ mul_le_mul_of_nonneg_right h hc.le, λ h, calc a = a * c * (1 / c) : mul_mul_div a (ne_of_lt hc).symm ... ≤ b * (1 / c) : mul_le_mul_of_nonneg_right h (one_div_pos.2 hc).le ... = b / c : (div_eq_mul_one_div b c).symm⟩ lemma le_div_iff' (hc : 0 < c) : a ≤ b / c ↔ c * a ≤ b := by rw [mul_comm, le_div_iff hc] lemma div_le_iff (hb : 0 < b) : a / b ≤ c ↔ a ≤ c * b := ⟨λ h, calc a = a / b * b : by rw (div_mul_cancel _ (ne_of_lt hb).symm) ... ≤ c * b : mul_le_mul_of_nonneg_right h hb.le, λ h, calc a / b = a * (1 / b) : div_eq_mul_one_div a b ... ≤ (c * b) * (1 / b) : mul_le_mul_of_nonneg_right h (one_div_pos.2 hb).le ... = (c * b) / b : (div_eq_mul_one_div (c * b) b).symm ... = c : by refine (div_eq_iff (ne_of_gt hb)).mpr rfl⟩ lemma div_le_iff' (hb : 0 < b) : a / b ≤ c ↔ a ≤ b * c := by rw [mul_comm, div_le_iff hb] lemma lt_div_iff (hc : 0 < c) : a < b / c ↔ a * c < b := lt_iff_lt_of_le_iff_le $ div_le_iff hc lemma lt_div_iff' (hc : 0 < c) : a < b / c ↔ c * a < b := by rw [mul_comm, lt_div_iff hc] lemma div_lt_iff (hc : 0 < c) : b / c < a ↔ b < a * c := lt_iff_lt_of_le_iff_le (le_div_iff hc) lemma div_lt_iff' (hc : 0 < c) : b / c < a ↔ b < c * a := by rw [mul_comm, div_lt_iff hc] lemma inv_mul_le_iff (h : 0 < b) : b⁻¹ * a ≤ c ↔ a ≤ b * c := begin rw [inv_eq_one_div, mul_comm, ← div_eq_mul_one_div], exact div_le_iff' h, end lemma inv_mul_le_iff' (h : 0 < b) : b⁻¹ * a ≤ c ↔ a ≤ c * b := by rw [inv_mul_le_iff h, mul_comm] lemma mul_inv_le_iff (h : 0 < b) : a * b⁻¹ ≤ c ↔ a ≤ b * c := by rw [mul_comm, inv_mul_le_iff h] lemma mul_inv_le_iff' (h : 0 < b) : a * b⁻¹ ≤ c ↔ a ≤ c * b := by rw [mul_comm, inv_mul_le_iff' h] lemma div_self_le_one (a : α) : a / a ≤ 1 := if h : a = 0 then by simp [h] else by simp [h] lemma inv_mul_lt_iff (h : 0 < b) : b⁻¹ * a < c ↔ a < b * c := begin rw [inv_eq_one_div, mul_comm, ← div_eq_mul_one_div], exact div_lt_iff' h, end lemma inv_mul_lt_iff' (h : 0 < b) : b⁻¹ * a < c ↔ a < c * b := by rw [inv_mul_lt_iff h, mul_comm] lemma mul_inv_lt_iff (h : 0 < b) : a * b⁻¹ < c ↔ a < b * c := by rw [mul_comm, inv_mul_lt_iff h] lemma mul_inv_lt_iff' (h : 0 < b) : a * b⁻¹ < c ↔ a < c * b := by rw [mul_comm, inv_mul_lt_iff' h] lemma inv_pos_le_iff_one_le_mul (ha : 0 < a) : a⁻¹ ≤ b ↔ 1 ≤ b * a := by { rw [inv_eq_one_div], exact div_le_iff ha } lemma inv_pos_le_iff_one_le_mul' (ha : 0 < a) : a⁻¹ ≤ b ↔ 1 ≤ a * b := by { rw [inv_eq_one_div], exact div_le_iff' ha } lemma inv_pos_lt_iff_one_lt_mul (ha : 0 < a) : a⁻¹ < b ↔ 1 < b * a := by { rw [inv_eq_one_div], exact div_lt_iff ha } lemma inv_pos_lt_iff_one_lt_mul' (ha : 0 < a) : a⁻¹ < b ↔ 1 < a * b := by { rw [inv_eq_one_div], exact div_lt_iff' ha } /-- One direction of `div_le_iff` where `b` is allowed to be `0` (but `c` must be nonnegative) -/ lemma div_le_of_nonneg_of_le_mul (hb : 0 ≤ b) (hc : 0 ≤ c) (h : a ≤ c * b) : a / b ≤ c := by { rcases eq_or_lt_of_le hb with rfl|hb', simp [hc], rwa [div_le_iff hb'] } lemma div_le_one_of_le (h : a ≤ b) (hb : 0 ≤ b) : a / b ≤ 1 := div_le_of_nonneg_of_le_mul hb zero_le_one $ by rwa one_mul /-! ### Bi-implications of inequalities using inversions -/ lemma inv_le_inv_of_le (ha : 0 < a) (h : a ≤ b) : b⁻¹ ≤ a⁻¹ := by rwa [← one_div a, le_div_iff' ha, ← div_eq_mul_inv, div_le_iff (ha.trans_le h), one_mul] /-- See `inv_le_inv_of_le` for the implication from right-to-left with one fewer assumption. -/ lemma inv_le_inv (ha : 0 < a) (hb : 0 < b) : a⁻¹ ≤ b⁻¹ ↔ b ≤ a := by rw [← one_div, div_le_iff ha, ← div_eq_inv_mul, le_div_iff hb, one_mul] /-- In a linear ordered field, for positive `a` and `b` we have `a⁻¹ ≤ b ↔ b⁻¹ ≤ a`. See also `inv_le_of_inv_le` for a one-sided implication with one fewer assumption. -/ lemma inv_le (ha : 0 < a) (hb : 0 < b) : a⁻¹ ≤ b ↔ b⁻¹ ≤ a := by rw [← inv_le_inv hb (inv_pos.2 ha), inv_inv] lemma inv_le_of_inv_le (ha : 0 < a) (h : a⁻¹ ≤ b) : b⁻¹ ≤ a := (inv_le ha ((inv_pos.2 ha).trans_le h)).1 h lemma le_inv (ha : 0 < a) (hb : 0 < b) : a ≤ b⁻¹ ↔ b ≤ a⁻¹ := by rw [← inv_le_inv (inv_pos.2 hb) ha, inv_inv] /-- See `inv_lt_inv_of_lt` for the implication from right-to-left with one fewer assumption. -/ lemma inv_lt_inv (ha : 0 < a) (hb : 0 < b) : a⁻¹ < b⁻¹ ↔ b < a := lt_iff_lt_of_le_iff_le (inv_le_inv hb ha) lemma inv_lt_inv_of_lt (hb : 0 < b) (h : b < a) : a⁻¹ < b⁻¹ := (inv_lt_inv (hb.trans h) hb).2 h /-- In a linear ordered field, for positive `a` and `b` we have `a⁻¹ < b ↔ b⁻¹ < a`. See also `inv_lt_of_inv_lt` for a one-sided implication with one fewer assumption. -/ lemma inv_lt (ha : 0 < a) (hb : 0 < b) : a⁻¹ < b ↔ b⁻¹ < a := lt_iff_lt_of_le_iff_le (le_inv hb ha) lemma inv_lt_of_inv_lt (ha : 0 < a) (h : a⁻¹ < b) : b⁻¹ < a := (inv_lt ha ((inv_pos.2 ha).trans h)).1 h lemma lt_inv (ha : 0 < a) (hb : 0 < b) : a < b⁻¹ ↔ b < a⁻¹ := lt_iff_lt_of_le_iff_le (inv_le hb ha) lemma inv_lt_one (ha : 1 < a) : a⁻¹ < 1 := by rwa [inv_lt ((@zero_lt_one α _ _).trans ha) zero_lt_one, inv_one] lemma one_lt_inv (h₁ : 0 < a) (h₂ : a < 1) : 1 < a⁻¹ := by rwa [lt_inv (@zero_lt_one α _ _) h₁, inv_one] lemma inv_le_one (ha : 1 ≤ a) : a⁻¹ ≤ 1 := by rwa [inv_le ((@zero_lt_one α _ _).trans_le ha) zero_lt_one, inv_one] lemma one_le_inv (h₁ : 0 < a) (h₂ : a ≤ 1) : 1 ≤ a⁻¹ := by rwa [le_inv (@zero_lt_one α _ _) h₁, inv_one] lemma inv_lt_one_iff_of_pos (h₀ : 0 < a) : a⁻¹ < 1 ↔ 1 < a := ⟨λ h₁, inv_inv a ▸ one_lt_inv (inv_pos.2 h₀) h₁, inv_lt_one⟩ lemma inv_lt_one_iff : a⁻¹ < 1 ↔ a ≤ 0 ∨ 1 < a := begin cases le_or_lt a 0 with ha ha, { simp [ha, (inv_nonpos.2 ha).trans_lt zero_lt_one] }, { simp only [ha.not_le, false_or, inv_lt_one_iff_of_pos ha] } end lemma one_lt_inv_iff : 1 < a⁻¹ ↔ 0 < a ∧ a < 1 := ⟨λ h, ⟨inv_pos.1 (zero_lt_one.trans h), inv_inv a ▸ inv_lt_one h⟩, and_imp.2 one_lt_inv⟩ lemma inv_le_one_iff : a⁻¹ ≤ 1 ↔ a ≤ 0 ∨ 1 ≤ a := begin rcases em (a = 1) with (rfl|ha), { simp [le_rfl] }, { simp only [ne.le_iff_lt (ne.symm ha), ne.le_iff_lt (mt inv_eq_one.1 ha), inv_lt_one_iff] } end lemma one_le_inv_iff : 1 ≤ a⁻¹ ↔ 0 < a ∧ a ≤ 1 := ⟨λ h, ⟨inv_pos.1 (zero_lt_one.trans_le h), inv_inv a ▸ inv_le_one h⟩, and_imp.2 one_le_inv⟩ /-! ### Relating two divisions. -/ @[mono] lemma div_le_div_of_le (hc : 0 ≤ c) (h : a ≤ b) : a / c ≤ b / c := begin rw [div_eq_mul_one_div a c, div_eq_mul_one_div b c], exact mul_le_mul_of_nonneg_right h (one_div_nonneg.2 hc) end -- Not a `mono` lemma b/c `div_le_div` is strictly more general lemma div_le_div_of_le_left (ha : 0 ≤ a) (hc : 0 < c) (h : c ≤ b) : a / b ≤ a / c := begin rw [div_eq_mul_inv, div_eq_mul_inv], exact mul_le_mul_of_nonneg_left ((inv_le_inv (hc.trans_le h) hc).mpr h) ha end lemma div_le_div_of_le_of_nonneg (hab : a ≤ b) (hc : 0 ≤ c) : a / c ≤ b / c := div_le_div_of_le hc hab lemma div_lt_div_of_lt (hc : 0 < c) (h : a < b) : a / c < b / c := begin rw [div_eq_mul_one_div a c, div_eq_mul_one_div b c], exact mul_lt_mul_of_pos_right h (one_div_pos.2 hc) end lemma div_le_div_right (hc : 0 < c) : a / c ≤ b / c ↔ a ≤ b := ⟨le_imp_le_of_lt_imp_lt $ div_lt_div_of_lt hc, div_le_div_of_le $ hc.le⟩ lemma div_lt_div_right (hc : 0 < c) : a / c < b / c ↔ a < b := lt_iff_lt_of_le_iff_le $ div_le_div_right hc lemma div_lt_div_left (ha : 0 < a) (hb : 0 < b) (hc : 0 < c) : a / b < a / c ↔ c < b := by simp only [div_eq_mul_inv, mul_lt_mul_left ha, inv_lt_inv hb hc] lemma div_le_div_left (ha : 0 < a) (hb : 0 < b) (hc : 0 < c) : a / b ≤ a / c ↔ c ≤ b := le_iff_le_iff_lt_iff_lt.2 (div_lt_div_left ha hc hb) lemma div_lt_div_iff (b0 : 0 < b) (d0 : 0 < d) : a / b < c / d ↔ a * d < c * b := by rw [lt_div_iff d0, div_mul_eq_mul_div, div_lt_iff b0] lemma div_le_div_iff (b0 : 0 < b) (d0 : 0 < d) : a / b ≤ c / d ↔ a * d ≤ c * b := by rw [le_div_iff d0, div_mul_eq_mul_div, div_le_iff b0] @[mono] lemma div_le_div (hc : 0 ≤ c) (hac : a ≤ c) (hd : 0 < d) (hbd : d ≤ b) : a / b ≤ c / d := by { rw div_le_div_iff (hd.trans_le hbd) hd, exact mul_le_mul hac hbd hd.le hc } lemma div_lt_div (hac : a < c) (hbd : d ≤ b) (c0 : 0 ≤ c) (d0 : 0 < d) : a / b < c / d := (div_lt_div_iff (d0.trans_le hbd) d0).2 (mul_lt_mul hac hbd d0 c0) lemma div_lt_div' (hac : a ≤ c) (hbd : d < b) (c0 : 0 < c) (d0 : 0 < d) : a / b < c / d := (div_lt_div_iff (d0.trans hbd) d0).2 (mul_lt_mul' hac hbd d0.le c0) lemma div_lt_div_of_lt_left (hc : 0 < c) (hb : 0 < b) (h : b < a) : c / a < c / b := (div_lt_div_left hc (hb.trans h) hb).mpr h /-! ### Relating one division and involving `1` -/ lemma div_le_self (ha : 0 ≤ a) (hb : 1 ≤ b) : a / b ≤ a := by simpa only [div_one] using div_le_div_of_le_left ha zero_lt_one hb lemma div_lt_self (ha : 0 < a) (hb : 1 < b) : a / b < a := by simpa only [div_one] using div_lt_div_of_lt_left ha zero_lt_one hb lemma le_div_self (ha : 0 ≤ a) (hb₀ : 0 < b) (hb₁ : b ≤ 1) : a ≤ a / b := by simpa only [div_one] using div_le_div_of_le_left ha hb₀ hb₁ lemma one_le_div (hb : 0 < b) : 1 ≤ a / b ↔ b ≤ a := by rw [le_div_iff hb, one_mul] lemma div_le_one (hb : 0 < b) : a / b ≤ 1 ↔ a ≤ b := by rw [div_le_iff hb, one_mul] lemma one_lt_div (hb : 0 < b) : 1 < a / b ↔ b < a := by rw [lt_div_iff hb, one_mul] lemma div_lt_one (hb : 0 < b) : a / b < 1 ↔ a < b := by rw [div_lt_iff hb, one_mul] lemma one_div_le (ha : 0 < a) (hb : 0 < b) : 1 / a ≤ b ↔ 1 / b ≤ a := by simpa using inv_le ha hb lemma one_div_lt (ha : 0 < a) (hb : 0 < b) : 1 / a < b ↔ 1 / b < a := by simpa using inv_lt ha hb lemma le_one_div (ha : 0 < a) (hb : 0 < b) : a ≤ 1 / b ↔ b ≤ 1 / a := by simpa using le_inv ha hb lemma lt_one_div (ha : 0 < a) (hb : 0 < b) : a < 1 / b ↔ b < 1 / a := by simpa using lt_inv ha hb /-! ### Relating two divisions, involving `1` -/ lemma one_div_le_one_div_of_le (ha : 0 < a) (h : a ≤ b) : 1 / b ≤ 1 / a := by simpa using inv_le_inv_of_le ha h lemma one_div_lt_one_div_of_lt (ha : 0 < a) (h : a < b) : 1 / b < 1 / a := by rwa [lt_div_iff' ha, ← div_eq_mul_one_div, div_lt_one (ha.trans h)] lemma le_of_one_div_le_one_div (ha : 0 < a) (h : 1 / a ≤ 1 / b) : b ≤ a := le_imp_le_of_lt_imp_lt (one_div_lt_one_div_of_lt ha) h lemma lt_of_one_div_lt_one_div (ha : 0 < a) (h : 1 / a < 1 / b) : b < a := lt_imp_lt_of_le_imp_le (one_div_le_one_div_of_le ha) h /-- For the single implications with fewer assumptions, see `one_div_le_one_div_of_le` and `le_of_one_div_le_one_div` -/ lemma one_div_le_one_div (ha : 0 < a) (hb : 0 < b) : 1 / a ≤ 1 / b ↔ b ≤ a := div_le_div_left zero_lt_one ha hb /-- For the single implications with fewer assumptions, see `one_div_lt_one_div_of_lt` and `lt_of_one_div_lt_one_div` -/ lemma one_div_lt_one_div (ha : 0 < a) (hb : 0 < b) : 1 / a < 1 / b ↔ b < a := div_lt_div_left zero_lt_one ha hb lemma one_lt_one_div (h1 : 0 < a) (h2 : a < 1) : 1 < 1 / a := by rwa [lt_one_div (@zero_lt_one α _ _) h1, one_div_one] lemma one_le_one_div (h1 : 0 < a) (h2 : a ≤ 1) : 1 ≤ 1 / a := by rwa [le_one_div (@zero_lt_one α _ _) h1, one_div_one] /-! ### Integer powers -/ lemma zpow_le_of_le (ha : 1 ≤ a) (h : m ≤ n) : a ^ m ≤ a ^ n := begin have ha₀ : 0 < a, from one_pos.trans_le ha, lift n - m to ℕ using sub_nonneg.2 h with k hk, calc a ^ m = a ^ m * 1 : (mul_one _).symm ... ≤ a ^ m * a ^ k : mul_le_mul_of_nonneg_left (one_le_pow_of_one_le ha _) (zpow_nonneg ha₀.le _) ... = a ^ n : by rw [← zpow_coe_nat, ← zpow_add₀ ha₀.ne', hk, add_sub_cancel'_right] end lemma zpow_le_one_of_nonpos (ha : 1 ≤ a) (hn : n ≤ 0) : a ^ n ≤ 1 := (zpow_le_of_le ha hn).trans_eq $ zpow_zero _ lemma one_le_zpow_of_nonneg (ha : 1 ≤ a) (hn : 0 ≤ n) : 1 ≤ a ^ n := (zpow_zero _).symm.trans_le $ zpow_le_of_le ha hn protected lemma nat.zpow_pos_of_pos {a : ℕ} (h : 0 < a) (n : ℤ) : 0 < (a : α)^n := by { apply zpow_pos_of_pos, exact_mod_cast h } lemma nat.zpow_ne_zero_of_pos {a : ℕ} (h : 0 < a) (n : ℤ) : (a : α)^n ≠ 0 := (nat.zpow_pos_of_pos h n).ne' lemma one_lt_zpow (ha : 1 < a) : ∀ n : ℤ, 0 < n → 1 < a ^ n | (n : ℕ) h := (zpow_coe_nat _ _).symm.subst (one_lt_pow ha $ int.coe_nat_ne_zero.mp h.ne') | -[1+ n] h := ((int.neg_succ_not_pos _).mp h).elim lemma zpow_strict_mono (hx : 1 < a) : strict_mono ((^) a : ℤ → α) := strict_mono_int_of_lt_succ $ λ n, have xpos : 0 < a, from zero_lt_one.trans hx, calc a ^ n < a ^ n * a : lt_mul_of_one_lt_right (zpow_pos_of_pos xpos _) hx ... = a ^ (n + 1) : (zpow_add_one₀ xpos.ne' _).symm lemma zpow_strict_anti (h₀ : 0 < a) (h₁ : a < 1) : strict_anti ((^) a : ℤ → α) := strict_anti_int_of_succ_lt $ λ n, calc a ^ (n + 1) = a ^ n * a : zpow_add_one₀ h₀.ne' _ ... < a ^ n * 1 : (mul_lt_mul_left $ zpow_pos_of_pos h₀ _).2 h₁ ... = a ^ n : mul_one _ @[simp] lemma zpow_lt_iff_lt (hx : 1 < a) : a ^ m < a ^ n ↔ m < n := (zpow_strict_mono hx).lt_iff_lt @[simp] lemma zpow_le_iff_le (hx : 1 < a) : a ^ m ≤ a ^ n ↔ m ≤ n := (zpow_strict_mono hx).le_iff_le @[simp] lemma div_pow_le (ha : 0 ≤ a) (hb : 1 ≤ b) (k : ℕ) : a/b^k ≤ a := div_le_self ha $ one_le_pow_of_one_le hb _ lemma zpow_injective (h₀ : 0 < a) (h₁ : a ≠ 1) : injective ((^) a : ℤ → α) := begin rcases h₁.lt_or_lt with H|H, { exact (zpow_strict_anti h₀ H).injective }, { exact (zpow_strict_mono H).injective } end @[simp] lemma zpow_inj (h₀ : 0 < a) (h₁ : a ≠ 1) : a ^ m = a ^ n ↔ m = n := (zpow_injective h₀ h₁).eq_iff lemma zpow_le_max_of_min_le {x : α} (hx : 1 ≤ x) {a b c : ℤ} (h : min a b ≤ c) : x ^ -c ≤ max (x ^ -a) (x ^ -b) := begin have : antitone (λ n : ℤ, x ^ -n) := λ m n h, zpow_le_of_le hx (neg_le_neg h), exact (this h).trans_eq this.map_min, end lemma zpow_le_max_iff_min_le {x : α} (hx : 1 < x) {a b c : ℤ} : x ^ -c ≤ max (x ^ -a) (x ^ -b) ↔ min a b ≤ c := by simp_rw [le_max_iff, min_le_iff, zpow_le_iff_le hx, neg_le_neg_iff] /-! ### Results about halving. The equalities also hold in semifields of characteristic `0`. -/ /- TODO: Unify `add_halves` and `add_halves'` into a single lemma about `division_semiring` + `char_zero` -/ lemma add_halves (a : α) : a / 2 + a / 2 = a := by rw [div_add_div_same, ← two_mul, mul_div_cancel_left a two_ne_zero] -- TODO: Generalize to `division_semiring` lemma add_self_div_two (a : α) : (a + a) / 2 = a := by rw [← mul_two, mul_div_cancel a two_ne_zero] lemma half_pos (h : 0 < a) : 0 < a / 2 := div_pos h zero_lt_two lemma one_half_pos : (0:α) < 1 / 2 := half_pos zero_lt_one lemma div_two_lt_of_pos (h : 0 < a) : a / 2 < a := by { rw [div_lt_iff (@zero_lt_two α _ _)], exact lt_mul_of_one_lt_right h one_lt_two } lemma half_lt_self : 0 < a → a / 2 < a := div_two_lt_of_pos lemma half_le_self (ha_nonneg : 0 ≤ a) : a / 2 ≤ a := begin by_cases h0 : a = 0, { simp [h0], }, { rw ← ne.def at h0, exact (half_lt_self (lt_of_le_of_ne ha_nonneg h0.symm)).le, }, end lemma one_half_lt_one : (1 / 2 : α) < 1 := half_lt_self zero_lt_one lemma two_inv_lt_one : (2⁻¹ : α) < 1 := (one_div _).symm.trans_lt one_half_lt_one lemma left_lt_add_div_two : a < (a + b) / 2 ↔ a < b := by simp [lt_div_iff, mul_two] lemma add_div_two_lt_right : (a + b) / 2 < b ↔ a < b := by simp [div_lt_iff, mul_two] /-! ### Miscellaneous lemmas -/ lemma mul_le_mul_of_mul_div_le (h : a * (b / c) ≤ d) (hc : 0 < c) : b * a ≤ d * c := begin rw [← mul_div_assoc] at h, rwa [mul_comm b, ← div_le_iff hc], end lemma div_mul_le_div_mul_of_div_le_div (h : a / b ≤ c / d) (he : 0 ≤ e) : a / (b * e) ≤ c / (d * e) := begin rw [div_mul_eq_div_mul_one_div, div_mul_eq_div_mul_one_div], exact mul_le_mul_of_nonneg_right h (one_div_nonneg.2 he) end lemma exists_pos_mul_lt {a : α} (h : 0 < a) (b : α) : ∃ c : α, 0 < c ∧ b * c < a := begin have : 0 < a / max (b + 1) 1, from div_pos h (lt_max_iff.2 (or.inr zero_lt_one)), refine ⟨a / max (b + 1) 1, this, _⟩, rw [← lt_div_iff this, div_div_cancel' h.ne'], exact lt_max_iff.2 (or.inl $ lt_add_one _) end lemma monotone.div_const {β : Type*} [preorder β] {f : β → α} (hf : monotone f) {c : α} (hc : 0 ≤ c) : monotone (λ x, (f x) / c) := begin haveI := @linear_order.decidable_le α _, simpa only [div_eq_mul_inv] using (decidable.monotone_mul_right_of_nonneg (inv_nonneg.2 hc)).comp hf end lemma strict_mono.div_const {β : Type*} [preorder β] {f : β → α} (hf : strict_mono f) {c : α} (hc : 0 < c) : strict_mono (λ x, (f x) / c) := by simpa only [div_eq_mul_inv] using hf.mul_const (inv_pos.2 hc) @[priority 100] -- see Note [lower instance priority] instance linear_ordered_field.to_densely_ordered : densely_ordered α := { dense := λ a₁ a₂ h, ⟨(a₁ + a₂) / 2, calc a₁ = (a₁ + a₁) / 2 : (add_self_div_two a₁).symm ... < (a₁ + a₂) / 2 : div_lt_div_of_lt zero_lt_two (add_lt_add_left h _), calc (a₁ + a₂) / 2 < (a₂ + a₂) / 2 : div_lt_div_of_lt zero_lt_two (add_lt_add_right h _) ... = a₂ : add_self_div_two a₂⟩ } lemma min_div_div_right {c : α} (hc : 0 ≤ c) (a b : α) : min (a / c) (b / c) = (min a b) / c := eq.symm $ monotone.map_min (λ x y, div_le_div_of_le hc) lemma max_div_div_right {c : α} (hc : 0 ≤ c) (a b : α) : max (a / c) (b / c) = (max a b) / c := eq.symm $ monotone.map_max (λ x y, div_le_div_of_le hc) lemma one_div_strict_anti_on : strict_anti_on (λ x : α, 1 / x) (set.Ioi 0) := λ x x1 y y1 xy, (one_div_lt_one_div (set.mem_Ioi.mp y1) (set.mem_Ioi.mp x1)).mpr xy lemma one_div_pow_le_one_div_pow_of_le (a1 : 1 ≤ a) {m n : ℕ} (mn : m ≤ n) : 1 / a ^ n ≤ 1 / a ^ m := by refine (one_div_le_one_div _ _).mpr (pow_le_pow a1 mn); exact pow_pos (zero_lt_one.trans_le a1) _ lemma one_div_pow_lt_one_div_pow_of_lt (a1 : 1 < a) {m n : ℕ} (mn : m < n) : 1 / a ^ n < 1 / a ^ m := by refine (one_div_lt_one_div _ _).mpr (pow_lt_pow a1 mn); exact pow_pos (trans zero_lt_one a1) _ lemma one_div_pow_anti (a1 : 1 ≤ a) : antitone (λ n : ℕ, 1 / a ^ n) := λ m n, one_div_pow_le_one_div_pow_of_le a1 lemma one_div_pow_strict_anti (a1 : 1 < a) : strict_anti (λ n : ℕ, 1 / a ^ n) := λ m n, one_div_pow_lt_one_div_pow_of_lt a1 lemma inv_strict_anti_on : strict_anti_on (λ x : α, x⁻¹) (set.Ioi 0) := λ x hx y hy xy, (inv_lt_inv hy hx).2 xy lemma inv_pow_le_inv_pow_of_le (a1 : 1 ≤ a) {m n : ℕ} (mn : m ≤ n) : (a ^ n)⁻¹ ≤ (a ^ m)⁻¹ := by convert one_div_pow_le_one_div_pow_of_le a1 mn; simp lemma inv_pow_lt_inv_pow_of_lt (a1 : 1 < a) {m n : ℕ} (mn : m < n) : (a ^ n)⁻¹ < (a ^ m)⁻¹ := by convert one_div_pow_lt_one_div_pow_of_lt a1 mn; simp lemma inv_pow_anti (a1 : 1 ≤ a) : antitone (λ n : ℕ, (a ^ n)⁻¹) := λ m n, inv_pow_le_inv_pow_of_le a1 lemma inv_pow_strict_anti (a1 : 1 < a) : strict_anti (λ n : ℕ, (a ^ n)⁻¹) := λ m n, inv_pow_lt_inv_pow_of_lt a1 /-! ### Results about `is_lub` and `is_glb` -/ lemma is_glb.mul_left {s : set α} (ha : 0 ≤ a) (hs : is_glb s b) : is_glb ((λ b, a * b) '' s) (a * b) := begin rcases lt_or_eq_of_le ha with ha | rfl, { exact (order_iso.mul_left₀ _ ha).is_glb_image'.2 hs, }, { simp_rw zero_mul, rw hs.nonempty.image_const, exact is_glb_singleton }, end lemma is_glb.mul_right {s : set α} (ha : 0 ≤ a) (hs : is_glb s b) : is_glb ((λ b, b * a) '' s) (b * a) := by simpa [mul_comm] using hs.mul_left ha end linear_ordered_semifield section variables [linear_ordered_field α] {a b c d : α} {n : ℤ} /-! ### Lemmas about pos, nonneg, nonpos, neg -/ lemma div_pos_iff : 0 < a / b ↔ 0 < a ∧ 0 < b ∨ a < 0 ∧ b < 0 := by simp [division_def, mul_pos_iff] lemma div_neg_iff : a / b < 0 ↔ 0 < a ∧ b < 0 ∨ a < 0 ∧ 0 < b := by simp [division_def, mul_neg_iff] lemma div_nonneg_iff : 0 ≤ a / b ↔ 0 ≤ a ∧ 0 ≤ b ∨ a ≤ 0 ∧ b ≤ 0 := by simp [division_def, mul_nonneg_iff] lemma div_nonpos_iff : a / b ≤ 0 ↔ 0 ≤ a ∧ b ≤ 0 ∨ a ≤ 0 ∧ 0 ≤ b := by simp [division_def, mul_nonpos_iff] lemma div_nonneg_of_nonpos (ha : a ≤ 0) (hb : b ≤ 0) : 0 ≤ a / b := div_nonneg_iff.2 $ or.inr ⟨ha, hb⟩ lemma div_pos_of_neg_of_neg (ha : a < 0) (hb : b < 0) : 0 < a / b := div_pos_iff.2 $ or.inr ⟨ha, hb⟩ lemma div_neg_of_neg_of_pos (ha : a < 0) (hb : 0 < b) : a / b < 0 := div_neg_iff.2 $ or.inr ⟨ha, hb⟩ lemma div_neg_of_pos_of_neg (ha : 0 < a) (hb : b < 0) : a / b < 0 := div_neg_iff.2 $ or.inl ⟨ha, hb⟩ lemma zpow_bit0_nonneg (a : α) (n : ℤ) : 0 ≤ a ^ bit0 n := (mul_self_nonneg _).trans_eq $ (zpow_bit0 _ _).symm lemma zpow_two_nonneg (a : α) : 0 ≤ a ^ (2 : ℤ) := zpow_bit0_nonneg _ _ lemma zpow_bit0_pos (h : a ≠ 0) (n : ℤ) : 0 < a ^ bit0 n := (zpow_bit0_nonneg a n).lt_of_ne (zpow_ne_zero _ h).symm lemma zpow_two_pos_of_ne_zero (h : a ≠ 0) : 0 < a ^ (2 : ℤ) := zpow_bit0_pos h _ @[simp] lemma zpow_bit1_neg_iff : a ^ bit1 n < 0 ↔ a < 0 := ⟨λ h, not_le.1 $ λ h', not_le.2 h $ zpow_nonneg h' _, λ h, by rw [bit1, zpow_add_one₀ h.ne]; exact mul_neg_of_pos_of_neg (zpow_bit0_pos h.ne _) h⟩ @[simp] lemma zpow_bit1_nonneg_iff : 0 ≤ a ^ bit1 n ↔ 0 ≤ a := le_iff_le_iff_lt_iff_lt.2 zpow_bit1_neg_iff @[simp] lemma zpow_bit1_nonpos_iff : a ^ bit1 n ≤ 0 ↔ a ≤ 0 := by rw [le_iff_lt_or_eq, le_iff_lt_or_eq, zpow_bit1_neg_iff, zpow_eq_zero_iff (int.bit1_ne_zero n)] @[simp] lemma zpow_bit1_pos_iff : 0 < a ^ bit1 n ↔ 0 < a := lt_iff_lt_of_le_iff_le zpow_bit1_nonpos_iff /-! ### Relating one division with another term -/ lemma div_le_iff_of_neg (hc : c < 0) : b / c ≤ a ↔ a * c ≤ b := ⟨λ h, div_mul_cancel b (ne_of_lt hc) ▸ mul_le_mul_of_nonpos_right h hc.le, λ h, calc a = a * c * (1 / c) : mul_mul_div a (ne_of_lt hc) ... ≥ b * (1 / c) : mul_le_mul_of_nonpos_right h (one_div_neg.2 hc).le ... = b / c : (div_eq_mul_one_div b c).symm⟩ lemma div_le_iff_of_neg' (hc : c < 0) : b / c ≤ a ↔ c * a ≤ b := by rw [mul_comm, div_le_iff_of_neg hc] lemma le_div_iff_of_neg (hc : c < 0) : a ≤ b / c ↔ b ≤ a * c := by rw [← neg_neg c, mul_neg, div_neg, le_neg, div_le_iff (neg_pos.2 hc), neg_mul] lemma le_div_iff_of_neg' (hc : c < 0) : a ≤ b / c ↔ b ≤ c * a := by rw [mul_comm, le_div_iff_of_neg hc] lemma div_lt_iff_of_neg (hc : c < 0) : b / c < a ↔ a * c < b := lt_iff_lt_of_le_iff_le $ le_div_iff_of_neg hc lemma div_lt_iff_of_neg' (hc : c < 0) : b / c < a ↔ c * a < b := by rw [mul_comm, div_lt_iff_of_neg hc] lemma lt_div_iff_of_neg (hc : c < 0) : a < b / c ↔ b < a * c := lt_iff_lt_of_le_iff_le $ div_le_iff_of_neg hc lemma lt_div_iff_of_neg' (hc : c < 0) : a < b / c ↔ b < c * a := by rw [mul_comm, lt_div_iff_of_neg hc] /-! ### Bi-implications of inequalities using inversions -/ lemma inv_le_inv_of_neg (ha : a < 0) (hb : b < 0) : a⁻¹ ≤ b⁻¹ ↔ b ≤ a := by rw [← one_div, div_le_iff_of_neg ha, ← div_eq_inv_mul, div_le_iff_of_neg hb, one_mul] lemma inv_le_of_neg (ha : a < 0) (hb : b < 0) : a⁻¹ ≤ b ↔ b⁻¹ ≤ a := by rw [← inv_le_inv_of_neg hb (inv_lt_zero.2 ha), inv_inv] lemma le_inv_of_neg (ha : a < 0) (hb : b < 0) : a ≤ b⁻¹ ↔ b ≤ a⁻¹ := by rw [← inv_le_inv_of_neg (inv_lt_zero.2 hb) ha, inv_inv] lemma inv_lt_inv_of_neg (ha : a < 0) (hb : b < 0) : a⁻¹ < b⁻¹ ↔ b < a := lt_iff_lt_of_le_iff_le (inv_le_inv_of_neg hb ha) lemma inv_lt_of_neg (ha : a < 0) (hb : b < 0) : a⁻¹ < b ↔ b⁻¹ < a := lt_iff_lt_of_le_iff_le (le_inv_of_neg hb ha) lemma lt_inv_of_neg (ha : a < 0) (hb : b < 0) : a < b⁻¹ ↔ b < a⁻¹ := lt_iff_lt_of_le_iff_le (inv_le_of_neg hb ha) /-! ### Relating two divisions -/ lemma div_le_div_of_nonpos_of_le (hc : c ≤ 0) (h : b ≤ a) : a / c ≤ b / c := begin rw [div_eq_mul_one_div a c, div_eq_mul_one_div b c], exact mul_le_mul_of_nonpos_right h (one_div_nonpos.2 hc) end lemma div_lt_div_of_neg_of_lt (hc : c < 0) (h : b < a) : a / c < b / c := begin rw [div_eq_mul_one_div a c, div_eq_mul_one_div b c], exact mul_lt_mul_of_neg_right h (one_div_neg.2 hc) end lemma div_le_div_right_of_neg (hc : c < 0) : a / c ≤ b / c ↔ b ≤ a := ⟨le_imp_le_of_lt_imp_lt $ div_lt_div_of_neg_of_lt hc, div_le_div_of_nonpos_of_le $ hc.le⟩ lemma div_lt_div_right_of_neg (hc : c < 0) : a / c < b / c ↔ b < a := lt_iff_lt_of_le_iff_le $ div_le_div_right_of_neg hc /-! ### Relating one division and involving `1` -/ lemma one_le_div_of_neg (hb : b < 0) : 1 ≤ a / b ↔ a ≤ b := by rw [le_div_iff_of_neg hb, one_mul] lemma div_le_one_of_neg (hb : b < 0) : a / b ≤ 1 ↔ b ≤ a := by rw [div_le_iff_of_neg hb, one_mul] lemma one_lt_div_of_neg (hb : b < 0) : 1 < a / b ↔ a < b := by rw [lt_div_iff_of_neg hb, one_mul] lemma div_lt_one_of_neg (hb : b < 0) : a / b < 1 ↔ b < a := by rw [div_lt_iff_of_neg hb, one_mul] lemma one_div_le_of_neg (ha : a < 0) (hb : b < 0) : 1 / a ≤ b ↔ 1 / b ≤ a := by simpa using inv_le_of_neg ha hb lemma one_div_lt_of_neg (ha : a < 0) (hb : b < 0) : 1 / a < b ↔ 1 / b < a := by simpa using inv_lt_of_neg ha hb lemma le_one_div_of_neg (ha : a < 0) (hb : b < 0) : a ≤ 1 / b ↔ b ≤ 1 / a := by simpa using le_inv_of_neg ha hb lemma lt_one_div_of_neg (ha : a < 0) (hb : b < 0) : a < 1 / b ↔ b < 1 / a := by simpa using lt_inv_of_neg ha hb lemma one_lt_div_iff : 1 < a / b ↔ 0 < b ∧ b < a ∨ b < 0 ∧ a < b := begin rcases lt_trichotomy b 0 with (hb|rfl|hb), { simp [hb, hb.not_lt, one_lt_div_of_neg] }, { simp [lt_irrefl, zero_le_one] }, { simp [hb, hb.not_lt, one_lt_div] } end lemma one_le_div_iff : 1 ≤ a / b ↔ 0 < b ∧ b ≤ a ∨ b < 0 ∧ a ≤ b := begin rcases lt_trichotomy b 0 with (hb|rfl|hb), { simp [hb, hb.not_lt, one_le_div_of_neg] }, { simp [lt_irrefl, zero_lt_one.not_le, zero_lt_one] }, { simp [hb, hb.not_lt, one_le_div] } end lemma div_lt_one_iff : a / b < 1 ↔ 0 < b ∧ a < b ∨ b = 0 ∨ b < 0 ∧ b < a := begin rcases lt_trichotomy b 0 with (hb|rfl|hb), { simp [hb, hb.not_lt, hb.ne, div_lt_one_of_neg] }, { simp [zero_lt_one], }, { simp [hb, hb.not_lt, div_lt_one, hb.ne.symm] } end lemma div_le_one_iff : a / b ≤ 1 ↔ 0 < b ∧ a ≤ b ∨ b = 0 ∨ b < 0 ∧ b ≤ a := begin rcases lt_trichotomy b 0 with (hb|rfl|hb), { simp [hb, hb.not_lt, hb.ne, div_le_one_of_neg] }, { simp [zero_le_one], }, { simp [hb, hb.not_lt, div_le_one, hb.ne.symm] } end /-! ### Relating two divisions, involving `1` -/ lemma one_div_le_one_div_of_neg_of_le (hb : b < 0) (h : a ≤ b) : 1 / b ≤ 1 / a := by rwa [div_le_iff_of_neg' hb, ← div_eq_mul_one_div, div_le_one_of_neg (h.trans_lt hb)] lemma one_div_lt_one_div_of_neg_of_lt (hb : b < 0) (h : a < b) : 1 / b < 1 / a := by rwa [div_lt_iff_of_neg' hb, ← div_eq_mul_one_div, div_lt_one_of_neg (h.trans hb)] lemma le_of_neg_of_one_div_le_one_div (hb : b < 0) (h : 1 / a ≤ 1 / b) : b ≤ a := le_imp_le_of_lt_imp_lt (one_div_lt_one_div_of_neg_of_lt hb) h lemma lt_of_neg_of_one_div_lt_one_div (hb : b < 0) (h : 1 / a < 1 / b) : b < a := lt_imp_lt_of_le_imp_le (one_div_le_one_div_of_neg_of_le hb) h /-- For the single implications with fewer assumptions, see `one_div_lt_one_div_of_neg_of_lt` and `lt_of_one_div_lt_one_div` -/ lemma one_div_le_one_div_of_neg (ha : a < 0) (hb : b < 0) : 1 / a ≤ 1 / b ↔ b ≤ a := by simpa [one_div] using inv_le_inv_of_neg ha hb /-- For the single implications with fewer assumptions, see `one_div_lt_one_div_of_lt` and `lt_of_one_div_lt_one_div` -/ lemma one_div_lt_one_div_of_neg (ha : a < 0) (hb : b < 0) : 1 / a < 1 / b ↔ b < a := lt_iff_lt_of_le_iff_le (one_div_le_one_div_of_neg hb ha) lemma one_div_lt_neg_one (h1 : a < 0) (h2 : -1 < a) : 1 / a < -1 := suffices 1 / a < 1 / -1, by rwa one_div_neg_one_eq_neg_one at this, one_div_lt_one_div_of_neg_of_lt h1 h2 lemma one_div_le_neg_one (h1 : a < 0) (h2 : -1 ≤ a) : 1 / a ≤ -1 := suffices 1 / a ≤ 1 / -1, by rwa one_div_neg_one_eq_neg_one at this, one_div_le_one_div_of_neg_of_le h1 h2 /-! ### Results about halving -/ lemma sub_self_div_two (a : α) : a - a / 2 = a / 2 := suffices a / 2 + a / 2 - a / 2 = a / 2, by rwa add_halves at this, by rw [add_sub_cancel] lemma div_two_sub_self (a : α) : a / 2 - a = - (a / 2) := suffices a / 2 - (a / 2 + a / 2) = - (a / 2), by rwa add_halves at this, by rw [sub_add_eq_sub_sub, sub_self, zero_sub] lemma add_sub_div_two_lt (h : a < b) : a + (b - a) / 2 < b := begin rwa [← div_sub_div_same, sub_eq_add_neg, add_comm (b/2), ← add_assoc, ← sub_eq_add_neg, ← lt_sub_iff_add_lt, sub_self_div_two, sub_self_div_two, div_lt_div_right (@zero_lt_two α _ _)] end /-- An inequality involving `2`. -/ lemma sub_one_div_inv_le_two (a2 : 2 ≤ a) : (1 - 1 / a)⁻¹ ≤ 2 := begin -- Take inverses on both sides to obtain `2⁻¹ ≤ 1 - 1 / a` refine (inv_le_inv_of_le (inv_pos.2 zero_lt_two) _).trans_eq (inv_inv (2 : α)), -- move `1 / a` to the left and `1 - 1 / 2 = 1 / 2` to the right to obtain `1 / a ≤ ⅟ 2` refine (le_sub_iff_add_le.2 (_ : _ + 2⁻¹ = _ ).le).trans ((sub_le_sub_iff_left 1).2 _), { -- show 2⁻¹ + 2⁻¹ = 1 exact (two_mul _).symm.trans (mul_inv_cancel two_ne_zero) }, { -- take inverses on both sides and use the assumption `2 ≤ a`. exact (one_div a).le.trans (inv_le_inv_of_le zero_lt_two a2) } end /-! ### Results about `is_lub` and `is_glb` -/ -- TODO: Generalize to `linear_ordered_semifield` lemma is_lub.mul_left {s : set α} (ha : 0 ≤ a) (hs : is_lub s b) : is_lub ((λ b, a * b) '' s) (a * b) := begin rcases lt_or_eq_of_le ha with ha | rfl, { exact (order_iso.mul_left₀ _ ha).is_lub_image'.2 hs, }, { simp_rw zero_mul, rw hs.nonempty.image_const, exact is_lub_singleton }, end -- TODO: Generalize to `linear_ordered_semifield` lemma is_lub.mul_right {s : set α} (ha : 0 ≤ a) (hs : is_lub s b) : is_lub ((λ b, b * a) '' s) (b * a) := by simpa [mul_comm] using hs.mul_left ha /-! ### Miscellaneous lemmmas -/ lemma mul_sub_mul_div_mul_neg_iff (hc : c ≠ 0) (hd : d ≠ 0) : (a * d - b * c) / (c * d) < 0 ↔ a / c < b / d := by rw [mul_comm b c, ← div_sub_div _ _ hc hd, sub_lt_zero] lemma mul_sub_mul_div_mul_nonpos_iff (hc : c ≠ 0) (hd : d ≠ 0) : (a * d - b * c) / (c * d) ≤ 0 ↔ a / c ≤ b / d := by rw [mul_comm b c, ← div_sub_div _ _ hc hd, sub_nonpos] alias mul_sub_mul_div_mul_neg_iff ↔ div_lt_div_of_mul_sub_mul_div_neg mul_sub_mul_div_mul_neg alias mul_sub_mul_div_mul_nonpos_iff ↔ div_le_div_of_mul_sub_mul_div_nonpos mul_sub_mul_div_mul_nonpos lemma exists_add_lt_and_pos_of_lt (h : b < a) : ∃ c, b + c < a ∧ 0 < c := ⟨(a - b) / 2, add_sub_div_two_lt h, div_pos (sub_pos_of_lt h) zero_lt_two⟩ lemma le_of_forall_sub_le (h : ∀ ε > 0, b - ε ≤ a) : b ≤ a := begin contrapose! h, simpa only [and_comm ((0 : α) < _), lt_sub_iff_add_lt, gt_iff_lt] using exists_add_lt_and_pos_of_lt h, end lemma mul_self_inj_of_nonneg (a0 : 0 ≤ a) (b0 : 0 ≤ b) : a * a = b * b ↔ a = b := mul_self_eq_mul_self_iff.trans $ or_iff_left_of_imp $ λ h, by { subst a, have : b = 0 := le_antisymm (neg_nonneg.1 a0) b0, rw [this, neg_zero] } lemma min_div_div_right_of_nonpos (hc : c ≤ 0) (a b : α) : min (a / c) (b / c) = (max a b) / c := eq.symm $ antitone.map_max $ λ x y, div_le_div_of_nonpos_of_le hc lemma max_div_div_right_of_nonpos (hc : c ≤ 0) (a b : α) : max (a / c) (b / c) = (min a b) / c := eq.symm $ antitone.map_min $ λ x y, div_le_div_of_nonpos_of_le hc lemma abs_inv (a : α) : |a⁻¹| = (|a|)⁻¹ := map_inv₀ (abs_hom : α →*₀ α) a lemma abs_div (a b : α) : |a / b| = |a| / |b| := map_div₀ (abs_hom : α →*₀ α) a b lemma abs_one_div (a : α) : |1 / a| = 1 / |a| := by rw [abs_div, abs_one] lemma pow_minus_two_nonneg : 0 ≤ a^(-2 : ℤ) := begin simp only [inv_nonneg, zpow_neg], change 0 ≤ a ^ ((2 : ℕ) : ℤ), rw zpow_coe_nat, apply sq_nonneg, end /-- Bernoulli's inequality reformulated to estimate `(n : α)`. -/ lemma nat.cast_le_pow_sub_div_sub (H : 1 < a) (n : ℕ) : (n : α) ≤ (a ^ n - 1) / (a - 1) := (le_div_iff (sub_pos.2 H)).2 $ le_sub_left_of_add_le $ one_add_mul_sub_le_pow ((neg_le_self zero_le_one).trans H.le) _ /-- 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 (H : 1 < a) (n : ℕ) : (n : α) ≤ a ^ n / (a - 1) := (n.cast_le_pow_sub_div_sub H).trans $ div_le_div_of_le (sub_nonneg.2 H.le) (sub_le_self _ zero_le_one) end section canonically_linear_ordered_semifield variables [canonically_linear_ordered_semifield α] [has_sub α] [has_ordered_sub α] lemma tsub_div (a b c : α) : (a - b) / c = a / c - b / c := by simp_rw [div_eq_mul_inv, tsub_mul] end canonically_linear_ordered_semifield
82d97f03fe524c74243f5e7c7fd70d70e0e2be35
94e33a31faa76775069b071adea97e86e218a8ee
/src/data/zmod/quotient.lean
f1cfd89b5585eca6eae98b3c730ce313a809cc6d
[ "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
6,805
lean
/- Copyright (c) 2021 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import algebra.ne_zero import group_theory.group_action.quotient import ring_theory.int.basic /-! # `zmod n` and quotient groups / rings This file relates `zmod n` to the quotient group `quotient_add_group.quotient (add_subgroup.zmultiples n)` and to the quotient ring `(ideal.span {n}).quotient`. ## Main definitions - `zmod.quotient_zmultiples_nat_equiv_zmod` and `zmod.quotient_zmultiples_equiv_zmod`: `zmod n` is the group quotient of `ℤ` by `n ℤ := add_subgroup.zmultiples (n)`, (where `n : ℕ` and `n : ℤ` respectively) - `zmod.quotient_span_nat_equiv_zmod` and `zmod.quotient_span_equiv_zmod`: `zmod n` is the ring quotient of `ℤ` by `n ℤ : ideal.span {n}` (where `n : ℕ` and `n : ℤ` respectively) - `zmod.lift n f` is the map from `zmod n` induced by `f : ℤ →+ A` that maps `n` to `0`. ## Tags zmod, quotient group, quotient ring, ideal quotient -/ open quotient_add_group open zmod variables (n : ℕ) {A R : Type*} [add_group A] [ring R] namespace int /-- `ℤ` modulo multiples of `n : ℕ` is `zmod n`. -/ def quotient_zmultiples_nat_equiv_zmod : ℤ ⧸ add_subgroup.zmultiples (n : ℤ) ≃+ zmod n := (equiv_quotient_of_eq (zmod.ker_int_cast_add_hom _)).symm.trans $ quotient_ker_equiv_of_right_inverse (int.cast_add_hom (zmod n)) coe int_cast_zmod_cast /-- `ℤ` modulo multiples of `a : ℤ` is `zmod a.nat_abs`. -/ def quotient_zmultiples_equiv_zmod (a : ℤ) : ℤ ⧸ add_subgroup.zmultiples a ≃+ zmod a.nat_abs := (equiv_quotient_of_eq (zmultiples_nat_abs a)).symm.trans (quotient_zmultiples_nat_equiv_zmod a.nat_abs) /-- `ℤ` modulo the ideal generated by `n : ℕ` is `zmod n`. -/ def quotient_span_nat_equiv_zmod : ℤ ⧸ ideal.span {↑n} ≃+* zmod n := (ideal.quot_equiv_of_eq (zmod.ker_int_cast_ring_hom _)).symm.trans $ ring_hom.quotient_ker_equiv_of_right_inverse $ show function.right_inverse coe (int.cast_ring_hom (zmod n)), from int_cast_zmod_cast /-- `ℤ` modulo the ideal generated by `a : ℤ` is `zmod a.nat_abs`. -/ def quotient_span_equiv_zmod (a : ℤ) : ℤ ⧸ ideal.span ({a} : set ℤ) ≃+* zmod a.nat_abs := (ideal.quot_equiv_of_eq (span_nat_abs a)).symm.trans (quotient_span_nat_equiv_zmod a.nat_abs) end int namespace add_action open add_subgroup add_monoid_hom add_equiv function variables {α β : Type*} [add_group α] (a : α) [add_action α β] (b : β) /-- The quotient `(ℤ ∙ a) ⧸ (stabilizer b)` is cyclic of order `minimal_period ((+ᵥ) a) b`. -/ noncomputable def zmultiples_quotient_stabilizer_equiv : zmultiples a ⧸ stabilizer (zmultiples a) b ≃+ zmod (minimal_period ((+ᵥ) a) b) := (of_bijective (map _ (stabilizer (zmultiples a) b) (zmultiples_hom (zmultiples a) ⟨a, mem_zmultiples a⟩) (by { rw [zmultiples_le, mem_comap, mem_stabilizer_iff, zmultiples_hom_apply, coe_nat_zsmul, ←vadd_iterate], exact is_periodic_pt_minimal_period ((+ᵥ) a) b })) ⟨by { rw [←ker_eq_bot_iff, eq_bot_iff], refine λ q, induction_on' q (λ n hn, _), rw [mem_bot, eq_zero_iff, int.mem_zmultiples_iff, ←zsmul_vadd_eq_iff_minimal_period_dvd], exact (eq_zero_iff _).mp hn }, λ q, induction_on' q (λ ⟨_, n, rfl⟩, ⟨n, rfl⟩)⟩).symm.trans (int.quotient_zmultiples_nat_equiv_zmod (minimal_period ((+ᵥ) a) b)) lemma zmultiples_quotient_stabilizer_equiv_symm_apply (n : zmod (minimal_period ((+ᵥ) a) b)) : (zmultiples_quotient_stabilizer_equiv a b).symm n = (n : ℤ) • (⟨a, mem_zmultiples a⟩ : zmultiples a) := rfl end add_action namespace mul_action open add_action subgroup add_subgroup function variables {α β : Type*} [group α] (a : α) [mul_action α β] (b : β) local attribute [semireducible] mul_opposite /-- The quotient `(a ^ ℤ) ⧸ (stabilizer b)` is cyclic of order `minimal_period ((•) a) b`. -/ noncomputable def zpowers_quotient_stabilizer_equiv : zpowers a ⧸ stabilizer (zpowers a) b ≃* multiplicative (zmod (minimal_period ((•) a) b)) := let f := zmultiples_quotient_stabilizer_equiv (additive.of_mul a) b in ⟨f.to_fun, f.inv_fun, f.left_inv, f.right_inv, f.map_add'⟩ lemma zpowers_quotient_stabilizer_equiv_symm_apply (n : zmod (minimal_period ((•) a) b)) : (zpowers_quotient_stabilizer_equiv a b).symm n = (⟨a, mem_zpowers a⟩ : zpowers a) ^ (n : ℤ) := rfl /-- The orbit `(a ^ ℤ) • b` is a cycle of order `minimal_period ((•) a) b`. -/ noncomputable def orbit_zpowers_equiv : orbit (zpowers a) b ≃ zmod (minimal_period ((•) a) b) := (orbit_equiv_quotient_stabilizer _ b).trans (zpowers_quotient_stabilizer_equiv a b).to_equiv /-- The orbit `(ℤ • a) +ᵥ b` is a cycle of order `minimal_period ((+ᵥ) a) b`. -/ noncomputable def _root_.add_action.orbit_zmultiples_equiv {α β : Type*} [add_group α] (a : α) [add_action α β] (b : β) : add_action.orbit (zmultiples a) b ≃ zmod (minimal_period ((+ᵥ) a) b) := (add_action.orbit_equiv_quotient_stabilizer (zmultiples a) b).trans (zmultiples_quotient_stabilizer_equiv a b).to_equiv attribute [to_additive orbit_zmultiples_equiv] orbit_zpowers_equiv @[to_additive orbit_zmultiples_equiv_symm_apply] lemma orbit_zpowers_equiv_symm_apply (k : zmod (minimal_period ((•) a) b)) : (orbit_zpowers_equiv a b).symm k = (⟨a, mem_zpowers a⟩ : zpowers a) ^ (k : ℤ) • ⟨b, mem_orbit_self b⟩ := rfl lemma orbit_zpowers_equiv_symm_apply' (k : ℤ) : (orbit_zpowers_equiv a b).symm k = (⟨a, mem_zpowers a⟩ : zpowers a) ^ k • ⟨b, mem_orbit_self b⟩ := begin rw [orbit_zpowers_equiv_symm_apply, zmod.coe_int_cast], exact subtype.ext (zpow_smul_mod_minimal_period _ _ k), end lemma _root_.add_action.orbit_zmultiples_equiv_symm_apply' {α β : Type*} [add_group α] (a : α) [add_action α β] (b : β) (k : ℤ) : (add_action.orbit_zmultiples_equiv a b).symm k = (k • (⟨a, mem_zmultiples a⟩ : zmultiples a)) +ᵥ ⟨b, add_action.mem_orbit_self b⟩ := begin rw [add_action.orbit_zmultiples_equiv_symm_apply, zmod.coe_int_cast], exact subtype.ext (zsmul_vadd_mod_minimal_period _ _ k), end attribute [to_additive orbit_zmultiples_equiv_symm_apply'] orbit_zpowers_equiv_symm_apply' @[to_additive] lemma minimal_period_eq_card [fintype (orbit (zpowers a) b)] : minimal_period ((•) a) b = fintype.card (orbit (zpowers a) b) := by rw [←fintype.of_equiv_card (orbit_zpowers_equiv a b), zmod.card] @[to_additive] instance minimal_period_pos [fintype $ orbit (zpowers a) b] : ne_zero $ minimal_period ((•) a) b := ⟨begin haveI : nonempty (orbit (zpowers a) b) := (orbit_nonempty b).to_subtype, rw minimal_period_eq_card, exact fintype.card_ne_zero, end⟩ end mul_action
e30f7047175024664538128a89036495c2b22b57
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Lean/Elab/Level.lean
e34aa747fbeb2fb2c48a56bc94956e9c80fcdb1c
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
3,340
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.Log import Lean.Parser.Level import Lean.Elab.Exception import Lean.Elab.AutoBound namespace Lean.Elab.Level structure Context where options : Options ref : Syntax autoBoundImplicit : Bool structure State where ngen : NameGenerator mctx : MetavarContext levelNames : List Name abbrev LevelElabM := ReaderT Context (EStateM Exception State) instance : MonadOptions LevelElabM where getOptions := return (← read).options instance : MonadRef LevelElabM where getRef := return (← read).ref withRef ref x := withReader (fun ctx => { ctx with ref := ref }) x instance : AddMessageContext LevelElabM where addMessageContext msg := pure msg instance : MonadNameGenerator LevelElabM where getNGen := return (← get).ngen setNGen ngen := modify fun s => { s with ngen := ngen } def mkFreshLevelMVar : LevelElabM Level := do let mvarId ← mkFreshLMVarId modify fun s => { s with mctx := s.mctx.addLevelMVarDecl mvarId } return mkLevelMVar mvarId register_builtin_option maxUniverseOffset : Nat := { defValue := 32 descr := "maximum universe level offset" } private def checkUniverseOffset [Monad m] [MonadError m] [MonadOptions m] (n : Nat) : m Unit := do let max := maxUniverseOffset.get (← getOptions) unless n <= max do throwError "maximum universe level offset threshold ({max}) has been reached, you can increase the limit using option `set_option maxUniverseOffset <limit>`, but you are probably misusing universe levels since offsets are usually small natural numbers" partial def elabLevel (stx : Syntax) : LevelElabM Level := withRef stx do let kind := stx.getKind if kind == ``Lean.Parser.Level.paren then elabLevel (stx.getArg 1) else if kind == ``Lean.Parser.Level.max then let args := stx.getArg 1 |>.getArgs args[:args.size - 1].foldrM (init := ← elabLevel args.back) fun stx lvl => return mkLevelMax' (← elabLevel stx) lvl else if kind == ``Lean.Parser.Level.imax then let args := stx.getArg 1 |>.getArgs args[:args.size - 1].foldrM (init := ← elabLevel args.back) fun stx lvl => return mkLevelIMax' (← elabLevel stx) lvl else if kind == ``Lean.Parser.Level.hole then mkFreshLevelMVar else if kind == numLitKind then match stx.isNatLit? with | some val => checkUniverseOffset val; return Level.ofNat val | none => throwIllFormedSyntax else if kind == identKind then let paramName := stx.getId unless (← get).levelNames.contains paramName do if (← read).autoBoundImplicit && isValidAutoBoundLevelName paramName (relaxedAutoImplicit.get (← read).options) then modify fun s => { s with levelNames := paramName :: s.levelNames } else throwError "unknown universe level '{paramName}'" return mkLevelParam paramName else if kind == `Lean.Parser.Level.addLit then let lvl ← elabLevel (stx.getArg 0) match stx.getArg 2 |>.isNatLit? with | some val => checkUniverseOffset val; return lvl.addOffset val | none => throwIllFormedSyntax else throwError "unexpected universe level syntax kind" end Lean.Elab.Level
b7160949a7b3e19716d6f4fbe5a226d00dcc5122
0d4c30038160d9c35586ce4dace36fe26a35023b
/src/category_theory/limits/shapes/pullbacks.lean
b71e8858d7ef1b68b1d733975c322fc3ef78b907
[ "Apache-2.0" ]
permissive
b-mehta/mathlib
b0c8ec929ec638447e4262f7071570d23db52e14
ce72cde867feabe5bb908cf9e895acc0e11bf1eb
refs/heads/master
1,599,457,264,781
1,586,969,260,000
1,586,969,260,000
220,672,634
0
0
Apache-2.0
1,583,944,480,000
1,573,317,991,000
Lean
UTF-8
Lean
false
false
26,651
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import data.fintype.basic import category_theory.limits.limits import category_theory.limits.shapes.finite_limits import category_theory.sparse /-! # Pullbacks We define a category `walking_cospan` (resp. `walking_span`), which is the index category for the given data for a pullback (resp. pushout) diagram. Convenience methods `cospan f g` and `span f g` construct functors from the walking (co)span, hitting the given morphisms. We define `pullback f g` and `pushout f g` as limits and colimits of such functors. Typeclasses `has_pullbacks` and `has_pushouts` assert the existence of (co)limits shaped as walking (co)spans. -/ open category_theory namespace category_theory.limits universes v u local attribute [tidy] tactic.case_bash /-- The type of objects for the diagram indexing a pullback. -/ @[derive decidable_eq, derive inhabited] inductive walking_cospan : Type v | left | right | one /-- The type of objects for the diagram indexing a pushout. -/ @[derive decidable_eq, derive inhabited] inductive walking_span : Type v | zero | left | right instance fintype_walking_cospan : fintype walking_cospan := { elems := [walking_cospan.left, walking_cospan.right, walking_cospan.one].to_finset, complete := λ x, by { cases x; simp } } instance fintype_walking_span : fintype walking_span := { elems := [walking_span.zero, walking_span.left, walking_span.right].to_finset, complete := λ x, by { cases x; simp } } namespace walking_cospan /-- The arrows in a pullback diagram. -/ @[derive decidable_eq] inductive hom : walking_cospan → walking_cospan → Type v | inl : hom left one | inr : hom right one | id : Π X : walking_cospan.{v}, hom X X /-- Satisfying the inhabited linter -/ instance hom.inhabited : inhabited (hom left one) := { default := hom.inl } open hom instance fintype_walking_cospan_hom (j j' : walking_cospan) : fintype (hom j j') := { elems := walking_cospan.rec_on j (walking_cospan.rec_on j' [hom.id left].to_finset ∅ [inl].to_finset) (walking_cospan.rec_on j' ∅ [hom.id right].to_finset [inr].to_finset) (walking_cospan.rec_on j' ∅ ∅ [hom.id one].to_finset), complete := by tidy } /-- Composition of morphisms in the category indexing a pullback. -/ def hom.comp : Π (X Y Z : walking_cospan) (f : hom X Y) (g : hom Y Z), hom X Z | _ _ _ (id _) h := h | _ _ _ inl (id one) := inl | _ _ _ inr (id one) := inr . instance category_struct : category_struct walking_cospan := { hom := hom, id := hom.id, comp := hom.comp, } instance (X Y : walking_cospan) : subsingleton (X ⟶ Y) := by tidy -- We make this a @[simp] lemma later; if we do it now there's a mysterious -- failure in `cospan`, below. lemma hom_id (X : walking_cospan.{v}) : hom.id X = 𝟙 X := rfl /-- The walking_cospan is the index diagram for a pullback. -/ instance : small_category.{v} walking_cospan.{v} := sparse_category instance : fin_category.{v} walking_cospan.{v} := { fintype_hom := walking_cospan.fintype_walking_cospan_hom } end walking_cospan namespace walking_span /-- The arrows in a pushout diagram. -/ @[derive decidable_eq] inductive hom : walking_span → walking_span → Type v | fst : hom zero left | snd : hom zero right | id : Π X : walking_span.{v}, hom X X instance hom.inhabited : inhabited (hom zero left) := { default := hom.fst } open hom instance fintype_walking_span_hom (j j' : walking_span) : fintype (hom j j') := { elems := walking_span.rec_on j (walking_span.rec_on j' [hom.id zero].to_finset [fst].to_finset [snd].to_finset) (walking_span.rec_on j' ∅ [hom.id left].to_finset ∅) (walking_span.rec_on j' ∅ ∅ [hom.id right].to_finset), complete := by tidy } /-- Composition of morphisms in the category indexing a pushout. -/ def hom.comp : Π (X Y Z : walking_span) (f : hom X Y) (g : hom Y Z), hom X Z | _ _ _ (id _) h := h | _ _ _ fst (id left) := fst | _ _ _ snd (id right) := snd . instance category_struct : category_struct walking_span := { hom := hom, id := hom.id, comp := hom.comp } instance (X Y : walking_span) : subsingleton (X ⟶ Y) := by tidy -- We make this a @[simp] lemma later; if we do it now there's a mysterious -- failure in `span`, below. lemma hom_id (X : walking_span.{v}) : hom.id X = 𝟙 X := rfl /-- The walking_span is the index diagram for a pushout. -/ instance : small_category.{v} walking_span.{v} := sparse_category instance : fin_category.{v} walking_span.{v} := { fintype_hom := walking_span.fintype_walking_span_hom } end walking_span open walking_span walking_cospan walking_span.hom walking_cospan.hom variables {C : Type u} [𝒞 : category.{v} C] include 𝒞 /-- `cospan f g` is the functor from the walking cospan hitting `f` and `g`. -/ def cospan {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : walking_cospan.{v} ⥤ C := { obj := λ x, match x with | left := X | right := Y | one := Z end, map := λ x y h, match x, y, h with | _, _, (id _) := 𝟙 _ | _, _, inl := f | _, _, inr := g end } /-- `span f g` is the functor from the walking span hitting `f` and `g`. -/ def span {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : walking_span.{v} ⥤ C := { obj := λ x, match x with | zero := X | left := Y | right := Z end, map := λ x y h, match x, y, h with | _, _, (id _) := 𝟙 _ | _, _, fst := f | _, _, snd := g end } @[simp] lemma cospan_left {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : (cospan f g).obj walking_cospan.left = X := rfl @[simp] lemma span_left {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : (span f g).obj walking_span.left = Y := rfl @[simp] lemma cospan_right {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : (cospan f g).obj walking_cospan.right = Y := rfl @[simp] lemma span_right {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : (span f g).obj walking_span.right = Z := rfl @[simp] lemma cospan_one {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : (cospan f g).obj walking_cospan.one = Z := rfl @[simp] lemma span_zero {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : (span f g).obj walking_span.zero = X := rfl @[simp] lemma cospan_map_inl {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : (cospan f g).map walking_cospan.hom.inl = f := rfl @[simp] lemma span_map_fst {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : (span f g).map walking_span.hom.fst = f := rfl @[simp] lemma cospan_map_inr {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : (cospan f g).map walking_cospan.hom.inr = g := rfl @[simp] lemma span_map_snd {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : (span f g).map walking_span.hom.snd = g := rfl lemma cospan_map_id {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) (w : walking_cospan) : (cospan f g).map (walking_cospan.hom.id w) = 𝟙 _ := rfl lemma span_map_id {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) (w : walking_span) : (span f g).map (walking_span.hom.id w) = 𝟙 _ := rfl /-- Every diagram indexing an equalizer is naturally isomorphic (actually, equal) to a `cospan` -/ def diagram_iso_cospan (F : walking_cospan ⥤ C) : F ≅ cospan (F.map inl) (F.map inr) := nat_iso.of_components (λ j, eq_to_iso $ by cases j; tidy) $ by tidy /-- Every diagram indexing a coequalizer naturally isomorphic (actually, equal) to a `span` -/ def diagram_iso_span (F : walking_span ⥤ C) : F ≅ span (F.map fst) (F.map snd) := nat_iso.of_components (λ j, eq_to_iso $ by cases j; tidy) $ by tidy variables {X Y Z : C} attribute [simp] walking_cospan.hom_id walking_span.hom_id /-- A pullback cone is just a cone on the cospan formed by two morphisms `f : X ⟶ Z` and `g : Y ⟶ Z`.-/ abbreviation pullback_cone (f : X ⟶ Z) (g : Y ⟶ Z) := cone (cospan f g) namespace pullback_cone variables {f : X ⟶ Z} {g : Y ⟶ Z} /-- The first projection of a pullback cone. -/ abbreviation fst (t : pullback_cone f g) : t.X ⟶ X := t.π.app left /-- The second projection of a pullback cone. -/ abbreviation snd (t : pullback_cone f g) : t.X ⟶ Y := t.π.app right /-- A pullback cone on `f` and `g` is determined by morphisms `fst : W ⟶ X` and `snd : W ⟶ Y` such that `fst ≫ f = snd ≫ g`. -/ def mk {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : pullback_cone f g := { X := W, π := { app := λ j, walking_cospan.cases_on j fst snd (fst ≫ f), naturality' := λ j j' f, by cases f; obviously } } @[simp] lemma mk_π_app_left {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : (mk fst snd eq).π.app left = fst := rfl @[simp] lemma mk_π_app_right {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : (mk fst snd eq).π.app right = snd := rfl @[simp] lemma mk_π_app_one {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : (mk fst snd eq).π.app one = fst ≫ f := rfl @[reassoc] lemma condition (t : pullback_cone f g) : fst t ≫ f = snd t ≫ g := begin erw [t.w inl, ← t.w inr], refl end /-- To check whether a morphism is equalized by the maps of a pullback cone, it suffices to check it for `fst t` and `snd t` -/ lemma equalizer_ext (t : pullback_cone f g) {W : C} {k l : W ⟶ t.X} (h₀ : k ≫ fst t = l ≫ fst t) (h₁ : k ≫ snd t = l ≫ snd t) : ∀ (j : walking_cospan), k ≫ t.π.app j = l ≫ t.π.app j | left := h₀ | right := h₁ | one := calc k ≫ t.π.app one = k ≫ t.π.app left ≫ (cospan f g).map inl : by rw ←t.w ... = l ≫ t.π.app left ≫ (cospan f g).map inl : by rw [←category.assoc, h₀, category.assoc] ... = l ≫ t.π.app one : by rw t.w lemma is_limit.hom_ext {t : pullback_cone f g} (ht : is_limit t) {W : C} {k l : W ⟶ t.X} (h₀ : k ≫ fst t = l ≫ fst t) (h₁ : k ≫ snd t = l ≫ snd t) : k = l := ht.hom_ext $ equalizer_ext _ h₀ h₁ /-- If `t` is a limit pullback cone over `f` and `g` and `h : W ⟶ X` and `k : W ⟶ Y` are such that `h ≫ f = k ≫ g`, then we have `l : W ⟶ t.X` satisfying `l ≫ fst t = h` and `l ≫ snd t = k`. -/ def is_limit.lift' {t : pullback_cone f g} (ht : is_limit t) {W : C} (h : W ⟶ X) (k : W ⟶ Y) (w : h ≫ f = k ≫ g) : {l : W ⟶ t.X // l ≫ fst t = h ∧ l ≫ snd t = k} := ⟨ht.lift $ pullback_cone.mk _ _ w, ht.fac _ _, ht.fac _ _⟩ /-- This is a slightly more convenient method to verify that a pullback cone is a limit cone. It only asks for a proof of facts that carry any mathematical content -/ def is_limit.mk (t : pullback_cone f g) (lift : Π (s : cone (cospan f g)), s.X ⟶ t.X) (fac_left : ∀ (s : cone (cospan f g)), lift s ≫ t.π.app left = s.π.app left) (fac_right : ∀ (s : cone (cospan f g)), lift s ≫ t.π.app right = s.π.app right) (uniq : ∀ (s : cone (cospan f g)) (m : s.X ⟶ t.X) (w : ∀ j : walking_cospan, m ≫ t.π.app j = s.π.app j), m = lift s) : is_limit t := { lift := lift, fac' := λ s j, walking_cospan.cases_on j (fac_left s) (fac_right s) $ by rw [←t.w inl, ←s.w inl, ←fac_left s, category.assoc], uniq' := uniq } end pullback_cone /-- A pushout cocone is just a cocone on the span formed by two morphisms `f : X ⟶ Y` and `g : X ⟶ Z`.-/ abbreviation pushout_cocone (f : X ⟶ Y) (g : X ⟶ Z) := cocone (span f g) namespace pushout_cocone variables {f : X ⟶ Y} {g : X ⟶ Z} /-- The first inclusion of a pushout cocone. -/ abbreviation inl (t : pushout_cocone f g) : Y ⟶ t.X := t.ι.app left /-- The second inclusion of a pushout cocone. -/ abbreviation inr (t : pushout_cocone f g) : Z ⟶ t.X := t.ι.app right /-- A pushout cocone on `f` and `g` is determined by morphisms `inl : Y ⟶ W` and `inr : Z ⟶ W` such that `f ≫ inl = g ↠ inr`. -/ def mk {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : pushout_cocone f g := { X := W, ι := { app := λ j, walking_span.cases_on j (f ≫ inl) inl inr, naturality' := λ j j' f, by cases f; obviously } } @[simp] lemma mk_ι_app_left {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : (mk inl inr eq).ι.app left = inl := rfl @[simp] lemma mk_ι_app_right {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : (mk inl inr eq).ι.app right = inr := rfl @[simp] lemma mk_ι_app_zero {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : (mk inl inr eq).ι.app zero = f ≫ inl := rfl @[reassoc] lemma condition (t : pushout_cocone f g) : f ≫ (inl t) = g ≫ (inr t) := begin erw [t.w fst, ← t.w snd], refl end /-- To check whether a morphism is coequalized by the maps of a pushout cocone, it suffices to check it for `inl t` and `inr t` -/ lemma coequalizer_ext (t : pushout_cocone f g) {W : C} {k l : t.X ⟶ W} (h₀ : inl t ≫ k = inl t ≫ l) (h₁ : inr t ≫ k = inr t ≫ l) : ∀ (j : walking_span), t.ι.app j ≫ k = t.ι.app j ≫ l | left := h₀ | right := h₁ | zero := calc t.ι.app zero ≫ k = ((span f g).map fst ≫ t.ι.app left) ≫ k : by rw ←t.w ... = ((span f g).map fst ≫ t.ι.app left) ≫ l : by rw [category.assoc, h₀, ←category.assoc] ... = t.ι.app zero ≫ l : by rw t.w lemma is_colimit.hom_ext {t : pushout_cocone f g} (ht : is_colimit t) {W : C} {k l : t.X ⟶ W} (h₀ : inl t ≫ k = inl t ≫ l) (h₁ : inr t ≫ k = inr t ≫ l) : k = l := ht.hom_ext $ coequalizer_ext _ h₀ h₁ /-- If `t` is a colimit pushout cocone over `f` and `g` and `h : Y ⟶ W` and `k : Z ⟶ W` are morphisms satisfying `f ≫ h = g ≫ k`, then we have a factorization `l : t.X ⟶ W` such that `inl t ≫ l = h` and `inr t ≫ l = k`. -/ def is_colimit.desc' {t : pushout_cocone f g} (ht : is_colimit t) {W : C} (h : Y ⟶ W) (k : Z ⟶ W) (w : f ≫ h = g ≫ k) : {l : t.X ⟶ W // inl t ≫ l = h ∧ inr t ≫ l = k } := ⟨ht.desc $ pushout_cocone.mk _ _ w, ht.fac _ _, ht.fac _ _⟩ /-- This is a slightly more convenient method to verify that a pushout cocone is a colimit cocone. It only asks for a proof of facts that carry any mathematical content -/ def is_colimit.mk (t : pushout_cocone f g) (desc : Π (s : cocone (span f g)), t.X ⟶ s.X) (fac_left : ∀ (s : cocone (span f g)), t.ι.app left ≫ desc s = s.ι.app left) (fac_right : ∀ (s : cocone (span f g)), t.ι.app right ≫ desc s = s.ι.app right) (uniq : ∀ (s : cocone (span f g)) (m : t.X ⟶ s.X) (w : ∀ j : walking_span, t.ι.app j ≫ m = s.ι.app j), m = desc s) : is_colimit t := { desc := desc, fac' := λ s j, walking_span.cases_on j (by rw [←s.w fst, ←t.w fst, category.assoc, fac_left s]) (fac_left s) (fac_right s), uniq' := uniq } end pushout_cocone /-- This is a helper construction that can be useful when verifying that a category has all pullbacks. Given `F : walking_cospan ⥤ C`, which is really the same as `cospan (F.map inl) (F.map inr)`, and a pullback cone on `F.map inl` and `F.map inr`, we get a cone on `F`. If you're thinking about using this, have a look at `has_pullbacks_of_has_limit_cospan`, which you may find to be an easier way of achieving your goal. -/ def cone.of_pullback_cone {F : walking_cospan.{v} ⥤ C} (t : pullback_cone (F.map inl) (F.map inr)) : cone F := { X := t.X, π := { app := λ X, t.π.app X ≫ eq_to_hom (by tidy), naturality' := λ j j' g, begin cases j; cases j'; cases g; dsimp; simp, exact (t.w inl).symm, exact (t.w inr).symm end } }. @[simp] lemma cone.of_pullback_cone_π {F : walking_cospan.{v} ⥤ C} (t : pullback_cone (F.map inl) (F.map inr)) (j) : (cone.of_pullback_cone t).π.app j = t.π.app j ≫ eq_to_hom (by tidy) := rfl /-- This is a helper construction that can be useful when verifying that a category has all pushout. Given `F : walking_span ⥤ C`, which is really the same as `span (F.map fst) (F.mal snd)`, and a pushout cocone on `F.map fst` and `F.map snd`, we get a cocone on `F`. If you're thinking about using this, have a look at `has_pushouts_of_has_colimit_span`, which you may find to be an easiery way of achieving your goal. -/ def cocone.of_pushout_cocone {F : walking_span.{v} ⥤ C} (t : pushout_cocone (F.map fst) (F.map snd)) : cocone F := { X := t.X, ι := { app := λ X, eq_to_hom (by tidy) ≫ t.ι.app X, naturality' := λ j j' g, begin cases j; cases j'; cases g; dsimp; simp, exact t.w fst, exact t.w snd end } }. @[simp] lemma cocone.of_pushout_cocone_ι {F : walking_span.{v} ⥤ C} (t : pushout_cocone (F.map fst) (F.map snd)) (j) : (cocone.of_pushout_cocone t).ι.app j = eq_to_hom (by tidy) ≫ t.ι.app j := rfl /-- Given `F : walking_cospan ⥤ C`, which is really the same as `cospan (F.map inl) (F.map inr)`, and a cone on `F`, we get a pullback cone on `F.map inl` and `F.map inr`. -/ def pullback_cone.of_cone {F : walking_cospan.{v} ⥤ C} (t : cone F) : pullback_cone (F.map inl) (F.map inr) := { X := t.X, π := { app := λ j, t.π.app j ≫ eq_to_hom (by tidy) } } @[simp] lemma pullback_cone.of_cone_π {F : walking_cospan.{v} ⥤ C} (t : cone F) (j) : (pullback_cone.of_cone t).π.app j = t.π.app j ≫ eq_to_hom (by tidy) := rfl /-- Given `F : walking_span ⥤ C`, which is really the same as `span (F.map fst) (F.map snd)`, and a cocone on `F`, we get a pushout cocone on `F.map fst` and `F.map snd`. -/ def pushout_cocone.of_cocone {F : walking_span.{v} ⥤ C} (t : cocone F) : pushout_cocone (F.map fst) (F.map snd) := { X := t.X, ι := { app := λ j, eq_to_hom (by tidy) ≫ t.ι.app j } } @[simp] lemma pushout_cocone.of_cocone_ι {F : walking_span.{v} ⥤ C} (t : cocone F) (j) : (pushout_cocone.of_cocone t).ι.app j = eq_to_hom (by tidy) ≫ t.ι.app j := rfl /-- `pullback f g` computes the pullback of a pair of morphisms with the same target. -/ abbreviation pullback {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) [has_limit (cospan f g)] := limit (cospan f g) /-- `pushout f g` computes the pushout of a pair of morphisms with the same source. -/ abbreviation pushout {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) [has_colimit (span f g)] := colimit (span f g) /-- The first projection of the pullback of `f` and `g`. -/ abbreviation pullback.fst {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] : pullback f g ⟶ X := limit.π (cospan f g) walking_cospan.left /-- The second projection of the pullback of `f` and `g`. -/ abbreviation pullback.snd {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] : pullback f g ⟶ Y := limit.π (cospan f g) walking_cospan.right /-- The first inclusion into the pushout of `f` and `g`. -/ abbreviation pushout.inl {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_colimit (span f g)] : Y ⟶ pushout f g := colimit.ι (span f g) walking_span.left /-- The second inclusion into the pushout of `f` and `g`. -/ abbreviation pushout.inr {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_colimit (span f g)] : Z ⟶ pushout f g := colimit.ι (span f g) walking_span.right /-- A pair of morphisms `h : W ⟶ X` and `k : W ⟶ Y` satisfying `h ≫ f = k ≫ g` induces a morphism `pullback.lift : W ⟶ pullback f g`. -/ abbreviation pullback.lift {W X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] (h : W ⟶ X) (k : W ⟶ Y) (w : h ≫ f = k ≫ g) : W ⟶ pullback f g := limit.lift _ (pullback_cone.mk h k w) /-- A pair of morphisms `h : Y ⟶ W` and `k : Z ⟶ W` satisfying `f ≫ h = g ≫ k` induces a morphism `pushout.desc : pushout f g ⟶ W`. -/ abbreviation pushout.desc {W X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_colimit (span f g)] (h : Y ⟶ W) (k : Z ⟶ W) (w : f ≫ h = g ≫ k) : pushout f g ⟶ W := colimit.desc _ (pushout_cocone.mk h k w) @[simp, reassoc] lemma pullback.lift_fst {W X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] (h : W ⟶ X) (k : W ⟶ Y) (w : h ≫ f = k ≫ g) : pullback.lift h k w ≫ pullback.fst = h := limit.lift_π _ _ @[simp, reassoc] lemma pullback.lift_snd {W X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] (h : W ⟶ X) (k : W ⟶ Y) (w : h ≫ f = k ≫ g) : pullback.lift h k w ≫ pullback.snd = k := limit.lift_π _ _ @[simp, reassoc] lemma pushout.inl_desc {W X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_colimit (span f g)] (h : Y ⟶ W) (k : Z ⟶ W) (w : f ≫ h = g ≫ k) : pushout.inl ≫ pushout.desc h k w = h := colimit.ι_desc _ _ @[simp, reassoc] lemma pushout.inr_desc {W X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_colimit (span f g)] (h : Y ⟶ W) (k : Z ⟶ W) (w : f ≫ h = g ≫ k) : pushout.inr ≫ pushout.desc h k w = k := colimit.ι_desc _ _ /-- A pair of morphisms `h : W ⟶ X` and `k : W ⟶ Y` satisfying `h ≫ f = k ≫ g` induces a morphism `l : W ⟶ pullback f g` such that `l ≫ pullback.fst = h` and `l ≫ pullback.snd = k`. -/ def pullback.lift' {W X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] (h : W ⟶ X) (k : W ⟶ Y) (w : h ≫ f = k ≫ g) : {l : W ⟶ pullback f g // l ≫ pullback.fst = h ∧ l ≫ pullback.snd = k} := ⟨pullback.lift h k w, pullback.lift_fst _ _ _, pullback.lift_snd _ _ _⟩ /-- A pair of morphisms `h : Y ⟶ W` and `k : Z ⟶ W` satisfying `f ≫ h = g ≫ k` induces a morphism `l : pushout f g ⟶ W` such that `pushout.inl ≫ l = h` and `pushout.inr ≫ l = k`. -/ def pullback.desc' {W X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_colimit (span f g)] (h : Y ⟶ W) (k : Z ⟶ W) (w : f ≫ h = g ≫ k) : {l : pushout f g ⟶ W // pushout.inl ≫ l = h ∧ pushout.inr ≫ l = k} := ⟨pushout.desc h k w, pushout.inl_desc _ _ _, pushout.inr_desc _ _ _⟩ lemma pullback.condition {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] : (pullback.fst : pullback f g ⟶ X) ≫ f = pullback.snd ≫ g := (limit.w (cospan f g) walking_cospan.hom.inl).trans (limit.w (cospan f g) walking_cospan.hom.inr).symm lemma pushout.condition {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_colimit (span f g)] : f ≫ (pushout.inl : Y ⟶ pushout f g) = g ≫ pushout.inr := (colimit.w (span f g) walking_span.hom.fst).trans (colimit.w (span f g) walking_span.hom.snd).symm /-- Two morphisms into a pullback are equal if their compositions with the pullback morphisms are equal -/ @[ext] lemma pullback.hom_ext {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] {W : C} {k l : W ⟶ pullback f g} (h₀ : k ≫ pullback.fst = l ≫ pullback.fst) (h₁ : k ≫ pullback.snd = l ≫ pullback.snd) : k = l := limit.hom_ext $ pullback_cone.equalizer_ext _ h₀ h₁ /-- The pullback of a monomorphism is a monomorphism -/ instance pullback.fst_of_mono {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] [mono g] : mono (pullback.fst : pullback f g ⟶ X) := ⟨λ W u v h, pullback.hom_ext h $ (cancel_mono g).1 $ calc (u ≫ pullback.snd) ≫ g = u ≫ pullback.fst ≫ f : by rw [category.assoc, pullback.condition] ... = v ≫ pullback.fst ≫ f : by rw [←category.assoc, h, category.assoc] ... = (v ≫ pullback.snd) ≫ g : by rw [pullback.condition, ←category.assoc]⟩ /-- The pullback of a monomorphism is a monomorphism -/ instance pullback.snd_of_mono {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] [mono f] : mono (pullback.snd : pullback f g ⟶ Y) := ⟨λ W u v h, pullback.hom_ext ((cancel_mono f).1 $ calc (u ≫ pullback.fst) ≫ f = u ≫ pullback.snd ≫ g : by rw [category.assoc, pullback.condition] ... = v ≫ pullback.snd ≫ g : by rw [←category.assoc, h, category.assoc] ... = (v ≫ pullback.fst) ≫ f : by rw [←pullback.condition, ←category.assoc]) h⟩ /-- Two morphisms out of a pushout are equal if their compositions with the pushout morphisms are equal -/ @[ext] lemma pushout.hom_ext {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_colimit (span f g)] {W : C} {k l : pushout f g ⟶ W} (h₀ : pushout.inl ≫ k = pushout.inl ≫ l) (h₁ : pushout.inr ≫ k = pushout.inr ≫ l) : k = l := colimit.hom_ext $ pushout_cocone.coequalizer_ext _ h₀ h₁ /-- The pushout of an epimorphism is an epimorphism -/ instance pushout.inl_of_epi {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_colimit (span f g)] [epi g] : epi (pushout.inl : Y ⟶ pushout f g) := ⟨λ W u v h, pushout.hom_ext h $ (cancel_epi g).1 $ calc g ≫ pushout.inr ≫ u = (f ≫ pushout.inl) ≫ u : by rw [←category.assoc, ←pushout.condition] ... = f ≫ pushout.inl ≫ v : by rw [category.assoc, h] ... = g ≫ pushout.inr ≫ v : by rw [←category.assoc, pushout.condition, category.assoc]⟩ /-- The pushout of an epimorphism is an epimorphism -/ instance pushout.inr_of_epi {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_colimit (span f g)] [epi f] : epi (pushout.inr : Z ⟶ pushout f g) := ⟨λ W u v h, pushout.hom_ext ((cancel_epi f).1 $ calc f ≫ pushout.inl ≫ u = (g ≫ pushout.inr) ≫ u : by rw [←category.assoc, pushout.condition] ... = g ≫ pushout.inr ≫ v : by rw [category.assoc, h] ... = f ≫ pushout.inl ≫ v : by rw [←category.assoc, ←pushout.condition, category.assoc]) h⟩ variables (C) /-- `has_pullbacks` represents a choice of pullback for every pair of morphisms -/ class has_pullbacks := (has_limits_of_shape : has_limits_of_shape.{v} walking_cospan C) /-- `has_pushouts` represents a choice of pushout for every pair of morphisms -/ class has_pushouts := (has_colimits_of_shape : has_colimits_of_shape.{v} walking_span C) attribute [instance] has_pullbacks.has_limits_of_shape has_pushouts.has_colimits_of_shape /-- Pullbacks are finite limits, so if `C` has all finite limits, it also has all pullbacks -/ def has_pullbacks_of_has_finite_limits [has_finite_limits.{v} C] : has_pullbacks.{v} C := { has_limits_of_shape := infer_instance } /-- Pushouts are finite colimits, so if `C` has all finite colimits, it also has all pushouts -/ def has_pushouts_of_has_finite_colimits [has_finite_colimits.{v} C] : has_pushouts.{v} C := { has_colimits_of_shape := infer_instance } /-- If `C` has all limits of diagrams `cospan f g`, then it has all pullbacks -/ def has_pullbacks_of_has_limit_cospan [Π {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z}, has_limit (cospan f g)] : has_pullbacks.{v} C := { has_limits_of_shape := { has_limit := λ F, has_limit_of_iso (diagram_iso_cospan F).symm } } /-- If `C` has all colimits of diagrams `span f g`, then it has all pushouts -/ def has_pushouts_of_has_colimit_span [Π {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z}, has_colimit (span f g)] : has_pushouts.{v} C := { has_colimits_of_shape := { has_colimit := λ F, has_colimit_of_iso (diagram_iso_span F) } } end category_theory.limits
694ff4bbe7cd21b5db8f69904e909740f67d2733
bb31430994044506fa42fd667e2d556327e18dfe
/src/topology/separation.lean
3e55ac79f65342c5fb9761865b31570e91e4b582
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
93,415
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 topology.subset_properties import topology.connected import topology.nhds_set import topology.inseparable /-! # Separation properties of topological spaces. This file defines the predicate `separated_nhds`, and common separation axioms (under the Kolmogorov classification). ## Main definitions * `separated_nhds`: Two `set`s are separated by neighbourhoods if they are contained in disjoint open sets. * `t0_space`: A T₀/Kolmogorov space is a space where, for every two points `x ≠ y`, there is an open set that contains one, but not the other. * `t1_space`: A T₁/Fréchet space is a space where every singleton set is closed. This is equivalent to, for every pair `x ≠ y`, there existing an open set containing `x` but not `y` (`t1_space_iff_exists_open` shows that these conditions are equivalent.) * `t2_space`: A T₂/Hausdorff space is a space where, for every two points `x ≠ y`, there is two disjoint open sets, one containing `x`, and the other `y`. * `t2_5_space`: A T₂.₅/Urysohn space is a space where, for every two points `x ≠ y`, there is two open sets, one containing `x`, and the other `y`, whose closures are disjoint. * `t3_space`: A T₃ space, is one where given any closed `C` and `x ∉ C`, there is disjoint open sets containing `x` and `C` respectively. In `mathlib`, T₃ implies T₂.₅. * `normal_space`: A T₄ space (sometimes referred to as normal, but authors vary on whether this includes T₂; `mathlib` does), is one where given two disjoint closed sets, we can find two open sets that separate them. In `mathlib`, T₄ implies T₃. * `t5_space`: A T₅ space, also known as a *completely normal Hausdorff space* ## Main results ### T₀ spaces * `is_closed.exists_closed_singleton` Given a closed set `S` in a compact T₀ space, there is some `x ∈ S` such that `{x}` is closed. * `exists_open_singleton_of_open_finset` Given an open `finset` `S` in a T₀ space, there is some `x ∈ S` such that `{x}` is open. ### T₁ spaces * `is_closed_map_const`: The constant map is a closed map. * `discrete_of_t1_of_finite`: A finite T₁ space must have the discrete topology. ### T₂ spaces * `t2_iff_nhds`: A space is T₂ iff the neighbourhoods of distinct points generate the bottom filter. * `t2_iff_is_closed_diagonal`: A space is T₂ iff the `diagonal` of `α` (that is, the set of all points of the form `(a, a) : α × α`) is closed under the product topology. * `finset_disjoint_finset_opens_of_t2`: Any two disjoint finsets are `separated_nhds`. * Most topological constructions preserve Hausdorffness; these results are part of the typeclass inference system (e.g. `embedding.t2_space`) * `set.eq_on.closure`: If two functions are equal on some set `s`, they are equal on its closure. * `is_compact.is_closed`: All compact sets are closed. * `locally_compact_of_compact_nhds`: If every point has a compact neighbourhood, then the space is locally compact. * `totally_separated_space_of_t1_of_basis_clopen`: If `α` has a clopen basis, then it is a `totally_separated_space`. * `loc_compact_t2_tot_disc_iff_tot_sep`: A locally compact T₂ space is totally disconnected iff it is totally separated. If the space is also compact: * `normal_of_compact_t2`: A compact T₂ space is a `normal_space`. * `connected_components_eq_Inter_clopen`: The connected component of a point is the intersection of all its clopen neighbourhoods. * `compact_t2_tot_disc_iff_tot_sep`: Being a `totally_disconnected_space` is equivalent to being a `totally_separated_space`. * `connected_components.t2`: `connected_components α` is T₂ for `α` T₂ and compact. ### T₃ spaces * `disjoint_nested_nhds`: Given two points `x ≠ y`, we can find neighbourhoods `x ∈ V₁ ⊆ U₁` and `y ∈ V₂ ⊆ U₂`, with the `Vₖ` closed and the `Uₖ` open, such that the `Uₖ` are disjoint. ## References https://en.wikipedia.org/wiki/Separation_axiom -/ open function set filter topological_space open_locale topological_space filter classical universes u v variables {α : Type u} {β : Type v} [topological_space α] section separation /-- `separated_nhds` is a predicate on pairs of sub`set`s of a topological space. It holds if the two sub`set`s are contained in disjoint open sets. -/ def separated_nhds : set α → set α → Prop := λ (s t : set α), ∃ U V : (set α), (is_open U) ∧ is_open V ∧ (s ⊆ U) ∧ (t ⊆ V) ∧ disjoint U V lemma separated_nhds_iff_disjoint {s t : set α} : separated_nhds s t ↔ disjoint (𝓝ˢ s) (𝓝ˢ t) := by simp only [(has_basis_nhds_set s).disjoint_iff (has_basis_nhds_set t), separated_nhds, exists_prop, ← exists_and_distrib_left, and.assoc, and.comm, and.left_comm] namespace separated_nhds variables {s s₁ s₂ t t₁ t₂ u : set α} @[symm] lemma symm : separated_nhds s t → separated_nhds t s := λ ⟨U, V, oU, oV, aU, bV, UV⟩, ⟨V, U, oV, oU, bV, aU, disjoint.symm UV⟩ lemma comm (s t : set α) : separated_nhds s t ↔ separated_nhds t s := ⟨symm, symm⟩ lemma preimage [topological_space β] {f : α → β} {s t : set β} (h : separated_nhds s t) (hf : continuous f) : separated_nhds (f ⁻¹' s) (f ⁻¹' t) := let ⟨U, V, oU, oV, sU, tV, UV⟩ := h in ⟨f ⁻¹' U, f ⁻¹' V, oU.preimage hf, oV.preimage hf, preimage_mono sU, preimage_mono tV, UV.preimage f⟩ protected lemma disjoint (h : separated_nhds s t) : disjoint s t := let ⟨U, V, hU, hV, hsU, htV, hd⟩ := h in hd.mono hsU htV lemma disjoint_closure_left (h : separated_nhds s t) : disjoint (closure s) t := let ⟨U, V, hU, hV, hsU, htV, hd⟩ := h in (hd.closure_left hV).mono (closure_mono hsU) htV lemma disjoint_closure_right (h : separated_nhds s t) : disjoint s (closure t) := h.symm.disjoint_closure_left.symm lemma empty_right (s : set α) : separated_nhds s ∅ := ⟨_, _, is_open_univ, is_open_empty, λ a h, mem_univ a, λ a h, by cases h, disjoint_empty _⟩ lemma empty_left (s : set α) : separated_nhds ∅ s := (empty_right _).symm lemma mono (h : separated_nhds s₂ t₂) (hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) : separated_nhds s₁ t₁ := let ⟨U, V, hU, hV, hsU, htV, hd⟩ := h in ⟨U, V, hU, hV, hs.trans hsU, ht.trans htV, hd⟩ lemma union_left : separated_nhds s u → separated_nhds t u → separated_nhds (s ∪ t) u := by simpa only [separated_nhds_iff_disjoint, nhds_set_union, disjoint_sup_left] using and.intro lemma union_right (ht : separated_nhds s t) (hu : separated_nhds s u) : separated_nhds s (t ∪ u) := (ht.symm.union_left hu.symm).symm end separated_nhds /-- A T₀ space, also known as a Kolmogorov space, is a topological space such that for every pair `x ≠ y`, there is an open set containing one but not the other. We formulate the definition in terms of the `inseparable` relation. -/ class t0_space (α : Type u) [topological_space α] : Prop := (t0 : ∀ ⦃x y : α⦄, inseparable x y → x = y) lemma t0_space_iff_inseparable (α : Type u) [topological_space α] : t0_space α ↔ ∀ (x y : α), inseparable x y → x = y := ⟨λ ⟨h⟩, h, λ h, ⟨h⟩⟩ lemma t0_space_iff_not_inseparable (α : Type u) [topological_space α] : t0_space α ↔ ∀ (x y : α), x ≠ y → ¬inseparable x y := by simp only [t0_space_iff_inseparable, ne.def, not_imp_not] lemma inseparable.eq [t0_space α] {x y : α} (h : inseparable x y) : x = y := t0_space.t0 h lemma t0_space_iff_nhds_injective (α : Type u) [topological_space α] : t0_space α ↔ injective (𝓝 : α → filter α) := t0_space_iff_inseparable α lemma nhds_injective [t0_space α] : injective (𝓝 : α → filter α) := (t0_space_iff_nhds_injective α).1 ‹_› lemma inseparable_iff_eq [t0_space α] {x y : α} : inseparable x y ↔ x = y := nhds_injective.eq_iff @[simp] lemma nhds_eq_nhds_iff [t0_space α] {a b : α} : 𝓝 a = 𝓝 b ↔ a = b := nhds_injective.eq_iff @[simp] lemma inseparable_eq_eq [t0_space α] : inseparable = @eq α := funext₂ $ λ x y, propext inseparable_iff_eq lemma t0_space_iff_exists_is_open_xor_mem (α : Type u) [topological_space α] : t0_space α ↔ ∀ x y, x ≠ y → ∃ U:set α, is_open U ∧ (xor (x ∈ U) (y ∈ U)) := by simp only [t0_space_iff_not_inseparable, xor_iff_not_iff, not_forall, exists_prop, inseparable_iff_forall_open] lemma exists_is_open_xor_mem [t0_space α] {x y : α} (h : x ≠ y) : ∃ U : set α, is_open U ∧ xor (x ∈ U) (y ∈ U) := (t0_space_iff_exists_is_open_xor_mem α).1 ‹_› x y h /-- Specialization forms a partial order on a t0 topological space. -/ def specialization_order (α : Type*) [topological_space α] [t0_space α] : partial_order α := { .. specialization_preorder α, .. partial_order.lift (order_dual.to_dual ∘ 𝓝) nhds_injective } instance : t0_space (separation_quotient α) := ⟨λ x' y', quotient.induction_on₂' x' y' $ λ x y h, separation_quotient.mk_eq_mk.2 $ separation_quotient.inducing_mk.inseparable_iff.1 h⟩ theorem minimal_nonempty_closed_subsingleton [t0_space α] {s : set α} (hs : is_closed s) (hmin : ∀ t ⊆ s, t.nonempty → is_closed t → t = s) : s.subsingleton := begin refine λ x hx y hy, of_not_not (λ hxy, _), rcases exists_is_open_xor_mem hxy with ⟨U, hUo, hU⟩, wlog h : x ∈ U ∧ y ∉ U := hU using [x y, y x], cases h with hxU hyU, have : s \ U = s := hmin (s \ U) (diff_subset _ _) ⟨y, hy, hyU⟩ (hs.sdiff hUo), exact (this.symm.subset hx).2 hxU end theorem minimal_nonempty_closed_eq_singleton [t0_space α] {s : set α} (hs : is_closed s) (hne : s.nonempty) (hmin : ∀ t ⊆ s, t.nonempty → is_closed t → t = s) : ∃ x, s = {x} := exists_eq_singleton_iff_nonempty_subsingleton.2 ⟨hne, minimal_nonempty_closed_subsingleton hs hmin⟩ /-- Given a closed set `S` in a compact T₀ space, there is some `x ∈ S` such that `{x}` is closed. -/ theorem is_closed.exists_closed_singleton {α : Type*} [topological_space α] [t0_space α] [compact_space α] {S : set α} (hS : is_closed S) (hne : S.nonempty) : ∃ (x : α), x ∈ S ∧ is_closed ({x} : set α) := begin obtain ⟨V, Vsub, Vne, Vcls, hV⟩ := hS.exists_minimal_nonempty_closed_subset hne, rcases minimal_nonempty_closed_eq_singleton Vcls Vne hV with ⟨x, rfl⟩, exact ⟨x, Vsub (mem_singleton x), Vcls⟩ end theorem minimal_nonempty_open_subsingleton [t0_space α] {s : set α} (hs : is_open s) (hmin : ∀ t ⊆ s, t.nonempty → is_open t → t = s) : s.subsingleton := begin refine λ x hx y hy, of_not_not (λ hxy, _), rcases exists_is_open_xor_mem hxy with ⟨U, hUo, hU⟩, wlog h : x ∈ U ∧ y ∉ U := hU using [x y, y x], cases h with hxU hyU, have : s ∩ U = s := hmin (s ∩ U) (inter_subset_left _ _) ⟨x, hx, hxU⟩ (hs.inter hUo), exact hyU (this.symm.subset hy).2 end theorem minimal_nonempty_open_eq_singleton [t0_space α] {s : set α} (hs : is_open s) (hne : s.nonempty) (hmin : ∀ t ⊆ s, t.nonempty → is_open t → t = s) : ∃ x, s = {x} := exists_eq_singleton_iff_nonempty_subsingleton.2 ⟨hne, minimal_nonempty_open_subsingleton hs hmin⟩ /-- Given an open finite set `S` in a T₀ space, there is some `x ∈ S` such that `{x}` is open. -/ theorem exists_open_singleton_of_open_finite [t0_space α] {s : set α} (hfin : s.finite) (hne : s.nonempty) (ho : is_open s) : ∃ x ∈ s, is_open ({x} : set α) := begin lift s to finset α using hfin, induction s using finset.strong_induction_on with s ihs, rcases em (∃ t ⊂ s, t.nonempty ∧ is_open (t : set α)) with ⟨t, hts, htne, hto⟩|ht, { rcases ihs t hts htne hto with ⟨x, hxt, hxo⟩, exact ⟨x, hts.1 hxt, hxo⟩ }, { rcases minimal_nonempty_open_eq_singleton ho hne _ with ⟨x, hx⟩, { exact ⟨x, hx.symm ▸ rfl, hx ▸ ho⟩ }, refine λ t hts htne hto, of_not_not (λ hts', ht _), lift t to finset α using s.finite_to_set.subset hts, exact ⟨t, ssubset_iff_subset_ne.2 ⟨hts, mt finset.coe_inj.2 hts'⟩, htne, hto⟩ } end theorem exists_open_singleton_of_fintype [t0_space α] [finite α] [nonempty α] : ∃ x : α, is_open ({x} : set α) := let ⟨x, _, h⟩ := exists_open_singleton_of_open_finite (set.to_finite _) univ_nonempty is_open_univ in ⟨x, h⟩ lemma t0_space_of_injective_of_continuous [topological_space β] {f : α → β} (hf : function.injective f) (hf' : continuous f) [t0_space β] : t0_space α := ⟨λ x y h, hf $ (h.map hf').eq⟩ protected lemma embedding.t0_space [topological_space β] [t0_space β] {f : α → β} (hf : embedding f) : t0_space α := t0_space_of_injective_of_continuous hf.inj hf.continuous instance subtype.t0_space [t0_space α] {p : α → Prop} : t0_space (subtype p) := embedding_subtype_coe.t0_space theorem t0_space_iff_or_not_mem_closure (α : Type u) [topological_space α] : t0_space α ↔ (∀ a b : α, a ≠ b → (a ∉ closure ({b} : set α) ∨ b ∉ closure ({a} : set α))) := by simp only [t0_space_iff_not_inseparable, inseparable_iff_mem_closure, not_and_distrib] instance [topological_space β] [t0_space α] [t0_space β] : t0_space (α × β) := ⟨λ x y h, prod.ext (h.map continuous_fst).eq (h.map continuous_snd).eq⟩ instance {ι : Type*} {π : ι → Type*} [Π i, topological_space (π i)] [Π i, t0_space (π i)] : t0_space (Π i, π i) := ⟨λ x y h, funext $ λ i, (h.map (continuous_apply i)).eq⟩ lemma t0_space.of_cover (h : ∀ x y, inseparable x y → ∃ s : set α, x ∈ s ∧ y ∈ s ∧ t0_space s) : t0_space α := begin refine ⟨λ x y hxy, _⟩, rcases h x y hxy with ⟨s, hxs, hys, hs⟩, resetI, lift x to s using hxs, lift y to s using hys, rw ← subtype_inseparable_iff at hxy, exact congr_arg coe hxy.eq end lemma t0_space.of_open_cover (h : ∀ x, ∃ s : set α, x ∈ s ∧ is_open s ∧ t0_space s) : t0_space α := t0_space.of_cover $ λ x y hxy, let ⟨s, hxs, hso, hs⟩ := h x in ⟨s, hxs, (hxy.mem_open_iff hso).1 hxs, hs⟩ /-- A T₁ space, also known as a Fréchet space, is a topological space where every singleton set is closed. Equivalently, for every pair `x ≠ y`, there is an open set containing `x` and not `y`. -/ class t1_space (α : Type u) [topological_space α] : Prop := (t1 : ∀x, is_closed ({x} : set α)) lemma is_closed_singleton [t1_space α] {x : α} : is_closed ({x} : set α) := t1_space.t1 x lemma is_open_compl_singleton [t1_space α] {x : α} : is_open ({x}ᶜ : set α) := is_closed_singleton.is_open_compl lemma is_open_ne [t1_space α] {x : α} : is_open {y | y ≠ x} := is_open_compl_singleton @[to_additive] lemma continuous.is_open_mul_support [t1_space α] [has_one α] [topological_space β] {f : β → α} (hf : continuous f) : is_open (mul_support f) := is_open_ne.preimage hf lemma ne.nhds_within_compl_singleton [t1_space α] {x y : α} (h : x ≠ y) : 𝓝[{y}ᶜ] x = 𝓝 x := is_open_ne.nhds_within_eq h lemma ne.nhds_within_diff_singleton [t1_space α] {x y : α} (h : x ≠ y) (s : set α) : 𝓝[s \ {y}] x = 𝓝[s] x := begin rw [diff_eq, inter_comm, nhds_within_inter_of_mem], exact mem_nhds_within_of_mem_nhds (is_open_ne.mem_nhds h) end lemma is_open_set_of_eventually_nhds_within [t1_space α] {p : α → Prop} : is_open {x | ∀ᶠ y in 𝓝[≠] x, p y} := begin refine is_open_iff_mem_nhds.mpr (λ a ha, _), filter_upwards [eventually_nhds_nhds_within.mpr ha] with b hb, by_cases a = b, { subst h, exact hb }, { rw (ne.symm h).nhds_within_compl_singleton at hb, exact hb.filter_mono nhds_within_le_nhds } end protected lemma set.finite.is_closed [t1_space α] {s : set α} (hs : set.finite s) : is_closed s := begin rw ← bUnion_of_singleton s, exact is_closed_bUnion hs (λ i hi, is_closed_singleton) end lemma topological_space.is_topological_basis.exists_mem_of_ne [t1_space α] {b : set (set α)} (hb : is_topological_basis b) {x y : α} (h : x ≠ y) : ∃ a ∈ b, x ∈ a ∧ y ∉ a := begin rcases hb.is_open_iff.1 is_open_ne x h with ⟨a, ab, xa, ha⟩, exact ⟨a, ab, xa, λ h, ha h rfl⟩, end lemma filter.coclosed_compact_le_cofinite [t1_space α] : filter.coclosed_compact α ≤ filter.cofinite := λ s hs, compl_compl s ▸ hs.is_compact.compl_mem_coclosed_compact_of_is_closed hs.is_closed variable (α) /-- In a `t1_space`, relatively compact sets form a bornology. Its cobounded filter is `filter.coclosed_compact`. See also `bornology.in_compact` the bornology of sets contained in a compact set. -/ def bornology.relatively_compact [t1_space α] : bornology α := { cobounded := filter.coclosed_compact α, le_cofinite := filter.coclosed_compact_le_cofinite } variable {α} lemma bornology.relatively_compact.is_bounded_iff [t1_space α] {s : set α} : @bornology.is_bounded _ (bornology.relatively_compact α) s ↔ is_compact (closure s) := begin change sᶜ ∈ filter.coclosed_compact α ↔ _, rw filter.mem_coclosed_compact, split, { rintros ⟨t, ht₁, ht₂, hst⟩, rw compl_subset_compl at hst, exact is_compact_of_is_closed_subset ht₂ is_closed_closure (closure_minimal hst ht₁) }, { intros h, exact ⟨closure s, is_closed_closure, h, compl_subset_compl.mpr subset_closure⟩ } end protected lemma finset.is_closed [t1_space α] (s : finset α) : is_closed (s : set α) := s.finite_to_set.is_closed lemma t1_space_tfae (α : Type u) [topological_space α] : tfae [t1_space α, ∀ x, is_closed ({x} : set α), ∀ x, is_open ({x}ᶜ : set α), continuous (@cofinite_topology.of α), ∀ ⦃x y : α⦄, x ≠ y → {y}ᶜ ∈ 𝓝 x, ∀ ⦃x y : α⦄, x ≠ y → ∃ s ∈ 𝓝 x, y ∉ s, ∀ ⦃x y : α⦄, x ≠ y → ∃ (U : set α) (hU : is_open U), x ∈ U ∧ y ∉ U, ∀ ⦃x y : α⦄, x ≠ y → disjoint (𝓝 x) (pure y), ∀ ⦃x y : α⦄, x ≠ y → disjoint (pure x) (𝓝 y), ∀ ⦃x y : α⦄, x ⤳ y → x = y] := begin tfae_have : 1 ↔ 2, from ⟨λ h, h.1, λ h, ⟨h⟩⟩, tfae_have : 2 ↔ 3, by simp only [is_open_compl_iff], tfae_have : 5 ↔ 3, { refine forall_swap.trans _, simp only [is_open_iff_mem_nhds, mem_compl_iff, mem_singleton_iff] }, tfae_have : 5 ↔ 6, by simp only [← subset_compl_singleton_iff, exists_mem_subset_iff], tfae_have : 5 ↔ 7, by simp only [(nhds_basis_opens _).mem_iff, subset_compl_singleton_iff, exists_prop, and.assoc, and.left_comm], tfae_have : 5 ↔ 8, by simp only [← principal_singleton, disjoint_principal_right], tfae_have : 8 ↔ 9, from forall_swap.trans (by simp only [disjoint.comm, ne_comm]), tfae_have : 1 → 4, { simp only [continuous_def, cofinite_topology.is_open_iff'], rintro H s (rfl|hs), exacts [is_open_empty, compl_compl s ▸ (@set.finite.is_closed _ _ H _ hs).is_open_compl] }, tfae_have : 4 → 2, from λ h x, (cofinite_topology.is_closed_iff.2 $ or.inr (finite_singleton _)).preimage h, tfae_have : 2 ↔ 10, { simp only [← closure_subset_iff_is_closed, specializes_iff_mem_closure, subset_def, mem_singleton_iff, eq_comm] }, tfae_finish end lemma t1_space_iff_continuous_cofinite_of {α : Type*} [topological_space α] : t1_space α ↔ continuous (@cofinite_topology.of α) := (t1_space_tfae α).out 0 3 lemma cofinite_topology.continuous_of [t1_space α] : continuous (@cofinite_topology.of α) := t1_space_iff_continuous_cofinite_of.mp ‹_› lemma t1_space_iff_exists_open : t1_space α ↔ ∀ (x y), x ≠ y → (∃ (U : set α) (hU : is_open U), x ∈ U ∧ y ∉ U) := (t1_space_tfae α).out 0 6 lemma t1_space_iff_disjoint_pure_nhds : t1_space α ↔ ∀ ⦃x y : α⦄, x ≠ y → disjoint (pure x) (𝓝 y) := (t1_space_tfae α).out 0 8 lemma t1_space_iff_disjoint_nhds_pure : t1_space α ↔ ∀ ⦃x y : α⦄, x ≠ y → disjoint (𝓝 x) (pure y) := (t1_space_tfae α).out 0 7 lemma t1_space_iff_specializes_imp_eq : t1_space α ↔ ∀ ⦃x y : α⦄, x ⤳ y → x = y := (t1_space_tfae α).out 0 9 lemma disjoint_pure_nhds [t1_space α] {x y : α} (h : x ≠ y) : disjoint (pure x) (𝓝 y) := t1_space_iff_disjoint_pure_nhds.mp ‹_› h lemma disjoint_nhds_pure [t1_space α] {x y : α} (h : x ≠ y) : disjoint (𝓝 x) (pure y) := t1_space_iff_disjoint_nhds_pure.mp ‹_› h lemma specializes.eq [t1_space α] {x y : α} (h : x ⤳ y) : x = y := t1_space_iff_specializes_imp_eq.1 ‹_› h lemma specializes_iff_eq [t1_space α] {x y : α} : x ⤳ y ↔ x = y := ⟨specializes.eq, λ h, h ▸ specializes_rfl⟩ @[simp] lemma specializes_eq_eq [t1_space α] : (⤳) = @eq α := funext₂ $ λ x y, propext specializes_iff_eq @[simp] lemma pure_le_nhds_iff [t1_space α] {a b : α} : pure a ≤ 𝓝 b ↔ a = b := specializes_iff_pure.symm.trans specializes_iff_eq @[simp] lemma nhds_le_nhds_iff [t1_space α] {a b : α} : 𝓝 a ≤ 𝓝 b ↔ a = b := specializes_iff_eq instance {α : Type*} : t1_space (cofinite_topology α) := t1_space_iff_continuous_cofinite_of.mpr continuous_id lemma t1_space_antitone {α : Type*} : antitone (@t1_space α) := begin simp only [antitone, t1_space_iff_continuous_cofinite_of, continuous_iff_le_induced], exact λ t₁ t₂ h, h.trans end lemma continuous_within_at_update_of_ne [t1_space α] [decidable_eq α] [topological_space β] {f : α → β} {s : set α} {x y : α} {z : β} (hne : y ≠ x) : continuous_within_at (function.update f x z) s y ↔ continuous_within_at f s y := eventually_eq.congr_continuous_within_at (mem_nhds_within_of_mem_nhds $ mem_of_superset (is_open_ne.mem_nhds hne) $ λ y' hy', function.update_noteq hy' _ _) (function.update_noteq hne _ _) lemma continuous_at_update_of_ne [t1_space α] [decidable_eq α] [topological_space β] {f : α → β} {x y : α} {z : β} (hne : y ≠ x) : continuous_at (function.update f x z) y ↔ continuous_at f y := by simp only [← continuous_within_at_univ, continuous_within_at_update_of_ne hne] lemma continuous_on_update_iff [t1_space α] [decidable_eq α] [topological_space β] {f : α → β} {s : set α} {x : α} {y : β} : continuous_on (function.update f x y) s ↔ continuous_on f (s \ {x}) ∧ (x ∈ s → tendsto f (𝓝[s \ {x}] x) (𝓝 y)) := begin rw [continuous_on, ← and_forall_ne x, and_comm], refine and_congr ⟨λ H z hz, _, λ H z hzx hzs, _⟩ (forall_congr $ λ hxs, _), { specialize H z hz.2 hz.1, rw continuous_within_at_update_of_ne hz.2 at H, exact H.mono (diff_subset _ _) }, { rw continuous_within_at_update_of_ne hzx, refine (H z ⟨hzs, hzx⟩).mono_of_mem (inter_mem_nhds_within _ _), exact is_open_ne.mem_nhds hzx }, { exact continuous_within_at_update_same } end lemma t1_space_of_injective_of_continuous [topological_space β] {f : α → β} (hf : function.injective f) (hf' : continuous f) [t1_space β] : t1_space α := t1_space_iff_specializes_imp_eq.2 $ λ x y h, hf (h.map hf').eq protected lemma embedding.t1_space [topological_space β] [t1_space β] {f : α → β} (hf : embedding f) : t1_space α := t1_space_of_injective_of_continuous hf.inj hf.continuous instance subtype.t1_space {α : Type u} [topological_space α] [t1_space α] {p : α → Prop} : t1_space (subtype p) := embedding_subtype_coe.t1_space instance [topological_space β] [t1_space α] [t1_space β] : t1_space (α × β) := ⟨λ ⟨a, b⟩, @singleton_prod_singleton _ _ a b ▸ is_closed_singleton.prod is_closed_singleton⟩ instance {ι : Type*} {π : ι → Type*} [Π i, topological_space (π i)] [Π i, t1_space (π i)] : t1_space (Π i, π i) := ⟨λ f, univ_pi_singleton f ▸ is_closed_set_pi (λ i hi, is_closed_singleton)⟩ @[priority 100] -- see Note [lower instance priority] instance t1_space.t0_space [t1_space α] : t0_space α := ⟨λ x y h, h.specializes.eq⟩ @[simp] lemma compl_singleton_mem_nhds_iff [t1_space α] {x y : α} : {x}ᶜ ∈ 𝓝 y ↔ y ≠ x := is_open_compl_singleton.mem_nhds_iff lemma compl_singleton_mem_nhds [t1_space α] {x y : α} (h : y ≠ x) : {x}ᶜ ∈ 𝓝 y := compl_singleton_mem_nhds_iff.mpr h @[simp] lemma closure_singleton [t1_space α] {a : α} : closure ({a} : set α) = {a} := is_closed_singleton.closure_eq lemma set.subsingleton.closure [t1_space α] {s : set α} (hs : s.subsingleton) : (closure s).subsingleton := hs.induction_on (by simp) $ λ x, by simp @[simp] lemma subsingleton_closure [t1_space α] {s : set α} : (closure s).subsingleton ↔ s.subsingleton := ⟨λ h, h.anti subset_closure, λ h, h.closure⟩ lemma is_closed_map_const {α β} [topological_space α] [topological_space β] [t1_space β] {y : β} : is_closed_map (function.const α y) := is_closed_map.of_nonempty $ λ s hs h2s, by simp_rw [h2s.image_const, is_closed_singleton] lemma nhds_within_insert_of_ne [t1_space α] {x y : α} {s : set α} (hxy : x ≠ y) : 𝓝[insert y s] x = 𝓝[s] x := begin refine le_antisymm (λ t ht, _) (nhds_within_mono x $ subset_insert y s), obtain ⟨o, ho, hxo, host⟩ := mem_nhds_within.mp ht, refine mem_nhds_within.mpr ⟨o \ {y}, ho.sdiff is_closed_singleton, ⟨hxo, hxy⟩, _⟩, rw [inter_insert_of_not_mem $ not_mem_diff_of_mem (mem_singleton y)], exact (inter_subset_inter (diff_subset _ _) subset.rfl).trans host end /-- If `t` is a subset of `s`, except for one point, then `insert x s` is a neighborhood of `x` within `t`. -/ lemma insert_mem_nhds_within_of_subset_insert [t1_space α] {x y : α} {s t : set α} (hu : t ⊆ insert y s) : insert x s ∈ 𝓝[t] x := begin rcases eq_or_ne x y with rfl|h, { exact mem_of_superset self_mem_nhds_within hu }, refine nhds_within_mono x hu _, rw [nhds_within_insert_of_ne h], exact mem_of_superset self_mem_nhds_within (subset_insert x s) end lemma bInter_basis_nhds [t1_space α] {ι : Sort*} {p : ι → Prop} {s : ι → set α} {x : α} (h : (𝓝 x).has_basis p s) : (⋂ i (h : p i), s i) = {x} := begin simp only [eq_singleton_iff_unique_mem, mem_Inter], refine ⟨λ i hi, mem_of_mem_nhds $ h.mem_of_mem hi, λ y hy, _⟩, contrapose! hy, rcases h.mem_iff.1 (compl_singleton_mem_nhds hy.symm) with ⟨i, hi, hsub⟩, exact ⟨i, hi, λ h, hsub h rfl⟩ end @[simp] lemma compl_singleton_mem_nhds_set_iff [t1_space α] {x : α} {s : set α} : {x}ᶜ ∈ 𝓝ˢ s ↔ x ∉ s := by rwa [is_open_compl_singleton.mem_nhds_set, subset_compl_singleton_iff] @[simp] lemma nhds_set_le_iff [t1_space α] {s t : set α} : 𝓝ˢ s ≤ 𝓝ˢ t ↔ s ⊆ t := begin refine ⟨_, λ h, monotone_nhds_set h⟩, simp_rw [filter.le_def], intros h x hx, specialize h {x}ᶜ, simp_rw [compl_singleton_mem_nhds_set_iff] at h, by_contra hxt, exact h hxt hx, end @[simp] lemma nhds_set_inj_iff [t1_space α] {s t : set α} : 𝓝ˢ s = 𝓝ˢ t ↔ s = t := by { simp_rw [le_antisymm_iff], exact and_congr nhds_set_le_iff nhds_set_le_iff } lemma injective_nhds_set [t1_space α] : function.injective (𝓝ˢ : set α → filter α) := λ s t hst, nhds_set_inj_iff.mp hst lemma strict_mono_nhds_set [t1_space α] : strict_mono (𝓝ˢ : set α → filter α) := monotone_nhds_set.strict_mono_of_injective injective_nhds_set @[simp] lemma nhds_le_nhds_set_iff [t1_space α] {s : set α} {x : α} : 𝓝 x ≤ 𝓝ˢ s ↔ x ∈ s := by rw [← nhds_set_singleton, nhds_set_le_iff, singleton_subset_iff] /-- Removing a non-isolated point from a dense set, one still obtains a dense set. -/ lemma dense.diff_singleton [t1_space α] {s : set α} (hs : dense s) (x : α) [ne_bot (𝓝[≠] x)] : dense (s \ {x}) := hs.inter_of_open_right (dense_compl_singleton x) is_open_compl_singleton /-- Removing a finset from a dense set in a space without isolated points, one still obtains a dense set. -/ lemma dense.diff_finset [t1_space α] [∀ (x : α), ne_bot (𝓝[≠] x)] {s : set α} (hs : dense s) (t : finset α) : dense (s \ t) := begin induction t using finset.induction_on with x s hxs ih hd, { simpa using hs }, { rw [finset.coe_insert, ← union_singleton, ← diff_diff], exact ih.diff_singleton _, } end /-- Removing a finite set from a dense set in a space without isolated points, one still obtains a dense set. -/ lemma dense.diff_finite [t1_space α] [∀ (x : α), ne_bot (𝓝[≠] x)] {s : set α} (hs : dense s) {t : set α} (ht : t.finite) : dense (s \ t) := begin convert hs.diff_finset ht.to_finset, exact (finite.coe_to_finset _).symm, end /-- If a function to a `t1_space` tends to some limit `b` at some point `a`, then necessarily `b = f a`. -/ lemma eq_of_tendsto_nhds [topological_space β] [t1_space β] {f : α → β} {a : α} {b : β} (h : tendsto f (𝓝 a) (𝓝 b)) : f a = b := by_contra $ assume (hfa : f a ≠ b), have fact₁ : {f a}ᶜ ∈ 𝓝 b := compl_singleton_mem_nhds hfa.symm, have fact₂ : tendsto f (pure a) (𝓝 b) := h.comp (tendsto_id'.2 $ pure_le_nhds a), fact₂ fact₁ (eq.refl $ f a) lemma filter.tendsto.eventually_ne [topological_space β] [t1_space β] {α : Type*} {g : α → β} {l : filter α} {b₁ b₂ : β} (hg : tendsto g l (𝓝 b₁)) (hb : b₁ ≠ b₂) : ∀ᶠ z in l, g z ≠ b₂ := hg.eventually (is_open_compl_singleton.eventually_mem hb) lemma continuous_at.eventually_ne [topological_space β] [t1_space β] {g : α → β} {a : α} {b : β} (hg1 : continuous_at g a) (hg2 : g a ≠ b) : ∀ᶠ z in 𝓝 a, g z ≠ b := hg1.tendsto.eventually_ne hg2 /-- To prove a function to a `t1_space` is continuous at some point `a`, it suffices to prove that `f` admits *some* limit at `a`. -/ lemma continuous_at_of_tendsto_nhds [topological_space β] [t1_space β] {f : α → β} {a : α} {b : β} (h : tendsto f (𝓝 a) (𝓝 b)) : continuous_at f a := show tendsto f (𝓝 a) (𝓝 $ f a), by rwa eq_of_tendsto_nhds h @[simp] lemma tendsto_const_nhds_iff [t1_space α] {l : filter β} [ne_bot l] {c d : α} : tendsto (λ x, c) l (𝓝 d) ↔ c = d := by simp_rw [tendsto, filter.map_const, pure_le_nhds_iff] /-- A point with a finite neighborhood has to be isolated. -/ lemma is_open_singleton_of_finite_mem_nhds {α : Type*} [topological_space α] [t1_space α] (x : α) {s : set α} (hs : s ∈ 𝓝 x) (hsf : s.finite) : is_open ({x} : set α) := begin have A : {x} ⊆ s, by simp only [singleton_subset_iff, mem_of_mem_nhds hs], have B : is_closed (s \ {x}) := (hsf.subset (diff_subset _ _)).is_closed, have C : (s \ {x})ᶜ ∈ 𝓝 x, from B.is_open_compl.mem_nhds (λ h, h.2 rfl), have D : {x} ∈ 𝓝 x, by simpa only [← diff_eq, diff_diff_cancel_left A] using inter_mem hs C, rwa [← mem_interior_iff_mem_nhds, ← singleton_subset_iff, subset_interior_iff_is_open] at D end /-- If the punctured neighborhoods of a point form a nontrivial filter, then any neighborhood is infinite. -/ lemma infinite_of_mem_nhds {α} [topological_space α] [t1_space α] (x : α) [hx : ne_bot (𝓝[≠] x)] {s : set α} (hs : s ∈ 𝓝 x) : set.infinite s := begin refine λ hsf, hx.1 _, rw [← is_open_singleton_iff_punctured_nhds], exact is_open_singleton_of_finite_mem_nhds x hs hsf end lemma discrete_of_t1_of_finite {X : Type*} [topological_space X] [t1_space X] [finite X] : discrete_topology X := begin apply singletons_open_iff_discrete.mp, intros x, rw [← is_closed_compl_iff], exact (set.to_finite _).is_closed end lemma preconnected_space.trivial_of_discrete [preconnected_space α] [discrete_topology α] : subsingleton α := begin rw ←not_nontrivial_iff_subsingleton, rintro ⟨x, y, hxy⟩, rw [ne.def, ←mem_singleton_iff, (is_clopen_discrete _).eq_univ $ singleton_nonempty y] at hxy, exact hxy (mem_univ x) end lemma is_preconnected.infinite_of_nontrivial [t1_space α] {s : set α} (h : is_preconnected s) (hs : s.nontrivial) : s.infinite := begin refine mt (λ hf, (subsingleton_coe s).mp _) (not_subsingleton_iff.mpr hs), haveI := @discrete_of_t1_of_finite s _ _ hf.to_subtype, exact @preconnected_space.trivial_of_discrete _ _ (subtype.preconnected_space h) _ end lemma connected_space.infinite [connected_space α] [nontrivial α] [t1_space α] : infinite α := infinite_univ_iff.mp $ is_preconnected_univ.infinite_of_nontrivial nontrivial_univ lemma singleton_mem_nhds_within_of_mem_discrete {s : set α} [discrete_topology s] {x : α} (hx : x ∈ s) : {x} ∈ 𝓝[s] x := begin have : ({⟨x, hx⟩} : set s) ∈ 𝓝 (⟨x, hx⟩ : s), by simp [nhds_discrete], simpa only [nhds_within_eq_map_subtype_coe hx, image_singleton] using @image_mem_map _ _ _ (coe : s → α) _ this end /-- The neighbourhoods filter of `x` within `s`, under the discrete topology, is equal to the pure `x` filter (which is the principal filter at the singleton `{x}`.) -/ lemma nhds_within_of_mem_discrete {s : set α} [discrete_topology s] {x : α} (hx : x ∈ s) : 𝓝[s] x = pure x := le_antisymm (le_pure_iff.2 $ singleton_mem_nhds_within_of_mem_discrete hx) (pure_le_nhds_within hx) lemma filter.has_basis.exists_inter_eq_singleton_of_mem_discrete {ι : Type*} {p : ι → Prop} {t : ι → set α} {s : set α} [discrete_topology s] {x : α} (hb : (𝓝 x).has_basis p t) (hx : x ∈ s) : ∃ i (hi : p i), t i ∩ s = {x} := begin rcases (nhds_within_has_basis hb s).mem_iff.1 (singleton_mem_nhds_within_of_mem_discrete hx) with ⟨i, hi, hix⟩, exact ⟨i, hi, subset.antisymm hix $ singleton_subset_iff.2 ⟨mem_of_mem_nhds $ hb.mem_of_mem hi, hx⟩⟩ end /-- A point `x` in a discrete subset `s` of a topological space admits a neighbourhood that only meets `s` at `x`. -/ lemma nhds_inter_eq_singleton_of_mem_discrete {s : set α} [discrete_topology s] {x : α} (hx : x ∈ s) : ∃ U ∈ 𝓝 x, U ∩ s = {x} := by simpa using (𝓝 x).basis_sets.exists_inter_eq_singleton_of_mem_discrete hx /-- For point `x` in a discrete subset `s` of a topological space, there is a set `U` such that 1. `U` is a punctured neighborhood of `x` (ie. `U ∪ {x}` is a neighbourhood of `x`), 2. `U` is disjoint from `s`. -/ lemma disjoint_nhds_within_of_mem_discrete {s : set α} [discrete_topology s] {x : α} (hx : x ∈ s) : ∃ U ∈ 𝓝[≠] x, disjoint U s := let ⟨V, h, h'⟩ := nhds_inter_eq_singleton_of_mem_discrete hx in ⟨{x}ᶜ ∩ V, inter_mem_nhds_within _ h, (disjoint_iff_inter_eq_empty.mpr (by { rw [inter_assoc, h', compl_inter_self] }))⟩ /-- Let `X` be a topological space and let `s, t ⊆ X` be two subsets. If there is an inclusion `t ⊆ s`, then the topological space structure on `t` induced by `X` is the same as the one obtained by the induced topological space structure on `s`. -/ lemma topological_space.subset_trans {X : Type*} [tX : topological_space X] {s t : set X} (ts : t ⊆ s) : (subtype.topological_space : topological_space t) = (subtype.topological_space : topological_space s).induced (set.inclusion ts) := begin change tX.induced ((coe : s → X) ∘ (set.inclusion ts)) = topological_space.induced (set.inclusion ts) (tX.induced _), rw ← induced_compose, end /-- The topology pulled-back under an inclusion `f : X → Y` from the discrete topology (`⊥`) is the discrete topology. This version does not assume the choice of a topology on either the source `X` nor the target `Y` of the inclusion `f`. -/ lemma induced_bot {X Y : Type*} {f : X → Y} (hf : function.injective f) : topological_space.induced f ⊥ = ⊥ := eq_of_nhds_eq_nhds (by simp [nhds_induced, ← set.image_singleton, hf.preimage_image, nhds_bot]) /-- The topology induced under an inclusion `f : X → Y` from the discrete topological space `Y` is the discrete topology on `X`. -/ lemma discrete_topology_induced {X Y : Type*} [tY : topological_space Y] [discrete_topology Y] {f : X → Y} (hf : function.injective f) : @discrete_topology X (topological_space.induced f tY) := by apply discrete_topology.mk; by rw [discrete_topology.eq_bot Y, induced_bot hf] lemma embedding.discrete_topology {X Y : Type*} [topological_space X] [tY : topological_space Y] [discrete_topology Y] {f : X → Y} (hf : embedding f) : discrete_topology X := ⟨by rw [hf.induced, discrete_topology.eq_bot Y, induced_bot hf.inj]⟩ /-- Let `s, t ⊆ X` be two subsets of a topological space `X`. If `t ⊆ s` and the topology induced by `X`on `s` is discrete, then also the topology induces on `t` is discrete. -/ lemma discrete_topology.of_subset {X : Type*} [topological_space X] {s t : set X} (ds : discrete_topology s) (ts : t ⊆ s) : discrete_topology t := begin rw [topological_space.subset_trans ts, ds.eq_bot], exact {eq_bot := induced_bot (set.inclusion_injective ts)} end /-- A T₂ space, also known as a Hausdorff space, is one in which for every `x ≠ y` there exists disjoint open sets around `x` and `y`. This is the most widely used of the separation axioms. -/ @[mk_iff] class t2_space (α : Type u) [topological_space α] : Prop := (t2 : ∀ x y, x ≠ y → ∃ u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ disjoint u v) /-- Two different points can be separated by open sets. -/ lemma t2_separation [t2_space α] {x y : α} (h : x ≠ y) : ∃ u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ disjoint u v := t2_space.t2 x y h lemma t2_space_iff_disjoint_nhds : t2_space α ↔ ∀ x y : α, x ≠ y → disjoint (𝓝 x) (𝓝 y) := begin refine (t2_space_iff α).trans (forall₃_congr $ λ x y hne, _), simp only [(nhds_basis_opens x).disjoint_iff (nhds_basis_opens y), exists_prop, ← exists_and_distrib_left, and.assoc, and_comm, and.left_comm] end @[simp] lemma disjoint_nhds_nhds [t2_space α] {x y : α} : disjoint (𝓝 x) (𝓝 y) ↔ x ≠ y := ⟨λ hd he, by simpa [he, nhds_ne_bot.ne] using hd, t2_space_iff_disjoint_nhds.mp ‹_› x y⟩ lemma pairwise_disjoint_nhds [t2_space α] : pairwise (disjoint on (𝓝 : α → filter α)) := λ x y, disjoint_nhds_nhds.2 protected lemma set.pairwise_disjoint_nhds [t2_space α] (s : set α) : s.pairwise_disjoint 𝓝 := pairwise_disjoint_nhds.set_pairwise s /-- Points of a finite set can be separated by open sets from each other. -/ lemma set.finite.t2_separation [t2_space α] {s : set α} (hs : s.finite) : ∃ U : α → set α, (∀ x, x ∈ U x ∧ is_open (U x)) ∧ s.pairwise_disjoint U := s.pairwise_disjoint_nhds.exists_mem_filter_basis hs nhds_basis_opens lemma is_open_set_of_disjoint_nhds_nhds : is_open {p : α × α | disjoint (𝓝 p.1) (𝓝 p.2)} := begin simp only [is_open_iff_mem_nhds, prod.forall, mem_set_of_eq], intros x y h, obtain ⟨U, hU, V, hV, hd⟩ := ((nhds_basis_opens x).disjoint_iff (nhds_basis_opens y)).mp h, exact mem_nhds_prod_iff.mpr ⟨U, hU.2.mem_nhds hU.1, V, hV.2.mem_nhds hV.1, λ ⟨x', y'⟩ ⟨hx', hy'⟩, disjoint_of_disjoint_of_mem hd (hU.2.mem_nhds hx') (hV.2.mem_nhds hy')⟩ end @[priority 100] -- see Note [lower instance priority] instance t2_space.t1_space [t2_space α] : t1_space α := t1_space_iff_disjoint_pure_nhds.mpr $ λ x y hne, (disjoint_nhds_nhds.2 hne).mono_left $ pure_le_nhds _ /-- A space is T₂ iff the neighbourhoods of distinct points generate the bottom filter. -/ lemma t2_iff_nhds : t2_space α ↔ ∀ {x y : α}, ne_bot (𝓝 x ⊓ 𝓝 y) → x = y := by simp only [t2_space_iff_disjoint_nhds, disjoint_iff, ne_bot_iff, ne.def, not_imp_comm] lemma eq_of_nhds_ne_bot [t2_space α] {x y : α} (h : ne_bot (𝓝 x ⊓ 𝓝 y)) : x = y := t2_iff_nhds.mp ‹_› h lemma t2_space_iff_nhds : t2_space α ↔ ∀ {x y : α}, x ≠ y → ∃ (U ∈ 𝓝 x) (V ∈ 𝓝 y), disjoint U V := by simp only [t2_space_iff_disjoint_nhds, filter.disjoint_iff] lemma t2_separation_nhds [t2_space α] {x y : α} (h : x ≠ y) : ∃ u v, u ∈ 𝓝 x ∧ v ∈ 𝓝 y ∧ disjoint u v := let ⟨u, v, open_u, open_v, x_in, y_in, huv⟩ := t2_separation h in ⟨u, v, open_u.mem_nhds x_in, open_v.mem_nhds y_in, huv⟩ lemma t2_separation_compact_nhds [locally_compact_space α] [t2_space α] {x y : α} (h : x ≠ y) : ∃ u v, u ∈ 𝓝 x ∧ v ∈ 𝓝 y ∧ is_compact u ∧ is_compact v ∧ disjoint u v := by simpa only [exists_prop, ← exists_and_distrib_left, and_comm, and.assoc, and.left_comm] using ((compact_basis_nhds x).disjoint_iff (compact_basis_nhds y)).1 (disjoint_nhds_nhds.2 h) lemma t2_iff_ultrafilter : t2_space α ↔ ∀ {x y : α} (f : ultrafilter α), ↑f ≤ 𝓝 x → ↑f ≤ 𝓝 y → x = y := t2_iff_nhds.trans $ by simp only [←exists_ultrafilter_iff, and_imp, le_inf_iff, exists_imp_distrib] lemma t2_iff_is_closed_diagonal : t2_space α ↔ is_closed (diagonal α) := by simp only [t2_space_iff_disjoint_nhds, ← is_open_compl_iff, is_open_iff_mem_nhds, prod.forall, nhds_prod_eq, compl_diagonal_mem_prod, mem_compl_iff, mem_diagonal_iff] lemma is_closed_diagonal [t2_space α] : is_closed (diagonal α) := t2_iff_is_closed_diagonal.mp ‹_› section separated open separated_nhds finset lemma finset_disjoint_finset_opens_of_t2 [t2_space α] : ∀ (s t : finset α), disjoint s t → separated_nhds (s : set α) t := begin refine induction_on_union _ (λ a b hi d, (hi d.symm).symm) (λ a d, empty_right a) (λ a b ab, _) _, { obtain ⟨U, V, oU, oV, aU, bV, UV⟩ := t2_separation (finset.disjoint_singleton.1 ab), refine ⟨U, V, oU, oV, _, _, UV⟩; exact singleton_subset_set_iff.mpr ‹_› }, { intros a b c ac bc d, apply_mod_cast union_left (ac (disjoint_of_subset_left (a.subset_union_left b) d)) (bc _), exact disjoint_of_subset_left (a.subset_union_right b) d }, end lemma point_disjoint_finset_opens_of_t2 [t2_space α] {x : α} {s : finset α} (h : x ∉ s) : separated_nhds ({x} : set α) s := by exact_mod_cast finset_disjoint_finset_opens_of_t2 {x} s (finset.disjoint_singleton_left.mpr h) end separated lemma tendsto_nhds_unique [t2_space α] {f : β → α} {l : filter β} {a b : α} [ne_bot l] (ha : tendsto f l (𝓝 a)) (hb : tendsto f l (𝓝 b)) : a = b := eq_of_nhds_ne_bot $ ne_bot_of_le $ le_inf ha hb lemma tendsto_nhds_unique' [t2_space α] {f : β → α} {l : filter β} {a b : α} (hl : ne_bot l) (ha : tendsto f l (𝓝 a)) (hb : tendsto f l (𝓝 b)) : a = b := eq_of_nhds_ne_bot $ ne_bot_of_le $ le_inf ha hb lemma tendsto_nhds_unique_of_eventually_eq [t2_space α] {f g : β → α} {l : filter β} {a b : α} [ne_bot l] (ha : tendsto f l (𝓝 a)) (hb : tendsto g l (𝓝 b)) (hfg : f =ᶠ[l] g) : a = b := tendsto_nhds_unique (ha.congr' hfg) hb lemma tendsto_nhds_unique_of_frequently_eq [t2_space α] {f g : β → α} {l : filter β} {a b : α} (ha : tendsto f l (𝓝 a)) (hb : tendsto g l (𝓝 b)) (hfg : ∃ᶠ x in l, f x = g x) : a = b := have ∃ᶠ z : α × α in 𝓝 (a, b), z.1 = z.2 := (ha.prod_mk_nhds hb).frequently hfg, not_not.1 $ λ hne, this (is_closed_diagonal.is_open_compl.mem_nhds hne) /-- A T₂.₅ space, also known as a Urysohn space, is a topological space where for every pair `x ≠ y`, there are two open sets, with the intersection of closures empty, one containing `x` and the other `y` . -/ class t2_5_space (α : Type u) [topological_space α]: Prop := (t2_5 : ∀ ⦃x y : α⦄ (h : x ≠ y), disjoint ((𝓝 x).lift' closure) ((𝓝 y).lift' closure)) @[simp] lemma disjoint_lift'_closure_nhds [t2_5_space α] {x y : α} : disjoint ((𝓝 x).lift' closure) ((𝓝 y).lift' closure) ↔ x ≠ y := ⟨λ h hxy, by simpa [hxy, nhds_ne_bot.ne] using h, λ h, t2_5_space.t2_5 h⟩ @[priority 100] -- see Note [lower instance priority] instance t2_5_space.t2_space [t2_5_space α] : t2_space α := t2_space_iff_disjoint_nhds.2 $ λ x y hne, (disjoint_lift'_closure_nhds.2 hne).mono (le_lift'_closure _) (le_lift'_closure _) lemma exists_nhds_disjoint_closure [t2_5_space α] {x y : α} (h : x ≠ y) : ∃ (s ∈ 𝓝 x) (t ∈ 𝓝 y), disjoint (closure s) (closure t) := ((𝓝 x).basis_sets.lift'_closure.disjoint_iff (𝓝 y).basis_sets.lift'_closure).1 $ disjoint_lift'_closure_nhds.2 h lemma exists_open_nhds_disjoint_closure [t2_5_space α] {x y : α} (h : x ≠ y) : ∃ u : set α, x ∈ u ∧ is_open u ∧ ∃ v : set α, y ∈ v ∧ is_open v ∧ disjoint (closure u) (closure v) := by simpa only [exists_prop, and.assoc] using ((nhds_basis_opens x).lift'_closure.disjoint_iff (nhds_basis_opens y).lift'_closure).1 (disjoint_lift'_closure_nhds.2 h) section lim variables [t2_space α] {f : filter α} /-! ### Properties of `Lim` and `lim` In this section we use explicit `nonempty α` instances for `Lim` and `lim`. This way the lemmas are useful without a `nonempty α` instance. -/ lemma Lim_eq {a : α} [ne_bot f] (h : f ≤ 𝓝 a) : @Lim _ _ ⟨a⟩ f = a := tendsto_nhds_unique (le_nhds_Lim ⟨a, h⟩) h lemma Lim_eq_iff [ne_bot f] (h : ∃ (a : α), f ≤ nhds a) {a} : @Lim _ _ ⟨a⟩ f = a ↔ f ≤ 𝓝 a := ⟨λ c, c ▸ le_nhds_Lim h, Lim_eq⟩ lemma ultrafilter.Lim_eq_iff_le_nhds [compact_space α] {x : α} {F : ultrafilter α} : F.Lim = x ↔ ↑F ≤ 𝓝 x := ⟨λ h, h ▸ F.le_nhds_Lim, Lim_eq⟩ lemma is_open_iff_ultrafilter' [compact_space α] (U : set α) : is_open U ↔ (∀ F : ultrafilter α, F.Lim ∈ U → U ∈ F.1) := begin rw is_open_iff_ultrafilter, refine ⟨λ h F hF, h F.Lim hF F F.le_nhds_Lim, _⟩, intros cond x hx f h, rw [← (ultrafilter.Lim_eq_iff_le_nhds.2 h)] at hx, exact cond _ hx end lemma filter.tendsto.lim_eq {a : α} {f : filter β} [ne_bot f] {g : β → α} (h : tendsto g f (𝓝 a)) : @lim _ _ _ ⟨a⟩ f g = a := Lim_eq h lemma filter.lim_eq_iff {f : filter β} [ne_bot f] {g : β → α} (h : ∃ a, tendsto g f (𝓝 a)) {a} : @lim _ _ _ ⟨a⟩ f g = a ↔ tendsto g f (𝓝 a) := ⟨λ c, c ▸ tendsto_nhds_lim h, filter.tendsto.lim_eq⟩ lemma continuous.lim_eq [topological_space β] {f : β → α} (h : continuous f) (a : β) : @lim _ _ _ ⟨f a⟩ (𝓝 a) f = f a := (h.tendsto a).lim_eq @[simp] lemma Lim_nhds (a : α) : @Lim _ _ ⟨a⟩ (𝓝 a) = a := Lim_eq le_rfl @[simp] lemma lim_nhds_id (a : α) : @lim _ _ _ ⟨a⟩ (𝓝 a) id = a := Lim_nhds a @[simp] lemma Lim_nhds_within {a : α} {s : set α} (h : a ∈ closure s) : @Lim _ _ ⟨a⟩ (𝓝[s] a) = a := by haveI : ne_bot (𝓝[s] a) := mem_closure_iff_cluster_pt.1 h; exact Lim_eq inf_le_left @[simp] lemma lim_nhds_within_id {a : α} {s : set α} (h : a ∈ closure s) : @lim _ _ _ ⟨a⟩ (𝓝[s] a) id = a := Lim_nhds_within h end lim /-! ### `t2_space` constructions We use two lemmas to prove that various standard constructions generate Hausdorff spaces from Hausdorff spaces: * `separated_by_continuous` says that two points `x y : α` can be separated by open neighborhoods provided that there exists a continuous map `f : α → β` with a Hausdorff codomain such that `f x ≠ f y`. We use this lemma to prove that topological spaces defined using `induced` are Hausdorff spaces. * `separated_by_open_embedding` says that for an open embedding `f : α → β` of a Hausdorff space `α`, the images of two distinct points `x y : α`, `x ≠ y` can be separated by open neighborhoods. We use this lemma to prove that topological spaces defined using `coinduced` are Hausdorff spaces. -/ @[priority 100] -- see Note [lower instance priority] instance discrete_topology.to_t2_space {α : Type*} [topological_space α] [discrete_topology α] : t2_space α := ⟨λ x y h, ⟨{x}, {y}, is_open_discrete _, is_open_discrete _, rfl, rfl, disjoint_singleton.2 h⟩⟩ lemma separated_by_continuous {α : Type*} {β : Type*} [topological_space α] [topological_space β] [t2_space β] {f : α → β} (hf : continuous f) {x y : α} (h : f x ≠ f y) : ∃u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ disjoint u v := let ⟨u, v, uo, vo, xu, yv, uv⟩ := t2_separation h in ⟨f ⁻¹' u, f ⁻¹' v, uo.preimage hf, vo.preimage hf, xu, yv, uv.preimage _⟩ lemma separated_by_open_embedding {α β : Type*} [topological_space α] [topological_space β] [t2_space α] {f : α → β} (hf : open_embedding f) {x y : α} (h : x ≠ y) : ∃ u v : set β, is_open u ∧ is_open v ∧ f x ∈ u ∧ f y ∈ v ∧ disjoint u v := let ⟨u, v, uo, vo, xu, yv, uv⟩ := t2_separation h in ⟨f '' u, f '' v, hf.is_open_map _ uo, hf.is_open_map _ vo, mem_image_of_mem _ xu, mem_image_of_mem _ yv, disjoint_image_of_injective hf.inj uv⟩ instance {α : Type*} {p : α → Prop} [t : topological_space α] [t2_space α] : t2_space (subtype p) := ⟨assume x y h, separated_by_continuous continuous_subtype_val (mt subtype.eq h)⟩ instance {α : Type*} {β : Type*} [t₁ : topological_space α] [t2_space α] [t₂ : topological_space β] [t2_space β] : t2_space (α × β) := ⟨assume ⟨x₁,x₂⟩ ⟨y₁,y₂⟩ h, or.elim (not_and_distrib.mp (mt prod.ext_iff.mpr h)) (λ h₁, separated_by_continuous continuous_fst h₁) (λ h₂, separated_by_continuous continuous_snd h₂)⟩ lemma embedding.t2_space [topological_space β] [t2_space β] {f : α → β} (hf : embedding f) : t2_space α := ⟨λ x y h, separated_by_continuous hf.continuous (hf.inj.ne h)⟩ instance {α : Type*} {β : Type*} [t₁ : topological_space α] [t2_space α] [t₂ : topological_space β] [t2_space β] : t2_space (α ⊕ β) := begin constructor, rintros (x|x) (y|y) h, { replace h : x ≠ y := λ c, (c.subst h) rfl, exact separated_by_open_embedding open_embedding_inl h }, { exact ⟨_, _, is_open_range_inl, is_open_range_inr, ⟨x, rfl⟩, ⟨y, rfl⟩, is_compl_range_inl_range_inr.disjoint⟩ }, { exact ⟨_, _, is_open_range_inr, is_open_range_inl, ⟨x, rfl⟩, ⟨y, rfl⟩, is_compl_range_inl_range_inr.disjoint.symm⟩ }, { replace h : x ≠ y := λ c, (c.subst h) rfl, exact separated_by_open_embedding open_embedding_inr h } end instance Pi.t2_space {α : Type*} {β : α → Type v} [t₂ : Πa, topological_space (β a)] [∀a, t2_space (β a)] : t2_space (Πa, β a) := ⟨assume x y h, let ⟨i, hi⟩ := not_forall.mp (mt funext h) in separated_by_continuous (continuous_apply i) hi⟩ instance sigma.t2_space {ι : Type*} {α : ι → Type*} [Πi, topological_space (α i)] [∀a, t2_space (α a)] : t2_space (Σi, α i) := begin constructor, rintros ⟨i, x⟩ ⟨j, y⟩ neq, rcases em (i = j) with (rfl|h), { replace neq : x ≠ y := λ c, (c.subst neq) rfl, exact separated_by_open_embedding open_embedding_sigma_mk neq }, { exact ⟨_, _, is_open_range_sigma_mk, is_open_range_sigma_mk, ⟨x, rfl⟩, ⟨y, rfl⟩, set.disjoint_left.mpr $ by tidy⟩ } end variables {γ : Type*} [topological_space β] [topological_space γ] lemma is_closed_eq [t2_space α] {f g : β → α} (hf : continuous f) (hg : continuous g) : is_closed {x:β | f x = g x} := continuous_iff_is_closed.mp (hf.prod_mk hg) _ is_closed_diagonal lemma is_open_ne_fun [t2_space α] {f g : β → α} (hf : continuous f) (hg : continuous g) : is_open {x:β | f x ≠ g x} := is_open_compl_iff.mpr $ is_closed_eq hf hg /-- If two continuous maps are equal on `s`, then they are equal on the closure of `s`. See also `set.eq_on.of_subset_closure` for a more general version. -/ lemma set.eq_on.closure [t2_space α] {s : set β} {f g : β → α} (h : eq_on f g s) (hf : continuous f) (hg : continuous g) : eq_on f g (closure s) := closure_minimal h (is_closed_eq hf hg) /-- If two continuous functions are equal on a dense set, then they are equal. -/ lemma continuous.ext_on [t2_space α] {s : set β} (hs : dense s) {f g : β → α} (hf : continuous f) (hg : continuous g) (h : eq_on f g s) : f = g := funext $ λ x, h.closure hf hg (hs x) lemma eq_on_closure₂' [t2_space α] {s : set β} {t : set γ} {f g : β → γ → α} (h : ∀ (x ∈ s) (y ∈ t), f x y = g x y) (hf₁ : ∀ x, continuous (f x)) (hf₂ : ∀ y, continuous (λ x, f x y)) (hg₁ : ∀ x, continuous (g x)) (hg₂ : ∀ y, continuous (λ x, g x y)) : ∀ (x ∈ closure s) (y ∈ closure t), f x y = g x y := suffices closure s ⊆ ⋂ y ∈ closure t, {x | f x y = g x y}, by simpa only [subset_def, mem_Inter], closure_minimal (λ x hx, mem_Inter₂.2 $ set.eq_on.closure (h x hx) (hf₁ _) (hg₁ _)) $ is_closed_bInter $ λ y hy, is_closed_eq (hf₂ _) (hg₂ _) lemma eq_on_closure₂ [t2_space α] {s : set β} {t : set γ} {f g : β → γ → α} (h : ∀ (x ∈ s) (y ∈ t), f x y = g x y) (hf : continuous (uncurry f)) (hg : continuous (uncurry g)) : ∀ (x ∈ closure s) (y ∈ closure t), f x y = g x y := eq_on_closure₂' h (λ x, continuous_uncurry_left x hf) (λ x, continuous_uncurry_right x hf) (λ y, continuous_uncurry_left y hg) (λ y, continuous_uncurry_right y hg) /-- If `f x = g x` for all `x ∈ s` and `f`, `g` are continuous on `t`, `s ⊆ t ⊆ closure s`, then `f x = g x` for all `x ∈ t`. See also `set.eq_on.closure`. -/ lemma set.eq_on.of_subset_closure [t2_space α] {s t : set β} {f g : β → α} (h : eq_on f g s) (hf : continuous_on f t) (hg : continuous_on g t) (hst : s ⊆ t) (hts : t ⊆ closure s) : eq_on f g t := begin intros x hx, haveI : (𝓝[s] x).ne_bot, from mem_closure_iff_cluster_pt.mp (hts hx), exact tendsto_nhds_unique_of_eventually_eq ((hf x hx).mono_left $ nhds_within_mono _ hst) ((hg x hx).mono_left $ nhds_within_mono _ hst) (h.eventually_eq_of_mem self_mem_nhds_within) end lemma function.left_inverse.closed_range [t2_space α] {f : α → β} {g : β → α} (h : function.left_inverse f g) (hf : continuous f) (hg : continuous g) : is_closed (range g) := have eq_on (g ∘ f) id (closure $ range g), from h.right_inv_on_range.eq_on.closure (hg.comp hf) continuous_id, is_closed_of_closure_subset $ λ x hx, calc x = g (f x) : (this hx).symm ... ∈ _ : mem_range_self _ lemma function.left_inverse.closed_embedding [t2_space α] {f : α → β} {g : β → α} (h : function.left_inverse f g) (hf : continuous f) (hg : continuous g) : closed_embedding g := ⟨h.embedding hf hg, h.closed_range hf hg⟩ lemma is_compact_is_compact_separated [t2_space α] {s t : set α} (hs : is_compact s) (ht : is_compact t) (hst : disjoint s t) : separated_nhds s t := by simp only [separated_nhds, prod_subset_compl_diagonal_iff_disjoint.symm] at ⊢ hst; exact generalized_tube_lemma hs ht is_closed_diagonal.is_open_compl hst /-- In a `t2_space`, every compact set is closed. -/ lemma is_compact.is_closed [t2_space α] {s : set α} (hs : is_compact s) : is_closed s := is_open_compl_iff.1 $ is_open_iff_forall_mem_open.mpr $ assume x hx, let ⟨u, v, uo, vo, su, xv, uv⟩ := is_compact_is_compact_separated hs is_compact_singleton (disjoint_singleton_right.2 hx) in ⟨v, (uv.mono_left $ show s ≤ u, from su).subset_compl_left, vo, by simpa using xv⟩ @[simp] lemma filter.coclosed_compact_eq_cocompact [t2_space α] : coclosed_compact α = cocompact α := by simp [coclosed_compact, cocompact, infi_and', and_iff_right_of_imp is_compact.is_closed] @[simp] lemma bornology.relatively_compact_eq_in_compact [t2_space α] : bornology.relatively_compact α = bornology.in_compact α := by rw bornology.ext_iff; exact filter.coclosed_compact_eq_cocompact /-- If `V : ι → set α` is a decreasing family of compact sets then any neighborhood of `⋂ i, V i` contains some `V i`. This is a version of `exists_subset_nhd_of_compact'` where we don't need to assume each `V i` closed because it follows from compactness since `α` is assumed to be Hausdorff. -/ lemma exists_subset_nhds_of_is_compact [t2_space α] {ι : Type*} [nonempty ι] {V : ι → set α} (hV : directed (⊇) V) (hV_cpct : ∀ i, is_compact (V i)) {U : set α} (hU : ∀ x ∈ ⋂ i, V i, U ∈ 𝓝 x) : ∃ i, V i ⊆ U := exists_subset_nhds_of_is_compact' hV hV_cpct (λ i, (hV_cpct i).is_closed) hU lemma compact_exhaustion.is_closed [t2_space α] (K : compact_exhaustion α) (n : ℕ) : is_closed (K n) := (K.is_compact n).is_closed lemma is_compact.inter [t2_space α] {s t : set α} (hs : is_compact s) (ht : is_compact t) : is_compact (s ∩ t) := hs.inter_right $ ht.is_closed lemma is_compact_closure_of_subset_compact [t2_space α] {s t : set α} (ht : is_compact t) (h : s ⊆ t) : is_compact (closure s) := is_compact_of_is_closed_subset ht is_closed_closure (closure_minimal h ht.is_closed) @[simp] lemma exists_compact_superset_iff [t2_space α] {s : set α} : (∃ K, is_compact K ∧ s ⊆ K) ↔ is_compact (closure s) := ⟨λ ⟨K, hK, hsK⟩, is_compact_closure_of_subset_compact hK hsK, λ h, ⟨closure s, h, subset_closure⟩⟩ lemma image_closure_of_is_compact [t2_space β] {s : set α} (hs : is_compact (closure s)) {f : α → β} (hf : continuous_on f (closure s)) : f '' closure s = closure (f '' s) := subset.antisymm hf.image_closure $ closure_minimal (image_subset f subset_closure) (hs.image_of_continuous_on hf).is_closed /-- If a compact set is covered by two open sets, then we can cover it by two compact subsets. -/ lemma is_compact.binary_compact_cover [t2_space α] {K U V : set α} (hK : is_compact K) (hU : is_open U) (hV : is_open V) (h2K : K ⊆ U ∪ V) : ∃ K₁ K₂ : set α, is_compact K₁ ∧ is_compact K₂ ∧ K₁ ⊆ U ∧ K₂ ⊆ V ∧ K = K₁ ∪ K₂ := begin obtain ⟨O₁, O₂, h1O₁, h1O₂, h2O₁, h2O₂, hO⟩ := is_compact_is_compact_separated (hK.diff hU) (hK.diff hV) (by rwa [disjoint_iff_inter_eq_empty, diff_inter_diff, diff_eq_empty]), exact ⟨_, _, hK.diff h1O₁, hK.diff h1O₂, by rwa [diff_subset_comm], by rwa [diff_subset_comm], by rw [← diff_inter, hO.inter_eq, diff_empty]⟩ end lemma continuous.is_closed_map [compact_space α] [t2_space β] {f : α → β} (h : continuous f) : is_closed_map f := λ s hs, (hs.is_compact.image h).is_closed lemma continuous.closed_embedding [compact_space α] [t2_space β] {f : α → β} (h : continuous f) (hf : function.injective f) : closed_embedding f := closed_embedding_of_continuous_injective_closed h hf h.is_closed_map section open finset function /-- For every finite open cover `Uᵢ` of a compact set, there exists a compact cover `Kᵢ ⊆ Uᵢ`. -/ lemma is_compact.finite_compact_cover [t2_space α] {s : set α} (hs : is_compact s) {ι} (t : finset ι) (U : ι → set α) (hU : ∀ i ∈ t, is_open (U i)) (hsC : s ⊆ ⋃ i ∈ t, U i) : ∃ K : ι → set α, (∀ i, is_compact (K i)) ∧ (∀i, K i ⊆ U i) ∧ s = ⋃ i ∈ t, K i := begin classical, induction t using finset.induction with x t hx ih generalizing U hU s hs hsC, { refine ⟨λ _, ∅, λ i, is_compact_empty, λ i, empty_subset _, _⟩, simpa only [subset_empty_iff, Union_false, Union_empty] using hsC }, simp only [finset.set_bUnion_insert] at hsC, simp only [finset.mem_insert] at hU, have hU' : ∀ i ∈ t, is_open (U i) := λ i hi, hU i (or.inr hi), rcases hs.binary_compact_cover (hU x (or.inl rfl)) (is_open_bUnion hU') hsC with ⟨K₁, K₂, h1K₁, h1K₂, h2K₁, h2K₂, hK⟩, rcases ih U hU' h1K₂ h2K₂ with ⟨K, h1K, h2K, h3K⟩, refine ⟨update K x K₁, _, _, _⟩, { intros i, by_cases hi : i = x, { simp only [update_same, hi, h1K₁] }, { rw [← ne.def] at hi, simp only [update_noteq hi, h1K] }}, { intros i, by_cases hi : i = x, { simp only [update_same, hi, h2K₁] }, { rw [← ne.def] at hi, simp only [update_noteq hi, h2K] }}, { simp only [set_bUnion_insert_update _ hx, hK, h3K] } end end lemma locally_compact_of_compact_nhds [t2_space α] (h : ∀ x : α, ∃ s, s ∈ 𝓝 x ∧ is_compact s) : locally_compact_space α := ⟨assume x n hn, let ⟨u, un, uo, xu⟩ := mem_nhds_iff.mp hn in let ⟨k, kx, kc⟩ := h x in -- K is compact but not necessarily contained in N. -- K \ U is again compact and doesn't contain x, so -- we may find open sets V, W separating x from K \ U. -- Then K \ W is a compact neighborhood of x contained in U. let ⟨v, w, vo, wo, xv, kuw, vw⟩ := is_compact_is_compact_separated is_compact_singleton (kc.diff uo) (disjoint_singleton_left.2 $ λ h, h.2 xu) in have wn : wᶜ ∈ 𝓝 x, from mem_nhds_iff.mpr ⟨v, vw.subset_compl_right, vo, singleton_subset_iff.mp xv⟩, ⟨k \ w, filter.inter_mem kx wn, subset.trans (diff_subset_comm.mp kuw) un, kc.diff wo⟩⟩ @[priority 100] -- see Note [lower instance priority] instance locally_compact_of_compact [t2_space α] [compact_space α] : locally_compact_space α := locally_compact_of_compact_nhds (assume x, ⟨univ, is_open_univ.mem_nhds trivial, is_compact_univ⟩) /-- In a locally compact T₂ space, every point has an open neighborhood with compact closure -/ lemma exists_open_with_compact_closure [locally_compact_space α] [t2_space α] (x : α) : ∃ (U : set α), is_open U ∧ x ∈ U ∧ is_compact (closure U) := begin rcases exists_compact_mem_nhds x with ⟨K, hKc, hxK⟩, rcases mem_nhds_iff.1 hxK with ⟨t, h1t, h2t, h3t⟩, exact ⟨t, h2t, h3t, is_compact_closure_of_subset_compact hKc h1t⟩ end /-- In a locally compact T₂ space, every compact set has an open neighborhood with compact closure. -/ lemma exists_open_superset_and_is_compact_closure [locally_compact_space α] [t2_space α] {K : set α} (hK : is_compact K) : ∃ V, is_open V ∧ K ⊆ V ∧ is_compact (closure V) := begin rcases exists_compact_superset hK with ⟨K', hK', hKK'⟩, refine ⟨interior K', is_open_interior, hKK', is_compact_closure_of_subset_compact hK' interior_subset⟩, end /-- In a locally compact T₂ space, given a compact set `K` inside an open set `U`, we can find a open set `V` between these sets with compact closure: `K ⊆ V` and the closure of `V` is inside `U`. -/ lemma exists_open_between_and_is_compact_closure [locally_compact_space α] [t2_space α] {K U : set α} (hK : is_compact K) (hU : is_open U) (hKU : K ⊆ U) : ∃ V, is_open V ∧ K ⊆ V ∧ closure V ⊆ U ∧ is_compact (closure V) := begin rcases exists_compact_between hK hU hKU with ⟨V, hV, hKV, hVU⟩, exact ⟨interior V, is_open_interior, hKV, (closure_minimal interior_subset hV.is_closed).trans hVU, is_compact_closure_of_subset_compact hV interior_subset⟩, end lemma is_preirreducible_iff_subsingleton [t2_space α] {S : set α} : is_preirreducible S ↔ S.subsingleton := begin refine ⟨λ h x hx y hy, _, set.subsingleton.is_preirreducible⟩, by_contradiction e, obtain ⟨U, V, hU, hV, hxU, hyV, h'⟩ := t2_separation e, exact ((h U V hU hV ⟨x, hx, hxU⟩ ⟨y, hy, hyV⟩).mono $ inter_subset_right _ _).not_disjoint h', end alias is_preirreducible_iff_subsingleton ↔ is_preirreducible.subsingleton _ attribute [protected] is_preirreducible.subsingleton lemma is_irreducible_iff_singleton [t2_space α] {S : set α} : is_irreducible S ↔ ∃ x, S = {x} := by rw [is_irreducible, is_preirreducible_iff_subsingleton, exists_eq_singleton_iff_nonempty_subsingleton] /-- There does not exist a nontrivial preirreducible T₂ space. -/ lemma not_preirreducible_nontrivial_t2 (α) [topological_space α] [preirreducible_space α] [nontrivial α] [t2_space α] : false := (preirreducible_space.is_preirreducible_univ α).subsingleton.not_nontrivial nontrivial_univ end separation section regular_space /-- A topological space is called a *regular space* if for any closed set `s` and `a ∉ s`, there exist disjoint open sets `U ⊇ s` and `V ∋ a`. We formulate this condition in terms of `disjoint`ness of filters `𝓝ˢ s` and `𝓝 a`. -/ @[mk_iff] class regular_space (X : Type u) [topological_space X] : Prop := (regular : ∀ {s : set X} {a}, is_closed s → a ∉ s → disjoint (𝓝ˢ s) (𝓝 a)) lemma regular_space_tfae (X : Type u) [topological_space X] : tfae [regular_space X, ∀ (s : set X) (a ∉ closure s), disjoint (𝓝ˢ s) (𝓝 a), ∀ (a : X) (s : set X), disjoint (𝓝ˢ s) (𝓝 a) ↔ a ∉ closure s, ∀ (a : X) (s ∈ 𝓝 a), ∃ t ∈ 𝓝 a, is_closed t ∧ t ⊆ s, ∀ a : X, (𝓝 a).lift' closure ≤ 𝓝 a, ∀ a : X, (𝓝 a).lift' closure = 𝓝 a] := begin tfae_have : 1 ↔ 5, { rw [regular_space_iff, (@compl_surjective (set X) _).forall, forall_swap], simp only [is_closed_compl_iff, mem_compl_iff, not_not, @and_comm (_ ∈ _), (nhds_basis_opens _).lift'_closure.le_basis_iff (nhds_basis_opens _), and_imp, (nhds_basis_opens _).disjoint_iff_right, exists_prop, ← subset_interior_iff_mem_nhds_set, interior_compl, compl_subset_compl] }, tfae_have : 5 → 6, from λ h a, (h a).antisymm (𝓝 _).le_lift'_closure, tfae_have : 6 → 4, { intros H a s hs, rw [← H] at hs, rcases (𝓝 a).basis_sets.lift'_closure.mem_iff.mp hs with ⟨U, hU, hUs⟩, exact ⟨closure U, mem_of_superset hU subset_closure, is_closed_closure, hUs⟩ }, tfae_have : 4 → 2, { intros H s a ha, have ha' : sᶜ ∈ 𝓝 a, by rwa [← mem_interior_iff_mem_nhds, interior_compl], rcases H _ _ ha' with ⟨U, hU, hUc, hUs⟩, refine disjoint_of_disjoint_of_mem disjoint_compl_left _ hU, rwa [← subset_interior_iff_mem_nhds_set, hUc.is_open_compl.interior_eq, subset_compl_comm] }, tfae_have : 2 → 3, { refine λ H a s, ⟨λ hd has, mem_closure_iff_nhds_ne_bot.mp has _, H s a⟩, exact (hd.symm.mono_right $ @principal_le_nhds_set _ _ s).eq_bot }, tfae_have : 3 → 1, from λ H, ⟨λ s a hs ha, (H _ _).mpr $ hs.closure_eq.symm ▸ ha⟩, tfae_finish end lemma regular_space.of_lift'_closure (h : ∀ a : α, (𝓝 a).lift' closure = 𝓝 a) : regular_space α := iff.mpr ((regular_space_tfae α).out 0 5) h lemma regular_space.of_basis {ι : α → Sort*} {p : Π a, ι a → Prop} {s : Π a, ι a → set α} (h₁ : ∀ a, (𝓝 a).has_basis (p a) (s a)) (h₂ : ∀ a i, p a i → is_closed (s a i)) : regular_space α := regular_space.of_lift'_closure $ λ a, (h₁ a).lift'_closure_eq_self (h₂ a) lemma regular_space.of_exists_mem_nhds_is_closed_subset (h : ∀ (a : α) (s ∈ 𝓝 a), ∃ t ∈ 𝓝 a, is_closed t ∧ t ⊆ s) : regular_space α := iff.mpr ((regular_space_tfae α).out 0 3) h variables [regular_space α] {a : α} {s : set α} lemma disjoint_nhds_set_nhds : disjoint (𝓝ˢ s) (𝓝 a) ↔ a ∉ closure s := iff.mp ((regular_space_tfae α).out 0 2) ‹_› _ _ lemma disjoint_nhds_nhds_set : disjoint (𝓝 a) (𝓝ˢ s) ↔ a ∉ closure s := disjoint.comm.trans disjoint_nhds_set_nhds lemma exists_mem_nhds_is_closed_subset {a : α} {s : set α} (h : s ∈ 𝓝 a) : ∃ t ∈ 𝓝 a, is_closed t ∧ t ⊆ s := iff.mp ((regular_space_tfae α).out 0 3) ‹_› _ _ h lemma closed_nhds_basis (a : α) : (𝓝 a).has_basis (λ s : set α, s ∈ 𝓝 a ∧ is_closed s) id := has_basis_self.2 (λ _, exists_mem_nhds_is_closed_subset) lemma lift'_nhds_closure (a : α) : (𝓝 a).lift' closure = 𝓝 a := (closed_nhds_basis a).lift'_closure_eq_self (λ s hs, hs.2) lemma filter.has_basis.nhds_closure {ι : Sort*} {a : α} {p : ι → Prop} {s : ι → set α} (h : (𝓝 a).has_basis p s) : (𝓝 a).has_basis p (λ i, closure (s i)) := lift'_nhds_closure a ▸ h.lift'_closure lemma has_basis_nhds_closure (a : α) : (𝓝 a).has_basis (λ s, s ∈ 𝓝 a) closure := (𝓝 a).basis_sets.nhds_closure lemma has_basis_opens_closure (a : α) : (𝓝 a).has_basis (λ s, a ∈ s ∧ is_open s) closure := (nhds_basis_opens a).nhds_closure lemma topological_space.is_topological_basis.nhds_basis_closure {B : set (set α)} (hB : topological_space.is_topological_basis B) (a : α) : (𝓝 a).has_basis (λ s : set α, a ∈ s ∧ s ∈ B) closure := by simpa only [and_comm] using hB.nhds_has_basis.nhds_closure lemma topological_space.is_topological_basis.exists_closure_subset {B : set (set α)} (hB : topological_space.is_topological_basis B) {a : α} {s : set α} (h : s ∈ 𝓝 a) : ∃ t ∈ B, a ∈ t ∧ closure t ⊆ s := by simpa only [exists_prop, and.assoc] using hB.nhds_has_basis.nhds_closure.mem_iff.mp h lemma disjoint_nhds_nhds_iff_not_specializes {a b : α} : disjoint (𝓝 a) (𝓝 b) ↔ ¬a ⤳ b := by rw [← nhds_set_singleton, disjoint_nhds_set_nhds, specializes_iff_mem_closure] lemma specializes_comm {a b : α} : a ⤳ b ↔ b ⤳ a := by simp only [← disjoint_nhds_nhds_iff_not_specializes.not_left, disjoint.comm] alias specializes_comm ↔ specializes.symm _ lemma specializes_iff_inseparable {a b : α} : a ⤳ b ↔ inseparable a b := ⟨λ h, h.antisymm h.symm, le_of_eq⟩ lemma is_closed_set_of_specializes : is_closed {p : α × α | p.1 ⤳ p.2} := by simp only [← is_open_compl_iff, compl_set_of, ← disjoint_nhds_nhds_iff_not_specializes, is_open_set_of_disjoint_nhds_nhds] lemma is_closed_set_of_inseparable : is_closed {p : α × α | inseparable p.1 p.2} := by simp only [← specializes_iff_inseparable, is_closed_set_of_specializes] protected lemma inducing.regular_space [topological_space β] {f : β → α} (hf : inducing f) : regular_space β := regular_space.of_basis (λ b, by { rw [hf.nhds_eq_comap b], exact (closed_nhds_basis _).comap _ }) $ λ b s hs, hs.2.preimage hf.continuous lemma regular_space_induced (f : β → α) : @regular_space β (induced f ‹_›) := by { letI := induced f ‹_›, exact inducing.regular_space ⟨rfl⟩ } lemma regular_space_Inf {X} {T : set (topological_space X)} (h : ∀ t ∈ T, @regular_space X t) : @regular_space X (Inf T) := begin letI := Inf T, have : ∀ a, (𝓝 a).has_basis (λ If : Σ I : set T, I → set X, If.1.finite ∧ ∀ i : If.1, If.2 i ∈ @nhds X i a ∧ @is_closed X i (If.2 i)) (λ If, ⋂ i : If.1, If.snd i), { intro a, rw [nhds_Inf, ← infi_subtype''], exact has_basis_infi (λ t : T, @closed_nhds_basis X t (h t t.2) a) }, refine regular_space.of_basis this (λ a If hIf, is_closed_Inter $ λ i, _), exact (hIf.2 i).2.mono (Inf_le (i : T).2) end lemma regular_space_infi {ι X} {t : ι → topological_space X} (h : ∀ i, @regular_space X (t i)) : @regular_space X (infi t) := regular_space_Inf $ forall_range_iff.mpr h lemma regular_space.inf {X} {t₁ t₂ : topological_space X} (h₁ : @regular_space X t₁) (h₂ : @regular_space X t₂) : @regular_space X (t₁ ⊓ t₂) := by { rw [inf_eq_infi], exact regular_space_infi (bool.forall_bool.2 ⟨h₂, h₁⟩) } instance {p : α → Prop} : regular_space (subtype p) := embedding_subtype_coe.to_inducing.regular_space instance [topological_space β] [regular_space β] : regular_space (α × β) := (regular_space_induced prod.fst).inf (regular_space_induced prod.snd) instance {ι : Type*} {π : ι → Type*} [Π i, topological_space (π i)] [∀ i, regular_space (π i)] : regular_space (Π i, π i) := regular_space_infi $ λ i, regular_space_induced _ end regular_space section t3 /-- A T₃ space is a T₀ space which is a regular space. Any T₃ space is a T₁ space, a T₂ space, and a T₂.₅ space. -/ class t3_space (α : Type u) [topological_space α] extends t0_space α, regular_space α : Prop @[priority 100] -- see Note [lower instance priority] instance t3_space.t2_5_space [t3_space α] : t2_5_space α := begin refine ⟨λ x y hne, _⟩, rw [lift'_nhds_closure, lift'_nhds_closure], have : x ∉ closure {y} ∨ y ∉ closure {x}, from (t0_space_iff_or_not_mem_closure α).mp infer_instance x y hne, wlog H : x ∉ closure {y} := this using [x y, y x] tactic.skip, { rwa [← disjoint_nhds_nhds_set, nhds_set_singleton] at H }, { exact λ h, (this h.symm).symm } end protected lemma embedding.t3_space [topological_space β] [t3_space β] {f : α → β} (hf : embedding f) : t3_space α := { to_t0_space := hf.t0_space, to_regular_space := hf.to_inducing.regular_space } instance subtype.t3_space [t3_space α] {p : α → Prop} : t3_space (subtype p) := embedding_subtype_coe.t3_space instance [topological_space β] [t3_space α] [t3_space β] : t3_space (α × β) := ⟨⟩ instance {ι : Type*} {π : ι → Type*} [Π i, topological_space (π i)] [Π i, t3_space (π i)] : t3_space (Π i, π i) := ⟨⟩ /-- Given two points `x ≠ y`, we can find neighbourhoods `x ∈ V₁ ⊆ U₁` and `y ∈ V₂ ⊆ U₂`, with the `Vₖ` closed and the `Uₖ` open, such that the `Uₖ` are disjoint. -/ lemma disjoint_nested_nhds [t3_space α] {x y : α} (h : x ≠ y) : ∃ (U₁ V₁ ∈ 𝓝 x) (U₂ V₂ ∈ 𝓝 y), is_closed V₁ ∧ is_closed V₂ ∧ is_open U₁ ∧ is_open U₂ ∧ V₁ ⊆ U₁ ∧ V₂ ⊆ U₂ ∧ disjoint U₁ U₂ := begin rcases t2_separation h with ⟨U₁, U₂, U₁_op, U₂_op, x_in, y_in, H⟩, rcases exists_mem_nhds_is_closed_subset (U₁_op.mem_nhds x_in) with ⟨V₁, V₁_in, V₁_closed, h₁⟩, rcases exists_mem_nhds_is_closed_subset (U₂_op.mem_nhds y_in) with ⟨V₂, V₂_in, V₂_closed, h₂⟩, exact ⟨U₁, mem_of_superset V₁_in h₁, V₁, V₁_in, U₂, mem_of_superset V₂_in h₂, V₂, V₂_in, V₁_closed, V₂_closed, U₁_op, U₂_op, h₁, h₂, H⟩ end open separation_quotient /-- The `separation_quotient` of a regular space is a T₃ space. -/ instance [regular_space α] : t3_space (separation_quotient α) := { regular := λ s, surjective_mk.forall.2 $ λ a hs ha, by { rw [← disjoint_comap_iff surjective_mk, comap_mk_nhds_mk, comap_mk_nhds_set], exact regular_space.regular (hs.preimage continuous_mk) ha } } end t3 section normality /-- A T₄ space, also known as a normal space (although this condition sometimes omits T₂), is one in which for every pair of disjoint closed sets `C` and `D`, there exist disjoint open sets containing `C` and `D` respectively. -/ class normal_space (α : Type u) [topological_space α] extends t1_space α : Prop := (normal : ∀ s t : set α, is_closed s → is_closed t → disjoint s t → separated_nhds s t) theorem normal_separation [normal_space α] {s t : set α} (H1 : is_closed s) (H2 : is_closed t) (H3 : disjoint s t) : separated_nhds s t := normal_space.normal s t H1 H2 H3 theorem normal_exists_closure_subset [normal_space α] {s t : set α} (hs : is_closed s) (ht : is_open t) (hst : s ⊆ t) : ∃ u, is_open u ∧ s ⊆ u ∧ closure u ⊆ t := begin have : disjoint s tᶜ, from set.disjoint_left.mpr (λ x hxs hxt, hxt (hst hxs)), rcases normal_separation hs (is_closed_compl_iff.2 ht) this with ⟨s', t', hs', ht', hss', htt', hs't'⟩, refine ⟨s', hs', hss', subset.trans (closure_minimal _ (is_closed_compl_iff.2 ht')) (compl_subset_comm.1 htt')⟩, exact λ x hxs hxt, hs't'.le_bot ⟨hxs, hxt⟩ end @[priority 100] -- see Note [lower instance priority] instance normal_space.t3_space [normal_space α] : t3_space α := { regular := λ s x hs hxs, let ⟨u, v, hu, hv, hsu, hxv, huv⟩ := normal_separation hs is_closed_singleton (disjoint_singleton_right.mpr hxs) in disjoint_of_disjoint_of_mem huv (hu.mem_nhds_set.2 hsu) (hv.mem_nhds $ hxv rfl) } -- We can't make this an instance because it could cause an instance loop. lemma normal_of_compact_t2 [compact_space α] [t2_space α] : normal_space α := ⟨λ s t hs ht, is_compact_is_compact_separated hs.is_compact ht.is_compact⟩ protected lemma closed_embedding.normal_space [topological_space β] [normal_space β] {f : α → β} (hf : closed_embedding f) : normal_space α := { to_t1_space := hf.to_embedding.t1_space, normal := begin intros s t hs ht hst, have H : separated_nhds (f '' s) (f '' t), from normal_space.normal (f '' s) (f '' t) (hf.is_closed_map s hs) (hf.is_closed_map t ht) (disjoint_image_of_injective hf.inj hst), exact (H.preimage hf.continuous).mono (subset_preimage_image _ _) (subset_preimage_image _ _) end } namespace separation_quotient /-- The `separation_quotient` of a normal space is a T₄ space. We don't have separate typeclasses for normal spaces (without T₁ assumption) and T₄ spaces, so we use the same class for assumption and for conclusion. One can prove this using a homeomorphism between `α` and `separation_quotient α`. We give an alternative proof that works without assuming that `α` is a T₁ space. -/ instance [normal_space α] : normal_space (separation_quotient α) := { normal := λ s t hs ht hd, separated_nhds_iff_disjoint.2 $ begin rw [← disjoint_comap_iff surjective_mk, comap_mk_nhds_set, comap_mk_nhds_set], exact separated_nhds_iff_disjoint.1 (normal_separation (hs.preimage continuous_mk) (ht.preimage continuous_mk) (hd.preimage mk)) end } end separation_quotient variable (α) /-- A T₃ topological space with second countable topology is a normal space. This lemma is not an instance to avoid a loop. -/ lemma normal_space_of_t3_second_countable [second_countable_topology α] [t3_space α] : normal_space α := begin have key : ∀ {s t : set α}, is_closed t → disjoint s t → ∃ U : set (countable_basis α), (s ⊆ ⋃ u ∈ U, ↑u) ∧ (∀ u ∈ U, disjoint (closure ↑u) t) ∧ ∀ n : ℕ, is_closed (⋃ (u ∈ U) (h : encodable.encode u ≤ n), closure (u : set α)), { intros s t hc hd, rw disjoint_left at hd, have : ∀ x ∈ s, ∃ U ∈ countable_basis α, x ∈ U ∧ disjoint (closure U) t, { intros x hx, rcases (is_basis_countable_basis α).exists_closure_subset (hc.is_open_compl.mem_nhds (hd hx)) with ⟨u, hu, hxu, hut⟩, exact ⟨u, hu, hxu, disjoint_left.2 hut⟩ }, choose! U hu hxu hd, set V : s → countable_basis α := maps_to.restrict _ _ _ hu, refine ⟨range V, _, forall_range_iff.2 $ subtype.forall.2 hd, λ n, _⟩, { rw bUnion_range, exact λ x hx, mem_Union.2 ⟨⟨x, hx⟩, hxu x hx⟩ }, { simp only [← supr_eq_Union, supr_and'], exact is_closed_bUnion (((finite_le_nat n).preimage_embedding (encodable.encode' _)).subset $ inter_subset_right _ _) (λ u hu, is_closed_closure) } }, refine ⟨λ s t hs ht hd, _⟩, rcases key ht hd with ⟨U, hsU, hUd, hUc⟩, rcases key hs hd.symm with ⟨V, htV, hVd, hVc⟩, refine ⟨⋃ u ∈ U, ↑u \ ⋃ (v ∈ V) (hv : encodable.encode v ≤ encodable.encode u), closure ↑v, ⋃ v ∈ V, ↑v \ ⋃ (u ∈ U) (hu : encodable.encode u ≤ encodable.encode v), closure ↑u, is_open_bUnion $ λ u hu, (is_open_of_mem_countable_basis u.2).sdiff (hVc _), is_open_bUnion $ λ v hv, (is_open_of_mem_countable_basis v.2).sdiff (hUc _), λ x hx, _, λ x hx, _, _⟩, { rcases mem_Union₂.1 (hsU hx) with ⟨u, huU, hxu⟩, refine mem_bUnion huU ⟨hxu, _⟩, simp only [mem_Union], rintro ⟨v, hvV, -, hxv⟩, exact (hVd v hvV).le_bot ⟨hxv, hx⟩ }, { rcases mem_Union₂.1 (htV hx) with ⟨v, hvV, hxv⟩, refine mem_bUnion hvV ⟨hxv, _⟩, simp only [mem_Union], rintro ⟨u, huU, -, hxu⟩, exact (hUd u huU).le_bot ⟨hxu, hx⟩ }, { simp only [disjoint_left, mem_Union, mem_diff, not_exists, not_and, not_forall, not_not], rintro a ⟨u, huU, hau, haV⟩ v hvV hav, cases le_total (encodable.encode u) (encodable.encode v) with hle hle, exacts [⟨u, huU, hle, subset_closure hau⟩, (haV _ hvV hle $ subset_closure hav).elim] } end end normality section completely_normal /-- A topological space `α` is a *completely normal Hausdorff space* if each subspace `s : set α` is a normal Hausdorff space. Equivalently, `α` is a `T₁` space and for any two sets `s`, `t` such that `closure s` is disjoint with `t` and `s` is disjoint with `closure t`, there exist disjoint neighbourhoods of `s` and `t`. -/ class t5_space (α : Type u) [topological_space α] extends t1_space α : Prop := (completely_normal : ∀ ⦃s t : set α⦄, disjoint (closure s) t → disjoint s (closure t) → disjoint (𝓝ˢ s) (𝓝ˢ t)) export t5_space (completely_normal) lemma embedding.t5_space [topological_space β] [t5_space β] {e : α → β} (he : embedding e) : t5_space α := begin haveI := he.t1_space, refine ⟨λ s t hd₁ hd₂, _⟩, simp only [he.to_inducing.nhds_set_eq_comap], refine disjoint_comap (completely_normal _ _), { rwa [← subset_compl_iff_disjoint_left, image_subset_iff, preimage_compl, ← he.closure_eq_preimage_closure_image, subset_compl_iff_disjoint_left] }, { rwa [← subset_compl_iff_disjoint_right, image_subset_iff, preimage_compl, ← he.closure_eq_preimage_closure_image, subset_compl_iff_disjoint_right] } end /-- A subspace of a `T₅` space is a `T₅` space. -/ instance [t5_space α] {p : α → Prop} : t5_space {x // p x} := embedding_subtype_coe.t5_space /-- A `T₅` space is a `T₄` space. -/ @[priority 100] -- see Note [lower instance priority] instance t5_space.to_normal_space [t5_space α] : normal_space α := ⟨λ s t hs ht hd, separated_nhds_iff_disjoint.2 $ completely_normal (by rwa [hs.closure_eq]) (by rwa [ht.closure_eq])⟩ open separation_quotient /-- The `separation_quotient` of a completely normal space is a T₅ space. We don't have separate typeclasses for completely normal spaces (without T₁ assumption) and T₅ spaces, so we use the same class for assumption and for conclusion. One can prove this using a homeomorphism between `α` and `separation_quotient α`. We give an alternative proof that works without assuming that `α` is a T₁ space. -/ instance [t5_space α] : t5_space (separation_quotient α) := { completely_normal := λ s t hd₁ hd₂, begin rw [← disjoint_comap_iff surjective_mk, comap_mk_nhds_set, comap_mk_nhds_set], apply t5_space.completely_normal; rw [← preimage_mk_closure], exacts [hd₁.preimage mk, hd₂.preimage mk] end } end completely_normal /-- In a compact t2 space, the connected component of a point equals the intersection of all its clopen neighbourhoods. -/ lemma connected_component_eq_Inter_clopen [t2_space α] [compact_space α] (x : α) : connected_component x = ⋂ Z : {Z : set α // is_clopen Z ∧ x ∈ Z}, Z := begin apply eq_of_subset_of_subset connected_component_subset_Inter_clopen, -- Reduce to showing that the clopen intersection is connected. refine is_preconnected.subset_connected_component _ (mem_Inter.2 (λ Z, Z.2.2)), -- We do this by showing that any disjoint cover by two closed sets implies -- that one of these closed sets must contain our whole thing. -- To reduce to the case where the cover is disjoint on all of `α` we need that `s` is closed have hs : @is_closed α _ (⋂ (Z : {Z : set α // is_clopen Z ∧ x ∈ Z}), Z) := is_closed_Inter (λ Z, Z.2.1.2), rw (is_preconnected_iff_subset_of_fully_disjoint_closed hs), intros a b ha hb hab ab_disj, haveI := @normal_of_compact_t2 α _ _ _, -- Since our space is normal, we get two larger disjoint open sets containing the disjoint -- closed sets. If we can show that our intersection is a subset of any of these we can then -- "descend" this to show that it is a subset of either a or b. rcases normal_separation ha hb ab_disj with ⟨u, v, hu, hv, hau, hbv, huv⟩, -- If we can find a clopen set around x, contained in u ∪ v, we get a disjoint decomposition -- Z = Z ∩ u ∪ Z ∩ v of clopen sets. The intersection of all clopen neighbourhoods will then lie -- in whichever of u or v x lies in and hence will be a subset of either a or b. rsuffices ⟨Z, H⟩ : ∃ (Z : set α), is_clopen Z ∧ x ∈ Z ∧ Z ⊆ u ∪ v, { have H1 := is_clopen_inter_of_disjoint_cover_clopen H.1 H.2.2 hu hv huv, rw [union_comm] at H, have H2 := is_clopen_inter_of_disjoint_cover_clopen H.1 H.2.2 hv hu huv.symm, by_cases (x ∈ u), -- The x ∈ u case. { left, suffices : (⋂ (Z : {Z : set α // is_clopen Z ∧ x ∈ Z}), ↑Z) ⊆ u, { replace hab : (⋂ (Z : {Z // is_clopen Z ∧ x ∈ Z}), ↑Z) ≤ a ∪ b := hab, replace this : (⋂ (Z : {Z // is_clopen Z ∧ x ∈ Z}), ↑Z) ≤ u := this, exact disjoint.left_le_of_le_sup_right hab (huv.mono this hbv) }, { apply subset.trans _ (inter_subset_right Z u), apply Inter_subset (λ Z : {Z : set α // is_clopen Z ∧ x ∈ Z}, ↑Z) ⟨Z ∩ u, H1, mem_inter H.2.1 h⟩ } }, -- If x ∉ u, we get x ∈ v since x ∈ u ∪ v. The rest is then like the x ∈ u case. have h1 : x ∈ v, { cases (mem_union x u v).1 (mem_of_subset_of_mem (subset.trans hab (union_subset_union hau hbv)) (mem_Inter.2 (λ i, i.2.2))) with h1 h1, { exfalso, exact h h1}, { exact h1} }, right, suffices : (⋂ (Z : {Z : set α // is_clopen Z ∧ x ∈ Z}), ↑Z) ⊆ v, { replace this : (⋂ (Z : {Z // is_clopen Z ∧ x ∈ Z}), ↑Z) ≤ v := this, exact (huv.symm.mono this hau).left_le_of_le_sup_left hab }, { apply subset.trans _ (inter_subset_right Z v), apply Inter_subset (λ Z : {Z : set α // is_clopen Z ∧ x ∈ Z}, ↑Z) ⟨Z ∩ v, H2, mem_inter H.2.1 h1⟩ } }, -- Now we find the required Z. We utilize the fact that X \ u ∪ v will be compact, -- so there must be some finite intersection of clopen neighbourhoods of X disjoint to it, -- but a finite intersection of clopen sets is clopen so we let this be our Z. have H1 := (hu.union hv).is_closed_compl.is_compact.inter_Inter_nonempty (λ Z : {Z : set α // is_clopen Z ∧ x ∈ Z}, Z) (λ Z, Z.2.1.2), rw [←not_disjoint_iff_nonempty_inter, imp_not_comm, not_forall] at H1, cases H1 (disjoint_compl_left_iff_subset.2 $ hab.trans $ union_subset_union hau hbv) with Zi H2, refine ⟨(⋂ (U ∈ Zi), subtype.val U), _, _, _⟩, { exact is_clopen_bInter_finset (λ Z hZ, Z.2.1) }, { exact mem_Inter₂.2 (λ Z hZ, Z.2.2) }, { rwa [←disjoint_compl_left_iff_subset, disjoint_iff_inter_eq_empty, ←not_nonempty_iff_eq_empty] } end section profinite /-- A T1 space with a clopen basis is totally separated. -/ lemma totally_separated_space_of_t1_of_basis_clopen [t1_space α] (h : is_topological_basis {s : set α | is_clopen s}) : totally_separated_space α := begin constructor, rintros x - y - hxy, rcases h.mem_nhds_iff.mp (is_open_ne.mem_nhds hxy) with ⟨U, hU, hxU, hyU⟩, exact ⟨U, Uᶜ, hU.is_open, hU.compl.is_open, hxU, λ h, hyU h rfl, (union_compl_self U).superset, disjoint_compl_right⟩ end variables [t2_space α] [compact_space α] /-- A compact Hausdorff space is totally disconnected if and only if it is totally separated, this is also true for locally compact spaces. -/ theorem compact_t2_tot_disc_iff_tot_sep : totally_disconnected_space α ↔ totally_separated_space α := begin split, { intro h, constructor, rintros x - y -, contrapose!, intros hyp, suffices : x ∈ connected_component y, by simpa [totally_disconnected_space_iff_connected_component_singleton.1 h y, mem_singleton_iff], rw [connected_component_eq_Inter_clopen, mem_Inter], rintro ⟨w : set α, hw : is_clopen w, hy : y ∈ w⟩, by_contra hx, exact hyp wᶜ w hw.2.is_open_compl hw.1 hx hy (@is_compl_compl _ w _).symm.codisjoint.top_le disjoint_compl_left }, apply totally_separated_space.totally_disconnected_space, end variables [totally_disconnected_space α] lemma nhds_basis_clopen (x : α) : (𝓝 x).has_basis (λ s : set α, x ∈ s ∧ is_clopen s) id := ⟨λ U, begin split, { have : connected_component x = {x}, from totally_disconnected_space_iff_connected_component_singleton.mp ‹_› x, rw connected_component_eq_Inter_clopen at this, intros hU, let N := {Z // is_clopen Z ∧ x ∈ Z}, rsuffices ⟨⟨s, hs, hs'⟩, hs''⟩ : ∃ Z : N, Z.val ⊆ U, { exact ⟨s, ⟨hs', hs⟩, hs''⟩ }, haveI : nonempty N := ⟨⟨univ, is_clopen_univ, mem_univ x⟩⟩, have hNcl : ∀ Z : N, is_closed Z.val := (λ Z, Z.property.1.2), have hdir : directed superset (λ Z : N, Z.val), { rintros ⟨s, hs, hxs⟩ ⟨t, ht, hxt⟩, exact ⟨⟨s ∩ t, hs.inter ht, ⟨hxs, hxt⟩⟩, inter_subset_left s t, inter_subset_right s t⟩ }, have h_nhd: ∀ y ∈ (⋂ Z : N, Z.val), U ∈ 𝓝 y, { intros y y_in, erw [this, mem_singleton_iff] at y_in, rwa y_in }, exact exists_subset_nhds_of_compact_space hdir hNcl h_nhd }, { rintro ⟨V, ⟨hxV, V_op, -⟩, hUV : V ⊆ U⟩, rw mem_nhds_iff, exact ⟨V, hUV, V_op, hxV⟩ } end⟩ lemma is_topological_basis_clopen : is_topological_basis {s : set α | is_clopen s} := begin apply is_topological_basis_of_open_of_nhds (λ U (hU : is_clopen U), hU.1), intros x U hxU U_op, have : U ∈ 𝓝 x, from is_open.mem_nhds U_op hxU, rcases (nhds_basis_clopen x).mem_iff.mp this with ⟨V, ⟨hxV, hV⟩, hVU : V ⊆ U⟩, use V, tauto end /-- Every member of an open set in a compact Hausdorff totally disconnected space is contained in a clopen set contained in the open set. -/ lemma compact_exists_clopen_in_open {x : α} {U : set α} (is_open : is_open U) (memU : x ∈ U) : ∃ (V : set α) (hV : is_clopen V), x ∈ V ∧ V ⊆ U := (is_topological_basis.mem_nhds_iff is_topological_basis_clopen).1 (is_open.mem_nhds memU) end profinite section locally_compact variables {H : Type*} [topological_space H] [locally_compact_space H] [t2_space H] /-- A locally compact Hausdorff totally disconnected space has a basis with clopen elements. -/ lemma loc_compact_Haus_tot_disc_of_zero_dim [totally_disconnected_space H] : is_topological_basis {s : set H | is_clopen s} := begin refine is_topological_basis_of_open_of_nhds (λ u hu, hu.1) _, rintros x U memU hU, obtain ⟨s, comp, xs, sU⟩ := exists_compact_subset hU memU, obtain ⟨t, h, ht, xt⟩ := mem_interior.1 xs, let u : set s := (coe : s → H)⁻¹' (interior s), have u_open_in_s : is_open u := is_open_interior.preimage continuous_subtype_coe, let X : s := ⟨x, h xt⟩, have Xu : X ∈ u := xs, haveI : compact_space s := is_compact_iff_compact_space.1 comp, obtain ⟨V : set s, clopen_in_s, Vx, V_sub⟩ := compact_exists_clopen_in_open u_open_in_s Xu, have V_clopen : is_clopen ((coe : s → H) '' V), { refine ⟨_, (comp.is_closed.closed_embedding_subtype_coe.closed_iff_image_closed).1 clopen_in_s.2⟩, let v : set u := (coe : u → s)⁻¹' V, have : (coe : u → H) = (coe : s → H) ∘ (coe : u → s) := rfl, have f0 : embedding (coe : u → H) := embedding_subtype_coe.comp embedding_subtype_coe, have f1 : open_embedding (coe : u → H), { refine ⟨f0, _⟩, { have : set.range (coe : u → H) = interior s, { rw [this, set.range_comp, subtype.range_coe, subtype.image_preimage_coe], apply set.inter_eq_self_of_subset_left interior_subset, }, rw this, apply is_open_interior } }, have f2 : is_open v := clopen_in_s.1.preimage continuous_subtype_coe, have f3 : (coe : s → H) '' V = (coe : u → H) '' v, { rw [this, image_comp coe coe, subtype.image_preimage_coe, inter_eq_self_of_subset_left V_sub] }, rw f3, apply f1.is_open_map v f2 }, refine ⟨coe '' V, V_clopen, by simp [Vx, h xt], _⟩, transitivity s, { simp }, assumption end /-- A locally compact Hausdorff space is totally disconnected if and only if it is totally separated. -/ theorem loc_compact_t2_tot_disc_iff_tot_sep : totally_disconnected_space H ↔ totally_separated_space H := begin split, { introI h, exact totally_separated_space_of_t1_of_basis_clopen loc_compact_Haus_tot_disc_of_zero_dim }, apply totally_separated_space.totally_disconnected_space, end end locally_compact /-- `connected_components α` is Hausdorff when `α` is Hausdorff and compact -/ instance connected_components.t2 [t2_space α] [compact_space α] : t2_space (connected_components α) := begin -- Proof follows that of: https://stacks.math.columbia.edu/tag/0900 -- Fix 2 distinct connected components, with points a and b refine ⟨connected_components.surjective_coe.forall₂.2 $ λ a b ne, _⟩, rw connected_components.coe_ne_coe at ne, have h := connected_component_disjoint ne, -- write ↑b as the intersection of all clopen subsets containing it rw [connected_component_eq_Inter_clopen b, disjoint_iff_inter_eq_empty] at h, -- Now we show that this can be reduced to some clopen containing `↑b` being disjoint to `↑a` obtain ⟨U, V, hU, ha, hb, rfl⟩ : ∃ (U : set α) (V : set (connected_components α)), is_clopen U ∧ connected_component a ∩ U = ∅ ∧ connected_component b ⊆ U ∧ coe ⁻¹' V = U, { cases is_closed_connected_component.is_compact.elim_finite_subfamily_closed _ _ h with fin_a ha, swap, { exact λ Z, Z.2.1.2 }, -- This clopen and its complement will separate the connected components of `a` and `b` set U : set α := (⋂ (i : {Z // is_clopen Z ∧ b ∈ Z}) (H : i ∈ fin_a), i), have hU : is_clopen U := is_clopen_bInter_finset (λ i j, i.2.1), exact ⟨U, coe '' U, hU, ha, subset_Inter₂ (λ Z _, Z.2.1.connected_component_subset Z.2.2), (connected_components_preimage_image U).symm ▸ hU.bUnion_connected_component_eq⟩ }, rw connected_components.quotient_map_coe.is_clopen_preimage at hU, refine ⟨Vᶜ, V, hU.compl.is_open, hU.is_open, _, hb mem_connected_component, disjoint_compl_left⟩, exact λ h, flip set.nonempty.ne_empty ha ⟨a, mem_connected_component, h⟩, end
ac9a55c4e08d6907726a47e3a77eb26ee3fbd416
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/doc/examples/Certora2022/ex5.lean
4ee42805ca025f9df5b71a9c8cbeccc194fb822c
[ "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
463
lean
/- Implicit arguments and universe polymorphism -/ def f (α β : Sort u) (a : α) (b : β) : α := a #eval f Nat String 1 "hello" -- 1 def g {α β : Sort u} (a : α) (b : β) : α := a #eval g 1 "hello" def h (a : α) (b : β) : α := a #check g -- ?m.1 → ?m.2 → ?m.1 #check @g -- {α β : Sort u} → α → β → α #check @h -- {α : Sort u_1} → {β : Sort u_2} → α → β → α #check g (α := Nat) (β := String) -- Nat → String → Nat
a627ea52e76e44877c94396d39af7a24f9e04fe2
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/group/with_one/units.lean
9c28cc1249e65c9657b954b01e5591852a344500
[ "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
1,007
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Johan Commelin -/ import algebra.group.with_one.basic import algebra.group_with_zero.units.basic /-! # Isomorphism between a group and the units of itself adjoined with `0` > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. ## Notes This is here to keep `algebra.group_with_zero.units.basic` out of the import requirements of `algebra.order.field.defs`. -/ namespace with_zero /-- Any group is isomorphic to the units of itself adjoined with `0`. -/ def units_with_zero_equiv {α : Type*} [group α] : (with_zero α)ˣ ≃* α := { to_fun := λ a, unzero a.ne_zero, inv_fun := λ a, units.mk0 a coe_ne_zero, left_inv := λ _, units.ext $ by simpa only [coe_unzero], right_inv := λ _, rfl, map_mul' := λ _ _, coe_inj.mp $ by simpa only [coe_unzero, coe_mul] } end with_zero
a876b0979d0bc17d8e6074947544a8ba0ff2d351
a4673261e60b025e2c8c825dfa4ab9108246c32e
/tests/lean/run/match1.lean
3e9c502a83acfd043eda18c5f7a942dbf1f95fe1
[ "Apache-2.0" ]
permissive
jcommelin/lean4
c02dec0cc32c4bccab009285475f265f17d73228
2909313475588cc20ac0436e55548a4502050d0a
refs/heads/master
1,674,129,550,893
1,606,415,348,000
1,606,415,348,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,355
lean
def f (xs : List Nat) : List Bool := xs.map fun | 0 => true | _ => false #eval f [1, 2, 0, 2] theorem ex1 : f [1, 0, 2] = [false, true, false] := rfl #check f def g (xs : List Nat) : List Bool := xs.map <| by { intro | 0 => exact true | _ => exact false } theorem ex2 : g [1, 0, 2] = [false, true, false] := rfl theorem ex3 {p q r : Prop} : p ∨ q → r → (q ∧ r) ∨ (p ∧ r) := by intro | Or.inl hp, h => { apply Or.inr; apply And.intro; assumption; assumption } | Or.inr hq, h => { apply Or.inl; exact ⟨hq, h⟩ } inductive C | mk₁ : Nat → C | mk₂ : Nat → Nat → C def C.x : C → Nat | C.mk₁ x => x | C.mk₂ x _ => x def head : {α : Type} → List α → Option α | _, a::as => some a | _, _ => none theorem ex4 : head [1, 2] = some 1 := rfl def head2 : {α : Type} → List α → Option α := @fun | _, a::as => some a | _, _ => none theorem ex5 : head2 [1, 2] = some 1 := rfl def head3 {α : Type} (xs : List α) : Option α := let rec aux : {α : Type} → List α → Option α | _, a::as => some a | _, _ => none; aux xs theorem ex6 : head3 [1, 2] = some 1 := rfl inductive Vec.{u} (α : Type u) : Nat → Type u | nil : Vec α 0 | cons {n} (head : α) (tail : Vec α n) : Vec α (n+1) def Vec.mapHead1 {α β δ} : {n : Nat} → Vec α n → Vec β n → (α → β → δ) → Option δ | _, nil, nil, f => none | _, cons a as, cons b bs, f => some (f a b) def Vec.mapHead2 {α β δ} : {n : Nat} → Vec α n → Vec β n → (α → β → δ) → Option δ | _, nil, nil, f => none | _, @cons _ n a as, cons b bs, f => some (f a b) def Vec.mapHead3 {α β δ} : {n : Nat} → Vec α n → Vec β n → (α → β → δ) → Option δ | _, nil, nil, f => none | _, cons (tail := as) (head := a), cons b bs, f => some (f a b) inductive Foo | mk₁ (x y z w : Nat) | mk₂ (x y z w : Nat) def Foo.z : Foo → Nat | mk₁ (z := z) .. => z | mk₂ (z := z) .. => z #eval (Foo.mk₁ 10 20 30 40).z theorem ex7 : (Foo.mk₁ 10 20 30 40).z = 30 := rfl def Foo.addY? : Foo × Foo → Option Nat | (mk₁ (y := y₁) .., mk₁ (y := y₂) ..) => some (y₁ + y₂) | _ => none #eval Foo.addY? (Foo.mk₁ 1 2 3 4, Foo.mk₁ 10 20 30 40) theorem ex8 : Foo.addY? (Foo.mk₁ 1 2 3 4, Foo.mk₁ 10 20 30 40) = some 22 := rfl instance {α} : Inhabited (Sigma fun m => Vec α m) := ⟨⟨0, Vec.nil⟩⟩ partial def filter {α} (p : α → Bool) : {n : Nat} → Vec α n → Sigma fun m => Vec α m | _, Vec.nil => ⟨0, Vec.nil⟩ | _, Vec.cons x xs => match p x, filter p xs with | true, ⟨_, ys⟩ => ⟨_, Vec.cons x ys⟩ | false, ys => ys inductive Bla | ofNat (x : Nat) | ofBool (x : Bool) def Bla.optional? : Bla → Option Nat | ofNat x => some x | ofBool _ => none def Bla.isNat? (b : Bla) : Option { x : Nat // optional? b = some x } := match b.optional? with | some y => some ⟨y, rfl⟩ | none => none def foo (b : Bla) : Option Nat := b.optional? theorem fooEq (b : Bla) : foo b = b.optional? := rfl def Bla.isNat2? (b : Bla) : Option { x : Nat // optional? b = some x } := match h:foo b with | some y => some ⟨y, Eq.trans (fooEq b).symm h⟩ | none => none def foo2 (x : Nat) : Nat := match x, rfl : (y : Nat) → x = y → Nat with | 0, h => 0 | x+1, h => 1
b988d61b263dab7cf8dd84db7b2c760b92e832cd
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/measure_theory/probability_mass_function/monad.lean
4ad03b41afe9cbbe4ccbf57078bf7ad07eed0dc0
[ "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
14,340
lean
/- Copyright (c) 2020 Devon Tuma. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Devon Tuma -/ import measure_theory.probability_mass_function.basic /-! # Monad Operations for Probability Mass Functions This file constructs two operations on `pmf` that give it a monad structure. `pure a` is the distribution where a single value `a` has probability `1`. `bind pa pb : pmf β` is the distribution given by sampling `a : α` from `pa : pmf α`, and then sampling from `pb a : pmf β` to get a final result `b : β`. `bind_on_support` generalizes `bind` to allow binding to a partial function, so that the second argument only needs to be defined on the support of the first argument. -/ noncomputable theory variables {α β γ : Type*} open_locale classical big_operators nnreal ennreal namespace pmf section pure /-- The pure `pmf` is the `pmf` where all the mass lies in one point. The value of `pure a` is `1` at `a` and `0` elsewhere. -/ def pure (a : α) : pmf α := ⟨λ a', if a' = a then 1 else 0, has_sum_ite_eq _ _⟩ variables (a a' : α) @[simp] lemma pure_apply : pure a a' = (if a' = a then 1 else 0) := rfl @[simp] lemma support_pure : (pure a).support = {a} := set.ext (λ a', by simp [mem_support_iff]) lemma mem_support_pure_iff: a' ∈ (pure a).support ↔ a' = a := by simp instance [inhabited α] : inhabited (pmf α) := ⟨pure default⟩ section measure variable (s : set α) lemma to_outer_measure_pure_apply : (pure a).to_outer_measure s = if a ∈ s then 1 else 0 := begin refine (to_outer_measure_apply' (pure a) s).trans _, split_ifs with ha ha, { refine ennreal.coe_eq_one.2 ((tsum_congr (λ b, _)).trans (tsum_ite_eq a 1)), exact ite_eq_left_iff.2 (λ hb, symm (ite_eq_right_iff.2 (λ h, (hb $ h.symm ▸ ha).elim))) }, { refine ennreal.coe_eq_zero.2 ((tsum_congr (λ b, _)).trans (tsum_zero)), exact ite_eq_right_iff.2 (λ hb, ite_eq_right_iff.2 (λ h, (ha $ h ▸ hb).elim)) } end /-- The measure of a set under `pure a` is `1` for sets containing `a` and `0` otherwise -/ lemma to_measure_pure_apply [measurable_space α] (hs : measurable_set s) : (pure a).to_measure s = if a ∈ s then 1 else 0 := (to_measure_apply_eq_to_outer_measure_apply (pure a) s hs).trans (to_outer_measure_pure_apply a s) end measure end pure section bind protected lemma bind.summable (p : pmf α) (f : α → pmf β) (b : β) : summable (λ a : α, p a * f a b) := begin refine nnreal.summable_of_le (assume a, _) p.summable_coe, suffices : p a * f a b ≤ p a * 1, { simpa }, exact mul_le_mul_of_nonneg_left ((f a).coe_le_one _) (p a).2 end /-- The monadic bind operation for `pmf`. -/ def bind (p : pmf α) (f : α → pmf β) : pmf β := ⟨λ b, ∑'a, p a * f a b, begin apply ennreal.has_sum_coe.1, simp only [ennreal.coe_tsum (bind.summable p f _)], rw [ennreal.summable.has_sum_iff, ennreal.tsum_comm], simp [ennreal.tsum_mul_left, (ennreal.coe_tsum (f _).summable_coe).symm, (ennreal.coe_tsum p.summable_coe).symm] end⟩ variables (p : pmf α) (f : α → pmf β) (g : β → pmf γ) @[simp] lemma bind_apply (b : β) : p.bind f b = ∑'a, p a * f a b := rfl @[simp] lemma support_bind : (p.bind f).support = {b | ∃ a ∈ p.support, b ∈ (f a).support} := set.ext (λ b, by simp [mem_support_iff, tsum_eq_zero_iff (bind.summable p f b), not_or_distrib]) lemma mem_support_bind_iff (b : β) : b ∈ (p.bind f).support ↔ ∃ a ∈ p.support, b ∈ (f a).support := by simp lemma coe_bind_apply (b : β) : (p.bind f b : ℝ≥0∞) = ∑'a, p a * f a b := eq.trans (ennreal.coe_tsum $ bind.summable p f b) $ by simp @[simp] lemma pure_bind (a : α) : (pure a).bind f = f a := have ∀ b a', ite (a' = a) 1 0 * f a' b = ite (a' = a) (f a b) 0, from assume b a', by split_ifs; simp; subst h; simp, by ext b; simp [this] @[simp] lemma bind_pure : p.bind pure = p := have ∀ a a', (p a * ite (a' = a) 1 0) = ite (a = a') (p a') 0, from assume a a', begin split_ifs; try { subst a }; try { subst a' }; simp * at * end, by ext b; simp [this] @[simp] lemma bind_bind : (p.bind f).bind g = p.bind (λ a, (f a).bind g) := begin ext1 b, simp only [ennreal.coe_eq_coe.symm, coe_bind_apply, ennreal.tsum_mul_left.symm, ennreal.tsum_mul_right.symm], rw [ennreal.tsum_comm], simp [mul_assoc, mul_left_comm, mul_comm] end lemma bind_comm (p : pmf α) (q : pmf β) (f : α → β → pmf γ) : p.bind (λ a, q.bind (f a)) = q.bind (λ b, p.bind (λ a, f a b)) := begin ext1 b, simp only [ennreal.coe_eq_coe.symm, coe_bind_apply, ennreal.tsum_mul_left.symm, ennreal.tsum_mul_right.symm], rw [ennreal.tsum_comm], simp [mul_assoc, mul_left_comm, mul_comm] end section measure variable (s : set β) lemma to_outer_measure_bind_apply : (p.bind f).to_outer_measure s = ∑' (a : α), (p a : ℝ≥0∞) * (f a).to_outer_measure s := calc (p.bind f).to_outer_measure s = ∑' (b : β), if b ∈ s then (↑(∑' (a : α), p a * f a b) : ℝ≥0∞) else 0 : by simp [to_outer_measure_apply, set.indicator_apply] ... = ∑' (b : β), ↑(∑' (a : α), p a * (if b ∈ s then f a b else 0)) : tsum_congr (λ b, by split_ifs; simp) ... = ∑' (b : β) (a : α), ↑(p a * (if b ∈ s then f a b else 0)) : tsum_congr (λ b, ennreal.coe_tsum $ nnreal.summable_of_le (by split_ifs; simp) (bind.summable p f b)) ... = ∑' (a : α) (b : β), ↑(p a) * ↑(if b ∈ s then f a b else 0) : ennreal.tsum_comm.trans (tsum_congr $ λ a, tsum_congr $ λ b, ennreal.coe_mul) ... = ∑' (a : α), ↑(p a) * ∑' (b : β), ↑(if b ∈ s then f a b else 0) : tsum_congr (λ a, ennreal.tsum_mul_left) ... = ∑' (a : α), ↑(p a) * ∑' (b : β), if b ∈ s then ↑(f a b) else (0 : ℝ≥0∞) : tsum_congr (λ a, congr_arg (λ x, ↑(p a) * x) $ tsum_congr (λ b, by split_ifs; refl)) ... = ∑' (a : α), ↑(p a) * (f a).to_outer_measure s : tsum_congr (λ a, by rw [to_outer_measure_apply, set.indicator]) /-- The measure of a set under `p.bind f` is the sum over `a : α` of the probability of `a` under `p` times the measure of the set under `f a` -/ lemma to_measure_bind_apply [measurable_space β] (hs : measurable_set s) : (p.bind f).to_measure s = ∑' (a : α), (p a : ℝ≥0∞) * (f a).to_measure s := (to_measure_apply_eq_to_outer_measure_apply (p.bind f) s hs).trans ((to_outer_measure_bind_apply p f s).trans (tsum_congr (λ a, congr_arg (λ x, p a * x) (to_measure_apply_eq_to_outer_measure_apply (f a) s hs).symm))) end measure end bind instance : monad pmf := { pure := λ A a, pure a, bind := λ A B pa pb, pa.bind pb } section bind_on_support protected lemma bind_on_support.summable (p : pmf α) (f : Π a ∈ p.support, pmf β) (b : β) : summable (λ a : α, p a * if h : p a = 0 then 0 else f a h b) := begin refine nnreal.summable_of_le (assume a, _) p.summable_coe, split_ifs, { refine (mul_zero (p a)).symm ▸ le_of_eq h.symm }, { suffices : p a * f a h b ≤ p a * 1, { simpa }, exact mul_le_mul_of_nonneg_left ((f a h).coe_le_one _) (p a).2 } end /-- Generalized version of `bind` allowing `f` to only be defined on the support of `p`. `p.bind f` is equivalent to `p.bind_on_support (λ a _, f a)`, see `bind_on_support_eq_bind` -/ def bind_on_support (p : pmf α) (f : Π a ∈ p.support, pmf β) : pmf β := ⟨λ b, ∑' a, p a * if h : p a = 0 then 0 else f a h b, ennreal.has_sum_coe.1 begin simp only [ennreal.coe_tsum (bind_on_support.summable p f _)], rw [ennreal.summable.has_sum_iff, ennreal.tsum_comm], simp only [ennreal.coe_mul, ennreal.coe_one, ennreal.tsum_mul_left], have : ∑' (a : α), (p a : ennreal) = 1 := by simp only [←ennreal.coe_tsum p.summable_coe, ennreal.coe_one, tsum_coe], refine trans (tsum_congr (λ a, _)) this, split_ifs with h, { simp [h] }, { simp [← ennreal.coe_tsum (f a h).summable_coe, (f a h).tsum_coe] } end⟩ variables {p : pmf α} (f : Π a ∈ p.support, pmf β) @[simp] lemma bind_on_support_apply (b : β) : p.bind_on_support f b = ∑' a, p a * if h : p a = 0 then 0 else f a h b := rfl @[simp] lemma support_bind_on_support : (p.bind_on_support f).support = {b | ∃ (a : α) (h : a ∈ p.support), b ∈ (f a h).support} := begin refine set.ext (λ b, _), simp only [tsum_eq_zero_iff (bind_on_support.summable p f b), not_or_distrib, mem_support_iff, bind_on_support_apply, ne.def, not_forall, mul_eq_zero], exact ⟨λ hb, let ⟨a, ⟨ha, ha'⟩⟩ := hb in ⟨a, ha, by simpa [ha] using ha'⟩, λ hb, let ⟨a, ha, ha'⟩ := hb in ⟨a, ⟨ha, by simpa [(mem_support_iff _ a).1 ha] using ha'⟩⟩⟩ end lemma mem_support_bind_on_support_iff (b : β) : b ∈ (p.bind_on_support f).support ↔ ∃ (a : α) (h : a ∈ p.support), b ∈ (f a h).support := by simp /-- `bind_on_support` reduces to `bind` if `f` doesn't depend on the additional hypothesis -/ @[simp] lemma bind_on_support_eq_bind (p : pmf α) (f : α → pmf β) : p.bind_on_support (λ a _, f a) = p.bind f := begin ext b, simp only [bind_on_support_apply (λ a _, f a), p.bind_apply f, dite_eq_ite, nnreal.coe_eq, mul_ite, mul_zero], refine congr_arg _ (funext (λ a, _)), split_ifs with h; simp [h], end lemma coe_bind_on_support_apply (b : β) : (p.bind_on_support f b : ℝ≥0∞) = ∑' a, p a * if h : p a = 0 then 0 else f a h b := by simp only [bind_on_support_apply, ennreal.coe_tsum (bind_on_support.summable p f b), dite_cast, ennreal.coe_mul, ennreal.coe_zero] lemma bind_on_support_eq_zero_iff (b : β) : p.bind_on_support f b = 0 ↔ ∀ a (ha : p a ≠ 0), f a ha b = 0 := begin simp only [bind_on_support_apply, tsum_eq_zero_iff (bind_on_support.summable p f b), mul_eq_zero, or_iff_not_imp_left], exact ⟨λ h a ha, trans (dif_neg ha).symm (h a ha), λ h a ha, trans (dif_neg ha) (h a ha)⟩, end @[simp] lemma pure_bind_on_support (a : α) (f : Π (a' : α) (ha : a' ∈ (pure a).support), pmf β) : (pure a).bind_on_support f = f a ((mem_support_pure_iff a a).mpr rfl) := begin refine pmf.ext (λ b, _), simp only [nnreal.coe_eq, bind_on_support_apply, pure_apply], refine trans (tsum_congr (λ a', _)) (tsum_ite_eq a _), by_cases h : (a' = a); simp [h], end lemma bind_on_support_pure (p : pmf α) : p.bind_on_support (λ a _, pure a) = p := by simp only [pmf.bind_pure, pmf.bind_on_support_eq_bind] @[simp] lemma bind_on_support_bind_on_support (p : pmf α) (f : ∀ a ∈ p.support, pmf β) (g : ∀ (b ∈ (p.bind_on_support f).support), pmf γ) : (p.bind_on_support f).bind_on_support g = p.bind_on_support (λ a ha, (f a ha).bind_on_support (λ b hb, g b ((mem_support_bind_on_support_iff f b).mpr ⟨a, ha, hb⟩))) := begin refine pmf.ext (λ a, _), simp only [ennreal.coe_eq_coe.symm, coe_bind_on_support_apply, ← tsum_dite_right, ennreal.tsum_mul_left.symm, ennreal.tsum_mul_right.symm], simp only [ennreal.tsum_eq_zero, ennreal.coe_eq_coe, ennreal.coe_eq_zero, ennreal.coe_zero, dite_eq_left_iff, mul_eq_zero], refine ennreal.tsum_comm.trans (tsum_congr (λ a', tsum_congr (λ b, _))), split_ifs, any_goals { ring1 }, { have := h_1 a', simp [h] at this, contradiction }, { simp [h_2], }, end lemma bind_on_support_comm (p : pmf α) (q : pmf β) (f : ∀ (a ∈ p.support) (b ∈ q.support), pmf γ) : p.bind_on_support (λ a ha, q.bind_on_support (f a ha)) = q.bind_on_support (λ b hb, p.bind_on_support (λ a ha, f a ha b hb)) := begin apply pmf.ext, rintro c, simp only [ennreal.coe_eq_coe.symm, coe_bind_on_support_apply, ← tsum_dite_right, ennreal.tsum_mul_left.symm, ennreal.tsum_mul_right.symm], refine trans (ennreal.tsum_comm) (tsum_congr (λ b, tsum_congr (λ a, _))), split_ifs with h1 h2 h2; ring, end section measure variable (s : set β) lemma to_outer_measure_bind_on_support_apply : (p.bind_on_support f).to_outer_measure s = ∑' (a : α), (p a : ℝ≥0) * if h : p a = 0 then 0 else (f a h).to_outer_measure s := let g : α → β → ℝ≥0 := λ a b, if h : p a = 0 then 0 else f a h b in calc (p.bind_on_support f).to_outer_measure s = ∑' (b : β), if b ∈ s then ↑(∑' (a : α), p a * g a b) else 0 : by simp [to_outer_measure_apply, set.indicator_apply] ... = ∑' (b : β), ↑(∑' (a : α), p a * (if b ∈ s then g a b else 0)) : tsum_congr (λ b, by split_ifs; simp) ... = ∑' (b : β) (a : α), ↑(p a * (if b ∈ s then g a b else 0)) : tsum_congr (λ b, ennreal.coe_tsum $ nnreal.summable_of_le (by split_ifs; simp) (bind_on_support.summable p f b)) ... = ∑' (a : α) (b : β), ↑(p a) * ↑(if b ∈ s then g a b else 0) : ennreal.tsum_comm.trans (tsum_congr $ λ a, tsum_congr $ λ b, ennreal.coe_mul) ... = ∑' (a : α), ↑(p a) * ∑' (b : β), ↑(if b ∈ s then g a b else 0) : tsum_congr (λ a, ennreal.tsum_mul_left) ... = ∑' (a : α), ↑(p a) * ∑' (b : β), if b ∈ s then ↑(g a b) else (0 : ℝ≥0∞) : tsum_congr (λ a, congr_arg (λ x, ↑(p a) * x) $ tsum_congr (λ b, by split_ifs; refl)) ... = ∑' (a : α), ↑(p a) * if h : p a = 0 then 0 else (f a h).to_outer_measure s : tsum_congr (λ a, congr_arg (has_mul.mul ↑(p a)) begin split_ifs with h h, { exact ennreal.tsum_eq_zero.mpr (λ x, (by simp [g, h] : (0 : ℝ≥0∞) = ↑(g a x)) ▸ (if_t_t (x ∈ s) 0)) }, { simp [to_outer_measure_apply, g, h, set.indicator_apply] } end) /-- The measure of a set under `p.bind_on_support f` is the sum over `a : α` of the probability of `a` under `p` times the measure of the set under `f a _`. The additional if statement is needed since `f` is only a partial function -/ lemma to_measure_bind_on_support_apply [measurable_space β] (hs : measurable_set s) : (p.bind_on_support f).to_measure s = ∑' (a : α), (p a : ℝ≥0∞) * if h : p a = 0 then 0 else (f a h).to_measure s := (to_measure_apply_eq_to_outer_measure_apply (p.bind_on_support f) s hs).trans ((to_outer_measure_bind_on_support_apply f s).trans (tsum_congr $ λ a, congr_arg (has_mul.mul ↑(p a)) (congr_arg (dite (p a = 0) (λ _, 0)) $ funext (λ h, symm $ to_measure_apply_eq_to_outer_measure_apply (f a h) s hs)))) end measure end bind_on_support end pmf
36a2c9b30f8055661ef49ec887b44a3d4135e525
618003631150032a5676f229d13a079ac875ff77
/src/topology/algebra/group_completion.lean
3918cc54bb02a44a671f1514aa8cf1c588897fd3
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
4,136
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Johannes Hölzl Completion of topological groups: -/ import topology.uniform_space.completion import topology.algebra.uniform_group noncomputable theory universes u v section group open uniform_space Cauchy filter set variables {α : Type u} [uniform_space α] instance [has_zero α] : has_zero (completion α) := ⟨(0 : α)⟩ instance [has_neg α] : has_neg (completion α) := ⟨completion.map (λa, -a : α → α)⟩ instance [has_add α] : has_add (completion α) := ⟨completion.map₂ (+)⟩ -- TODO: switch sides once #1103 is fixed @[norm_cast] lemma uniform_space.completion.coe_zero [has_zero α] : ((0 : α) : completion α) = 0 := rfl end group namespace uniform_space.completion section uniform_add_group open uniform_space uniform_space.completion variables {α : Type*} [uniform_space α] [add_group α] [uniform_add_group α] @[norm_cast] lemma coe_neg (a : α) : ((- a : α) : completion α) = - a := (map_coe uniform_continuous_neg a).symm @[norm_cast] lemma coe_add (a b : α) : ((a + b : α) : completion α) = a + b := (map₂_coe_coe a b (+) uniform_continuous_add).symm instance : add_group (completion α) := { zero_add := assume a, completion.induction_on a (is_closed_eq (continuous_map₂ continuous_const continuous_id) continuous_id) (assume a, show 0 + (a : completion α) = a, by rw_mod_cast zero_add), add_zero := assume a, completion.induction_on a (is_closed_eq (continuous_map₂ continuous_id continuous_const) continuous_id) (assume a, show (a : completion α) + 0 = a, by rw_mod_cast add_zero), add_left_neg := assume a, completion.induction_on a (is_closed_eq (continuous_map₂ completion.continuous_map continuous_id) continuous_const) (assume a, show - (a : completion α) + a = 0, by { rw_mod_cast add_left_neg, refl }), add_assoc := assume a b c, completion.induction_on₃ a b c (is_closed_eq (continuous_map₂ (continuous_map₂ continuous_fst (continuous_fst.comp continuous_snd)) (continuous_snd.comp continuous_snd)) (continuous_map₂ continuous_fst (continuous_map₂ (continuous_fst.comp continuous_snd) (continuous_snd.comp continuous_snd)))) (assume a b c, show (a : completion α) + b + c = a + (b + c), by repeat { rw_mod_cast add_assoc }), .. completion.has_zero, .. completion.has_neg, ..completion.has_add } instance : uniform_add_group (completion α) := ⟨(uniform_continuous_map₂ (+)).bicompl uniform_continuous_id uniform_continuous_map⟩ instance is_add_group_hom_coe : is_add_group_hom (coe : α → completion α) := { map_add := coe_add } variables {β : Type v} [uniform_space β] [add_group β] [uniform_add_group β] lemma is_add_group_hom_extension [complete_space β] [separated β] {f : α → β} [is_add_group_hom f] (hf : continuous f) : is_add_group_hom (completion.extension f) := have hf : uniform_continuous f, from uniform_continuous_of_continuous hf, { map_add := assume a b, completion.induction_on₂ a b (is_closed_eq (continuous_extension.comp continuous_add) ((continuous_extension.comp continuous_fst).add (continuous_extension.comp continuous_snd))) (assume a b, by rw_mod_cast [extension_coe hf, extension_coe hf, extension_coe hf, is_add_hom.map_add f]) } lemma is_add_group_hom_map {f : α → β} [is_add_group_hom f] (hf : continuous f) : is_add_group_hom (completion.map f) := @is_add_group_hom_extension _ _ _ _ _ _ _ _ _ _ _ (is_add_group_hom.comp _ _) ((continuous_coe _).comp hf) instance {α : Type u} [uniform_space α] [add_comm_group α] [uniform_add_group α] : add_comm_group (completion α) := { add_comm := assume a b, completion.induction_on₂ a b (is_closed_eq (continuous_map₂ continuous_fst continuous_snd) (continuous_map₂ continuous_snd continuous_fst)) (assume x y, by { change ↑x + ↑y = ↑y + ↑x, rw [← coe_add, ← coe_add, add_comm]}), .. completion.add_group } end uniform_add_group end uniform_space.completion
fc86743a821636d278f70de6e86163dff229344a
9b9a16fa2cb737daee6b2785474678b6fa91d6d4
/src/category_theory/yoneda.lean
5e5fd54c2c407c28062efeaea5f417a611f30514
[ "Apache-2.0" ]
permissive
johoelzl/mathlib
253f46daa30b644d011e8e119025b01ad69735c4
592e3c7a2dfbd5826919b4605559d35d4d75938f
refs/heads/master
1,625,657,216,488
1,551,374,946,000
1,551,374,946,000
98,915,829
0
0
Apache-2.0
1,522,917,267,000
1,501,524,499,000
Lean
UTF-8
Lean
false
false
6,473
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison /- The Yoneda embedding, as a functor `yoneda : C ⥤ (Cᵒᵖ ⥤ Type v₁)`, along with an instance that it is `fully_faithful`. Also the Yoneda lemma, `yoneda_lemma : (yoneda_pairing C) ≅ (yoneda_evaluation C)`. -/ import category_theory.natural_transformation import category_theory.opposites import category_theory.types import category_theory.fully_faithful import category_theory.natural_isomorphism namespace category_theory universes v₁ u₁ u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation variables {C : Type u₁} [𝒞 : category.{v₁} C] include 𝒞 def yoneda : C ⥤ (Cᵒᵖ ⥤ Type v₁) := { obj := λ X, { obj := λ Y, unop Y ⟶ X, map := λ Y Y' f g, f.unop ≫ g, map_comp' := λ _ _ _ f g, begin ext1, dsimp at *, erw [category.assoc] end, map_id' := λ Y, begin ext1, dsimp at *, erw [category.id_comp] end }, map := λ X X' f, { app := λ Y g, g ≫ f } } def coyoneda : Cᵒᵖ ⥤ (C ⥤ Type v₁) := { obj := λ X, { obj := λ Y, unop X ⟶ Y, map := λ Y Y' f g, g ≫ f, map_comp' := λ _ _ _ f g, begin ext1, dsimp at *, erw [category.assoc] end, map_id' := λ Y, begin ext1, dsimp at *, erw [category.comp_id] end }, map := λ X X' f, { app := λ Y g, f.unop ≫ g }, map_comp' := λ _ _ _ f g, begin ext1, ext1, dsimp at *, erw [category.assoc] end, map_id' := λ X, begin ext1, ext1, dsimp at *, erw [category.id_comp] end } namespace yoneda @[simp] lemma obj_obj (X : C) (Y : Cᵒᵖ) : (yoneda.obj X).obj Y = (unop Y ⟶ X) := rfl @[simp] lemma obj_map (X : C) {Y Y' : Cᵒᵖ} (f : Y ⟶ Y') : (yoneda.obj X).map f = λ g, f.unop ≫ g := rfl @[simp] lemma map_app {X X' : C} (f : X ⟶ X') (Y : Cᵒᵖ) : (yoneda.map f).app Y = λ g, g ≫ f := rfl lemma obj_map_id {X Y : C} (f : op X ⟶ op Y) : ((@yoneda C _).obj X).map f (𝟙 X) = ((@yoneda C _).map f.unop).app (op Y) (𝟙 Y) := by obviously @[simp] lemma naturality {X Y : C} (α : yoneda.obj X ⟶ yoneda.obj Y) {Z Z' : C} (f : Z ⟶ Z') (h : Z' ⟶ X) : f ≫ α.app (op Z') h = α.app (op Z) (f ≫ h) := begin erw [functor_to_types.naturality], refl end instance yoneda_fully_faithful : fully_faithful (@yoneda C _) := { preimage := λ X Y f, (f.app (op X)) (𝟙 X), injectivity' := λ X Y f g p, begin injection p with h, convert (congr_fun (congr_fun h (op X)) (𝟙 X)); dsimp; simp, end } /-- Extensionality via Yoneda. The typical usage would be ``` -- Goal is `X ≅ Y` apply yoneda.ext, -- Goals are now functions `(Z ⟶ X) → (Z ⟶ Y)`, `(Z ⟶ Y) → (Z ⟶ X)`, and the fact that these functions are inverses and natural in `Z`. ``` -/ def ext (X Y : C) (p : Π {Z : C}, (Z ⟶ X) → (Z ⟶ Y)) (q : Π {Z : C}, (Z ⟶ Y) → (Z ⟶ X)) (h₁ : Π {Z : C} (f : Z ⟶ X), q (p f) = f) (h₂ : Π {Z : C} (f : Z ⟶ Y), p (q f) = f) (n : Π {Z Z' : C} (f : Z' ⟶ Z) (g : Z ⟶ X), p (f ≫ g) = f ≫ p g) : X ≅ Y := @preimage_iso _ _ _ _ yoneda _ _ _ _ (nat_iso.of_components (λ Z, { hom := p, inv := q, }) (by tidy)) -- We need to help typeclass inference with some awkward universe levels here. instance prod_category_instance_1 : category ((Cᵒᵖ ⥤ Type v₁) × Cᵒᵖ) := category_theory.prod.{(max u₁ v₁) v₁} (Cᵒᵖ ⥤ Type v₁) Cᵒᵖ instance prod_category_instance_2 : category (Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁)) := category_theory.prod.{v₁ (max u₁ v₁)} Cᵒᵖ (Cᵒᵖ ⥤ Type v₁) end yoneda namespace coyoneda @[simp] lemma obj_obj (X : Cᵒᵖ) (Y : C) : (coyoneda.obj X).obj Y = (unop X ⟶ Y) := rfl @[simp] lemma obj_map {X' X : C} (f : X' ⟶ X) (Y : Cᵒᵖ) : (coyoneda.obj Y).map f = λ g, g ≫ f := rfl @[simp] lemma map_app (X : C) {Y Y' : Cᵒᵖ} (f : Y ⟶ Y') : (coyoneda.map f).app X = λ g, f.unop ≫ g := rfl end coyoneda class representable (F : Cᵒᵖ ⥤ Type v₁) := (X : C) (w : yoneda.obj X ≅ F) variables (C) open yoneda def yoneda_evaluation : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁) ⥤ Type (max u₁ v₁) := evaluation_uncurried Cᵒᵖ (Type v₁) ⋙ ulift_functor.{u₁} @[simp] lemma yoneda_evaluation_map_down (P Q : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁)) (α : P ⟶ Q) (x : (yoneda_evaluation C).obj P) : ((yoneda_evaluation C).map α x).down = α.2.app Q.1 (P.2.map α.1 x.down) := rfl def yoneda_pairing : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁) ⥤ Type (max u₁ v₁) := functor.prod yoneda.op (functor.id (Cᵒᵖ ⥤ Type v₁)) ⋙ functor.hom (Cᵒᵖ ⥤ Type v₁) @[simp] lemma yoneda_pairing_map (P Q : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁)) (α : P ⟶ Q) (β : (yoneda_pairing C).obj P) : (yoneda_pairing C).map α β = yoneda.map α.1.unop ≫ β ≫ α.2 := rfl def yoneda_lemma : yoneda_pairing C ≅ yoneda_evaluation C := { hom := { app := λ F x, ulift.up ((x.app F.1) (𝟙 (unop F.1))), naturality' := begin intros X Y f, ext1, ext1, cases f, cases Y, cases X, dsimp at *, simp at *, erw [←functor_to_types.naturality, obj_map_id, functor_to_types.naturality, functor_to_types.map_id] end }, inv := { app := λ F x, { app := λ X a, (F.2.map a.op) x.down, naturality' := begin intros X Y f, ext1, cases x, cases F, dsimp at *, erw [functor_to_types.map_comp] end }, naturality' := begin intros X Y f, ext1, ext1, ext1, cases x, cases f, cases Y, cases X, dsimp at *, erw [←functor_to_types.naturality, functor_to_types.map_comp] end }, hom_inv_id' := begin ext1, ext1, ext1, ext1, cases X, dsimp at *, erw [←functor_to_types.naturality, obj_map_id, functor_to_types.naturality, functor_to_types.map_id], refl, end, inv_hom_id' := begin ext1, ext1, ext1, cases x, cases X, dsimp at *, erw [functor_to_types.map_id] end }. variables {C} @[simp] def yoneda_sections (X : C) (F : Cᵒᵖ ⥤ Type v₁) : (yoneda.obj X ⟹ F) ≅ ulift.{u₁} (F.obj (op X)) := nat_iso.app (yoneda_lemma C) (op X, F) omit 𝒞 @[simp] def yoneda_sections_small {C : Type u₁} [small_category C] (X : C) (F : Cᵒᵖ ⥤ Type u₁) : (yoneda.obj X ⟹ F) ≅ F.obj (op X) := yoneda_sections X F ≪≫ ulift_trivial _ end category_theory
c3c372a0ebac945c677edf8fef4270ae2f26adb0
48eee836fdb5c613d9a20741c17db44c8e12e61c
/src/util/meta/expr.lean
277038a86703e608324aec02923d3aff9439bcef
[ "Apache-2.0" ]
permissive
fgdorais/lean-universal
06430443a4abe51e303e602684c2977d1f5c0834
9259b0f7fb3aa83a9e0a7a3eaa44c262e42cc9b1
refs/heads/master
1,592,479,744,136
1,589,473,399,000
1,589,473,399,000
196,287,552
1
1
null
null
null
null
UTF-8
Lean
false
false
3,950
lean
-- Copyright © 2019 François G. Dorais. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. import .name import .level namespace expr meta def mk_list (l : level) (t : expr) : list expr → expr | [] := expr.app (expr.const `list.nil [l]) t | (x::xs) := let e := mk_list xs in expr.mk_app (expr.const `list.cons [l]) [t,x,e] meta def prop_sort : expr := sort level.zero meta def type_sort : expr := sort level.one meta def mk_local (pfx : name) : name → binder_info → expr → expr := λ n b t, expr.local_const (pfx ++ n) n b t meta def mk_locals (pfx : name) (b : binder_info) : list (name × expr) → list expr | [] := [] | ((n,t)::nts) := mk_local pfx n b t :: mk_locals nts meta def mk_num_locals (pfx root : name) (base : nat) : list expr → binder_info → list expr := λ ls bi, let ls : list (name × expr) := list.zip (mk_num_names root base ls.length) ls in mk_locals pfx bi ls meta def mk_sub_locals (pfx root : name) (base : nat) : list expr → binder_info → list expr := λ ls bi, let ls : list (name × expr) := list.zip (mk_sub_names root base ls.length) ls in mk_locals pfx bi ls meta def mk_vars : list nat → list expr := list.map mk_var meta def mk_num_vars (len : nat) (fst : nat := 0) : list expr := mk_vars $ list.range' len fst meta def mk_sort : level → expr := expr.sort meta def mk_sorts : list level → list expr := list.map expr.sort meta def bind_lambdas : expr → list expr → expr | e [] := e | e (p::ps) := bind_lambda (bind_lambdas e ps) p meta def bind_pis : expr → list expr → expr | e [] := e | e (p::ps) := bind_pi (bind_pis e ps) p meta def num_pis {elab : opt_param bool tt} (root : name) (base : nat) (bi : binder_info) : list (expr elab) → expr elab → expr elab | [] e := e | (t::ts) e := expr.pi (mk_num_name root (base + ts.length)) bi t $ num_pis ts e meta def num_lambdas {elab : opt_param bool tt} (root : name) (base : nat) (bi : binder_info) : list (expr elab) → expr elab → expr elab | [] e := e | (t::ts) e := expr.lam (mk_num_name root (base + ts.length)) bi t $ num_lambdas ts e meta def sub_pis {elab : opt_param bool tt} (root : name) (base : nat) (bi : binder_info) : list (expr elab) → expr elab → expr elab | [] e := e | (t::ts) e := expr.pi (mk_sub_name root (base + ts.length)) bi t $ sub_pis ts e meta def sub_lambdas {elab : opt_param bool tt} (root : name) (base : nat) (bi : binder_info) : list (expr elab) → expr elab → expr elab | [] e := e | (t::ts) e := expr.lam (mk_sub_name root (base + ts.length)) bi t $ sub_lambdas ts e meta def sorts {elab : opt_param bool tt} : list level → list (expr elab) := list.map sort meta def num_sorts {elab : opt_param bool tt} (root : name) (base : nat) : nat → list (expr elab) := λ n, expr.sorts $ level.num_params root base n meta def sub_sorts {elab : opt_param bool tt} (root : name) (base : nat) : nat → list (expr elab) := λ n, expr.sorts $ level.sub_params root base n meta def app_beta : expr → expr → expr | (expr.lam _ _ _ e) := instantiate_var e | e := expr.app e meta def mk_app_beta : expr → list expr → expr | (expr.lam _ _ _ e) (x::xs) := mk_app_beta (instantiate_var e x) xs | e xs := mk_app e xs end expr namespace tactic meta def mk_locals (root : name) (base : nat) (bi : binder_info) : list expr → tactic (list expr) | [] := return [] | (x::xs) := mk_locals xs >>= λ ls, mk_local' (mk_num_name root (base + xs.length)) bi x >>= λ l, return (l::ls) meta def get_locals (root : name) (base : nat) : nat → tactic (list expr) | 0 := return [] | (n+1) := get_locals n >>= λ xs, get_local (mk_num_name root (base + xs.length)) >>= λ x, return (x::xs) meta def mk_local_lambdas : expr → tactic (list expr × expr) | (expr.lam n bi d b) := do p ← mk_local' n bi d, e ← whnf (expr.instantiate_var b p), (ps, r) ← mk_local_lambdas e, return ((p :: ps), r) | e := return ([], e) end tactic
8d2e931f227a62b275b9584a064c1c17ddd635c1
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/category/CommRing/default_auto.lean
a50f545fe573b2628e13ac11d756a4500d3cc341
[]
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
266
lean
import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.category.CommRing.adjunctions import Mathlib.algebra.category.CommRing.limits import Mathlib.algebra.category.CommRing.colimits import Mathlib.PostPort namespace Mathlib end Mathlib
025514dcb10cc8b43bd9789fd2e1272f6767e423
3f7026ea8bef0825ca0339a275c03b911baef64d
/src/category_theory/adjunction/basic.lean
09ca83c9912a38413f9fc0b66a7dbda8961e91cc
[ "Apache-2.0" ]
permissive
rspencer01/mathlib
b1e3afa5c121362ef0881012cc116513ab09f18c
c7d36292c6b9234dc40143c16288932ae38fdc12
refs/heads/master
1,595,010,346,708
1,567,511,503,000
1,567,511,503,000
206,071,681
0
0
Apache-2.0
1,567,513,643,000
1,567,513,643,000
null
UTF-8
Lean
false
false
10,256
lean
/- Copyright (c) 2019 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Johan Commelin -/ import category_theory.equivalence import data.equiv.basic namespace category_theory open category universes v₁ v₂ v₃ u₁ u₂ u₃ -- declare the `v`'s first; see `category_theory.category` for an explanation local attribute [elab_simple] whisker_left whisker_right variables {C : Type u₁} [𝒞 : category.{v₁} C] {D : Type u₂} [𝒟 : category.{v₂} D] include 𝒞 𝒟 /-- `F ⊣ G` represents the data of an adjunction between two functors `F : C ⥤ D` and `G : D ⥤ C`. `F` is the left adjoint and `G` is the right adjoint. -/ structure adjunction (F : C ⥤ D) (G : D ⥤ C) := (hom_equiv : Π (X Y), (F.obj X ⟶ Y) ≃ (X ⟶ G.obj Y)) (unit : 𝟭 C ⟶ F.comp G) (counit : G.comp F ⟶ 𝟭 D) (hom_equiv_unit' : Π {X Y f}, (hom_equiv X Y) f = (unit : _ ⟶ _).app X ≫ G.map f . obviously) (hom_equiv_counit' : Π {X Y g}, (hom_equiv X Y).symm g = F.map g ≫ counit.app Y . obviously) infix ` ⊣ `:15 := adjunction class is_left_adjoint (left : C ⥤ D) := (right : D ⥤ C) (adj : left ⊣ right) class is_right_adjoint (right : D ⥤ C) := (left : C ⥤ D) (adj : left ⊣ right) def left_adjoint (R : D ⥤ C) [is_right_adjoint R] : C ⥤ D := is_right_adjoint.left R def right_adjoint (L : C ⥤ D) [is_left_adjoint L] : D ⥤ C := is_left_adjoint.right L namespace adjunction restate_axiom hom_equiv_unit' restate_axiom hom_equiv_counit' attribute [simp, priority 1] hom_equiv_unit hom_equiv_counit section variables {F : C ⥤ D} {G : D ⥤ C} (adj : F ⊣ G) {X' X : C} {Y Y' : D} @[simp, priority 1] lemma hom_equiv_naturality_left_symm (f : X' ⟶ X) (g : X ⟶ G.obj Y) : (adj.hom_equiv X' Y).symm (f ≫ g) = F.map f ≫ (adj.hom_equiv X Y).symm g := by rw [hom_equiv_counit, F.map_comp, assoc, adj.hom_equiv_counit.symm] @[simp] lemma hom_equiv_naturality_left (f : X' ⟶ X) (g : F.obj X ⟶ Y) : (adj.hom_equiv X' Y) (F.map f ≫ g) = f ≫ (adj.hom_equiv X Y) g := by rw [← equiv.eq_symm_apply]; simp [-hom_equiv_unit] @[simp, priority 1] lemma hom_equiv_naturality_right (f : F.obj X ⟶ Y) (g : Y ⟶ Y') : (adj.hom_equiv X Y') (f ≫ g) = (adj.hom_equiv X Y) f ≫ G.map g := by rw [hom_equiv_unit, G.map_comp, ← assoc, ←hom_equiv_unit] @[simp] lemma hom_equiv_naturality_right_symm (f : X ⟶ G.obj Y) (g : Y ⟶ Y') : (adj.hom_equiv X Y').symm (f ≫ G.map g) = (adj.hom_equiv X Y).symm f ≫ g := by rw [equiv.symm_apply_eq]; simp [-hom_equiv_counit] @[simp] lemma left_triangle : (whisker_right adj.unit F) ≫ (whisker_left F adj.counit) = nat_trans.id _ := begin ext1 X, dsimp, erw [← adj.hom_equiv_counit, equiv.symm_apply_eq, adj.hom_equiv_unit], simp end @[simp] lemma right_triangle : (whisker_left G adj.unit) ≫ (whisker_right adj.counit G) = nat_trans.id _ := begin ext1 Y, dsimp, erw [← adj.hom_equiv_unit, ← equiv.eq_symm_apply, adj.hom_equiv_counit], simp end @[simp, reassoc] lemma left_triangle_components : F.map (adj.unit.app X) ≫ adj.counit.app (F.obj X) = 𝟙 (F.obj X) := congr_arg (λ (t : nat_trans _ (𝟭 C ⋙ F)), t.app X) adj.left_triangle @[simp, reassoc] lemma right_triangle_components {Y : D} : adj.unit.app (G.obj Y) ≫ G.map (adj.counit.app Y) = 𝟙 (G.obj Y) := congr_arg (λ (t : nat_trans _ (G ⋙ 𝟭 C)), t.app Y) adj.right_triangle @[simp, reassoc] lemma counit_naturality {X Y : D} (f : X ⟶ Y) : F.map (G.map f) ≫ (adj.counit).app Y = (adj.counit).app X ≫ f := adj.counit.naturality f @[simp, reassoc] lemma unit_naturality {X Y : C} (f : X ⟶ Y) : (adj.unit).app X ≫ G.map (F.map f) = f ≫ (adj.unit).app Y := (adj.unit.naturality f).symm end end adjunction namespace adjunction structure core_hom_equiv (F : C ⥤ D) (G : D ⥤ C) := (hom_equiv : Π (X Y), (F.obj X ⟶ Y) ≃ (X ⟶ G.obj Y)) (hom_equiv_naturality_left_symm' : Π {X' X Y} (f : X' ⟶ X) (g : X ⟶ G.obj Y), (hom_equiv X' Y).symm (f ≫ g) = F.map f ≫ (hom_equiv X Y).symm g . obviously) (hom_equiv_naturality_right' : Π {X Y Y'} (f : F.obj X ⟶ Y) (g : Y ⟶ Y'), (hom_equiv X Y') (f ≫ g) = (hom_equiv X Y) f ≫ G.map g . obviously) namespace core_hom_equiv restate_axiom hom_equiv_naturality_left_symm' restate_axiom hom_equiv_naturality_right' attribute [simp, priority 1] hom_equiv_naturality_left_symm hom_equiv_naturality_right variables {F : C ⥤ D} {G : D ⥤ C} (adj : core_hom_equiv F G) {X' X : C} {Y Y' : D} @[simp] lemma hom_equiv_naturality_left (f : X' ⟶ X) (g : F.obj X ⟶ Y) : (adj.hom_equiv X' Y) (F.map f ≫ g) = f ≫ (adj.hom_equiv X Y) g := by rw [← equiv.eq_symm_apply]; simp @[simp] lemma hom_equiv_naturality_right_symm (f : X ⟶ G.obj Y) (g : Y ⟶ Y') : (adj.hom_equiv X Y').symm (f ≫ G.map g) = (adj.hom_equiv X Y).symm f ≫ g := by rw [equiv.symm_apply_eq]; simp end core_hom_equiv structure core_unit_counit (F : C ⥤ D) (G : D ⥤ C) := (unit : 𝟭 C ⟶ F.comp G) (counit : G.comp F ⟶ 𝟭 D) (left_triangle' : whisker_right unit F ≫ whisker_left F counit = nat_trans.id _ . obviously) (right_triangle' : whisker_left G unit ≫ whisker_right counit G = nat_trans.id _ . obviously) namespace core_unit_counit restate_axiom left_triangle' restate_axiom right_triangle' attribute [simp] left_triangle right_triangle end core_unit_counit variables {F : C ⥤ D} {G : D ⥤ C} def mk_of_hom_equiv (adj : core_hom_equiv F G) : F ⊣ G := { unit := { app := λ X, (adj.hom_equiv X (F.obj X)) (𝟙 (F.obj X)), naturality' := begin intros, erw [← adj.hom_equiv_naturality_left, ← adj.hom_equiv_naturality_right], dsimp, simp end }, counit := { app := λ Y, (adj.hom_equiv _ _).inv_fun (𝟙 (G.obj Y)), naturality' := begin intros, erw [← adj.hom_equiv_naturality_left_symm, ← adj.hom_equiv_naturality_right_symm], dsimp, simp end }, hom_equiv_unit' := λ X Y f, by erw [← adj.hom_equiv_naturality_right]; simp, hom_equiv_counit' := λ X Y f, by erw [← adj.hom_equiv_naturality_left_symm]; simp, .. adj } def mk_of_unit_counit (adj : core_unit_counit F G) : F ⊣ G := { hom_equiv := λ X Y, { to_fun := λ f, adj.unit.app X ≫ G.map f, inv_fun := λ g, F.map g ≫ adj.counit.app Y, left_inv := λ f, begin change F.map (_ ≫ _) ≫ _ = _, rw [F.map_comp, assoc, ←functor.comp_map, adj.counit.naturality, ←assoc], convert id_comp _ f, exact congr_arg (λ t : nat_trans _ _, t.app _) adj.left_triangle end, right_inv := λ g, begin change _ ≫ G.map (_ ≫ _) = _, rw [G.map_comp, ←assoc, ←functor.comp_map, ←adj.unit.naturality, assoc], convert comp_id _ g, exact congr_arg (λ t : nat_trans _ _, t.app _) adj.right_triangle end }, .. adj } section omit 𝒟 def id : 𝟭 C ⊣ 𝟭 C := { hom_equiv := λ X Y, equiv.refl _, unit := 𝟙 _, counit := 𝟙 _ } end section variables {E : Type u₃} [ℰ : category.{v₃} E] (H : D ⥤ E) (I : E ⥤ D) def comp (adj₁ : F ⊣ G) (adj₂ : H ⊣ I) : F ⋙ H ⊣ I ⋙ G := { hom_equiv := λ X Z, equiv.trans (adj₂.hom_equiv _ _) (adj₁.hom_equiv _ _), unit := adj₁.unit ≫ (whisker_left F $ whisker_right adj₂.unit G) ≫ (functor.associator _ _ _).inv, counit := (functor.associator _ _ _).hom ≫ (whisker_left I $ whisker_right adj₁.counit H) ≫ adj₂.counit } end section construct_left -- Construction of a left adjoint. In order to construct a left -- adjoint to a functor G : D → C, it suffices to give the object part -- of a functor F : C → D together with isomorphisms Hom(FX, Y) ≃ -- Hom(X, GY) natural in Y. The action of F on morphisms can be -- constructed from this data. variables {F_obj : C → D} {G} variables (e : Π X Y, (F_obj X ⟶ Y) ≃ (X ⟶ G.obj Y)) variables (he : Π X Y Y' g h, e X Y' (h ≫ g) = e X Y h ≫ G.map g) include he private lemma he' {X Y Y'} (f g) : (e X Y').symm (f ≫ G.map g) = (e X Y).symm f ≫ g := by intros; rw [equiv.symm_apply_eq, he]; simp def left_adjoint_of_equiv : C ⥤ D := { obj := F_obj, map := λ X X' f, (e X (F_obj X')).symm (f ≫ e X' (F_obj X') (𝟙 _)), map_comp' := λ X X' X'' f f', begin rw [equiv.symm_apply_eq, he, equiv.apply_symm_apply], conv { to_rhs, rw [assoc, ←he, id_comp, equiv.apply_symm_apply] }, simp end } def adjunction_of_equiv_left : left_adjoint_of_equiv e he ⊣ G := mk_of_hom_equiv { hom_equiv := e, hom_equiv_naturality_left_symm' := begin intros, erw [← he' e he, ← equiv.apply_eq_iff_eq], simp [(he _ _ _ _ _).symm] end } end construct_left section construct_right -- Construction of a right adjoint, analogous to the above. variables {F} {G_obj : D → C} variables (e : Π X Y, (F.obj X ⟶ Y) ≃ (X ⟶ G_obj Y)) variables (he : Π X' X Y f g, e X' Y (F.map f ≫ g) = f ≫ e X Y g) include he private lemma he' {X' X Y} (f g) : F.map f ≫ (e X Y).symm g = (e X' Y).symm (f ≫ g) := by intros; rw [equiv.eq_symm_apply, he]; simp def right_adjoint_of_equiv : D ⥤ C := { obj := G_obj, map := λ Y Y' g, (e (G_obj Y) Y') ((e (G_obj Y) Y).symm (𝟙 _) ≫ g), map_comp' := λ Y Y' Y'' g g', begin rw [← equiv.eq_symm_apply, ← he' e he, equiv.symm_apply_apply], conv { to_rhs, rw [← assoc, he' e he, comp_id, equiv.symm_apply_apply] }, simp end } def adjunction_of_equiv_right : F ⊣ right_adjoint_of_equiv e he := mk_of_hom_equiv { hom_equiv := e, hom_equiv_naturality_left_symm' := by intros; rw [equiv.symm_apply_eq, he]; simp, hom_equiv_naturality_right' := begin intros X Y Y' g h, erw [←he, equiv.apply_eq_iff_eq, ←assoc, he' e he, comp_id, equiv.symm_apply_apply] end } end construct_right end adjunction open adjunction namespace equivalence def to_adjunction (e : C ≌ D) : e.functor ⊣ e.inverse := mk_of_unit_counit ⟨e.unit, e.counit, by { ext, exact e.functor_unit_comp X }, by { ext, exact e.unit_inverse_comp X }⟩ end equivalence namespace functor def adjunction (E : C ⥤ D) [is_equivalence E] : E ⊣ E.inv := (E.as_equivalence).to_adjunction end functor end category_theory
a872d8f9946dcdbc77f7585b1d81360eb92f1b0a
3f1a1d97c03bb24b55a1b9969bb4b3c619491d5a
/library/init/meta/interactive.lean
93fdca801de11c53caa54e08d2bbc8266cb46667
[ "Apache-2.0" ]
permissive
praveenmunagapati/lean
00c3b4496cef8e758396005013b9776bb82c4f56
fc760f57d20e0a486d14bc8a08d89147b60f530c
refs/heads/master
1,630,692,342,183
1,515,626,222,000
1,515,626,222,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
64,432
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.tactic init.meta.rewrite_tactic init.meta.simp_tactic import init.meta.smt.congruence_closure init.category.combinators import init.meta.interactive_base init.meta.derive init.meta.match_tactic open lean open lean.parser local postfix `?`:9001 := optional local postfix *:9001 := many namespace tactic /- allows metavars -/ meta def i_to_expr (q : pexpr) : tactic expr := to_expr q tt /- allow metavars and no subgoals -/ meta def i_to_expr_no_subgoals (q : pexpr) : tactic expr := to_expr q tt ff /- doesn't allows metavars -/ meta def i_to_expr_strict (q : pexpr) : tactic expr := to_expr q ff /- Auxiliary version of i_to_expr for apply-like tactics. This is a workaround for comment https://github.com/leanprover/lean/issues/1342#issuecomment-307912291 at issue #1342. In interactive mode, given a tactic apply f we want the apply tactic to create all metavariables. The following definition will return `@f` for `f`. That is, it will **not** create metavariables for implicit arguments. Before we added `i_to_expr_for_apply`, the tactic apply le_antisymm would first elaborate `le_antisymm`, and create @le_antisymm ?m_1 ?m_2 ?m_3 ?m_4 The type class resolution problem ?m_2 : weak_order ?m_1 by the elaborator since ?m_1 is not assigned yet, and the problem is discarded. Then, we would invoke `apply_core`, which would create two new metavariables for the explicit arguments, and try to unify the resulting type with the current target. After the unification, the metavariables ?m_1, ?m_3 and ?m_4 are assigned, but we lost the information about the pending type class resolution problem. With `i_to_expr_for_apply`, `le_antisymm` is elaborate into `@le_antisymm`, the apply_core tactic creates all metavariables, and solves the ones that can be solved by type class resolution. Another possible fix: we modify the elaborator to return pending type class resolution problems, and store them in the tactic_state. -/ meta def i_to_expr_for_apply (q : pexpr) : tactic expr := let aux (n : name) : tactic expr := do p ← resolve_name n, match p with | (expr.const c []) := do r ← mk_const c, save_type_info r q, return r | _ := i_to_expr p end in match q with | (expr.const c []) := aux c | (expr.local_const c _ _ _) := aux c | _ := i_to_expr q end namespace interactive open interactive interactive.types expr /-- itactic: parse a nested "interactive" tactic. That is, parse `{` tactic `}` -/ meta def itactic : Type := tactic unit meta def propagate_tags (tac : tactic unit) : tactic unit := do tag ← get_main_tag, if tag = [] then tac else focus1 $ do tac, gs ← get_goals, when (bnot gs.empty) $ do new_tag ← get_main_tag, when new_tag.empty $ with_enable_tags (set_main_tag tag) meta def concat_tags (tac : tactic (list (name × expr))) : tactic unit := mcond tags_enabled (do in_tag ← get_main_tag, r ← tac, /- remove assigned metavars -/ r ← r.mfilter $ λ ⟨n, m⟩, bnot <$> is_assigned m, match r with | [(_, m)] := set_tag m in_tag /- if there is only new subgoal, we just propagate `in_tag` -/ | _ := r.mmap' (λ ⟨n, m⟩, set_tag m (n::in_tag)) end) (tac >> skip) /-- If the current goal is a Pi/forall `∀ x : t, u` (resp. `let x := t in u`) then `intro` puts `x : t` (resp. `x := t`) in the local context. The new subgoal target is `u`. If the goal is an arrow `t → u`, then it puts `h : t` in the local context and the new goal target is `u`. If the goal is neither a Pi/forall nor begins with a let binder, the tactic `intro` applies the tactic `whnf` until an introduction can be applied or the goal is not head reducible. In the latter case, the tactic fails. -/ meta def intro : parse ident_? → tactic unit | none := propagate_tags (intro1 >> skip) | (some h) := propagate_tags (tactic.intro h >> skip) /-- Similar to `intro` tactic. The tactic `intros` will keep introducing new hypotheses until the goal target is not a Pi/forall or let binder. The variant `intros h₁ ... hₙ` introduces `n` new hypotheses using the given identifiers to name them. -/ meta def intros : parse ident_* → tactic unit | [] := propagate_tags (tactic.intros >> skip) | hs := propagate_tags (intro_lst hs >> skip) /-- The tactic `introv` allows the user to automatically introduce the variables of a theorem and explicitly name the hypotheses involved. The given names are used to name non-dependent hypotheses. Examples: ``` example : ∀ a b : nat, a = b → b = a := begin introv h, exact h.symm end ``` The state after `introv h` is ``` a b : ℕ, h : a = b ⊢ b = a ``` ``` example : ∀ a b : nat, a = b → ∀ c, b = c → a = c := begin introv h₁ h₂, exact h₁.trans h₂ end ``` The state after `introv h₁ h₂` is ``` a b : ℕ, h₁ : a = b, c : ℕ, h₂ : b = c ⊢ a = c ``` -/ meta def introv (ns : parse ident_*) : tactic unit := propagate_tags (tactic.introv ns >> return ()) /-- The tactic `rename h₁ h₂` renames hypothesis `h₁` to `h₂` in the current local context. -/ meta def rename (h₁ h₂ : parse ident) : tactic unit := propagate_tags (tactic.rename h₁ h₂) /-- The `apply` tactic tries to match the current goal against the conclusion of the type of term. The argument term should be a term well-formed in the local context of the main goal. If it succeeds, then the tactic returns as many subgoals as the number of premises that have not been fixed by type inference or type class resolution. Non-dependent premises are added before dependent ones. The `apply` tactic uses higher-order pattern matching, type class resolution, and first-order unification with dependent types. -/ meta def apply (q : parse texpr) : tactic unit := concat_tags (do h ← i_to_expr_for_apply q, tactic.apply h) /-- Similar to the `apply` tactic, but does not reorder goals. -/ meta def fapply (q : parse texpr) : tactic unit := concat_tags (i_to_expr_for_apply q >>= tactic.fapply) /-- Similar to the `apply` tactic, but only creates subgoals for non-dependent premises that have not been fixed by type inference or type class resolution. -/ meta def eapply (q : parse texpr) : tactic unit := concat_tags (i_to_expr_for_apply q >>= tactic.eapply) /-- Similar to the `apply` tactic, but allows the user to provide a `apply_cfg` configuration object. -/ meta def apply_with (q : parse parser.pexpr) (cfg : apply_cfg) : tactic unit := concat_tags (do e ← i_to_expr_for_apply q, tactic.apply e cfg) /-- Similar to the `apply` tactic, but uses matching instead of unification. `apply_match t` is equivalent to `apply_with t {unify := ff}` -/ meta def mapply (q : parse texpr) : tactic unit := concat_tags (do e ← i_to_expr_for_apply q, tactic.apply e {unify := ff}) /-- This tactic tries to close the main goal `... ⊢ t` by generating a term of type `t` using type class resolution. -/ meta def apply_instance : tactic unit := tactic.apply_instance /-- This tactic behaves like `exact`, but with a big difference: the user can put underscores `_` in the expression as placeholders for holes that need to be filled, and `refine` will generate as many subgoals as there are holes. Note that some holes may be implicit. The type of each hole must either be synthesized by the system or declared by an explicit type ascription like `(_ : nat → Prop)`. -/ meta def refine (q : parse texpr) : tactic unit := tactic.refine q /-- This tactic looks in the local context for a hypothesis whose type is equal to the goal target. If it finds one, it uses it to prove the goal, and otherwise it fails. -/ meta def assumption : tactic unit := tactic.assumption /-- Try to apply `assumption` to all goals. -/ meta def assumption' : tactic unit := tactic.any_goals tactic.assumption private meta def change_core (e : expr) : option expr → tactic unit | none := tactic.change e | (some h) := do num_reverted : ℕ ← revert h, expr.pi n bi d b ← target, tactic.change $ expr.pi n bi e b, intron num_reverted /-- `change u` replaces the target `t` of the main goal to `u` provided that `t` is well formed with respect to the local context of the main goal and `t` and `u` are definitionally equal. `change u at h` will change a local hypothesis to `u`. `change t with u at h1 h2 ...` will replace `t` with `u` in all the supplied hypotheses (or `*`), or in the goal if no `at` clause is specified, provided that `t` and `u` are definitionally equal. -/ meta def change (q : parse texpr) : parse (tk "with" *> texpr)? → parse location → tactic unit | none (loc.ns [none]) := do e ← i_to_expr q, change_core e none | none (loc.ns [some h]) := do eq ← i_to_expr q, eh ← get_local h, change_core eq (some eh) | none _ := fail "change-at does not support multiple locations" | (some w) l := do u ← mk_meta_univ, ty ← mk_meta_var (sort u), eq ← i_to_expr ``(%%q : %%ty), ew ← i_to_expr ``(%%w : %%ty), let repl := λe : expr, e.replace (λ a n, if a = eq then some ew else none), l.try_apply (λh, do e ← infer_type h, change_core (repl e) (some h)) (do g ← target, change_core (repl g) none) /-- This tactic provides an exact proof term to solve the main goal. If `t` is the goal and `p` is a term of type `u` then `exact p` succeeds if and only if `t` and `u` can be unified. -/ meta def exact (q : parse texpr) : tactic unit := do tgt : expr ← target, i_to_expr_strict ``(%%q : %%tgt) >>= tactic.exact /-- Like `exact`, but takes a list of terms and checks that all goals are discharged after the tactic. -/ meta def exacts : parse pexpr_list_or_texpr → tactic unit | [] := done | (t :: ts) := exact t >> exacts ts /-- A synonym for `exact` that allows writing `have/suffices/show ..., from ...` in tactic mode. -/ meta def «from» := exact /-- `revert h₁ ... hₙ` applies to any goal with hypotheses `h₁` ... `hₙ`. It moves the hypotheses and their dependencies to the target of the goal. This tactic is the inverse of `intro`. -/ meta def revert (ids : parse ident*) : tactic unit := propagate_tags (do hs ← mmap tactic.get_local ids, revert_lst hs, skip) private meta def resolve_name' (n : name) : tactic expr := do { p ← resolve_name n, match p with | expr.const n _ := mk_const n -- create metavars for universe levels | _ := i_to_expr p end } /- Version of to_expr that tries to bypass the elaborator if `p` is just a constant or local constant. This is not an optimization, by skipping the elaborator we make sure that no unwanted resolution is used. Example: the elaborator will force any unassigned ?A that must have be an instance of (has_one ?A) to nat. Remark: another benefit is that auxiliary temporary metavariables do not appear in error messages. -/ meta def to_expr' (p : pexpr) : tactic expr := match p with | (const c []) := do new_e ← resolve_name' c, save_type_info new_e p, return new_e | (local_const c _ _ _) := do new_e ← resolve_name' c, save_type_info new_e p, return new_e | _ := i_to_expr p end @[derive has_reflect] meta structure rw_rule := (pos : pos) (symm : bool) (rule : pexpr) meta def get_rule_eqn_lemmas (r : rw_rule) : tactic (list name) := let aux (n : name) : tactic (list name) := do { p ← resolve_name n, -- unpack local refs let e := p.erase_annotations.get_app_fn.erase_annotations, match e with | const n _ := get_eqn_lemmas_for tt n | _ := return [] end } <|> return [] in match r.rule with | const n _ := aux n | local_const n _ _ _ := aux n | _ := return [] end private meta def rw_goal (cfg : rewrite_cfg) (rs : list rw_rule) : tactic unit := rs.mmap' $ λ r, do save_info r.pos, eq_lemmas ← get_rule_eqn_lemmas r, orelse' (do e ← to_expr' r.rule, rewrite_target e {symm := r.symm, ..cfg}) (eq_lemmas.mfirst $ λ n, do e ← mk_const n, rewrite_target e {symm := r.symm, ..cfg}) (eq_lemmas.empty) private meta def uses_hyp (e : expr) (h : expr) : bool := e.fold ff $ λ t _ r, r || to_bool (t = h) private meta def rw_hyp (cfg : rewrite_cfg) : list rw_rule → expr → tactic unit | [] hyp := skip | (r::rs) hyp := do save_info r.pos, eq_lemmas ← get_rule_eqn_lemmas r, orelse' (do e ← to_expr' r.rule, when (not (uses_hyp e hyp)) $ rewrite_hyp e hyp {symm := r.symm, ..cfg} >>= rw_hyp rs) (eq_lemmas.mfirst $ λ n, do e ← mk_const n, rewrite_hyp e hyp {symm := r.symm, ..cfg} >>= rw_hyp rs) (eq_lemmas.empty) meta def rw_rule_p (ep : parser pexpr) : parser rw_rule := rw_rule.mk <$> cur_pos <*> (option.is_some <$> (with_desc "←" (tk "←" <|> tk "<-"))?) <*> ep @[derive has_reflect] meta structure rw_rules_t := (rules : list rw_rule) (end_pos : option pos) -- accepts the same content as `pexpr_list_or_texpr`, but with correct goal info pos annotations meta def rw_rules : parser rw_rules_t := (tk "[" *> rw_rules_t.mk <$> sep_by (skip_info (tk ",")) (set_goal_info_pos $ rw_rule_p (parser.pexpr 0)) <*> (some <$> cur_pos <* set_goal_info_pos (tk "]"))) <|> rw_rules_t.mk <$> (list.ret <$> rw_rule_p texpr) <*> return none private meta def rw_core (rs : parse rw_rules) (loca : parse location) (cfg : rewrite_cfg) : tactic unit := match loca with | loc.wildcard := loca.try_apply (rw_hyp cfg rs.rules) (rw_goal cfg rs.rules) | _ := loca.apply (rw_hyp cfg rs.rules) (rw_goal cfg rs.rules) end >> try (reflexivity reducible) >> (returnopt rs.end_pos >>= save_info <|> skip) /-- `rewrite e` applies identity `e` as a rewrite rule to the target of the main goal. If `e` is preceded by left arrow (`←` or `<-`), the rewrite is applied in the reverse direction. If `e` is a defined constant, then the equational lemmas associated with `e` are used. This provides a convenient way to unfold `e`. `rewrite [e₁, ..., eₙ]` applies the given rules sequentially. `rewrite e at l` rewrites `e` at location(s) `l`, where `l` is either `*` or a list of hypotheses in the local context. In the latter case, a turnstile `⊢` or `|-` can also be used, to signify the target of the goal. -/ meta def rewrite (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {}) : tactic unit := propagate_tags (rw_core q l cfg) /-- An abbreviation for `rewrite`. -/ meta def rw (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {}) : tactic unit := propagate_tags (rw_core q l cfg) /-- `rewrite` followed by `assumption`. -/ meta def rwa (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {}) : tactic unit := rewrite q l cfg >> try assumption /-- A variant of `rewrite` that uses the unifier more aggressively, unfolding semireducible definitions. -/ meta def erewrite (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {md := semireducible}) : tactic unit := propagate_tags (rw_core q l cfg) /-- An abbreviation for `erewrite`. -/ meta def erw (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {md := semireducible}) : tactic unit := propagate_tags (rw_core q l cfg) precedence `generalizing` : 0 private meta def collect_hyps_uids : tactic name_set := do ctx ← local_context, return $ ctx.foldl (λ r h, r.insert h.local_uniq_name) mk_name_set private meta def revert_new_hyps (input_hyp_uids : name_set) : tactic unit := do ctx ← local_context, let to_revert := ctx.foldr (λ h r, if input_hyp_uids.contains h.local_uniq_name then r else h::r) [], tag ← get_main_tag, m ← revert_lst to_revert, set_main_tag (mk_num_name `_case m :: tag) /-- Apply `t` to main goal, and revert any new hypothesis in the generated goals, and tag generated goals when using supported tactics such as: `induction`, `apply`, `cases`, `constructor`, ... This tactic is useful for writing robust proof scripts that are not sensitive to the name generation strategy used by `t`. ``` example (n : ℕ) : n = n := begin with_cases { induction n }, case nat.zero { reflexivity }, case nat.succ : n' ih { reflexivity } end ``` TODO(Leo): improve docstring -/ meta def with_cases (t : itactic) : tactic unit := with_enable_tags $ focus1 $ do input_hyp_uids ← collect_hyps_uids, t, all_goals (revert_new_hyps input_hyp_uids) private meta def get_type_name (e : expr) : tactic name := do e_type ← infer_type e >>= whnf, (const I ls) ← return $ get_app_fn e_type, return I private meta def generalize_arg_p_aux : pexpr → parser (pexpr × name) | (app (app (macro _ [const `eq _ ]) h) (local_const x _ _ _)) := pure (h, x) | _ := fail "parse error" private meta def generalize_arg_p : parser (pexpr × name) := with_desc "expr = id" $ parser.pexpr 0 >>= generalize_arg_p_aux /-- `generalize : e = x` replaces all occurrences of `e` in the target with a new hypothesis `x` of the same type. `generalize h : e = x` in addition registers the hypothesis `h : e = x`. -/ meta def generalize (h : parse ident?) (_ : parse $ tk ":") (p : parse generalize_arg_p) : tactic unit := propagate_tags $ do let (p, x) := p, e ← i_to_expr p, some h ← pure h | tactic.generalize e x >> intro1 >> skip, tgt ← target, -- if generalizing fails, fall back to not replacing anything tgt' ← do { ⟨tgt', _⟩ ← solve_aux tgt (tactic.generalize e x >> target), to_expr ``(Π x, %%e = x → %%(tgt'.binding_body.lift_vars 0 1)) } <|> to_expr ``(Π x, %%e = x → %%tgt), t ← assert h tgt', swap, exact ``(%%t %%e rfl), intro x, intro h meta def cases_arg_p : parser (option name × pexpr) := with_desc "(id :)? expr" $ do t ← texpr, match t with | (local_const x _ _ _) := (tk ":" *> do t ← texpr, pure (some x, t)) <|> pure (none, t) | _ := pure (none, t) end /-- Given the initial tag `in_tag` and the cases names produced by `induction` or `cases` tactic, update the tag of the new subgoals. -/ private meta def set_cases_tags (in_tag : tag) (rs : list name) : tactic unit := do te ← tags_enabled, gs ← get_goals, match gs with | [g] := when te (set_tag g in_tag) -- if only one goal was produced, we should not make the tag longer | _ := do let tgs : list (name × expr) := rs.map₂ (λ n g, (n, g)) gs, if te then tgs.mmap' (λ ⟨n, g⟩, set_tag g (n::in_tag)) /- If `induction/cases` is not in a `with_cases` block, we still set tags using `_case_simple` to make sure we can use the `case` notation. ``` induction h, case c { ... } ``` -/ else tgs.mmap' (λ ⟨n, g⟩, with_enable_tags (set_tag g (`_case_simple::n::[]))) end private meta def set_induction_tags (in_tag : tag) (rs : list (name × list expr × list (name × expr))) : tactic unit := set_cases_tags in_tag (rs.map (λ e, e.1)) /-- Assuming `x` is a variable in the local context with an inductive type, `induction x` applies induction on `x` to the main goal, producing one goal for each constructor of the inductive type, in which the target is replaced by a general instance of that constructor and an inductive hypothesis is added for each recursive argument to the constructor. If the type of an element in the local context depends on `x`, that element is reverted and reintroduced afterward, so that the inductive hypothesis incorporates that hypothesis as well. For example, given `n : nat` and a goal with a hypothesis `h : P n` and target `Q n`, `induction n` produces one goal with hypothesis `h : P 0` and target `Q 0`, and one goal with hypotheses `h : P (nat.succ a)` and `ih₁ : P a → Q a` and target `Q (nat.succ a)`. Here the names `a` and `ih₁` ire chosen automatically. `induction e`, where `e` is an expression instead of a variable, generalizes `e` in the goal, and then performs induction on the resulting variable. `induction e with y₁ ... yₙ`, where `e` is a variable or an expression, specifies that the sequence of names `y₁ ... yₙ` should be used for the arguments to the constructors and inductive hypotheses, including implicit arguments. If the list does not include enough names for all of the arguments, additional names are generated automatically. If too many names are given, the extra ones are ignored. Underscores can be used in the list, in which case the corresponding names are generated automatically. Note that for long sequences of names, the `case` tactic provides a more convenient naming mechanism. `induction e using r` allows the user to specify the principle of induction that should be used. Here `r` should be a theorem whose result type must be of the form `C t`, where `C` is a bound variable and `t` is a (possibly empty) sequence of bound variables `induction e generalizing z₁ ... zₙ`, where `z₁ ... zₙ` are variables in the local context, generalizes over `z₁ ... zₙ` before applying the induction but then introduces them in each goal. In other words, the net effect is that each inductive hypothesis is generalized. `induction h : t` will introduce an equality of the form `h : t = C x y`, asserting that the input term is equal to the current constructor case, to the context. -/ meta def induction (hp : parse cases_arg_p) (rec_name : parse using_ident) (ids : parse with_ident_list) (revert : parse $ (tk "generalizing" *> ident*)?) : tactic unit := do in_tag ← get_main_tag, focus1 $ do { -- process `h : t` case e ← match hp with | (some h, p) := do x ← mk_fresh_name, generalize h () (p, x), get_local x | (none, p) := i_to_expr p end, -- generalize major premise e ← if e.is_local_constant then pure e else tactic.generalize e >> intro1, -- generalize major premise args (e, newvars, locals) ← do { none ← pure rec_name | pure (e, [], []), t ← infer_type e, t ← whnf_ginductive t, const n _ ← pure t.get_app_fn | pure (e, [], []), env ← get_env, tt ← pure $ env.is_inductive n | pure (e, [], []), let (locals, nonlocals) := (t.get_app_args.drop $ env.inductive_num_params n).partition (λ arg : expr, arg.is_local_constant), _ :: _ ← pure nonlocals | pure (e, [], []), n ← tactic.revert e, newvars ← nonlocals.mmap $ λ arg, do { n ← revert_kdeps arg, tactic.generalize arg, h ← intro1, intron n, -- now try to clear hypotheses that may have been abstracted away let locals := arg.fold [] (λ e _ acc, if e.is_local_constant then e::acc else acc), locals.mmap' (try ∘ clear), pure h }, intron (n-1), e ← intro1, pure (e, newvars, locals) }, -- revert `generalizing` params n ← mmap tactic.get_local (revert.get_or_else []) >>= revert_lst, rs ← tactic.induction e ids rec_name, all_goals $ do { intron n, clear_lst (newvars.map local_pp_name), (e::locals).mmap' (try ∘ clear) }, set_induction_tags in_tag rs } private meta def is_case_simple_tag : tag → bool | (`_case_simple :: _) := tt | _ := ff private meta def is_case_tag : tag → option nat | (name.mk_numeral n `_case :: _) := some n.val | _ := none private meta def tag_match (t : tag) (pre : list name) : bool := pre.is_prefix_of t.reverse && ((is_case_tag t).is_some || is_case_simple_tag t) private meta def collect_tagged_goals (pre : list name) : tactic (list expr) := do gs ← get_goals, gs.mfoldr (λ g r, do t ← get_tag g, if tag_match t pre then return (g::r) else return r) [] private meta def find_tagged_goal_aux (pre : list name) : tactic expr := do gs ← collect_tagged_goals pre, match gs with | [] := fail ("invalid `case`, there is no goal tagged with prefix " ++ to_string pre) | [g] := return g | gs := do tags : list (list name) ← gs.mmap get_tag, fail ("invalid `case`, there is more than one goal tagged with prefix " ++ to_string pre ++ ", matching tags: " ++ to_string tags) end private meta def find_tagged_goal (pre : list name) : tactic expr := match pre with | [] := do g::gs ← get_goals, return g | _ := find_tagged_goal_aux pre <|> -- try to resolve constructor names, and try again do env ← get_env, pre ← pre.mmap (λ id, (do r_id ← resolve_constant id, if (env.inductive_type_of r_id).is_none then return id else return r_id) <|> return id), find_tagged_goal_aux pre end private meta def find_case (goals : list expr) (ty : name) (idx : nat) (num_indices : nat) : option expr → expr → option (expr × expr) | case e := if e.has_meta_var then match e with | (mvar _ _ _) := do case ← case, guard $ e ∈ goals, pure (case, e) | (app _ _) := let idx := match e.get_app_fn with | const (name.mk_string rec ty') _ := guard (ty' = ty) >> match mk_simple_name rec with | `drec := some idx | `rec := some idx -- indices + major premise | `dcases_on := some (idx + num_indices + 1) | `cases_on := some (idx + num_indices + 1) | _ := none end | _ := none end in match idx with | none := list.foldl (<|>) (find_case case e.get_app_fn) $ e.get_app_args.map (find_case case) | some idx := let args := e.get_app_args in do arg ← args.nth idx, args.enum.foldl (λ acc ⟨i, arg⟩, match acc with | some _ := acc | _ := if i ≠ idx then find_case none arg else none end) -- start recursion with likely case (find_case (some arg) arg) end | (lam _ _ _ e) := find_case case e | (macro n args) := list.foldl (<|>) none $ args.map (find_case case) | _ := none end else none private meta def rename_lams : expr → list name → tactic unit | (lam n _ _ e) (n'::ns) := (rename n n' >> rename_lams e ns) <|> rename_lams e (n'::ns) | _ _ := skip /-- Focuses on the `induction`/`cases`/`with_cases` subgoal corresponding to the given tag prefix, optionally renaming introduced locals. ``` example (n : ℕ) : n = n := begin induction n, case nat.zero { reflexivity }, case nat.succ : a ih { reflexivity } end ``` -/ meta def case (pre : parse ident_*) (ids : parse $ (tk ":" *> ident_*)?) (tac : itactic) : tactic unit := do g ← find_tagged_goal pre, tag ← get_tag g, let ids := ids.get_or_else [], match is_case_tag tag with | some n := do let m := ids.length, gs ← get_goals, set_goals $ g :: gs.filter (≠ g), intro_lst ids, when (m < n) $ intron (n - m), solve1 tac | none := match is_case_simple_tag tag with | tt := /- Use the old `case` implementation -/ do r ← result, env ← get_env, [ctor_id] ← return pre, ctor ← resolve_constant ctor_id <|> fail ("'" ++ to_string ctor_id ++ "' is not a constructor"), ty ← (env.inductive_type_of ctor).to_monad <|> fail ("'" ++ to_string ctor ++ "' is not a constructor"), let ctors := env.constructors_of ty, let idx := env.inductive_num_params ty + /- motive -/ 1 + list.index_of ctor ctors, /- Remark: we now use `find_case` just to locate the `lambda` used in `rename_lams`. The goal is now located using tags. -/ (case, _) ← (find_case [g] ty idx (env.inductive_num_indices ty) none r ).to_monad <|> fail "could not find open goal of given case", gs ← get_goals, set_goals $ g :: gs.filter (≠ g), rename_lams case ids, solve1 tac | ff := failed end end /-- Assuming `x` is a variable in the local context with an inductive type, `destruct x` splits the main goal, producing one goal for each constructor of the inductive type, in which `x` is assumed to be a general instance of that constructor. In contrast to `cases`, the local context is unchanged, i.e. no elements are reverted or introduced. For example, given `n : nat` and a goal with a hypothesis `h : P n` and target `Q n`, `destruct n` produces one goal with target `n = 0 → Q n`, and one goal with target `∀ (a : ℕ), (λ (w : ℕ), n = w → Q n) (nat.succ a)`. Here the name `a` is chosen automatically. -/ meta def destruct (p : parse texpr) : tactic unit := i_to_expr p >>= tactic.destruct meta def cases_core (e : expr) (ids : list name := []) : tactic unit := do in_tag ← get_main_tag, focus1 $ do rs ← tactic.cases e ids, set_cases_tags in_tag rs /-- Assuming `x` is a variable in the local context with an inductive type, `cases x` splits the main goal, producing one goal for each constructor of the inductive type, in which the target is replaced by a general instance of that constructor. If the type of an element in the local context depends on `x`, that element is reverted and reintroduced afterward, so that the case split affects that hypothesis as well. For example, given `n : nat` and a goal with a hypothesis `h : P n` and target `Q n`, `cases n` produces one goal with hypothesis `h : P 0` and target `Q 0`, and one goal with hypothesis `h : P (nat.succ a)` and target `Q (nat.succ a)`. Here the name `a` is chosen automatically. `cases e`, where `e` is an expression instead of a variable, generalizes `e` in the goal, and then cases on the resulting variable. `cases e with y₁ ... yₙ`, where `e` is a variable or an expression, specifies that the sequence of names `y₁ ... yₙ` should be used for the arguments to the constructors, including implicit arguments. If the list does not include enough names for all of the arguments, additional names are generated automatically. If too many names are given, the extra ones are ignored. Underscores can be used in the list, in which case the corresponding names are generated automatically. `cases h : e`, where `e` is a variable or an expression, performs cases on `e` as above, but also adds a hypothesis `h : e = ...` to each hypothesis, where `...` is the constructor instance for that particular case. -/ meta def cases : parse cases_arg_p → parse with_ident_list → tactic unit | (none, p) ids := do e ← i_to_expr p, cases_core e ids | (some h, p) ids := do x ← mk_fresh_name, generalize h () (p, x), hx ← get_local x, cases_core hx ids private meta def find_matching_hyp (ps : list pattern) : tactic expr := any_hyp $ λ h, do type ← infer_type h, ps.mfirst $ λ p, do match_pattern p type, return h /-- `cases_matching p` applies the `cases` tactic to a hypothesis `h : type` if `type` matches the pattern `p`. `cases_matching [p_1, ..., p_n]` applies the `cases` tactic to a hypothesis `h : type` if `type` matches one of the given patterns. `cases_matching* p` more efficient and compact version of `focus1 { repeat { cases_matching p } }`. It is more efficient because the pattern is compiled once. Example: The following tactic destructs all conjunctions and disjunctions in the current goal. ``` cases_matching* [_ ∨ _, _ ∧ _] ``` -/ meta def cases_matching (rec : parse $ (tk "*")?) (ps : parse pexpr_list_or_texpr) : tactic unit := do ps ← ps.mmap pexpr_to_pattern, if rec.is_none then find_matching_hyp ps >>= cases_core else tactic.focus1 $ tactic.repeat $ find_matching_hyp ps >>= cases_core /-- Shorthand for `cases_matching` -/ meta def casesm (rec : parse $ (tk "*")?) (ps : parse pexpr_list_or_texpr) : tactic unit := cases_matching rec ps private meta def try_cases_for_types (type_names : list name) (at_most_one : bool) : tactic unit := any_hyp $ λ h, do I ← expr.get_app_fn <$> (infer_type h >>= head_beta), guard I.is_constant, guard (I.const_name ∈ type_names), tactic.focus1 (cases_core h >> if at_most_one then do n ← num_goals, guard (n <= 1) else skip) /-- `cases_type I` applies the `cases` tactic to a hypothesis `h : (I ...)` `cases_type I_1 ... I_n` applies the `cases` tactic to a hypothesis `h : (I_1 ...)` or ... or `h : (I_n ...)` `cases_type* I` is shorthand for `focus1 { repeat { cases_type I } }` `cases_type! I` only applies `cases` if the number of resulting subgoals is <= 1. Example: The following tactic destructs all conjunctions and disjunctions in the current goal. ``` cases_type* or and ``` -/ meta def cases_type (one : parse $ (tk "!")?) (rec : parse $ (tk "*")?) (type_names : parse ident*) : tactic unit := do type_names ← type_names.mmap resolve_constant, if rec.is_none then try_cases_for_types type_names (bnot one.is_none) else tactic.focus1 $ tactic.repeat $ try_cases_for_types type_names (bnot one.is_none) /-- Tries to solve the current goal using a canonical proof of `true`, or the `reflexivity` tactic, or the `contradiction` tactic. -/ meta def trivial : tactic unit := tactic.triv <|> tactic.reflexivity <|> tactic.contradiction <|> fail "trivial tactic failed" /-- Closes the main goal using `sorry`. -/ meta def admit : tactic unit := tactic.admit /-- The contradiction tactic attempts to find in the current local context a hypothesis that is equivalent to an empty inductive type (e.g. `false`), a hypothesis of the form `c_1 ... = c_2 ...` where `c_1` and `c_2` are distinct constructors, or two contradictory hypotheses. -/ meta def contradiction : tactic unit := tactic.contradiction /-- `iterate { t }` repeatedly applies tactic `t` until `t` fails. `iterate { t }` always succeeds. `iterate n { t }` applies `t` `n` times. -/ meta def iterate (n : parse small_nat?) (t : itactic) : tactic unit := match n with | none := tactic.iterate t | some n := iterate_exactly n t end /-- `repeat { t }` applies `t` to each goal. If the application succeeds, the tactic is applied recursively to all the generated subgoals until it eventually fails. The recursion stops in a subgoal when the tactic has failed to make progress. The tactic `repeat { t }` never fails. -/ meta def repeat : itactic → tactic unit := tactic.repeat /-- `try { t }` tries to apply tactic `t`, but succeeds whether or not `t` succeeds. -/ meta def try : itactic → tactic unit := tactic.try /-- A do-nothing tactic that always succeeds. -/ meta def skip : tactic unit := tactic.skip /-- `solve1 { t }` applies the tactic `t` to the main goal and fails if it is not solved. -/ meta def solve1 : itactic → tactic unit := tactic.solve1 /-- `abstract id { t }` tries to use tactic `t` to solve the main goal. If it succeeds, it abstracts the goal as an independent definition or theorem with name `id`. If `id` is omitted, a name is generated automatically. -/ meta def abstract (id : parse ident?) (tac : itactic) : tactic unit := tactic.abstract tac id /-- `all_goals { t }` applies the tactic `t` to every goal, and succeeds if each application succeeds. -/ meta def all_goals : itactic → tactic unit := tactic.all_goals /-- `any_goals { t }` applies the tactic `t` to every goal, and succeeds if at least one application succeeds. -/ meta def any_goals : itactic → tactic unit := tactic.any_goals /-- `focus { t }` temporarily hides all goals other than the first, applies `t`, and then restores the other goals. It fails if there are no goals. -/ meta def focus (tac : itactic) : tactic unit := tactic.focus1 tac private meta def assume_core (n : name) (ty : pexpr) := do t ← target, when (not $ t.is_pi ∨ t.is_let) whnf_target, t ← target, when (not $ t.is_pi ∨ t.is_let) $ fail "assume tactic failed, Pi/let expression expected", ty ← i_to_expr ty, unify ty t.binding_domain, intro_core n >> skip /-- Assuming the target of the goal is a Pi or a let, `assume h : t` unifies the type of the binder with `t` and introduces it with name `h`, just like `intro h`. If `h` is absent, the tactic uses the name `this`. If `t` is omitted, it will be inferred. `assume (h₁ : t₁) ... (hₙ : tₙ)` introduces multiple hypotheses. Any of the types may be omitted, but the names must be present. -/ meta def «assume» : parse (sum.inl <$> (tk ":" *> texpr) <|> sum.inr <$> parse_binders tac_rbp) → tactic unit | (sum.inl ty) := assume_core `this ty | (sum.inr binders) := binders.mmap' $ λ b, assume_core b.local_pp_name b.local_type /-- `have h : t := p` adds the hypothesis `h : t` to the current goal if `p` a term of type `t`. If `t` is omitted, it will be inferred. `have h : t` adds the hypothesis `h : t` to the current goal and opens a new subgoal with target `t`. The new subgoal becomes the main goal. If `t` is omitted, it will be replaced by a fresh metavariable. If `h` is omitted, the name `this` is used. -/ meta def «have» (h : parse ident?) (q₁ : parse (tk ":" *> texpr)?) (q₂ : parse $ (tk ":=" *> texpr)?) : tactic unit := let h := h.get_or_else `this in match q₁, q₂ with | some e, some p := do t ← i_to_expr e, v ← i_to_expr ``(%%p : %%t), tactic.assertv h t v | none, some p := do p ← i_to_expr p, tactic.note h none p | some e, none := i_to_expr e >>= tactic.assert h | none, none := do u ← mk_meta_univ, e ← mk_meta_var (sort u), tactic.assert h e end >> skip /-- `let h : t := p` adds the hypothesis `h : t := p` to the current goal if `p` a term of type `t`. If `t` is omitted, it will be inferred. `let h : t` adds the hypothesis `h : t := ?M` to the current goal and opens a new subgoal `?M : t`. The new subgoal becomes the main goal. If `t` is omitted, it will be replaced by a fresh metavariable. If `h` is omitted, the name `this` is used. -/ meta def «let» (h : parse ident?) (q₁ : parse (tk ":" *> texpr)?) (q₂ : parse $ (tk ":=" *> texpr)?) : tactic unit := let h := h.get_or_else `this in match q₁, q₂ with | some e, some p := do t ← i_to_expr e, v ← i_to_expr ``(%%p : %%t), tactic.definev h t v | none, some p := do p ← i_to_expr p, tactic.pose h none p | some e, none := i_to_expr e >>= tactic.define h | none, none := do u ← mk_meta_univ, e ← mk_meta_var (sort u), tactic.define h e end >> skip /-- `suffices h : t` is the same as `have h : t, tactic.swap`. In other words, it adds the hypothesis `h : t` to the current goal and opens a new subgoal with target `t`. -/ meta def «suffices» (h : parse ident?) (t : parse (tk ":" *> texpr)?) : tactic unit := «have» h t none >> tactic.swap /-- This tactic displays the current state in the tracing buffer. -/ meta def trace_state : tactic unit := tactic.trace_state /-- `trace a` displays `a` in the tracing buffer. -/ meta def trace {α : Type} [has_to_tactic_format α] (a : α) : tactic unit := tactic.trace a /-- `existsi e` will instantiate an existential quantifier in the target with `e` and leave the instantiated body as the new target. More generally, it applies to any inductive type with one constructor and at least two arguments, applying the constructor with `e` as the first argument and leaving the remaining arguments as goals. `existsi [e₁, ..., eₙ]` iteratively does the same for each expression in the list. -/ meta def existsi : parse pexpr_list_or_texpr → tactic unit | [] := return () | (p::ps) := i_to_expr p >>= tactic.existsi >> existsi ps /-- This tactic applies to a goal such that its conclusion is an inductive type (say `I`). It tries to apply each constructor of `I` until it succeeds. -/ meta def constructor : tactic unit := concat_tags tactic.constructor /-- Similar to `constructor`, but only non-dependent premises are added as new goals. -/ meta def econstructor : tactic unit := concat_tags tactic.econstructor /-- Applies the first constructor when the type of the target is an inductive data type with two constructors. -/ meta def left : tactic unit := concat_tags tactic.left /-- Applies the second constructor when the type of the target is an inductive data type with two constructors. -/ meta def right : tactic unit := concat_tags tactic.right /-- Applies the constructor when the type of the target is an inductive data type with one constructor. -/ meta def split : tactic unit := concat_tags tactic.split private meta def constructor_matching_aux (ps : list pattern) : tactic unit := do t ← target, ps.mfirst (λ p, match_pattern p t), constructor meta def constructor_matching (rec : parse $ (tk "*")?) (ps : parse pexpr_list_or_texpr) : tactic unit := do ps ← ps.mmap pexpr_to_pattern, if rec.is_none then constructor_matching_aux ps else tactic.focus1 $ tactic.repeat $ constructor_matching_aux ps /-- Replaces the target of the main goal by `false`. -/ meta def exfalso : tactic unit := tactic.exfalso /-- The `injection` tactic is based on the fact that constructors of inductive data types are injections. That means that if `c` is a constructor of an inductive datatype, and if `(c t₁)` and `(c t₂)` are two terms that are equal then `t₁` and `t₂` are equal too. If `q` is a proof of a statement of conclusion `t₁ = t₂`, then injection applies injectivity to derive the equality of all arguments of `t₁` and `t₂` placed in the same positions. For example, from `(a::b) = (c::d)` we derive `a=c` and `b=d`. To use this tactic `t₁` and `t₂` should be constructor applications of the same constructor. Given `h : a::b = c::d`, the tactic `injection h` adds two new hypothesis with types `a = c` and `b = d` to the main goal. The tactic `injection h with h₁ h₂` uses the names `h₁` and `h₂` to name the new hypotheses. -/ meta def injection (q : parse texpr) (hs : parse with_ident_list) : tactic unit := do e ← i_to_expr q, tactic.injection_with e hs, try assumption /-- `injections with h₁ ... hₙ` iteratively applies `injection` to hypotheses using the names `h₁ ... hₙ`. -/ meta def injections (hs : parse with_ident_list) : tactic unit := do tactic.injections_with hs, try assumption end interactive meta structure simp_config_ext extends simp_config := (discharger : tactic unit := failed) section mk_simp_set open expr interactive.types @[derive has_reflect] meta inductive simp_arg_type : Type | all_hyps : simp_arg_type | except : name → simp_arg_type | expr : pexpr → simp_arg_type meta def simp_arg : parser simp_arg_type := (tk "*" *> return simp_arg_type.all_hyps) <|> (tk "-" *> simp_arg_type.except <$> ident) <|> (simp_arg_type.expr <$> texpr) meta def simp_arg_list : parser (list simp_arg_type) := (tk "*" *> return [simp_arg_type.all_hyps]) <|> list_of simp_arg <|> return [] private meta def resolve_exception_ids (all_hyps : bool) : list name → list name → list name → tactic (list name × list name) | [] gex hex := return (gex.reverse, hex.reverse) | (id::ids) gex hex := do p ← resolve_name id, let e := p.erase_annotations.get_app_fn.erase_annotations, match e with | const n _ := resolve_exception_ids ids (n::gex) hex | local_const n _ _ _ := when (not all_hyps) (fail $ sformat! "invalid local exception {id}, '*' was not used") >> resolve_exception_ids ids gex (n::hex) | _ := fail $ sformat! "invalid exception {id}, unknown identifier" end /- Return (hs, gex, hex, all) -/ meta def decode_simp_arg_list (hs : list simp_arg_type) : tactic $ list pexpr × list name × list name × bool := do let (hs, ex, all) := hs.foldl (λ r h, match r, h with | (es, ex, all), simp_arg_type.all_hyps := (es, ex, tt) | (es, ex, all), simp_arg_type.except id := (es, id::ex, all) | (es, ex, all), simp_arg_type.expr e := (e::es, ex, all) end) ([], [], ff), (gex, hex) ← resolve_exception_ids all ex [] [], return (hs.reverse, gex, hex, all) private meta def add_simps : simp_lemmas → list name → tactic simp_lemmas | s [] := return s | s (n::ns) := do s' ← s.add_simp n, add_simps s' ns private meta def report_invalid_simp_lemma {α : Type} (n : name): tactic α := fail format!"invalid simplification lemma '{n}' (use command 'set_option trace.simp_lemmas true' for more details)" private meta def check_no_overload (p : pexpr) : tactic unit := when p.is_choice_macro $ match p with | macro _ ps := fail $ to_fmt "ambiguous overload, possible interpretations" ++ format.join (ps.map (λ p, (to_fmt p).indent 4)) | _ := failed end private meta def simp_lemmas.resolve_and_add (s : simp_lemmas) (u : list name) (n : name) (ref : pexpr) : tactic (simp_lemmas × list name) := do p ← resolve_name n, check_no_overload p, -- unpack local refs let e := p.erase_annotations.get_app_fn.erase_annotations, match e with | const n _ := (do b ← is_valid_simp_lemma_cnst n, guard b, save_const_type_info n ref, s ← s.add_simp n, return (s, u)) <|> (do eqns ← get_eqn_lemmas_for tt n, guard (eqns.length > 0), save_const_type_info n ref, s ← add_simps s eqns, return (s, u)) <|> (do env ← get_env, guard (env.is_projection n).is_some, return (s, n::u)) <|> report_invalid_simp_lemma n | _ := (do e ← i_to_expr_no_subgoals p, b ← is_valid_simp_lemma e, guard b, try (save_type_info e ref), s ← s.add e, return (s, u)) <|> report_invalid_simp_lemma n end private meta def simp_lemmas.add_pexpr (s : simp_lemmas) (u : list name) (p : pexpr) : tactic (simp_lemmas × list name) := match p with | (const c []) := simp_lemmas.resolve_and_add s u c p | (local_const c _ _ _) := simp_lemmas.resolve_and_add s u c p | _ := do new_e ← i_to_expr_no_subgoals p, s ← s.add new_e, return (s, u) end private meta def simp_lemmas.append_pexprs : simp_lemmas → list name → list pexpr → tactic (simp_lemmas × list name) | s u [] := return (s, u) | s u (l::ls) := do (s, u) ← simp_lemmas.add_pexpr s u l, simp_lemmas.append_pexprs s u ls meta def mk_simp_set_core (no_dflt : bool) (attr_names : list name) (hs : list simp_arg_type) (at_star : bool) : tactic (bool × simp_lemmas × list name) := do (hs, gex, hex, all_hyps) ← decode_simp_arg_list hs, when (all_hyps ∧ at_star ∧ not hex.empty) $ fail "A tactic of the form `simp [*, -h] at *` is currently not supported", s ← join_user_simp_lemmas no_dflt attr_names, (s, u) ← simp_lemmas.append_pexprs s [] hs, s ← if not at_star ∧ all_hyps then do ctx ← collect_ctx_simps, let ctx := ctx.filter (λ h, h.local_uniq_name ∉ hex), -- remove local exceptions s.append ctx else return s, -- add equational lemmas, if any gex ← gex.mmap (λ n, list.cons n <$> get_eqn_lemmas_for tt n), return (all_hyps, simp_lemmas.erase s $ gex.join, u) meta def mk_simp_set (no_dflt : bool) (attr_names : list name) (hs : list simp_arg_type) : tactic (simp_lemmas × list name) := prod.snd <$> (mk_simp_set_core no_dflt attr_names hs ff) end mk_simp_set namespace interactive open interactive interactive.types expr meta def simp_core_aux (cfg : simp_config) (discharger : tactic unit) (s : simp_lemmas) (u : list name) (hs : list expr) (tgt : bool) : tactic unit := do to_remove ← hs.mfilter $ λ h, do { h_type ← infer_type h, (do (new_h_type, pr) ← simplify s u h_type cfg `eq discharger, assert h.local_pp_name new_h_type, mk_eq_mp pr h >>= tactic.exact >> return tt) <|> (return ff) }, goal_simplified ← if tgt then (simp_target s u cfg discharger >> return tt) <|> (return ff) else return ff, guard (cfg.fail_if_unchanged = ff ∨ to_remove.length > 0 ∨ goal_simplified) <|> fail "simplify tactic failed to simplify", to_remove.mmap' (λ h, try (clear h)) meta def simp_core (cfg : simp_config) (discharger : tactic unit) (no_dflt : bool) (hs : list simp_arg_type) (attr_names : list name) (locat : loc) : tactic unit := match locat with | loc.wildcard := do (all_hyps, s, u) ← mk_simp_set_core no_dflt attr_names hs tt, if all_hyps then tactic.simp_all s u cfg discharger else do hyps ← non_dep_prop_hyps, simp_core_aux cfg discharger s u hyps tt | _ := do (s, u) ← mk_simp_set no_dflt attr_names hs, ns ← locat.get_locals, simp_core_aux cfg discharger s u ns locat.include_goal end >> try tactic.triv >> try (tactic.reflexivity reducible) /-- The `simp` tactic uses lemmas and hypotheses to simplify the main goal target or non-dependent hypotheses. It has many variants. `simp` simplifies the main goal target using lemmas tagged with the attribute `[simp]`. `simp [h₁ h₂ ... hₙ]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]` and the given `hᵢ`'s, where the `hᵢ`'s are expressions. If an `hᵢ` is a defined constant `f`, then the equational lemmas associated with `f` are used. This provides a convenient way to unfold `f`. `simp [*]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]` and all hypotheses. `simp *` is a shorthand for `simp [*]`. `simp only [h₁ h₂ ... hₙ]` is like `simp [h₁ h₂ ... hₙ]` but does not use `[simp]` lemmas `simp [-id_1, ... -id_n]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]`, but removes the ones named `idᵢ`. `simp at h₁ h₂ ... hₙ` simplifies the non-dependent hypotheses `h₁ : T₁` ... `hₙ : Tₙ`. The tactic fails if the target or another hypothesis depends on one of them. The token `⊢` or `|-` can be added to the list to include the target. `simp at *` simplifies all the hypotheses and the target. `simp * at *` simplifies target and all (non-dependent propositional) hypotheses using the other hypotheses. `simp with attr₁ ... attrₙ` simplifies the main goal target using the lemmas tagged with any of the attributes `[attr₁]`, ..., `[attrₙ]` or `[simp]`. -/ meta def simp (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (locat : parse location) (cfg : simp_config_ext := {}) : tactic unit := propagate_tags (simp_core cfg.to_simp_config cfg.discharger no_dflt hs attr_names locat) /-- Just construct the simp set and trace it. Used for debugging. -/ meta def trace_simp_set (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) : tactic unit := do (s, _) ← mk_simp_set no_dflt attr_names hs, s.pp >>= trace /-- `simp_intros h₁ h₂ ... hₙ` is similar to `intros h₁ h₂ ... hₙ` except that each hypothesis is simplified as it is introduced, and each introduced hypothesis is used to simplify later ones and the final target. As with `simp`, a list of simplification lemmas can be provided. The modifiers `only` and `with` behave as with `simp`. -/ meta def simp_intros (ids : parse ident_*) (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (cfg : simp_intros_config := {}) : tactic unit := do (s, u) ← mk_simp_set no_dflt attr_names hs, when (¬u.empty) (fail (sformat! "simp_intros tactic does not support {u}")), tactic.simp_intros s u ids cfg, try triv >> try (reflexivity reducible) private meta def to_simp_arg_list (es : list pexpr) : list simp_arg_type := es.map simp_arg_type.expr /-- `dsimp` is similar to `simp`, except that it only uses definitional equalities. -/ meta def dsimp (no_dflt : parse only_flag) (es : parse simp_arg_list) (attr_names : parse with_ident_list) (l : parse location) (cfg : dsimp_config := {}) : tactic unit := do (s, u) ← mk_simp_set no_dflt attr_names es, match l with | loc.wildcard := do ls ← local_context, n ← revert_lst ls, dsimp_target s u cfg, intron n | _ := l.apply (λ h, dsimp_hyp h s u cfg) (dsimp_target s u cfg) end /-- This tactic applies to a goal whose target has the form `t ~ u` where `~` is a reflexive relation, that is, a relation which has a reflexivity lemma tagged with the attribute `[refl]`. The tactic checks whether `t` and `u` are definitionally equal and then solves the goal. -/ meta def reflexivity : tactic unit := tactic.reflexivity /-- Shorter name for the tactic `reflexivity`. -/ meta def refl : tactic unit := tactic.reflexivity /-- This tactic applies to a goal whose target has the form `t ~ u` where `~` is a symmetric relation, that is, a relation which has a symmetry lemma tagged with the attribute `[symm]`. It replaces the target with `u ~ t`. -/ meta def symmetry : tactic unit := tactic.symmetry /-- This tactic applies to a goal whose target has the form `t ~ u` where `~` is a transitive relation, that is, a relation which has a transitivity lemma tagged with the attribute `[trans]`. `transitivity s` replaces the goal with the two subgoals `t ~ s` and `s ~ u`. If `s` is omitted, then a metavariable is used instead. -/ meta def transitivity (q : parse texpr?) : tactic unit := tactic.transitivity >> match q with | none := skip | some q := do (r, lhs, rhs) ← target_lhs_rhs, i_to_expr q >>= unify rhs end /-- Proves a goal with target `s = t` when `s` and `t` are equal up to the associativity and commutativity of their binary operations. -/ meta def ac_reflexivity : tactic unit := tactic.ac_refl /-- An abbreviation for `ac_reflexivity`. -/ meta def ac_refl : tactic unit := tactic.ac_refl /-- Tries to prove the main goal using congruence closure. -/ meta def cc : tactic unit := tactic.cc /-- Given hypothesis `h : x = t` or `h : t = x`, where `x` is a local constant, `subst h` substitutes `x` by `t` everywhere in the main goal and then clears `h`. -/ meta def subst (q : parse texpr) : tactic unit := i_to_expr q >>= tactic.subst >> try (tactic.reflexivity reducible) /-- `clear h₁ ... hₙ` tries to clear each hypothesis `hᵢ` from the local context. -/ meta def clear : parse ident* → tactic unit := tactic.clear_lst private meta def to_qualified_name_core : name → list name → tactic name | n [] := fail $ "unknown declaration '" ++ to_string n ++ "'" | n (ns::nss) := do curr ← return $ ns ++ n, env ← get_env, if env.contains curr then return curr else to_qualified_name_core n nss private meta def to_qualified_name (n : name) : tactic name := do env ← get_env, if env.contains n then return n else do ns ← open_namespaces, to_qualified_name_core n ns private meta def to_qualified_names : list name → tactic (list name) | [] := return [] | (c::cs) := do new_c ← to_qualified_name c, new_cs ← to_qualified_names cs, return (new_c::new_cs) /-- Similar to `unfold`, but only uses definitional equalities. -/ meta def dunfold (cs : parse ident*) (l : parse location) (cfg : dunfold_config := {}) : tactic unit := match l with | (loc.wildcard) := do ls ← tactic.local_context, n ← revert_lst ls, new_cs ← to_qualified_names cs, dunfold_target new_cs cfg, intron n | _ := do new_cs ← to_qualified_names cs, l.apply (λ h, dunfold_hyp cs h cfg) (dunfold_target new_cs cfg) end private meta def delta_hyps : list name → list name → tactic unit | cs [] := skip | cs (h::hs) := get_local h >>= delta_hyp cs >> delta_hyps cs hs /-- Similar to `dunfold`, but performs a raw delta reduction, rather than using an equation associated with the defined constants. -/ meta def delta : parse ident* → parse location → tactic unit | cs (loc.wildcard) := do ls ← tactic.local_context, n ← revert_lst ls, new_cs ← to_qualified_names cs, delta_target new_cs, intron n | cs l := do new_cs ← to_qualified_names cs, l.apply (delta_hyp new_cs) (delta_target new_cs) private meta def unfold_projs_hyps (cfg : unfold_proj_config := {}) (hs : list name) : tactic bool := hs.mfoldl (λ r h, do h ← get_local h, (unfold_projs_hyp h cfg >> return tt) <|> return r) ff /-- This tactic unfolds all structure projections. -/ meta def unfold_projs (l : parse location) (cfg : unfold_proj_config := {}) : tactic unit := match l with | loc.wildcard := do ls ← local_context, b₁ ← unfold_projs_hyps cfg (ls.map expr.local_pp_name), b₂ ← (tactic.unfold_projs_target cfg >> return tt) <|> return ff, when (not b₁ ∧ not b₂) (fail "unfold_projs failed to simplify") | _ := l.try_apply (λ h, unfold_projs_hyp h cfg) (tactic.unfold_projs_target cfg) <|> fail "unfold_projs failed to simplify" end end interactive meta def ids_to_simp_arg_list (tac_name : name) (cs : list name) : tactic (list simp_arg_type) := cs.mmap $ λ c, do n ← resolve_name c, hs ← get_eqn_lemmas_for ff n.const_name, env ← get_env, let p := env.is_projection n.const_name, when (hs.empty ∧ p.is_none) (fail (sformat! "{tac_name} tactic failed, {c} does not have equational lemmas nor is a projection")), return $ simp_arg_type.expr (expr.const c []) structure unfold_config extends simp_config := (zeta := ff) (proj := ff) (eta := ff) (canonize_instances := ff) namespace interactive open interactive interactive.types expr /-- Given defined constants `e₁ ... eₙ`, `unfold e₁ ... eₙ` iteratively unfolds all occurrences in the target of the main goal, using equational lemmas associated with the definitions. As with `simp`, the `at` modifier can be used to specify locations for the unfolding. -/ meta def unfold (cs : parse ident*) (locat : parse location) (cfg : unfold_config := {}) : tactic unit := do es ← ids_to_simp_arg_list "unfold" cs, let no_dflt := tt, simp_core cfg.to_simp_config failed no_dflt es [] locat /-- Similar to `unfold`, but does not iterate the unfolding. -/ meta def unfold1 (cs : parse ident*) (locat : parse location) (cfg : unfold_config := {single_pass := tt}) : tactic unit := unfold cs locat cfg /-- If the target of the main goal is an `opt_param`, assigns the default value. -/ meta def apply_opt_param : tactic unit := tactic.apply_opt_param /-- If the target of the main goal is an `auto_param`, executes the associated tactic. -/ meta def apply_auto_param : tactic unit := tactic.apply_auto_param /-- Fails if the given tactic succeeds. -/ meta def fail_if_success (tac : itactic) : tactic unit := tactic.fail_if_success tac /-- Succeeds if the given tactic fails. -/ meta def success_if_fail (tac : itactic) : tactic unit := tactic.success_if_fail tac meta def guard_expr_eq (t : expr) (p : parse $ tk ":=" *> texpr) : tactic unit := do e ← to_expr p, guard (alpha_eqv t e) /-- `guard_target t` fails if the target of the main goal is not `t`. We use this tactic for writing tests. -/ meta def guard_target (p : parse texpr) : tactic unit := do t ← target, guard_expr_eq t p /-- `guard_hyp h := t` fails if the hypothesis `h` does not have type `t`. We use this tactic for writing tests. -/ meta def guard_hyp (n : parse ident) (p : parse $ tk ":=" *> texpr) : tactic unit := do h ← get_local n >>= infer_type, guard_expr_eq h p /-- `match_target t` fails if target does not match pattern `t`. -/ meta def match_target (t : parse texpr) (m := reducible) : tactic unit := tactic.match_target t m >> skip /-- `by_cases (h :)? p` splits the main goal into two cases, assuming `h : p` in the first branch, and `h : ¬ p` in the second branch. This tactic requires that `p` is decidable. To ensure that all propositions are decidable via classical reasoning, use `local attribute classical.prop_decidable [instance]`. -/ meta def by_cases : parse cases_arg_p → tactic unit | (n, q) := concat_tags $ do p ← tactic.to_expr_strict q, tactic.by_cases p (n.get_or_else `h), pos_g :: neg_g :: rest ← get_goals, return [(`pos, pos_g), (`neg, neg_g)] /-- Apply function extensionality and introduce new hypotheses. The tactic `funext` will keep applying new the `funext` lemma until the goal target is not reducible to ``` |- ((fun x, ...) = (fun x, ...)) ``` The variant `funext h₁ ... hₙ` applies `funext` `n` times, and uses the given identifiers to name the new hypotheses. -/ meta def funext : parse ident_* → tactic unit | [] := tactic.funext >> skip | hs := funext_lst hs >> skip /-- If the target of the main goal is a proposition `p`, `by_contradiction h` reduces the goal to proving `false` using the additional hypothesis `h : ¬ p`. If `h` is omitted, a name is generated automatically. This tactic requires that `p` is decidable. To ensure that all propositions are decidable via classical reasoning, use `local attribute classical.prop_decidable [instance]`. -/ meta def by_contradiction (n : parse ident?) : tactic unit := tactic.by_contradiction n >> return () /-- An abbreviation for `by_contradiction`. -/ meta def by_contra (n : parse ident?) : tactic unit := by_contradiction n /-- Type check the given expression, and trace its type. -/ meta def type_check (p : parse texpr) : tactic unit := do e ← to_expr p, tactic.type_check e, infer_type e >>= trace /-- Fail if there are unsolved goals. -/ meta def done : tactic unit := tactic.done private meta def show_aux (p : pexpr) : list expr → list expr → tactic unit | [] r := fail "show tactic failed" | (g::gs) r := do do {set_goals [g], g_ty ← target, ty ← i_to_expr p, unify g_ty ty, set_goals (g :: r.reverse ++ gs), tactic.change ty} <|> show_aux gs (g::r) /-- `show t` finds the first goal whose target unifies with `t`. It makes that the main goal, performs the unification, and replaces the target with the unified version of `t`. -/ meta def «show» (q : parse texpr) : tactic unit := do gs ← get_goals, show_aux q gs [] /-- The tactic `specialize h a₁ ... aₙ` works on local hypothesis `h`. The premises of this hypothesis, either universal quantifications or non-dependent implications, are instantiated by concrete terms coming either from arguments `a₁` ... `aₙ`. The tactic adds a new hypothesis with the same name `h := h a₁ ... aₙ` and tries to clear the previous one. -/ meta def specialize (p : parse texpr) : tactic unit := do e ← i_to_expr p, let h := expr.get_app_fn e, if h.is_local_constant then tactic.note h.local_pp_name none e >> try (tactic.clear h) else tactic.fail "specialize requires a term of the form `h x_1 .. x_n` where `h` appears in the local context" end interactive end tactic section add_interactive open tactic /- See add_interactive -/ private meta def add_interactive_aux (new_namespace : name) : list name → command | [] := return () | (n::ns) := do env ← get_env, d_name ← resolve_constant n, (declaration.defn _ ls ty val hints trusted) ← env.get d_name, (name.mk_string h _) ← return d_name, let new_name := `tactic.interactive <.> h, add_decl (declaration.defn new_name ls ty (expr.const d_name (ls.map level.param)) hints trusted), add_interactive_aux ns /-- Copy a list of meta definitions in the current namespace to tactic.interactive. This command is useful when we want to update tactic.interactive without closing the current namespace. -/ meta def add_interactive (ns : list name) (p : name := `tactic.interactive) : command := add_interactive_aux p ns meta def has_dup : tactic bool := do ctx ← local_context, let p : name_set × bool := ctx.foldl (λ ⟨s, r⟩ h, if r then (s, r) else if s.contains h.local_pp_name then (s, tt) else (s.insert h.local_pp_name, ff)) (mk_name_set, ff), return p.2 /-- Renames hypotheses with the same name. -/ meta def dedup : tactic unit := mwhen has_dup $ do ctx ← local_context, n ← revert_lst ctx, intron n end add_interactive
0f1721053926d2ff90daf29b5456e7bcb49fc678
798dd332c1ad790518589a09bc82459fb12e5156
/order/filter.lean
d198de6128d66ce13e4d0b111ffb6d1fe22f1e15
[ "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
75,625
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 Theory of filters on sets. -/ import order.galois_connection data.set data.finset order.zorn open lattice set universes u v w x y local attribute [instance] classical.prop_decidable namespace lattice variables {α : Type u} {ι : Sort v} section variable [complete_lattice α] lemma Inf_eq_finite_sets {s : set α} : Inf s = (⨅ t ∈ { t | finite t ∧ t ⊆ s}, Inf t) := le_antisymm (le_infi $ assume t, le_infi $ assume ⟨_, h⟩, Inf_le_Inf h) (le_Inf $ assume b h, infi_le_of_le {b} $ infi_le_of_le (by simp [h]) $ Inf_le $ by simp) lemma infi_insert_finset {ι : Type v} {s : finset ι} {f : ι → α} {i : ι} : (⨅j∈insert i s, f j) = f i ⊓ (⨅j∈s, f j) := by simp [infi_or, infi_inf_eq] lemma infi_empty_finset {ι : Type v} {f : ι → α} : (⨅j∈(∅ : finset ι), f j) = ⊤ := by simp end -- TODO: move lemma inf_left_comm [semilattice_inf α] (a b c : α) : a ⊓ (b ⊓ c) = b ⊓ (a ⊓ c) := by rw [← inf_assoc, ← inf_assoc, @inf_comm α _ a] def complete_lattice.copy (c : complete_lattice α) (le : α → α → Prop) (eq_le : le = @complete_lattice.le α c) (top : α) (eq_top : top = @complete_lattice.top α c) (bot : α) (eq_bot : bot = @complete_lattice.bot α c) (sup : α → α → α) (eq_sup : sup = @complete_lattice.sup α c) (inf : α → α → α) (eq_inf : inf = @complete_lattice.inf α c) (Sup : set α → α) (eq_Sup : Sup = @complete_lattice.Sup α c) (Inf : set α → α) (eq_Inf : Inf = @complete_lattice.Inf α c) : complete_lattice α := begin refine { le := le, top := top, bot := bot, sup := sup, inf := inf, Sup := Sup, Inf := Inf, ..}; subst_vars, exact @complete_lattice.le_refl α c, exact @complete_lattice.le_trans α c, exact @complete_lattice.le_antisymm α c, exact @complete_lattice.le_sup_left α c, exact @complete_lattice.le_sup_right α c, exact @complete_lattice.sup_le α c, exact @complete_lattice.inf_le_left α c, exact @complete_lattice.inf_le_right α c, exact @complete_lattice.le_inf α c, exact @complete_lattice.le_top α c, exact @complete_lattice.bot_le α c, exact @complete_lattice.le_Sup α c, exact @complete_lattice.Sup_le α c, exact @complete_lattice.Inf_le α c, exact @complete_lattice.le_Inf α c end end lattice namespace set variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} {ι : Sort y} theorem monotone_inter [preorder β] {f g : β → set α} (hf : monotone f) (hg : monotone g) : monotone (λx, (f x) ∩ (g x)) := assume a b h x ⟨h₁, h₂⟩, ⟨hf h h₁, hg h 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 end set open set lattice section order variables {α : Type u} (r : α → α → Prop) local infix `≼` : 50 := r /-- A family of elements of α is directed (with respect to a relation `≼` on α) if there is a member of the family `≼`-above any pair in the family. -/ def directed {ι : Sort v} (f : ι → α) := ∀x y, ∃z, f z ≼ f x ∧ f z ≼ f y /-- A subset of α is directed if there is an element of the set `≼`-above any pair of elements in the set. -/ def directed_on (s : set α) := ∀ (x ∈ s) (y ∈ s), ∃z ∈ s, z ≼ x ∧ z ≼ y 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 [directed_on]; 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₂⟩ end order theorem directed_of_chain {α : Type u} {β : Type v} [preorder β] {f : α → β} {c : set α} (h : zorn.chain (λa b, f b ≤ f a) c) : directed (≤) (λx:{a:α // a ∈ c}, f (x.val)) := assume ⟨a, ha⟩ ⟨b, hb⟩, classical.by_cases (assume : a = b, by simp [this]; exact ⟨b, hb, le_refl _⟩) (assume : a ≠ b, have f b ≤ f a ∨ f a ≤ f b, from h a ha b hb this, or.elim this (assume : f b ≤ f a, ⟨⟨b, hb⟩, this, le_refl _⟩) (assume : f a ≤ f b, ⟨⟨a, ha⟩, le_refl _, this⟩)) 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) namespace filter variables {α : Type u} {f g : filter α} {s t : set α} 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.sets ↔ s ∈ g.sets := by rw [filter_eq_iff, ext_iff] @[extensionality] protected lemma ext : (∀ s, s ∈ f.sets ↔ s ∈ g.sets) → f = g := filter.ext_iff.2 lemma univ_mem_sets : univ ∈ f.sets := f.univ_sets lemma mem_sets_of_superset : ∀{x y : set α}, x ∈ f.sets → x ⊆ y → y ∈ f.sets := f.sets_of_superset lemma inter_mem_sets : ∀{s t}, s ∈ f.sets → t ∈ f.sets → s ∩ t ∈ f.sets := f.inter_sets lemma univ_mem_sets' (h : ∀ a, a ∈ s): s ∈ f.sets := mem_sets_of_superset univ_mem_sets (assume x _, h x) lemma mp_sets (hs : s ∈ f.sets) (h : {x | x ∈ s → x ∈ t} ∈ f.sets) : t ∈ f.sets := mem_sets_of_superset (inter_mem_sets hs h) $ assume x ⟨h₁, h₂⟩, h₂ h₁ lemma Inter_mem_sets {β : Type v} {s : β → set α} {is : set β} (hf : finite is) : (∀i∈is, s i ∈ f.sets) → (⋂i∈is, s i) ∈ f.sets := finite.induction_on hf (assume hs, by simp [univ_mem_sets]) (assume i is _ hf hi hs, have h₁ : s i ∈ f.sets, from hs i (by simp), have h₂ : (⋂x∈is, s x) ∈ f.sets, from hi $ assume a ha, hs _ $ by simp [ha], by simp [inter_mem_sets h₁ h₂]) lemma exists_sets_subset_iff : (∃t∈f.sets, t ⊆ s) ↔ s ∈ f.sets := ⟨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.sets) := assume s t hst h, mem_sets_of_superset h hst end filter namespace tactic.interactive open tactic interactive /-- `filter [t1, ⋯, tn]` replaces a goal of the form `s ∈ f.sets` and terms `h1 : t1 ∈ f.sets, ⋯, tn ∈ f.sets` with `∀x, x ∈ t1 → ⋯ → x ∈ tn → x ∈ s`. `filter [t1, ⋯, tn] e` is a short form for `{ filter [t1, ⋯, tn], 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', match e' with | some e := interactive.exact e | none := skip end 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 } instance : inhabited (filter α) := ⟨principal ∅⟩ @[simp] lemma mem_principal_sets {s t : set α} : s ∈ (principal t).sets ↔ t ⊆ s := iff.rfl lemma mem_principal_self (s : set α) : s ∈ (principal s).sets := subset.refl _ end principal 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.sets} ∈ f.sets}, univ_sets := by simp [univ_mem_sets]; exact univ_mem_sets, 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).sets ↔ {t | s ∈ filter.sets t} ∈ f.sets := iff.rfl end join section lattice instance : partial_order (filter α) := { le := λf g, g.sets ⊆ f.sets, 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.sets, x ∈ f.sets := 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 := {s | generate_sets g s}, 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)) protected def mk_of_closure (s : set (set α)) (hs : (generate s).sets = s) : filter α := { sets := s, univ_sets := hs ▸ univ_mem_sets, sets_of_superset := assume x y, hs ▸ mem_sets_of_superset, inter_sets := assume x y, hs ▸ inter_mem_sets } 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, hs.symm ▸ iff.refl _ /- Galois insertion from sets of sets into a 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, generate_sets.basic, 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.sets) (b ∈ g.sets), 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).sets ↔ ∃t₁∈f.sets, ∃t₂∈g.sets, t₁ ∩ t₂ ⊆ s := iff.rfl lemma mem_inf_sets_of_left {f g : filter α} {s : set α} (h : s ∈ f.sets) : s ∈ (f ⊓ g).sets := ⟨s, h, univ, univ_mem_sets, inter_subset_left _ _⟩ lemma mem_inf_sets_of_right {f g : filter α} {s : set α} (h : s ∈ g.sets) : s ∈ (f ⊓ g).sets := ⟨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.sets) (ht : t ∈ g.sets) : s ∩ t ∈ (f ⊓ g).sets := 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 α).sets ↔ (∀x, x ∈ s) := iff.refl _ @[simp] lemma mem_top_sets {s : set α} : s ∈ (⊤ : filter α).sets ↔ 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.lattice.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.lattice.has_top).1 (top_unique $ assume s hs, (eq_univ_of_forall hs).symm ▸ univ_mem_sets) /- bot -/ _ rfl /- sup -/ _ rfl /- inf -/ (filter.lattice.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⟩, mem_sets_of_superset (inter_mem_sets (@inf_le_left (filter α) _ _ _ _ ha) (@inf_le_right (filter α) _ _ _ _ hb)) hs) end /- Sup -/ (join ∘ principal) (by ext s x; exact (@mem_bInter_iff _ _ s filter.sets x).symm) /- Inf -/ _ rfl end complete_lattice 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 α).sets := trivial @[simp] lemma mem_sup_sets {f g : filter α} {s : set α} : s ∈ (f ⊔ g).sets ↔ s ∈ f.sets ∧ s ∈ g.sets := iff.rfl @[simp] lemma mem_Sup_sets {x : set α} {s : set (filter α)} : x ∈ (Sup s).sets ↔ (∀f∈s, x ∈ (f:filter α).sets) := iff.rfl @[simp] lemma mem_supr_sets {x : set α} {f : ι → filter α} : x ∈ (supr f).sets ↔ (∀i, x ∈ (f i).sets) := by simp [supr_sets_eq] @[simp] lemma le_principal_iff {s : set α} {f : filter α} : f ≤ principal s ↔ s ∈ f.sets := show (∀{t}, s ⊆ t → t ∈ f.sets) ↔ s ∈ f.sets, from ⟨assume h, h (subset.refl s), assume hs t ht, mem_sets_of_superset hs ht⟩ lemma principal_mono {s t : set α} : principal s ≤ principal t ↔ s ⊆ t := by simp lemma monotone_principal : monotone (principal : set α → filter α) := by simp [monotone, principal_mono]; exact assume a b h, h @[simp] lemma principal_eq_iff_eq {s t : set α} : principal s = principal t ↔ s = t := by simp [le_antisymm_iff]; refl @[simp] lemma join_principal_eq_Sup {s : set (filter α)} : join (principal s) = Sup s := rfl /- lattice equations -/ lemma empty_in_sets_eq_bot {f : filter α} : ∅ ∈ f.sets ↔ f = ⊥ := ⟨assume h, bot_unique $ assume s _, mem_sets_of_superset h (empty_subset s), assume : f = ⊥, this.symm ▸ mem_bot_sets⟩ lemma inhabited_of_mem_sets {f : filter α} {s : set α} (hf : f ≠ ⊥) (hs : s ∈ f.sets) : ∃x, x ∈ s := have ∅ ∉ f.sets, from assume h, hf $ empty_in_sets_eq_bot.mp h, have s ≠ ∅, from assume h, this (h ▸ hs), exists_mem_of_ne_empty this 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_neq_empty_iff_neq_bot {f : filter α} : (∀ (s : set α), s ∈ f.sets → s ≠ ∅) ↔ f ≠ ⊥ := by simp [(@empty_in_sets_eq_bot α f).symm]; exact ⟨assume h hs, h _ hs rfl, assume h s hs eq, h $ eq ▸ hs⟩ lemma mem_sets_of_neq_bot {f : filter α} {s : set α} (h : f ⊓ principal (-s) = ⊥) : s ∈ f.sets := have ∅ ∈ (f ⊓ principal (- s)).sets, 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 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 := begin simp, exact ⟨i, univ_mem_sets⟩ end, sets_of_superset := begin simp, assume x y i hx hxy, exact ⟨i, mem_sets_of_superset hx hxy⟩ end, inter_sets := begin simp, 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 subset.antisymm (show u ≤ infi f, from le_infi $ assume i, le_supr (λi, (f i).sets) i) (Union_subset $ assume i, infi_le f i) lemma infi_sets_eq' {f : β → filter α} {s : set β} (h : directed_on (λx y, f x ≤ f y) s) (ne : ∃i, i ∈ s) : (⨅ i∈s, f i).sets = (⋃ i ∈ s, (f i).sets) := let ⟨i, hi⟩ := ne in calc (⨅ i ∈ s, f i).sets = (⨅ t : {t // t ∈ s}, (f t.val)).sets : by rw [infi_subtype]; refl ... = (⨆ t : {t // t ∈ s}, (f t.val).sets) : infi_sets_eq (assume ⟨x, hx⟩ ⟨y, hy⟩, match h x hx y hy with ⟨z, h₁, h₂, h₃⟩ := ⟨⟨z, h₁⟩, h₂, h₃⟩ end) ⟨⟨i, hi⟩⟩ ... = (⨆ t ∈ {t | t ∈ s}, (f t).sets) : by rw [supr_subtype]; refl lemma Inf_sets_eq_finite {s : set (filter α)} : (Inf s).sets = (⋃ t ∈ {t | finite t ∧ t ⊆ s}, (Inf t).sets) := calc (Inf s).sets = (⨅ t ∈ { t | finite t ∧ t ⊆ s}, Inf t).sets : by rw [lattice.Inf_eq_finite_sets] ... = (⨆ t ∈ {t | finite t ∧ t ⊆ s}, (Inf t).sets) : infi_sets_eq' (assume x ⟨hx₁, hx₂⟩ y ⟨hy₁, hy₂⟩, ⟨x ∪ y, ⟨finite_union hx₁ hy₁, union_subset hx₂ hy₂⟩, Inf_le_Inf $ subset_union_left _ _, Inf_le_Inf $ subset_union_right _ _⟩) ⟨∅, by simp⟩ @[simp] lemma sup_join {f₁ f₂ : filter (filter α)} : (join f₁ ⊔ join f₂) = join (f₁ ⊔ f₂) := filter_eq $ set.ext $ assume x, by simp [supr_sets_eq, join] @[simp] lemma supr_join {ι : Sort w} {f : ι → filter (filter α)} : (⨆x, join (f x)) = join (⨆x, f x) := filter_eq $ set.ext $ assume x, by simp [supr_sets_eq, join] 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.lattice.complete_lattice } private lemma infi_finite_distrib {s : set (filter α)} {f : filter α} (h : finite s) : (⨅ a ∈ s, f ⊔ a) = f ⊔ (Inf s) := finite.induction_on h (by simp only [mem_empty_eq, infi_false, infi_top, Inf_empty, sup_top_eq]) (by intros a s hn hs hi; rw [infi_insert, hi, ← sup_inf_left, Inf_insert]) /- the complementary version with ⨆ g∈s, f ⊓ g does not hold! -/ lemma binfi_sup_eq { f : filter α } {s : set (filter α)} : (⨅ g∈s, f ⊔ g) = f ⊔ Inf s := le_antisymm begin intros t h, cases h with h₁ h₂, rw [Inf_sets_eq_finite] at h₂, simp [and_assoc] at h₂, rcases h₂ with ⟨s', hs', hs's, ht'⟩, have ht : t ∈ (⨅ a ∈ s', f ⊔ a).sets, { rw [infi_finite_distrib], exact ⟨h₁, ht'⟩, exact hs' }, clear h₁ ht', revert ht t, change (⨅ a ∈ s, f ⊔ a) ≤ (⨅ a ∈ s', f ⊔ a), apply infi_le_infi2 _, exact assume i, ⟨i, infi_le_infi2 $ assume h, ⟨hs's h, le_refl _⟩⟩ end (le_infi $ assume g, le_infi $ assume h, sup_le_sup (le_refl f) $ Inf_le h) lemma infi_sup_eq { f : filter α } {g : ι → filter α} : (⨅ x, f ⊔ g x) = f ⊔ infi g := calc (⨅ x, f ⊔ g x) = (⨅ x (h : ∃i, g i = x), f ⊔ x) : by simp; rw [infi_comm]; simp ... = f ⊔ Inf {x | ∃i, g i = x} : binfi_sup_eq ... = f ⊔ infi g : by rw [Inf_eq_infi]; dsimp; simp; rw [infi_comm]; simp lemma mem_infi_sets_finset {s : finset α} {f : α → filter β} : ∀t, t ∈ (⨅a∈s, f a).sets ↔ (∃p:α → set β, (∀a∈s, p a ∈ (f a).sets) ∧ (⋂a∈s, p a) ⊆ t) := show ∀t, t ∈ (⨅a∈s, f a).sets ↔ (∃p:α → set β, (∀a∈s, p a ∈ (f a).sets) ∧ (⨅a∈s, p a) ≤ t), begin refine finset.induction_on s _ _, { simp only [finset.not_mem_empty, false_implies_iff, lattice.infi_empty_finset, 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, lattice.infi_insert_finset, 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 : (⨅j ∈ s, function.update p a t₁ j) = (⨅j ∈ s, p j), begin congr, funext b, congr, funext h, apply this, assumption end, 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 }, from assume p hpa hp ht, ⟨p a, hpa, (⨅j∈s, p j), ⟨⟨p, hp, le_refl _⟩, ht⟩⟩ } end /- principal equations -/ @[simp] lemma inf_principal {s t : set α} : principal s ⊓ principal t = principal (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 α} : principal s ⊔ principal t = principal (s ∪ t) := filter_eq $ set.ext $ by simp [union_subset_iff] @[simp] lemma supr_principal {ι : Sort w} {s : ι → set α} : (⨆x, principal (s x)) = principal (⋃i, s i) := filter_eq $ set.ext $ assume x, by simp [supr_sets_eq]; exact (@supr_le_iff (set α) _ _ _ _).symm lemma principal_univ : principal (univ : set α) = ⊤ := top_unique $ by simp lemma principal_empty : principal (∅ : set α) = ⊥ := bot_unique $ assume s _, empty_subset _ @[simp] lemma principal_eq_bot_iff {s : set α} : principal s = ⊥ ↔ s = ∅ := ⟨assume h, principal_eq_iff_eq.mp $ by simp [principal_empty, h], assume h, by simp [*, principal_empty]⟩ lemma inf_principal_eq_bot {f : filter α} {s : set α} (hs : -s ∈ f.sets) : f ⊓ principal s = ⊥ := empty_in_sets_eq_bot.mp ⟨_, hs, s, mem_principal_self s, assume x ⟨h₁, h₂⟩, h₁ h₂⟩ end lattice 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 (principal s) = principal (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 mem_map : t ∈ (map m f).sets ↔ {x | m x ∈ t} ∈ f.sets := iff.rfl lemma image_mem_map (hs : s ∈ f.sets) : m '' s ∈ (map m f).sets := f.sets_of_superset hs $ subset_preimage_image m s @[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 end map section comap /-- The inverse map of a filter -/ def comap (m : α → β) (f : filter β) : filter α := { sets := { s | ∃t∈f.sets, m ⁻¹' t ⊆ s }, univ_sets := ⟨univ, univ_mem_sets, by simp⟩, 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₂⟩ } end comap /-- The cofinite filter is the filter of subsets whose complements are finite. -/ def cofinite : filter α := { sets := {s | finite (- s)}, univ_sets := by simp, sets_of_superset := assume s t (hs : finite (-s)) (st: s ⊆ t), finite_subset hs $ @lattice.neg_le_neg (set α) _ _ _ st, inter_sets := assume s t (hs : finite (-s)) (ht : finite (-t)), by simp [compl_inter, finite_union, ht, hs] } /-- The monadic bind operation on filter is defined the usual way in terms of `map` and `join`. -/ def bind (f : filter α) (m : α → filter β) : filter β := join (map m f) instance : monad filter := { bind := @bind, pure := λ(α : Type u) x, principal {x}, map := @filter.map } instance : is_lawful_monad filter := { id_map := assume α f, filter_eq rfl, pure_bind := assume α β a f, by simp [bind, Sup_image], bind_assoc := assume α β γ f m₁ m₂, filter_eq rfl, bind_pure_comp_eq_map := assume α β f x, filter_eq $ by simp [bind, join, map, preimage, principal] } @[simp] lemma pure_def (x : α) : pure x = principal {x} := rfl @[simp] lemma mem_pure {a : α} {s : set α} : a ∈ s → s ∈ (pure a : filter α).sets := by simp; exact id @[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 instance : alternative filter := { failure := λα, ⊥, orelse := λα x y, x ⊔ y } /- 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).sets ↔ ∃t∈g.sets, m ⁻¹' t ⊆ s := iff.rfl theorem preimage_mem_comap (ht : t ∈ g.sets) : m ⁻¹' t ∈ (comap m g).sets := ⟨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_comap_comp {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 (principal t) = principal (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⟩⟩ 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 lemma map_mono (h : f₁ ≤ f₂) : map m f₁ ≤ map m f₂ := (gc_map_comap m).monotone_l h lemma monotone_map : monotone (map m) | a b := map_mono lemma comap_mono (h : g₁ ≤ g₂) : comap m g₁ ≤ comap m g₂ := (gc_map_comap m).monotone_u h lemma monotone_comap : monotone (comap m) | a b := comap_mono @[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 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, by simp⟩ 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₂⟩) (sup_le (comap_mono le_sup_left) (comap_mono le_sup_right)) lemma le_map_comap' {f : filter β} {m : α → β} {s : set β} (hs : s ∈ f.sets) (hm : ∀b∈s, ∃a, m a = b) : f ≤ map m (comap m f) := assume t' ⟨t, ht, (sub : m ⁻¹' t ⊆ m ⁻¹' t')⟩, by filter_upwards [ht, hs] assume x hxt hxs, let ⟨y, hy⟩ := hm x hxs in hy ▸ sub (show m y ∈ t, from hy.symm ▸ hxt) lemma le_map_comap {f : filter β} {m : α → β} (hm : ∀x, ∃y, m y = x) : f ≤ map m (comap m f) := le_map_comap' univ_mem_sets (assume b _, hm b) lemma comap_map {f : filter α} {m : α → β} (h : ∀ x y, m x = m y → x = y) : comap m (map m f) = f := have ∀s, preimage m (image m s) = s, from assume s, preimage_image_eq s h, le_antisymm (assume s hs, ⟨ image m s, f.sets_of_superset hs $ by simp [this, subset.refl], by simp [this, subset.refl]⟩) le_comap_map lemma le_of_map_le_map_inj' {f g : filter α} {m : α → β} {s : set α} (hsf : s ∈ f.sets) (hsg : s ∈ g.sets) (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.sets) (hsg : s ∈ g.sets) (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) map_mono lemma eq_of_map_eq_map_inj' {f g : filter α} {m : α → β} {s : set α} (hsf : s ∈ f.sets) (hsg : s ∈ g.sets) (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 lemma comap_neq_bot {f : filter β} {m : α → β} (hm : ∀t∈f.sets, ∃a, m a ∈ t) : comap m f ≠ ⊥ := forall_sets_neq_empty_iff_neq_bot.mp $ assume s ⟨t, ht, t_s⟩, let ⟨a, (ha : a ∈ preimage m t)⟩ := hm t ht in neq_bot_of_le_neq_bot (ne_empty_of_mem ha) t_s lemma comap_neq_bot_of_surj {f : filter β} {m : α → β} (hf : f ≠ ⊥) (hm : ∀b, ∃a, m a = b) : comap m f ≠ ⊥ := comap_neq_bot $ assume t ht, let ⟨b, (hx : b ∈ t)⟩ := inhabited_of_mem_sets hf ht, ⟨a, (ha : m a = b)⟩ := hm b in ⟨a, ha.symm ▸ hx⟩ @[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 [*]⟩ lemma map_ne_bot (hf : f ≠ ⊥) : map m f ≠ ⊥ := assume h, hf $ by rwa [map_eq_bot_iff] at h lemma sInter_comap_sets (f : α → β) (F : filter β) : ⋂₀(comap f F).sets = ⋂ U ∈ F.sets, f ⁻¹' U := begin ext x, suffices : (∀ (A : set α) (B : set β), B ∈ F.sets → f ⁻¹' B ⊆ A → x ∈ A) ↔ ∀ (B : set β), B ∈ F.sets → f x ∈ B, by simp [set.mem_sInter, set.mem_Inter, mem_comap_sets, this], split, { intros h U U_in, simpa [set.subset.refl] 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 lemma map_cong {m₁ m₂ : α → β} {f : filter α} (h : {x | m₁ x = m₂ x} ∈ f.sets) : map m₁ f = map m₂ f := have ∀(m₁ m₂ : α → β) (h : {x | m₁ x = m₂ x} ∈ f.sets), map m₁ f ≤ map m₂ f, begin intros m₁ m₂ h s hs, show {x | m₁ x ∈ s} ∈ f.sets, filter_upwards [h, hs], simp [subset_def] {contextual := tt} end, le_antisymm (this m₁ m₂ h) (this m₂ m₁ $ mem_sets_of_superset h $ assume x, eq.symm) -- 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) (hι : nonempty ι) : map m (infi f) = (⨅ i, map m (f i)) := le_antisymm map_infi_le (assume s (hs : preimage m s ∈ (infi f).sets), have ∃i, preimage m s ∈ (f i).sets, by simp [infi_sets_eq hf hι] at hs; assumption, let ⟨i, hi⟩ := this in have (⨅ i, map m (f i)) ≤ principal s, from infi_le_of_le i $ by simp; assumption, by simp at this; assumption) lemma map_binfi_eq {ι : Type w} {f : ι → filter α} {m : α → β} {p : ι → Prop} (h : directed_on (λx y, f x ≤ f y) {x | p x}) (ne : ∃i, p i) : map m (⨅i (h : p i), f i) = (⨅i (h: p i), map m (f i)) := let ⟨i, hi⟩ := ne in calc map m (⨅i (h : p i), f i) = map m (⨅i:subtype p, f i.val) : by simp [infi_subtype] ... = (⨅i:subtype p, map m (f i.val)) : map_infi_eq (assume ⟨x, hx⟩ ⟨y, hy⟩, match h x hx y hy with ⟨z, h₁, h₂, h₃⟩ := ⟨⟨z, h₁⟩, h₂, h₃⟩ end) ⟨⟨i, hi⟩⟩ ... = (⨅i (h : p i), map m (f i)) : by simp [infi_subtype] lemma map_inf' {f g : filter α} {m : α → β} {t : set α} (htf : t ∈ f.sets) (htg : t ∈ g.sets) (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 (le_inf (map_mono inf_le_left) (map_mono inf_le_right)) (assume s hs, _), simp [map, 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 : ∀ x y, m x = m y → x = y) : map m (f ⊓ g) = map m f ⊓ map m g := map_inf' univ_mem_sets univ_mem_sets (assume x _ y _, h x y) 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 [h₂, preimage_id] ... ⊆ preimage m b : preimage_mono h) (assume b (hb : preimage m b ∈ f.sets), ⟨preimage m b, hb, show preimage (m ∘ n) b ⊆ b, by simp [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 /- bind equations -/ @[simp] lemma mem_bind_sets {s : set β} {f : filter α} {m : α → filter β} : s ∈ (bind f m).sets ↔ ∃t ∈ f.sets, ∀x ∈ t, s ∈ (m x).sets := calc s ∈ (bind f m).sets ↔ {a | s ∈ (m a).sets} ∈ f.sets : by simp [bind] ... ↔ (∃t ∈ f.sets, t ⊆ {a | s ∈ (m a).sets}) : exists_sets_subset_iff.symm ... ↔ (∃t ∈ f.sets, ∀x ∈ t, s ∈ (m x).sets) : iff.refl _ lemma bind_mono {f : filter α} {g h : α → filter β} (h₁ : {a | g a ≤ h a} ∈ f.sets) : bind f g ≤ bind f h := assume x h₂, show (_ ∈ f.sets), by filter_upwards [h₁, h₂] assume s gh' h', gh' h' lemma bind_sup {f g : filter α} {h : α → filter β} : bind (f ⊔ g) h = bind f h ⊔ bind g h := by simp [bind] lemma bind_mono2 {f g : filter α} {h : α → filter β} (h₁ : f ≤ g) : bind f h ≤ bind g h := assume s h', h₁ h' lemma principal_bind {s : set α} {f : α → filter β} : (bind (principal s) f) = (⨆x ∈ s, f x) := show join (map f (principal s)) = (⨆x ∈ s, f x), by simp [Sup_image] lemma seq_mono {β : Type u} {f₁ f₂ : filter (α → β)} {g₁ g₂ : filter α} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁ <*> g₁ ≤ f₂ <*> g₂ := le_trans (bind_mono2 hf) (bind_mono $ univ_mem_sets' $ assume f, map_mono hg) @[simp] lemma mem_pure_sets {a : α} {s : set α} : s ∈ (pure a : filter α).sets ↔ a ∈ s := by simp @[simp] lemma mem_return_sets {a : α} {s : set α} : s ∈ (return a : filter α).sets ↔ a ∈ s := mem_pure_sets lemma infi_neq_bot_of_directed {f : ι → filter α} (hn : nonempty α) (hd : directed (≤) f) (hb : ∀i, f i ≠ ⊥): (infi f) ≠ ⊥ := let ⟨x⟩ := hn in assume h, have he: ∅ ∈ (infi f).sets, from h.symm ▸ mem_bot_sets, classical.by_cases (assume : nonempty ι, have ∃i, ∅ ∈ (f i).sets, by rw [infi_sets_eq hd this] at he; simp at he; assumption, let ⟨i, hi⟩ := this in hb i $ bot_unique $ assume s _, (f i).sets_of_superset hi $ empty_subset _) (assume : ¬ nonempty ι, have univ ⊆ (∅ : set α), begin rw [←principal_mono, principal_univ, principal_empty, ←h], exact (le_infi $ assume i, false.elim $ this ⟨i⟩) end, this $ mem_univ x) lemma infi_neq_bot_iff_of_directed {f : ι → filter α} (hn : nonempty α) (hd : directed (≤) f) : (infi f) ≠ ⊥ ↔ (∀i, f i ≠ ⊥) := ⟨assume neq_bot i eq_bot, neq_bot $ bot_unique $ infi_le_of_le i $ eq_bot ▸ le_refl _, infi_neq_bot_of_directed hn hd⟩ lemma mem_infi_sets {f : ι → filter α} (i : ι) : ∀{s}, s ∈ (f i).sets → s ∈ (⨅i, f i).sets := show (⨅i, f i) ≤ f i, from infi_le _ _ @[elab_as_eliminator] lemma infi_sets_induct {f : ι → filter α} {s : set α} (hs : s ∈ (infi f).sets) {p : set α → Prop} (uni : p univ) (ins : ∀{i s₁ s₂}, s₁ ∈ (f i).sets → p s₂ → p (s₁ ∩ s₂)) (upw : ∀{s₁ s₂}, s₁ ⊆ s₂ → p s₁ → p s₂) : p s := begin have hs' : s ∈ (Inf {a : filter α | ∃ (i : ι), a = f i}).sets := hs, rw [Inf_sets_eq_finite] at hs', simp only [mem_Union] at hs', rcases hs' with ⟨is, ⟨fin_is, his⟩, hs⟩, revert his s, refine finite.induction_on fin_is _ (λ fi is fi_ne_is fin_is ih, _); intros his s hs' hs, { rw [Inf_empty, mem_top_sets] at hs, simpa [hs] }, { rw [Inf_insert] at hs, rcases hs with ⟨s₁, hs₁, s₂, hs₂, hs⟩, rcases (his (mem_insert _ _) : ∃i, fi = f i) with ⟨i, rfl⟩, have hs₂ : p s₂, from have his : is ⊆ {x | ∃i, x = f i}, from assume i hi, his $ mem_insert_of_mem _ hi, have infi f ≤ Inf is, from Inf_le_Inf his, ih his (this hs₂) hs₂, exact upw hs (ins hs₁ hs₂) } end @[simp] lemma pure_neq_bot {α : Type u} {a : α} : pure a ≠ (⊥ : filter α) := by simp [pure, has_pure.pure] /- tendsto -/ /-- `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₂.sets, f ⁻¹' s ∈ l₁.sets := iff.rfl lemma tendsto_iff_comap {f : α → β} {l₁ : filter α} {l₂ : filter β} : tendsto f l₁ l₂ ↔ l₁ ≤ l₂.comap f := map_le_iff_le_comap lemma tendsto_cong {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (h : tendsto f₁ l₁ l₂) (hl : {x | f₁ x = f₂ x} ∈ l₁.sets) : tendsto f₂ l₁ l₂ := by rwa [tendsto, ←map_cong hl] lemma tendsto_id' {x y : filter α} : x ≤ y → tendsto id x y := by simp [tendsto] { 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 γ} (hf : tendsto f x y) (hg : tendsto g y z) : 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_le_left {f : α → β} {x y : filter α} {z : filter β} (h : y ≤ x) : tendsto f x z → tendsto f y z := le_trans (map_mono h) lemma tendsto_le_right {f : α → β} {x : filter α} {y z : filter β} (h₁ : y ≤ z) (h₂ : tendsto f x y) : tendsto f x z := le_trans h₂ 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, h.comp tendsto_comap, assume h, map_le_iff_le_comap.mp $ by rwa [map_map]⟩ lemma tendsto_comap'' {m : α → β} {f : filter α} {g : filter β} (s : set α) {i : γ → α} (hs : s ∈ f.sets) (hi : ∀a∈s, ∃c, i c = a) (h : tendsto (m ∘ i) (comap i f) g) : tendsto m f g := have tendsto m (map i $ comap i $ f) g, by rwa [tendsto, ←map_compose] at h, le_trans (map_mono $ le_map_comap' hs hi) this lemma comap_eq_of_inverse {f : filter α} {g : filter β} {φ : α → β} {ψ : β → α} (inv₁ : φ ∘ ψ = id) (inv₂ : ψ ∘ φ = id) (lim₁ : tendsto φ f g) (lim₂ : tendsto ψ g f) : comap φ g = f := begin have ineq₁ := calc comap φ g = map ψ g : eq.symm (map_eq_comap_of_inverse inv₂ inv₁) ... ≤ f : lim₂, have ineq₂ : f ≤ comap φ g := map_le_iff_le_comap.1 lim₁, exact le_antisymm ineq₁ ineq₂ 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 [tendsto] 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_infi {f : α → β} {x : filter α} {y : ι → filter β} : tendsto f x (⨅i, y i) ↔ ∀i, tendsto f x (y i) := by simp [tendsto] lemma tendsto_infi' {f : α → β} {x : ι → filter α} {y : filter β} (i : ι) : tendsto f (x i) y → tendsto f (⨅i, x i) y := tendsto_le_left (infi_le _ _) lemma tendsto_principal {f : α → β} {a : filter α} {s : set β} : tendsto f a (principal s) ↔ {a | f a ∈ s} ∈ a.sets := by simp [tendsto] lemma tendsto_principal_principal {f : α → β} {s : set α} {t : set β} : tendsto f (principal s) (principal t) ↔ ∀a∈s, f a ∈ t := by simp [tendsto, image_subset_iff]; refl section lift /-- A variant on `bind` using a function `g` taking a set instead of a member of `α`. -/ protected def lift (f : filter α) (g : set α → filter β) := ⨅s ∈ f.sets, g s variables {f f₁ f₂ : filter α} {g g₁ g₂ : set α → filter β} lemma lift_sets_eq (hg : monotone g) : (f.lift g).sets = (⋃t∈f.sets, (g t).sets) := infi_sets_eq' (assume s hs t ht, ⟨s ∩ t, inter_mem_sets hs ht, hg $ inter_subset_left s t, hg $ inter_subset_right s t⟩) ⟨univ, univ_mem_sets⟩ lemma mem_lift {s : set β} {t : set α} (ht : t ∈ f.sets) (hs : s ∈ (g t).sets) : s ∈ (f.lift g).sets := le_principal_iff.mp $ show f.lift g ≤ principal s, from infi_le_of_le t $ infi_le_of_le ht $ le_principal_iff.mpr hs lemma mem_lift_sets (hg : monotone g) {s : set β} : s ∈ (f.lift g).sets ↔ (∃t∈f.sets, s ∈ (g t).sets) := by rw [lift_sets_eq hg]; simp only [mem_Union] lemma lift_le {f : filter α} {g : set α → filter β} {h : filter β} {s : set α} (hs : s ∈ f.sets) (hg : g s ≤ h) : f.lift g ≤ h := infi_le_of_le s $ infi_le_of_le hs $ hg lemma le_lift {f : filter α} {g : set α → filter β} {h : filter β} (hh : ∀s∈f.sets, h ≤ g s) : h ≤ f.lift g := le_infi $ assume s, le_infi $ assume hs, hh s hs lemma lift_mono (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁.lift g₁ ≤ f₂.lift g₂ := infi_le_infi $ assume s, infi_le_infi2 $ assume hs, ⟨hf hs, hg s⟩ lemma lift_mono' (hg : ∀s∈f.sets, g₁ s ≤ g₂ s) : f.lift g₁ ≤ f.lift g₂ := infi_le_infi $ assume s, infi_le_infi $ assume hs, hg s hs lemma map_lift_eq {m : β → γ} (hg : monotone g) : map m (f.lift g) = f.lift (map m ∘ g) := have monotone (map m ∘ g), from monotone_comp hg monotone_map, filter_eq $ set.ext $ by simp [mem_lift_sets, hg, @mem_lift_sets _ _ f _ this] lemma comap_lift_eq {m : γ → β} (hg : monotone g) : comap m (f.lift g) = f.lift (comap m ∘ g) := have monotone (comap m ∘ g), from monotone_comp hg monotone_comap, filter_eq $ set.ext begin simp only [hg, @mem_lift_sets _ _ f _ this, comap, mem_lift_sets, mem_set_of_eq, exists_prop, function.comp_apply], exact λ s, ⟨λ ⟨b, ⟨a, ha, hb⟩, hs⟩, ⟨a, ha, b, hb, hs⟩, λ ⟨a, ha, b, hb, hs⟩, ⟨b, ⟨a, ha, hb⟩, hs⟩⟩ end theorem comap_lift_eq2 {m : β → α} {g : set β → filter γ} (hg : monotone g) : (comap m f).lift g = f.lift (g ∘ preimage m) := le_antisymm (le_infi $ assume s, le_infi $ assume hs, infi_le_of_le (preimage m s) $ infi_le _ ⟨s, hs, subset.refl _⟩) (le_infi $ assume s, le_infi $ assume ⟨s', hs', (h_sub : preimage m s' ⊆ s)⟩, infi_le_of_le s' $ infi_le_of_le hs' $ hg h_sub) lemma map_lift_eq2 {g : set β → filter γ} {m : α → β} (hg : monotone g) : (map m f).lift g = f.lift (g ∘ image m) := le_antisymm (infi_le_infi2 $ assume s, ⟨image m s, infi_le_infi2 $ assume hs, ⟨ f.sets_of_superset hs $ assume a h, mem_image_of_mem _ h, le_refl _⟩⟩) (infi_le_infi2 $ assume t, ⟨preimage m t, infi_le_infi2 $ assume ht, ⟨ht, hg $ assume x, assume h : x ∈ m '' preimage m t, let ⟨y, hy, h_eq⟩ := h in show x ∈ t, from h_eq ▸ hy⟩⟩) lemma lift_comm {g : filter β} {h : set α → set β → filter γ} : f.lift (λs, g.lift (h s)) = g.lift (λt, f.lift (λs, h s t)) := le_antisymm (le_infi $ assume i, le_infi $ assume hi, le_infi $ assume j, le_infi $ assume hj, infi_le_of_le j $ infi_le_of_le hj $ infi_le_of_le i $ infi_le _ hi) (le_infi $ assume i, le_infi $ assume hi, le_infi $ assume j, le_infi $ assume hj, infi_le_of_le j $ infi_le_of_le hj $ infi_le_of_le i $ infi_le _ hi) lemma lift_assoc {h : set β → filter γ} (hg : monotone g) : (f.lift g).lift h = f.lift (λs, (g s).lift h) := le_antisymm (le_infi $ assume s, le_infi $ assume hs, le_infi $ assume t, le_infi $ assume ht, infi_le_of_le t $ infi_le _ $ (mem_lift_sets hg).mpr ⟨_, hs, ht⟩) (le_infi $ assume t, le_infi $ assume ht, let ⟨s, hs, h'⟩ := (mem_lift_sets hg).mp ht in infi_le_of_le s $ infi_le_of_le hs $ infi_le_of_le t $ infi_le _ h') lemma lift_lift_same_le_lift {g : set α → set α → filter β} : f.lift (λs, f.lift (g s)) ≤ f.lift (λs, g s s) := le_infi $ assume s, le_infi $ assume hs, infi_le_of_le s $ infi_le_of_le hs $ infi_le_of_le s $ infi_le _ hs lemma lift_lift_same_eq_lift {g : set α → set α → filter β} (hg₁ : ∀s, monotone (λt, g s t)) (hg₂ : ∀t, monotone (λs, g s t)): f.lift (λs, f.lift (g s)) = f.lift (λs, g s s) := le_antisymm lift_lift_same_le_lift (le_infi $ assume s, le_infi $ assume hs, le_infi $ assume t, le_infi $ assume ht, infi_le_of_le (s ∩ t) $ infi_le_of_le (inter_mem_sets hs ht) $ calc g (s ∩ t) (s ∩ t) ≤ g s (s ∩ t) : hg₂ (s ∩ t) (inter_subset_left _ _) ... ≤ g s t : hg₁ s (inter_subset_right _ _)) lemma lift_principal {s : set α} (hg : monotone g) : (principal s).lift g = g s := le_antisymm (infi_le_of_le s $ infi_le _ $ subset.refl _) (le_infi $ assume t, le_infi $ assume hi, hg hi) theorem monotone_lift [preorder γ] {f : γ → filter α} {g : γ → set α → filter β} (hf : monotone f) (hg : monotone g) : monotone (λc, (f c).lift (g c)) := assume a b h, lift_mono (hf h) (hg h) lemma lift_neq_bot_iff (hm : monotone g) : (f.lift g ≠ ⊥) ↔ (∀s∈f.sets, g s ≠ ⊥) := classical.by_cases (assume hn : nonempty β, calc f.lift g ≠ ⊥ ↔ (⨅s : { s // s ∈ f.sets}, g s.val) ≠ ⊥ : by simp [filter.lift, infi_subtype] ... ↔ (∀s:{ s // s ∈ f.sets}, g s.val ≠ ⊥) : infi_neq_bot_iff_of_directed hn (assume ⟨a, ha⟩ ⟨b, hb⟩, ⟨⟨a ∩ b, inter_mem_sets ha hb⟩, hm $ inter_subset_left _ _, hm $ inter_subset_right _ _⟩) ... ↔ (∀s∈f.sets, g s ≠ ⊥) : ⟨assume h s hs, h ⟨s, hs⟩, assume h ⟨s, hs⟩, h s hs⟩) (assume hn : ¬ nonempty β, have h₁ : f.lift g = ⊥, from filter_eq_bot_of_not_nonempty hn, have h₂ : ∀s, g s = ⊥, from assume s, filter_eq_bot_of_not_nonempty hn, calc (f.lift g ≠ ⊥) ↔ false : by simp [h₁] ... ↔ (∀s∈f.sets, false) : ⟨false.elim, assume h, h univ univ_mem_sets⟩ ... ↔ (∀s∈f.sets, g s ≠ ⊥) : by simp [h₂]) @[simp] lemma lift_const {f : filter α} {g : filter β} : f.lift (λx, g) = g := le_antisymm (lift_le univ_mem_sets $ le_refl g) (le_lift $ assume s hs, le_refl g) @[simp] lemma lift_inf {f : filter α} {g h : set α → filter β} : f.lift (λx, g x ⊓ h x) = f.lift g ⊓ f.lift h := by simp [filter.lift, infi_inf_eq] @[simp] lemma lift_principal2 {f : filter α} : f.lift principal = f := le_antisymm (assume s hs, mem_lift hs (mem_principal_self s)) (le_infi $ assume s, le_infi $ assume hs, by simp [hs]) lemma lift_infi {f : ι → filter α} {g : set α → filter β} (hι : nonempty ι) (hg : ∀{s t}, g s ⊓ g t = g (s ∩ t)) : (infi f).lift g = (⨅i, (f i).lift g) := le_antisymm (le_infi $ assume i, lift_mono (infi_le _ _) (le_refl _)) (assume s, have g_mono : monotone g, from assume s t h, le_of_inf_eq $ eq.trans hg $ congr_arg g $ inter_eq_self_of_subset_left h, have ∀t∈(infi f).sets, (⨅ (i : ι), filter.lift (f i) g) ≤ g t, from assume t ht, infi_sets_induct ht (let ⟨i⟩ := hι in infi_le_of_le i $ infi_le_of_le univ $ infi_le _ univ_mem_sets) (assume i s₁ s₂ hs₁ hs₂, @hg s₁ s₂ ▸ le_inf (infi_le_of_le i $ infi_le_of_le s₁ $ infi_le _ hs₁) hs₂) (assume s₁ s₂ hs₁ hs₂, le_trans hs₂ $ g_mono hs₁), begin rw [lift_sets_eq g_mono], simp only [mem_Union, exists_imp_distrib], exact assume t ht hs, this t ht hs end) end lift section lift' /-- Specialize `lift` to functions `set α → set β`. This can be viewed as a generalization of `comap`. -/ protected def lift' (f : filter α) (h : set α → set β) := f.lift (principal ∘ h) variables {f f₁ f₂ : filter α} {h h₁ h₂ : set α → set β} lemma mem_lift' {t : set α} (ht : t ∈ f.sets) : h t ∈ (f.lift' h).sets := le_principal_iff.mp $ show f.lift' h ≤ principal (h t), from infi_le_of_le t $ infi_le_of_le ht $ le_refl _ lemma mem_lift'_sets (hh : monotone h) {s : set β} : s ∈ (f.lift' h).sets ↔ (∃t∈f.sets, h t ⊆ s) := have monotone (principal ∘ h), from assume a b h, principal_mono.mpr $ hh h, by simp [filter.lift', @mem_lift_sets α β f _ this] lemma lift'_le {f : filter α} {g : set α → set β} {h : filter β} {s : set α} (hs : s ∈ f.sets) (hg : principal (g s) ≤ h) : f.lift' g ≤ h := lift_le hs hg lemma lift'_mono (hf : f₁ ≤ f₂) (hh : h₁ ≤ h₂) : f₁.lift' h₁ ≤ f₂.lift' h₂ := lift_mono hf $ assume s, principal_mono.mpr $ hh s lemma lift'_mono' (hh : ∀s∈f.sets, h₁ s ⊆ h₂ s) : f.lift' h₁ ≤ f.lift' h₂ := infi_le_infi $ assume s, infi_le_infi $ assume hs, principal_mono.mpr $ hh s hs lemma lift'_cong (hh : ∀s∈f.sets, h₁ s = h₂ s) : f.lift' h₁ = f.lift' h₂ := le_antisymm (lift'_mono' $ assume s hs, le_of_eq $ hh s hs) (lift'_mono' $ assume s hs, le_of_eq $ (hh s hs).symm) lemma map_lift'_eq {m : β → γ} (hh : monotone h) : map m (f.lift' h) = f.lift' (image m ∘ h) := calc map m (f.lift' h) = f.lift (map m ∘ principal ∘ h) : map_lift_eq $ monotone_comp hh monotone_principal ... = f.lift' (image m ∘ h) : by simp [function.comp, filter.lift'] lemma map_lift'_eq2 {g : set β → set γ} {m : α → β} (hg : monotone g) : (map m f).lift' g = f.lift' (g ∘ image m) := map_lift_eq2 $ monotone_comp hg monotone_principal theorem comap_lift'_eq {m : γ → β} (hh : monotone h) : comap m (f.lift' h) = f.lift' (preimage m ∘ h) := calc comap m (f.lift' h) = f.lift (comap m ∘ principal ∘ h) : comap_lift_eq $ monotone_comp hh monotone_principal ... = f.lift' (preimage m ∘ h) : by simp [function.comp, filter.lift'] theorem comap_lift'_eq2 {m : β → α} {g : set β → set γ} (hg : monotone g) : (comap m f).lift' g = f.lift' (g ∘ preimage m) := comap_lift_eq2 $ monotone_comp hg monotone_principal lemma lift'_principal {s : set α} (hh : monotone h) : (principal s).lift' h = principal (h s) := lift_principal $ monotone_comp hh monotone_principal lemma principal_le_lift' {t : set β} (hh : ∀s∈f.sets, t ⊆ h s) : principal t ≤ f.lift' h := le_infi $ assume s, le_infi $ assume hs, principal_mono.mpr (hh s hs) theorem monotone_lift' [preorder γ] {f : γ → filter α} {g : γ → set α → set β} (hf : monotone f) (hg : monotone g) : monotone (λc, (f c).lift' (g c)) := assume a b h, lift'_mono (hf h) (hg h) lemma lift_lift'_assoc {g : set α → set β} {h : set β → filter γ} (hg : monotone g) (hh : monotone h) : (f.lift' g).lift h = f.lift (λs, h (g s)) := calc (f.lift' g).lift h = f.lift (λs, (principal (g s)).lift h) : lift_assoc (monotone_comp hg monotone_principal) ... = f.lift (λs, h (g s)) : by simp [lift_principal, hh] lemma lift'_lift'_assoc {g : set α → set β} {h : set β → set γ} (hg : monotone g) (hh : monotone h) : (f.lift' g).lift' h = f.lift' (λs, h (g s)) := lift_lift'_assoc hg (monotone_comp hh monotone_principal) lemma lift'_lift_assoc {g : set α → filter β} {h : set β → set γ} (hg : monotone g) : (f.lift g).lift' h = f.lift (λs, (g s).lift' h) := lift_assoc hg lemma lift_lift'_same_le_lift' {g : set α → set α → set β} : f.lift (λs, f.lift' (g s)) ≤ f.lift' (λs, g s s) := lift_lift_same_le_lift lemma lift_lift'_same_eq_lift' {g : set α → set α → set β} (hg₁ : ∀s, monotone (λt, g s t)) (hg₂ : ∀t, monotone (λs, g s t)): f.lift (λs, f.lift' (g s)) = f.lift' (λs, g s s) := lift_lift_same_eq_lift (assume s, monotone_comp monotone_id $ monotone_comp (hg₁ s) monotone_principal) (assume t, monotone_comp (hg₂ t) monotone_principal) lemma lift'_inf_principal_eq {h : set α → set β} {s : set β} : f.lift' h ⊓ principal s = f.lift' (λt, h t ∩ s) := le_antisymm (le_infi $ assume t, le_infi $ assume ht, calc filter.lift' f h ⊓ principal s ≤ principal (h t) ⊓ principal s : inf_le_inf (infi_le_of_le t $ infi_le _ ht) (le_refl _) ... = _ : by simp) (le_inf (le_infi $ assume t, le_infi $ assume ht, infi_le_of_le t $ infi_le_of_le ht $ by simp; exact inter_subset_right _ _) (infi_le_of_le univ $ infi_le_of_le univ_mem_sets $ by simp; exact inter_subset_left _ _)) lemma lift'_neq_bot_iff (hh : monotone h) : (f.lift' h ≠ ⊥) ↔ (∀s∈f.sets, h s ≠ ∅) := calc (f.lift' h ≠ ⊥) ↔ (∀s∈f.sets, principal (h s) ≠ ⊥) : lift_neq_bot_iff (monotone_comp hh monotone_principal) ... ↔ (∀s∈f.sets, h s ≠ ∅) : by simp [principal_eq_bot_iff] @[simp] lemma lift'_id {f : filter α} : f.lift' id = f := lift_principal2 lemma le_lift' {f : filter α} {h : set α → set β} {g : filter β} (h_le : ∀s∈f.sets, h s ∈ g.sets) : g ≤ f.lift' h := le_infi $ assume s, le_infi $ assume hs, by simp [h_le]; exact h_le s hs lemma lift_infi' {f : ι → filter α} {g : set α → filter β} (hι : nonempty ι) (hf : directed (≤) f) (hg : monotone g) : (infi f).lift g = (⨅i, (f i).lift g) := le_antisymm (le_infi $ assume i, lift_mono (infi_le _ _) (le_refl _)) (assume s, begin rw [lift_sets_eq hg], simp only [mem_Union, exists_imp_distrib, infi_sets_eq hf hι], exact assume t i ht hs, mem_infi_sets i $ mem_lift ht hs end) lemma lift'_infi {f : ι → filter α} {g : set α → set β} (hι : nonempty ι) (hg : ∀{s t}, g s ∩ g t = g (s ∩ t)) : (infi f).lift' g = (⨅i, (f i).lift' g) := lift_infi hι $ by simp; apply assume s t, hg theorem comap_eq_lift' {f : filter β} {m : α → β} : comap m f = f.lift' (preimage m) := filter_eq $ set.ext $ by simp [mem_lift'_sets, monotone_preimage, comap] end lift' 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 lemma prod_mem_prod {s : set α} {t : set β} {f : filter α} {g : filter β} (hs : s ∈ f.sets) (ht : t ∈ g.sets) : set.prod s t ∈ (filter.prod f g).sets := inter_mem_inf_sets (preimage_mem_comap hs) (preimage_mem_comap ht) lemma mem_prod_iff {s : set (α×β)} {f : filter α} {g : filter β} : s ∈ (filter.prod f g).sets ↔ (∃t₁∈f.sets, ∃t₂∈g.sets, set.prod t₁ t₂ ⊆ s) := begin simp [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 tendsto_fst {f : filter α} {g : filter β} : tendsto prod.fst (filter.prod f g) f := tendsto_inf_left tendsto_comap lemma tendsto_snd {f : filter α} {g : filter β} : tendsto prod.snd (filter.prod 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 (filter.prod g h) := tendsto_inf.2 ⟨tendsto_comap_iff.2 h₁, tendsto_comap_iff.2 h₂⟩ lemma prod_infi_left {f : ι → filter α} {g : filter β} (i : ι) : filter.prod (⨅i, f i) g = (⨅i, filter.prod (f i) g) := by rw [filter.prod, comap_infi, infi_inf i]; simp [filter.prod] lemma prod_infi_right {f : filter α} {g : ι → filter β} (i : ι) : filter.prod f (⨅i, g i) = (⨅i, filter.prod f (g i)) := by rw [filter.prod, comap_infi, inf_infi i]; simp [filter.prod] lemma prod_mono {f₁ f₂ : filter α} {g₁ g₂ : filter β} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : filter.prod f₁ g₁ ≤ filter.prod 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₂ : β₂ → α₂} : filter.prod (comap m₁ f₁) (comap m₂ f₂) = comap (λp:β₁×β₂, (m₁ p.1, m₂ p.2)) (filter.prod f₁ f₂) := by simp [filter.prod, comap_comap_comp] lemma prod_comm' : filter.prod f g = comap (prod.swap) (filter.prod g f) := by simp [filter.prod, comap_comap_comp, function.comp, inf_comm] lemma prod_comm : filter.prod f g = map (λp:β×α, (p.2, p.1)) (filter.prod 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₂ : α₂ → β₂} : filter.prod (map m₁ f₁) (map m₂ f₂) = map (λp:α₁×α₂, (m₁ p.1, m₂ p.2)) (filter.prod 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_fst.comp (le_refl _)).prod_mk (tendsto_snd.comp (le_refl _))) lemma prod_inf_prod {f₁ f₂ : filter α} {g₁ g₂ : filter β} : filter.prod f₁ g₁ ⊓ filter.prod f₂ g₂ = filter.prod (f₁ ⊓ f₂) (g₁ ⊓ g₂) := by simp only [filter.prod, comap_inf, inf_comm, inf_assoc, lattice.inf_left_comm] @[simp] lemma prod_bot1 {f : filter α} : filter.prod f (⊥ : filter β) = ⊥ := by simp [filter.prod] @[simp] lemma prod_bot2 {g : filter β} : filter.prod (⊥ : filter α) g = ⊥ := by simp [filter.prod] @[simp] lemma prod_principal_principal {s : set α} {t : set β} : filter.prod (principal s) (principal t) = principal (set.prod s t) := by simp [filter.prod, comap_principal]; refl lemma prod_def {f : filter α} {g : filter β} : f.prod g = (f.lift $ λs, g.lift' $ set.prod s) := have ∀(s:set α) (t : set β), principal (set.prod s t) = (principal s).comap prod.fst ⊓ (principal t).comap prod.snd, by simp; intros; refl, begin simp [filter.lift', function.comp, this, -comap_principal, lift_inf], rw [← comap_lift_eq monotone_principal, ← comap_lift_eq monotone_principal], simp [filter.prod] end lemma prod_same_eq : filter.prod f f = f.lift' (λt, set.prod t t) := by rw [prod_def]; from lift_lift'_same_eq_lift' (assume s, set.monotone_prod monotone_const monotone_id) (assume t, set.monotone_prod monotone_id monotone_const) lemma mem_prod_same_iff {s : set (α×α)} : s ∈ (filter.prod f f).sets ↔ (∃t∈f.sets, set.prod t t ⊆ s) := by rw [prod_same_eq, mem_lift'_sets]; exact set.monotone_prod monotone_id monotone_id lemma prod_lift_lift {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x} {f₁ : filter α₁} {f₂ : filter α₂} {g₁ : set α₁ → filter β₁} {g₂ : set α₂ → filter β₂} (hg₁ : monotone g₁) (hg₂ : monotone g₂) : filter.prod (f₁.lift g₁) (f₂.lift g₂) = f₁.lift (λs, f₂.lift (λt, filter.prod (g₁ s) (g₂ t))) := begin simp only [prod_def], rw [lift_assoc], apply congr_arg, funext x, rw [lift_comm], apply congr_arg, funext y, rw [lift'_lift_assoc], exact hg₂, exact hg₁ end lemma prod_lift'_lift' {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x} {f₁ : filter α₁} {f₂ : filter α₂} {g₁ : set α₁ → set β₁} {g₂ : set α₂ → set β₂} (hg₁ : monotone g₁) (hg₂ : monotone g₂) : filter.prod (f₁.lift' g₁) (f₂.lift' g₂) = f₁.lift (λs, f₂.lift' (λt, set.prod (g₁ s) (g₂ t))) := begin rw [prod_def, lift_lift'_assoc], apply congr_arg, funext x, rw [lift'_lift'_assoc], exact hg₂, exact set.monotone_prod monotone_const monotone_id, exact hg₁, exact (monotone_lift' monotone_const $ monotone_lam $ assume x, set.monotone_prod monotone_id monotone_const) end lemma prod_neq_bot {f : filter α} {g : filter β} : filter.prod f g ≠ ⊥ ↔ (f ≠ ⊥ ∧ g ≠ ⊥) := calc filter.prod f g ≠ ⊥ ↔ (∀s∈f.sets, g.lift' (set.prod s) ≠ ⊥) : begin rw [prod_def, lift_neq_bot_iff], exact (monotone_lift' monotone_const $ monotone_lam $ assume s, set.monotone_prod monotone_id monotone_const) end ... ↔ (∀s∈f.sets, ∀t∈g.sets, s ≠ ∅ ∧ t ≠ ∅) : begin apply forall_congr, intro s, apply forall_congr, intro hs, rw [lift'_neq_bot_iff], apply forall_congr, intro t, apply forall_congr, intro ht, rw [set.prod_neq_empty_iff], exact set.monotone_prod monotone_const monotone_id end ... ↔ (∀s∈f.sets, s ≠ ∅) ∧ (∀t∈g.sets, t ≠ ∅) : ⟨assume h, ⟨assume s hs, (h s hs univ univ_mem_sets).left, assume t ht, (h univ univ_mem_sets t ht).right⟩, assume ⟨h₁, h₂⟩ s hs t ht, ⟨h₁ s hs, h₂ t ht⟩⟩ ... ↔ _ : by simp only [forall_sets_neq_empty_iff_neq_bot] lemma tendsto_prod_iff {f : α × β → γ} {x : filter α} {y : filter β} {z : filter γ} : filter.tendsto f (filter.prod x y) z ↔ ∀ W ∈ z.sets, ∃ U ∈ x.sets, ∃ V ∈ y.sets, ∀ x y, x ∈ U → y ∈ V → f (x, y) ∈ W := by simp [tendsto_def, mem_prod_iff, set.prod_sub_preimage_iff] lemma tendsto_prod_self_iff {f : α × α → β} {x : filter α} {y : filter β} : filter.tendsto f (filter.prod x x) y ↔ ∀ W ∈ y.sets, ∃ U ∈ x.sets, ∀ (x x' : α), x ∈ U → x' ∈ U → f (x, x') ∈ W := by simp [tendsto_def, mem_prod_same_iff, set.prod_sub_preimage_iff] end prod /- at_top and at_bot -/ /-- `at_top` is the filter representing the limit `→ ∞` on an ordered set. It is generated by the collection of up-sets `{b | a ≤ b}`. (The preorder need not have a top element for this to be well defined, and indeed is trivial when a top element exists.) -/ def at_top [preorder α] : filter α := ⨅ a, principal {b | a ≤ b} /-- `at_bot` is the filter representing the limit `→ -∞` on an ordered set. It is generated by the collection of down-sets `{b | b ≤ a}`. (The preorder need not have a bottom element for this to be well defined, and indeed is trivial when a bottom element exists.) -/ def at_bot [preorder α] : filter α := ⨅ a, principal {b | b ≤ a} lemma mem_at_top [preorder α] (a : α) : {b : α | a ≤ b} ∈ (@at_top α _).sets := mem_infi_sets a $ subset.refl _ @[simp] lemma at_top_ne_bot [inhabited α] [semilattice_sup α] : (at_top : filter α) ≠ ⊥ := infi_neq_bot_of_directed (by apply_instance) (assume a b, ⟨a ⊔ b, by simp {contextual := tt}⟩) (assume a, by simp [principal_eq_bot_iff]; exact ne_empty_of_mem (le_refl a)) @[simp] lemma mem_at_top_sets [inhabited α] [semilattice_sup α] {s : set α} : s ∈ (at_top : filter α).sets ↔ ∃a:α, ∀b≥a, b ∈ s := iff.intro (assume h, infi_sets_induct h ⟨default α, by simp⟩ (assume a s₁ s₂ ha ⟨b, hb⟩, ⟨a ⊔ b, assume c hc, ⟨ha $ le_trans le_sup_left hc, hb _ $ le_trans le_sup_right hc⟩⟩) (assume s₁ s₂ h ⟨a, ha⟩, ⟨a, assume b hb, h $ ha _ hb⟩)) (assume ⟨a, h⟩, mem_infi_sets a $ assume x, h x) lemma map_at_top_eq [inhabited α] [semilattice_sup α] {f : α → β} : at_top.map f = (⨅a, principal $ f '' {a' | a ≤ a'}) := calc map f (⨅a, principal {a' | a ≤ a'}) = (⨅a, map f $ principal {a' | a ≤ a'}) : map_infi_eq (assume a b, ⟨a ⊔ b, by simp {contextual := tt}⟩) ⟨default α⟩ ... = (⨅a, principal $ f '' {a' | a ≤ a'}) : by simp lemma tendsto_finset_image_at_top_at_top {i : β → γ} {j : γ → β} (h : ∀x, j (i x) = x) : tendsto (λs:finset γ, s.image j) at_top at_top := tendsto_infi.2 $ assume s, tendsto_infi' (s.image i) $ tendsto_principal_principal.2 $ assume t (ht : s.image i ⊆ t), calc s = (s.image i).image j : by simp [finset.image_image, (∘), h]; exact finset.image_id.symm ... ⊆ t.image j : finset.image_subset_image ht /- ultrafilter -/ section ultrafilter open zorn variables {f g : filter α} /-- An ultrafilter is a minimal (maximal in the set order) proper filter. -/ def ultrafilter (f : filter α) := f ≠ ⊥ ∧ ∀g, g ≠ ⊥ → g ≤ f → f ≤ g lemma ultrafilter_pure {a : α} : ultrafilter (pure a) := ⟨pure_neq_bot, assume g hg ha, have {a} ∈ g.sets, begin simp at ha, assumption end, show ∀s∈g.sets, {a} ⊆ s, from classical.by_contradiction $ begin simp only [classical.not_forall, not_imp, exists_imp_distrib, singleton_subset_iff], exact assume s ⟨hs, hna⟩, have {a} ∩ s ∈ g.sets, from inter_mem_sets ‹{a} ∈ g.sets› hs, have ∅ ∈ g.sets, from mem_sets_of_superset this $ assume x ⟨hxa, hxs⟩, begin simp at hxa; simp [hxa] at hxs, exact hna hxs end, have g = ⊥, from empty_in_sets_eq_bot.mp this, hg this end⟩ lemma ultrafilter_unique (hg : ultrafilter g) (hf : f ≠ ⊥) (h : f ≤ g) : f = g := le_antisymm h (hg.right _ hf h) lemma exists_ultrafilter (h : f ≠ ⊥) : ∃u, u ≤ f ∧ ultrafilter u := let τ := {f' // f' ≠ ⊥ ∧ f' ≤ f}, r : τ → τ → Prop := λt₁ t₂, t₂.val ≤ t₁.val, ⟨a, ha⟩ := inhabited_of_mem_sets h univ_mem_sets, top : τ := ⟨f, h, le_refl f⟩, sup : Π(c:set τ), chain r c → τ := λc hc, ⟨⨅a:{a:τ // a ∈ insert top c}, a.val.val, infi_neq_bot_of_directed ⟨a⟩ (directed_of_chain $ chain_insert hc $ assume ⟨b, _, hb⟩ _ _, or.inl hb) (assume ⟨⟨a, ha, _⟩, _⟩, ha), infi_le_of_le ⟨top, mem_insert _ _⟩ (le_refl _)⟩ in have ∀c (hc: chain r c) a (ha : a ∈ c), r a (sup c hc), from assume c hc a ha, infi_le_of_le ⟨a, mem_insert_of_mem _ ha⟩ (le_refl _), have (∃ (u : τ), ∀ (a : τ), r u a → r a u), from zorn (assume c hc, ⟨sup c hc, this c hc⟩) (assume f₁ f₂ f₃ h₁ h₂, le_trans h₂ h₁), let ⟨uτ, hmin⟩ := this in ⟨uτ.val, uτ.property.right, uτ.property.left, assume g hg₁ hg₂, hmin ⟨g, hg₁, le_trans hg₂ uτ.property.right⟩ hg₂⟩ lemma le_of_ultrafilter {g : filter α} (hf : ultrafilter f) (h : f ⊓ g ≠ ⊥) : f ≤ g := le_of_inf_eq $ ultrafilter_unique hf h inf_le_left lemma mem_or_compl_mem_of_ultrafilter (hf : ultrafilter f) (s : set α) : s ∈ f.sets ∨ - s ∈ f.sets := classical.or_iff_not_imp_right.2 $ assume : - s ∉ f.sets, have f ≤ principal s, from le_of_ultrafilter hf $ assume h, this $ mem_sets_of_neq_bot $ by simp [*], by simp at this; assumption lemma mem_or_mem_of_ultrafilter {s t : set α} (hf : ultrafilter f) (h : s ∪ t ∈ f.sets) : s ∈ f.sets ∨ t ∈ f.sets := (mem_or_compl_mem_of_ultrafilter hf s).imp_right (assume : -s ∈ f.sets, by filter_upwards [this, h] assume x hnx hx, hx.resolve_left hnx) lemma mem_of_finite_sUnion_ultrafilter {s : set (set α)} (hf : ultrafilter f) (hs : finite s) : ⋃₀ s ∈ f.sets → ∃t∈s, t ∈ f.sets := finite.induction_on hs (by simp [empty_in_sets_eq_bot, hf.left]) $ λ t s' ht' hs' ih, by simp; exact assume h, (mem_or_mem_of_ultrafilter hf h).elim (assume : t ∈ f.sets, ⟨t, or.inl rfl, this⟩) (assume h, let ⟨t, hts', ht⟩ := ih h in ⟨t, or.inr hts', ht⟩) lemma mem_of_finite_Union_ultrafilter {is : set β} {s : β → set α} (hf : ultrafilter f) (his : finite is) (h : (⋃i∈is, s i) ∈ f.sets) : ∃i∈is, s i ∈ f.sets := have his : finite (image s is), from finite_image s his, have h : (⋃₀ image s is) ∈ f.sets, from by simp [sUnion_image]; assumption, let ⟨t, ⟨i, hi, h_eq⟩, (ht : t ∈ f.sets)⟩ := mem_of_finite_sUnion_ultrafilter hf his h in ⟨i, hi, h_eq.symm ▸ ht⟩ lemma ultrafilter_of_split {f : filter α} (hf : f ≠ ⊥) (h : ∀s, s ∈ f.sets ∨ - s ∈ f.sets) : ultrafilter f := ⟨hf, assume g hg g_le s hs, (h s).elim id $ assume : - s ∈ f.sets, have s ∩ -s ∈ g.sets, from inter_mem_sets hs (g_le this), by simp [empty_in_sets_eq_bot, hg] at this; contradiction⟩ lemma ultrafilter_map {f : filter α} {m : α → β} (h : ultrafilter f) : ultrafilter (map m f) := ultrafilter_of_split (by simp [map_eq_bot_iff, h.left]) $ assume s, show preimage m s ∈ f.sets ∨ - preimage m s ∈ f.sets, from mem_or_compl_mem_of_ultrafilter h (preimage m s) /-- Construct an ultrafilter extending a given filter. The ultrafilter lemma is the assertion that such a filter exists; we use the axiom of choice to pick one. -/ noncomputable def ultrafilter_of (f : filter α) : filter α := if h : f = ⊥ then ⊥ else classical.epsilon (λu, u ≤ f ∧ ultrafilter u) lemma ultrafilter_of_spec (h : f ≠ ⊥) : ultrafilter_of f ≤ f ∧ ultrafilter (ultrafilter_of f) := begin have h' := classical.epsilon_spec (exists_ultrafilter h), simp [ultrafilter_of, dif_neg, h], simp at h', assumption end lemma ultrafilter_of_le : ultrafilter_of f ≤ f := if h : f = ⊥ then by simp [ultrafilter_of, dif_pos, h]; exact le_refl _ else (ultrafilter_of_spec h).left lemma ultrafilter_ultrafilter_of (h : f ≠ ⊥) : ultrafilter (ultrafilter_of f) := (ultrafilter_of_spec h).right lemma ultrafilter_of_ultrafilter (h : ultrafilter f) : ultrafilter_of f = f := ultrafilter_unique h (ultrafilter_ultrafilter_of h.left).left ultrafilter_of_le end ultrafilter end filter
de51c98bbd63a5a111b02de4a1c50e1a8cf756b1
4fa161becb8ce7378a709f5992a594764699e268
/src/analysis/normed_space/enorm.lean
df266755516c88ccc10414b44b8e44258e0388e5
[ "Apache-2.0" ]
permissive
laughinggas/mathlib
e4aa4565ae34e46e834434284cb26bd9d67bc373
86dcd5cda7a5017c8b3c8876c89a510a19d49aad
refs/heads/master
1,669,496,232,688
1,592,831,995,000
1,592,831,995,000
274,155,979
0
0
Apache-2.0
1,592,835,190,000
1,592,835,189,000
null
UTF-8
Lean
false
false
7,512
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Yury G. Kudryashov -/ import analysis.normed_space.basic /-! # Extended norm In this file we define a structure `enorm 𝕜 V` representing an extended norm (i.e., a norm that can take the value `∞`) on a vector space `V` over a normed field `𝕜`. We do not use `class` for an `enorm` because the same space can have more than one extended norm. For example, the space of measurable functions `f : α → ℝ` has a family of `L_p` extended norms. We prove some basic inequalities, then define * `emetric_space` structure on `V` corresponding to `e : enorm 𝕜 V`; * the subspace of vectors with finite norm, called `e.finite_subspace`; * a `normed_space` structure on this space. The last definition is an instance because the type involves `e`. ## Implementation notes We do not define extended normed groups. They can be added to the chain once someone will need them. ## Tags normed space, extended norm -/ local attribute [instance, priority 1001] classical.prop_decidable /-- Extended norm on a vector space. As in the case of normed spaces, we require only `∥c • x∥ ≤ ∥c∥ * ∥x∥` in the definition, then prove an equality in `map_smul`. -/ structure enorm (𝕜 : Type*) (V : Type*) [normed_field 𝕜] [add_comm_group V] [vector_space 𝕜 V] := (to_fun : V → ennreal) (eq_zero' : ∀ x, to_fun x = 0 → x = 0) (map_add_le' : ∀ x y : V, to_fun (x + y) ≤ to_fun x + to_fun y) (map_smul_le' : ∀ (c : 𝕜) (x : V), to_fun (c • x) ≤ nnnorm c * to_fun x) namespace enorm variables {𝕜 : Type*} {V : Type*} [normed_field 𝕜] [add_comm_group V] [vector_space 𝕜 V] (e : enorm 𝕜 V) instance : has_coe_to_fun (enorm 𝕜 V) := ⟨_, enorm.to_fun⟩ lemma coe_fn_injective ⦃e₁ e₂ : enorm 𝕜 V⦄ (h : ⇑e₁ = e₂) : e₁ = e₂ := by cases e₁; cases e₂; congr; exact h @[ext] lemma ext {e₁ e₂ : enorm 𝕜 V} (h : ∀ x, e₁ x = e₂ x) : e₁ = e₂ := coe_fn_injective $ funext h lemma ext_iff {e₁ e₂ : enorm 𝕜 V} : e₁ = e₂ ↔ ∀ x, e₁ x = e₂ x := ⟨λ h x, h ▸ rfl, ext⟩ @[simp] lemma map_smul (c : 𝕜) (x : V) : e (c • x) = nnnorm c * e x := le_antisymm (e.map_smul_le' c x) $ begin by_cases hc : c = 0, { simp [hc] }, calc (nnnorm c : ennreal) * e x = nnnorm c * e (c⁻¹ • c • x) : by rw [inv_smul_smul' hc] ... ≤ nnnorm c * (nnnorm (c⁻¹) * e (c • x)) : _ ... = e (c • x) : _, { exact ennreal.mul_le_mul (le_refl _) (e.map_smul_le' _ _) }, { rw [← mul_assoc, normed_field.nnnorm_inv, ennreal.coe_inv, ennreal.mul_inv_cancel _ ennreal.coe_ne_top, one_mul]; simp [hc] } end @[simp] lemma map_zero : e 0 = 0 := by { rw [← zero_smul 𝕜 (0:V), e.map_smul], norm_num } @[simp] lemma eq_zero_iff {x : V} : e x = 0 ↔ x = 0 := ⟨e.eq_zero' x, λ h, h.symm ▸ e.map_zero⟩ @[simp] lemma map_neg (x : V) : e (-x) = e x := calc e (-x) = nnnorm (-1:𝕜) * e x : by rw [← map_smul, neg_one_smul] ... = e x : by simp lemma map_sub_rev (x y : V) : e (x - y) = e (y - x) := by rw [← neg_sub, e.map_neg] lemma map_add_le (x y : V) : e (x + y) ≤ e x + e y := e.map_add_le' x y lemma map_sub_le (x y : V) : e (x - y) ≤ e x + e y := calc e (x - y) ≤ e x + e (-y) : e.map_add_le x (-y) ... = e x + e y : by rw [e.map_neg] instance : partial_order (enorm 𝕜 V) := { le := λ e₁ e₂, ∀ x, e₁ x ≤ e₂ x, le_refl := λ e x, le_refl _, le_trans := λ e₁ e₂ e₃ h₁₂ h₂₃ x, le_trans (h₁₂ x) (h₂₃ x), le_antisymm := λ e₁ e₂ h₁₂ h₂₁, ext $ λ x, le_antisymm (h₁₂ x) (h₂₁ x) } /-- The `enorm` sending each non-zero vector to infinity. -/ noncomputable instance : has_top (enorm 𝕜 V) := ⟨{ to_fun := λ x, if x = 0 then 0 else ⊤, eq_zero' := λ x, by { split_ifs; simp [*] }, map_add_le' := λ x y, begin split_ifs with hxy hx hy hy hx hy hy; try { simp [*] }, simpa [hx, hy] using hxy end, map_smul_le' := λ c x, begin split_ifs with hcx hx hx; simp only [smul_eq_zero, not_or_distrib] at hcx, { simp only [mul_zero, le_refl] }, { have : c = 0, by tauto, simp [this] }, { tauto }, { simp [hcx.1] } end }⟩ noncomputable instance : inhabited (enorm 𝕜 V) := ⟨⊤⟩ lemma top_map {x : V} (hx : x ≠ 0) : (⊤ : enorm 𝕜 V) x = ⊤ := if_neg hx noncomputable instance : semilattice_sup_top (enorm 𝕜 V) := { le := (≤), lt := (<), top := ⊤, le_top := λ e x, if h : x = 0 then by simp [h] else by simp [top_map h], sup := λ e₁ e₂, { to_fun := λ x, max (e₁ x) (e₂ x), eq_zero' := λ x h, e₁.eq_zero_iff.1 (ennreal.max_eq_zero_iff.1 h).1, map_add_le' := λ x y, max_le (le_trans (e₁.map_add_le _ _) $ add_le_add' (le_max_left _ _) (le_max_left _ _)) (le_trans (e₂.map_add_le _ _) $ add_le_add' (le_max_right _ _) (le_max_right _ _)), map_smul_le' := λ c x, le_of_eq $ by simp only [map_smul, ennreal.mul_max] }, le_sup_left := λ e₁ e₂ x, le_max_left _ _, le_sup_right := λ e₁ e₂ x, le_max_right _ _, sup_le := λ e₁ e₂ e₃ h₁ h₂ x, max_le (h₁ x) (h₂ x), .. enorm.partial_order } @[simp, norm_cast] lemma coe_max (e₁ e₂ : enorm 𝕜 V) : ⇑(e₁ ⊔ e₂) = λ x, max (e₁ x) (e₂ x) := rfl @[norm_cast] lemma max_map (e₁ e₂ : enorm 𝕜 V) (x : V) : (e₁ ⊔ e₂) x = max (e₁ x) (e₂ x) := rfl /-- Structure of an `emetric_space` defined by an extended norm. -/ def emetric_space : emetric_space V := { edist := λ x y, e (x - y), edist_self := λ x, by simp, eq_of_edist_eq_zero := λ x y, by simp [sub_eq_zero], edist_comm := e.map_sub_rev, edist_triangle := λ x y z, calc e (x - z) = e ((x - y) + (y - z)) : by rw [sub_add_sub_cancel] ... ≤ e (x - y) + e (y - z) : e.map_add_le (x - y) (y - z) } /-- The subspace of vectors with finite enorm. -/ def finite_subspace : subspace 𝕜 V := { carrier := {x | e x < ⊤}, zero_mem' := by simp, add_mem' := λ x y hx hy, lt_of_le_of_lt (e.map_add_le x y) (ennreal.add_lt_top.2 ⟨hx, hy⟩), smul_mem' := λ c x hx, calc e (c • x) = nnnorm c * e x : e.map_smul c x ... < ⊤ : ennreal.mul_lt_top ennreal.coe_lt_top hx } /-- Metric space structure on `e.finite_subspace`. We use `emetric_space.to_metric_space_of_dist` to ensure that this definition agrees with `e.emetric_space`. -/ instance : metric_space e.finite_subspace := begin letI := e.emetric_space, refine emetric_space.to_metric_space_of_dist _ (λ x y, _) (λ x y, rfl), change e (x - y) ≠ ⊤, rw [← ennreal.lt_top_iff_ne_top], exact lt_of_le_of_lt (e.map_sub_le x y) (ennreal.add_lt_top.2 ⟨x.2, y.2⟩) end lemma finite_dist_eq (x y : e.finite_subspace) : dist x y = (e (x - y)).to_real := rfl lemma finite_edist_eq (x y : e.finite_subspace) : edist x y = e (x - y) := rfl /-- Normed group instance on `e.finite_subspace`. -/ instance : normed_group e.finite_subspace := { norm := λ x, (e x).to_real, dist_eq := λ x y, rfl } lemma finite_norm_eq (x : e.finite_subspace) : ∥x∥ = (e x).to_real := rfl /-- Normed space instance on `e.finite_subspace`. -/ instance : normed_space 𝕜 e.finite_subspace := { norm_smul_le := λ c x, le_of_eq $ by simp [finite_norm_eq, ← ennreal.to_real_mul_to_real] } end enorm
b4aa33946007b5b1b5f3356a31c64bf545ec496c
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/archive/wiedijk_100_theorems/solution_of_cubic.lean
57e17a74e712ff3648393545081f9e445bfa016e
[ "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
7,015
lean
/- Copyright (c) 2022 Jeoff Lee. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeoff Lee -/ import tactic.linear_combination import ring_theory.polynomial.cyclotomic.roots /-! # The Solution of a Cubic > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file proves Theorem 37 from the [100 Theorems List](https://www.cs.ru.nl/~freek/100/). In this file, we give the solutions to the cubic equation `a * x^3 + b * x^2 + c * x + d = 0` over a field `K` that has characteristic neither 2 nor 3, that has a third primitive root of unity, and in which certain other quantities admit square and cube roots. This is based on the [Cardano's Formula](https://en.wikipedia.org/wiki/Cubic_equation#Cardano's_formula). ## Main statements - `cubic_eq_zero_iff` : gives the roots of the cubic equation where the discriminant `p = 3 * a * c - b^2` is nonzero. - `cubic_eq_zero_iff_of_p_eq_zero` : gives the roots of the cubic equation where the discriminant equals zero. ## References Originally ported from Isabelle/HOL. The [original file](https://isabelle.in.tum.de/dist/library/HOL/HOL-ex/Cubic_Quartic.html) was written by Amine Chaieb. ## Tags polynomial, cubic, root -/ namespace theorems_100 section field open polynomial variables {K : Type*} [field K] variables [invertible (2 : K)] [invertible (3 : K)] variables (a b c d : K) variables {ω p q r s t : K} lemma cube_root_of_unity_sum (hω : is_primitive_root ω 3) : 1 + ω + ω^2 = 0 := begin convert hω.is_root_cyclotomic (nat.succ_pos _), simp only [cyclotomic_prime, eval_geom_sum], simp [finset.sum_range_succ] end /-- The roots of a monic cubic whose quadratic term is zero and whose discriminant is nonzero. -/ lemma cubic_basic_eq_zero_iff (hω : is_primitive_root ω 3) (hp_nonzero : p ≠ 0) (hr : r^2 = q^2 + p^3) (hs3 : s^3 = q + r) (ht : t * s = p) (x : K) : x^3 + 3 * p * x - 2 * q = 0 ↔ x = s - t ∨ x = s * ω - t * ω^2 ∨ x = s * ω^2 - t * ω := begin have h₁ : ∀ x a₁ a₂ a₃ : K, x = a₁ ∨ x = a₂ ∨ x = a₃ ↔ (x - a₁) * (x - a₂) * (x - a₃) = 0, { intros, simp only [mul_eq_zero, sub_eq_zero, or.assoc] }, rw h₁, refine eq.congr _ rfl, have hs_nonzero : s ≠ 0, { contrapose! hp_nonzero with hs_nonzero, linear_combination -1*ht + t*hs_nonzero }, rw ← mul_left_inj' (pow_ne_zero 3 hs_nonzero), have H := cube_root_of_unity_sum hω, linear_combination hr + (- q + r + s ^ 3) * hs3 - (3 * x * s ^ 3 + (t * s) ^ 2 + (t * s) * p + p ^ 2) * ht + ((x ^ 2 * (s - t) + x * (- ω * (s ^ 2 + t ^ 2) + s * t * (3 + ω ^ 2 - ω)) - (-(s ^ 3 - t ^ 3) * (ω - 1) + s^2 * t * ω ^ 2 - s * t^2 * ω ^ 2)) * s ^ 3) * H, end /-- Roots of a monic cubic whose discriminant is nonzero. -/ lemma cubic_monic_eq_zero_iff (hω : is_primitive_root ω 3) (hp : p = (3 * c - b^2) / 9) (hp_nonzero : p ≠ 0) (hq : q = (9 * b * c - 2 * b^3 - 27 * d) / 54) (hr : r^2 = q^2 + p^3) (hs3 : s^3 = q + r) (ht : t * s = p) (x : K) : x^3 + b * x^2 + c * x + d = 0 ↔ x = s - t - b / 3 ∨ x = s * ω - t * ω^2 - b / 3 ∨ x = s * ω^2 - t * ω - b / 3 := begin let y := x + b / 3, have hi2 : (2 : K) ≠ 0 := nonzero_of_invertible _, have hi3 : (3 : K) ≠ 0 := nonzero_of_invertible _, have h9 : (9 : K) = 3^2 := by norm_num, have h54 : (54 : K) = 2*3^3 := by norm_num, have h₁ : x^3 + b * x^2 + c * x + d = y^3 + 3 * p * y - 2 * q, { dsimp only [y], rw [hp, hq], field_simp [h9, h54], ring, }, rw [h₁, cubic_basic_eq_zero_iff hω hp_nonzero hr hs3 ht y], dsimp only [y], simp_rw [eq_sub_iff_add_eq], end /-- **The Solution of Cubic**. The roots of a cubic polynomial whose discriminant is nonzero. -/ theorem cubic_eq_zero_iff (ha : a ≠ 0) (hω : is_primitive_root ω 3) (hp : p = (3 * a * c - b^2) / (9 * a^2)) (hp_nonzero : p ≠ 0) (hq : q = (9 * a * b * c - 2 * b^3 - 27 * a^2 * d) / (54 * a^3)) (hr : r^2 = q^2 + p^3) (hs3 : s^3 = q + r) (ht : t * s = p) (x : K) : a * x^3 + b * x^2 + c * x + d = 0 ↔ x = s - t - b / (3 * a) ∨ x = s * ω - t * ω^2 - b / (3 * a) ∨ x = s * ω^2 - t * ω - b / (3 * a) := begin have hi2 : (2 : K) ≠ 0 := nonzero_of_invertible _, have hi3 : (3 : K) ≠ 0 := nonzero_of_invertible _, have h9 : (9 : K) = 3^2 := by norm_num, have h54 : (54 : K) = 2*3^3 := by norm_num, have h₁ : a * x^3 + b * x^2 + c * x + d = a * (x^3 + b/a * x^2 + c/a * x + d/a), { field_simp, ring }, have h₂ : ∀ x, a * x = 0 ↔ x = 0, { intros x, simp [ha], }, have hp' : p = (3 * (c/a) - (b/a) ^ 2) / 9, { field_simp [hp, h9], ring_nf }, have hq' : q = (9 * (b/a) * (c/a) - 2 * (b/a) ^ 3 - 27 * (d/a)) / 54, { field_simp [hq, h54], ring_nf }, rw [h₁, h₂, cubic_monic_eq_zero_iff (b/a) (c/a) (d/a) hω hp' hp_nonzero hq' hr hs3 ht x], have h₄ := calc b / a / 3 = b / (a * 3) : by { field_simp [ha] } ... = b / (3 * a) : by rw mul_comm, rw [h₄], end /-- the solution of the cubic equation when p equals zero. -/ lemma cubic_eq_zero_iff_of_p_eq_zero (ha : a ≠ 0) (hω : is_primitive_root ω 3) (hpz : 3 * a * c - b^2 = 0) (hq : q = (9 * a * b * c - 2 * b^3 - 27 * a^2 * d) / (54 * a^3)) (hs3 : s^3 = 2 * q) (x : K) : a * x^3 + b * x^2 + c * x + d = 0 ↔ x = s - b / (3 * a) ∨ x = s * ω - b / (3 * a) ∨ x = s * ω^2 - b / (3 * a) := begin have h₁ : ∀ x a₁ a₂ a₃ : K, x = a₁ ∨ x = a₂ ∨ x = a₃ ↔ (x - a₁) * (x - a₂) * (x - a₃) = 0, { intros, simp only [mul_eq_zero, sub_eq_zero, or.assoc] }, have hi2 : (2 : K) ≠ 0 := nonzero_of_invertible _, have hi3 : (3 : K) ≠ 0 := nonzero_of_invertible _, have h54 : (54 : K) = 2*3^3 := by norm_num, have hb2 : b^2 = 3 * a * c, { rw sub_eq_zero at hpz, rw hpz }, have hb3 : b^3 = 3 * a * b * c, { rw [pow_succ, hb2], ring }, have h₂ := calc a * x^3 + b * x^2 + c * x + d = a * (x + b/(3*a))^3 + (c - b^2/(3*a)) * x + (d - b^3*a/(3*a)^3) : by { field_simp, ring } ... = a * (x + b/(3*a))^3 + (d - (9*a*b*c-2*b^3)*a/(3*a)^3) : by { simp only [hb2, hb3], field_simp, ring } ... = a * ((x + b/(3*a))^3 - s^3) : by { rw [hs3, hq], field_simp [h54], ring, }, have h₃ : ∀ x, a * x = 0 ↔ x = 0, { intro x, simp [ha] }, have h₄ : ∀ x : K, x^3 - s^3 = (x - s) * (x - s * ω) * (x - s * ω^2), { intro x, calc x^3 - s^3 = (x - s) * (x^2 + x*s + s^2) : by ring ... = (x - s) * (x^2 - (ω+ω^2)*x*s + (1+ω+ω^2)*x*s + s^2) : by ring ... = (x - s) * (x^2 - (ω+ω^2)*x*s + ω^3*s^2) : by { rw [hω.pow_eq_one, cube_root_of_unity_sum hω], simp, } ... = (x - s) * (x - s * ω) * (x - s * ω^2) : by ring }, rw [h₁, h₂, h₃, h₄ (x + b/(3*a))], ring_nf, end end field end theorems_100
e3135240dc7d89601ab0fa228bd215476ae74940
b561a44b48979a98df50ade0789a21c79ee31288
/stage0/src/Lean/Elab/Structure.lean
50753cebf1aa696962165e948becff31ebe0548a
[ "Apache-2.0" ]
permissive
3401ijk/lean4
97659c475ebd33a034fed515cb83a85f75ccfb06
a5b1b8de4f4b038ff752b9e607b721f15a9a4351
refs/heads/master
1,693,933,007,651
1,636,424,845,000
1,636,424,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
44,157
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Parser.Command import Lean.Meta.Closure import Lean.Meta.SizeOf import Lean.Meta.Injective import Lean.Meta.Structure import Lean.Meta.AppBuilder import Lean.Elab.Command import Lean.Elab.DeclModifiers import Lean.Elab.DeclUtil import Lean.Elab.Inductive import Lean.Elab.DeclarationRange import Lean.Elab.Binders namespace Lean.Elab.Command open Meta /- Recall that the `structure command syntax is ``` leading_parser (structureTk <|> classTk) >> declId >> many Term.bracketedBinder >> optional «extends» >> Term.optType >> optional (" := " >> optional structCtor >> structFields) ``` -/ structure StructCtorView where ref : Syntax modifiers : Modifiers inferMod : Bool -- true if `{}` is used in the constructor declaration name : Name declName : Name structure StructFieldView where ref : Syntax modifiers : Modifiers binderInfo : BinderInfo inferMod : Bool declName : Name name : Name binders : Syntax type? : Option Syntax value? : Option Syntax structure StructView where ref : Syntax modifiers : Modifiers scopeLevelNames : List Name -- All `universe` declarations in the current scope allUserLevelNames : List Name -- `scopeLevelNames` ++ explicit universe parameters provided in the `structure` command isClass : Bool declName : Name scopeVars : Array Expr -- All `variable` declaration in the current scope params : Array Expr -- Explicit parameters provided in the `structure` command parents : Array Syntax type : Syntax ctor : StructCtorView fields : Array StructFieldView inductive StructFieldKind where | newField | copiedField | fromParent | subobject deriving Inhabited, BEq structure StructFieldInfo where name : Name declName : Name -- Remark: for `fromParent` fields, `declName` is only relevant in the generation of auxiliary "default value" functions. fvar : Expr kind : StructFieldKind inferMod : Bool := false value? : Option Expr := none deriving Inhabited def StructFieldInfo.isFromParent (info : StructFieldInfo) : Bool := match info.kind with | StructFieldKind.fromParent => true | _ => false def StructFieldInfo.isSubobject (info : StructFieldInfo) : Bool := match info.kind with | StructFieldKind.subobject => true | _ => false /- Auxiliary declaration for `mkProjections` -/ structure ProjectionInfo where declName : Name inferMod : Bool structure ElabStructResult where decl : Declaration projInfos : List ProjectionInfo projInstances : List Name -- projections (to parent classes) that must be marked as instances. mctx : MetavarContext lctx : LocalContext localInsts : LocalInstances defaultAuxDecls : Array (Name × Expr × Expr) private def defaultCtorName := `mk /- The structure constructor syntax is ``` leading_parser try (declModifiers >> ident >> optional inferMod >> " :: ") ``` -/ private def expandCtor (structStx : Syntax) (structModifiers : Modifiers) (structDeclName : Name) : TermElabM StructCtorView := do let useDefault := do let declName := structDeclName ++ defaultCtorName addAuxDeclarationRanges declName structStx[2] structStx[2] pure { ref := structStx, modifiers := {}, inferMod := false, name := defaultCtorName, declName } if structStx[5].isNone then useDefault else let optCtor := structStx[5][1] if optCtor.isNone then useDefault else let ctor := optCtor[0] withRef ctor do let ctorModifiers ← elabModifiers ctor[0] checkValidCtorModifier ctorModifiers if ctorModifiers.isPrivate && structModifiers.isPrivate then throwError "invalid 'private' constructor in a 'private' structure" if ctorModifiers.isProtected && structModifiers.isPrivate then throwError "invalid 'protected' constructor in a 'private' structure" let inferMod := !ctor[2].isNone let name := ctor[1].getId let declName := structDeclName ++ name let declName ← applyVisibility ctorModifiers.visibility declName addDocString' declName ctorModifiers.docString? addAuxDeclarationRanges declName ctor[1] ctor[1] pure { ref := ctor, name, modifiers := ctorModifiers, inferMod, declName } def checkValidFieldModifier (modifiers : Modifiers) : TermElabM Unit := do if modifiers.isNoncomputable then throwError "invalid use of 'noncomputable' in field declaration" if modifiers.isPartial then throwError "invalid use of 'partial' in field declaration" if modifiers.isUnsafe then throwError "invalid use of 'unsafe' in field declaration" if modifiers.attrs.size != 0 then throwError "invalid use of attributes in field declaration" /- ``` def structExplicitBinder := leading_parser atomic (declModifiers true >> "(") >> many1 ident >> optional inferMod >> optDeclSig >> optional (Term.binderTactic <|> Term.binderDefault) >> ")" def structImplicitBinder := leading_parser atomic (declModifiers true >> "{") >> many1 ident >> optional inferMod >> declSig >> "}" def structInstBinder := leading_parser atomic (declModifiers true >> "[") >> many1 ident >> optional inferMod >> declSig >> "]" def structSimpleBinder := leading_parser atomic (declModifiers true >> ident) >> optional inferMod >> optDeclSig >> optional (Term.binderTactic <|> Term.binderDefault) def structFields := leading_parser many (structExplicitBinder <|> structImplicitBinder <|> structInstBinder) ``` -/ private def expandFields (structStx : Syntax) (structModifiers : Modifiers) (structDeclName : Name) : TermElabM (Array StructFieldView) := let fieldBinders := if structStx[5].isNone then #[] else structStx[5][2][0].getArgs fieldBinders.foldlM (init := #[]) fun (views : Array StructFieldView) fieldBinder => withRef fieldBinder do let mut fieldBinder := fieldBinder if fieldBinder.getKind == ``Parser.Command.structSimpleBinder then fieldBinder := mkNode ``Parser.Command.structExplicitBinder #[ fieldBinder[0], mkAtomFrom fieldBinder "(", mkNullNode #[ fieldBinder[1] ], fieldBinder[2], fieldBinder[3], fieldBinder[4], mkAtomFrom fieldBinder ")" ] let k := fieldBinder.getKind let binfo ← if k == ``Parser.Command.structExplicitBinder then pure BinderInfo.default else if k == ``Parser.Command.structImplicitBinder then pure BinderInfo.implicit else if k == ``Parser.Command.structInstBinder then pure BinderInfo.instImplicit else throwError "unexpected kind of structure field" let fieldModifiers ← elabModifiers fieldBinder[0] checkValidFieldModifier fieldModifiers if fieldModifiers.isPrivate && structModifiers.isPrivate then throwError "invalid 'private' field in a 'private' structure" if fieldModifiers.isProtected && structModifiers.isPrivate then throwError "invalid 'protected' field in a 'private' structure" let inferMod := !fieldBinder[3].isNone let (binders, type?) ← if binfo == BinderInfo.default then let (binders, type?) := expandOptDeclSig fieldBinder[4] let optBinderTacticDefault := fieldBinder[5] if optBinderTacticDefault.isNone then pure (binders, type?) else if optBinderTacticDefault[0].getKind != ``Parser.Term.binderTactic then pure (binders, type?) else let binderTactic := optBinderTacticDefault[0] match type? with | none => throwErrorAt binderTactic "invalid field declaration, type must be provided when auto-param (tactic) is used" | some type => let tac := binderTactic[2] let name ← Term.declareTacticSyntax tac -- The tactic should be for binders+type. -- It is safe to reset the binders to a "null" node since there is no value to be elaborated let type ← `(forall $(binders.getArgs):bracketedBinder*, $type) let type ← `(autoParam $type $(mkIdentFrom tac name)) pure (mkNullNode, some type) else let (binders, type) := expandDeclSig fieldBinder[4] pure (binders, some type) let value? ← if binfo != BinderInfo.default then pure none else let optBinderTacticDefault := fieldBinder[5] -- trace[Elab.struct] ">>> {optBinderTacticDefault}" if optBinderTacticDefault.isNone then pure none else if optBinderTacticDefault[0].getKind == ``Parser.Term.binderTactic then pure none else -- binderDefault := leading_parser " := " >> termParser pure (some optBinderTacticDefault[0][1]) let idents := fieldBinder[2].getArgs idents.foldlM (init := views) fun (views : Array StructFieldView) ident => withRef ident do let name := ident.getId.eraseMacroScopes unless name.isAtomic do throwErrorAt ident "invalid field name '{name.eraseMacroScopes}', field names must be atomic" let declName := structDeclName ++ name let declName ← applyVisibility fieldModifiers.visibility declName addDocString' declName fieldModifiers.docString? return views.push { ref := ident modifiers := fieldModifiers binderInfo := binfo inferMod declName name binders type? value? } private def validStructType (type : Expr) : Bool := match type with | Expr.sort .. => true | _ => false private def findFieldInfo? (infos : Array StructFieldInfo) (fieldName : Name) : Option StructFieldInfo := infos.find? fun info => info.name == fieldName private def containsFieldName (infos : Array StructFieldInfo) (fieldName : Name) : Bool := (findFieldInfo? infos fieldName).isSome private def updateFieldInfoVal (infos : Array StructFieldInfo) (fieldName : Name) (value : Expr) : Array StructFieldInfo := infos.map fun info => if info.name == fieldName then { info with value? := value } else info register_builtin_option structureDiamondWarning : Bool := { defValue := false descr := "enable/disable warning messages for structure diamonds" } /-- Return `some fieldName` if field `fieldName` of the parent structure `parentStructName` is already in `infos` -/ private def findExistingField? (infos : Array StructFieldInfo) (parentStructName : Name) : CoreM (Option Name) := do let fieldNames := getStructureFieldsFlattened (← getEnv) parentStructName for fieldName in fieldNames do if containsFieldName infos fieldName then return some fieldName return none private partial def processSubfields (structDeclName : Name) (parentFVar : Expr) (parentStructName : Name) (subfieldNames : Array Name) (infos : Array StructFieldInfo) (k : Array StructFieldInfo → TermElabM α) : TermElabM α := go 0 infos where go (i : Nat) (infos : Array StructFieldInfo) := do if h : i < subfieldNames.size then let subfieldName := subfieldNames.get ⟨i, h⟩ if containsFieldName infos subfieldName then throwError "field '{subfieldName}' from '{parentStructName}' has already been declared" let val ← mkProjection parentFVar subfieldName let type ← inferType val withLetDecl subfieldName type val fun subfieldFVar => /- The following `declName` is only used for creating the `_default` auxiliary declaration name when its default value is overwritten in the structure. If the default value is not overwritten, then its value is irrelevant. -/ let declName := structDeclName ++ subfieldName let infos := infos.push { name := subfieldName, declName, fvar := subfieldFVar, kind := StructFieldKind.fromParent } go (i+1) infos else k infos /-- Return `some (structName, fieldName, struct)` if `e` is a projection function application -/ private def isProjFnApp? (e : Expr) : MetaM (Option (Name × Name × Expr)) := do match e.getAppFn with | Expr.const declName .. => match (← getProjectionFnInfo? declName) with | some { ctorName := ctorName, numParams := n, .. } => if declName.isStr && e.getAppNumArgs == n+1 then let ConstantInfo.ctorInfo ctorVal ← getConstInfo ctorName | unreachable! return some (ctorVal.induct, declName.getString!, e.appArg!) else return none | _ => return none | _ => return none /-- Return `some fieldName`, if `e` is an expression that represents an access to field `fieldName` of the structure `s`. The name of the structure type must be `structName`. -/ private partial def isProjectionOf? (e : Expr) (structName : Name) (s : Expr) : MetaM (Option Name) := do if let some (baseStructName, fieldName, e) ← isProjFnApp? e then if let some path ← visit e #[] then if let some path' := getPathToBaseStructure? (← getEnv) baseStructName structName then if path'.toArray == path.reverse then return some fieldName return none where visit (e : Expr) (path : Array Name) : MetaM (Option (Array Name)) := do if e == s then return some path -- Check whether `e` is a `toParent` field if let some (_, _, e') ← isProjFnApp? e then visit e' (path.push e.getAppFn.constName!) else return none /-- Auxiliary method for `copyNewFieldsFrom`. -/ private def getFieldType (infos : Array StructFieldInfo) (parentStructName : Name) (parentType : Expr) (fieldName : Name) : MetaM Expr := do withLocalDeclD (← mkFreshId) parentType fun parent => do let proj ← mkProjection parent fieldName let projType ← inferType proj /- Eliminate occurrences of `parent`. This may happen when structure contains dependent fields. -/ let visit (e : Expr) : MetaM TransformStep := do if let some fieldName ← isProjectionOf? e parentStructName parent then -- trace[Meta.debug] "field '{fieldName}' of {e}" match (← findFieldInfo? infos fieldName) with | some existingFieldInfo => return TransformStep.done existingFieldInfo.fvar | none => throwError "unexpected field access {indentExpr e}" else return TransformStep.done e Meta.transform projType (post := visit) private def toVisibility (fieldInfo : StructureFieldInfo) : CoreM Visibility := do if isProtected (← getEnv) fieldInfo.projFn then return Visibility.protected else if isPrivateName fieldInfo.projFn then return Visibility.private else return Visibility.regular abbrev FieldMap := NameMap Expr -- Map from field name to expression representing the field /-- Reduce projetions of the structures in `structNames` -/ private def reduceProjs (e : Expr) (structNames : NameSet) : MetaM Expr := let reduce (e : Expr) : MetaM TransformStep := do match (← reduceProjOf? e structNames.contains) with | some v => return TransformStep.done v | _ => return TransformStep.done e transform e (post := reduce) /-- Copy the default value for field `fieldName` set at structure `structName`. The arguments for the `_default` auxiliary function are provided by `fieldMap`. Recall some of the entries in `fieldMap` are constructor applications, and they needed to be reduced using `reduceProjs`. Otherwise, the produced default value may be "cyclic". That is, we reduce projections of the structures in `expandedStructNames`. Here is an example that shows why the reduction is needed. ``` structure A where a : Nat structure B where a : Nat b : Nat c : Nat structure C extends B where d : Nat c := b + d structure D extends A, C #print D.c._default ``` Without the reduction, it produces ``` def D.c._default : A → Nat → Nat → Nat → Nat := fun toA b c d => id ({ a := toA.a, b := b, c := c : B }.b + d) ``` -/ private partial def copyDefaultValue? (fieldMap : FieldMap) (expandedStructNames : NameSet) (structName : Name) (fieldName : Name) : TermElabM (Option Expr) := do match getDefaultFnForField? (← getEnv) structName fieldName with | none => return none | some defaultFn => let cinfo ← getConstInfo defaultFn let us ← mkFreshLevelMVarsFor cinfo go? (cinfo.instantiateValueLevelParams us) where failed : TermElabM (Option Expr) := do logWarning s!"ignoring default value for field '{fieldName}' defined at '{structName}'" return none go? (e : Expr) : TermElabM (Option Expr) := do match e with | Expr.lam n d b c => if c.binderInfo.isExplicit then let fieldName := n match fieldMap.find? n with | none => failed | some val => let valType ← inferType val if (← isDefEq valType d) then go? (b.instantiate1 val) else failed else let arg ← mkFreshExprMVar d go? (b.instantiate1 arg) | e => let r := if e.isAppOfArity ``id 2 then e.appArg! else e return some (← reduceProjs (← instantiateMVars e.appArg!) expandedStructNames) private partial def copyNewFieldsFrom (structDeclName : Name) (infos : Array StructFieldInfo) (parentType : Expr) (k : Array StructFieldInfo → TermElabM α) : TermElabM α := do copyFields infos {} parentType fun infos _ _ => k infos where copyFields (infos : Array StructFieldInfo) (expandedStructNames : NameSet) (parentType : Expr) (k : Array StructFieldInfo → FieldMap → NameSet → TermElabM α) : TermElabM α := do let parentStructName ← getStructureName parentType let fieldNames := getStructureFields (← getEnv) parentStructName let rec copy (i : Nat) (infos : Array StructFieldInfo) (fieldMap : FieldMap) (expandedStructNames : NameSet) : TermElabM α := do if h : i < fieldNames.size then let fieldName := fieldNames.get ⟨i, h⟩ let fieldType ← getFieldType infos parentStructName parentType fieldName match (← findFieldInfo? infos fieldName) with | some existingFieldInfo => let existingFieldType ← inferType existingFieldInfo.fvar unless (← isDefEq fieldType existingFieldType) do throwError "parent field type mismatch, field '{fieldName}' from parent '{parentStructName}' {← mkHasTypeButIsExpectedMsg fieldType existingFieldType}" /- Remark: if structure has a default value for this field, it will be set at the `processOveriddenDefaultValues` below. -/ copy (i+1) infos (fieldMap.insert fieldName existingFieldInfo.fvar) expandedStructNames | none => let some fieldInfo ← getFieldInfo? (← getEnv) parentStructName fieldName | unreachable! let addNewField : TermElabM α := do let value? ← copyDefaultValue? fieldMap expandedStructNames parentStructName fieldName withLocalDecl fieldName fieldInfo.binderInfo fieldType fun fieldFVar => do let fieldDeclName := structDeclName ++ fieldName let fieldDeclName ← applyVisibility (← toVisibility fieldInfo) fieldDeclName let infos := infos.push { name := fieldName, declName := fieldDeclName, fvar := fieldFVar, value?, kind := StructFieldKind.copiedField, inferMod := fieldInfo.inferMod } copy (i+1) infos (fieldMap.insert fieldName fieldFVar) expandedStructNames if fieldInfo.subobject?.isSome then let fieldParentStructName ← getStructureName fieldType if (← findExistingField? infos fieldParentStructName).isSome then -- See comment at `copyDefaultValue?` let expandedStructNames := expandedStructNames.insert fieldParentStructName copyFields infos expandedStructNames fieldType fun infos nestedFieldMap expandedStructNames => do let fieldVal ← mkCompositeField fieldType nestedFieldMap trace[Meta.debug] "composite, {fieldName} := {fieldVal}" copy (i+1) infos (fieldMap.insert fieldName fieldVal) expandedStructNames else addNewField else addNewField else let infos ← processOveriddenDefaultValues infos fieldMap expandedStructNames parentStructName k infos fieldMap expandedStructNames copy 0 infos {} expandedStructNames processOveriddenDefaultValues (infos : Array StructFieldInfo) (fieldMap : FieldMap) (expandedStructNames : NameSet) (parentStructName : Name) : TermElabM (Array StructFieldInfo) := infos.mapM fun info => do match (← copyDefaultValue? fieldMap expandedStructNames parentStructName info.name) with | some value => return { info with value? := value } | none => return info mkCompositeField (parentType : Expr) (fieldMap : FieldMap) : TermElabM Expr := do let env ← getEnv let Expr.const parentStructName us _ ← pure parentType.getAppFn | unreachable! let parentCtor := getStructureCtor env parentStructName let mut result := mkAppN (mkConst parentCtor.name us) parentType.getAppArgs for fieldName in getStructureFields env parentStructName do match fieldMap.find? fieldName with | some val => result := mkApp result val | none => throwError "failed to copied fields from parent structure{indentExpr parentType}" -- TODO improve error message return result private partial def mkToParentName (parentStructName : Name) (p : Name → Bool) : Name := do let base := Name.mkSimple $ "to" ++ parentStructName.eraseMacroScopes.getString! if p base then base else let rec go (i : Nat) : Name := let curr := base.appendIndexAfter i if p curr then curr else go (i+1) go 1 private partial def withParents (view : StructView) (k : Array StructFieldInfo → Array Expr → TermElabM α) : TermElabM α := do go 0 #[] #[] where go (i : Nat) (infos : Array StructFieldInfo) (copiedParents : Array Expr) : TermElabM α := do if h : i < view.parents.size then let parentStx := view.parents.get ⟨i, h⟩ withRef parentStx do let parentType ← Term.elabType parentStx let parentStructName ← getStructureName parentType if let some existingFieldName ← findExistingField? infos parentStructName then if structureDiamondWarning.get (← getOptions) then logWarning s!"field '{existingFieldName}' from '{parentStructName}' has already been declared" copyNewFieldsFrom view.declName infos parentType fun infos => go (i+1) infos (copiedParents.push parentType) -- TODO: if `class`, then we need to create a let-decl that stores the local instance for the `parentStructure` else let env ← getEnv let subfieldNames := getStructureFieldsFlattened env parentStructName let toParentName := mkToParentName parentStructName fun n => !containsFieldName infos n && !subfieldNames.contains n let binfo := if view.isClass && isClass env parentStructName then BinderInfo.instImplicit else BinderInfo.default withLocalDecl toParentName binfo parentType fun parentFVar => let infos := infos.push { name := toParentName, declName := view.declName ++ toParentName, fvar := parentFVar, kind := StructFieldKind.subobject } processSubfields view.declName parentFVar parentStructName subfieldNames infos fun infos => go (i+1) infos copiedParents else k infos copiedParents private def elabFieldTypeValue (view : StructFieldView) : TermElabM (Option Expr × Option Expr) := do Term.withAutoBoundImplicit <| Term.elabBinders view.binders.getArgs fun params => do match view.type? with | none => match view.value? with | none => return (none, none) | some valStx => Term.synthesizeSyntheticMVarsNoPostponing let params ← Term.addAutoBoundImplicits params let value ← Term.elabTerm valStx none let value ← mkLambdaFVars params value return (none, value) | some typeStx => let type ← Term.elabType typeStx Term.synthesizeSyntheticMVarsNoPostponing let params ← Term.addAutoBoundImplicits params match view.value? with | none => let type ← mkForallFVars params type return (type, none) | some valStx => let value ← Term.elabTermEnsuringType valStx type Term.synthesizeSyntheticMVarsNoPostponing let type ← mkForallFVars params type let value ← mkLambdaFVars params value return (type, value) private partial def withFields (views : Array StructFieldView) (infos : Array StructFieldInfo) (k : Array StructFieldInfo → TermElabM α) : TermElabM α := do go 0 {} infos where go (i : Nat) (defaultValsOverridden : NameSet) (infos : Array StructFieldInfo) : TermElabM α := do if h : i < views.size then let view := views.get ⟨i, h⟩ withRef view.ref do match findFieldInfo? infos view.name with | none => let (type?, value?) ← elabFieldTypeValue view match type?, value? with | none, none => throwError "invalid field, type expected" | some type, _ => withLocalDecl view.name view.binderInfo type fun fieldFVar => let infos := infos.push { name := view.name, declName := view.declName, fvar := fieldFVar, value? := value?, kind := StructFieldKind.newField, inferMod := view.inferMod } go (i+1) defaultValsOverridden infos | none, some value => let type ← inferType value withLocalDecl view.name view.binderInfo type fun fieldFVar => let infos := infos.push { name := view.name, declName := view.declName, fvar := fieldFVar, value? := value, kind := StructFieldKind.newField, inferMod := view.inferMod } go (i+1) defaultValsOverridden infos | some info => let updateDefaultValue (fromParent : Bool) : TermElabM α := do match view.value? with | none => throwError "field '{view.name}' has been declared in parent structure" | some valStx => if let some type := view.type? then throwErrorAt type "omit field '{view.name}' type to set default value" else if defaultValsOverridden.contains info.name then throwError "field '{view.name}' new default value has already been set" let defaultValsOverridden := defaultValsOverridden.insert info.name let mut valStx := valStx if view.binders.getArgs.size > 0 then valStx ← `(fun $(view.binders.getArgs)* => $valStx:term) let fvarType ← inferType info.fvar let value ← Term.elabTermEnsuringType valStx fvarType let infos := updateFieldInfoVal infos info.name value go (i+1) defaultValsOverridden infos match info.kind with | StructFieldKind.newField => throwError "field '{view.name}' has already been declared" | StructFieldKind.subobject => throwError "unexpected subobject field reference" -- improve error message | StructFieldKind.copiedField => updateDefaultValue false | StructFieldKind.fromParent => updateDefaultValue true else k infos private def getResultUniverse (type : Expr) : TermElabM Level := do let type ← whnf type match type with | Expr.sort u _ => pure u | _ => throwError "unexpected structure resulting type" private def collectUsed (params : Array Expr) (fieldInfos : Array StructFieldInfo) : StateRefT CollectFVars.State MetaM Unit := do params.forM fun p => do let type ← inferType p Meta.collectUsedFVars type fieldInfos.forM fun info => do let fvarType ← inferType info.fvar Meta.collectUsedFVars fvarType match info.value? with | none => pure () | some value => Meta.collectUsedFVars value private def removeUnused (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo) : TermElabM (LocalContext × LocalInstances × Array Expr) := do let (_, used) ← (collectUsed params fieldInfos).run {} Meta.removeUnused scopeVars used private def withUsed {α} (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo) (k : Array Expr → TermElabM α) : TermElabM α := do let (lctx, localInsts, vars) ← removeUnused scopeVars params fieldInfos withLCtx lctx localInsts <| k vars private def levelMVarToParamFVar (fvar : Expr) : StateRefT Nat TermElabM Unit := do let type ← inferType fvar discard <| Term.levelMVarToParam' type private def levelMVarToParamFVars (fvars : Array Expr) : StateRefT Nat TermElabM Unit := fvars.forM levelMVarToParamFVar private def levelMVarToParamAux (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo) : StateRefT Nat TermElabM (Array StructFieldInfo) := do levelMVarToParamFVars scopeVars levelMVarToParamFVars params fieldInfos.mapM fun info => do levelMVarToParamFVar info.fvar match info.value? with | none => pure info | some value => let value ← Term.levelMVarToParam' value pure { info with value? := value } private def levelMVarToParam (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo) : TermElabM (Array StructFieldInfo) := (levelMVarToParamAux scopeVars params fieldInfos).run' 1 private partial def collectUniversesFromFields (r : Level) (rOffset : Nat) (fieldInfos : Array StructFieldInfo) : TermElabM (Array Level) := do fieldInfos.foldlM (init := #[]) fun (us : Array Level) (info : StructFieldInfo) => do let type ← inferType info.fvar let u ← getLevel type let u ← instantiateLevelMVars u accLevelAtCtor u r rOffset us private def updateResultingUniverse (fieldInfos : Array StructFieldInfo) (type : Expr) : TermElabM Expr := do let r ← getResultUniverse type let rOffset : Nat := r.getOffset let r : Level := r.getLevelOffset match r with | Level.mvar mvarId _ => let us ← collectUniversesFromFields r rOffset fieldInfos let rNew := mkResultUniverse us rOffset assignLevelMVar mvarId rNew instantiateMVars type | _ => throwError "failed to compute resulting universe level of structure, provide universe explicitly" private def collectLevelParamsInFVar (s : CollectLevelParams.State) (fvar : Expr) : TermElabM CollectLevelParams.State := do let type ← inferType fvar let type ← instantiateMVars type return collectLevelParams s type private def collectLevelParamsInFVars (fvars : Array Expr) (s : CollectLevelParams.State) : TermElabM CollectLevelParams.State := fvars.foldlM collectLevelParamsInFVar s private def collectLevelParamsInStructure (structType : Expr) (scopeVars : Array Expr) (params : Array Expr) (fieldInfos : Array StructFieldInfo) : TermElabM (Array Name) := do let s := collectLevelParams {} structType let s ← collectLevelParamsInFVars scopeVars s let s ← collectLevelParamsInFVars params s let s ← fieldInfos.foldlM (init := s) fun s info => collectLevelParamsInFVar s info.fvar return s.params private def addCtorFields (fieldInfos : Array StructFieldInfo) : Nat → Expr → TermElabM Expr | 0, type => pure type | i+1, type => do let info := fieldInfos[i] let decl ← Term.getFVarLocalDecl! info.fvar let type ← instantiateMVars type let type := type.abstract #[info.fvar] match info.kind with | StructFieldKind.fromParent => let val := decl.value addCtorFields fieldInfos i (type.instantiate1 val) | _ => addCtorFields fieldInfos i (mkForall decl.userName decl.binderInfo decl.type type) private def mkCtor (view : StructView) (levelParams : List Name) (params : Array Expr) (fieldInfos : Array StructFieldInfo) : TermElabM Constructor := withRef view.ref do let type := mkAppN (mkConst view.declName (levelParams.map mkLevelParam)) params let type ← addCtorFields fieldInfos fieldInfos.size type let type ← mkForallFVars params type let type ← instantiateMVars type let type := type.inferImplicit params.size !view.ctor.inferMod -- trace[Meta.debug] "ctor type {type}" pure { name := view.ctor.declName, type } @[extern "lean_mk_projections"] private constant mkProjections (env : Environment) (structName : Name) (projs : List ProjectionInfo) (isClass : Bool) : Except KernelException Environment private def addProjections (structName : Name) (projs : List ProjectionInfo) (isClass : Bool) : TermElabM Unit := do let env ← getEnv match mkProjections env structName projs isClass with | Except.ok env => setEnv env | Except.error ex => throwKernelException ex private def registerStructure (structName : Name) (infos : Array StructFieldInfo) : TermElabM Unit := do let fields ← infos.filterMapM fun info => do if info.kind == StructFieldKind.fromParent then return none else return some { fieldName := info.name projFn := info.declName inferMod := info.inferMod binderInfo := (← getFVarLocalDecl info.fvar).binderInfo subobject? := if info.kind == StructFieldKind.subobject then match (← getEnv).find? info.declName with | some (ConstantInfo.defnInfo val) => match val.type.getForallBody.getAppFn with | Expr.const parentName .. => some parentName | _ => panic! "ill-formed structure" | _ => panic! "ill-formed environment" else none } modifyEnv fun env => Lean.registerStructure env { structName, fields } private def mkAuxConstructions (declName : Name) : TermElabM Unit := do let env ← getEnv let hasUnit := env.contains `PUnit let hasEq := env.contains `Eq let hasHEq := env.contains `HEq mkRecOn declName if hasUnit then mkCasesOn declName if hasUnit && hasEq && hasHEq then mkNoConfusion declName private def addDefaults (lctx : LocalContext) (defaultAuxDecls : Array (Name × Expr × Expr)) : TermElabM Unit := do let localInsts ← getLocalInstances withLCtx lctx localInsts do defaultAuxDecls.forM fun (declName, type, value) => do let value ← instantiateMVars value if value.hasExprMVar then throwError "invalid default value for field, it contains metavariables{indentExpr value}" /- The identity function is used as "marker". -/ let value ← mkId value discard <| mkAuxDefinition declName type value (zeta := true) setReducibleAttribute declName private partial def mkCoercionToCopiedParent (levelParams : List Name) (params : Array Expr) (view : StructView) (parentType : Expr) : MetaM Unit := do let env ← getEnv let structName := view.declName let sourceFieldNames := getStructureFieldsFlattened env structName let structType ← mkAppN (Lean.mkConst structName (levelParams.map mkLevelParam)) params let Expr.const parentStructName us _ ← pure parentType.getAppFn | unreachable! let binfo := if view.isClass && isClass env parentStructName then BinderInfo.instImplicit else BinderInfo.default withLocalDecl `self binfo structType fun source => do let declType ← instantiateMVars (← mkForallFVars params (← mkForallFVars #[source] parentType)) let declType := declType.inferImplicit params.size true let rec copyFields (parentType : Expr) : MetaM Expr := do let Expr.const parentStructName us _ ← pure parentType.getAppFn | unreachable! let parentCtor := getStructureCtor env parentStructName let mut result := mkAppN (mkConst parentCtor.name us) parentType.getAppArgs for fieldName in getStructureFields env parentStructName do if sourceFieldNames.contains fieldName then let fieldVal ← mkProjection source fieldName result := mkApp result fieldVal else -- fieldInfo must be a field of `parentStructName` let some fieldInfo ← getFieldInfo? env parentStructName fieldName | unreachable! if fieldInfo.subobject?.isNone then throwError "failed to build coercion to parent structure" let resultType ← whnfD (← inferType result) unless resultType.isForall do throwError "failed to build coercion to parent structure, unexpect type{indentExpr resultType}" let fieldVal ← copyFields resultType.bindingDomain! result := mkApp result fieldVal return result let declVal ← instantiateMVars (← mkLambdaFVars params (← mkLambdaFVars #[source] (← copyFields parentType))) let declName := structName ++ mkToParentName (← getStructureName parentType) fun n => !env.contains (structName ++ n) addAndCompile <| Declaration.defnDecl { name := declName levelParams := levelParams type := declType value := declVal hints := ReducibilityHints.abbrev safety := if view.modifiers.isUnsafe then DefinitionSafety.unsafe else DefinitionSafety.safe } if binfo.isInstImplicit then addInstance declName AttributeKind.global (eval_prio default) else setReducibleAttribute declName private def elabStructureView (view : StructView) : TermElabM Unit := do view.fields.forM fun field => do if field.declName == view.ctor.declName then throwErrorAt field.ref "invalid field name '{field.name}', it is equal to structure constructor name" addAuxDeclarationRanges field.declName field.ref field.ref let numExplicitParams := view.params.size let type ← Term.elabType view.type unless validStructType type do throwErrorAt view.type "expected Type" withRef view.ref do withParents view fun fieldInfos copiedParents => do withFields view.fields fieldInfos fun fieldInfos => do Term.synthesizeSyntheticMVarsNoPostponing let u ← getResultUniverse type let inferLevel ← shouldInferResultUniverse u withUsed view.scopeVars view.params fieldInfos fun scopeVars => do let numParams := scopeVars.size + numExplicitParams let fieldInfos ← levelMVarToParam scopeVars view.params fieldInfos let type ← withRef view.ref do if inferLevel then updateResultingUniverse fieldInfos type else checkResultingUniverse (← getResultUniverse type) pure type trace[Elab.structure] "type: {type}" let usedLevelNames ← collectLevelParamsInStructure type scopeVars view.params fieldInfos match sortDeclLevelParams view.scopeLevelNames view.allUserLevelNames usedLevelNames with | Except.error msg => withRef view.ref <| throwError msg | Except.ok levelParams => let params := scopeVars ++ view.params let ctor ← mkCtor view levelParams params fieldInfos let type ← mkForallFVars params type let type ← instantiateMVars type let indType := { name := view.declName, type := type, ctors := [ctor] : InductiveType } let decl := Declaration.inductDecl levelParams params.size [indType] view.modifiers.isUnsafe Term.ensureNoUnassignedMVars decl addDecl decl let projInfos := (fieldInfos.filter fun (info : StructFieldInfo) => !info.isFromParent).toList.map fun (info : StructFieldInfo) => { declName := info.declName, inferMod := info.inferMod : ProjectionInfo } addProjections view.declName projInfos view.isClass registerStructure view.declName fieldInfos mkAuxConstructions view.declName let instParents ← fieldInfos.filterM fun info => do let decl ← Term.getFVarLocalDecl! info.fvar pure (info.isSubobject && decl.binderInfo.isInstImplicit) let projInstances := instParents.toList.map fun info => info.declName Term.applyAttributesAt view.declName view.modifiers.attrs AttributeApplicationTime.afterTypeChecking projInstances.forM fun declName => addInstance declName AttributeKind.global (eval_prio default) copiedParents.forM fun parent => mkCoercionToCopiedParent levelParams params view parent let lctx ← getLCtx let fieldsWithDefault := fieldInfos.filter fun info => info.value?.isSome let defaultAuxDecls ← fieldsWithDefault.mapM fun info => do let type ← inferType info.fvar pure (mkDefaultFnOfProjFn info.declName, type, info.value?.get!) /- The `lctx` and `defaultAuxDecls` are used to create the auxiliary "default value" declarations The parameters `params` for these definitions must be marked as implicit, and all others as explicit. -/ let lctx := params.foldl (init := lctx) fun (lctx : LocalContext) (p : Expr) => lctx.setBinderInfo p.fvarId! BinderInfo.implicit let lctx := fieldInfos.foldl (init := lctx) fun (lctx : LocalContext) (info : StructFieldInfo) => if info.isFromParent then lctx -- `fromParent` fields are elaborated as let-decls, and are zeta-expanded when creating "default value" auxiliary functions else lctx.setBinderInfo info.fvar.fvarId! BinderInfo.default addDefaults lctx defaultAuxDecls /- leading_parser (structureTk <|> classTk) >> declId >> many Term.bracketedBinder >> optional «extends» >> Term.optType >> " := " >> optional structCtor >> structFields >> optDeriving where def «extends» := leading_parser " extends " >> sepBy1 termParser ", " def typeSpec := leading_parser " : " >> termParser def optType : Parser := optional typeSpec def structFields := leading_parser many (structExplicitBinder <|> structImplicitBinder <|> structInstBinder) def structCtor := leading_parser try (declModifiers >> ident >> optional inferMod >> " :: ") -/ def elabStructure (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := do checkValidInductiveModifier modifiers let isClass := stx[0].getKind == ``Parser.Command.classTk let modifiers := if isClass then modifiers.addAttribute { name := `class } else modifiers let declId := stx[1] let params := stx[2].getArgs let exts := stx[3] let parents := if exts.isNone then #[] else exts[0][1].getSepArgs let optType := stx[4] let derivingClassViews ← getOptDerivingClasses stx[6] let type ← if optType.isNone then `(Sort _) else pure optType[0][1] let declName ← runTermElabM none fun scopeVars => do let scopeLevelNames ← Term.getLevelNames let ⟨name, declName, allUserLevelNames⟩ ← Elab.expandDeclId (← getCurrNamespace) scopeLevelNames declId modifiers addDeclarationRanges declName stx Term.withDeclName declName do let ctor ← expandCtor stx modifiers declName let fields ← expandFields stx modifiers declName Term.withLevelNames allUserLevelNames <| Term.withAutoBoundImplicit <| Term.elabBinders params fun params => do Term.synthesizeSyntheticMVarsNoPostponing let params ← Term.addAutoBoundImplicits params let allUserLevelNames ← Term.getLevelNames elabStructureView { ref := stx modifiers scopeLevelNames allUserLevelNames declName isClass scopeVars params parents type ctor fields } unless isClass do mkSizeOfInstances declName mkInjectiveTheorems declName return declName derivingClassViews.forM fun view => view.applyHandlers #[declName] builtin_initialize registerTraceClass `Elab.structure end Lean.Elab.Command
21882d4f2abaa96c9d7af65bba94d7324bb99d9c
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/preadditive/biproducts.lean
f55a792f99a33b9e777efc73d871b39566ace81d
[ "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
11,367
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 tactic.abel import category_theory.limits.shapes.biproducts import category_theory.preadditive /-! # Basic facts about morphisms between biproducts in preadditive categories. * In any category (with zero morphisms), if `biprod.map f g` is an isomorphism, then both `f` and `g` are isomorphisms. The remaining lemmas hold in any preadditive category. * If `f` is a morphism `X₁ ⊞ X₂ ⟶ Y₁ ⊞ Y₂` whose `X₁ ⟶ Y₁` entry is an isomorphism, then we can construct isomorphisms `L : X₁ ⊞ X₂ ≅ X₁ ⊞ X₂` and `R : Y₁ ⊞ Y₂ ≅ Y₁ ⊞ Y₂` so that `L.hom ≫ g ≫ R.hom` is diagonal (with `X₁ ⟶ Y₁` component still `f`), via Gaussian elimination. * As a corollary of the previous two facts, if we have an isomorphism `X₁ ⊞ X₂ ≅ Y₁ ⊞ Y₂` whose `X₁ ⟶ Y₁` entry is an isomorphism, we can construct an isomorphism `X₂ ≅ Y₂`. * If `f : W ⊞ X ⟶ Y ⊞ Z` is an isomorphism, either `𝟙 W = 0`, or at least one of the component maps `W ⟶ Y` and `W ⟶ Z` is nonzero. * If `f : ⨁ S ⟶ ⨁ T` is an isomorphism, then every column (corresponding to a nonzero summand in the domain) has some nonzero matrix entry. -/ open category_theory open category_theory.preadditive open category_theory.limits universes v u noncomputable theory namespace category_theory variables {C : Type u} [category.{v} C] section variables [has_zero_morphisms.{v} C] [has_binary_biproducts.{v} C] /-- If ``` (f 0) (0 g) ``` is invertible, then `f` is invertible. -/ lemma is_iso_left_of_is_iso_biprod_map {W X Y Z : C} (f : W ⟶ Y) (g : X ⟶ Z) [is_iso (biprod.map f g)] : is_iso f := ⟨⟨biprod.inl ≫ inv (biprod.map f g) ≫ biprod.fst, ⟨begin have t := congr_arg (λ p : W ⊞ X ⟶ W ⊞ X, biprod.inl ≫ p ≫ biprod.fst) (is_iso.hom_inv_id (biprod.map f g)), simp only [category.id_comp, category.assoc, biprod.inl_map_assoc] at t, simp [t], end, begin have t := congr_arg (λ p : Y ⊞ Z ⟶ Y ⊞ Z, biprod.inl ≫ p ≫ biprod.fst) (is_iso.inv_hom_id (biprod.map f g)), simp only [category.id_comp, category.assoc, biprod.map_fst] at t, simp only [category.assoc], simp [t], end⟩⟩⟩ /-- If ``` (f 0) (0 g) ``` is invertible, then `g` is invertible. -/ lemma is_iso_right_of_is_iso_biprod_map {W X Y Z : C} (f : W ⟶ Y) (g : X ⟶ Z) [is_iso (biprod.map f g)] : is_iso g := begin letI : is_iso (biprod.map g f) := by { rw [←biprod.braiding_map_braiding], apply_instance, }, exact is_iso_left_of_is_iso_biprod_map g f, end end section variables [preadditive.{v} C] [has_binary_biproducts.{v} C] variables {X₁ X₂ Y₁ Y₂ : C} variables (f₁₁ : X₁ ⟶ Y₁) (f₁₂ : X₁ ⟶ Y₂) (f₂₁ : X₂ ⟶ Y₁) (f₂₂ : X₂ ⟶ Y₂) /-- The "matrix" morphism `X₁ ⊞ X₂ ⟶ Y₁ ⊞ Y₂` with specified components. -/ def biprod.of_components : X₁ ⊞ X₂ ⟶ Y₁ ⊞ Y₂ := biprod.fst ≫ f₁₁ ≫ biprod.inl + biprod.fst ≫ f₁₂ ≫ biprod.inr + biprod.snd ≫ f₂₁ ≫ biprod.inl + biprod.snd ≫ f₂₂ ≫ biprod.inr @[simp] lemma biprod.inl_of_components : biprod.inl ≫ biprod.of_components f₁₁ f₁₂ f₂₁ f₂₂ = f₁₁ ≫ biprod.inl + f₁₂ ≫ biprod.inr := by simp [biprod.of_components] @[simp] lemma biprod.inr_of_components : biprod.inr ≫ biprod.of_components f₁₁ f₁₂ f₂₁ f₂₂ = f₂₁ ≫ biprod.inl + f₂₂ ≫ biprod.inr := by simp [biprod.of_components] @[simp] lemma biprod.of_components_fst : biprod.of_components f₁₁ f₁₂ f₂₁ f₂₂ ≫ biprod.fst = biprod.fst ≫ f₁₁ + biprod.snd ≫ f₂₁ := by simp [biprod.of_components] @[simp] lemma biprod.of_components_snd : biprod.of_components f₁₁ f₁₂ f₂₁ f₂₂ ≫ biprod.snd = biprod.fst ≫ f₁₂ + biprod.snd ≫ f₂₂ := by simp [biprod.of_components] @[simp] lemma biprod.of_components_eq (f : X₁ ⊞ X₂ ⟶ Y₁ ⊞ Y₂) : biprod.of_components (biprod.inl ≫ f ≫ biprod.fst) (biprod.inl ≫ f ≫ biprod.snd) (biprod.inr ≫ f ≫ biprod.fst) (biprod.inr ≫ f ≫ biprod.snd) = f := begin ext; simp, end @[simp] lemma biprod.of_components_comp {X₁ X₂ Y₁ Y₂ Z₁ Z₂ : C} (f₁₁ : X₁ ⟶ Y₁) (f₁₂ : X₁ ⟶ Y₂) (f₂₁ : X₂ ⟶ Y₁) (f₂₂ : X₂ ⟶ Y₂) (g₁₁ : Y₁ ⟶ Z₁) (g₁₂ : Y₁ ⟶ Z₂) (g₂₁ : Y₂ ⟶ Z₁) (g₂₂ : Y₂ ⟶ Z₂) : biprod.of_components f₁₁ f₁₂ f₂₁ f₂₂ ≫ biprod.of_components g₁₁ g₁₂ g₂₁ g₂₂ = biprod.of_components (f₁₁ ≫ g₁₁ + f₁₂ ≫ g₂₁) (f₁₁ ≫ g₁₂ + f₁₂ ≫ g₂₂) (f₂₁ ≫ g₁₁ + f₂₂ ≫ g₂₁) (f₂₁ ≫ g₁₂ + f₂₂ ≫ g₂₂) := begin dsimp [biprod.of_components], apply biprod.hom_ext; apply biprod.hom_ext'; simp only [add_comp, comp_add, add_comp_assoc, add_zero, zero_add, biprod.inl_fst, biprod.inl_snd, biprod.inr_fst, biprod.inr_snd, biprod.inl_fst_assoc, biprod.inl_snd_assoc, biprod.inr_fst_assoc, biprod.inr_snd_assoc, comp_zero, zero_comp, category.comp_id, category.assoc], end /-- The unipotent upper triangular matrix ``` (1 r) (0 1) ``` as an isomorphism. -/ @[simps] def biprod.unipotent_upper {X₁ X₂ : C} (r : X₁ ⟶ X₂) : X₁ ⊞ X₂ ≅ X₁ ⊞ X₂ := { hom := biprod.of_components (𝟙 _) r 0 (𝟙 _), inv := biprod.of_components (𝟙 _) (-r) 0 (𝟙 _), } /-- The unipotent lower triangular matrix ``` (1 0) (r 1) ``` as an isomorphism. -/ @[simps] def biprod.unipotent_lower {X₁ X₂ : C} (r : X₂ ⟶ X₁) : X₁ ⊞ X₂ ≅ X₁ ⊞ X₂ := { hom := biprod.of_components (𝟙 _) 0 r (𝟙 _), inv := biprod.of_components (𝟙 _) 0 (-r) (𝟙 _), } /-- If `f` is a morphism `X₁ ⊞ X₂ ⟶ Y₁ ⊞ Y₂` whose `X₁ ⟶ Y₁` entry is an isomorphism, then we can construct isomorphisms `L : X₁ ⊞ X₂ ≅ X₁ ⊞ X₂` and `R : Y₁ ⊞ Y₂ ≅ Y₁ ⊞ Y₂` so that `L.hom ≫ g ≫ R.hom` is diagonal (with `X₁ ⟶ Y₁` component still `f`), via Gaussian elimination. (This is the version of `biprod.gaussian` written in terms of components.) -/ def biprod.gaussian' [is_iso f₁₁] : Σ' (L : X₁ ⊞ X₂ ≅ X₁ ⊞ X₂) (R : Y₁ ⊞ Y₂ ≅ Y₁ ⊞ Y₂) (g₂₂ : X₂ ⟶ Y₂), L.hom ≫ (biprod.of_components f₁₁ f₁₂ f₂₁ f₂₂) ≫ R.hom = biprod.map f₁₁ g₂₂ := ⟨biprod.unipotent_lower (-(f₂₁ ≫ inv f₁₁)), biprod.unipotent_upper (-(inv f₁₁ ≫ f₁₂)), f₂₂ - f₂₁ ≫ (inv f₁₁) ≫ f₁₂, by ext; simp; abel⟩ /-- If `f` is a morphism `X₁ ⊞ X₂ ⟶ Y₁ ⊞ Y₂` whose `X₁ ⟶ Y₁` entry is an isomorphism, then we can construct isomorphisms `L : X₁ ⊞ X₂ ≅ X₁ ⊞ X₂` and `R : Y₁ ⊞ Y₂ ≅ Y₁ ⊞ Y₂` so that `L.hom ≫ g ≫ R.hom` is diagonal (with `X₁ ⟶ Y₁` component still `f`), via Gaussian elimination. -/ def biprod.gaussian (f : X₁ ⊞ X₂ ⟶ Y₁ ⊞ Y₂) [is_iso (biprod.inl ≫ f ≫ biprod.fst)] : Σ' (L : X₁ ⊞ X₂ ≅ X₁ ⊞ X₂) (R : Y₁ ⊞ Y₂ ≅ Y₁ ⊞ Y₂) (g₂₂ : X₂ ⟶ Y₂), L.hom ≫ f ≫ R.hom = biprod.map (biprod.inl ≫ f ≫ biprod.fst) g₂₂ := begin let := biprod.gaussian' (biprod.inl ≫ f ≫ biprod.fst) (biprod.inl ≫ f ≫ biprod.snd) (biprod.inr ≫ f ≫ biprod.fst) (biprod.inr ≫ f ≫ biprod.snd), simpa [biprod.of_components_eq], end /-- If `X₁ ⊞ X₂ ≅ Y₁ ⊞ Y₂` via a two-by-two matrix whose `X₁ ⟶ Y₁` entry is an isomorphism, then we can construct an isomorphism `X₂ ≅ Y₂`, via Gaussian elimination. -/ def biprod.iso_elim' [is_iso f₁₁] [is_iso (biprod.of_components f₁₁ f₁₂ f₂₁ f₂₂)] : X₂ ≅ Y₂ := begin obtain ⟨L, R, g, w⟩ := biprod.gaussian' f₁₁ f₁₂ f₂₁ f₂₂, letI : is_iso (biprod.map f₁₁ g) := by { rw ←w, apply_instance, }, letI : is_iso g := (is_iso_right_of_is_iso_biprod_map f₁₁ g), exact as_iso g, end /-- If `f` is an isomorphism `X₁ ⊞ X₂ ≅ Y₁ ⊞ Y₂` whose `X₁ ⟶ Y₁` entry is an isomorphism, then we can construct an isomorphism `X₂ ≅ Y₂`, via Gaussian elimination. -/ def biprod.iso_elim (f : X₁ ⊞ X₂ ≅ Y₁ ⊞ Y₂) [is_iso (biprod.inl ≫ f.hom ≫ biprod.fst)] : X₂ ≅ Y₂ := begin letI : is_iso (biprod.of_components (biprod.inl ≫ f.hom ≫ biprod.fst) (biprod.inl ≫ f.hom ≫ biprod.snd) (biprod.inr ≫ f.hom ≫ biprod.fst) (biprod.inr ≫ f.hom ≫ biprod.snd)) := by { simp only [biprod.of_components_eq], apply_instance, }, exact biprod.iso_elim' (biprod.inl ≫ f.hom ≫ biprod.fst) (biprod.inl ≫ f.hom ≫ biprod.snd) (biprod.inr ≫ f.hom ≫ biprod.fst) (biprod.inr ≫ f.hom ≫ biprod.snd) end lemma biprod.column_nonzero_of_iso {W X Y Z : C} (f : W ⊞ X ⟶ Y ⊞ Z) [is_iso f] : 𝟙 W = 0 ∨ biprod.inl ≫ f ≫ biprod.fst ≠ 0 ∨ biprod.inl ≫ f ≫ biprod.snd ≠ 0 := begin by_contra' h, rcases h with ⟨nz, a₁, a₂⟩, set x := biprod.inl ≫ f ≫ inv f ≫ biprod.fst, have h₁ : x = 𝟙 W, by simp [x], have h₀ : x = 0, { dsimp [x], rw [←category.id_comp (inv f), category.assoc, ←biprod.total], conv_lhs { slice 2 3, rw [comp_add], }, simp only [category.assoc], rw [comp_add_assoc, add_comp], conv_lhs { congr, skip, slice 1 3, rw a₂, }, simp only [zero_comp, add_zero], conv_lhs { slice 1 3, rw a₁, }, simp only [zero_comp], }, exact nz (h₁.symm.trans h₀), end end variables [preadditive.{v} C] lemma biproduct.column_nonzero_of_iso' {σ τ : Type v} [decidable_eq σ] [decidable_eq τ] [fintype τ] {S : σ → C} [has_biproduct.{v} S] {T : τ → C} [has_biproduct.{v} T] (s : σ) (f : ⨁ S ⟶ ⨁ T) [is_iso f] : (∀ t : τ, biproduct.ι S s ≫ f ≫ biproduct.π T t = 0) → 𝟙 (S s) = 0 := begin intro z, set x := biproduct.ι S s ≫ f ≫ inv f ≫ biproduct.π S s, have h₁ : x = 𝟙 (S s), by simp [x], have h₀ : x = 0, { dsimp [x], rw [←category.id_comp (inv f), category.assoc, ←biproduct.total], simp only [comp_sum_assoc], conv_lhs { congr, apply_congr, skip, simp only [reassoc_of z], }, simp, }, exact h₁.symm.trans h₀, end /-- If `f : ⨁ S ⟶ ⨁ T` is an isomorphism, and `s` is a non-trivial summand of the source, then there is some `t` in the target so that the `s, t` matrix entry of `f` is nonzero. -/ def biproduct.column_nonzero_of_iso {σ τ : Type v} [decidable_eq σ] [decidable_eq τ] [fintype τ] {S : σ → C} [has_biproduct.{v} S] {T : τ → C} [has_biproduct.{v} T] (s : σ) (nz : 𝟙 (S s) ≠ 0) [∀ t, decidable_eq (S s ⟶ T t)] (f : ⨁ S ⟶ ⨁ T) [is_iso f] : trunc (Σ' t : τ, biproduct.ι S s ≫ f ≫ biproduct.π T t ≠ 0) := begin apply trunc_sigma_of_exists, -- Do this before we run `classical`, so we get the right `decidable_eq` instances. have t := biproduct.column_nonzero_of_iso'.{v} s f, by_contradiction h, simp only [not_exists_not] at h, exact nz (t h) end end category_theory
70c122fb9b3e18c4a952f2a53a3c5ae08251df7f
9ad8d18fbe5f120c22b5e035bc240f711d2cbd7e
/src/exercises/primes.doc.lean
d07569258d38f733e86ff8715b1201da678be8c5
[]
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
28,817
lean
import data.nat.prime /-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We will use basic definitions about primes and divisibility taken from the mathlib library. The home page of the library is <a href="https://github.com/leanprover/mathlib">https://github.com/leanprover/mathlib</a> and you can browse and search the source code there. If you set things up in a standard way, you should have a copy of the library in more or less the same place as your own Lean files, with directory structure like this: <ul> <li><span class="path">.git</span>: a director that we can ignore. </li> <li><span class="path">.gitignore</span>, <span class="path">leanpkg.path</span>, <span class="path">leanpkg.toml</span>: files that we can ignore</li> <li>_target <ul> <li>deps <ul> <li>mathlib <ul> <li>Subdirectories algebra, analysis, category, computability, data, .... These contain uncompiled, human-readable files with extension .lean, and also compiled files with extension .olean. </li> </ul> </li> </ul> </li> </ul> </li> <li>src <ul> <li>Your own Lean files, such as the one shown here.</li> </ul> </li> </ul> <br/><br/> The line `import data.nat.prime` allows us to use definitions and results from the file <span class="mathlib">data/nat/prime.lean</span>. For example, that file proves that $2$ is prime, and gives the name `prime_two` to that fact. (However, see the comment on the next line.) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-/ open nat /-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The file <span class="mathlib">data/nat/prime.lean</span> proves a number of facts. For example, it proves that $2$ is prime, and gives the name `prime_two` to that fact. However, the same file also says `namespace nat` near the top. Because of this, the full name of the relevant theorem is really `nat.prime_two`. The line `open nat` in the current file allows us to drop the `nat` prefix. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-/ lemma larger_prime : ∀ n : ℕ, ∃ p, (prime p) ∧ (p > n) := /-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This line states the result that we want to prove, and attaches the name `larger_prime` to the result. <ul> <li>There are various symbols that do not appear on your keyboard. These can usually be entered in Visual Studio Code using LaTeX syntax. For example, you can type `\forall` followed by a space, and the `\forall` will automatically turn into into `∀`. For `ℕ`, `ℤ`, `ℚ` and `ℝ` one can enter `\nat`, `\int`, `\rat` and `\real`. Alternatively, one can enter `\N`, `\Z`, `\Q` and `\R`. </li> <li>To indicate that $n$ is in $ℕ$ we write `n : ℕ` rather than `n ∈ ℕ`, following the conventions of type theory rather than set theory. </li> <li>The expression `prime p` refers to the definition of primality taken from the file <span class="mathlib">data/nat/prime.lean</span>. That definition essentially gives a function from natural numbers to truth values. To apply that function to the argument $p$, we write `prime p` (following the conventions of Lisp-like programming languages) rather than `prime(p)` as in traditional functional notation. Note that if we had not had the line `open nat`, we would have had to say `nat.prime p` instead of `prime p`. If you did not already know where to find the definition of primality, you could enter "prime" in the search boxes at <a href="https://github.com/leanprover/mathlib">github.com/leanprover/mathlib</a> and <a href="https://github.com/leanprover/mathlib">github.com/leanprover/lean</a>. </li> <li>Note the commas associated with the quantifiers, and the `:=` at the end of the line. If you have this file open in Visual Studio Code, and you take out the first comma, then you should see three error messages in the Lean messages window. (If you do not see the relevant window, you should press CTRL-SHIFT-ENTER, or click the <img src="../../images/left_msg_icon.png"/> icon near the top of the screen.) None of those error messages is optimal, but <span class="error">unknown identifier 'n'</span> gives some indication of the location of the problem. On the other hand, if you leave out the <span class="error">:=</span> then the error messages are completely opaque. </li> </ul> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-/ begin /-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This marks the beginning of the proof. For some simple kinds of proofs it is not necessary to have a `begin ... end` wrapper. For some complicated proofs there will be nested `begin ... end` blocks to prove various intermediate claims that arise in the course of the proof. <br/><br/> Inside the `begin ... end` block, we enter "tactic mode", as discussed in Chapter 5 of the book <a href="https://leanprover.github.io/theorem_proving_in_lean/">Theorem Proving in Lean</a>. (References to "Chapter n" or "Section p.q" below will always refer to this book.) This can be explained as follows. A Lean proof is a kind of complex data structure. Outside of tactic mode, we can construct a proof by programming methods, in which we explicitly apply various functions to simpler structures that we have already defined. Inside tactic mode, we can construct proofs by a kind of dialogue with the proof assistant, which is much more similar to a traditional writer's imagined dialogue with the reader. <br/><br/> If you have this file open in Visual Studio Code, and you click at the end of the word `begin`, you should see a message like this in the Lean messages window: <div class="lean_messages"> ⊢ ∀ (n : ℕ), ∃ (p : ℕ), prime p ∧ p > n </div> This states our current proof goal. (If you do not see the relevant window, you should press CTRL-SHIFT-ENTER, or click the <img src="../../images/left_msg_icon.png"/> icon near the top of the screen.) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-/ intro n, /-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We are aiming to prove a statement that is universally quantified over the natural numbers. In traditional writing, we would start by saying "let $n$ be an arbitrary natural number", or some similar phrase. The line `intro n,` plays a similar role in Lean. <br/><br/> If you click on the end of this line in VS Code, you will see that the tactic state has changed to <div class="lean_messages"> n : ℕ ⊢ ∃ (p : ℕ), prime p ∧ p > n </div> This means, essentially, that we are working in a context where we have a given natural number $n$, and we aim to prove that there is a prime $p$ with $p>n$. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-/ let m := fact n + 1, /-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We now define $m$ to be $n!+1$. Again note the terminating comma. The tactic state changes to <div class="lean_messages"> n : ℕ, m : ℕ := fact n + 1 ⊢ ∃ (p : ℕ), prime p ∧ p > n </div> incorporating the definition of $m$ in the context. <br/><br/> In VS Code you can hover over the word `fact` with your mouse to see that the full name is `nat.fact` and that the type is `ℕ → ℕ`, and there is also a comment explaining that `fact` is the factorial function. If you hold the CTRL key while hovering, you will see the actual recursive definition of the function. If you hold the CTRL key and click, then you will jump to the file where that definition appears. Alternatively, you can right-click and then type F12 or Alt-F12. For this particular definition, the relevant file is <span class="mathlib">data/nat/basic.lean</span>. Note that we did not explicitly import `data.nat.basic`, but we imported `data.nat.prime`, which imports `data.nat.sqrt`, which imports `data.nat.basic`. Some standard properties of factorials are proved in the same place. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-/ let p := min_fac m, /-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This line defines $p$ using the function `min_fac` defined in <span class="mathlib">data/nat/basic.lean</span>. This is supposed to be defined by the requirement that `min_fac k` is the smallest $d>1$ such that $d$ divides $k$. This makes sense for $k=0$ (with `min_fac 0 = 2`) and for $k>1$, but this characterisation would leave `min_fac 1` undefined. The approach taken by the Lean library is to arbitrarily define `min_fac 1 = 1`. This of course means that some theorems about the properties of `min_fac` will need auxiliary hypotheses. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-/ use p, /-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Our goal is to prove that there exists a number with certain properties. The tactic `use p` converts this to the goal of proving that the specific number `p` has those properties. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-/ have p_prime : prime p, /-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Our goal is to prove `prime p ∧ p > n`. The most obvious thing to do next would be to split this into two goals: the proof that `p` is prime, and the proof that `p > n`. However, it is convenient to use the fact that `p` is prime as part of the proof that `p > n`, and the obvious structure would not allow for that. We need to attach a name to the claim that `p` is prime, then prove it, then return to the main goal. <br/><br/> The effect of the current line is to add `prime p` as a new current goal, with `prime p ∧ p > n` retained as a secondary goal to be addressed later. The current line also ensures that the name `p_prime` will be attached to our proof that `p` is prime, once we have provided it. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-/ { /-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We open a set of curly brackets in which to deal with the first goal (of proving that `p` is prime). This is not strictly necessary: we could just give a sequence of tactics, and Lean would apply them to the first goal until that goal was solved, and then apply any subsequent tactics to the second goal. However, it is usually clearer to use brackets. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-/ apply min_fac_prime, /-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We now apply the theorem named `min_fac_prime` from <span class="mathlib">data/nat/prime.lean</span>. <br/><br/> Recall that `min_fac n` was arbitrarily defined to be $1$ when $n=1$, so the theorem that `min_fac n` is prime is only valid with the side condition that $n\neq 1$. (In more detail, the theorem `min_fac_prime` is stated as <div class="code"> ∀ {n : ℕ}, n ≠ 1 → prime (min_fac n), </div> so it is essentially a function that takes as input a natural number $n$ together with a proof that $n\neq 1$, and produces a proof that `min_fac n` is prime. The `apply` tactic works out that the relevant value of `n` is $m = n!+1$, so it replaces the goal of proving that $p$ is prime by the goal of proving that $n!+1≠1$. Unfortunately we will need to supply a few fiddly details to achieve this goal. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-/ apply ne_of_gt, /-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ First, we apply the theorem `ne_of_gt`, which says that `a > b → a ≠ b`. The `apply` tactic works out which values of `a` and `b` are relevant (this process is called "unification"). Also, the theorem is valid for any type with a preorder, and the `apply` tactic knows that by default it should use the standard order on `ℕ`; this is handled using the mechanism of typeclass instances as described in <span class="tpil">Chapter 10</span>. Thus, the goal changes to proving that $n!+1>1$. <br/><br/> The name `ne_of_gt` illustrates the standard naming conventions for the mathlib library: the string `ne` indicates the conclusion `a ≠ b`, the string `gt` indicates the hypothesis `a > b`, and the string `_of_` indicates an implication. This is designed to work well with auto-completion in VS Code: you know you want to prove a statement of the form `a ≠ b`, so you can start typing `apply ne_of_...` and Lean will suggest things that might be helpful. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-/ apply succ_lt_succ, /-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We now apply the theorem `succ_lt_succ`, which says that `i < j → (i + 1) < (j + 1)`; this converts the goal to $0<n!$. Here `lt` stands for "less than", and `succ` refers to the successor operation $a\mapsto a+1$. As in Peano arithmetic, addition is actually defined in terms of the successor operation rather than the other way around. The hypothesis of this theorem is easy to guess, so the name is just based on the conclusion. <br/><br/> You might think that we would instead need a theorem saying `i > j → (i + 1) > (j + 1)` instead, and this would presumably be called `succ_gt_succ`. However, Lean defines `a > b` to mean `b < a`, and it applies this transformation quite eagerly. Theorems are generally written with hypotheses and conclusions in the form `b < a`, and Lean applies any required translations automatically. There is not in fact a theorem named `succ_gt_succ`, but we do not need one. <br/><br/> Note also that the `apply` tactic has unfolded the definition $m:=n!+1$ in order to see that `succ_lt_succ` is applicable. We could have helped with this by writing `dsimp [m],` before `apply succ_lt_succ`; this would have changed the goal to say explicitly that `(fact n) + 1 > 1`. This kind of help is sometimes necessary, but not in this particular case. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-/ apply fact_pos, }, /-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The theorem `fact_pos` says that $k! > 0$ for all $k$, so we can apply it to solve the current goal. We have added a comma after `fact_pos` just to persuade Lean to give an explicit message saying "no goals". This message is potentially misleading; we still need to prove that $p > n$, but that goal is hidden while we are inside the curly brackets that enclose the proof that $p$ is prime. If we move the cursor outside those curly brackets, then the goal $p > n$ becomes visible again. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-/ split, /-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Our goal is to prove `prime p ∧ p > n`. The tactic `split` converts this into two goals, namely `prime p` and `p > n`. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-/ {assumption}, /-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The current goal is to prove that `p` is prime. The context already contains a term (named `p_prime`) that `p` is prime, so we can just use the `assumption` tactic to complete the proof. We have placed this in curly brackets to separate it from the proof of the other goal (that `p > n`) but this is not strictly necessary. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-/ { /-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We now open a second pair of curly brackets, within which we will prove that $p > n$. Again, these brackets are not strictly necessary, but they help to make the structure of the proof visible. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-/ apply lt_of_not_ge, /-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Our goal is to prove that `p > n`, which Lean converts automatically to `n < p`. The theorem `lt_of_not_ge` converts this goal to `¬ n ≥ p`. As with the theorem `ne_of_gt` mentioned previously, this conversion rule is not proved directly for `ℕ`. Instead, the standard library defines the standard order on `ℕ` and proves that it is a linear order, using a definition for which the above rule is not an axiom; instead, it is proved as a simple lemma valid for any type equipped with a linear order. When we invoke `lt_of_not_ge` here, Lean needs to remember that we have given `ℕ` a linear order that it should use by default unless we say otherwise. This is handled by the mechanism of typeclass instances, as described in <span class="tpil">Chapter 10</span>. (In fact, this same mechanism is also used to interpret expressions such as `n + m`: the symbol `+` has different meanings in different places, and typeclasses are used to supply the relevant definition in any given context.) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-/ intro p_le_n, /-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ It is part of the basic logical framework of Lean that a proof of `¬ n ≥ p` is the same as a procedure that takes a hypothetical proof of `n ≥ p` (or equivalently `p ≤ n`) and produces a contradiction, or in other words a proof of the proposition `false`. <br/><br/> The current line means: "let `p_le_n` be a hypothetical proof that $p\leq n$". The meaning of the assumption is forced by the nature of the goal. By contrast, the name of the assumption is arbitrary; we have chosen to call it `p_le_n` to indicate its meaning, but we could equally well have written `intro foo,` instead. In fact, we could just have written `intro`, and then Lean would choose an arbitrary name. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-/ have p_gt_0 : p > 0, {apply min_fac_pos}, -- (b) have p_gt_0 : p > 0, exact min_fac_pos m, -- (c) have p_gt_0 : p > 0 := min_fac_pos m, -- (d) have p_gt_0 : p > 0 := min_fac_pos _, -- (e) have p_gt_0 := min_fac_pos m, -- (f) have p_gt_0 : p > 0 := by {apply min_fac_pos}, -- (g) let p_gt_0 := min_fac_pos m, /-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We now state that $p>0$, attach the name `p_gt_0` to this claim, and prove it by applying the theorem named `min_fac_pos` from <span class="mathlib">data/nat/prime.lean</span>. In more detail, the phrase `have p_gt_0 : p > 0,` adds `p > 0` as a new goal, and the phrase `{apply min_fac_pos},` gives a proof; the new goal therefore disappears, and the context gains a term named `p_gt_0` of type `p > 0`. <br/><br/> The following five lines all start with a double dash; this converts them to comments which are ignored by Lean. In each case we could remove the double dash and the initial label to get a line of Lean code which would have the same effect as the current line. <br/><br/> Version (b) uses the `exact` tactic instead of `apply`. After `exact` we must supply a term that represents a proof of `p > 0`. We can again use `min_fac_pos` for this, except that we now need to supply the argument `m`. Versions (c) to (g) all involve a ":=", and on the right hand side of that symbol we must work in term mode by default, rather than using tactics. Thus, version (c) is essentially the same as (b). In this situation we have to supply something as an argument to `min_fac_pos`, but we are allowed to write the symbol `_`, which instructs Lean to work out what is required; this is version (d). Lean can only do this because it knows that `p_gt_0` is supposed to have type `p > 0`. We can leave out that type annotation as in version (e), but in that case we need to give the argument explicitly. In version (f) we use the construct `by { ... }` to switch back into tactic mode. Version (g) illustrates the fact that `have` is essentially a synonym for `let`; it is standard to use `have` for propositions and `let` for other types, but this is not enforced. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-/ have d0 : p ∣ fact n := dvd_fact p_gt_0 p_le_n, /-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We now prove that $p$ divides $n!$. The proof appeals to the fact (named `dvd_fact`) that $a$ divides $b!$ whenever $a>0$ and $a\leq b$. We supply the explicit arguments `p_gt_0` and `p_le_n` to verify the hypotheses; the implicit arguments $p$ and $n$ are deduced from the context. <br/><br/> One needs to be careful about the symbol for divisibility. If you just type `|` then you will get a tall vertical bar, which is used by Lean for syntax related to pattern matching, and which does not relate to divisibility. If you type `\|` you will get a shorter vertical bar, which is the one that you need. Alternatively, one could write `has_dvd.dvd a b` instead of `a ∣ b`. (The full explanation for this slightly awkward syntax involves typeclasses; we will not give details here.) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-/ have d1 : p ∣ fact n + 1 := min_fac_dvd m, /-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We now claim that $p$ divides $m=n! + 1$. As $p$ was defined to be `min_fac m`, this amounts to the claim that the `min_fac` function was correctly defined. This was proved in `prime.lean` under the name `min_fac_dvd`. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-/ have d : p ∣ 1 := (nat.dvd_add_iff_right d0).mpr d1, /-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We now want to prove that `p` divides `1`. For this, we appeal to the fact that if $a$ divides $b$, then $a$ divides $c$ iff $a$ divides $b+c$. This fact has the name `dvd_add_iff_right`. Unfortunately, there are two versions of this fact that are currently visible. One of them comes from the file <span class="library">init/algebra/ring.lean</span>, and applies to an arbitrary commutative ring. The other comes from <span class="library">init/data/nat/lemmas.lean</span>, and applies only to `ℕ` (which is a semiring rather than a ring). Note that both of these are in the core Lean library, not in mathlib. We need to use the version for `ℕ`, so we need to resolve the ambiguity by providing the explicit prefix in `nat.dvd_add_iff_right`. <br/><br/> By applying `nat.dvd_add_iff_right` to `d0`, we obtain a proof that $p$ divides $n!+1$ iff $p$ divides $1$. The syntax `(...).mpr` extracts the right-to-left half of this equivalence, which we can then apply to the fact `d1` to obtain a proof that $p$ divides $1$. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-/ exact prime.not_dvd_one p_prime d /-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Our goal is to produce a contradiction, or equivalently to prove the proposition `false`. We do this using the keyword `exact` (which is the name of a kind of tautological tactic) followed by an expression that evaluates to `false`. The theorem `prime.not_dvd_one` says that no prime divides $1$. Equivalently, it is a function that accepts a proof that a number is prime, together with a proof that that number divides $1$, and produces `false`. We can thus apply `prime.not_dvd_one` to the ingredients `p_prime` and `d` to obtain the required contradiction. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-/ }, end /-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The proof is now complete. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-/ #check larger_prime /-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Lean accepts correct proofs without explicit acknowledgement. To get more positive feedback, we can enter `#check larger_prime`: this will restate the fact that we have proved in the message window. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-/ lemma larger_prime' : ∀ n : ℕ, ∃ p, (prime p) ∧ (p > n) := /-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We now start again and give essentially the same proof in a different style. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-/ begin intro n, let m := fact n + 1, let p := min_fac m, /-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ These lines are the same as before. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-/ have : m ≠ 1 := ne_of_gt (nat.succ_lt_succ (fact_pos n)), /-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Here we have a slight variation. Previously, in every `have` statement there was a name before the colon, which could be used to refer to the relevant fact after it had been proved. Here we omit the name. On the next line, we will need to refer back to the fact that `m ≠ 1`, but we will just use the keyword `this`, which refers back to the most recent anonymous `have`. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-/ have p_prime : prime p := min_fac_prime this, have p_gt_0 : p > 0 := min_fac_pos m, have not_p_le_n : ¬ p ≤ n, { intro p_le_n, have d0 : p ∣ fact n := dvd_fact p_gt_0 p_le_n, have d1 : p ∣ fact n + 1 := min_fac_dvd m, /-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ These lines are much the same as before, but with proof terms instead of tactics. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-/ have : p ∣ 1 := (nat.dvd_add_iff_right d0).mpr d1, exact prime.not_dvd_one p_prime ‹p ∣ 1› /-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Here is another anonymous `have`. We could again use the keyword `this` to refer to the result, but instead we illustrate another possible syntax. Because the context contains a unique term of type `p ∣ 1`, we can use the notation `‹p ∣ 1›` to refer to it. This notation involves "French quotes", which can be entered as \f< and \f>. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-/ }, have p_gt_n : p > n := lt_of_not_ge not_p_le_n, /-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ As before, we use `lt_of_not_ge` to get a proof of `p > n`. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-/ exact (exists.intro p (and.intro p_prime p_gt_n)), end /-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The function `and.intro` can be used to combine `p_prime` and `p_gt_n` into a proof of `prime p ∧ p > n`, then the function `exists.intro` can be used to generate a proof of `∃ p, prime p ∧ p > n`. We can feed this into the `exact` tactic to finish the proof. <br/><br/> Usually we would not write `exists.intro p (and.intro p_prime p_gt_n)`, but instead would use the terser expression `⟨p,⟨p_prime,p_gt_n⟩⟩`. The brackets here are angle brackets, entered as \< and \> or \langle and \rangle. With the default fonts, they can be hard to distinguish visually from ordinary round brackets, and they are also different from the French quotes that we used earlier. Anyway, angle brackets can be used in many situations to combine terms, provided that Lean already knows the expected type of the combination. Here we are using the `exact` tactic so the argument must match the type of the goal `∃ p, prime p ∧ p > n`, and Lean can work everything out from this. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-/ lemma larger_prime'' : ∀ n : ℕ, ∃ p, (prime p) ∧ (p > n) := λ n, let m := fact n + 1 in let p := min_fac m in let p_prime := min_fac_prime (ne_of_gt (nat.succ_lt_succ (fact_pos n))) in ⟨p,⟨p_prime, (lt_of_not_ge (λ p_le_n, prime.not_dvd_one p_prime ((nat.dvd_add_iff_right (dvd_fact p_prime.pos p_le_n)).mpr (min_fac_dvd m))))⟩⟩ /-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Finally, we give a third proof written as a single proof term with no tactics of any kind. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-/
fb8cf98efabaeab46ad47c47796105b7491a1e39
74caf7451c921a8d5ab9c6e2b828c9d0a35aae95
/library/init/algebra/ring.lean
f715952b4a8a63734cff2f2ada367aa692236cee
[ "Apache-2.0" ]
permissive
sakas--/lean
f37b6fad4fd4206f2891b89f0f8135f57921fc3f
570d9052820be1d6442a5cc58ece37397f8a9e4c
refs/heads/master
1,586,127,145,194
1,480,960,018,000
1,480,960,635,000
40,137,176
0
0
null
1,438,621,351,000
1,438,621,351,000
null
UTF-8
Lean
false
false
8,541
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura -/ prelude import init.algebra.group /- Make sure instances defined in this file have lower priority than the ones defined for concrete structures -/ set_option default_priority 100 universe variable u class distrib (α : Type u) extends has_mul α, has_add α := (left_distrib : ∀ a b c : α, a * (b + c) = (a * b) + (a * c)) (right_distrib : ∀ a b c : α, (a + b) * c = (a * c) + (b * c)) variable {α : Type u} lemma left_distrib [distrib α] (a b c : α) : a * (b + c) = a * b + a * c := distrib.left_distrib a b c lemma right_distrib [distrib α] (a b c : α) : (a + b) * c = a * c + b * c := distrib.right_distrib a b c class mul_zero_class (α : Type u) extends has_mul α, has_zero α := (zero_mul : ∀ a : α, 0 * a = 0) (mul_zero : ∀ a : α, a * 0 = 0) @[simp] lemma zero_mul [mul_zero_class α] (a : α) : 0 * a = 0 := mul_zero_class.zero_mul a @[simp] lemma mul_zero [mul_zero_class α] (a : α) : a * 0 = 0 := mul_zero_class.mul_zero a class zero_ne_one_class (α : Type u) extends has_zero α, has_one α := (zero_ne_one : 0 ≠ (1:α)) lemma zero_ne_one [s: zero_ne_one_class α] : 0 ≠ (1:α) := @zero_ne_one_class.zero_ne_one α s /- semiring -/ structure semiring (α : Type u) extends comm_monoid α renaming mul→add mul_assoc→add_assoc one→zero one_mul→zero_add mul_one→add_zero mul_comm→add_comm, monoid α, distrib α, mul_zero_class α attribute [class] semiring instance add_comm_monoid_of_semiring (α : Type u) [s : semiring α] : add_comm_monoid α := @semiring.to_comm_monoid α s instance monoid_of_semiring (α : Type u) [s : semiring α] : monoid α := @semiring.to_monoid α s instance distrib_of_semiring (α : Type u) [s : semiring α] : distrib α := @semiring.to_distrib α s instance mul_zero_class_of_semiring (α : Type u) [s : semiring α] : mul_zero_class α := @semiring.to_mul_zero_class α s section semiring variables [semiring α] lemma one_add_one_eq_two : 1 + 1 = (2 : α) := begin unfold bit0, reflexivity end lemma ne_zero_of_mul_ne_zero_right {a b : α} (h : a * b ≠ 0) : a ≠ 0 := suppose a = 0, have a * b = 0, by rw [this, zero_mul], h this lemma ne_zero_of_mul_ne_zero_left {a b : α} (h : a * b ≠ 0) : b ≠ 0 := suppose b = 0, have a * b = 0, by rw [this, mul_zero], h this lemma distrib_three_right (a b c d : α) : (a + b + c) * d = a * d + b * d + c * d := by simp [right_distrib] end semiring class comm_semiring (α : Type u) extends semiring α, comm_monoid α /- ring -/ structure ring (α : Type u) extends comm_group α renaming mul→add mul_assoc→add_assoc one→zero one_mul→zero_add mul_one→add_zero inv→neg mul_left_inv→add_left_inv mul_comm→add_comm, monoid α, distrib α attribute [class] ring instance to_add_comm_group_of_ring (α : Type u) [s : ring α] : add_comm_group α := @ring.to_comm_group α s instance monoid_of_ring (α : Type u) [s : ring α] : monoid α := @ring.to_monoid α s instance distrib_of_ring (α : Type u) [s : ring α] : distrib α := @ring.to_distrib α s lemma ring.mul_zero [ring α] (a : α) : a * 0 = 0 := have a * 0 + 0 = a * 0 + a * 0, from calc a * 0 + 0 = a * (0 + 0) : by simp ... = a * 0 + a * 0 : by rw left_distrib, show a * 0 = 0, from (add_left_cancel this)^.symm lemma ring.zero_mul [ring α] (a : α) : 0 * a = 0 := have 0 * a + 0 = 0 * a + 0 * a, from calc 0 * a + 0 = (0 + 0) * a : by simp ... = 0 * a + 0 * a : by rewrite right_distrib, show 0 * a = 0, from (add_left_cancel this)^.symm instance ring.to_semiring [s : ring α] : semiring α := { s with mul_zero := ring.mul_zero, zero_mul := ring.zero_mul } lemma neg_mul_eq_neg_mul [s : ring α] (a b : α) : -(a * b) = -a * b := neg_eq_of_add_eq_zero begin rw [-right_distrib, add_right_neg, zero_mul] end lemma neg_mul_eq_mul_neg [s : ring α] (a b : α) : -(a * b) = a * -b := neg_eq_of_add_eq_zero begin rw [-left_distrib, add_right_neg, mul_zero] end @[simp] lemma neg_mul_eq_neg_mul_symm [s : ring α] (a b : α) : - a * b = - (a * b) := eq.symm (neg_mul_eq_neg_mul a b) @[simp] lemma mul_neg_eq_neg_mul_symm [s : ring α] (a b : α) : a * - b = - (a * b) := eq.symm (neg_mul_eq_mul_neg a b) lemma neg_mul_neg [s : ring α] (a b : α) : -a * -b = a * b := by simp lemma neg_mul_comm [s : ring α] (a b : α) : -a * b = a * -b := by simp lemma mul_sub_left_distrib [s : ring α] (a b c : α) : a * (b - c) = a * b - a * c := calc a * (b - c) = a * b + a * -c : left_distrib a b (-c) ... = a * b - a * c : by simp lemma mul_sub_right_distrib [s : ring α] (a b c : α) : (a - b) * c = a * c - b * c := calc (a - b) * c = a * c + -b * c : right_distrib a (-b) c ... = a * c - b * c : by simp class comm_ring (α : Type u) extends ring α, comm_semigroup α instance comm_ring.to_comm_semiring [s : comm_ring α] : comm_semiring α := { s with mul_zero := mul_zero, zero_mul := zero_mul } section comm_ring variable [comm_ring α] lemma mul_self_sub_mul_self_eq (a b : α) : a * a - b * b = (a + b) * (a - b) := by simp [right_distrib, left_distrib] lemma mul_self_sub_one_eq (a : α) : a * a - 1 = (a + 1) * (a - 1) := by simp [right_distrib, left_distrib] lemma add_mul_self_eq (a b : α) : (a + b) * (a + b) = a*a + 2*a*b + b*b := calc (a + b)*(a + b) = a*a + (1+1)*a*b + b*b : by simp [right_distrib, left_distrib] ... = a*a + 2*a*b + b*b : by rw one_add_one_eq_two end comm_ring class no_zero_divisors (α : Type u) extends has_mul α, has_zero α := (eq_zero_or_eq_zero_of_mul_eq_zero : ∀ a b : α, a * b = 0 → a = 0 ∨ b = 0) lemma eq_zero_or_eq_zero_of_mul_eq_zero [no_zero_divisors α] {a b : α} (h : a * b = 0) : a = 0 ∨ b = 0 := no_zero_divisors.eq_zero_or_eq_zero_of_mul_eq_zero a b h lemma eq_zero_of_mul_self_eq_zero [no_zero_divisors α] {a : α} (h : a * a = 0) : a = 0 := or.elim (eq_zero_or_eq_zero_of_mul_eq_zero h) (assume h', h') (assume h', h') class integral_domain (α : Type u) extends comm_ring α, no_zero_divisors α, zero_ne_one_class α section integral_domain variable [integral_domain α] lemma mul_ne_zero {a b : α} (h₁ : a ≠ 0) (h₂ : b ≠ 0) : a * b ≠ 0 := λ h, or.elim (eq_zero_or_eq_zero_of_mul_eq_zero h) (assume h₃, h₁ h₃) (assume h₄, h₂ h₄) lemma eq_of_mul_eq_mul_right {a b c : α} (ha : a ≠ 0) (h : b * a = c * a) : b = c := have b * a - c * a = 0, from sub_eq_zero_of_eq h, have (b - c) * a = 0, by rw [mul_sub_right_distrib, this], have b - c = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this)^.resolve_right ha, eq_of_sub_eq_zero this lemma eq_of_mul_eq_mul_left {a b c : α} (ha : a ≠ 0) (h : a * b = a * c) : b = c := have a * b - a * c = 0, from sub_eq_zero_of_eq h, have a * (b - c) = 0, by rw [mul_sub_left_distrib, this], have b - c = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this)^.resolve_left ha, eq_of_sub_eq_zero this lemma eq_zero_of_mul_eq_self_right {a b : α} (h₁ : b ≠ 1) (h₂ : a * b = a) : a = 0 := have hb : b - 1 ≠ 0, from suppose b - 1 = 0, have b = 0 + 1, from eq_add_of_sub_eq this, have b = 1, by rwa zero_add at this, h₁ this, have a * b - a = 0, by simp [h₂], have a * (b - 1) = 0, by rwa [mul_sub_left_distrib, mul_one], show a = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this)^.resolve_right hb lemma eq_zero_of_mul_eq_self_left {a b : α} (h₁ : b ≠ 1) (h₂ : b * a = a) : a = 0 := eq_zero_of_mul_eq_self_right h₁ (by rwa mul_comm at h₂) lemma mul_self_eq_mul_self_iff (a b : α) : a * a = b * b ↔ a = b ∨ a = -b := iff.intro (suppose a * a = b * b, have (a - b) * (a + b) = 0, by rewrite [mul_comm, -mul_self_sub_mul_self_eq, this, sub_self], have a - b = 0 ∨ a + b = 0, from eq_zero_or_eq_zero_of_mul_eq_zero this, or.elim this (suppose a - b = 0, or.inl (eq_of_sub_eq_zero this)) (suppose a + b = 0, or.inr (eq_neg_of_add_eq_zero this))) (suppose a = b ∨ a = -b, or.elim this (suppose a = b, by rewrite this) (suppose a = -b, by rewrite [this, neg_mul_neg])) lemma mul_self_eq_one_iff (a : α) : a * a = 1 ↔ a = 1 ∨ a = -1 := have a * a = 1 * 1 ↔ a = 1 ∨ a = -1, from mul_self_eq_mul_self_iff a 1, by rwa mul_one at this end integral_domain
36601d91ee92908a4d31219a799c9be8544f6e1a
30b012bb72d640ec30c8fdd4c45fdfa67beb012c
/group_theory/order_of_element.lean
7c258dc6011010c5ae50ab21c26fb35ffa5ec43b
[ "Apache-2.0" ]
permissive
kckennylau/mathlib
21fb810b701b10d6606d9002a4004f7672262e83
47b3477e20ffb5a06588dd3abb01fe0fe3205646
refs/heads/master
1,634,976,409,281
1,542,042,832,000
1,542,319,733,000
109,560,458
0
0
Apache-2.0
1,542,369,208,000
1,509,867,494,000
Lean
UTF-8
Lean
false
false
20,561
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import data.set.finite group_theory.coset data.nat.totient open function variables {α : Type*} {s : set α} {a a₁ a₂ b c: α} -- TODO this lemma isn't used anywhere in this file, and should be moved elsewhere. namespace finset open finset lemma mem_range_iff_mem_finset_range_of_mod_eq [decidable_eq α] {f : ℤ → α} {a : α} {n : ℕ} (hn : 0 < n) (h : ∀i, f (i % n) = f i) : a ∈ set.range f ↔ a ∈ (finset.range n).image (λi, f i) := suffices (∃i, f (i % n) = a) ↔ ∃i, i < n ∧ f ↑i = a, by simpa [h], have hn' : 0 < (n : ℤ), from int.coe_nat_lt.mpr hn, iff.intro (assume ⟨i, hi⟩, have 0 ≤ i % ↑n, from int.mod_nonneg _ (ne_of_gt hn'), ⟨int.to_nat (i % n), by rw [←int.coe_nat_lt, int.to_nat_of_nonneg this]; exact ⟨int.mod_lt_of_pos i hn', hi⟩⟩) (assume ⟨i, hi, ha⟩, ⟨i, by rw [int.mod_eq_of_lt (int.coe_zero_le _) (int.coe_nat_lt_coe_nat_of_lt hi), ha]⟩) end finset section order_of variables [group α] [fintype α] [decidable_eq α] open set lemma exists_gpow_eq_one (a : α) : ∃i≠0, a ^ (i:ℤ) = 1 := have ¬ injective (λi, a ^ i), from not_injective_int_fintype, let ⟨i, j, a_eq, ne⟩ := show ∃(i j : ℤ), a ^ i = a ^ j ∧ i ≠ j, by rw [injective] at this; simpa [classical.not_forall] in have a ^ (i - j) = 1, by simp [gpow_add, gpow_neg, a_eq], ⟨i - j, sub_ne_zero.mpr ne, this⟩ lemma exists_pow_eq_one (a : α) : ∃i > 0, a ^ i = 1 := let ⟨i, hi, eq⟩ := exists_gpow_eq_one a in begin cases i, { exact ⟨i, nat.pos_of_ne_zero (by simp [int.of_nat_eq_coe, *] at *), eq⟩ }, { exact ⟨i + 1, dec_trivial, inv_eq_one.1 eq⟩ } end /-- `order_of a` is the order of the element `a`, i.e. the `n ≥ 1`, s.t. `a ^ n = 1` -/ def order_of (a : α) : ℕ := nat.find (exists_pow_eq_one a) lemma pow_order_of_eq_one (a : α) : a ^ order_of a = 1 := let ⟨h₁, h₂⟩ := nat.find_spec (exists_pow_eq_one a) in h₂ lemma order_of_pos (a : α) : order_of a > 0 := let ⟨h₁, h₂⟩ := nat.find_spec (exists_pow_eq_one a) in h₁ private lemma pow_injective_aux {n m : ℕ} (a : α) (h : n ≤ m) (hn : n < order_of a) (hm : m < order_of a) (eq : a ^ n = a ^ m) : n = m := decidable.by_contradiction $ assume ne : n ≠ m, have h₁ : m - n > 0, from nat.pos_of_ne_zero (by simp [nat.sub_eq_iff_eq_add h, ne.symm]), have h₂ : a ^ (m - n) = 1, by simp [pow_sub _ h, eq], have le : order_of a ≤ m - n, from nat.find_min' (exists_pow_eq_one a) ⟨h₁, h₂⟩, have lt : m - n < order_of a, from (nat.sub_lt_left_iff_lt_add h).mpr $ nat.lt_add_left _ _ _ hm, lt_irrefl _ (lt_of_le_of_lt le lt) lemma pow_injective_of_lt_order_of {n m : ℕ} (a : α) (hn : n < order_of a) (hm : m < order_of a) (eq : a ^ n = a ^ m) : n = m := (le_total n m).elim (assume h, pow_injective_aux a h hn hm eq) (assume h, (pow_injective_aux a h hm hn eq.symm).symm) lemma order_of_le_card_univ : order_of a ≤ fintype.card α := finset.card_le_of_inj_on ((^) a) (assume n _, fintype.complete _) (assume i j, pow_injective_of_lt_order_of a) lemma pow_eq_mod_order_of {n : ℕ} : a ^ n = a ^ (n % order_of a) := calc a ^ n = a ^ (n % order_of a + order_of a * (n / order_of a)) : by rw [nat.mod_add_div] ... = a ^ (n % order_of a) : by simp [pow_add, pow_mul, pow_order_of_eq_one] lemma gpow_eq_mod_order_of {i : ℤ} : a ^ i = a ^ (i % order_of a) := calc a ^ i = a ^ (i % order_of a + order_of a * (i / order_of a)) : by rw [int.mod_add_div] ... = a ^ (i % order_of a) : by simp [gpow_add, gpow_mul, pow_order_of_eq_one] lemma mem_gpowers_iff_mem_range_order_of {a a' : α} : a' ∈ gpowers a ↔ a' ∈ (finset.range (order_of a)).image ((^) a : ℕ → α) := finset.mem_range_iff_mem_finset_range_of_mod_eq (order_of_pos a) (assume i, gpow_eq_mod_order_of.symm) instance decidable_gpowers : decidable_pred (gpowers a) := assume a', decidable_of_iff' (a' ∈ (finset.range (order_of a)).image ((^) a)) mem_gpowers_iff_mem_range_order_of lemma order_of_dvd_of_pow_eq_one {n : ℕ} (h : a ^ n = 1) : order_of a ∣ n := by_contradiction (λ h₁, nat.find_min _ (show n % order_of a < order_of a, from nat.mod_lt _ (order_of_pos _)) ⟨nat.pos_of_ne_zero (mt nat.dvd_of_mod_eq_zero h₁), by rwa ← pow_eq_mod_order_of⟩) lemma order_of_le_of_pow_eq_one {n : ℕ} (hn : 0 < n) (h : a ^ n = 1) : order_of a ≤ n := nat.find_min' (exists_pow_eq_one a) ⟨hn, h⟩ lemma sum_card_order_of_eq_card_pow_eq_one {n : ℕ} (hn : 0 < n) : ((finset.range n.succ).filter (∣ n)).sum (λ m, (finset.univ.filter (λ a : α, order_of a = m)).card) = (finset.univ.filter (λ a : α, a ^ n = 1)).card := calc ((finset.range n.succ).filter (∣ n)).sum (λ m, (finset.univ.filter (λ a : α, order_of a = m)).card) = _ : (finset.card_bind (by simp [finset.ext]; cc)).symm ... = _ : congr_arg finset.card (finset.ext.2 (begin assume a, suffices : order_of a ≤ n ∧ order_of a ∣ n ↔ a ^ n = 1, { simpa [-finset.range_succ, nat.lt_succ_iff], }, exact ⟨λ h, let ⟨m, hm⟩ := h.2 in by rw [hm, pow_mul, pow_order_of_eq_one, _root_.one_pow], λ h, ⟨order_of_le_of_pow_eq_one hn h, order_of_dvd_of_pow_eq_one h⟩⟩ end)) section local attribute [instance] set_fintype lemma order_eq_card_gpowers : order_of a = fintype.card (gpowers a) := begin refine (finset.card_eq_of_bijective _ _ _ _).symm, { exact λn hn, ⟨gpow a n, ⟨n, rfl⟩⟩ }, { exact assume ⟨_, i, rfl⟩ _, have pos: (0:int) < order_of a, from int.coe_nat_lt.mpr $ order_of_pos a, have 0 ≤ i % (order_of a), from int.mod_nonneg _ $ ne_of_gt pos, ⟨int.to_nat (i % order_of a), by rw [← int.coe_nat_lt, int.to_nat_of_nonneg this]; exact ⟨int.mod_lt_of_pos _ pos, subtype.eq gpow_eq_mod_order_of.symm⟩⟩ }, { intros, exact finset.mem_univ _ }, { exact assume i j hi hj eq, pow_injective_of_lt_order_of a hi hj $ by simpa using eq } end section classical local attribute [instance] classical.prop_decidable open quotient_group /- TODO: use cardinal theory, introduce `card : set α → ℕ`, or setup decidability for cosets -/ lemma order_of_dvd_card_univ : order_of a ∣ fintype.card α := have ft_prod : fintype (quotient (gpowers a) × (gpowers a)), from fintype.of_equiv α (gpowers.is_subgroup a).group_equiv_quotient_times_subgroup, have ft_s : fintype (gpowers a), from @fintype.fintype_prod_right _ _ _ ft_prod _, have ft_cosets : fintype (quotient (gpowers a)), from @fintype.fintype_prod_left _ _ _ ft_prod ⟨⟨1, is_submonoid.one_mem (gpowers a)⟩⟩, have ft : fintype (quotient (gpowers a) × (gpowers a)), from @prod.fintype _ _ ft_cosets ft_s, have eq₁ : fintype.card α = @fintype.card _ ft_cosets * @fintype.card _ ft_s, from calc fintype.card α = @fintype.card _ ft_prod : @fintype.card_congr _ _ _ ft_prod (gpowers.is_subgroup a).group_equiv_quotient_times_subgroup ... = @fintype.card _ (@prod.fintype _ _ ft_cosets ft_s) : congr_arg (@fintype.card _) $ subsingleton.elim _ _ ... = @fintype.card _ ft_cosets * @fintype.card _ ft_s : @fintype.card_prod _ _ ft_cosets ft_s, have eq₂ : order_of a = @fintype.card _ ft_s, from calc order_of a = _ : order_eq_card_gpowers ... = _ : congr_arg (@fintype.card _) $ subsingleton.elim _ _, dvd.intro (@fintype.card (quotient (gpowers a)) ft_cosets) $ by rw [eq₁, eq₂, mul_comm] end classical @[simp] lemma pow_card_eq_one (a : α) : a ^ fintype.card α = 1 := let ⟨m, hm⟩ := @order_of_dvd_card_univ _ a _ _ _ in by simp [hm, pow_mul, pow_order_of_eq_one] lemma powers_eq_gpowers (a : α) : powers a = gpowers a := set.ext (λ x, ⟨λ ⟨n, hn⟩, ⟨n, by simp * at *⟩, λ ⟨i, hi⟩, ⟨(i % order_of a).nat_abs, by rwa [← gpow_coe_nat, int.nat_abs_of_nonneg (int.mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 (order_of_pos _))), ← gpow_eq_mod_order_of]⟩⟩) open nat lemma order_of_pow (a : α) (n : ℕ) : order_of (a ^ n) = order_of a / gcd (order_of a) n := dvd_antisymm (order_of_dvd_of_pow_eq_one (by rw [← pow_mul, ← nat.mul_div_assoc _ (gcd_dvd_left _ _), mul_comm, nat.mul_div_assoc _ (gcd_dvd_right _ _), pow_mul, pow_order_of_eq_one, _root_.one_pow])) (have gcd_pos : 0 < gcd (order_of a) n, from gcd_pos_of_pos_left n (order_of_pos a), have hdvd : order_of a ∣ n * order_of (a ^ n), from order_of_dvd_of_pow_eq_one (by rw [pow_mul, pow_order_of_eq_one]), coprime.dvd_of_dvd_mul_right (coprime_div_gcd_div_gcd gcd_pos) (dvd_of_mul_dvd_mul_right gcd_pos (by rwa [nat.div_mul_cancel (gcd_dvd_left _ _), mul_assoc, nat.div_mul_cancel (gcd_dvd_right _ _), mul_comm]))) lemma pow_gcd_card_eq_one_iff {n : ℕ} {a : α} : a ^ n = 1 ↔ a ^ (gcd n (fintype.card α)) = 1 := ⟨λ h, have hn : order_of a ∣ n, from dvd_of_mod_eq_zero $ by_contradiction (λ ha, by rw pow_eq_mod_order_of at h; exact (not_le_of_gt (nat.mod_lt n (order_of_pos a))) (order_of_le_of_pow_eq_one (nat.pos_of_ne_zero ha) h)), let ⟨m, hm⟩ := dvd_gcd hn order_of_dvd_card_univ in by rw [hm, pow_mul, pow_order_of_eq_one, _root_.one_pow], λ h, let ⟨m, hm⟩ := gcd_dvd_left n (fintype.card α) in by rw [hm, pow_mul, h, _root_.one_pow]⟩ end end order_of section cyclic local attribute [instance] set_fintype class is_cyclic (α : Type*) [group α] : Prop := (exists_generator : ∃ g : α, ∀ x, x ∈ gpowers g) def is_cyclic.comm_group [hg : group α] [is_cyclic α] : comm_group α := { mul_comm := λ x y, show x * y = y * x, from let ⟨g, hg⟩ := is_cyclic.exists_generator α in let ⟨n, hn⟩ := hg x in let ⟨m, hm⟩ := hg y in hm ▸ hn ▸ gpow_mul_comm _ _ _, ..hg } lemma is_cyclic_of_order_of_eq_card [group α] [fintype α] [decidable_eq α] (x : α) (hx : order_of x = fintype.card α) : is_cyclic α := ⟨⟨x, set.eq_univ_iff_forall.1 $ set.eq_of_subset_of_card_le (set.subset_univ _) (by rw [fintype.card_congr (equiv.set.univ α), ← hx, order_eq_card_gpowers])⟩⟩ lemma order_of_eq_card_of_forall_mem_gpowers [group α] [fintype α] [decidable_eq α] {g : α} (hx : ∀ x, x ∈ gpowers g) : order_of g = fintype.card α := by rw [← fintype.card_congr (equiv.set.univ α), order_eq_card_gpowers]; simp [hx]; congr instance [group α] : is_cyclic (is_subgroup.trivial α) := ⟨⟨(1 : is_subgroup.trivial α), λ x, ⟨0, subtype.eq $ eq.symm (is_subgroup.mem_trivial.1 x.2)⟩⟩⟩ instance is_subgroup.is_cyclic [group α] [is_cyclic α] (H : set α) [is_subgroup H] : is_cyclic H := by haveI := classical.prop_decidable; exact let ⟨g, hg⟩ := is_cyclic.exists_generator α in if hx : ∃ (x : α), x ∈ H ∧ x ≠ (1 : α) then let ⟨x, hx₁, hx₂⟩ := hx in let ⟨k, hk⟩ := hg x in have hex : ∃ n : ℕ, 0 < n ∧ g ^ n ∈ H, from ⟨k.nat_abs, nat.pos_of_ne_zero (λ h, hx₂ $ by rw [← hk, int.eq_zero_of_nat_abs_eq_zero h, gpow_zero]), match k, hk with | (k : ℕ), hk := by rw [int.nat_abs_of_nat, ← gpow_coe_nat, hk]; exact hx₁ | -[1+ k], hk := by rw [int.nat_abs_of_neg_succ_of_nat, ← is_subgroup.inv_mem_iff H]; simp * at * end⟩, ⟨⟨⟨g ^ nat.find hex, (nat.find_spec hex).2⟩, λ ⟨x, hx⟩, let ⟨k, hk⟩ := hg x in have hk₁ : g ^ ((nat.find hex : ℤ) * (k / nat.find hex)) ∈ gpowers (g ^ nat.find hex), from ⟨k / nat.find hex, eq.symm $ gpow_mul _ _ _⟩, have hk₂ : g ^ ((nat.find hex : ℤ) * (k / nat.find hex)) ∈ H, by rw gpow_mul; exact is_subgroup.gpow_mem (nat.find_spec hex).2, have hk₃ : g ^ (k % nat.find hex) ∈ H, from (is_subgroup.mul_mem_cancel_left H hk₂).1 $ by rw [← gpow_add, int.mod_add_div, hk]; exact hx, have hk₄ : k % nat.find hex = (k % nat.find hex).nat_abs, by rw int.nat_abs_of_nonneg (int.mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 (nat.find_spec hex).1)), have hk₅ : g ^ (k % nat.find hex ).nat_abs ∈ H, by rwa [← gpow_coe_nat, ← hk₄], have hk₆ : (k % (nat.find hex : ℤ)).nat_abs = 0, from by_contradiction (λ h, nat.find_min hex (int.coe_nat_lt.1 $ by rw [← hk₄]; exact int.mod_lt_of_pos _ (int.coe_nat_pos.2 (nat.find_spec hex).1)) ⟨nat.pos_of_ne_zero h, hk₅⟩), ⟨k / (nat.find hex : ℤ), subtype.coe_ext.2 begin suffices : g ^ ((nat.find hex : ℤ) * (k / nat.find hex)) = x, { simpa [gpow_mul] }, rw [int.mul_div_cancel' (int.dvd_of_mod_eq_zero (int.eq_zero_of_nat_abs_eq_zero hk₆)), hk] end⟩⟩⟩ else have H = is_subgroup.trivial α, from set.ext $ λ x, ⟨λ h, by simp at *; tauto, λ h, by rw [is_subgroup.mem_trivial.1 h]; exact is_submonoid.one_mem _⟩, by clear _let_match; subst this; apply_instance open finset nat lemma is_cyclic.card_pow_eq_one_le [group α] [fintype α] [decidable_eq α] [is_cyclic α] {n : ℕ} (hn0 : 0 < n) : (univ.filter (λ a : α, a ^ n = 1)).card ≤ n := let ⟨g, hg⟩ := is_cyclic.exists_generator α in calc (univ.filter (λ a : α, a ^ n = 1)).card ≤ (gpowers (g ^ (fintype.card α / (gcd n (fintype.card α))))).to_finset.card : card_le_of_subset (λ x hx, let ⟨m, hm⟩ := show x ∈ powers g, from (powers_eq_gpowers g).symm ▸ hg x in set.mem_to_finset.2 ⟨(m / (fintype.card α / (gcd n (fintype.card α))) : ℕ), have hgmn : g ^ (m * gcd n (fintype.card α)) = 1, by rw [pow_mul, hm, ← pow_gcd_card_eq_one_iff]; exact (mem_filter.1 hx).2, begin rw [gpow_coe_nat, ← pow_mul, nat.mul_div_cancel_left', hm], refine dvd_of_mul_dvd_mul_right (gcd_pos_of_pos_left (fintype.card α) hn0) _, conv {to_lhs, rw [nat.div_mul_cancel (gcd_dvd_right _ _), ← order_of_eq_card_of_forall_mem_gpowers hg]}, exact order_of_dvd_of_pow_eq_one hgmn end⟩) ... ≤ n : let ⟨m, hm⟩ := gcd_dvd_right n (fintype.card α) in have hm0 : 0 < m, from nat.pos_of_ne_zero (λ hm0, (by rw [hm0, mul_zero, fintype.card_eq_zero_iff] at hm; exact hm 1)), begin rw [← set.card_fintype_of_finset' _ (λ _, set.mem_to_finset), ← order_eq_card_gpowers, order_of_pow, order_of_eq_card_of_forall_mem_gpowers hg], rw [hm] {occs := occurrences.pos [2,3]}, rw [nat.mul_div_cancel_left _ (gcd_pos_of_pos_left _ hn0), gcd_mul_left_left, hm, nat.mul_div_cancel _ hm0], exact le_of_dvd hn0 (gcd_dvd_left _ _) end section totient variables [group α] [fintype α] [decidable_eq α] (hn : ∀ n : ℕ, 0 < n → (univ.filter (λ a : α, a ^ n = 1)).card ≤ n) include hn lemma card_pow_eq_one_eq_order_of_aux (a : α) : (finset.univ.filter (λ b : α, b ^ order_of a = 1)).card = order_of a := le_antisymm (hn _ (order_of_pos _)) (calc order_of a = @fintype.card (gpowers a) (id _) : order_eq_card_gpowers ... ≤ @fintype.card (↑(univ.filter (λ b : α, b ^ order_of a = 1)) : set α) (set.fintype_of_finset _ (λ _, iff.rfl)) : @fintype.card_le_of_injective (gpowers a) (↑(univ.filter (λ b : α, b ^ order_of a = 1)) : set α) (id _) (id _) (λ b, ⟨b.1, mem_filter.2 ⟨mem_univ _, let ⟨i, hi⟩ := b.2 in by rw [← hi, ← gpow_coe_nat, ← gpow_mul, mul_comm, gpow_mul, gpow_coe_nat, pow_order_of_eq_one, one_gpow]⟩⟩) (λ _ _ h, subtype.eq (subtype.mk.inj h)) ... = (univ.filter (λ b : α, b ^ order_of a = 1)).card : set.card_fintype_of_finset _ _) local notation `φ` := nat.totient private lemma card_order_of_eq_totient_aux₁ : ∀ {d : ℕ}, d ∣ fintype.card α → 0 < (univ.filter (λ a : α, order_of a = d)).card → (univ.filter (λ a : α, order_of a = d)).card = φ d | 0 := λ hd hd0, absurd hd0 (mt card_pos.1 (by simp [finset.ext, nat.pos_iff_ne_zero.1 (order_of_pos _)])) | (d+1) := λ hd hd0, let ⟨a, ha⟩ := exists_mem_of_ne_empty (card_pos.1 hd0) in have ha : order_of a = d.succ, from (mem_filter.1 ha).2, have h : ((range d.succ).filter (∣ d.succ)).sum (λ m, (univ.filter (λ a : α, order_of a = m)).card) = ((range d.succ).filter (∣ d.succ)).sum φ, from finset.sum_congr rfl (λ m hm, have hmd : m < d.succ, from mem_range.1 (mem_filter.1 hm).1, have hm : m ∣ d.succ, from (mem_filter.1 hm).2, card_order_of_eq_totient_aux₁ (dvd.trans hm hd) (finset.card_pos.2 (ne_empty_of_mem (show a ^ (d.succ / m) ∈ _, from mem_filter.2 ⟨mem_univ _, by rw [order_of_pow, ha, gcd_eq_right (div_dvd_of_dvd hm), nat.div_div_self hm (succ_pos _)]⟩)))), have hinsert : insert d.succ ((range d.succ).filter (∣ d.succ)) = (range d.succ.succ).filter (∣ d.succ), from (finset.ext.2 $ λ x, ⟨λ h, (mem_insert.1 h).elim (λ h, by simp [h]) (by clear _let_match; simp; tauto), by clear _let_match; simp {contextual := tt}; tauto⟩), have hinsert₁ : d.succ ∉ (range d.succ).filter (∣ d.succ), by simp [-range_succ, mem_range, zero_le_one, le_succ], (add_right_inj (((range d.succ).filter (∣ d.succ)).sum (λ m, (univ.filter (λ a : α, order_of a = m)).card))).1 (calc _ = (insert d.succ (filter (∣ d.succ) (range d.succ))).sum (λ m, (univ.filter (λ a : α, order_of a = m)).card) : eq.symm (finset.sum_insert (by simp [-range_succ, mem_range, zero_le_one, le_succ])) ... = ((range d.succ.succ).filter (∣ d.succ)).sum (λ m, (univ.filter (λ a : α, order_of a = m)).card) : sum_congr hinsert (λ _ _, rfl) ... = (univ.filter (λ a : α, a ^ d.succ = 1)).card : sum_card_order_of_eq_card_pow_eq_one (succ_pos d) ... = ((range d.succ.succ).filter (∣ d.succ)).sum φ : ha ▸ (card_pow_eq_one_eq_order_of_aux hn a).symm ▸ (sum_totient _).symm ... = _ : by rw [h, ← sum_insert hinsert₁]; exact finset.sum_congr hinsert.symm (λ _ _, rfl)) lemma card_order_of_eq_totient_aux₂ {d : ℕ} (hd : d ∣ fintype.card α) : (univ.filter (λ a : α, order_of a = d)).card = φ d := by_contradiction $ λ h, have h0 : (univ.filter (λ a : α , order_of a = d)).card = 0 := not_not.1 (mt nat.pos_iff_ne_zero.2 (mt (card_order_of_eq_totient_aux₁ hn hd) h)), let c := fintype.card α in have hc0 : 0 < c, from fintype.card_pos_iff.2 ⟨1⟩, lt_irrefl c $ calc c = (univ.filter (λ a : α, a ^ c = 1)).card : congr_arg card $ by simp [finset.ext, c] ... = ((range c.succ).filter (∣ c)).sum (λ m, (univ.filter (λ a : α, order_of a = m)).card) : (sum_card_order_of_eq_card_pow_eq_one hc0).symm ... = (((range c.succ).filter (∣ c)).erase d).sum (λ m, (univ.filter (λ a : α, order_of a = m)).card) : eq.symm (sum_subset (erase_subset _ _) (λ m hm₁ hm₂, have m = d, by simp at *; cc, by simp [*, finset.ext] at *; exact h0)) ... ≤ (((range c.succ).filter (∣ c)).erase d).sum φ : sum_le_sum (λ m hm, have hmc : m ∣ c, by simp at hm; tauto, (imp_iff_not_or.1 (card_order_of_eq_totient_aux₁ hn hmc)).elim (λ h, by simp [nat.le_zero_iff.1 (le_of_not_gt h), nat.zero_le]) (by simp [le_refl] {contextual := tt})) ... < φ d + (((range c.succ).filter (∣ c)).erase d).sum φ : lt_add_of_pos_left _ (totient_pos (nat.pos_of_ne_zero (λ h, nat.pos_iff_ne_zero.1 hc0 (eq_zero_of_zero_dvd $ h ▸ hd)))) ... = (insert d (((range c.succ).filter (∣ c)).erase d)).sum φ : eq.symm (sum_insert (by simp)) ... = ((range c.succ).filter (∣ c)).sum φ : finset.sum_congr (finset.insert_erase (mem_filter.2 ⟨mem_range.2 (lt_succ_of_le (le_of_dvd hc0 hd)), hd⟩)) (λ _ _, rfl) ... = c : sum_totient _ lemma is_cyclic_of_card_pow_eq_one_le : is_cyclic α := have ∃ x, x ∈ univ.filter (λ a : α, order_of a = fintype.card α), from exists_mem_of_ne_empty (card_pos.1 $ by rw [card_order_of_eq_totient_aux₂ hn (dvd_refl _)]; exact totient_pos (fintype.card_pos_iff.2 ⟨1⟩)), let ⟨x, hx⟩ := this in is_cyclic_of_order_of_eq_card x (finset.mem_filter.1 hx).2 end totient lemma is_cyclic.card_order_of_eq_totient [group α] [is_cyclic α] [fintype α] [decidable_eq α] {d : ℕ} (hd : d ∣ fintype.card α) : (univ.filter (λ a : α, order_of a = d)).card = totient d := card_order_of_eq_totient_aux₂ (λ n, is_cyclic.card_pow_eq_one_le) hd end cyclic